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