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