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