- improved logging of payload traffic
[oweals/gnunet.git] / src / cadet / cadet_api.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011 Christian Grothoff (and other contributing authors)
4      GNUnet is free software; you can redistribute it and/or modify
5      it under the terms of the GNU General Public License as published
6      by the Free Software Foundation; either version 3, or (at your
7      option) any later version.
8      GNUnet is distributed in the hope that it will be useful, but
9      WITHOUT ANY WARRANTY; without even the implied warranty of
10      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11      General Public License for more details.
12      You should have received a copy of the GNU General Public License
13      along with GNUnet; see the file COPYING.  If not, write to the
14      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
15      Boston, MA 02110-1301, USA.
16 */
17
18 /**
19  * @file cadet/cadet_api.c
20  * @brief cadet api: client implementation of new cadet service
21  * @author Bartlomiej Polot
22  */
23
24 #include "platform.h"
25 #include "gnunet_util_lib.h"
26 #include "gnunet_cadet_service.h"
27 #include "cadet.h"
28 #include "cadet_protocol.h"
29
30 #define LOG(kind,...) GNUNET_log_from (kind, "cadet-api",__VA_ARGS__)
31 #define DATA_OVERHEAD sizeof(struct GNUNET_CADET_LocalData)
32
33 /******************************************************************************/
34 /************************      DATA STRUCTURES     ****************************/
35 /******************************************************************************/
36
37 /**
38  * Transmission queue to the service
39  */
40 struct GNUNET_CADET_TransmitHandle
41 {
42
43     /**
44      * Double Linked list
45      */
46   struct GNUNET_CADET_TransmitHandle *next;
47
48     /**
49      * Double Linked list
50      */
51   struct GNUNET_CADET_TransmitHandle *prev;
52
53     /**
54      * Channel this message is sent on / for (may be NULL for control messages).
55      */
56   struct GNUNET_CADET_Channel *channel;
57
58     /**
59      * Callback to obtain the message to transmit, or NULL if we
60      * got the message in 'data'.  Notice that messages built
61      * by 'notify' need to be encapsulated with information about
62      * the 'target'.
63      */
64   GNUNET_CONNECTION_TransmitReadyNotify notify;
65
66     /**
67      * Closure for 'notify'
68      */
69   void *notify_cls;
70
71     /**
72      * How long is this message valid.  Once the timeout has been
73      * reached, the message must no longer be sent.  If this
74      * is a message with a 'notify' callback set, the 'notify'
75      * function should be called with 'buf' NULL and size 0.
76      */
77   struct GNUNET_TIME_Absolute timeout;
78
79     /**
80      * Task triggering a timeout, can be NO_TASK if the timeout is FOREVER.
81      */
82   struct GNUNET_SCHEDULER_Task * timeout_task;
83
84     /**
85      * Size of 'data' -- or the desired size of 'notify' if 'data' is NULL.
86      */
87   size_t size;
88 };
89
90 union CadetInfoCB {
91
92   /**
93    * Channel callback.
94    */
95   GNUNET_CADET_ChannelCB channel_cb;
96
97   /**
98    * Monitor callback
99    */
100   GNUNET_CADET_PeersCB peers_cb;
101
102   /**
103    * Monitor callback
104    */
105   GNUNET_CADET_PeerCB peer_cb;
106
107   /**
108    * Monitor callback
109    */
110   GNUNET_CADET_TunnelsCB tunnels_cb;
111
112   /**
113    * Tunnel callback.
114    */
115   GNUNET_CADET_TunnelCB tunnel_cb;
116 };
117
118
119 /**
120  * Opaque handle to the service.
121  */
122 struct GNUNET_CADET_Handle
123 {
124
125     /**
126      * Handle to the server connection, to send messages later
127      */
128   struct GNUNET_CLIENT_Connection *client;
129
130     /**
131      * Set of handlers used for processing incoming messages in the channels
132      */
133   const struct GNUNET_CADET_MessageHandler *message_handlers;
134
135   /**
136    * Number of handlers in the handlers array.
137    */
138   unsigned int n_handlers;
139
140   /**
141    * Ports open.
142    */
143   const uint32_t *ports;
144
145   /**
146    * Number of ports.
147    */
148   unsigned int n_ports;
149
150     /**
151      * Double linked list of the channels this client is connected to, head.
152      */
153   struct GNUNET_CADET_Channel *channels_head;
154
155     /**
156      * Double linked list of the channels this client is connected to, tail.
157      */
158   struct GNUNET_CADET_Channel *channels_tail;
159
160     /**
161      * Callback for inbound channel creation
162      */
163   GNUNET_CADET_InboundChannelNotificationHandler *new_channel;
164
165     /**
166      * Callback for inbound channel disconnection
167      */
168   GNUNET_CADET_ChannelEndHandler *cleaner;
169
170     /**
171      * Handle to cancel pending transmissions in case of disconnection
172      */
173   struct GNUNET_CLIENT_TransmitHandle *th;
174
175     /**
176      * Closure for all the handlers given by the client
177      */
178   void *cls;
179
180     /**
181      * Messages to send to the service, head.
182      */
183   struct GNUNET_CADET_TransmitHandle *th_head;
184
185     /**
186      * Messages to send to the service, tail.
187      */
188   struct GNUNET_CADET_TransmitHandle *th_tail;
189
190     /**
191      * chid of the next channel to create (to avoid reusing IDs often)
192      */
193   CADET_ChannelNumber next_chid;
194
195     /**
196      * Have we started the task to receive messages from the service
197      * yet? We do this after we send the 'CADET_LOCAL_CONNECT' message.
198      */
199   int in_receive;
200
201   /**
202    * Configuration given by the client, in case of reconnection
203    */
204   const struct GNUNET_CONFIGURATION_Handle *cfg;
205
206   /**
207    * Time to the next reconnect in case one reconnect fails
208    */
209   struct GNUNET_TIME_Relative reconnect_time;
210
211   /**
212    * Task for trying to reconnect.
213    */
214   struct GNUNET_SCHEDULER_Task * reconnect_task;
215
216   /**
217    * Callback for an info task (only one active at a time).
218    */
219   union CadetInfoCB info_cb;
220
221   /**
222    * Info callback closure for @c info_cb.
223    */
224   void *info_cls;
225 };
226
227
228 /**
229  * Description of a peer
230  */
231 struct GNUNET_CADET_Peer
232 {
233     /**
234      * ID of the peer in short form
235      */
236   GNUNET_PEER_Id id;
237
238   /**
239    * Channel this peer belongs to
240    */
241   struct GNUNET_CADET_Channel *t;
242 };
243
244
245 /**
246  * Opaque handle to a channel.
247  */
248 struct GNUNET_CADET_Channel
249 {
250
251     /**
252      * DLL next
253      */
254   struct GNUNET_CADET_Channel *next;
255
256     /**
257      * DLL prev
258      */
259   struct GNUNET_CADET_Channel *prev;
260
261     /**
262      * Handle to the cadet this channel belongs to
263      */
264   struct GNUNET_CADET_Handle *cadet;
265
266     /**
267      * Local ID of the channel
268      */
269   CADET_ChannelNumber chid;
270
271     /**
272      * Port number.
273      */
274   uint32_t port;
275
276     /**
277      * Other end of the channel.
278      */
279   GNUNET_PEER_Id peer;
280
281   /**
282    * Any data the caller wants to put in here
283    */
284   void *ctx;
285
286     /**
287      * Size of packet queued in this channel
288      */
289   unsigned int packet_size;
290
291     /**
292      * Channel options: reliability, etc.
293      */
294   enum GNUNET_CADET_ChannelOption options;
295
296     /**
297      * Are we allowed to send to the service?
298      */
299   int allow_send;
300
301 };
302
303
304 /**
305  * Implementation state for cadet's message queue.
306  */
307 struct CadetMQState
308 {
309   /**
310    * The current transmit handle, or NULL
311    * if no transmit is active.
312    */
313   struct GNUNET_CADET_TransmitHandle *th;
314
315   /**
316    * Channel to send the data over.
317    */
318   struct GNUNET_CADET_Channel *channel;
319 };
320
321
322 /******************************************************************************/
323 /***********************         DECLARATIONS         *************************/
324 /******************************************************************************/
325
326 /**
327  * Function called to send a message to the service.
328  * "buf" will be NULL and "size" zero if the socket was closed for writing in
329  * the meantime.
330  *
331  * @param cls closure, the cadet handle
332  * @param size number of bytes available in buf
333  * @param buf where the callee should write the connect message
334  * @return number of bytes written to buf
335  */
336 static size_t
337 send_callback (void *cls, size_t size, void *buf);
338
339
340 /******************************************************************************/
341 /***********************     AUXILIARY FUNCTIONS      *************************/
342 /******************************************************************************/
343
344 /**
345  * Check if transmission is a payload packet.
346  *
347  * @param th Transmission handle.
348  *
349  * @return #GNUNET_YES if it is a payload packet,
350  *         #GNUNET_NO if it is a cadet management packet.
351  */
352 static int
353 th_is_payload (struct GNUNET_CADET_TransmitHandle *th)
354 {
355   return (th->notify != NULL) ? GNUNET_YES : GNUNET_NO;
356 }
357
358
359 /**
360  * Check whether there is any message ready in the queue and find the size.
361  *
362  * @param h Cadet handle.
363  *
364  * @return The size of the first ready message in the queue, including overhead.
365  *         0 if there is none.
366  */
367 static size_t
368 message_ready_size (struct GNUNET_CADET_Handle *h)
369 {
370   struct GNUNET_CADET_TransmitHandle *th;
371   struct GNUNET_CADET_Channel *ch;
372
373   for (th = h->th_head; NULL != th; th = th->next)
374   {
375     ch = th->channel;
376     if (GNUNET_NO == th_is_payload (th) || GNUNET_YES == ch->allow_send)
377       return th->size;
378   }
379   return 0;
380 }
381
382
383 /**
384  * Get the channel handler for the channel specified by id from the given handle
385  * @param h Cadet handle
386  * @param chid ID of the wanted channel
387  * @return handle to the required channel or NULL if not found
388  */
389 static struct GNUNET_CADET_Channel *
390 retrieve_channel (struct GNUNET_CADET_Handle *h, CADET_ChannelNumber chid)
391 {
392   struct GNUNET_CADET_Channel *ch;
393
394   ch = h->channels_head;
395   while (ch != NULL)
396   {
397     if (ch->chid == chid)
398       return ch;
399     ch = ch->next;
400   }
401   return NULL;
402 }
403
404
405 /**
406  * Create a new channel and insert it in the channel list of the cadet handle
407  *
408  * @param h Cadet handle
409  * @param chid Desired chid of the channel, 0 to assign one automatically.
410  *
411  * @return Handle to the created channel.
412  */
413 static struct GNUNET_CADET_Channel *
414 create_channel (struct GNUNET_CADET_Handle *h, CADET_ChannelNumber chid)
415 {
416   struct GNUNET_CADET_Channel *ch;
417
418   ch = GNUNET_new (struct GNUNET_CADET_Channel);
419   GNUNET_CONTAINER_DLL_insert (h->channels_head, h->channels_tail, ch);
420   ch->cadet = h;
421   if (0 == chid)
422   {
423     ch->chid = h->next_chid;
424     while (NULL != retrieve_channel (h, h->next_chid))
425     {
426       h->next_chid++;
427       h->next_chid &= ~GNUNET_CADET_LOCAL_CHANNEL_ID_SERV;
428       h->next_chid |= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
429     }
430   }
431   else
432   {
433     ch->chid = chid;
434   }
435   ch->allow_send = GNUNET_NO;
436   return ch;
437 }
438
439
440 /**
441  * Destroy the specified channel.
442  * - Destroys all peers, calling the disconnect callback on each if needed
443  * - Cancels all outgoing traffic for that channel, calling respective notifys
444  * - Calls cleaner if channel was inbound
445  * - Frees all memory used
446  *
447  * @param ch Pointer to the channel.
448  * @param call_cleaner Whether to call the cleaner handler.
449  *
450  * @return Handle to the required channel or NULL if not found.
451  */
452 static void
453 destroy_channel (struct GNUNET_CADET_Channel *ch, int call_cleaner)
454 {
455   struct GNUNET_CADET_Handle *h;
456   struct GNUNET_CADET_TransmitHandle *th;
457   struct GNUNET_CADET_TransmitHandle *next;
458
459   LOG (GNUNET_ERROR_TYPE_DEBUG, " destroy_channel %X\n", ch->chid);
460
461   if (NULL == ch)
462   {
463     GNUNET_break (0);
464     return;
465   }
466   h = ch->cadet;
467
468   GNUNET_CONTAINER_DLL_remove (h->channels_head, h->channels_tail, ch);
469
470   /* signal channel destruction */
471   if ( (NULL != h->cleaner) && (0 != ch->peer) && (GNUNET_YES == call_cleaner) )
472   {
473     LOG (GNUNET_ERROR_TYPE_DEBUG, " calling cleaner\n");
474     h->cleaner (h->cls, ch, ch->ctx);
475   }
476
477   /* check that clients did not leave messages behind in the queue */
478   for (th = h->th_head; NULL != th; th = next)
479   {
480     next = th->next;
481     if (th->channel != ch)
482       continue;
483     /* Clients should have aborted their requests already.
484      * Management traffic should be ok, as clients can't cancel that.
485      * If the service crashed and we are reconnecting, it's ok.
486      */
487     GNUNET_break (GNUNET_NO == th_is_payload (th)
488                   || GNUNET_NO == h->in_receive);
489     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
490
491     /* clean up request */
492     if (NULL != th->timeout_task)
493       GNUNET_SCHEDULER_cancel (th->timeout_task);
494     GNUNET_free (th);
495   }
496
497   /* if there are no more pending requests with cadet service, cancel active request */
498   /* Note: this should be unnecessary... */
499   if ((0 == message_ready_size (h)) && (NULL != h->th))
500   {
501     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
502     h->th = NULL;
503   }
504
505   if (0 != ch->peer)
506     GNUNET_PEER_change_rc (ch->peer, -1);
507   GNUNET_free (ch);
508   return;
509 }
510
511
512 /**
513  * Notify client that the transmission has timed out
514  *
515  * @param cls closure
516  * @param tc task context
517  */
518 static void
519 timeout_transmission (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
520 {
521   struct GNUNET_CADET_TransmitHandle *th = cls;
522   struct GNUNET_CADET_Handle *cadet = th->channel->cadet;
523
524   th->timeout_task = NULL;
525   th->channel->packet_size = 0;
526   GNUNET_CONTAINER_DLL_remove (cadet->th_head, cadet->th_tail, th);
527   if (GNUNET_YES == th_is_payload (th))
528     GNUNET_break (0 == th->notify (th->notify_cls, 0, NULL));
529   GNUNET_free (th);
530   if ((0 == message_ready_size (cadet)) && (NULL != cadet->th))
531   {
532     /* nothing ready to transmit, no point in asking for transmission */
533     GNUNET_CLIENT_notify_transmit_ready_cancel (cadet->th);
534     cadet->th = NULL;
535   }
536 }
537
538
539 /**
540  * Add a transmit handle to the transmission queue and set the
541  * timeout if needed.
542  *
543  * @param h cadet handle with the queue head and tail
544  * @param th handle to the packet to be transmitted
545  */
546 static void
547 add_to_queue (struct GNUNET_CADET_Handle *h,
548               struct GNUNET_CADET_TransmitHandle *th)
549 {
550   GNUNET_CONTAINER_DLL_insert_tail (h->th_head, h->th_tail, th);
551   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us == th->timeout.abs_value_us)
552     return;
553   th->timeout_task =
554       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
555                                     (th->timeout), &timeout_transmission, th);
556 }
557
558
559 /**
560  * Auxiliary function to send an already constructed packet to the service.
561  * Takes care of creating a new queue element, copying the message and
562  * calling the tmt_rdy function if necessary.
563  *
564  * @param h cadet handle
565  * @param msg message to transmit
566  * @param channel channel this send is related to (NULL if N/A)
567  */
568 static void
569 send_packet (struct GNUNET_CADET_Handle *h,
570              const struct GNUNET_MessageHeader *msg,
571              struct GNUNET_CADET_Channel *channel);
572
573
574 /**
575  * Send an ack on the channel to confirm the processing of a message.
576  *
577  * @param ch Channel on which to send the ACK.
578  */
579 static void
580 send_ack (struct GNUNET_CADET_Channel *ch)
581 {
582   struct GNUNET_CADET_LocalAck msg;
583
584   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending ACK on channel %X\n", ch->chid);
585   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
586   msg.header.size = htons (sizeof (msg));
587   msg.channel_id = htonl (ch->chid);
588
589   send_packet (ch->cadet, &msg.header, ch);
590   return;
591 }
592
593
594
595 /**
596  * Reconnect callback: tries to reconnect again after a failer previous
597  * reconnecttion
598  * @param cls closure (cadet handle)
599  * @param tc task context
600  */
601 static void
602 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
603
604
605 /**
606  * Send a connect packet to the service with the applications and types
607  * requested by the user.
608  *
609  * @param h The cadet handle.
610  *
611  */
612 static void
613 send_connect (struct GNUNET_CADET_Handle *h)
614 {
615   size_t size;
616
617   size = sizeof (struct GNUNET_CADET_ClientConnect);
618   size += h->n_ports * sizeof (uint32_t);
619   {
620     char buf[size] GNUNET_ALIGN;
621     struct GNUNET_CADET_ClientConnect *msg;
622     uint32_t *ports;
623     uint16_t i;
624
625     /* build connection packet */
626     msg = (struct GNUNET_CADET_ClientConnect *) buf;
627     msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_CONNECT);
628     msg->header.size = htons (size);
629     ports = (uint32_t *) &msg[1];
630     for (i = 0; i < h->n_ports; i++)
631     {
632       ports[i] = htonl (h->ports[i]);
633       LOG (GNUNET_ERROR_TYPE_DEBUG, " port %u\n",
634            h->ports[i]);
635     }
636     LOG (GNUNET_ERROR_TYPE_DEBUG,
637          "Sending %lu bytes long message with %u ports\n",
638          ntohs (msg->header.size), h->n_ports);
639     send_packet (h, &msg->header, NULL);
640   }
641 }
642
643
644 /**
645  * Reconnect to the service, retransmit all infomation to try to restore the
646  * original state.
647  *
648  * @param h handle to the cadet
649  *
650  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
651  */
652 static int
653 do_reconnect (struct GNUNET_CADET_Handle *h)
654 {
655   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
656   LOG (GNUNET_ERROR_TYPE_DEBUG, "*******   RECONNECT   *******\n");
657   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
658   LOG (GNUNET_ERROR_TYPE_DEBUG, "******** on %p *******\n", h);
659   LOG (GNUNET_ERROR_TYPE_DEBUG, "*****************************\n");
660
661   /* disconnect */
662   if (NULL != h->th)
663   {
664     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
665     h->th = NULL;
666   }
667   if (NULL != h->client)
668   {
669     GNUNET_CLIENT_disconnect (h->client);
670   }
671
672   /* connect again */
673   h->client = GNUNET_CLIENT_connect ("cadet", h->cfg);
674   if (h->client == NULL)
675   {
676     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
677                                                       &reconnect_cbk, h);
678     h->reconnect_time =
679         GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS,
680                                   GNUNET_TIME_relative_multiply
681                                   (h->reconnect_time, 2));
682     LOG (GNUNET_ERROR_TYPE_DEBUG, "Next retry in %s\n",
683          GNUNET_STRINGS_relative_time_to_string (h->reconnect_time,
684                                                  GNUNET_NO));
685     GNUNET_break (0);
686     return GNUNET_NO;
687   }
688   else
689   {
690     h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
691   }
692   send_connect (h);
693   return GNUNET_YES;
694 }
695
696 /**
697  * Reconnect callback: tries to reconnect again after a failer previous
698  * reconnecttion
699  * @param cls closure (cadet handle)
700  * @param tc task context
701  */
702 static void
703 reconnect_cbk (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
704 {
705   struct GNUNET_CADET_Handle *h = cls;
706
707   h->reconnect_task = NULL;
708   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
709     return;
710   do_reconnect (h);
711 }
712
713
714 /**
715  * Reconnect to the service, retransmit all infomation to try to restore the
716  * original state.
717  *
718  * @param h handle to the cadet
719  *
720  * @return GNUNET_YES in case of sucess, GNUNET_NO otherwise (service down...)
721  */
722 static void
723 reconnect (struct GNUNET_CADET_Handle *h)
724 {
725   struct GNUNET_CADET_Channel *ch;
726
727   LOG (GNUNET_ERROR_TYPE_DEBUG,
728        "Requested RECONNECT, destroying all channels\n");
729   h->in_receive = GNUNET_NO;
730   for (ch = h->channels_head; NULL != ch; ch = h->channels_head)
731     destroy_channel (ch, GNUNET_YES);
732   if (NULL == h->reconnect_task)
733     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
734                                                       &reconnect_cbk, h);
735 }
736
737
738 /******************************************************************************/
739 /***********************      RECEIVE HANDLERS     ****************************/
740 /******************************************************************************/
741
742 /**
743  * Process the new channel notification and add it to the channels in the handle
744  *
745  * @param h     The cadet handle
746  * @param msg   A message with the details of the new incoming channel
747  */
748 static void
749 process_channel_created (struct GNUNET_CADET_Handle *h,
750                          const struct GNUNET_CADET_ChannelMessage *msg)
751 {
752   struct GNUNET_CADET_Channel *ch;
753   CADET_ChannelNumber chid;
754   uint32_t port;
755
756   chid = ntohl (msg->channel_id);
757   port = ntohl (msg->port);
758   LOG (GNUNET_ERROR_TYPE_DEBUG, "Creating incoming channel %X:%u\n", chid, port);
759   if (chid < GNUNET_CADET_LOCAL_CHANNEL_ID_SERV)
760   {
761     GNUNET_break (0);
762     return;
763   }
764   if (NULL != h->new_channel)
765   {
766     void *ctx;
767
768     ch = create_channel (h, chid);
769     ch->allow_send = GNUNET_NO;
770     ch->peer = GNUNET_PEER_intern (&msg->peer);
771     ch->cadet = h;
772     ch->chid = chid;
773     ch->port = port;
774     ch->options = ntohl (msg->opt);
775
776     LOG (GNUNET_ERROR_TYPE_DEBUG, "  created channel %p\n", ch);
777     ctx = h->new_channel (h->cls, ch, &msg->peer, ch->port, ch->options);
778     if (NULL != ctx)
779       ch->ctx = ctx;
780     LOG (GNUNET_ERROR_TYPE_DEBUG, "User notified\n");
781   }
782   else
783   {
784     struct GNUNET_CADET_ChannelMessage d_msg;
785
786     LOG (GNUNET_ERROR_TYPE_DEBUG, "No handler for incoming channels\n");
787
788     d_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
789     d_msg.header.size = htons (sizeof (struct GNUNET_CADET_ChannelMessage));
790     d_msg.channel_id = msg->channel_id;
791     memset (&d_msg.peer, 0, sizeof (struct GNUNET_PeerIdentity));
792     d_msg.port = 0;
793     d_msg.opt = 0;
794
795     send_packet (h, &d_msg.header, NULL);
796   }
797   return;
798 }
799
800
801 /**
802  * Process the channel destroy notification and free associated resources
803  *
804  * @param h     The cadet handle
805  * @param msg   A message with the details of the channel being destroyed
806  */
807 static void
808 process_channel_destroy (struct GNUNET_CADET_Handle *h,
809                          const struct GNUNET_CADET_ChannelMessage *msg)
810 {
811   struct GNUNET_CADET_Channel *ch;
812   CADET_ChannelNumber chid;
813
814   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel Destroy received from service\n");
815   chid = ntohl (msg->channel_id);
816   ch = retrieve_channel (h, chid);
817
818   if (NULL == ch)
819   {
820     LOG (GNUNET_ERROR_TYPE_DEBUG, "channel %X unknown\n", chid);
821     return;
822   }
823   LOG (GNUNET_ERROR_TYPE_DEBUG, " destroying channel %X\n", ch->chid);
824   destroy_channel (ch, GNUNET_YES);
825 }
826
827
828 /**
829  * Process the incoming data packets, call appropriate handlers.
830  *
831  * @param h         The cadet handle
832  * @param message   A message encapsulating the data
833  */
834 static void
835 process_incoming_data (struct GNUNET_CADET_Handle *h,
836                        const struct GNUNET_MessageHeader *message)
837 {
838   const struct GNUNET_MessageHeader *payload;
839   const struct GNUNET_CADET_MessageHandler *handler;
840   struct GNUNET_CADET_LocalData *dmsg;
841   struct GNUNET_CADET_Channel *ch;
842   size_t size;
843   unsigned int i;
844   uint16_t type;
845
846   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a data message!\n");
847   dmsg = (struct GNUNET_CADET_LocalData *) message;
848   ch = retrieve_channel (h, ntohl (dmsg->id));
849   if (NULL == ch)
850   {
851     GNUNET_break (0);
852     return;
853   }
854
855   payload = (struct GNUNET_MessageHeader *) &dmsg[1];
856   LOG (GNUNET_ERROR_TYPE_DEBUG, "  %s data on channel %s [%X]\n",
857        GC_f2s (ch->chid >= GNUNET_CADET_LOCAL_CHANNEL_ID_SERV),
858        GNUNET_i2s (GNUNET_PEER_resolve2 (ch->peer)), ntohl (dmsg->id));
859
860   size = ntohs (message->size);
861   LOG (GNUNET_ERROR_TYPE_DEBUG, "  %u bytes\n", size);
862
863   type = ntohs (payload->type);
864   size = ntohs (payload->size);
865   LOG (GNUNET_ERROR_TYPE_DEBUG, "  payload type %s\n", GC_m2s (type));
866   for (i = 0; i < h->n_handlers; i++)
867   {
868     handler = &h->message_handlers[i];
869     LOG (GNUNET_ERROR_TYPE_DEBUG, "    checking handler for type %u\n",
870          handler->type);
871     if (handler->type == type)
872     {
873       if (GNUNET_OK !=
874           handler->callback (h->cls, ch, &ch->ctx, payload))
875       {
876         LOG (GNUNET_ERROR_TYPE_DEBUG, "callback caused disconnection\n");
877         GNUNET_CADET_channel_destroy (ch);
878         return;
879       }
880       else
881       {
882         LOG (GNUNET_ERROR_TYPE_DEBUG,
883              "callback completed successfully\n");
884         return;
885       }
886     }
887   }
888 }
889
890
891 /**
892  * Process a local ACK message, enabling the client to send
893  * more data to the service.
894  *
895  * @param h Cadet handle.
896  * @param message Message itself.
897  */
898 static void
899 process_ack (struct GNUNET_CADET_Handle *h,
900              const struct GNUNET_MessageHeader *message)
901 {
902   struct GNUNET_CADET_LocalAck *msg;
903   struct GNUNET_CADET_Channel *ch;
904   CADET_ChannelNumber chid;
905
906   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got an ACK!\n");
907   msg = (struct GNUNET_CADET_LocalAck *) message;
908   chid = ntohl (msg->channel_id);
909   ch = retrieve_channel (h, chid);
910   if (NULL == ch)
911   {
912     LOG (GNUNET_ERROR_TYPE_DEBUG, "ACK on unknown channel %X\n", chid);
913     return;
914   }
915   LOG (GNUNET_ERROR_TYPE_DEBUG, "  on channel %X!\n", ch->chid);
916   ch->allow_send = GNUNET_YES;
917   if (NULL == h->th && 0 < ch->packet_size)
918   {
919     LOG (GNUNET_ERROR_TYPE_DEBUG, "  tmt rdy was NULL, requesting!\n");
920     h->th = GNUNET_CLIENT_notify_transmit_ready (h->client, ch->packet_size,
921                                                  GNUNET_TIME_UNIT_FOREVER_REL,
922                                                  GNUNET_YES, &send_callback, h);
923   }
924 }
925
926
927 /*
928  * Process a local reply about info on all channels, pass info to the user.
929  *
930  * @param h Cadet handle.
931  * @param message Message itself.
932  */
933 // static void
934 // process_get_channels (struct GNUNET_CADET_Handle *h,
935 //                      const struct GNUNET_MessageHeader *message)
936 // {
937 //   struct GNUNET_CADET_LocalInfo *msg;
938 //
939 //   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Get Channels messasge received\n");
940 //
941 //   if (NULL == h->channels_cb)
942 //   {
943 //     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  ignored\n");
944 //     return;
945 //   }
946 //
947 //   msg = (struct GNUNET_CADET_LocalInfo *) message;
948 //   if (ntohs (message->size) !=
949 //       (sizeof (struct GNUNET_CADET_LocalInfo) +
950 //        sizeof (struct GNUNET_PeerIdentity)))
951 //   {
952 //     GNUNET_break_op (0);
953 //     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
954 //                 "Get channels message: size %hu - expected %u\n",
955 //                 ntohs (message->size),
956 //                 sizeof (struct GNUNET_CADET_LocalInfo));
957 //     return;
958 //   }
959 //   h->channels_cb (h->channels_cls,
960 //                   ntohl (msg->channel_id),
961 //                   &msg->owner,
962 //                   &msg->destination);
963 // }
964
965
966
967 /*
968  * Process a local monitor_channel reply, pass info to the user.
969  *
970  * @param h Cadet handle.
971  * @param message Message itself.
972  */
973 // static void
974 // process_show_channel (struct GNUNET_CADET_Handle *h,
975 //                      const struct GNUNET_MessageHeader *message)
976 // {
977 //   struct GNUNET_CADET_LocalInfo *msg;
978 //   size_t esize;
979 //
980 //   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Show Channel messasge received\n");
981 //
982 //   if (NULL == h->channel_cb)
983 //   {
984 //     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  ignored\n");
985 //     return;
986 //   }
987 //
988 //   /* Verify message sanity */
989 //   msg = (struct GNUNET_CADET_LocalInfo *) message;
990 //   esize = sizeof (struct GNUNET_CADET_LocalInfo);
991 //   if (ntohs (message->size) != esize)
992 //   {
993 //     GNUNET_break_op (0);
994 //     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
995 //                 "Show channel message: size %hu - expected %u\n",
996 //                 ntohs (message->size),
997 //                 esize);
998 //
999 //     h->channel_cb (h->channel_cls, NULL, NULL);
1000 //     h->channel_cb = NULL;
1001 //     h->channel_cls = NULL;
1002 //
1003 //     return;
1004 //   }
1005 //
1006 //   h->channel_cb (h->channel_cls,
1007 //                  &msg->destination,
1008 //                  &msg->owner);
1009 // }
1010
1011
1012
1013 /**
1014  * Process a local reply about info on all tunnels, pass info to the user.
1015  *
1016  * @param h Cadet handle.
1017  * @param message Message itself.
1018  */
1019 static void
1020 process_get_peers (struct GNUNET_CADET_Handle *h,
1021                      const struct GNUNET_MessageHeader *message)
1022 {
1023   struct GNUNET_CADET_LocalInfoPeer *msg;
1024   uint16_t size;
1025
1026   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Get Peer messasge received\n");
1027
1028   if (NULL == h->info_cb.peers_cb)
1029   {
1030     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ignored\n");
1031     return;
1032   }
1033
1034   size = ntohs (message->size);
1035   if (sizeof (struct GNUNET_CADET_LocalInfoPeer) > size)
1036   {
1037     h->info_cb.peers_cb (h->info_cls, NULL, -1, 0, 0);
1038     h->info_cb.peers_cb = NULL;
1039     h->info_cls = NULL;
1040     return;
1041   }
1042
1043   msg = (struct GNUNET_CADET_LocalInfoPeer *) message;
1044   h->info_cb.peers_cb (h->info_cls, &msg->destination,
1045                        (int) ntohs (msg->tunnel),
1046                        (unsigned int ) ntohs (msg->paths),
1047                        0);
1048 }
1049
1050
1051 /**
1052  * Process a local peer info reply, pass info to the user.
1053  *
1054  * @param h Cadet handle.
1055  * @param message Message itself.
1056  */
1057 static void
1058 process_get_peer (struct GNUNET_CADET_Handle *h,
1059                   const struct GNUNET_MessageHeader *message)
1060 {
1061   struct GNUNET_CADET_LocalInfoTunnel *msg;
1062   size_t esize;
1063   size_t msize;
1064
1065   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Get Tunnel messasge received\n");
1066   if (NULL == h->info_cb.peer_cb)
1067   {
1068     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ignored\n");
1069     return;
1070   }
1071
1072   /* Verify message sanity */
1073   msg = (struct GNUNET_CADET_LocalInfoTunnel *) message;
1074   msize = ntohs (message->size);
1075   esize = sizeof (struct GNUNET_CADET_LocalInfoPeer);
1076   if (esize > msize)
1077   {
1078     GNUNET_break_op (0);
1079     h->info_cb.peer_cb (h->info_cls, NULL, 0, 0, 0, NULL);
1080     goto clean_cls;
1081   }
1082 //   esize += ch_n * sizeof (CADET_ChannelNumber);
1083 //   esize += c_n * sizeof (struct GNUNET_CADET_Hash);
1084   if (msize != esize)
1085   {
1086     GNUNET_break_op (0);
1087     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "m:%u, e: %u\n", msize, esize);
1088     h->info_cb.peer_cb (h->info_cls, NULL, 0, 0, 0, NULL);
1089     goto clean_cls;
1090   }
1091
1092   /* Call Callback with tunnel info. */
1093   h->info_cb.peer_cb (h->info_cls, &msg->destination, 0, 0, 0, NULL);
1094
1095   clean_cls:
1096   h->info_cb.peer_cb = NULL;
1097   h->info_cls = NULL;
1098 }
1099
1100
1101 /**
1102  * Process a local reply about info on all tunnels, pass info to the user.
1103  *
1104  * @param h Cadet handle.
1105  * @param message Message itself.
1106  */
1107 static void
1108 process_get_tunnels (struct GNUNET_CADET_Handle *h,
1109                      const struct GNUNET_MessageHeader *message)
1110 {
1111   struct GNUNET_CADET_LocalInfoTunnel *msg;
1112   uint16_t size;
1113
1114   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Get Tunnels messasge received\n");
1115
1116   if (NULL == h->info_cb.tunnels_cb)
1117   {
1118     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ignored\n");
1119     return;
1120   }
1121
1122   size = ntohs (message->size);
1123   if (sizeof (struct GNUNET_CADET_LocalInfoTunnel) > size)
1124   {
1125     h->info_cb.tunnels_cb (h->info_cls, NULL, 0, 0, 0, 0);
1126     h->info_cb.tunnels_cb = NULL;
1127     h->info_cls = NULL;
1128     return;
1129   }
1130
1131   msg = (struct GNUNET_CADET_LocalInfoTunnel *) message;
1132   h->info_cb.tunnels_cb (h->info_cls, &msg->destination,
1133                          ntohl (msg->channels), ntohl (msg->connections),
1134                          ntohs (msg->estate), ntohs (msg->cstate));
1135
1136 }
1137
1138
1139 /**
1140  * Process a local tunnel info reply, pass info to the user.
1141  *
1142  * @param h Cadet handle.
1143  * @param message Message itself.
1144  */
1145 static void
1146 process_get_tunnel (struct GNUNET_CADET_Handle *h,
1147                     const struct GNUNET_MessageHeader *message)
1148 {
1149   struct GNUNET_CADET_LocalInfoTunnel *msg;
1150   size_t esize;
1151   size_t msize;
1152   unsigned int ch_n;
1153   unsigned int c_n;
1154   struct GNUNET_CADET_Hash *conns;
1155   CADET_ChannelNumber *chns;
1156
1157   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Get Tunnel messasge received\n");
1158   if (NULL == h->info_cb.tunnel_cb)
1159   {
1160     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "  ignored\n");
1161     return;
1162   }
1163
1164   /* Verify message sanity */
1165   msg = (struct GNUNET_CADET_LocalInfoTunnel *) message;
1166   msize = ntohs (message->size);
1167   esize = sizeof (struct GNUNET_CADET_LocalInfoTunnel);
1168   if (esize > msize)
1169   {
1170     GNUNET_break_op (0);
1171     h->info_cb.tunnel_cb (h->info_cls, NULL, 0, 0, NULL, NULL, 0, 0);
1172     goto clean_cls;
1173   }
1174   ch_n = ntohl (msg->channels);
1175   c_n = ntohl (msg->connections);
1176   esize += ch_n * sizeof (CADET_ChannelNumber);
1177   esize += c_n * sizeof (struct GNUNET_CADET_Hash);
1178   if (msize != esize)
1179   {
1180     GNUNET_break_op (0);
1181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "m:%u, e: %u (%u ch, %u conn)\n",
1182                 msize, esize, ch_n, c_n);
1183     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%u (%u ch, %u conn)\n",
1184                 sizeof (struct GNUNET_CADET_LocalInfoTunnel),
1185                 sizeof (CADET_ChannelNumber), sizeof (struct GNUNET_HashCode));
1186     h->info_cb.tunnel_cb (h->info_cls, NULL, 0, 0, NULL, NULL, 0, 0);
1187     goto clean_cls;
1188   }
1189
1190   /* Call Callback with tunnel info. */
1191   conns = (struct GNUNET_CADET_Hash *) &msg[1];
1192   chns = (CADET_ChannelNumber *) &conns[c_n];
1193   h->info_cb.tunnel_cb (h->info_cls, &msg->destination,
1194                 ch_n, c_n, chns, conns,
1195                 ntohs (msg->estate), ntohs (msg->cstate));
1196
1197 clean_cls:
1198   h->info_cb.tunnel_cb = NULL;
1199   h->info_cls = NULL;
1200 }
1201
1202
1203 /**
1204  * Function to process all messages received from the service
1205  *
1206  * @param cls closure
1207  * @param msg message received, NULL on timeout or fatal error
1208  */
1209 static void
1210 msg_received (void *cls, const struct GNUNET_MessageHeader *msg)
1211 {
1212   struct GNUNET_CADET_Handle *h = cls;
1213   uint16_t type;
1214
1215   if (msg == NULL)
1216   {
1217     LOG (GNUNET_ERROR_TYPE_DEBUG,
1218          "Cadet service disconnected, reconnecting\n", h);
1219     reconnect (h);
1220     return;
1221   }
1222   type = ntohs (msg->type);
1223   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1224   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a message: %s\n",
1225        GC_m2s (type));
1226   switch (type)
1227   {
1228     /* Notify of a new incoming channel */
1229   case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1230     process_channel_created (h, (struct GNUNET_CADET_ChannelMessage *) msg);
1231     break;
1232     /* Notify of a channel disconnection */
1233   case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY: /* TODO separate(gid problem)*/
1234   case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1235     process_channel_destroy (h, (struct GNUNET_CADET_ChannelMessage *) msg);
1236     break;
1237   case GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA:
1238     process_incoming_data (h, msg);
1239     break;
1240   case GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK:
1241     process_ack (h, msg);
1242     break;
1243 //   case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNELS:
1244 //     process_get_channels (h, msg);
1245 //     break;
1246 //   case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL:
1247 //     process_show_channel (h, msg);
1248 //     break;
1249   case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS:
1250     process_get_peers (h, msg);
1251     break;
1252   case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER:
1253     process_get_peer (h, msg);
1254     break;
1255   case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS:
1256     process_get_tunnels (h, msg);
1257     break;
1258   case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL:
1259     process_get_tunnel (h, msg);
1260     break;
1261 //   case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL:
1262 //     process_show_channel (h, msg);
1263 //     break;
1264   default:
1265     /* We shouldn't get any other packages, log and ignore */
1266     LOG (GNUNET_ERROR_TYPE_WARNING,
1267          "unsolicited message form service (type %s)\n",
1268          GC_m2s (ntohs (msg->type)));
1269   }
1270   LOG (GNUNET_ERROR_TYPE_DEBUG, "message processed\n");
1271   if (GNUNET_YES == h->in_receive)
1272   {
1273     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1274                            GNUNET_TIME_UNIT_FOREVER_REL);
1275   }
1276   else
1277   {
1278     LOG (GNUNET_ERROR_TYPE_DEBUG,
1279          "in receive off, not calling CLIENT_receive\n");
1280   }
1281 }
1282
1283
1284 /******************************************************************************/
1285 /************************       SEND FUNCTIONS     ****************************/
1286 /******************************************************************************/
1287
1288 /**
1289  * Function called to send a message to the service.
1290  * "buf" will be NULL and "size" zero if the socket was closed for writing in
1291  * the meantime.
1292  *
1293  * @param cls closure, the cadet handle
1294  * @param size number of bytes available in buf
1295  * @param buf where the callee should write the connect message
1296  * @return number of bytes written to buf
1297  */
1298 static size_t
1299 send_callback (void *cls, size_t size, void *buf)
1300 {
1301   struct GNUNET_CADET_Handle *h = cls;
1302   struct GNUNET_CADET_TransmitHandle *th;
1303   struct GNUNET_CADET_TransmitHandle *next;
1304   struct GNUNET_CADET_Channel *ch;
1305   char *cbuf = buf;
1306   size_t tsize;
1307   size_t psize;
1308   size_t nsize;
1309
1310   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1311   LOG (GNUNET_ERROR_TYPE_DEBUG, "# Send callback, buffer %u\n", size);
1312   if ((0 == size) || (NULL == buf))
1313   {
1314     LOG (GNUNET_ERROR_TYPE_DEBUG, "# Received NULL send callback on %p\n", h);
1315     reconnect (h);
1316     h->th = NULL;
1317     return 0;
1318   }
1319   tsize = 0;
1320   next = h->th_head;
1321   nsize = message_ready_size (h);
1322   while ((NULL != (th = next)) && (0 < nsize) && (size >= nsize))
1323   {
1324     ch = th->channel;
1325     if (GNUNET_YES == th_is_payload (th))
1326     {
1327       struct GNUNET_CADET_LocalData *dmsg;
1328       struct GNUNET_MessageHeader *mh;
1329
1330       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  payload, %u bytes on %X (%p)\n",
1331            th->size, ch->chid, ch);
1332       if (GNUNET_NO == ch->allow_send)
1333       {
1334         /* This channel is not ready to transmit yet, Try the next message */
1335         next = th->next;
1336         continue;
1337       }
1338       ch->packet_size = 0;
1339       GNUNET_assert (size >= th->size);
1340       dmsg = (struct GNUNET_CADET_LocalData *) cbuf;
1341       mh = (struct GNUNET_MessageHeader *) &dmsg[1];
1342       psize = th->notify (th->notify_cls, size - DATA_OVERHEAD, mh);
1343
1344       if (psize > 0)
1345       {
1346         GNUNET_assert (sizeof (struct GNUNET_MessageHeader) <= psize);
1347         psize += DATA_OVERHEAD;
1348         GNUNET_assert (size >= psize);
1349         dmsg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA);
1350         dmsg->header.size = htons (psize);
1351         dmsg->id = htonl (ch->chid);
1352         LOG (GNUNET_ERROR_TYPE_DEBUG, "#  sending, type %s\n",
1353              GC_m2s (ntohs (mh->type)));
1354         ch->allow_send = GNUNET_NO;
1355       }
1356       else
1357       {
1358         LOG (GNUNET_ERROR_TYPE_DEBUG,
1359              "#  callback returned size 0, "
1360              "application canceled transmission\n");
1361       }
1362     }
1363     else
1364     {
1365       const struct GNUNET_MessageHeader *mh;
1366
1367       mh = (const struct GNUNET_MessageHeader *) &th[1];
1368       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  cadet internal traffic, type %s\n",
1369            GC_m2s (ntohs (mh->type)));
1370       memcpy (cbuf, &th[1], th->size);
1371       psize = th->size;
1372     }
1373     GNUNET_assert (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE >= psize);
1374     if (th->timeout_task != NULL)
1375       GNUNET_SCHEDULER_cancel (th->timeout_task);
1376     next = th->next;
1377     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
1378     GNUNET_free (th);
1379     nsize = message_ready_size (h);
1380     cbuf += psize;
1381     size -= psize;
1382     tsize += psize;
1383   }
1384   LOG (GNUNET_ERROR_TYPE_DEBUG, "#  total size: %u\n", tsize);
1385   h->th = NULL;
1386   size = message_ready_size (h);
1387   if (0 != size)
1388   {
1389     LOG (GNUNET_ERROR_TYPE_DEBUG, "#  next size: %u\n", size);
1390     h->th =
1391         GNUNET_CLIENT_notify_transmit_ready (h->client, size,
1392                                              GNUNET_TIME_UNIT_FOREVER_REL,
1393                                              GNUNET_YES, &send_callback, h);
1394   }
1395   else
1396   {
1397     if (NULL != h->th_head)
1398       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  nothing ready to transmit\n");
1399     else
1400       LOG (GNUNET_ERROR_TYPE_DEBUG, "#  nothing left to transmit\n");
1401   }
1402   if (GNUNET_NO == h->in_receive)
1403   {
1404     LOG (GNUNET_ERROR_TYPE_DEBUG, "# start receiving from service\n");
1405     h->in_receive = GNUNET_YES;
1406     GNUNET_CLIENT_receive (h->client, &msg_received, h,
1407                            GNUNET_TIME_UNIT_FOREVER_REL);
1408   }
1409   LOG (GNUNET_ERROR_TYPE_DEBUG, "# Send callback() END\n");
1410   return tsize;
1411 }
1412
1413
1414 /**
1415  * Auxiliary function to send an already constructed packet to the service.
1416  * Takes care of creating a new queue element, copying the message and
1417  * calling the tmt_rdy function if necessary.
1418  *
1419  * @param h cadet handle
1420  * @param msg message to transmit
1421  * @param channel channel this send is related to (NULL if N/A)
1422  */
1423 static void
1424 send_packet (struct GNUNET_CADET_Handle *h,
1425              const struct GNUNET_MessageHeader *msg,
1426              struct GNUNET_CADET_Channel *channel)
1427 {
1428   struct GNUNET_CADET_TransmitHandle *th;
1429   size_t msize;
1430
1431   LOG (GNUNET_ERROR_TYPE_DEBUG, " Sending message to service: %s\n",
1432        GC_m2s(ntohs(msg->type)));
1433   msize = ntohs (msg->size);
1434   th = GNUNET_malloc (sizeof (struct GNUNET_CADET_TransmitHandle) + msize);
1435   th->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1436   th->size = msize;
1437   th->channel = channel;
1438   memcpy (&th[1], msg, msize);
1439   add_to_queue (h, th);
1440   if (NULL != h->th)
1441     return;
1442   LOG (GNUNET_ERROR_TYPE_DEBUG, "  calling ntfy tmt rdy for %u bytes\n", msize);
1443   h->th =
1444       GNUNET_CLIENT_notify_transmit_ready (h->client, msize,
1445                                            GNUNET_TIME_UNIT_FOREVER_REL,
1446                                            GNUNET_YES, &send_callback, h);
1447 }
1448
1449
1450 /******************************************************************************/
1451 /**********************      API CALL DEFINITIONS     *************************/
1452 /******************************************************************************/
1453
1454 struct GNUNET_CADET_Handle *
1455 GNUNET_CADET_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, void *cls,
1456                      GNUNET_CADET_InboundChannelNotificationHandler new_channel,
1457                      GNUNET_CADET_ChannelEndHandler cleaner,
1458                      const struct GNUNET_CADET_MessageHandler *handlers,
1459                      const uint32_t *ports)
1460 {
1461   struct GNUNET_CADET_Handle *h;
1462
1463   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_CADET_connect()\n");
1464   h = GNUNET_new (struct GNUNET_CADET_Handle);
1465   LOG (GNUNET_ERROR_TYPE_DEBUG, " addr %p\n", h);
1466   h->cfg = cfg;
1467   h->new_channel = new_channel;
1468   h->cleaner = cleaner;
1469   h->client = GNUNET_CLIENT_connect ("cadet", cfg);
1470   if (h->client == NULL)
1471   {
1472     GNUNET_break (0);
1473     GNUNET_free (h);
1474     return NULL;
1475   }
1476   h->cls = cls;
1477   h->message_handlers = handlers;
1478   h->ports = ports;
1479   h->next_chid = GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
1480   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1481   h->reconnect_task = NULL;
1482
1483   if (NULL != ports && ports[0] != 0 && NULL == new_channel)
1484   {
1485     GNUNET_break (0);
1486     LOG (GNUNET_ERROR_TYPE_DEBUG,
1487          "no new channel handler given, ports parameter is useless!!\n");
1488   }
1489   if ((NULL == ports || ports[0] == 0) && NULL != new_channel)
1490   {
1491     GNUNET_break (0);
1492     LOG (GNUNET_ERROR_TYPE_DEBUG,
1493          "no ports given, new channel handler will never be called!!\n");
1494   }
1495   /* count handlers */
1496   for (h->n_handlers = 0;
1497        handlers && handlers[h->n_handlers].type;
1498        h->n_handlers++) ;
1499   for (h->n_ports = 0;
1500        ports && ports[h->n_ports];
1501        h->n_ports++) ;
1502   send_connect (h);
1503   LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_CADET_connect() END\n");
1504   return h;
1505 }
1506
1507
1508 void
1509 GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle)
1510 {
1511   struct GNUNET_CADET_Channel *ch;
1512   struct GNUNET_CADET_Channel *aux;
1513   struct GNUNET_CADET_TransmitHandle *th;
1514
1515   LOG (GNUNET_ERROR_TYPE_DEBUG, "CADET DISCONNECT\n");
1516
1517   ch = handle->channels_head;
1518   while (NULL != ch)
1519   {
1520     aux = ch->next;
1521     if (ch->chid < GNUNET_CADET_LOCAL_CHANNEL_ID_SERV)
1522     {
1523       GNUNET_break (0);
1524       LOG (GNUNET_ERROR_TYPE_DEBUG, "channel %X not destroyed\n", ch->chid);
1525     }
1526     destroy_channel (ch, GNUNET_YES);
1527     ch = aux;
1528   }
1529   while ( (th = handle->th_head) != NULL)
1530   {
1531     struct GNUNET_MessageHeader *msg;
1532
1533     /* Make sure it is an allowed packet (everything else should have been
1534      * already canceled).
1535      */
1536     GNUNET_break (GNUNET_NO == th_is_payload (th));
1537     msg = (struct GNUNET_MessageHeader *) &th[1];
1538     switch (ntohs(msg->type))
1539     {
1540       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_CONNECT:
1541       case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1542       case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1543       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNELS:
1544       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL:
1545       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER:
1546       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS:
1547       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL:
1548       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS:
1549         break;
1550       default:
1551         GNUNET_break (0);
1552         LOG (GNUNET_ERROR_TYPE_ERROR, "unexpected msg %u\n",
1553              ntohs(msg->type));
1554     }
1555
1556     GNUNET_CONTAINER_DLL_remove (handle->th_head, handle->th_tail, th);
1557     GNUNET_free (th);
1558   }
1559
1560   if (NULL != handle->th)
1561   {
1562     GNUNET_CLIENT_notify_transmit_ready_cancel (handle->th);
1563     handle->th = NULL;
1564   }
1565   if (NULL != handle->client)
1566   {
1567     GNUNET_CLIENT_disconnect (handle->client);
1568     handle->client = NULL;
1569   }
1570   if (NULL != handle->reconnect_task)
1571   {
1572     GNUNET_SCHEDULER_cancel(handle->reconnect_task);
1573     handle->reconnect_task = NULL;
1574   }
1575   GNUNET_free (handle);
1576 }
1577
1578
1579 /**
1580  * Create a new channel towards a remote peer.
1581  *
1582  * If the destination port is not open by any peer or the destination peer
1583  * does not accept the channel, #GNUNET_CADET_ChannelEndHandler will be called
1584  * for this channel.
1585  *
1586  * @param h cadet handle
1587  * @param channel_ctx client's channel context to associate with the channel
1588  * @param peer peer identity the channel should go to
1589  * @param port Port number.
1590  * @param options CadetOption flag field, with all desired option bits set to 1.
1591  *
1592  * @return handle to the channel
1593  */
1594 struct GNUNET_CADET_Channel *
1595 GNUNET_CADET_channel_create (struct GNUNET_CADET_Handle *h,
1596                             void *channel_ctx,
1597                             const struct GNUNET_PeerIdentity *peer,
1598                             uint32_t port,
1599                             enum GNUNET_CADET_ChannelOption options)
1600 {
1601   struct GNUNET_CADET_Channel *ch;
1602   struct GNUNET_CADET_ChannelMessage msg;
1603
1604   LOG (GNUNET_ERROR_TYPE_DEBUG,
1605        "Creating new channel to %s:%u\n",
1606        GNUNET_i2s (peer), port);
1607   ch = create_channel (h, 0);
1608   LOG (GNUNET_ERROR_TYPE_DEBUG, "  at %p\n", ch);
1609   LOG (GNUNET_ERROR_TYPE_DEBUG, "  number %X\n", ch->chid);
1610   ch->ctx = channel_ctx;
1611   ch->peer = GNUNET_PEER_intern (peer);
1612   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE);
1613   msg.header.size = htons (sizeof (struct GNUNET_CADET_ChannelMessage));
1614   msg.channel_id = htonl (ch->chid);
1615   msg.port = htonl (port);
1616   msg.peer = *peer;
1617   msg.opt = htonl (options);
1618   ch->allow_send = GNUNET_NO;
1619   send_packet (h, &msg.header, ch);
1620   return ch;
1621 }
1622
1623
1624 void
1625 GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel)
1626 {
1627   struct GNUNET_CADET_Handle *h;
1628   struct GNUNET_CADET_ChannelMessage msg;
1629   struct GNUNET_CADET_TransmitHandle *th;
1630
1631   LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying channel\n");
1632   h = channel->cadet;
1633
1634   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1635   msg.header.size = htons (sizeof (struct GNUNET_CADET_ChannelMessage));
1636   msg.channel_id = htonl (channel->chid);
1637   memset (&msg.peer, 0, sizeof (struct GNUNET_PeerIdentity));
1638   msg.port = 0;
1639   msg.opt = 0;
1640   th = h->th_head;
1641   while (th != NULL)
1642   {
1643     struct GNUNET_CADET_TransmitHandle *aux;
1644     if (th->channel == channel)
1645     {
1646       aux = th->next;
1647       if (GNUNET_YES == th_is_payload (th))
1648       {
1649         /* applications should cancel before destroying channel */
1650         GNUNET_break (0);
1651         th->notify (th->notify_cls, 0, NULL);
1652       }
1653       GNUNET_CADET_notify_transmit_ready_cancel (th);
1654       th = aux;
1655     }
1656     else
1657       th = th->next;
1658   }
1659
1660   destroy_channel (channel, GNUNET_YES);
1661   send_packet (h, &msg.header, NULL);
1662 }
1663
1664
1665 /**
1666  * Get information about a channel.
1667  *
1668  * @param channel Channel handle.
1669  * @param option Query (GNUNET_CADET_OPTION_*).
1670  * @param ... dependant on option, currently not used
1671  *
1672  * @return Union with an answer to the query.
1673  */
1674 const union GNUNET_CADET_ChannelInfo *
1675 GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel,
1676                               enum GNUNET_CADET_ChannelOption option, ...)
1677 {
1678   static int bool_flag;
1679   const union GNUNET_CADET_ChannelInfo *ret;
1680
1681   switch (option)
1682   {
1683     case GNUNET_CADET_OPTION_NOBUFFER:
1684     case GNUNET_CADET_OPTION_RELIABLE:
1685     case GNUNET_CADET_OPTION_OOORDER:
1686       if (0 != (option & channel->options))
1687         bool_flag = GNUNET_YES;
1688       else
1689         bool_flag = GNUNET_NO;
1690       ret = (const union GNUNET_CADET_ChannelInfo *) &bool_flag;
1691       break;
1692     case GNUNET_CADET_OPTION_PEER:
1693       ret = (const union GNUNET_CADET_ChannelInfo *) GNUNET_PEER_resolve2 (channel->peer);
1694       break;
1695     default:
1696       GNUNET_break (0);
1697       return NULL;
1698   }
1699
1700   return ret;
1701 }
1702
1703 struct GNUNET_CADET_TransmitHandle *
1704 GNUNET_CADET_notify_transmit_ready (struct GNUNET_CADET_Channel *channel, int cork,
1705                                     struct GNUNET_TIME_Relative maxdelay,
1706                                     size_t notify_size,
1707                                     GNUNET_CONNECTION_TransmitReadyNotify notify,
1708                                     void *notify_cls)
1709 {
1710   struct GNUNET_CADET_TransmitHandle *th;
1711
1712   GNUNET_assert (NULL != channel);
1713   GNUNET_assert (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE >= notify_size);
1714   LOG (GNUNET_ERROR_TYPE_DEBUG, "CADET NOTIFY TRANSMIT READY\n");
1715   LOG (GNUNET_ERROR_TYPE_DEBUG, "    on channel %X\n", channel->chid);
1716   LOG (GNUNET_ERROR_TYPE_DEBUG, "    allow_send %d\n", channel->allow_send);
1717   if (channel->chid >= GNUNET_CADET_LOCAL_CHANNEL_ID_SERV)
1718     LOG (GNUNET_ERROR_TYPE_DEBUG, "    to origin\n");
1719   else
1720     LOG (GNUNET_ERROR_TYPE_DEBUG, "    to destination\n");
1721   LOG (GNUNET_ERROR_TYPE_DEBUG, "    payload size %u\n", notify_size);
1722   GNUNET_assert (NULL != notify);
1723   GNUNET_assert (0 == channel->packet_size); // Only one data packet allowed
1724   th = GNUNET_new (struct GNUNET_CADET_TransmitHandle);
1725   th->channel = channel;
1726   th->timeout = GNUNET_TIME_relative_to_absolute (maxdelay);
1727   th->size = notify_size + DATA_OVERHEAD;
1728   channel->packet_size = th->size;
1729   LOG (GNUNET_ERROR_TYPE_DEBUG, "    total size %u\n", th->size);
1730   th->notify = notify;
1731   th->notify_cls = notify_cls;
1732   add_to_queue (channel->cadet, th);
1733   if (NULL != channel->cadet->th)
1734     return th;
1735   if (GNUNET_NO == channel->allow_send)
1736     return th;
1737   LOG (GNUNET_ERROR_TYPE_DEBUG, "    call client notify tmt rdy\n");
1738   channel->cadet->th =
1739       GNUNET_CLIENT_notify_transmit_ready (channel->cadet->client, th->size,
1740                                            GNUNET_TIME_UNIT_FOREVER_REL,
1741                                            GNUNET_YES, &send_callback,
1742                                            channel->cadet);
1743   LOG (GNUNET_ERROR_TYPE_DEBUG, "CADET NOTIFY TRANSMIT READY END\n");
1744   return th;
1745 }
1746
1747
1748 void
1749 GNUNET_CADET_notify_transmit_ready_cancel (struct GNUNET_CADET_TransmitHandle *th)
1750 {
1751   struct GNUNET_CADET_Handle *cadet;
1752
1753   LOG (GNUNET_ERROR_TYPE_DEBUG, "CADET NOTIFY TRANSMIT READY CANCEL\n");
1754   LOG (GNUNET_ERROR_TYPE_DEBUG, "    on channel %X (%p)\n",
1755        th->channel->chid, th->channel);
1756   LOG (GNUNET_ERROR_TYPE_DEBUG, "    size %u bytes\n", th->size);
1757   th->channel->packet_size = 0;
1758   cadet = th->channel->cadet;
1759   if (th->timeout_task != NULL)
1760     GNUNET_SCHEDULER_cancel (th->timeout_task);
1761   GNUNET_CONTAINER_DLL_remove (cadet->th_head, cadet->th_tail, th);
1762   GNUNET_free (th);
1763   if ((0 == message_ready_size (cadet)) && (NULL != cadet->th))
1764   {
1765     /* queue empty, no point in asking for transmission */
1766     GNUNET_CLIENT_notify_transmit_ready_cancel (cadet->th);
1767     cadet->th = NULL;
1768   }
1769   LOG (GNUNET_ERROR_TYPE_DEBUG, "CADET NOTIFY TRANSMIT READY CANCEL END\n");
1770 }
1771
1772
1773 void
1774 GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel)
1775 {
1776   send_ack (channel);
1777 }
1778
1779
1780 static void
1781 send_info_request (struct GNUNET_CADET_Handle *h, uint16_t type)
1782 {
1783   struct GNUNET_MessageHeader msg;
1784
1785   msg.size = htons (sizeof (msg));
1786   msg.type = htons (type);
1787   send_packet (h, &msg, NULL);
1788 }
1789
1790
1791 /**
1792  * Request a debug dump on the service's STDERR.
1793  *
1794  * WARNING: unstable API, likely to change in the future!
1795  *
1796  * @param h cadet handle
1797  */
1798 void
1799 GNUNET_CADET_request_dump (struct GNUNET_CADET_Handle *h)
1800 {
1801   LOG (GNUNET_ERROR_TYPE_DEBUG, "requesting dump\n");
1802   send_info_request (h, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP);
1803 }
1804
1805
1806 /**
1807  * Request information about peers known to the running cadet service.
1808  * The callback will be called for every peer known to the service.
1809  * Only one info request (of any kind) can be active at once.
1810  *
1811  *
1812  * WARNING: unstable API, likely to change in the future!
1813  *
1814  * @param h Handle to the cadet peer.
1815  * @param callback Function to call with the requested data.
1816  * @param callback_cls Closure for @c callback.
1817  *
1818  * @return #GNUNET_OK / #GNUNET_SYSERR
1819  */
1820 int
1821 GNUNET_CADET_get_peers (struct GNUNET_CADET_Handle *h,
1822                        GNUNET_CADET_PeersCB callback,
1823                        void *callback_cls)
1824 {
1825   if (NULL != h->info_cb.peers_cb)
1826   {
1827     GNUNET_break (0);
1828     return GNUNET_SYSERR;
1829   }
1830   send_info_request (h, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
1831   h->info_cb.peers_cb = callback;
1832   h->info_cls = callback_cls;
1833   return GNUNET_OK;
1834 }
1835
1836
1837 /**
1838  * Cancel a peer info request. The callback will not be called (anymore).
1839  *
1840  * WARNING: unstable API, likely to change in the future!
1841  *
1842  * @param h Cadet handle.
1843  *
1844  * @return Closure given to GNUNET_CADET_get_peers.
1845  */
1846 void *
1847 GNUNET_CADET_get_peers_cancel (struct GNUNET_CADET_Handle *h)
1848 {
1849   void *cls;
1850
1851   cls = h->info_cls;
1852   h->info_cb.peers_cb = NULL;
1853   h->info_cls = NULL;
1854   return cls;
1855 }
1856
1857
1858 /**
1859  * Request information about a peer known to the running cadet peer.
1860  * The callback will be called for the tunnel once.
1861  * Only one info request (of any kind) can be active at once.
1862  *
1863  * WARNING: unstable API, likely to change in the future!
1864  *
1865  * @param h Handle to the cadet peer.
1866  * @param id Peer whose tunnel to examine.
1867  * @param callback Function to call with the requested data.
1868  * @param callback_cls Closure for @c callback.
1869  *
1870  * @return #GNUNET_OK / #GNUNET_SYSERR
1871  */
1872 int
1873 GNUNET_CADET_get_peer (struct GNUNET_CADET_Handle *h,
1874                       const struct GNUNET_PeerIdentity *id,
1875                       GNUNET_CADET_PeerCB callback,
1876                       void *callback_cls)
1877 {
1878   struct GNUNET_CADET_LocalInfo msg;
1879
1880   if (NULL != h->info_cb.peer_cb)
1881   {
1882     GNUNET_break (0);
1883     return GNUNET_SYSERR;
1884   }
1885
1886   memset (&msg, 0, sizeof (msg));
1887   msg.header.size = htons (sizeof (msg));
1888   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
1889   msg.peer = *id;
1890   send_packet (h, &msg.header, NULL);
1891   h->info_cb.peer_cb = callback;
1892   h->info_cls = callback_cls;
1893   return GNUNET_OK;
1894 }
1895
1896
1897 /**
1898  * Request information about tunnels of the running cadet peer.
1899  * The callback will be called for every tunnel of the service.
1900  * Only one info request (of any kind) can be active at once.
1901  *
1902  * WARNING: unstable API, likely to change in the future!
1903  *
1904  * @param h Handle to the cadet peer.
1905  * @param callback Function to call with the requested data.
1906  * @param callback_cls Closure for @c callback.
1907  *
1908  * @return #GNUNET_OK / #GNUNET_SYSERR
1909  */
1910 int
1911 GNUNET_CADET_get_tunnels (struct GNUNET_CADET_Handle *h,
1912                          GNUNET_CADET_TunnelsCB callback,
1913                          void *callback_cls)
1914 {
1915   if (NULL != h->info_cb.tunnels_cb)
1916   {
1917     GNUNET_break (0);
1918     return GNUNET_SYSERR;
1919   }
1920   send_info_request (h, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
1921   h->info_cb.tunnels_cb = callback;
1922   h->info_cls = callback_cls;
1923   return GNUNET_OK;
1924 }
1925
1926
1927 /**
1928  * Cancel a monitor request. The monitor callback will not be called.
1929  *
1930  * @param h Cadet handle.
1931  *
1932  * @return Closure given to GNUNET_CADET_get_tunnels.
1933  */
1934 void *
1935 GNUNET_CADET_get_tunnels_cancel (struct GNUNET_CADET_Handle *h)
1936 {
1937   void *cls;
1938
1939   h->info_cb.tunnels_cb = NULL;
1940   cls = h->info_cls;
1941   h->info_cls = NULL;
1942
1943   return cls;
1944 }
1945
1946
1947
1948 /**
1949  * Request information about a tunnel of the running cadet peer.
1950  * The callback will be called for the tunnel once.
1951  * Only one info request (of any kind) can be active at once.
1952  *
1953  * WARNING: unstable API, likely to change in the future!
1954  *
1955  * @param h Handle to the cadet peer.
1956  * @param id Peer whose tunnel to examine.
1957  * @param callback Function to call with the requested data.
1958  * @param callback_cls Closure for @c callback.
1959  *
1960  * @return #GNUNET_OK / #GNUNET_SYSERR
1961  */
1962 int
1963 GNUNET_CADET_get_tunnel (struct GNUNET_CADET_Handle *h,
1964                         const struct GNUNET_PeerIdentity *id,
1965                         GNUNET_CADET_TunnelCB callback,
1966                         void *callback_cls)
1967 {
1968   struct GNUNET_CADET_LocalInfo msg;
1969
1970   if (NULL != h->info_cb.tunnel_cb)
1971   {
1972     GNUNET_break (0);
1973     return GNUNET_SYSERR;
1974   }
1975
1976   memset (&msg, 0, sizeof (msg));
1977   msg.header.size = htons (sizeof (msg));
1978   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1979   msg.peer = *id;
1980   send_packet (h, &msg.header, NULL);
1981   h->info_cb.tunnel_cb = callback;
1982   h->info_cls = callback_cls;
1983   return GNUNET_OK;
1984 }
1985
1986
1987 /**
1988  * Request information about a specific channel of the running cadet peer.
1989  *
1990  * WARNING: unstable API, likely to change in the future!
1991  * FIXME Add destination option.
1992  *
1993  * @param h Handle to the cadet peer.
1994  * @param initiator ID of the owner of the channel.
1995  * @param channel_number Channel number.
1996  * @param callback Function to call with the requested data.
1997  * @param callback_cls Closure for @c callback.
1998  *
1999  * @return #GNUNET_OK / #GNUNET_SYSERR
2000  */
2001 int
2002 GNUNET_CADET_show_channel (struct GNUNET_CADET_Handle *h,
2003                          struct GNUNET_PeerIdentity *initiator,
2004                          unsigned int channel_number,
2005                          GNUNET_CADET_ChannelCB callback,
2006                          void *callback_cls)
2007 {
2008   struct GNUNET_CADET_LocalInfo msg;
2009
2010   if (NULL != h->info_cb.channel_cb)
2011   {
2012     GNUNET_break (0);
2013     return GNUNET_SYSERR;
2014   }
2015
2016   msg.header.size = htons (sizeof (msg));
2017   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL);
2018   msg.peer = *initiator;
2019   msg.channel_id = htonl (channel_number);
2020 //   msg.reserved = 0;
2021   send_packet (h, &msg.header, NULL);
2022   h->info_cb.channel_cb = callback;
2023   h->info_cls = callback_cls;
2024   return GNUNET_OK;
2025 }
2026
2027
2028 /**
2029  * Function called to notify a client about the connection
2030  * begin ready to queue more data.  "buf" will be
2031  * NULL and "size" zero if the connection was closed for
2032  * writing in the meantime.
2033  *
2034  * @param cls closure
2035  * @param size number of bytes available in buf
2036  * @param buf where the callee should write the message
2037  * @return number of bytes written to buf
2038  */
2039 static size_t
2040 cadet_mq_ntr (void *cls, size_t size,
2041              void *buf)
2042 {
2043   struct GNUNET_MQ_Handle *mq = cls;
2044   struct CadetMQState *state = GNUNET_MQ_impl_state (mq);
2045   const struct GNUNET_MessageHeader *msg = GNUNET_MQ_impl_current (mq);
2046   uint16_t msize;
2047
2048   state->th = NULL;
2049   if (NULL == buf)
2050   {
2051     GNUNET_MQ_inject_error (mq, GNUNET_MQ_ERROR_WRITE);
2052     return 0;
2053   }
2054   msize = ntohs (msg->size);
2055   GNUNET_assert (msize <= size);
2056   memcpy (buf, msg, msize);
2057   GNUNET_MQ_impl_send_continue (mq);
2058   return msize;
2059 }
2060
2061
2062 /**
2063  * Signature of functions implementing the
2064  * sending functionality of a message queue.
2065  *
2066  * @param mq the message queue
2067  * @param msg the message to send
2068  * @param impl_state state of the implementation
2069  */
2070 static void
2071 cadet_mq_send_impl (struct GNUNET_MQ_Handle *mq,
2072                     const struct GNUNET_MessageHeader *msg,
2073                     void *impl_state)
2074 {
2075   struct CadetMQState *state = impl_state;
2076
2077   GNUNET_assert (NULL == state->th);
2078   state->th =
2079       GNUNET_CADET_notify_transmit_ready (state->channel,
2080                                          /* FIXME: add option for corking */
2081                                          GNUNET_NO,
2082                                          GNUNET_TIME_UNIT_FOREVER_REL,
2083                                          ntohs (msg->size),
2084                                          &cadet_mq_ntr, mq);
2085
2086 }
2087
2088
2089 /**
2090  * Signature of functions implementing the
2091  * destruction of a message queue.
2092  * Implementations must not free 'mq', but should
2093  * take care of 'impl_state'.
2094  *
2095  * @param mq the message queue to destroy
2096  * @param impl_state state of the implementation
2097  */
2098 static void
2099 cadet_mq_destroy_impl (struct GNUNET_MQ_Handle *mq,
2100                        void *impl_state)
2101 {
2102   struct CadetMQState *state = impl_state;
2103
2104   if (NULL != state->th)
2105     GNUNET_CADET_notify_transmit_ready_cancel (state->th);
2106
2107   GNUNET_free (state);
2108 }
2109
2110
2111 /**
2112  * Create a message queue for a cadet channel.
2113  * The message queue can only be used to transmit messages,
2114  * not to receive them.
2115  *
2116  * @param channel the channel to create the message qeue for
2117  * @return a message queue to messages over the channel
2118  */
2119 struct GNUNET_MQ_Handle *
2120 GNUNET_CADET_mq_create (struct GNUNET_CADET_Channel *channel)
2121 {
2122   struct GNUNET_MQ_Handle *mq;
2123   struct CadetMQState *state;
2124
2125   state = GNUNET_new (struct CadetMQState);
2126   state->channel = channel;
2127
2128   mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
2129                                       &cadet_mq_destroy_impl,
2130                                       NULL, /* FIXME: cancel impl. */
2131                                       state,
2132                                       NULL, /* no msg handlers */
2133                                       NULL, /* no err handlers */
2134                                       NULL); /* no handler cls */
2135   return mq;
2136 }
2137