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