socks5_client_socket.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/socket/socks5_client_socket.h"
  5. #include <utility>
  6. #include "base/bind.h"
  7. #include "base/callback_helpers.h"
  8. #include "base/compiler_specific.h"
  9. #include "base/format_macros.h"
  10. #include "base/strings/string_util.h"
  11. #include "base/sys_byteorder.h"
  12. #include "base/trace_event/trace_event.h"
  13. #include "net/base/io_buffer.h"
  14. #include "net/base/sys_addrinfo.h"
  15. #include "net/log/net_log.h"
  16. #include "net/log/net_log_event_type.h"
  17. #include "net/traffic_annotation/network_traffic_annotation.h"
  18. namespace net {
  19. const unsigned int SOCKS5ClientSocket::kGreetReadHeaderSize = 2;
  20. const unsigned int SOCKS5ClientSocket::kWriteHeaderSize = 10;
  21. const unsigned int SOCKS5ClientSocket::kReadHeaderSize = 5;
  22. const uint8_t SOCKS5ClientSocket::kSOCKS5Version = 0x05;
  23. const uint8_t SOCKS5ClientSocket::kTunnelCommand = 0x01;
  24. const uint8_t SOCKS5ClientSocket::kNullByte = 0x00;
  25. static_assert(sizeof(struct in_addr) == 4, "incorrect system size of IPv4");
  26. static_assert(sizeof(struct in6_addr) == 16, "incorrect system size of IPv6");
  27. SOCKS5ClientSocket::SOCKS5ClientSocket(
  28. std::unique_ptr<StreamSocket> transport_socket,
  29. const HostPortPair& destination,
  30. const NetworkTrafficAnnotationTag& traffic_annotation)
  31. : io_callback_(base::BindRepeating(&SOCKS5ClientSocket::OnIOComplete,
  32. base::Unretained(this))),
  33. transport_socket_(std::move(transport_socket)),
  34. read_header_size(kReadHeaderSize),
  35. destination_(destination),
  36. net_log_(transport_socket_->NetLog()),
  37. traffic_annotation_(traffic_annotation) {}
  38. SOCKS5ClientSocket::~SOCKS5ClientSocket() {
  39. Disconnect();
  40. }
  41. int SOCKS5ClientSocket::Connect(CompletionOnceCallback callback) {
  42. DCHECK(transport_socket_);
  43. DCHECK_EQ(STATE_NONE, next_state_);
  44. DCHECK(user_callback_.is_null());
  45. // If already connected, then just return OK.
  46. if (completed_handshake_)
  47. return OK;
  48. net_log_.BeginEvent(NetLogEventType::SOCKS5_CONNECT);
  49. next_state_ = STATE_GREET_WRITE;
  50. buffer_.clear();
  51. int rv = DoLoop(OK);
  52. if (rv == ERR_IO_PENDING) {
  53. user_callback_ = std::move(callback);
  54. } else {
  55. net_log_.EndEventWithNetErrorCode(NetLogEventType::SOCKS5_CONNECT, rv);
  56. }
  57. return rv;
  58. }
  59. void SOCKS5ClientSocket::Disconnect() {
  60. completed_handshake_ = false;
  61. transport_socket_->Disconnect();
  62. // Reset other states to make sure they aren't mistakenly used later.
  63. // These are the states initialized by Connect().
  64. next_state_ = STATE_NONE;
  65. user_callback_.Reset();
  66. }
  67. bool SOCKS5ClientSocket::IsConnected() const {
  68. return completed_handshake_ && transport_socket_->IsConnected();
  69. }
  70. bool SOCKS5ClientSocket::IsConnectedAndIdle() const {
  71. return completed_handshake_ && transport_socket_->IsConnectedAndIdle();
  72. }
  73. const NetLogWithSource& SOCKS5ClientSocket::NetLog() const {
  74. return net_log_;
  75. }
  76. bool SOCKS5ClientSocket::WasEverUsed() const {
  77. return was_ever_used_;
  78. }
  79. bool SOCKS5ClientSocket::WasAlpnNegotiated() const {
  80. if (transport_socket_)
  81. return transport_socket_->WasAlpnNegotiated();
  82. NOTREACHED();
  83. return false;
  84. }
  85. NextProto SOCKS5ClientSocket::GetNegotiatedProtocol() const {
  86. if (transport_socket_)
  87. return transport_socket_->GetNegotiatedProtocol();
  88. NOTREACHED();
  89. return kProtoUnknown;
  90. }
  91. bool SOCKS5ClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
  92. if (transport_socket_)
  93. return transport_socket_->GetSSLInfo(ssl_info);
  94. NOTREACHED();
  95. return false;
  96. }
  97. int64_t SOCKS5ClientSocket::GetTotalReceivedBytes() const {
  98. return transport_socket_->GetTotalReceivedBytes();
  99. }
  100. void SOCKS5ClientSocket::ApplySocketTag(const SocketTag& tag) {
  101. return transport_socket_->ApplySocketTag(tag);
  102. }
  103. // Read is called by the transport layer above to read. This can only be done
  104. // if the SOCKS handshake is complete.
  105. int SOCKS5ClientSocket::Read(IOBuffer* buf,
  106. int buf_len,
  107. CompletionOnceCallback callback) {
  108. DCHECK(completed_handshake_);
  109. DCHECK_EQ(STATE_NONE, next_state_);
  110. DCHECK(user_callback_.is_null());
  111. DCHECK(!callback.is_null());
  112. int rv = transport_socket_->Read(
  113. buf, buf_len,
  114. base::BindOnce(&SOCKS5ClientSocket::OnReadWriteComplete,
  115. base::Unretained(this), std::move(callback)));
  116. if (rv > 0)
  117. was_ever_used_ = true;
  118. return rv;
  119. }
  120. // Write is called by the transport layer. This can only be done if the
  121. // SOCKS handshake is complete.
  122. int SOCKS5ClientSocket::Write(
  123. IOBuffer* buf,
  124. int buf_len,
  125. CompletionOnceCallback callback,
  126. const NetworkTrafficAnnotationTag& traffic_annotation) {
  127. DCHECK(completed_handshake_);
  128. DCHECK_EQ(STATE_NONE, next_state_);
  129. DCHECK(user_callback_.is_null());
  130. DCHECK(!callback.is_null());
  131. int rv = transport_socket_->Write(
  132. buf, buf_len,
  133. base::BindOnce(&SOCKS5ClientSocket::OnReadWriteComplete,
  134. base::Unretained(this), std::move(callback)),
  135. traffic_annotation);
  136. if (rv > 0)
  137. was_ever_used_ = true;
  138. return rv;
  139. }
  140. int SOCKS5ClientSocket::SetReceiveBufferSize(int32_t size) {
  141. return transport_socket_->SetReceiveBufferSize(size);
  142. }
  143. int SOCKS5ClientSocket::SetSendBufferSize(int32_t size) {
  144. return transport_socket_->SetSendBufferSize(size);
  145. }
  146. void SOCKS5ClientSocket::DoCallback(int result) {
  147. DCHECK_NE(ERR_IO_PENDING, result);
  148. DCHECK(!user_callback_.is_null());
  149. // Since Run() may result in Read being called,
  150. // clear user_callback_ up front.
  151. std::move(user_callback_).Run(result);
  152. }
  153. void SOCKS5ClientSocket::OnIOComplete(int result) {
  154. DCHECK_NE(STATE_NONE, next_state_);
  155. int rv = DoLoop(result);
  156. if (rv != ERR_IO_PENDING) {
  157. net_log_.EndEvent(NetLogEventType::SOCKS5_CONNECT);
  158. DoCallback(rv);
  159. }
  160. }
  161. void SOCKS5ClientSocket::OnReadWriteComplete(CompletionOnceCallback callback,
  162. int result) {
  163. DCHECK_NE(ERR_IO_PENDING, result);
  164. DCHECK(!callback.is_null());
  165. if (result > 0)
  166. was_ever_used_ = true;
  167. std::move(callback).Run(result);
  168. }
  169. int SOCKS5ClientSocket::DoLoop(int last_io_result) {
  170. DCHECK_NE(next_state_, STATE_NONE);
  171. int rv = last_io_result;
  172. do {
  173. State state = next_state_;
  174. next_state_ = STATE_NONE;
  175. switch (state) {
  176. case STATE_GREET_WRITE:
  177. DCHECK_EQ(OK, rv);
  178. net_log_.BeginEvent(NetLogEventType::SOCKS5_GREET_WRITE);
  179. rv = DoGreetWrite();
  180. break;
  181. case STATE_GREET_WRITE_COMPLETE:
  182. rv = DoGreetWriteComplete(rv);
  183. net_log_.EndEventWithNetErrorCode(NetLogEventType::SOCKS5_GREET_WRITE,
  184. rv);
  185. break;
  186. case STATE_GREET_READ:
  187. DCHECK_EQ(OK, rv);
  188. net_log_.BeginEvent(NetLogEventType::SOCKS5_GREET_READ);
  189. rv = DoGreetRead();
  190. break;
  191. case STATE_GREET_READ_COMPLETE:
  192. rv = DoGreetReadComplete(rv);
  193. net_log_.EndEventWithNetErrorCode(NetLogEventType::SOCKS5_GREET_READ,
  194. rv);
  195. break;
  196. case STATE_HANDSHAKE_WRITE:
  197. DCHECK_EQ(OK, rv);
  198. net_log_.BeginEvent(NetLogEventType::SOCKS5_HANDSHAKE_WRITE);
  199. rv = DoHandshakeWrite();
  200. break;
  201. case STATE_HANDSHAKE_WRITE_COMPLETE:
  202. rv = DoHandshakeWriteComplete(rv);
  203. net_log_.EndEventWithNetErrorCode(
  204. NetLogEventType::SOCKS5_HANDSHAKE_WRITE, rv);
  205. break;
  206. case STATE_HANDSHAKE_READ:
  207. DCHECK_EQ(OK, rv);
  208. net_log_.BeginEvent(NetLogEventType::SOCKS5_HANDSHAKE_READ);
  209. rv = DoHandshakeRead();
  210. break;
  211. case STATE_HANDSHAKE_READ_COMPLETE:
  212. rv = DoHandshakeReadComplete(rv);
  213. net_log_.EndEventWithNetErrorCode(
  214. NetLogEventType::SOCKS5_HANDSHAKE_READ, rv);
  215. break;
  216. default:
  217. NOTREACHED() << "bad state";
  218. rv = ERR_UNEXPECTED;
  219. break;
  220. }
  221. } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
  222. return rv;
  223. }
  224. const char kSOCKS5GreetWriteData[] = { 0x05, 0x01, 0x00 }; // no authentication
  225. int SOCKS5ClientSocket::DoGreetWrite() {
  226. // Since we only have 1 byte to send the hostname length in, if the
  227. // URL has a hostname longer than 255 characters we can't send it.
  228. if (0xFF < destination_.host().size()) {
  229. net_log_.AddEvent(NetLogEventType::SOCKS_HOSTNAME_TOO_BIG);
  230. return ERR_SOCKS_CONNECTION_FAILED;
  231. }
  232. if (buffer_.empty()) {
  233. buffer_ =
  234. std::string(kSOCKS5GreetWriteData, std::size(kSOCKS5GreetWriteData));
  235. bytes_sent_ = 0;
  236. }
  237. next_state_ = STATE_GREET_WRITE_COMPLETE;
  238. size_t handshake_buf_len = buffer_.size() - bytes_sent_;
  239. handshake_buf_ = base::MakeRefCounted<IOBuffer>(handshake_buf_len);
  240. memcpy(handshake_buf_->data(), &buffer_.data()[bytes_sent_],
  241. handshake_buf_len);
  242. return transport_socket_->Write(handshake_buf_.get(), handshake_buf_len,
  243. io_callback_, traffic_annotation_);
  244. }
  245. int SOCKS5ClientSocket::DoGreetWriteComplete(int result) {
  246. if (result < 0)
  247. return result;
  248. bytes_sent_ += result;
  249. if (bytes_sent_ == buffer_.size()) {
  250. buffer_.clear();
  251. bytes_received_ = 0;
  252. next_state_ = STATE_GREET_READ;
  253. } else {
  254. next_state_ = STATE_GREET_WRITE;
  255. }
  256. return OK;
  257. }
  258. int SOCKS5ClientSocket::DoGreetRead() {
  259. next_state_ = STATE_GREET_READ_COMPLETE;
  260. size_t handshake_buf_len = kGreetReadHeaderSize - bytes_received_;
  261. handshake_buf_ = base::MakeRefCounted<IOBuffer>(handshake_buf_len);
  262. return transport_socket_->Read(handshake_buf_.get(), handshake_buf_len,
  263. io_callback_);
  264. }
  265. int SOCKS5ClientSocket::DoGreetReadComplete(int result) {
  266. if (result < 0)
  267. return result;
  268. if (result == 0) {
  269. net_log_.AddEvent(
  270. NetLogEventType::SOCKS_UNEXPECTEDLY_CLOSED_DURING_GREETING);
  271. return ERR_SOCKS_CONNECTION_FAILED;
  272. }
  273. bytes_received_ += result;
  274. buffer_.append(handshake_buf_->data(), result);
  275. if (bytes_received_ < kGreetReadHeaderSize) {
  276. next_state_ = STATE_GREET_READ;
  277. return OK;
  278. }
  279. // Got the greet data.
  280. if (buffer_[0] != kSOCKS5Version) {
  281. net_log_.AddEventWithIntParams(NetLogEventType::SOCKS_UNEXPECTED_VERSION,
  282. "version", buffer_[0]);
  283. return ERR_SOCKS_CONNECTION_FAILED;
  284. }
  285. if (buffer_[1] != 0x00) {
  286. net_log_.AddEventWithIntParams(NetLogEventType::SOCKS_UNEXPECTED_AUTH,
  287. "method", buffer_[1]);
  288. return ERR_SOCKS_CONNECTION_FAILED;
  289. }
  290. buffer_.clear();
  291. next_state_ = STATE_HANDSHAKE_WRITE;
  292. return OK;
  293. }
  294. int SOCKS5ClientSocket::BuildHandshakeWriteBuffer(std::string* handshake)
  295. const {
  296. DCHECK(handshake->empty());
  297. handshake->push_back(kSOCKS5Version);
  298. handshake->push_back(kTunnelCommand); // Connect command
  299. handshake->push_back(kNullByte); // Reserved null
  300. handshake->push_back(kEndPointDomain); // The type of the address.
  301. DCHECK_GE(static_cast<size_t>(0xFF), destination_.host().size());
  302. // First add the size of the hostname, followed by the hostname.
  303. handshake->push_back(static_cast<unsigned char>(destination_.host().size()));
  304. handshake->append(destination_.host());
  305. uint16_t nw_port = base::HostToNet16(destination_.port());
  306. handshake->append(reinterpret_cast<char*>(&nw_port), sizeof(nw_port));
  307. return OK;
  308. }
  309. // Writes the SOCKS handshake data to the underlying socket connection.
  310. int SOCKS5ClientSocket::DoHandshakeWrite() {
  311. next_state_ = STATE_HANDSHAKE_WRITE_COMPLETE;
  312. if (buffer_.empty()) {
  313. int rv = BuildHandshakeWriteBuffer(&buffer_);
  314. if (rv != OK)
  315. return rv;
  316. bytes_sent_ = 0;
  317. }
  318. int handshake_buf_len = buffer_.size() - bytes_sent_;
  319. DCHECK_LT(0, handshake_buf_len);
  320. handshake_buf_ = base::MakeRefCounted<IOBuffer>(handshake_buf_len);
  321. memcpy(handshake_buf_->data(), &buffer_[bytes_sent_],
  322. handshake_buf_len);
  323. return transport_socket_->Write(handshake_buf_.get(), handshake_buf_len,
  324. io_callback_, traffic_annotation_);
  325. }
  326. int SOCKS5ClientSocket::DoHandshakeWriteComplete(int result) {
  327. if (result < 0)
  328. return result;
  329. // We ignore the case when result is 0, since the underlying Write
  330. // may return spurious writes while waiting on the socket.
  331. bytes_sent_ += result;
  332. if (bytes_sent_ == buffer_.size()) {
  333. next_state_ = STATE_HANDSHAKE_READ;
  334. buffer_.clear();
  335. } else if (bytes_sent_ < buffer_.size()) {
  336. next_state_ = STATE_HANDSHAKE_WRITE;
  337. } else {
  338. NOTREACHED();
  339. }
  340. return OK;
  341. }
  342. int SOCKS5ClientSocket::DoHandshakeRead() {
  343. next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
  344. if (buffer_.empty()) {
  345. bytes_received_ = 0;
  346. read_header_size = kReadHeaderSize;
  347. }
  348. int handshake_buf_len = read_header_size - bytes_received_;
  349. handshake_buf_ = base::MakeRefCounted<IOBuffer>(handshake_buf_len);
  350. return transport_socket_->Read(handshake_buf_.get(), handshake_buf_len,
  351. io_callback_);
  352. }
  353. int SOCKS5ClientSocket::DoHandshakeReadComplete(int result) {
  354. if (result < 0)
  355. return result;
  356. // The underlying socket closed unexpectedly.
  357. if (result == 0) {
  358. net_log_.AddEvent(
  359. NetLogEventType::SOCKS_UNEXPECTEDLY_CLOSED_DURING_HANDSHAKE);
  360. return ERR_SOCKS_CONNECTION_FAILED;
  361. }
  362. buffer_.append(handshake_buf_->data(), result);
  363. bytes_received_ += result;
  364. // When the first few bytes are read, check how many more are required
  365. // and accordingly increase them
  366. if (bytes_received_ == kReadHeaderSize) {
  367. if (buffer_[0] != kSOCKS5Version || buffer_[2] != kNullByte) {
  368. net_log_.AddEventWithIntParams(NetLogEventType::SOCKS_UNEXPECTED_VERSION,
  369. "version", buffer_[0]);
  370. return ERR_SOCKS_CONNECTION_FAILED;
  371. }
  372. if (buffer_[1] != 0x00) {
  373. net_log_.AddEventWithIntParams(NetLogEventType::SOCKS_SERVER_ERROR,
  374. "error_code", buffer_[1]);
  375. return ERR_SOCKS_CONNECTION_FAILED;
  376. }
  377. // We check the type of IP/Domain the server returns and accordingly
  378. // increase the size of the response. For domains, we need to read the
  379. // size of the domain, so the initial request size is upto the domain
  380. // size. Since for IPv4/IPv6 the size is fixed and hence no 'size' is
  381. // read, we substract 1 byte from the additional request size.
  382. SocksEndPointAddressType address_type =
  383. static_cast<SocksEndPointAddressType>(buffer_[3]);
  384. if (address_type == kEndPointDomain) {
  385. read_header_size += static_cast<uint8_t>(buffer_[4]);
  386. } else if (address_type == kEndPointResolvedIPv4) {
  387. read_header_size += sizeof(struct in_addr) - 1;
  388. } else if (address_type == kEndPointResolvedIPv6) {
  389. read_header_size += sizeof(struct in6_addr) - 1;
  390. } else {
  391. net_log_.AddEventWithIntParams(
  392. NetLogEventType::SOCKS_UNKNOWN_ADDRESS_TYPE, "address_type",
  393. buffer_[3]);
  394. return ERR_SOCKS_CONNECTION_FAILED;
  395. }
  396. read_header_size += 2; // for the port.
  397. next_state_ = STATE_HANDSHAKE_READ;
  398. return OK;
  399. }
  400. // When the final bytes are read, setup handshake. We ignore the rest
  401. // of the response since they represent the SOCKSv5 endpoint and have
  402. // no use when doing a tunnel connection.
  403. if (bytes_received_ == read_header_size) {
  404. completed_handshake_ = true;
  405. buffer_.clear();
  406. next_state_ = STATE_NONE;
  407. return OK;
  408. }
  409. next_state_ = STATE_HANDSHAKE_READ;
  410. return OK;
  411. }
  412. int SOCKS5ClientSocket::GetPeerAddress(IPEndPoint* address) const {
  413. return transport_socket_->GetPeerAddress(address);
  414. }
  415. int SOCKS5ClientSocket::GetLocalAddress(IPEndPoint* address) const {
  416. return transport_socket_->GetLocalAddress(address);
  417. }
  418. } // namespace net