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