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