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