f6fd3f664e21ecd7b4387face8b0ccc3898e01f4
[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_drq.h"
38 #include "gnunet-service-fs_indexing.h"
39 #include "fs.h"
40
41 #define DEBUG_FS GNUNET_YES
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 static 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   mydev = 0;
358   myino = 0;
359   if ( ( (dev != 0) ||
360          (ino != 0) ) &&
361        (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
362                                                        &mydev,
363                                                        &myino)) &&
364        ( (dev == mydev) &&
365          (ino == myino) ) )
366     {      
367       /* fast validation OK! */
368       signal_index_ok (ii);
369       return;
370     }
371 #if DEBUG_FS
372   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
373               "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n",
374               (unsigned long long) ino,
375               (unsigned long long) myino,
376               (unsigned int) dev,
377               (unsigned int) mydev);
378 #endif
379   /* slow validation, need to hash full file (again) */
380   GNUNET_CRYPTO_hash_file (sched,
381                            GNUNET_SCHEDULER_PRIORITY_IDLE,
382                            fn,
383                            HASHING_BLOCKSIZE,
384                            &hash_for_index_val,
385                            ii);
386 }
387
388
389 /**
390  * Handle INDEX_LIST_GET-message.
391  *
392  * @param cls closure
393  * @param client identification of the client
394  * @param message the actual message
395  */
396 void
397 GNUNET_FS_handle_index_list_get (void *cls,
398                                  struct GNUNET_SERVER_Client *client,
399                                  const struct GNUNET_MessageHeader *message)
400 {
401   struct GNUNET_SERVER_TransmitContext *tc;
402   struct IndexInfoMessage *iim;
403   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
404   size_t slen;
405   const char *fn;
406   struct IndexInfo *pos;
407
408   tc = GNUNET_SERVER_transmit_context_create (client);
409   iim = (struct IndexInfoMessage*) buf;
410   pos = indexed_files;
411   while (NULL != pos)
412     {
413       fn = pos->filename;
414       slen = strlen (fn) + 1;
415       if (slen + sizeof (struct IndexInfoMessage) > 
416           GNUNET_SERVER_MAX_MESSAGE_SIZE)
417         {
418           GNUNET_break (0);
419           break;
420         }
421       iim->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
422       iim->header.size = htons (slen + sizeof (struct IndexInfoMessage));
423       iim->reserved = 0;
424       iim->file_id = pos->file_id;
425       memcpy (&iim[1], fn, slen);
426       GNUNET_SERVER_transmit_context_append_message (tc,
427                                                      &iim->header);
428       pos = pos->next;
429     }
430   GNUNET_SERVER_transmit_context_append_data (tc,
431                                               NULL, 0,
432                                               GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
433   GNUNET_SERVER_transmit_context_run (tc,
434                                       GNUNET_TIME_UNIT_MINUTES);
435 }
436
437
438 /**
439  * Handle UNINDEX-message.
440  *
441  * @param cls closure
442  * @param client identification of the client
443  * @param message the actual message
444  */
445 void
446 GNUNET_FS_handle_unindex (void *cls,
447                           struct GNUNET_SERVER_Client *client,
448                           const struct GNUNET_MessageHeader *message)
449 {
450   const struct UnindexMessage *um;
451   struct IndexInfo *pos;
452   struct IndexInfo *prev;
453   struct IndexInfo *next;
454   struct GNUNET_SERVER_TransmitContext *tc;
455   int found;
456   
457   um = (const struct UnindexMessage*) message;
458   found = GNUNET_NO;
459   prev = NULL;
460   pos = indexed_files;
461   while (NULL != pos)
462     {
463       next = pos->next;
464       if (0 == memcmp (&pos->file_id,
465                        &um->file_id,
466                        sizeof (GNUNET_HashCode)))
467         {
468           if (prev == NULL)
469             indexed_files = next;
470           else
471             prev->next = next;
472           GNUNET_free (pos);
473           found = GNUNET_YES;
474         }
475       else
476         {
477           prev = pos;
478         }
479       pos = next;
480     }
481 #if DEBUG_FS
482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
483               "Client requested unindexing of file `%s': %s\n",
484               GNUNET_h2s (&um->file_id),
485               found ? "found" : "not found");
486 #endif
487   if (GNUNET_YES == found)    
488     write_index_list ();
489   tc = GNUNET_SERVER_transmit_context_create (client);
490   GNUNET_SERVER_transmit_context_append_data (tc,
491                                               NULL, 0,
492                                               GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
493   GNUNET_SERVER_transmit_context_run (tc,
494                                       GNUNET_TIME_UNIT_MINUTES);
495 }
496
497
498
499
500 /**
501  * Continuation called from datastore's remove
502  * function.
503  *
504  * @param cls unused
505  * @param success did the deletion work?
506  * @param msg error message
507  */
508 static void
509 remove_cont (void *cls,
510              int success,
511              const char *msg)
512 {
513   if (GNUNET_OK != success)
514     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
515                 _("Failed to delete bogus block: %s\n"),
516                 msg);
517 }
518
519
520 /**
521  * We've received an on-demand encoded block from the datastore.
522  * Attempt to do on-demand encoding and (if successful), call the
523  * continuation with the resulting block.  On error, clean up and ask
524  * the datastore for more results.
525  *
526  * @param key key for the content
527  * @param size number of bytes in data
528  * @param data content stored
529  * @param type type of the content
530  * @param priority priority of the content
531  * @param anonymity anonymity-level for the content
532  * @param expiration expiration time for the content
533  * @param uid unique identifier for the datum;
534  *        maybe 0 if no unique identifier is available
535  * @param cont function to call with the actual block (at most once, on success)
536  * @param cont_cls closure for cont
537  * @return GNUNET_OK on success
538  */
539 int
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                                   GNUNET_DATASTORE_Iterator cont,
549                                   void *cont_cls)
550 {
551   const struct OnDemandBlock *odb;
552   GNUNET_HashCode nkey;
553   struct GNUNET_CRYPTO_AesSessionKey skey;
554   struct GNUNET_CRYPTO_AesInitializationVector iv;
555   GNUNET_HashCode query;
556   ssize_t nsize;
557   char ndata[DBLOCK_SIZE];
558   char edata[DBLOCK_SIZE];
559   const char *fn;
560   struct GNUNET_DISK_FileHandle *fh;
561   uint64_t off;
562
563   if (size != sizeof (struct OnDemandBlock))
564     {
565       GNUNET_break (0);
566       GNUNET_FS_drq_remove (key,
567                             size,
568                             data,
569                             &remove_cont,
570                             NULL,
571                             GNUNET_TIME_UNIT_FOREVER_REL);
572       return GNUNET_SYSERR;
573     }
574   odb = (const struct OnDemandBlock*) data;
575   off = GNUNET_ntohll (odb->offset);
576   fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
577                                                         &odb->file_id);
578   fh = NULL;
579   if ( (NULL == fn) ||
580        (NULL == (fh = GNUNET_DISK_file_open (fn, 
581                                              GNUNET_DISK_OPEN_READ,
582                                              GNUNET_DISK_PERM_NONE))) ||
583        (off !=
584         GNUNET_DISK_file_seek (fh,
585                                off,
586                                GNUNET_DISK_SEEK_SET)) ||
587        (-1 ==
588         (nsize = GNUNET_DISK_file_read (fh,
589                                         ndata,
590                                         sizeof (ndata)))) )
591     {
592       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
593                   _("Could not access indexed file `%s' at offset %llu: %s\n"),
594                   GNUNET_h2s (&odb->file_id),
595                   (unsigned long long) off,
596                   STRERROR (errno));
597       if (fh != NULL)
598         GNUNET_DISK_file_close (fh);
599       /* FIXME: if this happens often, we need
600          to remove the OnDemand block from the DS! */
601       return GNUNET_SYSERR;
602     }
603   GNUNET_DISK_file_close (fh);
604   GNUNET_CRYPTO_hash (ndata,
605                       nsize,
606                       &nkey);
607   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
608   GNUNET_CRYPTO_aes_encrypt (ndata,
609                              nsize,
610                              &skey,
611                              &iv,
612                              edata);
613   GNUNET_CRYPTO_hash (edata,
614                       nsize,
615                       &query);
616   if (0 != memcmp (&query, 
617                    key,
618                    sizeof (GNUNET_HashCode)))
619     {
620       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
621                   _("Indexed file `%s' changed at offset %llu\n"),
622                   fn,
623                   (unsigned long long) off);
624       /* FIXME: if this happens often, we need
625          to remove the OnDemand block from the DS! */
626       return GNUNET_SYSERR;
627     }
628 #if DEBUG_FS
629       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
630                   "On-demand encoded block for query `%s'\n",
631                   GNUNET_h2s (key));
632 #endif  
633   cont (cont_cls,
634         key,
635         nsize,
636         edata,
637         GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
638         priority,
639         anonymity,
640         expiration,
641         uid);
642   return GNUNET_OK;
643 }
644
645
646 /**
647  * Task run during shutdown.
648  *
649  * @param cls unused
650  * @param tc unused
651  */
652 static void
653 shutdown_task (void *cls,
654                const struct GNUNET_SCHEDULER_TaskContext *tc)
655 {
656   struct IndexInfo *pos;  
657
658   GNUNET_CONTAINER_multihashmap_destroy (ifm);
659   ifm = NULL;
660   while (NULL != (pos = indexed_files))
661     {
662       indexed_files = pos->next;
663       GNUNET_free (pos);
664     }
665   sched = NULL;
666   cfg = NULL;
667 }
668
669
670 /**
671  * Initialize the indexing submodule.
672  *
673  * @param s scheduler to use
674  * @param c configuration to use
675  */
676 int
677 GNUNET_FS_indexing_init (struct GNUNET_SCHEDULER_Handle *s,
678                          const struct GNUNET_CONFIGURATION_Handle *c)
679 {
680   sched = s;
681   cfg = c;
682   ifm = GNUNET_CONTAINER_multihashmap_create (128);
683   GNUNET_SCHEDULER_add_delayed (sched,
684                                 GNUNET_TIME_UNIT_FOREVER_REL,
685                                 &shutdown_task,
686                                 NULL);
687   read_index_list ();
688   return GNUNET_OK;
689 }
690
691 /* end of gnunet-service-fs_indexing.c */