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( 109 ProcessHandle /* peer_process_handle */, 110 TransitDescriptor* descriptor) { 111 descriptor->fd = handle(); 112 descriptor->auto_close = false; 113 return descriptor->fd != kInvalidHandle; 114 } 115 116 bool SyncSocket::Close() { 117 const bool retval = CloseHandle(handle_); 118 handle_ = kInvalidHandle; 119 return retval; 120 } 121 122 size_t SyncSocket::Send(const void* buffer, size_t length) { 123 ThreadRestrictions::AssertIOAllowed(); 124 return SendHelper(handle_, buffer, length); 125 } 126 127 size_t SyncSocket::Receive(void* buffer, size_t length) { 128 ThreadRestrictions::AssertIOAllowed(); 129 DCHECK_GT(length, 0u); 130 DCHECK_LE(length, kMaxMessageLength); 131 DCHECK_NE(handle_, kInvalidHandle); 132 char* charbuffer = static_cast<char*>(buffer); 133 if (ReadFromFD(handle_, charbuffer, length)) 134 return length; 135 return 0; 136 } 137 138 size_t SyncSocket::ReceiveWithTimeout(void* buffer, 139 size_t length, 140 TimeDelta timeout) { 141 ThreadRestrictions::AssertIOAllowed(); 142 DCHECK_GT(length, 0u); 143 DCHECK_LE(length, kMaxMessageLength); 144 DCHECK_NE(handle_, kInvalidHandle); 145 146 // TODO(dalecurtis): There's an undiagnosed issue on OSX where we're seeing 147 // large numbers of open files which prevents select() from being used. In 148 // this case, the best we can do is Peek() to see if we can Receive() now or 149 // return a timeout error (0) if not. See http://crbug.com/314364. 150 if (handle_ >= FD_SETSIZE) 151 return Peek() < length ? 0 : Receive(buffer, length); 152 153 // Only timeouts greater than zero and less than one second are allowed. 154 DCHECK_GT(timeout.InMicroseconds(), 0); 155 DCHECK_LT(timeout.InMicroseconds(), 156 base::TimeDelta::FromSeconds(1).InMicroseconds()); 157 158 // Track the start time so we can reduce the timeout as data is read. 159 TimeTicks start_time = TimeTicks::Now(); 160 const TimeTicks finish_time = start_time + timeout; 161 162 fd_set read_fds; 163 size_t bytes_read_total; 164 for (bytes_read_total = 0; 165 bytes_read_total < length && timeout.InMicroseconds() > 0; 166 timeout = finish_time - base::TimeTicks::Now()) { 167 FD_ZERO(&read_fds); 168 FD_SET(handle_, &read_fds); 169 170 // Wait for data to become available. 171 struct timeval timeout_struct = 172 { 0, static_cast<suseconds_t>(timeout.InMicroseconds()) }; 173 const int select_result = 174 select(handle_ + 1, &read_fds, NULL, NULL, &timeout_struct); 175 // Handle EINTR manually since we need to update the timeout value. 176 if (select_result == -1 && errno == EINTR) 177 continue; 178 if (select_result <= 0) 179 return bytes_read_total; 180 181 // select() only tells us that data is ready for reading, not how much. We 182 // must Peek() for the amount ready for reading to avoid blocking. 183 DCHECK(FD_ISSET(handle_, &read_fds)); 184 const size_t bytes_to_read = std::min(Peek(), length - bytes_read_total); 185 186 // There may be zero bytes to read if the socket at the other end closed. 187 if (!bytes_to_read) 188 return bytes_read_total; 189 190 const size_t bytes_received = 191 Receive(static_cast<char*>(buffer) + bytes_read_total, bytes_to_read); 192 bytes_read_total += bytes_received; 193 if (bytes_received != bytes_to_read) 194 return bytes_read_total; 195 } 196 197 return bytes_read_total; 198 } 199 200 size_t SyncSocket::Peek() { 201 DCHECK_NE(handle_, kInvalidHandle); 202 int number_chars = 0; 203 if (ioctl(handle_, FIONREAD, &number_chars) == -1) { 204 // If there is an error in ioctl, signal that the channel would block. 205 return 0; 206 } 207 DCHECK_GE(number_chars, 0); 208 return number_chars; 209 } 210 211 CancelableSyncSocket::CancelableSyncSocket() {} 212 CancelableSyncSocket::CancelableSyncSocket(Handle handle) 213 : SyncSocket(handle) { 214 } 215 216 bool CancelableSyncSocket::Shutdown() { 217 DCHECK_NE(handle_, kInvalidHandle); 218 return HANDLE_EINTR(shutdown(handle_, SHUT_RDWR)) >= 0; 219 } 220 221 size_t CancelableSyncSocket::Send(const void* buffer, size_t length) { 222 DCHECK_GT(length, 0u); 223 DCHECK_LE(length, kMaxMessageLength); 224 DCHECK_NE(handle_, kInvalidHandle); 225 226 const long flags = fcntl(handle_, F_GETFL, NULL); 227 if (flags != -1 && (flags & O_NONBLOCK) == 0) { 228 // Set the socket to non-blocking mode for sending if its original mode 229 // is blocking. 230 fcntl(handle_, F_SETFL, flags | O_NONBLOCK); 231 } 232 233 const size_t len = SendHelper(handle_, buffer, length); 234 235 if (flags != -1 && (flags & O_NONBLOCK) == 0) { 236 // Restore the original flags. 237 fcntl(handle_, F_SETFL, flags); 238 } 239 240 return len; 241 } 242 243 // static 244 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a, 245 CancelableSyncSocket* socket_b) { 246 return SyncSocket::CreatePair(socket_a, socket_b); 247 } 248 249 } // namespace base 250