-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathbt_peer_connection.cpp
3794 lines (3169 loc) · 105 KB
/
bt_peer_connection.cpp
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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2006-2020, Arvid Norberg
Copyright (c) 2007, Un Shyam
Copyright (c) 2015, Mikhail Titov
Copyright (c) 2016-2020, Alden Torres
Copyright (c) 2016-2018, Pavel Pimenov
Copyright (c) 2016-2017, Andrei Kurushin
Copyright (c) 2016-2020, Steven Siloti
Copyright (c) 2017, Antoine Dahan
Copyright (c) 2018, Greg Hazel
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/config.hpp"
#include <memory> // unique_ptr
#include <vector>
#include <functional>
#ifndef TORRENT_DISABLE_LOGGING
#include "libtorrent/hex.hpp" // to_hex
#endif
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/identify_client.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/aux_/invariant_check.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/aux_/io.hpp"
#include "libtorrent/socket_io.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/aux_/session_interface.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/random.hpp"
#include "libtorrent/aux_/alloca.hpp"
#include "libtorrent/aux_/socket_type.hpp"
#include "libtorrent/aux_/merkle.hpp"
#include "libtorrent/performance_counters.hpp" // for counters
#include "libtorrent/aux_/alert_manager.hpp" // for alert_manager
#include "libtorrent/string_util.hpp" // for search
#include "libtorrent/aux_/generate_peer_id.hpp"
#if !defined TORRENT_DISABLE_ENCRYPTION
#include "libtorrent/pe_crypto.hpp"
#include "libtorrent/hasher.hpp"
#endif
namespace libtorrent {
#if !defined TORRENT_DISABLE_ENCRYPTION
namespace {
constexpr std::size_t handshake_len = 68;
constexpr std::size_t dh_key_len = 96;
// stream key (info hash of attached torrent)
// secret is the DH shared secret
// initializes m_enc_handler
std::shared_ptr<rc4_handler> init_pe_rc4_handler(key_t const& secret
, sha1_hash const& stream_key, bool const outgoing)
{
hasher h;
static const char keyA[] = {'k', 'e', 'y', 'A'};
static const char keyB[] = {'k', 'e', 'y', 'B'};
// encryption rc4 longkeys
// outgoing connection : hash ('keyA',S,SKEY)
// incoming connection : hash ('keyB',S,SKEY)
std::array<char, dh_key_len> const secret_buf = export_key(secret);
if (outgoing) h.update(keyA); else h.update(keyB);
h.update(secret_buf);
h.update(stream_key);
sha1_hash const local_key = h.final();
h.reset();
// decryption rc4 longkeys
// outgoing connection : hash ('keyB',S,SKEY)
// incoming connection : hash ('keyA',S,SKEY)
if (outgoing) h.update(keyB); else h.update(keyA);
h.update(secret_buf);
h.update(stream_key);
sha1_hash const remote_key = h.final();
auto ret = std::make_shared<rc4_handler>();
ret->set_incoming_key(remote_key);
ret->set_outgoing_key(local_key);
return ret;
}
} // anonymous namespace
#endif
#ifndef TORRENT_DISABLE_EXTENSIONS
bool ut_pex_peer_store::was_introduced_by(tcp::endpoint const &ep)
{
if (aux::is_v4(ep))
{
peers4_t::value_type const v(ep.address().to_v4().to_bytes(), ep.port());
auto const i = std::lower_bound(m_peers.begin(), m_peers.end(), v);
return i != m_peers.end() && *i == v;
}
else
{
peers6_t::value_type const v(ep.address().to_v6().to_bytes(), ep.port());
auto const i = std::lower_bound(m_peers6.begin(), m_peers6.end(), v);
return i != m_peers6.end() && *i == v;
}
}
#endif // TORRENT_DISABLE_EXTENSIONS
bt_peer_connection::bt_peer_connection(peer_connection_args& pack)
: peer_connection(pack)
, m_supports_extensions(false)
, m_supports_dht_port(false)
, m_supports_fast(false)
, m_sent_bitfield(false)
, m_sent_handshake(false)
, m_sent_allowed_fast(false)
#if !defined TORRENT_DISABLE_ENCRYPTION
, m_encrypted(false)
, m_rc4_encrypted(false)
, m_recv_buffer(peer_connection::m_recv_buffer)
#endif
, m_our_peer_id(pack.our_peer_id)
{
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "CONSTRUCT", "bt_peer_connection");
#endif
m_reserved_bits.fill(0);
}
void bt_peer_connection::start()
{
peer_connection::start();
// start in the state where we are trying to read the
// handshake from the other side
m_recv_buffer.reset(20);
setup_receive();
}
bt_peer_connection::~bt_peer_connection() = default;
#if !defined TORRENT_DISABLE_ENCRYPTION
void bt_peer_connection::switch_send_crypto(std::shared_ptr<crypto_plugin> crypto)
{
if (m_enc_handler.switch_send_crypto(std::move(crypto), send_buffer_size() - get_send_barrier()))
set_send_barrier(send_buffer_size());
}
void bt_peer_connection::switch_recv_crypto(std::shared_ptr<crypto_plugin> crypto)
{
m_enc_handler.switch_recv_crypto(std::move(crypto), m_recv_buffer);
}
#endif
void bt_peer_connection::on_connected()
{
if (is_disconnecting()) return;
std::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
if (t->graceful_pause())
{
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "ON_CONNECTED", "graceful-paused");
#endif
disconnect(errors::torrent_paused, operation_t::bittorrent);
return;
}
// make sure are much as possible of the response ends up in the same
// packet, or at least back-to-back packets
cork c_(*this);
#if !defined TORRENT_DISABLE_ENCRYPTION
auto out_policy = static_cast<std::uint8_t>(m_settings.get_int(settings_pack::out_enc_policy));
#ifdef TORRENT_SSL_PEERS
// never try an encrypted connection when already using SSL
if (is_ssl(get_socket()))
out_policy = settings_pack::pe_disabled;
#endif
#ifndef TORRENT_DISABLE_LOGGING
static char const* policy_name[] = {"forced", "enabled", "disabled"};
TORRENT_ASSERT(out_policy < sizeof(policy_name)/sizeof(policy_name[0]));
peer_log(peer_log_alert::info, "ENCRYPTION"
, "outgoing encryption policy: %s", policy_name[out_policy]);
#endif
if (out_policy == settings_pack::pe_forced)
{
write_pe1_2_dhkey();
if (is_disconnecting()) return;
m_state = state_t::read_pe_dhkey;
m_recv_buffer.reset(dh_key_len);
setup_receive();
}
else if (out_policy == settings_pack::pe_enabled)
{
TORRENT_ASSERT(peer_info_struct());
torrent_peer* pi = peer_info_struct();
if (pi->pe_support == true)
{
// toggle encryption support flag, toggled back to
// true if encrypted portion of the handshake
// completes correctly
pi->pe_support = false;
// if this fails, we need to reconnect
// fast.
fast_reconnect(true);
write_pe1_2_dhkey();
if (is_disconnecting()) return;
m_state = state_t::read_pe_dhkey;
m_recv_buffer.reset(dh_key_len);
setup_receive();
}
else // pi->pe_support == false
{
// toggled back to false if standard handshake
// completes correctly (without encryption)
pi->pe_support = true;
write_handshake();
m_recv_buffer.reset(20);
setup_receive();
}
}
else if (out_policy == settings_pack::pe_disabled)
#endif
{
write_handshake();
// start in the state where we are trying to read the
// handshake from the other side
m_recv_buffer.reset(20);
setup_receive();
}
}
void bt_peer_connection::on_metadata()
{
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "ON_METADATA");
#endif
disconnect_if_redundant();
if (m_disconnecting) return;
if (!m_sent_handshake) return;
// we're still waiting to fully handshake with this peer. At the end of
// the handshake we'll send the bitfield and dht port anyway. It's too
// early to do now
if (static_cast<int>(m_state)
< static_cast<int>(state_t::read_packet_size))
{
return;
}
// connections that are still in the handshake
// will send their bitfield when the handshake
// is done
std::shared_ptr<torrent> t = associated_torrent().lock();
#ifndef TORRENT_DISABLE_SHARE_MODE
if (!t->share_mode())
#endif
{
bool const upload_only_enabled = t->is_upload_only()
#ifndef TORRENT_DISABLE_SUPERSEEDING
&& !t->super_seeding()
#endif
;
send_upload_only(upload_only_enabled);
}
if (m_sent_bitfield) return;
TORRENT_ASSERT(t);
write_bitfield();
TORRENT_ASSERT(m_sent_bitfield);
write_dht_port();
maybe_send_hash_request();
}
void bt_peer_connection::write_dht_port()
{
#ifndef TORRENT_DISABLE_DHT
if (m_supports_dht_port && m_ses.has_dht())
{
int const port = m_ses.external_udp_port(local_endpoint().address());
if (port >= 0) write_dht_port(port);
}
#endif
}
void bt_peer_connection::write_dht_port(int const listen_port)
{
INVARIANT_CHECK;
TORRENT_ASSERT(m_sent_handshake);
TORRENT_ASSERT(m_sent_bitfield);
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::outgoing_message, "DHT_PORT", "%d", listen_port);
#endif
char msg[] = {0,0,0,3, msg_dht_port, 0, 0};
char* ptr = msg + 5;
aux::write_uint16(listen_port, ptr);
send_buffer(msg);
stats_counters().inc_stats_counter(counters::num_outgoing_dht_port);
}
template<class F, typename... Args>
void bt_peer_connection::extension_notify(F message, Args... args)
{
#ifndef TORRENT_DISABLE_EXTENSIONS
for (auto const& e : m_extensions)
{
(*e.*message)(args...);
}
#endif
}
void bt_peer_connection::write_have_all()
{
INVARIANT_CHECK;
m_sent_bitfield = true;
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::outgoing_message, "HAVE_ALL");
#endif
send_message(msg_have_all, counters::num_outgoing_have_all);
#ifndef TORRENT_DISABLE_EXTENSIONS
extension_notify(&peer_plugin::sent_have_all);
#endif
}
void bt_peer_connection::write_have_none()
{
INVARIANT_CHECK;
m_sent_bitfield = true;
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::outgoing_message, "HAVE_NONE");
#endif
send_message(msg_have_none, counters::num_outgoing_have_none);
#ifndef TORRENT_DISABLE_EXTENSIONS
extension_notify(&peer_plugin::sent_have_none);
#endif
}
void bt_peer_connection::write_reject_request(peer_request const& r)
{
INVARIANT_CHECK;
stats_counters().inc_stats_counter(counters::piece_rejects);
if (!m_supports_fast) return;
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::outgoing_message, "REJECT_PIECE"
, "piece: %d | s: %d | l: %d", static_cast<int>(r.piece)
, r.start, r.length);
#endif
send_message(msg_reject_request, counters::num_outgoing_reject
, static_cast<int>(r.piece), r.start, r.length);
#ifndef TORRENT_DISABLE_EXTENSIONS
extension_notify(&peer_plugin::sent_reject_request, r);
#endif
}
void bt_peer_connection::write_allow_fast(piece_index_t const piece)
{
INVARIANT_CHECK;
if (!m_supports_fast) return;
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::outgoing_message, "ALLOWED_FAST", "%d"
, static_cast<int>(piece));
#endif
TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
send_message(msg_allowed_fast, counters::num_outgoing_allowed_fast
, static_cast<int>(piece));
#ifndef TORRENT_DISABLE_EXTENSIONS
extension_notify(&peer_plugin::sent_allow_fast, piece);
#endif
}
void bt_peer_connection::write_suggest(piece_index_t const piece)
{
INVARIANT_CHECK;
if (!m_supports_fast) return;
#if TORRENT_USE_ASSERTS
std::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
TORRENT_ASSERT(t->valid_metadata());
#endif
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::outgoing_message))
{
#if !TORRENT_USE_ASSERTS
std::shared_ptr<torrent> t = associated_torrent().lock();
#endif
peer_log(peer_log_alert::outgoing_message, "SUGGEST"
, "piece: %d num_peers: %d", static_cast<int>(piece)
, t->has_picker() ? t->picker().get_availability(piece) : -1);
}
#endif
send_message(msg_suggest_piece, counters::num_outgoing_suggest
, static_cast<int>(piece));
#ifndef TORRENT_DISABLE_EXTENSIONS
extension_notify(&peer_plugin::sent_suggest, piece);
#endif
}
void bt_peer_connection::get_specific_peer_info(peer_info& p) const
{
TORRENT_ASSERT(!associated_torrent().expired());
if (is_interesting()) p.flags |= peer_info::interesting;
if (is_choked()) p.flags |= peer_info::choked;
if (is_peer_interested()) p.flags |= peer_info::remote_interested;
if (has_peer_choked()) p.flags |= peer_info::remote_choked;
if (support_extensions()) p.flags |= peer_info::supports_extensions;
if (is_outgoing()) p.flags |= peer_info::local_connection;
#if TORRENT_USE_I2P
if (is_i2p(get_socket())) p.flags |= peer_info::i2p_socket;
#endif
if (is_utp(get_socket())) p.flags |= peer_info::utp_socket;
if (is_ssl(get_socket())) p.flags |= peer_info::ssl_socket;
#if !defined TORRENT_DISABLE_ENCRYPTION
if (m_encrypted)
{
p.flags |= m_rc4_encrypted
? peer_info::rc4_encrypted
: peer_info::plaintext_encrypted;
}
#endif
if (!is_connecting() && in_handshake())
p.flags |= peer_info::handshake;
if (is_connecting()) p.flags |= peer_info::connecting;
p.client = m_client_version;
p.connection_type = peer_info::standard_bittorrent;
}
bool bt_peer_connection::in_handshake() const
{
// this returns true until we have received a handshake
// and until we have send our handshake
return !m_sent_handshake || m_state < state_t::read_packet_size;
}
#if !defined TORRENT_DISABLE_ENCRYPTION
void bt_peer_connection::write_pe1_2_dhkey()
{
INVARIANT_CHECK;
TORRENT_ASSERT(!m_encrypted);
TORRENT_ASSERT(!m_rc4_encrypted);
TORRENT_ASSERT(!m_dh_key_exchange.get());
TORRENT_ASSERT(!m_sent_handshake);
#ifndef TORRENT_DISABLE_LOGGING
if (is_outgoing())
peer_log(peer_log_alert::info, "ENCRYPTION", "initiating encrypted handshake");
#endif
m_dh_key_exchange.reset(new (std::nothrow) dh_key_exchange);
if (!m_dh_key_exchange || !m_dh_key_exchange->good())
{
disconnect(errors::no_memory, operation_t::encryption);
return;
}
int const pad_size = int(random(512));
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "ENCRYPTION", "pad size: %d", pad_size);
#endif
char msg[dh_key_len + 512];
char* ptr = msg;
int const buf_size = int(dh_key_len) + pad_size;
std::array<char, dh_key_len> const local_key = export_key(m_dh_key_exchange->get_local_key());
std::memcpy(ptr, local_key.data(), dh_key_len);
ptr += dh_key_len;
aux::random_bytes({ptr, pad_size});
send_buffer({msg, buf_size});
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "ENCRYPTION", "sent DH key");
#endif
}
void bt_peer_connection::write_pe3_sync()
{
INVARIANT_CHECK;
TORRENT_ASSERT(!m_encrypted);
TORRENT_ASSERT(!m_rc4_encrypted);
TORRENT_ASSERT(is_outgoing());
TORRENT_ASSERT(!m_sent_handshake);
hasher h;
sha1_hash const& info_hash = associated_info_hash();
key_t const secret_key = m_dh_key_exchange->get_secret();
std::array<char, dh_key_len> const secret = export_key(secret_key);
int const pad_size = int(random(512));
// synchash,skeyhash,vc,crypto_provide,len(pad),pad,len(ia)
char msg[20 + 20 + 8 + 4 + 2 + 512 + 2];
char* ptr = msg;
static char const req1[4] = {'r', 'e', 'q', '1'};
// sync hash (hash('req1',S))
h.reset();
h.update(req1);
h.update(secret);
sha1_hash const sync_hash = h.final();
std::memcpy(ptr, sync_hash.data(), 20);
ptr += 20;
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::info))
{
peer_log(peer_log_alert::info, "ENCRYPTION"
, "writing synchash %s secret: %s"
, aux::to_hex(sync_hash).c_str()
, aux::to_hex(secret).c_str());
}
#endif
static char const req2[4] = {'r', 'e', 'q', '2'};
// stream key obfuscated hash [ hash('req2',SKEY) xor hash('req3',S) ]
h.reset();
h.update(req2);
h.update(info_hash);
sha1_hash const streamkey_hash = h.final();
static char const req3[4] = {'r', 'e', 'q', '3'};
h.reset();
h.update(req3);
h.update(secret);
sha1_hash const obfsc_hash = h.final() ^ streamkey_hash;
std::memcpy(ptr, obfsc_hash.data(), 20);
ptr += 20;
// Discard DH key exchange data, setup RC4 keys
m_rc4 = init_pe_rc4_handler(secret_key, info_hash, is_outgoing());
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "ENCRYPTION", "computed RC4 keys");
#endif
m_dh_key_exchange.reset(); // secret should be invalid at this point
// write the verification constant and crypto field
int const encrypt_size = int(sizeof(msg)) - 512 + pad_size - 40;
// this is an invalid setting, but let's just make the best of the situation
int const enc_level = m_settings.get_int(settings_pack::allowed_enc_level);
std::uint8_t const crypto_provide = ((enc_level & settings_pack::pe_both) == 0)
? std::uint8_t(settings_pack::pe_both)
: std::uint8_t(enc_level);
#ifndef TORRENT_DISABLE_LOGGING
static char const* level[] = {"plaintext", "rc4", "plaintext rc4"};
peer_log(peer_log_alert::info, "ENCRYPTION"
, "%s", level[crypto_provide - 1]);
#endif
write_pe_vc_cryptofield({ptr, encrypt_size}, crypto_provide, pad_size);
span<char> vec(ptr, encrypt_size);
m_rc4->encrypt(vec);
send_buffer({msg, int(sizeof(msg)) - 512 + pad_size});
}
void bt_peer_connection::write_pe4_sync(int const crypto_select)
{
INVARIANT_CHECK;
TORRENT_ASSERT(!is_outgoing());
TORRENT_ASSERT(!m_encrypted);
TORRENT_ASSERT(!m_rc4_encrypted);
TORRENT_ASSERT(crypto_select == 0x02 || crypto_select == 0x01);
TORRENT_ASSERT(!m_sent_handshake);
int const pad_size = int(random(512));
int const buf_size = 8 + 4 + 2 + pad_size;
char msg[512 + 8 + 4 + 2];
write_pe_vc_cryptofield(msg, crypto_select, pad_size);
span<char> vec(msg, buf_size);
m_rc4->encrypt(vec);
send_buffer(vec);
// encryption method has been negotiated
if (crypto_select == 0x02)
m_rc4_encrypted = true;
else // 0x01
m_rc4_encrypted = false;
#ifndef TORRENT_DISABLE_LOGGING
peer_log(peer_log_alert::info, "ENCRYPTION", " crypto select: %s"
, (crypto_select == 0x01) ? "plaintext" : "rc4");
#endif
}
void bt_peer_connection::write_pe_vc_cryptofield(
span<char> write_buf
, int const crypto_field
, int const pad_size)
{
INVARIANT_CHECK;
TORRENT_ASSERT(crypto_field <= 0x03 && crypto_field > 0);
// vc,crypto_field,len(pad),pad, (len(ia))
TORRENT_ASSERT((write_buf.size() >= 8+4+2+pad_size+2
&& is_outgoing())
|| (write_buf.size() >= 8+4+2+pad_size && !is_outgoing()));
TORRENT_ASSERT(!m_sent_handshake);
// encrypt(vc, crypto_provide/select, len(Pad), len(IA))
// len(pad) is zero for now, len(IA) only for outgoing connections
// vc
std::memset(write_buf.data(), 0, 8);
write_buf = write_buf.subspan(8);
aux::write_uint32(crypto_field, write_buf);
aux::write_uint16(pad_size, write_buf); // len (pad)
aux::random_bytes(write_buf.first(pad_size));
write_buf = write_buf.subspan(pad_size);
// append len(ia) if we are initiating
if (is_outgoing())
aux::write_uint16(handshake_len, write_buf); // len(IA)
}
void bt_peer_connection::rc4_decrypt(span<char> buf)
{
m_rc4->decrypt(buf);
}
#endif // #if !defined TORRENT_DISABLE_ENCRYPTION
void bt_peer_connection::write_handshake()
{
INVARIANT_CHECK;
TORRENT_ASSERT(!m_sent_handshake);
m_sent_handshake = true;
std::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
// add handshake to the send buffer
static const char version_string[] = "BitTorrent protocol";
const int string_len = sizeof(version_string) - 1;
char handshake[1 + string_len + 8 + 20 + 20];
char* ptr = handshake;
// length of version string
aux::write_uint8(string_len, ptr);
// protocol identifier
std::memcpy(ptr, version_string, string_len);
ptr += string_len;
// 8 zeroes
std::memset(ptr, 0, 8);
#ifndef TORRENT_DISABLE_DHT
// indicate that we support the DHT messages
*(ptr + 7) |= 0x01;
#endif
// we support extensions
*(ptr + 5) |= 0x10;
// we support FAST extension
*(ptr + 7) |= 0x04;
// this is a v1 peer in a hybrid torrent
// indicate that we support upgrading to v2
if (!peer_info_struct()->protocol_v2 && t->info_hash().has_v2())
{
*(ptr + 7) |= 0x10;
}
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::outgoing_message))
{
std::string bitmask;
for (int k = 0; k < 8; ++k)
{
for (int j = 0; j < 8; ++j)
{
if (ptr[k] & (0x80 >> j)) bitmask += '1';
else bitmask += '0';
}
}
peer_log(peer_log_alert::outgoing_message, "EXTENSIONS"
, "%s", bitmask.c_str());
}
#endif
ptr += 8;
// info hash
sha1_hash const& ih = associated_info_hash();
std::memcpy(ptr, ih.data(), ih.size());
ptr += 20;
std::memcpy(ptr, m_our_peer_id.data(), 20);
TORRENT_ASSERT(!ih.is_all_zeros());
#ifndef TORRENT_DISABLE_LOGGING
if (should_log(peer_log_alert::outgoing))
{
peer_log(peer_log_alert::outgoing, "HANDSHAKE"
, "sent peer_id: %s client: %s"
, aux::to_hex(m_our_peer_id).c_str(), identify_client(m_our_peer_id).c_str());
}
if (should_log(peer_log_alert::outgoing_message))
{
peer_log(peer_log_alert::outgoing_message, "HANDSHAKE"
, "ih: %s", aux::to_hex(ih).c_str());
}
#endif
send_buffer(handshake);
}
piece_block_progress bt_peer_connection::downloading_piece_progress() const
{
std::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
span<char const> recv_buffer = m_recv_buffer.get();
// are we currently receiving a 'piece' message?
if (m_state != state_t::read_packet
|| int(recv_buffer.size()) <= 9
|| recv_buffer[0] != msg_piece)
return {};
const char* ptr = recv_buffer.data() + 1;
peer_request r;
r.piece = piece_index_t(aux::read_int32(ptr));
r.start = aux::read_int32(ptr);
r.length = m_recv_buffer.packet_size() - 9;
// is any of the piece message header data invalid?
if (!verify_piece(r)) return {};
piece_block_progress p;
p.piece_index = r.piece;
p.block_index = r.start / t->block_size();
p.bytes_downloaded = int(recv_buffer.size()) - 9;
p.full_block_bytes = r.length;
return p;
}
// message handlers
// -----------------------------
// ----------- CHOKE -----------
// -----------------------------
void bt_peer_connection::on_choke(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received >= 0);
received_bytes(0, received);
if (m_recv_buffer.packet_size() != 1)
{
disconnect(errors::invalid_choke, operation_t::bittorrent, peer_error);
return;
}
if (!m_recv_buffer.packet_finished()) return;
incoming_choke();
if (is_disconnecting()) return;
if (!m_supports_fast)
{
// we just got choked, and the peer that choked use
// doesn't support fast extensions, so we have to
// assume that the choke message implies that all
// of our requests are rejected. Go through them and
// pretend that we received reject request messages
std::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
auto const dlq = download_queue();
for (pending_block const& pb : dlq)
{
peer_request r;
r.piece = pb.block.piece_index;
r.start = pb.block.block_index * t->block_size();
r.length = t->block_size();
// if it's the last piece, make sure to
// set the length of the request to not
// exceed the end of the torrent. This is
// necessary in order to maintain a correct
// m_outstanding_bytes
if (r.piece == t->torrent_file().last_piece())
{
r.length = std::min(t->torrent_file().piece_size(
r.piece) - r.start, r.length);
}
incoming_reject_request(r);
}
}
}
// -----------------------------
// ---------- UNCHOKE ----------
// -----------------------------
void bt_peer_connection::on_unchoke(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received >= 0);
received_bytes(0, received);
if (m_recv_buffer.packet_size() != 1)
{
disconnect(errors::invalid_unchoke, operation_t::bittorrent, peer_error);
return;
}
if (!m_recv_buffer.packet_finished()) return;
incoming_unchoke();
}
// -----------------------------
// -------- INTERESTED ---------
// -----------------------------
void bt_peer_connection::on_interested(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received >= 0);
received_bytes(0, received);
if (m_recv_buffer.packet_size() != 1)
{
disconnect(errors::invalid_interested, operation_t::bittorrent, peer_error);
return;
}
if (!m_recv_buffer.packet_finished()) return;
// we defer sending the allowed set until the peer says it's interested in
// us. This saves some bandwidth and allows us to omit messages for pieces
// that the peer already has
if (!m_sent_allowed_fast && m_supports_fast)
{
m_sent_allowed_fast = true;
send_allowed_set();
}
incoming_interested();
}
// -----------------------------
// ------ NOT INTERESTED -------
// -----------------------------
void bt_peer_connection::on_not_interested(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received >= 0);
received_bytes(0, received);
if (m_recv_buffer.packet_size() != 1)
{
disconnect(errors::invalid_not_interested, operation_t::bittorrent, peer_error);
return;
}
if (!m_recv_buffer.packet_finished()) return;
incoming_not_interested();
}
// -----------------------------
// ----------- HAVE ------------
// -----------------------------
void bt_peer_connection::on_have(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received >= 0);
received_bytes(0, received);
if (m_recv_buffer.packet_size() != 5)
{
disconnect(errors::invalid_have, operation_t::bittorrent, peer_error);
return;
}
if (!m_recv_buffer.packet_finished()) return;
span<char const> recv_buffer = m_recv_buffer.get();
const char* ptr = recv_buffer.data() + 1;
piece_index_t const index(aux::read_int32(ptr));
incoming_have(index);
maybe_send_hash_request();
}
// -----------------------------
// --------- BITFIELD ----------
// -----------------------------
void bt_peer_connection::on_bitfield(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received >= 0);
std::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
received_bytes(0, received);
// if we don't have the metadata, we cannot
// verify the bitfield size
if (t->valid_metadata()
&& m_recv_buffer.packet_size() - 1 != (t->torrent_file().num_pieces() + CHAR_BIT - 1) / CHAR_BIT)
{
disconnect(errors::invalid_bitfield_size, operation_t::bittorrent, peer_error);
return;
}
if (!m_recv_buffer.packet_finished()) return;
span<char const> recv_buffer = m_recv_buffer.get();