fix startup interaction between channel and tunnel to not send CHANNEL_OPEN until...
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2017 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file cadet/gnunet-service-cadet-new_tunnels.c
22  * @brief Information we track per tunnel.
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  *
26  * FIXME:
27  * - check KX estate machine -- make sure it is never stuck!
28  * - clean up KX logic, including adding sender authentication
29  * - implement connection management (evaluate, kill old ones,
30  *   search for new ones)
31  * - when managing connections, distinguish those that
32  *   have (recently) had traffic from those that were
33  *   never ready (or not recently)
34  */
35 #include "platform.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet-service-cadet-new.h"
40 #include "cadet_protocol.h"
41 #include "gnunet-service-cadet-new_channel.h"
42 #include "gnunet-service-cadet-new_connection.h"
43 #include "gnunet-service-cadet-new_tunnels.h"
44 #include "gnunet-service-cadet-new_peer.h"
45 #include "gnunet-service-cadet-new_paths.h"
46
47
48 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
49
50
51 /**
52  * How long do we wait until tearing down an idle tunnel?
53  */
54 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
55
56 /**
57  * Yuck, replace by 'offsetof' expression?
58  * FIXME.
59  */
60 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
61                         + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
62
63
64 /**
65  * Maximum number of skipped keys we keep in memory per tunnel.
66  */
67 #define MAX_SKIPPED_KEYS 64
68
69 /**
70  * Maximum number of keys (and thus ratchet steps) we are willing to
71  * skip before we decide this is either a bogus packet or a DoS-attempt.
72  */
73 #define MAX_KEY_GAP 256
74
75
76 /**
77  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
78  */
79 struct CadetTunnelSkippedKey
80 {
81   /**
82    * DLL next.
83    */
84   struct CadetTunnelSkippedKey *next;
85
86   /**
87    * DLL prev.
88    */
89   struct CadetTunnelSkippedKey *prev;
90
91   /**
92    * When was this key stored (for timeout).
93    */
94   struct GNUNET_TIME_Absolute timestamp;
95
96   /**
97    * Header key.
98    */
99   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
100
101   /**
102    * Message key.
103    */
104   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
105
106   /**
107    * Key number for a given HK.
108    */
109   unsigned int Kn;
110 };
111
112
113 /**
114  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
115  */
116 struct CadetTunnelAxolotl
117 {
118   /**
119    * A (double linked) list of stored message keys and associated header keys
120    * for "skipped" messages, i.e. messages that have not been
121    * received despite the reception of more recent messages, (head).
122    */
123   struct CadetTunnelSkippedKey *skipped_head;
124
125   /**
126    * Skipped messages' keys DLL, tail.
127    */
128   struct CadetTunnelSkippedKey *skipped_tail;
129
130   /**
131    * 32-byte root key which gets updated by DH ratchet.
132    */
133   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
134
135   /**
136    * 32-byte header key (send).
137    */
138   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
139
140   /**
141    * 32-byte header key (recv)
142    */
143   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
144
145   /**
146    * 32-byte next header key (send).
147    */
148   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
149
150   /**
151    * 32-byte next header key (recv).
152    */
153   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
154
155   /**
156    * 32-byte chain keys (used for forward-secrecy updating, send).
157    */
158   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
159
160   /**
161    * 32-byte chain keys (used for forward-secrecy updating, recv).
162    */
163   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
164
165   /**
166    * ECDH for key exchange (A0 / B0).
167    */
168   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
169
170   /**
171    * ECDH Ratchet key (send).
172    */
173   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
174
175   /**
176    * ECDH Ratchet key (recv).
177    */
178   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
179
180   /**
181    * When does this ratchet expire and a new one is triggered.
182    */
183   struct GNUNET_TIME_Absolute ratchet_expiration;
184
185   /**
186    * Number of elements in @a skipped_head <-> @a skipped_tail.
187    */
188   unsigned int skipped;
189
190   /**
191    * Message number (reset to 0 with each new ratchet, next message to send).
192    */
193   uint32_t Ns;
194
195   /**
196    * Message number (reset to 0 with each new ratchet, next message to recv).
197    */
198   uint32_t Nr;
199
200   /**
201    * Previous message numbers (# of msgs sent under prev ratchet)
202    */
203   uint32_t PNs;
204
205   /**
206    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
207    */
208   int ratchet_flag;
209
210   /**
211    * Number of messages recieved since our last ratchet advance.
212    * - If this counter = 0, we cannot send a new ratchet key in next msg.
213    * - If this counter > 0, we can (but don't yet have to) send a new key.
214    */
215   unsigned int ratchet_allowed;
216
217   /**
218    * Number of messages recieved since our last ratchet advance.
219    * - If this counter = 0, we cannot send a new ratchet key in next msg.
220    * - If this counter > 0, we can (but don't yet have to) send a new key.
221    */
222   unsigned int ratchet_counter;
223
224 };
225
226
227 /**
228  * Struct used to save messages in a non-ready tunnel to send once connected.
229  */
230 struct CadetTunnelQueueEntry
231 {
232   /**
233    * We are entries in a DLL
234    */
235   struct CadetTunnelQueueEntry *next;
236
237   /**
238    * We are entries in a DLL
239    */
240   struct CadetTunnelQueueEntry *prev;
241
242   /**
243    * Tunnel these messages belong in.
244    */
245   struct CadetTunnel *t;
246
247   /**
248    * Continuation to call once sent (on the channel layer).
249    */
250   GNUNET_SCHEDULER_TaskCallback cont;
251
252   /**
253    * Closure for @c cont.
254    */
255   void *cont_cls;
256
257   /**
258    * Envelope of message to send follows.
259    */
260   struct GNUNET_MQ_Envelope *env;
261
262   /**
263    * Where to put the connection identifier into the payload
264    * of the message in @e env once we have it?
265    */
266   struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
267 };
268
269
270 /**
271  * Struct containing all information regarding a tunnel to a peer.
272  */
273 struct CadetTunnel
274 {
275   /**
276    * Destination of the tunnel.
277    */
278   struct CadetPeer *destination;
279
280   /**
281    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
282    * ephemeral key changes.
283    */
284   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
285
286   /**
287    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
288    */
289   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
290
291   /**
292    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
293    */
294   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
295
296   /**
297    * Axolotl info.
298    */
299   struct CadetTunnelAxolotl ax;
300
301   /**
302    * Task scheduled if there are no more channels using the tunnel.
303    */
304   struct GNUNET_SCHEDULER_Task *destroy_task;
305
306   /**
307    * Task to trim connections if too many are present.
308    */
309   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
310
311   /**
312    * Task to trigger KX.
313    */
314   struct GNUNET_SCHEDULER_Task *kx_task;
315
316   /**
317    * Tokenizer for decrypted messages.
318    */
319   struct GNUNET_MessageStreamTokenizer *mst;
320
321   /**
322    * Dispatcher for decrypted messages only (do NOT use for sending!).
323    */
324   struct GNUNET_MQ_Handle *mq;
325
326   /**
327    * DLL of connections that are actively used to reach the destination peer.
328    */
329   struct CadetTConnection *connection_head;
330
331   /**
332    * DLL of connections that are actively used to reach the destination peer.
333    */
334   struct CadetTConnection *connection_tail;
335
336   /**
337    * Channels inside this tunnel. Maps
338    * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
339    */
340   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
341
342   /**
343    * Channel ID for the next created channel in this tunnel.
344    */
345   struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
346
347   /**
348    * Queued messages, to transmit once tunnel gets connected.
349    */
350   struct CadetTunnelQueueEntry *tq_head;
351
352   /**
353    * Queued messages, to transmit once tunnel gets connected.
354    */
355   struct CadetTunnelQueueEntry *tq_tail;
356
357
358   /**
359    * Ephemeral message in the queue (to avoid queueing more than one).
360    */
361   struct CadetConnectionQueue *ephm_hKILL;
362
363   /**
364    * Pong message in the queue.
365    */
366   struct CadetConnectionQueue *pong_hKILL;
367
368   /**
369    * How long do we wait until we retry the KX?
370    */
371   struct GNUNET_TIME_Relative kx_retry_delay;
372
373   /**
374    * When do we try the next KX?
375    */
376   struct GNUNET_TIME_Absolute next_kx_attempt;
377
378   /**
379    * Number of connections in the @e connection_head DLL.
380    */
381   unsigned int num_connections;
382
383   /**
384    * Number of entries in the @e tq_head DLL.
385    */
386   unsigned int tq_len;
387
388   /**
389    * State of the tunnel encryption.
390    */
391   enum CadetTunnelEState estate;
392
393 };
394
395
396 /**
397  * Get the static string for the peer this tunnel is directed.
398  *
399  * @param t Tunnel.
400  *
401  * @return Static string the destination peer's ID.
402  */
403 const char *
404 GCT_2s (const struct CadetTunnel *t)
405 {
406   static char buf[64];
407
408   if (NULL == t)
409     return "T(NULL)";
410
411   GNUNET_snprintf (buf,
412                    sizeof (buf),
413                    "T(%s)",
414                    GCP_2s (t->destination));
415   return buf;
416 }
417
418
419 /**
420  * Get string description for tunnel encryption state.
421  *
422  * @param es Tunnel state.
423  *
424  * @return String representation.
425  */
426 static const char *
427 estate2s (enum CadetTunnelEState es)
428 {
429   static char buf[32];
430
431   switch (es)
432   {
433     case CADET_TUNNEL_KEY_UNINITIALIZED:
434       return "CADET_TUNNEL_KEY_UNINITIALIZED";
435     case CADET_TUNNEL_KEY_SENT:
436       return "CADET_TUNNEL_KEY_SENT";
437     case CADET_TUNNEL_KEY_PING:
438       return "CADET_TUNNEL_KEY_PING";
439     case CADET_TUNNEL_KEY_OK:
440       return "CADET_TUNNEL_KEY_OK";
441     case CADET_TUNNEL_KEY_REKEY:
442       return "CADET_TUNNEL_KEY_REKEY";
443     default:
444       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
445       return buf;
446   }
447 }
448
449
450 /**
451  * Return the peer to which this tunnel goes.
452  *
453  * @param t a tunnel
454  * @return the destination of the tunnel
455  */
456 struct CadetPeer *
457 GCT_get_destination (struct CadetTunnel *t)
458 {
459   return t->destination;
460 }
461
462
463 /**
464  * Count channels of a tunnel.
465  *
466  * @param t Tunnel on which to count.
467  *
468  * @return Number of channels.
469  */
470 unsigned int
471 GCT_count_channels (struct CadetTunnel *t)
472 {
473   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
474 }
475
476
477 /**
478  * Lookup a channel by its @a ctn.
479  *
480  * @param t tunnel to look in
481  * @param ctn number of channel to find
482  * @return NULL if channel does not exist
483  */
484 struct CadetChannel *
485 lookup_channel (struct CadetTunnel *t,
486                 struct GNUNET_CADET_ChannelTunnelNumber ctn)
487 {
488   return GNUNET_CONTAINER_multihashmap32_get (t->channels,
489                                               ntohl (ctn.cn));
490 }
491
492
493 /**
494  * Count all created connections of a tunnel. Not necessarily ready connections!
495  *
496  * @param t Tunnel on which to count.
497  *
498  * @return Number of connections created, either being established or ready.
499  */
500 unsigned int
501 GCT_count_any_connections (struct CadetTunnel *t)
502 {
503   return t->num_connections;
504 }
505
506
507 /**
508  * Find first connection that is ready in the list of
509  * our connections.  Picks ready connections round-robin.
510  *
511  * @param t tunnel to search
512  * @return NULL if we have no connection that is ready
513  */
514 static struct CadetTConnection *
515 get_ready_connection (struct CadetTunnel *t)
516 {
517   for (struct CadetTConnection *pos = t->connection_head;
518        NULL != pos;
519        pos = pos->next)
520     if (GNUNET_YES == pos->is_ready)
521     {
522       if (pos != t->connection_tail)
523       {
524         /* move 'pos' to the end, so we try other ready connections
525            first next time (round-robin, modulo availability) */
526         GNUNET_CONTAINER_DLL_remove (t->connection_head,
527                                      t->connection_tail,
528                                      pos);
529         GNUNET_CONTAINER_DLL_insert_tail (t->connection_head,
530                                           t->connection_tail,
531                                           pos);
532       }
533       return pos;
534     }
535   return NULL;
536 }
537
538
539 /**
540  * Get the encryption state of a tunnel.
541  *
542  * @param t Tunnel.
543  *
544  * @return Tunnel's encryption state.
545  */
546 enum CadetTunnelEState
547 GCT_get_estate (struct CadetTunnel *t)
548 {
549   return t->estate;
550 }
551
552
553 /**
554  * Create a new Axolotl ephemeral (ratchet) key.
555  *
556  * @param t Tunnel.
557  */
558 static void
559 new_ephemeral (struct CadetTunnel *t)
560 {
561   GNUNET_free_non_null (t->ax.DHRs);
562   t->ax.DHRs = GNUNET_CRYPTO_ecdhe_key_create ();
563 }
564
565
566
567 /**
568  * Called when either we have a new connection, or a new message in the
569  * queue, or some existing connection has transmission capacity.  Looks
570  * at our message queue and if there is a message, picks a connection
571  * to send it on.
572  *
573  * @param t tunnel to process messages on
574  */
575 static void
576 trigger_transmissions (struct CadetTunnel *t);
577
578
579 /* ************************************** start core crypto ***************************** */
580
581
582 /**
583  * Calculate HMAC.
584  *
585  * @param plaintext Content to HMAC.
586  * @param size Size of @c plaintext.
587  * @param iv Initialization vector for the message.
588  * @param key Key to use.
589  * @param hmac[out] Destination to store the HMAC.
590  */
591 static void
592 t_hmac (const void *plaintext,
593         size_t size,
594         uint32_t iv,
595         const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
596         struct GNUNET_ShortHashCode *hmac)
597 {
598   static const char ctx[] = "cadet authentication key";
599   struct GNUNET_CRYPTO_AuthKey auth_key;
600   struct GNUNET_HashCode hash;
601
602   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
603                                  key,
604                                  &iv, sizeof (iv),
605                                  key, sizeof (*key),
606                                  ctx, sizeof (ctx),
607                                  NULL);
608   /* Two step: CADET_Hash is only 256 bits, HashCode is 512. */
609   GNUNET_CRYPTO_hmac (&auth_key,
610                       plaintext,
611                       size,
612                       &hash);
613   GNUNET_memcpy (hmac,
614                  &hash,
615                  sizeof (*hmac));
616 }
617
618
619 /**
620  * Perform a HMAC.
621  *
622  * @param key Key to use.
623  * @param hash[out] Resulting HMAC.
624  * @param source Source key material (data to HMAC).
625  * @param len Length of @a source.
626  */
627 static void
628 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
629                 struct GNUNET_HashCode *hash,
630                 const void *source,
631                 unsigned int len)
632 {
633   static const char ctx[] = "axolotl HMAC-HASH";
634   struct GNUNET_CRYPTO_AuthKey auth_key;
635
636   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
637                                  key,
638                                  ctx, sizeof (ctx),
639                                  NULL);
640   GNUNET_CRYPTO_hmac (&auth_key,
641                       source,
642                       len,
643                       hash);
644 }
645
646
647 /**
648  * Derive a symmetric encryption key from an HMAC-HASH.
649  *
650  * @param key Key to use for the HMAC.
651  * @param[out] out Key to generate.
652  * @param source Source key material (data to HMAC).
653  * @param len Length of @a source.
654  */
655 static void
656 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
657                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
658                    const void *source,
659                    unsigned int len)
660 {
661   static const char ctx[] = "axolotl derive key";
662   struct GNUNET_HashCode h;
663
664   t_ax_hmac_hash (key,
665                   &h,
666                   source,
667                   len);
668   GNUNET_CRYPTO_kdf (out, sizeof (*out),
669                      ctx, sizeof (ctx),
670                      &h, sizeof (h),
671                      NULL);
672 }
673
674
675 /**
676  * Encrypt data with the axolotl tunnel key.
677  *
678  * @param t Tunnel whose key to use.
679  * @param dst Destination with @a size bytes for the encrypted data.
680  * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
681  * @param size Size of the buffers at @a src and @a dst
682  */
683 static void
684 t_ax_encrypt (struct CadetTunnel *t,
685               void *dst,
686               const void *src,
687               size_t size)
688 {
689   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
690   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
691   struct CadetTunnelAxolotl *ax;
692   size_t out_size;
693
694   ax = &t->ax;
695   ax->ratchet_counter++;
696   if ( (GNUNET_YES == ax->ratchet_allowed) &&
697        ( (ratchet_messages <= ax->ratchet_counter) ||
698          (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
699   {
700     ax->ratchet_flag = GNUNET_YES;
701   }
702   if (GNUNET_YES == ax->ratchet_flag)
703   {
704     /* Advance ratchet */
705     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
706     struct GNUNET_HashCode dh;
707     struct GNUNET_HashCode hmac;
708     static const char ctx[] = "axolotl ratchet";
709
710     new_ephemeral (t);
711     ax->HKs = ax->NHKs;
712
713     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
714     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
715                             &ax->DHRr,
716                             &dh);
717     t_ax_hmac_hash (&ax->RK,
718                     &hmac,
719                     &dh,
720                     sizeof (dh));
721     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
722                        ctx, sizeof (ctx),
723                        &hmac, sizeof (hmac),
724                        NULL);
725     ax->RK = keys[0];
726     ax->NHKs = keys[1];
727     ax->CKs = keys[2];
728
729     ax->PNs = ax->Ns;
730     ax->Ns = 0;
731     ax->ratchet_flag = GNUNET_NO;
732     ax->ratchet_allowed = GNUNET_NO;
733     ax->ratchet_counter = 0;
734     ax->ratchet_expiration
735       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
736                                   ratchet_time);
737   }
738
739   t_hmac_derive_key (&ax->CKs,
740                      &MK,
741                      "0",
742                      1);
743   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
744                                      &MK,
745                                      NULL, 0,
746                                      NULL);
747
748   out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
749                                               size,
750                                               &MK,
751                                               &iv,
752                                               dst);
753   GNUNET_assert (size == out_size);
754   t_hmac_derive_key (&ax->CKs,
755                      &ax->CKs,
756                      "1",
757                      1);
758 }
759
760
761 /**
762  * Decrypt data with the axolotl tunnel key.
763  *
764  * @param t Tunnel whose key to use.
765  * @param dst Destination for the decrypted data, must contain @a size bytes.
766  * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
767  * @param size Size of the @a src and @a dst buffers
768  */
769 static void
770 t_ax_decrypt (struct CadetTunnel *t,
771               void *dst,
772               const void *src,
773               size_t size)
774 {
775   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
776   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
777   struct CadetTunnelAxolotl *ax;
778   size_t out_size;
779
780   ax = &t->ax;
781   t_hmac_derive_key (&ax->CKr,
782                      &MK,
783                      "0",
784                      1);
785   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
786                                      &MK,
787                                      NULL, 0,
788                                      NULL);
789   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
790   out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
791                                               size,
792                                               &MK,
793                                               &iv,
794                                               dst);
795   GNUNET_assert (out_size == size);
796   t_hmac_derive_key (&ax->CKr,
797                      &ax->CKr,
798                      "1",
799                      1);
800 }
801
802
803 /**
804  * Encrypt header with the axolotl header key.
805  *
806  * @param t Tunnel whose key to use.
807  * @param msg Message whose header to encrypt.
808  */
809 static void
810 t_h_encrypt (struct CadetTunnel *t,
811              struct GNUNET_CADET_TunnelEncryptedMessage *msg)
812 {
813   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
814   struct CadetTunnelAxolotl *ax;
815   size_t out_size;
816
817   ax = &t->ax;
818   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
819                                      &ax->HKs,
820                                      NULL, 0,
821                                      NULL);
822   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->Ns,
823                                               AX_HEADER_SIZE,
824                                               &ax->HKs,
825                                               &iv,
826                                               &msg->Ns);
827   GNUNET_assert (AX_HEADER_SIZE == out_size);
828 }
829
830
831 /**
832  * Decrypt header with the current axolotl header key.
833  *
834  * @param t Tunnel whose current ax HK to use.
835  * @param src Message whose header to decrypt.
836  * @param dst Where to decrypt header to.
837  */
838 static void
839 t_h_decrypt (struct CadetTunnel *t,
840              const struct GNUNET_CADET_TunnelEncryptedMessage *src,
841              struct GNUNET_CADET_TunnelEncryptedMessage *dst)
842 {
843   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
844   struct CadetTunnelAxolotl *ax;
845   size_t out_size;
846
847   ax = &t->ax;
848   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
849                                      &ax->HKr,
850                                      NULL, 0,
851                                      NULL);
852   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
853                                               AX_HEADER_SIZE,
854                                               &ax->HKr,
855                                               &iv,
856                                               &dst->Ns);
857   GNUNET_assert (AX_HEADER_SIZE == out_size);
858 }
859
860
861 /**
862  * Delete a key from the list of skipped keys.
863  *
864  * @param t Tunnel to delete from.
865  * @param key Key to delete.
866  */
867 static void
868 delete_skipped_key (struct CadetTunnel *t,
869                     struct CadetTunnelSkippedKey *key)
870 {
871   GNUNET_CONTAINER_DLL_remove (t->ax.skipped_head,
872                                t->ax.skipped_tail,
873                                key);
874   GNUNET_free (key);
875   t->ax.skipped--;
876 }
877
878
879 /**
880  * Decrypt and verify data with the appropriate tunnel key and verify that the
881  * data has not been altered since it was sent by the remote peer.
882  *
883  * @param t Tunnel whose key to use.
884  * @param dst Destination for the plaintext.
885  * @param src Source of the message. Can overlap with @c dst.
886  * @param size Size of the message.
887  * @return Size of the decrypted data, -1 if an error was encountered.
888  */
889 static ssize_t
890 try_old_ax_keys (struct CadetTunnel *t,
891                  void *dst,
892                  const struct GNUNET_CADET_TunnelEncryptedMessage *src,
893                  size_t size)
894 {
895   struct CadetTunnelSkippedKey *key;
896   struct GNUNET_ShortHashCode *hmac;
897   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
898   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
899   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
900   size_t esize;
901   size_t res;
902   size_t len;
903   unsigned int N;
904
905   LOG (GNUNET_ERROR_TYPE_DEBUG,
906        "Trying skipped keys\n");
907   hmac = &plaintext_header.hmac;
908   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
909
910   /* Find a correct Header Key */
911   valid_HK = NULL;
912   for (key = t->ax.skipped_head; NULL != key; key = key->next)
913   {
914     t_hmac (&src->Ns,
915             AX_HEADER_SIZE + esize,
916             0,
917             &key->HK,
918             hmac);
919     if (0 == memcmp (hmac,
920                      &src->hmac,
921                      sizeof (*hmac)))
922     {
923       valid_HK = &key->HK;
924       break;
925     }
926   }
927   if (NULL == key)
928     return -1;
929
930   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
931   GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
932   len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
933   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
934
935   /* Decrypt header */
936   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
937                                      &key->HK,
938                                      NULL, 0,
939                                      NULL);
940   res = GNUNET_CRYPTO_symmetric_decrypt (&src->Ns,
941                                          AX_HEADER_SIZE,
942                                          &key->HK,
943                                          &iv,
944                                          &plaintext_header.Ns);
945   GNUNET_assert (AX_HEADER_SIZE == res);
946
947   /* Find the correct message key */
948   N = ntohl (plaintext_header.Ns);
949   while ( (NULL != key) &&
950           (N != key->Kn) )
951     key = key->next;
952   if ( (NULL == key) ||
953        (0 != memcmp (&key->HK,
954                      valid_HK,
955                      sizeof (*valid_HK))) )
956     return -1;
957
958   /* Decrypt payload */
959   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
960                                      &key->MK,
961                                      NULL,
962                                      0,
963                                      NULL);
964   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
965                                          len,
966                                          &key->MK,
967                                          &iv,
968                                          dst);
969   delete_skipped_key (t,
970                       key);
971   return res;
972 }
973
974
975 /**
976  * Delete a key from the list of skipped keys.
977  *
978  * @param t Tunnel to delete from.
979  * @param HKr Header Key to use.
980  */
981 static void
982 store_skipped_key (struct CadetTunnel *t,
983                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
984 {
985   struct CadetTunnelSkippedKey *key;
986
987   key = GNUNET_new (struct CadetTunnelSkippedKey);
988   key->timestamp = GNUNET_TIME_absolute_get ();
989   key->Kn = t->ax.Nr;
990   key->HK = t->ax.HKr;
991   t_hmac_derive_key (&t->ax.CKr,
992                      &key->MK,
993                      "0",
994                      1);
995   t_hmac_derive_key (&t->ax.CKr,
996                      &t->ax.CKr,
997                      "1",
998                      1);
999   GNUNET_CONTAINER_DLL_insert (t->ax.skipped_head,
1000                                t->ax.skipped_tail,
1001                                key);
1002   t->ax.skipped++;
1003   t->ax.Nr++;
1004 }
1005
1006
1007 /**
1008  * Stage skipped AX keys and calculate the message key.
1009  * Stores each HK and MK for skipped messages.
1010  *
1011  * @param t Tunnel where to stage the keys.
1012  * @param HKr Header key.
1013  * @param Np Received meesage number.
1014  * @return #GNUNET_OK if keys were stored.
1015  *         #GNUNET_SYSERR if an error ocurred (Np not expected).
1016  */
1017 static int
1018 store_ax_keys (struct CadetTunnel *t,
1019                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1020                uint32_t Np)
1021 {
1022   int gap;
1023
1024   gap = Np - t->ax.Nr;
1025   LOG (GNUNET_ERROR_TYPE_DEBUG,
1026        "Storing skipped keys [%u, %u)\n",
1027        t->ax.Nr,
1028        Np);
1029   if (MAX_KEY_GAP < gap)
1030   {
1031     /* Avoid DoS (forcing peer to do 2^33 chain HMAC operations) */
1032     /* TODO: start new key exchange on return */
1033     GNUNET_break_op (0);
1034     LOG (GNUNET_ERROR_TYPE_WARNING,
1035          "Got message %u, expected %u+\n",
1036          Np,
1037          t->ax.Nr);
1038     return GNUNET_SYSERR;
1039   }
1040   if (0 > gap)
1041   {
1042     /* Delayed message: don't store keys, flag to try old keys. */
1043     return GNUNET_SYSERR;
1044   }
1045
1046   while (t->ax.Nr < Np)
1047     store_skipped_key (t,
1048                        HKr);
1049
1050   while (t->ax.skipped > MAX_SKIPPED_KEYS)
1051     delete_skipped_key (t,
1052                         t->ax.skipped_tail);
1053   return GNUNET_OK;
1054 }
1055
1056
1057 /**
1058  * Decrypt and verify data with the appropriate tunnel key and verify that the
1059  * data has not been altered since it was sent by the remote peer.
1060  *
1061  * @param t Tunnel whose key to use.
1062  * @param dst Destination for the plaintext.
1063  * @param src Source of the message. Can overlap with @c dst.
1064  * @param size Size of the message.
1065  * @return Size of the decrypted data, -1 if an error was encountered.
1066  */
1067 static ssize_t
1068 t_ax_decrypt_and_validate (struct CadetTunnel *t,
1069                            void *dst,
1070                            const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1071                            size_t size)
1072 {
1073   struct CadetTunnelAxolotl *ax;
1074   struct GNUNET_ShortHashCode msg_hmac;
1075   struct GNUNET_HashCode hmac;
1076   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1077   uint32_t Np;
1078   uint32_t PNp;
1079   size_t esize; /* Size of encryped payload */
1080
1081   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1082   ax = &t->ax;
1083
1084   /* Try current HK */
1085   t_hmac (&src->Ns,
1086           AX_HEADER_SIZE + esize,
1087           0, &ax->HKr,
1088           &msg_hmac);
1089   if (0 != memcmp (&msg_hmac,
1090                    &src->hmac,
1091                    sizeof (msg_hmac)))
1092   {
1093     static const char ctx[] = "axolotl ratchet";
1094     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1095     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1096     struct GNUNET_HashCode dh;
1097     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1098
1099     /* Try Next HK */
1100     t_hmac (&src->Ns,
1101             AX_HEADER_SIZE + esize,
1102             0,
1103             &ax->NHKr,
1104             &msg_hmac);
1105     if (0 != memcmp (&msg_hmac,
1106                      &src->hmac,
1107                      sizeof (msg_hmac)))
1108     {
1109       /* Try the skipped keys, if that fails, we're out of luck. */
1110       return try_old_ax_keys (t,
1111                               dst,
1112                               src,
1113                               size);
1114     }
1115     HK = ax->HKr;
1116     ax->HKr = ax->NHKr;
1117     t_h_decrypt (t,
1118                  src,
1119                  &plaintext_header);
1120     Np = ntohl (plaintext_header.Ns);
1121     PNp = ntohl (plaintext_header.PNs);
1122     DHRp = &plaintext_header.DHRs;
1123     store_ax_keys (t,
1124                    &HK,
1125                    PNp);
1126
1127     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1128     GNUNET_CRYPTO_ecc_ecdh (ax->DHRs,
1129                             DHRp,
1130                             &dh);
1131     t_ax_hmac_hash (&ax->RK,
1132                     &hmac,
1133                     &dh, sizeof (dh));
1134     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1135                        ctx, sizeof (ctx),
1136                        &hmac, sizeof (hmac),
1137                        NULL);
1138
1139     /* Commit "purported" keys */
1140     ax->RK = keys[0];
1141     ax->NHKr = keys[1];
1142     ax->CKr = keys[2];
1143     ax->DHRr = *DHRp;
1144     ax->Nr = 0;
1145     ax->ratchet_allowed = GNUNET_YES;
1146   }
1147   else
1148   {
1149     t_h_decrypt (t,
1150                  src,
1151                  &plaintext_header);
1152     Np = ntohl (plaintext_header.Ns);
1153     PNp = ntohl (plaintext_header.PNs);
1154   }
1155   if ( (Np != ax->Nr) &&
1156        (GNUNET_OK != store_ax_keys (t,
1157                                     &ax->HKr,
1158                                     Np)) )
1159   {
1160     /* Try the skipped keys, if that fails, we're out of luck. */
1161     return try_old_ax_keys (t,
1162                             dst,
1163                             src,
1164                             size);
1165   }
1166
1167   t_ax_decrypt (t,
1168                 dst,
1169                 &src[1],
1170                 esize);
1171   ax->Nr = Np + 1;
1172   return esize;
1173 }
1174
1175
1176 /**
1177  * Our tunnel became ready for the first time, notify channels
1178  * that have been waiting.
1179  *
1180  * @param cls our tunnel, not used
1181  * @param key unique ID of the channel, not used
1182  * @param value the `struct CadetChannel` to notify
1183  * @return #GNUNET_OK (continue to iterate)
1184  */
1185 static int
1186 notify_tunnel_up_cb (void *cls,
1187                      uint32_t key,
1188                      void *value)
1189 {
1190   struct CadetChannel *ch = value;
1191
1192   GCCH_tunnel_up (ch);
1193   return GNUNET_OK;
1194 }
1195
1196
1197 /**
1198  * Change the tunnel encryption state.
1199  * If the encryption state changes to OK, stop the rekey task.
1200  *
1201  * @param t Tunnel whose encryption state to change, or NULL.
1202  * @param state New encryption state.
1203  */
1204 void
1205 GCT_change_estate (struct CadetTunnel *t,
1206                    enum CadetTunnelEState state)
1207 {
1208   enum CadetTunnelEState old = t->estate;
1209
1210   t->estate = state;
1211   LOG (GNUNET_ERROR_TYPE_DEBUG,
1212        "Tunnel %s estate changed from %d to %d\n",
1213        GCT_2s (t),
1214        old,
1215        state);
1216
1217   if ( (CADET_TUNNEL_KEY_OK != old) &&
1218        (CADET_TUNNEL_KEY_OK == t->estate) )
1219   {
1220     if (NULL != t->kx_task)
1221     {
1222       GNUNET_SCHEDULER_cancel (t->kx_task);
1223       t->kx_task = NULL;
1224     }
1225     if (CADET_TUNNEL_KEY_REKEY != old)
1226     {
1227       /* notify all channels that have been waiting */
1228       GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1229                                                &notify_tunnel_up_cb,
1230                                                t);
1231     }
1232
1233     /* FIXME: schedule rekey task! */
1234   }
1235 }
1236
1237
1238 /**
1239  * Send a KX message.
1240  *
1241  * FIXME: does not take care of sender-authentication yet!
1242  *
1243  * @param t Tunnel on which to send it.
1244  * @param force_reply Force the other peer to reply with a KX message.
1245  */
1246 static void
1247 send_kx (struct CadetTunnel *t,
1248          int force_reply)
1249 {
1250   struct CadetTunnelAxolotl *ax = &t->ax;
1251   struct CadetTConnection *ct;
1252   struct CadetConnection *cc;
1253   struct GNUNET_MQ_Envelope *env;
1254   struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1255   enum GNUNET_CADET_KX_Flags flags;
1256
1257   ct = get_ready_connection (t);
1258   if (NULL == ct)
1259   {
1260     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1261                 "Wanted to send KX on tunnel %s, but no connection is ready, deferring\n",
1262                 GCT_2s (t));
1263     return;
1264   }
1265   cc = ct->cc;
1266   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1267               "Sending KX on tunnel %s using connection %s\n",
1268               GCT_2s (t),
1269               GCC_2s (ct->cc));
1270
1271   // GNUNET_assert (GNUNET_NO == GCT_is_loopback (t));
1272   env = GNUNET_MQ_msg (msg,
1273                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1274   flags = GNUNET_CADET_KX_FLAG_NONE;
1275   if (GNUNET_YES == force_reply)
1276     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1277   msg->flags = htonl (flags);
1278   msg->cid = *GCC_get_id (cc);
1279   GNUNET_CRYPTO_ecdhe_key_get_public (ax->kx_0,
1280                                       &msg->ephemeral_key);
1281   GNUNET_CRYPTO_ecdhe_key_get_public (ax->DHRs,
1282                                       &msg->ratchet_key);
1283   GCC_transmit (cc,
1284                 env);
1285   t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1286   t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1287   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1288     GCT_change_estate (t,
1289                        CADET_TUNNEL_KEY_SENT);
1290 }
1291
1292
1293 /**
1294  * Handle KX message.
1295  *
1296  * FIXME: sender-authentication in KX is missing!
1297  *
1298  * @param ct connection/tunnel combo that received encrypted message
1299  * @param msg the key exchange message
1300  */
1301 void
1302 GCT_handle_kx (struct CadetTConnection *ct,
1303                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1304 {
1305   struct CadetTunnel *t = ct->t;
1306   struct CadetTunnelAxolotl *ax = &t->ax;
1307   struct GNUNET_HashCode key_material[3];
1308   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1309   const char salt[] = "CADET Axolotl salt";
1310   const struct GNUNET_PeerIdentity *pid;
1311   int am_I_alice;
1312
1313   pid = GCP_get_id (t->destination);
1314   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1315                                            pid))
1316     am_I_alice = GNUNET_YES;
1317   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1318                                                 pid))
1319     am_I_alice = GNUNET_NO;
1320   else
1321   {
1322     GNUNET_break_op (0);
1323     return;
1324   }
1325
1326   if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1327   {
1328     if (NULL != t->kx_task)
1329     {
1330       GNUNET_SCHEDULER_cancel (t->kx_task);
1331       t->kx_task = NULL;
1332     }
1333     send_kx (t,
1334              GNUNET_NO);
1335   }
1336
1337   if (0 == memcmp (&ax->DHRr,
1338                    &msg->ratchet_key,
1339                    sizeof (msg->ratchet_key)))
1340   {
1341     LOG (GNUNET_ERROR_TYPE_DEBUG,
1342          " known ratchet key, exit\n");
1343     return;
1344   }
1345
1346   ax->DHRr = msg->ratchet_key;
1347
1348   /* ECDH A B0 */
1349   if (GNUNET_YES == am_I_alice)
1350   {
1351     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1352                               &msg->ephemeral_key, /* B0 */
1353                               &key_material[0]);
1354   }
1355   else
1356   {
1357     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
1358                               &pid->public_key,    /* A */
1359                               &key_material[0]);
1360   }
1361
1362   /* ECDH A0 B */
1363   if (GNUNET_YES == am_I_alice)
1364   {
1365     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
1366                               &pid->public_key,    /* B */
1367                               &key_material[1]);
1368   }
1369   else
1370   {
1371     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1372                               &msg->ephemeral_key, /* B0 */
1373                               &key_material[1]);
1374
1375
1376   }
1377
1378   /* ECDH A0 B0 */
1379   /* (This is the triple-DH, we could probably safely skip this,
1380      as A0/B0 are already in the key material.) */
1381   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
1382                           &msg->ephemeral_key,  /* B0 or A0 */
1383                           &key_material[2]);
1384
1385   /* KDF */
1386   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1387                      salt, sizeof (salt),
1388                      &key_material, sizeof (key_material),
1389                      NULL);
1390
1391   if (0 == memcmp (&ax->RK,
1392                    &keys[0],
1393                    sizeof (ax->RK)))
1394   {
1395     LOG (GNUNET_ERROR_TYPE_INFO,
1396          " known handshake key, exit\n");
1397     return;
1398   }
1399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1400               "Handling KX message for tunnel %s\n",
1401               GCT_2s (t));
1402
1403   ax->RK = keys[0];
1404   if (GNUNET_YES == am_I_alice)
1405   {
1406     ax->HKr = keys[1];
1407     ax->NHKs = keys[2];
1408     ax->NHKr = keys[3];
1409     ax->CKr = keys[4];
1410     ax->ratchet_flag = GNUNET_YES;
1411   }
1412   else
1413   {
1414     ax->HKs = keys[1];
1415     ax->NHKr = keys[2];
1416     ax->NHKs = keys[3];
1417     ax->CKs = keys[4];
1418     ax->ratchet_flag = GNUNET_NO;
1419     ax->ratchet_allowed = GNUNET_NO;
1420     ax->ratchet_counter = 0;
1421     ax->ratchet_expiration
1422       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1423                                   ratchet_time);
1424   }
1425   ax->PNs = 0;
1426   ax->Nr = 0;
1427   ax->Ns = 0;
1428
1429   switch (t->estate)
1430   {
1431   case CADET_TUNNEL_KEY_UNINITIALIZED:
1432     GCT_change_estate (t,
1433                        CADET_TUNNEL_KEY_PING);
1434     break;
1435   case CADET_TUNNEL_KEY_SENT:
1436     /* Got a response to us sending our key; now
1437        we can start transmitting! */
1438     GCT_change_estate (t,
1439                        CADET_TUNNEL_KEY_OK);
1440     trigger_transmissions (t);
1441     break;
1442   case CADET_TUNNEL_KEY_PING:
1443     /* Got a key yet again; need encrypted payload to advance */
1444     break;
1445   case CADET_TUNNEL_KEY_OK:
1446     /* Did not expect a key, but so what. */
1447     break;
1448   case CADET_TUNNEL_KEY_REKEY:
1449     /* Got a key yet again; need encrypted payload to advance */
1450     break;
1451   }
1452 }
1453
1454
1455 /* ************************************** end core crypto ***************************** */
1456
1457
1458 /**
1459  * Compute the next free channel tunnel number for this tunnel.
1460  *
1461  * @param t the tunnel
1462  * @return unused number that can uniquely identify a channel in the tunnel
1463  */
1464 static struct GNUNET_CADET_ChannelTunnelNumber
1465 get_next_free_ctn (struct CadetTunnel *t)
1466 {
1467   struct GNUNET_CADET_ChannelTunnelNumber ret;
1468   uint32_t ctn;
1469
1470   /* FIXME: this logic does NOT prevent both ends of the
1471      channel from picking the same CTN!
1472      Need to reserve one bit of the CTN for the
1473      direction, i.e. which side established the connection! */
1474   ctn = ntohl (t->next_ctn.cn);
1475   while (NULL !=
1476          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1477                                               ctn))
1478     ctn++;
1479   t->next_ctn.cn = htonl (ctn + 1);
1480   ret.cn = ntohl (ctn);
1481   return ret;
1482 }
1483
1484
1485 /**
1486  * Add a channel to a tunnel, and notify channel that we are ready
1487  * for transmission if we are already up.  Otherwise that notification
1488  * will be done later in #notify_tunnel_up_cb().
1489  *
1490  * @param t Tunnel.
1491  * @param ch Channel
1492  * @return unique number identifying @a ch within @a t
1493  */
1494 struct GNUNET_CADET_ChannelTunnelNumber
1495 GCT_add_channel (struct CadetTunnel *t,
1496                  struct CadetChannel *ch)
1497 {
1498   struct GNUNET_CADET_ChannelTunnelNumber ctn;
1499
1500   ctn = get_next_free_ctn (t);
1501   GNUNET_assert (GNUNET_YES ==
1502                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1503                                                       ntohl (ctn.cn),
1504                                                       ch,
1505                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1506   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1507               "Adding channel %s to tunnel %s\n",
1508               GCCH_2s (ch),
1509               GCT_2s (t));
1510   if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1511        (CADET_TUNNEL_KEY_REKEY == t->estate) )
1512     GCCH_tunnel_up (ch);
1513   return ctn;
1514 }
1515
1516
1517 /**
1518  * This tunnel is no longer used, destroy it.
1519  *
1520  * @param cls the idle tunnel
1521  */
1522 static void
1523 destroy_tunnel (void *cls)
1524 {
1525   struct CadetTunnel *t = cls;
1526   struct CadetTConnection *ct;
1527   struct CadetTunnelQueueEntry *tq;
1528
1529   t->destroy_task = NULL;
1530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1531               "Destroying idle tunnel %s\n",
1532               GCT_2s (t));
1533   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1534   while (NULL != (ct = t->connection_head))
1535   {
1536     GNUNET_assert (ct->t == t);
1537     GNUNET_CONTAINER_DLL_remove (t->connection_head,
1538                                  t->connection_tail,
1539                                  ct);
1540     GCC_destroy (ct->cc);
1541     GNUNET_free (ct);
1542   }
1543   while (NULL != (tq = t->tq_head))
1544     GCT_send_cancel (tq);
1545   GCP_drop_tunnel (t->destination,
1546                    t);
1547   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1548   if (NULL != t->maintain_connections_task)
1549   {
1550     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1551     t->maintain_connections_task = NULL;
1552   }
1553   GNUNET_MST_destroy (t->mst);
1554   GNUNET_MQ_destroy (t->mq);
1555   while (NULL != t->ax.skipped_head)
1556     delete_skipped_key (t,
1557                         t->ax.skipped_head);
1558   GNUNET_assert (0 == t->ax.skipped);
1559   GNUNET_free_non_null (t->ax.kx_0);
1560   GNUNET_free_non_null (t->ax.DHRs);
1561   GNUNET_free (t);
1562 }
1563
1564
1565 /**
1566  * Remove a channel from a tunnel.
1567  *
1568  * @param t Tunnel.
1569  * @param ch Channel
1570  * @param ctn unique number identifying @a ch within @a t
1571  */
1572 void
1573 GCT_remove_channel (struct CadetTunnel *t,
1574                     struct CadetChannel *ch,
1575                     struct GNUNET_CADET_ChannelTunnelNumber ctn)
1576 {
1577   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1578               "Removing channel %s from tunnel %s\n",
1579               GCCH_2s (ch),
1580               GCT_2s (t));
1581   GNUNET_assert (GNUNET_YES ==
1582                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1583                                                          ntohl (ctn.cn),
1584                                                          ch));
1585   if (0 ==
1586       GNUNET_CONTAINER_multihashmap32_size (t->channels))
1587   {
1588     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1589                                                     &destroy_tunnel,
1590                                                     t);
1591   }
1592 }
1593
1594
1595 /**
1596  * Destroys the tunnel @a t now, without delay. Used during shutdown.
1597  *
1598  * @param t tunnel to destroy
1599  */
1600 void
1601 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1602 {
1603   GNUNET_assert (0 ==
1604                  GNUNET_CONTAINER_multihashmap32_size (t->channels));
1605   GNUNET_SCHEDULER_cancel (t->destroy_task);
1606   destroy_tunnel (t);
1607 }
1608
1609
1610 /**
1611  * It's been a while, we should try to redo the KX, if we can.
1612  *
1613  * @param cls the `struct CadetTunnel` to do KX for.
1614  */
1615 static void
1616 retry_kx (void *cls)
1617 {
1618   struct CadetTunnel *t = cls;
1619
1620   t->kx_task = NULL;
1621   send_kx (t,
1622            ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1623              (CADET_TUNNEL_KEY_SENT == t->estate) )
1624            ? GNUNET_YES
1625            : GNUNET_NO);
1626 }
1627
1628
1629 /**
1630  * Send normal payload from queue in @a t via connection @a ct.
1631  * Does nothing if our payload queue is empty.
1632  *
1633  * @param t tunnel to send data from
1634  * @param ct connection to use for transmission (is ready)
1635  */
1636 static void
1637 try_send_normal_payload (struct CadetTunnel *t,
1638                          struct CadetTConnection *ct)
1639 {
1640   struct CadetTunnelQueueEntry *tq;
1641
1642   GNUNET_assert (GNUNET_YES == ct->is_ready);
1643   tq = t->tq_head;
1644   if (NULL == tq)
1645   {
1646     /* no messages pending right now */
1647     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1648                 "Not sending payload of tunnel %s on ready connection %s (nothing pending)\n",
1649                 GCT_2s (t),
1650                 GCC_2s (ct->cc));
1651     return;
1652   }
1653   /* ready to send message 'tq' on tunnel 'ct' */
1654   GNUNET_assert (t == tq->t);
1655   GNUNET_CONTAINER_DLL_remove (t->tq_head,
1656                                t->tq_tail,
1657                                tq);
1658   if (NULL != tq->cid)
1659     *tq->cid = *GCC_get_id (ct->cc);
1660   ct->is_ready = GNUNET_NO;
1661   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1662               "Sending payload of tunnel %s on connection %s\n",
1663               GCT_2s (t),
1664               GCC_2s (ct->cc));
1665   GCC_transmit (ct->cc,
1666                 tq->env);
1667   if (NULL != tq->cont)
1668     tq->cont (tq->cont_cls);
1669   GNUNET_free (tq);
1670 }
1671
1672
1673 /**
1674  * A connection is @a is_ready for transmission.  Looks at our message
1675  * queue and if there is a message, sends it out via the connection.
1676  *
1677  * @param cls the `struct CadetTConnection` that is @a is_ready
1678  * @param is_ready #GNUNET_YES if connection are now ready,
1679  *                 #GNUNET_NO if connection are no longer ready
1680  */
1681 static void
1682 connection_ready_cb (void *cls,
1683                      int is_ready)
1684 {
1685   struct CadetTConnection *ct = cls;
1686   struct CadetTunnel *t = ct->t;
1687
1688   if (GNUNET_NO == is_ready)
1689   {
1690     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1691                 "Connection %s no longer ready for tunnel %s\n",
1692                 GCC_2s (ct->cc),
1693                 GCT_2s (t));
1694     ct->is_ready = GNUNET_NO;
1695     return;
1696   }
1697   ct->is_ready = GNUNET_YES;
1698   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1699               "Connection %s now ready for tunnel %s in state %s\n",
1700               GCC_2s (ct->cc),
1701               GCT_2s (t),
1702               estate2s (t->estate));
1703   switch (t->estate)
1704   {
1705   case CADET_TUNNEL_KEY_UNINITIALIZED:
1706     send_kx (t,
1707              GNUNET_YES);
1708     break;
1709   case CADET_TUNNEL_KEY_SENT:
1710   case CADET_TUNNEL_KEY_PING:
1711     /* opportunity to #retry_kx() starts now, schedule job */
1712     if (NULL == t->kx_task)
1713     {
1714       t->kx_task
1715         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1716                                    &retry_kx,
1717                                    t);
1718     }
1719     break;
1720   case CADET_TUNNEL_KEY_OK:
1721     try_send_normal_payload (t,
1722                              ct);
1723     break;
1724   case CADET_TUNNEL_KEY_REKEY:
1725     send_kx (t,
1726              GNUNET_NO);
1727     t->estate = CADET_TUNNEL_KEY_OK;
1728     break;
1729   }
1730 }
1731
1732
1733 /**
1734  * Called when either we have a new connection, or a new message in the
1735  * queue, or some existing connection has transmission capacity.  Looks
1736  * at our message queue and if there is a message, picks a connection
1737  * to send it on.
1738  *
1739  * @param t tunnel to process messages on
1740  */
1741 static void
1742 trigger_transmissions (struct CadetTunnel *t)
1743 {
1744   struct CadetTConnection *ct;
1745
1746   if (NULL == t->tq_head)
1747     return; /* no messages pending right now */
1748   ct = get_ready_connection (t);
1749   if (NULL == ct)
1750     return; /* no connections ready */
1751   try_send_normal_payload (t,
1752                            ct);
1753 }
1754
1755
1756 /**
1757  * Function called to maintain the connections underlying our tunnel.
1758  * Tries to maintain (incl. tear down) connections for the tunnel, and
1759  * if there is a significant change, may trigger transmissions.
1760  *
1761  * Basically, needs to check if there are connections that perform
1762  * badly, and if so eventually kill them and trigger a replacement.
1763  * The strategy is to open one more connection than
1764  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1765  * least-performing one, and then inquire for new ones.
1766  *
1767  * @param cls the `struct CadetTunnel`
1768  */
1769 static void
1770 maintain_connections_cb (void *cls)
1771 {
1772   struct CadetTunnel *t = cls;
1773
1774   t->maintain_connections_task = NULL;
1775   GNUNET_break (0); // FIXME: implement!
1776 }
1777
1778
1779 /**
1780  * Consider using the path @a p for the tunnel @a t.
1781  * The tunnel destination is at offset @a off in path @a p.
1782  *
1783  * @param cls our tunnel
1784  * @param path a path to our destination
1785  * @param off offset of the destination on path @a path
1786  * @return #GNUNET_YES (should keep iterating)
1787  */
1788 static int
1789 consider_path_cb (void *cls,
1790                   struct CadetPeerPath *path,
1791                   unsigned int off)
1792 {
1793   struct CadetTunnel *t = cls;
1794   unsigned int min_length = UINT_MAX;
1795   GNUNET_CONTAINER_HeapCostType max_desire = 0;
1796   struct CadetTConnection *ct;
1797
1798   /* Check if we care about the new path. */
1799   for (ct = t->connection_head;
1800        NULL != ct;
1801        ct = ct->next)
1802   {
1803     struct CadetPeerPath *ps;
1804
1805     ps = GCC_get_path (ct->cc);
1806     if (ps == path)
1807       return GNUNET_YES; /* duplicate */
1808     min_length = GNUNET_MIN (min_length,
1809                              GCPP_get_length (ps));
1810     max_desire = GNUNET_MAX (max_desire,
1811                              GCPP_get_desirability (ps));
1812   }
1813
1814   /* FIXME: not sure we should really just count
1815      'num_connections' here, as they may all have
1816      consistently failed to connect. */
1817
1818   /* We iterate by increasing path length; if we have enough paths and
1819      this one is more than twice as long than what we are currently
1820      using, then ignore all of these super-long ones! */
1821   if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1822        (min_length * 2 < off) )
1823   {
1824     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1825                 "Ignoring paths of length %u, they are way too long.\n",
1826                 min_length * 2);
1827     return GNUNET_NO;
1828   }
1829   /* If we have enough paths and this one looks no better, ignore it. */
1830   if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1831        (min_length < GCPP_get_length (path)) &&
1832        (max_desire > GCPP_get_desirability (path)) )
1833   {
1834     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1835                 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1836                 GCPP_get_length (path),
1837                 (unsigned long long) GCPP_get_desirability (path),
1838                 GCP_2s (t->destination));
1839     return GNUNET_YES;
1840   }
1841
1842   /* Path is interesting (better by some metric, or we don't have
1843      enough paths yet). */
1844   ct = GNUNET_new (struct CadetTConnection);
1845   ct->created = GNUNET_TIME_absolute_get ();
1846   ct->t = t;
1847   ct->cc = GCC_create (t->destination,
1848                        path,
1849                        ct,
1850                        &connection_ready_cb,
1851                        ct);
1852   /* FIXME: schedule job to kill connection (and path?)  if it takes
1853      too long to get ready! (And track performance data on how long
1854      other connections took with the tunnel!)
1855      => Note: to be done within 'connection'-logic! */
1856   GNUNET_CONTAINER_DLL_insert (t->connection_head,
1857                                t->connection_tail,
1858                                ct);
1859   t->num_connections++;
1860   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1861               "Found interesting path %s for tunnel %s, created connection %s\n",
1862               GCPP_2s (path),
1863               GCT_2s (t),
1864               GCC_2s (ct->cc));
1865   return GNUNET_YES;
1866 }
1867
1868
1869 /**
1870  * Consider using the path @a p for the tunnel @a t.
1871  * The tunnel destination is at offset @a off in path @a p.
1872  *
1873  * @param cls our tunnel
1874  * @param path a path to our destination
1875  * @param off offset of the destination on path @a path
1876  */
1877 void
1878 GCT_consider_path (struct CadetTunnel *t,
1879                    struct CadetPeerPath *p,
1880                    unsigned int off)
1881 {
1882   (void) consider_path_cb (t,
1883                            p,
1884                            off);
1885 }
1886
1887
1888 /**
1889  * NOT IMPLEMENTED.
1890  *
1891  * @param cls the `struct CadetTunnel` for which we decrypted the message
1892  * @param msg  the message we received on the tunnel
1893  */
1894 static void
1895 handle_plaintext_keepalive (void *cls,
1896                             const struct GNUNET_MessageHeader *msg)
1897 {
1898   struct CadetTunnel *t = cls;
1899
1900   GNUNET_break (0); // FIXME
1901 }
1902
1903
1904 /**
1905  * Check that @a msg is well-formed.
1906  *
1907  * @param cls the `struct CadetTunnel` for which we decrypted the message
1908  * @param msg  the message we received on the tunnel
1909  * @return #GNUNET_OK (any variable-size payload goes)
1910  */
1911 static int
1912 check_plaintext_data (void *cls,
1913                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1914 {
1915   return GNUNET_OK;
1916 }
1917
1918
1919 /**
1920  * We received payload data for a channel.  Locate the channel
1921  * and process the data, or return an error if the channel is unknown.
1922  *
1923  * @param cls the `struct CadetTunnel` for which we decrypted the message
1924  * @param msg the message we received on the tunnel
1925  */
1926 static void
1927 handle_plaintext_data (void *cls,
1928                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1929 {
1930   struct CadetTunnel *t = cls;
1931   struct CadetChannel *ch;
1932
1933   ch = lookup_channel (t,
1934                        msg->ctn);
1935   if (NULL == ch)
1936   {
1937     /* We don't know about such a channel, might have been destroyed on our
1938        end in the meantime, or never existed. Send back a DESTROY. */
1939     LOG (GNUNET_ERROR_TYPE_DEBUG,
1940          "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
1941          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
1942          ntohl (msg->ctn.cn));
1943     GCT_send_channel_destroy (t,
1944                               msg->ctn);
1945     return;
1946   }
1947   GCCH_handle_channel_plaintext_data (ch,
1948                                       msg);
1949 }
1950
1951
1952 /**
1953  * We received an acknowledgement for data we sent on a channel.
1954  * Locate the channel and process it, or return an error if the
1955  * channel is unknown.
1956  *
1957  * @param cls the `struct CadetTunnel` for which we decrypted the message
1958  * @param ack the message we received on the tunnel
1959  */
1960 static void
1961 handle_plaintext_data_ack (void *cls,
1962                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1963 {
1964   struct CadetTunnel *t = cls;
1965   struct CadetChannel *ch;
1966
1967   ch = lookup_channel (t,
1968                        ack->ctn);
1969   if (NULL == ch)
1970   {
1971     /* We don't know about such a channel, might have been destroyed on our
1972        end in the meantime, or never existed. Send back a DESTROY. */
1973     LOG (GNUNET_ERROR_TYPE_DEBUG,
1974          "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
1975          ntohl (ack->ctn.cn));
1976     GCT_send_channel_destroy (t,
1977                               ack->ctn);
1978     return;
1979   }
1980   GCCH_handle_channel_plaintext_data_ack (ch,
1981                                           ack);
1982 }
1983
1984
1985 /**
1986  * We have received a request to open a channel to a port from
1987  * another peer.  Creates the incoming channel.
1988  *
1989  * @param cls the `struct CadetTunnel` for which we decrypted the message
1990  * @param cc the message we received on the tunnel
1991  */
1992 static void
1993 handle_plaintext_channel_open (void *cls,
1994                                const struct GNUNET_CADET_ChannelOpenMessage *cc)
1995 {
1996   struct CadetTunnel *t = cls;
1997   struct CadetChannel *ch;
1998   struct GNUNET_CADET_ChannelTunnelNumber ctn;
1999
2000   LOG (GNUNET_ERROR_TYPE_DEBUG,
2001        "Receicved channel OPEN on port %s from peer %s\n",
2002        GNUNET_h2s (&cc->port),
2003        GCP_2s (GCT_get_destination (t)));
2004   ctn = get_next_free_ctn (t);
2005   ch = GCCH_channel_incoming_new (t,
2006                                   ctn,
2007                                   &cc->port,
2008                                   ntohl (cc->opt));
2009   GNUNET_assert (GNUNET_OK ==
2010                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2011                                                       ntohl (ctn.cn),
2012                                                       ch,
2013                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2014 }
2015
2016
2017 /**
2018  * Send a DESTROY message via the tunnel.
2019  *
2020  * @param t the tunnel to transmit over
2021  * @param ctn ID of the channel to destroy
2022  */
2023 void
2024 GCT_send_channel_destroy (struct CadetTunnel *t,
2025                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
2026 {
2027   struct GNUNET_CADET_ChannelManageMessage msg;
2028
2029   LOG (GNUNET_ERROR_TYPE_DEBUG,
2030        "Sending DESTORY message for channel ID %u\n",
2031        ntohl (ctn.cn));
2032   msg.header.size = htons (sizeof (msg));
2033   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2034   msg.reserved = htonl (0);
2035   msg.ctn = ctn;
2036   GCT_send (t,
2037             &msg.header,
2038             NULL,
2039             NULL);
2040 }
2041
2042
2043 /**
2044  * We have received confirmation from the target peer that the
2045  * given channel could be established (the port is open).
2046  * Tell the client.
2047  *
2048  * @param cls the `struct CadetTunnel` for which we decrypted the message
2049  * @param cm the message we received on the tunnel
2050  */
2051 static void
2052 handle_plaintext_channel_open_ack (void *cls,
2053                                    const struct GNUNET_CADET_ChannelManageMessage *cm)
2054 {
2055   struct CadetTunnel *t = cls;
2056   struct CadetChannel *ch;
2057
2058   ch = lookup_channel (t,
2059                        cm->ctn);
2060   if (NULL == ch)
2061   {
2062     /* We don't know about such a channel, might have been destroyed on our
2063        end in the meantime, or never existed. Send back a DESTROY. */
2064     LOG (GNUNET_ERROR_TYPE_DEBUG,
2065          "Received channel OPEN_ACK for unknown channel, sending DESTROY\n",
2066          GCCH_2s (ch));
2067     GCT_send_channel_destroy (t,
2068                               cm->ctn);
2069     return;
2070   }
2071   GCCH_handle_channel_open_ack (ch);
2072 }
2073
2074
2075 /**
2076  * We received a message saying that a channel should be destroyed.
2077  * Pass it on to the correct channel.
2078  *
2079  * @param cls the `struct CadetTunnel` for which we decrypted the message
2080  * @param cm the message we received on the tunnel
2081  */
2082 static void
2083 handle_plaintext_channel_destroy (void *cls,
2084                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
2085 {
2086   struct CadetTunnel *t = cls;
2087   struct CadetChannel *ch;
2088
2089   ch = lookup_channel (t,
2090                        cm->ctn);
2091   if (NULL == ch)
2092   {
2093     /* We don't know about such a channel, might have been destroyed on our
2094        end in the meantime, or never existed. */
2095     LOG (GNUNET_ERROR_TYPE_DEBUG,
2096          "Received channel DESTORY for unknown channel. Ignoring.\n",
2097          GCCH_2s (ch));
2098     return;
2099   }
2100   GCCH_handle_remote_destroy (ch);
2101 }
2102
2103
2104 /**
2105  * Handles a message we decrypted, by injecting it into
2106  * our message queue (which will do the dispatching).
2107  *
2108  * @param cls the `struct CadetTunnel` that got the message
2109  * @param msg the message
2110  * @return #GNUNET_OK (continue to process)
2111  */
2112 static int
2113 handle_decrypted (void *cls,
2114                   const struct GNUNET_MessageHeader *msg)
2115 {
2116   struct CadetTunnel *t = cls;
2117
2118   GNUNET_MQ_inject_message (t->mq,
2119                             msg);
2120   return GNUNET_OK;
2121 }
2122
2123
2124 /**
2125  * Function called if we had an error processing
2126  * an incoming decrypted message.
2127  *
2128  * @param cls the `struct CadetTunnel`
2129  * @param error error code
2130  */
2131 static void
2132 decrypted_error_cb (void *cls,
2133                     enum GNUNET_MQ_Error error)
2134 {
2135   GNUNET_break_op (0);
2136 }
2137
2138
2139 /**
2140  * Create a tunnel to @a destionation.  Must only be called
2141  * from within #GCP_get_tunnel().
2142  *
2143  * @param destination where to create the tunnel to
2144  * @return new tunnel to @a destination
2145  */
2146 struct CadetTunnel *
2147 GCT_create_tunnel (struct CadetPeer *destination)
2148 {
2149   struct GNUNET_MQ_MessageHandler handlers[] = {
2150     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2151                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2152                              struct GNUNET_MessageHeader,
2153                              NULL),
2154     GNUNET_MQ_hd_var_size (plaintext_data,
2155                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2156                            struct GNUNET_CADET_ChannelAppDataMessage,
2157                            NULL),
2158     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2159                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2160                              struct GNUNET_CADET_ChannelDataAckMessage,
2161                              NULL),
2162     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2163                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2164                              struct GNUNET_CADET_ChannelOpenMessage,
2165                              NULL),
2166     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2167                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2168                              struct GNUNET_CADET_ChannelManageMessage,
2169                              NULL),
2170     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2171                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2172                              struct GNUNET_CADET_ChannelManageMessage,
2173                              NULL),
2174     GNUNET_MQ_handler_end ()
2175   };
2176   struct CadetTunnel *t;
2177
2178   t = GNUNET_new (struct CadetTunnel);
2179   new_ephemeral (t);
2180   t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2181   t->destination = destination;
2182   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2183   (void) GCP_iterate_paths (destination,
2184                             &consider_path_cb,
2185                             t);
2186   t->maintain_connections_task
2187     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2188                                 t);
2189   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2190                                          NULL,
2191                                          NULL,
2192                                          NULL,
2193                                          handlers,
2194                                          &decrypted_error_cb,
2195                                          t);
2196   t->mst = GNUNET_MST_create (&handle_decrypted,
2197                               t);
2198   return t;
2199 }
2200
2201
2202 /**
2203  * Add a @a connection to the @a tunnel.
2204  *
2205  * @param t a tunnel
2206  * @param cid connection identifer to use for the connection
2207  * @param path path to use for the connection
2208  */
2209 void
2210 GCT_add_inbound_connection (struct CadetTunnel *t,
2211                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2212                             struct CadetPeerPath *path)
2213 {
2214   struct CadetTConnection *ct;
2215
2216   ct = GNUNET_new (struct CadetTConnection);
2217   ct->created = GNUNET_TIME_absolute_get ();
2218   ct->t = t;
2219   ct->cc = GCC_create_inbound (t->destination,
2220                                path,
2221                                ct,
2222                                cid,
2223                                &connection_ready_cb,
2224                                t);
2225   /* FIXME: schedule job to kill connection (and path?)  if it takes
2226      too long to get ready! (And track performance data on how long
2227      other connections took with the tunnel!)
2228      => Note: to be done within 'connection'-logic! */
2229   GNUNET_CONTAINER_DLL_insert (t->connection_head,
2230                                t->connection_tail,
2231                                ct);
2232   t->num_connections++;
2233   LOG (GNUNET_ERROR_TYPE_DEBUG,
2234        "Tunnel %s has new connection %s\n",
2235        GCT_2s (t),
2236        GCC_2s (ct->cc));
2237 }
2238
2239
2240 /**
2241  * Handle encrypted message.
2242  *
2243  * @param ct connection/tunnel combo that received encrypted message
2244  * @param msg the encrypted message to decrypt
2245  */
2246 void
2247 GCT_handle_encrypted (struct CadetTConnection *ct,
2248                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2249 {
2250   struct CadetTunnel *t = ct->t;
2251   uint16_t size = ntohs (msg->header.size);
2252   char cbuf [size] GNUNET_ALIGN;
2253   ssize_t decrypted_size;
2254
2255   LOG (GNUNET_ERROR_TYPE_DEBUG,
2256        "Tunnel %s received %u bytes of encrypted data in state %d\n",
2257        GCT_2s (t),
2258        (unsigned int) size,
2259        t->estate);
2260
2261   switch (t->estate)
2262   {
2263   case CADET_TUNNEL_KEY_UNINITIALIZED:
2264     /* We did not even SEND our KX, how can the other peer
2265        send us encrypted data? */
2266     GNUNET_break_op (0);
2267     return;
2268   case CADET_TUNNEL_KEY_SENT:
2269     /* We did not get the KX of the other peer, but that
2270        might have been lost.  Ask for KX again. */
2271     GNUNET_STATISTICS_update (stats,
2272                               "# received encrypted without KX",
2273                               1,
2274                               GNUNET_NO);
2275     if (NULL != t->kx_task)
2276       GNUNET_SCHEDULER_cancel (t->kx_task);
2277     t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2278                                            t);
2279     return;
2280   case CADET_TUNNEL_KEY_PING:
2281     /* Great, first payload, we might graduate to OK */
2282   case CADET_TUNNEL_KEY_OK:
2283   case CADET_TUNNEL_KEY_REKEY:
2284     break;
2285   }
2286
2287   GNUNET_STATISTICS_update (stats,
2288                             "# received encrypted",
2289                             1,
2290                             GNUNET_NO);
2291   decrypted_size = t_ax_decrypt_and_validate (t,
2292                                               cbuf,
2293                                               msg,
2294                                               size);
2295
2296   if (-1 == decrypted_size)
2297   {
2298     GNUNET_break_op (0);
2299     LOG (GNUNET_ERROR_TYPE_WARNING,
2300          "Tunnel %s failed to decrypt and validate encrypted data\n",
2301          GCT_2s (t));
2302     GNUNET_STATISTICS_update (stats,
2303                               "# unable to decrypt",
2304                               1,
2305                               GNUNET_NO);
2306     return;
2307   }
2308   if (CADET_TUNNEL_KEY_PING == t->estate)
2309   {
2310     GCT_change_estate (t,
2311                        CADET_TUNNEL_KEY_OK);
2312     trigger_transmissions (t);
2313   }
2314   /* The MST will ultimately call #handle_decrypted() on each message. */
2315   GNUNET_break_op (GNUNET_OK ==
2316                    GNUNET_MST_from_buffer (t->mst,
2317                                            cbuf,
2318                                            decrypted_size,
2319                                            GNUNET_YES,
2320                                            GNUNET_NO));
2321 }
2322
2323
2324 /**
2325  * Sends an already built message on a tunnel, encrypting it and
2326  * choosing the best connection if not provided.
2327  *
2328  * @param message Message to send. Function modifies it.
2329  * @param t Tunnel on which this message is transmitted.
2330  * @param cont Continuation to call once message is really sent.
2331  * @param cont_cls Closure for @c cont.
2332  * @return Handle to cancel message. NULL if @c cont is NULL.
2333  */
2334 struct CadetTunnelQueueEntry *
2335 GCT_send (struct CadetTunnel *t,
2336           const struct GNUNET_MessageHeader *message,
2337           GNUNET_SCHEDULER_TaskCallback cont,
2338           void *cont_cls)
2339 {
2340   struct CadetTunnelQueueEntry *tq;
2341   uint16_t payload_size;
2342   struct GNUNET_MQ_Envelope *env;
2343   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2344
2345   payload_size = ntohs (message->size);
2346   LOG (GNUNET_ERROR_TYPE_DEBUG,
2347        "Encrypting %u bytes of for tunnel %s\n",
2348        (unsigned int) payload_size,
2349        GCT_2s (t));
2350   env = GNUNET_MQ_msg_extra (ax_msg,
2351                              payload_size,
2352                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2353   t_ax_encrypt (t,
2354                 &ax_msg[1],
2355                 message,
2356                 payload_size);
2357   ax_msg->Ns = htonl (t->ax.Ns++);
2358   ax_msg->PNs = htonl (t->ax.PNs);
2359   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2360                                       &ax_msg->DHRs);
2361   t_h_encrypt (t,
2362                ax_msg);
2363   t_hmac (&ax_msg->Ns,
2364           AX_HEADER_SIZE + payload_size,
2365           0,
2366           &t->ax.HKs,
2367           &ax_msg->hmac);
2368
2369   tq = GNUNET_malloc (sizeof (*tq));
2370   tq->t = t;
2371   tq->env = env;
2372   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2373   tq->cont = cont;
2374   tq->cont_cls = cont_cls;
2375   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2376                                     t->tq_tail,
2377                                     tq);
2378   trigger_transmissions (t);
2379   return tq;
2380 }
2381
2382
2383 /**
2384  * Cancel a previously sent message while it's in the queue.
2385  *
2386  * ONLY can be called before the continuation given to the send
2387  * function is called. Once the continuation is called, the message is
2388  * no longer in the queue!
2389  *
2390  * @param tq Handle to the queue entry to cancel.
2391  */
2392 void
2393 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2394 {
2395   struct CadetTunnel *t = tq->t;
2396
2397   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2398                                t->tq_tail,
2399                                tq);
2400   GNUNET_MQ_discard (tq->env);
2401   GNUNET_free (tq);
2402 }
2403
2404
2405 /**
2406  * Iterate over all connections of a tunnel.
2407  *
2408  * @param t Tunnel whose connections to iterate.
2409  * @param iter Iterator.
2410  * @param iter_cls Closure for @c iter.
2411  */
2412 void
2413 GCT_iterate_connections (struct CadetTunnel *t,
2414                          GCT_ConnectionIterator iter,
2415                          void *iter_cls)
2416 {
2417   for (struct CadetTConnection *ct = t->connection_head;
2418        NULL != ct;
2419        ct = ct->next)
2420     iter (iter_cls,
2421           ct->cc);
2422 }
2423
2424
2425 /**
2426  * Closure for #iterate_channels_cb.
2427  */
2428 struct ChanIterCls
2429 {
2430   /**
2431    * Function to call.
2432    */
2433   GCT_ChannelIterator iter;
2434
2435   /**
2436    * Closure for @e iter.
2437    */
2438   void *iter_cls;
2439 };
2440
2441
2442 /**
2443  * Helper function for #GCT_iterate_channels.
2444  *
2445  * @param cls the `struct ChanIterCls`
2446  * @param key unused
2447  * @param value a `struct CadetChannel`
2448  * @return #GNUNET_OK
2449  */
2450 static int
2451 iterate_channels_cb (void *cls,
2452                      uint32_t key,
2453                      void *value)
2454 {
2455   struct ChanIterCls *ctx = cls;
2456   struct CadetChannel *ch = value;
2457
2458   ctx->iter (ctx->iter_cls,
2459              ch);
2460   return GNUNET_OK;
2461 }
2462
2463
2464 /**
2465  * Iterate over all channels of a tunnel.
2466  *
2467  * @param t Tunnel whose channels to iterate.
2468  * @param iter Iterator.
2469  * @param iter_cls Closure for @c iter.
2470  */
2471 void
2472 GCT_iterate_channels (struct CadetTunnel *t,
2473                       GCT_ChannelIterator iter,
2474                       void *iter_cls)
2475 {
2476   struct ChanIterCls ctx;
2477
2478   ctx.iter = iter;
2479   ctx.iter_cls = iter_cls;
2480   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2481                                            &iterate_channels_cb,
2482                                            &ctx);
2483
2484 }
2485
2486
2487 /**
2488  * Call #GCCH_debug() on a channel.
2489  *
2490  * @param cls points to the log level to use
2491  * @param key unused
2492  * @param value the `struct CadetChannel` to dump
2493  * @return #GNUNET_OK (continue iteration)
2494  */
2495 static int
2496 debug_channel (void *cls,
2497                uint32_t key,
2498                void *value)
2499 {
2500   const enum GNUNET_ErrorType *level = cls;
2501   struct CadetChannel *ch = value;
2502
2503   GCCH_debug (ch, *level);
2504   return GNUNET_OK;
2505 }
2506
2507
2508 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2509
2510
2511 /**
2512  * Log all possible info about the tunnel state.
2513  *
2514  * @param t Tunnel to debug.
2515  * @param level Debug level to use.
2516  */
2517 void
2518 GCT_debug (const struct CadetTunnel *t,
2519            enum GNUNET_ErrorType level)
2520 {
2521   struct CadetTConnection *iter_c;
2522   int do_log;
2523
2524   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2525                                        "cadet-tun",
2526                                        __FILE__, __FUNCTION__, __LINE__);
2527   if (0 == do_log)
2528     return;
2529
2530   LOG2 (level,
2531         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2532         GCT_2s (t),
2533         estate2s (t->estate),
2534         t->tq_len,
2535         t->num_connections);
2536 #if DUMP_KEYS_TO_STDERR
2537   ax_debug (t->ax, level);
2538 #endif
2539   LOG2 (level,
2540         "TTT channels:\n");
2541   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2542                                            &debug_channel,
2543                                            &level);
2544   LOG2 (level,
2545         "TTT connections:\n");
2546   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2547     GCC_debug (iter_c->cc,
2548                level);
2549
2550   LOG2 (level,
2551         "TTT TUNNEL END\n");
2552 }
2553
2554
2555 /* end of gnunet-service-cadet-new_tunnels.c */