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