blob: c07e62a6120d9a4f837b4690e5c1d34fd9b494b8 [file] [log] [blame]
[email protected]774bdcc2012-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
[email protected]0840cc72009-11-24 16:14:537#include "base/logging.h"
[email protected]62558f12013-10-19 22:13:198#include "base/threading/thread_restrictions.h"
[email protected]532e9bd2012-01-25 12:04:179#include "base/win/scoped_handle.h"
[email protected]0840cc72009-11-24 16:14:5310
[email protected]0840cc72009-11-24 16:14:5311namespace base {
12
[email protected]532e9bd2012-01-25 12:04:1713using win::ScopedHandle;
14
[email protected]0840cc72009-11-24 16:14:5315namespace {
[email protected]774bdcc2012-01-19 03:44:3816// IMPORTANT: do not change how this name is generated because it will break
17// in sandboxed scenarios as we might have by-name policies that allow pipe
18// creation. Also keep the secure random number generation.
19const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\chrome.sync.%u.%u.%lu";
20const size_t kPipePathMax = arraysize(kPipeNameFormat) + (3 * 10) + 1;
[email protected]0840cc72009-11-24 16:14:5321
22// To avoid users sending negative message lengths to Send/Receive
23// we clamp message lengths, which are size_t, to no more than INT_MAX.
24const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
25
26const int kOutBufferSize = 4096;
27const int kInBufferSize = 4096;
28const int kDefaultTimeoutMilliSeconds = 1000;
29
[email protected]532e9bd2012-01-25 12:04:1730bool CreatePairImpl(HANDLE* socket_a, HANDLE* socket_b, bool overlapped) {
[email protected]62558f12013-10-19 22:13:1931 DCHECK_NE(socket_a, socket_b);
32 DCHECK_EQ(*socket_a, SyncSocket::kInvalidHandle);
33 DCHECK_EQ(*socket_b, SyncSocket::kInvalidHandle);
[email protected]0840cc72009-11-24 16:14:5334
35 wchar_t name[kPipePathMax];
[email protected]532e9bd2012-01-25 12:04:1736 ScopedHandle handle_a;
37 DWORD flags = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE;
38 if (overlapped)
39 flags |= FILE_FLAG_OVERLAPPED;
40
[email protected]0840cc72009-11-24 16:14:5341 do {
42 unsigned int rnd_name;
43 if (rand_s(&rnd_name) != 0)
44 return false;
[email protected]532e9bd2012-01-25 12:04:1745
[email protected]774bdcc2012-01-19 03:44:3846 swprintf(name, kPipePathMax,
47 kPipeNameFormat,
48 GetCurrentProcessId(),
49 GetCurrentThreadId(),
[email protected]0840cc72009-11-24 16:14:5350 rnd_name);
[email protected]532e9bd2012-01-25 12:04:1751
52 handle_a.Set(CreateNamedPipeW(
[email protected]0840cc72009-11-24 16:14:5353 name,
[email protected]532e9bd2012-01-25 12:04:1754 flags,
[email protected]0840cc72009-11-24 16:14:5355 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
56 1,
57 kOutBufferSize,
58 kInBufferSize,
59 kDefaultTimeoutMilliSeconds,
[email protected]532e9bd2012-01-25 12:04:1760 NULL));
61 } while (!handle_a.IsValid() &&
[email protected]774bdcc2012-01-19 03:44:3862 (GetLastError() == ERROR_PIPE_BUSY));
63
[email protected]532e9bd2012-01-25 12:04:1764 if (!handle_a.IsValid()) {
[email protected]774bdcc2012-01-19 03:44:3865 NOTREACHED();
66 return false;
67 }
[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]774bdcc2012-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;
73 if (overlapped)
74 flags |= FILE_FLAG_OVERLAPPED;
75
76 ScopedHandle handle_b(CreateFileW(name,
77 GENERIC_READ | GENERIC_WRITE,
78 0, // no sharing.
79 NULL, // default security attributes.
80 OPEN_EXISTING, // opens existing pipe.
81 flags,
82 NULL)); // no template file.
83 if (!handle_b.IsValid()) {
84 DPLOG(ERROR) << "CreateFileW failed";
[email protected]0840cc72009-11-24 16:14:5385 return false;
86 }
[email protected]532e9bd2012-01-25 12:04:1787
rvargasecaef8a2014-09-23 22:03:1188 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
96 *socket_a = handle_a.Take();
97 *socket_b = handle_b.Take();
98
[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.
105 return static_cast<DWORD>(((max_size - current_pos) <= UINT_MAX) ?
106 (max_size - current_pos) : UINT_MAX);
107}
108
109// Template function that supports calling ReadFile or WriteFile in an
110// overlapped fashion and waits for IO completion. The function also waits
111// on an event that can be used to cancel the operation. If the operation
112// is cancelled, the function returns and closes the relevant socket object.
113template <typename BufferType, typename Function>
[email protected]62558f12013-10-19 22:13:19114size_t CancelableFileOperation(Function operation,
115 HANDLE file,
116 BufferType* buffer,
117 size_t length,
118 WaitableEvent* io_event,
119 WaitableEvent* cancel_event,
[email protected]5d272092012-04-19 10:23:03120 CancelableSyncSocket* socket,
121 DWORD timeout_in_ms) {
[email protected]62558f12013-10-19 22:13:19122 ThreadRestrictions::AssertIOAllowed();
[email protected]532e9bd2012-01-25 12:04:17123 // The buffer must be byte size or the length check won't make much sense.
124 COMPILE_ASSERT(sizeof(buffer[0]) == sizeof(char), incorrect_buffer_type);
[email protected]62558f12013-10-19 22:13:19125 DCHECK_GT(length, 0u);
[email protected]532e9bd2012-01-25 12:04:17126 DCHECK_LE(length, kMaxMessageLength);
[email protected]62558f12013-10-19 22:13:19127 DCHECK_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();
133 finish_time =
134 current_time + base::TimeDelta::FromMilliseconds(timeout_in_ms);
135 }
136
[email protected]532e9bd2012-01-25 12:04:17137 size_t count = 0;
[email protected]62558f12013-10-19 22:13:19138 do {
139 // The OVERLAPPED structure will be modified by ReadFile or WriteFile.
140 OVERLAPPED ol = { 0 };
141 ol.hEvent = io_event->handle();
142
143 const DWORD chunk = GetNextChunkSize(count, length);
[email protected]532e9bd2012-01-25 12:04:17144 // This is either the ReadFile or WriteFile call depending on whether
145 // we're receiving or sending data.
[email protected]23bf6982012-02-03 12:44:44146 DWORD len = 0;
[email protected]62558f12013-10-19 22:13:19147 const BOOL operation_ok = operation(
148 file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol);
149 if (!operation_ok) {
[email protected]532e9bd2012-01-25 12:04:17150 if (::GetLastError() == ERROR_IO_PENDING) {
[email protected]5d272092012-04-19 10:23:03151 HANDLE events[] = { io_event->handle(), cancel_event->handle() };
[email protected]62558f12013-10-19 22:13:19152 const int wait_result = WaitForMultipleObjects(
153 ARRAYSIZE_UNSAFE(events), events, FALSE,
154 timeout_in_ms == INFINITE
155 ? timeout_in_ms
156 : (finish_time - current_time).InMilliseconds());
dalecurtis3bdbb012014-09-16 00:41:22157 if (wait_result != WAIT_OBJECT_0 + 0) {
158 // CancelIo() doesn't synchronously cancel outstanding IO, only marks
159 // outstanding IO for cancellation. We must call GetOverlappedResult()
160 // below to ensure in flight writes complete before returning.
[email protected]23bf6982012-02-03 12:44:44161 CancelIo(file);
[email protected]532e9bd2012-01-25 12:04:17162 }
dalecurtis3bdbb012014-09-16 00:41:22163
164 // We set the |bWait| parameter to TRUE for GetOverlappedResult() to
165 // ensure writes are complete before returning.
166 if (!GetOverlappedResult(file, &ol, &len, TRUE))
167 len = 0;
168
169 if (wait_result == WAIT_OBJECT_0 + 1) {
170 DVLOG(1) << "Shutdown was signaled. Closing socket.";
171 socket->Close();
172 return count;
173 }
174
175 // Timeouts will be handled by the while() condition below since
176 // GetOverlappedResult() may complete successfully after CancelIo().
177 DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT);
[email protected]532e9bd2012-01-25 12:04:17178 } else {
[email protected]5d272092012-04-19 10:23:03179 break;
[email protected]532e9bd2012-01-25 12:04:17180 }
181 }
[email protected]5d272092012-04-19 10:23:03182
[email protected]532e9bd2012-01-25 12:04:17183 count += len;
[email protected]5d272092012-04-19 10:23:03184
185 // Quit the operation if we can't write/read anymore.
186 if (len != chunk)
187 break;
[email protected]5d272092012-04-19 10:23:03188
[email protected]62558f12013-10-19 22:13:19189 // Since TimeTicks::Now() is expensive, only bother updating the time if we
190 // have more work to do.
191 if (timeout_in_ms != INFINITE && count < length)
192 current_time = base::TimeTicks::Now();
193 } while (count < length &&
194 (timeout_in_ms == INFINITE || current_time < finish_time));
195
196 return count;
[email protected]532e9bd2012-01-25 12:04:17197}
198
199} // namespace
200
[email protected]0f248ef2013-05-23 04:34:11201#if defined(COMPONENT_BUILD)
[email protected]532e9bd2012-01-25 12:04:17202const SyncSocket::Handle SyncSocket::kInvalidHandle = INVALID_HANDLE_VALUE;
[email protected]0f248ef2013-05-23 04:34:11203#endif
[email protected]532e9bd2012-01-25 12:04:17204
205SyncSocket::SyncSocket() : handle_(kInvalidHandle) {}
206
207SyncSocket::~SyncSocket() {
208 Close();
209}
210
211// static
212bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
213 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, false);
214}
215
burnik3d670052014-09-08 06:58:22216// static
217SyncSocket::Handle SyncSocket::UnwrapHandle(
218 const TransitDescriptor& descriptor) {
219 return descriptor;
220}
221
222bool SyncSocket::PrepareTransitDescriptor(ProcessHandle peer_process_handle,
223 TransitDescriptor* descriptor) {
224 DCHECK(descriptor);
225 if (!::DuplicateHandle(GetCurrentProcess(), handle(), peer_process_handle,
226 descriptor, 0, FALSE, DUPLICATE_SAME_ACCESS)) {
227 DPLOG(ERROR) << "Cannot duplicate socket handle for peer process.";
228 return false;
229 }
230 return true;
231}
232
[email protected]532e9bd2012-01-25 12:04:17233bool SyncSocket::Close() {
234 if (handle_ == kInvalidHandle)
[email protected]62558f12013-10-19 22:13:19235 return true;
[email protected]532e9bd2012-01-25 12:04:17236
[email protected]62558f12013-10-19 22:13:19237 const BOOL result = CloseHandle(handle_);
[email protected]0840cc72009-11-24 16:14:53238 handle_ = kInvalidHandle;
[email protected]62558f12013-10-19 22:13:19239 return result == TRUE;
[email protected]0840cc72009-11-24 16:14:53240}
241
242size_t SyncSocket::Send(const void* buffer, size_t length) {
[email protected]62558f12013-10-19 22:13:19243 ThreadRestrictions::AssertIOAllowed();
244 DCHECK_GT(length, 0u);
[email protected]d7a93ad2011-04-22 13:13:07245 DCHECK_LE(length, kMaxMessageLength);
[email protected]62558f12013-10-19 22:13:19246 DCHECK_NE(handle_, kInvalidHandle);
[email protected]0840cc72009-11-24 16:14:53247 size_t count = 0;
248 while (count < length) {
249 DWORD len;
[email protected]532e9bd2012-01-25 12:04:17250 DWORD chunk = GetNextChunkSize(count, length);
[email protected]0840cc72009-11-24 16:14:53251 if (WriteFile(handle_, static_cast<const char*>(buffer) + count,
252 chunk, &len, NULL) == FALSE) {
[email protected]62558f12013-10-19 22:13:19253 return count;
[email protected]0840cc72009-11-24 16:14:53254 }
255 count += len;
256 }
257 return count;
258}
259
[email protected]62558f12013-10-19 22:13:19260size_t SyncSocket::ReceiveWithTimeout(void* buffer,
261 size_t length,
262 TimeDelta timeout) {
263 NOTIMPLEMENTED();
264 return 0;
265}
266
[email protected]0840cc72009-11-24 16:14:53267size_t SyncSocket::Receive(void* buffer, size_t length) {
[email protected]62558f12013-10-19 22:13:19268 ThreadRestrictions::AssertIOAllowed();
269 DCHECK_GT(length, 0u);
[email protected]d7a93ad2011-04-22 13:13:07270 DCHECK_LE(length, kMaxMessageLength);
[email protected]62558f12013-10-19 22:13:19271 DCHECK_NE(handle_, kInvalidHandle);
[email protected]0840cc72009-11-24 16:14:53272 size_t count = 0;
273 while (count < length) {
274 DWORD len;
[email protected]532e9bd2012-01-25 12:04:17275 DWORD chunk = GetNextChunkSize(count, length);
[email protected]0840cc72009-11-24 16:14:53276 if (ReadFile(handle_, static_cast<char*>(buffer) + count,
277 chunk, &len, NULL) == FALSE) {
[email protected]62558f12013-10-19 22:13:19278 return count;
[email protected]0840cc72009-11-24 16:14:53279 }
280 count += len;
281 }
282 return count;
283}
284
[email protected]d8b65912009-12-04 22:53:22285size_t SyncSocket::Peek() {
286 DWORD available = 0;
287 PeekNamedPipe(handle_, NULL, 0, NULL, &available, NULL);
288 return available;
289}
290
[email protected]532e9bd2012-01-25 12:04:17291CancelableSyncSocket::CancelableSyncSocket()
292 : shutdown_event_(true, false), file_operation_(true, false) {
293}
294
295CancelableSyncSocket::CancelableSyncSocket(Handle handle)
296 : SyncSocket(handle), shutdown_event_(true, false),
297 file_operation_(true, false) {
298}
299
300bool CancelableSyncSocket::Shutdown() {
301 // This doesn't shut down the pipe immediately, but subsequent Receive or Send
302 // methods will fail straight away.
303 shutdown_event_.Signal();
304 return true;
305}
306
307bool CancelableSyncSocket::Close() {
[email protected]62558f12013-10-19 22:13:19308 const bool result = SyncSocket::Close();
[email protected]532e9bd2012-01-25 12:04:17309 shutdown_event_.Reset();
[email protected]62558f12013-10-19 22:13:19310 return result;
[email protected]532e9bd2012-01-25 12:04:17311}
312
313size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
[email protected]5d272092012-04-19 10:23:03314 static const DWORD kWaitTimeOutInMs = 500;
315 return CancelableFileOperation(
316 &WriteFile, handle_, reinterpret_cast<const char*>(buffer),
317 length, &file_operation_, &shutdown_event_, this, kWaitTimeOutInMs);
[email protected]532e9bd2012-01-25 12:04:17318}
319
320size_t CancelableSyncSocket::Receive(void* buffer, size_t length) {
[email protected]62558f12013-10-19 22:13:19321 return CancelableFileOperation(
322 &ReadFile, handle_, reinterpret_cast<char*>(buffer), length,
323 &file_operation_, &shutdown_event_, this, INFINITE);
324}
325
326size_t CancelableSyncSocket::ReceiveWithTimeout(void* buffer,
327 size_t length,
328 TimeDelta timeout) {
329 return CancelableFileOperation(
330 &ReadFile, handle_, reinterpret_cast<char*>(buffer), length,
331 &file_operation_, &shutdown_event_, this, timeout.InMilliseconds());
[email protected]532e9bd2012-01-25 12:04:17332}
333
334// static
335bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
336 CancelableSyncSocket* socket_b) {
337 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, true);
338}
339
[email protected]0840cc72009-11-24 16:14:53340} // namespace base