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/browser/browser_process_impl.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/debug/alias.h"
15 #include "base/debug/leak_annotations.h"
16 #include "base/path_service.h"
17 #include "base/prefs/json_pref_store.h"
18 #include "base/prefs/pref_registry_simple.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/synchronization/waitable_event.h"
21 #include "base/threading/thread.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "chrome/browser/apps/chrome_apps_client.h"
24 #include "chrome/browser/automation/automation_provider_list.h"
25 #include "chrome/browser/background/background_mode_manager.h"
26 #include "chrome/browser/chrome_browser_main.h"
27 #include "chrome/browser/chrome_content_browser_client.h"
28 #include "chrome/browser/chrome_notification_types.h"
29 #include "chrome/browser/component_updater/component_updater_configurator.h"
30 #include "chrome/browser/component_updater/component_updater_service.h"
31 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
32 #include "chrome/browser/defaults.h"
33 #include "chrome/browser/devtools/remote_debugging_server.h"
34 #include "chrome/browser/download/download_request_limiter.h"
35 #include "chrome/browser/download/download_status_updater.h"
36 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
37 #include "chrome/browser/extensions/event_router_forwarder.h"
38 #include "chrome/browser/extensions/extension_renderer_state.h"
39 #include "chrome/browser/first_run/upgrade_util.h"
40 #include "chrome/browser/gpu/gl_string_manager.h"
41 #include "chrome/browser/gpu/gpu_mode_manager.h"
42 #include "chrome/browser/icon_manager.h"
43 #include "chrome/browser/idle.h"
44 #include "chrome/browser/intranet_redirect_detector.h"
45 #include "chrome/browser/io_thread.h"
46 #include "chrome/browser/lifetime/application_lifetime.h"
47 #include "chrome/browser/metrics/metrics_service.h"
48 #include "chrome/browser/metrics/thread_watcher.h"
49 #include "chrome/browser/metrics/variations/variations_service.h"
50 #include "chrome/browser/net/chrome_net_log.h"
51 #include "chrome/browser/net/crl_set_fetcher.h"
52 #include "chrome/browser/net/sdch_dictionary_fetcher.h"
53 #include "chrome/browser/notifications/notification_ui_manager.h"
54 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
55 #include "chrome/browser/plugins/plugin_finder.h"
56 #include "chrome/browser/prefs/browser_prefs.h"
57 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
58 #include "chrome/browser/prerender/prerender_tracker.h"
59 #include "chrome/browser/printing/background_printing_manager.h"
60 #include "chrome/browser/printing/print_job_manager.h"
61 #include "chrome/browser/printing/print_preview_dialog_controller.h"
62 #include "chrome/browser/profiles/profile_manager.h"
63 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
64 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
65 #include "chrome/browser/shell_integration.h"
66 #include "chrome/browser/status_icons/status_tray.h"
67 #include "chrome/browser/ui/bookmarks/bookmark_prompt_controller.h"
68 #include "chrome/browser/ui/browser_dialogs.h"
69 #include "chrome/browser/ui/browser_finder.h"
70 #include "chrome/browser/web_resource/promo_resource_service.h"
71 #include "chrome/common/chrome_constants.h"
72 #include "chrome/common/chrome_paths.h"
73 #include "chrome/common/chrome_switches.h"
74 #include "chrome/common/extensions/chrome_extensions_client.h"
75 #include "chrome/common/extensions/extension_l10n_util.h"
76 #include "chrome/common/pref_names.h"
77 #include "chrome/common/profile_management_switches.h"
78 #include "chrome/common/switch_utils.h"
79 #include "chrome/common/url_constants.h"
80 #include "chrome/installer/util/google_update_constants.h"
81 #include "components/policy/core/common/policy_service.h"
82 #include "components/translate/core/browser/translate_download_manager.h"
83 #include "content/public/browser/browser_thread.h"
84 #include "content/public/browser/child_process_security_policy.h"
85 #include "content/public/browser/notification_details.h"
86 #include "content/public/browser/plugin_service.h"
87 #include "content/public/browser/render_process_host.h"
88 #include "content/public/browser/resource_dispatcher_host.h"
89 #include "extensions/common/constants.h"
90 #include "net/socket/client_socket_pool_manager.h"
91 #include "net/url_request/url_request_context_getter.h"
92 #include "ui/base/l10n/l10n_util.h"
93 #include "ui/message_center/message_center.h"
95 #if defined(ENABLE_CONFIGURATION_POLICY)
96 #include "components/policy/core/browser/browser_policy_connector.h"
98 #include "components/policy/core/common/policy_service_stub.h"
99 #endif // defined(ENABLE_CONFIGURATION_POLICY)
102 #include "base/win/windows_version.h"
103 #include "ui/views/focus/view_storage.h"
104 #elif defined(OS_MACOSX)
105 #include "chrome/browser/chrome_browser_main_mac.h"
108 #if defined(USE_AURA)
109 #include "ui/aura/env.h"
112 #if !defined(OS_ANDROID) && !defined(OS_IOS)
113 #include "chrome/browser/media_galleries/media_file_system_registry.h"
114 #include "components/storage_monitor/storage_monitor.h"
117 #if defined(ENABLE_PLUGIN_INSTALLATION)
118 #include "chrome/browser/plugins/plugins_resource_service.h"
121 #if defined(ENABLE_WEBRTC)
122 #include "chrome/browser/media/webrtc_log_uploader.h"
125 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
126 // How often to check if the persistent instance of Chrome needs to restart
127 // to install an update.
128 static const int kUpdateCheckIntervalHours = 6;
132 // Attest to the fact that the call to the file thread to save preferences has
133 // run, and it is safe to terminate. This avoids the potential of some other
134 // task prematurely terminating our waiting message loop by posting a
136 static bool g_end_session_file_thread_has_completed = false;
140 // How long to wait for the File thread to complete during EndSession, on
141 // Linux. We have a timeout here because we're unable to run the UI messageloop
142 // and there's some deadlock risk. Our only option is to exit anyway.
143 static const int kEndSessionTimeoutSeconds = 10;
146 using content::BrowserThread;
147 using content::ChildProcessSecurityPolicy;
148 using content::PluginService;
149 using content::ResourceDispatcherHost;
151 BrowserProcessImpl::BrowserProcessImpl(
152 base::SequencedTaskRunner* local_state_task_runner,
153 const CommandLine& command_line)
154 : created_metrics_service_(false),
155 created_watchdog_thread_(false),
156 created_browser_policy_connector_(false),
157 created_profile_manager_(false),
158 created_local_state_(false),
159 created_icon_manager_(false),
160 created_notification_ui_manager_(false),
161 created_safe_browsing_service_(false),
162 module_ref_count_(0),
164 download_status_updater_(new DownloadStatusUpdater),
165 local_state_task_runner_(local_state_task_runner) {
166 g_browser_process = this;
167 platform_part_.reset(new BrowserProcessPlatformPart());
169 #if defined(ENABLE_PRINTING)
170 // Must be created after the NotificationService.
171 print_job_manager_.reset(new printing::PrintJobManager);
174 net_log_.reset(new ChromeNetLog);
176 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
177 extensions::kExtensionScheme);
178 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
179 extensions::kExtensionResourceScheme);
180 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
181 chrome::kChromeSearchScheme);
183 #if defined(OS_MACOSX)
187 apps::AppsClient::Set(ChromeAppsClient::GetInstance());
188 extensions::ExtensionsClient::Set(
189 extensions::ChromeExtensionsClient::GetInstance());
191 extensions_browser_client_.reset(
192 new extensions::ChromeExtensionsBrowserClient);
193 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
195 extension_event_router_forwarder_ = new extensions::EventRouterForwarder;
196 ExtensionRendererState::GetInstance()->Init();
198 message_center::MessageCenter::Initialize();
201 BrowserProcessImpl::~BrowserProcessImpl() {
202 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
204 g_browser_process = NULL;
207 void BrowserProcessImpl::StartTearDown() {
208 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
209 #if defined(ENABLE_AUTOMATION)
210 // Delete the AutomationProviderList before NotificationService,
211 // since it may try to unregister notifications
212 // Both NotificationService and AutomationProvider are singleton instances in
213 // the BrowserProcess. Since AutomationProvider may have some active
214 // notification observers, it is essential that it gets destroyed before the
215 // NotificationService. NotificationService won't be destroyed until after
216 // this destructor is run.
217 automation_provider_list_.reset();
220 // We need to shutdown the SdchDictionaryFetcher as it regularly holds
221 // a pointer to a URLFetcher, and that URLFetcher (upon destruction) will do
222 // a PostDelayedTask onto the IO thread. This shutdown call will both discard
223 // any pending URLFetchers, and avoid creating any more.
224 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
225 base::Bind(&SdchDictionaryFetcher::Shutdown));
227 // We need to destroy the MetricsService, VariationsService,
228 // IntranetRedirectDetector, PromoResourceService, and SafeBrowsing
229 // ClientSideDetectionService (owned by the SafeBrowsingService) before the
230 // io_thread_ gets destroyed, since their destructors can call the URLFetcher
231 // destructor, which does a PostDelayedTask operation on the IO thread. (The
232 // IO thread will handle that URLFetcher operation before going away.)
233 metrics_service_.reset();
234 variations_service_.reset();
235 intranet_redirect_detector_.reset();
236 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
237 if (safe_browsing_service_.get())
238 safe_browsing_service()->ShutDown();
241 // Need to clear the desktop notification balloons before the io_thread_ and
242 // before the profiles, since if there are any still showing we will access
243 // those things during teardown.
244 notification_ui_manager_.reset();
246 // Need to clear profiles (download managers) before the io_thread_.
248 TRACE_EVENT0("shutdown",
249 "BrowserProcessImpl::StartTearDown:ProfileManager");
250 // The desktop User Manager needs to be closed before the guest profile
252 if (switches::IsNewProfileManagement())
253 chrome::HideUserManager();
254 profile_manager_.reset();
257 #if !defined(OS_ANDROID)
258 // Debugger must be cleaned up before IO thread and NotificationService.
259 remote_debugging_server_.reset();
262 ExtensionRendererState::GetInstance()->Shutdown();
264 #if !defined(OS_ANDROID) && !defined(OS_IOS)
265 media_file_system_registry_.reset();
266 // Remove the global instance of the Storage Monitor now. Otherwise the
267 // FILE thread would be gone when we try to release it in the dtor and
268 // Valgrind would report a leak on almost every single browser_test.
269 // TODO(gbillock): Make this unnecessary.
270 StorageMonitor::Destroy();
273 message_center::MessageCenter::Shutdown();
275 #if defined(ENABLE_CONFIGURATION_POLICY)
276 // The policy providers managed by |browser_policy_connector_| need to shut
277 // down while the IO and FILE threads are still alive.
278 if (browser_policy_connector_)
279 browser_policy_connector_->Shutdown();
282 // Stop the watchdog thread before stopping other threads.
283 watchdog_thread_.reset();
285 #if defined(USE_AURA)
286 // Delete aura after the metrics service has been deleted as it accesses
287 // monitor information.
288 aura::Env::DeleteInstance();
291 platform_part()->StartTearDown();
293 #if defined(ENABLE_WEBRTC)
294 webrtc_log_uploader_.reset();
298 local_state()->CommitPendingWrite();
301 void BrowserProcessImpl::PostDestroyThreads() {
302 // With the file_thread_ flushed, we can release any icon resources.
303 icon_manager_.reset();
305 // Reset associated state right after actual thread is stopped,
306 // as io_thread_.global_ cleanup happens in CleanUp on the IO
307 // thread, i.e. as the thread exits its message loop.
309 // This is important also because in various places, the
310 // IOThread object being NULL is considered synonymous with the
311 // IO thread having stopped.
316 // Send a QuitTask to the given MessageLoop when the (file) thread has processed
317 // our (other) recent requests (to save preferences).
318 // Change the boolean so that the receiving thread will know that we did indeed
319 // send the QuitTask that terminated the message loop.
320 static void PostQuit(base::MessageLoop* message_loop) {
321 g_end_session_file_thread_has_completed = true;
322 message_loop->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
324 #elif defined(USE_X11)
325 static void Signal(base::WaitableEvent* event) {
330 unsigned int BrowserProcessImpl::AddRefModule() {
331 DCHECK(CalledOnValidThread());
333 // CHECK(!IsShuttingDown());
334 if (IsShuttingDown()) {
335 // Copy the stacktrace which released the final reference onto our stack so
336 // it will be available in the crash report for inspection.
337 base::debug::StackTrace callstack = release_last_reference_callstack_;
338 base::debug::Alias(&callstack);
344 return module_ref_count_;
347 unsigned int BrowserProcessImpl::ReleaseModule() {
348 DCHECK(CalledOnValidThread());
349 DCHECK_NE(0u, module_ref_count_);
351 if (0 == module_ref_count_) {
352 release_last_reference_callstack_ = base::debug::StackTrace();
354 #if defined(ENABLE_PRINTING)
355 // Wait for the pending print jobs to finish. Don't do this later, since
356 // this might cause a nested message loop to run, and we don't want pending
357 // tasks to run once teardown has started.
358 print_job_manager_->Shutdown();
361 #if defined(LEAK_SANITIZER)
362 // Check for memory leaks now, before we start shutting down threads. Doing
363 // this early means we won't report any shutdown-only leaks (as they have
364 // not yet happened at this point).
365 // If leaks are found, this will make the process exit immediately.
366 __lsan_do_leak_check();
369 CHECK(base::MessageLoop::current()->is_running());
371 #if defined(OS_MACOSX)
372 base::MessageLoop::current()->PostTask(
374 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
376 base::MessageLoop::current()->Quit();
378 return module_ref_count_;
381 void BrowserProcessImpl::EndSession() {
382 // Mark all the profiles as clean.
383 ProfileManager* pm = profile_manager();
384 std::vector<Profile*> profiles(pm->GetLoadedProfiles());
385 for (size_t i = 0; i < profiles.size(); ++i)
386 profiles[i]->SetExitType(Profile::EXIT_SESSION_ENDED);
388 // Tell the metrics service it was cleanly shutdown.
389 MetricsService* metrics = g_browser_process->metrics_service();
390 if (metrics && local_state()) {
391 metrics->RecordStartOfSessionEnd();
392 #if !defined(OS_CHROMEOS)
393 // MetricsService lazily writes to prefs, force it to write now.
394 // On ChromeOS, chrome gets killed when hangs, so no need to
395 // commit prefs::kStabilitySessionEndCompleted change immediately.
396 local_state()->CommitPendingWrite();
400 // http://crbug.com/125207
401 base::ThreadRestrictions::ScopedAllowWait allow_wait;
403 // We must write that the profile and metrics service shutdown cleanly,
404 // otherwise on startup we'll think we crashed. So we block until done and
405 // then proceed with normal shutdown.
407 // Can't run a local loop on linux. Instead create a waitable event.
408 scoped_ptr<base::WaitableEvent> done_writing(
409 new base::WaitableEvent(false, false));
410 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
411 base::Bind(Signal, done_writing.get()));
412 // If all file writes haven't cleared in the timeout, leak the WaitableEvent
413 // so that there's no race to reference it in Signal().
414 if (!done_writing->TimedWait(
415 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds))) {
416 ignore_result(done_writing.release());
419 #elif defined(OS_WIN)
420 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
421 base::Bind(PostQuit, base::MessageLoop::current()));
422 int quits_received = 0;
424 base::MessageLoop::current()->Run();
426 } while (!g_end_session_file_thread_has_completed);
427 // If we did get extra quits, then we should re-post them to the message loop.
428 while (--quits_received > 0) {
429 base::MessageLoop::current()->PostTask(FROM_HERE,
430 base::MessageLoop::QuitClosure());
437 MetricsService* BrowserProcessImpl::metrics_service() {
438 DCHECK(CalledOnValidThread());
439 if (!created_metrics_service_)
440 CreateMetricsService();
441 return metrics_service_.get();
444 IOThread* BrowserProcessImpl::io_thread() {
445 DCHECK(CalledOnValidThread());
446 DCHECK(io_thread_.get());
447 return io_thread_.get();
450 WatchDogThread* BrowserProcessImpl::watchdog_thread() {
451 DCHECK(CalledOnValidThread());
452 if (!created_watchdog_thread_)
453 CreateWatchdogThread();
454 DCHECK(watchdog_thread_.get() != NULL);
455 return watchdog_thread_.get();
458 ProfileManager* BrowserProcessImpl::profile_manager() {
459 DCHECK(CalledOnValidThread());
460 if (!created_profile_manager_)
461 CreateProfileManager();
462 return profile_manager_.get();
465 PrefService* BrowserProcessImpl::local_state() {
466 DCHECK(CalledOnValidThread());
467 if (!created_local_state_)
469 return local_state_.get();
472 net::URLRequestContextGetter* BrowserProcessImpl::system_request_context() {
473 DCHECK(CalledOnValidThread());
474 return io_thread()->system_url_request_context_getter();
477 chrome_variations::VariationsService* BrowserProcessImpl::variations_service() {
478 DCHECK(CalledOnValidThread());
479 if (!variations_service_.get()) {
480 variations_service_.reset(
481 chrome_variations::VariationsService::Create(local_state()));
483 return variations_service_.get();
486 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
487 return platform_part_.get();
490 extensions::EventRouterForwarder*
491 BrowserProcessImpl::extension_event_router_forwarder() {
492 return extension_event_router_forwarder_.get();
495 NotificationUIManager* BrowserProcessImpl::notification_ui_manager() {
496 DCHECK(CalledOnValidThread());
497 if (!created_notification_ui_manager_)
498 CreateNotificationUIManager();
499 return notification_ui_manager_.get();
502 message_center::MessageCenter* BrowserProcessImpl::message_center() {
503 DCHECK(CalledOnValidThread());
504 return message_center::MessageCenter::Get();
507 policy::BrowserPolicyConnector* BrowserProcessImpl::browser_policy_connector() {
508 DCHECK(CalledOnValidThread());
509 #if defined(ENABLE_CONFIGURATION_POLICY)
510 if (!created_browser_policy_connector_) {
511 DCHECK(!browser_policy_connector_);
512 browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector();
513 created_browser_policy_connector_ = true;
515 return browser_policy_connector_.get();
521 policy::PolicyService* BrowserProcessImpl::policy_service() {
522 #if defined(ENABLE_CONFIGURATION_POLICY)
523 return browser_policy_connector()->GetPolicyService();
525 if (!policy_service_.get())
526 policy_service_.reset(new policy::PolicyServiceStub());
527 return policy_service_.get();
531 IconManager* BrowserProcessImpl::icon_manager() {
532 DCHECK(CalledOnValidThread());
533 if (!created_icon_manager_)
535 return icon_manager_.get();
538 GLStringManager* BrowserProcessImpl::gl_string_manager() {
539 DCHECK(CalledOnValidThread());
540 if (!gl_string_manager_.get())
541 gl_string_manager_.reset(new GLStringManager());
542 return gl_string_manager_.get();
545 GpuModeManager* BrowserProcessImpl::gpu_mode_manager() {
546 DCHECK(CalledOnValidThread());
547 if (!gpu_mode_manager_.get())
548 gpu_mode_manager_.reset(new GpuModeManager());
549 return gpu_mode_manager_.get();
552 AutomationProviderList* BrowserProcessImpl::GetAutomationProviderList() {
553 DCHECK(CalledOnValidThread());
554 #if defined(ENABLE_AUTOMATION)
555 if (automation_provider_list_.get() == NULL)
556 automation_provider_list_.reset(new AutomationProviderList());
557 return automation_provider_list_.get();
563 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
564 chrome::HostDesktopType host_desktop_type,
565 const std::string& ip,
567 const std::string& frontend_url) {
568 DCHECK(CalledOnValidThread());
569 #if !defined(OS_ANDROID)
570 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
571 // is started with several profiles or existing browser process is reused.
572 if (!remote_debugging_server_.get()) {
573 remote_debugging_server_.reset(
574 new RemoteDebuggingServer(host_desktop_type, ip, port,
580 bool BrowserProcessImpl::IsShuttingDown() {
581 DCHECK(CalledOnValidThread());
582 return did_start_ && 0 == module_ref_count_;
585 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
586 DCHECK(CalledOnValidThread());
587 return print_job_manager_.get();
590 printing::PrintPreviewDialogController*
591 BrowserProcessImpl::print_preview_dialog_controller() {
592 #if defined(ENABLE_FULL_PRINTING)
593 DCHECK(CalledOnValidThread());
594 if (!print_preview_dialog_controller_.get())
595 CreatePrintPreviewDialogController();
596 return print_preview_dialog_controller_.get();
603 printing::BackgroundPrintingManager*
604 BrowserProcessImpl::background_printing_manager() {
605 #if defined(ENABLE_FULL_PRINTING)
606 DCHECK(CalledOnValidThread());
607 if (!background_printing_manager_.get())
608 CreateBackgroundPrintingManager();
609 return background_printing_manager_.get();
616 IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() {
617 DCHECK(CalledOnValidThread());
618 if (!intranet_redirect_detector_.get())
619 CreateIntranetRedirectDetector();
620 return intranet_redirect_detector_.get();
623 const std::string& BrowserProcessImpl::GetApplicationLocale() {
624 DCHECK(!locale_.empty());
628 void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) {
630 extension_l10n_util::SetProcessLocale(locale);
631 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale);
632 TranslateDownloadManager::GetInstance()->set_application_locale(locale);
635 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
636 return download_status_updater_.get();
639 BookmarkPromptController* BrowserProcessImpl::bookmark_prompt_controller() {
640 #if defined(OS_ANDROID)
643 return bookmark_prompt_controller_.get();
647 MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() {
648 #if defined(OS_ANDROID) || defined(OS_IOS)
651 if (!media_file_system_registry_)
652 media_file_system_registry_.reset(new MediaFileSystemRegistry());
653 return media_file_system_registry_.get();
657 bool BrowserProcessImpl::created_local_state() const {
658 return created_local_state_;
661 #if defined(ENABLE_WEBRTC)
662 WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() {
663 if (!webrtc_log_uploader_.get())
664 webrtc_log_uploader_.reset(new WebRtcLogUploader());
665 return webrtc_log_uploader_.get();
670 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
671 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
673 // This policy needs to be defined before the net subsystem is initialized,
675 registry->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy,
676 net::kDefaultMaxSocketsPerProxyServer);
678 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
680 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
681 registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
682 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
684 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
685 registry->RegisterStringPref(prefs::kRelaunchMode,
686 upgrade_util::kRelaunchModeDefault);
690 // TODO(brettw,*): this comment about ResourceBundle was here since
691 // initial commit. This comment seems unrelated, bit-rotten and
692 // a candidate for removal.
693 // Initialize ResourceBundle which handles files loaded from external
694 // sources. This has to be done before uninstall code path and before prefs
696 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
697 #if defined(OS_CHROMEOS)
698 registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
699 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
701 #endif // defined(OS_CHROMEOS)
702 #if !defined(OS_CHROMEOS)
703 registry->RegisterBooleanPref(
704 prefs::kMetricsReportingEnabled,
705 GoogleUpdateSettings::GetCollectStatsConsent());
706 #endif // !defined(OS_CHROMEOS)
708 #if defined(OS_ANDROID)
709 registry->RegisterBooleanPref(
710 prefs::kCrashReportingEnabled, false);
711 #endif // defined(OS_ANDROID)
714 DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() {
715 DCHECK(CalledOnValidThread());
716 if (!download_request_limiter_.get())
717 download_request_limiter_ = new DownloadRequestLimiter();
718 return download_request_limiter_.get();
721 BackgroundModeManager* BrowserProcessImpl::background_mode_manager() {
722 DCHECK(CalledOnValidThread());
723 #if defined(ENABLE_BACKGROUND)
724 if (!background_mode_manager_.get())
725 CreateBackgroundModeManager();
726 return background_mode_manager_.get();
733 void BrowserProcessImpl::set_background_mode_manager_for_test(
734 scoped_ptr<BackgroundModeManager> manager) {
735 background_mode_manager_ = manager.Pass();
738 StatusTray* BrowserProcessImpl::status_tray() {
739 DCHECK(CalledOnValidThread());
740 if (!status_tray_.get())
742 return status_tray_.get();
746 SafeBrowsingService* BrowserProcessImpl::safe_browsing_service() {
747 DCHECK(CalledOnValidThread());
748 if (!created_safe_browsing_service_)
749 CreateSafeBrowsingService();
750 return safe_browsing_service_.get();
753 safe_browsing::ClientSideDetectionService*
754 BrowserProcessImpl::safe_browsing_detection_service() {
755 DCHECK(CalledOnValidThread());
756 if (safe_browsing_service())
757 return safe_browsing_service()->safe_browsing_detection_service();
761 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
762 void BrowserProcessImpl::StartAutoupdateTimer() {
763 autoupdate_timer_.Start(FROM_HERE,
764 base::TimeDelta::FromHours(kUpdateCheckIntervalHours),
766 &BrowserProcessImpl::OnAutoupdateTimer);
770 ChromeNetLog* BrowserProcessImpl::net_log() {
771 return net_log_.get();
774 prerender::PrerenderTracker* BrowserProcessImpl::prerender_tracker() {
775 if (!prerender_tracker_.get())
776 prerender_tracker_.reset(new prerender::PrerenderTracker);
778 return prerender_tracker_.get();
781 component_updater::ComponentUpdateService*
782 BrowserProcessImpl::component_updater() {
783 if (!component_updater_.get()) {
784 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
786 component_updater::ComponentUpdateService::Configurator* configurator =
787 component_updater::MakeChromeComponentUpdaterConfigurator(
788 CommandLine::ForCurrentProcess(),
789 io_thread()->system_url_request_context_getter());
790 // Creating the component updater does not do anything, components
791 // need to be registered and Start() needs to be called.
792 component_updater_.reset(ComponentUpdateServiceFactory(configurator));
794 return component_updater_.get();
797 CRLSetFetcher* BrowserProcessImpl::crl_set_fetcher() {
798 if (!crl_set_fetcher_.get())
799 crl_set_fetcher_ = new CRLSetFetcher();
800 return crl_set_fetcher_.get();
803 component_updater::PnaclComponentInstaller*
804 BrowserProcessImpl::pnacl_component_installer() {
805 if (!pnacl_component_installer_.get()) {
806 pnacl_component_installer_.reset(
807 new component_updater::PnaclComponentInstaller());
809 return pnacl_component_installer_.get();
812 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
813 resource_dispatcher_host_delegate_.reset(
814 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
815 ResourceDispatcherHost::Get()->SetDelegate(
816 resource_dispatcher_host_delegate_.get());
818 pref_change_registrar_.Add(
819 prefs::kAllowCrossOriginAuthPrompt,
820 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy,
821 base::Unretained(this)));
822 ApplyAllowCrossOriginAuthPromptPolicy();
825 void BrowserProcessImpl::CreateMetricsService() {
826 DCHECK(!created_metrics_service_ && metrics_service_.get() == NULL);
827 created_metrics_service_ = true;
829 metrics_service_.reset(new MetricsService);
832 void BrowserProcessImpl::CreateWatchdogThread() {
833 DCHECK(!created_watchdog_thread_ && watchdog_thread_.get() == NULL);
834 created_watchdog_thread_ = true;
836 scoped_ptr<WatchDogThread> thread(new WatchDogThread());
837 if (!thread->Start())
839 watchdog_thread_.swap(thread);
842 void BrowserProcessImpl::CreateProfileManager() {
843 DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL);
844 created_profile_manager_ = true;
846 base::FilePath user_data_dir;
847 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
848 profile_manager_.reset(new ProfileManager(user_data_dir));
851 void BrowserProcessImpl::CreateLocalState() {
852 DCHECK(!created_local_state_ && local_state_.get() == NULL);
853 created_local_state_ = true;
855 base::FilePath local_state_path;
856 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path));
857 scoped_refptr<PrefRegistrySimple> pref_registry = new PrefRegistrySimple;
859 // Register local state preferences.
860 chrome::RegisterLocalState(pref_registry.get());
863 chrome_prefs::CreateLocalState(local_state_path,
864 local_state_task_runner_.get(),
869 pref_change_registrar_.Init(local_state_.get());
871 // Initialize the notification for the default browser setting policy.
872 pref_change_registrar_.Add(
873 prefs::kDefaultBrowserSettingEnabled,
874 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy,
875 base::Unretained(this)));
877 // This preference must be kept in sync with external values; update them
878 // whenever the preference or its controlling policy changes.
879 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
880 pref_change_registrar_.Add(
881 prefs::kMetricsReportingEnabled,
882 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy,
883 base::Unretained(this)));
886 int max_per_proxy = local_state_->GetInteger(prefs::kMaxConnectionsPerProxy);
887 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
888 net::HttpNetworkSession::NORMAL_SOCKET_POOL,
889 std::max(std::min(max_per_proxy, 99),
890 net::ClientSocketPoolManager::max_sockets_per_group(
891 net::HttpNetworkSession::NORMAL_SOCKET_POOL)));
894 void BrowserProcessImpl::PreCreateThreads() {
895 io_thread_.reset(new IOThread(local_state(), policy_service(), net_log_.get(),
896 extension_event_router_forwarder_.get()));
899 void BrowserProcessImpl::PreMainMessageLoopRun() {
900 #if defined(ENABLE_CONFIGURATION_POLICY)
901 // browser_policy_connector() is created very early because local_state()
902 // needs policy to be initialized with the managed preference values.
903 // However, policy fetches from the network and loading of disk caches
904 // requires that threads are running; this Init() call lets the connector
905 // resume its initialization now that the loops are spinning and the
906 // system request context is available for the fetchers.
907 browser_policy_connector()->Init(local_state(), system_request_context());
910 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
911 ApplyDefaultBrowserPolicy();
913 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
914 ApplyMetricsReportingPolicy();
917 #if defined(ENABLE_PLUGINS)
918 PluginService* plugin_service = PluginService::GetInstance();
919 plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance());
920 plugin_service->StartWatchingPlugins();
922 #if defined(OS_POSIX)
923 // Also find plugins in a user-specific plugins dir,
924 // e.g. ~/.config/chromium/Plugins.
925 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
926 if (!cmd_line.HasSwitch(switches::kDisablePluginsDiscovery)) {
927 base::FilePath user_data_dir;
928 if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
929 plugin_service->AddExtraPluginDir(user_data_dir.Append("Plugins"));
933 // Triggers initialization of the singleton instance on UI thread.
934 PluginFinder::GetInstance()->Init();
936 #if defined(ENABLE_PLUGIN_INSTALLATION)
937 DCHECK(!plugins_resource_service_.get());
938 plugins_resource_service_ = new PluginsResourceService(local_state());
939 plugins_resource_service_->Init();
941 #endif // defined(ENABLE_PLUGINS)
943 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
944 if (!command_line.HasSwitch(switches::kDisableWebResources)) {
945 DCHECK(!promo_resource_service_.get());
946 promo_resource_service_ = new PromoResourceService;
947 promo_resource_service_->StartAfterDelay();
950 #if !defined(OS_ANDROID)
951 if (browser_defaults::bookmarks_enabled &&
952 BookmarkPromptController::IsEnabled()) {
953 bookmark_prompt_controller_.reset(new BookmarkPromptController());
957 #if !defined(OS_ANDROID) && !defined(OS_IOS)
958 StorageMonitor::Create();
961 platform_part_->PreMainMessageLoopRun();
964 void BrowserProcessImpl::CreateIconManager() {
965 DCHECK(!created_icon_manager_ && icon_manager_.get() == NULL);
966 created_icon_manager_ = true;
967 icon_manager_.reset(new IconManager);
970 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
971 DCHECK(intranet_redirect_detector_.get() == NULL);
972 scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector(
973 new IntranetRedirectDetector);
974 intranet_redirect_detector_.swap(intranet_redirect_detector);
977 void BrowserProcessImpl::CreateNotificationUIManager() {
978 #if defined(ENABLE_NOTIFICATIONS)
979 DCHECK(notification_ui_manager_.get() == NULL);
980 notification_ui_manager_.reset(NotificationUIManager::Create(local_state()));
981 created_notification_ui_manager_ = true;
985 void BrowserProcessImpl::CreateBackgroundModeManager() {
986 DCHECK(background_mode_manager_.get() == NULL);
987 background_mode_manager_.reset(
988 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
989 &profile_manager()->GetProfileInfoCache()));
992 void BrowserProcessImpl::CreateStatusTray() {
993 DCHECK(status_tray_.get() == NULL);
994 status_tray_.reset(StatusTray::Create());
997 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
998 #if defined(ENABLE_FULL_PRINTING)
999 DCHECK(print_preview_dialog_controller_.get() == NULL);
1000 print_preview_dialog_controller_ =
1001 new printing::PrintPreviewDialogController();
1007 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
1008 #if defined(ENABLE_FULL_PRINTING)
1009 DCHECK(background_printing_manager_.get() == NULL);
1010 background_printing_manager_.reset(new printing::BackgroundPrintingManager());
1016 void BrowserProcessImpl::CreateSafeBrowsingService() {
1017 DCHECK(safe_browsing_service_.get() == NULL);
1018 // Set this flag to true so that we don't retry indefinitely to
1019 // create the service class if there was an error.
1020 created_safe_browsing_service_ = true;
1021 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
1022 safe_browsing_service_ = SafeBrowsingService::CreateSafeBrowsingService();
1023 safe_browsing_service_->Initialize();
1027 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
1028 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) {
1029 scoped_refptr<ShellIntegration::DefaultWebClientWorker>
1030 set_browser_worker = new ShellIntegration::DefaultBrowserWorker(NULL);
1031 set_browser_worker->StartSetAsDefault();
1035 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1036 bool value = local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
1037 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value);
1040 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1041 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1042 CHECK(BrowserThread::PostTask(
1043 BrowserThread::FILE, FROM_HERE,
1045 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent),
1046 local_state()->GetBoolean(prefs::kMetricsReportingEnabled))));
1050 // Mac is currently not supported.
1051 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1053 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1054 // Check if browser is in the background and if it needs to be restarted to
1055 // apply a pending update.
1056 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1057 upgrade_util::IsUpdatePendingRestart();
1060 // Switches to add when auto-restarting Chrome.
1061 const char* const kSwitchesToAddOnAutorestart[] = {
1062 switches::kNoStartupWindow
1065 void BrowserProcessImpl::RestartBackgroundInstance() {
1066 CommandLine* old_cl = CommandLine::ForCurrentProcess();
1067 scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl->GetProgram()));
1069 std::map<std::string, CommandLine::StringType> switches =
1070 old_cl->GetSwitches();
1072 switches::RemoveSwitchesForAutostart(&switches);
1074 // Append the rest of the switches (along with their values, if any)
1075 // to the new command line
1076 for (std::map<std::string, CommandLine::StringType>::const_iterator i =
1077 switches.begin(); i != switches.end(); ++i) {
1078 CommandLine::StringType switch_value = i->second;
1079 if (switch_value.length() > 0) {
1080 new_cl->AppendSwitchNative(i->first, i->second);
1082 new_cl->AppendSwitch(i->first);
1086 // Ensure that our desired switches are set on the new process.
1087 for (size_t i = 0; i < arraysize(kSwitchesToAddOnAutorestart); ++i) {
1088 if (!new_cl->HasSwitch(kSwitchesToAddOnAutorestart[i]))
1089 new_cl->AppendSwitch(kSwitchesToAddOnAutorestart[i]);
1092 DLOG(WARNING) << "Shutting down current instance of the browser.";
1093 chrome::AttemptExit();
1095 // Transfer ownership to Upgrade.
1096 upgrade_util::SetNewCommandLine(new_cl.release());
1099 void BrowserProcessImpl::OnAutoupdateTimer() {
1100 if (CanAutorestartForUpdate()) {
1101 DLOG(WARNING) << "Detected update. Restarting browser.";
1102 RestartBackgroundInstance();
1106 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)