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