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