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