blob: c408de52238e90bbd7a76a927d5c65bedd32beb7 [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>
[email protected]182c44fa2009-11-26 00:28:0210#include <stdio.h>
[email protected]1e1f1a72009-12-06 19:45:0811#include <sys/ioctl.h>
[email protected]182c44fa2009-11-26 00:28:0212#include <sys/socket.h>
[email protected]5d272092012-04-19 10:23:0313#include <sys/types.h>
[email protected]182c44fa2009-11-26 00:28:0214
[email protected]94f8c952011-06-25 04:54:4115#if defined(OS_SOLARIS)
16#include <sys/filio.h>
17#endif
18
[email protected]182c44fa2009-11-26 00:28:0219#include "base/file_util.h"
20#include "base/logging.h"
[email protected]62558f12013-10-19 22:13:1921#include "base/threading/thread_restrictions.h"
[email protected]182c44fa2009-11-26 00:28:0222
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
[email protected]62558f12013-10-19 22:13:1930// 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 = file_util::WriteFileDescriptor(handle, charbuffer, length);
40 return len < 0 ? 0 : static_cast<size_t>(len);
41}
42
[email protected]1da08e72013-11-01 19:58:1243bool 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
[email protected]182c44fa2009-11-26 00:28:0252} // namespace
53
[email protected]5895ee12011-12-22 19:33:2754const SyncSocket::Handle SyncSocket::kInvalidHandle = -1;
55
[email protected]532e9bd2012-01-25 12:04:1756SyncSocket::SyncSocket() : handle_(kInvalidHandle) {}
57
58SyncSocket::~SyncSocket() {
59 Close();
60}
61
62// static
63bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
[email protected]62558f12013-10-19 22:13:1964 DCHECK_NE(socket_a, socket_b);
65 DCHECK_EQ(socket_a->handle_, kInvalidHandle);
66 DCHECK_EQ(socket_b->handle_, kInvalidHandle);
[email protected]532e9bd2012-01-25 12:04:1767
[email protected]182c44fa2009-11-26 00:28:0268#if defined(OS_MACOSX)
69 int nosigpipe = 1;
70#endif // defined(OS_MACOSX)
71
[email protected]532e9bd2012-01-25 12:04:1772 Handle handles[2] = { kInvalidHandle, kInvalidHandle };
[email protected]1da08e72013-11-01 19:58:1273 if (socketpair(AF_UNIX, SOCK_STREAM, 0, handles) != 0) {
74 CloseHandle(handles[0]);
75 CloseHandle(handles[1]);
76 return false;
77 }
[email protected]532e9bd2012-01-25 12:04:1778
[email protected]182c44fa2009-11-26 00:28:0279#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)) {
[email protected]1da08e72013-11-01 19:58:1286 CloseHandle(handles[0]);
87 CloseHandle(handles[1]);
88 return false;
[email protected]182c44fa2009-11-26 00:28:0289 }
90#endif
[email protected]532e9bd2012-01-25 12:04:1791
[email protected]182c44fa2009-11-26 00:28:0292 // Copy the handles out for successful return.
[email protected]532e9bd2012-01-25 12:04:1793 socket_a->handle_ = handles[0];
94 socket_b->handle_ = handles[1];
95
[email protected]182c44fa2009-11-26 00:28:0296 return true;
[email protected]182c44fa2009-11-26 00:28:0297}
98
99bool SyncSocket::Close() {
[email protected]1da08e72013-11-01 19:58:12100 const bool retval = CloseHandle(handle_);
[email protected]182c44fa2009-11-26 00:28:02101 handle_ = kInvalidHandle;
[email protected]1da08e72013-11-01 19:58:12102 return retval;
[email protected]182c44fa2009-11-26 00:28:02103}
104
105size_t SyncSocket::Send(const void* buffer, size_t length) {
[email protected]62558f12013-10-19 22:13:19106 ThreadRestrictions::AssertIOAllowed();
107 return SendHelper(handle_, buffer, length);
[email protected]182c44fa2009-11-26 00:28:02108}
109
110size_t SyncSocket::Receive(void* buffer, size_t length) {
[email protected]62558f12013-10-19 22:13:19111 ThreadRestrictions::AssertIOAllowed();
112 DCHECK_GT(length, 0u);
[email protected]d7a93ad2011-04-22 13:13:07113 DCHECK_LE(length, kMaxMessageLength);
[email protected]62558f12013-10-19 22:13:19114 DCHECK_NE(handle_, kInvalidHandle);
[email protected]182c44fa2009-11-26 00:28:02115 char* charbuffer = static_cast<char*>(buffer);
[email protected]532e9bd2012-01-25 12:04:17116 if (file_util::ReadFromFD(handle_, charbuffer, length))
[email protected]182c44fa2009-11-26 00:28:02117 return length;
[email protected]532e9bd2012-01-25 12:04:17118 return 0;
[email protected]182c44fa2009-11-26 00:28:02119}
120
[email protected]62558f12013-10-19 22:13:19121size_t SyncSocket::ReceiveWithTimeout(void* buffer,
122 size_t length,
123 TimeDelta timeout) {
124 ThreadRestrictions::AssertIOAllowed();
125 DCHECK_GT(length, 0u);
126 DCHECK_LE(length, kMaxMessageLength);
127 DCHECK_NE(handle_, kInvalidHandle);
[email protected]1da08e72013-11-01 19:58:12128 CHECK_LT(handle_, FD_SETSIZE);
[email protected]62558f12013-10-19 22:13:19129
130 // Only timeouts greater than zero and less than one second are allowed.
131 DCHECK_GT(timeout.InMicroseconds(), 0);
132 DCHECK_LT(timeout.InMicroseconds(),
133 base::TimeDelta::FromSeconds(1).InMicroseconds());
134
135 // Track the start time so we can reduce the timeout as data is read.
136 TimeTicks start_time = TimeTicks::Now();
137 const TimeTicks finish_time = start_time + timeout;
138
139 fd_set read_fds;
140 size_t bytes_read_total;
141 for (bytes_read_total = 0;
142 bytes_read_total < length && timeout.InMicroseconds() > 0;
143 timeout = finish_time - base::TimeTicks::Now()) {
144 FD_ZERO(&read_fds);
145 FD_SET(handle_, &read_fds);
146
147 // Wait for data to become available.
148 struct timeval timeout_struct =
149 { 0, static_cast<suseconds_t>(timeout.InMicroseconds()) };
150 const int select_result =
151 select(handle_ + 1, &read_fds, NULL, NULL, &timeout_struct);
152 // Handle EINTR manually since we need to update the timeout value.
153 if (select_result == -1 && errno == EINTR)
154 continue;
155 if (select_result <= 0)
156 return bytes_read_total;
157
158 // select() only tells us that data is ready for reading, not how much. We
159 // must Peek() for the amount ready for reading to avoid blocking.
160 DCHECK(FD_ISSET(handle_, &read_fds));
161 const size_t bytes_to_read = std::min(Peek(), length - bytes_read_total);
162
163 // There may be zero bytes to read if the socket at the other end closed.
164 if (!bytes_to_read)
165 return bytes_read_total;
166
167 const size_t bytes_received =
168 Receive(static_cast<char*>(buffer) + bytes_read_total, bytes_to_read);
169 bytes_read_total += bytes_received;
170 if (bytes_received != bytes_to_read)
171 return bytes_read_total;
172 }
173
174 return bytes_read_total;
175}
176
[email protected]d8b65912009-12-04 22:53:22177size_t SyncSocket::Peek() {
[email protected]62558f12013-10-19 22:13:19178 DCHECK_NE(handle_, kInvalidHandle);
179 int number_chars = 0;
180 if (ioctl(handle_, FIONREAD, &number_chars) == -1) {
[email protected]1e1f1a72009-12-06 19:45:08181 // If there is an error in ioctl, signal that the channel would block.
182 return 0;
183 }
[email protected]62558f12013-10-19 22:13:19184 DCHECK_GE(number_chars, 0);
185 return number_chars;
[email protected]d8b65912009-12-04 22:53:22186}
187
[email protected]532e9bd2012-01-25 12:04:17188CancelableSyncSocket::CancelableSyncSocket() {}
189CancelableSyncSocket::CancelableSyncSocket(Handle handle)
190 : SyncSocket(handle) {
191}
192
193bool CancelableSyncSocket::Shutdown() {
[email protected]62558f12013-10-19 22:13:19194 DCHECK_NE(handle_, kInvalidHandle);
195 return HANDLE_EINTR(shutdown(handle_, SHUT_RDWR)) >= 0;
[email protected]532e9bd2012-01-25 12:04:17196}
197
[email protected]5d272092012-04-19 10:23:03198size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
[email protected]62558f12013-10-19 22:13:19199 DCHECK_GT(length, 0u);
200 DCHECK_LE(length, kMaxMessageLength);
201 DCHECK_NE(handle_, kInvalidHandle);
202
203 const long flags = fcntl(handle_, F_GETFL, NULL);
[email protected]5d272092012-04-19 10:23:03204 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
205 // Set the socket to non-blocking mode for sending if its original mode
206 // is blocking.
207 fcntl(handle_, F_SETFL, flags | O_NONBLOCK);
208 }
209
[email protected]62558f12013-10-19 22:13:19210 const size_t len = SendHelper(handle_, buffer, length);
[email protected]5d272092012-04-19 10:23:03211
212 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
213 // Restore the original flags.
214 fcntl(handle_, F_SETFL, flags);
215 }
216
217 return len;
218}
219
[email protected]532e9bd2012-01-25 12:04:17220// static
221bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
222 CancelableSyncSocket* socket_b) {
223 return SyncSocket::CreatePair(socket_a, socket_b);
224}
225
[email protected]182c44fa2009-11-26 00:28:02226} // namespace base