blob: 5d9e25e5eadeb7769b74e19bdae80c3233b5a2dc [file] [log] [blame]
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
sehr@google.comfdc90062009-11-26 09:28:02 +09002// 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>
xians@chromium.orgf7d9af82012-04-19 19:23:03 +09008#include <fcntl.h>
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +09009#include <limits.h>
avia6a6a682015-12-27 07:15:14 +090010#include <stddef.h>
sehr@google.comfdc90062009-11-26 09:28:02 +090011#include <stdio.h>
sehr@google.comb72918f2009-12-07 04:45:08 +090012#include <sys/ioctl.h>
sehr@google.comfdc90062009-11-26 09:28:02 +090013#include <sys/socket.h>
xians@chromium.orgf7d9af82012-04-19 19:23:03 +090014#include <sys/types.h>
sehr@google.comfdc90062009-11-26 09:28:02 +090015
chromium@hybridsource.org8f85a6a2011-06-25 13:54:41 +090016#if defined(OS_SOLARIS)
17#include <sys/filio.h>
18#endif
19
brettw@chromium.org01f3da42014-08-14 05:22:14 +090020#include "base/files/file_util.h"
sehr@google.comfdc90062009-11-26 09:28:02 +090021#include "base/logging.h"
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +090022#include "base/threading/thread_restrictions.h"
avia6a6a682015-12-27 07:15:14 +090023#include "build/build_config.h"
sehr@google.comfdc90062009-11-26 09:28:02 +090024
25namespace base {
26
27namespace {
28// To avoid users sending negative message lengths to Send/Receive
29// we clamp message lengths, which are size_t, to no more than INT_MAX.
30const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
31
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +090032// Writes |length| of |buffer| into |handle|. Returns the number of bytes
33// written or zero on error. |length| must be greater than 0.
34size_t SendHelper(SyncSocket::Handle handle,
35 const void* buffer,
36 size_t length) {
37 DCHECK_GT(length, 0u);
38 DCHECK_LE(length, kMaxMessageLength);
39 DCHECK_NE(handle, SyncSocket::kInvalidHandle);
40 const char* charbuffer = static_cast<const char*>(buffer);
chirantan05106cc2014-10-08 08:15:30 +090041 return WriteFileDescriptor(handle, charbuffer, length)
42 ? static_cast<size_t>(length)
43 : 0;
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +090044}
45
dalecurtis@chromium.org5df2c4a2013-11-02 04:58:12 +090046bool CloseHandle(SyncSocket::Handle handle) {
47 if (handle != SyncSocket::kInvalidHandle && close(handle) < 0) {
48 DPLOG(ERROR) << "close";
49 return false;
50 }
51
52 return true;
53}
54
sehr@google.comfdc90062009-11-26 09:28:02 +090055} // namespace
56
groby@chromium.orge870b642011-12-23 04:33:27 +090057const SyncSocket::Handle SyncSocket::kInvalidHandle = -1;
58
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +090059SyncSocket::SyncSocket() : handle_(kInvalidHandle) {}
60
61SyncSocket::~SyncSocket() {
62 Close();
63}
64
65// static
66bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +090067 DCHECK_NE(socket_a, socket_b);
68 DCHECK_EQ(socket_a->handle_, kInvalidHandle);
69 DCHECK_EQ(socket_b->handle_, kInvalidHandle);
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +090070
sehr@google.comfdc90062009-11-26 09:28:02 +090071#if defined(OS_MACOSX)
72 int nosigpipe = 1;
73#endif // defined(OS_MACOSX)
74
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +090075 Handle handles[2] = { kInvalidHandle, kInvalidHandle };
dalecurtis@chromium.org5df2c4a2013-11-02 04:58:12 +090076 if (socketpair(AF_UNIX, SOCK_STREAM, 0, handles) != 0) {
77 CloseHandle(handles[0]);
78 CloseHandle(handles[1]);
79 return false;
80 }
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +090081
sehr@google.comfdc90062009-11-26 09:28:02 +090082#if defined(OS_MACOSX)
83 // On OSX an attempt to read or write to a closed socket may generate a
84 // SIGPIPE rather than returning -1. setsockopt will shut this off.
85 if (0 != setsockopt(handles[0], SOL_SOCKET, SO_NOSIGPIPE,
86 &nosigpipe, sizeof nosigpipe) ||
87 0 != setsockopt(handles[1], SOL_SOCKET, SO_NOSIGPIPE,
88 &nosigpipe, sizeof nosigpipe)) {
dalecurtis@chromium.org5df2c4a2013-11-02 04:58:12 +090089 CloseHandle(handles[0]);
90 CloseHandle(handles[1]);
91 return false;
sehr@google.comfdc90062009-11-26 09:28:02 +090092 }
93#endif
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +090094
sehr@google.comfdc90062009-11-26 09:28:02 +090095 // Copy the handles out for successful return.
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +090096 socket_a->handle_ = handles[0];
97 socket_b->handle_ = handles[1];
98
sehr@google.comfdc90062009-11-26 09:28:02 +090099 return true;
sehr@google.comfdc90062009-11-26 09:28:02 +0900100}
101
burnik81ab7622014-09-08 15:58:22 +0900102// static
103SyncSocket::Handle SyncSocket::UnwrapHandle(
104 const TransitDescriptor& descriptor) {
105 return descriptor.fd;
106}
107
108bool SyncSocket::PrepareTransitDescriptor(ProcessHandle peer_process_handle,
109 TransitDescriptor* descriptor) {
110 descriptor->fd = handle();
111 descriptor->auto_close = false;
112 return descriptor->fd != kInvalidHandle;
113}
114
sehr@google.comfdc90062009-11-26 09:28:02 +0900115bool SyncSocket::Close() {
dalecurtis@chromium.org5df2c4a2013-11-02 04:58:12 +0900116 const bool retval = CloseHandle(handle_);
sehr@google.comfdc90062009-11-26 09:28:02 +0900117 handle_ = kInvalidHandle;
dalecurtis@chromium.org5df2c4a2013-11-02 04:58:12 +0900118 return retval;
sehr@google.comfdc90062009-11-26 09:28:02 +0900119}
120
121size_t SyncSocket::Send(const void* buffer, size_t length) {
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900122 ThreadRestrictions::AssertIOAllowed();
123 return SendHelper(handle_, buffer, length);
sehr@google.comfdc90062009-11-26 09:28:02 +0900124}
125
126size_t SyncSocket::Receive(void* buffer, size_t length) {
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900127 ThreadRestrictions::AssertIOAllowed();
128 DCHECK_GT(length, 0u);
kushi.p@gmail.come4869772011-04-22 22:13:07 +0900129 DCHECK_LE(length, kMaxMessageLength);
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900130 DCHECK_NE(handle_, kInvalidHandle);
sehr@google.comfdc90062009-11-26 09:28:02 +0900131 char* charbuffer = static_cast<char*>(buffer);
brettw@chromium.org2873d9b2013-11-28 08:22:08 +0900132 if (ReadFromFD(handle_, charbuffer, length))
sehr@google.comfdc90062009-11-26 09:28:02 +0900133 return length;
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +0900134 return 0;
sehr@google.comfdc90062009-11-26 09:28:02 +0900135}
136
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900137size_t SyncSocket::ReceiveWithTimeout(void* buffer,
138 size_t length,
139 TimeDelta timeout) {
140 ThreadRestrictions::AssertIOAllowed();
141 DCHECK_GT(length, 0u);
142 DCHECK_LE(length, kMaxMessageLength);
143 DCHECK_NE(handle_, kInvalidHandle);
dalecurtis@google.com345e71a2013-11-05 09:14:27 +0900144
145 // TODO(dalecurtis): There's an undiagnosed issue on OSX where we're seeing
146 // large numbers of open files which prevents select() from being used. In
147 // this case, the best we can do is Peek() to see if we can Receive() now or
148 // return a timeout error (0) if not. See http://crbug.com/314364.
149 if (handle_ >= FD_SETSIZE)
150 return Peek() < length ? 0 : Receive(buffer, length);
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900151
152 // Only timeouts greater than zero and less than one second are allowed.
153 DCHECK_GT(timeout.InMicroseconds(), 0);
154 DCHECK_LT(timeout.InMicroseconds(),
155 base::TimeDelta::FromSeconds(1).InMicroseconds());
156
157 // Track the start time so we can reduce the timeout as data is read.
158 TimeTicks start_time = TimeTicks::Now();
159 const TimeTicks finish_time = start_time + timeout;
160
161 fd_set read_fds;
162 size_t bytes_read_total;
163 for (bytes_read_total = 0;
164 bytes_read_total < length && timeout.InMicroseconds() > 0;
165 timeout = finish_time - base::TimeTicks::Now()) {
166 FD_ZERO(&read_fds);
167 FD_SET(handle_, &read_fds);
168
169 // Wait for data to become available.
170 struct timeval timeout_struct =
171 { 0, static_cast<suseconds_t>(timeout.InMicroseconds()) };
172 const int select_result =
173 select(handle_ + 1, &read_fds, NULL, NULL, &timeout_struct);
174 // Handle EINTR manually since we need to update the timeout value.
175 if (select_result == -1 && errno == EINTR)
176 continue;
177 if (select_result <= 0)
178 return bytes_read_total;
179
180 // select() only tells us that data is ready for reading, not how much. We
181 // must Peek() for the amount ready for reading to avoid blocking.
182 DCHECK(FD_ISSET(handle_, &read_fds));
183 const size_t bytes_to_read = std::min(Peek(), length - bytes_read_total);
184
185 // There may be zero bytes to read if the socket at the other end closed.
186 if (!bytes_to_read)
187 return bytes_read_total;
188
189 const size_t bytes_received =
190 Receive(static_cast<char*>(buffer) + bytes_read_total, bytes_to_read);
191 bytes_read_total += bytes_received;
192 if (bytes_received != bytes_to_read)
193 return bytes_read_total;
194 }
195
196 return bytes_read_total;
197}
198
cpu@chromium.org750392c2009-12-05 07:53:22 +0900199size_t SyncSocket::Peek() {
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900200 DCHECK_NE(handle_, kInvalidHandle);
201 int number_chars = 0;
202 if (ioctl(handle_, FIONREAD, &number_chars) == -1) {
sehr@google.comb72918f2009-12-07 04:45:08 +0900203 // If there is an error in ioctl, signal that the channel would block.
204 return 0;
205 }
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900206 DCHECK_GE(number_chars, 0);
207 return number_chars;
cpu@chromium.org750392c2009-12-05 07:53:22 +0900208}
209
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +0900210CancelableSyncSocket::CancelableSyncSocket() {}
211CancelableSyncSocket::CancelableSyncSocket(Handle handle)
212 : SyncSocket(handle) {
213}
214
215bool CancelableSyncSocket::Shutdown() {
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900216 DCHECK_NE(handle_, kInvalidHandle);
217 return HANDLE_EINTR(shutdown(handle_, SHUT_RDWR)) >= 0;
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +0900218}
219
xians@chromium.orgf7d9af82012-04-19 19:23:03 +0900220size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900221 DCHECK_GT(length, 0u);
222 DCHECK_LE(length, kMaxMessageLength);
223 DCHECK_NE(handle_, kInvalidHandle);
224
tfarina91856872016-03-09 23:40:13 +0900225 const int flags = fcntl(handle_, F_GETFL);
xians@chromium.orgf7d9af82012-04-19 19:23:03 +0900226 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
227 // Set the socket to non-blocking mode for sending if its original mode
228 // is blocking.
229 fcntl(handle_, F_SETFL, flags | O_NONBLOCK);
230 }
231
dalecurtis@chromium.org96b19df2013-10-20 07:13:19 +0900232 const size_t len = SendHelper(handle_, buffer, length);
xians@chromium.orgf7d9af82012-04-19 19:23:03 +0900233
234 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
235 // Restore the original flags.
236 fcntl(handle_, F_SETFL, flags);
237 }
238
239 return len;
240}
241
tommi@chromium.orgd5f359a2012-01-25 21:04:17 +0900242// static
243bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
244 CancelableSyncSocket* socket_b) {
245 return SyncSocket::CreatePair(socket_a, socket_b);
246}
247
sehr@google.comfdc90062009-11-26 09:28:02 +0900248} // namespace base