- dont allow a client to send more data when output buffer is full
[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 /**
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      * DLL of messages received out of order.
117      */
118   struct MeshReliableMessage        *head_recv;
119   struct MeshReliableMessage        *tail_recv;
120
121     /**
122      * Messages received.
123      */
124   unsigned int                      n_recv;
125
126     /**
127      * Next MID to use for outgoing traffic.
128      */
129   uint32_t                          mid_send;
130
131     /**
132      * Next MID expected for incoming traffic.
133      */
134   uint32_t                          mid_recv;
135
136     /**
137      * Can we send data to the client?
138      */
139   int                               client_ready;
140
141   /**
142    * Can the client send data to us?
143    */
144   int                               client_allowed;
145
146     /**
147      * Task to resend/poll in case no ACK is received.
148      */
149   GNUNET_SCHEDULER_TaskIdentifier   retry_task;
150
151     /**
152      * Counter for exponential backoff.
153      */
154   struct GNUNET_TIME_Relative       retry_timer;
155
156     /**
157      * How long does it usually take to get an ACK.
158      */
159   struct GNUNET_TIME_Relative       expected_delay;
160 };
161
162
163 /**
164  * Struct containing all information regarding a channel to a remote client.
165  */
166 struct MeshChannel
167 {
168     /**
169      * Tunnel this channel is in.
170      */
171   struct MeshTunnel3 *t;
172
173     /**
174      * Destination port of the channel.
175      */
176   uint32_t port;
177
178     /**
179      * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
180      */
181   MESH_ChannelNumber gid;
182
183     /**
184      * Local tunnel number for root (owner) client.
185      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
186      */
187   MESH_ChannelNumber lid_root;
188
189     /**
190      * Local tunnel number for local destination clients (incoming number)
191      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
192      */
193   MESH_ChannelNumber lid_dest;
194
195     /**
196      * Channel state.
197      */
198   enum MeshChannelState state;
199
200     /**
201      * Is the tunnel bufferless (minimum latency)?
202      */
203   int nobuffer;
204
205     /**
206      * Is the tunnel reliable?
207      */
208   int reliable;
209
210     /**
211      * Last time the channel was used
212      */
213   struct GNUNET_TIME_Absolute timestamp;
214
215     /**
216      * Client owner of the tunnel, if any
217      */
218   struct MeshClient *root;
219
220     /**
221      * Client destination of the tunnel, if any.
222      */
223   struct MeshClient *dest;
224
225     /**
226      * Flag to signal the destruction of the channel.
227      * If this is set GNUNET_YES the channel will be destroyed
228      * when the queue is empty.
229      */
230   int destroy;
231
232     /**
233      * Total messages pending for this channel, payload or not.
234      */
235   unsigned int pending_messages;
236
237     /**
238      * Reliability data.
239      * Only present (non-NULL) at the owner of a tunnel.
240      */
241   struct MeshChannelReliability *root_rel;
242
243     /**
244      * Reliability data.
245      * Only present (non-NULL) at the destination of a tunnel.
246      */
247   struct MeshChannelReliability *dest_rel;
248
249 };
250
251
252 /******************************************************************************/
253 /*******************************   GLOBALS  ***********************************/
254 /******************************************************************************/
255
256 /**
257  * Global handle to the statistics service.
258  */
259 extern struct GNUNET_STATISTICS_Handle *stats;
260
261 /**
262  * Local peer own ID (memory efficient handle).
263  */
264 extern GNUNET_PEER_Id myid;
265
266
267 /******************************************************************************/
268 /********************************   STATIC  ***********************************/
269 /******************************************************************************/
270
271 /**
272  * Destroy a reliable message after it has been acknowledged, either by
273  * direct mid ACK or bitfield. Updates the appropriate data structures and
274  * timers and frees all memory.
275  *
276  * @param copy Message that is no longer needed: remote peer got it.
277  * @param update_time Is the timing information relevant?
278  *                    If this message is ACK in a batch the timing information
279  *                    is skewed by the retransmission, count only for the
280  *                    retransmitted message.
281  */
282 static void
283 rel_message_free (struct MeshReliableMessage *copy, int update_time);
284
285 /**
286  * We have received a message out of order, or the client is not ready.
287  * Buffer it until we receive an ACK from the client or the missing
288  * message from the channel.
289  *
290  * @param msg Message to buffer (MUST be of type MESH_DATA).
291  * @param rel Reliability data to the corresponding direction.
292  */
293 static void
294 add_buffered_data (const struct GNUNET_MESH_Data *msg,
295                    struct MeshChannelReliability *rel)
296 {
297   struct MeshReliableMessage *copy;
298   struct MeshReliableMessage *prev;
299   uint32_t mid;
300   uint16_t size;
301
302   size = ntohs (msg->header.size);
303   mid = ntohl (msg->mid);
304
305   LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
306
307   copy = GNUNET_malloc (sizeof (*copy) + size);
308   copy->mid = mid;
309   copy->rel = rel;
310   copy->type = GNUNET_MESSAGE_TYPE_MESH_DATA;
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, GNUNET_YES);
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   copy->timestamp = GNUNET_TIME_absolute_get();
674   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
675   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
676                                                   &channel_retransmit_message,
677                                                   cls);
678 }
679
680
681 /**
682  * Destroy a reliable message after it has been acknowledged, either by
683  * direct mid ACK or bitfield. Updates the appropriate data structures and
684  * timers and frees all memory.
685  *
686  * @param copy Message that is no longer needed: remote peer got it.
687  * @param update_time Is the timing information relevant?
688  *                    If this message is ACK in a batch the timing information
689  *                    is skewed by the retransmission, count only for the
690  *                    retransmitted message.
691  */
692 static void
693 rel_message_free (struct MeshReliableMessage *copy, int update_time)
694 {
695   struct MeshChannelReliability *rel;
696   struct GNUNET_TIME_Relative time;
697
698   rel = copy->rel;
699   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
700   if (update_time)
701   {
702     time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
703     rel->expected_delay.rel_value_us *= 7;
704     rel->expected_delay.rel_value_us += time.rel_value_us;
705     rel->expected_delay.rel_value_us /= 8;
706     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
707                 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
708     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
709                 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
710                                                         GNUNET_NO));
711     rel->retry_timer = rel->expected_delay;
712   }
713   else
714   {
715     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! batch free, ignoring timing\n");
716   }
717   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
718   GNUNET_free (copy);
719 }
720
721
722 /**
723  * Confirm we got a channel create.
724  *
725  * @param ch The channel to confirm.
726  * @param fwd Should we send a FWD ACK? (going dest->root)
727  */
728 static void
729 channel_send_ack (struct MeshChannel *ch, int fwd)
730 {
731   struct GNUNET_MESH_ChannelManage msg;
732
733   msg.header.size = htons (sizeof (msg));
734   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
735   LOG (GNUNET_ERROR_TYPE_DEBUG,
736               "  sending channel %s ack for channel %s\n",
737               fwd ? "FWD" : "BCK", GMCH_2s (ch));
738
739   msg.chid = htonl (ch->gid);
740   GMCH_send_prebuilt_message (&msg.header, ch, !fwd);
741 }
742
743
744 /**
745  * Notify that a channel create didn't succeed.
746  *
747  * @param ch The channel to reject.
748  */
749 static void
750 channel_send_nack (struct MeshChannel *ch)
751 {
752   struct GNUNET_MESH_ChannelManage msg;
753
754   msg.header.size = htons (sizeof (msg));
755   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK);
756   LOG (GNUNET_ERROR_TYPE_DEBUG,
757        "  sending channel NACK for channel %s\n",
758        GMCH_2s (ch));
759
760   msg.chid = htonl (ch->gid);
761   GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO);
762 }
763
764
765 /**
766  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
767  *
768  * @param ch Channel to mark as ready.
769  * @param fwd Was the ACK message a FWD ACK? (dest->root, SYNACK)
770  */
771 static void
772 channel_confirm (struct MeshChannel *ch, int fwd)
773 {
774   struct MeshChannelReliability *rel;
775   struct MeshReliableMessage *copy;
776   struct MeshReliableMessage *next;
777
778   LOG (GNUNET_ERROR_TYPE_DEBUG,
779               "  channel confirm %s %s:%X\n",
780               fwd ? "FWD" : "BCK", GMT_2s (ch->t), ch->gid);
781   ch->state = MESH_CHANNEL_READY;
782
783   rel = fwd ? ch->root_rel : ch->dest_rel;
784   rel->client_ready = GNUNET_YES;
785   for (copy = rel->head_sent; NULL != copy; copy = next)
786   {
787     struct GNUNET_MessageHeader *msg;
788
789     next = copy->next;
790     msg = (struct GNUNET_MessageHeader *) &copy[1];
791     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
792     {
793       rel_message_free (copy, GNUNET_YES);
794       /* TODO return? */
795     }
796   }
797   send_client_ack (ch, fwd);
798
799   /* In case of a FWD ACK (SYNACK) send a BCK ACK (ACK). */
800   if (fwd)
801     channel_send_ack (ch, !fwd);
802 }
803
804
805 /**
806  * Save a copy to retransmit in case it gets lost.
807  *
808  * Initializes all needed callbacks and timers.
809  *
810  * @param ch Channel this message goes on.
811  * @param msg Message to copy.
812  * @param fwd Is this fwd traffic?
813  */
814 static void
815 channel_save_copy (struct MeshChannel *ch,
816                    const struct GNUNET_MessageHeader *msg,
817                    int fwd)
818 {
819   struct MeshChannelReliability *rel;
820   struct MeshReliableMessage *copy;
821   uint32_t mid;
822   uint16_t type;
823   uint16_t size;
824
825   rel = fwd ? ch->root_rel : ch->dest_rel;
826   mid = rel->mid_send - 1;
827   type = ntohs (msg->type);
828   size = ntohs (msg->size);
829
830   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u %s\n",
831        mid, GNUNET_MESH_DEBUG_M2S (type));
832   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
833   copy->mid = mid;
834   copy->timestamp = GNUNET_TIME_absolute_get ();
835   copy->rel = rel;
836   copy->type = type;
837   memcpy (&copy[1], msg, size);
838   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
839   if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
840   {
841     rel->retry_timer =
842         GNUNET_TIME_relative_multiply (rel->expected_delay,
843                                         MESH_RETRANSMIT_MARGIN);
844     rel->retry_task =
845         GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
846                                       &channel_retransmit_message,
847                                       rel);
848   }
849 }
850
851
852 /**
853  * Destroy a channel and free all resources.
854  *
855  * @param ch Channel to destroy.
856  */
857 static void
858 channel_destroy (struct MeshChannel *ch)
859 {
860   struct MeshClient *c;
861
862   if (NULL == ch)
863     return;
864
865   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
866               GMT_2s (ch->t), ch->gid);
867   GMCH_debug (ch);
868
869   c = ch->root;
870   if (NULL != c)
871   {
872     GML_channel_remove (c, ch->lid_root, ch);
873   }
874
875   c = ch->dest;
876   if (NULL != c)
877   {
878     GML_channel_remove (c, ch->lid_dest, ch);
879   }
880
881   channel_rel_free_all (ch->root_rel);
882   channel_rel_free_all (ch->dest_rel);
883
884   GMT_remove_channel (ch->t, ch);
885   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
886
887   GNUNET_free (ch);
888 }
889
890
891 /**
892  * Create a new channel.
893  *
894  * @param t Tunnel this channel is in.
895  * @param owner Client that owns the channel, NULL for foreign channels.
896  * @param lid_root Local ID for root client.
897  *
898  * @return A new initialized channel. NULL on error.
899  */
900 static struct MeshChannel *
901 channel_new (struct MeshTunnel3 *t,
902              struct MeshClient *owner,
903              MESH_ChannelNumber lid_root)
904 {
905   struct MeshChannel *ch;
906
907   ch = GNUNET_new (struct MeshChannel);
908   ch->root = owner;
909   ch->lid_root = lid_root;
910   ch->t = t;
911
912   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
913
914   if (NULL != owner)
915   {
916     ch->gid = GMT_get_next_chid (t);
917     GML_channel_add (owner, lid_root, ch);
918   }
919   GMT_add_channel (t, ch);
920
921   return ch;
922 }
923
924
925 /**
926  * Set options in a channel, extracted from a bit flag field
927  *
928  * @param ch Channel to set options to.
929  * @param options Bit array in host byte order.
930  */
931 static void
932 channel_set_options (struct MeshChannel *ch, uint32_t options)
933 {
934   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
935                  GNUNET_YES : GNUNET_NO;
936   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
937                  GNUNET_YES : GNUNET_NO;
938 }
939
940 static int
941 is_loopback (const struct MeshChannel *ch)
942 {
943   if (NULL != ch->t)
944     return GMT_is_loopback (ch->t);
945
946   return (NULL != ch->root && NULL != ch->dest);
947 }
948
949
950 /**
951  * Handle a loopback message: call the appropriate handler for the message type.
952  *
953  * @param ch Channel this message is on.
954  * @param msgh Message header.
955  * @param fwd Is this FWD traffic?
956  */
957 void
958 handle_loopback (struct MeshChannel *ch,
959                  const struct GNUNET_MessageHeader *msgh,
960                  int fwd)
961 {
962   uint16_t type;
963
964   type = ntohs (msgh->type);
965   LOG (GNUNET_ERROR_TYPE_DEBUG,
966        "Loopback %s %s message!\n",
967        fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (type));
968
969   switch (type)
970   {
971     case GNUNET_MESSAGE_TYPE_MESH_DATA:
972       /* Don't send hop ACK, wait for client to ACK */
973       GMCH_handle_data (ch, (struct GNUNET_MESH_Data *) msgh, fwd);
974       break;
975
976     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
977       GMCH_handle_data_ack (ch, (struct GNUNET_MESH_DataACK *) msgh, fwd);
978       break;
979
980     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
981       GMCH_handle_create (ch->t,
982                           (struct GNUNET_MESH_ChannelCreate *) msgh);
983       break;
984
985     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
986       GMCH_handle_ack (ch,
987                        (struct GNUNET_MESH_ChannelManage *) msgh,
988                        fwd);
989       break;
990
991     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
992       GMCH_handle_nack (ch);
993       break;
994
995     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
996       GMCH_handle_destroy (ch,
997                            (struct GNUNET_MESH_ChannelManage *) msgh,
998                            fwd);
999       break;
1000
1001     default:
1002       GNUNET_break_op (0);
1003       LOG (GNUNET_ERROR_TYPE_DEBUG,
1004            "end-to-end message not known (%u)\n",
1005            ntohs (msgh->type));
1006   }
1007 }
1008
1009
1010
1011 /******************************************************************************/
1012 /********************************    API    ***********************************/
1013 /******************************************************************************/
1014
1015
1016 /**
1017  * Get channel ID.
1018  *
1019  * @param ch Channel.
1020  *
1021  * @return ID
1022  */
1023 MESH_ChannelNumber
1024 GMCH_get_id (const struct MeshChannel *ch)
1025 {
1026   return ch->gid;
1027 }
1028
1029
1030 /**
1031  * Get the channel tunnel.
1032  *
1033  * @param ch Channel to get the tunnel from.
1034  *
1035  * @return tunnel of the channel.
1036  */
1037 struct MeshTunnel3 *
1038 GMCH_get_tunnel (const struct MeshChannel *ch)
1039 {
1040   return ch->t;
1041 }
1042
1043
1044 /**
1045  * Get free buffer space towards the client on a specific channel.
1046  *
1047  * @param ch Channel.
1048  * @param fwd Is query about FWD traffic?
1049  *
1050  * @return Free buffer space [0 - 64]
1051  */
1052 unsigned int
1053 GMCH_get_buffer (struct MeshChannel *ch, int fwd)
1054 {
1055   struct MeshChannelReliability *rel;
1056
1057   rel = fwd ? ch->dest_rel : ch->root_rel;
1058
1059   /* If rel is NULL it means that the end is not yet created,
1060    * most probably is a loopback channel at the point of sending
1061    * the ChannelCreate to itself.
1062    */
1063   if (NULL == rel)
1064     return 64;
1065
1066   return (64 - rel->n_recv);
1067 }
1068
1069
1070 /**
1071  * Get flow control status of end point: is client allow to send?
1072  *
1073  * @param ch Channel.
1074  * @param fwd Is query about FWD traffic? (Request root status).
1075  *
1076  * @return #GNUNET_YES if client is allowed to send us data.
1077  */
1078 int
1079 GMCH_get_allowed (struct MeshChannel *ch, int fwd)
1080 {
1081   struct MeshChannelReliability *rel;
1082
1083   rel = fwd ? ch->root_rel : ch->dest_rel;
1084
1085   return rel->client_allowed;
1086 }
1087
1088
1089 /**
1090  * Is the root client for this channel on this peer?
1091  *
1092  * @param ch Channel.
1093  * @param fwd Is this for fwd traffic?
1094  *
1095  * @return #GNUNET_YES in case it is.
1096  */
1097 int
1098 GMCH_is_origin (struct MeshChannel *ch, int fwd)
1099 {
1100   struct MeshClient *c;
1101
1102   c = fwd ? ch->root : ch->dest;
1103   return NULL != c;
1104 }
1105
1106
1107 /**
1108  * Is the destination client for this channel on this peer?
1109  *
1110  * @param ch Channel.
1111  * @param fwd Is this for fwd traffic?
1112  *
1113  * @return #GNUNET_YES in case it is.
1114  */
1115 int
1116 GMCH_is_terminal (struct MeshChannel *ch, int fwd)
1117 {
1118   struct MeshClient *c;
1119
1120   c = fwd ? ch->dest : ch->root;
1121   return NULL != c;
1122 }
1123
1124
1125 /**
1126  * Notify the destination client that a new incoming channel was created.
1127  *
1128  * @param ch Channel that was created.
1129  */
1130 void
1131 GMCH_send_create (struct MeshChannel *ch)
1132 {
1133   uint32_t opt;
1134
1135   if (NULL == ch->dest)
1136     return;
1137
1138   opt = 0;
1139   opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1140   opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1141   GML_send_channel_create (ch->dest, ch->lid_dest, ch->port, opt,
1142                            GMT_get_destination (ch->t));
1143
1144 }
1145
1146 /**
1147  * Notify a client that the channel is no longer valid.
1148  *
1149  * @param ch Channel that is destroyed.
1150  */
1151 void
1152 GMCH_send_destroy (struct MeshChannel *ch)
1153 {
1154   struct GNUNET_MESH_ChannelManage msg;
1155
1156   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
1157   msg.header.size = htons (sizeof (msg));
1158   msg.chid = htonl (ch->gid);
1159
1160   /* If root is not NULL, notify.
1161    * If it's NULL, check lid_root. When a local destroy comes in, root 
1162    * is set to NULL but lid_root is left untouched. In this case, do nothing,
1163    * the client is the one who reuqested the channel to be destroyed.
1164    */
1165   if (NULL != ch->root)
1166     GML_send_channel_destroy (ch->root, ch->lid_root);
1167   else if (0 == ch->lid_root)
1168     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO);
1169
1170   if (NULL != ch->dest)
1171     GML_send_channel_destroy (ch->dest, ch->lid_dest);
1172   else if (0 == ch->lid_dest)
1173     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_YES);
1174 }
1175
1176
1177 /**
1178  * Send data on a channel.
1179  *
1180  * If the destination is local, send it to client, otherwise encrypt and
1181  * send to next hop.
1182  *
1183  * @param ch Channel
1184  * @param msg Message.
1185  * @param fwd Is this a fwd (root->dest) message?
1186  */
1187 void
1188 GMCH_send_data (struct MeshChannel *ch,
1189                 const struct GNUNET_MESH_Data *msg,
1190                 int fwd)
1191 {
1192   if (GMCH_is_terminal (ch, fwd))
1193   {
1194     GML_send_data (fwd ? ch->dest : ch->root,
1195                    msg,
1196                    fwd ? ch->lid_dest : ch->lid_root);
1197   }
1198   else
1199   {
1200     GMT_send_prebuilt_message (&msg->header, ch->t, ch, fwd);
1201   }
1202 }
1203
1204
1205 /**
1206  * Send an end-to-end ACK message for the most recent in-sequence payload.
1207  *
1208  * If channel is not reliable, do nothing.
1209  *
1210  * @param ch Channel this is about.
1211  * @param fwd Is for FWD traffic? (ACK dest->owner)
1212  */
1213 void
1214 GMCH_send_data_ack (struct MeshChannel *ch, int fwd)
1215 {
1216   struct GNUNET_MESH_DataACK msg;
1217   struct MeshChannelReliability *rel;
1218   struct MeshReliableMessage *copy;
1219   unsigned int delta;
1220   uint64_t mask;
1221   uint32_t ack;
1222
1223   if (GNUNET_NO == ch->reliable)
1224   {
1225     return;
1226   }
1227   rel = fwd ? ch->dest_rel : ch->root_rel;
1228   ack = rel->mid_recv - 1;
1229   LOG (GNUNET_ERROR_TYPE_DEBUG,
1230               " !! Send DATA_ACK for %u\n",
1231               ack);
1232
1233   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA_ACK);
1234   msg.header.size = htons (sizeof (msg));
1235   msg.chid = htonl (ch->gid);
1236   msg.futures = 0;
1237   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
1238   {
1239     if (copy->type != GNUNET_MESSAGE_TYPE_MESH_DATA)
1240     {
1241       LOG (GNUNET_ERROR_TYPE_DEBUG,
1242            "!!  Type %s, expected DATA\n",
1243            GNUNET_MESH_DEBUG_M2S (copy->type));
1244       continue;
1245     }
1246     if (copy->mid == ack + 1)
1247     {
1248       ack++;
1249       continue;
1250     }
1251     delta = copy->mid - (ack + 1);
1252     if (63 < delta)
1253       break;
1254     mask = 0x1LL << delta;
1255     msg.futures |= mask;
1256     LOG (GNUNET_ERROR_TYPE_DEBUG,
1257          " !! setting bit for %u (delta %u) (%llX) -> %llX\n",
1258          copy->mid, delta, mask, msg.futures);
1259   }
1260   msg.mid = htonl (ack);
1261   LOG (GNUNET_ERROR_TYPE_DEBUG,
1262        "!!! ACK for %u, futures %llX\n",
1263        ack, msg.futures);
1264
1265   GMCH_send_prebuilt_message (&msg.header, ch, !fwd);
1266   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1267 }
1268
1269
1270 /**
1271  * Allow a client to send us more data, in case it was choked.
1272  *
1273  * @param ch Channel.
1274  * @param fwd Is this about FWD traffic? (Root client).
1275  */
1276 void
1277 GMCH_allow_client (struct MeshChannel *ch, int fwd)
1278 {
1279   struct MeshChannelReliability *rel;
1280   unsigned int buffer;
1281
1282   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH allow\n");
1283
1284   if (MESH_CHANNEL_READY != ch->state)
1285   {
1286     LOG (GNUNET_ERROR_TYPE_DEBUG, " channel not ready yet!\n");
1287     return;
1288   }
1289
1290   if (GNUNET_YES == ch->reliable)
1291   {
1292     rel = fwd ? ch->root_rel : ch->dest_rel;
1293     if (NULL == rel)
1294     {
1295       GNUNET_break (0);
1296       return;
1297     }
1298     if (NULL != rel->head_sent && 64 <= rel->mid_send - rel->head_sent->mid)
1299     {
1300       LOG (GNUNET_ERROR_TYPE_DEBUG, " too big MID gap! Wait for ACK.\n");
1301       return;
1302     }
1303   }
1304
1305   if (is_loopback (ch))
1306     buffer = GMCH_get_buffer (ch, fwd);
1307   else
1308     buffer = GMT_get_connections_buffer (ch->t);
1309
1310   if (0 == buffer)
1311   {
1312     LOG (GNUNET_ERROR_TYPE_DEBUG, " no buffer space.\n");
1313     return;
1314   }
1315
1316   LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space %u, allowing\n", buffer);
1317   send_client_ack (ch, fwd);
1318 }
1319
1320
1321 /**
1322  * Log channel info.
1323  *
1324  * @param ch Channel.
1325  */
1326 void
1327 GMCH_debug (struct MeshChannel *ch)
1328 {
1329   if (NULL == ch)
1330   {
1331     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
1332     return;
1333   }
1334   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X (%p)\n",
1335               GMT_2s (ch->t), ch->gid, ch);
1336   LOG (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
1337               ch->root, ch->root_rel);
1338   if (NULL != ch->root)
1339   {
1340     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->root));
1341     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1342                 ch->root_rel->client_ready ? "YES" : "NO");
1343     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_root);
1344   }
1345   LOG (GNUNET_ERROR_TYPE_DEBUG, "  dest %p/%p\n",
1346               ch->dest, ch->dest_rel);
1347   if (NULL != ch->dest)
1348   {
1349     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->dest));
1350     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1351                 ch->dest_rel->client_ready ? "YES" : "NO");
1352     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_dest);
1353   }
1354 }
1355
1356
1357 /**
1358  * Handle an ACK given by a client.
1359  *
1360  * Mark client as ready and send him any buffered data we could have for him.
1361  *
1362  * @param ch Channel.
1363  * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by dest and go BCK)
1364  */
1365 void
1366 GMCH_handle_local_ack (struct MeshChannel *ch, int fwd)
1367 {
1368   struct MeshChannelReliability *rel;
1369   struct MeshClient *c;
1370
1371   rel = fwd ? ch->dest_rel : ch->root_rel;
1372   c   = fwd ? ch->dest     : ch->root;
1373
1374   rel->client_ready = GNUNET_YES;
1375   send_client_buffered_data (ch, c, fwd);
1376   if (is_loopback (ch))
1377   {
1378     unsigned int buffer;
1379
1380     buffer = GMCH_get_buffer (ch, fwd);
1381     if (0 < buffer)
1382       GMCH_allow_client (ch, fwd);
1383
1384     return;
1385   }
1386   GMT_send_connection_acks (ch->t);
1387 }
1388
1389
1390 /**
1391  * Handle data given by a client.
1392  *
1393  * Check whether the client is allowed to send in this tunnel, save if channel
1394  * is reliable and send an ACK to the client if there is still buffer space
1395  * in the tunnel.
1396  *
1397  * @param ch Channel.
1398  * @param c Client which sent the data.
1399  * @param message Message.
1400  * @param fwd Is this a FWD data?
1401  *
1402  * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
1403  */
1404 int
1405 GMCH_handle_local_data (struct MeshChannel *ch,
1406                         struct MeshClient *c,
1407                         struct GNUNET_MessageHeader *message,
1408                         int fwd)
1409 {
1410   struct MeshChannelReliability *rel;
1411   struct GNUNET_MESH_Data *payload;
1412   size_t size = ntohs (message->size);
1413   uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
1414   unsigned char cbuf[p2p_size];
1415
1416   /* Is the client in the channel? */
1417   if ( !( (fwd &&
1418            ch->root == c)
1419          ||
1420           (!fwd &&
1421            ch->dest == c) ) )
1422   {
1423     GNUNET_break_op (0);
1424     return GNUNET_SYSERR;
1425   }
1426
1427   rel = fwd ? ch->root_rel : ch->dest_rel;
1428
1429   if (GNUNET_NO == rel->client_allowed)
1430   {
1431     GNUNET_break_op (0);
1432     return GNUNET_SYSERR;
1433   }
1434
1435   rel->client_allowed = GNUNET_NO;
1436
1437   /* Ok, everything is correct, send the message. */
1438   payload = (struct GNUNET_MESH_Data *) cbuf;
1439   payload->mid = htonl (rel->mid_send);
1440   rel->mid_send++;
1441   memcpy (&payload[1], message, size);
1442   payload->header.size = htons (p2p_size);
1443   payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
1444   payload->chid = htonl (ch->gid);
1445   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1446   if (GNUNET_YES == ch->reliable)
1447     channel_save_copy (ch, &payload->header, fwd);
1448   GMCH_send_prebuilt_message (&payload->header, ch, fwd);
1449
1450   if (is_loopback (ch))
1451   {
1452     if (GMCH_get_buffer (ch, fwd) > 0);
1453       send_client_ack (ch, fwd);
1454
1455     return GNUNET_OK;
1456   }
1457
1458   if (GMT_get_connections_buffer (ch->t) > 0)
1459   {
1460     send_client_ack (ch, fwd);
1461   }
1462
1463   return GNUNET_OK;
1464 }
1465
1466
1467 /**
1468  * Handle a channel destroy requested by a client.
1469  *
1470  * Destroy the channel and the tunnel in case this was the last channel.
1471  *
1472  * @param ch Channel.
1473  * @param c Client that requested the destruction (to avoid notifying him).
1474  */
1475 void
1476 GMCH_handle_local_destroy (struct MeshChannel *ch,
1477                            struct MeshClient *c)
1478 {
1479   struct MeshTunnel3 *t;
1480
1481   /* Cleanup after the tunnel */
1482   if (c == ch->dest)
1483   {
1484     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
1485     GML_client_delete_channel (c, ch, ch->lid_dest);
1486     ch->dest = NULL;
1487   }
1488   if (c == ch->root)
1489   {
1490     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
1491     GML_client_delete_channel (c, ch, ch->lid_root);
1492     ch->root = NULL;
1493   }
1494
1495   t = ch->t;
1496   GMCH_send_destroy (ch);
1497   channel_destroy (ch);
1498   GMT_destroy_if_empty (t);
1499 }
1500
1501
1502 /**
1503  * Handle a channel create requested by a client.
1504  *
1505  * Create the channel and the tunnel in case this was the first0 channel.
1506  *
1507  * @param c Client that requested the creation (will be the root).
1508  * @param msg Create Channel message.
1509  *
1510  * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
1511  */
1512 int
1513 GMCH_handle_local_create (struct MeshClient *c,
1514                           struct GNUNET_MESH_ChannelMessage *msg)
1515 {
1516   struct MeshChannel *ch;
1517   struct MeshTunnel3 *t;
1518   struct MeshPeer *peer;
1519   MESH_ChannelNumber chid;
1520
1521   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
1522               GNUNET_i2s (&msg->peer), ntohl (msg->port));
1523   chid = ntohl (msg->channel_id);
1524
1525   /* Sanity check for duplicate channel IDs */
1526   if (NULL != GML_channel_get (c, chid))
1527   {
1528     GNUNET_break (0);
1529     return GNUNET_SYSERR;
1530   }
1531
1532   peer = GMP_get (&msg->peer);
1533   GMP_add_tunnel (peer);
1534   t = GMP_get_tunnel (peer);
1535
1536   if (GMP_get_short_id (peer) == myid)
1537   {
1538     GMT_change_state (t, MESH_TUNNEL3_READY);
1539   }
1540   else
1541   {
1542     GMP_connect (peer);
1543   }
1544
1545   /* Create channel */
1546   ch = channel_new (t, c, chid);
1547   if (NULL == ch)
1548   {
1549     GNUNET_break (0);
1550     return GNUNET_SYSERR;
1551   }
1552   ch->port = ntohl (msg->port);
1553   channel_set_options (ch, ntohl (msg->opt));
1554
1555   /* In unreliable channels, we'll use the DLL to buffer BCK data */
1556   ch->root_rel = GNUNET_new (struct MeshChannelReliability);
1557   ch->root_rel->ch = ch;
1558   ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;
1559
1560   LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s\n", GMCH_2s (ch));
1561
1562   /* Send create channel */
1563   {
1564     struct GNUNET_MESH_ChannelCreate msgcc;
1565
1566     msgcc.header.size = htons (sizeof (msgcc));
1567     msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
1568     msgcc.chid = htonl (ch->gid);
1569     msgcc.port = msg->port;
1570     msgcc.opt = msg->opt;
1571
1572     GMT_send_prebuilt_message (&msgcc.header, t, ch, GNUNET_YES);
1573   }
1574   return GNUNET_OK;
1575 }
1576
1577
1578 /**
1579  * Handler for mesh network payload traffic.
1580  *
1581  * @param ch Channel for the message.
1582  * @param msg Unencryted data message.
1583  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1584  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1585  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1586  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1587  */
1588 void
1589 GMCH_handle_data (struct MeshChannel *ch,
1590                   const struct GNUNET_MESH_Data *msg,
1591                   int fwd)
1592 {
1593   struct MeshChannelReliability *rel;
1594   struct MeshClient *c;
1595   uint32_t mid;
1596
1597   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1598   if (GNUNET_SYSERR == fwd)
1599   {
1600     if (is_loopback (ch))
1601     {
1602       /* It is a loopback channel after all... */
1603       GNUNET_break (0);
1604       return;
1605     }
1606     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1607   }
1608
1609   /*  Initialize FWD/BCK data */
1610   c   = fwd ? ch->dest     : ch->root;
1611   rel = fwd ? ch->dest_rel : ch->root_rel;
1612
1613   if (NULL == c)
1614   {
1615     GNUNET_break (0);
1616     return;
1617   }
1618
1619   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
1620
1621   mid = ntohl (msg->mid);
1622   LOG (GNUNET_ERROR_TYPE_DEBUG, "!! got mid %u\n", mid);
1623
1624   if (GNUNET_NO == ch->reliable ||
1625       ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
1626         GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1627   {
1628     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
1629     if (GNUNET_YES == ch->reliable)
1630     {
1631       /* Is this the exact next expected messasge? */
1632       if (mid == rel->mid_recv)
1633       {
1634         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
1635         rel->mid_recv++;
1636         send_client_data (ch, msg, fwd);
1637       }
1638       else
1639       {
1640         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1641         add_buffered_data (msg, rel);
1642       }
1643     }
1644     else
1645     {
1646       /* Tunnel is unreliable: send to clients directly */
1647       /* FIXME: accept Out Of Order traffic */
1648       rel->mid_recv = mid + 1;
1649       send_client_data (ch, msg, fwd);
1650     }
1651   }
1652   else
1653   {
1654     GNUNET_break_op (0);
1655     LOG (GNUNET_ERROR_TYPE_DEBUG,
1656                 " MID %u not expected (%u - %u), dropping!\n",
1657                 mid, rel->mid_recv, rel->mid_recv + 63);
1658   }
1659
1660   GMCH_send_data_ack (ch, fwd);
1661 }
1662
1663
1664 /**
1665  * Handler for mesh network traffic end-to-end ACKs.
1666  *
1667  * @param ch Channel on which we got this message.
1668  * @param msg Data message.
1669  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1670  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1671  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1672  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1673  */
1674 void
1675 GMCH_handle_data_ack (struct MeshChannel *ch,
1676                       const struct GNUNET_MESH_DataACK *msg,
1677                       int fwd)
1678 {
1679   struct MeshChannelReliability *rel;
1680   struct MeshReliableMessage *copy;
1681   struct MeshReliableMessage *next;
1682   uint32_t ack;
1683   int work;
1684
1685   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1686   if (GNUNET_SYSERR == fwd)
1687   {
1688     if (is_loopback (ch))
1689     {
1690       /* It is a loopback channel after all... */
1691       GNUNET_break (0);
1692       return;
1693     }
1694     /* Inverted: if message came 'FWD' is a 'BCK ACK'. */
1695     fwd = (NULL != ch->dest) ? GNUNET_NO : GNUNET_YES;
1696   }
1697
1698   ack = ntohl (msg->mid);
1699   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
1700        (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
1701
1702   if (GNUNET_YES == fwd)
1703   {
1704     rel = ch->root_rel;
1705   }
1706   else
1707   {
1708     rel = ch->dest_rel;
1709   }
1710   if (NULL == rel)
1711   {
1712     GNUNET_break_op (0);
1713     return;
1714   }
1715
1716   /* Free ACK'd copies: no need to retransmit those anymore */
1717   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
1718   {
1719     if (GMC_is_pid_bigger (copy->mid, ack))
1720     {
1721       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
1722       channel_rel_free_sent (rel, msg);
1723       break;
1724     }
1725     work = GNUNET_YES;
1726     LOG (GNUNET_ERROR_TYPE_DEBUG, " !!  id %u\n", copy->mid);
1727     next = copy->next;
1728     rel_message_free (copy, GNUNET_YES);
1729   }
1730
1731   /* ACK client if needed */
1732   GMCH_allow_client (ch, fwd);
1733
1734   /* If some message was free'd, update the retransmission delay */
1735   if (GNUNET_YES == work)
1736   {
1737     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
1738     {
1739       GNUNET_SCHEDULER_cancel (rel->retry_task);
1740       if (NULL == rel->head_sent)
1741       {
1742         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
1743       }
1744       else
1745       {
1746         struct GNUNET_TIME_Absolute new_target;
1747         struct GNUNET_TIME_Relative delay;
1748
1749         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
1750                                                MESH_RETRANSMIT_MARGIN);
1751         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
1752                                                delay);
1753         delay = GNUNET_TIME_absolute_get_remaining (new_target);
1754         rel->retry_task =
1755             GNUNET_SCHEDULER_add_delayed (delay,
1756                                           &channel_retransmit_message,
1757                                           rel);
1758       }
1759     }
1760     else
1761       GNUNET_break (0);
1762   }
1763 }
1764
1765
1766 /**
1767  * Handler for channel create messages.
1768  *
1769  * Does not have fwd parameter because it's always 'FWD': channel is incoming.
1770  *
1771  * @param t Tunnel this channel will be in.
1772  * @param msg Channel crate message.
1773  */
1774 struct MeshChannel *
1775 GMCH_handle_create (struct MeshTunnel3 *t,
1776                     const struct GNUNET_MESH_ChannelCreate *msg)
1777 {
1778   MESH_ChannelNumber chid;
1779   struct MeshChannel *ch;
1780   struct MeshClient *c;
1781   uint32_t port;
1782
1783   chid = ntohl (msg->chid);
1784
1785   ch = GMT_get_channel (t, chid);
1786   if (NULL == ch)
1787   {
1788     /* Create channel */
1789     ch = channel_new (t, NULL, 0);
1790     ch->gid = chid;
1791   }
1792   channel_set_options (ch, ntohl (msg->opt));
1793
1794   /* Find a destination client */
1795   port = ntohl (msg->port);
1796   LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
1797   c = GML_client_get_by_port (port);
1798   if (NULL == c)
1799   {
1800     /* TODO send reject */
1801     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
1802     if (is_loopback (ch))
1803     {
1804       LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback: destroy on handler\n");
1805       channel_send_nack (ch);
1806     }
1807     else
1808     {
1809       LOG (GNUNET_ERROR_TYPE_DEBUG, "  not loopback: destroy now\n");
1810       channel_send_nack (ch);
1811       channel_destroy (ch);
1812     }
1813     return NULL;
1814   }
1815   else
1816   {
1817     LOG (GNUNET_ERROR_TYPE_DEBUG, "  client %p has port registered\n", c);
1818   }
1819
1820   add_destination (ch, c);
1821   if (GNUNET_YES == ch->reliable)
1822     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
1823   else
1824     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Not Reliable\n");
1825
1826   GMCH_send_create (ch);
1827   channel_send_ack (ch, GNUNET_YES);
1828
1829   return ch;
1830 }
1831
1832
1833 /**
1834  * Handler for channel NACK messages.
1835  *
1836  * NACK messages always go dest -> root, no need for 'fwd' or 'msg' parameter.
1837  *
1838  * @param ch Channel.
1839  */
1840 void
1841 GMCH_handle_nack (struct MeshChannel *ch)
1842 {
1843   send_client_nack (ch);
1844   channel_destroy (ch);
1845 }
1846
1847
1848 /**
1849  * Handler for channel ack messages.
1850  *
1851  * @param ch Channel.
1852  * @param msg Message.
1853  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1854  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1855  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1856  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1857  */
1858 void
1859 GMCH_handle_ack (struct MeshChannel *ch,
1860                  const struct GNUNET_MESH_ChannelManage *msg,
1861                  int fwd)
1862 {
1863   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1864   if (GNUNET_SYSERR == fwd)
1865   {
1866     if (is_loopback (ch))
1867     {
1868       /* It is a loopback channel after all... */
1869       GNUNET_break (0);
1870       return;
1871     }
1872     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1873   }
1874
1875   channel_confirm (ch, !fwd);
1876 }
1877
1878
1879 /**
1880  * Handler for channel destroy messages.
1881  *
1882  * @param ch Channel to be destroyed of.
1883  * @param msg Message.
1884  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1885  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1886  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1887  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1888  */
1889 void
1890 GMCH_handle_destroy (struct MeshChannel *ch,
1891                      const struct GNUNET_MESH_ChannelManage *msg,
1892                      int fwd)
1893 {
1894   struct MeshTunnel3 *t;
1895
1896   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1897   if (GNUNET_SYSERR == fwd)
1898   {
1899     if (is_loopback (ch))
1900     {
1901       /* It is a loopback channel after all... */
1902       GNUNET_break (0);
1903       return;
1904     }
1905     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1906   }
1907
1908   GMCH_debug (ch);
1909   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
1910   {
1911     /* Not for us (don't destroy twice a half-open loopback channel) */
1912     return;
1913   }
1914
1915   t = ch->t;
1916   GMCH_send_destroy (ch);
1917   channel_destroy (ch);
1918   GMT_destroy_if_empty (t);
1919 }
1920
1921
1922 /**
1923  * Sends an already built message on a channel.
1924  *
1925  * If the channel is on a loopback tunnel, notifies the appropriate destination
1926  * client locally.
1927  *
1928  * On a normal channel passes the message to the tunnel for encryption and
1929  * sending on a connection.
1930  *
1931  * This function DOES NOT save the message for retransmission.
1932  *
1933  * @param message Message to send. Function makes a copy of it.
1934  * @param ch Channel on which this message is transmitted.
1935  * @param fwd Is this a fwd message?
1936  */
1937 void
1938 GMCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1939                             struct MeshChannel *ch, int fwd)
1940 {
1941   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH Send %s %s on channel %s\n",
1942        fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (ntohs (message->type)), 
1943        GMCH_2s (ch));
1944
1945   if (GMT_is_loopback (ch->t))
1946   {
1947     handle_loopback (ch, message, fwd);
1948     return;
1949   }
1950
1951   GMT_send_prebuilt_message (message, ch->t, ch, fwd);
1952 }
1953
1954
1955 /**
1956  * Get the static string for identification of the channel.
1957  *
1958  * @param ch Channel.
1959  *
1960  * @return Static string with the channel IDs.
1961  */
1962 const char *
1963 GMCH_2s (const struct MeshChannel *ch)
1964 {
1965   static char buf[64];
1966
1967   if (NULL == ch)
1968     return "(NULL Channel)";
1969
1970   sprintf (buf, "%s:%X (%X / %X)",
1971            GMT_2s (ch->t), ch->gid, ch->lid_root, ch->lid_dest);
1972
1973   return buf;
1974 }