blob: f6fa182f5d7d4e54a24ed49596295943091113be [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:261/*
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 13:03:0512#pragma warning(disable : 4786)
henrike@webrtc.orgf0488722014-05-13 18:00:2613#endif
14
Ali Tofigh7fa90572022-03-17 14:47:4915#include "rtc_base/socket_adapters.h"
16
andresp@webrtc.orgff689be2015-02-12 11:54:2617#include <algorithm>
18
Niels Mölleraa3c1cc2018-11-02 09:54:5619#include "absl/strings/match.h"
Ali Tofigh7fa90572022-03-17 14:47:4920#include "absl/strings/string_view.h"
Yves Gerey988cc082018-10-23 10:03:0121#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 17:11:0022#include "rtc_base/byte_buffer.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3123#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 17:11:0024#include "rtc_base/http_common.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3125#include "rtc_base/logging.h"
Jonas Olsson366a50c2018-09-06 11:41:3026#include "rtc_base/strings/string_builder.h"
Joachim Bauch5b32f232018-03-07 19:02:2627#include "rtc_base/zero_memory.h"
henrike@webrtc.orgf0488722014-05-13 18:00:2628
henrike@webrtc.orgf0488722014-05-13 18:00:2629namespace rtc {
30
Niels Möllerd0b88792021-08-12 08:32:3031BufferedReadAdapter::BufferedReadAdapter(Socket* socket, size_t size)
Yves Gerey665174f2018-06-19 13:03:0532 : AsyncSocketAdapter(socket),
33 buffer_size_(size),
34 data_len_(0),
35 buffering_(false) {
henrike@webrtc.orgf0488722014-05-13 18:00:2636 buffer_ = new char[buffer_size_];
37}
38
39BufferedReadAdapter::~BufferedReadAdapter() {
Yves Gerey665174f2018-06-19 13:03:0540 delete[] buffer_;
henrike@webrtc.orgf0488722014-05-13 18:00:2641}
42
Yves Gerey665174f2018-06-19 13:03:0543int BufferedReadAdapter::Send(const void* pv, size_t cb) {
henrike@webrtc.orgf0488722014-05-13 18:00:2644 if (buffering_) {
45 // TODO: Spoof error better; Signal Writeable
Niels Möller8729d782021-08-11 09:22:4446 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:2647 return -1;
48 }
49 return AsyncSocketAdapter::Send(pv, cb);
50}
51
Stefan Holmer9131efd2016-05-23 16:19:2652int BufferedReadAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
henrike@webrtc.orgf0488722014-05-13 18:00:2653 if (buffering_) {
Niels Möller8729d782021-08-11 09:22:4454 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:2655 return -1;
56 }
57
58 size_t read = 0;
59
60 if (data_len_) {
andresp@webrtc.orgff689be2015-02-12 11:54:2661 read = std::min(cb, data_len_);
henrike@webrtc.orgf0488722014-05-13 18:00:2662 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 13:03:0567 pv = static_cast<char*>(pv) + read;
henrike@webrtc.orgf0488722014-05-13 18:00:2668 cb -= read;
69 }
70
71 // FIX: If cb == 0, we won't generate another read event
72
Stefan Holmer9131efd2016-05-23 16:19:2673 int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
deadbeefc5d0d952015-07-16 17:22:2174 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:2678
deadbeefc5d0d952015-07-16 17:22:2179 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:2686}
87
88void BufferedReadAdapter::BufferInput(bool on) {
89 buffering_ = on;
90}
91
Niels Möllerd0b88792021-08-12 08:32:3092void BufferedReadAdapter::OnReadEvent(Socket* socket) {
Niels Möller8729d782021-08-11 09:22:4493 RTC_DCHECK(socket == GetSocket());
henrike@webrtc.orgf0488722014-05-13 18:00:2694
95 if (!buffering_) {
96 AsyncSocketAdapter::OnReadEvent(socket);
97 return;
98 }
99
100 if (data_len_ >= buffer_size_) {
Jonas Olsson45cc8902018-02-13 09:37:07101 RTC_LOG(LS_ERROR) << "Input buffer overflow";
Artem Titovd3251962021-11-15 15:57:07102 RTC_DCHECK_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26103 data_len_ = 0;
104 }
105
Niels Möller8729d782021-08-11 09:22:44106 int len = AsyncSocketAdapter::Recv(buffer_ + data_len_,
107 buffer_size_ - data_len_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26108 if (len < 0) {
109 // TODO: Do something better like forwarding the error to the user.
Harald Alvestrand97597c02021-11-04 12:01:23110 RTC_LOG_ERR(LS_INFO) << "Recv";
henrike@webrtc.orgf0488722014-05-13 18:00:26111 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 10:23:21124static 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:26138};
139
Niels Möller44153152018-12-17 13:04:05140// 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:26147// This is a TLSv1 SERVER_HELLO message.
Peter Boström0c4e06b2015-10-07 10:23:21148static 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:26166};
167
Niels Möller44153152018-12-17 13:04:05168// static
169ArrayView<const uint8_t> AsyncSSLSocket::SslServerHello() {
170 return {kSslServerHello, sizeof(kSslServerHello)};
171}
172
Niels Möllerd0b88792021-08-12 08:32:30173AsyncSSLSocket::AsyncSSLSocket(Socket* socket)
Yves Gerey665174f2018-06-19 13:03:05174 : BufferedReadAdapter(socket, 1024) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26175
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 08:32:30183void AsyncSSLSocket::OnConnectEvent(Socket* socket) {
Niels Möller8729d782021-08-11 09:22:44184 RTC_DCHECK(socket == GetSocket());
henrike@webrtc.orgf0488722014-05-13 18:00:26185 // TODO: we could buffer output too...
nissec16fa5e2017-02-07 15:18:43186 const int res = DirectSend(kSslClientHello, sizeof(kSslClientHello));
Niels Möllerb0cb4d12021-08-20 09:04:04187 if (res != sizeof(kSslClientHello)) {
Niels Möller2eb465f2021-08-23 09:17:56188 RTC_LOG(LS_ERROR) << "Sending fake SSL ClientHello message failed.";
Niels Möllerb0cb4d12021-08-20 09:04:04189 Close();
190 SignalCloseEvent(this, 0);
191 }
henrike@webrtc.orgf0488722014-05-13 18:00:26192}
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 09:17:56199 RTC_LOG(LS_ERROR) << "Received non-matching fake SSL ServerHello message.";
henrike@webrtc.orgf0488722014-05-13 18:00:26200 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 22:45:49219///////////////////////////////////////////////////////////////////////////////
220
Niels Möllerd0b88792021-08-12 08:32:30221AsyncHttpsProxySocket::AsyncHttpsProxySocket(Socket* socket,
Ali Tofigh7fa90572022-03-17 14:47:49222 absl::string_view user_agent,
deadbeeff137e972017-03-23 22:45:49223 const SocketAddress& proxy,
Ali Tofigh7fa90572022-03-17 14:47:49224 absl::string_view username,
deadbeeff137e972017-03-23 22:45:49225 const CryptString& password)
Yves Gerey665174f2018-06-19 13:03:05226 : 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 22:45:49234
235AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
236 delete context_;
237}
238
239int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
240 int ret;
Mirko Bonadei675513b2017-11-09 10:09:25241 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
242 << proxy_.ToSensitiveString() << ")";
deadbeeff137e972017-03-23 22:45:49243 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 08:32:30276void AsyncHttpsProxySocket::OnConnectEvent(Socket* socket) {
Mirko Bonadei675513b2017-11-09 10:09:25277 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
deadbeeff137e972017-03-23 22:45:49278 if (!ShouldIssueConnect()) {
279 state_ = PS_TUNNEL;
280 BufferedReadAdapter::OnConnectEvent(socket);
281 return;
282 }
283 SendRequest();
284}
285
Niels Möllerd0b88792021-08-12 08:32:30286void AsyncHttpsProxySocket::OnCloseEvent(Socket* socket, int err) {
Mirko Bonadei675513b2017-11-09 10:09:25287 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
deadbeeff137e972017-03-23 22:45:49288 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 09:26:11313 size_t length = pos - start - 1;
314 if ((length > 0) && (data[start + length - 1] == '\r'))
315 --length;
deadbeeff137e972017-03-23 22:45:49316
Mirko Bonadei54c90f22021-10-03 09:26:11317 data[start + length] = 0;
318 ProcessLine(data + start, length);
deadbeeff137e972017-03-23 22:45:49319 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 11:41:30346 rtc::StringBuilder ss;
deadbeeff137e972017-03-23 22:45:49347 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 10:09:25361 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
deadbeeff137e972017-03-23 22:45:49362}
363
Yves Gerey665174f2018-06-19 13:03:05364void AsyncHttpsProxySocket::ProcessLine(char* data, size_t len) {
Mirko Bonadei675513b2017-11-09 10:09:25365 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
deadbeeff137e972017-03-23 22:45:49366
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 17:45:02381 if (!unknown_mechanisms_.empty()) {
382 RTC_LOG(LS_ERROR) << "Unsupported authentication methods: "
383 << unknown_mechanisms_;
deadbeeff137e972017-03-23 22:45:49384 }
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 13:03:05396 case 200:
397 // connection good!
398 state_ = PS_TUNNEL_HEADERS;
399 return;
deadbeeff137e972017-03-23 22:45:49400#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 13:03:05403 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 22:45:49410 }
Yves Gerey665174f2018-06-19 13:03:05411 } else if ((state_ == PS_AUTHENTICATE) &&
Niels Mölleraa3c1cc2018-11-02 09:54:56412 absl::StartsWithIgnoreCase(data, "Proxy-Authenticate:")) {
deadbeeff137e972017-03-23 22:45:49413 std::string response, auth_method;
Ali Tofigh2ab914c2022-04-13 10:55:15414 switch (HttpAuthenticate(absl::string_view(data + 19, len - 19), proxy_,
415 "CONNECT", "/", user_, pass_, context_, response,
416 auth_method)) {
Yves Gerey665174f2018-06-19 13:03:05417 case HAR_IGNORE:
418 RTC_LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
419 if (!unknown_mechanisms_.empty())
420 unknown_mechanisms_.append(", ");
421 unknown_mechanisms_.append(auth_method);
422 break;
423 case HAR_RESPONSE:
424 headers_ = "Proxy-Authorization: ";
425 headers_.append(response);
426 headers_.append("\r\n");
427 state_ = PS_SKIP_HEADERS;
428 unknown_mechanisms_.clear();
429 break;
430 case HAR_CREDENTIALS:
431 defer_error_ = SOCKET_EACCES;
432 state_ = PS_ERROR_HEADERS;
433 unknown_mechanisms_.clear();
434 break;
435 case HAR_ERROR:
436 defer_error_ = 0;
437 state_ = PS_ERROR_HEADERS;
438 unknown_mechanisms_.clear();
439 break;
deadbeeff137e972017-03-23 22:45:49440 }
Niels Mölleraa3c1cc2018-11-02 09:54:56441 } else if (absl::StartsWithIgnoreCase(data, "Content-Length:")) {
deadbeeff137e972017-03-23 22:45:49442 content_length_ = strtoul(data + 15, 0, 0);
Niels Mölleraa3c1cc2018-11-02 09:54:56443 } else if (absl::StartsWithIgnoreCase(data, "Proxy-Connection: Keep-Alive")) {
deadbeeff137e972017-03-23 22:45:49444 expect_close_ = false;
445 /*
Niels Mölleraa3c1cc2018-11-02 09:54:56446 } else if (absl::StartsWithIgnoreCase(data, "Connection: close") {
deadbeeff137e972017-03-23 22:45:49447 expect_close_ = true;
448 */
449 }
450}
451
452void AsyncHttpsProxySocket::EndResponse() {
453 if (!expect_close_) {
454 SendRequest();
455 return;
456 }
457
458 // No point in waiting for the server to close... let's close now
459 // TODO: Refactor out PS_WAIT_CLOSE
460 state_ = PS_WAIT_CLOSE;
461 BufferedReadAdapter::Close();
462 OnCloseEvent(this, 0);
463}
464
465void AsyncHttpsProxySocket::Error(int error) {
466 BufferInput(false);
467 Close();
468 SetError(error);
469 SignalCloseEvent(this, error);
470}
471
henrike@webrtc.orgf0488722014-05-13 18:00:26472} // namespace rtc