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