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/memory/singleton.h"
15 #include "base/path_service.h"
16 #include "base/prefs/json_pref_store.h"
17 #include "base/strings/string16.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/values.h"
20 #include "chrome/common/chrome_constants.h"
21 #include "chrome/common/chrome_paths.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "chrome/common/env_vars.h"
24 #include "chrome/common/pref_names.h"
25 #include "chrome/common/service_process_util.h"
26 #include "chrome/grit/chromium_strings.h"
27 #include "chrome/grit/generated_resources.h"
28 #include "chrome/service/cloud_print/cloud_print_proxy.h"
29 #include "chrome/service/net/service_url_request_context_getter.h"
30 #include "chrome/service/service_ipc_server.h"
31 #include "chrome/service/service_process_prefs.h"
32 #include "net/base/network_change_notifier.h"
33 #include "net/url_request/url_fetcher.h"
34 #include "ui/base/l10n/l10n_util.h"
35 #include "ui/base/resource/resource_bundle.h"
36 #include "ui/base/ui_base_switches.h"
39 #include <glib-object.h>
42 ServiceProcess
* g_service_process
= NULL
;
46 // Delay in seconds after the last service is disabled before we attempt
48 const int kShutdownDelaySeconds
= 60;
50 const char kDefaultServiceProcessLocale
[] = "en-US";
52 class ServiceIOThread
: public base::Thread
{
54 explicit ServiceIOThread(const char* name
);
55 ~ServiceIOThread() override
;
58 void CleanUp() override
;
61 DISALLOW_COPY_AND_ASSIGN(ServiceIOThread
);
64 ServiceIOThread::ServiceIOThread(const char* name
) : base::Thread(name
) {}
65 ServiceIOThread::~ServiceIOThread() {
69 void ServiceIOThread::CleanUp() {
70 net::URLFetcher::CancelAll();
73 // Prepares the localized strings that are going to be displayed to
74 // the user if the service process dies. These strings are stored in the
75 // environment block so they are accessible in the early stages of the
76 // chrome executable's lifetime.
77 void PrepareRestartOnCrashEnviroment(
78 const base::CommandLine
& parsed_command_line
) {
79 scoped_ptr
<base::Environment
> env(base::Environment::Create());
80 // Clear this var so child processes don't show the dialog by default.
81 env
->UnSetVar(env_vars::kShowRestart
);
83 // For non-interactive tests we don't restart on crash.
84 if (env
->HasVar(env_vars::kHeadless
))
87 // If the known command-line test options are used we don't create the
88 // environment block which means we don't get the restart dialog.
89 if (parsed_command_line
.HasSwitch(switches::kNoErrorDialogs
))
92 // The encoding we use for the info is "title|context|direction" where
93 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
94 // on the current locale.
95 base::string16
dlg_strings(
96 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE
));
97 dlg_strings
.push_back('|');
98 base::string16
adjusted_string(l10n_util::GetStringFUTF16(
99 IDS_SERVICE_CRASH_RECOVERY_CONTENT
,
100 l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT
)));
101 base::i18n::AdjustStringForLocaleDirection(&adjusted_string
);
102 dlg_strings
.append(adjusted_string
);
103 dlg_strings
.push_back('|');
104 dlg_strings
.append(base::ASCIIToUTF16(
105 base::i18n::IsRTL() ? env_vars::kRtlLocale
: env_vars::kLtrLocale
));
107 env
->SetVar(env_vars::kRestartInfo
, base::UTF16ToUTF8(dlg_strings
));
112 ServiceProcess::ServiceProcess()
113 : shutdown_event_(true, false),
114 main_message_loop_(NULL
),
115 enabled_services_(0),
116 update_available_(false) {
117 DCHECK(!g_service_process
);
118 g_service_process
= this;
121 bool ServiceProcess::Initialize(base::MessageLoopForUI
* message_loop
,
122 const base::CommandLine
& command_line
,
123 ServiceProcessState
* state
) {
124 #if defined(USE_GLIB)
125 // g_type_init has been deprecated since version 2.35.
126 #if !GLIB_CHECK_VERSION(2, 35, 0)
127 // GLib type system initialization is needed for gconf.
130 #endif // defined(OS_LINUX) || defined(OS_OPENBSD)
131 main_message_loop_
= message_loop
;
132 service_process_state_
.reset(state
);
133 network_change_notifier_
.reset(net::NetworkChangeNotifier::Create());
134 base::Thread::Options options
;
135 options
.message_loop_type
= base::MessageLoop::TYPE_IO
;
136 io_thread_
.reset(new ServiceIOThread("ServiceProcess_IO"));
137 file_thread_
.reset(new base::Thread("ServiceProcess_File"));
138 if (!io_thread_
->StartWithOptions(options
) ||
139 !file_thread_
->StartWithOptions(options
)) {
144 blocking_pool_
= new base::SequencedWorkerPool(3, "ServiceBlocking");
146 request_context_getter_
= new ServiceURLRequestContextGetter();
148 base::FilePath user_data_dir
;
149 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
150 base::FilePath pref_path
=
151 user_data_dir
.Append(chrome::kServiceStateFileName
);
152 service_prefs_
.reset(new ServiceProcessPrefs(
154 JsonPrefStore::GetTaskRunnerForFile(pref_path
, blocking_pool_
.get())
156 service_prefs_
->ReadPrefs();
158 // This switch it required to run connector with test gaia.
159 if (command_line
.HasSwitch(switches::kIgnoreUrlFetcherCertRequests
))
160 net::URLFetcher::SetIgnoreCertificateRequests(true);
162 // Check if a locale override has been specified on the command-line.
163 std::string locale
= command_line
.GetSwitchValueASCII(switches::kLang
);
164 if (!locale
.empty()) {
165 service_prefs_
->SetString(prefs::kApplicationLocale
, locale
);
166 service_prefs_
->WritePrefs();
168 // If no command-line value was specified, read the last used locale from
171 service_prefs_
->GetString(prefs::kApplicationLocale
, std::string());
172 // If no locale was specified anywhere, use the default one.
174 locale
= kDefaultServiceProcessLocale
;
176 ui::ResourceBundle::InitSharedInstanceWithLocale(
177 locale
, NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
179 PrepareRestartOnCrashEnviroment(command_line
);
181 // Enable Cloud Print if needed. First check the command-line.
182 // Then check if the cloud print proxy was previously enabled.
183 if (command_line
.HasSwitch(switches::kEnableCloudPrintProxy
) ||
184 service_prefs_
->GetBoolean(prefs::kCloudPrintProxyEnabled
, false)) {
185 GetCloudPrintProxy()->EnableForUser();
188 VLOG(1) << "Starting Service Process IPC Server";
189 ipc_server_
.reset(new ServiceIPCServer(
190 service_process_state_
->GetServiceProcessChannel()));
193 // After the IPC server has started we signal that the service process is
195 if (!service_process_state_
->SignalReady(
196 io_thread_
->message_loop_proxy().get(),
197 base::Bind(&ServiceProcess::Terminate
, base::Unretained(this)))) {
201 // See if we need to stay running.
202 ScheduleShutdownCheck();
207 bool ServiceProcess::Teardown() {
208 service_prefs_
.reset();
209 cloud_print_proxy_
.reset();
212 // Signal this event before shutting down the service process. That way all
213 // background threads can cleanup.
214 shutdown_event_
.Signal();
216 file_thread_
.reset();
218 if (blocking_pool_
.get()) {
219 // The goal is to make it impossible for chrome to 'infinite loop' during
220 // shutdown, but to reasonably expect that all BLOCKING_SHUTDOWN tasks
221 // queued during shutdown get run. There's nothing particularly scientific
222 // about the number chosen.
223 const int kMaxNewShutdownBlockingTasks
= 1000;
224 blocking_pool_
->Shutdown(kMaxNewShutdownBlockingTasks
);
225 blocking_pool_
= NULL
;
228 // The NetworkChangeNotifier must be destroyed after all other threads that
229 // might use it have been shut down.
230 network_change_notifier_
.reset();
232 service_process_state_
->SignalStopped();
236 // This method is called when a shutdown command is received from IPC channel
237 // or there was an error in the IPC channel.
238 void ServiceProcess::Shutdown() {
239 #if defined(OS_MACOSX)
240 // On MacOS X the service must be removed from the launchd job list.
241 // http://www.chromium.org/developers/design-documents/service-processes
242 // The best way to do that is to go through the ForceServiceProcessShutdown
243 // path. If it succeeds Terminate() will be called from the handler registered
244 // via service_process_state_->SignalReady().
245 // On failure call Terminate() directly to force the process to actually
247 if (!ForceServiceProcessShutdown("", 0)) {
255 void ServiceProcess::Terminate() {
256 main_message_loop_
->PostTask(FROM_HERE
, base::MessageLoop::QuitClosure());
259 bool ServiceProcess::HandleClientDisconnect() {
260 // If there are no enabled services or if there is an update available
261 // we want to shutdown right away. Else we want to keep listening for
263 if (!enabled_services_
|| update_available()) {
270 cloud_print::CloudPrintProxy
* ServiceProcess::GetCloudPrintProxy() {
271 if (!cloud_print_proxy_
.get()) {
272 cloud_print_proxy_
.reset(new cloud_print::CloudPrintProxy());
273 cloud_print_proxy_
->Initialize(service_prefs_
.get(), this);
275 return cloud_print_proxy_
.get();
278 void ServiceProcess::OnCloudPrintProxyEnabled(bool persist_state
) {
280 // Save the preference that we have enabled the cloud print proxy.
281 service_prefs_
->SetBoolean(prefs::kCloudPrintProxyEnabled
, true);
282 service_prefs_
->WritePrefs();
287 void ServiceProcess::OnCloudPrintProxyDisabled(bool persist_state
) {
289 // Save the preference that we have disabled the cloud print proxy.
290 service_prefs_
->SetBoolean(prefs::kCloudPrintProxyEnabled
, false);
291 service_prefs_
->WritePrefs();
296 ServiceURLRequestContextGetter
*
297 ServiceProcess::GetServiceURLRequestContextGetter() {
298 DCHECK(request_context_getter_
.get());
299 return request_context_getter_
.get();
302 void ServiceProcess::OnServiceEnabled() {
304 if ((1 == enabled_services_
) &&
305 !base::CommandLine::ForCurrentProcess()->HasSwitch(
306 switches::kNoServiceAutorun
)) {
307 if (!service_process_state_
->AddToAutoRun()) {
308 // TODO(scottbyer/sanjeevr/dmaclach): Handle error condition
309 LOG(ERROR
) << "Unable to AddToAutoRun";
314 void ServiceProcess::OnServiceDisabled() {
315 DCHECK_NE(enabled_services_
, 0);
317 if (0 == enabled_services_
) {
318 if (!service_process_state_
->RemoveFromAutoRun()) {
319 // TODO(scottbyer/sanjeevr/dmaclach): Handle error condition
320 LOG(ERROR
) << "Unable to RemoveFromAutoRun";
322 // We will wait for some time to respond to IPCs before shutting down.
323 ScheduleShutdownCheck();
327 void ServiceProcess::ScheduleShutdownCheck() {
328 base::MessageLoop::current()->PostDelayedTask(
330 base::Bind(&ServiceProcess::ShutdownIfNeeded
, base::Unretained(this)),
331 base::TimeDelta::FromSeconds(kShutdownDelaySeconds
));
334 void ServiceProcess::ShutdownIfNeeded() {
335 if (0 == enabled_services_
) {
336 if (ipc_server_
->is_client_connected()) {
337 // If there is a client connected, we need to try again later.
338 // Note that there is still a timing window here because a client may
339 // decide to connect at this point.
340 // TODO(sanjeevr): Fix this timing window.
341 ScheduleShutdownCheck();
348 ServiceProcess::~ServiceProcess() {
350 g_service_process
= NULL
;