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