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"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/command_line.h"
15 #include "base/debug/alias.h"
16 #include "base/file_util.h"
17 #include "base/path_service.h"
18 #include "base/prefs/json_pref_store.h"
19 #include "base/prefs/pref_registry_simple.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/synchronization/waitable_event.h"
22 #include "base/threading/thread.h"
23 #include "base/threading/thread_restrictions.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/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/event_router_forwarder.h"
36 #include "chrome/browser/extensions/extension_renderer_state.h"
37 #include "chrome/browser/first_run/upgrade_util.h"
38 #include "chrome/browser/gpu/gl_string_manager.h"
39 #include "chrome/browser/gpu/gpu_mode_manager.h"
40 #include "chrome/browser/icon_manager.h"
41 #include "chrome/browser/idle.h"
42 #include "chrome/browser/intranet_redirect_detector.h"
43 #include "chrome/browser/io_thread.h"
44 #include "chrome/browser/lifetime/application_lifetime.h"
45 #include "chrome/browser/media_galleries/media_file_system_registry.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/policy/policy_service.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/thumbnails/render_widget_snapshot_taker.h"
68 #include "chrome/browser/ui/bookmarks/bookmark_prompt_controller.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_notification_types.h"
73 #include "chrome/common/chrome_paths.h"
74 #include "chrome/common/chrome_switches.h"
75 #include "chrome/common/extensions/extension_l10n_util.h"
76 #include "chrome/common/extensions/permissions/chrome_api_permissions.h"
77 #include "chrome/common/extensions/permissions/permissions_info.h"
78 #include "chrome/common/pref_names.h"
79 #include "chrome/common/switch_utils.h"
80 #include "chrome/common/url_constants.h"
81 #include "chrome/installer/util/google_update_constants.h"
82 #include "content/public/browser/browser_thread.h"
83 #include "content/public/browser/child_process_security_policy.h"
84 #include "content/public/browser/notification_details.h"
85 #include "content/public/browser/plugin_service.h"
86 #include "content/public/browser/render_process_host.h"
87 #include "content/public/browser/resource_dispatcher_host.h"
88 #include "extensions/common/constants.h"
89 #include "net/socket/client_socket_pool_manager.h"
90 #include "net/url_request/url_request_context_getter.h"
91 #include "ui/base/l10n/l10n_util.h"
93 #if defined(ENABLE_CONFIGURATION_POLICY)
94 #include "chrome/browser/policy/browser_policy_connector.h"
96 #include "chrome/browser/policy/policy_service_stub.h"
97 #endif // defined(ENABLE_CONFIGURATION_POLICY)
99 #if defined(ENABLE_MESSAGE_CENTER)
100 #include "ui/message_center/message_center.h"
104 #include "base/win/windows_version.h"
105 #include "ui/views/focus/view_storage.h"
106 #if defined(USE_AURA)
107 #include "chrome/browser/metro_viewer/metro_viewer_process_host_win.h"
109 #elif defined(OS_MACOSX)
110 #include "chrome/browser/chrome_browser_main_mac.h"
113 #if defined(USE_AURA)
114 #include "ui/aura/env.h"
117 #if defined(OS_CHROMEOS)
118 #include "chrome/browser/chromeos/memory/oom_priority_manager.h"
119 #endif // defined(OS_CHROMEOS)
121 #if defined(ENABLE_PLUGIN_INSTALLATION)
122 #include "chrome/browser/plugins/plugins_resource_service.h"
125 #if defined(OS_MACOSX)
126 #include "apps/app_shim/app_shim_host_manager_mac.h"
129 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
130 // How often to check if the persistent instance of Chrome needs to restart
131 // to install an update.
132 static const int kUpdateCheckIntervalHours
= 6;
136 // Attest to the fact that the call to the file thread to save preferences has
137 // run, and it is safe to terminate. This avoids the potential of some other
138 // task prematurely terminating our waiting message loop by posting a
140 static bool g_end_session_file_thread_has_completed
= false;
144 // How long to wait for the File thread to complete during EndSession, on
145 // Linux. We have a timeout here because we're unable to run the UI messageloop
146 // and there's some deadlock risk. Our only option is to exit anyway.
147 static const int kEndSessionTimeoutSeconds
= 10;
150 using content::BrowserThread
;
151 using content::ChildProcessSecurityPolicy
;
152 using content::PluginService
;
153 using content::ResourceDispatcherHost
;
155 BrowserProcessImpl::BrowserProcessImpl(
156 base::SequencedTaskRunner
* local_state_task_runner
,
157 const CommandLine
& command_line
)
158 : created_metrics_service_(false),
159 created_watchdog_thread_(false),
160 created_browser_policy_connector_(false),
161 created_profile_manager_(false),
162 created_local_state_(false),
163 created_icon_manager_(false),
164 created_notification_ui_manager_(false),
165 created_safe_browsing_service_(false),
166 module_ref_count_(0),
168 checked_for_new_frames_(false),
169 using_new_frames_(false),
170 render_widget_snapshot_taker_(new RenderWidgetSnapshotTaker
),
171 download_status_updater_(new DownloadStatusUpdater
),
172 local_state_task_runner_(local_state_task_runner
) {
173 g_browser_process
= this;
175 #if defined(ENABLE_PRINTING)
176 // Must be created after the NotificationService.
177 print_job_manager_
.reset(new printing::PrintJobManager
);
180 net_log_
.reset(new ChromeNetLog
);
182 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
183 extensions::kExtensionScheme
);
184 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
185 chrome::kExtensionResourceScheme
);
186 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme(
187 chrome::kChromeSearchScheme
);
189 #if defined(OS_MACOSX)
193 extensions::PermissionsInfo::GetInstance()->InitializeWithDelegate(
194 extensions::ChromeAPIPermissions());
195 extension_event_router_forwarder_
= new extensions::EventRouterForwarder
;
196 ExtensionRendererState::GetInstance()->Init();
198 #if defined(ENABLE_MESSAGE_CENTER)
199 message_center::MessageCenter::Initialize();
203 BrowserProcessImpl::~BrowserProcessImpl() {
204 tracked_objects::ThreadData::EnsureCleanupWasCalled(4);
206 g_browser_process
= NULL
;
209 void BrowserProcessImpl::StartTearDown() {
210 #if defined(ENABLE_AUTOMATION)
211 // Delete the AutomationProviderList before NotificationService,
212 // since it may try to unregister notifications
213 // Both NotificationService and AutomationProvider are singleton instances in
214 // the BrowserProcess. Since AutomationProvider may have some active
215 // notification observers, it is essential that it gets destroyed before the
216 // NotificationService. NotificationService won't be destroyed until after
217 // this destructor is run.
218 automation_provider_list_
.reset();
221 // We need to shutdown the SdchDictionaryFetcher as it regularly holds
222 // a pointer to a URLFetcher, and that URLFetcher (upon destruction) will do
223 // a PostDelayedTask onto the IO thread. This shutdown call will both discard
224 // any pending URLFetchers, and avoid creating any more.
225 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
226 base::Bind(&SdchDictionaryFetcher::Shutdown
));
228 // We need to destroy the MetricsService, VariationsService,
229 // IntranetRedirectDetector, PromoResourceService, and SafeBrowsing
230 // ClientSideDetectionService (owned by the SafeBrowsingService) before the
231 // io_thread_ gets destroyed, since their destructors can call the URLFetcher
232 // destructor, which does a PostDelayedTask operation on the IO thread. (The
233 // IO thread will handle that URLFetcher operation before going away.)
234 metrics_service_
.reset();
235 variations_service_
.reset();
236 intranet_redirect_detector_
.reset();
237 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
238 if (safe_browsing_service_
.get())
239 safe_browsing_service()->ShutDown();
242 // Need to clear the desktop notification balloons before the io_thread_ and
243 // before the profiles, since if there are any still showing we will access
244 // those things during teardown.
245 notification_ui_manager_
.reset();
247 // Need to clear profiles (download managers) before the io_thread_.
248 profile_manager_
.reset();
250 #if !defined(OS_ANDROID)
251 // Debugger must be cleaned up before IO thread and NotificationService.
252 remote_debugging_server_
.reset();
255 ExtensionRendererState::GetInstance()->Shutdown();
257 #if defined(ENABLE_MESSAGE_CENTER)
258 message_center::MessageCenter::Shutdown();
261 #if defined(ENABLE_CONFIGURATION_POLICY)
262 // The policy providers managed by |browser_policy_connector_| need to shut
263 // down while the IO and FILE threads are still alive.
264 if (browser_policy_connector_
)
265 browser_policy_connector_
->Shutdown();
268 // Stop the watchdog thread before stopping other threads.
269 watchdog_thread_
.reset();
271 #if defined(USE_AURA)
272 // Delete aura after the metrics service has been deleted as it accesses
273 // monitor information.
274 aura::Env::DeleteInstance();
277 #if defined(OS_MACOSX)
278 app_shim_host_manager_
.reset();
282 void BrowserProcessImpl::PostDestroyThreads() {
283 // With the file_thread_ flushed, we can release any icon resources.
284 icon_manager_
.reset();
286 // Reset associated state right after actual thread is stopped,
287 // as io_thread_.global_ cleanup happens in CleanUp on the IO
288 // thread, i.e. as the thread exits its message loop.
290 // This is important also because in various places, the
291 // IOThread object being NULL is considered synonymous with the
292 // IO thread having stopped.
297 // Send a QuitTask to the given MessageLoop when the (file) thread has processed
298 // our (other) recent requests (to save preferences).
299 // Change the boolean so that the receiving thread will know that we did indeed
300 // send the QuitTask that terminated the message loop.
301 static void PostQuit(MessageLoop
* message_loop
) {
302 g_end_session_file_thread_has_completed
= true;
303 message_loop
->PostTask(FROM_HERE
, MessageLoop::QuitClosure());
305 #elif defined(USE_X11)
306 static void Signal(base::WaitableEvent
* event
) {
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
);
325 return module_ref_count_
;
328 unsigned int BrowserProcessImpl::ReleaseModule() {
329 DCHECK(CalledOnValidThread());
330 DCHECK_NE(0u, 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_
->OnQuit();
340 print_job_manager_
.reset();
343 CHECK(MessageLoop::current()->is_running());
345 #if defined(OS_MACOSX)
346 MessageLoop::current()->PostTask(
348 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop
));
350 MessageLoop::current()->Quit();
352 return module_ref_count_
;
355 void BrowserProcessImpl::EndSession() {
356 // Mark all the profiles as clean.
357 ProfileManager
* pm
= profile_manager();
358 std::vector
<Profile
*> profiles(pm
->GetLoadedProfiles());
359 for (size_t i
= 0; i
< profiles
.size(); ++i
)
360 profiles
[i
]->SetExitType(Profile::EXIT_SESSION_ENDED
);
362 // Tell the metrics service it was cleanly shutdown.
363 MetricsService
* metrics
= g_browser_process
->metrics_service();
364 if (metrics
&& local_state()) {
365 metrics
->RecordStartOfSessionEnd();
367 // MetricsService lazily writes to prefs, force it to write now.
368 local_state()->CommitPendingWrite();
371 // http://crbug.com/125207
372 base::ThreadRestrictions::ScopedAllowWait allow_wait
;
374 // We must write that the profile and metrics service shutdown cleanly,
375 // otherwise on startup we'll think we crashed. So we block until done and
376 // then proceed with normal shutdown.
378 // Can't run a local loop on linux. Instead create a waitable event.
379 scoped_ptr
<base::WaitableEvent
> done_writing(
380 new base::WaitableEvent(false, false));
381 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
382 base::Bind(Signal
, done_writing
.get()));
383 // If all file writes haven't cleared in the timeout, leak the WaitableEvent
384 // so that there's no race to reference it in Signal().
385 if (!done_writing
->TimedWait(
386 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds
))) {
387 ignore_result(done_writing
.release());
390 #elif defined(OS_WIN)
391 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE
,
392 base::Bind(PostQuit
, MessageLoop::current()));
393 int quits_received
= 0;
395 MessageLoop::current()->Run();
397 } while (!g_end_session_file_thread_has_completed
);
398 // If we did get extra quits, then we should re-post them to the message loop.
399 while (--quits_received
> 0)
400 MessageLoop::current()->PostTask(FROM_HERE
, MessageLoop::QuitClosure());
406 MetricsService
* BrowserProcessImpl::metrics_service() {
407 DCHECK(CalledOnValidThread());
408 if (!created_metrics_service_
)
409 CreateMetricsService();
410 return metrics_service_
.get();
413 IOThread
* BrowserProcessImpl::io_thread() {
414 DCHECK(CalledOnValidThread());
415 DCHECK(io_thread_
.get());
416 return io_thread_
.get();
419 WatchDogThread
* BrowserProcessImpl::watchdog_thread() {
420 DCHECK(CalledOnValidThread());
421 if (!created_watchdog_thread_
)
422 CreateWatchdogThread();
423 DCHECK(watchdog_thread_
.get() != NULL
);
424 return watchdog_thread_
.get();
427 ProfileManager
* BrowserProcessImpl::profile_manager() {
428 DCHECK(CalledOnValidThread());
429 if (!created_profile_manager_
)
430 CreateProfileManager();
431 return profile_manager_
.get();
434 PrefService
* BrowserProcessImpl::local_state() {
435 DCHECK(CalledOnValidThread());
436 if (!created_local_state_
)
438 return local_state_
.get();
441 net::URLRequestContextGetter
* BrowserProcessImpl::system_request_context() {
442 DCHECK(CalledOnValidThread());
443 return io_thread()->system_url_request_context_getter();
446 chrome_variations::VariationsService
* BrowserProcessImpl::variations_service() {
447 DCHECK(CalledOnValidThread());
448 if (!variations_service_
.get()) {
449 variations_service_
.reset(
450 chrome_variations::VariationsService::Create(local_state()));
452 return variations_service_
.get();
455 #if defined(OS_CHROMEOS)
456 chromeos::OomPriorityManager
* BrowserProcessImpl::oom_priority_manager() {
457 DCHECK(CalledOnValidThread());
458 if (!oom_priority_manager_
.get())
459 oom_priority_manager_
.reset(new chromeos::OomPriorityManager());
460 return oom_priority_manager_
.get();
462 #endif // defined(OS_CHROMEOS)
464 extensions::EventRouterForwarder
*
465 BrowserProcessImpl::extension_event_router_forwarder() {
466 return extension_event_router_forwarder_
.get();
469 NotificationUIManager
* BrowserProcessImpl::notification_ui_manager() {
470 DCHECK(CalledOnValidThread());
471 if (!created_notification_ui_manager_
)
472 CreateNotificationUIManager();
473 return notification_ui_manager_
.get();
476 #if defined(ENABLE_MESSAGE_CENTER)
477 message_center::MessageCenter
* BrowserProcessImpl::message_center() {
478 DCHECK(CalledOnValidThread());
479 return message_center::MessageCenter::Get();
483 policy::BrowserPolicyConnector
* BrowserProcessImpl::browser_policy_connector() {
484 DCHECK(CalledOnValidThread());
485 #if defined(ENABLE_CONFIGURATION_POLICY)
486 if (!created_browser_policy_connector_
) {
487 DCHECK(!browser_policy_connector_
);
488 browser_policy_connector_
.reset(new policy::BrowserPolicyConnector());
489 created_browser_policy_connector_
= true;
491 return browser_policy_connector_
.get();
497 policy::PolicyService
* BrowserProcessImpl::policy_service() {
498 #if defined(ENABLE_CONFIGURATION_POLICY)
499 return browser_policy_connector()->GetPolicyService();
501 if (!policy_service_
.get())
502 policy_service_
.reset(new policy::PolicyServiceStub());
503 return policy_service_
.get();
507 IconManager
* BrowserProcessImpl::icon_manager() {
508 DCHECK(CalledOnValidThread());
509 if (!created_icon_manager_
)
511 return icon_manager_
.get();
514 GLStringManager
* BrowserProcessImpl::gl_string_manager() {
515 DCHECK(CalledOnValidThread());
516 if (!gl_string_manager_
.get())
517 gl_string_manager_
.reset(new GLStringManager());
518 return gl_string_manager_
.get();
521 GpuModeManager
* BrowserProcessImpl::gpu_mode_manager() {
522 DCHECK(CalledOnValidThread());
523 if (!gpu_mode_manager_
.get())
524 gpu_mode_manager_
.reset(new GpuModeManager());
525 return gpu_mode_manager_
.get();
528 RenderWidgetSnapshotTaker
* BrowserProcessImpl::GetRenderWidgetSnapshotTaker() {
529 return render_widget_snapshot_taker_
.get();
532 AutomationProviderList
* BrowserProcessImpl::GetAutomationProviderList() {
533 DCHECK(CalledOnValidThread());
534 #if defined(ENABLE_AUTOMATION)
535 if (automation_provider_list_
.get() == NULL
)
536 automation_provider_list_
.reset(new AutomationProviderList());
537 return automation_provider_list_
.get();
543 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler(
545 chrome::HostDesktopType host_desktop_type
,
546 const std::string
& ip
,
548 const std::string
& frontend_url
) {
549 DCHECK(CalledOnValidThread());
550 #if !defined(OS_ANDROID)
551 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser
552 // is started with several profiles or existing browser process is reused.
553 if (!remote_debugging_server_
.get()) {
554 remote_debugging_server_
.reset(
555 new RemoteDebuggingServer(profile
, host_desktop_type
, ip
, port
,
561 bool BrowserProcessImpl::IsShuttingDown() {
562 DCHECK(CalledOnValidThread());
563 return did_start_
&& 0 == module_ref_count_
;
566 printing::PrintJobManager
* BrowserProcessImpl::print_job_manager() {
567 // TODO(abarth): DCHECK(CalledOnValidThread());
568 // http://code.google.com/p/chromium/issues/detail?id=6828
569 // print_job_manager_ is initialized in the constructor and destroyed in the
570 // destructor, so it should always be valid.
571 DCHECK(print_job_manager_
.get());
572 return print_job_manager_
.get();
575 printing::PrintPreviewDialogController
*
576 BrowserProcessImpl::print_preview_dialog_controller() {
577 #if defined(ENABLE_PRINTING)
578 DCHECK(CalledOnValidThread());
579 if (!print_preview_dialog_controller_
.get())
580 CreatePrintPreviewDialogController();
581 return print_preview_dialog_controller_
.get();
588 printing::BackgroundPrintingManager
*
589 BrowserProcessImpl::background_printing_manager() {
590 #if defined(ENABLE_PRINTING)
591 DCHECK(CalledOnValidThread());
592 if (!background_printing_manager_
.get())
593 CreateBackgroundPrintingManager();
594 return background_printing_manager_
.get();
601 IntranetRedirectDetector
* BrowserProcessImpl::intranet_redirect_detector() {
602 DCHECK(CalledOnValidThread());
603 if (!intranet_redirect_detector_
.get())
604 CreateIntranetRedirectDetector();
605 return intranet_redirect_detector_
.get();
608 const std::string
& BrowserProcessImpl::GetApplicationLocale() {
609 DCHECK(!locale_
.empty());
613 void BrowserProcessImpl::SetApplicationLocale(const std::string
& locale
) {
615 extension_l10n_util::SetProcessLocale(locale
);
616 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale
);
619 DownloadStatusUpdater
* BrowserProcessImpl::download_status_updater() {
620 return download_status_updater_
.get();
623 BookmarkPromptController
* BrowserProcessImpl::bookmark_prompt_controller() {
624 #if defined(OS_ANDROID)
627 return bookmark_prompt_controller_
.get();
631 chrome::MediaFileSystemRegistry
*
632 BrowserProcessImpl::media_file_system_registry() {
633 if (!media_file_system_registry_
)
634 media_file_system_registry_
.reset(new chrome::MediaFileSystemRegistry());
635 return media_file_system_registry_
.get();
639 void BrowserProcessImpl::PlatformSpecificCommandLineProcessing(
640 const CommandLine
& command_line
) {
644 bool BrowserProcessImpl::created_local_state() const {
645 return created_local_state_
;
649 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple
* registry
) {
650 registry
->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled
,
652 // This policy needs to be defined before the net subsystem is initialized,
654 registry
->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy
,
655 net::kDefaultMaxSocketsPerProxyServer
);
657 // This is observed by ChildProcessSecurityPolicy, which lives in content/
658 // though, so it can't register itself.
659 registry
->RegisterListPref(prefs::kDisabledSchemes
);
661 registry
->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt
, false);
664 if (base::win::GetVersion() >= base::win::VERSION_WIN8
)
665 registry
->RegisterBooleanPref(prefs::kRestartSwitchMode
, false);
668 // TODO(brettw,*): this comment about ResourceBundle was here since
669 // initial commit. This comment seems unrelated, bit-rotten and
670 // a candidate for removal.
671 // Initialize ResourceBundle which handles files loaded from external
672 // sources. This has to be done before uninstall code path and before prefs
674 registry
->RegisterStringPref(prefs::kApplicationLocale
, std::string());
675 #if defined(OS_CHROMEOS)
676 registry
->RegisterStringPref(prefs::kOwnerLocale
, std::string());
677 registry
->RegisterStringPref(prefs::kHardwareKeyboardLayout
,
679 #endif // defined(OS_CHROMEOS)
680 #if !defined(OS_CHROMEOS)
681 registry
->RegisterBooleanPref(
682 prefs::kMetricsReportingEnabled
,
683 GoogleUpdateSettings::GetCollectStatsConsent());
684 #endif // !defined(OS_CHROMEOS)
687 DownloadRequestLimiter
* BrowserProcessImpl::download_request_limiter() {
688 DCHECK(CalledOnValidThread());
689 if (!download_request_limiter_
)
690 download_request_limiter_
= new DownloadRequestLimiter();
691 return download_request_limiter_
;
694 BackgroundModeManager
* BrowserProcessImpl::background_mode_manager() {
695 DCHECK(CalledOnValidThread());
696 #if defined(ENABLE_BACKGROUND)
697 if (!background_mode_manager_
.get())
698 CreateBackgroundModeManager();
699 return background_mode_manager_
.get();
706 StatusTray
* BrowserProcessImpl::status_tray() {
707 DCHECK(CalledOnValidThread());
708 if (!status_tray_
.get())
710 return status_tray_
.get();
714 SafeBrowsingService
* BrowserProcessImpl::safe_browsing_service() {
715 DCHECK(CalledOnValidThread());
716 if (!created_safe_browsing_service_
)
717 CreateSafeBrowsingService();
718 return safe_browsing_service_
.get();
721 safe_browsing::ClientSideDetectionService
*
722 BrowserProcessImpl::safe_browsing_detection_service() {
723 DCHECK(CalledOnValidThread());
724 if (safe_browsing_service())
725 return safe_browsing_service()->safe_browsing_detection_service();
729 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
730 void BrowserProcessImpl::StartAutoupdateTimer() {
731 autoupdate_timer_
.Start(FROM_HERE
,
732 base::TimeDelta::FromHours(kUpdateCheckIntervalHours
),
734 &BrowserProcessImpl::OnAutoupdateTimer
);
738 ChromeNetLog
* BrowserProcessImpl::net_log() {
739 return net_log_
.get();
742 prerender::PrerenderTracker
* BrowserProcessImpl::prerender_tracker() {
743 if (!prerender_tracker_
.get())
744 prerender_tracker_
.reset(new prerender::PrerenderTracker
);
746 return prerender_tracker_
.get();
749 ComponentUpdateService
* BrowserProcessImpl::component_updater() {
750 if (!component_updater_
.get()) {
751 ComponentUpdateService::Configurator
* configurator
=
752 MakeChromeComponentUpdaterConfigurator(
753 CommandLine::ForCurrentProcess(),
754 io_thread()->system_url_request_context_getter());
755 // Creating the component updater does not do anything, components
756 // need to be registered and Start() needs to be called.
757 component_updater_
.reset(ComponentUpdateServiceFactory(configurator
));
759 return component_updater_
.get();
762 CRLSetFetcher
* BrowserProcessImpl::crl_set_fetcher() {
763 if (!crl_set_fetcher_
.get())
764 crl_set_fetcher_
= new CRLSetFetcher();
765 return crl_set_fetcher_
.get();
768 PnaclComponentInstaller
* BrowserProcessImpl::pnacl_component_installer() {
769 if (!pnacl_component_installer_
.get())
770 pnacl_component_installer_
.reset(new PnaclComponentInstaller());
771 return pnacl_component_installer_
.get();
774 void BrowserProcessImpl::ResourceDispatcherHostCreated() {
775 resource_dispatcher_host_delegate_
.reset(
776 new ChromeResourceDispatcherHostDelegate(prerender_tracker()));
777 ResourceDispatcherHost::Get()->SetDelegate(
778 resource_dispatcher_host_delegate_
.get());
780 pref_change_registrar_
.Add(
781 prefs::kAllowCrossOriginAuthPrompt
,
782 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy
,
783 base::Unretained(this)));
784 ApplyAllowCrossOriginAuthPromptPolicy();
787 void BrowserProcessImpl::CreateMetricsService() {
788 DCHECK(!created_metrics_service_
&& metrics_service_
.get() == NULL
);
789 created_metrics_service_
= true;
791 metrics_service_
.reset(new MetricsService
);
794 void BrowserProcessImpl::CreateWatchdogThread() {
795 DCHECK(!created_watchdog_thread_
&& watchdog_thread_
.get() == NULL
);
796 created_watchdog_thread_
= true;
798 scoped_ptr
<WatchDogThread
> thread(new WatchDogThread());
799 if (!thread
->Start())
801 watchdog_thread_
.swap(thread
);
804 void BrowserProcessImpl::CreateProfileManager() {
805 DCHECK(!created_profile_manager_
&& profile_manager_
.get() == NULL
);
806 created_profile_manager_
= true;
808 base::FilePath user_data_dir
;
809 PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
);
810 profile_manager_
.reset(new ProfileManager(user_data_dir
));
813 void BrowserProcessImpl::CreateLocalState() {
814 DCHECK(!created_local_state_
&& local_state_
.get() == NULL
);
815 created_local_state_
= true;
817 base::FilePath local_state_path
;
818 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE
, &local_state_path
));
819 scoped_refptr
<PrefRegistrySimple
> pref_registry
= new PrefRegistrySimple
;
821 // Register local state preferences.
822 chrome::RegisterLocalState(pref_registry
);
825 chrome_prefs::CreateLocalState(local_state_path
,
826 local_state_task_runner_
,
832 pref_change_registrar_
.Init(local_state_
.get());
834 // Initialize the notification for the default browser setting policy.
835 pref_change_registrar_
.Add(
836 prefs::kDefaultBrowserSettingEnabled
,
837 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy
,
838 base::Unretained(this)));
840 int max_per_proxy
= local_state_
->GetInteger(prefs::kMaxConnectionsPerProxy
);
841 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server(
842 net::HttpNetworkSession::NORMAL_SOCKET_POOL
,
843 std::max(std::min(max_per_proxy
, 99),
844 net::ClientSocketPoolManager::max_sockets_per_group(
845 net::HttpNetworkSession::NORMAL_SOCKET_POOL
)));
847 pref_change_registrar_
.Add(
848 prefs::kDisabledSchemes
,
849 base::Bind(&BrowserProcessImpl::ApplyDisabledSchemesPolicy
,
850 base::Unretained(this)));
851 ApplyDisabledSchemesPolicy();
854 void BrowserProcessImpl::PreCreateThreads() {
855 io_thread_
.reset(new IOThread(local_state(), policy_service(), net_log_
.get(),
856 extension_event_router_forwarder_
.get()));
859 void BrowserProcessImpl::PreMainMessageLoopRun() {
860 #if defined(ENABLE_CONFIGURATION_POLICY)
861 // browser_policy_connector() is created very early because local_state()
862 // needs policy to be initialized with the managed preference values.
863 // However, policy fetches from the network and loading of disk caches
864 // requires that threads are running; this Init() call lets the connector
865 // resume its initialization now that the loops are spinning and the
866 // system request context is available for the fetchers.
867 browser_policy_connector()->Init(local_state(), system_request_context());
870 if (local_state_
->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled
))
871 ApplyDefaultBrowserPolicy();
873 #if defined(ENABLE_PLUGINS)
874 PluginService
* plugin_service
= PluginService::GetInstance();
875 plugin_service
->SetFilter(ChromePluginServiceFilter::GetInstance());
876 plugin_service
->StartWatchingPlugins();
878 #if defined(OS_POSIX)
879 // Also find plugins in a user-specific plugins dir,
880 // e.g. ~/.config/chromium/Plugins.
881 base::FilePath user_data_dir
;
882 if (PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
883 plugin_service
->AddExtraPluginDir(user_data_dir
.Append("Plugins"));
886 // Triggers initialization of the singleton instance on UI thread.
887 PluginFinder::GetInstance()->Init();
889 #if defined(ENABLE_PLUGIN_INSTALLATION)
890 DCHECK(!plugins_resource_service_
.get());
891 plugins_resource_service_
= new PluginsResourceService(local_state());
892 plugins_resource_service_
->Init();
894 #endif // defined(ENABLE_PLUGINS)
896 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
897 if (!command_line
.HasSwitch(switches::kDisableWebResources
)) {
898 DCHECK(!promo_resource_service_
.get());
899 promo_resource_service_
= new PromoResourceService
;
900 promo_resource_service_
->StartAfterDelay();
903 #if !defined(OS_ANDROID)
904 if (browser_defaults::bookmarks_enabled
&&
905 BookmarkPromptController::IsEnabled()) {
906 bookmark_prompt_controller_
.reset(new BookmarkPromptController());
910 #if defined(OS_MACOSX)
911 app_shim_host_manager_
.reset(new AppShimHostManager
);
915 void BrowserProcessImpl::CreateIconManager() {
916 DCHECK(!created_icon_manager_
&& icon_manager_
.get() == NULL
);
917 created_icon_manager_
= true;
918 icon_manager_
.reset(new IconManager
);
921 void BrowserProcessImpl::CreateIntranetRedirectDetector() {
922 DCHECK(intranet_redirect_detector_
.get() == NULL
);
923 scoped_ptr
<IntranetRedirectDetector
> intranet_redirect_detector(
924 new IntranetRedirectDetector
);
925 intranet_redirect_detector_
.swap(intranet_redirect_detector
);
928 void BrowserProcessImpl::CreateNotificationUIManager() {
929 #if defined(ENABLE_NOTIFICATIONS)
930 DCHECK(notification_ui_manager_
.get() == NULL
);
931 notification_ui_manager_
.reset(NotificationUIManager::Create(local_state()));
932 created_notification_ui_manager_
= true;
936 void BrowserProcessImpl::CreateBackgroundModeManager() {
937 DCHECK(background_mode_manager_
.get() == NULL
);
938 background_mode_manager_
.reset(
939 new BackgroundModeManager(CommandLine::ForCurrentProcess(),
940 &profile_manager()->GetProfileInfoCache()));
943 void BrowserProcessImpl::CreateStatusTray() {
944 DCHECK(status_tray_
.get() == NULL
);
945 status_tray_
.reset(StatusTray::Create());
948 void BrowserProcessImpl::CreatePrintPreviewDialogController() {
949 #if defined(ENABLE_PRINTING)
950 DCHECK(print_preview_dialog_controller_
.get() == NULL
);
951 print_preview_dialog_controller_
=
952 new printing::PrintPreviewDialogController();
958 void BrowserProcessImpl::CreateBackgroundPrintingManager() {
959 #if defined(ENABLE_PRINTING)
960 DCHECK(background_printing_manager_
.get() == NULL
);
961 background_printing_manager_
.reset(new printing::BackgroundPrintingManager());
967 void BrowserProcessImpl::CreateSafeBrowsingService() {
968 DCHECK(safe_browsing_service_
.get() == NULL
);
969 // Set this flag to true so that we don't retry indefinitely to
970 // create the service class if there was an error.
971 created_safe_browsing_service_
= true;
972 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
973 safe_browsing_service_
= SafeBrowsingService::CreateSafeBrowsingService();
974 safe_browsing_service_
->Initialize();
978 void BrowserProcessImpl::ApplyDisabledSchemesPolicy() {
979 std::set
<std::string
> schemes
;
980 const ListValue
* scheme_list
=
981 local_state()->GetList(prefs::kDisabledSchemes
);
982 for (ListValue::const_iterator iter
= scheme_list
->begin();
983 iter
!= scheme_list
->end(); ++iter
) {
985 if ((*iter
)->GetAsString(&scheme
))
986 schemes
.insert(scheme
);
988 ChildProcessSecurityPolicy::GetInstance()->RegisterDisabledSchemes(schemes
);
991 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() {
992 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled
)) {
993 scoped_refptr
<ShellIntegration::DefaultWebClientWorker
>
994 set_browser_worker
= new ShellIntegration::DefaultBrowserWorker(NULL
);
995 set_browser_worker
->StartSetAsDefault();
999 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() {
1000 bool value
= local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt
);
1001 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value
);
1004 // Mac is currently not supported.
1005 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)
1007 bool BrowserProcessImpl::CanAutorestartForUpdate() const {
1008 // Check if browser is in the background and if it needs to be restarted to
1009 // apply a pending update.
1010 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() &&
1011 upgrade_util::IsUpdatePendingRestart();
1014 // Switches to add when auto-restarting Chrome.
1015 const char* const kSwitchesToAddOnAutorestart
[] = {
1016 switches::kNoStartupWindow
1019 void BrowserProcessImpl::RestartBackgroundInstance() {
1020 CommandLine
* old_cl
= CommandLine::ForCurrentProcess();
1021 scoped_ptr
<CommandLine
> new_cl(new CommandLine(old_cl
->GetProgram()));
1023 std::map
<std::string
, CommandLine::StringType
> switches
=
1024 old_cl
->GetSwitches();
1026 switches::RemoveSwitchesForAutostart(&switches
);
1028 // Append the rest of the switches (along with their values, if any)
1029 // to the new command line
1030 for (std::map
<std::string
, CommandLine::StringType
>::const_iterator i
=
1031 switches
.begin(); i
!= switches
.end(); ++i
) {
1032 CommandLine::StringType switch_value
= i
->second
;
1033 if (switch_value
.length() > 0) {
1034 new_cl
->AppendSwitchNative(i
->first
, i
->second
);
1036 new_cl
->AppendSwitch(i
->first
);
1040 // Ensure that our desired switches are set on the new process.
1041 for (size_t i
= 0; i
< arraysize(kSwitchesToAddOnAutorestart
); ++i
) {
1042 if (!new_cl
->HasSwitch(kSwitchesToAddOnAutorestart
[i
]))
1043 new_cl
->AppendSwitch(kSwitchesToAddOnAutorestart
[i
]);
1046 DLOG(WARNING
) << "Shutting down current instance of the browser.";
1047 chrome::AttemptExit();
1049 // Transfer ownership to Upgrade.
1050 upgrade_util::SetNewCommandLine(new_cl
.release());
1053 void BrowserProcessImpl::OnAutoupdateTimer() {
1054 if (CanAutorestartForUpdate()) {
1055 DLOG(WARNING
) << "Detected update. Restarting browser.";
1056 RestartBackgroundInstance();
1060 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS)