| 6 |
| 7 | #include <limits.h> |
| 8 | #include <stddef.h> |
| 9 |
| 10 | #include "base/logging.h" |
| 11 | #include "base/rand_util.h" |
| 12 | #include "base/stl_util.h" |
| 13 | #include "base/threading/scoped_blocking_call.h" |
| 14 | #include "base/win/scoped_handle.h" |
| 15 |
| 16 | namespace base { |
| 17 |
| 18 | using win::ScopedHandle; |
| 19 |
| 20 | namespace { |
| 21 | // IMPORTANT: do not change how this name is generated because it will break |
| 22 | // in sandboxed scenarios as we might have by-name policies that allow pipe |
| 23 | // creation. Also keep the secure random number generation. |
| 24 | const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\chrome.sync.%u.%u.%lu"; |
| 25 | const size_t kPipePathMax = base::size(kPipeNameFormat) + (3 * 10) + 1; |
| 26 |
| 27 | // To avoid users sending negative message lengths to Send/Receive |
| 28 | // we clamp message lengths, which are size_t, to no more than INT_MAX. |
| 29 | const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX); |
| 30 |
| 31 | const int kOutBufferSize = 4096; |
| 32 | const int kInBufferSize = 4096; |
| 33 | const int kDefaultTimeoutMilliSeconds = 1000; |
| 34 |
| 35 | bool CreatePairImpl(ScopedHandle* socket_a, |
| 36 | ScopedHandle* socket_b, |
| 37 | bool overlapped) { |
| 38 | DCHECK_NE(socket_a, socket_b); |
| 39 | DCHECK(!socket_a->IsValid()); |
| 40 | DCHECK(!socket_b->IsValid()); |
| 41 |
| 42 | wchar_t name[kPipePathMax]; |
| 43 | ScopedHandle handle_a; |
| 44 | DWORD flags = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE; |
| 45 | if (overlapped) |
| 46 | flags |= FILE_FLAG_OVERLAPPED; |
| 47 |
| 48 | do { |
| 49 | unsigned long rnd_name; |
| 50 | RandBytes(&rnd_name, sizeof(rnd_name)); |
| 51 |
| 52 | swprintf(name, kPipePathMax, |
| 53 | kPipeNameFormat, |
| 54 | GetCurrentProcessId(), |
| 55 | GetCurrentThreadId(), |
| 56 | rnd_name); |
| 57 |
| 58 | handle_a.Set(CreateNamedPipeW( |
| 59 | name, |
| 60 | flags, |
| 61 | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, |
| 62 | 1, |
| 63 | kOutBufferSize, |
| 64 | kInBufferSize, |
| 65 | kDefaultTimeoutMilliSeconds, |
| 66 | NULL)); |
| 67 | } while (!handle_a.IsValid() && |
| 68 | (GetLastError() == ERROR_PIPE_BUSY)); |
| 69 |
| 70 | if (!handle_a.IsValid()) { |
| 71 | NOTREACHED(); |
| 72 | return false; |
| 73 | } |
| 74 |
| 75 | // The SECURITY_ANONYMOUS flag means that the server side (handle_a) cannot |
| 76 | // impersonate the client (handle_b). This allows us not to care which side |
| 77 | // ends up in which side of a privilege boundary. |
| 78 | flags = SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS; |
| 79 | if (overlapped) |
| 80 | flags |= FILE_FLAG_OVERLAPPED; |
| 81 |
| 82 | ScopedHandle handle_b(CreateFileW(name, |
| 83 | GENERIC_READ | GENERIC_WRITE, |
| 84 | 0, // no sharing. |
| 85 | NULL, // default security attributes. |
| 86 | OPEN_EXISTING, // opens existing pipe. |
| 87 | flags, |
| 88 | NULL)); // no template file. |
| 89 | if (!handle_b.IsValid()) { |
| 90 | DPLOG(ERROR) << "CreateFileW failed"; |
| 91 | return false; |
| 92 | } |
| 93 |
| 94 | if (!ConnectNamedPipe(handle_a.Get(), NULL)) { |
| 95 | DWORD error = GetLastError(); |
| 96 | if (error != ERROR_PIPE_CONNECTED) { |
| 97 | DPLOG(ERROR) << "ConnectNamedPipe failed"; |
| 98 | return false; |
| 99 | } |
| 100 | } |
| 101 |
| 102 | *socket_a = std::move(handle_a); |
| 103 | *socket_b = std::move(handle_b); |
| 104 |
| 105 | return true; |
| 106 | } |
| 107 |
| 108 | // Inline helper to avoid having the cast everywhere. |
| 109 | DWORD GetNextChunkSize(size_t current_pos, size_t max_size) { |
| 110 | // The following statement is for 64 bit portability. |
| 111 | return static_cast<DWORD>(((max_size - current_pos) <= UINT_MAX) ? |
| 112 | (max_size - current_pos) : UINT_MAX); |
| 113 | } |
| 114 |
| 115 | // Template function that supports calling ReadFile or WriteFile in an |
| 116 | // overlapped fashion and waits for IO completion. The function also waits |
| 117 | // on an event that can be used to cancel the operation. If the operation |
| 118 | // is cancelled, the function returns and closes the relevant socket object. |
| 119 | template <typename BufferType, typename Function> |
| 120 | size_t CancelableFileOperation(Function operation, |
| 121 | HANDLE file, |
| 122 | BufferType* buffer, |
| 123 | size_t length, |
| 124 | WaitableEvent* io_event, |
| 125 | WaitableEvent* cancel_event, |
| 126 | CancelableSyncSocket* socket, |
| 127 | DWORD timeout_in_ms) { |
| 128 | ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK); |
| 129 | // The buffer must be byte size or the length check won't make much sense. |
| 130 | static_assert(sizeof(buffer[0]) == sizeof(char), "incorrect buffer type"); |
| 131 | DCHECK_GT(length, 0u); |
| 132 | DCHECK_LE(length, kMaxMessageLength); |
| 133 | DCHECK_NE(file, SyncSocket::kInvalidHandle); |
| 134 |
| 135 | // Track the finish time so we can calculate the timeout as data is read. |
| 136 | TimeTicks current_time, finish_time; |
| 137 | if (timeout_in_ms != INFINITE) { |
| 138 | current_time = TimeTicks::Now(); |
| 139 | finish_time = |
| 140 | current_time + base::TimeDelta::FromMilliseconds(timeout_in_ms); |
| 141 | } |
| 142 |
| 143 | size_t count = 0; |
| 144 | do { |
| 145 | // The OVERLAPPED structure will be modified by ReadFile or WriteFile. |
| 146 | OVERLAPPED ol = { 0 }; |
| 147 | ol.hEvent = io_event->handle(); |
| 148 |
| 149 | const DWORD chunk = GetNextChunkSize(count, length); |
| 150 | // This is either the ReadFile or WriteFile call depending on whether |
| 151 | // we're receiving or sending data. |
| 152 | DWORD len = 0; |
| 153 | const BOOL operation_ok = operation( |
| 154 | file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol); |
| 155 | if (!operation_ok) { |
| 156 | if (::GetLastError() == ERROR_IO_PENDING) { |
| 157 | HANDLE events[] = { io_event->handle(), cancel_event->handle() }; |
| 158 | const int wait_result = WaitForMultipleObjects( |
| 159 | base::size(events), events, FALSE, |
| 160 | timeout_in_ms == INFINITE |
| 161 | ? timeout_in_ms |
| 162 | : static_cast<DWORD>( |
| 163 | (finish_time - current_time).InMilliseconds())); |
| 164 | if (wait_result != WAIT_OBJECT_0 + 0) { |
| 165 | // CancelIo() doesn't synchronously cancel outstanding IO, only marks |
| 166 | // outstanding IO for cancellation. We must call GetOverlappedResult() |
| 167 | // below to ensure in flight writes complete before returning. |
| 168 | CancelIo(file); |
| 169 | } |
| 170 |
| 171 | // We set the |bWait| parameter to TRUE for GetOverlappedResult() to |
| 172 | // ensure writes are complete before returning. |
| 173 | if (!GetOverlappedResult(file, &ol, &len, TRUE)) |
| 174 | len = 0; |
| 175 |
| 176 | if (wait_result == WAIT_OBJECT_0 + 1) { |
| 177 | DVLOG(1) << "Shutdown was signaled. Closing socket."; |
| 178 | socket->Close(); |
| 179 | return count; |
| 180 | } |
| 181 |
| 182 | // Timeouts will be handled by the while() condition below since |
| 183 | // GetOverlappedResult() may complete successfully after CancelIo(). |
| 184 | DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT); |
| 185 | } else { |
| 186 | break; |
| 187 | } |
| 188 | } |
| 189 |
| 190 | count += len; |
| 191 |
| 192 | // Quit the operation if we can't write/read anymore. |
| 193 | if (len != chunk) |
| 194 | break; |
| 195 |
| 196 | // Since TimeTicks::Now() is expensive, only bother updating the time if we |
| 197 | // have more work to do. |
| 198 | if (timeout_in_ms != INFINITE && count < length) |
| 199 | current_time = base::TimeTicks::Now(); |
| 200 | } while (count < length && |
| 201 | (timeout_in_ms == INFINITE || current_time < finish_time)); |
| 202 |
| 203 | return count; |
| 204 | } |
| 205 |
| 206 | } // namespace |
| 207 |
| 208 | // static |
| 209 | bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) { |
| 210 | return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, false); |
| 211 | } |
| 212 |
| 213 | void SyncSocket::Close() { |
| 214 | handle_.Close(); |
| 215 | } |
| 216 |
| 217 | size_t SyncSocket::Send(const void* buffer, size_t length) { |
| 218 | ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK); |
| 219 | DCHECK_GT(length, 0u); |
| 220 | DCHECK_LE(length, kMaxMessageLength); |
| 221 | DCHECK(IsValid()); |
| 222 | size_t count = 0; |
| 223 | while (count < length) { |
| 224 | DWORD len; |
| 225 | DWORD chunk = GetNextChunkSize(count, length); |
| 226 | if (::WriteFile(handle(), static_cast<const char*>(buffer) + count, chunk, |
| 227 | &len, NULL) == FALSE) { |
| 228 | return count; |
| 229 | } |
| 230 | count += len; |
| 231 | } |
| 232 | return count; |
| 233 | } |
| 234 |
| 235 | size_t SyncSocket::ReceiveWithTimeout(void* buffer, |
| 236 | size_t length, |
| 237 | TimeDelta timeout) { |
| 238 | NOTIMPLEMENTED(); |
| 239 | return 0; |
| 240 | } |
| 241 |
| 242 | size_t SyncSocket::Receive(void* buffer, size_t length) { |
| 243 | ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK); |
| 244 | DCHECK_GT(length, 0u); |
| 245 | DCHECK_LE(length, kMaxMessageLength); |
| 246 | DCHECK(IsValid()); |
| 247 | size_t count = 0; |
| 248 | while (count < length) { |
| 249 | DWORD len; |
| 250 | DWORD chunk = GetNextChunkSize(count, length); |
| 251 | if (::ReadFile(handle(), static_cast<char*>(buffer) + count, chunk, &len, |
| 252 | NULL) == FALSE) { |
| 253 | return count; |
| 254 | } |
| 255 | count += len; |
| 256 | } |
| 257 | return count; |
| 258 | } |
| 259 |
| 260 | size_t SyncSocket::Peek() { |
| 261 | DWORD available = 0; |
| 262 | PeekNamedPipe(handle(), NULL, 0, NULL, &available, NULL); |
| 263 | return available; |
| 264 | } |
| 265 |
| 266 | bool SyncSocket::IsValid() const { |
| 267 | return handle_.IsValid(); |
| 268 | } |
| 269 |
| 270 | SyncSocket::Handle SyncSocket::handle() const { |
| 271 | return handle_.Get(); |
| 272 | } |
| 273 |
| 274 | SyncSocket::Handle SyncSocket::Release() { |
| 275 | return handle_.Take(); |
| 276 | } |
| 277 |
| 278 | bool CancelableSyncSocket::Shutdown() { |
| 279 | // This doesn't shut down the pipe immediately, but subsequent Receive or Send |
| 280 | // methods will fail straight away. |
| 281 | shutdown_event_.Signal(); |
| 282 | return true; |
| 283 | } |
| 284 |
| 285 | void CancelableSyncSocket::Close() { |
| 286 | SyncSocket::Close(); |
| 287 | shutdown_event_.Reset(); |
| 288 | } |
| 289 |
| 290 | size_t CancelableSyncSocket::Send(const void* buffer, size_t length) { |
| 291 | static const DWORD kWaitTimeOutInMs = 500; |
| 292 | return CancelableFileOperation( |
| 293 | &::WriteFile, handle(), reinterpret_cast<const char*>(buffer), length, |
| 294 | &file_operation_, &shutdown_event_, this, kWaitTimeOutInMs); |
| 295 | } |
| 296 |
| 297 | size_t CancelableSyncSocket::Receive(void* buffer, size_t length) { |
| 298 | return CancelableFileOperation( |
| 299 | &::ReadFile, handle(), reinterpret_cast<char*>(buffer), length, |
| 300 | &file_operation_, &shutdown_event_, this, INFINITE); |
| 301 | } |
| 302 |
| 303 | size_t CancelableSyncSocket::ReceiveWithTimeout(void* buffer, |
| 304 | size_t length, |
| 305 | TimeDelta timeout) { |
| 306 | return CancelableFileOperation(&::ReadFile, handle(), |
| 307 | reinterpret_cast<char*>(buffer), length, |
| 308 | &file_operation_, &shutdown_event_, this, |
| 309 | static_cast<DWORD>(timeout.InMilliseconds())); |
| 310 | } |
| 311 |
| 312 | // static |
| 313 | bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a, |
| 314 | CancelableSyncSocket* socket_b) { |
| 315 | return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, true); |
| 316 | } |
| 317 |
| 318 | } // namespace base |
| 319 |