- Revamp traffic logging, small bugfixes, complete doxygen
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_channel.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013 Christian Grothoff (and other contributing authors)
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  * @param tc TaskContext.
725  */
726 static void
727 channel_retransmit_message (void *cls,
728                             const struct GNUNET_SCHEDULER_TaskContext *tc)
729 {
730   struct CadetChannelReliability *rel = cls;
731   struct CadetReliableMessage *copy;
732   struct CadetChannel *ch;
733   struct GNUNET_CADET_Data *payload;
734   int fwd;
735
736   rel->retry_task = NULL;
737   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
738     return;
739
740   ch = rel->ch;
741   copy = rel->head_sent;
742   if (NULL == copy)
743   {
744     GNUNET_break (0); // FIXME tripped in rps testcase
745     return;
746   }
747
748   payload = (struct GNUNET_CADET_Data *) &copy[1];
749   fwd = (rel == ch->root_rel);
750
751   /* Message not found in the queue that we are going to use. */
752   LOG (GNUNET_ERROR_TYPE_DEBUG, "RETRANSMIT MID %u\n", copy->mid);
753
754   GCCH_send_prebuilt_message (&payload->header, ch, fwd, copy);
755   GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
756 }
757
758
759 /**
760  * We haven't received an Channel ACK after a certain time: resend the CREATE.
761  *
762  * @param cls Closure (CadetChannelReliability of the channel to recreate)
763  * @param tc TaskContext.
764  */
765 static void
766 channel_recreate (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
767 {
768   struct CadetChannelReliability *rel = cls;
769
770   rel->retry_task = NULL;
771   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
772     return;
773
774   LOG (GNUNET_ERROR_TYPE_DEBUG, "RE-CREATE\n");
775   GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
776
777   if (rel == rel->ch->root_rel)
778   {
779     send_create (rel->ch);
780   }
781   else if (rel == rel->ch->dest_rel)
782   {
783     send_ack (rel->ch, GNUNET_YES);
784   }
785   else
786   {
787     GNUNET_break (0);
788   }
789
790 }
791
792
793 /**
794  * Message has been sent: start retransmission timer.
795  *
796  * @param cls Closure (queue structure).
797  * @param t Tunnel.
798  * @param q Queue handler (no longer valid).
799  * @param type Type of message.
800  * @param size Size of the message.
801  */
802 static void
803 ch_message_sent (void *cls,
804                  struct CadetTunnel *t,
805                  struct CadetTunnelQueue *q,
806                  uint16_t type, size_t size)
807 {
808   struct CadetChannelQueue *chq = cls;
809   struct CadetReliableMessage *copy = chq->copy;
810   struct CadetChannelReliability *rel;
811
812   LOG (GNUNET_ERROR_TYPE_DEBUG, "channel_message_sent callback %s\n",
813        GC_m2s (chq->type));
814
815   switch (chq->type)
816   {
817     case GNUNET_MESSAGE_TYPE_CADET_DATA:
818       LOG (GNUNET_ERROR_TYPE_DEBUG, "data MID %u sent\n", copy->mid);
819       GNUNET_assert (chq == copy->chq);
820       copy->timestamp = GNUNET_TIME_absolute_get ();
821       rel = copy->rel;
822       if (NULL == rel->retry_task)
823       {
824         LOG (GNUNET_ERROR_TYPE_DEBUG, "  scheduling retry in %d * %s\n",
825              CADET_RETRANSMIT_MARGIN,
826              GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
827                                                      GNUNET_YES));
828         if (0 != rel->expected_delay.rel_value_us)
829         {
830           rel->retry_timer =
831               GNUNET_TIME_relative_multiply (rel->expected_delay,
832                                              CADET_RETRANSMIT_MARGIN);
833         }
834         else
835         {
836           rel->retry_timer = CADET_RETRANSMIT_TIME;
837         }
838         LOG (GNUNET_ERROR_TYPE_DEBUG, "  using delay %s\n",
839              GNUNET_STRINGS_relative_time_to_string (rel->retry_timer,
840                                                      GNUNET_NO));
841         rel->retry_task =
842             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
843                                           &channel_retransmit_message, rel);
844       }
845       else
846       {
847         LOG (GNUNET_ERROR_TYPE_DEBUG, "retry running %p\n", rel->retry_task);
848       }
849       copy->chq = NULL;
850       break;
851
852
853     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
854     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
855     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
856       LOG (GNUNET_ERROR_TYPE_DEBUG, "sent %s\n", GC_m2s (chq->type));
857       rel = chq->rel;
858       GNUNET_assert (rel->uniq == chq);
859       rel->uniq = NULL;
860
861       if (CADET_CHANNEL_READY != rel->ch->state
862           && GNUNET_MESSAGE_TYPE_CADET_DATA_ACK != type
863           && GNUNET_NO == rel->ch->destroy)
864       {
865         GNUNET_assert (NULL == rel->retry_task);
866         LOG (GNUNET_ERROR_TYPE_DEBUG, "STD BACKOFF %s\n",
867              GNUNET_STRINGS_relative_time_to_string (rel->retry_timer,
868                                                      GNUNET_NO));
869         rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
870         rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
871                                                         &channel_recreate, rel);
872       }
873       break;
874
875     default:
876       GNUNET_break (0);
877   }
878
879   GNUNET_free (chq);
880 }
881
882
883 /**
884  * send a channel create message.
885  *
886  * @param ch Channel for which to send.
887  */
888 static void
889 send_create (struct CadetChannel *ch)
890 {
891   struct GNUNET_CADET_ChannelCreate msgcc;
892
893   msgcc.header.size = htons (sizeof (msgcc));
894   msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE);
895   msgcc.chid = htonl (ch->gid);
896   msgcc.port = htonl (ch->port);
897   msgcc.opt = htonl (channel_get_options (ch));
898
899   GCCH_send_prebuilt_message (&msgcc.header, ch, GNUNET_YES, NULL);
900 }
901
902
903 /**
904  * Confirm we got a channel create or FWD ack.
905  *
906  * @param ch The channel to confirm.
907  * @param fwd Should we send a FWD ACK? (going dest->root)
908  */
909 static void
910 send_ack (struct CadetChannel *ch, int fwd)
911 {
912   struct GNUNET_CADET_ChannelManage msg;
913
914   msg.header.size = htons (sizeof (msg));
915   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK);
916   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending channel %s ack for channel %s\n",
917        GC_f2s (fwd), GCCH_2s (ch));
918
919   msg.chid = htonl (ch->gid);
920   GCCH_send_prebuilt_message (&msg.header, ch, !fwd, NULL);
921 }
922
923
924 /**
925  * Send a message and don't keep any info about it: we won't need to cancel it
926  * or resend it.
927  *
928  * @param msg Header of the message to fire away.
929  * @param ch Channel on which the message should go.
930  * @param force Is this a forced (undroppable) message?
931  */
932 static void
933 fire_and_forget (const struct GNUNET_MessageHeader *msg,
934                  struct CadetChannel *ch,
935                  int force)
936 {
937   GNUNET_break (NULL == GCT_send_prebuilt_message (msg, ch->t, NULL,
938                                                    force, NULL, NULL));
939 }
940
941
942 /**
943  * Notify that a channel create didn't succeed.
944  *
945  * @param ch The channel to reject.
946  */
947 static void
948 send_nack (struct CadetChannel *ch)
949 {
950   struct GNUNET_CADET_ChannelManage msg;
951
952   msg.header.size = htons (sizeof (msg));
953   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK);
954   LOG (GNUNET_ERROR_TYPE_DEBUG,
955        "  sending channel NACK for channel %s\n",
956        GCCH_2s (ch));
957
958   msg.chid = htonl (ch->gid);
959   GCCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO, NULL);
960 }
961
962
963 /**
964  * Destroy all reliable messages queued for a channel,
965  * during a channel destruction.
966  * Frees the reliability structure itself.
967  *
968  * @param rel Reliability data for a channel.
969  */
970 static void
971 channel_rel_free_all (struct CadetChannelReliability *rel)
972 {
973   struct CadetReliableMessage *copy;
974   struct CadetReliableMessage *next;
975
976   if (NULL == rel)
977     return;
978
979   for (copy = rel->head_recv; NULL != copy; copy = next)
980   {
981     next = copy->next;
982     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
983     LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE ALL RECV %p\n", copy);
984     GNUNET_break (NULL == copy->chq);
985     GNUNET_free (copy);
986   }
987   for (copy = rel->head_sent; NULL != copy; copy = next)
988   {
989     next = copy->next;
990     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
991     LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE ALL SEND %p\n", copy);
992     if (NULL != copy->chq)
993     {
994       if (NULL != copy->chq->tq)
995       {
996         GCT_cancel (copy->chq->tq);
997         /* ch_message_sent will free copy->q */
998       }
999       else
1000       {
1001         GNUNET_free (copy->chq);
1002         GNUNET_break (0);
1003       }
1004     }
1005     GNUNET_free (copy);
1006   }
1007   if (NULL != rel->uniq && NULL != rel->uniq->tq)
1008   {
1009     GCT_cancel (rel->uniq->tq);
1010     /* ch_message_sent is called freeing uniq */
1011   }
1012   if (NULL != rel->retry_task)
1013   {
1014     GNUNET_SCHEDULER_cancel (rel->retry_task);
1015     rel->retry_task = NULL;
1016   }
1017   GNUNET_free (rel);
1018 }
1019
1020
1021 /**
1022  * Mark future messages as ACK'd.
1023  *
1024  * @param rel Reliability data.
1025  * @param msg DataACK message with a bitfield of future ACK'd messages.
1026  *
1027  * @return How many messages have been freed.
1028  */
1029 static unsigned int
1030 channel_rel_free_sent (struct CadetChannelReliability *rel,
1031                        const struct GNUNET_CADET_DataACK *msg)
1032 {
1033   struct CadetReliableMessage *copy;
1034   struct CadetReliableMessage *next;
1035   uint64_t bitfield;
1036   uint64_t mask;
1037   uint32_t mid;
1038   uint32_t target;
1039   unsigned int i;
1040   unsigned int r;
1041
1042   bitfield = msg->futures;
1043   mid = ntohl (msg->mid);
1044   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable %u %lX\n", mid, bitfield);
1045   LOG (GNUNET_ERROR_TYPE_DEBUG, " rel %p, head %p\n", rel, rel->head_sent);
1046   for (i = 0, r = 0, copy = rel->head_sent;
1047        i < 64 && NULL != copy && 0 != bitfield;
1048        i++)
1049   {
1050     LOG (GNUNET_ERROR_TYPE_DEBUG, " trying bit %u (mid %u)\n", i, mid + i + 1);
1051     mask = 0x1LL << i;
1052     if (0 == (bitfield & mask))
1053      continue;
1054
1055     LOG (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
1056     /* Bit was set, clear the bit from the bitfield */
1057     bitfield &= ~mask;
1058
1059     /* The i-th bit was set. Do we have that copy? */
1060     /* Skip copies with mid < target */
1061     target = mid + i + 1;
1062     LOG (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
1063     while (NULL != copy && GC_is_pid_bigger (target, copy->mid))
1064       copy = copy->next;
1065
1066     /* Did we run out of copies? (previously freed, it's ok) */
1067     if (NULL == copy)
1068     {
1069       LOG (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
1070       return r;
1071     }
1072
1073     /* Did we overshoot the target? (previously freed, it's ok) */
1074     if (GC_is_pid_bigger (copy->mid, target))
1075     {
1076       LOG (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
1077       i += copy->mid - target - 1;   /* MID: 90, t = 85, i += 4 (i++ later) */
1078       mask = (0x1LL << (i + 1)) - 1; /* Mask = i-th bit and all before */
1079       bitfield &= ~mask;             /* Clear all bits up to MID - 1 */
1080       continue;
1081     }
1082
1083     /* Now copy->mid == target, free it */
1084     next = copy->next;
1085     GNUNET_break (GNUNET_YES != rel_message_free (copy, GNUNET_YES));
1086     r++;
1087     copy = next;
1088   }
1089   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
1090   return r;
1091 }
1092
1093
1094 /**
1095  * Destroy a reliable message after it has been acknowledged, either by
1096  * direct mid ACK or bitfield. Updates the appropriate data structures and
1097  * timers and frees all memory.
1098  *
1099  * @param copy Message that is no longer needed: remote peer got it.
1100  * @param update_time Is the timing information relevant?
1101  *                    If this message is ACK in a batch the timing information
1102  *                    is skewed by the retransmission, count only for the
1103  *                    retransmitted message.
1104  *
1105  * @return #GNUNET_YES if channel was destroyed as a result of the call,
1106  *         #GNUNET_NO otherwise.
1107  */
1108 static int
1109 rel_message_free (struct CadetReliableMessage *copy, int update_time)
1110 {
1111   struct CadetChannelReliability *rel;
1112   struct GNUNET_TIME_Relative time;
1113
1114   rel = copy->rel;
1115   LOG (GNUNET_ERROR_TYPE_DEBUG, "Freeing %u\n", copy->mid);
1116   if (GNUNET_YES == update_time)
1117   {
1118     time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
1119     if (0 == rel->expected_delay.rel_value_us)
1120       rel->expected_delay = time;
1121     else
1122     {
1123       rel->expected_delay.rel_value_us *= 7;
1124       rel->expected_delay.rel_value_us += time.rel_value_us;
1125       rel->expected_delay.rel_value_us /= 8;
1126     }
1127     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message time %12s\n",
1128          GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
1129     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new delay    %12s\n",
1130          GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
1131                                                  GNUNET_NO));
1132     rel->retry_timer = rel->expected_delay;
1133   }
1134   else
1135   {
1136     LOG (GNUNET_ERROR_TYPE_DEBUG, "batch free, ignoring timing\n");
1137   }
1138   rel->ch->pending_messages--;
1139   if (NULL != copy->chq)
1140   {
1141     GCT_cancel (copy->chq->tq);
1142     /* copy->q is set to NULL by ch_message_sent */
1143   }
1144   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
1145   LOG (GNUNET_ERROR_TYPE_DEBUG, " free send copy MID %u at %p\n",
1146        copy->mid, copy);
1147   GNUNET_free (copy);
1148
1149   if (GNUNET_NO != rel->ch->destroy && 0 == rel->ch->pending_messages)
1150   {
1151     GCCH_destroy (rel->ch);
1152     return GNUNET_YES;
1153   }
1154   return GNUNET_NO;
1155 }
1156
1157
1158 /**
1159  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
1160  *
1161  * @param ch Channel to mark as ready.
1162  * @param fwd Was the ACK message a FWD ACK? (dest->root, SYNACK)
1163  */
1164 static void
1165 channel_confirm (struct CadetChannel *ch, int fwd)
1166 {
1167   struct CadetChannelReliability *rel;
1168   enum CadetChannelState oldstate;
1169
1170   rel = fwd ? ch->root_rel : ch->dest_rel;
1171   if (NULL == rel)
1172   {
1173     GNUNET_break (GNUNET_NO != ch->destroy);
1174     return;
1175   }
1176   LOG (GNUNET_ERROR_TYPE_DEBUG, "  channel confirm %s %s\n",
1177        GC_f2s (fwd), GCCH_2s (ch));
1178   oldstate = ch->state;
1179   ch->state = CADET_CHANNEL_READY;
1180
1181   if (CADET_CHANNEL_READY != oldstate || GNUNET_YES == is_loopback (ch))
1182   {
1183     rel->client_ready = GNUNET_YES;
1184     rel->expected_delay = rel->retry_timer;
1185     LOG (GNUNET_ERROR_TYPE_DEBUG, "  confirm retry timer %s\n",
1186          GNUNET_STRINGS_relative_time_to_string (rel->retry_timer, GNUNET_NO));
1187     if (GCT_get_connections_buffer (ch->t) > 0 || GCT_is_loopback (ch->t))
1188       send_client_ack (ch, fwd);
1189
1190     if (NULL != rel->retry_task)
1191     {
1192       GNUNET_SCHEDULER_cancel (rel->retry_task);
1193       rel->retry_task = NULL;
1194     }
1195     else if (NULL != rel->uniq)
1196     {
1197       GCT_cancel (rel->uniq->tq);
1198       /* ch_message_sent will free and NULL uniq */
1199     }
1200     else if (GNUNET_NO == is_loopback (ch))
1201     {
1202       /* We SHOULD have been trying to retransmit this! */
1203       GNUNET_break (0);
1204     }
1205   }
1206
1207   /* In case of a FWD ACK (SYNACK) send a BCK ACK (ACK). */
1208   if (GNUNET_YES == fwd)
1209     send_ack (ch, GNUNET_NO);
1210 }
1211
1212
1213 /**
1214  * Save a copy to retransmit in case it gets lost.
1215  *
1216  * Initializes all needed callbacks and timers.
1217  *
1218  * @param ch Channel this message goes on.
1219  * @param msg Message to copy.
1220  * @param fwd Is this fwd traffic?
1221  */
1222 static struct CadetReliableMessage *
1223 channel_save_copy (struct CadetChannel *ch,
1224                    const struct GNUNET_MessageHeader *msg,
1225                    int fwd)
1226 {
1227   struct CadetChannelReliability *rel;
1228   struct CadetReliableMessage *copy;
1229   uint32_t mid;
1230   uint16_t type;
1231   uint16_t size;
1232
1233   rel = fwd ? ch->root_rel : ch->dest_rel;
1234   mid = rel->mid_send - 1;
1235   type = ntohs (msg->type);
1236   size = ntohs (msg->size);
1237
1238   LOG (GNUNET_ERROR_TYPE_DEBUG, "save MID %u %s\n", mid, GC_m2s (type));
1239   copy = GNUNET_malloc (sizeof (struct CadetReliableMessage) + size);
1240   LOG (GNUNET_ERROR_TYPE_DEBUG, "  at %p\n", copy);
1241   copy->mid = mid;
1242   copy->rel = rel;
1243   copy->type = type;
1244   memcpy (&copy[1], msg, size);
1245   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
1246   ch->pending_messages++;
1247
1248   return copy;
1249 }
1250
1251
1252 /**
1253  * Create a new channel.
1254  *
1255  * @param t Tunnel this channel is in.
1256  * @param owner Client that owns the channel, NULL for foreign channels.
1257  * @param lid_root Local ID for root client.
1258  *
1259  * @return A new initialized channel. NULL on error.
1260  */
1261 static struct CadetChannel *
1262 channel_new (struct CadetTunnel *t,
1263              struct CadetClient *owner,
1264              CADET_ChannelNumber lid_root)
1265 {
1266   struct CadetChannel *ch;
1267
1268   ch = GNUNET_new (struct CadetChannel);
1269   ch->root = owner;
1270   ch->lid_root = lid_root;
1271   ch->t = t;
1272
1273   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
1274
1275   if (NULL != owner)
1276   {
1277     ch->gid = GCT_get_next_chid (t);
1278     GML_channel_add (owner, lid_root, ch);
1279   }
1280   GCT_add_channel (t, ch);
1281
1282   return ch;
1283 }
1284
1285
1286 /**
1287  * Handle a loopback message: call the appropriate handler for the message type.
1288  *
1289  * @param ch Channel this message is on.
1290  * @param msgh Message header.
1291  * @param fwd Is this FWD traffic?
1292  */
1293 void
1294 handle_loopback (struct CadetChannel *ch,
1295                  const struct GNUNET_MessageHeader *msgh,
1296                  int fwd)
1297 {
1298   uint16_t type;
1299
1300   type = ntohs (msgh->type);
1301   LOG (GNUNET_ERROR_TYPE_DEBUG,
1302        "Loopback %s %s message!\n",
1303        GC_f2s (fwd), GC_m2s (type));
1304
1305   switch (type)
1306   {
1307     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1308       /* Don't send hop ACK, wait for client to ACK */
1309       LOG (GNUNET_ERROR_TYPE_DEBUG, "SEND loopback %u (%u)\n",
1310            ntohl (((struct GNUNET_CADET_Data *) msgh)->mid), ntohs (msgh->size));
1311       GCCH_handle_data (ch, (struct GNUNET_CADET_Data *) msgh, fwd);
1312       break;
1313
1314     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1315       GCCH_handle_data_ack (ch, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1316       break;
1317
1318     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1319       GCCH_handle_create (ch->t,
1320                           (struct GNUNET_CADET_ChannelCreate *) msgh);
1321       break;
1322
1323     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1324       GCCH_handle_ack (ch,
1325                        (struct GNUNET_CADET_ChannelManage *) msgh,
1326                        fwd);
1327       break;
1328
1329     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1330       GCCH_handle_nack (ch);
1331       break;
1332
1333     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1334       GCCH_handle_destroy (ch,
1335                            (struct GNUNET_CADET_ChannelManage *) msgh,
1336                            fwd);
1337       break;
1338
1339     default:
1340       GNUNET_break_op (0);
1341       LOG (GNUNET_ERROR_TYPE_DEBUG,
1342            "end-to-end message not known (%u)\n",
1343            ntohs (msgh->type));
1344   }
1345 }
1346
1347
1348
1349 /******************************************************************************/
1350 /********************************    API    ***********************************/
1351 /******************************************************************************/
1352
1353 /**
1354  * Destroy a channel and free all resources.
1355  *
1356  * @param ch Channel to destroy.
1357  */
1358 void
1359 GCCH_destroy (struct CadetChannel *ch)
1360 {
1361   struct CadetClient *c;
1362   struct CadetTunnel *t;
1363
1364   if (NULL == ch)
1365     return;
1366   if (2 == ch->destroy)
1367     return; /* recursive call */
1368   ch->destroy = 2;
1369
1370   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
1371               GCT_2s (ch->t), ch->gid);
1372   GCCH_debug (ch, GNUNET_ERROR_TYPE_DEBUG);
1373
1374   c = ch->root;
1375   if (NULL != c)
1376   {
1377     GML_channel_remove (c, ch->lid_root, ch);
1378   }
1379
1380   c = ch->dest;
1381   if (NULL != c)
1382   {
1383     GML_channel_remove (c, ch->lid_dest, ch);
1384   }
1385
1386   channel_rel_free_all (ch->root_rel);
1387   channel_rel_free_all (ch->dest_rel);
1388
1389   t = ch->t;
1390   GCT_remove_channel (t, ch);
1391   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
1392
1393   GNUNET_free (ch);
1394   GCT_destroy_if_empty (t);
1395 }
1396
1397
1398 /**
1399  * Get the channel's public ID.
1400  *
1401  * @param ch Channel.
1402  *
1403  * @return ID used to identify the channel with the remote peer.
1404  */
1405 CADET_ChannelNumber
1406 GCCH_get_id (const struct CadetChannel *ch)
1407 {
1408   return ch->gid;
1409 }
1410
1411
1412 /**
1413  * Get the channel tunnel.
1414  *
1415  * @param ch Channel to get the tunnel from.
1416  *
1417  * @return tunnel of the channel.
1418  */
1419 struct CadetTunnel *
1420 GCCH_get_tunnel (const struct CadetChannel *ch)
1421 {
1422   return ch->t;
1423 }
1424
1425
1426 /**
1427  * Get free buffer space towards the client on a specific channel.
1428  *
1429  * @param ch Channel.
1430  * @param fwd Is query about FWD traffic?
1431  *
1432  * @return Free buffer space [0 - 64]
1433  */
1434 unsigned int
1435 GCCH_get_buffer (struct CadetChannel *ch, int fwd)
1436 {
1437   struct CadetChannelReliability *rel;
1438
1439   rel = fwd ? ch->dest_rel : ch->root_rel;
1440   LOG (GNUNET_ERROR_TYPE_DEBUG, "   get buffer, channel %s\n", GCCH_2s (ch));
1441   GCCH_debug (ch, GNUNET_ERROR_TYPE_DEBUG);
1442   /* If rel is NULL it means that the end is not yet created,
1443    * most probably is a loopback channel at the point of sending
1444    * the ChannelCreate to itself.
1445    */
1446   if (NULL == rel)
1447   {
1448     LOG (GNUNET_ERROR_TYPE_DEBUG, "  rel is NULL: max\n");
1449     return 64;
1450   }
1451
1452   LOG (GNUNET_ERROR_TYPE_DEBUG, "   n_recv %d\n", rel->n_recv);
1453   return (64 - rel->n_recv);
1454 }
1455
1456
1457 /**
1458  * Get flow control status of end point: is client allow to send?
1459  *
1460  * @param ch Channel.
1461  * @param fwd Is query about FWD traffic? (Request root status).
1462  *
1463  * @return #GNUNET_YES if client is allowed to send us data.
1464  */
1465 int
1466 GCCH_get_allowed (struct CadetChannel *ch, int fwd)
1467 {
1468   struct CadetChannelReliability *rel;
1469
1470   rel = fwd ? ch->root_rel : ch->dest_rel;
1471
1472   if (NULL == rel)
1473   {
1474     /* Probably shutting down: root/dest NULL'ed to mark disconnection */
1475     GNUNET_break (GNUNET_NO != ch->destroy);
1476     return 0;
1477   }
1478
1479   return rel->client_allowed;
1480 }
1481
1482
1483 /**
1484  * Is the root client for this channel on this peer?
1485  *
1486  * @param ch Channel.
1487  * @param fwd Is this for fwd traffic?
1488  *
1489  * @return #GNUNET_YES in case it is.
1490  */
1491 int
1492 GCCH_is_origin (struct CadetChannel *ch, int fwd)
1493 {
1494   struct CadetClient *c;
1495
1496   c = fwd ? ch->root : ch->dest;
1497   return NULL != c;
1498 }
1499
1500
1501 /**
1502  * Is the destination client for this channel on this peer?
1503  *
1504  * @param ch Channel.
1505  * @param fwd Is this for fwd traffic?
1506  *
1507  * @return #GNUNET_YES in case it is.
1508  */
1509 int
1510 GCCH_is_terminal (struct CadetChannel *ch, int fwd)
1511 {
1512   struct CadetClient *c;
1513
1514   c = fwd ? ch->dest : ch->root;
1515   return NULL != c;
1516 }
1517
1518
1519 /**
1520  * Send an end-to-end ACK message for the most recent in-sequence payload.
1521  *
1522  * If channel is not reliable, do nothing.
1523  *
1524  * @param ch Channel this is about.
1525  * @param fwd Is for FWD traffic? (ACK dest->owner)
1526  */
1527 void
1528 GCCH_send_data_ack (struct CadetChannel *ch, int fwd)
1529 {
1530   struct GNUNET_CADET_DataACK msg;
1531   struct CadetChannelReliability *rel;
1532   struct CadetReliableMessage *copy;
1533   unsigned int delta;
1534   uint64_t mask;
1535   uint32_t ack;
1536
1537   if (GNUNET_NO == ch->reliable)
1538     return;
1539
1540   rel = fwd ? ch->dest_rel : ch->root_rel;
1541   ack = rel->mid_recv - 1;
1542
1543   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_DATA_ACK);
1544   msg.header.size = htons (sizeof (msg));
1545   msg.chid = htonl (ch->gid);
1546   msg.mid = htonl (ack);
1547
1548   msg.futures = 0LL;
1549   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
1550   {
1551     if (copy->type != GNUNET_MESSAGE_TYPE_CADET_DATA)
1552     {
1553       LOG (GNUNET_ERROR_TYPE_DEBUG, " Type %s, expected DATA\n",
1554            GC_m2s (copy->type));
1555       continue;
1556     }
1557     GNUNET_assert (GC_is_pid_bigger(copy->mid, ack));
1558     delta = copy->mid - (ack + 1);
1559     if (63 < delta)
1560       break;
1561     mask = 0x1LL << delta;
1562     msg.futures |= mask;
1563     LOG (GNUNET_ERROR_TYPE_DEBUG,
1564          " setting bit for %u (delta %u) (%lX) -> %lX\n",
1565          copy->mid, delta, mask, msg.futures);
1566   }
1567
1568   GCCH_send_prebuilt_message (&msg.header, ch, !fwd, NULL);
1569   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1570 }
1571
1572
1573 /**
1574  * Allow a client to send us more data, in case it was choked.
1575  *
1576  * @param ch Channel.
1577  * @param fwd Is this about FWD traffic? (Root client).
1578  */
1579 void
1580 GCCH_allow_client (struct CadetChannel *ch, int fwd)
1581 {
1582   struct CadetChannelReliability *rel;
1583   unsigned int buffer;
1584
1585   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH allow\n");
1586
1587   if (CADET_CHANNEL_READY != ch->state)
1588   {
1589     LOG (GNUNET_ERROR_TYPE_DEBUG, " channel not ready yet!\n");
1590     return;
1591   }
1592
1593   if (GNUNET_YES == ch->reliable)
1594   {
1595     rel = fwd ? ch->root_rel : ch->dest_rel;
1596     if (NULL == rel)
1597     {
1598       GNUNET_break (GNUNET_NO != ch->destroy);
1599       return;
1600     }
1601     if (NULL != rel->head_sent)
1602     {
1603       if (64 <= rel->mid_send - rel->head_sent->mid)
1604       {
1605         LOG (GNUNET_ERROR_TYPE_DEBUG, " too big MID gap! Wait for ACK.\n");
1606         return;
1607       }
1608       else
1609       {
1610         LOG (GNUNET_ERROR_TYPE_DEBUG, " gap ok: %u - %u\n",
1611              rel->head_sent->mid, rel->mid_send);
1612         struct CadetReliableMessage *aux;
1613         for (aux = rel->head_sent; NULL != aux; aux = aux->next)
1614         {
1615           LOG (GNUNET_ERROR_TYPE_DEBUG, "   - sent mid %u\n", aux->mid);
1616         }
1617       }
1618     }
1619     else
1620     {
1621       LOG (GNUNET_ERROR_TYPE_DEBUG, " head sent is NULL\n");
1622     }
1623   }
1624
1625   if (is_loopback (ch))
1626     buffer = GCCH_get_buffer (ch, fwd);
1627   else
1628     buffer = GCT_get_connections_buffer (ch->t);
1629
1630   if (0 == buffer)
1631   {
1632     LOG (GNUNET_ERROR_TYPE_DEBUG, " no buffer space.\n");
1633     return;
1634   }
1635
1636   LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space %u, allowing\n", buffer);
1637   send_client_ack (ch, fwd);
1638 }
1639
1640
1641 /**
1642  * Log channel info.
1643  *
1644  * @param ch Channel.
1645  * @param level Debug level to use.
1646  */
1647 void
1648 GCCH_debug (struct CadetChannel *ch, enum GNUNET_ErrorType level)
1649 {
1650   int do_log;
1651
1652   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
1653                                        "cadet-chn",
1654                                        __FILE__, __FUNCTION__, __LINE__);
1655   if (0 == do_log)
1656     return;
1657
1658   if (NULL == ch)
1659   {
1660     LOG2 (level, "CHN *** DEBUG NULL CHANNEL ***\n");
1661     return;
1662   }
1663   LOG2 (level, "CHN Channel %s:%X (%p)\n", GCT_2s (ch->t), ch->gid, ch);
1664   LOG2 (level, "CHN   root %p/%p\n", ch->root, ch->root_rel);
1665   if (NULL != ch->root)
1666   {
1667     LOG2 (level, "CHN   cli %s\n", GML_2s (ch->root));
1668     LOG2 (level, "CHN   ready %s\n", ch->root_rel->client_ready ? "YES" : "NO");
1669     LOG2 (level, "CHN   id %X\n", ch->lid_root);
1670     LOG2 (level, "CHN   recv %d\n", ch->root_rel->n_recv);
1671     LOG2 (level, "CHN   MID r: %d, s: %d\n",
1672           ch->root_rel->mid_recv, ch->root_rel->mid_send);
1673   }
1674   LOG2 (level, "CHN   dest %p/%p\n",
1675               ch->dest, ch->dest_rel);
1676   if (NULL != ch->dest)
1677   {
1678     LOG2 (level, "CHN   cli %s\n", GML_2s (ch->dest));
1679     LOG2 (level, "CHN   ready %s\n", ch->dest_rel->client_ready ? "YES" : "NO");
1680     LOG2 (level, "CHN   id %X\n", ch->lid_dest);
1681     LOG2 (level, "CHN   recv %d\n", ch->dest_rel->n_recv);
1682     LOG2 (level, "CHN   MID r: %d, s: %d\n",
1683           ch->dest_rel->mid_recv, ch->dest_rel->mid_send);
1684
1685   }
1686 }
1687
1688
1689 /**
1690  * Handle an ACK given by a client.
1691  *
1692  * Mark client as ready and send him any buffered data we could have for him.
1693  *
1694  * @param ch Channel.
1695  * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by dest and go BCK)
1696  */
1697 void
1698 GCCH_handle_local_ack (struct CadetChannel *ch, int fwd)
1699 {
1700   struct CadetChannelReliability *rel;
1701   struct CadetClient *c;
1702
1703   rel = fwd ? ch->dest_rel : ch->root_rel;
1704   c   = fwd ? ch->dest     : ch->root;
1705
1706   rel->client_ready = GNUNET_YES;
1707   send_client_buffered_data (ch, c, fwd);
1708
1709   if (GNUNET_YES == ch->destroy && 0 == rel->n_recv)
1710   {
1711     send_destroy (ch, GNUNET_YES);
1712     GCCH_destroy (ch);
1713     return;
1714   }
1715   /* if loopback is marked for destruction, no need to ACK to the other peer,
1716    * it requested the destruction and is already gone, therefore, else if.
1717    */
1718   else if (is_loopback (ch))
1719   {
1720     unsigned int buffer;
1721
1722     buffer = GCCH_get_buffer (ch, fwd);
1723     if (0 < buffer)
1724       GCCH_allow_client (ch, fwd);
1725
1726     return;
1727   }
1728   GCT_send_connection_acks (ch->t);
1729 }
1730
1731
1732 /**
1733  * Handle data given by a client.
1734  *
1735  * Check whether the client is allowed to send in this tunnel, save if channel
1736  * is reliable and send an ACK to the client if there is still buffer space
1737  * in the tunnel.
1738  *
1739  * @param ch Channel.
1740  * @param c Client which sent the data.
1741  * @param fwd Is this a FWD data?
1742  * @param message Data message.
1743  * @param size Size of data.
1744  *
1745  * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
1746  */
1747 int
1748 GCCH_handle_local_data (struct CadetChannel *ch,
1749                         struct CadetClient *c, int fwd,
1750                         const struct GNUNET_MessageHeader *message,
1751                         size_t size)
1752 {
1753   struct CadetChannelReliability *rel;
1754   struct GNUNET_CADET_Data *payload;
1755   uint16_t p2p_size = sizeof(struct GNUNET_CADET_Data) + size;
1756   unsigned char cbuf[p2p_size];
1757   unsigned char buffer;
1758
1759   /* Is the client in the channel? */
1760   if ( !( (fwd &&
1761            ch->root == c)
1762          ||
1763           (!fwd &&
1764            ch->dest == c) ) )
1765   {
1766     GNUNET_break_op (0);
1767     return GNUNET_SYSERR;
1768   }
1769
1770   rel = fwd ? ch->root_rel : ch->dest_rel;
1771
1772   if (GNUNET_NO == rel->client_allowed)
1773   {
1774     GNUNET_break_op (0);
1775     return GNUNET_SYSERR;
1776   }
1777
1778   rel->client_allowed = GNUNET_NO;
1779
1780   /* Ok, everything is correct, send the message. */
1781   payload = (struct GNUNET_CADET_Data *) cbuf;
1782   payload->mid = htonl (rel->mid_send);
1783   rel->mid_send++;
1784   memcpy (&payload[1], message, size);
1785   payload->header.size = htons (p2p_size);
1786   payload->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_DATA);
1787   payload->chid = htonl (ch->gid);
1788   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1789   GCCH_send_prebuilt_message (&payload->header, ch, fwd, NULL);
1790
1791   if (is_loopback (ch))
1792     buffer = GCCH_get_buffer (ch, fwd);
1793   else
1794     buffer = GCT_get_connections_buffer (ch->t);
1795
1796   if (0 < buffer)
1797     GCCH_allow_client (ch, fwd);
1798
1799   return GNUNET_OK;
1800 }
1801
1802
1803 /**
1804  * Handle a channel destroy requested by a client.
1805  *
1806  * TODO: add "reason" field
1807  *
1808  * Destroy the channel and the tunnel in case this was the last channel.
1809  *
1810  * @param ch Channel.
1811  * @param c Client that requested the destruction (to avoid notifying him).
1812  * @param is_root Is the request coming from root?
1813  */
1814 void
1815 GCCH_handle_local_destroy (struct CadetChannel *ch,
1816                            struct CadetClient *c,
1817                            int is_root)
1818 {
1819   ch->destroy = GNUNET_YES;
1820   /* Cleanup after the tunnel */
1821   if (GNUNET_NO == is_root && c == ch->dest)
1822   {
1823     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
1824     GML_client_delete_channel (c, ch, ch->lid_dest);
1825     ch->dest = NULL;
1826   }
1827   if (GNUNET_YES == is_root && c == ch->root)
1828   {
1829     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
1830     GML_client_delete_channel (c, ch, ch->lid_root);
1831     ch->root = NULL;
1832   }
1833
1834   send_destroy (ch, GNUNET_NO);
1835   if (0 == ch->pending_messages)
1836     GCCH_destroy (ch);
1837 }
1838
1839
1840 /**
1841  * Handle a channel create requested by a client.
1842  *
1843  * Create the channel and the tunnel in case this was the first0 channel.
1844  *
1845  * @param c Client that requested the creation (will be the root).
1846  * @param msg Create Channel message.
1847  *
1848  * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
1849  */
1850 int
1851 GCCH_handle_local_create (struct CadetClient *c,
1852                           struct GNUNET_CADET_ChannelMessage *msg)
1853 {
1854   struct CadetChannel *ch;
1855   struct CadetTunnel *t;
1856   struct CadetPeer *peer;
1857   CADET_ChannelNumber chid;
1858
1859   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
1860        GNUNET_i2s (&msg->peer), ntohl (msg->port));
1861   chid = ntohl (msg->channel_id);
1862
1863   /* Sanity check for duplicate channel IDs */
1864   if (NULL != GML_channel_get (c, chid))
1865   {
1866     GNUNET_break (0);
1867     return GNUNET_SYSERR;
1868   }
1869
1870   peer = GCP_get (&msg->peer, GNUNET_YES);
1871   GCP_add_tunnel (peer);
1872   t = GCP_get_tunnel (peer);
1873
1874   if (GCP_get_short_id (peer) == myid)
1875   {
1876     GCT_change_cstate (t, CADET_TUNNEL_READY);
1877   }
1878   else
1879   {
1880     /* FIXME change to a tunnel API, eliminate ch <-> peer connection */
1881     GCP_connect (peer);
1882   }
1883
1884   /* Create channel */
1885   ch = channel_new (t, c, chid);
1886   if (NULL == ch)
1887   {
1888     GNUNET_break (0);
1889     return GNUNET_SYSERR;
1890   }
1891   ch->port = ntohl (msg->port);
1892   channel_set_options (ch, ntohl (msg->opt));
1893
1894   /* In unreliable channels, we'll use the DLL to buffer BCK data */
1895   ch->root_rel = GNUNET_new (struct CadetChannelReliability);
1896   ch->root_rel->ch = ch;
1897   ch->root_rel->retry_timer = CADET_RETRANSMIT_TIME;
1898   ch->root_rel->expected_delay.rel_value_us = 0;
1899
1900   LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s\n", GCCH_2s (ch));
1901
1902   send_create (ch);
1903
1904   return GNUNET_OK;
1905 }
1906
1907
1908 /**
1909  * Handler for cadet network payload traffic.
1910  *
1911  * @param ch Channel for the message.
1912  * @param msg Unencryted data message.
1913  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1914  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1915  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1916  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1917  */
1918 void
1919 GCCH_handle_data (struct CadetChannel *ch,
1920                   const struct GNUNET_CADET_Data *msg,
1921                   int fwd)
1922 {
1923   struct CadetChannelReliability *rel;
1924   struct CadetClient *c;
1925   struct GNUNET_MessageHeader *payload_msg;
1926   uint32_t mid;
1927   uint16_t payload_type;
1928   uint16_t payload_size;
1929
1930   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1931   if (GNUNET_SYSERR == fwd)
1932   {
1933     if (is_loopback (ch))
1934     {
1935       /* It is a loopback channel after all... */
1936       GNUNET_break (0);
1937       return;
1938     }
1939     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1940   }
1941
1942   /*  Initialize FWD/BCK data */
1943   c   = fwd ? ch->dest     : ch->root;
1944   rel = fwd ? ch->dest_rel : ch->root_rel;
1945
1946   if (NULL == c)
1947   {
1948     GNUNET_break (GNUNET_NO != ch->destroy);
1949     return;
1950   }
1951
1952   if (CADET_CHANNEL_READY != ch->state)
1953   {
1954     if (GNUNET_NO == fwd)
1955     {
1956       /* If we are the root, this means the other peer has sent traffic before
1957        * receiving our ACK. Even if the SYNACK goes missing, no traffic should
1958        * be sent before the ACK.
1959        */
1960       GNUNET_break_op (0);
1961       return;
1962     }
1963     /* If we are the dest, this means that the SYNACK got to the root but
1964      * the ACK went missing. Treat this as an ACK.
1965      */
1966     channel_confirm (ch, GNUNET_NO);
1967   }
1968
1969   payload_msg = (struct GNUNET_MessageHeader *) &msg[1];
1970   payload_type = ntohs (payload_msg->type);
1971   payload_size = ntohs (payload_msg->size);
1972
1973   GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
1974   GNUNET_STATISTICS_update (stats, "# bytes received", payload_size, GNUNET_NO);
1975
1976   mid = ntohl (msg->mid);
1977   LOG (GNUNET_ERROR_TYPE_INFO, "<== %s (%s %4u) on chan %s (%p) %s [%5u]\n",
1978        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_DATA), GC_m2s (payload_type), mid,
1979        GCCH_2s (ch), ch, GC_f2s (fwd), ntohs (msg->header.size));
1980
1981   if (GNUNET_NO == ch->reliable ||
1982       ( !GC_is_pid_bigger (rel->mid_recv, mid) &&
1983         GC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1984   {
1985     if (GNUNET_YES == ch->reliable)
1986     {
1987       /* Is this the exact next expected messasge? */
1988       if (mid == rel->mid_recv)
1989       {
1990         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected, sending to client\n");
1991         send_client_data (ch, msg, fwd);
1992       }
1993       else
1994       {
1995         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1996         add_buffered_data (msg, rel);
1997       }
1998     }
1999     else
2000     {
2001       /* Tunnel is unreliable: send to clients directly */
2002       /* FIXME: accept Out Of Order traffic */
2003       rel->mid_recv = mid + 1;
2004       send_client_data (ch, msg, fwd);
2005     }
2006   }
2007   else
2008   {
2009     GNUNET_STATISTICS_update (stats, "# duplicate MID", 1, GNUNET_NO);
2010     if (GC_is_pid_bigger (rel->mid_recv, mid))
2011     {
2012       GNUNET_break_op (0);
2013       LOG (GNUNET_ERROR_TYPE_INFO,
2014           "MID %u on channel %s not expected (window: %u - %u). Dropping!\n",
2015           mid, GCCH_2s (ch), rel->mid_recv, rel->mid_recv + 63);
2016     }
2017     else
2018     {
2019       LOG (GNUNET_ERROR_TYPE_INFO,
2020            "Duplicate MID %u, channel %s (expecting MID %u). Re-sending ACK!\n",
2021            mid, GCCH_2s (ch), rel->mid_recv);
2022       if (NULL != rel->uniq)
2023       {
2024         LOG (GNUNET_ERROR_TYPE_WARNING,
2025             "We are trying to send an ACK, but don't seem have the "
2026             "bandwidth. Try to increase your [ats] QUOTA in you config file\n");
2027       }
2028
2029     }
2030   }
2031
2032   GCCH_send_data_ack (ch, fwd);
2033 }
2034
2035
2036 /**
2037  * Handler for cadet network traffic end-to-end ACKs.
2038  *
2039  * @param ch Channel on which we got this message.
2040  * @param msg Data message.
2041  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2042  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2043  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2044  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2045  */
2046 void
2047 GCCH_handle_data_ack (struct CadetChannel *ch,
2048                       const struct GNUNET_CADET_DataACK *msg,
2049                       int fwd)
2050 {
2051   struct CadetChannelReliability *rel;
2052   struct CadetReliableMessage *copy;
2053   struct CadetReliableMessage *next;
2054   uint32_t ack;
2055   int work;
2056
2057   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2058   if (GNUNET_SYSERR == fwd)
2059   {
2060     if (is_loopback (ch))
2061     {
2062       /* It is a loopback channel after all... */
2063       GNUNET_break (0);
2064       return;
2065     }
2066     /* Inverted: if message came 'FWD' is a 'BCK ACK'. */
2067     fwd = (NULL != ch->dest) ? GNUNET_NO : GNUNET_YES;
2068   }
2069
2070   ack = ntohl (msg->mid);
2071   LOG (GNUNET_ERROR_TYPE_INFO,
2072        "<== %s (0x%010lX %4u) on chan %s (%p) %s [%5u]\n",
2073        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_DATA_ACK), msg->futures, ack,
2074        GCCH_2s (ch), ch, GC_f2s (fwd), ntohs (msg->header.size));
2075
2076   if (GNUNET_YES == fwd)
2077     rel = ch->root_rel;
2078   else
2079     rel = ch->dest_rel;
2080
2081   if (NULL == rel)
2082   {
2083     GNUNET_break (GNUNET_NO != ch->destroy);
2084     return;
2085   }
2086
2087   /* Free ACK'd copies: no need to retransmit those anymore FIXME refactor */
2088   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
2089   {
2090     if (GC_is_pid_bigger (copy->mid, ack))
2091     {
2092       LOG (GNUNET_ERROR_TYPE_DEBUG, "  head %u, out!\n", copy->mid);
2093       if (0 < channel_rel_free_sent (rel, msg))
2094         work = GNUNET_YES;
2095       break;
2096     }
2097     work = GNUNET_YES;
2098     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %u\n", copy->mid);
2099     next = copy->next;
2100     if (GNUNET_YES == rel_message_free (copy, GNUNET_YES))
2101     {
2102       LOG (GNUNET_ERROR_TYPE_DEBUG, " channel destoyed\n");
2103       return;
2104     }
2105   }
2106
2107   /* ACK client if needed and possible */
2108   GCCH_allow_client (ch, fwd);
2109
2110   /* If some message was free'd, update the retransmission delay */
2111   if (GNUNET_YES == work)
2112   {
2113     if (NULL != rel->retry_task)
2114     {
2115       GNUNET_SCHEDULER_cancel (rel->retry_task);
2116       rel->retry_task = NULL;
2117       if (NULL != rel->head_sent && NULL == rel->head_sent->chq)
2118       {
2119         struct GNUNET_TIME_Absolute new_target;
2120         struct GNUNET_TIME_Relative delay;
2121
2122         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
2123                                                CADET_RETRANSMIT_MARGIN);
2124         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
2125                                                delay);
2126         delay = GNUNET_TIME_absolute_get_remaining (new_target);
2127         rel->retry_task =
2128             GNUNET_SCHEDULER_add_delayed (delay,
2129                                           &channel_retransmit_message,
2130                                           rel);
2131       }
2132     }
2133     else
2134     {
2135       /* Work was done but no task was pending.
2136        * Task was cancelled by a retransmission that is sitting in the queue.
2137        */
2138       // FIXME add test to make sure this is the case, probably add return
2139       // value to GCCH_send_prebuilt_message
2140     }
2141   }
2142 }
2143
2144
2145 /**
2146  * Handler for channel create messages.
2147  *
2148  * Does not have fwd parameter because it's always 'FWD': channel is incoming.
2149  *
2150  * @param t Tunnel this channel will be in.
2151  * @param msg Channel crate message.
2152  */
2153 struct CadetChannel *
2154 GCCH_handle_create (struct CadetTunnel *t,
2155                     const struct GNUNET_CADET_ChannelCreate *msg)
2156 {
2157   CADET_ChannelNumber chid;
2158   struct CadetChannel *ch;
2159   struct CadetClient *c;
2160   int new_channel;
2161   uint32_t port;
2162
2163   chid = ntohl (msg->chid);
2164
2165   ch = GCT_get_channel (t, chid);
2166   if (NULL == ch)
2167   {
2168     /* Create channel */
2169     ch = channel_new (t, NULL, 0);
2170     ch->gid = chid;
2171     channel_set_options (ch, ntohl (msg->opt));
2172     new_channel = GNUNET_YES;
2173   }
2174   else
2175   {
2176     new_channel = GNUNET_NO;
2177   }
2178   port = ntohl (msg->port);
2179
2180   LOG (GNUNET_ERROR_TYPE_INFO,
2181        "<== %s (  0x%08X %4u) on chan %s (%p) %s [%5u]\n",
2182        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE), chid, port,
2183        GCCH_2s (ch), ch, GC_f2s (GNUNET_YES), ntohs (msg->header.size));
2184
2185   if (GNUNET_YES == new_channel || GCT_is_loopback (t))
2186   {
2187     /* Find a destination client */
2188     ch->port = port;
2189     LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", ch->port);
2190     c = GML_client_get_by_port (ch->port);
2191     if (NULL == c)
2192     {
2193       LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
2194       if (is_loopback (ch))
2195       {
2196         LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback: destroy on handler\n");
2197         send_nack (ch);
2198       }
2199       else
2200       {
2201         LOG (GNUNET_ERROR_TYPE_DEBUG, "  not loopback: destroy now\n");
2202         send_nack (ch);
2203         GCCH_destroy (ch);
2204       }
2205       return NULL;
2206     }
2207     else
2208     {
2209       LOG (GNUNET_ERROR_TYPE_DEBUG, "  client %p has port registered\n", c);
2210     }
2211
2212     add_destination (ch, c);
2213     if (GNUNET_YES == ch->reliable)
2214       LOG (GNUNET_ERROR_TYPE_DEBUG, "Reliable\n");
2215     else
2216       LOG (GNUNET_ERROR_TYPE_DEBUG, "Not Reliable\n");
2217
2218     send_client_create (ch);
2219     ch->state =  CADET_CHANNEL_SENT;
2220   }
2221   else
2222   {
2223     LOG (GNUNET_ERROR_TYPE_DEBUG, "  duplicate create channel\n");
2224     if (NULL != ch->dest_rel->retry_task)
2225     {
2226       LOG (GNUNET_ERROR_TYPE_DEBUG, "  clearing retry task\n");
2227       /* we were waiting to re-send our 'SYNACK', wait no more! */
2228       GNUNET_SCHEDULER_cancel (ch->dest_rel->retry_task);
2229       ch->dest_rel->retry_task = NULL;
2230     }
2231     else if (NULL != ch->dest_rel->uniq)
2232     {
2233       /* we are waiting to for our 'SYNACK' to leave the queue, all done! */
2234       return ch;
2235     }
2236   }
2237   send_ack (ch, GNUNET_YES);
2238
2239   return ch;
2240 }
2241
2242
2243 /**
2244  * Handler for channel NACK messages.
2245  *
2246  * NACK messages always go dest -> root, no need for 'fwd' or 'msg' parameter.
2247  *
2248  * @param ch Channel.
2249  */
2250 void
2251 GCCH_handle_nack (struct CadetChannel *ch)
2252 {
2253   LOG (GNUNET_ERROR_TYPE_INFO,
2254        "<== %s (  0x%08X %4u) on chan %s (%p) %s [%5u]\n",
2255        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK), ch->gid, 0,
2256        GCCH_2s (ch), ch, "---", 0);
2257
2258   send_client_nack (ch);
2259   GCCH_destroy (ch);
2260 }
2261
2262
2263 /**
2264  * Handler for channel ack messages.
2265  *
2266  * @param ch Channel.
2267  * @param msg Message.
2268  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2269  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2270  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2271  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2272  */
2273 void
2274 GCCH_handle_ack (struct CadetChannel *ch,
2275                  const struct GNUNET_CADET_ChannelManage *msg,
2276                  int fwd)
2277 {
2278   LOG (GNUNET_ERROR_TYPE_INFO,
2279        "<== %s (  0x%08X %4u) on chan %s (%p) %s [%5u]\n",
2280        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK), ch->gid, 0,
2281        GCCH_2s (ch), ch, GC_f2s (fwd), ntohs (msg->header.size));
2282
2283   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2284   if (GNUNET_SYSERR == fwd)
2285   {
2286     if (is_loopback (ch))
2287     {
2288       /* It is a loopback channel after all... */
2289       GNUNET_break (0);
2290       return;
2291     }
2292     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
2293   }
2294
2295   channel_confirm (ch, !fwd);
2296 }
2297
2298
2299 /**
2300  * Handler for channel destroy messages.
2301  *
2302  * @param ch Channel to be destroyed of.
2303  * @param msg Message.
2304  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2305  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2306  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2307  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2308  */
2309 void
2310 GCCH_handle_destroy (struct CadetChannel *ch,
2311                      const struct GNUNET_CADET_ChannelManage *msg,
2312                      int fwd)
2313 {
2314   struct CadetChannelReliability *rel;
2315
2316   LOG (GNUNET_ERROR_TYPE_INFO,
2317        "<== %s (  0x%08X %4u) on chan %s (%p) %s [%5u]\n",
2318        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY), ch->gid, 0,
2319        GCCH_2s (ch), ch, GC_f2s (fwd), ntohs (msg->header.size));
2320
2321   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2322   if (GNUNET_SYSERR == fwd)
2323   {
2324     if (is_loopback (ch))
2325     {
2326       /* It is a loopback channel after all... */
2327       GNUNET_break (0);
2328       return;
2329     }
2330     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
2331   }
2332
2333   GCCH_debug (ch, GNUNET_ERROR_TYPE_DEBUG);
2334   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
2335   {
2336     /* Not for us (don't destroy twice a half-open loopback channel) */
2337     return;
2338   }
2339
2340   rel = fwd ? ch->dest_rel : ch->root_rel;
2341   if (0 == rel->n_recv)
2342   {
2343     send_destroy (ch, GNUNET_YES);
2344     GCCH_destroy (ch);
2345   }
2346   else
2347   {
2348     ch->destroy = GNUNET_YES;
2349   }
2350 }
2351
2352
2353 /**
2354  * Sends an already built message on a channel.
2355  *
2356  * If the channel is on a loopback tunnel, notifies the appropriate destination
2357  * client locally.
2358  *
2359  * On a normal channel passes the message to the tunnel for encryption and
2360  * sending on a connection.
2361  *
2362  * This function DOES NOT save the message for retransmission.
2363  *
2364  * @param message Message to send. Function makes a copy of it.
2365  * @param ch Channel on which this message is transmitted.
2366  * @param fwd Is this a fwd message?
2367  * @param existing_copy This is a retransmission, don't save a copy.
2368  */
2369 void
2370 GCCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2371                             struct CadetChannel *ch, int fwd,
2372                             void *existing_copy)
2373 {
2374   struct CadetChannelQueue *chq;
2375   uint32_t data_id;
2376   uint16_t type;
2377   uint16_t size;
2378   char info[32];
2379
2380   type = ntohs (message->type);
2381   size = ntohs (message->size);
2382
2383   switch (type)
2384   {
2385     case GNUNET_MESSAGE_TYPE_CADET_DATA:
2386     {
2387       struct GNUNET_CADET_Data *data_msg;
2388       struct GNUNET_MessageHeader *payload_msg;
2389       uint16_t payload_type;
2390
2391       data_msg = (struct GNUNET_CADET_Data *) message;
2392       data_id = ntohl (data_msg->mid);
2393       payload_msg = (struct GNUNET_MessageHeader *) &data_msg[1];
2394       payload_type = ntohs (payload_msg->type);
2395       strncpy (info, GC_m2s (payload_type), 31);
2396       info[31] = '\0';
2397       break;
2398     }
2399     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2400     {
2401       struct GNUNET_CADET_DataACK *ack_msg;
2402       ack_msg = (struct GNUNET_CADET_DataACK *) message;
2403       data_id = ntohl (ack_msg->mid);
2404       SPRINTF (info, "0x%010lX", ack_msg->futures);
2405       break;
2406     }
2407     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2408     {
2409       struct GNUNET_CADET_ChannelCreate *cc_msg;
2410       cc_msg = (struct GNUNET_CADET_ChannelCreate *) message;
2411       data_id = ntohl (cc_msg->port);
2412       SPRINTF (info, "  0x%08X", ntohl (cc_msg->chid));
2413       break;
2414     }
2415     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2416     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2417     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2418     {
2419       struct GNUNET_CADET_ChannelManage *m_msg;
2420       m_msg = (struct GNUNET_CADET_ChannelManage *) message;
2421       data_id = 0;
2422       SPRINTF (info, "  0x%08X", ntohl (m_msg->chid));
2423       break;
2424     }
2425     default:
2426       data_id = 0;
2427       info[0] = '\0';
2428   }
2429   LOG (GNUNET_ERROR_TYPE_INFO,
2430        "==> %s (%12s %4u) on chan %s (%p) %s [%5u]\n",
2431        GC_m2s (type), info, data_id,
2432        GCCH_2s (ch), ch, GC_f2s (fwd), size);
2433
2434   if (GCT_is_loopback (ch->t))
2435   {
2436     handle_loopback (ch, message, fwd);
2437     return;
2438   }
2439
2440   switch (type)
2441   {
2442     case GNUNET_MESSAGE_TYPE_CADET_DATA:
2443       if (GNUNET_YES == ch->reliable)
2444       {
2445         chq = GNUNET_new (struct CadetChannelQueue);
2446         chq->type = type;
2447         if (NULL == existing_copy)
2448           chq->copy = channel_save_copy (ch, message, fwd);
2449         else
2450         {
2451           chq->copy = (struct CadetReliableMessage *) existing_copy;
2452           if (NULL != chq->copy->chq)
2453           {
2454             /* Last retransmission was queued but not yet sent!
2455              * This retransmission was scheduled by a ch_message_sent which
2456              * followed a very fast RTT, so the tiny delay made the
2457              * retransmission function to execute before the previous
2458              * retransmitted message even had a chance to leave the peer.
2459              * Cancel this message and wait until the pending
2460              * retransmission leaves the peer and ch_message_sent starts
2461              * the timer for the next one.
2462              */
2463             GNUNET_free (chq);
2464             LOG (GNUNET_ERROR_TYPE_DEBUG,
2465                  "  exisitng copy not yet transmitted!\n");
2466             return;
2467           }
2468           LOG (GNUNET_ERROR_TYPE_DEBUG,
2469                "  using existing copy: %p {r:%p q:%p t:%u}\n",
2470                existing_copy,
2471                chq->copy->rel, chq->copy->chq, chq->copy->type);
2472         }
2473         LOG (GNUNET_ERROR_TYPE_DEBUG, "  new chq: %p\n", chq);
2474         chq->copy->chq = chq;
2475         chq->tq = GCT_send_prebuilt_message (message, ch->t, NULL,
2476                                              NULL != existing_copy,
2477                                              &ch_message_sent, chq);
2478         /* q itself is stored in copy */
2479         GNUNET_assert (NULL != chq->tq || GNUNET_NO != ch->destroy);
2480       }
2481       else
2482       {
2483         fire_and_forget (message, ch, GNUNET_NO);
2484       }
2485       break;
2486
2487
2488     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2489     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2490     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2491       chq = GNUNET_new (struct CadetChannelQueue);
2492       chq->type = type;
2493       chq->rel = fwd ? ch->root_rel : ch->dest_rel;
2494       if (NULL != chq->rel->uniq)
2495       {
2496         if (NULL != chq->rel->uniq->tq)
2497         {
2498           GCT_cancel (chq->rel->uniq->tq);
2499           /* ch_message_sent is called, freeing and NULLing uniq */
2500           GNUNET_break (NULL == chq->rel->uniq);
2501         }
2502         else
2503         {
2504           GNUNET_break (0);
2505           GNUNET_free (chq->rel->uniq);
2506         }
2507       }
2508
2509       chq->tq = GCT_send_prebuilt_message (message, ch->t, NULL, GNUNET_YES,
2510                                            &ch_message_sent, chq);
2511       if (NULL == chq->tq)
2512       {
2513         GNUNET_break (0);
2514         GCT_debug (ch->t, GNUNET_ERROR_TYPE_ERROR);
2515         GNUNET_free (chq);
2516         chq = NULL;
2517         return;
2518       }
2519       chq->rel->uniq = chq;
2520       break;
2521
2522
2523     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2524     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2525       fire_and_forget (message, ch, GNUNET_YES);
2526       break;
2527
2528
2529     default:
2530       GNUNET_break (0);
2531       LOG (GNUNET_ERROR_TYPE_WARNING, "type %s unknown!\n", GC_m2s (type));
2532       fire_and_forget (message, ch, GNUNET_YES);
2533   }
2534 }
2535
2536
2537 /**
2538  * Get the static string for identification of the channel.
2539  *
2540  * @param ch Channel.
2541  *
2542  * @return Static string with the channel IDs.
2543  */
2544 const char *
2545 GCCH_2s (const struct CadetChannel *ch)
2546 {
2547   static char buf[64];
2548
2549   if (NULL == ch)
2550     return "(NULL Channel)";
2551
2552   SPRINTF (buf, "%s:%u gid:%X (%X / %X)",
2553            GCT_2s (ch->t), ch->port, ch->gid, ch->lid_root, ch->lid_dest);
2554
2555   return buf;
2556 }