Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / sandbox / win / src / sharedmem_ipc_server.cc
blob5ce7da5d581487269e2647d320ca2aabb0fded95
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/callback.h"
6 #include "base/logging.h"
7 #include "base/memory/scoped_ptr.h"
8 #include "sandbox/win/src/sharedmem_ipc_server.h"
9 #include "sandbox/win/src/sharedmem_ipc_client.h"
10 #include "sandbox/win/src/sandbox.h"
11 #include "sandbox/win/src/sandbox_types.h"
12 #include "sandbox/win/src/crosscall_params.h"
13 #include "sandbox/win/src/crosscall_server.h"
15 namespace {
16 // This handle must not be closed.
17 volatile HANDLE g_alive_mutex = NULL;
20 namespace sandbox {
22 SharedMemIPCServer::SharedMemIPCServer(HANDLE target_process,
23 DWORD target_process_id,
24 HANDLE target_job,
25 ThreadProvider* thread_provider,
26 Dispatcher* dispatcher)
27 : client_control_(NULL),
28 thread_provider_(thread_provider),
29 target_process_(target_process),
30 target_process_id_(target_process_id),
31 target_job_object_(target_job),
32 call_dispatcher_(dispatcher) {
33 // We create a initially owned mutex. If the server dies unexpectedly,
34 // the thread that owns it will fail to release the lock and windows will
35 // report to the target (when it tries to acquire it) that the wait was
36 // abandoned. Note: We purposely leak the local handle because we want it to
37 // be closed by Windows itself so it is properly marked as abandoned if the
38 // server dies.
39 if (!g_alive_mutex) {
40 HANDLE mutex = ::CreateMutexW(NULL, TRUE, NULL);
41 if (::InterlockedCompareExchangePointer(&g_alive_mutex, mutex, NULL)) {
42 // We lost the race to create the mutex.
43 ::CloseHandle(mutex);
48 SharedMemIPCServer::~SharedMemIPCServer() {
49 // Free the wait handles associated with the thread pool.
50 if (!thread_provider_->UnRegisterWaits(this)) {
51 // Better to leak than to crash.
52 return;
54 // Free the IPC signal events.
55 ServerContexts::iterator it;
56 for (it = server_contexts_.begin(); it != server_contexts_.end(); ++it) {
57 ServerControl* context = (*it);
58 ::CloseHandle(context->ping_event);
59 ::CloseHandle(context->pong_event);
60 delete context;
63 if (client_control_)
64 ::UnmapViewOfFile(client_control_);
67 bool SharedMemIPCServer::Init(void* shared_mem, uint32 shared_size,
68 uint32 channel_size) {
69 // The shared memory needs to be at least as big as a channel.
70 if (shared_size < channel_size) {
71 return false;
73 // The channel size should be aligned.
74 if (0 != (channel_size % 32)) {
75 return false;
78 // Calculate how many channels we can fit in the shared memory.
79 shared_size -= offsetof(IPCControl, channels);
80 size_t channel_count = shared_size / (sizeof(ChannelControl) + channel_size);
82 // If we cannot fit even one channel we bail out.
83 if (0 == channel_count) {
84 return false;
86 // Calculate the start of the first channel.
87 size_t base_start = (sizeof(ChannelControl)* channel_count) +
88 offsetof(IPCControl, channels);
90 client_control_ = reinterpret_cast<IPCControl*>(shared_mem);
91 client_control_->channels_count = 0;
93 // This is the initialization that we do per-channel. Basically:
94 // 1) make two events (ping & pong)
95 // 2) create handles to the events for the client and the server.
96 // 3) initialize the channel (client_context) with the state.
97 // 4) initialize the server side of the channel (service_context).
98 // 5) call the thread provider RegisterWait to register the ping events.
99 for (size_t ix = 0; ix != channel_count; ++ix) {
100 ChannelControl* client_context = &client_control_->channels[ix];
101 ServerControl* service_context = new ServerControl;
102 server_contexts_.push_back(service_context);
104 if (!MakeEvents(&service_context->ping_event,
105 &service_context->pong_event,
106 &client_context->ping_event,
107 &client_context->pong_event)) {
108 return false;
111 client_context->channel_base = base_start;
112 client_context->state = kFreeChannel;
114 // Note that some of these values are available as members of this
115 // object but we put them again into the service_context because we
116 // will be called on a static method (ThreadPingEventReady)
117 service_context->shared_base = reinterpret_cast<char*>(shared_mem);
118 service_context->channel_size = channel_size;
119 service_context->channel = client_context;
120 service_context->channel_buffer = service_context->shared_base +
121 client_context->channel_base;
122 service_context->dispatcher = call_dispatcher_;
123 service_context->target_info.process = target_process_;
124 service_context->target_info.process_id = target_process_id_;
125 service_context->target_info.job_object = target_job_object_;
126 // Advance to the next channel.
127 base_start += channel_size;
128 // Register the ping event with the threadpool.
129 thread_provider_->RegisterWait(this, service_context->ping_event,
130 ThreadPingEventReady, service_context);
132 if (!::DuplicateHandle(::GetCurrentProcess(), g_alive_mutex,
133 target_process_, &client_control_->server_alive,
134 SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, 0)) {
135 return false;
137 // This last setting indicates to the client all is setup.
138 client_control_->channels_count = channel_count;
139 return true;
142 // Releases memory allocated for IPC arguments, if needed.
143 void ReleaseArgs(const IPCParams* ipc_params, void* args[kMaxIpcParams]) {
144 for (size_t i = 0; i < kMaxIpcParams; i++) {
145 switch (ipc_params->args[i]) {
146 case WCHAR_TYPE: {
147 delete reinterpret_cast<base::string16*>(args[i]);
148 args[i] = NULL;
149 break;
151 case INOUTPTR_TYPE: {
152 delete reinterpret_cast<CountedBuffer*>(args[i]);
153 args[i] = NULL;
154 break;
156 default: break;
161 // Fills up the list of arguments (args and ipc_params) for an IPC call.
162 bool GetArgs(CrossCallParamsEx* params, IPCParams* ipc_params,
163 void* args[kMaxIpcParams]) {
164 if (kMaxIpcParams < params->GetParamsCount())
165 return false;
167 for (uint32 i = 0; i < params->GetParamsCount(); i++) {
168 uint32 size;
169 ArgType type;
170 args[i] = params->GetRawParameter(i, &size, &type);
171 if (args[i]) {
172 ipc_params->args[i] = type;
173 switch (type) {
174 case WCHAR_TYPE: {
175 scoped_ptr<base::string16> data(new base::string16);
176 if (!params->GetParameterStr(i, data.get())) {
177 args[i] = 0;
178 ReleaseArgs(ipc_params, args);
179 return false;
181 args[i] = data.release();
182 break;
184 case UINT32_TYPE: {
185 uint32 data;
186 if (!params->GetParameter32(i, &data)) {
187 ReleaseArgs(ipc_params, args);
188 return false;
190 IPCInt ipc_int(data);
191 args[i] = ipc_int.AsVoidPtr();
192 break;
194 case VOIDPTR_TYPE : {
195 void* data;
196 if (!params->GetParameterVoidPtr(i, &data)) {
197 ReleaseArgs(ipc_params, args);
198 return false;
200 args[i] = data;
201 break;
203 case INOUTPTR_TYPE: {
204 if (!args[i]) {
205 ReleaseArgs(ipc_params, args);
206 return false;
208 CountedBuffer* buffer = new CountedBuffer(args[i] , size);
209 args[i] = buffer;
210 break;
212 default: break;
216 return true;
219 bool SharedMemIPCServer::InvokeCallback(const ServerControl* service_context,
220 void* ipc_buffer,
221 CrossCallReturn* call_result) {
222 // Set the default error code;
223 SetCallError(SBOX_ERROR_INVALID_IPC, call_result);
224 uint32 output_size = 0;
225 // Parse, verify and copy the message. The handler operates on a copy
226 // of the message so the client cannot play dirty tricks by changing the
227 // data in the channel while the IPC is being processed.
228 scoped_ptr<CrossCallParamsEx> params(
229 CrossCallParamsEx::CreateFromBuffer(ipc_buffer,
230 service_context->channel_size,
231 &output_size));
232 if (!params.get())
233 return false;
235 uint32 tag = params->GetTag();
236 static_assert(0 == INVALID_TYPE, "incorrect type enum");
237 IPCParams ipc_params = {0};
238 ipc_params.ipc_tag = tag;
240 void* args[kMaxIpcParams];
241 if (!GetArgs(params.get(), &ipc_params, args))
242 return false;
244 IPCInfo ipc_info = {0};
245 ipc_info.ipc_tag = tag;
246 ipc_info.client_info = &service_context->target_info;
247 Dispatcher* dispatcher = service_context->dispatcher;
248 DCHECK(dispatcher);
249 bool error = true;
250 Dispatcher* handler = NULL;
252 Dispatcher::CallbackGeneric callback_generic;
253 handler = dispatcher->OnMessageReady(&ipc_params, &callback_generic);
254 if (handler) {
255 switch (params->GetParamsCount()) {
256 case 0: {
257 // Ask the IPC dispatcher if she can service this IPC.
258 Dispatcher::Callback0 callback =
259 reinterpret_cast<Dispatcher::Callback0>(callback_generic);
260 if (!(handler->*callback)(&ipc_info))
261 break;
262 error = false;
263 break;
265 case 1: {
266 Dispatcher::Callback1 callback =
267 reinterpret_cast<Dispatcher::Callback1>(callback_generic);
268 if (!(handler->*callback)(&ipc_info, args[0]))
269 break;
270 error = false;
271 break;
273 case 2: {
274 Dispatcher::Callback2 callback =
275 reinterpret_cast<Dispatcher::Callback2>(callback_generic);
276 if (!(handler->*callback)(&ipc_info, args[0], args[1]))
277 break;
278 error = false;
279 break;
281 case 3: {
282 Dispatcher::Callback3 callback =
283 reinterpret_cast<Dispatcher::Callback3>(callback_generic);
284 if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2]))
285 break;
286 error = false;
287 break;
289 case 4: {
290 Dispatcher::Callback4 callback =
291 reinterpret_cast<Dispatcher::Callback4>(callback_generic);
292 if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2],
293 args[3]))
294 break;
295 error = false;
296 break;
298 case 5: {
299 Dispatcher::Callback5 callback =
300 reinterpret_cast<Dispatcher::Callback5>(callback_generic);
301 if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
302 args[4]))
303 break;
304 error = false;
305 break;
307 case 6: {
308 Dispatcher::Callback6 callback =
309 reinterpret_cast<Dispatcher::Callback6>(callback_generic);
310 if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
311 args[4], args[5]))
312 break;
313 error = false;
314 break;
316 case 7: {
317 Dispatcher::Callback7 callback =
318 reinterpret_cast<Dispatcher::Callback7>(callback_generic);
319 if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
320 args[4], args[5], args[6]))
321 break;
322 error = false;
323 break;
325 case 8: {
326 Dispatcher::Callback8 callback =
327 reinterpret_cast<Dispatcher::Callback8>(callback_generic);
328 if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
329 args[4], args[5], args[6], args[7]))
330 break;
331 error = false;
332 break;
334 case 9: {
335 Dispatcher::Callback9 callback =
336 reinterpret_cast<Dispatcher::Callback9>(callback_generic);
337 if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
338 args[4], args[5], args[6], args[7], args[8]))
339 break;
340 error = false;
341 break;
343 default: {
344 NOTREACHED();
345 break;
350 if (error) {
351 if (handler)
352 SetCallError(SBOX_ERROR_FAILED_IPC, call_result);
353 } else {
354 memcpy(call_result, &ipc_info.return_info, sizeof(*call_result));
355 SetCallSuccess(call_result);
356 if (params->IsInOut()) {
357 // Maybe the params got changed by the broker. We need to upadte the
358 // memory section.
359 memcpy(ipc_buffer, params.get(), output_size);
363 ReleaseArgs(&ipc_params, args);
365 return !error;
368 // This function gets called by a thread from the thread pool when a
369 // ping event fires. The context is the same as passed in the RegisterWait()
370 // call above.
371 void __stdcall SharedMemIPCServer::ThreadPingEventReady(void* context,
372 unsigned char) {
373 if (NULL == context) {
374 DCHECK(false);
375 return;
377 ServerControl* service_context = reinterpret_cast<ServerControl*>(context);
378 // Since the event fired, the channel *must* be busy. Change to kAckChannel
379 // while we service it.
380 LONG last_state =
381 ::InterlockedCompareExchange(&service_context->channel->state,
382 kAckChannel, kBusyChannel);
383 if (kBusyChannel != last_state) {
384 DCHECK(false);
385 return;
388 // Prepare the result structure. At this point we will return some result
389 // even if the IPC is invalid, malformed or has no handler.
390 CrossCallReturn call_result = {0};
391 void* buffer = service_context->channel_buffer;
393 InvokeCallback(service_context, buffer, &call_result);
395 // Copy the answer back into the channel and signal the pong event. This
396 // should wake up the client so he can finish the the ipc cycle.
397 CrossCallParams* call_params = reinterpret_cast<CrossCallParams*>(buffer);
398 memcpy(call_params->GetCallReturn(), &call_result, sizeof(call_result));
399 ::InterlockedExchange(&service_context->channel->state, kAckChannel);
400 ::SetEvent(service_context->pong_event);
403 bool SharedMemIPCServer::MakeEvents(HANDLE* server_ping, HANDLE* server_pong,
404 HANDLE* client_ping, HANDLE* client_pong) {
405 // Note that the IPC client has no right to delete the events. That would
406 // cause problems. The server *owns* the events.
407 const DWORD kDesiredAccess = SYNCHRONIZE | EVENT_MODIFY_STATE;
409 // The events are auto reset, and start not signaled.
410 *server_ping = ::CreateEventW(NULL, FALSE, FALSE, NULL);
411 if (!::DuplicateHandle(::GetCurrentProcess(), *server_ping, target_process_,
412 client_ping, kDesiredAccess, FALSE, 0)) {
413 return false;
415 *server_pong = ::CreateEventW(NULL, FALSE, FALSE, NULL);
416 if (!::DuplicateHandle(::GetCurrentProcess(), *server_pong, target_process_,
417 client_pong, kDesiredAccess, FALSE, 0)) {
418 return false;
420 return true;
423 } // namespace sandbox