cc: Added inline to Tile::IsReadyToDraw
[chromium-blink-merge.git] / net / socket / tcp_client_socket_win.cc
blobf1334e78a468b144e8783e9fbae5a812dba50af4
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"
7 #include <mstcpip.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"
27 namespace net {
29 namespace {
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();
38 return rv == 0;
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();
45 return rv == 0;
48 // Disable Nagle.
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.
68 // See also:
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),
74 sizeof(val));
75 DCHECK(!rv) << "Could not disable nagle";
76 return rv == 0;
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.
96 return rv == 0;
99 // Sets socket parameters. Returns the OS error code (or 0 on
100 // success).
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
104 // to 64KB.
105 // See also:
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);
120 return 0;
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;
130 return os_error;
132 int error = SetupSocket(*socket);
133 if (error) {
134 if (closesocket(*socket) < 0)
135 PLOG(ERROR) << "closesocket";
136 *socket = INVALID_SOCKET;
137 return error;
139 return 0;
142 int MapConnectError(int os_error) {
143 switch (os_error) {
144 // connect fails with WSAEACCES when Windows Firewall blocks the
145 // connection.
146 case WSAEACCES:
147 return ERR_NETWORK_ACCESS_DENIED;
148 case WSAETIMEDOUT:
149 return ERR_CONNECTION_TIMED_OUT;
150 default: {
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;
161 return net_error;
166 } // namespace
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> {
176 public:
177 explicit Core(TCPClientSocketWin* socket);
179 // Start watching for the end of a read or write operation.
180 void WatchForRead();
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_;
200 private:
201 friend class base::RefCounted<Core>;
203 class ReadDelegate : public base::win::ObjectWatcher::Delegate {
204 public:
205 explicit ReadDelegate(Core* core) : core_(core) {}
206 virtual ~ReadDelegate() {}
208 // base::ObjectWatcher::Delegate methods:
209 virtual void OnObjectSignaled(HANDLE object);
211 private:
212 Core* const core_;
215 class WriteDelegate : public base::win::ObjectWatcher::Delegate {
216 public:
217 explicit WriteDelegate(Core* core) : core_(core) {}
218 virtual ~WriteDelegate() {}
220 // base::ObjectWatcher::Delegate methods:
221 virtual void OnObjectSignaled(HANDLE object);
223 private:
224 Core* const core_;
227 ~Core();
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),
250 socket_(socket),
251 reader_(this),
252 writer_(this) {
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().
274 AddRef();
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().
281 AddRef();
282 write_watcher_.StartWatching(write_overlapped_.hEvent, &writer_);
285 void TCPClientSocketWin::Core::ReadDelegate::OnObjectSignaled(
286 HANDLE object) {
287 DCHECK_EQ(object, core_->read_overlapped_.hEvent);
288 if (core_->socket_) {
289 if (core_->socket_->waiting_connect())
290 core_->socket_->DidCompleteConnect();
291 else
292 core_->socket_->DidSignalRead();
295 core_->Release();
298 void TCPClientSocketWin::Core::WriteDelegate::OnObjectSignaled(
299 HANDLE object) {
300 DCHECK_EQ(object, core_->write_overlapped_.hEvent);
301 if (core_->socket_)
302 core_->socket_->DidCompleteWrite();
304 core_->Release();
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());
324 EnsureWinsockInit();
327 TCPClientSocketWin::~TCPClientSocketWin() {
328 Disconnect();
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);
336 if (error)
337 return MapSystemError(error);
339 socket_ = socket;
340 SetNonBlocking(socket_);
342 core_ = new Core(this);
343 current_address_index_ = 0;
344 use_history_.set_was_ever_connected();
346 return OK;
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_);
361 if (error)
362 return MapSystemError(error);
364 if (bind(bound_socket_, storage.addr, storage.addr_len)) {
365 error = errno;
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));
374 return 0;
378 int TCPClientSocketWin::Connect(const CompletionCallback& callback) {
379 DCHECK(CalledOnValidThread());
381 // If already connected, then just return OK.
382 if (socket_ != INVALID_SOCKET)
383 return OK;
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;
402 } else {
403 LogConnectCompletion(rv);
406 return rv;
409 int TCPClientSocketWin::DoConnectLoop(int result) {
410 DCHECK_NE(next_connect_state_, CONNECT_STATE_NONE);
412 int rv = result;
413 do {
414 ConnectState state = next_connect_state_;
415 next_connect_state_ = CONNECT_STATE_NONE;
416 switch (state) {
417 case CONNECT_STATE_CONNECT:
418 DCHECK_EQ(OK, rv);
419 rv = DoConnect();
420 break;
421 case CONNECT_STATE_CONNECT_COMPLETE:
422 rv = DoConnectComplete(rv);
423 break;
424 default:
425 LOG(DFATAL) << "bad state " << state;
426 rv = ERR_UNEXPECTED;
427 break;
429 } while (rv != ERR_IO_PENDING && next_connect_state_ != CONNECT_STATE_NONE);
431 return rv;
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;
455 } else {
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);
469 DCHECK(!core_);
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.
489 NOTREACHED();
491 if (ResetEventIfSignaled(core_->read_overlapped_.hEvent))
492 return OK;
493 } else {
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;
510 if (result != OK) {
511 net_log_.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT,
512 NetLog::IntegerCallback("os_error", os_error));
513 } else {
514 net_log_.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT);
517 if (result == OK) {
518 use_history_.set_was_ever_connected();
519 return OK; // Done!
522 // Close whatever partially connected socket we currently have.
523 DoDisconnect();
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_;
529 return OK;
532 // Otherwise there is nothing to fall back to, so give up.
533 return result;
536 void TCPClientSocketWin::Disconnect() {
537 DCHECK(CalledOnValidThread());
539 DoDisconnect();
540 current_address_index_ = -1;
541 bind_address_.reset();
544 void TCPClientSocketWin::DoDisconnect() {
545 DCHECK(CalledOnValidThread());
547 if (socket_ == INVALID_SOCKET)
548 return;
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".
568 core_->Release();
571 waiting_read_ = false;
572 waiting_write_ = false;
574 core_->Detach();
575 core_ = NULL;
577 previously_disconnected_ = true;
580 bool TCPClientSocketWin::IsConnected() const {
581 DCHECK(CalledOnValidThread());
583 if (socket_ == INVALID_SOCKET || waiting_connect())
584 return false;
586 if (waiting_read_)
587 return true;
589 // Check if connection is alive.
590 char c;
591 int rv = recv(socket_, &c, 1, MSG_PEEK);
592 if (rv == 0)
593 return false;
594 if (rv == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
595 return false;
597 return true;
600 bool TCPClientSocketWin::IsConnectedAndIdle() const {
601 DCHECK(CalledOnValidThread());
603 if (socket_ == INVALID_SOCKET || waiting_connect())
604 return false;
606 if (waiting_read_)
607 return true;
609 // Check if connection is alive and we haven't received any data
610 // unexpectedly.
611 char c;
612 int rv = recv(socket_, &c, 1, MSG_PEEK);
613 if (rv >= 0)
614 return false;
615 if (WSAGetLastError() != WSAEWOULDBLOCK)
616 return false;
618 return true;
621 int TCPClientSocketWin::GetPeerAddress(IPEndPoint* address) const {
622 DCHECK(CalledOnValidThread());
623 DCHECK(address);
624 if (!IsConnected())
625 return ERR_SOCKET_NOT_CONNECTED;
626 *address = addresses_[current_address_index_];
627 return OK;
630 int TCPClientSocketWin::GetLocalAddress(IPEndPoint* address) const {
631 DCHECK(CalledOnValidThread());
632 DCHECK(address);
633 if (socket_ == INVALID_SOCKET) {
634 if (bind_address_.get()) {
635 *address = *bind_address_;
636 return OK;
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))
647 return ERR_FAILED;
648 return OK;
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.
665 return false;
668 bool TCPClientSocketWin::WasNpnNegotiated() const {
669 return false;
672 NextProto TCPClientSocketWin::GetNegotiatedProtocol() const {
673 return kProtoUnknown;
676 bool TCPClientSocketWin::GetSSLInfo(SSLInfo* ssl_info) {
677 return false;
680 int TCPClientSocketWin::Read(IOBuffer* buf,
681 int buf_len,
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,
693 int buf_len,
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");
703 writes.Increment();
705 WSABUF write_buffer;
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);
711 DWORD num;
712 int rv = WSASend(socket_, &write_buffer, 1, &num, 0,
713 &core_->write_overlapped_, NULL);
714 if (rv == 0) {
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");
725 write_bytes.Add(rv);
726 if (rv > 0)
727 use_history_.set_was_used_to_convey_data();
728 net_log_.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_SENT, rv,
729 buf->data());
730 return rv;
732 } else {
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));
738 return net_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) {
768 if (net_error == OK)
769 UpdateConnectionTypeHistograms(CONNECTION_ANY);
771 if (net_error != OK) {
772 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT, net_error);
773 return;
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);
780 if (rv != 0) {
781 LOG(ERROR) << "getsockname() [rv: " << rv
782 << "] error: " << WSAGetLastError();
783 NOTREACHED();
784 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT, rv);
785 return;
788 net_log_.EndEvent(
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,
799 FD_READ | FD_CLOSE);
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);
807 net_log_.AddEvent(
808 NetLog::TYPE_SOCKET_READ_ERROR,
809 CreateNetLogSocketErrorCallback(net_error, os_error));
810 return net_error;
812 } else {
813 base::StatsCounter read_bytes("tcp.read_bytes");
814 if (rv > 0) {
815 use_history_.set_was_used_to_convey_data();
816 read_bytes.Add(rv);
818 net_log_.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_RECEIVED, rv,
819 buf->data());
820 return 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();
838 c.Run(rv);
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();
848 c.Run(rv);
851 void TCPClientSocketWin::DidCompleteConnect() {
852 DCHECK_EQ(next_connect_state_, CONNECT_STATE_CONNECT_COMPLETE);
853 int result;
855 WSANETWORKEVENTS events;
856 int rv = WSAEnumNetworkEvents(socket_, core_->read_overlapped_.hEvent,
857 &events);
858 int os_error = 0;
859 if (rv == SOCKET_ERROR) {
860 NOTREACHED();
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);
866 } else {
867 NOTREACHED();
868 result = ERR_UNEXPECTED;
871 connect_os_error_ = os_error;
872 rv = DoConnectLoop(result);
873 if (rv != ERR_IO_PENDING) {
874 LogConnectCompletion(rv);
875 DoReadCallback(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;
887 int rv;
888 if (!ok) {
889 int os_error = WSAGetLastError();
890 rv = MapSystemError(os_error);
891 net_log_.AddEvent(NetLog::TYPE_SOCKET_WRITE_ERROR,
892 CreateNetLogSocketErrorCallback(rv, os_error));
893 } else {
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;
902 } else {
903 base::StatsCounter write_bytes("tcp.write_bytes");
904 write_bytes.Add(num_bytes);
905 if (num_bytes > 0)
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;
912 DoWriteCallback(rv);
915 void TCPClientSocketWin::DidSignalRead() {
916 DCHECK(waiting_read_);
917 int os_error = 0;
918 WSANETWORKEVENTS network_events;
919 int rv = WSAEnumNetworkEvents(socket_, core_->read_overlapped_.hEvent,
920 &network_events);
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
939 // reset.
940 rv = DoRead(core_->read_iobuffer_, core_->read_buffer_length_,
941 read_callback_);
942 if (rv == ERR_IO_PENDING)
943 return;
944 } else {
945 // This may happen because Read() may succeed synchronously and
946 // consume all the received data without resetting the event object.
947 core_->WatchForRead();
948 return;
950 waiting_read_ = false;
951 core_->read_iobuffer_ = NULL;
952 core_->read_buffer_length_ = 0;
953 DoReadCallback(rv);
956 } // namespace net