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