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