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