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