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