blob: 45e002a6c78fcfb08b05b28c4d13523df69653ba [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#if defined(_MSC_VER) && _MSC_VER < 1300
Yves Gerey665174f2018-06-19 15:03:05 +020012#pragma warning(disable : 4786)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013#endif
14
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015#include <errno.h>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
Yves Gerey665174f2018-06-19 15:03:05 +020019#include <time.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020
21#if defined(WEBRTC_WIN)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022#include <windows.h>
23#include <winsock2.h>
24#include <ws2tcpip.h>
Yves Gerey988cc082018-10-23 12:03:01 +020025
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026#define SECURITY_WIN32
27#include <security.h>
28#endif
29
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000030#include <algorithm>
31
Yves Gerey988cc082018-10-23 12:03:01 +020032#include "rtc_base/buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/bytebuffer.h"
34#include "rtc_base/checks.h"
35#include "rtc_base/httpcommon.h"
36#include "rtc_base/logging.h"
37#include "rtc_base/socketadapters.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020038#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/stringutils.h"
Joachim Bauch5b32f232018-03-07 20:02:26 +010040#include "rtc_base/zero_memory.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042namespace rtc {
43
44BufferedReadAdapter::BufferedReadAdapter(AsyncSocket* socket, size_t size)
Yves Gerey665174f2018-06-19 15:03:05 +020045 : AsyncSocketAdapter(socket),
46 buffer_size_(size),
47 data_len_(0),
48 buffering_(false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000049 buffer_ = new char[buffer_size_];
50}
51
52BufferedReadAdapter::~BufferedReadAdapter() {
Yves Gerey665174f2018-06-19 15:03:05 +020053 delete[] buffer_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000054}
55
Yves Gerey665174f2018-06-19 15:03:05 +020056int BufferedReadAdapter::Send(const void* pv, size_t cb) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057 if (buffering_) {
58 // TODO: Spoof error better; Signal Writeable
59 socket_->SetError(EWOULDBLOCK);
60 return -1;
61 }
62 return AsyncSocketAdapter::Send(pv, cb);
63}
64
Stefan Holmer9131efd2016-05-23 18:19:26 +020065int BufferedReadAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066 if (buffering_) {
67 socket_->SetError(EWOULDBLOCK);
68 return -1;
69 }
70
71 size_t read = 0;
72
73 if (data_len_) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000074 read = std::min(cb, data_len_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000075 memcpy(pv, buffer_, read);
76 data_len_ -= read;
77 if (data_len_ > 0) {
78 memmove(buffer_, buffer_ + read, data_len_);
79 }
Yves Gerey665174f2018-06-19 15:03:05 +020080 pv = static_cast<char*>(pv) + read;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000081 cb -= read;
82 }
83
84 // FIX: If cb == 0, we won't generate another read event
85
Stefan Holmer9131efd2016-05-23 18:19:26 +020086 int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
deadbeefc5d0d952015-07-16 10:22:21 -070087 if (res >= 0) {
88 // Read from socket and possibly buffer; return combined length
89 return res + static_cast<int>(read);
90 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091
deadbeefc5d0d952015-07-16 10:22:21 -070092 if (read > 0) {
93 // Failed to read from socket, but still read something from buffer
94 return static_cast<int>(read);
95 }
96
97 // Didn't read anything; return error from socket
98 return res;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000099}
100
101void BufferedReadAdapter::BufferInput(bool on) {
102 buffering_ = on;
103}
104
Yves Gerey665174f2018-06-19 15:03:05 +0200105void BufferedReadAdapter::OnReadEvent(AsyncSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800106 RTC_DCHECK(socket == socket_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107
108 if (!buffering_) {
109 AsyncSocketAdapter::OnReadEvent(socket);
110 return;
111 }
112
113 if (data_len_ >= buffer_size_) {
Jonas Olsson45cc8902018-02-13 10:37:07 +0100114 RTC_LOG(LS_ERROR) << "Input buffer overflow";
nissec80e7412017-01-11 05:56:46 -0800115 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116 data_len_ = 0;
117 }
118
Stefan Holmer9131efd2016-05-23 18:19:26 +0200119 int len =
120 socket_->Recv(buffer_ + data_len_, buffer_size_ - data_len_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121 if (len < 0) {
122 // TODO: Do something better like forwarding the error to the user.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100123 RTC_LOG_ERR(INFO) << "Recv";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124 return;
125 }
126
127 data_len_ += len;
128
129 ProcessInput(buffer_, &data_len_);
130}
131
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000132AsyncProxyServerSocket::AsyncProxyServerSocket(AsyncSocket* socket,
133 size_t buffer_size)
Yves Gerey665174f2018-06-19 15:03:05 +0200134 : BufferedReadAdapter(socket, buffer_size) {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000135
136AsyncProxyServerSocket::~AsyncProxyServerSocket() = default;
137
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138///////////////////////////////////////////////////////////////////////////////
139
140// This is a SSL v2 CLIENT_HELLO message.
141// TODO: Should this have a session id? The response doesn't have a
142// certificate, so the hello should have a session id.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200143static const uint8_t kSslClientHello[] = {
144 0x80, 0x46, // msg len
145 0x01, // CLIENT_HELLO
146 0x03, 0x01, // SSL 3.1
147 0x00, 0x2d, // ciphersuite len
148 0x00, 0x00, // session id len
149 0x00, 0x10, // challenge len
150 0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0, // ciphersuites
151 0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80, //
152 0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a, //
153 0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, //
154 0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06, //
155 0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc, // challenge
156 0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea //
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000157};
158
159// This is a TLSv1 SERVER_HELLO message.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200160static const uint8_t kSslServerHello[] = {
161 0x16, // handshake message
162 0x03, 0x01, // SSL 3.1
163 0x00, 0x4a, // message len
164 0x02, // SERVER_HELLO
165 0x00, 0x00, 0x46, // handshake len
166 0x03, 0x01, // SSL 3.1
167 0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0, // server random
168 0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f, //
169 0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1, //
170 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f, //
171 0x20, // session id len
172 0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f, // session id
173 0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b, //
174 0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38, //
175 0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c, //
176 0x00, 0x04, // RSA/RC4-128/MD5
177 0x00 // null compression
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178};
179
180AsyncSSLSocket::AsyncSSLSocket(AsyncSocket* socket)
Yves Gerey665174f2018-06-19 15:03:05 +0200181 : BufferedReadAdapter(socket, 1024) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182
183int AsyncSSLSocket::Connect(const SocketAddress& addr) {
184 // Begin buffering before we connect, so that there isn't a race condition
185 // between potential senders and receiving the OnConnectEvent signal
186 BufferInput(true);
187 return BufferedReadAdapter::Connect(addr);
188}
189
Yves Gerey665174f2018-06-19 15:03:05 +0200190void AsyncSSLSocket::OnConnectEvent(AsyncSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800191 RTC_DCHECK(socket == socket_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000192 // TODO: we could buffer output too...
nissec16fa5e2017-02-07 07:18:43 -0800193 const int res = DirectSend(kSslClientHello, sizeof(kSslClientHello));
194 RTC_DCHECK_EQ(sizeof(kSslClientHello), res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000195}
196
197void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
198 if (*len < sizeof(kSslServerHello))
199 return;
200
201 if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
202 Close();
203 SignalCloseEvent(this, 0); // TODO: error code?
204 return;
205 }
206
207 *len -= sizeof(kSslServerHello);
208 if (*len > 0) {
209 memmove(data, data + sizeof(kSslServerHello), *len);
210 }
211
212 bool remainder = (*len > 0);
213 BufferInput(false);
214 SignalConnectEvent(this);
215
216 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
217 if (remainder)
218 SignalReadEvent(this);
219}
220
221AsyncSSLServerSocket::AsyncSSLServerSocket(AsyncSocket* socket)
Yves Gerey665174f2018-06-19 15:03:05 +0200222 : BufferedReadAdapter(socket, 1024) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000223 BufferInput(true);
224}
225
226void AsyncSSLServerSocket::ProcessInput(char* data, size_t* len) {
227 // We only accept client hello messages.
228 if (*len < sizeof(kSslClientHello)) {
229 return;
230 }
231
232 if (memcmp(kSslClientHello, data, sizeof(kSslClientHello)) != 0) {
233 Close();
234 SignalCloseEvent(this, 0);
235 return;
236 }
237
238 *len -= sizeof(kSslClientHello);
239
240 // Clients should not send more data until the handshake is completed.
nisseede5da42017-01-12 05:15:36 -0800241 RTC_DCHECK(*len == 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242
243 // Send a server hello back to the client.
244 DirectSend(kSslServerHello, sizeof(kSslServerHello));
245
246 // Handshake completed for us, redirect input to our parent.
247 BufferInput(false);
248}
249
deadbeeff137e972017-03-23 15:45:49 -0700250///////////////////////////////////////////////////////////////////////////////
251
252AsyncHttpsProxySocket::AsyncHttpsProxySocket(AsyncSocket* socket,
253 const std::string& user_agent,
254 const SocketAddress& proxy,
255 const std::string& username,
256 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200257 : BufferedReadAdapter(socket, 1024),
258 proxy_(proxy),
259 agent_(user_agent),
260 user_(username),
261 pass_(password),
262 force_connect_(false),
263 state_(PS_ERROR),
264 context_(0) {}
deadbeeff137e972017-03-23 15:45:49 -0700265
266AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
267 delete context_;
268}
269
270int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
271 int ret;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100272 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
273 << proxy_.ToSensitiveString() << ")";
deadbeeff137e972017-03-23 15:45:49 -0700274 dest_ = addr;
275 state_ = PS_INIT;
276 if (ShouldIssueConnect()) {
277 BufferInput(true);
278 }
279 ret = BufferedReadAdapter::Connect(proxy_);
280 // TODO: Set state_ appropriately if Connect fails.
281 return ret;
282}
283
284SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
285 return dest_;
286}
287
288int AsyncHttpsProxySocket::Close() {
289 headers_.clear();
290 state_ = PS_ERROR;
291 dest_.Clear();
292 delete context_;
293 context_ = nullptr;
294 return BufferedReadAdapter::Close();
295}
296
297Socket::ConnState AsyncHttpsProxySocket::GetState() const {
298 if (state_ < PS_TUNNEL) {
299 return CS_CONNECTING;
300 } else if (state_ == PS_TUNNEL) {
301 return CS_CONNECTED;
302 } else {
303 return CS_CLOSED;
304 }
305}
306
Yves Gerey665174f2018-06-19 15:03:05 +0200307void AsyncHttpsProxySocket::OnConnectEvent(AsyncSocket* socket) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100308 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
deadbeeff137e972017-03-23 15:45:49 -0700309 if (!ShouldIssueConnect()) {
310 state_ = PS_TUNNEL;
311 BufferedReadAdapter::OnConnectEvent(socket);
312 return;
313 }
314 SendRequest();
315}
316
Yves Gerey665174f2018-06-19 15:03:05 +0200317void AsyncHttpsProxySocket::OnCloseEvent(AsyncSocket* socket, int err) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100318 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
deadbeeff137e972017-03-23 15:45:49 -0700319 if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
320 state_ = PS_ERROR;
321 Connect(dest_);
322 } else {
323 BufferedReadAdapter::OnCloseEvent(socket, err);
324 }
325}
326
327void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
328 size_t start = 0;
329 for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
330 if (state_ == PS_SKIP_BODY) {
331 size_t consume = std::min(*len - pos, content_length_);
332 pos += consume;
333 start = pos;
334 content_length_ -= consume;
335 if (content_length_ == 0) {
336 EndResponse();
337 }
338 continue;
339 }
340
341 if (data[pos++] != '\n')
342 continue;
343
344 size_t len = pos - start - 1;
345 if ((len > 0) && (data[start + len - 1] == '\r'))
346 --len;
347
348 data[start + len] = 0;
349 ProcessLine(data + start, len);
350 start = pos;
351 }
352
353 *len -= start;
354 if (*len > 0) {
355 memmove(data, data + start, *len);
356 }
357
358 if (state_ != PS_TUNNEL)
359 return;
360
361 bool remainder = (*len > 0);
362 BufferInput(false);
363 SignalConnectEvent(this);
364
365 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
366 if (remainder)
367 SignalReadEvent(this); // TODO: signal this??
368}
369
370bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
371 // TODO: Think about whether a more sophisticated test
372 // than dest port == 80 is needed.
373 return force_connect_ || (dest_.port() != 80);
374}
375
376void AsyncHttpsProxySocket::SendRequest() {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200377 rtc::StringBuilder ss;
deadbeeff137e972017-03-23 15:45:49 -0700378 ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
379 ss << "User-Agent: " << agent_ << "\r\n";
380 ss << "Host: " << dest_.HostAsURIString() << "\r\n";
381 ss << "Content-Length: 0\r\n";
382 ss << "Proxy-Connection: Keep-Alive\r\n";
383 ss << headers_;
384 ss << "\r\n";
385 std::string str = ss.str();
386 DirectSend(str.c_str(), str.size());
387 state_ = PS_LEADER;
388 expect_close_ = true;
389 content_length_ = 0;
390 headers_.clear();
391
Mirko Bonadei675513b2017-11-09 11:09:25 +0100392 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
deadbeeff137e972017-03-23 15:45:49 -0700393}
394
Yves Gerey665174f2018-06-19 15:03:05 +0200395void AsyncHttpsProxySocket::ProcessLine(char* data, size_t len) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100396 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
deadbeeff137e972017-03-23 15:45:49 -0700397
398 if (len == 0) {
399 if (state_ == PS_TUNNEL_HEADERS) {
400 state_ = PS_TUNNEL;
401 } else if (state_ == PS_ERROR_HEADERS) {
402 Error(defer_error_);
403 return;
404 } else if (state_ == PS_SKIP_HEADERS) {
405 if (content_length_) {
406 state_ = PS_SKIP_BODY;
407 } else {
408 EndResponse();
409 return;
410 }
411 } else {
412 static bool report = false;
413 if (!unknown_mechanisms_.empty() && !report) {
414 report = true;
415 std::string msg(
Yves Gerey665174f2018-06-19 15:03:05 +0200416 "Unable to connect to the Google Talk service due to an "
417 "incompatibility "
418 "with your proxy.\r\nPlease help us resolve this issue by "
419 "submitting the "
420 "following information to us using our technical issue submission "
421 "form "
422 "at:\r\n\r\n"
423 "http://www.google.com/support/talk/bin/request.py\r\n\r\n"
424 "We apologize for the inconvenience.\r\n\r\n"
425 "Information to submit to Google: ");
426 // std::string msg("Please report the following information to
427 // foo@bar.com:\r\nUnknown methods: ");
deadbeeff137e972017-03-23 15:45:49 -0700428 msg.append(unknown_mechanisms_);
429#if defined(WEBRTC_WIN)
430 MessageBoxA(0, msg.c_str(), "Oops!", MB_OK);
431#endif
432#if defined(WEBRTC_POSIX)
433 // TODO: Raise a signal so the UI can be separated.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100434 RTC_LOG(LS_ERROR) << "Oops!\n\n" << msg;
deadbeeff137e972017-03-23 15:45:49 -0700435#endif
436 }
437 // Unexpected end of headers
438 Error(0);
439 return;
440 }
441 } else if (state_ == PS_LEADER) {
442 unsigned int code;
443 if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
444 Error(0);
445 return;
446 }
447 switch (code) {
Yves Gerey665174f2018-06-19 15:03:05 +0200448 case 200:
449 // connection good!
450 state_ = PS_TUNNEL_HEADERS;
451 return;
deadbeeff137e972017-03-23 15:45:49 -0700452#if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
453#error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
454#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200455 case 407: // HTTP_STATUS_PROXY_AUTH_REQ
456 state_ = PS_AUTHENTICATE;
457 return;
458 default:
459 defer_error_ = 0;
460 state_ = PS_ERROR_HEADERS;
461 return;
deadbeeff137e972017-03-23 15:45:49 -0700462 }
Yves Gerey665174f2018-06-19 15:03:05 +0200463 } else if ((state_ == PS_AUTHENTICATE) &&
464 (_strnicmp(data, "Proxy-Authenticate:", 19) == 0)) {
deadbeeff137e972017-03-23 15:45:49 -0700465 std::string response, auth_method;
Yves Gerey665174f2018-06-19 15:03:05 +0200466 switch (HttpAuthenticate(data + 19, len - 19, proxy_, "CONNECT", "/", user_,
467 pass_, context_, response, auth_method)) {
468 case HAR_IGNORE:
469 RTC_LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
470 if (!unknown_mechanisms_.empty())
471 unknown_mechanisms_.append(", ");
472 unknown_mechanisms_.append(auth_method);
473 break;
474 case HAR_RESPONSE:
475 headers_ = "Proxy-Authorization: ";
476 headers_.append(response);
477 headers_.append("\r\n");
478 state_ = PS_SKIP_HEADERS;
479 unknown_mechanisms_.clear();
480 break;
481 case HAR_CREDENTIALS:
482 defer_error_ = SOCKET_EACCES;
483 state_ = PS_ERROR_HEADERS;
484 unknown_mechanisms_.clear();
485 break;
486 case HAR_ERROR:
487 defer_error_ = 0;
488 state_ = PS_ERROR_HEADERS;
489 unknown_mechanisms_.clear();
490 break;
deadbeeff137e972017-03-23 15:45:49 -0700491 }
492 } else if (_strnicmp(data, "Content-Length:", 15) == 0) {
493 content_length_ = strtoul(data + 15, 0, 0);
494 } else if (_strnicmp(data, "Proxy-Connection: Keep-Alive", 28) == 0) {
495 expect_close_ = false;
496 /*
497 } else if (_strnicmp(data, "Connection: close", 17) == 0) {
498 expect_close_ = true;
499 */
500 }
501}
502
503void AsyncHttpsProxySocket::EndResponse() {
504 if (!expect_close_) {
505 SendRequest();
506 return;
507 }
508
509 // No point in waiting for the server to close... let's close now
510 // TODO: Refactor out PS_WAIT_CLOSE
511 state_ = PS_WAIT_CLOSE;
512 BufferedReadAdapter::Close();
513 OnCloseEvent(this, 0);
514}
515
516void AsyncHttpsProxySocket::Error(int error) {
517 BufferInput(false);
518 Close();
519 SetError(error);
520 SignalCloseEvent(this, error);
521}
522
523///////////////////////////////////////////////////////////////////////////////
524
525AsyncSocksProxySocket::AsyncSocksProxySocket(AsyncSocket* socket,
526 const SocketAddress& proxy,
527 const std::string& username,
528 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200529 : BufferedReadAdapter(socket, 1024),
530 state_(SS_ERROR),
531 proxy_(proxy),
532 user_(username),
533 pass_(password) {}
deadbeeff137e972017-03-23 15:45:49 -0700534
535AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
536
537int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
538 int ret;
539 dest_ = addr;
540 state_ = SS_INIT;
541 BufferInput(true);
542 ret = BufferedReadAdapter::Connect(proxy_);
543 // TODO: Set state_ appropriately if Connect fails.
544 return ret;
545}
546
547SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
548 return dest_;
549}
550
551int AsyncSocksProxySocket::Close() {
552 state_ = SS_ERROR;
553 dest_.Clear();
554 return BufferedReadAdapter::Close();
555}
556
557Socket::ConnState AsyncSocksProxySocket::GetState() const {
558 if (state_ < SS_TUNNEL) {
559 return CS_CONNECTING;
560 } else if (state_ == SS_TUNNEL) {
561 return CS_CONNECTED;
562 } else {
563 return CS_CLOSED;
564 }
565}
566
567void AsyncSocksProxySocket::OnConnectEvent(AsyncSocket* socket) {
568 SendHello();
569}
570
571void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
572 RTC_DCHECK(state_ < SS_TUNNEL);
573
574 ByteBufferReader response(data, *len);
575
576 if (state_ == SS_HELLO) {
577 uint8_t ver, method;
Yves Gerey665174f2018-06-19 15:03:05 +0200578 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&method))
deadbeeff137e972017-03-23 15:45:49 -0700579 return;
580
581 if (ver != 5) {
582 Error(0);
583 return;
584 }
585
586 if (method == 0) {
587 SendConnect();
588 } else if (method == 2) {
589 SendAuth();
590 } else {
591 Error(0);
592 return;
593 }
594 } else if (state_ == SS_AUTH) {
595 uint8_t ver, status;
Yves Gerey665174f2018-06-19 15:03:05 +0200596 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&status))
deadbeeff137e972017-03-23 15:45:49 -0700597 return;
598
599 if ((ver != 1) || (status != 0)) {
600 Error(SOCKET_EACCES);
601 return;
602 }
603
604 SendConnect();
605 } else if (state_ == SS_CONNECT) {
606 uint8_t ver, rep, rsv, atyp;
Yves Gerey665174f2018-06-19 15:03:05 +0200607 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&rep) ||
608 !response.ReadUInt8(&rsv) || !response.ReadUInt8(&atyp))
deadbeeff137e972017-03-23 15:45:49 -0700609 return;
610
611 if ((ver != 5) || (rep != 0)) {
612 Error(0);
613 return;
614 }
615
616 uint16_t port;
617 if (atyp == 1) {
618 uint32_t addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200619 if (!response.ReadUInt32(&addr) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700620 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100621 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700622 } else if (atyp == 3) {
623 uint8_t len;
624 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200625 if (!response.ReadUInt8(&len) || !response.ReadString(&addr, len) ||
deadbeeff137e972017-03-23 15:45:49 -0700626 !response.ReadUInt16(&port))
627 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100628 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700629 } else if (atyp == 4) {
630 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200631 if (!response.ReadString(&addr, 16) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700632 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100633 RTC_LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
deadbeeff137e972017-03-23 15:45:49 -0700634 } else {
635 Error(0);
636 return;
637 }
638
639 state_ = SS_TUNNEL;
640 }
641
642 // Consume parsed data
643 *len = response.Length();
644 memmove(data, response.Data(), *len);
645
646 if (state_ != SS_TUNNEL)
647 return;
648
649 bool remainder = (*len > 0);
650 BufferInput(false);
651 SignalConnectEvent(this);
652
653 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
654 if (remainder)
655 SignalReadEvent(this); // TODO: signal this??
656}
657
658void AsyncSocksProxySocket::SendHello() {
659 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200660 request.WriteUInt8(5); // Socks Version
deadbeeff137e972017-03-23 15:45:49 -0700661 if (user_.empty()) {
662 request.WriteUInt8(1); // Authentication Mechanisms
663 request.WriteUInt8(0); // No authentication
664 } else {
665 request.WriteUInt8(2); // Authentication Mechanisms
666 request.WriteUInt8(0); // No authentication
667 request.WriteUInt8(2); // Username/Password
668 }
669 DirectSend(request.Data(), request.Length());
670 state_ = SS_HELLO;
671}
672
673void AsyncSocksProxySocket::SendAuth() {
Joachim Bauch4c6a30c2018-03-08 00:55:33 +0100674 ByteBufferWriterT<ZeroOnFreeBuffer<char>> request;
Yves Gerey665174f2018-06-19 15:03:05 +0200675 request.WriteUInt8(1); // Negotiation Version
deadbeeff137e972017-03-23 15:45:49 -0700676 request.WriteUInt8(static_cast<uint8_t>(user_.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200677 request.WriteString(user_); // Username
deadbeeff137e972017-03-23 15:45:49 -0700678 request.WriteUInt8(static_cast<uint8_t>(pass_.GetLength()));
679 size_t len = pass_.GetLength() + 1;
Yves Gerey665174f2018-06-19 15:03:05 +0200680 char* sensitive = new char[len];
deadbeeff137e972017-03-23 15:45:49 -0700681 pass_.CopyTo(sensitive, true);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100682 request.WriteBytes(sensitive, pass_.GetLength()); // Password
683 ExplicitZeroMemory(sensitive, len);
Yves Gerey665174f2018-06-19 15:03:05 +0200684 delete[] sensitive;
deadbeeff137e972017-03-23 15:45:49 -0700685 DirectSend(request.Data(), request.Length());
686 state_ = SS_AUTH;
687}
688
689void AsyncSocksProxySocket::SendConnect() {
690 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200691 request.WriteUInt8(5); // Socks Version
692 request.WriteUInt8(1); // CONNECT
693 request.WriteUInt8(0); // Reserved
deadbeeff137e972017-03-23 15:45:49 -0700694 if (dest_.IsUnresolvedIP()) {
695 std::string hostname = dest_.hostname();
Yves Gerey665174f2018-06-19 15:03:05 +0200696 request.WriteUInt8(3); // DOMAINNAME
deadbeeff137e972017-03-23 15:45:49 -0700697 request.WriteUInt8(static_cast<uint8_t>(hostname.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200698 request.WriteString(hostname); // Destination Hostname
deadbeeff137e972017-03-23 15:45:49 -0700699 } else {
700 request.WriteUInt8(1); // IPV4
701 request.WriteUInt32(dest_.ip()); // Destination IP
702 }
703 request.WriteUInt16(dest_.port()); // Destination Port
704 DirectSend(request.Data(), request.Length());
705 state_ = SS_CONNECT;
706}
707
708void AsyncSocksProxySocket::Error(int error) {
709 state_ = SS_ERROR;
710 BufferInput(false);
711 Close();
712 SetError(SOCKET_EACCES);
713 SignalCloseEvent(this, error);
714}
715
716AsyncSocksProxyServerSocket::AsyncSocksProxyServerSocket(AsyncSocket* socket)
717 : AsyncProxyServerSocket(socket, kBufferSize), state_(SS_HELLO) {
718 BufferInput(true);
719}
720
721void AsyncSocksProxyServerSocket::ProcessInput(char* data, size_t* len) {
722 // TODO: See if the whole message has arrived
723 RTC_DCHECK(state_ < SS_CONNECT_PENDING);
724
725 ByteBufferReader response(data, *len);
726 if (state_ == SS_HELLO) {
727 HandleHello(&response);
728 } else if (state_ == SS_AUTH) {
729 HandleAuth(&response);
730 } else if (state_ == SS_CONNECT) {
731 HandleConnect(&response);
732 }
733
734 // Consume parsed data
735 *len = response.Length();
736 memmove(data, response.Data(), *len);
737}
738
739void AsyncSocksProxyServerSocket::DirectSend(const ByteBufferWriter& buf) {
740 BufferedReadAdapter::DirectSend(buf.Data(), buf.Length());
741}
742
743void AsyncSocksProxyServerSocket::HandleHello(ByteBufferReader* request) {
744 uint8_t ver, num_methods;
Yves Gerey665174f2018-06-19 15:03:05 +0200745 if (!request->ReadUInt8(&ver) || !request->ReadUInt8(&num_methods)) {
deadbeeff137e972017-03-23 15:45:49 -0700746 Error(0);
747 return;
748 }
749
750 if (ver != 5) {
751 Error(0);
752 return;
753 }
754
755 // Handle either no-auth (0) or user/pass auth (2)
756 uint8_t method = 0xFF;
757 if (num_methods > 0 && !request->ReadUInt8(&method)) {
758 Error(0);
759 return;
760 }
761
762 // TODO: Ask the server which method to use.
763 SendHelloReply(method);
764 if (method == 0) {
765 state_ = SS_CONNECT;
766 } else if (method == 2) {
767 state_ = SS_AUTH;
768 } else {
769 state_ = SS_ERROR;
770 }
771}
772
773void AsyncSocksProxyServerSocket::SendHelloReply(uint8_t method) {
774 ByteBufferWriter response;
Yves Gerey665174f2018-06-19 15:03:05 +0200775 response.WriteUInt8(5); // Socks Version
deadbeeff137e972017-03-23 15:45:49 -0700776 response.WriteUInt8(method); // Auth method
777 DirectSend(response);
778}
779
780void AsyncSocksProxyServerSocket::HandleAuth(ByteBufferReader* request) {
781 uint8_t ver, user_len, pass_len;
782 std::string user, pass;
Yves Gerey665174f2018-06-19 15:03:05 +0200783 if (!request->ReadUInt8(&ver) || !request->ReadUInt8(&user_len) ||
784 !request->ReadString(&user, user_len) || !request->ReadUInt8(&pass_len) ||
deadbeeff137e972017-03-23 15:45:49 -0700785 !request->ReadString(&pass, pass_len)) {
786 Error(0);
787 return;
788 }
789
790 // TODO: Allow for checking of credentials.
791 SendAuthReply(0);
792 state_ = SS_CONNECT;
793}
794
795void AsyncSocksProxyServerSocket::SendAuthReply(uint8_t result) {
796 ByteBufferWriter response;
797 response.WriteUInt8(1); // Negotiation Version
798 response.WriteUInt8(result);
799 DirectSend(response);
800}
801
802void AsyncSocksProxyServerSocket::HandleConnect(ByteBufferReader* request) {
803 uint8_t ver, command, reserved, addr_type;
804 uint32_t ip;
805 uint16_t port;
Yves Gerey665174f2018-06-19 15:03:05 +0200806 if (!request->ReadUInt8(&ver) || !request->ReadUInt8(&command) ||
807 !request->ReadUInt8(&reserved) || !request->ReadUInt8(&addr_type) ||
808 !request->ReadUInt32(&ip) || !request->ReadUInt16(&port)) {
809 Error(0);
810 return;
deadbeeff137e972017-03-23 15:45:49 -0700811 }
812
Yves Gerey665174f2018-06-19 15:03:05 +0200813 if (ver != 5 || command != 1 || reserved != 0 || addr_type != 1) {
814 Error(0);
815 return;
deadbeeff137e972017-03-23 15:45:49 -0700816 }
817
818 SignalConnectRequest(this, SocketAddress(ip, port));
819 state_ = SS_CONNECT_PENDING;
820}
821
822void AsyncSocksProxyServerSocket::SendConnectResult(int result,
823 const SocketAddress& addr) {
824 if (state_ != SS_CONNECT_PENDING)
825 return;
826
827 ByteBufferWriter response;
Yves Gerey665174f2018-06-19 15:03:05 +0200828 response.WriteUInt8(5); // Socks version
deadbeeff137e972017-03-23 15:45:49 -0700829 response.WriteUInt8((result != 0)); // 0x01 is generic error
Yves Gerey665174f2018-06-19 15:03:05 +0200830 response.WriteUInt8(0); // reserved
831 response.WriteUInt8(1); // IPv4 address
deadbeeff137e972017-03-23 15:45:49 -0700832 response.WriteUInt32(addr.ip());
833 response.WriteUInt16(addr.port());
834 DirectSend(response);
835 BufferInput(false);
836 state_ = SS_TUNNEL;
837}
838
839void AsyncSocksProxyServerSocket::Error(int error) {
840 state_ = SS_ERROR;
841 BufferInput(false);
842 Close();
843 SetError(SOCKET_EACCES);
844 SignalCloseEvent(this, error);
845}
846
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000847} // namespace rtc