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