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