715edf6f4039ff7e44952ac8f44aff49b7c00832
[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 %llX\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) (%llX) -> %llX\n",
1565          copy->mid, delta, mask, msg.futures);
1566   }
1567   LOG (GNUNET_ERROR_TYPE_INFO, "===> DATA_ACK for %u + %llX\n",
1568        ack, msg.futures);
1569
1570   GCCH_send_prebuilt_message (&msg.header, ch, !fwd, NULL);
1571   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1572 }
1573
1574
1575 /**
1576  * Allow a client to send us more data, in case it was choked.
1577  *
1578  * @param ch Channel.
1579  * @param fwd Is this about FWD traffic? (Root client).
1580  */
1581 void
1582 GCCH_allow_client (struct CadetChannel *ch, int fwd)
1583 {
1584   struct CadetChannelReliability *rel;
1585   unsigned int buffer;
1586
1587   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH allow\n");
1588
1589   if (CADET_CHANNEL_READY != ch->state)
1590   {
1591     LOG (GNUNET_ERROR_TYPE_DEBUG, " channel not ready yet!\n");
1592     return;
1593   }
1594
1595   if (GNUNET_YES == ch->reliable)
1596   {
1597     rel = fwd ? ch->root_rel : ch->dest_rel;
1598     if (NULL == rel)
1599     {
1600       GNUNET_break (GNUNET_NO != ch->destroy);
1601       return;
1602     }
1603     if (NULL != rel->head_sent)
1604     {
1605       if (64 <= rel->mid_send - rel->head_sent->mid)
1606       {
1607         LOG (GNUNET_ERROR_TYPE_DEBUG, " too big MID gap! Wait for ACK.\n");
1608         return;
1609       }
1610       else
1611       {
1612         LOG (GNUNET_ERROR_TYPE_DEBUG, " gap ok: %u - %u\n",
1613              rel->head_sent->mid, rel->mid_send);
1614         struct CadetReliableMessage *aux;
1615         for (aux = rel->head_sent; NULL != aux; aux = aux->next)
1616         {
1617           LOG (GNUNET_ERROR_TYPE_DEBUG, "   - sent mid %u\n", aux->mid);
1618         }
1619       }
1620     }
1621     else
1622     {
1623       LOG (GNUNET_ERROR_TYPE_DEBUG, " head sent is NULL\n");
1624     }
1625   }
1626
1627   if (is_loopback (ch))
1628     buffer = GCCH_get_buffer (ch, fwd);
1629   else
1630     buffer = GCT_get_connections_buffer (ch->t);
1631
1632   if (0 == buffer)
1633   {
1634     LOG (GNUNET_ERROR_TYPE_DEBUG, " no buffer space.\n");
1635     return;
1636   }
1637
1638   LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space %u, allowing\n", buffer);
1639   send_client_ack (ch, fwd);
1640 }
1641
1642
1643 /**
1644  * Log channel info.
1645  *
1646  * @param ch Channel.
1647  * @param level Debug level to use.
1648  */
1649 void
1650 GCCH_debug (struct CadetChannel *ch, enum GNUNET_ErrorType level)
1651 {
1652   int do_log;
1653
1654   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
1655                                        "cadet-chn",
1656                                        __FILE__, __FUNCTION__, __LINE__);
1657   if (0 == do_log)
1658     return;
1659
1660   if (NULL == ch)
1661   {
1662     LOG2 (level, "*** DEBUG NULL CHANNEL ***\n");
1663     return;
1664   }
1665   LOG2 (level, "Channel %s:%X (%p)\n", GCT_2s (ch->t), ch->gid, ch);
1666   LOG2 (level, "  root %p/%p\n", ch->root, ch->root_rel);
1667   if (NULL != ch->root)
1668   {
1669     LOG2 (level, "  cli %s\n", GML_2s (ch->root));
1670     LOG2 (level, "  ready %s\n", ch->root_rel->client_ready ? "YES" : "NO");
1671     LOG2 (level, "  id %X\n", ch->lid_root);
1672     LOG2 (level, "  recv %d\n", ch->root_rel->n_recv);
1673     LOG2 (level, "  MID r: %d, s: %d\n",
1674           ch->root_rel->mid_recv, ch->root_rel->mid_send);
1675   }
1676   LOG2 (level, "  dest %p/%p\n",
1677               ch->dest, ch->dest_rel);
1678   if (NULL != ch->dest)
1679   {
1680     LOG2 (level, "  cli %s\n", GML_2s (ch->dest));
1681     LOG2 (level, "  ready %s\n", ch->dest_rel->client_ready ? "YES" : "NO");
1682     LOG2 (level, "  id %X\n", ch->lid_dest);
1683     LOG2 (level, "  recv %d\n", ch->dest_rel->n_recv);
1684     LOG2 (level, "  MID r: %d, s: %d\n",
1685           ch->dest_rel->mid_recv, ch->dest_rel->mid_send);
1686
1687   }
1688 }
1689
1690
1691 /**
1692  * Handle an ACK given by a client.
1693  *
1694  * Mark client as ready and send him any buffered data we could have for him.
1695  *
1696  * @param ch Channel.
1697  * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by dest and go BCK)
1698  */
1699 void
1700 GCCH_handle_local_ack (struct CadetChannel *ch, int fwd)
1701 {
1702   struct CadetChannelReliability *rel;
1703   struct CadetClient *c;
1704
1705   rel = fwd ? ch->dest_rel : ch->root_rel;
1706   c   = fwd ? ch->dest     : ch->root;
1707
1708   rel->client_ready = GNUNET_YES;
1709   send_client_buffered_data (ch, c, fwd);
1710
1711   if (GNUNET_YES == ch->destroy && 0 == rel->n_recv)
1712   {
1713     send_destroy (ch, GNUNET_YES);
1714     GCCH_destroy (ch);
1715     return;
1716   }
1717   /* if loopback is marked for destruction, no need to ACK to the other peer,
1718    * it requested the destruction and is already gone, therefore, else if.
1719    */
1720   else if (is_loopback (ch))
1721   {
1722     unsigned int buffer;
1723
1724     buffer = GCCH_get_buffer (ch, fwd);
1725     if (0 < buffer)
1726       GCCH_allow_client (ch, fwd);
1727
1728     return;
1729   }
1730   GCT_send_connection_acks (ch->t);
1731 }
1732
1733
1734 /**
1735  * Handle data given by a client.
1736  *
1737  * Check whether the client is allowed to send in this tunnel, save if channel
1738  * is reliable and send an ACK to the client if there is still buffer space
1739  * in the tunnel.
1740  *
1741  * @param ch Channel.
1742  * @param c Client which sent the data.
1743  * @param fwd Is this a FWD data?
1744  * @param message Data message.
1745  * @param size Size of data.
1746  *
1747  * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
1748  */
1749 int
1750 GCCH_handle_local_data (struct CadetChannel *ch,
1751                         struct CadetClient *c, int fwd,
1752                         const struct GNUNET_MessageHeader *message,
1753                         size_t size)
1754 {
1755   struct CadetChannelReliability *rel;
1756   struct GNUNET_CADET_Data *payload;
1757   uint16_t p2p_size = sizeof(struct GNUNET_CADET_Data) + size;
1758   unsigned char cbuf[p2p_size];
1759   unsigned char buffer;
1760
1761   /* Is the client in the channel? */
1762   if ( !( (fwd &&
1763            ch->root == c)
1764          ||
1765           (!fwd &&
1766            ch->dest == c) ) )
1767   {
1768     GNUNET_break_op (0);
1769     return GNUNET_SYSERR;
1770   }
1771
1772   rel = fwd ? ch->root_rel : ch->dest_rel;
1773
1774   if (GNUNET_NO == rel->client_allowed)
1775   {
1776     GNUNET_break_op (0);
1777     return GNUNET_SYSERR;
1778   }
1779
1780   rel->client_allowed = GNUNET_NO;
1781
1782   /* Ok, everything is correct, send the message. */
1783   payload = (struct GNUNET_CADET_Data *) cbuf;
1784   payload->mid = htonl (rel->mid_send);
1785   rel->mid_send++;
1786   memcpy (&payload[1], message, size);
1787   payload->header.size = htons (p2p_size);
1788   payload->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_DATA);
1789   payload->chid = htonl (ch->gid);
1790   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1791   GCCH_send_prebuilt_message (&payload->header, ch, fwd, NULL);
1792
1793   if (is_loopback (ch))
1794     buffer = GCCH_get_buffer (ch, fwd);
1795   else
1796     buffer = GCT_get_connections_buffer (ch->t);
1797
1798   if (0 < buffer)
1799     GCCH_allow_client (ch, fwd);
1800
1801   return GNUNET_OK;
1802 }
1803
1804
1805 /**
1806  * Handle a channel destroy requested by a client.
1807  *
1808  * TODO: add "reason" field
1809  *
1810  * Destroy the channel and the tunnel in case this was the last channel.
1811  *
1812  * @param ch Channel.
1813  * @param c Client that requested the destruction (to avoid notifying him).
1814  * @param is_root Is the request coming from root?
1815  */
1816 void
1817 GCCH_handle_local_destroy (struct CadetChannel *ch,
1818                            struct CadetClient *c,
1819                            int is_root)
1820 {
1821   ch->destroy = GNUNET_YES;
1822   /* Cleanup after the tunnel */
1823   if (GNUNET_NO == is_root && c == ch->dest)
1824   {
1825     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
1826     GML_client_delete_channel (c, ch, ch->lid_dest);
1827     ch->dest = NULL;
1828   }
1829   if (GNUNET_YES == is_root && c == ch->root)
1830   {
1831     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
1832     GML_client_delete_channel (c, ch, ch->lid_root);
1833     ch->root = NULL;
1834   }
1835
1836   send_destroy (ch, GNUNET_NO);
1837   if (0 == ch->pending_messages)
1838     GCCH_destroy (ch);
1839 }
1840
1841
1842 /**
1843  * Handle a channel create requested by a client.
1844  *
1845  * Create the channel and the tunnel in case this was the first0 channel.
1846  *
1847  * @param c Client that requested the creation (will be the root).
1848  * @param msg Create Channel message.
1849  *
1850  * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
1851  */
1852 int
1853 GCCH_handle_local_create (struct CadetClient *c,
1854                           struct GNUNET_CADET_ChannelMessage *msg)
1855 {
1856   struct CadetChannel *ch;
1857   struct CadetTunnel *t;
1858   struct CadetPeer *peer;
1859   CADET_ChannelNumber chid;
1860
1861   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
1862               GNUNET_i2s (&msg->peer), ntohl (msg->port));
1863   chid = ntohl (msg->channel_id);
1864
1865   /* Sanity check for duplicate channel IDs */
1866   if (NULL != GML_channel_get (c, chid))
1867   {
1868     GNUNET_break (0);
1869     return GNUNET_SYSERR;
1870   }
1871
1872   peer = GCP_get (&msg->peer, GNUNET_YES);
1873   GCP_add_tunnel (peer);
1874   t = GCP_get_tunnel (peer);
1875
1876   if (GCP_get_short_id (peer) == myid)
1877   {
1878     GCT_change_cstate (t, CADET_TUNNEL_READY);
1879   }
1880   else
1881   {
1882     /* FIXME change to a tunnel API, eliminate ch <-> peer connection */
1883     GCP_connect (peer);
1884   }
1885
1886   /* Create channel */
1887   ch = channel_new (t, c, chid);
1888   if (NULL == ch)
1889   {
1890     GNUNET_break (0);
1891     return GNUNET_SYSERR;
1892   }
1893   ch->port = ntohl (msg->port);
1894   channel_set_options (ch, ntohl (msg->opt));
1895
1896   /* In unreliable channels, we'll use the DLL to buffer BCK data */
1897   ch->root_rel = GNUNET_new (struct CadetChannelReliability);
1898   ch->root_rel->ch = ch;
1899   ch->root_rel->retry_timer = CADET_RETRANSMIT_TIME;
1900   ch->root_rel->expected_delay.rel_value_us = 0;
1901
1902   LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s\n", GCCH_2s (ch));
1903
1904   send_create (ch);
1905
1906   return GNUNET_OK;
1907 }
1908
1909
1910 /**
1911  * Handler for cadet network payload traffic.
1912  *
1913  * @param ch Channel for the message.
1914  * @param msg Unencryted data message.
1915  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1916  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1917  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1918  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1919  */
1920 void
1921 GCCH_handle_data (struct CadetChannel *ch,
1922                   const struct GNUNET_CADET_Data *msg,
1923                   int fwd)
1924 {
1925   struct CadetChannelReliability *rel;
1926   struct CadetClient *c;
1927   uint32_t mid;
1928
1929   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1930   if (GNUNET_SYSERR == fwd)
1931   {
1932     if (is_loopback (ch))
1933     {
1934       /* It is a loopback channel after all... */
1935       GNUNET_break (0);
1936       return;
1937     }
1938     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1939   }
1940
1941   /*  Initialize FWD/BCK data */
1942   c   = fwd ? ch->dest     : ch->root;
1943   rel = fwd ? ch->dest_rel : ch->root_rel;
1944
1945   if (NULL == c)
1946   {
1947     GNUNET_break (GNUNET_NO != ch->destroy);
1948     return;
1949   }
1950
1951   if (CADET_CHANNEL_READY != ch->state)
1952   {
1953     if (GNUNET_NO == fwd)
1954     {
1955       /* If we are the root, this means the other peer has sent traffic before
1956        * receiving our ACK. Even if the SYNACK goes missing, no traffic should
1957        * be sent before the ACK.
1958        */
1959       GNUNET_break_op (0);
1960       return;
1961     }
1962     /* If we are the dest, this means that the SYNACK got to the root but
1963      * the ACK went missing. Treat this as an ACK.
1964      */
1965     channel_confirm (ch, GNUNET_NO);
1966   }
1967
1968   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
1969
1970   mid = ntohl (msg->mid);
1971   LOG (GNUNET_ERROR_TYPE_INFO, "<=== DATA %u %s on channel %s\n",
1972        mid, GC_f2s (fwd), GCCH_2s (ch));
1973
1974   if (GNUNET_NO == ch->reliable ||
1975       ( !GC_is_pid_bigger (rel->mid_recv, mid) &&
1976         GC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1977   {
1978     LOG (GNUNET_ERROR_TYPE_DEBUG, "RECV MID %u (%u)\n",
1979          mid, ntohs (msg->header.size));
1980     if (GNUNET_YES == ch->reliable)
1981     {
1982       /* Is this the exact next expected messasge? */
1983       if (mid == rel->mid_recv)
1984       {
1985         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected, sending to client\n");
1986         send_client_data (ch, msg, fwd);
1987       }
1988       else
1989       {
1990         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1991         add_buffered_data (msg, rel);
1992       }
1993     }
1994     else
1995     {
1996       /* Tunnel is unreliable: send to clients directly */
1997       /* FIXME: accept Out Of Order traffic */
1998       rel->mid_recv = mid + 1;
1999       send_client_data (ch, msg, fwd);
2000     }
2001   }
2002   else
2003   {
2004     if (GC_is_pid_bigger (rel->mid_recv, mid))
2005     {
2006       GNUNET_break_op (0);
2007       LOG (GNUNET_ERROR_TYPE_WARNING,
2008           "MID %u on channel %s not expected (window: %u - %u). Dropping!\n",
2009           mid, GCCH_2s (ch), rel->mid_recv, rel->mid_recv + 63);
2010     }
2011     else
2012     {
2013       LOG (GNUNET_ERROR_TYPE_WARNING,
2014            "Duplicate MID %u, channel %s (expecting MID %u). Re-sending ACK!\n",
2015            mid, GCCH_2s (ch), rel->mid_recv);
2016       if (NULL != rel->uniq)
2017       {
2018         LOG (GNUNET_ERROR_TYPE_WARNING,
2019             "We are trying to send an ACK, but don't seem have the "
2020             "bandwidth. Try to increase your ats QUOTA in you config file\n");
2021       }
2022
2023     }
2024   }
2025
2026   GCCH_send_data_ack (ch, fwd);
2027 }
2028
2029
2030 /**
2031  * Handler for cadet network traffic end-to-end ACKs.
2032  *
2033  * @param ch Channel on which we got this message.
2034  * @param msg Data message.
2035  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2036  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2037  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2038  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2039  */
2040 void
2041 GCCH_handle_data_ack (struct CadetChannel *ch,
2042                       const struct GNUNET_CADET_DataACK *msg,
2043                       int fwd)
2044 {
2045   struct CadetChannelReliability *rel;
2046   struct CadetReliableMessage *copy;
2047   struct CadetReliableMessage *next;
2048   uint32_t ack;
2049   int work;
2050
2051   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2052   if (GNUNET_SYSERR == fwd)
2053   {
2054     if (is_loopback (ch))
2055     {
2056       /* It is a loopback channel after all... */
2057       GNUNET_break (0);
2058       return;
2059     }
2060     /* Inverted: if message came 'FWD' is a 'BCK ACK'. */
2061     fwd = (NULL != ch->dest) ? GNUNET_NO : GNUNET_YES;
2062   }
2063
2064   ack = ntohl (msg->mid);
2065   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s ACK %u + %llX\n",
2066        GC_f2s (fwd), ack, msg->futures);
2067
2068   if (GNUNET_YES == fwd)
2069     rel = ch->root_rel;
2070   else
2071     rel = ch->dest_rel;
2072
2073   if (NULL == rel)
2074   {
2075     GNUNET_break (GNUNET_NO != ch->destroy);
2076     return;
2077   }
2078
2079   /* Free ACK'd copies: no need to retransmit those anymore FIXME refactor */
2080   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
2081   {
2082     if (GC_is_pid_bigger (copy->mid, ack))
2083     {
2084       LOG (GNUNET_ERROR_TYPE_DEBUG, "  head %u, out!\n", copy->mid);
2085       if (0 < channel_rel_free_sent (rel, msg))
2086         work = GNUNET_YES;
2087       break;
2088     }
2089     work = GNUNET_YES;
2090     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %u\n", copy->mid);
2091     next = copy->next;
2092     if (GNUNET_YES == rel_message_free (copy, GNUNET_YES))
2093     {
2094       LOG (GNUNET_ERROR_TYPE_DEBUG, " channel destoyed\n");
2095       return;
2096     }
2097   }
2098
2099   /* ACK client if needed and possible */
2100   GCCH_allow_client (ch, fwd);
2101
2102   /* If some message was free'd, update the retransmission delay */
2103   if (GNUNET_YES == work)
2104   {
2105     if (NULL != rel->retry_task)
2106     {
2107       GNUNET_SCHEDULER_cancel (rel->retry_task);
2108       rel->retry_task = NULL;
2109       if (NULL != rel->head_sent && NULL == rel->head_sent->chq)
2110       {
2111         struct GNUNET_TIME_Absolute new_target;
2112         struct GNUNET_TIME_Relative delay;
2113
2114         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
2115                                                CADET_RETRANSMIT_MARGIN);
2116         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
2117                                                delay);
2118         delay = GNUNET_TIME_absolute_get_remaining (new_target);
2119         rel->retry_task =
2120             GNUNET_SCHEDULER_add_delayed (delay,
2121                                           &channel_retransmit_message,
2122                                           rel);
2123       }
2124     }
2125     else
2126     {
2127       /* Work was done but no task was pending? Shouldn't happen! */
2128       GNUNET_break (0);
2129     }
2130   }
2131 }
2132
2133
2134 /**
2135  * Handler for channel create messages.
2136  *
2137  * Does not have fwd parameter because it's always 'FWD': channel is incoming.
2138  *
2139  * @param t Tunnel this channel will be in.
2140  * @param msg Channel crate message.
2141  */
2142 struct CadetChannel *
2143 GCCH_handle_create (struct CadetTunnel *t,
2144                     const struct GNUNET_CADET_ChannelCreate *msg)
2145 {
2146   CADET_ChannelNumber chid;
2147   struct CadetChannel *ch;
2148   struct CadetClient *c;
2149   int new_channel;
2150
2151   chid = ntohl (msg->chid);
2152   ch = GCT_get_channel (t, chid);
2153   if (NULL == ch)
2154   {
2155     /* Create channel */
2156     ch = channel_new (t, NULL, 0);
2157     ch->gid = chid;
2158     channel_set_options (ch, ntohl (msg->opt));
2159     new_channel = GNUNET_YES;
2160   }
2161   else
2162   {
2163     new_channel = GNUNET_NO;
2164   }
2165
2166   if (GNUNET_YES == new_channel || GCT_is_loopback (t))
2167   {
2168     /* Find a destination client */
2169     ch->port = ntohl (msg->port);
2170     LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", ch->port);
2171     c = GML_client_get_by_port (ch->port);
2172     if (NULL == c)
2173     {
2174       LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
2175       if (is_loopback (ch))
2176       {
2177         LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback: destroy on handler\n");
2178         send_nack (ch);
2179       }
2180       else
2181       {
2182         LOG (GNUNET_ERROR_TYPE_DEBUG, "  not loopback: destroy now\n");
2183         send_nack (ch);
2184         GCCH_destroy (ch);
2185       }
2186       return NULL;
2187     }
2188     else
2189     {
2190       LOG (GNUNET_ERROR_TYPE_DEBUG, "  client %p has port registered\n", c);
2191     }
2192
2193     add_destination (ch, c);
2194     if (GNUNET_YES == ch->reliable)
2195       LOG (GNUNET_ERROR_TYPE_DEBUG, "Reliable\n");
2196     else
2197       LOG (GNUNET_ERROR_TYPE_DEBUG, "Not Reliable\n");
2198
2199     send_client_create (ch);
2200     ch->state =  CADET_CHANNEL_SENT;
2201   }
2202   else
2203   {
2204     LOG (GNUNET_ERROR_TYPE_DEBUG, "  duplicate create channel\n");
2205     if (NULL != ch->dest_rel->retry_task)
2206     {
2207       LOG (GNUNET_ERROR_TYPE_DEBUG, "  clearing retry task\n");
2208       /* we were waiting to re-send our 'SYNACK', wait no more! */
2209       GNUNET_SCHEDULER_cancel (ch->dest_rel->retry_task);
2210       ch->dest_rel->retry_task = NULL;
2211     }
2212     else if (NULL != ch->dest_rel->uniq)
2213     {
2214       /* we are waiting to for our 'SYNACK' to leave the queue, all done! */
2215       return ch;
2216     }
2217   }
2218   send_ack (ch, GNUNET_YES);
2219
2220   return ch;
2221 }
2222
2223
2224 /**
2225  * Handler for channel NACK messages.
2226  *
2227  * NACK messages always go dest -> root, no need for 'fwd' or 'msg' parameter.
2228  *
2229  * @param ch Channel.
2230  */
2231 void
2232 GCCH_handle_nack (struct CadetChannel *ch)
2233 {
2234   send_client_nack (ch);
2235   GCCH_destroy (ch);
2236 }
2237
2238
2239 /**
2240  * Handler for channel ack messages.
2241  *
2242  * @param ch Channel.
2243  * @param msg Message.
2244  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2245  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2246  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2247  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2248  */
2249 void
2250 GCCH_handle_ack (struct CadetChannel *ch,
2251                  const struct GNUNET_CADET_ChannelManage *msg,
2252                  int fwd)
2253 {
2254   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2255   if (GNUNET_SYSERR == fwd)
2256   {
2257     if (is_loopback (ch))
2258     {
2259       /* It is a loopback channel after all... */
2260       GNUNET_break (0);
2261       return;
2262     }
2263     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
2264   }
2265
2266   channel_confirm (ch, !fwd);
2267 }
2268
2269
2270 /**
2271  * Handler for channel destroy messages.
2272  *
2273  * @param ch Channel to be destroyed of.
2274  * @param msg Message.
2275  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2276  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2277  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2278  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2279  */
2280 void
2281 GCCH_handle_destroy (struct CadetChannel *ch,
2282                      const struct GNUNET_CADET_ChannelManage *msg,
2283                      int fwd)
2284 {
2285   struct CadetChannelReliability *rel;
2286
2287   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2288   if (GNUNET_SYSERR == fwd)
2289   {
2290     if (is_loopback (ch))
2291     {
2292       /* It is a loopback channel after all... */
2293       GNUNET_break (0);
2294       return;
2295     }
2296     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
2297   }
2298
2299   GCCH_debug (ch, GNUNET_ERROR_TYPE_DEBUG);
2300   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
2301   {
2302     /* Not for us (don't destroy twice a half-open loopback channel) */
2303     return;
2304   }
2305
2306   rel = fwd ? ch->dest_rel : ch->root_rel;
2307   if (0 == rel->n_recv)
2308   {
2309     send_destroy (ch, GNUNET_YES);
2310     GCCH_destroy (ch);
2311   }
2312   else
2313   {
2314     ch->destroy = GNUNET_YES;
2315   }
2316 }
2317
2318
2319 /**
2320  * Sends an already built message on a channel.
2321  *
2322  * If the channel is on a loopback tunnel, notifies the appropriate destination
2323  * client locally.
2324  *
2325  * On a normal channel passes the message to the tunnel for encryption and
2326  * sending on a connection.
2327  *
2328  * This function DOES NOT save the message for retransmission.
2329  *
2330  * @param message Message to send. Function makes a copy of it.
2331  * @param ch Channel on which this message is transmitted.
2332  * @param fwd Is this a fwd message?
2333  * @param existing_copy This is a retransmission, don't save a copy.
2334  */
2335 void
2336 GCCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2337                             struct CadetChannel *ch, int fwd,
2338                             void *existing_copy)
2339 {
2340   struct CadetChannelQueue *chq;
2341   uint16_t type;
2342
2343   type = ntohs (message->type);
2344   LOG (GNUNET_ERROR_TYPE_INFO, "===> %s %s on channel %s\n",
2345        GC_m2s (type), GC_f2s (fwd), GCCH_2s (ch));
2346
2347   if (GCT_is_loopback (ch->t))
2348   {
2349     handle_loopback (ch, message, fwd);
2350     return;
2351   }
2352
2353   switch (type)
2354   {
2355     struct GNUNET_CADET_Data *payload;
2356     case GNUNET_MESSAGE_TYPE_CADET_DATA:
2357
2358       payload = (struct GNUNET_CADET_Data *) message;
2359       LOG (GNUNET_ERROR_TYPE_INFO, "===> %s %u\n",
2360            GC_m2s (type), ntohl (payload->mid));
2361       if (GNUNET_YES == ch->reliable)
2362       {
2363         chq = GNUNET_new (struct CadetChannelQueue);
2364         chq->type = type;
2365         if (NULL == existing_copy)
2366           chq->copy = channel_save_copy (ch, message, fwd);
2367         else
2368         {
2369           chq->copy = (struct CadetReliableMessage *) existing_copy;
2370           if (NULL != chq->copy->chq)
2371           {
2372             /* Last retransmission was queued but not yet sent!
2373              * This retransmission was scheduled by a ch_message_sent which
2374              * followed a very fast RTT, so the tiny delay made the
2375              * retransmission function to execute before the previous
2376              * retransmitted message even had a chance to leave the peer.
2377              * Cancel this message and wait until the pending
2378              * retransmission leaves the peer and ch_message_sent starts
2379              * the timer for the next one.
2380              */
2381             GNUNET_free (chq);
2382             LOG (GNUNET_ERROR_TYPE_DEBUG,
2383                  "  exisitng copy not yet transmitted!\n");
2384             return;
2385           }
2386           LOG (GNUNET_ERROR_TYPE_DEBUG,
2387                "  using existing copy: %p {r:%p q:%p t:%u}\n",
2388                existing_copy,
2389                chq->copy->rel, chq->copy->chq, chq->copy->type);
2390         }
2391         LOG (GNUNET_ERROR_TYPE_DEBUG, "  new chq: %p\n", chq);
2392         chq->copy->chq = chq;
2393         chq->tq = GCT_send_prebuilt_message (message, ch->t, NULL,
2394                                              NULL != existing_copy,
2395                                              &ch_message_sent, chq);
2396         /* q itself is stored in copy */
2397         GNUNET_assert (NULL != chq->tq || GNUNET_NO != ch->destroy);
2398       }
2399       else
2400       {
2401         fire_and_forget (message, ch, GNUNET_NO);
2402       }
2403       break;
2404
2405
2406     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
2407     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
2408     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
2409       chq = GNUNET_new (struct CadetChannelQueue);
2410       chq->type = type;
2411       chq->rel = fwd ? ch->root_rel : ch->dest_rel;
2412       if (NULL != chq->rel->uniq)
2413       {
2414         if (NULL != chq->rel->uniq->tq)
2415         {
2416           GCT_cancel (chq->rel->uniq->tq);
2417           /* ch_message_sent is called, freeing and NULLing uniq */
2418           GNUNET_break (NULL == chq->rel->uniq);
2419         }
2420         else
2421         {
2422           GNUNET_break (0);
2423           GNUNET_free (chq->rel->uniq);
2424         }
2425       }
2426
2427       chq->tq = GCT_send_prebuilt_message (message, ch->t, NULL, GNUNET_YES,
2428                                            &ch_message_sent, chq);
2429       if (NULL == chq->tq)
2430       {
2431         GNUNET_break (0);
2432         GCT_debug (ch->t, GNUNET_ERROR_TYPE_ERROR);
2433         GNUNET_free (chq);
2434         chq = NULL;
2435         return;
2436       }
2437       chq->rel->uniq = chq;
2438       break;
2439
2440
2441     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
2442     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
2443       fire_and_forget (message, ch, GNUNET_YES);
2444       break;
2445
2446
2447     default:
2448       GNUNET_break (0);
2449       LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s unknown!\n", GC_m2s (type));
2450       fire_and_forget (message, ch, GNUNET_YES);
2451   }
2452 }
2453
2454
2455 /**
2456  * Get the static string for identification of the channel.
2457  *
2458  * @param ch Channel.
2459  *
2460  * @return Static string with the channel IDs.
2461  */
2462 const char *
2463 GCCH_2s (const struct CadetChannel *ch)
2464 {
2465   static char buf[64];
2466
2467   if (NULL == ch)
2468     return "(NULL Channel)";
2469
2470   SPRINTF (buf, "%s:%u gid:%X (%X / %X)",
2471            GCT_2s (ch->t), ch->port, ch->gid, ch->lid_root, ch->lid_dest);
2472
2473   return buf;
2474 }