arg
[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   fn = GNUNET_STRINGS_filename_expand ((const char*) &ism[1]);
350   if (fn == NULL)
351     {
352       GNUNET_SERVER_receive_done (client,
353                                   GNUNET_SYSERR);
354       return;
355     }
356   dev = GNUNET_ntohll (ism->device);
357   ino = GNUNET_ntohll (ism->inode);
358   ism = (const struct IndexStartMessage*) message;
359   slen = strlen (fn) + 1;
360   ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
361   ii->filename = (const char*) &ii[1];
362   memcpy (&ii[1], fn, slen);
363   ii->file_id = ism->file_id;  
364 #if DEBUG_FS
365   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
366               "Received `%s' message for file `%s'\n",
367               "START_INDEX",
368               ii->filename);
369 #endif
370
371   ii->tc = GNUNET_SERVER_transmit_context_create (client);
372   mydev = 0;
373   myino = 0;
374   if ( ( (dev != 0) ||
375          (ino != 0) ) &&
376        (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
377                                                        &mydev,
378                                                        &myino)) &&
379        ( (dev == mydev) &&
380          (ino == myino) ) )
381     {      
382       /* fast validation OK! */
383       signal_index_ok (ii);
384       GNUNET_free (fn);
385       return;
386     }
387 #if DEBUG_FS
388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
389               "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n",
390               (unsigned long long) ino,
391               (unsigned long long) myino,
392               (unsigned int) dev,
393               (unsigned int) mydev);
394 #endif
395   /* slow validation, need to hash full file (again) */
396   ii->fhc = GNUNET_CRYPTO_hash_file (GNUNET_SCHEDULER_PRIORITY_IDLE,
397                                      fn,
398                                      HASHING_BLOCKSIZE,
399                                      &hash_for_index_val,
400                                      ii);
401   if (ii->fhc == NULL)    
402     hash_for_index_val (ii, NULL);    
403   GNUNET_free (fn);
404 }
405
406
407 /**
408  * Handle INDEX_LIST_GET-message.
409  *
410  * @param cls closure
411  * @param client identification of the client
412  * @param message the actual message
413  */
414 void
415 GNUNET_FS_handle_index_list_get (void *cls,
416                                  struct GNUNET_SERVER_Client *client,
417                                  const struct GNUNET_MessageHeader *message)
418 {
419   struct GNUNET_SERVER_TransmitContext *tc;
420   struct IndexInfoMessage *iim;
421   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
422   size_t slen;
423   const char *fn;
424   struct IndexInfo *pos;
425
426   tc = GNUNET_SERVER_transmit_context_create (client);
427   iim = (struct IndexInfoMessage*) buf;
428   pos = indexed_files;
429   while (NULL != pos)
430     {
431       fn = pos->filename;
432       slen = strlen (fn) + 1;
433       if (slen + sizeof (struct IndexInfoMessage) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
434         {
435           GNUNET_break (0);
436           break;
437         }
438       iim->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
439       iim->header.size = htons (slen + sizeof (struct IndexInfoMessage));
440       iim->reserved = 0;
441       iim->file_id = pos->file_id;
442       memcpy (&iim[1], fn, slen);
443       GNUNET_SERVER_transmit_context_append_message (tc,
444                                                      &iim->header);
445       pos = pos->next;
446     }
447   GNUNET_SERVER_transmit_context_append_data (tc,
448                                               NULL, 0,
449                                               GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
450   GNUNET_SERVER_transmit_context_run (tc,
451                                       GNUNET_TIME_UNIT_MINUTES);
452 }
453
454
455 /**
456  * Handle UNINDEX-message.
457  *
458  * @param cls closure
459  * @param client identification of the client
460  * @param message the actual message
461  */
462 void
463 GNUNET_FS_handle_unindex (void *cls,
464                           struct GNUNET_SERVER_Client *client,
465                           const struct GNUNET_MessageHeader *message)
466 {
467   const struct UnindexMessage *um;
468   struct IndexInfo *pos;
469   struct IndexInfo *prev;
470   struct IndexInfo *next;
471   struct GNUNET_SERVER_TransmitContext *tc;
472   int found;
473
474   um = (const struct UnindexMessage*) message;
475   found = GNUNET_NO;
476   prev = NULL;
477   pos = indexed_files;
478   while (NULL != pos)
479     {
480       next = pos->next;
481       if (0 == memcmp (&pos->file_id,
482                        &um->file_id,
483                        sizeof (GNUNET_HashCode)))
484         {
485           if (prev == NULL)
486             indexed_files = next;
487           else
488             prev->next = next;
489           GNUNET_break (GNUNET_OK ==
490                         GNUNET_CONTAINER_multihashmap_remove (ifm,
491                                                               &pos->file_id,
492                                                               (void*) pos->filename));
493           GNUNET_free (pos);
494           found = GNUNET_YES;
495         }
496       else
497         {
498           prev = pos;
499         }
500       pos = next;
501     }
502 #if DEBUG_FS
503   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
504               "Client requested unindexing of file `%s': %s\n",
505               GNUNET_h2s (&um->file_id),
506               found ? "found" : "not found");
507 #endif
508   if (GNUNET_YES == found)    
509     write_index_list ();
510   tc = GNUNET_SERVER_transmit_context_create (client);
511   GNUNET_SERVER_transmit_context_append_data (tc,
512                                               NULL, 0,
513                                               GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
514   GNUNET_SERVER_transmit_context_run (tc,
515                                       GNUNET_TIME_UNIT_MINUTES);
516 }
517
518
519
520
521 /**
522  * Continuation called from datastore's remove
523  * function.
524  *
525  * @param cls unused
526  * @param success did the deletion work?
527  * @param msg error message
528  */
529 static void
530 remove_cont (void *cls,
531              int success,
532              const char *msg)
533 {
534   if (GNUNET_OK != success)
535     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
536                 _("Failed to delete bogus block: %s\n"),
537                 msg);
538 }
539
540
541 /**
542  * We've received an on-demand encoded block from the datastore.
543  * Attempt to do on-demand encoding and (if successful), call the
544  * continuation with the resulting block.  On error, clean up and ask
545  * the datastore for more results.
546  *
547  * @param key key for the content
548  * @param size number of bytes in data
549  * @param data content stored
550  * @param type type of the content
551  * @param priority priority of the content
552  * @param anonymity anonymity-level for the content
553  * @param expiration expiration time for the content
554  * @param uid unique identifier for the datum;
555  *        maybe 0 if no unique identifier is available
556  * @param cont function to call with the actual block (at most once, on success)
557  * @param cont_cls closure for cont
558  * @return GNUNET_OK on success
559  */
560 int
561 GNUNET_FS_handle_on_demand_block (const GNUNET_HashCode * key,
562                                   uint32_t size,
563                                   const void *data,
564                                   enum GNUNET_BLOCK_Type type,
565                                   uint32_t priority,
566                                   uint32_t anonymity,
567                                   struct GNUNET_TIME_Absolute
568                                   expiration, uint64_t uid,
569                                   GNUNET_DATASTORE_DatumProcessor cont,
570                                   void *cont_cls)
571 {
572   const struct OnDemandBlock *odb;
573   GNUNET_HashCode nkey;
574   struct GNUNET_CRYPTO_AesSessionKey skey;
575   struct GNUNET_CRYPTO_AesInitializationVector iv;
576   GNUNET_HashCode query;
577   ssize_t nsize;
578   char ndata[DBLOCK_SIZE];
579   char edata[DBLOCK_SIZE];
580   const char *fn;
581   struct GNUNET_DISK_FileHandle *fh;
582   uint64_t off;
583
584   if (size != sizeof (struct OnDemandBlock))
585     {
586       GNUNET_break (0);
587       GNUNET_DATASTORE_remove (dsh,
588                                key,
589                                size,
590                                data,
591                                -1, -1,
592                                GNUNET_TIME_UNIT_FOREVER_REL,
593                                &remove_cont,
594                                NULL);
595       return GNUNET_SYSERR;
596     }
597   odb = (const struct OnDemandBlock*) data;
598   off = GNUNET_ntohll (odb->offset);
599   fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
600                                                         &odb->file_id);
601   fh = NULL;
602   if ( (NULL == fn) ||
603        (NULL == (fh = GNUNET_DISK_file_open (fn, 
604                                              GNUNET_DISK_OPEN_READ,
605                                              GNUNET_DISK_PERM_NONE))) ||
606        (off !=
607         GNUNET_DISK_file_seek (fh,
608                                off,
609                                GNUNET_DISK_SEEK_SET)) ||
610        (-1 ==
611         (nsize = GNUNET_DISK_file_read (fh,
612                                         ndata,
613                                         sizeof (ndata)))) )
614     {
615       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
616                   _("Could not access indexed file `%s' (%s) at offset %llu: %s\n"),
617                   GNUNET_h2s (&odb->file_id),
618                   fn,
619                   (unsigned long long) off,
620                   (fn == NULL) ? _("not indexed") : STRERROR (errno));
621       if (fh != NULL)
622         GNUNET_DISK_file_close (fh);
623       GNUNET_DATASTORE_remove (dsh,
624                                key,
625                                size,
626                                data,
627                                -1, -1,
628                                GNUNET_TIME_UNIT_FOREVER_REL,
629                                &remove_cont,
630                                NULL);
631       return GNUNET_SYSERR;
632     }
633   GNUNET_DISK_file_close (fh);
634   GNUNET_CRYPTO_hash (ndata,
635                       nsize,
636                       &nkey);
637   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
638   GNUNET_CRYPTO_aes_encrypt (ndata,
639                              nsize,
640                              &skey,
641                              &iv,
642                              edata);
643   GNUNET_CRYPTO_hash (edata,
644                       nsize,
645                       &query);
646   if (0 != memcmp (&query, 
647                    key,
648                    sizeof (GNUNET_HashCode)))
649     {
650       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
651                   _("Indexed file `%s' changed at offset %llu\n"),
652                   fn,
653                   (unsigned long long) off);
654       GNUNET_DATASTORE_remove (dsh,
655                                key,
656                                size,
657                                data,
658                                -1, -1,
659                                GNUNET_TIME_UNIT_FOREVER_REL,
660                                &remove_cont,
661                                NULL);
662       return GNUNET_SYSERR;
663     }
664 #if DEBUG_FS
665       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
666                   "On-demand encoded block for query `%s'\n",
667                   GNUNET_h2s (key));
668 #endif  
669   cont (cont_cls,
670         key,
671         nsize,
672         edata,
673         GNUNET_BLOCK_TYPE_FS_DBLOCK,
674         priority,
675         anonymity,
676         expiration,
677         uid);
678   return GNUNET_OK;
679 }
680
681
682 /**
683  * Shutdown the module.
684  */
685 void
686 GNUNET_FS_indexing_done ()
687 {
688   struct IndexInfo *pos;  
689
690   GNUNET_CONTAINER_multihashmap_destroy (ifm);
691   ifm = NULL;
692   while (NULL != (pos = indexed_files))
693     {
694       indexed_files = pos->next;
695       if (pos->fhc != NULL)
696         GNUNET_CRYPTO_hash_file_cancel (pos->fhc);
697       GNUNET_free (pos);
698     }
699   cfg = NULL;
700 }
701
702
703 /**
704  * Initialize the indexing submodule.
705  *
706  * @param c configuration to use
707  * @param d datastore to use
708  */
709 int
710 GNUNET_FS_indexing_init (const struct GNUNET_CONFIGURATION_Handle *c,
711                          struct GNUNET_DATASTORE_Handle *d)
712 {
713   cfg = c;
714   dsh = d;
715   ifm = GNUNET_CONTAINER_multihashmap_create (128);
716   read_index_list ();
717   return GNUNET_OK;
718 }
719
720 /* end of gnunet-service-fs_indexing.c */