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