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