3 Copyright (c) 2003 - 2006, Arvid Norberg
4 Copyright (c) 2007, Arvid Norberg, Un Shyam
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions
11 * Redistributions of source code must retain the above copyright
12 notice, this list of conditions and the following disclaimer.
13 * Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in
15 the documentation and/or other materials provided with the distribution.
16 * Neither the name of the author nor the names of its
17 contributors may be used to endorse or promote products derived
18 from this software without specific prior written permission.
20 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 POSSIBILITY OF SUCH DAMAGE.
34 #include "libtorrent/pch.hpp"
40 #include <boost/bind.hpp>
42 #include "libtorrent/bt_peer_connection.hpp"
43 #include "libtorrent/session.hpp"
44 #include "libtorrent/identify_client.hpp"
45 #include "libtorrent/entry.hpp"
46 #include "libtorrent/bencode.hpp"
47 #include "libtorrent/alert_types.hpp"
48 #include "libtorrent/invariant_check.hpp"
49 #include "libtorrent/io.hpp"
50 #include "libtorrent/version.hpp"
51 #include "libtorrent/extensions.hpp"
52 #include "libtorrent/aux_/session_impl.hpp"
54 #ifndef TORRENT_DISABLE_ENCRYPTION
55 #include "libtorrent/pe_crypto.hpp"
56 #include "libtorrent/hasher.hpp"
60 using boost::shared_ptr
;
61 using libtorrent::aux::session_impl
;
65 const bt_peer_connection::message_handler
66 bt_peer_connection::m_message_handler
[] =
68 &bt_peer_connection::on_choke
,
69 &bt_peer_connection::on_unchoke
,
70 &bt_peer_connection::on_interested
,
71 &bt_peer_connection::on_not_interested
,
72 &bt_peer_connection::on_have
,
73 &bt_peer_connection::on_bitfield
,
74 &bt_peer_connection::on_request
,
75 &bt_peer_connection::on_piece
,
76 &bt_peer_connection::on_cancel
,
77 &bt_peer_connection::on_dht_port
,
79 // FAST extension messages
80 &bt_peer_connection::on_suggest_piece
,
81 &bt_peer_connection::on_have_all
,
82 &bt_peer_connection::on_have_none
,
83 &bt_peer_connection::on_reject_request
,
84 &bt_peer_connection::on_allowed_fast
,
86 &bt_peer_connection::on_extended
90 bt_peer_connection::bt_peer_connection(
92 , boost::weak_ptr
<torrent
> tor
93 , shared_ptr
<socket_type
> s
94 , tcp::endpoint
const& remote
95 , policy::peer
* peerinfo
)
96 : peer_connection(ses
, tor
, s
, remote
98 , m_state(read_protocol_identifier
)
99 #ifndef TORRENT_DISABLE_EXTENSIONS
100 , m_supports_extensions(false)
102 , m_supports_dht_port(false)
103 , m_supports_fast(false)
104 #ifndef TORRENT_DISABLE_ENCRYPTION
106 , m_rc4_encrypted(false)
107 , m_sync_bytes_read(0)
108 , m_enc_send_buffer(0, 0)
111 , m_sent_bitfield(false)
112 , m_in_constructor(true)
113 , m_sent_handshake(false)
116 #ifdef TORRENT_VERBOSE_LOGGING
117 (*m_logger
) << "*** bt_peer_connection\n";
121 m_in_constructor
= false;
125 bt_peer_connection::bt_peer_connection(
127 , boost::shared_ptr
<socket_type
> s
128 , tcp::endpoint
const& remote
129 , policy::peer
* peerinfo
)
130 : peer_connection(ses
, s
, remote
, peerinfo
)
131 , m_state(read_protocol_identifier
)
132 #ifndef TORRENT_DISABLE_EXTENSIONS
133 , m_supports_extensions(false)
135 , m_supports_dht_port(false)
136 , m_supports_fast(false)
137 #ifndef TORRENT_DISABLE_ENCRYPTION
139 , m_rc4_encrypted(false)
140 , m_sync_bytes_read(0)
141 , m_enc_send_buffer(0, 0)
144 , m_sent_bitfield(false)
145 , m_in_constructor(true)
146 , m_sent_handshake(false)
150 // we are not attached to any torrent yet.
151 // we have to wait for the handshake to see
152 // which torrent the connector want's to connect to
155 // upload bandwidth will only be given to connections
156 // that are part of a torrent. Since this is an incoming
157 // connection, we have to give it some initial bandwidth
158 // to send the handshake.
159 #ifndef TORRENT_DISABLE_ENCRYPTION
160 m_bandwidth_limit
[download_channel
].assign(2048);
161 m_bandwidth_limit
[upload_channel
].assign(2048);
163 m_bandwidth_limit
[download_channel
].assign(80);
164 m_bandwidth_limit
[upload_channel
].assign(80);
168 m_in_constructor
= false;
172 void bt_peer_connection::start()
174 peer_connection::start();
176 // start in the state where we are trying to read the
177 // handshake from the other side
178 reset_recv_buffer(20);
182 bt_peer_connection::~bt_peer_connection()
186 void bt_peer_connection::on_connected()
188 #ifndef TORRENT_DISABLE_ENCRYPTION
190 pe_settings::enc_policy
const& out_enc_policy
= m_ses
.get_pe_settings().out_enc_policy
;
192 if (out_enc_policy
== pe_settings::forced
)
195 if (is_disconnecting()) return;
197 m_state
= read_pe_dhkey
;
198 reset_recv_buffer(dh_key_len
);
201 else if (out_enc_policy
== pe_settings::enabled
)
203 TORRENT_ASSERT(peer_info_struct());
205 policy::peer
* pi
= peer_info_struct();
206 if (pi
->pe_support
== true)
208 // toggle encryption support flag, toggled back to
209 // true if encrypted portion of the handshake
210 // completes correctly
211 pi
->pe_support
= false;
213 // if this fails, we need to reconnect
215 fast_reconnect(true);
218 if (is_disconnecting()) return;
219 m_state
= read_pe_dhkey
;
220 reset_recv_buffer(dh_key_len
);
223 else // pi->pe_support == false
225 // toggled back to false if standard handshake
226 // completes correctly (without encryption)
227 pi
->pe_support
= true;
230 reset_recv_buffer(20);
234 else if (out_enc_policy
== pe_settings::disabled
)
239 // start in the state where we are trying to read the
240 // handshake from the other side
241 reset_recv_buffer(20);
246 void bt_peer_connection::on_metadata()
248 // connections that are still in the handshake
249 // will send their bitfield when the handshake
251 if (m_state
< read_packet_size
) return;
252 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
255 #ifndef TORRENT_DISABLE_DHT
256 if (m_supports_dht_port
&& m_ses
.m_dht
)
257 write_dht_port(m_ses
.get_dht_settings().service_port
);
261 void bt_peer_connection::write_dht_port(int listen_port
)
265 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
267 #ifdef TORRENT_VERBOSE_LOGGING
268 (*m_logger
) << time_now_string()
269 << " ==> DHT_PORT [ " << listen_port
<< " ]\n";
271 char msg
[] = {0,0,0,3, msg_dht_port
, 0, 0};
273 detail::write_uint16(listen_port
, ptr
);
274 send_buffer(msg
, sizeof(msg
));
277 void bt_peer_connection::write_have_all()
280 TORRENT_ASSERT(m_sent_handshake
&& !m_sent_bitfield
);
282 m_sent_bitfield
= true;
284 #ifdef TORRENT_VERBOSE_LOGGING
285 (*m_logger
) << time_now_string()
286 << " ==> HAVE_ALL\n";
288 char msg
[] = {0,0,0,1, msg_have_all
};
289 send_buffer(msg
, sizeof(msg
));
292 void bt_peer_connection::write_have_none()
295 TORRENT_ASSERT(m_sent_handshake
&& !m_sent_bitfield
);
297 m_sent_bitfield
= true;
299 #ifdef TORRENT_VERBOSE_LOGGING
300 (*m_logger
) << time_now_string()
301 << " ==> HAVE_NONE\n";
303 char msg
[] = {0,0,0,1, msg_have_none
};
304 send_buffer(msg
, sizeof(msg
));
307 void bt_peer_connection::write_reject_request(peer_request
const& r
)
311 if (!m_supports_fast
) return;
313 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
314 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
316 char msg
[] = {0,0,0,13, msg_reject_request
,0,0,0,0, 0,0,0,0, 0,0,0,0};
318 detail::write_int32(r
.piece
, ptr
); // index
319 detail::write_int32(r
.start
, ptr
); // begin
320 detail::write_int32(r
.length
, ptr
); // length
321 send_buffer(msg
, sizeof(msg
));
324 void bt_peer_connection::write_allow_fast(int piece
)
328 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
329 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
330 TORRENT_ASSERT(m_supports_fast
);
332 char msg
[] = {0,0,0,5, msg_allowed_fast
, 0, 0, 0, 0};
334 detail::write_int32(piece
, ptr
);
335 send_buffer(msg
, sizeof(msg
));
338 void bt_peer_connection::get_specific_peer_info(peer_info
& p
) const
340 TORRENT_ASSERT(!associated_torrent().expired());
342 if (is_interesting()) p
.flags
|= peer_info::interesting
;
343 if (is_choked()) p
.flags
|= peer_info::choked
;
344 if (is_peer_interested()) p
.flags
|= peer_info::remote_interested
;
345 if (has_peer_choked()) p
.flags
|= peer_info::remote_choked
;
346 if (support_extensions()) p
.flags
|= peer_info::supports_extensions
;
347 if (is_local()) p
.flags
|= peer_info::local_connection
;
349 #ifndef TORRENT_DISABLE_ENCRYPTION
353 p
.flags
|= peer_info::rc4_encrypted
:
354 p
.flags
|= peer_info::plaintext_encrypted
;
358 if (!is_connecting() && in_handshake())
359 p
.flags
|= peer_info::handshake
;
360 if (is_connecting() && !is_queued()) p
.flags
|= peer_info::connecting
;
361 if (is_queued()) p
.flags
|= peer_info::queued
;
363 p
.client
= m_client_version
;
364 p
.connection_type
= peer_info::standard_bittorrent
;
368 bool bt_peer_connection::in_handshake() const
370 return m_state
< read_packet_size
;
373 #ifndef TORRENT_DISABLE_ENCRYPTION
375 void bt_peer_connection::write_pe1_2_dhkey()
379 TORRENT_ASSERT(!m_encrypted
);
380 TORRENT_ASSERT(!m_rc4_encrypted
);
381 TORRENT_ASSERT(!m_dh_key_exchange
.get());
382 TORRENT_ASSERT(!m_sent_handshake
);
384 #ifdef TORRENT_VERBOSE_LOGGING
386 (*m_logger
) << " initiating encrypted handshake\n";
389 m_dh_key_exchange
.reset(new (std::nothrow
) dh_key_exchange
);
390 if (!m_dh_key_exchange
|| !m_dh_key_exchange
->good())
392 disconnect("out of memory");
396 int pad_size
= std::rand() % 512;
398 #ifdef TORRENT_VERBOSE_LOGGING
399 (*m_logger
) << " pad size: " << pad_size
<< "\n";
402 buffer::interval send_buf
= allocate_send_buffer(dh_key_len
+ pad_size
);
403 if (send_buf
.begin
== 0)
405 disconnect("out of memory");
409 std::copy(m_dh_key_exchange
->get_local_key(),
410 m_dh_key_exchange
->get_local_key() + dh_key_len
,
413 std::generate(send_buf
.begin
+ dh_key_len
, send_buf
.end
, std::rand
);
416 #ifdef TORRENT_VERBOSE_LOGGING
417 (*m_logger
) << " sent DH key\n";
421 void bt_peer_connection::write_pe3_sync()
425 TORRENT_ASSERT(!m_encrypted
);
426 TORRENT_ASSERT(!m_rc4_encrypted
);
427 TORRENT_ASSERT(is_local());
428 TORRENT_ASSERT(!m_sent_handshake
);
430 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
434 sha1_hash
const& info_hash
= t
->torrent_file().info_hash();
435 char const* const secret
= m_dh_key_exchange
->get_secret();
437 int pad_size
= rand() % 512;
439 // synchash,skeyhash,vc,crypto_provide,len(pad),pad,len(ia)
440 buffer::interval send_buf
=
441 allocate_send_buffer(20 + 20 + 8 + 4 + 2 + pad_size
+ 2);
442 if (send_buf
.begin
== 0) return; // out of memory
444 // sync hash (hash('req1',S))
447 h
.update(secret
, dh_key_len
);
448 sha1_hash sync_hash
= h
.final();
450 std::copy(sync_hash
.begin(), sync_hash
.end(), send_buf
.begin
);
451 send_buf
.begin
+= 20;
453 // stream key obfuscated hash [ hash('req2',SKEY) xor hash('req3',S) ]
456 h
.update((const char*)info_hash
.begin(), 20);
457 sha1_hash streamkey_hash
= h
.final();
461 h
.update(secret
, dh_key_len
);
462 sha1_hash obfsc_hash
= h
.final();
463 obfsc_hash
^= streamkey_hash
;
465 std::copy(obfsc_hash
.begin(), obfsc_hash
.end(), send_buf
.begin
);
466 send_buf
.begin
+= 20;
468 // Discard DH key exchange data, setup RC4 keys
469 init_pe_RC4_handler(secret
, info_hash
);
470 m_dh_key_exchange
.reset(); // secret should be invalid at this point
472 // write the verification constant and crypto field
473 TORRENT_ASSERT(send_buf
.left() == 8 + 4 + 2 + pad_size
+ 2);
474 int encrypt_size
= send_buf
.left();
476 int crypto_provide
= 0;
477 pe_settings::enc_level
const& allowed_enc_level
= m_ses
.get_pe_settings().allowed_enc_level
;
479 if (allowed_enc_level
== pe_settings::both
)
480 crypto_provide
= 0x03;
481 else if (allowed_enc_level
== pe_settings::rc4
)
482 crypto_provide
= 0x02;
483 else if (allowed_enc_level
== pe_settings::plaintext
)
484 crypto_provide
= 0x01;
486 #ifdef TORRENT_VERBOSE_LOGGING
487 (*m_logger
) << " crypto provide : [ ";
488 if (allowed_enc_level
== pe_settings::both
)
489 (*m_logger
) << "plaintext rc4 ]\n";
490 else if (allowed_enc_level
== pe_settings::rc4
)
491 (*m_logger
) << "rc4 ]\n";
492 else if (allowed_enc_level
== pe_settings::plaintext
)
493 (*m_logger
) << "plaintext ]\n";
496 write_pe_vc_cryptofield(send_buf
, crypto_provide
, pad_size
);
497 m_RC4_handler
->encrypt(send_buf
.end
- encrypt_size
, encrypt_size
);
499 TORRENT_ASSERT(send_buf
.begin
== send_buf
.end
);
503 void bt_peer_connection::write_pe4_sync(int crypto_select
)
507 TORRENT_ASSERT(!is_local());
508 TORRENT_ASSERT(!m_encrypted
);
509 TORRENT_ASSERT(!m_rc4_encrypted
);
510 TORRENT_ASSERT(crypto_select
== 0x02 || crypto_select
== 0x01);
511 TORRENT_ASSERT(!m_sent_handshake
);
513 int pad_size
=rand() % 512;
515 const int buf_size
= 8 + 4 + 2 + pad_size
;
516 buffer::interval send_buf
= allocate_send_buffer(buf_size
);
517 if (send_buf
.begin
== 0) return; // out of memory
518 write_pe_vc_cryptofield(send_buf
, crypto_select
, pad_size
);
520 m_RC4_handler
->encrypt(send_buf
.end
- buf_size
, buf_size
);
523 // encryption method has been negotiated
524 if (crypto_select
== 0x02)
525 m_rc4_encrypted
= true;
527 m_rc4_encrypted
= false;
529 #ifdef TORRENT_VERBOSE_LOGGING
530 (*m_logger
) << " crypto select : [ ";
531 if (crypto_select
== 0x01)
532 (*m_logger
) << "plaintext ]\n";
534 (*m_logger
) << "rc4 ]\n";
538 void bt_peer_connection::write_pe_vc_cryptofield(buffer::interval
& write_buf
539 , int crypto_field
, int pad_size
)
543 TORRENT_ASSERT(crypto_field
<= 0x03 && crypto_field
> 0);
544 // vc,crypto_field,len(pad),pad, (len(ia))
545 TORRENT_ASSERT( (write_buf
.left() == 8+4+2+pad_size
+2 && is_local()) ||
546 (write_buf
.left() == 8+4+2+pad_size
&& !is_local()) );
547 TORRENT_ASSERT(!m_sent_handshake
);
549 // encrypt(vc, crypto_provide/select, len(Pad), len(IA))
550 // len(pad) is zero for now, len(IA) only for outgoing connections
553 std::fill(write_buf
.begin
, write_buf
.begin
+ 8, 0);
554 write_buf
.begin
+= 8;
556 detail::write_uint32(crypto_field
, write_buf
.begin
);
557 detail::write_uint16(pad_size
, write_buf
.begin
); // len (pad)
559 // fill pad with zeroes
560 std::generate(write_buf
.begin
, write_buf
.begin
+ pad_size
, &std::rand
);
561 write_buf
.begin
+= pad_size
;
563 // append len(ia) if we are initiating
565 detail::write_uint16(handshake_len
, write_buf
.begin
); // len(IA)
567 TORRENT_ASSERT(write_buf
.begin
== write_buf
.end
);
570 void bt_peer_connection::init_pe_RC4_handler(char const* secret
, sha1_hash
const& stream_key
)
574 TORRENT_ASSERT(secret
);
577 static const char keyA
[] = "keyA";
578 static const char keyB
[] = "keyB";
580 // encryption rc4 longkeys
581 // outgoing connection : hash ('keyA',S,SKEY)
582 // incoming connection : hash ('keyB',S,SKEY)
584 is_local() ? h
.update(keyA
, 4) : h
.update(keyB
, 4);
585 h
.update(secret
, dh_key_len
);
586 h
.update((char const*)stream_key
.begin(), 20);
587 const sha1_hash local_key
= h
.final();
591 // decryption rc4 longkeys
592 // outgoing connection : hash ('keyB',S,SKEY)
593 // incoming connection : hash ('keyA',S,SKEY)
595 is_local() ? h
.update(keyB
, 4) : h
.update(keyA
, 4);
596 h
.update(secret
, dh_key_len
);
597 h
.update((char const*)stream_key
.begin(), 20);
598 const sha1_hash remote_key
= h
.final();
600 TORRENT_ASSERT(!m_RC4_handler
.get());
601 m_RC4_handler
.reset(new RC4_handler (local_key
, remote_key
));
603 #ifdef TORRENT_VERBOSE_LOGGING
604 (*m_logger
) << " computed RC4 keys\n";
608 void bt_peer_connection::send_buffer(char* buf
, int size
, int flags
)
611 TORRENT_ASSERT(size
> 0);
613 if (m_encrypted
&& m_rc4_encrypted
)
614 m_RC4_handler
->encrypt(buf
, size
);
616 peer_connection::send_buffer(buf
, size
, flags
);
619 buffer::interval
bt_peer_connection::allocate_send_buffer(int size
)
621 if (m_encrypted
&& m_rc4_encrypted
)
623 TORRENT_ASSERT(m_enc_send_buffer
.left() == 0);
624 m_enc_send_buffer
= peer_connection::allocate_send_buffer(size
);
625 return m_enc_send_buffer
;
629 buffer::interval i
= peer_connection::allocate_send_buffer(size
);
634 void bt_peer_connection::setup_send()
636 if (m_encrypted
&& m_rc4_encrypted
&& m_enc_send_buffer
.left())
638 TORRENT_ASSERT(m_enc_send_buffer
.begin
);
639 TORRENT_ASSERT(m_enc_send_buffer
.end
);
641 m_RC4_handler
->encrypt(m_enc_send_buffer
.begin
, m_enc_send_buffer
.left());
642 m_enc_send_buffer
.end
= m_enc_send_buffer
.begin
;
644 peer_connection::setup_send();
647 int bt_peer_connection::get_syncoffset(char const* src
, int src_size
,
648 char const* target
, int target_size
) const
650 TORRENT_ASSERT(target_size
>= src_size
);
651 TORRENT_ASSERT(src_size
> 0);
653 TORRENT_ASSERT(target
);
655 int traverse_limit
= target_size
- src_size
;
657 // TODO: this could be optimized using knuth morris pratt
658 for (int i
= 0; i
< traverse_limit
; ++i
)
660 char const* target_ptr
= target
+ i
;
661 if (std::equal(src
, src
+src_size
, target_ptr
))
666 // for (int i = 0; i < target_size; ++i)
668 // // first is iterator in src[] at which mismatch occurs
669 // // second is iterator in target[] at which mismatch occurs
670 // std::pair<const char*, const char*> ret;
671 // int src_sync_size;
672 // if (i > traverse_limit) // partial sync test
674 // ret = std::mismatch(src, src + src_size - (i - traverse_limit), &target[i]);
675 // src_sync_size = ret.first - src;
676 // if (src_sync_size == (src_size - (i - traverse_limit)))
679 // else // complete sync test
681 // ret = std::mismatch(src, src + src_size, &target[i]);
682 // src_sync_size = ret.first - src;
683 // if (src_sync_size == src_size)
691 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
693 void bt_peer_connection::write_handshake()
697 TORRENT_ASSERT(!m_sent_handshake
);
699 m_sent_handshake
= true;
702 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
705 // add handshake to the send buffer
706 const char version_string
[] = "BitTorrent protocol";
707 const int string_len
= sizeof(version_string
)-1;
709 buffer::interval i
= allocate_send_buffer(1 + string_len
+ 8 + 20 + 20);
710 if (i
.begin
== 0) return; // out of memory
711 // length of version string
712 *i
.begin
= string_len
;
715 // version string itself
718 , version_string
+ string_len
720 i
.begin
+= string_len
;
723 std::fill(i
.begin
, i
.begin
+ 8, 0);
725 #ifndef TORRENT_DISABLE_DHT
726 // indicate that we support the DHT messages
727 *(i
.begin
+ 7) |= 0x01;
730 #ifndef TORRENT_DISABLE_EXTENSIONS
731 // we support extensions
732 *(i
.begin
+ 5) |= 0x10;
735 // we support FAST extension
736 *(i
.begin
+ 7) |= 0x04;
741 sha1_hash
const& ih
= t
->torrent_file().info_hash();
742 std::copy(ih
.begin(), ih
.end(), i
.begin
);
747 m_ses
.get_peer_id().begin()
748 , m_ses
.get_peer_id().end()
751 TORRENT_ASSERT(i
.begin
== i
.end
);
753 #ifdef TORRENT_VERBOSE_LOGGING
754 (*m_logger
) << time_now_string() << " ==> HANDSHAKE\n";
759 boost::optional
<piece_block_progress
> bt_peer_connection::downloading_piece_progress() const
761 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
764 buffer::const_interval recv_buffer
= receive_buffer();
765 // are we currently receiving a 'piece' message?
766 if (m_state
!= read_packet
767 || recv_buffer
.left() < 9
768 || recv_buffer
[0] != msg_piece
)
769 return boost::optional
<piece_block_progress
>();
771 const char* ptr
= recv_buffer
.begin
+ 1;
773 r
.piece
= detail::read_int32(ptr
);
774 r
.start
= detail::read_int32(ptr
);
775 r
.length
= packet_size() - 9;
777 // is any of the piece message header data invalid?
778 if (!verify_piece(r
))
779 return boost::optional
<piece_block_progress
>();
781 piece_block_progress p
;
783 p
.piece_index
= r
.piece
;
784 p
.block_index
= r
.start
/ t
->block_size();
785 p
.bytes_downloaded
= recv_buffer
.left() - 9;
786 p
.full_block_bytes
= r
.length
;
788 return boost::optional
<piece_block_progress
>(p
);
794 // -----------------------------
795 // --------- KEEPALIVE ---------
796 // -----------------------------
798 void bt_peer_connection::on_keepalive()
802 #ifdef TORRENT_VERBOSE_LOGGING
803 (*m_logger
) << time_now_string() << " <== KEEPALIVE\n";
805 incoming_keepalive();
808 // -----------------------------
809 // ----------- CHOKE -----------
810 // -----------------------------
812 void bt_peer_connection::on_choke(int received
)
816 TORRENT_ASSERT(received
> 0);
817 if (packet_size() != 1)
819 disconnect("'choke' message size != 1", 2);
822 m_statistics
.received_bytes(0, received
);
823 if (!packet_finished()) return;
826 if (is_disconnecting()) return;
827 if (!m_supports_fast
)
829 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
831 while (!download_queue().empty())
833 piece_block
const& b
= download_queue().front().block
;
835 r
.piece
= b
.piece_index
;
836 r
.start
= b
.block_index
* t
->block_size();
837 r
.length
= t
->block_size();
838 incoming_reject_request(r
);
843 // -----------------------------
844 // ---------- UNCHOKE ----------
845 // -----------------------------
847 void bt_peer_connection::on_unchoke(int received
)
851 TORRENT_ASSERT(received
> 0);
852 if (packet_size() != 1)
854 disconnect("'unchoke' message size != 1", 2);
857 m_statistics
.received_bytes(0, received
);
858 if (!packet_finished()) return;
863 // -----------------------------
864 // -------- INTERESTED ---------
865 // -----------------------------
867 void bt_peer_connection::on_interested(int received
)
871 TORRENT_ASSERT(received
> 0);
872 if (packet_size() != 1)
874 disconnect("'interested' message size != 1", 2);
877 m_statistics
.received_bytes(0, received
);
878 if (!packet_finished()) return;
880 incoming_interested();
883 // -----------------------------
884 // ------ NOT INTERESTED -------
885 // -----------------------------
887 void bt_peer_connection::on_not_interested(int received
)
891 TORRENT_ASSERT(received
> 0);
892 if (packet_size() != 1)
894 disconnect("'not interested' message size != 1", 2);
897 m_statistics
.received_bytes(0, received
);
898 if (!packet_finished()) return;
900 incoming_not_interested();
903 // -----------------------------
904 // ----------- HAVE ------------
905 // -----------------------------
907 void bt_peer_connection::on_have(int received
)
911 TORRENT_ASSERT(received
> 0);
912 if (packet_size() != 5)
914 disconnect("'have' message size != 5", 2);
917 m_statistics
.received_bytes(0, received
);
918 if (!packet_finished()) return;
920 buffer::const_interval recv_buffer
= receive_buffer();
922 const char* ptr
= recv_buffer
.begin
+ 1;
923 int index
= detail::read_int32(ptr
);
925 incoming_have(index
);
928 // -----------------------------
929 // --------- BITFIELD ----------
930 // -----------------------------
932 void bt_peer_connection::on_bitfield(int received
)
936 TORRENT_ASSERT(received
> 0);
938 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
941 // if we don't have the metedata, we cannot
942 // verify the bitfield size
943 if (t
->valid_metadata()
944 && packet_size() - 1 != (t
->torrent_file().num_pieces() + 7) / 8)
946 std::stringstream msg
;
947 msg
<< "got bitfield with invalid size: " << (packet_size() - 1)
948 << " bytes. expected: " << ((t
->torrent_file().num_pieces() + 7) / 8)
950 disconnect(msg
.str().c_str(), 2);
954 m_statistics
.received_bytes(0, received
);
955 if (!packet_finished()) return;
957 buffer::const_interval recv_buffer
= receive_buffer();
960 bits
.borrow_bytes((char*)recv_buffer
.begin
+ 1
961 , t
->valid_metadata()?get_bitfield().size():(packet_size()-1)*8);
963 incoming_bitfield(bits
);
966 // -----------------------------
967 // ---------- REQUEST ----------
968 // -----------------------------
970 void bt_peer_connection::on_request(int received
)
974 TORRENT_ASSERT(received
> 0);
975 if (packet_size() != 13)
977 disconnect("'request' message size != 13", 2);
980 m_statistics
.received_bytes(0, received
);
981 if (!packet_finished()) return;
983 buffer::const_interval recv_buffer
= receive_buffer();
986 const char* ptr
= recv_buffer
.begin
+ 1;
987 r
.piece
= detail::read_int32(ptr
);
988 r
.start
= detail::read_int32(ptr
);
989 r
.length
= detail::read_int32(ptr
);
994 // -----------------------------
995 // ----------- PIECE -----------
996 // -----------------------------
998 void bt_peer_connection::on_piece(int received
)
1002 TORRENT_ASSERT(received
> 0);
1004 buffer::const_interval recv_buffer
= receive_buffer();
1005 int recv_pos
= recv_buffer
.end
- recv_buffer
.begin
;
1009 TORRENT_ASSERT(!has_disk_receive_buffer());
1010 if (!allocate_disk_receive_buffer(packet_size() - 9))
1013 TORRENT_ASSERT(has_disk_receive_buffer());
1015 // classify the received data as protocol chatter
1016 // or data payload for the statistics
1018 // only received protocol data
1019 m_statistics
.received_bytes(0, received
);
1020 else if (recv_pos
- received
>= 9)
1021 // only received payload data
1022 m_statistics
.received_bytes(received
, 0);
1025 // received a bit of both
1026 TORRENT_ASSERT(recv_pos
- received
< 9);
1027 TORRENT_ASSERT(recv_pos
> 9);
1028 TORRENT_ASSERT(9 - (recv_pos
- received
) <= 9);
1029 m_statistics
.received_bytes(
1031 , 9 - (recv_pos
- received
));
1034 incoming_piece_fragment();
1035 if (is_disconnecting()) return;
1036 if (!packet_finished()) return;
1038 const char* ptr
= recv_buffer
.begin
+ 1;
1040 p
.piece
= detail::read_int32(ptr
);
1041 p
.start
= detail::read_int32(ptr
);
1042 p
.length
= packet_size() - 9;
1044 disk_buffer_holder
holder(m_ses
, release_disk_receive_buffer());
1045 incoming_piece(p
, holder
);
1048 // -----------------------------
1049 // ---------- CANCEL -----------
1050 // -----------------------------
1052 void bt_peer_connection::on_cancel(int received
)
1056 TORRENT_ASSERT(received
> 0);
1057 if (packet_size() != 13)
1059 disconnect("'cancel' message size != 13", 2);
1062 m_statistics
.received_bytes(0, received
);
1063 if (!packet_finished()) return;
1065 buffer::const_interval recv_buffer
= receive_buffer();
1068 const char* ptr
= recv_buffer
.begin
+ 1;
1069 r
.piece
= detail::read_int32(ptr
);
1070 r
.start
= detail::read_int32(ptr
);
1071 r
.length
= detail::read_int32(ptr
);
1076 // -----------------------------
1077 // --------- DHT PORT ----------
1078 // -----------------------------
1080 void bt_peer_connection::on_dht_port(int received
)
1084 if (!m_supports_dht_port
)
1086 disconnect("got 'dht_port' message from peer that doesn't support it", 2);
1090 TORRENT_ASSERT(received
> 0);
1091 if (packet_size() != 3)
1093 disconnect("'dht_port' message size != 3", 2);
1096 m_statistics
.received_bytes(0, received
);
1097 if (!packet_finished()) return;
1099 buffer::const_interval recv_buffer
= receive_buffer();
1101 const char* ptr
= recv_buffer
.begin
+ 1;
1102 int listen_port
= detail::read_uint16(ptr
);
1104 incoming_dht_port(listen_port
);
1107 void bt_peer_connection::on_suggest_piece(int received
)
1111 if (!m_supports_fast
)
1113 disconnect("got 'suggest_piece' without FAST excension support", 2);
1117 m_statistics
.received_bytes(0, received
);
1118 if (!packet_finished()) return;
1120 buffer::const_interval recv_buffer
= receive_buffer();
1122 const char* ptr
= recv_buffer
.begin
+ 1;
1123 int piece
= detail::read_uint32(ptr
);
1124 incoming_suggest(piece
);
1127 void bt_peer_connection::on_have_all(int received
)
1131 if (!m_supports_fast
)
1133 disconnect("got 'have_all' without FAST extension support", 2);
1136 m_statistics
.received_bytes(0, received
);
1137 incoming_have_all();
1140 void bt_peer_connection::on_have_none(int received
)
1144 if (!m_supports_fast
)
1146 disconnect("got 'have_none' without FAST extension support", 2);
1149 m_statistics
.received_bytes(0, received
);
1150 incoming_have_none();
1153 void bt_peer_connection::on_reject_request(int received
)
1157 if (!m_supports_fast
)
1159 disconnect("got 'reject_request' without FAST extension support", 2);
1163 m_statistics
.received_bytes(0, received
);
1164 if (!packet_finished()) return;
1166 buffer::const_interval recv_buffer
= receive_buffer();
1169 const char* ptr
= recv_buffer
.begin
+ 1;
1170 r
.piece
= detail::read_int32(ptr
);
1171 r
.start
= detail::read_int32(ptr
);
1172 r
.length
= detail::read_int32(ptr
);
1174 incoming_reject_request(r
);
1177 void bt_peer_connection::on_allowed_fast(int received
)
1181 if (!m_supports_fast
)
1183 disconnect("got 'allowed_fast' without FAST extension support", 2);
1187 m_statistics
.received_bytes(0, received
);
1188 if (!packet_finished()) return;
1189 buffer::const_interval recv_buffer
= receive_buffer();
1190 const char* ptr
= recv_buffer
.begin
+ 1;
1191 int index
= detail::read_int32(ptr
);
1193 incoming_allowed_fast(index
);
1196 // -----------------------------
1197 // --------- EXTENDED ----------
1198 // -----------------------------
1200 void bt_peer_connection::on_extended(int received
)
1204 TORRENT_ASSERT(received
> 0);
1205 m_statistics
.received_bytes(0, received
);
1206 if (packet_size() < 2)
1208 disconnect("'extended' message smaller than 2 bytes", 2);
1212 if (associated_torrent().expired())
1214 disconnect("'extended' message sent before proper handshake", 2);
1218 buffer::const_interval recv_buffer
= receive_buffer();
1219 if (recv_buffer
.left() < 2) return;
1221 TORRENT_ASSERT(*recv_buffer
.begin
== msg_extended
);
1222 ++recv_buffer
.begin
;
1224 int extended_id
= detail::read_uint8(recv_buffer
.begin
);
1226 if (extended_id
== 0)
1228 on_extended_handshake();
1232 #ifndef TORRENT_DISABLE_EXTENSIONS
1233 for (extension_list_t::iterator i
= m_extensions
.begin()
1234 , end(m_extensions
.end()); i
!= end
; ++i
)
1236 if ((*i
)->on_extended(packet_size() - 2, extended_id
1242 std::stringstream msg
;
1243 msg
<< "unknown extended message id: " << extended_id
;
1244 disconnect(msg
.str().c_str(), 2);
1248 void bt_peer_connection::on_extended_handshake()
1250 if (!packet_finished()) return;
1252 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
1255 buffer::const_interval recv_buffer
= receive_buffer();
1258 lazy_bdecode(recv_buffer
.begin
+ 2, recv_buffer
.end
, root
);
1259 if (root
.type() != lazy_entry::dict_t
)
1261 #ifdef TORRENT_VERBOSE_LOGGING
1262 (*m_logger
) << "invalid extended handshake\n";
1267 #ifdef TORRENT_VERBOSE_LOGGING
1268 (*m_logger
) << "<== EXTENDED HANDSHAKE: \n" << root
;
1271 #ifndef TORRENT_DISABLE_EXTENSIONS
1272 for (extension_list_t::iterator i
= m_extensions
.begin();
1273 !m_extensions
.empty() && i
!= m_extensions
.end();)
1275 // a false return value means that the extension
1276 // isn't supported by the other end. So, it is removed.
1277 if (!(*i
)->on_extension_handshake(root
))
1278 i
= m_extensions
.erase(i
);
1284 // there is supposed to be a remote listen port
1285 int listen_port
= root
.dict_find_int_value("p");
1286 if (listen_port
> 0 && peer_info_struct() != 0)
1288 t
->get_policy().update_peer_port(listen_port
1289 , peer_info_struct(), peer_info::incoming
);
1291 // there should be a version too
1292 // but where do we put that info?
1294 std::string client_info
= root
.dict_find_string_value("v");
1295 if (!client_info
.empty()) m_client_version
= client_info
;
1297 int reqq
= root
.dict_find_int_value("reqq");
1298 if (reqq
> 0) m_max_out_request_queue
= reqq
;
1300 if (root
.dict_find_int_value("upload_only"))
1301 set_upload_only(true);
1303 std::string myip
= root
.dict_find_string_value("yourip");
1306 // TODO: don't trust this blindly
1307 if (myip
.size() == address_v4::bytes_type::static_size
)
1309 address_v4::bytes_type bytes
;
1310 std::copy(myip
.begin(), myip
.end(), bytes
.begin());
1311 m_ses
.set_external_address(address_v4(bytes
));
1313 else if (myip
.size() == address_v6::bytes_type::static_size
)
1315 address_v6::bytes_type bytes
;
1316 std::copy(myip
.begin(), myip
.end(), bytes
.begin());
1317 address_v6
ipv6_address(bytes
);
1318 if (ipv6_address
.is_v4_mapped())
1319 m_ses
.set_external_address(ipv6_address
.to_v4());
1321 m_ses
.set_external_address(ipv6_address
);
1325 // if we're finished and this peer is uploading only
1327 if (t
->is_finished() && upload_only())
1328 disconnect("upload to upload connection, closing");
1331 bool bt_peer_connection::dispatch_message(int received
)
1335 TORRENT_ASSERT(received
> 0);
1337 // this means the connection has been closed already
1338 if (associated_torrent().expired()) return false;
1340 buffer::const_interval recv_buffer
= receive_buffer();
1342 TORRENT_ASSERT(recv_buffer
.left() >= 1);
1343 int packet_type
= recv_buffer
[0];
1345 || packet_type
>= num_supported_messages
1346 || m_message_handler
[packet_type
] == 0)
1348 #ifndef TORRENT_DISABLE_EXTENSIONS
1349 for (extension_list_t::iterator i
= m_extensions
.begin()
1350 , end(m_extensions
.end()); i
!= end
; ++i
)
1352 if ((*i
)->on_unknown_message(packet_size(), packet_type
1353 , buffer::const_interval(recv_buffer
.begin
+1
1354 , recv_buffer
.end
)))
1355 return packet_finished();
1359 std::stringstream msg
;
1360 msg
<< "unkown message id: " << packet_type
<< " size: " << packet_size();
1361 disconnect(msg
.str().c_str(), 2);
1362 return packet_finished();
1365 TORRENT_ASSERT(m_message_handler
[packet_type
] != 0);
1368 size_type cur_payload_dl
= m_statistics
.last_payload_downloaded();
1369 size_type cur_protocol_dl
= m_statistics
.last_protocol_downloaded();
1371 // call the correct handler for this packet type
1372 (this->*m_message_handler
[packet_type
])(received
);
1374 TORRENT_ASSERT(m_statistics
.last_payload_downloaded() - cur_payload_dl
>= 0);
1375 TORRENT_ASSERT(m_statistics
.last_protocol_downloaded() - cur_protocol_dl
>= 0);
1376 size_type stats_diff
= m_statistics
.last_payload_downloaded() - cur_payload_dl
+
1377 m_statistics
.last_protocol_downloaded() - cur_protocol_dl
;
1378 TORRENT_ASSERT(stats_diff
== received
);
1381 return packet_finished();
1384 void bt_peer_connection::write_keepalive()
1388 // Don't require the bitfield to have been sent at this point
1389 // the case where m_sent_bitfield may not be true is if the
1390 // torrent doesn't have any metadata, and a peer is timimg out.
1391 // then the keep-alive message will be sent before the bitfield
1392 // this is a violation to the original protocol, but necessary
1393 // for the metadata extension.
1394 TORRENT_ASSERT(m_sent_handshake
);
1396 char msg
[] = {0,0,0,0};
1397 send_buffer(msg
, sizeof(msg
));
1400 void bt_peer_connection::write_cancel(peer_request
const& r
)
1404 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
1405 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
1407 char msg
[17] = {0,0,0,13, msg_cancel
};
1408 char* ptr
= msg
+ 5;
1409 detail::write_int32(r
.piece
, ptr
); // index
1410 detail::write_int32(r
.start
, ptr
); // begin
1411 detail::write_int32(r
.length
, ptr
); // length
1412 send_buffer(msg
, sizeof(msg
));
1414 if (!m_supports_fast
)
1415 incoming_reject_request(r
);
1418 void bt_peer_connection::write_request(peer_request
const& r
)
1422 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
1423 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
1425 char msg
[17] = {0,0,0,13, msg_request
};
1426 char* ptr
= msg
+ 5;
1428 detail::write_int32(r
.piece
, ptr
); // index
1429 detail::write_int32(r
.start
, ptr
); // begin
1430 detail::write_int32(r
.length
, ptr
); // length
1431 send_buffer(msg
, sizeof(msg
), message_type_request
);
1434 void bt_peer_connection::write_bitfield()
1438 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
1440 TORRENT_ASSERT(m_sent_handshake
&& !m_sent_bitfield
);
1441 TORRENT_ASSERT(t
->valid_metadata());
1443 // in this case, have_all or have_none should be sent instead
1444 TORRENT_ASSERT(!m_supports_fast
|| !t
->is_seed() || t
->num_have() != 0);
1446 if (m_supports_fast
&& t
->is_seed())
1452 else if (m_supports_fast
&& t
->num_have() == 0)
1458 else if (t
->num_have() == 0)
1460 // don't send a bitfield if we don't have any pieces
1461 #ifdef TORRENT_VERBOSE_LOGGING
1462 (*m_logger
) << time_now_string() << " *** NOT SENDING BITFIELD\n";
1465 m_sent_bitfield
= true;
1470 int num_pieces
= t
->torrent_file().num_pieces();
1471 int lazy_pieces
[50];
1472 int num_lazy_pieces
= 0;
1475 if (t
->is_seed() && m_ses
.settings().lazy_bitfields
)
1477 num_lazy_pieces
= (std::min
)(50, num_pieces
/ 10);
1478 if (num_lazy_pieces
< 1) num_lazy_pieces
= 1;
1479 for (int i
= 0; i
< num_pieces
; ++i
)
1481 if (rand() % (num_pieces
- i
) >= num_lazy_pieces
- lazy_piece
) continue;
1482 lazy_pieces
[lazy_piece
++] = i
;
1484 TORRENT_ASSERT(lazy_piece
== num_lazy_pieces
);
1488 const int packet_size
= (num_pieces
+ 7) / 8 + 5;
1490 buffer::interval i
= allocate_send_buffer(packet_size
);
1491 if (i
.begin
== 0) return; // out of memory
1493 detail::write_int32(packet_size
- 4, i
.begin
);
1494 detail::write_uint8(msg_bitfield
, i
.begin
);
1498 memset(i
.begin
, 0xff, packet_size
- 5);
1502 memset(i
.begin
, 0, packet_size
- 5);
1503 piece_picker
const& p
= t
->picker();
1505 unsigned char* byte
= (unsigned char*)i
.begin
;
1506 for (int i
= 0; i
< num_pieces
; ++i
)
1508 if (p
.have_piece(i
)) *byte
|= mask
;
1517 for (int c
= 0; c
< num_lazy_pieces
; ++c
)
1518 i
.begin
[lazy_pieces
[c
] / 8] &= ~(0x80 >> (lazy_pieces
[c
] & 7));
1519 TORRENT_ASSERT(i
.end
- i
.begin
== (num_pieces
+ 7) / 8);
1521 #ifdef TORRENT_VERBOSE_LOGGING
1522 (*m_logger
) << time_now_string() << " ==> BITFIELD ";
1524 std::stringstream bitfield_string
;
1525 for (int k
= 0; k
< num_pieces
; ++k
)
1527 if (i
.begin
[k
/ 8] & (0x80 >> (k
% 8))) bitfield_string
<< "1";
1528 else bitfield_string
<< "0";
1530 bitfield_string
<< "\n";
1531 (*m_logger
) << bitfield_string
.str();
1534 m_sent_bitfield
= true;
1537 if (num_lazy_pieces
> 0)
1539 for (int i
= 0; i
< num_lazy_pieces
; ++i
)
1541 write_have(lazy_pieces
[i
]);
1542 #ifdef TORRENT_VERBOSE_LOGGING
1543 (*m_logger
) << time_now_string()
1544 << " ==> HAVE [ piece: " << lazy_pieces
[i
] << "]\n";
1549 if (m_supports_fast
)
1554 #ifndef TORRENT_DISABLE_EXTENSIONS
1555 void bt_peer_connection::write_extensions()
1559 #ifdef TORRENT_VERBOSE_LOGGING
1560 (*m_logger
) << time_now_string() << " ==> EXTENSIONS\n";
1562 TORRENT_ASSERT(m_supports_extensions
);
1563 TORRENT_ASSERT(m_sent_handshake
);
1565 entry
handshake(entry::dictionary_t
);
1566 entry
extension_list(entry::dictionary_t
);
1568 handshake
["m"] = extension_list
;
1570 // only send the port in case we bade the connection
1571 // on incoming connections the other end already knows
1573 if (is_local()) handshake
["p"] = m_ses
.listen_port();
1574 handshake
["v"] = m_ses
.settings().user_agent
;
1575 std::string remote_address
;
1576 std::back_insert_iterator
<std::string
> out(remote_address
);
1577 detail::write_address(remote().address(), out
);
1578 handshake
["yourip"] = remote_address
;
1579 handshake
["reqq"] = m_ses
.settings().max_allowed_in_request_queue
;
1580 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
1582 if (t
->is_finished()) handshake
["upload_only"] = 1;
1584 tcp::endpoint ep
= m_ses
.get_ipv6_interface();
1585 if (!is_any(ep
.address()))
1587 std::string ipv6_address
;
1588 std::back_insert_iterator
<std::string
> out(ipv6_address
);
1589 detail::write_address(ep
.address(), out
);
1590 handshake
["ipv6"] = ipv6_address
;
1593 // loop backwards, to make the first extension be the last
1594 // to fill in the handshake (i.e. give the first extensions priority)
1595 for (extension_list_t::reverse_iterator i
= m_extensions
.rbegin()
1596 , end(m_extensions
.rend()); i
!= end
; ++i
)
1598 (*i
)->add_handshake(handshake
);
1601 std::vector
<char> msg
;
1602 bencode(std::back_inserter(msg
), handshake
);
1604 // make room for message
1605 buffer::interval i
= allocate_send_buffer(6 + msg
.size());
1606 if (i
.begin
== 0) return; // out of memory
1608 // write the length of the message
1609 detail::write_int32((int)msg
.size() + 2, i
.begin
);
1610 detail::write_uint8(msg_extended
, i
.begin
);
1611 // signal handshake message
1612 detail::write_uint8(0, i
.begin
);
1614 std::copy(msg
.begin(), msg
.end(), i
.begin
);
1615 i
.begin
+= msg
.size();
1616 TORRENT_ASSERT(i
.begin
== i
.end
);
1618 #ifdef TORRENT_VERBOSE_LOGGING
1619 std::stringstream ext
;
1620 handshake
.print(ext
);
1621 (*m_logger
) << "==> EXTENDED HANDSHAKE: \n" << ext
.str();
1628 void bt_peer_connection::write_choke()
1632 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
1634 if (is_choked()) return;
1635 char msg
[] = {0,0,0,1,msg_choke
};
1636 send_buffer(msg
, sizeof(msg
));
1639 void bt_peer_connection::write_unchoke()
1643 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
1645 char msg
[] = {0,0,0,1,msg_unchoke
};
1646 send_buffer(msg
, sizeof(msg
));
1649 void bt_peer_connection::write_interested()
1653 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
1655 char msg
[] = {0,0,0,1,msg_interested
};
1656 send_buffer(msg
, sizeof(msg
));
1659 void bt_peer_connection::write_not_interested()
1663 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
1665 char msg
[] = {0,0,0,1,msg_not_interested
};
1666 send_buffer(msg
, sizeof(msg
));
1669 void bt_peer_connection::write_have(int index
)
1672 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
1673 TORRENT_ASSERT(index
>= 0);
1674 TORRENT_ASSERT(index
< associated_torrent().lock()->torrent_file().num_pieces());
1675 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
1677 char msg
[] = {0,0,0,5,msg_have
,0,0,0,0};
1678 char* ptr
= msg
+ 5;
1679 detail::write_int32(index
, ptr
);
1680 send_buffer(msg
, sizeof(msg
));
1683 void bt_peer_connection::write_piece(peer_request
const& r
, disk_buffer_holder
& buffer
)
1687 TORRENT_ASSERT(m_sent_handshake
&& m_sent_bitfield
);
1689 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
1692 char msg
[4 + 1 + 4 + 4];
1694 TORRENT_ASSERT(r
.length
<= 16 * 1024);
1695 detail::write_int32(r
.length
+ 1 + 4 + 4, ptr
);
1696 detail::write_uint8(msg_piece
, ptr
);
1697 detail::write_int32(r
.piece
, ptr
);
1698 detail::write_int32(r
.start
, ptr
);
1699 send_buffer(msg
, sizeof(msg
));
1701 append_send_buffer(buffer
.get(), r
.length
1702 , boost::bind(&session_impl::free_disk_buffer
1703 , boost::ref(m_ses
), _1
));
1706 m_payloads
.push_back(range(send_buffer_size() - r
.length
, r
.length
));
1712 struct match_peer_id
1714 match_peer_id(peer_id
const& id
, peer_connection
const* pc
)
1715 : m_id(id
), m_pc(pc
)
1716 { TORRENT_ASSERT(pc
); }
1718 bool operator()(std::pair
<const address
, policy::peer
> const& p
) const
1720 return p
.second
.connection
!= m_pc
1721 && p
.second
.connection
1722 && p
.second
.connection
->pid() == m_id
1723 && !p
.second
.connection
->pid().is_all_zeros()
1724 && p
.second
.addr
== m_pc
->remote().address();
1727 peer_id
const& m_id
;
1728 peer_connection
const* m_pc
;
1732 // --------------------------
1734 // --------------------------
1736 // throws exception when the client should be disconnected
1737 void bt_peer_connection::on_receive(error_code
const& error
1738 , std::size_t bytes_transferred
)
1744 m_statistics
.received_bytes(0, bytes_transferred
);
1748 boost::shared_ptr
<torrent
> t
= associated_torrent().lock();
1750 #ifndef TORRENT_DISABLE_ENCRYPTION
1751 TORRENT_ASSERT(in_handshake() || !m_rc4_encrypted
|| m_encrypted
);
1752 if (m_rc4_encrypted
&& m_encrypted
)
1754 std::pair
<buffer::interval
, buffer::interval
> wr_buf
= wr_recv_buffers(bytes_transferred
);
1755 m_RC4_handler
->decrypt(wr_buf
.first
.begin
, wr_buf
.first
.left());
1756 if (wr_buf
.second
.left()) m_RC4_handler
->decrypt(wr_buf
.second
.begin
, wr_buf
.second
.left());
1760 buffer::const_interval recv_buffer
= receive_buffer();
1762 #ifndef TORRENT_DISABLE_ENCRYPTION
1763 // m_state is set to read_pe_dhkey in initial state
1764 // (read_protocol_identifier) for incoming, or in constructor
1766 if (m_state
== read_pe_dhkey
)
1768 m_statistics
.received_bytes(0, bytes_transferred
);
1770 TORRENT_ASSERT(!m_encrypted
);
1771 TORRENT_ASSERT(!m_rc4_encrypted
);
1772 TORRENT_ASSERT(packet_size() == dh_key_len
);
1773 TORRENT_ASSERT(recv_buffer
== receive_buffer());
1775 if (!packet_finished()) return;
1777 // write our dh public key. m_dh_key_exchange is
1778 // initialized in write_pe1_2_dhkey()
1779 if (!is_local()) write_pe1_2_dhkey();
1780 if (is_disconnecting()) return;
1782 // read dh key, generate shared secret
1783 if (m_dh_key_exchange
->compute_secret(recv_buffer
.begin
) == -1)
1785 disconnect("out of memory");
1789 #ifdef TORRENT_VERBOSE_LOGGING
1790 (*m_logger
) << " received DH key\n";
1793 // PadA/B can be a max of 512 bytes, and 20 bytes more for
1794 // the sync hash (if incoming), or 8 bytes more for the
1795 // encrypted verification constant (if outgoing). Instead
1796 // of requesting the maximum possible, request the maximum
1797 // possible to ensure we do not overshoot the standard
1802 m_state
= read_pe_syncvc
;
1805 // initial payload is the standard handshake, this is
1806 // always rc4 if sent here. m_rc4_encrypted is flagged
1807 // again according to peer selection.
1808 m_rc4_encrypted
= true;
1811 m_rc4_encrypted
= false;
1812 m_encrypted
= false;
1814 // vc,crypto_select,len(pad),pad, encrypt(handshake)
1815 // 8+4+2+0+handshake_len
1816 reset_recv_buffer(8+4+2+0+handshake_len
);
1820 // already written dh key
1821 m_state
= read_pe_synchash
;
1822 // synchash,skeyhash,vc,crypto_provide,len(pad),pad,encrypt(handshake)
1823 reset_recv_buffer(20+20+8+4+2+0+handshake_len
);
1825 TORRENT_ASSERT(!packet_finished());
1829 // cannot fall through into
1830 if (m_state
== read_pe_synchash
)
1832 TORRENT_ASSERT(!m_encrypted
);
1833 TORRENT_ASSERT(!m_rc4_encrypted
);
1834 TORRENT_ASSERT(!is_local());
1835 TORRENT_ASSERT(recv_buffer
== receive_buffer());
1837 if (recv_buffer
.left() < 20)
1839 m_statistics
.received_bytes(0, bytes_transferred
);
1841 if (packet_finished())
1842 disconnect("sync hash not found", 2);
1846 if (!m_sync_hash
.get())
1848 TORRENT_ASSERT(m_sync_bytes_read
== 0);
1851 // compute synchash (hash('req1',S))
1852 h
.update("req1", 4);
1853 h
.update(m_dh_key_exchange
->get_secret(), dh_key_len
);
1855 m_sync_hash
.reset(new sha1_hash(h
.final()));
1858 int syncoffset
= get_syncoffset((char*)m_sync_hash
->begin(), 20
1859 , recv_buffer
.begin
, recv_buffer
.left());
1862 if (syncoffset
== -1)
1864 m_statistics
.received_bytes(0, bytes_transferred
);
1866 std::size_t bytes_processed
= recv_buffer
.left() - 20;
1867 m_sync_bytes_read
+= bytes_processed
;
1868 if (m_sync_bytes_read
>= 512)
1870 disconnect("sync hash not found within 532 bytes", 2);
1874 cut_receive_buffer(bytes_processed
, (std::min
)(packet_size()
1875 , (512+20) - m_sync_bytes_read
));
1877 TORRENT_ASSERT(!packet_finished());
1880 // found complete sync
1883 std::size_t bytes_processed
= syncoffset
+ 20;
1884 #ifdef TORRENT_VERBOSE_LOGGING
1885 (*m_logger
) << " sync point (hash) found at offset "
1886 << m_sync_bytes_read
+ bytes_processed
- 20 << "\n";
1888 m_state
= read_pe_skey_vc
;
1889 // skey,vc - 28 bytes
1890 m_sync_hash
.reset();
1891 int transferred_used
= bytes_processed
- recv_buffer
.left() + bytes_transferred
;
1892 TORRENT_ASSERT(transferred_used
<= int(bytes_transferred
));
1893 m_statistics
.received_bytes(0, transferred_used
);
1894 bytes_transferred
-= transferred_used
;
1895 cut_receive_buffer(bytes_processed
, 28);
1899 if (m_state
== read_pe_skey_vc
)
1901 m_statistics
.received_bytes(0, bytes_transferred
);
1903 TORRENT_ASSERT(!m_encrypted
);
1904 TORRENT_ASSERT(!m_rc4_encrypted
);
1905 TORRENT_ASSERT(!is_local());
1906 TORRENT_ASSERT(packet_size() == 28);
1908 if (!packet_finished()) return;
1910 recv_buffer
= receive_buffer();
1912 aux::session_impl::torrent_map::const_iterator i
;
1914 for (i
= m_ses
.m_torrents
.begin(); i
!= m_ses
.m_torrents
.end(); ++i
)
1916 torrent
const& ti
= *i
->second
;
1917 sha1_hash
const& skey_hash
= ti
.obfuscated_hash();
1918 sha1_hash obfs_hash
= m_dh_key_exchange
->get_hash_xor_mask();
1919 obfs_hash
^= skey_hash
;
1921 if (std::equal(recv_buffer
.begin
, recv_buffer
.begin
+ 20,
1922 (char*)&obfs_hash
[0]))
1926 attach_to_torrent(ti
.info_hash());
1927 if (is_disconnecting()) return;
1929 t
= associated_torrent().lock();
1933 init_pe_RC4_handler(m_dh_key_exchange
->get_secret(), ti
.info_hash());
1934 #ifdef TORRENT_VERBOSE_LOGGING
1935 (*m_logger
) << " stream key found, torrent located.\n";
1941 if (!m_RC4_handler
.get())
1943 disconnect("invalid streamkey identifier (info hash) in encrypted handshake", 2);
1948 buffer::interval wr_recv_buf
= wr_recv_buffer();
1949 m_RC4_handler
->decrypt(wr_recv_buf
.begin
+ 20, 8);
1950 wr_recv_buf
.begin
+= 28;
1952 const char sh_vc
[] = {0,0,0,0, 0,0,0,0};
1953 if (!std::equal(sh_vc
, sh_vc
+8, recv_buffer
.begin
+ 20))
1955 disconnect("unable to verify constant", 2);
1959 #ifdef TORRENT_VERBOSE_LOGGING
1960 (*m_logger
) << " verification constant found\n";
1962 m_state
= read_pe_cryptofield
;
1963 reset_recv_buffer(4 + 2);
1966 // cannot fall through into
1967 if (m_state
== read_pe_syncvc
)
1969 TORRENT_ASSERT(is_local());
1970 TORRENT_ASSERT(!m_encrypted
);
1971 TORRENT_ASSERT(!m_rc4_encrypted
);
1972 TORRENT_ASSERT(recv_buffer
== receive_buffer());
1974 if (recv_buffer
.left() < 8)
1976 m_statistics
.received_bytes(0, bytes_transferred
);
1977 if (packet_finished())
1978 disconnect("sync verification constant not found", 2);
1982 // generate the verification constant
1983 if (!m_sync_vc
.get())
1985 TORRENT_ASSERT(m_sync_bytes_read
== 0);
1987 m_sync_vc
.reset (new char[8]);
1988 std::fill(m_sync_vc
.get(), m_sync_vc
.get() + 8, 0);
1989 m_RC4_handler
->decrypt(m_sync_vc
.get(), 8);
1992 TORRENT_ASSERT(m_sync_vc
.get());
1993 int syncoffset
= get_syncoffset(m_sync_vc
.get(), 8
1994 , recv_buffer
.begin
, recv_buffer
.left());
1997 if (syncoffset
== -1)
1999 std::size_t bytes_processed
= recv_buffer
.left() - 8;
2000 m_sync_bytes_read
+= bytes_processed
;
2001 m_statistics
.received_bytes(0, bytes_transferred
);
2003 if (m_sync_bytes_read
>= 512)
2005 disconnect("sync verification constant not found within 520 bytes", 2);
2009 cut_receive_buffer(bytes_processed
, (std::min
)(packet_size()
2010 , (512+8) - m_sync_bytes_read
));
2012 TORRENT_ASSERT(!packet_finished());
2015 // found complete sync
2018 std::size_t bytes_processed
= syncoffset
+ 8;
2019 #ifdef TORRENT_VERBOSE_LOGGING
2020 (*m_logger
) << " sync point (verification constant) found at offset "
2021 << m_sync_bytes_read
+ bytes_processed
- 8 << "\n";
2023 int transferred_used
= bytes_processed
- recv_buffer
.left() + bytes_transferred
;
2024 TORRENT_ASSERT(transferred_used
<= int(bytes_transferred
));
2025 m_statistics
.received_bytes(0, transferred_used
);
2026 bytes_transferred
-= transferred_used
;
2028 cut_receive_buffer(bytes_processed
, 4 + 2);
2030 // delete verification constant
2032 m_state
= read_pe_cryptofield
;
2037 if (m_state
== read_pe_cryptofield
) // local/remote
2039 TORRENT_ASSERT(!m_encrypted
);
2040 TORRENT_ASSERT(!m_rc4_encrypted
);
2041 TORRENT_ASSERT(packet_size() == 4+2);
2042 m_statistics
.received_bytes(0, bytes_transferred
);
2043 bytes_transferred
= 0;
2045 if (!packet_finished()) return;
2047 buffer::interval wr_buf
= wr_recv_buffer();
2048 m_RC4_handler
->decrypt(wr_buf
.begin
, packet_size());
2050 recv_buffer
= receive_buffer();
2052 int crypto_field
= detail::read_int32(recv_buffer
.begin
);
2054 #ifdef TORRENT_VERBOSE_LOGGING
2056 (*m_logger
) << " crypto provide : [ ";
2058 (*m_logger
) << " crypto select : [ ";
2060 if (crypto_field
& 0x01)
2061 (*m_logger
) << "plaintext ";
2062 if (crypto_field
& 0x02)
2063 (*m_logger
) << "rc4 ";
2064 (*m_logger
) << "]\n";
2069 int crypto_select
= 0;
2070 // select a crypto method
2071 switch (m_ses
.get_pe_settings().allowed_enc_level
)
2073 case pe_settings::plaintext
:
2074 if (!(crypto_field
& 0x01))
2076 disconnect("plaintext not provided", 1);
2079 crypto_select
= 0x01;
2081 case pe_settings::rc4
:
2082 if (!(crypto_field
& 0x02))
2084 disconnect("rc4 not provided", 1);
2087 crypto_select
= 0x02;
2089 case pe_settings::both
:
2090 if (m_ses
.get_pe_settings().prefer_rc4
)
2092 if (crypto_field
& 0x02)
2093 crypto_select
= 0x02;
2094 else if (crypto_field
& 0x01)
2095 crypto_select
= 0x01;
2099 if (crypto_field
& 0x01)
2100 crypto_select
= 0x01;
2101 else if (crypto_field
& 0x02)
2102 crypto_select
= 0x02;
2106 disconnect("rc4/plaintext not provided", 1);
2112 // write the pe4 step
2113 write_pe4_sync(crypto_select
);
2117 // check if crypto select is valid
2118 pe_settings::enc_level
const& allowed_enc_level
= m_ses
.get_pe_settings().allowed_enc_level
;
2120 if (crypto_field
== 0x02)
2122 if (allowed_enc_level
== pe_settings::plaintext
)
2124 disconnect("rc4 selected by peer when not provided", 2);
2127 m_rc4_encrypted
= true;
2129 else if (crypto_field
== 0x01)
2131 if (allowed_enc_level
== pe_settings::rc4
)
2133 disconnect("plaintext selected by peer when not provided", 2);
2136 m_rc4_encrypted
= false;
2140 disconnect("unsupported crypto method selected by peer", 2);
2145 int len_pad
= detail::read_int16(recv_buffer
.begin
);
2146 if (len_pad
< 0 || len_pad
> 512)
2148 disconnect("invalid pad length", 2);
2152 m_state
= read_pe_pad
;
2154 reset_recv_buffer(len_pad
+ 2); // len(IA) at the end of pad
2160 m_state
= init_bt_handshake
;
2163 reset_recv_buffer(len_pad
);
2167 if (m_state
== read_pe_pad
)
2169 TORRENT_ASSERT(!m_encrypted
);
2170 m_statistics
.received_bytes(0, bytes_transferred
);
2171 bytes_transferred
= 0;
2172 if (!packet_finished()) return;
2174 int pad_size
= is_local() ? packet_size() : packet_size() - 2;
2176 buffer::interval wr_buf
= wr_recv_buffer();
2177 m_RC4_handler
->decrypt(wr_buf
.begin
, packet_size());
2179 recv_buffer
= receive_buffer();
2183 recv_buffer
.begin
+= pad_size
;
2184 int len_ia
= detail::read_int16(recv_buffer
.begin
);
2188 disconnect("invalid len_ia in handshake", 2);
2192 #ifdef TORRENT_VERBOSE_LOGGING
2193 (*m_logger
) << " len(IA) : " << len_ia
<< "\n";
2197 // everything after this is Encrypt2
2199 m_state
= init_bt_handshake
;
2203 m_state
= read_pe_ia
;
2204 reset_recv_buffer(len_ia
);
2209 // everything that arrives after this is Encrypt2
2211 m_state
= init_bt_handshake
;
2215 if (m_state
== read_pe_ia
)
2217 m_statistics
.received_bytes(0, bytes_transferred
);
2218 TORRENT_ASSERT(!is_local());
2219 TORRENT_ASSERT(!m_encrypted
);
2221 if (!packet_finished()) return;
2223 // ia is always rc4, so decrypt it
2224 buffer::interval wr_buf
= wr_recv_buffer();
2225 m_RC4_handler
->decrypt(wr_buf
.begin
, packet_size());
2227 #ifdef TORRENT_VERBOSE_LOGGING
2228 (*m_logger
) << " decrypted ia : " << packet_size() << " bytes\n";
2231 if (!m_rc4_encrypted
)
2233 m_RC4_handler
.reset();
2234 #ifdef TORRENT_VERBOSE_LOGGING
2235 (*m_logger
) << " destroyed rc4 keys\n";
2239 // everything that arrives after this is Encrypt2
2242 m_state
= read_protocol_identifier
;
2243 cut_receive_buffer(0, 20);
2246 if (m_state
== init_bt_handshake
)
2248 m_statistics
.received_bytes(0, bytes_transferred
);
2249 bytes_transferred
= 0;
2250 TORRENT_ASSERT(m_encrypted
);
2252 // decrypt remaining received bytes
2253 if (m_rc4_encrypted
)
2255 buffer::interval wr_buf
= wr_recv_buffer();
2256 wr_buf
.begin
+= packet_size();
2257 m_RC4_handler
->decrypt(wr_buf
.begin
, wr_buf
.left());
2258 #ifdef TORRENT_VERBOSE_LOGGING
2259 (*m_logger
) << " decrypted remaining " << wr_buf
.left() << " bytes\n";
2262 else // !m_rc4_encrypted
2264 m_RC4_handler
.reset();
2265 #ifdef TORRENT_VERBOSE_LOGGING
2266 (*m_logger
) << " destroyed rc4 keys\n";
2270 // payload stream, start with 20 handshake bytes
2271 m_state
= read_protocol_identifier
;
2272 reset_recv_buffer(20);
2274 // encrypted portion of handshake completed, toggle
2275 // peer_info pe_support flag back to true
2277 m_ses
.get_pe_settings().out_enc_policy
== pe_settings::enabled
)
2279 policy::peer
* pi
= peer_info_struct();
2282 pi
->pe_support
= true;
2286 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
2288 if (m_state
== read_protocol_identifier
)
2290 m_statistics
.received_bytes(0, bytes_transferred
);
2291 bytes_transferred
= 0;
2292 TORRENT_ASSERT(packet_size() == 20);
2294 if (!packet_finished()) return;
2295 recv_buffer
= receive_buffer();
2297 int packet_size
= recv_buffer
[0];
2298 const char protocol_string
[] = "BitTorrent protocol";
2300 if (packet_size
!= 19 ||
2301 !std::equal(recv_buffer
.begin
+ 1, recv_buffer
.begin
+ 19, protocol_string
))
2303 #ifndef TORRENT_DISABLE_ENCRYPTION
2304 if (!is_local() && m_ses
.get_pe_settings().in_enc_policy
== pe_settings::disabled
)
2306 disconnect("encrypted incoming connections disabled");
2310 // Don't attempt to perform an encrypted handshake
2311 // within an encrypted connection
2312 if (!m_encrypted
&& !is_local())
2314 #ifdef TORRENT_VERBOSE_LOGGING
2315 (*m_logger
) << " attempting encrypted connection\n";
2317 m_state
= read_pe_dhkey
;
2318 cut_receive_buffer(0, dh_key_len
);
2319 TORRENT_ASSERT(!packet_finished());
2323 TORRENT_ASSERT((!is_local() && m_encrypted
) || is_local());
2324 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
2325 disconnect("incorrect protocol identifier", 2);
2329 #ifndef TORRENT_DISABLE_ENCRYPTION
2330 TORRENT_ASSERT(m_state
!= read_pe_dhkey
);
2333 (m_ses
.get_pe_settings().in_enc_policy
== pe_settings::forced
) &&
2336 disconnect("non encrypted incoming connections disabled");
2341 #ifdef TORRENT_VERBOSE_LOGGING
2342 (*m_logger
) << " BitTorrent protocol\n";
2345 m_state
= read_info_hash
;
2346 reset_recv_buffer(28);
2350 if (m_state
== read_info_hash
)
2352 m_statistics
.received_bytes(0, bytes_transferred
);
2353 bytes_transferred
= 0;
2354 TORRENT_ASSERT(packet_size() == 28);
2356 if (!packet_finished()) return;
2357 recv_buffer
= receive_buffer();
2360 #ifdef TORRENT_VERBOSE_LOGGING
2361 for (int i
=0; i
< 8; ++i
)
2363 for (int j
=0; j
< 8; ++j
)
2365 if (recv_buffer
[i
] & (0x80 >> j
)) (*m_logger
) << "1";
2366 else (*m_logger
) << "0";
2369 (*m_logger
) << "\n";
2370 if (recv_buffer
[7] & 0x01)
2371 (*m_logger
) << "supports DHT port message\n";
2372 if (recv_buffer
[7] & 0x04)
2373 (*m_logger
) << "supports FAST extensions\n";
2374 if (recv_buffer
[5] & 0x10)
2375 (*m_logger
) << "supports extensions protocol\n";
2378 #ifndef DISABLE_EXTENSIONS
2379 std::memcpy(m_reserved_bits
, recv_buffer
.begin
, 20);
2380 if ((recv_buffer
[5] & 0x10))
2381 m_supports_extensions
= true;
2383 if (recv_buffer
[7] & 0x01)
2384 m_supports_dht_port
= true;
2386 if (recv_buffer
[7] & 0x04)
2387 m_supports_fast
= true;
2389 // ok, now we have got enough of the handshake. Is this connection
2390 // attached to a torrent?
2393 // now, we have to see if there's a torrent with the
2394 // info_hash we got from the peer
2395 sha1_hash info_hash
;
2396 std::copy(recv_buffer
.begin
+ 8, recv_buffer
.begin
+ 28
2397 , (char*)info_hash
.begin());
2399 attach_to_torrent(info_hash
);
2400 if (is_disconnecting()) return;
2405 if (!std::equal(recv_buffer
.begin
+ 8, recv_buffer
.begin
+ 28
2406 , (const char*)t
->torrent_file().info_hash().begin()))
2408 #ifdef TORRENT_VERBOSE_LOGGING
2409 (*m_logger
) << " received invalid info_hash\n";
2411 disconnect("invalid info-hash in handshake", 2);
2415 #ifdef TORRENT_VERBOSE_LOGGING
2416 (*m_logger
) << " info_hash received\n";
2420 t
= associated_torrent().lock();
2423 // if this is a local connection, we have already
2424 // sent the handshake
2425 if (!is_local()) write_handshake();
2426 // if (t->valid_metadata())
2427 // write_bitfield();
2429 if (is_disconnecting()) return;
2431 TORRENT_ASSERT(t
->get_policy().has_connection(this));
2433 m_state
= read_peer_id
;
2434 reset_recv_buffer(20);
2438 if (m_state
== read_peer_id
)
2440 m_statistics
.received_bytes(0, bytes_transferred
);
2441 bytes_transferred
= 0;
2444 TORRENT_ASSERT(!packet_finished()); // TODO
2447 TORRENT_ASSERT(packet_size() == 20);
2449 if (!packet_finished()) return;
2450 recv_buffer
= receive_buffer();
2452 #ifdef TORRENT_VERBOSE_LOGGING
2455 std::copy(recv_buffer
.begin
, recv_buffer
.begin
+ 20, (char*)tmp
.begin());
2456 std::stringstream s
;
2457 s
<< "received peer_id: " << tmp
<< " client: " << identify_client(tmp
) << "\n";
2459 for (peer_id::iterator i
= tmp
.begin(); i
!= tmp
.end(); ++i
)
2461 if (std::isprint(*i
)) s
<< *i
;
2465 (*m_logger
) << s
.str();
2469 std::copy(recv_buffer
.begin
, recv_buffer
.begin
+ 20, (char*)pid
.begin());
2472 if (t
->settings().allow_multiple_connections_per_ip
)
2474 // now, let's see if this connection should be closed
2475 policy
& p
= t
->get_policy();
2476 policy::iterator i
= std::find_if(p
.begin_peer(), p
.end_peer()
2477 , match_peer_id(pid
, this));
2478 if (i
!= p
.end_peer())
2480 TORRENT_ASSERT(i
->second
.connection
->pid() == pid
);
2481 // we found another connection with the same peer-id
2482 // which connection should be closed in order to be
2483 // sure that the other end closes the same connection?
2484 // the peer with greatest peer-id is the one allowed to
2485 // initiate connections. So, if our peer-id is greater than
2486 // the others, we should close the incoming connection,
2487 // if not, we should close the outgoing one.
2488 if (pid
< m_ses
.get_peer_id() && is_local())
2490 i
->second
.connection
->disconnect("duplicate peer-id, connection closed");
2494 disconnect("duplicate peer-id, connection closed");
2500 if (pid
== m_ses
.get_peer_id())
2502 disconnect("closing connection to ourself", 1);
2506 m_client_version
= identify_client(pid
);
2507 boost::optional
<fingerprint
> f
= client_fingerprint(pid
);
2508 if (f
&& std::equal(f
->name
, f
->name
+ 2, "BC"))
2510 // if this is a bitcomet client, lower the request queue size limit
2511 if (m_max_out_request_queue
> 50) m_max_out_request_queue
= 50;
2514 // disconnect if the peer has the same peer-id as ourself
2515 // since it most likely is ourself then
2516 if (pid
== m_ses
.get_peer_id())
2518 disconnect("closing connection to ourself", 1);
2522 #ifndef TORRENT_DISABLE_EXTENSIONS
2523 for (extension_list_t::iterator i
= m_extensions
.begin()
2524 , end(m_extensions
.end()); i
!= end
;)
2526 if (!(*i
)->on_handshake(m_reserved_bits
))
2528 i
= m_extensions
.erase(i
);
2535 if (is_disconnecting()) return;
2537 if (m_supports_extensions
) write_extensions();
2540 #ifdef TORRENT_VERBOSE_LOGGING
2541 (*m_logger
) << time_now_string() << " <== HANDSHAKE\n";
2543 // consider this a successful connection, reset the failcount
2544 if (peer_info_struct()) peer_info_struct()->failcount
= 0;
2546 #ifndef TORRENT_DISABLE_ENCRYPTION
2547 // Toggle pe_support back to false if this is a
2548 // standard successful connection
2549 if (is_local() && !m_encrypted
&&
2550 m_ses
.get_pe_settings().out_enc_policy
== pe_settings::enabled
)
2552 policy::peer
* pi
= peer_info_struct();
2555 pi
->pe_support
= false;
2559 m_state
= read_packet_size
;
2560 reset_recv_buffer(5);
2561 if (t
->ready_for_connections())
2564 #ifndef TORRENT_DISABLE_DHT
2565 if (m_supports_dht_port
&& m_ses
.m_dht
)
2566 write_dht_port(m_ses
.get_dht_settings().service_port
);
2570 TORRENT_ASSERT(!packet_finished());
2574 // cannot fall through into
2575 if (m_state
== read_packet_size
)
2577 // Make sure this is not fallen though into
2578 TORRENT_ASSERT(recv_buffer
== receive_buffer());
2579 TORRENT_ASSERT(packet_size() == 5);
2583 if (recv_buffer
.left() < 4)
2585 m_statistics
.received_bytes(0, bytes_transferred
);
2588 int transferred_used
= 4 - recv_buffer
.left() + bytes_transferred
;
2589 TORRENT_ASSERT(transferred_used
<= int(bytes_transferred
));
2590 m_statistics
.received_bytes(0, transferred_used
);
2591 bytes_transferred
-= transferred_used
;
2593 const char* ptr
= recv_buffer
.begin
;
2594 int packet_size
= detail::read_int32(ptr
);
2596 // don't accept packets larger than 1 MB
2597 if (packet_size
> 1024*1024 || packet_size
< 0)
2599 m_statistics
.received_bytes(0, bytes_transferred
);
2601 std::stringstream msg
;
2602 msg
<< "packet > 1 MB (" << (unsigned int)packet_size
<< " bytes)";
2603 disconnect(msg
.str().c_str(), 2);
2607 if (packet_size
== 0)
2609 m_statistics
.received_bytes(0, bytes_transferred
);
2610 incoming_keepalive();
2611 if (is_disconnecting()) return;
2612 // keepalive message
2613 m_state
= read_packet_size
;
2614 cut_receive_buffer(4, 5);
2619 if (recv_buffer
.left() < 5) return;
2621 m_state
= read_packet
;
2622 cut_receive_buffer(4, packet_size
);
2623 TORRENT_ASSERT(bytes_transferred
== 1);
2624 recv_buffer
= receive_buffer();
2625 TORRENT_ASSERT(recv_buffer
.left() == 1);
2629 if (m_state
== read_packet
)
2631 TORRENT_ASSERT(recv_buffer
== receive_buffer());
2633 if (dispatch_message(bytes_transferred
))
2635 m_state
= read_packet_size
;
2636 reset_recv_buffer(5);
2638 TORRENT_ASSERT(!packet_finished());
2642 TORRENT_ASSERT(!packet_finished());
2645 // --------------------------
2647 // --------------------------
2649 void bt_peer_connection::on_sent(error_code
const& error
2650 , std::size_t bytes_transferred
)
2656 m_statistics
.sent_bytes(0, bytes_transferred
);
2660 // manage the payload markers
2661 int amount_payload
= 0;
2662 if (!m_payloads
.empty())
2664 for (std::deque
<range
>::iterator i
= m_payloads
.begin();
2665 i
!= m_payloads
.end(); ++i
)
2667 i
->start
-= bytes_transferred
;
2670 if (i
->start
+ i
->length
<= 0)
2672 amount_payload
+= i
->length
;
2676 amount_payload
+= -i
->start
;
2677 i
->length
-= -i
->start
;
2684 // TODO: move the erasing into the loop above
2685 // remove all payload ranges that has been sent
2687 std::remove_if(m_payloads
.begin(), m_payloads
.end(), range_below_zero
)
2688 , m_payloads
.end());
2690 TORRENT_ASSERT(amount_payload
<= (int)bytes_transferred
);
2691 m_statistics
.sent_bytes(amount_payload
, bytes_transferred
- amount_payload
);
2695 void bt_peer_connection::check_invariant() const
2697 #ifndef TORRENT_DISABLE_ENCRYPTION
2698 TORRENT_ASSERT( (bool(m_state
!= read_pe_dhkey
) || m_dh_key_exchange
.get())
2701 TORRENT_ASSERT(!m_rc4_encrypted
|| m_RC4_handler
.get());
2703 if (is_seed()) TORRENT_ASSERT(upload_only());
2705 if (!in_handshake())
2707 TORRENT_ASSERT(m_sent_handshake
);
2710 if (!m_payloads
.empty())
2712 for (std::deque
<range
>::const_iterator i
= m_payloads
.begin();
2713 i
!= m_payloads
.end() - 1; ++i
)
2715 TORRENT_ASSERT(i
->start
+ i
->length
<= (i
+1)->start
);