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