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