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