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