1 // Copyright (c) 2012 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 "base/sync_socket.h"
13 #include <sys/ioctl.h>
14 #include <sys/socket.h>
15 #include <sys/types.h>
17 #if defined(OS_SOLARIS)
18 #include <sys/filio.h>
21 #include "base/check_op.h"
22 #include "base/containers/span.h"
23 #include "base/files/file_util.h"
24 #include "base/threading/scoped_blocking_call.h"
25 #include "build/build_config.h"
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.
32 const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
34 // Writes |length| of |buffer| into |handle|. Returns the number of bytes
35 // written or zero on error. |length| must be greater than 0.
36 size_t SendHelper(SyncSocket::Handle handle,
39 DCHECK_GT(length, 0u);
40 DCHECK_LE(length, kMaxMessageLength);
41 DCHECK_NE(handle, SyncSocket::kInvalidHandle);
42 return WriteFileDescriptor(
43 handle, make_span(static_cast<const uint8_t*>(buffer), length))
51 bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
52 DCHECK_NE(socket_a, socket_b);
53 DCHECK(!socket_a->IsValid());
54 DCHECK(!socket_b->IsValid());
58 #endif // defined(OS_APPLE)
60 ScopedHandle handles[2];
63 Handle raw_handles[2] = {kInvalidHandle, kInvalidHandle};
64 if (socketpair(AF_UNIX, SOCK_STREAM, 0, raw_handles) != 0) {
67 handles[0].reset(raw_handles[0]);
68 handles[1].reset(raw_handles[1]);
72 // 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.
74 if (0 != setsockopt(handles[0].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
76 0 != setsockopt(handles[1].get(), SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe,
82 // Copy the handles out for successful return.
83 socket_a->handle_ = std::move(handles[0]);
84 socket_b->handle_ = std::move(handles[1]);
89 void SyncSocket::Close() {
93 size_t SyncSocket::Send(const void* buffer, size_t length) {
94 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
95 return SendHelper(handle(), buffer, length);
98 size_t SyncSocket::Receive(void* buffer, size_t length) {
99 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
100 DCHECK_GT(length, 0u);
101 DCHECK_LE(length, kMaxMessageLength);
103 char* charbuffer = static_cast<char*>(buffer);
104 if (ReadFromFD(handle(), charbuffer, length))
109 size_t SyncSocket::ReceiveWithTimeout(void* buffer,
112 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
113 DCHECK_GT(length, 0u);
114 DCHECK_LE(length, kMaxMessageLength);
117 // Only timeouts greater than zero and less than one second are allowed.
118 DCHECK_GT(timeout.InMicroseconds(), 0);
119 DCHECK_LT(timeout.InMicroseconds(),
120 TimeDelta::FromSeconds(1).InMicroseconds());
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;
126 struct pollfd pollfd;
127 pollfd.fd = handle();
128 pollfd.events = POLLIN;
131 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());
138 const int poll_result = poll(&pollfd, 1, timeout_ms);
139 // Handle EINTR manually since we need to update the timeout value.
140 if (poll_result == -1 && errno == EINTR)
142 // Return if other type of error or a timeout.
143 if (poll_result <= 0)
144 return bytes_read_total;
146 // poll() only tells us that data is ready for reading, not how much. We
147 // must Peek() for the amount ready for reading to avoid blocking.
148 // 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;
153 const size_t bytes_to_read = std::min(Peek(), length - bytes_read_total);
155 // There may be zero bytes to read if the socket at the other end closed.
157 return bytes_read_total;
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;
166 return bytes_read_total;
169 size_t SyncSocket::Peek() {
171 int number_chars = 0;
172 if (ioctl(handle_.get(), FIONREAD, &number_chars) == -1) {
173 // If there is an error in ioctl, signal that the channel would block.
176 DCHECK_GE(number_chars, 0);
180 bool SyncSocket::IsValid() const {
181 return handle_.is_valid();
184 SyncSocket::Handle SyncSocket::handle() const {
185 return handle_.get();
188 SyncSocket::Handle SyncSocket::Release() {
189 return handle_.release();
192 bool CancelableSyncSocket::Shutdown() {
194 return HANDLE_EINTR(shutdown(handle(), SHUT_RDWR)) >= 0;
197 size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
198 DCHECK_GT(length, 0u);
199 DCHECK_LE(length, kMaxMessageLength);
202 const int flags = fcntl(handle(), F_GETFL);
203 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
204 // Set the socket to non-blocking mode for sending if its original mode
206 fcntl(handle(), F_SETFL, flags | O_NONBLOCK);
209 const size_t len = SendHelper(handle(), buffer, length);
211 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
212 // Restore the original flags.
213 fcntl(handle(), F_SETFL, flags);
220 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
221 CancelableSyncSocket* socket_b) {
222 return SyncSocket::CreatePair(socket_a, socket_b);