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