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