-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
handshake.cc
931 lines (765 loc) · 28.4 KB
/
handshake.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
// This file Copyright © 2017-2023 Mnemosyne LLC.
// It may be used under GPLv2 (SPDX: GPL-2.0-only), GPLv3 (SPDX: GPL-3.0-only),
// or any future license endorsed by Mnemosyne LLC.
// License text can be found in the licenses/ folder.
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <string_view>
#include <utility>
#include <fmt/core.h>
#include "libtransmission/transmission.h"
#include "libtransmission/bitfield.h"
#include "libtransmission/clients.h"
#include "libtransmission/crypto-utils.h"
#include "libtransmission/handshake.h"
#include "libtransmission/log.h"
#include "libtransmission/peer-io.h"
#include "libtransmission/timer.h"
#include "libtransmission/tr-assert.h"
#include "libtransmission/tr-buffer.h"
#include "libtransmission/utils.h"
#define tr_logAddTraceHand(handshake, msg) tr_logAddTrace(msg, (handshake)->peer_io_->display_name())
using namespace std::literals;
using DH = tr_message_stream_encryption::DH;
bool tr_handshake::build_handshake_message(tr_peerIo* io, uint8_t* buf) const
{
auto const& info_hash = io->torrent_hash();
TR_ASSERT_MSG(info_hash != tr_sha1_digest_t{}, "build_handshake_message requires an info_hash");
auto const info = mediator_->torrent(info_hash);
if (!info)
{
return false;
}
auto flags = tr_bitfield{ HandshakeFlagsBits };
flags.set(LtepFlag);
flags.set(FextFlag);
if (mediator_->allows_dht())
{
flags.set(DhtFlag);
}
auto const flag_bytes = flags.raw();
[[maybe_unused]] auto* walk = buf;
walk = std::copy_n(reinterpret_cast<uint8_t const*>(std::data(HandshakeName)), std::size(HandshakeName), walk);
walk = std::copy(std::begin(flag_bytes), std::end(flag_bytes), walk);
walk = std::copy_n(reinterpret_cast<char const*>(std::data(info_hash)), std::size(info_hash), walk);
walk = std::copy(std::begin(info->client_peer_id), std::end(info->client_peer_id), walk);
TR_ASSERT(walk - buf == HandshakeSize);
return true;
}
tr_handshake::ParseResult tr_handshake::parse_handshake(tr_peerIo* peer_io)
{
tr_logAddTraceHand(this, fmt::format("payload: need {}, got {}", HandshakeSize, peer_io->read_buffer_size()));
if (peer_io->read_buffer_size() < HandshakeSize)
{
return ParseResult::EncryptionWrong;
}
/* confirm the protocol */
auto name = decltype(HandshakeName){};
peer_io->read_bytes(std::data(name), std::size(name));
if (name != HandshakeName)
{
return ParseResult::EncryptionWrong;
}
/* read the reserved bytes */
auto flags = tr_bitfield{ HandshakeFlagsBits };
auto reserved = std::array<uint8_t, HandshakeFlagsBytes>{};
peer_io->read_bytes(std::data(reserved), std::size(reserved));
flags.set_raw(std::data(reserved), std::size(reserved));
peer_io->set_supports_dht(flags.test(DhtFlag));
peer_io->set_supports_ltep(flags.test(LtepFlag));
peer_io->set_supports_fext(flags.test(FextFlag));
// torrent hash
auto info_hash = tr_sha1_digest_t{};
peer_io->read_bytes(std::data(info_hash), std::size(info_hash));
if (info_hash == tr_sha1_digest_t{} || info_hash != peer_io->torrent_hash())
{
tr_logAddTraceHand(this, "peer returned the wrong hash. wtf?");
return ParseResult::BadTorrent;
}
// peer_id
auto peer_id = tr_peer_id_t{};
peer_io->read_bytes(std::data(peer_id), std::size(peer_id));
set_peer_id(peer_id);
/* peer id */
auto const peer_id_sv = std::string_view{ std::data(peer_id), std::size(peer_id) };
tr_logAddTraceHand(this, fmt::format("peer-id is '{}'", peer_id_sv));
if (auto const info = mediator_->torrent(info_hash); info && info->client_peer_id == peer_id)
{
tr_logAddTraceHand(this, "streuth! we've connected to ourselves.");
return ParseResult::PeerIsSelf;
}
return ParseResult::Ok;
}
// --- Outgoing Connections
// 1 A->B: our public key (Ya) and some padding (PadA)
void tr_handshake::send_ya(tr_peerIo* io)
{
send_public_key_and_pad<PadaMaxlen>(io);
set_state(tr_handshake::State::AwaitingYb);
}
[[nodiscard]] uint32_t tr_handshake::get_crypto_select(tr_encryption_mode encryption_mode, uint32_t crypto_provide) noexcept
{
auto choices = std::array<uint32_t, 2>{};
int n_choices = 0;
switch (encryption_mode)
{
case TR_ENCRYPTION_REQUIRED:
choices[n_choices++] = CryptoProvideCrypto;
break;
case TR_ENCRYPTION_PREFERRED:
choices[n_choices++] = CryptoProvideCrypto;
choices[n_choices++] = CryptoProvidePlaintext;
break;
case TR_CLEAR_PREFERRED:
choices[n_choices++] = CryptoProvidePlaintext;
choices[n_choices++] = CryptoProvideCrypto;
break;
}
for (auto const& choice : choices)
{
if ((crypto_provide & choice) != 0)
{
return choice;
}
}
return 0;
}
ReadState tr_handshake::read_yb(tr_peerIo* peer_io)
{
if (peer_io->read_buffer_size() < std::size(HandshakeName))
{
return READ_LATER;
}
bool const is_encrypted = !peer_io->read_buffer_starts_with(HandshakeName);
auto peer_public_key = DH::key_bigend_t{};
if (is_encrypted && (peer_io->read_buffer_size() < std::size(peer_public_key)))
{
return READ_LATER;
}
tr_logAddTraceHand(this, is_encrypted ? "got an encrypted handshake" : "got a plain handshake");
if (!is_encrypted)
{
set_state(tr_handshake::State::AwaitingHandshake);
return READ_NOW;
}
set_have_read_anything_from_peer(true);
// get the peer's public key
peer_io->read_bytes(std::data(peer_public_key), std::size(peer_public_key));
dh_.setPeerPublicKey(peer_public_key);
/* now send these: HASH('req1', S), HASH('req2', SKEY) xor HASH('req3', S),
* ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA)), ENCRYPT(IA) */
auto outbuf = libtransmission::SmallBuffer<4096>{};
/* HASH('req1', S) */
outbuf.add(tr_sha1::digest("req1"sv, dh_.secret()));
auto const& info_hash = peer_io->torrent_hash();
TR_ASSERT_MSG(info_hash != tr_sha1_digest_t{}, "readYb requires an info_hash");
/* HASH('req2', SKEY) xor HASH('req3', S) */
{
auto const req2 = tr_sha1::digest("req2"sv, info_hash);
auto const req3 = tr_sha1::digest("req3"sv, dh_.secret());
auto x_or = tr_sha1_digest_t{};
for (size_t i = 0, n = std::size(x_or); i < n; ++i)
{
x_or[i] = req2[i] ^ req3[i];
}
outbuf.add(x_or);
}
/* ENCRYPT(VC, crypto_provide, len(PadC), PadC
* PadC is reserved for future extensions to the handshake...
* standard practice at this time is for it to be zero-length */
peer_io->write(outbuf, false);
peer_io->encrypt_init(peer_io->is_incoming(), dh_, info_hash);
outbuf.add(VC);
outbuf.add_uint32(crypto_provide());
outbuf.add_uint16(0);
/* ENCRYPT len(IA)), ENCRYPT(IA) */
if (auto msg = std::array<uint8_t, HandshakeSize>{}; build_handshake_message(peer_io, std::data(msg)))
{
outbuf.add_uint16(std::size(msg));
outbuf.add(msg);
have_sent_bittorrent_handshake_ = true;
}
else
{
return done(false);
}
/* send it */
set_state(State::AwaitingVc);
peer_io->write(outbuf, false);
return READ_NOW;
}
// MSE spec: "Since the length of [PadB is] unknown,
// A will be able to resynchronize on ENCRYPT(VC)"
ReadState tr_handshake::read_vc(tr_peerIo* peer_io)
{
auto const info_hash = peer_io->torrent_hash();
TR_ASSERT_MSG(info_hash != tr_sha1_digest_t{}, "readVC requires an info_hash");
// We need to find the end of PadB by looking for `ENCRYPT(VC)`,
// so calculate and cache the value of `ENCRYPT(VC)`.
if (!encrypted_vc_)
{
auto filter = tr_message_stream_encryption::Filter{};
filter.encrypt_init(true, dh_, info_hash);
auto needle = decltype(VC){};
filter.encrypt(std::data(VC), std::size(VC), std::data(needle));
encrypted_vc_ = needle;
}
for (size_t i = 0; i < PadbMaxlen; ++i)
{
if (peer_io->read_buffer_size() < std::size(*encrypted_vc_))
{
tr_logAddTraceHand(this, "not enough bytes... returning read_more");
return READ_LATER;
}
if (peer_io->read_buffer_starts_with(*encrypted_vc_))
{
tr_logAddTraceHand(this, "got it!");
// We already know it's a match; now we just need to
// consume it from the read buffer.
peer_io->decrypt_init(peer_io->is_incoming(), dh_, info_hash);
peer_io->read_bytes(std::data(*encrypted_vc_), std::size(*encrypted_vc_));
set_state(tr_handshake::State::AwaitingCryptoSelect);
return READ_NOW;
}
peer_io->read_buffer_drain(1);
}
tr_logAddTraceHand(this, "couldn't find ENCRYPT(VC)");
return done(false);
}
ReadState tr_handshake::read_crypto_select(tr_peerIo* peer_io)
{
if (static size_t constexpr NeedLen = sizeof(uint32_t) + sizeof(uint16_t); peer_io->read_buffer_size() < NeedLen)
{
return READ_LATER;
}
auto crypto_select = uint32_t{};
peer_io->read_uint32(&crypto_select);
crypto_select_ = crypto_select;
tr_logAddTraceHand(this, fmt::format("crypto select is {}", crypto_select));
if ((crypto_select & crypto_provide()) == 0)
{
tr_logAddTraceHand(this, "peer selected an encryption option we didn't offer");
return done(false);
}
uint16_t pad_d_len = 0;
peer_io->read_uint16(&pad_d_len);
tr_logAddTraceHand(this, fmt::format("pad_d_len is {}", pad_d_len));
if (pad_d_len > 512)
{
tr_logAddTraceHand(this, "encryption handshake: pad_d_len is too long");
return done(false);
}
pad_d_len_ = pad_d_len;
set_state(tr_handshake::State::AwaitingPadD);
return READ_NOW;
}
ReadState tr_handshake::read_pad_d(tr_peerIo* peer_io)
{
size_t const needlen = pad_d_len_;
tr_logAddTraceHand(this, fmt::format("pad d: need {}, got {}", needlen, peer_io->read_buffer_size()));
if (peer_io->read_buffer_size() < needlen)
{
return READ_LATER;
}
peer_io->read_buffer_drain(needlen);
set_state(tr_handshake::State::AwaitingHandshake);
return READ_NOW;
}
// --- Incoming Connections
ReadState tr_handshake::read_handshake(tr_peerIo* peer_io)
{
static auto constexpr Needlen = IncomingHandshakeLen;
tr_logAddTraceHand(this, fmt::format("payload: need {}, got {}", Needlen, peer_io->read_buffer_size()));
if (peer_io->read_buffer_size() < Needlen)
{
return READ_LATER;
}
set_have_read_anything_from_peer(true);
if (peer_io->read_buffer_starts_with(HandshakeName)) // unencrypted
{
if (encryption_mode_ == TR_ENCRYPTION_REQUIRED)
{
tr_logAddTraceHand(this, "peer is unencrypted, and we're disallowing that");
return done(false);
}
}
else // either encrypted or corrupt
{
if (is_incoming())
{
tr_logAddTraceHand(this, "I think peer is sending us an encrypted handshake...");
set_state(tr_handshake::State::AwaitingYa);
return READ_NOW;
}
}
auto name = decltype(HandshakeName){};
peer_io->read_bytes(std::data(name), std::size(name));
if (name != HandshakeName)
{
return done(false);
}
// reserved bytes / flags
auto reserved = std::array<uint8_t, HandshakeFlagsBytes>{};
auto flags = tr_bitfield{ HandshakeFlagsBits };
peer_io->read_bytes(std::data(reserved), std::size(reserved));
flags.set_raw(std::data(reserved), std::size(reserved));
peer_io->set_supports_dht(flags.test(DhtFlag));
peer_io->set_supports_ltep(flags.test(LtepFlag));
peer_io->set_supports_fext(flags.test(FextFlag));
/* torrent hash */
auto hash = tr_sha1_digest_t{};
peer_io->read_bytes(std::data(hash), std::size(hash));
if (is_incoming())
{
if (!mediator_->torrent(hash))
{
tr_logAddTraceHand(this, "peer is trying to connect to us for a torrent we don't have.");
return done(false);
}
peer_io->set_torrent_hash(hash);
}
else // outgoing
{
if (peer_io->torrent_hash() != hash)
{
tr_logAddTraceHand(this, "peer returned the wrong hash. wtf?");
return done(false);
}
}
// If it's an incoming message, we need to send a response handshake
if (!have_sent_bittorrent_handshake_)
{
auto msg = std::array<uint8_t, HandshakeSize>{};
if (!build_handshake_message(peer_io, std::data(msg)))
{
return done(false);
}
peer_io->write_bytes(std::data(msg), std::size(msg), false);
have_sent_bittorrent_handshake_ = true;
}
set_state(State::AwaitingPeerId);
return READ_NOW;
}
ReadState tr_handshake::read_peer_id(tr_peerIo* peer_io)
{
// read the peer_id
auto peer_id = tr_peer_id_t{};
if (peer_io->read_buffer_size() < std::size(peer_id))
{
return READ_LATER;
}
peer_io->read_bytes(std::data(peer_id), std::size(peer_id));
set_peer_id(peer_id);
auto client = std::array<char, 128>{};
tr_clientForId(std::data(client), std::size(client), peer_id);
tr_logAddTraceHand(this, fmt::format("peer-id is '{}' ... isIncoming is {}", std::data(client), is_incoming()));
// if we've somehow connected to ourselves, don't keep the connection
auto const info_hash = peer_io_->torrent_hash();
auto const info = mediator_->torrent(info_hash);
auto const connected_to_self = info && info->client_peer_id == peer_id;
return done(!connected_to_self);
}
ReadState tr_handshake::read_ya(tr_peerIo* peer_io)
{
auto peer_public_key = DH::key_bigend_t{};
tr_logAddTraceHand(
this,
fmt::format("in readYa... need {}, have {}", std::size(peer_public_key), peer_io->read_buffer_size()));
if (peer_io->read_buffer_size() < std::size(peer_public_key))
{
return READ_LATER;
}
/* read the incoming peer's public key */
peer_io->read_bytes(std::data(peer_public_key), std::size(peer_public_key));
dh_.setPeerPublicKey(peer_public_key);
// send our public key to the peer
tr_logAddTraceHand(this, "sending B->A: Diffie Hellman Yb, PadB");
send_public_key_and_pad<PadbMaxlen>(peer_io);
set_state(State::AwaitingPadA);
return READ_NOW;
}
ReadState tr_handshake::read_pad_a(tr_peerIo* peer_io)
{
// find the end of PadA by looking for HASH('req1', S)
auto const needle = tr_sha1::digest("req1"sv, dh_.secret());
for (size_t i = 0; i < PadaMaxlen; ++i)
{
if (peer_io->read_buffer_size() < std::size(needle))
{
tr_logAddTraceHand(this, "not enough bytes... returning read_more");
return READ_LATER;
}
if (peer_io->read_buffer_starts_with(needle))
{
tr_logAddTraceHand(this, "found it... looking setting to awaiting_crypto_provide");
peer_io->read_buffer_drain(std::size(needle));
set_state(State::AwaitingCryptoProvide);
return READ_NOW;
}
peer_io->read_buffer_drain(1U);
}
tr_logAddTraceHand(this, "couldn't find HASH('req', S)");
return done(false);
}
ReadState tr_handshake::read_crypto_provide(tr_peerIo* peer_io)
{
/* HASH('req2', SKEY) xor HASH('req3', S), ENCRYPT(VC, crypto_provide, len(PadC)) */
uint16_t padc_len = 0;
uint32_t crypto_provide = 0;
auto obfuscated_hash = tr_sha1_digest_t{};
size_t const needlen = sizeof(obfuscated_hash) + /* HASH('req2', SKEY) xor HASH('req3', S) */
std::size(VC) + sizeof(crypto_provide) + sizeof(padc_len);
if (peer_io->read_buffer_size() < needlen)
{
return READ_LATER;
}
/* This next piece is HASH('req2', SKEY) xor HASH('req3', S) ...
* we can get the first half of that (the obfuscatedTorrentHash)
* by building the latter and xor'ing it with what the peer sent us */
tr_logAddTraceHand(this, "reading obfuscated torrent hash...");
auto req2 = tr_sha1_digest_t{};
peer_io->read_bytes(std::data(req2), std::size(req2));
auto const req3 = tr_sha1::digest("req3"sv, dh_.secret());
for (size_t i = 0; i < std::size(obfuscated_hash); ++i)
{
obfuscated_hash[i] = req2[i] ^ req3[i];
}
if (auto const info = mediator_->torrent_from_obfuscated(obfuscated_hash); info)
{
bool const client_is_seed = info->is_done;
bool const peer_is_seed = mediator_->is_peer_known_seed(info->id, peer_io->socket_address());
tr_logAddTraceHand(this, fmt::format("got INCOMING connection's encrypted handshake for torrent [{}]", info->id));
peer_io->set_torrent_hash(info->info_hash);
if (client_is_seed && peer_is_seed)
{
tr_logAddTraceHand(this, "another seed tried to reconnect to us!");
return done(false);
}
}
else
{
tr_logAddTraceHand(this, "can't find that torrent...");
return done(false);
}
/* next part: ENCRYPT(VC, crypto_provide, len(PadC), */
auto const& info_hash = peer_io->torrent_hash();
TR_ASSERT_MSG(info_hash != tr_sha1_digest_t{}, "readCryptoProvide requires an info_hash");
peer_io->decrypt_init(peer_io->is_incoming(), dh_, info_hash);
auto vc_in = vc_t{};
peer_io->read_bytes(std::data(vc_in), std::size(vc_in));
peer_io->read_uint32(&crypto_provide);
crypto_provide_ = crypto_provide;
tr_logAddTraceHand(this, fmt::format("crypto_provide is {}", crypto_provide));
peer_io->read_uint16(&padc_len);
tr_logAddTraceHand(this, fmt::format("padc is {}", padc_len));
if (padc_len > PadcMaxlen)
{
tr_logAddTraceHand(this, "peer's PadC is too big");
return done(false);
}
pad_c_len_ = padc_len;
set_state(State::AwaitingPadC);
return READ_NOW;
}
ReadState tr_handshake::read_pad_c(tr_peerIo* peer_io)
{
if (auto const needlen = pad_c_len_ + sizeof(uint16_t); peer_io->read_buffer_size() < needlen)
{
return READ_LATER;
}
// read the throwaway padc
auto pad_c = std::array<char, PadcMaxlen>{};
peer_io->read_bytes(std::data(pad_c), pad_c_len_);
/* read ia_len */
uint16_t ia_len = 0;
peer_io->read_uint16(&ia_len);
tr_logAddTraceHand(this, fmt::format("ia_len is {}", ia_len));
ia_len_ = ia_len;
set_state(State::AwaitingIa);
return READ_NOW;
}
ReadState tr_handshake::read_ia(tr_peerIo* peer_io)
{
size_t const needlen = ia_len_;
tr_logAddTraceHand(this, fmt::format("reading IA... have {}, need {}", peer_io->read_buffer_size(), needlen));
if (peer_io->read_buffer_size() < needlen)
{
return READ_LATER;
}
// B->A: ENCRYPT(VC, crypto_select, len(padD), padD), ENCRYPT2(Payload Stream)
auto const& info_hash = peer_io->torrent_hash();
TR_ASSERT_MSG(info_hash != tr_sha1_digest_t{}, "readIA requires an info_hash");
peer_io->encrypt_init(peer_io->is_incoming(), dh_, info_hash);
auto outbuf = libtransmission::SmallBuffer<4096>{};
// send VC
tr_logAddTraceHand(this, "sending vc");
outbuf.add(VC);
/* send crypto_select */
uint32_t const crypto_select = get_crypto_select(encryption_mode_, crypto_provide_);
if (crypto_select != 0)
{
tr_logAddTraceHand(this, fmt::format("selecting crypto mode '{}'", crypto_select));
outbuf.add_uint32(crypto_select);
}
else
{
tr_logAddTraceHand(this, "peer didn't offer an encryption mode we like.");
return done(false);
}
tr_logAddTraceHand(this, "sending pad d");
/* ENCRYPT(VC, crypto_provide, len(PadD), PadD
* PadD is reserved for future extensions to the handshake...
* standard practice at this time is for it to be zero-length */
outbuf.add_uint16(0);
/* maybe de-encrypt our connection */
if (crypto_select == CryptoProvidePlaintext)
{
peer_io->write(outbuf, false);
TR_ASSERT(std::empty(outbuf));
}
tr_logAddTraceHand(this, "sending handshake");
/* send our handshake */
if (auto msg = std::array<uint8_t, HandshakeSize>{}; build_handshake_message(peer_io, std::data(msg)))
{
outbuf.add(msg);
have_sent_bittorrent_handshake_ = true;
}
else
{
return done(false);
}
/* send it out */
peer_io->write(outbuf, false);
/* now await the handshake */
set_state(State::AwaitingPayloadStream);
return READ_NOW;
}
ReadState tr_handshake::read_payload_stream(tr_peerIo* peer_io)
{
static auto constexpr Needlen = HandshakeSize;
tr_logAddTraceHand(this, fmt::format("reading payload stream... have {}, need {}", peer_io->read_buffer_size(), Needlen));
if (peer_io->read_buffer_size() < Needlen)
{
return READ_LATER;
}
/* parse the handshake ... */
auto const i = parse_handshake(peer_io);
tr_logAddTraceHand(this, fmt::format("parseHandshake returned {}", static_cast<int>(i)));
if (i != ParseResult::Ok)
{
return done(false);
}
/* we've completed the BT handshake... pass the work on to peer-msgs */
return done(true);
}
// ---
ReadState tr_handshake::can_read(tr_peerIo* peer_io, void* vhandshake, size_t* piece)
{
auto* handshake = static_cast<tr_handshake*>(vhandshake);
bool ready_for_more = true;
/* no piece data in handshake */
*piece = 0;
tr_logAddTraceHand(handshake, fmt::format("handling canRead; state is [{}]", handshake->state_string()));
ReadState ret = READ_NOW;
while (ready_for_more)
{
switch (handshake->state())
{
case State::AwaitingHandshake:
ret = handshake->read_handshake(peer_io);
break;
case State::AwaitingPeerId:
ret = handshake->read_peer_id(peer_io);
break;
case State::AwaitingYa:
ret = handshake->read_ya(peer_io);
break;
case State::AwaitingPadA:
ret = handshake->read_pad_a(peer_io);
break;
case State::AwaitingCryptoProvide:
ret = handshake->read_crypto_provide(peer_io);
break;
case State::AwaitingPadC:
ret = handshake->read_pad_c(peer_io);
break;
case State::AwaitingIa:
ret = handshake->read_ia(peer_io);
break;
case State::AwaitingPayloadStream:
ret = handshake->read_payload_stream(peer_io);
break;
case State::AwaitingYb:
ret = handshake->read_yb(peer_io);
break;
case State::AwaitingVc:
ret = handshake->read_vc(peer_io);
break;
case State::AwaitingCryptoSelect:
ret = handshake->read_crypto_select(peer_io);
break;
case State::AwaitingPadD:
ret = handshake->read_pad_d(peer_io);
break;
default:
#ifdef TR_ENABLE_ASSERTS
TR_ASSERT_MSG(
false,
fmt::format(FMT_STRING("unhandled handshake state {:d}"), static_cast<int>(handshake->state())));
#else
ret = READ_ERR;
break;
#endif
}
if (ret != READ_NOW)
{
ready_for_more = false;
}
else if (handshake->is_state(State::AwaitingPadC))
{
ready_for_more = peer_io->read_buffer_size() >= handshake->pad_c_len_;
}
else if (handshake->is_state(State::AwaitingPadD))
{
ready_for_more = peer_io->read_buffer_size() >= handshake->pad_d_len_;
}
else if (handshake->is_state(State::AwaitingIa))
{
ready_for_more = peer_io->read_buffer_size() >= handshake->ia_len_;
}
}
return ret;
}
void tr_handshake::on_error(tr_peerIo* io, tr_error const& error, void* vhandshake)
{
auto* handshake = static_cast<tr_handshake*>(vhandshake);
if (io->is_utp() && !io->is_incoming() && handshake->is_state(State::AwaitingYb))
{
// the peer probably doesn't speak µTP.
auto const info_hash = io->torrent_hash();
auto const info = handshake->mediator_->torrent(info_hash);
/* Don't mark a peer as non-µTP unless it's really a connect failure. */
if ((error.code == ETIMEDOUT || error.code == ECONNREFUSED) && info)
{
handshake->mediator_->set_utp_failed(info_hash, io->socket_address());
}
if (handshake->mediator_->allows_tcp() && io->reconnect())
{
auto msg = std::array<uint8_t, HandshakeSize>{};
handshake->build_handshake_message(io, std::data(msg));
handshake->have_sent_bittorrent_handshake_ = true;
handshake->set_state(State::AwaitingHandshake);
io->write_bytes(std::data(msg), std::size(msg), false);
return;
}
}
/* if the error happened while we were sending a public key, we might
* have encountered a peer that doesn't do encryption... reconnect and
* try a plaintext handshake */
if ((handshake->is_state(State::AwaitingYb) || handshake->is_state(State::AwaitingVc)) &&
handshake->encryption_mode_ != TR_ENCRYPTION_REQUIRED && handshake->mediator_->allows_tcp() && io->reconnect())
{
auto msg = std::array<uint8_t, HandshakeSize>{};
tr_logAddTraceHand(handshake, "handshake failed, trying plaintext...");
handshake->build_handshake_message(io, std::data(msg));
handshake->have_sent_bittorrent_handshake_ = true;
handshake->set_state(State::AwaitingHandshake);
io->write_bytes(std::data(msg), std::size(msg), false);
return;
}
tr_logAddTraceHand(handshake, fmt::format("handshake socket err: {:s} ({:d})", error.message, error.code));
handshake->done(false);
}
bool tr_handshake::fire_done(bool is_connected)
{
maybe_recycle_dh();
if (!on_done_)
{
return false;
}
// handshake could get destroyed inside on_done,
// so handle all our housekeeping *before* calling it
auto cb = DoneFunc{};
std::swap(cb, on_done_);
auto peer_io = std::shared_ptr<tr_peerIo>{};
std::swap(peer_io, peer_io_);
bool const success = (cb)(Result{ std::move(peer_io), peer_id_, have_read_anything_from_peer_, is_connected });
return success;
}
std::string_view tr_handshake::state_string(State state) noexcept
{
switch (state)
{
case State::AwaitingHandshake:
return "awaiting handshake";
case State::AwaitingPeerId:
return "awaiting peer id";
case State::AwaitingYa:
return "awaiting ya";
case State::AwaitingPadA:
return "awaiting pad a";
case State::AwaitingCryptoProvide:
return "awaiting crypto provide";
case State::AwaitingPadC:
return "awaiting pad c";
case State::AwaitingIa:
return "awaiting ia";
case State::AwaitingPayloadStream:
return "awaiting payload stream";
// outgoing
case State::AwaitingYb:
return "awaiting yb";
case State::AwaitingVc:
return "awaiting vc";
case State::AwaitingCryptoSelect:
return "awaiting crypto select";
case State::AwaitingPadD:
return "awaiting pad d";
}
return "unknown state";
}
uint32_t tr_handshake::crypto_provide() const noexcept
{
auto provide = uint32_t{};
switch (encryption_mode_)
{
case TR_ENCRYPTION_REQUIRED:
case TR_ENCRYPTION_PREFERRED:
provide |= CryptoProvideCrypto;
break;
case TR_CLEAR_PREFERRED:
provide |= CryptoProvideCrypto | CryptoProvidePlaintext;
break;
}
return provide;
}
// ---
tr_handshake::tr_handshake(Mediator* mediator, std::shared_ptr<tr_peerIo> peer_io, tr_encryption_mode mode, DoneFunc on_done)
: dh_{ tr_handshake::get_dh(mediator) }
, on_done_{ std::move(on_done) }
, peer_io_{ std::move(peer_io) }
, timeout_timer_{ mediator->timer_maker().create([this]() { fire_done(false); }) }
, mediator_{ mediator }
, encryption_mode_{ mode }
{
timeout_timer_->start_single_shot(HandshakeTimeoutSec);
peer_io_->set_callbacks(&tr_handshake::can_read, nullptr, &tr_handshake::on_error, this);
if (is_incoming())
{
set_state(State::AwaitingHandshake);
}
else if (encryption_mode_ != TR_CLEAR_PREFERRED)
{
send_ya(peer_io_.get());
}
else
{
auto msg = std::array<uint8_t, HandshakeSize>{};
build_handshake_message(peer_io_.get(), std::data(msg));
have_sent_bittorrent_handshake_ = true;
set_state(State::AwaitingHandshake);
peer_io_->write_bytes(std::data(msg), std::size(msg), false);
}
}