- refactor key generation, cache peers ephemeral key to create new keys immediately
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_tunnel.c
1 /*
2      This file is part of GNUnet.
3      (C) 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 #include "platform.h"
22 #include "gnunet_util_lib.h"
23
24 #include "gnunet_signatures.h"
25 #include "gnunet_statistics_service.h"
26
27 #include "cadet_protocol.h"
28 #include "cadet_path.h"
29
30 #include "gnunet-service-cadet_tunnel.h"
31 #include "gnunet-service-cadet_connection.h"
32 #include "gnunet-service-cadet_channel.h"
33 #include "gnunet-service-cadet_peer.h"
34
35 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
36
37 #define REKEY_WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
38
39 #define CONNECTIONS_PER_TUNNEL 3
40
41 /******************************************************************************/
42 /********************************   STRUCTS  **********************************/
43 /******************************************************************************/
44
45 struct CadetTChannel
46 {
47   struct CadetTChannel *next;
48   struct CadetTChannel *prev;
49   struct CadetChannel *ch;
50 };
51
52
53 /**
54  * Connection list and metadata.
55  */
56 struct CadetTConnection
57 {
58   /**
59    * Next in DLL.
60    */
61   struct CadetTConnection *next;
62
63   /**
64    * Prev in DLL.
65    */
66   struct CadetTConnection *prev;
67
68   /**
69    * Connection handle.
70    */
71   struct CadetConnection *c;
72
73   /**
74    * Creation time, to keep oldest connection alive.
75    */
76   struct GNUNET_TIME_Absolute created;
77
78   /**
79    * Connection throughput, to keep fastest connection alive.
80    */
81   uint32_t throughput;
82 };
83
84 /**
85  * Structure used during a Key eXchange.
86  */
87 struct CadetTunnelKXCtx
88 {
89   /**
90    * Encryption ("our") old key, for encrypting traffic sent by us
91    * end before the key exchange is finished or times out.
92    */
93   struct GNUNET_CRYPTO_SymmetricSessionKey e_key_old;
94
95   /**
96    * Decryption ("their") old key, for decrypting traffic sent by the
97    * other end before the key exchange started.
98    */
99   struct GNUNET_CRYPTO_SymmetricSessionKey d_key_old;
100
101   /**
102    * Challenge to send in a ping and expect in the pong.
103    */
104   uint32_t challenge;
105
106   /**
107    * When the rekey started. One minute after this the new key will be used.
108    */
109   struct GNUNET_TIME_Absolute rekey_start_time;
110 };
111
112 /**
113  * Struct containing all information regarding a tunnel to a peer.
114  */
115 struct CadetTunnel
116 {
117     /**
118      * Endpoint of the tunnel.
119      */
120   struct CadetPeer *peer;
121
122     /**
123      * State of the tunnel connectivity.
124      */
125   enum CadetTunnelCState cstate;
126
127   /**
128    * State of the tunnel encryption.
129    */
130   enum CadetTunnelEState estate;
131
132   /**
133    * Key eXchange context.
134    */
135   struct CadetTunnelKXCtx *kx_ctx;
136
137   /**
138    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own ephemeral
139    * key changes.
140    */
141   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
142
143   /**
144    * Encryption ("our") key.
145    */
146   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
147
148   /**
149    * Decryption ("their") key.
150    */
151   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
152
153   /**
154    * Task to start the rekey process.
155    */
156   GNUNET_SCHEDULER_TaskIdentifier rekey_task;
157
158   /**
159    * Paths that are actively used to reach the destination peer.
160    */
161   struct CadetTConnection *connection_head;
162   struct CadetTConnection *connection_tail;
163
164   /**
165    * Next connection number.
166    */
167   uint32_t next_cid;
168
169   /**
170    * Channels inside this tunnel.
171    */
172   struct CadetTChannel *channel_head;
173   struct CadetTChannel *channel_tail;
174
175   /**
176    * Channel ID for the next created channel.
177    */
178   CADET_ChannelNumber next_chid;
179
180   /**
181    * Destroy flag: if true, destroy on last message.
182    */
183   GNUNET_SCHEDULER_TaskIdentifier destroy_task;
184
185   /**
186    * Queued messages, to transmit once tunnel gets connected.
187    */
188   struct CadetTunnelDelayed *tq_head;
189   struct CadetTunnelDelayed *tq_tail;
190 };
191
192
193 /**
194  * Struct used to save messages in a non-ready tunnel to send once connected.
195  */
196 struct CadetTunnelDelayed
197 {
198   /**
199    * DLL
200    */
201   struct CadetTunnelDelayed *next;
202   struct CadetTunnelDelayed *prev;
203
204   /**
205    * Tunnel.
206    */
207   struct CadetTunnel *t;
208
209   /**
210    * Tunnel queue given to the channel to cancel request. Update on send_queued.
211    */
212   struct CadetTunnelQueue *tq;
213
214   /**
215    * Message to send.
216    */
217   /* struct GNUNET_MessageHeader *msg; */
218 };
219
220
221 /**
222  * Handle for messages queued but not yet sent.
223  */
224 struct CadetTunnelQueue
225 {
226   /**
227    * Connection queue handle, to cancel if necessary.
228    */
229   struct CadetConnectionQueue *cq;
230
231   /**
232    * Handle in case message hasn't been given to a connection yet.
233    */
234   struct CadetTunnelDelayed *tqd;
235
236   /**
237    * Continuation to call once sent.
238    */
239   GCT_sent cont;
240
241   /**
242    * Closure for @c cont.
243    */
244   void *cont_cls;
245 };
246
247
248 /******************************************************************************/
249 /*******************************   GLOBALS  ***********************************/
250 /******************************************************************************/
251
252 /**
253  * Global handle to the statistics service.
254  */
255 extern struct GNUNET_STATISTICS_Handle *stats;
256
257 /**
258  * Local peer own ID (memory efficient handle).
259  */
260 extern GNUNET_PEER_Id myid;
261
262 /**
263  * Local peer own ID (full value).
264  */
265 extern struct GNUNET_PeerIdentity my_full_id;
266
267
268 /**
269  * Don't try to recover tunnels if shutting down.
270  */
271 extern int shutting_down;
272
273
274 /**
275  * Set of all tunnels, in order to trigger a new exchange on rekey.
276  * Indexed by peer's ID.
277  */
278 static struct GNUNET_CONTAINER_MultiPeerMap *tunnels;
279
280 /**
281  * Default TTL for payload packets.
282  */
283 static unsigned long long default_ttl;
284
285 /**
286  * Own private key.
287  */
288 const static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
289
290 /**
291  * Own ephemeral private key.
292  */
293 static struct GNUNET_CRYPTO_EcdhePrivateKey *my_ephemeral_key;
294
295 /**
296  * Cached message used to perform a key exchange.
297  */
298 static struct GNUNET_CADET_KX_Ephemeral kx_msg;
299
300 /**
301  * Task to generate a new ephemeral key.
302  */
303 static GNUNET_SCHEDULER_TaskIdentifier rekey_task;
304
305 /**
306  * Rekey period.
307  */
308 static struct GNUNET_TIME_Relative rekey_period;
309
310 /******************************************************************************/
311 /********************************   STATIC  ***********************************/
312 /******************************************************************************/
313
314 /**
315  * Get string description for tunnel connectivity state.
316  *
317  * @param cs Tunnel state.
318  *
319  * @return String representation.
320  */
321 static const char *
322 cstate2s (enum CadetTunnelCState cs)
323 {
324   static char buf[128];
325
326   switch (cs)
327   {
328     case CADET_TUNNEL3_NEW:
329       return "CADET_TUNNEL3_NEW";
330     case CADET_TUNNEL3_SEARCHING:
331       return "CADET_TUNNEL3_SEARCHING";
332     case CADET_TUNNEL3_WAITING:
333       return "CADET_TUNNEL3_WAITING";
334     case CADET_TUNNEL3_READY:
335       return "CADET_TUNNEL3_READY";
336
337     default:
338       sprintf (buf, "%u (UNKNOWN STATE)", cs);
339       return buf;
340   }
341   return "";
342 }
343
344
345 /**
346  * Get string description for tunnel encryption state.
347  *
348  * @param es Tunnel state.
349  *
350  * @return String representation.
351  */
352 static const char *
353 estate2s (enum CadetTunnelEState es)
354 {
355   static char buf[128];
356
357   switch (es)
358   {
359     case CADET_TUNNEL3_KEY_UNINITIALIZED:
360       return "CADET_TUNNEL3_KEY_UNINITIALIZED";
361     case CADET_TUNNEL3_KEY_SENT:
362       return "CADET_TUNNEL3_KEY_SENT";
363     case CADET_TUNNEL3_KEY_PING:
364       return "CADET_TUNNEL3_KEY_PING";
365     case CADET_TUNNEL3_KEY_OK:
366       return "CADET_TUNNEL3_KEY_OK";
367
368     default:
369       sprintf (buf, "%u (UNKNOWN STATE)", es);
370       return buf;
371   }
372   return "";
373 }
374
375
376 /**
377  * @brief Check if tunnel is ready to send traffic.
378  *
379  * Tunnel must be connected and with encryption correctly set up.
380  *
381  * @param t Tunnel to check.
382  *
383  * @return #GNUNET_YES if ready, #GNUNET_NO otherwise
384  */
385 static int
386 is_ready (struct CadetTunnel *t)
387 {
388   int ready;
389
390   GCT_debug (t);
391   ready = (CADET_TUNNEL3_READY == t->cstate && CADET_TUNNEL3_KEY_OK == t->estate);
392   ready = ready || GCT_is_loopback (t);
393   return ready;
394 }
395
396
397 /**
398  * Ephemeral key message purpose size.
399  *
400  * @return Size of the part of the ephemeral key message that must be signed.
401  */
402 size_t
403 ephemeral_purpose_size (void)
404 {
405   return sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
406          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
407          sizeof (struct GNUNET_TIME_AbsoluteNBO) +
408          sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) +
409          sizeof (struct GNUNET_PeerIdentity);
410 }
411
412
413 /**
414  * Size of the encrypted part of a ping message.
415  *
416  * @return Size of the encrypted part of a ping message.
417  */
418 size_t
419 ping_encryption_size (void)
420 {
421   return sizeof (struct GNUNET_PeerIdentity) + sizeof (uint32_t);
422 }
423
424
425 /**
426  * Get the channel's buffer. ONLY FOR NON-LOOPBACK CHANNELS!!
427  *
428  * @param tch Tunnel's channel handle.
429  *
430  * @return Amount of messages the channel can still buffer towards the client.
431  */
432 static unsigned int
433 get_channel_buffer (const struct CadetTChannel *tch)
434 {
435   int fwd;
436
437   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
438   fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
439
440   return GCCH_get_buffer (tch->ch, fwd);
441 }
442
443
444 /**
445  * Get the channel's allowance status.
446  *
447  * @param tch Tunnel's channel handle.
448  *
449  * @return #GNUNET_YES if we allowed the client to send data to us.
450  */
451 static int
452 get_channel_allowed (const struct CadetTChannel *tch)
453 {
454   int fwd;
455
456   /* If channel is outgoing, is origin in the FWD direction and fwd is YES */
457   fwd = GCCH_is_origin (tch->ch, GNUNET_YES);
458
459   return GCCH_get_allowed (tch->ch, fwd);
460 }
461
462
463 /**
464  * Get the connection's buffer.
465  *
466  * @param tc Tunnel's connection handle.
467  *
468  * @return Amount of messages the connection can still buffer.
469  */
470 static unsigned int
471 get_connection_buffer (const struct CadetTConnection *tc)
472 {
473   int fwd;
474
475   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
476   fwd = GCC_is_origin (tc->c, GNUNET_YES);
477
478   return GCC_get_buffer (tc->c, fwd);
479 }
480
481
482 /**
483  * Get the connection's allowance.
484  *
485  * @param tc Tunnel's connection handle.
486  *
487  * @return Amount of messages we have allowed the next peer to send us.
488  */
489 static unsigned int
490 get_connection_allowed (const struct CadetTConnection *tc)
491 {
492   int fwd;
493
494   /* If connection is outgoing, is origin in the FWD direction and fwd is YES */
495   fwd = GCC_is_origin (tc->c, GNUNET_YES);
496
497   return GCC_get_allowed (tc->c, fwd);
498 }
499
500
501 /**
502  * Check that a ephemeral key message s well formed and correctly signed.
503  *
504  * @param t Tunnel on which the message came.
505  * @param msg The ephemeral key message.
506  *
507  * @return GNUNET_OK if message is fine, GNUNET_SYSERR otherwise.
508  */
509 int
510 check_ephemeral (struct CadetTunnel *t,
511                  const struct GNUNET_CADET_KX_Ephemeral *msg)
512 {
513   /* Check message size */
514   if (ntohs (msg->header.size) != sizeof (struct GNUNET_CADET_KX_Ephemeral))
515     return GNUNET_SYSERR;
516
517   /* Check signature size */
518   if (ntohl (msg->purpose.size) != ephemeral_purpose_size ())
519     return GNUNET_SYSERR;
520
521   /* Check origin */
522   if (0 != memcmp (&msg->origin_identity,
523                    GCP_get_id (t->peer),
524                    sizeof (struct GNUNET_PeerIdentity)))
525     return GNUNET_SYSERR;
526
527   /* Check signature */
528   if (GNUNET_OK !=
529       GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_KX,
530                                   &msg->purpose,
531                                   &msg->signature,
532                                   &msg->origin_identity.public_key))
533     return GNUNET_SYSERR;
534
535   return GNUNET_OK;
536 }
537
538
539 /**
540  * Encrypt data with the tunnel key.
541  *
542  * @param t Tunnel whose key to use.
543  * @param dst Destination for the encrypted data.
544  * @param src Source of the plaintext. Can overlap with @c dst.
545  * @param size Size of the plaintext.
546  * @param iv Initialization Vector to use.
547  */
548 static int
549 t_encrypt (struct CadetTunnel *t,
550            void *dst, const void *src,
551            size_t size, uint32_t iv)
552 {
553   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
554   size_t out_size;
555
556   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_encrypt start\n");
557   GNUNET_CRYPTO_symmetric_derive_iv (&siv, &t->e_key, &iv, sizeof (iv), NULL);
558   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_encrypt IV derived\n");
559   out_size = GNUNET_CRYPTO_symmetric_encrypt (src, size, &t->e_key, &siv, dst);
560   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_encrypt end\n");
561
562   return out_size;
563 }
564
565
566 /**
567  * Decrypt data with the tunnel key.
568  *
569  * @param t Tunnel whose key to use.
570  * @param dst Destination for the plaintext.
571  * @param src Source of the encrypted data. Can overlap with @c dst.
572  * @param size Size of the encrypted data.
573  * @param iv Initialization Vector to use.
574  */
575 static int
576 t_decrypt (struct CadetTunnel *t,
577            void *dst, const void *src,
578            size_t size, uint32_t iv)
579 {
580   struct GNUNET_CRYPTO_SymmetricInitializationVector siv;
581   struct GNUNET_CRYPTO_SymmetricSessionKey *key;
582   size_t out_size;
583
584   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_decrypt start\n");
585   if (t->estate == CADET_TUNNEL3_KEY_OK || t->estate == CADET_TUNNEL3_KEY_PING)
586   {
587     key = &t->d_key;
588   }
589   else if (NULL != t->kx_ctx)
590   {
591     key = &t->kx_ctx->d_key_old;
592   }
593   else
594   {
595     GNUNET_STATISTICS_update (stats, "# non decryptable data", 1, GNUNET_NO);
596     LOG (GNUNET_ERROR_TYPE_DEBUG,
597          "WARNING got data on %s without a valid key\n",
598          GCT_2s (t));
599     GCT_debug (t);
600     return 0;
601   }
602
603   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_decrypt iv\n");
604   GNUNET_CRYPTO_symmetric_derive_iv (&siv, key, &iv, sizeof (iv), NULL);
605   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_decrypt iv done\n");
606   out_size = GNUNET_CRYPTO_symmetric_decrypt (src, size, key, &siv, dst);
607   LOG (GNUNET_ERROR_TYPE_DEBUG, "  t_decrypt end\n");
608
609   return out_size;
610 }
611
612
613 /**
614  * Create key material by doing ECDH on the local and remote ephemeral keys.
615  *
616  * @param key_material Where to store the key material.
617  * @param ephemeral_key Peer's public ephemeral key.
618  */
619 void
620 derive_key_material (struct GNUNET_HashCode *key_material,
621                      const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key)
622 {
623   if (GNUNET_OK !=
624       GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key,
625                               ephemeral_key,
626                               key_material))
627   {
628     GNUNET_break (0);
629   }
630 }
631
632
633 /**
634  * Create a symmetic key from the identities of both ends and the key material
635  * from ECDH.
636  *
637  * @param key Destination for the generated key.
638  * @param sender ID of the peer that will encrypt with @c key.
639  * @param receiver ID of the peer that will decrypt with @c key.
640  * @param key_material Hash created with ECDH with the ephemeral keys.
641  */
642 void
643 derive_symmertic (struct GNUNET_CRYPTO_SymmetricSessionKey *key,
644                   const struct GNUNET_PeerIdentity *sender,
645                   const struct GNUNET_PeerIdentity *receiver,
646                   const struct GNUNET_HashCode *key_material)
647 {
648   const char salt[] = "CADET kx salt";
649
650   GNUNET_CRYPTO_kdf (key, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey),
651                      salt, sizeof (salt),
652                      key_material, sizeof (struct GNUNET_HashCode),
653                      sender, sizeof (struct GNUNET_PeerIdentity),
654                      receiver, sizeof (struct GNUNET_PeerIdentity),
655                      NULL);
656 }
657
658
659 /**
660  * Derive the tunnel's keys using our own and the peer's ephemeral keys.
661  *
662  * @param t Tunnel for which to create the keys.
663  */
664 static void
665 create_keys (struct CadetTunnel *t)
666 {
667   struct GNUNET_HashCode km;
668
669   derive_key_material (&km, &t->peers_ephemeral_key);
670   derive_symmertic (&t->e_key, &my_full_id, GCP_get_id (t->peer), &km);
671   derive_symmertic (&t->d_key, GCP_get_id (t->peer), &my_full_id, &km);
672 }
673
674
675 /**
676  * Pick a connection on which send the next data message.
677  *
678  * @param t Tunnel on which to send the message.
679  *
680  * @return The connection on which to send the next message.
681  */
682 static struct CadetConnection *
683 tunnel_get_connection (struct CadetTunnel *t)
684 {
685   struct CadetTConnection *iter;
686   struct CadetConnection *best;
687   unsigned int qn;
688   unsigned int lowest_q;
689
690   LOG (GNUNET_ERROR_TYPE_DEBUG, "tunnel_get_connection %s\n", GCT_2s (t));
691   best = NULL;
692   lowest_q = UINT_MAX;
693   for (iter = t->connection_head; NULL != iter; iter = iter->next)
694   {
695     LOG (GNUNET_ERROR_TYPE_DEBUG, "  connection %s: %u\n",
696          GCC_2s (iter->c), GCC_get_state (iter->c));
697     if (CADET_CONNECTION_READY == GCC_get_state (iter->c))
698     {
699       qn = GCC_get_qn (iter->c, GCC_is_origin (iter->c, GNUNET_YES));
700       LOG (GNUNET_ERROR_TYPE_DEBUG, "    q_n %u, \n", qn);
701       if (qn < lowest_q)
702       {
703         best = iter->c;
704         lowest_q = qn;
705       }
706     }
707   }
708   LOG (GNUNET_ERROR_TYPE_DEBUG, " selected: connection %s\n", GCC_2s (best));
709   return best;
710 }
711
712
713 /**
714  * Callback called when a queued message is sent.
715  *
716  * Calculates the average time and connection packet tracking.
717  *
718  * @param cls Closure (TunnelQueue handle).
719  * @param c Connection this message was on.
720  * @param q Connection queue handle (unused).
721  * @param type Type of message sent.
722  * @param fwd Was this a FWD going message?
723  * @param size Size of the message.
724  */
725 static void
726 tun_message_sent (void *cls,
727               struct CadetConnection *c,
728               struct CadetConnectionQueue *q,
729               uint16_t type, int fwd, size_t size)
730 {
731   struct CadetTunnelQueue *qt = cls;
732   struct CadetTunnel *t;
733
734   LOG (GNUNET_ERROR_TYPE_DEBUG, "tun_message_sent\n");
735
736   GNUNET_assert (NULL != qt->cont);
737   t = NULL == c ? NULL : GCC_get_tunnel (c);
738   qt->cont (qt->cont_cls, t, qt, type, size);
739   GNUNET_free (qt);
740 }
741
742
743 /**
744  * Delete a queued message: either was sent or the channel was destroyed
745  * before the tunnel's key exchange had a chance to finish.
746  *
747  * @param tqd Delayed queue handle.
748  */
749 static void
750 unqueue_data (struct CadetTunnelDelayed *tqd)
751 {
752   GNUNET_CONTAINER_DLL_remove (tqd->t->tq_head, tqd->t->tq_tail, tqd);
753   GNUNET_free (tqd);
754 }
755
756
757 /**
758  * Cache a message to be sent once tunnel is online.
759  *
760  * @param t Tunnel to hold the message.
761  * @param msg Message itself (copy will be made).
762  */
763 static struct CadetTunnelDelayed *
764 queue_data (struct CadetTunnel *t, const struct GNUNET_MessageHeader *msg)
765 {
766   struct CadetTunnelDelayed *tqd;
767   uint16_t size = ntohs (msg->size);
768
769   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue data on Tunnel %s\n", GCT_2s (t));
770
771   if (GNUNET_YES == is_ready (t))
772   {
773     GNUNET_break (0);
774     return NULL;
775   }
776
777   tqd = GNUNET_malloc (sizeof (struct CadetTunnelDelayed) + size);
778
779   tqd->t = t;
780   memcpy (&tqd[1], msg, size);
781   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, t->tq_tail, tqd);
782   return tqd;
783 }
784
785
786 /**
787  * Calculate HMAC.
788  *
789  * @param t Tunnel to get keys from.
790  * @param plaintext Content to HMAC.
791  * @param size Size of @c plaintext.
792  * @param iv Initialization vector for the message.
793  * @param outgoing Is this an outgoing message that we encrypted?
794  * @param hmac Destination to store the HMAC.
795  */
796 static void
797 t_hmac (struct CadetTunnel *t, const void *plaintext, size_t size, uint32_t iv,
798         int outgoing, struct GNUNET_CADET_Hash *hmac)
799 {
800   struct GNUNET_CRYPTO_AuthKey auth_key;
801   static const char ctx[] = "cadet authentication key";
802   struct GNUNET_CRYPTO_SymmetricSessionKey *key;
803   struct GNUNET_HashCode hash;
804
805   key = outgoing ? &t->e_key : &t->d_key;
806   GNUNET_CRYPTO_hmac_derive_key (&auth_key, key,
807                                  &iv, sizeof (iv),
808                                  key, sizeof (*key),
809                                  ctx, sizeof (ctx),
810                                  NULL);
811   GNUNET_CRYPTO_hmac (&auth_key, plaintext, size, &hash);
812   memcpy (hmac, &hash, sizeof (*hmac));
813 }
814
815
816 /**
817  * Sends an already built message on a tunnel, encrypting it and
818  * choosing the best connection.
819  *
820  * @param message Message to send. Function modifies it.
821  * @param t Tunnel on which this message is transmitted.
822  * @param c Connection to use (autoselect if NULL).
823  * @param force Force the tunnel to take the message (buffer overfill).
824  * @param cont Continuation to call once message is really sent.
825  * @param cont_cls Closure for @c cont.
826  * @param existing_q In case this a transmission of previously queued data,
827  *                   this should be TunnelQueue given to the client.
828  *                   Otherwise, NULL.
829  *
830  * @return Handle to cancel message. NULL if @c cont is NULL.
831  */
832 static struct CadetTunnelQueue *
833 send_prebuilt_message (const struct GNUNET_MessageHeader *message,
834                        struct CadetTunnel *t, struct CadetConnection *c,
835                        int force, GCT_sent cont, void *cont_cls,
836                        struct CadetTunnelQueue *existing_q)
837 {
838   struct CadetTunnelQueue *tq;
839   struct GNUNET_CADET_Encrypted *msg;
840   size_t size = ntohs (message->size);
841   char cbuf[sizeof (struct GNUNET_CADET_Encrypted) + size];
842   uint32_t mid;
843   uint32_t iv;
844   uint16_t type;
845   int fwd;
846
847   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT Send on Tunnel %s\n", GCT_2s (t));
848
849   if (GNUNET_NO == is_ready (t))
850   {
851     struct CadetTunnelDelayed *tqd;
852     /* A non null existing_q indicates sending of queued data.
853      * Should only happen after tunnel becomes ready.
854      */
855     GNUNET_assert (NULL == existing_q);
856     tqd = queue_data (t, message);
857     if (NULL == cont)
858       return NULL;
859     tq = GNUNET_new (struct CadetTunnelQueue);
860     tq->tqd = tqd;
861     tqd->tq = tq;
862     tq->cont = cont;
863     tq->cont_cls = cont_cls;
864     return tq;
865   }
866
867   GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
868
869   iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
870   msg = (struct GNUNET_CADET_Encrypted *) cbuf;
871   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED);
872   msg->iv = iv;
873   GNUNET_assert (t_encrypt (t, &msg[1], message, size, iv) == size);
874   t_hmac (t, &msg[1], size, iv, GNUNET_YES, &msg->hmac);
875   msg->header.size = htons (sizeof (struct GNUNET_CADET_Encrypted) + size);
876
877   if (NULL == c)
878     c = tunnel_get_connection (t);
879   if (NULL == c)
880   {
881     if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
882         || CADET_TUNNEL3_SEARCHING != t->cstate)
883     {
884       GNUNET_break (0);
885       GCT_debug (t);
886     }
887     return NULL;
888   }
889
890   mid = 0;
891   type = ntohs (message->type);
892   switch (type)
893   {
894     case GNUNET_MESSAGE_TYPE_CADET_DATA:
895     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
896       if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
897         mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
898       else
899         mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
900       /* Fall thru */
901     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
902     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
903     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
904     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
905     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
906       msg->cid = *GCC_get_id (c);
907       msg->ttl = htonl (default_ttl);
908       break;
909     default:
910       GNUNET_break (0);
911   }
912   LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
913
914   fwd = GCC_is_origin (c, GNUNET_YES);
915
916   if (NULL == cont)
917   {
918     GNUNET_break (NULL ==
919                   GCC_send_prebuilt_message (&msg->header, type, mid,
920                                              c, fwd, force, NULL, NULL));
921     return NULL;
922   }
923   if (NULL == existing_q)
924   {
925     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
926   }
927   else
928   {
929     tq = existing_q;
930     tq->tqd = NULL;
931   }
932   tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
933                                       &tun_message_sent, tq);
934   tq->cont = cont;
935   tq->cont_cls = cont_cls;
936
937   return tq;
938 }
939
940
941 /**
942  * Send all cached messages that we can, tunnel is online.
943  *
944  * @param t Tunnel that holds the messages. Cannot be loopback.
945  */
946 static void
947 send_queued_data (struct CadetTunnel *t)
948 {
949   struct CadetTunnelDelayed *tqd;
950   struct CadetTunnelDelayed *next;
951   unsigned int room;
952
953   LOG (GNUNET_ERROR_TYPE_DEBUG,
954        "GCT_send_queued_data on tunnel %s\n",
955        GCT_2s (t));
956
957   if (GCT_is_loopback (t))
958   {
959     GNUNET_break (0);
960     return;
961   }
962
963   if (GNUNET_NO == is_ready (t))
964   {
965     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not ready yet: %s/%s\n",
966          estate2s (t->estate), cstate2s (t->cstate));
967     return;
968   }
969
970   room = GCT_get_connections_buffer (t);
971   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
972   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
973   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
974   {
975     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
976     next = tqd->next;
977     room--;
978     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
979                            tqd->t, NULL, GNUNET_YES,
980                            NULL != tqd->tq ? tqd->tq->cont : NULL,
981                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
982                            tqd->tq);
983     unqueue_data (tqd);
984   }
985   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
986 }
987
988
989 /**
990  * Sends key exchange message on a tunnel, choosing the best connection.
991  * Should not be called on loopback tunnels.
992  *
993  * @param t Tunnel on which this message is transmitted.
994  * @param message Message to send. Function modifies it.
995  */
996 static void
997 send_kx (struct CadetTunnel *t,
998          const struct GNUNET_MessageHeader *message)
999 {
1000   struct CadetConnection *c;
1001   struct GNUNET_CADET_KX *msg;
1002   size_t size = ntohs (message->size);
1003   char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1004   uint16_t type;
1005   int fwd;
1006
1007   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1008
1009   /* Avoid loopback. */
1010   if (GCT_is_loopback (t))
1011   {
1012     LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback!\n");
1013     GNUNET_break (0);
1014     return;
1015   }
1016
1017   /* Even if tunnel is being destroyed, send anyway.
1018    * Could be a response to a rekey initiated by remote peer,
1019    * who is trying to create a new channel!
1020    */
1021
1022   /* Must have a connection. */
1023   if (NULL == t->connection_head)
1024   {
1025     GNUNET_break (CADET_TUNNEL3_SEARCHING == t->cstate);
1026     GCT_debug (t);
1027     return;
1028   }
1029
1030   msg = (struct GNUNET_CADET_KX *) cbuf;
1031   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1032   msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1033   c = tunnel_get_connection (t);
1034   if (NULL == c)
1035   {
1036     GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1037                   || CADET_TUNNEL3_READY != t->cstate);
1038     GCT_debug (t);
1039     return;
1040   }
1041   type = ntohs (message->type);
1042   switch (type)
1043   {
1044     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1045     case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1046     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1047       memcpy (&msg[1], message, size);
1048       break;
1049     default:
1050       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1051            GC_m2s (type));
1052       GNUNET_break (0);
1053   }
1054
1055   fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1056   /* TODO save handle and cancel in case of a unneeded retransmission */
1057   GCC_send_prebuilt_message (&msg->header, GNUNET_MESSAGE_TYPE_CADET_KX,
1058                              message->type, c, fwd, GNUNET_YES, NULL, NULL);
1059 }
1060
1061
1062 /**
1063  * Send the ephemeral key on a tunnel.
1064  *
1065  * @param t Tunnel on which to send the key.
1066  */
1067 static void
1068 send_ephemeral (struct CadetTunnel *t)
1069 {
1070   LOG (GNUNET_ERROR_TYPE_INFO, "=> EPHM for %s\n", GCT_2s (t));
1071
1072   kx_msg.sender_status = htonl (t->estate);
1073   send_kx (t, &kx_msg.header);
1074 }
1075
1076 /**
1077  * Send a ping message on a tunnel.
1078  *
1079  * @param t Tunnel on which to send the ping.
1080  */
1081 static void
1082 send_ping (struct CadetTunnel *t)
1083 {
1084   struct GNUNET_CADET_KX_Ping msg;
1085
1086   LOG (GNUNET_ERROR_TYPE_INFO, "=> PING for %s\n", GCT_2s (t));
1087   msg.header.size = htons (sizeof (msg));
1088   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1089   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1090   msg.target = *GCP_get_id (t->peer);
1091   msg.nonce = t->kx_ctx->challenge;
1092
1093   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
1094   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&msg.target));
1095   t_encrypt (t, &msg.target, &msg.target, ping_encryption_size(), msg.iv);
1096   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
1097   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg.target));
1098
1099   send_kx (t, &msg.header);
1100 }
1101
1102
1103 /**
1104  * Send a pong message on a tunnel.
1105  *d_
1106  * @param t Tunnel on which to send the pong.
1107  * @param challenge Value sent in the ping that we have to send back.
1108  */
1109 static void
1110 send_pong (struct CadetTunnel *t, uint32_t challenge)
1111 {
1112   struct GNUNET_CADET_KX_Pong msg;
1113
1114   LOG (GNUNET_ERROR_TYPE_INFO, "=> PONG for %s\n", GCT_2s (t));
1115   msg.header.size = htons (sizeof (msg));
1116   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1117   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1118   msg.nonce = challenge;
1119   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
1120   t_encrypt (t, &msg.nonce, &msg.nonce, sizeof (msg.nonce), msg.iv);
1121   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
1122
1123   send_kx (t, &msg.header);
1124 }
1125
1126
1127 /**
1128  * Initiate a rekey with the remote peer.
1129  *
1130  * @param cls Closure (tunnel).
1131  * @param tc TaskContext.
1132  */
1133 static void
1134 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1135 {
1136   struct CadetTunnel *t = cls;
1137
1138   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1139
1140   LOG (GNUNET_ERROR_TYPE_DEBUG, "Re-key Tunnel %s\n", GCT_2s (t));
1141   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1142     return;
1143
1144   if (NULL == t->kx_ctx)
1145   {
1146     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new kx ctx\n");
1147     t->kx_ctx = GNUNET_new (struct CadetTunnelKXCtx);
1148     t->kx_ctx->challenge =
1149         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1150     t->kx_ctx->d_key_old = t->d_key;
1151     t->kx_ctx->e_key_old = t->e_key;
1152     create_keys (t);
1153     t->kx_ctx->rekey_start_time = GNUNET_TIME_absolute_get ();
1154     LOG (GNUNET_ERROR_TYPE_DEBUG, "  new challenge for %s: %u\n",
1155          GCT_2s (t), t->kx_ctx->challenge);
1156   }
1157
1158   send_ephemeral (t);
1159
1160   switch (t->estate)
1161   {
1162     case CADET_TUNNEL3_KEY_UNINITIALIZED:
1163       t->estate = CADET_TUNNEL3_KEY_SENT;
1164       break;
1165     case CADET_TUNNEL3_KEY_SENT:
1166       break;
1167     case CADET_TUNNEL3_KEY_PING:
1168     case CADET_TUNNEL3_KEY_OK:
1169       send_ping (t);
1170       t->estate = CADET_TUNNEL3_KEY_PING;
1171       break;
1172     default:
1173       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1174   }
1175
1176   // FIXME exponential backoff
1177   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
1178        GNUNET_STRINGS_relative_time_to_string (REKEY_WAIT, GNUNET_YES));
1179   t->rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_WAIT, &rekey_tunnel, t);
1180 }
1181
1182
1183 /**
1184  * Our ephemeral key has changed, create new session key on all tunnels.
1185  *
1186  * Each tunnel will start the Key Exchange with a random delay between
1187  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1188  * per second, on average.
1189  *
1190  * @param cls Closure (size of the hashmap).
1191  * @param key Current public key.
1192  * @param value Value in the hash map (tunnel).
1193  *
1194  * @return #GNUNET_YES, so we should continue to iterate,
1195  */
1196 static int
1197 rekey_iterator (void *cls,
1198                 const struct GNUNET_PeerIdentity *key,
1199                 void *value)
1200 {
1201   struct CadetTunnel *t = value;
1202   struct GNUNET_TIME_Relative delay;
1203   long n = (long) cls;
1204   uint32_t r;
1205
1206   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1207     return GNUNET_YES;
1208
1209   if (GNUNET_YES == GCT_is_loopback (t))
1210     return GNUNET_YES;
1211
1212   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1213   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1214   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1215
1216   return GNUNET_YES;
1217 }
1218
1219
1220 /**
1221  * Create a new ephemeral key and key message, schedule next rekeying.
1222  *
1223  * @param cls Closure (unused).
1224  * @param tc TaskContext.
1225  */
1226 static void
1227 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1228 {
1229   struct GNUNET_TIME_Absolute time;
1230   long n;
1231
1232   rekey_task = GNUNET_SCHEDULER_NO_TASK;
1233
1234   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1235     return;
1236
1237   GNUNET_free_non_null (my_ephemeral_key);
1238   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1239
1240   time = GNUNET_TIME_absolute_get ();
1241   kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1242   time = GNUNET_TIME_absolute_add (time, rekey_period);
1243   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1244   kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1245   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1246
1247   GNUNET_assert (GNUNET_OK ==
1248                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1249                                            &kx_msg.purpose,
1250                                            &kx_msg.signature));
1251
1252   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1253   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1254
1255   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1256 }
1257
1258
1259 /**
1260  * Called only on shutdown, destroy every tunnel.
1261  *
1262  * @param cls Closure (unused).
1263  * @param key Current public key.
1264  * @param value Value in the hash map (tunnel).
1265  *
1266  * @return #GNUNET_YES, so we should continue to iterate,
1267  */
1268 static int
1269 destroy_iterator (void *cls,
1270                 const struct GNUNET_PeerIdentity *key,
1271                 void *value)
1272 {
1273   struct CadetTunnel *t = value;
1274
1275   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1276   GCT_destroy (t);
1277   return GNUNET_YES;
1278 }
1279
1280
1281 /**
1282  * Notify remote peer that we don't know a channel he is talking about,
1283  * probably CHANNEL_DESTROY was missed.
1284  *
1285  * @param t Tunnel on which to notify.
1286  * @param gid ID of the channel.
1287  */
1288 static void
1289 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1290 {
1291   struct GNUNET_CADET_ChannelManage msg;
1292
1293   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1294   msg.header.size = htons (sizeof (msg));
1295   msg.chid = htonl (gid);
1296
1297   LOG (GNUNET_ERROR_TYPE_DEBUG,
1298        "WARNING destroying unknown channel %u on tunnel %s\n",
1299        gid, GCT_2s (t));
1300   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1301 }
1302
1303
1304 /**
1305  * Demultiplex data per channel and call appropriate channel handler.
1306  *
1307  * @param t Tunnel on which the data came.
1308  * @param msg Data message.
1309  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1310  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1311  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1312  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1313  */
1314 static void
1315 handle_data (struct CadetTunnel *t,
1316              const struct GNUNET_CADET_Data *msg,
1317              int fwd)
1318 {
1319   struct CadetChannel *ch;
1320   size_t size;
1321
1322   /* Check size */
1323   size = ntohs (msg->header.size);
1324   if (size <
1325       sizeof (struct GNUNET_CADET_Data) +
1326       sizeof (struct GNUNET_MessageHeader))
1327   {
1328     GNUNET_break (0);
1329     return;
1330   }
1331   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1332               GC_m2s (ntohs (msg[1].header.type)));
1333
1334   /* Check channel */
1335   ch = GCT_get_channel (t, ntohl (msg->chid));
1336   if (NULL == ch)
1337   {
1338     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1339                               1, GNUNET_NO);
1340     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1341          ntohl (msg->chid));
1342     send_channel_destroy (t, ntohl (msg->chid));
1343     return;
1344   }
1345
1346   GCCH_handle_data (ch, msg, fwd);
1347 }
1348
1349
1350 /**
1351  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1352  *
1353  * @param t Tunnel on which the DATA ACK came.
1354  * @param msg DATA ACK message.
1355  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1356  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1357  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1358  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1359  */
1360 static void
1361 handle_data_ack (struct CadetTunnel *t,
1362                  const struct GNUNET_CADET_DataACK *msg,
1363                  int fwd)
1364 {
1365   struct CadetChannel *ch;
1366   size_t size;
1367
1368   /* Check size */
1369   size = ntohs (msg->header.size);
1370   if (size != sizeof (struct GNUNET_CADET_DataACK))
1371   {
1372     GNUNET_break (0);
1373     return;
1374   }
1375
1376   /* Check channel */
1377   ch = GCT_get_channel (t, ntohl (msg->chid));
1378   if (NULL == ch)
1379   {
1380     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1381                               1, GNUNET_NO);
1382     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1383          ntohl (msg->chid));
1384     return;
1385   }
1386
1387   GCCH_handle_data_ack (ch, msg, fwd);
1388 }
1389
1390
1391 /**
1392  * Handle channel create.
1393  *
1394  * @param t Tunnel on which the data came.
1395  * @param msg Data message.
1396  */
1397 static void
1398 handle_ch_create (struct CadetTunnel *t,
1399                   const struct GNUNET_CADET_ChannelCreate *msg)
1400 {
1401   struct CadetChannel *ch;
1402   size_t size;
1403
1404   /* Check size */
1405   size = ntohs (msg->header.size);
1406   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1407   {
1408     GNUNET_break (0);
1409     return;
1410   }
1411
1412   /* Check channel */
1413   ch = GCT_get_channel (t, ntohl (msg->chid));
1414   if (NULL != ch && ! GCT_is_loopback (t))
1415   {
1416     /* Probably a retransmission, safe to ignore */
1417     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
1418   }
1419   ch = GCCH_handle_create (t, msg);
1420   if (NULL != ch)
1421     GCT_add_channel (t, ch);
1422 }
1423
1424
1425
1426 /**
1427  * Handle channel NACK: check correctness and call channel handler for NACKs.
1428  *
1429  * @param t Tunnel on which the NACK came.
1430  * @param msg NACK message.
1431  */
1432 static void
1433 handle_ch_nack (struct CadetTunnel *t,
1434                 const struct GNUNET_CADET_ChannelManage *msg)
1435 {
1436   struct CadetChannel *ch;
1437   size_t size;
1438
1439   /* Check size */
1440   size = ntohs (msg->header.size);
1441   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1442   {
1443     GNUNET_break (0);
1444     return;
1445   }
1446
1447   /* Check channel */
1448   ch = GCT_get_channel (t, ntohl (msg->chid));
1449   if (NULL == ch)
1450   {
1451     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1452                               1, GNUNET_NO);
1453     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1454          ntohl (msg->chid));
1455     return;
1456   }
1457
1458   GCCH_handle_nack (ch);
1459 }
1460
1461
1462 /**
1463  * Handle a CHANNEL ACK (SYNACK/ACK).
1464  *
1465  * @param t Tunnel on which the CHANNEL ACK came.
1466  * @param msg CHANNEL ACK message.
1467  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1468  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1469  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1470  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1471  */
1472 static void
1473 handle_ch_ack (struct CadetTunnel *t,
1474                const struct GNUNET_CADET_ChannelManage *msg,
1475                int fwd)
1476 {
1477   struct CadetChannel *ch;
1478   size_t size;
1479
1480   /* Check size */
1481   size = ntohs (msg->header.size);
1482   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1483   {
1484     GNUNET_break (0);
1485     return;
1486   }
1487
1488   /* Check channel */
1489   ch = GCT_get_channel (t, ntohl (msg->chid));
1490   if (NULL == ch)
1491   {
1492     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1493                               1, GNUNET_NO);
1494     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1495          ntohl (msg->chid));
1496     return;
1497   }
1498
1499   GCCH_handle_ack (ch, msg, fwd);
1500 }
1501
1502
1503
1504 /**
1505  * Handle a channel destruction message.
1506  *
1507  * @param t Tunnel on which the message came.
1508  * @param msg Channel destroy message.
1509  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1510  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1511  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1512  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1513  */
1514 static void
1515 handle_ch_destroy (struct CadetTunnel *t,
1516                    const struct GNUNET_CADET_ChannelManage *msg,
1517                    int fwd)
1518 {
1519   struct CadetChannel *ch;
1520   size_t size;
1521
1522   /* Check size */
1523   size = ntohs (msg->header.size);
1524   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1525   {
1526     GNUNET_break (0);
1527     return;
1528   }
1529
1530   /* Check channel */
1531   ch = GCT_get_channel (t, ntohl (msg->chid));
1532   if (NULL == ch)
1533   {
1534     /* Probably a retransmission, safe to ignore */
1535     return;
1536   }
1537
1538   GCCH_handle_destroy (ch, msg, fwd);
1539 }
1540
1541
1542 /**
1543  * The peer's ephemeral key has changed: update the symmetrical keys.
1544  *
1545  * @param t Tunnel this message came on.
1546  * @param msg Key eXchange message.
1547  */
1548 static void
1549 handle_ephemeral (struct CadetTunnel *t,
1550                   const struct GNUNET_CADET_KX_Ephemeral *msg)
1551 {
1552   LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1553
1554   if (GNUNET_OK != check_ephemeral (t, msg))
1555   {
1556     GNUNET_break_op (0);
1557     return;
1558   }
1559   t->peers_ephemeral_key = msg->ephemeral_key;
1560   create_keys (t);
1561   if (CADET_TUNNEL3_KEY_SENT == t->estate)
1562   {
1563     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, sending ping\n");
1564     send_ping (t);
1565     t->estate = CADET_TUNNEL3_KEY_PING;
1566   }
1567 }
1568
1569
1570 /**
1571  * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1572  * Answer with by retransmitting the challenge with the "opposite" key.
1573  *
1574  * @param t Tunnel this message came on.
1575  * @param msg Key eXchange Ping message.
1576  */
1577 static void
1578 handle_ping (struct CadetTunnel *t,
1579              const struct GNUNET_CADET_KX_Ping *msg)
1580 {
1581   struct GNUNET_CADET_KX_Ping res;
1582
1583   if (ntohs (msg->header.size) != sizeof (res))
1584   {
1585     GNUNET_break_op (0);
1586     return;
1587   }
1588
1589   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1590   t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1591   if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1592   {
1593     GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1594     LOG (GNUNET_ERROR_TYPE_WARNING, "  malformed PING on %s\n", GCT_2s (t));
1595     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e got %u\n", msg->nonce);
1596     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg->target));
1597     LOG (GNUNET_ERROR_TYPE_DEBUG, "  got %u\n", res.nonce);
1598     LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&res.target));
1599     send_ephemeral (t);
1600     send_ping (t);
1601     return;
1602   }
1603
1604   send_pong (t, res.nonce);
1605 }
1606
1607
1608 /**
1609  * Peer has answer to our challenge.
1610  * If answer is successful, consider the key exchange finished and clean
1611  * up all related state.
1612  *
1613  * @param t Tunnel this message came on.
1614  * @param msg Key eXchange Pong message.
1615  */
1616 static void
1617 handle_pong (struct CadetTunnel *t,
1618              const struct GNUNET_CADET_KX_Pong *msg)
1619 {
1620   uint32_t challenge;
1621
1622   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1623   if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1624   {
1625     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1626     return;
1627   }
1628   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1629
1630   if (challenge != t->kx_ctx->challenge)
1631   {
1632     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1633     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1634          challenge, msg->nonce, t->kx_ctx->challenge);
1635     send_ephemeral (t);
1636     send_ping (t);
1637     return;
1638   }
1639   GNUNET_SCHEDULER_cancel (t->rekey_task);
1640   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1641   GNUNET_free (t->kx_ctx);
1642   t->kx_ctx = NULL;
1643   GCT_change_estate (t, CADET_TUNNEL3_KEY_OK);
1644 }
1645
1646
1647 /**
1648  * Demultiplex by message type and call appropriate handler for a message
1649  * towards a channel of a local tunnel.
1650  *
1651  * @param t Tunnel this message came on.
1652  * @param msgh Message header.
1653  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1654  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1655  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1656  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1657  */
1658 static void
1659 handle_decrypted (struct CadetTunnel *t,
1660                   const struct GNUNET_MessageHeader *msgh,
1661                   int fwd)
1662 {
1663   uint16_t type;
1664
1665   type = ntohs (msgh->type);
1666   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1667
1668   switch (type)
1669   {
1670     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1671       /* Do nothing, connection aleady got updated. */
1672       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1673       break;
1674
1675     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1676       /* Don't send hop ACK, wait for client to ACK */
1677       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1678       break;
1679
1680     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1681       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1682       break;
1683
1684     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1685       handle_ch_create (t,
1686                         (struct GNUNET_CADET_ChannelCreate *) msgh);
1687       break;
1688
1689     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1690       handle_ch_nack (t,
1691                       (struct GNUNET_CADET_ChannelManage *) msgh);
1692       break;
1693
1694     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1695       handle_ch_ack (t,
1696                      (struct GNUNET_CADET_ChannelManage *) msgh,
1697                      fwd);
1698       break;
1699
1700     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1701       handle_ch_destroy (t,
1702                          (struct GNUNET_CADET_ChannelManage *) msgh,
1703                          fwd);
1704       break;
1705
1706     default:
1707       GNUNET_break_op (0);
1708       LOG (GNUNET_ERROR_TYPE_WARNING,
1709            "end-to-end message not known (%u)\n",
1710            ntohs (msgh->type));
1711       GCT_debug (t);
1712   }
1713 }
1714
1715 /******************************************************************************/
1716 /********************************    API    ***********************************/
1717 /******************************************************************************/
1718
1719 /**
1720  * Decrypt and demultiplex by message type. Call appropriate handler
1721  * for every message.
1722  *
1723  * @param t Tunnel this message came on.
1724  * @param msg Encrypted message.
1725  */
1726 void
1727 GCT_handle_encrypted (struct CadetTunnel *t,
1728                       const struct GNUNET_CADET_Encrypted *msg)
1729 {
1730   size_t size = ntohs (msg->header.size);
1731   size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1732   size_t decrypted_size;
1733   char cbuf [payload_size];
1734   struct GNUNET_MessageHeader *msgh;
1735   unsigned int off;
1736   struct GNUNET_CADET_Hash hmac;
1737
1738   decrypted_size = t_decrypt (t, cbuf, &msg[1], payload_size, msg->iv);
1739   t_hmac (t, &msg[1], payload_size, msg->iv, GNUNET_NO, &hmac);
1740   if (0 != memcmp (&hmac, &msg->hmac, sizeof (hmac)))
1741   {
1742     /* checksum failed */
1743     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1744                 "Failed checksum validation for a message on tunnel `%s'\n",
1745                 GCT_2s (t));
1746     GNUNET_STATISTICS_update (stats, "# wrong HMAC", 1, GNUNET_NO);
1747     return;
1748   }
1749   off = 0;
1750   while (off < decrypted_size)
1751   {
1752     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
1753     handle_decrypted (t, msgh, GNUNET_SYSERR);
1754     off += ntohs (msgh->size);
1755   }
1756 }
1757
1758
1759 /**
1760  * Demultiplex an encapsulated KX message by message type.
1761  *
1762  * @param t Tunnel on which the message came.
1763  * @param message Payload of KX message.
1764  */
1765 void
1766 GCT_handle_kx (struct CadetTunnel *t,
1767                const struct GNUNET_MessageHeader *message)
1768 {
1769   uint16_t type;
1770
1771   type = ntohs (message->type);
1772   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
1773   switch (type)
1774   {
1775     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1776       handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
1777       break;
1778
1779     case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1780       handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
1781       break;
1782
1783     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1784       handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
1785       break;
1786
1787     default:
1788       GNUNET_break_op (0);
1789       LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
1790   }
1791 }
1792
1793
1794 /**
1795  * Initialize the tunnel subsystem.
1796  *
1797  * @param c Configuration handle.
1798  * @param key ECC private key, to derive all other keys and do crypto.
1799  */
1800 void
1801 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
1802           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
1803 {
1804   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1805   if (GNUNET_OK !=
1806       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
1807                                              &default_ttl))
1808   {
1809     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1810                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
1811     default_ttl = 64;
1812   }
1813   if (GNUNET_OK !=
1814       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
1815                                            &rekey_period))
1816   {
1817     rekey_period = GNUNET_TIME_UNIT_DAYS;
1818   }
1819
1820   my_private_key = key;
1821   kx_msg.header.size = htons (sizeof (kx_msg));
1822   kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
1823   kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
1824   kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
1825   kx_msg.origin_identity = my_full_id;
1826   rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
1827
1828   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
1829 }
1830
1831
1832 /**
1833  * Shut down the tunnel subsystem.
1834  */
1835 void
1836 GCT_shutdown (void)
1837 {
1838   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
1839   {
1840     GNUNET_SCHEDULER_cancel (rekey_task);
1841     rekey_task = GNUNET_SCHEDULER_NO_TASK;
1842   }
1843   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
1844   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
1845 }
1846
1847
1848 /**
1849  * Create a tunnel.
1850  *
1851  * @param destination Peer this tunnel is towards.
1852  */
1853 struct CadetTunnel *
1854 GCT_new (struct CadetPeer *destination)
1855 {
1856   struct CadetTunnel *t;
1857
1858   t = GNUNET_new (struct CadetTunnel);
1859   t->next_chid = 0;
1860   t->peer = destination;
1861
1862   if (GNUNET_OK !=
1863       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
1864                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
1865   {
1866     GNUNET_break (0);
1867     GNUNET_free (t);
1868     return NULL;
1869   }
1870   return t;
1871 }
1872
1873
1874 /**
1875  * Change the tunnel's connection state.
1876  *
1877  * @param t Tunnel whose connection state to change.
1878  * @param cstate New connection state.
1879  */
1880 void
1881 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
1882 {
1883   if (NULL == t)
1884     return;
1885   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
1886        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
1887   if (myid != GCP_get_short_id (t->peer) &&
1888       CADET_TUNNEL3_READY != t->cstate &&
1889       CADET_TUNNEL3_READY == cstate)
1890   {
1891     t->cstate = cstate;
1892     if (CADET_TUNNEL3_KEY_OK == t->estate)
1893     {
1894       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
1895       send_queued_data (t);
1896     }
1897     else if (CADET_TUNNEL3_KEY_UNINITIALIZED == t->estate)
1898     {
1899       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered rekey\n");
1900       rekey_tunnel (t, NULL);
1901     }
1902   }
1903   t->cstate = cstate;
1904
1905   if (CADET_TUNNEL3_READY == cstate
1906       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
1907   {
1908     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
1909     GCP_stop_search (t->peer);
1910   }
1911 }
1912
1913 /**
1914  * Change the tunnel encryption state.
1915  *
1916  * @param t Tunnel whose encryption state to change.
1917  * @param state New encryption state.
1918  */
1919 void
1920 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
1921 {
1922   if (NULL == t)
1923     return;
1924   LOG (GNUNET_ERROR_TYPE_DEBUG,
1925        "Tunnel %s estate was %s\n",
1926        GCP_2s (t->peer), estate2s (t->estate));
1927   LOG (GNUNET_ERROR_TYPE_DEBUG,
1928        "Tunnel %s estate is now %s\n",
1929        GCP_2s (t->peer), estate2s (state));
1930   if (myid != GCP_get_short_id (t->peer) &&
1931       CADET_TUNNEL3_KEY_OK != t->estate && CADET_TUNNEL3_KEY_OK == state)
1932   {
1933     t->estate = state;
1934     send_queued_data (t);
1935     return;
1936   }
1937   t->estate = state;
1938 }
1939
1940
1941 /**
1942  * @brief Check if tunnel has too many connections, and remove one if necessary.
1943  *
1944  * Currently this means the newest connection, unless it is a direct one.
1945  * Implemented as a task to avoid freeing a connection that is in the middle
1946  * of being created/processed.
1947  *
1948  * @param cls Closure (Tunnel to check).
1949  * @param tc Task context.
1950  */
1951 static void
1952 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1953 {
1954   struct CadetTunnel *t = cls;
1955
1956   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1957     return;
1958
1959   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
1960   {
1961     struct CadetTConnection *iter;
1962     struct CadetTConnection *c;
1963
1964     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
1965     {
1966       if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
1967           && GNUNET_NO == GCC_is_direct (iter->c))
1968       {
1969         c = iter;
1970       }
1971     }
1972     if (NULL != c)
1973     {
1974       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
1975            GCT_2s (t));
1976       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
1977            GCC_2s (c->c));
1978       GCC_destroy (c->c);
1979     }
1980     else
1981     {
1982       GNUNET_break (0);
1983     }
1984   }
1985 }
1986
1987
1988 /**
1989  * Add a connection to a tunnel.
1990  *
1991  * @param t Tunnel.
1992  * @param c Connection.
1993  */
1994 void
1995 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
1996 {
1997   struct CadetTConnection *aux;
1998
1999   GNUNET_assert (NULL != c);
2000
2001   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2002   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2003   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2004     if (aux->c == c)
2005       return;
2006
2007   aux = GNUNET_new (struct CadetTConnection);
2008   aux->c = c;
2009   aux->created = GNUNET_TIME_absolute_get ();
2010
2011   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2012
2013   GNUNET_SCHEDULER_add_now (&trim_connections, t);
2014 }
2015
2016
2017 /**
2018  * Mark a path as no longer valid for this tunnel: has been tried and failed.
2019  *
2020  * @param t Tunnel to update.
2021  * @param path Invalid path to remove. Is destroyed after removal.
2022  */
2023 void
2024 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2025 {
2026   GCP_remove_path (t->peer, path);
2027 }
2028
2029
2030 /**
2031  * Remove a connection from a tunnel.
2032  *
2033  * @param t Tunnel.
2034  * @param c Connection.
2035  */
2036 void
2037 GCT_remove_connection (struct CadetTunnel *t,
2038                        struct CadetConnection *c)
2039 {
2040   struct CadetTConnection *aux;
2041   struct CadetTConnection *next;
2042
2043   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2044        GCC_2s (c), GCT_2s (t));
2045   for (aux = t->connection_head; aux != NULL; aux = next)
2046   {
2047     next = aux->next;
2048     if (aux->c == c)
2049     {
2050       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2051       GNUNET_free (aux);
2052     }
2053   }
2054
2055   /* Start new connections if needed */
2056   if (CONNECTIONS_PER_TUNNEL < GCT_count_connections (t)
2057       && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2058       && CADET_TUNNEL3_SHUTDOWN != t->cstate
2059       && GNUNET_NO == shutting_down)
2060   {
2061     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no more connections, getting new ones\n");
2062     t->cstate = CADET_TUNNEL3_SEARCHING;
2063     GCP_connect (t->peer);
2064     return;
2065   }
2066
2067   /* If not marked as ready, no change is needed */
2068   if (CADET_TUNNEL3_READY != t->cstate)
2069     return;
2070
2071   /* Check if any connection is ready to maintaing cstate */
2072   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2073     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2074       return;
2075
2076   t->cstate = CADET_TUNNEL3_WAITING;
2077 }
2078
2079
2080 /**
2081  * Add a channel to a tunnel.
2082  *
2083  * @param t Tunnel.
2084  * @param ch Channel.
2085  */
2086 void
2087 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2088 {
2089   struct CadetTChannel *aux;
2090
2091   GNUNET_assert (NULL != ch);
2092
2093   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2094
2095   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2096   {
2097     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
2098     if (aux->ch == ch)
2099       return;
2100   }
2101
2102   aux = GNUNET_new (struct CadetTChannel);
2103   aux->ch = ch;
2104   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2105   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2106
2107   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2108   {
2109     GNUNET_SCHEDULER_cancel (t->destroy_task);
2110     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2111     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2112   }
2113 }
2114
2115
2116 /**
2117  * Remove a channel from a tunnel.
2118  *
2119  * @param t Tunnel.
2120  * @param ch Channel.
2121  */
2122 void
2123 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2124 {
2125   struct CadetTChannel *aux;
2126
2127   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2128   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2129   {
2130     if (aux->ch == ch)
2131     {
2132       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2133       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2134       GNUNET_free (aux);
2135       return;
2136     }
2137   }
2138 }
2139
2140
2141 /**
2142  * Search for a channel by global ID.
2143  *
2144  * @param t Tunnel containing the channel.
2145  * @param chid Public channel number.
2146  *
2147  * @return channel handler, NULL if doesn't exist
2148  */
2149 struct CadetChannel *
2150 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2151 {
2152   struct CadetTChannel *iter;
2153
2154   if (NULL == t)
2155     return NULL;
2156
2157   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2158   {
2159     if (GCCH_get_id (iter->ch) == chid)
2160       break;
2161   }
2162
2163   return NULL == iter ? NULL : iter->ch;
2164 }
2165
2166
2167 /**
2168  * @brief Destroy a tunnel and free all resources.
2169  *
2170  * Should only be called a while after the tunnel has been marked as destroyed,
2171  * in case there is a new channel added to the same peer shortly after marking
2172  * the tunnel. This way we avoid a new public key handshake.
2173  *
2174  * @param cls Closure (tunnel to destroy).
2175  * @param tc Task context.
2176  */
2177 static void
2178 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2179 {
2180   struct CadetTunnel *t = cls;
2181   struct CadetTConnection *iter;
2182
2183   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2184   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2185   {
2186     LOG (GNUNET_ERROR_TYPE_WARNING,
2187          "Not destroying tunnel, due to shutdown. "
2188          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2189     return;
2190   }
2191   t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2192   t->cstate = CADET_TUNNEL3_SHUTDOWN;
2193
2194   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2195   {
2196     GCC_send_destroy (iter->c);
2197   }
2198   GCT_destroy (t);
2199 }
2200
2201
2202 /**
2203  * Tunnel is empty: destroy it.
2204  *
2205  * Notifies all connections about the destruction.
2206  *
2207  * @param t Tunnel to destroy.
2208  */
2209 void
2210 GCT_destroy_empty (struct CadetTunnel *t)
2211 {
2212   if (GNUNET_YES == shutting_down)
2213     return; /* Will be destroyed immediately anyway */
2214
2215   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2216   {
2217     LOG (GNUNET_ERROR_TYPE_DEBUG,
2218          "Tunnel %s is already scheduled for destruction\n",
2219          GCT_2s (t));
2220     GNUNET_break (0);
2221     /* should never happen, tunnel can only become empty once, and the
2222      * task identifier should be NO_TASK (cleaned when the tunnel was created
2223      * or became un-empty)
2224      */
2225     return;
2226   }
2227
2228   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2229        GCT_2s (t));
2230
2231   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2232                                                   &delayed_destroy, t);
2233   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2234        t, t->destroy_task);
2235 }
2236
2237
2238 /**
2239  * Destroy tunnel if empty (no more channels).
2240  *
2241  * @param t Tunnel to destroy if empty.
2242  */
2243 void
2244 GCT_destroy_if_empty (struct CadetTunnel *t)
2245 {
2246   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2247   if (1 < GCT_count_channels (t))
2248     return;
2249
2250   GCT_destroy_empty (t);
2251 }
2252
2253
2254 /**
2255  * Destroy the tunnel.
2256  *
2257  * This function does not generate any warning traffic to clients or peers.
2258  *
2259  * Tasks:
2260  * Cancel messages belonging to this tunnel queued to neighbors.
2261  * Free any allocated resources linked to the tunnel.
2262  *
2263  * @param t The tunnel to destroy.
2264  */
2265 void
2266 GCT_destroy (struct CadetTunnel *t)
2267 {
2268   struct CadetTConnection *iter_c;
2269   struct CadetTConnection *next_c;
2270   struct CadetTChannel *iter_ch;
2271   struct CadetTChannel *next_ch;
2272
2273   if (NULL == t)
2274     return;
2275
2276   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2277
2278   GNUNET_break (GNUNET_YES ==
2279                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2280                                                       GCP_get_id (t->peer), t));
2281
2282   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2283   {
2284     next_c = iter_c->next;
2285     GCC_destroy (iter_c->c);
2286   }
2287   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2288   {
2289     next_ch = iter_ch->next;
2290     GCCH_destroy (iter_ch->ch);
2291     /* Should only happen on shutdown, but it's ok. */
2292   }
2293
2294   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2295   {
2296     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2297     GNUNET_SCHEDULER_cancel (t->destroy_task);
2298     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2299   }
2300
2301   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2302   GCP_set_tunnel (t->peer, NULL);
2303
2304   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2305   {
2306     GNUNET_SCHEDULER_cancel (t->rekey_task);
2307     t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2308     if (NULL != t->kx_ctx)
2309       GNUNET_free (t->kx_ctx);
2310     else
2311       GNUNET_break (0);
2312   }
2313
2314   GNUNET_free (t);
2315 }
2316
2317
2318 /**
2319  * @brief Use the given path for the tunnel.
2320  * Update the next and prev hops (and RCs).
2321  * (Re)start the path refresh in case the tunnel is locally owned.
2322  *
2323  * @param t Tunnel to update.
2324  * @param p Path to use.
2325  *
2326  * @return Connection created.
2327  */
2328 struct CadetConnection *
2329 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2330 {
2331   struct CadetConnection *c;
2332   struct GNUNET_CADET_Hash cid;
2333   unsigned int own_pos;
2334
2335   if (NULL == t || NULL == p)
2336   {
2337     GNUNET_break (0);
2338     return NULL;
2339   }
2340
2341   if (CADET_TUNNEL3_SHUTDOWN == t->cstate)
2342   {
2343     GNUNET_break (0);
2344     return NULL;
2345   }
2346
2347   for (own_pos = 0; own_pos < p->length; own_pos++)
2348   {
2349     if (p->peers[own_pos] == myid)
2350       break;
2351   }
2352   if (own_pos >= p->length)
2353   {
2354     GNUNET_break_op (0);
2355     return NULL;
2356   }
2357
2358   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2359   c = GCC_new (&cid, t, p, own_pos);
2360   if (NULL == c)
2361   {
2362     /* Path was flawed */
2363     return NULL;
2364   }
2365   GCT_add_connection (t, c);
2366   return c;
2367 }
2368
2369
2370 /**
2371  * Count established (ready) connections of a tunnel.
2372  *
2373  * @param t Tunnel on which to count.
2374  *
2375  * @return Number of connections.
2376  */
2377 unsigned int
2378 GCT_count_connections (struct CadetTunnel *t)
2379 {
2380   struct CadetTConnection *iter;
2381   unsigned int count;
2382
2383   if (NULL == t)
2384     return 0;
2385
2386   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2387     if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2388       count++;
2389
2390   return count;
2391 }
2392
2393 /**
2394  * Count channels of a tunnel.
2395  *
2396  * @param t Tunnel on which to count.
2397  *
2398  * @return Number of channels.
2399  */
2400 unsigned int
2401 GCT_count_channels (struct CadetTunnel *t)
2402 {
2403   struct CadetTChannel *iter;
2404   unsigned int count;
2405
2406   for (count = 0, iter = t->channel_head;
2407        NULL != iter;
2408        iter = iter->next, count++) /* skip */;
2409
2410   return count;
2411 }
2412
2413
2414 /**
2415  * Get the connectivity state of a tunnel.
2416  *
2417  * @param t Tunnel.
2418  *
2419  * @return Tunnel's connectivity state.
2420  */
2421 enum CadetTunnelCState
2422 GCT_get_cstate (struct CadetTunnel *t)
2423 {
2424   if (NULL == t)
2425   {
2426     GNUNET_assert (0);
2427     return (enum CadetTunnelCState) -1;
2428   }
2429   return t->cstate;
2430 }
2431
2432
2433 /**
2434  * Get the encryption state of a tunnel.
2435  *
2436  * @param t Tunnel.
2437  *
2438  * @return Tunnel's encryption state.
2439  */
2440 enum CadetTunnelEState
2441 GCT_get_estate (struct CadetTunnel *t)
2442 {
2443   if (NULL == t)
2444   {
2445     GNUNET_assert (0);
2446     return (enum CadetTunnelEState) -1;
2447   }
2448   return t->estate;
2449 }
2450
2451 /**
2452  * Get the maximum buffer space for a tunnel towards a local client.
2453  *
2454  * @param t Tunnel.
2455  *
2456  * @return Biggest buffer space offered by any channel in the tunnel.
2457  */
2458 unsigned int
2459 GCT_get_channels_buffer (struct CadetTunnel *t)
2460 {
2461   struct CadetTChannel *iter;
2462   unsigned int buffer;
2463   unsigned int ch_buf;
2464
2465   if (NULL == t->channel_head)
2466   {
2467     /* Probably getting buffer for a channel create/handshake. */
2468     return 64;
2469   }
2470
2471   buffer = 0;
2472   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2473   {
2474     ch_buf = get_channel_buffer (iter);
2475     if (ch_buf > buffer)
2476       buffer = ch_buf;
2477   }
2478   return buffer;
2479 }
2480
2481
2482 /**
2483  * Get the total buffer space for a tunnel for P2P traffic.
2484  *
2485  * @param t Tunnel.
2486  *
2487  * @return Buffer space offered by all connections in the tunnel.
2488  */
2489 unsigned int
2490 GCT_get_connections_buffer (struct CadetTunnel *t)
2491 {
2492   struct CadetTConnection *iter;
2493   unsigned int buffer;
2494
2495   buffer = 0;
2496   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2497   {
2498     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2499     {
2500       continue;
2501     }
2502     buffer += get_connection_buffer (iter);
2503   }
2504
2505   return buffer;
2506 }
2507
2508
2509 /**
2510  * Get the tunnel's destination.
2511  *
2512  * @param t Tunnel.
2513  *
2514  * @return ID of the destination peer.
2515  */
2516 const struct GNUNET_PeerIdentity *
2517 GCT_get_destination (struct CadetTunnel *t)
2518 {
2519   return GCP_get_id (t->peer);
2520 }
2521
2522
2523 /**
2524  * Get the tunnel's next free global channel ID.
2525  *
2526  * @param t Tunnel.
2527  *
2528  * @return GID of a channel free to use.
2529  */
2530 CADET_ChannelNumber
2531 GCT_get_next_chid (struct CadetTunnel *t)
2532 {
2533   CADET_ChannelNumber chid;
2534   CADET_ChannelNumber mask;
2535   int result;
2536
2537   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2538    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2539    * If peer's ID is bigger, start at 0x4... bit 30 = 1
2540    */
2541   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2542   if (0 > result)
2543     mask = 0x40000000;
2544   else
2545     mask = 0x0;
2546   t->next_chid |= mask;
2547
2548   while (NULL != GCT_get_channel (t, t->next_chid))
2549   {
2550     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2551     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2552     t->next_chid |= mask;
2553   }
2554   chid = t->next_chid;
2555   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2556   t->next_chid |= mask;
2557
2558   return chid;
2559 }
2560
2561
2562 /**
2563  * Send ACK on one or more channels due to buffer in connections.
2564  *
2565  * @param t Channel which has some free buffer space.
2566  */
2567 void
2568 GCT_unchoke_channels (struct CadetTunnel *t)
2569 {
2570   struct CadetTChannel *iter;
2571   unsigned int buffer;
2572   unsigned int channels = GCT_count_channels (t);
2573   unsigned int choked_n;
2574   struct CadetChannel *choked[channels];
2575
2576   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2577   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2578   if (NULL != t->channel_head)
2579     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2580
2581   /* Get buffer space */
2582   buffer = GCT_get_connections_buffer (t);
2583   if (0 == buffer)
2584   {
2585     return;
2586   }
2587
2588   /* Count and remember choked channels */
2589   choked_n = 0;
2590   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2591   {
2592     if (GNUNET_NO == get_channel_allowed (iter))
2593     {
2594       choked[choked_n++] = iter->ch;
2595     }
2596   }
2597
2598   /* Unchoke random channels */
2599   while (0 < buffer && 0 < choked_n)
2600   {
2601     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2602                                                choked_n);
2603     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2604     choked_n--;
2605     buffer--;
2606     choked[r] = choked[choked_n];
2607   }
2608 }
2609
2610
2611 /**
2612  * Send ACK on one or more connections due to buffer space to the client.
2613  *
2614  * Iterates all connections of the tunnel and sends ACKs appropriately.
2615  *
2616  * @param t Tunnel.
2617  */
2618 void
2619 GCT_send_connection_acks (struct CadetTunnel *t)
2620 {
2621   struct CadetTConnection *iter;
2622   uint32_t allowed;
2623   uint32_t to_allow;
2624   uint32_t allow_per_connection;
2625   unsigned int cs;
2626   unsigned int buffer;
2627
2628   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2629        GCT_2s (t));
2630
2631   if (NULL == t)
2632   {
2633     GNUNET_break (0);
2634     return;
2635   }
2636
2637   buffer = GCT_get_channels_buffer (t);
2638   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
2639
2640   /* Count connections, how many messages are already allowed */
2641   cs = GCT_count_connections (t);
2642   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2643   {
2644     allowed += get_connection_allowed (iter);
2645   }
2646   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
2647
2648   /* Make sure there is no overflow */
2649   if (allowed > buffer)
2650   {
2651     return;
2652   }
2653
2654   /* Authorize connections to send more data */
2655   to_allow = buffer; /* - allowed; */
2656
2657   for (iter = t->connection_head;
2658        NULL != iter && to_allow > 0;
2659        iter = iter->next)
2660   {
2661     allow_per_connection = to_allow/cs;
2662     to_allow -= allow_per_connection;
2663     cs--;
2664     if (get_connection_allowed (iter) > 64 / 3)
2665     {
2666       continue;
2667     }
2668     GCC_allow (iter->c, allow_per_connection,
2669                GCC_is_origin (iter->c, GNUNET_NO));
2670   }
2671
2672   GNUNET_break (to_allow == 0);
2673 }
2674
2675
2676 /**
2677  * Cancel a previously sent message while it's in the queue.
2678  *
2679  * ONLY can be called before the continuation given to the send function
2680  * is called. Once the continuation is called, the message is no longer in the
2681  * queue.
2682  *
2683  * @param q Handle to the queue.
2684  */
2685 void
2686 GCT_cancel (struct CadetTunnelQueue *q)
2687 {
2688   if (NULL != q->cq)
2689   {
2690     GCC_cancel (q->cq);
2691     /* tun_message_sent() will be called and free q */
2692   }
2693   else if (NULL != q->tqd)
2694   {
2695     unqueue_data (q->tqd);
2696     q->tqd = NULL;
2697     if (NULL != q->cont)
2698       q->cont (q->cont_cls, NULL, q, 0, 0);
2699     GNUNET_free (q);
2700   }
2701   else
2702   {
2703     GNUNET_break (0);
2704   }
2705 }
2706
2707
2708 /**
2709  * Sends an already built message on a tunnel, encrypting it and
2710  * choosing the best connection if not provided.
2711  *
2712  * @param message Message to send. Function modifies it.
2713  * @param t Tunnel on which this message is transmitted.
2714  * @param c Connection to use (autoselect if NULL).
2715  * @param force Force the tunnel to take the message (buffer overfill).
2716  * @param cont Continuation to call once message is really sent.
2717  * @param cont_cls Closure for @c cont.
2718  *
2719  * @return Handle to cancel message. NULL if @c cont is NULL.
2720  */
2721 struct CadetTunnelQueue *
2722 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2723                            struct CadetTunnel *t, struct CadetConnection *c,
2724                            int force, GCT_sent cont, void *cont_cls)
2725 {
2726   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
2727 }
2728
2729
2730 /**
2731  * Is the tunnel directed towards the local peer?
2732  *
2733  * @param t Tunnel.
2734  *
2735  * @return #GNUNET_YES if it is loopback.
2736  */
2737 int
2738 GCT_is_loopback (const struct CadetTunnel *t)
2739 {
2740   return (myid == GCP_get_short_id (t->peer));
2741 }
2742
2743
2744 /**
2745  * Is the tunnel this path already?
2746  *
2747  * @param t Tunnel.
2748  * @param p Path.
2749  *
2750  * @return #GNUNET_YES a connection uses this path.
2751  */
2752 int
2753 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
2754 {
2755   struct CadetTConnection *iter;
2756
2757   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2758     if (GCC_get_path (iter->c) == p)
2759       return GNUNET_YES;
2760
2761   return GNUNET_NO;
2762 }
2763
2764
2765 /**
2766  * Get a cost of a path for a tunnel considering existing connections.
2767  *
2768  * @param t Tunnel.
2769  * @param path Candidate path.
2770  *
2771  * @return Cost of the path (path length + number of overlapping nodes)
2772  */
2773 unsigned int
2774 GCT_get_path_cost (const struct CadetTunnel *t,
2775                    const struct CadetPeerPath *path)
2776 {
2777   struct CadetTConnection *iter;
2778   const struct CadetPeerPath *aux;
2779   unsigned int overlap;
2780   unsigned int i;
2781   unsigned int j;
2782
2783   if (NULL == path)
2784     return 0;
2785
2786   overlap = 0;
2787   GNUNET_assert (NULL != t);
2788
2789   for (i = 0; i < path->length; i++)
2790   {
2791     for (iter = t->connection_head; NULL != iter; iter = iter->next)
2792     {
2793       aux = GCC_get_path (iter->c);
2794       if (NULL == aux)
2795         continue;
2796
2797       for (j = 0; j < aux->length; j++)
2798       {
2799         if (path->peers[i] == aux->peers[j])
2800         {
2801           overlap++;
2802           break;
2803         }
2804       }
2805     }
2806   }
2807   return path->length + overlap;
2808 }
2809
2810
2811 /**
2812  * Get the static string for the peer this tunnel is directed.
2813  *
2814  * @param t Tunnel.
2815  *
2816  * @return Static string the destination peer's ID.
2817  */
2818 const char *
2819 GCT_2s (const struct CadetTunnel *t)
2820 {
2821   if (NULL == t)
2822     return "(NULL)";
2823
2824   return GCP_2s (t->peer);
2825 }
2826
2827
2828 /******************************************************************************/
2829 /*****************************    INFO/DEBUG    *******************************/
2830 /******************************************************************************/
2831
2832
2833 /**
2834  * Log all possible info about the tunnel state to stderr.
2835  *
2836  * @param t Tunnel to debug.
2837  */
2838 void
2839 GCT_debug (const struct CadetTunnel *t)
2840 {
2841   struct CadetTChannel *iterch;
2842   struct CadetTConnection *iterc;
2843
2844   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
2845   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  cstate %s, estate %s\n",
2846        cstate2s (t->cstate), estate2s (t->estate));
2847   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  kx_ctx %p, rekey_task %u\n",
2848        t->kx_ctx, t->rekey_task);
2849   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  tq_head %p, tq_tail %p\n",
2850        t->tq_head, t->tq_tail);
2851   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  destroy %u\n", t->destroy_task);
2852
2853   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  channels:\n");
2854   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
2855   {
2856     LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  - %s\n", GCCH_2s (iterch->ch));
2857   }
2858
2859   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  connections:\n");
2860   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
2861   {
2862     LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT  - %s [%u] buf: %u/%u (qn %u/%u)\n",
2863          GCC_2s (iterc->c), GCC_get_state (iterc->c),
2864          GCC_get_buffer (iterc->c, GNUNET_YES),
2865          GCC_get_buffer (iterc->c, GNUNET_NO),
2866          GCC_get_qn (iterc->c, GNUNET_YES),
2867          GCC_get_qn (iterc->c, GNUNET_NO));
2868   }
2869
2870   LOG (GNUNET_ERROR_TYPE_DEBUG, "TTT DEBUG TUNNEL END\n");
2871 }
2872
2873
2874 /**
2875  * Iterate all tunnels.
2876  *
2877  * @param iter Iterator.
2878  * @param cls Closure for @c iter.
2879  */
2880 void
2881 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2882 {
2883   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
2884 }
2885
2886
2887 /**
2888  * Count all tunnels.
2889  *
2890  * @return Number of tunnels to remote peers kept by this peer.
2891  */
2892 unsigned int
2893 GCT_count_all (void)
2894 {
2895   return GNUNET_CONTAINER_multipeermap_size (tunnels);
2896 }
2897
2898
2899 /**
2900  * Iterate all connections of a tunnel.
2901  *
2902  * @param t Tunnel whose connections to iterate.
2903  * @param iter Iterator.
2904  * @param cls Closure for @c iter.
2905  */
2906 void
2907 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
2908 {
2909   struct CadetTConnection *ct;
2910
2911   for (ct = t->connection_head; NULL != ct; ct = ct->next)
2912     iter (cls, ct->c);
2913 }
2914
2915
2916 /**
2917  * Iterate all channels of a tunnel.
2918  *
2919  * @param t Tunnel whose channels to iterate.
2920  * @param iter Iterator.
2921  * @param cls Closure for @c iter.
2922  */
2923 void
2924 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
2925 {
2926   struct CadetTChannel *cht;
2927
2928   for (cht = t->channel_head; NULL != cht; cht = cht->next)
2929     iter (cls, cht->ch);
2930 }