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