blob: 0bd6efad3e2431919f93610f4720b732aeb1d5df [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";
Artem Titovd3251962021-11-15 16:57:07 +0100100 RTC_DCHECK_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.
Harald Alvestrand97597c02021-11-04 12:01:23 +0000108 RTC_LOG_ERR(LS_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)) {
Niels Möller2eb465f2021-08-23 11:17:56 +0200186 RTC_LOG(LS_ERROR) << "Sending fake SSL ClientHello message failed.";
Niels Möllerb0cb4d12021-08-20 11:04:04 +0200187 Close();
188 SignalCloseEvent(this, 0);
189 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190}
191
192void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
193 if (*len < sizeof(kSslServerHello))
194 return;
195
196 if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
Niels Möller2eb465f2021-08-23 11:17:56 +0200197 RTC_LOG(LS_ERROR) << "Received non-matching fake SSL ServerHello message.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198 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
deadbeeff137e972017-03-23 15:45:49 -0700217///////////////////////////////////////////////////////////////////////////////
218
Niels Möllerd0b88792021-08-12 10:32:30 +0200219AsyncHttpsProxySocket::AsyncHttpsProxySocket(Socket* socket,
deadbeeff137e972017-03-23 15:45:49 -0700220 const std::string& user_agent,
221 const SocketAddress& proxy,
222 const std::string& username,
223 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200224 : BufferedReadAdapter(socket, 1024),
225 proxy_(proxy),
226 agent_(user_agent),
227 user_(username),
228 pass_(password),
229 force_connect_(false),
230 state_(PS_ERROR),
231 context_(0) {}
deadbeeff137e972017-03-23 15:45:49 -0700232
233AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
234 delete context_;
235}
236
237int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
238 int ret;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100239 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
240 << proxy_.ToSensitiveString() << ")";
deadbeeff137e972017-03-23 15:45:49 -0700241 dest_ = addr;
242 state_ = PS_INIT;
243 if (ShouldIssueConnect()) {
244 BufferInput(true);
245 }
246 ret = BufferedReadAdapter::Connect(proxy_);
247 // TODO: Set state_ appropriately if Connect fails.
248 return ret;
249}
250
251SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
252 return dest_;
253}
254
255int AsyncHttpsProxySocket::Close() {
256 headers_.clear();
257 state_ = PS_ERROR;
258 dest_.Clear();
259 delete context_;
260 context_ = nullptr;
261 return BufferedReadAdapter::Close();
262}
263
264Socket::ConnState AsyncHttpsProxySocket::GetState() const {
265 if (state_ < PS_TUNNEL) {
266 return CS_CONNECTING;
267 } else if (state_ == PS_TUNNEL) {
268 return CS_CONNECTED;
269 } else {
270 return CS_CLOSED;
271 }
272}
273
Niels Möllerd0b88792021-08-12 10:32:30 +0200274void AsyncHttpsProxySocket::OnConnectEvent(Socket* socket) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100275 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
deadbeeff137e972017-03-23 15:45:49 -0700276 if (!ShouldIssueConnect()) {
277 state_ = PS_TUNNEL;
278 BufferedReadAdapter::OnConnectEvent(socket);
279 return;
280 }
281 SendRequest();
282}
283
Niels Möllerd0b88792021-08-12 10:32:30 +0200284void AsyncHttpsProxySocket::OnCloseEvent(Socket* socket, int err) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100285 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
deadbeeff137e972017-03-23 15:45:49 -0700286 if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
287 state_ = PS_ERROR;
288 Connect(dest_);
289 } else {
290 BufferedReadAdapter::OnCloseEvent(socket, err);
291 }
292}
293
294void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
295 size_t start = 0;
296 for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
297 if (state_ == PS_SKIP_BODY) {
298 size_t consume = std::min(*len - pos, content_length_);
299 pos += consume;
300 start = pos;
301 content_length_ -= consume;
302 if (content_length_ == 0) {
303 EndResponse();
304 }
305 continue;
306 }
307
308 if (data[pos++] != '\n')
309 continue;
310
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200311 size_t length = pos - start - 1;
312 if ((length > 0) && (data[start + length - 1] == '\r'))
313 --length;
deadbeeff137e972017-03-23 15:45:49 -0700314
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200315 data[start + length] = 0;
316 ProcessLine(data + start, length);
deadbeeff137e972017-03-23 15:45:49 -0700317 start = pos;
318 }
319
320 *len -= start;
321 if (*len > 0) {
322 memmove(data, data + start, *len);
323 }
324
325 if (state_ != PS_TUNNEL)
326 return;
327
328 bool remainder = (*len > 0);
329 BufferInput(false);
330 SignalConnectEvent(this);
331
332 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
333 if (remainder)
334 SignalReadEvent(this); // TODO: signal this??
335}
336
337bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
338 // TODO: Think about whether a more sophisticated test
339 // than dest port == 80 is needed.
340 return force_connect_ || (dest_.port() != 80);
341}
342
343void AsyncHttpsProxySocket::SendRequest() {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200344 rtc::StringBuilder ss;
deadbeeff137e972017-03-23 15:45:49 -0700345 ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
346 ss << "User-Agent: " << agent_ << "\r\n";
347 ss << "Host: " << dest_.HostAsURIString() << "\r\n";
348 ss << "Content-Length: 0\r\n";
349 ss << "Proxy-Connection: Keep-Alive\r\n";
350 ss << headers_;
351 ss << "\r\n";
352 std::string str = ss.str();
353 DirectSend(str.c_str(), str.size());
354 state_ = PS_LEADER;
355 expect_close_ = true;
356 content_length_ = 0;
357 headers_.clear();
358
Mirko Bonadei675513b2017-11-09 11:09:25 +0100359 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
deadbeeff137e972017-03-23 15:45:49 -0700360}
361
Yves Gerey665174f2018-06-19 15:03:05 +0200362void AsyncHttpsProxySocket::ProcessLine(char* data, size_t len) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100363 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
deadbeeff137e972017-03-23 15:45:49 -0700364
365 if (len == 0) {
366 if (state_ == PS_TUNNEL_HEADERS) {
367 state_ = PS_TUNNEL;
368 } else if (state_ == PS_ERROR_HEADERS) {
369 Error(defer_error_);
370 return;
371 } else if (state_ == PS_SKIP_HEADERS) {
372 if (content_length_) {
373 state_ = PS_SKIP_BODY;
374 } else {
375 EndResponse();
376 return;
377 }
378 } else {
Anders Klemets1425d402019-12-09 09:45:02 -0800379 if (!unknown_mechanisms_.empty()) {
380 RTC_LOG(LS_ERROR) << "Unsupported authentication methods: "
381 << unknown_mechanisms_;
deadbeeff137e972017-03-23 15:45:49 -0700382 }
383 // Unexpected end of headers
384 Error(0);
385 return;
386 }
387 } else if (state_ == PS_LEADER) {
388 unsigned int code;
389 if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
390 Error(0);
391 return;
392 }
393 switch (code) {
Yves Gerey665174f2018-06-19 15:03:05 +0200394 case 200:
395 // connection good!
396 state_ = PS_TUNNEL_HEADERS;
397 return;
deadbeeff137e972017-03-23 15:45:49 -0700398#if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
399#error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
400#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200401 case 407: // HTTP_STATUS_PROXY_AUTH_REQ
402 state_ = PS_AUTHENTICATE;
403 return;
404 default:
405 defer_error_ = 0;
406 state_ = PS_ERROR_HEADERS;
407 return;
deadbeeff137e972017-03-23 15:45:49 -0700408 }
Yves Gerey665174f2018-06-19 15:03:05 +0200409 } else if ((state_ == PS_AUTHENTICATE) &&
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100410 absl::StartsWithIgnoreCase(data, "Proxy-Authenticate:")) {
deadbeeff137e972017-03-23 15:45:49 -0700411 std::string response, auth_method;
Yves Gerey665174f2018-06-19 15:03:05 +0200412 switch (HttpAuthenticate(data + 19, len - 19, proxy_, "CONNECT", "/", user_,
413 pass_, context_, response, auth_method)) {
414 case HAR_IGNORE:
415 RTC_LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
416 if (!unknown_mechanisms_.empty())
417 unknown_mechanisms_.append(", ");
418 unknown_mechanisms_.append(auth_method);
419 break;
420 case HAR_RESPONSE:
421 headers_ = "Proxy-Authorization: ";
422 headers_.append(response);
423 headers_.append("\r\n");
424 state_ = PS_SKIP_HEADERS;
425 unknown_mechanisms_.clear();
426 break;
427 case HAR_CREDENTIALS:
428 defer_error_ = SOCKET_EACCES;
429 state_ = PS_ERROR_HEADERS;
430 unknown_mechanisms_.clear();
431 break;
432 case HAR_ERROR:
433 defer_error_ = 0;
434 state_ = PS_ERROR_HEADERS;
435 unknown_mechanisms_.clear();
436 break;
deadbeeff137e972017-03-23 15:45:49 -0700437 }
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100438 } else if (absl::StartsWithIgnoreCase(data, "Content-Length:")) {
deadbeeff137e972017-03-23 15:45:49 -0700439 content_length_ = strtoul(data + 15, 0, 0);
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100440 } else if (absl::StartsWithIgnoreCase(data, "Proxy-Connection: Keep-Alive")) {
deadbeeff137e972017-03-23 15:45:49 -0700441 expect_close_ = false;
442 /*
Niels Mölleraa3c1cc2018-11-02 10:54:56 +0100443 } else if (absl::StartsWithIgnoreCase(data, "Connection: close") {
deadbeeff137e972017-03-23 15:45:49 -0700444 expect_close_ = true;
445 */
446 }
447}
448
449void AsyncHttpsProxySocket::EndResponse() {
450 if (!expect_close_) {
451 SendRequest();
452 return;
453 }
454
455 // No point in waiting for the server to close... let's close now
456 // TODO: Refactor out PS_WAIT_CLOSE
457 state_ = PS_WAIT_CLOSE;
458 BufferedReadAdapter::Close();
459 OnCloseEvent(this, 0);
460}
461
462void AsyncHttpsProxySocket::Error(int error) {
463 BufferInput(false);
464 Close();
465 SetError(error);
466 SignalCloseEvent(this, error);
467}
468
469///////////////////////////////////////////////////////////////////////////////
470
Niels Möllerd0b88792021-08-12 10:32:30 +0200471AsyncSocksProxySocket::AsyncSocksProxySocket(Socket* socket,
deadbeeff137e972017-03-23 15:45:49 -0700472 const SocketAddress& proxy,
473 const std::string& username,
474 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200475 : BufferedReadAdapter(socket, 1024),
476 state_(SS_ERROR),
477 proxy_(proxy),
478 user_(username),
479 pass_(password) {}
deadbeeff137e972017-03-23 15:45:49 -0700480
481AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
482
483int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
484 int ret;
485 dest_ = addr;
486 state_ = SS_INIT;
487 BufferInput(true);
488 ret = BufferedReadAdapter::Connect(proxy_);
489 // TODO: Set state_ appropriately if Connect fails.
490 return ret;
491}
492
493SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
494 return dest_;
495}
496
497int AsyncSocksProxySocket::Close() {
498 state_ = SS_ERROR;
499 dest_.Clear();
500 return BufferedReadAdapter::Close();
501}
502
503Socket::ConnState AsyncSocksProxySocket::GetState() const {
504 if (state_ < SS_TUNNEL) {
505 return CS_CONNECTING;
506 } else if (state_ == SS_TUNNEL) {
507 return CS_CONNECTED;
508 } else {
509 return CS_CLOSED;
510 }
511}
512
Niels Möllerd0b88792021-08-12 10:32:30 +0200513void AsyncSocksProxySocket::OnConnectEvent(Socket* socket) {
deadbeeff137e972017-03-23 15:45:49 -0700514 SendHello();
515}
516
517void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
518 RTC_DCHECK(state_ < SS_TUNNEL);
519
520 ByteBufferReader response(data, *len);
521
522 if (state_ == SS_HELLO) {
523 uint8_t ver, method;
Yves Gerey665174f2018-06-19 15:03:05 +0200524 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&method))
deadbeeff137e972017-03-23 15:45:49 -0700525 return;
526
527 if (ver != 5) {
528 Error(0);
529 return;
530 }
531
532 if (method == 0) {
533 SendConnect();
534 } else if (method == 2) {
535 SendAuth();
536 } else {
537 Error(0);
538 return;
539 }
540 } else if (state_ == SS_AUTH) {
541 uint8_t ver, status;
Yves Gerey665174f2018-06-19 15:03:05 +0200542 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&status))
deadbeeff137e972017-03-23 15:45:49 -0700543 return;
544
545 if ((ver != 1) || (status != 0)) {
546 Error(SOCKET_EACCES);
547 return;
548 }
549
550 SendConnect();
551 } else if (state_ == SS_CONNECT) {
552 uint8_t ver, rep, rsv, atyp;
Yves Gerey665174f2018-06-19 15:03:05 +0200553 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&rep) ||
554 !response.ReadUInt8(&rsv) || !response.ReadUInt8(&atyp))
deadbeeff137e972017-03-23 15:45:49 -0700555 return;
556
557 if ((ver != 5) || (rep != 0)) {
558 Error(0);
559 return;
560 }
561
562 uint16_t port;
563 if (atyp == 1) {
564 uint32_t addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200565 if (!response.ReadUInt32(&addr) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700566 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100567 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700568 } else if (atyp == 3) {
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200569 uint8_t length;
deadbeeff137e972017-03-23 15:45:49 -0700570 std::string addr;
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200571 if (!response.ReadUInt8(&length) || !response.ReadString(&addr, length) ||
deadbeeff137e972017-03-23 15:45:49 -0700572 !response.ReadUInt16(&port))
573 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100574 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700575 } else if (atyp == 4) {
576 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200577 if (!response.ReadString(&addr, 16) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700578 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100579 RTC_LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
deadbeeff137e972017-03-23 15:45:49 -0700580 } else {
581 Error(0);
582 return;
583 }
584
585 state_ = SS_TUNNEL;
586 }
587
588 // Consume parsed data
589 *len = response.Length();
590 memmove(data, response.Data(), *len);
591
592 if (state_ != SS_TUNNEL)
593 return;
594
595 bool remainder = (*len > 0);
596 BufferInput(false);
597 SignalConnectEvent(this);
598
599 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
600 if (remainder)
601 SignalReadEvent(this); // TODO: signal this??
602}
603
604void AsyncSocksProxySocket::SendHello() {
605 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200606 request.WriteUInt8(5); // Socks Version
deadbeeff137e972017-03-23 15:45:49 -0700607 if (user_.empty()) {
608 request.WriteUInt8(1); // Authentication Mechanisms
609 request.WriteUInt8(0); // No authentication
610 } else {
611 request.WriteUInt8(2); // Authentication Mechanisms
612 request.WriteUInt8(0); // No authentication
613 request.WriteUInt8(2); // Username/Password
614 }
615 DirectSend(request.Data(), request.Length());
616 state_ = SS_HELLO;
617}
618
619void AsyncSocksProxySocket::SendAuth() {
Joachim Bauch4c6a30c2018-03-08 00:55:33 +0100620 ByteBufferWriterT<ZeroOnFreeBuffer<char>> request;
Yves Gerey665174f2018-06-19 15:03:05 +0200621 request.WriteUInt8(1); // Negotiation Version
deadbeeff137e972017-03-23 15:45:49 -0700622 request.WriteUInt8(static_cast<uint8_t>(user_.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200623 request.WriteString(user_); // Username
deadbeeff137e972017-03-23 15:45:49 -0700624 request.WriteUInt8(static_cast<uint8_t>(pass_.GetLength()));
625 size_t len = pass_.GetLength() + 1;
Yves Gerey665174f2018-06-19 15:03:05 +0200626 char* sensitive = new char[len];
deadbeeff137e972017-03-23 15:45:49 -0700627 pass_.CopyTo(sensitive, true);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100628 request.WriteBytes(sensitive, pass_.GetLength()); // Password
629 ExplicitZeroMemory(sensitive, len);
Yves Gerey665174f2018-06-19 15:03:05 +0200630 delete[] sensitive;
deadbeeff137e972017-03-23 15:45:49 -0700631 DirectSend(request.Data(), request.Length());
632 state_ = SS_AUTH;
633}
634
635void AsyncSocksProxySocket::SendConnect() {
636 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200637 request.WriteUInt8(5); // Socks Version
638 request.WriteUInt8(1); // CONNECT
639 request.WriteUInt8(0); // Reserved
deadbeeff137e972017-03-23 15:45:49 -0700640 if (dest_.IsUnresolvedIP()) {
641 std::string hostname = dest_.hostname();
Yves Gerey665174f2018-06-19 15:03:05 +0200642 request.WriteUInt8(3); // DOMAINNAME
deadbeeff137e972017-03-23 15:45:49 -0700643 request.WriteUInt8(static_cast<uint8_t>(hostname.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200644 request.WriteString(hostname); // Destination Hostname
deadbeeff137e972017-03-23 15:45:49 -0700645 } else {
646 request.WriteUInt8(1); // IPV4
647 request.WriteUInt32(dest_.ip()); // Destination IP
648 }
649 request.WriteUInt16(dest_.port()); // Destination Port
650 DirectSend(request.Data(), request.Length());
651 state_ = SS_CONNECT;
652}
653
654void AsyncSocksProxySocket::Error(int error) {
655 state_ = SS_ERROR;
656 BufferInput(false);
657 Close();
658 SetError(SOCKET_EACCES);
659 SignalCloseEvent(this, error);
660}
661
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000662} // namespace rtc