• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <utility>
11 
12 #include "base/check.h"
13 #include "base/containers/span.h"
14 #include "base/logging.h"
15 #include "base/notimplemented.h"
16 #include "base/rand_util.h"
17 #include "base/threading/scoped_blocking_call.h"
18 #include "base/win/scoped_handle.h"
19 
20 namespace base {
21 
22 using win::ScopedHandle;
23 
24 namespace {
25 // IMPORTANT: do not change how this name is generated because it will break
26 // in sandboxed scenarios as we might have by-name policies that allow pipe
27 // creation. Also keep the secure random number generation.
28 const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\chrome.sync.%u.%u.%lu";
29 const size_t kPipePathMax = std::size(kPipeNameFormat) + (3 * 10) + 1;
30 
31 // To avoid users sending negative message lengths to Send/Receive
32 // we clamp message lengths, which are size_t, to no more than INT_MAX.
33 const size_t kMaxMessageLength = static_cast<size_t>(INT_MAX);
34 
35 const int kOutBufferSize = 4096;
36 const int kInBufferSize = 4096;
37 const int kDefaultTimeoutMilliSeconds = 1000;
38 
CreatePairImpl(ScopedHandle * socket_a,ScopedHandle * socket_b,bool overlapped)39 bool CreatePairImpl(ScopedHandle* socket_a,
40                     ScopedHandle* socket_b,
41                     bool overlapped) {
42   DCHECK_NE(socket_a, socket_b);
43   DCHECK(!socket_a->is_valid());
44   DCHECK(!socket_b->is_valid());
45 
46   wchar_t name[kPipePathMax];
47   ScopedHandle handle_a;
48   DWORD flags = PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE;
49   if (overlapped)
50     flags |= FILE_FLAG_OVERLAPPED;
51 
52   do {
53     unsigned long rnd_name;
54     RandBytes(byte_span_from_ref(rnd_name));
55 
56     swprintf(name, kPipePathMax,
57              kPipeNameFormat,
58              GetCurrentProcessId(),
59              GetCurrentThreadId(),
60              rnd_name);
61 
62     handle_a.Set(CreateNamedPipeW(
63         name,
64         flags,
65         PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
66         1,
67         kOutBufferSize,
68         kInBufferSize,
69         kDefaultTimeoutMilliSeconds,
70         NULL));
71   } while (!handle_a.is_valid() && (GetLastError() == ERROR_PIPE_BUSY));
72 
73   CHECK(handle_a.is_valid());
74 
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
77   // ends up in which side of a privilege boundary.
78   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.is_valid()) {
90     DPLOG(ERROR) << "CreateFileW failed";
91     return false;
92   }
93 
94   if (!ConnectNamedPipe(handle_a.get(), NULL)) {
95     DWORD error = GetLastError();
96     if (error != ERROR_PIPE_CONNECTED) {
97       DPLOG(ERROR) << "ConnectNamedPipe failed";
98       return false;
99     }
100   }
101 
102   *socket_a = std::move(handle_a);
103   *socket_b = std::move(handle_b);
104 
105   return true;
106 }
107 
108 // Inline helper to avoid having the cast everywhere.
GetNextChunkSize(size_t current_pos,size_t max_size)109 DWORD 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.
119 template <typename DataType, typename Function>
CancelableFileOperation(Function operation,HANDLE file,span<DataType> buffer,WaitableEvent * io_event,WaitableEvent * cancel_event,CancelableSyncSocket * socket,DWORD timeout_in_ms)120 size_t CancelableFileOperation(Function operation,
121                                HANDLE file,
122                                span<DataType> buffer,
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(DataType) == 1u, "incorrect buffer type");
130   CHECK(!buffer.empty());
131   CHECK_LE(buffer.size(), kMaxMessageLength);
132   CHECK_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_size = GetNextChunkSize(count, buffer.size());
148     // This is either the ReadFile or WriteFile call depending on whether
149     // we're receiving or sending data.
150     DWORD len = 0;
151     auto operation_buffer = buffer.subspan(count, chunk_size);
152     // SAFETY: The below static_cast is in range for DWORD because
153     // `operation_buffer` is constructed with a DWORD length above from
154     // `chunk_size`.
155     const BOOL operation_ok =
156         operation(file, operation_buffer.data(),
157                   static_cast<DWORD>(operation_buffer.size()), &len, &ol);
158     if (!operation_ok) {
159       if (::GetLastError() == ERROR_IO_PENDING) {
160         HANDLE events[] = { io_event->handle(), cancel_event->handle() };
161         const DWORD wait_result = WaitForMultipleObjects(
162             std::size(events), events, FALSE,
163             timeout_in_ms == INFINITE
164                 ? timeout_in_ms
165                 : static_cast<DWORD>(
166                       (finish_time - current_time).InMilliseconds()));
167         if (wait_result != WAIT_OBJECT_0 + 0) {
168           // CancelIo() doesn't synchronously cancel outstanding IO, only marks
169           // outstanding IO for cancellation. We must call GetOverlappedResult()
170           // below to ensure in flight writes complete before returning.
171           CancelIo(file);
172         }
173 
174         // We set the |bWait| parameter to TRUE for GetOverlappedResult() to
175         // ensure writes are complete before returning.
176         if (!GetOverlappedResult(file, &ol, &len, TRUE))
177           len = 0;
178 
179         if (wait_result == WAIT_OBJECT_0 + 1) {
180           DVLOG(1) << "Shutdown was signaled. Closing socket.";
181           socket->Close();
182           return count;
183         }
184 
185         // Timeouts will be handled by the while() condition below since
186         // GetOverlappedResult() may complete successfully after CancelIo().
187         DCHECK(wait_result == WAIT_OBJECT_0 + 0 || wait_result == WAIT_TIMEOUT);
188       } else {
189         break;
190       }
191     }
192 
193     count += len;
194 
195     // Quit the operation if we can't write/read anymore.
196     if (len != chunk_size) {
197       break;
198     }
199 
200     // Since TimeTicks::Now() is expensive, only bother updating the time if we
201     // have more work to do.
202     if (timeout_in_ms != INFINITE && count < buffer.size()) {
203       current_time = base::TimeTicks::Now();
204     }
205   } while (count < buffer.size() &&
206            (timeout_in_ms == INFINITE || current_time < finish_time));
207 
208   return count;
209 }
210 
211 }  // namespace
212 
213 // static
CreatePair(SyncSocket * socket_a,SyncSocket * socket_b)214 bool SyncSocket::CreatePair(SyncSocket* socket_a, SyncSocket* socket_b) {
215   return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, false);
216 }
217 
Close()218 void SyncSocket::Close() {
219   handle_.Close();
220 }
221 
Send(span<const uint8_t> data)222 size_t SyncSocket::Send(span<const uint8_t> data) {
223   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
224   CHECK_LE(data.size(), kMaxMessageLength);
225   DCHECK(IsValid());
226   size_t count = 0;
227   while (count < data.size()) {
228     DWORD len;
229     const DWORD chunk_size = GetNextChunkSize(count, data.size());
230     auto data_chunk = data.subspan(count, chunk_size);
231     // SAFETY: The below static_cast is in range for DWORD because `data_chunk`
232     // is constructed with a DWORD length above from `chunk_size`.
233     if (::WriteFile(handle(), data_chunk.data(),
234                     static_cast<DWORD>(data_chunk.size()), &len,
235                     NULL) == FALSE) {
236       return count;
237     }
238     count += len;
239   }
240   return count;
241 }
242 
ReceiveWithTimeout(span<uint8_t> buffer,TimeDelta timeout)243 size_t SyncSocket::ReceiveWithTimeout(span<uint8_t> buffer, TimeDelta timeout) {
244   NOTIMPLEMENTED();
245   return 0;
246 }
247 
Receive(span<uint8_t> buffer)248 size_t SyncSocket::Receive(span<uint8_t> buffer) {
249   ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
250   CHECK_LE(buffer.size(), kMaxMessageLength);
251   DCHECK(IsValid());
252   size_t count = 0;
253   while (count < buffer.size()) {
254     DWORD len;
255     const DWORD chunk_size = GetNextChunkSize(count, buffer.size());
256     auto data_chunk = buffer.subspan(count, chunk_size);
257     // SAFETY: The below static_cast is in range for DWORD because `data_chunk`
258     // is constructed with a DWORD length above from `chunk_size`.
259     if (::ReadFile(handle(), data_chunk.data(),
260                    static_cast<DWORD>(data_chunk.size()), &len,
261                    NULL) == FALSE) {
262       return count;
263     }
264     count += len;
265   }
266   return count;
267 }
268 
Peek()269 size_t SyncSocket::Peek() {
270   DWORD available = 0;
271   PeekNamedPipe(handle(), NULL, 0, NULL, &available, NULL);
272   return available;
273 }
274 
IsValid() const275 bool SyncSocket::IsValid() const {
276   return handle_.is_valid();
277 }
278 
handle() const279 SyncSocket::Handle SyncSocket::handle() const {
280   return handle_.get();
281 }
282 
Release()283 SyncSocket::Handle SyncSocket::Release() {
284   return handle_.release();
285 }
286 
Shutdown()287 bool CancelableSyncSocket::Shutdown() {
288   // This doesn't shut down the pipe immediately, but subsequent Receive or Send
289   // methods will fail straight away.
290   shutdown_event_.Signal();
291   return true;
292 }
293 
Close()294 void CancelableSyncSocket::Close() {
295   SyncSocket::Close();
296   shutdown_event_.Reset();
297 }
298 
Send(span<const uint8_t> data)299 size_t CancelableSyncSocket::Send(span<const uint8_t> data) {
300   static const DWORD kWaitTimeOutInMs = 500;
301   return CancelableFileOperation(&::WriteFile, handle(), data, &file_operation_,
302                                  &shutdown_event_, this, kWaitTimeOutInMs);
303 }
304 
Receive(span<uint8_t> buffer)305 size_t CancelableSyncSocket::Receive(span<uint8_t> buffer) {
306   return CancelableFileOperation(&::ReadFile, handle(), buffer,
307                                  &file_operation_, &shutdown_event_, this,
308                                  INFINITE);
309 }
310 
ReceiveWithTimeout(span<uint8_t> buffer,TimeDelta timeout)311 size_t CancelableSyncSocket::ReceiveWithTimeout(span<uint8_t> buffer,
312                                                 TimeDelta timeout) {
313   return CancelableFileOperation(&::ReadFile, handle(), buffer,
314                                  &file_operation_, &shutdown_event_, this,
315                                  static_cast<DWORD>(timeout.InMilliseconds()));
316 }
317 
318 // static
CreatePair(CancelableSyncSocket * socket_a,CancelableSyncSocket * socket_b)319 bool CancelableSyncSocket::CreatePair(CancelableSyncSocket* socket_a,
320                                       CancelableSyncSocket* socket_b) {
321   return CreatePairImpl(&socket_a->handle_, &socket_b->handle_, true);
322 }
323 
324 }  // namespace base
325