- fix super-fast (< 20ms) retransmission behavior when the RTT is smaller than the...
[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 MeshChannelQueue       *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 (reliable) messages pending ACK for this channel.
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.rel_value_us = 0;
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       LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE RECV %p\n", copy);
472       GNUNET_free (copy);
473     }
474     else
475     {
476       LOG (GNUNET_ERROR_TYPE_DEBUG,
477            " reliable && don't have %u, next is %u\n",
478            rel->mid_recv,
479            copy->mid);
480       return;
481     }
482   }
483   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
484 }
485
486
487 /**
488  * Allow a client to send more data.
489  *
490  * In case the client was already allowed to send data, do nothing.
491  *
492  * @param ch Channel.
493  * @param fwd Is this a FWD ACK? (FWD ACKs are sent to root)
494  */
495 static void
496 send_client_ack (struct MeshChannel *ch, int fwd)
497 {
498   struct MeshChannelReliability *rel = fwd ? ch->root_rel : ch->dest_rel;
499
500   LOG (GNUNET_ERROR_TYPE_DEBUG,
501        "  sending %s ack to client on channel %s\n",
502        GM_f2s (fwd), GMCH_2s (ch));
503
504   if (NULL == rel)
505   {
506     GNUNET_break (0);
507     return;
508   }
509
510   if (GNUNET_YES == rel->client_allowed)
511   {
512     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already allowed\n");
513     return;
514   }
515   rel->client_allowed = GNUNET_YES;
516
517   GML_send_ack (fwd ? ch->root : ch->dest, fwd ? ch->lid_root : ch->lid_dest);
518 }
519
520
521 /**
522  * Notify the root that the destination rejected the channel.
523  *
524  * @param ch Rejected channel.
525  */
526 static void
527 send_client_nack (struct MeshChannel *ch)
528 {
529   if (NULL == ch->root)
530   {
531     GNUNET_break (0);
532     return;
533   }
534   GML_send_nack (ch->root, ch->lid_root);
535 }
536
537
538 /**
539  * Notify a client that the channel is no longer valid.
540  *
541  * @param ch Channel that is destroyed.
542  * @param local_only Should we avoid sending it to other peers?
543  */
544 static void
545 send_destroy (struct MeshChannel *ch, int local_only)
546 {
547   struct GNUNET_MESH_ChannelManage msg;
548
549   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
550   msg.header.size = htons (sizeof (msg));
551   msg.chid = htonl (ch->gid);
552
553   /* If root is not NULL, notify.
554    * If it's NULL, check lid_root. When a local destroy comes in, root
555    * is set to NULL but lid_root is left untouched. In this case, do nothing,
556    * the client is the one who reuqested the channel to be destroyed.
557    */
558   if (NULL != ch->root)
559     GML_send_channel_destroy (ch->root, ch->lid_root);
560   else if (0 == ch->lid_root && GNUNET_NO == local_only)
561     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO, NULL);
562
563   if (NULL != ch->dest)
564     GML_send_channel_destroy (ch->dest, ch->lid_dest);
565   else if (0 == ch->lid_dest && GNUNET_NO == local_only)
566     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_YES, NULL);
567 }
568
569
570 /**
571  * Destroy all reliable messages queued for a channel,
572  * during a channel destruction.
573  * Frees the reliability structure itself.
574  *
575  * @param rel Reliability data for a channel.
576  */
577 static void
578 channel_rel_free_all (struct MeshChannelReliability *rel)
579 {
580   struct MeshReliableMessage *copy;
581   struct MeshReliableMessage *next;
582
583   if (NULL == rel)
584     return;
585
586   for (copy = rel->head_recv; NULL != copy; copy = next)
587   {
588     next = copy->next;
589     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
590     LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE BATCH RECV %p\n", copy);
591     GNUNET_free (copy);
592   }
593   for (copy = rel->head_sent; NULL != copy; copy = next)
594   {
595     next = copy->next;
596     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
597     LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE BATCH %p\n", copy);
598     GNUNET_free (copy);
599   }
600   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
601   {
602     GNUNET_SCHEDULER_cancel (rel->retry_task);
603   }
604   if (NULL != rel->ack_q)
605     GMT_cancel (rel->ack_q->q);
606   GNUNET_free (rel);
607 }
608
609
610 /**
611  * Mark future messages as ACK'd.
612  *
613  * @param rel Reliability data.
614  * @param msg DataACK message with a bitfield of future ACK'd messages.
615  */
616 static void
617 channel_rel_free_sent (struct MeshChannelReliability *rel,
618                        const struct GNUNET_MESH_DataACK *msg)
619 {
620   struct MeshReliableMessage *copy;
621   struct MeshReliableMessage *next;
622   uint64_t bitfield;
623   uint64_t mask;
624   uint32_t mid;
625   uint32_t target;
626   unsigned int i;
627
628   bitfield = msg->futures;
629   mid = ntohl (msg->mid);
630   LOG (GNUNET_ERROR_TYPE_DEBUG,
631               "!!! free_sent_reliable %u %llX\n",
632               mid, bitfield);
633   LOG (GNUNET_ERROR_TYPE_DEBUG,
634               " rel %p, head %p\n",
635               rel, rel->head_sent);
636   for (i = 0, copy = rel->head_sent;
637        i < 64 && NULL != copy && 0 != bitfield;
638        i++)
639   {
640     LOG (GNUNET_ERROR_TYPE_DEBUG,
641                 " trying bit %u (mid %u)\n",
642                 i, mid + i + 1);
643     mask = 0x1LL << i;
644     if (0 == (bitfield & mask))
645      continue;
646
647     LOG (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
648     /* Bit was set, clear the bit from the bitfield */
649     bitfield &= ~mask;
650
651     /* The i-th bit was set. Do we have that copy? */
652     /* Skip copies with mid < target */
653     target = mid + i + 1;
654     LOG (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
655     while (NULL != copy && GM_is_pid_bigger (target, copy->mid))
656      copy = copy->next;
657
658     /* Did we run out of copies? (previously freed, it's ok) */
659     if (NULL == copy)
660     {
661      LOG (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
662      return;
663     }
664
665     /* Did we overshoot the target? (previously freed, it's ok) */
666     if (GM_is_pid_bigger (copy->mid, target))
667     {
668      LOG (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
669      continue;
670     }
671
672     /* Now copy->mid == target, free it */
673     next = copy->next;
674     rel_message_free (copy, GNUNET_YES);
675     copy = next;
676   }
677   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
678 }
679
680
681 /**
682  * We haven't received an ACK after a certain time: restransmit the message.
683  *
684  * @param cls Closure (MeshReliableMessage with the message to restransmit)
685  * @param tc TaskContext.
686  */
687 static void
688 channel_retransmit_message (void *cls,
689                             const struct GNUNET_SCHEDULER_TaskContext *tc)
690 {
691   struct MeshChannelReliability *rel = cls;
692   struct MeshReliableMessage *copy;
693   struct MeshChannel *ch;
694   struct GNUNET_MESH_Data *payload;
695   int fwd;
696
697   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
698   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
699     return;
700
701   ch = rel->ch;
702   copy = rel->head_sent;
703   if (NULL == copy)
704   {
705     GNUNET_break (0);
706     return;
707   }
708
709   payload = (struct GNUNET_MESH_Data *) &copy[1];
710   fwd = (rel == ch->root_rel);
711
712   /* Message not found in the queue that we are going to use. */
713   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
714
715   GMCH_send_prebuilt_message (&payload->header, ch, fwd, copy);
716   GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
717 }
718
719
720 /**
721  * Destroy a reliable message after it has been acknowledged, either by
722  * direct mid ACK or bitfield. Updates the appropriate data structures and
723  * timers and frees all memory.
724  *
725  * @param copy Message that is no longer needed: remote peer got it.
726  * @param update_time Is the timing information relevant?
727  *                    If this message is ACK in a batch the timing information
728  *                    is skewed by the retransmission, count only for the
729  *                    retransmitted message.
730  */
731 static void
732 rel_message_free (struct MeshReliableMessage *copy, int update_time)
733 {
734   struct MeshChannelReliability *rel;
735   struct GNUNET_TIME_Relative time;
736
737   rel = copy->rel;
738   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
739   if (update_time)
740   {
741     time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
742     if (0 == rel->expected_delay.rel_value_us)
743       rel->expected_delay = time;
744     else
745     {
746       rel->expected_delay.rel_value_us *= 7;
747       rel->expected_delay.rel_value_us += time.rel_value_us;
748       rel->expected_delay.rel_value_us /= 8;
749     }
750     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
751                 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
752     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
753                 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
754                                                         GNUNET_NO));
755     rel->retry_timer = rel->expected_delay;
756   }
757   else
758   {
759     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! batch free, ignoring timing\n");
760   }
761   rel->ch->pending_messages--;
762   if (GNUNET_NO != rel->ch->destroy && 0 == rel->ch->pending_messages)
763   {
764     struct MeshTunnel3 *t = rel->ch->t;
765     GMCH_destroy (rel->ch);
766     GMT_destroy_if_empty (t);
767   }
768   if (NULL != copy->q)
769   {
770     GMT_cancel (copy->q->q);
771   }
772   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
773   LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE %p\n", copy);
774   GNUNET_free (copy);
775 }
776
777
778 /**
779  * Confirm we got a channel create.
780  *
781  * @param ch The channel to confirm.
782  * @param fwd Should we send a FWD ACK? (going dest->root)
783  */
784 static void
785 channel_send_ack (struct MeshChannel *ch, int fwd)
786 {
787   struct GNUNET_MESH_ChannelManage msg;
788
789   msg.header.size = htons (sizeof (msg));
790   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
791   LOG (GNUNET_ERROR_TYPE_DEBUG,
792               "  sending channel %s ack for channel %s\n",
793               GM_f2s (fwd), GMCH_2s (ch));
794
795   msg.chid = htonl (ch->gid);
796   GMCH_send_prebuilt_message (&msg.header, ch, !fwd, NULL);
797 }
798
799
800 /**
801  * Notify that a channel create didn't succeed.
802  *
803  * @param ch The channel to reject.
804  */
805 static void
806 channel_send_nack (struct MeshChannel *ch)
807 {
808   struct GNUNET_MESH_ChannelManage msg;
809
810   msg.header.size = htons (sizeof (msg));
811   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK);
812   LOG (GNUNET_ERROR_TYPE_DEBUG,
813        "  sending channel NACK for channel %s\n",
814        GMCH_2s (ch));
815
816   msg.chid = htonl (ch->gid);
817   GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO, NULL);
818 }
819
820
821 /**
822  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
823  *
824  * @param ch Channel to mark as ready.
825  * @param fwd Was the ACK message a FWD ACK? (dest->root, SYNACK)
826  */
827 static void
828 channel_confirm (struct MeshChannel *ch, int fwd)
829 {
830   struct MeshChannelReliability *rel;
831   struct MeshReliableMessage *copy;
832   struct MeshReliableMessage *next;
833
834   LOG (GNUNET_ERROR_TYPE_DEBUG,
835               "  channel confirm %s %s:%X\n",
836               GM_f2s (fwd), GMT_2s (ch->t), ch->gid);
837   ch->state = MESH_CHANNEL_READY;
838
839   rel = fwd ? ch->root_rel : ch->dest_rel;
840   rel->client_ready = GNUNET_YES;
841   for (copy = rel->head_sent; NULL != copy; copy = next)
842   {
843     struct GNUNET_MessageHeader *msg;
844
845     next = copy->next;
846     msg = (struct GNUNET_MessageHeader *) &copy[1];
847     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
848     {
849       rel_message_free (copy, GNUNET_YES);
850       /* TODO return? */
851     }
852   }
853   send_client_ack (ch, fwd);
854
855   /* In case of a FWD ACK (SYNACK) send a BCK ACK (ACK). */
856   if (fwd)
857     channel_send_ack (ch, !fwd);
858 }
859
860
861 /**
862  * Message has been sent: start retransmission timer.
863  *
864  * @param cls Closure (queue structure).
865  * @param t Tunnel.
866  * @param q Queue handler (no longer valid).
867  * @param type Type of message.
868  * @param size Size of the message.
869  */
870 static void
871 ch_message_sent (void *cls,
872                  struct MeshTunnel3 *t,
873                  struct MeshTunnel3Queue *q,
874                  uint16_t type, size_t size)
875 {
876   struct MeshChannelQueue *ch_q = cls;
877   struct MeshReliableMessage *copy = ch_q->copy;
878   struct MeshChannelReliability *rel;
879
880   switch (ch_q->type)
881   {
882     case GNUNET_MESSAGE_TYPE_MESH_DATA:
883       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SENT %u %s (c: %p, q: %p)\n",
884            copy->mid, GM_m2s (type), copy, copy->q);
885       GNUNET_assert (ch_q == copy->q);
886       copy->timestamp = GNUNET_TIME_absolute_get ();
887       rel = copy->rel;
888       if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
889       {
890         if (0 != rel->expected_delay.rel_value_us)
891         {
892           rel->retry_timer =
893               GNUNET_TIME_relative_multiply (rel->expected_delay,
894                                              MESH_RETRANSMIT_MARGIN);
895         }
896         else
897         {
898           rel->retry_timer = MESH_RETRANSMIT_TIME;
899         }
900         rel->retry_task =
901             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
902                                           &channel_retransmit_message,
903                                           rel);
904       }
905       copy->q = NULL;
906       break;
907
908
909     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
910       rel = ch_q->rel;
911       GNUNET_assert (rel->ack_q == ch_q);
912       rel->ack_q = NULL;
913       break;
914
915
916     default:
917       GNUNET_break (0);
918       GNUNET_free (ch_q);
919       return;
920   }
921
922   GNUNET_free (ch_q);
923 }
924
925
926 /**
927  * Save a copy to retransmit in case it gets lost.
928  *
929  * Initializes all needed callbacks and timers.
930  *
931  * @param ch Channel this message goes on.
932  * @param msg Message to copy.
933  * @param fwd Is this fwd traffic?
934  */
935 static struct MeshReliableMessage *
936 channel_save_copy (struct MeshChannel *ch,
937                    const struct GNUNET_MessageHeader *msg,
938                    int fwd)
939 {
940   struct MeshChannelReliability *rel;
941   struct MeshReliableMessage *copy;
942   uint32_t mid;
943   uint16_t type;
944   uint16_t size;
945
946   rel = fwd ? ch->root_rel : ch->dest_rel;
947   mid = rel->mid_send - 1;
948   type = ntohs (msg->type);
949   size = ntohs (msg->size);
950
951   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u %s\n", mid, GM_m2s (type));
952   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
953   LOG (GNUNET_ERROR_TYPE_DEBUG, "  at %p\n", copy);
954   copy->mid = mid;
955   copy->rel = rel;
956   copy->type = type;
957   memcpy (&copy[1], msg, size);
958   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
959   ch->pending_messages++;
960
961   return copy;
962 }
963
964
965 /**
966  * Create a new channel.
967  *
968  * @param t Tunnel this channel is in.
969  * @param owner Client that owns the channel, NULL for foreign channels.
970  * @param lid_root Local ID for root client.
971  *
972  * @return A new initialized channel. NULL on error.
973  */
974 static struct MeshChannel *
975 channel_new (struct MeshTunnel3 *t,
976              struct MeshClient *owner,
977              MESH_ChannelNumber lid_root)
978 {
979   struct MeshChannel *ch;
980
981   ch = GNUNET_new (struct MeshChannel);
982   ch->root = owner;
983   ch->lid_root = lid_root;
984   ch->t = t;
985
986   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
987
988   if (NULL != owner)
989   {
990     ch->gid = GMT_get_next_chid (t);
991     GML_channel_add (owner, lid_root, ch);
992   }
993   GMT_add_channel (t, ch);
994
995   return ch;
996 }
997
998
999 /**
1000  * Set options in a channel, extracted from a bit flag field
1001  *
1002  * @param ch Channel to set options to.
1003  * @param options Bit array in host byte order.
1004  */
1005 static void
1006 channel_set_options (struct MeshChannel *ch, uint32_t options)
1007 {
1008   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
1009                  GNUNET_YES : GNUNET_NO;
1010   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
1011                  GNUNET_YES : GNUNET_NO;
1012 }
1013
1014 static int
1015 is_loopback (const struct MeshChannel *ch)
1016 {
1017   if (NULL != ch->t)
1018     return GMT_is_loopback (ch->t);
1019
1020   return (NULL != ch->root && NULL != ch->dest);
1021 }
1022
1023
1024 /**
1025  * Handle a loopback message: call the appropriate handler for the message type.
1026  *
1027  * @param ch Channel this message is on.
1028  * @param msgh Message header.
1029  * @param fwd Is this FWD traffic?
1030  */
1031 void
1032 handle_loopback (struct MeshChannel *ch,
1033                  const struct GNUNET_MessageHeader *msgh,
1034                  int fwd)
1035 {
1036   uint16_t type;
1037
1038   type = ntohs (msgh->type);
1039   LOG (GNUNET_ERROR_TYPE_DEBUG,
1040        "Loopback %s %s message!\n",
1041        GM_f2s (fwd), GM_m2s (type));
1042
1043   switch (type)
1044   {
1045     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1046       /* Don't send hop ACK, wait for client to ACK */
1047       GMCH_handle_data (ch, (struct GNUNET_MESH_Data *) msgh, fwd);
1048       break;
1049
1050     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1051       GMCH_handle_data_ack (ch, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1052       break;
1053
1054     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1055       GMCH_handle_create (ch->t,
1056                           (struct GNUNET_MESH_ChannelCreate *) msgh);
1057       break;
1058
1059     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1060       GMCH_handle_ack (ch,
1061                        (struct GNUNET_MESH_ChannelManage *) msgh,
1062                        fwd);
1063       break;
1064
1065     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1066       GMCH_handle_nack (ch);
1067       break;
1068
1069     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1070       GMCH_handle_destroy (ch,
1071                            (struct GNUNET_MESH_ChannelManage *) msgh,
1072                            fwd);
1073       break;
1074
1075     default:
1076       GNUNET_break_op (0);
1077       LOG (GNUNET_ERROR_TYPE_DEBUG,
1078            "end-to-end message not known (%u)\n",
1079            ntohs (msgh->type));
1080   }
1081 }
1082
1083
1084
1085 /******************************************************************************/
1086 /********************************    API    ***********************************/
1087 /******************************************************************************/
1088
1089 /**
1090  * Destroy a channel and free all resources.
1091  *
1092  * @param ch Channel to destroy.
1093  */
1094 void
1095 GMCH_destroy (struct MeshChannel *ch)
1096 {
1097   struct MeshClient *c;
1098
1099   if (NULL == ch)
1100     return;
1101
1102   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
1103               GMT_2s (ch->t), ch->gid);
1104   GMCH_debug (ch);
1105
1106   c = ch->root;
1107   if (NULL != c)
1108   {
1109     GML_channel_remove (c, ch->lid_root, ch);
1110   }
1111
1112   c = ch->dest;
1113   if (NULL != c)
1114   {
1115     GML_channel_remove (c, ch->lid_dest, ch);
1116   }
1117
1118   channel_rel_free_all (ch->root_rel);
1119   channel_rel_free_all (ch->dest_rel);
1120
1121   GMT_remove_channel (ch->t, ch);
1122   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
1123
1124   GNUNET_free (ch);
1125 }
1126
1127
1128 /**
1129  * Get channel ID.
1130  *
1131  * @param ch Channel.
1132  *
1133  * @return ID
1134  */
1135 MESH_ChannelNumber
1136 GMCH_get_id (const struct MeshChannel *ch)
1137 {
1138   return ch->gid;
1139 }
1140
1141
1142 /**
1143  * Get the channel tunnel.
1144  *
1145  * @param ch Channel to get the tunnel from.
1146  *
1147  * @return tunnel of the channel.
1148  */
1149 struct MeshTunnel3 *
1150 GMCH_get_tunnel (const struct MeshChannel *ch)
1151 {
1152   return ch->t;
1153 }
1154
1155
1156 /**
1157  * Get free buffer space towards the client on a specific channel.
1158  *
1159  * @param ch Channel.
1160  * @param fwd Is query about FWD traffic?
1161  *
1162  * @return Free buffer space [0 - 64]
1163  */
1164 unsigned int
1165 GMCH_get_buffer (struct MeshChannel *ch, int fwd)
1166 {
1167   struct MeshChannelReliability *rel;
1168
1169   rel = fwd ? ch->dest_rel : ch->root_rel;
1170
1171   /* If rel is NULL it means that the end is not yet created,
1172    * most probably is a loopback channel at the point of sending
1173    * the ChannelCreate to itself.
1174    */
1175   if (NULL == rel)
1176     return 64;
1177
1178   return (64 - rel->n_recv);
1179 }
1180
1181
1182 /**
1183  * Get flow control status of end point: is client allow to send?
1184  *
1185  * @param ch Channel.
1186  * @param fwd Is query about FWD traffic? (Request root status).
1187  *
1188  * @return #GNUNET_YES if client is allowed to send us data.
1189  */
1190 int
1191 GMCH_get_allowed (struct MeshChannel *ch, int fwd)
1192 {
1193   struct MeshChannelReliability *rel;
1194
1195   rel = fwd ? ch->root_rel : ch->dest_rel;
1196
1197   if (NULL == rel)
1198   {
1199     /* Probably shutting down: root/dest NULL'ed to mark disconnection */
1200     GNUNET_break (GNUNET_NO != ch->destroy);
1201     return 0;
1202   }
1203
1204   return rel->client_allowed;
1205 }
1206
1207
1208 /**
1209  * Is the root client for this channel on this peer?
1210  *
1211  * @param ch Channel.
1212  * @param fwd Is this for fwd traffic?
1213  *
1214  * @return #GNUNET_YES in case it is.
1215  */
1216 int
1217 GMCH_is_origin (struct MeshChannel *ch, int fwd)
1218 {
1219   struct MeshClient *c;
1220
1221   c = fwd ? ch->root : ch->dest;
1222   return NULL != c;
1223 }
1224
1225
1226 /**
1227  * Is the destination client for this channel on this peer?
1228  *
1229  * @param ch Channel.
1230  * @param fwd Is this for fwd traffic?
1231  *
1232  * @return #GNUNET_YES in case it is.
1233  */
1234 int
1235 GMCH_is_terminal (struct MeshChannel *ch, int fwd)
1236 {
1237   struct MeshClient *c;
1238
1239   c = fwd ? ch->dest : ch->root;
1240   return NULL != c;
1241 }
1242
1243
1244 /**
1245  * Notify the destination client that a new incoming channel was created.
1246  *
1247  * @param ch Channel that was created.
1248  */
1249 void
1250 GMCH_send_create (struct MeshChannel *ch)
1251 {
1252   uint32_t opt;
1253
1254   if (NULL == ch->dest)
1255     return;
1256
1257   opt = 0;
1258   opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1259   opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1260   GML_send_channel_create (ch->dest, ch->lid_dest, ch->port, opt,
1261                            GMT_get_destination (ch->t));
1262
1263 }
1264
1265
1266 /**
1267  * Send an end-to-end ACK message for the most recent in-sequence payload.
1268  *
1269  * If channel is not reliable, do nothing.
1270  *
1271  * @param ch Channel this is about.
1272  * @param fwd Is for FWD traffic? (ACK dest->owner)
1273  */
1274 void
1275 GMCH_send_data_ack (struct MeshChannel *ch, int fwd)
1276 {
1277   struct GNUNET_MESH_DataACK msg;
1278   struct MeshChannelReliability *rel;
1279   struct MeshReliableMessage *copy;
1280   unsigned int delta;
1281   uint64_t mask;
1282   uint32_t ack;
1283
1284   if (GNUNET_NO == ch->reliable)
1285   {
1286     return;
1287   }
1288   rel = fwd ? ch->dest_rel : ch->root_rel;
1289   ack = rel->mid_recv - 1;
1290   LOG (GNUNET_ERROR_TYPE_DEBUG,
1291               " !! Send DATA_ACK for %u\n",
1292               ack);
1293
1294   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA_ACK);
1295   msg.header.size = htons (sizeof (msg));
1296   msg.chid = htonl (ch->gid);
1297   msg.futures = 0;
1298   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
1299   {
1300     if (copy->type != GNUNET_MESSAGE_TYPE_MESH_DATA)
1301     {
1302       LOG (GNUNET_ERROR_TYPE_DEBUG,
1303            "!!  Type %s, expected DATA\n",
1304            GM_m2s (copy->type));
1305       continue;
1306     }
1307     if (copy->mid == ack + 1)
1308     {
1309       ack++;
1310       continue;
1311     }
1312     delta = copy->mid - (ack + 1);
1313     if (63 < delta)
1314       break;
1315     mask = 0x1LL << delta;
1316     msg.futures |= mask;
1317     LOG (GNUNET_ERROR_TYPE_DEBUG,
1318          " !! setting bit for %u (delta %u) (%llX) -> %llX\n",
1319          copy->mid, delta, mask, msg.futures);
1320   }
1321   msg.mid = htonl (ack);
1322   LOG (GNUNET_ERROR_TYPE_DEBUG,
1323        "!!! ACK for %u, futures %llX\n",
1324        ack, msg.futures);
1325
1326   GMCH_send_prebuilt_message (&msg.header, ch, !fwd, NULL);
1327   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1328 }
1329
1330
1331 /**
1332  * Allow a client to send us more data, in case it was choked.
1333  *
1334  * @param ch Channel.
1335  * @param fwd Is this about FWD traffic? (Root client).
1336  */
1337 void
1338 GMCH_allow_client (struct MeshChannel *ch, int fwd)
1339 {
1340   struct MeshChannelReliability *rel;
1341   unsigned int buffer;
1342
1343   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH allow\n");
1344
1345   if (MESH_CHANNEL_READY != ch->state)
1346   {
1347     LOG (GNUNET_ERROR_TYPE_DEBUG, " channel not ready yet!\n");
1348     return;
1349   }
1350
1351   if (GNUNET_YES == ch->reliable)
1352   {
1353     rel = fwd ? ch->root_rel : ch->dest_rel;
1354     if (NULL == rel)
1355     {
1356       GNUNET_break (GNUNET_NO != ch->destroy);
1357       return;
1358     }
1359     if (NULL != rel->head_sent && 64 <= rel->mid_send - rel->head_sent->mid)
1360     {
1361       LOG (GNUNET_ERROR_TYPE_DEBUG, " too big MID gap! Wait for ACK.\n");
1362       return;
1363     }
1364   }
1365
1366   if (is_loopback (ch))
1367     buffer = GMCH_get_buffer (ch, fwd);
1368   else
1369     buffer = GMT_get_connections_buffer (ch->t);
1370
1371   if (0 == buffer)
1372   {
1373     LOG (GNUNET_ERROR_TYPE_DEBUG, " no buffer space.\n");
1374     return;
1375   }
1376
1377   LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space %u, allowing\n", buffer);
1378   send_client_ack (ch, fwd);
1379 }
1380
1381
1382 /**
1383  * Log channel info.
1384  *
1385  * @param ch Channel.
1386  */
1387 void
1388 GMCH_debug (struct MeshChannel *ch)
1389 {
1390   if (NULL == ch)
1391   {
1392     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
1393     return;
1394   }
1395   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X (%p)\n",
1396               GMT_2s (ch->t), ch->gid, ch);
1397   LOG (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
1398               ch->root, ch->root_rel);
1399   if (NULL != ch->root)
1400   {
1401     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->root));
1402     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1403                 ch->root_rel->client_ready ? "YES" : "NO");
1404     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_root);
1405   }
1406   LOG (GNUNET_ERROR_TYPE_DEBUG, "  dest %p/%p\n",
1407               ch->dest, ch->dest_rel);
1408   if (NULL != ch->dest)
1409   {
1410     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->dest));
1411     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1412                 ch->dest_rel->client_ready ? "YES" : "NO");
1413     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_dest);
1414   }
1415 }
1416
1417
1418 /**
1419  * Handle an ACK given by a client.
1420  *
1421  * Mark client as ready and send him any buffered data we could have for him.
1422  *
1423  * @param ch Channel.
1424  * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by dest and go BCK)
1425  */
1426 void
1427 GMCH_handle_local_ack (struct MeshChannel *ch, int fwd)
1428 {
1429   struct MeshChannelReliability *rel;
1430   struct MeshClient *c;
1431
1432   rel = fwd ? ch->dest_rel : ch->root_rel;
1433   c   = fwd ? ch->dest     : ch->root;
1434
1435   rel->client_ready = GNUNET_YES;
1436   send_client_buffered_data (ch, c, fwd);
1437   if (is_loopback (ch))
1438   {
1439     unsigned int buffer;
1440
1441     buffer = GMCH_get_buffer (ch, fwd);
1442     if (0 < buffer)
1443       GMCH_allow_client (ch, fwd);
1444
1445     return;
1446   }
1447   GMT_send_connection_acks (ch->t);
1448 }
1449
1450
1451 /**
1452  * Handle data given by a client.
1453  *
1454  * Check whether the client is allowed to send in this tunnel, save if channel
1455  * is reliable and send an ACK to the client if there is still buffer space
1456  * in the tunnel.
1457  *
1458  * @param ch Channel.
1459  * @param c Client which sent the data.
1460  * @param message Message.
1461  * @param fwd Is this a FWD data?
1462  *
1463  * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
1464  */
1465 int
1466 GMCH_handle_local_data (struct MeshChannel *ch,
1467                         struct MeshClient *c,
1468                         struct GNUNET_MessageHeader *message,
1469                         int fwd)
1470 {
1471   struct MeshChannelReliability *rel;
1472   struct GNUNET_MESH_Data *payload;
1473   size_t size = ntohs (message->size);
1474   uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
1475   unsigned char cbuf[p2p_size];
1476
1477   /* Is the client in the channel? */
1478   if ( !( (fwd &&
1479            ch->root == c)
1480          ||
1481           (!fwd &&
1482            ch->dest == c) ) )
1483   {
1484     GNUNET_break_op (0);
1485     return GNUNET_SYSERR;
1486   }
1487
1488   rel = fwd ? ch->root_rel : ch->dest_rel;
1489
1490   if (GNUNET_NO == rel->client_allowed)
1491   {
1492     GNUNET_break_op (0);
1493     return GNUNET_SYSERR;
1494   }
1495
1496   rel->client_allowed = GNUNET_NO;
1497
1498   /* Ok, everything is correct, send the message. */
1499   payload = (struct GNUNET_MESH_Data *) cbuf;
1500   payload->mid = htonl (rel->mid_send);
1501   rel->mid_send++;
1502   memcpy (&payload[1], message, size);
1503   payload->header.size = htons (p2p_size);
1504   payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
1505   payload->chid = htonl (ch->gid);
1506   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1507   GMCH_send_prebuilt_message (&payload->header, ch, fwd, NULL);
1508
1509   if (is_loopback (ch))
1510   {
1511     if (GMCH_get_buffer (ch, fwd) > 0)
1512       send_client_ack (ch, fwd);
1513
1514     return GNUNET_OK;
1515   }
1516
1517   if (GMT_get_connections_buffer (ch->t) > 0)
1518   {
1519     send_client_ack (ch, fwd);
1520   }
1521
1522   return GNUNET_OK;
1523 }
1524
1525
1526 /**
1527  * Handle a channel destroy requested by a client.
1528  *
1529  * Destroy the channel and the tunnel in case this was the last channel.
1530  *
1531  * @param ch Channel.
1532  * @param c Client that requested the destruction (to avoid notifying him).
1533  * @param is_root Is the request coming from root?
1534  */
1535 void
1536 GMCH_handle_local_destroy (struct MeshChannel *ch,
1537                            struct MeshClient *c,
1538                            int is_root)
1539 {
1540   struct MeshTunnel3 *t;
1541
1542   ch->destroy = GNUNET_YES;
1543   /* Cleanup after the tunnel */
1544   if (GNUNET_NO == is_root && c == ch->dest)
1545   {
1546     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
1547     GML_client_delete_channel (c, ch, ch->lid_dest);
1548     ch->dest = NULL;
1549   }
1550   if (GNUNET_YES == is_root && c == ch->root)
1551   {
1552     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
1553     GML_client_delete_channel (c, ch, ch->lid_root);
1554     ch->root = NULL;
1555   }
1556
1557   t = ch->t;
1558   send_destroy (ch, GNUNET_NO);
1559   if (0 == ch->pending_messages)
1560   {
1561     GMCH_destroy (ch);
1562     GMT_destroy_if_empty (t);
1563   }
1564 }
1565
1566
1567 /**
1568  * Handle a channel create requested by a client.
1569  *
1570  * Create the channel and the tunnel in case this was the first0 channel.
1571  *
1572  * @param c Client that requested the creation (will be the root).
1573  * @param msg Create Channel message.
1574  *
1575  * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
1576  */
1577 int
1578 GMCH_handle_local_create (struct MeshClient *c,
1579                           struct GNUNET_MESH_ChannelMessage *msg)
1580 {
1581   struct MeshChannel *ch;
1582   struct MeshTunnel3 *t;
1583   struct MeshPeer *peer;
1584   MESH_ChannelNumber chid;
1585
1586   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
1587               GNUNET_i2s (&msg->peer), ntohl (msg->port));
1588   chid = ntohl (msg->channel_id);
1589
1590   /* Sanity check for duplicate channel IDs */
1591   if (NULL != GML_channel_get (c, chid))
1592   {
1593     GNUNET_break (0);
1594     return GNUNET_SYSERR;
1595   }
1596
1597   peer = GMP_get (&msg->peer);
1598   GMP_add_tunnel (peer);
1599   t = GMP_get_tunnel (peer);
1600
1601   if (GMP_get_short_id (peer) == myid)
1602   {
1603     GMT_change_cstate (t, MESH_TUNNEL3_READY);
1604   }
1605   else
1606   {
1607     GMP_connect (peer);
1608   }
1609
1610   /* Create channel */
1611   ch = channel_new (t, c, chid);
1612   if (NULL == ch)
1613   {
1614     GNUNET_break (0);
1615     return GNUNET_SYSERR;
1616   }
1617   ch->port = ntohl (msg->port);
1618   channel_set_options (ch, ntohl (msg->opt));
1619
1620   /* In unreliable channels, we'll use the DLL to buffer BCK data */
1621   ch->root_rel = GNUNET_new (struct MeshChannelReliability);
1622   ch->root_rel->ch = ch;
1623   ch->root_rel->expected_delay.rel_value_us = 0;
1624
1625   LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s\n", GMCH_2s (ch));
1626
1627   /* Send create channel */
1628   {
1629     struct GNUNET_MESH_ChannelCreate msgcc;
1630
1631     msgcc.header.size = htons (sizeof (msgcc));
1632     msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
1633     msgcc.chid = htonl (ch->gid);
1634     msgcc.port = msg->port;
1635     msgcc.opt = msg->opt;
1636
1637     /* FIXME retransmit if lost */
1638     GMT_send_prebuilt_message (&msgcc.header, t, ch,
1639                                GNUNET_YES, GNUNET_YES, NULL, NULL);
1640   }
1641   return GNUNET_OK;
1642 }
1643
1644
1645 /**
1646  * Handler for mesh network payload traffic.
1647  *
1648  * @param ch Channel for the message.
1649  * @param msg Unencryted data message.
1650  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1651  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1652  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1653  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1654  */
1655 void
1656 GMCH_handle_data (struct MeshChannel *ch,
1657                   const struct GNUNET_MESH_Data *msg,
1658                   int fwd)
1659 {
1660   struct MeshChannelReliability *rel;
1661   struct MeshClient *c;
1662   uint32_t mid;
1663
1664   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1665   if (GNUNET_SYSERR == fwd)
1666   {
1667     if (is_loopback (ch))
1668     {
1669       /* It is a loopback channel after all... */
1670       GNUNET_break (0);
1671       return;
1672     }
1673     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1674   }
1675
1676   /*  Initialize FWD/BCK data */
1677   c   = fwd ? ch->dest     : ch->root;
1678   rel = fwd ? ch->dest_rel : ch->root_rel;
1679
1680   if (NULL == c)
1681   {
1682     GNUNET_break (0);
1683     return;
1684   }
1685
1686   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
1687
1688   mid = ntohl (msg->mid);
1689   LOG (GNUNET_ERROR_TYPE_DEBUG, "!! got mid %u\n", mid);
1690
1691   if (GNUNET_NO == ch->reliable ||
1692       ( !GM_is_pid_bigger (rel->mid_recv, mid) &&
1693         GM_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1694   {
1695     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
1696     if (GNUNET_YES == ch->reliable)
1697     {
1698       /* Is this the exact next expected messasge? */
1699       if (mid == rel->mid_recv)
1700       {
1701         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
1702         rel->mid_recv++;
1703         send_client_data (ch, msg, fwd);
1704       }
1705       else
1706       {
1707         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1708         add_buffered_data (msg, rel);
1709       }
1710     }
1711     else
1712     {
1713       /* Tunnel is unreliable: send to clients directly */
1714       /* FIXME: accept Out Of Order traffic */
1715       rel->mid_recv = mid + 1;
1716       send_client_data (ch, msg, fwd);
1717     }
1718   }
1719   else
1720   {
1721     GNUNET_break_op (GM_is_pid_bigger (rel->mid_recv, mid));
1722     LOG (GNUNET_ERROR_TYPE_DEBUG,
1723                 " !!! MID %u not expected (%u - %u), dropping!\n",
1724                 mid, rel->mid_recv, rel->mid_recv + 63);
1725   }
1726
1727   GMCH_send_data_ack (ch, fwd);
1728 }
1729
1730
1731 /**
1732  * Handler for mesh network traffic end-to-end ACKs.
1733  *
1734  * @param ch Channel on which we got this message.
1735  * @param msg Data message.
1736  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1737  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1738  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1739  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1740  */
1741 void
1742 GMCH_handle_data_ack (struct MeshChannel *ch,
1743                       const struct GNUNET_MESH_DataACK *msg,
1744                       int fwd)
1745 {
1746   struct MeshChannelReliability *rel;
1747   struct MeshReliableMessage *copy;
1748   struct MeshReliableMessage *next;
1749   uint32_t ack;
1750   int work;
1751
1752   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1753   if (GNUNET_SYSERR == fwd)
1754   {
1755     if (is_loopback (ch))
1756     {
1757       /* It is a loopback channel after all... */
1758       GNUNET_break (0);
1759       return;
1760     }
1761     /* Inverted: if message came 'FWD' is a 'BCK ACK'. */
1762     fwd = (NULL != ch->dest) ? GNUNET_NO : GNUNET_YES;
1763   }
1764
1765   ack = ntohl (msg->mid);
1766   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
1767        (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
1768
1769   if (GNUNET_YES == fwd)
1770   {
1771     rel = ch->root_rel;
1772   }
1773   else
1774   {
1775     rel = ch->dest_rel;
1776   }
1777   if (NULL == rel)
1778   {
1779     GNUNET_break_op (0);
1780     return;
1781   }
1782
1783   /* Free ACK'd copies: no need to retransmit those anymore */
1784   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
1785   {
1786     if (GM_is_pid_bigger (copy->mid, ack))
1787     {
1788       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
1789       channel_rel_free_sent (rel, msg);
1790       break;
1791     }
1792     work = GNUNET_YES;
1793     LOG (GNUNET_ERROR_TYPE_DEBUG, " !!  id %u\n", copy->mid);
1794     next = copy->next;
1795     rel_message_free (copy, GNUNET_YES);
1796   }
1797
1798   /* ACK client if needed */
1799   GMCH_allow_client (ch, fwd);
1800
1801   /* If some message was free'd, update the retransmission delay */
1802   if (GNUNET_YES == work)
1803   {
1804     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
1805     {
1806       GNUNET_SCHEDULER_cancel (rel->retry_task);
1807       if (NULL != rel->head_sent && NULL == rel->head_sent->q)
1808       {
1809         struct GNUNET_TIME_Absolute new_target;
1810         struct GNUNET_TIME_Relative delay;
1811
1812         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
1813                                                MESH_RETRANSMIT_MARGIN);
1814         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
1815                                                delay);
1816         delay = GNUNET_TIME_absolute_get_remaining (new_target);
1817         rel->retry_task =
1818             GNUNET_SCHEDULER_add_delayed (delay,
1819                                           &channel_retransmit_message,
1820                                           rel);
1821       }
1822       else /* either no more traffic to ack or traffic has just been queued */
1823       {
1824         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
1825       }
1826     }
1827     else /* work was done but no task was pending? shouldn't happen! */
1828     {
1829       GNUNET_break (0);
1830     }
1831   }
1832 }
1833
1834
1835 /**
1836  * Handler for channel create messages.
1837  *
1838  * Does not have fwd parameter because it's always 'FWD': channel is incoming.
1839  *
1840  * @param t Tunnel this channel will be in.
1841  * @param msg Channel crate message.
1842  */
1843 struct MeshChannel *
1844 GMCH_handle_create (struct MeshTunnel3 *t,
1845                     const struct GNUNET_MESH_ChannelCreate *msg)
1846 {
1847   MESH_ChannelNumber chid;
1848   struct MeshChannel *ch;
1849   struct MeshClient *c;
1850
1851   chid = ntohl (msg->chid);
1852
1853   ch = GMT_get_channel (t, chid);
1854   if (NULL == ch)
1855   {
1856     /* Create channel */
1857     ch = channel_new (t, NULL, 0);
1858     ch->gid = chid;
1859   }
1860   channel_set_options (ch, ntohl (msg->opt));
1861
1862   /* Find a destination client */
1863   ch->port = ntohl (msg->port);
1864   LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", ch->port);
1865   c = GML_client_get_by_port (ch->port);
1866   if (NULL == c)
1867   {
1868     /* TODO send reject */
1869     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
1870     if (is_loopback (ch))
1871     {
1872       LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback: destroy on handler\n");
1873       channel_send_nack (ch);
1874     }
1875     else
1876     {
1877       LOG (GNUNET_ERROR_TYPE_DEBUG, "  not loopback: destroy now\n");
1878       channel_send_nack (ch);
1879       GMCH_destroy (ch);
1880     }
1881     return NULL;
1882   }
1883   else
1884   {
1885     LOG (GNUNET_ERROR_TYPE_DEBUG, "  client %p has port registered\n", c);
1886   }
1887
1888   add_destination (ch, c);
1889   if (GNUNET_YES == ch->reliable)
1890     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
1891   else
1892     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Not Reliable\n");
1893
1894   GMCH_send_create (ch);
1895   channel_send_ack (ch, GNUNET_YES);
1896
1897   return ch;
1898 }
1899
1900
1901 /**
1902  * Handler for channel NACK messages.
1903  *
1904  * NACK messages always go dest -> root, no need for 'fwd' or 'msg' parameter.
1905  *
1906  * @param ch Channel.
1907  */
1908 void
1909 GMCH_handle_nack (struct MeshChannel *ch)
1910 {
1911   send_client_nack (ch);
1912   GMCH_destroy (ch);
1913 }
1914
1915
1916 /**
1917  * Handler for channel ack messages.
1918  *
1919  * @param ch Channel.
1920  * @param msg Message.
1921  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1922  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1923  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1924  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1925  */
1926 void
1927 GMCH_handle_ack (struct MeshChannel *ch,
1928                  const struct GNUNET_MESH_ChannelManage *msg,
1929                  int fwd)
1930 {
1931   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1932   if (GNUNET_SYSERR == fwd)
1933   {
1934     if (is_loopback (ch))
1935     {
1936       /* It is a loopback channel after all... */
1937       GNUNET_break (0);
1938       return;
1939     }
1940     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1941   }
1942
1943   channel_confirm (ch, !fwd);
1944 }
1945
1946
1947 /**
1948  * Handler for channel destroy messages.
1949  *
1950  * @param ch Channel to be destroyed of.
1951  * @param msg Message.
1952  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1953  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1954  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1955  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1956  */
1957 void
1958 GMCH_handle_destroy (struct MeshChannel *ch,
1959                      const struct GNUNET_MESH_ChannelManage *msg,
1960                      int fwd)
1961 {
1962   struct MeshTunnel3 *t;
1963
1964   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1965   if (GNUNET_SYSERR == fwd)
1966   {
1967     if (is_loopback (ch))
1968     {
1969       /* It is a loopback channel after all... */
1970       GNUNET_break (0);
1971       return;
1972     }
1973     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1974   }
1975
1976   GMCH_debug (ch);
1977   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
1978   {
1979     /* Not for us (don't destroy twice a half-open loopback channel) */
1980     return;
1981   }
1982
1983   t = ch->t;
1984   send_destroy (ch, GNUNET_YES);
1985   GMCH_destroy (ch);
1986   GMT_destroy_if_empty (t);
1987 }
1988
1989
1990 /**
1991  * Sends an already built message on a channel.
1992  *
1993  * If the channel is on a loopback tunnel, notifies the appropriate destination
1994  * client locally.
1995  *
1996  * On a normal channel passes the message to the tunnel for encryption and
1997  * sending on a connection.
1998  *
1999  * This function DOES NOT save the message for retransmission.
2000  *
2001  * @param message Message to send. Function makes a copy of it.
2002  * @param ch Channel on which this message is transmitted.
2003  * @param fwd Is this a fwd message?
2004  * @param existing_copy This is a retransmission, don't save a copy.
2005  */
2006 void
2007 GMCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2008                             struct MeshChannel *ch, int fwd,
2009                             void *existing_copy)
2010 {
2011   uint16_t type;
2012
2013   type = ntohs (message->type);
2014   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH Send %s %s on channel %s\n",
2015        GM_f2s (fwd), GM_m2s (type),
2016        GMCH_2s (ch));
2017
2018   if (GMT_is_loopback (ch->t))
2019   {
2020     handle_loopback (ch, message, fwd);
2021     return;
2022   }
2023
2024   switch (type)
2025   {
2026     case GNUNET_MESSAGE_TYPE_MESH_DATA:
2027
2028       if (GNUNET_YES == ch->reliable)
2029       {
2030         struct MeshChannelQueue *q;
2031
2032         q = GNUNET_new (struct MeshChannelQueue);
2033         q->type = type;
2034         if (NULL == existing_copy)
2035           q->copy = channel_save_copy (ch, message, fwd);
2036         else
2037         {
2038           q->copy = (struct MeshReliableMessage *) existing_copy;
2039           if (NULL != q->copy->q)
2040           {
2041             /* Last retransmission was scheduled but not sent!
2042              * This retransmission was executed by a ch_message_sent
2043              * following a very fast RRT, which scheduled the retransmission
2044              * before the retransmitted message had a chance to leave the peer.
2045              * Cancel this transmission and wait until the pending
2046              * retransmission schedules the next one.
2047              */
2048             GNUNET_free (q);
2049             return;
2050           }
2051           LOG (GNUNET_ERROR_TYPE_DEBUG,
2052                "  using existing copy: %p {r:%p q:%p t:%u}\n",
2053                existing_copy,
2054                q->copy->rel, q->copy->q, q->copy->type);
2055         }
2056         LOG (GNUNET_ERROR_TYPE_DEBUG, "  new q: %p\n", q);
2057         q->copy->q = q;
2058         q->q = GMT_send_prebuilt_message (message, ch->t, ch,
2059                                           fwd, NULL != existing_copy,
2060                                           &ch_message_sent, q);
2061         /* q itself is stored in copy */
2062       }
2063       else
2064       {
2065         GNUNET_break (NULL == GMT_send_prebuilt_message (message, ch->t, ch,
2066                                                          fwd, GNUNET_NO,
2067                                                          NULL, NULL));
2068       }
2069       break;
2070
2071     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
2072       {
2073         struct MeshChannelReliability *rel;
2074
2075         rel = fwd ? ch->root_rel : ch->dest_rel;
2076         if (NULL != rel->ack_q)
2077         {
2078           GMT_cancel (rel->ack_q->q);
2079           /* ch_message_sent is called, freeing ack_q */
2080         }
2081         rel->ack_q = GNUNET_new (struct MeshChannelQueue);
2082         rel->ack_q->type = type;
2083         rel->ack_q->rel = rel;
2084         rel->ack_q->q = GMT_send_prebuilt_message (message, ch->t, ch,
2085                                                    fwd, GNUNET_YES,
2086                                                    &ch_message_sent,
2087                                                   rel->ack_q);
2088       }
2089       break;
2090     default:
2091       GNUNET_break (NULL == GMT_send_prebuilt_message (message, ch->t, ch,
2092                                                        fwd, GNUNET_YES,
2093                                                        NULL, NULL));
2094   }
2095 }
2096
2097
2098 /**
2099  * Get the static string for identification of the channel.
2100  *
2101  * @param ch Channel.
2102  *
2103  * @return Static string with the channel IDs.
2104  */
2105 const char *
2106 GMCH_2s (const struct MeshChannel *ch)
2107 {
2108   static char buf[64];
2109
2110   if (NULL == ch)
2111     return "(NULL Channel)";
2112
2113   sprintf (buf, "%s:%u gid:%X (%X / %X)",
2114            GMT_2s (ch->t), ch->port, ch->gid, ch->lid_root, ch->lid_dest);
2115
2116   return buf;
2117 }