attempting to fix #5464
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_channel.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2017 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18 /**
19  * @file cadet/gnunet-service-cadet_channel.c
20  * @brief logical links between CADET clients
21  * @author Bartlomiej Polot
22  * @author Christian Grothoff
23  *
24  * TODO:
25  * - Congestion/flow control:
26  *   + estimate max bandwidth using bursts and use to for CONGESTION CONTROL!
27  *     (and figure out how/where to use this!)
28  *   + figure out flow control without ACKs (unreliable traffic!)
29  * - revisit handling of 'unbuffered' traffic!
30  *   (need to push down through tunnel into connection selection)
31  * - revisit handling of 'buffered' traffic: 4 is a rather small buffer; maybe
32  *   reserve more bits in 'options' to allow for buffer size control?
33  */
34 #include "platform.h"
35 #include "cadet.h"
36 #include "gnunet_statistics_service.h"
37 #include "gnunet-service-cadet_channel.h"
38 #include "gnunet-service-cadet_connection.h"
39 #include "gnunet-service-cadet_tunnels.h"
40 #include "gnunet-service-cadet_paths.h"
41
42 #define LOG(level,...) GNUNET_log_from (level,"cadet-chn",__VA_ARGS__)
43
44 /**
45  * How long do we initially wait before retransmitting?
46  */
47 #define CADET_INITIAL_RETRANSMIT_TIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
48
49 /**
50  * How long do we wait before dropping state about incoming
51  * connection to closed port?
52  */
53 #define TIMEOUT_CLOSED_PORT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
54
55 /**
56  * How long do we wait at least before retransmitting ever?
57  */
58 #define MIN_RTT_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 75)
59
60 /**
61  * Maximum message ID into the future we accept for out-of-order messages.
62  * If the message is more than this into the future, we drop it.  This is
63  * important both to detect values that are actually in the past, as well
64  * as to limit adversarially triggerable memory consumption.
65  *
66  * Note that right now we have "max_pending_messages = 4" hard-coded in
67  * the logic below, so a value of 4 would suffice here. But we plan to
68  * allow larger windows in the future...
69  */
70 #define MAX_OUT_OF_ORDER_DISTANCE 1024
71
72
73 /**
74  * All the states a channel can be in.
75  */
76 enum CadetChannelState
77 {
78   /**
79    * Uninitialized status, should never appear in operation.
80    */
81   CADET_CHANNEL_NEW,
82
83   /**
84    * Channel is to a port that is not open, we're waiting for the
85    * port to be opened.
86    */
87   CADET_CHANNEL_LOOSE,
88
89   /**
90    * CHANNEL_OPEN message sent, waiting for CHANNEL_OPEN_ACK.
91    */
92   CADET_CHANNEL_OPEN_SENT,
93
94   /**
95    * Connection confirmed, ready to carry traffic.
96    */
97   CADET_CHANNEL_READY
98 };
99
100
101 /**
102  * Info needed to retry a message in case it gets lost.
103  * Note that we DO use this structure also for unreliable
104  * messages.
105  */
106 struct CadetReliableMessage
107 {
108   /**
109    * Double linked list, FIFO style
110    */
111   struct CadetReliableMessage *next;
112
113   /**
114    * Double linked list, FIFO style
115    */
116   struct CadetReliableMessage *prev;
117
118   /**
119    * Which channel is this message in?
120    */
121   struct CadetChannel *ch;
122
123   /**
124    * Entry in the tunnels queue for this message, NULL if it has left
125    * the tunnel.  Used to cancel transmission in case we receive an
126    * ACK in time.
127    */
128   struct CadetTunnelQueueEntry *qe;
129
130   /**
131    * Data message we are trying to send.
132    */
133   struct GNUNET_CADET_ChannelAppDataMessage *data_message;
134
135   /**
136    * How soon should we retry if we fail to get an ACK?
137    * Messages in the queue are sorted by this value.
138    */
139   struct GNUNET_TIME_Absolute next_retry;
140
141   /**
142    * How long do we wait for an ACK after transmission?
143    * Use for the back-off calculation.
144    */
145   struct GNUNET_TIME_Relative retry_delay;
146
147   /**
148    * Time when we first successfully transmitted the message
149    * (that is, set @e num_transmissions to 1).
150    */
151   struct GNUNET_TIME_Absolute first_transmission_time;
152
153   /**
154    * Identifier of the connection that this message took when it
155    * was first transmitted.  Only useful if @e num_transmissions is 1.
156    */
157   struct GNUNET_CADET_ConnectionTunnelIdentifier connection_taken;
158
159   /**
160    * How often was this message transmitted?  #GNUNET_SYSERR if there
161    * was an error transmitting the message, #GNUNET_NO if it was not
162    * yet transmitted ever, otherwise the number of (re) transmissions.
163    */
164   int num_transmissions;
165
166 };
167
168
169 /**
170  * List of received out-of-order data messages.
171  */
172 struct CadetOutOfOrderMessage
173 {
174   /**
175    * Double linked list, FIFO style
176    */
177   struct CadetOutOfOrderMessage *next;
178
179   /**
180    * Double linked list, FIFO style
181    */
182   struct CadetOutOfOrderMessage *prev;
183
184   /**
185    * ID of the message (messages up to this point needed
186    * before we give this one to the client).
187    */
188   struct ChannelMessageIdentifier mid;
189
190   /**
191    * The envelope with the payload of the out-of-order message
192    */
193   struct GNUNET_MQ_Envelope *env;
194
195 };
196
197
198 /**
199  * Client endpoint of a `struct CadetChannel`.  A channel may be a
200  * loopback channel, in which case it has two of these endpoints.
201  * Note that flow control also is required in both directions.
202  */
203 struct CadetChannelClient
204 {
205   /**
206    * Client handle.  Not by itself sufficient to designate
207    * the client endpoint, as the same client handle may
208    * be used for both the owner and the destination, and
209    * we thus also need the channel ID to identify the client.
210    */
211   struct CadetClient *c;
212
213   /**
214    * Head of DLL of messages received out of order or while client was unready.
215    */
216   struct CadetOutOfOrderMessage *head_recv;
217
218   /**
219    * Tail DLL of messages received out of order or while client was unready.
220    */
221   struct CadetOutOfOrderMessage *tail_recv;
222
223   /**
224    * Local tunnel number for this client.
225    * (if owner >= #GNUNET_CADET_LOCAL_CHANNEL_ID_CLI,
226    *  otherwise < #GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
227    */
228   struct GNUNET_CADET_ClientChannelNumber ccn;
229
230   /**
231    * Number of entries currently in @a head_recv DLL.
232    */
233   unsigned int num_recv;
234
235   /**
236    * Can we send data to the client?
237    */
238   int client_ready;
239
240 };
241
242
243 /**
244  * Struct containing all information regarding a channel to a remote client.
245  */
246 struct CadetChannel
247 {
248   /**
249    * Tunnel this channel is in.
250    */
251   struct CadetTunnel *t;
252
253   /**
254    * Client owner of the tunnel, if any.
255    * (Used if this channel represends the initiating end of the tunnel.)
256    */
257   struct CadetChannelClient *owner;
258
259   /**
260    * Client destination of the tunnel, if any.
261    * (Used if this channel represents the listening end of the tunnel.)
262    */
263   struct CadetChannelClient *dest;
264
265   /**
266    * Last entry in the tunnel's queue relating to control messages
267    * (#GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN or
268    * #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK).  Used to cancel
269    * transmission in case we receive updated information.
270    */
271   struct CadetTunnelQueueEntry *last_control_qe;
272
273   /**
274    * Head of DLL of messages sent and not yet ACK'd.
275    */
276   struct CadetReliableMessage *head_sent;
277
278   /**
279    * Tail of DLL of messages sent and not yet ACK'd.
280    */
281   struct CadetReliableMessage *tail_sent;
282
283   /**
284    * Task to resend/poll in case no ACK is received.
285    */
286   struct GNUNET_SCHEDULER_Task *retry_control_task;
287
288   /**
289    * Task to resend/poll in case no ACK is received.
290    */
291   struct GNUNET_SCHEDULER_Task *retry_data_task;
292
293   /**
294    * Last time the channel was used
295    */
296   struct GNUNET_TIME_Absolute timestamp;
297
298   /**
299    * Destination port of the channel.
300    */
301   struct GNUNET_HashCode port;
302
303   /**
304    * Hash'ed port of the channel with initiator and destination PID.
305    */
306   struct GNUNET_HashCode h_port;
307
308   /**
309    * Counter for exponential backoff.
310    */
311   struct GNUNET_TIME_Relative retry_time;
312
313   /**
314    * Bitfield of already-received messages past @e mid_recv.
315    */
316   uint64_t mid_futures;
317
318   /**
319    * Next MID expected for incoming traffic.
320    */
321   struct ChannelMessageIdentifier mid_recv;
322
323   /**
324    * Next MID to use for outgoing traffic.
325    */
326   struct ChannelMessageIdentifier mid_send;
327
328   /**
329    * Total (reliable) messages pending ACK for this channel.
330    */
331   unsigned int pending_messages;
332
333   /**
334    * Maximum (reliable) messages pending ACK for this channel
335    * before we throttle the client.
336    */
337   unsigned int max_pending_messages;
338
339   /**
340    * Number identifying this channel in its tunnel.
341    */
342   struct GNUNET_CADET_ChannelTunnelNumber ctn;
343
344   /**
345    * Channel state.
346    */
347   enum CadetChannelState state;
348
349   /**
350    * Count how many ACKs we skipped, used to prevent long
351    * sequences of ACK skipping.
352    */
353   unsigned int skip_ack_series;
354
355   /**
356    * Is the tunnel bufferless (minimum latency)?
357    */
358   int nobuffer;
359
360   /**
361    * Is the tunnel reliable?
362    */
363   int reliable;
364
365   /**
366    * Is the tunnel out-of-order?
367    */
368   int out_of_order;
369
370   /**
371    * Is this channel a loopback channel, where the destination is us again?
372    */
373   int is_loopback;
374
375   /**
376    * Flag to signal the destruction of the channel.  If this is set to
377    * #GNUNET_YES the channel will be destroyed once the queue is
378    * empty.
379    */
380   int destroy;
381
382 };
383
384
385 /**
386  * Get the static string for identification of the channel.
387  *
388  * @param ch Channel.
389  *
390  * @return Static string with the channel IDs.
391  */
392 const char *
393 GCCH_2s (const struct CadetChannel *ch)
394 {
395   static char buf[128];
396
397   GNUNET_snprintf (buf,
398                    sizeof (buf),
399                    "Channel %s:%s ctn:%X(%X/%X)",
400                    (GNUNET_YES == ch->is_loopback)
401                    ? "loopback"
402                    : GNUNET_i2s (GCP_get_id (GCT_get_destination (ch->t))),
403                    GNUNET_h2s (&ch->port),
404                    ch->ctn,
405                    (NULL == ch->owner) ? 0 : ntohl (ch->owner->ccn.channel_of_client),
406                    (NULL == ch->dest) ? 0 : ntohl (ch->dest->ccn.channel_of_client));
407   return buf;
408 }
409
410
411 /**
412  * Hash the @a port and @a initiator and @a listener to
413  * calculate the "challenge" @a h_port we send to the other
414  * peer on #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN.
415  *
416  * @param[out] h_port set to the hash of @a port, @a initiator and @a listener
417  * @param port cadet port, as seen by CADET clients
418  * @param listener peer that is listining on @a port
419  */
420 void
421 GCCH_hash_port (struct GNUNET_HashCode *h_port,
422                 const struct GNUNET_HashCode *port,
423                 const struct GNUNET_PeerIdentity *listener)
424 {
425   struct GNUNET_HashContext *hc;
426
427   hc = GNUNET_CRYPTO_hash_context_start ();
428   GNUNET_CRYPTO_hash_context_read (hc,
429                                    port,
430                                    sizeof (*port));
431   GNUNET_CRYPTO_hash_context_read (hc,
432                                    listener,
433                                    sizeof (*listener));
434   GNUNET_CRYPTO_hash_context_finish (hc,
435                                      h_port);
436   LOG (GNUNET_ERROR_TYPE_DEBUG,
437        "Calculated port hash %s\n",
438        GNUNET_h2s (h_port));
439 }
440
441
442 /**
443  * Get the channel's public ID.
444  *
445  * @param ch Channel.
446  *
447  * @return ID used to identify the channel with the remote peer.
448  */
449 struct GNUNET_CADET_ChannelTunnelNumber
450 GCCH_get_id (const struct CadetChannel *ch)
451 {
452   return ch->ctn;
453 }
454
455
456 /**
457  * Release memory associated with @a ccc
458  *
459  * @param ccc data structure to clean up
460  */
461 static void
462 free_channel_client (struct CadetChannelClient *ccc)
463 {
464   struct CadetOutOfOrderMessage *com;
465
466   while (NULL != (com = ccc->head_recv))
467   {
468     GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
469                                  ccc->tail_recv,
470                                  com);
471     ccc->num_recv--;
472     GNUNET_MQ_discard (com->env);
473     GNUNET_free (com);
474   }
475   GNUNET_free (ccc);
476 }
477
478
479 /**
480  * Destroy the given channel.
481  *
482  * @param ch channel to destroy
483  */
484 static void
485 channel_destroy (struct CadetChannel *ch)
486 {
487   struct CadetReliableMessage *crm;
488
489   while (NULL != (crm = ch->head_sent))
490   {
491     GNUNET_assert (ch == crm->ch);
492     if (NULL != crm->qe)
493     {
494       GCT_send_cancel (crm->qe);
495       crm->qe = NULL;
496     }
497     GNUNET_CONTAINER_DLL_remove (ch->head_sent,
498                                  ch->tail_sent,
499                                  crm);
500     GNUNET_free (crm->data_message);
501     GNUNET_free (crm);
502   }
503   if (CADET_CHANNEL_LOOSE == ch->state)
504   {
505     GSC_drop_loose_channel (&ch->h_port,
506                             ch);
507   }
508   if (NULL != ch->owner)
509   {
510     free_channel_client (ch->owner);
511     ch->owner = NULL;
512   }
513   if (NULL != ch->dest)
514   {
515     free_channel_client (ch->dest);
516     ch->dest = NULL;
517   }
518   if (NULL != ch->last_control_qe)
519   {
520     GCT_send_cancel (ch->last_control_qe);
521     ch->last_control_qe = NULL;
522   }
523   if (NULL != ch->retry_data_task)
524   {
525     GNUNET_SCHEDULER_cancel (ch->retry_data_task);
526     ch->retry_data_task = NULL;
527   }
528   if (NULL != ch->retry_control_task)
529   {
530     GNUNET_SCHEDULER_cancel (ch->retry_control_task);
531     ch->retry_control_task = NULL;
532   }
533   if (GNUNET_NO == ch->is_loopback)
534   {
535     GCT_remove_channel (ch->t,
536                         ch,
537                         ch->ctn);
538     ch->t = NULL;
539   }
540   GNUNET_free (ch);
541 }
542
543
544 /**
545  * Send a channel create message.
546  *
547  * @param cls Channel for which to send.
548  */
549 static void
550 send_channel_open (void *cls);
551
552
553 /**
554  * Function called once the tunnel confirms that we sent the
555  * create message.  Delays for a bit until we retry.
556  *
557  * @param cls our `struct CadetChannel`.
558  * @param cid identifier of the connection within the tunnel, NULL
559  *            if transmission failed
560  */
561 static void
562 channel_open_sent_cb (void *cls,
563                       const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid)
564 {
565   struct CadetChannel *ch = cls;
566
567   GNUNET_assert (NULL != ch->last_control_qe);
568   ch->last_control_qe = NULL;
569   ch->retry_time = GNUNET_TIME_STD_BACKOFF (ch->retry_time);
570   LOG (GNUNET_ERROR_TYPE_DEBUG,
571        "Sent CADET_CHANNEL_OPEN on %s, retrying in %s\n",
572        GCCH_2s (ch),
573        GNUNET_STRINGS_relative_time_to_string (ch->retry_time,
574                                                GNUNET_YES));
575   ch->retry_control_task
576     = GNUNET_SCHEDULER_add_delayed (ch->retry_time,
577                                     &send_channel_open,
578                                     ch);
579 }
580
581
582 /**
583  * Send a channel open message.
584  *
585  * @param cls Channel for which to send.
586  */
587 static void
588 send_channel_open (void *cls)
589 {
590   struct CadetChannel *ch = cls;
591   struct GNUNET_CADET_ChannelOpenMessage msgcc;
592   uint32_t options;
593
594   ch->retry_control_task = NULL;
595   LOG (GNUNET_ERROR_TYPE_DEBUG,
596        "Sending CHANNEL_OPEN message for %s\n",
597        GCCH_2s (ch));
598   options = 0;
599   if (ch->nobuffer)
600     options |= GNUNET_CADET_OPTION_NOBUFFER;
601   if (ch->reliable)
602     options |= GNUNET_CADET_OPTION_RELIABLE;
603   if (ch->out_of_order)
604     options |= GNUNET_CADET_OPTION_OUT_OF_ORDER;
605   msgcc.header.size = htons (sizeof (msgcc));
606   msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN);
607   msgcc.opt = htonl (options);
608   msgcc.h_port = ch->h_port;
609   msgcc.ctn = ch->ctn;
610   ch->state = CADET_CHANNEL_OPEN_SENT;
611   if (NULL != ch->last_control_qe)
612     GCT_send_cancel (ch->last_control_qe);
613   ch->last_control_qe = GCT_send (ch->t,
614                                   &msgcc.header,
615                                   &channel_open_sent_cb,
616                                   ch);
617   GNUNET_assert (NULL == ch->retry_control_task);
618 }
619
620
621 /**
622  * Function called once and only once after a channel was bound
623  * to its tunnel via #GCT_add_channel() is ready for transmission.
624  * Note that this is only the case for channels that this peer
625  * initiates, as for incoming channels we assume that they are
626  * ready for transmission immediately upon receiving the open
627  * message.  Used to bootstrap the #GCT_send() process.
628  *
629  * @param ch the channel for which the tunnel is now ready
630  */
631 void
632 GCCH_tunnel_up (struct CadetChannel *ch)
633 {
634   GNUNET_assert (NULL == ch->retry_control_task);
635   LOG (GNUNET_ERROR_TYPE_DEBUG,
636        "Tunnel up, sending CHANNEL_OPEN on %s now\n",
637        GCCH_2s (ch));
638   ch->retry_control_task
639     = GNUNET_SCHEDULER_add_now (&send_channel_open,
640                                 ch);
641 }
642
643
644 /**
645  * Create a new channel.
646  *
647  * @param owner local client owning the channel
648  * @param ccn local number of this channel at the @a owner
649  * @param destination peer to which we should build the channel
650  * @param port desired port at @a destination
651  * @param options options for the channel
652  * @return handle to the new channel
653  */
654 struct CadetChannel *
655 GCCH_channel_local_new (struct CadetClient *owner,
656                         struct GNUNET_CADET_ClientChannelNumber ccn,
657                         struct CadetPeer *destination,
658                         const struct GNUNET_HashCode *port,
659                         uint32_t options)
660 {
661   struct CadetChannel *ch;
662   struct CadetChannelClient *ccco;
663
664   ccco = GNUNET_new (struct CadetChannelClient);
665   ccco->c = owner;
666   ccco->ccn = ccn;
667   ccco->client_ready = GNUNET_YES;
668
669   ch = GNUNET_new (struct CadetChannel);
670   ch->mid_recv.mid = htonl (1); /* The OPEN_ACK counts as message 0! */
671   ch->nobuffer = (0 != (options & GNUNET_CADET_OPTION_NOBUFFER));
672   ch->reliable = (0 != (options & GNUNET_CADET_OPTION_RELIABLE));
673   ch->out_of_order = (0 != (options & GNUNET_CADET_OPTION_OUT_OF_ORDER));
674   ch->max_pending_messages = (ch->nobuffer) ? 1 : 4; /* FIXME: 4!? Do not hardcode! */
675   ch->owner = ccco;
676   ch->port = *port;
677   GCCH_hash_port (&ch->h_port,
678                   port,
679                   GCP_get_id (destination));
680   if (0 == memcmp (&my_full_id,
681                    GCP_get_id (destination),
682                    sizeof (struct GNUNET_PeerIdentity)))
683   {
684     struct OpenPort *op;
685
686     ch->is_loopback = GNUNET_YES;
687     op = GNUNET_CONTAINER_multihashmap_get (open_ports,
688                                             &ch->h_port);
689     if (NULL == op)
690     {
691       /* port closed, wait for it to possibly open */
692       ch->state = CADET_CHANNEL_LOOSE;
693       (void) GNUNET_CONTAINER_multihashmap_put (loose_channels,
694                                                 &ch->h_port,
695                                                 ch,
696                                                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
697       LOG (GNUNET_ERROR_TYPE_DEBUG,
698            "Created loose incoming loopback channel to port %s\n",
699            GNUNET_h2s (&ch->port));
700     }
701     else
702     {
703       GCCH_bind (ch,
704                  op->c,
705                  &op->port);
706     }
707   }
708   else
709   {
710     ch->t = GCP_get_tunnel (destination,
711                             GNUNET_YES);
712     ch->retry_time = CADET_INITIAL_RETRANSMIT_TIME;
713     ch->ctn = GCT_add_channel (ch->t,
714                                ch);
715   }
716   GNUNET_STATISTICS_update (stats,
717                             "# channels",
718                             1,
719                             GNUNET_NO);
720   LOG (GNUNET_ERROR_TYPE_DEBUG,
721        "Created channel to port %s at peer %s for %s using %s\n",
722        GNUNET_h2s (port),
723        GCP_2s (destination),
724        GSC_2s (owner),
725        (GNUNET_YES == ch->is_loopback) ? "loopback" : GCT_2s (ch->t));
726   return ch;
727 }
728
729
730 /**
731  * We had an incoming channel to a port that is closed.
732  * It has not been opened for a while, drop it.
733  *
734  * @param cls the channel to drop
735  */
736 static void
737 timeout_closed_cb (void *cls)
738 {
739   struct CadetChannel *ch = cls;
740
741   ch->retry_control_task = NULL;
742   LOG (GNUNET_ERROR_TYPE_DEBUG,
743        "Closing incoming channel to port %s from peer %s due to timeout\n",
744        GNUNET_h2s (&ch->port),
745        GCP_2s (GCT_get_destination (ch->t)));
746   channel_destroy (ch);
747 }
748
749
750 /**
751  * Create a new channel based on a request coming in over the network.
752  *
753  * @param t tunnel to the remote peer
754  * @param ctn identifier of this channel in the tunnel
755  * @param h_port desired hash of local port
756  * @param options options for the channel
757  * @return handle to the new channel
758  */
759 struct CadetChannel *
760 GCCH_channel_incoming_new (struct CadetTunnel *t,
761                            struct GNUNET_CADET_ChannelTunnelNumber ctn,
762                            const struct GNUNET_HashCode *h_port,
763                            uint32_t options)
764 {
765   struct CadetChannel *ch;
766   struct OpenPort *op;
767
768   ch = GNUNET_new (struct CadetChannel);
769   ch->h_port = *h_port;
770   ch->t = t;
771   ch->ctn = ctn;
772   ch->retry_time = CADET_INITIAL_RETRANSMIT_TIME;
773   ch->nobuffer = (0 != (options & GNUNET_CADET_OPTION_NOBUFFER));
774   ch->reliable = (0 != (options & GNUNET_CADET_OPTION_RELIABLE));
775   ch->out_of_order = (0 != (options & GNUNET_CADET_OPTION_OUT_OF_ORDER));
776   ch->max_pending_messages = (ch->nobuffer) ? 1 : 4; /* FIXME: 4!? Do not hardcode! */
777   GNUNET_STATISTICS_update (stats,
778                             "# channels",
779                             1,
780                             GNUNET_NO);
781
782   op = GNUNET_CONTAINER_multihashmap_get (open_ports,
783                                           h_port);
784   if (NULL == op)
785   {
786     /* port closed, wait for it to possibly open */
787     ch->state = CADET_CHANNEL_LOOSE;
788     (void) GNUNET_CONTAINER_multihashmap_put (loose_channels,
789                                               &ch->h_port,
790                                               ch,
791                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
792     GNUNET_assert (NULL == ch->retry_control_task);
793     ch->retry_control_task
794       = GNUNET_SCHEDULER_add_delayed (TIMEOUT_CLOSED_PORT,
795                                       &timeout_closed_cb,
796                                       ch);
797     LOG (GNUNET_ERROR_TYPE_DEBUG,
798          "Created loose incoming channel to port %s from peer %s\n",
799          GNUNET_h2s (&ch->port),
800          GCP_2s (GCT_get_destination (ch->t)));
801   }
802   else
803   {
804     GCCH_bind (ch,
805                op->c,
806                &op->port);
807   }
808   GNUNET_STATISTICS_update (stats,
809                             "# channels",
810                             1,
811                             GNUNET_NO);
812   return ch;
813 }
814
815
816 /**
817  * Function called once the tunnel confirms that we sent the
818  * ACK message.  Just remembers it was sent, we do not expect
819  * ACKs for ACKs ;-).
820  *
821  * @param cls our `struct CadetChannel`.
822  * @param cid identifier of the connection within the tunnel, NULL
823  *            if transmission failed
824  */
825 static void
826 send_ack_cb (void *cls,
827              const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid)
828 {
829   struct CadetChannel *ch = cls;
830
831   GNUNET_assert (NULL != ch->last_control_qe);
832   ch->last_control_qe = NULL;
833 }
834
835
836 /**
837  * Compute and send the current #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK to the other peer.
838  *
839  * @param ch channel to send the #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK for
840  */
841 static void
842 send_channel_data_ack (struct CadetChannel *ch)
843 {
844   struct GNUNET_CADET_ChannelDataAckMessage msg;
845
846   if (GNUNET_NO == ch->reliable)
847     return; /* no ACKs */
848   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK);
849   msg.header.size = htons (sizeof (msg));
850   msg.ctn = ch->ctn;
851   msg.mid.mid = htonl (ntohl (ch->mid_recv.mid));
852   msg.futures = GNUNET_htonll (ch->mid_futures);
853   LOG (GNUNET_ERROR_TYPE_DEBUG,
854        "Sending DATA_ACK %u:%llX via %s\n",
855        (unsigned int) ntohl (msg.mid.mid),
856        (unsigned long long) ch->mid_futures,
857        GCCH_2s (ch));
858   if (NULL != ch->last_control_qe)
859     GCT_send_cancel (ch->last_control_qe);
860   ch->last_control_qe = GCT_send (ch->t,
861                                   &msg.header,
862                                   &send_ack_cb,
863                                   ch);
864 }
865
866
867 /**
868  * Send our initial #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK to the client confirming that the
869  * connection is up.
870  *
871  * @param cls the `struct CadetChannel`
872  */
873 static void
874 send_open_ack (void *cls)
875 {
876   struct CadetChannel *ch = cls;
877   struct GNUNET_CADET_ChannelOpenAckMessage msg;
878
879   ch->retry_control_task = NULL;
880   LOG (GNUNET_ERROR_TYPE_DEBUG,
881        "Sending CHANNEL_OPEN_ACK on %s\n",
882        GCCH_2s (ch));
883   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK);
884   msg.header.size = htons (sizeof (msg));
885   msg.reserved = htonl (0);
886   msg.ctn = ch->ctn;
887   msg.port = ch->port;
888   if (NULL != ch->last_control_qe)
889     GCT_send_cancel (ch->last_control_qe);
890   ch->last_control_qe = GCT_send (ch->t,
891                                   &msg.header,
892                                   &send_ack_cb,
893                                   ch);
894 }
895
896
897 /**
898  * We got a #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN message again for
899  * this channel.  If the binding was successful, (re)transmit the
900  * #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK.
901  *
902  * @param ch channel that got the duplicate open
903  * @param cti identifier of the connection that delivered the message
904  */
905 void
906 GCCH_handle_duplicate_open (struct CadetChannel *ch,
907                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti)
908 {
909   if (NULL == ch->dest)
910   {
911     LOG (GNUNET_ERROR_TYPE_DEBUG,
912          "Ignoring duplicate CHANNEL_OPEN on %s: port is closed\n",
913          GCCH_2s (ch));
914     return;
915   }
916   if (NULL != ch->retry_control_task)
917   {
918     LOG (GNUNET_ERROR_TYPE_DEBUG,
919          "Ignoring duplicate CHANNEL_OPEN on %s: control message is pending\n",
920          GCCH_2s (ch));
921     return;
922   }
923   LOG (GNUNET_ERROR_TYPE_DEBUG,
924        "Retransmitting CHANNEL_OPEN_ACK on %s\n",
925        GCCH_2s (ch));
926   ch->retry_control_task
927     = GNUNET_SCHEDULER_add_now (&send_open_ack,
928                                 ch);
929 }
930
931
932 /**
933  * Send a #GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK to the client to solicit more messages.
934  *
935  * @param ch channel the ack is for
936  * @param to_owner #GNUNET_YES to send to owner,
937  *                 #GNUNET_NO to send to dest
938  */
939 static void
940 send_ack_to_client (struct CadetChannel *ch,
941                     int to_owner)
942 {
943   struct GNUNET_MQ_Envelope *env;
944   struct GNUNET_CADET_LocalAck *ack;
945   struct CadetChannelClient *ccc;
946
947   ccc = (GNUNET_YES == to_owner) ? ch->owner : ch->dest;
948   if (NULL == ccc)
949   {
950     /* This can happen if we are just getting ACKs after
951        our local client already disconnected. */
952     GNUNET_assert (GNUNET_YES == ch->destroy);
953     return;
954   }
955   env = GNUNET_MQ_msg (ack,
956                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
957   ack->ccn = ccc->ccn;
958   LOG (GNUNET_ERROR_TYPE_DEBUG,
959        "Sending CADET_LOCAL_ACK to %s (%s) at ccn %X (%u/%u pending)\n",
960        GSC_2s (ccc->c),
961        (GNUNET_YES == to_owner) ? "owner" : "dest",
962        ntohl (ack->ccn.channel_of_client),
963        ch->pending_messages,
964        ch->max_pending_messages);
965   GSC_send_to_client (ccc->c,
966                       env);
967 }
968
969
970 /**
971  * A client is bound to the port that we have a channel
972  * open to.  Send the acknowledgement for the connection
973  * request and establish the link with the client.
974  *
975  * @param ch open incoming channel
976  * @param c client listening on the respective @a port
977  * @param port the port @a is listening on
978  */
979 void
980 GCCH_bind (struct CadetChannel *ch,
981            struct CadetClient *c,
982            const struct GNUNET_HashCode *port)
983 {
984   uint32_t options;
985   struct CadetChannelClient *cccd;
986
987   LOG (GNUNET_ERROR_TYPE_DEBUG,
988        "Binding %s from %s to port %s of %s\n",
989        GCCH_2s (ch),
990        GCT_2s (ch->t),
991        GNUNET_h2s (&ch->port),
992        GSC_2s (c));
993   if (NULL != ch->retry_control_task)
994   {
995     /* there might be a timeout task here */
996     GNUNET_SCHEDULER_cancel (ch->retry_control_task);
997     ch->retry_control_task = NULL;
998   }
999   options = 0;
1000   if (ch->nobuffer)
1001     options |= GNUNET_CADET_OPTION_NOBUFFER;
1002   if (ch->reliable)
1003     options |= GNUNET_CADET_OPTION_RELIABLE;
1004   if (ch->out_of_order)
1005     options |= GNUNET_CADET_OPTION_OUT_OF_ORDER;
1006   cccd = GNUNET_new (struct CadetChannelClient);
1007   GNUNET_assert (NULL == ch->dest);
1008   ch->dest = cccd;
1009   ch->port = *port;
1010   cccd->c = c;
1011   cccd->client_ready = GNUNET_YES;
1012   cccd->ccn = GSC_bind (c,
1013                         ch,
1014                         (GNUNET_YES == ch->is_loopback)
1015                         ? GCP_get (&my_full_id,
1016                                    GNUNET_YES)
1017                         : GCT_get_destination (ch->t),
1018                         port,
1019                         options);
1020   GNUNET_assert (ntohl (cccd->ccn.channel_of_client) <
1021                  GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
1022   ch->mid_recv.mid = htonl (1); /* The OPEN counts as message 0! */
1023   if (GNUNET_YES == ch->is_loopback)
1024   {
1025     ch->state = CADET_CHANNEL_OPEN_SENT;
1026     GCCH_handle_channel_open_ack (ch,
1027                                   NULL,
1028                                   port);
1029   }
1030   else
1031   {
1032     /* notify other peer that we accepted the connection */
1033     ch->state = CADET_CHANNEL_READY;
1034     ch->retry_control_task
1035       = GNUNET_SCHEDULER_add_now (&send_open_ack,
1036                                   ch);
1037   }
1038   /* give client it's initial supply of ACKs */
1039   GNUNET_assert (ntohl (cccd->ccn.channel_of_client) <
1040                  GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
1041   for (unsigned int i=0;i<ch->max_pending_messages;i++)
1042     send_ack_to_client (ch,
1043                         GNUNET_NO);
1044 }
1045
1046
1047 /**
1048  * One of our clients has disconnected, tell the other one that we
1049  * are finished. Done asynchronously to avoid concurrent modification
1050  * issues if this is the same client.
1051  *
1052  * @param cls the `struct CadetChannel` where one of the ends is now dead
1053  */
1054 static void
1055 signal_remote_destroy_cb (void *cls)
1056 {
1057   struct CadetChannel *ch = cls;
1058   struct CadetChannelClient *ccc;
1059
1060   /* Find which end is left... */
1061   ch->retry_control_task = NULL;
1062   ccc = (NULL != ch->owner) ? ch->owner : ch->dest;
1063   GSC_handle_remote_channel_destroy (ccc->c,
1064                                      ccc->ccn,
1065                                      ch);
1066   channel_destroy (ch);
1067 }
1068
1069
1070 /**
1071  * Destroy locally created channel.  Called by the local client, so no
1072  * need to tell the client.
1073  *
1074  * @param ch channel to destroy
1075  * @param c client that caused the destruction
1076  * @param ccn client number of the client @a c
1077  */
1078 void
1079 GCCH_channel_local_destroy (struct CadetChannel *ch,
1080                             struct CadetClient *c,
1081                             struct GNUNET_CADET_ClientChannelNumber ccn)
1082 {
1083   LOG (GNUNET_ERROR_TYPE_DEBUG,
1084        "%s asks for destruction of %s\n",
1085        GSC_2s (c),
1086        GCCH_2s (ch));
1087   GNUNET_assert (NULL != c);
1088   if ( (NULL != ch->owner) &&
1089        (c == ch->owner->c) &&
1090        (ccn.channel_of_client == ch->owner->ccn.channel_of_client) )
1091   {
1092     free_channel_client (ch->owner);
1093     ch->owner = NULL;
1094   }
1095   else if ( (NULL != ch->dest) &&
1096             (c == ch->dest->c) &&
1097             (ccn.channel_of_client == ch->dest->ccn.channel_of_client) )
1098   {
1099     free_channel_client (ch->dest);
1100     ch->dest = NULL;
1101   }
1102   else
1103   {
1104     GNUNET_assert (0);
1105   }
1106
1107   if (GNUNET_YES == ch->destroy)
1108   {
1109     /* other end already destroyed, with the local client gone, no need
1110        to finish transmissions, just destroy immediately. */
1111     channel_destroy (ch);
1112     return;
1113   }
1114   if ( (NULL != ch->head_sent) &&
1115        ( (NULL != ch->owner) ||
1116          (NULL != ch->dest) ) )
1117   {
1118     /* Wait for other end to destroy us as well,
1119        and otherwise allow send queue to be transmitted first */
1120     ch->destroy = GNUNET_YES;
1121     return;
1122   }
1123   if ( (GNUNET_YES == ch->is_loopback) &&
1124        ( (NULL != ch->owner) ||
1125          (NULL != ch->dest) ) )
1126   {
1127     if (NULL != ch->retry_control_task)
1128       GNUNET_SCHEDULER_cancel (ch->retry_control_task);
1129     ch->retry_control_task
1130       = GNUNET_SCHEDULER_add_now (&signal_remote_destroy_cb,
1131                                   ch);
1132     return;
1133   }
1134   if (GNUNET_NO == ch->is_loopback)
1135   {
1136     /* If the we ever sent the CHANNEL_CREATE, we need to send a destroy message. */
1137     switch (ch->state)
1138     {
1139     case CADET_CHANNEL_NEW:
1140       /* We gave up on a channel that we created as a client to a remote
1141          target, but that never went anywhere. Nothing to do here. */
1142       break;
1143     case CADET_CHANNEL_LOOSE:
1144       break;
1145     default:
1146       GCT_send_channel_destroy (ch->t,
1147                                 ch->ctn);
1148     }
1149   }
1150   /* Nothing left to do, just finish destruction */
1151   channel_destroy (ch);
1152 }
1153
1154
1155 /**
1156  * We got an acknowledgement for the creation of the channel
1157  * (the port is open on the other side).  Verify that the
1158  * other end really has the right port, and begin transmissions.
1159  *
1160  * @param ch channel to destroy
1161  * @param cti identifier of the connection that delivered the message
1162  * @param port port number (needed to verify receiver knows the port)
1163  */
1164 void
1165 GCCH_handle_channel_open_ack (struct CadetChannel *ch,
1166                               const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti,
1167                               const struct GNUNET_HashCode *port)
1168 {
1169   switch (ch->state)
1170   {
1171   case CADET_CHANNEL_NEW:
1172     /* this should be impossible */
1173     GNUNET_break (0);
1174     break;
1175   case CADET_CHANNEL_LOOSE:
1176     /* This makes no sense. */
1177     GNUNET_break_op (0);
1178     break;
1179   case CADET_CHANNEL_OPEN_SENT:
1180     if (NULL == ch->owner)
1181     {
1182       /* We're not the owner, wrong direction! */
1183       GNUNET_break_op (0);
1184       return;
1185     }
1186     if (0 != memcmp (&ch->port,
1187                      port,
1188                      sizeof (struct GNUNET_HashCode)))
1189     {
1190       /* Other peer failed to provide the right port,
1191          refuse connection. */
1192       GNUNET_break_op (0);
1193       return;
1194     }
1195     LOG (GNUNET_ERROR_TYPE_DEBUG,
1196          "Received CHANNEL_OPEN_ACK for waiting %s, entering READY state\n",
1197          GCCH_2s (ch));
1198     if (NULL != ch->retry_control_task) /* can be NULL if ch->is_loopback */
1199     {
1200       GNUNET_SCHEDULER_cancel (ch->retry_control_task);
1201       ch->retry_control_task = NULL;
1202     }
1203     ch->state = CADET_CHANNEL_READY;
1204     /* On first connect, send client as many ACKs as we allow messages
1205        to be buffered! */
1206     for (unsigned int i=0;i<ch->max_pending_messages;i++)
1207       send_ack_to_client (ch,
1208                           GNUNET_YES);
1209     break;
1210   case CADET_CHANNEL_READY:
1211     /* duplicate ACK, maybe we retried the CREATE. Ignore. */
1212     LOG (GNUNET_ERROR_TYPE_DEBUG,
1213          "Received duplicate channel OPEN_ACK for %s\n",
1214          GCCH_2s (ch));
1215     GNUNET_STATISTICS_update (stats,
1216                               "# duplicate CREATE_ACKs",
1217                               1,
1218                               GNUNET_NO);
1219     break;
1220   }
1221 }
1222
1223
1224 /**
1225  * Test if element @a e1 comes before element @a e2.
1226  *
1227  * @param cls closure, to a flag where we indicate duplicate packets
1228  * @param m1 a message of to sort
1229  * @param m2 another message to sort
1230  * @return #GNUNET_YES if @e1 < @e2, otherwise #GNUNET_NO
1231  */
1232 static int
1233 is_before (void *cls,
1234            struct CadetOutOfOrderMessage *m1,
1235            struct CadetOutOfOrderMessage *m2)
1236 {
1237   int *duplicate = cls;
1238   uint32_t v1 = ntohl (m1->mid.mid);
1239   uint32_t v2 = ntohl (m2->mid.mid);
1240   uint32_t delta;
1241
1242   delta = v2 - v1;
1243   if (0 == delta)
1244     *duplicate = GNUNET_YES;
1245   if (delta > (uint32_t) INT_MAX)
1246   {
1247     /* in overflow range, we can safely assume we wrapped around */
1248     return GNUNET_NO;
1249   }
1250   else
1251   {
1252     /* result is small, thus v2 > v1, thus m1 < m2 */
1253     return GNUNET_YES;
1254   }
1255 }
1256
1257
1258 /**
1259  * We got payload data for a channel.  Pass it on to the client
1260  * and send an ACK to the other end (once flow control allows it!)
1261  *
1262  * @param ch channel that got data
1263  * @param cti identifier of the connection that delivered the message
1264  * @param msg message that was received
1265  */
1266 void
1267 GCCH_handle_channel_plaintext_data (struct CadetChannel *ch,
1268                                     const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti,
1269                                     const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1270 {
1271   struct GNUNET_MQ_Envelope *env;
1272   struct GNUNET_CADET_LocalData *ld;
1273   struct CadetChannelClient *ccc;
1274   size_t payload_size;
1275   struct CadetOutOfOrderMessage *com;
1276   int duplicate;
1277   uint32_t mid_min;
1278   uint32_t mid_max;
1279   uint32_t mid_msg;
1280   uint32_t delta;
1281
1282   GNUNET_assert (GNUNET_NO == ch->is_loopback);
1283   if ( (NULL == ch->owner) &&
1284        (NULL == ch->dest) )
1285   {
1286     /* This client is gone, but we still have messages to send to
1287        the other end (which is why @a ch is not yet dead).  However,
1288        we cannot pass messages to our client anymore. */
1289     LOG (GNUNET_ERROR_TYPE_DEBUG,
1290          "Dropping incoming payload on %s as this end is already closed\n",
1291          GCCH_2s (ch));
1292     /* send back DESTROY notification to stop further retransmissions! */
1293     if (GNUNET_YES == ch->destroy)
1294       GCT_send_channel_destroy (ch->t,
1295                                 ch->ctn);
1296     return;
1297   }
1298   payload_size = ntohs (msg->header.size) - sizeof (*msg);
1299   env = GNUNET_MQ_msg_extra (ld,
1300                              payload_size,
1301                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA);
1302   ld->ccn = (NULL == ch->dest) ? ch->owner->ccn : ch->dest->ccn;
1303   GNUNET_memcpy (&ld[1],
1304                  &msg[1],
1305                  payload_size);
1306   ccc = (NULL != ch->owner) ? ch->owner : ch->dest;
1307   if ( (GNUNET_YES == ccc->client_ready) &&
1308        ( (GNUNET_YES == ch->out_of_order) ||
1309          (msg->mid.mid == ch->mid_recv.mid) ) )
1310   {
1311     LOG (GNUNET_ERROR_TYPE_DEBUG,
1312          "Giving %u bytes of payload with MID %u from %s to client %s\n",
1313          (unsigned int) payload_size,
1314          ntohl (msg->mid.mid),
1315          GCCH_2s (ch),
1316          GSC_2s (ccc->c));
1317     ccc->client_ready = GNUNET_NO;
1318     GSC_send_to_client (ccc->c,
1319                         env);
1320     ch->mid_recv.mid = htonl (1 + ntohl (ch->mid_recv.mid));
1321     ch->mid_futures >>= 1;
1322     send_channel_data_ack (ch);
1323     return;
1324   }
1325
1326   if (GNUNET_YES == ch->reliable)
1327   {
1328     /* check if message ought to be dropped because it is ancient/too distant/duplicate */
1329     mid_min = ntohl (ch->mid_recv.mid);
1330     mid_max = mid_min + ch->max_pending_messages;
1331     mid_msg = ntohl (msg->mid.mid);
1332     if ( ( (uint32_t) (mid_msg - mid_min) > ch->max_pending_messages) ||
1333          ( (uint32_t) (mid_max - mid_msg) > ch->max_pending_messages) )
1334     {
1335       LOG (GNUNET_ERROR_TYPE_DEBUG,
1336            "%s at %u drops ancient or far-future message %u\n",
1337            GCCH_2s (ch),
1338            (unsigned int) mid_min,
1339            ntohl (msg->mid.mid));
1340
1341       GNUNET_STATISTICS_update (stats,
1342                                 "# duplicate DATA (ancient or future)",
1343                                 1,
1344                                 GNUNET_NO);
1345       GNUNET_MQ_discard (env);
1346       send_channel_data_ack (ch);
1347       return;
1348     }
1349     /* mark bit for future ACKs */
1350     delta = mid_msg - mid_min - 1; /* overflow/underflow are OK here */
1351     if (delta < 64)
1352     {
1353       if (0 != (ch->mid_futures & (1LLU << delta)))
1354       {
1355         /* Duplicate within the queue, drop also */
1356         LOG (GNUNET_ERROR_TYPE_DEBUG,
1357              "Duplicate payload of %u bytes on %s (mid %u) dropped\n",
1358              (unsigned int) payload_size,
1359              GCCH_2s (ch),
1360              ntohl (msg->mid.mid));
1361         GNUNET_STATISTICS_update (stats,
1362                                   "# duplicate DATA",
1363                                   1,
1364                                   GNUNET_NO);
1365         GNUNET_MQ_discard (env);
1366         send_channel_data_ack (ch);
1367         return;
1368       }
1369       ch->mid_futures |= (1LLU << delta);
1370       LOG (GNUNET_ERROR_TYPE_DEBUG,
1371            "Marked bit %llX for mid %u (base: %u); now: %llX\n",
1372            (1LLU << delta),
1373            mid_msg,
1374            mid_min,
1375            ch->mid_futures);
1376     }
1377   }
1378   else /* ! ch->reliable */
1379   {
1380     /* Channel is unreliable, so we do not ACK. But we also cannot
1381        allow buffering everything, so check if we have space... */
1382     if (ccc->num_recv >= ch->max_pending_messages)
1383     {
1384       struct CadetOutOfOrderMessage *drop;
1385
1386       /* Yep, need to drop. Drop the oldest message in
1387          the buffer. */
1388       LOG (GNUNET_ERROR_TYPE_DEBUG,
1389            "Queue full due slow client on %s, dropping oldest message\n",
1390            GCCH_2s (ch));
1391       GNUNET_STATISTICS_update (stats,
1392                                 "# messages dropped due to slow client",
1393                                 1,
1394                                 GNUNET_NO);
1395       drop = ccc->head_recv;
1396       GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
1397                                    ccc->tail_recv,
1398                                    drop);
1399       ccc->num_recv--;
1400       GNUNET_MQ_discard (drop->env);
1401       GNUNET_free (drop);
1402     }
1403   }
1404
1405   /* Insert message into sorted out-of-order queue */
1406   com = GNUNET_new (struct CadetOutOfOrderMessage);
1407   com->mid = msg->mid;
1408   com->env = env;
1409   duplicate = GNUNET_NO;
1410   GNUNET_CONTAINER_DLL_insert_sorted (struct CadetOutOfOrderMessage,
1411                                       is_before,
1412                                       &duplicate,
1413                                       ccc->head_recv,
1414                                       ccc->tail_recv,
1415                                       com);
1416   ccc->num_recv++;
1417   if (GNUNET_YES == duplicate)
1418   {
1419     /* Duplicate within the queue, drop also (this is not covered by
1420        the case above if "delta" >= 64, which could be the case if
1421        max_pending_messages is also >= 64 or if our client is unready
1422        and we are seeing retransmissions of the message our client is
1423        blocked on. */
1424     LOG (GNUNET_ERROR_TYPE_DEBUG,
1425          "Duplicate payload of %u bytes on %s (mid %u) dropped\n",
1426          (unsigned int) payload_size,
1427          GCCH_2s (ch),
1428          ntohl (msg->mid.mid));
1429     GNUNET_STATISTICS_update (stats,
1430                               "# duplicate DATA",
1431                               1,
1432                               GNUNET_NO);
1433     GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
1434                                  ccc->tail_recv,
1435                                  com);
1436     ccc->num_recv--;
1437     GNUNET_MQ_discard (com->env);
1438     GNUNET_free (com);
1439     send_channel_data_ack (ch);
1440     return;
1441   }
1442   LOG (GNUNET_ERROR_TYPE_DEBUG,
1443        "Queued %s payload of %u bytes on %s-%X(%p) (mid %u, need %u first)\n",
1444        (GNUNET_YES == ccc->client_ready)
1445        ? "out-of-order"
1446        : "client-not-ready",
1447        (unsigned int) payload_size,
1448        GCCH_2s (ch),
1449        ntohl (ccc->ccn.channel_of_client),
1450        ccc,
1451        ntohl (msg->mid.mid),
1452        ntohl (ch->mid_recv.mid));
1453   /* NOTE: this ACK we _could_ skip, as the packet is out-of-order and
1454      the sender may already be transmitting the previous one.  Needs
1455      experimental evaluation to see if/when this ACK helps or
1456      hurts. (We might even want another option.) */
1457   send_channel_data_ack (ch);
1458 }
1459
1460
1461 /**
1462  * Function called once the tunnel has sent one of our messages.
1463  * If the message is unreliable, simply frees the `crm`. If the
1464  * message was reliable, calculate retransmission time and
1465  * wait for ACK (or retransmit).
1466  *
1467  * @param cls the `struct CadetReliableMessage` that was sent
1468  * @param cid identifier of the connection within the tunnel, NULL
1469  *            if transmission failed
1470  */
1471 static void
1472 data_sent_cb (void *cls,
1473               const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid);
1474
1475
1476 /**
1477  * We need to retry a transmission, the last one took too long to
1478  * be acknowledged.
1479  *
1480  * @param cls the `struct CadetChannel` where we need to retransmit
1481  */
1482 static void
1483 retry_transmission (void *cls)
1484 {
1485   struct CadetChannel *ch = cls;
1486   struct CadetReliableMessage *crm = ch->head_sent;
1487
1488   ch->retry_data_task = NULL;
1489   GNUNET_assert (NULL == crm->qe);
1490   LOG (GNUNET_ERROR_TYPE_DEBUG,
1491        "Retrying transmission on %s of message %u\n",
1492        GCCH_2s (ch),
1493        (unsigned int) ntohl (crm->data_message->mid.mid));
1494   crm->qe = GCT_send (ch->t,
1495                       &crm->data_message->header,
1496                       &data_sent_cb,
1497                       crm);
1498   GNUNET_assert (NULL == ch->retry_data_task);
1499 }
1500
1501
1502 /**
1503  * We got an PLAINTEXT_DATA_ACK for a message in our queue, remove it from
1504  * the queue and tell our client that it can send more.
1505  *
1506  * @param ch the channel that got the PLAINTEXT_DATA_ACK
1507  * @param cti identifier of the connection that delivered the message
1508  * @param crm the message that got acknowledged
1509  */
1510 static void
1511 handle_matching_ack (struct CadetChannel *ch,
1512                      const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti,
1513                      struct CadetReliableMessage *crm)
1514 {
1515   GNUNET_CONTAINER_DLL_remove (ch->head_sent,
1516                                ch->tail_sent,
1517                                crm);
1518   ch->pending_messages--;
1519   GNUNET_assert (ch->pending_messages < ch->max_pending_messages);
1520   LOG (GNUNET_ERROR_TYPE_DEBUG,
1521        "Received DATA_ACK on %s for message %u (%u ACKs pending)\n",
1522        GCCH_2s (ch),
1523        (unsigned int) ntohl (crm->data_message->mid.mid),
1524        ch->pending_messages);
1525   if (NULL != crm->qe)
1526   {
1527     GCT_send_cancel (crm->qe);
1528     crm->qe = NULL;
1529   }
1530   if ( (1 == crm->num_transmissions) &&
1531        (NULL != cti) )
1532   {
1533     GCC_ack_observed (cti);
1534     if (0 == memcmp (cti,
1535                      &crm->connection_taken,
1536                      sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier)))
1537     {
1538       GCC_latency_observed (cti,
1539                             GNUNET_TIME_absolute_get_duration (crm->first_transmission_time));
1540     }
1541   }
1542   GNUNET_free (crm->data_message);
1543   GNUNET_free (crm);
1544   send_ack_to_client (ch,
1545                       (NULL == ch->owner)
1546                       ? GNUNET_NO
1547                       : GNUNET_YES);
1548 }
1549
1550
1551 /**
1552  * We got an acknowledgement for payload data for a channel.
1553  * Possibly resume transmissions.
1554  *
1555  * @param ch channel that got the ack
1556  * @param cti identifier of the connection that delivered the message
1557  * @param ack details about what was received
1558  */
1559 void
1560 GCCH_handle_channel_plaintext_data_ack (struct CadetChannel *ch,
1561                                         const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti,
1562                                         const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1563 {
1564   struct CadetReliableMessage *crm;
1565   struct CadetReliableMessage *crmn;
1566   int found;
1567   uint32_t mid_base;
1568   uint64_t mid_mask;
1569   unsigned int delta;
1570
1571   GNUNET_break (GNUNET_NO == ch->is_loopback);
1572   if (GNUNET_NO == ch->reliable)
1573   {
1574     /* not expecting ACKs on unreliable channel, odd */
1575     GNUNET_break_op (0);
1576     return;
1577   }
1578   /* mid_base is the MID of the next message that the
1579      other peer expects (i.e. that is missing!), everything
1580      LOWER (but excluding mid_base itself) was received. */
1581   mid_base = ntohl (ack->mid.mid);
1582   mid_mask = GNUNET_htonll (ack->futures);
1583   found = GNUNET_NO;
1584   for (crm = ch->head_sent;
1585         NULL != crm;
1586        crm = crmn)
1587   {
1588     crmn = crm->next;
1589     delta = (unsigned int) (ntohl (crm->data_message->mid.mid) - mid_base);
1590     if (delta >= UINT_MAX - ch->max_pending_messages)
1591     {
1592       /* overflow, means crm was a bit in the past, so this ACK counts for it. */
1593       LOG (GNUNET_ERROR_TYPE_DEBUG,
1594            "Got DATA_ACK with base %u satisfying past message %u on %s\n",
1595            (unsigned int) mid_base,
1596            ntohl (crm->data_message->mid.mid),
1597            GCCH_2s (ch));
1598       handle_matching_ack (ch,
1599                            cti,
1600                            crm);
1601       found = GNUNET_YES;
1602       continue;
1603     }
1604     delta--;
1605     if (delta >= 64)
1606       continue;
1607     LOG (GNUNET_ERROR_TYPE_DEBUG,
1608          "Testing bit %llX for mid %u (base: %u)\n",
1609          (1LLU << delta),
1610          ntohl (crm->data_message->mid.mid),
1611          mid_base);
1612     if (0 != (mid_mask & (1LLU << delta)))
1613     {
1614       LOG (GNUNET_ERROR_TYPE_DEBUG,
1615            "Got DATA_ACK with mask for %u on %s\n",
1616            ntohl (crm->data_message->mid.mid),
1617            GCCH_2s (ch));
1618       handle_matching_ack (ch,
1619                            cti,
1620                            crm);
1621       found = GNUNET_YES;
1622     }
1623   }
1624   if (GNUNET_NO == found)
1625   {
1626     /* ACK for message we already dropped, might have been a
1627        duplicate ACK? Ignore. */
1628     LOG (GNUNET_ERROR_TYPE_DEBUG,
1629          "Duplicate DATA_ACK on %s, ignoring\n",
1630          GCCH_2s (ch));
1631     GNUNET_STATISTICS_update (stats,
1632                               "# duplicate DATA_ACKs",
1633                               1,
1634                               GNUNET_NO);
1635     return;
1636   }
1637   if (NULL != ch->retry_data_task)
1638   {
1639     GNUNET_SCHEDULER_cancel (ch->retry_data_task);
1640     ch->retry_data_task = NULL;
1641   }
1642   if ( (NULL != ch->head_sent) &&
1643        (NULL == ch->head_sent->qe) )
1644     ch->retry_data_task
1645       = GNUNET_SCHEDULER_add_at (ch->head_sent->next_retry,
1646                                  &retry_transmission,
1647                                  ch);
1648 }
1649
1650
1651 /**
1652  * Destroy channel, based on the other peer closing the
1653  * connection.  Also needs to remove this channel from
1654  * the tunnel.
1655  *
1656  * @param ch channel to destroy
1657  * @param cti identifier of the connection that delivered the message,
1658  *            NULL if we are simulating receiving a destroy due to shutdown
1659  */
1660 void
1661 GCCH_handle_remote_destroy (struct CadetChannel *ch,
1662                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti)
1663 {
1664   struct CadetChannelClient *ccc;
1665
1666   GNUNET_assert (GNUNET_NO == ch->is_loopback);
1667   LOG (GNUNET_ERROR_TYPE_DEBUG,
1668        "Received remote channel DESTROY for %s\n",
1669        GCCH_2s (ch));
1670   if (GNUNET_YES == ch->destroy)
1671   {
1672     /* Local client already gone, this is instant-death. */
1673     channel_destroy (ch);
1674     return;
1675   }
1676   ccc = (NULL != ch->owner) ? ch->owner : ch->dest;
1677   if ( (NULL != ccc) &&
1678        (NULL != ccc->head_recv) )
1679   {
1680     LOG (GNUNET_ERROR_TYPE_WARNING,
1681          "Lost end of transmission due to remote shutdown on %s\n",
1682          GCCH_2s (ch));
1683     /* FIXME: change API to notify client about truncated transmission! */
1684   }
1685   ch->destroy = GNUNET_YES;
1686   if (NULL != ccc)
1687     GSC_handle_remote_channel_destroy (ccc->c,
1688                                        ccc->ccn,
1689                                        ch);
1690   channel_destroy (ch);
1691 }
1692
1693
1694 /**
1695  * Test if element @a e1 comes before element @a e2.
1696  *
1697  * @param cls closure, to a flag where we indicate duplicate packets
1698  * @param crm1 an element of to sort
1699  * @param crm2 another element to sort
1700  * @return #GNUNET_YES if @e1 < @e2, otherwise #GNUNET_NO
1701  */
1702 static int
1703 cmp_crm_by_next_retry (void *cls,
1704                        struct CadetReliableMessage *crm1,
1705                        struct CadetReliableMessage *crm2)
1706 {
1707   if (crm1->next_retry.abs_value_us <
1708       crm2->next_retry.abs_value_us)
1709     return GNUNET_YES;
1710   return GNUNET_NO;
1711 }
1712
1713
1714 /**
1715  * Function called once the tunnel has sent one of our messages.
1716  * If the message is unreliable, simply frees the `crm`. If the
1717  * message was reliable, calculate retransmission time and
1718  * wait for ACK (or retransmit).
1719  *
1720  * @param cls the `struct CadetReliableMessage` that was sent
1721  * @param cid identifier of the connection within the tunnel, NULL
1722  *            if transmission failed
1723  */
1724 static void
1725 data_sent_cb (void *cls,
1726               const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid)
1727 {
1728   struct CadetReliableMessage *crm = cls;
1729   struct CadetChannel *ch = crm->ch;
1730
1731   GNUNET_assert (GNUNET_NO == ch->is_loopback);
1732   GNUNET_assert (NULL != crm->qe);
1733   crm->qe = NULL;
1734   GNUNET_CONTAINER_DLL_remove (ch->head_sent,
1735                                ch->tail_sent,
1736                                crm);
1737   if (GNUNET_NO == ch->reliable)
1738   {
1739     GNUNET_free (crm->data_message);
1740     GNUNET_free (crm);
1741     ch->pending_messages--;
1742     send_ack_to_client (ch,
1743                         (NULL == ch->owner)
1744                         ? GNUNET_NO
1745                         : GNUNET_YES);
1746     return;
1747   }
1748   if (NULL == cid)
1749   {
1750     /* There was an error sending. */
1751     crm->num_transmissions = GNUNET_SYSERR;
1752   }
1753   else if (GNUNET_SYSERR != crm->num_transmissions)
1754   {
1755     /* Increment transmission counter, and possibly store @a cid
1756        if this was the first transmission. */
1757     crm->num_transmissions++;
1758     if (1 == crm->num_transmissions)
1759     {
1760       crm->first_transmission_time = GNUNET_TIME_absolute_get ();
1761       crm->connection_taken = *cid;
1762       GCC_ack_expected (cid);
1763     }
1764   }
1765   if ( (0 == crm->retry_delay.rel_value_us) &&
1766        (NULL != cid) )
1767   {
1768     struct CadetConnection *cc = GCC_lookup (cid);
1769
1770     if (NULL != cc)
1771       crm->retry_delay = GCC_get_metrics (cc)->aged_latency;
1772     else
1773       crm->retry_delay = ch->retry_time;
1774   }
1775   crm->retry_delay = GNUNET_TIME_STD_BACKOFF (crm->retry_delay);
1776   crm->retry_delay = GNUNET_TIME_relative_max (crm->retry_delay,
1777                                                MIN_RTT_DELAY);
1778   crm->next_retry = GNUNET_TIME_relative_to_absolute (crm->retry_delay);
1779
1780   GNUNET_CONTAINER_DLL_insert_sorted (struct CadetReliableMessage,
1781                                       cmp_crm_by_next_retry,
1782                                       NULL,
1783                                       ch->head_sent,
1784                                       ch->tail_sent,
1785                                       crm);
1786   LOG (GNUNET_ERROR_TYPE_DEBUG,
1787        "Message %u sent, next transmission on %s in %s\n",
1788        (unsigned int) ntohl (crm->data_message->mid.mid),
1789        GCCH_2s (ch),
1790        GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (ch->head_sent->next_retry),
1791                                                GNUNET_YES));
1792   if (NULL == ch->head_sent->qe)
1793   {
1794     if (NULL != ch->retry_data_task)
1795       GNUNET_SCHEDULER_cancel (ch->retry_data_task);
1796     ch->retry_data_task
1797       = GNUNET_SCHEDULER_add_at (ch->head_sent->next_retry,
1798                                  &retry_transmission,
1799                                  ch);
1800   }
1801 }
1802
1803
1804 /**
1805  * Handle data given by a client.
1806  *
1807  * Check whether the client is allowed to send in this tunnel, save if
1808  * channel is reliable and send an ACK to the client if there is still
1809  * buffer space in the tunnel.
1810  *
1811  * @param ch Channel.
1812  * @param sender_ccn ccn of the sender
1813  * @param buf payload to transmit.
1814  * @param buf_len number of bytes in @a buf
1815  * @return #GNUNET_OK if everything goes well,
1816  *         #GNUNET_SYSERR in case of an error.
1817  */
1818 int
1819 GCCH_handle_local_data (struct CadetChannel *ch,
1820                         struct GNUNET_CADET_ClientChannelNumber sender_ccn,
1821                         const char *buf,
1822                         size_t buf_len)
1823 {
1824   struct CadetReliableMessage *crm;
1825
1826   if (ch->pending_messages >= ch->max_pending_messages)
1827   {
1828     GNUNET_break (0);
1829     return GNUNET_SYSERR;
1830   }
1831   if (GNUNET_YES == ch->destroy)
1832   {
1833     /* we are going down, drop messages */
1834     return GNUNET_OK;
1835   }
1836   ch->pending_messages++;
1837
1838   if (GNUNET_YES == ch->is_loopback)
1839   {
1840     struct CadetChannelClient *receiver;
1841     struct GNUNET_MQ_Envelope *env;
1842     struct GNUNET_CADET_LocalData *ld;
1843     int ack_to_owner;
1844
1845     env = GNUNET_MQ_msg_extra (ld,
1846                                buf_len,
1847                                GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA);
1848     if ( (NULL != ch->owner) &&
1849          (sender_ccn.channel_of_client ==
1850           ch->owner->ccn.channel_of_client) )
1851     {
1852       receiver = ch->dest;
1853       ack_to_owner = GNUNET_YES;
1854     }
1855     else if ( (NULL != ch->dest) &&
1856               (sender_ccn.channel_of_client ==
1857                ch->dest->ccn.channel_of_client) )
1858     {
1859       receiver = ch->owner;
1860       ack_to_owner = GNUNET_NO;
1861     }
1862     else
1863     {
1864       GNUNET_break (0);
1865       return GNUNET_SYSERR;
1866     }
1867     GNUNET_assert (NULL != receiver);
1868     ld->ccn = receiver->ccn;
1869     GNUNET_memcpy (&ld[1],
1870                    buf,
1871                    buf_len);
1872     if (GNUNET_YES == receiver->client_ready)
1873     {
1874       ch->pending_messages--;
1875       GSC_send_to_client (receiver->c,
1876                           env);
1877       send_ack_to_client (ch,
1878                           ack_to_owner);
1879     }
1880     else
1881     {
1882       struct CadetOutOfOrderMessage *oom;
1883
1884       oom = GNUNET_new (struct CadetOutOfOrderMessage);
1885       oom->env = env;
1886       GNUNET_CONTAINER_DLL_insert_tail (receiver->head_recv,
1887                                         receiver->tail_recv,
1888                                         oom);
1889       receiver->num_recv++;
1890     }
1891     return GNUNET_OK;
1892   }
1893
1894   /* Everything is correct, send the message. */
1895   crm = GNUNET_malloc (sizeof (*crm));
1896   crm->ch = ch;
1897   crm->data_message = GNUNET_malloc (sizeof (struct GNUNET_CADET_ChannelAppDataMessage)
1898                                      + buf_len);
1899   crm->data_message->header.size = htons (sizeof (struct GNUNET_CADET_ChannelAppDataMessage) + buf_len);
1900   crm->data_message->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA);
1901   ch->mid_send.mid = htonl (ntohl (ch->mid_send.mid) + 1);
1902   crm->data_message->mid = ch->mid_send;
1903   crm->data_message->ctn = ch->ctn;
1904   GNUNET_memcpy (&crm->data_message[1],
1905                  buf,
1906                  buf_len);
1907   GNUNET_CONTAINER_DLL_insert_tail (ch->head_sent,
1908                                     ch->tail_sent,
1909                                     crm);
1910   LOG (GNUNET_ERROR_TYPE_DEBUG,
1911        "Sending message %u from local client to %s with %u bytes\n",
1912        ntohl (crm->data_message->mid.mid),
1913        GCCH_2s (ch),
1914        buf_len);
1915   if (NULL != ch->retry_data_task)
1916   {
1917     GNUNET_SCHEDULER_cancel (ch->retry_data_task);
1918     ch->retry_data_task = NULL;
1919   }
1920   crm->qe = GCT_send (ch->t,
1921                       &crm->data_message->header,
1922                       &data_sent_cb,
1923                       crm);
1924   GNUNET_assert (NULL == ch->retry_data_task);
1925   return GNUNET_OK;
1926 }
1927
1928
1929 /**
1930  * Handle ACK from client on local channel.  Means the client is ready
1931  * for more data, see if we have any for it.
1932  *
1933  * @param ch channel to destroy
1934  * @param client_ccn ccn of the client sending the ack
1935  */
1936 void
1937 GCCH_handle_local_ack (struct CadetChannel *ch,
1938                        struct GNUNET_CADET_ClientChannelNumber client_ccn)
1939 {
1940   struct CadetChannelClient *ccc;
1941   struct CadetOutOfOrderMessage *com;
1942
1943   if ( (NULL != ch->owner) &&
1944        (ch->owner->ccn.channel_of_client == client_ccn.channel_of_client) )
1945     ccc = ch->owner;
1946   else if ( (NULL != ch->dest) &&
1947             (ch->dest->ccn.channel_of_client == client_ccn.channel_of_client) )
1948     ccc = ch->dest;
1949   else
1950     GNUNET_assert (0);
1951   ccc->client_ready = GNUNET_YES;
1952   com = ccc->head_recv;
1953   if (NULL == com)
1954   {
1955     LOG (GNUNET_ERROR_TYPE_DEBUG,
1956          "Got LOCAL_ACK, %s-%X ready to receive more data, but none pending on %s-%X(%p)!\n",
1957          GSC_2s (ccc->c),
1958          ntohl (client_ccn.channel_of_client),
1959          GCCH_2s (ch),
1960          ntohl (ccc->ccn.channel_of_client),
1961          ccc);
1962     return; /* none pending */
1963   }
1964   if (GNUNET_YES == ch->is_loopback)
1965   {
1966     int to_owner;
1967
1968     /* Messages are always in-order, just send */
1969     GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
1970                                  ccc->tail_recv,
1971                                  com);
1972     ccc->num_recv--;
1973     GSC_send_to_client (ccc->c,
1974                         com->env);
1975     /* Notify sender that we can receive more */
1976     if ( (NULL != ch->owner) &&
1977          (ccc->ccn.channel_of_client ==
1978           ch->owner->ccn.channel_of_client) )
1979     {
1980       to_owner = GNUNET_NO;
1981     }
1982     else
1983     {
1984       GNUNET_assert ( (NULL != ch->dest) &&
1985                       (ccc->ccn.channel_of_client ==
1986                        ch->dest->ccn.channel_of_client) );
1987       to_owner = GNUNET_YES;
1988     }
1989     send_ack_to_client (ch,
1990                         to_owner);
1991     GNUNET_free (com);
1992     return;
1993   }
1994
1995   if ( (com->mid.mid != ch->mid_recv.mid) &&
1996        (GNUNET_NO == ch->out_of_order) &&
1997        (GNUNET_YES == ch->reliable) )
1998   {
1999     LOG (GNUNET_ERROR_TYPE_DEBUG,
2000          "Got LOCAL_ACK, %s-%X ready to receive more data (but next one is out-of-order %u vs. %u)!\n",
2001          GSC_2s (ccc->c),
2002          ntohl (ccc->ccn.channel_of_client),
2003          ntohl (com->mid.mid),
2004          ntohl (ch->mid_recv.mid));
2005     return; /* missing next one in-order */
2006   }
2007
2008   LOG (GNUNET_ERROR_TYPE_DEBUG,
2009        "Got LOCAL_ACK, giving payload message %u to %s-%X on %s\n",
2010        ntohl (com->mid.mid),
2011        GSC_2s (ccc->c),
2012        ntohl (ccc->ccn.channel_of_client),
2013        GCCH_2s (ch));
2014
2015   /* all good, pass next message to client */
2016   GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
2017                                ccc->tail_recv,
2018                                com);
2019   ccc->num_recv--;
2020   /* FIXME: if unreliable, this is not aggressive
2021      enough, as it would be OK to have lost some! */
2022
2023   ch->mid_recv.mid = htonl (1 + ntohl (com->mid.mid));
2024   ch->mid_futures >>= 1; /* equivalent to division by 2 */
2025   ccc->client_ready = GNUNET_NO;
2026   GSC_send_to_client (ccc->c,
2027                       com->env);
2028   GNUNET_free (com);
2029   send_channel_data_ack (ch);
2030   if (NULL != ccc->head_recv)
2031     return;
2032   if (GNUNET_NO == ch->destroy)
2033     return;
2034   GCT_send_channel_destroy (ch->t,
2035                             ch->ctn);
2036   channel_destroy (ch);
2037 }
2038
2039
2040 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-chn",__VA_ARGS__)
2041
2042
2043 /**
2044  * Log channel info.
2045  *
2046  * @param ch Channel.
2047  * @param level Debug level to use.
2048  */
2049 void
2050 GCCH_debug (struct CadetChannel *ch,
2051             enum GNUNET_ErrorType level)
2052 {
2053 #if !defined(GNUNET_CULL_LOGGING)
2054   int do_log;
2055
2056   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2057                                        "cadet-chn",
2058                                        __FILE__, __FUNCTION__, __LINE__);
2059   if (0 == do_log)
2060     return;
2061
2062   if (NULL == ch)
2063   {
2064     LOG2 (level, "CHN *** DEBUG NULL CHANNEL ***\n");
2065     return;
2066   }
2067   LOG2 (level,
2068         "CHN %s:%X (%p)\n",
2069         GCT_2s (ch->t),
2070         ch->ctn,
2071         ch);
2072   if (NULL != ch->owner)
2073   {
2074     LOG2 (level,
2075           "CHN origin %s ready %s local-id: %u\n",
2076           GSC_2s (ch->owner->c),
2077           ch->owner->client_ready ? "YES" : "NO",
2078           ntohl (ch->owner->ccn.channel_of_client));
2079   }
2080   if (NULL != ch->dest)
2081   {
2082     LOG2 (level,
2083           "CHN destination %s ready %s local-id: %u\n",
2084           GSC_2s (ch->dest->c),
2085           ch->dest->client_ready ? "YES" : "NO",
2086           ntohl (ch->dest->ccn.channel_of_client));
2087   }
2088   LOG2 (level,
2089         "CHN  Message IDs recv: %d (%LLX), send: %d\n",
2090         ntohl (ch->mid_recv.mid),
2091         (unsigned long long) ch->mid_futures,
2092         ntohl (ch->mid_send.mid));
2093 #endif
2094 }
2095
2096
2097
2098 /* end of gnunet-service-cadet-new_channel.c */