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