ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / net / socket / tcp_socket_win.cc
blobacbaa0d768b2fd7fb07b1a7175e33a6c11307a57
1 // Copyright 2013 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_socket.h"
6 #include "net/socket/tcp_socket_win.h"
8 #include <mstcpip.h>
10 #include "base/callback_helpers.h"
11 #include "base/logging.h"
12 #include "base/profiler/scoped_tracker.h"
13 #include "base/win/windows_version.h"
14 #include "net/base/address_list.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_util.h"
20 #include "net/base/network_activity_monitor.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;
33 int SetSocketReceiveBufferSize(SOCKET socket, int32 size) {
34 int rv = setsockopt(socket, SOL_SOCKET, SO_RCVBUF,
35 reinterpret_cast<const char*>(&size), sizeof(size));
36 int net_error = (rv == 0) ? OK : MapSystemError(WSAGetLastError());
37 DCHECK(!rv) << "Could not set socket receive buffer size: " << net_error;
38 return net_error;
41 int SetSocketSendBufferSize(SOCKET socket, int32 size) {
42 int rv = setsockopt(socket, SOL_SOCKET, SO_SNDBUF,
43 reinterpret_cast<const char*>(&size), sizeof(size));
44 int net_error = (rv == 0) ? OK : MapSystemError(WSAGetLastError());
45 DCHECK(!rv) << "Could not set socket send buffer size: " << net_error;
46 return net_error;
49 // Disable Nagle.
50 // The Nagle implementation on windows is governed by RFC 896. The idea
51 // behind Nagle is to reduce small packets on the network. When Nagle is
52 // enabled, if a partial packet has been sent, the TCP stack will disallow
53 // further *partial* packets until an ACK has been received from the other
54 // side. Good applications should always strive to send as much data as
55 // possible and avoid partial-packet sends. However, in most real world
56 // applications, there are edge cases where this does not happen, and two
57 // partial packets may be sent back to back. For a browser, it is NEVER
58 // a benefit to delay for an RTT before the second packet is sent.
60 // As a practical example in Chromium today, consider the case of a small
61 // POST. I have verified this:
62 // Client writes 649 bytes of header (partial packet #1)
63 // Client writes 50 bytes of POST data (partial packet #2)
64 // In the above example, with Nagle, a RTT delay is inserted between these
65 // two sends due to nagle. RTTs can easily be 100ms or more. The best
66 // fix is to make sure that for POSTing data, we write as much data as
67 // possible and minimize partial packets. We will fix that. But disabling
68 // Nagle also ensure we don't run into this delay in other edge cases.
69 // See also:
70 // http://technet.microsoft.com/en-us/library/bb726981.aspx
71 bool DisableNagle(SOCKET socket, bool disable) {
72 BOOL val = disable ? TRUE : FALSE;
73 int rv = setsockopt(socket, IPPROTO_TCP, TCP_NODELAY,
74 reinterpret_cast<const char*>(&val),
75 sizeof(val));
76 DCHECK(!rv) << "Could not disable nagle";
77 return rv == 0;
80 // Enable TCP Keep-Alive to prevent NAT routers from timing out TCP
81 // connections. See http://crbug.com/27400 for details.
82 bool SetTCPKeepAlive(SOCKET socket, BOOL enable, int delay_secs) {
83 int delay = delay_secs * 1000;
84 struct tcp_keepalive keepalive_vals = {
85 enable ? 1 : 0, // TCP keep-alive on.
86 delay, // Delay seconds before sending first TCP keep-alive packet.
87 delay, // Delay seconds between sending TCP keep-alive packets.
89 DWORD bytes_returned = 0xABAB;
90 int rv = WSAIoctl(socket, SIO_KEEPALIVE_VALS, &keepalive_vals,
91 sizeof(keepalive_vals), NULL, 0,
92 &bytes_returned, NULL, NULL);
93 DCHECK(!rv) << "Could not enable TCP Keep-Alive for socket: " << socket
94 << " [error: " << WSAGetLastError() << "].";
96 // Disregard any failure in disabling nagle or enabling TCP Keep-Alive.
97 return rv == 0;
100 int MapConnectError(int os_error) {
101 switch (os_error) {
102 // connect fails with WSAEACCES when Windows Firewall blocks the
103 // connection.
104 case WSAEACCES:
105 return ERR_NETWORK_ACCESS_DENIED;
106 case WSAETIMEDOUT:
107 return ERR_CONNECTION_TIMED_OUT;
108 default: {
109 int net_error = MapSystemError(os_error);
110 if (net_error == ERR_FAILED)
111 return ERR_CONNECTION_FAILED; // More specific than ERR_FAILED.
113 // Give a more specific error when the user is offline.
114 if (net_error == ERR_ADDRESS_UNREACHABLE &&
115 NetworkChangeNotifier::IsOffline()) {
116 return ERR_INTERNET_DISCONNECTED;
119 return net_error;
124 } // namespace
126 //-----------------------------------------------------------------------------
128 // Nothing to do for Windows since it doesn't support TCP FastOpen.
129 // TODO(jri): Remove these along with the corresponding global variables.
130 bool IsTCPFastOpenSupported() { return false; }
131 bool IsTCPFastOpenUserEnabled() { return false; }
132 void CheckSupportAndMaybeEnableTCPFastOpen(bool user_enabled) {}
134 // This class encapsulates all the state that has to be preserved as long as
135 // there is a network IO operation in progress. If the owner TCPSocketWin is
136 // destroyed while an operation is in progress, the Core is detached and it
137 // lives until the operation completes and the OS doesn't reference any resource
138 // declared on this class anymore.
139 class TCPSocketWin::Core : public base::RefCounted<Core> {
140 public:
141 explicit Core(TCPSocketWin* socket);
143 // Start watching for the end of a read or write operation.
144 void WatchForRead();
145 void WatchForWrite();
147 // The TCPSocketWin is going away.
148 void Detach() { socket_ = NULL; }
150 // The separate OVERLAPPED variables for asynchronous operation.
151 // |read_overlapped_| is used for both Connect() and Read().
152 // |write_overlapped_| is only used for Write();
153 OVERLAPPED read_overlapped_;
154 OVERLAPPED write_overlapped_;
156 // The buffers used in Read() and Write().
157 scoped_refptr<IOBuffer> read_iobuffer_;
158 scoped_refptr<IOBuffer> write_iobuffer_;
159 int read_buffer_length_;
160 int write_buffer_length_;
162 bool non_blocking_reads_initialized_;
164 private:
165 friend class base::RefCounted<Core>;
167 class ReadDelegate : public base::win::ObjectWatcher::Delegate {
168 public:
169 explicit ReadDelegate(Core* core) : core_(core) {}
170 virtual ~ReadDelegate() {}
172 // base::ObjectWatcher::Delegate methods:
173 virtual void OnObjectSignaled(HANDLE object);
175 private:
176 Core* const core_;
179 class WriteDelegate : public base::win::ObjectWatcher::Delegate {
180 public:
181 explicit WriteDelegate(Core* core) : core_(core) {}
182 virtual ~WriteDelegate() {}
184 // base::ObjectWatcher::Delegate methods:
185 virtual void OnObjectSignaled(HANDLE object);
187 private:
188 Core* const core_;
191 ~Core();
193 // The socket that created this object.
194 TCPSocketWin* socket_;
196 // |reader_| handles the signals from |read_watcher_|.
197 ReadDelegate reader_;
198 // |writer_| handles the signals from |write_watcher_|.
199 WriteDelegate writer_;
201 // |read_watcher_| watches for events from Connect() and Read().
202 base::win::ObjectWatcher read_watcher_;
203 // |write_watcher_| watches for events from Write();
204 base::win::ObjectWatcher write_watcher_;
206 DISALLOW_COPY_AND_ASSIGN(Core);
209 TCPSocketWin::Core::Core(TCPSocketWin* socket)
210 : read_buffer_length_(0),
211 write_buffer_length_(0),
212 non_blocking_reads_initialized_(false),
213 socket_(socket),
214 reader_(this),
215 writer_(this) {
216 memset(&read_overlapped_, 0, sizeof(read_overlapped_));
217 memset(&write_overlapped_, 0, sizeof(write_overlapped_));
219 read_overlapped_.hEvent = WSACreateEvent();
220 write_overlapped_.hEvent = WSACreateEvent();
223 TCPSocketWin::Core::~Core() {
224 // Make sure the message loop is not watching this object anymore.
225 read_watcher_.StopWatching();
226 write_watcher_.StopWatching();
228 WSACloseEvent(read_overlapped_.hEvent);
229 memset(&read_overlapped_, 0xaf, sizeof(read_overlapped_));
230 WSACloseEvent(write_overlapped_.hEvent);
231 memset(&write_overlapped_, 0xaf, sizeof(write_overlapped_));
234 void TCPSocketWin::Core::WatchForRead() {
235 // We grab an extra reference because there is an IO operation in progress.
236 // Balanced in ReadDelegate::OnObjectSignaled().
237 AddRef();
238 read_watcher_.StartWatching(read_overlapped_.hEvent, &reader_);
241 void TCPSocketWin::Core::WatchForWrite() {
242 // We grab an extra reference because there is an IO operation in progress.
243 // Balanced in WriteDelegate::OnObjectSignaled().
244 AddRef();
245 write_watcher_.StartWatching(write_overlapped_.hEvent, &writer_);
248 void TCPSocketWin::Core::ReadDelegate::OnObjectSignaled(HANDLE object) {
249 DCHECK_EQ(object, core_->read_overlapped_.hEvent);
250 if (core_->socket_) {
251 if (core_->socket_->waiting_connect_)
252 core_->socket_->DidCompleteConnect();
253 else
254 core_->socket_->DidSignalRead();
257 core_->Release();
260 void TCPSocketWin::Core::WriteDelegate::OnObjectSignaled(
261 HANDLE object) {
262 DCHECK_EQ(object, core_->write_overlapped_.hEvent);
263 if (core_->socket_)
264 core_->socket_->DidCompleteWrite();
266 core_->Release();
269 //-----------------------------------------------------------------------------
271 TCPSocketWin::TCPSocketWin(net::NetLog* net_log,
272 const net::NetLog::Source& source)
273 : socket_(INVALID_SOCKET),
274 accept_event_(WSA_INVALID_EVENT),
275 accept_socket_(NULL),
276 accept_address_(NULL),
277 waiting_connect_(false),
278 waiting_read_(false),
279 waiting_write_(false),
280 connect_os_error_(0),
281 logging_multiple_connect_attempts_(false),
282 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_SOCKET)) {
283 net_log_.BeginEvent(NetLog::TYPE_SOCKET_ALIVE,
284 source.ToEventParametersCallback());
285 EnsureWinsockInit();
288 TCPSocketWin::~TCPSocketWin() {
289 Close();
290 net_log_.EndEvent(NetLog::TYPE_SOCKET_ALIVE);
293 int TCPSocketWin::Open(AddressFamily family) {
294 DCHECK(CalledOnValidThread());
295 DCHECK_EQ(socket_, INVALID_SOCKET);
297 socket_ = CreatePlatformSocket(ConvertAddressFamily(family), SOCK_STREAM,
298 IPPROTO_TCP);
299 if (socket_ == INVALID_SOCKET) {
300 PLOG(ERROR) << "CreatePlatformSocket() returned an error";
301 return MapSystemError(WSAGetLastError());
304 if (SetNonBlocking(socket_)) {
305 int result = MapSystemError(WSAGetLastError());
306 Close();
307 return result;
310 return OK;
313 int TCPSocketWin::AdoptConnectedSocket(SOCKET socket,
314 const IPEndPoint& peer_address) {
315 DCHECK(CalledOnValidThread());
316 DCHECK_EQ(socket_, INVALID_SOCKET);
317 DCHECK(!core_.get());
319 socket_ = socket;
321 if (SetNonBlocking(socket_)) {
322 int result = MapSystemError(WSAGetLastError());
323 Close();
324 return result;
327 core_ = new Core(this);
328 peer_address_.reset(new IPEndPoint(peer_address));
330 return OK;
333 int TCPSocketWin::AdoptListenSocket(SOCKET socket) {
334 DCHECK(CalledOnValidThread());
335 DCHECK_EQ(socket_, INVALID_SOCKET);
337 socket_ = socket;
339 if (SetNonBlocking(socket_)) {
340 int result = MapSystemError(WSAGetLastError());
341 Close();
342 return result;
345 // |core_| is not needed for sockets that are used to accept connections.
346 // The operation here is more like Open but with an existing socket.
348 return OK;
351 int TCPSocketWin::Bind(const IPEndPoint& address) {
352 DCHECK(CalledOnValidThread());
353 DCHECK_NE(socket_, INVALID_SOCKET);
355 SockaddrStorage storage;
356 if (!address.ToSockAddr(storage.addr, &storage.addr_len))
357 return ERR_ADDRESS_INVALID;
359 int result = bind(socket_, storage.addr, storage.addr_len);
360 if (result < 0) {
361 PLOG(ERROR) << "bind() returned an error";
362 return MapSystemError(WSAGetLastError());
365 return OK;
368 int TCPSocketWin::Listen(int backlog) {
369 DCHECK(CalledOnValidThread());
370 DCHECK_GT(backlog, 0);
371 DCHECK_NE(socket_, INVALID_SOCKET);
372 DCHECK_EQ(accept_event_, WSA_INVALID_EVENT);
374 accept_event_ = WSACreateEvent();
375 if (accept_event_ == WSA_INVALID_EVENT) {
376 PLOG(ERROR) << "WSACreateEvent()";
377 return MapSystemError(WSAGetLastError());
380 int result = listen(socket_, backlog);
381 if (result < 0) {
382 PLOG(ERROR) << "listen() returned an error";
383 return MapSystemError(WSAGetLastError());
386 return OK;
389 int TCPSocketWin::Accept(scoped_ptr<TCPSocketWin>* socket,
390 IPEndPoint* address,
391 const CompletionCallback& callback) {
392 DCHECK(CalledOnValidThread());
393 DCHECK(socket);
394 DCHECK(address);
395 DCHECK(!callback.is_null());
396 DCHECK(accept_callback_.is_null());
398 net_log_.BeginEvent(NetLog::TYPE_TCP_ACCEPT);
400 int result = AcceptInternal(socket, address);
402 if (result == ERR_IO_PENDING) {
403 // Start watching.
404 WSAEventSelect(socket_, accept_event_, FD_ACCEPT);
405 accept_watcher_.StartWatching(accept_event_, this);
407 accept_socket_ = socket;
408 accept_address_ = address;
409 accept_callback_ = callback;
412 return result;
415 int TCPSocketWin::Connect(const IPEndPoint& address,
416 const CompletionCallback& callback) {
417 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
418 tracked_objects::ScopedTracker tracking_profile(
419 FROM_HERE_WITH_EXPLICIT_FUNCTION("436634 TCPSocketWin::Connect"));
421 DCHECK(CalledOnValidThread());
422 DCHECK_NE(socket_, INVALID_SOCKET);
423 DCHECK(!waiting_connect_);
425 // |peer_address_| and |core_| will be non-NULL if Connect() has been called.
426 // Unless Close() is called to reset the internal state, a second call to
427 // Connect() is not allowed.
428 // Please note that we enforce this even if the previous Connect() has
429 // completed and failed. Although it is allowed to connect the same |socket_|
430 // again after a connection attempt failed on Windows, it results in
431 // unspecified behavior according to POSIX. Therefore, we make it behave in
432 // the same way as TCPSocketLibevent.
433 DCHECK(!peer_address_ && !core_.get());
435 if (!logging_multiple_connect_attempts_)
436 LogConnectBegin(AddressList(address));
438 peer_address_.reset(new IPEndPoint(address));
440 int rv = DoConnect();
441 if (rv == ERR_IO_PENDING) {
442 // Synchronous operation not supported.
443 DCHECK(!callback.is_null());
444 read_callback_ = callback;
445 waiting_connect_ = true;
446 } else {
447 DoConnectComplete(rv);
450 return rv;
453 bool TCPSocketWin::IsConnected() const {
454 DCHECK(CalledOnValidThread());
456 if (socket_ == INVALID_SOCKET || waiting_connect_)
457 return false;
459 if (waiting_read_)
460 return true;
462 // Check if connection is alive.
463 char c;
464 int rv = recv(socket_, &c, 1, MSG_PEEK);
465 if (rv == 0)
466 return false;
467 if (rv == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
468 return false;
470 return true;
473 bool TCPSocketWin::IsConnectedAndIdle() const {
474 DCHECK(CalledOnValidThread());
476 if (socket_ == INVALID_SOCKET || waiting_connect_)
477 return false;
479 if (waiting_read_)
480 return true;
482 // Check if connection is alive and we haven't received any data
483 // unexpectedly.
484 char c;
485 int rv = recv(socket_, &c, 1, MSG_PEEK);
486 if (rv >= 0)
487 return false;
488 if (WSAGetLastError() != WSAEWOULDBLOCK)
489 return false;
491 return true;
494 int TCPSocketWin::Read(IOBuffer* buf,
495 int buf_len,
496 const CompletionCallback& callback) {
497 DCHECK(CalledOnValidThread());
498 DCHECK_NE(socket_, INVALID_SOCKET);
499 DCHECK(!waiting_read_);
500 CHECK(read_callback_.is_null());
501 DCHECK(!core_->read_iobuffer_.get());
503 return DoRead(buf, buf_len, callback);
506 int TCPSocketWin::Write(IOBuffer* buf,
507 int buf_len,
508 const CompletionCallback& callback) {
509 DCHECK(CalledOnValidThread());
510 DCHECK_NE(socket_, INVALID_SOCKET);
511 DCHECK(!waiting_write_);
512 CHECK(write_callback_.is_null());
513 DCHECK_GT(buf_len, 0);
514 DCHECK(!core_->write_iobuffer_.get());
516 WSABUF write_buffer;
517 write_buffer.len = buf_len;
518 write_buffer.buf = buf->data();
520 // TODO(wtc): Remove the assertion after enough testing.
521 AssertEventNotSignaled(core_->write_overlapped_.hEvent);
522 DWORD num;
523 int rv = WSASend(socket_, &write_buffer, 1, &num, 0,
524 &core_->write_overlapped_, NULL);
525 if (rv == 0) {
526 if (ResetEventIfSignaled(core_->write_overlapped_.hEvent)) {
527 rv = static_cast<int>(num);
528 if (rv > buf_len || rv < 0) {
529 // It seems that some winsock interceptors report that more was written
530 // than was available. Treat this as an error. http://crbug.com/27870
531 LOG(ERROR) << "Detected broken LSP: Asked to write " << buf_len
532 << " bytes, but " << rv << " bytes reported.";
533 return ERR_WINSOCK_UNEXPECTED_WRITTEN_BYTES;
535 net_log_.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_SENT, rv,
536 buf->data());
537 NetworkActivityMonitor::GetInstance()->IncrementBytesSent(rv);
538 return rv;
540 } else {
541 int os_error = WSAGetLastError();
542 if (os_error != WSA_IO_PENDING) {
543 int net_error = MapSystemError(os_error);
544 net_log_.AddEvent(NetLog::TYPE_SOCKET_WRITE_ERROR,
545 CreateNetLogSocketErrorCallback(net_error, os_error));
546 return net_error;
549 waiting_write_ = true;
550 write_callback_ = callback;
551 core_->write_iobuffer_ = buf;
552 core_->write_buffer_length_ = buf_len;
553 core_->WatchForWrite();
554 return ERR_IO_PENDING;
557 int TCPSocketWin::GetLocalAddress(IPEndPoint* address) const {
558 DCHECK(CalledOnValidThread());
559 DCHECK(address);
561 SockaddrStorage storage;
562 if (getsockname(socket_, storage.addr, &storage.addr_len))
563 return MapSystemError(WSAGetLastError());
564 if (!address->FromSockAddr(storage.addr, storage.addr_len))
565 return ERR_ADDRESS_INVALID;
567 return OK;
570 int TCPSocketWin::GetPeerAddress(IPEndPoint* address) const {
571 DCHECK(CalledOnValidThread());
572 DCHECK(address);
573 if (!IsConnected())
574 return ERR_SOCKET_NOT_CONNECTED;
575 *address = *peer_address_;
576 return OK;
579 int TCPSocketWin::SetDefaultOptionsForServer() {
580 return SetExclusiveAddrUse();
583 void TCPSocketWin::SetDefaultOptionsForClient() {
584 // Increase the socket buffer sizes from the default sizes for WinXP. In
585 // performance testing, there is substantial benefit by increasing from 8KB
586 // to 64KB.
587 // See also:
588 // http://support.microsoft.com/kb/823764/EN-US
589 // On Vista, if we manually set these sizes, Vista turns off its receive
590 // window auto-tuning feature.
591 // http://blogs.msdn.com/wndp/archive/2006/05/05/Winhec-blog-tcpip-2.aspx
592 // Since Vista's auto-tune is better than any static value we can could set,
593 // only change these on pre-vista machines.
594 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
595 const int32 kSocketBufferSize = 64 * 1024;
596 SetSocketReceiveBufferSize(socket_, kSocketBufferSize);
597 SetSocketSendBufferSize(socket_, kSocketBufferSize);
600 DisableNagle(socket_, true);
601 SetTCPKeepAlive(socket_, true, kTCPKeepAliveSeconds);
604 int TCPSocketWin::SetExclusiveAddrUse() {
605 // On Windows, a bound end point can be hijacked by another process by
606 // setting SO_REUSEADDR. Therefore a Windows-only option SO_EXCLUSIVEADDRUSE
607 // was introduced in Windows NT 4.0 SP4. If the socket that is bound to the
608 // end point has SO_EXCLUSIVEADDRUSE enabled, it is not possible for another
609 // socket to forcibly bind to the end point until the end point is unbound.
610 // It is recommend that all server applications must use SO_EXCLUSIVEADDRUSE.
611 // MSDN: http://goo.gl/M6fjQ.
613 // Unlike on *nix, on Windows a TCP server socket can always bind to an end
614 // point in TIME_WAIT state without setting SO_REUSEADDR, therefore it is not
615 // needed here.
617 // SO_EXCLUSIVEADDRUSE will prevent a TCP client socket from binding to an end
618 // point in TIME_WAIT status. It does not have this effect for a TCP server
619 // socket.
621 BOOL true_value = 1;
622 int rv = setsockopt(socket_, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
623 reinterpret_cast<const char*>(&true_value),
624 sizeof(true_value));
625 if (rv < 0)
626 return MapSystemError(errno);
627 return OK;
630 int TCPSocketWin::SetReceiveBufferSize(int32 size) {
631 DCHECK(CalledOnValidThread());
632 return SetSocketReceiveBufferSize(socket_, size);
635 int TCPSocketWin::SetSendBufferSize(int32 size) {
636 DCHECK(CalledOnValidThread());
637 return SetSocketSendBufferSize(socket_, size);
640 bool TCPSocketWin::SetKeepAlive(bool enable, int delay) {
641 return SetTCPKeepAlive(socket_, enable, delay);
644 bool TCPSocketWin::SetNoDelay(bool no_delay) {
645 return DisableNagle(socket_, no_delay);
648 void TCPSocketWin::Close() {
649 DCHECK(CalledOnValidThread());
651 if (socket_ != INVALID_SOCKET) {
652 // Only log the close event if there's actually a socket to close.
653 net_log_.AddEvent(NetLog::EventType::TYPE_SOCKET_CLOSED);
655 // Note: don't use CancelIo to cancel pending IO because it doesn't work
656 // when there is a Winsock layered service provider.
658 // In most socket implementations, closing a socket results in a graceful
659 // connection shutdown, but in Winsock we have to call shutdown explicitly.
660 // See the MSDN page "Graceful Shutdown, Linger Options, and Socket Closure"
661 // at http://msdn.microsoft.com/en-us/library/ms738547.aspx
662 shutdown(socket_, SD_SEND);
664 // This cancels any pending IO.
665 if (closesocket(socket_) < 0)
666 PLOG(ERROR) << "closesocket";
667 socket_ = INVALID_SOCKET;
670 if (!accept_callback_.is_null()) {
671 accept_watcher_.StopWatching();
672 accept_socket_ = NULL;
673 accept_address_ = NULL;
674 accept_callback_.Reset();
677 if (accept_event_) {
678 WSACloseEvent(accept_event_);
679 accept_event_ = WSA_INVALID_EVENT;
682 if (core_.get()) {
683 if (waiting_connect_) {
684 // We closed the socket, so this notification will never come.
685 // From MSDN' WSAEventSelect documentation:
686 // "Closing a socket with closesocket also cancels the association and
687 // selection of network events specified in WSAEventSelect for the
688 // socket".
689 core_->Release();
691 core_->Detach();
692 core_ = NULL;
695 waiting_connect_ = false;
696 waiting_read_ = false;
697 waiting_write_ = false;
699 read_callback_.Reset();
700 write_callback_.Reset();
701 peer_address_.reset();
702 connect_os_error_ = 0;
705 void TCPSocketWin::StartLoggingMultipleConnectAttempts(
706 const AddressList& addresses) {
707 if (!logging_multiple_connect_attempts_) {
708 logging_multiple_connect_attempts_ = true;
709 LogConnectBegin(addresses);
710 } else {
711 NOTREACHED();
715 void TCPSocketWin::EndLoggingMultipleConnectAttempts(int net_error) {
716 if (logging_multiple_connect_attempts_) {
717 LogConnectEnd(net_error);
718 logging_multiple_connect_attempts_ = false;
719 } else {
720 NOTREACHED();
724 int TCPSocketWin::AcceptInternal(scoped_ptr<TCPSocketWin>* socket,
725 IPEndPoint* address) {
726 SockaddrStorage storage;
727 int new_socket = accept(socket_, storage.addr, &storage.addr_len);
728 if (new_socket < 0) {
729 int net_error = MapSystemError(WSAGetLastError());
730 if (net_error != ERR_IO_PENDING)
731 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_ACCEPT, net_error);
732 return net_error;
735 IPEndPoint ip_end_point;
736 if (!ip_end_point.FromSockAddr(storage.addr, storage.addr_len)) {
737 NOTREACHED();
738 if (closesocket(new_socket) < 0)
739 PLOG(ERROR) << "closesocket";
740 int net_error = ERR_ADDRESS_INVALID;
741 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_ACCEPT, net_error);
742 return net_error;
744 scoped_ptr<TCPSocketWin> tcp_socket(new TCPSocketWin(
745 net_log_.net_log(), net_log_.source()));
746 int adopt_result = tcp_socket->AdoptConnectedSocket(new_socket, ip_end_point);
747 if (adopt_result != OK) {
748 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_ACCEPT, adopt_result);
749 return adopt_result;
751 *socket = tcp_socket.Pass();
752 *address = ip_end_point;
753 net_log_.EndEvent(NetLog::TYPE_TCP_ACCEPT,
754 CreateNetLogIPEndPointCallback(&ip_end_point));
755 return OK;
758 void TCPSocketWin::OnObjectSignaled(HANDLE object) {
759 WSANETWORKEVENTS ev;
760 if (WSAEnumNetworkEvents(socket_, accept_event_, &ev) == SOCKET_ERROR) {
761 PLOG(ERROR) << "WSAEnumNetworkEvents()";
762 return;
765 if (ev.lNetworkEvents & FD_ACCEPT) {
766 int result = AcceptInternal(accept_socket_, accept_address_);
767 if (result != ERR_IO_PENDING) {
768 accept_socket_ = NULL;
769 accept_address_ = NULL;
770 base::ResetAndReturn(&accept_callback_).Run(result);
772 } else {
773 // This happens when a client opens a connection and closes it before we
774 // have a chance to accept it.
775 DCHECK(ev.lNetworkEvents == 0);
777 // Start watching the next FD_ACCEPT event.
778 WSAEventSelect(socket_, accept_event_, FD_ACCEPT);
779 accept_watcher_.StartWatching(accept_event_, this);
783 int TCPSocketWin::DoConnect() {
784 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
785 tracked_objects::ScopedTracker tracking_profile(
786 FROM_HERE_WITH_EXPLICIT_FUNCTION("436634 TCPSocketWin::DoConnect"));
788 DCHECK_EQ(connect_os_error_, 0);
789 DCHECK(!core_.get());
791 net_log_.BeginEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT,
792 CreateNetLogIPEndPointCallback(peer_address_.get()));
794 core_ = new Core(this);
796 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
797 tracked_objects::ScopedTracker tracking_profile1(
798 FROM_HERE_WITH_EXPLICIT_FUNCTION("436634 TCPSocketWin::DoConnect1"));
800 // WSAEventSelect sets the socket to non-blocking mode as a side effect.
801 // Our connect() and recv() calls require that the socket be non-blocking.
802 WSAEventSelect(socket_, core_->read_overlapped_.hEvent, FD_CONNECT);
804 SockaddrStorage storage;
805 if (!peer_address_->ToSockAddr(storage.addr, &storage.addr_len))
806 return ERR_ADDRESS_INVALID;
808 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
809 tracked_objects::ScopedTracker tracking_profile2(
810 FROM_HERE_WITH_EXPLICIT_FUNCTION("436634 TCPSocketWin::DoConnect2"));
812 if (!connect(socket_, storage.addr, storage.addr_len)) {
813 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
814 tracked_objects::ScopedTracker tracking_profile3(
815 FROM_HERE_WITH_EXPLICIT_FUNCTION("436634 TCPSocketWin::DoConnect3"));
817 // Connected without waiting!
819 // The MSDN page for connect says:
820 // With a nonblocking socket, the connection attempt cannot be completed
821 // immediately. In this case, connect will return SOCKET_ERROR, and
822 // WSAGetLastError will return WSAEWOULDBLOCK.
823 // which implies that for a nonblocking socket, connect never returns 0.
824 // It's not documented whether the event object will be signaled or not
825 // if connect does return 0. So the code below is essentially dead code
826 // and we don't know if it's correct.
827 NOTREACHED();
829 if (ResetEventIfSignaled(core_->read_overlapped_.hEvent))
830 return OK;
831 } else {
832 int os_error = WSAGetLastError();
834 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
835 tracked_objects::ScopedTracker tracking_profile4(
836 FROM_HERE_WITH_EXPLICIT_FUNCTION("436634 TCPSocketWin::DoConnect4"));
838 if (os_error != WSAEWOULDBLOCK) {
839 LOG(ERROR) << "connect failed: " << os_error;
840 connect_os_error_ = os_error;
841 int rv = MapConnectError(os_error);
842 CHECK_NE(ERR_IO_PENDING, rv);
843 return rv;
847 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
848 tracked_objects::ScopedTracker tracking_profile5(
849 FROM_HERE_WITH_EXPLICIT_FUNCTION("436634 TCPSocketWin::DoConnect5"));
851 core_->WatchForRead();
852 return ERR_IO_PENDING;
855 void TCPSocketWin::DoConnectComplete(int result) {
856 // Log the end of this attempt (and any OS error it threw).
857 int os_error = connect_os_error_;
858 connect_os_error_ = 0;
859 if (result != OK) {
860 net_log_.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT,
861 NetLog::IntegerCallback("os_error", os_error));
862 } else {
863 net_log_.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT);
866 if (!logging_multiple_connect_attempts_)
867 LogConnectEnd(result);
870 void TCPSocketWin::LogConnectBegin(const AddressList& addresses) {
871 net_log_.BeginEvent(NetLog::TYPE_TCP_CONNECT,
872 addresses.CreateNetLogCallback());
875 void TCPSocketWin::LogConnectEnd(int net_error) {
876 if (net_error == OK)
877 UpdateConnectionTypeHistograms(CONNECTION_ANY);
879 if (net_error != OK) {
880 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT, net_error);
881 return;
884 struct sockaddr_storage source_address;
885 socklen_t addrlen = sizeof(source_address);
886 int rv = getsockname(
887 socket_, reinterpret_cast<struct sockaddr*>(&source_address), &addrlen);
888 if (rv != 0) {
889 LOG(ERROR) << "getsockname() [rv: " << rv
890 << "] error: " << WSAGetLastError();
891 NOTREACHED();
892 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT, rv);
893 return;
896 net_log_.EndEvent(
897 NetLog::TYPE_TCP_CONNECT,
898 CreateNetLogSourceAddressCallback(
899 reinterpret_cast<const struct sockaddr*>(&source_address),
900 sizeof(source_address)));
903 int TCPSocketWin::DoRead(IOBuffer* buf, int buf_len,
904 const CompletionCallback& callback) {
905 if (!core_->non_blocking_reads_initialized_) {
906 WSAEventSelect(socket_, core_->read_overlapped_.hEvent,
907 FD_READ | FD_CLOSE);
908 core_->non_blocking_reads_initialized_ = true;
910 int rv = recv(socket_, buf->data(), buf_len, 0);
911 if (rv == SOCKET_ERROR) {
912 int os_error = WSAGetLastError();
913 if (os_error != WSAEWOULDBLOCK) {
914 int net_error = MapSystemError(os_error);
915 net_log_.AddEvent(
916 NetLog::TYPE_SOCKET_READ_ERROR,
917 CreateNetLogSocketErrorCallback(net_error, os_error));
918 return net_error;
920 } else {
921 net_log_.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_RECEIVED, rv,
922 buf->data());
923 NetworkActivityMonitor::GetInstance()->IncrementBytesReceived(rv);
924 return rv;
927 waiting_read_ = true;
928 read_callback_ = callback;
929 core_->read_iobuffer_ = buf;
930 core_->read_buffer_length_ = buf_len;
931 core_->WatchForRead();
932 return ERR_IO_PENDING;
935 void TCPSocketWin::DidCompleteConnect() {
936 DCHECK(waiting_connect_);
937 DCHECK(!read_callback_.is_null());
938 int result;
940 WSANETWORKEVENTS events;
941 int rv;
943 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462784 is
944 // fixed.
945 tracked_objects::ScopedTracker tracking_profile1(
946 FROM_HERE_WITH_EXPLICIT_FUNCTION(
947 "462784 TCPSocketWin::DidCompleteConnect -> WSAEnumNetworkEvents"));
948 rv = WSAEnumNetworkEvents(socket_, core_->read_overlapped_.hEvent, &events);
950 int os_error = 0;
951 if (rv == SOCKET_ERROR) {
952 NOTREACHED();
953 os_error = WSAGetLastError();
954 result = MapSystemError(os_error);
955 } else if (events.lNetworkEvents & FD_CONNECT) {
956 os_error = events.iErrorCode[FD_CONNECT_BIT];
957 result = MapConnectError(os_error);
958 } else {
959 NOTREACHED();
960 result = ERR_UNEXPECTED;
963 connect_os_error_ = os_error;
964 DoConnectComplete(result);
965 waiting_connect_ = false;
967 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462784 is fixed.
968 tracked_objects::ScopedTracker tracking_profile4(
969 FROM_HERE_WITH_EXPLICIT_FUNCTION(
970 "462784 TCPSocketWin::DidCompleteConnect -> read_callback_"));
971 DCHECK_NE(result, ERR_IO_PENDING);
972 base::ResetAndReturn(&read_callback_).Run(result);
975 void TCPSocketWin::DidCompleteWrite() {
976 DCHECK(waiting_write_);
977 DCHECK(!write_callback_.is_null());
979 DWORD num_bytes, flags;
980 BOOL ok = WSAGetOverlappedResult(socket_, &core_->write_overlapped_,
981 &num_bytes, FALSE, &flags);
982 WSAResetEvent(core_->write_overlapped_.hEvent);
983 waiting_write_ = false;
984 int rv;
985 if (!ok) {
986 int os_error = WSAGetLastError();
987 rv = MapSystemError(os_error);
988 net_log_.AddEvent(NetLog::TYPE_SOCKET_WRITE_ERROR,
989 CreateNetLogSocketErrorCallback(rv, os_error));
990 } else {
991 rv = static_cast<int>(num_bytes);
992 if (rv > core_->write_buffer_length_ || rv < 0) {
993 // It seems that some winsock interceptors report that more was written
994 // than was available. Treat this as an error. http://crbug.com/27870
995 LOG(ERROR) << "Detected broken LSP: Asked to write "
996 << core_->write_buffer_length_ << " bytes, but " << rv
997 << " bytes reported.";
998 rv = ERR_WINSOCK_UNEXPECTED_WRITTEN_BYTES;
999 } else {
1000 net_log_.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_SENT, num_bytes,
1001 core_->write_iobuffer_->data());
1002 NetworkActivityMonitor::GetInstance()->IncrementBytesSent(num_bytes);
1006 core_->write_iobuffer_ = NULL;
1008 DCHECK_NE(rv, ERR_IO_PENDING);
1009 base::ResetAndReturn(&write_callback_).Run(rv);
1012 void TCPSocketWin::DidSignalRead() {
1013 DCHECK(waiting_read_);
1014 DCHECK(!read_callback_.is_null());
1016 int os_error = 0;
1017 WSANETWORKEVENTS network_events;
1018 int rv = WSAEnumNetworkEvents(socket_, core_->read_overlapped_.hEvent,
1019 &network_events);
1020 if (rv == SOCKET_ERROR) {
1021 os_error = WSAGetLastError();
1022 rv = MapSystemError(os_error);
1023 } else if (network_events.lNetworkEvents) {
1024 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462778 is
1025 // fixed.
1026 tracked_objects::ScopedTracker tracking_profile2(
1027 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1028 "462778 TCPSocketWin::DidSignalRead -> DoRead"));
1029 DCHECK_EQ(network_events.lNetworkEvents & ~(FD_READ | FD_CLOSE), 0);
1030 // If network_events.lNetworkEvents is FD_CLOSE and
1031 // network_events.iErrorCode[FD_CLOSE_BIT] is 0, it is a graceful
1032 // connection closure. It is tempting to directly set rv to 0 in
1033 // this case, but the MSDN pages for WSAEventSelect and
1034 // WSAAsyncSelect recommend we still call DoRead():
1035 // FD_CLOSE should only be posted after all data is read from a
1036 // socket, but an application should check for remaining data upon
1037 // receipt of FD_CLOSE to avoid any possibility of losing data.
1039 // If network_events.iErrorCode[FD_READ_BIT] or
1040 // network_events.iErrorCode[FD_CLOSE_BIT] is nonzero, still call
1041 // DoRead() because recv() reports a more accurate error code
1042 // (WSAECONNRESET vs. WSAECONNABORTED) when the connection was
1043 // reset.
1044 rv = DoRead(core_->read_iobuffer_.get(), core_->read_buffer_length_,
1045 read_callback_);
1046 if (rv == ERR_IO_PENDING)
1047 return;
1048 } else {
1049 // This may happen because Read() may succeed synchronously and
1050 // consume all the received data without resetting the event object.
1051 core_->WatchForRead();
1052 return;
1055 waiting_read_ = false;
1056 core_->read_iobuffer_ = NULL;
1057 core_->read_buffer_length_ = 0;
1059 DCHECK_NE(rv, ERR_IO_PENDING);
1060 base::ResetAndReturn(&read_callback_).Run(rv);
1063 } // namespace net