b142ea054ed529838c7328ae55652a9cbf8088bb
[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_enc.h"
28 #include "mesh_protocol_enc.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 /**
65  * Info needed to retry a message in case it gets lost.
66  */
67 struct MeshReliableMessage
68 {
69     /**
70      * Double linked list, FIFO style
71      */
72   struct MeshReliableMessage    *next;
73   struct MeshReliableMessage    *prev;
74
75     /**
76      * Type of message (payload, channel management).
77      */
78   int16_t type;
79
80     /**
81      * Tunnel Reliability queue this message is in.
82      */
83   struct MeshChannelReliability  *rel;
84
85     /**
86      * ID of the message (ACK needed to free)
87      */
88   uint32_t                      mid;
89
90     /**
91      * When was this message issued (to calculate ACK delay)
92      */
93   struct GNUNET_TIME_Absolute   timestamp;
94
95   /* struct GNUNET_MESH_Data with payload */
96 };
97
98
99 /**
100  * Info about the traffic state for a client in a channel.
101  */
102 struct MeshChannelReliability
103 {
104     /**
105      * Channel this is about.
106      */
107   struct MeshChannel *ch;
108
109     /**
110      * DLL of messages sent and not yet ACK'd.
111      */
112   struct MeshReliableMessage        *head_sent;
113   struct MeshReliableMessage        *tail_sent;
114
115     /**
116      * Messages pending to send.
117      */
118   unsigned int                      n_sent;
119
120     /**
121      * DLL of messages received out of order.
122      */
123   struct MeshReliableMessage        *head_recv;
124   struct MeshReliableMessage        *tail_recv;
125
126     /**
127      * Messages received.
128      */
129   unsigned int                      n_recv;
130
131     /**
132      * Next MID to use for outgoing traffic.
133      */
134   uint32_t                          mid_send;
135
136     /**
137      * Next MID expected for incoming traffic.
138      */
139   uint32_t                          mid_recv;
140
141     /**
142      * Can we send data to the client?
143      */
144   int                               client_ready;
145
146     /**
147      * Task to resend/poll in case no ACK is received.
148      */
149   GNUNET_SCHEDULER_TaskIdentifier   retry_task;
150
151     /**
152      * Counter for exponential backoff.
153      */
154   struct GNUNET_TIME_Relative       retry_timer;
155
156     /**
157      * How long does it usually take to get an ACK.
158      */
159   struct GNUNET_TIME_Relative       expected_delay;
160 };
161
162
163 /**
164  * Struct containing all information regarding a channel to a remote client.
165  */
166 struct MeshChannel
167 {
168     /**
169      * Tunnel this channel is in.
170      */
171   struct MeshTunnel3 *t;
172
173     /**
174      * Destination port of the channel.
175      */
176   uint32_t port;
177
178     /**
179      * Global channel number ( < GNUNET_MESH_LOCAL_CHANNEL_ID_CLI)
180      */
181   MESH_ChannelNumber gid;
182
183     /**
184      * Local tunnel number for root (owner) client.
185      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_CLI or 0 )
186      */
187   MESH_ChannelNumber lid_root;
188
189     /**
190      * Local tunnel number for local destination clients (incoming number)
191      * ( >= GNUNET_MESH_LOCAL_CHANNEL_ID_SERV or 0).
192      */
193   MESH_ChannelNumber lid_dest;
194
195     /**
196      * Channel state.
197      */
198   enum MeshChannelState state;
199
200     /**
201      * Is the tunnel bufferless (minimum latency)?
202      */
203   int nobuffer;
204
205     /**
206      * Is the tunnel reliable?
207      */
208   int reliable;
209
210     /**
211      * Last time the channel was used
212      */
213   struct GNUNET_TIME_Absolute timestamp;
214
215     /**
216      * Client owner of the tunnel, if any
217      */
218   struct MeshClient *root;
219
220     /**
221      * Client destination of the tunnel, if any.
222      */
223   struct MeshClient *dest;
224
225     /**
226      * Flag to signal the destruction of the channel.
227      * If this is set GNUNET_YES the channel will be destroyed
228      * when the queue is empty.
229      */
230   int destroy;
231
232     /**
233      * Total messages pending for this channel, payload or not.
234      */
235   unsigned int pending_messages;
236
237     /**
238      * Reliability data.
239      * Only present (non-NULL) at the owner of a tunnel.
240      */
241   struct MeshChannelReliability *root_rel;
242
243     /**
244      * Reliability data.
245      * Only present (non-NULL) at the destination of a tunnel.
246      */
247   struct MeshChannelReliability *dest_rel;
248
249 };
250
251
252 /******************************************************************************/
253 /*******************************   GLOBALS  ***********************************/
254 /******************************************************************************/
255
256 /**
257  * Global handle to the statistics service.
258  */
259 extern struct GNUNET_STATISTICS_Handle *stats;
260
261 /**
262  * Local peer own ID (memory efficient handle).
263  */
264 extern GNUNET_PEER_Id myid;
265
266
267 /******************************************************************************/
268 /********************************   STATIC  ***********************************/
269 /******************************************************************************/
270
271 /**
272  * Destroy a reliable message after it has been acknowledged, either by
273  * direct mid ACK or bitfield. Updates the appropriate data structures and
274  * timers and frees all memory.
275  *
276  * @param copy Message that is no longer needed: remote peer got it.
277  */
278 static void
279 rel_message_free (struct MeshReliableMessage *copy);
280
281 /**
282  * We have received a message out of order, or the client is not ready.
283  * Buffer it until we receive an ACK from the client or the missing
284  * message from the channel.
285  *
286  * @param msg Message to buffer (MUST be of type MESH_DATA).
287  * @param rel Reliability data to the corresponding direction.
288  */
289 static void
290 add_buffered_data (const struct GNUNET_MESH_Data *msg,
291                    struct MeshChannelReliability *rel)
292 {
293   struct MeshReliableMessage *copy;
294   struct MeshReliableMessage *prev;
295   uint32_t mid;
296   uint16_t size;
297
298   size = ntohs (msg->header.size);
299   mid = ntohl (msg->mid);
300
301   LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data %u\n", mid);
302
303   copy = GNUNET_malloc (sizeof (*copy) + size);
304   copy->mid = mid;
305   copy->rel = rel;
306   memcpy (&copy[1], msg, size);
307
308   rel->n_recv++;
309
310   // FIXME do something better than O(n), although n < 64...
311   // FIXME start from the end (most messages are the latest ones)
312   for (prev = rel->head_recv; NULL != prev; prev = prev->next)
313   {
314     LOG (GNUNET_ERROR_TYPE_DEBUG, " prev %u\n", prev->mid);
315     if (GMC_is_pid_bigger (prev->mid, mid))
316     {
317       LOG (GNUNET_ERROR_TYPE_DEBUG, " bingo!\n");
318       GNUNET_CONTAINER_DLL_insert_before (rel->head_recv, rel->tail_recv,
319                                           prev, copy);
320       return;
321     }
322   }
323     LOG (GNUNET_ERROR_TYPE_DEBUG, " insert at tail!\n");
324     GNUNET_CONTAINER_DLL_insert_tail (rel->head_recv, rel->tail_recv, copy);
325     LOG (GNUNET_ERROR_TYPE_DEBUG, "add_buffered_data END\n");
326 }
327
328
329 /**
330  * Send data to a client.
331  *
332  * If the client is ready, send directly, otherwise buffer while listening
333  * for a local ACK.
334  *
335  * @param ch Channel
336  * @param msg Message.
337  * @param fwd Is this a fwd (root->dest) message?
338  */
339 static void
340 send_client_data (struct MeshChannel *ch,
341                   const struct GNUNET_MESH_Data *msg,
342                   int fwd)
343 {
344   if (fwd)
345   {
346     if (ch->dest_rel->client_ready)
347       GML_send_data (ch->dest, msg, ch->lid_dest);
348     else
349       add_buffered_data (msg, ch->dest_rel);
350   }
351   else
352   {
353     if (ch->root_rel->client_ready)
354       GML_send_data (ch->root, msg, ch->lid_root);
355     else
356       add_buffered_data (msg, ch->root_rel);
357   }
358 }
359
360
361 /**
362  * Add a client to a channel, initializing all needed data structures.
363  *
364  * @param ch Channel to which add the client.
365  * @param c Client which to add to the channel.
366  */
367 void
368 GMCH_add_client (struct MeshChannel *ch, struct MeshClient *c)
369 {
370   if (NULL != ch->dest)
371   {
372     GNUNET_break (0);
373     return;
374   }
375
376   /* Assign local id as destination */
377   ch->lid_dest = GML_get_next_chid (c);
378
379   /* Store in client's hashmap */
380   GML_channel_add (c, ch->lid_dest, ch);
381
382   GNUNET_break (NULL == ch->dest_rel);
383   ch->dest_rel = GNUNET_new (struct MeshChannelReliability);
384   ch->dest_rel->ch = ch;
385   ch->dest_rel->expected_delay = MESH_RETRANSMIT_TIME;
386
387   ch->dest = c;
388 }
389
390
391 /**
392  * Destroy all reliable messages queued for a channel,
393  * during a channel destruction.
394  * Frees the reliability structure itself.
395  *
396  * @param rel Reliability data for a channel.
397  */
398 static void
399 channel_rel_free_all (struct MeshChannelReliability *rel)
400 {
401   struct MeshReliableMessage *copy;
402   struct MeshReliableMessage *next;
403
404   if (NULL == rel)
405     return;
406
407   for (copy = rel->head_recv; NULL != copy; copy = next)
408   {
409     next = copy->next;
410     GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
411     GNUNET_free (copy);
412   }
413   for (copy = rel->head_sent; NULL != copy; copy = next)
414   {
415     next = copy->next;
416     GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
417     GNUNET_free (copy);
418   }
419   if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
420     GNUNET_SCHEDULER_cancel (rel->retry_task);
421   GNUNET_free (rel);
422 }
423
424
425 /**
426  * Mark future messages as ACK'd.
427  *
428  * @param rel Reliability data.
429  * @param msg DataACK message with a bitfield of future ACK'd messages.
430  */
431 static void
432 channel_rel_free_sent (struct MeshChannelReliability *rel,
433                        const struct GNUNET_MESH_DataACK *msg)
434 {
435   struct MeshReliableMessage *copy;
436   struct MeshReliableMessage *next;
437   uint64_t bitfield;
438   uint64_t mask;
439   uint32_t mid;
440   uint32_t target;
441   unsigned int i;
442
443   bitfield = msg->futures;
444   mid = ntohl (msg->mid);
445   LOG (GNUNET_ERROR_TYPE_DEBUG,
446               "free_sent_reliable %u %llX\n",
447               mid, bitfield);
448   LOG (GNUNET_ERROR_TYPE_DEBUG,
449               " rel %p, head %p\n",
450               rel, rel->head_sent);
451   for (i = 0, copy = rel->head_sent;
452        i < 64 && NULL != copy && 0 != bitfield;
453        i++)
454   {
455     LOG (GNUNET_ERROR_TYPE_DEBUG,
456                 " trying bit %u (mid %u)\n",
457                 i, mid + i + 1);
458     mask = 0x1LL << i;
459     if (0 == (bitfield & mask))
460      continue;
461
462     LOG (GNUNET_ERROR_TYPE_DEBUG, " set!\n");
463     /* Bit was set, clear the bit from the bitfield */
464     bitfield &= ~mask;
465
466     /* The i-th bit was set. Do we have that copy? */
467     /* Skip copies with mid < target */
468     target = mid + i + 1;
469     LOG (GNUNET_ERROR_TYPE_DEBUG, " target %u\n", target);
470     while (NULL != copy && GMC_is_pid_bigger (target, copy->mid))
471      copy = copy->next;
472
473     /* Did we run out of copies? (previously freed, it's ok) */
474     if (NULL == copy)
475     {
476      LOG (GNUNET_ERROR_TYPE_DEBUG, "run out of copies...\n");
477      return;
478     }
479
480     /* Did we overshoot the target? (previously freed, it's ok) */
481     if (GMC_is_pid_bigger (copy->mid, target))
482     {
483      LOG (GNUNET_ERROR_TYPE_DEBUG, " next copy %u\n", copy->mid);
484      continue;
485     }
486
487     /* Now copy->mid == target, free it */
488     next = copy->next;
489     rel_message_free (copy);
490     copy = next;
491   }
492   LOG (GNUNET_ERROR_TYPE_DEBUG, "free_sent_reliable END\n");
493 }
494
495
496 /**
497  * We haven't received an ACK after a certain time: restransmit the message.
498  *
499  * @param cls Closure (MeshReliableMessage with the message to restransmit)
500  * @param tc TaskContext.
501  */
502 static void
503 channel_retransmit_message (void *cls,
504                             const struct GNUNET_SCHEDULER_TaskContext *tc)
505 {
506   struct MeshChannelReliability *rel = cls;
507   struct MeshReliableMessage *copy;
508   struct MeshChannel *ch;
509   struct GNUNET_MESH_Data *payload;
510   int fwd;
511
512   rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
513   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
514     return;
515
516   ch = rel->ch;
517   copy = rel->head_sent;
518   if (NULL == copy)
519   {
520     GNUNET_break (0);
521     return;
522   }
523
524   /* Search the message to be retransmitted in the outgoing queue.
525    * Check only the queue for the connection that is going to be used,
526    * if the message is stuck in some other connection's queue we shouldn't
527    * act upon it:
528    * - cancelling it and sending the new one doesn't guarantee it's delivery,
529    *   the old connection could be temporary stalled or the queue happened to
530    *   be long at time of insertion.
531    * - not sending the new one could cause terrible delays the old connection
532    *   is stalled.
533    */
534 //   FIXME access to queue elements is limited
535   payload = (struct GNUNET_MESH_Data *) &copy[1];
536   fwd = (rel == ch->root_rel);
537 //   c = GMT_get_connection (ch->t, fwd);
538 //   hop = connection_get_hop (c, fwd);
539 //   for (q = hop->queue_head; NULL != q; q = q->next)
540 //   {
541 //     if (ntohs (payload->header.type) == q->type && ch == q->ch)
542 //     {
543 //       struct GNUNET_MESH_Data *queued_data = q->cls;
544 // 
545 //       if (queued_data->mid == payload->mid)
546 //         break;
547 //     }
548 //   }
549
550   /* Message not found in the queue that we are going to use. */
551 //   if (NULL == q)
552 //   {
553     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RETRANSMIT %u\n", copy->mid);
554
555     GMCH_send_prebuilt_message (&payload->header, ch, fwd);
556     GNUNET_STATISTICS_update (stats, "# data retransmitted", 1, GNUNET_NO);
557 //   }
558 //   else
559 //   {
560 //     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! ALREADY IN QUEUE %u\n", copy->mid);
561 //   }
562
563   rel->retry_timer = GNUNET_TIME_STD_BACKOFF (rel->retry_timer);
564   rel->retry_task = GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
565                                                   &channel_retransmit_message,
566                                                   cls);
567 }
568
569
570 /**
571  * Destroy a reliable message after it has been acknowledged, either by
572  * direct mid ACK or bitfield. Updates the appropriate data structures and
573  * timers and frees all memory.
574  *
575  * @param copy Message that is no longer needed: remote peer got it.
576  */
577 static void
578 rel_message_free (struct MeshReliableMessage *copy)
579 {
580   struct MeshChannelReliability *rel;
581   struct GNUNET_TIME_Relative time;
582
583   rel = copy->rel;
584   time = GNUNET_TIME_absolute_get_duration (copy->timestamp);
585   rel->expected_delay.rel_value_us *= 7;
586   rel->expected_delay.rel_value_us += time.rel_value_us;
587   rel->expected_delay.rel_value_us /= 8;
588   rel->n_sent--;
589   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Freeing %u\n", copy->mid);
590   LOG (GNUNET_ERROR_TYPE_DEBUG, "    n_sent %u\n", rel->n_sent);
591   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  took %s\n",
592               GNUNET_STRINGS_relative_time_to_string (time, GNUNET_NO));
593   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  new expected delay %s\n",
594               GNUNET_STRINGS_relative_time_to_string (rel->expected_delay,
595                                                       GNUNET_NO));
596   rel->retry_timer = rel->expected_delay;
597   GNUNET_CONTAINER_DLL_remove (rel->head_sent, rel->tail_sent, copy);
598   GNUNET_free (copy);
599 }
600
601
602 /**
603  * Confirm we got a channel create.
604  *
605  * @param ch The channel to confirm.
606  * @param fwd Should we send a FWD ACK? (going dest->root)
607  */
608 static void
609 channel_send_ack (struct MeshChannel *ch, int fwd)
610 {
611   struct GNUNET_MESH_ChannelManage msg;
612
613   msg.header.size = htons (sizeof (msg));
614   msg.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK);
615   LOG (GNUNET_ERROR_TYPE_DEBUG,
616               "  sending channel %s ack for channel %s\n",
617               fwd ? "FWD" : "BCK", GMCH_2s (ch));
618
619   msg.chid = htonl (ch->gid);
620   GMCH_send_prebuilt_message (&msg.header, ch, !fwd);
621 }
622
623
624 /**
625  * Channel was ACK'd by remote peer, mark as ready and cancel retransmission.
626  *
627  * @param ch Channel to mark as ready.
628  * @param fwd Was the ACK message sent fwd? (dest->root, SYNACK)
629  */
630 static void
631 channel_confirm (struct MeshChannel *ch, int fwd)
632 {
633   struct MeshChannelReliability *rel;
634   struct MeshReliableMessage *copy;
635   struct MeshReliableMessage *next;
636
637   LOG (GNUNET_ERROR_TYPE_DEBUG,
638               "  channel confirm %s %s:%X\n",
639               fwd ? "FWD" : "BCK", GMT_2s (ch->t), ch->gid);
640   ch->state = MESH_CHANNEL_READY;
641
642   rel = fwd ? ch->root_rel : ch->dest_rel;
643   for (copy = rel->head_sent; NULL != copy; copy = next)
644   {
645     struct GNUNET_MessageHeader *msg;
646
647     next = copy->next;
648     msg = (struct GNUNET_MessageHeader *) &copy[1];
649     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE)
650     {
651       rel_message_free (copy);
652       /* TODO return? */
653     }
654   }
655   GML_send_ack (fwd ? ch->root : ch->dest, fwd ? ch->lid_root : ch->lid_dest);
656
657   /* In case of a FWD ACk (SYNACK) send a BCK ACK (ACK). */
658   if (fwd)
659     channel_send_ack (ch, !fwd);
660 }
661
662
663 /**
664  * Save a copy to retransmit in case it gets lost.
665  *
666  * Initializes all needed callbacks and timers.
667  *
668  * @param ch Channel this message goes on.
669  * @param msg Message to copy.
670  * @param fwd Is this fwd traffic?
671  */
672 static void
673 channel_save_copy (struct MeshChannel *ch,
674                    const struct GNUNET_MessageHeader *msg,
675                    int fwd)
676 {
677   struct MeshChannelReliability *rel;
678   struct MeshReliableMessage *copy;
679   uint32_t mid;
680   uint16_t type;
681   uint16_t size;
682
683   rel = fwd ? ch->root_rel : ch->dest_rel;
684   mid = rel->mid_send;
685   type = ntohs (msg->type);
686   size = ntohs (msg->size);
687
688   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! SAVE %u\n", mid);
689   copy = GNUNET_malloc (sizeof (struct MeshReliableMessage) + size);
690   copy->mid = mid;
691   copy->timestamp = GNUNET_TIME_absolute_get ();
692   copy->rel = rel;
693   copy->type = type;
694   memcpy (&copy[1], msg, size);
695   rel->n_sent++;
696   LOG (GNUNET_ERROR_TYPE_DEBUG, " n_sent %u\n", rel->n_sent);
697   GNUNET_CONTAINER_DLL_insert_tail (rel->head_sent, rel->tail_sent, copy);
698   if (GNUNET_SCHEDULER_NO_TASK == rel->retry_task)
699   {
700     rel->retry_timer =
701         GNUNET_TIME_relative_multiply (rel->expected_delay,
702                                         MESH_RETRANSMIT_MARGIN);
703     rel->retry_task =
704         GNUNET_SCHEDULER_add_delayed (rel->retry_timer,
705                                       &channel_retransmit_message,
706                                       rel);
707   }
708 }
709
710
711
712 /**
713  * Send a buffered message to the client, for in order delivery or
714  * as result of client ACK.
715  *
716  * @param ch Channel on which to empty the message buffer.
717  * @param c Client to send to.
718  * @param fwd Is this to send FWD data?.
719  */
720 static void
721 send_client_buffered_data (struct MeshChannel *ch,
722                            struct MeshClient *c,
723                            int fwd)
724 {
725   struct MeshReliableMessage *copy;
726   struct MeshChannelReliability *rel;
727
728   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data\n");
729   rel = fwd ? ch->dest_rel : ch->root_rel;
730   if (GNUNET_NO == rel->client_ready)
731   {
732     LOG (GNUNET_ERROR_TYPE_DEBUG, "client not ready\n");
733     return;
734   }
735
736   copy = rel->head_recv;
737   /* We never buffer channel management messages */
738   if (NULL != copy)
739   {
740     if (copy->mid == rel->mid_recv || GNUNET_NO == ch->reliable)
741     {
742       struct GNUNET_MESH_Data *msg = (struct GNUNET_MESH_Data *) &copy[1];
743
744       LOG (GNUNET_ERROR_TYPE_DEBUG,
745                   " have %u! now expecting %u\n",
746                   copy->mid, rel->mid_recv + 1);
747       send_client_data (ch, msg, fwd);
748       rel->n_recv--;
749       rel->mid_recv++;
750       GNUNET_CONTAINER_DLL_remove (rel->head_recv, rel->tail_recv, copy);
751       GNUNET_free (copy);
752     }
753     else
754     {
755       LOG (GNUNET_ERROR_TYPE_DEBUG,
756                   " reliable && don't have %u, next is %u\n",
757                   rel->mid_recv,
758                   copy->mid);
759       return;
760     }
761   }
762   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_buffered_data END\n");
763 }
764
765
766
767
768 /**
769  * Destroy a channel and free all resources.
770  *
771  * @param ch Channel to destroy.
772  */
773 static void
774 channel_destroy (struct MeshChannel *ch)
775 {
776   struct MeshClient *c;
777
778   if (NULL == ch)
779     return;
780
781   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying channel %s:%u\n",
782               GMT_2s (ch->t), ch->gid);
783   GMCH_debug (ch);
784
785   c = ch->root;
786   if (NULL != c)
787   {
788     GML_channel_remove (c, ch->lid_root, ch);
789   }
790
791   c = ch->dest;
792   if (NULL != c)
793   {
794     GML_channel_remove (c, ch->lid_dest, ch);
795   }
796
797   channel_rel_free_all (ch->root_rel);
798   channel_rel_free_all (ch->dest_rel);
799
800   GMT_remove_channel (ch->t, ch);
801   GNUNET_STATISTICS_update (stats, "# channels", -1, GNUNET_NO);
802
803   GNUNET_free (ch);
804 }
805
806
807 /**
808  * Create a new channel.
809  *
810  * @param t Tunnel this channel is in.
811  * @param owner Client that owns the channel, NULL for foreign channels.
812  * @param lid_root Local ID for root client.
813  *
814  * @return A new initialized channel. NULL on error.
815  */
816 static struct MeshChannel *
817 channel_new (struct MeshTunnel3 *t,
818              struct MeshClient *owner,
819              MESH_ChannelNumber lid_root)
820 {
821   struct MeshChannel *ch;
822
823   ch = GNUNET_new (struct MeshChannel);
824   ch->root = owner;
825   ch->lid_root = lid_root;
826   ch->t = t;
827
828   GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO);
829
830   if (NULL != owner)
831   {
832     ch->gid = GMT_get_next_chid (t);
833     GML_channel_add (owner, lid_root, ch);
834   }
835   GMT_add_channel (t, ch);
836
837   return ch;
838 }
839
840
841 /**
842  * Set options in a channel, extracted from a bit flag field
843  *
844  * @param ch Channel to set options to.
845  * @param options Bit array in host byte order.
846  */
847 static void
848 channel_set_options (struct MeshChannel *ch, uint32_t options)
849 {
850   ch->nobuffer = (options & GNUNET_MESH_OPTION_NOBUFFER) != 0 ?
851                  GNUNET_YES : GNUNET_NO;
852   ch->reliable = (options & GNUNET_MESH_OPTION_RELIABLE) != 0 ?
853                  GNUNET_YES : GNUNET_NO;
854 }
855
856
857 /**
858  * Handle a loopback message: call the appropriate handler for the message type.
859  *
860  * @param ch Channel this message is on.
861  * @param msgh Message header.
862  * @param fwd Is this FWD traffic?
863  */
864 void
865 handle_loopback (struct MeshChannel *ch,
866                  const struct GNUNET_MessageHeader *msgh,
867                  int fwd)
868 {
869   uint16_t type;
870
871   type = ntohs (msgh->type);
872   LOG (GNUNET_ERROR_TYPE_DEBUG,
873        "Loopback %s %s message!\n",
874        fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (type));
875
876   switch (type)
877   {
878     case GNUNET_MESSAGE_TYPE_MESH_DATA:
879       /* Don't send hop ACK, wait for client to ACK */
880       GMCH_handle_data (ch, (struct GNUNET_MESH_Data *) msgh, fwd);
881       break;
882
883     case GNUNET_MESSAGE_TYPE_MESH_DATA_ACK:
884       GMCH_handle_data_ack (ch, (struct GNUNET_MESH_DataACK *) msgh, fwd);
885       break;
886
887     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
888       GMCH_handle_create (ch->t,
889                           (struct GNUNET_MESH_ChannelCreate *) msgh,
890                           fwd);
891       break;
892
893     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_ACK:
894       GMCH_handle_ack (ch,
895                        (struct GNUNET_MESH_ChannelManage *) msgh,
896                        fwd);
897       break;
898
899     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
900       GMCH_handle_destroy (ch,
901                            (struct GNUNET_MESH_ChannelManage *) msgh,
902                            fwd);
903       break;
904
905     default:
906       GNUNET_break_op (0);
907       LOG (GNUNET_ERROR_TYPE_DEBUG,
908            "end-to-end message not known (%u)\n",
909            ntohs (msgh->type));
910   }
911 }
912
913
914
915 /******************************************************************************/
916 /********************************    API    ***********************************/
917 /******************************************************************************/
918
919 /**
920  * Get channel ID.
921  *
922  * @param ch Channel.
923  *
924  * @return ID
925  */
926 MESH_ChannelNumber
927 GMCH_get_id (const struct MeshChannel *ch)
928 {
929   return ch->gid;
930 }
931
932
933 /**
934  * Get the channel tunnel.
935  *
936  * @param ch Channel to get the tunnel from.
937  *
938  * @return tunnel of the channel.
939  */
940 struct MeshTunnel3 *
941 GMCH_get_tunnel (const struct MeshChannel *ch)
942 {
943   return ch->t;
944 }
945
946
947 /**
948  * Get free buffer space towards the client on a specific channel.
949  *
950  * @param ch Channel.
951  * @param fwd Is query about FWD traffic?
952  *
953  * @return Free buffer space [0 - 64]
954  */
955 unsigned int
956 GMCH_get_buffer (struct MeshChannel *ch, int fwd)
957 {
958   struct MeshChannelReliability *rel;
959
960   rel = fwd ? ch->dest_rel : ch->root_rel;
961
962   /* If rel is NULL it means that the end is not yet created,
963    * most probably is a loopback channel at the point of sending
964    * the ChannelCreate to itself.
965    */
966   if (NULL == rel)
967     return 64;
968
969   return (64 - rel->n_recv);
970 }
971
972
973 /**
974  * Is the root client for this channel on this peer?
975  *
976  * @param ch Channel.
977  * @param fwd Is this for fwd traffic?
978  *
979  * @return GNUNET_YES in case it is.
980  */
981 int
982 GMCH_is_origin (struct MeshChannel *ch, int fwd)
983 {
984   struct MeshClient *c;
985
986   c = fwd ? ch->root : ch->dest;
987   return NULL != c;
988 }
989
990
991 /**
992  * Is the destination client for this channel on this peer?
993  *
994  * @param ch Channel.
995  * @param fwd Is this for fwd traffic?
996  *
997  * @return GNUNET_YES in case it is.
998  */
999 int
1000 GMCH_is_terminal (struct MeshChannel *ch, int fwd)
1001 {
1002   struct MeshClient *c;
1003
1004   c = fwd ? ch->dest : ch->root;
1005   return NULL != c;
1006 }
1007
1008
1009 /**
1010  * Notify the destination client that a new incoming channel was created.
1011  *
1012  * @param ch Channel that was created.
1013  */
1014 void
1015 GMCH_send_create (struct MeshChannel *ch)
1016 {
1017   uint32_t opt;
1018
1019   if (NULL == ch->dest)
1020     return;
1021
1022   opt = 0;
1023   opt |= GNUNET_YES == ch->reliable ? GNUNET_MESH_OPTION_RELIABLE : 0;
1024   opt |= GNUNET_YES == ch->nobuffer ? GNUNET_MESH_OPTION_NOBUFFER : 0;
1025   GML_send_channel_create (ch->dest, ch->lid_dest, ch->port, opt,
1026                            GMT_get_destination (ch->t));
1027
1028 }
1029
1030 /**
1031  * Notify a client that the channel is no longer valid.
1032  * FIXME send on tunnel if some client == NULL?
1033  *
1034  * @param ch Channel that is destroyed.
1035  */
1036 void
1037 GMCH_send_destroy (struct MeshChannel *ch)
1038 {
1039   if (NULL != ch->root)
1040     GML_send_channel_destroy (ch->root, ch->lid_root);
1041
1042   if (NULL != ch->dest)
1043     GML_send_channel_destroy (ch->dest, ch->lid_dest);
1044 }
1045
1046
1047 /**
1048  * Send data on a channel.
1049  *
1050  * If the destination is local, send it to client, otherwise encrypt and
1051  * send to next hop.
1052  *
1053  * @param ch Channel
1054  * @param msg Message.
1055  * @param fwd Is this a fwd (root->dest) message?
1056  */
1057 void
1058 GMCH_send_data (struct MeshChannel *ch,
1059                 const struct GNUNET_MESH_Data *msg,
1060                 int fwd)
1061 {
1062   if (GMCH_is_terminal (ch, fwd))
1063   {
1064     GML_send_data (fwd ? ch->dest : ch->root,
1065                    msg,
1066                    fwd ? ch->lid_dest : ch->lid_root);
1067   }
1068   else
1069   {
1070     GMT_send_prebuilt_message (&msg->header, ch->t, ch, fwd);
1071   }
1072 }
1073
1074
1075 /**
1076  * Send an end-to-end ACK message for the most recent in-sequence payload.
1077  *
1078  * If channel is not reliable, do nothing.
1079  *
1080  * @param ch Channel this is about.
1081  * @param fwd Is for FWD traffic? (ACK dest->owner)
1082  */
1083 void
1084 GMCH_send_data_ack (struct MeshChannel *ch, int fwd)
1085 {
1086   struct GNUNET_MESH_DataACK msg;
1087   struct MeshChannelReliability *rel;
1088   struct MeshReliableMessage *copy;
1089   unsigned int delta;
1090   uint64_t mask;
1091   uint16_t type;
1092
1093   if (GNUNET_NO == ch->reliable)
1094   {
1095     return;
1096   }
1097   rel = fwd ? ch->dest_rel : ch->root_rel;
1098   LOG (GNUNET_ERROR_TYPE_DEBUG,
1099               "send_data_ack for %u\n",
1100               rel->mid_recv - 1);
1101
1102   type = GNUNET_MESSAGE_TYPE_MESH_DATA_ACK;
1103   msg.header.type = htons (type);
1104   msg.header.size = htons (sizeof (msg));
1105   msg.chid = htonl (ch->gid);
1106   msg.mid = htonl (rel->mid_recv - 1);
1107   msg.futures = 0;
1108   for (copy = rel->head_recv; NULL != copy; copy = copy->next)
1109   {
1110     if (copy->type != type)
1111       continue;
1112     delta = copy->mid - rel->mid_recv;
1113     if (63 < delta)
1114       break;
1115     mask = 0x1LL << delta;
1116     msg.futures |= mask;
1117     LOG (GNUNET_ERROR_TYPE_DEBUG,
1118                 " setting bit for %u (delta %u) (%llX) -> %llX\n",
1119                 copy->mid, delta, mask, msg.futures);
1120   }
1121   LOG (GNUNET_ERROR_TYPE_DEBUG, " final futures %llX\n", msg.futures);
1122
1123   GMCH_send_prebuilt_message (&msg.header, ch, fwd);
1124   LOG (GNUNET_ERROR_TYPE_DEBUG, "send_data_ack END\n");
1125 }
1126
1127
1128 /**
1129  * Log channel info.
1130  *
1131  * @param ch Channel.
1132  */
1133 void
1134 GMCH_debug (struct MeshChannel *ch)
1135 {
1136   if (NULL == ch)
1137   {
1138     LOG (GNUNET_ERROR_TYPE_DEBUG, "*** DEBUG NULL CHANNEL ***\n");
1139     return;
1140   }
1141   LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %s:%X (%p)\n",
1142               GMT_2s (ch->t), ch->gid, ch);
1143   LOG (GNUNET_ERROR_TYPE_DEBUG, "  root %p/%p\n",
1144               ch->root, ch->root_rel);
1145   if (NULL != ch->root)
1146   {
1147     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->root));
1148     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1149                 ch->root_rel->client_ready ? "YES" : "NO");
1150     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_root);
1151   }
1152   LOG (GNUNET_ERROR_TYPE_DEBUG, "  dest %p/%p\n",
1153               ch->dest, ch->dest_rel);
1154   if (NULL != ch->dest)
1155   {
1156     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cli %s\n", GML_2s (ch->dest));
1157     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ready %s\n",
1158                 ch->dest_rel->client_ready ? "YES" : "NO");
1159     LOG (GNUNET_ERROR_TYPE_DEBUG, "  id %X\n", ch->lid_dest);
1160   }
1161 }
1162
1163
1164 /**
1165  * Handle an ACK given by a client.
1166  *
1167  * Mark client as ready and send him any buffered data we could have for him.
1168  *
1169  * @param ch Channel.
1170  * @param fwd Is this a "FWD ACK"? (FWD ACKs are sent by root and go BCK)
1171  */
1172 void
1173 GMCH_handle_local_ack (struct MeshChannel *ch, int fwd)
1174 {
1175   struct MeshChannelReliability *rel;
1176   struct MeshClient *c;
1177
1178   rel = fwd ? ch->dest_rel : ch->root_rel;
1179   c   = fwd ? ch->dest     : ch->root;
1180
1181   rel->client_ready = GNUNET_YES;
1182   send_client_buffered_data (ch, c, fwd);
1183   GMC_send_ack (NULL, ch, fwd);
1184 }
1185
1186
1187 /**
1188  * Handle data given by a client.
1189  *
1190  * Check whether the client is allowed to send in this tunnel, save if channel
1191  * is reliable and send an ACK to the client if there is still buffer space
1192  * in the tunnel.
1193  *
1194  * @param ch Channel.
1195  * @param fwd Is this a FWD data?
1196  *
1197  * @return GNUNET_OK if everything goes well, GNUNET_SYSERR in case of en error.
1198  */
1199 int
1200 GMCH_handle_local_data (struct MeshChannel *ch,
1201                         struct MeshClient *c,
1202                         struct GNUNET_MessageHeader *message,
1203                         int fwd)
1204 {
1205   struct MeshChannelReliability *rel;
1206   struct GNUNET_MESH_Data *payload;
1207   size_t size = ntohs (message->size);
1208   uint16_t p2p_size = sizeof(struct GNUNET_MESH_Data) + size;
1209   unsigned char cbuf[p2p_size];
1210
1211   /* Is the client in the channel? */
1212   if ( !( (fwd &&
1213            ch->root == c)
1214          ||
1215           (!fwd &&
1216            ch->dest == c) ) )
1217   {
1218     GNUNET_break (0);
1219     return GNUNET_SYSERR;
1220   }
1221
1222   rel = fwd ? ch->root_rel : ch->dest_rel;
1223
1224   /* Ok, everything is correct, send the message. */
1225   payload = (struct GNUNET_MESH_Data *) cbuf;
1226   payload->mid = htonl (rel->mid_send);
1227   rel->mid_send++;
1228   memcpy (&payload[1], message, size);
1229   payload->header.size = htons (p2p_size);
1230   payload->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_DATA);
1231   payload->chid = htonl (ch->gid);
1232   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channel...\n");
1233   GMCH_send_prebuilt_message (&payload->header, ch, fwd);
1234
1235   if (GNUNET_YES == ch->reliable)
1236     channel_save_copy (ch, &payload->header, fwd);
1237   if (GMT_get_buffer (ch->t, fwd) > 0)
1238     GML_send_ack (c, fwd ? ch->lid_root : ch->lid_dest);
1239
1240   return GNUNET_OK;
1241 }
1242
1243
1244 /**
1245  * Handle a channel destroy requested by a client.
1246  *
1247  * Destroy the channel and the tunnel in case this was the last channel.
1248  *
1249  * @param ch Channel.
1250  * @param c Client that requested the destruction (to avoid notifying him).
1251  */
1252 void
1253 GMCH_handle_local_destroy (struct MeshChannel *ch,
1254                            struct MeshClient *c)
1255 {
1256   struct MeshTunnel3 *t;
1257
1258   /* Cleanup after the tunnel */
1259   if (c == ch->dest)
1260   {
1261     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is destination.\n", GML_2s (c));
1262     GML_client_delete_channel (c, ch, ch->lid_dest);
1263     ch->dest = NULL;
1264   }
1265   if (c == ch->root)
1266   {
1267     LOG (GNUNET_ERROR_TYPE_DEBUG, " Client %s is owner.\n", GML_2s (c));
1268     GML_client_delete_channel (c, ch, ch->lid_root);
1269     ch->root = NULL;
1270   }
1271
1272   t = ch->t;
1273   GMCH_send_destroy (ch);
1274   channel_destroy (ch);
1275   GMT_destroy_if_empty (t);
1276 }
1277
1278
1279 /**
1280  * Handle a channel create requested by a client.
1281  *
1282  * Create the channel and the tunnel in case this was the first0 channel.
1283  *
1284  * @param c Client that requested the creation (will be the root).
1285  * @param msg Create Channel message.
1286  *
1287  * @return GNUNET_OK if everything went fine, GNUNET_SYSERR otherwise.
1288  */
1289 int
1290 GMCH_handle_local_create (struct MeshClient *c,
1291                           struct GNUNET_MESH_ChannelMessage *msg)
1292 {
1293   struct MeshChannel *ch;
1294   struct MeshTunnel3 *t;
1295   struct MeshPeer *peer;
1296   MESH_ChannelNumber chid;
1297
1298   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s:%u\n",
1299               GNUNET_i2s (&msg->peer), ntohl (msg->port));
1300   chid = ntohl (msg->channel_id);
1301
1302   /* Sanity check for duplicate channel IDs */
1303   if (NULL != GML_channel_get (c, chid))
1304   {
1305     GNUNET_break (0);
1306     return GNUNET_SYSERR;
1307   }
1308
1309   peer = GMP_get (&msg->peer);
1310   GMP_add_tunnel (peer);
1311   t = GMP_get_tunnel (peer);
1312
1313   if (GMP_get_short_id (peer) == myid)
1314   {
1315     GMT_change_state (t, MESH_TUNNEL3_READY);
1316   }
1317   else
1318   {
1319     GMP_connect (peer);
1320   }
1321
1322   /* Create channel */
1323   ch = channel_new (t, c, chid);
1324   if (NULL == ch)
1325   {
1326     GNUNET_break (0);
1327     return GNUNET_SYSERR;
1328   }
1329   ch->port = ntohl (msg->port);
1330   channel_set_options (ch, ntohl (msg->opt));
1331
1332   /* In unreliable channels, we'll use the DLL to buffer BCK data */
1333   ch->root_rel = GNUNET_new (struct MeshChannelReliability);
1334   ch->root_rel->ch = ch;
1335   ch->root_rel->expected_delay = MESH_RETRANSMIT_TIME;
1336
1337   LOG (GNUNET_ERROR_TYPE_DEBUG, "CREATED CHANNEL %s\n", GMCH_2s (ch));
1338
1339   /* Send create channel */
1340   {
1341     struct GNUNET_MESH_ChannelCreate msgcc;
1342
1343     msgcc.header.size = htons (sizeof (msgcc));
1344     msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE);
1345     msgcc.chid = htonl (ch->gid);
1346     msgcc.port = msg->port;
1347     msgcc.opt = msg->opt;
1348
1349     GMT_queue_data (t, ch, &msgcc.header, GNUNET_YES);
1350   }
1351   return GNUNET_OK;
1352 }
1353
1354 /**
1355  * Handler for mesh network payload traffic.
1356  *
1357  * @param ch Channel for the message.
1358  * @param message Unencryted data message.
1359  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1360  */
1361 void
1362 GMCH_handle_data (struct MeshChannel *ch,
1363                   const struct GNUNET_MESH_Data *msg,
1364                   int fwd)
1365 {
1366   struct MeshChannelReliability *rel;
1367   struct MeshClient *c;
1368   uint32_t mid;
1369
1370   /*  Initialize FWD/BCK data */
1371   c   = fwd ? ch->dest     : ch->root;
1372   rel = fwd ? ch->dest_rel : ch->root_rel;
1373
1374   if (NULL == c)
1375   {
1376     GNUNET_break (0);
1377     return;
1378   }
1379
1380   GNUNET_STATISTICS_update (stats, "# data received", 1, GNUNET_NO);
1381
1382   mid = ntohl (msg->mid);
1383   LOG (GNUNET_ERROR_TYPE_DEBUG, " mid %u\n", mid);
1384
1385   if (GNUNET_NO == ch->reliable ||
1386       ( !GMC_is_pid_bigger (rel->mid_recv, mid) &&
1387         GMC_is_pid_bigger (rel->mid_recv + 64, mid) ) )
1388   {
1389     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! RECV %u\n", mid);
1390     if (GNUNET_YES == ch->reliable)
1391     {
1392       /* Is this the exact next expected messasge? */
1393       if (mid == rel->mid_recv)
1394       {
1395         LOG (GNUNET_ERROR_TYPE_DEBUG, "as expected\n");
1396         rel->mid_recv++;
1397         send_client_data (ch, msg, fwd);
1398       }
1399       else
1400       {
1401         LOG (GNUNET_ERROR_TYPE_DEBUG, "save for later\n");
1402         add_buffered_data (msg, rel);
1403       }
1404     }
1405     else
1406     {
1407       /* Tunnel is unreliable: send to clients directly */
1408       /* FIXME: accept Out Of Order traffic */
1409       rel->mid_recv = mid + 1;
1410       send_client_data (ch, msg, fwd);
1411     }
1412   }
1413   else
1414   {
1415     GNUNET_break_op (0);
1416     LOG (GNUNET_ERROR_TYPE_DEBUG,
1417                 " MID %u not expected (%u - %u), dropping!\n",
1418                 mid, rel->mid_recv, rel->mid_recv + 64);
1419   }
1420
1421   GMCH_send_data_ack (ch, fwd);
1422 }
1423
1424
1425 /**
1426  * Handler for mesh network traffic end-to-end ACKs.
1427  *
1428  * @param t Tunnel on which we got this message.
1429  * @param message Data message.
1430  * @param fwd Is this a fwd ACK? (dest->orig)
1431  */
1432 void
1433 GMCH_handle_data_ack (struct MeshChannel *ch,
1434                       const struct GNUNET_MESH_DataACK *msg,
1435                       int fwd)
1436 {
1437   struct MeshChannelReliability *rel;
1438   struct MeshReliableMessage *copy;
1439   struct MeshReliableMessage *next;
1440   uint32_t ack;
1441   int work;
1442
1443   ack = ntohl (msg->mid);
1444   LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! %s ACK %u\n",
1445               (GNUNET_YES == fwd) ? "FWD" : "BCK", ack);
1446
1447   if (GNUNET_YES == fwd)
1448   {
1449     rel = ch->root_rel;
1450   }
1451   else
1452   {
1453     rel = ch->dest_rel;
1454   }
1455   if (NULL == rel)
1456   {
1457     GNUNET_break (0);
1458     return;
1459   }
1460
1461   for (work = GNUNET_NO, copy = rel->head_sent; copy != NULL; copy = next)
1462   {
1463     if (GMC_is_pid_bigger (copy->mid, ack))
1464     {
1465       LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  head %u, out!\n", copy->mid);
1466       channel_rel_free_sent (rel, msg);
1467       break;
1468     }
1469     work = GNUNET_YES;
1470     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!!  id %u\n", copy->mid);
1471     next = copy->next;
1472     rel_message_free (copy);
1473   }
1474   /* ACK client if needed */
1475 //   channel_send_ack (t, type, GNUNET_MESSAGE_TYPE_MESH_UNICAST_ACK == type);
1476
1477   /* If some message was free'd, update the retransmission delay*/
1478   if (GNUNET_YES == work)
1479   {
1480     if (GNUNET_SCHEDULER_NO_TASK != rel->retry_task)
1481     {
1482       GNUNET_SCHEDULER_cancel (rel->retry_task);
1483       if (NULL == rel->head_sent)
1484       {
1485         rel->retry_task = GNUNET_SCHEDULER_NO_TASK;
1486       }
1487       else
1488       {
1489         struct GNUNET_TIME_Absolute new_target;
1490         struct GNUNET_TIME_Relative delay;
1491
1492         delay = GNUNET_TIME_relative_multiply (rel->retry_timer,
1493                                                MESH_RETRANSMIT_MARGIN);
1494         new_target = GNUNET_TIME_absolute_add (rel->head_sent->timestamp,
1495                                                delay);
1496         delay = GNUNET_TIME_absolute_get_remaining (new_target);
1497         rel->retry_task =
1498             GNUNET_SCHEDULER_add_delayed (delay,
1499                                           &channel_retransmit_message,
1500                                           rel);
1501       }
1502     }
1503     else
1504       GNUNET_break (0);
1505   }
1506 }
1507
1508
1509 /**
1510  * Handler for channel create messages.
1511  *
1512  * @param t Tunnel this channel will be in.
1513  * @param msg Message.
1514  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1515  */
1516 struct MeshChannel *
1517 GMCH_handle_create (struct MeshTunnel3 *t,
1518                     const struct GNUNET_MESH_ChannelCreate *msg,
1519                     int fwd)
1520 {
1521   MESH_ChannelNumber chid;
1522   struct MeshChannel *ch;
1523   struct MeshClient *c;
1524   uint32_t port;
1525
1526   chid = ntohl (msg->chid);
1527
1528   ch = GMT_get_channel (t, chid);
1529   if (NULL == ch)
1530   {
1531     /* Create channel */
1532     ch = channel_new (t, NULL, 0);
1533     ch->gid = chid;
1534   }
1535   channel_set_options (ch, ntohl (msg->opt));
1536
1537   /* Find a destination client */
1538   port = ntohl (msg->port);
1539   LOG (GNUNET_ERROR_TYPE_DEBUG, "   port %u\n", port);
1540   c = GML_client_get_by_port (port);
1541   if (NULL == c)
1542   {
1543     /* TODO send reject */
1544     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no client has port registered\n");
1545     channel_destroy (ch);
1546     return NULL;
1547   }
1548
1549   GMCH_add_client (ch, c);
1550   if (GNUNET_YES == ch->reliable)
1551     LOG (GNUNET_ERROR_TYPE_DEBUG, "!!! Reliable\n");
1552
1553   GMCH_send_create (ch);
1554   channel_send_ack (ch, fwd);
1555
1556   if (GNUNET_NO == ch->dest_rel->client_ready)
1557   {
1558     GML_send_ack (ch->dest, ch->lid_dest);
1559     ch->dest_rel->client_ready = GNUNET_YES;
1560   }
1561
1562   return ch;
1563 }
1564
1565
1566 /**
1567  * Handler for channel ack messages.
1568  *
1569  * @param ch Channel.
1570  * @param msg Message.
1571  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1572  */
1573 void
1574 GMCH_handle_ack (struct MeshChannel *ch,
1575                  const struct GNUNET_MESH_ChannelManage *msg,
1576                  int fwd)
1577 {
1578   channel_confirm (ch, !fwd);
1579 }
1580
1581
1582 /**
1583  * Handler for channel destroy messages.
1584  *
1585  * @param ch Channel to be destroyed of.
1586  * @param msg Message.
1587  * @param fwd Is this FWD traffic? GNUNET_YES : GNUNET_NO;
1588  */
1589 void
1590 GMCH_handle_destroy (struct MeshChannel *ch,
1591                      const struct GNUNET_MESH_ChannelManage *msg,
1592                      int fwd)
1593 {
1594   struct MeshTunnel3 *t;
1595
1596   GMCH_debug (ch);
1597   if ( (fwd && NULL == ch->dest) || (!fwd && NULL == ch->root) )
1598   {
1599     /* Not for us (don't destroy twice a half-open loopback channel) */
1600     return;
1601   }
1602
1603   t = ch->t;
1604   GMCH_send_destroy (ch);
1605   channel_destroy (ch);
1606   GMT_destroy_if_empty (t);
1607 }
1608
1609
1610 /**
1611  * Sends an already built message on a channel.
1612  *
1613  * If the channel is on a loopback tunnel, notifies the appropriate destination
1614  * client locally.
1615  *
1616  * On a normal channel passes the message to the tunnel for encryption and
1617  * sending on a connection.
1618  *
1619  * This function DOES NOT save the message for retransmission.
1620  *
1621  * @param message Message to send. Function makes a copy of it.
1622  * @param ch Channel on which this message is transmitted.
1623  * @param fwd Is this a fwd message?
1624  */
1625 void
1626 GMCH_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
1627                             struct MeshChannel *ch, int fwd)
1628 {
1629   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMCH Send %s %s on channel %s\n",
1630        fwd ? "FWD" : "BCK", GNUNET_MESH_DEBUG_M2S (ntohs (message->type)), 
1631        GMCH_2s (ch));
1632
1633   if (GMT_is_loopback (ch->t))
1634   {
1635     handle_loopback (ch, message, fwd);
1636     return;
1637   }
1638
1639   GMT_send_prebuilt_message (message, ch->t, ch, fwd);
1640 }
1641
1642
1643 /**
1644  * Get the static string for identification of the channel.
1645  *
1646  * @param ch Channel.
1647  *
1648  * @return Static string with the channel IDs.
1649  */
1650 const char *
1651 GMCH_2s (const struct MeshChannel *ch)
1652 {
1653   static char buf[64];
1654
1655   if (NULL == ch)
1656     return "(NULL Channel)";
1657
1658   sprintf (buf, "%s:%X (%X / %X)",
1659            GMT_2s (ch->t), ch->gid, ch->lid_root, ch->lid_dest);
1660
1661   return buf;
1662 }