memcmp() -> GNUNET_memcmp(), first take
[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      SPDX-License-Identifier: AGPL3.0-or-later
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 (CADET_CHANNEL_LOOSE == ch->state)
506   {
507     GSC_drop_loose_channel (&ch->h_port,
508                             ch);
509   }
510   if (NULL != ch->owner)
511   {
512     free_channel_client (ch->owner);
513     ch->owner = NULL;
514   }
515   if (NULL != ch->dest)
516   {
517     free_channel_client (ch->dest);
518     ch->dest = NULL;
519   }
520   if (NULL != ch->last_control_qe)
521   {
522     GCT_send_cancel (ch->last_control_qe);
523     ch->last_control_qe = NULL;
524   }
525   if (NULL != ch->retry_data_task)
526   {
527     GNUNET_SCHEDULER_cancel (ch->retry_data_task);
528     ch->retry_data_task = NULL;
529   }
530   if (NULL != ch->retry_control_task)
531   {
532     GNUNET_SCHEDULER_cancel (ch->retry_control_task);
533     ch->retry_control_task = NULL;
534   }
535   if (GNUNET_NO == ch->is_loopback)
536   {
537     GCT_remove_channel (ch->t,
538                         ch,
539                         ch->ctn);
540     ch->t = NULL;
541   }
542   GNUNET_free (ch);
543 }
544
545
546 /**
547  * Send a channel create message.
548  *
549  * @param cls Channel for which to send.
550  */
551 static void
552 send_channel_open (void *cls);
553
554
555 /**
556  * Function called once the tunnel confirms that we sent the
557  * create message.  Delays for a bit until we retry.
558  *
559  * @param cls our `struct CadetChannel`.
560  * @param cid identifier of the connection within the tunnel, NULL
561  *            if transmission failed
562  */
563 static void
564 channel_open_sent_cb (void *cls,
565                       const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid)
566 {
567   struct CadetChannel *ch = cls;
568
569   GNUNET_assert (NULL != ch->last_control_qe);
570   ch->last_control_qe = NULL;
571   ch->retry_time = GNUNET_TIME_STD_BACKOFF (ch->retry_time);
572   LOG (GNUNET_ERROR_TYPE_DEBUG,
573        "Sent CADET_CHANNEL_OPEN on %s, retrying in %s\n",
574        GCCH_2s (ch),
575        GNUNET_STRINGS_relative_time_to_string (ch->retry_time,
576                                                GNUNET_YES));
577   ch->retry_control_task
578     = GNUNET_SCHEDULER_add_delayed (ch->retry_time,
579                                     &send_channel_open,
580                                     ch);
581 }
582
583
584 /**
585  * Send a channel open message.
586  *
587  * @param cls Channel for which to send.
588  */
589 static void
590 send_channel_open (void *cls)
591 {
592   struct CadetChannel *ch = cls;
593   struct GNUNET_CADET_ChannelOpenMessage msgcc;
594   uint32_t options;
595
596   ch->retry_control_task = NULL;
597   LOG (GNUNET_ERROR_TYPE_DEBUG,
598        "Sending CHANNEL_OPEN message for %s\n",
599        GCCH_2s (ch));
600   options = 0;
601   if (ch->nobuffer)
602     options |= GNUNET_CADET_OPTION_NOBUFFER;
603   if (ch->reliable)
604     options |= GNUNET_CADET_OPTION_RELIABLE;
605   if (ch->out_of_order)
606     options |= GNUNET_CADET_OPTION_OUT_OF_ORDER;
607   msgcc.header.size = htons (sizeof (msgcc));
608   msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN);
609   msgcc.opt = htonl (options);
610   msgcc.h_port = ch->h_port;
611   msgcc.ctn = ch->ctn;
612   ch->state = CADET_CHANNEL_OPEN_SENT;
613   if (NULL != ch->last_control_qe)
614     GCT_send_cancel (ch->last_control_qe);
615   ch->last_control_qe = GCT_send (ch->t,
616                                   &msgcc.header,
617                                   &channel_open_sent_cb,
618                                   ch);
619   GNUNET_assert (NULL == ch->retry_control_task);
620 }
621
622
623 /**
624  * Function called once and only once after a channel was bound
625  * to its tunnel via #GCT_add_channel() is ready for transmission.
626  * Note that this is only the case for channels that this peer
627  * initiates, as for incoming channels we assume that they are
628  * ready for transmission immediately upon receiving the open
629  * message.  Used to bootstrap the #GCT_send() process.
630  *
631  * @param ch the channel for which the tunnel is now ready
632  */
633 void
634 GCCH_tunnel_up (struct CadetChannel *ch)
635 {
636   GNUNET_assert (NULL == ch->retry_control_task);
637   LOG (GNUNET_ERROR_TYPE_DEBUG,
638        "Tunnel up, sending CHANNEL_OPEN on %s now\n",
639        GCCH_2s (ch));
640   ch->retry_control_task
641     = GNUNET_SCHEDULER_add_now (&send_channel_open,
642                                 ch);
643 }
644
645
646 /**
647  * Create a new channel.
648  *
649  * @param owner local client owning the channel
650  * @param ccn local number of this channel at the @a owner
651  * @param destination peer to which we should build the channel
652  * @param port desired port at @a destination
653  * @param options options for the channel
654  * @return handle to the new channel
655  */
656 struct CadetChannel *
657 GCCH_channel_local_new (struct CadetClient *owner,
658                         struct GNUNET_CADET_ClientChannelNumber ccn,
659                         struct CadetPeer *destination,
660                         const struct GNUNET_HashCode *port,
661                         uint32_t options)
662 {
663   struct CadetChannel *ch;
664   struct CadetChannelClient *ccco;
665
666   ccco = GNUNET_new (struct CadetChannelClient);
667   ccco->c = owner;
668   ccco->ccn = ccn;
669   ccco->client_ready = GNUNET_YES;
670
671   ch = GNUNET_new (struct CadetChannel);
672   ch->mid_recv.mid = htonl (1); /* The OPEN_ACK counts as message 0! */
673   ch->nobuffer = (0 != (options & GNUNET_CADET_OPTION_NOBUFFER));
674   ch->reliable = (0 != (options & GNUNET_CADET_OPTION_RELIABLE));
675   ch->out_of_order = (0 != (options & GNUNET_CADET_OPTION_OUT_OF_ORDER));
676   ch->max_pending_messages = (ch->nobuffer) ? 1 : 4; /* FIXME: 4!? Do not hardcode! */
677   ch->owner = ccco;
678   ch->port = *port;
679   GCCH_hash_port (&ch->h_port,
680                   port,
681                   GCP_get_id (destination));
682   if (0 == GNUNET_memcmp (&my_full_id,
683                    GCP_get_id (destination)))
684   {
685     struct OpenPort *op;
686
687     ch->is_loopback = GNUNET_YES;
688     op = GNUNET_CONTAINER_multihashmap_get (open_ports,
689                                             &ch->h_port);
690     if (NULL == op)
691     {
692       /* port closed, wait for it to possibly open */
693       ch->state = CADET_CHANNEL_LOOSE;
694       (void) GNUNET_CONTAINER_multihashmap_put (loose_channels,
695                                                 &ch->h_port,
696                                                 ch,
697                                                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
698       LOG (GNUNET_ERROR_TYPE_DEBUG,
699            "Created loose incoming loopback channel to port %s\n",
700            GNUNET_h2s (&ch->port));
701     }
702     else
703     {
704       GCCH_bind (ch,
705                  op->c,
706                  &op->port);
707     }
708   }
709   else
710   {
711     ch->t = GCP_get_tunnel (destination,
712                             GNUNET_YES);
713     ch->retry_time = CADET_INITIAL_RETRANSMIT_TIME;
714     ch->ctn = GCT_add_channel (ch->t,
715                                ch);
716   }
717   GNUNET_STATISTICS_update (stats,
718                             "# channels",
719                             1,
720                             GNUNET_NO);
721   LOG (GNUNET_ERROR_TYPE_DEBUG,
722        "Created channel to port %s at peer %s for %s using %s\n",
723        GNUNET_h2s (port),
724        GCP_2s (destination),
725        GSC_2s (owner),
726        (GNUNET_YES == ch->is_loopback) ? "loopback" : GCT_2s (ch->t));
727   return ch;
728 }
729
730
731 /**
732  * We had an incoming channel to a port that is closed.
733  * It has not been opened for a while, drop it.
734  *
735  * @param cls the channel to drop
736  */
737 static void
738 timeout_closed_cb (void *cls)
739 {
740   struct CadetChannel *ch = cls;
741
742   ch->retry_control_task = NULL;
743   LOG (GNUNET_ERROR_TYPE_DEBUG,
744        "Closing incoming channel to port %s from peer %s due to timeout\n",
745        GNUNET_h2s (&ch->port),
746        GCP_2s (GCT_get_destination (ch->t)));
747   channel_destroy (ch);
748 }
749
750
751 /**
752  * Create a new channel based on a request coming in over the network.
753  *
754  * @param t tunnel to the remote peer
755  * @param ctn identifier of this channel in the tunnel
756  * @param h_port desired hash of local port
757  * @param options options for the channel
758  * @return handle to the new channel
759  */
760 struct CadetChannel *
761 GCCH_channel_incoming_new (struct CadetTunnel *t,
762                            struct GNUNET_CADET_ChannelTunnelNumber ctn,
763                            const struct GNUNET_HashCode *h_port,
764                            uint32_t options)
765 {
766   struct CadetChannel *ch;
767   struct OpenPort *op;
768
769   ch = GNUNET_new (struct CadetChannel);
770   ch->h_port = *h_port;
771   ch->t = t;
772   ch->ctn = ctn;
773   ch->retry_time = CADET_INITIAL_RETRANSMIT_TIME;
774   ch->nobuffer = (0 != (options & GNUNET_CADET_OPTION_NOBUFFER));
775   ch->reliable = (0 != (options & GNUNET_CADET_OPTION_RELIABLE));
776   ch->out_of_order = (0 != (options & GNUNET_CADET_OPTION_OUT_OF_ORDER));
777   ch->max_pending_messages = (ch->nobuffer) ? 1 : 4; /* FIXME: 4!? Do not hardcode! */
778   GNUNET_STATISTICS_update (stats,
779                             "# channels",
780                             1,
781                             GNUNET_NO);
782
783   op = GNUNET_CONTAINER_multihashmap_get (open_ports,
784                                           h_port);
785   if (NULL == op)
786   {
787     /* port closed, wait for it to possibly open */
788     ch->state = CADET_CHANNEL_LOOSE;
789     (void) GNUNET_CONTAINER_multihashmap_put (loose_channels,
790                                               &ch->h_port,
791                                               ch,
792                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
793     GNUNET_assert (NULL == ch->retry_control_task);
794     ch->retry_control_task
795       = GNUNET_SCHEDULER_add_delayed (TIMEOUT_CLOSED_PORT,
796                                       &timeout_closed_cb,
797                                       ch);
798     LOG (GNUNET_ERROR_TYPE_DEBUG,
799          "Created loose incoming channel to port %s from peer %s\n",
800          GNUNET_h2s (&ch->port),
801          GCP_2s (GCT_get_destination (ch->t)));
802   }
803   else
804   {
805     GCCH_bind (ch,
806                op->c,
807                &op->port);
808   }
809   GNUNET_STATISTICS_update (stats,
810                             "# channels",
811                             1,
812                             GNUNET_NO);
813   return ch;
814 }
815
816
817 /**
818  * Function called once the tunnel confirms that we sent the
819  * ACK message.  Just remembers it was sent, we do not expect
820  * ACKs for ACKs ;-).
821  *
822  * @param cls our `struct CadetChannel`.
823  * @param cid identifier of the connection within the tunnel, NULL
824  *            if transmission failed
825  */
826 static void
827 send_ack_cb (void *cls,
828              const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid)
829 {
830   struct CadetChannel *ch = cls;
831
832   GNUNET_assert (NULL != ch->last_control_qe);
833   ch->last_control_qe = NULL;
834 }
835
836
837 /**
838  * Compute and send the current #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK to the other peer.
839  *
840  * @param ch channel to send the #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK for
841  */
842 static void
843 send_channel_data_ack (struct CadetChannel *ch)
844 {
845   struct GNUNET_CADET_ChannelDataAckMessage msg;
846
847   if (GNUNET_NO == ch->reliable)
848     return; /* no ACKs */
849   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK);
850   msg.header.size = htons (sizeof (msg));
851   msg.ctn = ch->ctn;
852   msg.mid.mid = htonl (ntohl (ch->mid_recv.mid));
853   msg.futures = GNUNET_htonll (ch->mid_futures);
854   LOG (GNUNET_ERROR_TYPE_DEBUG,
855        "Sending DATA_ACK %u:%llX via %s\n",
856        (unsigned int) ntohl (msg.mid.mid),
857        (unsigned long long) ch->mid_futures,
858        GCCH_2s (ch));
859   if (NULL != ch->last_control_qe)
860     GCT_send_cancel (ch->last_control_qe);
861   ch->last_control_qe = GCT_send (ch->t,
862                                   &msg.header,
863                                   &send_ack_cb,
864                                   ch);
865 }
866
867
868 /**
869  * Send our initial #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK to the client confirming that the
870  * connection is up.
871  *
872  * @param cls the `struct CadetChannel`
873  */
874 static void
875 send_open_ack (void *cls)
876 {
877   struct CadetChannel *ch = cls;
878   struct GNUNET_CADET_ChannelOpenAckMessage msg;
879
880   ch->retry_control_task = NULL;
881   LOG (GNUNET_ERROR_TYPE_DEBUG,
882        "Sending CHANNEL_OPEN_ACK on %s\n",
883        GCCH_2s (ch));
884   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK);
885   msg.header.size = htons (sizeof (msg));
886   msg.reserved = htonl (0);
887   msg.ctn = ch->ctn;
888   msg.port = ch->port;
889   if (NULL != ch->last_control_qe)
890     GCT_send_cancel (ch->last_control_qe);
891   ch->last_control_qe = GCT_send (ch->t,
892                                   &msg.header,
893                                   &send_ack_cb,
894                                   ch);
895 }
896
897
898 /**
899  * We got a #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN message again for
900  * this channel.  If the binding was successful, (re)transmit the
901  * #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK.
902  *
903  * @param ch channel that got the duplicate open
904  * @param cti identifier of the connection that delivered the message
905  */
906 void
907 GCCH_handle_duplicate_open (struct CadetChannel *ch,
908                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti)
909 {
910   if (NULL == ch->dest)
911   {
912     LOG (GNUNET_ERROR_TYPE_DEBUG,
913          "Ignoring duplicate CHANNEL_OPEN on %s: port is closed\n",
914          GCCH_2s (ch));
915     return;
916   }
917   if (NULL != ch->retry_control_task)
918   {
919     LOG (GNUNET_ERROR_TYPE_DEBUG,
920          "Ignoring duplicate CHANNEL_OPEN on %s: control message is pending\n",
921          GCCH_2s (ch));
922     return;
923   }
924   LOG (GNUNET_ERROR_TYPE_DEBUG,
925        "Retransmitting CHANNEL_OPEN_ACK on %s\n",
926        GCCH_2s (ch));
927   ch->retry_control_task
928     = GNUNET_SCHEDULER_add_now (&send_open_ack,
929                                 ch);
930 }
931
932
933 /**
934  * Send a #GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK to the client to solicit more messages.
935  *
936  * @param ch channel the ack is for
937  * @param to_owner #GNUNET_YES to send to owner,
938  *                 #GNUNET_NO to send to dest
939  */
940 static void
941 send_ack_to_client (struct CadetChannel *ch,
942                     int to_owner)
943 {
944   struct GNUNET_MQ_Envelope *env;
945   struct GNUNET_CADET_LocalAck *ack;
946   struct CadetChannelClient *ccc;
947
948   ccc = (GNUNET_YES == to_owner) ? ch->owner : ch->dest;
949   if (NULL == ccc)
950   {
951     /* This can happen if we are just getting ACKs after
952        our local client already disconnected. */
953     GNUNET_assert (GNUNET_YES == ch->destroy);
954     return;
955   }
956   env = GNUNET_MQ_msg (ack,
957                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
958   ack->ccn = ccc->ccn;
959   LOG (GNUNET_ERROR_TYPE_DEBUG,
960        "Sending CADET_LOCAL_ACK to %s (%s) at ccn %X (%u/%u pending)\n",
961        GSC_2s (ccc->c),
962        (GNUNET_YES == to_owner) ? "owner" : "dest",
963        ntohl (ack->ccn.channel_of_client),
964        ch->pending_messages,
965        ch->max_pending_messages);
966   GSC_send_to_client (ccc->c,
967                       env);
968 }
969
970
971 /**
972  * A client is bound to the port that we have a channel
973  * open to.  Send the acknowledgement for the connection
974  * request and establish the link with the client.
975  *
976  * @param ch open incoming channel
977  * @param c client listening on the respective @a port
978  * @param port the port @a is listening on
979  */
980 void
981 GCCH_bind (struct CadetChannel *ch,
982            struct CadetClient *c,
983            const struct GNUNET_HashCode *port)
984 {
985   uint32_t options;
986   struct CadetChannelClient *cccd;
987
988   LOG (GNUNET_ERROR_TYPE_DEBUG,
989        "Binding %s from %s to port %s of %s\n",
990        GCCH_2s (ch),
991        GCT_2s (ch->t),
992        GNUNET_h2s (&ch->port),
993        GSC_2s (c));
994   if (NULL != ch->retry_control_task)
995   {
996     /* there might be a timeout task here */
997     GNUNET_SCHEDULER_cancel (ch->retry_control_task);
998     ch->retry_control_task = NULL;
999   }
1000   options = 0;
1001   if (ch->nobuffer)
1002     options |= GNUNET_CADET_OPTION_NOBUFFER;
1003   if (ch->reliable)
1004     options |= GNUNET_CADET_OPTION_RELIABLE;
1005   if (ch->out_of_order)
1006     options |= GNUNET_CADET_OPTION_OUT_OF_ORDER;
1007   cccd = GNUNET_new (struct CadetChannelClient);
1008   GNUNET_assert (NULL == ch->dest);
1009   ch->dest = cccd;
1010   ch->port = *port;
1011   cccd->c = c;
1012   cccd->client_ready = GNUNET_YES;
1013   cccd->ccn = GSC_bind (c,
1014                         ch,
1015                         (GNUNET_YES == ch->is_loopback)
1016                         ? GCP_get (&my_full_id,
1017                                    GNUNET_YES)
1018                         : GCT_get_destination (ch->t),
1019                         port,
1020                         options);
1021   GNUNET_assert (ntohl (cccd->ccn.channel_of_client) <
1022                  GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
1023   ch->mid_recv.mid = htonl (1); /* The OPEN counts as message 0! */
1024   if (GNUNET_YES == ch->is_loopback)
1025   {
1026     ch->state = CADET_CHANNEL_OPEN_SENT;
1027     GCCH_handle_channel_open_ack (ch,
1028                                   NULL,
1029                                   port);
1030   }
1031   else
1032   {
1033     /* notify other peer that we accepted the connection */
1034     ch->state = CADET_CHANNEL_READY;
1035     ch->retry_control_task
1036       = GNUNET_SCHEDULER_add_now (&send_open_ack,
1037                                   ch);
1038   }
1039   /* give client it's initial supply of ACKs */
1040   GNUNET_assert (ntohl (cccd->ccn.channel_of_client) <
1041                  GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
1042   for (unsigned int i=0;i<ch->max_pending_messages;i++)
1043     send_ack_to_client (ch,
1044                         GNUNET_NO);
1045 }
1046
1047
1048 /**
1049  * One of our clients has disconnected, tell the other one that we
1050  * are finished. Done asynchronously to avoid concurrent modification
1051  * issues if this is the same client.
1052  *
1053  * @param cls the `struct CadetChannel` where one of the ends is now dead
1054  */
1055 static void
1056 signal_remote_destroy_cb (void *cls)
1057 {
1058   struct CadetChannel *ch = cls;
1059   struct CadetChannelClient *ccc;
1060
1061   /* Find which end is left... */
1062   ch->retry_control_task = NULL;
1063   ccc = (NULL != ch->owner) ? ch->owner : ch->dest;
1064   GSC_handle_remote_channel_destroy (ccc->c,
1065                                      ccc->ccn,
1066                                      ch);
1067   channel_destroy (ch);
1068 }
1069
1070
1071 /**
1072  * Destroy locally created channel.  Called by the local client, so no
1073  * need to tell the client.
1074  *
1075  * @param ch channel to destroy
1076  * @param c client that caused the destruction
1077  * @param ccn client number of the client @a c
1078  */
1079 void
1080 GCCH_channel_local_destroy (struct CadetChannel *ch,
1081                             struct CadetClient *c,
1082                             struct GNUNET_CADET_ClientChannelNumber ccn)
1083 {
1084   LOG (GNUNET_ERROR_TYPE_DEBUG,
1085        "%s asks for destruction of %s\n",
1086        GSC_2s (c),
1087        GCCH_2s (ch));
1088   GNUNET_assert (NULL != c);
1089   if ( (NULL != ch->owner) &&
1090        (c == ch->owner->c) &&
1091        (ccn.channel_of_client == ch->owner->ccn.channel_of_client) )
1092   {
1093     free_channel_client (ch->owner);
1094     ch->owner = NULL;
1095   }
1096   else if ( (NULL != ch->dest) &&
1097             (c == ch->dest->c) &&
1098             (ccn.channel_of_client == ch->dest->ccn.channel_of_client) )
1099   {
1100     free_channel_client (ch->dest);
1101     ch->dest = NULL;
1102   }
1103   else
1104   {
1105     GNUNET_assert (0);
1106   }
1107
1108   if (GNUNET_YES == ch->destroy)
1109   {
1110     /* other end already destroyed, with the local client gone, no need
1111        to finish transmissions, just destroy immediately. */
1112     channel_destroy (ch);
1113     return;
1114   }
1115   if ( (NULL != ch->head_sent) &&
1116        ( (NULL != ch->owner) ||
1117          (NULL != ch->dest) ) )
1118   {
1119     /* Wait for other end to destroy us as well,
1120        and otherwise allow send queue to be transmitted first */
1121     ch->destroy = GNUNET_YES;
1122     return;
1123   }
1124   if ( (GNUNET_YES == ch->is_loopback) &&
1125        ( (NULL != ch->owner) ||
1126          (NULL != ch->dest) ) )
1127   {
1128     if (NULL != ch->retry_control_task)
1129       GNUNET_SCHEDULER_cancel (ch->retry_control_task);
1130     ch->retry_control_task
1131       = GNUNET_SCHEDULER_add_now (&signal_remote_destroy_cb,
1132                                   ch);
1133     return;
1134   }
1135   if (GNUNET_NO == ch->is_loopback)
1136   {
1137     /* If the we ever sent the CHANNEL_CREATE, we need to send a destroy message. */
1138     switch (ch->state)
1139     {
1140     case CADET_CHANNEL_NEW:
1141       /* We gave up on a channel that we created as a client to a remote
1142          target, but that never went anywhere. Nothing to do here. */
1143       break;
1144     case CADET_CHANNEL_LOOSE:
1145       break;
1146     default:
1147       GCT_send_channel_destroy (ch->t,
1148                                 ch->ctn);
1149     }
1150   }
1151   /* Nothing left to do, just finish destruction */
1152   channel_destroy (ch);
1153 }
1154
1155
1156 /**
1157  * We got an acknowledgement for the creation of the channel
1158  * (the port is open on the other side).  Verify that the
1159  * other end really has the right port, and begin transmissions.
1160  *
1161  * @param ch channel to destroy
1162  * @param cti identifier of the connection that delivered the message
1163  * @param port port number (needed to verify receiver knows the port)
1164  */
1165 void
1166 GCCH_handle_channel_open_ack (struct CadetChannel *ch,
1167                               const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti,
1168                               const struct GNUNET_HashCode *port)
1169 {
1170   switch (ch->state)
1171   {
1172   case CADET_CHANNEL_NEW:
1173     /* this should be impossible */
1174     GNUNET_break (0);
1175     break;
1176   case CADET_CHANNEL_LOOSE:
1177     /* This makes no sense. */
1178     GNUNET_break_op (0);
1179     break;
1180   case CADET_CHANNEL_OPEN_SENT:
1181     if (NULL == ch->owner)
1182     {
1183       /* We're not the owner, wrong direction! */
1184       GNUNET_break_op (0);
1185       return;
1186     }
1187     if (0 != GNUNET_memcmp (&ch->port,
1188                      port))
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   {
1309     /*
1310      * We ad-hoc send the message if
1311      * - The channel is out-of-order
1312      * - The channel is reliable and MID matches next expected MID
1313      * - The channel is unreliable and MID is before lowest seen MID
1314      */
1315     if ( (GNUNET_YES == ch->out_of_order) ||
1316          ((msg->mid.mid == ch->mid_recv.mid) &&
1317           (GNUNET_YES == ch->reliable)) ||
1318          ((GNUNET_NO == ch->reliable) &&
1319           (ntohl (msg->mid.mid) >= ntohl (ch->mid_recv.mid)) &&
1320           ((NULL == ccc->head_recv) ||
1321            (ntohl (msg->mid.mid) < ntohl (ccc->head_recv->mid.mid)))) )
1322     {
1323       LOG (GNUNET_ERROR_TYPE_DEBUG,
1324            "Giving %u bytes of payload with MID %u from %s to client %s\n",
1325            (unsigned int) payload_size,
1326            ntohl (msg->mid.mid),
1327            GCCH_2s (ch),
1328            GSC_2s (ccc->c));
1329       ccc->client_ready = GNUNET_NO;
1330       GSC_send_to_client (ccc->c,
1331                           env);
1332       if (GNUNET_NO == ch->out_of_order)
1333         ch->mid_recv.mid = htonl (1 + ntohl (msg->mid.mid));
1334       else
1335         ch->mid_recv.mid = htonl (1 + ntohl (ch->mid_recv.mid));
1336       ch->mid_futures >>= 1;
1337       if ( (GNUNET_YES == ch->out_of_order) &&
1338            (GNUNET_NO == ch->reliable) )
1339       {
1340         /* possibly shift by more if we skipped messages */
1341         uint64_t delta = htonl (msg->mid.mid) - 1 - ntohl (ch->mid_recv.mid);
1342         
1343         if (delta > 63)
1344           ch->mid_futures = 0;
1345         else
1346           ch->mid_futures >>= delta;
1347         ch->mid_recv.mid = htonl (1 + ntohl (msg->mid.mid));
1348       }
1349       send_channel_data_ack (ch);
1350       return;
1351     }
1352   }
1353
1354   if (GNUNET_YES == ch->reliable)
1355   {
1356     /* check if message ought to be dropped because it is ancient/too distant/duplicate */
1357     mid_min = ntohl (ch->mid_recv.mid);
1358     mid_max = mid_min + ch->max_pending_messages;
1359     mid_msg = ntohl (msg->mid.mid);
1360     if ( ( (uint32_t) (mid_msg - mid_min) > ch->max_pending_messages) ||
1361          ( (uint32_t) (mid_max - mid_msg) > ch->max_pending_messages) )
1362     {
1363       LOG (GNUNET_ERROR_TYPE_DEBUG,
1364            "%s at %u drops ancient or far-future message %u\n",
1365            GCCH_2s (ch),
1366            (unsigned int) mid_min,
1367            ntohl (msg->mid.mid));
1368
1369       GNUNET_STATISTICS_update (stats,
1370                                 "# duplicate DATA (ancient or future)",
1371                                 1,
1372                                 GNUNET_NO);
1373       GNUNET_MQ_discard (env);
1374       send_channel_data_ack (ch);
1375       return;
1376     }
1377     /* mark bit for future ACKs */
1378     delta = mid_msg - mid_min - 1; /* overflow/underflow are OK here */
1379     if (delta < 64)
1380     {
1381       if (0 != (ch->mid_futures & (1LLU << delta)))
1382       {
1383         /* Duplicate within the queue, drop also */
1384         LOG (GNUNET_ERROR_TYPE_DEBUG,
1385              "Duplicate payload of %u bytes on %s (mid %u) dropped\n",
1386              (unsigned int) payload_size,
1387              GCCH_2s (ch),
1388              ntohl (msg->mid.mid));
1389         GNUNET_STATISTICS_update (stats,
1390                                   "# duplicate DATA",
1391                                   1,
1392                                   GNUNET_NO);
1393         GNUNET_MQ_discard (env);
1394         send_channel_data_ack (ch);
1395         return;
1396       }
1397       ch->mid_futures |= (1LLU << delta);
1398       LOG (GNUNET_ERROR_TYPE_DEBUG,
1399            "Marked bit %llX for mid %u (base: %u); now: %llX\n",
1400            (1LLU << delta),
1401            mid_msg,
1402            mid_min,
1403            ch->mid_futures);
1404     }
1405   }
1406   else /* ! ch->reliable */
1407   {
1408     struct CadetOutOfOrderMessage *next_msg;
1409
1410     /**
1411      * We always send if possible in this case.
1412      * It is guaranteed that the queued MID < received MID
1413      **/
1414     if ((NULL != ccc->head_recv) &&
1415         (GNUNET_YES == ccc->client_ready))
1416     {
1417       next_msg = ccc->head_recv;
1418       LOG (GNUNET_ERROR_TYPE_DEBUG,
1419            "Giving queued MID %u from %s to client %s\n",
1420            ntohl (next_msg->mid.mid),
1421            GCCH_2s (ch),
1422            GSC_2s (ccc->c));
1423       ccc->client_ready = GNUNET_NO;
1424       GSC_send_to_client (ccc->c,
1425                           next_msg->env);
1426       ch->mid_recv.mid = htonl (1 + ntohl (next_msg->mid.mid));
1427       ch->mid_futures >>= 1;
1428       send_channel_data_ack (ch);
1429       GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
1430                                    ccc->tail_recv,
1431                                    next_msg);
1432       ccc->num_recv--;
1433       /* Do not process duplicate MID */
1434       if (msg->mid.mid == next_msg->mid.mid) /* Duplicate */
1435       {
1436         /* Duplicate within the queue, drop */
1437         LOG (GNUNET_ERROR_TYPE_DEBUG,
1438              "Message on %s (mid %u) dropped, duplicate\n",
1439              GCCH_2s (ch),
1440              ntohl (msg->mid.mid));
1441         GNUNET_free (next_msg);
1442         GNUNET_MQ_discard (env);
1443         return;
1444       }
1445       GNUNET_free (next_msg);
1446     }
1447
1448     if (ntohl (msg->mid.mid) < ntohl (ch->mid_recv.mid)) /* Old */
1449     {
1450       /* Duplicate within the queue, drop */
1451       LOG (GNUNET_ERROR_TYPE_DEBUG,
1452            "Message on %s (mid %u) dropped, old.\n",
1453            GCCH_2s (ch),
1454            ntohl (msg->mid.mid));
1455       GNUNET_MQ_discard (env);
1456       return;
1457     }
1458
1459     /* Channel is unreliable, so we do not ACK. But we also cannot
1460        allow buffering everything, so check if we have space... */
1461     if (ccc->num_recv >= ch->max_pending_messages)
1462     {
1463       struct CadetOutOfOrderMessage *drop;
1464
1465       /* Yep, need to drop. Drop the oldest message in
1466          the buffer. */
1467       LOG (GNUNET_ERROR_TYPE_DEBUG,
1468            "Queue full due slow client on %s, dropping oldest message\n",
1469            GCCH_2s (ch));
1470       GNUNET_STATISTICS_update (stats,
1471                                 "# messages dropped due to slow client",
1472                                 1,
1473                                 GNUNET_NO);
1474       drop = ccc->head_recv;
1475       GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
1476                                    ccc->tail_recv,
1477                                    drop);
1478       ccc->num_recv--;
1479       GNUNET_MQ_discard (drop->env);
1480       GNUNET_free (drop);
1481     }
1482   }
1483
1484   /* Insert message into sorted out-of-order queue */
1485   com = GNUNET_new (struct CadetOutOfOrderMessage);
1486   com->mid = msg->mid;
1487   com->env = env;
1488   duplicate = GNUNET_NO;
1489   GNUNET_CONTAINER_DLL_insert_sorted (struct CadetOutOfOrderMessage,
1490                                       is_before,
1491                                       &duplicate,
1492                                       ccc->head_recv,
1493                                       ccc->tail_recv,
1494                                       com);
1495   ccc->num_recv++;
1496   if (GNUNET_YES == duplicate)
1497   {
1498     /* Duplicate within the queue, drop also (this is not covered by
1499        the case above if "delta" >= 64, which could be the case if
1500        max_pending_messages is also >= 64 or if our client is unready
1501        and we are seeing retransmissions of the message our client is
1502        blocked on. */
1503     LOG (GNUNET_ERROR_TYPE_DEBUG,
1504          "Duplicate payload of %u bytes on %s (mid %u) dropped\n",
1505          (unsigned int) payload_size,
1506          GCCH_2s (ch),
1507          ntohl (msg->mid.mid));
1508     GNUNET_STATISTICS_update (stats,
1509                               "# duplicate DATA",
1510                               1,
1511                               GNUNET_NO);
1512     GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
1513                                  ccc->tail_recv,
1514                                  com);
1515     ccc->num_recv--;
1516     GNUNET_MQ_discard (com->env);
1517     GNUNET_free (com);
1518     send_channel_data_ack (ch);
1519     return;
1520   }
1521   LOG (GNUNET_ERROR_TYPE_DEBUG,
1522        "Queued %s payload of %u bytes on %s-%X(%p) (mid %u, need %u first)\n",
1523        (GNUNET_YES == ccc->client_ready)
1524        ? "out-of-order"
1525        : "client-not-ready",
1526        (unsigned int) payload_size,
1527        GCCH_2s (ch),
1528        ntohl (ccc->ccn.channel_of_client),
1529        ccc,
1530        ntohl (msg->mid.mid),
1531        ntohl (ch->mid_recv.mid));
1532   /* NOTE: this ACK we _could_ skip, as the packet is out-of-order and
1533      the sender may already be transmitting the previous one.  Needs
1534      experimental evaluation to see if/when this ACK helps or
1535      hurts. (We might even want another option.) */
1536   send_channel_data_ack (ch);
1537 }
1538
1539
1540 /**
1541  * Function called once the tunnel has sent one of our messages.
1542  * If the message is unreliable, simply frees the `crm`. If the
1543  * message was reliable, calculate retransmission time and
1544  * wait for ACK (or retransmit).
1545  *
1546  * @param cls the `struct CadetReliableMessage` that was sent
1547  * @param cid identifier of the connection within the tunnel, NULL
1548  *            if transmission failed
1549  */
1550 static void
1551 data_sent_cb (void *cls,
1552               const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid);
1553
1554
1555 /**
1556  * We need to retry a transmission, the last one took too long to
1557  * be acknowledged.
1558  *
1559  * @param cls the `struct CadetChannel` where we need to retransmit
1560  */
1561 static void
1562 retry_transmission (void *cls)
1563 {
1564   struct CadetChannel *ch = cls;
1565   struct CadetReliableMessage *crm = ch->head_sent;
1566
1567   ch->retry_data_task = NULL;
1568   GNUNET_assert (NULL == crm->qe);
1569   LOG (GNUNET_ERROR_TYPE_DEBUG,
1570        "Retrying transmission on %s of message %u\n",
1571        GCCH_2s (ch),
1572        (unsigned int) ntohl (crm->data_message->mid.mid));
1573   crm->qe = GCT_send (ch->t,
1574                       &crm->data_message->header,
1575                       &data_sent_cb,
1576                       crm);
1577   GNUNET_assert (NULL == ch->retry_data_task);
1578 }
1579
1580
1581 /**
1582  * We got an PLAINTEXT_DATA_ACK for a message in our queue, remove it from
1583  * the queue and tell our client that it can send more.
1584  *
1585  * @param ch the channel that got the PLAINTEXT_DATA_ACK
1586  * @param cti identifier of the connection that delivered the message
1587  * @param crm the message that got acknowledged
1588  */
1589 static void
1590 handle_matching_ack (struct CadetChannel *ch,
1591                      const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti,
1592                      struct CadetReliableMessage *crm)
1593 {
1594   GNUNET_CONTAINER_DLL_remove (ch->head_sent,
1595                                ch->tail_sent,
1596                                crm);
1597   ch->pending_messages--;
1598   GNUNET_assert (ch->pending_messages < ch->max_pending_messages);
1599   LOG (GNUNET_ERROR_TYPE_DEBUG,
1600        "Received DATA_ACK on %s for message %u (%u ACKs pending)\n",
1601        GCCH_2s (ch),
1602        (unsigned int) ntohl (crm->data_message->mid.mid),
1603        ch->pending_messages);
1604   if (NULL != crm->qe)
1605   {
1606     GCT_send_cancel (crm->qe);
1607     crm->qe = NULL;
1608   }
1609   if ( (1 == crm->num_transmissions) &&
1610        (NULL != cti) )
1611   {
1612     GCC_ack_observed (cti);
1613     if (0 == GNUNET_memcmp (cti,
1614                      &crm->connection_taken))
1615     {
1616       GCC_latency_observed (cti,
1617                             GNUNET_TIME_absolute_get_duration (crm->first_transmission_time));
1618     }
1619   }
1620   GNUNET_free (crm->data_message);
1621   GNUNET_free (crm);
1622   send_ack_to_client (ch,
1623                       (NULL == ch->owner)
1624                       ? GNUNET_NO
1625                       : GNUNET_YES);
1626 }
1627
1628
1629 /**
1630  * We got an acknowledgement for payload data for a channel.
1631  * Possibly resume transmissions.
1632  *
1633  * @param ch channel that got the ack
1634  * @param cti identifier of the connection that delivered the message
1635  * @param ack details about what was received
1636  */
1637 void
1638 GCCH_handle_channel_plaintext_data_ack (struct CadetChannel *ch,
1639                                         const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti,
1640                                         const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1641 {
1642   struct CadetReliableMessage *crm;
1643   struct CadetReliableMessage *crmn;
1644   int found;
1645   uint32_t mid_base;
1646   uint64_t mid_mask;
1647   unsigned int delta;
1648
1649   GNUNET_break (GNUNET_NO == ch->is_loopback);
1650   if (GNUNET_NO == ch->reliable)
1651   {
1652     /* not expecting ACKs on unreliable channel, odd */
1653     GNUNET_break_op (0);
1654     return;
1655   }
1656   /* mid_base is the MID of the next message that the
1657      other peer expects (i.e. that is missing!), everything
1658      LOWER (but excluding mid_base itself) was received. */
1659   mid_base = ntohl (ack->mid.mid);
1660   mid_mask = GNUNET_htonll (ack->futures);
1661   found = GNUNET_NO;
1662   for (crm = ch->head_sent;
1663        NULL != crm;
1664        crm = crmn)
1665   {
1666     crmn = crm->next;
1667     delta = (unsigned int) (ntohl (crm->data_message->mid.mid) - mid_base);
1668     if (delta >= UINT_MAX - ch->max_pending_messages)
1669     {
1670       /* overflow, means crm was a bit in the past, so this ACK counts for it. */
1671       LOG (GNUNET_ERROR_TYPE_DEBUG,
1672            "Got DATA_ACK with base %u satisfying past message %u on %s\n",
1673            (unsigned int) mid_base,
1674            ntohl (crm->data_message->mid.mid),
1675            GCCH_2s (ch));
1676       handle_matching_ack (ch,
1677                            cti,
1678                            crm);
1679       found = GNUNET_YES;
1680       continue;
1681     }
1682     delta--;
1683     if (delta >= 64)
1684       continue;
1685     LOG (GNUNET_ERROR_TYPE_DEBUG,
1686          "Testing bit %llX for mid %u (base: %u)\n",
1687          (1LLU << delta),
1688          ntohl (crm->data_message->mid.mid),
1689          mid_base);
1690     if (0 != (mid_mask & (1LLU << delta)))
1691     {
1692       LOG (GNUNET_ERROR_TYPE_DEBUG,
1693            "Got DATA_ACK with mask for %u on %s\n",
1694            ntohl (crm->data_message->mid.mid),
1695            GCCH_2s (ch));
1696       handle_matching_ack (ch,
1697                            cti,
1698                            crm);
1699       found = GNUNET_YES;
1700     }
1701   }
1702   if (GNUNET_NO == found)
1703   {
1704     /* ACK for message we already dropped, might have been a
1705        duplicate ACK? Ignore. */
1706     LOG (GNUNET_ERROR_TYPE_DEBUG,
1707          "Duplicate DATA_ACK on %s, ignoring\n",
1708          GCCH_2s (ch));
1709     GNUNET_STATISTICS_update (stats,
1710                               "# duplicate DATA_ACKs",
1711                               1,
1712                               GNUNET_NO);
1713     return;
1714   }
1715   if (NULL != ch->retry_data_task)
1716   {
1717     GNUNET_SCHEDULER_cancel (ch->retry_data_task);
1718     ch->retry_data_task = NULL;
1719   }
1720   if ( (NULL != ch->head_sent) &&
1721        (NULL == ch->head_sent->qe) )
1722     ch->retry_data_task
1723       = GNUNET_SCHEDULER_add_at (ch->head_sent->next_retry,
1724                                  &retry_transmission,
1725                                  ch);
1726 }
1727
1728
1729 /**
1730  * Destroy channel, based on the other peer closing the
1731  * connection.  Also needs to remove this channel from
1732  * the tunnel.
1733  *
1734  * @param ch channel to destroy
1735  * @param cti identifier of the connection that delivered the message,
1736  *            NULL if we are simulating receiving a destroy due to shutdown
1737  */
1738 void
1739 GCCH_handle_remote_destroy (struct CadetChannel *ch,
1740                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti)
1741 {
1742   struct CadetChannelClient *ccc;
1743
1744   GNUNET_assert (GNUNET_NO == ch->is_loopback);
1745   LOG (GNUNET_ERROR_TYPE_DEBUG,
1746        "Received remote channel DESTROY for %s\n",
1747        GCCH_2s (ch));
1748   if (GNUNET_YES == ch->destroy)
1749   {
1750     /* Local client already gone, this is instant-death. */
1751     channel_destroy (ch);
1752     return;
1753   }
1754   ccc = (NULL != ch->owner) ? ch->owner : ch->dest;
1755   if ( (NULL != ccc) &&
1756        (NULL != ccc->head_recv) )
1757   {
1758     LOG (GNUNET_ERROR_TYPE_WARNING,
1759          "Lost end of transmission due to remote shutdown on %s\n",
1760          GCCH_2s (ch));
1761     /* FIXME: change API to notify client about truncated transmission! */
1762   }
1763   ch->destroy = GNUNET_YES;
1764   if (NULL != ccc)
1765     GSC_handle_remote_channel_destroy (ccc->c,
1766                                        ccc->ccn,
1767                                        ch);
1768   channel_destroy (ch);
1769 }
1770
1771
1772 /**
1773  * Test if element @a e1 comes before element @a e2.
1774  *
1775  * @param cls closure, to a flag where we indicate duplicate packets
1776  * @param crm1 an element of to sort
1777  * @param crm2 another element to sort
1778  * @return #GNUNET_YES if @e1 < @e2, otherwise #GNUNET_NO
1779  */
1780 static int
1781 cmp_crm_by_next_retry (void *cls,
1782                        struct CadetReliableMessage *crm1,
1783                        struct CadetReliableMessage *crm2)
1784 {
1785   if (crm1->next_retry.abs_value_us <
1786       crm2->next_retry.abs_value_us)
1787     return GNUNET_YES;
1788   return GNUNET_NO;
1789 }
1790
1791
1792 /**
1793  * Function called once the tunnel has sent one of our messages.
1794  * If the message is unreliable, simply frees the `crm`. If the
1795  * message was reliable, calculate retransmission time and
1796  * wait for ACK (or retransmit).
1797  *
1798  * @param cls the `struct CadetReliableMessage` that was sent
1799  * @param cid identifier of the connection within the tunnel, NULL
1800  *            if transmission failed
1801  */
1802 static void
1803 data_sent_cb (void *cls,
1804               const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid)
1805 {
1806   struct CadetReliableMessage *crm = cls;
1807   struct CadetChannel *ch = crm->ch;
1808
1809   GNUNET_assert (GNUNET_NO == ch->is_loopback);
1810   GNUNET_assert (NULL != crm->qe);
1811   crm->qe = NULL;
1812   GNUNET_CONTAINER_DLL_remove (ch->head_sent,
1813                                ch->tail_sent,
1814                                crm);
1815   if (GNUNET_NO == ch->reliable)
1816   {
1817     GNUNET_free (crm->data_message);
1818     GNUNET_free (crm);
1819     ch->pending_messages--;
1820     send_ack_to_client (ch,
1821                         (NULL == ch->owner)
1822                         ? GNUNET_NO
1823                         : GNUNET_YES);
1824     return;
1825   }
1826   if (NULL == cid)
1827   {
1828     /* There was an error sending. */
1829     crm->num_transmissions = GNUNET_SYSERR;
1830   }
1831   else if (GNUNET_SYSERR != crm->num_transmissions)
1832   {
1833     /* Increment transmission counter, and possibly store @a cid
1834        if this was the first transmission. */
1835     crm->num_transmissions++;
1836     if (1 == crm->num_transmissions)
1837     {
1838       crm->first_transmission_time = GNUNET_TIME_absolute_get ();
1839       crm->connection_taken = *cid;
1840       GCC_ack_expected (cid);
1841     }
1842   }
1843   if ( (0 == crm->retry_delay.rel_value_us) &&
1844        (NULL != cid) )
1845   {
1846     struct CadetConnection *cc = GCC_lookup (cid);
1847
1848     if (NULL != cc)
1849       crm->retry_delay = GCC_get_metrics (cc)->aged_latency;
1850     else
1851       crm->retry_delay = ch->retry_time;
1852   }
1853   crm->retry_delay = GNUNET_TIME_STD_BACKOFF (crm->retry_delay);
1854   crm->retry_delay = GNUNET_TIME_relative_max (crm->retry_delay,
1855                                                MIN_RTT_DELAY);
1856   crm->next_retry = GNUNET_TIME_relative_to_absolute (crm->retry_delay);
1857
1858   GNUNET_CONTAINER_DLL_insert_sorted (struct CadetReliableMessage,
1859                                       cmp_crm_by_next_retry,
1860                                       NULL,
1861                                       ch->head_sent,
1862                                       ch->tail_sent,
1863                                       crm);
1864   LOG (GNUNET_ERROR_TYPE_DEBUG,
1865        "Message %u sent, next transmission on %s in %s\n",
1866        (unsigned int) ntohl (crm->data_message->mid.mid),
1867        GCCH_2s (ch),
1868        GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (ch->head_sent->next_retry),
1869                                                GNUNET_YES));
1870   if (NULL == ch->head_sent->qe)
1871   {
1872     if (NULL != ch->retry_data_task)
1873       GNUNET_SCHEDULER_cancel (ch->retry_data_task);
1874     ch->retry_data_task
1875       = GNUNET_SCHEDULER_add_at (ch->head_sent->next_retry,
1876                                  &retry_transmission,
1877                                  ch);
1878   }
1879 }
1880
1881
1882 /**
1883  * Handle data given by a client.
1884  *
1885  * Check whether the client is allowed to send in this tunnel, save if
1886  * channel is reliable and send an ACK to the client if there is still
1887  * buffer space in the tunnel.
1888  *
1889  * @param ch Channel.
1890  * @param sender_ccn ccn of the sender
1891  * @param buf payload to transmit.
1892  * @param buf_len number of bytes in @a buf
1893  * @return #GNUNET_OK if everything goes well,
1894  *         #GNUNET_SYSERR in case of an error.
1895  */
1896 int
1897 GCCH_handle_local_data (struct CadetChannel *ch,
1898                         struct GNUNET_CADET_ClientChannelNumber sender_ccn,
1899                         const char *buf,
1900                         size_t buf_len)
1901 {
1902   struct CadetReliableMessage *crm;
1903
1904   if (ch->pending_messages >= ch->max_pending_messages)
1905   {
1906     GNUNET_break (0); /* Fails: #5370 */
1907     return GNUNET_SYSERR;
1908   }
1909   if (GNUNET_YES == ch->destroy)
1910   {
1911     /* we are going down, drop messages */
1912     return GNUNET_OK;
1913   }
1914   ch->pending_messages++;
1915
1916   if (GNUNET_YES == ch->is_loopback)
1917   {
1918     struct CadetChannelClient *receiver;
1919     struct GNUNET_MQ_Envelope *env;
1920     struct GNUNET_CADET_LocalData *ld;
1921     int ack_to_owner;
1922
1923     env = GNUNET_MQ_msg_extra (ld,
1924                                buf_len,
1925                                GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA);
1926     if ( (NULL != ch->owner) &&
1927          (sender_ccn.channel_of_client ==
1928           ch->owner->ccn.channel_of_client) )
1929     {
1930       receiver = ch->dest;
1931       ack_to_owner = GNUNET_YES;
1932     }
1933     else if ( (NULL != ch->dest) &&
1934               (sender_ccn.channel_of_client ==
1935                ch->dest->ccn.channel_of_client) )
1936     {
1937       receiver = ch->owner;
1938       ack_to_owner = GNUNET_NO;
1939     }
1940     else
1941     {
1942       GNUNET_break (0);
1943       return GNUNET_SYSERR;
1944     }
1945     GNUNET_assert (NULL != receiver);
1946     ld->ccn = receiver->ccn;
1947     GNUNET_memcpy (&ld[1],
1948                    buf,
1949                    buf_len);
1950     if (GNUNET_YES == receiver->client_ready)
1951     {
1952       ch->pending_messages--;
1953       GSC_send_to_client (receiver->c,
1954                           env);
1955       send_ack_to_client (ch,
1956                           ack_to_owner);
1957     }
1958     else
1959     {
1960       struct CadetOutOfOrderMessage *oom;
1961
1962       oom = GNUNET_new (struct CadetOutOfOrderMessage);
1963       oom->env = env;
1964       GNUNET_CONTAINER_DLL_insert_tail (receiver->head_recv,
1965                                         receiver->tail_recv,
1966                                         oom);
1967       receiver->num_recv++;
1968     }
1969     return GNUNET_OK;
1970   }
1971
1972   /* Everything is correct, send the message. */
1973   crm = GNUNET_malloc (sizeof (*crm));
1974   crm->ch = ch;
1975   crm->data_message = GNUNET_malloc (sizeof (struct GNUNET_CADET_ChannelAppDataMessage)
1976                                      + buf_len);
1977   crm->data_message->header.size = htons (sizeof (struct GNUNET_CADET_ChannelAppDataMessage) + buf_len);
1978   crm->data_message->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA);
1979   ch->mid_send.mid = htonl (ntohl (ch->mid_send.mid) + 1);
1980   crm->data_message->mid = ch->mid_send;
1981   crm->data_message->ctn = ch->ctn;
1982   GNUNET_memcpy (&crm->data_message[1],
1983                  buf,
1984                  buf_len);
1985   GNUNET_CONTAINER_DLL_insert_tail (ch->head_sent,
1986                                     ch->tail_sent,
1987                                     crm);
1988   LOG (GNUNET_ERROR_TYPE_DEBUG,
1989        "Sending message %u from local client to %s with %u bytes\n",
1990        ntohl (crm->data_message->mid.mid),
1991        GCCH_2s (ch),
1992        buf_len);
1993   if (NULL != ch->retry_data_task)
1994   {
1995     GNUNET_SCHEDULER_cancel (ch->retry_data_task);
1996     ch->retry_data_task = NULL;
1997   }
1998   crm->qe = GCT_send (ch->t,
1999                       &crm->data_message->header,
2000                       &data_sent_cb,
2001                       crm);
2002   GNUNET_assert (NULL == ch->retry_data_task);
2003   return GNUNET_OK;
2004 }
2005
2006
2007 /**
2008  * Handle ACK from client on local channel.  Means the client is ready
2009  * for more data, see if we have any for it.
2010  *
2011  * @param ch channel to destroy
2012  * @param client_ccn ccn of the client sending the ack
2013  */
2014 void
2015 GCCH_handle_local_ack (struct CadetChannel *ch,
2016                        struct GNUNET_CADET_ClientChannelNumber client_ccn)
2017 {
2018   struct CadetChannelClient *ccc;
2019   struct CadetOutOfOrderMessage *com;
2020
2021   if ( (NULL != ch->owner) &&
2022        (ch->owner->ccn.channel_of_client == client_ccn.channel_of_client) )
2023     ccc = ch->owner;
2024   else if ( (NULL != ch->dest) &&
2025             (ch->dest->ccn.channel_of_client == client_ccn.channel_of_client) )
2026     ccc = ch->dest;
2027   else
2028     GNUNET_assert (0);
2029   ccc->client_ready = GNUNET_YES;
2030   com = ccc->head_recv;
2031   if (NULL == com)
2032   {
2033     LOG (GNUNET_ERROR_TYPE_DEBUG,
2034          "Got LOCAL_ACK, %s-%X ready to receive more data, but none pending on %s-%X(%p)!\n",
2035          GSC_2s (ccc->c),
2036          ntohl (client_ccn.channel_of_client),
2037          GCCH_2s (ch),
2038          ntohl (ccc->ccn.channel_of_client),
2039          ccc);
2040     return; /* none pending */
2041   }
2042   if (GNUNET_YES == ch->is_loopback)
2043   {
2044     int to_owner;
2045
2046     /* Messages are always in-order, just send */
2047     GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
2048                                  ccc->tail_recv,
2049                                  com);
2050     ccc->num_recv--;
2051     GSC_send_to_client (ccc->c,
2052                         com->env);
2053     /* Notify sender that we can receive more */
2054     if ( (NULL != ch->owner) &&
2055          (ccc->ccn.channel_of_client ==
2056           ch->owner->ccn.channel_of_client) )
2057     {
2058       to_owner = GNUNET_NO;
2059     }
2060     else
2061     {
2062       GNUNET_assert ( (NULL != ch->dest) &&
2063                       (ccc->ccn.channel_of_client ==
2064                        ch->dest->ccn.channel_of_client) );
2065       to_owner = GNUNET_YES;
2066     }
2067     send_ack_to_client (ch,
2068                         to_owner);
2069     GNUNET_free (com);
2070     return;
2071   }
2072
2073   if ( (com->mid.mid != ch->mid_recv.mid) &&
2074        (GNUNET_NO == ch->out_of_order) &&
2075        (GNUNET_YES == ch->reliable) )
2076   {
2077     LOG (GNUNET_ERROR_TYPE_DEBUG,
2078          "Got LOCAL_ACK, %s-%X ready to receive more data (but next one is out-of-order %u vs. %u)!\n",
2079          GSC_2s (ccc->c),
2080          ntohl (ccc->ccn.channel_of_client),
2081          ntohl (com->mid.mid),
2082          ntohl (ch->mid_recv.mid));
2083     return; /* missing next one in-order */
2084   }
2085
2086   LOG (GNUNET_ERROR_TYPE_DEBUG,
2087        "Got LOCAL_ACK, giving payload message %u to %s-%X on %s\n",
2088        ntohl (com->mid.mid),
2089        GSC_2s (ccc->c),
2090        ntohl (ccc->ccn.channel_of_client),
2091        GCCH_2s (ch));
2092
2093   /* all good, pass next message to client */
2094   GNUNET_CONTAINER_DLL_remove (ccc->head_recv,
2095                                ccc->tail_recv,
2096                                com);
2097   ccc->num_recv--;
2098   /* FIXME: if unreliable, this is not aggressive
2099      enough, as it would be OK to have lost some! */
2100
2101   ch->mid_recv.mid = htonl (1 + ntohl (com->mid.mid));
2102   ch->mid_futures >>= 1; /* equivalent to division by 2 */
2103   ccc->client_ready = GNUNET_NO;
2104   GSC_send_to_client (ccc->c,
2105                       com->env);
2106   GNUNET_free (com);
2107   send_channel_data_ack (ch);
2108   if (NULL != ccc->head_recv)
2109     return;
2110   if (GNUNET_NO == ch->destroy)
2111     return;
2112   GCT_send_channel_destroy (ch->t,
2113                             ch->ctn);
2114   channel_destroy (ch);
2115 }
2116
2117
2118 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-chn",__VA_ARGS__)
2119
2120
2121 /**
2122  * Log channel info.
2123  *
2124  * @param ch Channel.
2125  * @param level Debug level to use.
2126  */
2127 void
2128 GCCH_debug (struct CadetChannel *ch,
2129             enum GNUNET_ErrorType level)
2130 {
2131 #if !defined(GNUNET_CULL_LOGGING)
2132   int do_log;
2133
2134   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2135                                        "cadet-chn",
2136                                        __FILE__, __FUNCTION__, __LINE__);
2137   if (0 == do_log)
2138     return;
2139
2140   if (NULL == ch)
2141   {
2142     LOG2 (level, "CHN *** DEBUG NULL CHANNEL ***\n");
2143     return;
2144   }
2145   LOG2 (level,
2146         "CHN %s:%X (%p)\n",
2147         GCT_2s (ch->t),
2148         ch->ctn,
2149         ch);
2150   if (NULL != ch->owner)
2151   {
2152     LOG2 (level,
2153           "CHN origin %s ready %s local-id: %u\n",
2154           GSC_2s (ch->owner->c),
2155           ch->owner->client_ready ? "YES" : "NO",
2156           ntohl (ch->owner->ccn.channel_of_client));
2157   }
2158   if (NULL != ch->dest)
2159   {
2160     LOG2 (level,
2161           "CHN destination %s ready %s local-id: %u\n",
2162           GSC_2s (ch->dest->c),
2163           ch->dest->client_ready ? "YES" : "NO",
2164           ntohl (ch->dest->ccn.channel_of_client));
2165   }
2166   LOG2 (level,
2167         "CHN  Message IDs recv: %d (%LLX), send: %d\n",
2168         ntohl (ch->mid_recv.mid),
2169         (unsigned long long) ch->mid_futures,
2170         ntohl (ch->mid_send.mid));
2171 #endif
2172 }
2173
2174
2175
2176 /* end of gnunet-service-cadet-new_channel.c */