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