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