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.

910 lines
26 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #if defined(_MSC_VER) && _MSC_VER < 1300
  28. #pragma warning(disable:4786)
  29. #endif
  30. #include <time.h>
  31. #include <errno.h>
  32. #ifdef WIN32
  33. #define WIN32_LEAN_AND_MEAN
  34. #include <windows.h>
  35. #include <winsock2.h>
  36. #include <ws2tcpip.h>
  37. #define SECURITY_WIN32
  38. #include <security.h>
  39. #endif
  40. #include "talk/base/bytebuffer.h"
  41. #include "talk/base/common.h"
  42. #include "talk/base/httpcommon.h"
  43. #include "talk/base/logging.h"
  44. #include "talk/base/socketadapters.h"
  45. #include "talk/base/stringencode.h"
  46. #include "talk/base/stringutils.h"
  47. #ifdef WIN32
  48. #include "talk/base/sec_buffer.h"
  49. #endif // WIN32
  50. namespace talk_base {
  51. BufferedReadAdapter::BufferedReadAdapter(AsyncSocket* socket, size_t size)
  52. : AsyncSocketAdapter(socket), buffer_size_(size),
  53. data_len_(0), buffering_(false) {
  54. buffer_ = new char[buffer_size_];
  55. }
  56. BufferedReadAdapter::~BufferedReadAdapter() {
  57. delete [] buffer_;
  58. }
  59. int BufferedReadAdapter::Send(const void *pv, size_t cb) {
  60. if (buffering_) {
  61. // TODO: Spoof error better; Signal Writeable
  62. socket_->SetError(EWOULDBLOCK);
  63. return -1;
  64. }
  65. return AsyncSocketAdapter::Send(pv, cb);
  66. }
  67. int BufferedReadAdapter::Recv(void *pv, size_t cb) {
  68. if (buffering_) {
  69. socket_->SetError(EWOULDBLOCK);
  70. return -1;
  71. }
  72. size_t read = 0;
  73. if (data_len_) {
  74. read = _min(cb, data_len_);
  75. memcpy(pv, buffer_, read);
  76. data_len_ -= read;
  77. if (data_len_ > 0) {
  78. memmove(buffer_, buffer_ + read, data_len_);
  79. }
  80. pv = static_cast<char *>(pv) + read;
  81. cb -= read;
  82. }
  83. // FIX: If cb == 0, we won't generate another read event
  84. int res = AsyncSocketAdapter::Recv(pv, cb);
  85. if (res < 0)
  86. return res;
  87. return res + static_cast<int>(read);
  88. }
  89. void BufferedReadAdapter::BufferInput(bool on) {
  90. buffering_ = on;
  91. }
  92. void BufferedReadAdapter::OnReadEvent(AsyncSocket * socket) {
  93. ASSERT(socket == socket_);
  94. if (!buffering_) {
  95. AsyncSocketAdapter::OnReadEvent(socket);
  96. return;
  97. }
  98. if (data_len_ >= buffer_size_) {
  99. LOG(INFO) << "Input buffer overflow";
  100. ASSERT(false);
  101. data_len_ = 0;
  102. }
  103. int len = socket_->Recv(buffer_ + data_len_, buffer_size_ - data_len_);
  104. if (len < 0) {
  105. // TODO: Do something better like forwarding the error to the user.
  106. LOG_ERR(INFO) << "Recv";
  107. return;
  108. }
  109. data_len_ += len;
  110. ProcessInput(buffer_, &data_len_);
  111. }
  112. ///////////////////////////////////////////////////////////////////////////////
  113. // This is a SSL v2 CLIENT_HELLO message.
  114. // TODO: Should this have a session id? The response doesn't have a
  115. // certificate, so the hello should have a session id.
  116. static const uint8 kSslClientHello[] = {
  117. 0x80, 0x46, // msg len
  118. 0x01, // CLIENT_HELLO
  119. 0x03, 0x01, // SSL 3.1
  120. 0x00, 0x2d, // ciphersuite len
  121. 0x00, 0x00, // session id len
  122. 0x00, 0x10, // challenge len
  123. 0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0, // ciphersuites
  124. 0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80, //
  125. 0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a, //
  126. 0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, //
  127. 0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06, //
  128. 0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc, // challenge
  129. 0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea //
  130. };
  131. // This is a TLSv1 SERVER_HELLO message.
  132. static const uint8 kSslServerHello[] = {
  133. 0x16, // handshake message
  134. 0x03, 0x01, // SSL 3.1
  135. 0x00, 0x4a, // message len
  136. 0x02, // SERVER_HELLO
  137. 0x00, 0x00, 0x46, // handshake len
  138. 0x03, 0x01, // SSL 3.1
  139. 0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0, // server random
  140. 0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f, //
  141. 0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1, //
  142. 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f, //
  143. 0x20, // session id len
  144. 0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f, // session id
  145. 0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b, //
  146. 0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38, //
  147. 0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c, //
  148. 0x00, 0x04, // RSA/RC4-128/MD5
  149. 0x00 // null compression
  150. };
  151. AsyncSSLSocket::AsyncSSLSocket(AsyncSocket* socket)
  152. : BufferedReadAdapter(socket, 1024) {
  153. }
  154. int AsyncSSLSocket::Connect(const SocketAddress& addr) {
  155. // Begin buffering before we connect, so that there isn't a race condition
  156. // between potential senders and receiving the OnConnectEvent signal
  157. BufferInput(true);
  158. return BufferedReadAdapter::Connect(addr);
  159. }
  160. void AsyncSSLSocket::OnConnectEvent(AsyncSocket * socket) {
  161. ASSERT(socket == socket_);
  162. // TODO: we could buffer output too...
  163. VERIFY(sizeof(kSslClientHello) ==
  164. DirectSend(kSslClientHello, sizeof(kSslClientHello)));
  165. }
  166. void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
  167. if (*len < sizeof(kSslServerHello))
  168. return;
  169. if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
  170. Close();
  171. SignalCloseEvent(this, 0); // TODO: error code?
  172. return;
  173. }
  174. *len -= sizeof(kSslServerHello);
  175. if (*len > 0) {
  176. memmove(data, data + sizeof(kSslServerHello), *len);
  177. }
  178. bool remainder = (*len > 0);
  179. BufferInput(false);
  180. SignalConnectEvent(this);
  181. // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
  182. if (remainder)
  183. SignalReadEvent(this);
  184. }
  185. AsyncSSLServerSocket::AsyncSSLServerSocket(AsyncSocket* socket)
  186. : BufferedReadAdapter(socket, 1024) {
  187. BufferInput(true);
  188. }
  189. void AsyncSSLServerSocket::ProcessInput(char* data, size_t* len) {
  190. // We only accept client hello messages.
  191. if (*len < sizeof(kSslClientHello)) {
  192. return;
  193. }
  194. if (memcmp(kSslClientHello, data, sizeof(kSslClientHello)) != 0) {
  195. Close();
  196. SignalCloseEvent(this, 0);
  197. return;
  198. }
  199. *len -= sizeof(kSslClientHello);
  200. // Clients should not send more data until the handshake is completed.
  201. ASSERT(*len == 0);
  202. // Send a server hello back to the client.
  203. DirectSend(kSslServerHello, sizeof(kSslServerHello));
  204. // Handshake completed for us, redirect input to our parent.
  205. BufferInput(false);
  206. }
  207. ///////////////////////////////////////////////////////////////////////////////
  208. AsyncHttpsProxySocket::AsyncHttpsProxySocket(AsyncSocket* socket,
  209. const std::string& user_agent,
  210. const SocketAddress& proxy,
  211. const std::string& username,
  212. const CryptString& password)
  213. : BufferedReadAdapter(socket, 1024), proxy_(proxy), agent_(user_agent),
  214. user_(username), pass_(password), force_connect_(false), state_(PS_ERROR),
  215. context_(0) {
  216. }
  217. AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
  218. delete context_;
  219. }
  220. int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
  221. int ret;
  222. LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
  223. << proxy_.ToString() << ")";
  224. dest_ = addr;
  225. state_ = PS_INIT;
  226. if (ShouldIssueConnect()) {
  227. BufferInput(true);
  228. }
  229. ret = BufferedReadAdapter::Connect(proxy_);
  230. // TODO: Set state_ appropriately if Connect fails.
  231. return ret;
  232. }
  233. SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
  234. return dest_;
  235. }
  236. int AsyncHttpsProxySocket::Close() {
  237. headers_.clear();
  238. state_ = PS_ERROR;
  239. dest_.Clear();
  240. delete context_;
  241. context_ = NULL;
  242. return BufferedReadAdapter::Close();
  243. }
  244. Socket::ConnState AsyncHttpsProxySocket::GetState() const {
  245. if (state_ < PS_TUNNEL) {
  246. return CS_CONNECTING;
  247. } else if (state_ == PS_TUNNEL) {
  248. return CS_CONNECTED;
  249. } else {
  250. return CS_CLOSED;
  251. }
  252. }
  253. void AsyncHttpsProxySocket::OnConnectEvent(AsyncSocket * socket) {
  254. LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
  255. if (!ShouldIssueConnect()) {
  256. state_ = PS_TUNNEL;
  257. BufferedReadAdapter::OnConnectEvent(socket);
  258. return;
  259. }
  260. SendRequest();
  261. }
  262. void AsyncHttpsProxySocket::OnCloseEvent(AsyncSocket * socket, int err) {
  263. LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
  264. if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
  265. state_ = PS_ERROR;
  266. Connect(dest_);
  267. } else {
  268. BufferedReadAdapter::OnCloseEvent(socket, err);
  269. }
  270. }
  271. void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
  272. size_t start = 0;
  273. for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
  274. if (state_ == PS_SKIP_BODY) {
  275. size_t consume = _min(*len - pos, content_length_);
  276. pos += consume;
  277. start = pos;
  278. content_length_ -= consume;
  279. if (content_length_ == 0) {
  280. EndResponse();
  281. }
  282. continue;
  283. }
  284. if (data[pos++] != '\n')
  285. continue;
  286. size_t len = pos - start - 1;
  287. if ((len > 0) && (data[start + len - 1] == '\r'))
  288. --len;
  289. data[start + len] = 0;
  290. ProcessLine(data + start, len);
  291. start = pos;
  292. }
  293. *len -= start;
  294. if (*len > 0) {
  295. memmove(data, data + start, *len);
  296. }
  297. if (state_ != PS_TUNNEL)
  298. return;
  299. bool remainder = (*len > 0);
  300. BufferInput(false);
  301. SignalConnectEvent(this);
  302. // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
  303. if (remainder)
  304. SignalReadEvent(this); // TODO: signal this??
  305. }
  306. bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
  307. // TODO: Think about whether a more sophisticated test
  308. // than dest port == 80 is needed.
  309. return force_connect_ || (dest_.port() != 80);
  310. }
  311. void AsyncHttpsProxySocket::SendRequest() {
  312. std::stringstream ss;
  313. ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
  314. ss << "User-Agent: " << agent_ << "\r\n";
  315. ss << "Host: " << dest_.HostAsURIString() << "\r\n";
  316. ss << "Content-Length: 0\r\n";
  317. ss << "Proxy-Connection: Keep-Alive\r\n";
  318. ss << headers_;
  319. ss << "\r\n";
  320. std::string str = ss.str();
  321. DirectSend(str.c_str(), str.size());
  322. state_ = PS_LEADER;
  323. expect_close_ = true;
  324. content_length_ = 0;
  325. headers_.clear();
  326. LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
  327. }
  328. void AsyncHttpsProxySocket::ProcessLine(char * data, size_t len) {
  329. LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
  330. if (len == 0) {
  331. if (state_ == PS_TUNNEL_HEADERS) {
  332. state_ = PS_TUNNEL;
  333. } else if (state_ == PS_ERROR_HEADERS) {
  334. Error(defer_error_);
  335. return;
  336. } else if (state_ == PS_SKIP_HEADERS) {
  337. if (content_length_) {
  338. state_ = PS_SKIP_BODY;
  339. } else {
  340. EndResponse();
  341. return;
  342. }
  343. } else {
  344. static bool report = false;
  345. if (!unknown_mechanisms_.empty() && !report) {
  346. report = true;
  347. std::string msg(
  348. "Unable to connect to the Google Talk service due to an incompatibility "
  349. "with your proxy.\r\nPlease help us resolve this issue by submitting the "
  350. "following information to us using our technical issue submission form "
  351. "at:\r\n\r\n"
  352. "http://www.google.com/support/talk/bin/request.py\r\n\r\n"
  353. "We apologize for the inconvenience.\r\n\r\n"
  354. "Information to submit to Google: "
  355. );
  356. //std::string msg("Please report the following information to foo@bar.com:\r\nUnknown methods: ");
  357. msg.append(unknown_mechanisms_);
  358. #ifdef WIN32
  359. MessageBoxA(0, msg.c_str(), "Oops!", MB_OK);
  360. #endif
  361. #ifdef POSIX
  362. // TODO: Raise a signal so the UI can be separated.
  363. LOG(LS_ERROR) << "Oops!\n\n" << msg;
  364. #endif
  365. }
  366. // Unexpected end of headers
  367. Error(0);
  368. return;
  369. }
  370. } else if (state_ == PS_LEADER) {
  371. unsigned int code;
  372. if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
  373. Error(0);
  374. return;
  375. }
  376. switch (code) {
  377. case 200:
  378. // connection good!
  379. state_ = PS_TUNNEL_HEADERS;
  380. return;
  381. #if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
  382. #error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
  383. #endif
  384. case 407: // HTTP_STATUS_PROXY_AUTH_REQ
  385. state_ = PS_AUTHENTICATE;
  386. return;
  387. default:
  388. defer_error_ = 0;
  389. state_ = PS_ERROR_HEADERS;
  390. return;
  391. }
  392. } else if ((state_ == PS_AUTHENTICATE)
  393. && (_strnicmp(data, "Proxy-Authenticate:", 19) == 0)) {
  394. std::string response, auth_method;
  395. switch (HttpAuthenticate(data + 19, len - 19,
  396. proxy_, "CONNECT", "/",
  397. user_, pass_, context_, response, auth_method)) {
  398. case HAR_IGNORE:
  399. LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
  400. if (!unknown_mechanisms_.empty())
  401. unknown_mechanisms_.append(", ");
  402. unknown_mechanisms_.append(auth_method);
  403. break;
  404. case HAR_RESPONSE:
  405. headers_ = "Proxy-Authorization: ";
  406. headers_.append(response);
  407. headers_.append("\r\n");
  408. state_ = PS_SKIP_HEADERS;
  409. unknown_mechanisms_.clear();
  410. break;
  411. case HAR_CREDENTIALS:
  412. defer_error_ = SOCKET_EACCES;
  413. state_ = PS_ERROR_HEADERS;
  414. unknown_mechanisms_.clear();
  415. break;
  416. case HAR_ERROR:
  417. defer_error_ = 0;
  418. state_ = PS_ERROR_HEADERS;
  419. unknown_mechanisms_.clear();
  420. break;
  421. }
  422. } else if (_strnicmp(data, "Content-Length:", 15) == 0) {
  423. content_length_ = strtoul(data + 15, 0, 0);
  424. } else if (_strnicmp(data, "Proxy-Connection: Keep-Alive", 28) == 0) {
  425. expect_close_ = false;
  426. /*
  427. } else if (_strnicmp(data, "Connection: close", 17) == 0) {
  428. expect_close_ = true;
  429. */
  430. }
  431. }
  432. void AsyncHttpsProxySocket::EndResponse() {
  433. if (!expect_close_) {
  434. SendRequest();
  435. return;
  436. }
  437. // No point in waiting for the server to close... let's close now
  438. // TODO: Refactor out PS_WAIT_CLOSE
  439. state_ = PS_WAIT_CLOSE;
  440. BufferedReadAdapter::Close();
  441. OnCloseEvent(this, 0);
  442. }
  443. void AsyncHttpsProxySocket::Error(int error) {
  444. BufferInput(false);
  445. Close();
  446. SetError(error);
  447. SignalCloseEvent(this, error);
  448. }
  449. ///////////////////////////////////////////////////////////////////////////////
  450. AsyncSocksProxySocket::AsyncSocksProxySocket(AsyncSocket* socket,
  451. const SocketAddress& proxy,
  452. const std::string& username,
  453. const CryptString& password)
  454. : BufferedReadAdapter(socket, 1024), state_(SS_ERROR), proxy_(proxy),
  455. user_(username), pass_(password) {
  456. }
  457. int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
  458. int ret;
  459. dest_ = addr;
  460. state_ = SS_INIT;
  461. BufferInput(true);
  462. ret = BufferedReadAdapter::Connect(proxy_);
  463. // TODO: Set state_ appropriately if Connect fails.
  464. return ret;
  465. }
  466. SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
  467. return dest_;
  468. }
  469. int AsyncSocksProxySocket::Close() {
  470. state_ = SS_ERROR;
  471. dest_.Clear();
  472. return BufferedReadAdapter::Close();
  473. }
  474. Socket::ConnState AsyncSocksProxySocket::GetState() const {
  475. if (state_ < SS_TUNNEL) {
  476. return CS_CONNECTING;
  477. } else if (state_ == SS_TUNNEL) {
  478. return CS_CONNECTED;
  479. } else {
  480. return CS_CLOSED;
  481. }
  482. }
  483. void AsyncSocksProxySocket::OnConnectEvent(AsyncSocket* socket) {
  484. SendHello();
  485. }
  486. void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
  487. ASSERT(state_ < SS_TUNNEL);
  488. ByteBuffer response(data, *len);
  489. if (state_ == SS_HELLO) {
  490. uint8 ver, method;
  491. if (!response.ReadUInt8(&ver) ||
  492. !response.ReadUInt8(&method))
  493. return;
  494. if (ver != 5) {
  495. Error(0);
  496. return;
  497. }
  498. if (method == 0) {
  499. SendConnect();
  500. } else if (method == 2) {
  501. SendAuth();
  502. } else {
  503. Error(0);
  504. return;
  505. }
  506. } else if (state_ == SS_AUTH) {
  507. uint8 ver, status;
  508. if (!response.ReadUInt8(&ver) ||
  509. !response.ReadUInt8(&status))
  510. return;
  511. if ((ver != 1) || (status != 0)) {
  512. Error(SOCKET_EACCES);
  513. return;
  514. }
  515. SendConnect();
  516. } else if (state_ == SS_CONNECT) {
  517. uint8 ver, rep, rsv, atyp;
  518. if (!response.ReadUInt8(&ver) ||
  519. !response.ReadUInt8(&rep) ||
  520. !response.ReadUInt8(&rsv) ||
  521. !response.ReadUInt8(&atyp))
  522. return;
  523. if ((ver != 5) || (rep != 0)) {
  524. Error(0);
  525. return;
  526. }
  527. uint16 port;
  528. if (atyp == 1) {
  529. uint32 addr;
  530. if (!response.ReadUInt32(&addr) ||
  531. !response.ReadUInt16(&port))
  532. return;
  533. LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
  534. } else if (atyp == 3) {
  535. uint8 len;
  536. std::string addr;
  537. if (!response.ReadUInt8(&len) ||
  538. !response.ReadString(&addr, len) ||
  539. !response.ReadUInt16(&port))
  540. return;
  541. LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
  542. } else if (atyp == 4) {
  543. std::string addr;
  544. if (!response.ReadString(&addr, 16) ||
  545. !response.ReadUInt16(&port))
  546. return;
  547. LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
  548. } else {
  549. Error(0);
  550. return;
  551. }
  552. state_ = SS_TUNNEL;
  553. }
  554. // Consume parsed data
  555. *len = response.Length();
  556. memcpy(data, response.Data(), *len);
  557. if (state_ != SS_TUNNEL)
  558. return;
  559. bool remainder = (*len > 0);
  560. BufferInput(false);
  561. SignalConnectEvent(this);
  562. // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
  563. if (remainder)
  564. SignalReadEvent(this); // TODO: signal this??
  565. }
  566. void AsyncSocksProxySocket::SendHello() {
  567. ByteBuffer request;
  568. request.WriteUInt8(5); // Socks Version
  569. if (user_.empty()) {
  570. request.WriteUInt8(1); // Authentication Mechanisms
  571. request.WriteUInt8(0); // No authentication
  572. } else {
  573. request.WriteUInt8(2); // Authentication Mechanisms
  574. request.WriteUInt8(0); // No authentication
  575. request.WriteUInt8(2); // Username/Password
  576. }
  577. DirectSend(request.Data(), request.Length());
  578. state_ = SS_HELLO;
  579. }
  580. void AsyncSocksProxySocket::SendAuth() {
  581. ByteBuffer request;
  582. request.WriteUInt8(1); // Negotiation Version
  583. request.WriteUInt8(static_cast<uint8>(user_.size()));
  584. request.WriteString(user_); // Username
  585. request.WriteUInt8(static_cast<uint8>(pass_.GetLength()));
  586. size_t len = pass_.GetLength() + 1;
  587. char * sensitive = new char[len];
  588. pass_.CopyTo(sensitive, true);
  589. request.WriteString(sensitive); // Password
  590. memset(sensitive, 0, len);
  591. delete [] sensitive;
  592. DirectSend(request.Data(), request.Length());
  593. state_ = SS_AUTH;
  594. }
  595. void AsyncSocksProxySocket::SendConnect() {
  596. ByteBuffer request;
  597. request.WriteUInt8(5); // Socks Version
  598. request.WriteUInt8(1); // CONNECT
  599. request.WriteUInt8(0); // Reserved
  600. if (dest_.IsUnresolved()) {
  601. std::string hostname = dest_.hostname();
  602. request.WriteUInt8(3); // DOMAINNAME
  603. request.WriteUInt8(static_cast<uint8>(hostname.size()));
  604. request.WriteString(hostname); // Destination Hostname
  605. } else {
  606. request.WriteUInt8(1); // IPV4
  607. request.WriteUInt32(dest_.ip()); // Destination IP
  608. }
  609. request.WriteUInt16(dest_.port()); // Destination Port
  610. DirectSend(request.Data(), request.Length());
  611. state_ = SS_CONNECT;
  612. }
  613. void AsyncSocksProxySocket::Error(int error) {
  614. state_ = SS_ERROR;
  615. BufferInput(false);
  616. Close();
  617. SetError(SOCKET_EACCES);
  618. SignalCloseEvent(this, error);
  619. }
  620. AsyncSocksProxyServerSocket::AsyncSocksProxyServerSocket(AsyncSocket* socket)
  621. : AsyncProxyServerSocket(socket, kBufferSize), state_(SS_HELLO) {
  622. BufferInput(true);
  623. }
  624. void AsyncSocksProxyServerSocket::ProcessInput(char* data, size_t* len) {
  625. // TODO: See if the whole message has arrived
  626. ASSERT(state_ < SS_CONNECT_PENDING);
  627. ByteBuffer response(data, *len);
  628. if (state_ == SS_HELLO) {
  629. HandleHello(&response);
  630. } else if (state_ == SS_AUTH) {
  631. HandleAuth(&response);
  632. } else if (state_ == SS_CONNECT) {
  633. HandleConnect(&response);
  634. }
  635. // Consume parsed data
  636. *len = response.Length();
  637. memcpy(data, response.Data(), *len);
  638. }
  639. void AsyncSocksProxyServerSocket::DirectSend(const ByteBuffer& buf) {
  640. BufferedReadAdapter::DirectSend(buf.Data(), buf.Length());
  641. }
  642. void AsyncSocksProxyServerSocket::HandleHello(ByteBuffer* request) {
  643. uint8 ver, num_methods;
  644. if (!request->ReadUInt8(&ver) ||
  645. !request->ReadUInt8(&num_methods)) {
  646. Error(0);
  647. return;
  648. }
  649. if (ver != 5) {
  650. Error(0);
  651. return;
  652. }
  653. // Handle either no-auth (0) or user/pass auth (2)
  654. uint8 method = 0xFF;
  655. if (num_methods > 0 && !request->ReadUInt8(&method)) {
  656. Error(0);
  657. return;
  658. }
  659. // TODO: Ask the server which method to use.
  660. SendHelloReply(method);
  661. if (method == 0) {
  662. state_ = SS_CONNECT;
  663. } else if (method == 2) {
  664. state_ = SS_AUTH;
  665. } else {
  666. state_ = SS_ERROR;
  667. }
  668. }
  669. void AsyncSocksProxyServerSocket::SendHelloReply(int method) {
  670. ByteBuffer response;
  671. response.WriteUInt8(5); // Socks Version
  672. response.WriteUInt8(method); // Auth method
  673. DirectSend(response);
  674. }
  675. void AsyncSocksProxyServerSocket::HandleAuth(ByteBuffer* request) {
  676. uint8 ver, user_len, pass_len;
  677. std::string user, pass;
  678. if (!request->ReadUInt8(&ver) ||
  679. !request->ReadUInt8(&user_len) ||
  680. !request->ReadString(&user, user_len) ||
  681. !request->ReadUInt8(&pass_len) ||
  682. !request->ReadString(&pass, pass_len)) {
  683. Error(0);
  684. return;
  685. }
  686. // TODO: Allow for checking of credentials.
  687. SendAuthReply(0);
  688. state_ = SS_CONNECT;
  689. }
  690. void AsyncSocksProxyServerSocket::SendAuthReply(int result) {
  691. ByteBuffer response;
  692. response.WriteUInt8(1); // Negotiation Version
  693. response.WriteUInt8(result);
  694. DirectSend(response);
  695. }
  696. void AsyncSocksProxyServerSocket::HandleConnect(ByteBuffer* request) {
  697. uint8 ver, command, reserved, addr_type;
  698. uint32 ip;
  699. uint16 port;
  700. if (!request->ReadUInt8(&ver) ||
  701. !request->ReadUInt8(&command) ||
  702. !request->ReadUInt8(&reserved) ||
  703. !request->ReadUInt8(&addr_type) ||
  704. !request->ReadUInt32(&ip) ||
  705. !request->ReadUInt16(&port)) {
  706. Error(0);
  707. return;
  708. }
  709. if (ver != 5 || command != 1 ||
  710. reserved != 0 || addr_type != 1) {
  711. Error(0);
  712. return;
  713. }
  714. SignalConnectRequest(this, SocketAddress(ip, port));
  715. state_ = SS_CONNECT_PENDING;
  716. }
  717. void AsyncSocksProxyServerSocket::SendConnectResult(int result,
  718. const SocketAddress& addr) {
  719. if (state_ != SS_CONNECT_PENDING)
  720. return;
  721. ByteBuffer response;
  722. response.WriteUInt8(5); // Socks version
  723. response.WriteUInt8((result != 0)); // 0x01 is generic error
  724. response.WriteUInt8(0); // reserved
  725. response.WriteUInt8(1); // IPv4 address
  726. response.WriteUInt32(addr.ip());
  727. response.WriteUInt16(addr.port());
  728. DirectSend(response);
  729. BufferInput(false);
  730. state_ = SS_TUNNEL;
  731. }
  732. void AsyncSocksProxyServerSocket::Error(int error) {
  733. state_ = SS_ERROR;
  734. BufferInput(false);
  735. Close();
  736. SetError(SOCKET_EACCES);
  737. SignalCloseEvent(this, error);
  738. }
  739. ///////////////////////////////////////////////////////////////////////////////
  740. LoggingSocketAdapter::LoggingSocketAdapter(AsyncSocket* socket,
  741. LoggingSeverity level,
  742. const char * label, bool hex_mode)
  743. : AsyncSocketAdapter(socket), level_(level), hex_mode_(hex_mode) {
  744. label_.append("[");
  745. label_.append(label);
  746. label_.append("]");
  747. }
  748. int LoggingSocketAdapter::Send(const void *pv, size_t cb) {
  749. int res = AsyncSocketAdapter::Send(pv, cb);
  750. if (res > 0)
  751. LogMultiline(level_, label_.c_str(), false, pv, res, hex_mode_, &lms_);
  752. return res;
  753. }
  754. int LoggingSocketAdapter::SendTo(const void *pv, size_t cb,
  755. const SocketAddress& addr) {
  756. int res = AsyncSocketAdapter::SendTo(pv, cb, addr);
  757. if (res > 0)
  758. LogMultiline(level_, label_.c_str(), false, pv, res, hex_mode_, &lms_);
  759. return res;
  760. }
  761. int LoggingSocketAdapter::Recv(void *pv, size_t cb) {
  762. int res = AsyncSocketAdapter::Recv(pv, cb);
  763. if (res > 0)
  764. LogMultiline(level_, label_.c_str(), true, pv, res, hex_mode_, &lms_);
  765. return res;
  766. }
  767. int LoggingSocketAdapter::RecvFrom(void *pv, size_t cb, SocketAddress *paddr) {
  768. int res = AsyncSocketAdapter::RecvFrom(pv, cb, paddr);
  769. if (res > 0)
  770. LogMultiline(level_, label_.c_str(), true, pv, res, hex_mode_, &lms_);
  771. return res;
  772. }
  773. int LoggingSocketAdapter::Close() {
  774. LogMultiline(level_, label_.c_str(), false, NULL, 0, hex_mode_, &lms_);
  775. LogMultiline(level_, label_.c_str(), true, NULL, 0, hex_mode_, &lms_);
  776. LOG_V(level_) << label_ << " Closed locally";
  777. return socket_->Close();
  778. }
  779. void LoggingSocketAdapter::OnConnectEvent(AsyncSocket * socket) {
  780. LOG_V(level_) << label_ << " Connected";
  781. AsyncSocketAdapter::OnConnectEvent(socket);
  782. }
  783. void LoggingSocketAdapter::OnCloseEvent(AsyncSocket * socket, int err) {
  784. LogMultiline(level_, label_.c_str(), false, NULL, 0, hex_mode_, &lms_);
  785. LogMultiline(level_, label_.c_str(), true, NULL, 0, hex_mode_, &lms_);
  786. LOG_V(level_) << label_ << " Closed with error: " << err;
  787. AsyncSocketAdapter::OnCloseEvent(socket, err);
  788. }
  789. ///////////////////////////////////////////////////////////////////////////////
  790. } // namespace talk_base