Fix emulator build error
[platform/framework/web/chromium-efl.git] / base / sync_socket_win.cc
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.
4
5 #include "base/sync_socket.h"
6
7 #include <limits.h>
8 #include <stddef.h>
9
10 #include "base/logging.h"
11 #include "base/notreached.h"
12 #include "base/rand_util.h"
13 #include "base/threading/scoped_blocking_call.h"
14 #include "base/win/scoped_handle.h"
15
16 namespace base {
17
18 using win::ScopedHandle;
19
20 namespace {
21 // 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.
24 const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\chrome.sync.%u.%u.%lu";
25 const size_t kPipePathMax = std::size(kPipeNameFormat) + (3 * 10) + 1;
26
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.
29 const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
30
31 const int kOutBufferSize = 4096;
32 const int kInBufferSize = 4096;
33 const int kDefaultTimeoutMilliSeconds = 1000;
34
35 bool CreatePairImpl(ScopedHandle* socket_a,
36                     ScopedHandle* socket_b,
37                     bool overlapped) {
38   DCHECK_NE(socket_a, socket_b);
39   DCHECK(!socket_a->is_valid());
40   DCHECK(!socket_b->is_valid());
41
42   wchar_t name[kPipePathMax];
43   ScopedHandle handle_a;
44   DWORD flags = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE;
45   if (overlapped)
46     flags |= FILE_FLAG_OVERLAPPED;
47
48   do {
49     unsigned long rnd_name;
50     RandBytes(&rnd_name, sizeof(rnd_name));
51
52     swprintf(name, kPipePathMax,
53              kPipeNameFormat,
54              GetCurrentProcessId(),
55              GetCurrentThreadId(),
56              rnd_name);
57
58     handle_a.Set(CreateNamedPipeW(
59         name,
60         flags,
61         PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
62         1,
63         kOutBufferSize,
64         kInBufferSize,
65         kDefaultTimeoutMilliSeconds,
66         NULL));
67   } while (!handle_a.is_valid() && (GetLastError() == ERROR_PIPE_BUSY));
68
69   if (!handle_a.is_valid()) {
70     NOTREACHED();
71     return false;
72   }
73
74   // The SECURITY_ANONYMOUS flag means that the server side (handle_a) cannot
75   // impersonate the client (handle_b). This allows us not to care which side
76   // ends up in which side of a privilege boundary.
77   flags = SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS;
78   if (overlapped)
79     flags |= FILE_FLAG_OVERLAPPED;
80
81   ScopedHandle handle_b(CreateFileW(name,
82                                     GENERIC_READ | GENERIC_WRITE,
83                                     0,          // no sharing.
84                                     NULL,       // default security attributes.
85                                     OPEN_EXISTING,  // opens existing pipe.
86                                     flags,
87                                     NULL));     // no template file.
88   if (!handle_b.is_valid()) {
89     DPLOG(ERROR) << "CreateFileW failed";
90     return false;
91   }
92
93   if (!ConnectNamedPipe(handle_a.get(), NULL)) {
94     DWORD error = GetLastError();
95     if (error != ERROR_PIPE_CONNECTED) {
96       DPLOG(ERROR) << "ConnectNamedPipe failed";
97       return false;
98     }
99   }
100
101   *socket_a = std::move(handle_a);
102   *socket_b = std::move(handle_b);
103
104   return true;
105 }
106
107 // Inline helper to avoid having the cast everywhere.
108 DWORD GetNextChunkSize(size_t current_pos, size_t max_size) {
109   // The following statement is for 64 bit portability.
110   return static_cast<DWORD>(((max_size - current_pos) <= UINT_MAX) ?
111       (max_size - current_pos) : UINT_MAX);
112 }
113
114 // Template function that supports calling ReadFile or WriteFile in an
115 // overlapped fashion and waits for IO completion.  The function also waits
116 // on an event that can be used to cancel the operation.  If the operation
117 // is cancelled, the function returns and closes the relevant socket object.
118 template <typename BufferType, typename Function>
119 size_t CancelableFileOperation(Function operation,
120                                HANDLE file,
121                                BufferType* buffer,
122                                size_t length,
123                                WaitableEvent* io_event,
124                                WaitableEvent* cancel_event,
125                                CancelableSyncSocket* socket,
126                                DWORD timeout_in_ms) {
127   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
128   // The buffer must be byte size or the length check won't make much sense.
129   static_assert(sizeof(buffer[0]) == sizeof(char), "incorrect buffer type");
130   DCHECK_GT(length, 0u);
131   DCHECK_LE(length, kMaxMessageLength);
132   DCHECK_NE(file, SyncSocket::kInvalidHandle);
133
134   // Track the finish time so we can calculate the timeout as data is read.
135   TimeTicks current_time, finish_time;
136   if (timeout_in_ms != INFINITE) {
137     current_time = TimeTicks::Now();
138     finish_time = current_time + base::Milliseconds(timeout_in_ms);
139   }
140
141   size_t count = 0;
142   do {
143     // The OVERLAPPED structure will be modified by ReadFile or WriteFile.
144     OVERLAPPED ol = { 0 };
145     ol.hEvent = io_event->handle();
146
147     const DWORD chunk = GetNextChunkSize(count, length);
148     // This is either the ReadFile or WriteFile call depending on whether
149     // we're receiving or sending data.
150     DWORD len = 0;
151     const BOOL operation_ok = operation(
152         file, static_cast<BufferType*>(buffer) + count, chunk, &len, &ol);
153     if (!operation_ok) {
154       if (::GetLastError() == ERROR_IO_PENDING) {
155         HANDLE events[] = { io_event->handle(), cancel_event->handle() };
156         const DWORD wait_result = WaitForMultipleObjects(
157             std::size(events), events, FALSE,
158             timeout_in_ms == INFINITE
159                 ? timeout_in_ms
160                 : static_cast<DWORD>(
161                       (finish_time - current_time).InMilliseconds()));
162         if (wait_result != WAIT_OBJECT_0 + 0) {
163           // CancelIo() doesn't synchronously cancel outstanding IO, only marks
164           // outstanding IO for cancellation. We must call GetOverlappedResult()
165           // below to ensure in flight writes complete before returning.
166           CancelIo(file);
167         }
168
169         // We set the |bWait| parameter to TRUE for GetOverlappedResult() to
170         // ensure writes are complete before returning.
171         if (!GetOverlappedResult(file, &ol, &len, TRUE))
172           len = 0;
173
174         if (wait_result == WAIT_OBJECT_0 + 1) {
175           DVLOG(1) << "Shutdown was signaled. Closing socket.";
176           socket->Close();
177           return count;
178         }
179
180         // Timeouts will be handled by the while() condition below since
181         // GetOverlappedResult() may complete successfully after CancelIo().
182         DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT);
183       } else {
184         break;
185       }
186     }
187
188     count += len;
189
190     // Quit the operation if we can't write/read anymore.
191     if (len != chunk)
192       break;
193
194     // Since TimeTicks::Now() is expensive, only bother updating the time if we
195     // have more work to do.
196     if (timeout_in_ms != INFINITE && count < length)
197       current_time = base::TimeTicks::Now();
198   } while (count < length &&
199            (timeout_in_ms == INFINITE || current_time < finish_time));
200
201   return count;
202 }
203
204 }  // namespace
205
206 // static
207 bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
208   return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, false);
209 }
210
211 void SyncSocket::Close() {
212   handle_.Close();
213 }
214
215 size_t SyncSocket::Send(const void* buffer, size_t length) {
216   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
217   DCHECK_GT(length, 0u);
218   DCHECK_LE(length, kMaxMessageLength);
219   DCHECK(IsValid());
220   size_t count = 0;
221   while (count < length) {
222     DWORD len;
223     DWORD chunk = GetNextChunkSize(count, length);
224     if (::WriteFile(handle(), static_cast<const char*>(buffer) + count, chunk,
225                     &len, NULL) == FALSE) {
226       return count;
227     }
228     count += len;
229   }
230   return count;
231 }
232
233 size_t SyncSocket::ReceiveWithTimeout(void* buffer,
234                                       size_t length,
235                                       TimeDelta timeout) {
236   NOTIMPLEMENTED();
237   return 0;
238 }
239
240 size_t SyncSocket::Receive(void* buffer, size_t length) {
241   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
242   DCHECK_GT(length, 0u);
243   DCHECK_LE(length, kMaxMessageLength);
244   DCHECK(IsValid());
245   size_t count = 0;
246   while (count < length) {
247     DWORD len;
248     DWORD chunk = GetNextChunkSize(count, length);
249     if (::ReadFile(handle(), static_cast<char*>(buffer) + count, chunk, &len,
250                    NULL) == FALSE) {
251       return count;
252     }
253     count += len;
254   }
255   return count;
256 }
257
258 size_t SyncSocket::Peek() {
259   DWORD available = 0;
260   PeekNamedPipe(handle(), NULL, 0, NULL, &available, NULL);
261   return available;
262 }
263
264 bool SyncSocket::IsValid() const {
265   return handle_.is_valid();
266 }
267
268 SyncSocket::Handle SyncSocket::handle() const {
269   return handle_.get();
270 }
271
272 SyncSocket::Handle SyncSocket::Release() {
273   return handle_.release();
274 }
275
276 bool CancelableSyncSocket::Shutdown() {
277   // This doesn't shut down the pipe immediately, but subsequent Receive or Send
278   // methods will fail straight away.
279   shutdown_event_.Signal();
280   return true;
281 }
282
283 void CancelableSyncSocket::Close() {
284   SyncSocket::Close();
285   shutdown_event_.Reset();
286 }
287
288 size_t CancelableSyncSocket::Send(const void* buffer, size_t length) {
289   static const DWORD kWaitTimeOutInMs = 500;
290   return CancelableFileOperation(
291       &::WriteFile, handle(), reinterpret_cast<const char*>(buffer), length,
292       &file_operation_, &shutdown_event_, this, kWaitTimeOutInMs);
293 }
294
295 size_t CancelableSyncSocket::Receive(void* buffer, size_t length) {
296   return CancelableFileOperation(
297       &::ReadFile, handle(), reinterpret_cast<char*>(buffer), length,
298       &file_operation_, &shutdown_event_, this, INFINITE);
299 }
300
301 size_t CancelableSyncSocket::ReceiveWithTimeout(void* buffer,
302                                                 size_t length,
303                                                 TimeDelta timeout) {
304   return CancelableFileOperation(&::ReadFile, handle(),
305                                  reinterpret_cast<char*>(buffer), length,
306                                  &file_operation_, &shutdown_event_, this,
307                                  static_cast<DWORD>(timeout.InMilliseconds()));
308 }
309
310 // static
311 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
312                                       CancelableSyncSocket* socket_b) {
313   return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, true);
314 }
315
316 }  // namespace base