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