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