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