blob: 4634640b35b3b5246fca46c27ea8b13b282ac640 [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
Lei Zhangb7f26222021-06-15 18:45:4710#include "base/cxx17_backports.h"
[email protected]0840cc72009-11-24 16:14:5311#include "base/logging.h"
wfhcb35f4e72015-09-22 18:10:1112#include "base/rand_util.h"
Etienne Pierre-Doray3879b052018-09-17 14:17:2213#include "base/threading/scoped_blocking_call.h"
[email protected]532e9bd2012-01-25 12:04:1714#include "base/win/scoped_handle.h"
[email protected]0840cc72009-11-24 16:14:5315
[email protected]0840cc72009-11-24 16:14:5316namespace base {
17
[email protected]532e9bd2012-01-25 12:04:1718using win::ScopedHandle;
19
[email protected]0840cc72009-11-24 16:14:5320namespace {
[email protected]774bdcce2012-01-19 03:44:3821// 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.
24const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\chrome.sync.%u.%u.%lu";
Avi Drissmane3b70bf2019-01-04 19:50:2225const size_t kPipePathMax = base::size(kPipeNameFormat) + (3 * 10) + 1;
[email protected]0840cc72009-11-24 16:14:5326
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.
29const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
30
31const int kOutBufferSize = 4096;
32const int kInBufferSize = 4096;
33const int kDefaultTimeoutMilliSeconds = 1000;
34
Robert Sesek6ab73b022020-02-13 16:42:3935bool CreatePairImpl(ScopedHandle* socket_a,
36 ScopedHandle* socket_b,
37 bool overlapped) {
[email protected]62558f12013-10-19 22:13:1938 DCHECK_NE(socket_a, socket_b);
Robert Sesek6ab73b022020-02-13 16:42:3939 DCHECK(!socket_a->IsValid());
40 DCHECK(!socket_b->IsValid());
[email protected]0840cc72009-11-24 16:14:5341
42 wchar_t name[kPipePathMax];
[email protected]532e9bd2012-01-25 12:04:1743 ScopedHandle handle_a;
44 DWORD flags = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE;
45 if (overlapped)
46 flags |= FILE_FLAG_OVERLAPPED;
47
[email protected]0840cc72009-11-24 16:14:5348 do {
wfhcb35f4e72015-09-22 18:10:1149 unsigned long rnd_name;
50 RandBytes(&rnd_name, sizeof(rnd_name));
[email protected]532e9bd2012-01-25 12:04:1751
[email protected]774bdcce2012-01-19 03:44:3852 swprintf(name, kPipePathMax,
53 kPipeNameFormat,
54 GetCurrentProcessId(),
55 GetCurrentThreadId(),
[email protected]0840cc72009-11-24 16:14:5356 rnd_name);
[email protected]532e9bd2012-01-25 12:04:1757
58 handle_a.Set(CreateNamedPipeW(
[email protected]0840cc72009-11-24 16:14:5359 name,
[email protected]532e9bd2012-01-25 12:04:1760 flags,
[email protected]0840cc72009-11-24 16:14:5361 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
62 1,
63 kOutBufferSize,
64 kInBufferSize,
65 kDefaultTimeoutMilliSeconds,
[email protected]532e9bd2012-01-25 12:04:1766 NULL));
67 } while (!handle_a.IsValid() &&
[email protected]774bdcce2012-01-19 03:44:3868 (GetLastError() == ERROR_PIPE_BUSY));
69
[email protected]532e9bd2012-01-25 12:04:1770 if (!handle_a.IsValid()) {
[email protected]774bdcce2012-01-19 03:44:3871 NOTREACHED();
72 return false;
73 }
[email protected]532e9bd2012-01-25 12:04:1774
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
[email protected]774bdcce2012-01-19 03:44:3877 // ends up in which side of a privilege boundary.
[email protected]532e9bd2012-01-25 12:04:1778 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";
[email protected]0840cc72009-11-24 16:14:5391 return false;
92 }
[email protected]532e9bd2012-01-25 12:04:1793
rvargasecaef8a2014-09-23 22:03:1194 if (!ConnectNamedPipe(handle_a.Get(), NULL)) {
[email protected]0840cc72009-11-24 16:14:5395 DWORD error = GetLastError();
96 if (error != ERROR_PIPE_CONNECTED) {
[email protected]532e9bd2012-01-25 12:04:1797 DPLOG(ERROR) << "ConnectNamedPipe failed";
[email protected]0840cc72009-11-24 16:14:5398 return false;
99 }
100 }
[email protected]532e9bd2012-01-25 12:04:17101
Robert Sesek6ab73b022020-02-13 16:42:39102 *socket_a = std::move(handle_a);
103 *socket_b = std::move(handle_b);
[email protected]532e9bd2012-01-25 12:04:17104
[email protected]0840cc72009-11-24 16:14:53105 return true;
106}
107
[email protected]532e9bd2012-01-25 12:04:17108// Inline helper to avoid having the cast everywhere.
109DWORD 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.
119template <typename BufferType, typename Function>
[email protected]62558f12013-10-19 22:13:19120size_t CancelableFileOperation(Function operation,
121 HANDLE file,
122 BufferType* buffer,
123 size_t length,
124 WaitableEvent* io_event,
125 WaitableEvent* cancel_event,
[email protected]5d272092012-04-19 10:23:03126 CancelableSyncSocket* socket,
127 DWORD timeout_in_ms) {
Etienne Bergeron436d42212019-02-26 17:15:12128 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
[email protected]532e9bd2012-01-25 12:04:17129 // The buffer must be byte size or the length check won't make much sense.
avi4ec0dff2015-11-24 14:26:24130 static_assert(sizeof(buffer[0]) == sizeof(char), "incorrect buffer type");
[email protected]62558f12013-10-19 22:13:19131 DCHECK_GT(length, 0u);
[email protected]532e9bd2012-01-25 12:04:17132 DCHECK_LE(length, kMaxMessageLength);
[email protected]62558f12013-10-19 22:13:19133 DCHECK_NE(file, SyncSocket::kInvalidHandle);
[email protected]532e9bd2012-01-25 12:04:17134
[email protected]62558f12013-10-19 22:13:19135 // 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();
Peter Kastinge5a38ed2021-10-02 03:06:35139 finish_time = current_time + base::Milliseconds(timeout_in_ms);
[email protected]62558f12013-10-19 22:13:19140 }
141
[email protected]532e9bd2012-01-25 12:04:17142 size_t count = 0;
[email protected]62558f12013-10-19 22:13:19143 do {
144 // The OVERLAPPED structure will be modified by ReadFile or WriteFile.
145 OVERLAPPED ol = { 0 };
146 ol.hEvent = io_event->handle();
147
148 const DWORD chunk = GetNextChunkSize(count, length);
[email protected]532e9bd2012-01-25 12:04:17149 // This is either the ReadFile or WriteFile call depending on whether
150 // we're receiving or sending data.
[email protected]23bf6982012-02-03 12:44:44151 DWORD len = 0;
[email protected]62558f12013-10-19 22:13:19152 const BOOL operation_ok = operation(
153 file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol);
154 if (!operation_ok) {
[email protected]532e9bd2012-01-25 12:04:17155 if (::GetLastError() == ERROR_IO_PENDING) {
[email protected]5d272092012-04-19 10:23:03156 HANDLE events[] = { io_event->handle(), cancel_event->handle() };
[email protected]62558f12013-10-19 22:13:19157 const int wait_result = WaitForMultipleObjects(
Avi Drissmane3b70bf2019-01-04 19:50:22158 base::size(events), events, FALSE,
159 timeout_in_ms == INFINITE
160 ? timeout_in_ms
161 : static_cast<DWORD>(
162 (finish_time - current_time).InMilliseconds()));
dalecurtis3bdbb0162014-09-16 00:41:22163 if (wait_result != WAIT_OBJECT_0 + 0) {
164 // CancelIo() doesn't synchronously cancel outstanding IO, only marks
165 // outstanding IO for cancellation. We must call GetOverlappedResult()
166 // below to ensure in flight writes complete before returning.
[email protected]23bf6982012-02-03 12:44:44167 CancelIo(file);
[email protected]532e9bd2012-01-25 12:04:17168 }
dalecurtis3bdbb0162014-09-16 00:41:22169
170 // We set the |bWait| parameter to TRUE for GetOverlappedResult() to
171 // ensure writes are complete before returning.
172 if (!GetOverlappedResult(file, &ol, &len, TRUE))
173 len = 0;
174
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.
192 if (len != chunk)
193 break;
[email protected]5d272092012-04-19 10:23:03194
[email protected]62558f12013-10-19 22:13:19195 // Since TimeTicks::Now() is expensive, only bother updating the time if we
196 // have more work to do.
197 if (timeout_in_ms != INFINITE && count < length)
198 current_time = base::TimeTicks::Now();
199 } while (count < length &&
200 (timeout_in_ms == INFINITE || current_time < finish_time));
201
202 return count;
[email protected]532e9bd2012-01-25 12:04:17203}
204
205} // namespace
206
[email protected]532e9bd2012-01-25 12:04:17207// static
208bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
209 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, false);
210}
211
Robert Sesek6ab73b022020-02-13 16:42:39212void SyncSocket::Close() {
213 handle_.Close();
[email protected]0840cc72009-11-24 16:14:53214}
215
216size_t SyncSocket::Send(const void* buffer, size_t length) {
Etienne Bergeron436d42212019-02-26 17:15:12217 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
[email protected]62558f12013-10-19 22:13:19218 DCHECK_GT(length, 0u);
[email protected]d7a93ad2011-04-22 13:13:07219 DCHECK_LE(length, kMaxMessageLength);
Robert Sesek6ab73b022020-02-13 16:42:39220 DCHECK(IsValid());
[email protected]0840cc72009-11-24 16:14:53221 size_t count = 0;
222 while (count < length) {
223 DWORD len;
[email protected]532e9bd2012-01-25 12:04:17224 DWORD chunk = GetNextChunkSize(count, length);
Robert Sesek6ab73b022020-02-13 16:42:39225 if (::WriteFile(handle(), static_cast<const char*>(buffer) + count, chunk,
Nico Weber2499aee2017-10-17 20:56:49226 &len, NULL) == FALSE) {
[email protected]62558f12013-10-19 22:13:19227 return count;
[email protected]0840cc72009-11-24 16:14:53228 }
229 count += len;
230 }
231 return count;
232}
233
[email protected]62558f12013-10-19 22:13:19234size_t SyncSocket::ReceiveWithTimeout(void* buffer,
235 size_t length,
236 TimeDelta timeout) {
237 NOTIMPLEMENTED();
238 return 0;
239}
240
[email protected]0840cc72009-11-24 16:14:53241size_t SyncSocket::Receive(void* buffer, size_t length) {
Etienne Bergeron436d42212019-02-26 17:15:12242 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
[email protected]62558f12013-10-19 22:13:19243 DCHECK_GT(length, 0u);
[email protected]d7a93ad2011-04-22 13:13:07244 DCHECK_LE(length, kMaxMessageLength);
Robert Sesek6ab73b022020-02-13 16:42:39245 DCHECK(IsValid());
[email protected]0840cc72009-11-24 16:14:53246 size_t count = 0;
247 while (count < length) {
248 DWORD len;
[email protected]532e9bd2012-01-25 12:04:17249 DWORD chunk = GetNextChunkSize(count, length);
Robert Sesek6ab73b022020-02-13 16:42:39250 if (::ReadFile(handle(), static_cast<char*>(buffer) + count, chunk, &len,
Nico Weber2499aee2017-10-17 20:56:49251 NULL) == FALSE) {
[email protected]62558f12013-10-19 22:13:19252 return count;
[email protected]0840cc72009-11-24 16:14:53253 }
254 count += len;
255 }
256 return count;
257}
258
[email protected]d8b65912009-12-04 22:53:22259size_t SyncSocket::Peek() {
260 DWORD available = 0;
Robert Sesek6ab73b022020-02-13 16:42:39261 PeekNamedPipe(handle(), NULL, 0, NULL, &available, NULL);
[email protected]d8b65912009-12-04 22:53:22262 return available;
263}
264
Robert Sesek6ab73b022020-02-13 16:42:39265bool SyncSocket::IsValid() const {
266 return handle_.IsValid();
maxmorind4bcb112017-04-13 11:43:13267}
268
Robert Sesek6ab73b022020-02-13 16:42:39269SyncSocket::Handle SyncSocket::handle() const {
270 return handle_.Get();
271}
[email protected]532e9bd2012-01-25 12:04:17272
Robert Sesek6ab73b022020-02-13 16:42:39273SyncSocket::Handle SyncSocket::Release() {
274 return handle_.Take();
275}
[email protected]532e9bd2012-01-25 12:04:17276
277bool CancelableSyncSocket::Shutdown() {
278 // This doesn't shut down the pipe immediately, but subsequent Receive or Send
279 // methods will fail straight away.
280 shutdown_event_.Signal();
281 return true;
282}
283
Robert Sesek6ab73b022020-02-13 16:42:39284void CancelableSyncSocket::Close() {
285 SyncSocket::Close();
[email protected]532e9bd2012-01-25 12:04:17286 shutdown_event_.Reset();
[email protected]532e9bd2012-01-25 12:04:17287}
288
289size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
[email protected]5d272092012-04-19 10:23:03290 static const DWORD kWaitTimeOutInMs = 500;
291 return CancelableFileOperation(
Robert Sesek6ab73b022020-02-13 16:42:39292 &::WriteFile, handle(), reinterpret_cast<const char*>(buffer), length,
Nico Weber2499aee2017-10-17 20:56:49293 &file_operation_, &shutdown_event_, this, kWaitTimeOutInMs);
[email protected]532e9bd2012-01-25 12:04:17294}
295
296size_t CancelableSyncSocket::Receive(void* buffer, size_t length) {
[email protected]62558f12013-10-19 22:13:19297 return CancelableFileOperation(
Robert Sesek6ab73b022020-02-13 16:42:39298 &::ReadFile, handle(), reinterpret_cast<char*>(buffer), length,
[email protected]62558f12013-10-19 22:13:19299 &file_operation_, &shutdown_event_, this, INFINITE);
300}
301
302size_t CancelableSyncSocket::ReceiveWithTimeout(void* buffer,
303 size_t length,
304 TimeDelta timeout) {
Robert Sesek6ab73b022020-02-13 16:42:39305 return CancelableFileOperation(&::ReadFile, handle(),
Nico Weber2499aee2017-10-17 20:56:49306 reinterpret_cast<char*>(buffer), length,
307 &file_operation_, &shutdown_event_, this,
308 static_cast<DWORD>(timeout.InMilliseconds()));
[email protected]532e9bd2012-01-25 12:04:17309}
310
311// static
312bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
313 CancelableSyncSocket* socket_b) {
314 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, true);
315}
316
[email protected]0840cc72009-11-24 16:14:53317} // namespace base