- FIX: GNUNET_SET_STATUS_HALF_DONE is never called only GNUNET_SET_STATUS_DONE
[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   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
351     size_min = sizeof (struct GNUNET_PSYC_MessageModifier);
352   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
353     size_min = sizeof (struct GNUNET_PSYC_MessageData);
354   }
355
356   if (! ((0 < size_eq && size == size_eq)
357          || (0 < size_min && size_min <= size)))
358   {
359     GNUNET_break (0);
360     reschedule_connect (ch);
361     return;
362   }
363
364   switch (type)
365   {
366   case GNUNET_MESSAGE_TYPE_PSYC_MASTER_START_ACK:
367     cres = (struct CountersResult *) msg;
368     mst->max_message_id = GNUNET_ntohll (cres->max_message_id);
369     if (NULL != mst->start_cb)
370       mst->start_cb (ch->cb_cls, mst->max_message_id);
371     break;
372
373   case GNUNET_MESSAGE_TYPE_PSYC_SLAVE_JOIN_ACK:
374     cres = (struct CountersResult *) msg;
375 #if TODO
376     slv->max_message_id = GNUNET_ntohll (cres->max_message_id);
377     if (NULL != slv->join_ack_cb)
378       mst->join_ack_cb (ch->cb_cls, mst->max_message_id);
379 #endif
380     break;
381
382   case GNUNET_MESSAGE_TYPE_PSYC_TRANSMIT_ACK:
383     tack = (struct TransmitAck *) msg;
384     if (ch->is_master)
385     {
386       GNUNET_assert (NULL != mst->tmit);
387       if (GNUNET_PSYC_DATA_CONT != mst->tmit->status
388           || NULL == mst->tmit->notify)
389       {
390         GNUNET_free (mst->tmit);
391         mst->tmit = NULL;
392       }
393       else
394       {
395         ch->tmit_buf_avail = ntohs (tack->buf_avail);
396         ch->tmit_ack_pending = GNUNET_NO;
397         if (GNUNET_NO == ch->tmit_paused)
398           master_transmit_data (mst);
399       }
400     }
401     else
402     {
403       /* TODO: slave */
404     }
405     break;
406
407   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD:
408
409     break;
410
411   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER:
412
413     break;
414
415   case GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_DATA:
416
417     break;
418   }
419
420   GNUNET_CLIENT_receive (ch->client, &message_handler, ch,
421                          GNUNET_TIME_UNIT_FOREVER_REL);
422 }
423
424
425 /**
426  * Transmit next message to service.
427  *
428  * @param cls The 'struct GNUNET_PSYC_Channel'.
429  * @param size Number of bytes available in buf.
430  * @param buf Where to copy the message.
431  * @return Number of bytes copied to buf.
432  */
433 static size_t
434 send_next_message (void *cls, size_t size, void *buf)
435 {
436   struct GNUNET_PSYC_Channel *ch = cls;
437   struct OperationHandle *op = ch->tmit_head;
438   size_t ret;
439   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_next_message()\n");
440   ch->th = NULL;
441   if (NULL == op->msg)
442     return 0;
443   ret = ntohs (op->msg->size);
444   if (ret > size)
445   {
446     reschedule_connect (ch);
447     return 0;
448   }
449   memcpy (buf, op->msg, ret);
450
451   GNUNET_CONTAINER_DLL_remove (ch->tmit_head, ch->tmit_tail, op);
452   GNUNET_free (op);
453
454   if (NULL != ch->tmit_head)
455     transmit_next (ch);
456
457   if (GNUNET_NO == ch->in_receive)
458   {
459     ch->in_receive = GNUNET_YES;
460     GNUNET_CLIENT_receive (ch->client, &message_handler, ch,
461                            GNUNET_TIME_UNIT_FOREVER_REL);
462   }
463   return ret;
464 }
465
466
467 /**
468  * Schedule transmission of the next message from our queue.
469  *
470  * @param ch PSYC handle.
471  */
472 static void
473 transmit_next (struct GNUNET_PSYC_Channel *ch)
474 {
475   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_next()\n");
476   if (NULL != ch->th || NULL == ch->client)
477     return;
478
479   struct OperationHandle *op = ch->tmit_head;
480   if (NULL == op)
481     return;
482
483   ch->th = GNUNET_CLIENT_notify_transmit_ready (ch->client,
484                                                 ntohs (op->msg->size),
485                                                 GNUNET_TIME_UNIT_FOREVER_REL,
486                                                 GNUNET_NO,
487                                                 &send_next_message,
488                                                 ch);
489 }
490
491
492 /**
493  * Try again to connect to the PSYC service.
494  *
495  * @param cls Channel handle.
496  * @param tc Scheduler context.
497  */
498 static void
499 reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
500 {
501   struct GNUNET_PSYC_Channel *ch = cls;
502
503   ch->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
504   LOG (GNUNET_ERROR_TYPE_DEBUG,
505        "Connecting to PSYC service.\n");
506   GNUNET_assert (NULL == ch->client);
507   ch->client = GNUNET_CLIENT_connect ("psyc", ch->cfg);
508   GNUNET_assert (NULL != ch->client);
509
510   if (NULL == ch->tmit_head ||
511       ch->tmit_head->msg->type != ch->reconnect_msg->type)
512   {
513     uint16_t reconn_size = ntohs (ch->reconnect_msg->size);
514     struct OperationHandle *op = GNUNET_malloc (sizeof (*op) + reconn_size);
515     memcpy (&op[1], ch->reconnect_msg, reconn_size);
516     op->msg = (struct GNUNET_MessageHeader *) &op[1];
517     GNUNET_CONTAINER_DLL_insert (ch->tmit_head, ch->tmit_tail, op);
518   }
519   transmit_next (ch);
520 }
521
522
523 /**
524  * Disconnect from the PSYC service.
525  *
526  * @param c Channel handle to disconnect
527  */
528 static void
529 disconnect (void *c)
530 {
531   struct GNUNET_PSYC_Channel *ch = c;
532
533   GNUNET_assert (NULL != ch);
534   if (ch->tmit_head != ch->tmit_tail)
535   {
536     LOG (GNUNET_ERROR_TYPE_ERROR,
537          "Disconnecting while there are still outstanding messages!\n");
538     GNUNET_break (0);
539   }
540   if (ch->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
541   {
542     GNUNET_SCHEDULER_cancel (ch->reconnect_task);
543     ch->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
544   }
545   if (NULL != ch->th)
546   {
547     GNUNET_CLIENT_notify_transmit_ready_cancel (ch->th);
548     ch->th = NULL;
549   }
550   if (NULL != ch->client)
551   {
552     GNUNET_CLIENT_disconnect (ch->client);
553     ch->client = NULL;
554   }
555   if (NULL != ch->reconnect_msg)
556   {
557     GNUNET_free (ch->reconnect_msg);
558     ch->reconnect_msg = NULL;
559   }
560 }
561
562
563 /**
564  * Start a PSYC master channel.
565  *
566  * Will start a multicast group identified by the given ECC key.  Messages
567  * received from group members will be given to the respective handler methods.
568  * If a new member wants to join a group, the "join" method handler will be
569  * invoked; the join handler must then generate a "join" message to approve the
570  * joining of the new member.  The channel can also change group membership
571  * without explicit requests.  Note that PSYC doesn't itself "understand" join
572  * or part messages, the respective methods must call other PSYC functions to
573  * inform PSYC about the meaning of the respective events.
574  *
575  * @param cfg Configuration to use (to connect to PSYC service).
576  * @param channel_key ECC key that will be used to sign messages for this
577  *        PSYC session. The public key is used to identify the PSYC channel.
578  *        Note that end-users will usually not use the private key directly, but
579  *        rather look it up in GNS for places managed by other users, or select
580  *        a file with the private key(s) when setting up their own channels
581  *        FIXME: we'll likely want to use NOT the p521 curve here, but a cheaper
582  *        one in the future.
583  * @param policy Channel policy specifying join and history restrictions.
584  *        Used to automate join decisions.
585  * @param method Function to invoke on messages received from slaves.
586  * @param join_cb Function to invoke when a peer wants to join.
587  * @param master_started_cb Function to invoke after the channel master started.
588  * @param cls Closure for @a master_started_cb and @a join_cb.
589  * @return Handle for the channel master, NULL on error.
590  */
591 struct GNUNET_PSYC_Master *
592 GNUNET_PSYC_master_start (const struct GNUNET_CONFIGURATION_Handle *cfg,
593                           const struct GNUNET_CRYPTO_EddsaPrivateKey *channel_key,
594                           enum GNUNET_PSYC_Policy policy,
595                           GNUNET_PSYC_Method method,
596                           GNUNET_PSYC_JoinCallback join_cb,
597                           GNUNET_PSYC_MasterStartCallback master_started_cb,
598                           void *cls)
599 {
600   struct GNUNET_PSYC_Master *mst = GNUNET_malloc (sizeof (*mst));
601   struct GNUNET_PSYC_Channel *ch = &mst->ch;
602   struct MasterStartRequest *req = GNUNET_malloc (sizeof (*req));
603
604   req->header.size = htons (sizeof (*req));
605   req->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_MASTER_START);
606   req->channel_key = *channel_key;
607   req->policy = policy;
608
609   ch->cfg = cfg;
610   ch->is_master = GNUNET_YES;
611   ch->reconnect_msg = (struct GNUNET_MessageHeader *) req;
612   ch->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
613   ch->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect, mst);
614
615   ch->method_cb = method;
616   ch->join_cb = join_cb;
617   ch->cb_cls = cls;
618   mst->start_cb = master_started_cb;
619
620   return mst;
621 }
622
623
624 /**
625  * Stop a PSYC master channel.
626  *
627  * @param master PSYC channel master to stop.
628  */
629 void
630 GNUNET_PSYC_master_stop (struct GNUNET_PSYC_Master *master)
631 {
632   disconnect (master);
633   GNUNET_free (master);
634 }
635
636
637 /**
638  * Function to call with the decision made for a join request.
639  *
640  * Must be called once and only once in response to an invocation of the
641  * #GNUNET_PSYC_JoinCallback.
642  *
643  * @param jh Join request handle.
644  * @param is_admitted #GNUNET_YES if joining is approved,
645  *        #GNUNET_NO if it is disapproved.
646  * @param relay_count Number of relays given.
647  * @param relays Array of suggested peers that might be useful relays to use
648  *        when joining the multicast group (essentially a list of peers that
649  *        are already part of the multicast group and might thus be willing
650  *        to help with routing).  If empty, only this local peer (which must
651  *        be the multicast origin) is a good candidate for building the
652  *        multicast tree.  Note that it is unnecessary to specify our own
653  *        peer identity in this array.
654  * @param method_name Method name for the message transmitted with the response.
655  * @param env Environment containing transient variables for the message, or NULL.
656  * @param data Data of the message.
657  * @param data_size Size of @a data.
658  */
659 void
660 GNUNET_PSYC_join_decision (struct GNUNET_PSYC_JoinHandle *jh,
661                            int is_admitted,
662                            uint32_t relay_count,
663                            const struct GNUNET_PeerIdentity *relays,
664                            const char *method_name,
665                            const struct GNUNET_ENV_Environment *env,
666                            const void *data,
667                            size_t data_size)
668 {
669
670 }
671
672
673 /* FIXME: split up value into <64K chunks and transmit the continuations in
674  *        MOD_CONT msgs */
675 static int
676 send_modifier (void *cls, struct GNUNET_ENV_Modifier *mod)
677 {
678   struct GNUNET_PSYC_Channel *ch = cls;
679   size_t name_size = strlen (mod->name) + 1;
680   struct GNUNET_PSYC_MessageModifier *pmod;
681   struct OperationHandle *op = GNUNET_malloc (sizeof (*op) + sizeof (*pmod)
682                                               + name_size + mod->value_size);
683   pmod = (struct GNUNET_PSYC_MessageModifier *) &op[1];
684   op->msg = (struct GNUNET_MessageHeader *) pmod;
685
686   pmod->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_MODIFIER);
687   pmod->header.size = htons (sizeof (*pmod) + name_size + mod->value_size);
688   pmod->name_size = htons (name_size);
689   memcpy (&pmod[1], mod->name, name_size);
690   memcpy ((char *) &pmod[1] + name_size, mod->value, mod->value_size);
691
692   GNUNET_CONTAINER_DLL_insert_tail (ch->tmit_head, ch->tmit_tail, op);
693   return GNUNET_YES;
694 }
695
696
697 /**
698  * Send a message to call a method to all members in the PSYC channel.
699  *
700  * @param master Handle to the PSYC channel.
701  * @param method_name Which method should be invoked.
702  * @param env Environment containing state operations and transient variables
703  *            for the message, or NULL.
704  * @param notify Function to call to obtain the arguments.
705  * @param notify_cls Closure for @a notify.
706  * @param flags Flags for the message being transmitted.
707  * @return Transmission handle, NULL on error (i.e. more than one request
708  *         queued).
709  */
710 struct GNUNET_PSYC_MasterTransmitHandle *
711 GNUNET_PSYC_master_transmit (struct GNUNET_PSYC_Master *master,
712                              const char *method_name,
713                              const struct GNUNET_ENV_Environment *env,
714                              GNUNET_PSYC_MasterTransmitNotify notify,
715                              void *notify_cls,
716                              enum GNUNET_PSYC_MasterTransmitFlags flags)
717 {
718   GNUNET_assert (NULL != master);
719   struct GNUNET_PSYC_Channel *ch = &master->ch;
720   if (GNUNET_NO != ch->in_transmit)
721     return NULL;
722   ch->in_transmit = GNUNET_YES;
723
724   size_t size = strlen (method_name) + 1;
725   struct GNUNET_PSYC_MessageMethod *pmeth;
726   struct OperationHandle *op
727     = GNUNET_malloc (sizeof (*op) + sizeof (*pmeth) + size);
728   pmeth = (struct GNUNET_PSYC_MessageMethod *) &op[1];
729   op->msg = (struct GNUNET_MessageHeader *) pmeth;
730
731   pmeth->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_MESSAGE_METHOD);
732   pmeth->header.size = htons (sizeof (*pmeth) + size);
733   pmeth->flags = htonl (flags);
734   pmeth->mod_count = GNUNET_ntohll (GNUNET_ENV_environment_get_mod_count (env));
735   memcpy (&pmeth[1], method_name, size);
736
737   GNUNET_CONTAINER_DLL_insert_tail (ch->tmit_head, ch->tmit_tail, op);
738   GNUNET_ENV_environment_iterate (env, send_modifier, master);
739   transmit_next (ch);
740
741   master->tmit = GNUNET_malloc (sizeof (*master->tmit));
742   master->tmit->master = master;
743   master->tmit->notify = notify;
744   master->tmit->notify_cls = notify_cls;
745   master->tmit->status = GNUNET_PSYC_DATA_CONT;
746   return master->tmit;
747 }
748
749
750 /**
751  * Resume transmission to the channel.
752  *
753  * @param th Handle of the request that is being resumed.
754  */
755 void
756 GNUNET_PSYC_master_transmit_resume (struct GNUNET_PSYC_MasterTransmitHandle *th)
757 {
758   struct GNUNET_PSYC_Channel *ch = &th->master->ch;
759   if (GNUNET_NO == ch->tmit_ack_pending)
760   {
761     ch->tmit_paused = GNUNET_NO;
762     master_transmit_data (th->master);
763   }
764 }
765
766
767 /**
768  * Abort transmission request to the channel.
769  *
770  * @param th Handle of the request that is being aborted.
771  */
772 void
773 GNUNET_PSYC_master_transmit_cancel (struct GNUNET_PSYC_MasterTransmitHandle *th)
774 {
775   struct GNUNET_PSYC_Master *master = th->master;
776   struct GNUNET_PSYC_Channel *ch = &master->ch;
777   if (GNUNET_NO != ch->in_transmit)
778     return;
779 }
780
781
782 /**
783  * Join a PSYC channel.
784  *
785  * The entity joining is always the local peer.  The user must immediately use
786  * the GNUNET_PSYC_slave_transmit() functions to transmit a @e join_msg to the
787  * channel; if the join request succeeds, the channel state (and @e recent
788  * method calls) will be replayed to the joining member.  There is no explicit
789  * notification on failure (as the channel may simply take days to approve,
790  * and disapproval is simply being ignored).
791  *
792  * @param cfg Configuration to use.
793  * @param channel_key ECC public key that identifies the channel we wish to join.
794  * @param slave_key ECC private-public key pair that identifies the slave, and
795  *        used by multicast to sign the join request and subsequent unicast
796  *        requests sent to the master.
797  * @param origin Peer identity of the origin.
798  * @param relay_count Number of peers in the @a relays array.
799  * @param relays Peer identities of members of the multicast group, which serve
800  *        as relays and used to join the group at.
801  * @param method Function to invoke on messages received from the channel,
802  *        typically at least contains functions for @e join and @e part.
803  * @param join_cb function invoked once we have joined with the current
804  *        message ID of the channel
805  * @param slave_joined_cb Function to invoke when a peer wants to join.
806  * @param cls Closure for @a method_cb and @a slave_joined_cb.
807  * @param method_name Method name for the join request.
808  * @param env Environment containing transient variables for the request, or NULL.
809  * @param data Payload for the join message.
810  * @param data_size Number of bytes in @a data.
811  * @return Handle for the slave, NULL on error.
812  */
813 struct GNUNET_PSYC_Slave *
814 GNUNET_PSYC_slave_join (const struct GNUNET_CONFIGURATION_Handle *cfg,
815                         const struct GNUNET_CRYPTO_EddsaPublicKey *channel_key,
816                         const struct GNUNET_CRYPTO_EddsaPrivateKey *slave_key,
817                         const struct GNUNET_PeerIdentity *origin,
818                         uint32_t relay_count,
819                         const struct GNUNET_PeerIdentity *relays,
820                         GNUNET_PSYC_Method method,
821                         GNUNET_PSYC_JoinCallback join_cb,
822                         GNUNET_PSYC_SlaveJoinCallback slave_joined_cb,
823                         void *cls,
824                         const char *method_name,
825                         const struct GNUNET_ENV_Environment *env,
826                         const void *data,
827                         uint16_t data_size)
828 {
829   struct GNUNET_PSYC_Slave *slv = GNUNET_malloc (sizeof (*slv));
830   struct GNUNET_PSYC_Channel *ch = &slv->ch;
831   struct SlaveJoinRequest *req = GNUNET_malloc (sizeof (*req)
832                                                 + relay_count * sizeof (*relays));
833   req->header.size = htons (sizeof (*req)
834                             + relay_count * sizeof (*relays));
835   req->header.type = htons (GNUNET_MESSAGE_TYPE_PSYC_SLAVE_JOIN);
836   req->channel_key = *channel_key;
837   req->slave_key = *slave_key;
838   req->origin = *origin;
839   req->relay_count = relay_count;
840   memcpy (&req[1], relays, relay_count * sizeof (*relays));
841
842   ch->cfg = cfg;
843   ch->is_master = GNUNET_NO;
844   ch->reconnect_msg = (struct GNUNET_MessageHeader *) req;
845   ch->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
846   ch->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect, slv);
847
848   return slv;
849 }
850
851
852 /**
853  * Part a PSYC channel.
854  *
855  * Will terminate the connection to the PSYC service.  Polite clients should
856  * first explicitly send a part request (via GNUNET_PSYC_slave_transmit()).
857  *
858  * @param slave Slave handle.
859  */
860 void
861 GNUNET_PSYC_slave_part (struct GNUNET_PSYC_Slave *slave)
862 {
863   disconnect (slave);
864   GNUNET_free (slave);
865 }
866
867
868 /**
869  * Request a message to be sent to the channel master.
870  *
871  * @param slave Slave handle.
872  * @param method_name Which (PSYC) method should be invoked (on host).
873  * @param env Environment containing transient variables for the message, or
874  *            NULL.
875  * @param notify Function to call when we are allowed to transmit (to get data).
876  * @param notify_cls Closure for @a notify.
877  * @param flags Flags for the message being transmitted.
878  * @return Transmission handle, NULL on error (i.e. more than one request
879  *         queued).
880  */
881 struct GNUNET_PSYC_SlaveTransmitHandle *
882 GNUNET_PSYC_slave_transmit (struct GNUNET_PSYC_Slave *slave,
883                             const char *method_name,
884                             const struct GNUNET_ENV_Environment *env,
885                             GNUNET_PSYC_SlaveTransmitNotify notify,
886                             void *notify_cls,
887                             enum GNUNET_PSYC_SlaveTransmitFlags flags)
888 {
889   return NULL;
890 }
891
892
893 /**
894  * Resume transmission to the master.
895  *
896  * @param th Handle of the request that is being resumed.
897  */
898 void
899 GNUNET_PSYC_slave_transmit_resume (struct GNUNET_PSYC_MasterTransmitHandle *th)
900 {
901
902 }
903
904
905 /**
906  * Abort transmission request to master.
907  *
908  * @param th Handle of the request that is being aborted.
909  */
910 void
911 GNUNET_PSYC_slave_transmit_cancel (struct GNUNET_PSYC_SlaveTransmitHandle *th)
912 {
913
914 }
915
916
917 /**
918  * Convert a channel @a master to a @e channel handle to access the @e channel
919  * APIs.
920  *
921  * @param master Channel master handle.
922  * @return Channel handle, valid for as long as @a master is valid.
923  */
924 struct GNUNET_PSYC_Channel *
925 GNUNET_PSYC_master_get_channel (struct GNUNET_PSYC_Master *master)
926 {
927   return (struct GNUNET_PSYC_Channel *) master;
928 }
929
930
931 /**
932  * Convert @a slave to a @e channel handle to access the @e channel APIs.
933  *
934  * @param slave Slave handle.
935  * @return Channel handle, valid for as long as @a slave is valid.
936  */
937 struct GNUNET_PSYC_Channel *
938 GNUNET_PSYC_slave_get_channel (struct GNUNET_PSYC_Slave *slave)
939 {
940   return (struct GNUNET_PSYC_Channel *) slave;
941 }
942
943
944 /**
945  * Add a slave to the channel's membership list.
946  *
947  * Note that this will NOT generate any PSYC traffic, it will merely update the
948  * local database to modify how we react to <em>membership test</em> queries.
949  * The channel master still needs to explicitly transmit a @e join message to
950  * notify other channel members and they then also must still call this function
951  * in their respective methods handling the @e join message.  This way, how @e
952  * join and @e part operations are exactly implemented is still up to the
953  * application; for example, there might be a @e part_all method to kick out
954  * everyone.
955  *
956  * Note that channel slaves are explicitly trusted to execute such methods
957  * correctly; not doing so correctly will result in either denying other slaves
958  * access or offering access to channel data to non-members.
959  *
960  * @param channel Channel handle.
961  * @param slave_key Identity of channel slave to add.
962  * @param announced_at ID of the message that announced the membership change.
963  * @param effective_since Addition of slave is in effect since this message ID.
964  */
965 void
966 GNUNET_PSYC_channel_slave_add (struct GNUNET_PSYC_Channel *channel,
967                                const struct GNUNET_CRYPTO_EddsaPublicKey *slave_key,
968                                uint64_t announced_at,
969                                uint64_t effective_since)
970 {
971   struct ChannelSlaveAdd *slvadd;
972   struct OperationHandle *op = GNUNET_malloc (sizeof (*op) + sizeof (*slvadd));
973
974   slvadd = (struct ChannelSlaveAdd *) &op[1];
975   op->msg = (struct GNUNET_MessageHeader *) slvadd;
976
977   slvadd->header.type = GNUNET_MESSAGE_TYPE_PSYC_CHANNEL_SLAVE_ADD;
978   slvadd->header.size = htons (sizeof (*slvadd));
979   slvadd->announced_at = GNUNET_htonll (announced_at);
980   slvadd->effective_since = GNUNET_htonll (effective_since);
981   GNUNET_CONTAINER_DLL_insert_tail (channel->tmit_head,
982                                     channel->tmit_tail,
983                                     op);
984   transmit_next (channel);
985 }
986
987
988 /**
989  * Remove a slave from the channel's membership list.
990  *
991  * Note that this will NOT generate any PSYC traffic, it will merely update the
992  * local database to modify how we react to <em>membership test</em> queries.
993  * The channel master still needs to explicitly transmit a @e part message to
994  * notify other channel members and they then also must still call this function
995  * in their respective methods handling the @e part message.  This way, how
996  * @e join and @e part operations are exactly implemented is still up to the
997  * application; for example, there might be a @e part_all message to kick out
998  * everyone.
999  *
1000  * Note that channel members are explicitly trusted to perform these
1001  * operations correctly; not doing so correctly will result in either
1002  * denying members access or offering access to channel data to
1003  * non-members.
1004  *
1005  * @param channel Channel handle.
1006  * @param slave_key Identity of channel slave to remove.
1007  * @param announced_at ID of the message that announced the membership change.
1008  */
1009 void
1010 GNUNET_PSYC_channel_slave_remove (struct GNUNET_PSYC_Channel *channel,
1011                                   const struct GNUNET_CRYPTO_EddsaPublicKey *slave_key,
1012                                   uint64_t announced_at)
1013 {
1014   struct ChannelSlaveRemove *slvrm;
1015   struct OperationHandle *op = GNUNET_malloc (sizeof (*op) + sizeof (*slvrm));
1016
1017   slvrm = (struct ChannelSlaveRemove *) &op[1];
1018   op->msg = (struct GNUNET_MessageHeader *) slvrm;
1019   slvrm->header.type = GNUNET_MESSAGE_TYPE_PSYC_CHANNEL_SLAVE_RM;
1020   slvrm->header.size = htons (sizeof (*slvrm));
1021   slvrm->announced_at = GNUNET_htonll (announced_at);
1022   GNUNET_CONTAINER_DLL_insert_tail (channel->tmit_head,
1023                                     channel->tmit_tail,
1024                                     op);
1025   transmit_next (channel);
1026 }
1027
1028
1029 /**
1030  * Request to be told the message history of the channel.
1031  *
1032  * Historic messages (but NOT the state at the time) will be replayed (given to
1033  * the normal method handlers) if available and if access is permitted.
1034  *
1035  * To get the latest message, use 0 for both the start and end message ID.
1036  *
1037  * @param channel Which channel should be replayed?
1038  * @param start_message_id Earliest interesting point in history.
1039  * @param end_message_id Last (exclusive) interesting point in history.
1040  * @param method Function to invoke on messages received from the story.
1041  * @param finish_cb Function to call when the requested story has been fully
1042  *        told (counting message IDs might not suffice, as some messages
1043  *        might be secret and thus the listener would not know the story is
1044  *        finished without being told explicitly) once this function
1045  *        has been called, the client must not call
1046  *        GNUNET_PSYC_channel_story_tell_cancel() anymore.
1047  * @param cls Closure for the callbacks.
1048  * @return Handle to cancel story telling operation.
1049  */
1050 struct GNUNET_PSYC_Story *
1051 GNUNET_PSYC_channel_story_tell (struct GNUNET_PSYC_Channel *channel,
1052                                 uint64_t start_message_id,
1053                                 uint64_t end_message_id,
1054                                 GNUNET_PSYC_Method method,
1055                                 GNUNET_PSYC_FinishCallback *finish_cb,
1056                                 void *cls)
1057 {
1058   return NULL;
1059 }
1060
1061
1062 /**
1063  * Abort story telling.
1064  *
1065  * This function must not be called from within method handlers (as given to
1066  * GNUNET_PSYC_slave_join()) of the slave.
1067  *
1068  * @param story Story telling operation to stop.
1069  */
1070 void
1071 GNUNET_PSYC_channel_story_tell_cancel (struct GNUNET_PSYC_Story *story)
1072 {
1073
1074 }
1075
1076
1077 /**
1078  * Retrieve the best matching channel state variable.
1079  *
1080  * If the requested variable name is not present in the state, the nearest
1081  * less-specific name is matched; for example, requesting "_a_b" will match "_a"
1082  * if "_a_b" does not exist.
1083  *
1084  * @param channel Channel handle.
1085  * @param full_name Full name of the requested variable, the actual variable
1086  *        returned might have a shorter name..
1087  * @param cb Function called once when a matching state variable is found.
1088  *        Not called if there's no matching state variable.
1089  * @param cb_cls Closure for the callbacks.
1090  * @return Handle that can be used to cancel the query operation.
1091  */
1092 struct GNUNET_PSYC_StateQuery *
1093 GNUNET_PSYC_channel_state_get (struct GNUNET_PSYC_Channel *channel,
1094                                const char *full_name,
1095                                GNUNET_PSYC_StateCallback cb,
1096                                void *cb_cls)
1097 {
1098   return NULL;
1099 }
1100
1101
1102 /**
1103  * Return all channel state variables whose name matches a given prefix.
1104  *
1105  * A name matches if it starts with the given @a name_prefix, thus requesting
1106  * the empty prefix ("") will match all values; requesting "_a_b" will also
1107  * return values stored under "_a_b_c".
1108  *
1109  * The @a state_cb is invoked on all matching state variables asynchronously, as
1110  * the state is stored in and retrieved from the PSYCstore,
1111  *
1112  * @param channel Channel handle.
1113  * @param name_prefix Prefix of the state variable name to match.
1114  * @param cb Function to call with the matching state variables.
1115  * @param cb_cls Closure for the callbacks.
1116  * @return Handle that can be used to cancel the query operation.
1117  */
1118 struct GNUNET_PSYC_StateQuery *
1119 GNUNET_PSYC_channel_state_get_prefix (struct GNUNET_PSYC_Channel *channel,
1120                                       const char *name_prefix,
1121                                       GNUNET_PSYC_StateCallback cb,
1122                                       void *cb_cls)
1123 {
1124   return NULL;
1125 }
1126
1127
1128 /**
1129  * Cancel a state query operation.
1130  *
1131  * @param query Handle for the operation to cancel.
1132  */
1133 void
1134 GNUNET_PSYC_channel_state_get_cancel (struct GNUNET_PSYC_StateQuery *query)
1135 {
1136
1137 }
1138
1139
1140 /* end of psyc_api.c */