1 // libTorrent - BitTorrent library
2 // Copyright (C) 2005-2011, Jari Sundell
3 //
4 // This program is free software; you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation; either version 2 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 //
18 // In addition, as a special exception, the copyright holders give
19 // permission to link the code of portions of this program with the
20 // OpenSSL library under certain conditions as described in each
21 // individual source file, and distribute linked combinations
22 // including the two.
23 //
24 // You must obey the GNU General Public License in all respects for
25 // all of the code used other than OpenSSL.  If you modify file(s)
26 // with this exception, you may extend this exception to your version
27 // of the file(s), but you are not obligated to do so.  If you do not
28 // wish to do so, delete this exception statement from your version.
29 // If you delete this exception statement from all source files in the
30 // program, then also delete it here.
31 //
32 // Contact:  Jari Sundell <jaris@ifi.uio.no>
33 //
34 //           Skomakerveien 33
35 //           3185 Skoppum, NORWAY
36 
37 #include "config.h"
38 
39 #include <stdio.h>
40 
41 #include "download/download_main.h"
42 #include "net/throttle_list.h"
43 #include "torrent/dht_manager.h"
44 #include "torrent/download_info.h"
45 #include "torrent/exceptions.h"
46 #include "torrent/error.h"
47 #include "torrent/poll.h"
48 #include "torrent/throttle.h"
49 #include "utils/diffie_hellman.h"
50 
51 #include "globals.h"
52 #include "manager.h"
53 
54 #include "extensions.h"
55 #include "handshake.h"
56 #include "handshake_manager.h"
57 
58 namespace torrent {
59 
60 const char* Handshake::m_protocol = "BitTorrent protocol";
61 
62 class handshake_error : public network_error {
63 public:
handshake_error(int type,int error)64   handshake_error(int type, int error) : m_type(type), m_error(error) {}
65 
what() const66   virtual const char* what() const throw()  { return "Handshake error"; }
type() const67   virtual int         type() const throw()  { return m_type; }
error() const68   virtual int         error() const throw() { return m_error; }
69 
70 private:
71   int     m_type;
72   int     m_error;
73 };
74 
75 class handshake_succeeded : public network_error {
76 public:
handshake_succeeded()77   handshake_succeeded() {}
78 };
79 
Handshake(SocketFd fd,HandshakeManager * m,int encryptionOptions)80 Handshake::Handshake(SocketFd fd, HandshakeManager* m, int encryptionOptions) :
81   m_state(INACTIVE),
82 
83   m_manager(m),
84   m_peerInfo(NULL),
85   m_download(NULL),
86 
87   // Use global throttles until we know which download it is.
88   m_uploadThrottle(manager->upload_throttle()->throttle_list()),
89   m_downloadThrottle(manager->download_throttle()->throttle_list()),
90 
91   m_readDone(false),
92   m_writeDone(false),
93 
94   m_encryption(encryptionOptions),
95   m_extensions(m->default_extensions()) {
96 
97   set_fd(fd);
98 
99   m_readBuffer.reset();
100   m_writeBuffer.reset();
101 
102   m_taskTimeout.clear_time();
103   m_taskTimeout.slot() = std::bind(&HandshakeManager::receive_timeout, m, this);
104 }
105 
~Handshake()106 Handshake::~Handshake() {
107   if (m_taskTimeout.is_queued())
108     throw internal_error("Handshake m_taskTimeout bork bork bork.");
109 
110   if (get_fd().is_valid())
111     throw internal_error("Handshake dtor called but m_fd is still open.");
112 
113   m_encryption.cleanup();
114 }
115 
116 void
initialize_incoming(const rak::socket_address & sa)117 Handshake::initialize_incoming(const rak::socket_address& sa) {
118   m_incoming = true;
119   m_address = sa;
120 
121   if (m_encryption.options() & (ConnectionManager::encryption_allow_incoming | ConnectionManager::encryption_require))
122     m_state = READ_ENC_KEY;
123   else
124     m_state = READ_INFO;
125 
126   manager->poll()->open(this);
127   manager->poll()->insert_read(this);
128   manager->poll()->insert_error(this);
129 
130   // Use lower timeout here.
131   priority_queue_insert(&taskScheduler, &m_taskTimeout, (cachedTime + rak::timer::from_seconds(60)).round_seconds());
132 }
133 
134 void
initialize_outgoing(const rak::socket_address & sa,DownloadMain * d,PeerInfo * peerInfo)135 Handshake::initialize_outgoing(const rak::socket_address& sa, DownloadMain* d, PeerInfo* peerInfo) {
136   m_download = d;
137 
138   m_peerInfo = peerInfo;
139   m_peerInfo->set_flags(PeerInfo::flag_handshake);
140 
141   m_incoming = false;
142   m_address = sa;
143 
144   std::make_pair(m_uploadThrottle, m_downloadThrottle) = m_download->throttles(m_address.c_sockaddr());
145 
146   m_state = CONNECTING;
147 
148   manager->poll()->open(this);
149   manager->poll()->insert_write(this);
150   manager->poll()->insert_error(this);
151 
152   priority_queue_insert(&taskScheduler, &m_taskTimeout, (cachedTime + rak::timer::from_seconds(60)).round_seconds());
153 }
154 
155 void
deactivate_connection()156 Handshake::deactivate_connection() {
157   if (!get_fd().is_valid())
158     throw internal_error("Handshake::deactivate_connection called but m_fd is not open.");
159 
160   m_state = INACTIVE;
161 
162   priority_queue_erase(&taskScheduler, &m_taskTimeout);
163 
164   manager->poll()->remove_read(this);
165   manager->poll()->remove_write(this);
166   manager->poll()->remove_error(this);
167   manager->poll()->close(this);
168 }
169 
170 void
release_connection()171 Handshake::release_connection() {
172   if (!get_fd().is_valid())
173     throw internal_error("Handshake::release_connection called but m_fd is not open.");
174 
175   m_peerInfo->unset_flags(PeerInfo::flag_handshake);
176   m_peerInfo = NULL;
177 
178   get_fd().clear();
179 }
180 
181 void
destroy_connection()182 Handshake::destroy_connection() {
183   if (!get_fd().is_valid())
184     throw internal_error("Handshake::destroy_connection called but m_fd is not open.");
185 
186   manager->connection_manager()->dec_socket_count();
187 
188   get_fd().close();
189   get_fd().clear();
190 
191   if (m_peerInfo == NULL)
192     return;
193 
194   m_download->peer_list()->disconnected(m_peerInfo, 0);
195 
196   m_peerInfo->unset_flags(PeerInfo::flag_handshake);
197   m_peerInfo = NULL;
198 
199   if (!m_extensions->is_default()) {
200     m_extensions->cleanup();
201     delete m_extensions;
202   }
203 }
204 
205 int
retry_options()206 Handshake::retry_options() {
207   uint32_t options = m_encryption.options() & ~ConnectionManager::encryption_enable_retry;
208 
209   if (m_encryption.retry() == HandshakeEncryption::RETRY_PLAIN)
210     options &= ~ConnectionManager::encryption_try_outgoing;
211   else if (m_encryption.retry() == HandshakeEncryption::RETRY_ENCRYPTED)
212     options |= ConnectionManager::encryption_try_outgoing;
213   else
214     throw internal_error("Invalid retry type.");
215 
216   return options;
217 }
218 
219 inline uint32_t
read_unthrottled(void * buf,uint32_t length)220 Handshake::read_unthrottled(void* buf, uint32_t length) {
221   return m_downloadThrottle->node_used_unthrottled(read_stream_throws(buf, length));
222 }
223 
224 inline uint32_t
write_unthrottled(const void * buf,uint32_t length)225 Handshake::write_unthrottled(const void* buf, uint32_t length) {
226   return m_uploadThrottle->node_used_unthrottled(write_stream_throws(buf, length));
227 }
228 
229 // Handshake::read_proxy_connect()
230 // Entry: 0, 0
231 // * 0, [0, 508>
232 bool
read_proxy_connect()233 Handshake::read_proxy_connect() {
234   // Being greedy for now.
235   m_readBuffer.move_end(read_unthrottled(m_readBuffer.end(), 512));
236 
237   const char* pattern = "\r\n\r\n";
238   const unsigned int patternLength = 4;
239 
240   if (m_readBuffer.remaining() < patternLength)
241     return false;
242 
243   Buffer::iterator itr = std::search(m_readBuffer.begin(), m_readBuffer.end(),
244                                      (uint8_t*)pattern, (uint8_t*)pattern + patternLength);
245 
246   m_readBuffer.set_position_itr(itr != m_readBuffer.end() ? (itr + patternLength) : (itr - patternLength));
247   m_readBuffer.move_unused();
248 
249   return itr != m_readBuffer.end();
250 }
251 
252 // Handshake::read_encryption_key()
253 // Entry: * 0, [0, 508>
254 // IU 20, [20, enc_pad_read_size>
255 // *E 96, [96, enc_pad_read_size>
256 bool
read_encryption_key()257 Handshake::read_encryption_key() {
258   if (m_incoming) {
259     if (m_readBuffer.remaining() < 20)
260       m_readBuffer.move_end(read_unthrottled(m_readBuffer.end(), 20 - m_readBuffer.remaining()));
261 
262     if (m_readBuffer.remaining() < 20)
263       return false;
264 
265     if (m_readBuffer.peek_8() == 19 && std::memcmp(m_readBuffer.position() + 1, m_protocol, 19) == 0) {
266       // got unencrypted BT handshake
267       if (m_encryption.options() & ConnectionManager::encryption_require)
268         throw handshake_error(ConnectionManager::handshake_dropped, e_handshake_unencrypted_rejected);
269 
270       m_state = READ_INFO;
271       return true;
272     }
273   }
274 
275   // Read as much of key, pad and sync string as we can; this is safe
276   // because peer can't send anything beyond the initial BT handshake
277   // because it doesn't know our encryption choice yet.
278   if (m_readBuffer.remaining() < enc_pad_read_size)
279     m_readBuffer.move_end(read_unthrottled(m_readBuffer.end(), enc_pad_read_size - m_readBuffer.remaining()));
280 
281   // but we need at least the key at this point
282   if (m_readBuffer.size_end() < 96)
283     return false;
284 
285   // If the handshake fails after this, it wasn't because the peer
286   // doesn't like encrypted connections, so don't retry unencrypted.
287   m_encryption.set_retry(HandshakeEncryption::RETRY_NONE);
288 
289   if (m_incoming)
290     prepare_key_plus_pad();
291 
292   if(!m_encryption.key()->compute_secret(m_readBuffer.position(), 96))
293     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_encryption);
294   m_readBuffer.consume(96);
295 
296   // Determine the synchronisation string.
297   if (m_incoming)
298     m_encryption.hash_req1_to_sync();
299   else
300     m_encryption.encrypt_vc_to_sync(m_download->info()->hash().c_str());
301 
302   // also put as much as we can write so far in the buffer
303   if (!m_incoming)
304     prepare_enc_negotiation();
305 
306   m_state = READ_ENC_SYNC;
307   return true;
308 }
309 
310 // Handshake::read_encryption_sync()
311 // *E 96, [96, enc_pad_read_size>
312 bool
read_encryption_sync()313 Handshake::read_encryption_sync() {
314   // Check if we've read the sync string already in the previous
315   // state. This is very likely and avoids an unneeded read.
316   Buffer::iterator itr = std::search(m_readBuffer.position(), m_readBuffer.end(),
317                                      (uint8_t*)m_encryption.sync(), (uint8_t*)m_encryption.sync() + m_encryption.sync_length());
318 
319   if (itr == m_readBuffer.end()) {
320     // Otherwise read as many bytes as possible until we find the sync
321     // string.
322     int toRead = enc_pad_size + m_encryption.sync_length() - m_readBuffer.remaining();
323 
324     if (toRead <= 0)
325       throw handshake_error(ConnectionManager::handshake_failed, e_handshake_encryption_sync_failed);
326 
327     m_readBuffer.move_end(read_unthrottled(m_readBuffer.end(), toRead));
328 
329     itr = std::search(m_readBuffer.position(), m_readBuffer.end(),
330                       (uint8_t*)m_encryption.sync(), (uint8_t*)m_encryption.sync() + m_encryption.sync_length());
331 
332     if (itr == m_readBuffer.end())
333       return false;
334   }
335 
336   if (m_incoming) {
337     // We've found HASH('req1' + S), skip that and go on reading the
338     // SKEY hash.
339     m_readBuffer.consume(std::distance(m_readBuffer.position(), itr) + 20);
340     m_state = READ_ENC_SKEY;
341 
342   } else {
343     m_readBuffer.consume(std::distance(m_readBuffer.position(), itr));
344     m_state = READ_ENC_NEGOT;
345   }
346 
347   return true;
348 }
349 
350 bool
read_encryption_skey()351 Handshake::read_encryption_skey() {
352   if (!fill_read_buffer(20))
353     return false;
354 
355   m_encryption.deobfuscate_hash((char*)m_readBuffer.position());
356   m_download = m_manager->download_info_obfuscated((char*)m_readBuffer.position());
357   m_readBuffer.consume(20);
358 
359   validate_download();
360 
361   std::make_pair(m_uploadThrottle, m_downloadThrottle) = m_download->throttles(m_address.c_sockaddr());
362 
363   m_encryption.initialize_encrypt(m_download->info()->hash().c_str(), m_incoming);
364   m_encryption.initialize_decrypt(m_download->info()->hash().c_str(), m_incoming);
365 
366   m_encryption.info()->decrypt(m_readBuffer.position(), m_readBuffer.remaining());
367 
368   HandshakeEncryption::copy_vc(m_writeBuffer.end());
369   m_encryption.info()->encrypt(m_writeBuffer.end(), HandshakeEncryption::vc_length);
370   m_writeBuffer.move_end(HandshakeEncryption::vc_length);
371 
372   m_state = READ_ENC_NEGOT;
373   return true;
374 }
375 
376 bool
read_encryption_negotiation()377 Handshake::read_encryption_negotiation() {
378   if (!fill_read_buffer(enc_negotiation_size))
379     return false;
380 
381   if (!m_incoming) {
382     // Start decrypting, but don't decrypt beyond the initial
383     // encrypted handshake and later the pad because we may have read
384     // too much data which may be unencrypted if the peer chose that
385     // option.
386     m_encryption.initialize_decrypt(m_download->info()->hash().c_str(), m_incoming);
387     m_encryption.info()->decrypt(m_readBuffer.position(), enc_negotiation_size);
388   }
389 
390   if (!HandshakeEncryption::compare_vc(m_readBuffer.position()))
391     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
392 
393   m_readBuffer.consume(HandshakeEncryption::vc_length);
394 
395   m_encryption.set_crypto(m_readBuffer.read_32());
396   m_readPos = m_readBuffer.read_16();       // length of padC/padD
397 
398   if (m_readPos > enc_pad_size)
399     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
400 
401   // choose one of the offered encryptions, or check the chosen one is valid
402   if (m_incoming) {
403     if ((m_encryption.options() & ConnectionManager::encryption_prefer_plaintext) && m_encryption.has_crypto_plain()) {
404       m_encryption.set_crypto(HandshakeEncryption::crypto_plain);
405 
406     } else if ((m_encryption.options() & ConnectionManager::encryption_require_RC4) && !m_encryption.has_crypto_rc4()) {
407       throw handshake_error(ConnectionManager::handshake_dropped, e_handshake_unencrypted_rejected);
408 
409     } else if (m_encryption.has_crypto_rc4()) {
410       m_encryption.set_crypto(HandshakeEncryption::crypto_rc4);
411 
412     } else if (m_encryption.has_crypto_plain()) {
413       m_encryption.set_crypto(HandshakeEncryption::crypto_plain);
414 
415     } else {
416       throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_encryption);
417     }
418 
419     // at this point we can also write the rest of our negotiation reply
420     m_writeBuffer.write_32(m_encryption.crypto());
421     m_writeBuffer.write_16(0);
422     m_encryption.info()->encrypt(m_writeBuffer.end() - 4 - 2, 4 + 2);
423 
424   } else {
425     if (m_encryption.crypto() != HandshakeEncryption::crypto_rc4 && m_encryption.crypto() != HandshakeEncryption::crypto_plain)
426       throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_encryption);
427 
428     if ((m_encryption.options() & ConnectionManager::encryption_require_RC4) && (m_encryption.crypto() != HandshakeEncryption::crypto_rc4))
429       throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_encryption);
430   }
431 
432   if (!m_incoming) {
433     // decrypt appropriate part of buffer: only pad or all
434     if (m_encryption.crypto() == HandshakeEncryption::crypto_plain)
435       m_encryption.info()->decrypt(m_readBuffer.position(), std::min<uint32_t>(m_readPos, m_readBuffer.remaining()));
436     else
437       m_encryption.info()->decrypt(m_readBuffer.position(), m_readBuffer.remaining());
438   }
439 
440   // next, skip padC/padD
441   m_state = READ_ENC_PAD;
442   return true;
443 }
444 
445 bool
read_negotiation_reply()446 Handshake::read_negotiation_reply() {
447   if (!m_incoming) {
448     if (m_encryption.crypto() != HandshakeEncryption::crypto_rc4)
449       m_encryption.info()->set_obfuscated();
450 
451     m_state = READ_INFO;
452     return true;
453   }
454 
455   if (!fill_read_buffer(2))
456     return false;
457 
458   // The peer may send initial payload that is RC4 encrypted even if
459   // we have selected plaintext encryption, so read it ahead of BT
460   // handshake.
461   m_encryption.set_length_ia(m_readBuffer.read_16());
462 
463   if (m_encryption.length_ia() > handshake_size)
464     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
465 
466   m_state = READ_ENC_IA;
467 
468   return true;
469 }
470 
471 bool
read_info()472 Handshake::read_info() {
473   fill_read_buffer(handshake_size);
474 
475   // Check the first byte as early as possible so we can
476   // disconnect non-BT connections if they send less than 20 bytes.
477   if ((m_readBuffer.remaining() >= 1 && m_readBuffer.peek_8() != 19) ||
478       (m_readBuffer.remaining() >= 20 &&
479        (std::memcmp(m_readBuffer.position() + 1, m_protocol, 19) != 0)))
480     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_not_bittorrent);
481 
482   if (m_readBuffer.remaining() < part1_size)
483     return false;
484 
485   // If the handshake fails after this, it isn't being rejected because
486   // it is unencrypted, so don't retry.
487   m_encryption.set_retry(HandshakeEncryption::RETRY_NONE);
488 
489   m_readBuffer.consume(20);
490 
491   // Should do some option field stuff here, for now just copy.
492   m_readBuffer.read_range(m_options, m_options + 8);
493 
494   // Check the info hash.
495   if (m_incoming) {
496     if (m_download != NULL) {
497       // Have the download from the encrypted handshake, make sure it
498       // matches the BT handshake.
499       if (m_download->info()->hash().not_equal_to((char*)m_readBuffer.position()))
500         throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
501 
502     } else {
503       m_download = m_manager->download_info((char*)m_readBuffer.position());
504     }
505 
506     validate_download();
507 
508     std::make_pair(m_uploadThrottle, m_downloadThrottle) = m_download->throttles(m_address.c_sockaddr());
509 
510     prepare_handshake();
511 
512   } else {
513     if (m_download->info()->hash().not_equal_to((char*)m_readBuffer.position()))
514       throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
515   }
516 
517   m_readBuffer.consume(20);
518   m_state = READ_PEER;
519 
520   return true;
521 }
522 
523 bool
read_peer()524 Handshake::read_peer() {
525   if (!fill_read_buffer(20))
526     return false;
527 
528   prepare_peer_info();
529 
530   // Send EXTENSION_PROTOCOL handshake message if peer supports it.
531   if (m_peerInfo->supports_extensions())
532     write_extension_handshake();
533 
534   // Replay HAVE messages we receive after starting to send the bitfield.
535   // This avoids replaying HAVEs for pieces received between starting the
536   // handshake and now (e.g. when connecting takes longer). Ideally we
537   // should make a snapshot of the bitfield here in case it changes while
538   // we're sending it (if it can't be sent in one write() call).
539   m_initializedTime = cachedTime;
540 
541   // The download is just starting so we're not sending any
542   // bitfield. Pretend we wrote it already.
543   if (m_download->file_list()->bitfield()->is_all_unset() || m_download->initial_seeding() != NULL) {
544     m_writePos = m_download->file_list()->bitfield()->size_bytes();
545     m_writeBuffer.write_32(0);
546 
547     if (m_encryption.info()->is_encrypted())
548       m_encryption.info()->encrypt(m_writeBuffer.end() - 4, 4);
549 
550   } else {
551     prepare_bitfield();
552   }
553 
554   m_state = READ_MESSAGE;
555   manager->poll()->insert_write(this);
556 
557   // Give some extra time for reading/writing the bitfield.
558   priority_queue_erase(&taskScheduler, &m_taskTimeout);
559   priority_queue_insert(&taskScheduler, &m_taskTimeout, (cachedTime + rak::timer::from_seconds(120)).round_seconds());
560 
561   return true;
562 }
563 
564 bool
read_bitfield()565 Handshake::read_bitfield() {
566   if (m_readPos < m_bitfield.size_bytes()) {
567     uint32_t length = read_unthrottled(m_bitfield.begin() + m_readPos, m_bitfield.size_bytes() - m_readPos);
568 
569     if (m_encryption.info()->decrypt_valid())
570       m_encryption.info()->decrypt(m_bitfield.begin() + m_readPos, length);
571 
572     m_readPos += length;
573   }
574 
575   return m_readPos == m_bitfield.size_bytes();
576 }
577 
578 bool
read_extension()579 Handshake::read_extension() {
580   if (m_readBuffer.peek_32() > m_readBuffer.reserved())
581     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
582 
583   int32_t need = m_readBuffer.peek_32() + 4 - m_readBuffer.remaining();
584 
585   // We currently can't handle an extension handshake that doesn't
586   // completely fit in the buffer.  However these messages are usually
587   // ~100 bytes large and the buffer holds over 1000 bytes so it
588   // should be ok. Else maybe figure out how to disable extensions for
589   // when peer connects next time.
590   //
591   // In addition, make sure there's at least 5 bytes available after
592   // the PEX message has been read, so that we can fit the preamble of
593   // the BITFIELD message.
594   if (need + 5 > m_readBuffer.reserved_left()) {
595     m_readBuffer.move_unused();
596 
597     if (need + 5 > m_readBuffer.reserved_left())
598       throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
599   }
600 
601   if (!fill_read_buffer(m_readBuffer.peek_32() + 4))
602     return false;
603 
604   uint32_t length = m_readBuffer.read_32() - 2;
605   m_readBuffer.read_8();
606   m_extensions->read_start(m_readBuffer.read_8(), length, false);
607 
608   std::memcpy(m_extensions->read_position(), m_readBuffer.position(), length);
609   m_extensions->read_move(length);
610 
611   // Does this check need to check if it is a handshake we read?
612   if (!m_extensions->is_complete())
613     throw internal_error("Could not read extension handshake even though it should be in the read buffer.");
614 
615   m_extensions->read_done();
616   m_readBuffer.consume(length);
617   return true;
618 }
619 
620 bool
read_port()621 Handshake::read_port() {
622   if (m_readBuffer.peek_32() > m_readBuffer.reserved())
623     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
624 
625   int32_t need = m_readBuffer.peek_32() + 4 - m_readBuffer.remaining();
626 
627   if (need + 5 > m_readBuffer.reserved_left()) {
628     m_readBuffer.move_unused();
629 
630     if (need + 5 > m_readBuffer.reserved_left())
631       throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
632   }
633 
634   if (!fill_read_buffer(m_readBuffer.peek_32() + 4))
635     return false;
636 
637   uint32_t length = m_readBuffer.read_32() - 1;
638   m_readBuffer.read_8();
639 
640   if (length == 2)
641     manager->dht_manager()->add_node(m_address.c_sockaddr(), m_readBuffer.peek_16());
642 
643   m_readBuffer.consume(length);
644   return true;
645 }
646 
647 void
read_done()648 Handshake::read_done() {
649   if (m_readDone != false)
650     throw internal_error("Handshake::read_done() m_readDone != false.");
651 
652 //   if (m_peerInfo->supports_extensions() && m_extensions->is_initial_handshake())
653 //     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_order);
654 
655   m_readDone = true;
656   manager->poll()->remove_read(this);
657 
658   if (m_bitfield.empty()) {
659     m_bitfield.set_size_bits(m_download->file_list()->bitfield()->size_bits());
660     m_bitfield.allocate();
661     m_bitfield.unset_all();
662 
663   } else {
664     m_bitfield.update();
665   }
666 
667   // Should've started to write post handshake data already, but we were
668   // still reading the bitfield/extension and postponed it. If we had no
669   // bitfield to send, we need to send a keep-alive now.
670   if (m_writePos == m_download->file_list()->bitfield()->size_bytes())
671     prepare_post_handshake(m_download->file_list()->bitfield()->is_all_unset() || m_download->initial_seeding() != NULL);
672 
673   if (m_writeDone)
674     throw handshake_succeeded();
675 }
676 
677 void
event_read()678 Handshake::event_read() {
679   try {
680 
681 restart:
682     switch (m_state) {
683     case PROXY_CONNECT:
684       if (!read_proxy_connect())
685         break;
686 
687       m_state = PROXY_DONE;
688 
689       manager->poll()->insert_write(this);
690       return event_write();
691 
692     case READ_ENC_KEY:
693       if (!read_encryption_key())
694         break;
695 
696       if (m_state != READ_ENC_SYNC)
697         goto restart;
698 
699     case READ_ENC_SYNC:
700       if (!read_encryption_sync())
701         break;
702 
703       if (m_state != READ_ENC_SKEY)
704         goto restart;
705 
706     case READ_ENC_SKEY:
707       if (!read_encryption_skey())
708         break;
709 
710     case READ_ENC_NEGOT:
711       if (!read_encryption_negotiation())
712         break;
713 
714       if (m_state != READ_ENC_PAD)
715         goto restart;
716 
717     case READ_ENC_PAD:
718       if (m_readPos) {
719         // Read padC + lenIA or padD; pad length in m_readPos.
720         if (!fill_read_buffer(m_readPos + (m_incoming ? 2 : 0)))
721           // This can be improved (consume as much as was read)
722           break;
723 
724         m_readBuffer.consume(m_readPos);
725         m_readPos = 0;
726       }
727 
728       if (!read_negotiation_reply())
729         break;
730 
731       if (m_state != READ_ENC_IA)
732         goto restart;
733 
734     case READ_ENC_IA:
735       // Just read (and automatically decrypt) the initial payload
736       // and leave it in the buffer for READ_INFO later.
737       if (m_encryption.length_ia() > 0 && !fill_read_buffer(m_encryption.length_ia()))
738         break;
739 
740       if (m_readBuffer.remaining() > m_encryption.length_ia())
741         throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
742 
743       if (m_encryption.crypto() != HandshakeEncryption::crypto_rc4)
744         m_encryption.info()->set_obfuscated();
745 
746       m_state = READ_INFO;
747 
748     case READ_INFO:
749       if (!read_info())
750         break;
751 
752       if (m_state != READ_PEER)
753         goto restart;
754 
755     case READ_PEER:
756       if (!read_peer())
757         break;
758 
759       // Is this correct?
760       if (m_state != READ_MESSAGE)
761         goto restart;
762 
763     case READ_MESSAGE:
764     case POST_HANDSHAKE:
765       // For meta-downloads, we aren't interested in the bitfield or
766       // extension messages here, PCMetadata handles all that. The
767       // bitfield only refers to the single-chunk meta-data, so fake that.
768       if (m_download->info()->is_meta_download()) {
769         m_bitfield.set_size_bits(1);
770         m_bitfield.allocate();
771         m_bitfield.set(0);
772         read_done();
773         break;
774       }
775 
776       fill_read_buffer(5);
777 
778       // Received a keep-alive message which means we won't be
779       // getting any bitfield.
780       if (m_readBuffer.remaining() >= 4 && m_readBuffer.peek_32() == 0) {
781         m_readBuffer.read_32();
782         read_done();
783         break;
784       }
785 
786       if (m_readBuffer.remaining() < 5)
787         break;
788 
789       m_readPos = 0;
790 
791       // Extension handshake was sent after BT handshake but before
792       // bitfield, so handle that. If we've already received a message
793       // of this type then we will assume the peer won't be sending a
794       // bitfield, as the second extension message will be part of the
795       // normal traffic, not the handshake.
796       if (m_readBuffer.peek_8_at(4) == protocol_bitfield) {
797         const Bitfield* bitfield = m_download->file_list()->bitfield();
798 
799         if (!m_bitfield.empty() || m_readBuffer.read_32() != bitfield->size_bytes() + 1)
800           throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
801 
802         m_readBuffer.read_8();
803 
804         m_bitfield.set_size_bits(bitfield->size_bits());
805         m_bitfield.allocate();
806 
807         m_readPos = std::min<uint32_t>(m_bitfield.size_bytes(), m_readBuffer.remaining());
808         std::memcpy(m_bitfield.begin(), m_readBuffer.position(), m_readPos);
809         m_readBuffer.consume(m_readPos);
810 
811         m_state = READ_BITFIELD;
812 
813       } else if (m_readBuffer.peek_8_at(4) == protocol_extension && m_extensions->is_initial_handshake()) {
814         m_readPos = 0;
815         m_state = READ_EXT;
816 
817       } else if (m_readBuffer.peek_8_at(4) == protocol_port) {
818         // Some peers seem to send the port message before handshake,
819         // so handle it here.
820         m_readPos = 0;
821         m_state = READ_PORT;
822 
823       } else {
824         read_done();
825         break;
826       }
827 
828     case READ_BITFIELD:
829     case READ_EXT:
830     case READ_PORT:
831       // Gather the different command types into the same case group
832       // so that we don't need 'goto restart' above.
833       if ((m_state == READ_BITFIELD && !read_bitfield()) ||
834           (m_state == READ_EXT && !read_extension()) ||
835           (m_state == READ_PORT && !read_port()))
836         break;
837 
838       m_state = READ_MESSAGE;
839 
840       if (!m_bitfield.empty() && (!m_peerInfo->supports_extensions() || !m_extensions->is_initial_handshake())) {
841         read_done();
842         break;
843       }
844 
845       goto restart;
846 
847     default:
848       throw internal_error("Handshake::event_read() called in invalid state.");
849     }
850 
851     // Call event_write if we have any data to write. Make sure
852     // event_write() doesn't get called twice in this function.
853     if (m_writeBuffer.remaining() && !manager->poll()->in_write(this)) {
854       manager->poll()->insert_write(this);
855       return event_write();
856     }
857 
858   } catch (handshake_succeeded& e) {
859     m_manager->receive_succeeded(this);
860 
861   } catch (handshake_error& e) {
862     m_manager->receive_failed(this, e.type(), e.error());
863 
864   } catch (network_error& e) {
865     m_manager->receive_failed(this, ConnectionManager::handshake_failed, e_handshake_network_error);
866   }
867 }
868 
869 bool
fill_read_buffer(int size)870 Handshake::fill_read_buffer(int size) {
871   if (m_readBuffer.remaining() < size) {
872     if (size - m_readBuffer.remaining() > m_readBuffer.reserved_left())
873       throw internal_error("Handshake::fill_read_buffer(...) Buffer overflow.");
874 
875     int read = m_readBuffer.move_end(read_unthrottled(m_readBuffer.end(), size - m_readBuffer.remaining()));
876 
877     if (m_encryption.info()->decrypt_valid())
878       m_encryption.info()->decrypt(m_readBuffer.end() - read, read);
879   }
880 
881   return m_readBuffer.remaining() >= size;
882 }
883 
884 inline void
validate_download()885 Handshake::validate_download() {
886   if (m_download == NULL)
887     throw handshake_error(ConnectionManager::handshake_dropped, e_handshake_unknown_download);
888   if (!m_download->info()->is_active())
889     throw handshake_error(ConnectionManager::handshake_dropped, e_handshake_inactive_download);
890   if (!m_download->info()->is_accepting_new_peers())
891     throw handshake_error(ConnectionManager::handshake_dropped, e_handshake_not_accepting_connections);
892 }
893 
894 void
event_write()895 Handshake::event_write() {
896   try {
897 
898     switch (m_state) {
899     case CONNECTING:
900       if (get_fd().get_error())
901         throw handshake_error(ConnectionManager::handshake_failed, e_handshake_network_unreachable);
902 
903       manager->poll()->insert_read(this);
904 
905       if (m_encryption.options() & ConnectionManager::encryption_use_proxy) {
906         prepare_proxy_connect();
907 
908         m_state = PROXY_CONNECT;
909         break;
910       }
911 
912     case PROXY_DONE:
913       // If there's any bytes remaining, it means we got a reply from
914       // the other side before our proxy connect command was finished
915       // written. This probably means the other side isn't a proxy.
916       if (m_writeBuffer.remaining())
917         throw handshake_error(ConnectionManager::handshake_failed, e_handshake_not_bittorrent);
918 
919       m_writeBuffer.reset();
920 
921       if (m_encryption.options() & (ConnectionManager::encryption_try_outgoing | ConnectionManager::encryption_require)) {
922         prepare_key_plus_pad();
923 
924         // if connection fails, peer probably closed it because it was encrypted, so retry encrypted if enabled
925         if (!(m_encryption.options() & ConnectionManager::encryption_require))
926           m_encryption.set_retry(HandshakeEncryption::RETRY_PLAIN);
927 
928         m_state = READ_ENC_KEY;
929 
930       } else {
931         // if connection is closed before we read the handshake, it might
932         // be rejected because it is unencrypted, in that case retry encrypted
933         m_encryption.set_retry(HandshakeEncryption::RETRY_ENCRYPTED);
934 
935         prepare_handshake();
936 
937         if (m_incoming)
938           m_state = READ_PEER;
939         else
940           m_state = READ_INFO;
941       }
942 
943       break;
944 
945     case READ_MESSAGE:
946     case READ_BITFIELD:
947     case READ_EXT:
948       write_bitfield();
949       return;
950 
951     default:
952       break;
953     }
954 
955     if (!m_writeBuffer.remaining())
956       throw internal_error("event_write called with empty write buffer.");
957 
958     if (m_writeBuffer.consume(write_unthrottled(m_writeBuffer.position(), m_writeBuffer.remaining()))) {
959       if (m_state == POST_HANDSHAKE)
960         write_done();
961       else
962         manager->poll()->remove_write(this);
963     }
964 
965   } catch (handshake_succeeded& e) {
966     m_manager->receive_succeeded(this);
967 
968   } catch (handshake_error& e) {
969     m_manager->receive_failed(this, e.type(), e.error());
970 
971   } catch (network_error& e) {
972     m_manager->receive_failed(this, ConnectionManager::handshake_failed, e_handshake_network_error);
973   }
974 }
975 
976 void
prepare_proxy_connect()977 Handshake::prepare_proxy_connect() {
978   char buf[256];
979   m_address.address_c_str(buf, 256);
980 
981   int advance = snprintf((char*)m_writeBuffer.position(), m_writeBuffer.reserved_left(),
982                          "CONNECT %s:%hu HTTP/1.0\r\n\r\n", buf, m_address.port());
983 
984   if (advance == -1 || advance > m_writeBuffer.reserved_left())
985     throw internal_error("Handshake::prepare_proxy_connect() snprintf failed.");
986 
987   m_writeBuffer.move_end(advance);
988 }
989 
990 void
prepare_key_plus_pad()991 Handshake::prepare_key_plus_pad() {
992   if (!m_encryption.initialize())
993     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_invalid_value);
994 
995   m_encryption.key()->store_pub_key(m_writeBuffer.end(), 96);
996   m_writeBuffer.move_end(96);
997 
998   int length = random() % enc_pad_size;
999   char pad[length];
1000 
1001   std::generate_n(pad, length, &::random);
1002   m_writeBuffer.write_len(pad, length);
1003 }
1004 
1005 void
prepare_enc_negotiation()1006 Handshake::prepare_enc_negotiation() {
1007   char hash[20];
1008 
1009   // first piece, HASH('req1' + S)
1010   sha1_salt("req1", 4, m_encryption.key()->c_str(), m_encryption.key()->size(), m_writeBuffer.end());
1011   m_writeBuffer.move_end(20);
1012 
1013   // second piece, HASH('req2' + SKEY) ^ HASH('req3' + S)
1014   m_writeBuffer.write_len(m_download->info()->hash_obfuscated().c_str(), 20);
1015   sha1_salt("req3", 4, m_encryption.key()->c_str(), m_encryption.key()->size(), hash);
1016 
1017   for (int i = 0; i < 20; i++)
1018     m_writeBuffer.end()[i - 20] ^= hash[i];
1019 
1020   // last piece, ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA))
1021   m_encryption.initialize_encrypt(m_download->info()->hash().c_str(), m_incoming);
1022 
1023   Buffer::iterator old_end = m_writeBuffer.end();
1024 
1025   HandshakeEncryption::copy_vc(m_writeBuffer.end());
1026   m_writeBuffer.move_end(HandshakeEncryption::vc_length);
1027 
1028   if (m_encryption.options() & ConnectionManager::encryption_require_RC4)
1029     m_writeBuffer.write_32(HandshakeEncryption::crypto_rc4);
1030   else
1031     m_writeBuffer.write_32(HandshakeEncryption::crypto_plain | HandshakeEncryption::crypto_rc4);
1032 
1033   m_writeBuffer.write_16(0);
1034   m_writeBuffer.write_16(handshake_size);
1035   m_encryption.info()->encrypt(old_end, m_writeBuffer.end() - old_end);
1036 
1037   // write and encrypt BT handshake as initial payload IA
1038   prepare_handshake();
1039 }
1040 
1041 void
prepare_handshake()1042 Handshake::prepare_handshake() {
1043   m_writeBuffer.write_8(19);
1044   m_writeBuffer.write_range(m_protocol, m_protocol + 19);
1045 
1046   std::memset(m_writeBuffer.end(), 0, 8);
1047   *(m_writeBuffer.end()+5) |= 0x10;    // support extension protocol
1048   if (manager->dht_manager()->is_active())
1049     *(m_writeBuffer.end()+7) |= 0x01;  // DHT support, enable PORT message
1050   m_writeBuffer.move_end(8);
1051 
1052   m_writeBuffer.write_range(m_download->info()->hash().c_str(), m_download->info()->hash().c_str() + 20);
1053   m_writeBuffer.write_range(m_download->info()->local_id().c_str(), m_download->info()->local_id().c_str() + 20);
1054 
1055   if (m_encryption.info()->is_encrypted())
1056     m_encryption.info()->encrypt(m_writeBuffer.end() - handshake_size, handshake_size);
1057 }
1058 
1059 void
prepare_peer_info()1060 Handshake::prepare_peer_info() {
1061   if (std::memcmp(m_readBuffer.position(), m_download->info()->local_id().c_str(), 20) == 0)
1062     throw handshake_error(ConnectionManager::handshake_failed, e_handshake_is_self);
1063 
1064   // PeerInfo handling for outgoing connections needs to be moved to
1065   // HandshakeManager.
1066   if (m_peerInfo == NULL) {
1067     if (!m_incoming)
1068       throw internal_error("Handshake::prepare_peer_info() !m_incoming.");
1069 
1070     m_peerInfo = m_download->peer_list()->connected(m_address.c_sockaddr(), PeerList::connect_incoming);
1071 
1072     if (m_peerInfo == NULL)
1073       throw handshake_error(ConnectionManager::handshake_failed, e_handshake_network_error);
1074 
1075     if (m_peerInfo->failed_counter() > m_manager->max_failed)
1076       throw handshake_error(ConnectionManager::handshake_dropped, e_handshake_toomanyfailed);
1077 
1078     m_peerInfo->set_flags(PeerInfo::flag_handshake);
1079   }
1080 
1081   std::memcpy(m_peerInfo->set_options(), m_options, 8);
1082 
1083   m_peerInfo->mutable_id().assign((const char*)m_readBuffer.position());
1084   m_readBuffer.consume(20);
1085 
1086   hash_string_to_hex(m_peerInfo->id(), m_peerInfo->mutable_id_hex());
1087 
1088   // For meta downloads, we require support of the extension protocol.
1089   if (m_download->info()->is_meta_download() && !m_peerInfo->supports_extensions())
1090     throw handshake_error(ConnectionManager::handshake_dropped, e_handshake_unwanted_connection);
1091 }
1092 
1093 void
prepare_bitfield()1094 Handshake::prepare_bitfield() {
1095   m_writeBuffer.write_32(m_download->file_list()->bitfield()->size_bytes() + 1);
1096   m_writeBuffer.write_8(protocol_bitfield);
1097 
1098   if (m_encryption.info()->is_encrypted())
1099     m_encryption.info()->encrypt(m_writeBuffer.end() - 5, 5);
1100 
1101   m_writePos = 0;
1102 }
1103 
1104 void
prepare_post_handshake(bool must_write)1105 Handshake::prepare_post_handshake(bool must_write) {
1106   if (m_writePos != m_download->file_list()->bitfield()->size_bytes())
1107     throw internal_error("Handshake::prepare_post_handshake called while bitfield not written completely.");
1108 
1109   m_state = POST_HANDSHAKE;
1110 
1111   Buffer::iterator old_end = m_writeBuffer.end();
1112 
1113   // Send PORT message for DHT if enabled and peer supports it.
1114   if (m_peerInfo->supports_dht() && manager->dht_manager()->is_active() && manager->dht_manager()->can_receive_queries()) {
1115     m_writeBuffer.write_32(3);
1116     m_writeBuffer.write_8(protocol_port);
1117     m_writeBuffer.write_16(manager->dht_manager()->port());
1118     manager->dht_manager()->port_sent();
1119   }
1120 
1121   // Send a keep-alive if we still must send something.
1122   if (must_write && old_end == m_writeBuffer.end())
1123     m_writeBuffer.write_32(0);
1124 
1125   if (m_encryption.info()->is_encrypted())
1126     m_encryption.info()->encrypt(old_end, m_writeBuffer.end() - old_end);
1127 
1128   if (!m_writeBuffer.remaining())
1129     write_done();
1130 }
1131 
1132 void
write_done()1133 Handshake::write_done() {
1134   m_writeDone = true;
1135   manager->poll()->remove_write(this);
1136 
1137   // Ok to just check m_readDone as the call in event_read() won't
1138   // set it before the call.
1139   if (m_readDone)
1140     throw handshake_succeeded();
1141 }
1142 
1143 void
write_extension_handshake()1144 Handshake::write_extension_handshake() {
1145   DownloadInfo* info = m_download->info();
1146 
1147   if (m_extensions->is_default()) {
1148     m_extensions = new ProtocolExtension;
1149     m_extensions->set_info(m_peerInfo, m_download);
1150   }
1151 
1152   // PEX may be disabled but still active if disabled since last download tick.
1153   if (info->is_pex_enabled() && info->is_pex_active() && info->size_pex() < info->max_size_pex())
1154     m_extensions->set_local_enabled(ProtocolExtension::UT_PEX);
1155 
1156   DataBuffer message = m_extensions->generate_handshake_message();
1157 
1158   m_writeBuffer.write_32(message.length() + 2);
1159   m_writeBuffer.write_8(protocol_extension);
1160   m_writeBuffer.write_8(ProtocolExtension::HANDSHAKE);
1161   m_writeBuffer.write_range(message.data(), message.end());
1162 
1163   if (m_encryption.info()->is_encrypted())
1164     m_encryption.info()->encrypt(m_writeBuffer.end() - message.length() - 2 - 4, message.length() + 2 + 4);
1165 
1166   message.clear();
1167 }
1168 
1169 void
write_bitfield()1170 Handshake::write_bitfield() {
1171   const Bitfield* bitfield = m_download->file_list()->bitfield();
1172 
1173   if (m_writeDone != false)
1174     throw internal_error("Handshake::event_write() m_writeDone != false.");
1175 
1176   if (m_writeBuffer.remaining())
1177     if (!m_writeBuffer.consume(write_unthrottled(m_writeBuffer.position(), m_writeBuffer.remaining())))
1178       return;
1179 
1180   if (m_writePos != bitfield->size_bytes()) {
1181     if (m_encryption.info()->is_encrypted()) {
1182       if (m_writePos == 0)
1183         m_writeBuffer.reset();	// this should be unnecessary now
1184 
1185       uint32_t length = std::min<uint32_t>(bitfield->size_bytes() - m_writePos, m_writeBuffer.reserved()) - m_writeBuffer.size_end();
1186 
1187       if (length > 0) {
1188         std::memcpy(m_writeBuffer.end(), bitfield->begin() + m_writePos + m_writeBuffer.size_end(), length);
1189         m_encryption.info()->encrypt(m_writeBuffer.end(), length);
1190         m_writeBuffer.move_end(length);
1191       }
1192 
1193       length = write_unthrottled(m_writeBuffer.begin(), m_writeBuffer.size_end());
1194       m_writePos += length;
1195 
1196       if (length != m_writeBuffer.size_end() && length > 0)
1197         std::memmove(m_writeBuffer.begin(), m_writeBuffer.begin() + length, m_writeBuffer.size_end() - length);
1198 
1199       m_writeBuffer.move_end(-length);
1200 
1201     } else {
1202       m_writePos += write_unthrottled(bitfield->begin() + m_writePos,
1203                                       bitfield->size_bytes() - m_writePos);
1204     }
1205   }
1206 
1207   // We can't call prepare_post_handshake until the read code is done reading
1208   // the bitfield, so if we get here before then, postpone the post handshake
1209   // data until reading is done. Since we're done writing, remove us from the
1210   // poll in that case.
1211   if (m_writePos == bitfield->size_bytes()) {
1212     if (!m_readDone)
1213       manager->poll()->remove_write(this);
1214     else
1215       prepare_post_handshake(false);
1216   }
1217 }
1218 
1219 void
event_error()1220 Handshake::event_error() {
1221   if (m_state == INACTIVE)
1222     throw internal_error("Handshake::event_error() called on an inactive handshake.");
1223 
1224   m_manager->receive_failed(this, ConnectionManager::handshake_failed, e_handshake_network_error);
1225 }
1226 
1227 }
1228