AUTO_LT_SYNC
[tore.git] / libtorrent / src / bt_peer_connection.cpp
blob344a0647255417bb8d31b80c58b1cc6fe4aea580
1 /*
3 Copyright (c) 2003 - 2006, Arvid Norberg
4 Copyright (c) 2007, Arvid Norberg, Un Shyam
5 All rights reserved.
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions
9 are met:
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"
36 #include <vector>
37 #include <iostream>
38 #include <iomanip>
39 #include <limits>
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"
57 #endif
59 using boost::bind;
60 using boost::shared_ptr;
61 using libtorrent::aux::session_impl;
63 namespace libtorrent
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,
78 0, 0, 0,
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,
85 0, 0,
86 &bt_peer_connection::on_extended
90 bt_peer_connection::bt_peer_connection(
91 session_impl& ses
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
97 , peerinfo)
98 , m_state(read_protocol_identifier)
99 #ifndef TORRENT_DISABLE_EXTENSIONS
100 , m_supports_extensions(false)
101 #endif
102 , m_supports_dht_port(false)
103 , m_supports_fast(false)
104 #ifndef TORRENT_DISABLE_ENCRYPTION
105 , m_encrypted(false)
106 , m_rc4_encrypted(false)
107 , m_sync_bytes_read(0)
108 , m_enc_send_buffer(0, 0)
109 #endif
110 #ifndef NDEBUG
111 , m_sent_bitfield(false)
112 , m_in_constructor(true)
113 , m_sent_handshake(false)
114 #endif
116 #ifdef TORRENT_VERBOSE_LOGGING
117 (*m_logger) << "*** bt_peer_connection\n";
118 #endif
120 #ifndef NDEBUG
121 m_in_constructor = false;
122 #endif
125 bt_peer_connection::bt_peer_connection(
126 session_impl& ses
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)
134 #endif
135 , m_supports_dht_port(false)
136 , m_supports_fast(false)
137 #ifndef TORRENT_DISABLE_ENCRYPTION
138 , m_encrypted(false)
139 , m_rc4_encrypted(false)
140 , m_sync_bytes_read(0)
141 , m_enc_send_buffer(0, 0)
142 #endif
143 #ifndef NDEBUG
144 , m_sent_bitfield(false)
145 , m_in_constructor(true)
146 , m_sent_handshake(false)
147 #endif
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);
162 #else
163 m_bandwidth_limit[download_channel].assign(80);
164 m_bandwidth_limit[upload_channel].assign(80);
165 #endif
167 #ifndef NDEBUG
168 m_in_constructor = false;
169 #endif
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);
179 setup_receive();
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)
194 write_pe1_2_dhkey();
195 if (is_disconnecting()) return;
197 m_state = read_pe_dhkey;
198 reset_recv_buffer(dh_key_len);
199 setup_receive();
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
214 // fast.
215 fast_reconnect(true);
217 write_pe1_2_dhkey();
218 if (is_disconnecting()) return;
219 m_state = read_pe_dhkey;
220 reset_recv_buffer(dh_key_len);
221 setup_receive();
223 else // pi->pe_support == false
225 // toggled back to false if standard handshake
226 // completes correctly (without encryption)
227 pi->pe_support = true;
229 write_handshake();
230 reset_recv_buffer(20);
231 setup_receive();
234 else if (out_enc_policy == pe_settings::disabled)
235 #endif
237 write_handshake();
239 // start in the state where we are trying to read the
240 // handshake from the other side
241 reset_recv_buffer(20);
242 setup_receive();
246 void bt_peer_connection::on_metadata()
248 // connections that are still in the handshake
249 // will send their bitfield when the handshake
250 // is done
251 if (m_state < read_packet_size) return;
252 boost::shared_ptr<torrent> t = associated_torrent().lock();
253 TORRENT_ASSERT(t);
254 write_bitfield();
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);
258 #endif
261 void bt_peer_connection::write_dht_port(int listen_port)
263 INVARIANT_CHECK;
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";
270 #endif
271 char msg[] = {0,0,0,3, msg_dht_port, 0, 0};
272 char* ptr = msg + 5;
273 detail::write_uint16(listen_port, ptr);
274 send_buffer(msg, sizeof(msg));
277 void bt_peer_connection::write_have_all()
279 INVARIANT_CHECK;
280 TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
281 #ifndef NDEBUG
282 m_sent_bitfield = true;
283 #endif
284 #ifdef TORRENT_VERBOSE_LOGGING
285 (*m_logger) << time_now_string()
286 << " ==> HAVE_ALL\n";
287 #endif
288 char msg[] = {0,0,0,1, msg_have_all};
289 send_buffer(msg, sizeof(msg));
292 void bt_peer_connection::write_have_none()
294 INVARIANT_CHECK;
295 TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
296 #ifndef NDEBUG
297 m_sent_bitfield = true;
298 #endif
299 #ifdef TORRENT_VERBOSE_LOGGING
300 (*m_logger) << time_now_string()
301 << " ==> HAVE_NONE\n";
302 #endif
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)
309 INVARIANT_CHECK;
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};
317 char* ptr = msg + 5;
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)
326 INVARIANT_CHECK;
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};
333 char* ptr = msg + 5;
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
350 if (m_encrypted)
352 m_rc4_encrypted ?
353 p.flags |= peer_info::rc4_encrypted :
354 p.flags |= peer_info::plaintext_encrypted;
356 #endif
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()
377 INVARIANT_CHECK;
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
385 if (is_local())
386 (*m_logger) << " initiating encrypted handshake\n";
387 #endif
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");
393 return;
396 int pad_size = std::rand() % 512;
398 #ifdef TORRENT_VERBOSE_LOGGING
399 (*m_logger) << " pad size: " << pad_size << "\n";
400 #endif
402 buffer::interval send_buf = allocate_send_buffer(dh_key_len + pad_size);
403 if (send_buf.begin == 0)
405 disconnect("out of memory");
406 return;
409 std::copy(m_dh_key_exchange->get_local_key(),
410 m_dh_key_exchange->get_local_key() + dh_key_len,
411 send_buf.begin);
413 std::generate(send_buf.begin + dh_key_len, send_buf.end, std::rand);
414 setup_send();
416 #ifdef TORRENT_VERBOSE_LOGGING
417 (*m_logger) << " sent DH key\n";
418 #endif
421 void bt_peer_connection::write_pe3_sync()
423 INVARIANT_CHECK;
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();
431 TORRENT_ASSERT(t);
433 hasher h;
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))
445 h.reset();
446 h.update("req1",4);
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) ]
454 h.reset();
455 h.update("req2",4);
456 h.update((const char*)info_hash.begin(), 20);
457 sha1_hash streamkey_hash = h.final();
459 h.reset();
460 h.update("req3",4);
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";
494 #endif
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);
500 setup_send();
503 void bt_peer_connection::write_pe4_sync(int crypto_select)
505 INVARIANT_CHECK;
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);
521 setup_send();
523 // encryption method has been negotiated
524 if (crypto_select == 0x02)
525 m_rc4_encrypted = true;
526 else // 0x01
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";
533 else
534 (*m_logger) << "rc4 ]\n";
535 #endif
538 void bt_peer_connection::write_pe_vc_cryptofield(buffer::interval& write_buf
539 , int crypto_field, int pad_size)
541 INVARIANT_CHECK;
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
552 // vc
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
564 if (is_local())
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)
572 INVARIANT_CHECK;
574 TORRENT_ASSERT(secret);
576 hasher h;
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();
589 h.reset();
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";
605 #endif
608 void bt_peer_connection::send_buffer(char* buf, int size, int flags)
610 TORRENT_ASSERT(buf);
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;
627 else
629 buffer::interval i = peer_connection::allocate_send_buffer(size);
630 return i;
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);
652 TORRENT_ASSERT(src);
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))
662 return i;
665 // // Partial sync
666 // for (int i = 0; i < target_size; ++i)
667 // {
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
673 // {
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)))
677 // return i;
678 // }
679 // else // complete sync test
680 // {
681 // ret = std::mismatch(src, src + src_size, &target[i]);
682 // src_sync_size = ret.first - src;
683 // if (src_sync_size == src_size)
684 // return i;
685 // }
686 // }
688 // no complete sync
689 return -1;
691 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
693 void bt_peer_connection::write_handshake()
695 INVARIANT_CHECK;
697 TORRENT_ASSERT(!m_sent_handshake);
698 #ifndef NDEBUG
699 m_sent_handshake = true;
700 #endif
702 boost::shared_ptr<torrent> t = associated_torrent().lock();
703 TORRENT_ASSERT(t);
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;
713 ++i.begin;
715 // version string itself
716 std::copy(
717 version_string
718 , version_string + string_len
719 , i.begin);
720 i.begin += string_len;
722 // 8 zeroes
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;
728 #endif
730 #ifndef TORRENT_DISABLE_EXTENSIONS
731 // we support extensions
732 *(i.begin + 5) |= 0x10;
733 #endif
735 // we support FAST extension
736 *(i.begin + 7) |= 0x04;
738 i.begin += 8;
740 // info hash
741 sha1_hash const& ih = t->torrent_file().info_hash();
742 std::copy(ih.begin(), ih.end(), i.begin);
743 i.begin += 20;
745 // peer id
746 std::copy(
747 m_ses.get_peer_id().begin()
748 , m_ses.get_peer_id().end()
749 , i.begin);
750 i.begin += 20;
751 TORRENT_ASSERT(i.begin == i.end);
753 #ifdef TORRENT_VERBOSE_LOGGING
754 (*m_logger) << time_now_string() << " ==> HANDSHAKE\n";
755 #endif
756 setup_send();
759 boost::optional<piece_block_progress> bt_peer_connection::downloading_piece_progress() const
761 boost::shared_ptr<torrent> t = associated_torrent().lock();
762 TORRENT_ASSERT(t);
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;
772 peer_request r;
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);
792 // message handlers
794 // -----------------------------
795 // --------- KEEPALIVE ---------
796 // -----------------------------
798 void bt_peer_connection::on_keepalive()
800 INVARIANT_CHECK;
802 #ifdef TORRENT_VERBOSE_LOGGING
803 (*m_logger) << time_now_string() << " <== KEEPALIVE\n";
804 #endif
805 incoming_keepalive();
808 // -----------------------------
809 // ----------- CHOKE -----------
810 // -----------------------------
812 void bt_peer_connection::on_choke(int received)
814 INVARIANT_CHECK;
816 TORRENT_ASSERT(received > 0);
817 if (packet_size() != 1)
819 disconnect("'choke' message size != 1", 2);
820 return;
822 m_statistics.received_bytes(0, received);
823 if (!packet_finished()) return;
825 incoming_choke();
826 if (is_disconnecting()) return;
827 if (!m_supports_fast)
829 boost::shared_ptr<torrent> t = associated_torrent().lock();
830 TORRENT_ASSERT(t);
831 while (!download_queue().empty())
833 piece_block const& b = download_queue().front().block;
834 peer_request r;
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)
849 INVARIANT_CHECK;
851 TORRENT_ASSERT(received > 0);
852 if (packet_size() != 1)
854 disconnect("'unchoke' message size != 1", 2);
855 return;
857 m_statistics.received_bytes(0, received);
858 if (!packet_finished()) return;
860 incoming_unchoke();
863 // -----------------------------
864 // -------- INTERESTED ---------
865 // -----------------------------
867 void bt_peer_connection::on_interested(int received)
869 INVARIANT_CHECK;
871 TORRENT_ASSERT(received > 0);
872 if (packet_size() != 1)
874 disconnect("'interested' message size != 1", 2);
875 return;
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)
889 INVARIANT_CHECK;
891 TORRENT_ASSERT(received > 0);
892 if (packet_size() != 1)
894 disconnect("'not interested' message size != 1", 2);
895 return;
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)
909 INVARIANT_CHECK;
911 TORRENT_ASSERT(received > 0);
912 if (packet_size() != 5)
914 disconnect("'have' message size != 5", 2);
915 return;
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)
934 INVARIANT_CHECK;
936 TORRENT_ASSERT(received > 0);
938 boost::shared_ptr<torrent> t = associated_torrent().lock();
939 TORRENT_ASSERT(t);
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)
949 << " bytes";
950 disconnect(msg.str().c_str(), 2);
951 return;
954 m_statistics.received_bytes(0, received);
955 if (!packet_finished()) return;
957 buffer::const_interval recv_buffer = receive_buffer();
959 bitfield bits;
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)
972 INVARIANT_CHECK;
974 TORRENT_ASSERT(received > 0);
975 if (packet_size() != 13)
977 disconnect("'request' message size != 13", 2);
978 return;
980 m_statistics.received_bytes(0, received);
981 if (!packet_finished()) return;
983 buffer::const_interval recv_buffer = receive_buffer();
985 peer_request r;
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);
991 incoming_request(r);
994 // -----------------------------
995 // ----------- PIECE -----------
996 // -----------------------------
998 void bt_peer_connection::on_piece(int received)
1000 INVARIANT_CHECK;
1002 TORRENT_ASSERT(received > 0);
1004 buffer::const_interval recv_buffer = receive_buffer();
1005 int recv_pos = recv_buffer.end - recv_buffer.begin;
1007 if (recv_pos == 1)
1009 TORRENT_ASSERT(!has_disk_receive_buffer());
1010 if (!allocate_disk_receive_buffer(packet_size() - 9))
1011 return;
1013 TORRENT_ASSERT(has_disk_receive_buffer());
1015 // classify the received data as protocol chatter
1016 // or data payload for the statistics
1017 if (recv_pos <= 9)
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);
1023 else
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(
1030 recv_pos - 9
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;
1039 peer_request p;
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)
1054 INVARIANT_CHECK;
1056 TORRENT_ASSERT(received > 0);
1057 if (packet_size() != 13)
1059 disconnect("'cancel' message size != 13", 2);
1060 return;
1062 m_statistics.received_bytes(0, received);
1063 if (!packet_finished()) return;
1065 buffer::const_interval recv_buffer = receive_buffer();
1067 peer_request r;
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);
1073 incoming_cancel(r);
1076 // -----------------------------
1077 // --------- DHT PORT ----------
1078 // -----------------------------
1080 void bt_peer_connection::on_dht_port(int received)
1082 INVARIANT_CHECK;
1084 if (!m_supports_dht_port)
1086 disconnect("got 'dht_port' message from peer that doesn't support it", 2);
1087 return;
1090 TORRENT_ASSERT(received > 0);
1091 if (packet_size() != 3)
1093 disconnect("'dht_port' message size != 3", 2);
1094 return;
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)
1109 INVARIANT_CHECK;
1111 if (!m_supports_fast)
1113 disconnect("got 'suggest_piece' without FAST excension support", 2);
1114 return;
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)
1129 INVARIANT_CHECK;
1131 if (!m_supports_fast)
1133 disconnect("got 'have_all' without FAST extension support", 2);
1134 return;
1136 m_statistics.received_bytes(0, received);
1137 incoming_have_all();
1140 void bt_peer_connection::on_have_none(int received)
1142 INVARIANT_CHECK;
1144 if (!m_supports_fast)
1146 disconnect("got 'have_none' without FAST extension support", 2);
1147 return;
1149 m_statistics.received_bytes(0, received);
1150 incoming_have_none();
1153 void bt_peer_connection::on_reject_request(int received)
1155 INVARIANT_CHECK;
1157 if (!m_supports_fast)
1159 disconnect("got 'reject_request' without FAST extension support", 2);
1160 return;
1163 m_statistics.received_bytes(0, received);
1164 if (!packet_finished()) return;
1166 buffer::const_interval recv_buffer = receive_buffer();
1168 peer_request r;
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)
1179 INVARIANT_CHECK;
1181 if (!m_supports_fast)
1183 disconnect("got 'allowed_fast' without FAST extension support", 2);
1184 return;
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)
1202 INVARIANT_CHECK;
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);
1209 return;
1212 if (associated_torrent().expired())
1214 disconnect("'extended' message sent before proper handshake", 2);
1215 return;
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();
1229 return;
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
1237 , recv_buffer))
1238 return;
1240 #endif
1242 std::stringstream msg;
1243 msg << "unknown extended message id: " << extended_id;
1244 disconnect(msg.str().c_str(), 2);
1245 return;
1248 void bt_peer_connection::on_extended_handshake()
1250 if (!packet_finished()) return;
1252 boost::shared_ptr<torrent> t = associated_torrent().lock();
1253 TORRENT_ASSERT(t);
1255 buffer::const_interval recv_buffer = receive_buffer();
1257 lazy_entry root;
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";
1263 #endif
1264 return;
1267 #ifdef TORRENT_VERBOSE_LOGGING
1268 (*m_logger) << "<== EXTENDED HANDSHAKE: \n" << root;
1269 #endif
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);
1279 else
1280 ++i;
1282 #endif
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");
1304 if (!myip.empty())
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());
1320 else
1321 m_ses.set_external_address(ipv6_address);
1325 // if we're finished and this peer is uploading only
1326 // disconnect it
1327 if (t->is_finished() && upload_only())
1328 disconnect("upload to upload connection, closing");
1331 bool bt_peer_connection::dispatch_message(int received)
1333 INVARIANT_CHECK;
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];
1344 if (packet_type < 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();
1357 #endif
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);
1367 #ifndef NDEBUG
1368 size_type cur_payload_dl = m_statistics.last_payload_downloaded();
1369 size_type cur_protocol_dl = m_statistics.last_protocol_downloaded();
1370 #endif
1371 // call the correct handler for this packet type
1372 (this->*m_message_handler[packet_type])(received);
1373 #ifndef NDEBUG
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);
1379 #endif
1381 return packet_finished();
1384 void bt_peer_connection::write_keepalive()
1386 INVARIANT_CHECK;
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)
1402 INVARIANT_CHECK;
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)
1420 INVARIANT_CHECK;
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()
1436 INVARIANT_CHECK;
1438 boost::shared_ptr<torrent> t = associated_torrent().lock();
1439 TORRENT_ASSERT(t);
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())
1448 write_have_all();
1449 send_allowed_set();
1450 return;
1452 else if (m_supports_fast && t->num_have() == 0)
1454 write_have_none();
1455 send_allowed_set();
1456 return;
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";
1463 #endif
1464 #ifndef NDEBUG
1465 m_sent_bitfield = true;
1466 #endif
1467 return;
1470 int num_pieces = t->torrent_file().num_pieces();
1471 int lazy_pieces[50];
1472 int num_lazy_pieces = 0;
1473 int lazy_piece = 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);
1485 lazy_piece = 0;
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);
1496 if (t->is_seed())
1498 memset(i.begin, 0xff, packet_size - 5);
1500 else
1502 memset(i.begin, 0, packet_size - 5);
1503 piece_picker const& p = t->picker();
1504 int mask = 0x80;
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;
1509 mask >>= 1;
1510 if (mask == 0)
1512 mask = 0x80;
1513 ++byte;
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();
1532 #endif
1533 #ifndef NDEBUG
1534 m_sent_bitfield = true;
1535 #endif
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";
1545 #endif
1549 if (m_supports_fast)
1550 send_allowed_set();
1551 setup_send();
1554 #ifndef TORRENT_DISABLE_EXTENSIONS
1555 void bt_peer_connection::write_extensions()
1557 INVARIANT_CHECK;
1559 #ifdef TORRENT_VERBOSE_LOGGING
1560 (*m_logger) << time_now_string() << " ==> EXTENSIONS\n";
1561 #endif
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
1572 // our listen port
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();
1581 TORRENT_ASSERT(t);
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();
1622 #endif
1624 setup_send();
1626 #endif
1628 void bt_peer_connection::write_choke()
1630 INVARIANT_CHECK;
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()
1641 INVARIANT_CHECK;
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()
1651 INVARIANT_CHECK;
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()
1661 INVARIANT_CHECK;
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)
1671 INVARIANT_CHECK;
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)
1685 INVARIANT_CHECK;
1687 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1689 boost::shared_ptr<torrent> t = associated_torrent().lock();
1690 TORRENT_ASSERT(t);
1692 char msg[4 + 1 + 4 + 4];
1693 char* ptr = msg;
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));
1704 buffer.release();
1706 m_payloads.push_back(range(send_buffer_size() - r.length, r.length));
1707 setup_send();
1710 namespace
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 // --------------------------
1733 // RECEIVE DATA
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)
1740 INVARIANT_CHECK;
1742 if (error)
1744 m_statistics.received_bytes(0, bytes_transferred);
1745 return;
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());
1758 #endif
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
1765 // for outgoing
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");
1786 return;
1789 #ifdef TORRENT_VERBOSE_LOGGING
1790 (*m_logger) << " received DH key\n";
1791 #endif
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
1798 // handshake.
1800 if (is_local())
1802 m_state = read_pe_syncvc;
1803 write_pe3_sync();
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;
1809 m_encrypted = true;
1810 write_handshake();
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);
1818 else
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());
1826 return;
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);
1843 return;
1846 if (!m_sync_hash.get())
1848 TORRENT_ASSERT(m_sync_bytes_read == 0);
1849 hasher h;
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());
1861 // No sync
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);
1871 return;
1874 cut_receive_buffer(bytes_processed, (std::min)(packet_size()
1875 , (512+20) - m_sync_bytes_read));
1877 TORRENT_ASSERT(!packet_finished());
1878 return;
1880 // found complete sync
1881 else
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";
1887 #endif
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]))
1924 if (!t)
1926 attach_to_torrent(ti.info_hash());
1927 if (is_disconnecting()) return;
1929 t = associated_torrent().lock();
1930 TORRENT_ASSERT(t);
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";
1936 #endif
1937 break;
1941 if (!m_RC4_handler.get())
1943 disconnect("invalid streamkey identifier (info hash) in encrypted handshake", 2);
1944 return;
1947 // verify constant
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);
1956 return;
1959 #ifdef TORRENT_VERBOSE_LOGGING
1960 (*m_logger) << " verification constant found\n";
1961 #endif
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);
1979 return;
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());
1996 // No sync
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);
2006 return;
2009 cut_receive_buffer(bytes_processed, (std::min)(packet_size()
2010 , (512+8) - m_sync_bytes_read));
2012 TORRENT_ASSERT(!packet_finished());
2013 return;
2015 // found complete sync
2016 else
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";
2022 #endif
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
2031 m_sync_vc.reset();
2032 m_state = read_pe_cryptofield;
2033 // fall through
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
2055 if (!is_local())
2056 (*m_logger) << " crypto provide : [ ";
2057 else
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";
2065 #endif
2067 if (!is_local())
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);
2077 return;
2079 crypto_select = 0x01;
2080 break;
2081 case pe_settings::rc4:
2082 if (!(crypto_field & 0x02))
2084 disconnect("rc4 not provided", 1);
2085 return;
2087 crypto_select = 0x02;
2088 break;
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;
2097 else
2099 if (crypto_field & 0x01)
2100 crypto_select = 0x01;
2101 else if (crypto_field & 0x02)
2102 crypto_select = 0x02;
2104 if (!crypto_select)
2106 disconnect("rc4/plaintext not provided", 1);
2107 return;
2109 break;
2110 } // switch
2112 // write the pe4 step
2113 write_pe4_sync(crypto_select);
2115 else // is_local()
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);
2125 return;
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);
2134 return;
2136 m_rc4_encrypted = false;
2138 else
2140 disconnect("unsupported crypto method selected by peer", 2);
2141 return;
2145 int len_pad = detail::read_int16(recv_buffer.begin);
2146 if (len_pad < 0 || len_pad > 512)
2148 disconnect("invalid pad length", 2);
2149 return;
2152 m_state = read_pe_pad;
2153 if (!is_local())
2154 reset_recv_buffer(len_pad + 2); // len(IA) at the end of pad
2155 else
2157 if (len_pad == 0)
2159 m_encrypted = true;
2160 m_state = init_bt_handshake;
2162 else
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();
2181 if (!is_local())
2183 recv_buffer.begin += pad_size;
2184 int len_ia = detail::read_int16(recv_buffer.begin);
2186 if (len_ia < 0)
2188 disconnect("invalid len_ia in handshake", 2);
2189 return;
2192 #ifdef TORRENT_VERBOSE_LOGGING
2193 (*m_logger) << " len(IA) : " << len_ia << "\n";
2194 #endif
2195 if (len_ia == 0)
2197 // everything after this is Encrypt2
2198 m_encrypted = true;
2199 m_state = init_bt_handshake;
2201 else
2203 m_state = read_pe_ia;
2204 reset_recv_buffer(len_ia);
2207 else // is_local()
2209 // everything that arrives after this is Encrypt2
2210 m_encrypted = true;
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";
2229 #endif
2231 if (!m_rc4_encrypted)
2233 m_RC4_handler.reset();
2234 #ifdef TORRENT_VERBOSE_LOGGING
2235 (*m_logger) << " destroyed rc4 keys\n";
2236 #endif
2239 // everything that arrives after this is Encrypt2
2240 m_encrypted = true;
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";
2260 #endif
2262 else // !m_rc4_encrypted
2264 m_RC4_handler.reset();
2265 #ifdef TORRENT_VERBOSE_LOGGING
2266 (*m_logger) << " destroyed rc4 keys\n";
2267 #endif
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
2276 if (is_local() &&
2277 m_ses.get_pe_settings().out_enc_policy == pe_settings::enabled)
2279 policy::peer* pi = peer_info_struct();
2280 TORRENT_ASSERT(pi);
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");
2307 return;
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";
2316 #endif
2317 m_state = read_pe_dhkey;
2318 cut_receive_buffer(0, dh_key_len);
2319 TORRENT_ASSERT(!packet_finished());
2320 return;
2323 TORRENT_ASSERT((!is_local() && m_encrypted) || is_local());
2324 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
2325 disconnect("incorrect protocol identifier", 2);
2326 return;
2329 #ifndef TORRENT_DISABLE_ENCRYPTION
2330 TORRENT_ASSERT(m_state != read_pe_dhkey);
2332 if (!is_local() &&
2333 (m_ses.get_pe_settings().in_enc_policy == pe_settings::forced) &&
2334 !m_encrypted)
2336 disconnect("non encrypted incoming connections disabled");
2337 return;
2339 #endif
2341 #ifdef TORRENT_VERBOSE_LOGGING
2342 (*m_logger) << " BitTorrent protocol\n";
2343 #endif
2345 m_state = read_info_hash;
2346 reset_recv_buffer(28);
2349 // fall through
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";
2376 #endif
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;
2382 #endif
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?
2391 if (!t)
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;
2402 else
2404 // verify info hash
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";
2410 #endif
2411 disconnect("invalid info-hash in handshake", 2);
2412 return;
2415 #ifdef TORRENT_VERBOSE_LOGGING
2416 (*m_logger) << " info_hash received\n";
2417 #endif
2420 t = associated_torrent().lock();
2421 TORRENT_ASSERT(t);
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);
2437 // fall through
2438 if (m_state == read_peer_id)
2440 m_statistics.received_bytes(0, bytes_transferred);
2441 bytes_transferred = 0;
2442 if (!t)
2444 TORRENT_ASSERT(!packet_finished()); // TODO
2445 return;
2447 TORRENT_ASSERT(packet_size() == 20);
2449 if (!packet_finished()) return;
2450 recv_buffer = receive_buffer();
2452 #ifdef TORRENT_VERBOSE_LOGGING
2454 peer_id tmp;
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";
2458 s << "as ascii: ";
2459 for (peer_id::iterator i = tmp.begin(); i != tmp.end(); ++i)
2461 if (std::isprint(*i)) s << *i;
2462 else s << ".";
2464 s << "\n";
2465 (*m_logger) << s.str();
2467 #endif
2468 peer_id pid;
2469 std::copy(recv_buffer.begin, recv_buffer.begin + 20, (char*)pid.begin());
2470 set_pid(pid);
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");
2492 else
2494 disconnect("duplicate peer-id, connection closed");
2495 return;
2500 if (pid == m_ses.get_peer_id())
2502 disconnect("closing connection to ourself", 1);
2503 return;
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);
2519 return;
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);
2530 else
2532 ++i;
2535 if (is_disconnecting()) return;
2537 if (m_supports_extensions) write_extensions();
2538 #endif
2540 #ifdef TORRENT_VERBOSE_LOGGING
2541 (*m_logger) << time_now_string() << " <== HANDSHAKE\n";
2542 #endif
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();
2553 TORRENT_ASSERT(pi);
2555 pi->pe_support = false;
2557 #endif
2559 m_state = read_packet_size;
2560 reset_recv_buffer(5);
2561 if (t->ready_for_connections())
2563 write_bitfield();
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);
2567 #endif
2570 TORRENT_ASSERT(!packet_finished());
2571 return;
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);
2581 if (!t) return;
2583 if (recv_buffer.left() < 4)
2585 m_statistics.received_bytes(0, bytes_transferred);
2586 return;
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);
2600 // packet too large
2601 std::stringstream msg;
2602 msg << "packet > 1 MB (" << (unsigned int)packet_size << " bytes)";
2603 disconnect(msg.str().c_str(), 2);
2604 return;
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);
2615 return;
2617 else
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());
2632 if (!t) return;
2633 if (dispatch_message(bytes_transferred))
2635 m_state = read_packet_size;
2636 reset_recv_buffer(5);
2638 TORRENT_ASSERT(!packet_finished());
2639 return;
2642 TORRENT_ASSERT(!packet_finished());
2645 // --------------------------
2646 // SEND DATA
2647 // --------------------------
2649 void bt_peer_connection::on_sent(error_code const& error
2650 , std::size_t bytes_transferred)
2652 INVARIANT_CHECK;
2654 if (error)
2656 m_statistics.sent_bytes(0, bytes_transferred);
2657 return;
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;
2668 if (i->start < 0)
2670 if (i->start + i->length <= 0)
2672 amount_payload += i->length;
2674 else
2676 amount_payload += -i->start;
2677 i->length -= -i->start;
2678 i->start = 0;
2684 // TODO: move the erasing into the loop above
2685 // remove all payload ranges that has been sent
2686 m_payloads.erase(
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);
2694 #ifndef NDEBUG
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())
2699 || !is_local());
2701 TORRENT_ASSERT(!m_rc4_encrypted || m_RC4_handler.get());
2702 #endif
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);
2719 #endif