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