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