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