445ce18cfb70acea6993d788125cef1a01023f75
[oweals/gnunet.git] / src / fs / fs_namespace.c
1 /*
2      This file is part of GNUnet
3      (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file fs/fs_namespace.c
23  * @brief create and destroy namespaces
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_constants.h"
28 #include "gnunet_signatures.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_fs_service.h"
31 #include "fs.h"
32
33 /**
34  * Return the name of the directory in which we store
35  * our local namespaces (or rather, their public keys).
36  *
37  * @param h global fs handle 
38  * @return NULL on error, otherwise the name of the directory
39  */
40 static char *
41 get_namespace_directory (struct GNUNET_FS_Handle *h)
42 {
43   char *dn;
44
45   if (GNUNET_OK !=
46       GNUNET_CONFIGURATION_get_value_filename (h->cfg,
47                                                "FS",
48                                                "IDENTITY_DIR",
49                                                &dn))
50     {
51       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
52                   _("Configuration fails to specify `%s' in section `%s'\n"),
53                   "IDENTITY_DIR",
54                   "fs");
55       return NULL;
56     }
57   return dn;
58 }
59
60
61 /**
62  * Return the name of the directory in which we store
63  * the update information graph for the given local namespace.
64  *
65  * @param ns namespace handle 
66  * @return NULL on error, otherwise the name of the directory
67  */
68 static char *
69 get_update_information_directory (struct GNUNET_FS_Namespace *ns)
70 {
71   char *dn;
72   char *ret;
73
74   if (GNUNET_OK !=
75       GNUNET_CONFIGURATION_get_value_filename (ns->h->cfg,
76                                                "FS",
77                                                "UPDATE_DIR",
78                                                &dn))
79     {
80       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
81                   _("Configuration fails to specify `%s' in section `%s'\n"),
82                   "UPDATE_DIR",
83                   "fs");
84       return NULL;
85     }
86   GNUNET_asprintf (&ret,
87                    "%s%s%s",
88                    dn,
89                    DIR_SEPARATOR_STR,
90                    ns->name);
91   GNUNET_free (dn);
92   return ret;
93 }
94
95
96 /**
97  * Write the namespace update node graph to a file.
98  * 
99  * @param ns namespace to dump
100  */
101 static void
102 write_update_information_graph (struct GNUNET_FS_Namespace *ns)
103 {
104   char * fn;
105   struct GNUNET_BIO_WriteHandle *wh;
106   unsigned int i;
107   struct NamespaceUpdateNode *n;
108   char *uris;
109
110   fn = get_update_information_directory (ns);
111   wh = GNUNET_BIO_write_open (fn);
112   if (wh == NULL)
113     {
114       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
115                   _("Failed to open `%s' for writing: %s\n"),
116                   STRERROR (errno));
117       GNUNET_free (fn);
118       return;
119     }
120   if (GNUNET_OK != 
121       GNUNET_BIO_write_int32 (wh, ns->update_node_count))
122     goto END;
123   for (i=0;i<ns->update_node_count;i++)
124     {
125       n = ns->update_nodes[i];
126       uris = GNUNET_FS_uri_to_string (n->uri);
127       if ( (GNUNET_OK !=
128             GNUNET_BIO_write_string (wh, n->id)) ||
129            (GNUNET_OK != 
130             GNUNET_BIO_write_meta_data (wh, n->md)) ||
131            (GNUNET_OK !=
132             GNUNET_BIO_write_string (wh, n->update)) ||
133            (GNUNET_OK !=
134             GNUNET_BIO_write_string (wh, uris)) )
135         {
136           GNUNET_free (uris);
137           break;
138         }
139       GNUNET_free (uris);
140     }
141  END:
142   if (GNUNET_OK != GNUNET_BIO_write_close (wh))
143     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
144                 _("Failed to write `%s': %s\n"),
145                 STRERROR (errno));
146   GNUNET_free (fn);
147 }
148
149
150 /**
151  * Read the namespace update node graph from a file.
152  * 
153  * @param ns namespace to read
154  */
155 static void
156 read_update_information_graph (struct GNUNET_FS_Namespace *ns)
157 {
158   char * fn;
159   struct GNUNET_BIO_ReadHandle *rh;
160   unsigned int i;
161   struct NamespaceUpdateNode *n;
162   char *uris;
163   uint32_t count;
164   char *emsg;
165   
166   fn = get_update_information_directory (ns);
167   if (GNUNET_YES !=
168       GNUNET_DISK_file_test (fn))
169     {
170       GNUNET_free (fn);
171       return;
172     }
173   rh = GNUNET_BIO_read_open (fn);
174   if (rh == NULL)
175     {
176       GNUNET_free (fn);
177       return;
178     }
179   if (GNUNET_OK != 
180       GNUNET_BIO_read_int32 (rh, &count))
181     {
182       GNUNET_break (0);
183       goto END;
184     }
185   if (count > 1024 * 1024)
186     {
187       GNUNET_break (0);
188       goto END;
189     }
190   if (count == 0)
191     {
192       GNUNET_break (GNUNET_OK == GNUNET_BIO_read_close (rh, NULL));
193       GNUNET_free (fn);
194       return;
195     }
196   ns->update_nodes = GNUNET_malloc (count * sizeof (struct NamespaceUpdateNode*));
197   
198   for (i=0;i<count;i++)
199     {
200       n = GNUNET_malloc (sizeof (struct NamespaceUpdateNode));
201       if ( (GNUNET_OK !=
202             GNUNET_BIO_read_string (rh,  "identifier", &n->id, 1024)) ||
203            (GNUNET_OK != 
204             GNUNET_BIO_read_meta_data (rh, "meta", &n->md)) ||
205            (GNUNET_OK !=
206             GNUNET_BIO_read_string (rh, "update-id", &n->update, 1024)) ||
207            (GNUNET_OK !=
208             GNUNET_BIO_read_string (rh, "uri", &uris, 1024 * 2)) )
209         {
210           GNUNET_break (0);
211           GNUNET_free_non_null (n->id);
212           GNUNET_free_non_null (n->update);
213           if (n->md != NULL)
214             GNUNET_CONTAINER_meta_data_destroy (n->md);
215           GNUNET_free (n);
216           break;
217         }
218       n->uri = GNUNET_FS_uri_parse (uris, &emsg);
219       GNUNET_free (uris);
220       if (n->uri == NULL)
221         {
222           GNUNET_break (0);
223           GNUNET_free (emsg);
224           GNUNET_free (n->id);
225           GNUNET_free (n->update);
226           GNUNET_CONTAINER_meta_data_destroy (n->md);
227           GNUNET_free (n);
228           break;
229         }
230       ns->update_nodes[i] = n;
231     }
232   ns->update_node_count = i;
233  END:
234   if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg))
235     {
236       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
237                   _("Failed to write `%s': %s\n"),
238                   emsg);
239       GNUNET_free (emsg);
240     }
241   GNUNET_free (fn);
242 }
243
244
245 /**
246  * Context for advertising a namespace.
247  */
248 struct AdvertisementContext
249 {
250   /**
251    * Function to call with the result.
252    */
253   GNUNET_FS_PublishContinuation cont;
254
255   /**
256    * Closure for cont.
257    */
258   void *cont_cls;
259
260   /**
261    * Datastore handle.
262    */
263   struct GNUNET_DATASTORE_Handle *dsh;
264
265   /**
266    * Our scheduler.
267    */
268   struct GNUNET_SCHEDULER_Handle *sched;
269
270   /**
271    * Our KSK URI.
272    */ 
273   struct GNUNET_FS_Uri *ksk_uri;
274
275   /**
276    * Plaintext.
277    */
278   char *pt;
279
280   /**
281    * NBlock to sign and store.
282    */
283   struct NBlock *nb;
284
285   /**
286    * The namespace.
287    */
288   struct GNUNET_FS_Namespace *ns;
289
290   /**
291    * Expiration time.
292    */
293   struct GNUNET_TIME_Absolute expiration;
294
295   /**
296    * Number of bytes of plaintext.
297    */ 
298   size_t pt_size;
299
300   /**
301    * Anonymity level.
302    */
303   uint32_t anonymity;
304
305   /**
306    * Content priority.
307    */
308   uint32_t priority;
309
310   /**
311    * Current keyword offset.
312    */
313   unsigned int pos;
314 };
315
316
317 /**
318  * Disconnect from the datastore.
319  * 
320  * @param cls datastore handle
321  * @param tc scheduler context
322  */
323 static void
324 do_disconnect (void *cls,
325                const struct GNUNET_SCHEDULER_TaskContext *tc)
326 {
327   struct GNUNET_DATASTORE_Handle *dsh = cls;
328
329   GNUNET_DATASTORE_disconnect (dsh, 
330                                GNUNET_NO);
331 }
332
333
334 /**
335  * Continuation called to notify client about result of the
336  * operation.
337  *
338  * @param cls closure (our struct AdvertismentContext)
339  * @param success GNUNET_SYSERR on failure
340  * @param msg NULL on success, otherwise an error message
341  */
342 static void
343 advertisement_cont (void *cls,
344                     int success,
345                     const char *msg)
346 {
347   struct AdvertisementContext *ac = cls;
348   const char *keyword;
349   GNUNET_HashCode key;
350   GNUNET_HashCode query;
351   struct GNUNET_CRYPTO_AesSessionKey skey;
352   struct GNUNET_CRYPTO_AesInitializationVector iv;
353   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
354   
355   if (GNUNET_OK != success)
356     {
357       /* error! */
358       GNUNET_SCHEDULER_add_continuation (ac->sched,
359                                          &do_disconnect,
360                                          ac->dsh,
361                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
362       ac->cont (ac->cont_cls, NULL, msg);
363       GNUNET_FS_uri_destroy (ac->ksk_uri);
364       GNUNET_free (ac->pt);
365       GNUNET_free (ac->nb);
366       GNUNET_FS_namespace_delete (ac->ns, GNUNET_NO);
367       GNUNET_free (ac);
368       return;
369     }
370   if (ac->pos == ac->ksk_uri->data.ksk.keywordCount)
371     {
372       /* done! */
373       GNUNET_SCHEDULER_add_continuation (ac->sched,
374                                          &do_disconnect,
375                                          ac->dsh,
376                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
377       ac->cont (ac->cont_cls, ac->ksk_uri, NULL);
378       GNUNET_FS_uri_destroy (ac->ksk_uri);
379       GNUNET_free (ac->pt);
380       GNUNET_free (ac->nb);
381       GNUNET_FS_namespace_delete (ac->ns, GNUNET_NO);
382       GNUNET_free (ac);
383       return;
384     }
385   keyword = ac->ksk_uri->data.ksk.keywords[ac->pos++];
386   /* first character of keyword indicates if it is
387      mandatory or not -- ignore for hashing */
388   GNUNET_CRYPTO_hash (&keyword[1], strlen (&keyword[1]), &key);
389   GNUNET_CRYPTO_hash_to_aes_key (&key, &skey, &iv);
390   GNUNET_CRYPTO_aes_encrypt (ac->pt,
391                              ac->pt_size,
392                              &skey,
393                              &iv,
394                              &ac->nb[1]);
395   GNUNET_break (GNUNET_OK == 
396                 GNUNET_CRYPTO_rsa_sign (ac->ns->key,
397                                         &ac->nb->ns_purpose,
398                                         &ac->nb->ns_signature));
399   pk = GNUNET_CRYPTO_rsa_key_create_from_hash (&key);
400   GNUNET_assert (pk != NULL);
401   GNUNET_CRYPTO_rsa_key_get_public (pk, &ac->nb->keyspace);
402   GNUNET_CRYPTO_hash (&ac->nb->keyspace,
403                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
404                       &query);
405   GNUNET_break (GNUNET_OK == 
406                 GNUNET_CRYPTO_rsa_sign (pk,
407                                         &ac->nb->ksk_purpose,
408                                         &ac->nb->ksk_signature));
409   GNUNET_CRYPTO_rsa_key_free (pk);
410   GNUNET_DATASTORE_put (ac->dsh,
411                         0 /* no reservation */, 
412                         &query,
413                         ac->pt_size + sizeof (struct NBlock),
414                         ac->nb,
415                         GNUNET_BLOCK_TYPE_NBLOCK,
416                         ac->priority,
417                         ac->anonymity,
418                         ac->expiration,
419                         -2, 1,
420                         GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
421                         &advertisement_cont,
422                         ac);
423 }
424
425
426 /**
427  * Publish an advertismement for a namespace.  
428  *
429  * @param h handle to the file sharing subsystem
430  * @param ksk_uri keywords to use for advertisment
431  * @param namespace handle for the namespace that should be advertised
432  * @param meta meta-data for the namespace advertisement
433  * @param anonymity for the namespace advertismement
434  * @param priority for the namespace advertisement
435  * @param expiration for the namespace advertisement
436  * @param rootEntry name of the root of the namespace
437  * @param cont continuation
438  * @param cont_cls closure for cont
439  */
440 void
441 GNUNET_FS_namespace_advertise (struct GNUNET_FS_Handle *h,
442                                struct GNUNET_FS_Uri *ksk_uri,
443                                struct GNUNET_FS_Namespace *namespace,
444                                const struct GNUNET_CONTAINER_MetaData *meta,
445                                uint32_t anonymity,
446                                uint32_t priority,
447                                struct GNUNET_TIME_Absolute expiration,
448                                const char *rootEntry,
449                                GNUNET_FS_PublishContinuation cont,
450                                void *cont_cls)
451 {
452   size_t reslen;
453   size_t size;
454   ssize_t mdsize;
455   struct NBlock *nb;
456   char *mdst;
457   struct GNUNET_DATASTORE_Handle *dsh;
458   struct AdvertisementContext *ctx;
459   char *pt;
460
461   /* create advertisements */
462   mdsize = GNUNET_CONTAINER_meta_data_get_serialized_size (meta);
463   if (-1 == mdsize)
464     {
465       cont (cont_cls, NULL, _("Failed to serialize meta data"));
466       return;
467     }
468   reslen = strlen (rootEntry) + 1;
469   size = mdsize + sizeof (struct NBlock) + reslen;
470   if (size > MAX_NBLOCK_SIZE)
471     {
472       size = MAX_NBLOCK_SIZE;
473       mdsize = size - sizeof (struct NBlock) - reslen;
474     }
475
476   pt = GNUNET_malloc (mdsize + reslen);
477   memcpy (pt, rootEntry, reslen);
478   mdst = &pt[reslen];
479   mdsize = GNUNET_CONTAINER_meta_data_serialize (meta,
480                                                  &mdst,
481                                                  mdsize,
482                                                  GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
483   if (mdsize == -1)
484     {
485       GNUNET_break (0);
486       GNUNET_free (pt);
487       cont (cont_cls, NULL, _("Failed to serialize meta data"));
488       return;
489     }
490   size = mdsize + sizeof (struct NBlock) + reslen;  
491   nb = GNUNET_malloc (size);
492   GNUNET_CRYPTO_rsa_key_get_public (namespace->key, 
493                                     &nb->subspace);
494   nb->ns_purpose.size = htonl (mdsize + reslen + 
495                             sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
496                             sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
497   nb->ns_purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK);
498   nb->ksk_purpose.size = htonl (size - sizeof (struct GNUNET_CRYPTO_RsaSignature));
499   nb->ksk_purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK_KSIG);
500   dsh = GNUNET_DATASTORE_connect (h->cfg, h->sched);
501   if (NULL == dsh)
502     {
503       GNUNET_free (nb);
504       GNUNET_free (pt);
505       cont (cont_cls, NULL, _("Failed to connect to datastore service"));
506       return;
507     }  
508   ctx = GNUNET_malloc (sizeof (struct AdvertisementContext));
509   ctx->cont = cont;
510   ctx->cont_cls = cont_cls;
511   ctx->dsh = dsh;
512   ctx->sched = h->sched;
513   ctx->ksk_uri = GNUNET_FS_uri_dup (ksk_uri);
514   ctx->nb = nb;
515   ctx->pt = pt;
516   ctx->pt_size = mdsize + reslen;
517   ctx->ns = namespace;
518   ctx->ns->rc++;
519   ctx->anonymity = anonymity;
520   ctx->priority = priority;
521   ctx->expiration = expiration;
522   advertisement_cont (ctx, GNUNET_OK, NULL);
523 }
524
525
526 /**
527  * Create a namespace with the given name; if one already
528  * exists, return a handle to the existing namespace.
529  *
530  * @param h handle to the file sharing subsystem
531  * @param name name to use for the namespace
532  * @return handle to the namespace, NULL on error
533  */
534 struct GNUNET_FS_Namespace *
535 GNUNET_FS_namespace_create (struct GNUNET_FS_Handle *h,
536                             const char *name)
537 {
538   char *dn;
539   char *fn;
540   struct GNUNET_FS_Namespace *ret;
541
542   dn = get_namespace_directory (h);
543   GNUNET_asprintf (&fn,
544                    "%s%s%s",
545                    dn,
546                    DIR_SEPARATOR_STR,
547                    name);
548   GNUNET_free (dn);
549   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Namespace));
550   ret->h = h;
551   ret->rc = 1;
552   ret->key = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
553   if (ret->key == NULL)
554     {
555       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
556                   _("Failed to create or read private key for namespace `%s'\n"),
557                   name);
558       GNUNET_free (ret);
559       GNUNET_free (fn);
560       return NULL;
561     }
562   ret->name = GNUNET_strdup (name);
563   ret->filename = fn;
564   return ret;
565 }
566
567
568 /**
569  * Delete a namespace handle.  Can be used for a clean shutdown (free
570  * memory) or also to freeze the namespace to prevent further
571  * insertions by anyone.
572  *
573  * @param namespace handle to the namespace that should be deleted / freed
574  * @param freeze prevents future insertions; creating a namespace
575  *        with the same name again will create a fresh namespace instead
576  *
577  * @return GNUNET_OK on success, GNUNET_SYSERR on error
578  */
579 int 
580 GNUNET_FS_namespace_delete (struct GNUNET_FS_Namespace *namespace,
581                             int freeze)
582 {
583   unsigned int i;
584   struct NamespaceUpdateNode *nsn;
585
586   namespace->rc--;
587   if (freeze)
588     {
589       if (0 != UNLINK (namespace->filename))
590         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
591                                   "unlink",
592                                   namespace->filename);      
593     }
594   if (0 == namespace->rc)
595     {
596       GNUNET_CRYPTO_rsa_key_free (namespace->key);
597       GNUNET_free (namespace->filename);
598       GNUNET_free (namespace->name);
599       for (i=0;i<namespace->update_node_count;i++)
600         {
601           nsn = namespace->update_nodes[i];
602           GNUNET_CONTAINER_meta_data_destroy (nsn->md);
603           GNUNET_FS_uri_destroy (nsn->uri);
604           GNUNET_free (nsn->id);
605           GNUNET_free (nsn->update);
606           GNUNET_free (nsn);
607         }
608       GNUNET_array_grow (namespace->update_nodes,
609                          namespace->update_node_count,
610                          0);
611       if (namespace->update_map != NULL)
612         GNUNET_CONTAINER_multihashmap_destroy (namespace->update_map);
613       GNUNET_free (namespace);
614     }
615   return GNUNET_OK;
616 }
617
618
619 /**
620  * Context for the 'process_namespace' callback.
621  * Specifies a function to call on each namespace.
622  */
623 struct ProcessNamespaceContext
624 {
625   /**
626    * Function to call.
627    */
628   GNUNET_FS_NamespaceInfoProcessor cb;
629
630   /**
631    * Closure for 'cb'.
632    */
633   void *cb_cls;
634 };
635
636
637 /**
638  * Function called with a filename of a namespace. Reads the key and
639  * calls the callback.
640  *
641  * @param cls closure (struct ProcessNamespaceContext)
642  * @param filename complete filename (absolute path)
643  * @return GNUNET_OK to continue to iterate,
644  *  GNUNET_SYSERR to abort iteration with error!
645  */
646 static int
647 process_namespace (void *cls, 
648                    const char *filename)
649 {
650   struct ProcessNamespaceContext *pnc = cls;
651   struct GNUNET_CRYPTO_RsaPrivateKey *key;
652   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
653   GNUNET_HashCode id;
654   const char *name;
655   const char *t;
656
657   key = GNUNET_CRYPTO_rsa_key_create_from_file (filename);
658   if (key == NULL)
659     {
660       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
661                   _("Failed to read namespace private key file `%s', deleting it!\n"),
662                   filename);
663       if (0 != UNLINK (filename))
664         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
665                                   "unlink",
666                                   filename);
667       return GNUNET_OK;
668     }
669   GNUNET_CRYPTO_rsa_key_get_public (key, &pk);
670   GNUNET_CRYPTO_rsa_key_free (key);
671   GNUNET_CRYPTO_hash (&pk, sizeof(pk), &id); 
672   name = filename;
673   while (NULL != (t = strstr (name, DIR_SEPARATOR_STR)))
674     name = t + 1;
675   pnc->cb (pnc->cb_cls,
676            name,
677            &id);
678   return GNUNET_OK;
679 }
680
681
682 /**
683  * Build a list of all available local (!) namespaces The returned
684  * names are only the nicknames since we only iterate over the local
685  * namespaces.
686  *
687  * @param h handle to the file sharing subsystem
688  * @param cb function to call on each known namespace
689  * @param cb_cls closure for cb
690  */
691 void 
692 GNUNET_FS_namespace_list (struct GNUNET_FS_Handle *h,
693                           GNUNET_FS_NamespaceInfoProcessor cb,
694                           void *cb_cls)
695 {
696   char *dn;
697   struct ProcessNamespaceContext ctx;
698   
699   dn = get_namespace_directory (h);
700   if (dn == NULL)
701     return;
702   ctx.cb = cb;
703   ctx.cb_cls = cb_cls;
704   GNUNET_DISK_directory_scan (dn,
705                               &process_namespace,
706                               &ctx);
707   GNUNET_free (dn);
708 }
709
710
711
712
713 /**
714  * Context for the SKS publication.
715  */
716 struct PublishSksContext
717 {
718
719   /**
720    * URI of the new entry in the namespace.
721    */
722   struct GNUNET_FS_Uri *uri;
723
724   /**
725    * Namespace update node to add to namespace on success (or to be
726    * deleted if publishing failed).
727    */
728   struct NamespaceUpdateNode *nsn;
729
730   /**
731    * Namespace we're publishing to.
732    */
733   struct GNUNET_FS_Namespace *namespace;
734
735   /**
736    * Handle to the datastore.
737    */
738   struct GNUNET_DATASTORE_Handle *dsh;
739
740   /**
741    * Function to call once we're done.
742    */
743   GNUNET_FS_PublishContinuation cont;
744
745   /**
746    * Closure for cont.
747    */ 
748   void *cont_cls;
749
750 };
751
752
753 /**
754  * Function called by the datastore API with
755  * the result from the PUT (SBlock) request.
756  *
757  * @param cls closure of type "struct PublishSksContext*"
758  * @param success GNUNET_OK on success
759  * @param msg error message (or NULL)
760  */
761 static void
762 sb_put_cont (void *cls,
763              int success,
764              const char *msg)
765 {
766   struct PublishSksContext *psc = cls;
767   GNUNET_HashCode hc;
768
769   if (NULL != psc->dsh)
770     {
771       GNUNET_DATASTORE_disconnect (psc->dsh, GNUNET_NO);
772       psc->dsh = NULL;
773     }
774   if (GNUNET_OK != success)
775     {
776       psc->cont (psc->cont_cls,
777                  NULL,
778                  msg);
779     }
780   else
781     {
782       if (psc->nsn != NULL)
783         {
784           /* FIXME: this can be done much more
785              efficiently by simply appending to the
786              file and overwriting the 4-byte header */
787           if (psc->namespace->update_nodes == NULL)
788             read_update_information_graph (psc->namespace);
789           GNUNET_array_append (psc->namespace->update_nodes,
790                                psc->namespace->update_node_count,
791                                psc->nsn);
792           if (psc->namespace->update_map != NULL)
793             {
794               GNUNET_CRYPTO_hash (psc->nsn->id,
795                                   strlen (psc->nsn->id),
796                                   &hc);
797               GNUNET_CONTAINER_multihashmap_put (psc->namespace->update_map,
798                                                  &hc,
799                                                  psc->nsn,
800                                                  GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
801             }
802           psc->nsn = NULL;
803           write_update_information_graph (psc->namespace);
804         }
805       psc->cont (psc->cont_cls,
806                  psc->uri,
807                  NULL);
808     }
809   GNUNET_FS_namespace_delete (psc->namespace,
810                               GNUNET_NO);
811   GNUNET_FS_uri_destroy (psc->uri);
812   if (psc->nsn != NULL)
813     {
814       GNUNET_CONTAINER_meta_data_destroy (psc->nsn->md);
815       GNUNET_FS_uri_destroy (psc->nsn->uri);
816       GNUNET_free (psc->nsn->id);
817       GNUNET_free (psc->nsn->update);
818       GNUNET_free (psc->nsn);
819     }
820   GNUNET_free (psc);
821 }
822
823
824 /**
825  * Publish an SBlock on GNUnet.
826  *
827  * @param h handle to the file sharing subsystem
828  * @param namespace namespace to publish in
829  * @param identifier identifier to use
830  * @param update update identifier to use
831  * @param meta metadata to use
832  * @param uri URI to refer to in the SBlock
833  * @param expirationTime when the SBlock expires
834  * @param anonymity anonymity level for the SBlock
835  * @param priority priority for the SBlock
836  * @param options publication options
837  * @param cont continuation
838  * @param cont_cls closure for cont
839  */
840 void
841 GNUNET_FS_publish_sks (struct GNUNET_FS_Handle *h,
842                        struct GNUNET_FS_Namespace *namespace,
843                        const char *identifier,
844                        const char *update,
845                        const struct GNUNET_CONTAINER_MetaData *meta,
846                        const struct GNUNET_FS_Uri *uri,
847                        struct GNUNET_TIME_Absolute expirationTime,
848                        uint32_t anonymity,
849                        uint32_t priority,
850                        enum GNUNET_FS_PublishOptions options,
851                        GNUNET_FS_PublishContinuation cont,
852                        void *cont_cls)
853 {
854   struct PublishSksContext *psc;
855   struct GNUNET_CRYPTO_AesSessionKey sk;
856   struct GNUNET_CRYPTO_AesInitializationVector iv;
857   struct GNUNET_FS_Uri *sks_uri;
858   char *uris;
859   size_t size;
860   size_t slen;
861   size_t nidlen;
862   size_t idlen;
863   ssize_t mdsize;
864   struct SBlock *sb;
865   struct SBlock *sb_enc;
866   char *dest;
867   struct GNUNET_CONTAINER_MetaData *mmeta;
868   GNUNET_HashCode key;         /* hash of thisId = key */
869   GNUNET_HashCode id;          /* hash of hc = identifier */
870   GNUNET_HashCode query;       /* id ^ nsid = DB query */
871
872   if (NULL == meta)
873     mmeta = GNUNET_CONTAINER_meta_data_create ();
874   else
875     mmeta = GNUNET_CONTAINER_meta_data_duplicate (meta);
876   uris = GNUNET_FS_uri_to_string (uri);
877   slen = strlen (uris) + 1;
878   idlen = strlen (identifier);
879   if (update == NULL)
880     update = "";
881   nidlen = strlen (update) + 1;
882   mdsize = GNUNET_CONTAINER_meta_data_get_serialized_size (mmeta);
883   size = sizeof (struct SBlock) + slen + nidlen + mdsize;
884   if (size > MAX_SBLOCK_SIZE)
885     {
886       size = MAX_SBLOCK_SIZE;
887       mdsize = size - (sizeof (struct SBlock) + slen + nidlen);
888     }
889   sb = GNUNET_malloc (sizeof (struct SBlock) + size);
890   dest = (char *) &sb[1];
891   memcpy (dest, update, nidlen);
892   dest += nidlen;
893   memcpy (dest, uris, slen);
894   GNUNET_free (uris);
895   dest += slen;
896   mdsize = GNUNET_CONTAINER_meta_data_serialize (mmeta,
897                                                  &dest,
898                                                  mdsize, 
899                                                  GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
900   GNUNET_CONTAINER_meta_data_destroy (mmeta);
901   if (mdsize == -1)
902     {
903       GNUNET_break (0);
904       GNUNET_free (sb);
905       cont (cont_cls,
906             NULL,
907             _("Internal error."));
908       return;
909     }
910   size = sizeof (struct SBlock) + mdsize + slen + nidlen;
911   sb_enc = GNUNET_malloc (size);
912   GNUNET_CRYPTO_hash (identifier, idlen, &key);
913   GNUNET_CRYPTO_hash (&key, sizeof (GNUNET_HashCode), &id);
914   sks_uri = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri));
915   sks_uri->type = sks;
916   GNUNET_CRYPTO_rsa_key_get_public (namespace->key, &sb_enc->subspace);
917   GNUNET_CRYPTO_hash (&sb_enc->subspace,
918                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
919                       &sks_uri->data.sks.namespace);
920   sks_uri->data.sks.identifier = GNUNET_strdup (identifier);
921   GNUNET_CRYPTO_hash_xor (&id, 
922                           &sks_uri->data.sks.namespace, 
923                           &sb_enc->identifier);
924   GNUNET_CRYPTO_hash_to_aes_key (&key, &sk, &iv);
925   GNUNET_CRYPTO_aes_encrypt (&sb[1],
926                              size - sizeof (struct SBlock),
927                              &sk,
928                              &iv,
929                              &sb_enc[1]);
930   sb_enc->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK);
931   sb_enc->purpose.size = htonl(slen + mdsize + nidlen
932                                + sizeof(struct SBlock)
933                                - sizeof(struct GNUNET_CRYPTO_RsaSignature));
934   GNUNET_assert (GNUNET_OK == 
935                  GNUNET_CRYPTO_rsa_sign (namespace->key,
936                                          &sb_enc->purpose,
937                                          &sb_enc->signature));
938   psc = GNUNET_malloc (sizeof(struct PublishSksContext));
939   psc->uri = sks_uri;
940   psc->cont = cont;
941   psc->namespace = namespace;
942   namespace->rc++;
943   psc->cont_cls = cont_cls;
944   if (0 != (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY))
945     {
946       GNUNET_free (sb_enc);
947       GNUNET_free (sb);
948       sb_put_cont (psc,
949                    GNUNET_OK,
950                    NULL);
951       return;
952     }
953   psc->dsh = GNUNET_DATASTORE_connect (h->cfg, h->sched);
954   if (NULL == psc->dsh)
955     {
956       GNUNET_free (sb_enc);
957       GNUNET_free (sb);
958       sb_put_cont (psc,
959                    GNUNET_NO,
960                    _("Failed to connect to datastore."));
961       return;
962     }
963   GNUNET_CRYPTO_hash_xor (&sks_uri->data.sks.namespace,
964                           &id,
965                           &query);  
966   if (NULL != update)
967     {
968       psc->nsn = GNUNET_malloc (sizeof (struct NamespaceUpdateNode));
969       psc->nsn->id = GNUNET_strdup (identifier);
970       psc->nsn->update = GNUNET_strdup (update);
971       psc->nsn->md = GNUNET_CONTAINER_meta_data_duplicate (meta);
972       psc->nsn->uri = GNUNET_FS_uri_dup (uri);
973     }
974   GNUNET_DATASTORE_put (psc->dsh,
975                         0,
976                         &sb_enc->identifier,
977                         size,
978                         sb_enc,
979                         GNUNET_BLOCK_TYPE_SBLOCK, 
980                         priority,
981                         anonymity,
982                         expirationTime,
983                         -2, 1,
984                         GNUNET_CONSTANTS_SERVICE_TIMEOUT,
985                         &sb_put_cont,
986                         psc);
987   GNUNET_free (sb);
988   GNUNET_free (sb_enc);
989 }
990
991
992 /**
993  * Closure for 'process_update_node'.
994  */
995 struct ProcessUpdateClosure 
996 {
997   /**
998    * Function to call for each node.
999    */
1000   GNUNET_FS_IdentifierProcessor ip;
1001
1002   /**
1003    * Closure for 'ip'.
1004    */
1005   void *ip_cls;
1006 };
1007
1008
1009 /**
1010  * Call the iterator in the closure for each node.
1011  *
1012  * @param cls closure (of type 'struct ProcessUpdateClosure *')
1013  * @param key current key code
1014  * @param value value in the hash map (of type 'struct NamespaceUpdateNode *')
1015  * @return GNUNET_YES if we should continue to
1016  *         iterate,
1017  *         GNUNET_NO if not.
1018  */
1019 static int
1020 process_update_node (void *cls,
1021                      const GNUNET_HashCode * key,
1022                      void *value)
1023 {
1024   struct ProcessUpdateClosure *pc = cls;
1025   struct NamespaceUpdateNode *nsn = value;
1026
1027   pc->ip (pc->ip_cls,
1028           nsn->id,
1029           nsn->uri,
1030           nsn->md,
1031           nsn->update);
1032   return GNUNET_YES;
1033 }
1034
1035
1036 /**
1037  * Closure for 'find_sccs'.
1038  */
1039 struct FindSccClosure 
1040 {
1041   /**
1042    * Namespace we are operating on.
1043    */
1044   struct GNUNET_FS_Namespace *namespace;
1045
1046   /**
1047    * Array with 'head's of SCCs.
1048    */
1049   struct NamespaceUpdateNode **scc_array;
1050
1051   /**
1052    * Size of 'scc_array'
1053    */
1054   unsigned int scc_array_size;
1055
1056   /**
1057    * Current generational ID used.
1058    */
1059   unsigned int nug;
1060
1061   /**
1062    * Identifier for the current SCC, or UINT_MAX for none yet.
1063    */
1064   unsigned int id;
1065 };
1066
1067
1068 /**
1069  * Find all nodes reachable from the current node (including the
1070  * current node itself).  If they are in no SCC, add them to the
1071  * current one.   If they are the head of another SCC, merge the
1072  * SCCs.  If they are in the middle of another SCC, let them be.
1073  * We can tell that a node is already in an SCC by checking if
1074  * its 'nug' field is set to the current 'nug' value.  It is the
1075  * head of an SCC if it is in the 'scc_array' under its respective
1076  * 'scc_id'.
1077  *
1078  * @param cls closure (of type 'struct FindSccClosure')
1079  * @param key current key code
1080  * @param value value in the hash map
1081  * @return GNUNET_YES if we should continue to
1082  *         iterate,
1083  *         GNUNET_NO if not.
1084  */
1085 static int
1086 find_sccs (void *cls,
1087            const GNUNET_HashCode * key,
1088            void *value)
1089 {
1090   struct FindSccClosure *fc = cls;
1091   struct NamespaceUpdateNode *nsn = value;
1092   GNUNET_HashCode hc;
1093
1094   if (nsn->nug == fc->nug)
1095     {
1096       if (fc->scc_array[nsn->scc_id] != nsn)
1097         return GNUNET_YES; /* part of another SCC, end trace */
1098       fc->scc_array[nsn->scc_id] = NULL;
1099       if (fc->id == UINT_MAX)
1100         fc->id = nsn->scc_id; /* take over ID */
1101     }
1102   else
1103     {
1104       nsn->nug = fc->nug;
1105       /* trace */
1106       GNUNET_CRYPTO_hash (nsn->update,
1107                           strlen (nsn->update),
1108                           &hc);
1109       GNUNET_CONTAINER_multihashmap_get_multiple (fc->namespace->update_map,
1110                                                   &hc,
1111                                                   &find_sccs,
1112                                                   fc);
1113     }
1114   return GNUNET_YES;
1115 }
1116
1117
1118 /**
1119  * List all of the identifiers in the namespace for which we could
1120  * produce an update.  Namespace updates form a graph where each node
1121  * has a name.  Each node can have any number of URI/meta-data entries
1122  * which can each be linked to other nodes.  Cycles are possible.
1123  * 
1124  * Calling this function with "next_id" NULL will cause the library to
1125  * call "ip" with a root for each strongly connected component of the
1126  * graph (a root being a node from which all other nodes in the Scc
1127  * are reachable).
1128  * 
1129  * Calling this function with "next_id" being the name of a node will
1130  * cause the library to call "ip" with all children of the node.  Note
1131  * that cycles within an SCC are possible (including self-loops).
1132  *
1133  * @param namespace namespace to inspect for updateable content
1134  * @param next_id ID to look for; use NULL to look for SCC roots
1135  * @param ip function to call on each updateable identifier
1136  * @param ip_cls closure for ip
1137  */
1138 void
1139 GNUNET_FS_namespace_list_updateable (struct GNUNET_FS_Namespace *namespace,
1140                                      const char *next_id,
1141                                      GNUNET_FS_IdentifierProcessor ip, 
1142                                      void *ip_cls)
1143 {
1144   unsigned int i;
1145   unsigned int nug;
1146   GNUNET_HashCode hc;
1147   struct NamespaceUpdateNode *nsn;
1148   struct ProcessUpdateClosure pc;
1149   struct FindSccClosure fc;
1150
1151   if (namespace->update_nodes == NULL)
1152     read_update_information_graph (namespace);
1153   if (namespace->update_nodes == NULL)
1154     return; /* no nodes */
1155   if (namespace->update_map == NULL)
1156     {
1157       /* need to construct */
1158       namespace->update_map = GNUNET_CONTAINER_multihashmap_create (2 + 3 * namespace->update_node_count / 4);
1159       for (i=0;i<namespace->update_node_count;i++)
1160         {
1161           nsn = namespace->update_nodes[i];
1162           GNUNET_CRYPTO_hash (nsn->id,
1163                               strlen (nsn->id),
1164                               &hc);
1165           GNUNET_CONTAINER_multihashmap_put (namespace->update_map,
1166                                              &hc,
1167                                              nsn,
1168                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);                         
1169         }
1170     }
1171   if (next_id != NULL)
1172     {
1173       GNUNET_CRYPTO_hash (next_id,
1174                           strlen (next_id),
1175                           &hc);
1176       pc.ip = ip;
1177       pc.ip_cls = ip_cls;
1178       GNUNET_CONTAINER_multihashmap_get_multiple (namespace->update_map,
1179                                                   &hc,
1180                                                   &process_update_node,
1181                                                   &pc);
1182       return;
1183     }
1184   /* Find heads of SCCs in update graph */
1185   nug = ++namespace->nug_gen;
1186   fc.scc_array = NULL;
1187   fc.scc_array_size = 0;
1188
1189   for (i=0;i<namespace->update_node_count;i++)
1190     {
1191       nsn = namespace->update_nodes[i];
1192       if (nsn->nug == nug)
1193         continue; /* already placed in SCC */
1194       GNUNET_CRYPTO_hash (nsn->update,
1195                           strlen (nsn->update),
1196                           &hc);
1197       nsn->nug = nug;
1198       fc.id = UINT_MAX;
1199       fc.nug = nug;
1200       fc.namespace = namespace;
1201       GNUNET_CONTAINER_multihashmap_get_multiple (namespace->update_map,
1202                                                   &hc,
1203                                                   &find_sccs,
1204                                                   &fc);
1205       if (fc.id == UINT_MAX)
1206         {
1207           /* start new SCC */
1208           for (fc.id=0;fc.id<fc.scc_array_size;fc.id++)
1209             {
1210               if (fc.scc_array[fc.id] == NULL)
1211                 {
1212                   fc.scc_array[fc.id] = nsn;
1213                   nsn->scc_id = fc.id;
1214                   break;
1215                 }
1216             }
1217           if (fc.id == fc.scc_array_size)
1218             {
1219               GNUNET_array_append (fc.scc_array,
1220                                    fc.scc_array_size,
1221                                    nsn);
1222               nsn->scc_id = fc.id;
1223             }
1224           /* put all nodes with same identifier into this SCC */
1225           GNUNET_CRYPTO_hash (nsn->id,
1226                               strlen (nsn->id),
1227                               &hc);
1228           fc.id = nsn->scc_id;
1229           fc.nug = nug;
1230           fc.namespace = namespace;
1231           GNUNET_CONTAINER_multihashmap_get_multiple (namespace->update_map,
1232                                                       &hc,
1233                                                       &find_sccs,
1234                                                       &fc);
1235         }
1236       else
1237         {
1238           /* make head of SCC "id" */
1239           fc.scc_array[fc.id] = nsn;
1240           nsn->scc_id = fc.id;
1241         }
1242     }
1243   for (i=0;i<fc.scc_array_size;i++)
1244     {
1245       nsn = fc.scc_array[i];
1246       ip (ip_cls,
1247           nsn->id,
1248           nsn->uri,
1249           nsn->md,
1250           nsn->update);
1251     }
1252   GNUNET_array_grow (fc.scc_array,
1253                      fc.scc_array_size,
1254                      0);
1255 }
1256
1257
1258 /* end of fs_namespace.c */
1259