blob: bc7d2d85a956b62f8edd9e3cfb4d7ecc4e31acaa [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
Ali Tofigh7fa90572022-03-17 15:47:49 +010015#include "rtc_base/socket_adapters.h"
16
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000017#include <algorithm>
18
Niels Mölleraa3c1cc2018-11-02 10:54:56 +010019#include "absl/strings/match.h"
Ali Tofigh7fa90572022-03-17 15:47:49 +010020#include "absl/strings/string_view.h"
Yves Gerey988cc082018-10-23 12:03:01 +020021#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "rtc_base/byte_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/http_common.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "rtc_base/logging.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020026#include "rtc_base/strings/string_builder.h"
Joachim Bauch5b32f232018-03-07 20:02:26 +010027#include "rtc_base/zero_memory.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029namespace rtc {
30
Niels Möllerd0b88792021-08-12 10:32:30 +020031BufferedReadAdapter::BufferedReadAdapter(Socket* socket, size_t size)
Yves Gerey665174f2018-06-19 15:03:05 +020032 : AsyncSocketAdapter(socket),
33 buffer_size_(size),
34 data_len_(0),
35 buffering_(false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036 buffer_ = new char[buffer_size_];
37}
38
39BufferedReadAdapter::~BufferedReadAdapter() {
Yves Gerey665174f2018-06-19 15:03:05 +020040 delete[] buffer_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041}
42
Yves Gerey665174f2018-06-19 15:03:05 +020043int BufferedReadAdapter::Send(const void* pv, size_t cb) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044 if (buffering_) {
45 // TODO: Spoof error better; Signal Writeable
Niels Möller8729d782021-08-11 11:22:44 +020046 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000047 return -1;
48 }
49 return AsyncSocketAdapter::Send(pv, cb);
50}
51
Stefan Holmer9131efd2016-05-23 18:19:26 +020052int BufferedReadAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053 if (buffering_) {
Niels Möller8729d782021-08-11 11:22:44 +020054 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055 return -1;
56 }
57
58 size_t read = 0;
59
60 if (data_len_) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000061 read = std::min(cb, data_len_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062 memcpy(pv, buffer_, read);
63 data_len_ -= read;
64 if (data_len_ > 0) {
65 memmove(buffer_, buffer_ + read, data_len_);
66 }
Yves Gerey665174f2018-06-19 15:03:05 +020067 pv = static_cast<char*>(pv) + read;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000068 cb -= read;
69 }
70
71 // FIX: If cb == 0, we won't generate another read event
72
Stefan Holmer9131efd2016-05-23 18:19:26 +020073 int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
deadbeefc5d0d952015-07-16 10:22:21 -070074 if (res >= 0) {
75 // Read from socket and possibly buffer; return combined length
76 return res + static_cast<int>(read);
77 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000078
deadbeefc5d0d952015-07-16 10:22:21 -070079 if (read > 0) {
80 // Failed to read from socket, but still read something from buffer
81 return static_cast<int>(read);
82 }
83
84 // Didn't read anything; return error from socket
85 return res;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000086}
87
88void BufferedReadAdapter::BufferInput(bool on) {
89 buffering_ = on;
90}
91
Niels Möllerd0b88792021-08-12 10:32:30 +020092void BufferedReadAdapter::OnReadEvent(Socket* socket) {
Niels Möller8729d782021-08-11 11:22:44 +020093 RTC_DCHECK(socket == GetSocket());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094
95 if (!buffering_) {
96 AsyncSocketAdapter::OnReadEvent(socket);
97 return;
98 }
99
100 if (data_len_ >= buffer_size_) {
Jonas Olsson45cc8902018-02-13 10:37:07 +0100101 RTC_LOG(LS_ERROR) << "Input buffer overflow";
Artem Titovd3251962021-11-15 16:57:07 +0100102 RTC_DCHECK_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103 data_len_ = 0;
104 }
105
Niels Möller8729d782021-08-11 11:22:44 +0200106 int len = AsyncSocketAdapter::Recv(buffer_ + data_len_,
107 buffer_size_ - data_len_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000108 if (len < 0) {
109 // TODO: Do something better like forwarding the error to the user.
Harald Alvestrand97597c02021-11-04 12:01:23 +0000110 RTC_LOG_ERR(LS_INFO) << "Recv";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 return;
112 }
113
114 data_len_ += len;
115
116 ProcessInput(buffer_, &data_len_);
117}
118
119///////////////////////////////////////////////////////////////////////////////
120
121// This is a SSL v2 CLIENT_HELLO message.
122// TODO: Should this have a session id? The response doesn't have a
123// certificate, so the hello should have a session id.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200124static const uint8_t kSslClientHello[] = {
125 0x80, 0x46, // msg len
126 0x01, // CLIENT_HELLO
127 0x03, 0x01, // SSL 3.1
128 0x00, 0x2d, // ciphersuite len
129 0x00, 0x00, // session id len
130 0x00, 0x10, // challenge len
131 0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0, // ciphersuites
132 0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80, //
133 0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a, //
134 0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, //
135 0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06, //
136 0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc, // challenge
137 0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea //
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138};
139
Niels Möller44153152018-12-17 14:04:05 +0100140// static
141ArrayView<const uint8_t> AsyncSSLSocket::SslClientHello() {
142 // Implicit conversion directly from kSslClientHello to ArrayView fails when
143 // built with gcc.
144 return {kSslClientHello, sizeof(kSslClientHello)};
145}
146
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000147// This is a TLSv1 SERVER_HELLO message.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200148static const uint8_t kSslServerHello[] = {
149 0x16, // handshake message
150 0x03, 0x01, // SSL 3.1
151 0x00, 0x4a, // message len
152 0x02, // SERVER_HELLO
153 0x00, 0x00, 0x46, // handshake len
154 0x03, 0x01, // SSL 3.1
155 0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0, // server random
156 0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f, //
157 0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1, //
158 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f, //
159 0x20, // session id len
160 0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f, // session id
161 0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b, //
162 0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38, //
163 0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c, //
164 0x00, 0x04, // RSA/RC4-128/MD5
165 0x00 // null compression
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166};
167
Niels Möller44153152018-12-17 14:04:05 +0100168// static
169ArrayView<const uint8_t> AsyncSSLSocket::SslServerHello() {
170 return {kSslServerHello, sizeof(kSslServerHello)};
171}
172
Niels Möllerd0b88792021-08-12 10:32:30 +0200173AsyncSSLSocket::AsyncSSLSocket(Socket* socket)
Yves Gerey665174f2018-06-19 15:03:05 +0200174 : BufferedReadAdapter(socket, 1024) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175
176int AsyncSSLSocket::Connect(const SocketAddress& addr) {
177 // Begin buffering before we connect, so that there isn't a race condition
178 // between potential senders and receiving the OnConnectEvent signal
179 BufferInput(true);
180 return BufferedReadAdapter::Connect(addr);
181}
182
Niels Möllerd0b88792021-08-12 10:32:30 +0200183void AsyncSSLSocket::OnConnectEvent(Socket* socket) {
Niels Möller8729d782021-08-11 11:22:44 +0200184 RTC_DCHECK(socket == GetSocket());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 // TODO: we could buffer output too...
nissec16fa5e2017-02-07 07:18:43 -0800186 const int res = DirectSend(kSslClientHello, sizeof(kSslClientHello));
Niels Möllerb0cb4d12021-08-20 11:04:04 +0200187 if (res != sizeof(kSslClientHello)) {
Niels Möller2eb465f2021-08-23 11:17:56 +0200188 RTC_LOG(LS_ERROR) << "Sending fake SSL ClientHello message failed.";
Niels Möllerb0cb4d12021-08-20 11:04:04 +0200189 Close();
190 SignalCloseEvent(this, 0);
191 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000192}
193
194void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
195 if (*len < sizeof(kSslServerHello))
196 return;
197
198 if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
Niels Möller2eb465f2021-08-23 11:17:56 +0200199 RTC_LOG(LS_ERROR) << "Received non-matching fake SSL ServerHello message.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200 Close();
201 SignalCloseEvent(this, 0); // TODO: error code?
202 return;
203 }
204
205 *len -= sizeof(kSslServerHello);
206 if (*len > 0) {
207 memmove(data, data + sizeof(kSslServerHello), *len);
208 }
209
210 bool remainder = (*len > 0);
211 BufferInput(false);
212 SignalConnectEvent(this);
213
214 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
215 if (remainder)
216 SignalReadEvent(this);
217}
218
deadbeeff137e972017-03-23 15:45:49 -0700219///////////////////////////////////////////////////////////////////////////////
220
Niels Möllerd0b88792021-08-12 10:32:30 +0200221AsyncHttpsProxySocket::AsyncHttpsProxySocket(Socket* socket,
Ali Tofigh7fa90572022-03-17 15:47:49 +0100222 absl::string_view user_agent,
deadbeeff137e972017-03-23 15:45:49 -0700223 const SocketAddress& proxy,
Ali Tofigh7fa90572022-03-17 15:47:49 +0100224 absl::string_view username,
deadbeeff137e972017-03-23 15:45:49 -0700225 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200226 : BufferedReadAdapter(socket, 1024),
227 proxy_(proxy),
228 agent_(user_agent),
229 user_(username),
230 pass_(password),
231 force_connect_(false),
232 state_(PS_ERROR),
233 context_(0) {}
deadbeeff137e972017-03-23 15:45:49 -0700234
235AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
236 delete context_;
237}
238
239int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
240 int ret;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100241 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
242 << proxy_.ToSensitiveString() << ")";
deadbeeff137e972017-03-23 15:45:49 -0700243 dest_ = addr;
244 state_ = PS_INIT;
245 if (ShouldIssueConnect()) {
246 BufferInput(true);
247 }
248 ret = BufferedReadAdapter::Connect(proxy_);
249 // TODO: Set state_ appropriately if Connect fails.
250 return ret;
251}
252
253SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
254 return dest_;
255}
256
257int AsyncHttpsProxySocket::Close() {
258 headers_.clear();
259 state_ = PS_ERROR;
260 dest_.Clear();
261 delete context_;
262 context_ = nullptr;
263 return BufferedReadAdapter::Close();
264}
265
266Socket::ConnState AsyncHttpsProxySocket::GetState() const {
267 if (state_ < PS_TUNNEL) {
268 return CS_CONNECTING;
269 } else if (state_ == PS_TUNNEL) {
270 return CS_CONNECTED;
271 } else {
272 return CS_CLOSED;
273 }
274}
275
Niels Möllerd0b88792021-08-12 10:32:30 +0200276void AsyncHttpsProxySocket::OnConnectEvent(Socket* socket) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100277 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
deadbeeff137e972017-03-23 15:45:49 -0700278 if (!ShouldIssueConnect()) {
279 state_ = PS_TUNNEL;
280 BufferedReadAdapter::OnConnectEvent(socket);
281 return;
282 }
283 SendRequest();
284}
285
Niels Möllerd0b88792021-08-12 10:32:30 +0200286void AsyncHttpsProxySocket::OnCloseEvent(Socket* socket, int err) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100287 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
deadbeeff137e972017-03-23 15:45:49 -0700288 if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
289 state_ = PS_ERROR;
290 Connect(dest_);
291 } else {
292 BufferedReadAdapter::OnCloseEvent(socket, err);
293 }
294}
295
296void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
297 size_t start = 0;
298 for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
299 if (state_ == PS_SKIP_BODY) {
300 size_t consume = std::min(*len - pos, content_length_);
301 pos += consume;
302 start = pos;
303 content_length_ -= consume;
304 if (content_length_ == 0) {
305 EndResponse();
306 }
307 continue;
308 }
309
310 if (data[pos++] != '\n')
311 continue;
312
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200313 size_t length = pos - start - 1;
314 if ((length > 0) && (data[start + length - 1] == '\r'))
315 --length;
deadbeeff137e972017-03-23 15:45:49 -0700316
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200317 data[start + length] = 0;
318 ProcessLine(data + start, length);
deadbeeff137e972017-03-23 15:45:49 -0700319 start = pos;
320 }
321
322 *len -= start;
323 if (*len > 0) {
324 memmove(data, data + start, *len);
325 }
326
327 if (state_ != PS_TUNNEL)
328 return;
329
330 bool remainder = (*len > 0);
331 BufferInput(false);
332 SignalConnectEvent(this);
333
334 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
335 if (remainder)
336 SignalReadEvent(this); // TODO: signal this??
337}
338
339bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
340 // TODO: Think about whether a more sophisticated test
341 // than dest port == 80 is needed.
342 return force_connect_ || (dest_.port() != 80);
343}
344
345void AsyncHttpsProxySocket::SendRequest() {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200346 rtc::StringBuilder ss;
deadbeeff137e972017-03-23 15:45:49 -0700347 ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
348 ss << "User-Agent: " << agent_ << "\r\n";
349 ss << "Host: " << dest_.HostAsURIString() << "\r\n";
350 ss << "Content-Length: 0\r\n";
351 ss << "Proxy-Connection: Keep-Alive\r\n";
352 ss << headers_;
353 ss << "\r\n";
354 std::string str = ss.str();
355 DirectSend(str.c_str(), str.size());
356 state_ = PS_LEADER;
357 expect_close_ = true;
358 content_length_ = 0;
359 headers_.clear();
360
Mirko Bonadei675513b2017-11-09 11:09:25 +0100361 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
deadbeeff137e972017-03-23 15:45:49 -0700362}
363
Yves Gerey665174f2018-06-19 15:03:05 +0200364void AsyncHttpsProxySocket::ProcessLine(char* data, size_t len) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100365 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
deadbeeff137e972017-03-23 15:45:49 -0700366
367 if (len == 0) {
368 if (state_ == PS_TUNNEL_HEADERS) {
369 state_ = PS_TUNNEL;
370 } else if (state_ == PS_ERROR_HEADERS) {
371 Error(defer_error_);
372 return;
373 } else if (state_ == PS_SKIP_HEADERS) {
374 if (content_length_) {
375 state_ = PS_SKIP_BODY;
376 } else {
377 EndResponse();
378 return;
379 }
380 } else {
Anders Klemets1425d402019-12-09 09:45:02 -0800381 if (!unknown_mechanisms_.empty()) {
382 RTC_LOG(LS_ERROR) << "Unsupported authentication methods: "
383 << unknown_mechanisms_;
deadbeeff137e972017-03-23 15:45:49 -0700384 }
385 // Unexpected end of headers
386 Error(0);
387 return;
388 }
389 } else if (state_ == PS_LEADER) {
390 unsigned int code;
391 if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
392 Error(0);
393 return;
394 }
395 switch (code) {
Yves Gerey665174f2018-06-19 15:03:05 +0200396 case 200:
397 // connection good!
398 state_ = PS_TUNNEL_HEADERS;
399 return;
deadbeeff137e972017-03-23 15:45:49 -0700400#if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
401#error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
402#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200403 case 407: // HTTP_STATUS_PROXY_AUTH_REQ
404 state_ = PS_AUTHENTICATE;
405 return;
406 default:
407 defer_error_ = 0;
408 state_ = PS_ERROR_HEADERS;
409 return;
deadbeeff137e972017-03-23 15:45:49 -0700410 }
Yves Gerey665174f2018-06-19 15:03:05 +0200411 } else if ((state_ == PS_AUTHENTICATE) &&
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100412 absl::StartsWithIgnoreCase(data, "Proxy-Authenticate:")) {
deadbeeff137e972017-03-23 15:45:49 -0700413 std::string response, auth_method;
Yves Gerey665174f2018-06-19 15:03:05 +0200414 switch (HttpAuthenticate(data + 19, len - 19, proxy_, "CONNECT", "/", user_,
415 pass_, context_, response, auth_method)) {
416 case HAR_IGNORE:
417 RTC_LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
418 if (!unknown_mechanisms_.empty())
419 unknown_mechanisms_.append(", ");
420 unknown_mechanisms_.append(auth_method);
421 break;
422 case HAR_RESPONSE:
423 headers_ = "Proxy-Authorization: ";
424 headers_.append(response);
425 headers_.append("\r\n");
426 state_ = PS_SKIP_HEADERS;
427 unknown_mechanisms_.clear();
428 break;
429 case HAR_CREDENTIALS:
430 defer_error_ = SOCKET_EACCES;
431 state_ = PS_ERROR_HEADERS;
432 unknown_mechanisms_.clear();
433 break;
434 case HAR_ERROR:
435 defer_error_ = 0;
436 state_ = PS_ERROR_HEADERS;
437 unknown_mechanisms_.clear();
438 break;
deadbeeff137e972017-03-23 15:45:49 -0700439 }
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100440 } else if (absl::StartsWithIgnoreCase(data, "Content-Length:")) {
deadbeeff137e972017-03-23 15:45:49 -0700441 content_length_ = strtoul(data + 15, 0, 0);
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100442 } else if (absl::StartsWithIgnoreCase(data, "Proxy-Connection: Keep-Alive")) {
deadbeeff137e972017-03-23 15:45:49 -0700443 expect_close_ = false;
444 /*
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100445 } else if (absl::StartsWithIgnoreCase(data, "Connection: close") {
deadbeeff137e972017-03-23 15:45:49 -0700446 expect_close_ = true;
447 */
448 }
449}
450
451void AsyncHttpsProxySocket::EndResponse() {
452 if (!expect_close_) {
453 SendRequest();
454 return;
455 }
456
457 // No point in waiting for the server to close... let's close now
458 // TODO: Refactor out PS_WAIT_CLOSE
459 state_ = PS_WAIT_CLOSE;
460 BufferedReadAdapter::Close();
461 OnCloseEvent(this, 0);
462}
463
464void AsyncHttpsProxySocket::Error(int error) {
465 BufferInput(false);
466 Close();
467 SetError(error);
468 SignalCloseEvent(this, error);
469}
470
471///////////////////////////////////////////////////////////////////////////////
472
Niels Möllerd0b88792021-08-12 10:32:30 +0200473AsyncSocksProxySocket::AsyncSocksProxySocket(Socket* socket,
deadbeeff137e972017-03-23 15:45:49 -0700474 const SocketAddress& proxy,
Ali Tofigh7fa90572022-03-17 15:47:49 +0100475 absl::string_view username,
deadbeeff137e972017-03-23 15:45:49 -0700476 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200477 : BufferedReadAdapter(socket, 1024),
478 state_(SS_ERROR),
479 proxy_(proxy),
480 user_(username),
481 pass_(password) {}
deadbeeff137e972017-03-23 15:45:49 -0700482
483AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
484
485int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
486 int ret;
487 dest_ = addr;
488 state_ = SS_INIT;
489 BufferInput(true);
490 ret = BufferedReadAdapter::Connect(proxy_);
491 // TODO: Set state_ appropriately if Connect fails.
492 return ret;
493}
494
495SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
496 return dest_;
497}
498
499int AsyncSocksProxySocket::Close() {
500 state_ = SS_ERROR;
501 dest_.Clear();
502 return BufferedReadAdapter::Close();
503}
504
505Socket::ConnState AsyncSocksProxySocket::GetState() const {
506 if (state_ < SS_TUNNEL) {
507 return CS_CONNECTING;
508 } else if (state_ == SS_TUNNEL) {
509 return CS_CONNECTED;
510 } else {
511 return CS_CLOSED;
512 }
513}
514
Niels Möllerd0b88792021-08-12 10:32:30 +0200515void AsyncSocksProxySocket::OnConnectEvent(Socket* socket) {
deadbeeff137e972017-03-23 15:45:49 -0700516 SendHello();
517}
518
519void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
520 RTC_DCHECK(state_ < SS_TUNNEL);
521
522 ByteBufferReader response(data, *len);
523
524 if (state_ == SS_HELLO) {
525 uint8_t ver, method;
Yves Gerey665174f2018-06-19 15:03:05 +0200526 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&method))
deadbeeff137e972017-03-23 15:45:49 -0700527 return;
528
529 if (ver != 5) {
530 Error(0);
531 return;
532 }
533
534 if (method == 0) {
535 SendConnect();
536 } else if (method == 2) {
537 SendAuth();
538 } else {
539 Error(0);
540 return;
541 }
542 } else if (state_ == SS_AUTH) {
543 uint8_t ver, status;
Yves Gerey665174f2018-06-19 15:03:05 +0200544 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&status))
deadbeeff137e972017-03-23 15:45:49 -0700545 return;
546
547 if ((ver != 1) || (status != 0)) {
548 Error(SOCKET_EACCES);
549 return;
550 }
551
552 SendConnect();
553 } else if (state_ == SS_CONNECT) {
554 uint8_t ver, rep, rsv, atyp;
Yves Gerey665174f2018-06-19 15:03:05 +0200555 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&rep) ||
556 !response.ReadUInt8(&rsv) || !response.ReadUInt8(&atyp))
deadbeeff137e972017-03-23 15:45:49 -0700557 return;
558
559 if ((ver != 5) || (rep != 0)) {
560 Error(0);
561 return;
562 }
563
564 uint16_t port;
565 if (atyp == 1) {
566 uint32_t addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200567 if (!response.ReadUInt32(&addr) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700568 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100569 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700570 } else if (atyp == 3) {
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200571 uint8_t length;
deadbeeff137e972017-03-23 15:45:49 -0700572 std::string addr;
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200573 if (!response.ReadUInt8(&length) || !response.ReadString(&addr, length) ||
deadbeeff137e972017-03-23 15:45:49 -0700574 !response.ReadUInt16(&port))
575 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100576 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700577 } else if (atyp == 4) {
578 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200579 if (!response.ReadString(&addr, 16) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700580 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100581 RTC_LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
deadbeeff137e972017-03-23 15:45:49 -0700582 } else {
583 Error(0);
584 return;
585 }
586
587 state_ = SS_TUNNEL;
588 }
589
590 // Consume parsed data
591 *len = response.Length();
592 memmove(data, response.Data(), *len);
593
594 if (state_ != SS_TUNNEL)
595 return;
596
597 bool remainder = (*len > 0);
598 BufferInput(false);
599 SignalConnectEvent(this);
600
601 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
602 if (remainder)
603 SignalReadEvent(this); // TODO: signal this??
604}
605
606void AsyncSocksProxySocket::SendHello() {
607 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200608 request.WriteUInt8(5); // Socks Version
deadbeeff137e972017-03-23 15:45:49 -0700609 if (user_.empty()) {
610 request.WriteUInt8(1); // Authentication Mechanisms
611 request.WriteUInt8(0); // No authentication
612 } else {
613 request.WriteUInt8(2); // Authentication Mechanisms
614 request.WriteUInt8(0); // No authentication
615 request.WriteUInt8(2); // Username/Password
616 }
617 DirectSend(request.Data(), request.Length());
618 state_ = SS_HELLO;
619}
620
621void AsyncSocksProxySocket::SendAuth() {
Joachim Bauch4c6a30c2018-03-08 00:55:33 +0100622 ByteBufferWriterT<ZeroOnFreeBuffer<char>> request;
Yves Gerey665174f2018-06-19 15:03:05 +0200623 request.WriteUInt8(1); // Negotiation Version
deadbeeff137e972017-03-23 15:45:49 -0700624 request.WriteUInt8(static_cast<uint8_t>(user_.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200625 request.WriteString(user_); // Username
deadbeeff137e972017-03-23 15:45:49 -0700626 request.WriteUInt8(static_cast<uint8_t>(pass_.GetLength()));
627 size_t len = pass_.GetLength() + 1;
Yves Gerey665174f2018-06-19 15:03:05 +0200628 char* sensitive = new char[len];
deadbeeff137e972017-03-23 15:45:49 -0700629 pass_.CopyTo(sensitive, true);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100630 request.WriteBytes(sensitive, pass_.GetLength()); // Password
631 ExplicitZeroMemory(sensitive, len);
Yves Gerey665174f2018-06-19 15:03:05 +0200632 delete[] sensitive;
deadbeeff137e972017-03-23 15:45:49 -0700633 DirectSend(request.Data(), request.Length());
634 state_ = SS_AUTH;
635}
636
637void AsyncSocksProxySocket::SendConnect() {
638 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200639 request.WriteUInt8(5); // Socks Version
640 request.WriteUInt8(1); // CONNECT
641 request.WriteUInt8(0); // Reserved
deadbeeff137e972017-03-23 15:45:49 -0700642 if (dest_.IsUnresolvedIP()) {
643 std::string hostname = dest_.hostname();
Yves Gerey665174f2018-06-19 15:03:05 +0200644 request.WriteUInt8(3); // DOMAINNAME
deadbeeff137e972017-03-23 15:45:49 -0700645 request.WriteUInt8(static_cast<uint8_t>(hostname.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200646 request.WriteString(hostname); // Destination Hostname
deadbeeff137e972017-03-23 15:45:49 -0700647 } else {
648 request.WriteUInt8(1); // IPV4
649 request.WriteUInt32(dest_.ip()); // Destination IP
650 }
651 request.WriteUInt16(dest_.port()); // Destination Port
652 DirectSend(request.Data(), request.Length());
653 state_ = SS_CONNECT;
654}
655
656void AsyncSocksProxySocket::Error(int error) {
657 state_ = SS_ERROR;
658 BufferInput(false);
659 Close();
660 SetError(SOCKET_EACCES);
661 SignalCloseEvent(this, error);
662}
663
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000664} // namespace rtc