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