-fix non-deterministic peerstore sync failure
[oweals/gnunet.git] / src / peerstore / gnunet-service-peerstore.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2014, 2015 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file peerstore/gnunet-service-peerstore.c
23  * @brief peerstore service implementation
24  * @author Omar Tarabai
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "peerstore.h"
29 #include "gnunet_peerstore_plugin.h"
30 #include "peerstore_common.h"
31
32 /**
33  * Connected client entry
34  */
35 struct ClientEntry
36 {
37   /**
38    * DLL.
39    */
40   struct ClientEntry *next;
41
42   /**
43    * DLL.
44    */
45   struct ClientEntry *prev;
46
47   /**
48    * Corresponding server handle.
49    */
50   struct GNUNET_SERVER_Client *client;
51 };
52
53 /**
54  * Interval for expired records cleanup (in seconds)
55  */
56 #define EXPIRED_RECORDS_CLEANUP_INTERVAL 300    /* 5mins */
57
58 /**
59  * Our configuration.
60  */
61 static const struct GNUNET_CONFIGURATION_Handle *cfg;
62
63 /**
64  * Database plugin library name
65  */
66 static char *db_lib_name;
67
68 /**
69  * Database handle
70  */
71 static struct GNUNET_PEERSTORE_PluginFunctions *db;
72
73 /**
74  * Hashmap with all watch requests
75  */
76 static struct GNUNET_CONTAINER_MultiHashMap *watchers;
77
78 /**
79  * Our notification context.
80  */
81 static struct GNUNET_SERVER_NotificationContext *nc;
82
83 /**
84  * Head of linked list of connected clients
85  */
86 static struct ClientEntry *client_head;
87
88 /**
89  * Tail of linked list of connected clients
90  */
91 static struct ClientEntry *client_tail;
92
93 /**
94  * Are we in the process of shutting down the service? #GNUNET_YES / #GNUNET_NO
95  */
96 static int in_shutdown;
97
98 /**
99  * Perform the actual shutdown operations
100  */
101 static void
102 do_shutdown ()
103 {
104   if (NULL != db_lib_name)
105   {
106     GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, db));
107     GNUNET_free (db_lib_name);
108     db_lib_name = NULL;
109   }
110   if (NULL != nc)
111   {
112     GNUNET_SERVER_notification_context_destroy (nc);
113     nc = NULL;
114   }
115   if (NULL != watchers)
116   {
117     GNUNET_CONTAINER_multihashmap_destroy (watchers);
118     watchers = NULL;
119   }
120   GNUNET_SCHEDULER_shutdown ();
121 }
122
123
124 /**
125  * Task run during shutdown.
126  *
127  * @param cls unused
128  * @param tc unused
129  */
130 static void
131 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
132 {
133   in_shutdown = GNUNET_YES;
134   if (NULL == client_head)      /* Only when no connected clients. */
135     do_shutdown ();
136 }
137
138
139 /* Forward declaration */
140 static void
141 expire_records_continuation (void *cls, int success);
142
143
144 /**
145  * Deletes any expired records from storage
146  */
147 static void
148 cleanup_expired_records (void *cls,
149                          const struct GNUNET_SCHEDULER_TaskContext *tc)
150 {
151   int ret;
152
153   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
154     return;
155   GNUNET_assert (NULL != db);
156   ret =
157       db->expire_records (db->cls, GNUNET_TIME_absolute_get (),
158                           expire_records_continuation, NULL);
159   if (GNUNET_OK != ret)
160   {
161     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
162                                   (GNUNET_TIME_UNIT_SECONDS,
163                                    EXPIRED_RECORDS_CLEANUP_INTERVAL),
164                                   &cleanup_expired_records, NULL);
165   }
166 }
167
168
169 /**
170  * Continuation to expire_records called by the peerstore plugin
171  *
172  * @param cls unused
173  * @param success count of records deleted or #GNUNET_SYSERR
174  */
175 static void
176 expire_records_continuation (void *cls, int success)
177 {
178   if (success > 0)
179     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%d records expired.\n", success);
180   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
181                                 (GNUNET_TIME_UNIT_SECONDS,
182                                  EXPIRED_RECORDS_CLEANUP_INTERVAL),
183                                 &cleanup_expired_records, NULL);
184 }
185
186
187 /**
188  * Search for a disconnected client and remove it
189  *
190  * @param cls closuer, a 'struct GNUNET_PEERSTORE_Record *'
191  * @param key hash of record key
192  * @param value the watcher client, a 'struct GNUNET_SERVER_Client *'
193  * @return #GNUNET_OK to continue iterating
194  */
195 static int
196 client_disconnect_it (void *cls, const struct GNUNET_HashCode *key, void *value)
197 {
198   if (cls == value)
199     GNUNET_CONTAINER_multihashmap_remove (watchers, key, value);
200   return GNUNET_OK;
201 }
202
203
204 /**
205  * A client disconnected.  Remove all of its data structure entries.
206  *
207  * @param cls closure, NULL
208  * @param client identification of the client
209  */
210 static void
211 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
212 {
213   struct ClientEntry *ce;
214
215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "A client disconnected, cleaning up.\n");
216   if (NULL != watchers)
217     GNUNET_CONTAINER_multihashmap_iterate (watchers, &client_disconnect_it,
218                                            client);
219   ce = client_head;
220   while (ce != NULL)
221   {
222     if (ce->client == client)
223     {
224       GNUNET_CONTAINER_DLL_remove (client_head, client_tail, ce);
225       GNUNET_free (ce);
226       break;
227     }
228     ce = ce->next;
229   }
230   if (NULL == client_head && in_shutdown)
231     do_shutdown ();
232 }
233
234
235 /**
236  * Function called by for each matching record.
237  *
238  * @param cls closure
239  * @param record peerstore record found
240  * @param emsg error message or NULL if no errors
241  * @return #GNUNET_YES to continue iteration
242  */
243 static int
244 record_iterator (void *cls, const struct GNUNET_PEERSTORE_Record *record,
245                  const char *emsg)
246 {
247   struct GNUNET_PEERSTORE_Record *cls_record = cls;
248   struct StoreRecordMessage *srm;
249
250   if (NULL == record)
251   {
252     /* No more records */
253     struct GNUNET_MessageHeader endmsg;
254
255     endmsg.size = htons (sizeof (struct GNUNET_MessageHeader));
256     endmsg.type = htons (GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE_END);
257     GNUNET_SERVER_notification_context_unicast (nc, cls_record->client, &endmsg,
258                                                 GNUNET_NO);
259     GNUNET_SERVER_receive_done (cls_record->client,
260                                 NULL == emsg ? GNUNET_OK : GNUNET_SYSERR);
261     PEERSTORE_destroy_record (cls_record);
262     return GNUNET_NO;
263   }
264
265   srm =
266       PEERSTORE_create_record_message (record->sub_system, record->peer,
267                                        record->key, record->value,
268                                        record->value_size, record->expiry,
269                                        GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE_RECORD);
270   GNUNET_SERVER_notification_context_unicast (nc, cls_record->client,
271                                               (struct GNUNET_MessageHeader *)
272                                               srm, GNUNET_NO);
273   GNUNET_free (srm);
274   return GNUNET_YES;
275 }
276
277
278 /**
279  * Iterator over all watcher clients
280  * to notify them of a new record
281  *
282  * @param cls closuer, a 'struct GNUNET_PEERSTORE_Record *'
283  * @param key hash of record key
284  * @param value the watcher client, a 'struct GNUNET_SERVER_Client *'
285  * @return #GNUNET_YES to continue iterating
286  */
287 static int
288 watch_notifier_it (void *cls, const struct GNUNET_HashCode *key, void *value)
289 {
290   struct GNUNET_PEERSTORE_Record *record = cls;
291   struct GNUNET_SERVER_Client *client = value;
292   struct StoreRecordMessage *srm;
293
294   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found a watcher to update.\n");
295   srm =
296       PEERSTORE_create_record_message (record->sub_system, record->peer,
297                                        record->key, record->value,
298                                        record->value_size, record->expiry,
299                                        GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH_RECORD);
300   GNUNET_SERVER_notification_context_unicast (nc, client,
301                                               (const struct GNUNET_MessageHeader
302                                                *) srm, GNUNET_NO);
303   GNUNET_free (srm);
304   return GNUNET_YES;
305 }
306
307
308 /**
309  * Given a new record, notifies watchers
310  *
311  * @param record changed record to update watchers with
312  */
313 static void
314 watch_notifier (struct GNUNET_PEERSTORE_Record *record)
315 {
316   struct GNUNET_HashCode keyhash;
317
318   PEERSTORE_hash_key (record->sub_system, record->peer, record->key, &keyhash);
319   GNUNET_CONTAINER_multihashmap_get_multiple (watchers, &keyhash,
320                                               &watch_notifier_it, record);
321 }
322
323
324 /**
325  * Handle a watch cancel request from client
326  *
327  * @param cls unused
328  * @param client identification of the client
329  * @param message the actual message
330  */
331 static void
332 handle_watch_cancel (void *cls, struct GNUNET_SERVER_Client *client,
333                      const struct GNUNET_MessageHeader *message)
334 {
335   struct StoreKeyHashMessage *hm;
336
337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a watch cancel request.\n");
338   hm = (struct StoreKeyHashMessage *) message;
339   GNUNET_CONTAINER_multihashmap_remove (watchers, &hm->keyhash, client);
340   GNUNET_SERVER_receive_done (client, GNUNET_OK);
341 }
342
343
344 /**
345  * Handle a watch request from client
346  *
347  * @param cls unused
348  * @param client identification of the client
349  * @param message the actual message
350  */
351 static void
352 handle_watch (void *cls, struct GNUNET_SERVER_Client *client,
353               const struct GNUNET_MessageHeader *message)
354 {
355   struct StoreKeyHashMessage *hm;
356
357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a watch request.\n");
358   hm = (struct StoreKeyHashMessage *) message;
359   GNUNET_SERVER_client_mark_monitor (client);
360   GNUNET_SERVER_notification_context_add (nc, client);
361   GNUNET_CONTAINER_multihashmap_put (watchers, &hm->keyhash, client,
362                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
363   GNUNET_SERVER_receive_done (client, GNUNET_OK);
364 }
365
366
367 /**
368  * Handle an iterate request from client
369  *
370  * @param cls unused
371  * @param client identification of the client
372  * @param message the actual message
373  */
374 static void
375 handle_iterate (void *cls, struct GNUNET_SERVER_Client *client,
376                 const struct GNUNET_MessageHeader *message)
377 {
378   struct GNUNET_PEERSTORE_Record *record;
379
380   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received an iterate request.\n");
381   record = PEERSTORE_parse_record_message (message);
382   if (NULL == record)
383   {
384     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Malformed iterate request.\n"));
385     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
386     return;
387   }
388   if (NULL == record->sub_system)
389   {
390     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
391                 _("Sub system not supplied in client iterate request.\n"));
392     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
393     PEERSTORE_destroy_record (record);
394     return;
395   }
396   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
397               "Iterate request: ss `%s', peer `%s', key `%s'\n",
398               record->sub_system,
399               (NULL == record->peer) ? "NULL" : GNUNET_i2s (record->peer),
400               (NULL == record->key) ? "NULL" : record->key);
401   GNUNET_SERVER_notification_context_add (nc, client);
402   record->client = client;
403   if (GNUNET_OK !=
404       db->iterate_records (db->cls, record->sub_system, record->peer,
405                            record->key, &record_iterator, record))
406   {
407     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
408     PEERSTORE_destroy_record (record);
409   }
410 }
411
412
413 /**
414  * Continuation of store_record called by the peerstore plugin
415  *
416  * @param cls closure
417  * @param success result
418  */
419 static void
420 store_record_continuation (void *cls, int success)
421 {
422   struct GNUNET_PEERSTORE_Record *record = cls;
423
424   GNUNET_SERVER_receive_done (record->client, success);
425   if (GNUNET_OK == success)
426   {
427     watch_notifier (record);
428   }
429   PEERSTORE_destroy_record (record);
430 }
431
432
433 /**
434  * Handle a store request from client
435  *
436  * @param cls unused
437  * @param client identification of the client
438  * @param message the actual message
439  */
440 static void
441 handle_store (void *cls, struct GNUNET_SERVER_Client *client,
442               const struct GNUNET_MessageHeader *message)
443 {
444   struct GNUNET_PEERSTORE_Record *record;
445   struct StoreRecordMessage *srm;
446
447   record = PEERSTORE_parse_record_message (message);
448   if (NULL == record)
449   {
450     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
451                 _("Malformed store request from client\n"));
452     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
453     return;
454   }
455   srm = (struct StoreRecordMessage *) message;
456   if (NULL == record->sub_system || NULL == record->peer || NULL == record->key)
457   {
458     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
459                 _("Full key not supplied in client store request\n"));
460     PEERSTORE_destroy_record (record);
461     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
462     return;
463   }
464   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
465               "Received a store request (size: %lu).\n" " Sub system `%s'\n"
466               " Peer `%s'\n" " Key `%s'\n" " Value size %lu\n"
467               " Options: %d.\n", record->value_size, record->sub_system,
468               GNUNET_i2s (record->peer), record->key, record->value_size,
469               ntohl (srm->options));
470   record->client = client;
471   if (GNUNET_OK !=
472       db->store_record (db->cls, record->sub_system, record->peer, record->key,
473                         record->value, record->value_size, *record->expiry,
474                         ntohl (srm->options), store_record_continuation,
475                         record))
476   {
477     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
478                 _("Failed to store requested value, database error."));
479     PEERSTORE_destroy_record (record);
480     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
481     return;
482   }
483 }
484
485
486 /**
487  * Creates an entry for a new client or returns it if it already exists.
488  *
489  * @param client Client handle
490  * @return Client entry struct
491  */
492 static struct ClientEntry *
493 make_client_entry (struct GNUNET_SERVER_Client *client)
494 {
495   struct ClientEntry *ce;
496
497   ce = client_head;
498   while (NULL != ce)
499   {
500     if (ce->client == client)
501       return ce;
502     ce = ce->next;
503   }
504   if (GNUNET_YES == in_shutdown)
505   {
506     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
507     return NULL;
508   }
509   ce = GNUNET_new (struct ClientEntry);
510   ce->client = client;
511   GNUNET_CONTAINER_DLL_insert (client_head, client_tail, ce);
512   return ce;
513 }
514
515
516 /**
517  * Callback on a new client connection
518  *
519  * @param cls closure (unused)
520  * @param client identification of the client
521  */
522 static void
523 handle_client_connect (void *cls, struct GNUNET_SERVER_Client *client)
524 {
525   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "New client connection created.\n");
526   make_client_entry (client);
527 }
528
529
530 /**
531  * Peerstore service runner.
532  *
533  * @param cls closure
534  * @param server the initialized server
535  * @param c configuration to use
536  */
537 static void
538 run (void *cls, struct GNUNET_SERVER_Handle *server,
539      const struct GNUNET_CONFIGURATION_Handle *c)
540 {
541   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
542     {&handle_store, NULL, GNUNET_MESSAGE_TYPE_PEERSTORE_STORE, 0},
543     {&handle_iterate, NULL, GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE, 0},
544     {&handle_watch, NULL, GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH,
545      sizeof (struct StoreKeyHashMessage)},
546     {&handle_watch_cancel, NULL, GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH_CANCEL,
547      sizeof (struct StoreKeyHashMessage)},
548     {NULL, NULL, 0, 0}
549   };
550   char *database;
551
552   in_shutdown = GNUNET_NO;
553   cfg = c;
554   if (GNUNET_OK !=
555       GNUNET_CONFIGURATION_get_value_string (cfg, "peerstore", "DATABASE",
556                                              &database))
557     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("No database backend configured\n"));
558
559   else
560   {
561     GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_peerstore_%s", database);
562     db = GNUNET_PLUGIN_load (db_lib_name, (void *) cfg);
563     GNUNET_free (database);
564   }
565   if (NULL == db)
566   {
567     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
568                 _("Could not load database backend `%s'\n"), db_lib_name);
569     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
570     return;
571   }
572   nc = GNUNET_SERVER_notification_context_create (server, 16);
573   watchers = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
574   GNUNET_SCHEDULER_add_now (&cleanup_expired_records, NULL);
575   GNUNET_SERVER_add_handlers (server, handlers);
576   GNUNET_SERVER_connect_notify (server, &handle_client_connect, NULL);
577   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
578   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
579                                 NULL);
580 }
581
582
583 /**
584  * The main function for the peerstore service.
585  *
586  * @param argc number of arguments from the command line
587  * @param argv command line arguments
588  * @return 0 ok, 1 on error
589  */
590 int
591 main (int argc, char *const *argv)
592 {
593   return (GNUNET_OK ==
594           GNUNET_SERVICE_run (argc, argv, "peerstore",
595                               GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN, &run,
596                               NULL)) ? 0 : 1;
597 }
598
599 /* end of gnunet-service-peerstore.c */