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