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.
4
5#include "base/sync_socket.h"
6
7#include <errno.h>
8#include <fcntl.h>
9#include <limits.h>
10#include <stdio.h>
11#include <sys/ioctl.h>
12#include <sys/socket.h>
13#include <sys/types.h>
14
15#if defined(OS_SOLARIS)
16#include <sys/filio.h>
17#endif
18
19#include "base/files/file_util.h"
20#include "base/logging.h"
21#include "base/threading/thread_restrictions.h"
22
23namespace base {
24
25namespace {
26// To avoid users sending negative message lengths to Send/Receive
27// we clamp message lengths, which are size_t, to no more than INT_MAX.
28const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
29
30// Writes |length| of |buffer| into |handle|.  Returns the number of bytes
31// written or zero on error.  |length| must be greater than 0.
32size_t SendHelper(SyncSocket::Handle handle,
33                  const void* buffer,
34                  size_t length) {
35  DCHECK_GT(length, 0u);
36  DCHECK_LE(length, kMaxMessageLength);
37  DCHECK_NE(handle, SyncSocket::kInvalidHandle);
38  const char* charbuffer = static_cast<const char*>(buffer);
39  const int len = WriteFileDescriptor(handle, charbuffer, length);
40  return len < 0 ? 0 : static_cast<size_t>(len);
41}
42
43bool CloseHandle(SyncSocket::Handle handle) {
44  if (handle != SyncSocket::kInvalidHandle && close(handle) < 0) {
45    DPLOG(ERROR) << "close";
46    return false;
47  }
48
49  return true;
50}
51
52}  // namespace
53
54const SyncSocket::Handle SyncSocket::kInvalidHandle = -1;
55
56SyncSocket::SyncSocket() : handle_(kInvalidHandle) {}
57
58SyncSocket::~SyncSocket() {
59  Close();
60}
61
62// static
63bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
64  DCHECK_NE(socket_a, socket_b);
65  DCHECK_EQ(socket_a->handle_, kInvalidHandle);
66  DCHECK_EQ(socket_b->handle_, kInvalidHandle);
67
68#if defined(OS_MACOSX)
69  int nosigpipe = 1;
70#endif  // defined(OS_MACOSX)
71
72  Handle handles[2] = { kInvalidHandle, kInvalidHandle };
73  if (socketpair(AF_UNIX, SOCK_STREAM, 0, handles) != 0) {
74    CloseHandle(handles[0]);
75    CloseHandle(handles[1]);
76    return false;
77  }
78
79#if defined(OS_MACOSX)
80  // On OSX an attempt to read or write to a closed socket may generate a
81  // SIGPIPE rather than returning -1.  setsockopt will shut this off.
82  if (0 != setsockopt(handles[0], SOL_SOCKET, SO_NOSIGPIPE,
83                      &nosigpipe, sizeof nosigpipe) ||
84      0 != setsockopt(handles[1], SOL_SOCKET, SO_NOSIGPIPE,
85                      &nosigpipe, sizeof nosigpipe)) {
86    CloseHandle(handles[0]);
87    CloseHandle(handles[1]);
88    return false;
89  }
90#endif
91
92  // Copy the handles out for successful return.
93  socket_a->handle_ = handles[0];
94  socket_b->handle_ = handles[1];
95
96  return true;
97}
98
99// static
100SyncSocket::Handle SyncSocket::UnwrapHandle(
101    const TransitDescriptor& descriptor) {
102  return descriptor.fd;
103}
104
105bool SyncSocket::PrepareTransitDescriptor(ProcessHandle peer_process_handle,
106                                          TransitDescriptor* descriptor) {
107  descriptor->fd = handle();
108  descriptor->auto_close = false;
109  return descriptor->fd != kInvalidHandle;
110}
111
112bool SyncSocket::Close() {
113  const bool retval = CloseHandle(handle_);
114  handle_ = kInvalidHandle;
115  return retval;
116}
117
118size_t SyncSocket::Send(const void* buffer, size_t length) {
119  ThreadRestrictions::AssertIOAllowed();
120  return SendHelper(handle_, buffer, length);
121}
122
123size_t SyncSocket::Receive(void* buffer, size_t length) {
124  ThreadRestrictions::AssertIOAllowed();
125  DCHECK_GT(length, 0u);
126  DCHECK_LE(length, kMaxMessageLength);
127  DCHECK_NE(handle_, kInvalidHandle);
128  char* charbuffer = static_cast<char*>(buffer);
129  if (ReadFromFD(handle_, charbuffer, length))
130    return length;
131  return 0;
132}
133
134size_t SyncSocket::ReceiveWithTimeout(void* buffer,
135                                      size_t length,
136                                      TimeDelta timeout) {
137  ThreadRestrictions::AssertIOAllowed();
138  DCHECK_GT(length, 0u);
139  DCHECK_LE(length, kMaxMessageLength);
140  DCHECK_NE(handle_, kInvalidHandle);
141
142  // TODO(dalecurtis): There's an undiagnosed issue on OSX where we're seeing
143  // large numbers of open files which prevents select() from being used.  In
144  // this case, the best we can do is Peek() to see if we can Receive() now or
145  // return a timeout error (0) if not.  See http://crbug.com/314364.
146  if (handle_ >= FD_SETSIZE)
147    return Peek() < length ? 0 : Receive(buffer, length);
148
149  // Only timeouts greater than zero and less than one second are allowed.
150  DCHECK_GT(timeout.InMicroseconds(), 0);
151  DCHECK_LT(timeout.InMicroseconds(),
152            base::TimeDelta::FromSeconds(1).InMicroseconds());
153
154  // Track the start time so we can reduce the timeout as data is read.
155  TimeTicks start_time = TimeTicks::Now();
156  const TimeTicks finish_time = start_time + timeout;
157
158  fd_set read_fds;
159  size_t bytes_read_total;
160  for (bytes_read_total = 0;
161       bytes_read_total < length && timeout.InMicroseconds() > 0;
162       timeout = finish_time - base::TimeTicks::Now()) {
163    FD_ZERO(&read_fds);
164    FD_SET(handle_, &read_fds);
165
166    // Wait for data to become available.
167    struct timeval timeout_struct =
168        { 0, static_cast<suseconds_t>(timeout.InMicroseconds()) };
169    const int select_result =
170        select(handle_ + 1, &read_fds, NULL, NULL, &timeout_struct);
171    // Handle EINTR manually since we need to update the timeout value.
172    if (select_result == -1 && errno == EINTR)
173      continue;
174    if (select_result <= 0)
175      return bytes_read_total;
176
177    // select() only tells us that data is ready for reading, not how much.  We
178    // must Peek() for the amount ready for reading to avoid blocking.
179    DCHECK(FD_ISSET(handle_, &read_fds));
180    const size_t bytes_to_read = std::min(Peek(), length - bytes_read_total);
181
182    // There may be zero bytes to read if the socket at the other end closed.
183    if (!bytes_to_read)
184      return bytes_read_total;
185
186    const size_t bytes_received =
187        Receive(static_cast<char*>(buffer) + bytes_read_total, bytes_to_read);
188    bytes_read_total += bytes_received;
189    if (bytes_received != bytes_to_read)
190      return bytes_read_total;
191  }
192
193  return bytes_read_total;
194}
195
196size_t SyncSocket::Peek() {
197  DCHECK_NE(handle_, kInvalidHandle);
198  int number_chars = 0;
199  if (ioctl(handle_, FIONREAD, &number_chars) == -1) {
200    // If there is an error in ioctl, signal that the channel would block.
201    return 0;
202  }
203  DCHECK_GE(number_chars, 0);
204  return number_chars;
205}
206
207CancelableSyncSocket::CancelableSyncSocket() {}
208CancelableSyncSocket::CancelableSyncSocket(Handle handle)
209    : SyncSocket(handle) {
210}
211
212bool CancelableSyncSocket::Shutdown() {
213  DCHECK_NE(handle_, kInvalidHandle);
214  return HANDLE_EINTR(shutdown(handle_, SHUT_RDWR)) >= 0;
215}
216
217size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
218  DCHECK_GT(length, 0u);
219  DCHECK_LE(length, kMaxMessageLength);
220  DCHECK_NE(handle_, kInvalidHandle);
221
222  const long flags = fcntl(handle_, F_GETFL, NULL);
223  if (flags != -1 && (flags & O_NONBLOCK) == 0) {
224    // Set the socket to non-blocking mode for sending if its original mode
225    // is blocking.
226    fcntl(handle_, F_SETFL, flags | O_NONBLOCK);
227  }
228
229  const size_t len = SendHelper(handle_, buffer, length);
230
231  if (flags != -1 && (flags & O_NONBLOCK) == 0) {
232    // Restore the original flags.
233    fcntl(handle_, F_SETFL, flags);
234  }
235
236  return len;
237}
238
239// static
240bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
241                                      CancelableSyncSocket* socket_b) {
242  return SyncSocket::CreatePair(socket_a, socket_b);
243}
244
245}  // namespace base
246