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