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