fixes bug where priorities where lost when force-rechecking.
[libtorrent.git] / src / bt_peer_connection.cpp
blob7e9fd43ce1ce3beecbcec0434bee0ab9fda2497b
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 boost::shared_ptr<torrent> t = associated_torrent().lock();
249 TORRENT_ASSERT(t);
250 write_bitfield();
251 #ifndef TORRENT_DISABLE_DHT
252 if (m_supports_dht_port && m_ses.m_dht)
253 write_dht_port(m_ses.get_dht_settings().service_port);
254 #endif
255 if (is_interesting()) write_interested();
258 void bt_peer_connection::write_dht_port(int listen_port)
260 INVARIANT_CHECK;
262 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
264 #ifdef TORRENT_VERBOSE_LOGGING
265 (*m_logger) << time_now_string()
266 << " ==> DHT_PORT [ " << listen_port << " ]\n";
267 #endif
268 char msg[] = {0,0,0,3, msg_dht_port, 0, 0};
269 char* ptr = msg + 5;
270 detail::write_uint16(listen_port, ptr);
271 send_buffer(msg, sizeof(msg));
274 void bt_peer_connection::write_have_all()
276 INVARIANT_CHECK;
277 TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
278 #ifndef NDEBUG
279 m_sent_bitfield = true;
280 #endif
281 #ifdef TORRENT_VERBOSE_LOGGING
282 (*m_logger) << time_now_string()
283 << " ==> HAVE_ALL\n";
284 #endif
285 char msg[] = {0,0,0,1, msg_have_all};
286 send_buffer(msg, sizeof(msg));
289 void bt_peer_connection::write_have_none()
291 INVARIANT_CHECK;
292 TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
293 #ifndef NDEBUG
294 m_sent_bitfield = true;
295 #endif
296 #ifdef TORRENT_VERBOSE_LOGGING
297 (*m_logger) << time_now_string()
298 << " ==> HAVE_NONE\n";
299 #endif
300 char msg[] = {0,0,0,1, msg_have_none};
301 send_buffer(msg, sizeof(msg));
304 void bt_peer_connection::write_reject_request(peer_request const& r)
306 INVARIANT_CHECK;
308 if (!m_supports_fast) return;
310 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
311 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
313 char msg[] = {0,0,0,13, msg_reject_request,0,0,0,0, 0,0,0,0, 0,0,0,0};
314 char* ptr = msg + 5;
315 detail::write_int32(r.piece, ptr); // index
316 detail::write_int32(r.start, ptr); // begin
317 detail::write_int32(r.length, ptr); // length
318 send_buffer(msg, sizeof(msg));
321 void bt_peer_connection::write_allow_fast(int piece)
323 INVARIANT_CHECK;
325 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
326 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
327 TORRENT_ASSERT(m_supports_fast);
329 char msg[] = {0,0,0,5, msg_allowed_fast, 0, 0, 0, 0};
330 char* ptr = msg + 5;
331 detail::write_int32(piece, ptr);
332 send_buffer(msg, sizeof(msg));
335 void bt_peer_connection::get_specific_peer_info(peer_info& p) const
337 TORRENT_ASSERT(!associated_torrent().expired());
339 if (is_interesting()) p.flags |= peer_info::interesting;
340 if (is_choked()) p.flags |= peer_info::choked;
341 if (is_peer_interested()) p.flags |= peer_info::remote_interested;
342 if (has_peer_choked()) p.flags |= peer_info::remote_choked;
343 if (support_extensions()) p.flags |= peer_info::supports_extensions;
344 if (is_local()) p.flags |= peer_info::local_connection;
346 #ifndef TORRENT_DISABLE_ENCRYPTION
347 if (m_encrypted)
349 m_rc4_encrypted ?
350 p.flags |= peer_info::rc4_encrypted :
351 p.flags |= peer_info::plaintext_encrypted;
353 #endif
355 if (!is_connecting() && in_handshake())
356 p.flags |= peer_info::handshake;
357 if (is_connecting() && !is_queued()) p.flags |= peer_info::connecting;
358 if (is_queued()) p.flags |= peer_info::queued;
360 p.client = m_client_version;
361 p.connection_type = peer_info::standard_bittorrent;
365 bool bt_peer_connection::in_handshake() const
367 return m_state < read_packet_size;
370 #ifndef TORRENT_DISABLE_ENCRYPTION
372 void bt_peer_connection::write_pe1_2_dhkey()
374 INVARIANT_CHECK;
376 TORRENT_ASSERT(!m_encrypted);
377 TORRENT_ASSERT(!m_rc4_encrypted);
378 TORRENT_ASSERT(!m_dh_key_exchange.get());
379 TORRENT_ASSERT(!m_sent_handshake);
381 #ifdef TORRENT_VERBOSE_LOGGING
382 if (is_local())
383 (*m_logger) << " initiating encrypted handshake\n";
384 #endif
386 m_dh_key_exchange.reset(new (std::nothrow) dh_key_exchange);
387 if (!m_dh_key_exchange || !m_dh_key_exchange->good())
389 disconnect("out of memory");
390 return;
393 int pad_size = std::rand() % 512;
395 #ifdef TORRENT_VERBOSE_LOGGING
396 (*m_logger) << " pad size: " << pad_size << "\n";
397 #endif
399 buffer::interval send_buf = allocate_send_buffer(dh_key_len + pad_size);
400 if (send_buf.begin == 0)
402 disconnect("out of memory");
403 return;
406 std::copy(m_dh_key_exchange->get_local_key(),
407 m_dh_key_exchange->get_local_key() + dh_key_len,
408 send_buf.begin);
410 std::generate(send_buf.begin + dh_key_len, send_buf.end, std::rand);
411 setup_send();
413 #ifdef TORRENT_VERBOSE_LOGGING
414 (*m_logger) << " sent DH key\n";
415 #endif
418 void bt_peer_connection::write_pe3_sync()
420 INVARIANT_CHECK;
422 TORRENT_ASSERT(!m_encrypted);
423 TORRENT_ASSERT(!m_rc4_encrypted);
424 TORRENT_ASSERT(is_local());
425 TORRENT_ASSERT(!m_sent_handshake);
427 boost::shared_ptr<torrent> t = associated_torrent().lock();
428 TORRENT_ASSERT(t);
430 hasher h;
431 sha1_hash const& info_hash = t->torrent_file().info_hash();
432 char const* const secret = m_dh_key_exchange->get_secret();
434 int pad_size = rand() % 512;
436 // synchash,skeyhash,vc,crypto_provide,len(pad),pad,len(ia)
437 buffer::interval send_buf =
438 allocate_send_buffer(20 + 20 + 8 + 4 + 2 + pad_size + 2);
439 if (send_buf.begin == 0) return; // out of memory
441 // sync hash (hash('req1',S))
442 h.reset();
443 h.update("req1",4);
444 h.update(secret, dh_key_len);
445 sha1_hash sync_hash = h.final();
447 std::copy(sync_hash.begin(), sync_hash.end(), send_buf.begin);
448 send_buf.begin += 20;
450 // stream key obfuscated hash [ hash('req2',SKEY) xor hash('req3',S) ]
451 h.reset();
452 h.update("req2",4);
453 h.update((const char*)info_hash.begin(), 20);
454 sha1_hash streamkey_hash = h.final();
456 h.reset();
457 h.update("req3",4);
458 h.update(secret, dh_key_len);
459 sha1_hash obfsc_hash = h.final();
460 obfsc_hash ^= streamkey_hash;
462 std::copy(obfsc_hash.begin(), obfsc_hash.end(), send_buf.begin);
463 send_buf.begin += 20;
465 // Discard DH key exchange data, setup RC4 keys
466 init_pe_RC4_handler(secret, info_hash);
467 m_dh_key_exchange.reset(); // secret should be invalid at this point
469 // write the verification constant and crypto field
470 TORRENT_ASSERT(send_buf.left() == 8 + 4 + 2 + pad_size + 2);
471 int encrypt_size = send_buf.left();
473 int crypto_provide = 0;
474 pe_settings::enc_level const& allowed_enc_level = m_ses.get_pe_settings().allowed_enc_level;
476 if (allowed_enc_level == pe_settings::both)
477 crypto_provide = 0x03;
478 else if (allowed_enc_level == pe_settings::rc4)
479 crypto_provide = 0x02;
480 else if (allowed_enc_level == pe_settings::plaintext)
481 crypto_provide = 0x01;
483 #ifdef TORRENT_VERBOSE_LOGGING
484 (*m_logger) << " crypto provide : [ ";
485 if (allowed_enc_level == pe_settings::both)
486 (*m_logger) << "plaintext rc4 ]\n";
487 else if (allowed_enc_level == pe_settings::rc4)
488 (*m_logger) << "rc4 ]\n";
489 else if (allowed_enc_level == pe_settings::plaintext)
490 (*m_logger) << "plaintext ]\n";
491 #endif
493 write_pe_vc_cryptofield(send_buf, crypto_provide, pad_size);
494 m_RC4_handler->encrypt(send_buf.end - encrypt_size, encrypt_size);
496 TORRENT_ASSERT(send_buf.begin == send_buf.end);
497 setup_send();
500 void bt_peer_connection::write_pe4_sync(int crypto_select)
502 INVARIANT_CHECK;
504 TORRENT_ASSERT(!is_local());
505 TORRENT_ASSERT(!m_encrypted);
506 TORRENT_ASSERT(!m_rc4_encrypted);
507 TORRENT_ASSERT(crypto_select == 0x02 || crypto_select == 0x01);
508 TORRENT_ASSERT(!m_sent_handshake);
510 int pad_size =rand() % 512;
512 const int buf_size = 8 + 4 + 2 + pad_size;
513 buffer::interval send_buf = allocate_send_buffer(buf_size);
514 if (send_buf.begin == 0) return; // out of memory
515 write_pe_vc_cryptofield(send_buf, crypto_select, pad_size);
517 m_RC4_handler->encrypt(send_buf.end - buf_size, buf_size);
518 setup_send();
520 // encryption method has been negotiated
521 if (crypto_select == 0x02)
522 m_rc4_encrypted = true;
523 else // 0x01
524 m_rc4_encrypted = false;
526 #ifdef TORRENT_VERBOSE_LOGGING
527 (*m_logger) << " crypto select : [ ";
528 if (crypto_select == 0x01)
529 (*m_logger) << "plaintext ]\n";
530 else
531 (*m_logger) << "rc4 ]\n";
532 #endif
535 void bt_peer_connection::write_pe_vc_cryptofield(buffer::interval& write_buf
536 , int crypto_field, int pad_size)
538 INVARIANT_CHECK;
540 TORRENT_ASSERT(crypto_field <= 0x03 && crypto_field > 0);
541 // vc,crypto_field,len(pad),pad, (len(ia))
542 TORRENT_ASSERT( (write_buf.left() == 8+4+2+pad_size+2 && is_local()) ||
543 (write_buf.left() == 8+4+2+pad_size && !is_local()) );
544 TORRENT_ASSERT(!m_sent_handshake);
546 // encrypt(vc, crypto_provide/select, len(Pad), len(IA))
547 // len(pad) is zero for now, len(IA) only for outgoing connections
549 // vc
550 std::fill(write_buf.begin, write_buf.begin + 8, 0);
551 write_buf.begin += 8;
553 detail::write_uint32(crypto_field, write_buf.begin);
554 detail::write_uint16(pad_size, write_buf.begin); // len (pad)
556 // fill pad with zeroes
557 std::generate(write_buf.begin, write_buf.begin + pad_size, &std::rand);
558 write_buf.begin += pad_size;
560 // append len(ia) if we are initiating
561 if (is_local())
562 detail::write_uint16(handshake_len, write_buf.begin); // len(IA)
564 TORRENT_ASSERT(write_buf.begin == write_buf.end);
567 void bt_peer_connection::init_pe_RC4_handler(char const* secret, sha1_hash const& stream_key)
569 INVARIANT_CHECK;
571 TORRENT_ASSERT(secret);
573 hasher h;
574 static const char keyA[] = "keyA";
575 static const char keyB[] = "keyB";
577 // encryption rc4 longkeys
578 // outgoing connection : hash ('keyA',S,SKEY)
579 // incoming connection : hash ('keyB',S,SKEY)
581 is_local() ? h.update(keyA, 4) : h.update(keyB, 4);
582 h.update(secret, dh_key_len);
583 h.update((char const*)stream_key.begin(), 20);
584 const sha1_hash local_key = h.final();
586 h.reset();
588 // decryption rc4 longkeys
589 // outgoing connection : hash ('keyB',S,SKEY)
590 // incoming connection : hash ('keyA',S,SKEY)
592 is_local() ? h.update(keyB, 4) : h.update(keyA, 4);
593 h.update(secret, dh_key_len);
594 h.update((char const*)stream_key.begin(), 20);
595 const sha1_hash remote_key = h.final();
597 TORRENT_ASSERT(!m_RC4_handler.get());
598 m_RC4_handler.reset(new RC4_handler (local_key, remote_key));
600 #ifdef TORRENT_VERBOSE_LOGGING
601 (*m_logger) << " computed RC4 keys\n";
602 #endif
605 void bt_peer_connection::send_buffer(char* buf, int size, int flags)
607 TORRENT_ASSERT(buf);
608 TORRENT_ASSERT(size > 0);
610 if (m_encrypted && m_rc4_encrypted)
611 m_RC4_handler->encrypt(buf, size);
613 peer_connection::send_buffer(buf, size, flags);
616 buffer::interval bt_peer_connection::allocate_send_buffer(int size)
618 if (m_encrypted && m_rc4_encrypted)
620 TORRENT_ASSERT(m_enc_send_buffer.left() == 0);
621 m_enc_send_buffer = peer_connection::allocate_send_buffer(size);
622 return m_enc_send_buffer;
624 else
626 buffer::interval i = peer_connection::allocate_send_buffer(size);
627 return i;
631 void bt_peer_connection::setup_send()
633 if (m_encrypted && m_rc4_encrypted && m_enc_send_buffer.left())
635 TORRENT_ASSERT(m_enc_send_buffer.begin);
636 TORRENT_ASSERT(m_enc_send_buffer.end);
638 m_RC4_handler->encrypt(m_enc_send_buffer.begin, m_enc_send_buffer.left());
639 m_enc_send_buffer.end = m_enc_send_buffer.begin;
641 peer_connection::setup_send();
644 int bt_peer_connection::get_syncoffset(char const* src, int src_size,
645 char const* target, int target_size) const
647 TORRENT_ASSERT(target_size >= src_size);
648 TORRENT_ASSERT(src_size > 0);
649 TORRENT_ASSERT(src);
650 TORRENT_ASSERT(target);
652 int traverse_limit = target_size - src_size;
654 // TODO: this could be optimized using knuth morris pratt
655 for (int i = 0; i < traverse_limit; ++i)
657 char const* target_ptr = target + i;
658 if (std::equal(src, src+src_size, target_ptr))
659 return i;
662 // // Partial sync
663 // for (int i = 0; i < target_size; ++i)
664 // {
665 // // first is iterator in src[] at which mismatch occurs
666 // // second is iterator in target[] at which mismatch occurs
667 // std::pair<const char*, const char*> ret;
668 // int src_sync_size;
669 // if (i > traverse_limit) // partial sync test
670 // {
671 // ret = std::mismatch(src, src + src_size - (i - traverse_limit), &target[i]);
672 // src_sync_size = ret.first - src;
673 // if (src_sync_size == (src_size - (i - traverse_limit)))
674 // return i;
675 // }
676 // else // complete sync test
677 // {
678 // ret = std::mismatch(src, src + src_size, &target[i]);
679 // src_sync_size = ret.first - src;
680 // if (src_sync_size == src_size)
681 // return i;
682 // }
683 // }
685 // no complete sync
686 return -1;
688 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
690 void bt_peer_connection::write_handshake()
692 INVARIANT_CHECK;
694 TORRENT_ASSERT(!m_sent_handshake);
695 #ifndef NDEBUG
696 m_sent_handshake = true;
697 #endif
699 boost::shared_ptr<torrent> t = associated_torrent().lock();
700 TORRENT_ASSERT(t);
702 // add handshake to the send buffer
703 const char version_string[] = "BitTorrent protocol";
704 const int string_len = sizeof(version_string)-1;
706 buffer::interval i = allocate_send_buffer(1 + string_len + 8 + 20 + 20);
707 if (i.begin == 0) return; // out of memory
708 // length of version string
709 *i.begin = string_len;
710 ++i.begin;
712 // version string itself
713 std::copy(
714 version_string
715 , version_string + string_len
716 , i.begin);
717 i.begin += string_len;
719 // 8 zeroes
720 std::fill(i.begin, i.begin + 8, 0);
722 #ifndef TORRENT_DISABLE_DHT
723 // indicate that we support the DHT messages
724 *(i.begin + 7) |= 0x01;
725 #endif
727 #ifndef TORRENT_DISABLE_EXTENSIONS
728 // we support extensions
729 *(i.begin + 5) |= 0x10;
730 #endif
732 // we support FAST extension
733 *(i.begin + 7) |= 0x04;
735 i.begin += 8;
737 // info hash
738 sha1_hash const& ih = t->torrent_file().info_hash();
739 std::copy(ih.begin(), ih.end(), i.begin);
740 i.begin += 20;
742 // peer id
743 std::copy(
744 m_ses.get_peer_id().begin()
745 , m_ses.get_peer_id().end()
746 , i.begin);
747 i.begin += 20;
748 TORRENT_ASSERT(i.begin == i.end);
750 #ifdef TORRENT_VERBOSE_LOGGING
751 (*m_logger) << time_now_string() << " ==> HANDSHAKE\n";
752 #endif
753 setup_send();
756 boost::optional<piece_block_progress> bt_peer_connection::downloading_piece_progress() const
758 boost::shared_ptr<torrent> t = associated_torrent().lock();
759 TORRENT_ASSERT(t);
761 buffer::const_interval recv_buffer = receive_buffer();
762 // are we currently receiving a 'piece' message?
763 if (m_state != read_packet
764 || recv_buffer.left() < 9
765 || recv_buffer[0] != msg_piece)
766 return boost::optional<piece_block_progress>();
768 const char* ptr = recv_buffer.begin + 1;
769 peer_request r;
770 r.piece = detail::read_int32(ptr);
771 r.start = detail::read_int32(ptr);
772 r.length = packet_size() - 9;
774 // is any of the piece message header data invalid?
775 if (!verify_piece(r))
776 return boost::optional<piece_block_progress>();
778 piece_block_progress p;
780 p.piece_index = r.piece;
781 p.block_index = r.start / t->block_size();
782 p.bytes_downloaded = recv_buffer.left() - 9;
783 p.full_block_bytes = r.length;
785 return boost::optional<piece_block_progress>(p);
789 // message handlers
791 // -----------------------------
792 // --------- KEEPALIVE ---------
793 // -----------------------------
795 void bt_peer_connection::on_keepalive()
797 INVARIANT_CHECK;
799 #ifdef TORRENT_VERBOSE_LOGGING
800 (*m_logger) << time_now_string() << " <== KEEPALIVE\n";
801 #endif
802 incoming_keepalive();
805 // -----------------------------
806 // ----------- CHOKE -----------
807 // -----------------------------
809 void bt_peer_connection::on_choke(int received)
811 INVARIANT_CHECK;
813 TORRENT_ASSERT(received > 0);
814 if (packet_size() != 1)
816 disconnect("'choke' message size != 1", 2);
817 return;
819 m_statistics.received_bytes(0, received);
820 if (!packet_finished()) return;
822 incoming_choke();
823 if (is_disconnecting()) return;
824 if (!m_supports_fast)
826 boost::shared_ptr<torrent> t = associated_torrent().lock();
827 TORRENT_ASSERT(t);
828 while (!download_queue().empty())
830 piece_block const& b = download_queue().front().block;
831 peer_request r;
832 r.piece = b.piece_index;
833 r.start = b.block_index * t->block_size();
834 r.length = t->block_size();
835 incoming_reject_request(r);
840 // -----------------------------
841 // ---------- UNCHOKE ----------
842 // -----------------------------
844 void bt_peer_connection::on_unchoke(int received)
846 INVARIANT_CHECK;
848 TORRENT_ASSERT(received > 0);
849 if (packet_size() != 1)
851 disconnect("'unchoke' message size != 1", 2);
852 return;
854 m_statistics.received_bytes(0, received);
855 if (!packet_finished()) return;
857 incoming_unchoke();
860 // -----------------------------
861 // -------- INTERESTED ---------
862 // -----------------------------
864 void bt_peer_connection::on_interested(int received)
866 INVARIANT_CHECK;
868 TORRENT_ASSERT(received > 0);
869 if (packet_size() != 1)
871 disconnect("'interested' message size != 1", 2);
872 return;
874 m_statistics.received_bytes(0, received);
875 if (!packet_finished()) return;
877 incoming_interested();
880 // -----------------------------
881 // ------ NOT INTERESTED -------
882 // -----------------------------
884 void bt_peer_connection::on_not_interested(int received)
886 INVARIANT_CHECK;
888 TORRENT_ASSERT(received > 0);
889 if (packet_size() != 1)
891 disconnect("'not interested' message size != 1", 2);
892 return;
894 m_statistics.received_bytes(0, received);
895 if (!packet_finished()) return;
897 incoming_not_interested();
900 // -----------------------------
901 // ----------- HAVE ------------
902 // -----------------------------
904 void bt_peer_connection::on_have(int received)
906 INVARIANT_CHECK;
908 TORRENT_ASSERT(received > 0);
909 if (packet_size() != 5)
911 disconnect("'have' message size != 5", 2);
912 return;
914 m_statistics.received_bytes(0, received);
915 if (!packet_finished()) return;
917 buffer::const_interval recv_buffer = receive_buffer();
919 const char* ptr = recv_buffer.begin + 1;
920 int index = detail::read_int32(ptr);
922 incoming_have(index);
925 // -----------------------------
926 // --------- BITFIELD ----------
927 // -----------------------------
929 void bt_peer_connection::on_bitfield(int received)
931 INVARIANT_CHECK;
933 TORRENT_ASSERT(received > 0);
935 boost::shared_ptr<torrent> t = associated_torrent().lock();
936 TORRENT_ASSERT(t);
938 // if we don't have the metedata, we cannot
939 // verify the bitfield size
940 if (t->valid_metadata()
941 && packet_size() - 1 != ((int)get_bitfield().size() + 7) / 8)
943 disconnect("bitfield with invalid size", 2);
944 return;
947 m_statistics.received_bytes(0, received);
948 if (!packet_finished()) return;
950 buffer::const_interval recv_buffer = receive_buffer();
952 bitfield bits;
953 bits.borrow_bytes((char*)recv_buffer.begin + 1
954 , t->valid_metadata()?get_bitfield().size():(packet_size()-1)*8);
956 incoming_bitfield(bits);
959 // -----------------------------
960 // ---------- REQUEST ----------
961 // -----------------------------
963 void bt_peer_connection::on_request(int received)
965 INVARIANT_CHECK;
967 TORRENT_ASSERT(received > 0);
968 if (packet_size() != 13)
970 disconnect("'request' message size != 13", 2);
971 return;
973 m_statistics.received_bytes(0, received);
974 if (!packet_finished()) return;
976 buffer::const_interval recv_buffer = receive_buffer();
978 peer_request r;
979 const char* ptr = recv_buffer.begin + 1;
980 r.piece = detail::read_int32(ptr);
981 r.start = detail::read_int32(ptr);
982 r.length = detail::read_int32(ptr);
984 incoming_request(r);
987 // -----------------------------
988 // ----------- PIECE -----------
989 // -----------------------------
991 void bt_peer_connection::on_piece(int received)
993 INVARIANT_CHECK;
995 TORRENT_ASSERT(received > 0);
997 buffer::const_interval recv_buffer = receive_buffer();
998 int recv_pos = recv_buffer.end - recv_buffer.begin;
1000 if (recv_pos == 1)
1002 TORRENT_ASSERT(!has_disk_receive_buffer());
1003 if (!allocate_disk_receive_buffer(packet_size() - 9))
1004 return;
1006 TORRENT_ASSERT(has_disk_receive_buffer());
1008 // classify the received data as protocol chatter
1009 // or data payload for the statistics
1010 if (recv_pos <= 9)
1011 // only received protocol data
1012 m_statistics.received_bytes(0, received);
1013 else if (recv_pos - received >= 9)
1014 // only received payload data
1015 m_statistics.received_bytes(received, 0);
1016 else
1018 // received a bit of both
1019 TORRENT_ASSERT(recv_pos - received < 9);
1020 TORRENT_ASSERT(recv_pos > 9);
1021 TORRENT_ASSERT(9 - (recv_pos - received) <= 9);
1022 m_statistics.received_bytes(
1023 recv_pos - 9
1024 , 9 - (recv_pos - received));
1027 incoming_piece_fragment();
1028 if (is_disconnecting()) return;
1029 if (!packet_finished()) return;
1031 const char* ptr = recv_buffer.begin + 1;
1032 peer_request p;
1033 p.piece = detail::read_int32(ptr);
1034 p.start = detail::read_int32(ptr);
1035 p.length = packet_size() - 9;
1037 disk_buffer_holder holder(m_ses, release_disk_receive_buffer());
1038 incoming_piece(p, holder);
1041 // -----------------------------
1042 // ---------- CANCEL -----------
1043 // -----------------------------
1045 void bt_peer_connection::on_cancel(int received)
1047 INVARIANT_CHECK;
1049 TORRENT_ASSERT(received > 0);
1050 if (packet_size() != 13)
1052 disconnect("'cancel' message size != 13", 2);
1053 return;
1055 m_statistics.received_bytes(0, received);
1056 if (!packet_finished()) return;
1058 buffer::const_interval recv_buffer = receive_buffer();
1060 peer_request r;
1061 const char* ptr = recv_buffer.begin + 1;
1062 r.piece = detail::read_int32(ptr);
1063 r.start = detail::read_int32(ptr);
1064 r.length = detail::read_int32(ptr);
1066 incoming_cancel(r);
1069 // -----------------------------
1070 // --------- DHT PORT ----------
1071 // -----------------------------
1073 void bt_peer_connection::on_dht_port(int received)
1075 INVARIANT_CHECK;
1077 if (!m_supports_dht_port)
1079 disconnect("got 'dht_port' message from peer that doesn't support it", 2);
1080 return;
1083 TORRENT_ASSERT(received > 0);
1084 if (packet_size() != 3)
1086 disconnect("'dht_port' message size != 3", 2);
1087 return;
1089 m_statistics.received_bytes(0, received);
1090 if (!packet_finished()) return;
1092 buffer::const_interval recv_buffer = receive_buffer();
1094 const char* ptr = recv_buffer.begin + 1;
1095 int listen_port = detail::read_uint16(ptr);
1097 incoming_dht_port(listen_port);
1100 void bt_peer_connection::on_suggest_piece(int received)
1102 INVARIANT_CHECK;
1104 if (!m_supports_fast)
1106 disconnect("got 'suggest_piece' without FAST excension support", 2);
1107 return;
1110 m_statistics.received_bytes(0, received);
1111 if (!packet_finished()) return;
1113 buffer::const_interval recv_buffer = receive_buffer();
1115 const char* ptr = recv_buffer.begin + 1;
1116 int piece = detail::read_uint32(ptr);
1117 incoming_suggest(piece);
1120 void bt_peer_connection::on_have_all(int received)
1122 INVARIANT_CHECK;
1124 if (!m_supports_fast)
1126 disconnect("got 'have_all' without FAST extension support", 2);
1127 return;
1129 m_statistics.received_bytes(0, received);
1130 incoming_have_all();
1133 void bt_peer_connection::on_have_none(int received)
1135 INVARIANT_CHECK;
1137 if (!m_supports_fast)
1139 disconnect("got 'have_none' without FAST extension support", 2);
1140 return;
1142 m_statistics.received_bytes(0, received);
1143 incoming_have_none();
1146 void bt_peer_connection::on_reject_request(int received)
1148 INVARIANT_CHECK;
1150 if (!m_supports_fast)
1152 disconnect("got 'reject_request' without FAST extension support", 2);
1153 return;
1156 m_statistics.received_bytes(0, received);
1157 if (!packet_finished()) return;
1159 buffer::const_interval recv_buffer = receive_buffer();
1161 peer_request r;
1162 const char* ptr = recv_buffer.begin + 1;
1163 r.piece = detail::read_int32(ptr);
1164 r.start = detail::read_int32(ptr);
1165 r.length = detail::read_int32(ptr);
1167 incoming_reject_request(r);
1170 void bt_peer_connection::on_allowed_fast(int received)
1172 INVARIANT_CHECK;
1174 if (!m_supports_fast)
1176 disconnect("got 'allowed_fast' without FAST extension support", 2);
1177 return;
1180 m_statistics.received_bytes(0, received);
1181 if (!packet_finished()) return;
1182 buffer::const_interval recv_buffer = receive_buffer();
1183 const char* ptr = recv_buffer.begin + 1;
1184 int index = detail::read_int32(ptr);
1186 incoming_allowed_fast(index);
1189 // -----------------------------
1190 // --------- EXTENDED ----------
1191 // -----------------------------
1193 void bt_peer_connection::on_extended(int received)
1195 INVARIANT_CHECK;
1197 TORRENT_ASSERT(received > 0);
1198 m_statistics.received_bytes(0, received);
1199 if (packet_size() < 2)
1201 disconnect("'extended' message smaller than 2 bytes", 2);
1202 return;
1205 if (associated_torrent().expired())
1207 disconnect("'extended' message sent before proper handshake", 2);
1208 return;
1211 buffer::const_interval recv_buffer = receive_buffer();
1212 if (recv_buffer.left() < 2) return;
1214 TORRENT_ASSERT(*recv_buffer.begin == msg_extended);
1215 ++recv_buffer.begin;
1217 int extended_id = detail::read_uint8(recv_buffer.begin);
1219 if (extended_id == 0)
1221 on_extended_handshake();
1222 return;
1225 #ifndef TORRENT_DISABLE_EXTENSIONS
1226 for (extension_list_t::iterator i = m_extensions.begin()
1227 , end(m_extensions.end()); i != end; ++i)
1229 if ((*i)->on_extended(packet_size() - 2, extended_id
1230 , recv_buffer))
1231 return;
1233 #endif
1235 std::stringstream msg;
1236 msg << "unknown extended message id: " << extended_id;
1237 disconnect(msg.str().c_str(), 2);
1238 return;
1241 void bt_peer_connection::on_extended_handshake()
1243 if (!packet_finished()) return;
1245 boost::shared_ptr<torrent> t = associated_torrent().lock();
1246 TORRENT_ASSERT(t);
1248 buffer::const_interval recv_buffer = receive_buffer();
1250 lazy_entry root;
1251 lazy_bdecode(recv_buffer.begin + 2, recv_buffer.end, root);
1252 if (root.type() != lazy_entry::dict_t)
1254 #ifdef TORRENT_VERBOSE_LOGGING
1255 (*m_logger) << "invalid extended handshake\n";
1256 #endif
1257 return;
1260 #ifdef TORRENT_VERBOSE_LOGGING
1261 (*m_logger) << "<== EXTENDED HANDSHAKE: \n" << root;
1262 #endif
1264 #ifndef TORRENT_DISABLE_EXTENSIONS
1265 for (extension_list_t::iterator i = m_extensions.begin();
1266 !m_extensions.empty() && i != m_extensions.end();)
1268 // a false return value means that the extension
1269 // isn't supported by the other end. So, it is removed.
1270 if (!(*i)->on_extension_handshake(root))
1271 i = m_extensions.erase(i);
1272 else
1273 ++i;
1275 #endif
1277 // there is supposed to be a remote listen port
1278 int listen_port = root.dict_find_int_value("p");
1279 if (listen_port > 0 && peer_info_struct() != 0)
1281 t->get_policy().update_peer_port(listen_port
1282 , peer_info_struct(), peer_info::incoming);
1284 // there should be a version too
1285 // but where do we put that info?
1287 std::string client_info = root.dict_find_string_value("v");
1288 if (!client_info.empty()) m_client_version = client_info;
1290 int reqq = root.dict_find_int_value("reqq");
1291 if (reqq > 0) m_max_out_request_queue = reqq;
1293 if (root.dict_find_int_value("upload_only"))
1294 set_upload_only(true);
1296 std::string myip = root.dict_find_string_value("yourip");
1297 if (!myip.empty())
1299 // TODO: don't trust this blindly
1300 if (myip.size() == address_v4::bytes_type::static_size)
1302 address_v4::bytes_type bytes;
1303 std::copy(myip.begin(), myip.end(), bytes.begin());
1304 m_ses.set_external_address(address_v4(bytes));
1306 else if (myip.size() == address_v6::bytes_type::static_size)
1308 address_v6::bytes_type bytes;
1309 std::copy(myip.begin(), myip.end(), bytes.begin());
1310 m_ses.set_external_address(address_v6(bytes));
1314 // if we're finished and this peer is uploading only
1315 // disconnect it
1316 if (t->is_finished() && upload_only())
1317 disconnect("upload to upload connection, closing");
1320 bool bt_peer_connection::dispatch_message(int received)
1322 INVARIANT_CHECK;
1324 TORRENT_ASSERT(received > 0);
1326 // this means the connection has been closed already
1327 if (associated_torrent().expired()) return false;
1329 buffer::const_interval recv_buffer = receive_buffer();
1331 TORRENT_ASSERT(recv_buffer.left() >= 1);
1332 int packet_type = recv_buffer[0];
1333 if (packet_type < 0
1334 || packet_type >= num_supported_messages
1335 || m_message_handler[packet_type] == 0)
1337 #ifndef TORRENT_DISABLE_EXTENSIONS
1338 for (extension_list_t::iterator i = m_extensions.begin()
1339 , end(m_extensions.end()); i != end; ++i)
1341 if ((*i)->on_unknown_message(packet_size(), packet_type
1342 , buffer::const_interval(recv_buffer.begin+1
1343 , recv_buffer.end)))
1344 return packet_finished();
1346 #endif
1348 std::stringstream msg;
1349 msg << "unkown message id: " << packet_type << " size: " << packet_size();
1350 disconnect(msg.str().c_str(), 2);
1351 return packet_finished();
1354 TORRENT_ASSERT(m_message_handler[packet_type] != 0);
1356 // call the correct handler for this packet type
1357 (this->*m_message_handler[packet_type])(received);
1359 return packet_finished();
1362 void bt_peer_connection::write_keepalive()
1364 INVARIANT_CHECK;
1366 // Don't require the bitfield to have been sent at this point
1367 // the case where m_sent_bitfield may not be true is if the
1368 // torrent doesn't have any metadata, and a peer is timimg out.
1369 // then the keep-alive message will be sent before the bitfield
1370 // this is a violation to the original protocol, but necessary
1371 // for the metadata extension.
1372 TORRENT_ASSERT(m_sent_handshake);
1374 char msg[] = {0,0,0,0};
1375 send_buffer(msg, sizeof(msg));
1378 void bt_peer_connection::write_cancel(peer_request const& r)
1380 INVARIANT_CHECK;
1382 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1383 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
1385 char msg[17] = {0,0,0,13, msg_cancel};
1386 char* ptr = msg + 5;
1387 detail::write_int32(r.piece, ptr); // index
1388 detail::write_int32(r.start, ptr); // begin
1389 detail::write_int32(r.length, ptr); // length
1390 send_buffer(msg, sizeof(msg));
1392 if (!m_supports_fast)
1393 incoming_reject_request(r);
1396 void bt_peer_connection::write_request(peer_request const& r)
1398 INVARIANT_CHECK;
1400 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1401 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
1403 char msg[17] = {0,0,0,13, msg_request};
1404 char* ptr = msg + 5;
1406 detail::write_int32(r.piece, ptr); // index
1407 detail::write_int32(r.start, ptr); // begin
1408 detail::write_int32(r.length, ptr); // length
1409 send_buffer(msg, sizeof(msg), message_type_request);
1412 void bt_peer_connection::write_bitfield()
1414 INVARIANT_CHECK;
1416 boost::shared_ptr<torrent> t = associated_torrent().lock();
1417 TORRENT_ASSERT(t);
1418 TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
1419 TORRENT_ASSERT(t->valid_metadata());
1421 // in this case, have_all or have_none should be sent instead
1422 TORRENT_ASSERT(!m_supports_fast || !t->is_seed() || t->num_have() != 0);
1424 if (m_supports_fast && t->is_seed())
1426 write_have_all();
1427 send_allowed_set();
1428 return;
1430 else if (m_supports_fast && t->num_have() == 0)
1432 write_have_none();
1433 send_allowed_set();
1434 return;
1436 else if (t->num_have() == 0)
1438 // don't send a bitfield if we don't have any pieces
1439 #ifdef TORRENT_VERBOSE_LOGGING
1440 (*m_logger) << time_now_string() << " *** NOT SENDING BITFIELD";
1441 #endif
1442 #ifndef NDEBUG
1443 m_sent_bitfield = true;
1444 #endif
1445 return;
1448 int num_pieces = t->torrent_file().num_pieces();
1449 int lazy_pieces[50];
1450 int num_lazy_pieces = 0;
1451 int lazy_piece = 0;
1453 if (t->is_seed() && m_ses.settings().lazy_bitfields)
1455 num_lazy_pieces = (std::min)(50, num_pieces / 10);
1456 if (num_lazy_pieces < 1) num_lazy_pieces = 1;
1457 for (int i = 0; i < num_pieces; ++i)
1459 if (rand() % (num_pieces - i) >= num_lazy_pieces - lazy_piece) continue;
1460 lazy_pieces[lazy_piece++] = i;
1462 TORRENT_ASSERT(lazy_piece == num_lazy_pieces);
1463 lazy_piece = 0;
1466 const int packet_size = (num_pieces + 7) / 8 + 5;
1468 buffer::interval i = allocate_send_buffer(packet_size);
1469 if (i.begin == 0) return; // out of memory
1471 detail::write_int32(packet_size - 4, i.begin);
1472 detail::write_uint8(msg_bitfield, i.begin);
1474 if (t->is_seed())
1476 memset(i.begin, 0xff, packet_size - 5);
1478 else
1480 memset(i.begin, 0, packet_size - 5);
1481 piece_picker const& p = t->picker();
1482 int mask = 0x80;
1483 unsigned char* byte = (unsigned char*)i.begin;
1484 for (int i = 0; i < num_pieces; ++i)
1486 if (p.have_piece(i)) *byte |= mask;
1487 mask >>= 1;
1488 if (mask == 0)
1490 mask = 0x80;
1491 ++byte;
1495 for (int c = 0; c < num_lazy_pieces; ++c)
1496 i.begin[lazy_pieces[c] / 8] &= ~(0x80 >> (lazy_pieces[c] & 7));
1497 TORRENT_ASSERT(i.end - i.begin == (num_pieces + 7) / 8);
1499 #ifdef TORRENT_VERBOSE_LOGGING
1500 (*m_logger) << time_now_string() << " ==> BITFIELD ";
1502 std::stringstream bitfield_string;
1503 for (int k = 0; k < num_pieces; ++k)
1505 if (i.begin[k / 8] & (0x80 >> (k % 8))) bitfield_string << "1";
1506 else bitfield_string << "0";
1508 bitfield_string << "\n";
1509 (*m_logger) << bitfield_string.str();
1510 #endif
1511 #ifndef NDEBUG
1512 m_sent_bitfield = true;
1513 #endif
1515 if (num_lazy_pieces > 0)
1517 for (int i = 0; i < num_lazy_pieces; ++i)
1519 write_have(lazy_pieces[i]);
1520 #ifdef TORRENT_VERBOSE_LOGGING
1521 (*m_logger) << time_now_string()
1522 << " ==> HAVE [ piece: " << lazy_pieces[i] << "]\n";
1523 #endif
1527 if (m_supports_fast)
1528 send_allowed_set();
1529 setup_send();
1532 #ifndef TORRENT_DISABLE_EXTENSIONS
1533 void bt_peer_connection::write_extensions()
1535 INVARIANT_CHECK;
1537 #ifdef TORRENT_VERBOSE_LOGGING
1538 (*m_logger) << time_now_string() << " ==> EXTENSIONS\n";
1539 #endif
1540 TORRENT_ASSERT(m_supports_extensions);
1541 TORRENT_ASSERT(m_sent_handshake);
1543 entry handshake(entry::dictionary_t);
1544 entry extension_list(entry::dictionary_t);
1546 handshake["m"] = extension_list;
1548 // only send the port in case we bade the connection
1549 // on incoming connections the other end already knows
1550 // our listen port
1551 if (is_local()) handshake["p"] = m_ses.listen_port();
1552 handshake["v"] = m_ses.settings().user_agent;
1553 std::string remote_address;
1554 std::back_insert_iterator<std::string> out(remote_address);
1555 detail::write_address(remote().address(), out);
1556 handshake["yourip"] = remote_address;
1557 handshake["reqq"] = m_ses.settings().max_allowed_in_request_queue;
1558 boost::shared_ptr<torrent> t = associated_torrent().lock();
1559 TORRENT_ASSERT(t);
1560 if (t->is_finished()) handshake["upload_only"] = 1;
1562 tcp::endpoint ep = m_ses.get_ipv6_interface();
1563 if (ep != tcp::endpoint())
1565 std::string ipv6_address;
1566 std::back_insert_iterator<std::string> out(ipv6_address);
1567 detail::write_address(ep.address(), out);
1568 handshake["ipv6"] = ipv6_address;
1571 // loop backwards, to make the first extension be the last
1572 // to fill in the handshake (i.e. give the first extensions priority)
1573 for (extension_list_t::reverse_iterator i = m_extensions.rbegin()
1574 , end(m_extensions.rend()); i != end; ++i)
1576 (*i)->add_handshake(handshake);
1579 std::vector<char> msg;
1580 bencode(std::back_inserter(msg), handshake);
1582 // make room for message
1583 buffer::interval i = allocate_send_buffer(6 + msg.size());
1584 if (i.begin == 0) return; // out of memory
1586 // write the length of the message
1587 detail::write_int32((int)msg.size() + 2, i.begin);
1588 detail::write_uint8(msg_extended, i.begin);
1589 // signal handshake message
1590 detail::write_uint8(0, i.begin);
1592 std::copy(msg.begin(), msg.end(), i.begin);
1593 i.begin += msg.size();
1594 TORRENT_ASSERT(i.begin == i.end);
1596 #ifdef TORRENT_VERBOSE_LOGGING
1597 std::stringstream ext;
1598 handshake.print(ext);
1599 (*m_logger) << "==> EXTENDED HANDSHAKE: \n" << ext.str();
1600 #endif
1602 setup_send();
1604 #endif
1606 void bt_peer_connection::write_choke()
1608 INVARIANT_CHECK;
1610 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1612 if (is_choked()) return;
1613 char msg[] = {0,0,0,1,msg_choke};
1614 send_buffer(msg, sizeof(msg));
1617 void bt_peer_connection::write_unchoke()
1619 INVARIANT_CHECK;
1621 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1623 char msg[] = {0,0,0,1,msg_unchoke};
1624 send_buffer(msg, sizeof(msg));
1627 void bt_peer_connection::write_interested()
1629 INVARIANT_CHECK;
1631 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1633 char msg[] = {0,0,0,1,msg_interested};
1634 send_buffer(msg, sizeof(msg));
1637 void bt_peer_connection::write_not_interested()
1639 INVARIANT_CHECK;
1641 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1643 char msg[] = {0,0,0,1,msg_not_interested};
1644 send_buffer(msg, sizeof(msg));
1647 void bt_peer_connection::write_have(int index)
1649 INVARIANT_CHECK;
1650 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
1651 TORRENT_ASSERT(index >= 0);
1652 TORRENT_ASSERT(index < associated_torrent().lock()->torrent_file().num_pieces());
1653 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1655 char msg[] = {0,0,0,5,msg_have,0,0,0,0};
1656 char* ptr = msg + 5;
1657 detail::write_int32(index, ptr);
1658 send_buffer(msg, sizeof(msg));
1661 void bt_peer_connection::write_piece(peer_request const& r, disk_buffer_holder& buffer)
1663 INVARIANT_CHECK;
1665 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1667 boost::shared_ptr<torrent> t = associated_torrent().lock();
1668 TORRENT_ASSERT(t);
1670 char msg[4 + 1 + 4 + 4];
1671 char* ptr = msg;
1672 TORRENT_ASSERT(r.length <= 16 * 1024);
1673 detail::write_int32(r.length + 1 + 4 + 4, ptr);
1674 detail::write_uint8(msg_piece, ptr);
1675 detail::write_int32(r.piece, ptr);
1676 detail::write_int32(r.start, ptr);
1677 send_buffer(msg, sizeof(msg));
1679 append_send_buffer(buffer.get(), r.length
1680 , boost::bind(&session_impl::free_disk_buffer
1681 , boost::ref(m_ses), _1));
1682 buffer.release();
1684 m_payloads.push_back(range(send_buffer_size() - r.length, r.length));
1685 setup_send();
1688 namespace
1690 struct match_peer_id
1692 match_peer_id(peer_id const& id, peer_connection const* pc)
1693 : m_id(id), m_pc(pc)
1694 { TORRENT_ASSERT(pc); }
1696 bool operator()(std::pair<const address, policy::peer> const& p) const
1698 return p.second.connection != m_pc
1699 && p.second.connection
1700 && p.second.connection->pid() == m_id
1701 && !p.second.connection->pid().is_all_zeros()
1702 && p.second.addr == m_pc->remote().address();
1705 peer_id const& m_id;
1706 peer_connection const* m_pc;
1710 // --------------------------
1711 // RECEIVE DATA
1712 // --------------------------
1714 // throws exception when the client should be disconnected
1715 void bt_peer_connection::on_receive(error_code const& error
1716 , std::size_t bytes_transferred)
1718 INVARIANT_CHECK;
1720 if (error) return;
1721 boost::shared_ptr<torrent> t = associated_torrent().lock();
1723 if (in_handshake())
1724 m_statistics.received_bytes(0, bytes_transferred);
1726 #ifndef TORRENT_DISABLE_ENCRYPTION
1727 TORRENT_ASSERT(in_handshake() || !m_rc4_encrypted || m_encrypted);
1728 if (m_rc4_encrypted && m_encrypted)
1730 std::pair<buffer::interval, buffer::interval> wr_buf = wr_recv_buffers(bytes_transferred);
1731 m_RC4_handler->decrypt(wr_buf.first.begin, wr_buf.first.left());
1732 if (wr_buf.second.left()) m_RC4_handler->decrypt(wr_buf.second.begin, wr_buf.second.left());
1734 #endif
1736 buffer::const_interval recv_buffer = receive_buffer();
1738 #ifndef TORRENT_DISABLE_ENCRYPTION
1739 // m_state is set to read_pe_dhkey in initial state
1740 // (read_protocol_identifier) for incoming, or in constructor
1741 // for outgoing
1742 if (m_state == read_pe_dhkey)
1744 TORRENT_ASSERT(!m_encrypted);
1745 TORRENT_ASSERT(!m_rc4_encrypted);
1746 TORRENT_ASSERT(packet_size() == dh_key_len);
1747 TORRENT_ASSERT(recv_buffer == receive_buffer());
1749 if (!packet_finished()) return;
1751 // write our dh public key. m_dh_key_exchange is
1752 // initialized in write_pe1_2_dhkey()
1753 if (!is_local()) write_pe1_2_dhkey();
1754 if (is_disconnecting()) return;
1756 // read dh key, generate shared secret
1757 if (m_dh_key_exchange->compute_secret(recv_buffer.begin) == -1)
1759 disconnect("out of memory");
1760 return;
1763 #ifdef TORRENT_VERBOSE_LOGGING
1764 (*m_logger) << " received DH key\n";
1765 #endif
1767 // PadA/B can be a max of 512 bytes, and 20 bytes more for
1768 // the sync hash (if incoming), or 8 bytes more for the
1769 // encrypted verification constant (if outgoing). Instead
1770 // of requesting the maximum possible, request the maximum
1771 // possible to ensure we do not overshoot the standard
1772 // handshake.
1774 if (is_local())
1776 m_state = read_pe_syncvc;
1777 write_pe3_sync();
1779 // initial payload is the standard handshake, this is
1780 // always rc4 if sent here. m_rc4_encrypted is flagged
1781 // again according to peer selection.
1782 m_rc4_encrypted = true;
1783 m_encrypted = true;
1784 write_handshake();
1785 m_rc4_encrypted = false;
1786 m_encrypted = false;
1788 // vc,crypto_select,len(pad),pad, encrypt(handshake)
1789 // 8+4+2+0+handshake_len
1790 reset_recv_buffer(8+4+2+0+handshake_len);
1792 else
1794 // already written dh key
1795 m_state = read_pe_synchash;
1796 // synchash,skeyhash,vc,crypto_provide,len(pad),pad,encrypt(handshake)
1797 reset_recv_buffer(20+20+8+4+2+0+handshake_len);
1799 TORRENT_ASSERT(!packet_finished());
1800 return;
1803 // cannot fall through into
1804 if (m_state == read_pe_synchash)
1806 TORRENT_ASSERT(!m_encrypted);
1807 TORRENT_ASSERT(!m_rc4_encrypted);
1808 TORRENT_ASSERT(!is_local());
1809 TORRENT_ASSERT(recv_buffer == receive_buffer());
1811 if (recv_buffer.left() < 20)
1813 if (packet_finished())
1814 disconnect("sync hash not found", 2);
1815 return;
1818 if (!m_sync_hash.get())
1820 TORRENT_ASSERT(m_sync_bytes_read == 0);
1821 hasher h;
1823 // compute synchash (hash('req1',S))
1824 h.update("req1", 4);
1825 h.update(m_dh_key_exchange->get_secret(), dh_key_len);
1827 m_sync_hash.reset(new sha1_hash(h.final()));
1830 int syncoffset = get_syncoffset((char*)m_sync_hash->begin(), 20
1831 , recv_buffer.begin, recv_buffer.left());
1833 // No sync
1834 if (syncoffset == -1)
1836 std::size_t bytes_processed = recv_buffer.left() - 20;
1837 m_sync_bytes_read += bytes_processed;
1838 if (m_sync_bytes_read >= 512)
1840 disconnect("sync hash not found within 532 bytes", 2);
1841 return;
1844 cut_receive_buffer(bytes_processed, (std::min)(packet_size()
1845 , (512+20) - m_sync_bytes_read));
1847 TORRENT_ASSERT(!packet_finished());
1848 return;
1850 // found complete sync
1851 else
1853 std::size_t bytes_processed = syncoffset + 20;
1854 #ifdef TORRENT_VERBOSE_LOGGING
1855 (*m_logger) << " sync point (hash) found at offset "
1856 << m_sync_bytes_read + bytes_processed - 20 << "\n";
1857 #endif
1858 m_state = read_pe_skey_vc;
1859 // skey,vc - 28 bytes
1860 m_sync_hash.reset();
1861 cut_receive_buffer(bytes_processed, 28);
1865 if (m_state == read_pe_skey_vc)
1867 TORRENT_ASSERT(!m_encrypted);
1868 TORRENT_ASSERT(!m_rc4_encrypted);
1869 TORRENT_ASSERT(!is_local());
1870 TORRENT_ASSERT(packet_size() == 28);
1872 if (!packet_finished()) return;
1874 recv_buffer = receive_buffer();
1876 aux::session_impl::torrent_map::const_iterator i;
1878 for (i = m_ses.m_torrents.begin(); i != m_ses.m_torrents.end(); ++i)
1880 torrent const& ti = *i->second;
1881 sha1_hash const& skey_hash = ti.obfuscated_hash();
1882 sha1_hash obfs_hash = m_dh_key_exchange->get_hash_xor_mask();
1883 obfs_hash ^= skey_hash;
1885 if (std::equal(recv_buffer.begin, recv_buffer.begin + 20,
1886 (char*)&obfs_hash[0]))
1888 if (!t)
1890 attach_to_torrent(ti.info_hash());
1891 if (is_disconnecting()) return;
1893 t = associated_torrent().lock();
1894 TORRENT_ASSERT(t);
1897 init_pe_RC4_handler(m_dh_key_exchange->get_secret(), ti.info_hash());
1898 #ifdef TORRENT_VERBOSE_LOGGING
1899 (*m_logger) << " stream key found, torrent located.\n";
1900 #endif
1901 break;
1905 if (!m_RC4_handler.get())
1907 disconnect("invalid streamkey identifier (info hash) in encrypted handshake", 2);
1908 return;
1911 // verify constant
1912 buffer::interval wr_recv_buf = wr_recv_buffer();
1913 m_RC4_handler->decrypt(wr_recv_buf.begin + 20, 8);
1914 wr_recv_buf.begin += 28;
1916 const char sh_vc[] = {0,0,0,0, 0,0,0,0};
1917 if (!std::equal(sh_vc, sh_vc+8, recv_buffer.begin + 20))
1919 disconnect("unable to verify constant", 2);
1920 return;
1923 #ifdef TORRENT_VERBOSE_LOGGING
1924 (*m_logger) << " verification constant found\n";
1925 #endif
1926 m_state = read_pe_cryptofield;
1927 reset_recv_buffer(4 + 2);
1930 // cannot fall through into
1931 if (m_state == read_pe_syncvc)
1933 TORRENT_ASSERT(is_local());
1934 TORRENT_ASSERT(!m_encrypted);
1935 TORRENT_ASSERT(!m_rc4_encrypted);
1936 TORRENT_ASSERT(recv_buffer == receive_buffer());
1938 if (recv_buffer.left() < 8)
1940 if (packet_finished())
1941 disconnect("sync verification constant not found", 2);
1942 return;
1945 // generate the verification constant
1946 if (!m_sync_vc.get())
1948 TORRENT_ASSERT(m_sync_bytes_read == 0);
1950 m_sync_vc.reset (new char[8]);
1951 std::fill(m_sync_vc.get(), m_sync_vc.get() + 8, 0);
1952 m_RC4_handler->decrypt(m_sync_vc.get(), 8);
1955 TORRENT_ASSERT(m_sync_vc.get());
1956 int syncoffset = get_syncoffset(m_sync_vc.get(), 8
1957 , recv_buffer.begin, recv_buffer.left());
1959 // No sync
1960 if (syncoffset == -1)
1962 std::size_t bytes_processed = recv_buffer.left() - 8;
1963 m_sync_bytes_read += bytes_processed;
1964 if (m_sync_bytes_read >= 512)
1966 disconnect("sync verification constant not found within 520 bytes", 2);
1967 return;
1970 cut_receive_buffer(bytes_processed, (std::min)(packet_size(), (512+8) - m_sync_bytes_read));
1972 TORRENT_ASSERT(!packet_finished());
1973 return;
1975 // found complete sync
1976 else
1978 std::size_t bytes_processed = syncoffset + 8;
1979 #ifdef TORRENT_VERBOSE_LOGGING
1980 (*m_logger) << " sync point (verification constant) found at offset "
1981 << m_sync_bytes_read + bytes_processed - 8 << "\n";
1982 #endif
1983 cut_receive_buffer (bytes_processed, 4 + 2);
1985 // delete verification constant
1986 m_sync_vc.reset();
1987 m_state = read_pe_cryptofield;
1988 // fall through
1992 if (m_state == read_pe_cryptofield) // local/remote
1994 TORRENT_ASSERT(!m_encrypted);
1995 TORRENT_ASSERT(!m_rc4_encrypted);
1996 TORRENT_ASSERT(packet_size() == 4+2);
1998 if (!packet_finished()) return;
2000 buffer::interval wr_buf = wr_recv_buffer();
2001 m_RC4_handler->decrypt(wr_buf.begin, packet_size());
2003 recv_buffer = receive_buffer();
2005 int crypto_field = detail::read_int32(recv_buffer.begin);
2007 #ifdef TORRENT_VERBOSE_LOGGING
2008 if (!is_local())
2009 (*m_logger) << " crypto provide : [ ";
2010 else
2011 (*m_logger) << " crypto select : [ ";
2013 if (crypto_field & 0x01)
2014 (*m_logger) << "plaintext ";
2015 if (crypto_field & 0x02)
2016 (*m_logger) << "rc4 ";
2017 (*m_logger) << "]\n";
2018 #endif
2020 if (!is_local())
2022 int crypto_select = 0;
2023 // select a crypto method
2024 switch (m_ses.get_pe_settings().allowed_enc_level)
2026 case pe_settings::plaintext:
2027 if (!(crypto_field & 0x01))
2029 disconnect("plaintext not provided", 1);
2030 return;
2032 crypto_select = 0x01;
2033 break;
2034 case pe_settings::rc4:
2035 if (!(crypto_field & 0x02))
2037 disconnect("rc4 not provided", 1);
2038 return;
2040 crypto_select = 0x02;
2041 break;
2042 case pe_settings::both:
2043 if (m_ses.get_pe_settings().prefer_rc4)
2045 if (crypto_field & 0x02)
2046 crypto_select = 0x02;
2047 else if (crypto_field & 0x01)
2048 crypto_select = 0x01;
2050 else
2052 if (crypto_field & 0x01)
2053 crypto_select = 0x01;
2054 else if (crypto_field & 0x02)
2055 crypto_select = 0x02;
2057 if (!crypto_select)
2059 disconnect("rc4/plaintext not provided", 1);
2060 return;
2062 break;
2063 } // switch
2065 // write the pe4 step
2066 write_pe4_sync(crypto_select);
2068 else // is_local()
2070 // check if crypto select is valid
2071 pe_settings::enc_level const& allowed_enc_level = m_ses.get_pe_settings().allowed_enc_level;
2073 if (crypto_field == 0x02)
2075 if (allowed_enc_level == pe_settings::plaintext)
2077 disconnect("rc4 selected by peer when not provided", 2);
2078 return;
2080 m_rc4_encrypted = true;
2082 else if (crypto_field == 0x01)
2084 if (allowed_enc_level == pe_settings::rc4)
2086 disconnect("plaintext selected by peer when not provided", 2);
2087 return;
2089 m_rc4_encrypted = false;
2091 else
2093 disconnect("unsupported crypto method selected by peer", 2);
2094 return;
2098 int len_pad = detail::read_int16(recv_buffer.begin);
2099 if (len_pad < 0 || len_pad > 512)
2101 disconnect("invalid pad length", 2);
2102 return;
2105 m_state = read_pe_pad;
2106 if (!is_local())
2107 reset_recv_buffer(len_pad + 2); // len(IA) at the end of pad
2108 else
2110 if (len_pad == 0)
2112 m_encrypted = true;
2113 m_state = init_bt_handshake;
2115 else
2116 reset_recv_buffer(len_pad);
2120 if (m_state == read_pe_pad)
2122 TORRENT_ASSERT(!m_encrypted);
2123 if (!packet_finished()) return;
2125 int pad_size = is_local() ? packet_size() : packet_size() - 2;
2127 buffer::interval wr_buf = wr_recv_buffer();
2128 m_RC4_handler->decrypt(wr_buf.begin, packet_size());
2130 recv_buffer = receive_buffer();
2132 if (!is_local())
2134 recv_buffer.begin += pad_size;
2135 int len_ia = detail::read_int16(recv_buffer.begin);
2137 if (len_ia < 0)
2139 disconnect("invalid len_ia in handshake", 2);
2140 return;
2143 #ifdef TORRENT_VERBOSE_LOGGING
2144 (*m_logger) << " len(IA) : " << len_ia << "\n";
2145 #endif
2146 if (len_ia == 0)
2148 // everything after this is Encrypt2
2149 m_encrypted = true;
2150 m_state = init_bt_handshake;
2152 else
2154 m_state = read_pe_ia;
2155 reset_recv_buffer(len_ia);
2158 else // is_local()
2160 // everything that arrives after this is Encrypt2
2161 m_encrypted = true;
2162 m_state = init_bt_handshake;
2166 if (m_state == read_pe_ia)
2168 TORRENT_ASSERT(!is_local());
2169 TORRENT_ASSERT(!m_encrypted);
2171 if (!packet_finished()) return;
2173 // ia is always rc4, so decrypt it
2174 buffer::interval wr_buf = wr_recv_buffer();
2175 m_RC4_handler->decrypt(wr_buf.begin, packet_size());
2177 #ifdef TORRENT_VERBOSE_LOGGING
2178 (*m_logger) << " decrypted ia : " << packet_size() << " bytes\n";
2179 #endif
2181 if (!m_rc4_encrypted)
2183 m_RC4_handler.reset();
2184 #ifdef TORRENT_VERBOSE_LOGGING
2185 (*m_logger) << " destroyed rc4 keys\n";
2186 #endif
2189 // everything that arrives after this is Encrypt2
2190 m_encrypted = true;
2192 m_state = read_protocol_identifier;
2193 cut_receive_buffer(0, 20);
2196 if (m_state == init_bt_handshake)
2198 TORRENT_ASSERT(m_encrypted);
2200 // decrypt remaining received bytes
2201 if (m_rc4_encrypted)
2203 buffer::interval wr_buf = wr_recv_buffer();
2204 wr_buf.begin += packet_size();
2205 m_RC4_handler->decrypt(wr_buf.begin, wr_buf.left());
2206 #ifdef TORRENT_VERBOSE_LOGGING
2207 (*m_logger) << " decrypted remaining " << wr_buf.left() << " bytes\n";
2208 #endif
2210 else // !m_rc4_encrypted
2212 m_RC4_handler.reset();
2213 #ifdef TORRENT_VERBOSE_LOGGING
2214 (*m_logger) << " destroyed rc4 keys\n";
2215 #endif
2218 // payload stream, start with 20 handshake bytes
2219 m_state = read_protocol_identifier;
2220 reset_recv_buffer(20);
2222 // encrypted portion of handshake completed, toggle
2223 // peer_info pe_support flag back to true
2224 if (is_local() &&
2225 m_ses.get_pe_settings().out_enc_policy == pe_settings::enabled)
2227 policy::peer* pi = peer_info_struct();
2228 TORRENT_ASSERT(pi);
2230 pi->pe_support = true;
2234 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
2236 if (m_state == read_protocol_identifier)
2238 TORRENT_ASSERT(packet_size() == 20);
2240 if (!packet_finished()) return;
2241 recv_buffer = receive_buffer();
2243 int packet_size = recv_buffer[0];
2244 const char protocol_string[] = "BitTorrent protocol";
2246 if (packet_size != 19 ||
2247 !std::equal(recv_buffer.begin + 1, recv_buffer.begin + 19, protocol_string))
2249 #ifndef TORRENT_DISABLE_ENCRYPTION
2250 if (!is_local() && m_ses.get_pe_settings().in_enc_policy == pe_settings::disabled)
2252 disconnect("encrypted incoming connections disabled");
2253 return;
2256 // Don't attempt to perform an encrypted handshake
2257 // within an encrypted connection
2258 if (!m_encrypted && !is_local())
2260 #ifdef TORRENT_VERBOSE_LOGGING
2261 (*m_logger) << " attempting encrypted connection\n";
2262 #endif
2263 m_state = read_pe_dhkey;
2264 cut_receive_buffer(0, dh_key_len);
2265 TORRENT_ASSERT(!packet_finished());
2266 return;
2269 TORRENT_ASSERT((!is_local() && m_encrypted) || is_local());
2270 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
2271 disconnect("incorrect protocol identifier", 2);
2272 return;
2275 #ifndef TORRENT_DISABLE_ENCRYPTION
2276 TORRENT_ASSERT(m_state != read_pe_dhkey);
2278 if (!is_local() &&
2279 (m_ses.get_pe_settings().in_enc_policy == pe_settings::forced) &&
2280 !m_encrypted)
2282 disconnect("non encrypted incoming connections disabled");
2283 return;
2285 #endif
2287 #ifdef TORRENT_VERBOSE_LOGGING
2288 (*m_logger) << " BitTorrent protocol\n";
2289 #endif
2291 m_state = read_info_hash;
2292 reset_recv_buffer(28);
2295 // fall through
2296 if (m_state == read_info_hash)
2298 TORRENT_ASSERT(packet_size() == 28);
2300 if (!packet_finished()) return;
2301 recv_buffer = receive_buffer();
2304 #ifdef TORRENT_VERBOSE_LOGGING
2305 for (int i=0; i < 8; ++i)
2307 for (int j=0; j < 8; ++j)
2309 if (recv_buffer[i] & (0x80 >> j)) (*m_logger) << "1";
2310 else (*m_logger) << "0";
2313 (*m_logger) << "\n";
2314 if (recv_buffer[7] & 0x01)
2315 (*m_logger) << "supports DHT port message\n";
2316 if (recv_buffer[7] & 0x04)
2317 (*m_logger) << "supports FAST extensions\n";
2318 if (recv_buffer[5] & 0x10)
2319 (*m_logger) << "supports extensions protocol\n";
2320 #endif
2322 #ifndef DISABLE_EXTENSIONS
2323 std::memcpy(m_reserved_bits, recv_buffer.begin, 20);
2324 if ((recv_buffer[5] & 0x10))
2325 m_supports_extensions = true;
2326 #endif
2327 if (recv_buffer[7] & 0x01)
2328 m_supports_dht_port = true;
2330 if (recv_buffer[7] & 0x04)
2331 m_supports_fast = true;
2333 // ok, now we have got enough of the handshake. Is this connection
2334 // attached to a torrent?
2335 if (!t)
2337 // now, we have to see if there's a torrent with the
2338 // info_hash we got from the peer
2339 sha1_hash info_hash;
2340 std::copy(recv_buffer.begin + 8, recv_buffer.begin + 28
2341 , (char*)info_hash.begin());
2343 attach_to_torrent(info_hash);
2344 if (is_disconnecting()) return;
2346 else
2348 // verify info hash
2349 if (!std::equal(recv_buffer.begin + 8, recv_buffer.begin + 28
2350 , (const char*)t->torrent_file().info_hash().begin()))
2352 #ifdef TORRENT_VERBOSE_LOGGING
2353 (*m_logger) << " received invalid info_hash\n";
2354 #endif
2355 disconnect("invalid info-hash in handshake", 2);
2356 return;
2359 #ifdef TORRENT_VERBOSE_LOGGING
2360 (*m_logger) << " info_hash received\n";
2361 #endif
2364 t = associated_torrent().lock();
2365 TORRENT_ASSERT(t);
2367 // if this is a local connection, we have already
2368 // sent the handshake
2369 if (!is_local()) write_handshake();
2370 // if (t->valid_metadata())
2371 // write_bitfield();
2373 if (is_disconnecting()) return;
2375 TORRENT_ASSERT(t->get_policy().has_connection(this));
2377 m_state = read_peer_id;
2378 reset_recv_buffer(20);
2381 // fall through
2382 if (m_state == read_peer_id)
2384 if (!t)
2386 TORRENT_ASSERT(!packet_finished()); // TODO
2387 return;
2389 TORRENT_ASSERT(packet_size() == 20);
2391 if (!packet_finished()) return;
2392 recv_buffer = receive_buffer();
2394 #ifdef TORRENT_VERBOSE_LOGGING
2396 peer_id tmp;
2397 std::copy(recv_buffer.begin, recv_buffer.begin + 20, (char*)tmp.begin());
2398 std::stringstream s;
2399 s << "received peer_id: " << tmp << " client: " << identify_client(tmp) << "\n";
2400 s << "as ascii: ";
2401 for (peer_id::iterator i = tmp.begin(); i != tmp.end(); ++i)
2403 if (std::isprint(*i)) s << *i;
2404 else s << ".";
2406 s << "\n";
2407 (*m_logger) << s.str();
2409 #endif
2410 peer_id pid;
2411 std::copy(recv_buffer.begin, recv_buffer.begin + 20, (char*)pid.begin());
2412 set_pid(pid);
2414 if (t->settings().allow_multiple_connections_per_ip)
2416 // now, let's see if this connection should be closed
2417 policy& p = t->get_policy();
2418 policy::iterator i = std::find_if(p.begin_peer(), p.end_peer()
2419 , match_peer_id(pid, this));
2420 if (i != p.end_peer())
2422 TORRENT_ASSERT(i->second.connection->pid() == pid);
2423 // we found another connection with the same peer-id
2424 // which connection should be closed in order to be
2425 // sure that the other end closes the same connection?
2426 // the peer with greatest peer-id is the one allowed to
2427 // initiate connections. So, if our peer-id is greater than
2428 // the others, we should close the incoming connection,
2429 // if not, we should close the outgoing one.
2430 if (pid < m_ses.get_peer_id() && is_local())
2432 i->second.connection->disconnect("duplicate peer-id, connection closed");
2434 else
2436 disconnect("duplicate peer-id, connection closed");
2437 return;
2442 if (pid == m_ses.get_peer_id())
2444 disconnect("closing connection to ourself", 1);
2445 return;
2448 m_client_version = identify_client(pid);
2449 boost::optional<fingerprint> f = client_fingerprint(pid);
2450 if (f && std::equal(f->name, f->name + 2, "BC"))
2452 // if this is a bitcomet client, lower the request queue size limit
2453 if (m_max_out_request_queue > 50) m_max_out_request_queue = 50;
2456 // disconnect if the peer has the same peer-id as ourself
2457 // since it most likely is ourself then
2458 if (pid == m_ses.get_peer_id())
2460 disconnect("closing connection to ourself", 1);
2461 return;
2464 #ifndef TORRENT_DISABLE_EXTENSIONS
2465 for (extension_list_t::iterator i = m_extensions.begin()
2466 , end(m_extensions.end()); i != end;)
2468 if (!(*i)->on_handshake(m_reserved_bits))
2470 i = m_extensions.erase(i);
2472 else
2474 ++i;
2477 if (is_disconnecting()) return;
2479 if (m_supports_extensions) write_extensions();
2480 #endif
2482 #ifdef TORRENT_VERBOSE_LOGGING
2483 (*m_logger) << time_now_string() << " <== HANDSHAKE\n";
2484 #endif
2485 // consider this a successful connection, reset the failcount
2486 if (peer_info_struct()) peer_info_struct()->failcount = 0;
2488 #ifndef TORRENT_DISABLE_ENCRYPTION
2489 // Toggle pe_support back to false if this is a
2490 // standard successful connection
2491 if (is_local() && !m_encrypted &&
2492 m_ses.get_pe_settings().out_enc_policy == pe_settings::enabled)
2494 policy::peer* pi = peer_info_struct();
2495 TORRENT_ASSERT(pi);
2497 pi->pe_support = false;
2499 #endif
2501 m_state = read_packet_size;
2502 reset_recv_buffer(5);
2503 if (t->valid_metadata())
2505 write_bitfield();
2506 #ifndef TORRENT_DISABLE_DHT
2507 if (m_supports_dht_port && m_ses.m_dht)
2508 write_dht_port(m_ses.get_dht_settings().service_port);
2509 #endif
2512 TORRENT_ASSERT(!packet_finished());
2513 return;
2516 // cannot fall through into
2517 if (m_state == read_packet_size)
2519 // Make sure this is not fallen though into
2520 TORRENT_ASSERT(recv_buffer == receive_buffer());
2522 if (!t) return;
2523 m_statistics.received_bytes(0, bytes_transferred);
2525 if (recv_buffer.left() < 4) return;
2527 const char* ptr = recv_buffer.begin;
2528 int packet_size = detail::read_int32(ptr);
2530 // don't accept packets larger than 1 MB
2531 if (packet_size > 1024*1024 || packet_size < 0)
2533 // packet too large
2534 std::stringstream msg;
2535 msg << "packet > 1 MB (" << (unsigned int)packet_size << " bytes)";
2536 disconnect(msg.str().c_str(), 2);
2537 return;
2540 if (packet_size == 0)
2542 incoming_keepalive();
2543 if (is_disconnecting()) return;
2544 // keepalive message
2545 m_state = read_packet_size;
2546 cut_receive_buffer(4, 4);
2547 return;
2549 else
2551 if (recv_buffer.left() < 5) return;
2553 m_state = read_packet;
2554 cut_receive_buffer(4, packet_size);
2555 bytes_transferred = 1;
2556 recv_buffer = receive_buffer();
2557 TORRENT_ASSERT(recv_buffer.left() == 1);
2561 if (m_state == read_packet)
2563 TORRENT_ASSERT(recv_buffer == receive_buffer());
2564 if (!t) return;
2565 if (dispatch_message(bytes_transferred))
2567 m_state = read_packet_size;
2568 reset_recv_buffer(5);
2570 TORRENT_ASSERT(!packet_finished());
2571 return;
2574 TORRENT_ASSERT(!packet_finished());
2577 // --------------------------
2578 // SEND DATA
2579 // --------------------------
2581 void bt_peer_connection::on_sent(error_code const& error
2582 , std::size_t bytes_transferred)
2584 INVARIANT_CHECK;
2586 if (error) return;
2588 // manage the payload markers
2589 int amount_payload = 0;
2590 if (!m_payloads.empty())
2592 for (std::deque<range>::iterator i = m_payloads.begin();
2593 i != m_payloads.end(); ++i)
2595 i->start -= bytes_transferred;
2596 if (i->start < 0)
2598 if (i->start + i->length <= 0)
2600 amount_payload += i->length;
2602 else
2604 amount_payload += -i->start;
2605 i->length -= -i->start;
2606 i->start = 0;
2612 // TODO: move the erasing into the loop above
2613 // remove all payload ranges that has been sent
2614 m_payloads.erase(
2615 std::remove_if(m_payloads.begin(), m_payloads.end(), range_below_zero)
2616 , m_payloads.end());
2618 TORRENT_ASSERT(amount_payload <= (int)bytes_transferred);
2619 m_statistics.sent_bytes(amount_payload, bytes_transferred - amount_payload);
2622 #ifndef NDEBUG
2623 void bt_peer_connection::check_invariant() const
2625 #ifndef TORRENT_DISABLE_ENCRYPTION
2626 TORRENT_ASSERT( (bool(m_state != read_pe_dhkey) || m_dh_key_exchange.get())
2627 || !is_local());
2629 TORRENT_ASSERT(!m_rc4_encrypted || m_RC4_handler.get());
2630 #endif
2631 if (!in_handshake())
2633 TORRENT_ASSERT(m_sent_handshake);
2636 if (!m_payloads.empty())
2638 for (std::deque<range>::const_iterator i = m_payloads.begin();
2639 i != m_payloads.end() - 1; ++i)
2641 TORRENT_ASSERT(i->start + i->length <= (i+1)->start);
2645 #endif