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