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