Remove connection_history.js from remoting's JS tests.
[chromium-blink-merge.git] / base / sync_socket_posix.cc
blob5bb893aae87319a80aeeabb83ba0aea23edca349
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"
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>
15 #if defined(OS_SOLARIS)
16 #include <sys/filio.h>
17 #endif
19 #include "base/file_util.h"
20 #include "base/logging.h"
21 #include "base/threading/thread_restrictions.h"
23 namespace base {
25 namespace {
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.
28 const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
30 // Writes |length| of |buffer| into |handle|. Returns the number of bytes
31 // written or zero on error. |length| must be greater than 0.
32 size_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);
43 bool CloseHandle(SyncSocket::Handle handle) {
44 if (handle != SyncSocket::kInvalidHandle && close(handle) < 0) {
45 DPLOG(ERROR) << "close";
46 return false;
49 return true;
52 } // namespace
54 const SyncSocket::Handle SyncSocket::kInvalidHandle = -1;
56 SyncSocket::SyncSocket() : handle_(kInvalidHandle) {}
58 SyncSocket::~SyncSocket() {
59 Close();
62 // static
63 bool 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);
68 #if defined(OS_MACOSX)
69 int nosigpipe = 1;
70 #endif // defined(OS_MACOSX)
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;
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;
90 #endif
92 // Copy the handles out for successful return.
93 socket_a->handle_ = handles[0];
94 socket_b->handle_ = handles[1];
96 return true;
99 bool SyncSocket::Close() {
100 const bool retval = CloseHandle(handle_);
101 handle_ = kInvalidHandle;
102 return retval;
105 size_t SyncSocket::Send(const void* buffer, size_t length) {
106 ThreadRestrictions::AssertIOAllowed();
107 return SendHelper(handle_, buffer, length);
110 size_t SyncSocket::Receive(void* buffer, size_t length) {
111 ThreadRestrictions::AssertIOAllowed();
112 DCHECK_GT(length, 0u);
113 DCHECK_LE(length, kMaxMessageLength);
114 DCHECK_NE(handle_, kInvalidHandle);
115 char* charbuffer = static_cast<char*>(buffer);
116 if (ReadFromFD(handle_, charbuffer, length))
117 return length;
118 return 0;
121 size_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);
129 // TODO(dalecurtis): There's an undiagnosed issue on OSX where we're seeing
130 // large numbers of open files which prevents select() from being used. In
131 // this case, the best we can do is Peek() to see if we can Receive() now or
132 // return a timeout error (0) if not. See http://crbug.com/314364.
133 if (handle_ >= FD_SETSIZE)
134 return Peek() < length ? 0 : Receive(buffer, length);
136 // Only timeouts greater than zero and less than one second are allowed.
137 DCHECK_GT(timeout.InMicroseconds(), 0);
138 DCHECK_LT(timeout.InMicroseconds(),
139 base::TimeDelta::FromSeconds(1).InMicroseconds());
141 // Track the start time so we can reduce the timeout as data is read.
142 TimeTicks start_time = TimeTicks::Now();
143 const TimeTicks finish_time = start_time + timeout;
145 fd_set read_fds;
146 size_t bytes_read_total;
147 for (bytes_read_total = 0;
148 bytes_read_total < length && timeout.InMicroseconds() > 0;
149 timeout = finish_time - base::TimeTicks::Now()) {
150 FD_ZERO(&read_fds);
151 FD_SET(handle_, &read_fds);
153 // Wait for data to become available.
154 struct timeval timeout_struct =
155 { 0, static_cast<suseconds_t>(timeout.InMicroseconds()) };
156 const int select_result =
157 select(handle_ + 1, &read_fds, NULL, NULL, &timeout_struct);
158 // Handle EINTR manually since we need to update the timeout value.
159 if (select_result == -1 && errno == EINTR)
160 continue;
161 if (select_result <= 0)
162 return bytes_read_total;
164 // select() only tells us that data is ready for reading, not how much. We
165 // must Peek() for the amount ready for reading to avoid blocking.
166 DCHECK(FD_ISSET(handle_, &read_fds));
167 const size_t bytes_to_read = std::min(Peek(), length - bytes_read_total);
169 // There may be zero bytes to read if the socket at the other end closed.
170 if (!bytes_to_read)
171 return bytes_read_total;
173 const size_t bytes_received =
174 Receive(static_cast<char*>(buffer) + bytes_read_total, bytes_to_read);
175 bytes_read_total += bytes_received;
176 if (bytes_received != bytes_to_read)
177 return bytes_read_total;
180 return bytes_read_total;
183 size_t SyncSocket::Peek() {
184 DCHECK_NE(handle_, kInvalidHandle);
185 int number_chars = 0;
186 if (ioctl(handle_, FIONREAD, &number_chars) == -1) {
187 // If there is an error in ioctl, signal that the channel would block.
188 return 0;
190 DCHECK_GE(number_chars, 0);
191 return number_chars;
194 CancelableSyncSocket::CancelableSyncSocket() {}
195 CancelableSyncSocket::CancelableSyncSocket(Handle handle)
196 : SyncSocket(handle) {
199 bool CancelableSyncSocket::Shutdown() {
200 DCHECK_NE(handle_, kInvalidHandle);
201 return HANDLE_EINTR(shutdown(handle_, SHUT_RDWR)) >= 0;
204 size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
205 DCHECK_GT(length, 0u);
206 DCHECK_LE(length, kMaxMessageLength);
207 DCHECK_NE(handle_, kInvalidHandle);
209 const long flags = fcntl(handle_, F_GETFL, NULL);
210 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
211 // Set the socket to non-blocking mode for sending if its original mode
212 // is blocking.
213 fcntl(handle_, F_SETFL, flags | O_NONBLOCK);
216 const size_t len = SendHelper(handle_, buffer, length);
218 if (flags != -1 && (flags & O_NONBLOCK) == 0) {
219 // Restore the original flags.
220 fcntl(handle_, F_SETFL, flags);
223 return len;
226 // static
227 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
228 CancelableSyncSocket* socket_b) {
229 return SyncSocket::CreatePair(socket_a, socket_b);
232 } // namespace base