blob: 8095894420ccfcb2783ffcb2aa6d19d444f0d0c2 [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 Gerey665174f2018-06-19 15:03:05 +020016#include <time.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017
18#if defined(WEBRTC_WIN)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#include <windows.h>
20#include <winsock2.h>
21#include <ws2tcpip.h>
22#define SECURITY_WIN32
23#include <security.h>
24#endif
25
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000026#include <algorithm>
27
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/bytebuffer.h"
29#include "rtc_base/checks.h"
30#include "rtc_base/httpcommon.h"
31#include "rtc_base/logging.h"
32#include "rtc_base/socketadapters.h"
33#include "rtc_base/stringencode.h"
34#include "rtc_base/stringutils.h"
Joachim Bauch5b32f232018-03-07 20:02:26 +010035#include "rtc_base/zero_memory.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037namespace rtc {
38
39BufferedReadAdapter::BufferedReadAdapter(AsyncSocket* socket, size_t size)
Yves Gerey665174f2018-06-19 15:03:05 +020040 : AsyncSocketAdapter(socket),
41 buffer_size_(size),
42 data_len_(0),
43 buffering_(false) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044 buffer_ = new char[buffer_size_];
45}
46
47BufferedReadAdapter::~BufferedReadAdapter() {
Yves Gerey665174f2018-06-19 15:03:05 +020048 delete[] buffer_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000049}
50
Yves Gerey665174f2018-06-19 15:03:05 +020051int BufferedReadAdapter::Send(const void* pv, size_t cb) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052 if (buffering_) {
53 // TODO: Spoof error better; Signal Writeable
54 socket_->SetError(EWOULDBLOCK);
55 return -1;
56 }
57 return AsyncSocketAdapter::Send(pv, cb);
58}
59
Stefan Holmer9131efd2016-05-23 18:19:26 +020060int BufferedReadAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000061 if (buffering_) {
62 socket_->SetError(EWOULDBLOCK);
63 return -1;
64 }
65
66 size_t read = 0;
67
68 if (data_len_) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000069 read = std::min(cb, data_len_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070 memcpy(pv, buffer_, read);
71 data_len_ -= read;
72 if (data_len_ > 0) {
73 memmove(buffer_, buffer_ + read, data_len_);
74 }
Yves Gerey665174f2018-06-19 15:03:05 +020075 pv = static_cast<char*>(pv) + read;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000076 cb -= read;
77 }
78
79 // FIX: If cb == 0, we won't generate another read event
80
Stefan Holmer9131efd2016-05-23 18:19:26 +020081 int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
deadbeefc5d0d952015-07-16 10:22:21 -070082 if (res >= 0) {
83 // Read from socket and possibly buffer; return combined length
84 return res + static_cast<int>(read);
85 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000086
deadbeefc5d0d952015-07-16 10:22:21 -070087 if (read > 0) {
88 // Failed to read from socket, but still read something from buffer
89 return static_cast<int>(read);
90 }
91
92 // Didn't read anything; return error from socket
93 return res;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094}
95
96void BufferedReadAdapter::BufferInput(bool on) {
97 buffering_ = on;
98}
99
Yves Gerey665174f2018-06-19 15:03:05 +0200100void BufferedReadAdapter::OnReadEvent(AsyncSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800101 RTC_DCHECK(socket == socket_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000102
103 if (!buffering_) {
104 AsyncSocketAdapter::OnReadEvent(socket);
105 return;
106 }
107
108 if (data_len_ >= buffer_size_) {
Jonas Olsson45cc8902018-02-13 10:37:07 +0100109 RTC_LOG(LS_ERROR) << "Input buffer overflow";
nissec80e7412017-01-11 05:56:46 -0800110 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111 data_len_ = 0;
112 }
113
Stefan Holmer9131efd2016-05-23 18:19:26 +0200114 int len =
115 socket_->Recv(buffer_ + data_len_, buffer_size_ - data_len_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116 if (len < 0) {
117 // TODO: Do something better like forwarding the error to the user.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100118 RTC_LOG_ERR(INFO) << "Recv";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000119 return;
120 }
121
122 data_len_ += len;
123
124 ProcessInput(buffer_, &data_len_);
125}
126
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000127AsyncProxyServerSocket::AsyncProxyServerSocket(AsyncSocket* socket,
128 size_t buffer_size)
Yves Gerey665174f2018-06-19 15:03:05 +0200129 : BufferedReadAdapter(socket, buffer_size) {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000130
131AsyncProxyServerSocket::~AsyncProxyServerSocket() = default;
132
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133///////////////////////////////////////////////////////////////////////////////
134
135// This is a SSL v2 CLIENT_HELLO message.
136// TODO: Should this have a session id? The response doesn't have a
137// certificate, so the hello should have a session id.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200138static const uint8_t kSslClientHello[] = {
139 0x80, 0x46, // msg len
140 0x01, // CLIENT_HELLO
141 0x03, 0x01, // SSL 3.1
142 0x00, 0x2d, // ciphersuite len
143 0x00, 0x00, // session id len
144 0x00, 0x10, // challenge len
145 0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0, // ciphersuites
146 0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80, //
147 0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a, //
148 0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, //
149 0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06, //
150 0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc, // challenge
151 0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea //
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152};
153
154// This is a TLSv1 SERVER_HELLO message.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200155static const uint8_t kSslServerHello[] = {
156 0x16, // handshake message
157 0x03, 0x01, // SSL 3.1
158 0x00, 0x4a, // message len
159 0x02, // SERVER_HELLO
160 0x00, 0x00, 0x46, // handshake len
161 0x03, 0x01, // SSL 3.1
162 0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0, // server random
163 0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f, //
164 0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1, //
165 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f, //
166 0x20, // session id len
167 0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f, // session id
168 0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b, //
169 0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38, //
170 0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c, //
171 0x00, 0x04, // RSA/RC4-128/MD5
172 0x00 // null compression
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173};
174
175AsyncSSLSocket::AsyncSSLSocket(AsyncSocket* socket)
Yves Gerey665174f2018-06-19 15:03:05 +0200176 : BufferedReadAdapter(socket, 1024) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177
178int AsyncSSLSocket::Connect(const SocketAddress& addr) {
179 // Begin buffering before we connect, so that there isn't a race condition
180 // between potential senders and receiving the OnConnectEvent signal
181 BufferInput(true);
182 return BufferedReadAdapter::Connect(addr);
183}
184
Yves Gerey665174f2018-06-19 15:03:05 +0200185void AsyncSSLSocket::OnConnectEvent(AsyncSocket* socket) {
nisseede5da42017-01-12 05:15:36 -0800186 RTC_DCHECK(socket == socket_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187 // TODO: we could buffer output too...
nissec16fa5e2017-02-07 07:18:43 -0800188 const int res = DirectSend(kSslClientHello, sizeof(kSslClientHello));
189 RTC_DCHECK_EQ(sizeof(kSslClientHello), res);
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) {
197 Close();
198 SignalCloseEvent(this, 0); // TODO: error code?
199 return;
200 }
201
202 *len -= sizeof(kSslServerHello);
203 if (*len > 0) {
204 memmove(data, data + sizeof(kSslServerHello), *len);
205 }
206
207 bool remainder = (*len > 0);
208 BufferInput(false);
209 SignalConnectEvent(this);
210
211 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
212 if (remainder)
213 SignalReadEvent(this);
214}
215
216AsyncSSLServerSocket::AsyncSSLServerSocket(AsyncSocket* socket)
Yves Gerey665174f2018-06-19 15:03:05 +0200217 : BufferedReadAdapter(socket, 1024) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000218 BufferInput(true);
219}
220
221void AsyncSSLServerSocket::ProcessInput(char* data, size_t* len) {
222 // We only accept client hello messages.
223 if (*len < sizeof(kSslClientHello)) {
224 return;
225 }
226
227 if (memcmp(kSslClientHello, data, sizeof(kSslClientHello)) != 0) {
228 Close();
229 SignalCloseEvent(this, 0);
230 return;
231 }
232
233 *len -= sizeof(kSslClientHello);
234
235 // Clients should not send more data until the handshake is completed.
nisseede5da42017-01-12 05:15:36 -0800236 RTC_DCHECK(*len == 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237
238 // Send a server hello back to the client.
239 DirectSend(kSslServerHello, sizeof(kSslServerHello));
240
241 // Handshake completed for us, redirect input to our parent.
242 BufferInput(false);
243}
244
deadbeeff137e972017-03-23 15:45:49 -0700245///////////////////////////////////////////////////////////////////////////////
246
247AsyncHttpsProxySocket::AsyncHttpsProxySocket(AsyncSocket* socket,
248 const std::string& user_agent,
249 const SocketAddress& proxy,
250 const std::string& username,
251 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200252 : BufferedReadAdapter(socket, 1024),
253 proxy_(proxy),
254 agent_(user_agent),
255 user_(username),
256 pass_(password),
257 force_connect_(false),
258 state_(PS_ERROR),
259 context_(0) {}
deadbeeff137e972017-03-23 15:45:49 -0700260
261AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
262 delete context_;
263}
264
265int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
266 int ret;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100267 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
268 << proxy_.ToSensitiveString() << ")";
deadbeeff137e972017-03-23 15:45:49 -0700269 dest_ = addr;
270 state_ = PS_INIT;
271 if (ShouldIssueConnect()) {
272 BufferInput(true);
273 }
274 ret = BufferedReadAdapter::Connect(proxy_);
275 // TODO: Set state_ appropriately if Connect fails.
276 return ret;
277}
278
279SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
280 return dest_;
281}
282
283int AsyncHttpsProxySocket::Close() {
284 headers_.clear();
285 state_ = PS_ERROR;
286 dest_.Clear();
287 delete context_;
288 context_ = nullptr;
289 return BufferedReadAdapter::Close();
290}
291
292Socket::ConnState AsyncHttpsProxySocket::GetState() const {
293 if (state_ < PS_TUNNEL) {
294 return CS_CONNECTING;
295 } else if (state_ == PS_TUNNEL) {
296 return CS_CONNECTED;
297 } else {
298 return CS_CLOSED;
299 }
300}
301
Yves Gerey665174f2018-06-19 15:03:05 +0200302void AsyncHttpsProxySocket::OnConnectEvent(AsyncSocket* socket) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100303 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
deadbeeff137e972017-03-23 15:45:49 -0700304 if (!ShouldIssueConnect()) {
305 state_ = PS_TUNNEL;
306 BufferedReadAdapter::OnConnectEvent(socket);
307 return;
308 }
309 SendRequest();
310}
311
Yves Gerey665174f2018-06-19 15:03:05 +0200312void AsyncHttpsProxySocket::OnCloseEvent(AsyncSocket* socket, int err) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100313 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
deadbeeff137e972017-03-23 15:45:49 -0700314 if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
315 state_ = PS_ERROR;
316 Connect(dest_);
317 } else {
318 BufferedReadAdapter::OnCloseEvent(socket, err);
319 }
320}
321
322void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
323 size_t start = 0;
324 for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
325 if (state_ == PS_SKIP_BODY) {
326 size_t consume = std::min(*len - pos, content_length_);
327 pos += consume;
328 start = pos;
329 content_length_ -= consume;
330 if (content_length_ == 0) {
331 EndResponse();
332 }
333 continue;
334 }
335
336 if (data[pos++] != '\n')
337 continue;
338
339 size_t len = pos - start - 1;
340 if ((len > 0) && (data[start + len - 1] == '\r'))
341 --len;
342
343 data[start + len] = 0;
344 ProcessLine(data + start, len);
345 start = pos;
346 }
347
348 *len -= start;
349 if (*len > 0) {
350 memmove(data, data + start, *len);
351 }
352
353 if (state_ != PS_TUNNEL)
354 return;
355
356 bool remainder = (*len > 0);
357 BufferInput(false);
358 SignalConnectEvent(this);
359
360 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
361 if (remainder)
362 SignalReadEvent(this); // TODO: signal this??
363}
364
365bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
366 // TODO: Think about whether a more sophisticated test
367 // than dest port == 80 is needed.
368 return force_connect_ || (dest_.port() != 80);
369}
370
371void AsyncHttpsProxySocket::SendRequest() {
372 std::stringstream ss;
373 ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
374 ss << "User-Agent: " << agent_ << "\r\n";
375 ss << "Host: " << dest_.HostAsURIString() << "\r\n";
376 ss << "Content-Length: 0\r\n";
377 ss << "Proxy-Connection: Keep-Alive\r\n";
378 ss << headers_;
379 ss << "\r\n";
380 std::string str = ss.str();
381 DirectSend(str.c_str(), str.size());
382 state_ = PS_LEADER;
383 expect_close_ = true;
384 content_length_ = 0;
385 headers_.clear();
386
Mirko Bonadei675513b2017-11-09 11:09:25 +0100387 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
deadbeeff137e972017-03-23 15:45:49 -0700388}
389
Yves Gerey665174f2018-06-19 15:03:05 +0200390void AsyncHttpsProxySocket::ProcessLine(char* data, size_t len) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100391 RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
deadbeeff137e972017-03-23 15:45:49 -0700392
393 if (len == 0) {
394 if (state_ == PS_TUNNEL_HEADERS) {
395 state_ = PS_TUNNEL;
396 } else if (state_ == PS_ERROR_HEADERS) {
397 Error(defer_error_);
398 return;
399 } else if (state_ == PS_SKIP_HEADERS) {
400 if (content_length_) {
401 state_ = PS_SKIP_BODY;
402 } else {
403 EndResponse();
404 return;
405 }
406 } else {
407 static bool report = false;
408 if (!unknown_mechanisms_.empty() && !report) {
409 report = true;
410 std::string msg(
Yves Gerey665174f2018-06-19 15:03:05 +0200411 "Unable to connect to the Google Talk service due to an "
412 "incompatibility "
413 "with your proxy.\r\nPlease help us resolve this issue by "
414 "submitting the "
415 "following information to us using our technical issue submission "
416 "form "
417 "at:\r\n\r\n"
418 "http://www.google.com/support/talk/bin/request.py\r\n\r\n"
419 "We apologize for the inconvenience.\r\n\r\n"
420 "Information to submit to Google: ");
421 // std::string msg("Please report the following information to
422 // foo@bar.com:\r\nUnknown methods: ");
deadbeeff137e972017-03-23 15:45:49 -0700423 msg.append(unknown_mechanisms_);
424#if defined(WEBRTC_WIN)
425 MessageBoxA(0, msg.c_str(), "Oops!", MB_OK);
426#endif
427#if defined(WEBRTC_POSIX)
428 // TODO: Raise a signal so the UI can be separated.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100429 RTC_LOG(LS_ERROR) << "Oops!\n\n" << msg;
deadbeeff137e972017-03-23 15:45:49 -0700430#endif
431 }
432 // Unexpected end of headers
433 Error(0);
434 return;
435 }
436 } else if (state_ == PS_LEADER) {
437 unsigned int code;
438 if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
439 Error(0);
440 return;
441 }
442 switch (code) {
Yves Gerey665174f2018-06-19 15:03:05 +0200443 case 200:
444 // connection good!
445 state_ = PS_TUNNEL_HEADERS;
446 return;
deadbeeff137e972017-03-23 15:45:49 -0700447#if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
448#error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
449#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200450 case 407: // HTTP_STATUS_PROXY_AUTH_REQ
451 state_ = PS_AUTHENTICATE;
452 return;
453 default:
454 defer_error_ = 0;
455 state_ = PS_ERROR_HEADERS;
456 return;
deadbeeff137e972017-03-23 15:45:49 -0700457 }
Yves Gerey665174f2018-06-19 15:03:05 +0200458 } else if ((state_ == PS_AUTHENTICATE) &&
459 (_strnicmp(data, "Proxy-Authenticate:", 19) == 0)) {
deadbeeff137e972017-03-23 15:45:49 -0700460 std::string response, auth_method;
Yves Gerey665174f2018-06-19 15:03:05 +0200461 switch (HttpAuthenticate(data + 19, len - 19, proxy_, "CONNECT", "/", user_,
462 pass_, context_, response, auth_method)) {
463 case HAR_IGNORE:
464 RTC_LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
465 if (!unknown_mechanisms_.empty())
466 unknown_mechanisms_.append(", ");
467 unknown_mechanisms_.append(auth_method);
468 break;
469 case HAR_RESPONSE:
470 headers_ = "Proxy-Authorization: ";
471 headers_.append(response);
472 headers_.append("\r\n");
473 state_ = PS_SKIP_HEADERS;
474 unknown_mechanisms_.clear();
475 break;
476 case HAR_CREDENTIALS:
477 defer_error_ = SOCKET_EACCES;
478 state_ = PS_ERROR_HEADERS;
479 unknown_mechanisms_.clear();
480 break;
481 case HAR_ERROR:
482 defer_error_ = 0;
483 state_ = PS_ERROR_HEADERS;
484 unknown_mechanisms_.clear();
485 break;
deadbeeff137e972017-03-23 15:45:49 -0700486 }
487 } else if (_strnicmp(data, "Content-Length:", 15) == 0) {
488 content_length_ = strtoul(data + 15, 0, 0);
489 } else if (_strnicmp(data, "Proxy-Connection: Keep-Alive", 28) == 0) {
490 expect_close_ = false;
491 /*
492 } else if (_strnicmp(data, "Connection: close", 17) == 0) {
493 expect_close_ = true;
494 */
495 }
496}
497
498void AsyncHttpsProxySocket::EndResponse() {
499 if (!expect_close_) {
500 SendRequest();
501 return;
502 }
503
504 // No point in waiting for the server to close... let's close now
505 // TODO: Refactor out PS_WAIT_CLOSE
506 state_ = PS_WAIT_CLOSE;
507 BufferedReadAdapter::Close();
508 OnCloseEvent(this, 0);
509}
510
511void AsyncHttpsProxySocket::Error(int error) {
512 BufferInput(false);
513 Close();
514 SetError(error);
515 SignalCloseEvent(this, error);
516}
517
518///////////////////////////////////////////////////////////////////////////////
519
520AsyncSocksProxySocket::AsyncSocksProxySocket(AsyncSocket* socket,
521 const SocketAddress& proxy,
522 const std::string& username,
523 const CryptString& password)
Yves Gerey665174f2018-06-19 15:03:05 +0200524 : BufferedReadAdapter(socket, 1024),
525 state_(SS_ERROR),
526 proxy_(proxy),
527 user_(username),
528 pass_(password) {}
deadbeeff137e972017-03-23 15:45:49 -0700529
530AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
531
532int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
533 int ret;
534 dest_ = addr;
535 state_ = SS_INIT;
536 BufferInput(true);
537 ret = BufferedReadAdapter::Connect(proxy_);
538 // TODO: Set state_ appropriately if Connect fails.
539 return ret;
540}
541
542SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
543 return dest_;
544}
545
546int AsyncSocksProxySocket::Close() {
547 state_ = SS_ERROR;
548 dest_.Clear();
549 return BufferedReadAdapter::Close();
550}
551
552Socket::ConnState AsyncSocksProxySocket::GetState() const {
553 if (state_ < SS_TUNNEL) {
554 return CS_CONNECTING;
555 } else if (state_ == SS_TUNNEL) {
556 return CS_CONNECTED;
557 } else {
558 return CS_CLOSED;
559 }
560}
561
562void AsyncSocksProxySocket::OnConnectEvent(AsyncSocket* socket) {
563 SendHello();
564}
565
566void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
567 RTC_DCHECK(state_ < SS_TUNNEL);
568
569 ByteBufferReader response(data, *len);
570
571 if (state_ == SS_HELLO) {
572 uint8_t ver, method;
Yves Gerey665174f2018-06-19 15:03:05 +0200573 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&method))
deadbeeff137e972017-03-23 15:45:49 -0700574 return;
575
576 if (ver != 5) {
577 Error(0);
578 return;
579 }
580
581 if (method == 0) {
582 SendConnect();
583 } else if (method == 2) {
584 SendAuth();
585 } else {
586 Error(0);
587 return;
588 }
589 } else if (state_ == SS_AUTH) {
590 uint8_t ver, status;
Yves Gerey665174f2018-06-19 15:03:05 +0200591 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&status))
deadbeeff137e972017-03-23 15:45:49 -0700592 return;
593
594 if ((ver != 1) || (status != 0)) {
595 Error(SOCKET_EACCES);
596 return;
597 }
598
599 SendConnect();
600 } else if (state_ == SS_CONNECT) {
601 uint8_t ver, rep, rsv, atyp;
Yves Gerey665174f2018-06-19 15:03:05 +0200602 if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&rep) ||
603 !response.ReadUInt8(&rsv) || !response.ReadUInt8(&atyp))
deadbeeff137e972017-03-23 15:45:49 -0700604 return;
605
606 if ((ver != 5) || (rep != 0)) {
607 Error(0);
608 return;
609 }
610
611 uint16_t port;
612 if (atyp == 1) {
613 uint32_t addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200614 if (!response.ReadUInt32(&addr) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700615 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100616 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700617 } else if (atyp == 3) {
618 uint8_t len;
619 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200620 if (!response.ReadUInt8(&len) || !response.ReadString(&addr, len) ||
deadbeeff137e972017-03-23 15:45:49 -0700621 !response.ReadUInt16(&port))
622 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100623 RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
deadbeeff137e972017-03-23 15:45:49 -0700624 } else if (atyp == 4) {
625 std::string addr;
Yves Gerey665174f2018-06-19 15:03:05 +0200626 if (!response.ReadString(&addr, 16) || !response.ReadUInt16(&port))
deadbeeff137e972017-03-23 15:45:49 -0700627 return;
Mirko Bonadei675513b2017-11-09 11:09:25 +0100628 RTC_LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
deadbeeff137e972017-03-23 15:45:49 -0700629 } else {
630 Error(0);
631 return;
632 }
633
634 state_ = SS_TUNNEL;
635 }
636
637 // Consume parsed data
638 *len = response.Length();
639 memmove(data, response.Data(), *len);
640
641 if (state_ != SS_TUNNEL)
642 return;
643
644 bool remainder = (*len > 0);
645 BufferInput(false);
646 SignalConnectEvent(this);
647
648 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
649 if (remainder)
650 SignalReadEvent(this); // TODO: signal this??
651}
652
653void AsyncSocksProxySocket::SendHello() {
654 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200655 request.WriteUInt8(5); // Socks Version
deadbeeff137e972017-03-23 15:45:49 -0700656 if (user_.empty()) {
657 request.WriteUInt8(1); // Authentication Mechanisms
658 request.WriteUInt8(0); // No authentication
659 } else {
660 request.WriteUInt8(2); // Authentication Mechanisms
661 request.WriteUInt8(0); // No authentication
662 request.WriteUInt8(2); // Username/Password
663 }
664 DirectSend(request.Data(), request.Length());
665 state_ = SS_HELLO;
666}
667
668void AsyncSocksProxySocket::SendAuth() {
Joachim Bauch4c6a30c2018-03-08 00:55:33 +0100669 ByteBufferWriterT<ZeroOnFreeBuffer<char>> request;
Yves Gerey665174f2018-06-19 15:03:05 +0200670 request.WriteUInt8(1); // Negotiation Version
deadbeeff137e972017-03-23 15:45:49 -0700671 request.WriteUInt8(static_cast<uint8_t>(user_.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200672 request.WriteString(user_); // Username
deadbeeff137e972017-03-23 15:45:49 -0700673 request.WriteUInt8(static_cast<uint8_t>(pass_.GetLength()));
674 size_t len = pass_.GetLength() + 1;
Yves Gerey665174f2018-06-19 15:03:05 +0200675 char* sensitive = new char[len];
deadbeeff137e972017-03-23 15:45:49 -0700676 pass_.CopyTo(sensitive, true);
Joachim Bauch5b32f232018-03-07 20:02:26 +0100677 request.WriteBytes(sensitive, pass_.GetLength()); // Password
678 ExplicitZeroMemory(sensitive, len);
Yves Gerey665174f2018-06-19 15:03:05 +0200679 delete[] sensitive;
deadbeeff137e972017-03-23 15:45:49 -0700680 DirectSend(request.Data(), request.Length());
681 state_ = SS_AUTH;
682}
683
684void AsyncSocksProxySocket::SendConnect() {
685 ByteBufferWriter request;
Yves Gerey665174f2018-06-19 15:03:05 +0200686 request.WriteUInt8(5); // Socks Version
687 request.WriteUInt8(1); // CONNECT
688 request.WriteUInt8(0); // Reserved
deadbeeff137e972017-03-23 15:45:49 -0700689 if (dest_.IsUnresolvedIP()) {
690 std::string hostname = dest_.hostname();
Yves Gerey665174f2018-06-19 15:03:05 +0200691 request.WriteUInt8(3); // DOMAINNAME
deadbeeff137e972017-03-23 15:45:49 -0700692 request.WriteUInt8(static_cast<uint8_t>(hostname.size()));
Yves Gerey665174f2018-06-19 15:03:05 +0200693 request.WriteString(hostname); // Destination Hostname
deadbeeff137e972017-03-23 15:45:49 -0700694 } else {
695 request.WriteUInt8(1); // IPV4
696 request.WriteUInt32(dest_.ip()); // Destination IP
697 }
698 request.WriteUInt16(dest_.port()); // Destination Port
699 DirectSend(request.Data(), request.Length());
700 state_ = SS_CONNECT;
701}
702
703void AsyncSocksProxySocket::Error(int error) {
704 state_ = SS_ERROR;
705 BufferInput(false);
706 Close();
707 SetError(SOCKET_EACCES);
708 SignalCloseEvent(this, error);
709}
710
711AsyncSocksProxyServerSocket::AsyncSocksProxyServerSocket(AsyncSocket* socket)
712 : AsyncProxyServerSocket(socket, kBufferSize), state_(SS_HELLO) {
713 BufferInput(true);
714}
715
716void AsyncSocksProxyServerSocket::ProcessInput(char* data, size_t* len) {
717 // TODO: See if the whole message has arrived
718 RTC_DCHECK(state_ < SS_CONNECT_PENDING);
719
720 ByteBufferReader response(data, *len);
721 if (state_ == SS_HELLO) {
722 HandleHello(&response);
723 } else if (state_ == SS_AUTH) {
724 HandleAuth(&response);
725 } else if (state_ == SS_CONNECT) {
726 HandleConnect(&response);
727 }
728
729 // Consume parsed data
730 *len = response.Length();
731 memmove(data, response.Data(), *len);
732}
733
734void AsyncSocksProxyServerSocket::DirectSend(const ByteBufferWriter& buf) {
735 BufferedReadAdapter::DirectSend(buf.Data(), buf.Length());
736}
737
738void AsyncSocksProxyServerSocket::HandleHello(ByteBufferReader* request) {
739 uint8_t ver, num_methods;
Yves Gerey665174f2018-06-19 15:03:05 +0200740 if (!request->ReadUInt8(&ver) || !request->ReadUInt8(&num_methods)) {
deadbeeff137e972017-03-23 15:45:49 -0700741 Error(0);
742 return;
743 }
744
745 if (ver != 5) {
746 Error(0);
747 return;
748 }
749
750 // Handle either no-auth (0) or user/pass auth (2)
751 uint8_t method = 0xFF;
752 if (num_methods > 0 && !request->ReadUInt8(&method)) {
753 Error(0);
754 return;
755 }
756
757 // TODO: Ask the server which method to use.
758 SendHelloReply(method);
759 if (method == 0) {
760 state_ = SS_CONNECT;
761 } else if (method == 2) {
762 state_ = SS_AUTH;
763 } else {
764 state_ = SS_ERROR;
765 }
766}
767
768void AsyncSocksProxyServerSocket::SendHelloReply(uint8_t method) {
769 ByteBufferWriter response;
Yves Gerey665174f2018-06-19 15:03:05 +0200770 response.WriteUInt8(5); // Socks Version
deadbeeff137e972017-03-23 15:45:49 -0700771 response.WriteUInt8(method); // Auth method
772 DirectSend(response);
773}
774
775void AsyncSocksProxyServerSocket::HandleAuth(ByteBufferReader* request) {
776 uint8_t ver, user_len, pass_len;
777 std::string user, pass;
Yves Gerey665174f2018-06-19 15:03:05 +0200778 if (!request->ReadUInt8(&ver) || !request->ReadUInt8(&user_len) ||
779 !request->ReadString(&user, user_len) || !request->ReadUInt8(&pass_len) ||
deadbeeff137e972017-03-23 15:45:49 -0700780 !request->ReadString(&pass, pass_len)) {
781 Error(0);
782 return;
783 }
784
785 // TODO: Allow for checking of credentials.
786 SendAuthReply(0);
787 state_ = SS_CONNECT;
788}
789
790void AsyncSocksProxyServerSocket::SendAuthReply(uint8_t result) {
791 ByteBufferWriter response;
792 response.WriteUInt8(1); // Negotiation Version
793 response.WriteUInt8(result);
794 DirectSend(response);
795}
796
797void AsyncSocksProxyServerSocket::HandleConnect(ByteBufferReader* request) {
798 uint8_t ver, command, reserved, addr_type;
799 uint32_t ip;
800 uint16_t port;
Yves Gerey665174f2018-06-19 15:03:05 +0200801 if (!request->ReadUInt8(&ver) || !request->ReadUInt8(&command) ||
802 !request->ReadUInt8(&reserved) || !request->ReadUInt8(&addr_type) ||
803 !request->ReadUInt32(&ip) || !request->ReadUInt16(&port)) {
804 Error(0);
805 return;
deadbeeff137e972017-03-23 15:45:49 -0700806 }
807
Yves Gerey665174f2018-06-19 15:03:05 +0200808 if (ver != 5 || command != 1 || reserved != 0 || addr_type != 1) {
809 Error(0);
810 return;
deadbeeff137e972017-03-23 15:45:49 -0700811 }
812
813 SignalConnectRequest(this, SocketAddress(ip, port));
814 state_ = SS_CONNECT_PENDING;
815}
816
817void AsyncSocksProxyServerSocket::SendConnectResult(int result,
818 const SocketAddress& addr) {
819 if (state_ != SS_CONNECT_PENDING)
820 return;
821
822 ByteBufferWriter response;
Yves Gerey665174f2018-06-19 15:03:05 +0200823 response.WriteUInt8(5); // Socks version
deadbeeff137e972017-03-23 15:45:49 -0700824 response.WriteUInt8((result != 0)); // 0x01 is generic error
Yves Gerey665174f2018-06-19 15:03:05 +0200825 response.WriteUInt8(0); // reserved
826 response.WriteUInt8(1); // IPv4 address
deadbeeff137e972017-03-23 15:45:49 -0700827 response.WriteUInt32(addr.ip());
828 response.WriteUInt16(addr.port());
829 DirectSend(response);
830 BufferInput(false);
831 state_ = SS_TUNNEL;
832}
833
834void AsyncSocksProxyServerSocket::Error(int error) {
835 state_ = SS_ERROR;
836 BufferInput(false);
837 Close();
838 SetError(SOCKET_EACCES);
839 SignalCloseEvent(this, error);
840}
841
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000842} // namespace rtc