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