- include NULL guards in debug
[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 (CADET_TUNNEL_SEARCHING == GCT_get_cstate (c->t))
953   {
954     /* TODO DHT GET with RO_BART */
955     return;
956   }
957   switch (c->state)
958   {
959     case CADET_CONNECTION_NEW:
960       GNUNET_break (0);
961       /* fall-through */
962     case CADET_CONNECTION_SENT:
963       connection_recreate (c, fwd);
964       break;
965     case CADET_CONNECTION_READY:
966       send_connection_keepalive (c, fwd);
967       break;
968     default:
969       break;
970   }
971 }
972
973
974
975 /**
976  * Keep the connection alive.
977  *
978  * @param c Connection to keep alive.
979  * @param fwd Direction.
980  * @param shutdown Are we shutting down? (Don't send traffic)
981  *                 Non-zero value for true, not necessarily GNUNET_YES.
982  */
983 static void
984 connection_keepalive (struct CadetConnection *c, int fwd, int shutdown)
985 {
986   LOG (GNUNET_ERROR_TYPE_DEBUG, "%s keepalive for %s\n",
987        GC_f2s (fwd), GCC_2s (c));
988
989   if (fwd)
990     c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
991   else
992     c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
993
994   if (GNUNET_NO != shutdown)
995     return;
996
997   connection_maintain (c, fwd);
998
999   /* Next execution will be scheduled by message_sent */
1000 }
1001
1002
1003 /**
1004  * Keep the connection alive in the FWD direction.
1005  *
1006  * @param cls Closure (connection to keepalive).
1007  * @param tc TaskContext.
1008  */
1009 static void
1010 connection_fwd_keepalive (void *cls,
1011                           const struct GNUNET_SCHEDULER_TaskContext *tc)
1012 {
1013   connection_keepalive ((struct CadetConnection *) cls,
1014                         GNUNET_YES,
1015                         tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN);
1016 }
1017
1018
1019 /**
1020  * Keep the connection alive in the BCK direction.
1021  *
1022  * @param cls Closure (connection to keepalive).
1023  * @param tc TaskContext.
1024  */
1025 static void
1026 connection_bck_keepalive (void *cls,
1027                           const struct GNUNET_SCHEDULER_TaskContext *tc)
1028 {
1029   connection_keepalive ((struct CadetConnection *) cls,
1030                         GNUNET_NO,
1031                         tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN);
1032 }
1033
1034
1035 /**
1036  * Schedule next keepalive task, taking in consideration
1037  * the connection state and number of retries.
1038  *
1039  * If the peer is not the origin, do nothing.
1040  *
1041  * @param c Connection for which to schedule the next keepalive.
1042  * @param fwd Direction for the next keepalive.
1043  */
1044 static void
1045 schedule_next_keepalive (struct CadetConnection *c, int fwd)
1046 {
1047   struct GNUNET_TIME_Relative delay;
1048   GNUNET_SCHEDULER_TaskIdentifier *task_id;
1049   GNUNET_SCHEDULER_Task keepalive_task;
1050
1051   if (GNUNET_NO == GCC_is_origin (c, fwd))
1052     return;
1053
1054   /* Calculate delay to use, depending on the state of the connection */
1055   if (CADET_CONNECTION_READY == c->state)
1056   {
1057     delay = refresh_connection_time;
1058   }
1059   else
1060   {
1061     if (1 > c->create_retry)
1062       c->create_retry = 1;
1063     delay = GNUNET_TIME_relative_multiply (create_connection_time,
1064                                            c->create_retry);
1065     if (c->create_retry < 64)
1066       c->create_retry *= 2;
1067   }
1068
1069   /* Select direction-dependent parameters */
1070   if (GNUNET_YES == fwd)
1071   {
1072     task_id = &c->fwd_maintenance_task;
1073     keepalive_task = &connection_fwd_keepalive;
1074   }
1075   else
1076   {
1077     task_id = &c->bck_maintenance_task;
1078     keepalive_task = &connection_bck_keepalive;
1079   }
1080
1081   /* Check that no one scheduled it before us */
1082   if (GNUNET_SCHEDULER_NO_TASK != *task_id)
1083   {
1084     /* No need for a _break. It can happen for instance when sending a SYNACK
1085      * for a duplicate SYN: the first SYNACK scheduled the task. */
1086     GNUNET_SCHEDULER_cancel (*task_id);
1087   }
1088
1089   /* Schedule the task */
1090   *task_id = GNUNET_SCHEDULER_add_delayed (delay, keepalive_task, c);
1091   LOG (GNUNET_ERROR_TYPE_DEBUG, "next keepalive in %s\n",
1092        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1093 }
1094
1095
1096 /**
1097  * @brief Re-initiate traffic on this connection if necessary.
1098  *
1099  * Check if there is traffic queued towards this peer
1100  * and the core transmit handle is NULL (traffic was stalled).
1101  * If so, call core tmt rdy.
1102  *
1103  * @param c Connection on which initiate traffic.
1104  * @param fwd Is this about fwd traffic?
1105  */
1106 static void
1107 connection_unlock_queue (struct CadetConnection *c, int fwd)
1108 {
1109   struct CadetPeer *peer;
1110
1111   LOG (GNUNET_ERROR_TYPE_DEBUG,
1112               "connection_unlock_queue %s on %s\n",
1113               GC_f2s (fwd), GCC_2s (c));
1114
1115   if (GCC_is_terminal (c, fwd))
1116   {
1117     LOG (GNUNET_ERROR_TYPE_DEBUG, " is terminal!\n");
1118     return;
1119   }
1120
1121   peer = get_hop (c, fwd);
1122   GCP_queue_unlock (peer, c);
1123 }
1124
1125
1126 /**
1127  * Cancel all transmissions that belong to a certain connection.
1128  *
1129  * If the connection is scheduled for destruction and no more messages are left,
1130  * the connection will be destroyed by the continuation call.
1131  *
1132  * @param c Connection which to cancel. Might be destroyed during this call.
1133  * @param fwd Cancel fwd traffic?
1134  */
1135 static void
1136 connection_cancel_queues (struct CadetConnection *c, int fwd)
1137 {
1138   struct CadetFlowControl *fc;
1139   struct CadetPeer *peer;
1140
1141   LOG (GNUNET_ERROR_TYPE_DEBUG,
1142        " *** Cancel %s queues for connection %s\n",
1143        GC_f2s (fwd), GCC_2s (c));
1144   if (NULL == c)
1145   {
1146     GNUNET_break (0);
1147     return;
1148   }
1149
1150   fc = fwd ? &c->fwd_fc : &c->bck_fc;
1151   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
1152   {
1153     GNUNET_SCHEDULER_cancel (fc->poll_task);
1154     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1155     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** Cancel POLL in ccq for fc %p\n", fc);
1156   }
1157   peer = get_hop (c, fwd);
1158   GCP_queue_cancel (peer, c);
1159 }
1160
1161
1162 /**
1163  * Function called if a connection has been stalled for a while,
1164  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
1165  *
1166  * @param cls Closure (poll ctx).
1167  * @param tc TaskContext.
1168  */
1169 static void
1170 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1171
1172
1173 /**
1174  * Callback called when a queued POLL message is sent.
1175  *
1176  * @param cls Closure (FC).
1177  * @param c Connection this message was on.
1178  * @param q Queue handler this call invalidates.
1179  * @param type Type of message sent.
1180  * @param fwd Was this a FWD going message?
1181  * @param size Size of the message.
1182  */
1183 static void
1184 poll_sent (void *cls,
1185            struct CadetConnection *c,
1186            struct CadetConnectionQueue *q,
1187            uint16_t type, int fwd, size_t size)
1188 {
1189   struct CadetFlowControl *fc = cls;
1190
1191   if (2 == c->destroy)
1192   {
1193     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL canceled on shutdown\n");
1194     return;
1195   }
1196   LOG (GNUNET_ERROR_TYPE_DEBUG,
1197        " *** POLL sent for , scheduling new one!\n");
1198   fc->poll_msg = NULL;
1199   fc->poll_time = GNUNET_TIME_STD_BACKOFF (fc->poll_time);
1200   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
1201                                                 &connection_poll, fc);
1202   LOG (GNUNET_ERROR_TYPE_DEBUG, " task %u\n", fc->poll_task);
1203
1204 }
1205
1206 /**
1207  * Function called if a connection has been stalled for a while,
1208  * possibly due to a missed ACK. Poll the neighbor about its ACK status.
1209  *
1210  * @param cls Closure (poll ctx).
1211  * @param tc TaskContext.
1212  */
1213 static void
1214 connection_poll (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1215 {
1216   struct CadetFlowControl *fc = cls;
1217   struct GNUNET_CADET_Poll msg;
1218   struct CadetConnection *c;
1219
1220   fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1221   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1222   {
1223     return;
1224   }
1225
1226   c = fc->c;
1227   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** Polling connection %s %s\n",
1228        GCC_2s (c), fc == &c->fwd_fc ? "FWD" : "BCK");
1229
1230   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_POLL);
1231   msg.header.size = htons (sizeof (msg));
1232   msg.pid = htonl (fc->last_pid_sent);
1233   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** last pid sent: %u!\n", fc->last_pid_sent);
1234   fc->poll_msg =
1235       GCC_send_prebuilt_message (&msg.header, 0, fc->last_pid_sent, c,
1236                                  fc == &c->fwd_fc, GNUNET_YES, &poll_sent, fc);
1237   GNUNET_assert (NULL != fc->poll_msg);
1238 }
1239
1240
1241 /**
1242  * Timeout function due to lack of keepalive/traffic from the owner.
1243  * Destroys connection if called.
1244  *
1245  * @param cls Closure (connection to destroy).
1246  * @param tc TaskContext.
1247  */
1248 static void
1249 connection_fwd_timeout (void *cls,
1250                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1251 {
1252   struct CadetConnection *c = cls;
1253
1254   c->fwd_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
1255   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1256     return;
1257
1258   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s FWD timed out. Destroying.\n",
1259        GCC_2s (c));
1260   if (GCC_is_origin (c, GNUNET_YES)) /* If local, leave. */
1261   {
1262     GNUNET_break (0);
1263     return;
1264   }
1265
1266   GCC_destroy (c);
1267 }
1268
1269
1270 /**
1271  * Timeout function due to lack of keepalive/traffic from the destination.
1272  * Destroys connection if called.
1273  *
1274  * @param cls Closure (connection to destroy).
1275  * @param tc TaskContext
1276  */
1277 static void
1278 connection_bck_timeout (void *cls,
1279                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1280 {
1281   struct CadetConnection *c = cls;
1282
1283   c->bck_maintenance_task = GNUNET_SCHEDULER_NO_TASK;
1284   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1285     return;
1286
1287   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s BCK timed out. Destroying.\n",
1288        GCC_2s (c));
1289
1290   if (GCC_is_origin (c, GNUNET_NO)) /* If local, leave. */
1291   {
1292     GNUNET_break (0);
1293     return;
1294   }
1295
1296   GCC_destroy (c);
1297 }
1298
1299
1300 /**
1301  * Resets the connection timeout task, some other message has done the
1302  * task's job.
1303  * - For the first peer on the direction this means to send
1304  *   a keepalive or a path confirmation message (either create or ACK).
1305  * - For all other peers, this means to destroy the connection,
1306  *   due to lack of activity.
1307  * Starts the timeout if no timeout was running (connection just created).
1308  *
1309  * @param c Connection whose timeout to reset.
1310  * @param fwd Is this forward?
1311  *
1312  * TODO use heap to improve efficiency of scheduler.
1313  */
1314 static void
1315 connection_reset_timeout (struct CadetConnection *c, int fwd)
1316 {
1317   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection %s reset timeout\n", GC_f2s (fwd));
1318
1319   if (GCC_is_origin (c, fwd)) /* Startpoint */
1320   {
1321     schedule_next_keepalive (c, fwd);
1322   }
1323   else /* Relay, endpoint. */
1324   {
1325     struct GNUNET_TIME_Relative delay;
1326     GNUNET_SCHEDULER_TaskIdentifier *ti;
1327     GNUNET_SCHEDULER_Task f;
1328
1329     ti = fwd ? &c->fwd_maintenance_task : &c->bck_maintenance_task;
1330
1331     if (GNUNET_SCHEDULER_NO_TASK != *ti)
1332       GNUNET_SCHEDULER_cancel (*ti);
1333     delay = GNUNET_TIME_relative_multiply (refresh_connection_time, 4);
1334     f = fwd ? &connection_fwd_timeout : &connection_bck_timeout;
1335     *ti = GNUNET_SCHEDULER_add_delayed (delay, f, c);
1336   }
1337 }
1338
1339
1340 /**
1341  * Add the connection to the list of both neighbors.
1342  *
1343  * @param c Connection.
1344  *
1345  * @return #GNUNET_OK if everything went fine
1346  *         #GNUNET_SYSERR if the was an error and @c c is malformed.
1347  */
1348 static int
1349 register_neighbors (struct CadetConnection *c)
1350 {
1351   struct CadetPeer *next_peer;
1352   struct CadetPeer *prev_peer;
1353
1354   next_peer = get_next_hop (c);
1355   prev_peer = get_prev_hop (c);
1356
1357   LOG (GNUNET_ERROR_TYPE_DEBUG, "register neighbors for connection %s\n",
1358        GCC_2s (c));
1359   path_debug (c->path);
1360   LOG (GNUNET_ERROR_TYPE_DEBUG, "own pos %u\n", c->own_pos);
1361   LOG (GNUNET_ERROR_TYPE_DEBUG, "putting connection %s to next peer %p\n",
1362        GCC_2s (c), next_peer);
1363   LOG (GNUNET_ERROR_TYPE_DEBUG, "next peer %p %s\n", next_peer, GCP_2s (next_peer));
1364   LOG (GNUNET_ERROR_TYPE_DEBUG, "putting connection %s to prev peer %p\n",
1365        GCC_2s (c), prev_peer);
1366   LOG (GNUNET_ERROR_TYPE_DEBUG, "prev peer %p %s\n", prev_peer, GCP_2s (prev_peer));
1367
1368   if (GNUNET_NO == GCP_is_neighbor (next_peer)
1369       || GNUNET_NO == GCP_is_neighbor (prev_peer))
1370   {
1371     if (GCC_is_origin (c, GNUNET_YES))
1372       GNUNET_STATISTICS_update (stats, "# local bad paths", 1, GNUNET_NO);
1373     GNUNET_STATISTICS_update (stats, "# bad paths", 1, GNUNET_NO);
1374
1375     LOG (GNUNET_ERROR_TYPE_DEBUG, "  register neighbors failed\n");
1376     LOG (GNUNET_ERROR_TYPE_DEBUG, "  prev: %s, neighbor?: %d\n",
1377          GCP_2s (prev_peer), GCP_is_neighbor (prev_peer));
1378     LOG (GNUNET_ERROR_TYPE_DEBUG, "  next: %s, neighbor?: %d\n",
1379          GCP_2s (next_peer), GCP_is_neighbor (next_peer));
1380     return GNUNET_SYSERR;
1381   }
1382
1383   GCP_add_connection (next_peer, c);
1384   GCP_add_connection (prev_peer, c);
1385
1386   return GNUNET_OK;
1387 }
1388
1389
1390 /**
1391  * Remove the connection from the list of both neighbors.
1392  *
1393  * @param c Connection.
1394  */
1395 static void
1396 unregister_neighbors (struct CadetConnection *c)
1397 {
1398   struct CadetPeer *peer;
1399
1400   peer = get_next_hop (c);
1401   if (GNUNET_OK != GCP_remove_connection (peer, c))
1402   {
1403     GNUNET_assert (CADET_CONNECTION_NEW == c->state
1404                   || CADET_CONNECTION_DESTROYED == c->state);
1405     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate: %u\n", c->state);
1406     if (NULL != c->t) GCT_debug (c->t, GNUNET_ERROR_TYPE_DEBUG);
1407   }
1408
1409   peer = get_prev_hop (c);
1410   if (GNUNET_OK != GCP_remove_connection (peer, c))
1411   {
1412     GNUNET_assert (CADET_CONNECTION_NEW == c->state
1413                   || CADET_CONNECTION_DESTROYED == c->state);
1414     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate: %u\n", c->state);
1415     if (NULL != c->t) GCT_debug (c->t, GNUNET_ERROR_TYPE_DEBUG);
1416   }
1417 }
1418
1419
1420 /**
1421  * Bind the connection to the peer and the tunnel to that peer.
1422  *
1423  * If the peer has no tunnel, create one. Update tunnel and connection
1424  * data structres to reflect new status.
1425  *
1426  * @param c Connection.
1427  * @param peer Peer.
1428  */
1429 static void
1430 add_to_peer (struct CadetConnection *c, struct CadetPeer *peer)
1431 {
1432   GCP_add_tunnel (peer);
1433   c->t = GCP_get_tunnel (peer);
1434   GCT_add_connection (c->t, c);
1435 }
1436
1437
1438 /**
1439  * Builds a path from a PeerIdentity array.
1440  *
1441  * @param peers PeerIdentity array.
1442  * @param size Size of the @c peers array.
1443  * @param own_pos Output parameter: own position in the path.
1444  *
1445  * @return Fixed and shortened path.
1446  */
1447 static struct CadetPeerPath *
1448 build_path_from_peer_ids (struct GNUNET_PeerIdentity *peers,
1449                           unsigned int size,
1450                           unsigned int *own_pos)
1451 {
1452   struct CadetPeerPath *path;
1453   GNUNET_PEER_Id shortid;
1454   unsigned int i;
1455   unsigned int j;
1456   unsigned int offset;
1457
1458   /* Create path */
1459   LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating path...\n");
1460   path = path_new (size);
1461   *own_pos = 0;
1462   offset = 0;
1463   for (i = 0; i < size; i++)
1464   {
1465     LOG (GNUNET_ERROR_TYPE_DEBUG, "  - %u: taking %s\n",
1466          i, GNUNET_i2s (&peers[i]));
1467     shortid = GNUNET_PEER_intern (&peers[i]);
1468
1469     /* Check for loops / duplicates */
1470     for (j = 0; j < i - offset; j++)
1471     {
1472       if (path->peers[j] == shortid)
1473       {
1474         LOG (GNUNET_ERROR_TYPE_DEBUG, "    already exists at pos %u\n", j);
1475         offset = i - j;
1476         LOG (GNUNET_ERROR_TYPE_DEBUG, "    offset now %u\n", offset);
1477         GNUNET_PEER_change_rc (shortid, -1);
1478       }
1479     }
1480     LOG (GNUNET_ERROR_TYPE_DEBUG, "    storing at %u\n", i - offset);
1481     path->peers[i - offset] = shortid;
1482     if (path->peers[i - offset] == myid)
1483       *own_pos = i - offset;
1484   }
1485   path->length -= offset;
1486
1487   if (path->peers[*own_pos] != myid)
1488   {
1489     /* create path: self not found in path through self */
1490     GNUNET_break_op (0);
1491     path_destroy (path);
1492     return NULL;
1493   }
1494
1495   return path;
1496 }
1497
1498
1499 /**
1500  * Log receipt of message on stderr (INFO level).
1501  *
1502  * @param message Message received.
1503  * @param peer Peer who sent the message.
1504  * @param hash Connection ID.
1505  */
1506 static void
1507 log_message (const struct GNUNET_MessageHeader *message,
1508              const struct GNUNET_PeerIdentity *peer,
1509              const struct GNUNET_CADET_Hash *hash)
1510 {
1511   LOG (GNUNET_ERROR_TYPE_INFO, "<-- %s on connection %s from %s\n",
1512        GC_m2s (ntohs (message->type)), GNUNET_h2s (GC_h2hc (hash)),
1513        GNUNET_i2s (peer));
1514 }
1515
1516 /******************************************************************************/
1517 /********************************    API    ***********************************/
1518 /******************************************************************************/
1519
1520 /**
1521  * Core handler for connection creation.
1522  *
1523  * @param cls Closure (unused).
1524  * @param peer Sender (neighbor).
1525  * @param message Message.
1526  *
1527  * @return GNUNET_OK to keep the connection open,
1528  *         GNUNET_SYSERR to close it (signal serious error)
1529  */
1530 int
1531 GCC_handle_create (void *cls, const struct GNUNET_PeerIdentity *peer,
1532                    const struct GNUNET_MessageHeader *message)
1533 {
1534   struct GNUNET_CADET_ConnectionCreate *msg;
1535   struct GNUNET_PeerIdentity *id;
1536   struct GNUNET_CADET_Hash *cid;
1537   struct CadetPeerPath *path;
1538   struct CadetPeer *dest_peer;
1539   struct CadetPeer *orig_peer;
1540   struct CadetConnection *c;
1541   unsigned int own_pos;
1542   uint16_t size;
1543
1544   /* Check size */
1545   size = ntohs (message->size);
1546   if (size < sizeof (struct GNUNET_CADET_ConnectionCreate))
1547   {
1548     GNUNET_break_op (0);
1549     return GNUNET_OK;
1550   }
1551
1552   /* Calculate hops */
1553   size -= sizeof (struct GNUNET_CADET_ConnectionCreate);
1554   if (size % sizeof (struct GNUNET_PeerIdentity))
1555   {
1556     GNUNET_break_op (0);
1557     return GNUNET_OK;
1558   }
1559   size /= sizeof (struct GNUNET_PeerIdentity);
1560   if (1 > size)
1561   {
1562     GNUNET_break_op (0);
1563     return GNUNET_OK;
1564   }
1565   LOG (GNUNET_ERROR_TYPE_DEBUG, "    path has %u hops.\n", size);
1566
1567   /* Get parameters */
1568   msg = (struct GNUNET_CADET_ConnectionCreate *) message;
1569   cid = &msg->cid;
1570   log_message (message, peer, cid);
1571   id = (struct GNUNET_PeerIdentity *) &msg[1];
1572   LOG (GNUNET_ERROR_TYPE_DEBUG, "    origin: %s\n", GNUNET_i2s (id));
1573
1574   /* Create connection */
1575   c = connection_get (cid);
1576   if (NULL == c)
1577   {
1578     path = build_path_from_peer_ids ((struct GNUNET_PeerIdentity *) &msg[1],
1579                                      size, &own_pos);
1580     if (NULL == path)
1581       return GNUNET_OK;
1582     if (0 == own_pos)
1583     {
1584       GNUNET_break_op (0);
1585       path_destroy (path);
1586       return GNUNET_OK;
1587     }
1588     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Own position: %u\n", own_pos);
1589     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Creating connection\n");
1590     c = GCC_new (cid, NULL, path_duplicate (path), own_pos);
1591     if (NULL == c)
1592     {
1593       if (path->length - 1 == own_pos)
1594       {
1595         /* If we are destination, why did the creation fail? */
1596         GNUNET_break (0);
1597         return GNUNET_OK;
1598       }
1599       send_broken_unknown (cid, &my_full_id,
1600                            GNUNET_PEER_resolve2 (path->peers[own_pos + 1]),
1601                            peer);
1602       path_destroy (path);
1603       return GNUNET_OK;
1604     }
1605     GCP_add_path_to_all (path, GNUNET_NO);
1606     connection_reset_timeout (c, GNUNET_YES);
1607   }
1608   else
1609   {
1610     path = path_duplicate (c->path);
1611   }
1612   if (CADET_CONNECTION_NEW == c->state)
1613     connection_change_state (c, CADET_CONNECTION_SENT);
1614
1615   /* Remember peers */
1616   dest_peer = GCP_get (&id[size - 1]);
1617   orig_peer = GCP_get (&id[0]);
1618
1619   /* Is it a connection to us? */
1620   if (c->own_pos == path->length - 1)
1621   {
1622     LOG (GNUNET_ERROR_TYPE_DEBUG, "  It's for us!\n");
1623     GCP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_YES);
1624
1625     add_to_peer (c, orig_peer);
1626     if (CADET_TUNNEL_NEW == GCT_get_cstate (c->t))
1627       GCT_change_cstate (c->t,  CADET_TUNNEL_WAITING);
1628
1629     send_connection_ack (c, GNUNET_NO);
1630     if (CADET_CONNECTION_SENT == c->state)
1631       connection_change_state (c, CADET_CONNECTION_ACK);
1632   }
1633   else
1634   {
1635     /* It's for somebody else! Retransmit. */
1636     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Retransmitting.\n");
1637     GCP_add_path (dest_peer, path_duplicate (path), GNUNET_NO);
1638     GCP_add_path_to_origin (orig_peer, path_duplicate (path), GNUNET_NO);
1639     GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c,
1640                                                       GNUNET_YES, GNUNET_YES,
1641                                                       NULL, NULL));
1642   }
1643   path_destroy (path);
1644   return GNUNET_OK;
1645 }
1646
1647
1648 /**
1649  * Core handler for path confirmations.
1650  *
1651  * @param cls closure
1652  * @param message message
1653  * @param peer peer identity this notification is about
1654  *
1655  * @return GNUNET_OK to keep the connection open,
1656  *         GNUNET_SYSERR to close it (signal serious error)
1657  */
1658 int
1659 GCC_handle_confirm (void *cls, const struct GNUNET_PeerIdentity *peer,
1660                     const struct GNUNET_MessageHeader *message)
1661 {
1662   struct GNUNET_CADET_ConnectionACK *msg;
1663   struct CadetConnection *c;
1664   struct CadetPeerPath *p;
1665   struct CadetPeer *pi;
1666   enum CadetConnectionState oldstate;
1667   int fwd;
1668
1669   msg = (struct GNUNET_CADET_ConnectionACK *) message;
1670   log_message (message, peer, &msg->cid);
1671   c = connection_get (&msg->cid);
1672   if (NULL == c)
1673   {
1674     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1675                               1, GNUNET_NO);
1676     LOG (GNUNET_ERROR_TYPE_DEBUG, "  don't know the connection!\n");
1677     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
1678     return GNUNET_OK;
1679   }
1680
1681   if (GNUNET_NO != c->destroy)
1682   {
1683     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection being destroyed\n");
1684     return GNUNET_OK;
1685   }
1686
1687   oldstate = c->state;
1688   LOG (GNUNET_ERROR_TYPE_DEBUG, "  via peer %s\n", GNUNET_i2s (peer));
1689   pi = GCP_get (peer);
1690   if (get_next_hop (c) == pi)
1691   {
1692     LOG (GNUNET_ERROR_TYPE_DEBUG, "  SYNACK\n");
1693     fwd = GNUNET_NO;
1694     if (CADET_CONNECTION_SENT == oldstate)
1695       connection_change_state (c, CADET_CONNECTION_ACK);
1696   }
1697   else if (get_prev_hop (c) == pi)
1698   {
1699     LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK\n");
1700     fwd = GNUNET_YES;
1701     connection_change_state (c, CADET_CONNECTION_READY);
1702   }
1703   else
1704   {
1705     GNUNET_break_op (0);
1706     return GNUNET_OK;
1707   }
1708
1709   connection_reset_timeout (c, fwd);
1710
1711   /* Add path to peers? */
1712   p = c->path;
1713   if (NULL != p)
1714   {
1715     GCP_add_path_to_all (p, GNUNET_YES);
1716   }
1717   else
1718   {
1719     GNUNET_break (0);
1720   }
1721
1722   /* Message for us as creator? */
1723   if (GCC_is_origin (c, GNUNET_YES))
1724   {
1725     if (GNUNET_NO != fwd)
1726     {
1727       GNUNET_break_op (0);
1728       return GNUNET_OK;
1729     }
1730     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection (SYN)ACK for us!\n");
1731
1732     /* If just created, cancel the short timeout and start a long one */
1733     if (CADET_CONNECTION_SENT == oldstate)
1734       connection_reset_timeout (c, GNUNET_YES);
1735
1736     /* Change connection state */
1737     connection_change_state (c, CADET_CONNECTION_READY);
1738     send_connection_ack (c, GNUNET_YES);
1739
1740     /* Change tunnel state, trigger KX */
1741     if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
1742       GCT_change_cstate (c->t, CADET_TUNNEL_READY);
1743
1744     return GNUNET_OK;
1745   }
1746
1747   /* Message for us as destination? */
1748   if (GCC_is_terminal (c, GNUNET_YES))
1749   {
1750     if (GNUNET_YES != fwd)
1751     {
1752       GNUNET_break_op (0);
1753       return GNUNET_OK;
1754     }
1755     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Connection ACK for us!\n");
1756
1757     /* If just created, cancel the short timeout and start a long one */
1758     if (CADET_CONNECTION_ACK == oldstate)
1759       connection_reset_timeout (c, GNUNET_NO);
1760
1761     /* Change tunnel state */
1762     if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
1763       GCT_change_cstate (c->t, CADET_TUNNEL_READY);
1764
1765     return GNUNET_OK;
1766   }
1767
1768   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
1769   GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
1770                                                     GNUNET_YES, NULL, NULL));
1771   return GNUNET_OK;
1772 }
1773
1774
1775 /**
1776  * Core handler for notifications of broken connections.
1777  *
1778  * @param cls Closure (unused).
1779  * @param id Peer identity of sending neighbor.
1780  * @param message Message.
1781  *
1782  * @return GNUNET_OK to keep the connection open,
1783  *         GNUNET_SYSERR to close it (signal serious error)
1784  */
1785 int
1786 GCC_handle_broken (void* cls,
1787                    const struct GNUNET_PeerIdentity* id,
1788                    const struct GNUNET_MessageHeader* message)
1789 {
1790   struct GNUNET_CADET_ConnectionBroken *msg;
1791   struct CadetConnection *c;
1792   struct CadetTunnel *t;
1793   int fwd;
1794
1795   msg = (struct GNUNET_CADET_ConnectionBroken *) message;
1796   log_message (message, id, &msg->cid);
1797   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1798               GNUNET_i2s (&msg->peer1));
1799   LOG (GNUNET_ERROR_TYPE_DEBUG, "  regarding %s\n",
1800               GNUNET_i2s (&msg->peer2));
1801   c = connection_get (&msg->cid);
1802   if (NULL == c)
1803   {
1804     LOG (GNUNET_ERROR_TYPE_DEBUG, "  duplicate CONNECTION_BROKEN\n");
1805     return GNUNET_OK;
1806   }
1807
1808   t = c->t;
1809   fwd = is_fwd (c, id);
1810   if (GCC_is_terminal (c, fwd))
1811   {
1812     struct GNUNET_MessageHeader *out_msg;
1813     struct CadetPeer *neighbor;
1814     struct CadetPeer *endpoint;
1815     int pending_msgs;
1816
1817     if (NULL == t)
1818     {
1819       /* A terminal connection should not have 't' set to NULL. */
1820       GNUNET_break (0);
1821       return GNUNET_OK;
1822     }
1823     neighbor = get_hop (c, !fwd);
1824     endpoint = GCP_get_short (c->path->peers[c->path->length - 1]);
1825     path_invalidate (c->path);
1826     GCP_notify_broken_link (endpoint, &msg->peer1, &msg->peer2);
1827     c->state = CADET_CONNECTION_DESTROYED;
1828     pending_msgs = c->pending_messages;
1829
1830     /* GCP_connection_pop will destroy the connection when the last message
1831      * is popped! Do not use 'c' after the call. */
1832     while (NULL != (out_msg = GCP_connection_pop (neighbor, c)))
1833     {
1834       GNUNET_assert (NULL ==
1835                      GCT_send_prebuilt_message (out_msg, t, NULL, GNUNET_YES,
1836                                                 NULL, NULL));
1837       pending_msgs--;
1838     }
1839
1840     /* All pending messages should have been popped and the connection
1841      * destroyed. If not, destroy the connection anyway! */
1842     if (0 < pending_msgs)
1843     {
1844       GNUNET_break (0);
1845       GCC_destroy (c);
1846     }
1847     else
1848       GNUNET_break (0 == pending_msgs); /* Counter error! */
1849   }
1850   else
1851   {
1852     GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
1853                                                       GNUNET_YES, NULL, NULL));
1854     c->destroy = GNUNET_YES;
1855     connection_cancel_queues (c, !fwd);
1856   }
1857
1858   return GNUNET_OK;
1859 }
1860
1861
1862 /**
1863  * Core handler for tunnel destruction
1864  *
1865  * @param cls Closure (unused).
1866  * @param peer Peer identity of sending neighbor.
1867  * @param message Message.
1868  *
1869  * @return GNUNET_OK to keep the connection open,
1870  *         GNUNET_SYSERR to close it (signal serious error)
1871  */
1872 int
1873 GCC_handle_destroy (void *cls, const struct GNUNET_PeerIdentity *peer,
1874                     const struct GNUNET_MessageHeader *message)
1875 {
1876   struct GNUNET_CADET_ConnectionDestroy *msg;
1877   struct CadetConnection *c;
1878   int fwd;
1879
1880   msg = (struct GNUNET_CADET_ConnectionDestroy *) message;
1881   log_message (message, peer, &msg->cid);
1882   c = connection_get (&msg->cid);
1883   if (NULL == c)
1884   {
1885     /* Probably already got the message from another path,
1886      * destroyed the tunnel and retransmitted to children.
1887      * Safe to ignore.
1888      */
1889     GNUNET_STATISTICS_update (stats, "# control on unknown connection",
1890                               1, GNUNET_NO);
1891     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection unknown: already destroyed?\n");
1892     return GNUNET_OK;
1893   }
1894   fwd = is_fwd (c, peer);
1895   if (GNUNET_SYSERR == fwd)
1896   {
1897     GNUNET_break_op (0); /* FIXME */
1898     return GNUNET_OK;
1899   }
1900   if (GNUNET_NO == GCC_is_terminal (c, fwd))
1901     GNUNET_assert (NULL == GCC_send_prebuilt_message (message, 0, 0, c, fwd,
1902                                                       GNUNET_YES, NULL, NULL));
1903   else if (0 == c->pending_messages)
1904   {
1905     LOG (GNUNET_ERROR_TYPE_DEBUG, "  directly destroying connection!\n");
1906     GCC_destroy (c);
1907     return GNUNET_OK;
1908   }
1909   c->destroy = GNUNET_YES;
1910   c->state = CADET_CONNECTION_DESTROYED;
1911   if (NULL != c->t)
1912   {
1913     GCT_remove_connection (c->t, c);
1914     c->t = NULL;
1915   }
1916
1917   return GNUNET_OK;
1918 }
1919
1920 /**
1921  * Generic handler for cadet network encrypted traffic.
1922  *
1923  * @param peer Peer identity this notification is about.
1924  * @param msg Encrypted message.
1925  *
1926  * @return GNUNET_OK to keep the connection open,
1927  *         GNUNET_SYSERR to close it (signal serious error)
1928  */
1929 static int
1930 handle_cadet_encrypted (const struct GNUNET_PeerIdentity *peer,
1931                        const struct GNUNET_CADET_Encrypted *msg)
1932 {
1933   struct CadetConnection *c;
1934   struct CadetPeer *neighbor;
1935   struct CadetFlowControl *fc;
1936   GNUNET_PEER_Id peer_id;
1937   uint32_t pid;
1938   uint32_t ttl;
1939   size_t size;
1940   int fwd;
1941
1942   log_message (&msg->header, peer, &msg->cid);
1943
1944   /* Check size */
1945   size = ntohs (msg->header.size);
1946   if (size <
1947       sizeof (struct GNUNET_CADET_Encrypted) +
1948       sizeof (struct GNUNET_MessageHeader))
1949   {
1950     GNUNET_break_op (0);
1951     return GNUNET_OK;
1952   }
1953
1954   /* Check connection */
1955   c = connection_get (&msg->cid);
1956   if (NULL == c)
1957   {
1958     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
1959     LOG (GNUNET_ERROR_TYPE_DEBUG, "enc on unknown connection %s\n",
1960          GNUNET_h2s (GC_h2hc (&msg->cid)));
1961     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
1962     return GNUNET_OK;
1963   }
1964
1965   LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s\n", GCC_2s (c));
1966
1967   /* Check if origin is as expected */
1968   neighbor = get_prev_hop (c);
1969   peer_id = GNUNET_PEER_search (peer);
1970   if (peer_id == GCP_get_short_id (neighbor))
1971   {
1972     fwd = GNUNET_YES;
1973   }
1974   else
1975   {
1976     neighbor = get_next_hop (c);
1977     if (peer_id == GCP_get_short_id (neighbor))
1978     {
1979       fwd = GNUNET_NO;
1980     }
1981     else
1982     {
1983       /* Unexpected peer sending traffic on a connection. */
1984       GNUNET_break_op (0);
1985       return GNUNET_OK;
1986     }
1987   }
1988
1989   /* Check PID */
1990   fc = fwd ? &c->bck_fc : &c->fwd_fc;
1991   pid = ntohl (msg->pid);
1992   LOG (GNUNET_ERROR_TYPE_DEBUG, " PID %u (expected %u+)\n",
1993        pid, fc->last_pid_recv + 1);
1994   if (GC_is_pid_bigger (pid, fc->last_ack_sent))
1995   {
1996     GNUNET_STATISTICS_update (stats, "# unsolicited message", 1, GNUNET_NO);
1997     GNUNET_break_op (0);
1998     LOG (GNUNET_ERROR_TYPE_WARNING,
1999          "Received PID %u, (prev %u), ACK %u\n",
2000          pid, fc->last_pid_recv, fc->last_ack_sent);
2001     return GNUNET_OK;
2002   }
2003   if (GNUNET_NO == GC_is_pid_bigger (pid, fc->last_pid_recv))
2004   {
2005     GNUNET_STATISTICS_update (stats, "# duplicate PID", 1, GNUNET_NO);
2006     LOG (GNUNET_ERROR_TYPE_DEBUG,
2007                 " PID %u not expected (%u+), dropping!\n",
2008                 pid, fc->last_pid_recv + 1);
2009     return GNUNET_OK;
2010   }
2011   if (CADET_CONNECTION_SENT == c->state || CADET_CONNECTION_ACK == c->state)
2012     connection_change_state (c, CADET_CONNECTION_READY);
2013   connection_reset_timeout (c, fwd);
2014   fc->last_pid_recv = pid;
2015
2016   /* Is this message for us? */
2017   if (GCC_is_terminal (c, fwd))
2018   {
2019     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
2020     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
2021
2022     if (NULL == c->t)
2023     {
2024       GNUNET_break (GNUNET_NO != c->destroy);
2025       return GNUNET_OK;
2026     }
2027     fc->last_pid_recv = pid;
2028     GCT_handle_encrypted (c->t, msg);
2029     GCC_send_ack (c, fwd, GNUNET_NO);
2030     return GNUNET_OK;
2031   }
2032
2033   /* Message not for us: forward to next hop */
2034   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2035   ttl = ntohl (msg->ttl);
2036   LOG (GNUNET_ERROR_TYPE_DEBUG, "   ttl: %u\n", ttl);
2037   if (ttl == 0)
2038   {
2039     GNUNET_STATISTICS_update (stats, "# TTL drops", 1, GNUNET_NO);
2040     LOG (GNUNET_ERROR_TYPE_WARNING, " TTL is 0, DROPPING!\n");
2041     GCC_send_ack (c, fwd, GNUNET_NO);
2042     return GNUNET_OK;
2043   }
2044
2045   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
2046   GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
2047                                                     GNUNET_NO, NULL, NULL));
2048
2049   return GNUNET_OK;
2050 }
2051
2052 /**
2053  * Generic handler for cadet network encrypted traffic.
2054  *
2055  * @param peer Peer identity this notification is about.
2056  * @param msg Encrypted message.
2057  *
2058  * @return GNUNET_OK to keep the connection open,
2059  *         GNUNET_SYSERR to close it (signal serious error)
2060  */
2061 static int
2062 handle_cadet_kx (const struct GNUNET_PeerIdentity *peer,
2063                 const struct GNUNET_CADET_KX *msg)
2064 {
2065   struct CadetConnection *c;
2066   struct CadetPeer *neighbor;
2067   GNUNET_PEER_Id peer_id;
2068   size_t size;
2069   int fwd;
2070
2071   log_message (&msg->header, peer, &msg->cid);
2072
2073   /* Check size */
2074   size = ntohs (msg->header.size);
2075   if (size <
2076       sizeof (struct GNUNET_CADET_KX) +
2077       sizeof (struct GNUNET_MessageHeader))
2078   {
2079     GNUNET_break_op (0);
2080     return GNUNET_OK;
2081   }
2082
2083   /* Check connection */
2084   c = connection_get (&msg->cid);
2085   if (NULL == c)
2086   {
2087     GNUNET_STATISTICS_update (stats, "# unknown connection", 1, GNUNET_NO);
2088     LOG (GNUNET_ERROR_TYPE_DEBUG, "kx on unknown connection %s\n",
2089          GNUNET_h2s (GC_h2hc (&msg->cid)));
2090     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
2091     return GNUNET_OK;
2092   }
2093   LOG (GNUNET_ERROR_TYPE_DEBUG, " on connection %s\n", GCC_2s (c));
2094
2095   /* Check if origin is as expected */
2096   neighbor = get_prev_hop (c);
2097   peer_id = GNUNET_PEER_search (peer);
2098   if (peer_id == GCP_get_short_id (neighbor))
2099   {
2100     fwd = GNUNET_YES;
2101   }
2102   else
2103   {
2104     neighbor = get_next_hop (c);
2105     if (peer_id == GCP_get_short_id (neighbor))
2106     {
2107       fwd = GNUNET_NO;
2108     }
2109     else
2110     {
2111       /* Unexpected peer sending traffic on a connection. */
2112       GNUNET_break_op (0);
2113       return GNUNET_OK;
2114     }
2115   }
2116
2117   /* Count as connection confirmation. */
2118   if (CADET_CONNECTION_SENT == c->state || CADET_CONNECTION_ACK == c->state)
2119   {
2120     connection_change_state (c, CADET_CONNECTION_READY);
2121     if (NULL != c->t)
2122     {
2123       if (CADET_TUNNEL_WAITING == GCT_get_cstate (c->t))
2124         GCT_change_cstate (c->t, CADET_TUNNEL_READY);
2125     }
2126   }
2127   connection_reset_timeout (c, fwd);
2128
2129   /* Is this message for us? */
2130   if (GCC_is_terminal (c, fwd))
2131   {
2132     LOG (GNUNET_ERROR_TYPE_DEBUG, "  message for us!\n");
2133     GNUNET_STATISTICS_update (stats, "# messages received", 1, GNUNET_NO);
2134     if (NULL == c->t)
2135     {
2136       GNUNET_break (0);
2137       return GNUNET_OK;
2138     }
2139     GCT_handle_kx (c->t, &msg[1].header);
2140     return GNUNET_OK;
2141   }
2142
2143   /* Message not for us: forward to next hop */
2144   LOG (GNUNET_ERROR_TYPE_DEBUG, "  not for us, retransmitting...\n");
2145   GNUNET_STATISTICS_update (stats, "# messages forwarded", 1, GNUNET_NO);
2146   GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, 0, 0, c, fwd,
2147                                                     GNUNET_NO, NULL, NULL));
2148
2149   return GNUNET_OK;
2150 }
2151
2152
2153 /**
2154  * Core handler for encrypted cadet network traffic (channel mgmt, data).
2155  *
2156  * @param cls Closure (unused).
2157  * @param message Message received.
2158  * @param peer Peer who sent the message.
2159  *
2160  * @return GNUNET_OK to keep the connection open,
2161  *         GNUNET_SYSERR to close it (signal serious error)
2162  */
2163 int
2164 GCC_handle_encrypted (void *cls, const struct GNUNET_PeerIdentity *peer,
2165                       const struct GNUNET_MessageHeader *message)
2166 {
2167   return handle_cadet_encrypted (peer,
2168                                 (struct GNUNET_CADET_Encrypted *)message);
2169 }
2170
2171
2172 /**
2173  * Core handler for key exchange traffic (ephemeral key, ping, pong).
2174  *
2175  * @param cls Closure (unused).
2176  * @param message Message received.
2177  * @param peer Peer who sent the message.
2178  *
2179  * @return GNUNET_OK to keep the connection open,
2180  *         GNUNET_SYSERR to close it (signal serious error)
2181  */
2182 int
2183 GCC_handle_kx (void *cls, const struct GNUNET_PeerIdentity *peer,
2184                const struct GNUNET_MessageHeader *message)
2185 {
2186   return handle_cadet_kx (peer,
2187                          (struct GNUNET_CADET_KX *) message);
2188 }
2189
2190
2191 /**
2192  * Core handler for cadet network traffic point-to-point acks.
2193  *
2194  * @param cls closure
2195  * @param message message
2196  * @param peer peer identity this notification is about
2197  *
2198  * @return GNUNET_OK to keep the connection open,
2199  *         GNUNET_SYSERR to close it (signal serious error)
2200  */
2201 int
2202 GCC_handle_ack (void *cls, const struct GNUNET_PeerIdentity *peer,
2203                 const struct GNUNET_MessageHeader *message)
2204 {
2205   struct GNUNET_CADET_ACK *msg;
2206   struct CadetConnection *c;
2207   struct CadetFlowControl *fc;
2208   GNUNET_PEER_Id id;
2209   uint32_t ack;
2210   int fwd;
2211
2212   msg = (struct GNUNET_CADET_ACK *) message;
2213   log_message (message, peer, &msg->cid);
2214   c = connection_get (&msg->cid);
2215   if (NULL == c)
2216   {
2217     GNUNET_STATISTICS_update (stats, "# ack on unknown connection", 1,
2218                               GNUNET_NO);
2219     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
2220     return GNUNET_OK;
2221   }
2222
2223   /* Is this a forward or backward ACK? */
2224   id = GNUNET_PEER_search (peer);
2225   if (GCP_get_short_id (get_next_hop (c)) == id)
2226   {
2227     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD ACK\n");
2228     fc = &c->fwd_fc;
2229     fwd = GNUNET_YES;
2230   }
2231   else if (GCP_get_short_id (get_prev_hop (c)) == id)
2232   {
2233     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK ACK\n");
2234     fc = &c->bck_fc;
2235     fwd = GNUNET_NO;
2236   }
2237   else
2238   {
2239     GNUNET_break_op (0);
2240     return GNUNET_OK;
2241   }
2242
2243   ack = ntohl (msg->ack);
2244   LOG (GNUNET_ERROR_TYPE_DEBUG, "  ACK %u (was %u)\n",
2245               ack, fc->last_ack_recv);
2246   if (GC_is_pid_bigger (ack, fc->last_ack_recv))
2247     fc->last_ack_recv = ack;
2248
2249   /* Cancel polling if the ACK is big enough. */
2250   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task &&
2251       GC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2252   {
2253     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Cancel poll\n");
2254     GNUNET_SCHEDULER_cancel (fc->poll_task);
2255     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
2256     fc->poll_time = GNUNET_TIME_UNIT_SECONDS;
2257   }
2258
2259   connection_unlock_queue (c, fwd);
2260
2261   return GNUNET_OK;
2262 }
2263
2264
2265 /**
2266  * Core handler for cadet network traffic point-to-point ack polls.
2267  *
2268  * @param cls closure
2269  * @param message message
2270  * @param peer peer identity this notification is about
2271  *
2272  * @return GNUNET_OK to keep the connection open,
2273  *         GNUNET_SYSERR to close it (signal serious error)
2274  */
2275 int
2276 GCC_handle_poll (void *cls, const struct GNUNET_PeerIdentity *peer,
2277                  const struct GNUNET_MessageHeader *message)
2278 {
2279   struct GNUNET_CADET_Poll *msg;
2280   struct CadetConnection *c;
2281   struct CadetFlowControl *fc;
2282   GNUNET_PEER_Id id;
2283   uint32_t pid;
2284   int fwd;
2285
2286   msg = (struct GNUNET_CADET_Poll *) message;
2287   log_message (message, peer, &msg->cid);
2288   c = connection_get (&msg->cid);
2289   if (NULL == c)
2290   {
2291     GNUNET_STATISTICS_update (stats, "# poll on unknown connection", 1,
2292                               GNUNET_NO);
2293     LOG (GNUNET_ERROR_TYPE_DEBUG, "POLL message on unknown connection %s!\n",
2294          GNUNET_h2s (GC_h2hc (&msg->cid)));
2295     send_broken_unknown (&msg->cid, &my_full_id, NULL, peer);
2296     return GNUNET_OK;
2297   }
2298
2299   /* Is this a forward or backward ACK?
2300    * Note: a poll should never be needed in a loopback case,
2301    * since there is no possiblility of packet loss there, so
2302    * this way of discerining FWD/BCK should not be a problem.
2303    */
2304   id = GNUNET_PEER_search (peer);
2305   if (GCP_get_short_id (get_next_hop (c)) == id)
2306   {
2307     LOG (GNUNET_ERROR_TYPE_DEBUG, "  FWD FC\n");
2308     fc = &c->fwd_fc;
2309   }
2310   else if (GCP_get_short_id (get_prev_hop (c)) == id)
2311   {
2312     LOG (GNUNET_ERROR_TYPE_DEBUG, "  BCK FC\n");
2313     fc = &c->bck_fc;
2314   }
2315   else
2316   {
2317     GNUNET_break_op (0);
2318     return GNUNET_OK;
2319   }
2320
2321   pid = ntohl (msg->pid);
2322   LOG (GNUNET_ERROR_TYPE_DEBUG, "  PID %u, OLD %u\n", pid, fc->last_pid_recv);
2323   fc->last_pid_recv = pid;
2324   fwd = fc == &c->bck_fc;
2325   GCC_send_ack (c, fwd, GNUNET_YES);
2326
2327   return GNUNET_OK;
2328 }
2329
2330
2331 /**
2332  * Send an ACK on the appropriate connection/channel, depending on
2333  * the direction and the position of the peer.
2334  *
2335  * @param c Which connection to send the hop-by-hop ACK.
2336  * @param fwd Is this a fwd ACK? (will go dest->root).
2337  * @param force Send the ACK even if suboptimal (e.g. requested by POLL).
2338  */
2339 void
2340 GCC_send_ack (struct CadetConnection *c, int fwd, int force)
2341 {
2342   unsigned int buffer;
2343
2344   LOG (GNUNET_ERROR_TYPE_DEBUG,
2345        "GMC send %s ACK on %s\n",
2346        GC_f2s (fwd), GCC_2s (c));
2347
2348   if (NULL == c)
2349   {
2350     GNUNET_break (0);
2351     return;
2352   }
2353
2354   if (GNUNET_NO != c->destroy)
2355   {
2356     LOG (GNUNET_ERROR_TYPE_DEBUG, "  being destroyed, why bother...\n");
2357     return;
2358   }
2359
2360   /* Get available buffer space */
2361   if (GCC_is_terminal (c, fwd))
2362   {
2363     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from all channels\n");
2364     buffer = GCT_get_channels_buffer (c->t);
2365   }
2366   else
2367   {
2368     LOG (GNUNET_ERROR_TYPE_DEBUG, "  getting from one connection\n");
2369     buffer = GCC_get_buffer (c, fwd);
2370   }
2371   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer available: %u\n", buffer);
2372   if (0 == buffer && GNUNET_NO == force)
2373     return;
2374
2375   /* Send available buffer space */
2376   if (GCC_is_origin (c, fwd))
2377   {
2378     GNUNET_assert (NULL != c->t);
2379     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on channels...\n");
2380     GCT_unchoke_channels (c->t);
2381   }
2382   else
2383   {
2384     LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending on connection\n");
2385     send_ack (c, buffer, fwd, force);
2386   }
2387 }
2388
2389
2390 /**
2391  * Initialize the connections subsystem
2392  *
2393  * @param c Configuration handle.
2394  */
2395 void
2396 GCC_init (const struct GNUNET_CONFIGURATION_Handle *c)
2397 {
2398   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2399   if (GNUNET_OK !=
2400       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_MSGS_QUEUE",
2401                                              &max_msgs_queue))
2402   {
2403     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2404                                "CADET", "MAX_MSGS_QUEUE", "MISSING");
2405     GNUNET_SCHEDULER_shutdown ();
2406     return;
2407   }
2408
2409   if (GNUNET_OK !=
2410       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_CONNECTIONS",
2411                                              &max_connections))
2412   {
2413     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2414                                "CADET", "MAX_CONNECTIONS", "MISSING");
2415     GNUNET_SCHEDULER_shutdown ();
2416     return;
2417   }
2418
2419   if (GNUNET_OK !=
2420       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REFRESH_CONNECTION_TIME",
2421                                            &refresh_connection_time))
2422   {
2423     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
2424                                "CADET", "REFRESH_CONNECTION_TIME", "MISSING");
2425     GNUNET_SCHEDULER_shutdown ();
2426     return;
2427   }
2428   create_connection_time = GNUNET_TIME_UNIT_SECONDS;
2429   connections = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO);
2430 }
2431
2432
2433 /**
2434  * Destroy each connection on shutdown.
2435  *
2436  * @param cls Closure (unused).
2437  * @param key Current key code (CID, unused).
2438  * @param value Value in the hash map (connection)
2439  *
2440  * @return #GNUNET_YES, because we should continue to iterate,
2441  */
2442 static int
2443 shutdown_iterator (void *cls,
2444                    const struct GNUNET_HashCode *key,
2445                    void *value)
2446 {
2447   struct CadetConnection *c = value;
2448
2449   GCC_destroy (c);
2450   return GNUNET_YES;
2451 }
2452
2453
2454 /**
2455  * Shut down the connections subsystem.
2456  */
2457 void
2458 GCC_shutdown (void)
2459 {
2460   GNUNET_CONTAINER_multihashmap_iterate (connections, &shutdown_iterator, NULL);
2461   GNUNET_CONTAINER_multihashmap_destroy (connections);
2462   connections = NULL;
2463 }
2464
2465
2466 struct CadetConnection *
2467 GCC_new (const struct GNUNET_CADET_Hash *cid,
2468          struct CadetTunnel *t,
2469          struct CadetPeerPath *p,
2470          unsigned int own_pos)
2471 {
2472   struct CadetConnection *c;
2473
2474   c = GNUNET_new (struct CadetConnection);
2475   c->id = *cid;
2476   GNUNET_assert (GNUNET_OK ==
2477                  GNUNET_CONTAINER_multihashmap_put (connections,
2478                                                     GCC_get_h (c), c,
2479                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2480   fc_init (&c->fwd_fc);
2481   fc_init (&c->bck_fc);
2482   c->fwd_fc.c = c;
2483   c->bck_fc.c = c;
2484
2485   c->t = t;
2486   GNUNET_assert (own_pos <= p->length - 1);
2487   c->own_pos = own_pos;
2488   c->path = p;
2489   p->c = c;
2490
2491   if (GNUNET_OK != register_neighbors (c))
2492   {
2493     if (0 == own_pos)
2494     {
2495       path_invalidate (c->path);
2496       c->t = NULL;
2497       c->path = NULL;
2498     }
2499     GCC_destroy (c);
2500     return NULL;
2501   }
2502
2503   return c;
2504 }
2505
2506
2507 void
2508 GCC_destroy (struct CadetConnection *c)
2509 {
2510   if (NULL == c)
2511   {
2512     GNUNET_break (0);
2513     return;
2514   }
2515
2516   if (2 == c->destroy) /* cancel queues -> GCP_queue_cancel -> q_destroy -> */
2517     return;            /* -> message_sent -> GCC_destroy. Don't loop. */
2518   c->destroy = 2;
2519
2520   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying connection %s\n", GCC_2s (c));
2521   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc's f: %p, b: %p\n",
2522        &c->fwd_fc, &c->bck_fc);
2523   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc tasks f: %u, b: %u\n",
2524        c->fwd_fc.poll_task, c->bck_fc.poll_task);
2525
2526   /* Cancel all traffic */
2527   if (NULL != c->path)
2528   {
2529     connection_cancel_queues (c, GNUNET_YES);
2530     connection_cancel_queues (c, GNUNET_NO);
2531     unregister_neighbors (c);
2532   }
2533
2534   LOG (GNUNET_ERROR_TYPE_DEBUG, " fc tasks f: %u, b: %u\n",
2535        c->fwd_fc.poll_task, c->bck_fc.poll_task);
2536
2537   /* Cancel maintainance task (keepalive/timeout) */
2538   if (NULL != c->fwd_fc.poll_msg)
2539   {
2540     GCC_cancel (c->fwd_fc.poll_msg);
2541     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL msg FWD canceled\n");
2542   }
2543   if (NULL != c->bck_fc.poll_msg)
2544   {
2545     GCC_cancel (c->bck_fc.poll_msg);
2546     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL msg BCK canceled\n");
2547   }
2548
2549   /* Delete from tunnel */
2550   if (NULL != c->t)
2551     GCT_remove_connection (c->t, c);
2552
2553   if (GNUNET_NO == GCC_is_origin (c, GNUNET_YES) && NULL != c->path)
2554     path_destroy (c->path);
2555   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_maintenance_task)
2556     GNUNET_SCHEDULER_cancel (c->fwd_maintenance_task);
2557   if (GNUNET_SCHEDULER_NO_TASK != c->bck_maintenance_task)
2558     GNUNET_SCHEDULER_cancel (c->bck_maintenance_task);
2559   if (GNUNET_SCHEDULER_NO_TASK != c->fwd_fc.poll_task)
2560   {
2561     GNUNET_SCHEDULER_cancel (c->fwd_fc.poll_task);
2562     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL FWD canceled\n");
2563   }
2564   if (GNUNET_SCHEDULER_NO_TASK != c->bck_fc.poll_task)
2565   {
2566     GNUNET_SCHEDULER_cancel (c->bck_fc.poll_task);
2567     LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL BCK canceled\n");
2568   }
2569
2570   GNUNET_break (GNUNET_YES ==
2571                 GNUNET_CONTAINER_multihashmap_remove (connections,
2572                                                       GCC_get_h (c), c));
2573
2574   GNUNET_STATISTICS_update (stats, "# connections", -1, GNUNET_NO);
2575   GNUNET_free (c);
2576 }
2577
2578 /**
2579  * Get the connection ID.
2580  *
2581  * @param c Connection to get the ID from.
2582  *
2583  * @return ID of the connection.
2584  */
2585 const struct GNUNET_CADET_Hash *
2586 GCC_get_id (const struct CadetConnection *c)
2587 {
2588   return &c->id;
2589 }
2590
2591
2592 /**
2593  * Get the connection ID.
2594  *
2595  * @param c Connection to get the ID from.
2596  *
2597  * @return ID of the connection.
2598  */
2599 const struct GNUNET_HashCode *
2600 GCC_get_h (const struct CadetConnection *c)
2601 {
2602   return GC_h2hc (&c->id);
2603 }
2604
2605
2606 /**
2607  * Get the connection path.
2608  *
2609  * @param c Connection to get the path from.
2610  *
2611  * @return path used by the connection.
2612  */
2613 const struct CadetPeerPath *
2614 GCC_get_path (const struct CadetConnection *c)
2615 {
2616   if (GNUNET_NO == c->destroy)
2617     return c->path;
2618   return NULL;
2619 }
2620
2621
2622 /**
2623  * Get the connection state.
2624  *
2625  * @param c Connection to get the state from.
2626  *
2627  * @return state of the connection.
2628  */
2629 enum CadetConnectionState
2630 GCC_get_state (const struct CadetConnection *c)
2631 {
2632   return c->state;
2633 }
2634
2635 /**
2636  * Get the connection tunnel.
2637  *
2638  * @param c Connection to get the tunnel from.
2639  *
2640  * @return tunnel of the connection.
2641  */
2642 struct CadetTunnel *
2643 GCC_get_tunnel (const struct CadetConnection *c)
2644 {
2645   return c->t;
2646 }
2647
2648
2649 /**
2650  * Get free buffer space in a connection.
2651  *
2652  * @param c Connection.
2653  * @param fwd Is query about FWD traffic?
2654  *
2655  * @return Free buffer space [0 - max_msgs_queue/max_connections]
2656  */
2657 unsigned int
2658 GCC_get_buffer (struct CadetConnection *c, int fwd)
2659 {
2660   struct CadetFlowControl *fc;
2661
2662   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2663
2664   return (fc->queue_max - fc->queue_n);
2665 }
2666
2667 /**
2668  * Get how many messages have we allowed to send to us from a direction.
2669  *
2670  * @param c Connection.
2671  * @param fwd Are we asking about traffic from FWD (BCK messages)?
2672  *
2673  * @return last_ack_sent - last_pid_recv
2674  */
2675 unsigned int
2676 GCC_get_allowed (struct CadetConnection *c, int fwd)
2677 {
2678   struct CadetFlowControl *fc;
2679
2680   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2681   if (GC_is_pid_bigger(fc->last_pid_recv, fc->last_ack_sent))
2682   {
2683     return 0;
2684   }
2685   return (fc->last_ack_sent - fc->last_pid_recv);
2686 }
2687
2688 /**
2689  * Get messages queued in a connection.
2690  *
2691  * @param c Connection.
2692  * @param fwd Is query about FWD traffic?
2693  *
2694  * @return Number of messages queued.
2695  */
2696 unsigned int
2697 GCC_get_qn (struct CadetConnection *c, int fwd)
2698 {
2699   struct CadetFlowControl *fc;
2700
2701   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2702
2703   return fc->queue_n;
2704 }
2705
2706
2707 /**
2708  * Get next PID to use.
2709  *
2710  * @param c Connection.
2711  * @param fwd Is query about FWD traffic?
2712  *
2713  * @return Last PID used + 1.
2714  */
2715 unsigned int
2716 GCC_get_pid (struct CadetConnection *c, int fwd)
2717 {
2718   struct CadetFlowControl *fc;
2719
2720   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2721
2722   return fc->last_pid_sent + 1;
2723 }
2724
2725
2726 /**
2727  * Allow the connection to advertise a buffer of the given size.
2728  *
2729  * The connection will send an @c fwd ACK message (so: in direction !fwd)
2730  * allowing up to last_pid_recv + buffer.
2731  *
2732  * @param c Connection.
2733  * @param buffer How many more messages the connection can accept.
2734  * @param fwd Is this about FWD traffic? (The ack will go dest->root).
2735  */
2736 void
2737 GCC_allow (struct CadetConnection *c, unsigned int buffer, int fwd)
2738 {
2739   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowing %s %u messages %s\n",
2740        GCC_2s (c), buffer, GC_f2s (fwd));
2741   send_ack (c, buffer, fwd, GNUNET_NO);
2742 }
2743
2744
2745 /**
2746  * Notify other peers on a connection of a broken link. Mark connections
2747  * to destroy after all traffic has been sent.
2748  *
2749  * @param c Connection on which there has been a disconnection.
2750  * @param peer Peer that disconnected.
2751  */
2752 void
2753 GCC_notify_broken (struct CadetConnection *c,
2754                    struct CadetPeer *peer)
2755 {
2756   int fwd;
2757
2758   LOG (GNUNET_ERROR_TYPE_DEBUG,
2759        " notify broken on %s due to %s disconnect\n",
2760        GCC_2s (c), GCP_2s (peer));
2761
2762   fwd = peer == get_prev_hop (c);
2763
2764   if (GNUNET_YES == GCC_is_terminal (c, fwd))
2765   {
2766     /* Local shutdown, no one to notify about this. */
2767     GCC_destroy (c);
2768     return;
2769   }
2770   if (GNUNET_NO == c->destroy)
2771     send_broken (c, &my_full_id, GCP_get_id (peer), fwd);
2772
2773   /* Connection will have at least one pending message
2774    * (the one we just scheduled), so no point in checking whether to
2775    * destroy immediately. */
2776   c->destroy = GNUNET_YES;
2777   c->state = CADET_CONNECTION_DESTROYED;
2778
2779   /**
2780    * Cancel all queues, if no message is left, connection will be destroyed.
2781    */
2782   connection_cancel_queues (c, !fwd);
2783
2784   return;
2785 }
2786
2787
2788 /**
2789  * Is this peer the first one on the connection?
2790  *
2791  * @param c Connection.
2792  * @param fwd Is this about fwd traffic?
2793  *
2794  * @return #GNUNET_YES if origin, #GNUNET_NO if relay/terminal.
2795  */
2796 int
2797 GCC_is_origin (struct CadetConnection *c, int fwd)
2798 {
2799   if (!fwd && c->path->length - 1 == c->own_pos )
2800     return GNUNET_YES;
2801   if (fwd && 0 == c->own_pos)
2802     return GNUNET_YES;
2803   return GNUNET_NO;
2804 }
2805
2806
2807 /**
2808  * Is this peer the last one on the connection?
2809  *
2810  * @param c Connection.
2811  * @param fwd Is this about fwd traffic?
2812  *            Note that the ROOT is the terminal for BCK traffic!
2813  *
2814  * @return #GNUNET_YES if terminal, #GNUNET_NO if relay/origin.
2815  */
2816 int
2817 GCC_is_terminal (struct CadetConnection *c, int fwd)
2818 {
2819   return GCC_is_origin (c, !fwd);
2820 }
2821
2822
2823 /**
2824  * See if we are allowed to send by the next hop in the given direction.
2825  *
2826  * @param c Connection.
2827  * @param fwd Is this about fwd traffic?
2828  *
2829  * @return #GNUNET_YES in case it's OK to send.
2830  */
2831 int
2832 GCC_is_sendable (struct CadetConnection *c, int fwd)
2833 {
2834   struct CadetFlowControl *fc;
2835
2836   LOG (GNUNET_ERROR_TYPE_DEBUG, " checking sendability of %s traffic on %s\n",
2837        GC_f2s (fwd), GCC_2s (c));
2838   if (NULL == c)
2839   {
2840     GNUNET_break (0);
2841     return GNUNET_YES;
2842   }
2843   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2844   LOG (GNUNET_ERROR_TYPE_DEBUG,
2845        " last ack recv: %u, last pid sent: %u\n",
2846        fc->last_ack_recv, fc->last_pid_sent);
2847   if (GC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
2848   {
2849     LOG (GNUNET_ERROR_TYPE_DEBUG, " sendable\n");
2850     return GNUNET_YES;
2851   }
2852   LOG (GNUNET_ERROR_TYPE_DEBUG, " not sendable\n");
2853   return GNUNET_NO;
2854 }
2855
2856
2857 /**
2858  * Check if this connection is a direct one (never trim a direct connection).
2859  *
2860  * @param c Connection.
2861  *
2862  * @return #GNUNET_YES in case it's a direct connection, #GNUNET_NO otherwise.
2863  */
2864 int
2865 GCC_is_direct (struct CadetConnection *c)
2866 {
2867   return (c->path->length == 2) ? GNUNET_YES : GNUNET_NO;
2868 }
2869
2870 /**
2871  * Sends an already built message on a connection, properly registering
2872  * all used resources.
2873  *
2874  * @param message Message to send. Function makes a copy of it.
2875  *                If message is not hop-by-hop, decrements TTL of copy.
2876  * @param payload_type Type of payload, in case the message is encrypted.
2877  * @param c Connection on which this message is transmitted.
2878  * @param fwd Is this a fwd message?
2879  * @param force Force the connection to accept the message (buffer overfill).
2880  * @param cont Continuation called once message is sent. Can be NULL.
2881  * @param cont_cls Closure for @c cont.
2882  *
2883  * @return Handle to cancel the message before it's sent.
2884  *         NULL on error or if @c cont is NULL.
2885  *         Invalid on @c cont call.
2886  */
2887 struct CadetConnectionQueue *
2888 GCC_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2889                            uint16_t payload_type, uint32_t payload_id,
2890                            struct CadetConnection *c, int fwd, int force,
2891                            GCC_sent cont, void *cont_cls)
2892 {
2893   struct CadetFlowControl *fc;
2894   struct CadetConnectionQueue *q;
2895   void *data;
2896   size_t size;
2897   uint16_t type;
2898   int droppable;
2899
2900   size = ntohs (message->size);
2901   data = GNUNET_malloc (size);
2902   memcpy (data, message, size);
2903   type = ntohs (message->type);
2904   LOG (GNUNET_ERROR_TYPE_INFO, "--> %s (%s %u) on connection %s (%u bytes)\n",
2905        GC_m2s (type), GC_m2s (payload_type), payload_id, GCC_2s (c), size);
2906
2907   fc = fwd ? &c->fwd_fc : &c->bck_fc;
2908   droppable = GNUNET_NO == force;
2909   switch (type)
2910   {
2911     struct GNUNET_CADET_Encrypted *emsg;
2912     struct GNUNET_CADET_KX        *kmsg;
2913     struct GNUNET_CADET_ACK       *amsg;
2914     struct GNUNET_CADET_Poll      *pmsg;
2915     struct GNUNET_CADET_ConnectionDestroy *dmsg;
2916     struct GNUNET_CADET_ConnectionBroken  *bmsg;
2917     uint32_t ttl;
2918
2919     case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
2920       emsg = (struct GNUNET_CADET_Encrypted *) data;
2921       ttl = ntohl (emsg->ttl);
2922       if (0 == ttl)
2923       {
2924         GNUNET_break_op (0);
2925         GNUNET_free (data);
2926         return NULL;
2927       }
2928       emsg->cid = c->id;
2929       emsg->ttl = htonl (ttl - 1);
2930       emsg->pid = htonl (0);
2931       LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
2932       LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid sent %u\n", fc->last_pid_sent);
2933       LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack recv %u\n", fc->last_ack_recv);
2934       if (GNUNET_YES == droppable)
2935       {
2936         fc->queue_n++;
2937       }
2938       else
2939       {
2940         LOG (GNUNET_ERROR_TYPE_DEBUG, "  not droppable, Q_N stays the same\n");
2941       }
2942       if (GC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
2943       {
2944         GCC_start_poll (c, fwd);
2945       }
2946       break;
2947
2948     case GNUNET_MESSAGE_TYPE_CADET_KX:
2949       kmsg = (struct GNUNET_CADET_KX *) data;
2950       kmsg->cid = c->id;
2951       break;
2952
2953     case GNUNET_MESSAGE_TYPE_CADET_ACK:
2954       amsg = (struct GNUNET_CADET_ACK *) data;
2955       amsg->cid = c->id;
2956       LOG (GNUNET_ERROR_TYPE_DEBUG, " ack %u\n", ntohl (amsg->ack));
2957       droppable = GNUNET_NO;
2958       break;
2959
2960     case GNUNET_MESSAGE_TYPE_CADET_POLL:
2961       pmsg = (struct GNUNET_CADET_Poll *) data;
2962       pmsg->cid = c->id;
2963       LOG (GNUNET_ERROR_TYPE_DEBUG, " poll %u\n", ntohl (pmsg->pid));
2964       droppable = GNUNET_NO;
2965       break;
2966
2967     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
2968       dmsg = (struct GNUNET_CADET_ConnectionDestroy *) data;
2969       dmsg->cid = c->id;
2970       break;
2971
2972     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
2973       bmsg = (struct GNUNET_CADET_ConnectionBroken *) data;
2974       bmsg->cid = c->id;
2975       break;
2976
2977     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
2978       GNUNET_break (0);
2979       /* falltrough */
2980     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
2981     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
2982       break;
2983
2984     default:
2985       GNUNET_break (0);
2986       GNUNET_free (data);
2987       return NULL;
2988   }
2989
2990   if (fc->queue_n > fc->queue_max && droppable)
2991   {
2992     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
2993                               1, GNUNET_NO);
2994     GNUNET_break (0);
2995     LOG (GNUNET_ERROR_TYPE_DEBUG,
2996                 "queue full: %u/%u\n",
2997                 fc->queue_n, fc->queue_max);
2998     if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == type)
2999     {
3000       fc->queue_n--;
3001     }
3002     GNUNET_free (data);
3003     return NULL; /* Drop this message */
3004   }
3005
3006   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u\n", c, c->pending_messages);
3007   c->pending_messages++;
3008
3009   q = GNUNET_new (struct CadetConnectionQueue);
3010   q->forced = !droppable;
3011   q->q = GCP_queue_add (get_hop (c, fwd), data, type, payload_type, payload_id,
3012                         size, c, fwd, &conn_message_sent, q);
3013   if (NULL == q->q)
3014   {
3015     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING dropping msg on %s\n", GCC_2s (c));
3016     GNUNET_free (data);
3017     GNUNET_free (q);
3018     return NULL;
3019   }
3020   q->cont = cont;
3021   q->cont_cls = cont_cls;
3022   return (NULL == cont) ? NULL : q;
3023 }
3024
3025
3026 /**
3027  * Cancel a previously sent message while it's in the queue.
3028  *
3029  * ONLY can be called before the continuation given to the send function
3030  * is called. Once the continuation is called, the message is no longer in the
3031  * queue.
3032  *
3033  * @param q Handle to the queue.
3034  */
3035 void
3036 GCC_cancel (struct CadetConnectionQueue *q)
3037 {
3038   LOG (GNUNET_ERROR_TYPE_DEBUG, "!  GMC cancel message\n");
3039
3040   /* queue destroy calls message_sent, which calls q->cont and frees q */
3041   GCP_queue_destroy (q->q, GNUNET_YES, GNUNET_NO, 0);
3042 }
3043
3044
3045 /**
3046  * Sends a CREATE CONNECTION message for a path to a peer.
3047  * Changes the connection and tunnel states if necessary.
3048  *
3049  * @param connection Connection to create.
3050  */
3051 void
3052 GCC_send_create (struct CadetConnection *connection)
3053 {
3054   enum CadetTunnelCState state;
3055   size_t size;
3056
3057   size = sizeof (struct GNUNET_CADET_ConnectionCreate);
3058   size += connection->path->length * sizeof (struct GNUNET_PeerIdentity);
3059
3060   LOG (GNUNET_ERROR_TYPE_INFO, "===> %s on connection %s  (%u bytes)\n",
3061        GC_m2s (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE),
3062        GCC_2s (connection), size);
3063   LOG (GNUNET_ERROR_TYPE_DEBUG, "  C_P+ %p %u (create)\n",
3064        connection, connection->pending_messages);
3065   connection->pending_messages++;
3066
3067   connection->maintenance_q =
3068     GCP_queue_add (get_next_hop (connection), NULL,
3069                    GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, 0, 0,
3070                    size, connection, GNUNET_YES, &conn_message_sent, NULL);
3071
3072   state = GCT_get_cstate (connection->t);
3073   if (CADET_TUNNEL_SEARCHING == state || CADET_TUNNEL_NEW == state)
3074     GCT_change_cstate (connection->t, CADET_TUNNEL_WAITING);
3075   if (CADET_CONNECTION_NEW == connection->state)
3076     connection_change_state (connection, CADET_CONNECTION_SENT);
3077 }
3078
3079
3080 /**
3081  * Send a message to all peers in this connection that the connection
3082  * is no longer valid.
3083  *
3084  * If some peer should not receive the message, it should be zero'ed out
3085  * before calling this function.
3086  *
3087  * @param c The connection whose peers to notify.
3088  */
3089 void
3090 GCC_send_destroy (struct CadetConnection *c)
3091 {
3092   struct GNUNET_CADET_ConnectionDestroy msg;
3093
3094   if (GNUNET_YES == c->destroy)
3095     return;
3096
3097   msg.header.size = htons (sizeof (msg));
3098   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY);
3099   msg.cid = c->id;
3100   LOG (GNUNET_ERROR_TYPE_DEBUG,
3101               "  sending connection destroy for connection %s\n",
3102               GCC_2s (c));
3103
3104   if (GNUNET_NO == GCC_is_terminal (c, GNUNET_YES))
3105     GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg.header, 0, 0, c,
3106                                                       GNUNET_YES, GNUNET_YES,
3107                                                       NULL, NULL));
3108   if (GNUNET_NO == GCC_is_terminal (c, GNUNET_NO))
3109     GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg.header, 0, 0, c,
3110                                                       GNUNET_NO, GNUNET_YES,
3111                                                       NULL, NULL));
3112   c->destroy = GNUNET_YES;
3113   c->state = CADET_CONNECTION_DESTROYED;
3114 }
3115
3116
3117 /**
3118  * @brief Start a polling timer for the connection.
3119  *
3120  * When a neighbor does not accept more traffic on the connection it could be
3121  * caused by a simple congestion or by a lost ACK. Polling enables to check
3122  * for the lastest ACK status for a connection.
3123  *
3124  * @param c Connection.
3125  * @param fwd Should we poll in the FWD direction?
3126  */
3127 void
3128 GCC_start_poll (struct CadetConnection *c, int fwd)
3129 {
3130   struct CadetFlowControl *fc;
3131
3132   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3133   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL %s requested\n",
3134        GC_f2s (fwd));
3135   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task || NULL != fc->poll_msg)
3136   {
3137     LOG (GNUNET_ERROR_TYPE_DEBUG, " ***   not needed (%u, %p)\n",
3138          fc->poll_task, fc->poll_msg);
3139     return;
3140   }
3141   LOG (GNUNET_ERROR_TYPE_DEBUG, " *** POLL started on request\n");
3142   fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
3143                                                 &connection_poll,
3144                                                 fc);
3145 }
3146
3147
3148 /**
3149  * @brief Stop polling a connection for ACKs.
3150  *
3151  * Once we have enough ACKs for future traffic, polls are no longer necessary.
3152  *
3153  * @param c Connection.
3154  * @param fwd Should we stop the poll in the FWD direction?
3155  */
3156 void
3157 GCC_stop_poll (struct CadetConnection *c, int fwd)
3158 {
3159   struct CadetFlowControl *fc;
3160
3161   fc = fwd ? &c->fwd_fc : &c->bck_fc;
3162   if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
3163   {
3164     GNUNET_SCHEDULER_cancel (fc->poll_task);
3165     fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
3166   }
3167 }
3168
3169 /**
3170  * Get a (static) string for a connection.
3171  *
3172  * @param c Connection.
3173  */
3174 const char *
3175 GCC_2s (const struct CadetConnection *c)
3176 {
3177   if (NULL == c)
3178     return "NULL";
3179
3180   if (NULL != c->t)
3181   {
3182     static char buf[128];
3183
3184     sprintf (buf, "%s (->%s)",
3185              GNUNET_h2s (GC_h2hc (GCC_get_id (c))), GCT_2s (c->t));
3186     return buf;
3187   }
3188   return GNUNET_h2s (GC_h2hc (&c->id));
3189 }
3190
3191
3192 /**
3193  * Log all possible info about the connection state.
3194  *
3195  * @param c Connection to debug.
3196  * @param level Debug level to use.
3197  */
3198 void
3199 GCC_debug (const struct CadetConnection *c, enum GNUNET_ErrorType level)
3200 {
3201   int do_log;
3202   char *s;
3203
3204   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3205                                        "cadet-con",
3206                                        __FILE__, __FUNCTION__, __LINE__);
3207   if (0 == do_log)
3208     return;
3209
3210   if (NULL == c)
3211   {
3212     LOG2 (level, "CCC DEBUG NULL CONNECTION\n");
3213     return;
3214   }
3215
3216   LOG2 (level, "CCC DEBUG CONNECTION %s\n", GCC_2s (c));
3217   s = path_2s (c->path);
3218   LOG2 (level, "CCC  path %s, own pos: %u\n", s, c->own_pos);
3219   GNUNET_free (s);
3220   LOG2 (level, "CCC  state: %s, destroy: %u\n",
3221         GCC_state2s (c->state), c->destroy);
3222   LOG2 (level, "CCC  pending messages: %u\n", c->pending_messages);
3223   if (NULL != c->perf)
3224     LOG2 (level, "CCC  us/byte: %f\n", c->perf->avg);
3225
3226   LOG2 (level, "CCC  FWD flow control:\n");
3227   LOG2 (level, "CCC   queue: %u/%u\n", c->fwd_fc.queue_n, c->fwd_fc.queue_max);
3228   LOG2 (level, "CCC   last PID sent: %5u, recv: %5u\n",
3229         c->fwd_fc.last_pid_sent, c->fwd_fc.last_pid_recv);
3230   LOG2 (level, "CCC   last ACK sent: %5u, recv: %5u\n",
3231         c->fwd_fc.last_ack_sent, c->fwd_fc.last_ack_recv);
3232   LOG2 (level, "CCC   POLL: task %d, msg  %p, msg_ack %p)\n",
3233         c->fwd_fc.poll_task, c->fwd_fc.poll_msg, c->fwd_fc.ack_msg);
3234
3235   LOG2 (level, "CCC  BCK flow control:\n");
3236   LOG2 (level, "CCC   queue: %u/%u\n", c->bck_fc.queue_n, c->bck_fc.queue_max);
3237   LOG2 (level, "CCC   last PID sent: %5u, recv: %5u\n",
3238         c->bck_fc.last_pid_sent, c->bck_fc.last_pid_recv);
3239   LOG2 (level, "CCC   last ACK sent: %5u, recv: %5u\n",
3240         c->bck_fc.last_ack_sent, c->bck_fc.last_ack_recv);
3241   LOG2 (level, "CCC   POLL: task %d, msg  %p, msg_ack %p)\n",
3242         c->bck_fc.poll_task, c->bck_fc.poll_msg, c->bck_fc.ack_msg);
3243
3244   LOG2 (level, "CCC DEBUG CONNECTION END\n");
3245 }
3246