1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/socket/tcp_client_socket_win.h"
9 #include "base/basictypes.h"
10 #include "base/compiler_specific.h"
11 #include "base/metrics/stats_counters.h"
12 #include "base/strings/string_util.h"
13 #include "base/win/object_watcher.h"
14 #include "base/win/windows_version.h"
15 #include "net/base/connection_type_histograms.h"
16 #include "net/base/io_buffer.h"
17 #include "net/base/ip_endpoint.h"
18 #include "net/base/net_errors.h"
19 #include "net/base/net_log.h"
20 #include "net/base/net_util.h"
21 #include "net/base/network_change_notifier.h"
22 #include "net/base/winsock_init.h"
23 #include "net/base/winsock_util.h"
24 #include "net/socket/socket_descriptor.h"
25 #include "net/socket/socket_net_log_params.h"
31 const int kTCPKeepAliveSeconds
= 45;
32 bool g_disable_overlapped_reads
= false;
34 bool SetSocketReceiveBufferSize(SOCKET socket
, int32 size
) {
35 int rv
= setsockopt(socket
, SOL_SOCKET
, SO_RCVBUF
,
36 reinterpret_cast<const char*>(&size
), sizeof(size
));
37 DCHECK(!rv
) << "Could not set socket receive buffer size: " << GetLastError();
41 bool SetSocketSendBufferSize(SOCKET socket
, int32 size
) {
42 int rv
= setsockopt(socket
, SOL_SOCKET
, SO_SNDBUF
,
43 reinterpret_cast<const char*>(&size
), sizeof(size
));
44 DCHECK(!rv
) << "Could not set socket send buffer size: " << GetLastError();
49 // The Nagle implementation on windows is governed by RFC 896. The idea
50 // behind Nagle is to reduce small packets on the network. When Nagle is
51 // enabled, if a partial packet has been sent, the TCP stack will disallow
52 // further *partial* packets until an ACK has been received from the other
53 // side. Good applications should always strive to send as much data as
54 // possible and avoid partial-packet sends. However, in most real world
55 // applications, there are edge cases where this does not happen, and two
56 // partial packets may be sent back to back. For a browser, it is NEVER
57 // a benefit to delay for an RTT before the second packet is sent.
59 // As a practical example in Chromium today, consider the case of a small
60 // POST. I have verified this:
61 // Client writes 649 bytes of header (partial packet #1)
62 // Client writes 50 bytes of POST data (partial packet #2)
63 // In the above example, with Nagle, a RTT delay is inserted between these
64 // two sends due to nagle. RTTs can easily be 100ms or more. The best
65 // fix is to make sure that for POSTing data, we write as much data as
66 // possible and minimize partial packets. We will fix that. But disabling
67 // Nagle also ensure we don't run into this delay in other edge cases.
69 // http://technet.microsoft.com/en-us/library/bb726981.aspx
70 bool DisableNagle(SOCKET socket
, bool disable
) {
71 BOOL val
= disable
? TRUE
: FALSE
;
72 int rv
= setsockopt(socket
, IPPROTO_TCP
, TCP_NODELAY
,
73 reinterpret_cast<const char*>(&val
),
75 DCHECK(!rv
) << "Could not disable nagle";
79 // Enable TCP Keep-Alive to prevent NAT routers from timing out TCP
80 // connections. See http://crbug.com/27400 for details.
81 bool SetTCPKeepAlive(SOCKET socket
, BOOL enable
, int delay_secs
) {
82 int delay
= delay_secs
* 1000;
83 struct tcp_keepalive keepalive_vals
= {
84 enable
? 1 : 0, // TCP keep-alive on.
85 delay
, // Delay seconds before sending first TCP keep-alive packet.
86 delay
, // Delay seconds between sending TCP keep-alive packets.
88 DWORD bytes_returned
= 0xABAB;
89 int rv
= WSAIoctl(socket
, SIO_KEEPALIVE_VALS
, &keepalive_vals
,
90 sizeof(keepalive_vals
), NULL
, 0,
91 &bytes_returned
, NULL
, NULL
);
92 DCHECK(!rv
) << "Could not enable TCP Keep-Alive for socket: " << socket
93 << " [error: " << WSAGetLastError() << "].";
95 // Disregard any failure in disabling nagle or enabling TCP Keep-Alive.
99 // Sets socket parameters. Returns the OS error code (or 0 on
101 int SetupSocket(SOCKET socket
) {
102 // Increase the socket buffer sizes from the default sizes for WinXP. In
103 // performance testing, there is substantial benefit by increasing from 8KB
106 // http://support.microsoft.com/kb/823764/EN-US
107 // On Vista, if we manually set these sizes, Vista turns off its receive
108 // window auto-tuning feature.
109 // http://blogs.msdn.com/wndp/archive/2006/05/05/Winhec-blog-tcpip-2.aspx
110 // Since Vista's auto-tune is better than any static value we can could set,
111 // only change these on pre-vista machines.
112 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
113 const int32 kSocketBufferSize
= 64 * 1024;
114 SetSocketReceiveBufferSize(socket
, kSocketBufferSize
);
115 SetSocketSendBufferSize(socket
, kSocketBufferSize
);
118 DisableNagle(socket
, true);
119 SetTCPKeepAlive(socket
, true, kTCPKeepAliveSeconds
);
123 // Creates a new socket and sets default parameters for it. Returns
124 // the OS error code (or 0 on success).
125 int CreateSocket(int family
, SOCKET
* socket
) {
126 *socket
= CreatePlatformSocket(family
, SOCK_STREAM
, IPPROTO_TCP
);
127 if (*socket
== INVALID_SOCKET
) {
128 int os_error
= WSAGetLastError();
129 LOG(ERROR
) << "CreatePlatformSocket failed: " << os_error
;
132 int error
= SetupSocket(*socket
);
134 if (closesocket(*socket
) < 0)
135 PLOG(ERROR
) << "closesocket";
136 *socket
= INVALID_SOCKET
;
142 int MapConnectError(int os_error
) {
144 // connect fails with WSAEACCES when Windows Firewall blocks the
147 return ERR_NETWORK_ACCESS_DENIED
;
149 return ERR_CONNECTION_TIMED_OUT
;
151 int net_error
= MapSystemError(os_error
);
152 if (net_error
== ERR_FAILED
)
153 return ERR_CONNECTION_FAILED
; // More specific than ERR_FAILED.
155 // Give a more specific error when the user is offline.
156 if (net_error
== ERR_ADDRESS_UNREACHABLE
&&
157 NetworkChangeNotifier::IsOffline()) {
158 return ERR_INTERNET_DISCONNECTED
;
168 //-----------------------------------------------------------------------------
170 // This class encapsulates all the state that has to be preserved as long as
171 // there is a network IO operation in progress. If the owner TCPClientSocketWin
172 // is destroyed while an operation is in progress, the Core is detached and it
173 // lives until the operation completes and the OS doesn't reference any resource
174 // declared on this class anymore.
175 class TCPClientSocketWin::Core
: public base::RefCounted
<Core
> {
177 explicit Core(TCPClientSocketWin
* socket
);
179 // Start watching for the end of a read or write operation.
181 void WatchForWrite();
183 // The TCPClientSocketWin is going away.
184 void Detach() { socket_
= NULL
; }
186 // The separate OVERLAPPED variables for asynchronous operation.
187 // |read_overlapped_| is used for both Connect() and Read().
188 // |write_overlapped_| is only used for Write();
189 OVERLAPPED read_overlapped_
;
190 OVERLAPPED write_overlapped_
;
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_
;
196 int write_buffer_length_
;
198 bool non_blocking_reads_initialized_
;
201 friend class base::RefCounted
<Core
>;
203 class ReadDelegate
: public base::win::ObjectWatcher::Delegate
{
205 explicit ReadDelegate(Core
* core
) : core_(core
) {}
206 virtual ~ReadDelegate() {}
208 // base::ObjectWatcher::Delegate methods:
209 virtual void OnObjectSignaled(HANDLE object
);
215 class WriteDelegate
: public base::win::ObjectWatcher::Delegate
{
217 explicit WriteDelegate(Core
* core
) : core_(core
) {}
218 virtual ~WriteDelegate() {}
220 // base::ObjectWatcher::Delegate methods:
221 virtual void OnObjectSignaled(HANDLE object
);
229 // The socket that created this object.
230 TCPClientSocketWin
* socket_
;
232 // |reader_| handles the signals from |read_watcher_|.
233 ReadDelegate reader_
;
234 // |writer_| handles the signals from |write_watcher_|.
235 WriteDelegate writer_
;
237 // |read_watcher_| watches for events from Connect() and Read().
238 base::win::ObjectWatcher read_watcher_
;
239 // |write_watcher_| watches for events from Write();
240 base::win::ObjectWatcher write_watcher_
;
242 DISALLOW_COPY_AND_ASSIGN(Core
);
245 TCPClientSocketWin::Core::Core(
246 TCPClientSocketWin
* socket
)
247 : read_buffer_length_(0),
248 write_buffer_length_(0),
249 non_blocking_reads_initialized_(false),
253 memset(&read_overlapped_
, 0, sizeof(read_overlapped_
));
254 memset(&write_overlapped_
, 0, sizeof(write_overlapped_
));
256 read_overlapped_
.hEvent
= WSACreateEvent();
257 write_overlapped_
.hEvent
= WSACreateEvent();
260 TCPClientSocketWin::Core::~Core() {
261 // Make sure the message loop is not watching this object anymore.
262 read_watcher_
.StopWatching();
263 write_watcher_
.StopWatching();
265 WSACloseEvent(read_overlapped_
.hEvent
);
266 memset(&read_overlapped_
, 0xaf, sizeof(read_overlapped_
));
267 WSACloseEvent(write_overlapped_
.hEvent
);
268 memset(&write_overlapped_
, 0xaf, sizeof(write_overlapped_
));
271 void TCPClientSocketWin::Core::WatchForRead() {
272 // We grab an extra reference because there is an IO operation in progress.
273 // Balanced in ReadDelegate::OnObjectSignaled().
275 read_watcher_
.StartWatching(read_overlapped_
.hEvent
, &reader_
);
278 void TCPClientSocketWin::Core::WatchForWrite() {
279 // We grab an extra reference because there is an IO operation in progress.
280 // Balanced in WriteDelegate::OnObjectSignaled().
282 write_watcher_
.StartWatching(write_overlapped_
.hEvent
, &writer_
);
285 void TCPClientSocketWin::Core::ReadDelegate::OnObjectSignaled(
287 DCHECK_EQ(object
, core_
->read_overlapped_
.hEvent
);
288 if (core_
->socket_
) {
289 if (core_
->socket_
->waiting_connect())
290 core_
->socket_
->DidCompleteConnect();
292 core_
->socket_
->DidSignalRead();
298 void TCPClientSocketWin::Core::WriteDelegate::OnObjectSignaled(
300 DCHECK_EQ(object
, core_
->write_overlapped_
.hEvent
);
302 core_
->socket_
->DidCompleteWrite();
307 //-----------------------------------------------------------------------------
309 TCPClientSocketWin::TCPClientSocketWin(const AddressList
& addresses
,
310 net::NetLog
* net_log
,
311 const net::NetLog::Source
& source
)
312 : socket_(INVALID_SOCKET
),
313 bound_socket_(INVALID_SOCKET
),
314 addresses_(addresses
),
315 current_address_index_(-1),
316 waiting_read_(false),
317 waiting_write_(false),
318 next_connect_state_(CONNECT_STATE_NONE
),
319 connect_os_error_(0),
320 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_SOCKET
)),
321 previously_disconnected_(false) {
322 net_log_
.BeginEvent(NetLog::TYPE_SOCKET_ALIVE
,
323 source
.ToEventParametersCallback());
327 TCPClientSocketWin::~TCPClientSocketWin() {
329 net_log_
.EndEvent(NetLog::TYPE_SOCKET_ALIVE
);
332 int TCPClientSocketWin::AdoptSocket(SOCKET socket
) {
333 DCHECK_EQ(socket_
, INVALID_SOCKET
);
335 int error
= SetupSocket(socket
);
337 return MapSystemError(error
);
340 SetNonBlocking(socket_
);
342 core_
= new Core(this);
343 current_address_index_
= 0;
344 use_history_
.set_was_ever_connected();
349 int TCPClientSocketWin::Bind(const IPEndPoint
& address
) {
350 if (current_address_index_
>= 0 || bind_address_
.get()) {
351 // Cannot bind the socket if we are already connected or connecting.
352 return ERR_UNEXPECTED
;
355 SockaddrStorage storage
;
356 if (!address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
357 return ERR_INVALID_ARGUMENT
;
359 // Create |bound_socket_| and try to bind it to |address|.
360 int error
= CreateSocket(address
.GetSockAddrFamily(), &bound_socket_
);
362 return MapSystemError(error
);
364 if (bind(bound_socket_
, storage
.addr
, storage
.addr_len
)) {
366 if (closesocket(bound_socket_
) < 0)
367 PLOG(ERROR
) << "closesocket";
368 bound_socket_
= INVALID_SOCKET
;
369 return MapSystemError(error
);
372 bind_address_
.reset(new IPEndPoint(address
));
378 int TCPClientSocketWin::Connect(const CompletionCallback
& callback
) {
379 DCHECK(CalledOnValidThread());
381 // If already connected, then just return OK.
382 if (socket_
!= INVALID_SOCKET
)
385 base::StatsCounter
connects("tcp.connect");
386 connects
.Increment();
388 net_log_
.BeginEvent(NetLog::TYPE_TCP_CONNECT
,
389 addresses_
.CreateNetLogCallback());
391 // We will try to connect to each address in addresses_. Start with the
392 // first one in the list.
393 next_connect_state_
= CONNECT_STATE_CONNECT
;
394 current_address_index_
= 0;
396 int rv
= DoConnectLoop(OK
);
397 if (rv
== ERR_IO_PENDING
) {
398 // Synchronous operation not supported.
399 DCHECK(!callback
.is_null());
400 // TODO(ajwong): Is setting read_callback_ the right thing to do here??
401 read_callback_
= callback
;
403 LogConnectCompletion(rv
);
409 int TCPClientSocketWin::DoConnectLoop(int result
) {
410 DCHECK_NE(next_connect_state_
, CONNECT_STATE_NONE
);
414 ConnectState state
= next_connect_state_
;
415 next_connect_state_
= CONNECT_STATE_NONE
;
417 case CONNECT_STATE_CONNECT
:
421 case CONNECT_STATE_CONNECT_COMPLETE
:
422 rv
= DoConnectComplete(rv
);
425 LOG(DFATAL
) << "bad state " << state
;
429 } while (rv
!= ERR_IO_PENDING
&& next_connect_state_
!= CONNECT_STATE_NONE
);
434 int TCPClientSocketWin::DoConnect() {
435 DCHECK_GE(current_address_index_
, 0);
436 DCHECK_LT(current_address_index_
, static_cast<int>(addresses_
.size()));
437 DCHECK_EQ(0, connect_os_error_
);
439 const IPEndPoint
& endpoint
= addresses_
[current_address_index_
];
441 if (previously_disconnected_
) {
442 use_history_
.Reset();
443 previously_disconnected_
= false;
446 net_log_
.BeginEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT
,
447 CreateNetLogIPEndPointCallback(&endpoint
));
449 next_connect_state_
= CONNECT_STATE_CONNECT_COMPLETE
;
451 if (bound_socket_
!= INVALID_SOCKET
) {
452 DCHECK(bind_address_
.get());
453 socket_
= bound_socket_
;
454 bound_socket_
= INVALID_SOCKET
;
456 connect_os_error_
= CreateSocket(endpoint
.GetSockAddrFamily(), &socket_
);
457 if (connect_os_error_
!= 0)
458 return MapSystemError(connect_os_error_
);
460 if (bind_address_
.get()) {
461 SockaddrStorage storage
;
462 if (!bind_address_
->ToSockAddr(storage
.addr
, &storage
.addr_len
))
463 return ERR_INVALID_ARGUMENT
;
464 if (bind(socket_
, storage
.addr
, storage
.addr_len
))
465 return MapSystemError(errno
);
470 core_
= new Core(this);
471 // WSAEventSelect sets the socket to non-blocking mode as a side effect.
472 // Our connect() and recv() calls require that the socket be non-blocking.
473 WSAEventSelect(socket_
, core_
->read_overlapped_
.hEvent
, FD_CONNECT
);
475 SockaddrStorage storage
;
476 if (!endpoint
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
477 return ERR_INVALID_ARGUMENT
;
478 if (!connect(socket_
, storage
.addr
, storage
.addr_len
)) {
479 // Connected without waiting!
481 // The MSDN page for connect says:
482 // With a nonblocking socket, the connection attempt cannot be completed
483 // immediately. In this case, connect will return SOCKET_ERROR, and
484 // WSAGetLastError will return WSAEWOULDBLOCK.
485 // which implies that for a nonblocking socket, connect never returns 0.
486 // It's not documented whether the event object will be signaled or not
487 // if connect does return 0. So the code below is essentially dead code
488 // and we don't know if it's correct.
491 if (ResetEventIfSignaled(core_
->read_overlapped_
.hEvent
))
494 int os_error
= WSAGetLastError();
495 if (os_error
!= WSAEWOULDBLOCK
) {
496 LOG(ERROR
) << "connect failed: " << os_error
;
497 connect_os_error_
= os_error
;
498 return MapConnectError(os_error
);
502 core_
->WatchForRead();
503 return ERR_IO_PENDING
;
506 int TCPClientSocketWin::DoConnectComplete(int result
) {
507 // Log the end of this attempt (and any OS error it threw).
508 int os_error
= connect_os_error_
;
509 connect_os_error_
= 0;
511 net_log_
.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT
,
512 NetLog::IntegerCallback("os_error", os_error
));
514 net_log_
.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT
);
518 use_history_
.set_was_ever_connected();
522 // Close whatever partially connected socket we currently have.
525 // Try to fall back to the next address in the list.
526 if (current_address_index_
+ 1 < static_cast<int>(addresses_
.size())) {
527 next_connect_state_
= CONNECT_STATE_CONNECT
;
528 ++current_address_index_
;
532 // Otherwise there is nothing to fall back to, so give up.
536 void TCPClientSocketWin::Disconnect() {
537 DCHECK(CalledOnValidThread());
540 current_address_index_
= -1;
541 bind_address_
.reset();
544 void TCPClientSocketWin::DoDisconnect() {
545 DCHECK(CalledOnValidThread());
547 if (socket_
== INVALID_SOCKET
)
550 // Note: don't use CancelIo to cancel pending IO because it doesn't work
551 // when there is a Winsock layered service provider.
553 // In most socket implementations, closing a socket results in a graceful
554 // connection shutdown, but in Winsock we have to call shutdown explicitly.
555 // See the MSDN page "Graceful Shutdown, Linger Options, and Socket Closure"
556 // at http://msdn.microsoft.com/en-us/library/ms738547.aspx
557 shutdown(socket_
, SD_SEND
);
559 // This cancels any pending IO.
560 closesocket(socket_
);
561 socket_
= INVALID_SOCKET
;
563 if (waiting_connect()) {
564 // We closed the socket, so this notification will never come.
565 // From MSDN' WSAEventSelect documentation:
566 // "Closing a socket with closesocket also cancels the association and
567 // selection of network events specified in WSAEventSelect for the socket".
571 waiting_read_
= false;
572 waiting_write_
= false;
577 previously_disconnected_
= true;
580 bool TCPClientSocketWin::IsConnected() const {
581 DCHECK(CalledOnValidThread());
583 if (socket_
== INVALID_SOCKET
|| waiting_connect())
589 // Check if connection is alive.
591 int rv
= recv(socket_
, &c
, 1, MSG_PEEK
);
594 if (rv
== SOCKET_ERROR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
600 bool TCPClientSocketWin::IsConnectedAndIdle() const {
601 DCHECK(CalledOnValidThread());
603 if (socket_
== INVALID_SOCKET
|| waiting_connect())
609 // Check if connection is alive and we haven't received any data
612 int rv
= recv(socket_
, &c
, 1, MSG_PEEK
);
615 if (WSAGetLastError() != WSAEWOULDBLOCK
)
621 int TCPClientSocketWin::GetPeerAddress(IPEndPoint
* address
) const {
622 DCHECK(CalledOnValidThread());
625 return ERR_SOCKET_NOT_CONNECTED
;
626 *address
= addresses_
[current_address_index_
];
630 int TCPClientSocketWin::GetLocalAddress(IPEndPoint
* address
) const {
631 DCHECK(CalledOnValidThread());
633 if (socket_
== INVALID_SOCKET
) {
634 if (bind_address_
.get()) {
635 *address
= *bind_address_
;
638 return ERR_SOCKET_NOT_CONNECTED
;
641 struct sockaddr_storage addr_storage
;
642 socklen_t addr_len
= sizeof(addr_storage
);
643 struct sockaddr
* addr
= reinterpret_cast<struct sockaddr
*>(&addr_storage
);
644 if (getsockname(socket_
, addr
, &addr_len
))
645 return MapSystemError(WSAGetLastError());
646 if (!address
->FromSockAddr(addr
, addr_len
))
651 void TCPClientSocketWin::SetSubresourceSpeculation() {
652 use_history_
.set_subresource_speculation();
655 void TCPClientSocketWin::SetOmniboxSpeculation() {
656 use_history_
.set_omnibox_speculation();
659 bool TCPClientSocketWin::WasEverUsed() const {
660 return use_history_
.was_used_to_convey_data();
663 bool TCPClientSocketWin::UsingTCPFastOpen() const {
664 // Not supported on windows.
668 bool TCPClientSocketWin::WasNpnNegotiated() const {
672 NextProto
TCPClientSocketWin::GetNegotiatedProtocol() const {
673 return kProtoUnknown
;
676 bool TCPClientSocketWin::GetSSLInfo(SSLInfo
* ssl_info
) {
680 int TCPClientSocketWin::Read(IOBuffer
* buf
,
682 const CompletionCallback
& callback
) {
683 DCHECK(CalledOnValidThread());
684 DCHECK_NE(socket_
, INVALID_SOCKET
);
685 DCHECK(!waiting_read_
);
686 DCHECK(read_callback_
.is_null());
687 DCHECK(!core_
->read_iobuffer_
);
689 return DoRead(buf
, buf_len
, callback
);
692 int TCPClientSocketWin::Write(IOBuffer
* buf
,
694 const CompletionCallback
& callback
) {
695 DCHECK(CalledOnValidThread());
696 DCHECK_NE(socket_
, INVALID_SOCKET
);
697 DCHECK(!waiting_write_
);
698 DCHECK(write_callback_
.is_null());
699 DCHECK_GT(buf_len
, 0);
700 DCHECK(!core_
->write_iobuffer_
);
702 base::StatsCounter
writes("tcp.writes");
706 write_buffer
.len
= buf_len
;
707 write_buffer
.buf
= buf
->data();
709 // TODO(wtc): Remove the assertion after enough testing.
710 AssertEventNotSignaled(core_
->write_overlapped_
.hEvent
);
712 int rv
= WSASend(socket_
, &write_buffer
, 1, &num
, 0,
713 &core_
->write_overlapped_
, NULL
);
715 if (ResetEventIfSignaled(core_
->write_overlapped_
.hEvent
)) {
716 rv
= static_cast<int>(num
);
717 if (rv
> buf_len
|| rv
< 0) {
718 // It seems that some winsock interceptors report that more was written
719 // than was available. Treat this as an error. http://crbug.com/27870
720 LOG(ERROR
) << "Detected broken LSP: Asked to write " << buf_len
721 << " bytes, but " << rv
<< " bytes reported.";
722 return ERR_WINSOCK_UNEXPECTED_WRITTEN_BYTES
;
724 base::StatsCounter
write_bytes("tcp.write_bytes");
727 use_history_
.set_was_used_to_convey_data();
728 net_log_
.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_SENT
, rv
,
733 int os_error
= WSAGetLastError();
734 if (os_error
!= WSA_IO_PENDING
) {
735 int net_error
= MapSystemError(os_error
);
736 net_log_
.AddEvent(NetLog::TYPE_SOCKET_WRITE_ERROR
,
737 CreateNetLogSocketErrorCallback(net_error
, os_error
));
741 waiting_write_
= true;
742 write_callback_
= callback
;
743 core_
->write_iobuffer_
= buf
;
744 core_
->write_buffer_length_
= buf_len
;
745 core_
->WatchForWrite();
746 return ERR_IO_PENDING
;
749 bool TCPClientSocketWin::SetReceiveBufferSize(int32 size
) {
750 DCHECK(CalledOnValidThread());
751 return SetSocketReceiveBufferSize(socket_
, size
);
754 bool TCPClientSocketWin::SetSendBufferSize(int32 size
) {
755 DCHECK(CalledOnValidThread());
756 return SetSocketSendBufferSize(socket_
, size
);
759 bool TCPClientSocketWin::SetKeepAlive(bool enable
, int delay
) {
760 return SetTCPKeepAlive(socket_
, enable
, delay
);
763 bool TCPClientSocketWin::SetNoDelay(bool no_delay
) {
764 return DisableNagle(socket_
, no_delay
);
767 void TCPClientSocketWin::LogConnectCompletion(int net_error
) {
769 UpdateConnectionTypeHistograms(CONNECTION_ANY
);
771 if (net_error
!= OK
) {
772 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT
, net_error
);
776 struct sockaddr_storage source_address
;
777 socklen_t addrlen
= sizeof(source_address
);
778 int rv
= getsockname(
779 socket_
, reinterpret_cast<struct sockaddr
*>(&source_address
), &addrlen
);
781 LOG(ERROR
) << "getsockname() [rv: " << rv
782 << "] error: " << WSAGetLastError();
784 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT
, rv
);
789 NetLog::TYPE_TCP_CONNECT
,
790 CreateNetLogSourceAddressCallback(
791 reinterpret_cast<const struct sockaddr
*>(&source_address
),
792 sizeof(source_address
)));
795 int TCPClientSocketWin::DoRead(IOBuffer
* buf
, int buf_len
,
796 const CompletionCallback
& callback
) {
797 if (!core_
->non_blocking_reads_initialized_
) {
798 WSAEventSelect(socket_
, core_
->read_overlapped_
.hEvent
,
800 core_
->non_blocking_reads_initialized_
= true;
802 int rv
= recv(socket_
, buf
->data(), buf_len
, 0);
803 if (rv
== SOCKET_ERROR
) {
804 int os_error
= WSAGetLastError();
805 if (os_error
!= WSAEWOULDBLOCK
) {
806 int net_error
= MapSystemError(os_error
);
808 NetLog::TYPE_SOCKET_READ_ERROR
,
809 CreateNetLogSocketErrorCallback(net_error
, os_error
));
813 base::StatsCounter
read_bytes("tcp.read_bytes");
815 use_history_
.set_was_used_to_convey_data();
818 net_log_
.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_RECEIVED
, rv
,
823 waiting_read_
= true;
824 read_callback_
= callback
;
825 core_
->read_iobuffer_
= buf
;
826 core_
->read_buffer_length_
= buf_len
;
827 core_
->WatchForRead();
828 return ERR_IO_PENDING
;
831 void TCPClientSocketWin::DoReadCallback(int rv
) {
832 DCHECK_NE(rv
, ERR_IO_PENDING
);
833 DCHECK(!read_callback_
.is_null());
835 // Since Run may result in Read being called, clear read_callback_ up front.
836 CompletionCallback c
= read_callback_
;
837 read_callback_
.Reset();
841 void TCPClientSocketWin::DoWriteCallback(int rv
) {
842 DCHECK_NE(rv
, ERR_IO_PENDING
);
843 DCHECK(!write_callback_
.is_null());
845 // Since Run may result in Write being called, clear write_callback_ up front.
846 CompletionCallback c
= write_callback_
;
847 write_callback_
.Reset();
851 void TCPClientSocketWin::DidCompleteConnect() {
852 DCHECK_EQ(next_connect_state_
, CONNECT_STATE_CONNECT_COMPLETE
);
855 WSANETWORKEVENTS events
;
856 int rv
= WSAEnumNetworkEvents(socket_
, core_
->read_overlapped_
.hEvent
,
859 if (rv
== SOCKET_ERROR
) {
861 os_error
= WSAGetLastError();
862 result
= MapSystemError(os_error
);
863 } else if (events
.lNetworkEvents
& FD_CONNECT
) {
864 os_error
= events
.iErrorCode
[FD_CONNECT_BIT
];
865 result
= MapConnectError(os_error
);
868 result
= ERR_UNEXPECTED
;
871 connect_os_error_
= os_error
;
872 rv
= DoConnectLoop(result
);
873 if (rv
!= ERR_IO_PENDING
) {
874 LogConnectCompletion(rv
);
879 void TCPClientSocketWin::DidCompleteWrite() {
880 DCHECK(waiting_write_
);
882 DWORD num_bytes
, flags
;
883 BOOL ok
= WSAGetOverlappedResult(socket_
, &core_
->write_overlapped_
,
884 &num_bytes
, FALSE
, &flags
);
885 WSAResetEvent(core_
->write_overlapped_
.hEvent
);
886 waiting_write_
= false;
889 int os_error
= WSAGetLastError();
890 rv
= MapSystemError(os_error
);
891 net_log_
.AddEvent(NetLog::TYPE_SOCKET_WRITE_ERROR
,
892 CreateNetLogSocketErrorCallback(rv
, os_error
));
894 rv
= static_cast<int>(num_bytes
);
895 if (rv
> core_
->write_buffer_length_
|| rv
< 0) {
896 // It seems that some winsock interceptors report that more was written
897 // than was available. Treat this as an error. http://crbug.com/27870
898 LOG(ERROR
) << "Detected broken LSP: Asked to write "
899 << core_
->write_buffer_length_
<< " bytes, but " << rv
900 << " bytes reported.";
901 rv
= ERR_WINSOCK_UNEXPECTED_WRITTEN_BYTES
;
903 base::StatsCounter
write_bytes("tcp.write_bytes");
904 write_bytes
.Add(num_bytes
);
906 use_history_
.set_was_used_to_convey_data();
907 net_log_
.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_SENT
, num_bytes
,
908 core_
->write_iobuffer_
->data());
911 core_
->write_iobuffer_
= NULL
;
915 void TCPClientSocketWin::DidSignalRead() {
916 DCHECK(waiting_read_
);
918 WSANETWORKEVENTS network_events
;
919 int rv
= WSAEnumNetworkEvents(socket_
, core_
->read_overlapped_
.hEvent
,
921 if (rv
== SOCKET_ERROR
) {
922 os_error
= WSAGetLastError();
923 rv
= MapSystemError(os_error
);
924 } else if (network_events
.lNetworkEvents
) {
925 DCHECK_EQ(network_events
.lNetworkEvents
& ~(FD_READ
| FD_CLOSE
), 0);
926 // If network_events.lNetworkEvents is FD_CLOSE and
927 // network_events.iErrorCode[FD_CLOSE_BIT] is 0, it is a graceful
928 // connection closure. It is tempting to directly set rv to 0 in
929 // this case, but the MSDN pages for WSAEventSelect and
930 // WSAAsyncSelect recommend we still call DoRead():
931 // FD_CLOSE should only be posted after all data is read from a
932 // socket, but an application should check for remaining data upon
933 // receipt of FD_CLOSE to avoid any possibility of losing data.
935 // If network_events.iErrorCode[FD_READ_BIT] or
936 // network_events.iErrorCode[FD_CLOSE_BIT] is nonzero, still call
937 // DoRead() because recv() reports a more accurate error code
938 // (WSAECONNRESET vs. WSAECONNABORTED) when the connection was
940 rv
= DoRead(core_
->read_iobuffer_
, core_
->read_buffer_length_
,
942 if (rv
== ERR_IO_PENDING
)
945 // This may happen because Read() may succeed synchronously and
946 // consume all the received data without resetting the event object.
947 core_
->WatchForRead();
950 waiting_read_
= false;
951 core_
->read_iobuffer_
= NULL
;
952 core_
->read_buffer_length_
= 0;