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