-rps doxygen
[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   struct GNUNET_MQ_MessageHandler handlers[] = {
327     GNUNET_MQ_hd_var_size (result_code,
328                            GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_CODE,
329                            struct OperationResult,
330                            h),
331     GNUNET_MQ_hd_fixed_size (result_counters,
332                              GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_COUNTERS,
333                              struct CountersResult,
334                              h),
335     GNUNET_MQ_hd_var_size (result_fragment,
336                            GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_FRAGMENT,
337                            struct FragmentResult,
338                            h),
339     GNUNET_MQ_hd_var_size (result_state,
340                            GNUNET_MESSAGE_TYPE_PSYCSTORE_RESULT_STATE,
341                            struct StateResult,
342                            h),
343     GNUNET_MQ_handler_end ()
344   };
345
346   h->op = GNUNET_OP_create ();
347   GNUNET_assert (NULL == h->mq);
348   h->mq = GNUNET_CLIENT_connecT (h->cfg, "psycstore",
349                                  handlers, disconnected, h);
350   GNUNET_assert (NULL != h->mq);
351 }
352
353
354 /**
355  * Try again to connect to the PSYCstore service.
356  *
357  * @param cls Handle to the PSYCstore service.
358  */
359 static void
360 reconnect (void *cls)
361 {
362   do_connect (cls);
363 }
364
365
366 /**
367  * Connect to the PSYCstore service.
368  *
369  * @param cfg The configuration to use
370  * @return Handle to use
371  */
372 struct GNUNET_PSYCSTORE_Handle *
373 GNUNET_PSYCSTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
374 {
375   struct GNUNET_PSYCSTORE_Handle *h
376     = GNUNET_new (struct GNUNET_PSYCSTORE_Handle);
377   h->cfg = cfg;
378   h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
379   do_connect (h);
380   return h;
381 }
382
383
384 /**
385  * Disconnect from PSYCstore service
386  *
387  * @param h Handle to destroy
388  */
389 void
390 GNUNET_PSYCSTORE_disconnect (struct GNUNET_PSYCSTORE_Handle *h)
391 {
392   GNUNET_assert (NULL != h);
393   if (h->reconnect_task != NULL)
394   {
395     GNUNET_SCHEDULER_cancel (h->reconnect_task);
396     h->reconnect_task = NULL;
397   }
398   if (NULL != h->mq)
399   {
400     // FIXME: free data structures for pending operations
401     GNUNET_MQ_destroy (h->mq);
402     h->mq = NULL;
403   }
404   GNUNET_free (h);
405 }
406
407
408 /**
409  * Message sent notification.
410  *
411  * Remove invalidated envelope pointer.
412  */
413 static void
414 message_sent (void *cls)
415 {
416   struct GNUNET_PSYCSTORE_OperationHandle *op = cls;
417   op->env = NULL;
418 }
419
420
421 /**
422  * Create a new operation.
423  */
424 static struct GNUNET_PSYCSTORE_OperationHandle *
425 op_create (struct GNUNET_PSYCSTORE_Handle *h,
426            struct GNUNET_OP_Handle *hop,
427            GNUNET_PSYCSTORE_ResultCallback result_cb,
428            void *cls)
429 {
430   struct GNUNET_PSYCSTORE_OperationHandle *
431     op = GNUNET_malloc (sizeof (*op));
432   op->h = h;
433   op->op_id = GNUNET_OP_add (hop,
434                              (GNUNET_ResultCallback) result_cb,
435                              cls, op);
436   return op;
437 }
438
439
440 /**
441  * Send a message associated with an operation.
442  *
443  * @param h
444  *        PSYCstore handle.
445  * @param op
446  *        Operation handle.
447  * @param env
448  *        Message envelope to send.
449  * @param[out] op_id
450  *        Operation ID to write in network byte order. NULL if not needed.
451  *
452  * @return Operation handle.
453  *
454  */
455 static struct GNUNET_PSYCSTORE_OperationHandle *
456 op_send (struct GNUNET_PSYCSTORE_Handle *h,
457          struct GNUNET_PSYCSTORE_OperationHandle *op,
458          struct GNUNET_MQ_Envelope *env,
459          uint64_t *op_id)
460 {
461   op->env = env;
462   if (NULL != op_id)
463     *op_id = GNUNET_htonll (op->op_id);
464
465   GNUNET_MQ_notify_sent (env, message_sent, op);
466   GNUNET_MQ_send (h->mq, env);
467   return op;
468 }
469
470
471 /**
472  * Cancel a PSYCstore operation. Note that the operation MAY still
473  * be executed; this merely cancels the continuation; if the request
474  * was already transmitted, the service may still choose to complete
475  * the operation.
476  *
477  * @param op Operation to cancel.
478  *
479  * @return #GNUNET_YES if message was not sent yet and got discarded,
480  *         #GNUNET_NO  if it was already sent, and only the callbacks got cancelled.
481  */
482 int
483 GNUNET_PSYCSTORE_operation_cancel (struct GNUNET_PSYCSTORE_OperationHandle *op)
484 {
485   struct GNUNET_PSYCSTORE_Handle *h = op->h;
486   int ret = GNUNET_NO;
487
488   if (NULL != op->env)
489   {
490     GNUNET_MQ_send_cancel (op->env);
491     ret = GNUNET_YES;
492   }
493
494   GNUNET_OP_remove (h->op, op->op_id);
495   GNUNET_free (op);
496
497   return ret;
498 }
499
500
501 /**
502  * Store join/leave events for a PSYC channel in order to be able to answer
503  * membership test queries later.
504  *
505  * @param h
506  *        Handle for the PSYCstore.
507  * @param channel_key
508  *        The channel where the event happened.
509  * @param slave_key
510  *        Public key of joining/leaving slave.
511  * @param did_join
512  *        #GNUNET_YES on join, #GNUNET_NO on part.
513  * @param announced_at
514  *        ID of the message that announced the membership change.
515  * @param effective_since
516  *        Message ID this membership change is in effect since.
517  *        For joins it is <= announced_at, for parts it is always 0.
518  * @param group_generation
519  *        In case of a part, the last group generation the slave has access to.
520  *        It has relevance when a larger message have fragments with different
521  *        group generations.
522  * @param result_cb
523  *        Callback to call with the result of the storage operation.
524  * @param cls
525  *        Closure for the callback.
526  *
527  * @return Operation handle that can be used to cancel the operation.
528  */
529 struct GNUNET_PSYCSTORE_OperationHandle *
530 GNUNET_PSYCSTORE_membership_store (struct GNUNET_PSYCSTORE_Handle *h,
531                                    const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
532                                    const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
533                                    int did_join,
534                                    uint64_t announced_at,
535                                    uint64_t effective_since,
536                                    uint64_t group_generation,
537                                    GNUNET_PSYCSTORE_ResultCallback result_cb,
538                                    void *cls)
539 {
540   GNUNET_assert (NULL != h);
541   GNUNET_assert (NULL != channel_key);
542   GNUNET_assert (NULL != slave_key);
543   GNUNET_assert (GNUNET_YES == did_join || GNUNET_NO == did_join);
544   GNUNET_assert (did_join
545                  ? effective_since <= announced_at
546                  : effective_since == 0);
547
548   struct MembershipStoreRequest *req;
549   struct GNUNET_MQ_Envelope *
550     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_MEMBERSHIP_STORE);
551   req->channel_key = *channel_key;
552   req->slave_key = *slave_key;
553   req->did_join = did_join;
554   req->announced_at = GNUNET_htonll (announced_at);
555   req->effective_since = GNUNET_htonll (effective_since);
556   req->group_generation = GNUNET_htonll (group_generation);
557
558   return
559     op_send (h, op_create (h, h->op, result_cb, cls),
560              env, &req->op_id);
561 }
562
563
564 /**
565  * Test if a member was admitted to the channel at the given message ID.
566  *
567  * This is useful when relaying and replaying messages to check if a particular
568  * slave has access to the message fragment with a given group generation.  It
569  * is also used when handling join requests to determine whether the slave is
570  * currently admitted to the channel.
571  *
572  * @param h
573  *        Handle for the PSYCstore.
574  * @param channel_key
575  *        The channel we are interested in.
576  * @param slave_key
577  *        Public key of slave whose membership to check.
578  * @param message_id
579  *        Message ID for which to do the membership test.
580  * @param group_generation
581  *        Group generation of the fragment of the message to test.
582  *        It has relevance if the message consists of multiple fragments with
583  *        different group generations.
584  * @param result_cb
585  *        Callback to call with the test result.
586  * @param cls
587  *        Closure for the callback.
588  *
589  * @return Operation handle that can be used to cancel the operation.
590  */
591 struct GNUNET_PSYCSTORE_OperationHandle *
592 GNUNET_PSYCSTORE_membership_test (struct GNUNET_PSYCSTORE_Handle *h,
593                                   const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
594                                   const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
595                                   uint64_t message_id,
596                                   uint64_t group_generation,
597                                   GNUNET_PSYCSTORE_ResultCallback result_cb,
598                                   void *cls)
599 {
600   struct MembershipTestRequest *req;
601   struct GNUNET_MQ_Envelope *
602     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_MEMBERSHIP_TEST);
603   req->channel_key = *channel_key;
604   req->slave_key = *slave_key;
605   req->message_id = GNUNET_htonll (message_id);
606   req->group_generation = GNUNET_htonll (group_generation);
607
608   return
609     op_send (h, op_create (h, h->op, result_cb, cls),
610              env, &req->op_id);
611 }
612
613
614 /**
615  * Store a message fragment sent to a channel.
616  *
617  * @param h Handle for the PSYCstore.
618  * @param channel_key The channel the message belongs to.
619  * @param message Message to store.
620  * @param psycstore_flags Flags indicating whether the PSYC message contains
621  *        state modifiers.
622  * @param result_cb Callback to call with the result of the operation.
623  * @param cls Closure for the callback.
624  *
625  * @return Handle that can be used to cancel the operation.
626  */
627 struct GNUNET_PSYCSTORE_OperationHandle *
628 GNUNET_PSYCSTORE_fragment_store (struct GNUNET_PSYCSTORE_Handle *h,
629                                  const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
630                                  const struct GNUNET_MULTICAST_MessageHeader *msg,
631                                  enum GNUNET_PSYCSTORE_MessageFlags psycstore_flags,
632                                  GNUNET_PSYCSTORE_ResultCallback result_cb,
633                                  void *cls)
634 {
635   uint16_t size = ntohs (msg->header.size);
636   struct FragmentStoreRequest *req;
637   struct GNUNET_MQ_Envelope *
638     env = GNUNET_MQ_msg_extra (req, size,
639                                GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_STORE);
640   req->channel_key = *channel_key;
641   req->psycstore_flags = htonl (psycstore_flags);
642   GNUNET_memcpy (&req[1], msg, size);
643
644   return
645     op_send (h, op_create (h, h->op, result_cb, cls),
646              env, &req->op_id);
647 }
648
649
650 /**
651  * Retrieve message fragments by fragment ID range.
652  *
653  * @param h
654  *        Handle for the PSYCstore.
655  * @param channel_key
656  *        The channel we are interested in.
657  * @param slave_key
658  *        The slave requesting the fragment.  If not NULL, a membership test is
659  *        performed first and the fragment is only returned if the slave has
660  *        access to it.
661  * @param first_fragment_id
662  *        First fragment ID to retrieve.
663  *        Use 0 to get the latest message fragment.
664  * @param last_fragment_id
665  *        Last consecutive fragment ID to retrieve.
666  *        Use 0 to get the latest message fragment.
667  * @param fragment_limit
668  *        Maximum number of fragments to retrieve.
669  * @param fragment_cb
670  *        Callback to call with the retrieved fragments.
671  * @param result_cb
672  *        Callback to call with the result of the operation.
673  * @param cls
674  *        Closure for the callbacks.
675  *
676  * @return Handle that can be used to cancel the operation.
677  */
678 struct GNUNET_PSYCSTORE_OperationHandle *
679 GNUNET_PSYCSTORE_fragment_get (struct GNUNET_PSYCSTORE_Handle *h,
680                                const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
681                                const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
682                                uint64_t first_fragment_id,
683                                uint64_t last_fragment_id,
684                                GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
685                                GNUNET_PSYCSTORE_ResultCallback result_cb,
686                                void *cls)
687 {
688   struct FragmentGetRequest *req;
689   struct GNUNET_MQ_Envelope *
690     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_GET);
691   req->channel_key = *channel_key;
692   req->first_fragment_id = GNUNET_htonll (first_fragment_id);
693   req->last_fragment_id = GNUNET_htonll (last_fragment_id);
694   if (NULL != slave_key)
695   {
696     req->slave_key = *slave_key;
697     req->do_membership_test = GNUNET_YES;
698   }
699
700   struct GNUNET_PSYCSTORE_OperationHandle *
701     op = op_create (h, h->op, result_cb, cls);
702   op->fragment_cb = fragment_cb;
703   op->cls = cls;
704   return op_send (h, op, env, &req->op_id);
705 }
706
707
708 /**
709  * Retrieve latest message fragments.
710  *
711  * @param h
712  *        Handle for the PSYCstore.
713  * @param channel_key
714  *        The channel we are interested in.
715  * @param slave_key
716  *        The slave requesting the fragment.  If not NULL, a membership test is
717  *        performed first and the fragment is only returned if the slave has
718  *        access to it.
719  * @param first_fragment_id
720  *        First fragment ID to retrieve.
721  *        Use 0 to get the latest message fragment.
722  * @param last_fragment_id
723  *        Last consecutive fragment ID to retrieve.
724  *        Use 0 to get the latest message fragment.
725  * @param fragment_limit
726  *        Maximum number of fragments to retrieve.
727  * @param fragment_cb
728  *        Callback to call with the retrieved fragments.
729  * @param result_cb
730  *        Callback to call with the result of the operation.
731  * @param cls
732  *        Closure for the callbacks.
733  *
734  * @return Handle that can be used to cancel the operation.
735  */
736 struct GNUNET_PSYCSTORE_OperationHandle *
737 GNUNET_PSYCSTORE_fragment_get_latest (struct GNUNET_PSYCSTORE_Handle *h,
738                                       const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
739                                       const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
740                                       uint64_t fragment_limit,
741                                       GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
742                                       GNUNET_PSYCSTORE_ResultCallback result_cb,
743                                       void *cls)
744 {
745   struct FragmentGetRequest *req;
746   struct GNUNET_MQ_Envelope *
747     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_FRAGMENT_GET);
748   req->channel_key = *channel_key;
749   req->fragment_limit = GNUNET_ntohll (fragment_limit);
750   if (NULL != slave_key)
751   {
752     req->slave_key = *slave_key;
753     req->do_membership_test = GNUNET_YES;
754   }
755
756   struct GNUNET_PSYCSTORE_OperationHandle *
757     op = op_create (h, h->op, result_cb, cls);
758   op->fragment_cb = fragment_cb;
759   op->cls = cls;
760   return op_send (h, op, env, &req->op_id);
761 }
762
763
764 /**
765  * Retrieve all fragments of messages in a message ID range.
766  *
767  * @param h
768  *        Handle for the PSYCstore.
769  * @param channel_key
770  *        The channel we are interested in.
771  * @param slave_key
772  *        The slave requesting the message.
773  *        If not NULL, a membership test is performed first
774  *        and the message is only returned if the slave has access to it.
775  * @param first_message_id
776  *        First message ID to retrieve.
777  * @param last_message_id
778  *        Last consecutive message ID to retrieve.
779  * @param fragment_limit
780  *        Maximum number of fragments to retrieve.
781  * @param method_prefix
782  *        Retrieve only messages with a matching method prefix.
783  * @todo Implement method_prefix query.
784  * @param fragment_cb
785  *        Callback to call with the retrieved fragments.
786  * @param result_cb
787  *        Callback to call with the result of the operation.
788  * @param cls
789  *        Closure for the callbacks.
790  *
791  * @return Handle that can be used to cancel the operation.
792  */
793 struct GNUNET_PSYCSTORE_OperationHandle *
794 GNUNET_PSYCSTORE_message_get (struct GNUNET_PSYCSTORE_Handle *h,
795                               const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
796                               const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
797                               uint64_t first_message_id,
798                               uint64_t last_message_id,
799                               uint64_t fragment_limit,
800                               const char *method_prefix,
801                               GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
802                               GNUNET_PSYCSTORE_ResultCallback result_cb,
803                               void *cls)
804 {
805   struct MessageGetRequest *req;
806   if (NULL == method_prefix)
807     method_prefix = "";
808   uint16_t method_size = strnlen (method_prefix,
809                                   GNUNET_SERVER_MAX_MESSAGE_SIZE
810                                   - sizeof (*req)) + 1;
811
812   struct GNUNET_MQ_Envelope *
813     env = GNUNET_MQ_msg_extra (req, method_size,
814                                GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET);
815   req->channel_key = *channel_key;
816   req->first_message_id = GNUNET_htonll (first_message_id);
817   req->last_message_id = GNUNET_htonll (last_message_id);
818   req->fragment_limit = GNUNET_htonll (fragment_limit);
819   if (NULL != slave_key)
820   {
821     req->slave_key = *slave_key;
822     req->do_membership_test = GNUNET_YES;
823   }
824   GNUNET_memcpy (&req[1], method_prefix, method_size);
825   ((char *) &req[1])[method_size - 1] = '\0';
826
827   struct GNUNET_PSYCSTORE_OperationHandle *
828     op = op_create (h, h->op, result_cb, cls);
829   op->fragment_cb = fragment_cb;
830   op->cls = cls;
831   return op_send (h, op, env, &req->op_id);
832 }
833
834
835 /**
836  * Retrieve all fragments of the latest messages.
837  *
838  * @param h
839  *        Handle for the PSYCstore.
840  * @param channel_key
841  *        The channel we are interested in.
842  * @param slave_key
843  *        The slave requesting the message.
844  *        If not NULL, a membership test is performed first
845  *        and the message is only returned if the slave has access to it.
846  * @param message_limit
847  *        Maximum number of messages to retrieve.
848  * @param method_prefix
849  *        Retrieve only messages with a matching method prefix.
850  * @todo Implement method_prefix query.
851  * @param fragment_cb
852  *        Callback to call with the retrieved fragments.
853  * @param result_cb
854  *        Callback to call with the result of the operation.
855  * @param cls
856  *        Closure for the callbacks.
857  *
858  * @return Handle that can be used to cancel the operation.
859  */
860 struct GNUNET_PSYCSTORE_OperationHandle *
861 GNUNET_PSYCSTORE_message_get_latest (struct GNUNET_PSYCSTORE_Handle *h,
862                                      const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
863                                      const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
864                                      uint64_t message_limit,
865                                      const char *method_prefix,
866                                      GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
867                                      GNUNET_PSYCSTORE_ResultCallback result_cb,
868                                      void *cls)
869 {
870   struct MessageGetRequest *req;
871
872   if (NULL == method_prefix)
873     method_prefix = "";
874   uint16_t method_size = strnlen (method_prefix,
875                                   GNUNET_SERVER_MAX_MESSAGE_SIZE
876                                   - sizeof (*req)) + 1;
877   GNUNET_assert ('\0' == method_prefix[method_size - 1]);
878
879   struct GNUNET_MQ_Envelope *
880     env = GNUNET_MQ_msg_extra (req, method_size,
881                                GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET);
882   req->channel_key = *channel_key;
883   req->message_limit = GNUNET_ntohll (message_limit);
884   if (NULL != slave_key)
885   {
886     req->slave_key = *slave_key;
887     req->do_membership_test = GNUNET_YES;
888   }
889   GNUNET_memcpy (&req[1], method_prefix, method_size);
890
891   struct GNUNET_PSYCSTORE_OperationHandle *
892     op = op_create (h, h->op, result_cb, cls);
893   op->fragment_cb = fragment_cb;
894   op->cls = cls;
895   return op_send (h, op, env, &req->op_id);
896 }
897
898
899 /**
900  * Retrieve a fragment of message specified by its message ID and fragment
901  * offset.
902  *
903  * @param h
904  *        Handle for the PSYCstore.
905  * @param channel_key
906  *        The channel we are interested in.
907  * @param slave_key
908  *        The slave requesting the message fragment.  If not NULL, a membership
909  *        test is performed first and the message fragment is only returned
910  *        if the slave has access to it.
911  * @param message_id
912  *        Message ID to retrieve.  Use 0 to get the latest message.
913  * @param fragment_offset
914  *        Offset of the fragment to retrieve.
915  * @param fragment_cb
916  *        Callback to call with the retrieved fragments.
917  * @param result_cb
918  *        Callback to call with the result of the operation.
919  * @param cls
920  *        Closure for the callbacks.
921  *
922  * @return Handle that can be used to cancel the operation.
923  */
924 struct GNUNET_PSYCSTORE_OperationHandle *
925 GNUNET_PSYCSTORE_message_get_fragment (struct GNUNET_PSYCSTORE_Handle *h,
926                                        const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
927                                        const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_key,
928                                        uint64_t message_id,
929                                        uint64_t fragment_offset,
930                                        GNUNET_PSYCSTORE_FragmentCallback fragment_cb,
931                                        GNUNET_PSYCSTORE_ResultCallback result_cb,
932                                        void *cls)
933 {
934   struct MessageGetFragmentRequest *req;
935   struct GNUNET_MQ_Envelope *
936     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_MESSAGE_GET_FRAGMENT);
937
938   req->channel_key = *channel_key;
939   req->message_id = GNUNET_htonll (message_id);
940   req->fragment_offset = GNUNET_htonll (fragment_offset);
941   if (NULL != slave_key)
942   {
943     req->slave_key = *slave_key;
944     req->do_membership_test = GNUNET_YES;
945   }
946
947   struct GNUNET_PSYCSTORE_OperationHandle *
948     op = op_create (h, h->op, result_cb, cls);
949   op->fragment_cb = fragment_cb;
950   op->cls = cls;
951   return op_send (h, op, env, &req->op_id);
952 }
953
954
955 /**
956  * Retrieve latest values of counters for a channel master.
957  *
958  * The current value of counters are needed when a channel master is restarted,
959  * so that it can continue incrementing the counters from their last value.
960  *
961  * @param h
962  *        Handle for the PSYCstore.
963  * @param channel_key
964  *        Public key that identifies the channel.
965  * @param ccb
966  *        Callback to call with the result.
967  * @param ccb_cls
968  *        Closure for the @a ccb callback.
969  *
970  * @return Handle that can be used to cancel the operation.
971  */
972 struct GNUNET_PSYCSTORE_OperationHandle *
973 GNUNET_PSYCSTORE_counters_get (struct GNUNET_PSYCSTORE_Handle *h,
974                                struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
975                                GNUNET_PSYCSTORE_CountersCallback counters_cb,
976                                void *cls)
977 {
978   struct OperationRequest *req;
979   struct GNUNET_MQ_Envelope *
980     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_COUNTERS_GET);
981   req->channel_key = *channel_key;
982
983   struct GNUNET_PSYCSTORE_OperationHandle *
984     op = op_create (h, h->op, NULL, NULL);
985   op->counters_cb = counters_cb;
986   op->cls = cls;
987   return op_send (h, op, env, &req->op_id);
988 }
989
990
991 /**
992  * Apply modifiers of a message to the current channel state.
993  *
994  * An error is returned if there are missing messages containing state
995  * operations before the current one.
996  *
997  * @param h
998  *        Handle for the PSYCstore.
999  * @param channel_key
1000  *        The channel we are interested in.
1001  * @param message_id
1002  *        ID of the message that contains the @a modifiers.
1003  * @param state_delta
1004  *        Value of the _state_delta PSYC header variable of the message.
1005  * @param result_cb
1006  *        Callback to call with the result of the operation.
1007  * @param cls
1008  *        Closure for @a result_cb.
1009  *
1010  * @return Handle that can be used to cancel the operation.
1011  */
1012 struct GNUNET_PSYCSTORE_OperationHandle *
1013 GNUNET_PSYCSTORE_state_modify (struct GNUNET_PSYCSTORE_Handle *h,
1014                                const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1015                                uint64_t message_id,
1016                                uint64_t state_delta,
1017                                GNUNET_PSYCSTORE_ResultCallback result_cb,
1018                                void *cls)
1019 {
1020   struct StateModifyRequest *req;
1021   struct GNUNET_MQ_Envelope *
1022     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_MODIFY);
1023   req->channel_key = *channel_key;
1024   req->message_id = GNUNET_htonll (message_id);
1025   req->state_delta = GNUNET_htonll (state_delta);
1026
1027   return op_send (h, op_create (h, h->op, result_cb, cls),
1028                   env, &req->op_id);
1029 }
1030
1031
1032 struct StateSyncClosure
1033 {
1034   GNUNET_PSYCSTORE_ResultCallback result_cb;
1035   void *cls;
1036   uint8_t last;
1037 };
1038
1039
1040 static void
1041 state_sync_result (void *cls, int64_t result,
1042                    const char *err_msg, uint16_t err_msg_size)
1043 {
1044   struct StateSyncClosure *ssc = cls;
1045   if (GNUNET_OK != result || ssc->last)
1046     ssc->result_cb (ssc->cls, result, err_msg, err_msg_size);
1047   GNUNET_free (ssc);
1048 }
1049
1050
1051 /**
1052  * Store synchronized state.
1053  *
1054  * @param h
1055  *        Handle for the PSYCstore.
1056  * @param channel_key
1057  *        The channel we are interested in.
1058  * @param max_state_message_id
1059  *        ID of the last stateful message before @a state_hash_message_id.
1060  * @param state_hash_message_id
1061  *        ID of the message that contains the state_hash PSYC header variable.
1062  * @param modifier_count
1063  *        Number of elements in the @a modifiers array.
1064  * @param modifiers
1065  *        Full state to store.
1066  * @param result_cb
1067  *        Callback to call with the result of the operation.
1068  * @param cls
1069  *        Closure for the callback.
1070  *
1071  * @return Handle that can be used to cancel the operation.
1072  */
1073 struct GNUNET_PSYCSTORE_OperationHandle *
1074 GNUNET_PSYCSTORE_state_sync (struct GNUNET_PSYCSTORE_Handle *h,
1075                              const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1076                              uint64_t max_state_message_id,
1077                              uint64_t state_hash_message_id,
1078                              size_t modifier_count,
1079                              const struct GNUNET_PSYC_Modifier *modifiers,
1080                              GNUNET_PSYCSTORE_ResultCallback result_cb,
1081                              void *cls)
1082 {
1083   struct GNUNET_PSYCSTORE_OperationHandle *op = NULL;
1084   size_t i;
1085
1086   for (i = 0; i < modifier_count; i++) {
1087     struct StateSyncRequest *req;
1088     uint16_t name_size = strlen (modifiers[i].name) + 1;
1089
1090     struct GNUNET_MQ_Envelope *
1091       env = GNUNET_MQ_msg_extra (req,
1092                                  sizeof (*req) + name_size + modifiers[i].value_size,
1093                                  GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_SYNC);
1094
1095     req->header.type = htons (GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_SYNC);
1096     req->header.size = htons (sizeof (*req) + name_size
1097                               + modifiers[i].value_size);
1098     req->channel_key = *channel_key;
1099     req->max_state_message_id = GNUNET_htonll (max_state_message_id);
1100     req->state_hash_message_id = GNUNET_htonll (state_hash_message_id);
1101     req->name_size = htons (name_size);
1102     req->flags
1103       = (0 == i)
1104       ? STATE_OP_FIRST
1105       : (modifier_count - 1 == i)
1106       ? STATE_OP_LAST
1107       : 0;
1108
1109     GNUNET_memcpy (&req[1], modifiers[i].name, name_size);
1110     GNUNET_memcpy ((char *) &req[1] + name_size, modifiers[i].value, modifiers[i].value_size);
1111
1112     struct StateSyncClosure *ssc = GNUNET_malloc (sizeof (*ssc));
1113     ssc->last = (req->flags & STATE_OP_LAST);
1114     ssc->result_cb = result_cb;
1115     ssc->cls = cls;
1116
1117     op_send (h, op_create (h, h->op, state_sync_result, ssc),
1118              env, &req->op_id);
1119   }
1120   // FIXME: only one operation is returned,
1121   //        add pointers to other operations and make all cancellable.
1122   return op;
1123 }
1124
1125
1126 /**
1127  * Reset the state of a channel.
1128  *
1129  * Delete all state variables stored for the given channel.
1130  *
1131  * @param h
1132  *        Handle for the PSYCstore.
1133  * @param channel_key
1134  *        The channel we are interested in.
1135  * @param result_cb
1136  *        Callback to call with the result of the operation.
1137  * @param cls
1138  *        Closure for the callback.
1139  *
1140  * @return Handle that can be used to cancel the operation.
1141  */
1142 struct GNUNET_PSYCSTORE_OperationHandle *
1143 GNUNET_PSYCSTORE_state_reset (struct GNUNET_PSYCSTORE_Handle *h,
1144                               const struct GNUNET_CRYPTO_EddsaPublicKey
1145                               *channel_key,
1146                               GNUNET_PSYCSTORE_ResultCallback result_cb,
1147                               void *cls)
1148 {
1149   struct OperationRequest *req;
1150   struct GNUNET_MQ_Envelope *
1151     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_RESET);
1152   req->channel_key = *channel_key;
1153
1154   return
1155     op_send (h, op_create (h, h->op, result_cb, cls),
1156              env, &req->op_id);
1157 }
1158
1159
1160 /**
1161  * Update signed values of state variables in the state store.
1162  *
1163  * @param h
1164  *        Handle for the PSYCstore.
1165  * @param channel_key
1166  *        The channel we are interested in.
1167  * @param message_id
1168  *        Message ID that contained the state @a hash.
1169  * @param hash
1170  *        Hash of the serialized full state.
1171  * @param result_cb
1172  *        Callback to call with the result of the operation.
1173  * @param cls
1174  *        Closure for the callback.
1175  */
1176 struct GNUNET_PSYCSTORE_OperationHandle *
1177 GNUNET_PSYCSTORE_state_hash_update (struct GNUNET_PSYCSTORE_Handle *h,
1178                                     const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1179                                     uint64_t message_id,
1180                                     const struct GNUNET_HashCode *hash,
1181                                     GNUNET_PSYCSTORE_ResultCallback result_cb,
1182                                     void *cls)
1183 {
1184   struct StateHashUpdateRequest *req;
1185   struct GNUNET_MQ_Envelope *
1186     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_HASH_UPDATE);
1187   req->channel_key = *channel_key;
1188   req->hash = *hash;
1189
1190   return
1191     op_send (h, op_create (h, h->op, result_cb, cls),
1192              env, &req->op_id);
1193 }
1194
1195
1196 /**
1197  * Retrieve the best matching state variable.
1198  *
1199  * @param h
1200  *        Handle for the PSYCstore.
1201  * @param channel_key
1202  *        The channel we are interested in.
1203  * @param name
1204  *        Name of variable to match, the returned variable might be less specific.
1205  * @param state_cb
1206  *        Callback to return the matching state variable.
1207  * @param result_cb
1208  *        Callback to call with the result of the operation.
1209  * @param cls
1210  *        Closure for the callbacks.
1211  *
1212  * @return Handle that can be used to cancel the operation.
1213  */
1214 struct GNUNET_PSYCSTORE_OperationHandle *
1215 GNUNET_PSYCSTORE_state_get (struct GNUNET_PSYCSTORE_Handle *h,
1216                             const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1217                             const char *name,
1218                             GNUNET_PSYCSTORE_StateCallback state_cb,
1219                             GNUNET_PSYCSTORE_ResultCallback result_cb,
1220                             void *cls)
1221 {
1222   size_t name_size = strlen (name) + 1;
1223   struct OperationRequest *req;
1224   struct GNUNET_MQ_Envelope *
1225     env = GNUNET_MQ_msg_extra (req, name_size,
1226                                GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_GET);
1227   req->channel_key = *channel_key;
1228   GNUNET_memcpy (&req[1], name, name_size);
1229
1230   struct GNUNET_PSYCSTORE_OperationHandle *
1231     op = op_create (h, h->op, result_cb, cls);
1232   op->state_cb = state_cb;
1233   op->cls = cls;
1234   return op_send (h, op, env, &req->op_id);
1235 }
1236
1237
1238 /**
1239  * Retrieve all state variables for a channel with the given prefix.
1240  *
1241  * @param h
1242  *        Handle for the PSYCstore.
1243  * @param channel_key
1244  *        The channel we are interested in.
1245  * @param name_prefix
1246  *        Prefix of state variable names to match.
1247  * @param state_cb
1248  *        Callback to return matching state variables.
1249  * @param result_cb
1250  *        Callback to call with the result of the operation.
1251  * @param cls
1252  *        Closure for the callbacks.
1253  *
1254  * @return Handle that can be used to cancel the operation.
1255  */
1256 struct GNUNET_PSYCSTORE_OperationHandle *
1257 GNUNET_PSYCSTORE_state_get_prefix (struct GNUNET_PSYCSTORE_Handle *h,
1258                                    const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
1259                                    const char *name_prefix,
1260                                    GNUNET_PSYCSTORE_StateCallback state_cb,
1261                                    GNUNET_PSYCSTORE_ResultCallback result_cb,
1262                                    void *cls)
1263 {
1264   size_t name_size = strlen (name_prefix) + 1;
1265   struct OperationRequest *req;
1266   struct GNUNET_MQ_Envelope *
1267     env = GNUNET_MQ_msg_extra (req, name_size,
1268                                GNUNET_MESSAGE_TYPE_PSYCSTORE_STATE_GET_PREFIX);
1269   req->channel_key = *channel_key;
1270   GNUNET_memcpy (&req[1], name_prefix, name_size);
1271
1272   struct GNUNET_PSYCSTORE_OperationHandle *
1273     op = op_create (h, h->op, result_cb, cls);
1274   op->state_cb = state_cb;
1275   op->cls = cls;
1276   return op_send (h, op, env, &req->op_id);
1277 }
1278
1279 /* end of psycstore_api.c */