blob: 1120188413112f420c183b172d8fe5891eef2bb5 [file] [log] [blame]
[email protected]774bdcce2012-01-19 03:44:381// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[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
[email protected]0840cc72009-11-24 16:14:5310#include "base/logging.h"
wfhcb35f4e72015-09-22 18:10:1111#include "base/rand_util.h"
Etienne Pierre-Doray3879b052018-09-17 14:17:2212#include "base/threading/scoped_blocking_call.h"
[email protected]532e9bd2012-01-25 12:04:1713#include "base/win/scoped_handle.h"
[email protected]0840cc72009-11-24 16:14:5314
[email protected]0840cc72009-11-24 16:14:5315namespace base {
16
[email protected]532e9bd2012-01-25 12:04:1717using win::ScopedHandle;
18
[email protected]0840cc72009-11-24 16:14:5319namespace {
[email protected]774bdcce2012-01-19 03:44:3820// IMPORTANT: do not change how this name is generated because it will break
21// in sandboxed scenarios as we might have by-name policies that allow pipe
22// creation. Also keep the secure random number generation.
23const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\chrome.sync.%u.%u.%lu";
Daniel Chengf45f47602022-02-28 22:38:3224const size_t kPipePathMax = std::size(kPipeNameFormat) + (3 * 10) + 1;
[email protected]0840cc72009-11-24 16:14:5325
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.
28const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
29
30const int kOutBufferSize = 4096;
31const int kInBufferSize = 4096;
32const int kDefaultTimeoutMilliSeconds = 1000;
33
Robert Sesek6ab73b022020-02-13 16:42:3934bool CreatePairImpl(ScopedHandle* socket_a,
35 ScopedHandle* socket_b,
36 bool overlapped) {
[email protected]62558f12013-10-19 22:13:1937 DCHECK_NE(socket_a, socket_b);
Lei Zhang04c0bcb2022-02-04 04:13:4538 DCHECK(!socket_a->is_valid());
39 DCHECK(!socket_b->is_valid());
[email protected]0840cc72009-11-24 16:14:5340
41 wchar_t name[kPipePathMax];
[email protected]532e9bd2012-01-25 12:04:1742 ScopedHandle handle_a;
43 DWORD flags = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE;
44 if (overlapped)
45 flags |= FILE_FLAG_OVERLAPPED;
46
[email protected]0840cc72009-11-24 16:14:5347 do {
wfhcb35f4e72015-09-22 18:10:1148 unsigned long rnd_name;
49 RandBytes(&rnd_name, sizeof(rnd_name));
[email protected]532e9bd2012-01-25 12:04:1750
[email protected]774bdcce2012-01-19 03:44:3851 swprintf(name, kPipePathMax,
52 kPipeNameFormat,
53 GetCurrentProcessId(),
54 GetCurrentThreadId(),
[email protected]0840cc72009-11-24 16:14:5355 rnd_name);
[email protected]532e9bd2012-01-25 12:04:1756
57 handle_a.Set(CreateNamedPipeW(
[email protected]0840cc72009-11-24 16:14:5358 name,
[email protected]532e9bd2012-01-25 12:04:1759 flags,
[email protected]0840cc72009-11-24 16:14:5360 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
61 1,
62 kOutBufferSize,
63 kInBufferSize,
64 kDefaultTimeoutMilliSeconds,
[email protected]532e9bd2012-01-25 12:04:1765 NULL));
Lei Zhang04c0bcb2022-02-04 04:13:4566 } while (!handle_a.is_valid() && (GetLastError() == ERROR_PIPE_BUSY));
[email protected]774bdcce2012-01-19 03:44:3867
Lei Zhang04c0bcb2022-02-04 04:13:4568 if (!handle_a.is_valid()) {
[email protected]774bdcce2012-01-19 03:44:3869 NOTREACHED();
70 return false;
71 }
[email protected]532e9bd2012-01-25 12:04:1772
73 // The SECURITY_ANONYMOUS flag means that the server side (handle_a) cannot
74 // impersonate the client (handle_b). This allows us not to care which side
[email protected]774bdcce2012-01-19 03:44:3875 // ends up in which side of a privilege boundary.
[email protected]532e9bd2012-01-25 12:04:1776 flags = SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS;
77 if (overlapped)
78 flags |= FILE_FLAG_OVERLAPPED;
79
80 ScopedHandle handle_b(CreateFileW(name,
81 GENERIC_READ | GENERIC_WRITE,
82 0, // no sharing.
83 NULL, // default security attributes.
84 OPEN_EXISTING, // opens existing pipe.
85 flags,
86 NULL)); // no template file.
Lei Zhang04c0bcb2022-02-04 04:13:4587 if (!handle_b.is_valid()) {
[email protected]532e9bd2012-01-25 12:04:1788 DPLOG(ERROR) << "CreateFileW failed";
[email protected]0840cc72009-11-24 16:14:5389 return false;
90 }
[email protected]532e9bd2012-01-25 12:04:1791
Lei Zhang04c0bcb2022-02-04 04:13:4592 if (!ConnectNamedPipe(handle_a.get(), NULL)) {
[email protected]0840cc72009-11-24 16:14:5393 DWORD error = GetLastError();
94 if (error != ERROR_PIPE_CONNECTED) {
[email protected]532e9bd2012-01-25 12:04:1795 DPLOG(ERROR) << "ConnectNamedPipe failed";
[email protected]0840cc72009-11-24 16:14:5396 return false;
97 }
98 }
[email protected]532e9bd2012-01-25 12:04:1799
Robert Sesek6ab73b022020-02-13 16:42:39100 *socket_a = std::move(handle_a);
101 *socket_b = std::move(handle_b);
[email protected]532e9bd2012-01-25 12:04:17102
[email protected]0840cc72009-11-24 16:14:53103 return true;
104}
105
[email protected]532e9bd2012-01-25 12:04:17106// Inline helper to avoid having the cast everywhere.
107DWORD GetNextChunkSize(size_t current_pos, size_t max_size) {
108 // The following statement is for 64 bit portability.
109 return static_cast<DWORD>(((max_size - current_pos) <= UINT_MAX) ?
110 (max_size - current_pos) : UINT_MAX);
111}
112
113// Template function that supports calling ReadFile or WriteFile in an
114// overlapped fashion and waits for IO completion. The function also waits
115// on an event that can be used to cancel the operation. If the operation
116// is cancelled, the function returns and closes the relevant socket object.
117template <typename BufferType, typename Function>
[email protected]62558f12013-10-19 22:13:19118size_t CancelableFileOperation(Function operation,
119 HANDLE file,
120 BufferType* buffer,
121 size_t length,
122 WaitableEvent* io_event,
123 WaitableEvent* cancel_event,
[email protected]5d272092012-04-19 10:23:03124 CancelableSyncSocket* socket,
125 DWORD timeout_in_ms) {
Etienne Bergeron436d42212019-02-26 17:15:12126 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
[email protected]532e9bd2012-01-25 12:04:17127 // The buffer must be byte size or the length check won't make much sense.
avi4ec0dff2015-11-24 14:26:24128 static_assert(sizeof(buffer[0]) == sizeof(char), "incorrect buffer type");
[email protected]62558f12013-10-19 22:13:19129 DCHECK_GT(length, 0u);
[email protected]532e9bd2012-01-25 12:04:17130 DCHECK_LE(length, kMaxMessageLength);
[email protected]62558f12013-10-19 22:13:19131 DCHECK_NE(file, SyncSocket::kInvalidHandle);
[email protected]532e9bd2012-01-25 12:04:17132
[email protected]62558f12013-10-19 22:13:19133 // Track the finish time so we can calculate the timeout as data is read.
134 TimeTicks current_time, finish_time;
135 if (timeout_in_ms != INFINITE) {
136 current_time = TimeTicks::Now();
Peter Kastinge5a38ed2021-10-02 03:06:35137 finish_time = current_time + base::Milliseconds(timeout_in_ms);
[email protected]62558f12013-10-19 22:13:19138 }
139
[email protected]532e9bd2012-01-25 12:04:17140 size_t count = 0;
[email protected]62558f12013-10-19 22:13:19141 do {
142 // The OVERLAPPED structure will be modified by ReadFile or WriteFile.
143 OVERLAPPED ol = { 0 };
144 ol.hEvent = io_event->handle();
145
146 const DWORD chunk = GetNextChunkSize(count, length);
[email protected]532e9bd2012-01-25 12:04:17147 // This is either the ReadFile or WriteFile call depending on whether
148 // we're receiving or sending data.
[email protected]23bf6982012-02-03 12:44:44149 DWORD len = 0;
[email protected]62558f12013-10-19 22:13:19150 const BOOL operation_ok = operation(
151 file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol);
152 if (!operation_ok) {
[email protected]532e9bd2012-01-25 12:04:17153 if (::GetLastError() == ERROR_IO_PENDING) {
[email protected]5d272092012-04-19 10:23:03154 HANDLE events[] = { io_event->handle(), cancel_event->handle() };
Peter Kasting28b51cf2022-06-28 15:02:43155 const DWORD wait_result = WaitForMultipleObjects(
Daniel Chengf45f47602022-02-28 22:38:32156 std::size(events), events, FALSE,
Avi Drissmane3b70bf2019-01-04 19:50:22157 timeout_in_ms == INFINITE
158 ? timeout_in_ms
159 : static_cast<DWORD>(
160 (finish_time - current_time).InMilliseconds()));
dalecurtis3bdbb0162014-09-16 00:41:22161 if (wait_result != WAIT_OBJECT_0 + 0) {
162 // CancelIo() doesn't synchronously cancel outstanding IO, only marks
163 // outstanding IO for cancellation. We must call GetOverlappedResult()
164 // below to ensure in flight writes complete before returning.
[email protected]23bf6982012-02-03 12:44:44165 CancelIo(file);
[email protected]532e9bd2012-01-25 12:04:17166 }
dalecurtis3bdbb0162014-09-16 00:41:22167
168 // We set the |bWait| parameter to TRUE for GetOverlappedResult() to
169 // ensure writes are complete before returning.
170 if (!GetOverlappedResult(file, &ol, &len, TRUE))
171 len = 0;
172
173 if (wait_result == WAIT_OBJECT_0 + 1) {
174 DVLOG(1) << "Shutdown was signaled. Closing socket.";
175 socket->Close();
176 return count;
177 }
178
179 // Timeouts will be handled by the while() condition below since
180 // GetOverlappedResult() may complete successfully after CancelIo().
181 DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT);
[email protected]532e9bd2012-01-25 12:04:17182 } else {
[email protected]5d272092012-04-19 10:23:03183 break;
[email protected]532e9bd2012-01-25 12:04:17184 }
185 }
[email protected]5d272092012-04-19 10:23:03186
[email protected]532e9bd2012-01-25 12:04:17187 count += len;
[email protected]5d272092012-04-19 10:23:03188
189 // Quit the operation if we can't write/read anymore.
190 if (len != chunk)
191 break;
[email protected]5d272092012-04-19 10:23:03192
[email protected]62558f12013-10-19 22:13:19193 // Since TimeTicks::Now() is expensive, only bother updating the time if we
194 // have more work to do.
195 if (timeout_in_ms != INFINITE && count < length)
196 current_time = base::TimeTicks::Now();
197 } while (count < length &&
198 (timeout_in_ms == INFINITE || current_time < finish_time));
199
200 return count;
[email protected]532e9bd2012-01-25 12:04:17201}
202
203} // namespace
204
[email protected]532e9bd2012-01-25 12:04:17205// static
206bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
207 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, false);
208}
209
Robert Sesek6ab73b022020-02-13 16:42:39210void SyncSocket::Close() {
211 handle_.Close();
[email protected]0840cc72009-11-24 16:14:53212}
213
214size_t SyncSocket::Send(const void* buffer, size_t length) {
Etienne Bergeron436d42212019-02-26 17:15:12215 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
[email protected]62558f12013-10-19 22:13:19216 DCHECK_GT(length, 0u);
[email protected]d7a93ad2011-04-22 13:13:07217 DCHECK_LE(length, kMaxMessageLength);
Robert Sesek6ab73b022020-02-13 16:42:39218 DCHECK(IsValid());
[email protected]0840cc72009-11-24 16:14:53219 size_t count = 0;
220 while (count < length) {
221 DWORD len;
[email protected]532e9bd2012-01-25 12:04:17222 DWORD chunk = GetNextChunkSize(count, length);
Robert Sesek6ab73b022020-02-13 16:42:39223 if (::WriteFile(handle(), static_cast<const char*>(buffer) + count, chunk,
Nico Weber2499aee2017-10-17 20:56:49224 &len, NULL) == FALSE) {
[email protected]62558f12013-10-19 22:13:19225 return count;
[email protected]0840cc72009-11-24 16:14:53226 }
227 count += len;
228 }
229 return count;
230}
231
[email protected]62558f12013-10-19 22:13:19232size_t SyncSocket::ReceiveWithTimeout(void* buffer,
233 size_t length,
234 TimeDelta timeout) {
235 NOTIMPLEMENTED();
236 return 0;
237}
238
[email protected]0840cc72009-11-24 16:14:53239size_t SyncSocket::Receive(void* buffer, size_t length) {
Etienne Bergeron436d42212019-02-26 17:15:12240 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
[email protected]62558f12013-10-19 22:13:19241 DCHECK_GT(length, 0u);
[email protected]d7a93ad2011-04-22 13:13:07242 DCHECK_LE(length, kMaxMessageLength);
Robert Sesek6ab73b022020-02-13 16:42:39243 DCHECK(IsValid());
[email protected]0840cc72009-11-24 16:14:53244 size_t count = 0;
245 while (count < length) {
246 DWORD len;
[email protected]532e9bd2012-01-25 12:04:17247 DWORD chunk = GetNextChunkSize(count, length);
Robert Sesek6ab73b022020-02-13 16:42:39248 if (::ReadFile(handle(), static_cast<char*>(buffer) + count, chunk, &len,
Nico Weber2499aee2017-10-17 20:56:49249 NULL) == FALSE) {
[email protected]62558f12013-10-19 22:13:19250 return count;
[email protected]0840cc72009-11-24 16:14:53251 }
252 count += len;
253 }
254 return count;
255}
256
[email protected]d8b65912009-12-04 22:53:22257size_t SyncSocket::Peek() {
258 DWORD available = 0;
Robert Sesek6ab73b022020-02-13 16:42:39259 PeekNamedPipe(handle(), NULL, 0, NULL, &available, NULL);
[email protected]d8b65912009-12-04 22:53:22260 return available;
261}
262
Robert Sesek6ab73b022020-02-13 16:42:39263bool SyncSocket::IsValid() const {
Lei Zhang04c0bcb2022-02-04 04:13:45264 return handle_.is_valid();
maxmorind4bcb112017-04-13 11:43:13265}
266
Robert Sesek6ab73b022020-02-13 16:42:39267SyncSocket::Handle SyncSocket::handle() const {
Lei Zhang04c0bcb2022-02-04 04:13:45268 return handle_.get();
Robert Sesek6ab73b022020-02-13 16:42:39269}
[email protected]532e9bd2012-01-25 12:04:17270
Robert Sesek6ab73b022020-02-13 16:42:39271SyncSocket::Handle SyncSocket::Release() {
Lei Zhang04c0bcb2022-02-04 04:13:45272 return handle_.release();
Robert Sesek6ab73b022020-02-13 16:42:39273}
[email protected]532e9bd2012-01-25 12:04:17274
275bool CancelableSyncSocket::Shutdown() {
276 // This doesn't shut down the pipe immediately, but subsequent Receive or Send
277 // methods will fail straight away.
278 shutdown_event_.Signal();
279 return true;
280}
281
Robert Sesek6ab73b022020-02-13 16:42:39282void CancelableSyncSocket::Close() {
283 SyncSocket::Close();
[email protected]532e9bd2012-01-25 12:04:17284 shutdown_event_.Reset();
[email protected]532e9bd2012-01-25 12:04:17285}
286
287size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
[email protected]5d272092012-04-19 10:23:03288 static const DWORD kWaitTimeOutInMs = 500;
289 return CancelableFileOperation(
Robert Sesek6ab73b022020-02-13 16:42:39290 &::WriteFile, handle(), reinterpret_cast<const char*>(buffer), length,
Nico Weber2499aee2017-10-17 20:56:49291 &file_operation_, &shutdown_event_, this, kWaitTimeOutInMs);
[email protected]532e9bd2012-01-25 12:04:17292}
293
294size_t CancelableSyncSocket::Receive(void* buffer, size_t length) {
[email protected]62558f12013-10-19 22:13:19295 return CancelableFileOperation(
Robert Sesek6ab73b022020-02-13 16:42:39296 &::ReadFile, handle(), reinterpret_cast<char*>(buffer), length,
[email protected]62558f12013-10-19 22:13:19297 &file_operation_, &shutdown_event_, this, INFINITE);
298}
299
300size_t CancelableSyncSocket::ReceiveWithTimeout(void* buffer,
301 size_t length,
302 TimeDelta timeout) {
Robert Sesek6ab73b022020-02-13 16:42:39303 return CancelableFileOperation(&::ReadFile, handle(),
Nico Weber2499aee2017-10-17 20:56:49304 reinterpret_cast<char*>(buffer), length,
305 &file_operation_, &shutdown_event_, this,
306 static_cast<DWORD>(timeout.InMilliseconds()));
[email protected]532e9bd2012-01-25 12:04:17307}
308
309// static
310bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
311 CancelableSyncSocket* socket_b) {
312 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, true);
313}
314
[email protected]0840cc72009-11-24 16:14:53315} // namespace base