multicast: added replay_end(), returning replay handle from join_decision(); removed...
[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_assert (NULL != ir);
235     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
236                 _
237                 ("Index request received for file `%s' is already indexed as `%s'.  Permitting anyway.\n"),
238                 ii->filename,
239                 ir->filename);           
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   GNUNET_CONTAINER_DLL_insert (indexed_files_head,
247                                indexed_files_tail,
248                                ii);
249   write_index_list ();
250   GNUNET_SERVER_transmit_context_append_data (ii->tc, 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 struct 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 (struct 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     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Wanted `%s'\n",
278                 GNUNET_h2s (&ii->file_id));
279     GNUNET_SERVER_transmit_context_append_data (ii->tc, NULL, 0,
280                                                 GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED);
281     GNUNET_SERVER_transmit_context_run (ii->tc, GNUNET_TIME_UNIT_MINUTES);
282     GNUNET_free (ii);
283     return;
284   }
285   signal_index_ok (ii);
286 }
287
288
289 /**
290  * Handle INDEX_START-message.
291  *
292  * @param cls closure
293  * @param client identification of the client
294  * @param message the actual message
295  */
296 void
297 GNUNET_FS_handle_index_start (void *cls, struct GNUNET_SERVER_Client *client,
298                               const struct GNUNET_MessageHeader *message)
299 {
300   const struct IndexStartMessage *ism;
301   char *fn;
302   uint16_t msize;
303   struct IndexInfo *ii;
304   size_t slen;
305   uint64_t dev;
306   uint64_t ino;
307   uint64_t mydev;
308   uint64_t myino;
309
310   msize = ntohs (message->size);
311   if ((msize <= sizeof (struct IndexStartMessage)) ||
312       (((const char *) message)[msize - 1] != '\0'))
313   {
314     GNUNET_break (0);
315     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
316     return;
317   }
318   ism = (const struct IndexStartMessage *) message;
319   if (0 != ism->reserved)
320   {
321     GNUNET_break (0);
322     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
323     return;
324   }
325   fn = GNUNET_STRINGS_filename_expand ((const char *) &ism[1]);
326   if (fn == NULL)
327   {
328     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
329     return;
330   }
331   dev = GNUNET_ntohll (ism->device);
332   ino = GNUNET_ntohll (ism->inode);
333   ism = (const struct IndexStartMessage *) message;
334   slen = strlen (fn) + 1;
335   ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
336   ii->filename = (const char *) &ii[1];
337   memcpy (&ii[1], fn, slen);
338   ii->file_id = ism->file_id;
339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received `%s' message for file `%s'\n",
340               "START_INDEX", ii->filename);
341   ii->tc = GNUNET_SERVER_transmit_context_create (client);
342   mydev = 0;
343   myino = 0;
344   if (((dev != 0) || (ino != 0)) &&
345       (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn, &mydev, &myino)) &&
346       ((dev == mydev) && (ino == myino)))
347   {
348     /* fast validation OK! */
349     signal_index_ok (ii);
350     GNUNET_free (fn);
351     return;
352   }
353   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
354               "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n",
355               (unsigned long long) ino, (unsigned long long) myino,
356               (unsigned int) dev, (unsigned int) mydev);
357   /* slow validation, need to hash full file (again) */
358   ii->fhc =
359       GNUNET_CRYPTO_hash_file (GNUNET_SCHEDULER_PRIORITY_IDLE, fn,
360                                HASHING_BLOCKSIZE, &hash_for_index_val, ii);
361   if (ii->fhc == NULL)
362     hash_for_index_val (ii, NULL);
363   GNUNET_free (fn);
364 }
365
366
367 /**
368  * Handle INDEX_LIST_GET-message.
369  *
370  * @param cls closure
371  * @param client identification of the client
372  * @param message the actual message
373  */
374 void
375 GNUNET_FS_handle_index_list_get (void *cls, struct GNUNET_SERVER_Client *client,
376                                  const struct GNUNET_MessageHeader *message)
377 {
378   struct GNUNET_SERVER_TransmitContext *tc;
379   struct IndexInfoMessage *iim;
380   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN;
381   size_t slen;
382   const char *fn;
383   struct IndexInfo *pos;
384
385   tc = GNUNET_SERVER_transmit_context_create (client);
386   iim = (struct IndexInfoMessage *) buf;
387   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
388   {
389     fn = pos->filename;
390     slen = strlen (fn) + 1;
391     if (slen + sizeof (struct IndexInfoMessage) >=
392         GNUNET_SERVER_MAX_MESSAGE_SIZE)
393     {
394       GNUNET_break (0);
395       break;
396     }
397     iim->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
398     iim->header.size = htons (slen + sizeof (struct IndexInfoMessage));
399     iim->reserved = 0;
400     iim->file_id = pos->file_id;
401     memcpy (&iim[1], fn, slen);
402     GNUNET_SERVER_transmit_context_append_message (tc, &iim->header);
403   }
404   GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
405                                               GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
406   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_MINUTES);
407 }
408
409
410 /**
411  * Handle UNINDEX-message.
412  *
413  * @param cls closure
414  * @param client identification of the client
415  * @param message the actual message
416  */
417 void
418 GNUNET_FS_handle_unindex (void *cls, struct GNUNET_SERVER_Client *client,
419                           const struct GNUNET_MessageHeader *message)
420 {
421   const struct UnindexMessage *um;
422   struct IndexInfo *pos;
423   struct GNUNET_SERVER_TransmitContext *tc;
424   int found;
425
426   um = (const struct UnindexMessage *) message;
427   if (0 != um->reserved)
428   {
429     GNUNET_break (0);
430     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
431     return;
432   }
433   found = GNUNET_NO;
434   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
435   {
436     if (0 == memcmp (&pos->file_id, &um->file_id, sizeof (struct GNUNET_HashCode)))
437     {
438       GNUNET_CONTAINER_DLL_remove (indexed_files_head,
439                                    indexed_files_tail,
440                                    pos);
441       GNUNET_break (GNUNET_OK ==
442                     GNUNET_CONTAINER_multihashmap_remove (ifm, &pos->file_id,
443                                                           pos));
444       GNUNET_free (pos);
445       found = GNUNET_YES;
446       break;
447     }
448   }
449   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
450               "Client requested unindexing of file `%s': %s\n",
451               GNUNET_h2s (&um->file_id), found ? "found" : "not found");
452   if (GNUNET_YES == found)
453     write_index_list ();
454   tc = GNUNET_SERVER_transmit_context_create (client);
455   GNUNET_SERVER_transmit_context_append_data (tc, NULL, 0,
456                                               GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
457   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_MINUTES);
458 }
459
460
461 /**
462  * Continuation called from datastore's remove
463  * function.
464  *
465  * @param cls unused
466  * @param success did the deletion work?
467  * @param min_expiration minimum expiration time required for content to be stored
468  * @param msg error message
469  */
470 static void
471 remove_cont (void *cls, int success, 
472              struct GNUNET_TIME_Absolute min_expiration,
473              const char *msg)
474 {
475   if (GNUNET_OK != success)
476     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
477                 _("Failed to delete bogus block: %s\n"), msg);
478 }
479
480
481 /**
482  * We've received an on-demand encoded block from the datastore.
483  * Attempt to do on-demand encoding and (if successful), call the
484  * continuation with the resulting block.  On error, clean up and ask
485  * the datastore for more results.
486  *
487  * @param key key for the content
488  * @param size number of bytes in data
489  * @param data content stored
490  * @param type type of the content
491  * @param priority priority of the content
492  * @param anonymity anonymity-level for the content
493  * @param expiration expiration time for the content
494  * @param uid unique identifier for the datum;
495  *        maybe 0 if no unique identifier is available
496  * @param cont function to call with the actual block (at most once, on success)
497  * @param cont_cls closure for cont
498  * @return GNUNET_OK on success
499  */
500 int
501 GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode * key, uint32_t size,
502                                   const void *data, enum GNUNET_BLOCK_Type type,
503                                   uint32_t priority, uint32_t anonymity,
504                                   struct GNUNET_TIME_Absolute expiration,
505                                   uint64_t uid,
506                                   GNUNET_DATASTORE_DatumProcessor cont,
507                                   void *cont_cls)
508 {
509   const struct OnDemandBlock *odb;
510   struct GNUNET_HashCode nkey;
511   struct GNUNET_CRYPTO_AesSessionKey skey;
512   struct GNUNET_CRYPTO_AesInitializationVector iv;
513   struct GNUNET_HashCode query;
514   ssize_t nsize;
515   char ndata[DBLOCK_SIZE];
516   char edata[DBLOCK_SIZE];
517   const char *fn;
518   struct GNUNET_DISK_FileHandle *fh;
519   uint64_t off;
520   struct IndexInfo *ii;
521
522   if (size != sizeof (struct OnDemandBlock))
523   {
524     GNUNET_break (0);
525     GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1,
526                              GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
527     return GNUNET_SYSERR;
528   }
529   odb = (const struct OnDemandBlock *) data;
530   off = GNUNET_ntohll (odb->offset);
531   ii = GNUNET_CONTAINER_multihashmap_get (ifm, &odb->file_id);
532   if (NULL == ii)
533   {
534     GNUNET_break (0);
535     return GNUNET_SYSERR;
536   }
537   fn = ii->filename;
538   if ((NULL == fn) || (0 != ACCESS (fn, R_OK)))
539   {
540     GNUNET_STATISTICS_update (GSF_stats,
541                               gettext_noop
542                               ("# index blocks removed: original file inaccessible"),
543                               1, GNUNET_YES);
544     GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1,
545                              GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
546     return GNUNET_SYSERR;
547   }
548   if ((NULL ==
549        (fh =
550         GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ,
551                                GNUNET_DISK_PERM_NONE))) ||
552       (off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET)) ||
553       (-1 == (nsize = GNUNET_DISK_file_read (fh, ndata, sizeof (ndata)))))
554   {
555     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
556                 _
557                 ("Could not access indexed file `%s' (%s) at offset %llu: %s\n"),
558                 GNUNET_h2s (&odb->file_id), fn, (unsigned long long) off,
559                 (fn == NULL) ? _("not indexed") : STRERROR (errno));
560     if (fh != NULL)
561       GNUNET_DISK_file_close (fh);
562     GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1,
563                              GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
564     return GNUNET_SYSERR;
565   }
566   GNUNET_DISK_file_close (fh);
567   GNUNET_CRYPTO_hash (ndata, nsize, &nkey);
568   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
569   GNUNET_CRYPTO_aes_encrypt (ndata, nsize, &skey, &iv, edata);
570   GNUNET_CRYPTO_hash (edata, nsize, &query);
571   if (0 != memcmp (&query, key, sizeof (struct GNUNET_HashCode)))
572   {
573     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
574                 _("Indexed file `%s' changed at offset %llu\n"), fn,
575                 (unsigned long long) off);
576     GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1,
577                              GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
578     return GNUNET_SYSERR;
579   }
580   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
581               "On-demand encoded block for query `%s'\n", GNUNET_h2s (key));
582   cont (cont_cls, key, nsize, edata, GNUNET_BLOCK_TYPE_FS_DBLOCK, priority,
583         anonymity, expiration, uid);
584   return GNUNET_OK;
585 }
586
587
588 /**
589  * Shutdown the module.
590  */
591 void
592 GNUNET_FS_indexing_done ()
593 {
594   struct IndexInfo *pos;
595
596   while (NULL != (pos = indexed_files_head))
597   {
598     GNUNET_CONTAINER_DLL_remove (indexed_files_head,
599                                  indexed_files_tail,
600                                  pos);
601     if (pos->fhc != NULL)
602       GNUNET_CRYPTO_hash_file_cancel (pos->fhc);
603     GNUNET_break (GNUNET_OK ==
604                   GNUNET_CONTAINER_multihashmap_remove (ifm,
605                                                         &pos->file_id, pos));
606     GNUNET_free (pos);
607   }
608   GNUNET_CONTAINER_multihashmap_destroy (ifm);
609   ifm = NULL;
610   cfg = NULL;
611 }
612
613
614 /**
615  * Initialize the indexing submodule.
616  *
617  * @param c configuration to use
618  * @param d datastore to use
619  */
620 int
621 GNUNET_FS_indexing_init (const struct GNUNET_CONFIGURATION_Handle *c,
622                          struct GNUNET_DATASTORE_Handle *d)
623 {
624   cfg = c;
625   dsh = d;
626   ifm = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_YES);
627   read_index_list ();
628   return GNUNET_OK;
629 }
630
631 /* end of gnunet-service-fs_indexing.c */