- avoid duplicate (same path) connections
[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   unsigned 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 pid %u\n",
586        sent ? "" : "not ", GC_f2s (fwd), GC_m2s (type), pid);
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  * Resend all queued messages for a connection on other connections of the
1262  * same tunnel, if possible. The connection WILL BE DESTROYED by this function.
1263  *
1264  * @param c Connection whose messages to resend.
1265  * @param fwd Resend fwd messages?
1266  */
1267 static void
1268 resend_messages_and_destroy (struct CadetConnection *c, int fwd)
1269 {
1270   struct GNUNET_MessageHeader *out_msg;
1271   struct CadetTunnel *t = c->t;
1272   struct CadetPeer *neighbor;
1273   unsigned int pending;
1274   int destroyed;
1275
1276   c->state = CADET_CONNECTION_DESTROYED;
1277   c->destroy = GNUNET_YES;
1278
1279   destroyed = GNUNET_NO;
1280   neighbor = get_hop (c, fwd);
1281   pending = c->pending_messages;
1282
1283   while (NULL != (out_msg = GCP_connection_pop (neighbor, c, &destroyed)))
1284   {
1285     if (NULL != t)
1286       GCT_resend_message (out_msg, t);
1287     GNUNET_free (out_msg);
1288   }
1289
1290   /* All pending messages should have been popped,
1291    * and the connection destroyed by the continuation.
1292    */
1293   if (GNUNET_YES != destroyed)
1294   {
1295     if (0 != pending)
1296     {
1297       GNUNET_break (0);
1298       GCC_debug (c, GNUNET_ERROR_TYPE_ERROR);
1299       if (NULL != t) GCT_debug (t, GNUNET_ERROR_TYPE_ERROR);
1300     }
1301     GCC_destroy (c);
1302   }
1303 }
1304
1305
1306 /**
1307  * Timeout function due to lack of keepalive/traffic from the owner.
1308  * Destroys connection if called.
1309  *
1310  * @param cls Closure (connection to destroy).
1311  * @param tc TaskContext.
1312  */
1313 static void
1314 connection_fwd_timeout (void *cls,
1315                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1316 {
1317   struct CadetConnection *c = cls;
1318
1319   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
1320   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1321     return;
1322
1323   LOG (GNUNET_ERROR_TYPE_INFO, "Connection %s FWD timed out. Destroying.\n",
1324        GCC_2s (c));
1325   GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);
1326
1327   if (GCC_is_origin (c, GNUNET_YES)) /* If local, leave. */
1328   {
1329     GNUNET_break (0);
1330     return;
1331   }
1332
1333   /* If dest, salvage queued traffic. */
1334   if (GCC_is_origin (c, GNUNET_NO) && 0 < c->bck_fc.queue_n)
1335   {
1336     resend_messages_and_destroy (c, GNUNET_NO);
1337     return;
1338   }
1339
1340   GCC_destroy (c);
1341 }
1342
1343
1344 /**
1345  * Timeout function due to lack of keepalive/traffic from the destination.
1346  * Destroys connection if called.
1347  *
1348  * FIXME refactor and merge with connection_fwd_timeout.
1349  *
1350  * @param cls Closure (connection to destroy).
1351  * @param tc TaskContext
1352  */
1353 static void
1354 connection_bck_timeout (void *cls,
1355                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1356 {
1357   struct CadetConnection *c = cls;
1358
1359   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
1360   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1361     return;
1362
1363   LOG (GNUNET_ERROR_TYPE_INFO, "Connection %s BCK timed out. Destroying.\n",
1364        GCC_2s (c));
1365
1366   if (GCC_is_origin (c, GNUNET_NO)) /* If local, leave. */
1367   {
1368     GNUNET_break (0);
1369     return;
1370   }
1371
1372   /* If dest, salvage queued traffic. */
1373   if (GCC_is_origin (c, GNUNET_YES) && 0 < c->fwd_fc.queue_n)
1374   {
1375     resend_messages_and_destroy (c, GNUNET_YES);
1376     return;
1377   }
1378
1379   GCC_destroy (c);
1380 }
1381
1382
1383 /**
1384  * Resets the connection timeout task, some other message has done the
1385  * task's job.
1386  * - For the first peer on the direction this means to send
1387  *   a keepalive or a path confirmation message (either create or ACK).
1388  * - For all other peers, this means to destroy the connection,
1389  *   due to lack of activity.
1390  * Starts the timeout if no timeout was running (connection just created).
1391  *
1392  * @param c Connection whose timeout to reset.
1393  * @param fwd Is this forward?
1394  *
1395  * TODO use heap to improve efficiency of scheduler.
1396  */
1397 static void
1398 connection_reset_timeout (struct CadetConnection *c, int fwd)
1399 {
1400   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s reset timeout\n", GC_f2s (fwd));
1401
1402   if (GCC_is_origin (c, fwd)) /* Startpoint */
1403   {
1404     schedule_next_keepalive (c, fwd);
1405   }
1406   else /* Relay, endpoint. */
1407   {
1408     struct GNUNET_TIME_Relative delay;
1409     GNUNET_SCHEDULER_TaskIdentifier *ti;
1410     GNUNET_SCHEDULER_Task f;
1411
1412     ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
1413
1414     if (GNUNET_SCHEDULER_NO_TASK != *ti)
1415       GNUNET_SCHEDULER_cancel (*ti);
1416     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
1417     LOG (GNUNET_ERROR_TYPE_DEBUG, "  timing out in %s\n",
1418          GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_NO));
1419     f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
1420     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
1421   }
1422 }
1423
1424
1425 /**
1426  * Add the connection to the list of both neighbors.
1427  *
1428  * @param c Connection.
1429  *
1430  * @return #GNUNET_OK if everything went fine
1431  *         #GNUNET_SYSERR if the was an error and @c c is malformed.
1432  */
1433 static int
1434 register_neighbors (struct CadetConnection *c)
1435 {
1436   struct CadetPeer *next_peer;
1437   struct CadetPeer *prev_peer;
1438
1439   next_peer = get_next_hop (c);
1440   prev_peer = get_prev_hop (c);
1441
1442   LOG (GNUNET_ERROR_TYPE_DEBUG, "register neighbors for connection %s\n",
1443        GCC_2s (c));
1444   path_debug (c->path);
1445   LOG (GNUNET_ERROR_TYPE_DEBUG, "own pos %u\n", c->own_pos);
1446   LOG (GNUNET_ERROR_TYPE_DEBUG, "putting connection %s to next peer %p\n",
1447        GCC_2s (c), next_peer);
1448   LOG (GNUNET_ERROR_TYPE_DEBUG, "next peer %p %s\n", next_peer, GCP_2s (next_peer));
1449   LOG (GNUNET_ERROR_TYPE_DEBUG, "putting connection %s to prev peer %p\n",
1450        GCC_2s (c), prev_peer);
1451   LOG (GNUNET_ERROR_TYPE_DEBUG, "prev peer %p %s\n", prev_peer, GCP_2s (prev_peer));
1452
1453   if (GNUNET_NO == GCP_is_neighbor (next_peer)
1454       || GNUNET_NO == GCP_is_neighbor (prev_peer))
1455   {
1456     if (GCC_is_origin (c, GNUNET_YES))
1457       GNUNET_STATISTICS_update (stats, "# local bad paths", 1, GNUNET_NO);
1458     GNUNET_STATISTICS_update (stats, "# bad paths", 1, GNUNET_NO);
1459
1460     LOG (GNUNET_ERROR_TYPE_DEBUG, "  register neighbors failed\n");
1461     LOG (GNUNET_ERROR_TYPE_DEBUG, "  prev: %s, neighbor?: %d\n",
1462          GCP_2s (prev_peer), GCP_is_neighbor (prev_peer));
1463     LOG (GNUNET_ERROR_TYPE_DEBUG, "  next: %s, neighbor?: %d\n",
1464          GCP_2s (next_peer), GCP_is_neighbor (next_peer));
1465     return GNUNET_SYSERR;
1466   }
1467
1468   GCP_add_connection (next_peer, c);
1469   GCP_add_connection (prev_peer, c);
1470
1471   return GNUNET_OK;
1472 }
1473
1474
1475 /**
1476  * Remove the connection from the list of both neighbors.
1477  *
1478  * @param c Connection.
1479  */
1480 static void
1481 unregister_neighbors (struct CadetConnection *c)
1482 {
1483   struct CadetPeer *peer;
1484
1485   peer = get_next_hop (c);
1486   if (GNUNET_OK != GCP_remove_connection (peer, c))
1487   {
1488     GNUNET_assert (CADET_CONNECTION_NEW == c->state
1489                    || CADET_CONNECTION_DESTROYED <= c->state);
1490     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate: %u\n", c->state);
1491     if (NULL != c->t) GCT_debug (c->t, GNUNET_ERROR_TYPE_DEBUG);
1492   }
1493
1494   peer = get_prev_hop (c);
1495   if (GNUNET_OK != GCP_remove_connection (peer, c))
1496   {
1497     GNUNET_assert (CADET_CONNECTION_NEW == c->state
1498                    || CADET_CONNECTION_DESTROYED <= c->state);
1499     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate: %u\n", c->state);
1500     if (NULL != c->t) GCT_debug (c->t, GNUNET_ERROR_TYPE_DEBUG);
1501   }
1502 }
1503
1504
1505 /**
1506  * Bind the connection to the peer and the tunnel to that peer.
1507  *
1508  * If the peer has no tunnel, create one. Update tunnel and connection
1509  * data structres to reflect new status.
1510  *
1511  * @param c Connection.
1512  * @param peer Peer.
1513  */
1514 static void
1515 add_to_peer (struct CadetConnection *c, struct CadetPeer *peer)
1516 {
1517   GCP_add_tunnel (peer);
1518   c->t = GCP_get_tunnel (peer);
1519   GCT_add_connection (c->t, c);
1520 }
1521
1522
1523
1524 /**
1525  * Iterator to compare each connection's path with the path of a new connection.
1526  *
1527  * If the connection conincides, the c member of path is set to the connection
1528  * and the destroy flag of the connection is set.
1529  *
1530  * @param cls Closure (new path).
1531  * @param c Connection in the tunnel to check.
1532  */
1533 static void
1534 check_path (void *cls, struct CadetConnection *c)
1535 {
1536   struct CadetConnection *new_conn = cls;
1537   struct CadetPeerPath *path = new_conn->path;
1538
1539   LOG (GNUNET_ERROR_TYPE_DEBUG, "  checking %s, length %u\n",
1540        GCC_2s (c), c->path->length);
1541
1542   if (c != new_conn
1543       && c->destroy == GNUNET_NO
1544       && c->state != CADET_CONNECTION_BROKEN
1545       && c->state != CADET_CONNECTION_DESTROYED
1546       && c->path->length == path->length
1547       && 0 == memcmp (c->path->peers, path->peers,
1548                       sizeof (path->peers[0]) * path->length))
1549   {
1550     new_conn->destroy = GNUNET_YES;
1551     new_conn->path->c = c;
1552     LOG (GNUNET_ERROR_TYPE_DEBUG, "  MATCH!\n");
1553   }
1554 }
1555
1556 /**
1557  * Finds out if this path is already being used by and existing connection.
1558  *
1559  * Checks the tunnel towards the first peer in the path to see if it contains
1560  * any connection with the same path.
1561  *
1562  * If the existing connection is ready, it is kept.
1563  * Otherwise if the sender has a smaller ID that ours, we accept it (and
1564  * the peer will eventually reject our attempt).
1565  *
1566  * @param path Path to check.
1567  *
1568  * @return GNUNET_YES if the tunnel has a connection with the same path,
1569  *         GNUNET_NO otherwise.
1570  */
1571 static int
1572 does_connection_exist (struct CadetConnection *conn)
1573 {
1574   struct CadetPeer *p;
1575   struct CadetTunnel *t;
1576   struct CadetConnection *c;
1577
1578   p = GCP_get_short (conn->path->peers[0]);
1579   t = GCP_get_tunnel (p);
1580   if (NULL == t)
1581     return GNUNET_NO;
1582
1583   LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking for duplicates\n");
1584
1585   GCT_iterate_connections (t, &check_path, conn);
1586
1587   if (GNUNET_YES == conn->destroy)
1588   {
1589     c = conn->path->c;
1590     conn->destroy = GNUNET_NO;
1591     conn->path->c = conn;
1592     LOG (GNUNET_ERROR_TYPE_DEBUG, " found one\n");
1593     GCC_debug (c, GNUNET_ERROR_TYPE_DEBUG);
1594     if (CADET_CONNECTION_READY == c->state)
1595     {
1596       /* The other peer confirmed this connection,
1597        * they should not try to duplicate it. */
1598       GNUNET_break_op (0);
1599       return GNUNET_YES;
1600     }
1601
1602     if (GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (p)) > 0)
1603       return GNUNET_NO;
1604     else
1605       return GNUNET_YES;
1606   }
1607   else
1608     return GNUNET_NO;
1609 }
1610
1611
1612 /**
1613  * Log receipt of message on stderr (INFO level).
1614  *
1615  * @param message Message received.
1616  * @param peer Peer who sent the message.
1617  * @param hash Connection ID.
1618  */
1619 static void
1620 log_message (const struct GNUNET_MessageHeader *message,
1621              const struct GNUNET_PeerIdentity *peer,
1622              const struct GNUNET_CADET_Hash *hash)
1623 {
1624   LOG (GNUNET_ERROR_TYPE_INFO, "\n");
1625   LOG (GNUNET_ERROR_TYPE_INFO, "\n");
1626   LOG (GNUNET_ERROR_TYPE_INFO, "<-- %s on connection %s from %s\n",
1627        GC_m2s (ntohs (message->type)), GNUNET_h2s (GC_h2hc (hash)),
1628        GNUNET_i2s (peer));
1629 }
1630
1631 /******************************************************************************/
1632 /********************************    API    ***********************************/
1633 /******************************************************************************/
1634
1635 /**
1636  * Core handler for connection creation.
1637  *
1638  * @param cls Closure (unused).
1639  * @param peer Sender (neighbor).
1640  * @param message Message.
1641  *
1642  * @return GNUNET_OK to keep the connection open,
1643  *         GNUNET_SYSERR to close it (signal serious error)
1644  */
1645 int
1646 GCC_handle_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1647                    const struct GNUNET_MessageHeader *message)
1648 {
1649   struct GNUNET_CADET_ConnectionCreate *msg;
1650   struct GNUNET_PeerIdentity *id;
1651   struct GNUNET_CADET_Hash *cid;
1652   struct CadetPeerPath *path;
1653   struct CadetPeer *dest_peer;
1654   struct CadetPeer *orig_peer;
1655   struct CadetConnection *c;
1656   unsigned int own_pos;
1657   uint16_t size;
1658
1659   /* Check size */
1660   size = ntohs (message->size);
1661   if (size < sizeof (struct GNUNET_CADET_ConnectionCreate))
1662   {
1663     GNUNET_break_op (0);
1664     return GNUNET_OK;
1665   }
1666
1667   /* Calculate hops */
1668   size -= sizeof (struct GNUNET_CADET_ConnectionCreate);
1669   if (size % sizeof (struct GNUNET_PeerIdentity))
1670   {
1671     GNUNET_break_op (0);
1672     return GNUNET_OK;
1673   }
1674   size /= sizeof (struct GNUNET_PeerIdentity);
1675   if (1 > size)
1676   {
1677     GNUNET_break_op (0);
1678     return GNUNET_OK;
1679   }
1680   LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1681
1682   /* Get parameters */
1683   msg = (struct GNUNET_CADET_ConnectionCreate *) message;
1684   cid = &msg->cid;
1685   log_message (message, peer, cid);
1686   id = (struct GNUNET_PeerIdentity *) &msg[1];
1687   LOG (GNUNET_ERROR_TYPE_DEBUG, "    origin: %s\n", GNUNET_i2s (id));
1688
1689   /* Create connection */
1690   c = connection_get (cid);
1691   if (NULL == c)
1692   {
1693     path = path_build_from_peer_ids ((struct GNUNET_PeerIdentity *) &msg[1],
1694                                      size, myid, &own_pos);
1695     if (NULL == path)
1696       return GNUNET_OK;
1697
1698     if (0 == own_pos)
1699     {
1700       GNUNET_break_op (0);
1701       path_destroy (path);
1702       return GNUNET_OK;
1703     }
1704
1705     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1706     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1707     c = GCC_new (cid, NULL, path, own_pos);
1708     if (NULL == c)
1709     {
1710       if (path->length - 1 == own_pos)
1711       {
1712         /* If we are destination, why did the creation fail? */
1713         GNUNET_break (0);
1714         path_destroy (path);
1715         return GNUNET_OK;
1716       }
1717       send_broken_unknown (cid, &my_full_id,
1718                            GNUNET_PEER_resolve2 (path->peers[own_pos + 1]),
1719                            peer);
1720       path_destroy (path);
1721       return GNUNET_OK;
1722     }
1723     GCP_add_path_to_all (path, GNUNET_NO);
1724     connection_reset_timeout (c, GNUNET_YES);
1725   }
1726   else
1727   {
1728     path = path_duplicate (c->path);
1729   }
1730   if (CADET_CONNECTION_NEW == c->state)
1731     connection_change_state (c, CADET_CONNECTION_SENT);
1732
1733   /* Remember peers */
1734   dest_peer = GCP_get (&id[size - 1]);
1735   orig_peer = GCP_get (&id[0]);
1736
1737   /* Is it a connection to us? */
1738   if (c->own_pos == path->length - 1)
1739   {
1740     LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
1741     GCP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_YES);
1742
1743     add_to_peer (c, orig_peer);
1744     if (GNUNET_YES == does_connection_exist (c))
1745     {
1746       path_destroy (path);
1747       GCC_destroy (c);
1748       // FIXME use explicit duplicate
1749       send_broken_unknown (cid, &my_full_id, NULL, peer);
1750
1751       return GNUNET_OK;
1752     }
1753
1754     if (CADET_TUNNEL_NEW == GCT_get_cstate (c->t))
1755       GCT_change_cstate (c->t,  CADET_TUNNEL_WAITING);
1756
1757     send_connection_ack (c, GNUNET_NO);
1758     if (CADET_CONNECTION_SENT == c->state)
1759       connection_change_state (c, CADET_CONNECTION_ACK);
1760   }
1761   else
1762   {
1763     /* It's for somebody else! Retransmit. */
1764     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
1765     GCP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
1766     GCP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_NO);
1767     GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c,
1768                                                       GNUNET_YES, GNUNET_YES,
1769                                                       NULL, NULL));
1770   }
1771   path_destroy (path);
1772   return GNUNET_OK;
1773 }
1774
1775
1776 /**
1777  * Core handler for path confirmations.
1778  *
1779  * @param cls closure
1780  * @param message message
1781  * @param peer peer identity this notification is about
1782  *
1783  * @return GNUNET_OK to keep the connection open,
1784  *         GNUNET_SYSERR to close it (signal serious error)
1785  */
1786 int
1787 GCC_handle_confirm (void *cls, const struct GNUNET_PeerIdentity *peer,
1788                     const struct GNUNET_MessageHeader *message)
1789 {
1790   struct GNUNET_CADET_ConnectionACK *msg;
1791   struct CadetConnection *c;
1792   struct CadetPeerPath *p;
1793   struct CadetPeer *pi;
1794   enum CadetConnectionState oldstate;
1795   int fwd;
1796
1797   msg = (struct GNUNET_CADET_ConnectionACK *) message;
1798   log_message (message, peer, &msg->cid);
1799   c = connection_get (&msg->cid);
1800   if (NULL == c)
1801   {
1802     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1803                               1, GNUNET_NO);
1804     LOG (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
1805     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
1806     return GNUNET_OK;
1807   }
1808
1809   if (GNUNET_NO != c->destroy)
1810   {
1811     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection being destroyed\n");
1812     return GNUNET_OK;
1813   }
1814
1815   oldstate = c->state;
1816   LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n", GNUNET_i2s (peer));
1817   pi = GCP_get (peer);
1818   if (get_next_hop (c) == pi)
1819   {
1820     LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
1821     fwd = GNUNET_NO;
1822     if (CADET_CONNECTION_SENT == oldstate)
1823       connection_change_state (c, CADET_CONNECTION_ACK);
1824   }
1825   else if (get_prev_hop (c) == pi)
1826   {
1827     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FINAL ACK\n");
1828     fwd = GNUNET_YES;
1829     connection_change_state (c, CADET_CONNECTION_READY);
1830   }
1831   else
1832   {
1833     GNUNET_break_op (0);
1834     return GNUNET_OK;
1835   }
1836
1837   connection_reset_timeout (c, fwd);
1838
1839   /* Add path to peers? */
1840   p = c->path;
1841   if (NULL != p)
1842   {
1843     GCP_add_path_to_all (p, GNUNET_YES);
1844   }
1845   else
1846   {
1847     GNUNET_break (0);
1848   }
1849
1850   /* Message for us as creator? */
1851   if (GCC_is_origin (c, GNUNET_YES))
1852   {
1853     if (GNUNET_NO != fwd)
1854     {
1855       GNUNET_break_op (0);
1856       return GNUNET_OK;
1857     }
1858     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
1859
1860     /* If just created, cancel the short timeout and start a long one */
1861     if (CADET_CONNECTION_SENT == oldstate)
1862       connection_reset_timeout (c, GNUNET_YES);
1863
1864     /* Change connection state */
1865     connection_change_state (c, CADET_CONNECTION_READY);
1866     send_connection_ack (c, GNUNET_YES);
1867
1868     /* Change tunnel state, trigger KX */
1869     if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
1870       GCT_change_cstate (c->t, CADET_TUNNEL_READY);
1871
1872     return GNUNET_OK;
1873   }
1874
1875   /* Message for us as destination? */
1876   if (GCC_is_terminal (c, GNUNET_YES))
1877   {
1878     if (GNUNET_YES != fwd)
1879     {
1880       GNUNET_break_op (0);
1881       return GNUNET_OK;
1882     }
1883     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
1884
1885     /* If just created, cancel the short timeout and start a long one */
1886     if (CADET_CONNECTION_ACK == oldstate)
1887       connection_reset_timeout (c, GNUNET_NO);
1888
1889     /* Change tunnel state */
1890     if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
1891       GCT_change_cstate (c->t, CADET_TUNNEL_READY);
1892
1893     return GNUNET_OK;
1894   }
1895
1896   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1897   GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
1898                                                     GNUNET_YES, NULL, NULL));
1899   return GNUNET_OK;
1900 }
1901
1902
1903 /**
1904  * Core handler for notifications of broken connections.
1905  *
1906  * @param cls Closure (unused).
1907  * @param id Peer identity of sending neighbor.
1908  * @param message Message.
1909  *
1910  * @return GNUNET_OK to keep the connection open,
1911  *         GNUNET_SYSERR to close it (signal serious error)
1912  */
1913 int
1914 GCC_handle_broken (void* cls,
1915                    const struct GNUNET_PeerIdentity* id,
1916                    const struct GNUNET_MessageHeader* message)
1917 {
1918   struct GNUNET_CADET_ConnectionBroken *msg;
1919   struct CadetConnection *c;
1920   struct CadetTunnel *t;
1921   int pending;
1922   int fwd;
1923
1924   msg = (struct GNUNET_CADET_ConnectionBroken *) message;
1925   log_message (message, id, &msg->cid);
1926   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1927               GNUNET_i2s (&msg->peer1));
1928   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1929               GNUNET_i2s (&msg->peer2));
1930   c = connection_get (&msg->cid);
1931   if (NULL == c)
1932   {
1933     LOG (GNUNET_ERROR_TYPE_DEBUG, "  duplicate CONNECTION_BROKEN\n");
1934     return GNUNET_OK;
1935   }
1936
1937   t = c->t;
1938
1939   fwd = is_fwd (c, id);
1940   c->destroy = GNUNET_YES;
1941   if (GCC_is_terminal (c, fwd))
1942   {
1943     struct CadetPeer *endpoint;
1944
1945     if (NULL == t)
1946     {
1947       /* A terminal connection should not have 't' set to NULL. */
1948       GNUNET_break (0);
1949       GCC_debug (c, GNUNET_ERROR_TYPE_ERROR);
1950       return GNUNET_OK;
1951     }
1952     endpoint = GCP_get_short (c->path->peers[c->path->length - 1]);
1953     path_invalidate (c->path);
1954     GCP_notify_broken_link (endpoint, &msg->peer1, &msg->peer2);
1955
1956     c->state = CADET_CONNECTION_BROKEN;
1957     GCT_remove_connection (t, c);
1958     c->t = NULL;
1959
1960     pending = c->pending_messages;
1961     if (0 < pending)
1962       resend_messages_and_destroy (c, !fwd);
1963     else
1964       GCC_destroy (c);
1965   }
1966   else
1967   {
1968     GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
1969                                                       GNUNET_YES, NULL, NULL));
1970     connection_cancel_queues (c, !fwd);
1971   }
1972
1973   return GNUNET_OK;
1974 }
1975
1976
1977 /**
1978  * Core handler for tunnel destruction
1979  *
1980  * @param cls Closure (unused).
1981  * @param peer Peer identity of sending neighbor.
1982  * @param message Message.
1983  *
1984  * @return GNUNET_OK to keep the connection open,
1985  *         GNUNET_SYSERR to close it (signal serious error)
1986  */
1987 int
1988 GCC_handle_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
1989                     const struct GNUNET_MessageHeader *message)
1990 {
1991   struct GNUNET_CADET_ConnectionDestroy *msg;
1992   struct CadetConnection *c;
1993   int fwd;
1994
1995   msg = (struct GNUNET_CADET_ConnectionDestroy *) message;
1996   log_message (message, peer, &msg->cid);
1997   c = connection_get (&msg->cid);
1998   if (NULL == c)
1999   {
2000     /* Probably already got the message from another path,
2001      * destroyed the tunnel and retransmitted to children.
2002      * Safe to ignore.
2003      */
2004     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
2005                               1, GNUNET_NO);
2006     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection unknown: already destroyed?\n");
2007     return GNUNET_OK;
2008   }
2009   fwd = is_fwd (c, peer);
2010   if (GNUNET_SYSERR == fwd)
2011   {
2012     GNUNET_break_op (0); /* FIXME */
2013     return GNUNET_OK;
2014   }
2015   if (GNUNET_NO == GCC_is_terminal (c, fwd))
2016     GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
2017                                                       GNUNET_YES, NULL, NULL));
2018   else if (0 == c->pending_messages)
2019   {
2020     LOG (GNUNET_ERROR_TYPE_DEBUG, "  directly destroying connection!\n");
2021     GCC_destroy (c);
2022     return GNUNET_OK;
2023   }
2024   c->destroy = GNUNET_YES;
2025   c->state = CADET_CONNECTION_DESTROYED;
2026   if (NULL != c->t)
2027   {
2028     GCT_remove_connection (c->t, c);
2029     c->t = NULL;
2030   }
2031
2032   return GNUNET_OK;
2033 }
2034
2035 /**
2036  * Generic handler for cadet network encrypted traffic.
2037  *
2038  * @param peer Peer identity this notification is about.
2039  * @param msg Encrypted message.
2040  *
2041  * @return GNUNET_OK to keep the connection open,
2042  *         GNUNET_SYSERR to close it (signal serious error)
2043  */
2044 static int
2045 handle_cadet_encrypted (const struct GNUNET_PeerIdentity *peer,
2046                        const struct GNUNET_CADET_Encrypted *msg)
2047 {
2048   struct CadetConnection *c;
2049   struct CadetPeer *neighbor;
2050   struct CadetFlowControl *fc;
2051   GNUNET_PEER_Id peer_id;
2052   uint32_t pid;
2053   uint32_t ttl;
2054   size_t size;
2055   int fwd;
2056
2057   log_message (&msg->header, peer, &msg->cid);
2058
2059   /* Check size */
2060   size = ntohs (msg->header.size);
2061   if (size <
2062       sizeof (struct GNUNET_CADET_Encrypted) +
2063       sizeof (struct GNUNET_MessageHeader))
2064   {
2065     GNUNET_break_op (0);
2066     return GNUNET_OK;
2067   }
2068
2069   /* Check connection */
2070   c = connection_get (&msg->cid);
2071   if (NULL == c)
2072   {
2073     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
2074     LOG (GNUNET_ERROR_TYPE_DEBUG, "enc on unknown connection %s\n",
2075          GNUNET_h2s (GC_h2hc (&msg->cid)));
2076     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
2077     return GNUNET_OK;
2078   }
2079
2080   LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s\n", GCC_2s (c));
2081
2082   /* Check if origin is as expected */
2083   neighbor = get_prev_hop (c);
2084   peer_id = GNUNET_PEER_search (peer);
2085   if (peer_id == GCP_get_short_id (neighbor))
2086   {
2087     fwd = GNUNET_YES;
2088   }
2089   else
2090   {
2091     neighbor = get_next_hop (c);
2092     if (peer_id == GCP_get_short_id (neighbor))
2093     {
2094       fwd = GNUNET_NO;
2095     }
2096     else
2097     {
2098       /* Unexpected peer sending traffic on a connection. */
2099       GNUNET_break_op (0);
2100       return GNUNET_OK;
2101     }
2102   }
2103
2104   /* Check PID */
2105   fc = fwd ? &c->bck_fc : &c->fwd_fc;
2106   pid = ntohl (msg->pid);
2107   LOG (GNUNET_ERROR_TYPE_DEBUG, " PID %u (expected %u+)\n",
2108        pid, fc->last_pid_recv + 1);
2109   if (GC_is_pid_bigger (pid, fc->last_ack_sent))
2110   {
2111     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
2112     GNUNET_break_op (0);
2113     LOG (GNUNET_ERROR_TYPE_WARNING,
2114          "Received PID %u, (prev %u), ACK %u\n",
2115          pid, fc->last_pid_recv, fc->last_ack_sent);
2116     return GNUNET_OK;
2117   }
2118   if (GNUNET_NO == GC_is_pid_bigger (pid, fc->last_pid_recv))
2119   {
2120     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
2121     LOG (GNUNET_ERROR_TYPE_WARNING,
2122                 " PID %u not expected (%u+), dropping!\n",
2123                 pid, fc->last_pid_recv + 1);
2124     return GNUNET_OK;
2125   }
2126   if (CADET_CONNECTION_SENT == c->state || CADET_CONNECTION_ACK == c->state)
2127     connection_change_state (c, CADET_CONNECTION_READY);
2128   connection_reset_timeout (c, fwd);
2129   fc->last_pid_recv = pid;
2130
2131   /* Is this message for us? */
2132   if (GCC_is_terminal (c, fwd))
2133   {
2134     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
2135     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
2136
2137     if (NULL == c->t)
2138     {
2139       GNUNET_break (GNUNET_NO != c->destroy);
2140       return GNUNET_OK;
2141     }
2142     fc->last_pid_recv = pid;
2143     GCT_handle_encrypted (c->t, msg);
2144     GCC_send_ack (c, fwd, GNUNET_NO);
2145     return GNUNET_OK;
2146   }
2147
2148   /* Message not for us: forward to next hop */
2149   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2150   ttl = ntohl (msg->ttl);
2151   LOG (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
2152   if (ttl == 0)
2153   {
2154     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
2155     LOG (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
2156     GCC_send_ack (c, fwd, GNUNET_NO);
2157     return GNUNET_OK;
2158   }
2159
2160   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
2161   GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
2162                                                     GNUNET_NO, NULL, NULL));
2163
2164   return GNUNET_OK;
2165 }
2166
2167 /**
2168  * Generic handler for cadet network encrypted traffic.
2169  *
2170  * @param peer Peer identity this notification is about.
2171  * @param msg Encrypted message.
2172  *
2173  * @return GNUNET_OK to keep the connection open,
2174  *         GNUNET_SYSERR to close it (signal serious error)
2175  */
2176 static int
2177 handle_cadet_kx (const struct GNUNET_PeerIdentity *peer,
2178                 const struct GNUNET_CADET_KX *msg)
2179 {
2180   struct CadetConnection *c;
2181   struct CadetPeer *neighbor;
2182   GNUNET_PEER_Id peer_id;
2183   size_t size;
2184   int fwd;
2185
2186   log_message (&msg->header, peer, &msg->cid);
2187
2188   /* Check size */
2189   size = ntohs (msg->header.size);
2190   if (size <
2191       sizeof (struct GNUNET_CADET_KX) +
2192       sizeof (struct GNUNET_MessageHeader))
2193   {
2194     GNUNET_break_op (0);
2195     return GNUNET_OK;
2196   }
2197
2198   /* Check connection */
2199   c = connection_get (&msg->cid);
2200   if (NULL == c)
2201   {
2202     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
2203     LOG (GNUNET_ERROR_TYPE_DEBUG, "kx on unknown connection %s\n",
2204          GNUNET_h2s (GC_h2hc (&msg->cid)));
2205     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
2206     return GNUNET_OK;
2207   }
2208   LOG (GNUNET_ERROR_TYPE_DEBUG, " on connection %s\n", GCC_2s (c));
2209
2210   /* Check if origin is as expected */
2211   neighbor = get_prev_hop (c);
2212   peer_id = GNUNET_PEER_search (peer);
2213   if (peer_id == GCP_get_short_id (neighbor))
2214   {
2215     fwd = GNUNET_YES;
2216   }
2217   else
2218   {
2219     neighbor = get_next_hop (c);
2220     if (peer_id == GCP_get_short_id (neighbor))
2221     {
2222       fwd = GNUNET_NO;
2223     }
2224     else
2225     {
2226       /* Unexpected peer sending traffic on a connection. */
2227       GNUNET_break_op (0);
2228       return GNUNET_OK;
2229     }
2230   }
2231
2232   /* Count as connection confirmation. */
2233   if (CADET_CONNECTION_SENT == c->state || CADET_CONNECTION_ACK == c->state)
2234   {
2235     connection_change_state (c, CADET_CONNECTION_READY);
2236     if (NULL != c->t)
2237     {
2238       if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
2239         GCT_change_cstate (c->t, CADET_TUNNEL_READY);
2240     }
2241   }
2242   connection_reset_timeout (c, fwd);
2243
2244   /* Is this message for us? */
2245   if (GCC_is_terminal (c, fwd))
2246   {
2247     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
2248     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
2249     if (NULL == c->t)
2250     {
2251       GNUNET_break (0);
2252       return GNUNET_OK;
2253     }
2254     GCT_handle_kx (c->t, &msg[1].header);
2255     return GNUNET_OK;
2256   }
2257
2258   /* Message not for us: forward to next hop */
2259   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2260   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
2261   GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
2262                                                     GNUNET_NO, NULL, NULL));
2263
2264   return GNUNET_OK;
2265 }
2266
2267
2268 /**
2269  * Core handler for encrypted cadet network traffic (channel mgmt, data).
2270  *
2271  * @param cls Closure (unused).
2272  * @param message Message received.
2273  * @param peer Peer who sent the message.
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_encrypted (void *cls, const struct GNUNET_PeerIdentity *peer,
2280                       const struct GNUNET_MessageHeader *message)
2281 {
2282   return handle_cadet_encrypted (peer,
2283                                 (struct GNUNET_CADET_Encrypted *)message);
2284 }
2285
2286
2287 /**
2288  * Core handler for key exchange traffic (ephemeral key, ping, pong).
2289  *
2290  * @param cls Closure (unused).
2291  * @param message Message received.
2292  * @param peer Peer who sent the message.
2293  *
2294  * @return GNUNET_OK to keep the connection open,
2295  *         GNUNET_SYSERR to close it (signal serious error)
2296  */
2297 int
2298 GCC_handle_kx (void *cls, const struct GNUNET_PeerIdentity *peer,
2299                const struct GNUNET_MessageHeader *message)
2300 {
2301   return handle_cadet_kx (peer,
2302                          (struct GNUNET_CADET_KX *) message);
2303 }
2304
2305
2306 /**
2307  * Core handler for cadet network traffic point-to-point acks.
2308  *
2309  * @param cls closure
2310  * @param message message
2311  * @param peer peer identity this notification is about
2312  *
2313  * @return GNUNET_OK to keep the connection open,
2314  *         GNUNET_SYSERR to close it (signal serious error)
2315  */
2316 int
2317 GCC_handle_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2318                 const struct GNUNET_MessageHeader *message)
2319 {
2320   struct GNUNET_CADET_ACK *msg;
2321   struct CadetConnection *c;
2322   struct CadetFlowControl *fc;
2323   GNUNET_PEER_Id id;
2324   uint32_t ack;
2325   int fwd;
2326
2327   msg = (struct GNUNET_CADET_ACK *) message;
2328   log_message (message, peer, &msg->cid);
2329   c = connection_get (&msg->cid);
2330   if (NULL == c)
2331   {
2332     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
2333                               GNUNET_NO);
2334     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
2335     return GNUNET_OK;
2336   }
2337
2338   /* Is this a forward or backward ACK? */
2339   id = GNUNET_PEER_search (peer);
2340   if (GCP_get_short_id (get_next_hop (c)) == id)
2341   {
2342     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
2343     fc = &c->fwd_fc;
2344     fwd = GNUNET_YES;
2345   }
2346   else if (GCP_get_short_id (get_prev_hop (c)) == id)
2347   {
2348     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
2349     fc = &c->bck_fc;
2350     fwd = GNUNET_NO;
2351   }
2352   else
2353   {
2354     GNUNET_break_op (0);
2355     return GNUNET_OK;
2356   }
2357
2358   ack = ntohl (msg->ack);
2359   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
2360               ack, fc->last_ack_recv);
2361   if (GC_is_pid_bigger (ack, fc->last_ack_recv))
2362     fc->last_ack_recv = ack;
2363
2364   /* Cancel polling if the ACK is big enough. */
2365   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
2366       GC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2367   {
2368     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
2369     GNUNET_SCHEDULER_cancel (fc->poll_task);
2370     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2371     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
2372   }
2373
2374   connection_unlock_queue (c, fwd);
2375
2376   return GNUNET_OK;
2377 }
2378
2379
2380 /**
2381  * Core handler for cadet network traffic point-to-point ack polls.
2382  *
2383  * @param cls closure
2384  * @param message message
2385  * @param peer peer identity this notification is about
2386  *
2387  * @return GNUNET_OK to keep the connection open,
2388  *         GNUNET_SYSERR to close it (signal serious error)
2389  */
2390 int
2391 GCC_handle_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
2392                  const struct GNUNET_MessageHeader *message)
2393 {
2394   struct GNUNET_CADET_Poll *msg;
2395   struct CadetConnection *c;
2396   struct CadetFlowControl *fc;
2397   GNUNET_PEER_Id id;
2398   uint32_t pid;
2399   int fwd;
2400
2401   msg = (struct GNUNET_CADET_Poll *) message;
2402   log_message (message, peer, &msg->cid);
2403   c = connection_get (&msg->cid);
2404   if (NULL == c)
2405   {
2406     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
2407                               GNUNET_NO);
2408     LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL message on unknown connection %s!\n",
2409          GNUNET_h2s (GC_h2hc (&msg->cid)));
2410     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
2411     return GNUNET_OK;
2412   }
2413
2414   /* Is this a forward or backward ACK?
2415    * Note: a poll should never be needed in a loopback case,
2416    * since there is no possiblility of packet loss there, so
2417    * this way of discerining FWD/BCK should not be a problem.
2418    */
2419   id = GNUNET_PEER_search (peer);
2420   if (GCP_get_short_id (get_next_hop (c)) == id)
2421   {
2422     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
2423     fc = &c->fwd_fc;
2424   }
2425   else if (GCP_get_short_id (get_prev_hop (c)) == id)
2426   {
2427     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
2428     fc = &c->bck_fc;
2429   }
2430   else
2431   {
2432     GNUNET_break_op (0);
2433     return GNUNET_OK;
2434   }
2435
2436   pid = ntohl (msg->pid);
2437   LOG (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n", pid, fc->last_pid_recv);
2438   fc->last_pid_recv = pid;
2439   fwd = fc == &c->bck_fc;
2440   GCC_send_ack (c, fwd, GNUNET_YES);
2441
2442   return GNUNET_OK;
2443 }
2444
2445
2446 /**
2447  * Send an ACK on the appropriate connection/channel, depending on
2448  * the direction and the position of the peer.
2449  *
2450  * @param c Which connection to send the hop-by-hop ACK.
2451  * @param fwd Is this a fwd ACK? (will go dest->root).
2452  * @param force Send the ACK even if suboptimal (e.g. requested by POLL).
2453  */
2454 void
2455 GCC_send_ack (struct CadetConnection *c, int fwd, int force)
2456 {
2457   unsigned int buffer;
2458
2459   LOG (GNUNET_ERROR_TYPE_DEBUG,
2460        "GMC send %s ACK on %s\n",
2461        GC_f2s (fwd), GCC_2s (c));
2462
2463   if (NULL == c)
2464   {
2465     GNUNET_break (0);
2466     return;
2467   }
2468
2469   if (GNUNET_NO != c->destroy)
2470   {
2471     LOG (GNUNET_ERROR_TYPE_DEBUG, "  being destroyed, why bother...\n");
2472     return;
2473   }
2474
2475   /* Get available buffer space */
2476   if (GCC_is_terminal (c, fwd))
2477   {
2478     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from all channels\n");
2479     buffer = GCT_get_channels_buffer (c->t);
2480   }
2481   else
2482   {
2483     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
2484     buffer = GCC_get_buffer (c, fwd);
2485   }
2486   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
2487   if (0 == buffer && GNUNET_NO == force)
2488     return;
2489
2490   /* Send available buffer space */
2491   if (GCC_is_origin (c, fwd))
2492   {
2493     GNUNET_assert (NULL != c->t);
2494     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channels...\n");
2495     GCT_unchoke_channels (c->t);
2496   }
2497   else
2498   {
2499     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
2500     send_ack (c, buffer, fwd, force);
2501   }
2502 }
2503
2504
2505 /**
2506  * Initialize the connections subsystem
2507  *
2508  * @param c Configuration handle.
2509  */
2510 void
2511 GCC_init (const struct GNUNET_CONFIGURATION_Handle *c)
2512 {
2513   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2514   if (GNUNET_OK !=
2515       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_MSGS_QUEUE",
2516                                              &max_msgs_queue))
2517   {
2518     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2519                                "CADET", "MAX_MSGS_QUEUE", "MISSING");
2520     GNUNET_SCHEDULER_shutdown ();
2521     return;
2522   }
2523
2524   if (GNUNET_OK !=
2525       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_CONNECTIONS",
2526                                              &max_connections))
2527   {
2528     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2529                                "CADET", "MAX_CONNECTIONS", "MISSING");
2530     GNUNET_SCHEDULER_shutdown ();
2531     return;
2532   }
2533
2534   if (GNUNET_OK !=
2535       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REFRESH_CONNECTION_TIME",
2536                                            &refresh_connection_time))
2537   {
2538     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2539                                "CADET", "REFRESH_CONNECTION_TIME", "MISSING");
2540     GNUNET_SCHEDULER_shutdown ();
2541     return;
2542   }
2543   create_connection_time = GNUNET_TIME_UNIT_SECONDS;
2544   connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO);
2545 }
2546
2547
2548 /**
2549  * Destroy each connection on shutdown.
2550  *
2551  * @param cls Closure (unused).
2552  * @param key Current key code (CID, unused).
2553  * @param value Value in the hash map (connection)
2554  *
2555  * @return #GNUNET_YES, because we should continue to iterate,
2556  */
2557 static int
2558 shutdown_iterator (void *cls,
2559                    const struct GNUNET_HashCode *key,
2560                    void *value)
2561 {
2562   struct CadetConnection *c = value;
2563
2564   GCC_destroy (c);
2565   return GNUNET_YES;
2566 }
2567
2568
2569 /**
2570  * Shut down the connections subsystem.
2571  */
2572 void
2573 GCC_shutdown (void)
2574 {
2575   GNUNET_CONTAINER_multihashmap_iterate (connections, &shutdown_iterator, NULL);
2576   GNUNET_CONTAINER_multihashmap_destroy (connections);
2577   connections = NULL;
2578 }
2579
2580
2581 /**
2582  * Create a connection.
2583  *
2584  * @param cid Connection ID (either created locally or imposed remotely).
2585  * @param t Tunnel this connection belongs to (or NULL);
2586  * @param path Path this connection has to use (copy is made).
2587  * @param own_pos Own position in the @c path path.
2588  *
2589  * @return Newly created connection, NULL in case of error (own id not in path).
2590  */
2591 struct CadetConnection *
2592 GCC_new (const struct GNUNET_CADET_Hash *cid,
2593          struct CadetTunnel *t,
2594          struct CadetPeerPath *path,
2595          unsigned int own_pos)
2596 {
2597   struct CadetConnection *c;
2598   struct CadetPeerPath *p;
2599
2600   p = path_duplicate (path);
2601   c = GNUNET_new (struct CadetConnection);
2602   c->id = *cid;
2603   GNUNET_assert (GNUNET_OK ==
2604                  GNUNET_CONTAINER_multihashmap_put (connections,
2605                                                     GCC_get_h (c), c,
2606                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2607   fc_init (&c->fwd_fc);
2608   fc_init (&c->bck_fc);
2609   c->fwd_fc.c = c;
2610   c->bck_fc.c = c;
2611
2612   c->t = t;
2613   GNUNET_assert (own_pos <= p->length - 1);
2614   c->own_pos = own_pos;
2615   c->path = p;
2616   p->c = c;
2617
2618   if (GNUNET_OK != register_neighbors (c))
2619   {
2620     if (0 == own_pos)
2621     {
2622       path_invalidate (c->path);
2623       c->t = NULL;
2624       c->path = NULL;
2625     }
2626     GCC_destroy (c);
2627     return NULL;
2628   }
2629   LOG (GNUNET_ERROR_TYPE_INFO, "New connection %s\n", GCC_2s (c));
2630   return c;
2631 }
2632
2633
2634 void
2635 GCC_destroy (struct CadetConnection *c)
2636 {
2637   if (NULL == c)
2638   {
2639     GNUNET_break (0);
2640     return;
2641   }
2642
2643   if (2 == c->destroy) /* cancel queues -> GCP_queue_cancel -> q_destroy -> */
2644     return;            /* -> message_sent -> GCC_destroy. Don't loop. */
2645   c->destroy = 2;
2646
2647   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s\n", GCC_2s (c));
2648   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc's f: %p, b: %p\n",
2649        &c->fwd_fc, &c->bck_fc);
2650   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc tasks f: %u, b: %u\n",
2651        c->fwd_fc.poll_task, c->bck_fc.poll_task);
2652
2653   /* Cancel all traffic */
2654   if (NULL != c->path)
2655   {
2656     connection_cancel_queues (c, GNUNET_YES);
2657     connection_cancel_queues (c, GNUNET_NO);
2658     unregister_neighbors (c);
2659   }
2660
2661   /* Cancel maintainance task (keepalive/timeout) */
2662   if (NULL != c->fwd_fc.poll_msg)
2663   {
2664     GCC_cancel (c->fwd_fc.poll_msg);
2665     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL msg FWD canceled\n");
2666   }
2667   if (NULL != c->bck_fc.poll_msg)
2668   {
2669     GCC_cancel (c->bck_fc.poll_msg);
2670     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL msg BCK canceled\n");
2671   }
2672
2673   /* Delete from tunnel */
2674   if (NULL != c->t)
2675     GCT_remove_connection (c->t, c);
2676
2677   if (GNUNET_NO == GCC_is_origin (c, GNUNET_YES) && NULL != c->path)
2678     path_destroy (c->path);
2679   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
2680     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
2681   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
2682     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
2683   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_fc.poll_task)
2684   {
2685     GNUNET_SCHEDULER_cancel (c->fwd_fc.poll_task);
2686     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL FWD canceled\n");
2687   }
2688   if (GNUNET_SCHEDULER_NO_TASK != c->bck_fc.poll_task)
2689   {
2690     GNUNET_SCHEDULER_cancel (c->bck_fc.poll_task);
2691     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL BCK canceled\n");
2692   }
2693
2694   GNUNET_break (GNUNET_YES ==
2695                 GNUNET_CONTAINER_multihashmap_remove (connections,
2696                                                       GCC_get_h (c), c));
2697
2698   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
2699   GNUNET_free (c);
2700 }
2701
2702 /**
2703  * Get the connection ID.
2704  *
2705  * @param c Connection to get the ID from.
2706  *
2707  * @return ID of the connection.
2708  */
2709 const struct GNUNET_CADET_Hash *
2710 GCC_get_id (const struct CadetConnection *c)
2711 {
2712   return &c->id;
2713 }
2714
2715
2716 /**
2717  * Get the connection ID.
2718  *
2719  * @param c Connection to get the ID from.
2720  *
2721  * @return ID of the connection.
2722  */
2723 const struct GNUNET_HashCode *
2724 GCC_get_h (const struct CadetConnection *c)
2725 {
2726   return GC_h2hc (&c->id);
2727 }
2728
2729
2730 /**
2731  * Get the connection path.
2732  *
2733  * @param c Connection to get the path from.
2734  *
2735  * @return path used by the connection.
2736  */
2737 const struct CadetPeerPath *
2738 GCC_get_path (const struct CadetConnection *c)
2739 {
2740   if (GNUNET_NO == c->destroy)
2741     return c->path;
2742   return NULL;
2743 }
2744
2745
2746 /**
2747  * Get the connection state.
2748  *
2749  * @param c Connection to get the state from.
2750  *
2751  * @return state of the connection.
2752  */
2753 enum CadetConnectionState
2754 GCC_get_state (const struct CadetConnection *c)
2755 {
2756   return c->state;
2757 }
2758
2759 /**
2760  * Get the connection tunnel.
2761  *
2762  * @param c Connection to get the tunnel from.
2763  *
2764  * @return tunnel of the connection.
2765  */
2766 struct CadetTunnel *
2767 GCC_get_tunnel (const struct CadetConnection *c)
2768 {
2769   return c->t;
2770 }
2771
2772
2773 /**
2774  * Get free buffer space in a connection.
2775  *
2776  * @param c Connection.
2777  * @param fwd Is query about FWD traffic?
2778  *
2779  * @return Free buffer space [0 - max_msgs_queue/max_connections]
2780  */
2781 unsigned int
2782 GCC_get_buffer (struct CadetConnection *c, int fwd)
2783 {
2784   struct CadetFlowControl *fc;
2785
2786   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2787
2788   return (fc->queue_max - fc->queue_n);
2789 }
2790
2791 /**
2792  * Get how many messages have we allowed to send to us from a direction.
2793  *
2794  * @param c Connection.
2795  * @param fwd Are we asking about traffic from FWD (BCK messages)?
2796  *
2797  * @return last_ack_sent - last_pid_recv
2798  */
2799 unsigned int
2800 GCC_get_allowed (struct CadetConnection *c, int fwd)
2801 {
2802   struct CadetFlowControl *fc;
2803
2804   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2805   if (CADET_CONNECTION_READY != c->state
2806       || GC_is_pid_bigger (fc->last_pid_recv, fc->last_ack_sent))
2807   {
2808     return 0;
2809   }
2810   return (fc->last_ack_sent - fc->last_pid_recv);
2811 }
2812
2813 /**
2814  * Get messages queued in a connection.
2815  *
2816  * @param c Connection.
2817  * @param fwd Is query about FWD traffic?
2818  *
2819  * @return Number of messages queued.
2820  */
2821 unsigned int
2822 GCC_get_qn (struct CadetConnection *c, int fwd)
2823 {
2824   struct CadetFlowControl *fc;
2825
2826   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2827
2828   return fc->queue_n;
2829 }
2830
2831
2832 /**
2833  * Get next PID to use.
2834  *
2835  * @param c Connection.
2836  * @param fwd Is query about FWD traffic?
2837  *
2838  * @return Last PID used + 1.
2839  */
2840 unsigned int
2841 GCC_get_pid (struct CadetConnection *c, int fwd)
2842 {
2843   struct CadetFlowControl *fc;
2844
2845   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2846
2847   return fc->last_pid_sent + 1;
2848 }
2849
2850
2851 /**
2852  * Allow the connection to advertise a buffer of the given size.
2853  *
2854  * The connection will send an @c fwd ACK message (so: in direction !fwd)
2855  * allowing up to last_pid_recv + buffer.
2856  *
2857  * @param c Connection.
2858  * @param buffer How many more messages the connection can accept.
2859  * @param fwd Is this about FWD traffic? (The ack will go dest->root).
2860  */
2861 void
2862 GCC_allow (struct CadetConnection *c, unsigned int buffer, int fwd)
2863 {
2864   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowing %s %u messages %s\n",
2865        GCC_2s (c), buffer, GC_f2s (fwd));
2866   send_ack (c, buffer, fwd, GNUNET_NO);
2867 }
2868
2869
2870 /**
2871  * Notify other peers on a connection of a broken link. Mark connections
2872  * to destroy after all traffic has been sent.
2873  *
2874  * @param c Connection on which there has been a disconnection.
2875  * @param peer Peer that disconnected.
2876  */
2877 void
2878 GCC_notify_broken (struct CadetConnection *c,
2879                    struct CadetPeer *peer)
2880 {
2881   int fwd;
2882
2883   LOG (GNUNET_ERROR_TYPE_DEBUG,
2884        " notify broken on %s due to %s disconnect\n",
2885        GCC_2s (c), GCP_2s (peer));
2886
2887   fwd = peer == get_prev_hop (c);
2888
2889   if (GNUNET_YES == GCC_is_terminal (c, fwd))
2890   {
2891     /* Local shutdown, no one to notify about this. */
2892     GCC_destroy (c);
2893     return;
2894   }
2895   if (GNUNET_NO == c->destroy)
2896     send_broken (c, &my_full_id, GCP_get_id (peer), fwd);
2897
2898   /* Connection will have at least one pending message
2899    * (the one we just scheduled), so no point in checking whether to
2900    * destroy immediately. */
2901   c->destroy = GNUNET_YES;
2902   c->state = CADET_CONNECTION_DESTROYED;
2903
2904   /**
2905    * Cancel all queues, if no message is left, connection will be destroyed.
2906    */
2907   connection_cancel_queues (c, !fwd);
2908
2909   return;
2910 }
2911
2912
2913 /**
2914  * Is this peer the first one on the connection?
2915  *
2916  * @param c Connection.
2917  * @param fwd Is this about fwd traffic?
2918  *
2919  * @return #GNUNET_YES if origin, #GNUNET_NO if relay/terminal.
2920  */
2921 int
2922 GCC_is_origin (struct CadetConnection *c, int fwd)
2923 {
2924   if (!fwd && c->path->length - 1 == c->own_pos )
2925     return GNUNET_YES;
2926   if (fwd && 0 == c->own_pos)
2927     return GNUNET_YES;
2928   return GNUNET_NO;
2929 }
2930
2931
2932 /**
2933  * Is this peer the last one on the connection?
2934  *
2935  * @param c Connection.
2936  * @param fwd Is this about fwd traffic?
2937  *            Note that the ROOT is the terminal for BCK traffic!
2938  *
2939  * @return #GNUNET_YES if terminal, #GNUNET_NO if relay/origin.
2940  */
2941 int
2942 GCC_is_terminal (struct CadetConnection *c, int fwd)
2943 {
2944   return GCC_is_origin (c, !fwd);
2945 }
2946
2947
2948 /**
2949  * See if we are allowed to send by the next hop in the given direction.
2950  *
2951  * @param c Connection.
2952  * @param fwd Is this about fwd traffic?
2953  *
2954  * @return #GNUNET_YES in case it's OK to send.
2955  */
2956 int
2957 GCC_is_sendable (struct CadetConnection *c, int fwd)
2958 {
2959   struct CadetFlowControl *fc;
2960
2961   LOG (GNUNET_ERROR_TYPE_DEBUG, " checking sendability of %s traffic on %s\n",
2962        GC_f2s (fwd), GCC_2s (c));
2963   if (NULL == c)
2964   {
2965     GNUNET_break (0);
2966     return GNUNET_YES;
2967   }
2968   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2969   LOG (GNUNET_ERROR_TYPE_DEBUG,
2970        " last ack recv: %u, last pid sent: %u\n",
2971        fc->last_ack_recv, fc->last_pid_sent);
2972   if (GC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2973   {
2974     LOG (GNUNET_ERROR_TYPE_DEBUG, " sendable\n");
2975     return GNUNET_YES;
2976   }
2977   LOG (GNUNET_ERROR_TYPE_DEBUG, " not sendable\n");
2978   return GNUNET_NO;
2979 }
2980
2981
2982 /**
2983  * Check if this connection is a direct one (never trim a direct connection).
2984  *
2985  * @param c Connection.
2986  *
2987  * @return #GNUNET_YES in case it's a direct connection, #GNUNET_NO otherwise.
2988  */
2989 int
2990 GCC_is_direct (struct CadetConnection *c)
2991 {
2992   return (c->path->length == 2) ? GNUNET_YES : GNUNET_NO;
2993 }
2994
2995 /**
2996  * Sends an already built message on a connection, properly registering
2997  * all used resources.
2998  *
2999  * @param message Message to send. Function makes a copy of it.
3000  *                If message is not hop-by-hop, decrements TTL of copy.
3001  * @param payload_type Type of payload, in case the message is encrypted.
3002  * @param c Connection on which this message is transmitted.
3003  * @param fwd Is this a fwd message?
3004  * @param force Force the connection to accept the message (buffer overfill).
3005  * @param cont Continuation called once message is sent. Can be NULL.
3006  * @param cont_cls Closure for @c cont.
3007  *
3008  * @return Handle to cancel the message before it's sent.
3009  *         NULL on error or if @c cont is NULL.
3010  *         Invalid on @c cont call.
3011  */
3012 struct CadetConnectionQueue *
3013 GCC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
3014                            uint16_t payload_type, uint32_t payload_id,
3015                            struct CadetConnection *c, int fwd, int force,
3016                            GCC_sent cont, void *cont_cls)
3017 {
3018   struct CadetFlowControl *fc;
3019   struct CadetConnectionQueue *q;
3020   void *data;
3021   size_t size;
3022   uint16_t type;
3023   int droppable;
3024
3025   size = ntohs (message->size);
3026   data = GNUNET_malloc (size);
3027   memcpy (data, message, size);
3028   type = ntohs (message->type);
3029   LOG (GNUNET_ERROR_TYPE_INFO, "--> %s (%s %9u) on connection %s (%u bytes)\n",
3030        GC_m2s (type), GC_m2s (payload_type), payload_id, GCC_2s (c), size);
3031
3032   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3033   droppable = GNUNET_NO == force;
3034   switch (type)
3035   {
3036     struct GNUNET_CADET_Encrypted *emsg;
3037     struct GNUNET_CADET_KX        *kmsg;
3038     struct GNUNET_CADET_ACK       *amsg;
3039     struct GNUNET_CADET_Poll      *pmsg;
3040     struct GNUNET_CADET_ConnectionDestroy *dmsg;
3041     struct GNUNET_CADET_ConnectionBroken  *bmsg;
3042     uint32_t ttl;
3043
3044     case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
3045       emsg = (struct GNUNET_CADET_Encrypted *) data;
3046       ttl = ntohl (emsg->ttl);
3047       if (0 == ttl)
3048       {
3049         GNUNET_break_op (0);
3050         GNUNET_free (data);
3051         return NULL;
3052       }
3053       emsg->cid = c->id;
3054       emsg->ttl = htonl (ttl - 1);
3055       emsg->pid = htonl (0);
3056       LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
3057       LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid sent %u\n", fc->last_pid_sent);
3058       LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack recv %u\n", fc->last_ack_recv);
3059       if (GNUNET_YES == droppable)
3060       {
3061         fc->queue_n++;
3062       }
3063       else
3064       {
3065         LOG (GNUNET_ERROR_TYPE_DEBUG, "  not droppable, Q_N stays the same\n");
3066       }
3067       if (GC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
3068       {
3069         GCC_start_poll (c, fwd);
3070       }
3071       break;
3072
3073     case GNUNET_MESSAGE_TYPE_CADET_KX:
3074       kmsg = (struct GNUNET_CADET_KX *) data;
3075       kmsg->cid = c->id;
3076       break;
3077
3078     case GNUNET_MESSAGE_TYPE_CADET_ACK:
3079       amsg = (struct GNUNET_CADET_ACK *) data;
3080       amsg->cid = c->id;
3081       LOG (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
3082       droppable = GNUNET_NO;
3083       break;
3084
3085     case GNUNET_MESSAGE_TYPE_CADET_POLL:
3086       pmsg = (struct GNUNET_CADET_Poll *) data;
3087       pmsg->cid = c->id;
3088       LOG (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
3089       droppable = GNUNET_NO;
3090       break;
3091
3092     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
3093       dmsg = (struct GNUNET_CADET_ConnectionDestroy *) data;
3094       dmsg->cid = c->id;
3095       break;
3096
3097     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
3098       bmsg = (struct GNUNET_CADET_ConnectionBroken *) data;
3099       bmsg->cid = c->id;
3100       break;
3101
3102     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
3103     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
3104       break;
3105
3106     default:
3107       GNUNET_break (0);
3108       GNUNET_free (data);
3109       return NULL;
3110   }
3111
3112   if (fc->queue_n > fc->queue_max && droppable)
3113   {
3114     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
3115                               1, GNUNET_NO);
3116     GNUNET_break (0);
3117     LOG (GNUNET_ERROR_TYPE_DEBUG, "queue full: %u/%u\n",
3118          fc->queue_n, fc->queue_max);
3119     if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
3120     {
3121       fc->queue_n--;
3122     }
3123     GNUNET_free (data);
3124     return NULL; /* Drop this message */
3125   }
3126
3127   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %s %u\n",
3128        GCC_2s (c), c->pending_messages);
3129   c->pending_messages++;
3130
3131   q = GNUNET_new (struct CadetConnectionQueue);
3132   q->forced = !droppable;
3133   q->q = GCP_queue_add (get_hop (c, fwd), data, type, payload_type, payload_id,
3134                         size, c, fwd, &conn_message_sent, q);
3135   if (NULL == q->q)
3136   {
3137     LOG (GNUNET_ERROR_TYPE_DEBUG, "dropping msg on %s, NULL q\n", GCC_2s (c));
3138     GNUNET_free (data);
3139     GNUNET_free (q);
3140     return NULL;
3141   }
3142   q->cont = cont;
3143   q->cont_cls = cont_cls;
3144   return (NULL == cont) ? NULL : q;
3145 }
3146
3147
3148 /**
3149  * Cancel a previously sent message while it's in the queue.
3150  *
3151  * ONLY can be called before the continuation given to the send function
3152  * is called. Once the continuation is called, the message is no longer in the
3153  * queue.
3154  *
3155  * @param q Handle to the queue.
3156  */
3157 void
3158 GCC_cancel (struct CadetConnectionQueue *q)
3159 {
3160   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  GMC cancel message\n");
3161
3162   /* queue destroy calls message_sent, which calls q->cont and frees q */
3163   GCP_queue_destroy (q->q, GNUNET_YES, GNUNET_NO, 0);
3164 }
3165
3166
3167 /**
3168  * Sends a CREATE CONNECTION message for a path to a peer.
3169  * Changes the connection and tunnel states if necessary.
3170  *
3171  * @param connection Connection to create.
3172  */
3173 void
3174 GCC_send_create (struct CadetConnection *connection)
3175 {
3176   enum CadetTunnelCState state;
3177   size_t size;
3178
3179   size = sizeof (struct GNUNET_CADET_ConnectionCreate);
3180   size += connection->path->length * sizeof (struct GNUNET_PeerIdentity);
3181
3182   LOG (GNUNET_ERROR_TYPE_INFO, "---> %s on connection %s  (%u bytes)\n",
3183        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE),
3184        GCC_2s (connection), size);
3185   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u (create)\n",
3186        connection, connection->pending_messages);
3187   connection->pending_messages++;
3188
3189   connection->maintenance_q =
3190     GCP_queue_add (get_next_hop (connection), NULL,
3191                    GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, 0, 0,
3192                    size, connection, GNUNET_YES, &conn_message_sent, NULL);
3193
3194   state = GCT_get_cstate (connection->t);
3195   if (CADET_TUNNEL_SEARCHING == state || CADET_TUNNEL_NEW == state)
3196     GCT_change_cstate (connection->t, CADET_TUNNEL_WAITING);
3197   if (CADET_CONNECTION_NEW == connection->state)
3198     connection_change_state (connection, CADET_CONNECTION_SENT);
3199 }
3200
3201
3202 /**
3203  * Send a message to all peers in this connection that the connection
3204  * is no longer valid.
3205  *
3206  * If some peer should not receive the message, it should be zero'ed out
3207  * before calling this function.
3208  *
3209  * @param c The connection whose peers to notify.
3210  */
3211 void
3212 GCC_send_destroy (struct CadetConnection *c)
3213 {
3214   struct GNUNET_CADET_ConnectionDestroy msg;
3215
3216   if (GNUNET_YES == c->destroy)
3217     return;
3218
3219   msg.header.size = htons (sizeof (msg));
3220   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY);
3221   msg.cid = c->id;
3222   LOG (GNUNET_ERROR_TYPE_DEBUG,
3223               "  sending connection destroy for connection %s\n",
3224               GCC_2s (c));
3225
3226   if (GNUNET_NO == GCC_is_terminal (c, GNUNET_YES))
3227     GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg.header, 0, 0, c,
3228                                                       GNUNET_YES, GNUNET_YES,
3229                                                       NULL, NULL));
3230   if (GNUNET_NO == GCC_is_terminal (c, GNUNET_NO))
3231     GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg.header, 0, 0, c,
3232                                                       GNUNET_NO, GNUNET_YES,
3233                                                       NULL, NULL));
3234   c->destroy = GNUNET_YES;
3235   c->state = CADET_CONNECTION_DESTROYED;
3236 }
3237
3238
3239 /**
3240  * @brief Start a polling timer for the connection.
3241  *
3242  * When a neighbor does not accept more traffic on the connection it could be
3243  * caused by a simple congestion or by a lost ACK. Polling enables to check
3244  * for the lastest ACK status for a connection.
3245  *
3246  * @param c Connection.
3247  * @param fwd Should we poll in the FWD direction?
3248  */
3249 void
3250 GCC_start_poll (struct CadetConnection *c, int fwd)
3251 {
3252   struct CadetFlowControl *fc;
3253
3254   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3255   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL %s requested\n",
3256        GC_f2s (fwd));
3257   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task || NULL != fc->poll_msg)
3258   {
3259     LOG (GNUNET_ERROR_TYPE_DEBUG, " ***   not needed (%u, %p)\n",
3260          fc->poll_task, fc->poll_msg);
3261     return;
3262   }
3263   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL started on request\n");
3264   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3265                                                 &connection_poll,
3266                                                 fc);
3267 }
3268
3269
3270 /**
3271  * @brief Stop polling a connection for ACKs.
3272  *
3273  * Once we have enough ACKs for future traffic, polls are no longer necessary.
3274  *
3275  * @param c Connection.
3276  * @param fwd Should we stop the poll in the FWD direction?
3277  */
3278 void
3279 GCC_stop_poll (struct CadetConnection *c, int fwd)
3280 {
3281   struct CadetFlowControl *fc;
3282
3283   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3284   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
3285   {
3286     GNUNET_SCHEDULER_cancel (fc->poll_task);
3287     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3288   }
3289 }
3290
3291 /**
3292  * Get a (static) string for a connection.
3293  *
3294  * @param c Connection.
3295  */
3296 const char *
3297 GCC_2s (const struct CadetConnection *c)
3298 {
3299   if (NULL == c)
3300     return "NULL";
3301
3302   if (NULL != c->t)
3303   {
3304     static char buf[128];
3305
3306     SPRINTF (buf, "%s (->%s)",
3307              GNUNET_h2s (GC_h2hc (GCC_get_id (c))), GCT_2s (c->t));
3308     return buf;
3309   }
3310   return GNUNET_h2s (GC_h2hc (&c->id));
3311 }
3312
3313
3314 /**
3315  * Log all possible info about the connection state.
3316  *
3317  * @param c Connection to debug.
3318  * @param level Debug level to use.
3319  */
3320 void
3321 GCC_debug (const struct CadetConnection *c, enum GNUNET_ErrorType level)
3322 {
3323   int do_log;
3324   char *s;
3325
3326   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3327                                        "cadet-con",
3328                                        __FILE__, __FUNCTION__, __LINE__);
3329   if (0 == do_log)
3330     return;
3331
3332   if (NULL == c)
3333   {
3334     LOG2 (level, "CCC DEBUG NULL CONNECTION\n");
3335     return;
3336   }
3337
3338   LOG2 (level, "CCC DEBUG CONNECTION %s\n", GCC_2s (c));
3339   s = path_2s (c->path);
3340   LOG2 (level, "CCC  path %s, own pos: %u\n", s, c->own_pos);
3341   GNUNET_free (s);
3342   LOG2 (level, "CCC  state: %s, destroy: %u\n",
3343         GCC_state2s (c->state), c->destroy);
3344   LOG2 (level, "CCC  pending messages: %u\n", c->pending_messages);
3345   if (NULL != c->perf)
3346     LOG2 (level, "CCC  us/byte: %f\n", c->perf->avg);
3347
3348   LOG2 (level, "CCC  FWD flow control:\n");
3349   LOG2 (level, "CCC   queue: %u/%u\n", c->fwd_fc.queue_n, c->fwd_fc.queue_max);
3350   LOG2 (level, "CCC   last PID sent: %5u, recv: %5u\n",
3351         c->fwd_fc.last_pid_sent, c->fwd_fc.last_pid_recv);
3352   LOG2 (level, "CCC   last ACK sent: %5u, recv: %5u\n",
3353         c->fwd_fc.last_ack_sent, c->fwd_fc.last_ack_recv);
3354   LOG2 (level, "CCC   POLL: task %d, msg  %p, msg_ack %p)\n",
3355         c->fwd_fc.poll_task, c->fwd_fc.poll_msg, c->fwd_fc.ack_msg);
3356
3357   LOG2 (level, "CCC  BCK flow control:\n");
3358   LOG2 (level, "CCC   queue: %u/%u\n", c->bck_fc.queue_n, c->bck_fc.queue_max);
3359   LOG2 (level, "CCC   last PID sent: %5u, recv: %5u\n",
3360         c->bck_fc.last_pid_sent, c->bck_fc.last_pid_recv);
3361   LOG2 (level, "CCC   last ACK sent: %5u, recv: %5u\n",
3362         c->bck_fc.last_ack_sent, c->bck_fc.last_ack_recv);
3363   LOG2 (level, "CCC   POLL: task %d, msg  %p, msg_ack %p)\n",
3364         c->bck_fc.poll_task, c->bck_fc.poll_msg, c->bck_fc.ack_msg);
3365
3366   LOG2 (level, "CCC DEBUG CONNECTION END\n");
3367 }
3368