- don't warn when connection is being established
[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             && CADET_TUNNEL_WAITING != t->cstate))
1076     {
1077       GNUNET_break (0);
1078       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1079     }
1080     return NULL;
1081   }
1082
1083   mid = 0;
1084   type = ntohs (message->type);
1085   switch (type)
1086   {
1087     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1088     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1089       if (GNUNET_MESSAGE_TYPE_CADET_DATA == type)
1090         mid = ntohl (((struct GNUNET_CADET_Data *) message)->mid);
1091       else
1092         mid = ntohl (((struct GNUNET_CADET_DataACK *) message)->mid);
1093       /* Fall thru */
1094     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1095     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1096     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1097     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1098     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1099       msg->cid = *GCC_get_id (c);
1100       msg->ttl = htonl (default_ttl);
1101       break;
1102     default:
1103       GNUNET_break (0);
1104   }
1105   LOG (GNUNET_ERROR_TYPE_DEBUG, "type %s\n", GC_m2s (type));
1106
1107   fwd = GCC_is_origin (c, GNUNET_YES);
1108
1109   if (NULL == cont)
1110   {
1111     GNUNET_break (NULL == GCC_send_prebuilt_message (&msg->header, type, mid, c,
1112                                                      fwd, force, NULL, NULL));
1113     return NULL;
1114   }
1115   if (NULL == existing_q)
1116   {
1117     tq = GNUNET_new (struct CadetTunnelQueue); /* FIXME valgrind: leak*/
1118   }
1119   else
1120   {
1121     tq = existing_q;
1122     tq->tqd = NULL;
1123   }
1124   tq->cq = GCC_send_prebuilt_message (&msg->header, type, mid, c, fwd, force,
1125                                       &tun_message_sent, tq);
1126   GNUNET_assert (NULL != tq->cq);
1127   tq->cont = cont;
1128   tq->cont_cls = cont_cls;
1129
1130   return tq;
1131 }
1132
1133
1134 /**
1135  * Send all cached messages that we can, tunnel is online.
1136  *
1137  * @param t Tunnel that holds the messages. Cannot be loopback.
1138  */
1139 static void
1140 send_queued_data (struct CadetTunnel *t)
1141 {
1142   struct CadetTunnelDelayed *tqd;
1143   struct CadetTunnelDelayed *next;
1144   unsigned int room;
1145
1146   LOG (GNUNET_ERROR_TYPE_DEBUG,
1147        "GCT_send_queued_data on tunnel %s\n",
1148        GCT_2s (t));
1149
1150   if (GCT_is_loopback (t))
1151   {
1152     GNUNET_break (0);
1153     return;
1154   }
1155
1156   if (GNUNET_NO == is_ready (t))
1157   {
1158     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not ready yet: %s/%s\n",
1159          estate2s (t->estate), cstate2s (t->cstate));
1160     return;
1161   }
1162
1163   room = GCT_get_connections_buffer (t);
1164   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer space: %u\n", room);
1165   LOG (GNUNET_ERROR_TYPE_DEBUG, "  tq head: %p\n", t->tq_head);
1166   for (tqd = t->tq_head; NULL != tqd && room > 0; tqd = next)
1167   {
1168     LOG (GNUNET_ERROR_TYPE_DEBUG, " sending queued data\n");
1169     next = tqd->next;
1170     room--;
1171     send_prebuilt_message ((struct GNUNET_MessageHeader *) &tqd[1],
1172                            tqd->t, NULL, GNUNET_YES,
1173                            NULL != tqd->tq ? tqd->tq->cont : NULL,
1174                            NULL != tqd->tq ? tqd->tq->cont_cls : NULL,
1175                            tqd->tq);
1176     unqueue_data (tqd);
1177   }
1178   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_send_queued_data end\n", GCP_2s (t->peer));
1179 }
1180
1181
1182 /**
1183  * Sends key exchange message on a tunnel, choosing the best connection.
1184  * Should not be called on loopback tunnels.
1185  *
1186  * @param t Tunnel on which this message is transmitted.
1187  * @param message Message to send. Function modifies it.
1188  */
1189 static void
1190 send_kx (struct CadetTunnel *t,
1191          const struct GNUNET_MessageHeader *message)
1192 {
1193   struct CadetConnection *c;
1194   struct GNUNET_CADET_KX *msg;
1195   size_t size = ntohs (message->size);
1196   char cbuf[sizeof (struct GNUNET_CADET_KX) + size];
1197   uint16_t type;
1198   int fwd;
1199
1200   LOG (GNUNET_ERROR_TYPE_DEBUG, "GMT KX on Tunnel %s\n", GCT_2s (t));
1201
1202   /* Avoid loopback. */
1203   if (GCT_is_loopback (t))
1204   {
1205     LOG (GNUNET_ERROR_TYPE_DEBUG, "  loopback!\n");
1206     GNUNET_break (0);
1207     return;
1208   }
1209   type = ntohs (message->type);
1210
1211   /* Even if tunnel is being destroyed, send anyway.
1212    * Could be a response to a rekey initiated by remote peer,
1213    * who is trying to create a new channel!
1214    */
1215
1216   /* Must have a connection. */
1217   if (NULL == t->connection_head && CADET_TUNNEL_SEARCHING != t->cstate)
1218   {
1219     LOG (GNUNET_ERROR_TYPE_WARNING, "\n\n\n");
1220     GNUNET_break (0);
1221     LOG (GNUNET_ERROR_TYPE_WARNING, "sending %s\n", GC_m2s (type));
1222     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1223     GCP_debug (t->peer, GNUNET_ERROR_TYPE_WARNING);
1224     LOG (GNUNET_ERROR_TYPE_WARNING, "\n\n\n");
1225     return;
1226   }
1227
1228   msg = (struct GNUNET_CADET_KX *) cbuf;
1229   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX);
1230   msg->header.size = htons (sizeof (struct GNUNET_CADET_KX) + size);
1231   c = tunnel_get_connection (t);
1232   if (NULL == c)
1233   {
1234     GNUNET_break (GNUNET_SCHEDULER_NO_TASK != t->destroy_task
1235                   || CADET_TUNNEL_READY != t->cstate);
1236     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1237     return;
1238   }
1239   switch (type)
1240   {
1241     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
1242     case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
1243     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
1244       memcpy (&msg[1], message, size);
1245       break;
1246     default:
1247       LOG (GNUNET_ERROR_TYPE_DEBUG, "unkown type %s\n",
1248            GC_m2s (type));
1249       GNUNET_break (0);
1250   }
1251
1252   fwd = GCC_is_origin (t->connection_head->c, GNUNET_YES);
1253   /* TODO save handle and cancel in case of a unneeded retransmission */
1254   GNUNET_assert (NULL == GCC_send_prebuilt_message (&msg->header, type, 0, c,
1255                                                     fwd, GNUNET_YES,
1256                                                     NULL, NULL));
1257 }
1258
1259
1260 /**
1261  * Send the ephemeral key on a tunnel.
1262  *
1263  * @param t Tunnel on which to send the key.
1264  */
1265 static void
1266 send_ephemeral (struct CadetTunnel *t)
1267 {
1268   LOG (GNUNET_ERROR_TYPE_INFO, "===> EPHM for %s\n", GCT_2s (t));
1269
1270   kx_msg.sender_status = htonl (t->estate);
1271   send_kx (t, &kx_msg.header);
1272 }
1273
1274 /**
1275  * Send a ping message on a tunnel.
1276  *
1277  * @param t Tunnel on which to send the ping.
1278  */
1279 static void
1280 send_ping (struct CadetTunnel *t)
1281 {
1282   struct GNUNET_CADET_KX_Ping msg;
1283
1284   LOG (GNUNET_ERROR_TYPE_INFO, "===> PING for %s\n", GCT_2s (t));
1285   msg.header.size = htons (sizeof (msg));
1286   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PING);
1287   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1288   msg.target = *GCP_get_id (t->peer);
1289   msg.nonce = t->kx_ctx->challenge;
1290
1291   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
1292   LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&msg.target));
1293   t_encrypt (t, &msg.target, &msg.target,
1294              ping_encryption_size(), msg.iv, GNUNET_YES);
1295   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
1296   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg.target));
1297
1298   send_kx (t, &msg.header);
1299 }
1300
1301
1302 /**
1303  * Send a pong message on a tunnel.
1304  *d_
1305  * @param t Tunnel on which to send the pong.
1306  * @param challenge Value sent in the ping that we have to send back.
1307  */
1308 static void
1309 send_pong (struct CadetTunnel *t, uint32_t challenge)
1310 {
1311   struct GNUNET_CADET_KX_Pong msg;
1312
1313   LOG (GNUNET_ERROR_TYPE_INFO, "===> PONG for %s\n", GCT_2s (t));
1314   msg.header.size = htons (sizeof (msg));
1315   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_PONG);
1316   msg.iv = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
1317   msg.nonce = challenge;
1318   LOG (GNUNET_ERROR_TYPE_DEBUG, "  sending %u\n", msg.nonce);
1319   t_encrypt (t, &msg.nonce, &msg.nonce,
1320              sizeof (msg.nonce), msg.iv, GNUNET_YES);
1321   LOG (GNUNET_ERROR_TYPE_DEBUG, "  e sending %u\n", msg.nonce);
1322
1323   send_kx (t, &msg.header);
1324 }
1325
1326
1327 /**
1328  * Initiate a rekey with the remote peer.
1329  *
1330  * @param cls Closure (tunnel).
1331  * @param tc TaskContext.
1332  */
1333 static void
1334 rekey_tunnel (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1335 {
1336   struct CadetTunnel *t = cls;
1337
1338   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1339
1340   LOG (GNUNET_ERROR_TYPE_INFO, "Re-key Tunnel %s\n", GCT_2s (t));
1341   if (NULL != tc && 0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1342     return;
1343
1344   if (NULL == t->kx_ctx)
1345   {
1346     create_kx_ctx (t);
1347     create_keys (t);
1348   }
1349   else
1350   {
1351     struct GNUNET_TIME_Relative duration;
1352
1353     duration = GNUNET_TIME_absolute_get_duration (t->kx_ctx->rekey_start_time);
1354     LOG (GNUNET_ERROR_TYPE_DEBUG, " kx started %s ago\n",
1355          GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES));
1356
1357     // FIXME make duration of old keys configurable
1358     if (duration.rel_value_us >= GNUNET_TIME_UNIT_MINUTES.rel_value_us)
1359     {
1360       memset (&t->kx_ctx->d_key_old, 0, sizeof (t->kx_ctx->d_key_old));
1361       memset (&t->kx_ctx->e_key_old, 0, sizeof (t->kx_ctx->e_key_old));
1362     }
1363   }
1364
1365   send_ephemeral (t);
1366
1367   switch (t->estate)
1368   {
1369     case CADET_TUNNEL_KEY_UNINITIALIZED:
1370       t->estate = CADET_TUNNEL_KEY_SENT;
1371       break;
1372     case CADET_TUNNEL_KEY_SENT:
1373       break;
1374     case CADET_TUNNEL_KEY_OK:
1375       t->estate = CADET_TUNNEL_KEY_REKEY;
1376       /* fall-thru */
1377     case CADET_TUNNEL_KEY_PING:
1378     case CADET_TUNNEL_KEY_REKEY:
1379       send_ping (t);
1380       break;
1381     default:
1382       LOG (GNUNET_ERROR_TYPE_DEBUG, "Unexpected state %u\n", t->estate);
1383   }
1384
1385   // FIXME exponential backoff
1386   struct GNUNET_TIME_Relative delay;
1387
1388   delay = GNUNET_TIME_relative_divide (rekey_period, 16);
1389   delay = GNUNET_TIME_relative_min (delay, REKEY_WAIT);
1390   LOG (GNUNET_ERROR_TYPE_DEBUG, "  next call in %s\n",
1391        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1392   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1393 }
1394
1395
1396 /**
1397  * Our ephemeral key has changed, create new session key on all tunnels.
1398  *
1399  * Each tunnel will start the Key Exchange with a random delay between
1400  * 0 and number_of_tunnels*100 milliseconds, so there are 10 key exchanges
1401  * per second, on average.
1402  *
1403  * @param cls Closure (size of the hashmap).
1404  * @param key Current public key.
1405  * @param value Value in the hash map (tunnel).
1406  *
1407  * @return #GNUNET_YES, so we should continue to iterate,
1408  */
1409 static int
1410 rekey_iterator (void *cls,
1411                 const struct GNUNET_PeerIdentity *key,
1412                 void *value)
1413 {
1414   struct CadetTunnel *t = value;
1415   struct GNUNET_TIME_Relative delay;
1416   long n = (long) cls;
1417   uint32_t r;
1418
1419   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
1420     return GNUNET_YES;
1421
1422   if (GNUNET_YES == GCT_is_loopback (t))
1423     return GNUNET_YES;
1424
1425   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t) n * 100);
1426   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, r);
1427   t->rekey_task = GNUNET_SCHEDULER_add_delayed (delay, &rekey_tunnel, t);
1428
1429   return GNUNET_YES;
1430 }
1431
1432
1433 /**
1434  * Create a new ephemeral key and key message, schedule next rekeying.
1435  *
1436  * @param cls Closure (unused).
1437  * @param tc TaskContext.
1438  */
1439 static void
1440 rekey (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1441 {
1442   struct GNUNET_TIME_Absolute time;
1443   long n;
1444
1445   rekey_task = GNUNET_SCHEDULER_NO_TASK;
1446
1447   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1448     return;
1449
1450   GNUNET_free_non_null (my_ephemeral_key);
1451   my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create ();
1452
1453   time = GNUNET_TIME_absolute_get ();
1454   kx_msg.creation_time = GNUNET_TIME_absolute_hton (time);
1455   time = GNUNET_TIME_absolute_add (time, rekey_period);
1456   time = GNUNET_TIME_absolute_add (time, GNUNET_TIME_UNIT_MINUTES);
1457   kx_msg.expiration_time = GNUNET_TIME_absolute_hton (time);
1458   GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, &kx_msg.ephemeral_key);
1459
1460   GNUNET_assert (GNUNET_OK ==
1461                  GNUNET_CRYPTO_eddsa_sign (my_private_key,
1462                                            &kx_msg.purpose,
1463                                            &kx_msg.signature));
1464
1465   n = (long) GNUNET_CONTAINER_multipeermap_size (tunnels);
1466   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &rekey_iterator, (void *) n);
1467
1468   rekey_task = GNUNET_SCHEDULER_add_delayed (rekey_period, &rekey, NULL);
1469 }
1470
1471
1472 /**
1473  * Called only on shutdown, destroy every tunnel.
1474  *
1475  * @param cls Closure (unused).
1476  * @param key Current public key.
1477  * @param value Value in the hash map (tunnel).
1478  *
1479  * @return #GNUNET_YES, so we should continue to iterate,
1480  */
1481 static int
1482 destroy_iterator (void *cls,
1483                 const struct GNUNET_PeerIdentity *key,
1484                 void *value)
1485 {
1486   struct CadetTunnel *t = value;
1487
1488   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_shutdown destroying tunnel at %p\n", t);
1489   GCT_destroy (t);
1490   return GNUNET_YES;
1491 }
1492
1493
1494 /**
1495  * Notify remote peer that we don't know a channel he is talking about,
1496  * probably CHANNEL_DESTROY was missed.
1497  *
1498  * @param t Tunnel on which to notify.
1499  * @param gid ID of the channel.
1500  */
1501 static void
1502 send_channel_destroy (struct CadetTunnel *t, unsigned int gid)
1503 {
1504   struct GNUNET_CADET_ChannelManage msg;
1505
1506   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
1507   msg.header.size = htons (sizeof (msg));
1508   msg.chid = htonl (gid);
1509
1510   LOG (GNUNET_ERROR_TYPE_DEBUG,
1511        "WARNING destroying unknown channel %u on tunnel %s\n",
1512        gid, GCT_2s (t));
1513   send_prebuilt_message (&msg.header, t, NULL, GNUNET_YES, NULL, NULL, NULL);
1514 }
1515
1516
1517 /**
1518  * Demultiplex data per channel and call appropriate channel handler.
1519  *
1520  * @param t Tunnel on which the data came.
1521  * @param msg Data message.
1522  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1523  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1524  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1525  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1526  */
1527 static void
1528 handle_data (struct CadetTunnel *t,
1529              const struct GNUNET_CADET_Data *msg,
1530              int fwd)
1531 {
1532   struct CadetChannel *ch;
1533   size_t size;
1534
1535   /* Check size */
1536   size = ntohs (msg->header.size);
1537   if (size <
1538       sizeof (struct GNUNET_CADET_Data) +
1539       sizeof (struct GNUNET_MessageHeader))
1540   {
1541     GNUNET_break (0);
1542     return;
1543   }
1544   LOG (GNUNET_ERROR_TYPE_DEBUG, " payload of type %s\n",
1545               GC_m2s (ntohs (msg[1].header.type)));
1546
1547   /* Check channel */
1548   ch = GCT_get_channel (t, ntohl (msg->chid));
1549   if (NULL == ch)
1550   {
1551     GNUNET_STATISTICS_update (stats, "# data on unknown channel",
1552                               1, GNUNET_NO);
1553     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel 0x%X unknown\n",
1554          ntohl (msg->chid));
1555     send_channel_destroy (t, ntohl (msg->chid));
1556     return;
1557   }
1558
1559   GCCH_handle_data (ch, msg, fwd);
1560 }
1561
1562
1563 /**
1564  * Demultiplex data ACKs per channel and update appropriate channel buffer info.
1565  *
1566  * @param t Tunnel on which the DATA ACK came.
1567  * @param msg DATA ACK message.
1568  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1569  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1570  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1571  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1572  */
1573 static void
1574 handle_data_ack (struct CadetTunnel *t,
1575                  const struct GNUNET_CADET_DataACK *msg,
1576                  int fwd)
1577 {
1578   struct CadetChannel *ch;
1579   size_t size;
1580
1581   /* Check size */
1582   size = ntohs (msg->header.size);
1583   if (size != sizeof (struct GNUNET_CADET_DataACK))
1584   {
1585     GNUNET_break (0);
1586     return;
1587   }
1588
1589   /* Check channel */
1590   ch = GCT_get_channel (t, ntohl (msg->chid));
1591   if (NULL == ch)
1592   {
1593     GNUNET_STATISTICS_update (stats, "# data ack on unknown channel",
1594                               1, GNUNET_NO);
1595     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1596          ntohl (msg->chid));
1597     return;
1598   }
1599
1600   GCCH_handle_data_ack (ch, msg, fwd);
1601 }
1602
1603
1604 /**
1605  * Handle channel create.
1606  *
1607  * @param t Tunnel on which the data came.
1608  * @param msg Data message.
1609  */
1610 static void
1611 handle_ch_create (struct CadetTunnel *t,
1612                   const struct GNUNET_CADET_ChannelCreate *msg)
1613 {
1614   struct CadetChannel *ch;
1615   size_t size;
1616
1617   /* Check size */
1618   size = ntohs (msg->header.size);
1619   if (size != sizeof (struct GNUNET_CADET_ChannelCreate))
1620   {
1621     GNUNET_break (0);
1622     return;
1623   }
1624
1625   /* Check channel */
1626   ch = GCT_get_channel (t, ntohl (msg->chid));
1627   if (NULL != ch && ! GCT_is_loopback (t))
1628   {
1629     /* Probably a retransmission, safe to ignore */
1630     LOG (GNUNET_ERROR_TYPE_DEBUG, "   already exists...\n");
1631   }
1632   ch = GCCH_handle_create (t, msg);
1633   if (NULL != ch)
1634     GCT_add_channel (t, ch);
1635 }
1636
1637
1638
1639 /**
1640  * Handle channel NACK: check correctness and call channel handler for NACKs.
1641  *
1642  * @param t Tunnel on which the NACK came.
1643  * @param msg NACK message.
1644  */
1645 static void
1646 handle_ch_nack (struct CadetTunnel *t,
1647                 const struct GNUNET_CADET_ChannelManage *msg)
1648 {
1649   struct CadetChannel *ch;
1650   size_t size;
1651
1652   /* Check size */
1653   size = ntohs (msg->header.size);
1654   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1655   {
1656     GNUNET_break (0);
1657     return;
1658   }
1659
1660   /* Check channel */
1661   ch = GCT_get_channel (t, ntohl (msg->chid));
1662   if (NULL == ch)
1663   {
1664     GNUNET_STATISTICS_update (stats, "# channel NACK on unknown channel",
1665                               1, GNUNET_NO);
1666     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1667          ntohl (msg->chid));
1668     return;
1669   }
1670
1671   GCCH_handle_nack (ch);
1672 }
1673
1674
1675 /**
1676  * Handle a CHANNEL ACK (SYNACK/ACK).
1677  *
1678  * @param t Tunnel on which the CHANNEL ACK came.
1679  * @param msg CHANNEL ACK message.
1680  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1681  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1682  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1683  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1684  */
1685 static void
1686 handle_ch_ack (struct CadetTunnel *t,
1687                const struct GNUNET_CADET_ChannelManage *msg,
1688                int fwd)
1689 {
1690   struct CadetChannel *ch;
1691   size_t size;
1692
1693   /* Check size */
1694   size = ntohs (msg->header.size);
1695   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1696   {
1697     GNUNET_break (0);
1698     return;
1699   }
1700
1701   /* Check channel */
1702   ch = GCT_get_channel (t, ntohl (msg->chid));
1703   if (NULL == ch)
1704   {
1705     GNUNET_STATISTICS_update (stats, "# channel ack on unknown channel",
1706                               1, GNUNET_NO);
1707     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING channel %u unknown\n",
1708          ntohl (msg->chid));
1709     return;
1710   }
1711
1712   GCCH_handle_ack (ch, msg, fwd);
1713 }
1714
1715
1716 /**
1717  * Handle a channel destruction message.
1718  *
1719  * @param t Tunnel on which the message came.
1720  * @param msg Channel destroy message.
1721  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1722  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1723  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1724  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1725  */
1726 static void
1727 handle_ch_destroy (struct CadetTunnel *t,
1728                    const struct GNUNET_CADET_ChannelManage *msg,
1729                    int fwd)
1730 {
1731   struct CadetChannel *ch;
1732   size_t size;
1733
1734   /* Check size */
1735   size = ntohs (msg->header.size);
1736   if (size != sizeof (struct GNUNET_CADET_ChannelManage))
1737   {
1738     GNUNET_break (0);
1739     return;
1740   }
1741
1742   /* Check channel */
1743   ch = GCT_get_channel (t, ntohl (msg->chid));
1744   if (NULL == ch)
1745   {
1746     /* Probably a retransmission, safe to ignore */
1747     return;
1748   }
1749
1750   GCCH_handle_destroy (ch, msg, fwd);
1751 }
1752
1753
1754 /**
1755  * The peer's ephemeral key has changed: update the symmetrical keys.
1756  *
1757  * @param t Tunnel this message came on.
1758  * @param msg Key eXchange message.
1759  */
1760 static void
1761 handle_ephemeral (struct CadetTunnel *t,
1762                   const struct GNUNET_CADET_KX_Ephemeral *msg)
1763 {
1764   LOG (GNUNET_ERROR_TYPE_INFO, "<=== EPHM for %s\n", GCT_2s (t));
1765
1766   if (GNUNET_OK != check_ephemeral (t, msg))
1767   {
1768     GNUNET_break_op (0);
1769     return;
1770   }
1771
1772   if (NULL == t->kx_ctx)
1773     create_kx_ctx (t);
1774   if (0 != memcmp (&t->peers_ephemeral_key, &msg->ephemeral_key,
1775                    sizeof (msg->ephemeral_key)))
1776   {
1777     t->peers_ephemeral_key = msg->ephemeral_key;
1778     create_keys (t);
1779     if (CADET_TUNNEL_KEY_OK == t->estate)
1780     {
1781       t->estate = CADET_TUNNEL_KEY_REKEY;
1782     }
1783   }
1784   if (CADET_TUNNEL_KEY_SENT == t->estate)
1785   {
1786     LOG (GNUNET_ERROR_TYPE_DEBUG, "  our key was sent, sending ping\n");
1787     send_ping (t);
1788     t->estate = CADET_TUNNEL_KEY_PING;
1789   }
1790 }
1791
1792
1793 /**
1794  * Peer wants to check our symmetrical keys by sending an encrypted challenge.
1795  * Answer with by retransmitting the challenge with the "opposite" key.
1796  *
1797  * @param t Tunnel this message came on.
1798  * @param msg Key eXchange Ping message.
1799  */
1800 static void
1801 handle_ping (struct CadetTunnel *t,
1802              const struct GNUNET_CADET_KX_Ping *msg)
1803 {
1804   struct GNUNET_CADET_KX_Ping res;
1805
1806   if (ntohs (msg->header.size) != sizeof (res))
1807   {
1808     GNUNET_break_op (0);
1809     return;
1810   }
1811
1812   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PING for %s\n", GCT_2s (t));
1813   t_decrypt (t, &res.target, &msg->target, ping_encryption_size (), msg->iv);
1814   if (0 != memcmp (&my_full_id, &res.target, sizeof (my_full_id)))
1815   {
1816     GNUNET_STATISTICS_update (stats, "# malformed PINGs", 1, GNUNET_NO);
1817     LOG (GNUNET_ERROR_TYPE_WARNING, "  malformed PING on %s\n", GCT_2s (t));
1818     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e got %u\n", msg->nonce);
1819     LOG (GNUNET_ERROR_TYPE_DEBUG, "  e towards %s\n", GNUNET_i2s (&msg->target));
1820     LOG (GNUNET_ERROR_TYPE_DEBUG, "  got %u\n", res.nonce);
1821     LOG (GNUNET_ERROR_TYPE_DEBUG, "  towards %s\n", GNUNET_i2s (&res.target));
1822     if (NULL == t->kx_ctx)
1823       create_kx_ctx (t);
1824     send_ephemeral (t);
1825     send_ping (t);
1826     return;
1827   }
1828
1829   send_pong (t, res.nonce);
1830 }
1831
1832
1833 /**
1834  * @brief Finish the Key eXchange and destroy the old keys.
1835  *
1836  * @param cls Closure (Tunnel for which to finish the KX).
1837  * @param tc Task context.
1838  */
1839 static void
1840 finish_kx (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1841 {
1842   struct CadetTunnel *t = cls;
1843
1844   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1845     return;
1846
1847   LOG (GNUNET_ERROR_TYPE_INFO, "finish KX for %s\n", GCT_2s (t));
1848
1849   GNUNET_free (t->kx_ctx);
1850   t->kx_ctx = NULL;
1851 }
1852
1853
1854 /**
1855  * Peer has answer to our challenge.
1856  * If answer is successful, consider the key exchange finished and clean
1857  * up all related state.
1858  *
1859  * @param t Tunnel this message came on.
1860  * @param msg Key eXchange Pong message.
1861  */
1862 static void
1863 handle_pong (struct CadetTunnel *t,
1864              const struct GNUNET_CADET_KX_Pong *msg)
1865 {
1866   uint32_t challenge;
1867
1868   LOG (GNUNET_ERROR_TYPE_INFO, "<=== PONG for %s\n", GCT_2s (t));
1869   if (GNUNET_SCHEDULER_NO_TASK == t->rekey_task)
1870   {
1871     GNUNET_STATISTICS_update (stats, "# duplicate PONG messages", 1, GNUNET_NO);
1872     return;
1873   }
1874   t_decrypt (t, &challenge, &msg->nonce, sizeof (uint32_t), msg->iv);
1875
1876   if (challenge != t->kx_ctx->challenge)
1877   {
1878     LOG (GNUNET_ERROR_TYPE_WARNING, "Wrong PONG challenge on %s\n", GCT_2s (t));
1879     LOG (GNUNET_ERROR_TYPE_DEBUG, "PONG: %u (e: %u). Expected: %u.\n",
1880          challenge, msg->nonce, t->kx_ctx->challenge);
1881     send_ephemeral (t);
1882     send_ping (t);
1883     return;
1884   }
1885   GNUNET_SCHEDULER_cancel (t->rekey_task);
1886   t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
1887
1888   /* Don't free the old keys right away, but after a delay.
1889    * Rationale: the KX could have happened over a very fast connection,
1890    * with payload traffic still signed with the old key stuck in a slower
1891    * connection.
1892    * Don't keep the keys longer than 1/4 the rekey period, and no longer than
1893    * one minute.
1894    */
1895   if (GNUNET_SCHEDULER_NO_TASK == t->kx_ctx->finish_task)
1896   {
1897     struct GNUNET_TIME_Relative delay;
1898
1899     delay = GNUNET_TIME_relative_divide (rekey_period, 4);
1900     delay = GNUNET_TIME_relative_min (delay, GNUNET_TIME_UNIT_MINUTES);
1901     t->kx_ctx->finish_task = GNUNET_SCHEDULER_add_delayed (delay, finish_kx, t);
1902   }
1903   GCT_change_estate (t, CADET_TUNNEL_KEY_OK);
1904 }
1905
1906
1907 /**
1908  * Demultiplex by message type and call appropriate handler for a message
1909  * towards a channel of a local tunnel.
1910  *
1911  * @param t Tunnel this message came on.
1912  * @param msgh Message header.
1913  * @param fwd Is this message fwd? This only is meaningful in loopback channels.
1914  *            #GNUNET_YES if message is FWD on the respective channel (loopback)
1915  *            #GNUNET_NO if message is BCK on the respective channel (loopback)
1916  *            #GNUNET_SYSERR if message on a one-ended channel (remote)
1917  */
1918 static void
1919 handle_decrypted (struct CadetTunnel *t,
1920                   const struct GNUNET_MessageHeader *msgh,
1921                   int fwd)
1922 {
1923   uint16_t type;
1924
1925   type = ntohs (msgh->type);
1926   LOG (GNUNET_ERROR_TYPE_INFO, "<=== %s on %s\n", GC_m2s (type), GCT_2s (t));
1927
1928   switch (type)
1929   {
1930     case GNUNET_MESSAGE_TYPE_CADET_KEEPALIVE:
1931       /* Do nothing, connection aleady got updated. */
1932       GNUNET_STATISTICS_update (stats, "# keepalives received", 1, GNUNET_NO);
1933       break;
1934
1935     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1936       /* Don't send hop ACK, wait for client to ACK */
1937       handle_data (t, (struct GNUNET_CADET_Data *) msgh, fwd);
1938       break;
1939
1940     case GNUNET_MESSAGE_TYPE_CADET_DATA_ACK:
1941       handle_data_ack (t, (struct GNUNET_CADET_DataACK *) msgh, fwd);
1942       break;
1943
1944     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1945       handle_ch_create (t,
1946                         (struct GNUNET_CADET_ChannelCreate *) msgh);
1947       break;
1948
1949     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_NACK:
1950       handle_ch_nack (t,
1951                       (struct GNUNET_CADET_ChannelManage *) msgh);
1952       break;
1953
1954     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_ACK:
1955       handle_ch_ack (t,
1956                      (struct GNUNET_CADET_ChannelManage *) msgh,
1957                      fwd);
1958       break;
1959
1960     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1961       handle_ch_destroy (t,
1962                          (struct GNUNET_CADET_ChannelManage *) msgh,
1963                          fwd);
1964       break;
1965
1966     default:
1967       GNUNET_break_op (0);
1968       LOG (GNUNET_ERROR_TYPE_WARNING,
1969            "end-to-end message not known (%u)\n",
1970            ntohs (msgh->type));
1971       GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
1972   }
1973 }
1974
1975 /******************************************************************************/
1976 /********************************    API    ***********************************/
1977 /******************************************************************************/
1978
1979 /**
1980  * Decrypt and demultiplex by message type. Call appropriate handler
1981  * for every message.
1982  *
1983  * @param t Tunnel this message came on.
1984  * @param msg Encrypted message.
1985  */
1986 void
1987 GCT_handle_encrypted (struct CadetTunnel *t,
1988                       const struct GNUNET_CADET_Encrypted *msg)
1989 {
1990   size_t size = ntohs (msg->header.size);
1991   size_t payload_size = size - sizeof (struct GNUNET_CADET_Encrypted);
1992   int decrypted_size;
1993   char cbuf [payload_size];
1994   struct GNUNET_MessageHeader *msgh;
1995   unsigned int off;
1996
1997   decrypted_size = t_decrypt_and_validate (t, cbuf, &msg[1], payload_size,
1998                                            msg->iv, &msg->hmac);
1999
2000   if (-1 == decrypted_size)
2001   {
2002     GNUNET_break_op (0);
2003     return;
2004   }
2005
2006   off = 0;
2007   while (off < decrypted_size)
2008   {
2009     uint16_t msize;
2010
2011     msgh = (struct GNUNET_MessageHeader *) &cbuf[off];
2012     msize = ntohs (msgh->size);
2013     if (msize < sizeof (struct GNUNET_MessageHeader))
2014     {
2015       GNUNET_break_op (0);
2016       return;
2017     }
2018     handle_decrypted (t, msgh, GNUNET_SYSERR);
2019     off += msize;
2020   }
2021 }
2022
2023
2024 /**
2025  * Demultiplex an encapsulated KX message by message type.
2026  *
2027  * @param t Tunnel on which the message came.
2028  * @param message Payload of KX message.
2029  */
2030 void
2031 GCT_handle_kx (struct CadetTunnel *t,
2032                const struct GNUNET_MessageHeader *message)
2033 {
2034   uint16_t type;
2035
2036   type = ntohs (message->type);
2037   LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message received\n", type);
2038   switch (type)
2039   {
2040     case GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL:
2041       handle_ephemeral (t, (struct GNUNET_CADET_KX_Ephemeral *) message);
2042       break;
2043
2044     case GNUNET_MESSAGE_TYPE_CADET_KX_PING:
2045       handle_ping (t, (struct GNUNET_CADET_KX_Ping *) message);
2046       break;
2047
2048     case GNUNET_MESSAGE_TYPE_CADET_KX_PONG:
2049       handle_pong (t, (struct GNUNET_CADET_KX_Pong *) message);
2050       break;
2051
2052     default:
2053       GNUNET_break_op (0);
2054       LOG (GNUNET_ERROR_TYPE_DEBUG, "kx message not known (%u)\n", type);
2055   }
2056 }
2057
2058
2059 /**
2060  * Initialize the tunnel subsystem.
2061  *
2062  * @param c Configuration handle.
2063  * @param key ECC private key, to derive all other keys and do crypto.
2064  */
2065 void
2066 GCT_init (const struct GNUNET_CONFIGURATION_Handle *c,
2067           const struct GNUNET_CRYPTO_EddsaPrivateKey *key)
2068 {
2069   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
2070   if (GNUNET_OK !=
2071       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DEFAULT_TTL",
2072                                              &default_ttl))
2073   {
2074     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
2075                                "CADET", "DEFAULT_TTL", "USING DEFAULT");
2076     default_ttl = 64;
2077   }
2078   if (GNUNET_OK !=
2079       GNUNET_CONFIGURATION_get_value_time (c, "CADET", "REKEY_PERIOD",
2080                                            &rekey_period))
2081   {
2082     rekey_period = GNUNET_TIME_UNIT_DAYS;
2083   }
2084
2085   my_private_key = key;
2086   kx_msg.header.size = htons (sizeof (kx_msg));
2087   kx_msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_KX_EPHEMERAL);
2088   kx_msg.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CADET_KX);
2089   kx_msg.purpose.size = htonl (ephemeral_purpose_size ());
2090   kx_msg.origin_identity = my_full_id;
2091   rekey_task = GNUNET_SCHEDULER_add_now (&rekey, NULL);
2092
2093   tunnels = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES);
2094 }
2095
2096
2097 /**
2098  * Shut down the tunnel subsystem.
2099  */
2100 void
2101 GCT_shutdown (void)
2102 {
2103   if (GNUNET_SCHEDULER_NO_TASK != rekey_task)
2104   {
2105     GNUNET_SCHEDULER_cancel (rekey_task);
2106     rekey_task = GNUNET_SCHEDULER_NO_TASK;
2107   }
2108   GNUNET_CONTAINER_multipeermap_iterate (tunnels, &destroy_iterator, NULL);
2109   GNUNET_CONTAINER_multipeermap_destroy (tunnels);
2110 }
2111
2112
2113 /**
2114  * Create a tunnel.
2115  *
2116  * @param destination Peer this tunnel is towards.
2117  */
2118 struct CadetTunnel *
2119 GCT_new (struct CadetPeer *destination)
2120 {
2121   struct CadetTunnel *t;
2122
2123   t = GNUNET_new (struct CadetTunnel);
2124   t->next_chid = 0;
2125   t->peer = destination;
2126
2127   if (GNUNET_OK !=
2128       GNUNET_CONTAINER_multipeermap_put (tunnels, GCP_get_id (destination), t,
2129                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
2130   {
2131     GNUNET_break (0);
2132     GNUNET_free (t);
2133     return NULL;
2134   }
2135   return t;
2136 }
2137
2138
2139 /**
2140  * Change the tunnel's connection state.
2141  *
2142  * @param t Tunnel whose connection state to change.
2143  * @param cstate New connection state.
2144  */
2145 void
2146 GCT_change_cstate (struct CadetTunnel* t, enum CadetTunnelCState cstate)
2147 {
2148   if (NULL == t)
2149     return;
2150   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s cstate %s => %s\n",
2151        GCP_2s (t->peer), cstate2s (t->cstate), cstate2s (cstate));
2152   if (myid != GCP_get_short_id (t->peer) &&
2153       CADET_TUNNEL_READY != t->cstate &&
2154       CADET_TUNNEL_READY == cstate)
2155   {
2156     t->cstate = cstate;
2157     if (CADET_TUNNEL_KEY_OK == t->estate)
2158     {
2159       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered send queued data\n");
2160       send_queued_data (t);
2161     }
2162     else if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
2163     {
2164       LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered rekey\n");
2165       rekey_tunnel (t, NULL);
2166     }
2167   }
2168   t->cstate = cstate;
2169
2170   if (CADET_TUNNEL_READY == cstate
2171       && CONNECTIONS_PER_TUNNEL <= GCT_count_connections (t))
2172   {
2173     LOG (GNUNET_ERROR_TYPE_DEBUG, "  cstate triggered stop dht\n");
2174     GCP_stop_search (t->peer);
2175   }
2176 }
2177
2178 /**
2179  * Change the tunnel encryption state.
2180  *
2181  * @param t Tunnel whose encryption state to change.
2182  * @param state New encryption state.
2183  */
2184 void
2185 GCT_change_estate (struct CadetTunnel* t, enum CadetTunnelEState state)
2186 {
2187   if (NULL == t)
2188     return;
2189   LOG (GNUNET_ERROR_TYPE_DEBUG,
2190        "Tunnel %s estate was %s\n",
2191        GCP_2s (t->peer), estate2s (t->estate));
2192   LOG (GNUNET_ERROR_TYPE_DEBUG,
2193        "Tunnel %s estate is now %s\n",
2194        GCP_2s (t->peer), estate2s (state));
2195   if (myid != GCP_get_short_id (t->peer) &&
2196       CADET_TUNNEL_KEY_OK != t->estate && CADET_TUNNEL_KEY_OK == state)
2197   {
2198     t->estate = state;
2199     send_queued_data (t);
2200     return;
2201   }
2202   t->estate = state;
2203 }
2204
2205
2206 /**
2207  * @brief Check if tunnel has too many connections, and remove one if necessary.
2208  *
2209  * Currently this means the newest connection, unless it is a direct one.
2210  * Implemented as a task to avoid freeing a connection that is in the middle
2211  * of being created/processed.
2212  *
2213  * @param cls Closure (Tunnel to check).
2214  * @param tc Task context.
2215  */
2216 static void
2217 trim_connections (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2218 {
2219   struct CadetTunnel *t = cls;
2220
2221   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2222     return;
2223
2224   if (GCT_count_connections (t) > 2 * CONNECTIONS_PER_TUNNEL)
2225   {
2226     struct CadetTConnection *iter;
2227     struct CadetTConnection *c;
2228
2229     for (c = iter = t->connection_head; NULL != iter; iter = iter->next)
2230     {
2231       if ((NULL == c || iter->created.abs_value_us > c->created.abs_value_us)
2232           && GNUNET_NO == GCC_is_direct (iter->c))
2233       {
2234         c = iter;
2235       }
2236     }
2237     if (NULL != c)
2238     {
2239       LOG (GNUNET_ERROR_TYPE_DEBUG, "Too many connections on tunnel %s\n",
2240            GCT_2s (t));
2241       LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying connection %s\n",
2242            GCC_2s (c->c));
2243       GCC_destroy (c->c);
2244     }
2245     else
2246     {
2247       GNUNET_break (0);
2248     }
2249   }
2250 }
2251
2252
2253 /**
2254  * Add a connection to a tunnel.
2255  *
2256  * @param t Tunnel.
2257  * @param c Connection.
2258  */
2259 void
2260 GCT_add_connection (struct CadetTunnel *t, struct CadetConnection *c)
2261 {
2262   struct CadetTConnection *aux;
2263
2264   GNUNET_assert (NULL != c);
2265
2266   LOG (GNUNET_ERROR_TYPE_DEBUG, "add connection %s\n", GCC_2s (c));
2267   LOG (GNUNET_ERROR_TYPE_DEBUG, " to tunnel %s\n", GCT_2s (t));
2268   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2269     if (aux->c == c)
2270       return;
2271
2272   aux = GNUNET_new (struct CadetTConnection);
2273   aux->c = c;
2274   aux->created = GNUNET_TIME_absolute_get ();
2275
2276   GNUNET_CONTAINER_DLL_insert (t->connection_head, t->connection_tail, aux);
2277
2278   GNUNET_SCHEDULER_add_now (&trim_connections, t);
2279 }
2280
2281
2282 /**
2283  * Mark a path as no longer valid for this tunnel: has been tried and failed.
2284  *
2285  * @param t Tunnel to update.
2286  * @param path Invalid path to remove. Is destroyed after removal.
2287  */
2288 void
2289 GCT_remove_path (struct CadetTunnel *t, struct CadetPeerPath *path)
2290 {
2291   GCP_remove_path (t->peer, path);
2292 }
2293
2294
2295 /**
2296  * Remove a connection from a tunnel.
2297  *
2298  * @param t Tunnel.
2299  * @param c Connection.
2300  */
2301 void
2302 GCT_remove_connection (struct CadetTunnel *t,
2303                        struct CadetConnection *c)
2304 {
2305   struct CadetTConnection *aux;
2306   struct CadetTConnection *next;
2307
2308   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing connection %s from tunnel %s\n",
2309        GCC_2s (c), GCT_2s (t));
2310   for (aux = t->connection_head; aux != NULL; aux = next)
2311   {
2312     next = aux->next;
2313     if (aux->c == c)
2314     {
2315       GNUNET_CONTAINER_DLL_remove (t->connection_head, t->connection_tail, aux);
2316       GNUNET_free (aux);
2317     }
2318   }
2319
2320   /* Start new connections if needed */
2321   if (CONNECTIONS_PER_TUNNEL > GCT_count_connections (t)
2322       && GNUNET_SCHEDULER_NO_TASK == t->destroy_task
2323       && CADET_TUNNEL_SHUTDOWN != t->cstate
2324       && GNUNET_NO == shutting_down)
2325   {
2326     LOG (GNUNET_ERROR_TYPE_DEBUG, "  no more connections, getting new ones\n");
2327     GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2328     GCP_connect (t->peer);
2329     return;
2330   }
2331
2332   /* If not marked as ready, no change is needed */
2333   if (CADET_TUNNEL_READY != t->cstate)
2334     return;
2335
2336   /* Check if any connection is ready to maintain cstate */
2337   for (aux = t->connection_head; aux != NULL; aux = aux->next)
2338     if (CADET_CONNECTION_READY == GCC_get_state (aux->c))
2339       return;
2340
2341   GCT_change_cstate (t, CADET_TUNNEL_WAITING);
2342 }
2343
2344
2345 /**
2346  * Add a channel to a tunnel.
2347  *
2348  * @param t Tunnel.
2349  * @param ch Channel.
2350  */
2351 void
2352 GCT_add_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2353 {
2354   struct CadetTChannel *aux;
2355
2356   GNUNET_assert (NULL != ch);
2357
2358   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding channel %p to tunnel %p\n", ch, t);
2359
2360   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2361   {
2362     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already there %p\n", aux->ch);
2363     if (aux->ch == ch)
2364       return;
2365   }
2366
2367   aux = GNUNET_new (struct CadetTChannel);
2368   aux->ch = ch;
2369   LOG (GNUNET_ERROR_TYPE_DEBUG, " adding %p to %p\n", aux, t->channel_head);
2370   GNUNET_CONTAINER_DLL_insert_tail (t->channel_head, t->channel_tail, aux);
2371
2372   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2373   {
2374     GNUNET_SCHEDULER_cancel (t->destroy_task);
2375     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2376     LOG (GNUNET_ERROR_TYPE_DEBUG, " undo destroy!\n");
2377   }
2378 }
2379
2380
2381 /**
2382  * Remove a channel from a tunnel.
2383  *
2384  * @param t Tunnel.
2385  * @param ch Channel.
2386  */
2387 void
2388 GCT_remove_channel (struct CadetTunnel *t, struct CadetChannel *ch)
2389 {
2390   struct CadetTChannel *aux;
2391
2392   LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing channel %p from tunnel %p\n", ch, t);
2393   for (aux = t->channel_head; aux != NULL; aux = aux->next)
2394   {
2395     if (aux->ch == ch)
2396     {
2397       LOG (GNUNET_ERROR_TYPE_DEBUG, " found! %s\n", GCCH_2s (ch));
2398       GNUNET_CONTAINER_DLL_remove (t->channel_head, t->channel_tail, aux);
2399       GNUNET_free (aux);
2400       return;
2401     }
2402   }
2403 }
2404
2405
2406 /**
2407  * Search for a channel by global ID.
2408  *
2409  * @param t Tunnel containing the channel.
2410  * @param chid Public channel number.
2411  *
2412  * @return channel handler, NULL if doesn't exist
2413  */
2414 struct CadetChannel *
2415 GCT_get_channel (struct CadetTunnel *t, CADET_ChannelNumber chid)
2416 {
2417   struct CadetTChannel *iter;
2418
2419   if (NULL == t)
2420     return NULL;
2421
2422   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2423   {
2424     if (GCCH_get_id (iter->ch) == chid)
2425       break;
2426   }
2427
2428   return NULL == iter ? NULL : iter->ch;
2429 }
2430
2431
2432 /**
2433  * @brief Destroy a tunnel and free all resources.
2434  *
2435  * Should only be called a while after the tunnel has been marked as destroyed,
2436  * in case there is a new channel added to the same peer shortly after marking
2437  * the tunnel. This way we avoid a new public key handshake.
2438  *
2439  * @param cls Closure (tunnel to destroy).
2440  * @param tc Task context.
2441  */
2442 static void
2443 delayed_destroy (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2444 {
2445   struct CadetTunnel *t = cls;
2446   struct CadetTConnection *iter;
2447
2448   LOG (GNUNET_ERROR_TYPE_DEBUG, "delayed destroying tunnel %p\n", t);
2449   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
2450   {
2451     LOG (GNUNET_ERROR_TYPE_WARNING,
2452          "Not destroying tunnel, due to shutdown. "
2453          "Tunnel at %p should have been freed by GCT_shutdown\n", t);
2454     return;
2455   }
2456   t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2457   t->cstate = CADET_TUNNEL_SHUTDOWN;
2458
2459   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2460   {
2461     GCC_send_destroy (iter->c);
2462   }
2463   GCT_destroy (t);
2464 }
2465
2466
2467 /**
2468  * Tunnel is empty: destroy it.
2469  *
2470  * Notifies all connections about the destruction.
2471  *
2472  * @param t Tunnel to destroy.
2473  */
2474 void
2475 GCT_destroy_empty (struct CadetTunnel *t)
2476 {
2477   if (GNUNET_YES == shutting_down)
2478     return; /* Will be destroyed immediately anyway */
2479
2480   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2481   {
2482     LOG (GNUNET_ERROR_TYPE_WARNING,
2483          "Tunnel %s is already scheduled for destruction. Tunnel debug dump:\n",
2484          GCT_2s (t));
2485     GCT_debug (t, GNUNET_ERROR_TYPE_WARNING);
2486     GNUNET_break (0);
2487     /* should never happen, tunnel can only become empty once, and the
2488      * task identifier should be NO_TASK (cleaned when the tunnel was created
2489      * or became un-empty)
2490      */
2491     return;
2492   }
2493
2494   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s empty: destroying scheduled\n",
2495        GCT_2s (t));
2496
2497   // FIXME make delay a config option
2498   t->destroy_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
2499                                                   &delayed_destroy, t);
2500   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled destroy of %p as %llX\n",
2501        t, t->destroy_task);
2502 }
2503
2504
2505 /**
2506  * Destroy tunnel if empty (no more channels).
2507  *
2508  * @param t Tunnel to destroy if empty.
2509  */
2510 void
2511 GCT_destroy_if_empty (struct CadetTunnel *t)
2512 {
2513   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel %s destroy if empty\n", GCT_2s (t));
2514   if (1 < GCT_count_channels (t))
2515     return;
2516
2517   GCT_destroy_empty (t);
2518 }
2519
2520
2521 /**
2522  * Destroy the tunnel.
2523  *
2524  * This function does not generate any warning traffic to clients or peers.
2525  *
2526  * Tasks:
2527  * Cancel messages belonging to this tunnel queued to neighbors.
2528  * Free any allocated resources linked to the tunnel.
2529  *
2530  * @param t The tunnel to destroy.
2531  */
2532 void
2533 GCT_destroy (struct CadetTunnel *t)
2534 {
2535   struct CadetTConnection *iter_c;
2536   struct CadetTConnection *next_c;
2537   struct CadetTChannel *iter_ch;
2538   struct CadetTChannel *next_ch;
2539
2540   if (NULL == t)
2541     return;
2542
2543   LOG (GNUNET_ERROR_TYPE_DEBUG, "destroying tunnel %s\n", GCP_2s (t->peer));
2544
2545   GNUNET_break (GNUNET_YES ==
2546                 GNUNET_CONTAINER_multipeermap_remove (tunnels,
2547                                                       GCP_get_id (t->peer), t));
2548
2549   for (iter_c = t->connection_head; NULL != iter_c; iter_c = next_c)
2550   {
2551     next_c = iter_c->next;
2552     GCC_destroy (iter_c->c);
2553   }
2554   for (iter_ch = t->channel_head; NULL != iter_ch; iter_ch = next_ch)
2555   {
2556     next_ch = iter_ch->next;
2557     GCCH_destroy (iter_ch->ch);
2558     /* Should only happen on shutdown, but it's ok. */
2559   }
2560
2561   if (GNUNET_SCHEDULER_NO_TASK != t->destroy_task)
2562   {
2563     LOG (GNUNET_ERROR_TYPE_DEBUG, "cancelling %llX\n", t->destroy_task);
2564     GNUNET_SCHEDULER_cancel (t->destroy_task);
2565     t->destroy_task = GNUNET_SCHEDULER_NO_TASK;
2566   }
2567
2568   GNUNET_STATISTICS_update (stats, "# tunnels", -1, GNUNET_NO);
2569   GCP_set_tunnel (t->peer, NULL);
2570
2571   if (GNUNET_SCHEDULER_NO_TASK != t->rekey_task)
2572   {
2573     GNUNET_SCHEDULER_cancel (t->rekey_task);
2574     t->rekey_task = GNUNET_SCHEDULER_NO_TASK;
2575   }
2576   if (NULL != t->kx_ctx)
2577   {
2578     if (GNUNET_SCHEDULER_NO_TASK != t->kx_ctx->finish_task)
2579       GNUNET_SCHEDULER_cancel (t->kx_ctx->finish_task);
2580     GNUNET_free (t->kx_ctx);
2581   }
2582   GNUNET_free (t);
2583 }
2584
2585
2586 /**
2587  * @brief Use the given path for the tunnel.
2588  * Update the next and prev hops (and RCs).
2589  * (Re)start the path refresh in case the tunnel is locally owned.
2590  *
2591  * @param t Tunnel to update.
2592  * @param p Path to use.
2593  *
2594  * @return Connection created.
2595  */
2596 struct CadetConnection *
2597 GCT_use_path (struct CadetTunnel *t, struct CadetPeerPath *p)
2598 {
2599   struct CadetConnection *c;
2600   struct GNUNET_CADET_Hash cid;
2601   unsigned int own_pos;
2602
2603   if (NULL == t || NULL == p)
2604   {
2605     GNUNET_break (0);
2606     return NULL;
2607   }
2608
2609   if (CADET_TUNNEL_SHUTDOWN == t->cstate)
2610   {
2611     GNUNET_break (0);
2612     return NULL;
2613   }
2614
2615   for (own_pos = 0; own_pos < p->length; own_pos++)
2616   {
2617     if (p->peers[own_pos] == myid)
2618       break;
2619   }
2620   if (own_pos >= p->length)
2621   {
2622     GNUNET_break_op (0);
2623     return NULL;
2624   }
2625
2626   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid));
2627   c = GCC_new (&cid, t, p, own_pos);
2628   if (NULL == c)
2629   {
2630     /* Path was flawed */
2631     return NULL;
2632   }
2633   GCT_add_connection (t, c);
2634   return c;
2635 }
2636
2637
2638 /**
2639  * Count created connections of a tunnel. Not necessarily ready connections!
2640  *
2641  * @param t Tunnel on which to count.
2642  *
2643  * @return Number of connections created, either being established or ready.
2644  */
2645 unsigned int
2646 GCT_count_connections (struct CadetTunnel *t)
2647 {
2648   struct CadetTConnection *iter;
2649   unsigned int count;
2650
2651   if (NULL == t)
2652     return 0;
2653
2654   for (count = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2655     if (CADET_CONNECTION_DESTROYED != GCC_get_state (iter->c))
2656       count++;
2657
2658   return count;
2659 }
2660
2661 /**
2662  * Count channels of a tunnel.
2663  *
2664  * @param t Tunnel on which to count.
2665  *
2666  * @return Number of channels.
2667  */
2668 unsigned int
2669 GCT_count_channels (struct CadetTunnel *t)
2670 {
2671   struct CadetTChannel *iter;
2672   unsigned int count;
2673
2674   for (count = 0, iter = t->channel_head;
2675        NULL != iter;
2676        iter = iter->next, count++) /* skip */;
2677
2678   return count;
2679 }
2680
2681
2682 /**
2683  * Get the connectivity state of a tunnel.
2684  *
2685  * @param t Tunnel.
2686  *
2687  * @return Tunnel's connectivity state.
2688  */
2689 enum CadetTunnelCState
2690 GCT_get_cstate (struct CadetTunnel *t)
2691 {
2692   if (NULL == t)
2693   {
2694     GNUNET_assert (0);
2695     return (enum CadetTunnelCState) -1;
2696   }
2697   return t->cstate;
2698 }
2699
2700
2701 /**
2702  * Get the encryption state of a tunnel.
2703  *
2704  * @param t Tunnel.
2705  *
2706  * @return Tunnel's encryption state.
2707  */
2708 enum CadetTunnelEState
2709 GCT_get_estate (struct CadetTunnel *t)
2710 {
2711   if (NULL == t)
2712   {
2713     GNUNET_assert (0);
2714     return (enum CadetTunnelEState) -1;
2715   }
2716   return t->estate;
2717 }
2718
2719 /**
2720  * Get the maximum buffer space for a tunnel towards a local client.
2721  *
2722  * @param t Tunnel.
2723  *
2724  * @return Biggest buffer space offered by any channel in the tunnel.
2725  */
2726 unsigned int
2727 GCT_get_channels_buffer (struct CadetTunnel *t)
2728 {
2729   struct CadetTChannel *iter;
2730   unsigned int buffer;
2731   unsigned int ch_buf;
2732
2733   if (NULL == t->channel_head)
2734   {
2735     /* Probably getting buffer for a channel create/handshake. */
2736     return 64;
2737   }
2738
2739   buffer = 0;
2740   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2741   {
2742     ch_buf = get_channel_buffer (iter);
2743     if (ch_buf > buffer)
2744       buffer = ch_buf;
2745   }
2746   return buffer;
2747 }
2748
2749
2750 /**
2751  * Get the total buffer space for a tunnel for P2P traffic.
2752  *
2753  * @param t Tunnel.
2754  *
2755  * @return Buffer space offered by all connections in the tunnel.
2756  */
2757 unsigned int
2758 GCT_get_connections_buffer (struct CadetTunnel *t)
2759 {
2760   struct CadetTConnection *iter;
2761   unsigned int buffer;
2762
2763   if (GNUNET_NO == is_ready (t))
2764   {
2765     if (count_queued_data (t) > 3)
2766       return 0;
2767     else
2768       return 1;
2769   }
2770
2771   buffer = 0;
2772   for (iter = t->connection_head; NULL != iter; iter = iter->next)
2773   {
2774     if (GCC_get_state (iter->c) != CADET_CONNECTION_READY)
2775     {
2776       continue;
2777     }
2778     buffer += get_connection_buffer (iter);
2779   }
2780
2781   return buffer;
2782 }
2783
2784
2785 /**
2786  * Get the tunnel's destination.
2787  *
2788  * @param t Tunnel.
2789  *
2790  * @return ID of the destination peer.
2791  */
2792 const struct GNUNET_PeerIdentity *
2793 GCT_get_destination (struct CadetTunnel *t)
2794 {
2795   return GCP_get_id (t->peer);
2796 }
2797
2798
2799 /**
2800  * Get the tunnel's next free global channel ID.
2801  *
2802  * @param t Tunnel.
2803  *
2804  * @return GID of a channel free to use.
2805  */
2806 CADET_ChannelNumber
2807 GCT_get_next_chid (struct CadetTunnel *t)
2808 {
2809   CADET_ChannelNumber chid;
2810   CADET_ChannelNumber mask;
2811   int result;
2812
2813   /* Set bit 30 depending on the ID relationship. Bit 31 is always 0 for GID.
2814    * If our ID is bigger or loopback tunnel, start at 0, bit 30 = 0
2815    * If peer's ID is bigger, start at 0x4... bit 30 = 1
2816    */
2817   result = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, GCP_get_id (t->peer));
2818   if (0 > result)
2819     mask = 0x40000000;
2820   else
2821     mask = 0x0;
2822   t->next_chid |= mask;
2823
2824   while (NULL != GCT_get_channel (t, t->next_chid))
2825   {
2826     LOG (GNUNET_ERROR_TYPE_DEBUG, "Channel %u exists...\n", t->next_chid);
2827     t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2828     t->next_chid |= mask;
2829   }
2830   chid = t->next_chid;
2831   t->next_chid = (t->next_chid + 1) & ~GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
2832   t->next_chid |= mask;
2833
2834   return chid;
2835 }
2836
2837
2838 /**
2839  * Send ACK on one or more channels due to buffer in connections.
2840  *
2841  * @param t Channel which has some free buffer space.
2842  */
2843 void
2844 GCT_unchoke_channels (struct CadetTunnel *t)
2845 {
2846   struct CadetTChannel *iter;
2847   unsigned int buffer;
2848   unsigned int channels = GCT_count_channels (t);
2849   unsigned int choked_n;
2850   struct CadetChannel *choked[channels];
2851
2852   LOG (GNUNET_ERROR_TYPE_DEBUG, "GCT_unchoke_channels on %s\n", GCT_2s (t));
2853   LOG (GNUNET_ERROR_TYPE_DEBUG, " head: %p\n", t->channel_head);
2854   if (NULL != t->channel_head)
2855     LOG (GNUNET_ERROR_TYPE_DEBUG, " head ch: %p\n", t->channel_head->ch);
2856
2857   /* Get buffer space */
2858   buffer = GCT_get_connections_buffer (t);
2859   if (0 == buffer)
2860   {
2861     return;
2862   }
2863
2864   /* Count and remember choked channels */
2865   choked_n = 0;
2866   for (iter = t->channel_head; NULL != iter; iter = iter->next)
2867   {
2868     if (GNUNET_NO == get_channel_allowed (iter))
2869     {
2870       choked[choked_n++] = iter->ch;
2871     }
2872   }
2873
2874   /* Unchoke random channels */
2875   while (0 < buffer && 0 < choked_n)
2876   {
2877     unsigned int r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2878                                                choked_n);
2879     GCCH_allow_client (choked[r], GCCH_is_origin (choked[r], GNUNET_YES));
2880     choked_n--;
2881     buffer--;
2882     choked[r] = choked[choked_n];
2883   }
2884 }
2885
2886
2887 /**
2888  * Send ACK on one or more connections due to buffer space to the client.
2889  *
2890  * Iterates all connections of the tunnel and sends ACKs appropriately.
2891  *
2892  * @param t Tunnel.
2893  */
2894 void
2895 GCT_send_connection_acks (struct CadetTunnel *t)
2896 {
2897   struct CadetTConnection *iter;
2898   uint32_t allowed;
2899   uint32_t to_allow;
2900   uint32_t allow_per_connection;
2901   unsigned int cs;
2902   unsigned int buffer;
2903
2904   LOG (GNUNET_ERROR_TYPE_DEBUG, "Tunnel send connection ACKs on %s\n",
2905        GCT_2s (t));
2906
2907   if (NULL == t)
2908   {
2909     GNUNET_break (0);
2910     return;
2911   }
2912
2913   buffer = GCT_get_channels_buffer (t);
2914   LOG (GNUNET_ERROR_TYPE_DEBUG, "  buffer %u\n", buffer);
2915
2916   /* Count connections, how many messages are already allowed */
2917   cs = GCT_count_connections (t);
2918   for (allowed = 0, iter = t->connection_head; NULL != iter; iter = iter->next)
2919   {
2920     allowed += get_connection_allowed (iter);
2921   }
2922   LOG (GNUNET_ERROR_TYPE_DEBUG, "  allowed %u\n", allowed);
2923
2924   /* Make sure there is no overflow */
2925   if (allowed > buffer)
2926   {
2927     return;
2928   }
2929
2930   /* Authorize connections to send more data */
2931   to_allow = buffer; /* - allowed; */
2932
2933   for (iter = t->connection_head;
2934        NULL != iter && to_allow > 0;
2935        iter = iter->next)
2936   {
2937     allow_per_connection = to_allow/cs;
2938     to_allow -= allow_per_connection;
2939     cs--;
2940     if (get_connection_allowed (iter) > 64 / 3)
2941     {
2942       continue;
2943     }
2944     GCC_allow (iter->c, allow_per_connection,
2945                GCC_is_origin (iter->c, GNUNET_NO));
2946   }
2947
2948   GNUNET_break (to_allow == 0);
2949 }
2950
2951
2952 /**
2953  * Cancel a previously sent message while it's in the queue.
2954  *
2955  * ONLY can be called before the continuation given to the send function
2956  * is called. Once the continuation is called, the message is no longer in the
2957  * queue.
2958  *
2959  * @param q Handle to the queue.
2960  */
2961 void
2962 GCT_cancel (struct CadetTunnelQueue *q)
2963 {
2964   if (NULL != q->cq)
2965   {
2966     GCC_cancel (q->cq);
2967     /* tun_message_sent() will be called and free q */
2968   }
2969   else if (NULL != q->tqd)
2970   {
2971     unqueue_data (q->tqd);
2972     q->tqd = NULL;
2973     if (NULL != q->cont)
2974       q->cont (q->cont_cls, NULL, q, 0, 0);
2975     GNUNET_free (q);
2976   }
2977   else
2978   {
2979     GNUNET_break (0);
2980   }
2981 }
2982
2983
2984 /**
2985  * Sends an already built message on a tunnel, encrypting it and
2986  * choosing the best connection if not provided.
2987  *
2988  * @param message Message to send. Function modifies it.
2989  * @param t Tunnel on which this message is transmitted.
2990  * @param c Connection to use (autoselect if NULL).
2991  * @param force Force the tunnel to take the message (buffer overfill).
2992  * @param cont Continuation to call once message is really sent.
2993  * @param cont_cls Closure for @c cont.
2994  *
2995  * @return Handle to cancel message. NULL if @c cont is NULL.
2996  */
2997 struct CadetTunnelQueue *
2998 GCT_send_prebuilt_message (const struct GNUNET_MessageHeader *message,
2999                            struct CadetTunnel *t, struct CadetConnection *c,
3000                            int force, GCT_sent cont, void *cont_cls)
3001 {
3002   return send_prebuilt_message (message, t, c, force, cont, cont_cls, NULL);
3003 }
3004
3005
3006 /**
3007  * Is the tunnel directed towards the local peer?
3008  *
3009  * @param t Tunnel.
3010  *
3011  * @return #GNUNET_YES if it is loopback.
3012  */
3013 int
3014 GCT_is_loopback (const struct CadetTunnel *t)
3015 {
3016   return (myid == GCP_get_short_id (t->peer));
3017 }
3018
3019
3020 /**
3021  * Is the tunnel this path already?
3022  *
3023  * @param t Tunnel.
3024  * @param p Path.
3025  *
3026  * @return #GNUNET_YES a connection uses this path.
3027  */
3028 int
3029 GCT_is_path_used (const struct CadetTunnel *t, const struct CadetPeerPath *p)
3030 {
3031   struct CadetTConnection *iter;
3032
3033   for (iter = t->connection_head; NULL != iter; iter = iter->next)
3034     if (GCC_get_path (iter->c) == p)
3035       return GNUNET_YES;
3036
3037   return GNUNET_NO;
3038 }
3039
3040
3041 /**
3042  * Get a cost of a path for a tunnel considering existing connections.
3043  *
3044  * @param t Tunnel.
3045  * @param path Candidate path.
3046  *
3047  * @return Cost of the path (path length + number of overlapping nodes)
3048  */
3049 unsigned int
3050 GCT_get_path_cost (const struct CadetTunnel *t,
3051                    const struct CadetPeerPath *path)
3052 {
3053   struct CadetTConnection *iter;
3054   const struct CadetPeerPath *aux;
3055   unsigned int overlap;
3056   unsigned int i;
3057   unsigned int j;
3058
3059   if (NULL == path)
3060     return 0;
3061
3062   overlap = 0;
3063   GNUNET_assert (NULL != t);
3064
3065   for (i = 0; i < path->length; i++)
3066   {
3067     for (iter = t->connection_head; NULL != iter; iter = iter->next)
3068     {
3069       aux = GCC_get_path (iter->c);
3070       if (NULL == aux)
3071         continue;
3072
3073       for (j = 0; j < aux->length; j++)
3074       {
3075         if (path->peers[i] == aux->peers[j])
3076         {
3077           overlap++;
3078           break;
3079         }
3080       }
3081     }
3082   }
3083   return path->length + overlap;
3084 }
3085
3086
3087 /**
3088  * Get the static string for the peer this tunnel is directed.
3089  *
3090  * @param t Tunnel.
3091  *
3092  * @return Static string the destination peer's ID.
3093  */
3094 const char *
3095 GCT_2s (const struct CadetTunnel *t)
3096 {
3097   if (NULL == t)
3098     return "(NULL)";
3099
3100   return GCP_2s (t->peer);
3101 }
3102
3103
3104 /******************************************************************************/
3105 /*****************************    INFO/DEBUG    *******************************/
3106 /******************************************************************************/
3107
3108 /**
3109  * Log all possible info about the tunnel state.
3110  *
3111  * @param t Tunnel to debug.
3112  * @param level Debug level to use.
3113  */
3114 void
3115 GCT_debug (const struct CadetTunnel *t, enum GNUNET_ErrorType level)
3116 {
3117   struct CadetTChannel *iterch;
3118   struct CadetTConnection *iterc;
3119
3120   LOG (level, "TTT DEBUG TUNNEL TOWARDS %s\n", GCT_2s (t));
3121   LOG (level, "TTT  cstate %s, estate %s\n",
3122        cstate2s (t->cstate), estate2s (t->estate));
3123   LOG (level, "TTT  kx_ctx %p, rekey_task %u\n", t->kx_ctx, t->rekey_task);
3124   LOG (level, "TTT  tq_head %p, tq_tail %p\n", t->tq_head, t->tq_tail);
3125   LOG (level, "TTT  destroy %u\n", t->destroy_task);
3126
3127   LOG (level, "TTT  channels:\n");
3128   for (iterch = t->channel_head; NULL != iterch; iterch = iterch->next)
3129   {
3130     LOG (level, "TTT  - %s\n", GCCH_2s (iterch->ch));
3131   }
3132
3133   LOG (level, "TTT  connections:\n");
3134   for (iterc = t->connection_head; NULL != iterc; iterc = iterc->next)
3135   {
3136     LOG (level, "TTT  - %s [%u] buf: %u/%u (qn %u/%u)\n",
3137          GCC_2s (iterc->c), GCC_get_state (iterc->c),
3138          GCC_get_buffer (iterc->c, GNUNET_YES),
3139          GCC_get_buffer (iterc->c, GNUNET_NO),
3140          GCC_get_qn (iterc->c, GNUNET_YES),
3141          GCC_get_qn (iterc->c, GNUNET_NO));
3142   }
3143
3144   LOG (level, "TTT DEBUG TUNNEL END\n");
3145 }
3146
3147
3148 /**
3149  * Iterate all tunnels.
3150  *
3151  * @param iter Iterator.
3152  * @param cls Closure for @c iter.
3153  */
3154 void
3155 GCT_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
3156 {
3157   GNUNET_CONTAINER_multipeermap_iterate (tunnels, iter, cls);
3158 }
3159
3160
3161 /**
3162  * Count all tunnels.
3163  *
3164  * @return Number of tunnels to remote peers kept by this peer.
3165  */
3166 unsigned int
3167 GCT_count_all (void)
3168 {
3169   return GNUNET_CONTAINER_multipeermap_size (tunnels);
3170 }
3171
3172
3173 /**
3174  * Iterate all connections of a tunnel.
3175  *
3176  * @param t Tunnel whose connections to iterate.
3177  * @param iter Iterator.
3178  * @param cls Closure for @c iter.
3179  */
3180 void
3181 GCT_iterate_connections (struct CadetTunnel *t, GCT_conn_iter iter, void *cls)
3182 {
3183   struct CadetTConnection *ct;
3184
3185   for (ct = t->connection_head; NULL != ct; ct = ct->next)
3186     iter (cls, ct->c);
3187 }
3188
3189
3190 /**
3191  * Iterate all channels of a tunnel.
3192  *
3193  * @param t Tunnel whose channels to iterate.
3194  * @param iter Iterator.
3195  * @param cls Closure for @c iter.
3196  */
3197 void
3198 GCT_iterate_channels (struct CadetTunnel *t, GCT_chan_iter iter, void *cls)
3199 {
3200   struct CadetTChannel *cht;
3201
3202   for (cht = t->channel_head; NULL != cht; cht = cht->next)
3203     iter (cls, cht->ch);
3204 }