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