blob: acd9b633858c8814f6d4b8f86ca1d9d3d5184e81 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
Yves Gerey665174f2018-06-19 15:03:05 +020012#pragma warning(disable : 4786)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013#endif
14
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015#include <errno.h>
Yves Gerey665174f2018-06-19 15:03:05 +020016#include <time.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017
18#if defined(WEBRTC_WIN)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#include <windows.h>
20#include <winsock2.h>
21#include <ws2tcpip.h>
22#define SECURITY_WIN32
23#include <security.h>
24#endif
25
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000026#include <algorithm>
27
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/bytebuffer.h"
29#include "rtc_base/checks.h"
30#include "rtc_base/httpcommon.h"
31#include "rtc_base/logging.h"
32#include "rtc_base/socketadapters.h"
33#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020034#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/stringutils.h"
Joachim Bauch5b32f232018-03-07 20:02:26 +010036#include "rtc_base/zero_memory.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000038namespace rtc {
39
40BufferedReadAdapter::BufferedReadAdapter(AsyncSocket* socket, size_t size)
Yves Gerey665174f2018-06-19 15:03:05 +020041 : AsyncSocketAdapter(socket),
42 buffer_size_(size),
43 data_len_(0),
44 buffering_(false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000045 buffer_ = new char[buffer_size_];
46}
47
48BufferedReadAdapter::~BufferedReadAdapter() {
Yves Gerey665174f2018-06-19 15:03:05 +020049 delete[] buffer_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050}
51
Yves Gerey665174f2018-06-19 15:03:05 +020052int BufferedReadAdapter::Send(const void* pv, size_t cb) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053 if (buffering_) {
54 // TODO: Spoof error better; Signal Writeable
55 socket_->SetError(EWOULDBLOCK);
56 return -1;
57 }
58 return AsyncSocketAdapter::Send(pv, cb);
59}
60
Stefan Holmer9131efd2016-05-23 18:19:26 +020061int BufferedReadAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062 if (buffering_) {
63 socket_->SetError(EWOULDBLOCK);
64 return -1;
65 }
66
67 size_t read = 0;
68
69 if (data_len_) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000070 read = std::min(cb, data_len_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071 memcpy(pv, buffer_, read);
72 data_len_ -= read;
73 if (data_len_ > 0) {
74 memmove(buffer_, buffer_ + read, data_len_);
75 }
Yves Gerey665174f2018-06-19 15:03:05 +020076 pv = static_cast<char*>(pv) + read;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000077 cb -= read;
78 }
79
80 // FIX: If cb == 0, we won't generate another read event
81
Stefan Holmer9131efd2016-05-23 18:19:26 +020082 int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
deadbeefc5d0d952015-07-16 10:22:21 -070083 if (res >= 0) {
84 // Read from socket and possibly buffer; return combined length
85 return res + static_cast<int>(read);
86 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000087
deadbeefc5d0d952015-07-16 10:22:21 -070088 if (read > 0) {
89 // Failed to read from socket, but still read something from buffer
90 return static_cast<int>(read);
91 }
92
93 // Didn't read anything; return error from socket
94 return res;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000095}
96
97void BufferedReadAdapter::BufferInput(bool on) {
98 buffering_ = on;
99}
100
Yves Gerey665174f2018-06-19 15:03:05 +0200101void BufferedReadAdapter::OnReadEvent(AsyncSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800102 RTC_DCHECK(socket == socket_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103
104 if (!buffering_) {
105 AsyncSocketAdapter::OnReadEvent(socket);
106 return;
107 }
108
109 if (data_len_ >= buffer_size_) {
Jonas Olsson45cc8902018-02-13 10:37:07 +0100110 RTC_LOG(LS_ERROR) << "Input buffer overflow";
nissec80e7412017-01-11 05:56:46 -0800111 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000112 data_len_ = 0;
113 }
114
Stefan Holmer9131efd2016-05-23 18:19:26 +0200115 int len =
116 socket_->Recv(buffer_ + data_len_, buffer_size_ - data_len_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000117 if (len < 0) {
118 // TODO: Do something better like forwarding the error to the user.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100119 RTC_LOG_ERR(INFO) << "Recv";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000120 return;
121 }
122
123 data_len_ += len;
124
125 ProcessInput(buffer_, &data_len_);
126}
127
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000128AsyncProxyServerSocket::AsyncProxyServerSocket(AsyncSocket* socket,
129 size_t buffer_size)
Yves Gerey665174f2018-06-19 15:03:05 +0200130 : BufferedReadAdapter(socket, buffer_size) {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000131
132AsyncProxyServerSocket::~AsyncProxyServerSocket() = default;
133
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134///////////////////////////////////////////////////////////////////////////////
135
136// This is a SSL v2 CLIENT_HELLO message.
137// TODO: Should this have a session id? The response doesn't have a
138// certificate, so the hello should have a session id.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200139static const uint8_t kSslClientHello[] = {
140 0x80, 0x46, // msg len
141 0x01, // CLIENT_HELLO
142 0x03, 0x01, // SSL 3.1
143 0x00, 0x2d, // ciphersuite len
144 0x00, 0x00, // session id len
145 0x00, 0x10, // challenge len
146 0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0, // ciphersuites
147 0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80, //
148 0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a, //
149 0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, //
150 0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06, //
151 0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc, // challenge
152 0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea //
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000153};
154
155// This is a TLSv1 SERVER_HELLO message.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200156static const uint8_t kSslServerHello[] = {
157 0x16, // handshake message
158 0x03, 0x01, // SSL 3.1
159 0x00, 0x4a, // message len
160 0x02, // SERVER_HELLO
161 0x00, 0x00, 0x46, // handshake len
162 0x03, 0x01, // SSL 3.1
163 0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0, // server random
164 0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f, //
165 0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1, //
166 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f, //
167 0x20, // session id len
168 0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f, // session id
169 0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b, //
170 0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38, //
171 0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c, //
172 0x00, 0x04, // RSA/RC4-128/MD5
173 0x00 // null compression
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000174};
175
176AsyncSSLSocket::AsyncSSLSocket(AsyncSocket* socket)
Yves Gerey665174f2018-06-19 15:03:05 +0200177 : BufferedReadAdapter(socket, 1024) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178
179int AsyncSSLSocket::Connect(const SocketAddress& addr) {
180 // Begin buffering before we connect, so that there isn't a race condition
181 // between potential senders and receiving the OnConnectEvent signal
182 BufferInput(true);
183 return BufferedReadAdapter::Connect(addr);
184}
185
Yves Gerey665174f2018-06-19 15:03:05 +0200186void AsyncSSLSocket::OnConnectEvent(AsyncSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800187 RTC_DCHECK(socket == socket_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000188 // TODO: we could buffer output too...
nissec16fa5e2017-02-07 07:18:43 -0800189 const int res = DirectSend(kSslClientHello, sizeof(kSslClientHello));
190 RTC_DCHECK_EQ(sizeof(kSslClientHello), res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000191}
192
193void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
194 if (*len < sizeof(kSslServerHello))
195 return;
196
197 if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
198 Close();
199 SignalCloseEvent(this, 0); // TODO: error code?
200 return;
201 }
202
203 *len -= sizeof(kSslServerHello);
204 if (*len > 0) {
205 memmove(data, data + sizeof(kSslServerHello), *len);
206 }
207
208 bool remainder = (*len > 0);
209 BufferInput(false);
210 SignalConnectEvent(this);
211
212 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
213 if (remainder)
214 SignalReadEvent(this);
215}
216
217AsyncSSLServerSocket::AsyncSSLServerSocket(AsyncSocket* socket)
Yves Gerey665174f2018-06-19 15:03:05 +0200218 : BufferedReadAdapter(socket, 1024) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000219 BufferInput(true);
220}
221
222void AsyncSSLServerSocket::ProcessInput(char* data, size_t* len) {
223 // We only accept client hello messages.
224 if (*len < sizeof(kSslClientHello)) {
225 return;
226 }
227
228 if (memcmp(kSslClientHello, data, sizeof(kSslClientHello)) != 0) {
229 Close();
230 SignalCloseEvent(this, 0);
231 return;
232 }
233
234 *len -= sizeof(kSslClientHello);
235
236 // Clients should not send more data until the handshake is completed.
nisseede5da42017-01-12 05:15:36 -0800237 RTC_DCHECK(*len == 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000238
239 // Send a server hello back to the client.
240 DirectSend(kSslServerHello, sizeof(kSslServerHello));
241
242 // Handshake completed for us, redirect input to our parent.
243 BufferInput(false);
244}
245
deadbeeff137e972017-03-23 15:45:49 -0700246///////////////////////////////////////////////////////////////////////////////
247
248AsyncHttpsProxySocket::AsyncHttpsProxySocket(AsyncSocket* socket,
249 const std::string& user_agent,
250 const SocketAddress& proxy,
251 const std::string& username,
252 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200253 : BufferedReadAdapter(socket, 1024),
254 proxy_(proxy),
255 agent_(user_agent),
256 user_(username),
257 pass_(password),
258 force_connect_(false),
259 state_(PS_ERROR),
260 context_(0) {}
deadbeeff137e972017-03-23 15:45:49 -0700261
262AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
263 delete context_;
264}
265
266int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
267 int ret;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100268 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
269 << proxy_.ToSensitiveString() << ")";
deadbeeff137e972017-03-23 15:45:49 -0700270 dest_ = addr;
271 state_ = PS_INIT;
272 if (ShouldIssueConnect()) {
273 BufferInput(true);
274 }
275 ret = BufferedReadAdapter::Connect(proxy_);
276 // TODO: Set state_ appropriately if Connect fails.
277 return ret;
278}
279
280SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
281 return dest_;
282}
283
284int AsyncHttpsProxySocket::Close() {
285 headers_.clear();
286 state_ = PS_ERROR;
287 dest_.Clear();
288 delete context_;
289 context_ = nullptr;
290 return BufferedReadAdapter::Close();
291}
292
293Socket::ConnState AsyncHttpsProxySocket::GetState() const {
294 if (state_ < PS_TUNNEL) {
295 return CS_CONNECTING;
296 } else if (state_ == PS_TUNNEL) {
297 return CS_CONNECTED;
298 } else {
299 return CS_CLOSED;
300 }
301}
302
Yves Gerey665174f2018-06-19 15:03:05 +0200303void AsyncHttpsProxySocket::OnConnectEvent(AsyncSocket* socket) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100304 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
deadbeeff137e972017-03-23 15:45:49 -0700305 if (!ShouldIssueConnect()) {
306 state_ = PS_TUNNEL;
307 BufferedReadAdapter::OnConnectEvent(socket);
308 return;
309 }
310 SendRequest();
311}
312
Yves Gerey665174f2018-06-19 15:03:05 +0200313void AsyncHttpsProxySocket::OnCloseEvent(AsyncSocket* socket, int err) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100314 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
deadbeeff137e972017-03-23 15:45:49 -0700315 if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
316 state_ = PS_ERROR;
317 Connect(dest_);
318 } else {
319 BufferedReadAdapter::OnCloseEvent(socket, err);
320 }
321}
322
323void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
324 size_t start = 0;
325 for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
326 if (state_ == PS_SKIP_BODY) {
327 size_t consume = std::min(*len - pos, content_length_);
328 pos += consume;
329 start = pos;
330 content_length_ -= consume;
331 if (content_length_ == 0) {
332 EndResponse();
333 }
334 continue;
335 }
336
337 if (data[pos++] != '\n')
338 continue;
339
340 size_t len = pos - start - 1;
341 if ((len > 0) && (data[start + len - 1] == '\r'))
342 --len;
343
344 data[start + len] = 0;
345 ProcessLine(data + start, len);
346 start = pos;
347 }
348
349 *len -= start;
350 if (*len > 0) {
351 memmove(data, data + start, *len);
352 }
353
354 if (state_ != PS_TUNNEL)
355 return;
356
357 bool remainder = (*len > 0);
358 BufferInput(false);
359 SignalConnectEvent(this);
360
361 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
362 if (remainder)
363 SignalReadEvent(this); // TODO: signal this??
364}
365
366bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
367 // TODO: Think about whether a more sophisticated test
368 // than dest port == 80 is needed.
369 return force_connect_ || (dest_.port() != 80);
370}
371
372void AsyncHttpsProxySocket::SendRequest() {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200373 rtc::StringBuilder ss;
deadbeeff137e972017-03-23 15:45:49 -0700374 ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
375 ss << "User-Agent: " << agent_ << "\r\n";
376 ss << "Host: " << dest_.HostAsURIString() << "\r\n";
377 ss << "Content-Length: 0\r\n";
378 ss << "Proxy-Connection: Keep-Alive\r\n";
379 ss << headers_;
380 ss << "\r\n";
381 std::string str = ss.str();
382 DirectSend(str.c_str(), str.size());
383 state_ = PS_LEADER;
384 expect_close_ = true;
385 content_length_ = 0;
386 headers_.clear();
387
Mirko Bonadei675513b2017-11-09 11:09:25 +0100388 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
deadbeeff137e972017-03-23 15:45:49 -0700389}
390
Yves Gerey665174f2018-06-19 15:03:05 +0200391void AsyncHttpsProxySocket::ProcessLine(char* data, size_t len) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100392 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
deadbeeff137e972017-03-23 15:45:49 -0700393
394 if (len == 0) {
395 if (state_ == PS_TUNNEL_HEADERS) {
396 state_ = PS_TUNNEL;
397 } else if (state_ == PS_ERROR_HEADERS) {
398 Error(defer_error_);
399 return;
400 } else if (state_ == PS_SKIP_HEADERS) {
401 if (content_length_) {
402 state_ = PS_SKIP_BODY;
403 } else {
404 EndResponse();
405 return;
406 }
407 } else {
408 static bool report = false;
409 if (!unknown_mechanisms_.empty() && !report) {
410 report = true;
411 std::string msg(
Yves Gerey665174f2018-06-19 15:03:05 +0200412 "Unable to connect to the Google Talk service due to an "
413 "incompatibility "
414 "with your proxy.\r\nPlease help us resolve this issue by "
415 "submitting the "
416 "following information to us using our technical issue submission "
417 "form "
418 "at:\r\n\r\n"
419 "http://www.google.com/support/talk/bin/request.py\r\n\r\n"
420 "We apologize for the inconvenience.\r\n\r\n"
421 "Information to submit to Google: ");
422 // std::string msg("Please report the following information to
423 // foo@bar.com:\r\nUnknown methods: ");
deadbeeff137e972017-03-23 15:45:49 -0700424 msg.append(unknown_mechanisms_);
425#if defined(WEBRTC_WIN)
426 MessageBoxA(0, msg.c_str(), "Oops!", MB_OK);
427#endif
428#if defined(WEBRTC_POSIX)
429 // TODO: Raise a signal so the UI can be separated.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100430 RTC_LOG(LS_ERROR) << "Oops!\n\n" << msg;
deadbeeff137e972017-03-23 15:45:49 -0700431#endif
432 }
433 // Unexpected end of headers
434 Error(0);
435 return;
436 }
437 } else if (state_ == PS_LEADER) {
438 unsigned int code;
439 if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
440 Error(0);
441 return;
442 }
443 switch (code) {
Yves Gerey665174f2018-06-19 15:03:05 +0200444 case 200:
445 // connection good!
446 state_ = PS_TUNNEL_HEADERS;
447 return;
deadbeeff137e972017-03-23 15:45:49 -0700448#if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
449#error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
450#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200451 case 407: // HTTP_STATUS_PROXY_AUTH_REQ
452 state_ = PS_AUTHENTICATE;
453 return;
454 default:
455 defer_error_ = 0;
456 state_ = PS_ERROR_HEADERS;
457 return;
deadbeeff137e972017-03-23 15:45:49 -0700458 }
Yves Gerey665174f2018-06-19 15:03:05 +0200459 } else if ((state_ == PS_AUTHENTICATE) &&
460 (_strnicmp(data, "Proxy-Authenticate:", 19) == 0)) {
deadbeeff137e972017-03-23 15:45:49 -0700461 std::string response, auth_method;
Yves Gerey665174f2018-06-19 15:03:05 +0200462 switch (HttpAuthenticate(data + 19, len - 19, proxy_, "CONNECT", "/", user_,
463 pass_, context_, response, auth_method)) {
464 case HAR_IGNORE:
465 RTC_LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
466 if (!unknown_mechanisms_.empty())
467 unknown_mechanisms_.append(", ");
468 unknown_mechanisms_.append(auth_method);
469 break;
470 case HAR_RESPONSE:
471 headers_ = "Proxy-Authorization: ";
472 headers_.append(response);
473 headers_.append("\r\n");
474 state_ = PS_SKIP_HEADERS;
475 unknown_mechanisms_.clear();
476 break;
477 case HAR_CREDENTIALS:
478 defer_error_ = SOCKET_EACCES;
479 state_ = PS_ERROR_HEADERS;
480 unknown_mechanisms_.clear();
481 break;
482 case HAR_ERROR:
483 defer_error_ = 0;
484 state_ = PS_ERROR_HEADERS;
485 unknown_mechanisms_.clear();
486 break;
deadbeeff137e972017-03-23 15:45:49 -0700487 }
488 } else if (_strnicmp(data, "Content-Length:", 15) == 0) {
489 content_length_ = strtoul(data + 15, 0, 0);
490 } else if (_strnicmp(data, "Proxy-Connection: Keep-Alive", 28) == 0) {
491 expect_close_ = false;
492 /*
493 } else if (_strnicmp(data, "Connection: close", 17) == 0) {
494 expect_close_ = true;
495 */
496 }
497}
498
499void AsyncHttpsProxySocket::EndResponse() {
500 if (!expect_close_) {
501 SendRequest();
502 return;
503 }
504
505 // No point in waiting for the server to close... let's close now
506 // TODO: Refactor out PS_WAIT_CLOSE
507 state_ = PS_WAIT_CLOSE;
508 BufferedReadAdapter::Close();
509 OnCloseEvent(this, 0);
510}
511
512void AsyncHttpsProxySocket::Error(int error) {
513 BufferInput(false);
514 Close();
515 SetError(error);
516 SignalCloseEvent(this, error);
517}
518
519///////////////////////////////////////////////////////////////////////////////
520
521AsyncSocksProxySocket::AsyncSocksProxySocket(AsyncSocket* socket,
522 const SocketAddress& proxy,
523 const std::string& username,
524 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200525 : BufferedReadAdapter(socket, 1024),
526 state_(SS_ERROR),
527 proxy_(proxy),
528 user_(username),
529 pass_(password) {}
deadbeeff137e972017-03-23 15:45:49 -0700530
531AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
532
533int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
534 int ret;
535 dest_ = addr;
536 state_ = SS_INIT;
537 BufferInput(true);
538 ret = BufferedReadAdapter::Connect(proxy_);
539 // TODO: Set state_ appropriately if Connect fails.
540 return ret;
541}
542
543SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
544 return dest_;
545}
546
547int AsyncSocksProxySocket::Close() {
548 state_ = SS_ERROR;
549 dest_.Clear();
550 return BufferedReadAdapter::Close();
551}
552
553Socket::ConnState AsyncSocksProxySocket::GetState() const {
554 if (state_ < SS_TUNNEL) {
555 return CS_CONNECTING;
556 } else if (state_ == SS_TUNNEL) {
557 return CS_CONNECTED;
558 } else {
559 return CS_CLOSED;
560 }
561}
562
563void AsyncSocksProxySocket::OnConnectEvent(AsyncSocket* socket) {
564 SendHello();
565}
566
567void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
568 RTC_DCHECK(state_ < SS_TUNNEL);
569
570 ByteBufferReader response(data, *len);
571
572 if (state_ == SS_HELLO) {
573 uint8_t ver, method;
Yves Gerey665174f2018-06-19 15:03:05 +0200574 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&method))
deadbeeff137e972017-03-23 15:45:49 -0700575 return;
576
577 if (ver != 5) {
578 Error(0);
579 return;
580 }
581
582 if (method == 0) {
583 SendConnect();
584 } else if (method == 2) {
585 SendAuth();
586 } else {
587 Error(0);
588 return;
589 }
590 } else if (state_ == SS_AUTH) {
591 uint8_t ver, status;
Yves Gerey665174f2018-06-19 15:03:05 +0200592 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&status))
deadbeeff137e972017-03-23 15:45:49 -0700593 return;
594
595 if ((ver != 1) || (status != 0)) {
596 Error(SOCKET_EACCES);
597 return;
598 }
599
600 SendConnect();
601 } else if (state_ == SS_CONNECT) {
602 uint8_t ver, rep, rsv, atyp;
Yves Gerey665174f2018-06-19 15:03:05 +0200603 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&rep) ||
604 !response.ReadUInt8(&rsv) || !response.ReadUInt8(&atyp))
deadbeeff137e972017-03-23 15:45:49 -0700605 return;
606
607 if ((ver != 5) || (rep != 0)) {
608 Error(0);
609 return;
610 }
611
612 uint16_t port;
613 if (atyp == 1) {
614 uint32_t addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200615 if (!response.ReadUInt32(&addr) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700616 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100617 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700618 } else if (atyp == 3) {
619 uint8_t len;
620 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200621 if (!response.ReadUInt8(&len) || !response.ReadString(&addr, len) ||
deadbeeff137e972017-03-23 15:45:49 -0700622 !response.ReadUInt16(&port))
623 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100624 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700625 } else if (atyp == 4) {
626 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200627 if (!response.ReadString(&addr, 16) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700628 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100629 RTC_LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
deadbeeff137e972017-03-23 15:45:49 -0700630 } else {
631 Error(0);
632 return;
633 }
634
635 state_ = SS_TUNNEL;
636 }
637
638 // Consume parsed data
639 *len = response.Length();
640 memmove(data, response.Data(), *len);
641
642 if (state_ != SS_TUNNEL)
643 return;
644
645 bool remainder = (*len > 0);
646 BufferInput(false);
647 SignalConnectEvent(this);
648
649 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
650 if (remainder)
651 SignalReadEvent(this); // TODO: signal this??
652}
653
654void AsyncSocksProxySocket::SendHello() {
655 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200656 request.WriteUInt8(5); // Socks Version
deadbeeff137e972017-03-23 15:45:49 -0700657 if (user_.empty()) {
658 request.WriteUInt8(1); // Authentication Mechanisms
659 request.WriteUInt8(0); // No authentication
660 } else {
661 request.WriteUInt8(2); // Authentication Mechanisms
662 request.WriteUInt8(0); // No authentication
663 request.WriteUInt8(2); // Username/Password
664 }
665 DirectSend(request.Data(), request.Length());
666 state_ = SS_HELLO;
667}
668
669void AsyncSocksProxySocket::SendAuth() {
Joachim Bauch4c6a30c2018-03-08 00:55:33 +0100670 ByteBufferWriterT<ZeroOnFreeBuffer<char>> request;
Yves Gerey665174f2018-06-19 15:03:05 +0200671 request.WriteUInt8(1); // Negotiation Version
deadbeeff137e972017-03-23 15:45:49 -0700672 request.WriteUInt8(static_cast<uint8_t>(user_.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200673 request.WriteString(user_); // Username
deadbeeff137e972017-03-23 15:45:49 -0700674 request.WriteUInt8(static_cast<uint8_t>(pass_.GetLength()));
675 size_t len = pass_.GetLength() + 1;
Yves Gerey665174f2018-06-19 15:03:05 +0200676 char* sensitive = new char[len];
deadbeeff137e972017-03-23 15:45:49 -0700677 pass_.CopyTo(sensitive, true);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100678 request.WriteBytes(sensitive, pass_.GetLength()); // Password
679 ExplicitZeroMemory(sensitive, len);
Yves Gerey665174f2018-06-19 15:03:05 +0200680 delete[] sensitive;
deadbeeff137e972017-03-23 15:45:49 -0700681 DirectSend(request.Data(), request.Length());
682 state_ = SS_AUTH;
683}
684
685void AsyncSocksProxySocket::SendConnect() {
686 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200687 request.WriteUInt8(5); // Socks Version
688 request.WriteUInt8(1); // CONNECT
689 request.WriteUInt8(0); // Reserved
deadbeeff137e972017-03-23 15:45:49 -0700690 if (dest_.IsUnresolvedIP()) {
691 std::string hostname = dest_.hostname();
Yves Gerey665174f2018-06-19 15:03:05 +0200692 request.WriteUInt8(3); // DOMAINNAME
deadbeeff137e972017-03-23 15:45:49 -0700693 request.WriteUInt8(static_cast<uint8_t>(hostname.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200694 request.WriteString(hostname); // Destination Hostname
deadbeeff137e972017-03-23 15:45:49 -0700695 } else {
696 request.WriteUInt8(1); // IPV4
697 request.WriteUInt32(dest_.ip()); // Destination IP
698 }
699 request.WriteUInt16(dest_.port()); // Destination Port
700 DirectSend(request.Data(), request.Length());
701 state_ = SS_CONNECT;
702}
703
704void AsyncSocksProxySocket::Error(int error) {
705 state_ = SS_ERROR;
706 BufferInput(false);
707 Close();
708 SetError(SOCKET_EACCES);
709 SignalCloseEvent(this, error);
710}
711
712AsyncSocksProxyServerSocket::AsyncSocksProxyServerSocket(AsyncSocket* socket)
713 : AsyncProxyServerSocket(socket, kBufferSize), state_(SS_HELLO) {
714 BufferInput(true);
715}
716
717void AsyncSocksProxyServerSocket::ProcessInput(char* data, size_t* len) {
718 // TODO: See if the whole message has arrived
719 RTC_DCHECK(state_ < SS_CONNECT_PENDING);
720
721 ByteBufferReader response(data, *len);
722 if (state_ == SS_HELLO) {
723 HandleHello(&response);
724 } else if (state_ == SS_AUTH) {
725 HandleAuth(&response);
726 } else if (state_ == SS_CONNECT) {
727 HandleConnect(&response);
728 }
729
730 // Consume parsed data
731 *len = response.Length();
732 memmove(data, response.Data(), *len);
733}
734
735void AsyncSocksProxyServerSocket::DirectSend(const ByteBufferWriter& buf) {
736 BufferedReadAdapter::DirectSend(buf.Data(), buf.Length());
737}
738
739void AsyncSocksProxyServerSocket::HandleHello(ByteBufferReader* request) {
740 uint8_t ver, num_methods;
Yves Gerey665174f2018-06-19 15:03:05 +0200741 if (!request->ReadUInt8(&ver) || !request->ReadUInt8(&num_methods)) {
deadbeeff137e972017-03-23 15:45:49 -0700742 Error(0);
743 return;
744 }
745
746 if (ver != 5) {
747 Error(0);
748 return;
749 }
750
751 // Handle either no-auth (0) or user/pass auth (2)
752 uint8_t method = 0xFF;
753 if (num_methods > 0 && !request->ReadUInt8(&method)) {
754 Error(0);
755 return;
756 }
757
758 // TODO: Ask the server which method to use.
759 SendHelloReply(method);
760 if (method == 0) {
761 state_ = SS_CONNECT;
762 } else if (method == 2) {
763 state_ = SS_AUTH;
764 } else {
765 state_ = SS_ERROR;
766 }
767}
768
769void AsyncSocksProxyServerSocket::SendHelloReply(uint8_t method) {
770 ByteBufferWriter response;
Yves Gerey665174f2018-06-19 15:03:05 +0200771 response.WriteUInt8(5); // Socks Version
deadbeeff137e972017-03-23 15:45:49 -0700772 response.WriteUInt8(method); // Auth method
773 DirectSend(response);
774}
775
776void AsyncSocksProxyServerSocket::HandleAuth(ByteBufferReader* request) {
777 uint8_t ver, user_len, pass_len;
778 std::string user, pass;
Yves Gerey665174f2018-06-19 15:03:05 +0200779 if (!request->ReadUInt8(&ver) || !request->ReadUInt8(&user_len) ||
780 !request->ReadString(&user, user_len) || !request->ReadUInt8(&pass_len) ||
deadbeeff137e972017-03-23 15:45:49 -0700781 !request->ReadString(&pass, pass_len)) {
782 Error(0);
783 return;
784 }
785
786 // TODO: Allow for checking of credentials.
787 SendAuthReply(0);
788 state_ = SS_CONNECT;
789}
790
791void AsyncSocksProxyServerSocket::SendAuthReply(uint8_t result) {
792 ByteBufferWriter response;
793 response.WriteUInt8(1); // Negotiation Version
794 response.WriteUInt8(result);
795 DirectSend(response);
796}
797
798void AsyncSocksProxyServerSocket::HandleConnect(ByteBufferReader* request) {
799 uint8_t ver, command, reserved, addr_type;
800 uint32_t ip;
801 uint16_t port;
Yves Gerey665174f2018-06-19 15:03:05 +0200802 if (!request->ReadUInt8(&ver) || !request->ReadUInt8(&command) ||
803 !request->ReadUInt8(&reserved) || !request->ReadUInt8(&addr_type) ||
804 !request->ReadUInt32(&ip) || !request->ReadUInt16(&port)) {
805 Error(0);
806 return;
deadbeeff137e972017-03-23 15:45:49 -0700807 }
808
Yves Gerey665174f2018-06-19 15:03:05 +0200809 if (ver != 5 || command != 1 || reserved != 0 || addr_type != 1) {
810 Error(0);
811 return;
deadbeeff137e972017-03-23 15:45:49 -0700812 }
813
814 SignalConnectRequest(this, SocketAddress(ip, port));
815 state_ = SS_CONNECT_PENDING;
816}
817
818void AsyncSocksProxyServerSocket::SendConnectResult(int result,
819 const SocketAddress& addr) {
820 if (state_ != SS_CONNECT_PENDING)
821 return;
822
823 ByteBufferWriter response;
Yves Gerey665174f2018-06-19 15:03:05 +0200824 response.WriteUInt8(5); // Socks version
deadbeeff137e972017-03-23 15:45:49 -0700825 response.WriteUInt8((result != 0)); // 0x01 is generic error
Yves Gerey665174f2018-06-19 15:03:05 +0200826 response.WriteUInt8(0); // reserved
827 response.WriteUInt8(1); // IPv4 address
deadbeeff137e972017-03-23 15:45:49 -0700828 response.WriteUInt32(addr.ip());
829 response.WriteUInt16(addr.port());
830 DirectSend(response);
831 BufferInput(false);
832 state_ = SS_TUNNEL;
833}
834
835void AsyncSocksProxyServerSocket::Error(int error) {
836 state_ = SS_ERROR;
837 BufferInput(false);
838 Close();
839 SetError(SOCKET_EACCES);
840 SignalCloseEvent(this, error);
841}
842
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000843} // namespace rtc