1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/socket/tcp_socket.h"
6
7 #include <errno.h>
8 #include <netinet/tcp.h>
9 #include <sys/socket.h>
10
11 #include <algorithm>
12 #include <memory>
13
14 #include "base/atomicops.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/functional/bind.h"
18 #include "base/lazy_instance.h"
19 #include "base/logging.h"
20 #include "base/metrics/histogram_macros.h"
21 #include "base/posix/eintr_wrapper.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_piece.h"
24 #include "base/time/time.h"
25 #include "build/build_config.h"
26 #include "net/base/address_list.h"
27 #include "net/base/io_buffer.h"
28 #include "net/base/ip_endpoint.h"
29 #include "net/base/net_errors.h"
30 #include "net/base/network_activity_monitor.h"
31 #include "net/base/network_change_notifier.h"
32 #include "net/base/sockaddr_storage.h"
33 #include "net/base/sys_addrinfo.h"
34 #include "net/base/tracing.h"
35 #include "net/http/http_util.h"
36 #include "net/log/net_log.h"
37 #include "net/log/net_log_event_type.h"
38 #include "net/log/net_log_source.h"
39 #include "net/log/net_log_source_type.h"
40 #include "net/log/net_log_values.h"
41 #include "net/socket/socket_net_log_params.h"
42 #include "net/socket/socket_options.h"
43 #include "net/socket/socket_posix.h"
44 #include "net/socket/socket_tag.h"
45 #include "net/traffic_annotation/network_traffic_annotation.h"
46
47 #if BUILDFLAG(IS_ANDROID)
48 #include "net/android/network_library.h"
49 #endif // BUILDFLAG(IS_ANDROID)
50
51 // If we don't have a definition for TCPI_OPT_SYN_DATA, create one.
52 #if !defined(TCPI_OPT_SYN_DATA)
53 #define TCPI_OPT_SYN_DATA 32
54 #endif
55
56 // Fuchsia defines TCP_INFO, but it's not implemented.
57 // TODO(crbug.com/758294): Enable TCP_INFO on Fuchsia once it's implemented
58 // there (see NET-160).
59 #if defined(TCP_INFO) && !BUILDFLAG(IS_FUCHSIA)
60 #define HAVE_TCP_INFO
61 #endif
62
63 namespace net {
64
65 namespace {
66
67 // SetTCPKeepAlive sets SO_KEEPALIVE.
SetTCPKeepAlive(int fd,bool enable,int delay)68 bool SetTCPKeepAlive(int fd, bool enable, int delay) {
69 // Enabling TCP keepalives is the same on all platforms.
70 int on = enable ? 1 : 0;
71 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on))) {
72 PLOG(ERROR) << "Failed to set SO_KEEPALIVE on fd: " << fd;
73 return false;
74 }
75
76 // If we disabled TCP keep alive, our work is done here.
77 if (!enable)
78 return true;
79
80 // A delay of 0 doesn't work, and is the default, so ignore that and rely on
81 // whatever the OS defaults are once we turned it on above.
82 if (delay) {
83 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
84 // Setting the keepalive interval varies by platform.
85
86 // Set seconds until first TCP keep alive.
87 if (setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &delay, sizeof(delay))) {
88 PLOG(ERROR) << "Failed to set TCP_KEEPIDLE on fd: " << fd;
89 return false;
90 }
91 // Set seconds between TCP keep alives.
92 if (setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &delay, sizeof(delay))) {
93 PLOG(ERROR) << "Failed to set TCP_KEEPINTVL on fd: " << fd;
94 return false;
95 }
96 #elif BUILDFLAG(IS_APPLE)
97 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &delay, sizeof(delay))) {
98 PLOG(ERROR) << "Failed to set TCP_KEEPALIVE on fd: " << fd;
99 return false;
100 }
101 #endif
102 }
103
104 return true;
105 }
106
107 #if defined(HAVE_TCP_INFO)
108 // Returns a zero value if the transport RTT is unavailable.
GetTransportRtt(SocketDescriptor fd)109 base::TimeDelta GetTransportRtt(SocketDescriptor fd) {
110 // It is possible for the value returned by getsockopt(TCP_INFO) to be
111 // legitimately zero due to the way the RTT is calculated where fractions are
112 // rounded down. This is specially true for virtualized environments with
113 // paravirtualized clocks.
114 //
115 // If getsockopt(TCP_INFO) succeeds and the tcpi_rtt is zero, this code
116 // assumes that the RTT got rounded down to zero and rounds it back up to this
117 // value so that callers can assume that no packets defy the laws of physics.
118 constexpr uint32_t kMinValidRttMicros = 1;
119
120 tcp_info info;
121 // Reset |tcpi_rtt| to verify if getsockopt() actually updates |tcpi_rtt|.
122 info.tcpi_rtt = 0;
123
124 socklen_t info_len = sizeof(tcp_info);
125 if (getsockopt(fd, IPPROTO_TCP, TCP_INFO, &info, &info_len) != 0)
126 return base::TimeDelta();
127
128 // Verify that |tcpi_rtt| in tcp_info struct was updated. Note that it's
129 // possible that |info_len| is shorter than |sizeof(tcp_info)| which implies
130 // that only a subset of values in |info| may have been updated by
131 // getsockopt().
132 if (info_len < static_cast<socklen_t>(offsetof(tcp_info, tcpi_rtt) +
133 sizeof(info.tcpi_rtt))) {
134 return base::TimeDelta();
135 }
136
137 return base::Microseconds(std::max(info.tcpi_rtt, kMinValidRttMicros));
138 }
139
140 #endif // defined(TCP_INFO)
141
142 } // namespace
143
144 //-----------------------------------------------------------------------------
145
TCPSocketPosix(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLog * net_log,const NetLogSource & source)146 TCPSocketPosix::TCPSocketPosix(
147 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
148 NetLog* net_log,
149 const NetLogSource& source)
150 : socket_performance_watcher_(std::move(socket_performance_watcher)),
151 net_log_(NetLogWithSource::Make(net_log, NetLogSourceType::SOCKET)) {
152 net_log_.BeginEventReferencingSource(NetLogEventType::SOCKET_ALIVE, source);
153 }
154
TCPSocketPosix(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLogWithSource net_log_source)155 TCPSocketPosix::TCPSocketPosix(
156 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
157 NetLogWithSource net_log_source)
158 : socket_performance_watcher_(std::move(socket_performance_watcher)),
159 net_log_(net_log_source) {
160 net_log_.BeginEvent(NetLogEventType::SOCKET_ALIVE);
161 }
162
~TCPSocketPosix()163 TCPSocketPosix::~TCPSocketPosix() {
164 net_log_.EndEvent(NetLogEventType::SOCKET_ALIVE);
165 Close();
166 }
167
Open(AddressFamily family)168 int TCPSocketPosix::Open(AddressFamily family) {
169 DCHECK(!socket_);
170 socket_ = std::make_unique<SocketPosix>();
171 int rv = socket_->Open(ConvertAddressFamily(family));
172 if (rv != OK)
173 socket_.reset();
174 if (rv == OK && tag_ != SocketTag())
175 tag_.Apply(socket_->socket_fd());
176 return rv;
177 }
178
BindToNetwork(handles::NetworkHandle network)179 int TCPSocketPosix::BindToNetwork(handles::NetworkHandle network) {
180 DCHECK(IsValid());
181 DCHECK(!IsConnected());
182 #if BUILDFLAG(IS_ANDROID)
183 return net::android::BindToNetwork(socket_->socket_fd(), network);
184 #else
185 NOTIMPLEMENTED();
186 return ERR_NOT_IMPLEMENTED;
187 #endif // BUILDFLAG(IS_ANDROID)
188 }
189
AdoptConnectedSocket(SocketDescriptor socket,const IPEndPoint & peer_address)190 int TCPSocketPosix::AdoptConnectedSocket(SocketDescriptor socket,
191 const IPEndPoint& peer_address) {
192 DCHECK(!socket_);
193
194 SockaddrStorage storage;
195 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len) &&
196 // For backward compatibility, allows the empty address.
197 !(peer_address == IPEndPoint())) {
198 return ERR_ADDRESS_INVALID;
199 }
200
201 socket_ = std::make_unique<SocketPosix>();
202 int rv = socket_->AdoptConnectedSocket(socket, storage);
203 if (rv != OK)
204 socket_.reset();
205 if (rv == OK && tag_ != SocketTag())
206 tag_.Apply(socket_->socket_fd());
207 return rv;
208 }
209
AdoptUnconnectedSocket(SocketDescriptor socket)210 int TCPSocketPosix::AdoptUnconnectedSocket(SocketDescriptor socket) {
211 DCHECK(!socket_);
212
213 socket_ = std::make_unique<SocketPosix>();
214 int rv = socket_->AdoptUnconnectedSocket(socket);
215 if (rv != OK)
216 socket_.reset();
217 if (rv == OK && tag_ != SocketTag())
218 tag_.Apply(socket_->socket_fd());
219 return rv;
220 }
221
Bind(const IPEndPoint & address)222 int TCPSocketPosix::Bind(const IPEndPoint& address) {
223 DCHECK(socket_);
224
225 SockaddrStorage storage;
226 if (!address.ToSockAddr(storage.addr, &storage.addr_len))
227 return ERR_ADDRESS_INVALID;
228
229 return socket_->Bind(storage);
230 }
231
Listen(int backlog)232 int TCPSocketPosix::Listen(int backlog) {
233 DCHECK(socket_);
234 return socket_->Listen(backlog);
235 }
236
Accept(std::unique_ptr<TCPSocketPosix> * tcp_socket,IPEndPoint * address,CompletionOnceCallback callback)237 int TCPSocketPosix::Accept(std::unique_ptr<TCPSocketPosix>* tcp_socket,
238 IPEndPoint* address,
239 CompletionOnceCallback callback) {
240 DCHECK(tcp_socket);
241 DCHECK(!callback.is_null());
242 DCHECK(socket_);
243 DCHECK(!accept_socket_);
244
245 net_log_.BeginEvent(NetLogEventType::TCP_ACCEPT);
246
247 int rv = socket_->Accept(
248 &accept_socket_,
249 base::BindOnce(&TCPSocketPosix::AcceptCompleted, base::Unretained(this),
250 tcp_socket, address, std::move(callback)));
251 if (rv != ERR_IO_PENDING)
252 rv = HandleAcceptCompleted(tcp_socket, address, rv);
253 return rv;
254 }
255
Connect(const IPEndPoint & address,CompletionOnceCallback callback)256 int TCPSocketPosix::Connect(const IPEndPoint& address,
257 CompletionOnceCallback callback) {
258 DCHECK(socket_);
259
260 if (!logging_multiple_connect_attempts_)
261 LogConnectBegin(AddressList(address));
262
263 net_log_.BeginEvent(NetLogEventType::TCP_CONNECT_ATTEMPT,
264 [&] { return CreateNetLogIPEndPointParams(&address); });
265
266 SockaddrStorage storage;
267 if (!address.ToSockAddr(storage.addr, &storage.addr_len))
268 return ERR_ADDRESS_INVALID;
269
270 int rv = socket_->Connect(
271 storage, base::BindOnce(&TCPSocketPosix::ConnectCompleted,
272 base::Unretained(this), std::move(callback)));
273 if (rv != ERR_IO_PENDING)
274 rv = HandleConnectCompleted(rv);
275 return rv;
276 }
277
IsConnected() const278 bool TCPSocketPosix::IsConnected() const {
279 if (!socket_)
280 return false;
281
282 return socket_->IsConnected();
283 }
284
IsConnectedAndIdle() const285 bool TCPSocketPosix::IsConnectedAndIdle() const {
286 return socket_ && socket_->IsConnectedAndIdle();
287 }
288
Read(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)289 int TCPSocketPosix::Read(IOBuffer* buf,
290 int buf_len,
291 CompletionOnceCallback callback) {
292 DCHECK(socket_);
293 DCHECK(!callback.is_null());
294
295 int rv = socket_->Read(
296 buf, buf_len,
297 base::BindOnce(
298 &TCPSocketPosix::ReadCompleted,
299 // Grab a reference to |buf| so that ReadCompleted() can still
300 // use it when Read() completes, as otherwise, this transfers
301 // ownership of buf to socket.
302 base::Unretained(this), base::WrapRefCounted(buf),
303 std::move(callback)));
304 if (rv != ERR_IO_PENDING)
305 rv = HandleReadCompleted(buf, rv);
306 return rv;
307 }
308
ReadIfReady(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)309 int TCPSocketPosix::ReadIfReady(IOBuffer* buf,
310 int buf_len,
311 CompletionOnceCallback callback) {
312 DCHECK(socket_);
313 DCHECK(!callback.is_null());
314
315 int rv = socket_->ReadIfReady(
316 buf, buf_len,
317 base::BindOnce(&TCPSocketPosix::ReadIfReadyCompleted,
318 base::Unretained(this), std::move(callback)));
319 if (rv != ERR_IO_PENDING)
320 rv = HandleReadCompleted(buf, rv);
321 return rv;
322 }
323
CancelReadIfReady()324 int TCPSocketPosix::CancelReadIfReady() {
325 DCHECK(socket_);
326
327 return socket_->CancelReadIfReady();
328 }
329
Write(IOBuffer * buf,int buf_len,CompletionOnceCallback callback,const NetworkTrafficAnnotationTag & traffic_annotation)330 int TCPSocketPosix::Write(
331 IOBuffer* buf,
332 int buf_len,
333 CompletionOnceCallback callback,
334 const NetworkTrafficAnnotationTag& traffic_annotation) {
335 DCHECK(socket_);
336 DCHECK(!callback.is_null());
337
338 CompletionOnceCallback write_callback = base::BindOnce(
339 &TCPSocketPosix::WriteCompleted,
340 // Grab a reference to |buf| so that WriteCompleted() can still
341 // use it when Write() completes, as otherwise, this transfers
342 // ownership of buf to socket.
343 base::Unretained(this), base::WrapRefCounted(buf), std::move(callback));
344 int rv;
345
346 rv = socket_->Write(buf, buf_len, std::move(write_callback),
347 traffic_annotation);
348
349 if (rv != ERR_IO_PENDING)
350 rv = HandleWriteCompleted(buf, rv);
351 return rv;
352 }
353
GetLocalAddress(IPEndPoint * address) const354 int TCPSocketPosix::GetLocalAddress(IPEndPoint* address) const {
355 DCHECK(address);
356
357 if (!socket_)
358 return ERR_SOCKET_NOT_CONNECTED;
359
360 SockaddrStorage storage;
361 int rv = socket_->GetLocalAddress(&storage);
362 if (rv != OK)
363 return rv;
364
365 if (!address->FromSockAddr(storage.addr, storage.addr_len))
366 return ERR_ADDRESS_INVALID;
367
368 return OK;
369 }
370
GetPeerAddress(IPEndPoint * address) const371 int TCPSocketPosix::GetPeerAddress(IPEndPoint* address) const {
372 DCHECK(address);
373
374 if (!IsConnected())
375 return ERR_SOCKET_NOT_CONNECTED;
376
377 SockaddrStorage storage;
378 int rv = socket_->GetPeerAddress(&storage);
379 if (rv != OK)
380 return rv;
381
382 if (!address->FromSockAddr(storage.addr, storage.addr_len))
383 return ERR_ADDRESS_INVALID;
384
385 return OK;
386 }
387
SetDefaultOptionsForServer()388 int TCPSocketPosix::SetDefaultOptionsForServer() {
389 DCHECK(socket_);
390 return AllowAddressReuse();
391 }
392
SetDefaultOptionsForClient()393 void TCPSocketPosix::SetDefaultOptionsForClient() {
394 DCHECK(socket_);
395
396 // This mirrors the behaviour on Windows. See the comment in
397 // tcp_socket_win.cc after searching for "NODELAY".
398 // If SetTCPNoDelay fails, we don't care.
399 SetTCPNoDelay(socket_->socket_fd(), true);
400
401 // TCP keep alive wakes up the radio, which is expensive on mobile. Do not
402 // enable it there. It's useful to prevent TCP middleboxes from timing out
403 // connection mappings. Packets for timed out connection mappings at
404 // middleboxes will either lead to:
405 // a) Middleboxes sending TCP RSTs. It's up to higher layers to check for this
406 // and retry. The HTTP network transaction code does this.
407 // b) Middleboxes just drop the unrecognized TCP packet. This leads to the TCP
408 // stack retransmitting packets per TCP stack retransmission timeouts, which
409 // are very high (on the order of seconds). Given the number of
410 // retransmissions required before killing the connection, this can lead to
411 // tens of seconds or even minutes of delay, depending on OS.
412 #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
413 const int kTCPKeepAliveSeconds = 45;
414
415 SetTCPKeepAlive(socket_->socket_fd(), true, kTCPKeepAliveSeconds);
416 #endif
417 }
418
AllowAddressReuse()419 int TCPSocketPosix::AllowAddressReuse() {
420 DCHECK(socket_);
421
422 return SetReuseAddr(socket_->socket_fd(), true);
423 }
424
SetReceiveBufferSize(int32_t size)425 int TCPSocketPosix::SetReceiveBufferSize(int32_t size) {
426 DCHECK(socket_);
427
428 return SetSocketReceiveBufferSize(socket_->socket_fd(), size);
429 }
430
SetSendBufferSize(int32_t size)431 int TCPSocketPosix::SetSendBufferSize(int32_t size) {
432 DCHECK(socket_);
433
434 return SetSocketSendBufferSize(socket_->socket_fd(), size);
435 }
436
SetKeepAlive(bool enable,int delay)437 bool TCPSocketPosix::SetKeepAlive(bool enable, int delay) {
438 if (!socket_)
439 return false;
440
441 return SetTCPKeepAlive(socket_->socket_fd(), enable, delay);
442 }
443
SetNoDelay(bool no_delay)444 bool TCPSocketPosix::SetNoDelay(bool no_delay) {
445 if (!socket_)
446 return false;
447
448 return SetTCPNoDelay(socket_->socket_fd(), no_delay) == OK;
449 }
450
SetIPv6Only(bool ipv6_only)451 int TCPSocketPosix::SetIPv6Only(bool ipv6_only) {
452 CHECK(socket_);
453 return ::net::SetIPv6Only(socket_->socket_fd(), ipv6_only);
454 }
455
Close()456 void TCPSocketPosix::Close() {
457 TRACE_EVENT("base", perfetto::StaticString{"CloseSocketTCP"});
458 socket_.reset();
459 tag_ = SocketTag();
460 }
461
IsValid() const462 bool TCPSocketPosix::IsValid() const {
463 return socket_ != nullptr && socket_->socket_fd() != kInvalidSocket;
464 }
465
DetachFromThread()466 void TCPSocketPosix::DetachFromThread() {
467 socket_->DetachFromThread();
468 }
469
StartLoggingMultipleConnectAttempts(const AddressList & addresses)470 void TCPSocketPosix::StartLoggingMultipleConnectAttempts(
471 const AddressList& addresses) {
472 if (!logging_multiple_connect_attempts_) {
473 logging_multiple_connect_attempts_ = true;
474 LogConnectBegin(addresses);
475 } else {
476 NOTREACHED();
477 }
478 }
479
EndLoggingMultipleConnectAttempts(int net_error)480 void TCPSocketPosix::EndLoggingMultipleConnectAttempts(int net_error) {
481 if (logging_multiple_connect_attempts_) {
482 LogConnectEnd(net_error);
483 logging_multiple_connect_attempts_ = false;
484 } else {
485 NOTREACHED();
486 }
487 }
488
ReleaseSocketDescriptorForTesting()489 SocketDescriptor TCPSocketPosix::ReleaseSocketDescriptorForTesting() {
490 SocketDescriptor socket_descriptor = socket_->ReleaseConnectedSocket();
491 socket_.reset();
492 return socket_descriptor;
493 }
494
SocketDescriptorForTesting() const495 SocketDescriptor TCPSocketPosix::SocketDescriptorForTesting() const {
496 return socket_->socket_fd();
497 }
498
ApplySocketTag(const SocketTag & tag)499 void TCPSocketPosix::ApplySocketTag(const SocketTag& tag) {
500 if (IsValid() && tag != tag_) {
501 tag.Apply(socket_->socket_fd());
502 }
503 tag_ = tag;
504 }
505
AcceptCompleted(std::unique_ptr<TCPSocketPosix> * tcp_socket,IPEndPoint * address,CompletionOnceCallback callback,int rv)506 void TCPSocketPosix::AcceptCompleted(
507 std::unique_ptr<TCPSocketPosix>* tcp_socket,
508 IPEndPoint* address,
509 CompletionOnceCallback callback,
510 int rv) {
511 DCHECK_NE(ERR_IO_PENDING, rv);
512 std::move(callback).Run(HandleAcceptCompleted(tcp_socket, address, rv));
513 }
514
HandleAcceptCompleted(std::unique_ptr<TCPSocketPosix> * tcp_socket,IPEndPoint * address,int rv)515 int TCPSocketPosix::HandleAcceptCompleted(
516 std::unique_ptr<TCPSocketPosix>* tcp_socket,
517 IPEndPoint* address,
518 int rv) {
519 if (rv == OK)
520 rv = BuildTcpSocketPosix(tcp_socket, address);
521
522 if (rv == OK) {
523 net_log_.EndEvent(NetLogEventType::TCP_ACCEPT,
524 [&] { return CreateNetLogIPEndPointParams(address); });
525 } else {
526 net_log_.EndEventWithNetErrorCode(NetLogEventType::TCP_ACCEPT, rv);
527 }
528
529 return rv;
530 }
531
BuildTcpSocketPosix(std::unique_ptr<TCPSocketPosix> * tcp_socket,IPEndPoint * address)532 int TCPSocketPosix::BuildTcpSocketPosix(
533 std::unique_ptr<TCPSocketPosix>* tcp_socket,
534 IPEndPoint* address) {
535 DCHECK(accept_socket_);
536
537 SockaddrStorage storage;
538 if (accept_socket_->GetPeerAddress(&storage) != OK ||
539 !address->FromSockAddr(storage.addr, storage.addr_len)) {
540 accept_socket_.reset();
541 return ERR_ADDRESS_INVALID;
542 }
543
544 *tcp_socket = std::make_unique<TCPSocketPosix>(nullptr, net_log_.net_log(),
545 net_log_.source());
546 (*tcp_socket)->socket_ = std::move(accept_socket_);
547 return OK;
548 }
549
ConnectCompleted(CompletionOnceCallback callback,int rv)550 void TCPSocketPosix::ConnectCompleted(CompletionOnceCallback callback, int rv) {
551 DCHECK_NE(ERR_IO_PENDING, rv);
552 std::move(callback).Run(HandleConnectCompleted(rv));
553 }
554
HandleConnectCompleted(int rv)555 int TCPSocketPosix::HandleConnectCompleted(int rv) {
556 // Log the end of this attempt (and any OS error it threw).
557 if (rv != OK) {
558 net_log_.EndEventWithIntParams(NetLogEventType::TCP_CONNECT_ATTEMPT,
559 "os_error", errno);
560 tag_ = SocketTag();
561 } else {
562 net_log_.EndEvent(NetLogEventType::TCP_CONNECT_ATTEMPT);
563 NotifySocketPerformanceWatcher();
564 }
565
566 // Give a more specific error when the user is offline.
567 if (rv == ERR_ADDRESS_UNREACHABLE && NetworkChangeNotifier::IsOffline())
568 rv = ERR_INTERNET_DISCONNECTED;
569
570 if (!logging_multiple_connect_attempts_)
571 LogConnectEnd(rv);
572
573 return rv;
574 }
575
LogConnectBegin(const AddressList & addresses) const576 void TCPSocketPosix::LogConnectBegin(const AddressList& addresses) const {
577 net_log_.BeginEvent(NetLogEventType::TCP_CONNECT,
578 [&] { return addresses.NetLogParams(); });
579 }
580
LogConnectEnd(int net_error) const581 void TCPSocketPosix::LogConnectEnd(int net_error) const {
582 if (net_error != OK) {
583 net_log_.EndEventWithNetErrorCode(NetLogEventType::TCP_CONNECT, net_error);
584 return;
585 }
586
587 net_log_.EndEvent(NetLogEventType::TCP_CONNECT, [&] {
588 net::IPEndPoint local_address;
589 int net_error = GetLocalAddress(&local_address);
590 net::IPEndPoint remote_address;
591 if (net_error == net::OK)
592 net_error = GetPeerAddress(&remote_address);
593 if (net_error != net::OK)
594 return NetLogParamsWithInt("get_address_net_error", net_error);
595 return CreateNetLogAddressPairParams(local_address, remote_address);
596 });
597 }
598
ReadCompleted(const scoped_refptr<IOBuffer> & buf,CompletionOnceCallback callback,int rv)599 void TCPSocketPosix::ReadCompleted(const scoped_refptr<IOBuffer>& buf,
600 CompletionOnceCallback callback,
601 int rv) {
602 DCHECK_NE(ERR_IO_PENDING, rv);
603
604 std::move(callback).Run(HandleReadCompleted(buf.get(), rv));
605 }
606
ReadIfReadyCompleted(CompletionOnceCallback callback,int rv)607 void TCPSocketPosix::ReadIfReadyCompleted(CompletionOnceCallback callback,
608 int rv) {
609 DCHECK_NE(ERR_IO_PENDING, rv);
610 DCHECK_GE(OK, rv);
611
612 HandleReadCompletedHelper(rv);
613 std::move(callback).Run(rv);
614 }
615
HandleReadCompleted(IOBuffer * buf,int rv)616 int TCPSocketPosix::HandleReadCompleted(IOBuffer* buf, int rv) {
617 HandleReadCompletedHelper(rv);
618
619 if (rv < 0)
620 return rv;
621
622 // Notify the watcher only if at least 1 byte was read.
623 if (rv > 0)
624 NotifySocketPerformanceWatcher();
625
626 net_log_.AddByteTransferEvent(NetLogEventType::SOCKET_BYTES_RECEIVED, rv,
627 buf->data());
628 activity_monitor::IncrementBytesReceived(rv);
629
630 return rv;
631 }
632
HandleReadCompletedHelper(int rv)633 void TCPSocketPosix::HandleReadCompletedHelper(int rv) {
634 if (rv < 0) {
635 NetLogSocketError(net_log_, NetLogEventType::SOCKET_READ_ERROR, rv, errno);
636 }
637 }
638
WriteCompleted(const scoped_refptr<IOBuffer> & buf,CompletionOnceCallback callback,int rv)639 void TCPSocketPosix::WriteCompleted(const scoped_refptr<IOBuffer>& buf,
640 CompletionOnceCallback callback,
641 int rv) {
642 DCHECK_NE(ERR_IO_PENDING, rv);
643 std::move(callback).Run(HandleWriteCompleted(buf.get(), rv));
644 }
645
HandleWriteCompleted(IOBuffer * buf,int rv)646 int TCPSocketPosix::HandleWriteCompleted(IOBuffer* buf, int rv) {
647 if (rv < 0) {
648 NetLogSocketError(net_log_, NetLogEventType::SOCKET_WRITE_ERROR, rv, errno);
649 return rv;
650 }
651
652 // Notify the watcher only if at least 1 byte was written.
653 if (rv > 0)
654 NotifySocketPerformanceWatcher();
655
656 net_log_.AddByteTransferEvent(NetLogEventType::SOCKET_BYTES_SENT, rv,
657 buf->data());
658 return rv;
659 }
660
NotifySocketPerformanceWatcher()661 void TCPSocketPosix::NotifySocketPerformanceWatcher() {
662 #if defined(HAVE_TCP_INFO)
663 // Check if |socket_performance_watcher_| is interested in receiving a RTT
664 // update notification.
665 if (!socket_performance_watcher_ ||
666 !socket_performance_watcher_->ShouldNotifyUpdatedRTT()) {
667 return;
668 }
669
670 base::TimeDelta rtt = GetTransportRtt(socket_->socket_fd());
671 if (rtt.is_zero())
672 return;
673
674 socket_performance_watcher_->OnUpdatedRTTAvailable(rtt);
675 #endif // defined(TCP_INFO)
676 }
677
GetEstimatedRoundTripTime(base::TimeDelta * out_rtt) const678 bool TCPSocketPosix::GetEstimatedRoundTripTime(base::TimeDelta* out_rtt) const {
679 DCHECK(out_rtt);
680 if (!socket_)
681 return false;
682
683 #if defined(HAVE_TCP_INFO)
684 base::TimeDelta rtt = GetTransportRtt(socket_->socket_fd());
685 if (rtt.is_zero())
686 return false;
687 *out_rtt = rtt;
688 return true;
689 #else
690 return false;
691 #endif // defined(TCP_INFO)
692 }
693
694 } // namespace net
695