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