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