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