excluded mapped_storage from build
[libtorrent.git] / src / bt_peer_connection.cpp
blob72515ff197fa8ab2a1f09edef617a4c000cf86f4
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
257 void bt_peer_connection::write_dht_port(int listen_port)
259 INVARIANT_CHECK;
261 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
263 #ifdef TORRENT_VERBOSE_LOGGING
264 (*m_logger) << time_now_string()
265 << " ==> DHT_PORT [ " << listen_port << " ]\n";
266 #endif
267 char msg[] = {0,0,0,3, msg_dht_port, 0, 0};
268 char* ptr = msg + 5;
269 detail::write_uint16(listen_port, ptr);
270 send_buffer(msg, sizeof(msg));
273 void bt_peer_connection::write_have_all()
275 INVARIANT_CHECK;
276 TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
277 #ifndef NDEBUG
278 m_sent_bitfield = true;
279 #endif
280 #ifdef TORRENT_VERBOSE_LOGGING
281 (*m_logger) << time_now_string()
282 << " ==> HAVE_ALL\n";
283 #endif
284 char msg[] = {0,0,0,1, msg_have_all};
285 send_buffer(msg, sizeof(msg));
288 void bt_peer_connection::write_have_none()
290 INVARIANT_CHECK;
291 TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
292 #ifndef NDEBUG
293 m_sent_bitfield = true;
294 #endif
295 #ifdef TORRENT_VERBOSE_LOGGING
296 (*m_logger) << time_now_string()
297 << " ==> HAVE_NONE\n";
298 #endif
299 char msg[] = {0,0,0,1, msg_have_none};
300 send_buffer(msg, sizeof(msg));
303 void bt_peer_connection::write_reject_request(peer_request const& r)
305 INVARIANT_CHECK;
307 if (!m_supports_fast) return;
309 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
310 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
312 char msg[] = {0,0,0,13, msg_reject_request,0,0,0,0, 0,0,0,0, 0,0,0,0};
313 char* ptr = msg + 5;
314 detail::write_int32(r.piece, ptr); // index
315 detail::write_int32(r.start, ptr); // begin
316 detail::write_int32(r.length, ptr); // length
317 send_buffer(msg, sizeof(msg));
320 void bt_peer_connection::write_allow_fast(int piece)
322 INVARIANT_CHECK;
324 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
325 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
326 TORRENT_ASSERT(m_supports_fast);
328 char msg[] = {0,0,0,5, msg_allowed_fast, 0, 0, 0, 0};
329 char* ptr = msg + 5;
330 detail::write_int32(piece, ptr);
331 send_buffer(msg, sizeof(msg));
334 void bt_peer_connection::get_specific_peer_info(peer_info& p) const
336 TORRENT_ASSERT(!associated_torrent().expired());
338 if (is_interesting()) p.flags |= peer_info::interesting;
339 if (is_choked()) p.flags |= peer_info::choked;
340 if (is_peer_interested()) p.flags |= peer_info::remote_interested;
341 if (has_peer_choked()) p.flags |= peer_info::remote_choked;
342 if (support_extensions()) p.flags |= peer_info::supports_extensions;
343 if (is_local()) p.flags |= peer_info::local_connection;
345 #ifndef TORRENT_DISABLE_ENCRYPTION
346 if (m_encrypted)
348 m_rc4_encrypted ?
349 p.flags |= peer_info::rc4_encrypted :
350 p.flags |= peer_info::plaintext_encrypted;
352 #endif
354 if (!is_connecting() && in_handshake())
355 p.flags |= peer_info::handshake;
356 if (is_connecting() && !is_queued()) p.flags |= peer_info::connecting;
357 if (is_queued()) p.flags |= peer_info::queued;
359 p.client = m_client_version;
360 p.connection_type = peer_info::standard_bittorrent;
364 bool bt_peer_connection::in_handshake() const
366 return m_state < read_packet_size;
369 #ifndef TORRENT_DISABLE_ENCRYPTION
371 void bt_peer_connection::write_pe1_2_dhkey()
373 INVARIANT_CHECK;
375 TORRENT_ASSERT(!m_encrypted);
376 TORRENT_ASSERT(!m_rc4_encrypted);
377 TORRENT_ASSERT(!m_dh_key_exchange.get());
378 TORRENT_ASSERT(!m_sent_handshake);
380 #ifdef TORRENT_VERBOSE_LOGGING
381 if (is_local())
382 (*m_logger) << " initiating encrypted handshake\n";
383 #endif
385 m_dh_key_exchange.reset(new (std::nothrow) dh_key_exchange);
386 if (!m_dh_key_exchange || !m_dh_key_exchange->good())
388 disconnect("out of memory");
389 return;
392 int pad_size = std::rand() % 512;
394 #ifdef TORRENT_VERBOSE_LOGGING
395 (*m_logger) << " pad size: " << pad_size << "\n";
396 #endif
398 buffer::interval send_buf = allocate_send_buffer(dh_key_len + pad_size);
399 if (send_buf.begin == 0)
401 disconnect("out of memory");
402 return;
405 std::copy(m_dh_key_exchange->get_local_key(),
406 m_dh_key_exchange->get_local_key() + dh_key_len,
407 send_buf.begin);
409 std::generate(send_buf.begin + dh_key_len, send_buf.end, std::rand);
410 setup_send();
412 #ifdef TORRENT_VERBOSE_LOGGING
413 (*m_logger) << " sent DH key\n";
414 #endif
417 void bt_peer_connection::write_pe3_sync()
419 INVARIANT_CHECK;
421 TORRENT_ASSERT(!m_encrypted);
422 TORRENT_ASSERT(!m_rc4_encrypted);
423 TORRENT_ASSERT(is_local());
424 TORRENT_ASSERT(!m_sent_handshake);
426 boost::shared_ptr<torrent> t = associated_torrent().lock();
427 TORRENT_ASSERT(t);
429 hasher h;
430 sha1_hash const& info_hash = t->torrent_file().info_hash();
431 char const* const secret = m_dh_key_exchange->get_secret();
433 int pad_size = rand() % 512;
435 // synchash,skeyhash,vc,crypto_provide,len(pad),pad,len(ia)
436 buffer::interval send_buf =
437 allocate_send_buffer(20 + 20 + 8 + 4 + 2 + pad_size + 2);
438 if (send_buf.begin == 0) return; // out of memory
440 // sync hash (hash('req1',S))
441 h.reset();
442 h.update("req1",4);
443 h.update(secret, dh_key_len);
444 sha1_hash sync_hash = h.final();
446 std::copy(sync_hash.begin(), sync_hash.end(), send_buf.begin);
447 send_buf.begin += 20;
449 // stream key obfuscated hash [ hash('req2',SKEY) xor hash('req3',S) ]
450 h.reset();
451 h.update("req2",4);
452 h.update((const char*)info_hash.begin(), 20);
453 sha1_hash streamkey_hash = h.final();
455 h.reset();
456 h.update("req3",4);
457 h.update(secret, dh_key_len);
458 sha1_hash obfsc_hash = h.final();
459 obfsc_hash ^= streamkey_hash;
461 std::copy(obfsc_hash.begin(), obfsc_hash.end(), send_buf.begin);
462 send_buf.begin += 20;
464 // Discard DH key exchange data, setup RC4 keys
465 init_pe_RC4_handler(secret, info_hash);
466 m_dh_key_exchange.reset(); // secret should be invalid at this point
468 // write the verification constant and crypto field
469 TORRENT_ASSERT(send_buf.left() == 8 + 4 + 2 + pad_size + 2);
470 int encrypt_size = send_buf.left();
472 int crypto_provide = 0;
473 pe_settings::enc_level const& allowed_enc_level = m_ses.get_pe_settings().allowed_enc_level;
475 if (allowed_enc_level == pe_settings::both)
476 crypto_provide = 0x03;
477 else if (allowed_enc_level == pe_settings::rc4)
478 crypto_provide = 0x02;
479 else if (allowed_enc_level == pe_settings::plaintext)
480 crypto_provide = 0x01;
482 #ifdef TORRENT_VERBOSE_LOGGING
483 (*m_logger) << " crypto provide : [ ";
484 if (allowed_enc_level == pe_settings::both)
485 (*m_logger) << "plaintext rc4 ]\n";
486 else if (allowed_enc_level == pe_settings::rc4)
487 (*m_logger) << "rc4 ]\n";
488 else if (allowed_enc_level == pe_settings::plaintext)
489 (*m_logger) << "plaintext ]\n";
490 #endif
492 write_pe_vc_cryptofield(send_buf, crypto_provide, pad_size);
493 m_RC4_handler->encrypt(send_buf.end - encrypt_size, encrypt_size);
495 TORRENT_ASSERT(send_buf.begin == send_buf.end);
496 setup_send();
499 void bt_peer_connection::write_pe4_sync(int crypto_select)
501 INVARIANT_CHECK;
503 TORRENT_ASSERT(!is_local());
504 TORRENT_ASSERT(!m_encrypted);
505 TORRENT_ASSERT(!m_rc4_encrypted);
506 TORRENT_ASSERT(crypto_select == 0x02 || crypto_select == 0x01);
507 TORRENT_ASSERT(!m_sent_handshake);
509 int pad_size =rand() % 512;
511 const int buf_size = 8 + 4 + 2 + pad_size;
512 buffer::interval send_buf = allocate_send_buffer(buf_size);
513 if (send_buf.begin == 0) return; // out of memory
514 write_pe_vc_cryptofield(send_buf, crypto_select, pad_size);
516 m_RC4_handler->encrypt(send_buf.end - buf_size, buf_size);
517 setup_send();
519 // encryption method has been negotiated
520 if (crypto_select == 0x02)
521 m_rc4_encrypted = true;
522 else // 0x01
523 m_rc4_encrypted = false;
525 #ifdef TORRENT_VERBOSE_LOGGING
526 (*m_logger) << " crypto select : [ ";
527 if (crypto_select == 0x01)
528 (*m_logger) << "plaintext ]\n";
529 else
530 (*m_logger) << "rc4 ]\n";
531 #endif
534 void bt_peer_connection::write_pe_vc_cryptofield(buffer::interval& write_buf
535 , int crypto_field, int pad_size)
537 INVARIANT_CHECK;
539 TORRENT_ASSERT(crypto_field <= 0x03 && crypto_field > 0);
540 // vc,crypto_field,len(pad),pad, (len(ia))
541 TORRENT_ASSERT( (write_buf.left() == 8+4+2+pad_size+2 && is_local()) ||
542 (write_buf.left() == 8+4+2+pad_size && !is_local()) );
543 TORRENT_ASSERT(!m_sent_handshake);
545 // encrypt(vc, crypto_provide/select, len(Pad), len(IA))
546 // len(pad) is zero for now, len(IA) only for outgoing connections
548 // vc
549 std::fill(write_buf.begin, write_buf.begin + 8, 0);
550 write_buf.begin += 8;
552 detail::write_uint32(crypto_field, write_buf.begin);
553 detail::write_uint16(pad_size, write_buf.begin); // len (pad)
555 // fill pad with zeroes
556 std::generate(write_buf.begin, write_buf.begin + pad_size, &std::rand);
557 write_buf.begin += pad_size;
559 // append len(ia) if we are initiating
560 if (is_local())
561 detail::write_uint16(handshake_len, write_buf.begin); // len(IA)
563 TORRENT_ASSERT(write_buf.begin == write_buf.end);
566 void bt_peer_connection::init_pe_RC4_handler(char const* secret, sha1_hash const& stream_key)
568 INVARIANT_CHECK;
570 TORRENT_ASSERT(secret);
572 hasher h;
573 static const char keyA[] = "keyA";
574 static const char keyB[] = "keyB";
576 // encryption rc4 longkeys
577 // outgoing connection : hash ('keyA',S,SKEY)
578 // incoming connection : hash ('keyB',S,SKEY)
580 is_local() ? h.update(keyA, 4) : h.update(keyB, 4);
581 h.update(secret, dh_key_len);
582 h.update((char const*)stream_key.begin(), 20);
583 const sha1_hash local_key = h.final();
585 h.reset();
587 // decryption rc4 longkeys
588 // outgoing connection : hash ('keyB',S,SKEY)
589 // incoming connection : hash ('keyA',S,SKEY)
591 is_local() ? h.update(keyB, 4) : h.update(keyA, 4);
592 h.update(secret, dh_key_len);
593 h.update((char const*)stream_key.begin(), 20);
594 const sha1_hash remote_key = h.final();
596 TORRENT_ASSERT(!m_RC4_handler.get());
597 m_RC4_handler.reset(new RC4_handler (local_key, remote_key));
599 #ifdef TORRENT_VERBOSE_LOGGING
600 (*m_logger) << " computed RC4 keys\n";
601 #endif
604 void bt_peer_connection::send_buffer(char* buf, int size, int flags)
606 TORRENT_ASSERT(buf);
607 TORRENT_ASSERT(size > 0);
609 if (m_encrypted && m_rc4_encrypted)
610 m_RC4_handler->encrypt(buf, size);
612 peer_connection::send_buffer(buf, size, flags);
615 buffer::interval bt_peer_connection::allocate_send_buffer(int size)
617 if (m_encrypted && m_rc4_encrypted)
619 TORRENT_ASSERT(m_enc_send_buffer.left() == 0);
620 m_enc_send_buffer = peer_connection::allocate_send_buffer(size);
621 return m_enc_send_buffer;
623 else
625 buffer::interval i = peer_connection::allocate_send_buffer(size);
626 return i;
630 void bt_peer_connection::setup_send()
632 if (m_encrypted && m_rc4_encrypted && m_enc_send_buffer.left())
634 TORRENT_ASSERT(m_enc_send_buffer.begin);
635 TORRENT_ASSERT(m_enc_send_buffer.end);
637 m_RC4_handler->encrypt(m_enc_send_buffer.begin, m_enc_send_buffer.left());
638 m_enc_send_buffer.end = m_enc_send_buffer.begin;
640 peer_connection::setup_send();
643 int bt_peer_connection::get_syncoffset(char const* src, int src_size,
644 char const* target, int target_size) const
646 TORRENT_ASSERT(target_size >= src_size);
647 TORRENT_ASSERT(src_size > 0);
648 TORRENT_ASSERT(src);
649 TORRENT_ASSERT(target);
651 int traverse_limit = target_size - src_size;
653 // TODO: this could be optimized using knuth morris pratt
654 for (int i = 0; i < traverse_limit; ++i)
656 char const* target_ptr = target + i;
657 if (std::equal(src, src+src_size, target_ptr))
658 return i;
661 // // Partial sync
662 // for (int i = 0; i < target_size; ++i)
663 // {
664 // // first is iterator in src[] at which mismatch occurs
665 // // second is iterator in target[] at which mismatch occurs
666 // std::pair<const char*, const char*> ret;
667 // int src_sync_size;
668 // if (i > traverse_limit) // partial sync test
669 // {
670 // ret = std::mismatch(src, src + src_size - (i - traverse_limit), &target[i]);
671 // src_sync_size = ret.first - src;
672 // if (src_sync_size == (src_size - (i - traverse_limit)))
673 // return i;
674 // }
675 // else // complete sync test
676 // {
677 // ret = std::mismatch(src, src + src_size, &target[i]);
678 // src_sync_size = ret.first - src;
679 // if (src_sync_size == src_size)
680 // return i;
681 // }
682 // }
684 // no complete sync
685 return -1;
687 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
689 void bt_peer_connection::write_handshake()
691 INVARIANT_CHECK;
693 TORRENT_ASSERT(!m_sent_handshake);
694 #ifndef NDEBUG
695 m_sent_handshake = true;
696 #endif
698 boost::shared_ptr<torrent> t = associated_torrent().lock();
699 TORRENT_ASSERT(t);
701 // add handshake to the send buffer
702 const char version_string[] = "BitTorrent protocol";
703 const int string_len = sizeof(version_string)-1;
705 buffer::interval i = allocate_send_buffer(1 + string_len + 8 + 20 + 20);
706 if (i.begin == 0) return; // out of memory
707 // length of version string
708 *i.begin = string_len;
709 ++i.begin;
711 // version string itself
712 std::copy(
713 version_string
714 , version_string + string_len
715 , i.begin);
716 i.begin += string_len;
718 // 8 zeroes
719 std::fill(i.begin, i.begin + 8, 0);
721 #ifndef TORRENT_DISABLE_DHT
722 // indicate that we support the DHT messages
723 *(i.begin + 7) |= 0x01;
724 #endif
726 #ifndef TORRENT_DISABLE_EXTENSIONS
727 // we support extensions
728 *(i.begin + 5) |= 0x10;
729 #endif
731 // we support FAST extension
732 *(i.begin + 7) |= 0x04;
734 i.begin += 8;
736 // info hash
737 sha1_hash const& ih = t->torrent_file().info_hash();
738 std::copy(ih.begin(), ih.end(), i.begin);
739 i.begin += 20;
741 // peer id
742 std::copy(
743 m_ses.get_peer_id().begin()
744 , m_ses.get_peer_id().end()
745 , i.begin);
746 i.begin += 20;
747 TORRENT_ASSERT(i.begin == i.end);
749 #ifdef TORRENT_VERBOSE_LOGGING
750 (*m_logger) << time_now_string() << " ==> HANDSHAKE\n";
751 #endif
752 setup_send();
755 boost::optional<piece_block_progress> bt_peer_connection::downloading_piece_progress() const
757 boost::shared_ptr<torrent> t = associated_torrent().lock();
758 TORRENT_ASSERT(t);
760 buffer::const_interval recv_buffer = receive_buffer();
761 // are we currently receiving a 'piece' message?
762 if (m_state != read_packet
763 || recv_buffer.left() < 9
764 || recv_buffer[0] != msg_piece)
765 return boost::optional<piece_block_progress>();
767 const char* ptr = recv_buffer.begin + 1;
768 peer_request r;
769 r.piece = detail::read_int32(ptr);
770 r.start = detail::read_int32(ptr);
771 r.length = packet_size() - 9;
773 // is any of the piece message header data invalid?
774 if (!verify_piece(r))
775 return boost::optional<piece_block_progress>();
777 piece_block_progress p;
779 p.piece_index = r.piece;
780 p.block_index = r.start / t->block_size();
781 p.bytes_downloaded = recv_buffer.left() - 9;
782 p.full_block_bytes = r.length;
784 return boost::optional<piece_block_progress>(p);
788 // message handlers
790 // -----------------------------
791 // --------- KEEPALIVE ---------
792 // -----------------------------
794 void bt_peer_connection::on_keepalive()
796 INVARIANT_CHECK;
798 #ifdef TORRENT_VERBOSE_LOGGING
799 (*m_logger) << time_now_string() << " <== KEEPALIVE\n";
800 #endif
801 incoming_keepalive();
804 // -----------------------------
805 // ----------- CHOKE -----------
806 // -----------------------------
808 void bt_peer_connection::on_choke(int received)
810 INVARIANT_CHECK;
812 TORRENT_ASSERT(received > 0);
813 if (packet_size() != 1)
815 disconnect("'choke' message size != 1", 2);
816 return;
818 m_statistics.received_bytes(0, received);
819 if (!packet_finished()) return;
821 incoming_choke();
822 if (is_disconnecting()) return;
823 if (!m_supports_fast)
825 boost::shared_ptr<torrent> t = associated_torrent().lock();
826 TORRENT_ASSERT(t);
827 while (!download_queue().empty())
829 piece_block const& b = download_queue().front().block;
830 peer_request r;
831 r.piece = b.piece_index;
832 r.start = b.block_index * t->block_size();
833 r.length = t->block_size();
834 incoming_reject_request(r);
839 // -----------------------------
840 // ---------- UNCHOKE ----------
841 // -----------------------------
843 void bt_peer_connection::on_unchoke(int received)
845 INVARIANT_CHECK;
847 TORRENT_ASSERT(received > 0);
848 if (packet_size() != 1)
850 disconnect("'unchoke' message size != 1", 2);
851 return;
853 m_statistics.received_bytes(0, received);
854 if (!packet_finished()) return;
856 incoming_unchoke();
859 // -----------------------------
860 // -------- INTERESTED ---------
861 // -----------------------------
863 void bt_peer_connection::on_interested(int received)
865 INVARIANT_CHECK;
867 TORRENT_ASSERT(received > 0);
868 if (packet_size() != 1)
870 disconnect("'interested' message size != 1", 2);
871 return;
873 m_statistics.received_bytes(0, received);
874 if (!packet_finished()) return;
876 incoming_interested();
879 // -----------------------------
880 // ------ NOT INTERESTED -------
881 // -----------------------------
883 void bt_peer_connection::on_not_interested(int received)
885 INVARIANT_CHECK;
887 TORRENT_ASSERT(received > 0);
888 if (packet_size() != 1)
890 disconnect("'not interested' message size != 1", 2);
891 return;
893 m_statistics.received_bytes(0, received);
894 if (!packet_finished()) return;
896 incoming_not_interested();
899 // -----------------------------
900 // ----------- HAVE ------------
901 // -----------------------------
903 void bt_peer_connection::on_have(int received)
905 INVARIANT_CHECK;
907 TORRENT_ASSERT(received > 0);
908 if (packet_size() != 5)
910 disconnect("'have' message size != 5", 2);
911 return;
913 m_statistics.received_bytes(0, received);
914 if (!packet_finished()) return;
916 buffer::const_interval recv_buffer = receive_buffer();
918 const char* ptr = recv_buffer.begin + 1;
919 int index = detail::read_int32(ptr);
921 incoming_have(index);
924 // -----------------------------
925 // --------- BITFIELD ----------
926 // -----------------------------
928 void bt_peer_connection::on_bitfield(int received)
930 INVARIANT_CHECK;
932 TORRENT_ASSERT(received > 0);
934 boost::shared_ptr<torrent> t = associated_torrent().lock();
935 TORRENT_ASSERT(t);
937 // if we don't have the metedata, we cannot
938 // verify the bitfield size
939 if (t->valid_metadata()
940 && packet_size() - 1 != ((int)get_bitfield().size() + 7) / 8)
942 disconnect("bitfield with invalid size", 2);
943 return;
946 m_statistics.received_bytes(0, received);
947 if (!packet_finished()) return;
949 buffer::const_interval recv_buffer = receive_buffer();
951 bitfield bits;
952 bits.borrow_bytes((char*)recv_buffer.begin + 1
953 , t->valid_metadata()?get_bitfield().size():(packet_size()-1)*8);
955 incoming_bitfield(bits);
958 // -----------------------------
959 // ---------- REQUEST ----------
960 // -----------------------------
962 void bt_peer_connection::on_request(int received)
964 INVARIANT_CHECK;
966 TORRENT_ASSERT(received > 0);
967 if (packet_size() != 13)
969 disconnect("'request' message size != 13", 2);
970 return;
972 m_statistics.received_bytes(0, received);
973 if (!packet_finished()) return;
975 buffer::const_interval recv_buffer = receive_buffer();
977 peer_request r;
978 const char* ptr = recv_buffer.begin + 1;
979 r.piece = detail::read_int32(ptr);
980 r.start = detail::read_int32(ptr);
981 r.length = detail::read_int32(ptr);
983 incoming_request(r);
986 // -----------------------------
987 // ----------- PIECE -----------
988 // -----------------------------
990 void bt_peer_connection::on_piece(int received)
992 INVARIANT_CHECK;
994 TORRENT_ASSERT(received > 0);
996 buffer::const_interval recv_buffer = receive_buffer();
997 int recv_pos = recv_buffer.end - recv_buffer.begin;
999 if (recv_pos == 1)
1001 TORRENT_ASSERT(!has_disk_receive_buffer());
1002 if (!allocate_disk_receive_buffer(packet_size() - 9))
1003 return;
1005 TORRENT_ASSERT(has_disk_receive_buffer());
1007 // classify the received data as protocol chatter
1008 // or data payload for the statistics
1009 if (recv_pos <= 9)
1010 // only received protocol data
1011 m_statistics.received_bytes(0, received);
1012 else if (recv_pos - received >= 9)
1013 // only received payload data
1014 m_statistics.received_bytes(received, 0);
1015 else
1017 // received a bit of both
1018 TORRENT_ASSERT(recv_pos - received < 9);
1019 TORRENT_ASSERT(recv_pos > 9);
1020 TORRENT_ASSERT(9 - (recv_pos - received) <= 9);
1021 m_statistics.received_bytes(
1022 recv_pos - 9
1023 , 9 - (recv_pos - received));
1026 incoming_piece_fragment();
1027 if (is_disconnecting()) return;
1028 if (!packet_finished()) return;
1030 const char* ptr = recv_buffer.begin + 1;
1031 peer_request p;
1032 p.piece = detail::read_int32(ptr);
1033 p.start = detail::read_int32(ptr);
1034 p.length = packet_size() - 9;
1036 disk_buffer_holder holder(m_ses, release_disk_receive_buffer());
1037 incoming_piece(p, holder);
1040 // -----------------------------
1041 // ---------- CANCEL -----------
1042 // -----------------------------
1044 void bt_peer_connection::on_cancel(int received)
1046 INVARIANT_CHECK;
1048 TORRENT_ASSERT(received > 0);
1049 if (packet_size() != 13)
1051 disconnect("'cancel' message size != 13", 2);
1052 return;
1054 m_statistics.received_bytes(0, received);
1055 if (!packet_finished()) return;
1057 buffer::const_interval recv_buffer = receive_buffer();
1059 peer_request r;
1060 const char* ptr = recv_buffer.begin + 1;
1061 r.piece = detail::read_int32(ptr);
1062 r.start = detail::read_int32(ptr);
1063 r.length = detail::read_int32(ptr);
1065 incoming_cancel(r);
1068 // -----------------------------
1069 // --------- DHT PORT ----------
1070 // -----------------------------
1072 void bt_peer_connection::on_dht_port(int received)
1074 INVARIANT_CHECK;
1076 if (!m_supports_dht_port)
1078 disconnect("got 'dht_port' message from peer that doesn't support it", 2);
1079 return;
1082 TORRENT_ASSERT(received > 0);
1083 if (packet_size() != 3)
1085 disconnect("'dht_port' message size != 3", 2);
1086 return;
1088 m_statistics.received_bytes(0, received);
1089 if (!packet_finished()) return;
1091 buffer::const_interval recv_buffer = receive_buffer();
1093 const char* ptr = recv_buffer.begin + 1;
1094 int listen_port = detail::read_uint16(ptr);
1096 incoming_dht_port(listen_port);
1099 void bt_peer_connection::on_suggest_piece(int received)
1101 INVARIANT_CHECK;
1103 if (!m_supports_fast)
1105 disconnect("got 'suggest_piece' without FAST excension support", 2);
1106 return;
1109 m_statistics.received_bytes(0, received);
1110 if (!packet_finished()) return;
1112 buffer::const_interval recv_buffer = receive_buffer();
1114 const char* ptr = recv_buffer.begin + 1;
1115 int piece = detail::read_uint32(ptr);
1116 incoming_suggest(piece);
1119 void bt_peer_connection::on_have_all(int received)
1121 INVARIANT_CHECK;
1123 if (!m_supports_fast)
1125 disconnect("got 'have_all' without FAST extension support", 2);
1126 return;
1128 m_statistics.received_bytes(0, received);
1129 incoming_have_all();
1132 void bt_peer_connection::on_have_none(int received)
1134 INVARIANT_CHECK;
1136 if (!m_supports_fast)
1138 disconnect("got 'have_none' without FAST extension support", 2);
1139 return;
1141 m_statistics.received_bytes(0, received);
1142 incoming_have_none();
1145 void bt_peer_connection::on_reject_request(int received)
1147 INVARIANT_CHECK;
1149 if (!m_supports_fast)
1151 disconnect("got 'reject_request' without FAST extension support", 2);
1152 return;
1155 m_statistics.received_bytes(0, received);
1156 if (!packet_finished()) return;
1158 buffer::const_interval recv_buffer = receive_buffer();
1160 peer_request r;
1161 const char* ptr = recv_buffer.begin + 1;
1162 r.piece = detail::read_int32(ptr);
1163 r.start = detail::read_int32(ptr);
1164 r.length = detail::read_int32(ptr);
1166 incoming_reject_request(r);
1169 void bt_peer_connection::on_allowed_fast(int received)
1171 INVARIANT_CHECK;
1173 if (!m_supports_fast)
1175 disconnect("got 'allowed_fast' without FAST extension support", 2);
1176 return;
1179 m_statistics.received_bytes(0, received);
1180 if (!packet_finished()) return;
1181 buffer::const_interval recv_buffer = receive_buffer();
1182 const char* ptr = recv_buffer.begin + 1;
1183 int index = detail::read_int32(ptr);
1185 incoming_allowed_fast(index);
1188 // -----------------------------
1189 // --------- EXTENDED ----------
1190 // -----------------------------
1192 void bt_peer_connection::on_extended(int received)
1194 INVARIANT_CHECK;
1196 TORRENT_ASSERT(received > 0);
1197 m_statistics.received_bytes(0, received);
1198 if (packet_size() < 2)
1200 disconnect("'extended' message smaller than 2 bytes", 2);
1201 return;
1204 if (associated_torrent().expired())
1206 disconnect("'extended' message sent before proper handshake", 2);
1207 return;
1210 buffer::const_interval recv_buffer = receive_buffer();
1211 if (recv_buffer.left() < 2) return;
1213 TORRENT_ASSERT(*recv_buffer.begin == msg_extended);
1214 ++recv_buffer.begin;
1216 int extended_id = detail::read_uint8(recv_buffer.begin);
1218 if (extended_id == 0)
1220 on_extended_handshake();
1221 return;
1224 #ifndef TORRENT_DISABLE_EXTENSIONS
1225 for (extension_list_t::iterator i = m_extensions.begin()
1226 , end(m_extensions.end()); i != end; ++i)
1228 if ((*i)->on_extended(packet_size() - 2, extended_id
1229 , recv_buffer))
1230 return;
1232 #endif
1234 std::stringstream msg;
1235 msg << "unknown extended message id: " << extended_id;
1236 disconnect(msg.str().c_str(), 2);
1237 return;
1240 void bt_peer_connection::on_extended_handshake()
1242 if (!packet_finished()) return;
1244 boost::shared_ptr<torrent> t = associated_torrent().lock();
1245 TORRENT_ASSERT(t);
1247 buffer::const_interval recv_buffer = receive_buffer();
1249 lazy_entry root;
1250 lazy_bdecode(recv_buffer.begin + 2, recv_buffer.end, root);
1251 if (root.type() != lazy_entry::dict_t)
1253 #ifdef TORRENT_VERBOSE_LOGGING
1254 (*m_logger) << "invalid extended handshake\n";
1255 #endif
1256 return;
1259 #ifdef TORRENT_VERBOSE_LOGGING
1260 (*m_logger) << "<== EXTENDED HANDSHAKE: \n" << root;
1261 #endif
1263 #ifndef TORRENT_DISABLE_EXTENSIONS
1264 for (extension_list_t::iterator i = m_extensions.begin();
1265 !m_extensions.empty() && i != m_extensions.end();)
1267 // a false return value means that the extension
1268 // isn't supported by the other end. So, it is removed.
1269 if (!(*i)->on_extension_handshake(root))
1270 i = m_extensions.erase(i);
1271 else
1272 ++i;
1274 #endif
1276 // there is supposed to be a remote listen port
1277 int listen_port = root.dict_find_int_value("p");
1278 if (listen_port > 0 && peer_info_struct() != 0)
1280 t->get_policy().update_peer_port(listen_port
1281 , peer_info_struct(), peer_info::incoming);
1283 // there should be a version too
1284 // but where do we put that info?
1286 std::string client_info = root.dict_find_string_value("v");
1287 if (!client_info.empty()) m_client_version = client_info;
1289 int reqq = root.dict_find_int_value("reqq");
1290 if (reqq > 0) m_max_out_request_queue = reqq;
1292 if (root.dict_find_int_value("upload_only"))
1293 set_upload_only(true);
1295 std::string myip = root.dict_find_string_value("yourip");
1296 if (!myip.empty())
1298 // TODO: don't trust this blindly
1299 if (myip.size() == address_v4::bytes_type::static_size)
1301 address_v4::bytes_type bytes;
1302 std::copy(myip.begin(), myip.end(), bytes.begin());
1303 m_ses.set_external_address(address_v4(bytes));
1305 else if (myip.size() == address_v6::bytes_type::static_size)
1307 address_v6::bytes_type bytes;
1308 std::copy(myip.begin(), myip.end(), bytes.begin());
1309 m_ses.set_external_address(address_v6(bytes));
1313 // if we're finished and this peer is uploading only
1314 // disconnect it
1315 if (t->is_finished() && upload_only())
1316 disconnect("upload to upload connection, closing");
1319 bool bt_peer_connection::dispatch_message(int received)
1321 INVARIANT_CHECK;
1323 TORRENT_ASSERT(received > 0);
1325 // this means the connection has been closed already
1326 if (associated_torrent().expired()) return false;
1328 buffer::const_interval recv_buffer = receive_buffer();
1330 TORRENT_ASSERT(recv_buffer.left() >= 1);
1331 int packet_type = recv_buffer[0];
1332 if (packet_type < 0
1333 || packet_type >= num_supported_messages
1334 || m_message_handler[packet_type] == 0)
1336 #ifndef TORRENT_DISABLE_EXTENSIONS
1337 for (extension_list_t::iterator i = m_extensions.begin()
1338 , end(m_extensions.end()); i != end; ++i)
1340 if ((*i)->on_unknown_message(packet_size(), packet_type
1341 , buffer::const_interval(recv_buffer.begin+1
1342 , recv_buffer.end)))
1343 return packet_finished();
1345 #endif
1347 std::stringstream msg;
1348 msg << "unkown message id: " << packet_type << " size: " << packet_size();
1349 disconnect(msg.str().c_str(), 2);
1350 return packet_finished();
1353 TORRENT_ASSERT(m_message_handler[packet_type] != 0);
1355 // call the correct handler for this packet type
1356 (this->*m_message_handler[packet_type])(received);
1358 return packet_finished();
1361 void bt_peer_connection::write_keepalive()
1363 INVARIANT_CHECK;
1365 // Don't require the bitfield to have been sent at this point
1366 // the case where m_sent_bitfield may not be true is if the
1367 // torrent doesn't have any metadata, and a peer is timimg out.
1368 // then the keep-alive message will be sent before the bitfield
1369 // this is a violation to the original protocol, but necessary
1370 // for the metadata extension.
1371 TORRENT_ASSERT(m_sent_handshake);
1373 char msg[] = {0,0,0,0};
1374 send_buffer(msg, sizeof(msg));
1377 void bt_peer_connection::write_cancel(peer_request const& r)
1379 INVARIANT_CHECK;
1381 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1382 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
1384 char msg[17] = {0,0,0,13, msg_cancel};
1385 char* ptr = msg + 5;
1386 detail::write_int32(r.piece, ptr); // index
1387 detail::write_int32(r.start, ptr); // begin
1388 detail::write_int32(r.length, ptr); // length
1389 send_buffer(msg, sizeof(msg));
1391 if (!m_supports_fast)
1392 incoming_reject_request(r);
1395 void bt_peer_connection::write_request(peer_request const& r)
1397 INVARIANT_CHECK;
1399 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1400 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
1402 char msg[17] = {0,0,0,13, msg_request};
1403 char* ptr = msg + 5;
1405 detail::write_int32(r.piece, ptr); // index
1406 detail::write_int32(r.start, ptr); // begin
1407 detail::write_int32(r.length, ptr); // length
1408 send_buffer(msg, sizeof(msg), message_type_request);
1411 void bt_peer_connection::write_bitfield()
1413 INVARIANT_CHECK;
1415 boost::shared_ptr<torrent> t = associated_torrent().lock();
1416 TORRENT_ASSERT(t);
1417 TORRENT_ASSERT(m_sent_handshake && !m_sent_bitfield);
1418 TORRENT_ASSERT(t->valid_metadata());
1420 // in this case, have_all or have_none should be sent instead
1421 TORRENT_ASSERT(!m_supports_fast || !t->is_seed() || t->num_have() != 0);
1423 if (m_supports_fast && t->is_seed())
1425 write_have_all();
1426 send_allowed_set();
1427 return;
1429 else if (m_supports_fast && t->num_have() == 0)
1431 write_have_none();
1432 send_allowed_set();
1433 return;
1435 else if (t->num_have() == 0)
1437 // don't send a bitfield if we don't have any pieces
1438 #ifndef NDEBUG
1439 m_sent_bitfield = true;
1440 #endif
1441 return;
1444 int num_pieces = t->torrent_file().num_pieces();
1445 int lazy_pieces[50];
1446 int num_lazy_pieces = 0;
1447 int lazy_piece = 0;
1449 if (t->is_seed() && m_ses.settings().lazy_bitfields)
1451 num_lazy_pieces = (std::min)(50, num_pieces / 10);
1452 if (num_lazy_pieces < 1) num_lazy_pieces = 1;
1453 for (int i = 0; i < num_pieces; ++i)
1455 if (rand() % (num_pieces - i) >= num_lazy_pieces - lazy_piece) continue;
1456 lazy_pieces[lazy_piece++] = i;
1458 TORRENT_ASSERT(lazy_piece == num_lazy_pieces);
1459 lazy_piece = 0;
1462 const int packet_size = (num_pieces + 7) / 8 + 5;
1464 buffer::interval i = allocate_send_buffer(packet_size);
1465 if (i.begin == 0) return; // out of memory
1467 detail::write_int32(packet_size - 4, i.begin);
1468 detail::write_uint8(msg_bitfield, i.begin);
1470 if (t->is_seed())
1472 memset(i.begin, 0xff, packet_size - 5);
1474 else
1476 memset(i.begin, 0, packet_size - 5);
1477 piece_picker const& p = t->picker();
1478 int mask = 0x80;
1479 unsigned char* byte = (unsigned char*)i.begin;
1480 for (int i = 0; i < num_pieces; ++i)
1482 if (p.have_piece(i)) *byte |= mask;
1483 mask >>= 1;
1484 if (mask == 0)
1486 mask = 0x80;
1487 ++byte;
1491 for (int c = 0; c < num_lazy_pieces; ++c)
1492 i.begin[lazy_pieces[c] / 8] &= ~(0x80 >> (lazy_pieces[c] & 7));
1493 TORRENT_ASSERT(i.end - i.begin == (num_pieces + 7) / 8);
1495 #ifdef TORRENT_VERBOSE_LOGGING
1496 (*m_logger) << time_now_string() << " ==> BITFIELD ";
1498 std::stringstream bitfield_string;
1499 for (int k = 0; k < num_pieces; ++k)
1501 if (i.begin[k / 8] & (0x80 >> (k % 8))) bitfield_string << "1";
1502 else bitfield_string << "0";
1504 bitfield_string << "\n";
1505 (*m_logger) << bitfield_string.str();
1506 #endif
1507 #ifndef NDEBUG
1508 m_sent_bitfield = true;
1509 #endif
1511 if (num_lazy_pieces > 0)
1513 for (int i = 0; i < num_lazy_pieces; ++i)
1515 write_have(lazy_pieces[i]);
1516 #ifdef TORRENT_VERBOSE_LOGGING
1517 (*m_logger) << time_now_string()
1518 << " ==> HAVE [ piece: " << lazy_pieces[i] << "]\n";
1519 #endif
1523 if (m_supports_fast)
1524 send_allowed_set();
1525 setup_send();
1528 #ifndef TORRENT_DISABLE_EXTENSIONS
1529 void bt_peer_connection::write_extensions()
1531 INVARIANT_CHECK;
1533 #ifdef TORRENT_VERBOSE_LOGGING
1534 (*m_logger) << time_now_string() << " ==> EXTENSIONS\n";
1535 #endif
1536 TORRENT_ASSERT(m_supports_extensions);
1537 TORRENT_ASSERT(m_sent_handshake);
1539 entry handshake(entry::dictionary_t);
1540 entry extension_list(entry::dictionary_t);
1542 handshake["m"] = extension_list;
1544 // only send the port in case we bade the connection
1545 // on incoming connections the other end already knows
1546 // our listen port
1547 if (is_local()) handshake["p"] = m_ses.listen_port();
1548 handshake["v"] = m_ses.settings().user_agent;
1549 std::string remote_address;
1550 std::back_insert_iterator<std::string> out(remote_address);
1551 detail::write_address(remote().address(), out);
1552 handshake["yourip"] = remote_address;
1553 handshake["reqq"] = m_ses.settings().max_allowed_in_request_queue;
1554 boost::shared_ptr<torrent> t = associated_torrent().lock();
1555 TORRENT_ASSERT(t);
1556 if (t->is_finished()) handshake["upload_only"] = 1;
1558 tcp::endpoint ep = m_ses.get_ipv6_interface();
1559 if (ep != tcp::endpoint())
1561 std::string ipv6_address;
1562 std::back_insert_iterator<std::string> out(ipv6_address);
1563 detail::write_address(ep.address(), out);
1564 handshake["ipv6"] = ipv6_address;
1567 // loop backwards, to make the first extension be the last
1568 // to fill in the handshake (i.e. give the first extensions priority)
1569 for (extension_list_t::reverse_iterator i = m_extensions.rbegin()
1570 , end(m_extensions.rend()); i != end; ++i)
1572 (*i)->add_handshake(handshake);
1575 std::vector<char> msg;
1576 bencode(std::back_inserter(msg), handshake);
1578 // make room for message
1579 buffer::interval i = allocate_send_buffer(6 + msg.size());
1580 if (i.begin == 0) return; // out of memory
1582 // write the length of the message
1583 detail::write_int32((int)msg.size() + 2, i.begin);
1584 detail::write_uint8(msg_extended, i.begin);
1585 // signal handshake message
1586 detail::write_uint8(0, i.begin);
1588 std::copy(msg.begin(), msg.end(), i.begin);
1589 i.begin += msg.size();
1590 TORRENT_ASSERT(i.begin == i.end);
1592 #ifdef TORRENT_VERBOSE_LOGGING
1593 std::stringstream ext;
1594 handshake.print(ext);
1595 (*m_logger) << "==> EXTENDED HANDSHAKE: \n" << ext.str();
1596 #endif
1598 setup_send();
1600 #endif
1602 void bt_peer_connection::write_choke()
1604 INVARIANT_CHECK;
1606 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1608 if (is_choked()) return;
1609 char msg[] = {0,0,0,1,msg_choke};
1610 send_buffer(msg, sizeof(msg));
1613 void bt_peer_connection::write_unchoke()
1615 INVARIANT_CHECK;
1617 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1619 char msg[] = {0,0,0,1,msg_unchoke};
1620 send_buffer(msg, sizeof(msg));
1623 void bt_peer_connection::write_interested()
1625 INVARIANT_CHECK;
1627 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1629 char msg[] = {0,0,0,1,msg_interested};
1630 send_buffer(msg, sizeof(msg));
1633 void bt_peer_connection::write_not_interested()
1635 INVARIANT_CHECK;
1637 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1639 char msg[] = {0,0,0,1,msg_not_interested};
1640 send_buffer(msg, sizeof(msg));
1643 void bt_peer_connection::write_have(int index)
1645 INVARIANT_CHECK;
1646 TORRENT_ASSERT(associated_torrent().lock()->valid_metadata());
1647 TORRENT_ASSERT(index >= 0);
1648 TORRENT_ASSERT(index < associated_torrent().lock()->torrent_file().num_pieces());
1649 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1651 char msg[] = {0,0,0,5,msg_have,0,0,0,0};
1652 char* ptr = msg + 5;
1653 detail::write_int32(index, ptr);
1654 send_buffer(msg, sizeof(msg));
1657 void bt_peer_connection::write_piece(peer_request const& r, disk_buffer_holder& buffer)
1659 INVARIANT_CHECK;
1661 TORRENT_ASSERT(m_sent_handshake && m_sent_bitfield);
1663 boost::shared_ptr<torrent> t = associated_torrent().lock();
1664 TORRENT_ASSERT(t);
1666 char msg[4 + 1 + 4 + 4];
1667 char* ptr = msg;
1668 TORRENT_ASSERT(r.length <= 16 * 1024);
1669 detail::write_int32(r.length + 1 + 4 + 4, ptr);
1670 detail::write_uint8(msg_piece, ptr);
1671 detail::write_int32(r.piece, ptr);
1672 detail::write_int32(r.start, ptr);
1673 send_buffer(msg, sizeof(msg));
1675 append_send_buffer(buffer.get(), r.length
1676 , boost::bind(&session_impl::free_disk_buffer
1677 , boost::ref(m_ses), _1));
1678 buffer.release();
1680 m_payloads.push_back(range(send_buffer_size() - r.length, r.length));
1681 setup_send();
1684 namespace
1686 struct match_peer_id
1688 match_peer_id(peer_id const& id, peer_connection const* pc)
1689 : m_id(id), m_pc(pc)
1690 { TORRENT_ASSERT(pc); }
1692 bool operator()(std::pair<const address, policy::peer> const& p) const
1694 return p.second.connection != m_pc
1695 && p.second.connection
1696 && p.second.connection->pid() == m_id
1697 && !p.second.connection->pid().is_all_zeros()
1698 && p.second.addr == m_pc->remote().address();
1701 peer_id const& m_id;
1702 peer_connection const* m_pc;
1706 // --------------------------
1707 // RECEIVE DATA
1708 // --------------------------
1710 // throws exception when the client should be disconnected
1711 void bt_peer_connection::on_receive(error_code const& error
1712 , std::size_t bytes_transferred)
1714 INVARIANT_CHECK;
1716 if (error) return;
1717 boost::shared_ptr<torrent> t = associated_torrent().lock();
1719 if (in_handshake())
1720 m_statistics.received_bytes(0, bytes_transferred);
1722 #ifndef TORRENT_DISABLE_ENCRYPTION
1723 TORRENT_ASSERT(in_handshake() || !m_rc4_encrypted || m_encrypted);
1724 if (m_rc4_encrypted && m_encrypted)
1726 std::pair<buffer::interval, buffer::interval> wr_buf = wr_recv_buffers(bytes_transferred);
1727 m_RC4_handler->decrypt(wr_buf.first.begin, wr_buf.first.left());
1728 if (wr_buf.second.left()) m_RC4_handler->decrypt(wr_buf.second.begin, wr_buf.second.left());
1730 #endif
1732 buffer::const_interval recv_buffer = receive_buffer();
1734 #ifndef TORRENT_DISABLE_ENCRYPTION
1735 // m_state is set to read_pe_dhkey in initial state
1736 // (read_protocol_identifier) for incoming, or in constructor
1737 // for outgoing
1738 if (m_state == read_pe_dhkey)
1740 TORRENT_ASSERT(!m_encrypted);
1741 TORRENT_ASSERT(!m_rc4_encrypted);
1742 TORRENT_ASSERT(packet_size() == dh_key_len);
1743 TORRENT_ASSERT(recv_buffer == receive_buffer());
1745 if (!packet_finished()) return;
1747 // write our dh public key. m_dh_key_exchange is
1748 // initialized in write_pe1_2_dhkey()
1749 if (!is_local()) write_pe1_2_dhkey();
1750 if (is_disconnecting()) return;
1752 // read dh key, generate shared secret
1753 if (m_dh_key_exchange->compute_secret(recv_buffer.begin) == -1)
1755 disconnect("out of memory");
1756 return;
1759 #ifdef TORRENT_VERBOSE_LOGGING
1760 (*m_logger) << " received DH key\n";
1761 #endif
1763 // PadA/B can be a max of 512 bytes, and 20 bytes more for
1764 // the sync hash (if incoming), or 8 bytes more for the
1765 // encrypted verification constant (if outgoing). Instead
1766 // of requesting the maximum possible, request the maximum
1767 // possible to ensure we do not overshoot the standard
1768 // handshake.
1770 if (is_local())
1772 m_state = read_pe_syncvc;
1773 write_pe3_sync();
1775 // initial payload is the standard handshake, this is
1776 // always rc4 if sent here. m_rc4_encrypted is flagged
1777 // again according to peer selection.
1778 m_rc4_encrypted = true;
1779 m_encrypted = true;
1780 write_handshake();
1781 m_rc4_encrypted = false;
1782 m_encrypted = false;
1784 // vc,crypto_select,len(pad),pad, encrypt(handshake)
1785 // 8+4+2+0+handshake_len
1786 reset_recv_buffer(8+4+2+0+handshake_len);
1788 else
1790 // already written dh key
1791 m_state = read_pe_synchash;
1792 // synchash,skeyhash,vc,crypto_provide,len(pad),pad,encrypt(handshake)
1793 reset_recv_buffer(20+20+8+4+2+0+handshake_len);
1795 TORRENT_ASSERT(!packet_finished());
1796 return;
1799 // cannot fall through into
1800 if (m_state == read_pe_synchash)
1802 TORRENT_ASSERT(!m_encrypted);
1803 TORRENT_ASSERT(!m_rc4_encrypted);
1804 TORRENT_ASSERT(!is_local());
1805 TORRENT_ASSERT(recv_buffer == receive_buffer());
1807 if (recv_buffer.left() < 20)
1809 if (packet_finished())
1810 disconnect("sync hash not found", 2);
1811 return;
1814 if (!m_sync_hash.get())
1816 TORRENT_ASSERT(m_sync_bytes_read == 0);
1817 hasher h;
1819 // compute synchash (hash('req1',S))
1820 h.update("req1", 4);
1821 h.update(m_dh_key_exchange->get_secret(), dh_key_len);
1823 m_sync_hash.reset(new sha1_hash(h.final()));
1826 int syncoffset = get_syncoffset((char*)m_sync_hash->begin(), 20
1827 , recv_buffer.begin, recv_buffer.left());
1829 // No sync
1830 if (syncoffset == -1)
1832 std::size_t bytes_processed = recv_buffer.left() - 20;
1833 m_sync_bytes_read += bytes_processed;
1834 if (m_sync_bytes_read >= 512)
1836 disconnect("sync hash not found within 532 bytes", 2);
1837 return;
1840 cut_receive_buffer(bytes_processed, (std::min)(packet_size(), (512+20) - m_sync_bytes_read));
1842 TORRENT_ASSERT(!packet_finished());
1843 return;
1845 // found complete sync
1846 else
1848 std::size_t bytes_processed = syncoffset + 20;
1849 #ifdef TORRENT_VERBOSE_LOGGING
1850 (*m_logger) << " sync point (hash) found at offset "
1851 << m_sync_bytes_read + bytes_processed - 20 << "\n";
1852 #endif
1853 m_state = read_pe_skey_vc;
1854 // skey,vc - 28 bytes
1855 m_sync_hash.reset();
1856 cut_receive_buffer(bytes_processed, 28);
1860 if (m_state == read_pe_skey_vc)
1862 TORRENT_ASSERT(!m_encrypted);
1863 TORRENT_ASSERT(!m_rc4_encrypted);
1864 TORRENT_ASSERT(!is_local());
1865 TORRENT_ASSERT(packet_size() == 28);
1867 if (!packet_finished()) return;
1869 recv_buffer = receive_buffer();
1871 // only calls info_hash() on the torrent_handle's, which
1872 // never throws.
1873 session_impl::mutex_t::scoped_lock l(m_ses.m_mutex);
1875 std::vector<torrent_handle> active_torrents = m_ses.get_torrents();
1876 std::vector<torrent_handle>::const_iterator i;
1877 hasher h;
1878 sha1_hash skey_hash, obfs_hash;
1880 for (i = active_torrents.begin(); i != active_torrents.end(); ++i)
1882 torrent_handle const& t_h = *i; // TODO possible errors
1883 sha1_hash const& info_hash = t_h.info_hash();
1884 // TODO Does info_hash need to be checked for validity?
1886 h.reset();
1887 h.update("req2", 4);
1888 h.update((char*)info_hash.begin(), 20);
1890 skey_hash = h.final();
1892 h.reset();
1893 h.update("req3", 4);
1894 h.update(m_dh_key_exchange->get_secret(), dh_key_len);
1896 obfs_hash = h.final();
1897 obfs_hash ^= skey_hash;
1899 if (std::equal (recv_buffer.begin, recv_buffer.begin + 20,
1900 (char*)obfs_hash.begin()))
1902 if (!t)
1904 attach_to_torrent(info_hash);
1905 if (is_disconnecting()) return;
1907 t = associated_torrent().lock();
1908 TORRENT_ASSERT(t);
1911 init_pe_RC4_handler(m_dh_key_exchange->get_secret(), info_hash);
1912 #ifdef TORRENT_VERBOSE_LOGGING
1913 (*m_logger) << " stream key found, torrent located.\n";
1914 #endif
1915 continue; // TODO Check flow control with multiple torrents
1919 if (!m_RC4_handler.get())
1921 disconnect("invalid streamkey identifier (info hash) in encrypted handshake", 2);
1922 return;
1925 // verify constant
1926 buffer::interval wr_recv_buf = wr_recv_buffer();
1927 m_RC4_handler->decrypt(wr_recv_buf.begin + 20, 8);
1928 wr_recv_buf.begin += 28;
1930 const char sh_vc[] = {0,0,0,0, 0,0,0,0};
1931 if (!std::equal(sh_vc, sh_vc+8, recv_buffer.begin + 20))
1933 disconnect("unable to verify constant", 2);
1934 return;
1937 #ifdef TORRENT_VERBOSE_LOGGING
1938 (*m_logger) << " verification constant found\n";
1939 #endif
1940 m_state = read_pe_cryptofield;
1941 reset_recv_buffer(4 + 2);
1944 // cannot fall through into
1945 if (m_state == read_pe_syncvc)
1947 TORRENT_ASSERT(is_local());
1948 TORRENT_ASSERT(!m_encrypted);
1949 TORRENT_ASSERT(!m_rc4_encrypted);
1950 TORRENT_ASSERT(recv_buffer == receive_buffer());
1952 if (recv_buffer.left() < 8)
1954 if (packet_finished())
1955 disconnect("sync verification constant not found", 2);
1956 return;
1959 // generate the verification constant
1960 if (!m_sync_vc.get())
1962 TORRENT_ASSERT(m_sync_bytes_read == 0);
1964 m_sync_vc.reset (new char[8]);
1965 std::fill(m_sync_vc.get(), m_sync_vc.get() + 8, 0);
1966 m_RC4_handler->decrypt(m_sync_vc.get(), 8);
1969 TORRENT_ASSERT(m_sync_vc.get());
1970 int syncoffset = get_syncoffset(m_sync_vc.get(), 8
1971 , recv_buffer.begin, recv_buffer.left());
1973 // No sync
1974 if (syncoffset == -1)
1976 std::size_t bytes_processed = recv_buffer.left() - 8;
1977 m_sync_bytes_read += bytes_processed;
1978 if (m_sync_bytes_read >= 512)
1980 disconnect("sync verification constant not found within 520 bytes", 2);
1981 return;
1984 cut_receive_buffer(bytes_processed, (std::min)(packet_size(), (512+8) - m_sync_bytes_read));
1986 TORRENT_ASSERT(!packet_finished());
1987 return;
1989 // found complete sync
1990 else
1992 std::size_t bytes_processed = syncoffset + 8;
1993 #ifdef TORRENT_VERBOSE_LOGGING
1994 (*m_logger) << " sync point (verification constant) found at offset "
1995 << m_sync_bytes_read + bytes_processed - 8 << "\n";
1996 #endif
1997 cut_receive_buffer (bytes_processed, 4 + 2);
1999 // delete verification constant
2000 m_sync_vc.reset();
2001 m_state = read_pe_cryptofield;
2002 // fall through
2006 if (m_state == read_pe_cryptofield) // local/remote
2008 TORRENT_ASSERT(!m_encrypted);
2009 TORRENT_ASSERT(!m_rc4_encrypted);
2010 TORRENT_ASSERT(packet_size() == 4+2);
2012 if (!packet_finished()) return;
2014 buffer::interval wr_buf = wr_recv_buffer();
2015 m_RC4_handler->decrypt(wr_buf.begin, packet_size());
2017 recv_buffer = receive_buffer();
2019 int crypto_field = detail::read_int32(recv_buffer.begin);
2021 #ifdef TORRENT_VERBOSE_LOGGING
2022 if (!is_local())
2023 (*m_logger) << " crypto provide : [ ";
2024 else
2025 (*m_logger) << " crypto select : [ ";
2027 if (crypto_field & 0x01)
2028 (*m_logger) << "plaintext ";
2029 if (crypto_field & 0x02)
2030 (*m_logger) << "rc4 ";
2031 (*m_logger) << "]\n";
2032 #endif
2034 if (!is_local())
2036 int crypto_select = 0;
2037 // select a crypto method
2038 switch (m_ses.get_pe_settings().allowed_enc_level)
2040 case pe_settings::plaintext:
2041 if (!(crypto_field & 0x01))
2043 disconnect("plaintext not provided", 1);
2044 return;
2046 crypto_select = 0x01;
2047 break;
2048 case pe_settings::rc4:
2049 if (!(crypto_field & 0x02))
2051 disconnect("rc4 not provided", 1);
2052 return;
2054 crypto_select = 0x02;
2055 break;
2056 case pe_settings::both:
2057 if (m_ses.get_pe_settings().prefer_rc4)
2059 if (crypto_field & 0x02)
2060 crypto_select = 0x02;
2061 else if (crypto_field & 0x01)
2062 crypto_select = 0x01;
2064 else
2066 if (crypto_field & 0x01)
2067 crypto_select = 0x01;
2068 else if (crypto_field & 0x02)
2069 crypto_select = 0x02;
2071 if (!crypto_select)
2073 disconnect("rc4/plaintext not provided", 1);
2074 return;
2076 break;
2077 } // switch
2079 // write the pe4 step
2080 write_pe4_sync(crypto_select);
2082 else // is_local()
2084 // check if crypto select is valid
2085 pe_settings::enc_level const& allowed_enc_level = m_ses.get_pe_settings().allowed_enc_level;
2087 if (crypto_field == 0x02)
2089 if (allowed_enc_level == pe_settings::plaintext)
2091 disconnect("rc4 selected by peer when not provided", 2);
2092 return;
2094 m_rc4_encrypted = true;
2096 else if (crypto_field == 0x01)
2098 if (allowed_enc_level == pe_settings::rc4)
2100 disconnect("plaintext selected by peer when not provided", 2);
2101 return;
2103 m_rc4_encrypted = false;
2105 else
2107 disconnect("unsupported crypto method selected by peer", 2);
2108 return;
2112 int len_pad = detail::read_int16(recv_buffer.begin);
2113 if (len_pad < 0 || len_pad > 512)
2115 disconnect("invalid pad length", 2);
2116 return;
2119 m_state = read_pe_pad;
2120 if (!is_local())
2121 reset_recv_buffer(len_pad + 2); // len(IA) at the end of pad
2122 else
2124 if (len_pad == 0)
2126 m_encrypted = true;
2127 m_state = init_bt_handshake;
2129 else
2130 reset_recv_buffer(len_pad);
2134 if (m_state == read_pe_pad)
2136 TORRENT_ASSERT(!m_encrypted);
2137 if (!packet_finished()) return;
2139 int pad_size = is_local() ? packet_size() : packet_size() - 2;
2141 buffer::interval wr_buf = wr_recv_buffer();
2142 m_RC4_handler->decrypt(wr_buf.begin, packet_size());
2144 recv_buffer = receive_buffer();
2146 if (!is_local())
2148 recv_buffer.begin += pad_size;
2149 int len_ia = detail::read_int16(recv_buffer.begin);
2151 if (len_ia < 0)
2153 disconnect("invalid len_ia in handshake", 2);
2154 return;
2157 #ifdef TORRENT_VERBOSE_LOGGING
2158 (*m_logger) << " len(IA) : " << len_ia << "\n";
2159 #endif
2160 if (len_ia == 0)
2162 // everything after this is Encrypt2
2163 m_encrypted = true;
2164 m_state = init_bt_handshake;
2166 else
2168 m_state = read_pe_ia;
2169 reset_recv_buffer(len_ia);
2172 else // is_local()
2174 // everything that arrives after this is Encrypt2
2175 m_encrypted = true;
2176 m_state = init_bt_handshake;
2180 if (m_state == read_pe_ia)
2182 TORRENT_ASSERT(!is_local());
2183 TORRENT_ASSERT(!m_encrypted);
2185 if (!packet_finished()) return;
2187 // ia is always rc4, so decrypt it
2188 buffer::interval wr_buf = wr_recv_buffer();
2189 m_RC4_handler->decrypt(wr_buf.begin, packet_size());
2191 #ifdef TORRENT_VERBOSE_LOGGING
2192 (*m_logger) << " decrypted ia : " << packet_size() << " bytes\n";
2193 #endif
2195 if (!m_rc4_encrypted)
2197 m_RC4_handler.reset();
2198 #ifdef TORRENT_VERBOSE_LOGGING
2199 (*m_logger) << " destroyed rc4 keys\n";
2200 #endif
2203 // everything that arrives after this is Encrypt2
2204 m_encrypted = true;
2206 m_state = read_protocol_identifier;
2207 cut_receive_buffer(0, 20);
2210 if (m_state == init_bt_handshake)
2212 TORRENT_ASSERT(m_encrypted);
2214 // decrypt remaining received bytes
2215 if (m_rc4_encrypted)
2217 buffer::interval wr_buf = wr_recv_buffer();
2218 wr_buf.begin += packet_size();
2219 m_RC4_handler->decrypt(wr_buf.begin, wr_buf.left());
2220 #ifdef TORRENT_VERBOSE_LOGGING
2221 (*m_logger) << " decrypted remaining " << wr_buf.left() << " bytes\n";
2222 #endif
2224 else // !m_rc4_encrypted
2226 m_RC4_handler.reset();
2227 #ifdef TORRENT_VERBOSE_LOGGING
2228 (*m_logger) << " destroyed rc4 keys\n";
2229 #endif
2232 // payload stream, start with 20 handshake bytes
2233 m_state = read_protocol_identifier;
2234 reset_recv_buffer(20);
2236 // encrypted portion of handshake completed, toggle
2237 // peer_info pe_support flag back to true
2238 if (is_local() &&
2239 m_ses.get_pe_settings().out_enc_policy == pe_settings::enabled)
2241 policy::peer* pi = peer_info_struct();
2242 TORRENT_ASSERT(pi);
2244 pi->pe_support = true;
2248 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
2250 if (m_state == read_protocol_identifier)
2252 TORRENT_ASSERT(packet_size() == 20);
2254 if (!packet_finished()) return;
2255 recv_buffer = receive_buffer();
2257 int packet_size = recv_buffer[0];
2258 const char protocol_string[] = "BitTorrent protocol";
2260 if (packet_size != 19 ||
2261 !std::equal(recv_buffer.begin + 1, recv_buffer.begin + 19, protocol_string))
2263 #ifndef TORRENT_DISABLE_ENCRYPTION
2264 if (!is_local() && m_ses.get_pe_settings().in_enc_policy == pe_settings::disabled)
2266 disconnect("encrypted incoming connections disabled");
2267 return;
2270 // Don't attempt to perform an encrypted handshake
2271 // within an encrypted connection
2272 if (!m_encrypted && !is_local())
2274 #ifdef TORRENT_VERBOSE_LOGGING
2275 (*m_logger) << " attempting encrypted connection\n";
2276 #endif
2277 m_state = read_pe_dhkey;
2278 cut_receive_buffer(0, dh_key_len);
2279 TORRENT_ASSERT(!packet_finished());
2280 return;
2283 TORRENT_ASSERT((!is_local() && m_encrypted) || is_local());
2284 #endif // #ifndef TORRENT_DISABLE_ENCRYPTION
2285 disconnect("incorrect protocol identifier", 2);
2286 return;
2289 #ifndef TORRENT_DISABLE_ENCRYPTION
2290 TORRENT_ASSERT(m_state != read_pe_dhkey);
2292 if (!is_local() &&
2293 (m_ses.get_pe_settings().in_enc_policy == pe_settings::forced) &&
2294 !m_encrypted)
2296 disconnect("non encrypted incoming connections disabled");
2297 return;
2299 #endif
2301 #ifdef TORRENT_VERBOSE_LOGGING
2302 (*m_logger) << " BitTorrent protocol\n";
2303 #endif
2305 m_state = read_info_hash;
2306 reset_recv_buffer(28);
2309 // fall through
2310 if (m_state == read_info_hash)
2312 TORRENT_ASSERT(packet_size() == 28);
2314 if (!packet_finished()) return;
2315 recv_buffer = receive_buffer();
2318 #ifdef TORRENT_VERBOSE_LOGGING
2319 for (int i=0; i < 8; ++i)
2321 for (int j=0; j < 8; ++j)
2323 if (recv_buffer[i] & (0x80 >> j)) (*m_logger) << "1";
2324 else (*m_logger) << "0";
2327 (*m_logger) << "\n";
2328 if (recv_buffer[7] & 0x01)
2329 (*m_logger) << "supports DHT port message\n";
2330 if (recv_buffer[7] & 0x04)
2331 (*m_logger) << "supports FAST extensions\n";
2332 if (recv_buffer[5] & 0x10)
2333 (*m_logger) << "supports extensions protocol\n";
2334 #endif
2336 #ifndef DISABLE_EXTENSIONS
2337 std::memcpy(m_reserved_bits, recv_buffer.begin, 20);
2338 if ((recv_buffer[5] & 0x10))
2339 m_supports_extensions = true;
2340 #endif
2341 if (recv_buffer[7] & 0x01)
2342 m_supports_dht_port = true;
2344 if (recv_buffer[7] & 0x04)
2345 m_supports_fast = true;
2347 // ok, now we have got enough of the handshake. Is this connection
2348 // attached to a torrent?
2349 if (!t)
2351 // now, we have to see if there's a torrent with the
2352 // info_hash we got from the peer
2353 sha1_hash info_hash;
2354 std::copy(recv_buffer.begin + 8, recv_buffer.begin + 28
2355 , (char*)info_hash.begin());
2357 attach_to_torrent(info_hash);
2358 if (is_disconnecting()) return;
2360 else
2362 // verify info hash
2363 if (!std::equal(recv_buffer.begin + 8, recv_buffer.begin + 28
2364 , (const char*)t->torrent_file().info_hash().begin()))
2366 #ifdef TORRENT_VERBOSE_LOGGING
2367 (*m_logger) << " received invalid info_hash\n";
2368 #endif
2369 disconnect("invalid info-hash in handshake", 2);
2370 return;
2373 #ifdef TORRENT_VERBOSE_LOGGING
2374 (*m_logger) << " info_hash received\n";
2375 #endif
2378 t = associated_torrent().lock();
2379 TORRENT_ASSERT(t);
2381 // if this is a local connection, we have already
2382 // sent the handshake
2383 if (!is_local()) write_handshake();
2384 // if (t->valid_metadata())
2385 // write_bitfield();
2387 if (is_disconnecting()) return;
2389 TORRENT_ASSERT(t->get_policy().has_connection(this));
2391 m_state = read_peer_id;
2392 reset_recv_buffer(20);
2395 // fall through
2396 if (m_state == read_peer_id)
2398 if (!t)
2400 TORRENT_ASSERT(!packet_finished()); // TODO
2401 return;
2403 TORRENT_ASSERT(packet_size() == 20);
2405 if (!packet_finished()) return;
2406 recv_buffer = receive_buffer();
2408 #ifdef TORRENT_VERBOSE_LOGGING
2410 peer_id tmp;
2411 std::copy(recv_buffer.begin, recv_buffer.begin + 20, (char*)tmp.begin());
2412 std::stringstream s;
2413 s << "received peer_id: " << tmp << " client: " << identify_client(tmp) << "\n";
2414 s << "as ascii: ";
2415 for (peer_id::iterator i = tmp.begin(); i != tmp.end(); ++i)
2417 if (std::isprint(*i)) s << *i;
2418 else s << ".";
2420 s << "\n";
2421 (*m_logger) << s.str();
2423 #endif
2424 peer_id pid;
2425 std::copy(recv_buffer.begin, recv_buffer.begin + 20, (char*)pid.begin());
2426 set_pid(pid);
2428 if (t->settings().allow_multiple_connections_per_ip)
2430 // now, let's see if this connection should be closed
2431 policy& p = t->get_policy();
2432 policy::iterator i = std::find_if(p.begin_peer(), p.end_peer()
2433 , match_peer_id(pid, this));
2434 if (i != p.end_peer())
2436 TORRENT_ASSERT(i->second.connection->pid() == pid);
2437 // we found another connection with the same peer-id
2438 // which connection should be closed in order to be
2439 // sure that the other end closes the same connection?
2440 // the peer with greatest peer-id is the one allowed to
2441 // initiate connections. So, if our peer-id is greater than
2442 // the others, we should close the incoming connection,
2443 // if not, we should close the outgoing one.
2444 if (pid < m_ses.get_peer_id() && is_local())
2446 i->second.connection->disconnect("duplicate peer-id, connection closed");
2448 else
2450 disconnect("duplicate peer-id, connection closed");
2451 return;
2456 if (pid == m_ses.get_peer_id())
2458 disconnect("closing connection to ourself", 1);
2459 return;
2462 m_client_version = identify_client(pid);
2463 boost::optional<fingerprint> f = client_fingerprint(pid);
2464 if (f && std::equal(f->name, f->name + 2, "BC"))
2466 // if this is a bitcomet client, lower the request queue size limit
2467 if (m_max_out_request_queue > 50) m_max_out_request_queue = 50;
2470 // disconnect if the peer has the same peer-id as ourself
2471 // since it most likely is ourself then
2472 if (pid == m_ses.get_peer_id())
2474 disconnect("closing connection to ourself", 1);
2475 return;
2478 #ifndef TORRENT_DISABLE_EXTENSIONS
2479 for (extension_list_t::iterator i = m_extensions.begin()
2480 , end(m_extensions.end()); i != end;)
2482 if (!(*i)->on_handshake(m_reserved_bits))
2484 i = m_extensions.erase(i);
2486 else
2488 ++i;
2491 if (is_disconnecting()) return;
2493 if (m_supports_extensions) write_extensions();
2494 #endif
2496 #ifdef TORRENT_VERBOSE_LOGGING
2497 (*m_logger) << time_now_string() << " <== HANDSHAKE\n";
2498 #endif
2499 // consider this a successful connection, reset the failcount
2500 if (peer_info_struct()) peer_info_struct()->failcount = 0;
2502 #ifndef TORRENT_DISABLE_ENCRYPTION
2503 // Toggle pe_support back to false if this is a
2504 // standard successful connection
2505 if (is_local() && !m_encrypted &&
2506 m_ses.get_pe_settings().out_enc_policy == pe_settings::enabled)
2508 policy::peer* pi = peer_info_struct();
2509 TORRENT_ASSERT(pi);
2511 pi->pe_support = false;
2513 #endif
2515 m_state = read_packet_size;
2516 reset_recv_buffer(5);
2517 if (t->valid_metadata())
2519 write_bitfield();
2520 #ifndef TORRENT_DISABLE_DHT
2521 if (m_supports_dht_port && m_ses.m_dht)
2522 write_dht_port(m_ses.get_dht_settings().service_port);
2523 #endif
2526 TORRENT_ASSERT(!packet_finished());
2527 return;
2530 // cannot fall through into
2531 if (m_state == read_packet_size)
2533 // Make sure this is not fallen though into
2534 TORRENT_ASSERT(recv_buffer == receive_buffer());
2536 if (!t) return;
2537 m_statistics.received_bytes(0, bytes_transferred);
2539 if (recv_buffer.left() < 4) return;
2541 const char* ptr = recv_buffer.begin;
2542 int packet_size = detail::read_int32(ptr);
2544 // don't accept packets larger than 1 MB
2545 if (packet_size > 1024*1024 || packet_size < 0)
2547 // packet too large
2548 std::stringstream msg;
2549 msg << "packet > 1 MB (" << (unsigned int)packet_size << " bytes)";
2550 disconnect(msg.str().c_str(), 2);
2551 return;
2554 if (packet_size == 0)
2556 incoming_keepalive();
2557 if (is_disconnecting()) return;
2558 // keepalive message
2559 m_state = read_packet_size;
2560 cut_receive_buffer(4, 4);
2561 return;
2563 else
2565 if (recv_buffer.left() < 5) return;
2567 m_state = read_packet;
2568 cut_receive_buffer(4, packet_size);
2569 bytes_transferred = 1;
2570 recv_buffer = receive_buffer();
2571 TORRENT_ASSERT(recv_buffer.left() == 1);
2575 if (m_state == read_packet)
2577 TORRENT_ASSERT(recv_buffer == receive_buffer());
2578 if (!t) return;
2579 if (dispatch_message(bytes_transferred))
2581 m_state = read_packet_size;
2582 reset_recv_buffer(5);
2584 TORRENT_ASSERT(!packet_finished());
2585 return;
2588 TORRENT_ASSERT(!packet_finished());
2591 // --------------------------
2592 // SEND DATA
2593 // --------------------------
2595 void bt_peer_connection::on_sent(error_code const& error
2596 , std::size_t bytes_transferred)
2598 INVARIANT_CHECK;
2600 if (error) return;
2602 // manage the payload markers
2603 int amount_payload = 0;
2604 if (!m_payloads.empty())
2606 for (std::deque<range>::iterator i = m_payloads.begin();
2607 i != m_payloads.end(); ++i)
2609 i->start -= bytes_transferred;
2610 if (i->start < 0)
2612 if (i->start + i->length <= 0)
2614 amount_payload += i->length;
2616 else
2618 amount_payload += -i->start;
2619 i->length -= -i->start;
2620 i->start = 0;
2626 // TODO: move the erasing into the loop above
2627 // remove all payload ranges that has been sent
2628 m_payloads.erase(
2629 std::remove_if(m_payloads.begin(), m_payloads.end(), range_below_zero)
2630 , m_payloads.end());
2632 TORRENT_ASSERT(amount_payload <= (int)bytes_transferred);
2633 m_statistics.sent_bytes(amount_payload, bytes_transferred - amount_payload);
2636 #ifndef NDEBUG
2637 void bt_peer_connection::check_invariant() const
2639 #ifndef TORRENT_DISABLE_ENCRYPTION
2640 TORRENT_ASSERT( (bool(m_state != read_pe_dhkey) || m_dh_key_exchange.get())
2641 || !is_local());
2643 TORRENT_ASSERT(!m_rc4_encrypted || m_RC4_handler.get());
2644 #endif
2645 if (!in_handshake())
2647 TORRENT_ASSERT(m_sent_handshake);
2650 if (!m_in_constructor)
2651 peer_connection::check_invariant();
2653 if (!m_payloads.empty())
2655 for (std::deque<range>::const_iterator i = m_payloads.begin();
2656 i != m_payloads.end() - 1; ++i)
2658 TORRENT_ASSERT(i->start + i->length <= (i+1)->start);
2662 #endif