tighten formatting rules
[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 it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
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    * This is a doubly linked list.
46    */
47   struct IndexInfo *next;
48
49   /**
50    * This is a doubly linked list.
51    */
52   struct IndexInfo *prev;
53
54   /**
55    * Name of the indexed file.  Memory allocated
56    * at the end of this struct (do not free).
57    */
58   const char *filename;
59
60   /**
61    * Context for transmitting confirmation to client,
62    * NULL if we've done this already.
63    */
64   struct GNUNET_SERVER_TransmitContext *tc;
65
66   /**
67    * Context for hashing of the file.
68    */
69   struct GNUNET_CRYPTO_FileHashContext *fhc;
70
71   /**
72    * Hash of the contents of the file.
73    */
74   struct GNUNET_HashCode file_id;
75 };
76
77
78 /**
79  * Head of linked list of indexed files.
80  * FIXME: we don't need both a DLL and a hashmap here!
81  */
82 static struct IndexInfo *indexed_files_head;
83
84 /**
85  * Tail of linked list of indexed files.
86  */
87 static struct IndexInfo *indexed_files_tail;
88
89 /**
90  * Maps hash over content of indexed files to the respective 'struct IndexInfo'.
91  * The filenames are pointers into the indexed_files linked list and
92  * do not need to be freed.
93  */
94 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
95
96 /**
97  * Our configuration.
98  */
99 static const struct GNUNET_CONFIGURATION_Handle *cfg;
100
101 /**
102  * Datastore handle.  Created and destroyed by code in
103  * gnunet-service-fs (this is an alias).
104  */
105 static struct GNUNET_DATASTORE_Handle *dsh;
106
107
108 /**
109  * Write the current index information list to disk.
110  */
111 static void
112 write_index_list ()
113 {
114   struct GNUNET_BIO_WriteHandle *wh;
115   char *fn;
116   struct IndexInfo *pos;
117
118   if (GNUNET_OK !=
119       GNUNET_CONFIGURATION_get_value_filename (cfg, "FS", "INDEXDB", &fn))
120   {
121     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
122                                "fs",
123                                "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"),
131                 fn);
132     GNUNET_free (fn);
133     return;
134   }
135   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
136     if ((GNUNET_OK != GNUNET_BIO_write (wh,
137                                         &pos->file_id,
138                                         sizeof(struct GNUNET_HashCode))) ||
139         (GNUNET_OK != GNUNET_BIO_write_string (wh, pos->filename)))
140       break;
141   if (GNUNET_OK != GNUNET_BIO_write_close (wh))
142   {
143     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
144                 _ ("Error writing `%s'.\n"),
145                 fn);
146     GNUNET_free (fn);
147     return;
148   }
149   GNUNET_free (fn);
150 }
151
152
153 /**
154  * Read index information from disk.
155  */
156 static void
157 read_index_list ()
158 {
159   struct GNUNET_BIO_ReadHandle *rh;
160   char *fn;
161   struct IndexInfo *pos;
162   char *fname;
163   struct GNUNET_HashCode hc;
164   size_t slen;
165   char *emsg;
166
167   if (GNUNET_OK !=
168       GNUNET_CONFIGURATION_get_value_filename (cfg, "FS", "INDEXDB", &fn))
169   {
170     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
171                                "fs",
172                                "INDEXDB");
173     return;
174   }
175   if (GNUNET_NO == GNUNET_DISK_file_test (fn))
176   {
177     /* no index info yet */
178     GNUNET_free (fn);
179     return;
180   }
181   rh = GNUNET_BIO_read_open (fn);
182   if (NULL == rh)
183   {
184     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
185                 _ ("Could not open `%s'.\n"),
186                 fn);
187     GNUNET_free (fn);
188     return;
189   }
190   while (
191     (GNUNET_OK == GNUNET_BIO_read (rh,
192                                    "Hash of indexed file",
193                                    &hc,
194                                    sizeof(struct GNUNET_HashCode))) &&
195     (GNUNET_OK ==
196      GNUNET_BIO_read_string (rh, "Name of indexed file", &fname, 1024 * 16)) &&
197     (fname != NULL))
198   {
199     slen = strlen (fname) + 1;
200     pos = GNUNET_malloc (sizeof(struct IndexInfo) + slen);
201     pos->file_id = hc;
202     pos->filename = (const char *) &pos[1];
203     GNUNET_memcpy (&pos[1], fname, slen);
204     if (GNUNET_SYSERR == GNUNET_CONTAINER_multihashmap_put (
205           ifm,
206           &pos->file_id,
207           pos,
208           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
209     {
210       GNUNET_free (pos);
211     }
212     else
213     {
214       GNUNET_CONTAINER_DLL_insert (indexed_files_head, indexed_files_tail, pos);
215     }
216     GNUNET_free (fname);
217   }
218   if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg))
219     GNUNET_free (emsg);
220   GNUNET_free (fn);
221 }
222
223
224 /**
225  * Continuation called from datastore's remove
226  * function.
227  *
228  * @param cls unused
229  * @param success did the deletion work?
230  * @param min_expiration minimum expiration time required for content to be stored
231  * @param msg error message
232  */
233 static void
234 remove_cont (void *cls,
235              int success,
236              struct GNUNET_TIME_Absolute min_expiration,
237              const char *msg)
238 {
239   if (GNUNET_OK != success)
240     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
241                 _ ("Failed to delete bogus block: %s\n"),
242                 msg);
243 }
244
245
246 /**
247  * We've received an on-demand encoded block from the datastore.
248  * Attempt to do on-demand encoding and (if successful), call the
249  * continuation with the resulting block.  On error, clean up and ask
250  * the datastore for more results.
251  *
252  * @param key key for the content
253  * @param size number of bytes in data
254  * @param data content stored
255  * @param type type of the content
256  * @param priority priority of the content
257  * @param anonymity anonymity-level for the content
258  * @param replication replication-level for the content
259  * @param expiration expiration time for the content
260  * @param uid unique identifier for the datum;
261  *        maybe 0 if no unique identifier is available
262  * @param cont function to call with the actual block (at most once, on success)
263  * @param cont_cls closure for cont
264  * @return GNUNET_OK on success
265  */
266 int
267 GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode *key,
268                                   uint32_t size,
269                                   const void *data,
270                                   enum GNUNET_BLOCK_Type type,
271                                   uint32_t priority,
272                                   uint32_t anonymity,
273                                   uint32_t replication,
274                                   struct GNUNET_TIME_Absolute expiration,
275                                   uint64_t uid,
276                                   GNUNET_DATASTORE_DatumProcessor cont,
277                                   void *cont_cls)
278 {
279   const struct OnDemandBlock *odb;
280   struct GNUNET_HashCode nkey;
281   struct GNUNET_CRYPTO_SymmetricSessionKey skey;
282   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
283   struct GNUNET_HashCode query;
284   ssize_t nsize;
285   char ndata[DBLOCK_SIZE];
286   char edata[DBLOCK_SIZE];
287   const char *fn;
288   struct GNUNET_DISK_FileHandle *fh;
289   uint64_t off;
290   struct IndexInfo *ii;
291
292   if (size != sizeof(struct OnDemandBlock))
293   {
294     GNUNET_break (0);
295     GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1, &remove_cont, NULL);
296     return GNUNET_SYSERR;
297   }
298   odb = (const struct OnDemandBlock *) data;
299   off = GNUNET_ntohll (odb->offset);
300   ii = GNUNET_CONTAINER_multihashmap_get (ifm, &odb->file_id);
301   if (NULL == ii)
302   {
303     GNUNET_break (0);
304     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
305                 "Failed to find index %s\n",
306                 GNUNET_h2s (&odb->file_id));
307     return GNUNET_SYSERR;
308   }
309   fn = ii->filename;
310   if ((NULL == fn) || (0 != access (fn, R_OK)))
311   {
312     GNUNET_STATISTICS_update (
313       GSF_stats,
314       gettext_noop ("# index blocks removed: original file inaccessible"),
315       1,
316       GNUNET_YES);
317     GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1, &remove_cont, NULL);
318     return GNUNET_SYSERR;
319   }
320   if ((NULL == (fh = GNUNET_DISK_file_open (fn,
321                                             GNUNET_DISK_OPEN_READ,
322                                             GNUNET_DISK_PERM_NONE))) ||
323       (off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET)) ||
324       (-1 == (nsize = GNUNET_DISK_file_read (fh, ndata, sizeof(ndata)))))
325   {
326     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
327                 _ (
328                   "Could not access indexed file `%s' (%s) at offset %llu: %s\n"),
329                 GNUNET_h2s (&odb->file_id),
330                 fn,
331                 (unsigned long long) off,
332                 (fn == NULL) ? _ ("not indexed") : strerror (errno));
333     if (fh != NULL)
334       GNUNET_DISK_file_close (fh);
335     GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1, &remove_cont, NULL);
336     return GNUNET_SYSERR;
337   }
338   GNUNET_DISK_file_close (fh);
339   GNUNET_CRYPTO_hash (ndata, nsize, &nkey);
340   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
341   GNUNET_CRYPTO_symmetric_encrypt (ndata, nsize, &skey, &iv, edata);
342   GNUNET_CRYPTO_hash (edata, nsize, &query);
343   if (0 != memcmp (&query, key, sizeof(struct GNUNET_HashCode)))
344   {
345     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
346                 _ ("Indexed file `%s' changed at offset %llu\n"),
347                 fn,
348                 (unsigned long long) off);
349     GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1, &remove_cont, NULL);
350     return GNUNET_SYSERR;
351   }
352   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
353               "On-demand encoded block for query `%s'\n",
354               GNUNET_h2s (key));
355   cont (cont_cls,
356         key,
357         nsize,
358         edata,
359         GNUNET_BLOCK_TYPE_FS_DBLOCK,
360         priority,
361         anonymity,
362         replication,
363         expiration,
364         uid);
365   return GNUNET_OK;
366 }
367
368
369 /**
370  * Transmit information about indexed files to @a mq.
371  *
372  * @param mq message queue to send information to
373  */
374 void
375 GNUNET_FS_indexing_send_list (struct GNUNET_MQ_Handle *mq)
376 {
377   struct GNUNET_MQ_Envelope *env;
378   struct IndexInfoMessage *iim;
379   struct GNUNET_MessageHeader *iem;
380   size_t slen;
381   const char *fn;
382   struct IndexInfo *pos;
383
384   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
385   {
386     fn = pos->filename;
387     slen = strlen (fn) + 1;
388     if (slen + sizeof(struct IndexInfoMessage) >= GNUNET_MAX_MESSAGE_SIZE)
389     {
390       GNUNET_break (0);
391       break;
392     }
393     env =
394       GNUNET_MQ_msg_extra (iim, slen, GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
395     iim->reserved = 0;
396     iim->file_id = pos->file_id;
397     GNUNET_memcpy (&iim[1], fn, slen);
398     GNUNET_MQ_send (mq, env);
399   }
400   env = GNUNET_MQ_msg (iem, GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
401   GNUNET_MQ_send (mq, env);
402 }
403
404
405 /**
406  * Remove a file from the index.
407  *
408  * @param fid identifier of the file to remove
409  * @return #GNUNET_YES if the @a fid was found
410  */
411 int
412 GNUNET_FS_indexing_do_unindex (const struct GNUNET_HashCode *fid)
413 {
414   struct IndexInfo *pos;
415
416   for (pos = indexed_files_head; NULL != pos; pos = pos->next)
417   {
418     if (0 == memcmp (&pos->file_id, fid, sizeof(struct GNUNET_HashCode)))
419     {
420       GNUNET_CONTAINER_DLL_remove (indexed_files_head, indexed_files_tail, pos);
421       GNUNET_break (
422         GNUNET_OK ==
423         GNUNET_CONTAINER_multihashmap_remove (ifm, &pos->file_id, pos));
424       GNUNET_free (pos);
425       write_index_list ();
426       return GNUNET_YES;
427     }
428   }
429   return GNUNET_NO;
430 }
431
432
433 /**
434  * Add the given file to the list of indexed files.
435  *
436  * @param filename name of the file
437  * @param file_id hash identifier for @a filename
438  */
439 void
440 GNUNET_FS_add_to_index (const char *filename,
441                         const struct GNUNET_HashCode *file_id)
442 {
443   struct IndexInfo *ii;
444   size_t slen;
445
446   ii = GNUNET_CONTAINER_multihashmap_get (ifm, file_id);
447   if (NULL != ii)
448   {
449     GNUNET_log (
450       GNUNET_ERROR_TYPE_INFO,
451       _ (
452         "Index request received for file `%s' is already indexed as `%s'.  Permitting anyway.\n"),
453       filename,
454       ii->filename);
455     return;
456   }
457   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
458               "Adding file %s to index as %s\n",
459               filename,
460               GNUNET_h2s (file_id));
461   slen = strlen (filename) + 1;
462   ii = GNUNET_malloc (sizeof(struct IndexInfo) + slen);
463   ii->file_id = *file_id;
464   ii->filename = (const char *) &ii[1];
465   GNUNET_memcpy (&ii[1], filename, slen);
466   GNUNET_CONTAINER_DLL_insert (indexed_files_head, indexed_files_tail, ii);
467   GNUNET_assert (GNUNET_OK ==
468                  GNUNET_CONTAINER_multihashmap_put (
469                    ifm,
470                    &ii->file_id,
471                    ii,
472                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
473   write_index_list ();
474 }
475
476
477 /**
478  * Shutdown the module.
479  */
480 void
481 GNUNET_FS_indexing_done ()
482 {
483   struct IndexInfo *pos;
484
485   while (NULL != (pos = indexed_files_head))
486   {
487     GNUNET_CONTAINER_DLL_remove (indexed_files_head, indexed_files_tail, pos);
488     if (pos->fhc != NULL)
489       GNUNET_CRYPTO_hash_file_cancel (pos->fhc);
490     GNUNET_break (
491       GNUNET_OK ==
492       GNUNET_CONTAINER_multihashmap_remove (ifm, &pos->file_id, pos));
493     GNUNET_free (pos);
494   }
495   GNUNET_CONTAINER_multihashmap_destroy (ifm);
496   ifm = NULL;
497   cfg = NULL;
498 }
499
500
501 /**
502  * Initialize the indexing submodule.
503  *
504  * @param c configuration to use
505  * @param d datastore to use
506  */
507 int
508 GNUNET_FS_indexing_init (const struct GNUNET_CONFIGURATION_Handle *c,
509                          struct GNUNET_DATASTORE_Handle *d)
510 {
511   cfg = c;
512   dsh = d;
513   ifm = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_YES);
514   read_index_list ();
515   return GNUNET_OK;
516 }
517
518
519 /* end of gnunet-service-fs_indexing.c */