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