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