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