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