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 "chrome/service/service_process.h"
9 #include "base/basictypes.h"
10 #include "base/callback.h"
11 #include "base/command_line.h"
12 #include "base/environment.h"
13 #include "base/i18n/rtl.h"
14 #include "base/location.h"
15 #include "base/memory/singleton.h"
16 #include "base/path_service.h"
17 #include "base/prefs/json_pref_store.h"
18 #include "base/single_thread_task_runner.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/thread_task_runner_handle.h"
22 #include "base/values.h"
23 #include "chrome/common/chrome_constants.h"
24 #include "chrome/common/chrome_paths.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/common/env_vars.h"
27 #include "chrome/common/pref_names.h"
28 #include "chrome/common/service_process_util.h"
29 #include "chrome/grit/chromium_strings.h"
30 #include "chrome/grit/generated_resources.h"
31 #include "chrome/service/cloud_print/cloud_print_proxy.h"
32 #include "chrome/service/net/service_url_request_context_getter.h"
33 #include "chrome/service/service_ipc_server.h"
34 #include "chrome/service/service_process_prefs.h"
35 #include "net/base/network_change_notifier.h"
36 #include "net/url_request/url_fetcher.h"
37 #include "ui/base/l10n/l10n_util.h"
38 #include "ui/base/resource/resource_bundle.h"
39 #include "ui/base/ui_base_switches.h"
42 #include <glib-object.h>
45 ServiceProcess
* g_service_process
= NULL
;
49 // Delay in seconds after the last service is disabled before we attempt
51 const int kShutdownDelaySeconds
= 60;
53 const char kDefaultServiceProcessLocale
[] = "en-US";
55 class ServiceIOThread
: public base::Thread
{
57 explicit ServiceIOThread(const char* name
);
58 ~ServiceIOThread() override
;
61 void CleanUp() override
;
64 DISALLOW_COPY_AND_ASSIGN(ServiceIOThread
);
67 ServiceIOThread::ServiceIOThread(const char* name
) : base::Thread(name
) {}
68 ServiceIOThread::~ServiceIOThread() {
72 void ServiceIOThread::CleanUp() {
73 net::URLFetcher::CancelAll();
76 // Prepares the localized strings that are going to be displayed to
77 // the user if the service process dies. These strings are stored in the
78 // environment block so they are accessible in the early stages of the
79 // chrome executable's lifetime.
80 void PrepareRestartOnCrashEnviroment(
81 const base::CommandLine
& parsed_command_line
) {
82 scoped_ptr
<base::Environment
> env(base::Environment::Create());
83 // Clear this var so child processes don't show the dialog by default.
84 env
->UnSetVar(env_vars::kShowRestart
);
86 // For non-interactive tests we don't restart on crash.
87 if (env
->HasVar(env_vars::kHeadless
))
90 // If the known command-line test options are used we don't create the
91 // environment block which means we don't get the restart dialog.
92 if (parsed_command_line
.HasSwitch(switches::kNoErrorDialogs
))
95 // The encoding we use for the info is "title|context|direction" where
96 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
97 // on the current locale.
98 base::string16
dlg_strings(
99 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE
));
100 dlg_strings
.push_back('|');
101 base::string16
adjusted_string(l10n_util::GetStringFUTF16(
102 IDS_SERVICE_CRASH_RECOVERY_CONTENT
,
103 l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT
)));
104 base::i18n::AdjustStringForLocaleDirection(&adjusted_string
);
105 dlg_strings
.append(adjusted_string
);
106 dlg_strings
.push_back('|');
107 dlg_strings
.append(base::ASCIIToUTF16(
108 base::i18n::IsRTL() ? env_vars::kRtlLocale
: env_vars::kLtrLocale
));
110 env
->SetVar(env_vars::kRestartInfo
, base::UTF16ToUTF8(dlg_strings
));
115 ServiceProcess::ServiceProcess()
116 : shutdown_event_(true, false),
117 main_message_loop_(NULL
),
118 enabled_services_(0),
119 update_available_(false) {
120 DCHECK(!g_service_process
);
121 g_service_process
= this;
124 bool ServiceProcess::Initialize(base::MessageLoopForUI
* message_loop
,
125 const base::CommandLine
& command_line
,
126 ServiceProcessState
* state
) {
127 #if defined(USE_GLIB)
128 // g_type_init has been deprecated since version 2.35.
129 #if !GLIB_CHECK_VERSION(2, 35, 0)
130 // GLib type system initialization is needed for gconf.
133 #endif // defined(OS_LINUX) || defined(OS_OPENBSD)
134 main_message_loop_
= message_loop
;
135 service_process_state_
.reset(state
);
136 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
137 base::Thread::Options options
;
138 options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
139 io_thread_
.reset(new ServiceIOThread("ServiceProcess_IO"));
140 file_thread_
.reset(new base::Thread("ServiceProcess_File"));
141 if (!io_thread_
->StartWithOptions(options
) ||
142 !file_thread_
->StartWithOptions(options
)) {
147 blocking_pool_
= new base::SequencedWorkerPool(3, "ServiceBlocking");
149 request_context_getter_
= new ServiceURLRequestContextGetter();
151 base::FilePath user_data_dir
;
152 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
153 base::FilePath pref_path
=
154 user_data_dir
.Append(chrome::kServiceStateFileName
);
155 service_prefs_
.reset(new ServiceProcessPrefs(
157 JsonPrefStore::GetTaskRunnerForFile(pref_path
, blocking_pool_
.get())
159 service_prefs_
->ReadPrefs();
161 // This switch it required to run connector with test gaia.
162 if (command_line
.HasSwitch(switches::kIgnoreUrlFetcherCertRequests
))
163 net::URLFetcher::SetIgnoreCertificateRequests(true);
165 // Check if a locale override has been specified on the command-line.
166 std::string locale
= command_line
.GetSwitchValueASCII(switches::kLang
);
167 if (!locale
.empty()) {
168 service_prefs_
->SetString(prefs::kApplicationLocale
, locale
);
169 service_prefs_
->WritePrefs();
171 // If no command-line value was specified, read the last used locale from
174 service_prefs_
->GetString(prefs::kApplicationLocale
, std::string());
175 // If no locale was specified anywhere, use the default one.
177 locale
= kDefaultServiceProcessLocale
;
179 ui::ResourceBundle::InitSharedInstanceWithLocale(
180 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
182 PrepareRestartOnCrashEnviroment(command_line
);
184 // Enable Cloud Print if needed. First check the command-line.
185 // Then check if the cloud print proxy was previously enabled.
186 if (command_line
.HasSwitch(switches::kEnableCloudPrintProxy
) ||
187 service_prefs_
->GetBoolean(prefs::kCloudPrintProxyEnabled
, false)) {
188 GetCloudPrintProxy()->EnableForUser();
191 VLOG(1) << "Starting Service Process IPC Server";
192 ipc_server_
.reset(new ServiceIPCServer(
193 service_process_state_
->GetServiceProcessChannel()));
196 // After the IPC server has started we signal that the service process is
198 if (!service_process_state_
->SignalReady(
199 io_thread_
->task_runner().get(),
200 base::Bind(&ServiceProcess::Terminate
, base::Unretained(this)))) {
204 // See if we need to stay running.
205 ScheduleShutdownCheck();
210 bool ServiceProcess::Teardown() {
211 service_prefs_
.reset();
212 cloud_print_proxy_
.reset();
215 // Signal this event before shutting down the service process. That way all
216 // background threads can cleanup.
217 shutdown_event_
.Signal();
219 file_thread_
.reset();
221 if (blocking_pool_
.get()) {
222 // The goal is to make it impossible for chrome to 'infinite loop' during
223 // shutdown, but to reasonably expect that all BLOCKING_SHUTDOWN tasks
224 // queued during shutdown get run. There's nothing particularly scientific
225 // about the number chosen.
226 const int kMaxNewShutdownBlockingTasks
= 1000;
227 blocking_pool_
->Shutdown(kMaxNewShutdownBlockingTasks
);
228 blocking_pool_
= NULL
;
231 // The NetworkChangeNotifier must be destroyed after all other threads that
232 // might use it have been shut down.
233 network_change_notifier_
.reset();
235 service_process_state_
->SignalStopped();
239 // This method is called when a shutdown command is received from IPC channel
240 // or there was an error in the IPC channel.
241 void ServiceProcess::Shutdown() {
242 #if defined(OS_MACOSX)
243 // On MacOS X the service must be removed from the launchd job list.
244 // http://www.chromium.org/developers/design-documents/service-processes
245 // The best way to do that is to go through the ForceServiceProcessShutdown
246 // path. If it succeeds Terminate() will be called from the handler registered
247 // via service_process_state_->SignalReady().
248 // On failure call Terminate() directly to force the process to actually
250 if (!ForceServiceProcessShutdown("", 0)) {
258 void ServiceProcess::Terminate() {
259 main_message_loop_
->task_runner()->PostTask(FROM_HERE
,
260 base::MessageLoop::QuitClosure());
263 bool ServiceProcess::HandleClientDisconnect() {
264 // If there are no enabled services or if there is an update available
265 // we want to shutdown right away. Else we want to keep listening for
267 if (!enabled_services_
|| update_available()) {
274 cloud_print::CloudPrintProxy
* ServiceProcess::GetCloudPrintProxy() {
275 if (!cloud_print_proxy_
.get()) {
276 cloud_print_proxy_
.reset(new cloud_print::CloudPrintProxy());
277 cloud_print_proxy_
->Initialize(service_prefs_
.get(), this);
279 return cloud_print_proxy_
.get();
282 void ServiceProcess::OnCloudPrintProxyEnabled(bool persist_state
) {
284 // Save the preference that we have enabled the cloud print proxy.
285 service_prefs_
->SetBoolean(prefs::kCloudPrintProxyEnabled
, true);
286 service_prefs_
->WritePrefs();
291 void ServiceProcess::OnCloudPrintProxyDisabled(bool persist_state
) {
293 // Save the preference that we have disabled the cloud print proxy.
294 service_prefs_
->SetBoolean(prefs::kCloudPrintProxyEnabled
, false);
295 service_prefs_
->WritePrefs();
300 ServiceURLRequestContextGetter
*
301 ServiceProcess::GetServiceURLRequestContextGetter() {
302 DCHECK(request_context_getter_
.get());
303 return request_context_getter_
.get();
306 void ServiceProcess::OnServiceEnabled() {
308 if ((1 == enabled_services_
) &&
309 !base::CommandLine::ForCurrentProcess()->HasSwitch(
310 switches::kNoServiceAutorun
)) {
311 if (!service_process_state_
->AddToAutoRun()) {
312 // TODO(scottbyer/sanjeevr/dmaclach): Handle error condition
313 LOG(ERROR
) << "Unable to AddToAutoRun";
318 void ServiceProcess::OnServiceDisabled() {
319 DCHECK_NE(enabled_services_
, 0);
321 if (0 == enabled_services_
) {
322 if (!service_process_state_
->RemoveFromAutoRun()) {
323 // TODO(scottbyer/sanjeevr/dmaclach): Handle error condition
324 LOG(ERROR
) << "Unable to RemoveFromAutoRun";
326 // We will wait for some time to respond to IPCs before shutting down.
327 ScheduleShutdownCheck();
331 void ServiceProcess::ScheduleShutdownCheck() {
332 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
334 base::Bind(&ServiceProcess::ShutdownIfNeeded
, base::Unretained(this)),
335 base::TimeDelta::FromSeconds(kShutdownDelaySeconds
));
338 void ServiceProcess::ShutdownIfNeeded() {
339 if (0 == enabled_services_
) {
340 if (ipc_server_
->is_client_connected()) {
341 // If there is a client connected, we need to try again later.
342 // Note that there is still a timing window here because a client may
343 // decide to connect at this point.
344 // TODO(sanjeevr): Fix this timing window.
345 ScheduleShutdownCheck();
352 ServiceProcess::~ServiceProcess() {
354 g_service_process
= NULL
;