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