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