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