social: relay msgs; psyc: slicer api; multicast: reset fragment_offset
[oweals/gnunet.git] / src / psycstore / gnunet-service-psycstore.c
1 /*
2  * This file is part of GNUnet
3  * Copyright (C) 2013 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 psycstore/gnunet-service-psycstore.c
23  * @brief PSYCstore service
24  * @author Gabor X Toth
25  * @author Christian Grothoff
26  */
27
28 #include <inttypes.h>
29
30 #include "platform.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_statistics_service.h"
35 #include "gnunet_psyc_util_lib.h"
36 #include "gnunet_psycstore_service.h"
37 #include "gnunet_psycstore_plugin.h"
38 #include "psycstore.h"
39
40
41 /**
42  * Handle to our current configuration.
43  */
44 static const struct GNUNET_CONFIGURATION_Handle *cfg;
45
46 /**
47  * Handle to the statistics service.
48  */
49 static struct GNUNET_STATISTICS_Handle *stats;
50
51 /**
52  * Notification context, simplifies client broadcasts.
53  */
54 static struct GNUNET_SERVER_NotificationContext *nc;
55
56 /**
57  * Database handle
58  */
59 static struct GNUNET_PSYCSTORE_PluginFunctions *db;
60
61 /**
62  * Name of the database plugin
63  */
64 static char *db_lib_name;
65
66
67 /**
68  * Task run during shutdown.
69  *
70  * @param cls unused
71  * @param tc unused
72  */
73 static void
74 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
75 {
76   if (NULL != nc)
77   {
78     GNUNET_SERVER_notification_context_destroy (nc);
79     nc = NULL;
80   }
81   if (NULL != stats)
82   {
83     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
84     stats = NULL;
85   }
86   GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, db));
87   GNUNET_free (db_lib_name);
88   db_lib_name = NULL;
89 }
90
91
92 /**
93  * Send a result code back to the client.
94  *
95  * @param client
96  *        Client that should receive the result code.
97  * @param result_code
98  *        Code to transmit.
99  * @param op_id
100  *        Operation ID in network byte order.
101  * @param err_msg
102  *        Error message to include (or NULL for none).
103  */
104 static void
105 send_result_code (struct GNUNET_SERVER_Client *client, uint64_t op_id,
106                   int64_t result_code, const char *err_msg)
107 {
108   struct OperationResult *res;
109   size_t err_size = 0;
110
111   if (NULL != err_msg)
112     err_size = strnlen (err_msg,
113                         GNUNET_SERVER_MAX_MESSAGE_SIZE - sizeof (*res) - 1) + 1;
114   res = GNUNET_malloc (sizeof (struct OperationResult) + err_size);
115   res->header.type = htons (GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_CODE);
116   res->header.size = htons (sizeof (struct OperationResult) + err_size);
117   res->result_code = GNUNET_htonll (result_code - INT64_MIN);
118   res->op_id = op_id;
119   if (0 < err_size)
120   {
121     memcpy (&res[1], err_msg, err_size);
122     ((char *) &res[1])[err_size - 1] = '\0';
123   }
124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
125               "Sending result to client: %" PRId64 " (%s)\n",
126               result_code, err_msg);
127   GNUNET_SERVER_notification_context_add (nc, client);
128   GNUNET_SERVER_notification_context_unicast (nc, client, &res->header,
129                                               GNUNET_NO);
130   GNUNET_free (res);
131 }
132
133
134 enum
135 {
136   MEMBERSHIP_TEST_NOT_NEEDED = 0,
137   MEMBERSHIP_TEST_NEEDED = 1,
138   MEMBERSHIP_TEST_DONE = 2,
139 } MessageMembershipTest;
140
141
142 struct SendClosure
143 {
144   struct GNUNET_SERVER_Client *client;
145
146   /**
147    * Channel's public key.
148    */
149   struct GNUNET_CRYPTO_EddsaPublicKey channel_key;
150
151   /**
152    * Slave's public key.
153    */
154   struct GNUNET_CRYPTO_EcdsaPublicKey slave_key;
155
156   /**
157    * Operation ID.
158    */
159   uint64_t op_id;
160
161   /**
162    * Membership test result.
163    */
164   int membership_test_result;
165
166   /**
167    * Do membership test with @a slave_key before returning fragment?
168    * @see enum MessageMembershipTest
169    */
170   uint8_t membership_test;
171 };
172
173
174 static int
175 send_fragment (void *cls, struct GNUNET_MULTICAST_MessageHeader *msg,
176                enum GNUNET_PSYCSTORE_MessageFlags flags)
177 {
178   struct SendClosure *sc = cls;
179   struct FragmentResult *res;
180
181   if (MEMBERSHIP_TEST_NEEDED == sc->membership_test)
182   {
183     sc->membership_test = MEMBERSHIP_TEST_DONE;
184     sc->membership_test_result
185       = db->membership_test (db->cls, &sc->channel_key, &sc->slave_key,
186                              GNUNET_ntohll (msg->message_id));
187     switch (sc->membership_test_result)
188     {
189     case GNUNET_YES:
190       break;
191
192     case GNUNET_NO:
193     case GNUNET_SYSERR:
194       return GNUNET_NO;
195     }
196   }
197
198   size_t msg_size = ntohs (msg->header.size);
199
200   res = GNUNET_malloc (sizeof (struct FragmentResult) + msg_size);
201   res->header.type = htons (GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_FRAGMENT);
202   res->header.size = htons (sizeof (struct FragmentResult) + msg_size);
203   res->op_id = sc->op_id;
204   res->psycstore_flags = htonl (flags);
205   memcpy (&res[1], msg, msg_size);
206   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
207               "Sending fragment %ld to client\n",
208               GNUNET_ntohll (msg->fragment_id));
209   GNUNET_free (msg);
210   GNUNET_SERVER_notification_context_add (nc, sc->client);
211   GNUNET_SERVER_notification_context_unicast (nc, sc->client, &res->header,
212                                               GNUNET_NO);
213   GNUNET_free (res);
214   return GNUNET_YES;
215 }
216
217
218 static int
219 send_state_var (void *cls, const char *name,
220                 const void *value, uint32_t value_size)
221 {
222   struct SendClosure *sc = cls;
223   struct StateResult *res;
224   size_t name_size = strlen (name) + 1;
225
226   /** @todo FIXME: split up value into 64k chunks */
227
228   res = GNUNET_malloc (sizeof (struct StateResult) + name_size + value_size);
229   res->header.type = htons (GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_STATE);
230   res->header.size = htons (sizeof (struct StateResult) + name_size + value_size);
231   res->op_id = sc->op_id;
232   res->name_size = htons (name_size);
233   memcpy (&res[1], name, name_size);
234   memcpy ((char *) &res[1] + name_size, value, value_size);
235   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
236               "Sending state variable %s to client\n", name);
237   GNUNET_SERVER_notification_context_add (nc, sc->client);
238   GNUNET_SERVER_notification_context_unicast (nc, sc->client, &res->header,
239                                               GNUNET_NO);
240   GNUNET_free (res);
241   return GNUNET_OK;
242 }
243
244
245 static void
246 handle_membership_store (void *cls,
247                          struct GNUNET_SERVER_Client *client,
248                          const struct GNUNET_MessageHeader *msg)
249 {
250   const struct MembershipStoreRequest *req =
251     (const struct MembershipStoreRequest *) msg;
252
253   int ret = db->membership_store (db->cls, &req->channel_key, &req->slave_key,
254                                   req->did_join,
255                                   GNUNET_ntohll (req->announced_at),
256                                   GNUNET_ntohll (req->effective_since),
257                                   GNUNET_ntohll (req->group_generation));
258
259   if (ret != GNUNET_OK)
260     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
261                 _("Failed to store membership information!\n"));
262
263   send_result_code (client, req->op_id, ret, NULL);
264   GNUNET_SERVER_receive_done (client, GNUNET_OK);
265 }
266
267
268 static void
269 handle_membership_test (void *cls,
270                         struct GNUNET_SERVER_Client *client,
271                         const struct GNUNET_MessageHeader *msg)
272 {
273   const struct MembershipTestRequest *req =
274     (const struct MembershipTestRequest *) msg;
275
276   int ret = db->membership_test (db->cls, &req->channel_key, &req->slave_key,
277                                  GNUNET_ntohll (req->message_id));
278   switch (ret)
279   {
280   case GNUNET_YES:
281   case GNUNET_NO:
282     break;
283   default:
284     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
285                 _("Failed to test membership!\n"));
286   }
287
288   send_result_code (client, req->op_id, ret, NULL);
289   GNUNET_SERVER_receive_done (client, GNUNET_OK);
290 }
291
292
293 static void
294 handle_fragment_store (void *cls,
295                        struct GNUNET_SERVER_Client *client,
296                        const struct GNUNET_MessageHeader *msg)
297 {
298   const struct FragmentStoreRequest *req =
299     (const struct FragmentStoreRequest *) msg;
300
301   int ret = db->fragment_store (db->cls, &req->channel_key,
302                                 (const struct GNUNET_MULTICAST_MessageHeader *)
303                                 &req[1], ntohl (req->psycstore_flags));
304
305   if (ret != GNUNET_OK)
306     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
307                 _("Failed to store fragment!\n"));
308
309   send_result_code (client, req->op_id, ret, NULL);
310   GNUNET_SERVER_receive_done (client, GNUNET_OK);
311 }
312
313
314 static void
315 handle_fragment_get (void *cls,
316                      struct GNUNET_SERVER_Client *client,
317                      const struct GNUNET_MessageHeader *msg)
318 {
319   const struct FragmentGetRequest *
320     req = (const struct FragmentGetRequest *) msg;
321   struct SendClosure
322     sc = { .op_id = req->op_id,
323            .client = client,
324            .channel_key = req->channel_key,
325            .slave_key = req->slave_key,
326            .membership_test = req->do_membership_test };
327
328   int64_t ret;
329   uint64_t ret_frags = 0;
330   uint64_t first_fragment_id = GNUNET_ntohll (req->first_fragment_id);
331   uint64_t last_fragment_id = GNUNET_ntohll (req->last_fragment_id);
332   uint64_t limit = GNUNET_ntohll (req->fragment_limit);
333
334   if (0 == limit)
335     ret = db->fragment_get (db->cls, &req->channel_key,
336                             first_fragment_id, last_fragment_id,
337                             &ret_frags, send_fragment, &sc);
338   else
339     ret = db->fragment_get_latest (db->cls, &req->channel_key, limit,
340                                    &ret_frags, send_fragment, &sc);
341
342   switch (ret)
343   {
344   case GNUNET_YES:
345   case GNUNET_NO:
346     if (MEMBERSHIP_TEST_DONE == sc.membership_test)
347     {
348       switch (sc.membership_test_result)
349       {
350       case GNUNET_YES:
351         break;
352
353       case GNUNET_NO:
354         ret = GNUNET_PSYCSTORE_MEMBERSHIP_TEST_FAILED;
355         break;
356
357       case GNUNET_SYSERR:
358         ret = GNUNET_SYSERR;
359         break;
360       }
361     }
362     break;
363   default:
364     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
365                 _("Failed to get fragment!\n"));
366   }
367   send_result_code (client, req->op_id, (ret < 0) ? ret : ret_frags, NULL);
368   GNUNET_SERVER_receive_done (client, GNUNET_OK);
369 }
370
371
372 static void
373 handle_message_get (void *cls,
374                     struct GNUNET_SERVER_Client *client,
375                     const struct GNUNET_MessageHeader *msg)
376 {
377   const struct MessageGetRequest *
378     req = (const struct MessageGetRequest *) msg;
379   uint16_t size = ntohs (msg->size);
380   const char *method_prefix = (const char *) &req[1];
381
382   if (size < sizeof (*req) + 1
383       || '\0' != method_prefix[size - sizeof (*req) - 1])
384   {
385     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
386                 "Message get: invalid method prefix. size: %u < %u?\n",
387                 size, sizeof (*req) + 1);
388     GNUNET_break (0);
389     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
390     return;
391   }
392
393   struct SendClosure
394     sc = { .op_id = req->op_id,
395            .client = client,
396            .channel_key = req->channel_key,
397            .slave_key = req->slave_key,
398            .membership_test = req->do_membership_test };
399
400   int64_t ret;
401   uint64_t ret_frags = 0;
402   uint64_t first_message_id = GNUNET_ntohll (req->first_message_id);
403   uint64_t last_message_id = GNUNET_ntohll (req->last_message_id);
404   uint64_t msg_limit = GNUNET_ntohll (req->message_limit);
405   uint64_t frag_limit = GNUNET_ntohll (req->fragment_limit);
406
407   /** @todo method_prefix */
408   if (0 == msg_limit)
409     ret = db->message_get (db->cls, &req->channel_key,
410                            first_message_id, last_message_id, frag_limit,
411                            &ret_frags, send_fragment, &sc);
412   else
413     ret = db->message_get_latest (db->cls, &req->channel_key, msg_limit,
414                                   &ret_frags, send_fragment, &sc);
415
416   switch (ret)
417   {
418   case GNUNET_YES:
419   case GNUNET_NO:
420     break;
421   default:
422     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
423                 _("Failed to get message!\n"));
424   }
425
426   send_result_code (client, req->op_id, (ret < 0) ? ret : ret_frags, NULL);
427   GNUNET_SERVER_receive_done (client, GNUNET_OK);
428 }
429
430
431 static void
432 handle_message_get_fragment (void *cls,
433                              struct GNUNET_SERVER_Client *client,
434                              const struct GNUNET_MessageHeader *msg)
435 {
436   const struct MessageGetFragmentRequest *
437     req = (const struct MessageGetFragmentRequest *) msg;
438   struct SendClosure
439     sc = { .op_id = req->op_id, .client = client,
440            .channel_key = req->channel_key, .slave_key = req->slave_key,
441            .membership_test = req->do_membership_test };
442
443   int ret = db->message_get_fragment (db->cls, &req->channel_key,
444                                       GNUNET_ntohll (req->message_id),
445                                       GNUNET_ntohll (req->fragment_offset),
446                                       &send_fragment, &sc);
447   switch (ret)
448   {
449   case GNUNET_YES:
450   case GNUNET_NO:
451     break;
452   default:
453     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
454                 _("Failed to get message fragment!\n"));
455   }
456
457   send_result_code (client, req->op_id, ret, NULL);
458   GNUNET_SERVER_receive_done (client, GNUNET_OK);
459 }
460
461
462 static void
463 handle_counters_get (void *cls,
464                      struct GNUNET_SERVER_Client *client,
465                      const struct GNUNET_MessageHeader *msg)
466 {
467   const struct OperationRequest *req = (const struct OperationRequest *) msg;
468   struct CountersResult res = { {0} };
469
470   int ret = db->counters_message_get (db->cls, &req->channel_key,
471                                       &res.max_fragment_id, &res.max_message_id,
472                                       &res.max_group_generation);
473   switch (ret)
474   {
475   case GNUNET_OK:
476     ret = db->counters_state_get (db->cls, &req->channel_key,
477                                   &res.max_state_message_id);
478   case GNUNET_NO:
479     break;
480   default:
481     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
482                 _("Failed to get master counters!\n"));
483   }
484
485   res.header.type = htons (GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_COUNTERS);
486   res.header.size = htons (sizeof (res));
487   res.result_code = htonl (ret);
488   res.op_id = req->op_id;
489   res.max_fragment_id = GNUNET_htonll (res.max_fragment_id);
490   res.max_message_id = GNUNET_htonll (res.max_message_id);
491   res.max_group_generation = GNUNET_htonll (res.max_group_generation);
492   res.max_state_message_id = GNUNET_htonll (res.max_state_message_id);
493
494   GNUNET_SERVER_notification_context_add (nc, client);
495   GNUNET_SERVER_notification_context_unicast (nc, client, &res.header,
496                                               GNUNET_NO);
497
498   GNUNET_SERVER_receive_done (client, GNUNET_OK);
499 }
500
501
502 struct StateModifyClosure
503 {
504   const struct GNUNET_CRYPTO_EddsaPublicKey channel_key;
505   struct GNUNET_PSYC_ReceiveHandle *recv;
506   enum GNUNET_PSYC_MessageState msg_state;
507   char mod_oper;
508   char *mod_name;
509   char *mod_value;
510   uint32_t mod_value_size;
511   uint32_t mod_value_remaining;
512 };
513
514
515 static void
516 recv_state_message_part (void *cls,
517                          const struct GNUNET_PSYC_MessageHeader *msg,
518                          const struct GNUNET_MessageHeader *pmsg)
519 {
520   struct StateModifyClosure *scls = cls;
521   uint16_t psize;
522
523   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
524               "recv_state_message_part()  message_id: %" PRIu64
525               ", fragment_offset: %" PRIu64 ", flags: %u\n",
526               GNUNET_ntohll (msg->message_id),
527               GNUNET_ntohll (msg->fragment_offset),
528               ntohl (msg->flags));
529
530   if (NULL == pmsg)
531   {
532     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_ERROR;
533     return;
534   }
535
536   switch (ntohs (pmsg->type))
537   {
538   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD:
539   {
540     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_METHOD;
541     break;
542   }
543
544   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
545   {
546     struct GNUNET_PSYC_MessageModifier *
547       pmod = (struct GNUNET_PSYC_MessageModifier *) pmsg;
548     psize = ntohs (pmod->header.size);
549     uint16_t name_size = ntohs (pmod->name_size);
550     uint32_t value_size = ntohl (pmod->value_size);
551
552     const char *name = (const char *) &pmod[1];
553     const void *value = name + name_size;
554
555     if (GNUNET_PSYC_OP_SET != pmod->oper)
556     { // Apply non-transient operation.
557       if (psize == sizeof (*pmod) + name_size + value_size)
558       {
559         db->state_modify_op (db->cls, &scls->channel_key,
560                              pmod->oper, name, value, value_size);
561       }
562       else
563       {
564         scls->mod_oper = pmod->oper;
565         scls->mod_name = GNUNET_malloc (name_size);
566         memcpy (scls->mod_name, name, name_size);
567
568         scls->mod_value_size = value_size;
569         scls->mod_value = GNUNET_malloc (scls->mod_value_size);
570         scls->mod_value_remaining
571           = scls->mod_value_size - (psize - sizeof (*pmod) - name_size);
572         memcpy (scls->mod_value, value, value_size - scls->mod_value_remaining);
573       }
574     }
575     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_MODIFIER;
576     break;
577   }
578
579   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MOD_CONT:
580     if (GNUNET_PSYC_OP_SET != scls->mod_oper)
581     {
582       if (scls->mod_value_remaining == 0)
583       {
584         GNUNET_break_op (0);
585         scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_ERROR;
586       }
587       psize = ntohs (pmsg->size);
588       memcpy (scls->mod_value + (scls->mod_value_size - scls->mod_value_remaining),
589               &pmsg[1], psize - sizeof (*pmsg));
590       scls->mod_value_remaining -= psize - sizeof (*pmsg);
591       if (0 == scls->mod_value_remaining)
592       {
593         db->state_modify_op (db->cls, &scls->channel_key,
594                              scls->mod_oper, scls->mod_name,
595                              scls->mod_value, scls->mod_value_size);
596         GNUNET_free (scls->mod_name);
597         GNUNET_free (scls->mod_value);
598         scls->mod_oper = 0;
599         scls->mod_name = NULL;
600         scls->mod_value = NULL;
601         scls->mod_value_size = 0;
602       }
603     }
604     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_MOD_CONT;
605     break;
606
607   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
608     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_DATA;
609     break;
610
611   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
612     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_END;
613     break;
614
615   default:
616     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_ERROR;
617   }
618 }
619
620
621 static int
622 recv_state_fragment (void *cls, struct GNUNET_MULTICAST_MessageHeader *msg,
623                      enum GNUNET_PSYCSTORE_MessageFlags flags)
624 {
625   struct StateModifyClosure *scls = cls;
626
627   if (NULL == scls->recv)
628   {
629     scls->recv = GNUNET_PSYC_receive_create (NULL, recv_state_message_part,
630                                              scls);
631   }
632
633   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
634               "recv_state_fragment: %" PRIu64 "\n", GNUNET_ntohll (msg->fragment_id));
635
636   struct GNUNET_PSYC_MessageHeader *
637     pmsg = GNUNET_PSYC_message_header_create (msg, flags);
638   GNUNET_PSYC_receive_message (scls->recv, pmsg);
639   GNUNET_free (pmsg);
640
641   return GNUNET_YES;
642 }
643
644
645 static void
646 handle_state_modify (void *cls,
647                      struct GNUNET_SERVER_Client *client,
648                      const struct GNUNET_MessageHeader *msg)
649 {
650   const struct StateModifyRequest *req
651     = (const struct StateModifyRequest *) msg;
652
653   uint64_t message_id = GNUNET_ntohll (req->message_id);
654   uint64_t state_delta = GNUNET_ntohll (req->state_delta);
655   uint64_t ret_frags = 0;
656   struct StateModifyClosure
657     scls = { .channel_key = req->channel_key };
658
659   int ret = db->state_modify_begin (db->cls, &req->channel_key,
660                                     message_id, state_delta);
661
662   if (GNUNET_OK != ret)
663   {
664     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
665                 _("Failed to begin modifying state: %d\n"), ret);
666   }
667   else
668   {
669     ret = db->message_get (db->cls, &req->channel_key,
670                            message_id, message_id, 0,
671                            &ret_frags, recv_state_fragment, &scls);
672     if (GNUNET_OK != ret)
673     {
674       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
675                   _("Failed to modify state: %d\n"), ret);
676       GNUNET_break (0);
677     }
678     else
679     {
680       if (GNUNET_OK != db->state_modify_end (db->cls, &req->channel_key, message_id))
681       {
682         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
683                     _("Failed to end modifying state!\n"));
684         GNUNET_break (0);
685       }
686     }
687     if (NULL != scls.recv)
688     {
689       GNUNET_PSYC_receive_destroy (scls.recv);
690     }
691   }
692
693   send_result_code (client, req->op_id, ret, NULL);
694   GNUNET_SERVER_receive_done (client, GNUNET_OK);
695 }
696
697
698 /** @todo FIXME: stop processing further state sync messages after an error */
699 static void
700 handle_state_sync (void *cls,
701                    struct GNUNET_SERVER_Client *client,
702                    const struct GNUNET_MessageHeader *msg)
703 {
704   const struct StateSyncRequest *req
705     = (const struct StateSyncRequest *) msg;
706
707   int ret = GNUNET_SYSERR;
708   const char *name = (const char *) &req[1];
709   uint16_t name_size = ntohs (req->name_size);
710
711   if (name_size <= 2 || '\0' != name[name_size - 1])
712   {
713     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
714                 _("Tried to set invalid state variable name!\n"));
715     GNUNET_break_op (0);
716   }
717   else
718   {
719     ret = GNUNET_OK;
720
721     if (req->flags & STATE_OP_FIRST)
722     {
723       ret = db->state_sync_begin (db->cls, &req->channel_key);
724     }
725     if (ret != GNUNET_OK)
726     {
727       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
728                   _("Failed to begin synchronizing state!\n"));
729     }
730     else
731     {
732       ret = db->state_sync_assign (db->cls, &req->channel_key, name,
733                                    name + ntohs (req->name_size),
734                                    ntohs (req->header.size) - sizeof (*req)
735                                    - ntohs (req->name_size));
736     }
737
738     if (GNUNET_OK == ret && req->flags & STATE_OP_LAST)
739     {
740       ret = db->state_sync_end (db->cls, &req->channel_key,
741                                 GNUNET_ntohll (req->max_state_message_id),
742                                 GNUNET_ntohll (req->state_hash_message_id));
743       if (ret != GNUNET_OK)
744         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
745                     _("Failed to end synchronizing state!\n"));
746     }
747   }
748   send_result_code (client, req->op_id, ret, NULL);
749   GNUNET_SERVER_receive_done (client, GNUNET_OK);
750 }
751
752
753 static void
754 handle_state_reset (void *cls,
755                     struct GNUNET_SERVER_Client *client,
756                     const struct GNUNET_MessageHeader *msg)
757 {
758   const struct OperationRequest *req =
759     (const struct OperationRequest *) msg;
760
761   int ret = db->state_reset (db->cls, &req->channel_key);
762
763   if (ret != GNUNET_OK)
764     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
765                 _("Failed to reset state!\n"));
766
767   send_result_code (client, req->op_id, ret, NULL);
768   GNUNET_SERVER_receive_done (client, GNUNET_OK);
769 }
770
771
772 static void
773 handle_state_hash_update (void *cls,
774                           struct GNUNET_SERVER_Client *client,
775                           const struct GNUNET_MessageHeader *msg)
776 {
777   const struct OperationRequest *req =
778     (const struct OperationRequest *) msg;
779
780   int ret = db->state_reset (db->cls, &req->channel_key);
781
782   if (ret != GNUNET_OK)
783     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
784                 _("Failed to reset state!\n"));
785
786   send_result_code (client, req->op_id, ret, NULL);
787   GNUNET_SERVER_receive_done (client, GNUNET_OK);
788 }
789
790
791 static void
792 handle_state_get (void *cls,
793                   struct GNUNET_SERVER_Client *client,
794                   const struct GNUNET_MessageHeader *msg)
795 {
796   const struct OperationRequest *req =
797     (const struct OperationRequest *) msg;
798
799   struct SendClosure sc = { .op_id = req->op_id, .client = client };
800   int64_t ret = GNUNET_SYSERR;
801   const char *name = (const char *) &req[1];
802   uint16_t name_size = ntohs (req->header.size) - sizeof (*req);
803
804   if (name_size <= 2 || '\0' != name[name_size - 1])
805   {
806     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
807                 _("Tried to get invalid state variable name!\n"));
808     GNUNET_break (0);
809   }
810   else
811   {
812     ret = db->state_get (db->cls, &req->channel_key, name,
813                          &send_state_var, &sc);
814     if (GNUNET_NO == ret && name_size >= 5) /* min: _a_b\0 */
815     {
816       char *p, *n = GNUNET_malloc (name_size);
817       memcpy (n, name, name_size);
818       while (&n[1] < (p = strrchr (n, '_')) && GNUNET_NO == ret)
819       {
820         *p = '\0';
821         ret = db->state_get (db->cls, &req->channel_key, n,
822                              &send_state_var, &sc);
823       }
824       GNUNET_free (n);
825     }
826   }
827   switch (ret)
828   {
829   case GNUNET_OK:
830   case GNUNET_NO:
831     break;
832   default:
833     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
834                 _("Failed to get state variable!\n"));
835   }
836
837   send_result_code (client, req->op_id, ret, NULL);
838   GNUNET_SERVER_receive_done (client, GNUNET_OK);
839 }
840
841
842 static void
843 handle_state_get_prefix (void *cls,
844                          struct GNUNET_SERVER_Client *client,
845                          const struct GNUNET_MessageHeader *msg)
846 {
847   const struct OperationRequest *req =
848     (const struct OperationRequest *) msg;
849
850   struct SendClosure sc = { .op_id = req->op_id, .client = client };
851   int64_t ret = GNUNET_SYSERR;
852   const char *name = (const char *) &req[1];
853   uint16_t name_size = ntohs (req->header.size) - sizeof (*req);
854
855   if (name_size <= 1 || '\0' != name[name_size - 1])
856   {
857     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
858                 _("Tried to get invalid state variable name!\n"));
859     GNUNET_break (0);
860   }
861   else
862   {
863     ret = db->state_get_prefix (db->cls, &req->channel_key, name,
864                                 &send_state_var, &sc);
865   }
866   switch (ret)
867   {
868   case GNUNET_OK:
869   case GNUNET_NO:
870     break;
871   default:
872     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
873                 _("Failed to get state variable!\n"));
874   }
875
876   send_result_code (client, req->op_id, ret, NULL);
877   GNUNET_SERVER_receive_done (client, GNUNET_OK);
878 }
879
880
881 /**
882  * Initialize the PSYCstore service.
883  *
884  * @param cls Closure.
885  * @param server The initialized server.
886  * @param c Configuration to use.
887  */
888 static void
889 run (void *cls, struct GNUNET_SERVER_Handle *server,
890      const struct GNUNET_CONFIGURATION_Handle *c)
891 {
892   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
893     { &handle_membership_store, NULL,
894       GNUNET_MESSAGE_TYPE_PSYCSTORE_MEMBERSHIP_STORE,
895       sizeof (struct MembershipStoreRequest) },
896
897     { &handle_membership_test, NULL,
898       GNUNET_MESSAGE_TYPE_PSYCSTORE_MEMBERSHIP_TEST,
899       sizeof (struct MembershipTestRequest) },
900
901     { &handle_fragment_store, NULL,
902       GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_STORE, 0, },
903
904     { &handle_fragment_get, NULL,
905       GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_GET,
906       sizeof (struct FragmentGetRequest) },
907
908     { &handle_message_get, NULL,
909       GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET, 0 },
910
911     { &handle_message_get_fragment, NULL,
912       GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET_FRAGMENT,
913       sizeof (struct MessageGetFragmentRequest) },
914
915     { &handle_counters_get, NULL,
916       GNUNET_MESSAGE_TYPE_PSYCSTORE_COUNTERS_GET,
917       sizeof (struct OperationRequest) },
918
919     { &handle_state_modify, NULL,
920       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_MODIFY, 0 },
921
922     { &handle_state_sync, NULL,
923       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_SYNC, 0 },
924
925     { &handle_state_reset, NULL,
926       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_RESET,
927       sizeof (struct OperationRequest) },
928
929     { &handle_state_hash_update, NULL,
930       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_HASH_UPDATE,
931       sizeof (struct StateHashUpdateRequest) },
932
933     { &handle_state_get, NULL,
934       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_GET, 0 },
935
936     { &handle_state_get_prefix, NULL,
937       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_GET_PREFIX, 0 },
938
939     { NULL, NULL, 0, 0 }
940   };
941
942   cfg = c;
943
944   /* Loading database plugin */
945   char *database;
946   if (GNUNET_OK !=
947       GNUNET_CONFIGURATION_get_value_string (cfg, "psycstore", "database",
948                                              &database))
949   {
950     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n");
951   }
952   else
953   {
954     GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_psycstore_%s", database);
955     db = GNUNET_PLUGIN_load (db_lib_name, (void *) cfg);
956     GNUNET_free (database);
957   }
958   if (NULL == db)
959   {
960     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
961                 "Could not load database backend `%s'\n",
962                 db_lib_name);
963     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
964     return;
965   }
966
967   stats = GNUNET_STATISTICS_create ("psycstore", cfg);
968   GNUNET_SERVER_add_handlers (server, handlers);
969   nc = GNUNET_SERVER_notification_context_create (server, 1);
970   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
971                                 NULL);
972 }
973
974
975 /**
976  * The main function for the service.
977  *
978  * @param argc number of arguments from the command line
979  * @param argv command line arguments
980  * @return 0 ok, 1 on error
981  */
982 int
983 main (int argc, char *const *argv)
984 {
985   return (GNUNET_OK ==
986           GNUNET_SERVICE_run (argc, argv, "psycstore",
987                               GNUNET_SERVICE_OPTION_NONE,
988                               &run, NULL)) ? 0 : 1;
989 }
990
991
992 /* end of gnunet-service-psycstore.c */