also do send_kx if we fail to decrypt
[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  * - proper connection evaluation during connection management:
28  *   + consider quality (or quality spread?) of current connection set
29  *     when deciding how often to do maintenance
30  *   + interact with PEER to drive DHT GET/PUT operations based
31  *     on how much we like our connections
32  */
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_statistics_service.h"
36 #include "gnunet_signatures.h"
37 #include "gnunet-service-cadet-new.h"
38 #include "cadet_protocol.h"
39 #include "gnunet-service-cadet-new_channel.h"
40 #include "gnunet-service-cadet-new_connection.h"
41 #include "gnunet-service-cadet-new_tunnels.h"
42 #include "gnunet-service-cadet-new_peer.h"
43 #include "gnunet-service-cadet-new_paths.h"
44
45
46 #define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__)
47
48 /**
49  * How often do we try to decrypt payload with unverified key
50  * material?  Used to limit CPU increase upon receiving bogus
51  * KX.
52  */
53 #define MAX_UNVERIFIED_ATTEMPTS 16
54
55 /**
56  * How long do we wait until tearing down an idle tunnel?
57  */
58 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
59
60 /**
61  * How long do we wait initially before retransmitting the KX?
62  * TODO: replace by 2 RTT if/once we have connection-level RTT data!
63  */
64 #define INITIAL_KX_RETRY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
65
66 /**
67  * Maximum number of skipped keys we keep in memory per tunnel.
68  */
69 #define MAX_SKIPPED_KEYS 64
70
71 /**
72  * Maximum number of keys (and thus ratchet steps) we are willing to
73  * skip before we decide this is either a bogus packet or a DoS-attempt.
74  */
75 #define MAX_KEY_GAP 256
76
77
78 /**
79  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
80  */
81 struct CadetTunnelSkippedKey
82 {
83   /**
84    * DLL next.
85    */
86   struct CadetTunnelSkippedKey *next;
87
88   /**
89    * DLL prev.
90    */
91   struct CadetTunnelSkippedKey *prev;
92
93   /**
94    * When was this key stored (for timeout).
95    */
96   struct GNUNET_TIME_Absolute timestamp;
97
98   /**
99    * Header key.
100    */
101   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
102
103   /**
104    * Message key.
105    */
106   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
107
108   /**
109    * Key number for a given HK.
110    */
111   unsigned int Kn;
112 };
113
114
115 /**
116  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
117  */
118 struct CadetTunnelAxolotl
119 {
120   /**
121    * A (double linked) list of stored message keys and associated header keys
122    * for "skipped" messages, i.e. messages that have not been
123    * received despite the reception of more recent messages, (head).
124    */
125   struct CadetTunnelSkippedKey *skipped_head;
126
127   /**
128    * Skipped messages' keys DLL, tail.
129    */
130   struct CadetTunnelSkippedKey *skipped_tail;
131
132   /**
133    * 32-byte root key which gets updated by DH ratchet.
134    */
135   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
136
137   /**
138    * 32-byte header key (currently used for sending).
139    */
140   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
141
142   /**
143    * 32-byte header key (currently used for receiving)
144    */
145   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
146
147   /**
148    * 32-byte next header key (for sending), used once the
149    * ratchet advances.  We are sure that the sender has this
150    * key as well only after @e ratchet_allowed is #GNUNET_YES.
151    */
152   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
153
154   /**
155    * 32-byte next header key (for receiving).  To be tried
156    * when decrypting with @e HKr fails and thus the sender
157    * may have advanced the ratchet.
158    */
159   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
160
161   /**
162    * 32-byte chain keys (used for forward-secrecy) for
163    * sending messages. Updated for every message.
164    */
165   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
166
167   /**
168    * 32-byte chain keys (used for forward-secrecy) for
169    * receiving messages. Updated for every message. If
170    * messages are skipped, the respective derived MKs
171    * (and the current @HKr) are kept in the @e skipped_head DLL.
172    */
173   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
174
175   /**
176    * ECDH for key exchange (A0 / B0).
177    */
178   struct GNUNET_CRYPTO_EcdhePrivateKey kx_0;
179
180   /**
181    * ECDH Ratchet key (our private key in the current DH).
182    */
183   struct GNUNET_CRYPTO_EcdhePrivateKey DHRs;
184
185   /**
186    * ECDH Ratchet key (other peer's public key in the current DH).
187    */
188   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
189
190   /**
191    * Time when the current ratchet expires and a new one is triggered
192    * (if @e ratchet_allowed is #GNUNET_YES).
193    */
194   struct GNUNET_TIME_Absolute ratchet_expiration;
195
196   /**
197    * Number of elements in @a skipped_head <-> @a skipped_tail.
198    */
199   unsigned int skipped;
200
201   /**
202    * Message number (reset to 0 with each new ratchet, next message to send).
203    */
204   uint32_t Ns;
205
206   /**
207    * Message number (reset to 0 with each new ratchet, next message to recv).
208    */
209   uint32_t Nr;
210
211   /**
212    * Previous message numbers (# of msgs sent under prev ratchet)
213    */
214   uint32_t PNs;
215
216   /**
217    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
218    */
219   int ratchet_flag;
220
221   /**
222    * True (#GNUNET_YES) if we have received a message from the
223    * other peer that uses the keys from our last ratchet step.
224    * This implies that we are again allowed to advance the ratchet,
225    * otherwise we have to wait until the other peer sees our current
226    * ephemeral key and advances first.
227    *
228    * #GNUNET_NO if we have advanced the ratched but lack any evidence
229    * that the other peer has noticed this.
230    */
231   int ratchet_allowed;
232
233   /**
234    * Number of messages recieved since our last ratchet advance.
235    *
236    * If this counter = 0, we cannot send a new ratchet key in the next
237    * message.
238    *
239    * If this counter > 0, we could (but don't have to) send a new key.
240    *
241    * Once the @e ratchet_counter is larger than
242    * #ratchet_messages (or @e ratchet_expiration time has past), and
243    * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet.
244    */
245   unsigned int ratchet_counter;
246
247 };
248
249
250 /**
251  * Struct used to save messages in a non-ready tunnel to send once connected.
252  */
253 struct CadetTunnelQueueEntry
254 {
255   /**
256    * We are entries in a DLL
257    */
258   struct CadetTunnelQueueEntry *next;
259
260   /**
261    * We are entries in a DLL
262    */
263   struct CadetTunnelQueueEntry *prev;
264
265   /**
266    * Tunnel these messages belong in.
267    */
268   struct CadetTunnel *t;
269
270   /**
271    * Continuation to call once sent (on the channel layer).
272    */
273   GCT_SendContinuation cont;
274
275   /**
276    * Closure for @c cont.
277    */
278   void *cont_cls;
279
280   /**
281    * Envelope of message to send follows.
282    */
283   struct GNUNET_MQ_Envelope *env;
284
285   /**
286    * Where to put the connection identifier into the payload
287    * of the message in @e env once we have it?
288    */
289   struct GNUNET_CADET_ConnectionTunnelIdentifier *cid;
290 };
291
292
293 /**
294  * Struct containing all information regarding a tunnel to a peer.
295  */
296 struct CadetTunnel
297 {
298   /**
299    * Destination of the tunnel.
300    */
301   struct CadetPeer *destination;
302
303   /**
304    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
305    * ephemeral key changes.
306    */
307   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
308
309   /**
310    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
311    */
312   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
313
314   /**
315    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
316    */
317   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
318
319   /**
320    * Axolotl info.
321    */
322   struct CadetTunnelAxolotl ax;
323
324   /**
325    * Unverified Axolotl info, used only if we got a fresh KX (not a
326    * KX_AUTH) while our end of the tunnel was still up.  In this case,
327    * we keep the fresh KX around but do not put it into action until
328    * we got encrypted payload that assures us of the authenticity of
329    * the KX.
330    */
331   struct CadetTunnelAxolotl *unverified_ax;
332
333   /**
334    * Task scheduled if there are no more channels using the tunnel.
335    */
336   struct GNUNET_SCHEDULER_Task *destroy_task;
337
338   /**
339    * Task to trim connections if too many are present.
340    */
341   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
342
343   /**
344    * Task to send messages from queue (if possible).
345    */
346   struct GNUNET_SCHEDULER_Task *send_task;
347
348   /**
349    * Task to trigger KX.
350    */
351   struct GNUNET_SCHEDULER_Task *kx_task;
352
353   /**
354    * Tokenizer for decrypted messages.
355    */
356   struct GNUNET_MessageStreamTokenizer *mst;
357
358   /**
359    * Dispatcher for decrypted messages only (do NOT use for sending!).
360    */
361   struct GNUNET_MQ_Handle *mq;
362
363   /**
364    * DLL of ready connections that are actively used to reach the destination peer.
365    */
366   struct CadetTConnection *connection_ready_head;
367
368   /**
369    * DLL of ready connections that are actively used to reach the destination peer.
370    */
371   struct CadetTConnection *connection_ready_tail;
372
373   /**
374    * DLL of connections that we maintain that might be used to reach the destination peer.
375    */
376   struct CadetTConnection *connection_busy_head;
377
378   /**
379    * DLL of connections that we maintain that might be used to reach the destination peer.
380    */
381   struct CadetTConnection *connection_busy_tail;
382
383   /**
384    * Channels inside this tunnel. Maps
385    * `struct GNUNET_CADET_ChannelTunnelNumber` to a `struct CadetChannel`.
386    */
387   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
388
389   /**
390    * Channel ID for the next created channel in this tunnel.
391    */
392   struct GNUNET_CADET_ChannelTunnelNumber next_ctn;
393
394   /**
395    * Queued messages, to transmit once tunnel gets connected.
396    */
397   struct CadetTunnelQueueEntry *tq_head;
398
399   /**
400    * Queued messages, to transmit once tunnel gets connected.
401    */
402   struct CadetTunnelQueueEntry *tq_tail;
403
404   /**
405    * Identification of the connection from which we are currently processing
406    * a message. Only valid (non-NULL) during #handle_decrypted() and the
407    * handle-*()-functions called from our @e mq during that function.
408    */
409   struct CadetTConnection *current_ct;
410
411   /**
412    * How long do we wait until we retry the KX?
413    */
414   struct GNUNET_TIME_Relative kx_retry_delay;
415
416   /**
417    * When do we try the next KX?
418    */
419   struct GNUNET_TIME_Absolute next_kx_attempt;
420
421   /**
422    * Number of connections in the @e connection_ready_head DLL.
423    */
424   unsigned int num_ready_connections;
425
426   /**
427    * Number of connections in the @e connection_busy_head DLL.
428    */
429   unsigned int num_busy_connections;
430
431   /**
432    * How often have we tried and failed to decrypt a message using
433    * the unverified KX material from @e unverified_ax?  Used to
434    * stop trying after #MAX_UNVERIFIED_ATTEMPTS.
435    */
436   unsigned int unverified_attempts;
437
438   /**
439    * Number of entries in the @e tq_head DLL.
440    */
441   unsigned int tq_len;
442
443   /**
444    * State of the tunnel encryption.
445    */
446   enum CadetTunnelEState estate;
447
448   /**
449    * Force triggering KX_AUTH independent of @e estate.
450    */
451   int kx_auth_requested;
452
453 };
454
455
456 /**
457  * Connection @a ct is now unready, clear it's ready flag
458  * and move it from the ready DLL to the busy DLL.
459  *
460  * @param ct connection to move to unready status
461  */
462 static void
463 mark_connection_unready (struct CadetTConnection *ct)
464 {
465   struct CadetTunnel *t = ct->t;
466
467   GNUNET_assert (GNUNET_YES == ct->is_ready);
468   GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
469                                t->connection_ready_tail,
470                                ct);
471   GNUNET_assert (0 < t->num_ready_connections);
472   t->num_ready_connections--;
473   ct->is_ready = GNUNET_NO;
474   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
475                                t->connection_busy_tail,
476                                ct);
477   t->num_busy_connections++;
478 }
479
480
481 /**
482  * Get the static string for the peer this tunnel is directed.
483  *
484  * @param t Tunnel.
485  *
486  * @return Static string the destination peer's ID.
487  */
488 const char *
489 GCT_2s (const struct CadetTunnel *t)
490 {
491   static char buf[64];
492
493   if (NULL == t)
494     return "Tunnel(NULL)";
495   GNUNET_snprintf (buf,
496                    sizeof (buf),
497                    "Tunnel %s",
498                    GNUNET_i2s (GCP_get_id (t->destination)));
499   return buf;
500 }
501
502
503 /**
504  * Get string description for tunnel encryption state.
505  *
506  * @param es Tunnel state.
507  *
508  * @return String representation.
509  */
510 static const char *
511 estate2s (enum CadetTunnelEState es)
512 {
513   static char buf[32];
514
515   switch (es)
516   {
517   case CADET_TUNNEL_KEY_UNINITIALIZED:
518     return "CADET_TUNNEL_KEY_UNINITIALIZED";
519   case CADET_TUNNEL_KEY_AX_RECV:
520     return "CADET_TUNNEL_KEY_AX_RECV";
521   case CADET_TUNNEL_KEY_AX_SENT:
522     return "CADET_TUNNEL_KEY_AX_SENT";
523   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
524     return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV";
525   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
526     return "CADET_TUNNEL_KEY_AX_AUTH_SENT";
527   case CADET_TUNNEL_KEY_OK:
528     return "CADET_TUNNEL_KEY_OK";
529   default:
530     GNUNET_snprintf (buf,
531                      sizeof (buf),
532                      "%u (UNKNOWN STATE)",
533                      es);
534     return buf;
535   }
536 }
537
538
539 /**
540  * Return the peer to which this tunnel goes.
541  *
542  * @param t a tunnel
543  * @return the destination of the tunnel
544  */
545 struct CadetPeer *
546 GCT_get_destination (struct CadetTunnel *t)
547 {
548   return t->destination;
549 }
550
551
552 /**
553  * Count channels of a tunnel.
554  *
555  * @param t Tunnel on which to count.
556  *
557  * @return Number of channels.
558  */
559 unsigned int
560 GCT_count_channels (struct CadetTunnel *t)
561 {
562   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
563 }
564
565
566 /**
567  * Lookup a channel by its @a ctn.
568  *
569  * @param t tunnel to look in
570  * @param ctn number of channel to find
571  * @return NULL if channel does not exist
572  */
573 struct CadetChannel *
574 lookup_channel (struct CadetTunnel *t,
575                 struct GNUNET_CADET_ChannelTunnelNumber ctn)
576 {
577   return GNUNET_CONTAINER_multihashmap32_get (t->channels,
578                                               ntohl (ctn.cn));
579 }
580
581
582 /**
583  * Count all created connections of a tunnel. Not necessarily ready connections!
584  *
585  * @param t Tunnel on which to count.
586  *
587  * @return Number of connections created, either being established or ready.
588  */
589 unsigned int
590 GCT_count_any_connections (const struct CadetTunnel *t)
591 {
592   return t->num_ready_connections + t->num_busy_connections;
593 }
594
595
596 /**
597  * Find first connection that is ready in the list of
598  * our connections.  Picks ready connections round-robin.
599  *
600  * @param t tunnel to search
601  * @return NULL if we have no connection that is ready
602  */
603 static struct CadetTConnection *
604 get_ready_connection (struct CadetTunnel *t)
605 {
606   return t->connection_ready_head;
607 }
608
609
610 /**
611  * Get the encryption state of a tunnel.
612  *
613  * @param t Tunnel.
614  *
615  * @return Tunnel's encryption state.
616  */
617 enum CadetTunnelEState
618 GCT_get_estate (struct CadetTunnel *t)
619 {
620   return t->estate;
621 }
622
623
624 /**
625  * Called when either we have a new connection, or a new message in the
626  * queue, or some existing connection has transmission capacity.  Looks
627  * at our message queue and if there is a message, picks a connection
628  * to send it on.
629  *
630  * @param cls the `struct CadetTunnel` to process messages on
631  */
632 static void
633 trigger_transmissions (void *cls);
634
635
636 /* ************************************** start core crypto ***************************** */
637
638
639 /**
640  * Create a new Axolotl ephemeral (ratchet) key.
641  *
642  * @param ax key material to update
643  */
644 static void
645 new_ephemeral (struct CadetTunnelAxolotl *ax)
646 {
647   LOG (GNUNET_ERROR_TYPE_DEBUG,
648        "Creating new ephemeral ratchet key (DHRs)\n");
649   GNUNET_assert (GNUNET_OK ==
650                  GNUNET_CRYPTO_ecdhe_key_create2 (&ax->DHRs));
651 }
652
653
654 /**
655  * Calculate HMAC.
656  *
657  * @param plaintext Content to HMAC.
658  * @param size Size of @c plaintext.
659  * @param iv Initialization vector for the message.
660  * @param key Key to use.
661  * @param hmac[out] Destination to store the HMAC.
662  */
663 static void
664 t_hmac (const void *plaintext,
665         size_t size,
666         uint32_t iv,
667         const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
668         struct GNUNET_ShortHashCode *hmac)
669 {
670   static const char ctx[] = "cadet authentication key";
671   struct GNUNET_CRYPTO_AuthKey auth_key;
672   struct GNUNET_HashCode hash;
673
674   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
675                                  key,
676                                  &iv, sizeof (iv),
677                                  key, sizeof (*key),
678                                  ctx, sizeof (ctx),
679                                  NULL);
680   /* Two step: GNUNET_ShortHash is only 256 bits,
681      GNUNET_HashCode is 512, so we truncate. */
682   GNUNET_CRYPTO_hmac (&auth_key,
683                       plaintext,
684                       size,
685                       &hash);
686   GNUNET_memcpy (hmac,
687                  &hash,
688                  sizeof (*hmac));
689 }
690
691
692 /**
693  * Perform a HMAC.
694  *
695  * @param key Key to use.
696  * @param[out] hash Resulting HMAC.
697  * @param source Source key material (data to HMAC).
698  * @param len Length of @a source.
699  */
700 static void
701 t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
702                 struct GNUNET_HashCode *hash,
703                 const void *source,
704                 unsigned int len)
705 {
706   static const char ctx[] = "axolotl HMAC-HASH";
707   struct GNUNET_CRYPTO_AuthKey auth_key;
708
709   GNUNET_CRYPTO_hmac_derive_key (&auth_key,
710                                  key,
711                                  ctx, sizeof (ctx),
712                                  NULL);
713   GNUNET_CRYPTO_hmac (&auth_key,
714                       source,
715                       len,
716                       hash);
717 }
718
719
720 /**
721  * Derive a symmetric encryption key from an HMAC-HASH.
722  *
723  * @param key Key to use for the HMAC.
724  * @param[out] out Key to generate.
725  * @param source Source key material (data to HMAC).
726  * @param len Length of @a source.
727  */
728 static void
729 t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key,
730                    struct GNUNET_CRYPTO_SymmetricSessionKey *out,
731                    const void *source,
732                    unsigned int len)
733 {
734   static const char ctx[] = "axolotl derive key";
735   struct GNUNET_HashCode h;
736
737   t_ax_hmac_hash (key,
738                   &h,
739                   source,
740                   len);
741   GNUNET_CRYPTO_kdf (out, sizeof (*out),
742                      ctx, sizeof (ctx),
743                      &h, sizeof (h),
744                      NULL);
745 }
746
747
748 /**
749  * Encrypt data with the axolotl tunnel key.
750  *
751  * @param ax key material to use.
752  * @param dst Destination with @a size bytes for the encrypted data.
753  * @param src Source of the plaintext. Can overlap with @c dst, must contain @a size bytes
754  * @param size Size of the buffers at @a src and @a dst
755  */
756 static void
757 t_ax_encrypt (struct CadetTunnelAxolotl *ax,
758               void *dst,
759               const void *src,
760               size_t size)
761 {
762   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
763   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
764   size_t out_size;
765
766   ax->ratchet_counter++;
767   if ( (GNUNET_YES == ax->ratchet_allowed) &&
768        ( (ratchet_messages <= ax->ratchet_counter) ||
769          (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) )
770   {
771     ax->ratchet_flag = GNUNET_YES;
772   }
773   if (GNUNET_YES == ax->ratchet_flag)
774   {
775     /* Advance ratchet */
776     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3];
777     struct GNUNET_HashCode dh;
778     struct GNUNET_HashCode hmac;
779     static const char ctx[] = "axolotl ratchet";
780
781     new_ephemeral (ax);
782     ax->HKs = ax->NHKs;
783
784     /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */
785     GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
786                             &ax->DHRr,
787                             &dh);
788     t_ax_hmac_hash (&ax->RK,
789                     &hmac,
790                     &dh,
791                     sizeof (dh));
792     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
793                        ctx, sizeof (ctx),
794                        &hmac, sizeof (hmac),
795                        NULL);
796     ax->RK = keys[0];
797     ax->NHKs = keys[1];
798     ax->CKs = keys[2];
799
800     ax->PNs = ax->Ns;
801     ax->Ns = 0;
802     ax->ratchet_flag = GNUNET_NO;
803     ax->ratchet_allowed = GNUNET_NO;
804     ax->ratchet_counter = 0;
805     ax->ratchet_expiration
806       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
807                                   ratchet_time);
808   }
809
810   t_hmac_derive_key (&ax->CKs,
811                      &MK,
812                      "0",
813                      1);
814   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
815                                      &MK,
816                                      NULL, 0,
817                                      NULL);
818
819   out_size = GNUNET_CRYPTO_symmetric_encrypt (src,
820                                               size,
821                                               &MK,
822                                               &iv,
823                                               dst);
824   GNUNET_assert (size == out_size);
825   t_hmac_derive_key (&ax->CKs,
826                      &ax->CKs,
827                      "1",
828                      1);
829 }
830
831
832 /**
833  * Decrypt data with the axolotl tunnel key.
834  *
835  * @param ax key material to use.
836  * @param dst Destination for the decrypted data, must contain @a size bytes.
837  * @param src Source of the ciphertext. Can overlap with @c dst, must contain @a size bytes.
838  * @param size Size of the @a src and @a dst buffers
839  */
840 static void
841 t_ax_decrypt (struct CadetTunnelAxolotl *ax,
842               void *dst,
843               const void *src,
844               size_t size)
845 {
846   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
847   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
848   size_t out_size;
849
850   t_hmac_derive_key (&ax->CKr,
851                      &MK,
852                      "0",
853                      1);
854   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
855                                      &MK,
856                                      NULL, 0,
857                                      NULL);
858   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
859   out_size = GNUNET_CRYPTO_symmetric_decrypt (src,
860                                               size,
861                                               &MK,
862                                               &iv,
863                                               dst);
864   GNUNET_assert (out_size == size);
865   t_hmac_derive_key (&ax->CKr,
866                      &ax->CKr,
867                      "1",
868                      1);
869 }
870
871
872 /**
873  * Encrypt header with the axolotl header key.
874  *
875  * @param ax key material to use.
876  * @param[in|out] msg Message whose header to encrypt.
877  */
878 static void
879 t_h_encrypt (struct CadetTunnelAxolotl *ax,
880              struct GNUNET_CADET_TunnelEncryptedMessage *msg)
881 {
882   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
883   size_t out_size;
884
885   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
886                                      &ax->HKs,
887                                      NULL, 0,
888                                      NULL);
889   out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header,
890                                               sizeof (struct GNUNET_CADET_AxHeader),
891                                               &ax->HKs,
892                                               &iv,
893                                               &msg->ax_header);
894   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
895 }
896
897
898 /**
899  * Decrypt header with the current axolotl header key.
900  *
901  * @param ax key material to use.
902  * @param src Message whose header to decrypt.
903  * @param dst Where to decrypt header to.
904  */
905 static void
906 t_h_decrypt (struct CadetTunnelAxolotl *ax,
907              const struct GNUNET_CADET_TunnelEncryptedMessage *src,
908              struct GNUNET_CADET_TunnelEncryptedMessage *dst)
909 {
910   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
911   size_t out_size;
912
913   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
914                                      &ax->HKr,
915                                      NULL, 0,
916                                      NULL);
917   out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
918                                               sizeof (struct GNUNET_CADET_AxHeader),
919                                               &ax->HKr,
920                                               &iv,
921                                               &dst->ax_header.Ns);
922   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size);
923 }
924
925
926 /**
927  * Delete a key from the list of skipped keys.
928  *
929  * @param ax key material to delete @a key from.
930  * @param key Key to delete.
931  */
932 static void
933 delete_skipped_key (struct CadetTunnelAxolotl *ax,
934                     struct CadetTunnelSkippedKey *key)
935 {
936   GNUNET_CONTAINER_DLL_remove (ax->skipped_head,
937                                ax->skipped_tail,
938                                key);
939   GNUNET_free (key);
940   ax->skipped--;
941 }
942
943
944 /**
945  * Decrypt and verify data with the appropriate tunnel key and verify that the
946  * data has not been altered since it was sent by the remote peer.
947  *
948  * @param ax key material to use.
949  * @param dst Destination for the plaintext.
950  * @param src Source of the message. Can overlap with @c dst.
951  * @param size Size of the message.
952  * @return Size of the decrypted data, -1 if an error was encountered.
953  */
954 static ssize_t
955 try_old_ax_keys (struct CadetTunnelAxolotl *ax,
956                  void *dst,
957                  const struct GNUNET_CADET_TunnelEncryptedMessage *src,
958                  size_t size)
959 {
960   struct CadetTunnelSkippedKey *key;
961   struct GNUNET_ShortHashCode *hmac;
962   struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
963   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
964   struct GNUNET_CRYPTO_SymmetricSessionKey *valid_HK;
965   size_t esize;
966   size_t res;
967   size_t len;
968   unsigned int N;
969
970   LOG (GNUNET_ERROR_TYPE_DEBUG,
971        "Trying skipped keys\n");
972   hmac = &plaintext_header.hmac;
973   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
974
975   /* Find a correct Header Key */
976   valid_HK = NULL;
977   for (key = ax->skipped_head; NULL != key; key = key->next)
978   {
979     t_hmac (&src->ax_header,
980             sizeof (struct GNUNET_CADET_AxHeader) + esize,
981             0,
982             &key->HK,
983             hmac);
984     if (0 == memcmp (hmac,
985                      &src->hmac,
986                      sizeof (*hmac)))
987     {
988       valid_HK = &key->HK;
989       break;
990     }
991   }
992   if (NULL == key)
993     return -1;
994
995   /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */
996   GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage));
997   len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
998   GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader));
999
1000   /* Decrypt header */
1001   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1002                                      &key->HK,
1003                                      NULL, 0,
1004                                      NULL);
1005   res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns,
1006                                          sizeof (struct GNUNET_CADET_AxHeader),
1007                                          &key->HK,
1008                                          &iv,
1009                                          &plaintext_header.ax_header.Ns);
1010   GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res);
1011
1012   /* Find the correct message key */
1013   N = ntohl (plaintext_header.ax_header.Ns);
1014   while ( (NULL != key) &&
1015           (N != key->Kn) )
1016     key = key->next;
1017   if ( (NULL == key) ||
1018        (0 != memcmp (&key->HK,
1019                      valid_HK,
1020                      sizeof (*valid_HK))) )
1021     return -1;
1022
1023   /* Decrypt payload */
1024   GNUNET_CRYPTO_symmetric_derive_iv (&iv,
1025                                      &key->MK,
1026                                      NULL,
1027                                      0,
1028                                      NULL);
1029   res = GNUNET_CRYPTO_symmetric_decrypt (&src[1],
1030                                          len,
1031                                          &key->MK,
1032                                          &iv,
1033                                          dst);
1034   delete_skipped_key (ax,
1035                       key);
1036   return res;
1037 }
1038
1039
1040 /**
1041  * Delete a key from the list of skipped keys.
1042  *
1043  * @param ax key material to delete from.
1044  * @param HKr Header Key to use.
1045  */
1046 static void
1047 store_skipped_key (struct CadetTunnelAxolotl *ax,
1048                    const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr)
1049 {
1050   struct CadetTunnelSkippedKey *key;
1051
1052   key = GNUNET_new (struct CadetTunnelSkippedKey);
1053   key->timestamp = GNUNET_TIME_absolute_get ();
1054   key->Kn = ax->Nr;
1055   key->HK = ax->HKr;
1056   t_hmac_derive_key (&ax->CKr,
1057                      &key->MK,
1058                      "0",
1059                      1);
1060   t_hmac_derive_key (&ax->CKr,
1061                      &ax->CKr,
1062                      "1",
1063                      1);
1064   GNUNET_CONTAINER_DLL_insert (ax->skipped_head,
1065                                ax->skipped_tail,
1066                                key);
1067   ax->skipped++;
1068   ax->Nr++;
1069 }
1070
1071
1072 /**
1073  * Stage skipped AX keys and calculate the message key.
1074  * Stores each HK and MK for skipped messages.
1075  *
1076  * @param ax key material to use
1077  * @param HKr Header key.
1078  * @param Np Received meesage number.
1079  * @return #GNUNET_OK if keys were stored.
1080  *         #GNUNET_SYSERR if an error ocurred (@a Np not expected).
1081  */
1082 static int
1083 store_ax_keys (struct CadetTunnelAxolotl *ax,
1084                const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr,
1085                uint32_t Np)
1086 {
1087   int gap;
1088
1089   gap = Np - ax->Nr;
1090   LOG (GNUNET_ERROR_TYPE_DEBUG,
1091        "Storing skipped keys [%u, %u)\n",
1092        ax->Nr,
1093        Np);
1094   if (MAX_KEY_GAP < gap)
1095   {
1096     /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */
1097     /* TODO: start new key exchange on return */
1098     GNUNET_break_op (0);
1099     LOG (GNUNET_ERROR_TYPE_WARNING,
1100          "Got message %u, expected %u+\n",
1101          Np,
1102          ax->Nr);
1103     return GNUNET_SYSERR;
1104   }
1105   if (0 > gap)
1106   {
1107     /* Delayed message: don't store keys, flag to try old keys. */
1108     return GNUNET_SYSERR;
1109   }
1110
1111   while (ax->Nr < Np)
1112     store_skipped_key (ax,
1113                        HKr);
1114
1115   while (ax->skipped > MAX_SKIPPED_KEYS)
1116     delete_skipped_key (ax,
1117                         ax->skipped_tail);
1118   return GNUNET_OK;
1119 }
1120
1121
1122 /**
1123  * Decrypt and verify data with the appropriate tunnel key and verify that the
1124  * data has not been altered since it was sent by the remote peer.
1125  *
1126  * @param ax key material to use
1127  * @param dst Destination for the plaintext.
1128  * @param src Source of the message. Can overlap with @c dst.
1129  * @param size Size of the message.
1130  * @return Size of the decrypted data, -1 if an error was encountered.
1131  */
1132 static ssize_t
1133 t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax,
1134                            void *dst,
1135                            const struct GNUNET_CADET_TunnelEncryptedMessage *src,
1136                            size_t size)
1137 {
1138   struct GNUNET_ShortHashCode msg_hmac;
1139   struct GNUNET_HashCode hmac;
1140   struct GNUNET_CADET_TunnelEncryptedMessage plaintext_header;
1141   uint32_t Np;
1142   uint32_t PNp;
1143   size_t esize; /* Size of encryped payload */
1144
1145   esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage);
1146
1147   /* Try current HK */
1148   t_hmac (&src->ax_header,
1149           sizeof (struct GNUNET_CADET_AxHeader) + esize,
1150           0, &ax->HKr,
1151           &msg_hmac);
1152   if (0 != memcmp (&msg_hmac,
1153                    &src->hmac,
1154                    sizeof (msg_hmac)))
1155   {
1156     static const char ctx[] = "axolotl ratchet";
1157     struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */
1158     struct GNUNET_CRYPTO_SymmetricSessionKey HK;
1159     struct GNUNET_HashCode dh;
1160     struct GNUNET_CRYPTO_EcdhePublicKey *DHRp;
1161
1162     /* Try Next HK */
1163     t_hmac (&src->ax_header,
1164             sizeof (struct GNUNET_CADET_AxHeader) + esize,
1165             0,
1166             &ax->NHKr,
1167             &msg_hmac);
1168     if (0 != memcmp (&msg_hmac,
1169                      &src->hmac,
1170                      sizeof (msg_hmac)))
1171     {
1172       /* Try the skipped keys, if that fails, we're out of luck. */
1173       return try_old_ax_keys (ax,
1174                               dst,
1175                               src,
1176                               size);
1177     }
1178     HK = ax->HKr;
1179     ax->HKr = ax->NHKr;
1180     t_h_decrypt (ax,
1181                  src,
1182                  &plaintext_header);
1183     Np = ntohl (plaintext_header.ax_header.Ns);
1184     PNp = ntohl (plaintext_header.ax_header.PNs);
1185     DHRp = &plaintext_header.ax_header.DHRs;
1186     store_ax_keys (ax,
1187                    &HK,
1188                    PNp);
1189
1190     /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */
1191     GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs,
1192                             DHRp,
1193                             &dh);
1194     t_ax_hmac_hash (&ax->RK,
1195                     &hmac,
1196                     &dh, sizeof (dh));
1197     GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1198                        ctx, sizeof (ctx),
1199                        &hmac, sizeof (hmac),
1200                        NULL);
1201
1202     /* Commit "purported" keys */
1203     ax->RK = keys[0];
1204     ax->NHKr = keys[1];
1205     ax->CKr = keys[2];
1206     ax->DHRr = *DHRp;
1207     ax->Nr = 0;
1208     ax->ratchet_allowed = GNUNET_YES;
1209   }
1210   else
1211   {
1212     t_h_decrypt (ax,
1213                  src,
1214                  &plaintext_header);
1215     Np = ntohl (plaintext_header.ax_header.Ns);
1216     PNp = ntohl (plaintext_header.ax_header.PNs);
1217   }
1218   if ( (Np != ax->Nr) &&
1219        (GNUNET_OK != store_ax_keys (ax,
1220                                     &ax->HKr,
1221                                     Np)) )
1222   {
1223     /* Try the skipped keys, if that fails, we're out of luck. */
1224     return try_old_ax_keys (ax,
1225                             dst,
1226                             src,
1227                             size);
1228   }
1229
1230   t_ax_decrypt (ax,
1231                 dst,
1232                 &src[1],
1233                 esize);
1234   ax->Nr = Np + 1;
1235   return esize;
1236 }
1237
1238
1239 /**
1240  * Our tunnel became ready for the first time, notify channels
1241  * that have been waiting.
1242  *
1243  * @param cls our tunnel, not used
1244  * @param key unique ID of the channel, not used
1245  * @param value the `struct CadetChannel` to notify
1246  * @return #GNUNET_OK (continue to iterate)
1247  */
1248 static int
1249 notify_tunnel_up_cb (void *cls,
1250                      uint32_t key,
1251                      void *value)
1252 {
1253   struct CadetChannel *ch = value;
1254
1255   GCCH_tunnel_up (ch);
1256   return GNUNET_OK;
1257 }
1258
1259
1260 /**
1261  * Change the tunnel encryption state.
1262  * If the encryption state changes to OK, stop the rekey task.
1263  *
1264  * @param t Tunnel whose encryption state to change, or NULL.
1265  * @param state New encryption state.
1266  */
1267 void
1268 GCT_change_estate (struct CadetTunnel *t,
1269                    enum CadetTunnelEState state)
1270 {
1271   enum CadetTunnelEState old = t->estate;
1272
1273   t->estate = state;
1274   LOG (GNUNET_ERROR_TYPE_DEBUG,
1275        "%s estate changed from %s to %s\n",
1276        GCT_2s (t),
1277        estate2s (old),
1278        estate2s (state));
1279
1280   if ( (CADET_TUNNEL_KEY_OK != old) &&
1281        (CADET_TUNNEL_KEY_OK == t->estate) )
1282   {
1283     if (NULL != t->kx_task)
1284     {
1285       GNUNET_SCHEDULER_cancel (t->kx_task);
1286       t->kx_task = NULL;
1287     }
1288     /* notify all channels that have been waiting */
1289     GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1290                                              &notify_tunnel_up_cb,
1291                                              t);
1292     if (NULL != t->send_task)
1293       GNUNET_SCHEDULER_cancel (t->send_task);
1294     t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
1295                                              t);
1296   }
1297 }
1298
1299
1300 /**
1301  * Send a KX message.
1302  *
1303  * @param t tunnel on which to send the KX_AUTH
1304  * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1305  *           we are to find one that is ready.
1306  * @param ax axolotl key context to use
1307  */
1308 static void
1309 send_kx (struct CadetTunnel *t,
1310          struct CadetTConnection *ct,
1311          struct CadetTunnelAxolotl *ax)
1312 {
1313   struct CadetConnection *cc;
1314   struct GNUNET_MQ_Envelope *env;
1315   struct GNUNET_CADET_TunnelKeyExchangeMessage *msg;
1316   enum GNUNET_CADET_KX_Flags flags;
1317
1318   if (NULL == ct)
1319     ct = get_ready_connection (t);
1320   if (NULL == ct)
1321   {
1322     LOG (GNUNET_ERROR_TYPE_DEBUG,
1323          "Wanted to send %s in state %s, but no connection is ready, deferring\n",
1324          GCT_2s (t),
1325          estate2s (t->estate));
1326     t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1327     return;
1328   }
1329   cc = ct->cc;
1330   LOG (GNUNET_ERROR_TYPE_DEBUG,
1331        "Sending KX on %s via %s in state %s\n",
1332        GCT_2s (t),
1333        GCC_2s (cc),
1334        estate2s (t->estate));
1335   env = GNUNET_MQ_msg (msg,
1336                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX);
1337   flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */
1338   msg->flags = htonl (flags);
1339   msg->cid = *GCC_get_id (cc);
1340   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1341                                       &msg->ephemeral_key);
1342   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1343                                       &msg->ratchet_key);
1344   mark_connection_unready (ct);
1345   t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1346   t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1347   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1348     GCT_change_estate (t,
1349                        CADET_TUNNEL_KEY_AX_SENT);
1350   else if (CADET_TUNNEL_KEY_AX_RECV == t->estate)
1351     GCT_change_estate (t,
1352                        CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1353   GCC_transmit (cc,
1354                 env);
1355 }
1356
1357
1358 /**
1359  * Send a KX_AUTH message.
1360  *
1361  * @param t tunnel on which to send the KX_AUTH
1362  * @param ct Tunnel and connection on which to send the KX_AUTH, NULL if
1363  *           we are to find one that is ready.
1364  * @param ax axolotl key context to use
1365  * @param force_reply Force the other peer to reply with a KX_AUTH message
1366  *         (set if we would like to transmit right now, but cannot)
1367  */
1368 static void
1369 send_kx_auth (struct CadetTunnel *t,
1370               struct CadetTConnection *ct,
1371               struct CadetTunnelAxolotl *ax,
1372               int force_reply)
1373 {
1374   struct CadetConnection *cc;
1375   struct GNUNET_MQ_Envelope *env;
1376   struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg;
1377   enum GNUNET_CADET_KX_Flags flags;
1378
1379   if ( (NULL == ct) ||
1380        (GNUNET_NO == ct->is_ready) )
1381     ct = get_ready_connection (t);
1382   if (NULL == ct)
1383   {
1384     LOG (GNUNET_ERROR_TYPE_DEBUG,
1385          "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n",
1386          GCT_2s (t));
1387     t->next_kx_attempt = GNUNET_TIME_absolute_get ();
1388     t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */
1389     return;
1390   }
1391   t->kx_auth_requested = GNUNET_NO; /* clear flag */
1392   cc = ct->cc;
1393   LOG (GNUNET_ERROR_TYPE_DEBUG,
1394        "Sending KX_AUTH on %s using %s\n",
1395        GCT_2s (t),
1396        GCC_2s (ct->cc));
1397
1398   env = GNUNET_MQ_msg (msg,
1399                        GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH);
1400   flags = GNUNET_CADET_KX_FLAG_NONE;
1401   if (GNUNET_YES == force_reply)
1402     flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY;
1403   msg->kx.flags = htonl (flags);
1404   msg->kx.cid = *GCC_get_id (cc);
1405   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0,
1406                                       &msg->kx.ephemeral_key);
1407   GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs,
1408                                       &msg->kx.ratchet_key);
1409   /* Compute authenticator (this is the main difference to #send_kx()) */
1410   GNUNET_CRYPTO_hash (&ax->RK,
1411                       sizeof (ax->RK),
1412                       &msg->auth);
1413
1414   /* Compute when to be triggered again; actual job will
1415      be scheduled via #connection_ready_cb() */
1416   t->kx_retry_delay
1417     = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay);
1418   t->next_kx_attempt
1419     = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay);
1420
1421   /* Send via cc, mark it as unready */
1422   mark_connection_unready (ct);
1423
1424   /* Update state machine, unless we are already OK */
1425   if (CADET_TUNNEL_KEY_OK != t->estate)
1426     GCT_change_estate (t,
1427                        CADET_TUNNEL_KEY_AX_AUTH_SENT);
1428
1429   GCC_transmit (cc,
1430                 env);
1431 }
1432
1433
1434 /**
1435  * Cleanup state used by @a ax.
1436  *
1437  * @param ax state to free, but not memory of @a ax itself
1438  */
1439 static void
1440 cleanup_ax (struct CadetTunnelAxolotl *ax)
1441 {
1442   while (NULL != ax->skipped_head)
1443     delete_skipped_key (ax,
1444                         ax->skipped_head);
1445   GNUNET_assert (0 == ax->skipped);
1446   GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0);
1447   GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs);
1448 }
1449
1450
1451 /**
1452  * Update our Axolotl key state based on the KX data we received.
1453  * Computes the new chain keys, and root keys, etc, and also checks
1454  * wether this is a replay of the current chain.
1455  *
1456  * @param[in|out] axolotl chain key state to recompute
1457  * @param pid peer identity of the other peer
1458  * @param ephemeral_key ephemeral public key of the other peer
1459  * @param ratchet_key senders next ephemeral public key
1460  * @return #GNUNET_OK on success, #GNUNET_NO if the resulting
1461  *       root key is already in @a ax and thus the KX is useless;
1462  *       #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id)
1463  */
1464 static int
1465 update_ax_by_kx (struct CadetTunnelAxolotl *ax,
1466                  const struct GNUNET_PeerIdentity *pid,
1467                  const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key,
1468                  const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key)
1469 {
1470   struct GNUNET_HashCode key_material[3];
1471   struct GNUNET_CRYPTO_SymmetricSessionKey keys[5];
1472   const char salt[] = "CADET Axolotl salt";
1473   int am_I_alice;
1474
1475   if (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1476                                            pid))
1477     am_I_alice = GNUNET_YES;
1478   else if (0 < GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1479                                                 pid))
1480     am_I_alice = GNUNET_NO;
1481   else
1482   {
1483     GNUNET_break_op (0);
1484     return GNUNET_SYSERR;
1485   }
1486
1487   if (0 == memcmp (&ax->DHRr,
1488                    ratchet_key,
1489                    sizeof (*ratchet_key)))
1490   {
1491     LOG (GNUNET_ERROR_TYPE_DEBUG,
1492          "Ratchet key already known. Ignoring KX.\n");
1493     return GNUNET_NO;
1494   }
1495
1496   ax->DHRr = *ratchet_key;
1497
1498   /* ECDH A B0 */
1499   if (GNUNET_YES == am_I_alice)
1500   {
1501     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1502                               ephemeral_key, /* B0 */
1503                               &key_material[0]);
1504   }
1505   else
1506   {
1507     GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0,            /* B0 */
1508                               &pid->public_key,    /* A */
1509                               &key_material[0]);
1510   }
1511
1512   /* ECDH A0 B */
1513   if (GNUNET_YES == am_I_alice)
1514   {
1515     GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0,            /* A0 */
1516                               &pid->public_key,    /* B */
1517                               &key_material[1]);
1518   }
1519   else
1520   {
1521     GNUNET_CRYPTO_eddsa_ecdh (my_private_key,      /* A */
1522                               ephemeral_key, /* B0 */
1523                               &key_material[1]);
1524
1525
1526   }
1527
1528   /* ECDH A0 B0 */
1529   /* (This is the triple-DH, we could probably safely skip this,
1530      as A0/B0 are already in the key material.) */
1531   GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0,             /* A0 or B0 */
1532                           ephemeral_key,  /* B0 or A0 */
1533                           &key_material[2]);
1534
1535   /* KDF */
1536   GNUNET_CRYPTO_kdf (keys, sizeof (keys),
1537                      salt, sizeof (salt),
1538                      &key_material, sizeof (key_material),
1539                      NULL);
1540
1541   if (0 == memcmp (&ax->RK,
1542                    &keys[0],
1543                    sizeof (ax->RK)))
1544   {
1545     LOG (GNUNET_ERROR_TYPE_DEBUG,
1546          "Root key of handshake already known. Ignoring KX.\n");
1547     return GNUNET_NO;
1548   }
1549
1550   ax->RK = keys[0];
1551   if (GNUNET_YES == am_I_alice)
1552   {
1553     ax->HKr = keys[1];
1554     ax->NHKs = keys[2];
1555     ax->NHKr = keys[3];
1556     ax->CKr = keys[4];
1557     ax->ratchet_flag = GNUNET_YES;
1558   }
1559   else
1560   {
1561     ax->HKs = keys[1];
1562     ax->NHKr = keys[2];
1563     ax->NHKs = keys[3];
1564     ax->CKs = keys[4];
1565     ax->ratchet_flag = GNUNET_NO;
1566     ax->ratchet_expiration
1567       = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1568                                   ratchet_time);
1569   }
1570   return GNUNET_OK;
1571 }
1572
1573
1574 /**
1575  * Try to redo the KX or KX_AUTH handshake, if we can.
1576  *
1577  * @param cls the `struct CadetTunnel` to do KX for.
1578  */
1579 static void
1580 retry_kx (void *cls)
1581 {
1582   struct CadetTunnel *t = cls;
1583   struct CadetTunnelAxolotl *ax;
1584
1585   t->kx_task = NULL;
1586   LOG (GNUNET_ERROR_TYPE_DEBUG,
1587        "Trying to make KX progress on %s in state %s\n",
1588        GCT_2s (t),
1589        estate2s (t->estate));
1590   switch (t->estate)
1591   {
1592   case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */
1593   case CADET_TUNNEL_KEY_AX_SENT:       /* trying again */
1594     send_kx (t,
1595              NULL,
1596              &t->ax);
1597     break;
1598   case CADET_TUNNEL_KEY_AX_RECV:
1599   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1600     /* We are responding, so only require reply
1601        if WE have a channel waiting. */
1602     if (NULL != t->unverified_ax)
1603     {
1604       /* Send AX_AUTH so we might get this one verified */
1605       ax = t->unverified_ax;
1606     }
1607     else
1608     {
1609       /* How can this be? */
1610       GNUNET_break (0);
1611       ax = &t->ax;
1612     }
1613     send_kx_auth (t,
1614                   NULL,
1615                   ax,
1616                   (0 == GCT_count_channels (t))
1617                   ? GNUNET_NO
1618                   : GNUNET_YES);
1619     break;
1620   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1621     /* We are responding, so only require reply
1622        if WE have a channel waiting. */
1623     if (NULL != t->unverified_ax)
1624     {
1625       /* Send AX_AUTH so we might get this one verified */
1626       ax = t->unverified_ax;
1627     }
1628     else
1629     {
1630       /* How can this be? */
1631       GNUNET_break (0);
1632       ax = &t->ax;
1633     }
1634     send_kx_auth (t,
1635                   NULL,
1636                   ax,
1637                   (0 == GCT_count_channels (t))
1638                   ? GNUNET_NO
1639                   : GNUNET_YES);
1640     break;
1641   case CADET_TUNNEL_KEY_OK:
1642     /* Must have been the *other* peer asking us to
1643        respond with a KX_AUTH. */
1644     if (NULL != t->unverified_ax)
1645     {
1646       /* Sending AX_AUTH in response to AX so we might get this one verified */
1647       ax = t->unverified_ax;
1648     }
1649     else
1650     {
1651       /* Sending AX_AUTH in response to AX_AUTH */
1652       ax = &t->ax;
1653     }
1654     send_kx_auth (t,
1655                   NULL,
1656                   ax,
1657                   GNUNET_NO);
1658     break;
1659   }
1660 }
1661
1662
1663 /**
1664  * Handle KX message that lacks authentication (and which will thus
1665  * only be considered authenticated after we respond with our own
1666  * KX_AUTH and finally successfully decrypt payload).
1667  *
1668  * @param ct connection/tunnel combo that received encrypted message
1669  * @param msg the key exchange message
1670  */
1671 void
1672 GCT_handle_kx (struct CadetTConnection *ct,
1673                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
1674 {
1675   struct CadetTunnel *t = ct->t;
1676   struct CadetTunnelAxolotl *ax;
1677   int ret;
1678
1679   if (0 ==
1680       memcmp (&t->ax.DHRr,
1681               &msg->ratchet_key,
1682               sizeof (msg->ratchet_key)))
1683   {
1684     LOG (GNUNET_ERROR_TYPE_DEBUG,
1685          "Got duplicate KX. Firing back KX_AUTH.\n");
1686     send_kx_auth (t,
1687                   ct,
1688                   &t->ax,
1689                   GNUNET_NO);
1690     return;
1691   }
1692
1693   /* We only keep ONE unverified KX around, so if there is an existing one,
1694      clean it up. */
1695   if (NULL != t->unverified_ax)
1696   {
1697     if (0 ==
1698         memcmp (&t->unverified_ax->DHRr,
1699                 &msg->ratchet_key,
1700                 sizeof (msg->ratchet_key)))
1701     {
1702       LOG (GNUNET_ERROR_TYPE_DEBUG,
1703            "Got duplicate unverified KX on %s. Fire back KX_AUTH again.\n",
1704            GCT_2s (t));
1705       send_kx_auth (t,
1706                     ct,
1707                     t->unverified_ax,
1708                     GNUNET_NO);
1709       return;
1710     }
1711     LOG (GNUNET_ERROR_TYPE_DEBUG,
1712          "Dropping old unverified KX state. Got a fresh KX for %s.\n",
1713          GCT_2s (t));
1714     memset (t->unverified_ax,
1715             0,
1716             sizeof (struct CadetTunnelAxolotl));
1717     t->unverified_ax->DHRs = t->ax.DHRs;
1718     t->unverified_ax->kx_0 = t->ax.kx_0;
1719   }
1720   else
1721   {
1722     LOG (GNUNET_ERROR_TYPE_DEBUG,
1723          "Creating fresh unverified KX for %s.\n",
1724          GCT_2s (t));
1725     t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl);
1726     t->unverified_ax->DHRs = t->ax.DHRs;
1727     t->unverified_ax->kx_0 = t->ax.kx_0;
1728   }
1729   /* Set as the 'current' RK/DHRr the one we are currently using,
1730      so that the duplicate-detection logic of
1731      #update_ax_by_kx can work. */
1732   t->unverified_ax->RK = t->ax.RK;
1733   t->unverified_ax->DHRr = t->ax.DHRr;
1734   t->unverified_attempts = 0;
1735   ax = t->unverified_ax;
1736
1737   /* Update 'ax' by the new key material */
1738   ret = update_ax_by_kx (ax,
1739                          GCP_get_id (t->destination),
1740                          &msg->ephemeral_key,
1741                          &msg->ratchet_key);
1742   GNUNET_break (GNUNET_SYSERR != ret);
1743   if (GNUNET_OK != ret)
1744     return; /* duplicate KX, nothing to do */
1745
1746   /* move ahead in our state machine */
1747   if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate)
1748     GCT_change_estate (t,
1749                        CADET_TUNNEL_KEY_AX_RECV);
1750   else if (CADET_TUNNEL_KEY_AX_SENT == t->estate)
1751     GCT_change_estate (t,
1752                        CADET_TUNNEL_KEY_AX_SENT_AND_RECV);
1753
1754   /* KX is still not done, try again our end. */
1755   if (CADET_TUNNEL_KEY_OK != t->estate)
1756   {
1757     if (NULL != t->kx_task)
1758       GNUNET_SCHEDULER_cancel (t->kx_task);
1759     t->kx_task
1760       = GNUNET_SCHEDULER_add_now (&retry_kx,
1761                                   t);
1762   }
1763 }
1764
1765
1766 /**
1767  * Handle KX_AUTH message.
1768  *
1769  * @param ct connection/tunnel combo that received encrypted message
1770  * @param msg the key exchange message
1771  */
1772 void
1773 GCT_handle_kx_auth (struct CadetTConnection *ct,
1774                     const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
1775 {
1776   struct CadetTunnel *t = ct->t;
1777   struct CadetTunnelAxolotl ax_tmp;
1778   struct GNUNET_HashCode kx_auth;
1779   int ret;
1780
1781   if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) ||
1782        (CADET_TUNNEL_KEY_AX_RECV == t->estate) )
1783   {
1784     /* Confusing, we got a KX_AUTH before we even send our own
1785        KX. This should not happen. We'll send our own KX ASAP anyway,
1786        so let's ignore this here. */
1787     GNUNET_break_op (0);
1788     return;
1789   }
1790   LOG (GNUNET_ERROR_TYPE_DEBUG,
1791        "Handling KX_AUTH message for %s\n",
1792        GCT_2s (t));
1793
1794   /* We do everything in ax_tmp until we've checked the authentication
1795      so we don't clobber anything we care about by accident. */
1796   ax_tmp = t->ax;
1797
1798   /* Update 'ax' by the new key material */
1799   ret = update_ax_by_kx (&ax_tmp,
1800                          GCP_get_id (t->destination),
1801                          &msg->kx.ephemeral_key,
1802                          &msg->kx.ratchet_key);
1803   if (GNUNET_OK != ret)
1804   {
1805     if (GNUNET_NO == ret)
1806       GNUNET_STATISTICS_update (stats,
1807                                 "# redundant KX_AUTH received",
1808                                 1,
1809                                 GNUNET_NO);
1810     else
1811       GNUNET_break (0); /* connect to self!? */
1812     return;
1813   }
1814   GNUNET_CRYPTO_hash (&ax_tmp.RK,
1815                       sizeof (ax_tmp.RK),
1816                       &kx_auth);
1817   if (0 != memcmp (&kx_auth,
1818                    &msg->auth,
1819                    sizeof (kx_auth)))
1820   {
1821     /* This KX_AUTH is not using the latest KX/KX_AUTH data
1822        we transmitted to the sender, refuse it, try KX again. */
1823     GNUNET_break_op (0);
1824     send_kx (t,
1825              NULL,
1826              &t->ax);
1827     return;
1828   }
1829   /* Yep, we're good. */
1830   t->ax = ax_tmp;
1831   if (NULL != t->unverified_ax)
1832   {
1833     /* We got some "stale" KX before, drop that. */
1834     cleanup_ax (t->unverified_ax);
1835     GNUNET_free (t->unverified_ax);
1836     t->unverified_ax = NULL;
1837   }
1838
1839   /* move ahead in our state machine */
1840   switch (t->estate)
1841   {
1842   case CADET_TUNNEL_KEY_UNINITIALIZED:
1843   case CADET_TUNNEL_KEY_AX_RECV:
1844     /* Checked above, this is impossible. */
1845     GNUNET_assert (0);
1846     break;
1847   case CADET_TUNNEL_KEY_AX_SENT:      /* This is the normal case */
1848   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */
1849   case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */
1850     GCT_change_estate (t,
1851                        CADET_TUNNEL_KEY_OK);
1852     break;
1853   case CADET_TUNNEL_KEY_OK:
1854     /* Did not expect another KX_AUTH, but so what, still acceptable.
1855        Nothing to do here. */
1856     break;
1857   }
1858 }
1859
1860
1861
1862 /* ************************************** end core crypto ***************************** */
1863
1864
1865 /**
1866  * Compute the next free channel tunnel number for this tunnel.
1867  *
1868  * @param t the tunnel
1869  * @return unused number that can uniquely identify a channel in the tunnel
1870  */
1871 static struct GNUNET_CADET_ChannelTunnelNumber
1872 get_next_free_ctn (struct CadetTunnel *t)
1873 {
1874 #define HIGH_BIT 0x8000000
1875   struct GNUNET_CADET_ChannelTunnelNumber ret;
1876   uint32_t ctn;
1877   int cmp;
1878   uint32_t highbit;
1879
1880   cmp = GNUNET_CRYPTO_cmp_peer_identity (&my_full_id,
1881                                          GCP_get_id (GCT_get_destination (t)));
1882   if (0 < cmp)
1883     highbit = HIGH_BIT;
1884   else if (0 > cmp)
1885     highbit = 0;
1886   else
1887     GNUNET_assert (0); // loopback must never go here!
1888   ctn = ntohl (t->next_ctn.cn);
1889   while (NULL !=
1890          GNUNET_CONTAINER_multihashmap32_get (t->channels,
1891                                               ctn | highbit))
1892   {
1893     ctn = ((ctn + 1) & (~ HIGH_BIT));
1894   }
1895   t->next_ctn.cn = htonl ((ctn + 1) & (~ HIGH_BIT));
1896   ret.cn = htonl (ctn | highbit);
1897   return ret;
1898 }
1899
1900
1901 /**
1902  * Add a channel to a tunnel, and notify channel that we are ready
1903  * for transmission if we are already up.  Otherwise that notification
1904  * will be done later in #notify_tunnel_up_cb().
1905  *
1906  * @param t Tunnel.
1907  * @param ch Channel
1908  * @return unique number identifying @a ch within @a t
1909  */
1910 struct GNUNET_CADET_ChannelTunnelNumber
1911 GCT_add_channel (struct CadetTunnel *t,
1912                  struct CadetChannel *ch)
1913 {
1914   struct GNUNET_CADET_ChannelTunnelNumber ctn;
1915
1916   ctn = get_next_free_ctn (t);
1917   if (NULL != t->destroy_task)
1918   {
1919     GNUNET_SCHEDULER_cancel (t->destroy_task);
1920     t->destroy_task = NULL;
1921   }
1922   GNUNET_assert (GNUNET_YES ==
1923                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
1924                                                       ntohl (ctn.cn),
1925                                                       ch,
1926                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1927   LOG (GNUNET_ERROR_TYPE_DEBUG,
1928        "Adding %s to %s\n",
1929        GCCH_2s (ch),
1930        GCT_2s (t));
1931   switch (t->estate)
1932   {
1933   case CADET_TUNNEL_KEY_UNINITIALIZED:
1934     /* waiting for connection to start KX */
1935     break;
1936   case CADET_TUNNEL_KEY_AX_RECV:
1937   case CADET_TUNNEL_KEY_AX_SENT:
1938   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
1939     /* we're currently waiting for KX to complete */
1940     break;
1941   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
1942     /* waiting for OTHER peer to send us data,
1943        we might need to prompt more aggressively! */
1944     if (NULL == t->kx_task)
1945       t->kx_task
1946         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
1947                                    &retry_kx,
1948                                    t);
1949     break;
1950   case CADET_TUNNEL_KEY_OK:
1951     /* We are ready. Tell the new channel that we are up. */
1952     GCCH_tunnel_up (ch);
1953     break;
1954   }
1955   return ctn;
1956 }
1957
1958
1959 /**
1960  * We lost a connection, remove it from our list and clean up
1961  * the connection object itself.
1962  *
1963  * @param ct binding of connection to tunnel of the connection that was lost.
1964  */
1965 void
1966 GCT_connection_lost (struct CadetTConnection *ct)
1967 {
1968   struct CadetTunnel *t = ct->t;
1969
1970   if (GNUNET_YES == ct->is_ready)
1971     GNUNET_CONTAINER_DLL_remove (t->connection_ready_head,
1972                                  t->connection_ready_tail,
1973                                  ct);
1974   else
1975     GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
1976                                  t->connection_busy_tail,
1977                                  ct);
1978   GNUNET_free (ct);
1979 }
1980
1981
1982 /**
1983  * Clean up connection @a ct of a tunnel.
1984  *
1985  * @param cls the `struct CadetTunnel`
1986  * @param ct connection to clean up
1987  */
1988 static void
1989 destroy_t_connection (void *cls,
1990                       struct CadetTConnection *ct)
1991 {
1992   struct CadetTunnel *t = cls;
1993   struct CadetConnection *cc = ct->cc;
1994
1995   GNUNET_assert (ct->t == t);
1996   GCT_connection_lost (ct);
1997   GCC_destroy_without_tunnel (cc);
1998 }
1999
2000
2001 /**
2002  * This tunnel is no longer used, destroy it.
2003  *
2004  * @param cls the idle tunnel
2005  */
2006 static void
2007 destroy_tunnel (void *cls)
2008 {
2009   struct CadetTunnel *t = cls;
2010   struct CadetTunnelQueueEntry *tq;
2011
2012   t->destroy_task = NULL;
2013   LOG (GNUNET_ERROR_TYPE_DEBUG,
2014        "Destroying idle %s\n",
2015        GCT_2s (t));
2016   GNUNET_assert (0 == GCT_count_channels (t));
2017   GCT_iterate_connections (t,
2018                            &destroy_t_connection,
2019                            t);
2020   GNUNET_assert (NULL == t->connection_ready_head);
2021   GNUNET_assert (NULL == t->connection_busy_head);
2022   while (NULL != (tq = t->tq_head))
2023   {
2024     if (NULL != tq->cont)
2025       tq->cont (tq->cont_cls,
2026                 NULL);
2027     GCT_send_cancel (tq);
2028   }
2029   GCP_drop_tunnel (t->destination,
2030                    t);
2031   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
2032   if (NULL != t->maintain_connections_task)
2033   {
2034     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
2035     t->maintain_connections_task = NULL;
2036   }
2037   if (NULL != t->send_task)
2038   {
2039     GNUNET_SCHEDULER_cancel (t->send_task);
2040     t->send_task = NULL;
2041   }
2042   if (NULL != t->kx_task)
2043   {
2044     GNUNET_SCHEDULER_cancel (t->kx_task);
2045     t->kx_task = NULL;
2046   }
2047   GNUNET_MST_destroy (t->mst);
2048   GNUNET_MQ_destroy (t->mq);
2049   if (NULL != t->unverified_ax)
2050   {
2051     cleanup_ax (t->unverified_ax);
2052     GNUNET_free (t->unverified_ax);
2053   }
2054   cleanup_ax (&t->ax);
2055   GNUNET_assert (NULL == t->destroy_task);
2056   GNUNET_free (t);
2057 }
2058
2059
2060 /**
2061  * Remove a channel from a tunnel.
2062  *
2063  * @param t Tunnel.
2064  * @param ch Channel
2065  * @param ctn unique number identifying @a ch within @a t
2066  */
2067 void
2068 GCT_remove_channel (struct CadetTunnel *t,
2069                     struct CadetChannel *ch,
2070                     struct GNUNET_CADET_ChannelTunnelNumber ctn)
2071 {
2072   LOG (GNUNET_ERROR_TYPE_DEBUG,
2073        "Removing %s from %s\n",
2074        GCCH_2s (ch),
2075        GCT_2s (t));
2076   GNUNET_assert (GNUNET_YES ==
2077                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
2078                                                          ntohl (ctn.cn),
2079                                                          ch));
2080   if ( (0 ==
2081         GCT_count_channels (t)) &&
2082        (NULL == t->destroy_task) )
2083   {
2084     t->destroy_task
2085       = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
2086                                       &destroy_tunnel,
2087                                       t);
2088   }
2089 }
2090
2091
2092 /**
2093  * Destroy remaining channels during shutdown.
2094  *
2095  * @param cls the `struct CadetTunnel` of the channel
2096  * @param key key of the channel
2097  * @param value the `struct CadetChannel`
2098  * @return #GNUNET_OK (continue to iterate)
2099  */
2100 static int
2101 destroy_remaining_channels (void *cls,
2102                             uint32_t key,
2103                             void *value)
2104 {
2105   struct CadetChannel *ch = value;
2106
2107   GCCH_handle_remote_destroy (ch,
2108                               NULL);
2109   return GNUNET_OK;
2110 }
2111
2112
2113 /**
2114  * Destroys the tunnel @a t now, without delay. Used during shutdown.
2115  *
2116  * @param t tunnel to destroy
2117  */
2118 void
2119 GCT_destroy_tunnel_now (struct CadetTunnel *t)
2120 {
2121   GNUNET_assert (GNUNET_YES == shutting_down);
2122   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
2123                                            &destroy_remaining_channels,
2124                                            t);
2125   GNUNET_assert (0 ==
2126                  GCT_count_channels (t));
2127   if (NULL != t->destroy_task)
2128   {
2129     GNUNET_SCHEDULER_cancel (t->destroy_task);
2130     t->destroy_task = NULL;
2131   }
2132   destroy_tunnel (t);
2133 }
2134
2135
2136 /**
2137  * Send normal payload from queue in @a t via connection @a ct.
2138  * Does nothing if our payload queue is empty.
2139  *
2140  * @param t tunnel to send data from
2141  * @param ct connection to use for transmission (is ready)
2142  */
2143 static void
2144 try_send_normal_payload (struct CadetTunnel *t,
2145                          struct CadetTConnection *ct)
2146 {
2147   struct CadetTunnelQueueEntry *tq;
2148
2149   GNUNET_assert (GNUNET_YES == ct->is_ready);
2150   tq = t->tq_head;
2151   if (NULL == tq)
2152   {
2153     /* no messages pending right now */
2154     LOG (GNUNET_ERROR_TYPE_DEBUG,
2155          "Not sending payload of %s on ready %s (nothing pending)\n",
2156          GCT_2s (t),
2157          GCC_2s (ct->cc));
2158     return;
2159   }
2160   /* ready to send message 'tq' on tunnel 'ct' */
2161   GNUNET_assert (t == tq->t);
2162   GNUNET_CONTAINER_DLL_remove (t->tq_head,
2163                                t->tq_tail,
2164                                tq);
2165   if (NULL != tq->cid)
2166     *tq->cid = *GCC_get_id (ct->cc);
2167   mark_connection_unready (ct);
2168   LOG (GNUNET_ERROR_TYPE_DEBUG,
2169        "Sending payload of %s on %s\n",
2170        GCT_2s (t),
2171        GCC_2s (ct->cc));
2172   GCC_transmit (ct->cc,
2173                 tq->env);
2174   if (NULL != tq->cont)
2175     tq->cont (tq->cont_cls,
2176               GCC_get_id (ct->cc));
2177   GNUNET_free (tq);
2178 }
2179
2180
2181 /**
2182  * A connection is @a is_ready for transmission.  Looks at our message
2183  * queue and if there is a message, sends it out via the connection.
2184  *
2185  * @param cls the `struct CadetTConnection` that is @a is_ready
2186  * @param is_ready #GNUNET_YES if connection are now ready,
2187  *                 #GNUNET_NO if connection are no longer ready
2188  */
2189 static void
2190 connection_ready_cb (void *cls,
2191                      int is_ready)
2192 {
2193   struct CadetTConnection *ct = cls;
2194   struct CadetTunnel *t = ct->t;
2195
2196   if (GNUNET_NO == is_ready)
2197   {
2198     LOG (GNUNET_ERROR_TYPE_DEBUG,
2199          "%s no longer ready for %s\n",
2200          GCC_2s (ct->cc),
2201          GCT_2s (t));
2202     mark_connection_unready (ct);
2203     return;
2204   }
2205   GNUNET_assert (GNUNET_NO == ct->is_ready);
2206   GNUNET_CONTAINER_DLL_remove (t->connection_busy_head,
2207                                t->connection_busy_tail,
2208                                ct);
2209   GNUNET_assert (0 < t->num_busy_connections);
2210   t->num_busy_connections--;
2211   ct->is_ready = GNUNET_YES;
2212   GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head,
2213                                     t->connection_ready_tail,
2214                                     ct);
2215   t->num_ready_connections++;
2216
2217   LOG (GNUNET_ERROR_TYPE_DEBUG,
2218        "%s now ready for %s in state %s\n",
2219        GCC_2s (ct->cc),
2220        GCT_2s (t),
2221        estate2s (t->estate));
2222   switch (t->estate)
2223   {
2224   case CADET_TUNNEL_KEY_UNINITIALIZED:
2225     /* Do not begin KX if WE have no channels waiting! */
2226     if (0 == GCT_count_channels (t))
2227       return;
2228     /* We are uninitialized, just transmit immediately,
2229        without undue delay. */
2230     if (NULL != t->kx_task)
2231     {
2232       GNUNET_SCHEDULER_cancel (t->kx_task);
2233       t->kx_task = NULL;
2234     }
2235     send_kx (t,
2236              ct,
2237              &t->ax);
2238     break;
2239   case CADET_TUNNEL_KEY_AX_RECV:
2240   case CADET_TUNNEL_KEY_AX_SENT:
2241   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
2242   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
2243     /* we're currently waiting for KX to complete, schedule job */
2244     if (NULL == t->kx_task)
2245       t->kx_task
2246         = GNUNET_SCHEDULER_add_at (t->next_kx_attempt,
2247                                    &retry_kx,
2248                                    t);
2249     break;
2250   case CADET_TUNNEL_KEY_OK:
2251     if (GNUNET_YES == t->kx_auth_requested)
2252     {
2253       if (NULL != t->kx_task)
2254       {
2255         GNUNET_SCHEDULER_cancel (t->kx_task);
2256         t->kx_task = NULL;
2257       }
2258       send_kx_auth (t,
2259                     ct,
2260                     &t->ax,
2261                     GNUNET_NO);
2262       return;
2263     }
2264     try_send_normal_payload (t,
2265                              ct);
2266     break;
2267   }
2268 }
2269
2270
2271 /**
2272  * Called when either we have a new connection, or a new message in the
2273  * queue, or some existing connection has transmission capacity.  Looks
2274  * at our message queue and if there is a message, picks a connection
2275  * to send it on.
2276  *
2277  * @param cls the `struct CadetTunnel` to process messages on
2278  */
2279 static void
2280 trigger_transmissions (void *cls)
2281 {
2282   struct CadetTunnel *t = cls;
2283   struct CadetTConnection *ct;
2284
2285   t->send_task = NULL;
2286   if (NULL == t->tq_head)
2287     return; /* no messages pending right now */
2288   ct = get_ready_connection (t);
2289   if (NULL == ct)
2290     return; /* no connections ready */
2291   try_send_normal_payload (t,
2292                            ct);
2293 }
2294
2295
2296 /**
2297  * Closure for #evaluate_connection. Used to assemble summary information
2298  * about the existing connections so we can evaluate a new path.
2299  */
2300 struct EvaluationSummary
2301 {
2302
2303   /**
2304    * Minimum length of any of our connections, `UINT_MAX` if we have none.
2305    */
2306   unsigned int min_length;
2307
2308   /**
2309    * Maximum length of any of our connections, 0 if we have none.
2310    */
2311   unsigned int max_length;
2312
2313   /**
2314    * Minimum desirability of any of our connections, UINT64_MAX if we have none.
2315    */
2316   GNUNET_CONTAINER_HeapCostType min_desire;
2317
2318   /**
2319    * Maximum desirability of any of our connections, 0 if we have none.
2320    */
2321   GNUNET_CONTAINER_HeapCostType max_desire;
2322
2323   /**
2324    * Path we are comparing against for #evaluate_connection, can be NULL.
2325    */
2326   struct CadetPeerPath *path;
2327
2328   /**
2329    * Connection deemed the "worst" so far encountered by #evaluate_connection,
2330    * NULL if we did not yet encounter any connections.
2331    */
2332   struct CadetTConnection *worst;
2333
2334   /**
2335    * Numeric score of @e worst, only set if @e worst is non-NULL.
2336    */
2337   double worst_score;
2338
2339   /**
2340    * Set to #GNUNET_YES if we have a connection over @e path already.
2341    */
2342   int duplicate;
2343
2344 };
2345
2346
2347 /**
2348  * Evaluate a connection, updating our summary information in @a cls about
2349  * what kinds of connections we have.
2350  *
2351  * @param cls the `struct EvaluationSummary *` to update
2352  * @param ct a connection to include in the summary
2353  */
2354 static void
2355 evaluate_connection (void *cls,
2356                      struct CadetTConnection *ct)
2357 {
2358   struct EvaluationSummary *es = cls;
2359   struct CadetConnection *cc = ct->cc;
2360   struct CadetPeerPath *ps = GCC_get_path (cc);
2361   const struct CadetConnectionMetrics *metrics;
2362   GNUNET_CONTAINER_HeapCostType ct_desirability;
2363   struct GNUNET_TIME_Relative uptime;
2364   struct GNUNET_TIME_Relative last_use;
2365   uint32_t ct_length;
2366   double score;
2367   double success_rate;
2368
2369   if (ps == es->path)
2370   {
2371     LOG (GNUNET_ERROR_TYPE_DEBUG,
2372          "Ignoring duplicate path %s.\n",
2373          GCPP_2s (es->path));
2374     es->duplicate = GNUNET_YES;
2375     return;
2376   }
2377   ct_desirability = GCPP_get_desirability (ps);
2378   ct_length = GCPP_get_length (ps);
2379   metrics = GCC_get_metrics (cc);
2380   uptime = GNUNET_TIME_absolute_get_duration (metrics->age);
2381   last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use);
2382   /* We add 1.0 here to avoid division by zero. */
2383   success_rate = (metrics->num_acked_transmissions + 1.0) / (metrics->num_successes + 1.0);
2384   score
2385     = ct_desirability
2386     + 100.0 / (1.0 + ct_length) /* longer paths = better */
2387     + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */
2388     - last_use.rel_value_us / 1000L;          /* longer idle = worse */
2389   score *= success_rate;        /* weigh overall by success rate */
2390
2391   if ( (NULL == es->worst) ||
2392        (score < es->worst_score) )
2393   {
2394     es->worst = ct;
2395     es->worst_score = score;
2396   }
2397   es->min_length = GNUNET_MIN (es->min_length,
2398                                ct_length);
2399   es->max_length = GNUNET_MAX (es->max_length,
2400                                ct_length);
2401   es->min_desire = GNUNET_MIN (es->min_desire,
2402                                ct_desirability);
2403   es->max_desire = GNUNET_MAX (es->max_desire,
2404                                ct_desirability);
2405 }
2406
2407
2408 /**
2409  * Consider using the path @a p for the tunnel @a t.
2410  * The tunnel destination is at offset @a off in path @a p.
2411  *
2412  * @param cls our tunnel
2413  * @param path a path to our destination
2414  * @param off offset of the destination on path @a path
2415  * @return #GNUNET_YES (should keep iterating)
2416  */
2417 static int
2418 consider_path_cb (void *cls,
2419                   struct CadetPeerPath *path,
2420                   unsigned int off)
2421 {
2422   struct CadetTunnel *t = cls;
2423   struct EvaluationSummary es;
2424   struct CadetTConnection *ct;
2425
2426   GNUNET_assert (off < GCPP_get_length (path));
2427   es.min_length = UINT_MAX;
2428   es.max_length = 0;
2429   es.max_desire = 0;
2430   es.min_desire = UINT64_MAX;
2431   es.path = path;
2432   es.duplicate = GNUNET_NO;
2433   es.worst = NULL;
2434
2435   /* Compute evaluation summary over existing connections. */
2436   GCT_iterate_connections (t,
2437                            &evaluate_connection,
2438                            &es);
2439   if (GNUNET_YES == es.duplicate)
2440     return GNUNET_YES;
2441
2442   /* FIXME: not sure we should really just count
2443      'num_connections' here, as they may all have
2444      consistently failed to connect. */
2445
2446   /* We iterate by increasing path length; if we have enough paths and
2447      this one is more than twice as long than what we are currently
2448      using, then ignore all of these super-long ones! */
2449   if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) &&
2450        (es.min_length * 2 < off) &&
2451        (es.max_length < off) )
2452   {
2453     LOG (GNUNET_ERROR_TYPE_DEBUG,
2454          "Ignoring paths of length %u, they are way too long.\n",
2455          es.min_length * 2);
2456     return GNUNET_NO;
2457   }
2458   /* If we have enough paths and this one looks no better, ignore it. */
2459   if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
2460        (es.min_length < GCPP_get_length (path)) &&
2461        (es.min_desire > GCPP_get_desirability (path)) &&
2462        (es.max_length < off) )
2463   {
2464     LOG (GNUNET_ERROR_TYPE_DEBUG,
2465          "Ignoring path (%u/%llu) to %s, got something better already.\n",
2466          GCPP_get_length (path),
2467          (unsigned long long) GCPP_get_desirability (path),
2468          GCP_2s (t->destination));
2469     return GNUNET_YES;
2470   }
2471
2472   /* Path is interesting (better by some metric, or we don't have
2473      enough paths yet). */
2474   ct = GNUNET_new (struct CadetTConnection);
2475   ct->created = GNUNET_TIME_absolute_get ();
2476   ct->t = t;
2477   ct->cc = GCC_create (t->destination,
2478                        path,
2479                        off,
2480                        GNUNET_CADET_OPTION_DEFAULT, /* FIXME: set based on what channels want/need! */
2481                        ct,
2482                        &connection_ready_cb,
2483                        ct);
2484
2485   /* FIXME: schedule job to kill connection (and path?)  if it takes
2486      too long to get ready! (And track performance data on how long
2487      other connections took with the tunnel!)
2488      => Note: to be done within 'connection'-logic! */
2489   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2490                                t->connection_busy_tail,
2491                                ct);
2492   t->num_busy_connections++;
2493   LOG (GNUNET_ERROR_TYPE_DEBUG,
2494        "Found interesting path %s for %s, created %s\n",
2495        GCPP_2s (path),
2496        GCT_2s (t),
2497        GCC_2s (ct->cc));
2498   return GNUNET_YES;
2499 }
2500
2501
2502 /**
2503  * Function called to maintain the connections underlying our tunnel.
2504  * Tries to maintain (incl. tear down) connections for the tunnel, and
2505  * if there is a significant change, may trigger transmissions.
2506  *
2507  * Basically, needs to check if there are connections that perform
2508  * badly, and if so eventually kill them and trigger a replacement.
2509  * The strategy is to open one more connection than
2510  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
2511  * least-performing one, and then inquire for new ones.
2512  *
2513  * @param cls the `struct CadetTunnel`
2514  */
2515 static void
2516 maintain_connections_cb (void *cls)
2517 {
2518   struct CadetTunnel *t = cls;
2519   struct GNUNET_TIME_Relative delay;
2520   struct EvaluationSummary es;
2521
2522   t->maintain_connections_task = NULL;
2523   LOG (GNUNET_ERROR_TYPE_DEBUG,
2524        "Performing connection maintenance for %s.\n",
2525        GCT_2s (t));
2526
2527   es.min_length = UINT_MAX;
2528   es.max_length = 0;
2529   es.max_desire = 0;
2530   es.min_desire = UINT64_MAX;
2531   es.path = NULL;
2532   es.worst = NULL;
2533   es.duplicate = GNUNET_NO;
2534   GCT_iterate_connections (t,
2535                            &evaluate_connection,
2536                            &es);
2537   if ( (NULL != es.worst) &&
2538        (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) )
2539   {
2540     /* Clear out worst-performing connection 'es.worst'. */
2541     destroy_t_connection (t,
2542                           es.worst);
2543   }
2544
2545   /* Consider additional paths */
2546   (void) GCP_iterate_paths (t->destination,
2547                             &consider_path_cb,
2548                             t);
2549
2550   /* FIXME: calculate when to try again based on how well we are doing;
2551      in particular, if we have to few connections, we might be able
2552      to do without this (as PATHS should tell us whenever a new path
2553      is available instantly; however, need to make sure this job is
2554      restarted after that happens).
2555      Furthermore, if the paths we do know are in a reasonably narrow
2556      quality band and are plentyful, we might also consider us stabilized
2557      and then reduce the frequency accordingly.  */
2558   delay = GNUNET_TIME_UNIT_MINUTES;
2559   t->maintain_connections_task
2560     = GNUNET_SCHEDULER_add_delayed (delay,
2561                                     &maintain_connections_cb,
2562                                     t);
2563 }
2564
2565
2566 /**
2567  * Consider using the path @a p for the tunnel @a t.
2568  * The tunnel destination is at offset @a off in path @a p.
2569  *
2570  * @param cls our tunnel
2571  * @param path a path to our destination
2572  * @param off offset of the destination on path @a path
2573  */
2574 void
2575 GCT_consider_path (struct CadetTunnel *t,
2576                    struct CadetPeerPath *p,
2577                    unsigned int off)
2578 {
2579   LOG (GNUNET_ERROR_TYPE_DEBUG,
2580        "Considering %s for %s\n",
2581        GCPP_2s (p),
2582        GCT_2s (t));
2583   (void) consider_path_cb (t,
2584                            p,
2585                            off);
2586 }
2587
2588
2589 /**
2590  * We got a keepalive. Track in statistics.
2591  *
2592  * @param cls the `struct CadetTunnel` for which we decrypted the message
2593  * @param msg  the message we received on the tunnel
2594  */
2595 static void
2596 handle_plaintext_keepalive (void *cls,
2597                             const struct GNUNET_MessageHeader *msg)
2598 {
2599   struct CadetTunnel *t = cls;
2600
2601   LOG (GNUNET_ERROR_TYPE_DEBUG,
2602        "Received KEEPALIVE on %s\n",
2603        GCT_2s (t));
2604   GNUNET_STATISTICS_update (stats,
2605                             "# keepalives received",
2606                             1,
2607                             GNUNET_NO);
2608 }
2609
2610
2611 /**
2612  * Check that @a msg is well-formed.
2613  *
2614  * @param cls the `struct CadetTunnel` for which we decrypted the message
2615  * @param msg  the message we received on the tunnel
2616  * @return #GNUNET_OK (any variable-size payload goes)
2617  */
2618 static int
2619 check_plaintext_data (void *cls,
2620                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2621 {
2622   return GNUNET_OK;
2623 }
2624
2625
2626 /**
2627  * We received payload data for a channel.  Locate the channel
2628  * and process the data, or return an error if the channel is unknown.
2629  *
2630  * @param cls the `struct CadetTunnel` for which we decrypted the message
2631  * @param msg the message we received on the tunnel
2632  */
2633 static void
2634 handle_plaintext_data (void *cls,
2635                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2636 {
2637   struct CadetTunnel *t = cls;
2638   struct CadetChannel *ch;
2639
2640   ch = lookup_channel (t,
2641                        msg->ctn);
2642   if (NULL == ch)
2643   {
2644     /* We don't know about such a channel, might have been destroyed on our
2645        end in the meantime, or never existed. Send back a DESTROY. */
2646     LOG (GNUNET_ERROR_TYPE_DEBUG,
2647          "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
2648          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2649          ntohl (msg->ctn.cn));
2650     GCT_send_channel_destroy (t,
2651                               msg->ctn);
2652     return;
2653   }
2654   GCCH_handle_channel_plaintext_data (ch,
2655                                       GCC_get_id (t->current_ct->cc),
2656                                       msg);
2657 }
2658
2659
2660 /**
2661  * We received an acknowledgement for data we sent on a channel.
2662  * Locate the channel and process it, or return an error if the
2663  * channel is unknown.
2664  *
2665  * @param cls the `struct CadetTunnel` for which we decrypted the message
2666  * @param ack the message we received on the tunnel
2667  */
2668 static void
2669 handle_plaintext_data_ack (void *cls,
2670                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2671 {
2672   struct CadetTunnel *t = cls;
2673   struct CadetChannel *ch;
2674
2675   ch = lookup_channel (t,
2676                        ack->ctn);
2677   if (NULL == ch)
2678   {
2679     /* We don't know about such a channel, might have been destroyed on our
2680        end in the meantime, or never existed. Send back a DESTROY. */
2681     LOG (GNUNET_ERROR_TYPE_DEBUG,
2682          "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
2683          ntohl (ack->ctn.cn));
2684     GCT_send_channel_destroy (t,
2685                               ack->ctn);
2686     return;
2687   }
2688   GCCH_handle_channel_plaintext_data_ack (ch,
2689                                           GCC_get_id (t->current_ct->cc),
2690                                           ack);
2691 }
2692
2693
2694 /**
2695  * We have received a request to open a channel to a port from
2696  * another peer.  Creates the incoming channel.
2697  *
2698  * @param cls the `struct CadetTunnel` for which we decrypted the message
2699  * @param copen the message we received on the tunnel
2700  */
2701 static void
2702 handle_plaintext_channel_open (void *cls,
2703                                const struct GNUNET_CADET_ChannelOpenMessage *copen)
2704 {
2705   struct CadetTunnel *t = cls;
2706   struct CadetChannel *ch;
2707
2708   ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2709                                             ntohl (copen->ctn.cn));
2710   if (NULL != ch)
2711   {
2712     LOG (GNUNET_ERROR_TYPE_DEBUG,
2713          "Received duplicate channel CHANNEL_OPEN on port %s from %s (%s), resending ACK\n",
2714          GNUNET_h2s (&copen->port),
2715          GCT_2s (t),
2716          GCCH_2s (ch));
2717     GCCH_handle_duplicate_open (ch,
2718                                 GCC_get_id (t->current_ct->cc));
2719     return;
2720   }
2721   LOG (GNUNET_ERROR_TYPE_DEBUG,
2722        "Received CHANNEL_OPEN on port %s from %s\n",
2723        GNUNET_h2s (&copen->port),
2724        GCT_2s (t));
2725   ch = GCCH_channel_incoming_new (t,
2726                                   copen->ctn,
2727                                   &copen->port,
2728                                   ntohl (copen->opt));
2729   if (NULL != t->destroy_task)
2730   {
2731     GNUNET_SCHEDULER_cancel (t->destroy_task);
2732     t->destroy_task = NULL;
2733   }
2734   GNUNET_assert (GNUNET_OK ==
2735                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2736                                                       ntohl (copen->ctn.cn),
2737                                                       ch,
2738                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2739 }
2740
2741
2742 /**
2743  * Send a DESTROY message via the tunnel.
2744  *
2745  * @param t the tunnel to transmit over
2746  * @param ctn ID of the channel to destroy
2747  */
2748 void
2749 GCT_send_channel_destroy (struct CadetTunnel *t,
2750                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
2751 {
2752   struct GNUNET_CADET_ChannelManageMessage msg;
2753
2754   LOG (GNUNET_ERROR_TYPE_DEBUG,
2755        "Sending DESTORY message for channel ID %u\n",
2756        ntohl (ctn.cn));
2757   msg.header.size = htons (sizeof (msg));
2758   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2759   msg.reserved = htonl (0);
2760   msg.ctn = ctn;
2761   GCT_send (t,
2762             &msg.header,
2763             NULL,
2764             NULL);
2765 }
2766
2767
2768 /**
2769  * We have received confirmation from the target peer that the
2770  * given channel could be established (the port is open).
2771  * Tell the client.
2772  *
2773  * @param cls the `struct CadetTunnel` for which we decrypted the message
2774  * @param cm the message we received on the tunnel
2775  */
2776 static void
2777 handle_plaintext_channel_open_ack (void *cls,
2778                                    const struct GNUNET_CADET_ChannelManageMessage *cm)
2779 {
2780   struct CadetTunnel *t = cls;
2781   struct CadetChannel *ch;
2782
2783   ch = lookup_channel (t,
2784                        cm->ctn);
2785   if (NULL == ch)
2786   {
2787     /* We don't know about such a channel, might have been destroyed on our
2788        end in the meantime, or never existed. Send back a DESTROY. */
2789     LOG (GNUNET_ERROR_TYPE_DEBUG,
2790          "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2791          ntohl (cm->ctn.cn));
2792     GCT_send_channel_destroy (t,
2793                               cm->ctn);
2794     return;
2795   }
2796   LOG (GNUNET_ERROR_TYPE_DEBUG,
2797        "Received channel OPEN_ACK on channel %s from %s\n",
2798        GCCH_2s (ch),
2799        GCT_2s (t));
2800   GCCH_handle_channel_open_ack (ch,
2801                                 GCC_get_id (t->current_ct->cc));
2802 }
2803
2804
2805 /**
2806  * We received a message saying that a channel should be destroyed.
2807  * Pass it on to the correct channel.
2808  *
2809  * @param cls the `struct CadetTunnel` for which we decrypted the message
2810  * @param cm the message we received on the tunnel
2811  */
2812 static void
2813 handle_plaintext_channel_destroy (void *cls,
2814                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
2815 {
2816   struct CadetTunnel *t = cls;
2817   struct CadetChannel *ch;
2818
2819   ch = lookup_channel (t,
2820                        cm->ctn);
2821   if (NULL == ch)
2822   {
2823     /* We don't know about such a channel, might have been destroyed on our
2824        end in the meantime, or never existed. */
2825     LOG (GNUNET_ERROR_TYPE_DEBUG,
2826          "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2827          ntohl (cm->ctn.cn));
2828     return;
2829   }
2830   LOG (GNUNET_ERROR_TYPE_DEBUG,
2831        "Received channel DESTROY on %s from %s\n",
2832        GCCH_2s (ch),
2833        GCT_2s (t));
2834   GCCH_handle_remote_destroy (ch,
2835                               GCC_get_id (t->current_ct->cc));
2836 }
2837
2838
2839 /**
2840  * Handles a message we decrypted, by injecting it into
2841  * our message queue (which will do the dispatching).
2842  *
2843  * @param cls the `struct CadetTunnel` that got the message
2844  * @param msg the message
2845  * @return #GNUNET_OK (continue to process)
2846  */
2847 static int
2848 handle_decrypted (void *cls,
2849                   const struct GNUNET_MessageHeader *msg)
2850 {
2851   struct CadetTunnel *t = cls;
2852
2853   GNUNET_assert (NULL != t->current_ct);
2854   GNUNET_MQ_inject_message (t->mq,
2855                             msg);
2856   return GNUNET_OK;
2857 }
2858
2859
2860 /**
2861  * Function called if we had an error processing
2862  * an incoming decrypted message.
2863  *
2864  * @param cls the `struct CadetTunnel`
2865  * @param error error code
2866  */
2867 static void
2868 decrypted_error_cb (void *cls,
2869                     enum GNUNET_MQ_Error error)
2870 {
2871   GNUNET_break_op (0);
2872 }
2873
2874
2875 /**
2876  * Create a tunnel to @a destionation.  Must only be called
2877  * from within #GCP_get_tunnel().
2878  *
2879  * @param destination where to create the tunnel to
2880  * @return new tunnel to @a destination
2881  */
2882 struct CadetTunnel *
2883 GCT_create_tunnel (struct CadetPeer *destination)
2884 {
2885   struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2886   struct GNUNET_MQ_MessageHandler handlers[] = {
2887     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2888                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2889                              struct GNUNET_MessageHeader,
2890                              t),
2891     GNUNET_MQ_hd_var_size (plaintext_data,
2892                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2893                            struct GNUNET_CADET_ChannelAppDataMessage,
2894                            t),
2895     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2896                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2897                              struct GNUNET_CADET_ChannelDataAckMessage,
2898                              t),
2899     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2900                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2901                              struct GNUNET_CADET_ChannelOpenMessage,
2902                              t),
2903     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2904                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2905                              struct GNUNET_CADET_ChannelManageMessage,
2906                              t),
2907     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2908                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2909                              struct GNUNET_CADET_ChannelManageMessage,
2910                              t),
2911     GNUNET_MQ_handler_end ()
2912   };
2913
2914   t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2915   new_ephemeral (&t->ax);
2916   GNUNET_assert (GNUNET_OK ==
2917                  GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0));
2918   t->destination = destination;
2919   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2920   t->maintain_connections_task
2921     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2922                                 t);
2923   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2924                                          NULL,
2925                                          NULL,
2926                                          NULL,
2927                                          handlers,
2928                                          &decrypted_error_cb,
2929                                          t);
2930   t->mst = GNUNET_MST_create (&handle_decrypted,
2931                               t);
2932   return t;
2933 }
2934
2935
2936 /**
2937  * Add a @a connection to the @a tunnel.
2938  *
2939  * @param t a tunnel
2940  * @param cid connection identifer to use for the connection
2941  * @param options options for the connection
2942  * @param path path to use for the connection
2943  * @return #GNUNET_OK on success,
2944  *         #GNUNET_SYSERR on failure (duplicate connection)
2945  */
2946 int
2947 GCT_add_inbound_connection (struct CadetTunnel *t,
2948                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2949                             enum GNUNET_CADET_ChannelOption options,
2950                             struct CadetPeerPath *path)
2951 {
2952   struct CadetTConnection *ct;
2953
2954   ct = GNUNET_new (struct CadetTConnection);
2955   ct->created = GNUNET_TIME_absolute_get ();
2956   ct->t = t;
2957   ct->cc = GCC_create_inbound (t->destination,
2958                                path,
2959                                options,
2960                                ct,
2961                                cid,
2962                                &connection_ready_cb,
2963                                ct);
2964   if (NULL == ct->cc)
2965   {
2966     LOG (GNUNET_ERROR_TYPE_DEBUG,
2967          "%s refused inbound %s (duplicate)\n",
2968          GCT_2s (t),
2969          GCC_2s (ct->cc));
2970     GNUNET_free (ct);
2971     return GNUNET_SYSERR;
2972   }
2973   /* FIXME: schedule job to kill connection (and path?)  if it takes
2974      too long to get ready! (And track performance data on how long
2975      other connections took with the tunnel!)
2976      => Note: to be done within 'connection'-logic! */
2977   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2978                                t->connection_busy_tail,
2979                                ct);
2980   t->num_busy_connections++;
2981   LOG (GNUNET_ERROR_TYPE_DEBUG,
2982        "%s has new %s\n",
2983        GCT_2s (t),
2984        GCC_2s (ct->cc));
2985   return GNUNET_OK;
2986 }
2987
2988
2989 /**
2990  * Handle encrypted message.
2991  *
2992  * @param ct connection/tunnel combo that received encrypted message
2993  * @param msg the encrypted message to decrypt
2994  */
2995 void
2996 GCT_handle_encrypted (struct CadetTConnection *ct,
2997                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2998 {
2999   struct CadetTunnel *t = ct->t;
3000   uint16_t size = ntohs (msg->header.size);
3001   char cbuf [size] GNUNET_ALIGN;
3002   ssize_t decrypted_size;
3003
3004   LOG (GNUNET_ERROR_TYPE_DEBUG,
3005        "%s received %u bytes of encrypted data in state %d\n",
3006        GCT_2s (t),
3007        (unsigned int) size,
3008        t->estate);
3009
3010   switch (t->estate)
3011   {
3012   case CADET_TUNNEL_KEY_UNINITIALIZED:
3013   case CADET_TUNNEL_KEY_AX_RECV:
3014     /* We did not even SEND our KX, how can the other peer
3015        send us encrypted data? Must have been that we went
3016        down and the other peer still things we are up.
3017        Let's send it KX back. */
3018     GNUNET_STATISTICS_update (stats,
3019                               "# received encrypted without any KX",
3020                               1,
3021                               GNUNET_NO);
3022     if (NULL != t->kx_task)
3023     {
3024       GNUNET_SCHEDULER_cancel (t->kx_task);
3025       t->kx_task = NULL;
3026     }
3027     send_kx (t,
3028              ct,
3029              &t->ax);
3030     return;
3031   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
3032     /* We send KX, and other peer send KX to us at the same time.
3033        Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
3034     GNUNET_STATISTICS_update (stats,
3035                               "# received encrypted without KX_AUTH",
3036                               1,
3037                               GNUNET_NO);
3038     if (NULL != t->kx_task)
3039     {
3040       GNUNET_SCHEDULER_cancel (t->kx_task);
3041       t->kx_task = NULL;
3042     }
3043     send_kx_auth (t,
3044                   ct,
3045                   &t->ax,
3046                   GNUNET_YES);
3047     return;
3048   case CADET_TUNNEL_KEY_AX_SENT:
3049     /* We did not get the KX of the other peer, but that
3050        might have been lost.  Send our KX again immediately. */
3051     GNUNET_STATISTICS_update (stats,
3052                               "# received encrypted without KX",
3053                               1,
3054                               GNUNET_NO);
3055     if (NULL != t->kx_task)
3056     {
3057       GNUNET_SCHEDULER_cancel (t->kx_task);
3058       t->kx_task = NULL;
3059     }
3060     send_kx (t,
3061              ct,
3062              &t->ax);
3063     return;
3064   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3065     /* Great, first payload, we might graduate to OK! */
3066   case CADET_TUNNEL_KEY_OK:
3067     /* We are up and running, all good. */
3068     break;
3069   }
3070
3071   GNUNET_STATISTICS_update (stats,
3072                             "# received encrypted",
3073                             1,
3074                             GNUNET_NO);
3075   decrypted_size = -1;
3076   if (CADET_TUNNEL_KEY_OK == t->estate)
3077   {
3078     /* We have well-established key material available,
3079        try that. (This is the common case.) */
3080     decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3081                                                 cbuf,
3082                                                 msg,
3083                                                 size);
3084   }
3085
3086   if ( (-1 == decrypted_size) &&
3087        (NULL != t->unverified_ax) )
3088   {
3089     /* We have un-authenticated KX material available. We should try
3090        this as a back-up option, in case the sender crashed and
3091        switched keys. */
3092     decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3093                                                 cbuf,
3094                                                 msg,
3095                                                 size);
3096     if (-1 != decrypted_size)
3097     {
3098       /* It worked! Treat this as authentication of the AX data! */
3099       cleanup_ax (&t->ax);
3100       t->ax = *t->unverified_ax;
3101       GNUNET_free (t->unverified_ax);
3102       t->unverified_ax = NULL;
3103     }
3104     if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3105     {
3106       /* First time it worked, move tunnel into production! */
3107       GCT_change_estate (t,
3108                          CADET_TUNNEL_KEY_OK);
3109       if (NULL != t->send_task)
3110         GNUNET_SCHEDULER_cancel (t->send_task);
3111       t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3112                                                t);
3113     }
3114   }
3115   if (NULL != t->unverified_ax)
3116   {
3117     /* We had unverified KX material that was useless; so increment
3118        counter and eventually move to ignore it.  Note that we even do
3119        this increment if we successfully decrypted with the old KX
3120        material and thus didn't even both with the new one.  This is
3121        the ideal case, as a malicious injection of bogus KX data
3122        basically only causes us to increment a counter a few times. */
3123     t->unverified_attempts++;
3124     LOG (GNUNET_ERROR_TYPE_DEBUG,
3125          "Failed to decrypt message with unverified KX data %u times\n",
3126          t->unverified_attempts);
3127     if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3128     {
3129       cleanup_ax (t->unverified_ax);
3130       GNUNET_free (t->unverified_ax);
3131       t->unverified_ax = NULL;
3132     }
3133   }
3134
3135   if (-1 == decrypted_size)
3136   {
3137     /* Decryption failed for good, complain. */
3138     LOG (GNUNET_ERROR_TYPE_WARNING,
3139          "%s failed to decrypt and validate encrypted data, retrying KX\n",
3140          GCT_2s (t));
3141     GNUNET_STATISTICS_update (stats,
3142                               "# unable to decrypt",
3143                               1,
3144                               GNUNET_NO);
3145     if (NULL != t->kx_task)
3146     {
3147       GNUNET_SCHEDULER_cancel (t->kx_task);
3148       t->kx_task = NULL;
3149     }
3150     send_kx (t,
3151              ct,
3152              &t->ax);
3153     return;
3154   }
3155
3156   /* The MST will ultimately call #handle_decrypted() on each message. */
3157   t->current_ct = ct;
3158   GNUNET_break_op (GNUNET_OK ==
3159                    GNUNET_MST_from_buffer (t->mst,
3160                                            cbuf,
3161                                            decrypted_size,
3162                                            GNUNET_YES,
3163                                            GNUNET_NO));
3164   t->current_ct = NULL;
3165 }
3166
3167
3168 /**
3169  * Sends an already built message on a tunnel, encrypting it and
3170  * choosing the best connection if not provided.
3171  *
3172  * @param message Message to send. Function modifies it.
3173  * @param t Tunnel on which this message is transmitted.
3174  * @param cont Continuation to call once message is really sent.
3175  * @param cont_cls Closure for @c cont.
3176  * @return Handle to cancel message
3177  */
3178 struct CadetTunnelQueueEntry *
3179 GCT_send (struct CadetTunnel *t,
3180           const struct GNUNET_MessageHeader *message,
3181           GCT_SendContinuation cont,
3182           void *cont_cls)
3183 {
3184   struct CadetTunnelQueueEntry *tq;
3185   uint16_t payload_size;
3186   struct GNUNET_MQ_Envelope *env;
3187   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3188
3189   if (CADET_TUNNEL_KEY_OK != t->estate)
3190   {
3191     GNUNET_break (0);
3192     return NULL;
3193   }
3194   payload_size = ntohs (message->size);
3195   LOG (GNUNET_ERROR_TYPE_DEBUG,
3196        "Encrypting %u bytes for %s\n",
3197        (unsigned int) payload_size,
3198        GCT_2s (t));
3199   env = GNUNET_MQ_msg_extra (ax_msg,
3200                              payload_size,
3201                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3202   t_ax_encrypt (&t->ax,
3203                 &ax_msg[1],
3204                 message,
3205                 payload_size);
3206   ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3207   ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3208   /* FIXME: we should do this once, not once per message;
3209      this is a point multiplication, and DHRs does not
3210      change all the time. */
3211   GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
3212                                       &ax_msg->ax_header.DHRs);
3213   t_h_encrypt (&t->ax,
3214                ax_msg);
3215   t_hmac (&ax_msg->ax_header,
3216           sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3217           0,
3218           &t->ax.HKs,
3219           &ax_msg->hmac);
3220
3221   tq = GNUNET_malloc (sizeof (*tq));
3222   tq->t = t;
3223   tq->env = env;
3224   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3225   tq->cont = cont;
3226   tq->cont_cls = cont_cls;
3227   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3228                                     t->tq_tail,
3229                                     tq);
3230   if (NULL != t->send_task)
3231     GNUNET_SCHEDULER_cancel (t->send_task);
3232   t->send_task
3233     = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3234                                 t);
3235   return tq;
3236 }
3237
3238
3239 /**
3240  * Cancel a previously sent message while it's in the queue.
3241  *
3242  * ONLY can be called before the continuation given to the send
3243  * function is called. Once the continuation is called, the message is
3244  * no longer in the queue!
3245  *
3246  * @param tq Handle to the queue entry to cancel.
3247  */
3248 void
3249 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3250 {
3251   struct CadetTunnel *t = tq->t;
3252
3253   GNUNET_CONTAINER_DLL_remove (t->tq_head,
3254                                t->tq_tail,
3255                                tq);
3256   GNUNET_MQ_discard (tq->env);
3257   GNUNET_free (tq);
3258 }
3259
3260
3261 /**
3262  * Iterate over all connections of a tunnel.
3263  *
3264  * @param t Tunnel whose connections to iterate.
3265  * @param iter Iterator.
3266  * @param iter_cls Closure for @c iter.
3267  */
3268 void
3269 GCT_iterate_connections (struct CadetTunnel *t,
3270                          GCT_ConnectionIterator iter,
3271                          void *iter_cls)
3272 {
3273   struct CadetTConnection *n;
3274   for (struct CadetTConnection *ct = t->connection_ready_head;
3275        NULL != ct;
3276        ct = n)
3277   {
3278     n = ct->next;
3279     iter (iter_cls,
3280           ct);
3281   }
3282   for (struct CadetTConnection *ct = t->connection_busy_head;
3283        NULL != ct;
3284        ct = n)
3285   {
3286     n = ct->next;
3287     iter (iter_cls,
3288           ct);
3289   }
3290 }
3291
3292
3293 /**
3294  * Closure for #iterate_channels_cb.
3295  */
3296 struct ChanIterCls
3297 {
3298   /**
3299    * Function to call.
3300    */
3301   GCT_ChannelIterator iter;
3302
3303   /**
3304    * Closure for @e iter.
3305    */
3306   void *iter_cls;
3307 };
3308
3309
3310 /**
3311  * Helper function for #GCT_iterate_channels.
3312  *
3313  * @param cls the `struct ChanIterCls`
3314  * @param key unused
3315  * @param value a `struct CadetChannel`
3316  * @return #GNUNET_OK
3317  */
3318 static int
3319 iterate_channels_cb (void *cls,
3320                      uint32_t key,
3321                      void *value)
3322 {
3323   struct ChanIterCls *ctx = cls;
3324   struct CadetChannel *ch = value;
3325
3326   ctx->iter (ctx->iter_cls,
3327              ch);
3328   return GNUNET_OK;
3329 }
3330
3331
3332 /**
3333  * Iterate over all channels of a tunnel.
3334  *
3335  * @param t Tunnel whose channels to iterate.
3336  * @param iter Iterator.
3337  * @param iter_cls Closure for @c iter.
3338  */
3339 void
3340 GCT_iterate_channels (struct CadetTunnel *t,
3341                       GCT_ChannelIterator iter,
3342                       void *iter_cls)
3343 {
3344   struct ChanIterCls ctx;
3345
3346   ctx.iter = iter;
3347   ctx.iter_cls = iter_cls;
3348   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3349                                            &iterate_channels_cb,
3350                                            &ctx);
3351
3352 }
3353
3354
3355 /**
3356  * Call #GCCH_debug() on a channel.
3357  *
3358  * @param cls points to the log level to use
3359  * @param key unused
3360  * @param value the `struct CadetChannel` to dump
3361  * @return #GNUNET_OK (continue iteration)
3362  */
3363 static int
3364 debug_channel (void *cls,
3365                uint32_t key,
3366                void *value)
3367 {
3368   const enum GNUNET_ErrorType *level = cls;
3369   struct CadetChannel *ch = value;
3370
3371   GCCH_debug (ch, *level);
3372   return GNUNET_OK;
3373 }
3374
3375
3376 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3377
3378
3379 /**
3380  * Log all possible info about the tunnel state.
3381  *
3382  * @param t Tunnel to debug.
3383  * @param level Debug level to use.
3384  */
3385 void
3386 GCT_debug (const struct CadetTunnel *t,
3387            enum GNUNET_ErrorType level)
3388 {
3389   struct CadetTConnection *iter_c;
3390   int do_log;
3391
3392   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3393                                        "cadet-tun",
3394                                        __FILE__, __FUNCTION__, __LINE__);
3395   if (0 == do_log)
3396     return;
3397
3398   LOG2 (level,
3399         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3400         GCT_2s (t),
3401         estate2s (t->estate),
3402         t->tq_len,
3403         GCT_count_any_connections (t));
3404   LOG2 (level,
3405         "TTT channels:\n");
3406   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3407                                            &debug_channel,
3408                                            &level);
3409   LOG2 (level,
3410         "TTT connections:\n");
3411   for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3412     GCC_debug (iter_c->cc,
3413                level);
3414   for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3415     GCC_debug (iter_c->cc,
3416                level);
3417
3418   LOG2 (level,
3419         "TTT TUNNEL END\n");
3420 }
3421
3422
3423 /* end of gnunet-service-cadet-new_tunnels.c */