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