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