f8593ffd45e846ed1a9c632b27a56e280a1bc359
[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  * - 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_drq.h"
40 #include "gnunet-service-fs_indexing.h"
41 #include "fs.h"
42
43 #define DEBUG_FS GNUNET_YES
44
45 /**
46  * In-memory information about indexed files (also available
47  * on-disk).
48  */
49 struct IndexInfo
50 {
51   
52   /**
53    * This is a linked list.
54    */
55   struct IndexInfo *next;
56
57   /**
58    * Name of the indexed file.  Memory allocated
59    * at the end of this struct (do not free).
60    */
61   const char *filename;
62
63   /**
64    * Context for transmitting confirmation to client,
65    * NULL if we've done this already.
66    */
67   struct GNUNET_SERVER_TransmitContext *tc;
68
69   /**
70    * Context for hashing of the file.
71    */
72   struct GNUNET_CRYPTO_FileHashContext *fhc;
73   
74   /**
75    * Hash of the contents of the file.
76    */
77   GNUNET_HashCode file_id;
78
79 };
80
81
82 /**
83  * Linked list of indexed files.
84  */
85 static struct IndexInfo *indexed_files;
86
87 /**
88  * Maps hash over content of indexed files to the respective filename.
89  * The filenames are pointers into the indexed_files linked list and
90  * do not need to be freed.
91  */
92 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
93
94 /**
95  * Our scheduler.
96  */
97 static struct GNUNET_SCHEDULER_Handle *sched;
98
99 /**
100  * Our configuration.
101  */
102 static const struct GNUNET_CONFIGURATION_Handle *cfg;
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
204   while ( (GNUNET_OK ==
205            GNUNET_BIO_read (rh,
206                             "Hash of indexed file",
207                             &hc,
208                             sizeof (GNUNET_HashCode))) &&
209           (GNUNET_OK ==
210            GNUNET_BIO_read_string (rh, 
211                                    "Name of indexed file",
212                                    &fname,
213                                    1024 * 16)) )
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   uint32_t dev;
341   uint64_t ino;
342   uint32_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   dev = ntohl (ism->device);
357   ino = GNUNET_ntohll (ism->inode);
358   ism = (const struct IndexStartMessage*) message;
359   slen = strlen (fn) + 1;
360   ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
361   ii->filename = (const char*) &ii[1];
362   memcpy (&ii[1], fn, slen);
363   ii->file_id = ism->file_id;  
364   ii->tc = GNUNET_SERVER_transmit_context_create (client);
365   mydev = 0;
366   myino = 0;
367   if ( ( (dev != 0) ||
368          (ino != 0) ) &&
369        (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
370                                                        &mydev,
371                                                        &myino)) &&
372        ( (dev == mydev) &&
373          (ino == myino) ) )
374     {      
375       /* fast validation OK! */
376       signal_index_ok (ii);
377       GNUNET_free (fn);
378       return;
379     }
380 #if DEBUG_FS
381   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
382               "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n",
383               (unsigned long long) ino,
384               (unsigned long long) myino,
385               (unsigned int) dev,
386               (unsigned int) mydev);
387 #endif
388   /* slow validation, need to hash full file (again) */
389   ii->fhc = GNUNET_CRYPTO_hash_file (sched,
390                                      GNUNET_SCHEDULER_PRIORITY_IDLE,
391                                      fn,
392                                      HASHING_BLOCKSIZE,
393                                      &hash_for_index_val,
394                                      ii);
395   if (ii->fhc == NULL)    
396     hash_for_index_val (ii, NULL);    
397   GNUNET_free (fn);
398 }
399
400
401 /**
402  * Handle INDEX_LIST_GET-message.
403  *
404  * @param cls closure
405  * @param client identification of the client
406  * @param message the actual message
407  */
408 void
409 GNUNET_FS_handle_index_list_get (void *cls,
410                                  struct GNUNET_SERVER_Client *client,
411                                  const struct GNUNET_MessageHeader *message)
412 {
413   struct GNUNET_SERVER_TransmitContext *tc;
414   struct IndexInfoMessage *iim;
415   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
416   size_t slen;
417   const char *fn;
418   struct IndexInfo *pos;
419
420   tc = GNUNET_SERVER_transmit_context_create (client);
421   iim = (struct IndexInfoMessage*) buf;
422   pos = indexed_files;
423   while (NULL != pos)
424     {
425       fn = pos->filename;
426       slen = strlen (fn) + 1;
427       if (slen + sizeof (struct IndexInfoMessage) > 
428           GNUNET_SERVER_MAX_MESSAGE_SIZE)
429         {
430           GNUNET_break (0);
431           break;
432         }
433       iim->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
434       iim->header.size = htons (slen + sizeof (struct IndexInfoMessage));
435       iim->reserved = 0;
436       iim->file_id = pos->file_id;
437       memcpy (&iim[1], fn, slen);
438       GNUNET_SERVER_transmit_context_append_message (tc,
439                                                      &iim->header);
440       pos = pos->next;
441     }
442   GNUNET_SERVER_transmit_context_append_data (tc,
443                                               NULL, 0,
444                                               GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
445   GNUNET_SERVER_transmit_context_run (tc,
446                                       GNUNET_TIME_UNIT_MINUTES);
447 }
448
449
450 /**
451  * Handle UNINDEX-message.
452  *
453  * @param cls closure
454  * @param client identification of the client
455  * @param message the actual message
456  */
457 void
458 GNUNET_FS_handle_unindex (void *cls,
459                           struct GNUNET_SERVER_Client *client,
460                           const struct GNUNET_MessageHeader *message)
461 {
462   const struct UnindexMessage *um;
463   struct IndexInfo *pos;
464   struct IndexInfo *prev;
465   struct IndexInfo *next;
466   struct GNUNET_SERVER_TransmitContext *tc;
467   int found;
468   
469   um = (const struct UnindexMessage*) message;
470   found = GNUNET_NO;
471   prev = NULL;
472   pos = indexed_files;
473   while (NULL != pos)
474     {
475       next = pos->next;
476       if (0 == memcmp (&pos->file_id,
477                        &um->file_id,
478                        sizeof (GNUNET_HashCode)))
479         {
480           if (prev == NULL)
481             indexed_files = next;
482           else
483             prev->next = next;
484           GNUNET_free (pos);
485           found = GNUNET_YES;
486         }
487       else
488         {
489           prev = pos;
490         }
491       pos = next;
492     }
493 #if DEBUG_FS
494   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
495               "Client requested unindexing of file `%s': %s\n",
496               GNUNET_h2s (&um->file_id),
497               found ? "found" : "not found");
498 #endif
499   if (GNUNET_YES == found)    
500     write_index_list ();
501   tc = GNUNET_SERVER_transmit_context_create (client);
502   GNUNET_SERVER_transmit_context_append_data (tc,
503                                               NULL, 0,
504                                               GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
505   GNUNET_SERVER_transmit_context_run (tc,
506                                       GNUNET_TIME_UNIT_MINUTES);
507 }
508
509
510
511
512 /**
513  * Continuation called from datastore's remove
514  * function.
515  *
516  * @param cls unused
517  * @param success did the deletion work?
518  * @param msg error message
519  */
520 static void
521 remove_cont (void *cls,
522              int success,
523              const char *msg)
524 {
525   if (GNUNET_OK != success)
526     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
527                 _("Failed to delete bogus block: %s\n"),
528                 msg);
529 }
530
531
532 /**
533  * We've received an on-demand encoded block from the datastore.
534  * Attempt to do on-demand encoding and (if successful), call the
535  * continuation with the resulting block.  On error, clean up and ask
536  * the datastore for more results.
537  *
538  * @param key key for the content
539  * @param size number of bytes in data
540  * @param data content stored
541  * @param type type of the content
542  * @param priority priority of the content
543  * @param anonymity anonymity-level for the content
544  * @param expiration expiration time for the content
545  * @param uid unique identifier for the datum;
546  *        maybe 0 if no unique identifier is available
547  * @param cont function to call with the actual block (at most once, on success)
548  * @param cont_cls closure for cont
549  * @return GNUNET_OK on success
550  */
551 int
552 GNUNET_FS_handle_on_demand_block (const GNUNET_HashCode * key,
553                                   uint32_t size,
554                                   const void *data,
555                                   enum GNUNET_BLOCK_Type type,
556                                   uint32_t priority,
557                                   uint32_t anonymity,
558                                   struct GNUNET_TIME_Absolute
559                                   expiration, uint64_t uid,
560                                   GNUNET_DATASTORE_Iterator cont,
561                                   void *cont_cls)
562 {
563   const struct OnDemandBlock *odb;
564   GNUNET_HashCode nkey;
565   struct GNUNET_CRYPTO_AesSessionKey skey;
566   struct GNUNET_CRYPTO_AesInitializationVector iv;
567   GNUNET_HashCode query;
568   ssize_t nsize;
569   char ndata[DBLOCK_SIZE];
570   char edata[DBLOCK_SIZE];
571   const char *fn;
572   struct GNUNET_DISK_FileHandle *fh;
573   uint64_t off;
574
575   if (size != sizeof (struct OnDemandBlock))
576     {
577       GNUNET_break (0);
578       GNUNET_FS_drq_remove (key,
579                             size,
580                             data,
581                             &remove_cont,
582                             NULL,
583                             GNUNET_TIME_UNIT_FOREVER_REL);
584       return GNUNET_SYSERR;
585     }
586   odb = (const struct OnDemandBlock*) data;
587   off = GNUNET_ntohll (odb->offset);
588   fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
589                                                         &odb->file_id);
590   fh = NULL;
591   if ( (NULL == fn) ||
592        (NULL == (fh = GNUNET_DISK_file_open (fn, 
593                                              GNUNET_DISK_OPEN_READ,
594                                              GNUNET_DISK_PERM_NONE))) ||
595        (off !=
596         GNUNET_DISK_file_seek (fh,
597                                off,
598                                GNUNET_DISK_SEEK_SET)) ||
599        (-1 ==
600         (nsize = GNUNET_DISK_file_read (fh,
601                                         ndata,
602                                         sizeof (ndata)))) )
603     {
604       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
605                   _("Could not access indexed file `%s' at offset %llu: %s\n"),
606                   GNUNET_h2s (&odb->file_id),
607                   (unsigned long long) off,
608                   STRERROR (errno));
609       if (fh != NULL)
610         GNUNET_DISK_file_close (fh);
611       GNUNET_FS_drq_remove (key,
612                             size,
613                             data,
614                             &remove_cont,
615                             NULL,
616                             GNUNET_TIME_UNIT_FOREVER_REL);
617       return GNUNET_SYSERR;
618     }
619   GNUNET_DISK_file_close (fh);
620   GNUNET_CRYPTO_hash (ndata,
621                       nsize,
622                       &nkey);
623   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
624   GNUNET_CRYPTO_aes_encrypt (ndata,
625                              nsize,
626                              &skey,
627                              &iv,
628                              edata);
629   GNUNET_CRYPTO_hash (edata,
630                       nsize,
631                       &query);
632   if (0 != memcmp (&query, 
633                    key,
634                    sizeof (GNUNET_HashCode)))
635     {
636       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
637                   _("Indexed file `%s' changed at offset %llu\n"),
638                   fn,
639                   (unsigned long long) off);
640       GNUNET_FS_drq_remove (key,
641                             size,
642                             data,
643                             &remove_cont,
644                             NULL,
645                             GNUNET_TIME_UNIT_FOREVER_REL);
646       return GNUNET_SYSERR;
647     }
648 #if DEBUG_FS
649       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
650                   "On-demand encoded block for query `%s'\n",
651                   GNUNET_h2s (key));
652 #endif  
653   cont (cont_cls,
654         key,
655         nsize,
656         edata,
657         GNUNET_BLOCK_TYPE_DBLOCK,
658         priority,
659         anonymity,
660         expiration,
661         uid);
662   return GNUNET_OK;
663 }
664
665
666 /**
667  * Task run during shutdown.
668  *
669  * @param cls unused
670  * @param tc unused
671  */
672 static void
673 shutdown_task (void *cls,
674                const struct GNUNET_SCHEDULER_TaskContext *tc)
675 {
676   struct IndexInfo *pos;  
677
678   GNUNET_CONTAINER_multihashmap_destroy (ifm);
679   ifm = NULL;
680   while (NULL != (pos = indexed_files))
681     {
682       indexed_files = pos->next;
683       GNUNET_free (pos);
684     }
685   sched = NULL;
686   cfg = NULL;
687 }
688
689
690 /**
691  * Initialize the indexing submodule.
692  *
693  * @param s scheduler to use
694  * @param c configuration to use
695  */
696 int
697 GNUNET_FS_indexing_init (struct GNUNET_SCHEDULER_Handle *s,
698                          const struct GNUNET_CONFIGURATION_Handle *c)
699 {
700   sched = s;
701   cfg = c;
702   ifm = GNUNET_CONTAINER_multihashmap_create (128);
703   GNUNET_SCHEDULER_add_delayed (sched,
704                                 GNUNET_TIME_UNIT_FOREVER_REL,
705                                 &shutdown_task,
706                                 NULL);
707   read_index_list ();
708   return GNUNET_OK;
709 }
710
711 /* end of gnunet-service-fs_indexing.c */