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