spell out message types more, use correct conversion direction
[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 using %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))
1892   {
1893     ctn = ((ctn + 1) & (~ HIGH_BIT)) | highbit;
1894   }
1895   t->next_ctn.cn = htonl (((ctn + 1) & (~ HIGH_BIT)) | highbit);
1896   ret.cn = htonl (ctn);
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   (void) consider_path_cb (t,
2580                            p,
2581                            off);
2582 }
2583
2584
2585 /**
2586  * We got a keepalive. Track in statistics.
2587  *
2588  * @param cls the `struct CadetTunnel` for which we decrypted the message
2589  * @param msg  the message we received on the tunnel
2590  */
2591 static void
2592 handle_plaintext_keepalive (void *cls,
2593                             const struct GNUNET_MessageHeader *msg)
2594 {
2595   struct CadetTunnel *t = cls;
2596
2597   LOG (GNUNET_ERROR_TYPE_DEBUG,
2598        "Received KEEPALIVE on %s\n",
2599        GCT_2s (t));
2600   GNUNET_STATISTICS_update (stats,
2601                             "# keepalives received",
2602                             1,
2603                             GNUNET_NO);
2604 }
2605
2606
2607 /**
2608  * Check that @a msg is well-formed.
2609  *
2610  * @param cls the `struct CadetTunnel` for which we decrypted the message
2611  * @param msg  the message we received on the tunnel
2612  * @return #GNUNET_OK (any variable-size payload goes)
2613  */
2614 static int
2615 check_plaintext_data (void *cls,
2616                       const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2617 {
2618   return GNUNET_OK;
2619 }
2620
2621
2622 /**
2623  * We received payload data for a channel.  Locate the channel
2624  * and process the data, or return an error if the channel is unknown.
2625  *
2626  * @param cls the `struct CadetTunnel` for which we decrypted the message
2627  * @param msg the message we received on the tunnel
2628  */
2629 static void
2630 handle_plaintext_data (void *cls,
2631                        const struct GNUNET_CADET_ChannelAppDataMessage *msg)
2632 {
2633   struct CadetTunnel *t = cls;
2634   struct CadetChannel *ch;
2635
2636   ch = lookup_channel (t,
2637                        msg->ctn);
2638   if (NULL == ch)
2639   {
2640     /* We don't know about such a channel, might have been destroyed on our
2641        end in the meantime, or never existed. Send back a DESTROY. */
2642     LOG (GNUNET_ERROR_TYPE_DEBUG,
2643          "Received %u bytes of application data for unknown channel %u, sending DESTROY\n",
2644          (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)),
2645          ntohl (msg->ctn.cn));
2646     GCT_send_channel_destroy (t,
2647                               msg->ctn);
2648     return;
2649   }
2650   GCCH_handle_channel_plaintext_data (ch,
2651                                       GCC_get_id (t->current_ct->cc),
2652                                       msg);
2653 }
2654
2655
2656 /**
2657  * We received an acknowledgement for data we sent on a channel.
2658  * Locate the channel and process it, or return an error if the
2659  * channel is unknown.
2660  *
2661  * @param cls the `struct CadetTunnel` for which we decrypted the message
2662  * @param ack the message we received on the tunnel
2663  */
2664 static void
2665 handle_plaintext_data_ack (void *cls,
2666                            const struct GNUNET_CADET_ChannelDataAckMessage *ack)
2667 {
2668   struct CadetTunnel *t = cls;
2669   struct CadetChannel *ch;
2670
2671   ch = lookup_channel (t,
2672                        ack->ctn);
2673   if (NULL == ch)
2674   {
2675     /* We don't know about such a channel, might have been destroyed on our
2676        end in the meantime, or never existed. Send back a DESTROY. */
2677     LOG (GNUNET_ERROR_TYPE_DEBUG,
2678          "Received DATA_ACK for unknown channel %u, sending DESTROY\n",
2679          ntohl (ack->ctn.cn));
2680     GCT_send_channel_destroy (t,
2681                               ack->ctn);
2682     return;
2683   }
2684   GCCH_handle_channel_plaintext_data_ack (ch,
2685                                           GCC_get_id (t->current_ct->cc),
2686                                           ack);
2687 }
2688
2689
2690 /**
2691  * We have received a request to open a channel to a port from
2692  * another peer.  Creates the incoming channel.
2693  *
2694  * @param cls the `struct CadetTunnel` for which we decrypted the message
2695  * @param copen the message we received on the tunnel
2696  */
2697 static void
2698 handle_plaintext_channel_open (void *cls,
2699                                const struct GNUNET_CADET_ChannelOpenMessage *copen)
2700 {
2701   struct CadetTunnel *t = cls;
2702   struct CadetChannel *ch;
2703
2704   ch = GNUNET_CONTAINER_multihashmap32_get (t->channels,
2705                                             ntohl (copen->ctn.cn));
2706   if (NULL != ch)
2707   {
2708     LOG (GNUNET_ERROR_TYPE_DEBUG,
2709          "Received duplicate channel CHANNEL_OPEN on port %s from %s (%s), resending ACK\n",
2710          GNUNET_h2s (&copen->port),
2711          GCT_2s (t),
2712          GCCH_2s (ch));
2713     GCCH_handle_duplicate_open (ch,
2714                                 GCC_get_id (t->current_ct->cc));
2715     return;
2716   }
2717   LOG (GNUNET_ERROR_TYPE_DEBUG,
2718        "Received CHANNEL_OPEN on port %s from %s\n",
2719        GNUNET_h2s (&copen->port),
2720        GCT_2s (t));
2721   ch = GCCH_channel_incoming_new (t,
2722                                   copen->ctn,
2723                                   &copen->port,
2724                                   ntohl (copen->opt));
2725   if (NULL != t->destroy_task)
2726   {
2727     GNUNET_SCHEDULER_cancel (t->destroy_task);
2728     t->destroy_task = NULL;
2729   }
2730   GNUNET_assert (GNUNET_OK ==
2731                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
2732                                                       ntohl (copen->ctn.cn),
2733                                                       ch,
2734                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2735 }
2736
2737
2738 /**
2739  * Send a DESTROY message via the tunnel.
2740  *
2741  * @param t the tunnel to transmit over
2742  * @param ctn ID of the channel to destroy
2743  */
2744 void
2745 GCT_send_channel_destroy (struct CadetTunnel *t,
2746                           struct GNUNET_CADET_ChannelTunnelNumber ctn)
2747 {
2748   struct GNUNET_CADET_ChannelManageMessage msg;
2749
2750   LOG (GNUNET_ERROR_TYPE_DEBUG,
2751        "Sending DESTORY message for channel ID %u\n",
2752        ntohl (ctn.cn));
2753   msg.header.size = htons (sizeof (msg));
2754   msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY);
2755   msg.reserved = htonl (0);
2756   msg.ctn = ctn;
2757   GCT_send (t,
2758             &msg.header,
2759             NULL,
2760             NULL);
2761 }
2762
2763
2764 /**
2765  * We have received confirmation from the target peer that the
2766  * given channel could be established (the port is open).
2767  * Tell the client.
2768  *
2769  * @param cls the `struct CadetTunnel` for which we decrypted the message
2770  * @param cm the message we received on the tunnel
2771  */
2772 static void
2773 handle_plaintext_channel_open_ack (void *cls,
2774                                    const struct GNUNET_CADET_ChannelManageMessage *cm)
2775 {
2776   struct CadetTunnel *t = cls;
2777   struct CadetChannel *ch;
2778
2779   ch = lookup_channel (t,
2780                        cm->ctn);
2781   if (NULL == ch)
2782   {
2783     /* We don't know about such a channel, might have been destroyed on our
2784        end in the meantime, or never existed. Send back a DESTROY. */
2785     LOG (GNUNET_ERROR_TYPE_DEBUG,
2786          "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n",
2787          ntohl (cm->ctn.cn));
2788     GCT_send_channel_destroy (t,
2789                               cm->ctn);
2790     return;
2791   }
2792   LOG (GNUNET_ERROR_TYPE_DEBUG,
2793        "Received channel OPEN_ACK on channel %s from %s\n",
2794        GCCH_2s (ch),
2795        GCT_2s (t));
2796   GCCH_handle_channel_open_ack (ch,
2797                                 GCC_get_id (t->current_ct->cc));
2798 }
2799
2800
2801 /**
2802  * We received a message saying that a channel should be destroyed.
2803  * Pass it on to the correct channel.
2804  *
2805  * @param cls the `struct CadetTunnel` for which we decrypted the message
2806  * @param cm the message we received on the tunnel
2807  */
2808 static void
2809 handle_plaintext_channel_destroy (void *cls,
2810                                   const struct GNUNET_CADET_ChannelManageMessage *cm)
2811 {
2812   struct CadetTunnel *t = cls;
2813   struct CadetChannel *ch;
2814
2815   ch = lookup_channel (t,
2816                        cm->ctn);
2817   if (NULL == ch)
2818   {
2819     /* We don't know about such a channel, might have been destroyed on our
2820        end in the meantime, or never existed. */
2821     LOG (GNUNET_ERROR_TYPE_DEBUG,
2822          "Received channel DESTORY for unknown channel %u. Ignoring.\n",
2823          ntohl (cm->ctn.cn));
2824     return;
2825   }
2826   LOG (GNUNET_ERROR_TYPE_DEBUG,
2827        "Received channel DESTROY on %s from %s\n",
2828        GCCH_2s (ch),
2829        GCT_2s (t));
2830   GCCH_handle_remote_destroy (ch,
2831                               GCC_get_id (t->current_ct->cc));
2832 }
2833
2834
2835 /**
2836  * Handles a message we decrypted, by injecting it into
2837  * our message queue (which will do the dispatching).
2838  *
2839  * @param cls the `struct CadetTunnel` that got the message
2840  * @param msg the message
2841  * @return #GNUNET_OK (continue to process)
2842  */
2843 static int
2844 handle_decrypted (void *cls,
2845                   const struct GNUNET_MessageHeader *msg)
2846 {
2847   struct CadetTunnel *t = cls;
2848
2849   GNUNET_assert (NULL != t->current_ct);
2850   GNUNET_MQ_inject_message (t->mq,
2851                             msg);
2852   return GNUNET_OK;
2853 }
2854
2855
2856 /**
2857  * Function called if we had an error processing
2858  * an incoming decrypted message.
2859  *
2860  * @param cls the `struct CadetTunnel`
2861  * @param error error code
2862  */
2863 static void
2864 decrypted_error_cb (void *cls,
2865                     enum GNUNET_MQ_Error error)
2866 {
2867   GNUNET_break_op (0);
2868 }
2869
2870
2871 /**
2872  * Create a tunnel to @a destionation.  Must only be called
2873  * from within #GCP_get_tunnel().
2874  *
2875  * @param destination where to create the tunnel to
2876  * @return new tunnel to @a destination
2877  */
2878 struct CadetTunnel *
2879 GCT_create_tunnel (struct CadetPeer *destination)
2880 {
2881   struct CadetTunnel *t = GNUNET_new (struct CadetTunnel);
2882   struct GNUNET_MQ_MessageHandler handlers[] = {
2883     GNUNET_MQ_hd_fixed_size (plaintext_keepalive,
2884                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE,
2885                              struct GNUNET_MessageHeader,
2886                              t),
2887     GNUNET_MQ_hd_var_size (plaintext_data,
2888                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA,
2889                            struct GNUNET_CADET_ChannelAppDataMessage,
2890                            t),
2891     GNUNET_MQ_hd_fixed_size (plaintext_data_ack,
2892                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK,
2893                              struct GNUNET_CADET_ChannelDataAckMessage,
2894                              t),
2895     GNUNET_MQ_hd_fixed_size (plaintext_channel_open,
2896                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN,
2897                              struct GNUNET_CADET_ChannelOpenMessage,
2898                              t),
2899     GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack,
2900                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK,
2901                              struct GNUNET_CADET_ChannelManageMessage,
2902                              t),
2903     GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy,
2904                              GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
2905                              struct GNUNET_CADET_ChannelManageMessage,
2906                              t),
2907     GNUNET_MQ_handler_end ()
2908   };
2909
2910   t->kx_retry_delay = INITIAL_KX_RETRY_DELAY;
2911   new_ephemeral (&t->ax);
2912   GNUNET_assert (GNUNET_OK ==
2913                  GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0));
2914   t->destination = destination;
2915   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
2916   t->maintain_connections_task
2917     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
2918                                 t);
2919   t->mq = GNUNET_MQ_queue_for_callbacks (NULL,
2920                                          NULL,
2921                                          NULL,
2922                                          NULL,
2923                                          handlers,
2924                                          &decrypted_error_cb,
2925                                          t);
2926   t->mst = GNUNET_MST_create (&handle_decrypted,
2927                               t);
2928   return t;
2929 }
2930
2931
2932 /**
2933  * Add a @a connection to the @a tunnel.
2934  *
2935  * @param t a tunnel
2936  * @param cid connection identifer to use for the connection
2937  * @param options options for the connection
2938  * @param path path to use for the connection
2939  * @return #GNUNET_OK on success,
2940  *         #GNUNET_SYSERR on failure (duplicate connection)
2941  */
2942 int
2943 GCT_add_inbound_connection (struct CadetTunnel *t,
2944                             const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
2945                             enum GNUNET_CADET_ChannelOption options,
2946                             struct CadetPeerPath *path)
2947 {
2948   struct CadetTConnection *ct;
2949
2950   ct = GNUNET_new (struct CadetTConnection);
2951   ct->created = GNUNET_TIME_absolute_get ();
2952   ct->t = t;
2953   ct->cc = GCC_create_inbound (t->destination,
2954                                path,
2955                                options,
2956                                ct,
2957                                cid,
2958                                &connection_ready_cb,
2959                                ct);
2960   if (NULL == ct->cc)
2961   {
2962     LOG (GNUNET_ERROR_TYPE_DEBUG,
2963          "%s refused inbound %s (duplicate)\n",
2964          GCT_2s (t),
2965          GCC_2s (ct->cc));
2966     GNUNET_free (ct);
2967     return GNUNET_SYSERR;
2968   }
2969   /* FIXME: schedule job to kill connection (and path?)  if it takes
2970      too long to get ready! (And track performance data on how long
2971      other connections took with the tunnel!)
2972      => Note: to be done within 'connection'-logic! */
2973   GNUNET_CONTAINER_DLL_insert (t->connection_busy_head,
2974                                t->connection_busy_tail,
2975                                ct);
2976   t->num_busy_connections++;
2977   LOG (GNUNET_ERROR_TYPE_DEBUG,
2978        "%s has new %s\n",
2979        GCT_2s (t),
2980        GCC_2s (ct->cc));
2981   return GNUNET_OK;
2982 }
2983
2984
2985 /**
2986  * Handle encrypted message.
2987  *
2988  * @param ct connection/tunnel combo that received encrypted message
2989  * @param msg the encrypted message to decrypt
2990  */
2991 void
2992 GCT_handle_encrypted (struct CadetTConnection *ct,
2993                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
2994 {
2995   struct CadetTunnel *t = ct->t;
2996   uint16_t size = ntohs (msg->header.size);
2997   char cbuf [size] GNUNET_ALIGN;
2998   ssize_t decrypted_size;
2999
3000   LOG (GNUNET_ERROR_TYPE_DEBUG,
3001        "%s received %u bytes of encrypted data in state %d\n",
3002        GCT_2s (t),
3003        (unsigned int) size,
3004        t->estate);
3005
3006   switch (t->estate)
3007   {
3008   case CADET_TUNNEL_KEY_UNINITIALIZED:
3009   case CADET_TUNNEL_KEY_AX_RECV:
3010     /* We did not even SEND our KX, how can the other peer
3011        send us encrypted data? */
3012     GNUNET_break_op (0);
3013     return;
3014   case CADET_TUNNEL_KEY_AX_SENT_AND_RECV:
3015     /* We send KX, and other peer send KX to us at the same time.
3016        Neither KX is AUTH'ed, so let's try KX_AUTH this time. */
3017     GNUNET_STATISTICS_update (stats,
3018                               "# received encrypted without KX_AUTH",
3019                               1,
3020                               GNUNET_NO);
3021     if (NULL != t->kx_task)
3022     {
3023       GNUNET_SCHEDULER_cancel (t->kx_task);
3024       t->kx_task = NULL;
3025     }
3026     send_kx_auth (t,
3027                   ct,
3028                   &t->ax,
3029                   GNUNET_YES);
3030     return;
3031   case CADET_TUNNEL_KEY_AX_SENT:
3032     /* We did not get the KX of the other peer, but that
3033        might have been lost.  Send our KX again immediately. */
3034     GNUNET_STATISTICS_update (stats,
3035                               "# received encrypted without KX",
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 (t,
3044              ct,
3045              &t->ax);
3046     return;
3047   case CADET_TUNNEL_KEY_AX_AUTH_SENT:
3048     /* Great, first payload, we might graduate to OK! */
3049   case CADET_TUNNEL_KEY_OK:
3050     /* We are up and running, all good. */
3051     break;
3052   }
3053
3054   GNUNET_STATISTICS_update (stats,
3055                             "# received encrypted",
3056                             1,
3057                             GNUNET_NO);
3058   decrypted_size = -1;
3059   if (CADET_TUNNEL_KEY_OK == t->estate)
3060   {
3061     /* We have well-established key material available,
3062        try that. (This is the common case.) */
3063     decrypted_size = t_ax_decrypt_and_validate (&t->ax,
3064                                                 cbuf,
3065                                                 msg,
3066                                                 size);
3067   }
3068
3069   if ( (-1 == decrypted_size) &&
3070        (NULL != t->unverified_ax) )
3071   {
3072     /* We have un-authenticated KX material available. We should try
3073        this as a back-up option, in case the sender crashed and
3074        switched keys. */
3075     decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax,
3076                                                 cbuf,
3077                                                 msg,
3078                                                 size);
3079     if (-1 != decrypted_size)
3080     {
3081       /* It worked! Treat this as authentication of the AX data! */
3082       cleanup_ax (&t->ax);
3083       t->ax = *t->unverified_ax;
3084       GNUNET_free (t->unverified_ax);
3085       t->unverified_ax = NULL;
3086     }
3087     if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate)
3088     {
3089       /* First time it worked, move tunnel into production! */
3090       GCT_change_estate (t,
3091                          CADET_TUNNEL_KEY_OK);
3092       if (NULL != t->send_task)
3093         GNUNET_SCHEDULER_cancel (t->send_task);
3094       t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3095                                                t);
3096     }
3097   }
3098   if (NULL != t->unverified_ax)
3099   {
3100     /* We had unverified KX material that was useless; so increment
3101        counter and eventually move to ignore it.  Note that we even do
3102        this increment if we successfully decrypted with the old KX
3103        material and thus didn't even both with the new one.  This is
3104        the ideal case, as a malicious injection of bogus KX data
3105        basically only causes us to increment a counter a few times. */
3106     t->unverified_attempts++;
3107     LOG (GNUNET_ERROR_TYPE_DEBUG,
3108          "Failed to decrypt message with unverified KX data %u times\n",
3109          t->unverified_attempts);
3110     if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS)
3111     {
3112       cleanup_ax (t->unverified_ax);
3113       GNUNET_free (t->unverified_ax);
3114       t->unverified_ax = NULL;
3115     }
3116   }
3117
3118   if (-1 == decrypted_size)
3119   {
3120     /* Decryption failed for good, complain. */
3121     GNUNET_break_op (0);
3122     LOG (GNUNET_ERROR_TYPE_WARNING,
3123          "%s failed to decrypt and validate encrypted data\n",
3124          GCT_2s (t));
3125     GNUNET_STATISTICS_update (stats,
3126                               "# unable to decrypt",
3127                               1,
3128                               GNUNET_NO);
3129     return;
3130   }
3131
3132   /* The MST will ultimately call #handle_decrypted() on each message. */
3133   t->current_ct = ct;
3134   GNUNET_break_op (GNUNET_OK ==
3135                    GNUNET_MST_from_buffer (t->mst,
3136                                            cbuf,
3137                                            decrypted_size,
3138                                            GNUNET_YES,
3139                                            GNUNET_NO));
3140   t->current_ct = NULL;
3141 }
3142
3143
3144 /**
3145  * Sends an already built message on a tunnel, encrypting it and
3146  * choosing the best connection if not provided.
3147  *
3148  * @param message Message to send. Function modifies it.
3149  * @param t Tunnel on which this message is transmitted.
3150  * @param cont Continuation to call once message is really sent.
3151  * @param cont_cls Closure for @c cont.
3152  * @return Handle to cancel message
3153  */
3154 struct CadetTunnelQueueEntry *
3155 GCT_send (struct CadetTunnel *t,
3156           const struct GNUNET_MessageHeader *message,
3157           GCT_SendContinuation cont,
3158           void *cont_cls)
3159 {
3160   struct CadetTunnelQueueEntry *tq;
3161   uint16_t payload_size;
3162   struct GNUNET_MQ_Envelope *env;
3163   struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg;
3164
3165   if (CADET_TUNNEL_KEY_OK != t->estate)
3166   {
3167     GNUNET_break (0);
3168     return NULL;
3169   }
3170   payload_size = ntohs (message->size);
3171   LOG (GNUNET_ERROR_TYPE_DEBUG,
3172        "Encrypting %u bytes for %s\n",
3173        (unsigned int) payload_size,
3174        GCT_2s (t));
3175   env = GNUNET_MQ_msg_extra (ax_msg,
3176                              payload_size,
3177                              GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED);
3178   t_ax_encrypt (&t->ax,
3179                 &ax_msg[1],
3180                 message,
3181                 payload_size);
3182   ax_msg->ax_header.Ns = htonl (t->ax.Ns++);
3183   ax_msg->ax_header.PNs = htonl (t->ax.PNs);
3184   /* FIXME: we should do this once, not once per message;
3185      this is a point multiplication, and DHRs does not
3186      change all the time. */
3187   GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs,
3188                                       &ax_msg->ax_header.DHRs);
3189   t_h_encrypt (&t->ax,
3190                ax_msg);
3191   t_hmac (&ax_msg->ax_header,
3192           sizeof (struct GNUNET_CADET_AxHeader) + payload_size,
3193           0,
3194           &t->ax.HKs,
3195           &ax_msg->hmac);
3196
3197   tq = GNUNET_malloc (sizeof (*tq));
3198   tq->t = t;
3199   tq->env = env;
3200   tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */
3201   tq->cont = cont;
3202   tq->cont_cls = cont_cls;
3203   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
3204                                     t->tq_tail,
3205                                     tq);
3206   if (NULL != t->send_task)
3207     GNUNET_SCHEDULER_cancel (t->send_task);
3208   t->send_task
3209     = GNUNET_SCHEDULER_add_now (&trigger_transmissions,
3210                                 t);
3211   return tq;
3212 }
3213
3214
3215 /**
3216  * Cancel a previously sent message while it's in the queue.
3217  *
3218  * ONLY can be called before the continuation given to the send
3219  * function is called. Once the continuation is called, the message is
3220  * no longer in the queue!
3221  *
3222  * @param tq Handle to the queue entry to cancel.
3223  */
3224 void
3225 GCT_send_cancel (struct CadetTunnelQueueEntry *tq)
3226 {
3227   struct CadetTunnel *t = tq->t;
3228
3229   GNUNET_CONTAINER_DLL_remove (t->tq_head,
3230                                t->tq_tail,
3231                                tq);
3232   GNUNET_MQ_discard (tq->env);
3233   GNUNET_free (tq);
3234 }
3235
3236
3237 /**
3238  * Iterate over all connections of a tunnel.
3239  *
3240  * @param t Tunnel whose connections to iterate.
3241  * @param iter Iterator.
3242  * @param iter_cls Closure for @c iter.
3243  */
3244 void
3245 GCT_iterate_connections (struct CadetTunnel *t,
3246                          GCT_ConnectionIterator iter,
3247                          void *iter_cls)
3248 {
3249   struct CadetTConnection *n;
3250   for (struct CadetTConnection *ct = t->connection_ready_head;
3251        NULL != ct;
3252        ct = n)
3253   {
3254     n = ct->next;
3255     iter (iter_cls,
3256           ct);
3257   }
3258   for (struct CadetTConnection *ct = t->connection_busy_head;
3259        NULL != ct;
3260        ct = n)
3261   {
3262     n = ct->next;
3263     iter (iter_cls,
3264           ct);
3265   }
3266 }
3267
3268
3269 /**
3270  * Closure for #iterate_channels_cb.
3271  */
3272 struct ChanIterCls
3273 {
3274   /**
3275    * Function to call.
3276    */
3277   GCT_ChannelIterator iter;
3278
3279   /**
3280    * Closure for @e iter.
3281    */
3282   void *iter_cls;
3283 };
3284
3285
3286 /**
3287  * Helper function for #GCT_iterate_channels.
3288  *
3289  * @param cls the `struct ChanIterCls`
3290  * @param key unused
3291  * @param value a `struct CadetChannel`
3292  * @return #GNUNET_OK
3293  */
3294 static int
3295 iterate_channels_cb (void *cls,
3296                      uint32_t key,
3297                      void *value)
3298 {
3299   struct ChanIterCls *ctx = cls;
3300   struct CadetChannel *ch = value;
3301
3302   ctx->iter (ctx->iter_cls,
3303              ch);
3304   return GNUNET_OK;
3305 }
3306
3307
3308 /**
3309  * Iterate over all channels of a tunnel.
3310  *
3311  * @param t Tunnel whose channels to iterate.
3312  * @param iter Iterator.
3313  * @param iter_cls Closure for @c iter.
3314  */
3315 void
3316 GCT_iterate_channels (struct CadetTunnel *t,
3317                       GCT_ChannelIterator iter,
3318                       void *iter_cls)
3319 {
3320   struct ChanIterCls ctx;
3321
3322   ctx.iter = iter;
3323   ctx.iter_cls = iter_cls;
3324   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3325                                            &iterate_channels_cb,
3326                                            &ctx);
3327
3328 }
3329
3330
3331 /**
3332  * Call #GCCH_debug() on a channel.
3333  *
3334  * @param cls points to the log level to use
3335  * @param key unused
3336  * @param value the `struct CadetChannel` to dump
3337  * @return #GNUNET_OK (continue iteration)
3338  */
3339 static int
3340 debug_channel (void *cls,
3341                uint32_t key,
3342                void *value)
3343 {
3344   const enum GNUNET_ErrorType *level = cls;
3345   struct CadetChannel *ch = value;
3346
3347   GCCH_debug (ch, *level);
3348   return GNUNET_OK;
3349 }
3350
3351
3352 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
3353
3354
3355 /**
3356  * Log all possible info about the tunnel state.
3357  *
3358  * @param t Tunnel to debug.
3359  * @param level Debug level to use.
3360  */
3361 void
3362 GCT_debug (const struct CadetTunnel *t,
3363            enum GNUNET_ErrorType level)
3364 {
3365   struct CadetTConnection *iter_c;
3366   int do_log;
3367
3368   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
3369                                        "cadet-tun",
3370                                        __FILE__, __FUNCTION__, __LINE__);
3371   if (0 == do_log)
3372     return;
3373
3374   LOG2 (level,
3375         "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n",
3376         GCT_2s (t),
3377         estate2s (t->estate),
3378         t->tq_len,
3379         GCT_count_any_connections (t));
3380   LOG2 (level,
3381         "TTT channels:\n");
3382   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
3383                                            &debug_channel,
3384                                            &level);
3385   LOG2 (level,
3386         "TTT connections:\n");
3387   for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next)
3388     GCC_debug (iter_c->cc,
3389                level);
3390   for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next)
3391     GCC_debug (iter_c->cc,
3392                level);
3393
3394   LOG2 (level,
3395         "TTT TUNNEL END\n");
3396 }
3397
3398
3399 /* end of gnunet-service-cadet-new_tunnels.c */