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