Removed unused VideoCaptureCapability parameters.
[chromium-blink-merge.git] / content / zygote / zygote_main_linux.cc
blob567b3055ccc4dbb9938db0fe0733ee217b76b9b7
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 "content/zygote/zygote_main.h"
7 #include <dlfcn.h>
8 #include <fcntl.h>
9 #include <pthread.h>
10 #include <stdio.h>
11 #include <sys/socket.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <sys/wait.h>
15 #include <unistd.h>
17 #include "base/basictypes.h"
18 #include "base/command_line.h"
19 #include "base/linux_util.h"
20 #include "base/native_library.h"
21 #include "base/pickle.h"
22 #include "base/posix/eintr_wrapper.h"
23 #include "base/posix/unix_domain_socket_linux.h"
24 #include "base/rand_util.h"
25 #include "base/sys_info.h"
26 #include "build/build_config.h"
27 #include "content/common/child_process_sandbox_support_impl_linux.h"
28 #include "content/common/font_config_ipc_linux.h"
29 #include "content/common/pepper_plugin_list.h"
30 #include "content/common/sandbox_linux.h"
31 #include "content/common/zygote_commands_linux.h"
32 #include "content/public/common/content_switches.h"
33 #include "content/public/common/main_function_params.h"
34 #include "content/public/common/pepper_plugin_info.h"
35 #include "content/public/common/sandbox_linux.h"
36 #include "content/public/common/zygote_fork_delegate_linux.h"
37 #include "content/zygote/zygote_linux.h"
38 #include "crypto/nss_util.h"
39 #include "sandbox/linux/services/libc_urandom_override.h"
40 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
41 #include "third_party/icu/source/i18n/unicode/timezone.h"
42 #include "third_party/skia/include/ports/SkFontConfigInterface.h"
44 #if defined(OS_LINUX)
45 #include <sys/epoll.h>
46 #include <sys/prctl.h>
47 #include <sys/signal.h>
48 #else
49 #include <signal.h>
50 #endif
52 #if defined(ENABLE_WEBRTC)
53 #include "third_party/libjingle/overrides/init_webrtc.h"
54 #endif
56 namespace content {
58 // See http://code.google.com/p/chromium/wiki/LinuxZygote
60 static void ProxyLocaltimeCallToBrowser(time_t input, struct tm* output,
61 char* timezone_out,
62 size_t timezone_out_len) {
63 Pickle request;
64 request.WriteInt(LinuxSandbox::METHOD_LOCALTIME);
65 request.WriteString(
66 std::string(reinterpret_cast<char*>(&input), sizeof(input)));
68 uint8_t reply_buf[512];
69 const ssize_t r = UnixDomainSocket::SendRecvMsg(
70 GetSandboxFD(), reply_buf, sizeof(reply_buf), NULL,
71 request);
72 if (r == -1) {
73 memset(output, 0, sizeof(struct tm));
74 return;
77 Pickle reply(reinterpret_cast<char*>(reply_buf), r);
78 PickleIterator iter(reply);
79 std::string result, timezone;
80 if (!reply.ReadString(&iter, &result) ||
81 !reply.ReadString(&iter, &timezone) ||
82 result.size() != sizeof(struct tm)) {
83 memset(output, 0, sizeof(struct tm));
84 return;
87 memcpy(output, result.data(), sizeof(struct tm));
88 if (timezone_out_len) {
89 const size_t copy_len = std::min(timezone_out_len - 1, timezone.size());
90 memcpy(timezone_out, timezone.data(), copy_len);
91 timezone_out[copy_len] = 0;
92 output->tm_zone = timezone_out;
93 } else {
94 output->tm_zone = NULL;
98 static bool g_am_zygote_or_renderer = false;
100 // Sandbox interception of libc calls.
102 // Because we are running in a sandbox certain libc calls will fail (localtime
103 // being the motivating example - it needs to read /etc/localtime). We need to
104 // intercept these calls and proxy them to the browser. However, these calls
105 // may come from us or from our libraries. In some cases we can't just change
106 // our code.
108 // It's for these cases that we have the following setup:
110 // We define global functions for those functions which we wish to override.
111 // Since we will be first in the dynamic resolution order, the dynamic linker
112 // will point callers to our versions of these functions. However, we have the
113 // same binary for both the browser and the renderers, which means that our
114 // overrides will apply in the browser too.
116 // The global |g_am_zygote_or_renderer| is true iff we are in a zygote or
117 // renderer process. It's set in ZygoteMain and inherited by the renderers when
118 // they fork. (This means that it'll be incorrect for global constructor
119 // functions and before ZygoteMain is called - beware).
121 // Our replacement functions can check this global and either proxy
122 // the call to the browser over the sandbox IPC
123 // (http://code.google.com/p/chromium/wiki/LinuxSandboxIPC) or they can use
124 // dlsym with RTLD_NEXT to resolve the symbol, ignoring any symbols in the
125 // current module.
127 // Other avenues:
129 // Our first attempt involved some assembly to patch the GOT of the current
130 // module. This worked, but was platform specific and doesn't catch the case
131 // where a library makes a call rather than current module.
133 // We also considered patching the function in place, but this would again by
134 // platform specific and the above technique seems to work well enough.
136 typedef struct tm* (*LocaltimeFunction)(const time_t* timep);
137 typedef struct tm* (*LocaltimeRFunction)(const time_t* timep,
138 struct tm* result);
140 static pthread_once_t g_libc_localtime_funcs_guard = PTHREAD_ONCE_INIT;
141 static LocaltimeFunction g_libc_localtime;
142 static LocaltimeFunction g_libc_localtime64;
143 static LocaltimeRFunction g_libc_localtime_r;
144 static LocaltimeRFunction g_libc_localtime64_r;
146 static void InitLibcLocaltimeFunctions() {
147 g_libc_localtime = reinterpret_cast<LocaltimeFunction>(
148 dlsym(RTLD_NEXT, "localtime"));
149 g_libc_localtime64 = reinterpret_cast<LocaltimeFunction>(
150 dlsym(RTLD_NEXT, "localtime64"));
151 g_libc_localtime_r = reinterpret_cast<LocaltimeRFunction>(
152 dlsym(RTLD_NEXT, "localtime_r"));
153 g_libc_localtime64_r = reinterpret_cast<LocaltimeRFunction>(
154 dlsym(RTLD_NEXT, "localtime64_r"));
156 if (!g_libc_localtime || !g_libc_localtime_r) {
157 // http://code.google.com/p/chromium/issues/detail?id=16800
159 // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces
160 // it with a version which doesn't work. In this case we'll get a NULL
161 // result. There's not a lot we can do at this point, so we just bodge it!
162 LOG(ERROR) << "Your system is broken: dlsym doesn't work! This has been "
163 "reported to be caused by Nvidia's libGL. You should expect"
164 " time related functions to misbehave. "
165 "http://code.google.com/p/chromium/issues/detail?id=16800";
168 if (!g_libc_localtime)
169 g_libc_localtime = gmtime;
170 if (!g_libc_localtime64)
171 g_libc_localtime64 = g_libc_localtime;
172 if (!g_libc_localtime_r)
173 g_libc_localtime_r = gmtime_r;
174 if (!g_libc_localtime64_r)
175 g_libc_localtime64_r = g_libc_localtime_r;
178 // Define localtime_override() function with asm name "localtime", so that all
179 // references to localtime() will resolve to this function. Notice that we need
180 // to set visibility attribute to "default" to export the symbol, as it is set
181 // to "hidden" by default in chrome per build/common.gypi.
182 __attribute__ ((__visibility__("default")))
183 struct tm* localtime_override(const time_t* timep) __asm__ ("localtime");
185 __attribute__ ((__visibility__("default")))
186 struct tm* localtime_override(const time_t* timep) {
187 if (g_am_zygote_or_renderer) {
188 static struct tm time_struct;
189 static char timezone_string[64];
190 ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string,
191 sizeof(timezone_string));
192 return &time_struct;
193 } else {
194 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
195 InitLibcLocaltimeFunctions));
196 return g_libc_localtime(timep);
200 // Use same trick to override localtime64(), localtime_r() and localtime64_r().
201 __attribute__ ((__visibility__("default")))
202 struct tm* localtime64_override(const time_t* timep) __asm__ ("localtime64");
204 __attribute__ ((__visibility__("default")))
205 struct tm* localtime64_override(const time_t* timep) {
206 if (g_am_zygote_or_renderer) {
207 static struct tm time_struct;
208 static char timezone_string[64];
209 ProxyLocaltimeCallToBrowser(*timep, &time_struct, timezone_string,
210 sizeof(timezone_string));
211 return &time_struct;
212 } else {
213 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
214 InitLibcLocaltimeFunctions));
215 return g_libc_localtime64(timep);
219 __attribute__ ((__visibility__("default")))
220 struct tm* localtime_r_override(const time_t* timep,
221 struct tm* result) __asm__ ("localtime_r");
223 __attribute__ ((__visibility__("default")))
224 struct tm* localtime_r_override(const time_t* timep, struct tm* result) {
225 if (g_am_zygote_or_renderer) {
226 ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0);
227 return result;
228 } else {
229 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
230 InitLibcLocaltimeFunctions));
231 return g_libc_localtime_r(timep, result);
235 __attribute__ ((__visibility__("default")))
236 struct tm* localtime64_r_override(const time_t* timep,
237 struct tm* result) __asm__ ("localtime64_r");
239 __attribute__ ((__visibility__("default")))
240 struct tm* localtime64_r_override(const time_t* timep, struct tm* result) {
241 if (g_am_zygote_or_renderer) {
242 ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0);
243 return result;
244 } else {
245 CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard,
246 InitLibcLocaltimeFunctions));
247 return g_libc_localtime64_r(timep, result);
251 #if defined(ENABLE_PLUGINS)
252 // Loads the (native) libraries but does not initialize them (i.e., does not
253 // call PPP_InitializeModule). This is needed by the zygote on Linux to get
254 // access to the plugins before entering the sandbox.
255 void PreloadPepperPlugins() {
256 std::vector<PepperPluginInfo> plugins;
257 ComputePepperPluginList(&plugins);
258 for (size_t i = 0; i < plugins.size(); ++i) {
259 if (!plugins[i].is_internal && plugins[i].is_sandboxed) {
260 std::string error;
261 base::NativeLibrary library = base::LoadNativeLibrary(plugins[i].path,
262 &error);
263 DLOG_IF(WARNING, !library) << "Unable to load plugin "
264 << plugins[i].path.value() << " "
265 << error;
266 (void)library; // Prevent release-mode warning.
270 #endif
272 // This function triggers the static and lazy construction of objects that need
273 // to be created before imposing the sandbox.
274 static void PreSandboxInit() {
275 base::RandUint64();
277 base::SysInfo::MaxSharedMemorySize();
279 // ICU DateFormat class (used in base/time_format.cc) needs to get the
280 // Olson timezone ID by accessing the zoneinfo files on disk. After
281 // TimeZone::createDefault is called once here, the timezone ID is
282 // cached and there's no more need to access the file system.
283 scoped_ptr<icu::TimeZone> zone(icu::TimeZone::createDefault());
285 #if defined(USE_NSS)
286 // NSS libraries are loaded before sandbox is activated. This is to allow
287 // successful initialization of NSS which tries to load extra library files.
288 crypto::LoadNSSLibraries();
289 #elif defined(USE_OPENSSL)
290 // OpenSSL is intentionally not supported in the sandboxed processes, see
291 // http://crbug.com/99163. If that ever changes we'll likely need to init
292 // OpenSSL here (at least, load the library and error strings).
293 #else
294 // It's possible that another hypothetical crypto stack would not require
295 // pre-sandbox init, but more likely this is just a build configuration error.
296 #error Which SSL library are you using?
297 #endif
298 #if defined(ENABLE_PLUGINS)
299 // Ensure access to the Pepper plugins before the sandbox is turned on.
300 PreloadPepperPlugins();
301 #endif
302 #if defined(ENABLE_WEBRTC)
303 InitializeWebRtcModule();
304 #endif
305 SkFontConfigInterface::SetGlobal(
306 new FontConfigIPC(GetSandboxFD()))->unref();
309 // Do nothing here
310 static void SIGCHLDHandler(int signal) {
313 // The current process will become a process reaper like init.
314 // We fork a child that will continue normally, when it dies, we can safely
315 // exit.
316 // We need to be careful we close the magic kZygoteIdFd properly in the parent
317 // before this function returns.
318 static bool CreateInitProcessReaper() {
319 int sync_fds[2];
320 // We want to use send, so we can't use a pipe
321 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sync_fds)) {
322 LOG(ERROR) << "Failed to create socketpair";
323 return false;
326 // We use normal fork, not the ForkDelegate in this case since we are not a
327 // true Zygote yet.
328 pid_t child_pid = fork();
329 if (child_pid == -1) {
330 (void) HANDLE_EINTR(close(sync_fds[0]));
331 (void) HANDLE_EINTR(close(sync_fds[1]));
332 return false;
334 if (child_pid) {
335 // We are the parent, assuming the role of an init process.
336 // The disposition for SIGCHLD cannot be SIG_IGN or wait() will only return
337 // once all of our childs are dead. Since we're init we need to reap childs
338 // as they come.
339 struct sigaction action;
340 memset(&action, 0, sizeof(action));
341 action.sa_handler = &SIGCHLDHandler;
342 CHECK(sigaction(SIGCHLD, &action, NULL) == 0);
344 (void) HANDLE_EINTR(close(sync_fds[0]));
345 shutdown(sync_fds[1], SHUT_RD);
346 // This "magic" socket must only appear in one process.
347 (void) HANDLE_EINTR(close(kZygoteIdFd));
348 // Tell the child to continue
349 CHECK(HANDLE_EINTR(send(sync_fds[1], "C", 1, MSG_NOSIGNAL)) == 1);
350 (void) HANDLE_EINTR(close(sync_fds[1]));
352 for (;;) {
353 // Loop until we have reaped our one natural child
354 siginfo_t reaped_child_info;
355 int wait_ret =
356 HANDLE_EINTR(waitid(P_ALL, 0, &reaped_child_info, WEXITED));
357 if (wait_ret)
358 _exit(1);
359 if (reaped_child_info.si_pid == child_pid) {
360 int exit_code = 0;
361 // We're done waiting
362 if (reaped_child_info.si_code == CLD_EXITED) {
363 exit_code = reaped_child_info.si_status;
365 // Exit with the same exit code as our parent. This is most likely
366 // useless. _exit with 0 if we got signaled.
367 _exit(exit_code);
370 } else {
371 // The child needs to wait for the parent to close kZygoteIdFd to avoid a
372 // race condition
373 (void) HANDLE_EINTR(close(sync_fds[1]));
374 shutdown(sync_fds[0], SHUT_WR);
375 char should_continue;
376 int read_ret = HANDLE_EINTR(read(sync_fds[0], &should_continue, 1));
377 (void) HANDLE_EINTR(close(sync_fds[0]));
378 if (read_ret == 1)
379 return true;
380 else
381 return false;
385 // This will set the *using_suid_sandbox variable to true if the SUID sandbox
386 // is enabled. This does not necessarily exclude other types of sandboxing.
387 static bool EnterSuidSandbox(LinuxSandbox* linux_sandbox,
388 bool* using_suid_sandbox,
389 bool* has_started_new_init) {
390 *using_suid_sandbox = false;
391 *has_started_new_init = false;
393 sandbox::SetuidSandboxClient* setuid_sandbox =
394 linux_sandbox->setuid_sandbox_client();
396 if (!setuid_sandbox)
397 return false;
399 PreSandboxInit();
401 // Check that the pre-sandbox initialization didn't spawn threads.
402 DCHECK(linux_sandbox->IsSingleThreaded());
404 if (setuid_sandbox->IsSuidSandboxChild()) {
405 // Use the SUID sandbox. This still allows the seccomp sandbox to
406 // be enabled by the process later.
407 *using_suid_sandbox = true;
409 if (!setuid_sandbox->IsSuidSandboxUpToDate()) {
410 LOG(WARNING) << "You are using a wrong version of the setuid binary!\n"
411 "Please read "
412 "https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment."
413 "\n\n";
416 if (!setuid_sandbox->ChrootMe())
417 return false;
419 if (getpid() == 1) {
420 // The setuid sandbox has created a new PID namespace and we need
421 // to assume the role of init.
422 if (!CreateInitProcessReaper()) {
423 LOG(ERROR) << "Error creating an init process to reap zombies";
424 return false;
426 *has_started_new_init = true;
429 #if !defined(OS_OPENBSD)
430 // Previously, we required that the binary be non-readable. This causes the
431 // kernel to mark the process as non-dumpable at startup. The thinking was
432 // that, although we were putting the renderers into a PID namespace (with
433 // the SUID sandbox), they would nonetheless be in the /same/ PID
434 // namespace. So they could ptrace each other unless they were non-dumpable.
436 // If the binary was readable, then there would be a window between process
437 // startup and the point where we set the non-dumpable flag in which a
438 // compromised renderer could ptrace attach.
440 // However, now that we have a zygote model, only the (trusted) zygote
441 // exists at this point and we can set the non-dumpable flag which is
442 // inherited by all our renderer children.
444 // Note: a non-dumpable process can't be debugged. To debug sandbox-related
445 // issues, one can specify --allow-sandbox-debugging to let the process be
446 // dumpable.
447 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
448 if (!command_line.HasSwitch(switches::kAllowSandboxDebugging)) {
449 prctl(PR_SET_DUMPABLE, 0, 0, 0, 0);
450 if (prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) {
451 LOG(ERROR) << "Failed to set non-dumpable flag";
452 return false;
455 #endif
458 return true;
461 bool ZygoteMain(const MainFunctionParams& params,
462 ZygoteForkDelegate* forkdelegate) {
463 g_am_zygote_or_renderer = true;
464 sandbox::InitLibcUrandomOverrides();
466 LinuxSandbox* linux_sandbox = LinuxSandbox::GetInstance();
467 // This will pre-initialize the various sandboxes that need it.
468 linux_sandbox->PreinitializeSandbox();
470 if (forkdelegate != NULL) {
471 VLOG(1) << "ZygoteMain: initializing fork delegate";
472 forkdelegate->Init(GetSandboxFD());
473 } else {
474 VLOG(1) << "ZygoteMain: fork delegate is NULL";
477 // Turn on the sandbox.
478 bool using_suid_sandbox = false;
479 bool has_started_new_init = false;
481 if (!EnterSuidSandbox(linux_sandbox,
482 &using_suid_sandbox,
483 &has_started_new_init)) {
484 LOG(FATAL) << "Failed to enter sandbox. Fail safe abort. (errno: "
485 << errno << ")";
486 return false;
489 sandbox::SetuidSandboxClient* setuid_sandbox =
490 linux_sandbox->setuid_sandbox_client();
492 if (setuid_sandbox->IsInNewPIDNamespace() && !has_started_new_init) {
493 LOG(ERROR) << "The SUID sandbox created a new PID namespace but Zygote "
494 "is not the init process. Please, make sure the SUID "
495 "binary is up to date.";
498 int sandbox_flags = linux_sandbox->GetStatus();
500 Zygote zygote(sandbox_flags, forkdelegate);
501 // This function call can return multiple times, once per fork().
502 return zygote.ProcessRequests();
505 } // namespace content