must delay iteration over paths until later, as we may be right now creating a connection
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2017 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file cadet/gnunet-service-cadet-new_tunnels.c
22  * @brief Information we track per tunnel.
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  *
26  * FIXME:
27  * - check KX estate machine -- make sure it is never stuck!
28  * - clean up KX logic, including adding sender authentication
29  * - implement connection management (evaluate, kill old ones,
30  *   search for new ones)
31  * - when managing connections, distinguish those that
32  *   have (recently) had traffic from those that were
33  *   never ready (or not recently)
34  */
35 #include "platform.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_statistics_service.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet-service-cadet-new.h"
40 #include "cadet_protocol.h"
41 #include "gnunet-service-cadet-new_channel.h"
42 #include "gnunet-service-cadet-new_connection.h"
43 #include "gnunet-service-cadet-new_tunnels.h"
44 #include "gnunet-service-cadet-new_peer.h"
45 #include "gnunet-service-cadet-new_paths.h"
46
47
48 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
49
50
51 /**
52  * How long do we wait until tearing down an idle tunnel?
53  */
54 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
55
56 /**
57  * Yuck, replace by 'offsetof' expression?
58  * FIXME.
59  */
60 #define AX_HEADER_SIZE (sizeof (uint32_t) * 2\
61                         + sizeof (struct GNUNET_CRYPTO_EcdhePublicKey))
62
63
64 /**
65  * Maximum number of skipped keys we keep in memory per tunnel.
66  */
67 #define MAX_SKIPPED_KEYS 64
68
69 /**
70  * Maximum number of keys (and thus ratchet steps) we are willing to
71  * skip before we decide this is either a bogus packet or a DoS-attempt.
72  */
73 #define MAX_KEY_GAP 256
74
75
76 /**
77  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
78  */
79 struct CadetTunnelSkippedKey
80 {
81   /**
82    * DLL next.
83    */
84   struct CadetTunnelSkippedKey *next;
85
86   /**
87    * DLL prev.
88    */
89   struct CadetTunnelSkippedKey *prev;
90
91   /**
92    * When was this key stored (for timeout).
93    */
94   struct GNUNET_TIME_Absolute timestamp;
95
96   /**
97    * Header key.
98    */
99   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
100
101   /**
102    * Message key.
103    */
104   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
105
106   /**
107    * Key number for a given HK.
108    */
109   unsigned int Kn;
110 };
111
112
113 /**
114  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
115  */
116 struct CadetTunnelAxolotl
117 {
118   /**
119    * A (double linked) list of stored message keys and associated header keys
120    * for "skipped" messages, i.e. messages that have not been
121    * received despite the reception of more recent messages, (head).
122    */
123   struct CadetTunnelSkippedKey *skipped_head;
124
125   /**
126    * Skipped messages' keys DLL, tail.
127    */
128   struct CadetTunnelSkippedKey *skipped_tail;
129
130   /**
131    * 32-byte root key which gets updated by DH ratchet.
132    */
133   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
134
135   /**
136    * 32-byte header key (send).
137    */
138   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
139
140   /**
141    * 32-byte header key (recv)
142    */
143   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
144
145   /**
146    * 32-byte next header key (send).
147    */
148   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
149
150   /**
151    * 32-byte next header key (recv).
152    */
153   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
154
155   /**
156    * 32-byte chain keys (used for forward-secrecy updating, send).
157    */
158   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
159
160   /**
161    * 32-byte chain keys (used for forward-secrecy updating, recv).
162    */
163   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
164
165   /**
166    * ECDH for key exchange (A0 / B0).
167    */
168   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
169
170   /**
171    * ECDH Ratchet key (send).
172    */
173   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
174
175   /**
176    * ECDH Ratchet key (recv).
177    */
178   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
179
180   /**
181    * When does this ratchet expire and a new one is triggered.
182    */
183   struct GNUNET_TIME_Absolute ratchet_expiration;
184
185   /**
186    * Number of elements in @a skipped_head <-> @a skipped_tail.
187    */
188   unsigned int skipped;
189
190   /**
191    * Message number (reset to 0 with each new ratchet, next message to send).
192    */
193   uint32_t Ns;
194
195   /**
196    * Message number (reset to 0 with each new ratchet, next message to recv).
197    */
198   uint32_t Nr;
199
200   /**
201    * Previous message numbers (# of msgs sent under prev ratchet)
202    */
203   uint32_t PNs;
204
205   /**
206    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
207    */
208   int ratchet_flag;
209
210   /**
211    * Number of messages recieved since our last ratchet advance.
212    * - If this counter = 0, we cannot send a new ratchet key in next msg.
213    * - If this counter > 0, we can (but don't yet have to) send a new key.
214    */
215   unsigned int ratchet_allowed;
216
217   /**
218    * Number of messages recieved since our last ratchet advance.
219    * - If this counter = 0, we cannot send a new ratchet key in next msg.
220    * - If this counter > 0, we can (but don't yet have to) send a new key.
221    */
222   unsigned int ratchet_counter;
223
224 };
225
226
227 /**
228  * Struct used to save messages in a non-ready tunnel to send once connected.
229  */
230 struct CadetTunnelQueueEntry
231 {
232   /**
233    * We are entries in a DLL
234    */
235   struct CadetTunnelQueueEntry *next;
236
237   /**
238    * We are entries in a DLL
239    */
240   struct CadetTunnelQueueEntry *prev;
241
242   /**
243    * Tunnel these messages belong in.
244    */
245   struct CadetTunnel *t;
246
247   /**
248    * Continuation to call once sent (on the channel layer).
249    */
250   GNUNET_SCHEDULER_TaskCallback cont;
251
252   /**
253    * Closure for @c cont.
254    */
255   void *cont_cls;
256
257   /**
258    * Envelope of message to send follows.
259    */
260   struct GNUNET_MQ_Envelope *env;
261
262   /**
263    * Where to put the connection identifier into the payload
264    * of the message in @e env once we have it?
265    */
266   struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
267 };
268
269
270 /**
271  * Struct containing all information regarding a tunnel to a peer.
272  */
273 struct CadetTunnel
274 {
275   /**
276    * Destination of the tunnel.
277    */
278   struct CadetPeer *destination;
279
280   /**
281    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
282    * ephemeral key changes.
283    */
284   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
285
286   /**
287    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
288    */
289   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
290
291   /**
292    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
293    */
294   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
295
296   /**
297    * Axolotl info.
298    */
299   struct CadetTunnelAxolotl ax;
300
301   /**
302    * Task scheduled if there are no more channels using the tunnel.
303    */
304   struct GNUNET_SCHEDULER_Task *destroy_task;
305
306   /**
307    * Task to trim connections if too many are present.
308    */
309   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
310
311   /**
312    * Task to trigger KX.
313    */
314   struct GNUNET_SCHEDULER_Task *kx_task;
315
316   /**
317    * Tokenizer for decrypted messages.
318    */
319   struct GNUNET_MessageStreamTokenizer *mst;
320
321   /**
322    * Dispatcher for decrypted messages only (do NOT use for sending!).
323    */
324   struct GNUNET_MQ_Handle *mq;
325
326   /**
327    * DLL of connections that are actively used to reach the destination peer.
328    */
329   struct CadetTConnection *connection_head;
330
331   /**
332    * DLL of connections that are actively used to reach the destination peer.
333    */
334   struct CadetTConnection *connection_tail;
335
336   /**
337    * Channels inside this tunnel. Maps
338    * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
339    */
340   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
341
342   /**
343    * Channel ID for the next created channel in this tunnel.
344    */
345   struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
346
347   /**
348    * Queued messages, to transmit once tunnel gets connected.
349    */
350   struct CadetTunnelQueueEntry *tq_head;
351
352   /**
353    * Queued messages, to transmit once tunnel gets connected.
354    */
355   struct CadetTunnelQueueEntry *tq_tail;
356
357
358   /**
359    * Ephemeral message in the queue (to avoid queueing more than one).
360    */
361   struct CadetConnectionQueue *ephm_hKILL;
362
363   /**
364    * Pong message in the queue.
365    */
366   struct CadetConnectionQueue *pong_hKILL;
367
368   /**
369    * How long do we wait until we retry the KX?
370    */
371   struct GNUNET_TIME_Relative kx_retry_delay;
372
373   /**
374    * When do we try the next KX?
375    */
376   struct GNUNET_TIME_Absolute next_kx_attempt;
377
378   /**
379    * Number of connections in the @e connection_head DLL.
380    */
381   unsigned int num_connections;
382
383   /**
384    * Number of entries in the @e tq_head DLL.
385    */
386   unsigned int tq_len;
387
388   /**
389    * State of the tunnel encryption.
390    */
391   enum CadetTunnelEState estate;
392
393 };
394
395
396 /**
397  * Get the static string for the peer this tunnel is directed.
398  *
399  * @param t Tunnel.
400  *
401  * @return Static string the destination peer's ID.
402  */
403 const char *
404 GCT_2s (const struct CadetTunnel *t)
405 {
406   static char buf[64];
407
408   if (NULL == t)
409     return "T(NULL)";
410   GNUNET_snprintf (buf,
411                    sizeof (buf),
412                    "T(%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     GNUNET_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   GNUNET_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   GCC_transmit (cc,
1283                 env);
1284   t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1285   t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1286   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1287     GCT_change_estate (t,
1288                        CADET_TUNNEL_KEY_SENT);
1289 }
1290
1291
1292 /**
1293  * Handle KX message.
1294  *
1295  * FIXME: sender-authentication in KX is missing!
1296  *
1297  * @param ct connection/tunnel combo that received encrypted message
1298  * @param msg the key exchange message
1299  */
1300 void
1301 GCT_handle_kx (struct CadetTConnection *ct,
1302                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1303 {
1304   struct CadetTunnel *t = ct->t;
1305   struct CadetTunnelAxolotl *ax = &t->ax;
1306   struct GNUNET_HashCode key_material[3];
1307   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1308   const char salt[] = "CADET Axolotl salt";
1309   const struct GNUNET_PeerIdentity *pid;
1310   int am_I_alice;
1311
1312   pid = GCP_get_id (t->destination);
1313   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1314                                            pid))
1315     am_I_alice = GNUNET_YES;
1316   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1317                                                 pid))
1318     am_I_alice = GNUNET_NO;
1319   else
1320   {
1321     GNUNET_break_op (0);
1322     return;
1323   }
1324
1325   if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->flags)))
1326   {
1327     if (NULL != t->kx_task)
1328     {
1329       GNUNET_SCHEDULER_cancel (t->kx_task);
1330       t->kx_task = NULL;
1331     }
1332     send_kx (t,
1333              GNUNET_NO);
1334   }
1335
1336   if (0 == memcmp (&ax->DHRr,
1337                    &msg->ratchet_key,
1338                    sizeof (msg->ratchet_key)))
1339   {
1340     LOG (GNUNET_ERROR_TYPE_DEBUG,
1341          " known ratchet key, exit\n");
1342     return;
1343   }
1344
1345   ax->DHRr = msg->ratchet_key;
1346
1347   /* ECDH A B0 */
1348   if (GNUNET_YES == am_I_alice)
1349   {
1350     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1351                               &msg->ephemeral_key, /* B0 */
1352                               &key_material[0]);
1353   }
1354   else
1355   {
1356     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* B0 */
1357                               &pid->public_key,    /* A */
1358                               &key_material[0]);
1359   }
1360
1361   /* ECDH A0 B */
1362   if (GNUNET_YES == am_I_alice)
1363   {
1364     GNUNET_CRYPTO_ecdh_eddsa (ax->kx_0,            /* A0 */
1365                               &pid->public_key,    /* B */
1366                               &key_material[1]);
1367   }
1368   else
1369   {
1370     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1371                               &msg->ephemeral_key, /* B0 */
1372                               &key_material[1]);
1373
1374
1375   }
1376
1377   /* ECDH A0 B0 */
1378   /* (This is the triple-DH, we could probably safely skip this,
1379      as A0/B0 are already in the key material.) */
1380   GNUNET_CRYPTO_ecc_ecdh (ax->kx_0,             /* A0 or B0 */
1381                           &msg->ephemeral_key,  /* B0 or A0 */
1382                           &key_material[2]);
1383
1384   /* KDF */
1385   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1386                      salt, sizeof (salt),
1387                      &key_material, sizeof (key_material),
1388                      NULL);
1389
1390   if (0 == memcmp (&ax->RK,
1391                    &keys[0],
1392                    sizeof (ax->RK)))
1393   {
1394     LOG (GNUNET_ERROR_TYPE_INFO,
1395          " known handshake key, exit\n");
1396     return;
1397   }
1398   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1399               "Handling KX message for tunnel %s\n",
1400               GCT_2s (t));
1401
1402   ax->RK = keys[0];
1403   if (GNUNET_YES == am_I_alice)
1404   {
1405     ax->HKr = keys[1];
1406     ax->NHKs = keys[2];
1407     ax->NHKr = keys[3];
1408     ax->CKr = keys[4];
1409     ax->ratchet_flag = GNUNET_YES;
1410   }
1411   else
1412   {
1413     ax->HKs = keys[1];
1414     ax->NHKr = keys[2];
1415     ax->NHKs = keys[3];
1416     ax->CKs = keys[4];
1417     ax->ratchet_flag = GNUNET_NO;
1418     ax->ratchet_allowed = GNUNET_NO;
1419     ax->ratchet_counter = 0;
1420     ax->ratchet_expiration
1421       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1422                                   ratchet_time);
1423   }
1424   ax->PNs = 0;
1425   ax->Nr = 0;
1426   ax->Ns = 0;
1427
1428   switch (t->estate)
1429   {
1430   case CADET_TUNNEL_KEY_UNINITIALIZED:
1431     GCT_change_estate (t,
1432                        CADET_TUNNEL_KEY_PING);
1433     break;
1434   case CADET_TUNNEL_KEY_SENT:
1435     /* Got a response to us sending our key; now
1436        we can start transmitting! */
1437     GCT_change_estate (t,
1438                        CADET_TUNNEL_KEY_OK);
1439     trigger_transmissions (t);
1440     break;
1441   case CADET_TUNNEL_KEY_PING:
1442     /* Got a key yet again; need encrypted payload to advance */
1443     break;
1444   case CADET_TUNNEL_KEY_OK:
1445     /* Did not expect a key, but so what. */
1446     break;
1447   case CADET_TUNNEL_KEY_REKEY:
1448     /* Got a key yet again; need encrypted payload to advance */
1449     break;
1450   }
1451 }
1452
1453
1454 /* ************************************** end core crypto ***************************** */
1455
1456
1457 /**
1458  * Compute the next free channel tunnel number for this tunnel.
1459  *
1460  * @param t the tunnel
1461  * @return unused number that can uniquely identify a channel in the tunnel
1462  */
1463 static struct GNUNET_CADET_ChannelTunnelNumber
1464 get_next_free_ctn (struct CadetTunnel *t)
1465 {
1466   struct GNUNET_CADET_ChannelTunnelNumber ret;
1467   uint32_t ctn;
1468
1469   /* FIXME: this logic does NOT prevent both ends of the
1470      channel from picking the same CTN!
1471      Need to reserve one bit of the CTN for the
1472      direction, i.e. which side established the connection! */
1473   ctn = ntohl (t->next_ctn.cn);
1474   while (NULL !=
1475          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1476                                               ctn))
1477     ctn++;
1478   t->next_ctn.cn = htonl (ctn + 1);
1479   ret.cn = ntohl (ctn);
1480   return ret;
1481 }
1482
1483
1484 /**
1485  * Add a channel to a tunnel, and notify channel that we are ready
1486  * for transmission if we are already up.  Otherwise that notification
1487  * will be done later in #notify_tunnel_up_cb().
1488  *
1489  * @param t Tunnel.
1490  * @param ch Channel
1491  * @return unique number identifying @a ch within @a t
1492  */
1493 struct GNUNET_CADET_ChannelTunnelNumber
1494 GCT_add_channel (struct CadetTunnel *t,
1495                  struct CadetChannel *ch)
1496 {
1497   struct GNUNET_CADET_ChannelTunnelNumber ctn;
1498
1499   ctn = get_next_free_ctn (t);
1500   GNUNET_assert (GNUNET_YES ==
1501                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1502                                                       ntohl (ctn.cn),
1503                                                       ch,
1504                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1506               "Adding channel %s to tunnel %s\n",
1507               GCCH_2s (ch),
1508               GCT_2s (t));
1509   if ( (CADET_TUNNEL_KEY_OK == t->estate) ||
1510        (CADET_TUNNEL_KEY_REKEY == t->estate) )
1511     GCCH_tunnel_up (ch);
1512   return ctn;
1513 }
1514
1515
1516 /**
1517  * This tunnel is no longer used, destroy it.
1518  *
1519  * @param cls the idle tunnel
1520  */
1521 static void
1522 destroy_tunnel (void *cls)
1523 {
1524   struct CadetTunnel *t = cls;
1525   struct CadetTConnection *ct;
1526   struct CadetTunnelQueueEntry *tq;
1527
1528   t->destroy_task = NULL;
1529   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1530               "Destroying idle tunnel %s\n",
1531               GCT_2s (t));
1532   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
1533   while (NULL != (ct = t->connection_head))
1534   {
1535     GNUNET_assert (ct->t == t);
1536     GNUNET_CONTAINER_DLL_remove (t->connection_head,
1537                                  t->connection_tail,
1538                                  ct);
1539     GCC_destroy (ct->cc);
1540     GNUNET_free (ct);
1541   }
1542   while (NULL != (tq = t->tq_head))
1543     GCT_send_cancel (tq);
1544   GCP_drop_tunnel (t->destination,
1545                    t);
1546   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
1547   if (NULL != t->maintain_connections_task)
1548   {
1549     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
1550     t->maintain_connections_task = NULL;
1551   }
1552   GNUNET_MST_destroy (t->mst);
1553   GNUNET_MQ_destroy (t->mq);
1554   while (NULL != t->ax.skipped_head)
1555     delete_skipped_key (t,
1556                         t->ax.skipped_head);
1557   GNUNET_assert (0 == t->ax.skipped);
1558   GNUNET_free_non_null (t->ax.kx_0);
1559   GNUNET_free_non_null (t->ax.DHRs);
1560   GNUNET_free (t);
1561 }
1562
1563
1564 /**
1565  * Remove a channel from a tunnel.
1566  *
1567  * @param t Tunnel.
1568  * @param ch Channel
1569  * @param ctn unique number identifying @a ch within @a t
1570  */
1571 void
1572 GCT_remove_channel (struct CadetTunnel *t,
1573                     struct CadetChannel *ch,
1574                     struct GNUNET_CADET_ChannelTunnelNumber ctn)
1575 {
1576   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1577               "Removing channel %s from tunnel %s\n",
1578               GCCH_2s (ch),
1579               GCT_2s (t));
1580   GNUNET_assert (GNUNET_YES ==
1581                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
1582                                                          ntohl (ctn.cn),
1583                                                          ch));
1584   if (0 ==
1585       GNUNET_CONTAINER_multihashmap32_size (t->channels))
1586   {
1587     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
1588                                                     &destroy_tunnel,
1589                                                     t);
1590   }
1591 }
1592
1593
1594 /**
1595  * Destroys the tunnel @a t now, without delay. Used during shutdown.
1596  *
1597  * @param t tunnel to destroy
1598  */
1599 void
1600 GCT_destroy_tunnel_now (struct CadetTunnel *t)
1601 {
1602   GNUNET_assert (0 ==
1603                  GNUNET_CONTAINER_multihashmap32_size (t->channels));
1604   GNUNET_SCHEDULER_cancel (t->destroy_task);
1605   destroy_tunnel (t);
1606 }
1607
1608
1609 /**
1610  * It's been a while, we should try to redo the KX, if we can.
1611  *
1612  * @param cls the `struct CadetTunnel` to do KX for.
1613  */
1614 static void
1615 retry_kx (void *cls)
1616 {
1617   struct CadetTunnel *t = cls;
1618
1619   t->kx_task = NULL;
1620   send_kx (t,
1621            ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1622              (CADET_TUNNEL_KEY_SENT == t->estate) )
1623            ? GNUNET_YES
1624            : GNUNET_NO);
1625 }
1626
1627
1628 /**
1629  * Send normal payload from queue in @a t via connection @a ct.
1630  * Does nothing if our payload queue is empty.
1631  *
1632  * @param t tunnel to send data from
1633  * @param ct connection to use for transmission (is ready)
1634  */
1635 static void
1636 try_send_normal_payload (struct CadetTunnel *t,
1637                          struct CadetTConnection *ct)
1638 {
1639   struct CadetTunnelQueueEntry *tq;
1640
1641   GNUNET_assert (GNUNET_YES == ct->is_ready);
1642   tq = t->tq_head;
1643   if (NULL == tq)
1644   {
1645     /* no messages pending right now */
1646     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1647                 "Not sending payload of tunnel %s on ready connection %s (nothing pending)\n",
1648                 GCT_2s (t),
1649                 GCC_2s (ct->cc));
1650     return;
1651   }
1652   /* ready to send message 'tq' on tunnel 'ct' */
1653   GNUNET_assert (t == tq->t);
1654   GNUNET_CONTAINER_DLL_remove (t->tq_head,
1655                                t->tq_tail,
1656                                tq);
1657   if (NULL != tq->cid)
1658     *tq->cid = *GCC_get_id (ct->cc);
1659   ct->is_ready = GNUNET_NO;
1660   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1661               "Sending payload of tunnel %s on connection %s\n",
1662               GCT_2s (t),
1663               GCC_2s (ct->cc));
1664   GCC_transmit (ct->cc,
1665                 tq->env);
1666   if (NULL != tq->cont)
1667     tq->cont (tq->cont_cls);
1668   GNUNET_free (tq);
1669 }
1670
1671
1672 /**
1673  * A connection is @a is_ready for transmission.  Looks at our message
1674  * queue and if there is a message, sends it out via the connection.
1675  *
1676  * @param cls the `struct CadetTConnection` that is @a is_ready
1677  * @param is_ready #GNUNET_YES if connection are now ready,
1678  *                 #GNUNET_NO if connection are no longer ready
1679  */
1680 static void
1681 connection_ready_cb (void *cls,
1682                      int is_ready)
1683 {
1684   struct CadetTConnection *ct = cls;
1685   struct CadetTunnel *t = ct->t;
1686
1687   if (GNUNET_NO == is_ready)
1688   {
1689     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1690                 "Connection %s no longer ready for tunnel %s\n",
1691                 GCC_2s (ct->cc),
1692                 GCT_2s (t));
1693     ct->is_ready = GNUNET_NO;
1694     return;
1695   }
1696   ct->is_ready = GNUNET_YES;
1697   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1698               "Connection %s now ready for tunnel %s in state %s\n",
1699               GCC_2s (ct->cc),
1700               GCT_2s (t),
1701               estate2s (t->estate));
1702   switch (t->estate)
1703   {
1704   case CADET_TUNNEL_KEY_UNINITIALIZED:
1705     send_kx (t,
1706              GNUNET_YES);
1707     break;
1708   case CADET_TUNNEL_KEY_SENT:
1709   case CADET_TUNNEL_KEY_PING:
1710     /* opportunity to #retry_kx() starts now, schedule job */
1711     if (NULL == t->kx_task)
1712     {
1713       t->kx_task
1714         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1715                                    &retry_kx,
1716                                    t);
1717     }
1718     break;
1719   case CADET_TUNNEL_KEY_OK:
1720     try_send_normal_payload (t,
1721                              ct);
1722     break;
1723   case CADET_TUNNEL_KEY_REKEY:
1724     send_kx (t,
1725              GNUNET_NO);
1726     t->estate = CADET_TUNNEL_KEY_OK;
1727     break;
1728   }
1729 }
1730
1731
1732 /**
1733  * Called when either we have a new connection, or a new message in the
1734  * queue, or some existing connection has transmission capacity.  Looks
1735  * at our message queue and if there is a message, picks a connection
1736  * to send it on.
1737  *
1738  * @param t tunnel to process messages on
1739  */
1740 static void
1741 trigger_transmissions (struct CadetTunnel *t)
1742 {
1743   struct CadetTConnection *ct;
1744
1745   if (NULL == t->tq_head)
1746     return; /* no messages pending right now */
1747   ct = get_ready_connection (t);
1748   if (NULL == ct)
1749     return; /* no connections ready */
1750   try_send_normal_payload (t,
1751                            ct);
1752 }
1753
1754
1755 /**
1756  * Consider using the path @a p for the tunnel @a t.
1757  * The tunnel destination is at offset @a off in path @a p.
1758  *
1759  * @param cls our tunnel
1760  * @param path a path to our destination
1761  * @param off offset of the destination on path @a path
1762  * @return #GNUNET_YES (should keep iterating)
1763  */
1764 static int
1765 consider_path_cb (void *cls,
1766                   struct CadetPeerPath *path,
1767                   unsigned int off)
1768 {
1769   struct CadetTunnel *t = cls;
1770   unsigned int min_length = UINT_MAX;
1771   GNUNET_CONTAINER_HeapCostType max_desire = 0;
1772   struct CadetTConnection *ct;
1773
1774   /* Check if we care about the new path. */
1775   for (ct = t->connection_head;
1776        NULL != ct;
1777        ct = ct->next)
1778   {
1779     struct CadetPeerPath *ps;
1780
1781     ps = GCC_get_path (ct->cc);
1782     if (ps == path)
1783     {
1784       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1785                   "Ignoring duplicate path %s for tunnel %s.\n",
1786                   GCPP_2s (path),
1787                   GCT_2s (t));
1788       return GNUNET_YES; /* duplicate */
1789     }
1790     min_length = GNUNET_MIN (min_length,
1791                              GCPP_get_length (ps));
1792     max_desire = GNUNET_MAX (max_desire,
1793                              GCPP_get_desirability (ps));
1794   }
1795
1796   /* FIXME: not sure we should really just count
1797      'num_connections' here, as they may all have
1798      consistently failed to connect. */
1799
1800   /* We iterate by increasing path length; if we have enough paths and
1801      this one is more than twice as long than what we are currently
1802      using, then ignore all of these super-long ones! */
1803   if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
1804        (min_length * 2 < off) )
1805   {
1806     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1807                 "Ignoring paths of length %u, they are way too long.\n",
1808                 min_length * 2);
1809     return GNUNET_NO;
1810   }
1811   /* If we have enough paths and this one looks no better, ignore it. */
1812   if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
1813        (min_length < GCPP_get_length (path)) &&
1814        (max_desire > GCPP_get_desirability (path)) )
1815   {
1816     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1817                 "Ignoring path (%u/%llu) to %s, got something better already.\n",
1818                 GCPP_get_length (path),
1819                 (unsigned long long) GCPP_get_desirability (path),
1820                 GCP_2s (t->destination));
1821     return GNUNET_YES;
1822   }
1823
1824   /* Path is interesting (better by some metric, or we don't have
1825      enough paths yet). */
1826   ct = GNUNET_new (struct CadetTConnection);
1827   ct->created = GNUNET_TIME_absolute_get ();
1828   ct->t = t;
1829   ct->cc = GCC_create (t->destination,
1830                        path,
1831                        ct,
1832                        &connection_ready_cb,
1833                        ct);
1834   /* FIXME: schedule job to kill connection (and path?)  if it takes
1835      too long to get ready! (And track performance data on how long
1836      other connections took with the tunnel!)
1837      => Note: to be done within 'connection'-logic! */
1838   GNUNET_CONTAINER_DLL_insert (t->connection_head,
1839                                t->connection_tail,
1840                                ct);
1841   t->num_connections++;
1842   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1843               "Found interesting path %s for tunnel %s, created connection %s\n",
1844               GCPP_2s (path),
1845               GCT_2s (t),
1846               GCC_2s (ct->cc));
1847   return GNUNET_YES;
1848 }
1849
1850
1851 /**
1852  * Function called to maintain the connections underlying our tunnel.
1853  * Tries to maintain (incl. tear down) connections for the tunnel, and
1854  * if there is a significant change, may trigger transmissions.
1855  *
1856  * Basically, needs to check if there are connections that perform
1857  * badly, and if so eventually kill them and trigger a replacement.
1858  * The strategy is to open one more connection than
1859  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
1860  * least-performing one, and then inquire for new ones.
1861  *
1862  * @param cls the `struct CadetTunnel`
1863  */
1864 static void
1865 maintain_connections_cb (void *cls)
1866 {
1867   struct CadetTunnel *t = cls;
1868
1869   t->maintain_connections_task = NULL;
1870   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1871               "Performing connection maintenance for tunnel %s.\n",
1872               GCT_2s (t));
1873
1874   (void) GCP_iterate_paths (t->destination,
1875                             &consider_path_cb,
1876                             t);
1877
1878   GNUNET_break (0); // FIXME: implement!
1879 }
1880
1881
1882 /**
1883  * Consider using the path @a p for the tunnel @a t.
1884  * The tunnel destination is at offset @a off in path @a p.
1885  *
1886  * @param cls our tunnel
1887  * @param path a path to our destination
1888  * @param off offset of the destination on path @a path
1889  */
1890 void
1891 GCT_consider_path (struct CadetTunnel *t,
1892                    struct CadetPeerPath *p,
1893                    unsigned int off)
1894 {
1895   (void) consider_path_cb (t,
1896                            p,
1897                            off);
1898 }
1899
1900
1901 /**
1902  * NOT IMPLEMENTED.
1903  *
1904  * @param cls the `struct CadetTunnel` for which we decrypted the message
1905  * @param msg  the message we received on the tunnel
1906  */
1907 static void
1908 handle_plaintext_keepalive (void *cls,
1909                             const struct GNUNET_MessageHeader *msg)
1910 {
1911   struct CadetTunnel *t = cls;
1912
1913   GNUNET_break (0); // FIXME
1914 }
1915
1916
1917 /**
1918  * Check that @a msg is well-formed.
1919  *
1920  * @param cls the `struct CadetTunnel` for which we decrypted the message
1921  * @param msg  the message we received on the tunnel
1922  * @return #GNUNET_OK (any variable-size payload goes)
1923  */
1924 static int
1925 check_plaintext_data (void *cls,
1926                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1927 {
1928   return GNUNET_OK;
1929 }
1930
1931
1932 /**
1933  * We received payload data for a channel.  Locate the channel
1934  * and process the data, or return an error if the channel is unknown.
1935  *
1936  * @param cls the `struct CadetTunnel` for which we decrypted the message
1937  * @param msg the message we received on the tunnel
1938  */
1939 static void
1940 handle_plaintext_data (void *cls,
1941                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
1942 {
1943   struct CadetTunnel *t = cls;
1944   struct CadetChannel *ch;
1945
1946   ch = lookup_channel (t,
1947                        msg->ctn);
1948   if (NULL == ch)
1949   {
1950     /* We don't know about such a channel, might have been destroyed on our
1951        end in the meantime, or never existed. Send back a DESTROY. */
1952     LOG (GNUNET_ERROR_TYPE_DEBUG,
1953          "Receicved %u bytes of application data for unknown channel %u, sending DESTROY\n",
1954          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
1955          ntohl (msg->ctn.cn));
1956     GCT_send_channel_destroy (t,
1957                               msg->ctn);
1958     return;
1959   }
1960   GCCH_handle_channel_plaintext_data (ch,
1961                                       msg);
1962 }
1963
1964
1965 /**
1966  * We received an acknowledgement for data we sent on a channel.
1967  * Locate the channel and process it, or return an error if the
1968  * channel is unknown.
1969  *
1970  * @param cls the `struct CadetTunnel` for which we decrypted the message
1971  * @param ack the message we received on the tunnel
1972  */
1973 static void
1974 handle_plaintext_data_ack (void *cls,
1975                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
1976 {
1977   struct CadetTunnel *t = cls;
1978   struct CadetChannel *ch;
1979
1980   ch = lookup_channel (t,
1981                        ack->ctn);
1982   if (NULL == ch)
1983   {
1984     /* We don't know about such a channel, might have been destroyed on our
1985        end in the meantime, or never existed. Send back a DESTROY. */
1986     LOG (GNUNET_ERROR_TYPE_DEBUG,
1987          "Receicved DATA_ACK for unknown channel %u, sending DESTROY\n",
1988          ntohl (ack->ctn.cn));
1989     GCT_send_channel_destroy (t,
1990                               ack->ctn);
1991     return;
1992   }
1993   GCCH_handle_channel_plaintext_data_ack (ch,
1994                                           ack);
1995 }
1996
1997
1998 /**
1999  * We have received a request to open a channel to a port from
2000  * another peer.  Creates the incoming channel.
2001  *
2002  * @param cls the `struct CadetTunnel` for which we decrypted the message
2003  * @param cc the message we received on the tunnel
2004  */
2005 static void
2006 handle_plaintext_channel_open (void *cls,
2007                                const struct GNUNET_CADET_ChannelOpenMessage *cc)
2008 {
2009   struct CadetTunnel *t = cls;
2010   struct CadetChannel *ch;
2011   struct GNUNET_CADET_ChannelTunnelNumber ctn;
2012
2013   LOG (GNUNET_ERROR_TYPE_DEBUG,
2014        "Receicved channel OPEN on port %s from peer %s\n",
2015        GNUNET_h2s (&cc->port),
2016        GCP_2s (GCT_get_destination (t)));
2017   ctn = get_next_free_ctn (t);
2018   ch = GCCH_channel_incoming_new (t,
2019                                   ctn,
2020                                   &cc->port,
2021                                   ntohl (cc->opt));
2022   GNUNET_assert (GNUNET_OK ==
2023                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2024                                                       ntohl (ctn.cn),
2025                                                       ch,
2026                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2027 }
2028
2029
2030 /**
2031  * Send a DESTROY message via the tunnel.
2032  *
2033  * @param t the tunnel to transmit over
2034  * @param ctn ID of the channel to destroy
2035  */
2036 void
2037 GCT_send_channel_destroy (struct CadetTunnel *t,
2038                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
2039 {
2040   struct GNUNET_CADET_ChannelManageMessage msg;
2041
2042   LOG (GNUNET_ERROR_TYPE_DEBUG,
2043        "Sending DESTORY message for channel ID %u\n",
2044        ntohl (ctn.cn));
2045   msg.header.size = htons (sizeof (msg));
2046   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2047   msg.reserved = htonl (0);
2048   msg.ctn = ctn;
2049   GCT_send (t,
2050             &msg.header,
2051             NULL,
2052             NULL);
2053 }
2054
2055
2056 /**
2057  * We have received confirmation from the target peer that the
2058  * given channel could be established (the port is open).
2059  * Tell the client.
2060  *
2061  * @param cls the `struct CadetTunnel` for which we decrypted the message
2062  * @param cm the message we received on the tunnel
2063  */
2064 static void
2065 handle_plaintext_channel_open_ack (void *cls,
2066                                    const struct GNUNET_CADET_ChannelManageMessage *cm)
2067 {
2068   struct CadetTunnel *t = cls;
2069   struct CadetChannel *ch;
2070
2071   ch = lookup_channel (t,
2072                        cm->ctn);
2073   if (NULL == ch)
2074   {
2075     /* We don't know about such a channel, might have been destroyed on our
2076        end in the meantime, or never existed. Send back a DESTROY. */
2077     LOG (GNUNET_ERROR_TYPE_DEBUG,
2078          "Received channel OPEN_ACK for unknown channel, sending DESTROY\n",
2079          GCCH_2s (ch));
2080     GCT_send_channel_destroy (t,
2081                               cm->ctn);
2082     return;
2083   }
2084   GCCH_handle_channel_open_ack (ch);
2085 }
2086
2087
2088 /**
2089  * We received a message saying that a channel should be destroyed.
2090  * Pass it on to the correct channel.
2091  *
2092  * @param cls the `struct CadetTunnel` for which we decrypted the message
2093  * @param cm the message we received on the tunnel
2094  */
2095 static void
2096 handle_plaintext_channel_destroy (void *cls,
2097                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
2098 {
2099   struct CadetTunnel *t = cls;
2100   struct CadetChannel *ch;
2101
2102   ch = lookup_channel (t,
2103                        cm->ctn);
2104   if (NULL == ch)
2105   {
2106     /* We don't know about such a channel, might have been destroyed on our
2107        end in the meantime, or never existed. */
2108     LOG (GNUNET_ERROR_TYPE_DEBUG,
2109          "Received channel DESTORY for unknown channel. Ignoring.\n",
2110          GCCH_2s (ch));
2111     return;
2112   }
2113   GCCH_handle_remote_destroy (ch);
2114 }
2115
2116
2117 /**
2118  * Handles a message we decrypted, by injecting it into
2119  * our message queue (which will do the dispatching).
2120  *
2121  * @param cls the `struct CadetTunnel` that got the message
2122  * @param msg the message
2123  * @return #GNUNET_OK (continue to process)
2124  */
2125 static int
2126 handle_decrypted (void *cls,
2127                   const struct GNUNET_MessageHeader *msg)
2128 {
2129   struct CadetTunnel *t = cls;
2130
2131   GNUNET_MQ_inject_message (t->mq,
2132                             msg);
2133   return GNUNET_OK;
2134 }
2135
2136
2137 /**
2138  * Function called if we had an error processing
2139  * an incoming decrypted message.
2140  *
2141  * @param cls the `struct CadetTunnel`
2142  * @param error error code
2143  */
2144 static void
2145 decrypted_error_cb (void *cls,
2146                     enum GNUNET_MQ_Error error)
2147 {
2148   GNUNET_break_op (0);
2149 }
2150
2151
2152 /**
2153  * Create a tunnel to @a destionation.  Must only be called
2154  * from within #GCP_get_tunnel().
2155  *
2156  * @param destination where to create the tunnel to
2157  * @return new tunnel to @a destination
2158  */
2159 struct CadetTunnel *
2160 GCT_create_tunnel (struct CadetPeer *destination)
2161 {
2162   struct GNUNET_MQ_MessageHandler handlers[] = {
2163     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2164                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2165                              struct GNUNET_MessageHeader,
2166                              NULL),
2167     GNUNET_MQ_hd_var_size (plaintext_data,
2168                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2169                            struct GNUNET_CADET_ChannelAppDataMessage,
2170                            NULL),
2171     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2172                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2173                              struct GNUNET_CADET_ChannelDataAckMessage,
2174                              NULL),
2175     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2176                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2177                              struct GNUNET_CADET_ChannelOpenMessage,
2178                              NULL),
2179     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2180                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2181                              struct GNUNET_CADET_ChannelManageMessage,
2182                              NULL),
2183     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2184                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2185                              struct GNUNET_CADET_ChannelManageMessage,
2186                              NULL),
2187     GNUNET_MQ_handler_end ()
2188   };
2189   struct CadetTunnel *t;
2190
2191   t = GNUNET_new (struct CadetTunnel);
2192   new_ephemeral (t);
2193   t->ax.kx_0 = GNUNET_CRYPTO_ecdhe_key_create ();
2194   t->destination = destination;
2195   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2196   t->maintain_connections_task
2197     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2198                                 t);
2199   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2200                                          NULL,
2201                                          NULL,
2202                                          NULL,
2203                                          handlers,
2204                                          &decrypted_error_cb,
2205                                          t);
2206   t->mst = GNUNET_MST_create (&handle_decrypted,
2207                               t);
2208   return t;
2209 }
2210
2211
2212 /**
2213  * Add a @a connection to the @a tunnel.
2214  *
2215  * @param t a tunnel
2216  * @param cid connection identifer to use for the connection
2217  * @param path path to use for the connection
2218  */
2219 void
2220 GCT_add_inbound_connection (struct CadetTunnel *t,
2221                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2222                             struct CadetPeerPath *path)
2223 {
2224   struct CadetTConnection *ct;
2225
2226   ct = GNUNET_new (struct CadetTConnection);
2227   ct->created = GNUNET_TIME_absolute_get ();
2228   ct->t = t;
2229   ct->cc = GCC_create_inbound (t->destination,
2230                                path,
2231                                ct,
2232                                cid,
2233                                &connection_ready_cb,
2234                                t);
2235   /* FIXME: schedule job to kill connection (and path?)  if it takes
2236      too long to get ready! (And track performance data on how long
2237      other connections took with the tunnel!)
2238      => Note: to be done within 'connection'-logic! */
2239   GNUNET_CONTAINER_DLL_insert (t->connection_head,
2240                                t->connection_tail,
2241                                ct);
2242   t->num_connections++;
2243   LOG (GNUNET_ERROR_TYPE_DEBUG,
2244        "Tunnel %s has new connection %s\n",
2245        GCT_2s (t),
2246        GCC_2s (ct->cc));
2247 }
2248
2249
2250 /**
2251  * Handle encrypted message.
2252  *
2253  * @param ct connection/tunnel combo that received encrypted message
2254  * @param msg the encrypted message to decrypt
2255  */
2256 void
2257 GCT_handle_encrypted (struct CadetTConnection *ct,
2258                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2259 {
2260   struct CadetTunnel *t = ct->t;
2261   uint16_t size = ntohs (msg->header.size);
2262   char cbuf [size] GNUNET_ALIGN;
2263   ssize_t decrypted_size;
2264
2265   LOG (GNUNET_ERROR_TYPE_DEBUG,
2266        "Tunnel %s received %u bytes of encrypted data in state %d\n",
2267        GCT_2s (t),
2268        (unsigned int) size,
2269        t->estate);
2270
2271   switch (t->estate)
2272   {
2273   case CADET_TUNNEL_KEY_UNINITIALIZED:
2274     /* We did not even SEND our KX, how can the other peer
2275        send us encrypted data? */
2276     GNUNET_break_op (0);
2277     return;
2278   case CADET_TUNNEL_KEY_SENT:
2279     /* We did not get the KX of the other peer, but that
2280        might have been lost.  Ask for KX again. */
2281     GNUNET_STATISTICS_update (stats,
2282                               "# received encrypted without KX",
2283                               1,
2284                               GNUNET_NO);
2285     if (NULL != t->kx_task)
2286       GNUNET_SCHEDULER_cancel (t->kx_task);
2287     t->kx_task = GNUNET_SCHEDULER_add_now (&retry_kx,
2288                                            t);
2289     return;
2290   case CADET_TUNNEL_KEY_PING:
2291     /* Great, first payload, we might graduate to OK */
2292   case CADET_TUNNEL_KEY_OK:
2293   case CADET_TUNNEL_KEY_REKEY:
2294     break;
2295   }
2296
2297   GNUNET_STATISTICS_update (stats,
2298                             "# received encrypted",
2299                             1,
2300                             GNUNET_NO);
2301   decrypted_size = t_ax_decrypt_and_validate (t,
2302                                               cbuf,
2303                                               msg,
2304                                               size);
2305
2306   if (-1 == decrypted_size)
2307   {
2308     GNUNET_break_op (0);
2309     LOG (GNUNET_ERROR_TYPE_WARNING,
2310          "Tunnel %s failed to decrypt and validate encrypted data\n",
2311          GCT_2s (t));
2312     GNUNET_STATISTICS_update (stats,
2313                               "# unable to decrypt",
2314                               1,
2315                               GNUNET_NO);
2316     return;
2317   }
2318   if (CADET_TUNNEL_KEY_PING == t->estate)
2319   {
2320     GCT_change_estate (t,
2321                        CADET_TUNNEL_KEY_OK);
2322     trigger_transmissions (t);
2323   }
2324   /* The MST will ultimately call #handle_decrypted() on each message. */
2325   GNUNET_break_op (GNUNET_OK ==
2326                    GNUNET_MST_from_buffer (t->mst,
2327                                            cbuf,
2328                                            decrypted_size,
2329                                            GNUNET_YES,
2330                                            GNUNET_NO));
2331 }
2332
2333
2334 /**
2335  * Sends an already built message on a tunnel, encrypting it and
2336  * choosing the best connection if not provided.
2337  *
2338  * @param message Message to send. Function modifies it.
2339  * @param t Tunnel on which this message is transmitted.
2340  * @param cont Continuation to call once message is really sent.
2341  * @param cont_cls Closure for @c cont.
2342  * @return Handle to cancel message. NULL if @c cont is NULL.
2343  */
2344 struct CadetTunnelQueueEntry *
2345 GCT_send (struct CadetTunnel *t,
2346           const struct GNUNET_MessageHeader *message,
2347           GNUNET_SCHEDULER_TaskCallback cont,
2348           void *cont_cls)
2349 {
2350   struct CadetTunnelQueueEntry *tq;
2351   uint16_t payload_size;
2352   struct GNUNET_MQ_Envelope *env;
2353   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
2354
2355   payload_size = ntohs (message->size);
2356   LOG (GNUNET_ERROR_TYPE_DEBUG,
2357        "Encrypting %u bytes of for tunnel %s\n",
2358        (unsigned int) payload_size,
2359        GCT_2s (t));
2360   env = GNUNET_MQ_msg_extra (ax_msg,
2361                              payload_size,
2362                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
2363   t_ax_encrypt (t,
2364                 &ax_msg[1],
2365                 message,
2366                 payload_size);
2367   ax_msg->Ns = htonl (t->ax.Ns++);
2368   ax_msg->PNs = htonl (t->ax.PNs);
2369   GNUNET_CRYPTO_ecdhe_key_get_public (t->ax.DHRs,
2370                                       &ax_msg->DHRs);
2371   t_h_encrypt (t,
2372                ax_msg);
2373   t_hmac (&ax_msg->Ns,
2374           AX_HEADER_SIZE + payload_size,
2375           0,
2376           &t->ax.HKs,
2377           &ax_msg->hmac);
2378
2379   tq = GNUNET_malloc (sizeof (*tq));
2380   tq->t = t;
2381   tq->env = env;
2382   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
2383   tq->cont = cont;
2384   tq->cont_cls = cont_cls;
2385   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
2386                                     t->tq_tail,
2387                                     tq);
2388   trigger_transmissions (t);
2389   return tq;
2390 }
2391
2392
2393 /**
2394  * Cancel a previously sent message while it's in the queue.
2395  *
2396  * ONLY can be called before the continuation given to the send
2397  * function is called. Once the continuation is called, the message is
2398  * no longer in the queue!
2399  *
2400  * @param tq Handle to the queue entry to cancel.
2401  */
2402 void
2403 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
2404 {
2405   struct CadetTunnel *t = tq->t;
2406
2407   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2408                                t->tq_tail,
2409                                tq);
2410   GNUNET_MQ_discard (tq->env);
2411   GNUNET_free (tq);
2412 }
2413
2414
2415 /**
2416  * Iterate over all connections of a tunnel.
2417  *
2418  * @param t Tunnel whose connections to iterate.
2419  * @param iter Iterator.
2420  * @param iter_cls Closure for @c iter.
2421  */
2422 void
2423 GCT_iterate_connections (struct CadetTunnel *t,
2424                          GCT_ConnectionIterator iter,
2425                          void *iter_cls)
2426 {
2427   for (struct CadetTConnection *ct = t->connection_head;
2428        NULL != ct;
2429        ct = ct->next)
2430     iter (iter_cls,
2431           ct->cc);
2432 }
2433
2434
2435 /**
2436  * Closure for #iterate_channels_cb.
2437  */
2438 struct ChanIterCls
2439 {
2440   /**
2441    * Function to call.
2442    */
2443   GCT_ChannelIterator iter;
2444
2445   /**
2446    * Closure for @e iter.
2447    */
2448   void *iter_cls;
2449 };
2450
2451
2452 /**
2453  * Helper function for #GCT_iterate_channels.
2454  *
2455  * @param cls the `struct ChanIterCls`
2456  * @param key unused
2457  * @param value a `struct CadetChannel`
2458  * @return #GNUNET_OK
2459  */
2460 static int
2461 iterate_channels_cb (void *cls,
2462                      uint32_t key,
2463                      void *value)
2464 {
2465   struct ChanIterCls *ctx = cls;
2466   struct CadetChannel *ch = value;
2467
2468   ctx->iter (ctx->iter_cls,
2469              ch);
2470   return GNUNET_OK;
2471 }
2472
2473
2474 /**
2475  * Iterate over all channels of a tunnel.
2476  *
2477  * @param t Tunnel whose channels to iterate.
2478  * @param iter Iterator.
2479  * @param iter_cls Closure for @c iter.
2480  */
2481 void
2482 GCT_iterate_channels (struct CadetTunnel *t,
2483                       GCT_ChannelIterator iter,
2484                       void *iter_cls)
2485 {
2486   struct ChanIterCls ctx;
2487
2488   ctx.iter = iter;
2489   ctx.iter_cls = iter_cls;
2490   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2491                                            &iterate_channels_cb,
2492                                            &ctx);
2493
2494 }
2495
2496
2497 /**
2498  * Call #GCCH_debug() on a channel.
2499  *
2500  * @param cls points to the log level to use
2501  * @param key unused
2502  * @param value the `struct CadetChannel` to dump
2503  * @return #GNUNET_OK (continue iteration)
2504  */
2505 static int
2506 debug_channel (void *cls,
2507                uint32_t key,
2508                void *value)
2509 {
2510   const enum GNUNET_ErrorType *level = cls;
2511   struct CadetChannel *ch = value;
2512
2513   GCCH_debug (ch, *level);
2514   return GNUNET_OK;
2515 }
2516
2517
2518 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
2519
2520
2521 /**
2522  * Log all possible info about the tunnel state.
2523  *
2524  * @param t Tunnel to debug.
2525  * @param level Debug level to use.
2526  */
2527 void
2528 GCT_debug (const struct CadetTunnel *t,
2529            enum GNUNET_ErrorType level)
2530 {
2531   struct CadetTConnection *iter_c;
2532   int do_log;
2533
2534   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
2535                                        "cadet-tun",
2536                                        __FILE__, __FUNCTION__, __LINE__);
2537   if (0 == do_log)
2538     return;
2539
2540   LOG2 (level,
2541         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
2542         GCT_2s (t),
2543         estate2s (t->estate),
2544         t->tq_len,
2545         t->num_connections);
2546 #if DUMP_KEYS_TO_STDERR
2547   ax_debug (t->ax, level);
2548 #endif
2549   LOG2 (level,
2550         "TTT channels:\n");
2551   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2552                                            &debug_channel,
2553                                            &level);
2554   LOG2 (level,
2555         "TTT connections:\n");
2556   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
2557     GCC_debug (iter_c->cc,
2558                level);
2559
2560   LOG2 (level,
2561         "TTT TUNNEL END\n");
2562 }
2563
2564
2565 /* end of gnunet-service-cadet-new_tunnels.c */