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