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/files/file_path.h"
13 #include "base/files/file_util.h"
14 #include "base/logging.h"
15 #include "base/metrics/histogram.h"
16 #include "base/posix/eintr_wrapper.h"
17 #include "base/task_runner_util.h"
18 #include "base/threading/worker_pool.h"
19 #include "net/base/address_list.h"
20 #include "net/base/connection_type_histograms.h"
21 #include "net/base/io_buffer.h"
22 #include "net/base/ip_endpoint.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/net_util.h"
25 #include "net/base/network_activity_monitor.h"
26 #include "net/base/network_change_notifier.h"
27 #include "net/socket/socket_libevent.h"
28 #include "net/socket/socket_net_log_params.h"
30 // If we don't have a definition for TCPI_OPT_SYN_DATA, create one.
31 #ifndef TCPI_OPT_SYN_DATA
32 #define TCPI_OPT_SYN_DATA 32
39 // True if OS supports TCP FastOpen.
40 bool g_tcp_fastopen_supported
= false;
41 // True if TCP FastOpen is user-enabled for all connections.
42 // TODO(jri): Change global variable to param in HttpNetworkSession::Params.
43 bool g_tcp_fastopen_user_enabled
= false;
44 // True if TCP FastOpen connect-with-write has failed at least once.
45 bool g_tcp_fastopen_has_failed
= false;
47 // SetTCPNoDelay turns on/off buffering in the kernel. By default, TCP sockets
48 // will wait up to 200ms for more data to complete a packet before transmitting.
49 // After calling this function, the kernel will not wait. See TCP_NODELAY in
51 bool SetTCPNoDelay(int fd
, bool no_delay
) {
52 int on
= no_delay
? 1 : 0;
53 int error
= setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, &on
, sizeof(on
));
57 // SetTCPKeepAlive sets SO_KEEPALIVE.
58 bool SetTCPKeepAlive(int fd
, bool enable
, int delay
) {
59 int on
= enable
? 1 : 0;
60 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, &on
, sizeof(on
))) {
61 PLOG(ERROR
) << "Failed to set SO_KEEPALIVE on fd: " << fd
;
65 // If we disabled TCP keep alive, our work is done here.
69 #if defined(OS_LINUX) || defined(OS_ANDROID)
70 // Set seconds until first TCP keep alive.
71 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPIDLE
, &delay
, sizeof(delay
))) {
72 PLOG(ERROR
) << "Failed to set TCP_KEEPIDLE on fd: " << fd
;
75 // Set seconds between TCP keep alives.
76 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPINTVL
, &delay
, sizeof(delay
))) {
77 PLOG(ERROR
) << "Failed to set TCP_KEEPINTVL on fd: " << fd
;
84 #if defined(OS_LINUX) || defined(OS_ANDROID)
85 // Checks if the kernel supports TCP FastOpen.
86 bool SystemSupportsTCPFastOpen() {
87 const base::FilePath::CharType kTCPFastOpenProcFilePath
[] =
88 "/proc/sys/net/ipv4/tcp_fastopen";
89 std::string system_supports_tcp_fastopen
;
90 if (!base::ReadFileToString(base::FilePath(kTCPFastOpenProcFilePath
),
91 &system_supports_tcp_fastopen
)) {
94 // The read from /proc should return '1' if TCP FastOpen is enabled in the OS.
95 if (system_supports_tcp_fastopen
.empty() ||
96 (system_supports_tcp_fastopen
[0] != '1')) {
102 void RegisterTCPFastOpenIntentAndSupport(bool user_enabled
,
103 bool system_supported
) {
104 g_tcp_fastopen_supported
= system_supported
;
105 g_tcp_fastopen_user_enabled
= user_enabled
;
111 //-----------------------------------------------------------------------------
113 bool IsTCPFastOpenSupported() {
114 return g_tcp_fastopen_supported
;
117 bool IsTCPFastOpenUserEnabled() {
118 return g_tcp_fastopen_user_enabled
;
121 // This is asynchronous because it needs to do file IO, and it isn't allowed to
122 // do that on the IO thread.
123 void CheckSupportAndMaybeEnableTCPFastOpen(bool user_enabled
) {
124 #if defined(OS_LINUX) || defined(OS_ANDROID)
125 base::PostTaskAndReplyWithResult(
126 base::WorkerPool::GetTaskRunner(/*task_is_slow=*/false).get(),
128 base::Bind(SystemSupportsTCPFastOpen
),
129 base::Bind(RegisterTCPFastOpenIntentAndSupport
, user_enabled
));
133 TCPSocketLibevent::TCPSocketLibevent(NetLog
* net_log
,
134 const NetLog::Source
& source
)
135 : use_tcp_fastopen_(false),
136 tcp_fastopen_write_attempted_(false),
137 tcp_fastopen_connected_(false),
138 tcp_fastopen_status_(TCP_FASTOPEN_STATUS_UNKNOWN
),
139 logging_multiple_connect_attempts_(false),
140 net_log_(BoundNetLog::Make(net_log
, NetLog::SOURCE_SOCKET
)) {
141 net_log_
.BeginEvent(NetLog::TYPE_SOCKET_ALIVE
,
142 source
.ToEventParametersCallback());
145 TCPSocketLibevent::~TCPSocketLibevent() {
146 net_log_
.EndEvent(NetLog::TYPE_SOCKET_ALIVE
);
150 int TCPSocketLibevent::Open(AddressFamily family
) {
152 socket_
.reset(new SocketLibevent
);
153 int rv
= socket_
->Open(ConvertAddressFamily(family
));
159 int TCPSocketLibevent::AdoptConnectedSocket(int socket_fd
,
160 const IPEndPoint
& peer_address
) {
163 SockaddrStorage storage
;
164 if (!peer_address
.ToSockAddr(storage
.addr
, &storage
.addr_len
) &&
165 // For backward compatibility, allows the empty address.
166 !(peer_address
== IPEndPoint())) {
167 return ERR_ADDRESS_INVALID
;
170 socket_
.reset(new SocketLibevent
);
171 int rv
= socket_
->AdoptConnectedSocket(socket_fd
, storage
);
177 int TCPSocketLibevent::Bind(const IPEndPoint
& address
) {
180 SockaddrStorage storage
;
181 if (!address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
182 return ERR_ADDRESS_INVALID
;
184 return socket_
->Bind(storage
);
187 int TCPSocketLibevent::Listen(int backlog
) {
189 return socket_
->Listen(backlog
);
192 int TCPSocketLibevent::Accept(scoped_ptr
<TCPSocketLibevent
>* tcp_socket
,
194 const CompletionCallback
& callback
) {
196 DCHECK(!callback
.is_null());
198 DCHECK(!accept_socket_
);
200 net_log_
.BeginEvent(NetLog::TYPE_TCP_ACCEPT
);
202 int rv
= socket_
->Accept(
204 base::Bind(&TCPSocketLibevent::AcceptCompleted
,
205 base::Unretained(this), tcp_socket
, address
, callback
));
206 if (rv
!= ERR_IO_PENDING
)
207 rv
= HandleAcceptCompleted(tcp_socket
, address
, rv
);
211 int TCPSocketLibevent::Connect(const IPEndPoint
& address
,
212 const CompletionCallback
& callback
) {
215 if (!logging_multiple_connect_attempts_
)
216 LogConnectBegin(AddressList(address
));
218 net_log_
.BeginEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT
,
219 CreateNetLogIPEndPointCallback(&address
));
221 SockaddrStorage storage
;
222 if (!address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
223 return ERR_ADDRESS_INVALID
;
225 if (use_tcp_fastopen_
) {
226 // With TCP FastOpen, we pretend that the socket is connected.
227 DCHECK(!tcp_fastopen_write_attempted_
);
228 socket_
->SetPeerAddress(storage
);
232 int rv
= socket_
->Connect(storage
,
233 base::Bind(&TCPSocketLibevent::ConnectCompleted
,
234 base::Unretained(this), callback
));
235 if (rv
!= ERR_IO_PENDING
)
236 rv
= HandleConnectCompleted(rv
);
240 bool TCPSocketLibevent::IsConnected() const {
244 if (use_tcp_fastopen_
&& !tcp_fastopen_write_attempted_
&&
245 socket_
->HasPeerAddress()) {
246 // With TCP FastOpen, we pretend that the socket is connected.
247 // This allows GetPeerAddress() to return peer_address_.
251 return socket_
->IsConnected();
254 bool TCPSocketLibevent::IsConnectedAndIdle() const {
255 // TODO(wtc): should we also handle the TCP FastOpen case here,
256 // as we do in IsConnected()?
257 return socket_
&& socket_
->IsConnectedAndIdle();
260 int TCPSocketLibevent::Read(IOBuffer
* buf
,
262 const CompletionCallback
& callback
) {
264 DCHECK(!callback
.is_null());
266 int rv
= socket_
->Read(
268 base::Bind(&TCPSocketLibevent::ReadCompleted
,
269 // Grab a reference to |buf| so that ReadCompleted() can still
270 // use it when Read() completes, as otherwise, this transfers
271 // ownership of buf to socket.
272 base::Unretained(this), make_scoped_refptr(buf
), callback
));
273 if (rv
!= ERR_IO_PENDING
)
274 rv
= HandleReadCompleted(buf
, rv
);
278 int TCPSocketLibevent::Write(IOBuffer
* buf
,
280 const CompletionCallback
& callback
) {
282 DCHECK(!callback
.is_null());
284 CompletionCallback write_callback
=
285 base::Bind(&TCPSocketLibevent::WriteCompleted
,
286 // Grab a reference to |buf| so that WriteCompleted() can still
287 // use it when Write() completes, as otherwise, this transfers
288 // ownership of buf to socket.
289 base::Unretained(this), make_scoped_refptr(buf
), callback
);
292 if (use_tcp_fastopen_
&& !tcp_fastopen_write_attempted_
) {
293 rv
= TcpFastOpenWrite(buf
, buf_len
, write_callback
);
295 rv
= socket_
->Write(buf
, buf_len
, write_callback
);
298 if (rv
!= ERR_IO_PENDING
)
299 rv
= HandleWriteCompleted(buf
, rv
);
303 int TCPSocketLibevent::GetLocalAddress(IPEndPoint
* address
) const {
307 return ERR_SOCKET_NOT_CONNECTED
;
309 SockaddrStorage storage
;
310 int rv
= socket_
->GetLocalAddress(&storage
);
314 if (!address
->FromSockAddr(storage
.addr
, storage
.addr_len
))
315 return ERR_ADDRESS_INVALID
;
320 int TCPSocketLibevent::GetPeerAddress(IPEndPoint
* address
) const {
324 return ERR_SOCKET_NOT_CONNECTED
;
326 SockaddrStorage storage
;
327 int rv
= socket_
->GetPeerAddress(&storage
);
331 if (!address
->FromSockAddr(storage
.addr
, storage
.addr_len
))
332 return ERR_ADDRESS_INVALID
;
337 int TCPSocketLibevent::SetDefaultOptionsForServer() {
339 return SetAddressReuse(true);
342 void TCPSocketLibevent::SetDefaultOptionsForClient() {
345 // This mirrors the behaviour on Windows. See the comment in
346 // tcp_socket_win.cc after searching for "NODELAY".
347 // If SetTCPNoDelay fails, we don't care.
348 SetTCPNoDelay(socket_
->socket_fd(), true);
350 // TCP keep alive wakes up the radio, which is expensive on mobile. Do not
351 // enable it there. It's useful to prevent TCP middleboxes from timing out
352 // connection mappings. Packets for timed out connection mappings at
353 // middleboxes will either lead to:
354 // a) Middleboxes sending TCP RSTs. It's up to higher layers to check for this
355 // and retry. The HTTP network transaction code does this.
356 // b) Middleboxes just drop the unrecognized TCP packet. This leads to the TCP
357 // stack retransmitting packets per TCP stack retransmission timeouts, which
358 // are very high (on the order of seconds). Given the number of
359 // retransmissions required before killing the connection, this can lead to
360 // tens of seconds or even minutes of delay, depending on OS.
361 #if !defined(OS_ANDROID) && !defined(OS_IOS)
362 const int kTCPKeepAliveSeconds
= 45;
364 SetTCPKeepAlive(socket_
->socket_fd(), true, kTCPKeepAliveSeconds
);
368 int TCPSocketLibevent::SetAddressReuse(bool allow
) {
371 // SO_REUSEADDR is useful for server sockets to bind to a recently unbound
372 // port. When a socket is closed, the end point changes its state to TIME_WAIT
373 // and wait for 2 MSL (maximum segment lifetime) to ensure the remote peer
374 // acknowledges its closure. For server sockets, it is usually safe to
375 // bind to a TIME_WAIT end point immediately, which is a widely adopted
378 // Note that on *nix, SO_REUSEADDR does not enable the TCP socket to bind to
379 // an end point that is already bound by another socket. To do that one must
380 // set SO_REUSEPORT instead. This option is not provided on Linux prior
383 // SO_REUSEPORT is provided in MacOS X and iOS.
384 int boolean_value
= allow
? 1 : 0;
385 int rv
= setsockopt(socket_
->socket_fd(), SOL_SOCKET
, SO_REUSEADDR
,
386 &boolean_value
, sizeof(boolean_value
));
388 return MapSystemError(errno
);
392 int TCPSocketLibevent::SetReceiveBufferSize(int32 size
) {
394 int rv
= setsockopt(socket_
->socket_fd(), SOL_SOCKET
, SO_RCVBUF
,
395 reinterpret_cast<const char*>(&size
), sizeof(size
));
396 return (rv
== 0) ? OK
: MapSystemError(errno
);
399 int TCPSocketLibevent::SetSendBufferSize(int32 size
) {
401 int rv
= setsockopt(socket_
->socket_fd(), SOL_SOCKET
, SO_SNDBUF
,
402 reinterpret_cast<const char*>(&size
), sizeof(size
));
403 return (rv
== 0) ? OK
: MapSystemError(errno
);
406 bool TCPSocketLibevent::SetKeepAlive(bool enable
, int delay
) {
408 return SetTCPKeepAlive(socket_
->socket_fd(), enable
, delay
);
411 bool TCPSocketLibevent::SetNoDelay(bool no_delay
) {
413 return SetTCPNoDelay(socket_
->socket_fd(), no_delay
);
416 void TCPSocketLibevent::Close() {
419 // Record and reset TCP FastOpen state.
420 if (tcp_fastopen_write_attempted_
||
421 tcp_fastopen_status_
== TCP_FASTOPEN_PREVIOUSLY_FAILED
) {
422 UMA_HISTOGRAM_ENUMERATION("Net.TcpFastOpenSocketConnection",
423 tcp_fastopen_status_
, TCP_FASTOPEN_MAX_VALUE
);
425 use_tcp_fastopen_
= false;
426 tcp_fastopen_connected_
= false;
427 tcp_fastopen_write_attempted_
= false;
428 tcp_fastopen_status_
= TCP_FASTOPEN_STATUS_UNKNOWN
;
431 bool TCPSocketLibevent::UsingTCPFastOpen() const {
432 return use_tcp_fastopen_
;
435 void TCPSocketLibevent::EnableTCPFastOpenIfSupported() {
436 if (!IsTCPFastOpenSupported())
439 // Do not enable TCP FastOpen if it had previously failed.
440 // This check conservatively avoids middleboxes that may blackhole
441 // TCP FastOpen SYN+Data packets; on such a failure, subsequent sockets
442 // should not use TCP FastOpen.
443 if(!g_tcp_fastopen_has_failed
)
444 use_tcp_fastopen_
= true;
446 tcp_fastopen_status_
= TCP_FASTOPEN_PREVIOUSLY_FAILED
;
449 bool TCPSocketLibevent::IsValid() const {
450 return socket_
!= NULL
&& socket_
->socket_fd() != kInvalidSocket
;
453 void TCPSocketLibevent::StartLoggingMultipleConnectAttempts(
454 const AddressList
& addresses
) {
455 if (!logging_multiple_connect_attempts_
) {
456 logging_multiple_connect_attempts_
= true;
457 LogConnectBegin(addresses
);
463 void TCPSocketLibevent::EndLoggingMultipleConnectAttempts(int net_error
) {
464 if (logging_multiple_connect_attempts_
) {
465 LogConnectEnd(net_error
);
466 logging_multiple_connect_attempts_
= false;
472 void TCPSocketLibevent::AcceptCompleted(
473 scoped_ptr
<TCPSocketLibevent
>* tcp_socket
,
475 const CompletionCallback
& callback
,
477 DCHECK_NE(ERR_IO_PENDING
, rv
);
478 callback
.Run(HandleAcceptCompleted(tcp_socket
, address
, rv
));
481 int TCPSocketLibevent::HandleAcceptCompleted(
482 scoped_ptr
<TCPSocketLibevent
>* tcp_socket
,
486 rv
= BuildTcpSocketLibevent(tcp_socket
, address
);
489 net_log_
.EndEvent(NetLog::TYPE_TCP_ACCEPT
,
490 CreateNetLogIPEndPointCallback(address
));
492 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_TCP_ACCEPT
, rv
);
498 int TCPSocketLibevent::BuildTcpSocketLibevent(
499 scoped_ptr
<TCPSocketLibevent
>* tcp_socket
,
500 IPEndPoint
* address
) {
501 DCHECK(accept_socket_
);
503 SockaddrStorage storage
;
504 if (accept_socket_
->GetPeerAddress(&storage
) != OK
||
505 !address
->FromSockAddr(storage
.addr
, storage
.addr_len
)) {
506 accept_socket_
.reset();
507 return ERR_ADDRESS_INVALID
;
510 tcp_socket
->reset(new TCPSocketLibevent(net_log_
.net_log(),
512 (*tcp_socket
)->socket_
.reset(accept_socket_
.release());
516 void TCPSocketLibevent::ConnectCompleted(const CompletionCallback
& callback
,
518 DCHECK_NE(ERR_IO_PENDING
, rv
);
519 callback
.Run(HandleConnectCompleted(rv
));
522 int TCPSocketLibevent::HandleConnectCompleted(int rv
) const {
523 // Log the end of this attempt (and any OS error it threw).
525 net_log_
.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT
,
526 NetLog::IntegerCallback("os_error", errno
));
528 net_log_
.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT
);
531 // Give a more specific error when the user is offline.
532 if (rv
== ERR_ADDRESS_UNREACHABLE
&& NetworkChangeNotifier::IsOffline())
533 rv
= ERR_INTERNET_DISCONNECTED
;
535 if (!logging_multiple_connect_attempts_
)
541 void TCPSocketLibevent::LogConnectBegin(const AddressList
& addresses
) const {
542 net_log_
.BeginEvent(NetLog::TYPE_TCP_CONNECT
,
543 addresses
.CreateNetLogCallback());
546 void TCPSocketLibevent::LogConnectEnd(int net_error
) const {
547 if (net_error
!= OK
) {
548 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT
, net_error
);
552 UpdateConnectionTypeHistograms(CONNECTION_ANY
);
554 SockaddrStorage storage
;
555 int rv
= socket_
->GetLocalAddress(&storage
);
557 PLOG(ERROR
) << "GetLocalAddress() [rv: " << rv
<< "] error: ";
559 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT
, rv
);
563 net_log_
.EndEvent(NetLog::TYPE_TCP_CONNECT
,
564 CreateNetLogSourceAddressCallback(storage
.addr
,
568 void TCPSocketLibevent::ReadCompleted(const scoped_refptr
<IOBuffer
>& buf
,
569 const CompletionCallback
& callback
,
571 DCHECK_NE(ERR_IO_PENDING
, rv
);
572 callback
.Run(HandleReadCompleted(buf
.get(), rv
));
575 int TCPSocketLibevent::HandleReadCompleted(IOBuffer
* buf
, int rv
) {
576 if (tcp_fastopen_write_attempted_
&& !tcp_fastopen_connected_
) {
577 // A TCP FastOpen connect-with-write was attempted. This read was a
578 // subsequent read, which either succeeded or failed. If the read
579 // succeeded, the socket is considered connected via TCP FastOpen.
580 // If the read failed, TCP FastOpen is (conservatively) turned off for all
581 // subsequent connections. TCP FastOpen status is recorded in both cases.
582 // TODO (jri): This currently results in conservative behavior, where TCP
583 // FastOpen is turned off on _any_ error. Implement optimizations,
584 // such as turning off TCP FastOpen on more specific errors, and
585 // re-attempting TCP FastOpen after a certain amount of time has passed.
587 tcp_fastopen_connected_
= true;
589 g_tcp_fastopen_has_failed
= true;
590 UpdateTCPFastOpenStatusAfterRead();
594 net_log_
.AddEvent(NetLog::TYPE_SOCKET_READ_ERROR
,
595 CreateNetLogSocketErrorCallback(rv
, errno
));
598 net_log_
.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_RECEIVED
, rv
,
600 NetworkActivityMonitor::GetInstance()->IncrementBytesReceived(rv
);
605 void TCPSocketLibevent::WriteCompleted(const scoped_refptr
<IOBuffer
>& buf
,
606 const CompletionCallback
& callback
,
608 DCHECK_NE(ERR_IO_PENDING
, rv
);
609 callback
.Run(HandleWriteCompleted(buf
.get(), rv
));
612 int TCPSocketLibevent::HandleWriteCompleted(IOBuffer
* buf
, int rv
) {
614 if (tcp_fastopen_write_attempted_
&& !tcp_fastopen_connected_
) {
615 // TCP FastOpen connect-with-write was attempted, and the write failed
616 // for unknown reasons. Record status and (conservatively) turn off
617 // TCP FastOpen for all subsequent connections.
618 // TODO (jri): This currently results in conservative behavior, where TCP
619 // FastOpen is turned off on _any_ error. Implement optimizations,
620 // such as turning off TCP FastOpen on more specific errors, and
621 // re-attempting TCP FastOpen after a certain amount of time has passed.
622 tcp_fastopen_status_
= TCP_FASTOPEN_ERROR
;
623 g_tcp_fastopen_has_failed
= true;
625 net_log_
.AddEvent(NetLog::TYPE_SOCKET_WRITE_ERROR
,
626 CreateNetLogSocketErrorCallback(rv
, errno
));
629 net_log_
.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_SENT
, rv
,
631 NetworkActivityMonitor::GetInstance()->IncrementBytesSent(rv
);
635 int TCPSocketLibevent::TcpFastOpenWrite(
638 const CompletionCallback
& callback
) {
639 SockaddrStorage storage
;
640 int rv
= socket_
->GetPeerAddress(&storage
);
644 int flags
= 0x20000000; // Magic flag to enable TCP_FASTOPEN.
645 #if defined(OS_LINUX) || defined(OS_ANDROID)
646 // sendto() will fail with EPIPE when the system doesn't implement TCP
647 // FastOpen, and with EOPNOTSUPP when the system implements TCP FastOpen
648 // but it is disabled. Theoretically these shouldn't happen
649 // since the caller should check for system support on startup, but
650 // users may dynamically disable TCP FastOpen via sysctl.
651 flags
|= MSG_NOSIGNAL
;
652 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
653 rv
= HANDLE_EINTR(sendto(socket_
->socket_fd(),
659 tcp_fastopen_write_attempted_
= true;
662 tcp_fastopen_status_
= TCP_FASTOPEN_FAST_CONNECT_RETURN
;
666 DCHECK_NE(EPIPE
, errno
);
668 // If errno == EINPROGRESS, that means the kernel didn't have a cookie
669 // and would block. The kernel is internally doing a connect() though.
670 // Remap EINPROGRESS to EAGAIN so we treat this the same as our other
671 // asynchronous cases. Note that the user buffer has not been copied to
673 if (errno
== EINPROGRESS
) {
676 rv
= MapSystemError(errno
);
679 if (rv
!= ERR_IO_PENDING
) {
680 // TCP FastOpen connect-with-write was attempted, and the write failed
681 // since TCP FastOpen was not implemented or disabled in the OS.
682 // Record status and turn off TCP FastOpen for all subsequent connections.
683 // TODO (jri): This is almost certainly too conservative, since it blanket
684 // turns off TCP FastOpen on any write error. Two things need to be done
685 // here: (i) record a histogram of write errors; in particular, record
686 // occurrences of EOPNOTSUPP and EPIPE, and (ii) afterwards, consider
687 // turning off TCP FastOpen on more specific errors.
688 tcp_fastopen_status_
= TCP_FASTOPEN_ERROR
;
689 g_tcp_fastopen_has_failed
= true;
693 tcp_fastopen_status_
= TCP_FASTOPEN_SLOW_CONNECT_RETURN
;
694 return socket_
->WaitForWrite(buf
, buf_len
, callback
);
697 void TCPSocketLibevent::UpdateTCPFastOpenStatusAfterRead() {
698 DCHECK(tcp_fastopen_status_
== TCP_FASTOPEN_FAST_CONNECT_RETURN
||
699 tcp_fastopen_status_
== TCP_FASTOPEN_SLOW_CONNECT_RETURN
);
701 if (tcp_fastopen_write_attempted_
&& !tcp_fastopen_connected_
) {
702 // TCP FastOpen connect-with-write was attempted, and failed.
703 tcp_fastopen_status_
=
704 (tcp_fastopen_status_
== TCP_FASTOPEN_FAST_CONNECT_RETURN
?
705 TCP_FASTOPEN_FAST_CONNECT_READ_FAILED
:
706 TCP_FASTOPEN_SLOW_CONNECT_READ_FAILED
);
710 bool getsockopt_success
= false;
711 bool server_acked_data
= false;
712 #if defined(TCP_INFO)
713 // Probe to see the if the socket used TCP FastOpen.
715 socklen_t info_len
= sizeof(tcp_info
);
716 getsockopt_success
= getsockopt(socket_
->socket_fd(), IPPROTO_TCP
, TCP_INFO
,
717 &info
, &info_len
) == 0 &&
718 info_len
== sizeof(tcp_info
);
719 server_acked_data
= getsockopt_success
&&
720 (info
.tcpi_options
& TCPI_OPT_SYN_DATA
);
723 if (getsockopt_success
) {
724 if (tcp_fastopen_status_
== TCP_FASTOPEN_FAST_CONNECT_RETURN
) {
725 tcp_fastopen_status_
= (server_acked_data
?
726 TCP_FASTOPEN_SYN_DATA_ACK
:
727 TCP_FASTOPEN_SYN_DATA_NACK
);
729 tcp_fastopen_status_
= (server_acked_data
?
730 TCP_FASTOPEN_NO_SYN_DATA_ACK
:
731 TCP_FASTOPEN_NO_SYN_DATA_NACK
);
734 tcp_fastopen_status_
=
735 (tcp_fastopen_status_
== TCP_FASTOPEN_FAST_CONNECT_RETURN
?
736 TCP_FASTOPEN_SYN_DATA_GETSOCKOPT_FAILED
:
737 TCP_FASTOPEN_NO_SYN_DATA_GETSOCKOPT_FAILED
);