b65df9f4b0ca54018ee3d4a8158cf33b3b9a97af
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_connection.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2015 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file cadet/gnunet-service-cadet_connection.c
22  * @brief GNUnet CADET service connection handling
23  * @author Bartlomiej Polot
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "gnunet_statistics_service.h"
28 #include "cadet_path.h"
29 #include "cadet_protocol.h"
30 #include "cadet.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_peer.h"
33 #include "gnunet-service-cadet_tunnel.h"
34
35
36 /**
37  * Should we run somewhat expensive checks on our invariants?
38  */
39 #define CHECK_INVARIANTS 0
40
41
42 #define LOG(level, ...) GNUNET_log_from (level,"cadet-con",__VA_ARGS__)
43 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-con",__VA_ARGS__)
44
45
46 #define CADET_MAX_POLL_TIME      GNUNET_TIME_relative_multiply (\
47                                   GNUNET_TIME_UNIT_MINUTES,\
48                                   10)
49 #define AVG_MSGS                32
50
51
52 /******************************************************************************/
53 /********************************   STRUCTS  **********************************/
54 /******************************************************************************/
55
56 /**
57  * Handle for messages queued but not yet sent.
58  */
59 struct CadetConnectionQueue
60 {
61
62   struct CadetConnectionQueue *next;
63   struct CadetConnectionQueue *prev;
64
65   /**
66    * Peer queue handle, to cancel if necessary.
67    */
68   struct CadetPeerQueue *peer_q;
69
70   /**
71    * Continuation to call once sent.
72    */
73   GCC_sent cont;
74
75   /**
76    * Closure for @e cont.
77    */
78   void *cont_cls;
79
80   /**
81    * Was this a forced message? (Do not account for it)
82    */
83   int forced;
84 };
85
86
87 /**
88  * Struct to encapsulate all the Flow Control information to a peer to which
89  * we are directly connected (on a core level).
90  */
91 struct CadetFlowControl
92 {
93   /**
94    * Connection this controls.
95    */
96   struct CadetConnection *c;
97
98   struct CadetConnectionQueue *q_head;
99   struct CadetConnectionQueue *q_tail;
100
101   /**
102    * How many messages are in the queue on this connection.
103    */
104   unsigned int queue_n;
105
106   /**
107    * How many messages do we accept in the queue.
108    * If 0, the connection is broken in this direction (next hop disconnected).
109    */
110   unsigned int queue_max;
111
112   /**
113    * ID of the next packet to send.
114    */
115   uint32_t next_pid;
116
117   /**
118    * ID of the last packet sent towards the peer.
119    */
120   uint32_t last_pid_sent;
121
122   /**
123    * ID of the last packet received from the peer.
124    */
125   uint32_t last_pid_recv;
126
127   /**
128    * Bitmap of past 32 messages received:
129    * - LSB being @c last_pid_recv.
130    * - MSB being @c last_pid_recv - 31 (mod UINTMAX).
131    */
132   uint32_t recv_bitmap;
133
134   /**
135    * Last ACK sent to the peer (peer can't send more than this PID).
136    */
137   uint32_t last_ack_sent;
138
139   /**
140    * Last ACK sent towards the origin (for traffic towards leaf node).
141    */
142   uint32_t last_ack_recv;
143
144   /**
145    * Task to poll the peer in case of a lost ACK causes stall.
146    */
147   struct GNUNET_SCHEDULER_Task *poll_task;
148
149   /**
150    * How frequently to poll for ACKs.
151    */
152   struct GNUNET_TIME_Relative poll_time;
153
154   /**
155    * Queued poll message, to cancel if not necessary anymore (got ACK).
156    */
157   struct CadetConnectionQueue *poll_msg;
158
159   /**
160    * Queued poll message, to cancel if not necessary anymore (got ACK).
161    */
162   struct CadetConnectionQueue *ack_msg;
163 };
164
165 /**
166  * Keep a record of the last messages sent on this connection.
167  */
168 struct CadetConnectionPerformance
169 {
170   /**
171    * Circular buffer for storing measurements.
172    */
173   double usecsperbyte[AVG_MSGS];
174
175   /**
176    * Running average of @c usecsperbyte.
177    */
178   double avg;
179
180   /**
181    * How many values of @c usecsperbyte are valid.
182    */
183   uint16_t size;
184
185   /**
186    * Index of the next "free" position in @c usecsperbyte.
187    */
188   uint16_t idx;
189 };
190
191
192 /**
193  * Struct containing all information regarding a connection to a peer.
194  */
195 struct CadetConnection
196 {
197   /**
198    * Tunnel this connection is part of.
199    */
200   struct CadetTunnel *t;
201
202   /**
203    * Flow control information for traffic fwd.
204    */
205   struct CadetFlowControl fwd_fc;
206
207   /**
208    * Flow control information for traffic bck.
209    */
210   struct CadetFlowControl bck_fc;
211
212   /**
213    * Measure connection performance on the endpoint.
214    */
215   struct CadetConnectionPerformance *perf;
216
217   /**
218    * ID of the connection.
219    */
220   struct GNUNET_CADET_Hash id;
221
222   /**
223    * Path being used for the tunnel. At the origin of the connection
224    * it's a pointer to the destination's path pool, otherwise just a copy.
225    */
226   struct CadetPeerPath *path;
227
228   /**
229    * Task to keep the used paths alive at the owner,
230    * time tunnel out on all the other peers.
231    */
232   struct GNUNET_SCHEDULER_Task *fwd_maintenance_task;
233
234   /**
235    * Task to keep the used paths alive at the destination,
236    * time tunnel out on all the other peers.
237    */
238   struct GNUNET_SCHEDULER_Task *bck_maintenance_task;
239
240   /**
241    * Queue handle for maintainance traffic. One handle for FWD and BCK since
242    * one peer never needs to maintain both directions (no loopback connections).
243    */
244   struct CadetPeerQueue *maintenance_q;
245
246   /**
247    * Should equal #get_next_hop(), or NULL if that peer disconnected.
248    */
249   struct CadetPeer *next_peer;
250
251   /**
252    * Should equal #get_prev_hop(), or NULL if that peer disconnected.
253    */
254   struct CadetPeer *prev_peer;
255
256   /**
257    * State of the connection.
258    */
259   enum CadetConnectionState state;
260
261   /**
262    * Position of the local peer in the path.
263    */
264   unsigned int own_pos;
265
266   /**
267    * Pending message count.
268    */
269   unsigned int pending_messages;
270
271   /**
272    * Destroy flag:
273    * - if 0, connection in use.
274    * - if 1, destroy on last message.
275    * - if 2, connection is being destroyed don't re-enter.
276    */
277   int destroy;
278
279   /**
280    * In-connection-map flag. Sometimes, when @e destroy is set but
281    * actual destruction is delayed to enable us to finish processing
282    * queues (i.e. in the direction that is still working), we remove
283    * the connection from the map to prevent it from still being
284    * found (and used) by accident. This flag is set to #GNUNET_YES
285    * for a connection that is not in the #connections map.  Should
286    * only be #GNUNET_YES if #destroy is also non-zero.
287    */
288   int was_removed;
289
290   /**
291    * Counter to do exponential backoff when creating a connection (max 64).
292    */
293   unsigned short create_retry;
294
295   /**
296    * Task to check if connection has duplicates.
297    */
298   struct GNUNET_SCHEDULER_Task *check_duplicates_task;
299 };
300
301
302 /******************************************************************************/
303 /*******************************   GLOBALS  ***********************************/
304 /******************************************************************************/
305
306 /**
307  * Global handle to the statistics service.
308  */
309 extern struct GNUNET_STATISTICS_Handle *stats;
310
311 /**
312  * Local peer own ID (memory efficient handle).
313  */
314 extern GNUNET_PEER_Id myid;
315
316 /**
317  * Local peer own ID (full value).
318  */
319 extern struct GNUNET_PeerIdentity my_full_id;
320
321 /**
322  * Connections known, indexed by cid (CadetConnection).
323  */
324 static struct GNUNET_CONTAINER_MultiHashMap *connections;
325
326 /**
327  * How many connections are we willing to maintain.
328  *  Local connections are always allowed,
329  * even if there are more connections than max.
330  */
331 static unsigned long long max_connections;
332
333 /**
334  * How many messages *in total* are we willing to queue, divide by number of
335  * connections to get connection queue size.
336  */
337 static unsigned long long max_msgs_queue;
338
339 /**
340  * How often to send path keepalives. Paths timeout after 4 missed.
341  */
342 static struct GNUNET_TIME_Relative refresh_connection_time;
343
344 /**
345  * How often to send path create / ACKs.
346  */
347 static struct GNUNET_TIME_Relative create_connection_time;
348
349
350 /******************************************************************************/
351 /********************************   STATIC  ***********************************/
352 /******************************************************************************/
353
354
355
356 #if 0 // avoid compiler warning for unused static function
357 static void
358 fc_debug (struct CadetFlowControl *fc)
359 {
360   LOG (GNUNET_ERROR_TYPE_DEBUG, "    IN: %u/%u\n",
361               fc->last_pid_recv, fc->last_ack_sent);
362   LOG (GNUNET_ERROR_TYPE_DEBUG, "    OUT: %u/%u\n",
363               fc->last_pid_sent, fc->last_ack_recv);
364   LOG (GNUNET_ERROR_TYPE_DEBUG, "    QUEUE: %u/%u\n",
365               fc->queue_n, fc->queue_max);
366 }
367
368 static void
369 connection_debug (struct CadetConnection *c)
370 {
371   if (NULL == c)
372   {
373     LOG (GNUNET_ERROR_TYPE_INFO, "DEBUG NULL CONNECTION\n");
374     return;
375   }
376   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s:%X\n",
377               peer2s (c->t->peer), GCC_2s (c));
378   LOG (GNUNET_ERROR_TYPE_DEBUG, "  state: %u, pending msgs: %u\n",
379               c->state, c->pending_messages);
380   LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
381   fc_debug (&c->fwd_fc);
382   LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
383   fc_debug (&c->bck_fc);
384 }
385 #endif
386
387
388 /**
389  * Schedule next keepalive task, taking in consideration
390  * the connection state and number of retries.
391  *
392  * @param c Connection for which to schedule the next keepalive.
393  * @param fwd Direction for the next keepalive.
394  */
395 static void
396 schedule_next_keepalive (struct CadetConnection *c, int fwd);
397
398
399 /**
400  * Resets the connection timeout task, some other message has done the
401  * task's job.
402  * - For the first peer on the direction this means to send
403  *   a keepalive or a path confirmation message (either create or ACK).
404  * - For all other peers, this means to destroy the connection,
405  *   due to lack of activity.
406  * Starts the timeout if no timeout was running (connection just created).
407  *
408  * @param c Connection whose timeout to reset.
409  * @param fwd Is this forward?
410  */
411 static void
412 connection_reset_timeout (struct CadetConnection *c, int fwd);
413
414
415 /**
416  * Get string description for tunnel state. Reentrant.
417  *
418  * @param s Tunnel state.
419  *
420  * @return String representation.
421  */
422 static const char *
423 GCC_state2s (enum CadetConnectionState s)
424 {
425   switch (s)
426   {
427     case CADET_CONNECTION_NEW:
428       return "CADET_CONNECTION_NEW";
429     case CADET_CONNECTION_SENT:
430       return "CADET_CONNECTION_SENT";
431     case CADET_CONNECTION_ACK:
432       return "CADET_CONNECTION_ACK";
433     case CADET_CONNECTION_READY:
434       return "CADET_CONNECTION_READY";
435     case CADET_CONNECTION_DESTROYED:
436       return "CADET_CONNECTION_DESTROYED";
437     case CADET_CONNECTION_BROKEN:
438       return "CADET_CONNECTION_BROKEN";
439     default:
440       GNUNET_break (0);
441       LOG (GNUNET_ERROR_TYPE_ERROR, " conn state %u unknown!\n", s);
442       return "CADET_CONNECTION_STATE_ERROR";
443   }
444 }
445
446
447 /**
448  * Initialize a Flow Control structure to the initial state.
449  *
450  * @param fc Flow Control structure to initialize.
451  */
452 static void
453 fc_init (struct CadetFlowControl *fc)
454 {
455   fc->next_pid = (uint32_t) 0;
456   fc->last_pid_sent = (uint32_t) -1;
457   fc->last_pid_recv = (uint32_t) -1;
458   fc->last_ack_sent = (uint32_t) 0;
459   fc->last_ack_recv = (uint32_t) 0;
460   fc->poll_task = NULL;
461   fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
462   fc->queue_n = 0;
463   fc->queue_max = (max_msgs_queue / max_connections) + 1;
464 }
465
466
467 /**
468  * Find a connection.
469  *
470  * @param cid Connection ID.
471  *
472  * @return conntection with the given ID @cid or NULL if not found.
473  */
474 static struct CadetConnection *
475 connection_get (const struct GNUNET_CADET_Hash *cid)
476 {
477   return GNUNET_CONTAINER_multihashmap_get (connections, GC_h2hc (cid));
478 }
479
480
481 /**
482  * Change the connection state. Cannot change a connection marked as destroyed.
483  *
484  * @param c Connection to change.
485  * @param state New state to set.
486  */
487 static void
488 connection_change_state (struct CadetConnection* c,
489                          enum CadetConnectionState state)
490 {
491   LOG (GNUNET_ERROR_TYPE_DEBUG,
492        "Connection %s state %s -> %s\n",
493        GCC_2s (c), GCC_state2s (c->state), GCC_state2s (state));
494   if (CADET_CONNECTION_DESTROYED <= c->state) /* Destroyed or broken. */
495   {
496     LOG (GNUNET_ERROR_TYPE_DEBUG, "state not changing anymore\n");
497     return;
498   }
499   c->state = state;
500   if (CADET_CONNECTION_READY == state)
501     c->create_retry = 1;
502 }
503
504
505 /**
506  * Mark a connection as "destroyed", to send all pending traffic and freeing
507  * all associated resources, without accepting new status changes on it.
508  *
509  * @param c Connection to mark as destroyed.
510  */
511 static void
512 mark_destroyed (struct CadetConnection *c)
513 {
514   c->destroy = GNUNET_YES;
515   connection_change_state (c, CADET_CONNECTION_DESTROYED);
516 }
517
518
519 /**
520  * Callback called when a queued ACK message is sent.
521  *
522  * @param cls Closure (FC).
523  * @param c Connection this message was on.
524  * @param q Queue handler this call invalidates.
525  * @param type Type of message sent.
526  * @param fwd Was this a FWD going message?
527  * @param size Size of the message.
528  */
529 static void
530 ack_sent (void *cls,
531           struct CadetConnection *c,
532           struct CadetConnectionQueue *q,
533           uint16_t type, int fwd, size_t size)
534 {
535   struct CadetFlowControl *fc = cls;
536
537   fc->ack_msg = NULL;
538 }
539
540
541 /**
542  * Send an ACK on the connection, informing the predecessor about
543  * the available buffer space. Should not be called in case the peer
544  * is origin (no predecessor) in the @c fwd direction.
545  *
546  * Note that for fwd ack, the FWD mean forward *traffic* (root->dest),
547  * the ACK itself goes "back" (dest->root).
548  *
549  * @param c Connection on which to send the ACK.
550  * @param buffer How much space free to advertise?
551  * @param fwd Is this FWD ACK? (Going dest -> root)
552  * @param force Don't optimize out.
553  */
554 static void
555 send_ack (struct CadetConnection *c, unsigned int buffer, int fwd, int force)
556 {
557   struct CadetFlowControl *next_fc;
558   struct CadetFlowControl *prev_fc;
559   struct GNUNET_CADET_ACK msg;
560   uint32_t ack;
561   int delta;
562
563   GCC_check_connections ();
564   GNUNET_assert (GNUNET_NO == GCC_is_origin (c, fwd));
565
566   next_fc = fwd ? &c->fwd_fc : &c->bck_fc;
567   prev_fc = fwd ? &c->bck_fc : &c->fwd_fc;
568
569   LOG (GNUNET_ERROR_TYPE_DEBUG, "send %s ack on %s\n",
570        GC_f2s (fwd), GCC_2s (c));
571
572   /* Check if we need to transmit the ACK. */
573   delta = prev_fc->last_ack_sent - prev_fc->last_pid_recv;
574   if (3 < delta && buffer < delta && GNUNET_NO == force)
575   {
576     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending ACK, delta > 3\n");
577     LOG (GNUNET_ERROR_TYPE_DEBUG,
578          "  last pid recv: %u, last ack sent: %u\n",
579          prev_fc->last_pid_recv, prev_fc->last_ack_sent);
580     GCC_check_connections ();
581     return;
582   }
583
584   /* Ok, ACK might be necessary, what PID to ACK? */
585   ack = prev_fc->last_pid_recv + buffer;
586   LOG (GNUNET_ERROR_TYPE_DEBUG,
587        " ACK %u, last PID %u, last ACK %u, qmax %u, q %u\n",
588        ack, prev_fc->last_pid_recv, prev_fc->last_ack_sent,
589        next_fc->queue_max, next_fc->queue_n);
590   if (ack == prev_fc->last_ack_sent && GNUNET_NO == force)
591   {
592     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not sending FWD ACK, not needed\n");
593     GCC_check_connections ();
594     return;
595   }
596
597   /* Check if message is already in queue */
598   if (NULL != prev_fc->ack_msg)
599   {
600     if (GC_is_pid_bigger (ack, prev_fc->last_ack_sent))
601     {
602       LOG (GNUNET_ERROR_TYPE_DEBUG, " canceling old ACK\n");
603       GCC_cancel (prev_fc->ack_msg);
604       /* GCC_cancel triggers ack_sent(), which clears fc->ack_msg */
605     }
606     else
607     {
608       LOG (GNUNET_ERROR_TYPE_DEBUG, " same ACK already in queue\n");
609       GCC_check_connections ();
610       return;
611     }
612   }
613
614   prev_fc->last_ack_sent = ack;
615
616   /* Build ACK message and send on conn */
617   msg.header.size = htons (sizeof (msg));
618   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ACK);
619   msg.ack = htonl (ack);
620   msg.cid = c->id;
621
622   prev_fc->ack_msg = GCC_send_prebuilt_message (&msg.header, UINT16_MAX, ack,
623                                                 c, !fwd, GNUNET_YES,
624                                                 &ack_sent, prev_fc);
625   GNUNET_assert (NULL != prev_fc->ack_msg);
626   GCC_check_connections ();
627 }
628
629
630 /**
631  * Update performance information if we are a connection's endpoint.
632  *
633  * @param c Connection to update.
634  * @param wait How much time did we wait to send the last message.
635  * @param size Size of the last message.
636  */
637 static void
638 update_perf (struct CadetConnection *c,
639              struct GNUNET_TIME_Relative wait,
640              uint16_t size)
641 {
642   struct CadetConnectionPerformance *p;
643   double usecsperbyte;
644
645   if (NULL == c->perf)
646     return; /* Only endpoints are interested in timing. */
647
648   p = c->perf;
649   usecsperbyte = ((double) wait.rel_value_us) / size;
650   if (p->size == AVG_MSGS)
651   {
652     /* Array is full. Substract oldest value, add new one and store. */
653     p->avg -= (p->usecsperbyte[p->idx] / AVG_MSGS);
654     p->usecsperbyte[p->idx] = usecsperbyte;
655     p->avg += (p->usecsperbyte[p->idx] / AVG_MSGS);
656   }
657   else
658   {
659     /* Array not yet full. Add current value to avg and store. */
660     p->usecsperbyte[p->idx] = usecsperbyte;
661     p->avg *= p->size;
662     p->avg += p->usecsperbyte[p->idx];
663     p->size++;
664     p->avg /= p->size;
665   }
666   p->idx = (p->idx + 1) % AVG_MSGS;
667 }
668
669
670 /**
671  * Callback called when a connection queued message is sent.
672  *
673  * Calculates the average time and connection packet tracking.
674  *
675  * @param cls Closure (ConnectionQueue Handle), can be NULL.
676  * @param c Connection this message was on.
677  * @param fwd Was this a FWD going message?
678  * @param sent Was it really sent? (Could have been canceled)
679  * @param type Type of message sent.
680  * @param payload_type Type of payload, if applicable.
681  * @param pid Message ID, or 0 if not applicable (create, destroy, etc).
682  * @param size Size of the message.
683  * @param wait Time spent waiting for core (only the time for THIS message)
684  */
685 static void
686 conn_message_sent (void *cls,
687                    struct CadetConnection *c, int fwd, int sent,
688                    uint16_t type, uint16_t payload_type, uint32_t pid,
689                    size_t size,
690                    struct GNUNET_TIME_Relative wait)
691 {
692   struct CadetConnectionQueue *q = cls;
693   struct CadetFlowControl *fc;
694   int forced;
695
696   GCC_check_connections ();
697   LOG (GNUNET_ERROR_TYPE_DEBUG, "connection message_sent\n");
698
699   /* If c is NULL, nothing to update. */
700   if (NULL == c)
701   {
702     if (type != GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN
703         && type != GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY)
704     {
705       LOG (GNUNET_ERROR_TYPE_ERROR, "Message %s sent on NULL connection!\n",
706            GC_m2s (type));
707     }
708     GCC_check_connections ();
709     return;
710   }
711
712   LOG (GNUNET_ERROR_TYPE_DEBUG, " %ssent %s %s pid %u\n",
713        sent ? "" : "not ", GC_f2s (fwd),
714        GC_m2s (type), GC_m2s (payload_type), pid);
715   GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);
716
717   /* Update flow control info. */
718   fc = fwd ? &c->fwd_fc : &c->bck_fc;
719
720   if (NULL != q)
721   {
722     GNUNET_CONTAINER_DLL_remove (fc->q_head, fc->q_tail, q);
723     forced = q->forced;
724     if (NULL != q->cont)
725     {
726       LOG (GNUNET_ERROR_TYPE_DEBUG, " calling cont\n");
727       q->cont (q->cont_cls, c, q, type, fwd, size);
728     }
729     GNUNET_free (q);
730   }
731   else if (type == GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED)
732   {
733     /* SHOULD NO LONGER HAPPEN FIXME: REMOVE CASE */
734     // If NULL == q and ENCRYPTED == type, message must have been ch_mngmnt
735     forced = GNUNET_YES;
736     GNUNET_assert (0); // FIXME
737   }
738   else /* CONN_CREATE or CONN_ACK */
739   {
740     forced = GNUNET_YES;
741   }
742
743   LOG (GNUNET_ERROR_TYPE_DEBUG, " C_P- %p %u\n", c, c->pending_messages);
744   c->pending_messages--;
745   if ( (GNUNET_YES == c->destroy) &&
746        (0 == c->pending_messages) )
747   {
748     LOG (GNUNET_ERROR_TYPE_DEBUG,
749          "!  destroying connection!\n");
750     GCC_destroy (c);
751     GCC_check_connections ();
752     return;
753   }
754
755   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
756   switch (type)
757   {
758     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
759     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
760       c->maintenance_q = NULL;
761       /* Don't trigger a keepalive for sent ACKs, only SYN and SYNACKs */
762       if (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE == type || !fwd)
763         schedule_next_keepalive (c, fwd);
764       break;
765
766     case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
767       if (GNUNET_YES == sent)
768       {
769         GNUNET_assert (NULL != q);
770         fc->last_pid_sent = pid;
771         if (GC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
772           GCC_start_poll (c, fwd);
773         GCC_send_ack (c, fwd, GNUNET_NO);
774         connection_reset_timeout (c, fwd);
775       }
776
777       LOG (GNUNET_ERROR_TYPE_DEBUG, "!  Q_N- %p %u\n", fc, fc->queue_n);
778       if (GNUNET_NO == forced)
779       {
780         fc->queue_n--;
781         LOG (GNUNET_ERROR_TYPE_DEBUG,
782             "!   accounting pid %u\n",
783             fc->last_pid_sent);
784       }
785       else
786       {
787         LOG (GNUNET_ERROR_TYPE_DEBUG,
788              "!   forced, Q_N not accounting pid %u\n",
789              fc->last_pid_sent);
790       }
791       break;
792
793     case GNUNET_MESSAGE_TYPE_CADET_KX:
794       if (GNUNET_YES == sent)
795         connection_reset_timeout (c, fwd);
796       break;
797
798     case GNUNET_MESSAGE_TYPE_CADET_POLL:
799       fc->poll_msg = NULL;
800       break;
801
802     case GNUNET_MESSAGE_TYPE_CADET_ACK:
803       fc->ack_msg = NULL;
804       break;
805
806     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
807     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
808       break;
809
810     default:
811       LOG (GNUNET_ERROR_TYPE_ERROR, "%s unknown\n", GC_m2s (type));
812       GNUNET_break (0);
813       break;
814   }
815   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  message sent!\n");
816
817   update_perf (c, wait, size);
818   GCC_check_connections ();
819 }
820
821
822 /**
823  * Get the previous hop in a connection
824  *
825  * @param c Connection.
826  *
827  * @return Previous peer in the connection.
828  */
829 static struct CadetPeer *
830 get_prev_hop (const struct CadetConnection *c)
831 {
832   GNUNET_PEER_Id id;
833
834   if (NULL == c->path)
835     return NULL;
836   LOG (GNUNET_ERROR_TYPE_DEBUG,
837        " get prev hop %s [%u/%u]\n",
838        GCC_2s (c), c->own_pos, c->path->length);
839   if (0 == c->own_pos || c->path->length < 2)
840     id = c->path->peers[0];
841   else
842     id = c->path->peers[c->own_pos - 1];
843
844   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ID: %s (%u)\n",
845        GNUNET_i2s (GNUNET_PEER_resolve2 (id)), id);
846
847   return GCP_get_short (id, GNUNET_YES);
848 }
849
850
851 /**
852  * Get the next hop in a connection
853  *
854  * @param c Connection.
855  *
856  * @return Next peer in the connection.
857  */
858 static struct CadetPeer *
859 get_next_hop (const struct CadetConnection *c)
860 {
861   GNUNET_PEER_Id id;
862
863   if (NULL == c->path)
864     return NULL;
865
866   LOG (GNUNET_ERROR_TYPE_DEBUG, " get next hop %s [%u/%u]\n",
867        GCC_2s (c), c->own_pos, c->path->length);
868   if ((c->path->length - 1) == c->own_pos || c->path->length < 2)
869     id = c->path->peers[c->path->length - 1];
870   else
871     id = c->path->peers[c->own_pos + 1];
872
873   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ID: %s (%u)\n",
874        GNUNET_i2s (GNUNET_PEER_resolve2 (id)), id);
875
876   return GCP_get_short (id, GNUNET_YES);
877 }
878
879
880 /**
881  * Check that the direct neighbours (previous and next hop)
882  * are properly associated with this connection.
883  *
884  * @param c connection to check
885  */
886 static void
887 check_neighbours (const struct CadetConnection *c)
888 {
889   if (NULL == c->path)
890     return; /* nothing to check */
891   GCP_check_connection (get_next_hop (c), c);
892   GCP_check_connection (get_prev_hop (c), c);
893 }
894
895
896 /**
897  * Helper for #GCC_check_connections().  Calls #check_neighbours().
898  *
899  * @param cls NULL
900  * @param key ignored
901  * @param value the `struct CadetConnection` to check
902  * @return #GNUNET_OK (continue to iterate)
903  */
904 static int
905 check_connection (void *cls,
906                   const struct GNUNET_HashCode *key,
907                   void *value)
908 {
909   struct CadetConnection *c = value;
910
911   check_neighbours (c);
912   return GNUNET_OK;
913 }
914
915
916 /**
917  * Check invariants for all connections using #check_neighbours().
918  */
919 void
920 GCC_check_connections ()
921 {
922   if (0 == CHECK_INVARIANTS)
923     return;
924   if (NULL == connections)
925     return;
926   GNUNET_CONTAINER_multihashmap_iterate (connections,
927                                          &check_connection,
928                                          NULL);
929 }
930
931
932 /**
933  * Get the hop in a connection.
934  *
935  * @param c Connection.
936  * @param fwd Next in the FWD direction?
937  *
938  * @return Next peer in the connection.
939  */
940 static struct CadetPeer *
941 get_hop (struct CadetConnection *c, int fwd)
942 {
943   return (fwd) ? get_next_hop (c) : get_prev_hop (c);
944 }
945
946
947 /**
948  * Get a bit mask for a message received out-of-order.
949  *
950  * @param last_pid_recv Last PID we received prior to the out-of-order.
951  * @param ooo_pid PID of the out-of-order message.
952  */
953 static uint32_t
954 get_recv_bitmask (uint32_t last_pid_recv, uint32_t ooo_pid)
955 {
956   return 1 << (last_pid_recv - ooo_pid);
957 }
958
959
960 /**
961  * Check is an out-of-order message is ok:
962  * - at most 31 messages behind.
963  * - not duplicate.
964  *
965  * @param last_pid_recv Last in-order PID received.
966  */
967 static int
968 is_ooo_ok (uint32_t last_pid_recv, uint32_t ooo_pid, uint32_t ooo_bitmap)
969 {
970   uint32_t mask;
971
972   if (GC_is_pid_bigger (last_pid_recv - 31, ooo_pid))
973     return GNUNET_NO;
974
975   mask = get_recv_bitmask (last_pid_recv, ooo_pid);
976   if (0 != (ooo_bitmap & mask))
977     return GNUNET_NO;
978
979   return GNUNET_YES;
980 }
981
982
983 /**
984  * Is traffic coming from this sender 'FWD' traffic?
985  *
986  * @param c Connection to check.
987  * @param sender Short peer identity of neighbor.
988  *
989  * @return #GNUNET_YES in case the sender is the 'prev' hop and therefore
990  *         the traffic is 'FWD'.
991  *         #GNUNET_NO for BCK.
992  *         #GNUNET_SYSERR for errors (sender isn't a hop in the connection).
993  */
994 static int
995 is_fwd (const struct CadetConnection *c,
996         const struct CadetPeer *sender)
997 {
998   GNUNET_PEER_Id id;
999
1000   id = GCP_get_short_id (sender);
1001   if (GCP_get_short_id (get_prev_hop (c)) == id)
1002     return GNUNET_YES;
1003
1004   if (GCP_get_short_id (get_next_hop (c)) == id)
1005     return GNUNET_NO;
1006
1007   return GNUNET_SYSERR;
1008 }
1009
1010
1011 /**
1012  * Sends a CONNECTION ACK message in reponse to a received CONNECTION_CREATE
1013  * or a first CONNECTION_ACK directed to us.
1014  *
1015  * @param c Connection to confirm.
1016  * @param fwd Should we send it FWD? (root->dest)
1017  *            (First (~SYNACK) goes BCK, second (~ACK) goes FWD)
1018  */
1019 static void
1020 send_connection_ack (struct CadetConnection *c, int fwd)
1021 {
1022   struct GNUNET_CADET_ConnectionACK msg;
1023   struct CadetTunnel *t;
1024   const uint16_t size = sizeof (struct GNUNET_CADET_ConnectionACK);
1025   const uint16_t type = GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK;
1026
1027   GCC_check_connections ();
1028   t = c->t;
1029   LOG (GNUNET_ERROR_TYPE_INFO,
1030        "==> %s ({ C %s ACK}    0) on conn %s (%p) %s [%5u]\n",
1031        GC_m2s (type), GC_f2s (!fwd), GCC_2s (c), c, GC_f2s (fwd), size);
1032
1033   msg.header.size = htons (size);
1034   msg.header.type = htons (type);
1035   msg.reserved = htonl (0);
1036   msg.cid = c->id;
1037
1038   GNUNET_assert (NULL == c->maintenance_q);
1039   c->maintenance_q = GCP_send (get_hop (c, fwd), &msg.header,
1040                                GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK, 0,
1041                                c, fwd,
1042                                &conn_message_sent, NULL);
1043   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u (conn`ACK)\n",
1044        c, c->pending_messages);
1045   c->pending_messages++;
1046
1047   if (CADET_TUNNEL_NEW == GCT_get_cstate (t))
1048     GCT_change_cstate (t, CADET_TUNNEL_WAITING);
1049   if (CADET_CONNECTION_READY != c->state)
1050     connection_change_state (c, CADET_CONNECTION_SENT);
1051   GCC_check_connections ();
1052 }
1053
1054
1055 /**
1056  * Send a notification that a connection is broken.
1057  *
1058  * @param c Connection that is broken.
1059  * @param id1 Peer that has disconnected.
1060  * @param id2 Peer that has disconnected.
1061  * @param fwd Direction towards which to send it.
1062  */
1063 static void
1064 send_broken (struct CadetConnection *c,
1065              const struct GNUNET_PeerIdentity *id1,
1066              const struct GNUNET_PeerIdentity *id2,
1067              int fwd)
1068 {
1069   struct GNUNET_CADET_ConnectionBroken msg;
1070
1071   GCC_check_connections ();
1072   msg.header.size = htons (sizeof (struct GNUNET_CADET_ConnectionBroken));
1073   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN);
1074   msg.cid = c->id;
1075   msg.reserved = htonl (0);
1076   msg.peer1 = *id1;
1077   msg.peer2 = *id2;
1078   (void) GCC_send_prebuilt_message (&msg.header, UINT16_MAX, 0, c, fwd,
1079                                     GNUNET_YES, NULL, NULL);
1080   GCC_check_connections ();
1081 }
1082
1083
1084 /**
1085  * Send a notification that a connection is broken, when a connection
1086  * isn't even known to the local peer or soon to be destroyed.
1087  *
1088  * @param connection_id Connection ID.
1089  * @param id1 Peer that has disconnected, probably local peer.
1090  * @param id2 Peer that has disconnected can be NULL if unknown.
1091  * @param neighbor Peer to notify (neighbor who sent the connection).
1092  */
1093 static void
1094 send_broken_unknown (const struct GNUNET_CADET_Hash *connection_id,
1095                      const struct GNUNET_PeerIdentity *id1,
1096                      const struct GNUNET_PeerIdentity *id2,
1097                      struct CadetPeer *neighbor)
1098 {
1099   struct GNUNET_CADET_ConnectionBroken msg;
1100
1101   GCC_check_connections ();
1102   LOG (GNUNET_ERROR_TYPE_INFO, "--> BROKEN on unknown connection %s\n",
1103        GNUNET_h2s (GC_h2hc (connection_id)));
1104
1105   msg.header.size = htons (sizeof (struct GNUNET_CADET_ConnectionBroken));
1106   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN);
1107   msg.cid = *connection_id;
1108   msg.reserved = htonl (0);
1109   msg.peer1 = *id1;
1110   if (NULL != id2)
1111     msg.peer2 = *id2;
1112   else
1113     memset (&msg.peer2, 0, sizeof (msg.peer2));
1114   GNUNET_assert (NULL != GCP_send (neighbor, &msg.header,
1115                                    UINT16_MAX, 2,
1116                                    NULL, GNUNET_SYSERR, /* connection, fwd */
1117                                    NULL, NULL)); /* continuation */
1118   GCC_check_connections ();
1119 }
1120
1121
1122 /**
1123  * Send keepalive packets for a connection.
1124  *
1125  * @param c Connection to keep alive..
1126  * @param fwd Is this a FWD keepalive? (owner -> dest).
1127  */
1128 static void
1129 send_connection_keepalive (struct CadetConnection *c, int fwd)
1130 {
1131   struct GNUNET_MessageHeader msg;
1132   struct CadetFlowControl *fc;
1133   int tunnel_ready;
1134
1135   GCC_check_connections ();
1136   LOG (GNUNET_ERROR_TYPE_INFO,
1137        "keepalive %s for connection %s\n",
1138        GC_f2s (fwd), GCC_2s (c));
1139
1140   GNUNET_assert (NULL != c->t);
1141   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1142   tunnel_ready = GNUNET_YES == GCT_has_queued_traffic (c->t)
1143                  && CADET_TUNNEL_KEY_OK <= GCT_get_estate (c->t);
1144   if (0 < fc->queue_n || tunnel_ready)
1145   {
1146     LOG (GNUNET_ERROR_TYPE_INFO, "not sending keepalive, traffic in queue\n");
1147     return;
1148   }
1149
1150   GNUNET_STATISTICS_update (stats, "# keepalives sent", 1, GNUNET_NO);
1151
1152   GNUNET_assert (NULL != c->t);
1153   msg.size = htons (sizeof (msg));
1154   msg.type = htons (GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE);
1155
1156   GNUNET_assert (NULL ==
1157                  GCT_send_prebuilt_message (&msg, c->t, c,
1158                                             GNUNET_NO, NULL, NULL));
1159   GCC_check_connections ();
1160 }
1161
1162
1163 /**
1164  * Send CONNECTION_{CREATE/ACK} packets for a connection.
1165  *
1166  * @param c Connection for which to send the message.
1167  * @param fwd If #GNUNET_YES, send CREATE, otherwise send ACK.
1168  */
1169 static void
1170 connection_recreate (struct CadetConnection *c, int fwd)
1171 {
1172   LOG (GNUNET_ERROR_TYPE_DEBUG,
1173        "sending connection recreate\n");
1174   if (fwd)
1175     GCC_send_create (c);
1176   else
1177     send_connection_ack (c, GNUNET_NO);
1178 }
1179
1180
1181 /**
1182  * Generic connection timer management.
1183  * Depending on the role of the peer in the connection will send the
1184  * appropriate message (build or keepalive)
1185  *
1186  * @param c Conncetion to maintain.
1187  * @param fwd Is FWD?
1188  */
1189 static void
1190 connection_maintain (struct CadetConnection *c, int fwd)
1191 {
1192   if (GNUNET_NO != c->destroy)
1193   {
1194     LOG (GNUNET_ERROR_TYPE_INFO, "not sending keepalive, being destroyed\n");
1195     return;
1196   }
1197
1198   if (NULL == c->t)
1199   {
1200     GNUNET_break (0);
1201     GCC_debug (c, GNUNET_ERROR_TYPE_ERROR);
1202     return;
1203   }
1204
1205   if (CADET_TUNNEL_SEARCHING == GCT_get_cstate (c->t))
1206   {
1207     /* If status is SEARCHING, why is there a connection? Should be WAITING */
1208     GNUNET_break (0);
1209     GCT_debug (c->t, GNUNET_ERROR_TYPE_ERROR);
1210     LOG (GNUNET_ERROR_TYPE_INFO, "not sending keepalive, tunnel SEARCHING\n");
1211     schedule_next_keepalive (c, fwd);
1212     return;
1213   }
1214   switch (c->state)
1215   {
1216     case CADET_CONNECTION_NEW:
1217       GNUNET_break (0);
1218       /* fall-through */
1219     case CADET_CONNECTION_SENT:
1220       connection_recreate (c, fwd);
1221       break;
1222     case CADET_CONNECTION_READY:
1223       send_connection_keepalive (c, fwd);
1224       break;
1225     default:
1226       break;
1227   }
1228 }
1229
1230
1231 /**
1232  * Keep the connection alive.
1233  *
1234  * @param c Connection to keep alive.
1235  * @param fwd Direction.
1236  */
1237 static void
1238 connection_keepalive (struct CadetConnection *c,
1239                       int fwd)
1240 {
1241   GCC_check_connections ();
1242   LOG (GNUNET_ERROR_TYPE_DEBUG,
1243        "%s keepalive for %s\n",
1244        GC_f2s (fwd), GCC_2s (c));
1245
1246   if (fwd)
1247     c->fwd_maintenance_task = NULL;
1248   else
1249     c->bck_maintenance_task = NULL;
1250   connection_maintain (c, fwd);
1251   GCC_check_connections ();
1252   /* Next execution will be scheduled by message_sent or _maintain*/
1253 }
1254
1255
1256 /**
1257  * Keep the connection alive in the FWD direction.
1258  *
1259  * @param cls Closure (connection to keepalive).
1260  */
1261 static void
1262 connection_fwd_keepalive (void *cls)
1263 {
1264   struct CadetConnection *c = cls;
1265
1266   GCC_check_connections ();
1267   connection_keepalive (c,
1268                         GNUNET_YES);
1269   GCC_check_connections ();
1270 }
1271
1272
1273 /**
1274  * Keep the connection alive in the BCK direction.
1275  *
1276  * @param cls Closure (connection to keepalive).
1277  */
1278 static void
1279 connection_bck_keepalive (void *cls)
1280 {
1281   struct CadetConnection *c = cls;
1282
1283   GCC_check_connections ();
1284   connection_keepalive (c,
1285                         GNUNET_NO);
1286   GCC_check_connections ();
1287 }
1288
1289
1290 /**
1291  * Schedule next keepalive task, taking in consideration
1292  * the connection state and number of retries.
1293  *
1294  * If the peer is not the origin, do nothing.
1295  *
1296  * @param c Connection for which to schedule the next keepalive.
1297  * @param fwd Direction for the next keepalive.
1298  */
1299 static void
1300 schedule_next_keepalive (struct CadetConnection *c, int fwd)
1301 {
1302   struct GNUNET_TIME_Relative delay;
1303   struct GNUNET_SCHEDULER_Task * *task_id;
1304   GNUNET_SCHEDULER_TaskCallback keepalive_task;
1305
1306   GCC_check_connections ();
1307   if (GNUNET_NO == GCC_is_origin (c, fwd))
1308     return;
1309
1310   /* Calculate delay to use, depending on the state of the connection */
1311   if (CADET_CONNECTION_READY == c->state)
1312   {
1313     delay = refresh_connection_time;
1314   }
1315   else
1316   {
1317     if (1 > c->create_retry)
1318       c->create_retry = 1;
1319     delay = GNUNET_TIME_relative_multiply (create_connection_time,
1320                                            c->create_retry);
1321     if (c->create_retry < 64) // TODO make configurable
1322       c->create_retry *= 2;
1323   }
1324
1325   /* Select direction-dependent parameters */
1326   if (GNUNET_YES == fwd)
1327   {
1328     task_id = &c->fwd_maintenance_task;
1329     keepalive_task = &connection_fwd_keepalive;
1330   }
1331   else
1332   {
1333     task_id = &c->bck_maintenance_task;
1334     keepalive_task = &connection_bck_keepalive;
1335   }
1336
1337   /* Check that no one scheduled it before us */
1338   if (NULL != *task_id)
1339   {
1340     /* No need for a _break. It can happen for instance when sending a SYNACK
1341      * for a duplicate SYN: the first SYNACK scheduled the task. */
1342     GNUNET_SCHEDULER_cancel (*task_id);
1343   }
1344
1345   /* Schedule the task */
1346   *task_id = GNUNET_SCHEDULER_add_delayed (delay,
1347                                            keepalive_task,
1348                                            c);
1349   LOG (GNUNET_ERROR_TYPE_DEBUG,
1350        "next keepalive in %s\n",
1351        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1352   GCC_check_connections ();
1353 }
1354
1355
1356 /**
1357  * Cancel all transmissions that belong to a certain connection.
1358  *
1359  * If the connection is scheduled for destruction and no more messages are left,
1360  * the connection will be destroyed by the continuation call.
1361  *
1362  * @param c Connection which to cancel. Might be destroyed during this call.
1363  * @param fwd Cancel fwd traffic?
1364  */
1365 static void
1366 connection_cancel_queues (struct CadetConnection *c,
1367                           int fwd)
1368 {
1369   struct CadetFlowControl *fc;
1370
1371   GCC_check_connections ();
1372   LOG (GNUNET_ERROR_TYPE_DEBUG,
1373        "Cancel %s queues for connection %s\n",
1374        GC_f2s (fwd), GCC_2s (c));
1375   if (NULL == c)
1376   {
1377     GNUNET_break (0);
1378     return;
1379   }
1380
1381   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1382   if (NULL != fc->poll_task)
1383   {
1384     GNUNET_SCHEDULER_cancel (fc->poll_task);
1385     fc->poll_task = NULL;
1386     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cancelled POLL task for fc %p\n", fc);
1387   }
1388   if (NULL != fc->poll_msg)
1389   {
1390     GCC_cancel (fc->poll_msg);
1391     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cancelled POLL msg for fc %p\n", fc);
1392   }
1393
1394   while (NULL != fc->q_head)
1395   {
1396     GCC_cancel (fc->q_head);
1397   }
1398   GCC_check_connections ();
1399 }
1400
1401
1402 /**
1403  * Function called if a connection has been stalled for a while,
1404  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
1405  *
1406  * @param cls Closure (poll ctx).
1407  */
1408 static void
1409 send_connection_poll (void *cls);
1410
1411
1412 /**
1413  * Callback called when a queued POLL message is sent.
1414  *
1415  * @param cls Closure (flow control context).
1416  * @param c Connection this message was on.
1417  * @param q Queue handler this call invalidates.
1418  * @param type Type of message sent.
1419  * @param fwd Was this a FWD going message?
1420  * @param size Size of the message.
1421  */
1422 static void
1423 poll_sent (void *cls,
1424            struct CadetConnection *c,
1425            struct CadetConnectionQueue *q,
1426            uint16_t type, int fwd, size_t size)
1427 {
1428   struct CadetFlowControl *fc = cls;
1429
1430   GNUNET_assert (fc->poll_msg == q);
1431   fc->poll_msg = NULL;
1432   if (2 == c->destroy)
1433   {
1434     LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL canceled on shutdown\n");
1435     return;
1436   }
1437   if (0 == fc->queue_max)
1438   {
1439     LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL cancelled: neighbor disconnected\n");
1440     return;
1441   }
1442   LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL sent for %s, scheduling new one!\n",
1443        GCC_2s (c));
1444   GNUNET_assert (NULL == fc->poll_task);
1445   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
1446   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
1447                                                 &send_connection_poll,
1448                                                 fc);
1449   LOG (GNUNET_ERROR_TYPE_DEBUG, " task %u\n", fc->poll_task);
1450 }
1451
1452
1453 /**
1454  * Function called if a connection has been stalled for a while,
1455  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
1456  *
1457  * @param cls Closure (poll ctx).
1458  */
1459 static void
1460 send_connection_poll (void *cls)
1461 {
1462   struct CadetFlowControl *fc = cls;
1463   struct GNUNET_CADET_Poll msg;
1464   struct CadetConnection *c;
1465   int fwd;
1466
1467   fc->poll_task = NULL;
1468   GCC_check_connections ();
1469   c = fc->c;
1470   fwd = fc == &c->fwd_fc;
1471   LOG (GNUNET_ERROR_TYPE_DEBUG, "Polling connection %s %s\n",
1472        GCC_2s (c),  GC_f2s (fwd));
1473
1474   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_POLL);
1475   msg.header.size = htons (sizeof (msg));
1476   msg.cid = c->id;
1477   msg.pid = htonl (fc->last_pid_sent);
1478   LOG (GNUNET_ERROR_TYPE_DEBUG, " last pid sent: %u\n", fc->last_pid_sent);
1479   fc->poll_msg =
1480       GCC_send_prebuilt_message (&msg.header, UINT16_MAX, fc->last_pid_sent, c,
1481                                  fc == &c->fwd_fc, GNUNET_YES, &poll_sent, fc);
1482   GNUNET_assert (NULL != fc->poll_msg);
1483   GCC_check_connections ();
1484 }
1485
1486
1487 /**
1488  * Generic connection timeout implementation.
1489  *
1490  * Timeout function due to lack of keepalive/traffic from an endpoint.
1491  * Destroys connection if called.
1492  *
1493  * @param c Connection to destroy.
1494  * @param fwd Was the timeout from the origin? (FWD timeout)
1495  */
1496 static void
1497 connection_timeout (struct CadetConnection *c, int fwd)
1498 {
1499   GCC_check_connections ();
1500
1501   LOG (GNUNET_ERROR_TYPE_INFO,
1502        "Connection %s %s timed out. Destroying.\n",
1503        GCC_2s (c),
1504        GC_f2s (fwd));
1505   GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);
1506
1507   if (GCC_is_origin (c, fwd)) /* Loopback? Something is wrong! */
1508   {
1509     GNUNET_break (0);
1510     return;
1511   }
1512
1513   /* If dest, send "broken" notification. */
1514   if (GCC_is_terminal (c, fwd))
1515   {
1516     struct CadetPeer *next_hop;
1517
1518     next_hop = fwd ? get_prev_hop (c) : get_next_hop (c);
1519     send_broken_unknown (&c->id, &my_full_id, NULL, next_hop);
1520   }
1521
1522   GCC_destroy (c);
1523   GCC_check_connections ();
1524 }
1525
1526
1527 /**
1528  * Timeout function due to lack of keepalive/traffic from the owner.
1529  * Destroys connection if called.
1530  *
1531  * @param cls Closure (connection to destroy).
1532  */
1533 static void
1534 connection_fwd_timeout (void *cls)
1535 {
1536   struct CadetConnection *c = cls;
1537
1538   c->fwd_maintenance_task = NULL;
1539   GCC_check_connections ();
1540   connection_timeout (c, GNUNET_YES);
1541   GCC_check_connections ();
1542 }
1543
1544
1545 /**
1546  * Timeout function due to lack of keepalive/traffic from the destination.
1547  * Destroys connection if called.
1548  *
1549  * @param cls Closure (connection to destroy).
1550  */
1551 static void
1552 connection_bck_timeout (void *cls)
1553 {
1554   struct CadetConnection *c = cls;
1555
1556   c->bck_maintenance_task = NULL;
1557   GCC_check_connections ();
1558   connection_timeout (c, GNUNET_NO);
1559   GCC_check_connections ();
1560 }
1561
1562
1563 /**
1564  * Resets the connection timeout task, some other message has done the
1565  * task's job.
1566  * - For the first peer on the direction this means to send
1567  *   a keepalive or a path confirmation message (either create or ACK).
1568  * - For all other peers, this means to destroy the connection,
1569  *   due to lack of activity.
1570  * Starts the timeout if no timeout was running (connection just created).
1571  *
1572  * @param c Connection whose timeout to reset.
1573  * @param fwd Is this forward?
1574  *
1575  * TODO use heap to improve efficiency of scheduler.
1576  */
1577 static void
1578 connection_reset_timeout (struct CadetConnection *c, int fwd)
1579 {
1580   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s reset timeout\n", GC_f2s (fwd));
1581   if (GCC_is_origin (c, fwd)) /* Startpoint */
1582   {
1583     schedule_next_keepalive (c, fwd);
1584     if (NULL != c->maintenance_q)
1585     {
1586       GCP_send_cancel (c->maintenance_q);
1587       c->maintenance_q = NULL; /* Is set to NULL by conn_message_sent anyway */
1588     }
1589   }
1590   else /* Relay, endpoint. */
1591   {
1592     struct GNUNET_TIME_Relative delay;
1593     struct GNUNET_SCHEDULER_Task * *ti;
1594     GNUNET_SCHEDULER_TaskCallback f;
1595
1596     ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
1597
1598     if (NULL != *ti)
1599       GNUNET_SCHEDULER_cancel (*ti);
1600     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
1601     LOG (GNUNET_ERROR_TYPE_DEBUG,
1602          "  timing out in %s\n",
1603          GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_NO));
1604     f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
1605     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
1606   }
1607 }
1608
1609
1610 /**
1611  * Iterator to compare each connection's path with the path of a new connection.
1612  *
1613  * If the connection coincides, the c member of path is set to the connection
1614  * and the destroy flag of the connection is set.
1615  *
1616  * @param cls Closure (new path).
1617  * @param c Connection in the tunnel to check.
1618  */
1619 static void
1620 check_path (void *cls, struct CadetConnection *c)
1621 {
1622   struct CadetConnection *new_conn = cls;
1623   struct CadetPeerPath *path = new_conn->path;
1624
1625   LOG (GNUNET_ERROR_TYPE_DEBUG, "  checking %s (%p), length %u\n",
1626        GCC_2s (c), c, c->path->length);
1627
1628   if (c != new_conn
1629       && GNUNET_NO == c->destroy
1630       && CADET_CONNECTION_BROKEN != c->state
1631       && CADET_CONNECTION_DESTROYED != c->state
1632       && path_equivalent (path, c->path))
1633   {
1634     new_conn->destroy = GNUNET_YES; /* Do not mark_destroyed, */
1635     new_conn->path->c = c;          /* this is only a flag for the Iterator. */
1636     LOG (GNUNET_ERROR_TYPE_DEBUG, "  MATCH!\n");
1637   }
1638 }
1639
1640
1641 /**
1642  * Finds out if this path is already being used by an existing connection.
1643  *
1644  * Checks the tunnel towards the destination to see if it contains
1645  * any connection with the same path.
1646  *
1647  * If the existing connection is ready, it is kept.
1648  * Otherwise if the sender has a smaller ID that ours, we accept it (and
1649  * the peer will eventually reject our attempt).
1650  *
1651  * @param path Path to check.
1652  * @return #GNUNET_YES if the tunnel has a connection with the same path,
1653  *         #GNUNET_NO otherwise.
1654  */
1655 static int
1656 does_connection_exist (struct CadetConnection *conn)
1657 {
1658   struct CadetPeer *p;
1659   struct CadetTunnel *t;
1660   struct CadetConnection *c;
1661
1662   p = GCP_get_short (conn->path->peers[0], GNUNET_NO);
1663   if (NULL == p)
1664     return GNUNET_NO;
1665   t = GCP_get_tunnel (p);
1666   if (NULL == t)
1667     return GNUNET_NO;
1668
1669   LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking for duplicates\n");
1670
1671   GCT_iterate_connections (t, &check_path, conn);
1672
1673   if (GNUNET_YES == conn->destroy)
1674   {
1675     c = conn->path->c;
1676     conn->destroy = GNUNET_NO;
1677     conn->path->c = conn;
1678     LOG (GNUNET_ERROR_TYPE_DEBUG, " found duplicate of %s\n", GCC_2s (conn));
1679     LOG (GNUNET_ERROR_TYPE_DEBUG, " duplicate: %s\n", GCC_2s (c));
1680     GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);
1681     if (CADET_CONNECTION_READY == c->state)
1682     {
1683       /* The other peer confirmed a live connection with this path,
1684        * why are they trying to duplicate it? */
1685       GNUNET_STATISTICS_update (stats, "# duplicate connections", 1, GNUNET_NO);
1686       return GNUNET_YES;
1687     }
1688     LOG (GNUNET_ERROR_TYPE_DEBUG, " duplicate not ready, connection unique\n");
1689     return GNUNET_NO;
1690   }
1691   else
1692   {
1693     LOG (GNUNET_ERROR_TYPE_DEBUG, " %s has no duplicates\n", GCC_2s (conn));
1694     return GNUNET_NO;
1695   }
1696 }
1697
1698
1699 /**
1700  * @brief Check if the tunnel this connection belongs to has any other
1701  * connection with the same path, and destroy one if so.
1702  *
1703  * @param cls Closure (connection to check).
1704  */
1705 static void
1706 check_duplicates (void *cls)
1707 {
1708   struct CadetConnection *c = cls;
1709
1710   c->check_duplicates_task = NULL;
1711   if (GNUNET_YES == does_connection_exist (c))
1712   {
1713     GCT_debug (c->t, GNUNET_ERROR_TYPE_DEBUG);
1714     send_broken (c, &my_full_id, &my_full_id, GCC_is_origin (c, GNUNET_YES));
1715     GCC_destroy (c);
1716   }
1717 }
1718
1719
1720 /**
1721  * Wait for enough time to let any dead connections time out and check for
1722  * any remaining duplicates.
1723  *
1724  * @param c Connection that is a potential duplicate.
1725  */
1726 static void
1727 schedule_check_duplicates (struct CadetConnection *c)
1728 {
1729   struct GNUNET_TIME_Relative delay;
1730
1731   if (NULL != c->check_duplicates_task)
1732     return;
1733   delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 5);
1734   c->check_duplicates_task = GNUNET_SCHEDULER_add_delayed (delay,
1735                                                            &check_duplicates,
1736                                                            c);
1737 }
1738
1739
1740 /**
1741  * Add the connection to the list of both neighbors.
1742  *
1743  * @param c Connection.
1744  *
1745  * @return #GNUNET_OK if everything went fine
1746  *         #GNUNET_SYSERR if the was an error and @c c is malformed.
1747  */
1748 static int
1749 register_neighbors (struct CadetConnection *c)
1750 {
1751   c->next_peer = get_next_hop (c);
1752   c->prev_peer = get_prev_hop (c);
1753   GNUNET_assert (c->next_peer != c->prev_peer);
1754   LOG (GNUNET_ERROR_TYPE_DEBUG,
1755        "register neighbors for connection %s\n",
1756        GCC_2s (c));
1757   path_debug (c->path);
1758   LOG (GNUNET_ERROR_TYPE_DEBUG,
1759        "own pos %u\n", c->own_pos);
1760   LOG (GNUNET_ERROR_TYPE_DEBUG,
1761        "putting connection %s to next peer %p\n",
1762        GCC_2s (c),
1763        c->next_peer);
1764   LOG (GNUNET_ERROR_TYPE_DEBUG, "next peer %p %s\n",
1765        c->next_peer,
1766        GCP_2s (c->next_peer));
1767   LOG (GNUNET_ERROR_TYPE_DEBUG,
1768        "putting connection %s to prev peer %p\n",
1769        GCC_2s (c),
1770        c->prev_peer);
1771   LOG (GNUNET_ERROR_TYPE_DEBUG,
1772        "prev peer %p %s\n",
1773        c->prev_peer,
1774        GCP_2s (c->prev_peer));
1775
1776   if ( (GNUNET_NO == GCP_is_neighbor (c->next_peer)) ||
1777        (GNUNET_NO == GCP_is_neighbor (c->prev_peer)) )
1778   {
1779     if (GCC_is_origin (c, GNUNET_YES))
1780       GNUNET_STATISTICS_update (stats, "# local bad paths", 1, GNUNET_NO);
1781     GNUNET_STATISTICS_update (stats, "# bad paths", 1, GNUNET_NO);
1782
1783     LOG (GNUNET_ERROR_TYPE_DEBUG,
1784          "  register neighbors failed\n");
1785     LOG (GNUNET_ERROR_TYPE_DEBUG,
1786          "  prev: %s, neighbor?: %d\n",
1787          GCP_2s (c->prev_peer),
1788          GCP_is_neighbor (c->prev_peer));
1789     LOG (GNUNET_ERROR_TYPE_DEBUG,
1790          "  next: %s, neighbor?: %d\n",
1791          GCP_2s (c->next_peer),
1792          GCP_is_neighbor (c->next_peer));
1793     return GNUNET_SYSERR;
1794   }
1795   GCP_add_connection (c->next_peer, c, GNUNET_NO);
1796   GCP_add_connection (c->prev_peer, c, GNUNET_YES);
1797
1798   return GNUNET_OK;
1799 }
1800
1801
1802 /**
1803  * Remove the connection from the list of both neighbors.
1804  *
1805  * @param c Connection.
1806  */
1807 static void
1808 unregister_neighbors (struct CadetConnection *c)
1809 {
1810 //  struct CadetPeer *peer; FIXME dont use next_peer, prev_peer
1811   /* Either already unregistered or never got registered, it's ok either way. */
1812   if (NULL == c->path)
1813     return;
1814   if (NULL != c->next_peer)
1815   {
1816     GCP_remove_connection (c->next_peer, c);
1817     c->next_peer = NULL;
1818   }
1819   if (NULL != c->prev_peer)
1820   {
1821     GCP_remove_connection (c->prev_peer, c);
1822     c->prev_peer = NULL;
1823   }
1824 }
1825
1826
1827 /**
1828  * Invalidates all paths towards all peers that comprise the connection which
1829  * rely on the disconnected peer.
1830  *
1831  * ~O(n^3) (peers in connection * paths/peer * links/path)
1832  *
1833  * @param c Connection whose peers' paths to clean.
1834  * @param disconnected Peer that disconnected.
1835  */
1836 static void
1837 invalidate_paths (struct CadetConnection *c,
1838                   struct CadetPeer *disconnected)
1839 {
1840   struct CadetPeer *peer;
1841   unsigned int i;
1842
1843   for (i = 0; i < c->path->length; i++)
1844   {
1845     peer = GCP_get_short (c->path->peers[i], GNUNET_NO);
1846     if (NULL != peer)
1847       GCP_notify_broken_link (peer, &my_full_id, GCP_get_id (disconnected));
1848   }
1849 }
1850
1851
1852 /**
1853  * Bind the connection to the peer and the tunnel to that peer.
1854  *
1855  * If the peer has no tunnel, create one. Update tunnel and connection
1856  * data structres to reflect new status.
1857  *
1858  * @param c Connection.
1859  * @param peer Peer.
1860  */
1861 static void
1862 add_to_peer (struct CadetConnection *c,
1863              struct CadetPeer *peer)
1864 {
1865   GCP_add_tunnel (peer);
1866   c->t = GCP_get_tunnel (peer);
1867   GCT_add_connection (c->t, c);
1868 }
1869
1870
1871 /**
1872  * Log receipt of message on stderr (INFO level).
1873  *
1874  * @param message Message received.
1875  * @param peer    Peer who sent the message.
1876  * @param conn_id Connection ID of the message.
1877  */
1878 static void
1879 log_message (const struct GNUNET_MessageHeader *message,
1880              const struct CadetPeer *peer,
1881              const struct GNUNET_CADET_Hash *conn_id)
1882 {
1883   uint16_t size;
1884   uint16_t type;
1885   char *arrow;
1886
1887   size = ntohs (message->size);
1888   type = ntohs (message->type);
1889   switch (type)
1890   {
1891     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1892     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1893     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1894     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1895       arrow = "==";
1896       break;
1897     default:
1898       arrow = "--";
1899   }
1900   LOG (GNUNET_ERROR_TYPE_INFO, "<%s %s on conn %s from %s, %6u bytes\n",
1901        arrow, GC_m2s (type), GNUNET_h2s (GC_h2hc (conn_id)),
1902        GCP_2s(peer), (unsigned int) size);
1903 }
1904
1905 /******************************************************************************/
1906 /********************************    API    ***********************************/
1907 /******************************************************************************/
1908
1909 /**
1910  * Handler for connection creation.
1911  *
1912  * @param peer Message sender (neighbor).
1913  * @param msg Message itself.
1914  */
1915 void
1916 GCC_handle_create (struct CadetPeer *peer,
1917                    const struct GNUNET_CADET_ConnectionCreate *msg)
1918 {
1919   const struct GNUNET_CADET_Hash *cid;
1920   struct GNUNET_PeerIdentity *id;
1921   struct CadetPeerPath *path;
1922   struct CadetPeer *dest_peer;
1923   struct CadetPeer *orig_peer;
1924   struct CadetConnection *c;
1925   unsigned int own_pos;
1926   uint16_t size;
1927
1928   GCC_check_connections ();
1929   size = ntohs (msg->header.size);
1930
1931   /* Calculate hops */
1932   size -= sizeof (struct GNUNET_CADET_ConnectionCreate);
1933   if (0 != size % sizeof (struct GNUNET_PeerIdentity))
1934   {
1935     GNUNET_break_op (0);
1936     return;
1937   }
1938   size /= sizeof (struct GNUNET_PeerIdentity);
1939   if (1 > size)
1940   {
1941     GNUNET_break_op (0);
1942     return;
1943   }
1944   LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1945
1946   /* Get parameters */
1947   cid = &msg->cid;
1948   log_message (&msg->header, peer, cid);
1949   id = (struct GNUNET_PeerIdentity *) &msg[1];
1950   LOG (GNUNET_ERROR_TYPE_DEBUG, "    origin: %s\n", GNUNET_i2s (id));
1951
1952   /* Create connection */
1953   c = connection_get (cid);
1954   if (NULL == c)
1955   {
1956     path = path_build_from_peer_ids ((struct GNUNET_PeerIdentity *) &msg[1],
1957                                      size, myid, &own_pos);
1958     if (NULL == path)
1959     {
1960       /* Path was malformed, probably our own ID was not in it. */
1961       GNUNET_STATISTICS_update (stats, "# malformed paths", 1, GNUNET_NO);
1962       GNUNET_break_op (0);
1963       return;
1964     }
1965     if (0 == own_pos)
1966     {
1967       /* We received this request from a neighbor, we cannot be origin */
1968       GNUNET_STATISTICS_update (stats, "# fake paths", 1, GNUNET_NO);
1969       GNUNET_break_op (0);
1970       path_destroy (path);
1971       return;
1972     }
1973
1974     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1975     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1976     c = GCC_new (cid, NULL, path, own_pos);
1977     if (NULL == c)
1978     {
1979       if (path->length - 1 == own_pos)
1980       {
1981         /* If we are destination, why did the creation fail? */
1982         GNUNET_break (0);
1983         path_destroy (path);
1984         GCC_check_connections ();
1985         return;
1986       }
1987       send_broken_unknown (cid, &my_full_id,
1988                            GNUNET_PEER_resolve2 (path->peers[own_pos + 1]),
1989                            peer);
1990       path_destroy (path);
1991       GCC_check_connections ();
1992       return;
1993     }
1994     GCP_add_path_to_all (path, GNUNET_NO);
1995     connection_reset_timeout (c, GNUNET_YES);
1996   }
1997   else
1998   {
1999     path = path_duplicate (c->path);
2000   }
2001   if (CADET_CONNECTION_NEW == c->state)
2002     connection_change_state (c, CADET_CONNECTION_SENT);
2003
2004   /* Remember peers */
2005   dest_peer = GCP_get (&id[size - 1], GNUNET_YES);
2006   orig_peer = GCP_get (&id[0], GNUNET_YES);
2007
2008   /* Is it a connection to us? */
2009   if (c->own_pos == path->length - 1)
2010   {
2011     LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
2012     GCP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_YES);
2013
2014     add_to_peer (c, orig_peer);
2015     if (GNUNET_YES == does_connection_exist (c))
2016     {
2017       /* Peer created a connection equal to one we think exists
2018        * and is fine.
2019        * Solution: Keep both and postpone disambiguation. In the meantime
2020        * the connection will time out or peer will inform us it is broken.
2021        *
2022        * Other options:
2023        * - Use explicit duplicate.
2024        * - Accept new conn and destroy the old. (interruption in higher level)
2025        * - Keep the one with higher ID / created by peer with higher ID. */
2026        schedule_check_duplicates (c);
2027     }
2028
2029     if (CADET_TUNNEL_NEW == GCT_get_cstate (c->t))
2030       GCT_change_cstate (c->t,  CADET_TUNNEL_WAITING);
2031     if (NULL == c->maintenance_q)
2032       send_connection_ack (c, GNUNET_NO);
2033     if (CADET_CONNECTION_SENT == c->state)
2034       connection_change_state (c, CADET_CONNECTION_ACK);
2035   }
2036   else
2037   {
2038     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2039     GCP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
2040     GCP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_NO);
2041     (void) GCC_send_prebuilt_message (&msg->header, 0, 0, c,
2042                                       GNUNET_YES, GNUNET_YES, NULL, NULL);
2043   }
2044   path_destroy (path);
2045   GCC_check_connections ();
2046 }
2047
2048
2049 /**
2050  * Handler for connection confirmations.
2051  *
2052  * @param peer Message sender (neighbor).
2053  * @param msg Message itself.
2054  */
2055 void
2056 GCC_handle_confirm (struct CadetPeer *peer,
2057                     const struct GNUNET_CADET_ConnectionACK *msg)
2058 {
2059   struct CadetConnection *c;
2060   enum CadetConnectionState oldstate;
2061   int fwd;
2062
2063   GCC_check_connections ();
2064   log_message (&msg->header, peer, &msg->cid);
2065   c = connection_get (&msg->cid);
2066   if (NULL == c)
2067   {
2068     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
2069                               1, GNUNET_NO);
2070     LOG (GNUNET_ERROR_TYPE_DEBUG,
2071          "  don't know the connection!\n");
2072     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
2073     GCC_check_connections ();
2074     return;
2075   }
2076   if (GNUNET_NO != c->destroy)
2077   {
2078     GNUNET_assert (CADET_CONNECTION_DESTROYED == c->state);
2079     GNUNET_STATISTICS_update (stats, "# control on dying connection",
2080                               1, GNUNET_NO);
2081     LOG (GNUNET_ERROR_TYPE_DEBUG,
2082          "connection %s being destroyed, ignoring confirm\n",
2083          GCC_2s (c));
2084     GCC_check_connections ();
2085     return;
2086   }
2087
2088   oldstate = c->state;
2089   LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n", GCP_2s (peer));
2090   if (get_next_hop (c) == peer)
2091   {
2092     LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
2093     fwd = GNUNET_NO;
2094     if (CADET_CONNECTION_SENT == oldstate)
2095       connection_change_state (c, CADET_CONNECTION_ACK);
2096   }
2097   else if (get_prev_hop (c) == peer)
2098   {
2099     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FINAL ACK\n");
2100     fwd = GNUNET_YES;
2101     connection_change_state (c, CADET_CONNECTION_READY);
2102   }
2103   else
2104   {
2105     GNUNET_STATISTICS_update (stats, "# control on connection from wrong peer",
2106                               1, GNUNET_NO);
2107     GNUNET_break_op (0);
2108     return;
2109   }
2110
2111   connection_reset_timeout (c, fwd);
2112
2113   GNUNET_assert (NULL != c->path);
2114   GCP_add_path_to_all (c->path, GNUNET_YES);
2115
2116   /* Message for us as creator? */
2117   if (GNUNET_YES == GCC_is_origin (c, GNUNET_YES))
2118   {
2119     if (GNUNET_NO != fwd)
2120     {
2121       GNUNET_break (0);
2122       return;
2123     }
2124     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
2125
2126     /* If just created, cancel the short timeout and start a long one */
2127     if (CADET_CONNECTION_SENT == oldstate)
2128     {
2129       c->create_retry = 1;
2130       connection_reset_timeout (c, GNUNET_YES);
2131     }
2132
2133     /* Change connection state, send ACK */
2134     connection_change_state (c, CADET_CONNECTION_READY);
2135     send_connection_ack (c, GNUNET_YES);
2136
2137     /* Change tunnel state, trigger KX */
2138     if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
2139       GCT_change_cstate (c->t, CADET_TUNNEL_READY);
2140     GCC_check_connections ();
2141     return;
2142   }
2143
2144   /* Message for us as destination? */
2145   if (GCC_is_terminal (c, GNUNET_YES))
2146   {
2147     if (GNUNET_YES != fwd)
2148     {
2149       GNUNET_break (0);
2150       return;
2151     }
2152     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
2153
2154     /* If just created, cancel the short timeout and start a long one */
2155     if (CADET_CONNECTION_ACK == oldstate)
2156       connection_reset_timeout (c, GNUNET_NO);
2157
2158     /* Change tunnel state */
2159     if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
2160       GCT_change_cstate (c->t, CADET_TUNNEL_READY);
2161     GCC_check_connections ();
2162   }
2163   else
2164   {
2165     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2166     (void) GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
2167                                       GNUNET_YES, NULL, NULL);
2168   }
2169   GCC_check_connections ();
2170 }
2171
2172
2173 /**
2174  * Handler for notifications of broken connections.
2175  *
2176  * @param peer Message sender (neighbor).
2177  * @param msg Message itself.
2178  */
2179 void
2180 GCC_handle_broken (struct CadetPeer *peer,
2181                    const struct GNUNET_CADET_ConnectionBroken *msg)
2182 {
2183   struct CadetConnection *c;
2184   struct CadetTunnel *t;
2185   int fwd;
2186
2187   GCC_check_connections ();
2188   log_message (&msg->header, peer, &msg->cid);
2189   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n", GNUNET_i2s (&msg->peer1));
2190   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n", GNUNET_i2s (&msg->peer2));
2191   c = connection_get (&msg->cid);
2192   if (NULL == c)
2193   {
2194     LOG (GNUNET_ERROR_TYPE_DEBUG, "  duplicate CONNECTION_BROKEN\n");
2195     GNUNET_STATISTICS_update (stats, "# duplicate CONNECTION_BROKEN",
2196                               1, GNUNET_NO);
2197     GCC_check_connections ();
2198     return;
2199   }
2200
2201   t = c->t;
2202
2203   fwd = is_fwd (c, peer);
2204   if (GNUNET_SYSERR == fwd)
2205   {
2206     GNUNET_break_op (0);
2207     GCC_check_connections ();
2208     return;
2209   }
2210   mark_destroyed (c);
2211   if (GCC_is_terminal (c, fwd))
2212   {
2213     struct CadetPeer *endpoint;
2214
2215     if (NULL == t)
2216     {
2217       /* A terminal connection should not have 't' set to NULL. */
2218       GNUNET_break (0);
2219       GCC_debug (c, GNUNET_ERROR_TYPE_ERROR);
2220       return;
2221     }
2222     endpoint = GCP_get_short (c->path->peers[c->path->length - 1], GNUNET_YES);
2223     if (2 < c->path->length)
2224       path_invalidate (c->path);
2225     GCP_notify_broken_link (endpoint, &msg->peer1, &msg->peer2);
2226
2227     connection_change_state (c, CADET_CONNECTION_BROKEN);
2228     GCT_remove_connection (t, c);
2229     c->t = NULL;
2230
2231     GCC_destroy (c);
2232   }
2233   else
2234   {
2235     (void) GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
2236                                       GNUNET_YES, NULL, NULL);
2237     connection_cancel_queues (c, !fwd);
2238   }
2239   GCC_check_connections ();
2240   return;
2241 }
2242
2243
2244 /**
2245  * Handler for notifications of destroyed connections.
2246  *
2247  * @param peer Message sender (neighbor).
2248  * @param msg Message itself.
2249  */
2250 void
2251 GCC_handle_destroy (struct CadetPeer *peer,
2252                     const struct GNUNET_CADET_ConnectionDestroy *msg)
2253 {
2254   struct CadetConnection *c;
2255   int fwd;
2256
2257   GCC_check_connections ();
2258   log_message (&msg->header, peer, &msg->cid);
2259   c = connection_get (&msg->cid);
2260   if (NULL == c)
2261   {
2262     /* Probably already got the message from another path,
2263      * destroyed the tunnel and retransmitted to children.
2264      * Safe to ignore.
2265      */
2266     GNUNET_STATISTICS_update (stats,
2267                               "# control on unknown connection",
2268                               1, GNUNET_NO);
2269     LOG (GNUNET_ERROR_TYPE_DEBUG,
2270          "  connection unknown destroyed: previously destroyed?\n");
2271     GCC_check_connections ();
2272     return;
2273   }
2274
2275   fwd = is_fwd (c, peer);
2276   if (GNUNET_SYSERR == fwd)
2277   {
2278     GNUNET_break_op (0);
2279     GCC_check_connections ();
2280     return;
2281   }
2282
2283   if (GNUNET_NO == GCC_is_terminal (c, fwd))
2284   {
2285     (void) GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
2286                                       GNUNET_YES, NULL, NULL);
2287   }
2288   else if (0 == c->pending_messages)
2289   {
2290     LOG (GNUNET_ERROR_TYPE_DEBUG, "  directly destroying connection!\n");
2291     GCC_destroy (c);
2292     GCC_check_connections ();
2293     return;
2294   }
2295   mark_destroyed (c);
2296   if (NULL != c->t)
2297   {
2298     GCT_remove_connection (c->t, c);
2299     c->t = NULL;
2300   }
2301   GCC_check_connections ();
2302   return;
2303 }
2304
2305
2306 /**
2307  * Handler for cadet network traffic hop-by-hop acks.
2308  *
2309  * @param peer Message sender (neighbor).
2310  * @param msg Message itself.
2311  */
2312 void
2313 GCC_handle_ack (struct CadetPeer *peer,
2314                 const struct GNUNET_CADET_ACK *msg)
2315 {
2316   struct CadetConnection *c;
2317   struct CadetFlowControl *fc;
2318   uint32_t ack;
2319   int fwd;
2320
2321   GCC_check_connections ();
2322   log_message (&msg->header, peer, &msg->cid);
2323   c = connection_get (&msg->cid);
2324   if (NULL == c)
2325   {
2326     GNUNET_STATISTICS_update (stats,
2327                               "# ack on unknown connection",
2328                               1,
2329                               GNUNET_NO);
2330     send_broken_unknown (&msg->cid,
2331                          &my_full_id,
2332                          NULL,
2333                          peer);
2334     GCC_check_connections ();
2335     return;
2336   }
2337
2338   /* Is this a forward or backward ACK? */
2339   if (get_next_hop (c) == peer)
2340   {
2341     fc = &c->fwd_fc;
2342     fwd = GNUNET_YES;
2343   }
2344   else if (get_prev_hop (c) == peer)
2345   {
2346     fc = &c->bck_fc;
2347     fwd = GNUNET_NO;
2348   }
2349   else
2350   {
2351     GNUNET_break_op (0);
2352     return;
2353   }
2354
2355   ack = ntohl (msg->ack);
2356   LOG (GNUNET_ERROR_TYPE_DEBUG, " %s ACK %u (was %u)\n",
2357        GC_f2s (fwd), ack, fc->last_ack_recv);
2358   if (GC_is_pid_bigger (ack, fc->last_ack_recv))
2359     fc->last_ack_recv = ack;
2360
2361   /* Cancel polling if the ACK is big enough. */
2362   if (NULL != fc->poll_task &&
2363       GC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2364   {
2365     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
2366     GNUNET_SCHEDULER_cancel (fc->poll_task);
2367     fc->poll_task = NULL;
2368     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
2369   }
2370
2371   GCC_check_connections ();
2372 }
2373
2374
2375 /**
2376  * Handler for cadet network traffic hop-by-hop data counter polls.
2377  *
2378  * @param peer Message sender (neighbor).
2379  * @param msg Message itself.
2380  */
2381 void
2382 GCC_handle_poll (struct CadetPeer *peer,
2383                  const struct GNUNET_CADET_Poll *msg)
2384 {
2385   struct CadetConnection *c;
2386   struct CadetFlowControl *fc;
2387   uint32_t pid;
2388   int fwd;
2389
2390   GCC_check_connections ();
2391   log_message (&msg->header, peer, &msg->cid);
2392   c = connection_get (&msg->cid);
2393   if (NULL == c)
2394   {
2395     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
2396                               GNUNET_NO);
2397     LOG (GNUNET_ERROR_TYPE_DEBUG,
2398          "POLL message on unknown connection %s!\n",
2399          GNUNET_h2s (GC_h2hc (&msg->cid)));
2400     send_broken_unknown (&msg->cid,
2401                          &my_full_id,
2402                          NULL,
2403                          peer);
2404     GCC_check_connections ();
2405     return;
2406   }
2407
2408   /* Is this a forward or backward ACK?
2409    * Note: a poll should never be needed in a loopback case,
2410    * since there is no possiblility of packet loss there, so
2411    * this way of discerining FWD/BCK should not be a problem.
2412    */
2413   if (get_next_hop (c) == peer)
2414   {
2415     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
2416     fc = &c->fwd_fc;
2417   }
2418   else if (get_prev_hop (c) == peer)
2419   {
2420     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
2421     fc = &c->bck_fc;
2422   }
2423   else
2424   {
2425     GNUNET_break_op (0);
2426     return;
2427   }
2428
2429   pid = ntohl (msg->pid);
2430   LOG (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n", pid, fc->last_pid_recv);
2431   fc->last_pid_recv = pid;
2432   fwd = fc == &c->bck_fc;
2433   GCC_send_ack (c, fwd, GNUNET_YES);
2434   GCC_check_connections ();
2435 }
2436
2437
2438 /**
2439  * Check the message against internal state and test if it goes FWD or BCK.
2440  *
2441  * Updates the PID, state and timeout values for the connection.
2442  *
2443  * @param message Message to check. It must belong to an existing connection.
2444  * @param cid Connection ID (even if @a c is NULL, the ID is still needed).
2445  * @param c Connection this message should belong. If NULL, check fails.
2446  * @param sender Neighbor that sent the message.
2447  *
2448  * @return #GNUNET_YES if the message goes FWD.
2449  *         #GNUNET_NO if it goes BCK.
2450  *         #GNUNET_SYSERR if there is an error (unauthorized sender, ...).
2451  */
2452 static int
2453 check_message (const struct GNUNET_MessageHeader *message,
2454                const struct GNUNET_CADET_Hash* cid,
2455                struct CadetConnection *c,
2456                struct CadetPeer *sender,
2457                uint32_t pid)
2458 {
2459   struct CadetFlowControl *fc;
2460   struct CadetPeer *hop;
2461   int fwd;
2462   uint16_t type;
2463
2464   /* Check connection */
2465   if (NULL == c)
2466   {
2467     GNUNET_STATISTICS_update (stats,
2468                               "# unknown connection",
2469                               1, GNUNET_NO);
2470     LOG (GNUNET_ERROR_TYPE_DEBUG,
2471          "%s on unknown connection %s\n",
2472          GC_m2s (ntohs (message->type)),
2473          GNUNET_h2s (GC_h2hc (cid)));
2474     send_broken_unknown (cid,
2475                          &my_full_id,
2476                          NULL,
2477                          sender);
2478     return GNUNET_SYSERR;
2479   }
2480
2481   /* Check if origin is as expected */
2482   hop = get_prev_hop (c);
2483   if (sender == hop)
2484   {
2485     fwd = GNUNET_YES;
2486   }
2487   else
2488   {
2489     hop = get_next_hop (c);
2490     GNUNET_break (hop == c->next_peer);
2491     if (sender == hop)
2492     {
2493       fwd = GNUNET_NO;
2494     }
2495     else
2496     {
2497       /* Unexpected peer sending traffic on a connection. */
2498       GNUNET_break_op (0);
2499       return GNUNET_SYSERR;
2500     }
2501   }
2502
2503   /* Check PID for payload messages */
2504   type = ntohs (message->type);
2505   if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2506   {
2507     fc = fwd ? &c->bck_fc : &c->fwd_fc;
2508     LOG (GNUNET_ERROR_TYPE_DEBUG, " PID %u (expected %u - %u)\n",
2509          pid, fc->last_pid_recv + 1, fc->last_ack_sent);
2510     if (GC_is_pid_bigger (pid, fc->last_ack_sent))
2511     {
2512       GNUNET_break_op (0);
2513       GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
2514       LOG (GNUNET_ERROR_TYPE_WARNING, "Received PID %u, (prev %u), ACK %u\n",
2515           pid, fc->last_pid_recv, fc->last_ack_sent);
2516       return GNUNET_SYSERR;
2517     }
2518     if (GC_is_pid_bigger (pid, fc->last_pid_recv))
2519     {
2520       unsigned int delta;
2521
2522       delta = pid - fc->last_pid_recv;
2523       fc->last_pid_recv = pid;
2524       fc->recv_bitmap <<= delta;
2525       fc->recv_bitmap |= 1;
2526     }
2527     else
2528     {
2529       GNUNET_STATISTICS_update (stats, "# out of order PID", 1, GNUNET_NO);
2530       if (GNUNET_NO == is_ooo_ok (fc->last_pid_recv, pid, fc->recv_bitmap))
2531       {
2532         LOG (GNUNET_ERROR_TYPE_WARNING, "PID %u unexpected (%u+), dropping!\n",
2533              pid, fc->last_pid_recv - 31);
2534         return GNUNET_SYSERR;
2535       }
2536       fc->recv_bitmap |= get_recv_bitmask (fc->last_pid_recv, pid);
2537     }
2538   }
2539
2540   /* Count as connection confirmation. */
2541   if (CADET_CONNECTION_SENT == c->state || CADET_CONNECTION_ACK == c->state)
2542   {
2543     connection_change_state (c, CADET_CONNECTION_READY);
2544     if (NULL != c->t)
2545     {
2546       if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
2547         GCT_change_cstate (c->t, CADET_TUNNEL_READY);
2548     }
2549   }
2550   connection_reset_timeout (c, fwd);
2551
2552   return fwd;
2553 }
2554
2555
2556 /**
2557  * Handler for key exchange traffic (Axolotl KX).
2558  *
2559  * @param peer Message sender (neighbor).
2560  * @param msg Message itself.
2561  */
2562 void
2563 GCC_handle_kx (struct CadetPeer *peer,
2564                const struct GNUNET_CADET_KX *msg)
2565 {
2566   const struct GNUNET_CADET_Hash* cid;
2567   struct CadetConnection *c;
2568   int fwd;
2569
2570   GCC_check_connections ();
2571   cid = &msg->cid;
2572   log_message (&msg->header, peer, cid);
2573
2574   c = connection_get (cid);
2575   fwd = check_message (&msg->header,
2576                        cid,
2577                        c,
2578                        peer,
2579                        0);
2580
2581   /* If something went wrong, discard message. */
2582   if (GNUNET_SYSERR == fwd)
2583   {
2584     GNUNET_break_op (0);
2585     GCC_check_connections ();
2586     return;
2587   }
2588
2589   /* Is this message for us? */
2590   if (GCC_is_terminal (c, fwd))
2591   {
2592     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
2593     GNUNET_STATISTICS_update (stats, "# received KX", 1, GNUNET_NO);
2594     if (NULL == c->t)
2595     {
2596       GNUNET_break (0);
2597       return;
2598     }
2599     GCT_handle_kx (c->t, msg);
2600     GCC_check_connections ();
2601     return;
2602   }
2603
2604   /* Message not for us: forward to next hop */
2605   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2606   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
2607   (void) GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
2608                                     GNUNET_NO, NULL, NULL);
2609   GCC_check_connections ();
2610 }
2611
2612
2613 /**
2614  * Handler for encrypted cadet network traffic (channel mgmt, data).
2615  *
2616  * @param peer Message sender (neighbor).
2617  * @param msg Message itself.
2618  */
2619 void
2620 GCC_handle_encrypted (struct CadetPeer *peer,
2621                       const struct GNUNET_CADET_Encrypted *msg)
2622 {
2623   const struct GNUNET_CADET_Hash* cid;
2624   struct CadetConnection *c;
2625   uint32_t pid;
2626   int fwd;
2627
2628   GCC_check_connections ();
2629   cid = &msg->cid;
2630   pid = ntohl (msg->pid);
2631   log_message (&msg->header, peer, cid);
2632
2633   c = connection_get (cid);
2634   fwd = check_message (&msg->header,
2635                        cid,
2636                        c,
2637                        peer,
2638                        pid);
2639
2640   /* If something went wrong, discard message. */
2641   if (GNUNET_SYSERR == fwd)
2642   {
2643     GNUNET_break_op (0);
2644     GCC_check_connections ();
2645     return;
2646   }
2647
2648   /* Is this message for us? */
2649   if (GCC_is_terminal (c, fwd))
2650   {
2651     GNUNET_STATISTICS_update (stats, "# received encrypted", 1, GNUNET_NO);
2652
2653     if (NULL == c->t)
2654     {
2655       GNUNET_break (GNUNET_NO != c->destroy);
2656       return;
2657     }
2658     GCT_handle_encrypted (c->t, msg);
2659     GCC_send_ack (c, fwd, GNUNET_NO);
2660     GCC_check_connections ();
2661     return;
2662   }
2663
2664   /* Message not for us: forward to next hop */
2665   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2666   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
2667   (void) GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
2668                                     GNUNET_NO, NULL, NULL);
2669   GCC_check_connections ();
2670 }
2671
2672
2673 /**
2674  * Initialize the connections subsystem
2675  *
2676  * @param c Configuration handle.
2677  */
2678 void
2679 GCC_init (const struct GNUNET_CONFIGURATION_Handle *c)
2680 {
2681   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2682   if (GNUNET_OK !=
2683       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_MSGS_QUEUE",
2684                                              &max_msgs_queue))
2685   {
2686     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2687                                "CADET", "MAX_MSGS_QUEUE", "MISSING");
2688     GNUNET_SCHEDULER_shutdown ();
2689     return;
2690   }
2691
2692   if (GNUNET_OK !=
2693       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_CONNECTIONS",
2694                                              &max_connections))
2695   {
2696     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2697                                "CADET", "MAX_CONNECTIONS", "MISSING");
2698     GNUNET_SCHEDULER_shutdown ();
2699     return;
2700   }
2701
2702   if (GNUNET_OK !=
2703       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REFRESH_CONNECTION_TIME",
2704                                            &refresh_connection_time))
2705   {
2706     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2707                                "CADET", "REFRESH_CONNECTION_TIME", "MISSING");
2708     GNUNET_SCHEDULER_shutdown ();
2709     return;
2710   }
2711   create_connection_time = GNUNET_TIME_UNIT_SECONDS;
2712   connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO);
2713 }
2714
2715
2716 /**
2717  * Destroy each connection on shutdown.
2718  *
2719  * @param cls Closure (unused).
2720  * @param key Current key code (CID, unused).
2721  * @param value Value in the hash map (`struct CadetConnection`)
2722  *
2723  * @return #GNUNET_YES, because we should continue to iterate
2724  */
2725 static int
2726 shutdown_iterator (void *cls,
2727                    const struct GNUNET_HashCode *key,
2728                    void *value)
2729 {
2730   struct CadetConnection *c = value;
2731
2732   c->state = CADET_CONNECTION_DESTROYED;
2733   GCC_destroy (c);
2734   return GNUNET_YES;
2735 }
2736
2737
2738 /**
2739  * Shut down the connections subsystem.
2740  */
2741 void
2742 GCC_shutdown (void)
2743 {
2744   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connections\n");
2745   GCC_check_connections ();
2746   GNUNET_CONTAINER_multihashmap_iterate (connections,
2747                                          &shutdown_iterator,
2748                                          NULL);
2749   GNUNET_CONTAINER_multihashmap_destroy (connections);
2750   connections = NULL;
2751 }
2752
2753
2754 /**
2755  * Create a connection.
2756  *
2757  * @param cid Connection ID (either created locally or imposed remotely).
2758  * @param t Tunnel this connection belongs to (or NULL for transit connections);
2759  * @param path Path this connection has to use (copy is made).
2760  * @param own_pos Own position in the @c path path.
2761  *
2762  * @return Newly created connection.
2763  *         NULL in case of error: own id not in path, wrong neighbors, ...
2764 */
2765 struct CadetConnection *
2766 GCC_new (const struct GNUNET_CADET_Hash *cid,
2767          struct CadetTunnel *t,
2768          struct CadetPeerPath *path,
2769          unsigned int own_pos)
2770 {
2771   struct CadetConnection *c;
2772   struct CadetPeerPath *cpath;
2773
2774   GCC_check_connections ();
2775   cpath = path_duplicate (path);
2776   GNUNET_assert (NULL != cpath);
2777   c = GNUNET_new (struct CadetConnection);
2778   c->id = *cid;
2779   GNUNET_assert (GNUNET_OK ==
2780                  GNUNET_CONTAINER_multihashmap_put (connections,
2781                                                     GCC_get_h (c), c,
2782                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2783   fc_init (&c->fwd_fc);
2784   fc_init (&c->bck_fc);
2785   c->fwd_fc.c = c;
2786   c->bck_fc.c = c;
2787
2788   c->t = t;
2789   GNUNET_assert (own_pos <= cpath->length - 1);
2790   c->own_pos = own_pos;
2791   c->path = cpath;
2792   cpath->c = c;
2793   if (GNUNET_OK != register_neighbors (c))
2794   {
2795     if (0 == own_pos)
2796     {
2797       /* We were the origin of this request, this means we have invalid
2798        * info about the paths to reach the destination. We must invalidate
2799        * the *original* path to avoid trying it again in the next minute.
2800        */
2801       if (2 < path->length)
2802         path_invalidate (path);
2803       else
2804       {
2805         GNUNET_break (0);
2806         GCT_debug(t, GNUNET_ERROR_TYPE_WARNING);
2807       }
2808       c->t = NULL;
2809     }
2810     path_destroy (c->path);
2811     c->path = NULL;
2812     GCC_destroy (c);
2813     return NULL;
2814   }
2815   LOG (GNUNET_ERROR_TYPE_INFO, "New connection %s\n", GCC_2s (c));
2816   GCC_check_connections ();
2817   return c;
2818 }
2819
2820
2821 /**
2822  * Connection is no longer needed: destroy it.
2823  *
2824  * Cancels all pending traffic (including possible DESTROY messages), all
2825  * maintenance tasks and removes the connection from neighbor peers and tunnel.
2826  *
2827  * @param c Connection to destroy.
2828  */
2829 void
2830 GCC_destroy (struct CadetConnection *c)
2831 {
2832   GCC_check_connections ();
2833   if (NULL == c)
2834   {
2835     GNUNET_break (0);
2836     return;
2837   }
2838
2839   if (2 == c->destroy) /* cancel queues -> GCP_queue_cancel -> q_destroy -> */
2840     return;            /* -> message_sent -> GCC_destroy. Don't loop. */
2841   c->destroy = 2;
2842
2843   LOG (GNUNET_ERROR_TYPE_DEBUG,
2844        "destroying connection %s\n",
2845        GCC_2s (c));
2846   LOG (GNUNET_ERROR_TYPE_DEBUG,
2847        " fc's f: %p, b: %p\n",
2848        &c->fwd_fc, &c->bck_fc);
2849   LOG (GNUNET_ERROR_TYPE_DEBUG,
2850        " fc tasks f: %u, b: %u\n",
2851        c->fwd_fc.poll_task,
2852        c->bck_fc.poll_task);
2853
2854   /* Cancel all traffic */
2855   if (NULL != c->path)
2856   {
2857     connection_cancel_queues (c, GNUNET_YES);
2858     connection_cancel_queues (c, GNUNET_NO);
2859     if (NULL != c->maintenance_q)
2860     {
2861       GCP_send_cancel (c->maintenance_q);
2862       c->maintenance_q = NULL;
2863     }
2864   }
2865   unregister_neighbors (c);
2866   path_destroy (c->path);
2867   c->path = NULL;
2868
2869   /* Delete from tunnel */
2870   if (NULL != c->t)
2871     GCT_remove_connection (c->t, c);
2872
2873   if (NULL != c->check_duplicates_task)
2874     GNUNET_SCHEDULER_cancel (c->check_duplicates_task);
2875   if (NULL != c->fwd_maintenance_task)
2876     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
2877   if (NULL != c->bck_maintenance_task)
2878     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
2879
2880   if (GNUNET_NO == c->was_removed)
2881   {
2882     GNUNET_break (GNUNET_YES ==
2883                   GNUNET_CONTAINER_multihashmap_remove (connections,
2884                                                         GCC_get_h (c),
2885                                                         c));
2886   }
2887   GNUNET_STATISTICS_update (stats,
2888                             "# connections",
2889                             -1,
2890                             GNUNET_NO);
2891   GNUNET_free (c);
2892   GCC_check_connections ();
2893 }
2894
2895
2896 /**
2897  * Get the connection ID.
2898  *
2899  * @param c Connection to get the ID from.
2900  *
2901  * @return ID of the connection.
2902  */
2903 const struct GNUNET_CADET_Hash *
2904 GCC_get_id (const struct CadetConnection *c)
2905 {
2906   return &c->id;
2907 }
2908
2909
2910 /**
2911  * Get the connection ID.
2912  *
2913  * @param c Connection to get the ID from.
2914  *
2915  * @return ID of the connection.
2916  */
2917 const struct GNUNET_HashCode *
2918 GCC_get_h (const struct CadetConnection *c)
2919 {
2920   return GC_h2hc (&c->id);
2921 }
2922
2923
2924 /**
2925  * Get the connection path.
2926  *
2927  * @param c Connection to get the path from.
2928  *
2929  * @return path used by the connection.
2930  */
2931 const struct CadetPeerPath *
2932 GCC_get_path (const struct CadetConnection *c)
2933 {
2934   if (GNUNET_NO == c->destroy)
2935     return c->path;
2936   return NULL;
2937 }
2938
2939
2940 /**
2941  * Get the connection state.
2942  *
2943  * @param c Connection to get the state from.
2944  *
2945  * @return state of the connection.
2946  */
2947 enum CadetConnectionState
2948 GCC_get_state (const struct CadetConnection *c)
2949 {
2950   return c->state;
2951 }
2952
2953 /**
2954  * Get the connection tunnel.
2955  *
2956  * @param c Connection to get the tunnel from.
2957  *
2958  * @return tunnel of the connection.
2959  */
2960 struct CadetTunnel *
2961 GCC_get_tunnel (const struct CadetConnection *c)
2962 {
2963   return c->t;
2964 }
2965
2966
2967 /**
2968  * Get free buffer space in a connection.
2969  *
2970  * @param c Connection.
2971  * @param fwd Is query about FWD traffic?
2972  *
2973  * @return Free buffer space [0 - max_msgs_queue/max_connections]
2974  */
2975 unsigned int
2976 GCC_get_buffer (struct CadetConnection *c, int fwd)
2977 {
2978   struct CadetFlowControl *fc;
2979
2980   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2981
2982   LOG (GNUNET_ERROR_TYPE_DEBUG, "  Get %s buffer on %s: %u - %u\n",
2983        GC_f2s (fwd), GCC_2s (c), fc->queue_max, fc->queue_n);
2984   GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);
2985
2986   return (fc->queue_max - fc->queue_n);
2987 }
2988
2989
2990 /**
2991  * Get how many messages have we allowed to send to us from a direction.
2992  *
2993  * @param c Connection.
2994  * @param fwd Are we asking about traffic from FWD (BCK messages)?
2995  *
2996  * @return last_ack_sent - last_pid_recv
2997  */
2998 unsigned int
2999 GCC_get_allowed (struct CadetConnection *c, int fwd)
3000 {
3001   struct CadetFlowControl *fc;
3002
3003   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3004   if (CADET_CONNECTION_READY != c->state
3005       || GC_is_pid_bigger (fc->last_pid_recv, fc->last_ack_sent))
3006   {
3007     return 0;
3008   }
3009   return (fc->last_ack_sent - fc->last_pid_recv);
3010 }
3011
3012
3013 /**
3014  * Get messages queued in a connection.
3015  *
3016  * @param c Connection.
3017  * @param fwd Is query about FWD traffic?
3018  *
3019  * @return Number of messages queued.
3020  */
3021 unsigned int
3022 GCC_get_qn (struct CadetConnection *c, int fwd)
3023 {
3024   struct CadetFlowControl *fc;
3025
3026   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3027
3028   return fc->queue_n;
3029 }
3030
3031
3032 /**
3033  * Get next PID to use.
3034  *
3035  * @param c Connection.
3036  * @param fwd Is query about FWD traffic?
3037  *
3038  * @return Next PID to use.
3039  */
3040 uint32_t
3041 GCC_get_pid (struct CadetConnection *c, int fwd)
3042 {
3043   struct CadetFlowControl *fc;
3044   uint32_t pid;
3045
3046   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3047   pid = fc->next_pid;
3048   fc->next_pid++;
3049   return pid;
3050 }
3051
3052
3053 /**
3054  * Allow the connection to advertise a buffer of the given size.
3055  *
3056  * The connection will send an @c fwd ACK message (so: in direction !fwd)
3057  * allowing up to last_pid_recv + buffer.
3058  *
3059  * @param c Connection.
3060  * @param buffer How many more messages the connection can accept.
3061  * @param fwd Is this about FWD traffic? (The ack will go dest->root).
3062  */
3063 void
3064 GCC_allow (struct CadetConnection *c, unsigned int buffer, int fwd)
3065 {
3066   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowing %s %u messages %s\n",
3067        GCC_2s (c), buffer, GC_f2s (fwd));
3068   send_ack (c, buffer, fwd, GNUNET_NO);
3069 }
3070
3071
3072 /**
3073  * Notify other peers on a connection of a broken link. Mark connections
3074  * to destroy after all traffic has been sent.
3075  *
3076  * @param c Connection on which there has been a disconnection.
3077  * @param peer Peer that disconnected.
3078  */
3079 void
3080 GCC_neighbor_disconnected (struct CadetConnection *c, struct CadetPeer *peer)
3081 {
3082   struct CadetFlowControl *fc;
3083   char peer_name[16];
3084   int fwd;
3085
3086   GCC_check_connections ();
3087   strncpy (peer_name, GCP_2s (peer), 16);
3088   peer_name[15] = '\0';
3089   LOG (GNUNET_ERROR_TYPE_DEBUG,
3090        "shutting down %s, %s disconnected\n",
3091        GCC_2s (c), peer_name);
3092
3093   invalidate_paths (c, peer);
3094
3095   fwd = is_fwd (c, peer);
3096   if (GNUNET_SYSERR == fwd)
3097   {
3098     GNUNET_break (0);
3099     return;
3100   }
3101   if ( (GNUNET_YES == GCC_is_terminal (c, fwd)) ||
3102        (GNUNET_NO != c->destroy) )
3103   {
3104     /* Local shutdown, or other peer already down (hence 'c->destroy');
3105        so there is no one to notify about this, just clean up. */
3106     GCC_destroy (c);
3107     GCC_check_connections ();
3108     return;
3109   }
3110   /* Mark FlowControl towards the peer as unavaliable. */
3111   fc = fwd ? &c->bck_fc : &c->fwd_fc;
3112   fc->queue_max = 0;
3113
3114   send_broken (c, &my_full_id, GCP_get_id (peer), fwd);
3115
3116   /* Connection will have at least one pending message
3117    * (the one we just scheduled), so delay destruction
3118    * and remove from map so we don't use accidentally. */
3119   mark_destroyed (c);
3120   GNUNET_assert (GNUNET_NO == c->was_removed);
3121   c->was_removed = GNUNET_YES;
3122   GNUNET_break (GNUNET_YES ==
3123                 GNUNET_CONTAINER_multihashmap_remove (connections,
3124                                                       GCC_get_h (c),
3125                                                       c));
3126   /* Cancel queue in the direction that just died. */
3127   connection_cancel_queues (c, ! fwd);
3128   GCC_stop_poll (c, ! fwd);
3129   unregister_neighbors (c);
3130   GCC_check_connections ();
3131 }
3132
3133
3134 /**
3135  * Is this peer the first one on the connection?
3136  *
3137  * @param c Connection.
3138  * @param fwd Is this about fwd traffic?
3139  *
3140  * @return #GNUNET_YES if origin, #GNUNET_NO if relay/terminal.
3141  */
3142 int
3143 GCC_is_origin (struct CadetConnection *c, int fwd)
3144 {
3145   if (!fwd && c->path->length - 1 == c->own_pos )
3146     return GNUNET_YES;
3147   if (fwd && 0 == c->own_pos)
3148     return GNUNET_YES;
3149   return GNUNET_NO;
3150 }
3151
3152
3153 /**
3154  * Is this peer the last one on the connection?
3155  *
3156  * @param c Connection.
3157  * @param fwd Is this about fwd traffic?
3158  *            Note that the ROOT is the terminal for BCK traffic!
3159  *
3160  * @return #GNUNET_YES if terminal, #GNUNET_NO if relay/origin.
3161  */
3162 int
3163 GCC_is_terminal (struct CadetConnection *c, int fwd)
3164 {
3165   return GCC_is_origin (c, ! fwd);
3166 }
3167
3168
3169 /**
3170  * See if we are allowed to send by the next hop in the given direction.
3171  *
3172  * @param c Connection.
3173  * @param fwd Is this about fwd traffic?
3174  *
3175  * @return #GNUNET_YES in case it's OK to send.
3176  */
3177 int
3178 GCC_is_sendable (struct CadetConnection *c, int fwd)
3179 {
3180   struct CadetFlowControl *fc;
3181
3182   LOG (GNUNET_ERROR_TYPE_DEBUG,
3183        " checking sendability of %s traffic on %s\n",
3184        GC_f2s (fwd), GCC_2s (c));
3185   if (NULL == c)
3186   {
3187     GNUNET_break (0);
3188     return GNUNET_YES;
3189   }
3190   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3191   LOG (GNUNET_ERROR_TYPE_DEBUG,
3192        " last ack recv: %u, last pid sent: %u\n",
3193        fc->last_ack_recv, fc->last_pid_sent);
3194   if (GC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
3195   {
3196     LOG (GNUNET_ERROR_TYPE_DEBUG, " sendable\n");
3197     return GNUNET_YES;
3198   }
3199   LOG (GNUNET_ERROR_TYPE_DEBUG, " not sendable\n");
3200   return GNUNET_NO;
3201 }
3202
3203
3204 /**
3205  * Check if this connection is a direct one (never trim a direct connection).
3206  *
3207  * @param c Connection.
3208  *
3209  * @return #GNUNET_YES in case it's a direct connection, #GNUNET_NO otherwise.
3210  */
3211 int
3212 GCC_is_direct (struct CadetConnection *c)
3213 {
3214   return (c->path->length == 2) ? GNUNET_YES : GNUNET_NO;
3215 }
3216
3217
3218 /**
3219  * Sends a completely built message on a connection, properly registering
3220  * all used resources.
3221  *
3222  * @param message Message to send.
3223  * @param payload_type Type of payload, in case the message is encrypted.
3224  *                     0 for restransmissions (when type is no longer known)
3225  *                     UINT16_MAX when not applicable.
3226  * @param payload_id ID of the payload (PID, ACK, ...).
3227  * @param c Connection on which this message is transmitted.
3228  * @param fwd Is this a fwd message?
3229  * @param force Force the connection to accept the message (buffer overfill).
3230  * @param cont Continuation called once message is sent. Can be NULL.
3231  * @param cont_cls Closure for @c cont.
3232  *
3233  * @return Handle to cancel the message before it's sent.
3234  *         NULL on error or if @c cont is NULL.
3235  *         Invalid on @c cont call.
3236  */
3237 struct CadetConnectionQueue *
3238 GCC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3239                            uint16_t payload_type, uint32_t payload_id,
3240                            struct CadetConnection *c, int fwd, int force,
3241                            GCC_sent cont, void *cont_cls)
3242 {
3243   struct CadetFlowControl *fc;
3244   struct CadetConnectionQueue *q;
3245   uint16_t size;
3246   uint16_t type;
3247
3248   size = ntohs (message->size);
3249   type = ntohs (message->type);
3250
3251   GCC_check_connections ();
3252   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3253   if (0 == fc->queue_max)
3254   {
3255     GNUNET_break (0);
3256     return NULL;
3257   }
3258
3259   LOG (GNUNET_ERROR_TYPE_INFO,
3260        "--> %s (%s %4u) on conn %s (%p) %s [%5u]\n",
3261        GC_m2s (type), GC_m2s (payload_type), payload_id, GCC_2s (c), c,
3262        GC_f2s(fwd), size);
3263   switch (type)
3264   {
3265     case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3266       LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
3267       LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid sent %u\n", fc->last_pid_sent);
3268       LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack recv %u\n", fc->last_ack_recv);
3269       if (GNUNET_NO == force)
3270       {
3271         fc->queue_n++;
3272       }
3273       break;
3274
3275     case GNUNET_MESSAGE_TYPE_CADET_KX:
3276       break;
3277
3278     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
3279     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
3280        /* Should've only be used for restransmissions. */
3281       GNUNET_break (0 == payload_type);
3282       break;
3283
3284     case GNUNET_MESSAGE_TYPE_CADET_ACK:
3285     case GNUNET_MESSAGE_TYPE_CADET_POLL:
3286     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
3287     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
3288       GNUNET_assert (GNUNET_YES == force);
3289       break;
3290
3291     default:
3292       GNUNET_break (0);
3293       return NULL;
3294   }
3295
3296   if (fc->queue_n > fc->queue_max && GNUNET_NO == force)
3297   {
3298     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
3299                               1, GNUNET_NO);
3300     GNUNET_break (0);
3301     LOG (GNUNET_ERROR_TYPE_DEBUG, "queue full: %u/%u\n",
3302          fc->queue_n, fc->queue_max);
3303     if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
3304     {
3305       fc->queue_n--;
3306     }
3307     return NULL; /* Drop this message */
3308   }
3309
3310   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %s %u\n",
3311        GCC_2s (c), c->pending_messages);
3312   c->pending_messages++;
3313
3314   q = GNUNET_new (struct CadetConnectionQueue);
3315   q->forced = force;
3316   q->peer_q = GCP_send (get_hop (c, fwd), message,
3317                         payload_type, payload_id,
3318                         c, fwd,
3319                         &conn_message_sent, q);
3320   if (NULL == q->peer_q)
3321   {
3322     LOG (GNUNET_ERROR_TYPE_DEBUG, "dropping msg on %s, NULL q\n", GCC_2s (c));
3323     GNUNET_free (q);
3324     GCC_check_connections ();
3325     return NULL;
3326   }
3327   q->cont = cont;
3328   q->cont_cls = cont_cls;
3329   GNUNET_CONTAINER_DLL_insert (fc->q_head, fc->q_tail, q);
3330   GCC_check_connections ();
3331   return q;
3332 }
3333
3334
3335 /**
3336  * Cancel a previously sent message while it's in the queue.
3337  *
3338  * ONLY can be called before the continuation given to the send function
3339  * is called. Once the continuation is called, the message is no longer in the
3340  * queue.
3341  *
3342  * @param q Handle to the queue.
3343  */
3344 void
3345 GCC_cancel (struct CadetConnectionQueue *q)
3346 {
3347   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  GCC cancel message\n");
3348
3349   /* send_cancel calls message_sent, which calls q->cont and frees q */
3350   GCP_send_cancel (q->peer_q);
3351   GCC_check_connections ();
3352 }
3353
3354
3355 /**
3356  * Sends a CREATE CONNECTION message for a path to a peer.
3357  * Changes the connection and tunnel states if necessary.
3358  *
3359  * @param c Connection to create.
3360  */
3361 void
3362 GCC_send_create (struct CadetConnection *c)
3363 {
3364   enum CadetTunnelCState state;
3365   size_t size;
3366
3367   GCC_check_connections ();
3368   size = sizeof (struct GNUNET_CADET_ConnectionCreate);
3369   size += c->path->length * sizeof (struct GNUNET_PeerIdentity);
3370   {
3371     /* Allocate message on the stack */
3372     unsigned char cbuf[size];
3373     struct GNUNET_CADET_ConnectionCreate *msg;
3374     struct GNUNET_PeerIdentity *peers;
3375
3376     msg = (struct GNUNET_CADET_ConnectionCreate *) cbuf;
3377     msg->header.size = htons (size);
3378     msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE);
3379     msg->reserved = htonl (0);
3380     msg->cid = *GCC_get_id (c);
3381     peers = (struct GNUNET_PeerIdentity *) &msg[1];
3382     for (int i = 0; i < c->path->length; i++)
3383     {
3384       GNUNET_PEER_resolve (c->path->peers[i], peers++);
3385     }
3386     GNUNET_assert (NULL == c->maintenance_q);
3387     c->maintenance_q = GCP_send (get_next_hop (c),
3388                                  &msg->header,
3389                                  GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, 0,
3390                                  c, GNUNET_YES,
3391                                  &conn_message_sent, NULL);
3392   }
3393
3394   LOG (GNUNET_ERROR_TYPE_INFO, "==> %s %19s on conn %s (%p) FWD [%5u]\n",
3395        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE), "",
3396        GCC_2s (c), c, size);
3397   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u (create)\n",
3398          c, c->pending_messages);
3399   c->pending_messages++;
3400
3401   state = GCT_get_cstate (c->t);
3402   if (CADET_TUNNEL_SEARCHING == state || CADET_TUNNEL_NEW == state)
3403     GCT_change_cstate (c->t, CADET_TUNNEL_WAITING);
3404   if (CADET_CONNECTION_NEW == c->state)
3405     connection_change_state (c, CADET_CONNECTION_SENT);
3406   GCC_check_connections ();
3407 }
3408
3409
3410 /**
3411  * Send an ACK on the appropriate connection/channel, depending on
3412  * the direction and the position of the peer.
3413  *
3414  * @param c Which connection to send the hop-by-hop ACK.
3415  * @param fwd Is this a fwd ACK? (will go dest->root).
3416  * @param force Send the ACK even if suboptimal (e.g. requested by POLL).
3417  */
3418 void
3419 GCC_send_ack (struct CadetConnection *c, int fwd, int force)
3420 {
3421   unsigned int buffer;
3422
3423   GCC_check_connections ();
3424   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCC send %s ACK on %s\n",
3425        GC_f2s (fwd), GCC_2s (c));
3426
3427   if (NULL == c)
3428   {
3429     GNUNET_break (0);
3430     return;
3431   }
3432
3433   if (GNUNET_NO != c->destroy)
3434   {
3435     LOG (GNUNET_ERROR_TYPE_DEBUG, "  being destroyed, why bother...\n");
3436     GCC_check_connections ();
3437     return;
3438   }
3439
3440   /* Get available buffer space */
3441   if (GCC_is_terminal (c, fwd))
3442   {
3443     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from all channels\n");
3444     buffer = GCT_get_channels_buffer (c->t);
3445   }
3446   else
3447   {
3448     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
3449     buffer = GCC_get_buffer (c, fwd);
3450   }
3451   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
3452   if (0 == buffer && GNUNET_NO == force)
3453   {
3454     GCC_check_connections ();
3455     return;
3456   }
3457
3458   /* Send available buffer space */
3459   if (GNUNET_YES == GCC_is_origin (c, fwd))
3460   {
3461     GNUNET_assert (NULL != c->t);
3462     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channels...\n");
3463     GCT_unchoke_channels (c->t);
3464   }
3465   else
3466   {
3467     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
3468     send_ack (c, buffer, fwd, force);
3469   }
3470   GCC_check_connections ();
3471 }
3472
3473
3474 /**
3475  * Send a message to all peers in this connection that the connection
3476  * is no longer valid.
3477  *
3478  * If some peer should not receive the message, it should be zero'ed out
3479  * before calling this function.
3480  *
3481  * @param c The connection whose peers to notify.
3482  */
3483 void
3484 GCC_send_destroy (struct CadetConnection *c)
3485 {
3486   struct GNUNET_CADET_ConnectionDestroy msg;
3487
3488   if (GNUNET_YES == c->destroy)
3489     return;
3490   GCC_check_connections ();
3491   msg.header.size = htons (sizeof (msg));
3492   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY);
3493   msg.cid = c->id;
3494   msg.reserved = htonl (0);
3495   LOG (GNUNET_ERROR_TYPE_DEBUG,
3496               "  sending connection destroy for connection %s\n",
3497               GCC_2s (c));
3498
3499   if (GNUNET_NO == GCC_is_terminal (c, GNUNET_YES))
3500     (void) GCC_send_prebuilt_message (&msg.header, UINT16_MAX, 0, c,
3501                                       GNUNET_YES, GNUNET_YES, NULL, NULL);
3502   if (GNUNET_NO == GCC_is_terminal (c, GNUNET_NO))
3503     (void) GCC_send_prebuilt_message (&msg.header, UINT16_MAX, 0, c,
3504                                       GNUNET_NO, GNUNET_YES, NULL, NULL);
3505   mark_destroyed (c);
3506   GCC_check_connections ();
3507 }
3508
3509
3510 /**
3511  * @brief Start a polling timer for the connection.
3512  *
3513  * When a neighbor does not accept more traffic on the connection it could be
3514  * caused by a simple congestion or by a lost ACK. Polling enables to check
3515  * for the lastest ACK status for a connection.
3516  *
3517  * @param c Connection.
3518  * @param fwd Should we poll in the FWD direction?
3519  */
3520 void
3521 GCC_start_poll (struct CadetConnection *c, int fwd)
3522 {
3523   struct CadetFlowControl *fc;
3524
3525   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3526   LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL %s requested\n",
3527        GC_f2s (fwd));
3528   if (NULL != fc->poll_task || NULL != fc->poll_msg)
3529   {
3530     LOG (GNUNET_ERROR_TYPE_DEBUG, "  POLL already in progress (t: %p, m: %p)\n",
3531          fc->poll_task, fc->poll_msg);
3532     return;
3533   }
3534   if (0 == fc->queue_max)
3535   {
3536     /* Should not be needed, traffic should've been cancelled. */
3537     GNUNET_break (0);
3538     LOG (GNUNET_ERROR_TYPE_DEBUG, "  POLL not possible, peer disconnected\n");
3539     return;
3540   }
3541   LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL started on request\n");
3542   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3543                                                 &send_connection_poll,
3544                                                 fc);
3545 }
3546
3547
3548 /**
3549  * @brief Stop polling a connection for ACKs.
3550  *
3551  * Once we have enough ACKs for future traffic, polls are no longer necessary.
3552  *
3553  * @param c Connection.
3554  * @param fwd Should we stop the poll in the FWD direction?
3555  */
3556 void
3557 GCC_stop_poll (struct CadetConnection *c, int fwd)
3558 {
3559   struct CadetFlowControl *fc;
3560
3561   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3562   if (NULL != fc->poll_task)
3563   {
3564     GNUNET_SCHEDULER_cancel (fc->poll_task);
3565     fc->poll_task = NULL;
3566   }
3567   if (NULL != fc->poll_msg)
3568   {
3569     GCC_cancel (fc->poll_msg);
3570     fc->poll_msg = NULL;
3571   }
3572 }
3573
3574
3575 /**
3576  * Get a (static) string for a connection.
3577  *
3578  * @param c Connection.
3579  */
3580 const char *
3581 GCC_2s (const struct CadetConnection *c)
3582 {
3583   if (NULL == c)
3584     return "NULL";
3585
3586   if (NULL != c->t)
3587   {
3588     static char buf[128];
3589
3590     SPRINTF (buf, "%s (->%s)",
3591              GNUNET_h2s (GC_h2hc (GCC_get_id (c))), GCT_2s (c->t));
3592     return buf;
3593   }
3594   return GNUNET_h2s (GC_h2hc (&c->id));
3595 }
3596
3597
3598 /**
3599  * Log all possible info about the connection state.
3600  *
3601  * @param c Connection to debug.
3602  * @param level Debug level to use.
3603  */
3604 void
3605 GCC_debug (const struct CadetConnection *c, enum GNUNET_ErrorType level)
3606 {
3607   int do_log;
3608   char *s;
3609
3610   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3611                                        "cadet-con",
3612                                        __FILE__, __FUNCTION__, __LINE__);
3613   if (0 == do_log)
3614     return;
3615
3616   if (NULL == c)
3617   {
3618     LOG2 (level, "CCC DEBUG NULL CONNECTION\n");
3619     return;
3620   }
3621
3622   LOG2 (level, "CCC DEBUG CONNECTION %s\n", GCC_2s (c));
3623   s = path_2s (c->path);
3624   LOG2 (level, "CCC  path %s, own pos: %u\n", s, c->own_pos);
3625   GNUNET_free (s);
3626   LOG2 (level, "CCC  state: %s, destroy: %u\n",
3627         GCC_state2s (c->state), c->destroy);
3628   LOG2 (level, "CCC  pending messages: %u\n", c->pending_messages);
3629   if (NULL != c->perf)
3630     LOG2 (level, "CCC  us/byte: %f\n", c->perf->avg);
3631
3632   LOG2 (level, "CCC  FWD flow control:\n");
3633   LOG2 (level, "CCC   queue: %u/%u\n", c->fwd_fc.queue_n, c->fwd_fc.queue_max);
3634   LOG2 (level, "CCC   last PID sent: %5u, recv: %5u\n",
3635         c->fwd_fc.last_pid_sent, c->fwd_fc.last_pid_recv);
3636   LOG2 (level, "CCC   last ACK sent: %5u, recv: %5u\n",
3637         c->fwd_fc.last_ack_sent, c->fwd_fc.last_ack_recv);
3638   LOG2 (level, "CCC   recv PID bitmap: %X\n", c->fwd_fc.recv_bitmap);
3639   LOG2 (level, "CCC   poll: task %d, msg  %p, msg_ack %p)\n",
3640         c->fwd_fc.poll_task, c->fwd_fc.poll_msg, c->fwd_fc.ack_msg);
3641
3642   LOG2 (level, "CCC  BCK flow control:\n");
3643   LOG2 (level, "CCC   queue: %u/%u\n", c->bck_fc.queue_n, c->bck_fc.queue_max);
3644   LOG2 (level, "CCC   last PID sent: %5u, recv: %5u\n",
3645         c->bck_fc.last_pid_sent, c->bck_fc.last_pid_recv);
3646   LOG2 (level, "CCC   last ACK sent: %5u, recv: %5u\n",
3647         c->bck_fc.last_ack_sent, c->bck_fc.last_ack_recv);
3648   LOG2 (level, "CCC   recv PID bitmap: %X\n", c->bck_fc.recv_bitmap);
3649   LOG2 (level, "CCC   poll: task %d, msg  %p, msg_ack %p)\n",
3650         c->bck_fc.poll_task, c->bck_fc.poll_msg, c->bck_fc.ack_msg);
3651
3652   LOG2 (level, "CCC DEBUG CONNECTION END\n");
3653 }