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