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