-fix #2598
[oweals/gnunet.git] / src / fs / gnunet-service-fs.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 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.c
23  * @brief gnunet anonymity protocol implementation
24  * @author Christian Grothoff
25  *
26  * To use:
27  * - consider re-issue GSF_dht_lookup_ after non-DHT reply received
28  */
29 #include "platform.h"
30 #include <float.h>
31 #include "gnunet_constants.h"
32 #include "gnunet_core_service.h"
33 #include "gnunet_dht_service.h"
34 #include "gnunet_datastore_service.h"
35 #include "gnunet_load_lib.h"
36 #include "gnunet_peer_lib.h"
37 #include "gnunet_protocols.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet_transport_service.h"
41 #include "gnunet_util_lib.h"
42 #include "gnunet-service-fs_cp.h"
43 #include "gnunet-service-fs_indexing.h"
44 #include "gnunet-service-fs_lc.h"
45 #include "gnunet-service-fs_pe.h"
46 #include "gnunet-service-fs_pr.h"
47 #include "gnunet-service-fs_push.h"
48 #include "gnunet-service-fs_put.h"
49 #include "fs.h"
50
51 /**
52  * Size for the hash map for DHT requests from the FS
53  * service.  Should be about the number of concurrent
54  * DHT requests we plan to make.
55  */
56 #define FS_DHT_HT_SIZE 1024
57
58
59 /**
60  * How quickly do we age cover traffic?  At the given
61  * time interval, remaining cover traffic counters are
62  * decremented by 1/16th.
63  */
64 #define COVER_AGE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
65
66 /**
67  * Collect an instane number of statistics?  May cause excessive IPC.
68  */
69 #define INSANE_STATISTICS GNUNET_NO
70
71
72 /* ****************************** globals ****************************** */
73
74 /**
75  * Our connection to the datastore.
76  */
77 struct GNUNET_DATASTORE_Handle *GSF_dsh;
78
79 /**
80  * Our configuration.
81  */
82 const struct GNUNET_CONFIGURATION_Handle *GSF_cfg;
83
84 /**
85  * Handle for reporting statistics.
86  */
87 struct GNUNET_STATISTICS_Handle *GSF_stats;
88
89 /**
90  * Handle for DHT operations.
91  */
92 struct GNUNET_DHT_Handle *GSF_dht;
93
94 /**
95  * How long do requests typically stay in the routing table?
96  */
97 struct GNUNET_LOAD_Value *GSF_rt_entry_lifetime;
98
99 /**
100  * Running average of the observed latency to other peers (round trip).
101  * Initialized to 5s as the initial default.
102  */
103 struct GNUNET_TIME_Relative GSF_avg_latency = { 500 };
104
105 /**
106  * Typical priorities we're seeing from other peers right now.  Since
107  * most priorities will be zero, this value is the weighted average of
108  * non-zero priorities seen "recently".  In order to ensure that new
109  * values do not dramatically change the ratio, values are first
110  * "capped" to a reasonable range (+N of the current value) and then
111  * averaged into the existing value by a ratio of 1:N.  Hence
112  * receiving the largest possible priority can still only raise our
113  * "current_priorities" by at most 1.
114  */
115 double GSF_current_priorities;
116
117 /**
118  * How many query messages have we received 'recently' that
119  * have not yet been claimed as cover traffic?
120  */
121 unsigned int GSF_cover_query_count;
122
123 /**
124  * How many content messages have we received 'recently' that
125  * have not yet been claimed as cover traffic?
126  */
127 unsigned int GSF_cover_content_count;
128
129 /**
130  * Our block context.
131  */
132 struct GNUNET_BLOCK_Context *GSF_block_ctx;
133
134 /**
135  * Pointer to handle to the core service (points to NULL until we've
136  * connected to it).
137  */
138 struct GNUNET_CORE_Handle *GSF_core;
139
140 /**
141  * Are we introducing randomized delays for better anonymity?
142  */
143 int GSF_enable_randomized_delays;
144
145 /* ***************************** locals ******************************* */
146
147 /**
148  * Configuration for block library.
149  */
150 static struct GNUNET_CONFIGURATION_Handle *block_cfg;
151
152 /**
153  * ID of our task that we use to age the cover counters.
154  */
155 static GNUNET_SCHEDULER_TaskIdentifier cover_age_task;
156
157 /**
158  * Datastore 'GET' load tracking.
159  */
160 static struct GNUNET_LOAD_Value *datastore_get_load;
161
162 /**
163  * Identity of this peer.
164  */
165 static struct GNUNET_PeerIdentity my_id;
166
167 /**
168  * Task that periodically ages our cover traffic statistics.
169  *
170  * @param cls unused closure
171  * @param tc task context
172  */
173 static void
174 age_cover_counters (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
175 {
176   GSF_cover_content_count = (GSF_cover_content_count * 15) / 16;
177   GSF_cover_query_count = (GSF_cover_query_count * 15) / 16;
178   cover_age_task =
179       GNUNET_SCHEDULER_add_delayed (COVER_AGE_FREQUENCY, &age_cover_counters,
180                                     NULL);
181 }
182
183
184 /**
185  * We've just now completed a datastore request.  Update our
186  * datastore load calculations.
187  *
188  * @param start time when the datastore request was issued
189  */
190 void
191 GSF_update_datastore_delay_ (struct GNUNET_TIME_Absolute start)
192 {
193   struct GNUNET_TIME_Relative delay;
194
195   delay = GNUNET_TIME_absolute_get_duration (start);
196   GNUNET_LOAD_update (datastore_get_load, delay.rel_value);
197 }
198
199
200 /**
201  * Test if the DATABASE (GET) load on this peer is too high
202  * to even consider processing the query at
203  * all.
204  *
205  * @return GNUNET_YES if the load is too high to do anything (load high)
206  *         GNUNET_NO to process normally (load normal)
207  *         GNUNET_SYSERR to process for free (load low)
208  */
209 int
210 GSF_test_get_load_too_high_ (uint32_t priority)
211 {
212   double ld;
213
214   ld = GNUNET_LOAD_get_load (datastore_get_load);
215   if (ld < 1)
216     return GNUNET_SYSERR;
217   if (ld <= priority)
218     return GNUNET_NO;
219   return GNUNET_YES;
220 }
221
222
223 /**
224  * We've received peer performance information. Update
225  * our running average for the P2P latency.
226  *
227  * @param atsi performance information
228  * @param atsi_count number of 'atsi' records
229  */
230 static void
231 update_latencies (const struct GNUNET_ATS_Information *atsi,
232                   unsigned int atsi_count)
233 {
234   unsigned int i;
235
236   for (i = 0; i < atsi_count; i++)
237   {
238     if (ntohl (atsi[i].type) == GNUNET_ATS_QUALITY_NET_DELAY)
239     {
240       GSF_avg_latency.rel_value =
241           (GSF_avg_latency.rel_value * 31 +
242            GNUNET_MIN (5000, ntohl (atsi[i].value))) / 32;
243       GNUNET_STATISTICS_set (GSF_stats,
244                              gettext_noop
245                              ("# running average P2P latency (ms)"),
246                              GSF_avg_latency.rel_value, GNUNET_NO);
247       break;
248     }
249   }
250 }
251
252
253 /**
254  * Handle P2P "PUT" message.
255  *
256  * @param cls closure, always NULL
257  * @param other the other peer involved (sender or receiver, NULL
258  *        for loopback messages where we are both sender and receiver)
259  * @param message the actual message
260  * @param atsi performance information
261  * @param atsi_count number of records in 'atsi'
262  * @return GNUNET_OK to keep the connection open,
263  *         GNUNET_SYSERR to close it (signal serious error)
264  */
265 static int
266 handle_p2p_put (void *cls, const struct GNUNET_PeerIdentity *other,
267                 const struct GNUNET_MessageHeader *message,
268                 const struct GNUNET_ATS_Information *atsi,
269                 unsigned int atsi_count)
270 {
271   struct GSF_ConnectedPeer *cp;
272
273   cp = GSF_peer_get_ (other);
274   if (NULL == cp)
275   {
276     GNUNET_break (0);
277     return GNUNET_OK;
278   }
279   GSF_cover_content_count++;
280   update_latencies (atsi, atsi_count);
281   return GSF_handle_p2p_content_ (cp, message);
282 }
283
284
285 /**
286  * We have a new request, consider forwarding it to the given
287  * peer.
288  *
289  * @param cls the 'struct GSF_PendingRequest'
290  * @param peer identity of the peer
291  * @param cp handle to the connected peer record
292  * @param ppd peer performance data
293  */
294 static void
295 consider_request_for_forwarding (void *cls,
296                                  const struct GNUNET_PeerIdentity *peer,
297                                  struct GSF_ConnectedPeer *cp,
298                                  const struct GSF_PeerPerformanceData *ppd)
299 {
300   struct GSF_PendingRequest *pr = cls;
301
302   if (GNUNET_YES != GSF_pending_request_test_target_ (pr, peer))
303   {
304 #if INSANE_STATISTICS
305     GNUNET_STATISTICS_update (GSF_stats,
306                               gettext_noop ("# Loopback routes suppressed"), 1,
307                               GNUNET_NO);
308 #endif
309     return;
310   }
311   GSF_plan_add_ (cp, pr);
312 }
313
314
315 /**
316  * Function to be called after we're done processing
317  * replies from the local lookup.  If the result status
318  * code indicates that there may be more replies, plan
319  * forwarding the request.
320  *
321  * @param cls closure (NULL)
322  * @param pr the pending request we were processing
323  * @param result final datastore lookup result
324  */
325 static void
326 consider_forwarding (void *cls, struct GSF_PendingRequest *pr,
327                      enum GNUNET_BLOCK_EvaluationResult result)
328 {
329   if (GNUNET_BLOCK_EVALUATION_OK_LAST == result)
330     return;                     /* we're done... */
331   GSF_iterate_connected_peers_ (&consider_request_for_forwarding, pr);
332 }
333
334
335 /**
336  * Handle P2P "GET" request.
337  *
338  * @param cls closure, always NULL
339  * @param other the other peer involved (sender or receiver, NULL
340  *        for loopback messages where we are both sender and receiver)
341  * @param message the actual message
342  * @param atsi performance information
343  * @param atsi_count number of records in 'atsi'
344  * @return GNUNET_OK to keep the connection open,
345  *         GNUNET_SYSERR to close it (signal serious error)
346  */
347 static int
348 handle_p2p_get (void *cls, const struct GNUNET_PeerIdentity *other,
349                 const struct GNUNET_MessageHeader *message,
350                 const struct GNUNET_ATS_Information *atsi,
351                 unsigned int atsi_count)
352 {
353   struct GSF_PendingRequest *pr;
354
355   pr = GSF_handle_p2p_query_ (other, message);
356   if (NULL == pr)
357     return GNUNET_SYSERR;
358   GSF_pending_request_get_data_ (pr)->has_started = GNUNET_YES;
359   GSF_local_lookup_ (pr, &consider_forwarding, NULL);
360   update_latencies (atsi, atsi_count);
361   return GNUNET_OK;
362 }
363
364
365 /**
366  * We're done with the local lookup, now consider
367  * P2P processing (depending on request options and
368  * result status).  Also signal that we can now
369  * receive more request information from the client.
370  *
371  * @param cls the client doing the request ('struct GNUNET_SERVER_Client')
372  * @param pr the pending request we were processing
373  * @param result final datastore lookup result
374  */
375 static void
376 start_p2p_processing (void *cls, struct GSF_PendingRequest *pr,
377                       enum GNUNET_BLOCK_EvaluationResult result)
378 {
379   struct GNUNET_SERVER_Client *client = cls;
380   struct GSF_PendingRequestData *prd;
381
382   prd = GSF_pending_request_get_data_ (pr);
383   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
384               "Finished database lookup for local request `%s' with result %d\n",
385               GNUNET_h2s (&prd->query), result);
386   GNUNET_SERVER_receive_done (client, GNUNET_OK);
387   if (GNUNET_BLOCK_EVALUATION_OK_LAST == result)
388     return;                     /* we're done, 'pr' was already destroyed... */
389   if (0 != (GSF_PRO_LOCAL_ONLY & prd->options))
390   {
391     GSF_pending_request_cancel_ (pr, GNUNET_YES);
392     return;
393   }
394   GSF_dht_lookup_ (pr);
395   consider_forwarding (NULL, pr, result);
396 }
397
398
399 /**
400  * Handle START_SEARCH-message (search request from client).
401  *
402  * @param cls closure
403  * @param client identification of the client
404  * @param message the actual message
405  */
406 static void
407 handle_start_search (void *cls, struct GNUNET_SERVER_Client *client,
408                      const struct GNUNET_MessageHeader *message)
409 {
410   struct GSF_PendingRequest *pr;
411   int ret;
412
413   pr = NULL;
414   ret = GSF_local_client_start_search_handler_ (client, message, &pr);
415   switch (ret)
416   {
417   case GNUNET_SYSERR:
418     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
419     break;
420   case GNUNET_NO:
421     GNUNET_SERVER_receive_done (client, GNUNET_OK);
422     break;
423   case GNUNET_YES:
424     GSF_pending_request_get_data_ (pr)->has_started = GNUNET_YES;
425     GSF_local_lookup_ (pr, &start_p2p_processing, client);
426     break;
427   default:
428     GNUNET_assert (0);
429   }
430 }
431
432
433 /**
434  * Task run during shutdown.
435  *
436  * @param cls unused
437  * @param tc unused
438  */
439 static void
440 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
441 {
442   if (NULL != GSF_core)
443   {
444     GNUNET_CORE_disconnect (GSF_core);
445     GSF_core = NULL;
446   }
447   GSF_put_done_ ();
448   GSF_push_done_ ();
449   GSF_pending_request_done_ ();
450   GSF_plan_done ();
451   GSF_connected_peer_done_ ();
452   GNUNET_DATASTORE_disconnect (GSF_dsh, GNUNET_NO);
453   GSF_dsh = NULL;
454   GNUNET_DHT_disconnect (GSF_dht);
455   GSF_dht = NULL;
456   GNUNET_BLOCK_context_destroy (GSF_block_ctx);
457   GSF_block_ctx = NULL;
458   GNUNET_CONFIGURATION_destroy (block_cfg);
459   block_cfg = NULL;
460   GNUNET_STATISTICS_destroy (GSF_stats, GNUNET_NO);
461   GSF_stats = NULL;
462   if (GNUNET_SCHEDULER_NO_TASK != cover_age_task)
463   {
464     GNUNET_SCHEDULER_cancel (cover_age_task);
465     cover_age_task = GNUNET_SCHEDULER_NO_TASK;
466   }
467   GNUNET_FS_indexing_done ();
468   GNUNET_LOAD_value_free (datastore_get_load);
469   datastore_get_load = NULL;
470   GNUNET_LOAD_value_free (GSF_rt_entry_lifetime);
471   GSF_rt_entry_lifetime = NULL;
472 }
473
474
475 /**
476  * Function called for each pending request whenever a new
477  * peer connects, giving us a chance to decide about submitting
478  * the existing request to the new peer.
479  *
480  * @param cls the 'struct GSF_ConnectedPeer' of the new peer
481  * @param key query for the request
482  * @param pr handle to the pending request
483  * @return GNUNET_YES to continue to iterate
484  */
485 static int
486 consider_peer_for_forwarding (void *cls, const struct GNUNET_HashCode * key,
487                               struct GSF_PendingRequest *pr)
488 {
489   struct GSF_ConnectedPeer *cp = cls;
490   struct GNUNET_PeerIdentity pid;
491
492   GSF_connected_peer_get_identity_ (cp, &pid);
493   if (GNUNET_YES != GSF_pending_request_test_target_ (pr, &pid))
494   {
495     GNUNET_STATISTICS_update (GSF_stats,
496                               gettext_noop ("# Loopback routes suppressed"), 1,
497                               GNUNET_NO);
498     return GNUNET_YES;
499   }
500   GSF_plan_add_ (cp, pr);
501   return GNUNET_YES;
502 }
503
504
505 /**
506  * Method called whenever a given peer connects.
507  *
508  * @param cls closure, not used
509  * @param peer peer identity this notification is about
510  * @param atsi performance information
511  * @param atsi_count number of records in 'atsi'
512  */
513 static void
514 peer_connect_handler (void *cls, const struct GNUNET_PeerIdentity *peer,
515                       const struct GNUNET_ATS_Information *atsi,
516                       unsigned int atsi_count)
517 {
518   struct GSF_ConnectedPeer *cp;
519
520   if (0 == memcmp (&my_id, peer, sizeof (struct GNUNET_PeerIdentity)))
521     return;
522   cp = GSF_peer_connect_handler_ (peer, atsi, atsi_count);
523   if (NULL == cp)
524     return;
525   GSF_iterate_pending_requests_ (&consider_peer_for_forwarding, cp);
526 }
527
528
529 /**
530  * Function called after GNUNET_CORE_connect has succeeded
531  * (or failed for good).  Note that the private key of the
532  * peer is intentionally not exposed here; if you need it,
533  * your process should try to read the private key file
534  * directly (which should work if you are authorized...).
535  *
536  * @param cls closure
537  * @param server handle to the server, NULL if we failed
538  * @param my_identity ID of this peer, NULL if we failed
539  */
540 static void
541 peer_init_handler (void *cls, struct GNUNET_CORE_Handle *server,
542                    const struct GNUNET_PeerIdentity *my_identity)
543 {
544   my_id = *my_identity;
545 }
546
547
548 /**
549  * Process fs requests.
550  *
551  * @param server the initialized server
552  * @param c configuration to use
553  */
554 static int
555 main_init (struct GNUNET_SERVER_Handle *server,
556            const struct GNUNET_CONFIGURATION_Handle *c)
557 {
558   static const struct GNUNET_CORE_MessageHandler p2p_handlers[] = {
559     {&handle_p2p_get,
560      GNUNET_MESSAGE_TYPE_FS_GET, 0},
561     {&handle_p2p_put,
562      GNUNET_MESSAGE_TYPE_FS_PUT, 0},
563     {&GSF_handle_p2p_migration_stop_,
564      GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
565      sizeof (struct MigrationStopMessage)},
566     {NULL, 0, 0}
567   };
568   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
569     {&GNUNET_FS_handle_index_start, NULL,
570      GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
571     {&GNUNET_FS_handle_index_list_get, NULL,
572      GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET,
573      sizeof (struct GNUNET_MessageHeader)},
574     {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
575      sizeof (struct UnindexMessage)},
576     {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
577      0},
578     {NULL, NULL, 0, 0}
579   };
580
581   GSF_core =
582       GNUNET_CORE_connect (GSF_cfg, NULL, &peer_init_handler,
583                            &peer_connect_handler, &GSF_peer_disconnect_handler_,
584                            NULL, GNUNET_NO, NULL, GNUNET_NO, p2p_handlers);
585   if (NULL == GSF_core)
586   {
587     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
588                 _("Failed to connect to `%s' service.\n"), "core");
589     return GNUNET_SYSERR;
590   }
591   GNUNET_SERVER_disconnect_notify (server, &GSF_client_disconnect_handler_,
592                                    NULL);
593   GNUNET_SERVER_add_handlers (server, handlers);
594   cover_age_task =
595       GNUNET_SCHEDULER_add_delayed (COVER_AGE_FREQUENCY, &age_cover_counters,
596                                     NULL);
597   datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
598   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
599                                 NULL);
600   return GNUNET_OK;
601 }
602
603
604 /**
605  * Process fs requests.
606  *
607  * @param cls closure
608  * @param server the initialized server
609  * @param cfg configuration to use
610  */
611 static void
612 run (void *cls, struct GNUNET_SERVER_Handle *server,
613      const struct GNUNET_CONFIGURATION_Handle *cfg)
614 {
615   GSF_cfg = cfg;
616   GSF_enable_randomized_delays =
617       GNUNET_CONFIGURATION_get_value_yesno (cfg, "fs", "DELAY");
618   GSF_dsh = GNUNET_DATASTORE_connect (cfg);
619   if (NULL == GSF_dsh)
620   {
621     GNUNET_SCHEDULER_shutdown ();
622     return;
623   }
624   GSF_rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL);
625   GSF_stats = GNUNET_STATISTICS_create ("fs", cfg);
626   block_cfg = GNUNET_CONFIGURATION_create ();
627   GNUNET_CONFIGURATION_set_value_string (block_cfg, "block", "PLUGINS", "fs");
628   GSF_block_ctx = GNUNET_BLOCK_context_create (block_cfg);
629   GNUNET_assert (NULL != GSF_block_ctx);
630   GSF_dht = GNUNET_DHT_connect (cfg, FS_DHT_HT_SIZE);
631   GSF_plan_init ();
632   GSF_pending_request_init_ ();
633   GSF_connected_peer_init_ ();
634   GSF_push_init_ ();
635   GSF_put_init_ ();
636   if ((GNUNET_OK != GNUNET_FS_indexing_init (cfg, GSF_dsh)) ||
637       (GNUNET_OK != main_init (server, cfg)))
638   {
639     GNUNET_SCHEDULER_shutdown ();
640     shutdown_task (NULL, NULL);
641     return;
642   }
643 }
644
645
646 /**
647  * The main function for the fs service.
648  *
649  * @param argc number of arguments from the command line
650  * @param argv command line arguments
651  * @return 0 ok, 1 on error
652  */
653 int
654 main (int argc, char *const *argv)
655 {
656   return (GNUNET_OK ==
657           GNUNET_SERVICE_run (argc, argv, "fs", GNUNET_SERVICE_OPTION_NONE,
658                               &run, NULL)) ? 0 : 1;
659 }
660
661 /* end of gnunet-service-fs.c */