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