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