89be19a4259161522548701f516b47be16cc5253
[oweals/gnunet.git] / src / psycstore / psycstore_api.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/psycstore_api.c
23  * @brief API to interact with the 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_psycstore_service.h"
35 #include "gnunet_multicast_service.h"
36 #include "psycstore.h"
37
38 #define LOG(kind,...) GNUNET_log_from (kind, "psycstore-api",__VA_ARGS__)
39
40 /**
41  * Handle for an operation with the PSYCstore service.
42  */
43 struct GNUNET_PSYCSTORE_OperationHandle
44 {
45
46   /**
47    * Main PSYCstore handle.
48    */
49   struct GNUNET_PSYCSTORE_Handle *h;
50
51   /**
52    * Data callbacks.
53    */
54   union {
55     GNUNET_PSYCSTORE_FragmentCallback fragment_cb;
56     GNUNET_PSYCSTORE_CountersCallback counters_cb;
57     GNUNET_PSYCSTORE_StateCallback state_cb;
58   };
59
60   /**
61    * Closure for callbacks.
62    */
63   void *cls;
64
65   /**
66    * Message envelope.
67    */
68   struct GNUNET_MQ_Envelope *env;
69
70   /**
71    * Operation ID.
72    */
73   uint64_t op_id;
74 };
75
76
77 /**
78  * Handle for the service.
79  */
80 struct GNUNET_PSYCSTORE_Handle
81 {
82   /**
83    * Configuration to use.
84    */
85   const struct GNUNET_CONFIGURATION_Handle *cfg;
86
87   /**
88    * Client connection.
89    */
90   struct GNUNET_MQ_Handle *mq;
91
92   /**
93    * Async operations.
94    */
95   struct GNUNET_OP_Handle *op;
96
97   /**
98    * Task doing exponential back-off trying to reconnect.
99    */
100   struct GNUNET_SCHEDULER_Task *reconnect_task;
101
102   /**
103    * Delay for next connect retry.
104    */
105   struct GNUNET_TIME_Relative reconnect_delay;
106
107
108   GNUNET_PSYCSTORE_FragmentCallback *fragment_cb;
109
110   GNUNET_PSYCSTORE_CountersCallback *counters_cb;
111
112   GNUNET_PSYCSTORE_StateCallback *state_cb;
113   /**
114    * Closure for callbacks.
115    */
116   void *cb_cls;
117 };
118
119
120 static int
121 check_result_code (void *cls, const struct OperationResult *opres)
122 {
123   uint16_t size = ntohs (opres->header.size);
124   const char *str = (const char *) &opres[1];
125   if ( (sizeof (struct OperationResult) < size) &&
126        ('\0' != str[size - sizeof (*opres) - 1]) )
127   {
128     GNUNET_break (0);
129     return GNUNET_SYSERR;
130   }
131
132   return GNUNET_OK;
133 }
134
135
136 static void
137 handle_result_code (void *cls, const struct OperationResult *opres)
138 {
139   struct GNUNET_PSYCSTORE_Handle *h = cls;
140   struct GNUNET_PSYCSTORE_OperationHandle *op = NULL;
141   uint16_t size = ntohs (opres->header.size);
142
143   const char *
144     str = (sizeof (*opres) < size) ? (const char *) &opres[1] : "";
145
146   if (GNUNET_YES == GNUNET_OP_result (h->op, GNUNET_ntohll (opres->op_id),
147                                       GNUNET_ntohll (opres->result_code) + INT64_MIN,
148                                       str, size - sizeof (*opres), (void **) &op))
149   {
150     LOG (GNUNET_ERROR_TYPE_DEBUG,
151          "handle_result_code: Received result message with operation ID: %" PRIu64 "\n",
152          GNUNET_ntohll (opres->op_id));
153     GNUNET_free (op);
154   }
155   else
156   {
157     LOG (GNUNET_ERROR_TYPE_DEBUG,
158          "handle_result_code: No callback registered for operation with ID %" PRIu64 ".\n",
159          GNUNET_ntohll (opres->op_id));
160   }
161   h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
162 }
163
164
165 static void
166 handle_result_counters (void *cls, const struct CountersResult *cres)
167 {
168   struct GNUNET_PSYCSTORE_Handle *h = cls;
169   struct GNUNET_PSYCSTORE_OperationHandle *op = NULL;
170
171   if (GNUNET_YES == GNUNET_OP_get (h->op, GNUNET_ntohll (cres->op_id),
172                                    NULL, NULL, (void **) &op))
173   {
174     GNUNET_assert (NULL != op);
175     if (NULL != op->counters_cb)
176     {
177       op->counters_cb (op->cls,
178                        ntohl (cres->result_code),
179                        GNUNET_ntohll (cres->max_fragment_id),
180                        GNUNET_ntohll (cres->max_message_id),
181                        GNUNET_ntohll (cres->max_group_generation),
182                        GNUNET_ntohll (cres->max_state_message_id));
183     }
184     GNUNET_OP_remove (h->op, GNUNET_ntohll (cres->op_id));
185     GNUNET_free (op);
186   }
187   else
188   {
189     LOG (GNUNET_ERROR_TYPE_DEBUG,
190          "handle_result_counters: No callback registered for operation with ID %" PRIu64 ".\n",
191          GNUNET_ntohll (cres->op_id));
192   }
193   h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
194 }
195
196
197 static int
198 check_result_fragment (void *cls, const struct FragmentResult *fres)
199 {
200   uint16_t size = ntohs (fres->header.size);
201   struct GNUNET_MULTICAST_MessageHeader *mmsg =
202     (struct GNUNET_MULTICAST_MessageHeader *) &fres[1];
203   if (sizeof (*fres) + sizeof (*mmsg) < size
204       && sizeof (*fres) + ntohs (mmsg->header.size) != size)
205   {
206     LOG (GNUNET_ERROR_TYPE_ERROR,
207          "check_result_fragment: Received message with invalid length %lu bytes.\n",
208          size, sizeof (*fres));
209     GNUNET_break (0);
210     return GNUNET_SYSERR;
211   }
212   return GNUNET_OK;
213 }
214
215
216 static void
217 handle_result_fragment (void *cls, const struct FragmentResult *fres)
218 {
219   struct GNUNET_PSYCSTORE_Handle *h = cls;
220   struct GNUNET_PSYCSTORE_OperationHandle *op = NULL;
221
222   if (GNUNET_YES == GNUNET_OP_get (h->op, GNUNET_ntohll (fres->op_id),
223                                    NULL, NULL, (void **) &op))
224   {
225     GNUNET_assert (NULL != op);
226     if (NULL != op->fragment_cb)
227       op->fragment_cb (op->cls,
228                        (struct GNUNET_MULTICAST_MessageHeader *) &fres[1],
229                        ntohl (fres->psycstore_flags));
230     //GNUNET_OP_remove (h->op, GNUNET_ntohll (fres->op_id));
231     //GNUNET_free (op);
232   }
233   else
234   {
235     LOG (GNUNET_ERROR_TYPE_DEBUG,
236          "handle_result_fragment: No callback registered for operation with ID %" PRIu64 ".\n",
237          GNUNET_ntohll (fres->op_id));
238   }
239   h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
240 }
241
242
243 static int
244 check_result_state (void *cls, const struct StateResult *sres)
245 {
246   const char *name = (const char *) &sres[1];
247   uint16_t name_size = ntohs (sres->name_size);
248
249   if (name_size <= 2 || '\0' != name[name_size - 1])
250   {
251     LOG (GNUNET_ERROR_TYPE_ERROR,
252          "check_result_state: Received state result message with invalid name.\n");
253     GNUNET_break (0);
254     return GNUNET_SYSERR;
255   }
256   return GNUNET_OK;
257 }
258
259
260 static void
261 handle_result_state (void *cls, const struct StateResult *sres)
262 {
263   struct GNUNET_PSYCSTORE_Handle *h = cls;
264   struct GNUNET_PSYCSTORE_OperationHandle *op = NULL;
265
266   const char *name = (const char *) &sres[1];
267   uint16_t name_size = ntohs (sres->name_size);
268
269   if (GNUNET_YES == GNUNET_OP_get (h->op, GNUNET_ntohll (sres->op_id),
270                                    NULL, NULL, (void **) &op))
271   {
272     GNUNET_assert (NULL != op);
273     if (NULL != op->state_cb)
274        op->state_cb (op->cls, name, (char *) &sres[1] + name_size,
275                      ntohs (sres->header.size) - sizeof (*sres) - name_size);
276     //GNUNET_OP_remove (h->op, GNUNET_ntohll (sres->op_id));
277     //GNUNET_free (op);
278   }
279   else
280   {
281     LOG (GNUNET_ERROR_TYPE_DEBUG,
282          "handle_result_state: No callback registered for operation with ID %" PRIu64 ".\n",
283          GNUNET_ntohll (sres->op_id));
284   }
285   h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
286 }
287
288
289 static void
290 reconnect (void *cls);
291
292
293 /**
294  * Client disconnected from service.
295  *
296  * Reconnect after backoff period.=
297  */
298 static void
299 disconnected (void *cls, enum GNUNET_MQ_Error error)
300 {
301   struct GNUNET_PSYCSTORE_Handle *h = cls;
302
303   LOG (GNUNET_ERROR_TYPE_DEBUG,
304        "Origin client disconnected (%d), re-connecting\n",
305        (int) error);
306   if (NULL != h->mq)
307   {
308     GNUNET_MQ_destroy (h->mq);
309     GNUNET_OP_destroy (h->op);
310     h->mq = NULL;
311     h->op = NULL;
312   }
313
314   h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_delay,
315                                                     &reconnect, h);
316   h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay);
317 }
318
319
320 static void
321 do_connect (struct GNUNET_PSYCSTORE_Handle *h)
322 {
323   LOG (GNUNET_ERROR_TYPE_DEBUG,
324        "Connecting to PSYCstore service.\n");
325
326   GNUNET_MQ_hd_var_size (result_code,
327                          GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_CODE,
328                          struct OperationResult);
329
330   GNUNET_MQ_hd_fixed_size (result_counters,
331                            GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_COUNTERS,
332                            struct CountersResult);
333
334   GNUNET_MQ_hd_var_size (result_fragment,
335                          GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_FRAGMENT,
336                          struct FragmentResult);
337
338   GNUNET_MQ_hd_var_size (result_state,
339                          GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_STATE,
340                          struct StateResult);
341
342   struct GNUNET_MQ_MessageHandler handlers[] = {
343     make_result_code_handler (h),
344     make_result_counters_handler (h),
345     make_result_fragment_handler (h),
346     make_result_state_handler (h),
347     GNUNET_MQ_handler_end ()
348   };
349
350   h->op = GNUNET_OP_create ();
351   GNUNET_assert (NULL == h->mq);
352   h->mq = GNUNET_CLIENT_connecT (h->cfg, "psycstore",
353                                  handlers, disconnected, h);
354   GNUNET_assert (NULL != h->mq);
355 }
356
357
358 /**
359  * Try again to connect to the PSYCstore service.
360  *
361  * @param cls Handle to the PSYCstore service.
362  */
363 static void
364 reconnect (void *cls)
365 {
366   do_connect (cls);
367 }
368
369
370 /**
371  * Connect to the PSYCstore service.
372  *
373  * @param cfg The configuration to use
374  * @return Handle to use
375  */
376 struct GNUNET_PSYCSTORE_Handle *
377 GNUNET_PSYCSTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
378 {
379   struct GNUNET_PSYCSTORE_Handle *h
380     = GNUNET_new (struct GNUNET_PSYCSTORE_Handle);
381   h->cfg = cfg;
382   h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
383   do_connect (h);
384   return h;
385 }
386
387
388 /**
389  * Disconnect from PSYCstore service
390  *
391  * @param h Handle to destroy
392  */
393 void
394 GNUNET_PSYCSTORE_disconnect (struct GNUNET_PSYCSTORE_Handle *h)
395 {
396   GNUNET_assert (NULL != h);
397   if (h->reconnect_task != NULL)
398   {
399     GNUNET_SCHEDULER_cancel (h->reconnect_task);
400     h->reconnect_task = NULL;
401   }
402   if (NULL != h->mq)
403   {
404     // FIXME: free data structures for pending operations
405     GNUNET_MQ_destroy (h->mq);
406     h->mq = NULL;
407   }
408   GNUNET_free (h);
409 }
410
411
412 /**
413  * Message sent notification.
414  *
415  * Remove invalidated envelope pointer.
416  */
417 static void
418 message_sent (void *cls)
419 {
420   struct GNUNET_PSYCSTORE_OperationHandle *op = cls;
421   op->env = NULL;
422 }
423
424
425 /**
426  * Create a new operation.
427  */
428 static struct GNUNET_PSYCSTORE_OperationHandle *
429 op_create (struct GNUNET_PSYCSTORE_Handle *h,
430            struct GNUNET_OP_Handle *hop,
431            GNUNET_PSYCSTORE_ResultCallback result_cb,
432            void *cls)
433 {
434   struct GNUNET_PSYCSTORE_OperationHandle *
435     op = GNUNET_malloc (sizeof (*op));
436   op->h = h;
437   op->op_id = GNUNET_OP_add (hop,
438                              (GNUNET_ResultCallback) result_cb,
439                              cls, op);
440   return op;
441 }
442
443
444 /**
445  * Send a message associated with an operation.
446  *
447  * @param h
448  *        PSYCstore handle.
449  * @param op
450  *        Operation handle.
451  * @param env
452  *        Message envelope to send.
453  * @param[out] op_id
454  *        Operation ID to write in network byte order. NULL if not needed.
455  *
456  * @return Operation handle.
457  *
458  */
459 static struct GNUNET_PSYCSTORE_OperationHandle *
460 op_send (struct GNUNET_PSYCSTORE_Handle *h,
461          struct GNUNET_PSYCSTORE_OperationHandle *op,
462          struct GNUNET_MQ_Envelope *env,
463          uint64_t *op_id)
464 {
465   op->env = env;
466   if (NULL != op_id)
467     *op_id = GNUNET_htonll (op->op_id);
468
469   GNUNET_MQ_notify_sent (env, message_sent, op);
470   GNUNET_MQ_send (h->mq, env);
471   return op;
472 }
473
474
475 /**
476  * Cancel a PSYCstore operation. Note that the operation MAY still
477  * be executed; this merely cancels the continuation; if the request
478  * was already transmitted, the service may still choose to complete
479  * the operation.
480  *
481  * @param op Operation to cancel.
482  *
483  * @return #GNUNET_YES if message was not sent yet and got discarded,
484  *         #GNUNET_NO  if it was already sent, and only the callbacks got cancelled.
485  */
486 int
487 GNUNET_PSYCSTORE_operation_cancel (struct GNUNET_PSYCSTORE_OperationHandle *op)
488 {
489   struct GNUNET_PSYCSTORE_Handle *h = op->h;
490   int ret = GNUNET_NO;
491
492   if (NULL != op->env)
493   {
494     GNUNET_MQ_send_cancel (op->env);
495     ret = GNUNET_YES;
496   }
497
498   GNUNET_OP_remove (h->op, op->op_id);
499   GNUNET_free (op);
500
501   return ret;
502 }
503
504
505 /**
506  * Store join/leave events for a PSYC channel in order to be able to answer
507  * membership test queries later.
508  *
509  * @param h
510  *        Handle for the PSYCstore.
511  * @param channel_key
512  *        The channel where the event happened.
513  * @param slave_key
514  *        Public key of joining/leaving slave.
515  * @param did_join
516  *        #GNUNET_YES on join, #GNUNET_NO on part.
517  * @param announced_at
518  *        ID of the message that announced the membership change.
519  * @param effective_since
520  *        Message ID this membership change is in effect since.
521  *        For joins it is <= announced_at, for parts it is always 0.
522  * @param group_generation
523  *        In case of a part, the last group generation the slave has access to.
524  *        It has relevance when a larger message have fragments with different
525  *        group generations.
526  * @param result_cb
527  *        Callback to call with the result of the storage operation.
528  * @param cls
529  *        Closure for the callback.
530  *
531  * @return Operation handle that can be used to cancel the operation.
532  */
533 struct GNUNET_PSYCSTORE_OperationHandle *
534 GNUNET_PSYCSTORE_membership_store (struct GNUNET_PSYCSTORE_Handle *h,
535                                    const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
536                                    const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
537                                    int did_join,
538                                    uint64_t announced_at,
539                                    uint64_t effective_since,
540                                    uint64_t group_generation,
541                                    GNUNET_PSYCSTORE_ResultCallback result_cb,
542                                    void *cls)
543 {
544   GNUNET_assert (NULL != h);
545   GNUNET_assert (NULL != channel_key);
546   GNUNET_assert (NULL != slave_key);
547   GNUNET_assert (GNUNET_YES == did_join || GNUNET_NO == did_join);
548   GNUNET_assert (did_join
549                  ? effective_since <= announced_at
550                  : effective_since == 0);
551
552   struct MembershipStoreRequest *req;
553   struct GNUNET_MQ_Envelope *
554     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_MEMBERSHIP_STORE);
555   req->channel_key = *channel_key;
556   req->slave_key = *slave_key;
557   req->did_join = did_join;
558   req->announced_at = GNUNET_htonll (announced_at);
559   req->effective_since = GNUNET_htonll (effective_since);
560   req->group_generation = GNUNET_htonll (group_generation);
561
562   return
563     op_send (h, op_create (h, h->op, result_cb, cls),
564              env, &req->op_id);
565 }
566
567
568 /**
569  * Test if a member was admitted to the channel at the given message ID.
570  *
571  * This is useful when relaying and replaying messages to check if a particular
572  * slave has access to the message fragment with a given group generation.  It
573  * is also used when handling join requests to determine whether the slave is
574  * currently admitted to the channel.
575  *
576  * @param h
577  *        Handle for the PSYCstore.
578  * @param channel_key
579  *        The channel we are interested in.
580  * @param slave_key
581  *        Public key of slave whose membership to check.
582  * @param message_id
583  *        Message ID for which to do the membership test.
584  * @param group_generation
585  *        Group generation of the fragment of the message to test.
586  *        It has relevance if the message consists of multiple fragments with
587  *        different group generations.
588  * @param result_cb
589  *        Callback to call with the test result.
590  * @param cls
591  *        Closure for the callback.
592  *
593  * @return Operation handle that can be used to cancel the operation.
594  */
595 struct GNUNET_PSYCSTORE_OperationHandle *
596 GNUNET_PSYCSTORE_membership_test (struct GNUNET_PSYCSTORE_Handle *h,
597                                   const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
598                                   const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
599                                   uint64_t message_id,
600                                   uint64_t group_generation,
601                                   GNUNET_PSYCSTORE_ResultCallback result_cb,
602                                   void *cls)
603 {
604   struct MembershipTestRequest *req;
605   struct GNUNET_MQ_Envelope *
606     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_MEMBERSHIP_TEST);
607   req->channel_key = *channel_key;
608   req->slave_key = *slave_key;
609   req->message_id = GNUNET_htonll (message_id);
610   req->group_generation = GNUNET_htonll (group_generation);
611
612   return
613     op_send (h, op_create (h, h->op, result_cb, cls),
614              env, &req->op_id);
615 }
616
617
618 /**
619  * Store a message fragment sent to a channel.
620  *
621  * @param h Handle for the PSYCstore.
622  * @param channel_key The channel the message belongs to.
623  * @param message Message to store.
624  * @param psycstore_flags Flags indicating whether the PSYC message contains
625  *        state modifiers.
626  * @param result_cb Callback to call with the result of the operation.
627  * @param cls Closure for the callback.
628  *
629  * @return Handle that can be used to cancel the operation.
630  */
631 struct GNUNET_PSYCSTORE_OperationHandle *
632 GNUNET_PSYCSTORE_fragment_store (struct GNUNET_PSYCSTORE_Handle *h,
633                                  const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
634                                  const struct GNUNET_MULTICAST_MessageHeader *msg,
635                                  enum GNUNET_PSYCSTORE_MessageFlags psycstore_flags,
636                                  GNUNET_PSYCSTORE_ResultCallback result_cb,
637                                  void *cls)
638 {
639   uint16_t size = ntohs (msg->header.size);
640   struct FragmentStoreRequest *req;
641   struct GNUNET_MQ_Envelope *
642     env = GNUNET_MQ_msg_extra (req, size,
643                                GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_STORE);
644   req->channel_key = *channel_key;
645   req->psycstore_flags = htonl (psycstore_flags);
646   GNUNET_memcpy (&req[1], msg, size);
647
648   return
649     op_send (h, op_create (h, h->op, result_cb, cls),
650              env, &req->op_id);
651 }
652
653
654 /**
655  * Retrieve message fragments by fragment ID range.
656  *
657  * @param h
658  *        Handle for the PSYCstore.
659  * @param channel_key
660  *        The channel we are interested in.
661  * @param slave_key
662  *        The slave requesting the fragment.  If not NULL, a membership test is
663  *        performed first and the fragment is only returned if the slave has
664  *        access to it.
665  * @param first_fragment_id
666  *        First fragment ID to retrieve.
667  *        Use 0 to get the latest message fragment.
668  * @param last_fragment_id
669  *        Last consecutive fragment ID to retrieve.
670  *        Use 0 to get the latest message fragment.
671  * @param fragment_limit
672  *        Maximum number of fragments to retrieve.
673  * @param fragment_cb
674  *        Callback to call with the retrieved fragments.
675  * @param result_cb
676  *        Callback to call with the result of the operation.
677  * @param cls
678  *        Closure for the callbacks.
679  *
680  * @return Handle that can be used to cancel the operation.
681  */
682 struct GNUNET_PSYCSTORE_OperationHandle *
683 GNUNET_PSYCSTORE_fragment_get (struct GNUNET_PSYCSTORE_Handle *h,
684                                const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
685                                const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
686                                uint64_t first_fragment_id,
687                                uint64_t last_fragment_id,
688                                GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
689                                GNUNET_PSYCSTORE_ResultCallback result_cb,
690                                void *cls)
691 {
692   struct FragmentGetRequest *req;
693   struct GNUNET_MQ_Envelope *
694     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_GET);
695   req->channel_key = *channel_key;
696   req->first_fragment_id = GNUNET_htonll (first_fragment_id);
697   req->last_fragment_id = GNUNET_htonll (last_fragment_id);
698   if (NULL != slave_key)
699   {
700     req->slave_key = *slave_key;
701     req->do_membership_test = GNUNET_YES;
702   }
703
704   struct GNUNET_PSYCSTORE_OperationHandle *
705     op = op_create (h, h->op, result_cb, cls);
706   op->fragment_cb = fragment_cb;
707   op->cls = cls;
708   return op_send (h, op, env, &req->op_id);
709 }
710
711
712 /**
713  * Retrieve latest message fragments.
714  *
715  * @param h
716  *        Handle for the PSYCstore.
717  * @param channel_key
718  *        The channel we are interested in.
719  * @param slave_key
720  *        The slave requesting the fragment.  If not NULL, a membership test is
721  *        performed first and the fragment is only returned if the slave has
722  *        access to it.
723  * @param first_fragment_id
724  *        First fragment ID to retrieve.
725  *        Use 0 to get the latest message fragment.
726  * @param last_fragment_id
727  *        Last consecutive fragment ID to retrieve.
728  *        Use 0 to get the latest message fragment.
729  * @param fragment_limit
730  *        Maximum number of fragments to retrieve.
731  * @param fragment_cb
732  *        Callback to call with the retrieved fragments.
733  * @param result_cb
734  *        Callback to call with the result of the operation.
735  * @param cls
736  *        Closure for the callbacks.
737  *
738  * @return Handle that can be used to cancel the operation.
739  */
740 struct GNUNET_PSYCSTORE_OperationHandle *
741 GNUNET_PSYCSTORE_fragment_get_latest (struct GNUNET_PSYCSTORE_Handle *h,
742                                       const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
743                                       const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
744                                       uint64_t fragment_limit,
745                                       GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
746                                       GNUNET_PSYCSTORE_ResultCallback result_cb,
747                                       void *cls)
748 {
749   struct FragmentGetRequest *req;
750   struct GNUNET_MQ_Envelope *
751     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_GET);
752   req->channel_key = *channel_key;
753   req->fragment_limit = GNUNET_ntohll (fragment_limit);
754   if (NULL != slave_key)
755   {
756     req->slave_key = *slave_key;
757     req->do_membership_test = GNUNET_YES;
758   }
759
760   struct GNUNET_PSYCSTORE_OperationHandle *
761     op = op_create (h, h->op, result_cb, cls);
762   op->fragment_cb = fragment_cb;
763   op->cls = cls;
764   return op_send (h, op, env, &req->op_id);
765 }
766
767
768 /**
769  * Retrieve all fragments of messages in a message ID range.
770  *
771  * @param h
772  *        Handle for the PSYCstore.
773  * @param channel_key
774  *        The channel we are interested in.
775  * @param slave_key
776  *        The slave requesting the message.
777  *        If not NULL, a membership test is performed first
778  *        and the message is only returned if the slave has access to it.
779  * @param first_message_id
780  *        First message ID to retrieve.
781  * @param last_message_id
782  *        Last consecutive message ID to retrieve.
783  * @param fragment_limit
784  *        Maximum number of fragments to retrieve.
785  * @param method_prefix
786  *        Retrieve only messages with a matching method prefix.
787  * @todo Implement method_prefix query.
788  * @param fragment_cb
789  *        Callback to call with the retrieved fragments.
790  * @param result_cb
791  *        Callback to call with the result of the operation.
792  * @param cls
793  *        Closure for the callbacks.
794  *
795  * @return Handle that can be used to cancel the operation.
796  */
797 struct GNUNET_PSYCSTORE_OperationHandle *
798 GNUNET_PSYCSTORE_message_get (struct GNUNET_PSYCSTORE_Handle *h,
799                               const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
800                               const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
801                               uint64_t first_message_id,
802                               uint64_t last_message_id,
803                               uint64_t fragment_limit,
804                               const char *method_prefix,
805                               GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
806                               GNUNET_PSYCSTORE_ResultCallback result_cb,
807                               void *cls)
808 {
809   struct MessageGetRequest *req;
810   if (NULL == method_prefix)
811     method_prefix = "";
812   uint16_t method_size = strnlen (method_prefix,
813                                   GNUNET_SERVER_MAX_MESSAGE_SIZE
814                                   - sizeof (*req)) + 1;
815
816   struct GNUNET_MQ_Envelope *
817     env = GNUNET_MQ_msg_extra (req, method_size,
818                                GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET);
819   req->channel_key = *channel_key;
820   req->first_message_id = GNUNET_htonll (first_message_id);
821   req->last_message_id = GNUNET_htonll (last_message_id);
822   req->fragment_limit = GNUNET_htonll (fragment_limit);
823   if (NULL != slave_key)
824   {
825     req->slave_key = *slave_key;
826     req->do_membership_test = GNUNET_YES;
827   }
828   GNUNET_memcpy (&req[1], method_prefix, method_size);
829   ((char *) &req[1])[method_size - 1] = '\0';
830
831   struct GNUNET_PSYCSTORE_OperationHandle *
832     op = op_create (h, h->op, result_cb, cls);
833   op->fragment_cb = fragment_cb;
834   op->cls = cls;
835   return op_send (h, op, env, &req->op_id);
836 }
837
838
839 /**
840  * Retrieve all fragments of the latest messages.
841  *
842  * @param h
843  *        Handle for the PSYCstore.
844  * @param channel_key
845  *        The channel we are interested in.
846  * @param slave_key
847  *        The slave requesting the message.
848  *        If not NULL, a membership test is performed first
849  *        and the message is only returned if the slave has access to it.
850  * @param message_limit
851  *        Maximum number of messages to retrieve.
852  * @param method_prefix
853  *        Retrieve only messages with a matching method prefix.
854  * @todo Implement method_prefix query.
855  * @param fragment_cb
856  *        Callback to call with the retrieved fragments.
857  * @param result_cb
858  *        Callback to call with the result of the operation.
859  * @param cls
860  *        Closure for the callbacks.
861  *
862  * @return Handle that can be used to cancel the operation.
863  */
864 struct GNUNET_PSYCSTORE_OperationHandle *
865 GNUNET_PSYCSTORE_message_get_latest (struct GNUNET_PSYCSTORE_Handle *h,
866                                      const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
867                                      const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
868                                      uint64_t message_limit,
869                                      const char *method_prefix,
870                                      GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
871                                      GNUNET_PSYCSTORE_ResultCallback result_cb,
872                                      void *cls)
873 {
874   struct MessageGetRequest *req;
875
876   if (NULL == method_prefix)
877     method_prefix = "";
878   uint16_t method_size = strnlen (method_prefix,
879                                   GNUNET_SERVER_MAX_MESSAGE_SIZE
880                                   - sizeof (*req)) + 1;
881   GNUNET_assert ('\0' == method_prefix[method_size - 1]);
882
883   struct GNUNET_MQ_Envelope *
884     env = GNUNET_MQ_msg_extra (req, method_size,
885                                GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET);
886   req->channel_key = *channel_key;
887   req->message_limit = GNUNET_ntohll (message_limit);
888   if (NULL != slave_key)
889   {
890     req->slave_key = *slave_key;
891     req->do_membership_test = GNUNET_YES;
892   }
893   GNUNET_memcpy (&req[1], method_prefix, method_size);
894
895   struct GNUNET_PSYCSTORE_OperationHandle *
896     op = op_create (h, h->op, result_cb, cls);
897   op->fragment_cb = fragment_cb;
898   op->cls = cls;
899   return op_send (h, op, env, &req->op_id);
900 }
901
902
903 /**
904  * Retrieve a fragment of message specified by its message ID and fragment
905  * offset.
906  *
907  * @param h
908  *        Handle for the PSYCstore.
909  * @param channel_key
910  *        The channel we are interested in.
911  * @param slave_key
912  *        The slave requesting the message fragment.  If not NULL, a membership
913  *        test is performed first and the message fragment is only returned
914  *        if the slave has access to it.
915  * @param message_id
916  *        Message ID to retrieve.  Use 0 to get the latest message.
917  * @param fragment_offset
918  *        Offset of the fragment to retrieve.
919  * @param fragment_cb
920  *        Callback to call with the retrieved fragments.
921  * @param result_cb
922  *        Callback to call with the result of the operation.
923  * @param cls
924  *        Closure for the callbacks.
925  *
926  * @return Handle that can be used to cancel the operation.
927  */
928 struct GNUNET_PSYCSTORE_OperationHandle *
929 GNUNET_PSYCSTORE_message_get_fragment (struct GNUNET_PSYCSTORE_Handle *h,
930                                        const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
931                                        const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
932                                        uint64_t message_id,
933                                        uint64_t fragment_offset,
934                                        GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
935                                        GNUNET_PSYCSTORE_ResultCallback result_cb,
936                                        void *cls)
937 {
938   struct MessageGetFragmentRequest *req;
939   struct GNUNET_MQ_Envelope *
940     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET_FRAGMENT);
941
942   req->channel_key = *channel_key;
943   req->message_id = GNUNET_htonll (message_id);
944   req->fragment_offset = GNUNET_htonll (fragment_offset);
945   if (NULL != slave_key)
946   {
947     req->slave_key = *slave_key;
948     req->do_membership_test = GNUNET_YES;
949   }
950
951   struct GNUNET_PSYCSTORE_OperationHandle *
952     op = op_create (h, h->op, result_cb, cls);
953   op->fragment_cb = fragment_cb;
954   op->cls = cls;
955   return op_send (h, op, env, &req->op_id);
956 }
957
958
959 /**
960  * Retrieve latest values of counters for a channel master.
961  *
962  * The current value of counters are needed when a channel master is restarted,
963  * so that it can continue incrementing the counters from their last value.
964  *
965  * @param h
966  *        Handle for the PSYCstore.
967  * @param channel_key
968  *        Public key that identifies the channel.
969  * @param ccb
970  *        Callback to call with the result.
971  * @param ccb_cls
972  *        Closure for the @a ccb callback.
973  *
974  * @return Handle that can be used to cancel the operation.
975  */
976 struct GNUNET_PSYCSTORE_OperationHandle *
977 GNUNET_PSYCSTORE_counters_get (struct GNUNET_PSYCSTORE_Handle *h,
978                                struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
979                                GNUNET_PSYCSTORE_CountersCallback counters_cb,
980                                void *cls)
981 {
982   struct OperationRequest *req;
983   struct GNUNET_MQ_Envelope *
984     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_COUNTERS_GET);
985   req->channel_key = *channel_key;
986
987   struct GNUNET_PSYCSTORE_OperationHandle *
988     op = op_create (h, h->op, NULL, NULL);
989   op->counters_cb = counters_cb;
990   op->cls = cls;
991   return op_send (h, op, env, &req->op_id);
992 }
993
994
995 /**
996  * Apply modifiers of a message to the current channel state.
997  *
998  * An error is returned if there are missing messages containing state
999  * operations before the current one.
1000  *
1001  * @param h
1002  *        Handle for the PSYCstore.
1003  * @param channel_key
1004  *        The channel we are interested in.
1005  * @param message_id
1006  *        ID of the message that contains the @a modifiers.
1007  * @param state_delta
1008  *        Value of the _state_delta PSYC header variable of the message.
1009  * @param result_cb
1010  *        Callback to call with the result of the operation.
1011  * @param cls
1012  *        Closure for @a result_cb.
1013  *
1014  * @return Handle that can be used to cancel the operation.
1015  */
1016 struct GNUNET_PSYCSTORE_OperationHandle *
1017 GNUNET_PSYCSTORE_state_modify (struct GNUNET_PSYCSTORE_Handle *h,
1018                                const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1019                                uint64_t message_id,
1020                                uint64_t state_delta,
1021                                GNUNET_PSYCSTORE_ResultCallback result_cb,
1022                                void *cls)
1023 {
1024   struct StateModifyRequest *req;
1025   struct GNUNET_MQ_Envelope *
1026     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_MODIFY);
1027   req->channel_key = *channel_key;
1028   req->message_id = GNUNET_htonll (message_id);
1029   req->state_delta = GNUNET_htonll (state_delta);
1030
1031   return op_send (h, op_create (h, h->op, result_cb, cls),
1032                   env, &req->op_id);
1033 }
1034
1035
1036 struct StateSyncClosure
1037 {
1038   GNUNET_PSYCSTORE_ResultCallback result_cb;
1039   void *cls;
1040   uint8_t last;
1041 };
1042
1043
1044 static void
1045 state_sync_result (void *cls, int64_t result,
1046                    const char *err_msg, uint16_t err_msg_size)
1047 {
1048   struct StateSyncClosure *ssc = cls;
1049   if (GNUNET_OK != result || ssc->last)
1050     ssc->result_cb (ssc->cls, result, err_msg, err_msg_size);
1051   GNUNET_free (ssc);
1052 }
1053
1054
1055 /**
1056  * Store synchronized state.
1057  *
1058  * @param h
1059  *        Handle for the PSYCstore.
1060  * @param channel_key
1061  *        The channel we are interested in.
1062  * @param max_state_message_id
1063  *        ID of the last stateful message before @a state_hash_message_id.
1064  * @param state_hash_message_id
1065  *        ID of the message that contains the state_hash PSYC header variable.
1066  * @param modifier_count
1067  *        Number of elements in the @a modifiers array.
1068  * @param modifiers
1069  *        Full state to store.
1070  * @param result_cb
1071  *        Callback to call with the result of the operation.
1072  * @param cls
1073  *        Closure for the callback.
1074  *
1075  * @return Handle that can be used to cancel the operation.
1076  */
1077 struct GNUNET_PSYCSTORE_OperationHandle *
1078 GNUNET_PSYCSTORE_state_sync (struct GNUNET_PSYCSTORE_Handle *h,
1079                              const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1080                              uint64_t max_state_message_id,
1081                              uint64_t state_hash_message_id,
1082                              size_t modifier_count,
1083                              const struct GNUNET_PSYC_Modifier *modifiers,
1084                              GNUNET_PSYCSTORE_ResultCallback result_cb,
1085                              void *cls)
1086 {
1087   struct GNUNET_PSYCSTORE_OperationHandle *op = NULL;
1088   size_t i;
1089
1090   for (i = 0; i < modifier_count; i++) {
1091     struct StateSyncRequest *req;
1092     uint16_t name_size = strlen (modifiers[i].name) + 1;
1093
1094     struct GNUNET_MQ_Envelope *
1095       env = GNUNET_MQ_msg_extra (req,
1096                                  sizeof (*req) + name_size + modifiers[i].value_size,
1097                                  GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_SYNC);
1098
1099     req->header.type = htons (GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_SYNC);
1100     req->header.size = htons (sizeof (*req) + name_size
1101                               + modifiers[i].value_size);
1102     req->channel_key = *channel_key;
1103     req->max_state_message_id = GNUNET_htonll (max_state_message_id);
1104     req->state_hash_message_id = GNUNET_htonll (state_hash_message_id);
1105     req->name_size = htons (name_size);
1106     req->flags
1107       = (0 == i)
1108       ? STATE_OP_FIRST
1109       : (modifier_count - 1 == i)
1110       ? STATE_OP_LAST
1111       : 0;
1112
1113     GNUNET_memcpy (&req[1], modifiers[i].name, name_size);
1114     GNUNET_memcpy ((char *) &req[1] + name_size, modifiers[i].value, modifiers[i].value_size);
1115
1116     struct StateSyncClosure *ssc = GNUNET_malloc (sizeof (*ssc));
1117     ssc->last = (req->flags & STATE_OP_LAST);
1118     ssc->result_cb = result_cb;
1119     ssc->cls = cls;
1120
1121     op_send (h, op_create (h, h->op, state_sync_result, ssc),
1122              env, &req->op_id);
1123   }
1124   // FIXME: only one operation is returned,
1125   //        add pointers to other operations and make all cancellable.
1126   return op;
1127 }
1128
1129
1130 /**
1131  * Reset the state of a channel.
1132  *
1133  * Delete all state variables stored for the given channel.
1134  *
1135  * @param h
1136  *        Handle for the PSYCstore.
1137  * @param channel_key
1138  *        The channel we are interested in.
1139  * @param result_cb
1140  *        Callback to call with the result of the operation.
1141  * @param cls
1142  *        Closure for the callback.
1143  *
1144  * @return Handle that can be used to cancel the operation.
1145  */
1146 struct GNUNET_PSYCSTORE_OperationHandle *
1147 GNUNET_PSYCSTORE_state_reset (struct GNUNET_PSYCSTORE_Handle *h,
1148                               const struct GNUNET_CRYPTO_EddsaPublicKey
1149                               *channel_key,
1150                               GNUNET_PSYCSTORE_ResultCallback result_cb,
1151                               void *cls)
1152 {
1153   struct OperationRequest *req;
1154   struct GNUNET_MQ_Envelope *
1155     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_RESET);
1156   req->channel_key = *channel_key;
1157
1158   return
1159     op_send (h, op_create (h, h->op, result_cb, cls),
1160              env, &req->op_id);
1161 }
1162
1163
1164 /**
1165  * Update signed values of state variables in the state store.
1166  *
1167  * @param h
1168  *        Handle for the PSYCstore.
1169  * @param channel_key
1170  *        The channel we are interested in.
1171  * @param message_id
1172  *        Message ID that contained the state @a hash.
1173  * @param hash
1174  *        Hash of the serialized full state.
1175  * @param result_cb
1176  *        Callback to call with the result of the operation.
1177  * @param cls
1178  *        Closure for the callback.
1179  */
1180 struct GNUNET_PSYCSTORE_OperationHandle *
1181 GNUNET_PSYCSTORE_state_hash_update (struct GNUNET_PSYCSTORE_Handle *h,
1182                                     const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1183                                     uint64_t message_id,
1184                                     const struct GNUNET_HashCode *hash,
1185                                     GNUNET_PSYCSTORE_ResultCallback result_cb,
1186                                     void *cls)
1187 {
1188   struct StateHashUpdateRequest *req;
1189   struct GNUNET_MQ_Envelope *
1190     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_HASH_UPDATE);
1191   req->channel_key = *channel_key;
1192   req->hash = *hash;
1193
1194   return
1195     op_send (h, op_create (h, h->op, result_cb, cls),
1196              env, &req->op_id);
1197 }
1198
1199
1200 /**
1201  * Retrieve the best matching state variable.
1202  *
1203  * @param h
1204  *        Handle for the PSYCstore.
1205  * @param channel_key
1206  *        The channel we are interested in.
1207  * @param name
1208  *        Name of variable to match, the returned variable might be less specific.
1209  * @param state_cb
1210  *        Callback to return the matching state variable.
1211  * @param result_cb
1212  *        Callback to call with the result of the operation.
1213  * @param cls
1214  *        Closure for the callbacks.
1215  *
1216  * @return Handle that can be used to cancel the operation.
1217  */
1218 struct GNUNET_PSYCSTORE_OperationHandle *
1219 GNUNET_PSYCSTORE_state_get (struct GNUNET_PSYCSTORE_Handle *h,
1220                             const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1221                             const char *name,
1222                             GNUNET_PSYCSTORE_StateCallback state_cb,
1223                             GNUNET_PSYCSTORE_ResultCallback result_cb,
1224                             void *cls)
1225 {
1226   size_t name_size = strlen (name) + 1;
1227   struct OperationRequest *req;
1228   struct GNUNET_MQ_Envelope *
1229     env = GNUNET_MQ_msg_extra (req, name_size,
1230                                GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_GET);
1231   req->channel_key = *channel_key;
1232   GNUNET_memcpy (&req[1], name, name_size);
1233
1234   struct GNUNET_PSYCSTORE_OperationHandle *
1235     op = op_create (h, h->op, result_cb, cls);
1236   op->state_cb = state_cb;
1237   op->cls = cls;
1238   return op_send (h, op, env, &req->op_id);
1239 }
1240
1241
1242 /**
1243  * Retrieve all state variables for a channel with the given prefix.
1244  *
1245  * @param h
1246  *        Handle for the PSYCstore.
1247  * @param channel_key
1248  *        The channel we are interested in.
1249  * @param name_prefix
1250  *        Prefix of state variable names to match.
1251  * @param state_cb
1252  *        Callback to return matching state variables.
1253  * @param result_cb
1254  *        Callback to call with the result of the operation.
1255  * @param cls
1256  *        Closure for the callbacks.
1257  *
1258  * @return Handle that can be used to cancel the operation.
1259  */
1260 struct GNUNET_PSYCSTORE_OperationHandle *
1261 GNUNET_PSYCSTORE_state_get_prefix (struct GNUNET_PSYCSTORE_Handle *h,
1262                                    const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1263                                    const char *name_prefix,
1264                                    GNUNET_PSYCSTORE_StateCallback state_cb,
1265                                    GNUNET_PSYCSTORE_ResultCallback result_cb,
1266                                    void *cls)
1267 {
1268   size_t name_size = strlen (name_prefix) + 1;
1269   struct OperationRequest *req;
1270   struct GNUNET_MQ_Envelope *
1271     env = GNUNET_MQ_msg_extra (req, name_size,
1272                                GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_GET_PREFIX);
1273   req->channel_key = *channel_key;
1274   GNUNET_memcpy (&req[1], name_prefix, name_size);
1275
1276   struct GNUNET_PSYCSTORE_OperationHandle *
1277     op = op_create (h, h->op, result_cb, cls);
1278   op->state_cb = state_cb;
1279   op->cls = cls;
1280   return op_send (h, op, env, &req->op_id);
1281 }
1282
1283 /* end of psycstore_api.c */