/
bt_peer_connection.cpp
2648 lines (2201 loc) · 66.7 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) 2003 - 2006, Arvid Norberg
Copyright (c) 2007, Arvid Norberg, Un Shyam
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/pch.hpp"
#include <vector>
#include <iostream>
#include <iomanip>
#include <limits>
#include <boost/bind.hpp>
#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/invariant_check.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/version.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/aux_/session_impl.hpp"
#ifndef TORRENT_DISABLE_ENCRYPTION
#include "libtorrent/pe_crypto.hpp"
#include "libtorrent/hasher.hpp"
#endif
using boost::bind;
using boost::shared_ptr;
using libtorrent::aux::session_impl;
namespace libtorrent
{
const bt_peer_connection::message_handler
bt_peer_connection::m_message_handler[] =
{
&bt_peer_connection::on_choke,
&bt_peer_connection::on_unchoke,
&bt_peer_connection::on_interested,
&bt_peer_connection::on_not_interested,
&bt_peer_connection::on_have,
&bt_peer_connection::on_bitfield,
&bt_peer_connection::on_request,
&bt_peer_connection::on_piece,
&bt_peer_connection::on_cancel,
&bt_peer_connection::on_dht_port,
0, 0, 0,
// FAST extension messages
&bt_peer_connection::on_suggest_piece,
&bt_peer_connection::on_have_all,
&bt_peer_connection::on_have_none,
&bt_peer_connection::on_reject_request,
&bt_peer_connection::on_allowed_fast,
0, 0,
&bt_peer_connection::on_extended
};
bt_peer_connection::bt_peer_connection(
session_impl& ses
, boost::weak_ptr<torrent> tor
, shared_ptr<socket_type> s
, tcp::endpoint const& remote
, policy::peer* peerinfo)
: peer_connection(ses, tor, s, remote
, peerinfo)
, m_state(read_protocol_identifier)
#ifndef TORRENT_DISABLE_EXTENSIONS
, m_supports_extensions(false)
#endif
, m_supports_dht_port(false)
, m_supports_fast(false)
#ifndef TORRENT_DISABLE_ENCRYPTION
, m_encrypted(false)
, m_rc4_encrypted(false)
, m_sync_bytes_read(0)
, m_enc_send_buffer(0, 0)
#endif
#ifndef NDEBUG
, m_sent_bitfield(false)
, m_in_constructor(true)
, m_sent_handshake(false)
#endif
{
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << "*** bt_peer_connection\n";
#endif
#ifndef NDEBUG
m_in_constructor = false;
#endif
}
bt_peer_connection::bt_peer_connection(
session_impl& ses
, boost::shared_ptr<socket_type> s
, tcp::endpoint const& remote
, policy::peer* peerinfo)
: peer_connection(ses, s, remote, peerinfo)
, m_state(read_protocol_identifier)
#ifndef TORRENT_DISABLE_EXTENSIONS
, m_supports_extensions(false)
#endif
, m_supports_dht_port(false)
, m_supports_fast(false)
#ifndef TORRENT_DISABLE_ENCRYPTION
, m_encrypted(false)
, m_rc4_encrypted(false)
, m_sync_bytes_read(0)
, m_enc_send_buffer(0, 0)
#endif
#ifndef NDEBUG
, m_sent_bitfield(false)
, m_in_constructor(true)
, m_sent_handshake(false)
#endif
{
// we are not attached to any torrent yet.
// we have to wait for the handshake to see
// which torrent the connector want's to connect to
// upload bandwidth will only be given to connections
// that are part of a torrent. Since this is an incoming
// connection, we have to give it some initial bandwidth
// to send the handshake.
#ifndef TORRENT_DISABLE_ENCRYPTION
m_bandwidth_limit[download_channel].assign(2048);
m_bandwidth_limit[upload_channel].assign(2048);
#else
m_bandwidth_limit[download_channel].assign(80);
m_bandwidth_limit[upload_channel].assign(80);
#endif
#ifndef NDEBUG
m_in_constructor = false;
#endif
}
void bt_peer_connection::start()
{
peer_connection::start();
// start in the state where we are trying to read the
// handshake from the other side
reset_recv_buffer(20);
setup_receive();
}
bt_peer_connection::~bt_peer_connection()
{
}
void bt_peer_connection::on_connected()
{
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings::enc_policy const& out_enc_policy = m_ses.get_pe_settings().out_enc_policy;
if (out_enc_policy == pe_settings::forced)
{
write_pe1_2_dhkey();
if (is_disconnecting()) return;
m_state = read_pe_dhkey;
reset_recv_buffer(dh_key_len);
setup_receive();
}
else if (out_enc_policy == pe_settings::enabled)
{
TORRENT_ASSERT(peer_info_struct());
policy::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 = read_pe_dhkey;
reset_recv_buffer(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();
reset_recv_buffer(20);
setup_receive();
}
}
else if (out_enc_policy == pe_settings::disabled)
#endif
{
write_handshake();
// start in the state where we are trying to read the
// handshake from the other side
reset_recv_buffer(20);
setup_receive();
}
}
void bt_peer_connection::on_metadata()
{
boost::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
write_bitfield();
#ifndef TORRENT_DISABLE_DHT
if (m_supports_dht_port && m_ses.m_dht)
write_dht_port(m_ses.get_dht_settings().service_port);
#endif
if (is_interesting()) write_interested();
}
void bt_peer_connection::write_dht_port(int listen_port)
{
INVARIANT_CHECK;
TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << time_now_string()
<< " ==> DHT_PORT [ " << listen_port << " ]\n";
#endif
char msg[] = {0,0,0,3, msg_dht_port, 0, 0};
char* ptr = msg + 5;
detail::write_uint16(listen_port, ptr);
send_buffer(msg, sizeof(msg));
}
void bt_peer_connection::write_have_all()
{
INVARIANT_CHECK;
TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
#ifndef NDEBUG
m_sent_bitfield = true;
#endif
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << time_now_string()
<< " ==> HAVE_ALL\n";
#endif
char msg[] = {0,0,0,1, msg_have_all};
send_buffer(msg, sizeof(msg));
}
void bt_peer_connection::write_have_none()
{
INVARIANT_CHECK;
TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
#ifndef NDEBUG
m_sent_bitfield = true;
#endif
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << time_now_string()
<< " ==> HAVE_NONE\n";
#endif
char msg[] = {0,0,0,1, msg_have_none};
send_buffer(msg, sizeof(msg));
}
void bt_peer_connection::write_reject_request(peer_request const& r)
{
INVARIANT_CHECK;
if (!m_supports_fast) return;
TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
char msg[] = {0,0,0,13, msg_reject_request,0,0,0,0, 0,0,0,0, 0,0,0,0};
char* ptr = msg + 5;
detail::write_int32(r.piece, ptr); // index
detail::write_int32(r.start, ptr); // begin
detail::write_int32(r.length, ptr); // length
send_buffer(msg, sizeof(msg));
}
void bt_peer_connection::write_allow_fast(int piece)
{
INVARIANT_CHECK;
TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
TORRENT_ASSERT(m_supports_fast);
char msg[] = {0,0,0,5, msg_allowed_fast, 0, 0, 0, 0};
char* ptr = msg + 5;
detail::write_int32(piece, ptr);
send_buffer(msg, sizeof(msg));
}
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_local()) p.flags |= peer_info::local_connection;
#ifndef TORRENT_DISABLE_ENCRYPTION
if (m_encrypted)
{
m_rc4_encrypted ?
p.flags |= peer_info::rc4_encrypted :
p.flags |= peer_info::plaintext_encrypted;
}
#endif
if (!is_connecting() && in_handshake())
p.flags |= peer_info::handshake;
if (is_connecting() && !is_queued()) p.flags |= peer_info::connecting;
if (is_queued()) p.flags |= peer_info::queued;
p.client = m_client_version;
p.connection_type = peer_info::standard_bittorrent;
}
bool bt_peer_connection::in_handshake() const
{
return m_state < read_packet_size;
}
#ifndef 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);
#ifdef TORRENT_VERBOSE_LOGGING
if (is_local())
(*m_logger) << " initiating encrypted handshake\n";
#endif
m_dh_key_exchange.reset(new (std::nothrow) dh_key_exchange);
if (!m_dh_key_exchange || !m_dh_key_exchange->good())
{
disconnect("out of memory");
return;
}
int pad_size = std::rand() % 512;
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << " pad size: " << pad_size << "\n";
#endif
buffer::interval send_buf = allocate_send_buffer(dh_key_len + pad_size);
if (send_buf.begin == 0)
{
disconnect("out of memory");
return;
}
std::copy(m_dh_key_exchange->get_local_key(),
m_dh_key_exchange->get_local_key() + dh_key_len,
send_buf.begin);
std::generate(send_buf.begin + dh_key_len, send_buf.end, std::rand);
setup_send();
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << " sent DH key\n";
#endif
}
void bt_peer_connection::write_pe3_sync()
{
INVARIANT_CHECK;
TORRENT_ASSERT(!m_encrypted);
TORRENT_ASSERT(!m_rc4_encrypted);
TORRENT_ASSERT(is_local());
TORRENT_ASSERT(!m_sent_handshake);
boost::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
hasher h;
sha1_hash const& info_hash = t->torrent_file().info_hash();
char const* const secret = m_dh_key_exchange->get_secret();
int pad_size = rand() % 512;
// synchash,skeyhash,vc,crypto_provide,len(pad),pad,len(ia)
buffer::interval send_buf =
allocate_send_buffer(20 + 20 + 8 + 4 + 2 + pad_size + 2);
if (send_buf.begin == 0) return; // out of memory
// sync hash (hash('req1',S))
h.reset();
h.update("req1",4);
h.update(secret, dh_key_len);
sha1_hash sync_hash = h.final();
std::copy(sync_hash.begin(), sync_hash.end(), send_buf.begin);
send_buf.begin += 20;
// stream key obfuscated hash [ hash('req2',SKEY) xor hash('req3',S) ]
h.reset();
h.update("req2",4);
h.update((const char*)info_hash.begin(), 20);
sha1_hash streamkey_hash = h.final();
h.reset();
h.update("req3",4);
h.update(secret, dh_key_len);
sha1_hash obfsc_hash = h.final();
obfsc_hash ^= streamkey_hash;
std::copy(obfsc_hash.begin(), obfsc_hash.end(), send_buf.begin);
send_buf.begin += 20;
// Discard DH key exchange data, setup RC4 keys
init_pe_RC4_handler(secret, info_hash);
m_dh_key_exchange.reset(); // secret should be invalid at this point
// write the verification constant and crypto field
TORRENT_ASSERT(send_buf.left() == 8 + 4 + 2 + pad_size + 2);
int encrypt_size = send_buf.left();
int crypto_provide = 0;
pe_settings::enc_level const& allowed_enc_level = m_ses.get_pe_settings().allowed_enc_level;
if (allowed_enc_level == pe_settings::both)
crypto_provide = 0x03;
else if (allowed_enc_level == pe_settings::rc4)
crypto_provide = 0x02;
else if (allowed_enc_level == pe_settings::plaintext)
crypto_provide = 0x01;
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << " crypto provide : [ ";
if (allowed_enc_level == pe_settings::both)
(*m_logger) << "plaintext rc4 ]\n";
else if (allowed_enc_level == pe_settings::rc4)
(*m_logger) << "rc4 ]\n";
else if (allowed_enc_level == pe_settings::plaintext)
(*m_logger) << "plaintext ]\n";
#endif
write_pe_vc_cryptofield(send_buf, crypto_provide, pad_size);
m_RC4_handler->encrypt(send_buf.end - encrypt_size, encrypt_size);
TORRENT_ASSERT(send_buf.begin == send_buf.end);
setup_send();
}
void bt_peer_connection::write_pe4_sync(int crypto_select)
{
INVARIANT_CHECK;
TORRENT_ASSERT(!is_local());
TORRENT_ASSERT(!m_encrypted);
TORRENT_ASSERT(!m_rc4_encrypted);
TORRENT_ASSERT(crypto_select == 0x02 || crypto_select == 0x01);
TORRENT_ASSERT(!m_sent_handshake);
int pad_size =rand() % 512;
const int buf_size = 8 + 4 + 2 + pad_size;
buffer::interval send_buf = allocate_send_buffer(buf_size);
if (send_buf.begin == 0) return; // out of memory
write_pe_vc_cryptofield(send_buf, crypto_select, pad_size);
m_RC4_handler->encrypt(send_buf.end - buf_size, buf_size);
setup_send();
// encryption method has been negotiated
if (crypto_select == 0x02)
m_rc4_encrypted = true;
else // 0x01
m_rc4_encrypted = false;
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << " crypto select : [ ";
if (crypto_select == 0x01)
(*m_logger) << "plaintext ]\n";
else
(*m_logger) << "rc4 ]\n";
#endif
}
void bt_peer_connection::write_pe_vc_cryptofield(buffer::interval& write_buf
, int crypto_field, int pad_size)
{
INVARIANT_CHECK;
TORRENT_ASSERT(crypto_field <= 0x03 && crypto_field > 0);
// vc,crypto_field,len(pad),pad, (len(ia))
TORRENT_ASSERT( (write_buf.left() == 8+4+2+pad_size+2 && is_local()) ||
(write_buf.left() == 8+4+2+pad_size && !is_local()) );
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::fill(write_buf.begin, write_buf.begin + 8, 0);
write_buf.begin += 8;
detail::write_uint32(crypto_field, write_buf.begin);
detail::write_uint16(pad_size, write_buf.begin); // len (pad)
// fill pad with zeroes
std::generate(write_buf.begin, write_buf.begin + pad_size, &std::rand);
write_buf.begin += pad_size;
// append len(ia) if we are initiating
if (is_local())
detail::write_uint16(handshake_len, write_buf.begin); // len(IA)
TORRENT_ASSERT(write_buf.begin == write_buf.end);
}
void bt_peer_connection::init_pe_RC4_handler(char const* secret, sha1_hash const& stream_key)
{
INVARIANT_CHECK;
TORRENT_ASSERT(secret);
hasher h;
static const char keyA[] = "keyA";
static const char keyB[] = "keyB";
// encryption rc4 longkeys
// outgoing connection : hash ('keyA',S,SKEY)
// incoming connection : hash ('keyB',S,SKEY)
is_local() ? h.update(keyA, 4) : h.update(keyB, 4);
h.update(secret, dh_key_len);
h.update((char const*)stream_key.begin(), 20);
const sha1_hash local_key = h.final();
h.reset();
// decryption rc4 longkeys
// outgoing connection : hash ('keyB',S,SKEY)
// incoming connection : hash ('keyA',S,SKEY)
is_local() ? h.update(keyB, 4) : h.update(keyA, 4);
h.update(secret, dh_key_len);
h.update((char const*)stream_key.begin(), 20);
const sha1_hash remote_key = h.final();
TORRENT_ASSERT(!m_RC4_handler.get());
m_RC4_handler.reset(new RC4_handler (local_key, remote_key));
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << " computed RC4 keys\n";
#endif
}
void bt_peer_connection::send_buffer(char* buf, int size, int flags)
{
TORRENT_ASSERT(buf);
TORRENT_ASSERT(size > 0);
if (m_encrypted && m_rc4_encrypted)
m_RC4_handler->encrypt(buf, size);
peer_connection::send_buffer(buf, size, flags);
}
buffer::interval bt_peer_connection::allocate_send_buffer(int size)
{
if (m_encrypted && m_rc4_encrypted)
{
TORRENT_ASSERT(m_enc_send_buffer.left() == 0);
m_enc_send_buffer = peer_connection::allocate_send_buffer(size);
return m_enc_send_buffer;
}
else
{
buffer::interval i = peer_connection::allocate_send_buffer(size);
return i;
}
}
void bt_peer_connection::setup_send()
{
if (m_encrypted && m_rc4_encrypted && m_enc_send_buffer.left())
{
TORRENT_ASSERT(m_enc_send_buffer.begin);
TORRENT_ASSERT(m_enc_send_buffer.end);
m_RC4_handler->encrypt(m_enc_send_buffer.begin, m_enc_send_buffer.left());
m_enc_send_buffer.end = m_enc_send_buffer.begin;
}
peer_connection::setup_send();
}
int bt_peer_connection::get_syncoffset(char const* src, int src_size,
char const* target, int target_size) const
{
TORRENT_ASSERT(target_size >= src_size);
TORRENT_ASSERT(src_size > 0);
TORRENT_ASSERT(src);
TORRENT_ASSERT(target);
int traverse_limit = target_size - src_size;
// TODO: this could be optimized using knuth morris pratt
for (int i = 0; i < traverse_limit; ++i)
{
char const* target_ptr = target + i;
if (std::equal(src, src+src_size, target_ptr))
return i;
}
// // Partial sync
// for (int i = 0; i < target_size; ++i)
// {
// // first is iterator in src[] at which mismatch occurs
// // second is iterator in target[] at which mismatch occurs
// std::pair<const char*, const char*> ret;
// int src_sync_size;
// if (i > traverse_limit) // partial sync test
// {
// ret = std::mismatch(src, src + src_size - (i - traverse_limit), &target[i]);
// src_sync_size = ret.first - src;
// if (src_sync_size == (src_size - (i - traverse_limit)))
// return i;
// }
// else // complete sync test
// {
// ret = std::mismatch(src, src + src_size, &target[i]);
// src_sync_size = ret.first - src;
// if (src_sync_size == src_size)
// return i;
// }
// }
// no complete sync
return -1;
}
#endif // #ifndef TORRENT_DISABLE_ENCRYPTION
void bt_peer_connection::write_handshake()
{
INVARIANT_CHECK;
TORRENT_ASSERT(!m_sent_handshake);
#ifndef NDEBUG
m_sent_handshake = true;
#endif
boost::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
// add handshake to the send buffer
const char version_string[] = "BitTorrent protocol";
const int string_len = sizeof(version_string)-1;
buffer::interval i = allocate_send_buffer(1 + string_len + 8 + 20 + 20);
if (i.begin == 0) return; // out of memory
// length of version string
*i.begin = string_len;
++i.begin;
// version string itself
std::copy(
version_string
, version_string + string_len
, i.begin);
i.begin += string_len;
// 8 zeroes
std::fill(i.begin, i.begin + 8, 0);
#ifndef TORRENT_DISABLE_DHT
// indicate that we support the DHT messages
*(i.begin + 7) |= 0x01;
#endif
#ifndef TORRENT_DISABLE_EXTENSIONS
// we support extensions
*(i.begin + 5) |= 0x10;
#endif
// we support FAST extension
*(i.begin + 7) |= 0x04;
i.begin += 8;
// info hash
sha1_hash const& ih = t->torrent_file().info_hash();
std::copy(ih.begin(), ih.end(), i.begin);
i.begin += 20;
// peer id
std::copy(
m_ses.get_peer_id().begin()
, m_ses.get_peer_id().end()
, i.begin);
i.begin += 20;
TORRENT_ASSERT(i.begin == i.end);
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << time_now_string() << " ==> HANDSHAKE\n";
#endif
setup_send();
}
boost::optional<piece_block_progress> bt_peer_connection::downloading_piece_progress() const
{
boost::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
buffer::const_interval recv_buffer = receive_buffer();
// are we currently receiving a 'piece' message?
if (m_state != read_packet
|| recv_buffer.left() < 9
|| recv_buffer[0] != msg_piece)
return boost::optional<piece_block_progress>();
const char* ptr = recv_buffer.begin + 1;
peer_request r;
r.piece = detail::read_int32(ptr);
r.start = detail::read_int32(ptr);
r.length = packet_size() - 9;
// is any of the piece message header data invalid?
if (!verify_piece(r))
return boost::optional<piece_block_progress>();
piece_block_progress p;
p.piece_index = r.piece;
p.block_index = r.start / t->block_size();
p.bytes_downloaded = recv_buffer.left() - 9;
p.full_block_bytes = r.length;
return boost::optional<piece_block_progress>(p);
}
// message handlers
// -----------------------------
// --------- KEEPALIVE ---------
// -----------------------------
void bt_peer_connection::on_keepalive()
{
INVARIANT_CHECK;
#ifdef TORRENT_VERBOSE_LOGGING
(*m_logger) << time_now_string() << " <== KEEPALIVE\n";
#endif
incoming_keepalive();
}
// -----------------------------
// ----------- CHOKE -----------
// -----------------------------
void bt_peer_connection::on_choke(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received > 0);
if (packet_size() != 1)
{
disconnect("'choke' message size != 1", 2);
return;
}
m_statistics.received_bytes(0, received);
if (!packet_finished()) return;
incoming_choke();
if (is_disconnecting()) return;
if (!m_supports_fast)
{
boost::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
while (!download_queue().empty())
{
piece_block const& b = download_queue().front().block;
peer_request r;
r.piece = b.piece_index;
r.start = b.block_index * t->block_size();
r.length = t->block_size();
incoming_reject_request(r);
}
}
}
// -----------------------------
// ---------- UNCHOKE ----------
// -----------------------------
void bt_peer_connection::on_unchoke(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received > 0);
if (packet_size() != 1)
{
disconnect("'unchoke' message size != 1", 2);
return;
}
m_statistics.received_bytes(0, received);
if (!packet_finished()) return;
incoming_unchoke();
}
// -----------------------------
// -------- INTERESTED ---------
// -----------------------------
void bt_peer_connection::on_interested(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received > 0);
if (packet_size() != 1)
{
disconnect("'interested' message size != 1", 2);
return;
}
m_statistics.received_bytes(0, received);
if (!packet_finished()) return;
incoming_interested();
}
// -----------------------------
// ------ NOT INTERESTED -------
// -----------------------------
void bt_peer_connection::on_not_interested(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received > 0);
if (packet_size() != 1)
{
disconnect("'not interested' message size != 1", 2);
return;
}
m_statistics.received_bytes(0, received);
if (!packet_finished()) return;
incoming_not_interested();
}
// -----------------------------
// ----------- HAVE ------------
// -----------------------------
void bt_peer_connection::on_have(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received > 0);
if (packet_size() != 5)
{
disconnect("'have' message size != 5", 2);
return;
}
m_statistics.received_bytes(0, received);
if (!packet_finished()) return;
buffer::const_interval recv_buffer = receive_buffer();
const char* ptr = recv_buffer.begin + 1;
int index = detail::read_int32(ptr);
incoming_have(index);
}
// -----------------------------
// --------- BITFIELD ----------
// -----------------------------
void bt_peer_connection::on_bitfield(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received > 0);
boost::shared_ptr<torrent> t = associated_torrent().lock();
TORRENT_ASSERT(t);
// if we don't have the metedata, we cannot
// verify the bitfield size
if (t->valid_metadata()
&& packet_size() - 1 != ((int)get_bitfield().size() + 7) / 8)
{
disconnect("bitfield with invalid size", 2);
return;
}
m_statistics.received_bytes(0, received);
if (!packet_finished()) return;
buffer::const_interval recv_buffer = receive_buffer();
bitfield bits;
bits.borrow_bytes((char*)recv_buffer.begin + 1
, t->valid_metadata()?get_bitfield().size():(packet_size()-1)*8);
incoming_bitfield(bits);
}
// -----------------------------
// ---------- REQUEST ----------
// -----------------------------
void bt_peer_connection::on_request(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received > 0);
if (packet_size() != 13)
{
disconnect("'request' message size != 13", 2);
return;
}
m_statistics.received_bytes(0, received);
if (!packet_finished()) return;
buffer::const_interval recv_buffer = receive_buffer();
peer_request r;
const char* ptr = recv_buffer.begin + 1;
r.piece = detail::read_int32(ptr);
r.start = detail::read_int32(ptr);
r.length = detail::read_int32(ptr);
incoming_request(r);
}
// -----------------------------
// ----------- PIECE -----------
// -----------------------------
void bt_peer_connection::on_piece(int received)
{
INVARIANT_CHECK;
TORRENT_ASSERT(received > 0);
buffer::const_interval recv_buffer = receive_buffer();
int recv_pos = recv_buffer.end - recv_buffer.begin;
if (recv_pos == 1)