Roll src/third_party/skia e1a828c:3e3b58d
[chromium-blink-merge.git] / net / socket / tcp_socket_libevent.cc
blobd7fa9fa4460291b2b181319d5930488602240e0b
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"
7 #include <errno.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
32 #endif
34 namespace net {
36 namespace {
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
49 // `man 7 tcp`.
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));
53 return error == 0;
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;
61 return false;
64 // If we disabled TCP keep alive, our work is done here.
65 if (!enable)
66 return true;
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;
72 return false;
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;
77 return false;
79 #endif
80 return true;
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)) {
91 return false;
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')) {
96 return false;
98 return true;
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;
106 #endif
108 } // namespace
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(),
126 FROM_HERE,
127 base::Bind(SystemSupportsTCPFastOpen),
128 base::Bind(RegisterTCPFastOpenIntentAndSupport, user_enabled));
129 #endif
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);
146 Close();
149 int TCPSocketLibevent::Open(AddressFamily family) {
150 DCHECK(!socket_);
151 socket_.reset(new SocketLibevent);
152 int rv = socket_->Open(ConvertAddressFamily(family));
153 if (rv != OK)
154 socket_.reset();
155 return rv;
158 int TCPSocketLibevent::AdoptConnectedSocket(int socket_fd,
159 const IPEndPoint& peer_address) {
160 DCHECK(!socket_);
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);
171 if (rv != OK)
172 socket_.reset();
173 return rv;
176 int TCPSocketLibevent::Bind(const IPEndPoint& address) {
177 DCHECK(socket_);
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) {
187 DCHECK(socket_);
188 return socket_->Listen(backlog);
191 int TCPSocketLibevent::Accept(scoped_ptr<TCPSocketLibevent>* tcp_socket,
192 IPEndPoint* address,
193 const CompletionCallback& callback) {
194 DCHECK(tcp_socket);
195 DCHECK(!callback.is_null());
196 DCHECK(socket_);
197 DCHECK(!accept_socket_);
199 net_log_.BeginEvent(NetLog::TYPE_TCP_ACCEPT);
201 int rv = socket_->Accept(
202 &accept_socket_,
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);
207 return rv;
210 int TCPSocketLibevent::Connect(const IPEndPoint& address,
211 const CompletionCallback& callback) {
212 DCHECK(socket_);
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);
228 return OK;
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);
236 return rv;
239 bool TCPSocketLibevent::IsConnected() const {
240 if (!socket_)
241 return false;
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_.
247 return true;
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,
260 int buf_len,
261 const CompletionCallback& callback) {
262 DCHECK(socket_);
263 DCHECK(!callback.is_null());
265 int rv = socket_->Read(
266 buf, buf_len,
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);
274 return rv;
277 int TCPSocketLibevent::Write(IOBuffer* buf,
278 int buf_len,
279 const CompletionCallback& callback) {
280 DCHECK(socket_);
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);
289 int rv;
291 if (use_tcp_fastopen_ && !tcp_fastopen_write_attempted_) {
292 rv = TcpFastOpenWrite(buf, buf_len, write_callback);
293 } else {
294 rv = socket_->Write(buf, buf_len, write_callback);
297 if (rv != ERR_IO_PENDING)
298 rv = HandleWriteCompleted(buf, rv);
299 return rv;
302 int TCPSocketLibevent::GetLocalAddress(IPEndPoint* address) const {
303 DCHECK(address);
305 if (!socket_)
306 return ERR_SOCKET_NOT_CONNECTED;
308 SockaddrStorage storage;
309 int rv = socket_->GetLocalAddress(&storage);
310 if (rv != OK)
311 return rv;
313 if (!address->FromSockAddr(storage.addr, storage.addr_len))
314 return ERR_ADDRESS_INVALID;
316 return OK;
319 int TCPSocketLibevent::GetPeerAddress(IPEndPoint* address) const {
320 DCHECK(address);
322 if (!IsConnected())
323 return ERR_SOCKET_NOT_CONNECTED;
325 SockaddrStorage storage;
326 int rv = socket_->GetPeerAddress(&storage);
327 if (rv != OK)
328 return rv;
330 if (!address->FromSockAddr(storage.addr, storage.addr_len))
331 return ERR_ADDRESS_INVALID;
333 return OK;
336 int TCPSocketLibevent::SetDefaultOptionsForServer() {
337 DCHECK(socket_);
338 return SetAddressReuse(true);
341 void TCPSocketLibevent::SetDefaultOptionsForClient() {
342 DCHECK(socket_);
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);
364 #endif
367 int TCPSocketLibevent::SetAddressReuse(bool allow) {
368 DCHECK(socket_);
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
375 // behavior.
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
380 // to 3.9.
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));
386 if (rv < 0)
387 return MapSystemError(errno);
388 return OK;
391 int TCPSocketLibevent::SetReceiveBufferSize(int32 size) {
392 DCHECK(socket_);
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) {
399 DCHECK(socket_);
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) {
406 DCHECK(socket_);
407 return SetTCPKeepAlive(socket_->socket_fd(), enable, delay);
410 bool TCPSocketLibevent::SetNoDelay(bool no_delay) {
411 DCHECK(socket_);
412 return SetTCPNoDelay(socket_->socket_fd(), no_delay);
415 void TCPSocketLibevent::Close() {
416 socket_.reset();
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())
436 return;
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;
444 else
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);
457 } else {
458 NOTREACHED();
462 void TCPSocketLibevent::EndLoggingMultipleConnectAttempts(int net_error) {
463 if (logging_multiple_connect_attempts_) {
464 LogConnectEnd(net_error);
465 logging_multiple_connect_attempts_ = false;
466 } else {
467 NOTREACHED();
471 void TCPSocketLibevent::AcceptCompleted(
472 scoped_ptr<TCPSocketLibevent>* tcp_socket,
473 IPEndPoint* address,
474 const CompletionCallback& callback,
475 int rv) {
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,
482 IPEndPoint* address,
483 int rv) {
484 if (rv == OK)
485 rv = BuildTcpSocketLibevent(tcp_socket, address);
487 if (rv == OK) {
488 net_log_.EndEvent(NetLog::TYPE_TCP_ACCEPT,
489 CreateNetLogIPEndPointCallback(address));
490 } else {
491 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_ACCEPT, rv);
494 return 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(),
510 net_log_.source()));
511 (*tcp_socket)->socket_.reset(accept_socket_.release());
512 return OK;
515 void TCPSocketLibevent::ConnectCompleted(const CompletionCallback& callback,
516 int rv) const {
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).
523 if (rv != OK) {
524 net_log_.EndEvent(NetLog::TYPE_TCP_CONNECT_ATTEMPT,
525 NetLog::IntegerCallback("os_error", errno));
526 } else {
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_)
535 LogConnectEnd(rv);
537 return rv;
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);
551 return;
554 UpdateConnectionTypeHistograms(CONNECTION_ANY);
556 SockaddrStorage storage;
557 int rv = socket_->GetLocalAddress(&storage);
558 if (rv != OK) {
559 PLOG(ERROR) << "GetLocalAddress() [rv: " << rv << "] error: ";
560 NOTREACHED();
561 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_TCP_CONNECT, rv);
562 return;
565 net_log_.EndEvent(NetLog::TYPE_TCP_CONNECT,
566 CreateNetLogSourceAddressCallback(storage.addr,
567 storage.addr_len));
570 void TCPSocketLibevent::ReadCompleted(const scoped_refptr<IOBuffer>& buf,
571 const CompletionCallback& callback,
572 int rv) {
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.
588 if (rv >= 0)
589 tcp_fastopen_connected_ = true;
590 else
591 g_tcp_fastopen_has_failed = true;
592 UpdateTCPFastOpenStatusAfterRead();
595 if (rv < 0) {
596 net_log_.AddEvent(NetLog::TYPE_SOCKET_READ_ERROR,
597 CreateNetLogSocketErrorCallback(rv, errno));
598 return rv;
601 base::StatsCounter read_bytes("tcp.read_bytes");
602 read_bytes.Add(rv);
603 net_log_.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_RECEIVED, rv,
604 buf->data());
605 NetworkActivityMonitor::GetInstance()->IncrementBytesReceived(rv);
607 return rv;
610 void TCPSocketLibevent::WriteCompleted(const scoped_refptr<IOBuffer>& buf,
611 const CompletionCallback& callback,
612 int rv) {
613 DCHECK_NE(ERR_IO_PENDING, rv);
614 callback.Run(HandleWriteCompleted(buf.get(), rv));
617 int TCPSocketLibevent::HandleWriteCompleted(IOBuffer* buf, int rv) {
618 if (rv < 0) {
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));
632 return rv;
635 base::StatsCounter write_bytes("tcp.write_bytes");
636 write_bytes.Add(rv);
637 net_log_.AddByteTransferEvent(NetLog::TYPE_SOCKET_BYTES_SENT, rv,
638 buf->data());
639 NetworkActivityMonitor::GetInstance()->IncrementBytesSent(rv);
640 return rv;
643 int TCPSocketLibevent::TcpFastOpenWrite(
644 IOBuffer* buf,
645 int buf_len,
646 const CompletionCallback& callback) {
647 SockaddrStorage storage;
648 int rv = socket_->GetPeerAddress(&storage);
649 if (rv != OK)
650 return rv;
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(),
662 buf->data(),
663 buf_len,
664 flags,
665 storage.addr,
666 storage.addr_len));
667 tcp_fastopen_write_attempted_ = true;
669 if (rv >= 0) {
670 tcp_fastopen_status_ = TCP_FASTOPEN_FAST_CONNECT_RETURN;
671 return rv;
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
680 // kernel space.
681 if (errno == EINPROGRESS) {
682 rv = ERR_IO_PENDING;
683 } else {
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;
698 return rv;
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);
715 return;
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.
722 tcp_info info;
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);
729 #endif
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);
736 } else {
737 tcp_fastopen_status_ = (server_acked_data ?
738 TCP_FASTOPEN_NO_SYN_DATA_ACK :
739 TCP_FASTOPEN_NO_SYN_DATA_NACK);
741 } else {
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);
749 } // namespace net