blob: e1c8a072b2e0c24c03d50b72078eecf299100705 [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
12#pragma warning(disable:4786)
13#endif
14
15#include <time.h>
16#include <errno.h>
17
18#if defined(WEBRTC_WIN)
19#define WIN32_LEAN_AND_MEAN
20#include <windows.h>
21#include <winsock2.h>
22#include <ws2tcpip.h>
23#define SECURITY_WIN32
24#include <security.h>
25#endif
26
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000027#include <algorithm>
28
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029#include "webrtc/base/bytebuffer.h"
30#include "webrtc/base/common.h"
31#include "webrtc/base/httpcommon.h"
32#include "webrtc/base/logging.h"
33#include "webrtc/base/socketadapters.h"
34#include "webrtc/base/stringencode.h"
35#include "webrtc/base/stringutils.h"
36
37#if defined(WEBRTC_WIN)
38#include "webrtc/base/sec_buffer.h"
Stefan Holmer9131efd2016-05-23 18:19:26 +020039#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040
41namespace rtc {
42
43BufferedReadAdapter::BufferedReadAdapter(AsyncSocket* socket, size_t size)
44 : AsyncSocketAdapter(socket), buffer_size_(size),
45 data_len_(0), buffering_(false) {
46 buffer_ = new char[buffer_size_];
47}
48
49BufferedReadAdapter::~BufferedReadAdapter() {
50 delete [] buffer_;
51}
52
53int BufferedReadAdapter::Send(const void *pv, size_t cb) {
54 if (buffering_) {
55 // TODO: Spoof error better; Signal Writeable
56 socket_->SetError(EWOULDBLOCK);
57 return -1;
58 }
59 return AsyncSocketAdapter::Send(pv, cb);
60}
61
Stefan Holmer9131efd2016-05-23 18:19:26 +020062int BufferedReadAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063 if (buffering_) {
64 socket_->SetError(EWOULDBLOCK);
65 return -1;
66 }
67
68 size_t read = 0;
69
70 if (data_len_) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000071 read = std::min(cb, data_len_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072 memcpy(pv, buffer_, read);
73 data_len_ -= read;
74 if (data_len_ > 0) {
75 memmove(buffer_, buffer_ + read, data_len_);
76 }
77 pv = static_cast<char *>(pv) + read;
78 cb -= read;
79 }
80
81 // FIX: If cb == 0, we won't generate another read event
82
Stefan Holmer9131efd2016-05-23 18:19:26 +020083 int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
deadbeefc5d0d952015-07-16 10:22:21 -070084 if (res >= 0) {
85 // Read from socket and possibly buffer; return combined length
86 return res + static_cast<int>(read);
87 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000088
deadbeefc5d0d952015-07-16 10:22:21 -070089 if (read > 0) {
90 // Failed to read from socket, but still read something from buffer
91 return static_cast<int>(read);
92 }
93
94 // Didn't read anything; return error from socket
95 return res;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000096}
97
98void BufferedReadAdapter::BufferInput(bool on) {
99 buffering_ = on;
100}
101
102void BufferedReadAdapter::OnReadEvent(AsyncSocket * socket) {
103 ASSERT(socket == socket_);
104
105 if (!buffering_) {
106 AsyncSocketAdapter::OnReadEvent(socket);
107 return;
108 }
109
110 if (data_len_ >= buffer_size_) {
111 LOG(INFO) << "Input buffer overflow";
112 ASSERT(false);
113 data_len_ = 0;
114 }
115
Stefan Holmer9131efd2016-05-23 18:19:26 +0200116 int len =
117 socket_->Recv(buffer_ + data_len_, buffer_size_ - data_len_, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118 if (len < 0) {
119 // TODO: Do something better like forwarding the error to the user.
120 LOG_ERR(INFO) << "Recv";
121 return;
122 }
123
124 data_len_ += len;
125
126 ProcessInput(buffer_, &data_len_);
127}
128
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000129AsyncProxyServerSocket::AsyncProxyServerSocket(AsyncSocket* socket,
130 size_t buffer_size)
131 : BufferedReadAdapter(socket, buffer_size) {
132}
133
134AsyncProxyServerSocket::~AsyncProxyServerSocket() = default;
135
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136///////////////////////////////////////////////////////////////////////////////
137
138// This is a SSL v2 CLIENT_HELLO message.
139// TODO: Should this have a session id? The response doesn't have a
140// certificate, so the hello should have a session id.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200141static const uint8_t kSslClientHello[] = {
142 0x80, 0x46, // msg len
143 0x01, // CLIENT_HELLO
144 0x03, 0x01, // SSL 3.1
145 0x00, 0x2d, // ciphersuite len
146 0x00, 0x00, // session id len
147 0x00, 0x10, // challenge len
148 0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0, // ciphersuites
149 0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80, //
150 0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a, //
151 0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64, //
152 0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06, //
153 0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc, // challenge
154 0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea //
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000155};
156
157// This is a TLSv1 SERVER_HELLO message.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200158static const uint8_t kSslServerHello[] = {
159 0x16, // handshake message
160 0x03, 0x01, // SSL 3.1
161 0x00, 0x4a, // message len
162 0x02, // SERVER_HELLO
163 0x00, 0x00, 0x46, // handshake len
164 0x03, 0x01, // SSL 3.1
165 0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0, // server random
166 0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f, //
167 0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1, //
168 0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f, //
169 0x20, // session id len
170 0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f, // session id
171 0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b, //
172 0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38, //
173 0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c, //
174 0x00, 0x04, // RSA/RC4-128/MD5
175 0x00 // null compression
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000176};
177
178AsyncSSLSocket::AsyncSSLSocket(AsyncSocket* socket)
179 : BufferedReadAdapter(socket, 1024) {
180}
181
182int AsyncSSLSocket::Connect(const SocketAddress& addr) {
183 // Begin buffering before we connect, so that there isn't a race condition
184 // between potential senders and receiving the OnConnectEvent signal
185 BufferInput(true);
186 return BufferedReadAdapter::Connect(addr);
187}
188
189void AsyncSSLSocket::OnConnectEvent(AsyncSocket * socket) {
190 ASSERT(socket == socket_);
191 // TODO: we could buffer output too...
192 VERIFY(sizeof(kSslClientHello) ==
193 DirectSend(kSslClientHello, sizeof(kSslClientHello)));
194}
195
196void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
197 if (*len < sizeof(kSslServerHello))
198 return;
199
200 if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
201 Close();
202 SignalCloseEvent(this, 0); // TODO: error code?
203 return;
204 }
205
206 *len -= sizeof(kSslServerHello);
207 if (*len > 0) {
208 memmove(data, data + sizeof(kSslServerHello), *len);
209 }
210
211 bool remainder = (*len > 0);
212 BufferInput(false);
213 SignalConnectEvent(this);
214
215 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
216 if (remainder)
217 SignalReadEvent(this);
218}
219
220AsyncSSLServerSocket::AsyncSSLServerSocket(AsyncSocket* socket)
221 : BufferedReadAdapter(socket, 1024) {
222 BufferInput(true);
223}
224
225void AsyncSSLServerSocket::ProcessInput(char* data, size_t* len) {
226 // We only accept client hello messages.
227 if (*len < sizeof(kSslClientHello)) {
228 return;
229 }
230
231 if (memcmp(kSslClientHello, data, sizeof(kSslClientHello)) != 0) {
232 Close();
233 SignalCloseEvent(this, 0);
234 return;
235 }
236
237 *len -= sizeof(kSslClientHello);
238
239 // Clients should not send more data until the handshake is completed.
240 ASSERT(*len == 0);
241
242 // Send a server hello back to the client.
243 DirectSend(kSslServerHello, sizeof(kSslServerHello));
244
245 // Handshake completed for us, redirect input to our parent.
246 BufferInput(false);
247}
248
249///////////////////////////////////////////////////////////////////////////////
250
251AsyncHttpsProxySocket::AsyncHttpsProxySocket(AsyncSocket* socket,
252 const std::string& user_agent,
253 const SocketAddress& proxy,
254 const std::string& username,
255 const CryptString& password)
256 : BufferedReadAdapter(socket, 1024), proxy_(proxy), agent_(user_agent),
257 user_(username), pass_(password), force_connect_(false), state_(PS_ERROR),
258 context_(0) {
259}
260
261AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
262 delete context_;
263}
264
265int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
266 int ret;
267 LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
268 << proxy_.ToSensitiveString() << ")";
269 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_ = NULL;
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
302void AsyncHttpsProxySocket::OnConnectEvent(AsyncSocket * socket) {
303 LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
304 if (!ShouldIssueConnect()) {
305 state_ = PS_TUNNEL;
306 BufferedReadAdapter::OnConnectEvent(socket);
307 return;
308 }
309 SendRequest();
310}
311
312void AsyncHttpsProxySocket::OnCloseEvent(AsyncSocket * socket, int err) {
313 LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
314 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) {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000326 size_t consume = std::min(*len - pos, content_length_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000327 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
387 LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
388}
389
390void AsyncHttpsProxySocket::ProcessLine(char * data, size_t len) {
391 LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
392
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(
411 "Unable to connect to the Google Talk service due to an incompatibility "
412 "with your proxy.\r\nPlease help us resolve this issue by submitting the "
413 "following information to us using our technical issue submission form "
414 "at:\r\n\r\n"
415 "http://www.google.com/support/talk/bin/request.py\r\n\r\n"
416 "We apologize for the inconvenience.\r\n\r\n"
417 "Information to submit to Google: "
418 );
419 //std::string msg("Please report the following information to foo@bar.com:\r\nUnknown methods: ");
420 msg.append(unknown_mechanisms_);
421#if defined(WEBRTC_WIN)
422 MessageBoxA(0, msg.c_str(), "Oops!", MB_OK);
423#endif
424#if defined(WEBRTC_POSIX)
425 // TODO: Raise a signal so the UI can be separated.
426 LOG(LS_ERROR) << "Oops!\n\n" << msg;
427#endif
428 }
429 // Unexpected end of headers
430 Error(0);
431 return;
432 }
433 } else if (state_ == PS_LEADER) {
434 unsigned int code;
435 if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
436 Error(0);
437 return;
438 }
439 switch (code) {
440 case 200:
441 // connection good!
442 state_ = PS_TUNNEL_HEADERS;
443 return;
444#if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
445#error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
446#endif
447 case 407: // HTTP_STATUS_PROXY_AUTH_REQ
448 state_ = PS_AUTHENTICATE;
449 return;
450 default:
451 defer_error_ = 0;
452 state_ = PS_ERROR_HEADERS;
453 return;
454 }
455 } else if ((state_ == PS_AUTHENTICATE)
456 && (_strnicmp(data, "Proxy-Authenticate:", 19) == 0)) {
457 std::string response, auth_method;
458 switch (HttpAuthenticate(data + 19, len - 19,
459 proxy_, "CONNECT", "/",
460 user_, pass_, context_, response, auth_method)) {
461 case HAR_IGNORE:
462 LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
463 if (!unknown_mechanisms_.empty())
464 unknown_mechanisms_.append(", ");
465 unknown_mechanisms_.append(auth_method);
466 break;
467 case HAR_RESPONSE:
468 headers_ = "Proxy-Authorization: ";
469 headers_.append(response);
470 headers_.append("\r\n");
471 state_ = PS_SKIP_HEADERS;
472 unknown_mechanisms_.clear();
473 break;
474 case HAR_CREDENTIALS:
475 defer_error_ = SOCKET_EACCES;
476 state_ = PS_ERROR_HEADERS;
477 unknown_mechanisms_.clear();
478 break;
479 case HAR_ERROR:
480 defer_error_ = 0;
481 state_ = PS_ERROR_HEADERS;
482 unknown_mechanisms_.clear();
483 break;
484 }
485 } else if (_strnicmp(data, "Content-Length:", 15) == 0) {
486 content_length_ = strtoul(data + 15, 0, 0);
487 } else if (_strnicmp(data, "Proxy-Connection: Keep-Alive", 28) == 0) {
488 expect_close_ = false;
489 /*
490 } else if (_strnicmp(data, "Connection: close", 17) == 0) {
491 expect_close_ = true;
492 */
493 }
494}
495
496void AsyncHttpsProxySocket::EndResponse() {
497 if (!expect_close_) {
498 SendRequest();
499 return;
500 }
501
502 // No point in waiting for the server to close... let's close now
503 // TODO: Refactor out PS_WAIT_CLOSE
504 state_ = PS_WAIT_CLOSE;
505 BufferedReadAdapter::Close();
506 OnCloseEvent(this, 0);
507}
508
509void AsyncHttpsProxySocket::Error(int error) {
510 BufferInput(false);
511 Close();
512 SetError(error);
513 SignalCloseEvent(this, error);
514}
515
516///////////////////////////////////////////////////////////////////////////////
517
518AsyncSocksProxySocket::AsyncSocksProxySocket(AsyncSocket* socket,
519 const SocketAddress& proxy,
520 const std::string& username,
521 const CryptString& password)
522 : BufferedReadAdapter(socket, 1024), state_(SS_ERROR), proxy_(proxy),
523 user_(username), pass_(password) {
524}
525
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000526AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
527
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000528int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
529 int ret;
530 dest_ = addr;
531 state_ = SS_INIT;
532 BufferInput(true);
533 ret = BufferedReadAdapter::Connect(proxy_);
534 // TODO: Set state_ appropriately if Connect fails.
535 return ret;
536}
537
538SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
539 return dest_;
540}
541
542int AsyncSocksProxySocket::Close() {
543 state_ = SS_ERROR;
544 dest_.Clear();
545 return BufferedReadAdapter::Close();
546}
547
548Socket::ConnState AsyncSocksProxySocket::GetState() const {
549 if (state_ < SS_TUNNEL) {
550 return CS_CONNECTING;
551 } else if (state_ == SS_TUNNEL) {
552 return CS_CONNECTED;
553 } else {
554 return CS_CLOSED;
555 }
556}
557
558void AsyncSocksProxySocket::OnConnectEvent(AsyncSocket* socket) {
559 SendHello();
560}
561
562void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
563 ASSERT(state_ < SS_TUNNEL);
564
jbauchf1f87202016-03-30 06:43:37 -0700565 ByteBufferReader response(data, *len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000566
567 if (state_ == SS_HELLO) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200568 uint8_t ver, method;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000569 if (!response.ReadUInt8(&ver) ||
570 !response.ReadUInt8(&method))
571 return;
572
573 if (ver != 5) {
574 Error(0);
575 return;
576 }
577
578 if (method == 0) {
579 SendConnect();
580 } else if (method == 2) {
581 SendAuth();
582 } else {
583 Error(0);
584 return;
585 }
586 } else if (state_ == SS_AUTH) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200587 uint8_t ver, status;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000588 if (!response.ReadUInt8(&ver) ||
589 !response.ReadUInt8(&status))
590 return;
591
592 if ((ver != 1) || (status != 0)) {
593 Error(SOCKET_EACCES);
594 return;
595 }
596
597 SendConnect();
598 } else if (state_ == SS_CONNECT) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200599 uint8_t ver, rep, rsv, atyp;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000600 if (!response.ReadUInt8(&ver) ||
601 !response.ReadUInt8(&rep) ||
602 !response.ReadUInt8(&rsv) ||
603 !response.ReadUInt8(&atyp))
604 return;
605
606 if ((ver != 5) || (rep != 0)) {
607 Error(0);
608 return;
609 }
610
Peter Boström0c4e06b2015-10-07 12:23:21 +0200611 uint16_t port;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000612 if (atyp == 1) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200613 uint32_t addr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000614 if (!response.ReadUInt32(&addr) ||
615 !response.ReadUInt16(&port))
616 return;
617 LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
618 } else if (atyp == 3) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200619 uint8_t len;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000620 std::string addr;
621 if (!response.ReadUInt8(&len) ||
622 !response.ReadString(&addr, len) ||
623 !response.ReadUInt16(&port))
624 return;
625 LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
626 } else if (atyp == 4) {
627 std::string addr;
628 if (!response.ReadString(&addr, 16) ||
629 !response.ReadUInt16(&port))
630 return;
631 LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
632 } else {
633 Error(0);
634 return;
635 }
636
637 state_ = SS_TUNNEL;
638 }
639
640 // Consume parsed data
641 *len = response.Length();
jbauchf1f87202016-03-30 06:43:37 -0700642 memmove(data, response.Data(), *len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000643
644 if (state_ != SS_TUNNEL)
645 return;
646
647 bool remainder = (*len > 0);
648 BufferInput(false);
649 SignalConnectEvent(this);
650
651 // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
652 if (remainder)
653 SignalReadEvent(this); // TODO: signal this??
654}
655
656void AsyncSocksProxySocket::SendHello() {
jbauchf1f87202016-03-30 06:43:37 -0700657 ByteBufferWriter request;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000658 request.WriteUInt8(5); // Socks Version
659 if (user_.empty()) {
660 request.WriteUInt8(1); // Authentication Mechanisms
661 request.WriteUInt8(0); // No authentication
662 } else {
663 request.WriteUInt8(2); // Authentication Mechanisms
664 request.WriteUInt8(0); // No authentication
665 request.WriteUInt8(2); // Username/Password
666 }
667 DirectSend(request.Data(), request.Length());
668 state_ = SS_HELLO;
669}
670
671void AsyncSocksProxySocket::SendAuth() {
jbauchf1f87202016-03-30 06:43:37 -0700672 ByteBufferWriter request;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000673 request.WriteUInt8(1); // Negotiation Version
Peter Boström0c4e06b2015-10-07 12:23:21 +0200674 request.WriteUInt8(static_cast<uint8_t>(user_.size()));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000675 request.WriteString(user_); // Username
Peter Boström0c4e06b2015-10-07 12:23:21 +0200676 request.WriteUInt8(static_cast<uint8_t>(pass_.GetLength()));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000677 size_t len = pass_.GetLength() + 1;
678 char * sensitive = new char[len];
679 pass_.CopyTo(sensitive, true);
680 request.WriteString(sensitive); // Password
681 memset(sensitive, 0, len);
682 delete [] sensitive;
683 DirectSend(request.Data(), request.Length());
684 state_ = SS_AUTH;
685}
686
687void AsyncSocksProxySocket::SendConnect() {
jbauchf1f87202016-03-30 06:43:37 -0700688 ByteBufferWriter request;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000689 request.WriteUInt8(5); // Socks Version
690 request.WriteUInt8(1); // CONNECT
691 request.WriteUInt8(0); // Reserved
tfarina20a34612015-11-02 16:20:22 -0800692 if (dest_.IsUnresolvedIP()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000693 std::string hostname = dest_.hostname();
694 request.WriteUInt8(3); // DOMAINNAME
Peter Boström0c4e06b2015-10-07 12:23:21 +0200695 request.WriteUInt8(static_cast<uint8_t>(hostname.size()));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000696 request.WriteString(hostname); // Destination Hostname
697 } else {
698 request.WriteUInt8(1); // IPV4
699 request.WriteUInt32(dest_.ip()); // Destination IP
700 }
701 request.WriteUInt16(dest_.port()); // Destination Port
702 DirectSend(request.Data(), request.Length());
703 state_ = SS_CONNECT;
704}
705
706void AsyncSocksProxySocket::Error(int error) {
707 state_ = SS_ERROR;
708 BufferInput(false);
709 Close();
710 SetError(SOCKET_EACCES);
711 SignalCloseEvent(this, error);
712}
713
714AsyncSocksProxyServerSocket::AsyncSocksProxyServerSocket(AsyncSocket* socket)
715 : AsyncProxyServerSocket(socket, kBufferSize), state_(SS_HELLO) {
716 BufferInput(true);
717}
718
719void AsyncSocksProxyServerSocket::ProcessInput(char* data, size_t* len) {
720 // TODO: See if the whole message has arrived
721 ASSERT(state_ < SS_CONNECT_PENDING);
722
jbauchf1f87202016-03-30 06:43:37 -0700723 ByteBufferReader response(data, *len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000724 if (state_ == SS_HELLO) {
725 HandleHello(&response);
726 } else if (state_ == SS_AUTH) {
727 HandleAuth(&response);
728 } else if (state_ == SS_CONNECT) {
729 HandleConnect(&response);
730 }
731
732 // Consume parsed data
733 *len = response.Length();
jbauchf1f87202016-03-30 06:43:37 -0700734 memmove(data, response.Data(), *len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000735}
736
jbauchf1f87202016-03-30 06:43:37 -0700737void AsyncSocksProxyServerSocket::DirectSend(const ByteBufferWriter& buf) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000738 BufferedReadAdapter::DirectSend(buf.Data(), buf.Length());
739}
740
jbauchf1f87202016-03-30 06:43:37 -0700741void AsyncSocksProxyServerSocket::HandleHello(ByteBufferReader* request) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200742 uint8_t ver, num_methods;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000743 if (!request->ReadUInt8(&ver) ||
744 !request->ReadUInt8(&num_methods)) {
745 Error(0);
746 return;
747 }
748
749 if (ver != 5) {
750 Error(0);
751 return;
752 }
753
754 // Handle either no-auth (0) or user/pass auth (2)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200755 uint8_t method = 0xFF;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000756 if (num_methods > 0 && !request->ReadUInt8(&method)) {
757 Error(0);
758 return;
759 }
760
761 // TODO: Ask the server which method to use.
762 SendHelloReply(method);
763 if (method == 0) {
764 state_ = SS_CONNECT;
765 } else if (method == 2) {
766 state_ = SS_AUTH;
767 } else {
768 state_ = SS_ERROR;
769 }
770}
771
Peter Boström0c4e06b2015-10-07 12:23:21 +0200772void AsyncSocksProxyServerSocket::SendHelloReply(uint8_t method) {
jbauchf1f87202016-03-30 06:43:37 -0700773 ByteBufferWriter response;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000774 response.WriteUInt8(5); // Socks Version
775 response.WriteUInt8(method); // Auth method
776 DirectSend(response);
777}
778
jbauchf1f87202016-03-30 06:43:37 -0700779void AsyncSocksProxyServerSocket::HandleAuth(ByteBufferReader* request) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200780 uint8_t ver, user_len, pass_len;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000781 std::string user, pass;
782 if (!request->ReadUInt8(&ver) ||
783 !request->ReadUInt8(&user_len) ||
784 !request->ReadString(&user, user_len) ||
785 !request->ReadUInt8(&pass_len) ||
786 !request->ReadString(&pass, pass_len)) {
787 Error(0);
788 return;
789 }
790
791 // TODO: Allow for checking of credentials.
792 SendAuthReply(0);
793 state_ = SS_CONNECT;
794}
795
Peter Boström0c4e06b2015-10-07 12:23:21 +0200796void AsyncSocksProxyServerSocket::SendAuthReply(uint8_t result) {
jbauchf1f87202016-03-30 06:43:37 -0700797 ByteBufferWriter response;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000798 response.WriteUInt8(1); // Negotiation Version
799 response.WriteUInt8(result);
800 DirectSend(response);
801}
802
jbauchf1f87202016-03-30 06:43:37 -0700803void AsyncSocksProxyServerSocket::HandleConnect(ByteBufferReader* request) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200804 uint8_t ver, command, reserved, addr_type;
805 uint32_t ip;
806 uint16_t port;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000807 if (!request->ReadUInt8(&ver) ||
808 !request->ReadUInt8(&command) ||
809 !request->ReadUInt8(&reserved) ||
810 !request->ReadUInt8(&addr_type) ||
811 !request->ReadUInt32(&ip) ||
812 !request->ReadUInt16(&port)) {
813 Error(0);
814 return;
815 }
816
817 if (ver != 5 || command != 1 ||
818 reserved != 0 || addr_type != 1) {
819 Error(0);
820 return;
821 }
822
823 SignalConnectRequest(this, SocketAddress(ip, port));
824 state_ = SS_CONNECT_PENDING;
825}
826
827void AsyncSocksProxyServerSocket::SendConnectResult(int result,
828 const SocketAddress& addr) {
829 if (state_ != SS_CONNECT_PENDING)
830 return;
831
jbauchf1f87202016-03-30 06:43:37 -0700832 ByteBufferWriter response;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000833 response.WriteUInt8(5); // Socks version
834 response.WriteUInt8((result != 0)); // 0x01 is generic error
835 response.WriteUInt8(0); // reserved
836 response.WriteUInt8(1); // IPv4 address
837 response.WriteUInt32(addr.ip());
838 response.WriteUInt16(addr.port());
839 DirectSend(response);
840 BufferInput(false);
841 state_ = SS_TUNNEL;
842}
843
844void AsyncSocksProxyServerSocket::Error(int error) {
845 state_ = SS_ERROR;
846 BufferInput(false);
847 Close();
848 SetError(SOCKET_EACCES);
849 SignalCloseEvent(this, error);
850}
851
852///////////////////////////////////////////////////////////////////////////////
853
854LoggingSocketAdapter::LoggingSocketAdapter(AsyncSocket* socket,
855 LoggingSeverity level,
856 const char * label, bool hex_mode)
857 : AsyncSocketAdapter(socket), level_(level), hex_mode_(hex_mode) {
858 label_.append("[");
859 label_.append(label);
860 label_.append("]");
861}
862
863int LoggingSocketAdapter::Send(const void *pv, size_t cb) {
864 int res = AsyncSocketAdapter::Send(pv, cb);
865 if (res > 0)
866 LogMultiline(level_, label_.c_str(), false, pv, res, hex_mode_, &lms_);
867 return res;
868}
869
870int LoggingSocketAdapter::SendTo(const void *pv, size_t cb,
871 const SocketAddress& addr) {
872 int res = AsyncSocketAdapter::SendTo(pv, cb, addr);
873 if (res > 0)
874 LogMultiline(level_, label_.c_str(), false, pv, res, hex_mode_, &lms_);
875 return res;
876}
877
Stefan Holmer9131efd2016-05-23 18:19:26 +0200878int LoggingSocketAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
879 int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000880 if (res > 0)
881 LogMultiline(level_, label_.c_str(), true, pv, res, hex_mode_, &lms_);
882 return res;
883}
884
Stefan Holmer9131efd2016-05-23 18:19:26 +0200885int LoggingSocketAdapter::RecvFrom(void* pv,
886 size_t cb,
887 SocketAddress* paddr,
888 int64_t* timestamp) {
889 int res = AsyncSocketAdapter::RecvFrom(pv, cb, paddr, timestamp);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000890 if (res > 0)
891 LogMultiline(level_, label_.c_str(), true, pv, res, hex_mode_, &lms_);
892 return res;
893}
894
895int LoggingSocketAdapter::Close() {
896 LogMultiline(level_, label_.c_str(), false, NULL, 0, hex_mode_, &lms_);
897 LogMultiline(level_, label_.c_str(), true, NULL, 0, hex_mode_, &lms_);
898 LOG_V(level_) << label_ << " Closed locally";
899 return socket_->Close();
900}
901
902void LoggingSocketAdapter::OnConnectEvent(AsyncSocket * socket) {
903 LOG_V(level_) << label_ << " Connected";
904 AsyncSocketAdapter::OnConnectEvent(socket);
905}
906
907void LoggingSocketAdapter::OnCloseEvent(AsyncSocket * socket, int err) {
908 LogMultiline(level_, label_.c_str(), false, NULL, 0, hex_mode_, &lms_);
909 LogMultiline(level_, label_.c_str(), true, NULL, 0, hex_mode_, &lms_);
910 LOG_V(level_) << label_ << " Closed with error: " << err;
911 AsyncSocketAdapter::OnCloseEvent(socket, err);
912}
913
914///////////////////////////////////////////////////////////////////////////////
915
916} // namespace rtc