- fix "broken connection" notifications
[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 /**
330  * Send data to a client.
331  *
332  * If the client is ready, send directly, otherwise buffer while listening
333  * for a local ACK.
334  *
335  * @param ch Channel
336  * @param msg Message.
337  * @param fwd Is this a fwd (root->dest) message?
338  */
339 static void
340 send_client_data (struct MeshChannel *ch,
341                   const struct GNUNET_MESH_Data *msg,
342                   int fwd)
343 {
344   if (fwd)
345   {
346     if (ch->dest_rel->client_ready)
347       GML_send_data (ch->dest, msg, ch->lid_dest);
348     else
349       add_buffered_data (msg, ch->dest_rel);
350   }
351   else
352   {
353     if (ch->root_rel->client_ready)
354       GML_send_data (ch->root, msg, ch->lid_root);
355     else
356       add_buffered_data (msg, ch->root_rel);
357   }
358 }
359
360
361 /**
362  * Add a client to a channel, initializing all needed data structures.
363  *
364  * @param ch Channel to which add the client.
365  * @param c Client which to add to the channel.
366  */
367 void
368 GMCH_add_client (struct MeshChannel *ch, struct MeshClient *c)
369 {
370   if (NULL != ch->dest)
371   {
372     GNUNET_break (0);
373     return;
374   }
375
376   /* Assign local id as destination */
377   ch->lid_dest = GML_get_next_chid (c);
378
379   /* Store in client's hashmap */
380   GML_channel_add (c, ch->lid_dest, ch);
381
382   GNUNET_break (NULL == ch->dest_rel);
383   ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
384   ch->dest_rel->ch = ch;
385   ch->dest_rel->expected_delay = MESH_RETRANSMIT_TIME;
386
387   ch->dest = c;
388 }
389
390
391 /**
392  * Destroy all reliable messages queued for a channel,
393  * during a channel destruction.
394  * Frees the reliability structure itself.
395  *
396  * @param rel Reliability data for a channel.
397  */
398 static void
399 channel_rel_free_all (struct MeshChannelReliability *rel)
400 {
401   struct MeshReliableMessage *copy;
402   struct MeshReliableMessage *next;
403
404   if (NULL == rel)
405     return;
406
407   for (copy = rel->head_recv; NULL != copy; copy = next)
408   {
409     next = copy->next;
410     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
411     GNUNET_free (copy);
412   }
413   for (copy = rel->head_sent; NULL != copy; copy = next)
414   {
415     next = copy->next;
416     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
417     GNUNET_free (copy);
418   }
419   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
420     GNUNET_SCHEDULER_cancel (rel->retry_task);
421   GNUNET_free (rel);
422 }
423
424
425 /**
426  * Mark future messages as ACK'd.
427  *
428  * @param rel Reliability data.
429  * @param msg DataACK message with a bitfield of future ACK'd messages.
430  */
431 static void
432 channel_rel_free_sent (struct MeshChannelReliability *rel,
433                        const struct GNUNET_MESH_DataACK *msg)
434 {
435   struct MeshReliableMessage *copy;
436   struct MeshReliableMessage *next;
437   uint64_t bitfield;
438   uint64_t mask;
439   uint32_t mid;
440   uint32_t target;
441   unsigned int i;
442
443   bitfield = msg->futures;
444   mid = ntohl (msg->mid);
445   LOG (GNUNET_ERROR_TYPE_DEBUG,
446               "free_sent_reliable %u %llX\n",
447               mid, bitfield);
448   LOG (GNUNET_ERROR_TYPE_DEBUG,
449               " rel %p, head %p\n",
450               rel, rel->head_sent);
451   for (i = 0, copy = rel->head_sent;
452        i < 64 && NULL != copy && 0 != bitfield;
453        i++)
454   {
455     LOG (GNUNET_ERROR_TYPE_DEBUG,
456                 " trying bit %u (mid %u)\n",
457                 i, mid + i + 1);
458     mask = 0x1LL << i;
459     if (0 == (bitfield & mask))
460      continue;
461
462     LOG (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
463     /* Bit was set, clear the bit from the bitfield */
464     bitfield &= ~mask;
465
466     /* The i-th bit was set. Do we have that copy? */
467     /* Skip copies with mid < target */
468     target = mid + i + 1;
469     LOG (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
470     while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
471      copy = copy->next;
472
473     /* Did we run out of copies? (previously freed, it's ok) */
474     if (NULL == copy)
475     {
476      LOG (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
477      return;
478     }
479
480     /* Did we overshoot the target? (previously freed, it's ok) */
481     if (GMC_is_pid_bigger (copy->mid, target))
482     {
483      LOG (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
484      continue;
485     }
486
487     /* Now copy->mid == target, free it */
488     next = copy->next;
489     rel_message_free (copy);
490     copy = next;
491   }
492   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
493 }
494
495
496 /**
497  * We haven't received an ACK after a certain time: restransmit the message.
498  *
499  * @param cls Closure (MeshReliableMessage with the message to restransmit)
500  * @param tc TaskContext.
501  */
502 static void
503 channel_retransmit_message (void *cls,
504                             const struct GNUNET_SCHEDULER_TaskContext *tc)
505 {
506   struct MeshChannelReliability *rel = cls;
507   struct MeshReliableMessage *copy;
508   struct MeshChannel *ch;
509   struct GNUNET_MESH_Data *payload;
510   int fwd;
511
512   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
513   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
514     return;
515
516   ch = rel->ch;
517   copy = rel->head_sent;
518   if (NULL == copy)
519   {
520     GNUNET_break (0);
521     return;
522   }
523
524   /* Search the message to be retransmitted in the outgoing queue.
525    * Check only the queue for the connection that is going to be used,
526    * if the message is stuck in some other connection's queue we shouldn't
527    * act upon it:
528    * - cancelling it and sending the new one doesn't guarantee it's delivery,
529    *   the old connection could be temporary stalled or the queue happened to
530    *   be long at time of insertion.
531    * - not sending the new one could cause terrible delays the old connection
532    *   is stalled.
533    */
534 //   FIXME access to queue elements is limited
535   payload = (struct GNUNET_MESH_Data *) &copy[1];
536   fwd = (rel == ch->root_rel);
537 //   c = GMT_get_connection (ch->t, fwd);
538 //   hop = connection_get_hop (c, fwd);
539 //   for (q = hop->queue_head; NULL != q; q = q->next)
540 //   {
541 //     if (ntohs (payload->header.type) == q->type && ch == q->ch)
542 //     {
543 //       struct GNUNET_MESH_Data *queued_data = q->cls;
544 // 
545 //       if (queued_data->mid == payload->mid)
546 //         break;
547 //     }
548 //   }
549
550   /* Message not found in the queue that we are going to use. */
551 //   if (NULL == q)
552 //   {
553     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
554
555     GMCH_send_prebuilt_message (&payload->header, ch, fwd);
556     GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
557 //   }
558 //   else
559 //   {
560 //     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
561 //   }
562
563   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
564   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
565                                                   &channel_retransmit_message,
566                                                   cls);
567 }
568
569
570 /**
571  * Destroy a reliable message after it has been acknowledged, either by
572  * direct mid ACK or bitfield. Updates the appropriate data structures and
573  * timers and frees all memory.
574  *
575  * @param copy Message that is no longer needed: remote peer got it.
576  */
577 static void
578 rel_message_free (struct MeshReliableMessage *copy)
579 {
580   struct MeshChannelReliability *rel;
581   struct GNUNET_TIME_Relative time;
582
583   rel = copy->rel;
584   time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
585   rel->expected_delay.rel_value_us *= 7;
586   rel->expected_delay.rel_value_us += time.rel_value_us;
587   rel->expected_delay.rel_value_us /= 8;
588   rel->n_sent--;
589   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
590   LOG (GNUNET_ERROR_TYPE_DEBUG, "    n_sent %u\n", rel->n_sent);
591   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
592               GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
593   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
594               GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
595                                                       GNUNET_NO));
596   rel->retry_timer = rel->expected_delay;
597   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
598   GNUNET_free (copy);
599 }
600
601
602
603 /**
604  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
605  *
606  * @param ch Channel to mark as ready.
607  * @param fwd Was the CREATE message sent fwd?
608  */
609 static void
610 channel_confirm (struct MeshChannel *ch, int fwd)
611 {
612   struct MeshChannelReliability *rel;
613   struct MeshReliableMessage *copy;
614   struct MeshReliableMessage *next;
615
616   LOG (GNUNET_ERROR_TYPE_DEBUG,
617               "  channel confirm %s %s:%X\n",
618               fwd ? "FWD" : "BCK", GMT_2s (ch->t), ch->gid);
619   ch->state = MESH_CHANNEL_READY;
620
621   rel = fwd ? ch->root_rel : ch->dest_rel;
622   for (copy = rel->head_sent; NULL != copy; copy = next)
623   {
624     struct GNUNET_MessageHeader *msg;
625
626     next = copy->next;
627     msg = (struct GNUNET_MessageHeader *) &copy[1];
628     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
629     {
630       rel_message_free (copy);
631       /* TODO return? */
632     }
633   }
634   send_ack (NULL, ch, fwd);
635 }
636
637
638 /**
639  * Save a copy to retransmit in case it gets lost.
640  *
641  * Initializes all needed callbacks and timers.
642  *
643  * @param ch Channel this message goes on.
644  * @param msg Message to copy.
645  * @param fwd Is this fwd traffic?
646  */
647 static void
648 channel_save_copy (struct MeshChannel *ch,
649                    const struct GNUNET_MessageHeader *msg,
650                    int fwd)
651 {
652   struct MeshChannelReliability *rel;
653   struct MeshReliableMessage *copy;
654   uint32_t mid;
655   uint16_t type;
656   uint16_t size;
657
658   rel = fwd ? ch->root_rel : ch->dest_rel;
659   mid = rel->mid_send;
660   type = ntohs (msg->type);
661   size = ntohs (msg->size);
662
663   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u\n", mid);
664   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
665   copy->mid = mid;
666   copy->timestamp = GNUNET_TIME_absolute_get ();
667   copy->rel = rel;
668   copy->type = type;
669   memcpy (&copy[1], msg, size);
670   rel->n_sent++;
671   LOG (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
672   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
673   if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
674   {
675     rel->retry_timer =
676         GNUNET_TIME_relative_multiply (rel->expected_delay,
677                                         MESH_RETRANSMIT_MARGIN);
678     rel->retry_task =
679         GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
680                                       &channel_retransmit_message,
681                                       rel);
682   }
683 }
684
685
686
687 /**
688  * Send a buffered message to the client, for in order delivery or
689  * as result of client ACK.
690  *
691  * @param ch Channel on which to empty the message buffer.
692  * @param c Client to send to.
693  * @param fwd Is this to send FWD data?.
694  */
695 static void
696 send_client_buffered_data (struct MeshChannel *ch,
697                            struct MeshClient *c,
698                            int fwd)
699 {
700   struct MeshReliableMessage *copy;
701   struct MeshChannelReliability *rel;
702
703   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
704   rel = fwd ? ch->dest_rel : ch->root_rel;
705   if (GNUNET_NO == rel->client_ready)
706   {
707     LOG (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
708     return;
709   }
710
711   copy = rel->head_recv;
712   /* We never buffer channel management messages */
713   if (NULL != copy)
714   {
715     if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
716     {
717       struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];
718
719       LOG (GNUNET_ERROR_TYPE_DEBUG,
720                   " have %u! now expecting %u\n",
721                   copy->mid, rel->mid_recv + 1);
722       send_client_data (ch, msg, fwd);
723       rel->n_recv--;
724       rel->mid_recv++;
725       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
726       GNUNET_free (copy);
727     }
728     else
729     {
730       LOG (GNUNET_ERROR_TYPE_DEBUG,
731                   " reliable && don't have %u, next is %u\n",
732                   rel->mid_recv,
733                   copy->mid);
734       return;
735     }
736   }
737   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
738 }
739
740
741
742
743 /**
744  * Destroy a channel and free all resources.
745  *
746  * @param ch Channel to destroy.
747  */
748 static void
749 channel_destroy (struct MeshChannel *ch)
750 {
751   struct MeshClient *c;
752
753   if (NULL == ch)
754     return;
755
756   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
757               GMT_2s (ch->t), ch->gid);
758   GMCH_debug (ch);
759
760   c = ch->root;
761   if (NULL != c)
762   {
763     GML_channel_remove (c, ch->lid_root, ch);
764   }
765
766   c = ch->dest;
767   if (NULL != c)
768   {
769     GML_channel_remove (c, ch->lid_dest, ch);
770   }
771
772   channel_rel_free_all (ch->root_rel);
773   channel_rel_free_all (ch->dest_rel);
774
775   GMT_remove_channel (ch->t, ch);
776   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
777
778   GNUNET_free (ch);
779 }
780
781
782 /**
783  * Create a new channel.
784  *
785  * @param t Tunnel this channel is in.
786  * @param owner Client that owns the channel, NULL for foreign channels.
787  * @param lid_root Local ID for root client.
788  *
789  * @return A new initialized channel. NULL on error.
790  */
791 static struct MeshChannel *
792 channel_new (struct MeshTunnel3 *t,
793              struct MeshClient *owner, MESH_ChannelNumber lid_root)
794 {
795   struct MeshChannel *ch;
796
797   ch = GNUNET_new (struct MeshChannel);
798   ch->root = owner;
799   ch->lid_root = lid_root;
800   ch->t = t;
801
802   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
803
804   if (NULL != owner)
805   {
806     ch->gid = GMT_get_next_chid (t);
807     GML_channel_add (owner, lid_root, ch);
808   }
809   GMT_add_channel (t, ch);
810
811   return ch;
812 }
813
814
815 /**
816  * Set options in a channel, extracted from a bit flag field
817  *
818  * @param ch Channel to set options to.
819  * @param options Bit array in host byte order.
820  */
821 static void
822 channel_set_options (struct MeshChannel *ch, uint32_t options)
823 {
824   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
825                  GNUNET_YES : GNUNET_NO;
826   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
827                  GNUNET_YES : GNUNET_NO;
828 }
829
830
831
832 /**
833  * Confirm we got a channel create.
834  *
835  * @param ch The channel to confirm.
836  * @param fwd Should we send the ACK fwd?
837  */
838 static void
839 channel_send_ack (struct MeshChannel *ch, int fwd)
840 {
841   struct GNUNET_MESH_ChannelManage msg;
842
843   msg.header.size = htons (sizeof (msg));
844   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
845   LOG (GNUNET_ERROR_TYPE_DEBUG,
846               "  sending channel %s ack for channel %s:%X\n",
847               fwd ? "FWD" : "BCK", GMT_2s (ch->t),
848               ch->gid);
849
850   msg.chid = htonl (ch->gid);
851   GMCH_send_prebuilt_message (&msg.header, ch, !fwd);
852 }
853
854
855 /**
856  * Handle a loopback message: call the appropriate handler for the message type.
857  *
858  * @param ch Channel this message is on.
859  * @param msgh Message header.
860  * @param fwd Is this FWD traffic?
861  */
862 void
863 handle_loopback (struct MeshChannel *ch,
864                  const struct GNUNET_MessageHeader *msgh,
865                  int fwd)
866 {
867   uint16_t type;
868
869   type = ntohs (msgh->type);
870   LOG (GNUNET_ERROR_TYPE_DEBUG,
871        "Loopback %s message!\n",
872        GNUNET_MESH_DEBUG_M2S (type));
873
874   switch (type)
875   {
876     case GNUNET_MESSAGE_TYPE_MESH_DATA:
877       /* Don't send hop ACK, wait for client to ACK */
878       GMCH_handle_data (ch, (struct GNUNET_MESH_Data *) msgh, fwd);
879       break;
880
881     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
882       GMCH_handle_data_ack (ch, (struct GNUNET_MESH_DataACK *) msgh, fwd);
883       break;
884
885     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
886        // FIXME store channel in loopback tunnel?
887       GMCH_handle_create ((struct GNUNET_MESH_ChannelCreate *) msgh,
888                           fwd);
889       break;
890
891     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
892       GMCH_handle_ack (ch,
893                        (struct GNUNET_MESH_ChannelManage *) msgh,
894                        fwd);
895       break;
896
897     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
898       GMCH_handle_destroy (ch,
899                            (struct GNUNET_MESH_ChannelManage *) msgh,
900                            fwd);
901       break;
902
903     default:
904       GNUNET_break_op (0);
905       LOG (GNUNET_ERROR_TYPE_DEBUG,
906            "end-to-end message not known (%u)\n",
907            ntohs (msgh->type));
908   }
909 }
910
911
912
913 /******************************************************************************/
914 /********************************    API    ***********************************/
915 /******************************************************************************/
916
917 /**
918  * Get channel ID.
919  *
920  * @param ch Channel.
921  *
922  * @return ID
923  */
924 MESH_ChannelNumber
925 GMCH_get_id (const struct MeshChannel *ch)
926 {
927   return ch->gid;
928 }
929
930
931 /**
932  * Get the channel tunnel.
933  *
934  * @param ch Channel to get the tunnel from.
935  *
936  * @return tunnel of the channel.
937  */
938 struct MeshTunnel3 *
939 GMCH_get_tunnel (const struct MeshChannel *ch)
940 {
941   return ch->t;
942 }
943
944
945 /**
946  * Get free buffer space towards the client on a specific channel.
947  *
948  * @param ch Channel.
949  * @param fwd Is query about FWD traffic?
950  *
951  * @return Free buffer space [0 - 64]
952  */
953 unsigned int
954 GMCH_get_buffer (struct MeshChannel *ch, int fwd)
955 {
956   struct MeshChannelReliability *rel;
957
958   rel = fwd ? ch->dest_rel : ch->root_rel;
959
960   /* If rel is NULL it means that the end is not yet created,
961    * most probably is a loopback channel at the point of sending
962    * the ChannelCreate to itself.
963    */
964   if (NULL == rel)
965     return 64;
966
967   return (64 - rel->n_recv);
968 }
969
970
971 /**
972  * Is the root client for this channel on this peer?
973  *
974  * @param ch Channel.
975  * @param fwd Is this for fwd traffic?
976  *
977  * @return GNUNET_YES in case it is.
978  */
979 int
980 GMCH_is_origin (struct MeshChannel *ch, int fwd)
981 {
982   struct MeshClient *c;
983
984   c = fwd ? ch->root : ch->dest;
985   return NULL != c;
986 }
987
988
989 /**
990  * Is the destination client for this channel on this peer?
991  *
992  * @param ch Channel.
993  * @param fwd Is this for fwd traffic?
994  *
995  * @return GNUNET_YES in case it is.
996  */
997 int
998 GMCH_is_terminal (struct MeshChannel *ch, int fwd)
999 {
1000   struct MeshClient *c;
1001
1002   c = fwd ? ch->dest : ch->root;
1003   return NULL != c;
1004 }
1005
1006
1007 /**
1008  * Notify the destination client that a new incoming channel was created.
1009  *
1010  * @param ch Channel that was created.
1011  */
1012 void
1013 GMCH_send_create (struct MeshChannel *ch)
1014 {
1015   uint32_t opt;
1016
1017   if (NULL == ch->dest)
1018     return;
1019
1020   opt = 0;
1021   opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1022   opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1023   GML_send_channel_create (ch->dest, ch->lid_dest, ch->port, opt,
1024                            GMT_get_destination (ch->t));
1025
1026 }
1027
1028 /**
1029  * Notify a client that the channel is no longer valid.
1030  * FIXME send on tunnel if some client == NULL?
1031  *
1032  * @param ch Channel that is destroyed.
1033  */
1034 void
1035 GMCH_send_destroy (struct MeshChannel *ch)
1036 {
1037   if (NULL != ch->root)
1038     GML_send_channel_destroy (ch->root, ch->lid_root);
1039
1040   if (NULL != ch->dest)
1041     GML_send_channel_destroy (ch->dest, ch->lid_dest);
1042 }
1043
1044
1045 /**
1046  * Send data on a channel.
1047  *
1048  * If the destination is local, send it to client, otherwise encrypt and
1049  * send to next hop.
1050  *
1051  * @param ch Channel
1052  * @param msg Message.
1053  * @param fwd Is this a fwd (root->dest) message?
1054  */
1055 void
1056 GMCH_send_data (struct MeshChannel *ch,
1057                 const struct GNUNET_MESH_Data *msg,
1058                 int fwd)
1059 {
1060 }
1061
1062
1063 /**
1064  * Send an end-to-end ACK message for the most recent in-sequence payload.
1065  *
1066  * If channel is not reliable, do nothing.
1067  *
1068  * @param ch Channel this is about.
1069  * @param fwd Is for FWD traffic? (ACK dest->owner)
1070  */
1071 void
1072 GMCH_send_ack (struct MeshChannel *ch, int fwd)
1073 {
1074   struct GNUNET_MESH_DataACK msg;
1075   struct MeshChannelReliability *rel;
1076   struct MeshReliableMessage *copy;
1077   unsigned int delta;
1078   uint64_t mask;
1079   uint16_t type;
1080
1081   if (GNUNET_NO == ch->reliable)
1082   {
1083     return;
1084   }
1085   rel = fwd ? ch->dest_rel : ch->root_rel;
1086   LOG (GNUNET_ERROR_TYPE_DEBUG,
1087               "send_data_ack for %u\n",
1088               rel->mid_recv - 1);
1089
1090   type = GNUNET_MESSAGE_TYPE_MESH_DATA_ACK;
1091   msg.header.type = htons (type);
1092   msg.header.size = htons (sizeof (msg));
1093   msg.chid = htonl (ch->gid);
1094   msg.mid = htonl (rel->mid_recv - 1);
1095   msg.futures = 0;
1096   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
1097   {
1098     if (copy->type != type)
1099       continue;
1100     delta = copy->mid - rel->mid_recv;
1101     if (63 < delta)
1102       break;
1103     mask = 0x1LL << delta;
1104     msg.futures |= mask;
1105     LOG (GNUNET_ERROR_TYPE_DEBUG,
1106                 " setting bit for %u (delta %u) (%llX) -> %llX\n",
1107                 copy->mid, delta, mask, msg.futures);
1108   }
1109   LOG (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
1110
1111   GMCH_send_prebuilt_message (&msg.header, ch, fwd);
1112   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1113 }
1114
1115
1116 /**
1117  * Log channel info.
1118  *
1119  * @param ch Channel.
1120  */
1121 void
1122 GMCH_debug (struct MeshChannel *ch)
1123 {
1124   if (NULL == ch)
1125   {
1126     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
1127     return;
1128   }
1129   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X (%p)\n",
1130               GMT_2s (ch->t), ch->gid, ch);
1131   LOG (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
1132               ch->root, ch->root_rel);
1133   if (NULL != ch->root)
1134   {
1135     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->root));
1136     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1137                 ch->root_rel->client_ready ? "YES" : "NO");
1138     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_root);
1139   }
1140   LOG (GNUNET_ERROR_TYPE_DEBUG, "  dest %p/%p\n",
1141               ch->dest, ch->dest_rel);
1142   if (NULL != ch->dest)
1143   {
1144     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->dest));
1145     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1146                 ch->dest_rel->client_ready ? "YES" : "NO");
1147     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_dest);
1148   }
1149 }
1150
1151
1152 /**
1153  * Handle an ACK given by a client.
1154  *
1155  * Mark client as ready and send him any buffered data we could have for him.
1156  *
1157  * @param ch Channel.
1158  * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by root and go BCK)
1159  */
1160 void
1161 GMCH_handle_local_ack (struct MeshChannel *ch, int fwd)
1162 {
1163   struct MeshChannelReliability *rel;
1164   struct MeshClient *c;
1165
1166   rel = fwd ? ch->dest_rel : ch->root_rel;
1167   c   = fwd ? ch->dest     : ch->root;
1168
1169   rel->client_ready = GNUNET_YES;
1170   send_client_buffered_data (ch, c, fwd);
1171   send_ack (NULL, ch, fwd);
1172 }
1173
1174
1175 /**
1176  * Handle data given by a client.
1177  *
1178  * Check whether the client is allowed to send in this tunnel, save if channel
1179  * is reliable and send an ACK to the client if there is still buffer space
1180  * in the tunnel.
1181  *
1182  * @param ch Channel.
1183  * @param fwd Is this a FWD data?
1184  *
1185  * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
1186  */
1187 int
1188 GMCH_handle_local_data (struct MeshChannel *ch,
1189                         struct MeshClient *c,
1190                         struct GNUNET_MessageHeader *message,
1191                         int fwd)
1192 {
1193   struct MeshChannelReliability *rel;
1194   struct GNUNET_MESH_Data *payload;
1195   size_t size = ntohs (message->size);
1196   uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
1197   unsigned char cbuf[p2p_size];
1198
1199   /* Is the client in the channel? */
1200   if ( !( (fwd &&
1201            ch->root == c)
1202          ||
1203           (!fwd &&
1204            ch->dest == c) ) )
1205   {
1206     GNUNET_break (0);
1207     return GNUNET_SYSERR;
1208   }
1209
1210   rel = fwd ? ch->root_rel : ch->dest_rel;
1211
1212   /* Ok, everything is correct, send the message. */
1213   payload = (struct GNUNET_MESH_Data *) cbuf;
1214   payload->mid = htonl (rel->mid_send);
1215   rel->mid_send++;
1216   memcpy (&payload[1], message, size);
1217   payload->header.size = htons (p2p_size);
1218   payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
1219   payload->chid = htonl (ch->gid);
1220   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1221   GMCH_send_prebuilt_message (&payload->header, ch, fwd);
1222
1223   if (GNUNET_YES == ch->reliable)
1224     channel_save_copy (ch, &payload->header, fwd);
1225   if (GMT_get_buffer (ch->t, fwd) > 0)
1226     GML_send_ack (c, fwd ? ch->lid_root : ch->lid_dest);
1227
1228   return GNUNET_OK;
1229 }
1230
1231
1232 /**
1233  * Handle a channel destroy requested by a client.
1234  *
1235  * Destroy the channel and the tunnel in case this was the last channel.
1236  *
1237  * @param ch Channel.
1238  * @param c Client that requested the destruction (to avoid notifying him).
1239  */
1240 void
1241 GMCH_handle_local_destroy (struct MeshChannel *ch,
1242                            struct MeshClient *c)
1243 {
1244   struct MeshTunnel3 *t;
1245
1246   /* Cleanup after the tunnel */
1247   if (c == ch->dest)
1248   {
1249     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
1250     GML_client_delete_channel (c, ch, ch->lid_dest);
1251     ch->dest = NULL;
1252   }
1253   if (c == ch->root)
1254   {
1255     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
1256     GML_client_delete_channel (c, ch, ch->lid_root);
1257     ch->root = NULL;
1258   }
1259
1260   t = ch->t;
1261   GMCH_send_destroy (ch);
1262   channel_destroy (ch);
1263   GMT_destroy_if_empty (t);
1264 }
1265
1266
1267 /**
1268  * Handle a channel create requested by a client.
1269  *
1270  * Create the channel and the tunnel in case this was the first0 channel.
1271  *
1272  * @param c Client that requested the creation (will be the root).
1273  * @param msg Create Channel message.
1274  *
1275  * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
1276  */
1277 int
1278 GMCH_handle_local_create (struct MeshClient *c,
1279                           struct GNUNET_MESH_ChannelMessage *msg)
1280 {
1281   struct MeshChannel *ch;
1282   struct MeshTunnel3 *t;
1283   struct MeshPeer *peer;
1284   MESH_ChannelNumber chid;
1285
1286   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
1287               GNUNET_i2s (&msg->peer), ntohl (msg->port));
1288   chid = ntohl (msg->channel_id);
1289
1290   /* Sanity check for duplicate channel IDs */
1291   if (NULL != GML_channel_get (c, chid))
1292   {
1293     GNUNET_break (0);
1294     return GNUNET_SYSERR;
1295   }
1296
1297   peer = GMP_get (&msg->peer);
1298   GMP_add_tunnel (peer);
1299   t = GMP_get_tunnel (peer);
1300
1301   if (GMP_get_short_id (peer) == myid)
1302   {
1303     GMT_change_state (t, MESH_TUNNEL3_READY);
1304   }
1305   else
1306   {
1307     GMP_connect (peer);
1308   }
1309
1310   /* Create channel */
1311   ch = channel_new (t, c, chid);
1312   if (NULL == ch)
1313   {
1314     GNUNET_break (0);
1315     return GNUNET_SYSERR;
1316   }
1317   ch->port = ntohl (msg->port);
1318   channel_set_options (ch, ntohl (msg->opt));
1319
1320   /* In unreliable channels, we'll use the DLL to buffer BCK data */
1321   ch->root_rel = GNUNET_new (struct MeshChannelReliability);
1322   ch->root_rel->ch = ch;
1323   ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;
1324
1325   LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s[%x]:%u (%x)\n",
1326        GMT_2s (t), ch->gid, ch->port, ch->lid_root);
1327
1328   /* Send create channel */
1329   {
1330     struct GNUNET_MESH_ChannelCreate msgcc;
1331
1332     msgcc.header.size = htons (sizeof (msgcc));
1333     msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
1334     msgcc.chid = htonl (ch->gid);
1335     msgcc.port = msg->port;
1336     msgcc.opt = msg->opt;
1337
1338     GMT_queue_data (t, ch, &msgcc.header, GNUNET_YES);
1339   }
1340   return GNUNET_OK;
1341 }
1342
1343 /**
1344  * Handler for mesh network payload traffic.
1345  *
1346  * @param ch Channel for the message.
1347  * @param message Unencryted data message.
1348  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1349  */
1350 void
1351 GMCH_handle_data (struct MeshChannel *ch,
1352                   const struct GNUNET_MESH_Data *msg,
1353                   int fwd)
1354 {
1355   struct MeshChannelReliability *rel;
1356   struct MeshClient *c;
1357   uint32_t mid;
1358
1359   /*  Initialize FWD/BCK data */
1360   c   = fwd ? ch->dest     : ch->root;
1361   rel = fwd ? ch->dest_rel : ch->root_rel;
1362
1363   if (NULL == c)
1364   {
1365     GNUNET_break (0);
1366     return;
1367   }
1368
1369   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
1370
1371   mid = ntohl (msg->mid);
1372   LOG (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
1373
1374   if (GNUNET_NO == ch->reliable ||
1375       ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
1376         GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1377   {
1378     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
1379     if (GNUNET_YES == ch->reliable)
1380     {
1381       /* Is this the exact next expected messasge? */
1382       if (mid == rel->mid_recv)
1383       {
1384         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
1385         rel->mid_recv++;
1386         send_client_data (ch, msg, fwd);
1387       }
1388       else
1389       {
1390         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1391         add_buffered_data (msg, rel);
1392       }
1393     }
1394     else
1395     {
1396       /* Tunnel is unreliable: send to clients directly */
1397       /* FIXME: accept Out Of Order traffic */
1398       rel->mid_recv = mid + 1;
1399       send_client_data (ch, msg, fwd);
1400     }
1401   }
1402   else
1403   {
1404     GNUNET_break_op (0);
1405     LOG (GNUNET_ERROR_TYPE_DEBUG,
1406                 " MID %u not expected (%u - %u), dropping!\n",
1407                 mid, rel->mid_recv, rel->mid_recv + 64);
1408   }
1409
1410   GMCH_send_ack (ch, fwd);
1411 }
1412
1413
1414 /**
1415  * Handler for mesh network traffic end-to-end ACKs.
1416  *
1417  * @param t Tunnel on which we got this message.
1418  * @param message Data message.
1419  * @param fwd Is this a fwd ACK? (dest->orig)
1420  */
1421 void
1422 GMCH_handle_data_ack (struct MeshChannel *ch,
1423                       const struct GNUNET_MESH_DataACK *msg,
1424                       int fwd)
1425 {
1426   struct MeshChannelReliability *rel;
1427   struct MeshReliableMessage *copy;
1428   struct MeshReliableMessage *next;
1429   uint32_t ack;
1430   int work;
1431
1432   ack = ntohl (msg->mid);
1433   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
1434               (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
1435
1436   if (GNUNET_YES == fwd)
1437   {
1438     rel = ch->root_rel;
1439   }
1440   else
1441   {
1442     rel = ch->dest_rel;
1443   }
1444   if (NULL == rel)
1445   {
1446     GNUNET_break (0);
1447     return;
1448   }
1449
1450   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
1451   {
1452     if (GMC_is_pid_bigger (copy->mid, ack))
1453     {
1454       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
1455       channel_rel_free_sent (rel, msg);
1456       break;
1457     }
1458     work = GNUNET_YES;
1459     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
1460     next = copy->next;
1461     rel_message_free (copy);
1462   }
1463   /* ACK client if needed */
1464 //   channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
1465
1466   /* If some message was free'd, update the retransmission delay*/
1467   if (GNUNET_YES == work)
1468   {
1469     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
1470     {
1471       GNUNET_SCHEDULER_cancel (rel->retry_task);
1472       if (NULL == rel->head_sent)
1473       {
1474         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
1475       }
1476       else
1477       {
1478         struct GNUNET_TIME_Absolute new_target;
1479         struct GNUNET_TIME_Relative delay;
1480
1481         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
1482                                                MESH_RETRANSMIT_MARGIN);
1483         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
1484                                                delay);
1485         delay = GNUNET_TIME_absolute_get_remaining (new_target);
1486         rel->retry_task =
1487             GNUNET_SCHEDULER_add_delayed (delay,
1488                                           &channel_retransmit_message,
1489                                           rel);
1490       }
1491     }
1492     else
1493       GNUNET_break (0);
1494   }
1495 }
1496
1497
1498 /**
1499  * Handler for channel create messages.
1500  *
1501  * @param msg Message.
1502  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1503  */
1504 struct MeshChannel *
1505 GMCH_handle_create (const struct GNUNET_MESH_ChannelCreate *msg,
1506                     int fwd)
1507 {
1508   MESH_ChannelNumber chid;
1509   struct MeshChannel *ch;
1510   struct MeshClient *c;
1511   uint32_t port;
1512
1513   chid = ntohl (msg->chid);
1514
1515   /* Create channel */
1516   ch = channel_new (NULL, NULL, 0); /* FIXME pass t */
1517   ch->gid = chid;
1518   channel_set_options (ch, ntohl (msg->opt));
1519
1520   /* Find a destination client */
1521   port = ntohl (msg->port);
1522   LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
1523   c = GML_client_get_by_port (port);
1524   if (NULL == c)
1525   {
1526     /* TODO send reject */
1527     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
1528     channel_destroy (ch);
1529     return NULL;
1530   }
1531
1532   GMCH_add_client (ch, c);
1533   if (GNUNET_YES == ch->reliable)
1534     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
1535
1536   GMCH_send_create (ch);
1537   GMCH_send_ack (ch, fwd);
1538
1539   if (GNUNET_NO == ch->dest_rel->client_ready)
1540   {
1541     GML_send_ack (ch->dest, ch->lid_dest);
1542     ch->dest_rel->client_ready = GNUNET_YES;
1543   }
1544
1545   return ch;
1546 }
1547
1548
1549 /**
1550  * Handler for channel ack messages.
1551  *
1552  * @param ch Channel.
1553  * @param msg Message.
1554  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1555  */
1556 void
1557 GMCH_handle_ack (struct MeshChannel *ch,
1558                  const struct GNUNET_MESH_ChannelManage *msg,
1559                  int fwd)
1560 {
1561   channel_confirm (ch, !fwd);
1562 }
1563
1564
1565 /**
1566  * Handler for channel destroy messages.
1567  *
1568  * @param ch Channel to be destroyed of.
1569  * @param msg Message.
1570  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1571  */
1572 void
1573 GMCH_handle_destroy (struct MeshChannel *ch,
1574                      const struct GNUNET_MESH_ChannelManage *msg,
1575                      int fwd)
1576 {
1577   struct MeshTunnel3 *t;
1578
1579   GMCH_debug (ch);
1580   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
1581   {
1582     /* Not for us (don't destroy twice a half-open loopback channel) */
1583     return;
1584   }
1585
1586   t = ch->t;
1587   GMCH_send_destroy (ch);
1588   channel_destroy (ch);
1589   GMT_destroy_if_empty (t);
1590 }
1591
1592
1593 /**
1594  * Sends an already built message on a channel.
1595  *
1596  * If the channel is on a loopback tunnel, notifies the appropriate destination
1597  * client locally.
1598  *
1599  * On a normal channel passes the message to the tunnel for encryption and
1600  * sending on a connection.
1601  *
1602  * This function DOES NOT save the message for retransmission.
1603  *
1604  * @param message Message to send. Function makes a copy of it.
1605  * @param ch Channel on which this message is transmitted.
1606  * @param fwd Is this a fwd message?
1607  */
1608 void
1609 GMCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1610                             struct MeshChannel *ch, int fwd)
1611 {
1612   LOG (GNUNET_ERROR_TYPE_DEBUG, "Send on Channel %s:%X %s\n",
1613        GMT_2s (ch->t), ch->gid, fwd ? "FWD" : "BCK");
1614   LOG (GNUNET_ERROR_TYPE_DEBUG, "  %s\n",
1615        GNUNET_MESH_DEBUG_M2S (ntohs (message->type)));
1616
1617   if (GMT_is_loopback (ch->t))
1618   {
1619     handle_loopback (ch, message, fwd);
1620     return;
1621   }
1622
1623   GMT_send_prebuilt_message (message, ch->t, ch, fwd);
1624 }
1625
1626
1627 /**
1628  * Get the static string for identification of the channel.
1629  *
1630  * @param ch Channel.
1631  *
1632  * @return Static string with the channel IDs.
1633  */
1634 const char *
1635 GMCH_2s (const struct MeshChannel *ch)
1636 {
1637   static char buf[64];
1638
1639   if (NULL == ch)
1640     return "(NULL Channel)";
1641
1642   sprintf (buf, "%s:%X (%X / %X)",
1643            GMT_2s (ch->t), ch->gid, ch->lid_root, ch->lid_dest);
1644
1645   return buf;
1646 }