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