-bump name to 97
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh_channel.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21
22 #include "platform.h"
23 #include "gnunet_util_lib.h"
24
25 #include "gnunet_statistics_service.h"
26
27 #include "mesh_enc.h"
28 #include "mesh_protocol_enc.h"
29
30 #include "gnunet-service-mesh_channel.h"
31 #include "gnunet-service-mesh_local.h"
32 #include "gnunet-service-mesh_tunnel.h"
33
34 #define LOG(level, ...) GNUNET_log_from(level,"mesh-chn",__VA_ARGS__)
35
36 /**
37  * All the states a connection can be in.
38  */
39 enum MeshChannelState
40 {
41   /**
42    * Uninitialized status, should never appear in operation.
43    */
44   MESH_CHANNEL_NEW,
45
46   /**
47    * Connection create message sent, waiting for ACK.
48    */
49   MESH_CHANNEL_SENT,
50
51   /**
52    * Connection confirmed, ready to carry traffic..
53    */
54   MESH_CHANNEL_READY,
55 };
56
57
58
59 /**
60  * Info needed to retry a message in case it gets lost.
61  */
62 struct MeshReliableMessage
63 {
64     /**
65      * Double linked list, FIFO style
66      */
67   struct MeshReliableMessage    *next;
68   struct MeshReliableMessage    *prev;
69
70     /**
71      * Type of message (payload, channel management).
72      */
73   int16_t type;
74
75     /**
76      * Tunnel Reliability queue this message is in.
77      */
78   struct MeshChannelReliability  *rel;
79
80     /**
81      * ID of the message (ACK needed to free)
82      */
83   uint32_t                      mid;
84
85     /**
86      * When was this message issued (to calculate ACK delay)
87      */
88   struct GNUNET_TIME_Absolute   timestamp;
89
90   /* struct GNUNET_MESH_Data with payload */
91 };
92
93
94 /**
95  * Info about the traffic state for a client in a channel.
96  */
97 struct MeshChannelReliability
98 {
99     /**
100      * Channel this is about.
101      */
102   struct MeshChannel *ch;
103
104     /**
105      * DLL of messages sent and not yet ACK'd.
106      */
107   struct MeshReliableMessage        *head_sent;
108   struct MeshReliableMessage        *tail_sent;
109
110     /**
111      * Messages pending to send.
112      */
113   unsigned int                      n_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      * Task to resend/poll in case no ACK is received.
143      */
144   GNUNET_SCHEDULER_TaskIdentifier   retry_task;
145
146     /**
147      * Counter for exponential backoff.
148      */
149   struct GNUNET_TIME_Relative       retry_timer;
150
151     /**
152      * How long does it usually take to get an ACK.
153      */
154   struct GNUNET_TIME_Relative       expected_delay;
155 };
156
157
158 /**
159  * Struct containing all information regarding a channel to a remote client.
160  */
161 struct MeshChannel
162 {
163     /**
164      * Tunnel this channel is in.
165      */
166   struct MeshTunnel2 *t;
167
168     /**
169      * Double linked list.
170      */
171   struct MeshChannel    *next;
172   struct MeshChannel    *prev;
173
174     /**
175      * Destination port of the channel.
176      */
177   uint32_t port;
178
179     /**
180      * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
181      */
182   MESH_ChannelNumber gid;
183
184     /**
185      * Local tunnel number for root (owner) client.
186      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
187      */
188   MESH_ChannelNumber lid_root;
189
190     /**
191      * Local tunnel number for local destination clients (incoming number)
192      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
193      */
194   MESH_ChannelNumber lid_dest;
195
196     /**
197      * Channel state.
198      */
199   enum MeshChannelState state;
200
201     /**
202      * Is the tunnel bufferless (minimum latency)?
203      */
204   int nobuffer;
205
206     /**
207      * Is the tunnel reliable?
208      */
209   int reliable;
210
211     /**
212      * Last time the channel was used
213      */
214   struct GNUNET_TIME_Absolute timestamp;
215
216     /**
217      * Client owner of the tunnel, if any
218      */
219   struct MeshClient *root;
220
221     /**
222      * Client destination of the tunnel, if any.
223      */
224   struct MeshClient *dest;
225
226     /**
227      * Flag to signal the destruction of the channel.
228      * If this is set GNUNET_YES the channel will be destroyed
229      * when the queue is empty.
230      */
231   int destroy;
232
233     /**
234      * Total messages pending for this channel, payload or not.
235      */
236   unsigned int pending_messages;
237
238     /**
239      * Reliability data.
240      * Only present (non-NULL) at the owner of a tunnel.
241      */
242   struct MeshChannelReliability *root_rel;
243
244     /**
245      * Reliability data.
246      * Only present (non-NULL) at the destination of a tunnel.
247      */
248   struct MeshChannelReliability *dest_rel;
249
250 };
251
252
253 /******************************************************************************/
254 /*******************************   GLOBALS  ***********************************/
255 /******************************************************************************/
256
257 /**
258  * Global handle to the statistics service.
259  */
260 extern struct GNUNET_STATISTICS_Handle *stats;
261
262
263 /******************************************************************************/
264 /********************************   STATIC  ***********************************/
265 /******************************************************************************/
266
267 /**
268  * We have received a message out of order, or the client is not ready.
269  * Buffer it until we receive an ACK from the client or the missing
270  * message from the channel.
271  *
272  * @param msg Message to buffer (MUST be of type MESH_DATA).
273  * @param rel Reliability data to the corresponding direction.
274  */
275 static void
276 add_buffered_data (const struct GNUNET_MESH_Data *msg,
277                    struct MeshChannelReliability *rel)
278 {
279   struct MeshReliableMessage *copy;
280   struct MeshReliableMessage *prev;
281   uint32_t mid;
282   uint16_t size;
283
284   size = ntohs (msg->header.size);
285   mid = ntohl (msg->mid);
286
287   LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
288
289   copy = GNUNET_malloc (sizeof (*copy) + size);
290   copy->mid = mid;
291   copy->rel = rel;
292   memcpy (&copy[1], msg, size);
293
294   rel->n_recv++;
295
296   // FIXME do something better than O(n), although n < 64...
297   // FIXME start from the end (most messages are the latest ones)
298   for (prev = rel->head_recv; NULL != prev; prev = prev->next)
299   {
300     LOG (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
301     if (GMC_is_pid_bigger (prev->mid, mid))
302     {
303       LOG (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
304       GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
305                                           prev, copy);
306       return;
307     }
308   }
309     LOG (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
310     GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
311     LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
312 }
313
314
315 /**
316  * Send data to a client.
317  *
318  * If the client is ready, send directly, otherwise buffer while listening
319  * for a local ACK.
320  *
321  * @param ch Channel
322  * @param msg Message.
323  * @param fwd Is this a fwd (root->dest) message?
324  */
325 static void
326 send_client_data (struct MeshChannel *ch,
327                   const struct GNUNET_MESH_Data *msg,
328                   int fwd)
329 {
330   if (fwd)
331   {
332     if (ch->dest_rel->client_ready)
333       GML_send_data (ch, msg, ch->dest, ch->lid_dest);
334     else
335       add_buffered_data (msg, ch->dest_rel);
336   }
337   else
338   {
339     if (ch->root_rel->client_ready)
340       GML_send_data (ch, msg, ch->root, ch->lid_root);
341     else
342       add_buffered_data (msg, ch->root_rel);
343   }
344 }
345
346
347 /**
348  * Search for a channel among the channels for a client
349  *
350  * @param c the client whose channels to search in
351  * @param chid the local id of the channel
352  *
353  * @return channel handler, NULL if doesn't exist
354  */
355 static struct MeshChannel *
356 channel_get_by_local_id (struct MeshClient *c, MESH_ChannelNumber chid)
357 {
358   LOG (GNUNET_ERROR_TYPE_DEBUG, "   -- get CHID %X\n", chid);
359   if (0 == (chid & GNUNET_MESH_LOCAL_CHANNEL_ID_CLI))
360   {
361     GNUNET_break_op (0);
362     LOG (GNUNET_ERROR_TYPE_DEBUG, "CHID %X not a local chid\n", chid);
363     return NULL;
364   }
365   if (chid >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV)
366     return GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels, chid);
367   return GNUNET_CONTAINER_multihashmap32_get (c->own_channels, chid);
368 }
369
370
371
372 /**
373  * Search for a channel by global ID using full PeerIdentities.
374  *
375  * @param t Tunnel containing the channel.
376  * @param chid Public channel number.
377  *
378  * @return channel handler, NULL if doesn't exist
379  */
380 static struct MeshChannel *
381 channel_get (struct MeshTunnel2 *t, MESH_ChannelNumber chid)
382 {
383   struct MeshChannel *ch;
384
385   if (NULL == t)
386     return NULL;
387
388   for (ch = t->channel_head; NULL != ch; ch = ch->next)
389   {
390     if (ch->gid == chid)
391       break;
392   }
393
394   return ch;
395 }
396
397
398 /**
399  * Add a client to a channel, initializing all needed data structures.
400  *
401  * @param ch Channel to which add the client.
402  * @param c Client which to add to the channel.
403  */
404 static void
405 channel_add_client (struct MeshChannel *ch, struct MeshClient *c)
406 {
407   struct MeshTunnel2 *t = ch->t;
408
409   if (NULL != ch->dest)
410   {
411     GNUNET_break (0);
412     return;
413   }
414
415   /* Assign local id as destination */
416   while (NULL != channel_get_by_local_id (c, t->next_local_chid))
417     t->next_local_chid = (t->next_local_chid + 1) | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
418   ch->lid_dest = t->next_local_chid++;
419   t->next_local_chid = t->next_local_chid | GNUNET_MESH_LOCAL_CHANNEL_ID_SERV;
420
421   /* Store in client's hashmap */
422   if (GNUNET_OK !=
423       GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
424                                            ch->lid_dest, ch,
425                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
426   {
427     GNUNET_break (0);
428     return;
429   }
430
431   GNUNET_break (NULL == ch->dest_rel);
432   ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
433   ch->dest_rel->ch = ch;
434   ch->dest_rel->expected_delay = MESH_RETRANSMIT_TIME;
435
436   ch->dest = c;
437 }
438
439
440
441 /**
442  * Is the root client for this channel on this peer?
443  *
444  * @param ch Channel.
445  * @param fwd Is this for fwd traffic?
446  *
447  * @return GNUNET_YES in case it is.
448  */
449 static int
450 channel_is_origin (struct MeshChannel *ch, int fwd)
451 {
452   struct MeshClient *c;
453
454   c = fwd ? ch->root : ch->dest;
455   return NULL != c;
456 }
457
458
459 /**
460  * Is the destination client for this channel on this peer?
461  *
462  * @param ch Channel.
463  * @param fwd Is this for fwd traffic?
464  *
465  * @return GNUNET_YES in case it is.
466  */
467 static int
468 channel_is_terminal (struct MeshChannel *ch, int fwd)
469 {
470   struct MeshClient *c;
471
472   c = fwd ? ch->dest : ch->root;
473   return NULL != c;
474 }
475
476
477 /**
478  * Get free buffer space towards the client on a specific channel.
479  *
480  * @param ch Channel.
481  * @param fwd Is query about FWD traffic?
482  *
483  * @return Free buffer space [0 - 64]
484  */
485 static unsigned int
486 channel_get_buffer (struct MeshChannel *ch, int fwd)
487 {
488   struct MeshChannelReliability *rel;
489
490   rel = fwd ? ch->dest_rel : ch->root_rel;
491
492   /* If rel is NULL it means that the end is not yet created,
493    * most probably is a loopback channel at the point of sending
494    * the ChannelCreate to itself.
495    */
496   if (NULL == rel)
497     return 64;
498
499   return (64 - rel->n_recv);
500 }
501
502
503
504
505 /**
506  * Destroy all reliable messages queued for a channel,
507  * during a channel destruction.
508  * Frees the reliability structure itself.
509  *
510  * @param rel Reliability data for a channel.
511  */
512 static void
513 channel_rel_free_all (struct MeshChannelReliability *rel)
514 {
515   struct MeshReliableMessage *copy;
516   struct MeshReliableMessage *next;
517
518   if (NULL == rel)
519     return;
520
521   for (copy = rel->head_recv; NULL != copy; copy = next)
522   {
523     next = copy->next;
524     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
525     GNUNET_free (copy);
526   }
527   for (copy = rel->head_sent; NULL != copy; copy = next)
528   {
529     next = copy->next;
530     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
531     GNUNET_free (copy);
532   }
533   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
534     GNUNET_SCHEDULER_cancel (rel->retry_task);
535   GNUNET_free (rel);
536 }
537
538
539 /**
540  * Mark future messages as ACK'd.
541  *
542  * @param rel Reliability data.
543  * @param msg DataACK message with a bitfield of future ACK'd messages.
544  */
545 static void
546 channel_rel_free_sent (struct MeshChannelReliability *rel,
547                        const struct GNUNET_MESH_DataACK *msg)
548 {
549   struct MeshReliableMessage *copy;
550   struct MeshReliableMessage *next;
551   uint64_t bitfield;
552   uint64_t mask;
553   uint32_t mid;
554   uint32_t target;
555   unsigned int i;
556
557   bitfield = msg->futures;
558   mid = ntohl (msg->mid);
559   LOG (GNUNET_ERROR_TYPE_DEBUG,
560               "free_sent_reliable %u %llX\n",
561               mid, bitfield);
562   LOG (GNUNET_ERROR_TYPE_DEBUG,
563               " rel %p, head %p\n",
564               rel, rel->head_sent);
565   for (i = 0, copy = rel->head_sent;
566        i < 64 && NULL != copy && 0 != bitfield;
567        i++)
568   {
569     LOG (GNUNET_ERROR_TYPE_DEBUG,
570                 " trying bit %u (mid %u)\n",
571                 i, mid + i + 1);
572     mask = 0x1LL << i;
573     if (0 == (bitfield & mask))
574      continue;
575
576     LOG (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
577     /* Bit was set, clear the bit from the bitfield */
578     bitfield &= ~mask;
579
580     /* The i-th bit was set. Do we have that copy? */
581     /* Skip copies with mid < target */
582     target = mid + i + 1;
583     LOG (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
584     while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
585      copy = copy->next;
586
587     /* Did we run out of copies? (previously freed, it's ok) */
588     if (NULL == copy)
589     {
590      LOG (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
591      return;
592     }
593
594     /* Did we overshoot the target? (previously freed, it's ok) */
595     if (GMC_is_pid_bigger (copy->mid, target))
596     {
597      LOG (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
598      continue;
599     }
600
601     /* Now copy->mid == target, free it */
602     next = copy->next;
603     rel_message_free (copy);
604     copy = next;
605   }
606   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
607 }
608
609
610 /**
611  * We haven't received an ACK after a certain time: restransmit the message.
612  *
613  * @param cls Closure (MeshReliableMessage with the message to restransmit)
614  * @param tc TaskContext.
615  */
616 static void
617 channel_retransmit_message (void *cls,
618                             const struct GNUNET_SCHEDULER_TaskContext *tc)
619 {
620   struct MeshChannelReliability *rel = cls;
621   struct MeshReliableMessage *copy;
622   struct MeshPeerQueue *q;
623   struct MeshChannel *ch;
624   struct MeshConnection *c;
625   struct GNUNET_MESH_Data *payload;
626   struct MeshPeer *hop;
627   int fwd;
628
629   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
630   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
631     return;
632
633   ch = rel->ch;
634   copy = rel->head_sent;
635   if (NULL == copy)
636   {
637     GNUNET_break (0);
638     return;
639   }
640
641   /* Search the message to be retransmitted in the outgoing queue.
642    * Check only the queue for the connection that is going to be used,
643    * if the message is stuck in some other connection's queue we shouldn't
644    * act upon it:
645    * - cancelling it and sending the new one doesn't guarantee it's delivery,
646    *   the old connection could be temporary stalled or the queue happened to
647    *   be long at time of insertion.
648    * - not sending the new one could cause terrible delays the old connection
649    *   is stalled.
650    */
651   payload = (struct GNUNET_MESH_Data *) &copy[1];
652   fwd = (rel == ch->root_rel);
653   c = tunnel_get_connection (ch->t, fwd);
654   hop = connection_get_hop (c, fwd);
655   for (q = hop->queue_head; NULL != q; q = q->next)
656   {
657     if (ntohs (payload->header.type) == q->type && ch == q->ch)
658     {
659       struct GNUNET_MESH_Data *queued_data = q->cls;
660
661       if (queued_data->mid == payload->mid)
662         break;
663     }
664   }
665
666   /* Message not found in the queue that we are going to use. */
667   if (NULL == q)
668   {
669     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
670
671     send_prebuilt_message_channel (&payload->header, ch, fwd);
672     GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
673   }
674   else
675   {
676     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
677   }
678
679   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
680   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
681                                                   &channel_retransmit_message,
682                                                   cls);
683 }
684
685
686 /**
687  * Send ACK on one or more connections due to buffer space to the client.
688  *
689  * Iterates all connections of the tunnel and sends ACKs appropriately.
690  *
691  * @param ch Channel which has some free buffer space.
692  * @param fwd Is this in for FWD traffic? (ACK goes dest->root)
693  */
694 static void
695 channel_send_connections_ack (struct MeshChannel *ch,
696                               unsigned int buffer,
697                               int fwd)
698 {
699   struct MeshTunnel2 *t = ch->t;
700   struct MeshConnection *c;
701   struct MeshFlowControl *fc;
702   uint32_t allowed;
703   uint32_t to_allow;
704   uint32_t allow_per_connection;
705   unsigned int cs;
706
707   LOG (GNUNET_ERROR_TYPE_DEBUG,
708               "Channel send connection %s ack on %s:%X\n",
709               fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
710
711   /* Count connections, how many messages are already allowed */
712   for (cs = 0, allowed = 0, c = t->connection_head; NULL != c; c = c->next)
713   {
714     fc = fwd ? &c->fwd_fc : &c->bck_fc;
715     if (GMC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
716     {
717       GNUNET_break (0);
718       continue;
719     }
720     allowed += fc->last_ack_sent - fc->last_pid_recv;
721     cs++;
722   }
723
724   /* Make sure there is no overflow */
725   if (allowed > buffer)
726   {
727     GNUNET_break (0);
728     return;
729   }
730
731   /* Authorize connections to send more data */
732   to_allow = buffer - allowed;
733
734   for (c = t->connection_head; NULL != c && to_allow > 0; c = c->next)
735   {
736     allow_per_connection = to_allow/cs;
737     to_allow -= allow_per_connection;
738     cs--;
739     fc = fwd ? &c->fwd_fc : &c->bck_fc;
740     if (fc->last_ack_sent - fc->last_pid_recv > 64 / 3)
741     {
742       continue;
743     }
744     connection_send_ack (c, allow_per_connection, fwd);
745   }
746
747   LOG (GNUNET_ERROR_TYPE_DEBUG,
748                 "Channel send connection %s ack on %s:%X\n",
749                 fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
750   GNUNET_break (to_allow == 0);
751 }
752
753
754 /**
755  * Destroy a reliable message after it has been acknowledged, either by
756  * direct mid ACK or bitfield. Updates the appropriate data structures and
757  * timers and frees all memory.
758  *
759  * @param copy Message that is no longer needed: remote peer got it.
760  */
761 static void
762 rel_message_free (struct MeshReliableMessage *copy)
763 {
764   struct MeshChannelReliability *rel;
765   struct GNUNET_TIME_Relative time;
766
767   rel = copy->rel;
768   time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
769   rel->expected_delay.rel_value_us *= 7;
770   rel->expected_delay.rel_value_us += time.rel_value_us;
771   rel->expected_delay.rel_value_us /= 8;
772   rel->n_sent--;
773   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
774   LOG (GNUNET_ERROR_TYPE_DEBUG, "    n_sent %u\n", rel->n_sent);
775   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
776               GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
777   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
778               GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
779                                                       GNUNET_NO));
780   rel->retry_timer = rel->expected_delay;
781   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
782   GNUNET_free (copy);
783 }
784
785
786
787 /**
788  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
789  *
790  * @param ch Channel to mark as ready.
791  * @param fwd Was the CREATE message sent fwd?
792  */
793 static void
794 channel_confirm (struct MeshChannel *ch, int fwd)
795 {
796   struct MeshChannelReliability *rel;
797   struct MeshReliableMessage *copy;
798   struct MeshReliableMessage *next;
799
800   LOG (GNUNET_ERROR_TYPE_DEBUG,
801               "  channel confirm %s %s:%X\n",
802               fwd ? "FWD" : "BCK", peer2s (ch->t->peer), ch->gid);
803   ch->state = MESH_CHANNEL_READY;
804
805   rel = fwd ? ch->root_rel : ch->dest_rel;
806   for (copy = rel->head_sent; NULL != copy; copy = next)
807   {
808     struct GNUNET_MessageHeader *msg;
809
810     next = copy->next;
811     msg = (struct GNUNET_MessageHeader *) &copy[1];
812     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
813     {
814       rel_message_free (copy);
815       /* TODO return? */
816     }
817   }
818   send_ack (NULL, ch, fwd);
819 }
820
821
822 /**
823  * Save a copy to retransmit in case it gets lost.
824  *
825  * Initializes all needed callbacks and timers.
826  *
827  * @param ch Channel this message goes on.
828  * @param msg Message to copy.
829  * @param fwd Is this fwd traffic?
830  */
831 static void
832 channel_save_copy (struct MeshChannel *ch,
833                    const struct GNUNET_MessageHeader *msg,
834                    int fwd)
835 {
836   struct MeshChannelReliability *rel;
837   struct MeshReliableMessage *copy;
838   uint32_t mid;
839   uint16_t type;
840   uint16_t size;
841
842   rel = fwd ? ch->root_rel : ch->dest_rel;
843   mid = rel->mid_send;
844   type = ntohs (msg->type);
845   size = ntohs (msg->size);
846
847   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u\n", mid);
848   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
849   copy->mid = mid;
850   copy->timestamp = GNUNET_TIME_absolute_get ();
851   copy->rel = rel;
852   copy->type = type;
853   memcpy (&copy[1], msg, size);
854   rel->n_sent++;
855   LOG (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
856   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
857   if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
858   {
859     rel->retry_timer =
860         GNUNET_TIME_relative_multiply (rel->expected_delay,
861                                         MESH_RETRANSMIT_MARGIN);
862     rel->retry_task =
863         GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
864                                       &channel_retransmit_message,
865                                       rel);
866   }
867 }
868
869
870
871 /**
872  * Send a buffered message to the client, for in order delivery or
873  * as result of client ACK.
874  *
875  * @param ch Channel on which to empty the message buffer.
876  * @param c Client to send to.
877  * @param rel Reliability structure to corresponding peer.
878  *            If rel == bck_rel, this is FWD data.
879  */
880 static void
881 send_client_buffered_data (struct MeshChannel *ch,
882                                    struct MeshClient *c,
883                                    int fwd)
884 {
885   struct MeshReliableMessage *copy;
886   struct MeshChannelReliability *rel;
887
888   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
889   rel = fwd ? ch->dest_rel : ch->root_rel;
890   if (GNUNET_NO == rel->client_ready)
891   {
892     LOG (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
893     return;
894   }
895
896   copy = rel->head_recv;
897   /* We never buffer channel management messages */
898   if (NULL != copy)
899   {
900     if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
901     {
902       struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];
903
904       LOG (GNUNET_ERROR_TYPE_DEBUG,
905                   " have %u! now expecting %u\n",
906                   copy->mid, rel->mid_recv + 1);
907       send_client_data (ch, msg, fwd);
908       rel->n_recv--;
909       rel->mid_recv++;
910       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
911       GNUNET_free (copy);
912     }
913     else
914     {
915       LOG (GNUNET_ERROR_TYPE_DEBUG,
916                   " reliable && don't have %u, next is %u\n",
917                   rel->mid_recv,
918                   copy->mid);
919       return;
920     }
921   }
922   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
923 }
924
925
926
927
928 /**
929  * Destroy a channel and free all resources.
930  *
931  * @param ch Channel to destroy.
932  */
933 static void
934 channel_destroy (struct MeshChannel *ch)
935 {
936   struct MeshClient *c;
937
938   if (NULL == ch)
939     return;
940
941   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
942               peer2s (ch->t->peer), ch->gid);
943   GMCH_debug (ch);
944
945   c = ch->root;
946   if (NULL != c)
947   {
948     if (GNUNET_YES != GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
949                                                               ch->lid_root, ch))
950     {
951       GNUNET_break (0);
952     }
953   }
954
955   c = ch->dest;
956   if (NULL != c)
957   {
958     if (GNUNET_YES !=
959         GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
960                                                 ch->lid_dest, ch))
961     {
962       GNUNET_break (0);
963     }
964   }
965
966   channel_rel_free_all (ch->root_rel);
967   channel_rel_free_all (ch->dest_rel);
968
969   GNUNET_CONTAINER_DLL_remove (ch->t->channel_head, ch->t->channel_tail, ch);
970   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
971
972   GNUNET_free (ch);
973 }
974
975
976 /**
977  * Create a new channel.
978  *
979  * @param t Tunnel this channel is in.
980  * @param owner Client that owns the channel, NULL for foreign channels.
981  * @param lid_root Local ID for root client.
982  *
983  * @return A new initialized channel. NULL on error.
984  */
985 static struct MeshChannel *
986 channel_new (struct MeshTunnel2 *t,
987              struct MeshClient *owner, MESH_ChannelNumber lid_root)
988 {
989   struct MeshChannel *ch;
990
991   ch = GNUNET_new (struct MeshChannel);
992   ch->root = owner;
993   ch->lid_root = lid_root;
994   ch->t = t;
995
996   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
997
998   if (NULL != owner)
999   {
1000     while (NULL != channel_get (t, t->next_chid))
1001     {
1002       LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists (%p)...\n",
1003                   t->next_chid, channel_get (t, t->next_chid));
1004       t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1005     }
1006     ch->gid = t->next_chid;
1007     t->next_chid = (t->next_chid + 1) & ~GNUNET_MESH_LOCAL_CHANNEL_ID_CLI;
1008
1009     if (GNUNET_OK !=
1010         GNUNET_CONTAINER_multihashmap32_put (owner->own_channels, lid_root, ch,
1011                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1012     {
1013       GNUNET_break (0);
1014       channel_destroy (ch);
1015       GNUNET_SERVER_receive_done (owner->handle, GNUNET_SYSERR);
1016       return NULL;
1017     }
1018   }
1019   GNUNET_CONTAINER_DLL_insert (t->channel_head, t->channel_tail, ch);
1020
1021   return ch;
1022 }
1023
1024
1025 /**
1026  * Set options in a channel, extracted from a bit flag field
1027  *
1028  * @param ch Channel to set options to.
1029  * @param options Bit array in host byte order.
1030  */
1031 static void
1032 channel_set_options (struct MeshChannel *ch, uint32_t options)
1033 {
1034   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
1035                  GNUNET_YES : GNUNET_NO;
1036   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
1037                  GNUNET_YES : GNUNET_NO;
1038 }
1039
1040
1041
1042 /**
1043  * Confirm we got a channel create.
1044  *
1045  * @param ch The channel to confirm.
1046  * @param fwd Should we send the ACK fwd?
1047  */
1048 static void
1049 channel_send_ack (struct MeshChannel *ch, int fwd)
1050 {
1051   struct GNUNET_MESH_ChannelManage msg;
1052
1053   msg.header.size = htons (sizeof (msg));
1054   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
1055   LOG (GNUNET_ERROR_TYPE_DEBUG,
1056               "  sending channel %s ack for channel %s:%X\n",
1057               fwd ? "FWD" : "BCK", peer2s (ch->t->peer),
1058               ch->gid);
1059
1060   msg.chid = htonl (ch->gid);
1061   GMCH_send_prebuilt_message (&msg.header, ch, !fwd);
1062 }
1063
1064
1065 /**
1066  * Send a message to all clients (local and remote) of this channel
1067  * notifying that the channel is no longer valid.
1068  *
1069  * If some peer or client should not receive the message,
1070  * should be zero'ed out before calling this function.
1071  *
1072  * @param ch The channel whose clients to notify.
1073  */
1074 static void
1075 channel_send_destroy (struct MeshChannel *ch)
1076 {
1077   struct GNUNET_MESH_ChannelManage msg;
1078
1079   msg.header.size = htons (sizeof (msg));
1080   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
1081   LOG (GNUNET_ERROR_TYPE_DEBUG,
1082               "  sending channel destroy for channel %s:%X\n",
1083               peer2s (ch->t->peer),
1084               ch->gid);
1085
1086   if (channel_is_terminal (ch, GNUNET_NO))
1087   {
1088     if (NULL != ch->root && GNUNET_NO == ch->root->shutting_down)
1089     {
1090       msg.chid = htonl (ch->lid_root);
1091       send_local_channel_destroy (ch, GNUNET_NO);
1092     }
1093   }
1094   else
1095   {
1096     msg.chid = htonl (ch->gid);
1097     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO);
1098   }
1099
1100   if (channel_is_terminal (ch, GNUNET_YES))
1101   {
1102     if (NULL != ch->dest && GNUNET_NO == ch->dest->shutting_down)
1103     {
1104       msg.chid = htonl (ch->lid_dest);
1105       send_local_channel_destroy (ch, GNUNET_YES);
1106     }
1107   }
1108   else
1109   {
1110     msg.chid = htonl (ch->gid);
1111     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_YES);
1112   }
1113 }
1114
1115
1116 /**
1117  * Iterator for deleting each channel whose client endpoint disconnected.
1118  *
1119  * @param cls Closure (client that has disconnected).
1120  * @param key The local channel id (used to access the hashmap).
1121  * @param value The value stored at the key (channel to destroy).
1122  *
1123  * @return GNUNET_OK, keep iterating.
1124  */
1125 static int
1126 channel_destroy_iterator (void *cls,
1127                           uint32_t key,
1128                           void *value)
1129 {
1130   struct MeshChannel *ch = value;
1131   struct MeshClient *c = cls;
1132   struct MeshTunnel2 *t;
1133
1134   LOG (GNUNET_ERROR_TYPE_DEBUG,
1135               " Channel %X (%X / %X) destroy, due to client %u shutdown.\n",
1136               ch->gid, ch->lid_root, ch->lid_dest, c->id);
1137   channel_debug (ch);
1138
1139   if (c == ch->dest)
1140   {
1141     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %u is destination.\n", c->id);
1142   }
1143   if (c == ch->root)
1144   {
1145     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %u is owner.\n", c->id);
1146   }
1147
1148   t = ch->t;
1149   GMCH_send_destroy (ch);
1150   channel_send_destroy (ch);
1151   channel_destroy (ch);
1152   tunnel_destroy_if_empty (t);
1153
1154   return GNUNET_OK;
1155 }
1156
1157
1158 /**
1159  * Sends an already built message on a channel, properly registering
1160  * all used resources and encrypting the message with the tunnel's key.
1161  *
1162  * @param message Message to send. Function makes a copy of it.
1163  * @param ch Channel on which this message is transmitted.
1164  * @param fwd Is this a fwd message?
1165  */
1166 static void
1167 send (const struct GNUNET_MessageHeader *message,
1168       struct MeshChannel *ch, int fwd)
1169 {
1170   struct GNUNET_MESH_Encrypted *msg;
1171   size_t size = ntohs (message->size);
1172   char *cbuf[sizeof (struct GNUNET_MESH_Encrypted) + size];
1173   uint16_t type;
1174   uint64_t iv;
1175
1176   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send on Channel %s:%X %s\n",
1177               peer2s (ch->t->peer), ch->gid, fwd ? "FWD" : "BCK");
1178   LOG (GNUNET_ERROR_TYPE_DEBUG, "  %s\n",
1179               GNUNET_MESH_DEBUG_M2S (ntohs (message->type)));
1180
1181   if (channel_is_terminal (ch, fwd) || ch->t->peer->id == myid)
1182   {
1183     handle_decrypted (ch->t, message, fwd);
1184     return;
1185   }
1186
1187   type = fwd ? GNUNET_MESSAGE_TYPE_MESH_FWD : GNUNET_MESSAGE_TYPE_MESH_BCK;
1188   iv = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_NONCE, UINT64_MAX);
1189
1190   msg = (struct GNUNET_MESH_Encrypted *) cbuf;
1191   msg->header.type = htons (type);
1192   msg->header.size = htons (sizeof (struct GNUNET_MESH_Encrypted) + size);
1193   msg->iv = GNUNET_htonll (iv);
1194   GMT_encrypt (ch->t, &msg[1], message, size, iv, fwd);
1195   GMT_send_prebuilt_message (msg, ch->t, ch, fwd);
1196 }
1197
1198
1199 /******************************************************************************/
1200 /********************************    API    ***********************************/
1201 /******************************************************************************/
1202
1203 /**
1204  * Count channels in a DLL.
1205  * 
1206  * @param head Head of the DLL.
1207  */
1208 unsigned int
1209 GMCH_count (const struct MeshChannel *head)
1210 {
1211   unsigned int count;
1212   struct MeshChannel *iter;
1213   
1214   for (count = 0, iter = head; NULL != iter; iter = iter->next, count++);
1215   
1216   return count;
1217 }
1218
1219
1220 /**
1221  * Notify the destination client that a new incoming channel was created.
1222  *
1223  * @param ch Channel that was created.
1224  */
1225 void
1226 GMCH_send_create (struct MeshChannel *ch)
1227 {
1228   struct GNUNET_MESH_ChannelMessage msg;
1229   struct MeshTunnel2 *t = ch->t;
1230   uint32_t opt;
1231
1232   if (NULL == ch->dest)
1233     return;
1234
1235   opt = 0;
1236   opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1237   opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1238   GML_send_channel_create (ch->dest, ch->lid_dest, ch->port, opt,
1239                            GNUNET_PEER_resolve2 (t->peer->id));
1240
1241 }
1242
1243 /**
1244  * Notify a client that the channel is no longer valid.
1245  *
1246  * @param ch Channel that is destroyed.
1247  * @param fwd Forward notification (owner->dest)?
1248  */
1249 void
1250 GMCH_send_destroy (struct MeshChannel *ch, int fwd)
1251 {
1252   struct GNUNET_MeshClient *c = fwd ? ch->dest : ch->root;
1253   uint32_t id = fwd ? ch->lid_dest : ch->lid_root;
1254
1255   if (NULL == c)
1256   {
1257 //     TODO: send on connection?
1258     return;
1259   }
1260
1261   GML_send_channel_destroy (c, id);
1262 }
1263
1264
1265 /**
1266  * Send data on a channel.
1267  *
1268  * If the destination is local, send it to client, otherwise encrypt and
1269  * send to next hop.
1270  *
1271  * @param ch Channel
1272  * @param msg Message.
1273  * @param fwd Is this a fwd (root->dest) message?
1274  */
1275 void
1276 GMCH_send_data (struct MeshChannel *ch,
1277                 const struct GNUNET_MESH_Data *msg,
1278                 int fwd)
1279 {
1280 }
1281
1282
1283 /**
1284  * Send an end-to-end ACK message for the most recent in-sequence payload.
1285  *
1286  * If channel is not reliable, do nothing.
1287  *
1288  * @param ch Channel this is about.
1289  * @param fwd Is for FWD traffic? (ACK dest->owner)
1290  */
1291 static void
1292 GMCH_send_ack (struct MeshChannel *ch, int fwd)
1293 {
1294   struct GNUNET_MESH_DataACK msg;
1295   struct MeshChannelReliability *rel;
1296   struct MeshReliableMessage *copy;
1297   unsigned int delta;
1298   uint64_t mask;
1299   uint16_t type;
1300
1301   if (GNUNET_NO == ch->reliable)
1302   {
1303     return;
1304   }
1305   rel = fwd ? ch->dest_rel : ch->root_rel;
1306   LOG (GNUNET_ERROR_TYPE_DEBUG,
1307               "send_data_ack for %u\n",
1308               rel->mid_recv - 1);
1309
1310   type = GNUNET_MESSAGE_TYPE_MESH_DATA_ACK;
1311   msg.header.type = htons (type);
1312   msg.header.size = htons (sizeof (msg));
1313   msg.chid = htonl (ch->gid);
1314   msg.mid = htonl (rel->mid_recv - 1);
1315   msg.futures = 0;
1316   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
1317   {
1318     if (copy->type != type)
1319       continue;
1320     delta = copy->mid - rel->mid_recv;
1321     if (63 < delta)
1322       break;
1323     mask = 0x1LL << delta;
1324     msg.futures |= mask;
1325     LOG (GNUNET_ERROR_TYPE_DEBUG,
1326                 " setting bit for %u (delta %u) (%llX) -> %llX\n",
1327                 copy->mid, delta, mask, msg.futures);
1328   }
1329   LOG (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
1330
1331   send_prebuilt_message_channel (&msg.header, ch, fwd);
1332   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1333 }
1334
1335
1336 /**
1337  * Log channel info.
1338  *
1339  * @param ch Channel.
1340  */
1341 void
1342 GMCH_debug (struct MeshChannel *ch)
1343 {
1344   if (NULL == ch)
1345   {
1346     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
1347     return;
1348   }
1349   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X (%p)\n",
1350               peer2s (ch->t->peer), ch->gid, ch);
1351   LOG (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
1352               ch->root, ch->root_rel);
1353   if (NULL != ch->root)
1354   {
1355     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %u\n", ch->root->id);
1356     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1357                 ch->root_rel->client_ready ? "YES" : "NO");
1358     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_root);
1359   }
1360   LOG (GNUNET_ERROR_TYPE_DEBUG, "  dest %p/%p\n",
1361               ch->dest, ch->dest_rel);
1362   if (NULL != ch->dest)
1363   {
1364     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %u\n", ch->dest->id);
1365     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1366                 ch->dest_rel->client_ready ? "YES" : "NO");
1367     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_dest);
1368   }
1369 }
1370
1371
1372 /**
1373  * Handler for mesh network payload traffic.
1374  *
1375  * @param t Tunnel on which we got this message.
1376  * @param message Unencryted data message.
1377  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1378  */
1379 void
1380 GMCH_handle_data (struct MeshTunnel2 *t,
1381                   const struct GNUNET_MESH_Data *msg,
1382                   int fwd)
1383 {
1384   struct MeshChannelReliability *rel;
1385   struct MeshChannel *ch;
1386   struct MeshClient *c;
1387   uint32_t mid;
1388   uint16_t type;
1389   size_t size;
1390
1391   /* Check size */
1392   size = ntohs (msg->header.size);
1393   if (size <
1394       sizeof (struct GNUNET_MESH_Data) +
1395       sizeof (struct GNUNET_MessageHeader))
1396   {
1397     GNUNET_break (0);
1398     return;
1399   }
1400   type = ntohs (msg->header.type);
1401   LOG (GNUNET_ERROR_TYPE_DEBUG, "got a %s message\n",
1402               GNUNET_MESH_DEBUG_M2S (type));
1403   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1404               GNUNET_MESH_DEBUG_M2S (ntohs (msg[1].header.type)));
1405
1406   /* Check channel */
1407   ch = channel_get (t, ntohl (msg->chid));
1408   if (NULL == ch)
1409   {
1410     GNUNET_STATISTICS_update (stats, "# data on unknown channel", 1, GNUNET_NO);
1411     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1412                 ntohl (msg->chid));
1413     return;
1414   }
1415
1416   /*  Initialize FWD/BCK data */
1417   c   = fwd ? ch->dest     : ch->root;
1418   rel = fwd ? ch->dest_rel : ch->root_rel;
1419
1420   if (NULL == c)
1421   {
1422     GNUNET_break (0);
1423     return;
1424   }
1425
1426   GMT_change_state (t, MESH_TUNNEL_READY);
1427
1428   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
1429
1430   mid = ntohl (msg->mid);
1431   LOG (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
1432
1433   if (GNUNET_NO == ch->reliable ||
1434       ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
1435         GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1436   {
1437     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
1438     if (GNUNET_YES == ch->reliable)
1439     {
1440       /* Is this the exact next expected messasge? */
1441       if (mid == rel->mid_recv)
1442       {
1443         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
1444         rel->mid_recv++;
1445         send_client_data (ch, msg, fwd);
1446       }
1447       else
1448       {
1449         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1450         add_buffered_data (msg, rel);
1451       }
1452     }
1453     else
1454     {
1455       /* Tunnel is unreliable: send to clients directly */
1456       /* FIXME: accept Out Of Order traffic */
1457       rel->mid_recv = mid + 1;
1458       send_client_data (ch, msg, fwd);
1459     }
1460   }
1461   else
1462   {
1463     GNUNET_break_op (0);
1464     LOG (GNUNET_ERROR_TYPE_DEBUG,
1465                 " MID %u not expected (%u - %u), dropping!\n",
1466                 mid, rel->mid_recv, rel->mid_recv + 64);
1467   }
1468
1469   GMCH_send_ack (ch, fwd);
1470 }
1471
1472
1473 /**
1474  * Handler for mesh network traffic end-to-end ACKs.
1475  *
1476  * @param t Tunnel on which we got this message.
1477  * @param message Data message.
1478  * @param fwd Is this a fwd ACK? (dest->orig)
1479  */
1480 void
1481 GMCH_handle_data_ack (struct MeshTunnel2 *t,
1482                       const struct GNUNET_MESH_DataACK *msg,
1483                       int fwd)
1484 {
1485   struct MeshChannelReliability *rel;
1486   struct MeshReliableMessage *copy;
1487   struct MeshReliableMessage *next;
1488   struct MeshChannel *ch;
1489   uint32_t ack;
1490   uint16_t type;
1491   int work;
1492
1493   type = ntohs (msg->header.type);
1494   LOG (GNUNET_ERROR_TYPE_DEBUG, "Got a %s message!\n",
1495               GNUNET_MESH_DEBUG_M2S (type));
1496   ch = channel_get (t, ntohl (msg->chid));
1497   if (NULL == ch)
1498   {
1499     GNUNET_STATISTICS_update (stats, "# ack on unknown channel", 1, GNUNET_NO);
1500     return;
1501   }
1502   ack = ntohl (msg->mid);
1503   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
1504               (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
1505
1506   if (GNUNET_YES == fwd)
1507   {
1508     rel = ch->root_rel;
1509   }
1510   else
1511   {
1512     rel = ch->dest_rel;
1513   }
1514   if (NULL == rel)
1515   {
1516     GNUNET_break (0);
1517     return;
1518   }
1519
1520   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
1521   {
1522     if (GMC_is_pid_bigger (copy->mid, ack))
1523     {
1524       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
1525       channel_rel_free_sent (rel, msg);
1526       break;
1527     }
1528     work = GNUNET_YES;
1529     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
1530     next = copy->next;
1531     rel_message_free (copy);
1532   }
1533   /* ACK client if needed */
1534 //   channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
1535
1536   /* If some message was free'd, update the retransmission delay*/
1537   if (GNUNET_YES == work)
1538   {
1539     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
1540     {
1541       GNUNET_SCHEDULER_cancel (rel->retry_task);
1542       if (NULL == rel->head_sent)
1543       {
1544         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
1545       }
1546       else
1547       {
1548         struct GNUNET_TIME_Absolute new_target;
1549         struct GNUNET_TIME_Relative delay;
1550
1551         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
1552                                                MESH_RETRANSMIT_MARGIN);
1553         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
1554                                                delay);
1555         delay = GNUNET_TIME_absolute_get_remaining (new_target);
1556         rel->retry_task =
1557             GNUNET_SCHEDULER_add_delayed (delay,
1558                                           &channel_retransmit_message,
1559                                           rel);
1560       }
1561     }
1562     else
1563       GNUNET_break (0);
1564   }
1565 }
1566
1567
1568 /**
1569  * Handler for channel create messages.
1570  *
1571  * @param t Tunnel this channel is to be created in.
1572  * @param msg Message.
1573  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1574  */
1575 void
1576 GMCH_handle_create (struct MeshTunnel2 *t,
1577                     struct GNUNET_MESH_ChannelCreate *msg,
1578                     int fwd)
1579 {
1580   MESH_ChannelNumber chid;
1581   struct MeshChannel *ch;
1582   struct MeshClient *c;
1583   uint32_t port;
1584
1585   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received Channel Create\n");
1586   /* Check message size */
1587   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelCreate))
1588   {
1589     GNUNET_break_op (0);
1590     return;
1591   }
1592
1593   /* Check if channel exists */
1594   chid = ntohl (msg->chid);
1595   LOG (GNUNET_ERROR_TYPE_DEBUG, "   chid %u\n", chid);
1596   ch = channel_get (t, chid);
1597   if (NULL != ch)
1598   {
1599     /* Probably a retransmission, safe to ignore */
1600     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
1601     if (NULL != ch->dest)
1602     {
1603       LOG (GNUNET_ERROR_TYPE_DEBUG, "   duplicate CC!!\n");
1604       GMCH_send_ack (ch, !fwd);
1605       return;
1606     }
1607   }
1608   else
1609   {
1610     /* Create channel */
1611     ch = channel_new (t, NULL, 0);
1612     ch->gid = chid;
1613     channel_set_options (ch, ntohl (msg->opt));
1614   }
1615
1616   /* Find a destination client */
1617   port = ntohl (msg->port);
1618   LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
1619   c = GNUNET_CONTAINER_multihashmap32_get (ports, port);
1620   if (NULL == c)
1621   {
1622     /* TODO send reject */
1623     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
1624     /* TODO free ch */
1625     return;
1626   }
1627
1628   channel_add_client (ch, c);
1629   if (GNUNET_YES == ch->reliable)
1630     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
1631
1632   GMCH_send_create (ch);
1633   GMCH_send_ack (ch, fwd);
1634   GML_send_ack (ch, !fwd);
1635 }
1636
1637
1638 /**
1639  * Handler for channel ack messages.
1640  *
1641  * @param t Tunnel this channel is to be created in.
1642  * @param msg Message.
1643  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1644  */
1645 void
1646 GMCH_handle_ack (struct MeshTunnel2 *t,
1647                  struct GNUNET_MESH_ChannelManage *msg,
1648                  int fwd)
1649 {
1650   MESH_ChannelNumber chid;
1651   struct MeshChannel *ch;
1652
1653   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received Channel ACK\n");
1654   /* Check message size */
1655   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
1656   {
1657     GNUNET_break_op (0);
1658     return;
1659   }
1660
1661   /* Check if channel exists */
1662   chid = ntohl (msg->chid);
1663   ch = channel_get (t, chid);
1664   if (NULL == ch)
1665   {
1666     GNUNET_break_op (0);
1667     LOG (GNUNET_ERROR_TYPE_DEBUG, "   channel %u unknown!!\n", chid);
1668     return;
1669   }
1670
1671   channel_confirm (ch, !fwd);
1672 }
1673
1674
1675 /**
1676  * Handler for channel destroy messages.
1677  *
1678  * @param t Tunnel this channel is to be destroyed of.
1679  * @param msg Message.
1680  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1681  */
1682 void
1683 GMCH_handle_destroy (struct MeshTunnel2 *t,
1684                      struct GNUNET_MESH_ChannelManage *msg,
1685                      int fwd)
1686 {
1687   MESH_ChannelNumber chid;
1688   struct MeshChannel *ch;
1689
1690   /* Check message size */
1691   if (ntohs (msg->header.size) != sizeof (struct GNUNET_MESH_ChannelManage))
1692   {
1693     GNUNET_break_op (0);
1694     return;
1695   }
1696
1697   /* Check if channel exists */
1698   chid = ntohl (msg->chid);
1699   ch = channel_get (t, chid);
1700   if (NULL == ch)
1701   {
1702     /* Probably a retransmission, safe to ignore */
1703     return;
1704   }
1705   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
1706   {
1707     /* Not for us (don't destroy twice a half-open loopback channel) */
1708     return;
1709   }
1710
1711   GMCH_send_destroy (ch, fwd);
1712   channel_destroy (ch);
1713 }
1714