Componentize AccountReconcilor.
[chromium-blink-merge.git] / chrome / browser / browser_process_impl.cc
blobaf6ddb027bcd41d48ab6b49b2d4a680f119422ce
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"
7 #include <algorithm>
8 #include <map>
9 #include <vector>
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/background/background_mode_manager.h"
25 #include "chrome/browser/chrome_browser_main.h"
26 #include "chrome/browser/chrome_content_browser_client.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/component_updater/component_updater_configurator.h"
29 #include "chrome/browser/component_updater/component_updater_service.h"
30 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/devtools/remote_debugging_server.h"
33 #include "chrome/browser/download/download_request_limiter.h"
34 #include "chrome/browser/download/download_status_updater.h"
35 #include "chrome/browser/extensions/chrome_extensions_browser_client.h"
36 #include "chrome/browser/extensions/event_router_forwarder.h"
37 #include "chrome/browser/extensions/extension_renderer_state.h"
38 #include "chrome/browser/first_run/upgrade_util.h"
39 #include "chrome/browser/gpu/gl_string_manager.h"
40 #include "chrome/browser/gpu/gpu_mode_manager.h"
41 #include "chrome/browser/icon_manager.h"
42 #include "chrome/browser/idle.h"
43 #include "chrome/browser/intranet_redirect_detector.h"
44 #include "chrome/browser/io_thread.h"
45 #include "chrome/browser/lifetime/application_lifetime.h"
46 #include "chrome/browser/metrics/metrics_service.h"
47 #include "chrome/browser/metrics/thread_watcher.h"
48 #include "chrome/browser/metrics/variations/variations_service.h"
49 #include "chrome/browser/net/chrome_net_log.h"
50 #include "chrome/browser/net/crl_set_fetcher.h"
51 #include "chrome/browser/net/sdch_dictionary_fetcher.h"
52 #include "chrome/browser/notifications/notification_ui_manager.h"
53 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
54 #include "chrome/browser/plugins/plugin_finder.h"
55 #include "chrome/browser/prefs/browser_prefs.h"
56 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
57 #include "chrome/browser/prerender/prerender_tracker.h"
58 #include "chrome/browser/printing/background_printing_manager.h"
59 #include "chrome/browser/printing/print_job_manager.h"
60 #include "chrome/browser/printing/print_preview_dialog_controller.h"
61 #include "chrome/browser/profiles/profile_manager.h"
62 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
63 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
64 #include "chrome/browser/shell_integration.h"
65 #include "chrome/browser/status_icons/status_tray.h"
66 #include "chrome/browser/ui/bookmarks/bookmark_prompt_controller.h"
67 #include "chrome/browser/ui/browser_dialogs.h"
68 #include "chrome/browser/ui/browser_finder.h"
69 #include "chrome/browser/web_resource/promo_resource_service.h"
70 #include "chrome/common/chrome_constants.h"
71 #include "chrome/common/chrome_paths.h"
72 #include "chrome/common/chrome_switches.h"
73 #include "chrome/common/extensions/chrome_extensions_client.h"
74 #include "chrome/common/extensions/extension_l10n_util.h"
75 #include "chrome/common/pref_names.h"
76 #include "chrome/common/profile_management_switches.h"
77 #include "chrome/common/switch_utils.h"
78 #include "chrome/common/url_constants.h"
79 #include "chrome/installer/util/google_update_constants.h"
80 #include "components/policy/core/common/policy_service.h"
81 #include "components/rappor/rappor_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"
97 #else
98 #include "components/policy/core/common/policy_service_stub.h"
99 #endif // defined(ENABLE_CONFIGURATION_POLICY)
101 #if defined(OS_WIN)
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"
106 #endif
108 #if defined(USE_AURA)
109 #include "ui/aura/env.h"
110 #endif
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"
115 #endif
117 #if defined(ENABLE_PLUGIN_INSTALLATION)
118 #include "chrome/browser/plugins/plugins_resource_service.h"
119 #endif
121 #if defined(ENABLE_WEBRTC)
122 #include "chrome/browser/media/webrtc_log_uploader.h"
123 #endif
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;
129 #endif
131 #if defined(USE_X11) || defined(OS_WIN)
132 // How long to wait for the File thread to complete during EndSession, on Linux
133 // and Windows. We have a timeout here because we're unable to run the UI
134 // messageloop and there's some deadlock risk. Our only option is to exit
135 // anyway.
136 static const int kEndSessionTimeoutSeconds = 10;
137 #endif
139 using content::BrowserThread;
140 using content::ChildProcessSecurityPolicy;
141 using content::PluginService;
142 using content::ResourceDispatcherHost;
144 BrowserProcessImpl::BrowserProcessImpl(
145 base::SequencedTaskRunner* local_state_task_runner,
146 const CommandLine& command_line)
147 : created_metrics_service_(false),
148 created_watchdog_thread_(false),
149 created_browser_policy_connector_(false),
150 created_profile_manager_(false),
151 created_local_state_(false),
152 created_icon_manager_(false),
153 created_notification_ui_manager_(false),
154 created_safe_browsing_service_(false),
155 module_ref_count_(0),
156 did_start_(false),
157 download_status_updater_(new DownloadStatusUpdater),
158 local_state_task_runner_(local_state_task_runner) {
159 g_browser_process = this;
160 platform_part_.reset(new BrowserProcessPlatformPart());
162 #if defined(ENABLE_PRINTING)
163 // Must be created after the NotificationService.
164 print_job_manager_.reset(new printing::PrintJobManager);
165 #endif
167 net_log_.reset(new ChromeNetLog);
169 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
170 extensions::kExtensionScheme);
171 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
172 extensions::kExtensionResourceScheme);
173 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
174 chrome::kChromeSearchScheme);
176 #if defined(OS_MACOSX)
177 InitIdleMonitor();
178 #endif
180 apps::AppsClient::Set(ChromeAppsClient::GetInstance());
181 extensions::ExtensionsClient::Set(
182 extensions::ChromeExtensionsClient::GetInstance());
184 extensions_browser_client_.reset(
185 new extensions::ChromeExtensionsBrowserClient);
186 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
188 extension_event_router_forwarder_ = new extensions::EventRouterForwarder;
189 ExtensionRendererState::GetInstance()->Init();
191 message_center::MessageCenter::Initialize();
194 BrowserProcessImpl::~BrowserProcessImpl() {
195 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
197 g_browser_process = NULL;
200 void BrowserProcessImpl::StartTearDown() {
201 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown");
202 // We need to shutdown the SdchDictionaryFetcher as it regularly holds
203 // a pointer to a URLFetcher, and that URLFetcher (upon destruction) will do
204 // a PostDelayedTask onto the IO thread. This shutdown call will both discard
205 // any pending URLFetchers, and avoid creating any more.
206 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
207 base::Bind(&SdchDictionaryFetcher::Shutdown));
209 // We need to destroy the MetricsService, RapporService, VariationsService,
210 // IntranetRedirectDetector, PromoResourceService, and SafeBrowsing
211 // ClientSideDetectionService (owned by the SafeBrowsingService) before the
212 // io_thread_ gets destroyed, since their destructors can call the URLFetcher
213 // destructor, which does a PostDelayedTask operation on the IO thread. (The
214 // IO thread will handle that URLFetcher operation before going away.)
215 metrics_service_.reset();
216 rappor_service_.reset();
217 variations_service_.reset();
218 intranet_redirect_detector_.reset();
219 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
220 if (safe_browsing_service_.get())
221 safe_browsing_service()->ShutDown();
222 #endif
224 // Need to clear the desktop notification balloons before the io_thread_ and
225 // before the profiles, since if there are any still showing we will access
226 // those things during teardown.
227 notification_ui_manager_.reset();
229 // Need to clear profiles (download managers) before the io_thread_.
231 TRACE_EVENT0("shutdown",
232 "BrowserProcessImpl::StartTearDown:ProfileManager");
233 // The desktop User Manager needs to be closed before the guest profile
234 // can be destroyed.
235 if (switches::IsNewProfileManagement())
236 chrome::HideUserManager();
237 profile_manager_.reset();
240 #if !defined(OS_ANDROID)
241 // Debugger must be cleaned up before IO thread and NotificationService.
242 remote_debugging_server_.reset();
243 #endif
245 ExtensionRendererState::GetInstance()->Shutdown();
247 #if !defined(OS_ANDROID) && !defined(OS_IOS)
248 media_file_system_registry_.reset();
249 // Remove the global instance of the Storage Monitor now. Otherwise the
250 // FILE thread would be gone when we try to release it in the dtor and
251 // Valgrind would report a leak on almost every single browser_test.
252 // TODO(gbillock): Make this unnecessary.
253 storage_monitor::StorageMonitor::Destroy();
254 #endif
256 message_center::MessageCenter::Shutdown();
258 #if defined(ENABLE_CONFIGURATION_POLICY)
259 // The policy providers managed by |browser_policy_connector_| need to shut
260 // down while the IO and FILE threads are still alive.
261 if (browser_policy_connector_)
262 browser_policy_connector_->Shutdown();
263 #endif
265 // Stop the watchdog thread before stopping other threads.
266 watchdog_thread_.reset();
268 #if defined(USE_AURA)
269 // Delete aura after the metrics service has been deleted as it accesses
270 // monitor information.
271 aura::Env::DeleteInstance();
272 #endif
274 platform_part()->StartTearDown();
276 #if defined(ENABLE_WEBRTC)
277 // Cancel any uploads to release the system url request context references.
278 if (webrtc_log_uploader_)
279 webrtc_log_uploader_->StartShutdown();
280 #endif
282 if (local_state())
283 local_state()->CommitPendingWrite();
286 void BrowserProcessImpl::PostDestroyThreads() {
287 // With the file_thread_ flushed, we can release any icon resources.
288 icon_manager_.reset();
290 #if defined(ENABLE_WEBRTC)
291 // Must outlive the file thread.
292 webrtc_log_uploader_.reset();
293 #endif
295 // Reset associated state right after actual thread is stopped,
296 // as io_thread_.global_ cleanup happens in CleanUp on the IO
297 // thread, i.e. as the thread exits its message loop.
299 // This is important also because in various places, the
300 // IOThread object being NULL is considered synonymous with the
301 // IO thread having stopped.
302 io_thread_.reset();
305 #if defined(USE_X11) || defined(OS_WIN)
306 static void Signal(base::WaitableEvent* event) {
307 event->Signal();
309 #endif
311 unsigned int BrowserProcessImpl::AddRefModule() {
312 DCHECK(CalledOnValidThread());
314 // CHECK(!IsShuttingDown());
315 if (IsShuttingDown()) {
316 // Copy the stacktrace which released the final reference onto our stack so
317 // it will be available in the crash report for inspection.
318 base::debug::StackTrace callstack = release_last_reference_callstack_;
319 base::debug::Alias(&callstack);
320 CHECK(false);
323 did_start_ = true;
324 module_ref_count_++;
325 return module_ref_count_;
328 unsigned int BrowserProcessImpl::ReleaseModule() {
329 DCHECK(CalledOnValidThread());
330 DCHECK_NE(0u, module_ref_count_);
331 module_ref_count_--;
332 if (0 == module_ref_count_) {
333 release_last_reference_callstack_ = base::debug::StackTrace();
335 #if defined(ENABLE_PRINTING)
336 // Wait for the pending print jobs to finish. Don't do this later, since
337 // this might cause a nested message loop to run, and we don't want pending
338 // tasks to run once teardown has started.
339 print_job_manager_->Shutdown();
340 #endif
342 #if defined(LEAK_SANITIZER)
343 // Check for memory leaks now, before we start shutting down threads. Doing
344 // this early means we won't report any shutdown-only leaks (as they have
345 // not yet happened at this point).
346 // If leaks are found, this will make the process exit immediately.
347 __lsan_do_leak_check();
348 #endif
350 CHECK(base::MessageLoop::current()->is_running());
352 #if defined(OS_MACOSX)
353 base::MessageLoop::current()->PostTask(
354 FROM_HERE,
355 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop));
356 #endif
357 base::MessageLoop::current()->Quit();
359 return module_ref_count_;
362 void BrowserProcessImpl::EndSession() {
363 // Mark all the profiles as clean.
364 ProfileManager* pm = profile_manager();
365 std::vector<Profile*> profiles(pm->GetLoadedProfiles());
366 for (size_t i = 0; i < profiles.size(); ++i)
367 profiles[i]->SetExitType(Profile::EXIT_SESSION_ENDED);
369 // Tell the metrics service it was cleanly shutdown.
370 MetricsService* metrics = g_browser_process->metrics_service();
371 if (metrics && local_state()) {
372 metrics->RecordStartOfSessionEnd();
373 #if !defined(OS_CHROMEOS)
374 // MetricsService lazily writes to prefs, force it to write now.
375 // On ChromeOS, chrome gets killed when hangs, so no need to
376 // commit prefs::kStabilitySessionEndCompleted change immediately.
377 local_state()->CommitPendingWrite();
378 #endif
381 // http://crbug.com/125207
382 base::ThreadRestrictions::ScopedAllowWait allow_wait;
384 // We must write that the profile and metrics service shutdown cleanly,
385 // otherwise on startup we'll think we crashed. So we block until done and
386 // then proceed with normal shutdown.
387 #if defined(USE_X11) || defined(OS_WIN)
388 // Create a waitable event to block on file writing being complete.
390 // On Windows, we previously posted a message to FILE and then ran a nested
391 // message loop, waiting for that message to be processed until quitting.
392 // However, doing so means that other messages will also be processed. In
393 // particular, if the GPU process host notices that the GPU has been killed
394 // during shutdown, it races exiting the nested loop with the process host
395 // blocking the message loop attempting to re-establish a connection to the
396 // GPU process synchronously. Because the system may not be allowing
397 // processes to launch, this can result in a hang. See
398 // http://crbug.com/318527.
399 scoped_ptr<base::WaitableEvent> done_writing(
400 new base::WaitableEvent(false, false));
401 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
402 base::Bind(Signal, done_writing.get()));
403 // If all file writes haven't cleared in the timeout, leak the WaitableEvent
404 // so that there's no race to reference it in Signal().
405 if (!done_writing->TimedWait(
406 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds))) {
407 ignore_result(done_writing.release());
409 #else
410 NOTIMPLEMENTED();
411 #endif
414 MetricsService* BrowserProcessImpl::metrics_service() {
415 DCHECK(CalledOnValidThread());
416 if (!created_metrics_service_)
417 CreateMetricsService();
418 return metrics_service_.get();
421 rappor::RapporService* BrowserProcessImpl::rappor_service() {
422 DCHECK(CalledOnValidThread());
423 if (!rappor_service_.get())
424 rappor_service_.reset(new rappor::RapporService());
425 return rappor_service_.get();
428 IOThread* BrowserProcessImpl::io_thread() {
429 DCHECK(CalledOnValidThread());
430 DCHECK(io_thread_.get());
431 return io_thread_.get();
434 WatchDogThread* BrowserProcessImpl::watchdog_thread() {
435 DCHECK(CalledOnValidThread());
436 if (!created_watchdog_thread_)
437 CreateWatchdogThread();
438 DCHECK(watchdog_thread_.get() != NULL);
439 return watchdog_thread_.get();
442 ProfileManager* BrowserProcessImpl::profile_manager() {
443 DCHECK(CalledOnValidThread());
444 if (!created_profile_manager_)
445 CreateProfileManager();
446 return profile_manager_.get();
449 PrefService* BrowserProcessImpl::local_state() {
450 DCHECK(CalledOnValidThread());
451 if (!created_local_state_)
452 CreateLocalState();
453 return local_state_.get();
456 net::URLRequestContextGetter* BrowserProcessImpl::system_request_context() {
457 DCHECK(CalledOnValidThread());
458 return io_thread()->system_url_request_context_getter();
461 chrome_variations::VariationsService* BrowserProcessImpl::variations_service() {
462 DCHECK(CalledOnValidThread());
463 if (!variations_service_.get()) {
464 variations_service_.reset(
465 chrome_variations::VariationsService::Create(local_state()));
467 return variations_service_.get();
470 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
471 return platform_part_.get();
474 extensions::EventRouterForwarder*
475 BrowserProcessImpl::extension_event_router_forwarder() {
476 return extension_event_router_forwarder_.get();
479 NotificationUIManager* BrowserProcessImpl::notification_ui_manager() {
480 DCHECK(CalledOnValidThread());
481 if (!created_notification_ui_manager_)
482 CreateNotificationUIManager();
483 return notification_ui_manager_.get();
486 message_center::MessageCenter* BrowserProcessImpl::message_center() {
487 DCHECK(CalledOnValidThread());
488 return message_center::MessageCenter::Get();
491 policy::BrowserPolicyConnector* BrowserProcessImpl::browser_policy_connector() {
492 DCHECK(CalledOnValidThread());
493 #if defined(ENABLE_CONFIGURATION_POLICY)
494 if (!created_browser_policy_connector_) {
495 DCHECK(!browser_policy_connector_);
496 browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector();
497 created_browser_policy_connector_ = true;
499 return browser_policy_connector_.get();
500 #else
501 return NULL;
502 #endif
505 policy::PolicyService* BrowserProcessImpl::policy_service() {
506 #if defined(ENABLE_CONFIGURATION_POLICY)
507 return browser_policy_connector()->GetPolicyService();
508 #else
509 if (!policy_service_.get())
510 policy_service_.reset(new policy::PolicyServiceStub());
511 return policy_service_.get();
512 #endif
515 IconManager* BrowserProcessImpl::icon_manager() {
516 DCHECK(CalledOnValidThread());
517 if (!created_icon_manager_)
518 CreateIconManager();
519 return icon_manager_.get();
522 GLStringManager* BrowserProcessImpl::gl_string_manager() {
523 DCHECK(CalledOnValidThread());
524 if (!gl_string_manager_.get())
525 gl_string_manager_.reset(new GLStringManager());
526 return gl_string_manager_.get();
529 GpuModeManager* BrowserProcessImpl::gpu_mode_manager() {
530 DCHECK(CalledOnValidThread());
531 if (!gpu_mode_manager_.get())
532 gpu_mode_manager_.reset(new GpuModeManager());
533 return gpu_mode_manager_.get();
536 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
537 chrome::HostDesktopType host_desktop_type,
538 const std::string& ip,
539 int port) {
540 DCHECK(CalledOnValidThread());
541 #if !defined(OS_ANDROID)
542 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
543 // is started with several profiles or existing browser process is reused.
544 if (!remote_debugging_server_.get()) {
545 remote_debugging_server_.reset(
546 new RemoteDebuggingServer(host_desktop_type, ip, port));
548 #endif
551 bool BrowserProcessImpl::IsShuttingDown() {
552 DCHECK(CalledOnValidThread());
553 return did_start_ && 0 == module_ref_count_;
556 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
557 DCHECK(CalledOnValidThread());
558 return print_job_manager_.get();
561 printing::PrintPreviewDialogController*
562 BrowserProcessImpl::print_preview_dialog_controller() {
563 #if defined(ENABLE_FULL_PRINTING)
564 DCHECK(CalledOnValidThread());
565 if (!print_preview_dialog_controller_.get())
566 CreatePrintPreviewDialogController();
567 return print_preview_dialog_controller_.get();
568 #else
569 NOTIMPLEMENTED();
570 return NULL;
571 #endif
574 printing::BackgroundPrintingManager*
575 BrowserProcessImpl::background_printing_manager() {
576 #if defined(ENABLE_FULL_PRINTING)
577 DCHECK(CalledOnValidThread());
578 if (!background_printing_manager_.get())
579 CreateBackgroundPrintingManager();
580 return background_printing_manager_.get();
581 #else
582 NOTIMPLEMENTED();
583 return NULL;
584 #endif
587 IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() {
588 DCHECK(CalledOnValidThread());
589 if (!intranet_redirect_detector_.get())
590 CreateIntranetRedirectDetector();
591 return intranet_redirect_detector_.get();
594 const std::string& BrowserProcessImpl::GetApplicationLocale() {
595 DCHECK(!locale_.empty());
596 return locale_;
599 void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) {
600 locale_ = locale;
601 extension_l10n_util::SetProcessLocale(locale);
602 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale);
603 TranslateDownloadManager::GetInstance()->set_application_locale(locale);
606 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
607 return download_status_updater_.get();
610 BookmarkPromptController* BrowserProcessImpl::bookmark_prompt_controller() {
611 #if defined(OS_ANDROID)
612 return NULL;
613 #else
614 return bookmark_prompt_controller_.get();
615 #endif
618 MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() {
619 #if defined(OS_ANDROID) || defined(OS_IOS)
620 return NULL;
621 #else
622 if (!media_file_system_registry_)
623 media_file_system_registry_.reset(new MediaFileSystemRegistry());
624 return media_file_system_registry_.get();
625 #endif
628 bool BrowserProcessImpl::created_local_state() const {
629 return created_local_state_;
632 #if defined(ENABLE_WEBRTC)
633 WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() {
634 if (!webrtc_log_uploader_.get())
635 webrtc_log_uploader_.reset(new WebRtcLogUploader());
636 return webrtc_log_uploader_.get();
638 #endif
640 // static
641 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) {
642 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled,
643 false);
644 // This policy needs to be defined before the net subsystem is initialized,
645 // so we do it here.
646 registry->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy,
647 net::kDefaultMaxSocketsPerProxyServer);
649 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false);
651 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
652 registry->RegisterBooleanPref(prefs::kEulaAccepted, false);
653 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS)
654 #if defined(OS_WIN)
655 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
656 registry->RegisterStringPref(prefs::kRelaunchMode,
657 upgrade_util::kRelaunchModeDefault);
659 #endif
661 // TODO(brettw,*): this comment about ResourceBundle was here since
662 // initial commit. This comment seems unrelated, bit-rotten and
663 // a candidate for removal.
664 // Initialize ResourceBundle which handles files loaded from external
665 // sources. This has to be done before uninstall code path and before prefs
666 // are registered.
667 registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
668 #if defined(OS_CHROMEOS)
669 registry->RegisterStringPref(prefs::kOwnerLocale, std::string());
670 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout,
671 std::string());
672 #endif // defined(OS_CHROMEOS)
673 #if !defined(OS_CHROMEOS)
674 registry->RegisterBooleanPref(
675 prefs::kMetricsReportingEnabled,
676 GoogleUpdateSettings::GetCollectStatsConsent());
677 #endif // !defined(OS_CHROMEOS)
679 #if defined(OS_ANDROID)
680 registry->RegisterBooleanPref(
681 prefs::kCrashReportingEnabled, false);
682 #endif // defined(OS_ANDROID)
685 DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() {
686 DCHECK(CalledOnValidThread());
687 if (!download_request_limiter_.get())
688 download_request_limiter_ = new DownloadRequestLimiter();
689 return download_request_limiter_.get();
692 BackgroundModeManager* BrowserProcessImpl::background_mode_manager() {
693 DCHECK(CalledOnValidThread());
694 #if defined(ENABLE_BACKGROUND)
695 if (!background_mode_manager_.get())
696 CreateBackgroundModeManager();
697 return background_mode_manager_.get();
698 #else
699 NOTIMPLEMENTED();
700 return NULL;
701 #endif
704 void BrowserProcessImpl::set_background_mode_manager_for_test(
705 scoped_ptr<BackgroundModeManager> manager) {
706 background_mode_manager_ = manager.Pass();
709 StatusTray* BrowserProcessImpl::status_tray() {
710 DCHECK(CalledOnValidThread());
711 if (!status_tray_.get())
712 CreateStatusTray();
713 return status_tray_.get();
717 SafeBrowsingService* BrowserProcessImpl::safe_browsing_service() {
718 DCHECK(CalledOnValidThread());
719 if (!created_safe_browsing_service_)
720 CreateSafeBrowsingService();
721 return safe_browsing_service_.get();
724 safe_browsing::ClientSideDetectionService*
725 BrowserProcessImpl::safe_browsing_detection_service() {
726 DCHECK(CalledOnValidThread());
727 if (safe_browsing_service())
728 return safe_browsing_service()->safe_browsing_detection_service();
729 return NULL;
732 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
733 void BrowserProcessImpl::StartAutoupdateTimer() {
734 autoupdate_timer_.Start(FROM_HERE,
735 base::TimeDelta::FromHours(kUpdateCheckIntervalHours),
736 this,
737 &BrowserProcessImpl::OnAutoupdateTimer);
739 #endif
741 ChromeNetLog* BrowserProcessImpl::net_log() {
742 return net_log_.get();
745 prerender::PrerenderTracker* BrowserProcessImpl::prerender_tracker() {
746 if (!prerender_tracker_.get())
747 prerender_tracker_.reset(new prerender::PrerenderTracker);
749 return prerender_tracker_.get();
752 component_updater::ComponentUpdateService*
753 BrowserProcessImpl::component_updater() {
754 if (!component_updater_.get()) {
755 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
756 return NULL;
757 component_updater::ComponentUpdateService::Configurator* configurator =
758 component_updater::MakeChromeComponentUpdaterConfigurator(
759 CommandLine::ForCurrentProcess(),
760 io_thread()->system_url_request_context_getter());
761 // Creating the component updater does not do anything, components
762 // need to be registered and Start() needs to be called.
763 component_updater_.reset(ComponentUpdateServiceFactory(configurator));
765 return component_updater_.get();
768 CRLSetFetcher* BrowserProcessImpl::crl_set_fetcher() {
769 if (!crl_set_fetcher_.get())
770 crl_set_fetcher_ = new CRLSetFetcher();
771 return crl_set_fetcher_.get();
774 component_updater::PnaclComponentInstaller*
775 BrowserProcessImpl::pnacl_component_installer() {
776 if (!pnacl_component_installer_.get()) {
777 pnacl_component_installer_.reset(
778 new component_updater::PnaclComponentInstaller());
780 return pnacl_component_installer_.get();
783 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
784 resource_dispatcher_host_delegate_.reset(
785 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
786 ResourceDispatcherHost::Get()->SetDelegate(
787 resource_dispatcher_host_delegate_.get());
789 pref_change_registrar_.Add(
790 prefs::kAllowCrossOriginAuthPrompt,
791 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy,
792 base::Unretained(this)));
793 ApplyAllowCrossOriginAuthPromptPolicy();
796 void BrowserProcessImpl::CreateMetricsService() {
797 DCHECK(!created_metrics_service_ && metrics_service_.get() == NULL);
798 created_metrics_service_ = true;
800 metrics_service_.reset(new MetricsService);
803 void BrowserProcessImpl::CreateWatchdogThread() {
804 DCHECK(!created_watchdog_thread_ && watchdog_thread_.get() == NULL);
805 created_watchdog_thread_ = true;
807 scoped_ptr<WatchDogThread> thread(new WatchDogThread());
808 if (!thread->Start())
809 return;
810 watchdog_thread_.swap(thread);
813 void BrowserProcessImpl::CreateProfileManager() {
814 DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL);
815 created_profile_manager_ = true;
817 base::FilePath user_data_dir;
818 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
819 profile_manager_.reset(new ProfileManager(user_data_dir));
822 void BrowserProcessImpl::CreateLocalState() {
823 DCHECK(!created_local_state_ && local_state_.get() == NULL);
824 created_local_state_ = true;
826 base::FilePath local_state_path;
827 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path));
828 scoped_refptr<PrefRegistrySimple> pref_registry = new PrefRegistrySimple;
830 // Register local state preferences.
831 chrome::RegisterLocalState(pref_registry.get());
833 local_state_ =
834 chrome_prefs::CreateLocalState(local_state_path,
835 local_state_task_runner_.get(),
836 policy_service(),
837 pref_registry,
838 false).Pass();
840 pref_change_registrar_.Init(local_state_.get());
842 // Initialize the notification for the default browser setting policy.
843 pref_change_registrar_.Add(
844 prefs::kDefaultBrowserSettingEnabled,
845 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy,
846 base::Unretained(this)));
848 // This preference must be kept in sync with external values; update them
849 // whenever the preference or its controlling policy changes.
850 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
851 pref_change_registrar_.Add(
852 prefs::kMetricsReportingEnabled,
853 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy,
854 base::Unretained(this)));
855 #endif
857 int max_per_proxy = local_state_->GetInteger(prefs::kMaxConnectionsPerProxy);
858 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
859 net::HttpNetworkSession::NORMAL_SOCKET_POOL,
860 std::max(std::min(max_per_proxy, 99),
861 net::ClientSocketPoolManager::max_sockets_per_group(
862 net::HttpNetworkSession::NORMAL_SOCKET_POOL)));
865 void BrowserProcessImpl::PreCreateThreads() {
866 io_thread_.reset(new IOThread(local_state(), policy_service(), net_log_.get(),
867 extension_event_router_forwarder_.get()));
870 void BrowserProcessImpl::PreMainMessageLoopRun() {
871 #if defined(ENABLE_CONFIGURATION_POLICY)
872 // browser_policy_connector() is created very early because local_state()
873 // needs policy to be initialized with the managed preference values.
874 // However, policy fetches from the network and loading of disk caches
875 // requires that threads are running; this Init() call lets the connector
876 // resume its initialization now that the loops are spinning and the
877 // system request context is available for the fetchers.
878 browser_policy_connector()->Init(local_state(), system_request_context());
879 #endif
881 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled))
882 ApplyDefaultBrowserPolicy();
884 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
885 ApplyMetricsReportingPolicy();
886 #endif
888 #if defined(ENABLE_PLUGINS)
889 PluginService* plugin_service = PluginService::GetInstance();
890 plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance());
891 plugin_service->StartWatchingPlugins();
893 #if defined(OS_POSIX)
894 // Also find plugins in a user-specific plugins dir,
895 // e.g. ~/.config/chromium/Plugins.
896 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
897 if (!cmd_line.HasSwitch(switches::kDisablePluginsDiscovery)) {
898 base::FilePath user_data_dir;
899 if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
900 plugin_service->AddExtraPluginDir(user_data_dir.Append("Plugins"));
902 #endif
904 // Triggers initialization of the singleton instance on UI thread.
905 PluginFinder::GetInstance()->Init();
907 #if defined(ENABLE_PLUGIN_INSTALLATION)
908 DCHECK(!plugins_resource_service_.get());
909 plugins_resource_service_ = new PluginsResourceService(local_state());
910 plugins_resource_service_->Init();
911 #endif
912 #endif // defined(ENABLE_PLUGINS)
914 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
915 if (!command_line.HasSwitch(switches::kDisableWebResources)) {
916 DCHECK(!promo_resource_service_.get());
917 promo_resource_service_ = new PromoResourceService;
918 promo_resource_service_->StartAfterDelay();
921 #if !defined(OS_ANDROID)
922 if (browser_defaults::bookmarks_enabled &&
923 BookmarkPromptController::IsEnabled()) {
924 bookmark_prompt_controller_.reset(new BookmarkPromptController());
926 #endif
928 #if !defined(OS_ANDROID) && !defined(OS_IOS)
929 storage_monitor::StorageMonitor::Create();
930 #endif
932 platform_part_->PreMainMessageLoopRun();
935 void BrowserProcessImpl::CreateIconManager() {
936 DCHECK(!created_icon_manager_ && icon_manager_.get() == NULL);
937 created_icon_manager_ = true;
938 icon_manager_.reset(new IconManager);
941 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
942 DCHECK(intranet_redirect_detector_.get() == NULL);
943 scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector(
944 new IntranetRedirectDetector);
945 intranet_redirect_detector_.swap(intranet_redirect_detector);
948 void BrowserProcessImpl::CreateNotificationUIManager() {
949 #if defined(ENABLE_NOTIFICATIONS)
950 DCHECK(notification_ui_manager_.get() == NULL);
951 notification_ui_manager_.reset(NotificationUIManager::Create(local_state()));
952 created_notification_ui_manager_ = true;
953 #endif
956 void BrowserProcessImpl::CreateBackgroundModeManager() {
957 DCHECK(background_mode_manager_.get() == NULL);
958 background_mode_manager_.reset(
959 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
960 &profile_manager()->GetProfileInfoCache()));
963 void BrowserProcessImpl::CreateStatusTray() {
964 DCHECK(status_tray_.get() == NULL);
965 status_tray_.reset(StatusTray::Create());
968 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
969 #if defined(ENABLE_FULL_PRINTING)
970 DCHECK(print_preview_dialog_controller_.get() == NULL);
971 print_preview_dialog_controller_ =
972 new printing::PrintPreviewDialogController();
973 #else
974 NOTIMPLEMENTED();
975 #endif
978 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
979 #if defined(ENABLE_FULL_PRINTING)
980 DCHECK(background_printing_manager_.get() == NULL);
981 background_printing_manager_.reset(new printing::BackgroundPrintingManager());
982 #else
983 NOTIMPLEMENTED();
984 #endif
987 void BrowserProcessImpl::CreateSafeBrowsingService() {
988 DCHECK(safe_browsing_service_.get() == NULL);
989 // Set this flag to true so that we don't retry indefinitely to
990 // create the service class if there was an error.
991 created_safe_browsing_service_ = true;
992 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
993 safe_browsing_service_ = SafeBrowsingService::CreateSafeBrowsingService();
994 safe_browsing_service_->Initialize();
995 #endif
998 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
999 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) {
1000 scoped_refptr<ShellIntegration::DefaultWebClientWorker>
1001 set_browser_worker = new ShellIntegration::DefaultBrowserWorker(NULL);
1002 set_browser_worker->StartSetAsDefault();
1006 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1007 bool value = local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
1008 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value);
1011 void BrowserProcessImpl::ApplyMetricsReportingPolicy() {
1012 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS)
1013 CHECK(BrowserThread::PostTask(
1014 BrowserThread::FILE, FROM_HERE,
1015 base::Bind(
1016 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent),
1017 local_state()->GetBoolean(prefs::kMetricsReportingEnabled))));
1018 #endif
1021 // Mac is currently not supported.
1022 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1024 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1025 // Check if browser is in the background and if it needs to be restarted to
1026 // apply a pending update.
1027 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1028 upgrade_util::IsUpdatePendingRestart();
1031 // Switches to add when auto-restarting Chrome.
1032 const char* const kSwitchesToAddOnAutorestart[] = {
1033 switches::kNoStartupWindow
1036 void BrowserProcessImpl::RestartBackgroundInstance() {
1037 CommandLine* old_cl = CommandLine::ForCurrentProcess();
1038 scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl->GetProgram()));
1040 std::map<std::string, CommandLine::StringType> switches =
1041 old_cl->GetSwitches();
1043 switches::RemoveSwitchesForAutostart(&switches);
1045 // Append the rest of the switches (along with their values, if any)
1046 // to the new command line
1047 for (std::map<std::string, CommandLine::StringType>::const_iterator i =
1048 switches.begin(); i != switches.end(); ++i) {
1049 CommandLine::StringType switch_value = i->second;
1050 if (switch_value.length() > 0) {
1051 new_cl->AppendSwitchNative(i->first, i->second);
1052 } else {
1053 new_cl->AppendSwitch(i->first);
1057 // Ensure that our desired switches are set on the new process.
1058 for (size_t i = 0; i < arraysize(kSwitchesToAddOnAutorestart); ++i) {
1059 if (!new_cl->HasSwitch(kSwitchesToAddOnAutorestart[i]))
1060 new_cl->AppendSwitch(kSwitchesToAddOnAutorestart[i]);
1063 DLOG(WARNING) << "Shutting down current instance of the browser.";
1064 chrome::AttemptExit();
1066 // Transfer ownership to Upgrade.
1067 upgrade_util::SetNewCommandLine(new_cl.release());
1070 void BrowserProcessImpl::OnAutoupdateTimer() {
1071 if (CanAutorestartForUpdate()) {
1072 DLOG(WARNING) << "Detected update. Restarting browser.";
1073 RestartBackgroundInstance();
1077 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)