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