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