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