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