first batch of license fixes (boring)
[oweals/gnunet.git] / src / fs / gnunet-service-fs_indexing.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2010 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14 */
15
16 /**
17  * @file fs/gnunet-service-fs_indexing.c
18  * @brief program that provides indexing functions of the file-sharing service
19  * @author Christian Grothoff
20  */
21 #include "platform.h"
22 #include <float.h>
23 #include "gnunet_core_service.h"
24 #include "gnunet_datastore_service.h"
25 #include "gnunet_peer_lib.h"
26 #include "gnunet_protocols.h"
27 #include "gnunet_signatures.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet-service-fs.h"
30 #include "gnunet-service-fs_indexing.h"
31 #include "fs.h"
32
33 /**
34  * In-memory information about indexed files (also available
35  * on-disk).
36  */
37 struct IndexInfo
38 {
39
40   /**
41    * This is a doubly linked list.
42    */
43   struct IndexInfo *next;
44
45   /**
46    * This is a doubly linked list.
47    */
48   struct IndexInfo *prev;
49
50   /**
51    * Name of the indexed file.  Memory allocated
52    * at the end of this struct (do not free).
53    */
54   const char *filename;
55
56   /**
57    * Context for transmitting confirmation to client,
58    * NULL if we've done this already.
59    */
60   struct GNUNET_SERVER_TransmitContext *tc;
61
62   /**
63    * Context for hashing of the file.
64    */
65   struct GNUNET_CRYPTO_FileHashContext *fhc;
66
67   /**
68    * Hash of the contents of the file.
69    */
70   struct GNUNET_HashCode file_id;
71
72 };
73
74
75 /**
76  * Head of linked list of indexed files.
77  * FIXME: we don't need both a DLL and a hashmap here!
78  */
79 static struct IndexInfo *indexed_files_head;
80
81 /**
82  * Tail of linked list of indexed files.
83  */
84 static struct IndexInfo *indexed_files_tail;
85
86 /**
87  * Maps hash over content of indexed files to the respective 'struct IndexInfo'.
88  * The filenames are pointers into the indexed_files linked list and
89  * do not need to be freed.
90  */
91 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
92
93 /**
94  * Our configuration.
95  */
96 static const struct GNUNET_CONFIGURATION_Handle *cfg;
97
98 /**
99  * Datastore handle.  Created and destroyed by code in
100  * gnunet-service-fs (this is an alias).
101  */
102 static struct GNUNET_DATASTORE_Handle *dsh;
103
104
105 /**
106  * Write the current index information list to disk.
107  */
108 static void
109 write_index_list ()
110 {
111   struct GNUNET_BIO_WriteHandle *wh;
112   char *fn;
113   struct IndexInfo *pos;
114
115   if (GNUNET_OK !=
116       GNUNET_CONFIGURATION_get_value_filename (cfg, "FS",
117                                                "INDEXDB",
118                                                &fn))
119   {
120     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
121                                "fs",
122                                "INDEXDB");
123     return;
124   }
125   wh = GNUNET_BIO_write_open (fn);
126   if (NULL == wh)
127   {
128     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
129                 _("Could not open `%s'.\n"),
130                 fn);
131     GNUNET_free (fn);
132     return;
133   }
134   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
135     if ((GNUNET_OK !=
136          GNUNET_BIO_write (wh,
137                            &pos->file_id,
138                            sizeof (struct GNUNET_HashCode))) ||
139         (GNUNET_OK !=
140          GNUNET_BIO_write_string (wh,
141                                   pos->filename)))
142       break;
143   if (GNUNET_OK != GNUNET_BIO_write_close (wh))
144   {
145     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
146                 _("Error writing `%s'.\n"),
147                 fn);
148     GNUNET_free (fn);
149     return;
150   }
151   GNUNET_free (fn);
152 }
153
154
155 /**
156  * Read index information from disk.
157  */
158 static void
159 read_index_list ()
160 {
161   struct GNUNET_BIO_ReadHandle *rh;
162   char *fn;
163   struct IndexInfo *pos;
164   char *fname;
165   struct GNUNET_HashCode hc;
166   size_t slen;
167   char *emsg;
168
169   if (GNUNET_OK !=
170       GNUNET_CONFIGURATION_get_value_filename (cfg,
171                                                "FS",
172                                                "INDEXDB",
173                                                &fn))
174   {
175     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
176                                "fs",
177                                "INDEXDB");
178     return;
179   }
180   if (GNUNET_NO == GNUNET_DISK_file_test (fn))
181   {
182     /* no index info yet */
183     GNUNET_free (fn);
184     return;
185   }
186   rh = GNUNET_BIO_read_open (fn);
187   if (NULL == rh)
188   {
189     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
190                 _("Could not open `%s'.\n"),
191                 fn);
192     GNUNET_free (fn);
193     return;
194   }
195   while ( (GNUNET_OK ==
196            GNUNET_BIO_read (rh,
197                             "Hash of indexed file",
198                             &hc,
199                             sizeof (struct GNUNET_HashCode))) &&
200           (GNUNET_OK ==
201            GNUNET_BIO_read_string (rh,
202                                    "Name of indexed file",
203                                    &fname,
204                                    1024 * 16)) &&
205           (fname != NULL) )
206   {
207     slen = strlen (fname) + 1;
208     pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
209     pos->file_id = hc;
210     pos->filename = (const char *) &pos[1];
211     GNUNET_memcpy (&pos[1], fname, slen);
212     if (GNUNET_SYSERR ==
213         GNUNET_CONTAINER_multihashmap_put (ifm, &pos->file_id, pos,
214                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
215     {
216       GNUNET_free (pos);
217     }
218     else
219     {
220       GNUNET_CONTAINER_DLL_insert (indexed_files_head,
221                                    indexed_files_tail,
222                                    pos);
223     }
224     GNUNET_free (fname);
225   }
226   if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg))
227     GNUNET_free (emsg);
228   GNUNET_free (fn);
229 }
230
231
232 /**
233  * Continuation called from datastore's remove
234  * function.
235  *
236  * @param cls unused
237  * @param success did the deletion work?
238  * @param min_expiration minimum expiration time required for content to be stored
239  * @param msg error message
240  */
241 static void
242 remove_cont (void *cls, int success,
243              struct GNUNET_TIME_Absolute min_expiration,
244              const char *msg)
245 {
246   if (GNUNET_OK != success)
247     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
248                 _("Failed to delete bogus block: %s\n"), msg);
249 }
250
251
252 /**
253  * We've received an on-demand encoded block from the datastore.
254  * Attempt to do on-demand encoding and (if successful), call the
255  * continuation with the resulting block.  On error, clean up and ask
256  * the datastore for more results.
257  *
258  * @param key key for the content
259  * @param size number of bytes in data
260  * @param data content stored
261  * @param type type of the content
262  * @param priority priority of the content
263  * @param anonymity anonymity-level for the content
264  * @param replication replication-level for the content
265  * @param expiration expiration time for the content
266  * @param uid unique identifier for the datum;
267  *        maybe 0 if no unique identifier is available
268  * @param cont function to call with the actual block (at most once, on success)
269  * @param cont_cls closure for cont
270  * @return GNUNET_OK on success
271  */
272 int
273 GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode * key,
274                                   uint32_t size,
275                                   const void *data,
276                                   enum GNUNET_BLOCK_Type type,
277                                   uint32_t priority,
278                                   uint32_t anonymity,
279                                   uint32_t replication,
280                                   struct GNUNET_TIME_Absolute expiration,
281                                   uint64_t uid,
282                                   GNUNET_DATASTORE_DatumProcessor cont,
283                                   void *cont_cls)
284 {
285   const struct OnDemandBlock *odb;
286   struct GNUNET_HashCode nkey;
287   struct GNUNET_CRYPTO_SymmetricSessionKey skey;
288   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
289   struct GNUNET_HashCode query;
290   ssize_t nsize;
291   char ndata[DBLOCK_SIZE];
292   char edata[DBLOCK_SIZE];
293   const char *fn;
294   struct GNUNET_DISK_FileHandle *fh;
295   uint64_t off;
296   struct IndexInfo *ii;
297
298   if (size != sizeof (struct OnDemandBlock))
299   {
300     GNUNET_break (0);
301     GNUNET_DATASTORE_remove (dsh,
302                              key,
303                              size,
304                              data,
305                              -1,
306                              -1,
307                              &remove_cont, NULL);
308     return GNUNET_SYSERR;
309   }
310   odb = (const struct OnDemandBlock *) data;
311   off = GNUNET_ntohll (odb->offset);
312   ii = GNUNET_CONTAINER_multihashmap_get (ifm,
313                                           &odb->file_id);
314   if (NULL == ii)
315   {
316     GNUNET_break (0);
317     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
318                 "Failed to find index %s\n",
319                 GNUNET_h2s (&odb->file_id));
320     return GNUNET_SYSERR;
321   }
322   fn = ii->filename;
323   if ((NULL == fn) || (0 != ACCESS (fn, R_OK)))
324   {
325     GNUNET_STATISTICS_update (GSF_stats,
326                               gettext_noop ("# index blocks removed: original file inaccessible"),
327                               1,
328                               GNUNET_YES);
329     GNUNET_DATASTORE_remove (dsh,
330                              key,
331                              size,
332                              data,
333                              -1,
334                              -1,
335                              &remove_cont,
336                              NULL);
337     return GNUNET_SYSERR;
338   }
339   if ( (NULL ==
340         (fh =
341          GNUNET_DISK_file_open (fn,
342                                 GNUNET_DISK_OPEN_READ,
343                                 GNUNET_DISK_PERM_NONE))) ||
344        (off != GNUNET_DISK_file_seek (fh,
345                                       off,
346                                       GNUNET_DISK_SEEK_SET)) ||
347       (-1 == (nsize = GNUNET_DISK_file_read (fh,
348                                              ndata,
349                                              sizeof (ndata)))) )
350   {
351     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
352                 _("Could not access indexed file `%s' (%s) at offset %llu: %s\n"),
353                 GNUNET_h2s (&odb->file_id),
354                 fn,
355                 (unsigned long long) off,
356                 (fn == NULL) ? _("not indexed") : STRERROR (errno));
357     if (fh != NULL)
358       GNUNET_DISK_file_close (fh);
359     GNUNET_DATASTORE_remove (dsh,
360                              key,
361                              size,
362                              data,
363                              -1,
364                              -1,
365                              &remove_cont,
366                              NULL);
367     return GNUNET_SYSERR;
368   }
369   GNUNET_DISK_file_close (fh);
370   GNUNET_CRYPTO_hash (ndata,
371                       nsize,
372                       &nkey);
373   GNUNET_CRYPTO_hash_to_aes_key (&nkey,
374                                  &skey,
375                                  &iv);
376   GNUNET_CRYPTO_symmetric_encrypt (ndata,
377                                    nsize,
378                                    &skey,
379                                    &iv,
380                                    edata);
381   GNUNET_CRYPTO_hash (edata,
382                       nsize,
383                       &query);
384   if (0 != memcmp (&query,
385                    key,
386                    sizeof (struct GNUNET_HashCode)))
387   {
388     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
389                 _("Indexed file `%s' changed at offset %llu\n"),
390                 fn,
391                 (unsigned long long) off);
392     GNUNET_DATASTORE_remove (dsh,
393                              key,
394                              size,
395                              data,
396                              -1,
397                              -1,
398                              &remove_cont,
399                              NULL);
400     return GNUNET_SYSERR;
401   }
402   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
403               "On-demand encoded block for query `%s'\n",
404               GNUNET_h2s (key));
405   cont (cont_cls,
406         key,
407         nsize,
408         edata,
409         GNUNET_BLOCK_TYPE_FS_DBLOCK,
410         priority,
411         anonymity,
412         replication,
413         expiration,
414         uid);
415   return GNUNET_OK;
416 }
417
418
419 /**
420  * Transmit information about indexed files to @a mq.
421  *
422  * @param mq message queue to send information to
423  */
424 void
425 GNUNET_FS_indexing_send_list (struct GNUNET_MQ_Handle *mq)
426 {
427   struct GNUNET_MQ_Envelope *env;
428   struct IndexInfoMessage *iim;
429   struct GNUNET_MessageHeader *iem;
430   size_t slen;
431   const char *fn;
432   struct IndexInfo *pos;
433
434   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
435   {
436     fn = pos->filename;
437     slen = strlen (fn) + 1;
438     if (slen + sizeof (struct IndexInfoMessage) >=
439         GNUNET_MAX_MESSAGE_SIZE)
440     {
441       GNUNET_break (0);
442       break;
443     }
444     env = GNUNET_MQ_msg_extra (iim,
445                                slen,
446                                GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
447     iim->reserved = 0;
448     iim->file_id = pos->file_id;
449     GNUNET_memcpy (&iim[1],
450                    fn,
451                    slen);
452     GNUNET_MQ_send (mq,
453                     env);
454   }
455   env = GNUNET_MQ_msg (iem,
456                        GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
457   GNUNET_MQ_send (mq,
458                   env);
459 }
460
461
462 /**
463  * Remove a file from the index.
464  *
465  * @param fid identifier of the file to remove
466  * @return #GNUNET_YES if the @a fid was found
467  */
468 int
469 GNUNET_FS_indexing_do_unindex (const struct GNUNET_HashCode *fid)
470 {
471   struct IndexInfo *pos;
472
473   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
474   {
475     if (0 == memcmp (&pos->file_id,
476                      fid,
477                      sizeof (struct GNUNET_HashCode)))
478     {
479       GNUNET_CONTAINER_DLL_remove (indexed_files_head,
480                                    indexed_files_tail,
481                                    pos);
482       GNUNET_break (GNUNET_OK ==
483                     GNUNET_CONTAINER_multihashmap_remove (ifm,
484                                                           &pos->file_id,
485                                                           pos));
486       GNUNET_free (pos);
487       write_index_list ();
488       return GNUNET_YES;
489     }
490   }
491   return GNUNET_NO;
492 }
493
494
495 /**
496  * Add the given file to the list of indexed files.
497  *
498  * @param filename name of the file
499  * @param file_id hash identifier for @a filename
500  */
501 void
502 GNUNET_FS_add_to_index (const char *filename,
503                         const struct GNUNET_HashCode *file_id)
504 {
505   struct IndexInfo *ii;
506   size_t slen;
507
508   ii = GNUNET_CONTAINER_multihashmap_get (ifm,
509                                           file_id);
510   if (NULL != ii)
511   {
512     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
513                 _("Index request received for file `%s' is already indexed as `%s'.  Permitting anyway.\n"),
514                 filename,
515                 ii->filename);
516     return;
517   }
518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
519               "Adding file %s to index as %s\n",
520               filename,
521               GNUNET_h2s (file_id));
522   slen = strlen (filename) + 1;
523   ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
524   ii->file_id = *file_id;
525   ii->filename = (const char *) &ii[1];
526   GNUNET_memcpy (&ii[1],
527                  filename,
528                  slen);
529   GNUNET_CONTAINER_DLL_insert (indexed_files_head,
530                                indexed_files_tail,
531                                ii);
532   GNUNET_assert (GNUNET_OK ==
533                  GNUNET_CONTAINER_multihashmap_put (ifm,
534                                                     &ii->file_id,
535                                                     ii,
536                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
537   write_index_list ();
538 }
539
540
541 /**
542  * Shutdown the module.
543  */
544 void
545 GNUNET_FS_indexing_done ()
546 {
547   struct IndexInfo *pos;
548
549   while (NULL != (pos = indexed_files_head))
550   {
551     GNUNET_CONTAINER_DLL_remove (indexed_files_head,
552                                  indexed_files_tail,
553                                  pos);
554     if (pos->fhc != NULL)
555       GNUNET_CRYPTO_hash_file_cancel (pos->fhc);
556     GNUNET_break (GNUNET_OK ==
557                   GNUNET_CONTAINER_multihashmap_remove (ifm,
558                                                         &pos->file_id,
559                                                         pos));
560     GNUNET_free (pos);
561   }
562   GNUNET_CONTAINER_multihashmap_destroy (ifm);
563   ifm = NULL;
564   cfg = NULL;
565 }
566
567
568 /**
569  * Initialize the indexing submodule.
570  *
571  * @param c configuration to use
572  * @param d datastore to use
573  */
574 int
575 GNUNET_FS_indexing_init (const struct GNUNET_CONFIGURATION_Handle *c,
576                          struct GNUNET_DATASTORE_Handle *d)
577 {
578   cfg = c;
579   dsh = d;
580   ifm = GNUNET_CONTAINER_multihashmap_create (128,
581                                               GNUNET_YES);
582   read_index_list ();
583   return GNUNET_OK;
584 }
585
586 /* end of gnunet-service-fs_indexing.c */