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