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