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