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