indentation
[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, "FS", "INDEXDB", &fn))
111   {
112     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
113                 _("Configuration option `%s' in section `%s' missing.\n"),
114                 "INDEXDB", "FS");
115     return;
116   }
117   wh = GNUNET_BIO_write_open (fn);
118   if (NULL == wh)
119   {
120     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
121                 _("Could not open `%s'.\n"), fn);
122     GNUNET_free (fn);
123     return;
124   }
125   pos = indexed_files;
126   while (pos != NULL)
127   {
128     if ((GNUNET_OK !=
129          GNUNET_BIO_write (wh,
130                            &pos->file_id,
131                            sizeof (GNUNET_HashCode))) ||
132         (GNUNET_OK != GNUNET_BIO_write_string (wh, pos->filename)))
133       break;
134     pos = pos->next;
135   }
136   if (GNUNET_OK != GNUNET_BIO_write_close (wh))
137   {
138     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
139                 _("Error writing `%s'.\n"), fn);
140     GNUNET_free (fn);
141     return;
142   }
143   GNUNET_free (fn);
144 }
145
146
147 /**
148  * Read index information from disk.
149  */
150 static void
151 read_index_list ()
152 {
153   struct GNUNET_BIO_ReadHandle *rh;
154   char *fn;
155   struct IndexInfo *pos;
156   char *fname;
157   GNUNET_HashCode hc;
158   size_t slen;
159   char *emsg;
160
161   if (GNUNET_OK !=
162       GNUNET_CONFIGURATION_get_value_filename (cfg, "FS", "INDEXDB", &fn))
163   {
164     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
165                 _("Configuration option `%s' in section `%s' missing.\n"),
166                 "INDEXDB", "FS");
167     return;
168   }
169   if (GNUNET_NO == GNUNET_DISK_file_test (fn))
170   {
171     /* no index info yet */
172     GNUNET_free (fn);
173     return;
174   }
175   rh = GNUNET_BIO_read_open (fn);
176   if (NULL == rh)
177   {
178     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
179                 _("Could not open `%s'.\n"), fn);
180     GNUNET_free (fn);
181     return;
182   }
183   while ((GNUNET_OK ==
184           GNUNET_BIO_read (rh,
185                            "Hash of indexed file",
186                            &hc,
187                            sizeof (GNUNET_HashCode))) &&
188          (GNUNET_OK ==
189           GNUNET_BIO_read_string (rh,
190                                   "Name of indexed file",
191                                   &fname, 1024 * 16)) && (fname != NULL))
192   {
193     slen = strlen (fname) + 1;
194     pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
195     pos->file_id = hc;
196     pos->filename = (const char *) &pos[1];
197     memcpy (&pos[1], fname, slen);
198     if (GNUNET_SYSERR ==
199         GNUNET_CONTAINER_multihashmap_put (ifm,
200                                            &hc,
201                                            (void *) pos->filename,
202                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
203     {
204       GNUNET_free (pos);
205     }
206     else
207     {
208       pos->next = indexed_files;
209       indexed_files = pos;
210     }
211     GNUNET_free (fname);
212   }
213   if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg))
214     GNUNET_free (emsg);
215   GNUNET_free (fn);
216 }
217
218
219 /**
220  * We've validated the hash of the file we're about to index.  Signal
221  * success to the client and update our internal data structures.
222  *
223  * @param ii the index info entry for the request
224  */
225 static void
226 signal_index_ok (struct IndexInfo *ii)
227 {
228   if (GNUNET_SYSERR ==
229       GNUNET_CONTAINER_multihashmap_put (ifm,
230                                          &ii->file_id,
231                                          (void *) ii->filename,
232                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
233   {
234     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
235                 _
236                 ("Index request received for file `%s' is already indexed as `%s'.  Permitting anyway.\n"),
237                 ii->filename,
238                 (const char *) GNUNET_CONTAINER_multihashmap_get (ifm,
239                                                                   &ii->file_id));
240     GNUNET_SERVER_transmit_context_append_data (ii->tc, NULL, 0,
241                                                 GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
242     GNUNET_SERVER_transmit_context_run (ii->tc, GNUNET_TIME_UNIT_MINUTES);
243     GNUNET_free (ii);
244     return;
245   }
246   ii->next = indexed_files;
247   indexed_files = ii;
248   write_index_list ();
249   GNUNET_SERVER_transmit_context_append_data (ii->tc,
250                                               NULL, 0,
251                                               GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
252   GNUNET_SERVER_transmit_context_run (ii->tc, GNUNET_TIME_UNIT_MINUTES);
253   ii->tc = NULL;
254 }
255
256
257 /**
258  * Function called once the hash computation over an
259  * indexed file has completed.
260  *
261  * @param cls closure, our publishing context
262  * @param res resulting hash, NULL on error
263  */
264 static void
265 hash_for_index_val (void *cls, const GNUNET_HashCode * res)
266 {
267   struct IndexInfo *ii = cls;
268
269   ii->fhc = NULL;
270   if ((res == NULL) ||
271       (0 != memcmp (res, &ii->file_id, sizeof (GNUNET_HashCode))))
272   {
273     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
274                 _
275                 ("Hash mismatch trying to index file `%s' which has hash `%s'\n"),
276                 ii->filename, GNUNET_h2s (res));
277 #if DEBUG_FS
278     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
279                 "Wanted `%s'\n", GNUNET_h2s (&ii->file_id));
280 #endif
281     GNUNET_SERVER_transmit_context_append_data (ii->tc,
282                                                 NULL, 0,
283                                                 GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED);
284     GNUNET_SERVER_transmit_context_run (ii->tc, GNUNET_TIME_UNIT_MINUTES);
285     GNUNET_free (ii);
286     return;
287   }
288   signal_index_ok (ii);
289 }
290
291
292 /**
293  * Handle INDEX_START-message.
294  *
295  * @param cls closure
296  * @param client identification of the client
297  * @param message the actual message
298  */
299 void
300 GNUNET_FS_handle_index_start (void *cls,
301                               struct GNUNET_SERVER_Client *client,
302                               const struct GNUNET_MessageHeader *message)
303 {
304   const struct IndexStartMessage *ism;
305   char *fn;
306   uint16_t msize;
307   struct IndexInfo *ii;
308   size_t slen;
309   uint64_t dev;
310   uint64_t ino;
311   uint64_t mydev;
312   uint64_t myino;
313
314   msize = ntohs (message->size);
315   if ((msize <= sizeof (struct IndexStartMessage)) ||
316       (((const char *) message)[msize - 1] != '\0'))
317   {
318     GNUNET_break (0);
319     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
320     return;
321   }
322   ism = (const struct IndexStartMessage *) message;
323   if (0 != ism->reserved)
324   {
325     GNUNET_break (0);
326     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
327     return;
328   }
329   fn = GNUNET_STRINGS_filename_expand ((const char *) &ism[1]);
330   if (fn == NULL)
331   {
332     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
333     return;
334   }
335   dev = GNUNET_ntohll (ism->device);
336   ino = GNUNET_ntohll (ism->inode);
337   ism = (const struct IndexStartMessage *) message;
338   slen = strlen (fn) + 1;
339   ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
340   ii->filename = (const char *) &ii[1];
341   memcpy (&ii[1], fn, slen);
342   ii->file_id = ism->file_id;
343 #if DEBUG_FS
344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
345               "Received `%s' message for file `%s'\n",
346               "START_INDEX", ii->filename);
347 #endif
348
349   ii->tc = GNUNET_SERVER_transmit_context_create (client);
350   mydev = 0;
351   myino = 0;
352   if (((dev != 0) ||
353        (ino != 0)) &&
354       (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
355                                                       &mydev,
356                                                       &myino)) &&
357       ((dev == mydev) && (ino == myino)))
358   {
359     /* fast validation OK! */
360     signal_index_ok (ii);
361     GNUNET_free (fn);
362     return;
363   }
364 #if DEBUG_FS
365   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
366               "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n",
367               (unsigned long long) ino,
368               (unsigned long long) myino,
369               (unsigned int) dev, (unsigned int) mydev);
370 #endif
371   /* slow validation, need to hash full file (again) */
372   ii->fhc = GNUNET_CRYPTO_hash_file (GNUNET_SCHEDULER_PRIORITY_IDLE,
373                                      fn,
374                                      HASHING_BLOCKSIZE,
375                                      &hash_for_index_val, ii);
376   if (ii->fhc == NULL)
377     hash_for_index_val (ii, NULL);
378   GNUNET_free (fn);
379 }
380
381
382 /**
383  * Handle INDEX_LIST_GET-message.
384  *
385  * @param cls closure
386  * @param client identification of the client
387  * @param message the actual message
388  */
389 void
390 GNUNET_FS_handle_index_list_get (void *cls,
391                                  struct GNUNET_SERVER_Client *client,
392                                  const struct GNUNET_MessageHeader *message)
393 {
394   struct GNUNET_SERVER_TransmitContext *tc;
395   struct IndexInfoMessage *iim;
396   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1];
397   size_t slen;
398   const char *fn;
399   struct IndexInfo *pos;
400
401   tc = GNUNET_SERVER_transmit_context_create (client);
402   iim = (struct IndexInfoMessage *) buf;
403   pos = indexed_files;
404   while (NULL != pos)
405   {
406     fn = pos->filename;
407     slen = strlen (fn) + 1;
408     if (slen + sizeof (struct IndexInfoMessage) >=
409         GNUNET_SERVER_MAX_MESSAGE_SIZE)
410     {
411       GNUNET_break (0);
412       break;
413     }
414     iim->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
415     iim->header.size = htons (slen + sizeof (struct IndexInfoMessage));
416     iim->reserved = 0;
417     iim->file_id = pos->file_id;
418     memcpy (&iim[1], fn, slen);
419     GNUNET_SERVER_transmit_context_append_message (tc, &iim->header);
420     pos = pos->next;
421   }
422   GNUNET_SERVER_transmit_context_append_data (tc,
423                                               NULL, 0,
424                                               GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
425   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_MINUTES);
426 }
427
428
429 /**
430  * Handle UNINDEX-message.
431  *
432  * @param cls closure
433  * @param client identification of the client
434  * @param message the actual message
435  */
436 void
437 GNUNET_FS_handle_unindex (void *cls,
438                           struct GNUNET_SERVER_Client *client,
439                           const struct GNUNET_MessageHeader *message)
440 {
441   const struct UnindexMessage *um;
442   struct IndexInfo *pos;
443   struct IndexInfo *prev;
444   struct IndexInfo *next;
445   struct GNUNET_SERVER_TransmitContext *tc;
446   int found;
447
448   um = (const struct UnindexMessage *) message;
449   if (0 != um->reserved)
450   {
451     GNUNET_break (0);
452     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
453     return;
454   }
455   found = GNUNET_NO;
456   prev = NULL;
457   pos = indexed_files;
458   while (NULL != pos)
459   {
460     next = pos->next;
461     if (0 == memcmp (&pos->file_id, &um->file_id, sizeof (GNUNET_HashCode)))
462     {
463       if (prev == NULL)
464         indexed_files = next;
465       else
466         prev->next = next;
467       GNUNET_break (GNUNET_OK ==
468                     GNUNET_CONTAINER_multihashmap_remove (ifm,
469                                                           &pos->file_id,
470                                                           (void *)
471                                                           pos->filename));
472       GNUNET_free (pos);
473       found = GNUNET_YES;
474     }
475     else
476     {
477       prev = pos;
478     }
479     pos = next;
480   }
481 #if DEBUG_FS
482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
483               "Client requested unindexing of file `%s': %s\n",
484               GNUNET_h2s (&um->file_id), 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, GNUNET_TIME_UNIT_MINUTES);
493 }
494
495
496 /**
497  * Continuation called from datastore's remove
498  * function.
499  *
500  * @param cls unused
501  * @param success did the deletion work?
502  * @param msg error message
503  */
504 static void
505 remove_cont (void *cls, int success, const char *msg)
506 {
507   if (GNUNET_OK != success)
508     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
509                 _("Failed to delete bogus block: %s\n"), msg);
510 }
511
512
513 /**
514  * We've received an on-demand encoded block from the datastore.
515  * Attempt to do on-demand encoding and (if successful), call the
516  * continuation with the resulting block.  On error, clean up and ask
517  * the datastore for more results.
518  *
519  * @param key key for the content
520  * @param size number of bytes in data
521  * @param data content stored
522  * @param type type of the content
523  * @param priority priority of the content
524  * @param anonymity anonymity-level for the content
525  * @param expiration expiration time for the content
526  * @param uid unique identifier for the datum;
527  *        maybe 0 if no unique identifier is available
528  * @param cont function to call with the actual block (at most once, on success)
529  * @param cont_cls closure for cont
530  * @return GNUNET_OK on success
531  */
532 int
533 GNUNET_FS_handle_on_demand_block (const GNUNET_HashCode * key,
534                                   uint32_t size,
535                                   const void *data,
536                                   enum GNUNET_BLOCK_Type type,
537                                   uint32_t priority,
538                                   uint32_t anonymity,
539                                   struct GNUNET_TIME_Absolute
540                                   expiration, uint64_t uid,
541                                   GNUNET_DATASTORE_DatumProcessor cont,
542                                   void *cont_cls)
543 {
544   const struct OnDemandBlock *odb;
545   GNUNET_HashCode nkey;
546   struct GNUNET_CRYPTO_AesSessionKey skey;
547   struct GNUNET_CRYPTO_AesInitializationVector iv;
548   GNUNET_HashCode query;
549   ssize_t nsize;
550   char ndata[DBLOCK_SIZE];
551   char edata[DBLOCK_SIZE];
552   const char *fn;
553   struct GNUNET_DISK_FileHandle *fh;
554   uint64_t off;
555
556   if (size != sizeof (struct OnDemandBlock))
557   {
558     GNUNET_break (0);
559     GNUNET_DATASTORE_remove (dsh,
560                              key,
561                              size,
562                              data,
563                              -1, -1,
564                              GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
565     return GNUNET_SYSERR;
566   }
567   odb = (const struct OnDemandBlock *) data;
568   off = GNUNET_ntohll (odb->offset);
569   fn = (const char *) GNUNET_CONTAINER_multihashmap_get (ifm, &odb->file_id);
570   fh = NULL;
571   if ((NULL == fn) ||
572       (NULL == (fh = GNUNET_DISK_file_open (fn,
573                                             GNUNET_DISK_OPEN_READ,
574                                             GNUNET_DISK_PERM_NONE))) ||
575       (off !=
576        GNUNET_DISK_file_seek (fh,
577                               off,
578                               GNUNET_DISK_SEEK_SET)) ||
579       (-1 == (nsize = GNUNET_DISK_file_read (fh, ndata, sizeof (ndata)))))
580   {
581     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
582                 _
583                 ("Could not access indexed file `%s' (%s) at offset %llu: %s\n"),
584                 GNUNET_h2s (&odb->file_id), fn, (unsigned long long) off,
585                 (fn == NULL) ? _("not indexed") : STRERROR (errno));
586     if (fh != NULL)
587       GNUNET_DISK_file_close (fh);
588     GNUNET_DATASTORE_remove (dsh,
589                              key,
590                              size,
591                              data,
592                              -1, -1,
593                              GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
594     return GNUNET_SYSERR;
595   }
596   GNUNET_DISK_file_close (fh);
597   GNUNET_CRYPTO_hash (ndata, nsize, &nkey);
598   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
599   GNUNET_CRYPTO_aes_encrypt (ndata, nsize, &skey, &iv, edata);
600   GNUNET_CRYPTO_hash (edata, nsize, &query);
601   if (0 != memcmp (&query, key, sizeof (GNUNET_HashCode)))
602   {
603     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
604                 _("Indexed file `%s' changed at offset %llu\n"),
605                 fn, (unsigned long long) off);
606     GNUNET_DATASTORE_remove (dsh,
607                              key,
608                              size,
609                              data,
610                              -1, -1,
611                              GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
612     return GNUNET_SYSERR;
613   }
614 #if DEBUG_FS
615   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
616               "On-demand encoded block for query `%s'\n", GNUNET_h2s (key));
617 #endif
618   cont (cont_cls,
619         key,
620         nsize,
621         edata,
622         GNUNET_BLOCK_TYPE_FS_DBLOCK, priority, anonymity, expiration, uid);
623   return GNUNET_OK;
624 }
625
626
627 /**
628  * Shutdown the module.
629  */
630 void
631 GNUNET_FS_indexing_done ()
632 {
633   struct IndexInfo *pos;
634
635   GNUNET_CONTAINER_multihashmap_destroy (ifm);
636   ifm = NULL;
637   while (NULL != (pos = indexed_files))
638   {
639     indexed_files = pos->next;
640     if (pos->fhc != NULL)
641       GNUNET_CRYPTO_hash_file_cancel (pos->fhc);
642     GNUNET_free (pos);
643   }
644   cfg = NULL;
645 }
646
647
648 /**
649  * Initialize the indexing submodule.
650  *
651  * @param c configuration to use
652  * @param d datastore to use
653  */
654 int
655 GNUNET_FS_indexing_init (const struct GNUNET_CONFIGURATION_Handle *c,
656                          struct GNUNET_DATASTORE_Handle *d)
657 {
658   cfg = c;
659   dsh = d;
660   ifm = GNUNET_CONTAINER_multihashmap_create (128);
661   read_index_list ();
662   return GNUNET_OK;
663 }
664
665 /* end of gnunet-service-fs_indexing.c */