-fix records
[oweals/gnunet.git] / src / fs / gnunet-service-fs_indexing.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2010 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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  * FIXME: we don't need both a DLL and a hashmap here!
83  */
84 static struct IndexInfo *indexed_files_head;
85
86 /**
87  * Tail of linked list of indexed files.
88  */
89 static struct IndexInfo *indexed_files_tail;
90
91 /**
92  * Maps hash over content of indexed files to the respective 'struct IndexInfo'.
93  * The filenames are pointers into the indexed_files linked list and
94  * do not need to be freed.
95  */
96 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
97
98 /**
99  * Our configuration.
100  */
101 static const struct GNUNET_CONFIGURATION_Handle *cfg;
102
103 /**
104  * Datastore handle.  Created and destroyed by code in
105  * gnunet-service-fs (this is an alias).
106  */
107 static struct GNUNET_DATASTORE_Handle *dsh;
108
109
110 /**
111  * Write the current index information list to disk.
112  */
113 static void
114 write_index_list ()
115 {
116   struct GNUNET_BIO_WriteHandle *wh;
117   char *fn;
118   struct IndexInfo *pos;
119
120   if (GNUNET_OK !=
121       GNUNET_CONFIGURATION_get_value_filename (cfg, "FS",
122                                                "INDEXDB",
123                                                &fn))
124   {
125     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
126                                "fs",
127                                "INDEXDB");
128     return;
129   }
130   wh = GNUNET_BIO_write_open (fn);
131   if (NULL == wh)
132   {
133     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
134                 _("Could not open `%s'.\n"),
135                 fn);
136     GNUNET_free (fn);
137     return;
138   }
139   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
140     if ((GNUNET_OK !=
141          GNUNET_BIO_write (wh,
142                            &pos->file_id,
143                            sizeof (struct GNUNET_HashCode))) ||
144         (GNUNET_OK !=
145          GNUNET_BIO_write_string (wh,
146                                   pos->filename)))
147       break;
148   if (GNUNET_OK != GNUNET_BIO_write_close (wh))
149   {
150     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
151                 _("Error writing `%s'.\n"),
152                 fn);
153     GNUNET_free (fn);
154     return;
155   }
156   GNUNET_free (fn);
157 }
158
159
160 /**
161  * Read index information from disk.
162  */
163 static void
164 read_index_list ()
165 {
166   struct GNUNET_BIO_ReadHandle *rh;
167   char *fn;
168   struct IndexInfo *pos;
169   char *fname;
170   struct GNUNET_HashCode hc;
171   size_t slen;
172   char *emsg;
173
174   if (GNUNET_OK !=
175       GNUNET_CONFIGURATION_get_value_filename (cfg,
176                                                "FS",
177                                                "INDEXDB",
178                                                &fn))
179   {
180     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
181                                "fs",
182                                "INDEXDB");
183     return;
184   }
185   if (GNUNET_NO == GNUNET_DISK_file_test (fn))
186   {
187     /* no index info yet */
188     GNUNET_free (fn);
189     return;
190   }
191   rh = GNUNET_BIO_read_open (fn);
192   if (NULL == rh)
193   {
194     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
195                 _("Could not open `%s'.\n"),
196                 fn);
197     GNUNET_free (fn);
198     return;
199   }
200   while ( (GNUNET_OK ==
201            GNUNET_BIO_read (rh,
202                             "Hash of indexed file",
203                             &hc,
204                             sizeof (struct GNUNET_HashCode))) &&
205           (GNUNET_OK ==
206            GNUNET_BIO_read_string (rh,
207                                    "Name of indexed file",
208                                    &fname,
209                                    1024 * 16)) &&
210           (fname != NULL) )
211   {
212     slen = strlen (fname) + 1;
213     pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
214     pos->file_id = hc;
215     pos->filename = (const char *) &pos[1];
216     GNUNET_memcpy (&pos[1], fname, slen);
217     if (GNUNET_SYSERR ==
218         GNUNET_CONTAINER_multihashmap_put (ifm, &pos->file_id, pos,
219                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
220     {
221       GNUNET_free (pos);
222     }
223     else
224     {
225       GNUNET_CONTAINER_DLL_insert (indexed_files_head,
226                                    indexed_files_tail,
227                                    pos);
228     }
229     GNUNET_free (fname);
230   }
231   if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg))
232     GNUNET_free (emsg);
233   GNUNET_free (fn);
234 }
235
236
237 /**
238  * Continuation called from datastore's remove
239  * function.
240  *
241  * @param cls unused
242  * @param success did the deletion work?
243  * @param min_expiration minimum expiration time required for content to be stored
244  * @param msg error message
245  */
246 static void
247 remove_cont (void *cls, int success,
248              struct GNUNET_TIME_Absolute min_expiration,
249              const char *msg)
250 {
251   if (GNUNET_OK != success)
252     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
253                 _("Failed to delete bogus block: %s\n"), msg);
254 }
255
256
257 /**
258  * We've received an on-demand encoded block from the datastore.
259  * Attempt to do on-demand encoding and (if successful), call the
260  * continuation with the resulting block.  On error, clean up and ask
261  * the datastore for more results.
262  *
263  * @param key key for the content
264  * @param size number of bytes in data
265  * @param data content stored
266  * @param type type of the content
267  * @param priority priority of the content
268  * @param anonymity anonymity-level for the content
269  * @param replication replication-level for the content
270  * @param expiration expiration time for the content
271  * @param uid unique identifier for the datum;
272  *        maybe 0 if no unique identifier is available
273  * @param cont function to call with the actual block (at most once, on success)
274  * @param cont_cls closure for cont
275  * @return GNUNET_OK on success
276  */
277 int
278 GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode * key,
279                                   uint32_t size,
280                                   const void *data,
281                                   enum GNUNET_BLOCK_Type type,
282                                   uint32_t priority,
283                                   uint32_t anonymity,
284                                   uint32_t replication,
285                                   struct GNUNET_TIME_Absolute expiration,
286                                   uint64_t uid,
287                                   GNUNET_DATASTORE_DatumProcessor cont,
288                                   void *cont_cls)
289 {
290   const struct OnDemandBlock *odb;
291   struct GNUNET_HashCode nkey;
292   struct GNUNET_CRYPTO_SymmetricSessionKey skey;
293   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
294   struct GNUNET_HashCode query;
295   ssize_t nsize;
296   char ndata[DBLOCK_SIZE];
297   char edata[DBLOCK_SIZE];
298   const char *fn;
299   struct GNUNET_DISK_FileHandle *fh;
300   uint64_t off;
301   struct IndexInfo *ii;
302
303   if (size != sizeof (struct OnDemandBlock))
304   {
305     GNUNET_break (0);
306     GNUNET_DATASTORE_remove (dsh,
307                              key,
308                              size,
309                              data,
310                              -1,
311                              -1,
312                              &remove_cont, NULL);
313     return GNUNET_SYSERR;
314   }
315   odb = (const struct OnDemandBlock *) data;
316   off = GNUNET_ntohll (odb->offset);
317   ii = GNUNET_CONTAINER_multihashmap_get (ifm,
318                                           &odb->file_id);
319   if (NULL == ii)
320   {
321     GNUNET_break (0);
322     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
323                 "Failed to find index %s\n",
324                 GNUNET_h2s (&odb->file_id));
325     return GNUNET_SYSERR;
326   }
327   fn = ii->filename;
328   if ((NULL == fn) || (0 != ACCESS (fn, R_OK)))
329   {
330     GNUNET_STATISTICS_update (GSF_stats,
331                               gettext_noop ("# index blocks removed: original file inaccessible"),
332                               1,
333                               GNUNET_YES);
334     GNUNET_DATASTORE_remove (dsh,
335                              key,
336                              size,
337                              data,
338                              -1,
339                              -1,
340                              &remove_cont,
341                              NULL);
342     return GNUNET_SYSERR;
343   }
344   if ( (NULL ==
345         (fh =
346          GNUNET_DISK_file_open (fn,
347                                 GNUNET_DISK_OPEN_READ,
348                                 GNUNET_DISK_PERM_NONE))) ||
349        (off != GNUNET_DISK_file_seek (fh,
350                                       off,
351                                       GNUNET_DISK_SEEK_SET)) ||
352       (-1 == (nsize = GNUNET_DISK_file_read (fh,
353                                              ndata,
354                                              sizeof (ndata)))) )
355   {
356     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
357                 _("Could not access indexed file `%s' (%s) at offset %llu: %s\n"),
358                 GNUNET_h2s (&odb->file_id),
359                 fn,
360                 (unsigned long long) off,
361                 (fn == NULL) ? _("not indexed") : STRERROR (errno));
362     if (fh != NULL)
363       GNUNET_DISK_file_close (fh);
364     GNUNET_DATASTORE_remove (dsh,
365                              key,
366                              size,
367                              data,
368                              -1,
369                              -1,
370                              &remove_cont,
371                              NULL);
372     return GNUNET_SYSERR;
373   }
374   GNUNET_DISK_file_close (fh);
375   GNUNET_CRYPTO_hash (ndata,
376                       nsize,
377                       &nkey);
378   GNUNET_CRYPTO_hash_to_aes_key (&nkey,
379                                  &skey,
380                                  &iv);
381   GNUNET_CRYPTO_symmetric_encrypt (ndata,
382                                    nsize,
383                                    &skey,
384                                    &iv,
385                                    edata);
386   GNUNET_CRYPTO_hash (edata,
387                       nsize,
388                       &query);
389   if (0 != memcmp (&query,
390                    key,
391                    sizeof (struct GNUNET_HashCode)))
392   {
393     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
394                 _("Indexed file `%s' changed at offset %llu\n"),
395                 fn,
396                 (unsigned long long) off);
397     GNUNET_DATASTORE_remove (dsh,
398                              key,
399                              size,
400                              data,
401                              -1,
402                              -1,
403                              &remove_cont,
404                              NULL);
405     return GNUNET_SYSERR;
406   }
407   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
408               "On-demand encoded block for query `%s'\n",
409               GNUNET_h2s (key));
410   cont (cont_cls,
411         key,
412         nsize,
413         edata,
414         GNUNET_BLOCK_TYPE_FS_DBLOCK,
415         priority,
416         anonymity,
417         replication,
418         expiration,
419         uid);
420   return GNUNET_OK;
421 }
422
423
424 /**
425  * Transmit information about indexed files to @a mq.
426  *
427  * @param mq message queue to send information to
428  */
429 void
430 GNUNET_FS_indexing_send_list (struct GNUNET_MQ_Handle *mq)
431 {
432   struct GNUNET_MQ_Envelope *env;
433   struct IndexInfoMessage *iim;
434   struct GNUNET_MessageHeader *iem;
435   size_t slen;
436   const char *fn;
437   struct IndexInfo *pos;
438
439   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
440   {
441     fn = pos->filename;
442     slen = strlen (fn) + 1;
443     if (slen + sizeof (struct IndexInfoMessage) >=
444         GNUNET_MAX_MESSAGE_SIZE)
445     {
446       GNUNET_break (0);
447       break;
448     }
449     env = GNUNET_MQ_msg_extra (iim,
450                                slen,
451                                GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
452     iim->reserved = 0;
453     iim->file_id = pos->file_id;
454     GNUNET_memcpy (&iim[1],
455                    fn,
456                    slen);
457     GNUNET_MQ_send (mq,
458                     env);
459   }
460   env = GNUNET_MQ_msg (iem,
461                        GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
462   GNUNET_MQ_send (mq,
463                   env);
464 }
465
466
467 /**
468  * Remove a file from the index.
469  *
470  * @param fid identifier of the file to remove
471  * @return #GNUNET_YES if the @a fid was found
472  */
473 int
474 GNUNET_FS_indexing_do_unindex (const struct GNUNET_HashCode *fid)
475 {
476   struct IndexInfo *pos;
477
478   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
479   {
480     if (0 == memcmp (&pos->file_id,
481                      fid,
482                      sizeof (struct GNUNET_HashCode)))
483     {
484       GNUNET_CONTAINER_DLL_remove (indexed_files_head,
485                                    indexed_files_tail,
486                                    pos);
487       GNUNET_break (GNUNET_OK ==
488                     GNUNET_CONTAINER_multihashmap_remove (ifm,
489                                                           &pos->file_id,
490                                                           pos));
491       GNUNET_free (pos);
492       write_index_list ();
493       return GNUNET_YES;
494     }
495   }
496   return GNUNET_NO;
497 }
498
499
500 /**
501  * Add the given file to the list of indexed files.
502  *
503  * @param filename name of the file
504  * @param file_id hash identifier for @a filename
505  */
506 void
507 GNUNET_FS_add_to_index (const char *filename,
508                         const struct GNUNET_HashCode *file_id)
509 {
510   struct IndexInfo *ii;
511   size_t slen;
512
513   ii = GNUNET_CONTAINER_multihashmap_get (ifm,
514                                           file_id);
515   if (NULL != ii)
516   {
517     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
518                 _("Index request received for file `%s' is already indexed as `%s'.  Permitting anyway.\n"),
519                 filename,
520                 ii->filename);
521     return;
522   }
523   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
524               "Adding file %s to index as %s\n",
525               filename,
526               GNUNET_h2s (file_id));
527   slen = strlen (filename) + 1;
528   ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
529   ii->file_id = *file_id;
530   ii->filename = (const char *) &ii[1];
531   memcpy (&ii[1],
532           filename,
533           slen);
534   GNUNET_CONTAINER_DLL_insert (indexed_files_head,
535                                indexed_files_tail,
536                                ii);
537   GNUNET_assert (GNUNET_OK ==
538                  GNUNET_CONTAINER_multihashmap_put (ifm,
539                                                     &ii->file_id,
540                                                     ii,
541                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
542   write_index_list ();
543 }
544
545
546 /**
547  * Shutdown the module.
548  */
549 void
550 GNUNET_FS_indexing_done ()
551 {
552   struct IndexInfo *pos;
553
554   while (NULL != (pos = indexed_files_head))
555   {
556     GNUNET_CONTAINER_DLL_remove (indexed_files_head,
557                                  indexed_files_tail,
558                                  pos);
559     if (pos->fhc != NULL)
560       GNUNET_CRYPTO_hash_file_cancel (pos->fhc);
561     GNUNET_break (GNUNET_OK ==
562                   GNUNET_CONTAINER_multihashmap_remove (ifm,
563                                                         &pos->file_id,
564                                                         pos));
565     GNUNET_free (pos);
566   }
567   GNUNET_CONTAINER_multihashmap_destroy (ifm);
568   ifm = NULL;
569   cfg = NULL;
570 }
571
572
573 /**
574  * Initialize the indexing submodule.
575  *
576  * @param c configuration to use
577  * @param d datastore to use
578  */
579 int
580 GNUNET_FS_indexing_init (const struct GNUNET_CONFIGURATION_Handle *c,
581                          struct GNUNET_DATASTORE_Handle *d)
582 {
583   cfg = c;
584   dsh = d;
585   ifm = GNUNET_CONTAINER_multihashmap_create (128,
586                                               GNUNET_YES);
587   read_index_list ();
588   return GNUNET_OK;
589 }
590
591 /* end of gnunet-service-fs_indexing.c */