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