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