1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/sync_socket.h"
10 #include "base/logging.h"
11 #include "base/rand_util.h"
12 #include "base/threading/scoped_blocking_call.h"
13 #include "base/win/scoped_handle.h"
17 using win::ScopedHandle;
20 // 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.
23 const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\chrome.sync.%u.%u.%lu";
24 const size_t kPipePathMax = std::size(kPipeNameFormat) + (3 * 10) + 1;
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.
28 const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
30 const int kOutBufferSize = 4096;
31 const int kInBufferSize = 4096;
32 const int kDefaultTimeoutMilliSeconds = 1000;
34 bool CreatePairImpl(ScopedHandle* socket_a,
35 ScopedHandle* socket_b,
37 DCHECK_NE(socket_a, socket_b);
38 DCHECK(!socket_a->is_valid());
39 DCHECK(!socket_b->is_valid());
41 wchar_t name[kPipePathMax];
42 ScopedHandle handle_a;
43 DWORD flags = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE;
45 flags |= FILE_FLAG_OVERLAPPED;
48 unsigned long rnd_name;
49 RandBytes(&rnd_name, sizeof(rnd_name));
51 swprintf(name, kPipePathMax,
53 GetCurrentProcessId(),
57 handle_a.Set(CreateNamedPipeW(
60 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
64 kDefaultTimeoutMilliSeconds,
66 } while (!handle_a.is_valid() && (GetLastError() == ERROR_PIPE_BUSY));
68 if (!handle_a.is_valid()) {
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
75 // ends up in which side of a privilege boundary.
76 flags = SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS;
78 flags |= FILE_FLAG_OVERLAPPED;
80 ScopedHandle handle_b(CreateFileW(name,
81 GENERIC_READ | GENERIC_WRITE,
83 NULL, // default security attributes.
84 OPEN_EXISTING, // opens existing pipe.
86 NULL)); // no template file.
87 if (!handle_b.is_valid()) {
88 DPLOG(ERROR) << "CreateFileW failed";
92 if (!ConnectNamedPipe(handle_a.get(), NULL)) {
93 DWORD error = GetLastError();
94 if (error != ERROR_PIPE_CONNECTED) {
95 DPLOG(ERROR) << "ConnectNamedPipe failed";
100 *socket_a = std::move(handle_a);
101 *socket_b = std::move(handle_b);
106 // Inline helper to avoid having the cast everywhere.
107 DWORD 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);
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.
117 template <typename BufferType, typename Function>
118 size_t CancelableFileOperation(Function operation,
122 WaitableEvent* io_event,
123 WaitableEvent* cancel_event,
124 CancelableSyncSocket* socket,
125 DWORD timeout_in_ms) {
126 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
127 // The buffer must be byte size or the length check won't make much sense.
128 static_assert(sizeof(buffer[0]) == sizeof(char), "incorrect buffer type");
129 DCHECK_GT(length, 0u);
130 DCHECK_LE(length, kMaxMessageLength);
131 DCHECK_NE(file, SyncSocket::kInvalidHandle);
133 // 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();
137 finish_time = current_time + base::Milliseconds(timeout_in_ms);
142 // The OVERLAPPED structure will be modified by ReadFile or WriteFile.
143 OVERLAPPED ol = { 0 };
144 ol.hEvent = io_event->handle();
146 const DWORD chunk = GetNextChunkSize(count, length);
147 // This is either the ReadFile or WriteFile call depending on whether
148 // we're receiving or sending data.
150 const BOOL operation_ok = operation(
151 file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol);
153 if (::GetLastError() == ERROR_IO_PENDING) {
154 HANDLE events[] = { io_event->handle(), cancel_event->handle() };
155 const DWORD wait_result = WaitForMultipleObjects(
156 std::size(events), events, FALSE,
157 timeout_in_ms == INFINITE
159 : static_cast<DWORD>(
160 (finish_time - current_time).InMilliseconds()));
161 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.
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))
173 if (wait_result == WAIT_OBJECT_0 + 1) {
174 DVLOG(1) << "Shutdown was signaled. Closing socket.";
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);
189 // Quit the operation if we can't write/read anymore.
193 // 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));
206 bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
207 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, false);
210 void SyncSocket::Close() {
214 size_t SyncSocket::Send(const void* buffer, size_t length) {
215 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
216 DCHECK_GT(length, 0u);
217 DCHECK_LE(length, kMaxMessageLength);
220 while (count < length) {
222 DWORD chunk = GetNextChunkSize(count, length);
223 if (::WriteFile(handle(), static_cast<const char*>(buffer) + count, chunk,
224 &len, NULL) == FALSE) {
232 size_t SyncSocket::ReceiveWithTimeout(void* buffer,
239 size_t SyncSocket::Receive(void* buffer, size_t length) {
240 ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
241 DCHECK_GT(length, 0u);
242 DCHECK_LE(length, kMaxMessageLength);
245 while (count < length) {
247 DWORD chunk = GetNextChunkSize(count, length);
248 if (::ReadFile(handle(), static_cast<char*>(buffer) + count, chunk, &len,
257 size_t SyncSocket::Peek() {
259 PeekNamedPipe(handle(), NULL, 0, NULL, &available, NULL);
263 bool SyncSocket::IsValid() const {
264 return handle_.is_valid();
267 SyncSocket::Handle SyncSocket::handle() const {
268 return handle_.get();
271 SyncSocket::Handle SyncSocket::Release() {
272 return handle_.release();
275 bool 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();
282 void CancelableSyncSocket::Close() {
284 shutdown_event_.Reset();
287 size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
288 static const DWORD kWaitTimeOutInMs = 500;
289 return CancelableFileOperation(
290 &::WriteFile, handle(), reinterpret_cast<const char*>(buffer), length,
291 &file_operation_, &shutdown_event_, this, kWaitTimeOutInMs);
294 size_t CancelableSyncSocket::Receive(void* buffer, size_t length) {
295 return CancelableFileOperation(
296 &::ReadFile, handle(), reinterpret_cast<char*>(buffer), length,
297 &file_operation_, &shutdown_event_, this, INFINITE);
300 size_t CancelableSyncSocket::ReceiveWithTimeout(void* buffer,
303 return CancelableFileOperation(&::ReadFile, handle(),
304 reinterpret_cast<char*>(buffer), length,
305 &file_operation_, &shutdown_event_, this,
306 static_cast<DWORD>(timeout.InMilliseconds()));
310 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
311 CancelableSyncSocket* socket_b) {
312 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, true);