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