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