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