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