1 /*
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 <algorithm>
16 
17 #include "absl/strings/match.h"
18 #include "rtc_base/buffer.h"
19 #include "rtc_base/byte_buffer.h"
20 #include "rtc_base/checks.h"
21 #include "rtc_base/http_common.h"
22 #include "rtc_base/logging.h"
23 #include "rtc_base/socket_adapters.h"
24 #include "rtc_base/strings/string_builder.h"
25 #include "rtc_base/zero_memory.h"
26 
27 namespace rtc {
28 
BufferedReadAdapter(AsyncSocket * socket,size_t size)29 BufferedReadAdapter::BufferedReadAdapter(AsyncSocket* socket, size_t size)
30     : AsyncSocketAdapter(socket),
31       buffer_size_(size),
32       data_len_(0),
33       buffering_(false) {
34   buffer_ = new char[buffer_size_];
35 }
36 
~BufferedReadAdapter()37 BufferedReadAdapter::~BufferedReadAdapter() {
38   delete[] buffer_;
39 }
40 
Send(const void * pv,size_t cb)41 int BufferedReadAdapter::Send(const void* pv, size_t cb) {
42   if (buffering_) {
43     // TODO: Spoof error better; Signal Writeable
44     socket_->SetError(EWOULDBLOCK);
45     return -1;
46   }
47   return AsyncSocketAdapter::Send(pv, cb);
48 }
49 
Recv(void * pv,size_t cb,int64_t * timestamp)50 int BufferedReadAdapter::Recv(void* pv, size_t cb, int64_t* timestamp) {
51   if (buffering_) {
52     socket_->SetError(EWOULDBLOCK);
53     return -1;
54   }
55 
56   size_t read = 0;
57 
58   if (data_len_) {
59     read = std::min(cb, data_len_);
60     memcpy(pv, buffer_, read);
61     data_len_ -= read;
62     if (data_len_ > 0) {
63       memmove(buffer_, buffer_ + read, data_len_);
64     }
65     pv = static_cast<char*>(pv) + read;
66     cb -= read;
67   }
68 
69   // FIX: If cb == 0, we won't generate another read event
70 
71   int res = AsyncSocketAdapter::Recv(pv, cb, timestamp);
72   if (res >= 0) {
73     // Read from socket and possibly buffer; return combined length
74     return res + static_cast<int>(read);
75   }
76 
77   if (read > 0) {
78     // Failed to read from socket, but still read something from buffer
79     return static_cast<int>(read);
80   }
81 
82   // Didn't read anything; return error from socket
83   return res;
84 }
85 
BufferInput(bool on)86 void BufferedReadAdapter::BufferInput(bool on) {
87   buffering_ = on;
88 }
89 
OnReadEvent(AsyncSocket * socket)90 void BufferedReadAdapter::OnReadEvent(AsyncSocket* socket) {
91   RTC_DCHECK(socket == socket_);
92 
93   if (!buffering_) {
94     AsyncSocketAdapter::OnReadEvent(socket);
95     return;
96   }
97 
98   if (data_len_ >= buffer_size_) {
99     RTC_LOG(LS_ERROR) << "Input buffer overflow";
100     RTC_NOTREACHED();
101     data_len_ = 0;
102   }
103 
104   int len =
105       socket_->Recv(buffer_ + data_len_, buffer_size_ - data_len_, nullptr);
106   if (len < 0) {
107     // TODO: Do something better like forwarding the error to the user.
108     RTC_LOG_ERR(INFO) << "Recv";
109     return;
110   }
111 
112   data_len_ += len;
113 
114   ProcessInput(buffer_, &data_len_);
115 }
116 
117 ///////////////////////////////////////////////////////////////////////////////
118 
119 // This is a SSL v2 CLIENT_HELLO message.
120 // TODO: Should this have a session id? The response doesn't have a
121 // certificate, so the hello should have a session id.
122 static const uint8_t kSslClientHello[] = {
123     0x80, 0x46,                                            // msg len
124     0x01,                                                  // CLIENT_HELLO
125     0x03, 0x01,                                            // SSL 3.1
126     0x00, 0x2d,                                            // ciphersuite len
127     0x00, 0x00,                                            // session id len
128     0x00, 0x10,                                            // challenge len
129     0x01, 0x00, 0x80, 0x03, 0x00, 0x80, 0x07, 0x00, 0xc0,  // ciphersuites
130     0x06, 0x00, 0x40, 0x02, 0x00, 0x80, 0x04, 0x00, 0x80,  //
131     0x00, 0x00, 0x04, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x0a,  //
132     0x00, 0xfe, 0xfe, 0x00, 0x00, 0x09, 0x00, 0x00, 0x64,  //
133     0x00, 0x00, 0x62, 0x00, 0x00, 0x03, 0x00, 0x00, 0x06,  //
134     0x1f, 0x17, 0x0c, 0xa6, 0x2f, 0x00, 0x78, 0xfc,        // challenge
135     0x46, 0x55, 0x2e, 0xb1, 0x83, 0x39, 0xf1, 0xea         //
136 };
137 
138 // static
SslClientHello()139 ArrayView<const uint8_t> AsyncSSLSocket::SslClientHello() {
140   // Implicit conversion directly from kSslClientHello to ArrayView fails when
141   // built with gcc.
142   return {kSslClientHello, sizeof(kSslClientHello)};
143 }
144 
145 // This is a TLSv1 SERVER_HELLO message.
146 static const uint8_t kSslServerHello[] = {
147     0x16,                                            // handshake message
148     0x03, 0x01,                                      // SSL 3.1
149     0x00, 0x4a,                                      // message len
150     0x02,                                            // SERVER_HELLO
151     0x00, 0x00, 0x46,                                // handshake len
152     0x03, 0x01,                                      // SSL 3.1
153     0x42, 0x85, 0x45, 0xa7, 0x27, 0xa9, 0x5d, 0xa0,  // server random
154     0xb3, 0xc5, 0xe7, 0x53, 0xda, 0x48, 0x2b, 0x3f,  //
155     0xc6, 0x5a, 0xca, 0x89, 0xc1, 0x58, 0x52, 0xa1,  //
156     0x78, 0x3c, 0x5b, 0x17, 0x46, 0x00, 0x85, 0x3f,  //
157     0x20,                                            // session id len
158     0x0e, 0xd3, 0x06, 0x72, 0x5b, 0x5b, 0x1b, 0x5f,  // session id
159     0x15, 0xac, 0x13, 0xf9, 0x88, 0x53, 0x9d, 0x9b,  //
160     0xe8, 0x3d, 0x7b, 0x0c, 0x30, 0x32, 0x6e, 0x38,  //
161     0x4d, 0xa2, 0x75, 0x57, 0x41, 0x6c, 0x34, 0x5c,  //
162     0x00, 0x04,                                      // RSA/RC4-128/MD5
163     0x00                                             // null compression
164 };
165 
166 // static
SslServerHello()167 ArrayView<const uint8_t> AsyncSSLSocket::SslServerHello() {
168   return {kSslServerHello, sizeof(kSslServerHello)};
169 }
170 
AsyncSSLSocket(AsyncSocket * socket)171 AsyncSSLSocket::AsyncSSLSocket(AsyncSocket* socket)
172     : BufferedReadAdapter(socket, 1024) {}
173 
Connect(const SocketAddress & addr)174 int AsyncSSLSocket::Connect(const SocketAddress& addr) {
175   // Begin buffering before we connect, so that there isn't a race condition
176   // between potential senders and receiving the OnConnectEvent signal
177   BufferInput(true);
178   return BufferedReadAdapter::Connect(addr);
179 }
180 
OnConnectEvent(AsyncSocket * socket)181 void AsyncSSLSocket::OnConnectEvent(AsyncSocket* socket) {
182   RTC_DCHECK(socket == socket_);
183   // TODO: we could buffer output too...
184   const int res = DirectSend(kSslClientHello, sizeof(kSslClientHello));
185   RTC_DCHECK_EQ(sizeof(kSslClientHello), res);
186 }
187 
ProcessInput(char * data,size_t * len)188 void AsyncSSLSocket::ProcessInput(char* data, size_t* len) {
189   if (*len < sizeof(kSslServerHello))
190     return;
191 
192   if (memcmp(kSslServerHello, data, sizeof(kSslServerHello)) != 0) {
193     Close();
194     SignalCloseEvent(this, 0);  // TODO: error code?
195     return;
196   }
197 
198   *len -= sizeof(kSslServerHello);
199   if (*len > 0) {
200     memmove(data, data + sizeof(kSslServerHello), *len);
201   }
202 
203   bool remainder = (*len > 0);
204   BufferInput(false);
205   SignalConnectEvent(this);
206 
207   // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
208   if (remainder)
209     SignalReadEvent(this);
210 }
211 
212 ///////////////////////////////////////////////////////////////////////////////
213 
AsyncHttpsProxySocket(AsyncSocket * socket,const std::string & user_agent,const SocketAddress & proxy,const std::string & username,const CryptString & password)214 AsyncHttpsProxySocket::AsyncHttpsProxySocket(AsyncSocket* socket,
215                                              const std::string& user_agent,
216                                              const SocketAddress& proxy,
217                                              const std::string& username,
218                                              const CryptString& password)
219     : BufferedReadAdapter(socket, 1024),
220       proxy_(proxy),
221       agent_(user_agent),
222       user_(username),
223       pass_(password),
224       force_connect_(false),
225       state_(PS_ERROR),
226       context_(0) {}
227 
~AsyncHttpsProxySocket()228 AsyncHttpsProxySocket::~AsyncHttpsProxySocket() {
229   delete context_;
230 }
231 
Connect(const SocketAddress & addr)232 int AsyncHttpsProxySocket::Connect(const SocketAddress& addr) {
233   int ret;
234   RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::Connect("
235                       << proxy_.ToSensitiveString() << ")";
236   dest_ = addr;
237   state_ = PS_INIT;
238   if (ShouldIssueConnect()) {
239     BufferInput(true);
240   }
241   ret = BufferedReadAdapter::Connect(proxy_);
242   // TODO: Set state_ appropriately if Connect fails.
243   return ret;
244 }
245 
GetRemoteAddress() const246 SocketAddress AsyncHttpsProxySocket::GetRemoteAddress() const {
247   return dest_;
248 }
249 
Close()250 int AsyncHttpsProxySocket::Close() {
251   headers_.clear();
252   state_ = PS_ERROR;
253   dest_.Clear();
254   delete context_;
255   context_ = nullptr;
256   return BufferedReadAdapter::Close();
257 }
258 
GetState() const259 Socket::ConnState AsyncHttpsProxySocket::GetState() const {
260   if (state_ < PS_TUNNEL) {
261     return CS_CONNECTING;
262   } else if (state_ == PS_TUNNEL) {
263     return CS_CONNECTED;
264   } else {
265     return CS_CLOSED;
266   }
267 }
268 
OnConnectEvent(AsyncSocket * socket)269 void AsyncHttpsProxySocket::OnConnectEvent(AsyncSocket* socket) {
270   RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnConnectEvent";
271   if (!ShouldIssueConnect()) {
272     state_ = PS_TUNNEL;
273     BufferedReadAdapter::OnConnectEvent(socket);
274     return;
275   }
276   SendRequest();
277 }
278 
OnCloseEvent(AsyncSocket * socket,int err)279 void AsyncHttpsProxySocket::OnCloseEvent(AsyncSocket* socket, int err) {
280   RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket::OnCloseEvent(" << err << ")";
281   if ((state_ == PS_WAIT_CLOSE) && (err == 0)) {
282     state_ = PS_ERROR;
283     Connect(dest_);
284   } else {
285     BufferedReadAdapter::OnCloseEvent(socket, err);
286   }
287 }
288 
ProcessInput(char * data,size_t * len)289 void AsyncHttpsProxySocket::ProcessInput(char* data, size_t* len) {
290   size_t start = 0;
291   for (size_t pos = start; state_ < PS_TUNNEL && pos < *len;) {
292     if (state_ == PS_SKIP_BODY) {
293       size_t consume = std::min(*len - pos, content_length_);
294       pos += consume;
295       start = pos;
296       content_length_ -= consume;
297       if (content_length_ == 0) {
298         EndResponse();
299       }
300       continue;
301     }
302 
303     if (data[pos++] != '\n')
304       continue;
305 
306     size_t len = pos - start - 1;
307     if ((len > 0) && (data[start + len - 1] == '\r'))
308       --len;
309 
310     data[start + len] = 0;
311     ProcessLine(data + start, len);
312     start = pos;
313   }
314 
315   *len -= start;
316   if (*len > 0) {
317     memmove(data, data + start, *len);
318   }
319 
320   if (state_ != PS_TUNNEL)
321     return;
322 
323   bool remainder = (*len > 0);
324   BufferInput(false);
325   SignalConnectEvent(this);
326 
327   // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
328   if (remainder)
329     SignalReadEvent(this);  // TODO: signal this??
330 }
331 
ShouldIssueConnect() const332 bool AsyncHttpsProxySocket::ShouldIssueConnect() const {
333   // TODO: Think about whether a more sophisticated test
334   // than dest port == 80 is needed.
335   return force_connect_ || (dest_.port() != 80);
336 }
337 
SendRequest()338 void AsyncHttpsProxySocket::SendRequest() {
339   rtc::StringBuilder ss;
340   ss << "CONNECT " << dest_.ToString() << " HTTP/1.0\r\n";
341   ss << "User-Agent: " << agent_ << "\r\n";
342   ss << "Host: " << dest_.HostAsURIString() << "\r\n";
343   ss << "Content-Length: 0\r\n";
344   ss << "Proxy-Connection: Keep-Alive\r\n";
345   ss << headers_;
346   ss << "\r\n";
347   std::string str = ss.str();
348   DirectSend(str.c_str(), str.size());
349   state_ = PS_LEADER;
350   expect_close_ = true;
351   content_length_ = 0;
352   headers_.clear();
353 
354   RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket >> " << str;
355 }
356 
ProcessLine(char * data,size_t len)357 void AsyncHttpsProxySocket::ProcessLine(char* data, size_t len) {
358   RTC_LOG(LS_VERBOSE) << "AsyncHttpsProxySocket << " << data;
359 
360   if (len == 0) {
361     if (state_ == PS_TUNNEL_HEADERS) {
362       state_ = PS_TUNNEL;
363     } else if (state_ == PS_ERROR_HEADERS) {
364       Error(defer_error_);
365       return;
366     } else if (state_ == PS_SKIP_HEADERS) {
367       if (content_length_) {
368         state_ = PS_SKIP_BODY;
369       } else {
370         EndResponse();
371         return;
372       }
373     } else {
374       if (!unknown_mechanisms_.empty()) {
375         RTC_LOG(LS_ERROR) << "Unsupported authentication methods: "
376                           << unknown_mechanisms_;
377       }
378       // Unexpected end of headers
379       Error(0);
380       return;
381     }
382   } else if (state_ == PS_LEADER) {
383     unsigned int code;
384     if (sscanf(data, "HTTP/%*u.%*u %u", &code) != 1) {
385       Error(0);
386       return;
387     }
388     switch (code) {
389       case 200:
390         // connection good!
391         state_ = PS_TUNNEL_HEADERS;
392         return;
393 #if defined(HTTP_STATUS_PROXY_AUTH_REQ) && (HTTP_STATUS_PROXY_AUTH_REQ != 407)
394 #error Wrong code for HTTP_STATUS_PROXY_AUTH_REQ
395 #endif
396       case 407:  // HTTP_STATUS_PROXY_AUTH_REQ
397         state_ = PS_AUTHENTICATE;
398         return;
399       default:
400         defer_error_ = 0;
401         state_ = PS_ERROR_HEADERS;
402         return;
403     }
404   } else if ((state_ == PS_AUTHENTICATE) &&
405              absl::StartsWithIgnoreCase(data, "Proxy-Authenticate:")) {
406     std::string response, auth_method;
407     switch (HttpAuthenticate(data + 19, len - 19, proxy_, "CONNECT", "/", user_,
408                              pass_, context_, response, auth_method)) {
409       case HAR_IGNORE:
410         RTC_LOG(LS_VERBOSE) << "Ignoring Proxy-Authenticate: " << auth_method;
411         if (!unknown_mechanisms_.empty())
412           unknown_mechanisms_.append(", ");
413         unknown_mechanisms_.append(auth_method);
414         break;
415       case HAR_RESPONSE:
416         headers_ = "Proxy-Authorization: ";
417         headers_.append(response);
418         headers_.append("\r\n");
419         state_ = PS_SKIP_HEADERS;
420         unknown_mechanisms_.clear();
421         break;
422       case HAR_CREDENTIALS:
423         defer_error_ = SOCKET_EACCES;
424         state_ = PS_ERROR_HEADERS;
425         unknown_mechanisms_.clear();
426         break;
427       case HAR_ERROR:
428         defer_error_ = 0;
429         state_ = PS_ERROR_HEADERS;
430         unknown_mechanisms_.clear();
431         break;
432     }
433   } else if (absl::StartsWithIgnoreCase(data, "Content-Length:")) {
434     content_length_ = strtoul(data + 15, 0, 0);
435   } else if (absl::StartsWithIgnoreCase(data, "Proxy-Connection: Keep-Alive")) {
436     expect_close_ = false;
437     /*
438   } else if (absl::StartsWithIgnoreCase(data, "Connection: close") {
439     expect_close_ = true;
440     */
441   }
442 }
443 
EndResponse()444 void AsyncHttpsProxySocket::EndResponse() {
445   if (!expect_close_) {
446     SendRequest();
447     return;
448   }
449 
450   // No point in waiting for the server to close... let's close now
451   // TODO: Refactor out PS_WAIT_CLOSE
452   state_ = PS_WAIT_CLOSE;
453   BufferedReadAdapter::Close();
454   OnCloseEvent(this, 0);
455 }
456 
Error(int error)457 void AsyncHttpsProxySocket::Error(int error) {
458   BufferInput(false);
459   Close();
460   SetError(error);
461   SignalCloseEvent(this, error);
462 }
463 
464 ///////////////////////////////////////////////////////////////////////////////
465 
AsyncSocksProxySocket(AsyncSocket * socket,const SocketAddress & proxy,const std::string & username,const CryptString & password)466 AsyncSocksProxySocket::AsyncSocksProxySocket(AsyncSocket* socket,
467                                              const SocketAddress& proxy,
468                                              const std::string& username,
469                                              const CryptString& password)
470     : BufferedReadAdapter(socket, 1024),
471       state_(SS_ERROR),
472       proxy_(proxy),
473       user_(username),
474       pass_(password) {}
475 
476 AsyncSocksProxySocket::~AsyncSocksProxySocket() = default;
477 
Connect(const SocketAddress & addr)478 int AsyncSocksProxySocket::Connect(const SocketAddress& addr) {
479   int ret;
480   dest_ = addr;
481   state_ = SS_INIT;
482   BufferInput(true);
483   ret = BufferedReadAdapter::Connect(proxy_);
484   // TODO: Set state_ appropriately if Connect fails.
485   return ret;
486 }
487 
GetRemoteAddress() const488 SocketAddress AsyncSocksProxySocket::GetRemoteAddress() const {
489   return dest_;
490 }
491 
Close()492 int AsyncSocksProxySocket::Close() {
493   state_ = SS_ERROR;
494   dest_.Clear();
495   return BufferedReadAdapter::Close();
496 }
497 
GetState() const498 Socket::ConnState AsyncSocksProxySocket::GetState() const {
499   if (state_ < SS_TUNNEL) {
500     return CS_CONNECTING;
501   } else if (state_ == SS_TUNNEL) {
502     return CS_CONNECTED;
503   } else {
504     return CS_CLOSED;
505   }
506 }
507 
OnConnectEvent(AsyncSocket * socket)508 void AsyncSocksProxySocket::OnConnectEvent(AsyncSocket* socket) {
509   SendHello();
510 }
511 
ProcessInput(char * data,size_t * len)512 void AsyncSocksProxySocket::ProcessInput(char* data, size_t* len) {
513   RTC_DCHECK(state_ < SS_TUNNEL);
514 
515   ByteBufferReader response(data, *len);
516 
517   if (state_ == SS_HELLO) {
518     uint8_t ver, method;
519     if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&method))
520       return;
521 
522     if (ver != 5) {
523       Error(0);
524       return;
525     }
526 
527     if (method == 0) {
528       SendConnect();
529     } else if (method == 2) {
530       SendAuth();
531     } else {
532       Error(0);
533       return;
534     }
535   } else if (state_ == SS_AUTH) {
536     uint8_t ver, status;
537     if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&status))
538       return;
539 
540     if ((ver != 1) || (status != 0)) {
541       Error(SOCKET_EACCES);
542       return;
543     }
544 
545     SendConnect();
546   } else if (state_ == SS_CONNECT) {
547     uint8_t ver, rep, rsv, atyp;
548     if (!response.ReadUInt8(&ver) || !response.ReadUInt8(&rep) ||
549         !response.ReadUInt8(&rsv) || !response.ReadUInt8(&atyp))
550       return;
551 
552     if ((ver != 5) || (rep != 0)) {
553       Error(0);
554       return;
555     }
556 
557     uint16_t port;
558     if (atyp == 1) {
559       uint32_t addr;
560       if (!response.ReadUInt32(&addr) || !response.ReadUInt16(&port))
561         return;
562       RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
563     } else if (atyp == 3) {
564       uint8_t len;
565       std::string addr;
566       if (!response.ReadUInt8(&len) || !response.ReadString(&addr, len) ||
567           !response.ReadUInt16(&port))
568         return;
569       RTC_LOG(LS_VERBOSE) << "Bound on " << addr << ":" << port;
570     } else if (atyp == 4) {
571       std::string addr;
572       if (!response.ReadString(&addr, 16) || !response.ReadUInt16(&port))
573         return;
574       RTC_LOG(LS_VERBOSE) << "Bound on <IPV6>:" << port;
575     } else {
576       Error(0);
577       return;
578     }
579 
580     state_ = SS_TUNNEL;
581   }
582 
583   // Consume parsed data
584   *len = response.Length();
585   memmove(data, response.Data(), *len);
586 
587   if (state_ != SS_TUNNEL)
588     return;
589 
590   bool remainder = (*len > 0);
591   BufferInput(false);
592   SignalConnectEvent(this);
593 
594   // FIX: if SignalConnect causes the socket to be destroyed, we are in trouble
595   if (remainder)
596     SignalReadEvent(this);  // TODO: signal this??
597 }
598 
SendHello()599 void AsyncSocksProxySocket::SendHello() {
600   ByteBufferWriter request;
601   request.WriteUInt8(5);  // Socks Version
602   if (user_.empty()) {
603     request.WriteUInt8(1);  // Authentication Mechanisms
604     request.WriteUInt8(0);  // No authentication
605   } else {
606     request.WriteUInt8(2);  // Authentication Mechanisms
607     request.WriteUInt8(0);  // No authentication
608     request.WriteUInt8(2);  // Username/Password
609   }
610   DirectSend(request.Data(), request.Length());
611   state_ = SS_HELLO;
612 }
613 
SendAuth()614 void AsyncSocksProxySocket::SendAuth() {
615   ByteBufferWriterT<ZeroOnFreeBuffer<char>> request;
616   request.WriteUInt8(1);  // Negotiation Version
617   request.WriteUInt8(static_cast<uint8_t>(user_.size()));
618   request.WriteString(user_);  // Username
619   request.WriteUInt8(static_cast<uint8_t>(pass_.GetLength()));
620   size_t len = pass_.GetLength() + 1;
621   char* sensitive = new char[len];
622   pass_.CopyTo(sensitive, true);
623   request.WriteBytes(sensitive, pass_.GetLength());  // Password
624   ExplicitZeroMemory(sensitive, len);
625   delete[] sensitive;
626   DirectSend(request.Data(), request.Length());
627   state_ = SS_AUTH;
628 }
629 
SendConnect()630 void AsyncSocksProxySocket::SendConnect() {
631   ByteBufferWriter request;
632   request.WriteUInt8(5);  // Socks Version
633   request.WriteUInt8(1);  // CONNECT
634   request.WriteUInt8(0);  // Reserved
635   if (dest_.IsUnresolvedIP()) {
636     std::string hostname = dest_.hostname();
637     request.WriteUInt8(3);  // DOMAINNAME
638     request.WriteUInt8(static_cast<uint8_t>(hostname.size()));
639     request.WriteString(hostname);  // Destination Hostname
640   } else {
641     request.WriteUInt8(1);            // IPV4
642     request.WriteUInt32(dest_.ip());  // Destination IP
643   }
644   request.WriteUInt16(dest_.port());  // Destination Port
645   DirectSend(request.Data(), request.Length());
646   state_ = SS_CONNECT;
647 }
648 
Error(int error)649 void AsyncSocksProxySocket::Error(int error) {
650   state_ = SS_ERROR;
651   BufferInput(false);
652   Close();
653   SetError(SOCKET_EACCES);
654   SignalCloseEvent(this, error);
655 }
656 
657 }  // namespace rtc
658