You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

693 lines
20 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2004 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #if defined(_MSC_VER) && _MSC_VER < 1300
  11. #pragma warning(disable : 4786)
  12. #endif
  13. #include <errno.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <time.h>
  18. #if defined(WEBRTC_WIN)
  19. #include <windows.h>
  20. #include <winsock2.h>
  21. #include <ws2tcpip.h>
  22. #define SECURITY_WIN32
  23. #include <security.h>
  24. #endif
  25. #include <algorithm>
  26. #include "absl/strings/match.h"
  27. #include "rtc_base/buffer.h"
  28. #include "rtc_base/byte_buffer.h"
  29. #include "rtc_base/checks.h"
  30. #include "rtc_base/http_common.h"
  31. #include "rtc_base/logging.h"
  32. #include "rtc_base/socket_adapters.h"
  33. #include "rtc_base/strings/string_builder.h"
  34. #include "rtc_base/zero_memory.h"
  35. namespace rtc {
  36. BufferedReadAdapter::BufferedReadAdapter(AsyncSocket* socket, size_t size)
  37. : AsyncSocketAdapter(socket),
  38. buffer_size_(size),
  39. data_len_(0),
  40. buffering_(false) {
  41. buffer_ = new char[buffer_size_];
  42. }
  43. BufferedReadAdapter::~BufferedReadAdapter() {
  44. delete[] buffer_;
  45. }
  46. int BufferedReadAdapter::Send(const void* pv, size_t cb) {
  47. if (buffering_) {
  48. // TODO: Spoof error better; Signal Writeable
  49. socket_->SetError(EWOULDBLOCK);
  50. return -1;
  51. }
  52. return AsyncSocketAdapter::Send(pv, cb);
  53. }
  54. int BufferedReadAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
  55. if (buffering_) {
  56. socket_->SetError(EWOULDBLOCK);
  57. return -1;
  58. }
  59. size_t read = 0;
  60. if (data_len_) {
  61. read = std::min(cb, data_len_);
  62. memcpy(pv, buffer_, read);
  63. data_len_ -= read;
  64. if (data_len_ > 0) {
  65. memmove(buffer_, buffer_ + read, data_len_);
  66. }
  67. pv = static_cast<char*>(pv) + read;
  68. cb -= read;
  69. }
  70. // FIX: If cb == 0, we won't generate another read event
  71. int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
  72. if (res >= 0) {
  73. // Read from socket and possibly buffer; return combined length
  74. return res + static_cast<int>(read);
  75. }
  76. if (read > 0) {
  77. // Failed to read from socket, but still read something from buffer
  78. return static_cast<int>(read);
  79. }
  80. // Didn't read anything; return error from socket
  81. return res;
  82. }
  83. void BufferedReadAdapter::BufferInput(bool on) {
  84. buffering_ = on;
  85. }
  86. void BufferedReadAdapter::OnReadEvent(AsyncSocket* socket) {
  87. RTC_DCHECK(socket == socket_);
  88. if (!buffering_) {
  89. AsyncSocketAdapter::OnReadEvent(socket);
  90. return;
  91. }
  92. if (data_len_ >= buffer_size_) {
  93. RTC_LOG(LS_ERROR) << "Input buffer overflow";
  94. RTC_NOTREACHED();
  95. data_len_ = 0;
  96. }
  97. int len =
  98. socket_->Recv(buffer_ + data_len_, buffer_size_ - data_len_, nullptr);
  99. if (len < 0) {
  100. // TODO: Do something better like forwarding the error to the user.
  101. RTC_LOG_ERR(INFO) << "Recv";
  102. return;
  103. }
  104. data_len_ += len;
  105. ProcessInput(buffer_, &data_len_);
  106. }
  107. ///////////////////////////////////////////////////////////////////////////////
  108. // This is a SSL v2 CLIENT_HELLO message.
  109. // TODO: Should this have a session id? The response doesn't have a
  110. // certificate, so the hello should have a session id.
  111. static const uint8_t kSslClientHello[] = {
  112. 0x80, 0x46, // msg len
  113. 0x01, // CLIENT_HELLO
  114. 0x03, 0x01, // SSL 3.1
  115. 0x00, 0x2d, // ciphersuite len
  116. 0x00, 0x00, // session id len
  117. 0x00, 0x10, // challenge len
  118. 0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0, // ciphersuites
  119. 0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80, //
  120. 0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a, //
  121. 0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, //
  122. 0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06, //
  123. 0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc, // challenge
  124. 0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea //
  125. };
  126. // static
  127. ArrayView<const uint8_t> AsyncSSLSocket::SslClientHello() {
  128. // Implicit conversion directly from kSslClientHello to ArrayView fails when
  129. // built with gcc.
  130. return {kSslClientHello, sizeof(kSslClientHello)};
  131. }
  132. // This is a TLSv1 SERVER_HELLO message.
  133. static const uint8_t kSslServerHello[] = {
  134. 0x16, // handshake message
  135. 0x03, 0x01, // SSL 3.1
  136. 0x00, 0x4a, // message len
  137. 0x02, // SERVER_HELLO
  138. 0x00, 0x00, 0x46, // handshake len
  139. 0x03, 0x01, // SSL 3.1
  140. 0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0, // server random
  141. 0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f, //
  142. 0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1, //
  143. 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f, //
  144. 0x20, // session id len
  145. 0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f, // session id
  146. 0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b, //
  147. 0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38, //
  148. 0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c, //
  149. 0x00, 0x04, // RSA/RC4-128/MD5
  150. 0x00 // null compression
  151. };
  152. // static
  153. ArrayView<const uint8_t> AsyncSSLSocket::SslServerHello() {
  154. return {kSslServerHello, sizeof(kSslServerHello)};
  155. }
  156. AsyncSSLSocket::AsyncSSLSocket(AsyncSocket* socket)
  157. : BufferedReadAdapter(socket, 1024) {}
  158. int AsyncSSLSocket::Connect(const SocketAddress& addr) {
  159. // Begin buffering before we connect, so that there isn't a race condition
  160. // between potential senders and receiving the OnConnectEvent signal
  161. BufferInput(true);
  162. return BufferedReadAdapter::Connect(addr);
  163. }
  164. void AsyncSSLSocket::OnConnectEvent(AsyncSocket* socket) {
  165. RTC_DCHECK(socket == socket_);
  166. // TODO: we could buffer output too...
  167. const int res = DirectSend(kSslClientHello, sizeof(kSslClientHello));
  168. RTC_DCHECK_EQ(sizeof(kSslClientHello), res);
  169. }
  170. void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
  171. if (*len < sizeof(kSslServerHello))
  172. return;
  173. if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
  174. Close();
  175. SignalCloseEvent(this, 0); // TODO: error code?
  176. return;
  177. }
  178. *len -= sizeof(kSslServerHello);
  179. if (*len > 0) {
  180. memmove(data, data + sizeof(kSslServerHello), *len);
  181. }
  182. bool remainder = (*len > 0);
  183. BufferInput(false);
  184. SignalConnectEvent(this);
  185. // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
  186. if (remainder)
  187. SignalReadEvent(this);
  188. }
  189. ///////////////////////////////////////////////////////////////////////////////
  190. AsyncHttpsProxySocket::AsyncHttpsProxySocket(AsyncSocket* socket,
  191. const std::string& user_agent,
  192. const SocketAddress& proxy,
  193. const std::string& username,
  194. const CryptString& password)
  195. : BufferedReadAdapter(socket, 1024),
  196. proxy_(proxy),
  197. agent_(user_agent),
  198. user_(username),
  199. pass_(password),
  200. force_connect_(false),
  201. state_(PS_ERROR),
  202. context_(0) {}
  203. AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
  204. delete context_;
  205. }
  206. int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
  207. int ret;
  208. RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
  209. << proxy_.ToSensitiveString() << ")";
  210. dest_ = addr;
  211. state_ = PS_INIT;
  212. if (ShouldIssueConnect()) {
  213. BufferInput(true);
  214. }
  215. ret = BufferedReadAdapter::Connect(proxy_);
  216. // TODO: Set state_ appropriately if Connect fails.
  217. return ret;
  218. }
  219. SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
  220. return dest_;
  221. }
  222. int AsyncHttpsProxySocket::Close() {
  223. headers_.clear();
  224. state_ = PS_ERROR;
  225. dest_.Clear();
  226. delete context_;
  227. context_ = nullptr;
  228. return BufferedReadAdapter::Close();
  229. }
  230. Socket::ConnState AsyncHttpsProxySocket::GetState() const {
  231. if (state_ < PS_TUNNEL) {
  232. return CS_CONNECTING;
  233. } else if (state_ == PS_TUNNEL) {
  234. return CS_CONNECTED;
  235. } else {
  236. return CS_CLOSED;
  237. }
  238. }
  239. void AsyncHttpsProxySocket::OnConnectEvent(AsyncSocket* socket) {
  240. RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
  241. if (!ShouldIssueConnect()) {
  242. state_ = PS_TUNNEL;
  243. BufferedReadAdapter::OnConnectEvent(socket);
  244. return;
  245. }
  246. SendRequest();
  247. }
  248. void AsyncHttpsProxySocket::OnCloseEvent(AsyncSocket* socket, int err) {
  249. RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
  250. if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
  251. state_ = PS_ERROR;
  252. Connect(dest_);
  253. } else {
  254. BufferedReadAdapter::OnCloseEvent(socket, err);
  255. }
  256. }
  257. void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
  258. size_t start = 0;
  259. for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
  260. if (state_ == PS_SKIP_BODY) {
  261. size_t consume = std::min(*len - pos, content_length_);
  262. pos += consume;
  263. start = pos;
  264. content_length_ -= consume;
  265. if (content_length_ == 0) {
  266. EndResponse();
  267. }
  268. continue;
  269. }
  270. if (data[pos++] != '\n')
  271. continue;
  272. size_t len = pos - start - 1;
  273. if ((len > 0) && (data[start + len - 1] == '\r'))
  274. --len;
  275. data[start + len] = 0;
  276. ProcessLine(data + start, len);
  277. start = pos;
  278. }
  279. *len -= start;
  280. if (*len > 0) {
  281. memmove(data, data + start, *len);
  282. }
  283. if (state_ != PS_TUNNEL)
  284. return;
  285. bool remainder = (*len > 0);
  286. BufferInput(false);
  287. SignalConnectEvent(this);
  288. // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
  289. if (remainder)
  290. SignalReadEvent(this); // TODO: signal this??
  291. }
  292. bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
  293. // TODO: Think about whether a more sophisticated test
  294. // than dest port == 80 is needed.
  295. return force_connect_ || (dest_.port() != 80);
  296. }
  297. void AsyncHttpsProxySocket::SendRequest() {
  298. rtc::StringBuilder ss;
  299. ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
  300. ss << "User-Agent: " << agent_ << "\r\n";
  301. ss << "Host: " << dest_.HostAsURIString() << "\r\n";
  302. ss << "Content-Length: 0\r\n";
  303. ss << "Proxy-Connection: Keep-Alive\r\n";
  304. ss << headers_;
  305. ss << "\r\n";
  306. std::string str = ss.str();
  307. DirectSend(str.c_str(), str.size());
  308. state_ = PS_LEADER;
  309. expect_close_ = true;
  310. content_length_ = 0;
  311. headers_.clear();
  312. RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
  313. }
  314. void AsyncHttpsProxySocket::ProcessLine(char* data, size_t len) {
  315. RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
  316. if (len == 0) {
  317. if (state_ == PS_TUNNEL_HEADERS) {
  318. state_ = PS_TUNNEL;
  319. } else if (state_ == PS_ERROR_HEADERS) {
  320. Error(defer_error_);
  321. return;
  322. } else if (state_ == PS_SKIP_HEADERS) {
  323. if (content_length_) {
  324. state_ = PS_SKIP_BODY;
  325. } else {
  326. EndResponse();
  327. return;
  328. }
  329. } else {
  330. static bool report = false;
  331. if (!unknown_mechanisms_.empty() && !report) {
  332. report = true;
  333. std::string msg(
  334. "Unable to connect to the Google Talk service due to an "
  335. "incompatibility "
  336. "with your proxy.\r\nPlease help us resolve this issue by "
  337. "submitting the "
  338. "following information to us using our technical issue submission "
  339. "form "
  340. "at:\r\n\r\n"
  341. "http://www.google.com/support/talk/bin/request.py\r\n\r\n"
  342. "We apologize for the inconvenience.\r\n\r\n"
  343. "Information to submit to Google: ");
  344. // std::string msg("Please report the following information to
  345. // foo@bar.com:\r\nUnknown methods: ");
  346. msg.append(unknown_mechanisms_);
  347. #if defined(WEBRTC_WIN) && !defined(WINUWP)
  348. MessageBoxA(0, msg.c_str(), "Oops!", MB_OK);
  349. #endif
  350. #if defined(WEBRTC_POSIX)
  351. // TODO: Raise a signal so the UI can be separated.
  352. RTC_LOG(LS_ERROR) << "Oops!\n\n" << msg;
  353. #endif
  354. }
  355. // Unexpected end of headers
  356. Error(0);
  357. return;
  358. }
  359. } else if (state_ == PS_LEADER) {
  360. unsigned int code;
  361. if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
  362. Error(0);
  363. return;
  364. }
  365. switch (code) {
  366. case 200:
  367. // connection good!
  368. state_ = PS_TUNNEL_HEADERS;
  369. return;
  370. #if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
  371. #error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
  372. #endif
  373. case 407: // HTTP_STATUS_PROXY_AUTH_REQ
  374. state_ = PS_AUTHENTICATE;
  375. return;
  376. default:
  377. defer_error_ = 0;
  378. state_ = PS_ERROR_HEADERS;
  379. return;
  380. }
  381. } else if ((state_ == PS_AUTHENTICATE) &&
  382. absl::StartsWithIgnoreCase(data, "Proxy-Authenticate:")) {
  383. std::string response, auth_method;
  384. switch (HttpAuthenticate(data + 19, len - 19, proxy_, "CONNECT", "/", user_,
  385. pass_, context_, response, auth_method)) {
  386. case HAR_IGNORE:
  387. RTC_LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
  388. if (!unknown_mechanisms_.empty())
  389. unknown_mechanisms_.append(", ");
  390. unknown_mechanisms_.append(auth_method);
  391. break;
  392. case HAR_RESPONSE:
  393. headers_ = "Proxy-Authorization: ";
  394. headers_.append(response);
  395. headers_.append("\r\n");
  396. state_ = PS_SKIP_HEADERS;
  397. unknown_mechanisms_.clear();
  398. break;
  399. case HAR_CREDENTIALS:
  400. defer_error_ = SOCKET_EACCES;
  401. state_ = PS_ERROR_HEADERS;
  402. unknown_mechanisms_.clear();
  403. break;
  404. case HAR_ERROR:
  405. defer_error_ = 0;
  406. state_ = PS_ERROR_HEADERS;
  407. unknown_mechanisms_.clear();
  408. break;
  409. }
  410. } else if (absl::StartsWithIgnoreCase(data, "Content-Length:")) {
  411. content_length_ = strtoul(data + 15, 0, 0);
  412. } else if (absl::StartsWithIgnoreCase(data, "Proxy-Connection: Keep-Alive")) {
  413. expect_close_ = false;
  414. /*
  415. } else if (absl::StartsWithIgnoreCase(data, "Connection: close") {
  416. expect_close_ = true;
  417. */
  418. }
  419. }
  420. void AsyncHttpsProxySocket::EndResponse() {
  421. if (!expect_close_) {
  422. SendRequest();
  423. return;
  424. }
  425. // No point in waiting for the server to close... let's close now
  426. // TODO: Refactor out PS_WAIT_CLOSE
  427. state_ = PS_WAIT_CLOSE;
  428. BufferedReadAdapter::Close();
  429. OnCloseEvent(this, 0);
  430. }
  431. void AsyncHttpsProxySocket::Error(int error) {
  432. BufferInput(false);
  433. Close();
  434. SetError(error);
  435. SignalCloseEvent(this, error);
  436. }
  437. ///////////////////////////////////////////////////////////////////////////////
  438. AsyncSocksProxySocket::AsyncSocksProxySocket(AsyncSocket* socket,
  439. const SocketAddress& proxy,
  440. const std::string& username,
  441. const CryptString& password)
  442. : BufferedReadAdapter(socket, 1024),
  443. state_(SS_ERROR),
  444. proxy_(proxy),
  445. user_(username),
  446. pass_(password) {}
  447. AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
  448. int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
  449. int ret;
  450. dest_ = addr;
  451. state_ = SS_INIT;
  452. BufferInput(true);
  453. ret = BufferedReadAdapter::Connect(proxy_);
  454. // TODO: Set state_ appropriately if Connect fails.
  455. return ret;
  456. }
  457. SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
  458. return dest_;
  459. }
  460. int AsyncSocksProxySocket::Close() {
  461. state_ = SS_ERROR;
  462. dest_.Clear();
  463. return BufferedReadAdapter::Close();
  464. }
  465. Socket::ConnState AsyncSocksProxySocket::GetState() const {
  466. if (state_ < SS_TUNNEL) {
  467. return CS_CONNECTING;
  468. } else if (state_ == SS_TUNNEL) {
  469. return CS_CONNECTED;
  470. } else {
  471. return CS_CLOSED;
  472. }
  473. }
  474. void AsyncSocksProxySocket::OnConnectEvent(AsyncSocket* socket) {
  475. SendHello();
  476. }
  477. void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
  478. RTC_DCHECK(state_ < SS_TUNNEL);
  479. ByteBufferReader response(data, *len);
  480. if (state_ == SS_HELLO) {
  481. uint8_t ver, method;
  482. if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&method))
  483. return;
  484. if (ver != 5) {
  485. Error(0);
  486. return;
  487. }
  488. if (method == 0) {
  489. SendConnect();
  490. } else if (method == 2) {
  491. SendAuth();
  492. } else {
  493. Error(0);
  494. return;
  495. }
  496. } else if (state_ == SS_AUTH) {
  497. uint8_t ver, status;
  498. if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&status))
  499. return;
  500. if ((ver != 1) || (status != 0)) {
  501. Error(SOCKET_EACCES);
  502. return;
  503. }
  504. SendConnect();
  505. } else if (state_ == SS_CONNECT) {
  506. uint8_t ver, rep, rsv, atyp;
  507. if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&rep) ||
  508. !response.ReadUInt8(&rsv) || !response.ReadUInt8(&atyp))
  509. return;
  510. if ((ver != 5) || (rep != 0)) {
  511. Error(0);
  512. return;
  513. }
  514. uint16_t port;
  515. if (atyp == 1) {
  516. uint32_t addr;
  517. if (!response.ReadUInt32(&addr) || !response.ReadUInt16(&port))
  518. return;
  519. RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
  520. } else if (atyp == 3) {
  521. uint8_t len;
  522. std::string addr;
  523. if (!response.ReadUInt8(&len) || !response.ReadString(&addr, len) ||
  524. !response.ReadUInt16(&port))
  525. return;
  526. RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
  527. } else if (atyp == 4) {
  528. std::string addr;
  529. if (!response.ReadString(&addr, 16) || !response.ReadUInt16(&port))
  530. return;
  531. RTC_LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
  532. } else {
  533. Error(0);
  534. return;
  535. }
  536. state_ = SS_TUNNEL;
  537. }
  538. // Consume parsed data
  539. *len = response.Length();
  540. memmove(data, response.Data(), *len);
  541. if (state_ != SS_TUNNEL)
  542. return;
  543. bool remainder = (*len > 0);
  544. BufferInput(false);
  545. SignalConnectEvent(this);
  546. // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
  547. if (remainder)
  548. SignalReadEvent(this); // TODO: signal this??
  549. }
  550. void AsyncSocksProxySocket::SendHello() {
  551. ByteBufferWriter request;
  552. request.WriteUInt8(5); // Socks Version
  553. if (user_.empty()) {
  554. request.WriteUInt8(1); // Authentication Mechanisms
  555. request.WriteUInt8(0); // No authentication
  556. } else {
  557. request.WriteUInt8(2); // Authentication Mechanisms
  558. request.WriteUInt8(0); // No authentication
  559. request.WriteUInt8(2); // Username/Password
  560. }
  561. DirectSend(request.Data(), request.Length());
  562. state_ = SS_HELLO;
  563. }
  564. void AsyncSocksProxySocket::SendAuth() {
  565. ByteBufferWriterT<ZeroOnFreeBuffer<char>> request;
  566. request.WriteUInt8(1); // Negotiation Version
  567. request.WriteUInt8(static_cast<uint8_t>(user_.size()));
  568. request.WriteString(user_); // Username
  569. request.WriteUInt8(static_cast<uint8_t>(pass_.GetLength()));
  570. size_t len = pass_.GetLength() + 1;
  571. char* sensitive = new char[len];
  572. pass_.CopyTo(sensitive, true);
  573. request.WriteBytes(sensitive, pass_.GetLength()); // Password
  574. ExplicitZeroMemory(sensitive, len);
  575. delete[] sensitive;
  576. DirectSend(request.Data(), request.Length());
  577. state_ = SS_AUTH;
  578. }
  579. void AsyncSocksProxySocket::SendConnect() {
  580. ByteBufferWriter request;
  581. request.WriteUInt8(5); // Socks Version
  582. request.WriteUInt8(1); // CONNECT
  583. request.WriteUInt8(0); // Reserved
  584. if (dest_.IsUnresolvedIP()) {
  585. std::string hostname = dest_.hostname();
  586. request.WriteUInt8(3); // DOMAINNAME
  587. request.WriteUInt8(static_cast<uint8_t>(hostname.size()));
  588. request.WriteString(hostname); // Destination Hostname
  589. } else {
  590. request.WriteUInt8(1); // IPV4
  591. request.WriteUInt32(dest_.ip()); // Destination IP
  592. }
  593. request.WriteUInt16(dest_.port()); // Destination Port
  594. DirectSend(request.Data(), request.Length());
  595. state_ = SS_CONNECT;
  596. }
  597. void AsyncSocksProxySocket::Error(int error) {
  598. state_ = SS_ERROR;
  599. BufferInput(false);
  600. Close();
  601. SetError(SOCKET_EACCES);
  602. SignalCloseEvent(this, error);
  603. }
  604. } // namespace rtc