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