- fix coverity
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_channel.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21
22 #include "platform.h"
23 #include "gnunet_util_lib.h"
24
25 #include "gnunet_statistics_service.h"
26
27 #include "cadet.h"
28 #include "cadet_protocol.h"
29
30 #include "gnunet-service-cadet_channel.h"
31 #include "gnunet-service-cadet_local.h"
32 #include "gnunet-service-cadet_tunnel.h"
33 #include "gnunet-service-cadet_peer.h"
34
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-chn",__VA_ARGS__)
36 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-chn",__VA_ARGS__)
37
38 #define CADET_RETRANSMIT_TIME    GNUNET_TIME_relative_multiply(\
39                                     GNUNET_TIME_UNIT_MILLISECONDS, 250)
40 #define CADET_RETRANSMIT_MARGIN  4
41
42
43 /**
44  * All the states a connection can be in.
45  */
46 enum CadetChannelState
47 {
48   /**
49    * Uninitialized status, should never appear in operation.
50    */
51   CADET_CHANNEL_NEW,
52
53   /**
54    * Connection create message sent, waiting for ACK.
55    */
56   CADET_CHANNEL_SENT,
57
58   /**
59    * Connection confirmed, ready to carry traffic.
60    */
61   CADET_CHANNEL_READY,
62 };
63
64
65 /**
66  * Info holder for channel messages in queues.
67  */
68 struct CadetChannelQueue
69 {
70   /**
71    * Tunnel Queue.
72    */
73   struct CadetTunnelQueue *tq;
74
75   /**
76    * Message type (DATA/DATA_ACK)
77    */
78   uint16_t type;
79
80   /**
81    * Message copy (for DATAs, to start retransmission timer)
82    */
83   struct CadetReliableMessage *copy;
84
85   /**
86    * Reliability (for DATA_ACKs, to access rel->ack_q)
87    */
88   struct CadetChannelReliability *rel;
89 };
90
91
92 /**
93  * Info needed to retry a message in case it gets lost.
94  */
95 struct CadetReliableMessage
96 {
97     /**
98      * Double linked list, FIFO style
99      */
100   struct CadetReliableMessage   *next;
101   struct CadetReliableMessage   *prev;
102
103     /**
104      * Type of message (payload, channel management).
105      */
106   int16_t                       type;
107
108     /**
109      * Tunnel Reliability queue this message is in.
110      */
111   struct CadetChannelReliability *rel;
112
113     /**
114      * ID of the message (ACK needed to free)
115      */
116   uint32_t                      mid;
117
118   /**
119    * Tunnel Queue.
120    */
121   struct CadetChannelQueue      *chq;
122
123     /**
124      * When was this message issued (to calculate ACK delay)
125      */
126   struct GNUNET_TIME_Absolute   timestamp;
127
128   /* struct GNUNET_CADET_Data with payload */
129 };
130
131
132 /**
133  * Info about the traffic state for a client in a channel.
134  */
135 struct CadetChannelReliability
136 {
137     /**
138      * Channel this is about.
139      */
140   struct CadetChannel *ch;
141
142     /**
143      * DLL of messages sent and not yet ACK'd.
144      */
145   struct CadetReliableMessage        *head_sent;
146   struct CadetReliableMessage        *tail_sent;
147
148     /**
149      * DLL of messages received out of order.
150      */
151   struct CadetReliableMessage        *head_recv;
152   struct CadetReliableMessage        *tail_recv;
153
154     /**
155      * Messages received.
156      */
157   unsigned int                      n_recv;
158
159     /**
160      * Next MID to use for outgoing traffic.
161      */
162   uint32_t                          mid_send;
163
164     /**
165      * Next MID expected for incoming traffic.
166      */
167   uint32_t                          mid_recv;
168
169     /**
170      * Handle for queued unique data CREATE, DATA_ACK.
171      */
172   struct CadetChannelQueue           *uniq;
173
174     /**
175      * Can we send data to the client?
176      */
177   int                               client_ready;
178
179   /**
180    * Can the client send data to us?
181    */
182   int                               client_allowed;
183
184     /**
185      * Task to resend/poll in case no ACK is received.
186      */
187   struct GNUNET_SCHEDULER_Task *   retry_task;
188
189     /**
190      * Counter for exponential backoff.
191      */
192   struct GNUNET_TIME_Relative       retry_timer;
193
194     /**
195      * How long does it usually take to get an ACK.
196      */
197   struct GNUNET_TIME_Relative       expected_delay;
198 };
199
200
201 /**
202  * Struct containing all information regarding a channel to a remote client.
203  */
204 struct CadetChannel
205 {
206     /**
207      * Tunnel this channel is in.
208      */
209   struct CadetTunnel *t;
210
211     /**
212      * Destination port of the channel.
213      */
214   uint32_t port;
215
216     /**
217      * Global channel number ( < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
218      */
219   CADET_ChannelNumber gid;
220
221     /**
222      * Local tunnel number for root (owner) client.
223      * ( >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI or 0 )
224      */
225   CADET_ChannelNumber lid_root;
226
227     /**
228      * Local tunnel number for local destination clients (incoming number)
229      * ( >= GNUNET_CADET_LOCAL_CHANNEL_ID_SERV or 0).
230      */
231   CADET_ChannelNumber lid_dest;
232
233     /**
234      * Channel state.
235      */
236   enum CadetChannelState state;
237
238     /**
239      * Is the tunnel bufferless (minimum latency)?
240      */
241   int nobuffer;
242
243     /**
244      * Is the tunnel reliable?
245      */
246   int reliable;
247
248     /**
249      * Last time the channel was used
250      */
251   struct GNUNET_TIME_Absolute timestamp;
252
253     /**
254      * Client owner of the tunnel, if any
255      */
256   struct CadetClient *root;
257
258     /**
259      * Client destination of the tunnel, if any.
260      */
261   struct CadetClient *dest;
262
263     /**
264      * Flag to signal the destruction of the channel.
265      * If this is set GNUNET_YES the channel will be destroyed
266      * when the queue is empty.
267      */
268   int destroy;
269
270     /**
271      * Total (reliable) messages pending ACK for this channel.
272      */
273   unsigned int pending_messages;
274
275     /**
276      * Reliability data.
277      * Only present (non-NULL) at the owner of a tunnel.
278      */
279   struct CadetChannelReliability *root_rel;
280
281     /**
282      * Reliability data.
283      * Only present (non-NULL) at the destination of a tunnel.
284      */
285   struct CadetChannelReliability *dest_rel;
286
287 };
288
289
290 /******************************************************************************/
291 /*******************************   GLOBALS  ***********************************/
292 /******************************************************************************/
293
294 /**
295  * Global handle to the statistics service.
296  */
297 extern struct GNUNET_STATISTICS_Handle *stats;
298
299 /**
300  * Local peer own ID (memory efficient handle).
301  */
302 extern GNUNET_PEER_Id myid;
303
304
305 /******************************************************************************/
306 /********************************   STATIC  ***********************************/
307 /******************************************************************************/
308
309
310 /**
311  * Destroy a reliable message after it has been acknowledged, either by
312  * direct mid ACK or bitfield. Updates the appropriate data structures and
313  * timers and frees all memory.
314  *
315  * @param copy Message that is no longer needed: remote peer got it.
316  * @param update_time Is the timing information relevant?
317  *                    If this message is ACK in a batch the timing information
318  *                    is skewed by the retransmission, count only for the
319  *                    retransmitted message.
320  *
321  * @return #GNUNET_YES if channel was destroyed as a result of the call,
322  *         #GNUNET_NO otherwise.
323  */
324 static int
325 rel_message_free (struct CadetReliableMessage *copy, int update_time);
326
327 /**
328  * send a channel create message.
329  *
330  * @param ch Channel for which to send.
331  */
332 static void
333 send_create (struct CadetChannel *ch);
334
335 /**
336  * Confirm we got a channel create, FWD ack.
337  *
338  * @param ch The channel to confirm.
339  * @param fwd Should we send a FWD ACK? (going dest->root)
340  */
341 static void
342 send_ack (struct CadetChannel *ch, int fwd);
343
344
345
346 /**
347  * Test if the channel is loopback: both root and dest are on the local peer.
348  *
349  * @param ch Channel to test.
350  *
351  * @return #GNUNET_YES if channel is loopback, #GNUNET_NO otherwise.
352  */
353 static int
354 is_loopback (const struct CadetChannel *ch)
355 {
356   if (NULL != ch->t)
357     return GCT_is_loopback (ch->t);
358
359   return (NULL != ch->root && NULL != ch->dest);
360 }
361
362
363 /**
364  * Save a copy of the data message for later retransmission.
365  *
366  * @param msg Message to copy.
367  * @param mid Message ID.
368  * @param rel Reliability data for retransmission.
369  */
370 static struct CadetReliableMessage *
371 copy_message (const struct GNUNET_CADET_Data *msg, uint32_t mid,
372               struct CadetChannelReliability *rel)
373 {
374   struct CadetReliableMessage *copy;
375   uint16_t size;
376
377   size = ntohs (msg->header.size);
378   copy = GNUNET_malloc (sizeof (*copy) + size);
379   copy->mid = mid;
380   copy->rel = rel;
381   copy->type = GNUNET_MESSAGE_TYPE_CADET_DATA;
382   memcpy (&copy[1], msg, size);
383
384   return copy;
385 }
386
387 /**
388  * We have received a message out of order, or the client is not ready.
389  * Buffer it until we receive an ACK from the client or the missing
390  * message from the channel.
391  *
392  * @param msg Message to buffer (MUST be of type CADET_DATA).
393  * @param rel Reliability data to the corresponding direction.
394  */
395 static void
396 add_buffered_data (const struct GNUNET_CADET_Data *msg,
397                    struct CadetChannelReliability *rel)
398 {
399   struct CadetReliableMessage *copy;
400   struct CadetReliableMessage *prev;
401   uint32_t mid;
402
403   mid = ntohl (msg->mid);
404
405   LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data MID %u (%u)\n",
406        mid, rel->n_recv);
407
408   rel->n_recv++;
409
410   // FIXME do something better than O(n), although n < 64...
411   // FIXME start from the end (most messages are the latest ones)
412   for (prev = rel->head_recv; NULL != prev; prev = prev->next)
413   {
414     LOG (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
415     if (prev->mid == mid)
416     {
417       LOG (GNUNET_ERROR_TYPE_DEBUG, " already there!\n");
418       rel->n_recv--;
419       return;
420     }
421     else if (GC_is_pid_bigger (prev->mid, mid))
422     {
423       LOG (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
424       copy = copy_message (msg, mid, rel);
425       GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
426                                           prev, copy);
427       return;
428     }
429   }
430   copy = copy_message (msg, mid, rel);
431   LOG (GNUNET_ERROR_TYPE_DEBUG, " insert at tail! (now: %u)\n", rel->n_recv);
432   GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
433   LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
434 }
435
436
437 /**
438  * Add a destination client to a channel, initializing all data structures
439  * in the channel and the client.
440  *
441  * @param ch Channel to which add the destination.
442  * @param c Client which to add to the channel.
443  */
444 static void
445 add_destination (struct CadetChannel *ch, struct CadetClient *c)
446 {
447   if (NULL != ch->dest)
448   {
449     GNUNET_break (0);
450     return;
451   }
452
453   /* Assign local id as destination */
454   ch->lid_dest = GML_get_next_chid (c);
455
456   /* Store in client's hashmap */
457   GML_channel_add (c, ch->lid_dest, ch);
458
459   GNUNET_break (NULL == ch->dest_rel);
460   ch->dest_rel = GNUNET_new (struct CadetChannelReliability);
461   ch->dest_rel->ch = ch;
462   ch->dest_rel->expected_delay.rel_value_us = 0;
463   ch->dest_rel->retry_timer = CADET_RETRANSMIT_TIME;
464
465   ch->dest = c;
466 }
467
468
469 /**
470  * Set options in a channel, extracted from a bit flag field.
471  *
472  * @param ch Channel to set options to.
473  * @param options Bit array in host byte order.
474  */
475 static void
476 channel_set_options (struct CadetChannel *ch, uint32_t options)
477 {
478   ch->nobuffer = (options & GNUNET_CADET_OPTION_NOBUFFER) != 0 ?
479   GNUNET_YES : GNUNET_NO;
480   ch->reliable = (options & GNUNET_CADET_OPTION_RELIABLE) != 0 ?
481   GNUNET_YES : GNUNET_NO;
482 }
483
484
485 /**
486  * Get a bit flag field with the options of a channel.
487  *
488  * @param ch Channel to get options from.
489  *
490  * @return Bit array in host byte order.
491  */
492 static uint32_t
493 channel_get_options (struct CadetChannel *ch)
494 {
495   uint32_t options;
496
497   options = 0;
498   if (ch->nobuffer)
499     options |= GNUNET_CADET_OPTION_NOBUFFER;
500   if (ch->reliable)
501     options |= GNUNET_CADET_OPTION_RELIABLE;
502
503   return options;
504 }
505
506
507 /**
508  * Notify a client that the channel is no longer valid.
509  *
510  * @param ch Channel that is destroyed.
511  * @param local_only Should we avoid sending it to other peers?
512  */
513 static void
514 send_destroy (struct CadetChannel *ch, int local_only)
515 {
516   struct GNUNET_CADET_ChannelManage msg;
517
518   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
519   msg.header.size = htons (sizeof (msg));
520   msg.chid = htonl (ch->gid);
521
522   /* If root is not NULL, notify.
523    * If it's NULL, check lid_root. When a local destroy comes in, root
524    * is set to NULL but lid_root is left untouched. In this case, do nothing,
525    * the client is the one who requested the channel to be destroyed.
526    */
527   if (NULL != ch->root)
528     GML_send_channel_destroy (ch->root, ch->lid_root);
529   else if (0 == ch->lid_root && GNUNET_NO == local_only)
530     GCCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO, NULL);
531
532   if (NULL != ch->dest)
533     GML_send_channel_destroy (ch->dest, ch->lid_dest);
534   else if (0 == ch->lid_dest && GNUNET_NO == local_only)
535     GCCH_send_prebuilt_message (&msg.header, ch, GNUNET_YES, NULL);
536 }
537
538
539 /**
540  * Notify the destination client that a new incoming channel was created.
541  *
542  * @param ch Channel that was created.
543  */
544 static void
545 send_client_create (struct CadetChannel *ch)
546 {
547   uint32_t opt;
548
549   if (NULL == ch->dest)
550     return;
551
552   opt = 0;
553   opt |= GNUNET_YES == ch->reliable ? GNUNET_CADET_OPTION_RELIABLE : 0;
554   opt |= GNUNET_YES == ch->nobuffer ? GNUNET_CADET_OPTION_NOBUFFER : 0;
555   GML_send_channel_create (ch->dest, ch->lid_dest, ch->port, opt,
556                            GCT_get_destination (ch->t));
557
558 }
559
560
561 /**
562  * Send data to a client.
563  *
564  * If the client is ready, send directly, otherwise buffer while listening
565  * for a local ACK.
566  *
567  * @param ch Channel
568  * @param msg Message.
569  * @param fwd Is this a fwd (root->dest) message?
570  */
571 static void
572 send_client_data (struct CadetChannel *ch,
573                   const struct GNUNET_CADET_Data *msg,
574                   int fwd)
575 {
576   if (fwd)
577   {
578     if (ch->dest_rel->client_ready)
579     {
580       GML_send_data (ch->dest, msg, ch->lid_dest);
581       ch->dest_rel->client_ready = GNUNET_NO;
582       ch->dest_rel->mid_recv++;
583     }
584     else
585       add_buffered_data (msg, ch->dest_rel);
586   }
587   else
588   {
589     if (ch->root_rel->client_ready)
590     {
591       GML_send_data (ch->root, msg, ch->lid_root);
592       ch->root_rel->client_ready = GNUNET_NO;
593       ch->root_rel->mid_recv++;
594     }
595     else
596       add_buffered_data (msg, ch->root_rel);
597   }
598 }
599
600
601 /**
602  * Send a buffered message to the client, for in order delivery or
603  * as result of client ACK.
604  *
605  * @param ch Channel on which to empty the message buffer.
606  * @param c Client to send to.
607  * @param fwd Is this to send FWD data?.
608  */
609 static void
610 send_client_buffered_data (struct CadetChannel *ch,
611                            struct CadetClient *c,
612                            int fwd)
613 {
614   struct CadetReliableMessage *copy;
615   struct CadetChannelReliability *rel;
616
617   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
618   rel = fwd ? ch->dest_rel : ch->root_rel;
619   if (GNUNET_NO == rel->client_ready)
620   {
621     LOG (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
622     return;
623   }
624
625   copy = rel->head_recv;
626   /* We never buffer channel management messages */
627   if (NULL != copy)
628   {
629     if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
630     {
631       struct GNUNET_CADET_Data *msg = (struct GNUNET_CADET_Data *) &copy[1];
632
633       LOG (GNUNET_ERROR_TYPE_DEBUG, " have %u! now expecting %u\n",
634            copy->mid, rel->mid_recv + 1);
635       send_client_data (ch, msg, fwd);
636       rel->n_recv--;
637       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
638       LOG (GNUNET_ERROR_TYPE_DEBUG, " free copy recv MID %u (%p), %u left\n",
639            copy->mid, copy, rel->n_recv);
640       GNUNET_free (copy);
641       GCCH_send_data_ack (ch, fwd);
642     }
643     else
644     {
645       LOG (GNUNET_ERROR_TYPE_DEBUG, " reliable && don't have %u, next is %u\n",
646            rel->mid_recv, copy->mid);
647       if (GNUNET_YES == ch->destroy)
648       {
649         /* We don't have the next data piece and the remote peer has closed the
650          * channel. We won't receive it anymore, so just destroy the channel.
651          * FIXME: wait some time to allow other connections to
652          *        deliver missing messages
653          */
654         send_destroy (ch, GNUNET_YES);
655         GCCH_destroy (ch);
656       }
657     }
658   }
659   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
660 }
661
662
663 /**
664  * Allow a client to send more data.
665  *
666  * In case the client was already allowed to send data, do nothing.
667  *
668  * @param ch Channel.
669  * @param fwd Is this a FWD ACK? (FWD ACKs are sent to root)
670  */
671 static void
672 send_client_ack (struct CadetChannel *ch, int fwd)
673 {
674   struct CadetChannelReliability *rel = fwd ? ch->root_rel : ch->dest_rel;
675   struct CadetClient *c = fwd ? ch->root : ch->dest;
676
677   if (NULL == c)
678   {
679     GNUNET_break (GNUNET_NO != ch->destroy);
680     return;
681   }
682   LOG (GNUNET_ERROR_TYPE_DEBUG,
683        "  sending %s ack to client on channel %s\n",
684        GC_f2s (fwd), GCCH_2s (ch));
685
686   if (NULL == rel)
687   {
688     GNUNET_break (0);
689     return;
690   }
691
692   if (GNUNET_YES == rel->client_allowed)
693   {
694     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already allowed\n");
695     return;
696   }
697   rel->client_allowed = GNUNET_YES;
698
699   GML_send_ack (c, fwd ? ch->lid_root : ch->lid_dest);
700 }
701
702
703 /**
704  * Notify the root that the destination rejected the channel.
705  *
706  * @param ch Rejected channel.
707  */
708 static void
709 send_client_nack (struct CadetChannel *ch)
710 {
711   if (NULL == ch->root)
712   {
713     GNUNET_break (0);
714     return;
715   }
716   GML_send_channel_nack (ch->root, ch->lid_root);
717 }
718
719
720 /**
721  * We haven't received an ACK after a certain time: restransmit the message.
722  *
723  * @param cls Closure (CadetChannelReliability with the message to restransmit)
724  */
725 static void
726 channel_retransmit_message (void *cls)
727 {
728   struct CadetChannelReliability *rel = cls;
729   struct CadetReliableMessage *copy;
730   struct CadetChannel *ch;
731   struct GNUNET_CADET_Data *payload;
732   int fwd;
733
734   rel->retry_task = NULL;
735   ch = rel->ch;
736   copy = rel->head_sent;
737   if (NULL == copy)
738   {
739     GNUNET_break (0); // FIXME tripped in rps testcase
740     return;
741   }
742
743   payload = (struct GNUNET_CADET_Data *) &copy[1];
744   fwd = (rel == ch->root_rel);
745
746   /* Message not found in the queue that we are going to use. */
747   LOG (GNUNET_ERROR_TYPE_DEBUG, "RETRANSMIT MID %u\n", copy->mid);
748
749   GCCH_send_prebuilt_message (&payload->header, ch, fwd, copy);
750   GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
751 }
752
753
754 /**
755  * We haven't received an Channel ACK after a certain time: resend the CREATE.
756  *
757  * @param cls Closure (CadetChannelReliability of the channel to recreate)
758  */
759 static void
760 channel_recreate (void *cls)
761 {
762   struct CadetChannelReliability *rel = cls;
763
764   rel->retry_task = NULL;
765   LOG (GNUNET_ERROR_TYPE_DEBUG, "RE-CREATE\n");
766   GNUNET_STATISTICS_update (stats,
767                             "# data retransmitted", 1, GNUNET_NO);
768
769   if (rel == rel->ch->root_rel)
770   {
771     send_create (rel->ch);
772   }
773   else if (rel == rel->ch->dest_rel)
774   {
775     send_ack (rel->ch, GNUNET_YES);
776   }
777   else
778   {
779     GNUNET_break (0);
780   }
781 }
782
783
784 /**
785  * Message has been sent: start retransmission timer.
786  *
787  * @param cls Closure (queue structure).
788  * @param t Tunnel.
789  * @param q Queue handler (no longer valid).
790  * @param type Type of message.
791  * @param size Size of the message.
792  */
793 static void
794 ch_message_sent (void *cls,
795                  struct CadetTunnel *t,
796                  struct CadetTunnelQueue *q,
797                  uint16_t type, size_t size)
798 {
799   struct CadetChannelQueue *chq = cls;
800   struct CadetReliableMessage *copy = chq->copy;
801   struct CadetChannelReliability *rel;
802
803   LOG (GNUNET_ERROR_TYPE_DEBUG, "channel_message_sent callback %s\n",
804        GC_m2s (chq->type));
805
806   switch (chq->type)
807   {
808     case GNUNET_MESSAGE_TYPE_CADET_DATA:
809       LOG (GNUNET_ERROR_TYPE_DEBUG, "data MID %u sent\n", copy->mid);
810       GNUNET_assert (chq == copy->chq);
811       copy->timestamp = GNUNET_TIME_absolute_get ();
812       rel = copy->rel;
813       if (NULL == rel->retry_task)
814       {
815         LOG (GNUNET_ERROR_TYPE_DEBUG, "  scheduling retry in %d * %s\n",
816              CADET_RETRANSMIT_MARGIN,
817              GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
818                                                      GNUNET_YES));
819         if (0 != rel->expected_delay.rel_value_us)
820         {
821           rel->retry_timer =
822               GNUNET_TIME_relative_multiply (rel->expected_delay,
823                                              CADET_RETRANSMIT_MARGIN);
824         }
825         else
826         {
827           rel->retry_timer = CADET_RETRANSMIT_TIME;
828         }
829         LOG (GNUNET_ERROR_TYPE_DEBUG, "  using delay %s\n",
830              GNUNET_STRINGS_relative_time_to_string (rel->retry_timer,
831                                                      GNUNET_NO));
832         rel->retry_task =
833             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
834                                           &channel_retransmit_message, rel);
835       }
836       else
837       {
838         LOG (GNUNET_ERROR_TYPE_DEBUG, "retry running %p\n", rel->retry_task);
839       }
840       copy->chq = NULL;
841       break;
842
843
844     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
845     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
846     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
847       LOG (GNUNET_ERROR_TYPE_DEBUG, "sent %s\n", GC_m2s (chq->type));
848       rel = chq->rel;
849       GNUNET_assert (rel->uniq == chq);
850       rel->uniq = NULL;
851
852       if (CADET_CHANNEL_READY != rel->ch->state
853           && GNUNET_MESSAGE_TYPE_CADET_DATA_ACK != type
854           && GNUNET_NO == rel->ch->destroy)
855       {
856         GNUNET_assert (NULL == rel->retry_task);
857         LOG (GNUNET_ERROR_TYPE_DEBUG, "STD BACKOFF %s\n",
858              GNUNET_STRINGS_relative_time_to_string (rel->retry_timer,
859                                                      GNUNET_NO));
860         rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
861         rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
862                                                         &channel_recreate, rel);
863       }
864       break;
865
866     default:
867       GNUNET_break (0);
868   }
869
870   GNUNET_free (chq);
871 }
872
873
874 /**
875  * send a channel create message.
876  *
877  * @param ch Channel for which to send.
878  */
879 static void
880 send_create (struct CadetChannel *ch)
881 {
882   struct GNUNET_CADET_ChannelCreate msgcc;
883
884   msgcc.header.size = htons (sizeof (msgcc));
885   msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE);
886   msgcc.chid = htonl (ch->gid);
887   msgcc.port = htonl (ch->port);
888   msgcc.opt = htonl (channel_get_options (ch));
889
890   GCCH_send_prebuilt_message (&msgcc.header, ch, GNUNET_YES, NULL);
891 }
892
893
894 /**
895  * Confirm we got a channel create or FWD ack.
896  *
897  * @param ch The channel to confirm.
898  * @param fwd Should we send a FWD ACK? (going dest->root)
899  */
900 static void
901 send_ack (struct CadetChannel *ch, int fwd)
902 {
903   struct GNUNET_CADET_ChannelManage msg;
904
905   msg.header.size = htons (sizeof (msg));
906   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK);
907   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending channel %s ack for channel %s\n",
908        GC_f2s (fwd), GCCH_2s (ch));
909
910   msg.chid = htonl (ch->gid);
911   GCCH_send_prebuilt_message (&msg.header, ch, !fwd, NULL);
912 }
913
914
915 /**
916  * Send a message and don't keep any info about it: we won't need to cancel it
917  * or resend it.
918  *
919  * @param msg Header of the message to fire away.
920  * @param ch Channel on which the message should go.
921  * @param force Is this a forced (undroppable) message?
922  */
923 static void
924 fire_and_forget (const struct GNUNET_MessageHeader *msg,
925                  struct CadetChannel *ch,
926                  int force)
927 {
928   GNUNET_break (NULL == GCT_send_prebuilt_message (msg, ch->t, NULL,
929                                                    force, NULL, NULL));
930 }
931
932
933 /**
934  * Notify that a channel create didn't succeed.
935  *
936  * @param ch The channel to reject.
937  */
938 static void
939 send_nack (struct CadetChannel *ch)
940 {
941   struct GNUNET_CADET_ChannelManage msg;
942
943   msg.header.size = htons (sizeof (msg));
944   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK);
945   LOG (GNUNET_ERROR_TYPE_DEBUG,
946        "  sending channel NACK for channel %s\n",
947        GCCH_2s (ch));
948
949   msg.chid = htonl (ch->gid);
950   GCCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO, NULL);
951 }
952
953
954 /**
955  * Destroy all reliable messages queued for a channel,
956  * during a channel destruction.
957  * Frees the reliability structure itself.
958  *
959  * @param rel Reliability data for a channel.
960  */
961 static void
962 channel_rel_free_all (struct CadetChannelReliability *rel)
963 {
964   struct CadetReliableMessage *copy;
965   struct CadetReliableMessage *next;
966
967   if (NULL == rel)
968     return;
969
970   for (copy = rel->head_recv; NULL != copy; copy = next)
971   {
972     next = copy->next;
973     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
974     LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE ALL RECV %p\n", copy);
975     GNUNET_break (NULL == copy->chq);
976     GNUNET_free (copy);
977   }
978   for (copy = rel->head_sent; NULL != copy; copy = next)
979   {
980     next = copy->next;
981     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
982     LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE ALL SEND %p\n", copy);
983     if (NULL != copy->chq)
984     {
985       if (NULL != copy->chq->tq)
986       {
987         GCT_cancel (copy->chq->tq);
988         /* ch_message_sent will free copy->q */
989       }
990       else
991       {
992         GNUNET_free (copy->chq);
993         GNUNET_break (0);
994       }
995     }
996     GNUNET_free (copy);
997   }
998   if (NULL != rel->uniq && NULL != rel->uniq->tq)
999   {
1000     GCT_cancel (rel->uniq->tq);
1001     /* ch_message_sent is called freeing uniq */
1002   }
1003   if (NULL != rel->retry_task)
1004   {
1005     GNUNET_SCHEDULER_cancel (rel->retry_task);
1006     rel->retry_task = NULL;
1007   }
1008   GNUNET_free (rel);
1009 }
1010
1011
1012 /**
1013  * Mark future messages as ACK'd.
1014  *
1015  * @param rel Reliability data.
1016  * @param msg DataACK message with a bitfield of future ACK'd messages.
1017  *
1018  * @return How many messages have been freed.
1019  */
1020 static unsigned int
1021 channel_rel_free_sent (struct CadetChannelReliability *rel,
1022                        const struct GNUNET_CADET_DataACK *msg)
1023 {
1024   struct CadetReliableMessage *copy;
1025   struct CadetReliableMessage *next;
1026   uint64_t bitfield;
1027   uint64_t mask;
1028   uint32_t mid;
1029   uint32_t target;
1030   unsigned int i;
1031   unsigned int r;
1032
1033   bitfield = msg->futures;
1034   mid = ntohl (msg->mid);
1035   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable %u %lX\n", mid, bitfield);
1036   LOG (GNUNET_ERROR_TYPE_DEBUG, " rel %p, head %p\n", rel, rel->head_sent);
1037   for (i = 0, r = 0, copy = rel->head_sent;
1038        i < 64 && NULL != copy && 0 != bitfield;
1039        i++)
1040   {
1041     LOG (GNUNET_ERROR_TYPE_DEBUG, " trying bit %u (mid %u)\n", i, mid + i + 1);
1042     mask = 0x1LL << i;
1043     if (0 == (bitfield & mask))
1044      continue;
1045
1046     LOG (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
1047     /* Bit was set, clear the bit from the bitfield */
1048     bitfield &= ~mask;
1049
1050     /* The i-th bit was set. Do we have that copy? */
1051     /* Skip copies with mid < target */
1052     target = mid + i + 1;
1053     LOG (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
1054     while (NULL != copy && GC_is_pid_bigger (target, copy->mid))
1055       copy = copy->next;
1056
1057     /* Did we run out of copies? (previously freed, it's ok) */
1058     if (NULL == copy)
1059     {
1060       LOG (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
1061       return r;
1062     }
1063
1064     /* Did we overshoot the target? (previously freed, it's ok) */
1065     if (GC_is_pid_bigger (copy->mid, target))
1066     {
1067       LOG (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
1068       i += copy->mid - target - 1;   /* MID: 90, t = 85, i += 4 (i++ later) */
1069       mask = (0x1LL << (i + 1)) - 1; /* Mask = i-th bit and all before */
1070       bitfield &= ~mask;             /* Clear all bits up to MID - 1 */
1071       continue;
1072     }
1073
1074     /* Now copy->mid == target, free it */
1075     next = copy->next;
1076     GNUNET_break (GNUNET_YES != rel_message_free (copy, GNUNET_YES));
1077     r++;
1078     copy = next;
1079   }
1080   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
1081   return r;
1082 }
1083
1084
1085 /**
1086  * Destroy a reliable message after it has been acknowledged, either by
1087  * direct mid ACK or bitfield. Updates the appropriate data structures and
1088  * timers and frees all memory.
1089  *
1090  * @param copy Message that is no longer needed: remote peer got it.
1091  * @param update_time Is the timing information relevant?
1092  *                    If this message is ACK in a batch the timing information
1093  *                    is skewed by the retransmission, count only for the
1094  *                    retransmitted message.
1095  *
1096  * @return #GNUNET_YES if channel was destroyed as a result of the call,
1097  *         #GNUNET_NO otherwise.
1098  */
1099 static int
1100 rel_message_free (struct CadetReliableMessage *copy, int update_time)
1101 {
1102   struct CadetChannelReliability *rel;
1103   struct GNUNET_TIME_Relative time;
1104
1105   rel = copy->rel;
1106   LOG (GNUNET_ERROR_TYPE_DEBUG, "Freeing %u\n", copy->mid);
1107   if (GNUNET_YES == update_time)
1108   {
1109     time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
1110     if (0 == rel->expected_delay.rel_value_us)
1111       rel->expected_delay = time;
1112     else
1113     {
1114       rel->expected_delay.rel_value_us *= 7;
1115       rel->expected_delay.rel_value_us += time.rel_value_us;
1116       rel->expected_delay.rel_value_us /= 8;
1117     }
1118     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message time %12s\n",
1119          GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
1120     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new delay    %12s\n",
1121          GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
1122                                                  GNUNET_NO));
1123     rel->retry_timer = rel->expected_delay;
1124   }
1125   else
1126   {
1127     LOG (GNUNET_ERROR_TYPE_DEBUG, "batch free, ignoring timing\n");
1128   }
1129   rel->ch->pending_messages--;
1130   if (NULL != copy->chq)
1131   {
1132     GCT_cancel (copy->chq->tq);
1133     /* copy->q is set to NULL by ch_message_sent */
1134   }
1135   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
1136   LOG (GNUNET_ERROR_TYPE_DEBUG, " free send copy MID %u at %p\n",
1137        copy->mid, copy);
1138   GNUNET_free (copy);
1139
1140   if (GNUNET_NO != rel->ch->destroy && 0 == rel->ch->pending_messages)
1141   {
1142     GCCH_destroy (rel->ch);
1143     return GNUNET_YES;
1144   }
1145   return GNUNET_NO;
1146 }
1147
1148
1149 /**
1150  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
1151  *
1152  * @param ch Channel to mark as ready.
1153  * @param fwd Was the ACK message a FWD ACK? (dest->root, SYNACK)
1154  */
1155 static void
1156 channel_confirm (struct CadetChannel *ch, int fwd)
1157 {
1158   struct CadetChannelReliability *rel;
1159   enum CadetChannelState oldstate;
1160
1161   rel = fwd ? ch->root_rel : ch->dest_rel;
1162   if (NULL == rel)
1163   {
1164     GNUNET_break (GNUNET_NO != ch->destroy);
1165     return;
1166   }
1167   LOG (GNUNET_ERROR_TYPE_DEBUG, "  channel confirm %s %s\n",
1168        GC_f2s (fwd), GCCH_2s (ch));
1169   oldstate = ch->state;
1170   ch->state = CADET_CHANNEL_READY;
1171
1172   if (CADET_CHANNEL_READY != oldstate || GNUNET_YES == is_loopback (ch))
1173   {
1174     rel->client_ready = GNUNET_YES;
1175     rel->expected_delay = rel->retry_timer;
1176     LOG (GNUNET_ERROR_TYPE_DEBUG, "  confirm retry timer %s\n",
1177          GNUNET_STRINGS_relative_time_to_string (rel->retry_timer, GNUNET_NO));
1178     if (GCT_get_connections_buffer (ch->t) > 0 || GCT_is_loopback (ch->t))
1179       send_client_ack (ch, fwd);
1180
1181     if (NULL != rel->retry_task)
1182     {
1183       GNUNET_SCHEDULER_cancel (rel->retry_task);
1184       rel->retry_task = NULL;
1185     }
1186     else if (NULL != rel->uniq)
1187     {
1188       GCT_cancel (rel->uniq->tq);
1189       /* ch_message_sent will free and NULL uniq */
1190     }
1191     else if (GNUNET_NO == is_loopback (ch))
1192     {
1193       /* We SHOULD have been trying to retransmit this! */
1194       GNUNET_break (0);
1195     }
1196   }
1197
1198   /* In case of a FWD ACK (SYNACK) send a BCK ACK (ACK). */
1199   if (GNUNET_YES == fwd)
1200     send_ack (ch, GNUNET_NO);
1201 }
1202
1203
1204 /**
1205  * Save a copy to retransmit in case it gets lost.
1206  *
1207  * Initializes all needed callbacks and timers.
1208  *
1209  * @param ch Channel this message goes on.
1210  * @param msg Message to copy.
1211  * @param fwd Is this fwd traffic?
1212  */
1213 static struct CadetReliableMessage *
1214 channel_save_copy (struct CadetChannel *ch,
1215                    const struct GNUNET_MessageHeader *msg,
1216                    int fwd)
1217 {
1218   struct CadetChannelReliability *rel;
1219   struct CadetReliableMessage *copy;
1220   uint32_t mid;
1221   uint16_t type;
1222   uint16_t size;
1223
1224   rel = fwd ? ch->root_rel : ch->dest_rel;
1225   mid = rel->mid_send - 1;
1226   type = ntohs (msg->type);
1227   size = ntohs (msg->size);
1228
1229   LOG (GNUNET_ERROR_TYPE_DEBUG, "save MID %u %s\n", mid, GC_m2s (type));
1230   copy = GNUNET_malloc (sizeof (struct CadetReliableMessage) + size);
1231   LOG (GNUNET_ERROR_TYPE_DEBUG, "  at %p\n", copy);
1232   copy->mid = mid;
1233   copy->rel = rel;
1234   copy->type = type;
1235   memcpy (&copy[1], msg, size);
1236   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
1237   ch->pending_messages++;
1238
1239   return copy;
1240 }
1241
1242
1243 /**
1244  * Create a new channel.
1245  *
1246  * @param t Tunnel this channel is in.
1247  * @param owner Client that owns the channel, NULL for foreign channels.
1248  * @param lid_root Local ID for root client.
1249  *
1250  * @return A new initialized channel. NULL on error.
1251  */
1252 static struct CadetChannel *
1253 channel_new (struct CadetTunnel *t,
1254              struct CadetClient *owner,
1255              CADET_ChannelNumber lid_root)
1256 {
1257   struct CadetChannel *ch;
1258
1259   ch = GNUNET_new (struct CadetChannel);
1260   ch->root = owner;
1261   ch->lid_root = lid_root;
1262   ch->t = t;
1263
1264   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
1265
1266   if (NULL != owner)
1267   {
1268     ch->gid = GCT_get_next_chid (t);
1269     GML_channel_add (owner, lid_root, ch);
1270   }
1271   GCT_add_channel (t, ch);
1272
1273   return ch;
1274 }
1275
1276
1277 /**
1278  * Handle a loopback message: call the appropriate handler for the message type.
1279  *
1280  * @param ch Channel this message is on.
1281  * @param msgh Message header.
1282  * @param fwd Is this FWD traffic?
1283  */
1284 void
1285 handle_loopback (struct CadetChannel *ch,
1286                  const struct GNUNET_MessageHeader *msgh,
1287                  int fwd)
1288 {
1289   uint16_t type;
1290
1291   type = ntohs (msgh->type);
1292   LOG (GNUNET_ERROR_TYPE_DEBUG,
1293        "Loopback %s %s message!\n",
1294        GC_f2s (fwd), GC_m2s (type));
1295
1296   switch (type)
1297   {
1298     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1299       /* Don't send hop ACK, wait for client to ACK */
1300       LOG (GNUNET_ERROR_TYPE_DEBUG, "SEND loopback %u (%u)\n",
1301            ntohl (((struct GNUNET_CADET_Data *) msgh)->mid), ntohs (msgh->size));
1302       GCCH_handle_data (ch, (struct GNUNET_CADET_Data *) msgh, fwd);
1303       break;
1304
1305     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1306       GCCH_handle_data_ack (ch, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1307       break;
1308
1309     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1310       GCCH_handle_create (ch->t,
1311                           (struct GNUNET_CADET_ChannelCreate *) msgh);
1312       break;
1313
1314     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1315       GCCH_handle_ack (ch,
1316                        (struct GNUNET_CADET_ChannelManage *) msgh,
1317                        fwd);
1318       break;
1319
1320     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1321       GCCH_handle_nack (ch);
1322       break;
1323
1324     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1325       GCCH_handle_destroy (ch,
1326                            (struct GNUNET_CADET_ChannelManage *) msgh,
1327                            fwd);
1328       break;
1329
1330     default:
1331       GNUNET_break_op (0);
1332       LOG (GNUNET_ERROR_TYPE_DEBUG,
1333            "end-to-end message not known (%u)\n",
1334            ntohs (msgh->type));
1335   }
1336 }
1337
1338
1339
1340 /******************************************************************************/
1341 /********************************    API    ***********************************/
1342 /******************************************************************************/
1343
1344 /**
1345  * Destroy a channel and free all resources.
1346  *
1347  * @param ch Channel to destroy.
1348  */
1349 void
1350 GCCH_destroy (struct CadetChannel *ch)
1351 {
1352   struct CadetClient *c;
1353   struct CadetTunnel *t;
1354
1355   if (NULL == ch)
1356     return;
1357   if (2 == ch->destroy)
1358     return; /* recursive call */
1359   ch->destroy = 2;
1360
1361   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
1362               GCT_2s (ch->t), ch->gid);
1363   GCCH_debug (ch, GNUNET_ERROR_TYPE_DEBUG);
1364
1365   c = ch->root;
1366   if (NULL != c)
1367   {
1368     GML_channel_remove (c, ch->lid_root, ch);
1369   }
1370
1371   c = ch->dest;
1372   if (NULL != c)
1373   {
1374     GML_channel_remove (c, ch->lid_dest, ch);
1375   }
1376
1377   channel_rel_free_all (ch->root_rel);
1378   channel_rel_free_all (ch->dest_rel);
1379
1380   t = ch->t;
1381   GCT_remove_channel (t, ch);
1382   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
1383
1384   GNUNET_free (ch);
1385   GCT_destroy_if_empty (t);
1386 }
1387
1388
1389 /**
1390  * Get the channel's public ID.
1391  *
1392  * @param ch Channel.
1393  *
1394  * @return ID used to identify the channel with the remote peer.
1395  */
1396 CADET_ChannelNumber
1397 GCCH_get_id (const struct CadetChannel *ch)
1398 {
1399   return ch->gid;
1400 }
1401
1402
1403 /**
1404  * Get the channel tunnel.
1405  *
1406  * @param ch Channel to get the tunnel from.
1407  *
1408  * @return tunnel of the channel.
1409  */
1410 struct CadetTunnel *
1411 GCCH_get_tunnel (const struct CadetChannel *ch)
1412 {
1413   return ch->t;
1414 }
1415
1416
1417 /**
1418  * Get free buffer space towards the client on a specific channel.
1419  *
1420  * @param ch Channel.
1421  * @param fwd Is query about FWD traffic?
1422  *
1423  * @return Free buffer space [0 - 64]
1424  */
1425 unsigned int
1426 GCCH_get_buffer (struct CadetChannel *ch, int fwd)
1427 {
1428   struct CadetChannelReliability *rel;
1429
1430   rel = fwd ? ch->dest_rel : ch->root_rel;
1431   LOG (GNUNET_ERROR_TYPE_DEBUG, "   get buffer, channel %s\n", GCCH_2s (ch));
1432   GCCH_debug (ch, GNUNET_ERROR_TYPE_DEBUG);
1433   /* If rel is NULL it means that the end is not yet created,
1434    * most probably is a loopback channel at the point of sending
1435    * the ChannelCreate to itself.
1436    */
1437   if (NULL == rel)
1438   {
1439     LOG (GNUNET_ERROR_TYPE_DEBUG, "  rel is NULL: max\n");
1440     return 64;
1441   }
1442
1443   LOG (GNUNET_ERROR_TYPE_DEBUG, "   n_recv %d\n", rel->n_recv);
1444   return (64 - rel->n_recv);
1445 }
1446
1447
1448 /**
1449  * Get flow control status of end point: is client allow to send?
1450  *
1451  * @param ch Channel.
1452  * @param fwd Is query about FWD traffic? (Request root status).
1453  *
1454  * @return #GNUNET_YES if client is allowed to send us data.
1455  */
1456 int
1457 GCCH_get_allowed (struct CadetChannel *ch, int fwd)
1458 {
1459   struct CadetChannelReliability *rel;
1460
1461   rel = fwd ? ch->root_rel : ch->dest_rel;
1462
1463   if (NULL == rel)
1464   {
1465     /* Probably shutting down: root/dest NULL'ed to mark disconnection */
1466     GNUNET_break (GNUNET_NO != ch->destroy);
1467     return 0;
1468   }
1469
1470   return rel->client_allowed;
1471 }
1472
1473
1474 /**
1475  * Is the root client for this channel on this peer?
1476  *
1477  * @param ch Channel.
1478  * @param fwd Is this for fwd traffic?
1479  *
1480  * @return #GNUNET_YES in case it is.
1481  */
1482 int
1483 GCCH_is_origin (struct CadetChannel *ch, int fwd)
1484 {
1485   struct CadetClient *c;
1486
1487   c = fwd ? ch->root : ch->dest;
1488   return NULL != c;
1489 }
1490
1491
1492 /**
1493  * Is the destination client for this channel on this peer?
1494  *
1495  * @param ch Channel.
1496  * @param fwd Is this for fwd traffic?
1497  *
1498  * @return #GNUNET_YES in case it is.
1499  */
1500 int
1501 GCCH_is_terminal (struct CadetChannel *ch, int fwd)
1502 {
1503   struct CadetClient *c;
1504
1505   c = fwd ? ch->dest : ch->root;
1506   return NULL != c;
1507 }
1508
1509
1510 /**
1511  * Send an end-to-end ACK message for the most recent in-sequence payload.
1512  *
1513  * If channel is not reliable, do nothing.
1514  *
1515  * @param ch Channel this is about.
1516  * @param fwd Is for FWD traffic? (ACK dest->owner)
1517  */
1518 void
1519 GCCH_send_data_ack (struct CadetChannel *ch, int fwd)
1520 {
1521   struct GNUNET_CADET_DataACK msg;
1522   struct CadetChannelReliability *rel;
1523   struct CadetReliableMessage *copy;
1524   unsigned int delta;
1525   uint64_t mask;
1526   uint32_t ack;
1527
1528   if (GNUNET_NO == ch->reliable)
1529     return;
1530
1531   rel = fwd ? ch->dest_rel : ch->root_rel;
1532   ack = rel->mid_recv - 1;
1533
1534   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_DATA_ACK);
1535   msg.header.size = htons (sizeof (msg));
1536   msg.chid = htonl (ch->gid);
1537   msg.mid = htonl (ack);
1538
1539   msg.futures = 0LL;
1540   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
1541   {
1542     if (copy->type != GNUNET_MESSAGE_TYPE_CADET_DATA)
1543     {
1544       LOG (GNUNET_ERROR_TYPE_DEBUG, " Type %s, expected DATA\n",
1545            GC_m2s (copy->type));
1546       continue;
1547     }
1548     GNUNET_assert (GC_is_pid_bigger(copy->mid, ack));
1549     delta = copy->mid - (ack + 1);
1550     if (63 < delta)
1551       break;
1552     mask = 0x1LL << delta;
1553     msg.futures |= mask;
1554     LOG (GNUNET_ERROR_TYPE_DEBUG,
1555          " setting bit for %u (delta %u) (%lX) -> %lX\n",
1556          copy->mid, delta, mask, msg.futures);
1557   }
1558
1559   GCCH_send_prebuilt_message (&msg.header, ch, !fwd, NULL);
1560   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1561 }
1562
1563
1564 /**
1565  * Allow a client to send us more data, in case it was choked.
1566  *
1567  * @param ch Channel.
1568  * @param fwd Is this about FWD traffic? (Root client).
1569  */
1570 void
1571 GCCH_allow_client (struct CadetChannel *ch, int fwd)
1572 {
1573   struct CadetChannelReliability *rel;
1574   unsigned int buffer;
1575
1576   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH allow\n");
1577
1578   if (CADET_CHANNEL_READY != ch->state)
1579   {
1580     LOG (GNUNET_ERROR_TYPE_DEBUG, " channel not ready yet!\n");
1581     return;
1582   }
1583
1584   if (GNUNET_YES == ch->reliable)
1585   {
1586     rel = fwd ? ch->root_rel : ch->dest_rel;
1587     if (NULL == rel)
1588     {
1589       GNUNET_break (GNUNET_NO != ch->destroy);
1590       return;
1591     }
1592     if (NULL != rel->head_sent)
1593     {
1594       if (64 <= rel->mid_send - rel->head_sent->mid)
1595       {
1596         LOG (GNUNET_ERROR_TYPE_DEBUG, " too big MID gap! Wait for ACK.\n");
1597         return;
1598       }
1599       else
1600       {
1601         LOG (GNUNET_ERROR_TYPE_DEBUG, " gap ok: %u - %u\n",
1602              rel->head_sent->mid, rel->mid_send);
1603         struct CadetReliableMessage *aux;
1604         for (aux = rel->head_sent; NULL != aux; aux = aux->next)
1605         {
1606           LOG (GNUNET_ERROR_TYPE_DEBUG, "   - sent mid %u\n", aux->mid);
1607         }
1608       }
1609     }
1610     else
1611     {
1612       LOG (GNUNET_ERROR_TYPE_DEBUG, " head sent is NULL\n");
1613     }
1614   }
1615
1616   if (is_loopback (ch))
1617     buffer = GCCH_get_buffer (ch, fwd);
1618   else
1619     buffer = GCT_get_connections_buffer (ch->t);
1620
1621   if (0 == buffer)
1622   {
1623     LOG (GNUNET_ERROR_TYPE_DEBUG, " no buffer space.\n");
1624     return;
1625   }
1626
1627   LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space %u, allowing\n", buffer);
1628   send_client_ack (ch, fwd);
1629 }
1630
1631
1632 /**
1633  * Log channel info.
1634  *
1635  * @param ch Channel.
1636  * @param level Debug level to use.
1637  */
1638 void
1639 GCCH_debug (struct CadetChannel *ch, enum GNUNET_ErrorType level)
1640 {
1641   int do_log;
1642
1643   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
1644                                        "cadet-chn",
1645                                        __FILE__, __FUNCTION__, __LINE__);
1646   if (0 == do_log)
1647     return;
1648
1649   if (NULL == ch)
1650   {
1651     LOG2 (level, "CHN *** DEBUG NULL CHANNEL ***\n");
1652     return;
1653   }
1654   LOG2 (level, "CHN Channel %s:%X (%p)\n", GCT_2s (ch->t), ch->gid, ch);
1655   LOG2 (level, "CHN   root %p/%p\n", ch->root, ch->root_rel);
1656   if (NULL != ch->root)
1657   {
1658     LOG2 (level, "CHN   cli %s\n", GML_2s (ch->root));
1659     LOG2 (level, "CHN   ready %s\n", ch->root_rel->client_ready ? "YES" : "NO");
1660     LOG2 (level, "CHN   id %X\n", ch->lid_root);
1661     LOG2 (level, "CHN   recv %d\n", ch->root_rel->n_recv);
1662     LOG2 (level, "CHN   MID r: %d, s: %d\n",
1663           ch->root_rel->mid_recv, ch->root_rel->mid_send);
1664   }
1665   LOG2 (level, "CHN   dest %p/%p\n",
1666               ch->dest, ch->dest_rel);
1667   if (NULL != ch->dest)
1668   {
1669     LOG2 (level, "CHN   cli %s\n", GML_2s (ch->dest));
1670     LOG2 (level, "CHN   ready %s\n", ch->dest_rel->client_ready ? "YES" : "NO");
1671     LOG2 (level, "CHN   id %X\n", ch->lid_dest);
1672     LOG2 (level, "CHN   recv %d\n", ch->dest_rel->n_recv);
1673     LOG2 (level, "CHN   MID r: %d, s: %d\n",
1674           ch->dest_rel->mid_recv, ch->dest_rel->mid_send);
1675
1676   }
1677 }
1678
1679
1680 /**
1681  * Handle an ACK given by a client.
1682  *
1683  * Mark client as ready and send him any buffered data we could have for him.
1684  *
1685  * @param ch Channel.
1686  * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by dest and go BCK)
1687  */
1688 void
1689 GCCH_handle_local_ack (struct CadetChannel *ch, int fwd)
1690 {
1691   struct CadetChannelReliability *rel;
1692   struct CadetClient *c;
1693
1694   rel = fwd ? ch->dest_rel : ch->root_rel;
1695   c   = fwd ? ch->dest     : ch->root;
1696
1697   rel->client_ready = GNUNET_YES;
1698   send_client_buffered_data (ch, c, fwd);
1699
1700   if (GNUNET_YES == ch->destroy && 0 == rel->n_recv)
1701   {
1702     send_destroy (ch, GNUNET_YES);
1703     GCCH_destroy (ch);
1704     return;
1705   }
1706   /* if loopback is marked for destruction, no need to ACK to the other peer,
1707    * it requested the destruction and is already gone, therefore, else if.
1708    */
1709   else if (is_loopback (ch))
1710   {
1711     unsigned int buffer;
1712
1713     buffer = GCCH_get_buffer (ch, fwd);
1714     if (0 < buffer)
1715       GCCH_allow_client (ch, fwd);
1716
1717     return;
1718   }
1719   GCT_send_connection_acks (ch->t);
1720 }
1721
1722
1723 /**
1724  * Handle data given by a client.
1725  *
1726  * Check whether the client is allowed to send in this tunnel, save if channel
1727  * is reliable and send an ACK to the client if there is still buffer space
1728  * in the tunnel.
1729  *
1730  * @param ch Channel.
1731  * @param c Client which sent the data.
1732  * @param fwd Is this a FWD data?
1733  * @param message Data message.
1734  * @param size Size of data.
1735  *
1736  * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
1737  */
1738 int
1739 GCCH_handle_local_data (struct CadetChannel *ch,
1740                         struct CadetClient *c, int fwd,
1741                         const struct GNUNET_MessageHeader *message,
1742                         size_t size)
1743 {
1744   struct CadetChannelReliability *rel;
1745   struct GNUNET_CADET_Data *payload;
1746   uint16_t p2p_size = sizeof(struct GNUNET_CADET_Data) + size;
1747   unsigned char cbuf[p2p_size];
1748   unsigned char buffer;
1749
1750   /* Is the client in the channel? */
1751   if ( !( (fwd &&
1752            ch->root == c)
1753          ||
1754           (!fwd &&
1755            ch->dest == c) ) )
1756   {
1757     GNUNET_break_op (0);
1758     return GNUNET_SYSERR;
1759   }
1760
1761   rel = fwd ? ch->root_rel : ch->dest_rel;
1762
1763   if (GNUNET_NO == rel->client_allowed)
1764   {
1765     GNUNET_break_op (0);
1766     return GNUNET_SYSERR;
1767   }
1768
1769   rel->client_allowed = GNUNET_NO;
1770
1771   /* Ok, everything is correct, send the message. */
1772   payload = (struct GNUNET_CADET_Data *) cbuf;
1773   payload->mid = htonl (rel->mid_send);
1774   rel->mid_send++;
1775   memcpy (&payload[1], message, size);
1776   payload->header.size = htons (p2p_size);
1777   payload->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_DATA);
1778   payload->chid = htonl (ch->gid);
1779   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1780   GCCH_send_prebuilt_message (&payload->header, ch, fwd, NULL);
1781
1782   if (is_loopback (ch))
1783     buffer = GCCH_get_buffer (ch, fwd);
1784   else
1785     buffer = GCT_get_connections_buffer (ch->t);
1786
1787   if (0 < buffer)
1788     GCCH_allow_client (ch, fwd);
1789
1790   return GNUNET_OK;
1791 }
1792
1793
1794 /**
1795  * Handle a channel destroy requested by a client.
1796  *
1797  * TODO: add "reason" field
1798  *
1799  * Destroy the channel and the tunnel in case this was the last channel.
1800  *
1801  * @param ch Channel.
1802  * @param c Client that requested the destruction (to avoid notifying him).
1803  * @param is_root Is the request coming from root?
1804  */
1805 void
1806 GCCH_handle_local_destroy (struct CadetChannel *ch,
1807                            struct CadetClient *c,
1808                            int is_root)
1809 {
1810   ch->destroy = GNUNET_YES;
1811   /* Cleanup after the tunnel */
1812   if (GNUNET_NO == is_root && c == ch->dest)
1813   {
1814     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
1815     GML_client_delete_channel (c, ch, ch->lid_dest);
1816     ch->dest = NULL;
1817   }
1818   if (GNUNET_YES == is_root && c == ch->root)
1819   {
1820     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
1821     GML_client_delete_channel (c, ch, ch->lid_root);
1822     ch->root = NULL;
1823   }
1824
1825   send_destroy (ch, GNUNET_NO);
1826   if (0 == ch->pending_messages)
1827     GCCH_destroy (ch);
1828 }
1829
1830
1831 /**
1832  * Handle a channel create requested by a client.
1833  *
1834  * Create the channel and the tunnel in case this was the first0 channel.
1835  *
1836  * @param c Client that requested the creation (will be the root).
1837  * @param msg Create Channel message.
1838  *
1839  * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
1840  */
1841 int
1842 GCCH_handle_local_create (struct CadetClient *c,
1843                           struct GNUNET_CADET_ChannelMessage *msg)
1844 {
1845   struct CadetChannel *ch;
1846   struct CadetTunnel *t;
1847   struct CadetPeer *peer;
1848   CADET_ChannelNumber chid;
1849
1850   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
1851        GNUNET_i2s (&msg->peer), ntohl (msg->port));
1852   chid = ntohl (msg->channel_id);
1853
1854   /* Sanity check for duplicate channel IDs */
1855   if (NULL != GML_channel_get (c, chid))
1856   {
1857     GNUNET_break (0);
1858     return GNUNET_SYSERR;
1859   }
1860
1861   peer = GCP_get (&msg->peer, GNUNET_YES);
1862   GCP_add_tunnel (peer);
1863   t = GCP_get_tunnel (peer);
1864
1865   if (GCP_get_short_id (peer) == myid)
1866   {
1867     GCT_change_cstate (t, CADET_TUNNEL_READY);
1868   }
1869   else
1870   {
1871     /* FIXME change to a tunnel API, eliminate ch <-> peer connection */
1872     GCP_connect (peer);
1873   }
1874
1875   /* Create channel */
1876   ch = channel_new (t, c, chid);
1877   if (NULL == ch)
1878   {
1879     GNUNET_break (0);
1880     return GNUNET_SYSERR;
1881   }
1882   ch->port = ntohl (msg->port);
1883   channel_set_options (ch, ntohl (msg->opt));
1884
1885   /* In unreliable channels, we'll use the DLL to buffer BCK data */
1886   ch->root_rel = GNUNET_new (struct CadetChannelReliability);
1887   ch->root_rel->ch = ch;
1888   ch->root_rel->retry_timer = CADET_RETRANSMIT_TIME;
1889   ch->root_rel->expected_delay.rel_value_us = 0;
1890
1891   LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s\n", GCCH_2s (ch));
1892
1893   send_create (ch);
1894
1895   return GNUNET_OK;
1896 }
1897
1898
1899 /**
1900  * Handler for cadet network payload traffic.
1901  *
1902  * @param ch Channel for the message.
1903  * @param msg Unencryted data message.
1904  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1905  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1906  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1907  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1908  */
1909 void
1910 GCCH_handle_data (struct CadetChannel *ch,
1911                   const struct GNUNET_CADET_Data *msg,
1912                   int fwd)
1913 {
1914   struct CadetChannelReliability *rel;
1915   struct CadetClient *c;
1916   struct GNUNET_MessageHeader *payload_msg;
1917   uint32_t mid;
1918   uint16_t payload_type;
1919   uint16_t payload_size;
1920
1921   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1922   if (GNUNET_SYSERR == fwd)
1923   {
1924     if (is_loopback (ch))
1925     {
1926       /* It is a loopback channel after all... */
1927       GNUNET_break (0);
1928       return;
1929     }
1930     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1931   }
1932
1933   /*  Initialize FWD/BCK data */
1934   c   = fwd ? ch->dest     : ch->root;
1935   rel = fwd ? ch->dest_rel : ch->root_rel;
1936
1937   if (NULL == c)
1938   {
1939     GNUNET_break (GNUNET_NO != ch->destroy);
1940     return;
1941   }
1942
1943   if (CADET_CHANNEL_READY != ch->state)
1944   {
1945     if (GNUNET_NO == fwd)
1946     {
1947       /* If we are the root, this means the other peer has sent traffic before
1948        * receiving our ACK. Even if the SYNACK goes missing, no traffic should
1949        * be sent before the ACK.
1950        */
1951       GNUNET_break_op (0);
1952       return;
1953     }
1954     /* If we are the dest, this means that the SYNACK got to the root but
1955      * the ACK went missing. Treat this as an ACK.
1956      */
1957     channel_confirm (ch, GNUNET_NO);
1958   }
1959
1960   payload_msg = (struct GNUNET_MessageHeader *) &msg[1];
1961   payload_type = ntohs (payload_msg->type);
1962   payload_size = ntohs (payload_msg->size);
1963
1964   GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1965   GNUNET_STATISTICS_update (stats, "# bytes received", payload_size, GNUNET_NO);
1966
1967   mid = ntohl (msg->mid);
1968   LOG (GNUNET_ERROR_TYPE_INFO, "<== %s (%s %4u) on chan %s (%p) %s [%5u]\n",
1969        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_DATA), GC_m2s (payload_type), mid,
1970        GCCH_2s (ch), ch, GC_f2s (fwd), ntohs (msg->header.size));
1971
1972   if (GNUNET_NO == ch->reliable ||
1973       ( !GC_is_pid_bigger (rel->mid_recv, mid) &&
1974         GC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1975   {
1976     if (GNUNET_YES == ch->reliable)
1977     {
1978       /* Is this the exact next expected messasge? */
1979       if (mid == rel->mid_recv)
1980       {
1981         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected, sending to client\n");
1982         send_client_data (ch, msg, fwd);
1983       }
1984       else
1985       {
1986         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1987         add_buffered_data (msg, rel);
1988       }
1989     }
1990     else
1991     {
1992       /* Tunnel is unreliable: send to clients directly */
1993       /* FIXME: accept Out Of Order traffic */
1994       rel->mid_recv = mid + 1;
1995       send_client_data (ch, msg, fwd);
1996     }
1997   }
1998   else
1999   {
2000     GNUNET_STATISTICS_update (stats, "# duplicate MID", 1, GNUNET_NO);
2001     if (GC_is_pid_bigger (rel->mid_recv, mid))
2002     {
2003       GNUNET_break_op (0);
2004       LOG (GNUNET_ERROR_TYPE_INFO,
2005            "MID %u on channel %s not expected (window: %u - %u). Dropping!\n",
2006            mid, GCCH_2s (ch), rel->mid_recv, rel->mid_recv + 63);
2007     }
2008     else
2009     {
2010       LOG (GNUNET_ERROR_TYPE_INFO,
2011            "Duplicate MID %u, channel %s (expecting MID %u). Re-sending ACK!\n",
2012            mid, GCCH_2s (ch), rel->mid_recv);
2013       if (NULL != rel->uniq)
2014       {
2015         LOG (GNUNET_ERROR_TYPE_WARNING,
2016              "We are trying to send an ACK, but don't seem have the "
2017              "bandwidth. Have you set enough [ats] QUOTA in your config?\n");
2018       }
2019
2020     }
2021   }
2022
2023   GCCH_send_data_ack (ch, fwd);
2024 }
2025
2026
2027 /**
2028  * Handler for cadet network traffic end-to-end ACKs.
2029  *
2030  * @param ch Channel on which we got this message.
2031  * @param msg Data message.
2032  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2033  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2034  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2035  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2036  */
2037 void
2038 GCCH_handle_data_ack (struct CadetChannel *ch,
2039                       const struct GNUNET_CADET_DataACK *msg,
2040                       int fwd)
2041 {
2042   struct CadetChannelReliability *rel;
2043   struct CadetReliableMessage *copy;
2044   struct CadetReliableMessage *next;
2045   uint32_t ack;
2046   int work;
2047
2048   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2049   if (GNUNET_SYSERR == fwd)
2050   {
2051     if (is_loopback (ch))
2052     {
2053       /* It is a loopback channel after all... */
2054       GNUNET_break (0);
2055       return;
2056     }
2057     /* Inverted: if message came 'FWD' is a 'BCK ACK'. */
2058     fwd = (NULL != ch->dest) ? GNUNET_NO : GNUNET_YES;
2059   }
2060
2061   ack = ntohl (msg->mid);
2062   LOG (GNUNET_ERROR_TYPE_INFO,
2063        "<== %s (0x%010lX %4u) on chan %s (%p) %s [%5u]\n",
2064        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_DATA_ACK), msg->futures, ack,
2065        GCCH_2s (ch), ch, GC_f2s (fwd), ntohs (msg->header.size));
2066
2067   if (GNUNET_YES == fwd)
2068     rel = ch->root_rel;
2069   else
2070     rel = ch->dest_rel;
2071
2072   if (NULL == rel)
2073   {
2074     GNUNET_break (GNUNET_NO != ch->destroy);
2075     return;
2076   }
2077
2078   /* Free ACK'd copies: no need to retransmit those anymore FIXME refactor */
2079   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
2080   {
2081     if (GC_is_pid_bigger (copy->mid, ack))
2082     {
2083       LOG (GNUNET_ERROR_TYPE_DEBUG, "  head %u, out!\n", copy->mid);
2084       if (0 < channel_rel_free_sent (rel, msg))
2085         work = GNUNET_YES;
2086       break;
2087     }
2088     work = GNUNET_YES;
2089     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %u\n", copy->mid);
2090     next = copy->next;
2091     if (GNUNET_YES == rel_message_free (copy, GNUNET_YES))
2092     {
2093       LOG (GNUNET_ERROR_TYPE_DEBUG, " channel destoyed\n");
2094       return;
2095     }
2096   }
2097
2098   /* ACK client if needed and possible */
2099   GCCH_allow_client (ch, fwd);
2100
2101   /* If some message was free'd, update the retransmission delay */
2102   if (GNUNET_YES == work)
2103   {
2104     if (NULL != rel->retry_task)
2105     {
2106       GNUNET_SCHEDULER_cancel (rel->retry_task);
2107       rel->retry_task = NULL;
2108       if (NULL != rel->head_sent && NULL == rel->head_sent->chq)
2109       {
2110         struct GNUNET_TIME_Absolute new_target;
2111         struct GNUNET_TIME_Relative delay;
2112
2113         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
2114                                                CADET_RETRANSMIT_MARGIN);
2115         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
2116                                                delay);
2117         delay = GNUNET_TIME_absolute_get_remaining (new_target);
2118         rel->retry_task =
2119             GNUNET_SCHEDULER_add_delayed (delay,
2120                                           &channel_retransmit_message,
2121                                           rel);
2122       }
2123     }
2124     else
2125     {
2126       /* Work was done but no task was pending.
2127        * Task was cancelled by a retransmission that is sitting in the queue.
2128        */
2129       // FIXME add test to make sure this is the case, probably add return
2130       // value to GCCH_send_prebuilt_message
2131     }
2132   }
2133 }
2134
2135
2136 /**
2137  * Handler for channel create messages.
2138  *
2139  * Does not have fwd parameter because it's always 'FWD': channel is incoming.
2140  *
2141  * @param t Tunnel this channel will be in.
2142  * @param msg Channel crate message.
2143  */
2144 struct CadetChannel *
2145 GCCH_handle_create (struct CadetTunnel *t,
2146                     const struct GNUNET_CADET_ChannelCreate *msg)
2147 {
2148   CADET_ChannelNumber chid;
2149   struct CadetChannel *ch;
2150   struct CadetClient *c;
2151   int new_channel;
2152   uint32_t port;
2153
2154   chid = ntohl (msg->chid);
2155
2156   ch = GCT_get_channel (t, chid);
2157   if (NULL == ch)
2158   {
2159     /* Create channel */
2160     ch = channel_new (t, NULL, 0);
2161     ch->gid = chid;
2162     channel_set_options (ch, ntohl (msg->opt));
2163     new_channel = GNUNET_YES;
2164   }
2165   else
2166   {
2167     new_channel = GNUNET_NO;
2168   }
2169   port = ntohl (msg->port);
2170
2171   LOG (GNUNET_ERROR_TYPE_INFO,
2172        "<== %s (  0x%08X %4u) on chan %s (%p) %s [%5u]\n",
2173        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE), chid, port,
2174        GCCH_2s (ch), ch, GC_f2s (GNUNET_YES), ntohs (msg->header.size));
2175
2176   if (GNUNET_YES == new_channel || GCT_is_loopback (t))
2177   {
2178     /* Find a destination client */
2179     ch->port = port;
2180     LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", ch->port);
2181     c = GML_client_get_by_port (ch->port);
2182     if (NULL == c)
2183     {
2184       LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
2185       if (is_loopback (ch))
2186       {
2187         LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback: destroy on handler\n");
2188         send_nack (ch);
2189       }
2190       else
2191       {
2192         LOG (GNUNET_ERROR_TYPE_DEBUG, "  not loopback: destroy now\n");
2193         send_nack (ch);
2194         GCCH_destroy (ch);
2195       }
2196       return NULL;
2197     }
2198     else
2199     {
2200       LOG (GNUNET_ERROR_TYPE_DEBUG, "  client %p has port registered\n", c);
2201     }
2202
2203     add_destination (ch, c);
2204     if (GNUNET_YES == ch->reliable)
2205       LOG (GNUNET_ERROR_TYPE_DEBUG, "Reliable\n");
2206     else
2207       LOG (GNUNET_ERROR_TYPE_DEBUG, "Not Reliable\n");
2208
2209     send_client_create (ch);
2210     ch->state =  CADET_CHANNEL_SENT;
2211   }
2212   else
2213   {
2214     LOG (GNUNET_ERROR_TYPE_DEBUG, "  duplicate create channel\n");
2215     if (NULL != ch->dest_rel->retry_task)
2216     {
2217       LOG (GNUNET_ERROR_TYPE_DEBUG, "  clearing retry task\n");
2218       /* we were waiting to re-send our 'SYNACK', wait no more! */
2219       GNUNET_SCHEDULER_cancel (ch->dest_rel->retry_task);
2220       ch->dest_rel->retry_task = NULL;
2221     }
2222     else if (NULL != ch->dest_rel->uniq)
2223     {
2224       /* we are waiting to for our 'SYNACK' to leave the queue, all done! */
2225       return ch;
2226     }
2227   }
2228   send_ack (ch, GNUNET_YES);
2229
2230   return ch;
2231 }
2232
2233
2234 /**
2235  * Handler for channel NACK messages.
2236  *
2237  * NACK messages always go dest -> root, no need for 'fwd' or 'msg' parameter.
2238  *
2239  * @param ch Channel.
2240  */
2241 void
2242 GCCH_handle_nack (struct CadetChannel *ch)
2243 {
2244   LOG (GNUNET_ERROR_TYPE_INFO,
2245        "<== %s (  0x%08X %4u) on chan %s (%p) %s [%5u]\n",
2246        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK), ch->gid, 0,
2247        GCCH_2s (ch), ch, "---", 0);
2248
2249   send_client_nack (ch);
2250   GCCH_destroy (ch);
2251 }
2252
2253
2254 /**
2255  * Handler for channel ack messages.
2256  *
2257  * @param ch Channel.
2258  * @param msg Message.
2259  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2260  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2261  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2262  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2263  */
2264 void
2265 GCCH_handle_ack (struct CadetChannel *ch,
2266                  const struct GNUNET_CADET_ChannelManage *msg,
2267                  int fwd)
2268 {
2269   LOG (GNUNET_ERROR_TYPE_INFO,
2270        "<== %s (  0x%08X %4u) on chan %s (%p) %s [%5u]\n",
2271        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK), ch->gid, 0,
2272        GCCH_2s (ch), ch, GC_f2s (fwd), ntohs (msg->header.size));
2273
2274   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2275   if (GNUNET_SYSERR == fwd)
2276   {
2277     if (is_loopback (ch))
2278     {
2279       /* It is a loopback channel after all... */
2280       GNUNET_break (0);
2281       return;
2282     }
2283     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
2284   }
2285
2286   channel_confirm (ch, !fwd);
2287 }
2288
2289
2290 /**
2291  * Handler for channel destroy messages.
2292  *
2293  * @param ch Channel to be destroyed of.
2294  * @param msg Message.
2295  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2296  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2297  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2298  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2299  */
2300 void
2301 GCCH_handle_destroy (struct CadetChannel *ch,
2302                      const struct GNUNET_CADET_ChannelManage *msg,
2303                      int fwd)
2304 {
2305   struct CadetChannelReliability *rel;
2306
2307   LOG (GNUNET_ERROR_TYPE_INFO,
2308        "<== %s (  0x%08X %4u) on chan %s (%p) %s [%5u]\n",
2309        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY), ch->gid, 0,
2310        GCCH_2s (ch), ch, GC_f2s (fwd), ntohs (msg->header.size));
2311
2312   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2313   if (GNUNET_SYSERR == fwd)
2314   {
2315     if (is_loopback (ch))
2316     {
2317       /* It is a loopback channel after all... */
2318       GNUNET_break (0);
2319       return;
2320     }
2321     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
2322   }
2323
2324   GCCH_debug (ch, GNUNET_ERROR_TYPE_DEBUG);
2325   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
2326   {
2327     /* Not for us (don't destroy twice a half-open loopback channel) */
2328     return;
2329   }
2330
2331   rel = fwd ? ch->dest_rel : ch->root_rel;
2332   if (0 == rel->n_recv)
2333   {
2334     send_destroy (ch, GNUNET_YES);
2335     GCCH_destroy (ch);
2336   }
2337   else
2338   {
2339     ch->destroy = GNUNET_YES;
2340   }
2341 }
2342
2343
2344 /**
2345  * Sends an already built message on a channel.
2346  *
2347  * If the channel is on a loopback tunnel, notifies the appropriate destination
2348  * client locally.
2349  *
2350  * On a normal channel passes the message to the tunnel for encryption and
2351  * sending on a connection.
2352  *
2353  * This function DOES NOT save the message for retransmission.
2354  *
2355  * @param message Message to send. Function makes a copy of it.
2356  * @param ch Channel on which this message is transmitted.
2357  * @param fwd Is this a fwd message?
2358  * @param existing_copy This is a retransmission, don't save a copy.
2359  */
2360 void
2361 GCCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2362                             struct CadetChannel *ch, int fwd,
2363                             void *existing_copy)
2364 {
2365   struct CadetChannelQueue *chq;
2366   uint32_t data_id;
2367   uint16_t type;
2368   uint16_t size;
2369   char info[32];
2370
2371   type = ntohs (message->type);
2372   size = ntohs (message->size);
2373
2374   switch (type)
2375   {
2376     case GNUNET_MESSAGE_TYPE_CADET_DATA:
2377     {
2378       struct GNUNET_CADET_Data *data_msg;
2379       struct GNUNET_MessageHeader *payload_msg;
2380       uint16_t payload_type;
2381
2382       data_msg = (struct GNUNET_CADET_Data *) message;
2383       data_id = ntohl (data_msg->mid);
2384       payload_msg = (struct GNUNET_MessageHeader *) &data_msg[1];
2385       payload_type = ntohs (payload_msg->type);
2386       strncpy (info, GC_m2s (payload_type), 31);
2387       info[31] = '\0';
2388       break;
2389     }
2390     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2391     {
2392       struct GNUNET_CADET_DataACK *ack_msg;
2393       ack_msg = (struct GNUNET_CADET_DataACK *) message;
2394       data_id = ntohl (ack_msg->mid);
2395       SPRINTF (info, "0x%010lX", ack_msg->futures);
2396       break;
2397     }
2398     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2399     {
2400       struct GNUNET_CADET_ChannelCreate *cc_msg;
2401       cc_msg = (struct GNUNET_CADET_ChannelCreate *) message;
2402       data_id = ntohl (cc_msg->port);
2403       SPRINTF (info, "  0x%08X", ntohl (cc_msg->chid));
2404       break;
2405     }
2406     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2407     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2408     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2409     {
2410       struct GNUNET_CADET_ChannelManage *m_msg;
2411       m_msg = (struct GNUNET_CADET_ChannelManage *) message;
2412       data_id = 0;
2413       SPRINTF (info, "  0x%08X", ntohl (m_msg->chid));
2414       break;
2415     }
2416     default:
2417       data_id = 0;
2418       info[0] = '\0';
2419   }
2420   LOG (GNUNET_ERROR_TYPE_INFO,
2421        "==> %s (%12s %4u) on chan %s (%p) %s [%5u]\n",
2422        GC_m2s (type), info, data_id,
2423        GCCH_2s (ch), ch, GC_f2s (fwd), size);
2424
2425   if (GCT_is_loopback (ch->t))
2426   {
2427     handle_loopback (ch, message, fwd);
2428     return;
2429   }
2430
2431   switch (type)
2432   {
2433     case GNUNET_MESSAGE_TYPE_CADET_DATA:
2434       if (GNUNET_YES == ch->reliable)
2435       {
2436         chq = GNUNET_new (struct CadetChannelQueue);
2437         chq->type = type;
2438         if (NULL == existing_copy)
2439           chq->copy = channel_save_copy (ch, message, fwd);
2440         else
2441         {
2442           chq->copy = (struct CadetReliableMessage *) existing_copy;
2443           if (NULL != chq->copy->chq)
2444           {
2445             /* Last retransmission was queued but not yet sent!
2446              * This retransmission was scheduled by a ch_message_sent which
2447              * followed a very fast RTT, so the tiny delay made the
2448              * retransmission function to execute before the previous
2449              * retransmitted message even had a chance to leave the peer.
2450              * Cancel this message and wait until the pending
2451              * retransmission leaves the peer and ch_message_sent starts
2452              * the timer for the next one.
2453              */
2454             GNUNET_free (chq);
2455             LOG (GNUNET_ERROR_TYPE_DEBUG,
2456                  "  exisitng copy not yet transmitted!\n");
2457             return;
2458           }
2459           LOG (GNUNET_ERROR_TYPE_DEBUG,
2460                "  using existing copy: %p {r:%p q:%p t:%u}\n",
2461                existing_copy,
2462                chq->copy->rel, chq->copy->chq, chq->copy->type);
2463         }
2464         LOG (GNUNET_ERROR_TYPE_DEBUG, "  new chq: %p\n", chq);
2465         chq->copy->chq = chq;
2466         chq->tq = GCT_send_prebuilt_message (message, ch->t, NULL,
2467                                              GNUNET_YES,
2468                                              &ch_message_sent, chq);
2469         /* q itself is stored in copy */
2470         GNUNET_assert (NULL != chq->tq || GNUNET_NO != ch->destroy);
2471       }
2472       else
2473       {
2474         fire_and_forget (message, ch, GNUNET_NO);
2475       }
2476       break;
2477
2478
2479     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2480     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2481     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2482       chq = GNUNET_new (struct CadetChannelQueue);
2483       chq->type = type;
2484       chq->rel = fwd ? ch->root_rel : ch->dest_rel;
2485       if (NULL != chq->rel->uniq)
2486       {
2487         if (NULL != chq->rel->uniq->tq)
2488         {
2489           GCT_cancel (chq->rel->uniq->tq);
2490           /* ch_message_sent is called, freeing and NULLing uniq */
2491           GNUNET_break (NULL == chq->rel->uniq);
2492         }
2493         else
2494         {
2495           GNUNET_break (0);
2496           GNUNET_free (chq->rel->uniq);
2497         }
2498       }
2499
2500       chq->tq = GCT_send_prebuilt_message (message, ch->t, NULL, GNUNET_YES,
2501                                            &ch_message_sent, chq);
2502       if (NULL == chq->tq)
2503       {
2504         GNUNET_break (0);
2505         GCT_debug (ch->t, GNUNET_ERROR_TYPE_ERROR);
2506         GNUNET_free (chq);
2507         chq = NULL;
2508         return;
2509       }
2510       chq->rel->uniq = chq;
2511       break;
2512
2513
2514     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2515     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2516       fire_and_forget (message, ch, GNUNET_YES);
2517       break;
2518
2519
2520     default:
2521       GNUNET_break (0);
2522       LOG (GNUNET_ERROR_TYPE_WARNING, "type %s unknown!\n", GC_m2s (type));
2523       fire_and_forget (message, ch, GNUNET_YES);
2524   }
2525 }
2526
2527
2528 /**
2529  * Get the static string for identification of the channel.
2530  *
2531  * @param ch Channel.
2532  *
2533  * @return Static string with the channel IDs.
2534  */
2535 const char *
2536 GCCH_2s (const struct CadetChannel *ch)
2537 {
2538   static char buf[64];
2539
2540   if (NULL == ch)
2541     return "(NULL Channel)";
2542
2543   SPRINTF (buf, "%s:%u gid:%X (%X / %X)",
2544            GCT_2s (ch->t), ch->port, ch->gid, ch->lid_root, ch->lid_dest);
2545
2546   return buf;
2547 }