blob: cc541a42c649769bc893fb74054dc630414dc92b [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
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000015#include <algorithm>
16
Niels Mölleraa3c1cc2018-11-02 10:54:56 +010017#include "absl/strings/match.h"
Yves Gerey988cc082018-10-23 12:03:01 +020018#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080019#include "rtc_base/byte_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080021#include "rtc_base/http_common.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "rtc_base/socket_adapters.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020024#include "rtc_base/strings/string_builder.h"
Joachim Bauch5b32f232018-03-07 20:02:26 +010025#include "rtc_base/zero_memory.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027namespace rtc {
28
Niels Möllerd0b88792021-08-12 10:32:30 +020029BufferedReadAdapter::BufferedReadAdapter(Socket* socket, size_t size)
Yves Gerey665174f2018-06-19 15:03:05 +020030 : AsyncSocketAdapter(socket),
31 buffer_size_(size),
32 data_len_(0),
33 buffering_(false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000034 buffer_ = new char[buffer_size_];
35}
36
37BufferedReadAdapter::~BufferedReadAdapter() {
Yves Gerey665174f2018-06-19 15:03:05 +020038 delete[] buffer_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039}
40
Yves Gerey665174f2018-06-19 15:03:05 +020041int BufferedReadAdapter::Send(const void* pv, size_t cb) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042 if (buffering_) {
43 // TODO: Spoof error better; Signal Writeable
Niels Möller8729d782021-08-11 11:22:44 +020044 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000045 return -1;
46 }
47 return AsyncSocketAdapter::Send(pv, cb);
48}
49
Stefan Holmer9131efd2016-05-23 18:19:26 +020050int BufferedReadAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000051 if (buffering_) {
Niels Möller8729d782021-08-11 11:22:44 +020052 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053 return -1;
54 }
55
56 size_t read = 0;
57
58 if (data_len_) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000059 read = std::min(cb, data_len_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060 memcpy(pv, buffer_, read);
61 data_len_ -= read;
62 if (data_len_ > 0) {
63 memmove(buffer_, buffer_ + read, data_len_);
64 }
Yves Gerey665174f2018-06-19 15:03:05 +020065 pv = static_cast<char*>(pv) + read;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066 cb -= read;
67 }
68
69 // FIX: If cb == 0, we won't generate another read event
70
Stefan Holmer9131efd2016-05-23 18:19:26 +020071 int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
deadbeefc5d0d952015-07-16 10:22:21 -070072 if (res >= 0) {
73 // Read from socket and possibly buffer; return combined length
74 return res + static_cast<int>(read);
75 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000076
deadbeefc5d0d952015-07-16 10:22:21 -070077 if (read > 0) {
78 // Failed to read from socket, but still read something from buffer
79 return static_cast<int>(read);
80 }
81
82 // Didn't read anything; return error from socket
83 return res;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000084}
85
86void BufferedReadAdapter::BufferInput(bool on) {
87 buffering_ = on;
88}
89
Niels Möllerd0b88792021-08-12 10:32:30 +020090void BufferedReadAdapter::OnReadEvent(Socket* socket) {
Niels Möller8729d782021-08-11 11:22:44 +020091 RTC_DCHECK(socket == GetSocket());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092
93 if (!buffering_) {
94 AsyncSocketAdapter::OnReadEvent(socket);
95 return;
96 }
97
98 if (data_len_ >= buffer_size_) {
Jonas Olsson45cc8902018-02-13 10:37:07 +010099 RTC_LOG(LS_ERROR) << "Input buffer overflow";
nissec80e7412017-01-11 05:56:46 -0800100 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000101 data_len_ = 0;
102 }
103
Niels Möller8729d782021-08-11 11:22:44 +0200104 int len = AsyncSocketAdapter::Recv(buffer_ + data_len_,
105 buffer_size_ - data_len_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000106 if (len < 0) {
107 // TODO: Do something better like forwarding the error to the user.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100108 RTC_LOG_ERR(INFO) << "Recv";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000109 return;
110 }
111
112 data_len_ += len;
113
114 ProcessInput(buffer_, &data_len_);
115}
116
117///////////////////////////////////////////////////////////////////////////////
118
119// This is a SSL v2 CLIENT_HELLO message.
120// TODO: Should this have a session id? The response doesn't have a
121// certificate, so the hello should have a session id.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200122static const uint8_t kSslClientHello[] = {
123 0x80, 0x46, // msg len
124 0x01, // CLIENT_HELLO
125 0x03, 0x01, // SSL 3.1
126 0x00, 0x2d, // ciphersuite len
127 0x00, 0x00, // session id len
128 0x00, 0x10, // challenge len
129 0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0, // ciphersuites
130 0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80, //
131 0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a, //
132 0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, //
133 0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06, //
134 0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc, // challenge
135 0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea //
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136};
137
Niels Möller44153152018-12-17 14:04:05 +0100138// static
139ArrayView<const uint8_t> AsyncSSLSocket::SslClientHello() {
140 // Implicit conversion directly from kSslClientHello to ArrayView fails when
141 // built with gcc.
142 return {kSslClientHello, sizeof(kSslClientHello)};
143}
144
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145// This is a TLSv1 SERVER_HELLO message.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200146static const uint8_t kSslServerHello[] = {
147 0x16, // handshake message
148 0x03, 0x01, // SSL 3.1
149 0x00, 0x4a, // message len
150 0x02, // SERVER_HELLO
151 0x00, 0x00, 0x46, // handshake len
152 0x03, 0x01, // SSL 3.1
153 0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0, // server random
154 0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f, //
155 0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1, //
156 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f, //
157 0x20, // session id len
158 0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f, // session id
159 0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b, //
160 0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38, //
161 0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c, //
162 0x00, 0x04, // RSA/RC4-128/MD5
163 0x00 // null compression
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164};
165
Niels Möller44153152018-12-17 14:04:05 +0100166// static
167ArrayView<const uint8_t> AsyncSSLSocket::SslServerHello() {
168 return {kSslServerHello, sizeof(kSslServerHello)};
169}
170
Niels Möllerd0b88792021-08-12 10:32:30 +0200171AsyncSSLSocket::AsyncSSLSocket(Socket* socket)
Yves Gerey665174f2018-06-19 15:03:05 +0200172 : BufferedReadAdapter(socket, 1024) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173
174int AsyncSSLSocket::Connect(const SocketAddress& addr) {
175 // Begin buffering before we connect, so that there isn't a race condition
176 // between potential senders and receiving the OnConnectEvent signal
177 BufferInput(true);
178 return BufferedReadAdapter::Connect(addr);
179}
180
Niels Möllerd0b88792021-08-12 10:32:30 +0200181void AsyncSSLSocket::OnConnectEvent(Socket* socket) {
Niels Möller8729d782021-08-11 11:22:44 +0200182 RTC_DCHECK(socket == GetSocket());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000183 // TODO: we could buffer output too...
nissec16fa5e2017-02-07 07:18:43 -0800184 const int res = DirectSend(kSslClientHello, sizeof(kSslClientHello));
Niels Möllerb0cb4d12021-08-20 11:04:04 +0200185 if (res != sizeof(kSslClientHello)) {
186 Close();
187 SignalCloseEvent(this, 0);
188 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000189}
190
191void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
192 if (*len < sizeof(kSslServerHello))
193 return;
194
195 if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
196 Close();
197 SignalCloseEvent(this, 0); // TODO: error code?
198 return;
199 }
200
201 *len -= sizeof(kSslServerHello);
202 if (*len > 0) {
203 memmove(data, data + sizeof(kSslServerHello), *len);
204 }
205
206 bool remainder = (*len > 0);
207 BufferInput(false);
208 SignalConnectEvent(this);
209
210 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
211 if (remainder)
212 SignalReadEvent(this);
213}
214
deadbeeff137e972017-03-23 15:45:49 -0700215///////////////////////////////////////////////////////////////////////////////
216
Niels Möllerd0b88792021-08-12 10:32:30 +0200217AsyncHttpsProxySocket::AsyncHttpsProxySocket(Socket* socket,
deadbeeff137e972017-03-23 15:45:49 -0700218 const std::string& user_agent,
219 const SocketAddress& proxy,
220 const std::string& username,
221 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200222 : BufferedReadAdapter(socket, 1024),
223 proxy_(proxy),
224 agent_(user_agent),
225 user_(username),
226 pass_(password),
227 force_connect_(false),
228 state_(PS_ERROR),
229 context_(0) {}
deadbeeff137e972017-03-23 15:45:49 -0700230
231AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
232 delete context_;
233}
234
235int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
236 int ret;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100237 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
238 << proxy_.ToSensitiveString() << ")";
deadbeeff137e972017-03-23 15:45:49 -0700239 dest_ = addr;
240 state_ = PS_INIT;
241 if (ShouldIssueConnect()) {
242 BufferInput(true);
243 }
244 ret = BufferedReadAdapter::Connect(proxy_);
245 // TODO: Set state_ appropriately if Connect fails.
246 return ret;
247}
248
249SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
250 return dest_;
251}
252
253int AsyncHttpsProxySocket::Close() {
254 headers_.clear();
255 state_ = PS_ERROR;
256 dest_.Clear();
257 delete context_;
258 context_ = nullptr;
259 return BufferedReadAdapter::Close();
260}
261
262Socket::ConnState AsyncHttpsProxySocket::GetState() const {
263 if (state_ < PS_TUNNEL) {
264 return CS_CONNECTING;
265 } else if (state_ == PS_TUNNEL) {
266 return CS_CONNECTED;
267 } else {
268 return CS_CLOSED;
269 }
270}
271
Niels Möllerd0b88792021-08-12 10:32:30 +0200272void AsyncHttpsProxySocket::OnConnectEvent(Socket* socket) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100273 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
deadbeeff137e972017-03-23 15:45:49 -0700274 if (!ShouldIssueConnect()) {
275 state_ = PS_TUNNEL;
276 BufferedReadAdapter::OnConnectEvent(socket);
277 return;
278 }
279 SendRequest();
280}
281
Niels Möllerd0b88792021-08-12 10:32:30 +0200282void AsyncHttpsProxySocket::OnCloseEvent(Socket* socket, int err) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100283 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
deadbeeff137e972017-03-23 15:45:49 -0700284 if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
285 state_ = PS_ERROR;
286 Connect(dest_);
287 } else {
288 BufferedReadAdapter::OnCloseEvent(socket, err);
289 }
290}
291
292void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
293 size_t start = 0;
294 for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
295 if (state_ == PS_SKIP_BODY) {
296 size_t consume = std::min(*len - pos, content_length_);
297 pos += consume;
298 start = pos;
299 content_length_ -= consume;
300 if (content_length_ == 0) {
301 EndResponse();
302 }
303 continue;
304 }
305
306 if (data[pos++] != '\n')
307 continue;
308
309 size_t len = pos - start - 1;
310 if ((len > 0) && (data[start + len - 1] == '\r'))
311 --len;
312
313 data[start + len] = 0;
314 ProcessLine(data + start, len);
315 start = pos;
316 }
317
318 *len -= start;
319 if (*len > 0) {
320 memmove(data, data + start, *len);
321 }
322
323 if (state_ != PS_TUNNEL)
324 return;
325
326 bool remainder = (*len > 0);
327 BufferInput(false);
328 SignalConnectEvent(this);
329
330 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
331 if (remainder)
332 SignalReadEvent(this); // TODO: signal this??
333}
334
335bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
336 // TODO: Think about whether a more sophisticated test
337 // than dest port == 80 is needed.
338 return force_connect_ || (dest_.port() != 80);
339}
340
341void AsyncHttpsProxySocket::SendRequest() {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200342 rtc::StringBuilder ss;
deadbeeff137e972017-03-23 15:45:49 -0700343 ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
344 ss << "User-Agent: " << agent_ << "\r\n";
345 ss << "Host: " << dest_.HostAsURIString() << "\r\n";
346 ss << "Content-Length: 0\r\n";
347 ss << "Proxy-Connection: Keep-Alive\r\n";
348 ss << headers_;
349 ss << "\r\n";
350 std::string str = ss.str();
351 DirectSend(str.c_str(), str.size());
352 state_ = PS_LEADER;
353 expect_close_ = true;
354 content_length_ = 0;
355 headers_.clear();
356
Mirko Bonadei675513b2017-11-09 11:09:25 +0100357 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
deadbeeff137e972017-03-23 15:45:49 -0700358}
359
Yves Gerey665174f2018-06-19 15:03:05 +0200360void AsyncHttpsProxySocket::ProcessLine(char* data, size_t len) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100361 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
deadbeeff137e972017-03-23 15:45:49 -0700362
363 if (len == 0) {
364 if (state_ == PS_TUNNEL_HEADERS) {
365 state_ = PS_TUNNEL;
366 } else if (state_ == PS_ERROR_HEADERS) {
367 Error(defer_error_);
368 return;
369 } else if (state_ == PS_SKIP_HEADERS) {
370 if (content_length_) {
371 state_ = PS_SKIP_BODY;
372 } else {
373 EndResponse();
374 return;
375 }
376 } else {
Anders Klemets1425d402019-12-09 09:45:02 -0800377 if (!unknown_mechanisms_.empty()) {
378 RTC_LOG(LS_ERROR) << "Unsupported authentication methods: "
379 << unknown_mechanisms_;
deadbeeff137e972017-03-23 15:45:49 -0700380 }
381 // Unexpected end of headers
382 Error(0);
383 return;
384 }
385 } else if (state_ == PS_LEADER) {
386 unsigned int code;
387 if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
388 Error(0);
389 return;
390 }
391 switch (code) {
Yves Gerey665174f2018-06-19 15:03:05 +0200392 case 200:
393 // connection good!
394 state_ = PS_TUNNEL_HEADERS;
395 return;
deadbeeff137e972017-03-23 15:45:49 -0700396#if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
397#error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
398#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200399 case 407: // HTTP_STATUS_PROXY_AUTH_REQ
400 state_ = PS_AUTHENTICATE;
401 return;
402 default:
403 defer_error_ = 0;
404 state_ = PS_ERROR_HEADERS;
405 return;
deadbeeff137e972017-03-23 15:45:49 -0700406 }
Yves Gerey665174f2018-06-19 15:03:05 +0200407 } else if ((state_ == PS_AUTHENTICATE) &&
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100408 absl::StartsWithIgnoreCase(data, "Proxy-Authenticate:")) {
deadbeeff137e972017-03-23 15:45:49 -0700409 std::string response, auth_method;
Yves Gerey665174f2018-06-19 15:03:05 +0200410 switch (HttpAuthenticate(data + 19, len - 19, proxy_, "CONNECT", "/", user_,
411 pass_, context_, response, auth_method)) {
412 case HAR_IGNORE:
413 RTC_LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
414 if (!unknown_mechanisms_.empty())
415 unknown_mechanisms_.append(", ");
416 unknown_mechanisms_.append(auth_method);
417 break;
418 case HAR_RESPONSE:
419 headers_ = "Proxy-Authorization: ";
420 headers_.append(response);
421 headers_.append("\r\n");
422 state_ = PS_SKIP_HEADERS;
423 unknown_mechanisms_.clear();
424 break;
425 case HAR_CREDENTIALS:
426 defer_error_ = SOCKET_EACCES;
427 state_ = PS_ERROR_HEADERS;
428 unknown_mechanisms_.clear();
429 break;
430 case HAR_ERROR:
431 defer_error_ = 0;
432 state_ = PS_ERROR_HEADERS;
433 unknown_mechanisms_.clear();
434 break;
deadbeeff137e972017-03-23 15:45:49 -0700435 }
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100436 } else if (absl::StartsWithIgnoreCase(data, "Content-Length:")) {
deadbeeff137e972017-03-23 15:45:49 -0700437 content_length_ = strtoul(data + 15, 0, 0);
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100438 } else if (absl::StartsWithIgnoreCase(data, "Proxy-Connection: Keep-Alive")) {
deadbeeff137e972017-03-23 15:45:49 -0700439 expect_close_ = false;
440 /*
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100441 } else if (absl::StartsWithIgnoreCase(data, "Connection: close") {
deadbeeff137e972017-03-23 15:45:49 -0700442 expect_close_ = true;
443 */
444 }
445}
446
447void AsyncHttpsProxySocket::EndResponse() {
448 if (!expect_close_) {
449 SendRequest();
450 return;
451 }
452
453 // No point in waiting for the server to close... let's close now
454 // TODO: Refactor out PS_WAIT_CLOSE
455 state_ = PS_WAIT_CLOSE;
456 BufferedReadAdapter::Close();
457 OnCloseEvent(this, 0);
458}
459
460void AsyncHttpsProxySocket::Error(int error) {
461 BufferInput(false);
462 Close();
463 SetError(error);
464 SignalCloseEvent(this, error);
465}
466
467///////////////////////////////////////////////////////////////////////////////
468
Niels Möllerd0b88792021-08-12 10:32:30 +0200469AsyncSocksProxySocket::AsyncSocksProxySocket(Socket* socket,
deadbeeff137e972017-03-23 15:45:49 -0700470 const SocketAddress& proxy,
471 const std::string& username,
472 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200473 : BufferedReadAdapter(socket, 1024),
474 state_(SS_ERROR),
475 proxy_(proxy),
476 user_(username),
477 pass_(password) {}
deadbeeff137e972017-03-23 15:45:49 -0700478
479AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
480
481int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
482 int ret;
483 dest_ = addr;
484 state_ = SS_INIT;
485 BufferInput(true);
486 ret = BufferedReadAdapter::Connect(proxy_);
487 // TODO: Set state_ appropriately if Connect fails.
488 return ret;
489}
490
491SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
492 return dest_;
493}
494
495int AsyncSocksProxySocket::Close() {
496 state_ = SS_ERROR;
497 dest_.Clear();
498 return BufferedReadAdapter::Close();
499}
500
501Socket::ConnState AsyncSocksProxySocket::GetState() const {
502 if (state_ < SS_TUNNEL) {
503 return CS_CONNECTING;
504 } else if (state_ == SS_TUNNEL) {
505 return CS_CONNECTED;
506 } else {
507 return CS_CLOSED;
508 }
509}
510
Niels Möllerd0b88792021-08-12 10:32:30 +0200511void AsyncSocksProxySocket::OnConnectEvent(Socket* socket) {
deadbeeff137e972017-03-23 15:45:49 -0700512 SendHello();
513}
514
515void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
516 RTC_DCHECK(state_ < SS_TUNNEL);
517
518 ByteBufferReader response(data, *len);
519
520 if (state_ == SS_HELLO) {
521 uint8_t ver, method;
Yves Gerey665174f2018-06-19 15:03:05 +0200522 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&method))
deadbeeff137e972017-03-23 15:45:49 -0700523 return;
524
525 if (ver != 5) {
526 Error(0);
527 return;
528 }
529
530 if (method == 0) {
531 SendConnect();
532 } else if (method == 2) {
533 SendAuth();
534 } else {
535 Error(0);
536 return;
537 }
538 } else if (state_ == SS_AUTH) {
539 uint8_t ver, status;
Yves Gerey665174f2018-06-19 15:03:05 +0200540 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&status))
deadbeeff137e972017-03-23 15:45:49 -0700541 return;
542
543 if ((ver != 1) || (status != 0)) {
544 Error(SOCKET_EACCES);
545 return;
546 }
547
548 SendConnect();
549 } else if (state_ == SS_CONNECT) {
550 uint8_t ver, rep, rsv, atyp;
Yves Gerey665174f2018-06-19 15:03:05 +0200551 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&rep) ||
552 !response.ReadUInt8(&rsv) || !response.ReadUInt8(&atyp))
deadbeeff137e972017-03-23 15:45:49 -0700553 return;
554
555 if ((ver != 5) || (rep != 0)) {
556 Error(0);
557 return;
558 }
559
560 uint16_t port;
561 if (atyp == 1) {
562 uint32_t addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200563 if (!response.ReadUInt32(&addr) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700564 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100565 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700566 } else if (atyp == 3) {
567 uint8_t len;
568 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200569 if (!response.ReadUInt8(&len) || !response.ReadString(&addr, len) ||
deadbeeff137e972017-03-23 15:45:49 -0700570 !response.ReadUInt16(&port))
571 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100572 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700573 } else if (atyp == 4) {
574 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200575 if (!response.ReadString(&addr, 16) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700576 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100577 RTC_LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
deadbeeff137e972017-03-23 15:45:49 -0700578 } else {
579 Error(0);
580 return;
581 }
582
583 state_ = SS_TUNNEL;
584 }
585
586 // Consume parsed data
587 *len = response.Length();
588 memmove(data, response.Data(), *len);
589
590 if (state_ != SS_TUNNEL)
591 return;
592
593 bool remainder = (*len > 0);
594 BufferInput(false);
595 SignalConnectEvent(this);
596
597 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
598 if (remainder)
599 SignalReadEvent(this); // TODO: signal this??
600}
601
602void AsyncSocksProxySocket::SendHello() {
603 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200604 request.WriteUInt8(5); // Socks Version
deadbeeff137e972017-03-23 15:45:49 -0700605 if (user_.empty()) {
606 request.WriteUInt8(1); // Authentication Mechanisms
607 request.WriteUInt8(0); // No authentication
608 } else {
609 request.WriteUInt8(2); // Authentication Mechanisms
610 request.WriteUInt8(0); // No authentication
611 request.WriteUInt8(2); // Username/Password
612 }
613 DirectSend(request.Data(), request.Length());
614 state_ = SS_HELLO;
615}
616
617void AsyncSocksProxySocket::SendAuth() {
Joachim Bauch4c6a30c2018-03-08 00:55:33 +0100618 ByteBufferWriterT<ZeroOnFreeBuffer<char>> request;
Yves Gerey665174f2018-06-19 15:03:05 +0200619 request.WriteUInt8(1); // Negotiation Version
deadbeeff137e972017-03-23 15:45:49 -0700620 request.WriteUInt8(static_cast<uint8_t>(user_.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200621 request.WriteString(user_); // Username
deadbeeff137e972017-03-23 15:45:49 -0700622 request.WriteUInt8(static_cast<uint8_t>(pass_.GetLength()));
623 size_t len = pass_.GetLength() + 1;
Yves Gerey665174f2018-06-19 15:03:05 +0200624 char* sensitive = new char[len];
deadbeeff137e972017-03-23 15:45:49 -0700625 pass_.CopyTo(sensitive, true);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100626 request.WriteBytes(sensitive, pass_.GetLength()); // Password
627 ExplicitZeroMemory(sensitive, len);
Yves Gerey665174f2018-06-19 15:03:05 +0200628 delete[] sensitive;
deadbeeff137e972017-03-23 15:45:49 -0700629 DirectSend(request.Data(), request.Length());
630 state_ = SS_AUTH;
631}
632
633void AsyncSocksProxySocket::SendConnect() {
634 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200635 request.WriteUInt8(5); // Socks Version
636 request.WriteUInt8(1); // CONNECT
637 request.WriteUInt8(0); // Reserved
deadbeeff137e972017-03-23 15:45:49 -0700638 if (dest_.IsUnresolvedIP()) {
639 std::string hostname = dest_.hostname();
Yves Gerey665174f2018-06-19 15:03:05 +0200640 request.WriteUInt8(3); // DOMAINNAME
deadbeeff137e972017-03-23 15:45:49 -0700641 request.WriteUInt8(static_cast<uint8_t>(hostname.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200642 request.WriteString(hostname); // Destination Hostname
deadbeeff137e972017-03-23 15:45:49 -0700643 } else {
644 request.WriteUInt8(1); // IPV4
645 request.WriteUInt32(dest_.ip()); // Destination IP
646 }
647 request.WriteUInt16(dest_.port()); // Destination Port
648 DirectSend(request.Data(), request.Length());
649 state_ = SS_CONNECT;
650}
651
652void AsyncSocksProxySocket::Error(int error) {
653 state_ = SS_ERROR;
654 BufferInput(false);
655 Close();
656 SetError(SOCKET_EACCES);
657 SignalCloseEvent(this, error);
658}
659
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000660} // namespace rtc