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