social: guest_enter_by_name(); zone_add_pkey(); join_msg fixes
[oweals/gnunet.git] / src / psycstore / gnunet-service-psycstore.c
1 /*
2  * This file is part of GNUnet
3  * Copyright (C) 2013 Christian Grothoff (and other contributing authors)
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, .client = client,
323            .channel_key = req->channel_key, .slave_key = req->slave_key,
324            .membership_test = req->do_membership_test };
325
326   int64_t ret;
327   uint64_t ret_frags = 0;
328   uint64_t first_fragment_id = GNUNET_ntohll (req->first_fragment_id);
329   uint64_t last_fragment_id = GNUNET_ntohll (req->last_fragment_id);
330   uint64_t limit = GNUNET_ntohll (req->fragment_limit);
331
332   if (0 == limit)
333     ret = db->fragment_get (db->cls, &req->channel_key,
334                             first_fragment_id, last_fragment_id,
335                             &ret_frags, &send_fragment, &sc);
336   else
337     ret = db->fragment_get_latest (db->cls, &req->channel_key, limit,
338                                    &ret_frags, &send_fragment, &sc);
339
340   switch (ret)
341   {
342   case GNUNET_YES:
343   case GNUNET_NO:
344     if (MEMBERSHIP_TEST_DONE == sc.membership_test)
345     {
346       switch (sc.membership_test_result)
347       {
348       case GNUNET_YES:
349         break;
350
351       case GNUNET_NO:
352         ret = GNUNET_PSYCSTORE_MEMBERSHIP_TEST_FAILED;
353         break;
354
355       case GNUNET_SYSERR:
356         ret = GNUNET_SYSERR;
357         break;
358       }
359     }
360     break;
361   default:
362     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
363                 _("Failed to get fragment!\n"));
364   }
365   send_result_code (client, req->op_id, (ret < 0) ? ret : ret_frags, NULL);
366   GNUNET_SERVER_receive_done (client, GNUNET_OK);
367 }
368
369
370 static void
371 handle_message_get (void *cls,
372                     struct GNUNET_SERVER_Client *client,
373                     const struct GNUNET_MessageHeader *msg)
374 {
375   const struct MessageGetRequest *
376     req = (const struct MessageGetRequest *) msg;
377   uint16_t size = ntohs (msg->size);
378   const char *method_prefix = (const char *) &req[1];
379
380   if (size < sizeof (*req) + 1
381       || '\0' != method_prefix[size - sizeof (*req) - 1])
382   {
383     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
384                 "Message get: invalid method prefix. size: %u < %u?\n",
385                 size, sizeof (*req) + 1);
386     GNUNET_break (0);
387     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
388     return;
389   }
390
391   struct SendClosure
392     sc = { .op_id = req->op_id, .client = client,
393            .channel_key = req->channel_key, .slave_key = req->slave_key,
394            .membership_test = req->do_membership_test };
395
396   int64_t ret;
397   uint64_t ret_frags = 0;
398   uint64_t first_message_id = GNUNET_ntohll (req->first_message_id);
399   uint64_t last_message_id = GNUNET_ntohll (req->last_message_id);
400   uint64_t limit = GNUNET_ntohll (req->message_limit);
401
402   /** @todo method_prefix */
403   if (0 == limit)
404     ret = db->message_get (db->cls, &req->channel_key,
405                            first_message_id, last_message_id,
406                            &ret_frags, &send_fragment, &sc);
407   else
408     ret = db->message_get_latest (db->cls, &req->channel_key, limit,
409                                   &ret_frags, &send_fragment, &sc);
410
411   switch (ret)
412   {
413   case GNUNET_YES:
414   case GNUNET_NO:
415     break;
416   default:
417     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
418                 _("Failed to get message!\n"));
419   }
420
421   send_result_code (client, req->op_id, (ret < 0) ? ret : ret_frags, NULL);
422   GNUNET_SERVER_receive_done (client, GNUNET_OK);
423 }
424
425
426 static void
427 handle_message_get_fragment (void *cls,
428                              struct GNUNET_SERVER_Client *client,
429                              const struct GNUNET_MessageHeader *msg)
430 {
431   const struct MessageGetFragmentRequest *
432     req = (const struct MessageGetFragmentRequest *) msg;
433   struct SendClosure
434     sc = { .op_id = req->op_id, .client = client,
435            .channel_key = req->channel_key, .slave_key = req->slave_key,
436            .membership_test = req->do_membership_test };
437
438   int ret = db->message_get_fragment (db->cls, &req->channel_key,
439                                       GNUNET_ntohll (req->message_id),
440                                       GNUNET_ntohll (req->fragment_offset),
441                                       &send_fragment, &sc);
442   switch (ret)
443   {
444   case GNUNET_YES:
445   case GNUNET_NO:
446     break;
447   default:
448     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
449                 _("Failed to get message fragment!\n"));
450   }
451
452   send_result_code (client, req->op_id, ret, NULL);
453   GNUNET_SERVER_receive_done (client, GNUNET_OK);
454 }
455
456
457 static void
458 handle_counters_get (void *cls,
459                      struct GNUNET_SERVER_Client *client,
460                      const struct GNUNET_MessageHeader *msg)
461 {
462   const struct OperationRequest *req = (const struct OperationRequest *) msg;
463   struct CountersResult res = { {0} };
464
465   int ret = db->counters_message_get (db->cls, &req->channel_key,
466                                       &res.max_fragment_id, &res.max_message_id,
467                                       &res.max_group_generation);
468   switch (ret)
469   {
470   case GNUNET_OK:
471     ret = db->counters_state_get (db->cls, &req->channel_key,
472                                   &res.max_state_message_id);
473   case GNUNET_NO:
474     break;
475   default:
476     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
477                 _("Failed to get master counters!\n"));
478   }
479
480   res.header.type = htons (GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_COUNTERS);
481   res.header.size = htons (sizeof (res));
482   res.result_code = htonl (ret);
483   res.op_id = req->op_id;
484   res.max_fragment_id = GNUNET_htonll (res.max_fragment_id);
485   res.max_message_id = GNUNET_htonll (res.max_message_id);
486   res.max_group_generation = GNUNET_htonll (res.max_group_generation);
487   res.max_state_message_id = GNUNET_htonll (res.max_state_message_id);
488
489   GNUNET_SERVER_notification_context_add (nc, client);
490   GNUNET_SERVER_notification_context_unicast (nc, client, &res.header,
491                                               GNUNET_NO);
492
493   GNUNET_SERVER_receive_done (client, GNUNET_OK);
494 }
495
496
497 struct StateModifyClosure
498 {
499   const struct GNUNET_CRYPTO_EddsaPublicKey channel_key;
500   struct GNUNET_PSYC_ReceiveHandle *recv;
501   enum GNUNET_PSYC_MessageState msg_state;
502   char mod_oper;
503   char *mod_name;
504   char *mod_value;
505   uint32_t mod_value_size;
506   uint32_t mod_value_remaining;
507 };
508
509
510 static void
511 recv_state_message_part (void *cls,
512                          const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
513                          uint64_t message_id, uint32_t flags, uint64_t data_offset,
514                          const struct GNUNET_MessageHeader *msg)
515 {
516   struct StateModifyClosure *scls = cls;
517   uint16_t psize;
518
519   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
520               "recv_state_message_part()  message_id: %" PRIu64
521               ", data_offset: %" PRIu64 ", flags: %u\n",
522               message_id, data_offset, flags);
523
524   if (NULL == msg)
525   {
526     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_ERROR;
527     return;
528   }
529
530   switch (ntohs (msg->type))
531   {
532   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD:
533   {
534     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_METHOD;
535     break;
536   }
537
538   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
539   {
540     struct GNUNET_PSYC_MessageModifier *
541       pmod = (struct GNUNET_PSYC_MessageModifier *) msg;
542     psize = ntohs (pmod->header.size);
543     uint16_t name_size = ntohs (pmod->name_size);
544     uint32_t value_size = ntohl (pmod->value_size);
545
546     const char *name = (const char *) &pmod[1];
547     const void *value = name + name_size;
548
549     if (GNUNET_ENV_OP_SET != pmod->oper)
550     { // Apply non-transient operation.
551       if (psize == sizeof (*pmod) + name_size + value_size)
552       {
553         db->state_modify_op (db->cls, &scls->channel_key,
554                              pmod->oper, name, value, value_size);
555       }
556       else
557       {
558         scls->mod_oper = pmod->oper;
559         scls->mod_name = GNUNET_malloc (name_size);
560         memcpy (scls->mod_name, name, name_size);
561
562         scls->mod_value_size = value_size;
563         scls->mod_value = GNUNET_malloc (scls->mod_value_size);
564         scls->mod_value_remaining
565           = scls->mod_value_size - (psize - sizeof (*pmod) - name_size);
566         memcpy (scls->mod_value, value, value_size - scls->mod_value_remaining);
567       }
568     }
569     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_MODIFIER;
570     break;
571   }
572
573   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MOD_CONT:
574     if (GNUNET_ENV_OP_SET != scls->mod_oper)
575     {
576       if (scls->mod_value_remaining == 0)
577       {
578         GNUNET_break_op (0);
579         scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_ERROR;
580       }
581       psize = ntohs (msg->size);
582       memcpy (scls->mod_value + (scls->mod_value_size - scls->mod_value_remaining),
583               &msg[1], psize - sizeof (*msg));
584       scls->mod_value_remaining -= psize - sizeof (*msg);
585       if (0 == scls->mod_value_remaining)
586       {
587         db->state_modify_op (db->cls, &scls->channel_key,
588                              scls->mod_oper, scls->mod_name,
589                              scls->mod_value, scls->mod_value_size);
590         GNUNET_free (scls->mod_name);
591         GNUNET_free (scls->mod_value);
592         scls->mod_oper = 0;
593         scls->mod_name = NULL;
594         scls->mod_value = NULL;
595         scls->mod_value_size = 0;
596       }
597     }
598     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_MOD_CONT;
599     break;
600
601   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
602     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_DATA;
603     break;
604
605   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_END:
606     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_END;
607     break;
608
609   default:
610     scls->msg_state = GNUNET_PSYC_MESSAGE_STATE_ERROR;
611   }
612 }
613
614
615 static int
616 recv_state_fragment (void *cls, struct GNUNET_MULTICAST_MessageHeader *msg,
617                      enum GNUNET_PSYCSTORE_MessageFlags flags)
618 {
619   struct StateModifyClosure *scls = cls;
620
621   if (NULL == scls->recv)
622   {
623     scls->recv = GNUNET_PSYC_receive_create (NULL, recv_state_message_part,
624                                              scls);
625   }
626
627   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
628               "recv_state_fragment: %" PRIu64 "\n", GNUNET_ntohll (msg->fragment_id));
629
630   struct GNUNET_PSYC_MessageHeader *
631     pmsg = GNUNET_PSYC_message_header_create (msg, flags);
632   GNUNET_PSYC_receive_message (scls->recv, pmsg);
633   GNUNET_free (pmsg);
634
635   return GNUNET_YES;
636 }
637
638
639 static void
640 handle_state_modify (void *cls,
641                      struct GNUNET_SERVER_Client *client,
642                      const struct GNUNET_MessageHeader *msg)
643 {
644   const struct StateModifyRequest *req
645     = (const struct StateModifyRequest *) msg;
646
647   uint64_t message_id = GNUNET_ntohll (req->message_id);
648   uint64_t state_delta = GNUNET_ntohll (req->state_delta);
649   uint64_t ret_frags = 0;
650   struct StateModifyClosure
651     scls = { .channel_key = req->channel_key };
652
653   int ret = db->state_modify_begin (db->cls, &req->channel_key,
654                                     message_id, state_delta);
655
656   if (GNUNET_OK != ret)
657   {
658     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
659                 _("Failed to begin modifying state: %d\n"), ret);
660   }
661   else
662   {
663     ret = db->message_get (db->cls, &req->channel_key,
664                            message_id, message_id,
665                            &ret_frags, recv_state_fragment, &scls);
666     if (GNUNET_OK != ret)
667     {
668       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
669                   _("Failed to modify state: %d\n"), ret);
670       GNUNET_break (0);
671     }
672     else
673     {
674       if (GNUNET_OK != db->state_modify_end (db->cls, &req->channel_key, message_id))
675       {
676         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
677                     _("Failed to end modifying state!\n"));
678         GNUNET_break (0);
679       }
680     }
681     if (NULL != scls.recv)
682     {
683       GNUNET_PSYC_receive_destroy (scls.recv);
684     }
685   }
686
687   send_result_code (client, req->op_id, ret, NULL);
688   GNUNET_SERVER_receive_done (client, GNUNET_OK);
689 }
690
691
692 /** @todo FIXME: stop processing further state sync messages after an error */
693 static void
694 handle_state_sync (void *cls,
695                    struct GNUNET_SERVER_Client *client,
696                    const struct GNUNET_MessageHeader *msg)
697 {
698   const struct StateSyncRequest *req
699     = (const struct StateSyncRequest *) msg;
700
701   int ret = GNUNET_SYSERR;
702   const char *name = (const char *) &req[1];
703   uint16_t name_size = ntohs (req->name_size);
704
705   if (name_size <= 2 || '\0' != name[name_size - 1])
706   {
707     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
708                 _("Tried to set invalid state variable name!\n"));
709     GNUNET_break_op (0);
710   }
711   else
712   {
713     ret = GNUNET_OK;
714
715     if (req->flags & STATE_OP_FIRST)
716     {
717       ret = db->state_sync_begin (db->cls, &req->channel_key);
718     }
719     if (ret != GNUNET_OK)
720     {
721       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
722                   _("Failed to begin synchronizing state!\n"));
723     }
724     else
725     {
726       ret = db->state_sync_assign (db->cls, &req->channel_key, name,
727                                    name + ntohs (req->name_size),
728                                    ntohs (req->header.size) - sizeof (*req)
729                                    - ntohs (req->name_size));
730     }
731
732     if (GNUNET_OK == ret && req->flags & STATE_OP_LAST)
733     {
734       ret = db->state_sync_end (db->cls, &req->channel_key,
735                                 GNUNET_ntohll (req->max_state_message_id),
736                                 GNUNET_ntohll (req->state_hash_message_id));
737       if (ret != GNUNET_OK)
738         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
739                     _("Failed to end synchronizing state!\n"));
740     }
741   }
742   send_result_code (client, req->op_id, ret, NULL);
743   GNUNET_SERVER_receive_done (client, GNUNET_OK);
744 }
745
746
747 static void
748 handle_state_reset (void *cls,
749                     struct GNUNET_SERVER_Client *client,
750                     const struct GNUNET_MessageHeader *msg)
751 {
752   const struct OperationRequest *req =
753     (const struct OperationRequest *) msg;
754
755   int ret = db->state_reset (db->cls, &req->channel_key);
756
757   if (ret != GNUNET_OK)
758     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
759                 _("Failed to reset state!\n"));
760
761   send_result_code (client, req->op_id, ret, NULL);
762   GNUNET_SERVER_receive_done (client, GNUNET_OK);
763 }
764
765
766 static void
767 handle_state_hash_update (void *cls,
768                           struct GNUNET_SERVER_Client *client,
769                           const struct GNUNET_MessageHeader *msg)
770 {
771   const struct OperationRequest *req =
772     (const struct OperationRequest *) msg;
773
774   int ret = db->state_reset (db->cls, &req->channel_key);
775
776   if (ret != GNUNET_OK)
777     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
778                 _("Failed to reset state!\n"));
779
780   send_result_code (client, req->op_id, ret, NULL);
781   GNUNET_SERVER_receive_done (client, GNUNET_OK);
782 }
783
784
785 static void
786 handle_state_get (void *cls,
787                   struct GNUNET_SERVER_Client *client,
788                   const struct GNUNET_MessageHeader *msg)
789 {
790   const struct OperationRequest *req =
791     (const struct OperationRequest *) msg;
792
793   struct SendClosure sc = { .op_id = req->op_id, .client = client };
794   int64_t ret = GNUNET_SYSERR;
795   const char *name = (const char *) &req[1];
796   uint16_t name_size = ntohs (req->header.size) - sizeof (*req);
797
798   if (name_size <= 2 || '\0' != name[name_size - 1])
799   {
800     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
801                 _("Tried to get invalid state variable name!\n"));
802     GNUNET_break (0);
803   }
804   else
805   {
806     ret = db->state_get (db->cls, &req->channel_key, name,
807                          &send_state_var, &sc);
808     if (GNUNET_NO == ret && name_size >= 5) /* min: _a_b\0 */
809     {
810       char *p, *n = GNUNET_malloc (name_size);
811       memcpy (n, name, name_size);
812       while (&n[1] < (p = strrchr (n, '_')) && GNUNET_NO == ret)
813       {
814         *p = '\0';
815         ret = db->state_get (db->cls, &req->channel_key, n,
816                              &send_state_var, &sc);
817       }
818       GNUNET_free (n);
819     }
820   }
821   switch (ret)
822   {
823   case GNUNET_OK:
824   case GNUNET_NO:
825     break;
826   default:
827     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
828                 _("Failed to get state variable!\n"));
829   }
830
831   send_result_code (client, req->op_id, ret, NULL);
832   GNUNET_SERVER_receive_done (client, GNUNET_OK);
833 }
834
835
836 static void
837 handle_state_get_prefix (void *cls,
838                          struct GNUNET_SERVER_Client *client,
839                          const struct GNUNET_MessageHeader *msg)
840 {
841   const struct OperationRequest *req =
842     (const struct OperationRequest *) msg;
843
844   struct SendClosure sc = { .op_id = req->op_id, .client = client };
845   int64_t ret = GNUNET_SYSERR;
846   const char *name = (const char *) &req[1];
847   uint16_t name_size = ntohs (req->header.size) - sizeof (*req);
848
849   if (name_size <= 1 || '\0' != name[name_size - 1])
850   {
851     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
852                 _("Tried to get invalid state variable name!\n"));
853     GNUNET_break (0);
854   }
855   else
856   {
857     ret = db->state_get_prefix (db->cls, &req->channel_key, name,
858                                 &send_state_var, &sc);
859   }
860   switch (ret)
861   {
862   case GNUNET_OK:
863   case GNUNET_NO:
864     break;
865   default:
866     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
867                 _("Failed to get state variable!\n"));
868   }
869
870   send_result_code (client, req->op_id, ret, NULL);
871   GNUNET_SERVER_receive_done (client, GNUNET_OK);
872 }
873
874
875 /**
876  * Initialize the PSYCstore service.
877  *
878  * @param cls Closure.
879  * @param server The initialized server.
880  * @param c Configuration to use.
881  */
882 static void
883 run (void *cls, struct GNUNET_SERVER_Handle *server,
884      const struct GNUNET_CONFIGURATION_Handle *c)
885 {
886   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
887     { &handle_membership_store, NULL,
888       GNUNET_MESSAGE_TYPE_PSYCSTORE_MEMBERSHIP_STORE,
889       sizeof (struct MembershipStoreRequest) },
890
891     { &handle_membership_test, NULL,
892       GNUNET_MESSAGE_TYPE_PSYCSTORE_MEMBERSHIP_TEST,
893       sizeof (struct MembershipTestRequest) },
894
895     { &handle_fragment_store, NULL,
896       GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_STORE, 0, },
897
898     { &handle_fragment_get, NULL,
899       GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_GET,
900       sizeof (struct FragmentGetRequest) },
901
902     { &handle_message_get, NULL,
903       GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET, 0 },
904
905     { &handle_message_get_fragment, NULL,
906       GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET_FRAGMENT,
907       sizeof (struct MessageGetFragmentRequest) },
908
909     { &handle_counters_get, NULL,
910       GNUNET_MESSAGE_TYPE_PSYCSTORE_COUNTERS_GET,
911       sizeof (struct OperationRequest) },
912
913     { &handle_state_modify, NULL,
914       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_MODIFY, 0 },
915
916     { &handle_state_sync, NULL,
917       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_SYNC, 0 },
918
919     { &handle_state_reset, NULL,
920       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_RESET,
921       sizeof (struct OperationRequest) },
922
923     { &handle_state_hash_update, NULL,
924       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_HASH_UPDATE,
925       sizeof (struct StateHashUpdateRequest) },
926
927     { &handle_state_get, NULL,
928       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_GET, 0 },
929
930     { &handle_state_get_prefix, NULL,
931       GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_GET_PREFIX, 0 },
932
933     { NULL, NULL, 0, 0 }
934   };
935
936   cfg = c;
937
938   /* Loading database plugin */
939   char *database;
940   if (GNUNET_OK !=
941       GNUNET_CONFIGURATION_get_value_string (cfg, "psycstore", "database",
942                                              &database))
943   {
944     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n");
945   }
946   else
947   {
948     GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_psycstore_%s", database);
949     db = GNUNET_PLUGIN_load (db_lib_name, (void *) cfg);
950     GNUNET_free (database);
951   }
952   if (NULL == db)
953   {
954     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
955                 "Could not load database backend `%s'\n",
956                 db_lib_name);
957     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
958     return;
959   }
960
961   stats = GNUNET_STATISTICS_create ("psycstore", cfg);
962   GNUNET_SERVER_add_handlers (server, handlers);
963   nc = GNUNET_SERVER_notification_context_create (server, 1);
964   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
965                                 NULL);
966 }
967
968
969 /**
970  * The main function for the service.
971  *
972  * @param argc number of arguments from the command line
973  * @param argv command line arguments
974  * @return 0 ok, 1 on error
975  */
976 int
977 main (int argc, char *const *argv)
978 {
979   return (GNUNET_OK ==
980           GNUNET_SERVICE_run (argc, argv, "psycstore",
981                               GNUNET_SERVICE_OPTION_NONE,
982                               &run, NULL)) ? 0 : 1;
983 }
984
985
986 /* end of gnunet-service-psycstore.c */