- use callback awareness to cancel unneeded traffic
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh_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 "mesh.h"
28 #include "mesh_protocol.h"
29
30 #include "gnunet-service-mesh_channel.h"
31 #include "gnunet-service-mesh_local.h"
32 #include "gnunet-service-mesh_tunnel.h"
33 #include "gnunet-service-mesh_peer.h"
34
35 #define LOG(level, ...) GNUNET_log_from(level,"mesh-chn",__VA_ARGS__)
36
37 #define MESH_RETRANSMIT_TIME    GNUNET_TIME_UNIT_SECONDS
38 #define MESH_RETRANSMIT_MARGIN  4
39
40
41 /**
42  * All the states a connection can be in.
43  */
44 enum MeshChannelState
45 {
46   /**
47    * Uninitialized status, should never appear in operation.
48    */
49   MESH_CHANNEL_NEW,
50
51   /**
52    * Connection create message sent, waiting for ACK.
53    */
54   MESH_CHANNEL_SENT,
55
56   /**
57    * Connection confirmed, ready to carry traffic.
58    */
59   MESH_CHANNEL_READY,
60 };
61
62
63 /**
64  * Info holder for channel messages in queues.
65  */
66 struct MeshChannelQueue
67 {
68   /**
69    * Tunnel Queue.
70    */
71   struct MeshTunnel3Queue *q;
72
73   /**
74    * Message type (DATA/DATA_ACK)
75    */
76   uint16_t type;
77
78   /**
79    * Message copy (for DATAs, to start retransmission timer)
80    */
81   struct MeshReliableMessage *copy;
82
83   /**
84    * Reliability (for DATA_ACKs, to access rel->ack_q)
85    */
86   struct MeshChannelReliability *rel;
87 };
88
89
90 /**
91  * Info needed to retry a message in case it gets lost.
92  */
93 struct MeshReliableMessage
94 {
95     /**
96      * Double linked list, FIFO style
97      */
98   struct MeshReliableMessage    *next;
99   struct MeshReliableMessage    *prev;
100
101     /**
102      * Type of message (payload, channel management).
103      */
104   int16_t type;
105
106     /**
107      * Tunnel Reliability queue this message is in.
108      */
109   struct MeshChannelReliability  *rel;
110
111     /**
112      * ID of the message (ACK needed to free)
113      */
114   uint32_t                      mid;
115
116   /**
117    * Tunnel Queue.
118    */
119   struct MeshTunnel3Queue *q;
120
121     /**
122      * When was this message issued (to calculate ACK delay)
123      */
124   struct GNUNET_TIME_Absolute   timestamp;
125
126   /* struct GNUNET_MESH_Data with payload */
127 };
128
129
130 /**
131  * Info about the traffic state for a client in a channel.
132  */
133 struct MeshChannelReliability
134 {
135     /**
136      * Channel this is about.
137      */
138   struct MeshChannel *ch;
139
140     /**
141      * DLL of messages sent and not yet ACK'd.
142      */
143   struct MeshReliableMessage        *head_sent;
144   struct MeshReliableMessage        *tail_sent;
145
146     /**
147      * DLL of messages received out of order.
148      */
149   struct MeshReliableMessage        *head_recv;
150   struct MeshReliableMessage        *tail_recv;
151
152     /**
153      * Messages received.
154      */
155   unsigned int                      n_recv;
156
157     /**
158      * Next MID to use for outgoing traffic.
159      */
160   uint32_t                          mid_send;
161
162     /**
163      * Next MID expected for incoming traffic.
164      */
165   uint32_t                          mid_recv;
166
167     /**
168      * Handle for queued DATA_ACKs.
169      */
170   struct MeshChannelQueue           *ack_q;
171
172     /**
173      * Can we send data to the client?
174      */
175   int                               client_ready;
176
177   /**
178    * Can the client send data to us?
179    */
180   int                               client_allowed;
181
182     /**
183      * Task to resend/poll in case no ACK is received.
184      */
185   GNUNET_SCHEDULER_TaskIdentifier   retry_task;
186
187     /**
188      * Counter for exponential backoff.
189      */
190   struct GNUNET_TIME_Relative       retry_timer;
191
192     /**
193      * How long does it usually take to get an ACK.
194      */
195   struct GNUNET_TIME_Relative       expected_delay;
196 };
197
198
199 /**
200  * Struct containing all information regarding a channel to a remote client.
201  */
202 struct MeshChannel
203 {
204     /**
205      * Tunnel this channel is in.
206      */
207   struct MeshTunnel3 *t;
208
209     /**
210      * Destination port of the channel.
211      */
212   uint32_t port;
213
214     /**
215      * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
216      */
217   MESH_ChannelNumber gid;
218
219     /**
220      * Local tunnel number for root (owner) client.
221      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
222      */
223   MESH_ChannelNumber lid_root;
224
225     /**
226      * Local tunnel number for local destination clients (incoming number)
227      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
228      */
229   MESH_ChannelNumber lid_dest;
230
231     /**
232      * Channel state.
233      */
234   enum MeshChannelState state;
235
236     /**
237      * Is the tunnel bufferless (minimum latency)?
238      */
239   int nobuffer;
240
241     /**
242      * Is the tunnel reliable?
243      */
244   int reliable;
245
246     /**
247      * Last time the channel was used
248      */
249   struct GNUNET_TIME_Absolute timestamp;
250
251     /**
252      * Client owner of the tunnel, if any
253      */
254   struct MeshClient *root;
255
256     /**
257      * Client destination of the tunnel, if any.
258      */
259   struct MeshClient *dest;
260
261     /**
262      * Flag to signal the destruction of the channel.
263      * If this is set GNUNET_YES the channel will be destroyed
264      * when the queue is empty.
265      */
266   int destroy;
267
268     /**
269      * Total messages pending for this channel, payload or not.
270      */
271   unsigned int pending_messages;
272
273     /**
274      * Reliability data.
275      * Only present (non-NULL) at the owner of a tunnel.
276      */
277   struct MeshChannelReliability *root_rel;
278
279     /**
280      * Reliability data.
281      * Only present (non-NULL) at the destination of a tunnel.
282      */
283   struct MeshChannelReliability *dest_rel;
284
285 };
286
287
288 /******************************************************************************/
289 /*******************************   GLOBALS  ***********************************/
290 /******************************************************************************/
291
292 /**
293  * Global handle to the statistics service.
294  */
295 extern struct GNUNET_STATISTICS_Handle *stats;
296
297 /**
298  * Local peer own ID (memory efficient handle).
299  */
300 extern GNUNET_PEER_Id myid;
301
302
303 /******************************************************************************/
304 /********************************   STATIC  ***********************************/
305 /******************************************************************************/
306
307 /**
308  * Destroy a reliable message after it has been acknowledged, either by
309  * direct mid ACK or bitfield. Updates the appropriate data structures and
310  * timers and frees all memory.
311  *
312  * @param copy Message that is no longer needed: remote peer got it.
313  * @param update_time Is the timing information relevant?
314  *                    If this message is ACK in a batch the timing information
315  *                    is skewed by the retransmission, count only for the
316  *                    retransmitted message.
317  */
318 static void
319 rel_message_free (struct MeshReliableMessage *copy, int update_time);
320
321 /**
322  * We have received a message out of order, or the client is not ready.
323  * Buffer it until we receive an ACK from the client or the missing
324  * message from the channel.
325  *
326  * @param msg Message to buffer (MUST be of type MESH_DATA).
327  * @param rel Reliability data to the corresponding direction.
328  */
329 static void
330 add_buffered_data (const struct GNUNET_MESH_Data *msg,
331                    struct MeshChannelReliability *rel)
332 {
333   struct MeshReliableMessage *copy;
334   struct MeshReliableMessage *prev;
335   uint32_t mid;
336   uint16_t size;
337
338   size = ntohs (msg->header.size);
339   mid = ntohl (msg->mid);
340
341   LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
342
343   copy = GNUNET_malloc (sizeof (*copy) + size);
344   copy->mid = mid;
345   copy->rel = rel;
346   copy->type = GNUNET_MESSAGE_TYPE_MESH_DATA;
347   memcpy (&copy[1], msg, size);
348
349   rel->n_recv++;
350
351   // FIXME do something better than O(n), although n < 64...
352   // FIXME start from the end (most messages are the latest ones)
353   for (prev = rel->head_recv; NULL != prev; prev = prev->next)
354   {
355     LOG (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
356     if (GM_is_pid_bigger (prev->mid, mid))
357     {
358       LOG (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
359       GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
360                                           prev, copy);
361       return;
362     }
363   }
364     LOG (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
365     GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
366     LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
367 }
368
369 /**
370  * Add a destination client to a channel, initializing all data structures
371  * in the channel and the client.
372  *
373  * @param ch Channel to which add the destination.
374  * @param c Client which to add to the channel.
375  */
376 static void
377 add_destination (struct MeshChannel *ch, struct MeshClient *c)
378 {
379   if (NULL != ch->dest)
380   {
381     GNUNET_break (0);
382     return;
383   }
384
385   /* Assign local id as destination */
386   ch->lid_dest = GML_get_next_chid (c);
387
388   /* Store in client's hashmap */
389   GML_channel_add (c, ch->lid_dest, ch);
390
391   GNUNET_break (NULL == ch->dest_rel);
392   ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
393   ch->dest_rel->ch = ch;
394   ch->dest_rel->expected_delay = MESH_RETRANSMIT_TIME;
395
396   ch->dest = c;
397 }
398
399
400 /**
401  * Send data to a client.
402  *
403  * If the client is ready, send directly, otherwise buffer while listening
404  * for a local ACK.
405  *
406  * @param ch Channel
407  * @param msg Message.
408  * @param fwd Is this a fwd (root->dest) message?
409  */
410 static void
411 send_client_data (struct MeshChannel *ch,
412                   const struct GNUNET_MESH_Data *msg,
413                   int fwd)
414 {
415   if (fwd)
416   {
417     if (ch->dest_rel->client_ready)
418       GML_send_data (ch->dest, msg, ch->lid_dest);
419     else
420       add_buffered_data (msg, ch->dest_rel);
421   }
422   else
423   {
424     if (ch->root_rel->client_ready)
425       GML_send_data (ch->root, msg, ch->lid_root);
426     else
427       add_buffered_data (msg, ch->root_rel);
428   }
429 }
430
431
432 /**
433  * Send a buffered message to the client, for in order delivery or
434  * as result of client ACK.
435  *
436  * @param ch Channel on which to empty the message buffer.
437  * @param c Client to send to.
438  * @param fwd Is this to send FWD data?.
439  */
440 static void
441 send_client_buffered_data (struct MeshChannel *ch,
442                            struct MeshClient *c,
443                            int fwd)
444 {
445   struct MeshReliableMessage *copy;
446   struct MeshChannelReliability *rel;
447
448   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
449   rel = fwd ? ch->dest_rel : ch->root_rel;
450   if (GNUNET_NO == rel->client_ready)
451   {
452     LOG (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
453     return;
454   }
455
456   copy = rel->head_recv;
457   /* We never buffer channel management messages */
458   if (NULL != copy)
459   {
460     if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
461     {
462       struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];
463
464       LOG (GNUNET_ERROR_TYPE_DEBUG,
465            " have %u! now expecting %u\n",
466            copy->mid, rel->mid_recv + 1);
467       send_client_data (ch, msg, fwd);
468       rel->n_recv--;
469       rel->mid_recv++;
470       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
471       GNUNET_free (copy);
472     }
473     else
474     {
475       LOG (GNUNET_ERROR_TYPE_DEBUG,
476            " reliable && don't have %u, next is %u\n",
477            rel->mid_recv,
478            copy->mid);
479       return;
480     }
481   }
482   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
483 }
484
485
486 /**
487  * Allow a client to send more data.
488  *
489  * In case the client was already allowed to send data, do nothing.
490  *
491  * @param ch Channel.
492  * @param fwd Is this a FWD ACK? (FWD ACKs are sent to root)
493  */
494 static void
495 send_client_ack (struct MeshChannel *ch, int fwd)
496 {
497   struct MeshChannelReliability *rel = fwd ? ch->root_rel : ch->dest_rel;
498
499   LOG (GNUNET_ERROR_TYPE_DEBUG,
500        "  sending %s ack to client on channel %s\n",
501        GM_f2s (fwd), GMCH_2s (ch));
502
503   if (NULL == rel)
504   {
505     GNUNET_break (0);
506     return;
507   }
508
509   if (GNUNET_YES == rel->client_allowed)
510   {
511     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already allowed\n");
512     return;
513   }
514   rel->client_allowed = GNUNET_YES;
515
516   GML_send_ack (fwd ? ch->root : ch->dest, fwd ? ch->lid_root : ch->lid_dest);
517 }
518
519
520 /**
521  * Notify the root that the destination rejected the channel.
522  *
523  * @param ch Rejected channel.
524  */
525 static void
526 send_client_nack (struct MeshChannel *ch)
527 {
528   if (NULL == ch->root)
529   {
530     GNUNET_break (0);
531     return;
532   }
533   GML_send_nack (ch->root, ch->lid_root);
534 }
535
536
537 /**
538  * Notify a client that the channel is no longer valid.
539  *
540  * @param ch Channel that is destroyed.
541  * @param local_only Should we try to send it to other peers?
542  */
543 static void
544 send_destroy (struct MeshChannel *ch, int local_only)
545 {
546   struct GNUNET_MESH_ChannelManage msg;
547
548   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
549   msg.header.size = htons (sizeof (msg));
550   msg.chid = htonl (ch->gid);
551
552   /* If root is not NULL, notify.
553    * If it's NULL, check lid_root. When a local destroy comes in, root
554    * is set to NULL but lid_root is left untouched. In this case, do nothing,
555    * the client is the one who reuqested the channel to be destroyed.
556    */
557   if (NULL != ch->root)
558     GML_send_channel_destroy (ch->root, ch->lid_root);
559   else if (0 == ch->lid_root && GNUNET_NO == local_only)
560     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO, GNUNET_NO);
561
562   if (NULL != ch->dest)
563     GML_send_channel_destroy (ch->dest, ch->lid_dest);
564   else if (0 == ch->lid_dest && GNUNET_NO == local_only)
565     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_YES, GNUNET_NO);
566 }
567
568
569 /**
570  * Destroy all reliable messages queued for a channel,
571  * during a channel destruction.
572  * Frees the reliability structure itself.
573  *
574  * @param rel Reliability data for a channel.
575  */
576 static void
577 channel_rel_free_all (struct MeshChannelReliability *rel)
578 {
579   struct MeshReliableMessage *copy;
580   struct MeshReliableMessage *next;
581
582   if (NULL == rel)
583     return;
584
585   for (copy = rel->head_recv; NULL != copy; copy = next)
586   {
587     next = copy->next;
588     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
589     GNUNET_free (copy);
590   }
591   for (copy = rel->head_sent; NULL != copy; copy = next)
592   {
593     next = copy->next;
594     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
595     GNUNET_free (copy);
596   }
597   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
598     GNUNET_SCHEDULER_cancel (rel->retry_task);
599   GNUNET_free (rel);
600 }
601
602
603 /**
604  * Mark future messages as ACK'd.
605  *
606  * @param rel Reliability data.
607  * @param msg DataACK message with a bitfield of future ACK'd messages.
608  */
609 static void
610 channel_rel_free_sent (struct MeshChannelReliability *rel,
611                        const struct GNUNET_MESH_DataACK *msg)
612 {
613   struct MeshReliableMessage *copy;
614   struct MeshReliableMessage *next;
615   uint64_t bitfield;
616   uint64_t mask;
617   uint32_t mid;
618   uint32_t target;
619   unsigned int i;
620
621   bitfield = msg->futures;
622   mid = ntohl (msg->mid);
623   LOG (GNUNET_ERROR_TYPE_DEBUG,
624               "!!! free_sent_reliable %u %llX\n",
625               mid, bitfield);
626   LOG (GNUNET_ERROR_TYPE_DEBUG,
627               " rel %p, head %p\n",
628               rel, rel->head_sent);
629   for (i = 0, copy = rel->head_sent;
630        i < 64 && NULL != copy && 0 != bitfield;
631        i++)
632   {
633     LOG (GNUNET_ERROR_TYPE_DEBUG,
634                 " trying bit %u (mid %u)\n",
635                 i, mid + i + 1);
636     mask = 0x1LL << i;
637     if (0 == (bitfield & mask))
638      continue;
639
640     LOG (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
641     /* Bit was set, clear the bit from the bitfield */
642     bitfield &= ~mask;
643
644     /* The i-th bit was set. Do we have that copy? */
645     /* Skip copies with mid < target */
646     target = mid + i + 1;
647     LOG (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
648     while (NULL != copy && GM_is_pid_bigger (target, copy->mid))
649      copy = copy->next;
650
651     /* Did we run out of copies? (previously freed, it's ok) */
652     if (NULL == copy)
653     {
654      LOG (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
655      return;
656     }
657
658     /* Did we overshoot the target? (previously freed, it's ok) */
659     if (GM_is_pid_bigger (copy->mid, target))
660     {
661      LOG (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
662      continue;
663     }
664
665     /* Now copy->mid == target, free it */
666     next = copy->next;
667     rel_message_free (copy, GNUNET_YES);
668     copy = next;
669   }
670   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
671 }
672
673
674 /**
675  * We haven't received an ACK after a certain time: restransmit the message.
676  *
677  * @param cls Closure (MeshReliableMessage with the message to restransmit)
678  * @param tc TaskContext.
679  */
680 static void
681 channel_retransmit_message (void *cls,
682                             const struct GNUNET_SCHEDULER_TaskContext *tc)
683 {
684   struct MeshChannelReliability *rel = cls;
685   struct MeshReliableMessage *copy;
686   struct MeshChannel *ch;
687   struct GNUNET_MESH_Data *payload;
688   int fwd;
689
690   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
691   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
692     return;
693
694   ch = rel->ch;
695   copy = rel->head_sent;
696   if (NULL == copy)
697   {
698     GNUNET_break (0);
699     return;
700   }
701
702   payload = (struct GNUNET_MESH_Data *) &copy[1];
703   fwd = (rel == ch->root_rel);
704
705   /* Message not found in the queue that we are going to use. */
706   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
707
708   GMCH_send_prebuilt_message (&payload->header, ch, fwd, GNUNET_YES);
709   GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
710
711   copy->timestamp = GNUNET_TIME_absolute_get();
712   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
713   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
714                                                   &channel_retransmit_message,
715                                                   cls);
716 }
717
718
719 /**
720  * Destroy a reliable message after it has been acknowledged, either by
721  * direct mid ACK or bitfield. Updates the appropriate data structures and
722  * timers and frees all memory.
723  *
724  * @param copy Message that is no longer needed: remote peer got it.
725  * @param update_time Is the timing information relevant?
726  *                    If this message is ACK in a batch the timing information
727  *                    is skewed by the retransmission, count only for the
728  *                    retransmitted message.
729  */
730 static void
731 rel_message_free (struct MeshReliableMessage *copy, int update_time)
732 {
733   struct MeshChannelReliability *rel;
734   struct GNUNET_TIME_Relative time;
735
736   rel = copy->rel;
737   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
738   if (update_time)
739   {
740     time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
741     rel->expected_delay.rel_value_us *= 7;
742     rel->expected_delay.rel_value_us += time.rel_value_us;
743     rel->expected_delay.rel_value_us /= 8;
744     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
745                 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
746     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
747                 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
748                                                         GNUNET_NO));
749     rel->retry_timer = rel->expected_delay;
750   }
751   else
752   {
753     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! batch free, ignoring timing\n");
754   }
755   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
756   GNUNET_free (copy);
757 }
758
759
760 /**
761  * Confirm we got a channel create.
762  *
763  * @param ch The channel to confirm.
764  * @param fwd Should we send a FWD ACK? (going dest->root)
765  */
766 static void
767 channel_send_ack (struct MeshChannel *ch, int fwd)
768 {
769   struct GNUNET_MESH_ChannelManage msg;
770
771   msg.header.size = htons (sizeof (msg));
772   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
773   LOG (GNUNET_ERROR_TYPE_DEBUG,
774               "  sending channel %s ack for channel %s\n",
775               GM_f2s (fwd), GMCH_2s (ch));
776
777   msg.chid = htonl (ch->gid);
778   GMCH_send_prebuilt_message (&msg.header, ch, !fwd, GNUNET_NO);
779 }
780
781
782 /**
783  * Notify that a channel create didn't succeed.
784  *
785  * @param ch The channel to reject.
786  */
787 static void
788 channel_send_nack (struct MeshChannel *ch)
789 {
790   struct GNUNET_MESH_ChannelManage msg;
791
792   msg.header.size = htons (sizeof (msg));
793   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK);
794   LOG (GNUNET_ERROR_TYPE_DEBUG,
795        "  sending channel NACK for channel %s\n",
796        GMCH_2s (ch));
797
798   msg.chid = htonl (ch->gid);
799   GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO, GNUNET_NO);
800 }
801
802
803 /**
804  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
805  *
806  * @param ch Channel to mark as ready.
807  * @param fwd Was the ACK message a FWD ACK? (dest->root, SYNACK)
808  */
809 static void
810 channel_confirm (struct MeshChannel *ch, int fwd)
811 {
812   struct MeshChannelReliability *rel;
813   struct MeshReliableMessage *copy;
814   struct MeshReliableMessage *next;
815
816   LOG (GNUNET_ERROR_TYPE_DEBUG,
817               "  channel confirm %s %s:%X\n",
818               GM_f2s (fwd), GMT_2s (ch->t), ch->gid);
819   ch->state = MESH_CHANNEL_READY;
820
821   rel = fwd ? ch->root_rel : ch->dest_rel;
822   rel->client_ready = GNUNET_YES;
823   for (copy = rel->head_sent; NULL != copy; copy = next)
824   {
825     struct GNUNET_MessageHeader *msg;
826
827     next = copy->next;
828     msg = (struct GNUNET_MessageHeader *) &copy[1];
829     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
830     {
831       rel_message_free (copy, GNUNET_YES);
832       /* TODO return? */
833     }
834   }
835   send_client_ack (ch, fwd);
836
837   /* In case of a FWD ACK (SYNACK) send a BCK ACK (ACK). */
838   if (fwd)
839     channel_send_ack (ch, !fwd);
840 }
841
842
843 /**
844  * Message has been sent: start retransmission timer.
845  *
846  * @param cls Closure (queue structure).
847  * @param t Tunnel.
848  * @param q Queue handler (no longer valid).
849  * @param type Type of message.
850  * @param size Size of the message.
851  */
852 static void
853 ch_message_sent (void *cls,
854                  struct MeshTunnel3 *t,
855                  struct MeshTunnel3Queue *q,
856                  uint16_t type, size_t size)
857 {
858   struct MeshChannelQueue *ch_q = cls;
859   struct MeshReliableMessage *copy = ch_q->copy;
860   struct MeshChannelReliability *rel;
861
862   switch (ch_q->type)
863   {
864     case GNUNET_MESSAGE_TYPE_MESH_DATA:
865       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SENT %u %s\n",
866            copy->mid, GM_m2s (type));
867       copy->timestamp = GNUNET_TIME_absolute_get ();
868       rel = copy->rel;
869       if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
870       {
871         rel->retry_timer =
872             GNUNET_TIME_relative_multiply (rel->expected_delay,
873                                           MESH_RETRANSMIT_MARGIN);
874         rel->retry_task =
875             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
876                                           &channel_retransmit_message,
877                                           rel);
878       }
879       break;
880
881
882     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
883       rel = ch_q->rel;
884       GNUNET_assert (rel->ack_q == ch_q);
885       rel->ack_q = NULL;
886       break;
887
888
889     default:
890       GNUNET_break (0);
891   }
892
893   GNUNET_free (ch_q);
894 }
895
896
897 /**
898  * Save a copy to retransmit in case it gets lost.
899  *
900  * Initializes all needed callbacks and timers.
901  *
902  * @param ch Channel this message goes on.
903  * @param msg Message to copy.
904  * @param fwd Is this fwd traffic?
905  */
906 static struct MeshReliableMessage *
907 channel_save_copy (struct MeshChannel *ch,
908                    const struct GNUNET_MessageHeader *msg,
909                    int fwd)
910 {
911   struct MeshChannelReliability *rel;
912   struct MeshReliableMessage *copy;
913   uint32_t mid;
914   uint16_t type;
915   uint16_t size;
916
917   rel = fwd ? ch->root_rel : ch->dest_rel;
918   mid = rel->mid_send - 1;
919   type = ntohs (msg->type);
920   size = ntohs (msg->size);
921
922   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u %s\n", mid, GM_m2s (type));
923   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
924   copy->mid = mid;
925   copy->rel = rel;
926   copy->type = type;
927   memcpy (&copy[1], msg, size);
928   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
929
930   return copy;
931 }
932
933
934 /**
935  * Create a new channel.
936  *
937  * @param t Tunnel this channel is in.
938  * @param owner Client that owns the channel, NULL for foreign channels.
939  * @param lid_root Local ID for root client.
940  *
941  * @return A new initialized channel. NULL on error.
942  */
943 static struct MeshChannel *
944 channel_new (struct MeshTunnel3 *t,
945              struct MeshClient *owner,
946              MESH_ChannelNumber lid_root)
947 {
948   struct MeshChannel *ch;
949
950   ch = GNUNET_new (struct MeshChannel);
951   ch->root = owner;
952   ch->lid_root = lid_root;
953   ch->t = t;
954
955   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
956
957   if (NULL != owner)
958   {
959     ch->gid = GMT_get_next_chid (t);
960     GML_channel_add (owner, lid_root, ch);
961   }
962   GMT_add_channel (t, ch);
963
964   return ch;
965 }
966
967
968 /**
969  * Set options in a channel, extracted from a bit flag field
970  *
971  * @param ch Channel to set options to.
972  * @param options Bit array in host byte order.
973  */
974 static void
975 channel_set_options (struct MeshChannel *ch, uint32_t options)
976 {
977   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
978                  GNUNET_YES : GNUNET_NO;
979   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
980                  GNUNET_YES : GNUNET_NO;
981 }
982
983 static int
984 is_loopback (const struct MeshChannel *ch)
985 {
986   if (NULL != ch->t)
987     return GMT_is_loopback (ch->t);
988
989   return (NULL != ch->root && NULL != ch->dest);
990 }
991
992
993 /**
994  * Handle a loopback message: call the appropriate handler for the message type.
995  *
996  * @param ch Channel this message is on.
997  * @param msgh Message header.
998  * @param fwd Is this FWD traffic?
999  */
1000 void
1001 handle_loopback (struct MeshChannel *ch,
1002                  const struct GNUNET_MessageHeader *msgh,
1003                  int fwd)
1004 {
1005   uint16_t type;
1006
1007   type = ntohs (msgh->type);
1008   LOG (GNUNET_ERROR_TYPE_DEBUG,
1009        "Loopback %s %s message!\n",
1010        GM_f2s (fwd), GM_m2s (type));
1011
1012   switch (type)
1013   {
1014     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1015       /* Don't send hop ACK, wait for client to ACK */
1016       GMCH_handle_data (ch, (struct GNUNET_MESH_Data *) msgh, fwd);
1017       break;
1018
1019     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1020       GMCH_handle_data_ack (ch, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1021       break;
1022
1023     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1024       GMCH_handle_create (ch->t,
1025                           (struct GNUNET_MESH_ChannelCreate *) msgh);
1026       break;
1027
1028     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1029       GMCH_handle_ack (ch,
1030                        (struct GNUNET_MESH_ChannelManage *) msgh,
1031                        fwd);
1032       break;
1033
1034     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1035       GMCH_handle_nack (ch);
1036       break;
1037
1038     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1039       GMCH_handle_destroy (ch,
1040                            (struct GNUNET_MESH_ChannelManage *) msgh,
1041                            fwd);
1042       break;
1043
1044     default:
1045       GNUNET_break_op (0);
1046       LOG (GNUNET_ERROR_TYPE_DEBUG,
1047            "end-to-end message not known (%u)\n",
1048            ntohs (msgh->type));
1049   }
1050 }
1051
1052
1053
1054 /******************************************************************************/
1055 /********************************    API    ***********************************/
1056 /******************************************************************************/
1057
1058 /**
1059  * Destroy a channel and free all resources.
1060  *
1061  * @param ch Channel to destroy.
1062  */
1063 void
1064 GMCH_destroy (struct MeshChannel *ch)
1065 {
1066   struct MeshClient *c;
1067
1068   if (NULL == ch)
1069     return;
1070
1071   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
1072               GMT_2s (ch->t), ch->gid);
1073   GMCH_debug (ch);
1074
1075   c = ch->root;
1076   if (NULL != c)
1077   {
1078     GML_channel_remove (c, ch->lid_root, ch);
1079   }
1080
1081   c = ch->dest;
1082   if (NULL != c)
1083   {
1084     GML_channel_remove (c, ch->lid_dest, ch);
1085   }
1086
1087   channel_rel_free_all (ch->root_rel);
1088   channel_rel_free_all (ch->dest_rel);
1089
1090   GMT_remove_channel (ch->t, ch);
1091   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
1092
1093   GNUNET_free (ch);
1094 }
1095
1096
1097 /**
1098  * Get channel ID.
1099  *
1100  * @param ch Channel.
1101  *
1102  * @return ID
1103  */
1104 MESH_ChannelNumber
1105 GMCH_get_id (const struct MeshChannel *ch)
1106 {
1107   return ch->gid;
1108 }
1109
1110
1111 /**
1112  * Get the channel tunnel.
1113  *
1114  * @param ch Channel to get the tunnel from.
1115  *
1116  * @return tunnel of the channel.
1117  */
1118 struct MeshTunnel3 *
1119 GMCH_get_tunnel (const struct MeshChannel *ch)
1120 {
1121   return ch->t;
1122 }
1123
1124
1125 /**
1126  * Get free buffer space towards the client on a specific channel.
1127  *
1128  * @param ch Channel.
1129  * @param fwd Is query about FWD traffic?
1130  *
1131  * @return Free buffer space [0 - 64]
1132  */
1133 unsigned int
1134 GMCH_get_buffer (struct MeshChannel *ch, int fwd)
1135 {
1136   struct MeshChannelReliability *rel;
1137
1138   rel = fwd ? ch->dest_rel : ch->root_rel;
1139
1140   /* If rel is NULL it means that the end is not yet created,
1141    * most probably is a loopback channel at the point of sending
1142    * the ChannelCreate to itself.
1143    */
1144   if (NULL == rel)
1145     return 64;
1146
1147   return (64 - rel->n_recv);
1148 }
1149
1150
1151 /**
1152  * Get flow control status of end point: is client allow to send?
1153  *
1154  * @param ch Channel.
1155  * @param fwd Is query about FWD traffic? (Request root status).
1156  *
1157  * @return #GNUNET_YES if client is allowed to send us data.
1158  */
1159 int
1160 GMCH_get_allowed (struct MeshChannel *ch, int fwd)
1161 {
1162   struct MeshChannelReliability *rel;
1163
1164   rel = fwd ? ch->root_rel : ch->dest_rel;
1165
1166   return rel->client_allowed;
1167 }
1168
1169
1170 /**
1171  * Is the root client for this channel on this peer?
1172  *
1173  * @param ch Channel.
1174  * @param fwd Is this for fwd traffic?
1175  *
1176  * @return #GNUNET_YES in case it is.
1177  */
1178 int
1179 GMCH_is_origin (struct MeshChannel *ch, int fwd)
1180 {
1181   struct MeshClient *c;
1182
1183   c = fwd ? ch->root : ch->dest;
1184   return NULL != c;
1185 }
1186
1187
1188 /**
1189  * Is the destination client for this channel on this peer?
1190  *
1191  * @param ch Channel.
1192  * @param fwd Is this for fwd traffic?
1193  *
1194  * @return #GNUNET_YES in case it is.
1195  */
1196 int
1197 GMCH_is_terminal (struct MeshChannel *ch, int fwd)
1198 {
1199   struct MeshClient *c;
1200
1201   c = fwd ? ch->dest : ch->root;
1202   return NULL != c;
1203 }
1204
1205
1206 /**
1207  * Notify the destination client that a new incoming channel was created.
1208  *
1209  * @param ch Channel that was created.
1210  */
1211 void
1212 GMCH_send_create (struct MeshChannel *ch)
1213 {
1214   uint32_t opt;
1215
1216   if (NULL == ch->dest)
1217     return;
1218
1219   opt = 0;
1220   opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1221   opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1222   GML_send_channel_create (ch->dest, ch->lid_dest, ch->port, opt,
1223                            GMT_get_destination (ch->t));
1224
1225 }
1226
1227
1228 /**
1229  * Send an end-to-end ACK message for the most recent in-sequence payload.
1230  *
1231  * If channel is not reliable, do nothing.
1232  *
1233  * @param ch Channel this is about.
1234  * @param fwd Is for FWD traffic? (ACK dest->owner)
1235  */
1236 void
1237 GMCH_send_data_ack (struct MeshChannel *ch, int fwd)
1238 {
1239   struct GNUNET_MESH_DataACK msg;
1240   struct MeshChannelReliability *rel;
1241   struct MeshReliableMessage *copy;
1242   unsigned int delta;
1243   uint64_t mask;
1244   uint32_t ack;
1245
1246   if (GNUNET_NO == ch->reliable)
1247   {
1248     return;
1249   }
1250   rel = fwd ? ch->dest_rel : ch->root_rel;
1251   ack = rel->mid_recv - 1;
1252   LOG (GNUNET_ERROR_TYPE_DEBUG,
1253               " !! Send DATA_ACK for %u\n",
1254               ack);
1255
1256   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA_ACK);
1257   msg.header.size = htons (sizeof (msg));
1258   msg.chid = htonl (ch->gid);
1259   msg.futures = 0;
1260   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
1261   {
1262     if (copy->type != GNUNET_MESSAGE_TYPE_MESH_DATA)
1263     {
1264       LOG (GNUNET_ERROR_TYPE_DEBUG,
1265            "!!  Type %s, expected DATA\n",
1266            GM_m2s (copy->type));
1267       continue;
1268     }
1269     if (copy->mid == ack + 1)
1270     {
1271       ack++;
1272       continue;
1273     }
1274     delta = copy->mid - (ack + 1);
1275     if (63 < delta)
1276       break;
1277     mask = 0x1LL << delta;
1278     msg.futures |= mask;
1279     LOG (GNUNET_ERROR_TYPE_DEBUG,
1280          " !! setting bit for %u (delta %u) (%llX) -> %llX\n",
1281          copy->mid, delta, mask, msg.futures);
1282   }
1283   msg.mid = htonl (ack);
1284   LOG (GNUNET_ERROR_TYPE_DEBUG,
1285        "!!! ACK for %u, futures %llX\n",
1286        ack, msg.futures);
1287
1288   GMCH_send_prebuilt_message (&msg.header, ch, !fwd, GNUNET_NO);
1289   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1290 }
1291
1292
1293 /**
1294  * Allow a client to send us more data, in case it was choked.
1295  *
1296  * @param ch Channel.
1297  * @param fwd Is this about FWD traffic? (Root client).
1298  */
1299 void
1300 GMCH_allow_client (struct MeshChannel *ch, int fwd)
1301 {
1302   struct MeshChannelReliability *rel;
1303   unsigned int buffer;
1304
1305   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH allow\n");
1306
1307   if (MESH_CHANNEL_READY != ch->state)
1308   {
1309     LOG (GNUNET_ERROR_TYPE_DEBUG, " channel not ready yet!\n");
1310     return;
1311   }
1312
1313   if (GNUNET_YES == ch->reliable)
1314   {
1315     rel = fwd ? ch->root_rel : ch->dest_rel;
1316     if (NULL == rel)
1317     {
1318       GNUNET_break (0);
1319       return;
1320     }
1321     if (NULL != rel->head_sent && 64 <= rel->mid_send - rel->head_sent->mid)
1322     {
1323       LOG (GNUNET_ERROR_TYPE_DEBUG, " too big MID gap! Wait for ACK.\n");
1324       return;
1325     }
1326   }
1327
1328   if (is_loopback (ch))
1329     buffer = GMCH_get_buffer (ch, fwd);
1330   else
1331     buffer = GMT_get_connections_buffer (ch->t);
1332
1333   if (0 == buffer)
1334   {
1335     LOG (GNUNET_ERROR_TYPE_DEBUG, " no buffer space.\n");
1336     return;
1337   }
1338
1339   LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space %u, allowing\n", buffer);
1340   send_client_ack (ch, fwd);
1341 }
1342
1343
1344 /**
1345  * Log channel info.
1346  *
1347  * @param ch Channel.
1348  */
1349 void
1350 GMCH_debug (struct MeshChannel *ch)
1351 {
1352   if (NULL == ch)
1353   {
1354     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
1355     return;
1356   }
1357   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X (%p)\n",
1358               GMT_2s (ch->t), ch->gid, ch);
1359   LOG (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
1360               ch->root, ch->root_rel);
1361   if (NULL != ch->root)
1362   {
1363     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->root));
1364     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1365                 ch->root_rel->client_ready ? "YES" : "NO");
1366     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_root);
1367   }
1368   LOG (GNUNET_ERROR_TYPE_DEBUG, "  dest %p/%p\n",
1369               ch->dest, ch->dest_rel);
1370   if (NULL != ch->dest)
1371   {
1372     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->dest));
1373     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1374                 ch->dest_rel->client_ready ? "YES" : "NO");
1375     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_dest);
1376   }
1377 }
1378
1379
1380 /**
1381  * Handle an ACK given by a client.
1382  *
1383  * Mark client as ready and send him any buffered data we could have for him.
1384  *
1385  * @param ch Channel.
1386  * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by dest and go BCK)
1387  */
1388 void
1389 GMCH_handle_local_ack (struct MeshChannel *ch, int fwd)
1390 {
1391   struct MeshChannelReliability *rel;
1392   struct MeshClient *c;
1393
1394   rel = fwd ? ch->dest_rel : ch->root_rel;
1395   c   = fwd ? ch->dest     : ch->root;
1396
1397   rel->client_ready = GNUNET_YES;
1398   send_client_buffered_data (ch, c, fwd);
1399   if (is_loopback (ch))
1400   {
1401     unsigned int buffer;
1402
1403     buffer = GMCH_get_buffer (ch, fwd);
1404     if (0 < buffer)
1405       GMCH_allow_client (ch, fwd);
1406
1407     return;
1408   }
1409   GMT_send_connection_acks (ch->t);
1410 }
1411
1412
1413 /**
1414  * Handle data given by a client.
1415  *
1416  * Check whether the client is allowed to send in this tunnel, save if channel
1417  * is reliable and send an ACK to the client if there is still buffer space
1418  * in the tunnel.
1419  *
1420  * @param ch Channel.
1421  * @param c Client which sent the data.
1422  * @param message Message.
1423  * @param fwd Is this a FWD data?
1424  *
1425  * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
1426  */
1427 int
1428 GMCH_handle_local_data (struct MeshChannel *ch,
1429                         struct MeshClient *c,
1430                         struct GNUNET_MessageHeader *message,
1431                         int fwd)
1432 {
1433   struct MeshChannelReliability *rel;
1434   struct GNUNET_MESH_Data *payload;
1435   size_t size = ntohs (message->size);
1436   uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
1437   unsigned char cbuf[p2p_size];
1438
1439   /* Is the client in the channel? */
1440   if ( !( (fwd &&
1441            ch->root == c)
1442          ||
1443           (!fwd &&
1444            ch->dest == c) ) )
1445   {
1446     GNUNET_break_op (0);
1447     return GNUNET_SYSERR;
1448   }
1449
1450   rel = fwd ? ch->root_rel : ch->dest_rel;
1451
1452   if (GNUNET_NO == rel->client_allowed)
1453   {
1454     GNUNET_break_op (0);
1455     return GNUNET_SYSERR;
1456   }
1457
1458   rel->client_allowed = GNUNET_NO;
1459
1460   /* Ok, everything is correct, send the message. */
1461   payload = (struct GNUNET_MESH_Data *) cbuf;
1462   payload->mid = htonl (rel->mid_send);
1463   rel->mid_send++;
1464   memcpy (&payload[1], message, size);
1465   payload->header.size = htons (p2p_size);
1466   payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
1467   payload->chid = htonl (ch->gid);
1468   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1469   GMCH_send_prebuilt_message (&payload->header, ch, fwd, GNUNET_NO);
1470
1471   if (is_loopback (ch))
1472   {
1473     if (GMCH_get_buffer (ch, fwd) > 0)
1474       send_client_ack (ch, fwd);
1475
1476     return GNUNET_OK;
1477   }
1478
1479   if (GMT_get_connections_buffer (ch->t) > 0)
1480   {
1481     send_client_ack (ch, fwd);
1482   }
1483
1484   return GNUNET_OK;
1485 }
1486
1487
1488 /**
1489  * Handle a channel destroy requested by a client.
1490  *
1491  * Destroy the channel and the tunnel in case this was the last channel.
1492  *
1493  * @param ch Channel.
1494  * @param c Client that requested the destruction (to avoid notifying him).
1495  * @param is_root Is the request coming from root?
1496  */
1497 void
1498 GMCH_handle_local_destroy (struct MeshChannel *ch,
1499                            struct MeshClient *c,
1500                            int is_root)
1501 {
1502   struct MeshTunnel3 *t;
1503
1504   /* Cleanup after the tunnel */
1505   if (GNUNET_NO == is_root && c == ch->dest)
1506   {
1507     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
1508     GML_client_delete_channel (c, ch, ch->lid_dest);
1509     ch->dest = NULL;
1510   }
1511   if (GNUNET_YES == is_root && c == ch->root)
1512   {
1513     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
1514     GML_client_delete_channel (c, ch, ch->lid_root);
1515     ch->root = NULL;
1516   }
1517
1518   t = ch->t;
1519   send_destroy (ch, GNUNET_NO);
1520   GMCH_destroy (ch);
1521   GMT_destroy_if_empty (t);
1522 }
1523
1524
1525 /**
1526  * Handle a channel create requested by a client.
1527  *
1528  * Create the channel and the tunnel in case this was the first0 channel.
1529  *
1530  * @param c Client that requested the creation (will be the root).
1531  * @param msg Create Channel message.
1532  *
1533  * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
1534  */
1535 int
1536 GMCH_handle_local_create (struct MeshClient *c,
1537                           struct GNUNET_MESH_ChannelMessage *msg)
1538 {
1539   struct MeshChannel *ch;
1540   struct MeshTunnel3 *t;
1541   struct MeshPeer *peer;
1542   MESH_ChannelNumber chid;
1543
1544   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
1545               GNUNET_i2s (&msg->peer), ntohl (msg->port));
1546   chid = ntohl (msg->channel_id);
1547
1548   /* Sanity check for duplicate channel IDs */
1549   if (NULL != GML_channel_get (c, chid))
1550   {
1551     GNUNET_break (0);
1552     return GNUNET_SYSERR;
1553   }
1554
1555   peer = GMP_get (&msg->peer);
1556   GMP_add_tunnel (peer);
1557   t = GMP_get_tunnel (peer);
1558
1559   if (GMP_get_short_id (peer) == myid)
1560   {
1561     GMT_change_cstate (t, MESH_TUNNEL3_READY);
1562   }
1563   else
1564   {
1565     GMP_connect (peer);
1566   }
1567
1568   /* Create channel */
1569   ch = channel_new (t, c, chid);
1570   if (NULL == ch)
1571   {
1572     GNUNET_break (0);
1573     return GNUNET_SYSERR;
1574   }
1575   ch->port = ntohl (msg->port);
1576   channel_set_options (ch, ntohl (msg->opt));
1577
1578   /* In unreliable channels, we'll use the DLL to buffer BCK data */
1579   ch->root_rel = GNUNET_new (struct MeshChannelReliability);
1580   ch->root_rel->ch = ch;
1581   ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;
1582
1583   LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s\n", GMCH_2s (ch));
1584
1585   /* Send create channel */
1586   {
1587     struct GNUNET_MESH_ChannelCreate msgcc;
1588
1589     msgcc.header.size = htons (sizeof (msgcc));
1590     msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
1591     msgcc.chid = htonl (ch->gid);
1592     msgcc.port = msg->port;
1593     msgcc.opt = msg->opt;
1594
1595     GMT_send_prebuilt_message (&msgcc.header, t, ch, GNUNET_YES, NULL, NULL);
1596   }
1597   return GNUNET_OK;
1598 }
1599
1600
1601 /**
1602  * Handler for mesh network payload traffic.
1603  *
1604  * @param ch Channel for the message.
1605  * @param msg Unencryted data message.
1606  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1607  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1608  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1609  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1610  */
1611 void
1612 GMCH_handle_data (struct MeshChannel *ch,
1613                   const struct GNUNET_MESH_Data *msg,
1614                   int fwd)
1615 {
1616   struct MeshChannelReliability *rel;
1617   struct MeshClient *c;
1618   uint32_t mid;
1619
1620   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1621   if (GNUNET_SYSERR == fwd)
1622   {
1623     if (is_loopback (ch))
1624     {
1625       /* It is a loopback channel after all... */
1626       GNUNET_break (0);
1627       return;
1628     }
1629     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1630   }
1631
1632   /*  Initialize FWD/BCK data */
1633   c   = fwd ? ch->dest     : ch->root;
1634   rel = fwd ? ch->dest_rel : ch->root_rel;
1635
1636   if (NULL == c)
1637   {
1638     GNUNET_break (0);
1639     return;
1640   }
1641
1642   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
1643
1644   mid = ntohl (msg->mid);
1645   LOG (GNUNET_ERROR_TYPE_DEBUG, "!! got mid %u\n", mid);
1646
1647   if (GNUNET_NO == ch->reliable ||
1648       ( !GM_is_pid_bigger (rel->mid_recv, mid) &&
1649         GM_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1650   {
1651     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
1652     if (GNUNET_YES == ch->reliable)
1653     {
1654       /* Is this the exact next expected messasge? */
1655       if (mid == rel->mid_recv)
1656       {
1657         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
1658         rel->mid_recv++;
1659         send_client_data (ch, msg, fwd);
1660       }
1661       else
1662       {
1663         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1664         add_buffered_data (msg, rel);
1665       }
1666     }
1667     else
1668     {
1669       /* Tunnel is unreliable: send to clients directly */
1670       /* FIXME: accept Out Of Order traffic */
1671       rel->mid_recv = mid + 1;
1672       send_client_data (ch, msg, fwd);
1673     }
1674   }
1675   else
1676   {
1677     GNUNET_break_op (0);
1678     LOG (GNUNET_ERROR_TYPE_DEBUG,
1679                 " MID %u not expected (%u - %u), dropping!\n",
1680                 mid, rel->mid_recv, rel->mid_recv + 63);
1681   }
1682
1683   GMCH_send_data_ack (ch, fwd);
1684 }
1685
1686
1687 /**
1688  * Handler for mesh network traffic end-to-end ACKs.
1689  *
1690  * @param ch Channel on which we got this message.
1691  * @param msg Data message.
1692  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1693  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1694  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1695  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1696  */
1697 void
1698 GMCH_handle_data_ack (struct MeshChannel *ch,
1699                       const struct GNUNET_MESH_DataACK *msg,
1700                       int fwd)
1701 {
1702   struct MeshChannelReliability *rel;
1703   struct MeshReliableMessage *copy;
1704   struct MeshReliableMessage *next;
1705   uint32_t ack;
1706   int work;
1707
1708   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1709   if (GNUNET_SYSERR == fwd)
1710   {
1711     if (is_loopback (ch))
1712     {
1713       /* It is a loopback channel after all... */
1714       GNUNET_break (0);
1715       return;
1716     }
1717     /* Inverted: if message came 'FWD' is a 'BCK ACK'. */
1718     fwd = (NULL != ch->dest) ? GNUNET_NO : GNUNET_YES;
1719   }
1720
1721   ack = ntohl (msg->mid);
1722   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
1723        (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
1724
1725   if (GNUNET_YES == fwd)
1726   {
1727     rel = ch->root_rel;
1728   }
1729   else
1730   {
1731     rel = ch->dest_rel;
1732   }
1733   if (NULL == rel)
1734   {
1735     GNUNET_break_op (0);
1736     return;
1737   }
1738
1739   /* Free ACK'd copies: no need to retransmit those anymore */
1740   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
1741   {
1742     if (GM_is_pid_bigger (copy->mid, ack))
1743     {
1744       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
1745       channel_rel_free_sent (rel, msg);
1746       break;
1747     }
1748     work = GNUNET_YES;
1749     LOG (GNUNET_ERROR_TYPE_DEBUG, " !!  id %u\n", copy->mid);
1750     next = copy->next;
1751     rel_message_free (copy, GNUNET_YES);
1752   }
1753
1754   /* ACK client if needed */
1755   GMCH_allow_client (ch, fwd);
1756
1757   /* If some message was free'd, update the retransmission delay */
1758   if (GNUNET_YES == work)
1759   {
1760     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
1761     {
1762       GNUNET_SCHEDULER_cancel (rel->retry_task);
1763       if (NULL == rel->head_sent)
1764       {
1765         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
1766       }
1767       else
1768       {
1769         struct GNUNET_TIME_Absolute new_target;
1770         struct GNUNET_TIME_Relative delay;
1771
1772         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
1773                                                MESH_RETRANSMIT_MARGIN);
1774         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
1775                                                delay);
1776         delay = GNUNET_TIME_absolute_get_remaining (new_target);
1777         rel->retry_task =
1778             GNUNET_SCHEDULER_add_delayed (delay,
1779                                           &channel_retransmit_message,
1780                                           rel);
1781       }
1782     }
1783     else
1784       GNUNET_break (0);
1785   }
1786 }
1787
1788
1789 /**
1790  * Handler for channel create messages.
1791  *
1792  * Does not have fwd parameter because it's always 'FWD': channel is incoming.
1793  *
1794  * @param t Tunnel this channel will be in.
1795  * @param msg Channel crate message.
1796  */
1797 struct MeshChannel *
1798 GMCH_handle_create (struct MeshTunnel3 *t,
1799                     const struct GNUNET_MESH_ChannelCreate *msg)
1800 {
1801   MESH_ChannelNumber chid;
1802   struct MeshChannel *ch;
1803   struct MeshClient *c;
1804
1805   chid = ntohl (msg->chid);
1806
1807   ch = GMT_get_channel (t, chid);
1808   if (NULL == ch)
1809   {
1810     /* Create channel */
1811     ch = channel_new (t, NULL, 0);
1812     ch->gid = chid;
1813   }
1814   channel_set_options (ch, ntohl (msg->opt));
1815
1816   /* Find a destination client */
1817   ch->port = ntohl (msg->port);
1818   LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", ch->port);
1819   c = GML_client_get_by_port (ch->port);
1820   if (NULL == c)
1821   {
1822     /* TODO send reject */
1823     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
1824     if (is_loopback (ch))
1825     {
1826       LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback: destroy on handler\n");
1827       channel_send_nack (ch);
1828     }
1829     else
1830     {
1831       LOG (GNUNET_ERROR_TYPE_DEBUG, "  not loopback: destroy now\n");
1832       channel_send_nack (ch);
1833       GMCH_destroy (ch);
1834     }
1835     return NULL;
1836   }
1837   else
1838   {
1839     LOG (GNUNET_ERROR_TYPE_DEBUG, "  client %p has port registered\n", c);
1840   }
1841
1842   add_destination (ch, c);
1843   if (GNUNET_YES == ch->reliable)
1844     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
1845   else
1846     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Not Reliable\n");
1847
1848   GMCH_send_create (ch);
1849   channel_send_ack (ch, GNUNET_YES);
1850
1851   return ch;
1852 }
1853
1854
1855 /**
1856  * Handler for channel NACK messages.
1857  *
1858  * NACK messages always go dest -> root, no need for 'fwd' or 'msg' parameter.
1859  *
1860  * @param ch Channel.
1861  */
1862 void
1863 GMCH_handle_nack (struct MeshChannel *ch)
1864 {
1865   send_client_nack (ch);
1866   GMCH_destroy (ch);
1867 }
1868
1869
1870 /**
1871  * Handler for channel ack messages.
1872  *
1873  * @param ch Channel.
1874  * @param msg Message.
1875  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1876  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1877  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1878  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1879  */
1880 void
1881 GMCH_handle_ack (struct MeshChannel *ch,
1882                  const struct GNUNET_MESH_ChannelManage *msg,
1883                  int fwd)
1884 {
1885   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1886   if (GNUNET_SYSERR == fwd)
1887   {
1888     if (is_loopback (ch))
1889     {
1890       /* It is a loopback channel after all... */
1891       GNUNET_break (0);
1892       return;
1893     }
1894     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1895   }
1896
1897   channel_confirm (ch, !fwd);
1898 }
1899
1900
1901 /**
1902  * Handler for channel destroy messages.
1903  *
1904  * @param ch Channel to be destroyed of.
1905  * @param msg Message.
1906  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1907  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1908  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1909  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1910  */
1911 void
1912 GMCH_handle_destroy (struct MeshChannel *ch,
1913                      const struct GNUNET_MESH_ChannelManage *msg,
1914                      int fwd)
1915 {
1916   struct MeshTunnel3 *t;
1917
1918   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1919   if (GNUNET_SYSERR == fwd)
1920   {
1921     if (is_loopback (ch))
1922     {
1923       /* It is a loopback channel after all... */
1924       GNUNET_break (0);
1925       return;
1926     }
1927     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1928   }
1929
1930   GMCH_debug (ch);
1931   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
1932   {
1933     /* Not for us (don't destroy twice a half-open loopback channel) */
1934     return;
1935   }
1936
1937   t = ch->t;
1938   send_destroy (ch, GNUNET_YES);
1939   GMCH_destroy (ch);
1940   GMT_destroy_if_empty (t);
1941 }
1942
1943
1944 /**
1945  * Sends an already built message on a channel.
1946  *
1947  * If the channel is on a loopback tunnel, notifies the appropriate destination
1948  * client locally.
1949  *
1950  * On a normal channel passes the message to the tunnel for encryption and
1951  * sending on a connection.
1952  *
1953  * This function DOES NOT save the message for retransmission.
1954  *
1955  * @param message Message to send. Function makes a copy of it.
1956  * @param ch Channel on which this message is transmitted.
1957  * @param fwd Is this a fwd message?
1958  * @param retransmission Is this a retransmission? (Don't save a copy)
1959  */
1960 void
1961 GMCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1962                             struct MeshChannel *ch, int fwd,
1963                             int retransmission)
1964 {
1965   uint16_t type;
1966
1967   type = ntohs (message->type);
1968   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH Send %s %s on channel %s\n",
1969        GM_f2s (fwd), GM_m2s (type),
1970        GMCH_2s (ch));
1971
1972   if (GMT_is_loopback (ch->t))
1973   {
1974     handle_loopback (ch, message, fwd);
1975     return;
1976   }
1977
1978   if (GNUNET_YES == ch->reliable && GNUNET_NO == retransmission
1979       && GNUNET_MESSAGE_TYPE_MESH_DATA == type)
1980   {
1981     struct MeshChannelQueue *q;
1982
1983     q = GNUNET_new (struct MeshChannelQueue);
1984     q->type = type;
1985     q->copy = channel_save_copy (ch, message, fwd);
1986     q->q = GMT_send_prebuilt_message (message, ch->t, ch, fwd,
1987                                       &ch_message_sent, q);
1988     /* Don't store q itself: we never need to cancel messages */
1989   }
1990   else if (GNUNET_MESSAGE_TYPE_MESH_DATA_ACK == type)
1991   {
1992     struct MeshChannelReliability *rel;
1993
1994     rel = fwd ? ch->root_rel : ch->dest_rel;
1995     if (NULL != rel->ack_q)
1996     {
1997       GMT_cancel (rel->ack_q->q);
1998       /* ch_message_sent is called, freeing ack_q */
1999     }
2000     rel->ack_q = GNUNET_new (struct MeshChannelQueue);
2001     rel->ack_q->type = type;
2002     rel->ack_q->rel = rel;
2003     rel->ack_q->q = GMT_send_prebuilt_message (message, ch->t, ch, fwd,
2004                                                &ch_message_sent, rel->ack_q);
2005   }
2006   else
2007     GNUNET_break (NULL == GMT_send_prebuilt_message (message, ch->t, ch, fwd,
2008                                                      NULL, NULL));
2009 }
2010
2011
2012 /**
2013  * Get the static string for identification of the channel.
2014  *
2015  * @param ch Channel.
2016  *
2017  * @return Static string with the channel IDs.
2018  */
2019 const char *
2020 GMCH_2s (const struct MeshChannel *ch)
2021 {
2022   static char buf[64];
2023
2024   if (NULL == ch)
2025     return "(NULL Channel)";
2026
2027   sprintf (buf, "%s:%u gid:%X (%X / %X)",
2028            GMT_2s (ch->t), ch->port, ch->gid, ch->lid_root, ch->lid_dest);
2029
2030   return buf;
2031 }