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