ds
[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 2, 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 /**
34  * Return the name of the directory in which we store
35  * our local namespaces (or rather, their public keys).
36  *
37  * @param h global fs handle 
38  * @return NULL on error, otherwise the name of the directory
39  */
40 static char *
41 get_namespace_directory (struct GNUNET_FS_Handle *h)
42 {
43   char *dn;
44
45   if (GNUNET_OK !=
46       GNUNET_CONFIGURATION_get_value_filename (h->cfg,
47                                                "FS",
48                                                "IDENTITY_DIR",
49                                                &dn))
50     {
51       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
52                   _("Configuration fails to specify `%s' in section `%s'\n"),
53                   "IDENTITY_DIR",
54                   "fs");
55       return NULL;
56     }
57   return dn;
58 }
59
60
61 /**
62  * Context for advertising a namespace.
63  */
64 struct AdvertisementContext
65 {
66   /**
67    * Function to call with the result.
68    */
69   GNUNET_FS_PublishContinuation cont;
70
71   /**
72    * Closure for cont.
73    */
74   void *cont_cls;
75
76   /**
77    * Datastore handle.
78    */
79   struct GNUNET_DATASTORE_Handle *dsh;
80
81   /**
82    * Our KSK URI.
83    */ 
84   struct GNUNET_FS_Uri *ksk_uri;
85
86   /**
87    * Plaintext.
88    */
89   char *pt;
90
91   /**
92    * NBlock to sign and store.
93    */
94   struct NBlock *nb;
95
96   /**
97    * The namespace.
98    */
99   struct GNUNET_FS_Namespace *ns;
100
101   /**
102    * Expiration time.
103    */
104   struct GNUNET_TIME_Absolute expiration;
105
106   /**
107    * Number of bytes of plaintext.
108    */ 
109   size_t pt_size;
110
111   /**
112    * Anonymity level.
113    */
114   uint32_t anonymity;
115
116   /**
117    * Content priority.
118    */
119   uint32_t priority;
120
121   /**
122    * Current keyword offset.
123    */
124   unsigned int pos;
125 };
126
127
128 /**
129  * Continuation called to notify client about result of the
130  * operation.
131  *
132  * @param cls closure (our struct AdvertismentContext)
133  * @param success GNUNET_SYSERR on failure
134  * @param msg NULL on success, otherwise an error message
135  */
136 static void
137 advertisement_cont (void *cls,
138                     int success,
139                     const char *msg)
140 {
141   struct AdvertisementContext *ac = cls;
142   const char *keyword;
143   GNUNET_HashCode key;
144   GNUNET_HashCode query;
145   struct GNUNET_CRYPTO_AesSessionKey skey;
146   struct GNUNET_CRYPTO_AesInitializationVector iv;
147   struct GNUNET_CRYPTO_RsaPrivateKey *pk;
148   
149   if (GNUNET_OK != success)
150     {
151       /* error! */
152       GNUNET_DATASTORE_disconnect (ac->dsh, GNUNET_NO);
153       ac->cont (ac->cont_cls, NULL, msg);
154       GNUNET_FS_uri_destroy (ac->ksk_uri);
155       GNUNET_free (ac->pt);
156       GNUNET_free (ac->nb);
157       GNUNET_FS_namespace_delete (ac->ns, GNUNET_NO);
158       GNUNET_free (ac);
159       return;
160     }
161   if (ac->pos == ac->ksk_uri->data.ksk.keywordCount)
162     {
163       /* done! */
164       GNUNET_DATASTORE_disconnect (ac->dsh, GNUNET_NO);
165       ac->cont (ac->cont_cls, ac->ksk_uri, NULL);
166       GNUNET_FS_uri_destroy (ac->ksk_uri);
167       GNUNET_free (ac->pt);
168       GNUNET_free (ac->nb);
169       GNUNET_FS_namespace_delete (ac->ns, GNUNET_NO);
170       GNUNET_free (ac);
171       return;
172     }
173   keyword = ac->ksk_uri->data.ksk.keywords[ac->pos++];
174   /* first character of keyword indicates if it is
175      mandatory or not -- ignore for hashing */
176   GNUNET_CRYPTO_hash (&keyword[1], strlen (&keyword[1]), &key);
177   GNUNET_CRYPTO_hash_to_aes_key (&key, &skey, &iv);
178   GNUNET_CRYPTO_aes_encrypt (ac->pt,
179                              ac->pt_size,
180                              &skey,
181                              &iv,
182                              &ac->nb[1]);
183   GNUNET_break (GNUNET_OK == 
184                 GNUNET_CRYPTO_rsa_sign (ac->ns->key,
185                                         &ac->nb->ns_purpose,
186                                         &ac->nb->ns_signature));
187   pk = GNUNET_CRYPTO_rsa_key_create_from_hash (&key);
188   GNUNET_CRYPTO_rsa_key_get_public (pk, &ac->nb->keyspace);
189   GNUNET_CRYPTO_hash (&ac->nb->keyspace,
190                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
191                       &query);
192   GNUNET_break (GNUNET_OK == 
193                 GNUNET_CRYPTO_rsa_sign (pk,
194                                         &ac->nb->ksk_purpose,
195                                         &ac->nb->ksk_signature));
196   GNUNET_CRYPTO_rsa_key_free (pk);
197   GNUNET_DATASTORE_put (ac->dsh,
198                         0 /* no reservation */, 
199                         &query,
200                         ac->pt_size + sizeof (struct NBlock),
201                         ac->nb,
202                         GNUNET_BLOCK_TYPE_NBLOCK,
203                         ac->priority,
204                         ac->anonymity,
205                         ac->expiration,
206                         -2, 1,
207                         GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
208                         &advertisement_cont,
209                         ac);
210 }
211
212
213 /**
214  * Publish an advertismement for a namespace.  
215  *
216  * @param h handle to the file sharing subsystem
217  * @param ksk_uri keywords to use for advertisment
218  * @param namespace handle for the namespace that should be advertised
219  * @param meta meta-data for the namespace advertisement
220  * @param anonymity for the namespace advertismement
221  * @param priority for the namespace advertisement
222  * @param expiration for the namespace advertisement
223  * @param rootEntry name of the root of the namespace
224  * @param cont continuation
225  * @param cont_cls closure for cont
226  */
227 void
228 GNUNET_FS_namespace_advertise (struct GNUNET_FS_Handle *h,
229                                struct GNUNET_FS_Uri *ksk_uri,
230                                struct GNUNET_FS_Namespace *namespace,
231                                const struct GNUNET_CONTAINER_MetaData *meta,
232                                uint32_t anonymity,
233                                uint32_t priority,
234                                struct GNUNET_TIME_Absolute expiration,
235                                const char *rootEntry,
236                                GNUNET_FS_PublishContinuation cont,
237                                void *cont_cls)
238 {
239   size_t reslen;
240   size_t size;
241   ssize_t mdsize;
242   struct NBlock *nb;
243   char *mdst;
244   struct GNUNET_DATASTORE_Handle *dsh;
245   struct AdvertisementContext *ctx;
246   char *pt;
247
248   /* create advertisements */
249   mdsize = GNUNET_CONTAINER_meta_data_get_serialized_size (meta);
250   if (-1 == mdsize)
251     {
252       cont (cont_cls, NULL, _("Failed to serialize meta data"));
253       return;
254     }
255   reslen = strlen (rootEntry) + 1;
256   size = mdsize + sizeof (struct NBlock) + reslen;
257   if (size > MAX_NBLOCK_SIZE)
258     {
259       size = MAX_NBLOCK_SIZE;
260       mdsize = size - sizeof (struct NBlock) - reslen;
261     }
262
263   pt = GNUNET_malloc (mdsize + reslen);
264   memcpy (pt, rootEntry, reslen);
265   mdst = &pt[reslen];
266   mdsize = GNUNET_CONTAINER_meta_data_serialize (meta,
267                                                  &mdst,
268                                                  mdsize,
269                                                  GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
270   if (mdsize == -1)
271     {
272       GNUNET_break (0);
273       GNUNET_free (pt);
274       cont (cont_cls, NULL, _("Failed to serialize meta data"));
275       return;
276     }
277   size = mdsize + sizeof (struct NBlock) + reslen;  
278   nb = GNUNET_malloc (size);
279   GNUNET_CRYPTO_rsa_key_get_public (namespace->key, 
280                                     &nb->subspace);
281   nb->ns_purpose.size = htonl (mdsize + reslen + 
282                             sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
283                             sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
284   nb->ns_purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK);
285   nb->ksk_purpose.size = htonl (size - sizeof (struct GNUNET_CRYPTO_RsaSignature));
286   nb->ksk_purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_FS_NBLOCK_KSIG);
287   dsh = GNUNET_DATASTORE_connect (h->cfg, h->sched);
288   if (NULL == dsh)
289     {
290       GNUNET_free (nb);
291       GNUNET_free (pt);
292       cont (cont_cls, NULL, _("Failed to connect to datastore service"));
293       return;
294     }  
295   ctx = GNUNET_malloc (sizeof (struct AdvertisementContext));
296   ctx->cont = cont;
297   ctx->cont_cls = cont_cls;
298   ctx->dsh = dsh;
299   ctx->ksk_uri = GNUNET_FS_uri_dup (ksk_uri);
300   ctx->nb = nb;
301   ctx->pt = pt;
302   ctx->pt_size = mdsize + reslen;
303   ctx->ns = namespace;
304   ctx->ns->rc++;
305   ctx->anonymity = anonymity;
306   ctx->priority = priority;
307   ctx->expiration = expiration;
308   advertisement_cont (ctx, GNUNET_OK, NULL);
309 }
310
311
312 /**
313  * Create a namespace with the given name; if one already
314  * exists, return a handle to the existing namespace.
315  *
316  * @param h handle to the file sharing subsystem
317  * @param name name to use for the namespace
318  * @return handle to the namespace, NULL on error
319  */
320 struct GNUNET_FS_Namespace *
321 GNUNET_FS_namespace_create (struct GNUNET_FS_Handle *h,
322                             const char *name)
323 {
324   char *dn;
325   char *fn;
326   struct GNUNET_FS_Namespace *ret;
327
328   dn = get_namespace_directory (h);
329   GNUNET_asprintf (&fn,
330                    "%s%s%s",
331                    dn,
332                    DIR_SEPARATOR_STR,
333                    name);
334   GNUNET_free (dn);
335   ret = GNUNET_malloc (sizeof (struct GNUNET_FS_Namespace));
336   ret->rc = 1;
337   ret->key = GNUNET_CRYPTO_rsa_key_create_from_file (fn);
338   if (ret->key == NULL)
339     {
340       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
341                   _("Failed to create or read private key for namespace `%s'\n"),
342                   name);
343       GNUNET_free (ret);
344       GNUNET_free (fn);
345       return NULL;
346     }
347   ret->name = GNUNET_strdup (name);
348   ret->filename = fn;
349   return ret;
350 }
351
352
353 /**
354  * Delete a namespace handle.  Can be used for a clean shutdown (free
355  * memory) or also to freeze the namespace to prevent further
356  * insertions by anyone.
357  *
358  * @param namespace handle to the namespace that should be deleted / freed
359  * @param freeze prevents future insertions; creating a namespace
360  *        with the same name again will create a fresh namespace instead
361  *
362  * @return GNUNET_OK on success, GNUNET_SYSERR on error
363  */
364 int 
365 GNUNET_FS_namespace_delete (struct GNUNET_FS_Namespace *namespace,
366                             int freeze)
367 {
368   namespace->rc--;
369   if (freeze)
370     {
371       if (0 != UNLINK (namespace->filename))
372         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
373                                   "unlink",
374                                   namespace->filename);      
375     }
376   if (0 == namespace->rc)
377     {
378       GNUNET_CRYPTO_rsa_key_free (namespace->key);
379       GNUNET_free (namespace->filename);
380       GNUNET_free (namespace->name);
381       GNUNET_free (namespace);
382     }
383   return GNUNET_OK;
384 }
385
386
387 /**
388  * Context for the 'process_namespace' callback.
389  * Specifies a function to call on each namespace.
390  */
391 struct ProcessNamespaceContext
392 {
393   /**
394    * Function to call.
395    */
396   GNUNET_FS_NamespaceInfoProcessor cb;
397
398   /**
399    * Closure for 'cb'.
400    */
401   void *cb_cls;
402 };
403
404
405 /**
406  * Function called with a filename of a namespace. Reads the key and
407  * calls the callback.
408  *
409  * @param cls closure (struct ProcessNamespaceContext)
410  * @param filename complete filename (absolute path)
411  * @return GNUNET_OK to continue to iterate,
412  *  GNUNET_SYSERR to abort iteration with error!
413  */
414 static int
415 process_namespace (void *cls, 
416                    const char *filename)
417 {
418   struct ProcessNamespaceContext *pnc = cls;
419   struct GNUNET_CRYPTO_RsaPrivateKey *key;
420   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pk;
421   GNUNET_HashCode id;
422   const char *name;
423   const char *t;
424
425   key = GNUNET_CRYPTO_rsa_key_create_from_file (filename);
426   if (key == NULL)
427     {
428       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
429                   _("Failed to read namespace private key file `%s', deleting it!\n"),
430                   filename);
431       if (0 != UNLINK (filename))
432         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
433                                   "unlink",
434                                   filename);
435       return GNUNET_OK;
436     }
437   GNUNET_CRYPTO_rsa_key_get_public (key, &pk);
438   GNUNET_CRYPTO_rsa_key_free (key);
439   GNUNET_CRYPTO_hash (&pk, sizeof(pk), &id); 
440   name = filename;
441   while (NULL != (t = strstr (name, DIR_SEPARATOR_STR)))
442     name = t + 1;
443   pnc->cb (pnc->cb_cls,
444            name,
445            &id);
446   return GNUNET_OK;
447 }
448
449
450 /**
451  * Build a list of all available local (!) namespaces The returned
452  * names are only the nicknames since we only iterate over the local
453  * namespaces.
454  *
455  * @param h handle to the file sharing subsystem
456  * @param cb function to call on each known namespace
457  * @param cb_cls closure for cb
458  */
459 void 
460 GNUNET_FS_namespace_list (struct GNUNET_FS_Handle *h,
461                           GNUNET_FS_NamespaceInfoProcessor cb,
462                           void *cb_cls)
463 {
464   char *dn;
465   struct ProcessNamespaceContext ctx;
466   
467   dn = get_namespace_directory (h);
468   if (dn == NULL)
469     return;
470   ctx.cb = cb;
471   ctx.cb_cls = cb_cls;
472   GNUNET_DISK_directory_scan (dn,
473                               &process_namespace,
474                               &ctx);
475   GNUNET_free (dn);
476 }
477
478 /* end of fs_namespace.c */
479