f74930237539514746d7d57cee94b7bcb9f083eb
[oweals/gnunet.git] / src / psyc / psyc_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 psyc/psyc_api.c
23  * @brief PSYC service; high-level access to the PSYC protocol
24  *        note that clients of this API are NOT expected to
25  *        understand the PSYC message format, only the semantics!
26  *        Parsing (and serializing) the PSYC stream format is done
27  *        within the implementation of the libgnunetpsyc library,
28  *        and this API deliberately exposes as little as possible
29  *        of the actual data stream format to the application!
30  * @author Gabor X Toth
31  */
32
33 #include <inttypes.h>
34
35 #include "platform.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_multicast_service.h"
38 #include "gnunet_psyc_service.h"
39 #include "gnunet_psyc_util_lib.h"
40 #include "psyc.h"
41
42 #define LOG(kind,...) GNUNET_log_from (kind, "psyc-api",__VA_ARGS__)
43
44
45 /**
46  * Handle to access PSYC channel operations for both the master and slaves.
47  */
48 struct GNUNET_PSYC_Channel
49 {
50   /**
51    * Configuration to use.
52    */
53   const struct GNUNET_CONFIGURATION_Handle *cfg;
54
55   /**
56    * Client connection to the service.
57    */
58   struct GNUNET_MQ_Handle *mq;
59
60   /**
61    * Message to send on connect.
62    */
63   struct GNUNET_MQ_Envelope *connect_env;
64
65   /**
66    * Time to wait until we try to reconnect on failure.
67    */
68   struct GNUNET_TIME_Relative reconnect_delay;
69
70   /**
71    * Task for reconnecting when the listener fails.
72    */
73   struct GNUNET_SCHEDULER_Task *reconnect_task;
74
75   /**
76    * Async operations.
77    */
78   struct GNUNET_OP_Handle *op;
79
80   /**
81    * Transmission handle;
82    */
83   struct GNUNET_PSYC_TransmitHandle *tmit;
84
85   /**
86    * Receipt handle;
87    */
88   struct GNUNET_PSYC_ReceiveHandle *recv;
89
90   /**
91    * Function called after disconnected from the service.
92    */
93   GNUNET_ContinuationCallback disconnect_cb;
94
95   /**
96    * Closure for @a disconnect_cb.
97    */
98   void *disconnect_cls;
99
100   /**
101    * Are we polling for incoming messages right now?
102    */
103   uint8_t in_receive;
104
105   /**
106    * Is this a master or slave channel?
107    */
108   uint8_t is_master;
109
110   /**
111    * Is this channel in the process of disconnecting from the service?
112    * #GNUNET_YES or #GNUNET_NO
113    */
114   uint8_t is_disconnecting;
115 };
116
117
118 /**
119  * Handle for the master of a PSYC channel.
120  */
121 struct GNUNET_PSYC_Master
122 {
123   struct GNUNET_PSYC_Channel chn;
124
125   GNUNET_PSYC_MasterStartCallback start_cb;
126
127   /**
128    * Join request callback.
129    */
130   GNUNET_PSYC_JoinRequestCallback join_req_cb;
131
132   /**
133    * Closure for the callbacks.
134    */
135   void *cb_cls;
136 };
137
138
139 /**
140  * Handle for a PSYC channel slave.
141  */
142 struct GNUNET_PSYC_Slave
143 {
144   struct GNUNET_PSYC_Channel chn;
145
146   GNUNET_PSYC_SlaveConnectCallback connect_cb;
147
148   GNUNET_PSYC_JoinDecisionCallback join_dcsn_cb;
149
150   /**
151    * Closure for the callbacks.
152    */
153   void *cb_cls;
154 };
155
156
157 /**
158  * Handle that identifies a join request.
159  *
160  * Used to match calls to #GNUNET_PSYC_JoinRequestCallback to the
161  * corresponding calls to GNUNET_PSYC_join_decision().
162  */
163 struct GNUNET_PSYC_JoinHandle
164 {
165   struct GNUNET_PSYC_Master *mst;
166   struct GNUNET_CRYPTO_EcdsaPublicKey slave_pub_key;
167 };
168
169
170 /**
171  * Handle for a pending PSYC transmission operation.
172  */
173 struct GNUNET_PSYC_SlaveTransmitHandle
174 {
175
176 };
177
178
179 struct GNUNET_PSYC_HistoryRequest
180 {
181   /**
182    * Channel.
183    */
184   struct GNUNET_PSYC_Channel *chn;
185
186   /**
187    * Operation ID.
188    */
189   uint64_t op_id;
190
191   /**
192    * Message handler.
193    */
194   struct GNUNET_PSYC_ReceiveHandle *recv;
195
196   /**
197    * Function to call when the operation finished.
198    */
199   GNUNET_ResultCallback result_cb;
200
201   /**
202    * Closure for @a result_cb.
203    */
204   void *cls;
205 };
206
207
208 struct GNUNET_PSYC_StateRequest
209 {
210   /**
211    * Channel.
212    */
213   struct GNUNET_PSYC_Channel *chn;
214
215   /**
216    * Operation ID.
217    */
218   uint64_t op_id;
219
220   /**
221    * State variable result callback.
222    */
223   GNUNET_PSYC_StateVarCallback var_cb;
224
225   /**
226    * Function to call when the operation finished.
227    */
228   GNUNET_ResultCallback result_cb;
229
230   /**
231    * Closure for @a result_cb.
232    */
233   void *cls;
234 };
235
236
237 static int
238 check_channel_result (void *cls,
239                       const struct GNUNET_OperationResultMessage *res)
240 {
241   return GNUNET_OK;
242 }
243
244
245 static void
246 handle_channel_result (void *cls,
247                        const struct GNUNET_OperationResultMessage *res)
248 {
249   struct GNUNET_PSYC_Channel *chn = cls;
250
251   uint16_t size = ntohs (res->header.size);
252   if (size < sizeof (*res))
253   { /* Error, message too small. */
254     GNUNET_break (0);
255     return;
256   }
257
258   uint16_t data_size = size - sizeof (*res);
259   const char *data = (0 < data_size) ? (void *) &res[1] : NULL;
260   GNUNET_OP_result (chn->op, GNUNET_ntohll (res->op_id),
261                     GNUNET_ntohll (res->result_code),
262                     data, data_size, NULL);
263 }
264
265
266 static void
267 op_recv_history_result (void *cls, int64_t result,
268                         const void *data, uint16_t data_size)
269 {
270   LOG (GNUNET_ERROR_TYPE_DEBUG,
271        "Received history replay result: %" PRId64 ".\n", result);
272
273   struct GNUNET_PSYC_HistoryRequest *hist = cls;
274
275   if (NULL != hist->result_cb)
276     hist->result_cb (hist->cls, result, data, data_size);
277
278   GNUNET_PSYC_receive_destroy (hist->recv);
279   GNUNET_free (hist);
280 }
281
282
283 static void
284 op_recv_state_result (void *cls, int64_t result,
285                       const void *data, uint16_t data_size)
286 {
287   LOG (GNUNET_ERROR_TYPE_DEBUG,
288        "Received state request result: %" PRId64 ".\n", result);
289
290   struct GNUNET_PSYC_StateRequest *sr = cls;
291
292   if (NULL != sr->result_cb)
293     sr->result_cb (sr->cls, result, data, data_size);
294
295   GNUNET_free (sr);
296 }
297
298
299 static int
300 check_channel_history_result (void *cls,
301                               const struct GNUNET_OperationResultMessage *res)
302 {
303   struct GNUNET_PSYC_MessageHeader *
304     pmsg = (struct GNUNET_PSYC_MessageHeader *) GNUNET_MQ_extract_nested_mh (res);
305   uint16_t size = ntohs (res->header.size);
306
307   if (NULL == pmsg || size < sizeof (*res) + sizeof (*pmsg))
308   { /* Error, message too small. */
309     GNUNET_break_op (0);
310     return GNUNET_SYSERR;
311   }
312   return GNUNET_OK;
313 }
314
315
316 static void
317 handle_channel_history_result (void *cls,
318                                const struct GNUNET_OperationResultMessage *res)
319 {
320   struct GNUNET_PSYC_Channel *chn = cls;
321   struct GNUNET_PSYC_MessageHeader *
322     pmsg = (struct GNUNET_PSYC_MessageHeader *) GNUNET_MQ_extract_nested_mh (res);
323
324   LOG (GNUNET_ERROR_TYPE_DEBUG,
325        "%p Received historic fragment for message #%" PRIu64 ".\n",
326        chn, GNUNET_ntohll (pmsg->message_id));
327
328   GNUNET_ResultCallback result_cb = NULL;
329   struct GNUNET_PSYC_HistoryRequest *hist = NULL;
330
331   if (GNUNET_YES != GNUNET_OP_get (chn->op,
332                                    GNUNET_ntohll (res->op_id),
333                                    &result_cb, (void *) &hist, NULL))
334   { /* Operation not found. */
335     LOG (GNUNET_ERROR_TYPE_WARNING,
336          "%p Replay operation not found for historic fragment of message #%"
337          PRIu64 ".\n",
338          chn, GNUNET_ntohll (pmsg->message_id));
339     return;
340   }
341
342   GNUNET_PSYC_receive_message (hist->recv,
343                                (const struct GNUNET_PSYC_MessageHeader *) pmsg);
344 }
345
346
347 static int
348 check_channel_state_result (void *cls,
349                             const struct GNUNET_OperationResultMessage *res)
350 {
351   const struct GNUNET_MessageHeader *mod = GNUNET_MQ_extract_nested_mh (res);
352   uint16_t mod_size = ntohs (mod->size);
353   uint16_t size = ntohs (res->header.size);
354
355   if (NULL == mod || size - sizeof (*res) != mod_size)
356   {
357     GNUNET_break_op (0);
358     return GNUNET_SYSERR;
359   }
360   return GNUNET_OK;
361 }
362
363
364 static void
365 handle_channel_state_result (void *cls,
366                              const struct GNUNET_OperationResultMessage *res)
367 {
368   struct GNUNET_PSYC_Channel *chn = cls;
369
370   GNUNET_ResultCallback result_cb = NULL;
371   struct GNUNET_PSYC_StateRequest *sr = NULL;
372
373   if (GNUNET_YES != GNUNET_OP_get (chn->op,
374                                    GNUNET_ntohll (res->op_id),
375                                    &result_cb, (void *) &sr, NULL))
376   { /* Operation not found. */
377     return;
378   }
379
380   const struct GNUNET_MessageHeader *mod = GNUNET_MQ_extract_nested_mh (res);
381   uint16_t mod_size = ntohs (mod->size);
382
383   switch (ntohs (mod->type))
384   {
385   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
386   {
387     const struct GNUNET_PSYC_MessageModifier *
388       pmod = (const struct GNUNET_PSYC_MessageModifier *) mod;
389
390     const char *name = (const char *) &pmod[1];
391     uint16_t name_size = ntohs (pmod->name_size);
392     if ('\0' != name[name_size - 1])
393     {
394       GNUNET_break (0);
395       return;
396     }
397     sr->var_cb (sr->cls, mod, name, name + name_size,
398                 ntohs (pmod->header.size) - sizeof (*pmod),
399                 ntohs (pmod->value_size));
400     break;
401   }
402
403   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MOD_CONT:
404     sr->var_cb (sr->cls, mod, NULL, (const char *) &mod[1],
405                 mod_size - sizeof (*mod), 0);
406     break;
407   }
408 }
409
410
411 static int
412 check_channel_message (void *cls,
413                        const struct GNUNET_PSYC_MessageHeader *pmsg)
414 {
415   return GNUNET_OK;
416 }
417
418
419 static void
420 handle_channel_message (void *cls,
421                         const struct GNUNET_PSYC_MessageHeader *pmsg)
422 {
423   struct GNUNET_PSYC_Channel *chn = cls;
424
425   GNUNET_PSYC_receive_message (chn->recv, pmsg);
426 }
427
428
429 static void
430 handle_channel_message_ack (void *cls,
431                             const struct GNUNET_MessageHeader *msg)
432 {
433   struct GNUNET_PSYC_Channel *chn = cls;
434
435   GNUNET_PSYC_transmit_got_ack (chn->tmit);
436 }
437
438
439 static void
440 handle_master_start_ack (void *cls,
441                          const struct GNUNET_PSYC_CountersResultMessage *cres)
442 {
443   struct GNUNET_PSYC_Master *mst = cls;
444
445   int32_t result = ntohl (cres->result_code);
446   if (GNUNET_OK != result && GNUNET_NO != result)
447   {
448     LOG (GNUNET_ERROR_TYPE_ERROR, "Could not start master: %ld\n", result);
449     GNUNET_break (0);
450     /* FIXME: disconnect */
451   }
452   if (NULL != mst->start_cb)
453     mst->start_cb (mst->cb_cls, result, GNUNET_ntohll (cres->max_message_id));
454 }
455
456
457 static int
458 check_master_join_request (void *cls,
459                            const struct GNUNET_PSYC_JoinRequestMessage *req)
460 {
461   return GNUNET_OK;
462 }
463
464
465 static void
466 handle_master_join_request (void *cls,
467                             const struct GNUNET_PSYC_JoinRequestMessage *req)
468 {
469   struct GNUNET_PSYC_Master *mst = cls;
470
471   if (NULL == mst->join_req_cb)
472     return;
473
474   const struct GNUNET_PSYC_Message *join_msg = NULL;
475   if (sizeof (*req) + sizeof (*join_msg) <= ntohs (req->header.size))
476   {
477     join_msg = (struct GNUNET_PSYC_Message *) GNUNET_MQ_extract_nested_mh (req);
478     LOG (GNUNET_ERROR_TYPE_DEBUG,
479          "Received join_msg of type %u and size %u.\n",
480          ntohs (join_msg->header.type), ntohs (join_msg->header.size));
481   }
482
483   struct GNUNET_PSYC_JoinHandle *jh = GNUNET_malloc (sizeof (*jh));
484   jh->mst = mst;
485   jh->slave_pub_key = req->slave_pub_key;
486
487   if (NULL != mst->join_req_cb)
488     mst->join_req_cb (mst->cb_cls, req, &req->slave_pub_key, join_msg, jh);
489 }
490
491
492 static void
493 handle_slave_join_ack (void *cls,
494                        const struct GNUNET_PSYC_CountersResultMessage *cres)
495 {
496   struct GNUNET_PSYC_Slave *slv = cls;
497
498   int32_t result = ntohl (cres->result_code);
499   if (GNUNET_YES != result && GNUNET_NO != result)
500   {
501     LOG (GNUNET_ERROR_TYPE_ERROR, "Could not join slave.\n");
502     GNUNET_break (0);
503     /* FIXME: disconnect */
504   }
505   if (NULL != slv->connect_cb)
506     slv->connect_cb (slv->cb_cls, result, GNUNET_ntohll (cres->max_message_id));
507 }
508
509
510 static int
511 check_slave_join_decision (void *cls,
512                            const struct GNUNET_PSYC_JoinDecisionMessage *dcsn)
513 {
514   return GNUNET_OK;
515 }
516
517
518 static void
519 handle_slave_join_decision (void *cls,
520                             const struct GNUNET_PSYC_JoinDecisionMessage *dcsn)
521 {
522   struct GNUNET_PSYC_Slave *slv = cls;
523
524   struct GNUNET_PSYC_Message *pmsg = NULL;
525   if (ntohs (dcsn->header.size) <= sizeof (*dcsn) + sizeof (*pmsg))
526     pmsg = (struct GNUNET_PSYC_Message *) &dcsn[1];
527
528   if (NULL != slv->join_dcsn_cb)
529     slv->join_dcsn_cb (slv->cb_cls, dcsn, ntohl (dcsn->is_admitted), pmsg);
530 }
531
532
533 static void
534 channel_cleanup (struct GNUNET_PSYC_Channel *chn)
535 {
536   if (NULL != chn->tmit)
537   {
538     GNUNET_PSYC_transmit_destroy (chn->tmit);
539     chn->tmit = NULL;
540   }
541   if (NULL != chn->recv)
542   {
543     GNUNET_PSYC_receive_destroy (chn->recv);
544     chn->recv = NULL;
545   }
546   if (NULL != chn->connect_env)
547   {
548     GNUNET_MQ_discard (chn->connect_env);
549     chn->connect_env = NULL;
550   }
551   if (NULL != chn->mq)
552   {
553     GNUNET_MQ_destroy (chn->mq);
554     chn->mq = NULL;
555   }
556   if (NULL != chn->disconnect_cb)
557   {
558     chn->disconnect_cb (chn->disconnect_cls);
559     chn->disconnect_cb = NULL;
560   }
561   GNUNET_free (chn);
562 }
563
564
565 static void
566 channel_disconnect (struct GNUNET_PSYC_Channel *chn,
567                     GNUNET_ContinuationCallback cb,
568                     void *cls)
569 {
570   chn->is_disconnecting = GNUNET_YES;
571   chn->disconnect_cb = cb;
572   chn->disconnect_cls = cls;
573
574   if (NULL != chn->mq)
575   {
576     struct GNUNET_MQ_Envelope *env = GNUNET_MQ_get_last_envelope (chn->mq);
577     if (NULL != env)
578     {
579       GNUNET_MQ_notify_sent (env, (GNUNET_MQ_NotifyCallback) channel_cleanup, chn);
580     }
581     else
582     {
583       channel_cleanup (chn);
584     }
585   }
586   else
587   {
588     channel_cleanup (chn);
589   }
590 }
591
592
593 /*** MASTER ***/
594
595
596 static void
597 master_connect (struct GNUNET_PSYC_Master *mst);
598
599
600 static void
601 master_reconnect (void *cls)
602 {
603   master_connect (cls);
604 }
605
606
607 /**
608  * Master client disconnected from service.
609  *
610  * Reconnect after backoff period.
611  */
612 static void
613 master_disconnected (void *cls, enum GNUNET_MQ_Error error)
614 {
615   struct GNUNET_PSYC_Master *mst = cls;
616   struct GNUNET_PSYC_Channel *chn = &mst->chn;
617
618   LOG (GNUNET_ERROR_TYPE_DEBUG,
619        "Master client disconnected (%d), re-connecting\n",
620        (int) error);
621   if (NULL != chn->tmit)
622   {
623     GNUNET_PSYC_transmit_destroy (chn->tmit);
624     chn->tmit = NULL;
625   }
626   if (NULL != chn->mq)
627   {
628     GNUNET_MQ_destroy (chn->mq);
629     chn->mq = NULL;
630   }
631   chn->reconnect_task = GNUNET_SCHEDULER_add_delayed (chn->reconnect_delay,
632                                                       master_reconnect,
633                                                       mst);
634   chn->reconnect_delay = GNUNET_TIME_STD_BACKOFF (chn->reconnect_delay);
635 }
636
637
638 static void
639 master_connect (struct GNUNET_PSYC_Master *mst)
640 {
641   struct GNUNET_PSYC_Channel *chn = &mst->chn;
642
643   struct GNUNET_MQ_MessageHandler handlers[] = {
644     GNUNET_MQ_hd_fixed_size (master_start_ack,
645                              GNUNET_MESSAGE_TYPE_PSYC_MASTER_START_ACK,
646                              struct GNUNET_PSYC_CountersResultMessage,
647                              mst),
648     GNUNET_MQ_hd_var_size (master_join_request,
649                            GNUNET_MESSAGE_TYPE_PSYC_JOIN_REQUEST,
650                            struct GNUNET_PSYC_JoinRequestMessage,
651                            mst),
652     GNUNET_MQ_hd_var_size (channel_message,
653                            GNUNET_MESSAGE_TYPE_PSYC_MESSAGE,
654                            struct GNUNET_PSYC_MessageHeader,
655                            chn),
656     GNUNET_MQ_hd_fixed_size (channel_message_ack,
657                              GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_ACK,
658                              struct GNUNET_MessageHeader,
659                              chn),
660     GNUNET_MQ_hd_var_size (channel_history_result,
661                            GNUNET_MESSAGE_TYPE_PSYC_HISTORY_RESULT,
662                            struct GNUNET_OperationResultMessage,
663                            chn),
664     GNUNET_MQ_hd_var_size (channel_state_result,
665                            GNUNET_MESSAGE_TYPE_PSYC_STATE_RESULT,
666                            struct GNUNET_OperationResultMessage,
667                            chn),
668     GNUNET_MQ_hd_var_size (channel_result,
669                            GNUNET_MESSAGE_TYPE_PSYC_RESULT_CODE,
670                            struct GNUNET_OperationResultMessage,
671                            chn),
672     GNUNET_MQ_handler_end ()
673   };
674
675   chn->mq = GNUNET_CLIENT_connecT (chn->cfg, "psyc",
676                                    handlers, master_disconnected, mst);
677   GNUNET_assert (NULL != chn->mq);
678   chn->tmit = GNUNET_PSYC_transmit_create (chn->mq);
679
680   GNUNET_MQ_send_copy (chn->mq, chn->connect_env);
681 }
682
683
684 /**
685  * Start a PSYC master channel.
686  *
687  * Will start a multicast group identified by the given ECC key.  Messages
688  * received from group members will be given to the respective handler methods.
689  * If a new member wants to join a group, the "join" method handler will be
690  * invoked; the join handler must then generate a "join" message to approve the
691  * joining of the new member.  The channel can also change group membership
692  * without explicit requests.  Note that PSYC doesn't itself "understand" join
693  * or part messages, the respective methods must call other PSYC functions to
694  * inform PSYC about the meaning of the respective events.
695  *
696  * @param cfg  Configuration to use (to connect to PSYC service).
697  * @param channel_key  ECC key that will be used to sign messages for this
698  *        PSYC session. The public key is used to identify the PSYC channel.
699  *        Note that end-users will usually not use the private key directly, but
700  *        rather look it up in GNS for places managed by other users, or select
701  *        a file with the private key(s) when setting up their own channels
702  *        FIXME: we'll likely want to use NOT the p521 curve here, but a cheaper
703  *        one in the future.
704  * @param policy  Channel policy specifying join and history restrictions.
705  *        Used to automate join decisions.
706  * @param message_cb  Function to invoke on message parts received from slaves.
707  * @param join_request_cb  Function to invoke when a slave wants to join.
708  * @param master_start_cb  Function to invoke after the channel master started.
709  * @param cls  Closure for @a method and @a join_cb.
710  *
711  * @return Handle for the channel master, NULL on error.
712  */
713 struct GNUNET_PSYC_Master *
714 GNUNET_PSYC_master_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
715                           const struct GNUNET_CRYPTO_EddsaPrivateKey *channel_key,
716                           enum GNUNET_PSYC_Policy policy,
717                           GNUNET_PSYC_MasterStartCallback start_cb,
718                           GNUNET_PSYC_JoinRequestCallback join_request_cb,
719                           GNUNET_PSYC_MessageCallback message_cb,
720                           GNUNET_PSYC_MessagePartCallback message_part_cb,
721                           void *cls)
722 {
723   struct GNUNET_PSYC_Master *mst = GNUNET_new (struct GNUNET_PSYC_Master);
724   struct GNUNET_PSYC_Channel *chn = &mst->chn;
725   struct MasterStartRequest *req;
726
727   chn->connect_env = GNUNET_MQ_msg (req,
728                                     GNUNET_MESSAGE_TYPE_PSYC_MASTER_START);
729   req->channel_key = *channel_key;
730   req->policy = policy;
731
732   chn->cfg = cfg;
733   chn->is_master = GNUNET_YES;
734   chn->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
735
736   chn->op = GNUNET_OP_create ();
737   chn->recv = GNUNET_PSYC_receive_create (message_cb, message_part_cb, cls);
738
739   mst->start_cb = start_cb;
740   mst->join_req_cb = join_request_cb;
741   mst->cb_cls = cls;
742
743   master_connect (mst);
744   return mst;
745 }
746
747
748 /**
749  * Stop a PSYC master channel.
750  *
751  * @param master PSYC channel master to stop.
752  * @param keep_active  FIXME
753  */
754 void
755 GNUNET_PSYC_master_stop (struct GNUNET_PSYC_Master *mst,
756                          int keep_active,
757                          GNUNET_ContinuationCallback stop_cb,
758                          void *stop_cls)
759 {
760   struct GNUNET_PSYC_Channel *chn = &mst->chn;
761
762   /* FIXME: send msg to service */
763
764   channel_disconnect (chn, stop_cb, stop_cls);
765 }
766
767
768 /**
769  * Function to call with the decision made for a join request.
770  *
771  * Must be called once and only once in response to an invocation of the
772  * #GNUNET_PSYC_JoinCallback.
773  *
774  * @param jh Join request handle.
775  * @param is_admitted  #GNUNET_YES    if the join is approved,
776  *                     #GNUNET_NO     if it is disapproved,
777  *                     #GNUNET_SYSERR if we cannot answer the request.
778  * @param relay_count Number of relays given.
779  * @param relays Array of suggested peers that might be useful relays to use
780  *        when joining the multicast group (essentially a list of peers that
781  *        are already part of the multicast group and might thus be willing
782  *        to help with routing).  If empty, only this local peer (which must
783  *        be the multicast origin) is a good candidate for building the
784  *        multicast tree.  Note that it is unnecessary to specify our own
785  *        peer identity in this array.
786  * @param join_resp  Application-dependent join response message.
787  *
788  * @return #GNUNET_OK on success,
789  *         #GNUNET_SYSERR if the message is too large.
790  */
791 int
792 GNUNET_PSYC_join_decision (struct GNUNET_PSYC_JoinHandle *jh,
793                            int is_admitted,
794                            uint32_t relay_count,
795                            const struct GNUNET_PeerIdentity *relays,
796                            const struct GNUNET_PSYC_Message *join_resp)
797 {
798   struct GNUNET_PSYC_Channel *chn = &jh->mst->chn;
799   struct GNUNET_PSYC_JoinDecisionMessage *dcsn;
800   uint16_t join_resp_size
801     = (NULL != join_resp) ? ntohs (join_resp->header.size) : 0;
802   uint16_t relay_size = relay_count * sizeof (*relays);
803
804   if (GNUNET_MULTICAST_FRAGMENT_MAX_PAYLOAD
805       < sizeof (*dcsn) + relay_size + join_resp_size)
806     return GNUNET_SYSERR;
807
808   struct GNUNET_MQ_Envelope *
809     env = GNUNET_MQ_msg_extra (dcsn, relay_size + join_resp_size,
810                                GNUNET_MESSAGE_TYPE_PSYC_JOIN_DECISION);
811   dcsn->is_admitted = htonl (is_admitted);
812   dcsn->slave_pub_key = jh->slave_pub_key;
813
814   if (0 < join_resp_size)
815     GNUNET_memcpy (&dcsn[1], join_resp, join_resp_size);
816
817   GNUNET_MQ_send (chn->mq, env);
818   GNUNET_free (jh);
819   return GNUNET_OK;
820 }
821
822
823 /**
824  * Send a message to call a method to all members in the PSYC channel.
825  *
826  * @param master Handle to the PSYC channel.
827  * @param method_name Which method should be invoked.
828  * @param notify_mod Function to call to obtain modifiers.
829  * @param notify_data Function to call to obtain fragments of the data.
830  * @param notify_cls Closure for @a notify_mod and @a notify_data.
831  * @param flags Flags for the message being transmitted.
832  *
833  * @return Transmission handle, NULL on error (i.e. more than one request queued).
834  */
835 struct GNUNET_PSYC_MasterTransmitHandle *
836 GNUNET_PSYC_master_transmit (struct GNUNET_PSYC_Master *mst,
837                              const char *method_name,
838                              GNUNET_PSYC_TransmitNotifyModifier notify_mod,
839                              GNUNET_PSYC_TransmitNotifyData notify_data,
840                              void *notify_cls,
841                              enum GNUNET_PSYC_MasterTransmitFlags flags)
842 {
843   if (GNUNET_OK
844       == GNUNET_PSYC_transmit_message (mst->chn.tmit, method_name, NULL,
845                                        notify_mod, notify_data, notify_cls,
846                                        flags))
847     return (struct GNUNET_PSYC_MasterTransmitHandle *) mst->chn.tmit;
848   else
849     return NULL;
850 }
851
852
853 /**
854  * Resume transmission to the channel.
855  *
856  * @param tmit  Handle of the request that is being resumed.
857  */
858 void
859 GNUNET_PSYC_master_transmit_resume (struct GNUNET_PSYC_MasterTransmitHandle *tmit)
860 {
861   GNUNET_PSYC_transmit_resume ((struct GNUNET_PSYC_TransmitHandle *) tmit);
862 }
863
864
865 /**
866  * Abort transmission request to the channel.
867  *
868  * @param tmit  Handle of the request that is being aborted.
869  */
870 void
871 GNUNET_PSYC_master_transmit_cancel (struct GNUNET_PSYC_MasterTransmitHandle *tmit)
872 {
873   GNUNET_PSYC_transmit_cancel ((struct GNUNET_PSYC_TransmitHandle *) tmit);
874 }
875
876
877 /**
878  * Convert a channel @a master to a @e channel handle to access the @e channel
879  * APIs.
880  *
881  * @param master Channel master handle.
882  *
883  * @return Channel handle, valid for as long as @a master is valid.
884  */
885 struct GNUNET_PSYC_Channel *
886 GNUNET_PSYC_master_get_channel (struct GNUNET_PSYC_Master *master)
887 {
888   return &master->chn;
889 }
890
891
892 /*** SLAVE ***/
893
894
895 static void
896 slave_connect (struct GNUNET_PSYC_Slave *slv);
897
898
899 static void
900 slave_reconnect (void *cls)
901 {
902   slave_connect (cls);
903 }
904
905
906 /**
907  * Slave client disconnected from service.
908  *
909  * Reconnect after backoff period.
910  */
911 static void
912 slave_disconnected (void *cls, enum GNUNET_MQ_Error error)
913 {
914   struct GNUNET_PSYC_Slave *slv = cls;
915   struct GNUNET_PSYC_Channel *chn = &slv->chn;
916
917   LOG (GNUNET_ERROR_TYPE_DEBUG,
918        "Slave client disconnected (%d), re-connecting\n",
919        (int) error);
920   if (NULL != chn->tmit)
921   {
922     GNUNET_PSYC_transmit_destroy (chn->tmit);
923     chn->tmit = NULL;
924   }
925   if (NULL != chn->mq)
926   {
927     GNUNET_MQ_destroy (chn->mq);
928     chn->mq = NULL;
929   }
930   chn->reconnect_task = GNUNET_SCHEDULER_add_delayed (chn->reconnect_delay,
931                                                       slave_reconnect,
932                                                       slv);
933   chn->reconnect_delay = GNUNET_TIME_STD_BACKOFF (chn->reconnect_delay);
934 }
935
936
937 static void
938 slave_connect (struct GNUNET_PSYC_Slave *slv)
939 {
940   struct GNUNET_PSYC_Channel *chn = &slv->chn;
941
942   struct GNUNET_MQ_MessageHandler handlers[] = {
943     GNUNET_MQ_hd_fixed_size (slave_join_ack,
944                              GNUNET_MESSAGE_TYPE_PSYC_SLAVE_JOIN_ACK,
945                              struct GNUNET_PSYC_CountersResultMessage,
946                              slv),
947     GNUNET_MQ_hd_var_size (slave_join_decision,
948                            GNUNET_MESSAGE_TYPE_PSYC_JOIN_DECISION,
949                            struct GNUNET_PSYC_JoinDecisionMessage,
950                            slv),
951     GNUNET_MQ_hd_var_size (channel_message,
952                            GNUNET_MESSAGE_TYPE_PSYC_MESSAGE,
953                            struct GNUNET_PSYC_MessageHeader,
954                            chn),
955     GNUNET_MQ_hd_fixed_size (channel_message_ack,
956                              GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_ACK,
957                              struct GNUNET_MessageHeader,
958                              chn),
959     GNUNET_MQ_hd_var_size (channel_history_result,
960                            GNUNET_MESSAGE_TYPE_PSYC_HISTORY_RESULT,
961                            struct GNUNET_OperationResultMessage,
962                            chn),
963     GNUNET_MQ_hd_var_size (channel_state_result,
964                            GNUNET_MESSAGE_TYPE_PSYC_STATE_RESULT,
965                            struct GNUNET_OperationResultMessage,
966                            chn),
967     GNUNET_MQ_hd_var_size (channel_result,
968                            GNUNET_MESSAGE_TYPE_PSYC_RESULT_CODE,
969                            struct GNUNET_OperationResultMessage,
970                            chn),
971     GNUNET_MQ_handler_end ()
972   };
973
974   chn->mq = GNUNET_CLIENT_connecT (chn->cfg, "psyc",
975                                    handlers, slave_disconnected, slv);
976   GNUNET_assert (NULL != chn->mq);
977   chn->tmit = GNUNET_PSYC_transmit_create (chn->mq);
978
979   GNUNET_MQ_send_copy (chn->mq, chn->connect_env);
980 }
981
982
983 /**
984  * Join a PSYC channel.
985  *
986  * The entity joining is always the local peer.  The user must immediately use
987  * the GNUNET_PSYC_slave_transmit() functions to transmit a @e join_msg to the
988  * channel; if the join request succeeds, the channel state (and @e recent
989  * method calls) will be replayed to the joining member.  There is no explicit
990  * notification on failure (as the channel may simply take days to approve,
991  * and disapproval is simply being ignored).
992  *
993  * @param cfg
994  *        Configuration to use.
995  * @param channel_key  ECC public key that identifies the channel we wish to join.
996  * @param slave_key  ECC private-public key pair that identifies the slave, and
997  *        used by multicast to sign the join request and subsequent unicast
998  *        requests sent to the master.
999  * @param origin  Peer identity of the origin.
1000  * @param relay_count  Number of peers in the @a relays array.
1001  * @param relays  Peer identities of members of the multicast group, which serve
1002  *        as relays and used to join the group at.
1003  * @param message_cb  Function to invoke on message parts received from the
1004  *        channel, typically at least contains method handlers for @e join and
1005  *        @e part.
1006  * @param slave_connect_cb  Function invoked once we have connected to the
1007  *        PSYC service.
1008  * @param join_decision_cb  Function invoked once we have received a join
1009  *        decision.
1010  * @param cls  Closure for @a message_cb and @a slave_joined_cb.
1011  * @param method_name  Method name for the join request.
1012  * @param env  Environment containing transient variables for the request, or NULL.
1013  * @param data  Payload for the join message.
1014  * @param data_size  Number of bytes in @a data.
1015  *
1016  * @return Handle for the slave, NULL on error.
1017  */
1018 struct GNUNET_PSYC_Slave *
1019 GNUNET_PSYC_slave_join (const struct GNUNET_CONFIGURATION_Handle *cfg,
1020                         const struct GNUNET_CRYPTO_EddsaPublicKey *channel_pub_key,
1021                         const struct GNUNET_CRYPTO_EcdsaPrivateKey *slave_key,
1022                         enum GNUNET_PSYC_SlaveJoinFlags flags,
1023                         const struct GNUNET_PeerIdentity *origin,
1024                         uint32_t relay_count,
1025                         const struct GNUNET_PeerIdentity *relays,
1026                         GNUNET_PSYC_MessageCallback message_cb,
1027                         GNUNET_PSYC_MessagePartCallback message_part_cb,
1028                         GNUNET_PSYC_SlaveConnectCallback connect_cb,
1029                         GNUNET_PSYC_JoinDecisionCallback join_decision_cb,
1030                         void *cls,
1031                         const struct GNUNET_PSYC_Message *join_msg)
1032 {
1033   struct GNUNET_PSYC_Slave *slv = GNUNET_malloc (sizeof (*slv));
1034   struct GNUNET_PSYC_Channel *chn = &slv->chn;
1035   uint16_t relay_size = relay_count * sizeof (*relays);
1036   uint16_t join_msg_size;
1037   if (NULL == join_msg)
1038     join_msg_size = 0;
1039   else
1040     join_msg_size = ntohs (join_msg->header.size);
1041
1042   struct SlaveJoinRequest *req;
1043   chn->connect_env = GNUNET_MQ_msg_extra (req, relay_size + join_msg_size,
1044                                           GNUNET_MESSAGE_TYPE_PSYC_SLAVE_JOIN);
1045   req->channel_pub_key = *channel_pub_key;
1046   req->slave_key = *slave_key;
1047   req->origin = *origin;
1048   req->relay_count = htonl (relay_count);
1049   req->flags = htonl (flags);
1050
1051   if (0 < relay_size)
1052     GNUNET_memcpy (&req[1], relays, relay_size);
1053
1054   if (NULL != join_msg)
1055     GNUNET_memcpy ((char *) &req[1] + relay_size, join_msg, join_msg_size);
1056
1057   chn->cfg = cfg;
1058   chn->is_master = GNUNET_NO;
1059   chn->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
1060
1061   chn->op = GNUNET_OP_create ();
1062   chn->recv = GNUNET_PSYC_receive_create (message_cb, message_part_cb, cls);
1063
1064   slv->connect_cb = connect_cb;
1065   slv->join_dcsn_cb = join_decision_cb;
1066   slv->cb_cls = cls;
1067
1068   slave_connect (slv);
1069   return slv;
1070 }
1071
1072
1073 /**
1074  * Part a PSYC channel.
1075  *
1076  * Will terminate the connection to the PSYC service.  Polite clients should
1077  * first explicitly send a part request (via GNUNET_PSYC_slave_transmit()).
1078  *
1079  * @param slave Slave handle.
1080  */
1081 void
1082 GNUNET_PSYC_slave_part (struct GNUNET_PSYC_Slave *slv,
1083                         int keep_active,
1084                         GNUNET_ContinuationCallback part_cb,
1085                         void *part_cls)
1086 {
1087   struct GNUNET_PSYC_Channel *chn = &slv->chn;
1088
1089   /* FIXME: send msg to service */
1090
1091   channel_disconnect (chn, part_cb, part_cls);
1092 }
1093
1094
1095 /**
1096  * Request a message to be sent to the channel master.
1097  *
1098  * @param slave Slave handle.
1099  * @param method_name Which (PSYC) method should be invoked (on host).
1100  * @param notify_mod Function to call to obtain modifiers.
1101  * @param notify_data Function to call to obtain fragments of the data.
1102  * @param notify_cls Closure for @a notify.
1103  * @param flags Flags for the message being transmitted.
1104  *
1105  * @return Transmission handle, NULL on error (i.e. more than one request
1106  *         queued).
1107  */
1108 struct GNUNET_PSYC_SlaveTransmitHandle *
1109 GNUNET_PSYC_slave_transmit (struct GNUNET_PSYC_Slave *slv,
1110                             const char *method_name,
1111                             GNUNET_PSYC_TransmitNotifyModifier notify_mod,
1112                             GNUNET_PSYC_TransmitNotifyData notify_data,
1113                             void *notify_cls,
1114                             enum GNUNET_PSYC_SlaveTransmitFlags flags)
1115
1116 {
1117   if (GNUNET_OK
1118       == GNUNET_PSYC_transmit_message (slv->chn.tmit, method_name, NULL,
1119                                        notify_mod, notify_data, notify_cls,
1120                                        flags))
1121     return (struct GNUNET_PSYC_SlaveTransmitHandle *) slv->chn.tmit;
1122   else
1123     return NULL;
1124 }
1125
1126
1127 /**
1128  * Resume transmission to the master.
1129  *
1130  * @param tmit Handle of the request that is being resumed.
1131  */
1132 void
1133 GNUNET_PSYC_slave_transmit_resume (struct GNUNET_PSYC_SlaveTransmitHandle *tmit)
1134 {
1135   GNUNET_PSYC_transmit_resume ((struct GNUNET_PSYC_TransmitHandle *) tmit);
1136 }
1137
1138
1139 /**
1140  * Abort transmission request to master.
1141  *
1142  * @param tmit Handle of the request that is being aborted.
1143  */
1144 void
1145 GNUNET_PSYC_slave_transmit_cancel (struct GNUNET_PSYC_SlaveTransmitHandle *tmit)
1146 {
1147   GNUNET_PSYC_transmit_cancel ((struct GNUNET_PSYC_TransmitHandle *) tmit);
1148 }
1149
1150
1151 /**
1152  * Convert @a slave to a @e channel handle to access the @e channel APIs.
1153  *
1154  * @param slv Slave handle.
1155  *
1156  * @return Channel handle, valid for as long as @a slave is valid.
1157  */
1158 struct GNUNET_PSYC_Channel *
1159 GNUNET_PSYC_slave_get_channel (struct GNUNET_PSYC_Slave *slv)
1160 {
1161   return &slv->chn;
1162 }
1163
1164
1165 /**
1166  * Add a slave to the channel's membership list.
1167  *
1168  * Note that this will NOT generate any PSYC traffic, it will merely update the
1169  * local database to modify how we react to <em>membership test</em> queries.
1170  * The channel master still needs to explicitly transmit a @e join message to
1171  * notify other channel members and they then also must still call this function
1172  * in their respective methods handling the @e join message.  This way, how @e
1173  * join and @e part operations are exactly implemented is still up to the
1174  * application; for example, there might be a @e part_all method to kick out
1175  * everyone.
1176  *
1177  * Note that channel slaves are explicitly trusted to execute such methods
1178  * correctly; not doing so correctly will result in either denying other slaves
1179  * access or offering access to channel data to non-members.
1180  *
1181  * @param chn
1182  *        Channel handle.
1183  * @param slave_pub_key
1184  *        Identity of channel slave to add.
1185  * @param announced_at
1186  *        ID of the message that announced the membership change.
1187  * @param effective_since
1188  *        Addition of slave is in effect since this message ID.
1189  * @param result_cb
1190  *        Function to call with the result of the operation.
1191  *        The @e result_code argument is #GNUNET_OK on success, or
1192  *        #GNUNET_SYSERR on error.  In case of an error, the @e data argument
1193  *        can contain an optional error message.
1194  * @param cls
1195  *        Closure for @a result_cb.
1196  */
1197 void
1198 GNUNET_PSYC_channel_slave_add (struct GNUNET_PSYC_Channel *chn,
1199                                const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_pub_key,
1200                                uint64_t announced_at,
1201                                uint64_t effective_since,
1202                                GNUNET_ResultCallback result_cb,
1203                                void *cls)
1204 {
1205   struct ChannelMembershipStoreRequest *req;
1206   struct GNUNET_MQ_Envelope *
1207     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYC_CHANNEL_MEMBERSHIP_STORE);
1208   req->slave_pub_key = *slave_pub_key;
1209   req->announced_at = GNUNET_htonll (announced_at);
1210   req->effective_since = GNUNET_htonll (effective_since);
1211   req->did_join = GNUNET_YES;
1212   req->op_id = GNUNET_htonll (GNUNET_OP_add (chn->op, result_cb, cls, NULL));
1213
1214   GNUNET_MQ_send (chn->mq, env);
1215 }
1216
1217
1218 /**
1219  * Remove a slave from the channel's membership list.
1220  *
1221  * Note that this will NOT generate any PSYC traffic, it will merely update the
1222  * local database to modify how we react to <em>membership test</em> queries.
1223  * The channel master still needs to explicitly transmit a @e part message to
1224  * notify other channel members and they then also must still call this function
1225  * in their respective methods handling the @e part message.  This way, how
1226  * @e join and @e part operations are exactly implemented is still up to the
1227  * application; for example, there might be a @e part_all message to kick out
1228  * everyone.
1229  *
1230  * Note that channel members are explicitly trusted to perform these
1231  * operations correctly; not doing so correctly will result in either
1232  * denying members access or offering access to channel data to
1233  * non-members.
1234  *
1235  * @param chn
1236  *        Channel handle.
1237  * @param slave_pub_key
1238  *        Identity of channel slave to remove.
1239  * @param announced_at
1240  *        ID of the message that announced the membership change.
1241  * @param result_cb
1242  *        Function to call with the result of the operation.
1243  *        The @e result_code argument is #GNUNET_OK on success, or
1244  *        #GNUNET_SYSERR on error.  In case of an error, the @e data argument
1245  *        can contain an optional error message.
1246  * @param cls
1247  *        Closure for @a result_cb.
1248  */
1249 void
1250 GNUNET_PSYC_channel_slave_remove (struct GNUNET_PSYC_Channel *chn,
1251                                   const struct GNUNET_CRYPTO_EcdsaPublicKey *slave_pub_key,
1252                                   uint64_t announced_at,
1253                                   GNUNET_ResultCallback result_cb,
1254                                   void *cls)
1255 {
1256   struct ChannelMembershipStoreRequest *req;
1257   struct GNUNET_MQ_Envelope *
1258     env = GNUNET_MQ_msg (req, GNUNET_MESSAGE_TYPE_PSYC_CHANNEL_MEMBERSHIP_STORE);
1259   req->slave_pub_key = *slave_pub_key;
1260   req->announced_at = GNUNET_htonll (announced_at);
1261   req->did_join = GNUNET_NO;
1262   req->op_id = GNUNET_htonll (GNUNET_OP_add (chn->op, result_cb, cls, NULL));
1263
1264   GNUNET_MQ_send (chn->mq, env);
1265 }
1266
1267
1268 static struct GNUNET_PSYC_HistoryRequest *
1269 channel_history_replay (struct GNUNET_PSYC_Channel *chn,
1270                         uint64_t start_message_id,
1271                         uint64_t end_message_id,
1272                         uint64_t message_limit,
1273                         const char *method_prefix,
1274                         uint32_t flags,
1275                         GNUNET_PSYC_MessageCallback message_cb,
1276                         GNUNET_PSYC_MessagePartCallback message_part_cb,
1277                         GNUNET_ResultCallback result_cb,
1278                         void *cls)
1279 {
1280   struct GNUNET_PSYC_HistoryRequestMessage *req;
1281   struct GNUNET_PSYC_HistoryRequest *hist = GNUNET_malloc (sizeof (*hist));
1282   hist->chn = chn;
1283   hist->recv = GNUNET_PSYC_receive_create (message_cb, message_part_cb, cls);
1284   hist->result_cb = result_cb;
1285   hist->cls = cls;
1286   hist->op_id = GNUNET_OP_add (chn->op, op_recv_history_result, hist, NULL);
1287
1288   GNUNET_assert (NULL != method_prefix);
1289   uint16_t method_size = strnlen (method_prefix,
1290                                   GNUNET_SERVER_MAX_MESSAGE_SIZE
1291                                   - sizeof (*req)) + 1;
1292   GNUNET_assert ('\0' == method_prefix[method_size - 1]);
1293
1294   struct GNUNET_MQ_Envelope *
1295     env = GNUNET_MQ_msg_extra (req, method_size,
1296                                GNUNET_MESSAGE_TYPE_PSYC_HISTORY_REPLAY);
1297   req->start_message_id = GNUNET_htonll (start_message_id);
1298   req->end_message_id = GNUNET_htonll (end_message_id);
1299   req->message_limit = GNUNET_htonll (message_limit);
1300   req->flags = htonl (flags);
1301   req->op_id = GNUNET_htonll (hist->op_id);
1302   GNUNET_memcpy (&req[1], method_prefix, method_size);
1303
1304   GNUNET_MQ_send (chn->mq, env);
1305   return hist;
1306 }
1307
1308
1309 /**
1310  * Request to replay a part of the message history of the channel.
1311  *
1312  * Historic messages (but NOT the state at the time) will be replayed and given
1313  * to the normal method handlers with a #GNUNET_PSYC_MESSAGE_HISTORIC flag set.
1314  *
1315  * Messages are retrieved from the local PSYCstore if available,
1316  * otherwise requested from the network.
1317  *
1318  * @param channel
1319  *        Which channel should be replayed?
1320  * @param start_message_id
1321  *        Earliest interesting point in history.
1322  * @param end_message_id
1323  *        Last (inclusive) interesting point in history.
1324  * @param method_prefix
1325  *        Retrieve only messages with a matching method prefix.
1326  * @param flags
1327  *        OR'ed enum GNUNET_PSYC_HistoryReplayFlags
1328  * @param result_cb
1329  *        Function to call when the requested history has been fully replayed.
1330  * @param cls
1331  *        Closure for the callbacks.
1332  *
1333  * @return Handle to cancel history replay operation.
1334  */
1335 struct GNUNET_PSYC_HistoryRequest *
1336 GNUNET_PSYC_channel_history_replay (struct GNUNET_PSYC_Channel *chn,
1337                                     uint64_t start_message_id,
1338                                     uint64_t end_message_id,
1339                                     const char *method_prefix,
1340                                     uint32_t flags,
1341                                     GNUNET_PSYC_MessageCallback message_cb,
1342                                     GNUNET_PSYC_MessagePartCallback message_part_cb,
1343                                     GNUNET_ResultCallback result_cb,
1344                                     void *cls)
1345 {
1346   return channel_history_replay (chn, start_message_id, end_message_id, 0,
1347                                  method_prefix, flags,
1348                                  message_cb, message_part_cb, result_cb, cls);
1349 }
1350
1351
1352 /**
1353  * Request to replay the latest messages from the message history of the channel.
1354  *
1355  * Historic messages (but NOT the state at the time) will be replayed (given to
1356  * the normal method handlers) if available and if access is permitted.
1357  *
1358  * @param channel
1359  *        Which channel should be replayed?
1360  * @param message_limit
1361  *        Maximum number of messages to replay.
1362  * @param method_prefix
1363  *        Retrieve only messages with a matching method prefix.
1364  *        Use NULL or "" to retrieve all.
1365  * @param flags
1366  *        OR'ed enum GNUNET_PSYC_HistoryReplayFlags
1367  * @param result_cb
1368  *        Function to call when the requested history has been fully replayed.
1369  * @param cls
1370  *        Closure for the callbacks.
1371  *
1372  * @return Handle to cancel history replay operation.
1373  */
1374 struct GNUNET_PSYC_HistoryRequest *
1375 GNUNET_PSYC_channel_history_replay_latest (struct GNUNET_PSYC_Channel *chn,
1376                                            uint64_t message_limit,
1377                                            const char *method_prefix,
1378                                            uint32_t flags,
1379                                            GNUNET_PSYC_MessageCallback message_cb,
1380                                            GNUNET_PSYC_MessagePartCallback message_part_cb,
1381                                            GNUNET_ResultCallback result_cb,
1382                                            void *cls)
1383 {
1384   return channel_history_replay (chn, 0, 0, message_limit, method_prefix, flags,
1385                                  message_cb, message_part_cb, result_cb, cls);
1386 }
1387
1388
1389 void
1390 GNUNET_PSYC_channel_history_replay_cancel (struct GNUNET_PSYC_Channel *channel,
1391                                            struct GNUNET_PSYC_HistoryRequest *hist)
1392 {
1393   GNUNET_PSYC_receive_destroy (hist->recv);
1394   GNUNET_OP_remove (hist->chn->op, hist->op_id);
1395   GNUNET_free (hist);
1396 }
1397
1398
1399 /**
1400  * Retrieve the best matching channel state variable.
1401  *
1402  * If the requested variable name is not present in the state, the nearest
1403  * less-specific name is matched; for example, requesting "_a_b" will match "_a"
1404  * if "_a_b" does not exist.
1405  *
1406  * @param channel
1407  *        Channel handle.
1408  * @param full_name
1409  *        Full name of the requested variable.
1410  *        The actual variable returned might have a shorter name.
1411  * @param var_cb
1412  *        Function called once when a matching state variable is found.
1413  *        Not called if there's no matching state variable.
1414  * @param result_cb
1415  *        Function called after the operation finished.
1416  *        (i.e. all state variables have been returned via @a state_cb)
1417  * @param cls
1418  *        Closure for the callbacks.
1419  */
1420 static struct GNUNET_PSYC_StateRequest *
1421 channel_state_get (struct GNUNET_PSYC_Channel *chn,
1422                    uint16_t type, const char *name,
1423                    GNUNET_PSYC_StateVarCallback var_cb,
1424                    GNUNET_ResultCallback result_cb, void *cls)
1425 {
1426   struct StateRequest *req;
1427   struct GNUNET_PSYC_StateRequest *sr = GNUNET_malloc (sizeof (*sr));
1428   sr->chn = chn;
1429   sr->var_cb = var_cb;
1430   sr->result_cb = result_cb;
1431   sr->cls = cls;
1432   sr->op_id = GNUNET_OP_add (chn->op, op_recv_state_result, sr, NULL);
1433
1434   GNUNET_assert (NULL != name);
1435   size_t name_size = strnlen (name, GNUNET_SERVER_MAX_MESSAGE_SIZE
1436                               - sizeof (*req)) + 1;
1437   struct GNUNET_MQ_Envelope *
1438     env = GNUNET_MQ_msg_extra (req, name_size, type);
1439   req->op_id = GNUNET_htonll (sr->op_id);
1440   GNUNET_memcpy (&req[1], name, name_size);
1441
1442   GNUNET_MQ_send (chn->mq, env);
1443   return sr;
1444 }
1445
1446
1447 /**
1448  * Retrieve the best matching channel state variable.
1449  *
1450  * If the requested variable name is not present in the state, the nearest
1451  * less-specific name is matched; for example, requesting "_a_b" will match "_a"
1452  * if "_a_b" does not exist.
1453  *
1454  * @param channel
1455  *        Channel handle.
1456  * @param full_name
1457  *        Full name of the requested variable.
1458  *        The actual variable returned might have a shorter name.
1459  * @param var_cb
1460  *        Function called once when a matching state variable is found.
1461  *        Not called if there's no matching state variable.
1462  * @param result_cb
1463  *        Function called after the operation finished.
1464  *        (i.e. all state variables have been returned via @a state_cb)
1465  * @param cls
1466  *        Closure for the callbacks.
1467  */
1468 struct GNUNET_PSYC_StateRequest *
1469 GNUNET_PSYC_channel_state_get (struct GNUNET_PSYC_Channel *chn,
1470                                const char *full_name,
1471                                GNUNET_PSYC_StateVarCallback var_cb,
1472                                GNUNET_ResultCallback result_cb,
1473                                void *cls)
1474 {
1475   return channel_state_get (chn, GNUNET_MESSAGE_TYPE_PSYC_STATE_GET,
1476                             full_name, var_cb, result_cb, cls);
1477
1478 }
1479
1480
1481 /**
1482  * Return all channel state variables whose name matches a given prefix.
1483  *
1484  * A name matches if it starts with the given @a name_prefix, thus requesting
1485  * the empty prefix ("") will match all values; requesting "_a_b" will also
1486  * return values stored under "_a_b_c".
1487  *
1488  * The @a state_cb is invoked on all matching state variables asynchronously, as
1489  * the state is stored in and retrieved from the PSYCstore,
1490  *
1491  * @param channel
1492  *        Channel handle.
1493  * @param name_prefix
1494  *        Prefix of the state variable name to match.
1495  * @param var_cb
1496  *        Function called once when a matching state variable is found.
1497  *        Not called if there's no matching state variable.
1498  * @param result_cb
1499  *        Function called after the operation finished.
1500  *        (i.e. all state variables have been returned via @a state_cb)
1501  * @param cls
1502  *        Closure for the callbacks.
1503  */
1504 struct GNUNET_PSYC_StateRequest *
1505 GNUNET_PSYC_channel_state_get_prefix (struct GNUNET_PSYC_Channel *chn,
1506                                       const char *name_prefix,
1507                                       GNUNET_PSYC_StateVarCallback var_cb,
1508                                       GNUNET_ResultCallback result_cb,
1509                                       void *cls)
1510 {
1511   return channel_state_get (chn, GNUNET_MESSAGE_TYPE_PSYC_STATE_GET_PREFIX,
1512                             name_prefix, var_cb, result_cb, cls);
1513 }
1514
1515
1516 /**
1517  * Cancel a state request operation.
1518  *
1519  * @param sr
1520  *        Handle for the operation to cancel.
1521  */
1522 void
1523 GNUNET_PSYC_channel_state_get_cancel (struct GNUNET_PSYC_StateRequest *sr)
1524 {
1525   GNUNET_OP_remove (sr->chn->op, sr->op_id);
1526   GNUNET_free (sr);
1527 }
1528
1529 /* end of psyc_api.c */