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