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