-handle new error code from enum
[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 "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_env_lib.h"
36 #include "gnunet_psyc_service.h"
37 #include "psyc.h"
38
39 #define LOG(kind,...) GNUNET_log_from (kind, "psyc-api",__VA_ARGS__)
40
41
42 struct OperationHandle
43 {
44   struct OperationHandle *prev;
45   struct OperationHandle *next;
46   const struct GNUNET_MessageHeader *msg;
47 };
48
49 /**
50  * Handle to access PSYC channel operations for both the master and slaves.
51  */
52 struct GNUNET_PSYC_Channel
53 {
54   /**
55    * Configuration to use.
56    */
57   const struct GNUNET_CONFIGURATION_Handle *cfg;
58
59   /**
60    * Socket (if available).
61    */
62   struct GNUNET_CLIENT_Connection *client;
63
64   /**
65    * Currently pending transmission request, or NULL for none.
66    */
67   struct GNUNET_CLIENT_TransmitHandle *th;
68
69   /**
70    * Head of operations to transmit.
71    */
72   struct OperationHandle *tmit_head;
73
74   /**
75    * Tail of operations to transmit.
76    */
77   struct OperationHandle *tmit_tail;
78
79   /**
80    * Message to send on reconnect.
81    */
82   struct GNUNET_MessageHeader *reconnect_msg;
83
84   /**
85    * Task doing exponential back-off trying to reconnect.
86    */
87   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
88
89   /**
90    * Time for next connect retry.
91    */
92   struct GNUNET_TIME_Relative reconnect_delay;
93
94   GNUNET_PSYC_Method method_cb;
95
96   GNUNET_PSYC_JoinCallback join_cb;
97
98   void *cb_cls;
99
100   /**
101    * Are we polling for incoming messages right now?
102    */
103   int in_receive;
104
105   /**
106    * Are we currently transmitting a message?
107    */
108   int in_transmit;
109
110   /**
111    * Is this a master or slave channel?
112    */
113   int is_master;
114
115   /**
116    * Buffer space available for transmitting the next data fragment.
117    */
118   uint16_t tmit_buf_avail;
119
120   /**
121    * Is transmission paused?
122    */
123   uint8_t tmit_paused;
124
125   /**
126    * Are we still waiting for a PSYC_TRANSMIT_ACK?
127    */
128   uint8_t tmit_ack_pending;
129 };
130
131
132 /**
133  * Handle for a pending PSYC transmission operation.
134  */
135 struct GNUNET_PSYC_MasterTransmitHandle
136 {
137   struct GNUNET_PSYC_Master *master;
138   GNUNET_PSYC_MasterTransmitNotify notify;
139   void *notify_cls;
140   enum GNUNET_PSYC_DataStatus status;
141 };
142
143
144 /**
145  * Handle for the master of a PSYC channel.
146  */
147 struct GNUNET_PSYC_Master
148 {
149   struct GNUNET_PSYC_Channel ch;
150
151   struct GNUNET_PSYC_MasterTransmitHandle *tmit;
152
153   GNUNET_PSYC_MasterStartCallback start_cb;
154
155   uint64_t max_message_id;
156 };
157
158
159 /**
160  * Handle for a PSYC channel slave.
161  */
162 struct GNUNET_PSYC_Slave
163 {
164   struct GNUNET_PSYC_Channel ch;
165 };
166
167
168 /**
169  * Handle that identifies a join request.
170  *
171  * Used to match calls to #GNUNET_PSYC_JoinCallback to the
172  * corresponding calls to GNUNET_PSYC_join_decision().
173  */
174 struct GNUNET_PSYC_JoinHandle
175 {
176
177 };
178
179
180 /**
181  * Handle for a pending PSYC transmission operation.
182  */
183 struct GNUNET_PSYC_SlaveTransmitHandle
184 {
185
186 };
187
188
189 /**
190  * Handle to a story telling operation.
191  */
192 struct GNUNET_PSYC_Story
193 {
194
195 };
196
197
198 /**
199  * Handle for a state query operation.
200  */
201 struct GNUNET_PSYC_StateQuery
202 {
203
204 };
205
206
207 /**
208  * Try again to connect to the PSYC service.
209  *
210  * @param cls Handle to the PSYC service.
211  * @param tc Scheduler context
212  */
213 static void
214 reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
215
216
217 /**
218  * Reschedule a connect attempt to the service.
219  *
220  * @param c channel to reconnect
221  */
222 static void
223 reschedule_connect (struct GNUNET_PSYC_Channel *c)
224 {
225   GNUNET_assert (c->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
226
227   if (NULL != c->th)
228   {
229     GNUNET_CLIENT_notify_transmit_ready_cancel (c->th);
230     c->th = NULL;
231   }
232   if (NULL != c->client)
233   {
234     GNUNET_CLIENT_disconnect (c->client);
235     c->client = NULL;
236   }
237   c->in_receive = GNUNET_NO;
238   LOG (GNUNET_ERROR_TYPE_DEBUG,
239        "Scheduling task to reconnect to PSYC service in %s.\n",
240        GNUNET_STRINGS_relative_time_to_string (c->reconnect_delay, GNUNET_YES));
241   c->reconnect_task =
242       GNUNET_SCHEDULER_add_delayed (c->reconnect_delay, &reconnect, c);
243   c->reconnect_delay = GNUNET_TIME_STD_BACKOFF (c->reconnect_delay);
244 }
245
246
247 /**
248  * Schedule transmission of the next message from our queue.
249  *
250  * @param ch PSYC channel handle
251  */
252 static void
253 transmit_next (struct GNUNET_PSYC_Channel *ch);
254
255
256 /**
257  * Request data from client to transmit.
258  *
259  * @param mst Master handle.
260  */
261 static void
262 master_transmit_data (struct GNUNET_PSYC_Master *mst)
263 {
264   struct GNUNET_PSYC_Channel *ch = &mst->ch;
265   size_t data_size = ch->tmit_buf_avail;
266   struct GNUNET_PSYC_MessageData *pdata;
267   struct OperationHandle *op
268     = GNUNET_malloc (sizeof (*op) + sizeof (*pdata) + data_size);
269   pdata = (struct GNUNET_PSYC_MessageData *) &op[1];
270   op->msg = (struct GNUNET_MessageHeader *) pdata;
271   pdata->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA);
272
273   switch (mst->tmit->notify (mst->tmit->notify_cls, &data_size, &pdata[1]))
274   {
275   case GNUNET_NO:
276     mst->tmit->status = GNUNET_PSYC_DATA_CONT;
277     break;
278
279   case GNUNET_YES:
280     mst->tmit->status = GNUNET_PSYC_DATA_END;
281     break;
282
283   default:
284     mst->tmit->status = GNUNET_PSYC_DATA_CANCEL;
285     data_size = 0;
286     LOG (GNUNET_ERROR_TYPE_ERROR, "MasterTransmitNotify returned error.\n");
287   }
288
289   if ((GNUNET_PSYC_DATA_CONT == mst->tmit->status && 0 == data_size))
290   {
291     /* Transmission paused, nothing to send. */
292     ch->tmit_paused = GNUNET_YES;
293     GNUNET_free (op);
294   }
295   else
296   {
297     GNUNET_assert (data_size <= ch->tmit_buf_avail);
298     pdata->header.size = htons (sizeof (*pdata) + data_size);
299     pdata->status = htons (mst->tmit->status);
300     GNUNET_CONTAINER_DLL_insert_tail (ch->tmit_head, ch->tmit_tail, op);
301     ch->tmit_ack_pending = GNUNET_YES;
302     transmit_next (ch);
303   }
304 }
305
306
307 /**
308  * Type of a function to call when we receive a message
309  * from the service.
310  *
311  * @param cls closure
312  * @param msg message received, NULL on timeout or fatal error
313  */
314 static void
315 message_handler (void *cls,
316                  const struct GNUNET_MessageHeader *msg)
317 {
318   // YUCK! => please have disjoint message handlers...
319   struct GNUNET_PSYC_Channel *ch = cls;
320   struct GNUNET_PSYC_Master *mst = cls;
321   struct GNUNET_PSYC_Slave *slv = cls;
322   struct CountersResult *cres;
323   struct TransmitAck *tack;
324
325   if (NULL == msg)
326   {
327     reschedule_connect (ch);
328     return;
329   }
330   uint16_t size_eq = 0;
331   uint16_t size_min = 0;
332   uint16_t size = ntohs (msg->size);
333   uint16_t type = ntohs (msg->type);
334
335   LOG (GNUNET_ERROR_TYPE_DEBUG,
336        "Received message of type %d and size %u from PSYC service\n",
337        type, size);
338
339   switch (type)
340   {
341   case GNUNET_MESSAGE_TYPE_PSYC_MASTER_START_ACK:
342   case GNUNET_MESSAGE_TYPE_PSYC_SLAVE_JOIN_ACK:
343     size_eq = sizeof (struct CountersResult);
344     break;
345   case GNUNET_MESSAGE_TYPE_PSYC_TRANSMIT_ACK:
346     size_eq = sizeof (struct TransmitAck);
347     break;
348   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD:
349     size_min = sizeof (struct GNUNET_PSYC_MessageMethod);
350     break;
351   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
352     size_min = sizeof (struct GNUNET_PSYC_MessageModifier);
353     break;
354   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
355     size_min = sizeof (struct GNUNET_PSYC_MessageData);
356     break;
357   default:
358     GNUNET_break_op (0);
359     return;
360   }
361
362   if (! ((0 < size_eq && size == size_eq)
363          || (0 < size_min && size_min <= size)))
364   {
365     GNUNET_break (0);
366     reschedule_connect (ch);
367     return;
368   }
369
370   switch (type)
371   {
372   case GNUNET_MESSAGE_TYPE_PSYC_MASTER_START_ACK:
373     cres = (struct CountersResult *) msg;
374     mst->max_message_id = GNUNET_ntohll (cres->max_message_id);
375     if (NULL != mst->start_cb)
376       mst->start_cb (ch->cb_cls, mst->max_message_id);
377     break;
378
379   case GNUNET_MESSAGE_TYPE_PSYC_SLAVE_JOIN_ACK:
380     cres = (struct CountersResult *) msg;
381 #if TODO
382     slv->max_message_id = GNUNET_ntohll (cres->max_message_id);
383     if (NULL != slv->join_ack_cb)
384       mst->join_ack_cb (ch->cb_cls, mst->max_message_id);
385 #endif
386     break;
387
388   case GNUNET_MESSAGE_TYPE_PSYC_TRANSMIT_ACK:
389     tack = (struct TransmitAck *) msg;
390     if (ch->is_master)
391     {
392       GNUNET_assert (NULL != mst->tmit);
393       if (GNUNET_PSYC_DATA_CONT != mst->tmit->status
394           || NULL == mst->tmit->notify)
395       {
396         GNUNET_free (mst->tmit);
397         mst->tmit = NULL;
398       }
399       else
400       {
401         ch->tmit_buf_avail = ntohs (tack->buf_avail);
402         ch->tmit_ack_pending = GNUNET_NO;
403         if (GNUNET_NO == ch->tmit_paused)
404           master_transmit_data (mst);
405       }
406     }
407     else
408     {
409       /* TODO: slave */
410     }
411     break;
412
413   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD:
414
415     break;
416
417   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
418
419     break;
420
421   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
422
423     break;
424   }
425
426   GNUNET_CLIENT_receive (ch->client, &message_handler, ch,
427                          GNUNET_TIME_UNIT_FOREVER_REL);
428 }
429
430
431 /**
432  * Transmit next message to service.
433  *
434  * @param cls The 'struct GNUNET_PSYC_Channel'.
435  * @param size Number of bytes available in buf.
436  * @param buf Where to copy the message.
437  * @return Number of bytes copied to buf.
438  */
439 static size_t
440 send_next_message (void *cls, size_t size, void *buf)
441 {
442   struct GNUNET_PSYC_Channel *ch = cls;
443   struct OperationHandle *op = ch->tmit_head;
444   size_t ret;
445   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_next_message()\n");
446   ch->th = NULL;
447   if (NULL == op->msg)
448     return 0;
449   ret = ntohs (op->msg->size);
450   if (ret > size)
451   {
452     reschedule_connect (ch);
453     return 0;
454   }
455   memcpy (buf, op->msg, ret);
456
457   GNUNET_CONTAINER_DLL_remove (ch->tmit_head, ch->tmit_tail, op);
458   GNUNET_free (op);
459
460   if (NULL != ch->tmit_head)
461     transmit_next (ch);
462
463   if (GNUNET_NO == ch->in_receive)
464   {
465     ch->in_receive = GNUNET_YES;
466     GNUNET_CLIENT_receive (ch->client, &message_handler, ch,
467                            GNUNET_TIME_UNIT_FOREVER_REL);
468   }
469   return ret;
470 }
471
472
473 /**
474  * Schedule transmission of the next message from our queue.
475  *
476  * @param ch PSYC handle.
477  */
478 static void
479 transmit_next (struct GNUNET_PSYC_Channel *ch)
480 {
481   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_next()\n");
482   if (NULL != ch->th || NULL == ch->client)
483     return;
484
485   struct OperationHandle *op = ch->tmit_head;
486   if (NULL == op)
487     return;
488
489   ch->th = GNUNET_CLIENT_notify_transmit_ready (ch->client,
490                                                 ntohs (op->msg->size),
491                                                 GNUNET_TIME_UNIT_FOREVER_REL,
492                                                 GNUNET_NO,
493                                                 &send_next_message,
494                                                 ch);
495 }
496
497
498 /**
499  * Try again to connect to the PSYC service.
500  *
501  * @param cls Channel handle.
502  * @param tc Scheduler context.
503  */
504 static void
505 reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
506 {
507   struct GNUNET_PSYC_Channel *ch = cls;
508
509   ch->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
510   LOG (GNUNET_ERROR_TYPE_DEBUG,
511        "Connecting to PSYC service.\n");
512   GNUNET_assert (NULL == ch->client);
513   ch->client = GNUNET_CLIENT_connect ("psyc", ch->cfg);
514   GNUNET_assert (NULL != ch->client);
515
516   if (NULL == ch->tmit_head ||
517       ch->tmit_head->msg->type != ch->reconnect_msg->type)
518   {
519     uint16_t reconn_size = ntohs (ch->reconnect_msg->size);
520     struct OperationHandle *op = GNUNET_malloc (sizeof (*op) + reconn_size);
521     memcpy (&op[1], ch->reconnect_msg, reconn_size);
522     op->msg = (struct GNUNET_MessageHeader *) &op[1];
523     GNUNET_CONTAINER_DLL_insert (ch->tmit_head, ch->tmit_tail, op);
524   }
525   transmit_next (ch);
526 }
527
528
529 /**
530  * Disconnect from the PSYC service.
531  *
532  * @param c Channel handle to disconnect
533  */
534 static void
535 disconnect (void *c)
536 {
537   struct GNUNET_PSYC_Channel *ch = c;
538
539   GNUNET_assert (NULL != ch);
540   if (ch->tmit_head != ch->tmit_tail)
541   {
542     LOG (GNUNET_ERROR_TYPE_ERROR,
543          "Disconnecting while there are still outstanding messages!\n");
544     GNUNET_break (0);
545   }
546   if (ch->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
547   {
548     GNUNET_SCHEDULER_cancel (ch->reconnect_task);
549     ch->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
550   }
551   if (NULL != ch->th)
552   {
553     GNUNET_CLIENT_notify_transmit_ready_cancel (ch->th);
554     ch->th = NULL;
555   }
556   if (NULL != ch->client)
557   {
558     GNUNET_CLIENT_disconnect (ch->client);
559     ch->client = NULL;
560   }
561   if (NULL != ch->reconnect_msg)
562   {
563     GNUNET_free (ch->reconnect_msg);
564     ch->reconnect_msg = NULL;
565   }
566 }
567
568
569 /**
570  * Start a PSYC master channel.
571  *
572  * Will start a multicast group identified by the given ECC key.  Messages
573  * received from group members will be given to the respective handler methods.
574  * If a new member wants to join a group, the "join" method handler will be
575  * invoked; the join handler must then generate a "join" message to approve the
576  * joining of the new member.  The channel can also change group membership
577  * without explicit requests.  Note that PSYC doesn't itself "understand" join
578  * or part messages, the respective methods must call other PSYC functions to
579  * inform PSYC about the meaning of the respective events.
580  *
581  * @param cfg Configuration to use (to connect to PSYC service).
582  * @param channel_key ECC key that will be used to sign messages for this
583  *        PSYC session. The public key is used to identify the PSYC channel.
584  *        Note that end-users will usually not use the private key directly, but
585  *        rather look it up in GNS for places managed by other users, or select
586  *        a file with the private key(s) when setting up their own channels
587  *        FIXME: we'll likely want to use NOT the p521 curve here, but a cheaper
588  *        one in the future.
589  * @param policy Channel policy specifying join and history restrictions.
590  *        Used to automate join decisions.
591  * @param method Function to invoke on messages received from slaves.
592  * @param join_cb Function to invoke when a peer wants to join.
593  * @param master_started_cb Function to invoke after the channel master started.
594  * @param cls Closure for @a master_started_cb and @a join_cb.
595  * @return Handle for the channel master, NULL on error.
596  */
597 struct GNUNET_PSYC_Master *
598 GNUNET_PSYC_master_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
599                           const struct GNUNET_CRYPTO_EddsaPrivateKey *channel_key,
600                           enum GNUNET_PSYC_Policy policy,
601                           GNUNET_PSYC_Method method,
602                           GNUNET_PSYC_JoinCallback join_cb,
603                           GNUNET_PSYC_MasterStartCallback master_started_cb,
604                           void *cls)
605 {
606   struct GNUNET_PSYC_Master *mst = GNUNET_malloc (sizeof (*mst));
607   struct GNUNET_PSYC_Channel *ch = &mst->ch;
608   struct MasterStartRequest *req = GNUNET_malloc (sizeof (*req));
609
610   req->header.size = htons (sizeof (*req));
611   req->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_MASTER_START);
612   req->channel_key = *channel_key;
613   req->policy = policy;
614
615   ch->cfg = cfg;
616   ch->is_master = GNUNET_YES;
617   ch->reconnect_msg = (struct GNUNET_MessageHeader *) req;
618   ch->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
619   ch->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect, mst);
620
621   ch->method_cb = method;
622   ch->join_cb = join_cb;
623   ch->cb_cls = cls;
624   mst->start_cb = master_started_cb;
625
626   return mst;
627 }
628
629
630 /**
631  * Stop a PSYC master channel.
632  *
633  * @param master PSYC channel master to stop.
634  */
635 void
636 GNUNET_PSYC_master_stop (struct GNUNET_PSYC_Master *master)
637 {
638   disconnect (master);
639   GNUNET_free (master);
640 }
641
642
643 /**
644  * Function to call with the decision made for a join request.
645  *
646  * Must be called once and only once in response to an invocation of the
647  * #GNUNET_PSYC_JoinCallback.
648  *
649  * @param jh Join request handle.
650  * @param is_admitted #GNUNET_YES if joining is approved,
651  *        #GNUNET_NO if it is disapproved.
652  * @param relay_count Number of relays given.
653  * @param relays Array of suggested peers that might be useful relays to use
654  *        when joining the multicast group (essentially a list of peers that
655  *        are already part of the multicast group and might thus be willing
656  *        to help with routing).  If empty, only this local peer (which must
657  *        be the multicast origin) is a good candidate for building the
658  *        multicast tree.  Note that it is unnecessary to specify our own
659  *        peer identity in this array.
660  * @param method_name Method name for the message transmitted with the response.
661  * @param env Environment containing transient variables for the message, or NULL.
662  * @param data Data of the message.
663  * @param data_size Size of @a data.
664  */
665 void
666 GNUNET_PSYC_join_decision (struct GNUNET_PSYC_JoinHandle *jh,
667                            int is_admitted,
668                            uint32_t relay_count,
669                            const struct GNUNET_PeerIdentity *relays,
670                            const char *method_name,
671                            const struct GNUNET_ENV_Environment *env,
672                            const void *data,
673                            size_t data_size)
674 {
675
676 }
677
678
679 /* FIXME: split up value into <64K chunks and transmit the continuations in
680  *        MOD_CONT msgs */
681 static int
682 send_modifier (void *cls, struct GNUNET_ENV_Modifier *mod)
683 {
684   struct GNUNET_PSYC_Channel *ch = cls;
685   size_t name_size = strlen (mod->name) + 1;
686   struct GNUNET_PSYC_MessageModifier *pmod;
687   struct OperationHandle *op = GNUNET_malloc (sizeof (*op) + sizeof (*pmod)
688                                               + name_size + mod->value_size);
689   pmod = (struct GNUNET_PSYC_MessageModifier *) &op[1];
690   op->msg = (struct GNUNET_MessageHeader *) pmod;
691
692   pmod->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER);
693   pmod->header.size = htons (sizeof (*pmod) + name_size + mod->value_size);
694   pmod->name_size = htons (name_size);
695   memcpy (&pmod[1], mod->name, name_size);
696   memcpy ((char *) &pmod[1] + name_size, mod->value, mod->value_size);
697
698   GNUNET_CONTAINER_DLL_insert_tail (ch->tmit_head, ch->tmit_tail, op);
699   return GNUNET_YES;
700 }
701
702
703 /**
704  * Send a message to call a method to all members in the PSYC channel.
705  *
706  * @param master Handle to the PSYC channel.
707  * @param method_name Which method should be invoked.
708  * @param env Environment containing state operations and transient variables
709  *            for the message, or NULL.
710  * @param notify Function to call to obtain the arguments.
711  * @param notify_cls Closure for @a notify.
712  * @param flags Flags for the message being transmitted.
713  * @return Transmission handle, NULL on error (i.e. more than one request
714  *         queued).
715  */
716 struct GNUNET_PSYC_MasterTransmitHandle *
717 GNUNET_PSYC_master_transmit (struct GNUNET_PSYC_Master *master,
718                              const char *method_name,
719                              const struct GNUNET_ENV_Environment *env,
720                              GNUNET_PSYC_MasterTransmitNotify notify,
721                              void *notify_cls,
722                              enum GNUNET_PSYC_MasterTransmitFlags flags)
723 {
724   GNUNET_assert (NULL != master);
725   struct GNUNET_PSYC_Channel *ch = &master->ch;
726   if (GNUNET_NO != ch->in_transmit)
727     return NULL;
728   ch->in_transmit = GNUNET_YES;
729
730   size_t size = strlen (method_name) + 1;
731   struct GNUNET_PSYC_MessageMethod *pmeth;
732   struct OperationHandle *op
733     = GNUNET_malloc (sizeof (*op) + sizeof (*pmeth) + size);
734   pmeth = (struct GNUNET_PSYC_MessageMethod *) &op[1];
735   op->msg = (struct GNUNET_MessageHeader *) pmeth;
736
737   pmeth->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD);
738   pmeth->header.size = htons (sizeof (*pmeth) + size);
739   pmeth->flags = htonl (flags);
740   pmeth->mod_count = GNUNET_ntohll (GNUNET_ENV_environment_get_mod_count (env));
741   memcpy (&pmeth[1], method_name, size);
742
743   GNUNET_CONTAINER_DLL_insert_tail (ch->tmit_head, ch->tmit_tail, op);
744   GNUNET_ENV_environment_iterate (env, send_modifier, master);
745   transmit_next (ch);
746
747   master->tmit = GNUNET_malloc (sizeof (*master->tmit));
748   master->tmit->master = master;
749   master->tmit->notify = notify;
750   master->tmit->notify_cls = notify_cls;
751   master->tmit->status = GNUNET_PSYC_DATA_CONT;
752   return master->tmit;
753 }
754
755
756 /**
757  * Resume transmission to the channel.
758  *
759  * @param th Handle of the request that is being resumed.
760  */
761 void
762 GNUNET_PSYC_master_transmit_resume (struct GNUNET_PSYC_MasterTransmitHandle *th)
763 {
764   struct GNUNET_PSYC_Channel *ch = &th->master->ch;
765   if (GNUNET_NO == ch->tmit_ack_pending)
766   {
767     ch->tmit_paused = GNUNET_NO;
768     master_transmit_data (th->master);
769   }
770 }
771
772
773 /**
774  * Abort transmission request to the channel.
775  *
776  * @param th Handle of the request that is being aborted.
777  */
778 void
779 GNUNET_PSYC_master_transmit_cancel (struct GNUNET_PSYC_MasterTransmitHandle *th)
780 {
781   struct GNUNET_PSYC_Master *master = th->master;
782   struct GNUNET_PSYC_Channel *ch = &master->ch;
783   if (GNUNET_NO != ch->in_transmit)
784     return;
785 }
786
787
788 /**
789  * Join a PSYC channel.
790  *
791  * The entity joining is always the local peer.  The user must immediately use
792  * the GNUNET_PSYC_slave_transmit() functions to transmit a @e join_msg to the
793  * channel; if the join request succeeds, the channel state (and @e recent
794  * method calls) will be replayed to the joining member.  There is no explicit
795  * notification on failure (as the channel may simply take days to approve,
796  * and disapproval is simply being ignored).
797  *
798  * @param cfg Configuration to use.
799  * @param channel_key ECC public key that identifies the channel we wish to join.
800  * @param slave_key ECC private-public key pair that identifies the slave, and
801  *        used by multicast to sign the join request and subsequent unicast
802  *        requests sent to the master.
803  * @param origin Peer identity of the origin.
804  * @param relay_count Number of peers in the @a relays array.
805  * @param relays Peer identities of members of the multicast group, which serve
806  *        as relays and used to join the group at.
807  * @param method Function to invoke on messages received from the channel,
808  *        typically at least contains functions for @e join and @e part.
809  * @param join_cb function invoked once we have joined with the current
810  *        message ID of the channel
811  * @param slave_joined_cb Function to invoke when a peer wants to join.
812  * @param cls Closure for @a method_cb and @a slave_joined_cb.
813  * @param method_name Method name for the join request.
814  * @param env Environment containing transient variables for the request, or NULL.
815  * @param data Payload for the join message.
816  * @param data_size Number of bytes in @a data.
817  * @return Handle for the slave, NULL on error.
818  */
819 struct GNUNET_PSYC_Slave *
820 GNUNET_PSYC_slave_join (const struct GNUNET_CONFIGURATION_Handle *cfg,
821                         const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
822                         const struct GNUNET_CRYPTO_EddsaPrivateKey *slave_key,
823                         const struct GNUNET_PeerIdentity *origin,
824                         uint32_t relay_count,
825                         const struct GNUNET_PeerIdentity *relays,
826                         GNUNET_PSYC_Method method,
827                         GNUNET_PSYC_JoinCallback join_cb,
828                         GNUNET_PSYC_SlaveJoinCallback slave_joined_cb,
829                         void *cls,
830                         const char *method_name,
831                         const struct GNUNET_ENV_Environment *env,
832                         const void *data,
833                         uint16_t data_size)
834 {
835   struct GNUNET_PSYC_Slave *slv = GNUNET_malloc (sizeof (*slv));
836   struct GNUNET_PSYC_Channel *ch = &slv->ch;
837   struct SlaveJoinRequest *req = GNUNET_malloc (sizeof (*req)
838                                                 + relay_count * sizeof (*relays));
839   req->header.size = htons (sizeof (*req)
840                             + relay_count * sizeof (*relays));
841   req->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_SLAVE_JOIN);
842   req->channel_key = *channel_key;
843   req->slave_key = *slave_key;
844   req->origin = *origin;
845   req->relay_count = relay_count;
846   memcpy (&req[1], relays, relay_count * sizeof (*relays));
847
848   ch->cfg = cfg;
849   ch->is_master = GNUNET_NO;
850   ch->reconnect_msg = (struct GNUNET_MessageHeader *) req;
851   ch->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
852   ch->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect, slv);
853
854   return slv;
855 }
856
857
858 /**
859  * Part a PSYC channel.
860  *
861  * Will terminate the connection to the PSYC service.  Polite clients should
862  * first explicitly send a part request (via GNUNET_PSYC_slave_transmit()).
863  *
864  * @param slave Slave handle.
865  */
866 void
867 GNUNET_PSYC_slave_part (struct GNUNET_PSYC_Slave *slave)
868 {
869   disconnect (slave);
870   GNUNET_free (slave);
871 }
872
873
874 /**
875  * Request a message to be sent to the channel master.
876  *
877  * @param slave Slave handle.
878  * @param method_name Which (PSYC) method should be invoked (on host).
879  * @param env Environment containing transient variables for the message, or
880  *            NULL.
881  * @param notify Function to call when we are allowed to transmit (to get data).
882  * @param notify_cls Closure for @a notify.
883  * @param flags Flags for the message being transmitted.
884  * @return Transmission handle, NULL on error (i.e. more than one request
885  *         queued).
886  */
887 struct GNUNET_PSYC_SlaveTransmitHandle *
888 GNUNET_PSYC_slave_transmit (struct GNUNET_PSYC_Slave *slave,
889                             const char *method_name,
890                             const struct GNUNET_ENV_Environment *env,
891                             GNUNET_PSYC_SlaveTransmitNotify notify,
892                             void *notify_cls,
893                             enum GNUNET_PSYC_SlaveTransmitFlags flags)
894 {
895   return NULL;
896 }
897
898
899 /**
900  * Resume transmission to the master.
901  *
902  * @param th Handle of the request that is being resumed.
903  */
904 void
905 GNUNET_PSYC_slave_transmit_resume (struct GNUNET_PSYC_MasterTransmitHandle *th)
906 {
907
908 }
909
910
911 /**
912  * Abort transmission request to master.
913  *
914  * @param th Handle of the request that is being aborted.
915  */
916 void
917 GNUNET_PSYC_slave_transmit_cancel (struct GNUNET_PSYC_SlaveTransmitHandle *th)
918 {
919
920 }
921
922
923 /**
924  * Convert a channel @a master to a @e channel handle to access the @e channel
925  * APIs.
926  *
927  * @param master Channel master handle.
928  * @return Channel handle, valid for as long as @a master is valid.
929  */
930 struct GNUNET_PSYC_Channel *
931 GNUNET_PSYC_master_get_channel (struct GNUNET_PSYC_Master *master)
932 {
933   return (struct GNUNET_PSYC_Channel *) master;
934 }
935
936
937 /**
938  * Convert @a slave to a @e channel handle to access the @e channel APIs.
939  *
940  * @param slave Slave handle.
941  * @return Channel handle, valid for as long as @a slave is valid.
942  */
943 struct GNUNET_PSYC_Channel *
944 GNUNET_PSYC_slave_get_channel (struct GNUNET_PSYC_Slave *slave)
945 {
946   return (struct GNUNET_PSYC_Channel *) slave;
947 }
948
949
950 /**
951  * Add a slave to the channel's membership list.
952  *
953  * Note that this will NOT generate any PSYC traffic, it will merely update the
954  * local database to modify how we react to <em>membership test</em> queries.
955  * The channel master still needs to explicitly transmit a @e join message to
956  * notify other channel members and they then also must still call this function
957  * in their respective methods handling the @e join message.  This way, how @e
958  * join and @e part operations are exactly implemented is still up to the
959  * application; for example, there might be a @e part_all method to kick out
960  * everyone.
961  *
962  * Note that channel slaves are explicitly trusted to execute such methods
963  * correctly; not doing so correctly will result in either denying other slaves
964  * access or offering access to channel data to non-members.
965  *
966  * @param channel Channel handle.
967  * @param slave_key Identity of channel slave to add.
968  * @param announced_at ID of the message that announced the membership change.
969  * @param effective_since Addition of slave is in effect since this message ID.
970  */
971 void
972 GNUNET_PSYC_channel_slave_add (struct GNUNET_PSYC_Channel *channel,
973                                const struct GNUNET_CRYPTO_EddsaPublicKey *slave_key,
974                                uint64_t announced_at,
975                                uint64_t effective_since)
976 {
977   struct ChannelSlaveAdd *slvadd;
978   struct OperationHandle *op = GNUNET_malloc (sizeof (*op) + sizeof (*slvadd));
979
980   slvadd = (struct ChannelSlaveAdd *) &op[1];
981   op->msg = (struct GNUNET_MessageHeader *) slvadd;
982
983   slvadd->header.type = GNUNET_MESSAGE_TYPE_PSYC_CHANNEL_SLAVE_ADD;
984   slvadd->header.size = htons (sizeof (*slvadd));
985   slvadd->announced_at = GNUNET_htonll (announced_at);
986   slvadd->effective_since = GNUNET_htonll (effective_since);
987   GNUNET_CONTAINER_DLL_insert_tail (channel->tmit_head,
988                                     channel->tmit_tail,
989                                     op);
990   transmit_next (channel);
991 }
992
993
994 /**
995  * Remove a slave from the channel's membership list.
996  *
997  * Note that this will NOT generate any PSYC traffic, it will merely update the
998  * local database to modify how we react to <em>membership test</em> queries.
999  * The channel master still needs to explicitly transmit a @e part message to
1000  * notify other channel members and they then also must still call this function
1001  * in their respective methods handling the @e part message.  This way, how
1002  * @e join and @e part operations are exactly implemented is still up to the
1003  * application; for example, there might be a @e part_all message to kick out
1004  * everyone.
1005  *
1006  * Note that channel members are explicitly trusted to perform these
1007  * operations correctly; not doing so correctly will result in either
1008  * denying members access or offering access to channel data to
1009  * non-members.
1010  *
1011  * @param channel Channel handle.
1012  * @param slave_key Identity of channel slave to remove.
1013  * @param announced_at ID of the message that announced the membership change.
1014  */
1015 void
1016 GNUNET_PSYC_channel_slave_remove (struct GNUNET_PSYC_Channel *channel,
1017                                   const struct GNUNET_CRYPTO_EddsaPublicKey *slave_key,
1018                                   uint64_t announced_at)
1019 {
1020   struct ChannelSlaveRemove *slvrm;
1021   struct OperationHandle *op = GNUNET_malloc (sizeof (*op) + sizeof (*slvrm));
1022
1023   slvrm = (struct ChannelSlaveRemove *) &op[1];
1024   op->msg = (struct GNUNET_MessageHeader *) slvrm;
1025   slvrm->header.type = GNUNET_MESSAGE_TYPE_PSYC_CHANNEL_SLAVE_RM;
1026   slvrm->header.size = htons (sizeof (*slvrm));
1027   slvrm->announced_at = GNUNET_htonll (announced_at);
1028   GNUNET_CONTAINER_DLL_insert_tail (channel->tmit_head,
1029                                     channel->tmit_tail,
1030                                     op);
1031   transmit_next (channel);
1032 }
1033
1034
1035 /**
1036  * Request to be told the message history of the channel.
1037  *
1038  * Historic messages (but NOT the state at the time) will be replayed (given to
1039  * the normal method handlers) if available and if access is permitted.
1040  *
1041  * To get the latest message, use 0 for both the start and end message ID.
1042  *
1043  * @param channel Which channel should be replayed?
1044  * @param start_message_id Earliest interesting point in history.
1045  * @param end_message_id Last (exclusive) interesting point in history.
1046  * @param method Function to invoke on messages received from the story.
1047  * @param finish_cb Function to call when the requested story has been fully
1048  *        told (counting message IDs might not suffice, as some messages
1049  *        might be secret and thus the listener would not know the story is
1050  *        finished without being told explicitly) once this function
1051  *        has been called, the client must not call
1052  *        GNUNET_PSYC_channel_story_tell_cancel() anymore.
1053  * @param cls Closure for the callbacks.
1054  * @return Handle to cancel story telling operation.
1055  */
1056 struct GNUNET_PSYC_Story *
1057 GNUNET_PSYC_channel_story_tell (struct GNUNET_PSYC_Channel *channel,
1058                                 uint64_t start_message_id,
1059                                 uint64_t end_message_id,
1060                                 GNUNET_PSYC_Method method,
1061                                 GNUNET_PSYC_FinishCallback *finish_cb,
1062                                 void *cls)
1063 {
1064   return NULL;
1065 }
1066
1067
1068 /**
1069  * Abort story telling.
1070  *
1071  * This function must not be called from within method handlers (as given to
1072  * GNUNET_PSYC_slave_join()) of the slave.
1073  *
1074  * @param story Story telling operation to stop.
1075  */
1076 void
1077 GNUNET_PSYC_channel_story_tell_cancel (struct GNUNET_PSYC_Story *story)
1078 {
1079
1080 }
1081
1082
1083 /**
1084  * Retrieve the best matching channel state variable.
1085  *
1086  * If the requested variable name is not present in the state, the nearest
1087  * less-specific name is matched; for example, requesting "_a_b" will match "_a"
1088  * if "_a_b" does not exist.
1089  *
1090  * @param channel Channel handle.
1091  * @param full_name Full name of the requested variable, the actual variable
1092  *        returned might have a shorter name..
1093  * @param cb Function called once when a matching state variable is found.
1094  *        Not called if there's no matching state variable.
1095  * @param cb_cls Closure for the callbacks.
1096  * @return Handle that can be used to cancel the query operation.
1097  */
1098 struct GNUNET_PSYC_StateQuery *
1099 GNUNET_PSYC_channel_state_get (struct GNUNET_PSYC_Channel *channel,
1100                                const char *full_name,
1101                                GNUNET_PSYC_StateCallback cb,
1102                                void *cb_cls)
1103 {
1104   return NULL;
1105 }
1106
1107
1108 /**
1109  * Return all channel state variables whose name matches a given prefix.
1110  *
1111  * A name matches if it starts with the given @a name_prefix, thus requesting
1112  * the empty prefix ("") will match all values; requesting "_a_b" will also
1113  * return values stored under "_a_b_c".
1114  *
1115  * The @a state_cb is invoked on all matching state variables asynchronously, as
1116  * the state is stored in and retrieved from the PSYCstore,
1117  *
1118  * @param channel Channel handle.
1119  * @param name_prefix Prefix of the state variable name to match.
1120  * @param cb Function to call with the matching state variables.
1121  * @param cb_cls Closure for the callbacks.
1122  * @return Handle that can be used to cancel the query operation.
1123  */
1124 struct GNUNET_PSYC_StateQuery *
1125 GNUNET_PSYC_channel_state_get_prefix (struct GNUNET_PSYC_Channel *channel,
1126                                       const char *name_prefix,
1127                                       GNUNET_PSYC_StateCallback cb,
1128                                       void *cb_cls)
1129 {
1130   return NULL;
1131 }
1132
1133
1134 /**
1135  * Cancel a state query operation.
1136  *
1137  * @param query Handle for the operation to cancel.
1138  */
1139 void
1140 GNUNET_PSYC_channel_state_get_cancel (struct GNUNET_PSYC_StateQuery *query)
1141 {
1142
1143 }
1144
1145
1146 /* end of psyc_api.c */