• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9 
10 #include "net/socket/tcp_socket.h"
11 
12 #include <errno.h>
13 #include <mstcpip.h>
14 
15 #include <memory>
16 #include <utility>
17 
18 #include "base/check_op.h"
19 #include "base/feature_list.h"
20 #include "base/files/file_util.h"
21 #include "base/functional/bind.h"
22 #include "base/functional/callback_helpers.h"
23 #include "base/logging.h"
24 #include "base/memory/raw_ptr.h"
25 #include "base/win/windows_version.h"
26 #include "net/base/address_list.h"
27 #include "net/base/features.h"
28 #include "net/base/io_buffer.h"
29 #include "net/base/ip_endpoint.h"
30 #include "net/base/net_errors.h"
31 #include "net/base/network_activity_monitor.h"
32 #include "net/base/network_change_notifier.h"
33 #include "net/base/sockaddr_storage.h"
34 #include "net/base/winsock_init.h"
35 #include "net/base/winsock_util.h"
36 #include "net/log/net_log.h"
37 #include "net/log/net_log_event_type.h"
38 #include "net/log/net_log_source.h"
39 #include "net/log/net_log_source_type.h"
40 #include "net/log/net_log_values.h"
41 #include "net/socket/socket_descriptor.h"
42 #include "net/socket/socket_net_log_params.h"
43 #include "net/socket/socket_options.h"
44 #include "net/socket/socket_tag.h"
45 #include "net/socket/tcp_socket_io_completion_port_win.h"
46 #include "net/socket/tcp_socket_win.h"
47 
48 namespace net {
49 
50 namespace {
51 
52 const int kTCPKeepAliveSeconds = 45;
53 
54 // Disable Nagle.
55 // Enable TCP Keep-Alive to prevent NAT routers from timing out TCP
56 // connections. See http://crbug.com/27400 for details.
SetTCPKeepAlive(SOCKET socket,BOOL enable,int delay_secs)57 bool SetTCPKeepAlive(SOCKET socket, BOOL enable, int delay_secs) {
58   unsigned delay = delay_secs * 1000;
59   struct tcp_keepalive keepalive_vals = {
60       enable ? 1u : 0u,  // TCP keep-alive on.
61       delay,  // Delay seconds before sending first TCP keep-alive packet.
62       delay,  // Delay seconds between sending TCP keep-alive packets.
63   };
64   DWORD bytes_returned = 0xABAB;
65   int rv = WSAIoctl(socket, SIO_KEEPALIVE_VALS, &keepalive_vals,
66                     sizeof(keepalive_vals), nullptr, 0, &bytes_returned,
67                     nullptr, nullptr);
68   int os_error = WSAGetLastError();
69   DCHECK(!rv) << "Could not enable TCP Keep-Alive for socket: " << socket
70               << " [error: " << os_error << "].";
71 
72   // Disregard any failure in disabling nagle or enabling TCP Keep-Alive.
73   return rv == 0;
74 }
75 
MapConnectError(int os_error)76 int MapConnectError(int os_error) {
77   switch (os_error) {
78     // connect fails with WSAEACCES when Windows Firewall blocks the
79     // connection.
80     case WSAEACCES:
81       return ERR_NETWORK_ACCESS_DENIED;
82     case WSAETIMEDOUT:
83       return ERR_CONNECTION_TIMED_OUT;
84     default: {
85       int net_error = MapSystemError(os_error);
86       if (net_error == ERR_FAILED)
87         return ERR_CONNECTION_FAILED;  // More specific than ERR_FAILED.
88 
89       // Give a more specific error when the user is offline.
90       if (net_error == ERR_ADDRESS_UNREACHABLE &&
91           NetworkChangeNotifier::IsOffline()) {
92         return ERR_INTERNET_DISCONNECTED;
93       }
94 
95       return net_error;
96     }
97   }
98 }
99 
SetNonBlockingAndGetError(int fd,int * os_error)100 bool SetNonBlockingAndGetError(int fd, int* os_error) {
101   bool ret = base::SetNonBlocking(fd);
102   *os_error = WSAGetLastError();
103 
104   return ret;
105 }
106 
107 }  // namespace
108 
109 //-----------------------------------------------------------------------------
110 
111 class NET_EXPORT TCPSocketDefaultWin : public TCPSocketWin {
112  public:
113   TCPSocketDefaultWin(
114       std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
115       NetLog* net_log,
116       const NetLogSource& source);
117 
118   TCPSocketDefaultWin(
119       std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
120       NetLogWithSource net_log_source);
121 
122   ~TCPSocketDefaultWin() override;
123 
124   // TCPSocketWin:
125   int Read(IOBuffer* buf,
126            int buf_len,
127            CompletionOnceCallback callback) override;
128   int ReadIfReady(IOBuffer* buf,
129                   int buf_len,
130                   CompletionOnceCallback callback) override;
131   int CancelReadIfReady() override;
132   int Write(IOBuffer* buf,
133             int buf_len,
134             CompletionOnceCallback callback,
135             const NetworkTrafficAnnotationTag& traffic_annotation) override;
136 
137  protected:
138   // TCPSocketWin:
139   scoped_refptr<Core> CreateCore() override;
140   bool HasPendingRead() const override;
141   void OnClosed() override;
142 
143  private:
144   class CoreImpl;
145 
146   void RetryRead(int rv);
147   void DidCompleteWrite();
148   void DidSignalRead();
149 
150   CoreImpl& GetCoreImpl();
151 
152   // External callback; called when read is complete.
153   CompletionOnceCallback read_callback_;
154 
155   // Non-null if a ReadIfReady() is to be completed asynchronously. This is an
156   // external callback if user used ReadIfReady() instead of Read(), but a
157   // wrapped callback on top of RetryRead() if Read() is used.
158   CompletionOnceCallback read_if_ready_callback_;
159 
160   // External callback; called when write is complete.
161   CompletionOnceCallback write_callback_;
162 };
163 
164 class TCPSocketDefaultWin::CoreImpl : public TCPSocketWin::Core {
165  public:
166   explicit CoreImpl(TCPSocketDefaultWin* socket);
167 
168   CoreImpl(const CoreImpl&) = delete;
169   CoreImpl& operator=(const CoreImpl&) = delete;
170 
171   // Start watching for the end of a read or write operation.
172   void WatchForRead();
173   void WatchForWrite();
174 
175   // Stops watching for read.
176   void StopWatchingForRead();
177 
178   // TCPSocketWin::Core:
179   void Detach() override;
180   HANDLE GetConnectEvent() override;
181   void WatchForConnect() override;
182 
183   // Event handle for monitoring connect and read events through WSAEventSelect.
184   HANDLE read_event_;
185 
186   // OVERLAPPED variable for overlapped writes.
187   // TODO(mmenke): Can writes be switched to WSAEventSelect as well? That would
188   // allow removing this class. The only concern is whether that would have a
189   // negative perf impact.
190   OVERLAPPED write_overlapped_;
191 
192   // The buffers used in Read() and Write().
193   scoped_refptr<IOBuffer> read_iobuffer_;
194   scoped_refptr<IOBuffer> write_iobuffer_;
195   int read_buffer_length_ = 0;
196   int write_buffer_length_ = 0;
197 
198   bool non_blocking_reads_initialized_ = false;
199 
200  private:
201   class ReadDelegate : public base::win::ObjectWatcher::Delegate {
202    public:
ReadDelegate(CoreImpl * core)203     explicit ReadDelegate(CoreImpl* core) : core_(core) {}
204     ~ReadDelegate() override = default;
205 
206     // base::ObjectWatcher::Delegate methods:
207     void OnObjectSignaled(HANDLE object) override;
208 
209    private:
210     const raw_ptr<CoreImpl> core_;
211   };
212 
213   class WriteDelegate : public base::win::ObjectWatcher::Delegate {
214    public:
WriteDelegate(CoreImpl * core)215     explicit WriteDelegate(CoreImpl* core) : core_(core) {}
216     ~WriteDelegate() override = default;
217 
218     // base::ObjectWatcher::Delegate methods:
219     void OnObjectSignaled(HANDLE object) override;
220 
221    private:
222     const raw_ptr<CoreImpl> core_;
223   };
224 
225   ~CoreImpl() override;
226 
227   // The socket that created this object.
228   raw_ptr<TCPSocketDefaultWin> socket_;
229 
230   // |reader_| handles the signals from |read_watcher_|.
231   ReadDelegate reader_;
232   // |writer_| handles the signals from |write_watcher_|.
233   WriteDelegate writer_;
234 
235   // |read_watcher_| watches for events from Connect() and Read().
236   base::win::ObjectWatcher read_watcher_;
237   // |write_watcher_| watches for events from Write();
238   base::win::ObjectWatcher write_watcher_;
239 };
240 
241 TCPSocketWin::Core::Core() = default;
242 TCPSocketWin::Core::~Core() = default;
243 
CoreImpl(TCPSocketDefaultWin * socket)244 TCPSocketDefaultWin::CoreImpl::CoreImpl(TCPSocketDefaultWin* socket)
245     : read_event_(WSACreateEvent()),
246       socket_(socket),
247       reader_(this),
248       writer_(this) {
249   memset(&write_overlapped_, 0, sizeof(write_overlapped_));
250   write_overlapped_.hEvent = WSACreateEvent();
251 }
252 
~CoreImpl()253 TCPSocketDefaultWin::CoreImpl::~CoreImpl() {
254   // Detach should already have been called.
255   DCHECK(!socket_);
256 
257   // Stop the write watcher.  The read watcher should already have been stopped
258   // in Detach().
259   write_watcher_.StopWatching();
260   WSACloseEvent(write_overlapped_.hEvent);
261   memset(&write_overlapped_, 0xaf, sizeof(write_overlapped_));
262 }
263 
WatchForRead()264 void TCPSocketDefaultWin::CoreImpl::WatchForRead() {
265   // Reads use WSAEventSelect, which closesocket() cancels so unlike writes,
266   // there's no need to increment the reference count here.
267   read_watcher_.StartWatchingOnce(read_event_, &reader_);
268 }
269 
WatchForWrite()270 void TCPSocketDefaultWin::CoreImpl::WatchForWrite() {
271   // We grab an extra reference because there is an IO operation in progress.
272   // Balanced in WriteDelegate::OnObjectSignaled().
273   AddRef();
274   write_watcher_.StartWatchingOnce(write_overlapped_.hEvent, &writer_);
275 }
276 
StopWatchingForRead()277 void TCPSocketDefaultWin::CoreImpl::StopWatchingForRead() {
278   DCHECK(!socket_->connect_callback_);
279 
280   read_watcher_.StopWatching();
281 }
282 
Detach()283 void TCPSocketDefaultWin::CoreImpl::Detach() {
284   // Stop watching the read watcher. A read won't be signalled after the Detach
285   // call, since the socket has been closed, but it's possible the event was
286   // signalled when the socket was closed, but hasn't been handled yet, so need
287   // to stop watching now to avoid trying to handle the event. See
288   // https://crbug.com/831149
289   read_watcher_.StopWatching();
290   WSACloseEvent(read_event_);
291 
292   socket_ = nullptr;
293 }
294 
GetConnectEvent()295 HANDLE TCPSocketDefaultWin::CoreImpl::GetConnectEvent() {
296   // `read_event_` is used to watch for connect.
297   return read_event_;
298 }
299 
WatchForConnect()300 void TCPSocketDefaultWin::CoreImpl::WatchForConnect() {
301   // `read_event_` is used to watch for connect.
302   WatchForRead();
303 }
304 
OnObjectSignaled(HANDLE object)305 void TCPSocketDefaultWin::CoreImpl::ReadDelegate::OnObjectSignaled(
306     HANDLE object) {
307   DCHECK_EQ(object, core_->read_event_);
308   DCHECK(core_->socket_);
309   if (core_->socket_->connect_callback_) {
310     core_->socket_->DidCompleteConnect();
311   } else {
312     core_->socket_->DidSignalRead();
313   }
314 }
315 
OnObjectSignaled(HANDLE object)316 void TCPSocketDefaultWin::CoreImpl::WriteDelegate::OnObjectSignaled(
317     HANDLE object) {
318   DCHECK_EQ(object, core_->write_overlapped_.hEvent);
319   if (core_->socket_)
320     core_->socket_->DidCompleteWrite();
321 
322   // Matches the AddRef() in WatchForWrite().
323   core_->Release();
324 }
325 
326 //-----------------------------------------------------------------------------
327 
328 // static
Create(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLog * net_log,const NetLogSource & source)329 std::unique_ptr<TCPSocketWin> TCPSocketWin::Create(
330     std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
331     NetLog* net_log,
332     const NetLogSource& source) {
333   if (base::FeatureList::IsEnabled(features::kTcpSocketIoCompletionPortWin)) {
334     return std::make_unique<TcpSocketIoCompletionPortWin>(
335         std::move(socket_performance_watcher), net_log, source);
336   }
337   return std::make_unique<TCPSocketDefaultWin>(
338       std::move(socket_performance_watcher), net_log, source);
339 }
340 
341 // static
Create(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLogWithSource net_log_source)342 std::unique_ptr<TCPSocketWin> TCPSocketWin::Create(
343     std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
344     NetLogWithSource net_log_source) {
345   if (base::FeatureList::IsEnabled(features::kTcpSocketIoCompletionPortWin)) {
346     return std::make_unique<TcpSocketIoCompletionPortWin>(
347         std::move(socket_performance_watcher), net_log_source);
348   }
349   return std::make_unique<TCPSocketDefaultWin>(
350       std::move(socket_performance_watcher), std::move(net_log_source));
351 }
352 
TCPSocketWin(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,net::NetLog * net_log,const net::NetLogSource & source)353 TCPSocketWin::TCPSocketWin(
354     std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
355     net::NetLog* net_log,
356     const net::NetLogSource& source)
357     : socket_(INVALID_SOCKET),
358       socket_performance_watcher_(std::move(socket_performance_watcher)),
359       accept_event_(WSA_INVALID_EVENT),
360       net_log_(NetLogWithSource::Make(net_log, NetLogSourceType::SOCKET)) {
361   net_log_.BeginEventReferencingSource(NetLogEventType::SOCKET_ALIVE, source);
362   EnsureWinsockInit();
363 }
364 
TCPSocketWin(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLogWithSource net_log_source)365 TCPSocketWin::TCPSocketWin(
366     std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
367     NetLogWithSource net_log_source)
368     : socket_(INVALID_SOCKET),
369       socket_performance_watcher_(std::move(socket_performance_watcher)),
370       accept_event_(WSA_INVALID_EVENT),
371       net_log_(std::move(net_log_source)) {
372   net_log_.BeginEvent(NetLogEventType::SOCKET_ALIVE);
373   EnsureWinsockInit();
374 }
375 
~TCPSocketWin()376 TCPSocketWin::~TCPSocketWin() {
377   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
378 
379   // The subclass must call `Close`. See comment in header file.
380   CHECK(!core_);
381 
382   net_log_.EndEvent(NetLogEventType::SOCKET_ALIVE);
383 }
384 
Open(AddressFamily family)385 int TCPSocketWin::Open(AddressFamily family) {
386   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
387   DCHECK_EQ(socket_, INVALID_SOCKET);
388 
389   socket_ = CreatePlatformSocket(ConvertAddressFamily(family), SOCK_STREAM,
390                                  IPPROTO_TCP);
391   int os_error = WSAGetLastError();
392   if (socket_ == INVALID_SOCKET) {
393     PLOG(ERROR) << "CreatePlatformSocket() returned an error";
394     return MapSystemError(os_error);
395   }
396 
397   if (!SetNonBlockingAndGetError(socket_, &os_error)) {
398     int result = MapSystemError(os_error);
399     Close();
400     return result;
401   }
402 
403   return OK;
404 }
405 
AdoptConnectedSocket(SocketDescriptor socket,const IPEndPoint & peer_address)406 int TCPSocketWin::AdoptConnectedSocket(SocketDescriptor socket,
407                                        const IPEndPoint& peer_address) {
408   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
409   DCHECK_EQ(socket_, INVALID_SOCKET);
410   DCHECK(!core_.get());
411 
412   socket_ = socket;
413 
414   int os_error;
415   if (!SetNonBlockingAndGetError(socket_, &os_error)) {
416     int result = MapSystemError(os_error);
417     Close();
418     return result;
419   }
420 
421   core_ = CreateCore();
422   peer_address_ = std::make_unique<IPEndPoint>(peer_address);
423 
424   return OK;
425 }
426 
AdoptUnconnectedSocket(SocketDescriptor socket)427 int TCPSocketWin::AdoptUnconnectedSocket(SocketDescriptor socket) {
428   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
429   DCHECK_EQ(socket_, INVALID_SOCKET);
430 
431   socket_ = socket;
432 
433   int os_error;
434   if (!SetNonBlockingAndGetError(socket_, &os_error)) {
435     int result = MapSystemError(os_error);
436     Close();
437     return result;
438   }
439 
440   // |core_| is not needed for sockets that are used to accept connections.
441   // The operation here is more like Open but with an existing socket.
442 
443   return OK;
444 }
445 
Bind(const IPEndPoint & address)446 int TCPSocketWin::Bind(const IPEndPoint& address) {
447   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
448   DCHECK_NE(socket_, INVALID_SOCKET);
449 
450   SockaddrStorage storage;
451   if (!address.ToSockAddr(storage.addr, &storage.addr_len))
452     return ERR_ADDRESS_INVALID;
453 
454   int result = bind(socket_, storage.addr, storage.addr_len);
455   int os_error = WSAGetLastError();
456   if (result < 0) {
457     PLOG(ERROR) << "bind() returned an error";
458     return MapSystemError(os_error);
459   }
460 
461   return OK;
462 }
463 
Listen(int backlog)464 int TCPSocketWin::Listen(int backlog) {
465   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
466   DCHECK_GT(backlog, 0);
467   DCHECK_NE(socket_, INVALID_SOCKET);
468   DCHECK_EQ(accept_event_, WSA_INVALID_EVENT);
469 
470   accept_event_ = WSACreateEvent();
471   int os_error = WSAGetLastError();
472   if (accept_event_ == WSA_INVALID_EVENT) {
473     PLOG(ERROR) << "WSACreateEvent()";
474     return MapSystemError(os_error);
475   }
476 
477   int result = listen(socket_, backlog);
478   os_error = WSAGetLastError();
479   if (result < 0) {
480     PLOG(ERROR) << "listen() returned an error";
481     return MapSystemError(os_error);
482   }
483 
484   return OK;
485 }
486 
Accept(std::unique_ptr<TCPSocketWin> * socket,IPEndPoint * address,CompletionOnceCallback callback)487 int TCPSocketWin::Accept(std::unique_ptr<TCPSocketWin>* socket,
488                          IPEndPoint* address,
489                          CompletionOnceCallback callback) {
490   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
491   DCHECK(socket);
492   DCHECK(address);
493   DCHECK(!callback.is_null());
494   DCHECK(accept_callback_.is_null());
495 
496   net_log_.BeginEvent(NetLogEventType::TCP_ACCEPT);
497 
498   int result = AcceptInternal(socket, address);
499 
500   if (result == ERR_IO_PENDING) {
501     // Start watching.
502     WSAEventSelect(socket_, accept_event_, FD_ACCEPT);
503     accept_watcher_.StartWatchingOnce(accept_event_, this);
504 
505     accept_socket_ = socket;
506     accept_address_ = address;
507     accept_callback_ = std::move(callback);
508   }
509 
510   return result;
511 }
512 
Connect(const IPEndPoint & address,CompletionOnceCallback callback)513 int TCPSocketWin::Connect(const IPEndPoint& address,
514                           CompletionOnceCallback callback) {
515   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
516   DCHECK_NE(socket_, INVALID_SOCKET);
517   DCHECK(!connect_callback_);
518   DCHECK(callback);
519 
520   // |peer_address_| and |core_| will be non-NULL if Connect() has been called.
521   // Unless Close() is called to reset the internal state, a second call to
522   // Connect() is not allowed.
523   // Please note that we enforce this even if the previous Connect() has
524   // completed and failed. Although it is allowed to connect the same |socket_|
525   // again after a connection attempt failed on Windows, it results in
526   // unspecified behavior according to POSIX. Therefore, we make it behave in
527   // the same way as TCPSocketPosix.
528   DCHECK(!peer_address_ && !core_.get());
529 
530   if (!logging_multiple_connect_attempts_)
531     LogConnectBegin(AddressList(address));
532 
533   peer_address_ = std::make_unique<IPEndPoint>(address);
534 
535   int rv = DoConnect();
536   if (rv == ERR_IO_PENDING) {
537     // Synchronous operation not supported.
538     connect_callback_ = std::move(callback);
539   } else {
540     DoConnectComplete(rv);
541   }
542 
543   return rv;
544 }
545 
IsConnected() const546 bool TCPSocketWin::IsConnected() const {
547   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
548 
549   if (socket_ == INVALID_SOCKET || connect_callback_) {
550     // Outstanding connect attempt pending.
551     return false;
552   }
553 
554   if (HasPendingRead()) {
555     return true;
556   }
557 
558   char c;
559   int rv = recv(socket_, &c, 1, MSG_PEEK);
560   if (rv == 0) {
561     // Connection gracefully closed.
562     return false;
563   }
564   int os_error = WSAGetLastError();
565   if (rv == SOCKET_ERROR && os_error != WSAEWOULDBLOCK) {
566     // Connection dropped/terminated due to error.
567     return false;
568   }
569 
570   // One byte available or would block waiting for one byte.
571   return true;
572 }
573 
IsConnectedAndIdle() const574 bool TCPSocketWin::IsConnectedAndIdle() const {
575   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
576 
577   if (socket_ == INVALID_SOCKET || connect_callback_) {
578     // Outstanding connect attempt pending.
579     return false;
580   }
581 
582   if (HasPendingRead()) {
583     return true;
584   }
585 
586   char c;
587   int rv = recv(socket_, &c, 1, MSG_PEEK);
588   if (rv >= 0) {
589     // Connection gracefully closed or one byte available to read without
590     // blocking.
591     return false;
592   }
593   int os_error = WSAGetLastError();
594   if (os_error != WSAEWOULDBLOCK) {
595     // Connection dropped/terminated due to error.
596     return false;
597   }
598 
599   // No data available; blocking required.
600   return true;
601 }
602 
Read(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)603 int TCPSocketDefaultWin::Read(IOBuffer* buf,
604                               int buf_len,
605                               CompletionOnceCallback callback) {
606   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
607   CoreImpl& core = GetCoreImpl();
608   DCHECK(!core.read_iobuffer_.get());
609   // base::Unretained() is safe because RetryRead() won't be called when |this|
610   // is gone.
611   int rv = ReadIfReady(
612       buf, buf_len,
613       base::BindOnce(&TCPSocketDefaultWin::RetryRead, base::Unretained(this)));
614   if (rv != ERR_IO_PENDING)
615     return rv;
616   read_callback_ = std::move(callback);
617   core.read_iobuffer_ = buf;
618   core.read_buffer_length_ = buf_len;
619   return ERR_IO_PENDING;
620 }
621 
ReadIfReady(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)622 int TCPSocketDefaultWin::ReadIfReady(IOBuffer* buf,
623                                      int buf_len,
624                                      CompletionOnceCallback callback) {
625   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
626   DCHECK_NE(socket_, INVALID_SOCKET);
627   DCHECK(read_if_ready_callback_.is_null());
628 
629   CoreImpl& core = GetCoreImpl();
630   if (!core.non_blocking_reads_initialized_) {
631     WSAEventSelect(socket_, core.read_event_, FD_READ | FD_CLOSE);
632     core.non_blocking_reads_initialized_ = true;
633   }
634   int rv = recv(socket_, buf->data(), buf_len, 0);
635   int os_error = WSAGetLastError();
636   if (rv == SOCKET_ERROR) {
637     if (os_error != WSAEWOULDBLOCK) {
638       int net_error = MapSystemError(os_error);
639       NetLogSocketError(net_log_, NetLogEventType::SOCKET_READ_ERROR, net_error,
640                         os_error);
641       return net_error;
642     }
643   } else {
644     net_log_.AddByteTransferEvent(NetLogEventType::SOCKET_BYTES_RECEIVED, rv,
645                                   buf->data());
646     activity_monitor::IncrementBytesReceived(rv);
647     return rv;
648   }
649 
650   read_if_ready_callback_ = std::move(callback);
651   core.WatchForRead();
652   return ERR_IO_PENDING;
653 }
654 
CancelReadIfReady()655 int TCPSocketDefaultWin::CancelReadIfReady() {
656   DCHECK(read_callback_.is_null());
657   DCHECK(!read_if_ready_callback_.is_null());
658 
659   GetCoreImpl().StopWatchingForRead();
660   read_if_ready_callback_.Reset();
661   return net::OK;
662 }
663 
Write(IOBuffer * buf,int buf_len,CompletionOnceCallback callback,const NetworkTrafficAnnotationTag &)664 int TCPSocketDefaultWin::Write(
665     IOBuffer* buf,
666     int buf_len,
667     CompletionOnceCallback callback,
668     const NetworkTrafficAnnotationTag& /* traffic_annotation */) {
669   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
670   DCHECK_NE(socket_, INVALID_SOCKET);
671   CHECK(write_callback_.is_null());
672   DCHECK_GT(buf_len, 0);
673   CoreImpl& core = GetCoreImpl();
674   DCHECK(!core.write_iobuffer_.get());
675 
676   WSABUF write_buffer;
677   write_buffer.len = buf_len;
678   write_buffer.buf = buf->data();
679 
680   DWORD num;
681   int rv = WSASend(socket_, &write_buffer, 1, &num, 0, &core.write_overlapped_,
682                    nullptr);
683   int os_error = WSAGetLastError();
684   if (rv == 0) {
685     if (ResetEventIfSignaled(core.write_overlapped_.hEvent)) {
686       rv = static_cast<int>(num);
687       if (rv > buf_len || rv < 0) {
688         // It seems that some winsock interceptors report that more was written
689         // than was available. Treat this as an error.  http://crbug.com/27870
690         LOG(ERROR) << "Detected broken LSP: Asked to write " << buf_len
691                    << " bytes, but " << rv << " bytes reported.";
692         return ERR_WINSOCK_UNEXPECTED_WRITTEN_BYTES;
693       }
694       net_log_.AddByteTransferEvent(NetLogEventType::SOCKET_BYTES_SENT, rv,
695                                     buf->data());
696       return rv;
697     }
698   } else {
699     if (os_error != WSA_IO_PENDING) {
700       int net_error = MapSystemError(os_error);
701       NetLogSocketError(net_log_, NetLogEventType::SOCKET_WRITE_ERROR,
702                         net_error, os_error);
703       return net_error;
704     }
705   }
706   write_callback_ = std::move(callback);
707   core.write_iobuffer_ = buf;
708   core.write_buffer_length_ = buf_len;
709   core.WatchForWrite();
710   return ERR_IO_PENDING;
711 }
712 
GetLocalAddress(IPEndPoint * address) const713 int TCPSocketWin::GetLocalAddress(IPEndPoint* address) const {
714   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
715   DCHECK(address);
716 
717   SockaddrStorage storage;
718   if (getsockname(socket_, storage.addr, &storage.addr_len)) {
719     int os_error = WSAGetLastError();
720     return MapSystemError(os_error);
721   }
722   if (!address->FromSockAddr(storage.addr, storage.addr_len))
723     return ERR_ADDRESS_INVALID;
724 
725   return OK;
726 }
727 
GetPeerAddress(IPEndPoint * address) const728 int TCPSocketWin::GetPeerAddress(IPEndPoint* address) const {
729   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
730   DCHECK(address);
731   if (!IsConnected())
732     return ERR_SOCKET_NOT_CONNECTED;
733   *address = *peer_address_;
734   return OK;
735 }
736 
SetDefaultOptionsForServer()737 int TCPSocketWin::SetDefaultOptionsForServer() {
738   return SetExclusiveAddrUse();
739 }
740 
SetDefaultOptionsForClient()741 void TCPSocketWin::SetDefaultOptionsForClient() {
742   SetTCPNoDelay(socket_, /*no_delay=*/true);
743   SetTCPKeepAlive(socket_, true, kTCPKeepAliveSeconds);
744 }
745 
SetExclusiveAddrUse()746 int TCPSocketWin::SetExclusiveAddrUse() {
747   // On Windows, a bound end point can be hijacked by another process by
748   // setting SO_REUSEADDR. Therefore a Windows-only option SO_EXCLUSIVEADDRUSE
749   // was introduced in Windows NT 4.0 SP4. If the socket that is bound to the
750   // end point has SO_EXCLUSIVEADDRUSE enabled, it is not possible for another
751   // socket to forcibly bind to the end point until the end point is unbound.
752   // It is recommend that all server applications must use SO_EXCLUSIVEADDRUSE.
753   // MSDN: http://goo.gl/M6fjQ.
754   //
755   // Unlike on *nix, on Windows a TCP server socket can always bind to an end
756   // point in TIME_WAIT state without setting SO_REUSEADDR, therefore it is not
757   // needed here.
758   //
759   // SO_EXCLUSIVEADDRUSE will prevent a TCP client socket from binding to an end
760   // point in TIME_WAIT status. It does not have this effect for a TCP server
761   // socket.
762 
763   BOOL true_value = 1;
764   int rv = setsockopt(socket_, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
765                       reinterpret_cast<const char*>(&true_value),
766                       sizeof(true_value));
767   if (rv < 0)
768     return MapSystemError(errno);
769   return OK;
770 }
771 
SetReceiveBufferSize(int32_t size)772 int TCPSocketWin::SetReceiveBufferSize(int32_t size) {
773   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
774   return SetSocketReceiveBufferSize(socket_, size);
775 }
776 
SetSendBufferSize(int32_t size)777 int TCPSocketWin::SetSendBufferSize(int32_t size) {
778   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
779   return SetSocketSendBufferSize(socket_, size);
780 }
781 
SetKeepAlive(bool enable,int delay)782 bool TCPSocketWin::SetKeepAlive(bool enable, int delay) {
783   if (socket_ == INVALID_SOCKET)
784     return false;
785 
786   return SetTCPKeepAlive(socket_, enable, delay);
787 }
788 
SetNoDelay(bool no_delay)789 bool TCPSocketWin::SetNoDelay(bool no_delay) {
790   if (socket_ == INVALID_SOCKET)
791     return false;
792 
793   return SetTCPNoDelay(socket_, no_delay) == OK;
794 }
795 
SetIPv6Only(bool ipv6_only)796 int TCPSocketWin::SetIPv6Only(bool ipv6_only) {
797   return ::net::SetIPv6Only(socket_, ipv6_only);
798 }
799 
Close()800 void TCPSocketWin::Close() {
801   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
802 
803   if (socket_ != INVALID_SOCKET) {
804     // Only log the close event if there's actually a socket to close.
805     net_log_.AddEvent(NetLogEventType::SOCKET_CLOSED);
806 
807     // Note: don't use CancelIo to cancel pending IO because it doesn't work
808     // when there is a Winsock layered service provider.
809 
810     // In most socket implementations, closing a socket results in a graceful
811     // connection shutdown, but in Winsock we have to call shutdown explicitly.
812     // See the MSDN page "Graceful Shutdown, Linger Options, and Socket Closure"
813     // at http://msdn.microsoft.com/en-us/library/ms738547.aspx
814     shutdown(socket_, SD_SEND);
815 
816     // This cancels any pending IO.
817     if (closesocket(socket_) < 0)
818       PLOG(ERROR) << "closesocket";
819     socket_ = INVALID_SOCKET;
820   }
821 
822   if (!accept_callback_.is_null()) {
823     accept_watcher_.StopWatching();
824     accept_socket_ = nullptr;
825     accept_address_ = nullptr;
826     accept_callback_.Reset();
827   }
828 
829   if (accept_event_) {
830     WSACloseEvent(accept_event_);
831     accept_event_ = WSA_INVALID_EVENT;
832   }
833 
834   if (core_.get()) {
835     core_->Detach();
836     core_ = nullptr;
837 
838     // |core_| may still exist and own a reference to itself, if there's a
839     // pending write. It has to stay alive until the operation completes, even
840     // when the socket is closed. This is not the case for reads.
841   }
842 
843   connect_callback_.Reset();
844   OnClosed();
845 
846   peer_address_.reset();
847   connect_os_error_ = 0;
848 }
849 
DetachFromThread()850 void TCPSocketWin::DetachFromThread() {
851   DETACH_FROM_THREAD(thread_checker_);
852 }
853 
StartLoggingMultipleConnectAttempts(const AddressList & addresses)854 void TCPSocketWin::StartLoggingMultipleConnectAttempts(
855     const AddressList& addresses) {
856   if (!logging_multiple_connect_attempts_) {
857     logging_multiple_connect_attempts_ = true;
858     LogConnectBegin(addresses);
859   } else {
860     NOTREACHED();
861   }
862 }
863 
EndLoggingMultipleConnectAttempts(int net_error)864 void TCPSocketWin::EndLoggingMultipleConnectAttempts(int net_error) {
865   if (logging_multiple_connect_attempts_) {
866     LogConnectEnd(net_error);
867     logging_multiple_connect_attempts_ = false;
868   } else {
869     NOTREACHED();
870   }
871 }
872 
ReleaseSocketDescriptorForTesting()873 SocketDescriptor TCPSocketWin::ReleaseSocketDescriptorForTesting() {
874   CHECK(!registered_as_io_handler_);
875 
876   SocketDescriptor socket_descriptor = socket_;
877   socket_ = INVALID_SOCKET;
878   Close();
879   return socket_descriptor;
880 }
881 
SocketDescriptorForTesting() const882 SocketDescriptor TCPSocketWin::SocketDescriptorForTesting() const {
883   return socket_;
884 }
885 
CloseSocketDescriptorForTesting()886 void TCPSocketWin::CloseSocketDescriptorForTesting() {
887   CHECK_NE(socket_, INVALID_SOCKET);
888   CHECK_EQ(closesocket(socket_), 0);
889   // Clear `socket_` so that `Close()` doesn't attempt to close it again.
890   socket_ = INVALID_SOCKET;
891 }
892 
AcceptInternal(std::unique_ptr<TCPSocketWin> * socket,IPEndPoint * address)893 int TCPSocketWin::AcceptInternal(std::unique_ptr<TCPSocketWin>* socket,
894                                  IPEndPoint* address) {
895   SockaddrStorage storage;
896   int new_socket = accept(socket_, storage.addr, &storage.addr_len);
897   int os_error = WSAGetLastError();
898   if (new_socket < 0) {
899     int net_error = MapSystemError(os_error);
900     if (net_error != ERR_IO_PENDING)
901       net_log_.EndEventWithNetErrorCode(NetLogEventType::TCP_ACCEPT, net_error);
902     return net_error;
903   }
904 
905   IPEndPoint ip_end_point;
906   if (!ip_end_point.FromSockAddr(storage.addr, storage.addr_len)) {
907     NOTREACHED();
908   }
909   auto tcp_socket =
910       TCPSocketWin::Create(nullptr, net_log_.net_log(), net_log_.source());
911   int adopt_result = tcp_socket->AdoptConnectedSocket(new_socket, ip_end_point);
912   if (adopt_result != OK) {
913     net_log_.EndEventWithNetErrorCode(NetLogEventType::TCP_ACCEPT,
914                                       adopt_result);
915     return adopt_result;
916   }
917   *socket = std::move(tcp_socket);
918   *address = ip_end_point;
919   net_log_.EndEvent(NetLogEventType::TCP_ACCEPT, [&] {
920     return CreateNetLogIPEndPointParams(&ip_end_point);
921   });
922   return OK;
923 }
924 
OnObjectSignaled(HANDLE object)925 void TCPSocketWin::OnObjectSignaled(HANDLE object) {
926   WSANETWORKEVENTS ev;
927   if (WSAEnumNetworkEvents(socket_, accept_event_, &ev) == SOCKET_ERROR) {
928     PLOG(ERROR) << "WSAEnumNetworkEvents()";
929     return;
930   }
931 
932   if (ev.lNetworkEvents & FD_ACCEPT) {
933     int result = AcceptInternal(accept_socket_, accept_address_);
934     if (result != ERR_IO_PENDING) {
935       accept_socket_ = nullptr;
936       accept_address_ = nullptr;
937       std::move(accept_callback_).Run(result);
938     }
939   } else {
940     // This happens when a client opens a connection and closes it before we
941     // have a chance to accept it.
942     DCHECK(ev.lNetworkEvents == 0);
943 
944     // Start watching the next FD_ACCEPT event.
945     WSAEventSelect(socket_, accept_event_, FD_ACCEPT);
946     accept_watcher_.StartWatchingOnce(accept_event_, this);
947   }
948 }
949 
DoConnect()950 int TCPSocketWin::DoConnect() {
951   DCHECK_EQ(connect_os_error_, 0);
952   DCHECK(!core_.get());
953 
954   net_log_.BeginEvent(NetLogEventType::TCP_CONNECT_ATTEMPT, [&] {
955     return CreateNetLogIPEndPointParams(peer_address_.get());
956   });
957 
958   core_ = CreateCore();
959 
960   // WSAEventSelect sets the socket to non-blocking mode as a side effect.
961   // Our connect() and recv() calls require that the socket be non-blocking.
962   WSAEventSelect(socket_, core_->GetConnectEvent(), FD_CONNECT);
963 
964   SockaddrStorage storage;
965   if (!peer_address_->ToSockAddr(storage.addr, &storage.addr_len))
966     return ERR_ADDRESS_INVALID;
967 
968   // Set option to choose a random port, if the socket is not already bound.
969   // Ignore failures, which may happen if the socket was already bound.
970   if (base::win::GetVersion() >= base::win::Version::WIN10_20H1 &&
971       base::FeatureList::IsEnabled(features::kEnableTcpPortRandomization)) {
972     BOOL randomize_port = TRUE;
973     setsockopt(socket_, SOL_SOCKET, SO_RANDOMIZE_PORT,
974                reinterpret_cast<const char*>(&randomize_port),
975                sizeof(randomize_port));
976   }
977 
978   if (!connect(socket_, storage.addr, storage.addr_len)) {
979     // Connected without waiting!
980     //
981     // The MSDN page for connect says:
982     //   With a nonblocking socket, the connection attempt cannot be completed
983     //   immediately. In this case, connect will return SOCKET_ERROR, and
984     //   WSAGetLastError will return WSAEWOULDBLOCK.
985     // which implies that for a nonblocking socket, connect never returns 0.
986     // It's not documented whether the event object will be signaled or not
987     // if connect does return 0.
988     NOTREACHED();
989   } else {
990     int os_error = WSAGetLastError();
991     if (os_error != WSAEWOULDBLOCK) {
992       LOG(ERROR) << "connect failed: " << os_error;
993       connect_os_error_ = os_error;
994       int rv = MapConnectError(os_error);
995       CHECK_NE(ERR_IO_PENDING, rv);
996       return rv;
997     }
998   }
999 
1000   core_->WatchForConnect();
1001   return ERR_IO_PENDING;
1002 }
1003 
DoConnectComplete(int result)1004 void TCPSocketWin::DoConnectComplete(int result) {
1005   // Log the end of this attempt (and any OS error it threw).
1006   int os_error = connect_os_error_;
1007   connect_os_error_ = 0;
1008   if (result != OK) {
1009     net_log_.EndEventWithIntParams(NetLogEventType::TCP_CONNECT_ATTEMPT,
1010                                    "os_error", os_error);
1011   } else {
1012     net_log_.EndEvent(NetLogEventType::TCP_CONNECT_ATTEMPT);
1013   }
1014 
1015   if (!logging_multiple_connect_attempts_)
1016     LogConnectEnd(result);
1017 }
1018 
LogConnectBegin(const AddressList & addresses)1019 void TCPSocketWin::LogConnectBegin(const AddressList& addresses) {
1020   net_log_.BeginEvent(NetLogEventType::TCP_CONNECT,
1021                       [&] { return addresses.NetLogParams(); });
1022 }
1023 
LogConnectEnd(int net_error)1024 void TCPSocketWin::LogConnectEnd(int net_error) {
1025   if (net_error != OK) {
1026     net_log_.EndEventWithNetErrorCode(NetLogEventType::TCP_CONNECT, net_error);
1027     return;
1028   }
1029 
1030   net_log_.EndEvent(NetLogEventType::TCP_CONNECT, [&] {
1031     net::IPEndPoint local_address;
1032     int net_error = GetLocalAddress(&local_address);
1033     net::IPEndPoint remote_address;
1034     if (net_error == net::OK)
1035       net_error = GetPeerAddress(&remote_address);
1036     if (net_error != net::OK)
1037       return NetLogParamsWithInt("get_address_net_error", net_error);
1038     return CreateNetLogAddressPairParams(local_address, remote_address);
1039   });
1040 }
1041 
RetryRead(int rv)1042 void TCPSocketDefaultWin::RetryRead(int rv) {
1043   CoreImpl& core = GetCoreImpl();
1044   DCHECK(core.read_iobuffer_);
1045 
1046   if (rv == OK) {
1047     // base::Unretained() is safe because RetryRead() won't be called when
1048     // |this| is gone.
1049     rv = ReadIfReady(core.read_iobuffer_.get(), core.read_buffer_length_,
1050                      base::BindOnce(&TCPSocketDefaultWin::RetryRead,
1051                                     base::Unretained(this)));
1052     if (rv == ERR_IO_PENDING)
1053       return;
1054   }
1055   core.read_iobuffer_ = nullptr;
1056   core.read_buffer_length_ = 0;
1057   std::move(read_callback_).Run(rv);
1058 }
1059 
DidCompleteConnect()1060 void TCPSocketWin::DidCompleteConnect() {
1061   DCHECK(connect_callback_);
1062   int result;
1063 
1064   WSANETWORKEVENTS events;
1065   int rv = WSAEnumNetworkEvents(socket_, core_->GetConnectEvent(), &events);
1066   int os_error = WSAGetLastError();
1067   if (rv == SOCKET_ERROR) {
1068     DLOG(FATAL)
1069         << "WSAEnumNetworkEvents() failed with SOCKET_ERROR, os_error = "
1070         << os_error;
1071     result = MapSystemError(os_error);
1072   } else if (events.lNetworkEvents & FD_CONNECT) {
1073     os_error = events.iErrorCode[FD_CONNECT_BIT];
1074     result = MapConnectError(os_error);
1075   } else {
1076     DLOG(FATAL) << "WSAEnumNetworkEvents() failed, rv = " << rv;
1077     result = ERR_UNEXPECTED;
1078   }
1079 
1080   connect_os_error_ = os_error;
1081   DoConnectComplete(result);
1082 
1083   DCHECK_NE(result, ERR_IO_PENDING);
1084   std::move(connect_callback_).Run(result);
1085 }
1086 
DidCompleteWrite()1087 void TCPSocketDefaultWin::DidCompleteWrite() {
1088   DCHECK(!write_callback_.is_null());
1089 
1090   CoreImpl& core = GetCoreImpl();
1091   DWORD num_bytes, flags;
1092   BOOL ok = WSAGetOverlappedResult(socket_, &core.write_overlapped_, &num_bytes,
1093                                    FALSE, &flags);
1094   int os_error = WSAGetLastError();
1095   WSAResetEvent(core.write_overlapped_.hEvent);
1096   int rv;
1097   if (!ok) {
1098     rv = MapSystemError(os_error);
1099     NetLogSocketError(net_log_, NetLogEventType::SOCKET_WRITE_ERROR, rv,
1100                       os_error);
1101   } else {
1102     rv = static_cast<int>(num_bytes);
1103     if (rv > core.write_buffer_length_ || rv < 0) {
1104       // It seems that some winsock interceptors report that more was written
1105       // than was available. Treat this as an error.  http://crbug.com/27870
1106       LOG(ERROR) << "Detected broken LSP: Asked to write "
1107                  << core.write_buffer_length_ << " bytes, but " << rv
1108                  << " bytes reported.";
1109       rv = ERR_WINSOCK_UNEXPECTED_WRITTEN_BYTES;
1110     } else {
1111       net_log_.AddByteTransferEvent(NetLogEventType::SOCKET_BYTES_SENT,
1112                                     num_bytes, core.write_iobuffer_->data());
1113     }
1114   }
1115 
1116   core.write_iobuffer_ = nullptr;
1117 
1118   DCHECK_NE(rv, ERR_IO_PENDING);
1119   std::move(write_callback_).Run(rv);
1120 }
1121 
DidSignalRead()1122 void TCPSocketDefaultWin::DidSignalRead() {
1123   DCHECK(!read_if_ready_callback_.is_null());
1124 
1125   CoreImpl& core = GetCoreImpl();
1126   int os_error = 0;
1127   WSANETWORKEVENTS network_events;
1128   int rv = WSAEnumNetworkEvents(socket_, core.read_event_, &network_events);
1129   os_error = WSAGetLastError();
1130 
1131   if (rv == SOCKET_ERROR) {
1132     rv = MapSystemError(os_error);
1133   } else if (network_events.lNetworkEvents) {
1134     DCHECK_EQ(network_events.lNetworkEvents & ~(FD_READ | FD_CLOSE), 0);
1135     // If network_events.lNetworkEvents is FD_CLOSE and
1136     // network_events.iErrorCode[FD_CLOSE_BIT] is 0, it is a graceful
1137     // connection closure. It is tempting to directly set rv to 0 in
1138     // this case, but the MSDN pages for WSAEventSelect and
1139     // WSAAsyncSelect recommend we still call RetryRead():
1140     //   FD_CLOSE should only be posted after all data is read from a
1141     //   socket, but an application should check for remaining data upon
1142     //   receipt of FD_CLOSE to avoid any possibility of losing data.
1143     //
1144     // If network_events.iErrorCode[FD_READ_BIT] or
1145     // network_events.iErrorCode[FD_CLOSE_BIT] is nonzero, still call
1146     // RetryRead() because recv() reports a more accurate error code
1147     // (WSAECONNRESET vs. WSAECONNABORTED) when the connection was
1148     // reset.
1149     rv = OK;
1150   } else {
1151     // This may happen because Read() may succeed synchronously and
1152     // consume all the received data without resetting the event object.
1153     core.WatchForRead();
1154     return;
1155   }
1156 
1157   DCHECK_NE(rv, ERR_IO_PENDING);
1158   std::move(read_if_ready_callback_).Run(rv);
1159 }
1160 
GetEstimatedRoundTripTime(base::TimeDelta * out_rtt) const1161 bool TCPSocketWin::GetEstimatedRoundTripTime(base::TimeDelta* out_rtt) const {
1162   DCHECK(out_rtt);
1163   // TODO(bmcquade): Consider implementing using
1164   // GetPerTcpConnectionEStats/GetPerTcp6ConnectionEStats.
1165   return false;
1166 }
1167 
ApplySocketTag(const SocketTag & tag)1168 void TCPSocketWin::ApplySocketTag(const SocketTag& tag) {
1169   // Windows does not support any specific SocketTags so fail if any non-default
1170   // tag is applied.
1171   CHECK(tag == SocketTag());
1172 }
1173 
BindToNetwork(handles::NetworkHandle network)1174 int TCPSocketWin::BindToNetwork(handles::NetworkHandle network) {
1175   NOTIMPLEMENTED();
1176   return ERR_NOT_IMPLEMENTED;
1177 }
1178 
TCPSocketDefaultWin(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLog * net_log,const NetLogSource & source)1179 TCPSocketDefaultWin::TCPSocketDefaultWin(
1180     std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
1181     NetLog* net_log,
1182     const NetLogSource& source)
1183     : TCPSocketWin(std::move(socket_performance_watcher), net_log, source) {}
1184 
TCPSocketDefaultWin(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLogWithSource net_log_source)1185 TCPSocketDefaultWin::TCPSocketDefaultWin(
1186     std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
1187     NetLogWithSource net_log_source)
1188     : TCPSocketWin(std::move(socket_performance_watcher),
1189                    std::move(net_log_source)) {}
1190 
~TCPSocketDefaultWin()1191 TCPSocketDefaultWin::~TCPSocketDefaultWin() {
1192   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
1193   Close();
1194 }
1195 
GetCoreImpl()1196 TCPSocketDefaultWin::CoreImpl& TCPSocketDefaultWin::GetCoreImpl() {
1197   return CHECK_DEREF(static_cast<CoreImpl*>(core_.get()));
1198 }
1199 
CreateCore()1200 scoped_refptr<TCPSocketWin::Core> TCPSocketDefaultWin::CreateCore() {
1201   return base::MakeRefCounted<CoreImpl>(this);
1202 }
1203 
HasPendingRead() const1204 bool TCPSocketDefaultWin::HasPendingRead() const {
1205   CHECK(!read_callback_ || read_if_ready_callback_);
1206   return !read_if_ready_callback_.is_null();
1207 }
1208 
OnClosed()1209 void TCPSocketDefaultWin::OnClosed() {
1210   read_callback_.Reset();
1211   read_if_ready_callback_.Reset();
1212   write_callback_.Reset();
1213 }
1214 
1215 }  // namespace net
1216