- initialize timers
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh_channel.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21
22 #include "platform.h"
23 #include "gnunet_util_lib.h"
24
25 #include "gnunet_statistics_service.h"
26
27 #include "mesh.h"
28 #include "mesh_protocol.h"
29
30 #include "gnunet-service-mesh_channel.h"
31 #include "gnunet-service-mesh_local.h"
32 #include "gnunet-service-mesh_tunnel.h"
33 #include "gnunet-service-mesh_peer.h"
34
35 #define LOG(level, ...) GNUNET_log_from(level,"mesh-chn",__VA_ARGS__)
36
37 #define MESH_RETRANSMIT_TIME    GNUNET_TIME_UNIT_SECONDS
38 #define MESH_RETRANSMIT_MARGIN  4
39
40
41 /**
42  * All the states a connection can be in.
43  */
44 enum MeshChannelState
45 {
46   /**
47    * Uninitialized status, should never appear in operation.
48    */
49   MESH_CHANNEL_NEW,
50
51   /**
52    * Connection create message sent, waiting for ACK.
53    */
54   MESH_CHANNEL_SENT,
55
56   /**
57    * Connection confirmed, ready to carry traffic.
58    */
59   MESH_CHANNEL_READY,
60 };
61
62
63 /**
64  * Info holder for channel messages in queues.
65  */
66 struct MeshChannelQueue
67 {
68   /**
69    * Tunnel Queue.
70    */
71   struct MeshTunnel3Queue *q;
72
73   /**
74    * Message type (DATA/DATA_ACK)
75    */
76   uint16_t type;
77
78   /**
79    * Message copy (for DATAs, to start retransmission timer)
80    */
81   struct MeshReliableMessage *copy;
82
83   /**
84    * Reliability (for DATA_ACKs, to access rel->ack_q)
85    */
86   struct MeshChannelReliability *rel;
87 };
88
89
90 /**
91  * Info needed to retry a message in case it gets lost.
92  */
93 struct MeshReliableMessage
94 {
95     /**
96      * Double linked list, FIFO style
97      */
98   struct MeshReliableMessage    *next;
99   struct MeshReliableMessage    *prev;
100
101     /**
102      * Type of message (payload, channel management).
103      */
104   int16_t type;
105
106     /**
107      * Tunnel Reliability queue this message is in.
108      */
109   struct MeshChannelReliability  *rel;
110
111     /**
112      * ID of the message (ACK needed to free)
113      */
114   uint32_t                      mid;
115
116   /**
117    * Tunnel Queue.
118    */
119   struct MeshChannelQueue       *q;
120
121     /**
122      * When was this message issued (to calculate ACK delay)
123      */
124   struct GNUNET_TIME_Absolute   timestamp;
125
126   /* struct GNUNET_MESH_Data with payload */
127 };
128
129
130 /**
131  * Info about the traffic state for a client in a channel.
132  */
133 struct MeshChannelReliability
134 {
135     /**
136      * Channel this is about.
137      */
138   struct MeshChannel *ch;
139
140     /**
141      * DLL of messages sent and not yet ACK'd.
142      */
143   struct MeshReliableMessage        *head_sent;
144   struct MeshReliableMessage        *tail_sent;
145
146     /**
147      * DLL of messages received out of order.
148      */
149   struct MeshReliableMessage        *head_recv;
150   struct MeshReliableMessage        *tail_recv;
151
152     /**
153      * Messages received.
154      */
155   unsigned int                      n_recv;
156
157     /**
158      * Next MID to use for outgoing traffic.
159      */
160   uint32_t                          mid_send;
161
162     /**
163      * Next MID expected for incoming traffic.
164      */
165   uint32_t                          mid_recv;
166
167     /**
168      * Handle for queued unique data CREATE, DATA_ACK.
169      */
170   struct MeshChannelQueue           *uniq;
171
172     /**
173      * Can we send data to the client?
174      */
175   int                               client_ready;
176
177   /**
178    * Can the client send data to us?
179    */
180   int                               client_allowed;
181
182     /**
183      * Task to resend/poll in case no ACK is received.
184      */
185   GNUNET_SCHEDULER_TaskIdentifier   retry_task;
186
187     /**
188      * Counter for exponential backoff.
189      */
190   struct GNUNET_TIME_Relative       retry_timer;
191
192     /**
193      * How long does it usually take to get an ACK.
194      */
195   struct GNUNET_TIME_Relative       expected_delay;
196 };
197
198
199 /**
200  * Struct containing all information regarding a channel to a remote client.
201  */
202 struct MeshChannel
203 {
204     /**
205      * Tunnel this channel is in.
206      */
207   struct MeshTunnel3 *t;
208
209     /**
210      * Destination port of the channel.
211      */
212   uint32_t port;
213
214     /**
215      * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
216      */
217   MESH_ChannelNumber gid;
218
219     /**
220      * Local tunnel number for root (owner) client.
221      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
222      */
223   MESH_ChannelNumber lid_root;
224
225     /**
226      * Local tunnel number for local destination clients (incoming number)
227      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
228      */
229   MESH_ChannelNumber lid_dest;
230
231     /**
232      * Channel state.
233      */
234   enum MeshChannelState state;
235
236     /**
237      * Is the tunnel bufferless (minimum latency)?
238      */
239   int nobuffer;
240
241     /**
242      * Is the tunnel reliable?
243      */
244   int reliable;
245
246     /**
247      * Last time the channel was used
248      */
249   struct GNUNET_TIME_Absolute timestamp;
250
251     /**
252      * Client owner of the tunnel, if any
253      */
254   struct MeshClient *root;
255
256     /**
257      * Client destination of the tunnel, if any.
258      */
259   struct MeshClient *dest;
260
261     /**
262      * Flag to signal the destruction of the channel.
263      * If this is set GNUNET_YES the channel will be destroyed
264      * when the queue is empty.
265      */
266   int destroy;
267
268     /**
269      * Total (reliable) messages pending ACK for this channel.
270      */
271   unsigned int pending_messages;
272
273     /**
274      * Reliability data.
275      * Only present (non-NULL) at the owner of a tunnel.
276      */
277   struct MeshChannelReliability *root_rel;
278
279     /**
280      * Reliability data.
281      * Only present (non-NULL) at the destination of a tunnel.
282      */
283   struct MeshChannelReliability *dest_rel;
284
285 };
286
287
288 /******************************************************************************/
289 /*******************************   GLOBALS  ***********************************/
290 /******************************************************************************/
291
292 /**
293  * Global handle to the statistics service.
294  */
295 extern struct GNUNET_STATISTICS_Handle *stats;
296
297 /**
298  * Local peer own ID (memory efficient handle).
299  */
300 extern GNUNET_PEER_Id myid;
301
302
303 /******************************************************************************/
304 /********************************   STATIC  ***********************************/
305 /******************************************************************************/
306
307 /**
308  * Destroy a reliable message after it has been acknowledged, either by
309  * direct mid ACK or bitfield. Updates the appropriate data structures and
310  * timers and frees all memory.
311  *
312  * @param copy Message that is no longer needed: remote peer got it.
313  * @param update_time Is the timing information relevant?
314  *                    If this message is ACK in a batch the timing information
315  *                    is skewed by the retransmission, count only for the
316  *                    retransmitted message.
317  */
318 static void
319 rel_message_free (struct MeshReliableMessage *copy, int update_time);
320
321 /**
322  * send a channel create message.
323  *
324  * @param ch Channel for which to send.
325  */
326 static void
327 send_create (struct MeshChannel *ch);
328
329
330
331 /**
332  * We have received a message out of order, or the client is not ready.
333  * Buffer it until we receive an ACK from the client or the missing
334  * message from the channel.
335  *
336  * @param msg Message to buffer (MUST be of type MESH_DATA).
337  * @param rel Reliability data to the corresponding direction.
338  */
339 static void
340 add_buffered_data (const struct GNUNET_MESH_Data *msg,
341                    struct MeshChannelReliability *rel)
342 {
343   struct MeshReliableMessage *copy;
344   struct MeshReliableMessage *prev;
345   uint32_t mid;
346   uint16_t size;
347
348   size = ntohs (msg->header.size);
349   mid = ntohl (msg->mid);
350
351   LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
352
353   copy = GNUNET_malloc (sizeof (*copy) + size);
354   copy->mid = mid;
355   copy->rel = rel;
356   copy->type = GNUNET_MESSAGE_TYPE_MESH_DATA;
357   memcpy (&copy[1], msg, size);
358
359   rel->n_recv++;
360
361   // FIXME do something better than O(n), although n < 64...
362   // FIXME start from the end (most messages are the latest ones)
363   for (prev = rel->head_recv; NULL != prev; prev = prev->next)
364   {
365     LOG (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
366     if (GM_is_pid_bigger (prev->mid, mid))
367     {
368       LOG (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
369       GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
370                                           prev, copy);
371       return;
372     }
373   }
374     LOG (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
375     GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
376     LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
377 }
378
379 /**
380  * Add a destination client to a channel, initializing all data structures
381  * in the channel and the client.
382  *
383  * @param ch Channel to which add the destination.
384  * @param c Client which to add to the channel.
385  */
386 static void
387 add_destination (struct MeshChannel *ch, struct MeshClient *c)
388 {
389   if (NULL != ch->dest)
390   {
391     GNUNET_break (0);
392     return;
393   }
394
395   /* Assign local id as destination */
396   ch->lid_dest = GML_get_next_chid (c);
397
398   /* Store in client's hashmap */
399   GML_channel_add (c, ch->lid_dest, ch);
400
401   GNUNET_break (NULL == ch->dest_rel);
402   ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
403   ch->dest_rel->ch = ch;
404   ch->dest_rel->expected_delay.rel_value_us = 0;
405
406   ch->dest = c;
407 }
408
409
410 /**
411  * Set options in a channel, extracted from a bit flag field.
412  *
413  * @param ch Channel to set options to.
414  * @param options Bit array in host byte order.
415  */
416 static void
417 channel_set_options (struct MeshChannel *ch, uint32_t options)
418 {
419   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
420   GNUNET_YES : GNUNET_NO;
421   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
422   GNUNET_YES : GNUNET_NO;
423 }
424
425
426 /**
427  * Get a bit flag field with the options of a channel.
428  *
429  * @param ch Channel to get options from.
430  *
431  * @return Bit array in host byte order.
432  */
433 static uint32_t
434 channel_get_options (struct MeshChannel *ch)
435 {
436   uint32_t options;
437
438   options = 0;
439   if (ch->nobuffer)
440     options |= GNUNET_MESH_OPTION_NOBUFFER;
441   if (ch->reliable)
442     options |= GNUNET_MESH_OPTION_RELIABLE;
443
444   return options;
445 }
446
447
448 /**
449  * Notify the destination client that a new incoming channel was created.
450  *
451  * @param ch Channel that was created.
452  */
453 static void
454 send_client_create (struct MeshChannel *ch)
455 {
456   uint32_t opt;
457
458   if (NULL == ch->dest)
459     return;
460
461   opt = 0;
462   opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
463   opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
464   GML_send_channel_create (ch->dest, ch->lid_dest, ch->port, opt,
465                            GMT_get_destination (ch->t));
466
467 }
468
469
470 /**
471  * Send data to a client.
472  *
473  * If the client is ready, send directly, otherwise buffer while listening
474  * for a local ACK.
475  *
476  * @param ch Channel
477  * @param msg Message.
478  * @param fwd Is this a fwd (root->dest) message?
479  */
480 static void
481 send_client_data (struct MeshChannel *ch,
482                   const struct GNUNET_MESH_Data *msg,
483                   int fwd)
484 {
485   if (fwd)
486   {
487     if (ch->dest_rel->client_ready)
488       GML_send_data (ch->dest, msg, ch->lid_dest);
489     else
490       add_buffered_data (msg, ch->dest_rel);
491   }
492   else
493   {
494     if (ch->root_rel->client_ready)
495       GML_send_data (ch->root, msg, ch->lid_root);
496     else
497       add_buffered_data (msg, ch->root_rel);
498   }
499 }
500
501
502 /**
503  * Send a buffered message to the client, for in order delivery or
504  * as result of client ACK.
505  *
506  * @param ch Channel on which to empty the message buffer.
507  * @param c Client to send to.
508  * @param fwd Is this to send FWD data?.
509  */
510 static void
511 send_client_buffered_data (struct MeshChannel *ch,
512                            struct MeshClient *c,
513                            int fwd)
514 {
515   struct MeshReliableMessage *copy;
516   struct MeshChannelReliability *rel;
517
518   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
519   rel = fwd ? ch->dest_rel : ch->root_rel;
520   if (GNUNET_NO == rel->client_ready)
521   {
522     LOG (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
523     return;
524   }
525
526   copy = rel->head_recv;
527   /* We never buffer channel management messages */
528   if (NULL != copy)
529   {
530     if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
531     {
532       struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];
533
534       LOG (GNUNET_ERROR_TYPE_DEBUG,
535            " have %u! now expecting %u\n",
536            copy->mid, rel->mid_recv + 1);
537       send_client_data (ch, msg, fwd);
538       rel->n_recv--;
539       rel->mid_recv++;
540       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
541       LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE RECV %p\n", copy);
542       GNUNET_free (copy);
543     }
544     else
545     {
546       LOG (GNUNET_ERROR_TYPE_DEBUG,
547            " reliable && don't have %u, next is %u\n",
548            rel->mid_recv,
549            copy->mid);
550       return;
551     }
552   }
553   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
554 }
555
556
557 /**
558  * Allow a client to send more data.
559  *
560  * In case the client was already allowed to send data, do nothing.
561  *
562  * @param ch Channel.
563  * @param fwd Is this a FWD ACK? (FWD ACKs are sent to root)
564  */
565 static void
566 send_client_ack (struct MeshChannel *ch, int fwd)
567 {
568   struct MeshChannelReliability *rel = fwd ? ch->root_rel : ch->dest_rel;
569
570   LOG (GNUNET_ERROR_TYPE_DEBUG,
571        "  sending %s ack to client on channel %s\n",
572        GM_f2s (fwd), GMCH_2s (ch));
573
574   if (NULL == rel)
575   {
576     GNUNET_break (0);
577     return;
578   }
579
580   if (GNUNET_YES == rel->client_allowed)
581   {
582     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already allowed\n");
583     return;
584   }
585   rel->client_allowed = GNUNET_YES;
586
587   GML_send_ack (fwd ? ch->root : ch->dest, fwd ? ch->lid_root : ch->lid_dest);
588 }
589
590
591 /**
592  * Notify the root that the destination rejected the channel.
593  *
594  * @param ch Rejected channel.
595  */
596 static void
597 send_client_nack (struct MeshChannel *ch)
598 {
599   if (NULL == ch->root)
600   {
601     GNUNET_break (0);
602     return;
603   }
604   GML_send_nack (ch->root, ch->lid_root);
605 }
606
607
608 /**
609  * We haven't received an ACK after a certain time: restransmit the message.
610  *
611  * @param cls Closure (MeshChannelReliability with the message to restransmit)
612  * @param tc TaskContext.
613  */
614 static void
615 channel_retransmit_message (void *cls,
616                             const struct GNUNET_SCHEDULER_TaskContext *tc)
617 {
618   struct MeshChannelReliability *rel = cls;
619   struct MeshReliableMessage *copy;
620   struct MeshChannel *ch;
621   struct GNUNET_MESH_Data *payload;
622   int fwd;
623
624   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
625   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
626     return;
627
628   ch = rel->ch;
629   copy = rel->head_sent;
630   if (NULL == copy)
631   {
632     GNUNET_break (0);
633     return;
634   }
635
636   payload = (struct GNUNET_MESH_Data *) &copy[1];
637   fwd = (rel == ch->root_rel);
638
639   /* Message not found in the queue that we are going to use. */
640   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
641
642   GMCH_send_prebuilt_message (&payload->header, ch, fwd, copy);
643   GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
644 }
645
646
647 /**
648  * We haven't received an Channel ACK after a certain time: resend the CREATE.
649  *
650  * @param cls Closure (MeshChannelReliability of the channel to recreate)
651  * @param tc TaskContext.
652  */
653 static void
654 channel_recreate (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
655 {
656   struct MeshChannelReliability *rel = cls;
657
658   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
659   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
660     return;
661
662   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RE-CREATE\n");
663   GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
664
665   if (rel == rel->ch->root_rel)
666   {
667     send_create (rel->ch);
668   }
669   else
670   {
671
672   }
673
674 }
675
676
677 /**
678  * Message has been sent: start retransmission timer.
679  *
680  * @param cls Closure (queue structure).
681  * @param t Tunnel.
682  * @param q Queue handler (no longer valid).
683  * @param type Type of message.
684  * @param size Size of the message.
685  */
686 static void
687 ch_message_sent (void *cls,
688                  struct MeshTunnel3 *t,
689                  struct MeshTunnel3Queue *q,
690                  uint16_t type, size_t size)
691 {
692   struct MeshChannelQueue *ch_q = cls;
693   struct MeshReliableMessage *copy = ch_q->copy;
694   struct MeshChannelReliability *rel;
695
696   switch (ch_q->type)
697   {
698     case GNUNET_MESSAGE_TYPE_MESH_DATA:
699       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SENT %u %s (c: %p, q: %p)\n",
700            copy->mid, GM_m2s (type), copy, copy->q);
701       GNUNET_assert (ch_q == copy->q);
702       copy->timestamp = GNUNET_TIME_absolute_get ();
703       rel = copy->rel;
704       if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
705       {
706         if (0 != rel->expected_delay.rel_value_us)
707         {
708           rel->retry_timer =
709           GNUNET_TIME_relative_multiply (rel->expected_delay,
710                                          MESH_RETRANSMIT_MARGIN);
711         }
712         else
713         {
714           rel->retry_timer = MESH_RETRANSMIT_TIME;
715         }
716         rel->retry_task =
717             GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
718                                           &channel_retransmit_message, rel);
719       }
720       copy->q = NULL;
721       break;
722
723
724     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
725       rel = ch_q->rel;
726       GNUNET_assert (rel->uniq == ch_q);
727       rel->uniq = NULL;
728       break;
729
730
731     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
732       rel = ch_q->rel;
733       GNUNET_assert (rel->uniq == ch_q);
734       if (MESH_CHANNEL_READY != rel->ch->state)
735       {
736         struct GNUNET_TIME_Relative delay;
737
738         GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == rel->retry_task);
739         rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
740         rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
741                                                         &channel_recreate, rel);
742       }
743       rel->uniq = NULL;
744       break;
745
746
747     default:
748       GNUNET_break (0);
749       GNUNET_free (ch_q);
750       return;
751   }
752
753   GNUNET_free (ch_q);
754 }
755
756
757 /**
758  * send a channel create message.
759  *
760  * @param ch Channel for which to send.
761  */
762 static void
763 send_create (struct MeshChannel *ch)
764 {
765   struct GNUNET_MESH_ChannelCreate msgcc;
766   struct MeshChannelQueue *q;
767
768   msgcc.header.size = htons (sizeof (msgcc));
769   msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
770   msgcc.chid = htonl (ch->gid);
771   msgcc.port = htonl (ch->port);
772   msgcc.opt = htonl (channel_get_options (ch));
773
774   q = GNUNET_new (struct MeshChannelQueue);
775   q->rel = ch->root_rel;
776
777   /* FIXME cancel on confirm */
778   q->q = GMT_send_prebuilt_message (&msgcc.header, ch->t, ch,
779                                     GNUNET_YES, GNUNET_YES,
780                                     ch_message_sent, q);
781   q->rel->uniq = q;
782 }
783
784
785 /**
786  * Notify a client that the channel is no longer valid.
787  *
788  * @param ch Channel that is destroyed.
789  * @param local_only Should we avoid sending it to other peers?
790  */
791 static void
792 send_destroy (struct MeshChannel *ch, int local_only)
793 {
794   struct GNUNET_MESH_ChannelManage msg;
795
796   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY);
797   msg.header.size = htons (sizeof (msg));
798   msg.chid = htonl (ch->gid);
799
800   /* If root is not NULL, notify.
801    * If it's NULL, check lid_root. When a local destroy comes in, root
802    * is set to NULL but lid_root is left untouched. In this case, do nothing,
803    * the client is the one who reuqested the channel to be destroyed.
804    */
805   if (NULL != ch->root)
806     GML_send_channel_destroy (ch->root, ch->lid_root);
807   else if (0 == ch->lid_root && GNUNET_NO == local_only)
808     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO, NULL);
809
810   if (NULL != ch->dest)
811     GML_send_channel_destroy (ch->dest, ch->lid_dest);
812   else if (0 == ch->lid_dest && GNUNET_NO == local_only)
813     GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_YES, NULL);
814 }
815
816
817 /**
818  * Destroy all reliable messages queued for a channel,
819  * during a channel destruction.
820  * Frees the reliability structure itself.
821  *
822  * @param rel Reliability data for a channel.
823  */
824 static void
825 channel_rel_free_all (struct MeshChannelReliability *rel)
826 {
827   struct MeshReliableMessage *copy;
828   struct MeshReliableMessage *next;
829
830   if (NULL == rel)
831     return;
832
833   for (copy = rel->head_recv; NULL != copy; copy = next)
834   {
835     next = copy->next;
836     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
837     LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE BATCH RECV %p\n", copy);
838     GNUNET_free (copy);
839   }
840   for (copy = rel->head_sent; NULL != copy; copy = next)
841   {
842     next = copy->next;
843     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
844     LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE BATCH %p\n", copy);
845     GNUNET_free (copy);
846   }
847   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
848   {
849     GNUNET_SCHEDULER_cancel (rel->retry_task);
850   }
851   if (NULL != rel->uniq)
852     GMT_cancel (rel->uniq->q);
853   GNUNET_free (rel);
854 }
855
856
857 /**
858  * Mark future messages as ACK'd.
859  *
860  * @param rel Reliability data.
861  * @param msg DataACK message with a bitfield of future ACK'd messages.
862  */
863 static void
864 channel_rel_free_sent (struct MeshChannelReliability *rel,
865                        const struct GNUNET_MESH_DataACK *msg)
866 {
867   struct MeshReliableMessage *copy;
868   struct MeshReliableMessage *next;
869   uint64_t bitfield;
870   uint64_t mask;
871   uint32_t mid;
872   uint32_t target;
873   unsigned int i;
874
875   bitfield = msg->futures;
876   mid = ntohl (msg->mid);
877   LOG (GNUNET_ERROR_TYPE_DEBUG,
878               "!!! free_sent_reliable %u %llX\n",
879               mid, bitfield);
880   LOG (GNUNET_ERROR_TYPE_DEBUG,
881               " rel %p, head %p\n",
882               rel, rel->head_sent);
883   for (i = 0, copy = rel->head_sent;
884        i < 64 && NULL != copy && 0 != bitfield;
885        i++)
886   {
887     LOG (GNUNET_ERROR_TYPE_DEBUG,
888                 " trying bit %u (mid %u)\n",
889                 i, mid + i + 1);
890     mask = 0x1LL << i;
891     if (0 == (bitfield & mask))
892      continue;
893
894     LOG (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
895     /* Bit was set, clear the bit from the bitfield */
896     bitfield &= ~mask;
897
898     /* The i-th bit was set. Do we have that copy? */
899     /* Skip copies with mid < target */
900     target = mid + i + 1;
901     LOG (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
902     while (NULL != copy && GM_is_pid_bigger (target, copy->mid))
903      copy = copy->next;
904
905     /* Did we run out of copies? (previously freed, it's ok) */
906     if (NULL == copy)
907     {
908      LOG (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
909      return;
910     }
911
912     /* Did we overshoot the target? (previously freed, it's ok) */
913     if (GM_is_pid_bigger (copy->mid, target))
914     {
915      LOG (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
916      continue;
917     }
918
919     /* Now copy->mid == target, free it */
920     next = copy->next;
921     rel_message_free (copy, GNUNET_YES);
922     copy = next;
923   }
924   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
925 }
926
927
928 /**
929  * Destroy a reliable message after it has been acknowledged, either by
930  * direct mid ACK or bitfield. Updates the appropriate data structures and
931  * timers and frees all memory.
932  *
933  * @param copy Message that is no longer needed: remote peer got it.
934  * @param update_time Is the timing information relevant?
935  *                    If this message is ACK in a batch the timing information
936  *                    is skewed by the retransmission, count only for the
937  *                    retransmitted message.
938  */
939 static void
940 rel_message_free (struct MeshReliableMessage *copy, int update_time)
941 {
942   struct MeshChannelReliability *rel;
943   struct GNUNET_TIME_Relative time;
944
945   rel = copy->rel;
946   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
947   if (update_time)
948   {
949     time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
950     if (0 == rel->expected_delay.rel_value_us)
951       rel->expected_delay = time;
952     else
953     {
954       rel->expected_delay.rel_value_us *= 7;
955       rel->expected_delay.rel_value_us += time.rel_value_us;
956       rel->expected_delay.rel_value_us /= 8;
957     }
958     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
959                 GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
960     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
961                 GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
962                                                         GNUNET_NO));
963     rel->retry_timer = rel->expected_delay;
964   }
965   else
966   {
967     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! batch free, ignoring timing\n");
968   }
969   rel->ch->pending_messages--;
970   if (GNUNET_NO != rel->ch->destroy && 0 == rel->ch->pending_messages)
971   {
972     struct MeshTunnel3 *t = rel->ch->t;
973     GMCH_destroy (rel->ch);
974     GMT_destroy_if_empty (t);
975   }
976   if (NULL != copy->q)
977   {
978     GMT_cancel (copy->q->q);
979   }
980   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
981   LOG (GNUNET_ERROR_TYPE_DEBUG, " COPYFREE %p\n", copy);
982   GNUNET_free (copy);
983 }
984
985
986 /**
987  * Confirm we got a channel create.
988  *
989  * @param ch The channel to confirm.
990  * @param fwd Should we send a FWD ACK? (going dest->root)
991  */
992 static void
993 channel_send_ack (struct MeshChannel *ch, int fwd)
994 {
995   struct GNUNET_MESH_ChannelManage msg;
996
997   msg.header.size = htons (sizeof (msg));
998   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
999   LOG (GNUNET_ERROR_TYPE_DEBUG,
1000               "  sending channel %s ack for channel %s\n",
1001               GM_f2s (fwd), GMCH_2s (ch));
1002
1003   msg.chid = htonl (ch->gid);
1004   GMCH_send_prebuilt_message (&msg.header, ch, !fwd, NULL);
1005 }
1006
1007
1008 /**
1009  * Notify that a channel create didn't succeed.
1010  *
1011  * @param ch The channel to reject.
1012  */
1013 static void
1014 channel_send_nack (struct MeshChannel *ch)
1015 {
1016   struct GNUNET_MESH_ChannelManage msg;
1017
1018   msg.header.size = htons (sizeof (msg));
1019   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK);
1020   LOG (GNUNET_ERROR_TYPE_DEBUG,
1021        "  sending channel NACK for channel %s\n",
1022        GMCH_2s (ch));
1023
1024   msg.chid = htonl (ch->gid);
1025   GMCH_send_prebuilt_message (&msg.header, ch, GNUNET_NO, NULL);
1026 }
1027
1028
1029 /**
1030  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
1031  *
1032  * @param ch Channel to mark as ready.
1033  * @param fwd Was the ACK message a FWD ACK? (dest->root, SYNACK)
1034  */
1035 static void
1036 channel_confirm (struct MeshChannel *ch, int fwd)
1037 {
1038   struct MeshChannelReliability *rel;
1039
1040   LOG (GNUNET_ERROR_TYPE_DEBUG,
1041               "  channel confirm %s %s:%X\n",
1042               GM_f2s (fwd), GMT_2s (ch->t), ch->gid);
1043   ch->state = MESH_CHANNEL_READY;
1044
1045   rel = fwd ? ch->root_rel : ch->dest_rel;
1046   rel->client_ready = GNUNET_YES;
1047   rel->expected_delay = rel->retry_timer;
1048   send_client_ack (ch, fwd);
1049
1050   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
1051   {
1052     GNUNET_SCHEDULER_cancel (rel->retry_task);
1053     rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
1054   }
1055   else if (NULL != rel->uniq)
1056   {
1057     GMT_cancel (rel->uniq->q);
1058     /* ch_sent_message will free and NULL uniq */
1059   }
1060   else
1061   {
1062     /* We SHOULD have been trying to retransmit this! */
1063     GNUNET_break (0);
1064   }
1065
1066   /* In case of a FWD ACK (SYNACK) send a BCK ACK (ACK). */
1067   if (fwd)
1068     channel_send_ack (ch, !fwd);
1069 }
1070
1071
1072 /**
1073  * Save a copy to retransmit in case it gets lost.
1074  *
1075  * Initializes all needed callbacks and timers.
1076  *
1077  * @param ch Channel this message goes on.
1078  * @param msg Message to copy.
1079  * @param fwd Is this fwd traffic?
1080  */
1081 static struct MeshReliableMessage *
1082 channel_save_copy (struct MeshChannel *ch,
1083                    const struct GNUNET_MessageHeader *msg,
1084                    int fwd)
1085 {
1086   struct MeshChannelReliability *rel;
1087   struct MeshReliableMessage *copy;
1088   uint32_t mid;
1089   uint16_t type;
1090   uint16_t size;
1091
1092   rel = fwd ? ch->root_rel : ch->dest_rel;
1093   mid = rel->mid_send - 1;
1094   type = ntohs (msg->type);
1095   size = ntohs (msg->size);
1096
1097   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u %s\n", mid, GM_m2s (type));
1098   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
1099   LOG (GNUNET_ERROR_TYPE_DEBUG, "  at %p\n", copy);
1100   copy->mid = mid;
1101   copy->rel = rel;
1102   copy->type = type;
1103   memcpy (&copy[1], msg, size);
1104   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
1105   ch->pending_messages++;
1106
1107   return copy;
1108 }
1109
1110
1111 /**
1112  * Create a new channel.
1113  *
1114  * @param t Tunnel this channel is in.
1115  * @param owner Client that owns the channel, NULL for foreign channels.
1116  * @param lid_root Local ID for root client.
1117  *
1118  * @return A new initialized channel. NULL on error.
1119  */
1120 static struct MeshChannel *
1121 channel_new (struct MeshTunnel3 *t,
1122              struct MeshClient *owner,
1123              MESH_ChannelNumber lid_root)
1124 {
1125   struct MeshChannel *ch;
1126
1127   ch = GNUNET_new (struct MeshChannel);
1128   ch->root = owner;
1129   ch->lid_root = lid_root;
1130   ch->t = t;
1131
1132   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
1133
1134   if (NULL != owner)
1135   {
1136     ch->gid = GMT_get_next_chid (t);
1137     GML_channel_add (owner, lid_root, ch);
1138   }
1139   GMT_add_channel (t, ch);
1140
1141   return ch;
1142 }
1143
1144
1145 /**
1146  * Test if the channel is loopback: both root and dest are on the local peer.
1147  *
1148  * @param ch Channel to test.
1149  *
1150  * @return #GNUNET_YES if channel is loopback, #NGUNET_NO otherwise.
1151  */
1152 static int
1153 is_loopback (const struct MeshChannel *ch)
1154 {
1155   if (NULL != ch->t)
1156     return GMT_is_loopback (ch->t);
1157
1158   return (NULL != ch->root && NULL != ch->dest);
1159 }
1160
1161
1162 /**
1163  * Handle a loopback message: call the appropriate handler for the message type.
1164  *
1165  * @param ch Channel this message is on.
1166  * @param msgh Message header.
1167  * @param fwd Is this FWD traffic?
1168  */
1169 void
1170 handle_loopback (struct MeshChannel *ch,
1171                  const struct GNUNET_MessageHeader *msgh,
1172                  int fwd)
1173 {
1174   uint16_t type;
1175
1176   type = ntohs (msgh->type);
1177   LOG (GNUNET_ERROR_TYPE_DEBUG,
1178        "Loopback %s %s message!\n",
1179        GM_f2s (fwd), GM_m2s (type));
1180
1181   switch (type)
1182   {
1183     case GNUNET_MESSAGE_TYPE_MESH_DATA:
1184       /* Don't send hop ACK, wait for client to ACK */
1185       GMCH_handle_data (ch, (struct GNUNET_MESH_Data *) msgh, fwd);
1186       break;
1187
1188     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
1189       GMCH_handle_data_ack (ch, (struct GNUNET_MESH_DataACK *) msgh, fwd);
1190       break;
1191
1192     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
1193       GMCH_handle_create (ch->t,
1194                           (struct GNUNET_MESH_ChannelCreate *) msgh);
1195       break;
1196
1197     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
1198       GMCH_handle_ack (ch,
1199                        (struct GNUNET_MESH_ChannelManage *) msgh,
1200                        fwd);
1201       break;
1202
1203     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_NACK:
1204       GMCH_handle_nack (ch);
1205       break;
1206
1207     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
1208       GMCH_handle_destroy (ch,
1209                            (struct GNUNET_MESH_ChannelManage *) msgh,
1210                            fwd);
1211       break;
1212
1213     default:
1214       GNUNET_break_op (0);
1215       LOG (GNUNET_ERROR_TYPE_DEBUG,
1216            "end-to-end message not known (%u)\n",
1217            ntohs (msgh->type));
1218   }
1219 }
1220
1221
1222
1223 /******************************************************************************/
1224 /********************************    API    ***********************************/
1225 /******************************************************************************/
1226
1227 /**
1228  * Destroy a channel and free all resources.
1229  *
1230  * @param ch Channel to destroy.
1231  */
1232 void
1233 GMCH_destroy (struct MeshChannel *ch)
1234 {
1235   struct MeshClient *c;
1236
1237   if (NULL == ch)
1238     return;
1239
1240   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
1241               GMT_2s (ch->t), ch->gid);
1242   GMCH_debug (ch);
1243
1244   c = ch->root;
1245   if (NULL != c)
1246   {
1247     GML_channel_remove (c, ch->lid_root, ch);
1248   }
1249
1250   c = ch->dest;
1251   if (NULL != c)
1252   {
1253     GML_channel_remove (c, ch->lid_dest, ch);
1254   }
1255
1256   channel_rel_free_all (ch->root_rel);
1257   channel_rel_free_all (ch->dest_rel);
1258
1259   GMT_remove_channel (ch->t, ch);
1260   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
1261
1262   GNUNET_free (ch);
1263 }
1264
1265
1266 /**
1267  * Get channel ID.
1268  *
1269  * @param ch Channel.
1270  *
1271  * @return ID
1272  */
1273 MESH_ChannelNumber
1274 GMCH_get_id (const struct MeshChannel *ch)
1275 {
1276   return ch->gid;
1277 }
1278
1279
1280 /**
1281  * Get the channel tunnel.
1282  *
1283  * @param ch Channel to get the tunnel from.
1284  *
1285  * @return tunnel of the channel.
1286  */
1287 struct MeshTunnel3 *
1288 GMCH_get_tunnel (const struct MeshChannel *ch)
1289 {
1290   return ch->t;
1291 }
1292
1293
1294 /**
1295  * Get free buffer space towards the client on a specific channel.
1296  *
1297  * @param ch Channel.
1298  * @param fwd Is query about FWD traffic?
1299  *
1300  * @return Free buffer space [0 - 64]
1301  */
1302 unsigned int
1303 GMCH_get_buffer (struct MeshChannel *ch, int fwd)
1304 {
1305   struct MeshChannelReliability *rel;
1306
1307   rel = fwd ? ch->dest_rel : ch->root_rel;
1308
1309   /* If rel is NULL it means that the end is not yet created,
1310    * most probably is a loopback channel at the point of sending
1311    * the ChannelCreate to itself.
1312    */
1313   if (NULL == rel)
1314     return 64;
1315
1316   return (64 - rel->n_recv);
1317 }
1318
1319
1320 /**
1321  * Get flow control status of end point: is client allow to send?
1322  *
1323  * @param ch Channel.
1324  * @param fwd Is query about FWD traffic? (Request root status).
1325  *
1326  * @return #GNUNET_YES if client is allowed to send us data.
1327  */
1328 int
1329 GMCH_get_allowed (struct MeshChannel *ch, int fwd)
1330 {
1331   struct MeshChannelReliability *rel;
1332
1333   rel = fwd ? ch->root_rel : ch->dest_rel;
1334
1335   if (NULL == rel)
1336   {
1337     /* Probably shutting down: root/dest NULL'ed to mark disconnection */
1338     GNUNET_break (GNUNET_NO != ch->destroy);
1339     return 0;
1340   }
1341
1342   return rel->client_allowed;
1343 }
1344
1345
1346 /**
1347  * Is the root client for this channel on this peer?
1348  *
1349  * @param ch Channel.
1350  * @param fwd Is this for fwd traffic?
1351  *
1352  * @return #GNUNET_YES in case it is.
1353  */
1354 int
1355 GMCH_is_origin (struct MeshChannel *ch, int fwd)
1356 {
1357   struct MeshClient *c;
1358
1359   c = fwd ? ch->root : ch->dest;
1360   return NULL != c;
1361 }
1362
1363
1364 /**
1365  * Is the destination client for this channel on this peer?
1366  *
1367  * @param ch Channel.
1368  * @param fwd Is this for fwd traffic?
1369  *
1370  * @return #GNUNET_YES in case it is.
1371  */
1372 int
1373 GMCH_is_terminal (struct MeshChannel *ch, int fwd)
1374 {
1375   struct MeshClient *c;
1376
1377   c = fwd ? ch->dest : ch->root;
1378   return NULL != c;
1379 }
1380
1381
1382 /**
1383  * Send an end-to-end ACK message for the most recent in-sequence payload.
1384  *
1385  * If channel is not reliable, do nothing.
1386  *
1387  * @param ch Channel this is about.
1388  * @param fwd Is for FWD traffic? (ACK dest->owner)
1389  */
1390 void
1391 GMCH_send_data_ack (struct MeshChannel *ch, int fwd)
1392 {
1393   struct GNUNET_MESH_DataACK msg;
1394   struct MeshChannelReliability *rel;
1395   struct MeshReliableMessage *copy;
1396   unsigned int delta;
1397   uint64_t mask;
1398   uint32_t ack;
1399
1400   if (GNUNET_NO == ch->reliable)
1401   {
1402     return;
1403   }
1404   rel = fwd ? ch->dest_rel : ch->root_rel;
1405   ack = rel->mid_recv - 1;
1406   LOG (GNUNET_ERROR_TYPE_DEBUG,
1407               " !! Send DATA_ACK for %u\n",
1408               ack);
1409
1410   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA_ACK);
1411   msg.header.size = htons (sizeof (msg));
1412   msg.chid = htonl (ch->gid);
1413   msg.futures = 0;
1414   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
1415   {
1416     if (copy->type != GNUNET_MESSAGE_TYPE_MESH_DATA)
1417     {
1418       LOG (GNUNET_ERROR_TYPE_DEBUG,
1419            "!!  Type %s, expected DATA\n",
1420            GM_m2s (copy->type));
1421       continue;
1422     }
1423     if (copy->mid == ack + 1)
1424     {
1425       ack++;
1426       continue;
1427     }
1428     delta = copy->mid - (ack + 1);
1429     if (63 < delta)
1430       break;
1431     mask = 0x1LL << delta;
1432     msg.futures |= mask;
1433     LOG (GNUNET_ERROR_TYPE_DEBUG,
1434          " !! setting bit for %u (delta %u) (%llX) -> %llX\n",
1435          copy->mid, delta, mask, msg.futures);
1436   }
1437   msg.mid = htonl (ack);
1438   LOG (GNUNET_ERROR_TYPE_DEBUG,
1439        "!!! ACK for %u, futures %llX\n",
1440        ack, msg.futures);
1441
1442   GMCH_send_prebuilt_message (&msg.header, ch, !fwd, NULL);
1443   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1444 }
1445
1446
1447 /**
1448  * Allow a client to send us more data, in case it was choked.
1449  *
1450  * @param ch Channel.
1451  * @param fwd Is this about FWD traffic? (Root client).
1452  */
1453 void
1454 GMCH_allow_client (struct MeshChannel *ch, int fwd)
1455 {
1456   struct MeshChannelReliability *rel;
1457   unsigned int buffer;
1458
1459   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH allow\n");
1460
1461   if (MESH_CHANNEL_READY != ch->state)
1462   {
1463     LOG (GNUNET_ERROR_TYPE_DEBUG, " channel not ready yet!\n");
1464     return;
1465   }
1466
1467   if (GNUNET_YES == ch->reliable)
1468   {
1469     rel = fwd ? ch->root_rel : ch->dest_rel;
1470     if (NULL == rel)
1471     {
1472       GNUNET_break (GNUNET_NO != ch->destroy);
1473       return;
1474     }
1475     if (NULL != rel->head_sent && 64 <= rel->mid_send - rel->head_sent->mid)
1476     {
1477       LOG (GNUNET_ERROR_TYPE_DEBUG, " too big MID gap! Wait for ACK.\n");
1478       return;
1479     }
1480   }
1481
1482   if (is_loopback (ch))
1483     buffer = GMCH_get_buffer (ch, fwd);
1484   else
1485     buffer = GMT_get_connections_buffer (ch->t);
1486
1487   if (0 == buffer)
1488   {
1489     LOG (GNUNET_ERROR_TYPE_DEBUG, " no buffer space.\n");
1490     return;
1491   }
1492
1493   LOG (GNUNET_ERROR_TYPE_DEBUG, " buffer space %u, allowing\n", buffer);
1494   send_client_ack (ch, fwd);
1495 }
1496
1497
1498 /**
1499  * Log channel info.
1500  *
1501  * @param ch Channel.
1502  */
1503 void
1504 GMCH_debug (struct MeshChannel *ch)
1505 {
1506   if (NULL == ch)
1507   {
1508     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
1509     return;
1510   }
1511   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X (%p)\n",
1512               GMT_2s (ch->t), ch->gid, ch);
1513   LOG (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
1514               ch->root, ch->root_rel);
1515   if (NULL != ch->root)
1516   {
1517     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->root));
1518     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1519                 ch->root_rel->client_ready ? "YES" : "NO");
1520     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_root);
1521   }
1522   LOG (GNUNET_ERROR_TYPE_DEBUG, "  dest %p/%p\n",
1523               ch->dest, ch->dest_rel);
1524   if (NULL != ch->dest)
1525   {
1526     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->dest));
1527     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1528                 ch->dest_rel->client_ready ? "YES" : "NO");
1529     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_dest);
1530   }
1531 }
1532
1533
1534 /**
1535  * Handle an ACK given by a client.
1536  *
1537  * Mark client as ready and send him any buffered data we could have for him.
1538  *
1539  * @param ch Channel.
1540  * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by dest and go BCK)
1541  */
1542 void
1543 GMCH_handle_local_ack (struct MeshChannel *ch, int fwd)
1544 {
1545   struct MeshChannelReliability *rel;
1546   struct MeshClient *c;
1547
1548   rel = fwd ? ch->dest_rel : ch->root_rel;
1549   c   = fwd ? ch->dest     : ch->root;
1550
1551   rel->client_ready = GNUNET_YES;
1552   send_client_buffered_data (ch, c, fwd);
1553   if (is_loopback (ch))
1554   {
1555     unsigned int buffer;
1556
1557     buffer = GMCH_get_buffer (ch, fwd);
1558     if (0 < buffer)
1559       GMCH_allow_client (ch, fwd);
1560
1561     return;
1562   }
1563   GMT_send_connection_acks (ch->t);
1564 }
1565
1566
1567 /**
1568  * Handle data given by a client.
1569  *
1570  * Check whether the client is allowed to send in this tunnel, save if channel
1571  * is reliable and send an ACK to the client if there is still buffer space
1572  * in the tunnel.
1573  *
1574  * @param ch Channel.
1575  * @param c Client which sent the data.
1576  * @param message Message.
1577  * @param fwd Is this a FWD data?
1578  *
1579  * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
1580  */
1581 int
1582 GMCH_handle_local_data (struct MeshChannel *ch,
1583                         struct MeshClient *c,
1584                         struct GNUNET_MessageHeader *message,
1585                         int fwd)
1586 {
1587   struct MeshChannelReliability *rel;
1588   struct GNUNET_MESH_Data *payload;
1589   size_t size = ntohs (message->size);
1590   uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
1591   unsigned char cbuf[p2p_size];
1592
1593   /* Is the client in the channel? */
1594   if ( !( (fwd &&
1595            ch->root == c)
1596          ||
1597           (!fwd &&
1598            ch->dest == c) ) )
1599   {
1600     GNUNET_break_op (0);
1601     return GNUNET_SYSERR;
1602   }
1603
1604   rel = fwd ? ch->root_rel : ch->dest_rel;
1605
1606   if (GNUNET_NO == rel->client_allowed)
1607   {
1608     GNUNET_break_op (0);
1609     return GNUNET_SYSERR;
1610   }
1611
1612   rel->client_allowed = GNUNET_NO;
1613
1614   /* Ok, everything is correct, send the message. */
1615   payload = (struct GNUNET_MESH_Data *) cbuf;
1616   payload->mid = htonl (rel->mid_send);
1617   rel->mid_send++;
1618   memcpy (&payload[1], message, size);
1619   payload->header.size = htons (p2p_size);
1620   payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
1621   payload->chid = htonl (ch->gid);
1622   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1623   GMCH_send_prebuilt_message (&payload->header, ch, fwd, NULL);
1624
1625   if (is_loopback (ch))
1626   {
1627     if (GMCH_get_buffer (ch, fwd) > 0)
1628       send_client_ack (ch, fwd);
1629
1630     return GNUNET_OK;
1631   }
1632
1633   if (GMT_get_connections_buffer (ch->t) > 0)
1634   {
1635     send_client_ack (ch, fwd);
1636   }
1637
1638   return GNUNET_OK;
1639 }
1640
1641
1642 /**
1643  * Handle a channel destroy requested by a client.
1644  *
1645  * Destroy the channel and the tunnel in case this was the last channel.
1646  *
1647  * @param ch Channel.
1648  * @param c Client that requested the destruction (to avoid notifying him).
1649  * @param is_root Is the request coming from root?
1650  */
1651 void
1652 GMCH_handle_local_destroy (struct MeshChannel *ch,
1653                            struct MeshClient *c,
1654                            int is_root)
1655 {
1656   struct MeshTunnel3 *t;
1657
1658   ch->destroy = GNUNET_YES;
1659   /* Cleanup after the tunnel */
1660   if (GNUNET_NO == is_root && c == ch->dest)
1661   {
1662     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
1663     GML_client_delete_channel (c, ch, ch->lid_dest);
1664     ch->dest = NULL;
1665   }
1666   if (GNUNET_YES == is_root && c == ch->root)
1667   {
1668     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
1669     GML_client_delete_channel (c, ch, ch->lid_root);
1670     ch->root = NULL;
1671   }
1672
1673   t = ch->t;
1674   send_destroy (ch, GNUNET_NO);
1675   if (0 == ch->pending_messages)
1676   {
1677     GMCH_destroy (ch);
1678     GMT_destroy_if_empty (t);
1679   }
1680 }
1681
1682
1683 /**
1684  * Handle a channel create requested by a client.
1685  *
1686  * Create the channel and the tunnel in case this was the first0 channel.
1687  *
1688  * @param c Client that requested the creation (will be the root).
1689  * @param msg Create Channel message.
1690  *
1691  * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
1692  */
1693 int
1694 GMCH_handle_local_create (struct MeshClient *c,
1695                           struct GNUNET_MESH_ChannelMessage *msg)
1696 {
1697   struct MeshChannel *ch;
1698   struct MeshTunnel3 *t;
1699   struct MeshPeer *peer;
1700   MESH_ChannelNumber chid;
1701
1702   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
1703               GNUNET_i2s (&msg->peer), ntohl (msg->port));
1704   chid = ntohl (msg->channel_id);
1705
1706   /* Sanity check for duplicate channel IDs */
1707   if (NULL != GML_channel_get (c, chid))
1708   {
1709     GNUNET_break (0);
1710     return GNUNET_SYSERR;
1711   }
1712
1713   peer = GMP_get (&msg->peer);
1714   GMP_add_tunnel (peer);
1715   t = GMP_get_tunnel (peer);
1716
1717   if (GMP_get_short_id (peer) == myid)
1718   {
1719     GMT_change_cstate (t, MESH_TUNNEL3_READY);
1720   }
1721   else
1722   {
1723     GMP_connect (peer);
1724   }
1725
1726   /* Create channel */
1727   ch = channel_new (t, c, chid);
1728   if (NULL == ch)
1729   {
1730     GNUNET_break (0);
1731     return GNUNET_SYSERR;
1732   }
1733   ch->port = ntohl (msg->port);
1734   channel_set_options (ch, ntohl (msg->opt));
1735
1736   /* In unreliable channels, we'll use the DLL to buffer BCK data */
1737   ch->root_rel = GNUNET_new (struct MeshChannelReliability);
1738   ch->root_rel->ch = ch;
1739   ch->root_rel->retry_timer = GNUNET_TIME_UNIT_SECONDS;
1740   ch->root_rel->expected_delay.rel_value_us = 0;
1741
1742   LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s\n", GMCH_2s (ch));
1743
1744   send_create (ch);
1745
1746   return GNUNET_OK;
1747 }
1748
1749
1750 /**
1751  * Handler for mesh network payload traffic.
1752  *
1753  * @param ch Channel for the message.
1754  * @param msg Unencryted data message.
1755  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1756  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1757  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1758  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1759  */
1760 void
1761 GMCH_handle_data (struct MeshChannel *ch,
1762                   const struct GNUNET_MESH_Data *msg,
1763                   int fwd)
1764 {
1765   struct MeshChannelReliability *rel;
1766   struct MeshClient *c;
1767   uint32_t mid;
1768
1769   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1770   if (GNUNET_SYSERR == fwd)
1771   {
1772     if (is_loopback (ch))
1773     {
1774       /* It is a loopback channel after all... */
1775       GNUNET_break (0);
1776       return;
1777     }
1778     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
1779   }
1780
1781   /*  Initialize FWD/BCK data */
1782   c   = fwd ? ch->dest     : ch->root;
1783   rel = fwd ? ch->dest_rel : ch->root_rel;
1784
1785   if (NULL == c)
1786   {
1787     GNUNET_break (0);
1788     return;
1789   }
1790
1791   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
1792
1793   mid = ntohl (msg->mid);
1794   LOG (GNUNET_ERROR_TYPE_DEBUG, "!! got mid %u\n", mid);
1795
1796   if (GNUNET_NO == ch->reliable ||
1797       ( !GM_is_pid_bigger (rel->mid_recv, mid) &&
1798         GM_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1799   {
1800     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
1801     if (GNUNET_YES == ch->reliable)
1802     {
1803       /* Is this the exact next expected messasge? */
1804       if (mid == rel->mid_recv)
1805       {
1806         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
1807         rel->mid_recv++;
1808         send_client_data (ch, msg, fwd);
1809       }
1810       else
1811       {
1812         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1813         add_buffered_data (msg, rel);
1814       }
1815     }
1816     else
1817     {
1818       /* Tunnel is unreliable: send to clients directly */
1819       /* FIXME: accept Out Of Order traffic */
1820       rel->mid_recv = mid + 1;
1821       send_client_data (ch, msg, fwd);
1822     }
1823   }
1824   else
1825   {
1826     GNUNET_break_op (GM_is_pid_bigger (rel->mid_recv, mid));
1827     LOG (GNUNET_ERROR_TYPE_DEBUG,
1828                 " !!! MID %u not expected (%u - %u), dropping!\n",
1829                 mid, rel->mid_recv, rel->mid_recv + 63);
1830   }
1831
1832   GMCH_send_data_ack (ch, fwd);
1833 }
1834
1835
1836 /**
1837  * Handler for mesh network traffic end-to-end ACKs.
1838  *
1839  * @param ch Channel on which we got this message.
1840  * @param msg Data message.
1841  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1842  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1843  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1844  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1845  */
1846 void
1847 GMCH_handle_data_ack (struct MeshChannel *ch,
1848                       const struct GNUNET_MESH_DataACK *msg,
1849                       int fwd)
1850 {
1851   struct MeshChannelReliability *rel;
1852   struct MeshReliableMessage *copy;
1853   struct MeshReliableMessage *next;
1854   uint32_t ack;
1855   int work;
1856
1857   /* If this is a remote (non-loopback) channel, find 'fwd'. */
1858   if (GNUNET_SYSERR == fwd)
1859   {
1860     if (is_loopback (ch))
1861     {
1862       /* It is a loopback channel after all... */
1863       GNUNET_break (0);
1864       return;
1865     }
1866     /* Inverted: if message came 'FWD' is a 'BCK ACK'. */
1867     fwd = (NULL != ch->dest) ? GNUNET_NO : GNUNET_YES;
1868   }
1869
1870   ack = ntohl (msg->mid);
1871   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
1872        (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
1873
1874   if (GNUNET_YES == fwd)
1875   {
1876     rel = ch->root_rel;
1877   }
1878   else
1879   {
1880     rel = ch->dest_rel;
1881   }
1882   if (NULL == rel)
1883   {
1884     GNUNET_break_op (0);
1885     return;
1886   }
1887
1888   /* Free ACK'd copies: no need to retransmit those anymore */
1889   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
1890   {
1891     if (GM_is_pid_bigger (copy->mid, ack))
1892     {
1893       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
1894       channel_rel_free_sent (rel, msg);
1895       break;
1896     }
1897     work = GNUNET_YES;
1898     LOG (GNUNET_ERROR_TYPE_DEBUG, " !!  id %u\n", copy->mid);
1899     next = copy->next;
1900     rel_message_free (copy, GNUNET_YES);
1901   }
1902
1903   /* ACK client if needed */
1904   GMCH_allow_client (ch, fwd);
1905
1906   /* If some message was free'd, update the retransmission delay */
1907   if (GNUNET_YES == work)
1908   {
1909     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
1910     {
1911       GNUNET_SCHEDULER_cancel (rel->retry_task);
1912       if (NULL != rel->head_sent && NULL == rel->head_sent->q)
1913       {
1914         struct GNUNET_TIME_Absolute new_target;
1915         struct GNUNET_TIME_Relative delay;
1916
1917         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
1918                                                MESH_RETRANSMIT_MARGIN);
1919         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
1920                                                delay);
1921         delay = GNUNET_TIME_absolute_get_remaining (new_target);
1922         rel->retry_task =
1923             GNUNET_SCHEDULER_add_delayed (delay,
1924                                           &channel_retransmit_message,
1925                                           rel);
1926       }
1927       else /* either no more traffic to ack or traffic has just been queued */
1928       {
1929         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
1930       }
1931     }
1932     else /* work was done but no task was pending? shouldn't happen! */
1933     {
1934       GNUNET_break (0);
1935     }
1936   }
1937 }
1938
1939
1940 /**
1941  * Handler for channel create messages.
1942  *
1943  * Does not have fwd parameter because it's always 'FWD': channel is incoming.
1944  *
1945  * @param t Tunnel this channel will be in.
1946  * @param msg Channel crate message.
1947  */
1948 struct MeshChannel *
1949 GMCH_handle_create (struct MeshTunnel3 *t,
1950                     const struct GNUNET_MESH_ChannelCreate *msg)
1951 {
1952   MESH_ChannelNumber chid;
1953   struct MeshChannel *ch;
1954   struct MeshClient *c;
1955
1956   chid = ntohl (msg->chid);
1957
1958   ch = GMT_get_channel (t, chid);
1959   if (NULL == ch)
1960   {
1961     /* Create channel */
1962     ch = channel_new (t, NULL, 0);
1963     ch->gid = chid;
1964   }
1965   channel_set_options (ch, ntohl (msg->opt));
1966
1967   /* Find a destination client */
1968   ch->port = ntohl (msg->port);
1969   LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", ch->port);
1970   c = GML_client_get_by_port (ch->port);
1971   if (NULL == c)
1972   {
1973     /* TODO send reject */
1974     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
1975     if (is_loopback (ch))
1976     {
1977       LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback: destroy on handler\n");
1978       channel_send_nack (ch);
1979     }
1980     else
1981     {
1982       LOG (GNUNET_ERROR_TYPE_DEBUG, "  not loopback: destroy now\n");
1983       channel_send_nack (ch);
1984       GMCH_destroy (ch);
1985     }
1986     return NULL;
1987   }
1988   else
1989   {
1990     LOG (GNUNET_ERROR_TYPE_DEBUG, "  client %p has port registered\n", c);
1991   }
1992
1993   add_destination (ch, c);
1994   if (GNUNET_YES == ch->reliable)
1995     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
1996   else
1997     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Not Reliable\n");
1998
1999   send_client_create (ch);
2000   channel_send_ack (ch, GNUNET_YES);
2001
2002   return ch;
2003 }
2004
2005
2006 /**
2007  * Handler for channel NACK messages.
2008  *
2009  * NACK messages always go dest -> root, no need for 'fwd' or 'msg' parameter.
2010  *
2011  * @param ch Channel.
2012  */
2013 void
2014 GMCH_handle_nack (struct MeshChannel *ch)
2015 {
2016   send_client_nack (ch);
2017   GMCH_destroy (ch);
2018 }
2019
2020
2021 /**
2022  * Handler for channel ack messages.
2023  *
2024  * @param ch Channel.
2025  * @param msg Message.
2026  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2027  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2028  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2029  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2030  */
2031 void
2032 GMCH_handle_ack (struct MeshChannel *ch,
2033                  const struct GNUNET_MESH_ChannelManage *msg,
2034                  int fwd)
2035 {
2036   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2037   if (GNUNET_SYSERR == fwd)
2038   {
2039     if (is_loopback (ch))
2040     {
2041       /* It is a loopback channel after all... */
2042       GNUNET_break (0);
2043       return;
2044     }
2045     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
2046   }
2047
2048   channel_confirm (ch, !fwd);
2049 }
2050
2051
2052 /**
2053  * Handler for channel destroy messages.
2054  *
2055  * @param ch Channel to be destroyed of.
2056  * @param msg Message.
2057  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
2058  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
2059  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
2060  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
2061  */
2062 void
2063 GMCH_handle_destroy (struct MeshChannel *ch,
2064                      const struct GNUNET_MESH_ChannelManage *msg,
2065                      int fwd)
2066 {
2067   struct MeshTunnel3 *t;
2068
2069   /* If this is a remote (non-loopback) channel, find 'fwd'. */
2070   if (GNUNET_SYSERR == fwd)
2071   {
2072     if (is_loopback (ch))
2073     {
2074       /* It is a loopback channel after all... */
2075       GNUNET_break (0);
2076       return;
2077     }
2078     fwd = (NULL != ch->dest) ? GNUNET_YES : GNUNET_NO;
2079   }
2080
2081   GMCH_debug (ch);
2082   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
2083   {
2084     /* Not for us (don't destroy twice a half-open loopback channel) */
2085     return;
2086   }
2087
2088   t = ch->t;
2089   send_destroy (ch, GNUNET_YES);
2090   GMCH_destroy (ch);
2091   GMT_destroy_if_empty (t);
2092 }
2093
2094
2095 /**
2096  * Sends an already built message on a channel.
2097  *
2098  * If the channel is on a loopback tunnel, notifies the appropriate destination
2099  * client locally.
2100  *
2101  * On a normal channel passes the message to the tunnel for encryption and
2102  * sending on a connection.
2103  *
2104  * This function DOES NOT save the message for retransmission.
2105  *
2106  * @param message Message to send. Function makes a copy of it.
2107  * @param ch Channel on which this message is transmitted.
2108  * @param fwd Is this a fwd message?
2109  * @param existing_copy This is a retransmission, don't save a copy.
2110  */
2111 void
2112 GMCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2113                             struct MeshChannel *ch, int fwd,
2114                             void *existing_copy)
2115 {
2116   uint16_t type;
2117
2118   type = ntohs (message->type);
2119   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH Send %s %s on channel %s\n",
2120        GM_f2s (fwd), GM_m2s (type),
2121        GMCH_2s (ch));
2122
2123   if (GMT_is_loopback (ch->t))
2124   {
2125     handle_loopback (ch, message, fwd);
2126     return;
2127   }
2128
2129   switch (type)
2130   {
2131     case GNUNET_MESSAGE_TYPE_MESH_DATA:
2132
2133       if (GNUNET_YES == ch->reliable)
2134       {
2135         struct MeshChannelQueue *q;
2136
2137         q = GNUNET_new (struct MeshChannelQueue);
2138         q->type = type;
2139         if (NULL == existing_copy)
2140           q->copy = channel_save_copy (ch, message, fwd);
2141         else
2142         {
2143           q->copy = (struct MeshReliableMessage *) existing_copy;
2144           if (NULL != q->copy->q)
2145           {
2146             /* Last retransmission was queued but not yet sent!
2147              * This retransmission was scheduled by a ch_message_sent which
2148              * followed a very fast RTT, so the tiny delay made the
2149              * retransmission function to execute before the previous
2150              * retransmitted message even had a chance to leave the peer.
2151              * Cancel this message and wait until the pending
2152              * retransmission leaves the peer and ch_message_sent starts
2153              * the timer for the next one.
2154              */
2155             GNUNET_free (q);
2156             return;
2157           }
2158           LOG (GNUNET_ERROR_TYPE_DEBUG,
2159                "  using existing copy: %p {r:%p q:%p t:%u}\n",
2160                existing_copy,
2161                q->copy->rel, q->copy->q, q->copy->type);
2162         }
2163         LOG (GNUNET_ERROR_TYPE_DEBUG, "  new q: %p\n", q);
2164         q->copy->q = q;
2165         q->q = GMT_send_prebuilt_message (message, ch->t, ch,
2166                                           fwd, NULL != existing_copy,
2167                                           &ch_message_sent, q);
2168         /* q itself is stored in copy */
2169       }
2170       else
2171       {
2172         GNUNET_break (NULL == GMT_send_prebuilt_message (message, ch->t, ch,
2173                                                          fwd, GNUNET_NO,
2174                                                          NULL, NULL));
2175       }
2176       break;
2177
2178     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
2179       {
2180         struct MeshChannelReliability *rel;
2181
2182         rel = fwd ? ch->root_rel : ch->dest_rel;
2183         if (NULL != rel->uniq)
2184         {
2185           GMT_cancel (rel->uniq->q);
2186           /* ch_message_sent is called, freeing ack_q */
2187         }
2188         rel->uniq = GNUNET_new (struct MeshChannelQueue);
2189         rel->uniq->type = type;
2190         rel->uniq->rel = rel;
2191         rel->uniq->q = GMT_send_prebuilt_message (message, ch->t, ch,
2192                                                    fwd, GNUNET_YES,
2193                                                    &ch_message_sent,
2194                                                   rel->uniq);
2195       }
2196       break;
2197     default:
2198       GNUNET_break (NULL == GMT_send_prebuilt_message (message, ch->t, ch,
2199                                                        fwd, GNUNET_YES,
2200                                                        NULL, NULL));
2201   }
2202 }
2203
2204
2205 /**
2206  * Get the static string for identification of the channel.
2207  *
2208  * @param ch Channel.
2209  *
2210  * @return Static string with the channel IDs.
2211  */
2212 const char *
2213 GMCH_2s (const struct MeshChannel *ch)
2214 {
2215   static char buf[64];
2216
2217   if (NULL == ch)
2218     return "(NULL Channel)";
2219
2220   sprintf (buf, "%s:%u gid:%X (%X / %X)",
2221            GMT_2s (ch->t), ch->port, ch->gid, ch->lid_root, ch->lid_dest);
2222
2223   return buf;
2224 }