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 <stddef.h> 11 #include <stdio.h> 12 #include <sys/ioctl.h> 13 #include <sys/socket.h> 14 #include <sys/types.h> 15 16 #if defined(OS_SOLARIS) 17 #include <sys/filio.h> 18 #endif 19 20 #include "base/files/file_util.h" 21 #include "base/logging.h" 22 #include "base/threading/thread_restrictions.h" 23 #include "build/build_config.h" 24 25 namespace base { 26 27 namespace { 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. 30 const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX); 31 32 // Writes |length| of |buffer| into |handle|. Returns the number of bytes 33 // written or zero on error. |length| must be greater than 0. 34 size_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); 41 return WriteFileDescriptor(handle, charbuffer, length) 42 ? static_cast<size_t>(length) 43 : 0; 44 } 45 46 bool 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 55 } // namespace 56 57 const SyncSocket::Handle SyncSocket::kInvalidHandle = -1; 58 59 SyncSocket::SyncSocket() : handle_(kInvalidHandle) {} 60 61 SyncSocket::~SyncSocket() { 62 Close(); 63 } 64 65 // static 66 bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) { 67 DCHECK_NE(socket_a, socket_b); 68 DCHECK_EQ(socket_a->handle_, kInvalidHandle); 69 DCHECK_EQ(socket_b->handle_, kInvalidHandle); 70 71 #if defined(OS_MACOSX) 72 int nosigpipe = 1; 73 #endif // defined(OS_MACOSX) 74 75 Handle handles[2] = { kInvalidHandle, kInvalidHandle }; 76 if (socketpair(AF_UNIX, SOCK_STREAM, 0, handles) != 0) { 77 CloseHandle(handles[0]); 78 CloseHandle(handles[1]); 79 return false; 80 } 81 82 #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)) { 89 CloseHandle(handles[0]); 90 CloseHandle(handles[1]); 91 return false; 92 } 93 #endif 94 95 // Copy the handles out for successful return. 96 socket_a->handle_ = handles[0]; 97 socket_b->handle_ = handles[1]; 98 99 return true; 100 } 101 102 // static 103 SyncSocket::Handle SyncSocket::UnwrapHandle( 104 const TransitDescriptor& descriptor) { 105 return descriptor.fd; 106 } 107 108 bool 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 115 bool SyncSocket::Close() { 116 const bool retval = CloseHandle(handle_); 117 handle_ = kInvalidHandle; 118 return retval; 119 } 120 121 size_t SyncSocket::Send(const void* buffer, size_t length) { 122 ThreadRestrictions::AssertIOAllowed(); 123 return SendHelper(handle_, buffer, length); 124 } 125 126 size_t SyncSocket::Receive(void* buffer, size_t length) { 127 ThreadRestrictions::AssertIOAllowed(); 128 DCHECK_GT(length, 0u); 129 DCHECK_LE(length, kMaxMessageLength); 130 DCHECK_NE(handle_, kInvalidHandle); 131 char* charbuffer = static_cast<char*>(buffer); 132 if (ReadFromFD(handle_, charbuffer, length)) 133 return length; 134 return 0; 135 } 136 137 size_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); 144 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); 151 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 199 size_t SyncSocket::Peek() { 200 DCHECK_NE(handle_, kInvalidHandle); 201 int number_chars = 0; 202 if (ioctl(handle_, FIONREAD, &number_chars) == -1) { 203 // If there is an error in ioctl, signal that the channel would block. 204 return 0; 205 } 206 DCHECK_GE(number_chars, 0); 207 return number_chars; 208 } 209 210 CancelableSyncSocket::CancelableSyncSocket() {} 211 CancelableSyncSocket::CancelableSyncSocket(Handle handle) 212 : SyncSocket(handle) { 213 } 214 215 bool CancelableSyncSocket::Shutdown() { 216 DCHECK_NE(handle_, kInvalidHandle); 217 return HANDLE_EINTR(shutdown(handle_, SHUT_RDWR)) >= 0; 218 } 219 220 size_t CancelableSyncSocket::Send(const void* buffer, size_t length) { 221 DCHECK_GT(length, 0u); 222 DCHECK_LE(length, kMaxMessageLength); 223 DCHECK_NE(handle_, kInvalidHandle); 224 225 const int flags = fcntl(handle_, F_GETFL); 226 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 232 const size_t len = SendHelper(handle_, buffer, length); 233 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 242 // static 243 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a, 244 CancelableSyncSocket* socket_b) { 245 return SyncSocket::CreatePair(socket_a, socket_b); 246 } 247 248 } // namespace base 249