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