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