1 // Copyright 2012 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 "base/sync_socket.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <limits.h>
10 #include <poll.h>
11 #include <stddef.h>
12 #include <stdio.h>
13 #include <sys/ioctl.h>
14 #include <sys/socket.h>
15 #include <sys/types.h>
16
17 #include "base/check_op.h"
18 #include "base/containers/span.h"
19 #include "base/files/file_util.h"
20 #include "base/numerics/safe_conversions.h"
21 #include "base/threading/scoped_blocking_call.h"
22 #include "build/build_config.h"
23
24 #if BUILDFLAG(IS_SOLARIS)
25 #include <sys/filio.h>
26 #endif
27
28 namespace base {
29
30 namespace {
31 // To avoid users sending negative message lengths to Send/Receive
32 // we clamp message lengths, which are size_t, to no more than INT_MAX.
33 const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
34
35 // Writes |length| of |buffer| into |handle|. Returns the number of bytes
36 // written or zero on error. |length| must be greater than 0.
SendHelper(SyncSocket::Handle handle,span<const uint8_t> data)37 size_t SendHelper(SyncSocket::Handle handle, span<const uint8_t> data) {
38 CHECK_LE(data.size(), kMaxMessageLength);
39 DCHECK_NE(handle, SyncSocket::kInvalidHandle);
40 return WriteFileDescriptor(handle, data) ? data.size() : 0;
41 }
42
43 } // namespace
44
45 // static
CreatePair(SyncSocket * socket_a,SyncSocket * socket_b)46 bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
47 DCHECK_NE(socket_a, socket_b);
48 DCHECK(!socket_a->IsValid());
49 DCHECK(!socket_b->IsValid());
50
51 #if BUILDFLAG(IS_APPLE)
52 int nosigpipe = 1;
53 #endif // BUILDFLAG(IS_APPLE)
54
55 ScopedHandle handles[2];
56
57 {
58 Handle raw_handles[2] = {kInvalidHandle, kInvalidHandle};
59 if (socketpair(AF_UNIX, SOCK_STREAM, 0, raw_handles) != 0) {
60 return false;
61 }
62 handles[0].reset(raw_handles[0]);
63 handles[1].reset(raw_handles[1]);
64 }
65
66 #if BUILDFLAG(IS_APPLE)
67 // On OSX an attempt to read or write to a closed socket may generate a
68 // SIGPIPE rather than returning -1. setsockopt will shut this off.
69 if (0 != setsockopt(handles[0].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
70 sizeof(nosigpipe)) ||
71 0 != setsockopt(handles[1].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
72 sizeof(nosigpipe))) {
73 return false;
74 }
75 #endif
76
77 // Copy the handles out for successful return.
78 socket_a->handle_ = std::move(handles[0]);
79 socket_b->handle_ = std::move(handles[1]);
80
81 return true;
82 }
83
Close()84 void SyncSocket::Close() {
85 handle_.reset();
86 }
87
Send(span<const uint8_t> data)88 size_t SyncSocket::Send(span<const uint8_t> data) {
89 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
90 return SendHelper(handle(), data);
91 }
92
Send(const void * buffer,size_t length)93 size_t SyncSocket::Send(const void* buffer, size_t length) {
94 return Send(make_span(static_cast<const uint8_t*>(buffer), length));
95 }
96
Receive(span<uint8_t> buffer)97 size_t SyncSocket::Receive(span<uint8_t> buffer) {
98 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
99 CHECK_LE(buffer.size(), kMaxMessageLength);
100 DCHECK(IsValid());
101 if (ReadFromFD(handle(), as_writable_chars(buffer))) {
102 return buffer.size();
103 }
104 return 0;
105 }
106
ReceiveWithTimeout(void * buffer,size_t length,TimeDelta timeout)107 size_t SyncSocket::ReceiveWithTimeout(void* buffer,
108 size_t length,
109 TimeDelta timeout) {
110 return ReceiveWithTimeout(make_span(static_cast<uint8_t*>(buffer), length),
111 std::move(timeout));
112 }
113
Receive(void * buffer,size_t length)114 size_t SyncSocket::Receive(void* buffer, size_t length) {
115 return Receive(make_span(static_cast<uint8_t*>(buffer), length));
116 }
117
ReceiveWithTimeout(span<uint8_t> buffer,TimeDelta timeout)118 size_t SyncSocket::ReceiveWithTimeout(span<uint8_t> buffer, TimeDelta timeout) {
119 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
120 CHECK_LE(buffer.size(), kMaxMessageLength);
121 DCHECK(IsValid());
122
123 // Only timeouts greater than zero and less than one second are allowed.
124 DCHECK_GT(timeout.InMicroseconds(), 0);
125 DCHECK_LT(timeout.InMicroseconds(), Seconds(1).InMicroseconds());
126
127 // Track the start time so we can reduce the timeout as data is read.
128 TimeTicks start_time = TimeTicks::Now();
129 const TimeTicks finish_time = start_time + timeout;
130
131 struct pollfd pollfd;
132 pollfd.fd = handle();
133 pollfd.events = POLLIN;
134 pollfd.revents = 0;
135
136 size_t bytes_read_total = 0;
137 while (!buffer.empty()) {
138 const TimeDelta this_timeout = finish_time - TimeTicks::Now();
139 const int timeout_ms =
140 static_cast<int>(this_timeout.InMillisecondsRoundedUp());
141 if (timeout_ms <= 0)
142 break;
143 const int poll_result = poll(&pollfd, 1, timeout_ms);
144 // Handle EINTR manually since we need to update the timeout value.
145 if (poll_result == -1 && errno == EINTR)
146 continue;
147 // Return if other type of error or a timeout.
148 if (poll_result <= 0)
149 return bytes_read_total;
150
151 // poll() only tells us that data is ready for reading, not how much. We
152 // must Peek() for the amount ready for reading to avoid blocking.
153 // At hang up (POLLHUP), the write end has been closed and there might still
154 // be data to be read.
155 // No special handling is needed for error (POLLERR); we can let any of the
156 // following operations fail and handle it there.
157 DCHECK(pollfd.revents & (POLLIN | POLLHUP | POLLERR)) << pollfd.revents;
158 const size_t bytes_to_read = std::min(Peek(), buffer.size());
159
160 // There may be zero bytes to read if the socket at the other end closed.
161 if (!bytes_to_read)
162 return bytes_read_total;
163
164 const size_t bytes_received = Receive(buffer.subspan(0u, bytes_to_read));
165 bytes_read_total += bytes_received;
166 buffer = buffer.subspan(bytes_received);
167 if (bytes_received != bytes_to_read)
168 return bytes_read_total;
169 }
170
171 return bytes_read_total;
172 }
173
Peek()174 size_t SyncSocket::Peek() {
175 DCHECK(IsValid());
176 int number_chars = 0;
177 if (ioctl(handle_.get(), FIONREAD, &number_chars) == -1) {
178 // If there is an error in ioctl, signal that the channel would block.
179 return 0;
180 }
181 return checked_cast<size_t>(number_chars);
182 }
183
IsValid() const184 bool SyncSocket::IsValid() const {
185 return handle_.is_valid();
186 }
187
handle() const188 SyncSocket::Handle SyncSocket::handle() const {
189 return handle_.get();
190 }
191
Release()192 SyncSocket::Handle SyncSocket::Release() {
193 return handle_.release();
194 }
195
Shutdown()196 bool CancelableSyncSocket::Shutdown() {
197 DCHECK(IsValid());
198 return HANDLE_EINTR(shutdown(handle(), SHUT_RDWR)) >= 0;
199 }
200
Send(span<const uint8_t> data)201 size_t CancelableSyncSocket::Send(span<const uint8_t> data) {
202 CHECK_LE(data.size(), kMaxMessageLength);
203 DCHECK(IsValid());
204
205 const int flags = fcntl(handle(), F_GETFL);
206 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
207 // Set the socket to non-blocking mode for sending if its original mode
208 // is blocking.
209 fcntl(handle(), F_SETFL, flags | O_NONBLOCK);
210 }
211
212 const size_t len = SendHelper(handle(), data);
213
214 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
215 // Restore the original flags.
216 fcntl(handle(), F_SETFL, flags);
217 }
218
219 return len;
220 }
221
Send(const void * buffer,size_t length)222 size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
223 return Send(make_span(static_cast<const uint8_t*>(buffer), length));
224 }
225
226 // static
CreatePair(CancelableSyncSocket * socket_a,CancelableSyncSocket * socket_b)227 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
228 CancelableSyncSocket* socket_b) {
229 return SyncSocket::CreatePair(socket_a, socket_b);
230 }
231
232 } // namespace base
233