ebd7114d30a51782c7d82eb83f084dab9b3b9f3c
[oweals/gnunet.git] / src / fs / gnunet-service-fs_indexing.c
1 /*
2      This file is part of GNUnet.
3      (C) 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/gnunet-service-fs_indexing.c
23  * @brief program that provides indexing functions of the file-sharing service
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - indexed files/blocks not removed on errors
28  */
29 #include "platform.h"
30 #include <float.h>
31 #include "gnunet_core_service.h"
32 #include "gnunet_datastore_service.h"
33 #include "gnunet_peer_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_signatures.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet-service-fs_indexing.h"
38 #include "fs.h"
39
40 #define DEBUG_FS GNUNET_NO
41
42
43 /**
44  * In-memory information about indexed files (also available
45  * on-disk).
46  */
47 struct IndexInfo
48 {
49   
50   /**
51    * This is a linked list.
52    */
53   struct IndexInfo *next;
54
55   /**
56    * Name of the indexed file.  Memory allocated
57    * at the end of this struct (do not free).
58    */
59   const char *filename;
60
61   /**
62    * Context for transmitting confirmation to client,
63    * NULL if we've done this already.
64    */
65   struct GNUNET_SERVER_TransmitContext *tc;
66   
67   /**
68    * Hash of the contents of the file.
69    */
70   GNUNET_HashCode file_id;
71
72 };
73
74
75 /**
76  * Linked list of indexed files.
77  */
78 static struct IndexInfo *indexed_files;
79
80 /**
81  * Maps hash over content of indexed files to the respective filename.
82  * The filenames are pointers into the indexed_files linked list and
83  * do not need to be freed.
84  */
85 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
86
87 /**
88  * Our scheduler.
89  */
90 static struct GNUNET_SCHEDULER_Handle *sched;
91
92 /**
93  * Our configuration.
94  */
95 const struct GNUNET_CONFIGURATION_Handle *cfg;
96
97
98 /**
99  * Write the current index information list to disk.
100  */ 
101 static void
102 write_index_list ()
103 {
104   struct GNUNET_BIO_WriteHandle *wh;
105   char *fn;
106   struct IndexInfo *pos;  
107
108   if (GNUNET_OK !=
109       GNUNET_CONFIGURATION_get_value_filename (cfg,
110                                                "FS",
111                                                "INDEXDB",
112                                                &fn))
113     {
114       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
115                   _("Configuration option `%s' in section `%s' missing.\n"),
116                   "INDEXDB",
117                   "FS");
118       return;
119     }
120   wh = GNUNET_BIO_write_open (fn);
121   if (NULL == wh)
122     {
123       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
124                   _("Could not open `%s'.\n"),
125                   fn);
126       GNUNET_free (fn);
127       return;
128     }
129   pos = indexed_files;
130   while (pos != NULL)
131     {
132       if ( (GNUNET_OK !=
133             GNUNET_BIO_write (wh,
134                               &pos->file_id,
135                               sizeof (GNUNET_HashCode))) ||
136            (GNUNET_OK !=
137             GNUNET_BIO_write_string (wh,
138                                      pos->filename)) )
139         break;
140       pos = pos->next;
141     }
142   if (GNUNET_OK != 
143       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   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 (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
176                   _("Configuration option `%s' in section `%s' missing.\n"),
177                   "INDEXDB",
178                   "FS");
179       return;
180     }
181   if (GNUNET_NO == GNUNET_DISK_file_test (fn))
182     {
183       /* no index info  yet */
184       GNUNET_free (fn);
185       return;
186     }
187   rh = GNUNET_BIO_read_open (fn);
188   if (NULL == rh)
189     {
190       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
191                   _("Could not open `%s'.\n"),
192                   fn);
193       GNUNET_free (fn);
194       return;
195     }
196
197   while ( (GNUNET_OK ==
198            GNUNET_BIO_read (rh,
199                             "Hash of indexed file",
200                             &hc,
201                             sizeof (GNUNET_HashCode))) &&
202           (GNUNET_OK ==
203            GNUNET_BIO_read_string (rh, 
204                                    "Name of indexed file",
205                                    &fname,
206                                    1024 * 16)) )
207     {
208       slen = strlen (fname) + 1;
209       pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
210       pos->file_id = hc;
211       pos->filename = (const char *) &pos[1];
212       memcpy (&pos[1], fname, slen);
213       if (GNUNET_SYSERR ==
214           GNUNET_CONTAINER_multihashmap_put (ifm,
215                                              &hc,
216                                              (void*) pos->filename,
217                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
218         {
219           GNUNET_free (pos);
220         }
221       else
222         {
223           pos->next = indexed_files;
224           indexed_files = pos;
225         }
226       GNUNET_free (fname);
227     }
228   if (GNUNET_OK != 
229       GNUNET_BIO_read_close (rh, &emsg))
230     GNUNET_free (emsg);
231   GNUNET_free (fn);
232 }
233
234
235 /**
236  * We've validated the hash of the file we're about to index.  Signal
237  * success to the client and update our internal data structures.
238  *
239  * @param ii the index info entry for the request
240  */
241 static void
242 signal_index_ok (struct IndexInfo *ii)
243 {
244   if (GNUNET_SYSERR ==
245       GNUNET_CONTAINER_multihashmap_put (ifm,
246                                          &ii->file_id,
247                                          (void*) ii->filename,
248                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
249     {
250       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
251                   _("Index request received for file `%s' is indexed as `%s'.  Permitting anyway.\n"),
252                   ii->filename,
253                   (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
254                                                                    &ii->file_id));
255       GNUNET_SERVER_transmit_context_append_data (ii->tc,
256                                                   NULL, 0,
257                                                   GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
258       GNUNET_SERVER_transmit_context_run (ii->tc,
259                                           GNUNET_TIME_UNIT_MINUTES);
260       GNUNET_free (ii);
261       return;
262     }
263   ii->next = indexed_files;
264   indexed_files = ii;
265   write_index_list ();
266   GNUNET_SERVER_transmit_context_append_data (ii->tc,
267                                               NULL, 0,
268                                               GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
269   GNUNET_SERVER_transmit_context_run (ii->tc,
270                                       GNUNET_TIME_UNIT_MINUTES);
271   ii->tc = NULL;
272 }
273
274
275 /**
276  * Function called once the hash computation over an
277  * indexed file has completed.
278  *
279  * @param cls closure, our publishing context
280  * @param res resulting hash, NULL on error
281  */
282 static void 
283 hash_for_index_val (void *cls,
284                     const GNUNET_HashCode *
285                     res)
286 {
287   struct IndexInfo *ii = cls;
288   
289   if ( (res == NULL) ||
290        (0 != memcmp (res,
291                      &ii->file_id,
292                      sizeof(GNUNET_HashCode))) )
293     {
294       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
295                   _("Hash mismatch trying to index file `%s' which has hash `%s'\n"),
296                   ii->filename,
297                   GNUNET_h2s (res));
298 #if DEBUG_FS
299       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
300                   "Wanted `%s'\n",
301                   GNUNET_h2s (&ii->file_id));
302 #endif
303       GNUNET_SERVER_transmit_context_append_data (ii->tc,
304                                                   NULL, 0,
305                                                   GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED);
306       GNUNET_SERVER_transmit_context_run (ii->tc,
307                                           GNUNET_TIME_UNIT_MINUTES);
308       GNUNET_free (ii);
309       return;
310     }
311   signal_index_ok (ii);
312 }
313
314
315 /**
316  * Handle INDEX_START-message.
317  *
318  * @param cls closure
319  * @param client identification of the client
320  * @param message the actual message
321  */
322 void
323 GNUNET_FS_handle_index_start (void *cls,
324                               struct GNUNET_SERVER_Client *client,
325                               const struct GNUNET_MessageHeader *message)
326 {
327   const struct IndexStartMessage *ism;
328   const char *fn;
329   uint16_t msize;
330   struct IndexInfo *ii;
331   size_t slen;
332   uint32_t dev;
333   uint64_t ino;
334   uint32_t mydev;
335   uint64_t myino;
336
337   msize = ntohs(message->size);
338   if ( (msize <= sizeof (struct IndexStartMessage)) ||
339        ( ((const char *)message)[msize-1] != '\0') )
340     {
341       GNUNET_break (0);
342       GNUNET_SERVER_receive_done (client,
343                                   GNUNET_SYSERR);
344       return;
345     }
346   ism = (const struct IndexStartMessage*) message;
347   fn = (const char*) &ism[1];
348   dev = ntohl (ism->device);
349   ino = GNUNET_ntohll (ism->inode);
350   ism = (const struct IndexStartMessage*) message;
351   slen = strlen (fn) + 1;
352   ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
353   ii->filename = (const char*) &ii[1];
354   memcpy (&ii[1], fn, slen);
355   ii->file_id = ism->file_id;  
356   ii->tc = GNUNET_SERVER_transmit_context_create (client);
357   if ( ( (dev != 0) ||
358          (ino != 0) ) &&
359        (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
360                                                        &mydev,
361                                                        &myino)) &&
362        ( (dev == mydev) &&
363          (ino == myino) ) )
364     {      
365       /* fast validation OK! */
366       signal_index_ok (ii);
367       return;
368     }
369 #if DEBUG_FS
370   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
371               "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n",
372               (unsigned long long) ino,
373               (unsigned long long) myino,
374               (unsigned int) dev,
375               (unsigned int) mydev);
376 #endif
377   /* slow validation, need to hash full file (again) */
378   GNUNET_CRYPTO_hash_file (sched,
379                            GNUNET_SCHEDULER_PRIORITY_IDLE,
380                            fn,
381                            HASHING_BLOCKSIZE,
382                            &hash_for_index_val,
383                            ii);
384 }
385
386
387 /**
388  * Handle INDEX_LIST_GET-message.
389  *
390  * @param cls closure
391  * @param client identification of the client
392  * @param message the actual message
393  */
394 void
395 GNUNET_FS_handle_index_list_get (void *cls,
396                                  struct GNUNET_SERVER_Client *client,
397                                  const struct GNUNET_MessageHeader *message)
398 {
399   struct GNUNET_SERVER_TransmitContext *tc;
400   struct IndexInfoMessage *iim;
401   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
402   size_t slen;
403   const char *fn;
404   struct IndexInfo *pos;
405
406   tc = GNUNET_SERVER_transmit_context_create (client);
407   iim = (struct IndexInfoMessage*) buf;
408   pos = indexed_files;
409   while (NULL != pos)
410     {
411       fn = pos->filename;
412       slen = strlen (fn) + 1;
413       if (slen + sizeof (struct IndexInfoMessage) > 
414           GNUNET_SERVER_MAX_MESSAGE_SIZE)
415         {
416           GNUNET_break (0);
417           break;
418         }
419       iim->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
420       iim->header.size = htons (slen + sizeof (struct IndexInfoMessage));
421       iim->reserved = 0;
422       iim->file_id = pos->file_id;
423       memcpy (&iim[1], fn, slen);
424       GNUNET_SERVER_transmit_context_append_message (tc,
425                                                      &iim->header);
426       pos = pos->next;
427     }
428   GNUNET_SERVER_transmit_context_append_data (tc,
429                                               NULL, 0,
430                                               GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
431   GNUNET_SERVER_transmit_context_run (tc,
432                                       GNUNET_TIME_UNIT_MINUTES);
433 }
434
435
436 /**
437  * Handle UNINDEX-message.
438  *
439  * @param cls closure
440  * @param client identification of the client
441  * @param message the actual message
442  */
443 void
444 GNUNET_FS_handle_unindex (void *cls,
445                           struct GNUNET_SERVER_Client *client,
446                           const struct GNUNET_MessageHeader *message)
447 {
448   const struct UnindexMessage *um;
449   struct IndexInfo *pos;
450   struct IndexInfo *prev;
451   struct IndexInfo *next;
452   struct GNUNET_SERVER_TransmitContext *tc;
453   int found;
454   
455   um = (const struct UnindexMessage*) message;
456   found = GNUNET_NO;
457   prev = NULL;
458   pos = indexed_files;
459   while (NULL != pos)
460     {
461       next = pos->next;
462       if (0 == memcmp (&pos->file_id,
463                        &um->file_id,
464                        sizeof (GNUNET_HashCode)))
465         {
466           if (prev == NULL)
467             indexed_files = next;
468           else
469             prev->next = next;
470           GNUNET_free (pos);
471           found = GNUNET_YES;
472         }
473       else
474         {
475           prev = pos;
476         }
477       pos = next;
478     }
479 #if DEBUG_FS
480   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
481               "Client requested unindexing of file `%s': %s\n",
482               GNUNET_h2s (&um->file_id),
483               found ? "found" : "not found");
484 #endif
485   if (GNUNET_YES == found)    
486     write_index_list ();
487   tc = GNUNET_SERVER_transmit_context_create (client);
488   GNUNET_SERVER_transmit_context_append_data (tc,
489                                               NULL, 0,
490                                               GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
491   GNUNET_SERVER_transmit_context_run (tc,
492                                       GNUNET_TIME_UNIT_MINUTES);
493 }
494
495
496
497
498 /**
499  * Continuation called from datastore's remove
500  * function.
501  *
502  * @param cls unused
503  * @param success did the deletion work?
504  * @param msg error message
505  */
506 static void
507 remove_cont (void *cls,
508              int success,
509              const char *msg)
510 {
511   struct GNUNET_DATASTORE_Handle *dsh = cls;
512
513   if (GNUNET_OK != success)
514     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
515                 _("Failed to delete bogus block: %s\n"),
516                 msg);
517   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
518 }
519
520
521 /**
522  * We've received an on-demand encoded block from the datastore.
523  * Attempt to do on-demand encoding and (if successful), call the
524  * continuation with the resulting block.  On error, clean up and ask
525  * the datastore for more results.
526  *
527  * @param key key for the content
528  * @param size number of bytes in data
529  * @param data content stored
530  * @param type type of the content
531  * @param priority priority of the content
532  * @param anonymity anonymity-level for the content
533  * @param expiration expiration time for the content
534  * @param uid unique identifier for the datum;
535  *        maybe 0 if no unique identifier is available
536  * @param cont function to call with the actual block
537  * @param cont_cls closure for cont
538  */
539 void
540 GNUNET_FS_handle_on_demand_block (const GNUNET_HashCode * key,
541                                   uint32_t size,
542                                   const void *data,
543                                   uint32_t type,
544                                   uint32_t priority,
545                                   uint32_t anonymity,
546                                   struct GNUNET_TIME_Absolute
547                                   expiration, uint64_t uid,
548                                   struct GNUNET_DATASTORE_Handle *dsh,
549                                   GNUNET_DATASTORE_Iterator cont,
550                                   void *cont_cls)
551 {
552   const struct OnDemandBlock *odb;
553   GNUNET_HashCode nkey;
554   struct GNUNET_CRYPTO_AesSessionKey skey;
555   struct GNUNET_CRYPTO_AesInitializationVector iv;
556   GNUNET_HashCode query;
557   ssize_t nsize;
558   char ndata[DBLOCK_SIZE];
559   char edata[DBLOCK_SIZE];
560   const char *fn;
561   struct GNUNET_DISK_FileHandle *fh;
562   uint64_t off;
563
564   if (size != sizeof (struct OnDemandBlock))
565     {
566       GNUNET_break (0);
567       GNUNET_DATASTORE_remove (dsh, 
568                                key,
569                                size,
570                                data,
571                                &remove_cont,
572                                dsh,
573                                GNUNET_TIME_UNIT_FOREVER_REL);     
574       return;
575     }
576   odb = (const struct OnDemandBlock*) data;
577   off = GNUNET_ntohll (odb->offset);
578   fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
579                                                         &odb->file_id);
580   fh = NULL;
581   if ( (NULL == fn) ||
582        (NULL == (fh = GNUNET_DISK_file_open (fn, 
583                                              GNUNET_DISK_OPEN_READ,
584                                              GNUNET_DISK_PERM_NONE))) ||
585        (off !=
586         GNUNET_DISK_file_seek (fh,
587                                off,
588                                GNUNET_DISK_SEEK_SET)) ||
589        (-1 ==
590         (nsize = GNUNET_DISK_file_read (fh,
591                                         ndata,
592                                         sizeof (ndata)))) )
593     {
594       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
595                   _("Could not access indexed file `%s' at offset %llu: %s\n"),
596                   GNUNET_h2s (&odb->file_id),
597                   (unsigned long long) off,
598                   STRERROR (errno));
599       if (fh != NULL)
600         GNUNET_DISK_file_close (fh);
601       /* FIXME: if this happens often, we need
602          to remove the OnDemand block from the DS! */
603       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);        
604       return;
605     }
606   GNUNET_DISK_file_close (fh);
607   GNUNET_CRYPTO_hash (ndata,
608                       nsize,
609                       &nkey);
610   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
611   GNUNET_CRYPTO_aes_encrypt (ndata,
612                              nsize,
613                              &skey,
614                              &iv,
615                              edata);
616   GNUNET_CRYPTO_hash (edata,
617                       nsize,
618                       &query);
619   if (0 != memcmp (&query, 
620                    key,
621                    sizeof (GNUNET_HashCode)))
622     {
623       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
624                   _("Indexed file `%s' changed at offset %llu\n"),
625                   fn,
626                   (unsigned long long) off);
627       /* FIXME: if this happens often, we need
628          to remove the OnDemand block from the DS! */
629       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
630       return;
631     }
632   cont (cont_cls,
633         key,
634         nsize,
635         edata,
636         GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
637         priority,
638         anonymity,
639         expiration,
640         uid);
641 }
642
643
644 /**
645  * Task run during shutdown.
646  *
647  * @param cls unused
648  * @param tc unused
649  */
650 static void
651 shutdown_task (void *cls,
652                const struct GNUNET_SCHEDULER_TaskContext *tc)
653 {
654   struct IndexInfo *pos;  
655
656   GNUNET_CONTAINER_multihashmap_destroy (ifm);
657   ifm = NULL;
658   while (NULL != (pos = indexed_files))
659     {
660       indexed_files = pos->next;
661       GNUNET_free (pos);
662     }
663   sched = NULL;
664   cfg = NULL;
665 }
666
667
668 /**
669  * Initialize the indexing submodule.
670  *
671  * @param s scheduler to use
672  * @param c configuration to use
673  */
674 void
675 GNUNET_FS_init_indexing (struct GNUNET_SCHEDULER_Handle *s,
676                          const struct GNUNET_CONFIGURATION_Handle *c)
677 {
678   sched = s;
679   cfg = c;
680   ifm = GNUNET_CONTAINER_multihashmap_create (128);
681   GNUNET_SCHEDULER_add_delayed (sched,
682                                 GNUNET_TIME_UNIT_FOREVER_REL,
683                                 &shutdown_task,
684                                 NULL);
685   read_index_list ();
686 }
687
688 /* end of gnunet-service-fs_indexing.c */