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