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