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