blob: 86a47b5c14198ce8f709a1309478780c652d2d88 [file] [log] [blame]
[email protected]532e9bd2012-01-25 12:04:171// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]182c44fa2009-11-26 00:28:022// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/sync_socket.h"
6
7#include <errno.h>
[email protected]5d272092012-04-19 10:23:038#include <fcntl.h>
[email protected]62558f12013-10-19 22:13:199#include <limits.h>
grunellb464b3e2017-05-23 11:15:2610#include <poll.h>
avi9b6f42932015-12-26 22:15:1411#include <stddef.h>
[email protected]182c44fa2009-11-26 00:28:0212#include <stdio.h>
[email protected]1e1f1a72009-12-06 19:45:0813#include <sys/ioctl.h>
[email protected]182c44fa2009-11-26 00:28:0214#include <sys/socket.h>
[email protected]5d272092012-04-19 10:23:0315#include <sys/types.h>
[email protected]182c44fa2009-11-26 00:28:0216
[email protected]94f8c952011-06-25 04:54:4117#if defined(OS_SOLARIS)
18#include <sys/filio.h>
19#endif
20
Hans Wennborgc3cffa62020-04-27 10:09:1221#include "base/check_op.h"
Lei Zhangc9e8a162021-05-14 09:33:5222#include "base/containers/span.h"
[email protected]e3177dd52014-08-13 20:22:1423#include "base/files/file_util.h"
Etienne Pierre-Doray3879b052018-09-17 14:17:2224#include "base/threading/scoped_blocking_call.h"
avi9b6f42932015-12-26 22:15:1425#include "build/build_config.h"
[email protected]182c44fa2009-11-26 00:28:0226
27namespace base {
28
29namespace {
30// To avoid users sending negative message lengths to Send/Receive
31// we clamp message lengths, which are size_t, to no more than INT_MAX.
32const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
33
[email protected]62558f12013-10-19 22:13:1934// Writes |length| of |buffer| into |handle|. Returns the number of bytes
35// written or zero on error. |length| must be greater than 0.
36size_t SendHelper(SyncSocket::Handle handle,
37 const void* buffer,
38 size_t length) {
39 DCHECK_GT(length, 0u);
40 DCHECK_LE(length, kMaxMessageLength);
41 DCHECK_NE(handle, SyncSocket::kInvalidHandle);
Lei Zhangc9e8a162021-05-14 09:33:5242 return WriteFileDescriptor(
43 handle, make_span(static_cast<const uint8_t*>(buffer), length))
44 ? length
chirantan75ea2fd2014-10-07 23:15:3045 : 0;
[email protected]62558f12013-10-19 22:13:1946}
47
[email protected]182c44fa2009-11-26 00:28:0248} // namespace
49
[email protected]532e9bd2012-01-25 12:04:1750// static
51bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
[email protected]62558f12013-10-19 22:13:1952 DCHECK_NE(socket_a, socket_b);
Robert Sesek6ab73b022020-02-13 16:42:3953 DCHECK(!socket_a->IsValid());
54 DCHECK(!socket_b->IsValid());
[email protected]532e9bd2012-01-25 12:04:1755
Avi Drissman5b286372020-07-28 21:59:3856#if defined(OS_APPLE)
[email protected]182c44fa2009-11-26 00:28:0257 int nosigpipe = 1;
Avi Drissman5b286372020-07-28 21:59:3858#endif // defined(OS_APPLE)
[email protected]182c44fa2009-11-26 00:28:0259
Robert Sesek6ab73b022020-02-13 16:42:3960 ScopedHandle handles[2];
61
62 {
63 Handle raw_handles[2] = {kInvalidHandle, kInvalidHandle};
64 if (socketpair(AF_UNIX, SOCK_STREAM, 0, raw_handles) != 0) {
65 return false;
66 }
67 handles[0].reset(raw_handles[0]);
68 handles[1].reset(raw_handles[1]);
[email protected]1da08e72013-11-01 19:58:1269 }
[email protected]532e9bd2012-01-25 12:04:1770
Avi Drissman5b286372020-07-28 21:59:3871#if defined(OS_APPLE)
[email protected]182c44fa2009-11-26 00:28:0272 // On OSX an attempt to read or write to a closed socket may generate a
73 // SIGPIPE rather than returning -1. setsockopt will shut this off.
Robert Sesek6ab73b022020-02-13 16:42:3974 if (0 != setsockopt(handles[0].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
75 sizeof(nosigpipe)) ||
76 0 != setsockopt(handles[1].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
77 sizeof(nosigpipe))) {
[email protected]1da08e72013-11-01 19:58:1278 return false;
[email protected]182c44fa2009-11-26 00:28:0279 }
80#endif
[email protected]532e9bd2012-01-25 12:04:1781
[email protected]182c44fa2009-11-26 00:28:0282 // Copy the handles out for successful return.
Robert Sesek6ab73b022020-02-13 16:42:3983 socket_a->handle_ = std::move(handles[0]);
84 socket_b->handle_ = std::move(handles[1]);
[email protected]532e9bd2012-01-25 12:04:1785
[email protected]182c44fa2009-11-26 00:28:0286 return true;
[email protected]182c44fa2009-11-26 00:28:0287}
88
Robert Sesek6ab73b022020-02-13 16:42:3989void SyncSocket::Close() {
90 handle_.reset();
[email protected]182c44fa2009-11-26 00:28:0291}
92
93size_t SyncSocket::Send(const void* buffer, size_t length) {
Etienne Bergeron436d42212019-02-26 17:15:1294 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
Robert Sesek6ab73b022020-02-13 16:42:3995 return SendHelper(handle(), buffer, length);
[email protected]182c44fa2009-11-26 00:28:0296}
97
98size_t SyncSocket::Receive(void* buffer, size_t length) {
Etienne Bergeron436d42212019-02-26 17:15:1299 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
[email protected]62558f12013-10-19 22:13:19100 DCHECK_GT(length, 0u);
[email protected]d7a93ad2011-04-22 13:13:07101 DCHECK_LE(length, kMaxMessageLength);
Robert Sesek6ab73b022020-02-13 16:42:39102 DCHECK(IsValid());
[email protected]182c44fa2009-11-26 00:28:02103 char* charbuffer = static_cast<char*>(buffer);
Robert Sesek6ab73b022020-02-13 16:42:39104 if (ReadFromFD(handle(), charbuffer, length))
[email protected]182c44fa2009-11-26 00:28:02105 return length;
[email protected]532e9bd2012-01-25 12:04:17106 return 0;
[email protected]182c44fa2009-11-26 00:28:02107}
108
[email protected]62558f12013-10-19 22:13:19109size_t SyncSocket::ReceiveWithTimeout(void* buffer,
110 size_t length,
111 TimeDelta timeout) {
Etienne Bergeron436d42212019-02-26 17:15:12112 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
[email protected]62558f12013-10-19 22:13:19113 DCHECK_GT(length, 0u);
114 DCHECK_LE(length, kMaxMessageLength);
Robert Sesek6ab73b022020-02-13 16:42:39115 DCHECK(IsValid());
[email protected]1bc4379e2013-11-05 00:14:27116
[email protected]62558f12013-10-19 22:13:19117 // Only timeouts greater than zero and less than one second are allowed.
118 DCHECK_GT(timeout.InMicroseconds(), 0);
119 DCHECK_LT(timeout.InMicroseconds(),
grunellb464b3e2017-05-23 11:15:26120 TimeDelta::FromSeconds(1).InMicroseconds());
[email protected]62558f12013-10-19 22:13:19121
122 // Track the start time so we can reduce the timeout as data is read.
123 TimeTicks start_time = TimeTicks::Now();
124 const TimeTicks finish_time = start_time + timeout;
125
grunellb464b3e2017-05-23 11:15:26126 struct pollfd pollfd;
Robert Sesek6ab73b022020-02-13 16:42:39127 pollfd.fd = handle();
grunellb464b3e2017-05-23 11:15:26128 pollfd.events = POLLIN;
129 pollfd.revents = 0;
[email protected]62558f12013-10-19 22:13:19130
grunellb464b3e2017-05-23 11:15:26131 size_t bytes_read_total = 0;
132 while (bytes_read_total < length) {
133 const TimeDelta this_timeout = finish_time - TimeTicks::Now();
134 const int timeout_ms =
135 static_cast<int>(this_timeout.InMillisecondsRoundedUp());
136 if (timeout_ms <= 0)
137 break;
138 const int poll_result = poll(&pollfd, 1, timeout_ms);
[email protected]62558f12013-10-19 22:13:19139 // Handle EINTR manually since we need to update the timeout value.
grunellb464b3e2017-05-23 11:15:26140 if (poll_result == -1 && errno == EINTR)
[email protected]62558f12013-10-19 22:13:19141 continue;
grunellb464b3e2017-05-23 11:15:26142 // Return if other type of error or a timeout.
143 if (poll_result <= 0)
[email protected]62558f12013-10-19 22:13:19144 return bytes_read_total;
145
grunellb464b3e2017-05-23 11:15:26146 // poll() only tells us that data is ready for reading, not how much. We
[email protected]62558f12013-10-19 22:13:19147 // must Peek() for the amount ready for reading to avoid blocking.
grunellb464b3e2017-05-23 11:15:26148 // At hang up (POLLHUP), the write end has been closed and there might still
149 // be data to be read.
150 // No special handling is needed for error (POLLERR); we can let any of the
151 // following operations fail and handle it there.
152 DCHECK(pollfd.revents & (POLLIN | POLLHUP | POLLERR)) << pollfd.revents;
[email protected]62558f12013-10-19 22:13:19153 const size_t bytes_to_read = std::min(Peek(), length - bytes_read_total);
154
155 // There may be zero bytes to read if the socket at the other end closed.
156 if (!bytes_to_read)
157 return bytes_read_total;
158
159 const size_t bytes_received =
160 Receive(static_cast<char*>(buffer) + bytes_read_total, bytes_to_read);
161 bytes_read_total += bytes_received;
162 if (bytes_received != bytes_to_read)
163 return bytes_read_total;
164 }
165
166 return bytes_read_total;
167}
168
[email protected]d8b65912009-12-04 22:53:22169size_t SyncSocket::Peek() {
Robert Sesek6ab73b022020-02-13 16:42:39170 DCHECK(IsValid());
[email protected]62558f12013-10-19 22:13:19171 int number_chars = 0;
Robert Sesek6ab73b022020-02-13 16:42:39172 if (ioctl(handle_.get(), FIONREAD, &number_chars) == -1) {
[email protected]1e1f1a72009-12-06 19:45:08173 // If there is an error in ioctl, signal that the channel would block.
174 return 0;
175 }
[email protected]62558f12013-10-19 22:13:19176 DCHECK_GE(number_chars, 0);
177 return number_chars;
[email protected]d8b65912009-12-04 22:53:22178}
179
Robert Sesek6ab73b022020-02-13 16:42:39180bool SyncSocket::IsValid() const {
181 return handle_.is_valid();
maxmorind4bcb112017-04-13 11:43:13182}
183
Robert Sesek6ab73b022020-02-13 16:42:39184SyncSocket::Handle SyncSocket::handle() const {
185 return handle_.get();
186}
187
188SyncSocket::Handle SyncSocket::Release() {
189 return handle_.release();
[email protected]532e9bd2012-01-25 12:04:17190}
191
192bool CancelableSyncSocket::Shutdown() {
Robert Sesek6ab73b022020-02-13 16:42:39193 DCHECK(IsValid());
194 return HANDLE_EINTR(shutdown(handle(), SHUT_RDWR)) >= 0;
[email protected]532e9bd2012-01-25 12:04:17195}
196
[email protected]5d272092012-04-19 10:23:03197size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
[email protected]62558f12013-10-19 22:13:19198 DCHECK_GT(length, 0u);
199 DCHECK_LE(length, kMaxMessageLength);
Robert Sesek6ab73b022020-02-13 16:42:39200 DCHECK(IsValid());
[email protected]62558f12013-10-19 22:13:19201
Robert Sesek6ab73b022020-02-13 16:42:39202 const int flags = fcntl(handle(), F_GETFL);
[email protected]5d272092012-04-19 10:23:03203 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
204 // Set the socket to non-blocking mode for sending if its original mode
205 // is blocking.
Robert Sesek6ab73b022020-02-13 16:42:39206 fcntl(handle(), F_SETFL, flags | O_NONBLOCK);
[email protected]5d272092012-04-19 10:23:03207 }
208
Robert Sesek6ab73b022020-02-13 16:42:39209 const size_t len = SendHelper(handle(), buffer, length);
[email protected]5d272092012-04-19 10:23:03210
211 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
212 // Restore the original flags.
Robert Sesek6ab73b022020-02-13 16:42:39213 fcntl(handle(), F_SETFL, flags);
[email protected]5d272092012-04-19 10:23:03214 }
215
216 return len;
217}
218
[email protected]532e9bd2012-01-25 12:04:17219// static
220bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
221 CancelableSyncSocket* socket_b) {
222 return SyncSocket::CreatePair(socket_a, socket_b);
223}
224
[email protected]182c44fa2009-11-26 00:28:02225} // namespace base