more work on new tunnel logic
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_channel.c
1
2 /*
3      This file is part of GNUnet.
4      Copyright (C) 2001-2017 GNUnet e.V.
5
6      GNUnet is free software; you can redistribute it and/or modify
7      it under the terms of the GNU General Public License as published
8      by the Free Software Foundation; either version 3, or (at your
9      option) any later version.
10
11      GNUnet is distributed in the hope that it will be useful, but
12      WITHOUT ANY WARRANTY; without even the implied warranty of
13      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14      General Public License for more details.
15
16      You should have received a copy of the GNU General Public License
17      along with GNUnet; see the file COPYING.  If not, write to the
18      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19      Boston, MA 02110-1301, USA.
20 */
21 /**
22  * @file cadet/gnunet-service-cadet-new_channel.c
23  * @brief logical links between CADET clients
24  * @author Bartlomiej Polot
25  * @author Christian Grothoff
26  *
27  * TODO:
28  * - handle CREATE_ACK
29  * - handle plaintext data
30  * - handle plaintext ACK
31  * - handle destroy
32  * - estimate max bandwidth using bursts and use to for CONGESTION CONTROL!
33  * - check that '0xFFULL' really is sufficient for flow control!
34  * - what about the 'no buffer' option?
35  * - what about the 'out-of-order' option?
36  */
37 #include "platform.h"
38 #include "gnunet_util_lib.h"
39 #include "cadet.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet-service-cadet-new.h"
42 #include "gnunet-service-cadet-new_channel.h"
43 #include "gnunet-service-cadet-new_connection.h"
44 #include "gnunet-service-cadet-new_tunnels.h"
45 #include "gnunet-service-cadet-new_peer.h"
46 #include "gnunet-service-cadet-new_paths.h"
47
48 #define LOG(level, ...) GNUNET_log (level,__VA_ARGS__)
49
50 /**
51  * How long do we initially wait before retransmitting?
52  */
53 #define CADET_INITIAL_RETRANSMIT_TIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
54
55 /**
56  * How long do we wait before dropping state about incoming
57  * connection to closed port?
58  */
59 #define TIMEOUT_CLOSED_PORT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
60
61
62 /**
63  * All the states a connection can be in.
64  */
65 enum CadetChannelState
66 {
67   /**
68    * Uninitialized status, should never appear in operation.
69    */
70   CADET_CHANNEL_NEW,
71
72   /**
73    * Connection create message sent, waiting for ACK.
74    */
75   CADET_CHANNEL_CREATE_SENT,
76
77   /**
78    * Connection confirmed, ready to carry traffic.
79    */
80   CADET_CHANNEL_READY
81 };
82
83
84 /**
85  * Info needed to retry a message in case it gets lost.
86  * Note that we DO use this structure also for unreliable
87  * messages.
88  */
89 struct CadetReliableMessage
90 {
91   /**
92    * Double linked list, FIFO style
93    */
94   struct CadetReliableMessage *next;
95
96   /**
97    * Double linked list, FIFO style
98    */
99   struct CadetReliableMessage *prev;
100
101   /**
102    * Which channel is this message in?
103    */
104   struct CadetChannel *ch;
105
106   /**
107    * Entry in the tunnels queue for this message, NULL if it has left
108    * the tunnel.  Used to cancel transmission in case we receive an
109    * ACK in time.
110    */
111   struct CadetTunnelQueueEntry *qe;
112
113   /**
114    * How soon should we retry if we fail to get an ACK?
115    * Messages in the queue are sorted by this value.
116    */
117   struct GNUNET_TIME_Absolute next_retry;
118
119   /**
120    * How long do we wait for an ACK after transmission?
121    * Use for the back-off calculation.
122    */
123   struct GNUNET_TIME_Relative retry_delay;
124
125   /**
126    * Data message we are trying to send.
127    */
128   struct GNUNET_CADET_ChannelAppDataMessage data_message;
129
130   /* followed by variable-size payload */
131 };
132
133
134 /**
135  * List of received out-of-order data messages.
136  */
137 struct CadetOutOfOrderMessage
138 {
139   /**
140    * Double linked list, FIFO style
141    */
142   struct CadetOutOfOrderMessage *next;
143
144   /**
145    * Double linked list, FIFO style
146    */
147   struct CadetOutOfOrderMessage *prev;
148
149   /**
150    * ID of the message (ACK needed to free)
151    */
152   struct ChannelMessageIdentifier mid;
153
154   /**
155    * The envelope with the payload of the out-of-order message
156    */
157   struct GNUNET_MQ_Envelope *env;
158
159 };
160
161
162 /**
163  * Struct containing all information regarding a channel to a remote client.
164  */
165 struct CadetChannel
166 {
167   /**
168    * Tunnel this channel is in.
169    */
170   struct CadetTunnel *t;
171
172   /**
173    * Last entry in the tunnel's queue relating to control messages
174    * (#GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN or
175    * #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK).  Used to cancel
176    * transmission in case we receive updated information.
177    */
178   struct CadetTunnelQueueEntry *last_control_qe;
179
180   /**
181    * Client owner of the tunnel, if any.
182    * (Used if this channel represends the initiating end of the tunnel.)
183    */
184   struct CadetClient *owner;
185
186   /**
187    * Client destination of the tunnel, if any.
188    * (Used if this channel represents the listening end of the tunnel.)
189    */
190   struct CadetClient *dest;
191
192   /**
193    * Head of DLL of messages sent and not yet ACK'd.
194    */
195   struct CadetReliableMessage *head_sent;
196
197   /**
198    * Tail of DLL of messages sent and not yet ACK'd.
199    */
200   struct CadetReliableMessage *tail_sent;
201
202   /**
203    * Head of DLL of messages received out of order or while client was unready.
204    */
205   struct CadetOutOfOrderMessage *head_recv;
206
207   /**
208    * Tail DLL of messages received out of order or while client was unready.
209    */
210   struct CadetOutOfOrderMessage *tail_recv;
211
212   /**
213    * Task to resend/poll in case no ACK is received.
214    */
215   struct GNUNET_SCHEDULER_Task *retry_task;
216
217   /**
218    * Last time the channel was used
219    */
220   struct GNUNET_TIME_Absolute timestamp;
221
222   /**
223    * Destination port of the channel.
224    */
225   struct GNUNET_HashCode port;
226
227   /**
228    * Counter for exponential backoff.
229    */
230   struct GNUNET_TIME_Relative retry_time;
231
232   /**
233    * How long does it usually take to get an ACK.
234    */
235   struct GNUNET_TIME_Relative expected_delay;
236
237   /**
238    * Bitfield of already-received messages past @e mid_recv.
239    */
240   uint64_t mid_futures;
241
242   /**
243    * Next MID expected for incoming traffic.
244    */
245   struct ChannelMessageIdentifier mid_recv;
246
247   /**
248    * Next MID to use for outgoing traffic.
249    */
250   struct ChannelMessageIdentifier mid_send;
251
252   /**
253    * Total (reliable) messages pending ACK for this channel.
254    */
255   unsigned int pending_messages;
256
257   /**
258    * Maximum (reliable) messages pending ACK for this channel
259    * before we throttle the client.
260    */
261   unsigned int max_pending_messages;
262
263   /**
264    * Number identifying this channel in its tunnel.
265    */
266   struct GNUNET_CADET_ChannelTunnelNumber chid;
267
268   /**
269    * Local tunnel number for local client owning the channel.
270    * ( >= #GNUNET_CADET_LOCAL_CHANNEL_ID_CLI or 0 )
271    */
272   struct GNUNET_CADET_ClientChannelNumber lid;
273
274   /**
275    * Channel state.
276    */
277   enum CadetChannelState state;
278
279   /**
280    * Can we send data to the client?
281    */
282   int client_ready;
283
284   /**
285    * Can the client send data to us?
286    */
287   int client_allowed;
288
289   /**
290    * Is the tunnel bufferless (minimum latency)?
291    */
292   int nobuffer;
293
294   /**
295    * Is the tunnel reliable?
296    */
297   int reliable;
298
299   /**
300    * Is the tunnel out-of-order?
301    */
302   int out_of_order;
303
304   /**
305    * Flag to signal the destruction of the channel.  If this is set to
306    * #GNUNET_YES the channel will be destroyed once the queue is
307    * empty.
308    */
309   int destroy;
310
311 };
312
313
314
315 /**
316  * Get the static string for identification of the channel.
317  *
318  * @param ch Channel.
319  *
320  * @return Static string with the channel IDs.
321  */
322 const char *
323 GCCH_2s (const struct CadetChannel *ch)
324 {
325   static char buf[128];
326
327   if (NULL == ch)
328     return "(NULL Channel)";
329   GNUNET_snprintf (buf,
330                    sizeof (buf),
331                    "%s:%s chid:%X (%X)",
332                    GCT_2s (ch->t),
333                    GNUNET_h2s (&ch->port),
334                    ch->chid,
335                    ntohl (ch->lid.channel_of_client));
336   return buf;
337 }
338
339
340 /**
341  * Get the channel's public ID.
342  *
343  * @param ch Channel.
344  *
345  * @return ID used to identify the channel with the remote peer.
346  */
347 struct GNUNET_CADET_ChannelTunnelNumber
348 GCCH_get_id (const struct CadetChannel *ch)
349 {
350   return ch->chid;
351 }
352
353
354 /**
355  * Destroy the given channel.
356  *
357  * @param ch channel to destroy
358  */
359 static void
360 channel_destroy (struct CadetChannel *ch)
361 {
362   struct CadetReliableMessage *crm;
363   struct CadetOutOfOrderMessage *com;
364
365   while (NULL != (crm = ch->head_sent))
366   {
367     GNUNET_assert (ch == crm->ch);
368     if (NULL != crm->qe)
369     {
370       GCT_send_cancel (crm->qe);
371       crm->qe = NULL;
372     }
373     GNUNET_CONTAINER_DLL_remove (ch->head_sent,
374                                  ch->tail_sent,
375                                  crm);
376     GNUNET_free (crm);
377   }
378   while (NULL != (com = ch->head_recv))
379   {
380     GNUNET_CONTAINER_DLL_remove (ch->head_recv,
381                                  ch->tail_recv,
382                                  com);
383     GNUNET_MQ_discard (com->env);
384     GNUNET_free (com);
385   }
386   if (NULL != ch->last_control_qe)
387   {
388     GCT_send_cancel (ch->last_control_qe);
389     ch->last_control_qe = NULL;
390   }
391   if (NULL != ch->retry_task)
392   {
393     GNUNET_SCHEDULER_cancel (ch->retry_task);
394     ch->retry_task = NULL;
395   }
396   GCT_remove_channel (ch->t,
397                       ch,
398                       ch->chid);
399   GNUNET_free (ch);
400 }
401
402
403 /**
404  * Send a channel create message.
405  *
406  * @param cls Channel for which to send.
407  */
408 static void
409 send_create (void *cls);
410
411
412 /**
413  * Function called once the tunnel confirms that we sent the
414  * create message.  Delays for a bit until we retry.
415  *
416  * @param cls our `struct CadetChannel`.
417  */
418 static void
419 create_sent_cb (void *cls)
420 {
421   struct CadetChannel *ch = cls;
422
423   ch->last_control_qe = NULL;
424   ch->retry_time = GNUNET_TIME_STD_BACKOFF (ch->retry_time);
425   ch->retry_task = GNUNET_SCHEDULER_add_delayed (ch->retry_time,
426                                                  &send_create,
427                                                  ch);
428 }
429
430
431 /**
432  * Send a channel create message.
433  *
434  * @param cls Channel for which to send.
435  */
436 static void
437 send_create (void *cls)
438 {
439   struct CadetChannel *ch = cls;
440   struct GNUNET_CADET_ChannelOpenMessage msgcc;
441   uint32_t options;
442
443   options = 0;
444   if (ch->nobuffer)
445     options |= GNUNET_CADET_OPTION_NOBUFFER;
446   if (ch->reliable)
447     options |= GNUNET_CADET_OPTION_RELIABLE;
448   if (ch->out_of_order)
449     options |= GNUNET_CADET_OPTION_OUT_OF_ORDER;
450   msgcc.header.size = htons (sizeof (msgcc));
451   msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN);
452   msgcc.opt = htonl (options);
453   msgcc.port = ch->port;
454   msgcc.chid = ch->chid;
455   ch->state = CADET_CHANNEL_CREATE_SENT;
456   ch->last_control_qe = GCT_send (ch->t,
457                                   &msgcc.header,
458                                   &create_sent_cb,
459                                   ch);
460 }
461
462
463 /**
464  * Create a new channel.
465  *
466  * @param owner local client owning the channel
467  * @param owner_id local chid of this channel at the @a owner
468  * @param destination peer to which we should build the channel
469  * @param port desired port at @a destination
470  * @param options options for the channel
471  * @return handle to the new channel
472  */
473 struct CadetChannel *
474 GCCH_channel_local_new (struct CadetClient *owner,
475                         struct GNUNET_CADET_ClientChannelNumber owner_id,
476                         struct CadetPeer *destination,
477                         const struct GNUNET_HashCode *port,
478                         uint32_t options)
479 {
480   struct CadetChannel *ch;
481
482   ch = GNUNET_new (struct CadetChannel);
483   ch->max_pending_messages = 32; /* FIXME: allow control via options
484                                     or adjust dynamically... */
485   ch->owner = owner;
486   ch->lid = owner_id;
487   ch->port = *port;
488   ch->t = GCP_get_tunnel (destination,
489                           GNUNET_YES);
490   ch->chid = GCT_add_channel (ch->t,
491                               ch);
492   ch->retry_time = CADET_INITIAL_RETRANSMIT_TIME;
493   ch->nobuffer = (0 != (options & GNUNET_CADET_OPTION_NOBUFFER));
494   ch->reliable = (0 != (options & GNUNET_CADET_OPTION_RELIABLE));
495   ch->out_of_order = (0 != (options & GNUNET_CADET_OPTION_OUT_OF_ORDER));
496   ch->retry_task = GNUNET_SCHEDULER_add_now (&send_create,
497                                              ch);
498   GNUNET_STATISTICS_update (stats,
499                             "# channels",
500                             1,
501                             GNUNET_NO);
502   return ch;
503 }
504
505
506 /**
507  * We had an incoming channel to a port that is closed.
508  * It has not been opened for a while, drop it.
509  *
510  * @param cls the channel to drop
511  */
512 static void
513 timeout_closed_cb (void *cls)
514 {
515   struct CadetChannel *ch = cls;
516
517   ch->retry_task = NULL;
518   channel_destroy (ch);
519 }
520
521
522 /**
523  * Create a new channel based on a request coming in over the network.
524  *
525  * @param t tunnel to the remote peer
526  * @param chid identifier of this channel in the tunnel
527  * @param port desired local port
528  * @param options options for the channel
529  * @return handle to the new channel
530  */
531 struct CadetChannel *
532 GCCH_channel_incoming_new (struct CadetTunnel *t,
533                            struct GNUNET_CADET_ChannelTunnelNumber chid,
534                            const struct GNUNET_HashCode *port,
535                            uint32_t options)
536 {
537   struct CadetChannel *ch;
538   struct CadetClient *c;
539
540   ch = GNUNET_new (struct CadetChannel);
541   ch->max_pending_messages = 32; /* FIXME: allow control via options
542                                     or adjust dynamically... */
543   ch->port = *port;
544   ch->t = t;
545   ch->chid = chid;
546   ch->retry_time = CADET_INITIAL_RETRANSMIT_TIME;
547   ch->nobuffer = (0 != (options & GNUNET_CADET_OPTION_NOBUFFER));
548   ch->reliable = (0 != (options & GNUNET_CADET_OPTION_RELIABLE));
549   ch->out_of_order = (0 != (options & GNUNET_CADET_OPTION_OUT_OF_ORDER));
550   GNUNET_STATISTICS_update (stats,
551                             "# channels",
552                             1,
553                             GNUNET_NO);
554
555   c = GNUNET_CONTAINER_multihashmap_get (open_ports,
556                                          port);
557   if (NULL == c)
558   {
559     /* port closed, wait for it to possibly open */
560     (void) GNUNET_CONTAINER_multihashmap_put (loose_channels,
561                                               port,
562                                               ch,
563                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
564     ch->retry_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT_CLOSED_PORT,
565                                                    &timeout_closed_cb,
566                                                    ch);
567   }
568   else
569   {
570     GCCH_bind (ch,
571                c);
572   }
573   GNUNET_STATISTICS_update (stats,
574                             "# channels",
575                             1,
576                             GNUNET_NO);
577   return ch;
578 }
579
580
581 /**
582  * Function called once the tunnel confirms that we sent the
583  * ACK message.  Just remembers it was sent, we do not expect
584  * ACKs for ACKs ;-).
585  *
586  * @param cls our `struct CadetChannel`.
587  */
588 static void
589 send_ack_cb (void *cls)
590 {
591   struct CadetChannel *ch = cls;
592
593   ch->last_control_qe = NULL;
594 }
595
596
597 /**
598  * Compute and send the current ACK to the other peer.
599  *
600  * @param ch channel to send the ACK for
601  */
602 static void
603 send_channel_ack (struct CadetChannel *ch)
604 {
605   struct GNUNET_CADET_ChannelDataAckMessage msg;
606
607   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK);
608   msg.header.size = htons (sizeof (msg));
609   msg.chid = ch->chid;
610   msg.mid.mid = htonl (ntohl (ch->mid_recv.mid) - 1);
611   msg.futures = GNUNET_htonll (ch->mid_futures);
612   if (NULL != ch->last_control_qe)
613     GCT_send_cancel (ch->last_control_qe);
614   ch->last_control_qe = GCT_send (ch->t,
615                                   &msg.header,
616                                   &send_ack_cb,
617                                   ch);
618 }
619
620
621 /**
622  * Send our initial ACK to the client confirming that the
623  * connection is up.
624  *
625  * @param cls the `struct CadetChannel`
626  */
627 static void
628 send_connect_ack (void *cls)
629 {
630   struct CadetChannel *ch = cls;
631
632   ch->retry_task = NULL;
633   send_channel_ack (ch);
634 }
635
636
637 /**
638  * A client is bound to the port that we have a channel
639  * open to.  Send the acknowledgement for the connection
640  * request and establish the link with the client.
641  *
642  * @param ch open incoming channel
643  * @param c client listening on the respective port
644  */
645 void
646 GCCH_bind (struct CadetChannel *ch,
647            struct CadetClient *c)
648 {
649   uint32_t options;
650
651   if (NULL != ch->retry_task)
652   {
653     /* there might be a timeout task here */
654     GNUNET_SCHEDULER_cancel (ch->retry_task);
655     ch->retry_task = NULL;
656   }
657   options = 0;
658   if (ch->nobuffer)
659     options |= GNUNET_CADET_OPTION_NOBUFFER;
660   if (ch->reliable)
661     options |= GNUNET_CADET_OPTION_RELIABLE;
662   if (ch->out_of_order)
663     options |= GNUNET_CADET_OPTION_OUT_OF_ORDER;
664   ch->dest = c;
665   ch->lid = GSC_bind (c,
666                       ch,
667                       GCT_get_destination (ch->t),
668                       &ch->port,
669                       options);
670   ch->mid_recv.mid = htonl (1); /* The CONNECT counts as message 0! */
671
672   /* notify other peer that we accepted the connection */
673   ch->retry_task = GNUNET_SCHEDULER_add_now (&send_connect_ack,
674                                              ch);
675 }
676
677
678 /**
679  * Destroy locally created channel.  Called by the
680  * local client, so no need to tell the client.
681  *
682  * @param ch channel to destroy
683  */
684 void
685 GCCH_channel_local_destroy (struct CadetChannel *ch)
686 {
687   if (GNUNET_YES == ch->destroy)
688   {
689     /* other end already destroyed, with the local client gone, no need
690        to finish transmissions, just destroy immediately. */
691     channel_destroy (ch);
692     return;
693   }
694   if (NULL != ch->head_sent)
695   {
696     /* allow send queue to train first */
697     ch->destroy = GNUNET_YES;
698     return;
699   }
700   /* Nothing left to do, just finish destruction */
701   GCT_send_channel_destroy (ch->t,
702                             ch->chid);
703   channel_destroy (ch);
704 }
705
706
707 /**
708  * Destroy channel that was incoming.  Called by the
709  * local client, so no need to tell the client.
710  *
711  * @param ch channel to destroy
712  */
713 void
714 GCCH_channel_incoming_destroy (struct CadetChannel *ch)
715 {
716   if (GNUNET_YES == ch->destroy)
717   {
718     /* other end already destroyed, with the remote client gone, no need
719        to finish transmissions, just destroy immediately. */
720     channel_destroy (ch);
721     return;
722   }
723   if (NULL != ch->head_recv)
724   {
725     /* allow local client to see all data first */
726     ch->destroy = GNUNET_YES;
727     return;
728   }
729   /* Nothing left to do, just finish destruction */
730   GCT_send_channel_destroy (ch->t,
731                             ch->chid);
732   channel_destroy (ch);
733 }
734
735
736 /**
737  * We got an acknowledgement for the creation of the channel
738  * (the port is open on the other side). Begin transmissions.
739  *
740  * @param ch channel to destroy
741  */
742 void
743 GCCH_handle_channel_create_ack (struct CadetChannel *ch)
744 {
745   GNUNET_break (0); // FIXME!
746 }
747
748
749 /**
750  * We got payload data for a channel.  Pass it on to the client.
751  *
752  * @param ch channel that got data
753  */
754 void
755 GCCH_handle_channel_plaintext_data (struct CadetChannel *ch,
756                                     const struct GNUNET_CADET_ChannelAppDataMessage *msg)
757 {
758   GNUNET_break (0); // FIXME!
759 }
760
761
762 /**
763  * We got an acknowledgement for payload data for a channel.
764  * Possibly resume transmissions.
765  *
766  * @param ch channel that got the ack
767  * @param ack details about what was received
768  */
769 void
770 GCCH_handle_channel_plaintext_data_ack (struct CadetChannel *ch,
771                                         const struct GNUNET_CADET_ChannelDataAckMessage *ack)
772 {
773   GNUNET_break (0); // FIXME!
774 }
775
776
777 /**
778  * Destroy channel, based on the other peer closing the
779  * connection.  Also needs to remove this channel from
780  * the tunnel.
781  *
782  * FIXME: need to make it possible to defer destruction until we have
783  * received all messages up to the destroy, and right now the destroy
784  * message (and this API) fails to give is the information we need!
785  *
786  * FIXME: also need to know if the other peer got a destroy from
787  * us before!
788  *
789  * @param ch channel to destroy
790  */
791 void
792 GCCH_handle_remote_destroy (struct CadetChannel *ch)
793 {
794   GNUNET_break (0); // FIXME!
795 }
796
797
798 /**
799  * Function called once the tunnel has sent one of our messages.
800  * If the message is unreliable, simply frees the `crm`. If the
801  * message was reliable, calculate retransmission time and
802  * wait for ACK (or retransmit).
803  *
804  * @param cls the `struct CadetReliableMessage` that was sent
805  */
806 static void
807 data_sent_cb (void *cls);
808
809
810 /**
811  * We need to retry a transmission, the last one took too long to
812  * be acknowledged.
813  *
814  * @param cls the `struct CadetChannel` where we need to retransmit
815  */
816 static void
817 retry_transmission (void *cls)
818 {
819   struct CadetChannel *ch = cls;
820   struct CadetReliableMessage *crm = ch->head_sent;
821
822   GNUNET_assert (NULL == crm->qe);
823   crm->qe = GCT_send (ch->t,
824                       &crm->data_message.header,
825                       &data_sent_cb,
826                       crm);
827 }
828
829
830 /**
831  * Check if we can now allow the client to transmit, and if so,
832  * let the client know about it.
833  *
834  * @param ch channel to check
835  */
836 static void
837 GCCH_check_allow_client (struct CadetChannel *ch)
838 {
839   struct GNUNET_MQ_Envelope *env;
840   struct GNUNET_CADET_LocalAck *msg;
841
842   if (GNUNET_YES == ch->client_allowed)
843     return; /* client already allowed! */
844   if (CADET_CHANNEL_READY != ch->state)
845   {
846     /* destination did not yet ACK our CREATE! */
847     LOG (GNUNET_ERROR_TYPE_DEBUG,
848          "Channel %s not yet ready, throttling client until ACK.\n",
849          GCCH_2s (ch));
850     return;
851   }
852   if (ch->pending_messages > ch->max_pending_messages)
853   {
854     /* Too many messages in queue. */
855     LOG (GNUNET_ERROR_TYPE_DEBUG,
856          "Message queue still too long on channel %s, throttling client until ACK.\n",
857          GCCH_2s (ch));
858     return;
859   }
860   if ( (NULL != ch->head_sent) &&
861        (64 <= ntohl (ch->mid_send.mid) - ntohl (ch->head_sent->data_message.mid.mid)) )
862   {
863     LOG (GNUNET_ERROR_TYPE_DEBUG,
864          "Gap in ACKs too big on channel %s, throttling client until ACK.\n",
865          GCCH_2s (ch));
866     return;
867   }
868   ch->client_allowed = GNUNET_YES;
869
870
871   LOG (GNUNET_ERROR_TYPE_DEBUG,
872        "Sending local ack to channel %s client\n",
873        GCCH_2s (ch));
874   env = GNUNET_MQ_msg (msg,
875                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
876   msg->channel_id = ch->lid;
877   GSC_send_to_client (ch->owner ? ch->owner : ch->dest,
878                       env);
879 }
880
881
882 /**
883  * Function called once the tunnel has sent one of our messages.
884  * If the message is unreliable, simply frees the `crm`. If the
885  * message was reliable, calculate retransmission time and
886  * wait for ACK (or retransmit).
887  *
888  * @param cls the `struct CadetReliableMessage` that was sent
889  */
890 static void
891 data_sent_cb (void *cls)
892 {
893   struct CadetReliableMessage *crm = cls;
894   struct CadetChannel *ch = crm->ch;
895   struct CadetReliableMessage *off;
896
897   crm->qe = NULL;
898   GNUNET_CONTAINER_DLL_remove (ch->head_sent,
899                                ch->tail_sent,
900                                crm);
901   if (GNUNET_NO == ch->reliable)
902   {
903     GNUNET_free (crm);
904     ch->pending_messages--;
905     GCCH_check_allow_client (ch);
906     return;
907   }
908   if (0 == crm->retry_delay.rel_value_us)
909     crm->retry_delay = ch->expected_delay;
910   crm->next_retry = GNUNET_TIME_relative_to_absolute (crm->retry_delay);
911
912   /* find position for re-insertion into the DLL */
913   if ( (NULL == ch->head_sent) ||
914        (crm->next_retry.abs_value_us < ch->head_sent->next_retry.abs_value_us) )
915   {
916     /* insert at HEAD, also (re)schedule retry task! */
917     GNUNET_CONTAINER_DLL_insert (ch->head_sent,
918                                  ch->tail_sent,
919                                  crm);
920     if (NULL != ch->retry_task)
921       GNUNET_SCHEDULER_cancel (ch->retry_task);
922     ch->retry_task = GNUNET_SCHEDULER_add_delayed (crm->retry_delay,
923                                                    &retry_transmission,
924                                                    ch);
925     return;
926   }
927   for (off = ch->head_sent; NULL != off; off = off->next)
928     if (crm->next_retry.abs_value_us < off->next_retry.abs_value_us)
929       break;
930   if (NULL == off)
931   {
932     /* insert at tail */
933     GNUNET_CONTAINER_DLL_insert_tail (ch->head_sent,
934                                       ch->tail_sent,
935                                       crm);
936   }
937   else
938   {
939     /* insert before off */
940     GNUNET_CONTAINER_DLL_insert_after (ch->head_sent,
941                                        ch->tail_sent,
942                                        off->prev,
943                                        crm);
944   }
945 }
946
947
948 /**
949  * Handle data given by a client.
950  *
951  * Check whether the client is allowed to send in this tunnel, save if
952  * channel is reliable and send an ACK to the client if there is still
953  * buffer space in the tunnel.
954  *
955  * @param ch Channel.
956  * @param message payload to transmit.
957  * @return #GNUNET_OK if everything goes well,
958  *         #GNUNET_SYSERR in case of an error.
959  */
960 int
961 GCCH_handle_local_data (struct CadetChannel *ch,
962                         const struct GNUNET_MessageHeader *message)
963 {
964   uint16_t payload_size = ntohs (message->size);
965   struct CadetReliableMessage *crm;
966
967   if (GNUNET_NO == ch->client_allowed)
968   {
969     GNUNET_break_op (0);
970     return GNUNET_SYSERR;
971   }
972   ch->client_allowed = GNUNET_NO;
973   ch->pending_messages++;
974
975   /* Everything is correct, send the message. */
976   crm = GNUNET_malloc (sizeof (*crm) + payload_size);
977   crm->ch = ch;
978   crm->data_message.header.size = htons (sizeof (struct GNUNET_CADET_ChannelAppDataMessage) + payload_size);
979   crm->data_message.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA);
980   ch->mid_send.mid = htonl (ntohl (ch->mid_send.mid) + 1);
981   crm->data_message.mid = ch->mid_send;
982   crm->data_message.chid = ch->chid;
983   GNUNET_memcpy (&crm[1],
984                  message,
985                  payload_size);
986   GNUNET_CONTAINER_DLL_insert (ch->head_sent,
987                                ch->tail_sent,
988                                crm);
989   LOG (GNUNET_ERROR_TYPE_DEBUG,
990        "Sending %u bytes from local client to channel %s\n",
991        payload_size,
992        GCCH_2s (ch));
993   crm->qe = GCT_send (ch->t,
994                       &crm->data_message.header,
995                       &data_sent_cb,
996                       crm);
997   GCCH_check_allow_client (ch);
998   return GNUNET_OK;
999 }
1000
1001
1002 /**
1003  * Try to deliver messages to the local client, if it is ready for more.
1004  *
1005  * @param ch channel to process
1006  */
1007 static void
1008 send_client_buffered_data (struct CadetChannel *ch)
1009 {
1010   struct CadetOutOfOrderMessage *com;
1011
1012   if (GNUNET_NO == ch->client_ready)
1013     return; /* client not ready */
1014   com = ch->head_recv;
1015   if (NULL == com)
1016     return; /* none pending */
1017   if ( (com->mid.mid != ch->mid_recv.mid) &&
1018        (GNUNET_NO == ch->out_of_order) )
1019     return; /* missing next one in-order */
1020
1021   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1022               "Passing payload message to client on channel %s\n",
1023               GCCH_2s (ch));
1024
1025   /* all good, pass next message to client */
1026   GNUNET_CONTAINER_DLL_remove (ch->head_recv,
1027                                ch->tail_recv,
1028                                com);
1029   ch->mid_recv.mid = htonl (1 + ntohl (com->mid.mid));
1030   ch->mid_futures >>= 1; /* equivalent to division by 2 */
1031   GSC_send_to_client (ch->owner ? ch->owner : ch->dest,
1032                       com->env);
1033   GNUNET_free (com);
1034   if ( (0xFFULL == (ch->mid_futures & 0xFFULL)) &&
1035        (GNUNET_YES == ch->reliable) )
1036   {
1037     /* The next 15 messages were also already received (0xFF), this
1038        suggests that the sender may be blocked on flow control
1039        urgently waiting for an ACK from us. (As we have an inherent
1040        maximum of 64 bits, and 15 is getting too close for comfort.)
1041        So we should send one now. */
1042     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1043                 "Sender on channel %s likely blocked on flow-control, sending ACK now.\n",
1044                 GCCH_2s (ch));
1045     if (GNUNET_YES == ch->reliable)
1046       send_channel_ack (ch);
1047   }
1048
1049   if (NULL != ch->head_recv)
1050     return;
1051   if (GNUNET_NO == ch->destroy)
1052     return;
1053   GCT_send_channel_destroy (ch->t,
1054                             ch->chid);
1055   channel_destroy (ch);
1056 }
1057
1058
1059 /**
1060  * Handle ACK from client on local channel.
1061  *
1062  * @param ch channel to destroy
1063  */
1064 void
1065 GCCH_handle_local_ack (struct CadetChannel *ch)
1066 {
1067   ch->client_ready = GNUNET_YES;
1068   send_client_buffered_data (ch);
1069 }
1070
1071
1072 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-chn",__VA_ARGS__)
1073
1074
1075 /**
1076  * Log channel info.
1077  *
1078  * @param ch Channel.
1079  * @param level Debug level to use.
1080  */
1081 void
1082 GCCH_debug (struct CadetChannel *ch,
1083             enum GNUNET_ErrorType level)
1084 {
1085   int do_log;
1086
1087   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
1088                                        "cadet-chn",
1089                                        __FILE__, __FUNCTION__, __LINE__);
1090   if (0 == do_log)
1091     return;
1092
1093   if (NULL == ch)
1094   {
1095     LOG2 (level, "CHN *** DEBUG NULL CHANNEL ***\n");
1096     return;
1097   }
1098   LOG2 (level,
1099         "CHN Channel %s:%X (%p)\n",
1100         GCT_2s (ch->t),
1101         ch->chid,
1102         ch);
1103   if (NULL != ch->owner)
1104   {
1105     LOG2 (level,
1106           "CHN origin %s ready %s local-id: %u\n",
1107           GSC_2s (ch->owner),
1108           ch->client_ready ? "YES" : "NO",
1109           ntohl (ch->lid.channel_of_client));
1110   }
1111   if (NULL != ch->dest)
1112   {
1113     LOG2 (level,
1114           "CHN destination %s ready %s local-id: %u\n",
1115           GSC_2s (ch->dest),
1116           ch->client_ready ? "YES" : "NO",
1117           ntohl (ch->lid.channel_of_client));
1118   }
1119   LOG2 (level,
1120         "CHN  Message IDs recv: %d (%LLX), send: %d\n",
1121         ntohl (ch->mid_recv.mid),
1122         (unsigned long long) ch->mid_futures,
1123         ntohl (ch->mid_send.mid));
1124 }
1125
1126
1127
1128 /* end of gnunet-service-cadet-new_channel.c */