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"
8 #include <netinet/tcp.h>
9 #include <sys/socket.h>
11 #include "base/bind.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/stats_counters.h"
15 #include "base/posix/eintr_wrapper.h"
16 #include "base/task_runner_util.h"
17 #include "base/threading/worker_pool.h"
18 #include "net/base/address_list.h"
19 #include "net/base/connection_type_histograms.h"
20 #include "net/base/io_buffer.h"
21 #include "net/base/ip_endpoint.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/net_util.h"
24 #include "net/base/network_activity_monitor.h"
25 #include "net/base/network_change_notifier.h"
26 #include "net/socket/socket_libevent.h"
27 #include "net/socket/socket_net_log_params.h"
29 // If we don't have a definition for TCPI_OPT_SYN_DATA, create one.
30 #ifndef TCPI_OPT_SYN_DATA
31 #define TCPI_OPT_SYN_DATA 32
38 // True if OS supports TCP FastOpen.
39 bool g_tcp_fastopen_supported
= false;
40 // True if TCP FastOpen is user-enabled for all connections.
41 // TODO(jri): Change global variable to param in HttpNetworkSession::Params.
42 bool g_tcp_fastopen_user_enabled
= false;
43 // True if TCP FastOpen connect-with-write has failed at least once.
44 bool g_tcp_fastopen_has_failed
= false;
46 // SetTCPNoDelay turns on/off buffering in the kernel. By default, TCP sockets
47 // will wait up to 200ms for more data to complete a packet before transmitting.
48 // After calling this function, the kernel will not wait. See TCP_NODELAY in
50 bool SetTCPNoDelay(int fd
, bool no_delay
) {
51 int on
= no_delay
? 1 : 0;
52 int error
= setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, &on
, sizeof(on
));
56 // SetTCPKeepAlive sets SO_KEEPALIVE.
57 bool SetTCPKeepAlive(int fd
, bool enable
, int delay
) {
58 int on
= enable
? 1 : 0;
59 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, &on
, sizeof(on
))) {
60 PLOG(ERROR
) << "Failed to set SO_KEEPALIVE on fd: " << fd
;
64 // If we disabled TCP keep alive, our work is done here.
68 #if defined(OS_LINUX) || defined(OS_ANDROID)
69 // Set seconds until first TCP keep alive.
70 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPIDLE
, &delay
, sizeof(delay
))) {
71 PLOG(ERROR
) << "Failed to set TCP_KEEPIDLE on fd: " << fd
;
74 // Set seconds between TCP keep alives.
75 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPINTVL
, &delay
, sizeof(delay
))) {
76 PLOG(ERROR
) << "Failed to set TCP_KEEPINTVL on fd: " << fd
;
83 #if defined(OS_LINUX) || defined(OS_ANDROID)
84 // Checks if the kernel supports TCP FastOpen.
85 bool SystemSupportsTCPFastOpen() {
86 const base::FilePath::CharType kTCPFastOpenProcFilePath
[] =
87 "/proc/sys/net/ipv4/tcp_fastopen";
88 std::string system_supports_tcp_fastopen
;
89 if (!base::ReadFileToString(base::FilePath(kTCPFastOpenProcFilePath
),
90 &system_supports_tcp_fastopen
)) {
93 // The read from /proc should return '1' if TCP FastOpen is enabled in the OS.
94 if (system_supports_tcp_fastopen
.empty() ||
95 (system_supports_tcp_fastopen
[0] != '1')) {
101 void RegisterTCPFastOpenIntentAndSupport(bool user_enabled
,
102 bool system_supported
) {
103 g_tcp_fastopen_supported
= system_supported
;
104 g_tcp_fastopen_user_enabled
= user_enabled
;
110 //-----------------------------------------------------------------------------
112 bool IsTCPFastOpenSupported() {
113 return g_tcp_fastopen_supported
;
116 bool IsTCPFastOpenUserEnabled() {
117 return g_tcp_fastopen_user_enabled
;
120 // This is asynchronous because it needs to do file IO, and it isn't allowed to
121 // do that on the IO thread.
122 void CheckSupportAndMaybeEnableTCPFastOpen(bool user_enabled
) {
123 #if defined(OS_LINUX) || defined(OS_ANDROID)
124 base::PostTaskAndReplyWithResult(
125 base::WorkerPool::GetTaskRunner(/*task_is_slow=*/false).get(),
127 base::Bind(SystemSupportsTCPFastOpen
),
128 base::Bind(RegisterTCPFastOpenIntentAndSupport
, user_enabled
));
132 TCPSocketLibevent::TCPSocketLibevent(NetLog
* net_log
,
133 const NetLog::Source
& source
)
134 : use_tcp_fastopen_(false),
135 tcp_fastopen_write_attempted_(false),
136 tcp_fastopen_connected_(false),
137 tcp_fastopen_status_(TCP_FASTOPEN_STATUS_UNKNOWN
),
138 logging_multiple_connect_attempts_(false),
139 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_SOCKET
)) {
140 net_log_
.BeginEvent(NetLog::TYPE_SOCKET_ALIVE
,
141 source
.ToEventParametersCallback());
144 TCPSocketLibevent::~TCPSocketLibevent() {
145 net_log_
.EndEvent(NetLog::TYPE_SOCKET_ALIVE
);
149 int TCPSocketLibevent::Open(AddressFamily family
) {
151 socket_
.reset(new SocketLibevent
);
152 int rv
= socket_
->Open(ConvertAddressFamily(family
));
158 int TCPSocketLibevent::AdoptConnectedSocket(int socket_fd
,
159 const IPEndPoint
& peer_address
) {
162 SockaddrStorage storage
;
163 if (!peer_address
.ToSockAddr(storage
.addr
, &storage
.addr_len
) &&
164 // For backward compatibility, allows the empty address.
165 !(peer_address
== IPEndPoint())) {
166 return ERR_ADDRESS_INVALID
;
169 socket_
.reset(new SocketLibevent
);
170 int rv
= socket_
->AdoptConnectedSocket(socket_fd
, storage
);
176 int TCPSocketLibevent::Bind(const IPEndPoint
& address
) {
179 SockaddrStorage storage
;
180 if (!address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
181 return ERR_ADDRESS_INVALID
;
183 return socket_
->Bind(storage
);
186 int TCPSocketLibevent::Listen(int backlog
) {
188 return socket_
->Listen(backlog
);
191 int TCPSocketLibevent::Accept(scoped_ptr
<TCPSocketLibevent
>* tcp_socket
,
193 const CompletionCallback
& callback
) {
195 DCHECK(!callback
.is_null());
197 DCHECK(!accept_socket_
);
199 net_log_
.BeginEvent(NetLog::TYPE_TCP_ACCEPT
);
201 int rv
= socket_
->Accept(
203 base::Bind(&TCPSocketLibevent::AcceptCompleted
,
204 base::Unretained(this), tcp_socket
, address
, callback
));
205 if (rv
!= ERR_IO_PENDING
)
206 rv
= HandleAcceptCompleted(tcp_socket
, address
, rv
);
210 int TCPSocketLibevent::Connect(const IPEndPoint
& address
,
211 const CompletionCallback
& callback
) {
214 if (!logging_multiple_connect_attempts_
)
215 LogConnectBegin(AddressList(address
));
217 net_log_
.BeginEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT
,
218 CreateNetLogIPEndPointCallback(&address
));
220 SockaddrStorage storage
;
221 if (!address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
222 return ERR_ADDRESS_INVALID
;
224 if (use_tcp_fastopen_
) {
225 // With TCP FastOpen, we pretend that the socket is connected.
226 DCHECK(!tcp_fastopen_write_attempted_
);
227 socket_
->SetPeerAddress(storage
);
231 int rv
= socket_
->Connect(storage
,
232 base::Bind(&TCPSocketLibevent::ConnectCompleted
,
233 base::Unretained(this), callback
));
234 if (rv
!= ERR_IO_PENDING
)
235 rv
= HandleConnectCompleted(rv
);
239 bool TCPSocketLibevent::IsConnected() const {
243 if (use_tcp_fastopen_
&& !tcp_fastopen_write_attempted_
&&
244 socket_
->HasPeerAddress()) {
245 // With TCP FastOpen, we pretend that the socket is connected.
246 // This allows GetPeerAddress() to return peer_address_.
250 return socket_
->IsConnected();
253 bool TCPSocketLibevent::IsConnectedAndIdle() const {
254 // TODO(wtc): should we also handle the TCP FastOpen case here,
255 // as we do in IsConnected()?
256 return socket_
&& socket_
->IsConnectedAndIdle();
259 int TCPSocketLibevent::Read(IOBuffer
* buf
,
261 const CompletionCallback
& callback
) {
263 DCHECK(!callback
.is_null());
265 int rv
= socket_
->Read(
267 base::Bind(&TCPSocketLibevent::ReadCompleted
,
268 // Grab a reference to |buf| so that ReadCompleted() can still
269 // use it when Read() completes, as otherwise, this transfers
270 // ownership of buf to socket.
271 base::Unretained(this), make_scoped_refptr(buf
), callback
));
272 if (rv
!= ERR_IO_PENDING
)
273 rv
= HandleReadCompleted(buf
, rv
);
277 int TCPSocketLibevent::Write(IOBuffer
* buf
,
279 const CompletionCallback
& callback
) {
281 DCHECK(!callback
.is_null());
283 CompletionCallback write_callback
=
284 base::Bind(&TCPSocketLibevent::WriteCompleted
,
285 // Grab a reference to |buf| so that WriteCompleted() can still
286 // use it when Write() completes, as otherwise, this transfers
287 // ownership of buf to socket.
288 base::Unretained(this), make_scoped_refptr(buf
), callback
);
291 if (use_tcp_fastopen_
&& !tcp_fastopen_write_attempted_
) {
292 rv
= TcpFastOpenWrite(buf
, buf_len
, write_callback
);
294 rv
= socket_
->Write(buf
, buf_len
, write_callback
);
297 if (rv
!= ERR_IO_PENDING
)
298 rv
= HandleWriteCompleted(buf
, rv
);
302 int TCPSocketLibevent::GetLocalAddress(IPEndPoint
* address
) const {
306 return ERR_SOCKET_NOT_CONNECTED
;
308 SockaddrStorage storage
;
309 int rv
= socket_
->GetLocalAddress(&storage
);
313 if (!address
->FromSockAddr(storage
.addr
, storage
.addr_len
))
314 return ERR_ADDRESS_INVALID
;
319 int TCPSocketLibevent::GetPeerAddress(IPEndPoint
* address
) const {
323 return ERR_SOCKET_NOT_CONNECTED
;
325 SockaddrStorage storage
;
326 int rv
= socket_
->GetPeerAddress(&storage
);
330 if (!address
->FromSockAddr(storage
.addr
, storage
.addr_len
))
331 return ERR_ADDRESS_INVALID
;
336 int TCPSocketLibevent::SetDefaultOptionsForServer() {
338 return SetAddressReuse(true);
341 void TCPSocketLibevent::SetDefaultOptionsForClient() {
344 // This mirrors the behaviour on Windows. See the comment in
345 // tcp_socket_win.cc after searching for "NODELAY".
346 // If SetTCPNoDelay fails, we don't care.
347 SetTCPNoDelay(socket_
->socket_fd(), true);
349 // TCP keep alive wakes up the radio, which is expensive on mobile. Do not
350 // enable it there. It's useful to prevent TCP middleboxes from timing out
351 // connection mappings. Packets for timed out connection mappings at
352 // middleboxes will either lead to:
353 // a) Middleboxes sending TCP RSTs. It's up to higher layers to check for this
354 // and retry. The HTTP network transaction code does this.
355 // b) Middleboxes just drop the unrecognized TCP packet. This leads to the TCP
356 // stack retransmitting packets per TCP stack retransmission timeouts, which
357 // are very high (on the order of seconds). Given the number of
358 // retransmissions required before killing the connection, this can lead to
359 // tens of seconds or even minutes of delay, depending on OS.
360 #if !defined(OS_ANDROID) && !defined(OS_IOS)
361 const int kTCPKeepAliveSeconds
= 45;
363 SetTCPKeepAlive(socket_
->socket_fd(), true, kTCPKeepAliveSeconds
);
367 int TCPSocketLibevent::SetAddressReuse(bool allow
) {
370 // SO_REUSEADDR is useful for server sockets to bind to a recently unbound
371 // port. When a socket is closed, the end point changes its state to TIME_WAIT
372 // and wait for 2 MSL (maximum segment lifetime) to ensure the remote peer
373 // acknowledges its closure. For server sockets, it is usually safe to
374 // bind to a TIME_WAIT end point immediately, which is a widely adopted
377 // Note that on *nix, SO_REUSEADDR does not enable the TCP socket to bind to
378 // an end point that is already bound by another socket. To do that one must
379 // set SO_REUSEPORT instead. This option is not provided on Linux prior
382 // SO_REUSEPORT is provided in MacOS X and iOS.
383 int boolean_value
= allow
? 1 : 0;
384 int rv
= setsockopt(socket_
->socket_fd(), SOL_SOCKET
, SO_REUSEADDR
,
385 &boolean_value
, sizeof(boolean_value
));
387 return MapSystemError(errno
);
391 int TCPSocketLibevent::SetReceiveBufferSize(int32 size
) {
393 int rv
= setsockopt(socket_
->socket_fd(), SOL_SOCKET
, SO_RCVBUF
,
394 reinterpret_cast<const char*>(&size
), sizeof(size
));
395 return (rv
== 0) ? OK
: MapSystemError(errno
);
398 int TCPSocketLibevent::SetSendBufferSize(int32 size
) {
400 int rv
= setsockopt(socket_
->socket_fd(), SOL_SOCKET
, SO_SNDBUF
,
401 reinterpret_cast<const char*>(&size
), sizeof(size
));
402 return (rv
== 0) ? OK
: MapSystemError(errno
);
405 bool TCPSocketLibevent::SetKeepAlive(bool enable
, int delay
) {
407 return SetTCPKeepAlive(socket_
->socket_fd(), enable
, delay
);
410 bool TCPSocketLibevent::SetNoDelay(bool no_delay
) {
412 return SetTCPNoDelay(socket_
->socket_fd(), no_delay
);
415 void TCPSocketLibevent::Close() {
418 // Record and reset TCP FastOpen state.
419 if (tcp_fastopen_write_attempted_
||
420 tcp_fastopen_status_
== TCP_FASTOPEN_PREVIOUSLY_FAILED
) {
421 UMA_HISTOGRAM_ENUMERATION("Net.TcpFastOpenSocketConnection",
422 tcp_fastopen_status_
, TCP_FASTOPEN_MAX_VALUE
);
424 use_tcp_fastopen_
= false;
425 tcp_fastopen_connected_
= false;
426 tcp_fastopen_write_attempted_
= false;
427 tcp_fastopen_status_
= TCP_FASTOPEN_STATUS_UNKNOWN
;
430 bool TCPSocketLibevent::UsingTCPFastOpen() const {
431 return use_tcp_fastopen_
;
434 void TCPSocketLibevent::EnableTCPFastOpenIfSupported() {
435 if (!IsTCPFastOpenSupported())
438 // Do not enable TCP FastOpen if it had previously failed.
439 // This check conservatively avoids middleboxes that may blackhole
440 // TCP FastOpen SYN+Data packets; on such a failure, subsequent sockets
441 // should not use TCP FastOpen.
442 if(!g_tcp_fastopen_has_failed
)
443 use_tcp_fastopen_
= true;
445 tcp_fastopen_status_
= TCP_FASTOPEN_PREVIOUSLY_FAILED
;
448 bool TCPSocketLibevent::IsValid() const {
449 return socket_
!= NULL
&& socket_
->socket_fd() != kInvalidSocket
;
452 void TCPSocketLibevent::StartLoggingMultipleConnectAttempts(
453 const AddressList
& addresses
) {
454 if (!logging_multiple_connect_attempts_
) {
455 logging_multiple_connect_attempts_
= true;
456 LogConnectBegin(addresses
);
462 void TCPSocketLibevent::EndLoggingMultipleConnectAttempts(int net_error
) {
463 if (logging_multiple_connect_attempts_
) {
464 LogConnectEnd(net_error
);
465 logging_multiple_connect_attempts_
= false;
471 void TCPSocketLibevent::AcceptCompleted(
472 scoped_ptr
<TCPSocketLibevent
>* tcp_socket
,
474 const CompletionCallback
& callback
,
476 DCHECK_NE(ERR_IO_PENDING
, rv
);
477 callback
.Run(HandleAcceptCompleted(tcp_socket
, address
, rv
));
480 int TCPSocketLibevent::HandleAcceptCompleted(
481 scoped_ptr
<TCPSocketLibevent
>* tcp_socket
,
485 rv
= BuildTcpSocketLibevent(tcp_socket
, address
);
488 net_log_
.EndEvent(NetLog::TYPE_TCP_ACCEPT
,
489 CreateNetLogIPEndPointCallback(address
));
491 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_TCP_ACCEPT
, rv
);
497 int TCPSocketLibevent::BuildTcpSocketLibevent(
498 scoped_ptr
<TCPSocketLibevent
>* tcp_socket
,
499 IPEndPoint
* address
) {
500 DCHECK(accept_socket_
);
502 SockaddrStorage storage
;
503 if (accept_socket_
->GetPeerAddress(&storage
) != OK
||
504 !address
->FromSockAddr(storage
.addr
, storage
.addr_len
)) {
505 accept_socket_
.reset();
506 return ERR_ADDRESS_INVALID
;
509 tcp_socket
->reset(new TCPSocketLibevent(net_log_
.net_log(),
511 (*tcp_socket
)->socket_
.reset(accept_socket_
.release());
515 void TCPSocketLibevent::ConnectCompleted(const CompletionCallback
& callback
,
517 DCHECK_NE(ERR_IO_PENDING
, rv
);
518 callback
.Run(HandleConnectCompleted(rv
));
521 int TCPSocketLibevent::HandleConnectCompleted(int rv
) const {
522 // Log the end of this attempt (and any OS error it threw).
524 net_log_
.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT
,
525 NetLog::IntegerCallback("os_error", errno
));
527 net_log_
.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT
);
530 // Give a more specific error when the user is offline.
531 if (rv
== ERR_ADDRESS_UNREACHABLE
&& NetworkChangeNotifier::IsOffline())
532 rv
= ERR_INTERNET_DISCONNECTED
;
534 if (!logging_multiple_connect_attempts_
)
540 void TCPSocketLibevent::LogConnectBegin(const AddressList
& addresses
) const {
541 base::StatsCounter
connects("tcp.connect");
542 connects
.Increment();
544 net_log_
.BeginEvent(NetLog::TYPE_TCP_CONNECT
,
545 addresses
.CreateNetLogCallback());
548 void TCPSocketLibevent::LogConnectEnd(int net_error
) const {
549 if (net_error
!= OK
) {
550 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT
, net_error
);
554 UpdateConnectionTypeHistograms(CONNECTION_ANY
);
556 SockaddrStorage storage
;
557 int rv
= socket_
->GetLocalAddress(&storage
);
559 PLOG(ERROR
) << "GetLocalAddress() [rv: " << rv
<< "] error: ";
561 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT
, rv
);
565 net_log_
.EndEvent(NetLog::TYPE_TCP_CONNECT
,
566 CreateNetLogSourceAddressCallback(storage
.addr
,
570 void TCPSocketLibevent::ReadCompleted(const scoped_refptr
<IOBuffer
>& buf
,
571 const CompletionCallback
& callback
,
573 DCHECK_NE(ERR_IO_PENDING
, rv
);
574 callback
.Run(HandleReadCompleted(buf
.get(), rv
));
577 int TCPSocketLibevent::HandleReadCompleted(IOBuffer
* buf
, int rv
) {
578 if (tcp_fastopen_write_attempted_
&& !tcp_fastopen_connected_
) {
579 // A TCP FastOpen connect-with-write was attempted. This read was a
580 // subsequent read, which either succeeded or failed. If the read
581 // succeeded, the socket is considered connected via TCP FastOpen.
582 // If the read failed, TCP FastOpen is (conservatively) turned off for all
583 // subsequent connections. TCP FastOpen status is recorded in both cases.
584 // TODO (jri): This currently results in conservative behavior, where TCP
585 // FastOpen is turned off on _any_ error. Implement optimizations,
586 // such as turning off TCP FastOpen on more specific errors, and
587 // re-attempting TCP FastOpen after a certain amount of time has passed.
589 tcp_fastopen_connected_
= true;
591 g_tcp_fastopen_has_failed
= true;
592 UpdateTCPFastOpenStatusAfterRead();
596 net_log_
.AddEvent(NetLog::TYPE_SOCKET_READ_ERROR
,
597 CreateNetLogSocketErrorCallback(rv
, errno
));
601 base::StatsCounter
read_bytes("tcp.read_bytes");
603 net_log_
.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_RECEIVED
, rv
,
605 NetworkActivityMonitor::GetInstance()->IncrementBytesReceived(rv
);
610 void TCPSocketLibevent::WriteCompleted(const scoped_refptr
<IOBuffer
>& buf
,
611 const CompletionCallback
& callback
,
613 DCHECK_NE(ERR_IO_PENDING
, rv
);
614 callback
.Run(HandleWriteCompleted(buf
.get(), rv
));
617 int TCPSocketLibevent::HandleWriteCompleted(IOBuffer
* buf
, int rv
) {
619 if (tcp_fastopen_write_attempted_
&& !tcp_fastopen_connected_
) {
620 // TCP FastOpen connect-with-write was attempted, and the write failed
621 // for unknown reasons. Record status and (conservatively) turn off
622 // TCP FastOpen for all subsequent connections.
623 // TODO (jri): This currently results in conservative behavior, where TCP
624 // FastOpen is turned off on _any_ error. Implement optimizations,
625 // such as turning off TCP FastOpen on more specific errors, and
626 // re-attempting TCP FastOpen after a certain amount of time has passed.
627 tcp_fastopen_status_
= TCP_FASTOPEN_ERROR
;
628 g_tcp_fastopen_has_failed
= true;
630 net_log_
.AddEvent(NetLog::TYPE_SOCKET_WRITE_ERROR
,
631 CreateNetLogSocketErrorCallback(rv
, errno
));
635 base::StatsCounter
write_bytes("tcp.write_bytes");
637 net_log_
.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_SENT
, rv
,
639 NetworkActivityMonitor::GetInstance()->IncrementBytesSent(rv
);
643 int TCPSocketLibevent::TcpFastOpenWrite(
646 const CompletionCallback
& callback
) {
647 SockaddrStorage storage
;
648 int rv
= socket_
->GetPeerAddress(&storage
);
652 int flags
= 0x20000000; // Magic flag to enable TCP_FASTOPEN.
653 #if defined(OS_LINUX) || defined(OS_ANDROID)
654 // sendto() will fail with EPIPE when the system doesn't implement TCP
655 // FastOpen, and with EOPNOTSUPP when the system implements TCP FastOpen
656 // but it is disabled. Theoretically these shouldn't happen
657 // since the caller should check for system support on startup, but
658 // users may dynamically disable TCP FastOpen via sysctl.
659 flags
|= MSG_NOSIGNAL
;
660 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
661 rv
= HANDLE_EINTR(sendto(socket_
->socket_fd(),
667 tcp_fastopen_write_attempted_
= true;
670 tcp_fastopen_status_
= TCP_FASTOPEN_FAST_CONNECT_RETURN
;
674 DCHECK_NE(EPIPE
, errno
);
676 // If errno == EINPROGRESS, that means the kernel didn't have a cookie
677 // and would block. The kernel is internally doing a connect() though.
678 // Remap EINPROGRESS to EAGAIN so we treat this the same as our other
679 // asynchronous cases. Note that the user buffer has not been copied to
681 if (errno
== EINPROGRESS
) {
684 rv
= MapSystemError(errno
);
687 if (rv
!= ERR_IO_PENDING
) {
688 // TCP FastOpen connect-with-write was attempted, and the write failed
689 // since TCP FastOpen was not implemented or disabled in the OS.
690 // Record status and turn off TCP FastOpen for all subsequent connections.
691 // TODO (jri): This is almost certainly too conservative, since it blanket
692 // turns off TCP FastOpen on any write error. Two things need to be done
693 // here: (i) record a histogram of write errors; in particular, record
694 // occurrences of EOPNOTSUPP and EPIPE, and (ii) afterwards, consider
695 // turning off TCP FastOpen on more specific errors.
696 tcp_fastopen_status_
= TCP_FASTOPEN_ERROR
;
697 g_tcp_fastopen_has_failed
= true;
701 tcp_fastopen_status_
= TCP_FASTOPEN_SLOW_CONNECT_RETURN
;
702 return socket_
->WaitForWrite(buf
, buf_len
, callback
);
705 void TCPSocketLibevent::UpdateTCPFastOpenStatusAfterRead() {
706 DCHECK(tcp_fastopen_status_
== TCP_FASTOPEN_FAST_CONNECT_RETURN
||
707 tcp_fastopen_status_
== TCP_FASTOPEN_SLOW_CONNECT_RETURN
);
709 if (tcp_fastopen_write_attempted_
&& !tcp_fastopen_connected_
) {
710 // TCP FastOpen connect-with-write was attempted, and failed.
711 tcp_fastopen_status_
=
712 (tcp_fastopen_status_
== TCP_FASTOPEN_FAST_CONNECT_RETURN
?
713 TCP_FASTOPEN_FAST_CONNECT_READ_FAILED
:
714 TCP_FASTOPEN_SLOW_CONNECT_READ_FAILED
);
718 bool getsockopt_success
= false;
719 bool server_acked_data
= false;
720 #if defined(TCP_INFO)
721 // Probe to see the if the socket used TCP FastOpen.
723 socklen_t info_len
= sizeof(tcp_info
);
724 getsockopt_success
= getsockopt(socket_
->socket_fd(), IPPROTO_TCP
, TCP_INFO
,
725 &info
, &info_len
) == 0 &&
726 info_len
== sizeof(tcp_info
);
727 server_acked_data
= getsockopt_success
&&
728 (info
.tcpi_options
& TCPI_OPT_SYN_DATA
);
731 if (getsockopt_success
) {
732 if (tcp_fastopen_status_
== TCP_FASTOPEN_FAST_CONNECT_RETURN
) {
733 tcp_fastopen_status_
= (server_acked_data
?
734 TCP_FASTOPEN_SYN_DATA_ACK
:
735 TCP_FASTOPEN_SYN_DATA_NACK
);
737 tcp_fastopen_status_
= (server_acked_data
?
738 TCP_FASTOPEN_NO_SYN_DATA_ACK
:
739 TCP_FASTOPEN_NO_SYN_DATA_NACK
);
742 tcp_fastopen_status_
=
743 (tcp_fastopen_status_
== TCP_FASTOPEN_FAST_CONNECT_RETURN
?
744 TCP_FASTOPEN_SYN_DATA_GETSOCKOPT_FAILED
:
745 TCP_FASTOPEN_NO_SYN_DATA_GETSOCKOPT_FAILED
);