blob: 77bc8e15b180532b4d20cd33275155bd9d41a7d9 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
[email protected]0840cc72009-11-24 16:14:532// 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"
[email protected]532e9bd2012-01-25 12:04:176
avi9b6f42932015-12-26 22:15:147#include <limits.h>
8#include <stddef.h>
9
Austin Sullivanedf168fd2024-01-17 21:37:2010#include <utility>
11
Adam Riced47f4982024-09-03 16:18:2312#include "base/check.h"
Tom Sepez978847c2025-03-22 03:43:5913#include "base/compiler_specific.h"
Austin Sullivanedf168fd2024-01-17 21:37:2014#include "base/containers/span.h"
[email protected]0840cc72009-11-24 16:14:5315#include "base/logging.h"
Peter Boström6e2fd082024-01-23 01:17:5516#include "base/notimplemented.h"
wfhcb35f4e72015-09-22 18:10:1117#include "base/rand_util.h"
Etienne Pierre-Doray3879b052018-09-17 14:17:2218#include "base/threading/scoped_blocking_call.h"
[email protected]532e9bd2012-01-25 12:04:1719#include "base/win/scoped_handle.h"
[email protected]0840cc72009-11-24 16:14:5320
[email protected]0840cc72009-11-24 16:14:5321namespace base {
22
[email protected]532e9bd2012-01-25 12:04:1723using win::ScopedHandle;
24
[email protected]0840cc72009-11-24 16:14:5325namespace {
[email protected]774bdcce2012-01-19 03:44:3826// IMPORTANT: do not change how this name is generated because it will break
27// in sandboxed scenarios as we might have by-name policies that allow pipe
28// creation. Also keep the secure random number generation.
29const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\chrome.sync.%u.%u.%lu";
Daniel Chengf45f47602022-02-28 22:38:3230const size_t kPipePathMax = std::size(kPipeNameFormat) + (3 * 10) + 1;
[email protected]0840cc72009-11-24 16:14:5331
32// To avoid users sending negative message lengths to Send/Receive
33// we clamp message lengths, which are size_t, to no more than INT_MAX.
34const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
35
36const int kOutBufferSize = 4096;
37const int kInBufferSize = 4096;
38const int kDefaultTimeoutMilliSeconds = 1000;
39
Robert Sesek6ab73b022020-02-13 16:42:3940bool CreatePairImpl(ScopedHandle* socket_a,
41 ScopedHandle* socket_b,
42 bool overlapped) {
[email protected]62558f12013-10-19 22:13:1943 DCHECK_NE(socket_a, socket_b);
Lei Zhang04c0bcb2022-02-04 04:13:4544 DCHECK(!socket_a->is_valid());
45 DCHECK(!socket_b->is_valid());
[email protected]0840cc72009-11-24 16:14:5346
47 wchar_t name[kPipePathMax];
[email protected]532e9bd2012-01-25 12:04:1748 ScopedHandle handle_a;
49 DWORD flags = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE;
Peter Kasting134ef9af2024-12-28 02:30:0950 if (overlapped) {
[email protected]532e9bd2012-01-25 12:04:1751 flags |= FILE_FLAG_OVERLAPPED;
Peter Kasting134ef9af2024-12-28 02:30:0952 }
[email protected]532e9bd2012-01-25 12:04:1753
[email protected]0840cc72009-11-24 16:14:5354 do {
wfhcb35f4e72015-09-22 18:10:1155 unsigned long rnd_name;
danakj95305d272024-05-09 20:38:4456 RandBytes(byte_span_from_ref(rnd_name));
[email protected]532e9bd2012-01-25 12:04:1757
Tom Sepez978847c2025-03-22 03:43:5958 UNSAFE_TODO(swprintf(name, kPipePathMax, kPipeNameFormat,
59 GetCurrentProcessId(), GetCurrentThreadId(),
60 rnd_name));
[email protected]532e9bd2012-01-25 12:04:1761
62 handle_a.Set(CreateNamedPipeW(
Peter Kasting134ef9af2024-12-28 02:30:0963 name, flags, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, kOutBufferSize,
64 kInBufferSize, kDefaultTimeoutMilliSeconds, NULL));
Lei Zhang04c0bcb2022-02-04 04:13:4565 } while (!handle_a.is_valid() && (GetLastError() == ERROR_PIPE_BUSY));
[email protected]774bdcce2012-01-19 03:44:3866
Adam Riced47f4982024-09-03 16:18:2367 CHECK(handle_a.is_valid());
[email protected]532e9bd2012-01-25 12:04:1768
69 // The SECURITY_ANONYMOUS flag means that the server side (handle_a) cannot
70 // impersonate the client (handle_b). This allows us not to care which side
[email protected]774bdcce2012-01-19 03:44:3871 // ends up in which side of a privilege boundary.
[email protected]532e9bd2012-01-25 12:04:1772 flags = SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS;
Peter Kasting134ef9af2024-12-28 02:30:0973 if (overlapped) {
[email protected]532e9bd2012-01-25 12:04:1774 flags |= FILE_FLAG_OVERLAPPED;
Peter Kasting134ef9af2024-12-28 02:30:0975 }
[email protected]532e9bd2012-01-25 12:04:1776
Peter Kasting134ef9af2024-12-28 02:30:0977 ScopedHandle handle_b(CreateFileW(name, GENERIC_READ | GENERIC_WRITE,
78 0, // no sharing.
79 NULL, // default security attributes.
[email protected]532e9bd2012-01-25 12:04:1780 OPEN_EXISTING, // opens existing pipe.
81 flags,
Peter Kasting134ef9af2024-12-28 02:30:0982 NULL)); // no template file.
Lei Zhang04c0bcb2022-02-04 04:13:4583 if (!handle_b.is_valid()) {
[email protected]532e9bd2012-01-25 12:04:1784 DPLOG(ERROR) << "CreateFileW failed";
[email protected]0840cc72009-11-24 16:14:5385 return false;
86 }
[email protected]532e9bd2012-01-25 12:04:1787
Lei Zhang04c0bcb2022-02-04 04:13:4588 if (!ConnectNamedPipe(handle_a.get(), NULL)) {
[email protected]0840cc72009-11-24 16:14:5389 DWORD error = GetLastError();
90 if (error != ERROR_PIPE_CONNECTED) {
[email protected]532e9bd2012-01-25 12:04:1791 DPLOG(ERROR) << "ConnectNamedPipe failed";
[email protected]0840cc72009-11-24 16:14:5392 return false;
93 }
94 }
[email protected]532e9bd2012-01-25 12:04:1795
Robert Sesek6ab73b022020-02-13 16:42:3996 *socket_a = std::move(handle_a);
97 *socket_b = std::move(handle_b);
[email protected]532e9bd2012-01-25 12:04:1798
[email protected]0840cc72009-11-24 16:14:5399 return true;
100}
101
[email protected]532e9bd2012-01-25 12:04:17102// Inline helper to avoid having the cast everywhere.
103DWORD GetNextChunkSize(size_t current_pos, size_t max_size) {
104 // The following statement is for 64 bit portability.
Peter Kasting134ef9af2024-12-28 02:30:09105 return static_cast<DWORD>(((max_size - current_pos) <= UINT_MAX)
106 ? (max_size - current_pos)
107 : UINT_MAX);
[email protected]532e9bd2012-01-25 12:04:17108}
109
110// Template function that supports calling ReadFile or WriteFile in an
111// overlapped fashion and waits for IO completion. The function also waits
112// on an event that can be used to cancel the operation. If the operation
113// is cancelled, the function returns and closes the relevant socket object.
Austin Sullivanedf168fd2024-01-17 21:37:20114template <typename DataType, typename Function>
[email protected]62558f12013-10-19 22:13:19115size_t CancelableFileOperation(Function operation,
116 HANDLE file,
Austin Sullivanedf168fd2024-01-17 21:37:20117 span<DataType> buffer,
[email protected]62558f12013-10-19 22:13:19118 WaitableEvent* io_event,
119 WaitableEvent* cancel_event,
[email protected]5d272092012-04-19 10:23:03120 CancelableSyncSocket* socket,
121 DWORD timeout_in_ms) {
Etienne Bergeron436d42212019-02-26 17:15:12122 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
[email protected]532e9bd2012-01-25 12:04:17123 // The buffer must be byte size or the length check won't make much sense.
Austin Sullivanedf168fd2024-01-17 21:37:20124 static_assert(sizeof(DataType) == 1u, "incorrect buffer type");
125 CHECK(!buffer.empty());
126 CHECK_LE(buffer.size(), kMaxMessageLength);
127 CHECK_NE(file, SyncSocket::kInvalidHandle);
[email protected]532e9bd2012-01-25 12:04:17128
[email protected]62558f12013-10-19 22:13:19129 // Track the finish time so we can calculate the timeout as data is read.
130 TimeTicks current_time, finish_time;
131 if (timeout_in_ms != INFINITE) {
132 current_time = TimeTicks::Now();
Peter Kastinge5a38ed2021-10-02 03:06:35133 finish_time = current_time + base::Milliseconds(timeout_in_ms);
[email protected]62558f12013-10-19 22:13:19134 }
135
[email protected]532e9bd2012-01-25 12:04:17136 size_t count = 0;
[email protected]62558f12013-10-19 22:13:19137 do {
138 // The OVERLAPPED structure will be modified by ReadFile or WriteFile.
Peter Kasting134ef9af2024-12-28 02:30:09139 OVERLAPPED ol = {0};
[email protected]62558f12013-10-19 22:13:19140 ol.hEvent = io_event->handle();
141
Austin Sullivanedf168fd2024-01-17 21:37:20142 const DWORD chunk_size = GetNextChunkSize(count, buffer.size());
[email protected]532e9bd2012-01-25 12:04:17143 // This is either the ReadFile or WriteFile call depending on whether
144 // we're receiving or sending data.
[email protected]23bf6982012-02-03 12:44:44145 DWORD len = 0;
Austin Sullivanedf168fd2024-01-17 21:37:20146 auto operation_buffer = buffer.subspan(count, chunk_size);
147 // SAFETY: The below static_cast is in range for DWORD because
148 // `operation_buffer` is constructed with a DWORD length above from
149 // `chunk_size`.
150 const BOOL operation_ok =
151 operation(file, operation_buffer.data(),
152 static_cast<DWORD>(operation_buffer.size()), &len, &ol);
[email protected]62558f12013-10-19 22:13:19153 if (!operation_ok) {
[email protected]532e9bd2012-01-25 12:04:17154 if (::GetLastError() == ERROR_IO_PENDING) {
Peter Kasting134ef9af2024-12-28 02:30:09155 HANDLE events[] = {io_event->handle(), cancel_event->handle()};
Peter Kasting28b51cf2022-06-28 15:02:43156 const DWORD wait_result = WaitForMultipleObjects(
Daniel Chengf45f47602022-02-28 22:38:32157 std::size(events), events, FALSE,
Avi Drissmane3b70bf2019-01-04 19:50:22158 timeout_in_ms == INFINITE
159 ? timeout_in_ms
160 : static_cast<DWORD>(
161 (finish_time - current_time).InMilliseconds()));
dalecurtis3bdbb0162014-09-16 00:41:22162 if (wait_result != WAIT_OBJECT_0 + 0) {
163 // CancelIo() doesn't synchronously cancel outstanding IO, only marks
164 // outstanding IO for cancellation. We must call GetOverlappedResult()
165 // below to ensure in flight writes complete before returning.
[email protected]23bf6982012-02-03 12:44:44166 CancelIo(file);
[email protected]532e9bd2012-01-25 12:04:17167 }
dalecurtis3bdbb0162014-09-16 00:41:22168
169 // We set the |bWait| parameter to TRUE for GetOverlappedResult() to
170 // ensure writes are complete before returning.
Peter Kasting134ef9af2024-12-28 02:30:09171 if (!GetOverlappedResult(file, &ol, &len, TRUE)) {
dalecurtis3bdbb0162014-09-16 00:41:22172 len = 0;
Peter Kasting134ef9af2024-12-28 02:30:09173 }
dalecurtis3bdbb0162014-09-16 00:41:22174
175 if (wait_result == WAIT_OBJECT_0 + 1) {
176 DVLOG(1) << "Shutdown was signaled. Closing socket.";
177 socket->Close();
178 return count;
179 }
180
181 // Timeouts will be handled by the while() condition below since
182 // GetOverlappedResult() may complete successfully after CancelIo().
183 DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT);
[email protected]532e9bd2012-01-25 12:04:17184 } else {
[email protected]5d272092012-04-19 10:23:03185 break;
[email protected]532e9bd2012-01-25 12:04:17186 }
187 }
[email protected]5d272092012-04-19 10:23:03188
[email protected]532e9bd2012-01-25 12:04:17189 count += len;
[email protected]5d272092012-04-19 10:23:03190
191 // Quit the operation if we can't write/read anymore.
Austin Sullivanedf168fd2024-01-17 21:37:20192 if (len != chunk_size) {
[email protected]5d272092012-04-19 10:23:03193 break;
Austin Sullivanedf168fd2024-01-17 21:37:20194 }
[email protected]5d272092012-04-19 10:23:03195
[email protected]62558f12013-10-19 22:13:19196 // Since TimeTicks::Now() is expensive, only bother updating the time if we
197 // have more work to do.
Austin Sullivanedf168fd2024-01-17 21:37:20198 if (timeout_in_ms != INFINITE && count < buffer.size()) {
[email protected]62558f12013-10-19 22:13:19199 current_time = base::TimeTicks::Now();
Austin Sullivanedf168fd2024-01-17 21:37:20200 }
201 } while (count < buffer.size() &&
[email protected]62558f12013-10-19 22:13:19202 (timeout_in_ms == INFINITE || current_time < finish_time));
203
204 return count;
[email protected]532e9bd2012-01-25 12:04:17205}
206
207} // namespace
208
[email protected]532e9bd2012-01-25 12:04:17209// static
210bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
211 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, false);
212}
213
Robert Sesek6ab73b022020-02-13 16:42:39214void SyncSocket::Close() {
215 handle_.Close();
[email protected]0840cc72009-11-24 16:14:53216}
217
Austin Sullivanedf168fd2024-01-17 21:37:20218size_t SyncSocket::Send(span<const uint8_t> data) {
Etienne Bergeron436d42212019-02-26 17:15:12219 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
Austin Sullivanedf168fd2024-01-17 21:37:20220 CHECK_LE(data.size(), kMaxMessageLength);
Robert Sesek6ab73b022020-02-13 16:42:39221 DCHECK(IsValid());
[email protected]0840cc72009-11-24 16:14:53222 size_t count = 0;
Austin Sullivanedf168fd2024-01-17 21:37:20223 while (count < data.size()) {
[email protected]0840cc72009-11-24 16:14:53224 DWORD len;
Austin Sullivanedf168fd2024-01-17 21:37:20225 const DWORD chunk_size = GetNextChunkSize(count, data.size());
226 auto data_chunk = data.subspan(count, chunk_size);
227 // SAFETY: The below static_cast is in range for DWORD because `data_chunk`
228 // is constructed with a DWORD length above from `chunk_size`.
229 if (::WriteFile(handle(), data_chunk.data(),
230 static_cast<DWORD>(data_chunk.size()), &len,
231 NULL) == FALSE) {
[email protected]62558f12013-10-19 22:13:19232 return count;
[email protected]0840cc72009-11-24 16:14:53233 }
234 count += len;
235 }
236 return count;
237}
238
Austin Sullivanedf168fd2024-01-17 21:37:20239size_t SyncSocket::ReceiveWithTimeout(span<uint8_t> buffer, TimeDelta timeout) {
240 NOTIMPLEMENTED();
241 return 0;
242}
243
Austin Sullivanedf168fd2024-01-17 21:37:20244size_t SyncSocket::Receive(span<uint8_t> buffer) {
Etienne Bergeron436d42212019-02-26 17:15:12245 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
Austin Sullivanedf168fd2024-01-17 21:37:20246 CHECK_LE(buffer.size(), kMaxMessageLength);
Robert Sesek6ab73b022020-02-13 16:42:39247 DCHECK(IsValid());
[email protected]0840cc72009-11-24 16:14:53248 size_t count = 0;
Austin Sullivanedf168fd2024-01-17 21:37:20249 while (count < buffer.size()) {
[email protected]0840cc72009-11-24 16:14:53250 DWORD len;
Austin Sullivanedf168fd2024-01-17 21:37:20251 const DWORD chunk_size = GetNextChunkSize(count, buffer.size());
252 auto data_chunk = buffer.subspan(count, chunk_size);
253 // SAFETY: The below static_cast is in range for DWORD because `data_chunk`
254 // is constructed with a DWORD length above from `chunk_size`.
255 if (::ReadFile(handle(), data_chunk.data(),
256 static_cast<DWORD>(data_chunk.size()), &len,
Nico Weber2499aee2017-10-17 20:56:49257 NULL) == FALSE) {
[email protected]62558f12013-10-19 22:13:19258 return count;
[email protected]0840cc72009-11-24 16:14:53259 }
260 count += len;
261 }
262 return count;
263}
264
[email protected]d8b65912009-12-04 22:53:22265size_t SyncSocket::Peek() {
266 DWORD available = 0;
Robert Sesek6ab73b022020-02-13 16:42:39267 PeekNamedPipe(handle(), NULL, 0, NULL, &available, NULL);
[email protected]d8b65912009-12-04 22:53:22268 return available;
269}
270
Robert Sesek6ab73b022020-02-13 16:42:39271bool SyncSocket::IsValid() const {
Lei Zhang04c0bcb2022-02-04 04:13:45272 return handle_.is_valid();
maxmorind4bcb112017-04-13 11:43:13273}
274
Robert Sesek6ab73b022020-02-13 16:42:39275SyncSocket::Handle SyncSocket::handle() const {
Lei Zhang04c0bcb2022-02-04 04:13:45276 return handle_.get();
Robert Sesek6ab73b022020-02-13 16:42:39277}
[email protected]532e9bd2012-01-25 12:04:17278
Robert Sesek6ab73b022020-02-13 16:42:39279SyncSocket::Handle SyncSocket::Release() {
Lei Zhang04c0bcb2022-02-04 04:13:45280 return handle_.release();
Robert Sesek6ab73b022020-02-13 16:42:39281}
[email protected]532e9bd2012-01-25 12:04:17282
283bool CancelableSyncSocket::Shutdown() {
284 // This doesn't shut down the pipe immediately, but subsequent Receive or Send
285 // methods will fail straight away.
286 shutdown_event_.Signal();
287 return true;
288}
289
Robert Sesek6ab73b022020-02-13 16:42:39290void CancelableSyncSocket::Close() {
291 SyncSocket::Close();
[email protected]532e9bd2012-01-25 12:04:17292 shutdown_event_.Reset();
[email protected]532e9bd2012-01-25 12:04:17293}
294
Austin Sullivanedf168fd2024-01-17 21:37:20295size_t CancelableSyncSocket::Send(span<const uint8_t> data) {
[email protected]5d272092012-04-19 10:23:03296 static const DWORD kWaitTimeOutInMs = 500;
Austin Sullivanedf168fd2024-01-17 21:37:20297 return CancelableFileOperation(&::WriteFile, handle(), data, &file_operation_,
298 &shutdown_event_, this, kWaitTimeOutInMs);
299}
300
Austin Sullivanedf168fd2024-01-17 21:37:20301size_t CancelableSyncSocket::Receive(span<uint8_t> buffer) {
302 return CancelableFileOperation(&::ReadFile, handle(), buffer,
303 &file_operation_, &shutdown_event_, this,
304 INFINITE);
[email protected]