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