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