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