Merge branch 'master' of ssh://gnunet.org/gnunet
[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 expiration expiration time for the content
270  * @param uid unique identifier for the datum;
271  *        maybe 0 if no unique identifier is available
272  * @param cont function to call with the actual block (at most once, on success)
273  * @param cont_cls closure for cont
274  * @return GNUNET_OK on success
275  */
276 int
277 GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode * key,
278                                   uint32_t size,
279                                   const void *data,
280                                   enum GNUNET_BLOCK_Type type,
281                                   uint32_t priority,
282                                   uint32_t anonymity,
283                                   struct GNUNET_TIME_Absolute expiration,
284                                   uint64_t uid,
285                                   GNUNET_DATASTORE_DatumProcessor cont,
286                                   void *cont_cls)
287 {
288   const struct OnDemandBlock *odb;
289   struct GNUNET_HashCode nkey;
290   struct GNUNET_CRYPTO_SymmetricSessionKey skey;
291   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
292   struct GNUNET_HashCode query;
293   ssize_t nsize;
294   char ndata[DBLOCK_SIZE];
295   char edata[DBLOCK_SIZE];
296   const char *fn;
297   struct GNUNET_DISK_FileHandle *fh;
298   uint64_t off;
299   struct IndexInfo *ii;
300
301   if (size != sizeof (struct OnDemandBlock))
302   {
303     GNUNET_break (0);
304     GNUNET_DATASTORE_remove (dsh,
305                              key,
306                              size,
307                              data,
308                              -1,
309                              -1,
310                              &remove_cont, NULL);
311     return GNUNET_SYSERR;
312   }
313   odb = (const struct OnDemandBlock *) data;
314   off = GNUNET_ntohll (odb->offset);
315   ii = GNUNET_CONTAINER_multihashmap_get (ifm,
316                                           &odb->file_id);
317   if (NULL == ii)
318   {
319     GNUNET_break (0);
320     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
321                 "Failed to find index %s\n",
322                 GNUNET_h2s (&odb->file_id));
323     return GNUNET_SYSERR;
324   }
325   fn = ii->filename;
326   if ((NULL == fn) || (0 != ACCESS (fn, R_OK)))
327   {
328     GNUNET_STATISTICS_update (GSF_stats,
329                               gettext_noop ("# index blocks removed: original file inaccessible"),
330                               1,
331                               GNUNET_YES);
332     GNUNET_DATASTORE_remove (dsh,
333                              key,
334                              size,
335                              data,
336                              -1,
337                              -1,
338                              &remove_cont,
339                              NULL);
340     return GNUNET_SYSERR;
341   }
342   if ( (NULL ==
343         (fh =
344          GNUNET_DISK_file_open (fn,
345                                 GNUNET_DISK_OPEN_READ,
346                                 GNUNET_DISK_PERM_NONE))) ||
347        (off != GNUNET_DISK_file_seek (fh,
348                                       off,
349                                       GNUNET_DISK_SEEK_SET)) ||
350       (-1 == (nsize = GNUNET_DISK_file_read (fh,
351                                              ndata,
352                                              sizeof (ndata)))) )
353   {
354     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
355                 _("Could not access indexed file `%s' (%s) at offset %llu: %s\n"),
356                 GNUNET_h2s (&odb->file_id),
357                 fn,
358                 (unsigned long long) off,
359                 (fn == NULL) ? _("not indexed") : STRERROR (errno));
360     if (fh != NULL)
361       GNUNET_DISK_file_close (fh);
362     GNUNET_DATASTORE_remove (dsh,
363                              key,
364                              size,
365                              data,
366                              -1,
367                              -1,
368                              &remove_cont,
369                              NULL);
370     return GNUNET_SYSERR;
371   }
372   GNUNET_DISK_file_close (fh);
373   GNUNET_CRYPTO_hash (ndata,
374                       nsize,
375                       &nkey);
376   GNUNET_CRYPTO_hash_to_aes_key (&nkey,
377                                  &skey,
378                                  &iv);
379   GNUNET_CRYPTO_symmetric_encrypt (ndata,
380                                    nsize,
381                                    &skey,
382                                    &iv,
383                                    edata);
384   GNUNET_CRYPTO_hash (edata,
385                       nsize,
386                       &query);
387   if (0 != memcmp (&query,
388                    key,
389                    sizeof (struct GNUNET_HashCode)))
390   {
391     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
392                 _("Indexed file `%s' changed at offset %llu\n"),
393                 fn,
394                 (unsigned long long) off);
395     GNUNET_DATASTORE_remove (dsh,
396                              key,
397                              size,
398                              data,
399                              -1,
400                              -1,
401                              &remove_cont,
402                              NULL);
403     return GNUNET_SYSERR;
404   }
405   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
406               "On-demand encoded block for query `%s'\n",
407               GNUNET_h2s (key));
408   cont (cont_cls,
409         key,
410         nsize,
411         edata,
412         GNUNET_BLOCK_TYPE_FS_DBLOCK,
413         priority,
414         anonymity,
415         expiration,
416         uid);
417   return GNUNET_OK;
418 }
419
420
421 /**
422  * Transmit information about indexed files to @a mq.
423  *
424  * @param mq message queue to send information to
425  */
426 void
427 GNUNET_FS_indexing_send_list (struct GNUNET_MQ_Handle *mq)
428 {
429   struct GNUNET_MQ_Envelope *env;
430   struct IndexInfoMessage *iim;
431   struct GNUNET_MessageHeader *iem;
432   size_t slen;
433   const char *fn;
434   struct IndexInfo *pos;
435
436   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
437   {
438     fn = pos->filename;
439     slen = strlen (fn) + 1;
440     if (slen + sizeof (struct IndexInfoMessage) >=
441         GNUNET_SERVER_MAX_MESSAGE_SIZE)
442     {
443       GNUNET_break (0);
444       break;
445     }
446     env = GNUNET_MQ_msg_extra (iim,
447                                slen,
448                                GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
449     iim->reserved = 0;
450     iim->file_id = pos->file_id;
451     GNUNET_memcpy (&iim[1],
452                    fn,
453                    slen);
454     GNUNET_MQ_send (mq,
455                     env);
456   }
457   env = GNUNET_MQ_msg (iem,
458                        GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
459   GNUNET_MQ_send (mq,
460                   env);
461 }
462
463
464 /**
465  * Remove a file from the index.
466  *
467  * @param fid identifier of the file to remove
468  * @return #GNUNET_YES if the @a fid was found
469  */
470 int
471 GNUNET_FS_indexing_do_unindex (const struct GNUNET_HashCode *fid)
472 {
473   struct IndexInfo *pos;
474
475   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
476   {
477     if (0 == memcmp (&pos->file_id,
478                      fid,
479                      sizeof (struct GNUNET_HashCode)))
480     {
481       GNUNET_CONTAINER_DLL_remove (indexed_files_head,
482                                    indexed_files_tail,
483                                    pos);
484       GNUNET_break (GNUNET_OK ==
485                     GNUNET_CONTAINER_multihashmap_remove (ifm,
486                                                           &pos->file_id,
487                                                           pos));
488       GNUNET_free (pos);
489       write_index_list ();
490       return GNUNET_YES;
491     }
492   }
493   return GNUNET_NO;
494 }
495
496
497 /**
498  * Add the given file to the list of indexed files.
499  *
500  * @param filename name of the file
501  * @param file_id hash identifier for @a filename
502  */
503 void
504 GNUNET_FS_add_to_index (const char *filename,
505                         const struct GNUNET_HashCode *file_id)
506 {
507   struct IndexInfo *ii;
508   size_t slen;
509
510   ii = GNUNET_CONTAINER_multihashmap_get (ifm,
511                                           file_id);
512   if (NULL != ii)
513   {
514     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
515                 _("Index request received for file `%s' is already indexed as `%s'.  Permitting anyway.\n"),
516                 filename,
517                 ii->filename);
518     return;
519   }
520   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
521               "Adding file %s to index as %s\n",
522               filename,
523               GNUNET_h2s (file_id));
524   slen = strlen (filename) + 1;
525   ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
526   ii->file_id = *file_id;
527   ii->filename = (const char *) &ii[1];
528   memcpy (&ii[1],
529           filename,
530           slen);
531   GNUNET_CONTAINER_DLL_insert (indexed_files_head,
532                                indexed_files_tail,
533                                ii);
534   GNUNET_assert (GNUNET_OK ==
535                  GNUNET_CONTAINER_multihashmap_put (ifm,
536                                                     &ii->file_id,
537                                                     ii,
538                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
539   write_index_list ();
540 }
541
542
543 /**
544  * Shutdown the module.
545  */
546 void
547 GNUNET_FS_indexing_done ()
548 {
549   struct IndexInfo *pos;
550
551   while (NULL != (pos = indexed_files_head))
552   {
553     GNUNET_CONTAINER_DLL_remove (indexed_files_head,
554                                  indexed_files_tail,
555                                  pos);
556     if (pos->fhc != NULL)
557       GNUNET_CRYPTO_hash_file_cancel (pos->fhc);
558     GNUNET_break (GNUNET_OK ==
559                   GNUNET_CONTAINER_multihashmap_remove (ifm,
560                                                         &pos->file_id,
561                                                         pos));
562     GNUNET_free (pos);
563   }
564   GNUNET_CONTAINER_multihashmap_destroy (ifm);
565   ifm = NULL;
566   cfg = NULL;
567 }
568
569
570 /**
571  * Initialize the indexing submodule.
572  *
573  * @param c configuration to use
574  * @param d datastore to use
575  */
576 int
577 GNUNET_FS_indexing_init (const struct GNUNET_CONFIGURATION_Handle *c,
578                          struct GNUNET_DATASTORE_Handle *d)
579 {
580   cfg = c;
581   dsh = d;
582   ifm = GNUNET_CONTAINER_multihashmap_create (128,
583                                               GNUNET_YES);
584   read_index_list ();
585   return GNUNET_OK;
586 }
587
588 /* end of gnunet-service-fs_indexing.c */