fix
[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  * 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 #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 (sched,
403                                      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];
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) > 
441           GNUNET_SERVER_MAX_MESSAGE_SIZE)
442         {
443           GNUNET_break (0);
444           break;
445         }
446       iim->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
447       iim->header.size = htons (slen + sizeof (struct IndexInfoMessage));
448       iim->reserved = 0;
449       iim->file_id = pos->file_id;
450       memcpy (&iim[1], fn, slen);
451       GNUNET_SERVER_transmit_context_append_message (tc,
452                                                      &iim->header);
453       pos = pos->next;
454     }
455   GNUNET_SERVER_transmit_context_append_data (tc,
456                                               NULL, 0,
457                                               GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
458   GNUNET_SERVER_transmit_context_run (tc,
459                                       GNUNET_TIME_UNIT_MINUTES);
460 }
461
462
463 /**
464  * Handle UNINDEX-message.
465  *
466  * @param cls closure
467  * @param client identification of the client
468  * @param message the actual message
469  */
470 void
471 GNUNET_FS_handle_unindex (void *cls,
472                           struct GNUNET_SERVER_Client *client,
473                           const struct GNUNET_MessageHeader *message)
474 {
475   const struct UnindexMessage *um;
476   struct IndexInfo *pos;
477   struct IndexInfo *prev;
478   struct IndexInfo *next;
479   struct GNUNET_SERVER_TransmitContext *tc;
480   int found;
481   
482   um = (const struct UnindexMessage*) message;
483   found = GNUNET_NO;
484   prev = NULL;
485   pos = indexed_files;
486   while (NULL != pos)
487     {
488       next = pos->next;
489       if (0 == memcmp (&pos->file_id,
490                        &um->file_id,
491                        sizeof (GNUNET_HashCode)))
492         {
493           if (prev == NULL)
494             indexed_files = next;
495           else
496             prev->next = next;
497           GNUNET_free (pos);
498           found = GNUNET_YES;
499         }
500       else
501         {
502           prev = pos;
503         }
504       pos = next;
505     }
506 #if DEBUG_FS
507   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
508               "Client requested unindexing of file `%s': %s\n",
509               GNUNET_h2s (&um->file_id),
510               found ? "found" : "not found");
511 #endif
512   if (GNUNET_YES == found)    
513     write_index_list ();
514   tc = GNUNET_SERVER_transmit_context_create (client);
515   GNUNET_SERVER_transmit_context_append_data (tc,
516                                               NULL, 0,
517                                               GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
518   GNUNET_SERVER_transmit_context_run (tc,
519                                       GNUNET_TIME_UNIT_MINUTES);
520 }
521
522
523
524
525 /**
526  * Continuation called from datastore's remove
527  * function.
528  *
529  * @param cls unused
530  * @param success did the deletion work?
531  * @param msg error message
532  */
533 static void
534 remove_cont (void *cls,
535              int success,
536              const char *msg)
537 {
538   if (GNUNET_OK != success)
539     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
540                 _("Failed to delete bogus block: %s\n"),
541                 msg);
542 }
543
544
545 /**
546  * We've received an on-demand encoded block from the datastore.
547  * Attempt to do on-demand encoding and (if successful), call the
548  * continuation with the resulting block.  On error, clean up and ask
549  * the datastore for more results.
550  *
551  * @param key key for the content
552  * @param size number of bytes in data
553  * @param data content stored
554  * @param type type of the content
555  * @param priority priority of the content
556  * @param anonymity anonymity-level for the content
557  * @param expiration expiration time for the content
558  * @param uid unique identifier for the datum;
559  *        maybe 0 if no unique identifier is available
560  * @param cont function to call with the actual block (at most once, on success)
561  * @param cont_cls closure for cont
562  * @return GNUNET_OK on success
563  */
564 int
565 GNUNET_FS_handle_on_demand_block (const GNUNET_HashCode * key,
566                                   uint32_t size,
567                                   const void *data,
568                                   enum GNUNET_BLOCK_Type type,
569                                   uint32_t priority,
570                                   uint32_t anonymity,
571                                   struct GNUNET_TIME_Absolute
572                                   expiration, uint64_t uid,
573                                   GNUNET_DATASTORE_Iterator cont,
574                                   void *cont_cls)
575 {
576   const struct OnDemandBlock *odb;
577   GNUNET_HashCode nkey;
578   struct GNUNET_CRYPTO_AesSessionKey skey;
579   struct GNUNET_CRYPTO_AesInitializationVector iv;
580   GNUNET_HashCode query;
581   ssize_t nsize;
582   char ndata[DBLOCK_SIZE];
583   char edata[DBLOCK_SIZE];
584   const char *fn;
585   struct GNUNET_DISK_FileHandle *fh;
586   uint64_t off;
587
588   if (size != sizeof (struct OnDemandBlock))
589     {
590       GNUNET_break (0);
591       GNUNET_DATASTORE_remove (dsh,
592                                key,
593                                size,
594                                data,
595                                -1, -1,
596                                GNUNET_TIME_UNIT_FOREVER_REL,
597                                &remove_cont,
598                                NULL);
599       return GNUNET_SYSERR;
600     }
601   odb = (const struct OnDemandBlock*) data;
602   off = GNUNET_ntohll (odb->offset);
603   fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
604                                                         &odb->file_id);
605   fh = NULL;
606   if ( (NULL == fn) ||
607        (NULL == (fh = GNUNET_DISK_file_open (fn, 
608                                              GNUNET_DISK_OPEN_READ,
609                                              GNUNET_DISK_PERM_NONE))) ||
610        (off !=
611         GNUNET_DISK_file_seek (fh,
612                                off,
613                                GNUNET_DISK_SEEK_SET)) ||
614        (-1 ==
615         (nsize = GNUNET_DISK_file_read (fh,
616                                         ndata,
617                                         sizeof (ndata)))) )
618     {
619       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
620                   _("Could not access indexed file `%s' (%s) at offset %llu: %s\n"),
621                   GNUNET_h2s (&odb->file_id),
622                   fn,
623                   (unsigned long long) off,
624                   STRERROR (errno));
625       if (fh != NULL)
626         GNUNET_DISK_file_close (fh);
627       GNUNET_DATASTORE_remove (dsh,
628                                key,
629                                size,
630                                data,
631                                -1, -1,
632                                GNUNET_TIME_UNIT_FOREVER_REL,
633                                &remove_cont,
634                                NULL);
635       return GNUNET_SYSERR;
636     }
637   GNUNET_DISK_file_close (fh);
638   GNUNET_CRYPTO_hash (ndata,
639                       nsize,
640                       &nkey);
641   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
642   GNUNET_CRYPTO_aes_encrypt (ndata,
643                              nsize,
644                              &skey,
645                              &iv,
646                              edata);
647   GNUNET_CRYPTO_hash (edata,
648                       nsize,
649                       &query);
650   if (0 != memcmp (&query, 
651                    key,
652                    sizeof (GNUNET_HashCode)))
653     {
654       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
655                   _("Indexed file `%s' changed at offset %llu\n"),
656                   fn,
657                   (unsigned long long) off);
658       GNUNET_DATASTORE_remove (dsh,
659                                key,
660                                size,
661                                data,
662                                -1, -1,
663                                GNUNET_TIME_UNIT_FOREVER_REL,
664                                &remove_cont,
665                                NULL);
666       return GNUNET_SYSERR;
667     }
668 #if DEBUG_FS
669       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
670                   "On-demand encoded block for query `%s'\n",
671                   GNUNET_h2s (key));
672 #endif  
673   cont (cont_cls,
674         key,
675         nsize,
676         edata,
677         GNUNET_BLOCK_TYPE_DBLOCK,
678         priority,
679         anonymity,
680         expiration,
681         uid);
682   return GNUNET_OK;
683 }
684
685
686 /**
687  * Task run during shutdown.
688  *
689  * @param cls unused
690  * @param tc unused
691  */
692 static void
693 shutdown_task (void *cls,
694                const struct GNUNET_SCHEDULER_TaskContext *tc)
695 {
696   struct IndexInfo *pos;  
697
698   GNUNET_CONTAINER_multihashmap_destroy (ifm);
699   ifm = NULL;
700   while (NULL != (pos = indexed_files))
701     {
702       indexed_files = pos->next;
703       GNUNET_free (pos);
704     }
705   sched = NULL;
706   cfg = NULL;
707 }
708
709
710 /**
711  * Initialize the indexing submodule.
712  *
713  * @param s scheduler to use
714  * @param c configuration to use
715  * @param d datastore to use
716  */
717 int
718 GNUNET_FS_indexing_init (struct GNUNET_SCHEDULER_Handle *s,
719                          const struct GNUNET_CONFIGURATION_Handle *c,
720                          struct GNUNET_DATASTORE_Handle *d)
721 {
722   sched = s;
723   cfg = c;
724   dsh = d;
725   ifm = GNUNET_CONTAINER_multihashmap_create (128);
726   GNUNET_SCHEDULER_add_delayed (sched,
727                                 GNUNET_TIME_UNIT_FOREVER_REL,
728                                 &shutdown_task,
729                                 NULL);
730   read_index_list ();
731   return GNUNET_OK;
732 }
733
734 /* end of gnunet-service-fs_indexing.c */