Update V8 to version 4.7.58.
[chromium-blink-merge.git] / base / sync_socket_win.cc
blobfb722919f6c45239810eb45c01bdfe21d0d06cdf
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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"
7 #include "base/logging.h"
8 #include "base/threading/thread_restrictions.h"
9 #include "base/win/scoped_handle.h"
11 namespace base {
13 using win::ScopedHandle;
15 namespace {
16 // 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.
19 const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\chrome.sync.%u.%u.%lu";
20 const size_t kPipePathMax = arraysize(kPipeNameFormat) + (3 * 10) + 1;
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.
24 const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
26 const int kOutBufferSize = 4096;
27 const int kInBufferSize = 4096;
28 const int kDefaultTimeoutMilliSeconds = 1000;
30 bool CreatePairImpl(HANDLE* socket_a, HANDLE* socket_b, bool overlapped) {
31 DCHECK_NE(socket_a, socket_b);
32 DCHECK_EQ(*socket_a, SyncSocket::kInvalidHandle);
33 DCHECK_EQ(*socket_b, SyncSocket::kInvalidHandle);
35 wchar_t name[kPipePathMax];
36 ScopedHandle handle_a;
37 DWORD flags = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE;
38 if (overlapped)
39 flags |= FILE_FLAG_OVERLAPPED;
41 do {
42 unsigned int rnd_name;
43 if (rand_s(&rnd_name) != 0)
44 return false;
46 swprintf(name, kPipePathMax,
47 kPipeNameFormat,
48 GetCurrentProcessId(),
49 GetCurrentThreadId(),
50 rnd_name);
52 handle_a.Set(CreateNamedPipeW(
53 name,
54 flags,
55 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
57 kOutBufferSize,
58 kInBufferSize,
59 kDefaultTimeoutMilliSeconds,
60 NULL));
61 } while (!handle_a.IsValid() &&
62 (GetLastError() == ERROR_PIPE_BUSY));
64 if (!handle_a.IsValid()) {
65 NOTREACHED();
66 return false;
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
71 // ends up in which side of a privilege boundary.
72 flags = SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS;
73 if (overlapped)
74 flags |= FILE_FLAG_OVERLAPPED;
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";
85 return false;
88 if (!ConnectNamedPipe(handle_a.Get(), NULL)) {
89 DWORD error = GetLastError();
90 if (error != ERROR_PIPE_CONNECTED) {
91 DPLOG(ERROR) << "ConnectNamedPipe failed";
92 return false;
96 *socket_a = handle_a.Take();
97 *socket_b = handle_b.Take();
99 return true;
102 // Inline helper to avoid having the cast everywhere.
103 DWORD 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);
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.
113 template <typename BufferType, typename Function>
114 size_t CancelableFileOperation(Function operation,
115 HANDLE file,
116 BufferType* buffer,
117 size_t length,
118 WaitableEvent* io_event,
119 WaitableEvent* cancel_event,
120 CancelableSyncSocket* socket,
121 DWORD timeout_in_ms) {
122 ThreadRestrictions::AssertIOAllowed();
123 // 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);
125 DCHECK_GT(length, 0u);
126 DCHECK_LE(length, kMaxMessageLength);
127 DCHECK_NE(file, SyncSocket::kInvalidHandle);
129 // 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);
137 size_t count = 0;
138 do {
139 // The OVERLAPPED structure will be modified by ReadFile or WriteFile.
140 OVERLAPPED ol = { 0 };
141 ol.hEvent = io_event->handle();
143 const DWORD chunk = GetNextChunkSize(count, length);
144 // This is either the ReadFile or WriteFile call depending on whether
145 // we're receiving or sending data.
146 DWORD len = 0;
147 const BOOL operation_ok = operation(
148 file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol);
149 if (!operation_ok) {
150 if (::GetLastError() == ERROR_IO_PENDING) {
151 HANDLE events[] = { io_event->handle(), cancel_event->handle() };
152 const int wait_result = WaitForMultipleObjects(
153 arraysize(events), events, FALSE,
154 timeout_in_ms == INFINITE ?
155 timeout_in_ms :
156 static_cast<DWORD>(
157 (finish_time - current_time).InMilliseconds()));
158 if (wait_result != WAIT_OBJECT_0 + 0) {
159 // CancelIo() doesn't synchronously cancel outstanding IO, only marks
160 // outstanding IO for cancellation. We must call GetOverlappedResult()
161 // below to ensure in flight writes complete before returning.
162 CancelIo(file);
165 // We set the |bWait| parameter to TRUE for GetOverlappedResult() to
166 // ensure writes are complete before returning.
167 if (!GetOverlappedResult(file, &ol, &len, TRUE))
168 len = 0;
170 if (wait_result == WAIT_OBJECT_0 + 1) {
171 DVLOG(1) << "Shutdown was signaled. Closing socket.";
172 socket->Close();
173 return count;
176 // Timeouts will be handled by the while() condition below since
177 // GetOverlappedResult() may complete successfully after CancelIo().
178 DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT);
179 } else {
180 break;
184 count += len;
186 // Quit the operation if we can't write/read anymore.
187 if (len != chunk)
188 break;
190 // Since TimeTicks::Now() is expensive, only bother updating the time if we
191 // have more work to do.
192 if (timeout_in_ms != INFINITE && count < length)
193 current_time = base::TimeTicks::Now();
194 } while (count < length &&
195 (timeout_in_ms == INFINITE || current_time < finish_time));
197 return count;
200 } // namespace
202 #if defined(COMPONENT_BUILD)
203 const SyncSocket::Handle SyncSocket::kInvalidHandle = INVALID_HANDLE_VALUE;
204 #endif
206 SyncSocket::SyncSocket() : handle_(kInvalidHandle) {}
208 SyncSocket::~SyncSocket() {
209 Close();
212 // static
213 bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
214 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, false);
217 // static
218 SyncSocket::Handle SyncSocket::UnwrapHandle(
219 const TransitDescriptor& descriptor) {
220 return descriptor;
223 bool SyncSocket::PrepareTransitDescriptor(ProcessHandle peer_process_handle,
224 TransitDescriptor* descriptor) {
225 DCHECK(descriptor);
226 if (!::DuplicateHandle(GetCurrentProcess(), handle(), peer_process_handle,
227 descriptor, 0, FALSE, DUPLICATE_SAME_ACCESS)) {
228 DPLOG(ERROR) << "Cannot duplicate socket handle for peer process.";
229 return false;
231 return true;
234 bool SyncSocket::Close() {
235 if (handle_ == kInvalidHandle)
236 return true;
238 const BOOL result = ::CloseHandle(handle_);
239 CHECK(result);
240 handle_ = kInvalidHandle;
241 return result == TRUE;
244 size_t SyncSocket::Send(const void* buffer, size_t length) {
245 ThreadRestrictions::AssertIOAllowed();
246 DCHECK_GT(length, 0u);
247 DCHECK_LE(length, kMaxMessageLength);
248 DCHECK_NE(handle_, kInvalidHandle);
249 size_t count = 0;
250 while (count < length) {
251 DWORD len;
252 DWORD chunk = GetNextChunkSize(count, length);
253 if (WriteFile(handle_, static_cast<const char*>(buffer) + count,
254 chunk, &len, NULL) == FALSE) {
255 return count;
257 count += len;
259 return count;
262 size_t SyncSocket::ReceiveWithTimeout(void* buffer,
263 size_t length,
264 TimeDelta timeout) {
265 NOTIMPLEMENTED();
266 return 0;
269 size_t SyncSocket::Receive(void* buffer, size_t length) {
270 ThreadRestrictions::AssertIOAllowed();
271 DCHECK_GT(length, 0u);
272 DCHECK_LE(length, kMaxMessageLength);
273 DCHECK_NE(handle_, kInvalidHandle);
274 size_t count = 0;
275 while (count < length) {
276 DWORD len;
277 DWORD chunk = GetNextChunkSize(count, length);
278 if (ReadFile(handle_, static_cast<char*>(buffer) + count,
279 chunk, &len, NULL) == FALSE) {
280 return count;
282 count += len;
284 return count;
287 size_t SyncSocket::Peek() {
288 DWORD available = 0;
289 PeekNamedPipe(handle_, NULL, 0, NULL, &available, NULL);
290 return available;
293 CancelableSyncSocket::CancelableSyncSocket()
294 : shutdown_event_(true, false), file_operation_(true, false) {
297 CancelableSyncSocket::CancelableSyncSocket(Handle handle)
298 : SyncSocket(handle), shutdown_event_(true, false),
299 file_operation_(true, false) {
302 bool CancelableSyncSocket::Shutdown() {
303 // This doesn't shut down the pipe immediately, but subsequent Receive or Send
304 // methods will fail straight away.
305 shutdown_event_.Signal();
306 return true;
309 bool CancelableSyncSocket::Close() {
310 const bool result = SyncSocket::Close();
311 shutdown_event_.Reset();
312 return result;
315 size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
316 static const DWORD kWaitTimeOutInMs = 500;
317 return CancelableFileOperation(
318 &WriteFile, handle_, reinterpret_cast<const char*>(buffer),
319 length, &file_operation_, &shutdown_event_, this, kWaitTimeOutInMs);
322 size_t CancelableSyncSocket::Receive(void* buffer, size_t length) {
323 return CancelableFileOperation(
324 &ReadFile, handle_, reinterpret_cast<char*>(buffer), length,
325 &file_operation_, &shutdown_event_, this, INFINITE);
328 size_t CancelableSyncSocket::ReceiveWithTimeout(void* buffer,
329 size_t length,
330 TimeDelta timeout) {
331 return CancelableFileOperation(
332 &ReadFile, handle_, reinterpret_cast<char*>(buffer), length,
333 &file_operation_, &shutdown_event_, this,
334 static_cast<DWORD>(timeout.InMilliseconds()));
337 // static
338 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
339 CancelableSyncSocket* socket_b) {
340 return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, true);
343 } // namespace base