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