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