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