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