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/memory/ptr_util.h"
21 #include "base/metrics/histogram_macros.h"
22 #include "base/posix/eintr_wrapper.h"
23 #include "base/strings/string_number_conversions.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/42050612): 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
146 // static
Create(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLog * net_log,const NetLogSource & source)147 std::unique_ptr<TCPSocketPosix> TCPSocketPosix::Create(
148 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
149 NetLog* net_log,
150 const NetLogSource& source) {
151 return base::WrapUnique(new TCPSocketPosix(
152 std::move(socket_performance_watcher), net_log, source));
153 }
154
155 // static
Create(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLogWithSource net_log_source)156 std::unique_ptr<TCPSocketPosix> TCPSocketPosix::Create(
157 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
158 NetLogWithSource net_log_source) {
159 return base::WrapUnique(new TCPSocketPosix(
160 std::move(socket_performance_watcher), net_log_source));
161 }
162
TCPSocketPosix(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLog * net_log,const NetLogSource & source)163 TCPSocketPosix::TCPSocketPosix(
164 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
165 NetLog* net_log,
166 const NetLogSource& source)
167 : socket_performance_watcher_(std::move(socket_performance_watcher)),
168 net_log_(NetLogWithSource::Make(net_log, NetLogSourceType::SOCKET)) {
169 net_log_.BeginEventReferencingSource(NetLogEventType::SOCKET_ALIVE, source);
170 }
171
TCPSocketPosix(std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,NetLogWithSource net_log_source)172 TCPSocketPosix::TCPSocketPosix(
173 std::unique_ptr<SocketPerformanceWatcher> socket_performance_watcher,
174 NetLogWithSource net_log_source)
175 : socket_performance_watcher_(std::move(socket_performance_watcher)),
176 net_log_(net_log_source) {
177 net_log_.BeginEvent(NetLogEventType::SOCKET_ALIVE);
178 }
179
~TCPSocketPosix()180 TCPSocketPosix::~TCPSocketPosix() {
181 net_log_.EndEvent(NetLogEventType::SOCKET_ALIVE);
182 Close();
183 }
184
Open(AddressFamily family)185 int TCPSocketPosix::Open(AddressFamily family) {
186 DCHECK(!socket_);
187 socket_ = std::make_unique<SocketPosix>();
188 int rv = socket_->Open(ConvertAddressFamily(family));
189 if (rv != OK)
190 socket_.reset();
191 if (rv == OK && tag_ != SocketTag())
192 tag_.Apply(socket_->socket_fd());
193 return rv;
194 }
195
BindToNetwork(handles::NetworkHandle network)196 int TCPSocketPosix::BindToNetwork(handles::NetworkHandle network) {
197 DCHECK(IsValid());
198 DCHECK(!IsConnected());
199 #if BUILDFLAG(IS_ANDROID)
200 return net::android::BindToNetwork(socket_->socket_fd(), network);
201 #else
202 NOTIMPLEMENTED();
203 return ERR_NOT_IMPLEMENTED;
204 #endif // BUILDFLAG(IS_ANDROID)
205 }
206
AdoptConnectedSocket(SocketDescriptor socket,const IPEndPoint & peer_address)207 int TCPSocketPosix::AdoptConnectedSocket(SocketDescriptor socket,
208 const IPEndPoint& peer_address) {
209 DCHECK(!socket_);
210
211 SockaddrStorage storage;
212 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len) &&
213 // For backward compatibility, allows the empty address.
214 !(peer_address == IPEndPoint())) {
215 return ERR_ADDRESS_INVALID;
216 }
217
218 socket_ = std::make_unique<SocketPosix>();
219 int rv = socket_->AdoptConnectedSocket(socket, storage);
220 if (rv != OK)
221 socket_.reset();
222 if (rv == OK && tag_ != SocketTag())
223 tag_.Apply(socket_->socket_fd());
224 return rv;
225 }
226
AdoptUnconnectedSocket(SocketDescriptor socket)227 int TCPSocketPosix::AdoptUnconnectedSocket(SocketDescriptor socket) {
228 DCHECK(!socket_);
229
230 socket_ = std::make_unique<SocketPosix>();
231 int rv = socket_->AdoptUnconnectedSocket(socket);
232 if (rv != OK)
233 socket_.reset();
234 if (rv == OK && tag_ != SocketTag())
235 tag_.Apply(socket_->socket_fd());
236 return rv;
237 }
238
Bind(const IPEndPoint & address)239 int TCPSocketPosix::Bind(const IPEndPoint& address) {
240 DCHECK(socket_);
241
242 SockaddrStorage storage;
243 if (!address.ToSockAddr(storage.addr, &storage.addr_len))
244 return ERR_ADDRESS_INVALID;
245
246 return socket_->Bind(storage);
247 }
248
Listen(int backlog)249 int TCPSocketPosix::Listen(int backlog) {
250 DCHECK(socket_);
251 return socket_->Listen(backlog);
252 }
253
Accept(std::unique_ptr<TCPSocketPosix> * tcp_socket,IPEndPoint * address,CompletionOnceCallback callback)254 int TCPSocketPosix::Accept(std::unique_ptr<TCPSocketPosix>* tcp_socket,
255 IPEndPoint* address,
256 CompletionOnceCallback callback) {
257 DCHECK(tcp_socket);
258 DCHECK(!callback.is_null());
259 DCHECK(socket_);
260 DCHECK(!accept_socket_);
261
262 net_log_.BeginEvent(NetLogEventType::TCP_ACCEPT);
263
264 int rv = socket_->Accept(
265 &accept_socket_,
266 base::BindOnce(&TCPSocketPosix::AcceptCompleted, base::Unretained(this),
267 tcp_socket, address, std::move(callback)));
268 if (rv != ERR_IO_PENDING)
269 rv = HandleAcceptCompleted(tcp_socket, address, rv);
270 return rv;
271 }
272
Connect(const IPEndPoint & address,CompletionOnceCallback callback)273 int TCPSocketPosix::Connect(const IPEndPoint& address,
274 CompletionOnceCallback callback) {
275 DCHECK(socket_);
276
277 if (!logging_multiple_connect_attempts_)
278 LogConnectBegin(AddressList(address));
279
280 net_log_.BeginEvent(NetLogEventType::TCP_CONNECT_ATTEMPT,
281 [&] { return CreateNetLogIPEndPointParams(&address); });
282
283 SockaddrStorage storage;
284 if (!address.ToSockAddr(storage.addr, &storage.addr_len))
285 return ERR_ADDRESS_INVALID;
286
287 int rv = socket_->Connect(
288 storage, base::BindOnce(&TCPSocketPosix::ConnectCompleted,
289 base::Unretained(this), std::move(callback)));
290 if (rv != ERR_IO_PENDING)
291 rv = HandleConnectCompleted(rv);
292 return rv;
293 }
294
IsConnected() const295 bool TCPSocketPosix::IsConnected() const {
296 if (!socket_)
297 return false;
298
299 return socket_->IsConnected();
300 }
301
IsConnectedAndIdle() const302 bool TCPSocketPosix::IsConnectedAndIdle() const {
303 return socket_ && socket_->IsConnectedAndIdle();
304 }
305
Read(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)306 int TCPSocketPosix::Read(IOBuffer* buf,
307 int buf_len,
308 CompletionOnceCallback callback) {
309 DCHECK(socket_);
310 DCHECK(!callback.is_null());
311
312 int rv = socket_->Read(
313 buf, buf_len,
314 base::BindOnce(
315 &TCPSocketPosix::ReadCompleted,
316 // Grab a reference to |buf| so that ReadCompleted() can still
317 // use it when Read() completes, as otherwise, this transfers
318 // ownership of buf to socket.
319 base::Unretained(this), base::WrapRefCounted(buf),
320 std::move(callback)));
321 if (rv != ERR_IO_PENDING)
322 rv = HandleReadCompleted(buf, rv);
323 return rv;
324 }
325
ReadIfReady(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)326 int TCPSocketPosix::ReadIfReady(IOBuffer* buf,
327 int buf_len,
328 CompletionOnceCallback callback) {
329 DCHECK(socket_);
330 DCHECK(!callback.is_null());
331
332 int rv = socket_->ReadIfReady(
333 buf, buf_len,
334 base::BindOnce(&TCPSocketPosix::ReadIfReadyCompleted,
335 base::Unretained(this), std::move(callback)));
336 if (rv != ERR_IO_PENDING)
337 rv = HandleReadCompleted(buf, rv);
338 return rv;
339 }
340
CancelReadIfReady()341 int TCPSocketPosix::CancelReadIfReady() {
342 DCHECK(socket_);
343
344 return socket_->CancelReadIfReady();
345 }
346
Write(IOBuffer * buf,int buf_len,CompletionOnceCallback callback,const NetworkTrafficAnnotationTag & traffic_annotation)347 int TCPSocketPosix::Write(
348 IOBuffer* buf,
349 int buf_len,
350 CompletionOnceCallback callback,
351 const NetworkTrafficAnnotationTag& traffic_annotation) {
352 DCHECK(socket_);
353 DCHECK(!callback.is_null());
354
355 CompletionOnceCallback write_callback = base::BindOnce(
356 &TCPSocketPosix::WriteCompleted,
357 // Grab a reference to |buf| so that WriteCompleted() can still
358 // use it when Write() completes, as otherwise, this transfers
359 // ownership of buf to socket.
360 base::Unretained(this), base::WrapRefCounted(buf), std::move(callback));
361 int rv;
362
363 rv = socket_->Write(buf, buf_len, std::move(write_callback),
364 traffic_annotation);
365
366 if (rv != ERR_IO_PENDING)
367 rv = HandleWriteCompleted(buf, rv);
368 return rv;
369 }
370
GetLocalAddress(IPEndPoint * address) const371 int TCPSocketPosix::GetLocalAddress(IPEndPoint* address) const {
372 DCHECK(address);
373
374 if (!socket_)
375 return ERR_SOCKET_NOT_CONNECTED;
376
377 SockaddrStorage storage;
378 int rv = socket_->GetLocalAddress(&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
GetPeerAddress(IPEndPoint * address) const388 int TCPSocketPosix::GetPeerAddress(IPEndPoint* address) const {
389 DCHECK(address);
390
391 if (!IsConnected())
392 return ERR_SOCKET_NOT_CONNECTED;
393
394 SockaddrStorage storage;
395 int rv = socket_->GetPeerAddress(&storage);
396 if (rv != OK)
397 return rv;
398
399 if (!address->FromSockAddr(storage.addr, storage.addr_len))
400 return ERR_ADDRESS_INVALID;
401
402 return OK;
403 }
404
SetDefaultOptionsForServer()405 int TCPSocketPosix::SetDefaultOptionsForServer() {
406 DCHECK(socket_);
407 return AllowAddressReuse();
408 }
409
SetDefaultOptionsForClient()410 void TCPSocketPosix::SetDefaultOptionsForClient() {
411 DCHECK(socket_);
412
413 // This mirrors the behaviour on Windows. See the comment in
414 // tcp_socket_win.cc after searching for "NODELAY".
415 // If SetTCPNoDelay fails, we don't care.
416 SetTCPNoDelay(socket_->socket_fd(), true);
417
418 // TCP keep alive wakes up the radio, which is expensive on mobile. Do not
419 // enable it there. It's useful to prevent TCP middleboxes from timing out
420 // connection mappings. Packets for timed out connection mappings at
421 // middleboxes will either lead to:
422 // a) Middleboxes sending TCP RSTs. It's up to higher layers to check for this
423 // and retry. The HTTP network transaction code does this.
424 // b) Middleboxes just drop the unrecognized TCP packet. This leads to the TCP
425 // stack retransmitting packets per TCP stack retransmission timeouts, which
426 // are very high (on the order of seconds). Given the number of
427 // retransmissions required before killing the connection, this can lead to
428 // tens of seconds or even minutes of delay, depending on OS.
429 #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
430 const int kTCPKeepAliveSeconds = 45;
431
432 SetTCPKeepAlive(socket_->socket_fd(), true, kTCPKeepAliveSeconds);
433 #endif
434 }
435
AllowAddressReuse()436 int TCPSocketPosix::AllowAddressReuse() {
437 DCHECK(socket_);
438
439 return SetReuseAddr(socket_->socket_fd(), true);
440 }
441
SetReceiveBufferSize(int32_t size)442 int TCPSocketPosix::SetReceiveBufferSize(int32_t size) {
443 DCHECK(socket_);
444
445 return SetSocketReceiveBufferSize(socket_->socket_fd(), size);
446 }
447
SetSendBufferSize(int32_t size)448 int TCPSocketPosix::SetSendBufferSize(int32_t size) {
449 DCHECK(socket_);
450
451 return SetSocketSendBufferSize(socket_->socket_fd(), size);
452 }
453
SetKeepAlive(bool enable,int delay)454 bool TCPSocketPosix::SetKeepAlive(bool enable, int delay) {
455 if (!socket_)
456 return false;
457
458 return SetTCPKeepAlive(socket_->socket_fd(), enable, delay);
459 }
460
SetNoDelay(bool no_delay)461 bool TCPSocketPosix::SetNoDelay(bool no_delay) {
462 if (!socket_)
463 return false;
464
465 return SetTCPNoDelay(socket_->socket_fd(), no_delay) == OK;
466 }
467
SetIPv6Only(bool ipv6_only)468 int TCPSocketPosix::SetIPv6Only(bool ipv6_only) {
469 CHECK(socket_);
470 return ::net::SetIPv6Only(socket_->socket_fd(), ipv6_only);
471 }
472
Close()473 void TCPSocketPosix::Close() {
474 TRACE_EVENT("base", perfetto::StaticString{"CloseSocketTCP"});
475 socket_.reset();
476 tag_ = SocketTag();
477 }
478
IsValid() const479 bool TCPSocketPosix::IsValid() const {
480 return socket_ != nullptr && socket_->socket_fd() != kInvalidSocket;
481 }
482
DetachFromThread()483 void TCPSocketPosix::DetachFromThread() {
484 socket_->DetachFromThread();
485 }
486
StartLoggingMultipleConnectAttempts(const AddressList & addresses)487 void TCPSocketPosix::StartLoggingMultipleConnectAttempts(
488 const AddressList& addresses) {
489 if (!logging_multiple_connect_attempts_) {
490 logging_multiple_connect_attempts_ = true;
491 LogConnectBegin(addresses);
492 } else {
493 NOTREACHED();
494 }
495 }
496
EndLoggingMultipleConnectAttempts(int net_error)497 void TCPSocketPosix::EndLoggingMultipleConnectAttempts(int net_error) {
498 if (logging_multiple_connect_attempts_) {
499 LogConnectEnd(net_error);
500 logging_multiple_connect_attempts_ = false;
501 } else {
502 NOTREACHED();
503 }
504 }
505
ReleaseSocketDescriptorForTesting()506 SocketDescriptor TCPSocketPosix::ReleaseSocketDescriptorForTesting() {
507 SocketDescriptor socket_descriptor = socket_->ReleaseConnectedSocket();
508 socket_.reset();
509 return socket_descriptor;
510 }
511
SocketDescriptorForTesting() const512 SocketDescriptor TCPSocketPosix::SocketDescriptorForTesting() const {
513 return socket_->socket_fd();
514 }
515
ApplySocketTag(const SocketTag & tag)516 void TCPSocketPosix::ApplySocketTag(const SocketTag& tag) {
517 if (IsValid() && tag != tag_) {
518 tag.Apply(socket_->socket_fd());
519 }
520 tag_ = tag;
521 }
522
AcceptCompleted(std::unique_ptr<TCPSocketPosix> * tcp_socket,IPEndPoint * address,CompletionOnceCallback callback,int rv)523 void TCPSocketPosix::AcceptCompleted(
524 std::unique_ptr<TCPSocketPosix>* tcp_socket,
525 IPEndPoint* address,
526 CompletionOnceCallback callback,
527 int rv) {
528 DCHECK_NE(ERR_IO_PENDING, rv);
529 std::move(callback).Run(HandleAcceptCompleted(tcp_socket, address, rv));
530 }
531
HandleAcceptCompleted(std::unique_ptr<TCPSocketPosix> * tcp_socket,IPEndPoint * address,int rv)532 int TCPSocketPosix::HandleAcceptCompleted(
533 std::unique_ptr<TCPSocketPosix>* tcp_socket,
534 IPEndPoint* address,
535 int rv) {
536 if (rv == OK)
537 rv = BuildTcpSocketPosix(tcp_socket, address);
538
539 if (rv == OK) {
540 net_log_.EndEvent(NetLogEventType::TCP_ACCEPT,
541 [&] { return CreateNetLogIPEndPointParams(address); });
542 } else {
543 net_log_.EndEventWithNetErrorCode(NetLogEventType::TCP_ACCEPT, rv);
544 }
545
546 return rv;
547 }
548
BuildTcpSocketPosix(std::unique_ptr<TCPSocketPosix> * tcp_socket,IPEndPoint * address)549 int TCPSocketPosix::BuildTcpSocketPosix(
550 std::unique_ptr<TCPSocketPosix>* tcp_socket,
551 IPEndPoint* address) {
552 DCHECK(accept_socket_);
553
554 SockaddrStorage storage;
555 if (accept_socket_->GetPeerAddress(&storage) != OK ||
556 !address->FromSockAddr(storage.addr, storage.addr_len)) {
557 accept_socket_.reset();
558 return ERR_ADDRESS_INVALID;
559 }
560
561 *tcp_socket =
562 TCPSocketPosix::Create(nullptr, net_log_.net_log(), net_log_.source());
563 (*tcp_socket)->socket_ = std::move(accept_socket_);
564 return OK;
565 }
566
ConnectCompleted(CompletionOnceCallback callback,int rv)567 void TCPSocketPosix::ConnectCompleted(CompletionOnceCallback callback, int rv) {
568 DCHECK_NE(ERR_IO_PENDING, rv);
569 std::move(callback).Run(HandleConnectCompleted(rv));
570 }
571
HandleConnectCompleted(int rv)572 int TCPSocketPosix::HandleConnectCompleted(int rv) {
573 // Log the end of this attempt (and any OS error it threw).
574 if (rv != OK) {
575 net_log_.EndEventWithIntParams(NetLogEventType::TCP_CONNECT_ATTEMPT,
576 "os_error", errno);
577 tag_ = SocketTag();
578 } else {
579 net_log_.EndEvent(NetLogEventType::TCP_CONNECT_ATTEMPT);
580 NotifySocketPerformanceWatcher();
581 }
582
583 // Give a more specific error when the user is offline.
584 if (rv == ERR_ADDRESS_UNREACHABLE && NetworkChangeNotifier::IsOffline())
585 rv = ERR_INTERNET_DISCONNECTED;
586
587 if (!logging_multiple_connect_attempts_)
588 LogConnectEnd(rv);
589
590 return rv;
591 }
592
LogConnectBegin(const AddressList & addresses) const593 void TCPSocketPosix::LogConnectBegin(const AddressList& addresses) const {
594 net_log_.BeginEvent(NetLogEventType::TCP_CONNECT,
595 [&] { return addresses.NetLogParams(); });
596 }
597
LogConnectEnd(int net_error) const598 void TCPSocketPosix::LogConnectEnd(int net_error) const {
599 if (net_error != OK) {
600 net_log_.EndEventWithNetErrorCode(NetLogEventType::TCP_CONNECT, net_error);
601 return;
602 }
603
604 net_log_.EndEvent(NetLogEventType::TCP_CONNECT, [&] {
605 net::IPEndPoint local_address;
606 int net_error = GetLocalAddress(&local_address);
607 net::IPEndPoint remote_address;
608 if (net_error == net::OK)
609 net_error = GetPeerAddress(&remote_address);
610 if (net_error != net::OK)
611 return NetLogParamsWithInt("get_address_net_error", net_error);
612 return CreateNetLogAddressPairParams(local_address, remote_address);
613 });
614 }
615
ReadCompleted(const scoped_refptr<IOBuffer> & buf,CompletionOnceCallback callback,int rv)616 void TCPSocketPosix::ReadCompleted(const scoped_refptr<IOBuffer>& buf,
617 CompletionOnceCallback callback,
618 int rv) {
619 DCHECK_NE(ERR_IO_PENDING, rv);
620
621 std::move(callback).Run(HandleReadCompleted(buf.get(), rv));
622 }
623
ReadIfReadyCompleted(CompletionOnceCallback callback,int rv)624 void TCPSocketPosix::ReadIfReadyCompleted(CompletionOnceCallback callback,
625 int rv) {
626 DCHECK_NE(ERR_IO_PENDING, rv);
627 DCHECK_GE(OK, rv);
628
629 HandleReadCompletedHelper(rv);
630 std::move(callback).Run(rv);
631 }
632
HandleReadCompleted(IOBuffer * buf,int rv)633 int TCPSocketPosix::HandleReadCompleted(IOBuffer* buf, int rv) {
634 HandleReadCompletedHelper(rv);
635
636 if (rv < 0)
637 return rv;
638
639 // Notify the watcher only if at least 1 byte was read.
640 if (rv > 0)
641 NotifySocketPerformanceWatcher();
642
643 net_log_.AddByteTransferEvent(NetLogEventType::SOCKET_BYTES_RECEIVED, rv,
644 buf->data());
645 activity_monitor::IncrementBytesReceived(rv);
646
647 return rv;
648 }
649
HandleReadCompletedHelper(int rv)650 void TCPSocketPosix::HandleReadCompletedHelper(int rv) {
651 if (rv < 0) {
652 NetLogSocketError(net_log_, NetLogEventType::SOCKET_READ_ERROR, rv, errno);
653 }
654 }
655
WriteCompleted(const scoped_refptr<IOBuffer> & buf,CompletionOnceCallback callback,int rv)656 void TCPSocketPosix::WriteCompleted(const scoped_refptr<IOBuffer>& buf,
657 CompletionOnceCallback callback,
658 int rv) {
659 DCHECK_NE(ERR_IO_PENDING, rv);
660 std::move(callback).Run(HandleWriteCompleted(buf.get(), rv));
661 }
662
HandleWriteCompleted(IOBuffer * buf,int rv)663 int TCPSocketPosix::HandleWriteCompleted(IOBuffer* buf, int rv) {
664 if (rv < 0) {
665 NetLogSocketError(net_log_, NetLogEventType::SOCKET_WRITE_ERROR, rv, errno);
666 return rv;
667 }
668
669 // Notify the watcher only if at least 1 byte was written.
670 if (rv > 0)
671 NotifySocketPerformanceWatcher();
672
673 net_log_.AddByteTransferEvent(NetLogEventType::SOCKET_BYTES_SENT, rv,
674 buf->data());
675 return rv;
676 }
677
NotifySocketPerformanceWatcher()678 void TCPSocketPosix::NotifySocketPerformanceWatcher() {
679 #if defined(HAVE_TCP_INFO)
680 // Check if |socket_performance_watcher_| is interested in receiving a RTT
681 // update notification.
682 if (!socket_performance_watcher_ ||
683 !socket_performance_watcher_->ShouldNotifyUpdatedRTT()) {
684 return;
685 }
686
687 base::TimeDelta rtt = GetTransportRtt(socket_->socket_fd());
688 if (rtt.is_zero())
689 return;
690
691 socket_performance_watcher_->OnUpdatedRTTAvailable(rtt);
692 #endif // defined(TCP_INFO)
693 }
694
GetEstimatedRoundTripTime(base::TimeDelta * out_rtt) const695 bool TCPSocketPosix::GetEstimatedRoundTripTime(base::TimeDelta* out_rtt) const {
696 DCHECK(out_rtt);
697 if (!socket_)
698 return false;
699
700 #if defined(HAVE_TCP_INFO)
701 base::TimeDelta rtt = GetTransportRtt(socket_->socket_fd());
702 if (rtt.is_zero())
703 return false;
704 *out_rtt = rtt;
705 return true;
706 #else
707 return false;
708 #endif // defined(TCP_INFO)
709 }
710
711 } // namespace net
712