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