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. 4 5 #include "chrome/browser/browser_process_impl.h" 6 7 #include <algorithm> 8 #include <map> 9 #include <vector> 10 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/files/file_path.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 "base/time/default_tick_clock.h" 25 #include "chrome/browser/apps/chrome_apps_client.h" 26 #include "chrome/browser/background/background_mode_manager.h" 27 #include "chrome/browser/chrome_browser_main.h" 28 #include "chrome/browser/chrome_content_browser_client.h" 29 #include "chrome/browser/chrome_notification_types.h" 30 #include "chrome/browser/component_updater/component_updater_configurator.h" 31 #include "chrome/browser/component_updater/component_updater_service.h" 32 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h" 33 #include "chrome/browser/defaults.h" 34 #include "chrome/browser/devtools/remote_debugging_server.h" 35 #include "chrome/browser/download/download_request_limiter.h" 36 #include "chrome/browser/download/download_status_updater.h" 37 #include "chrome/browser/extensions/chrome_extensions_browser_client.h" 38 #include "chrome/browser/extensions/event_router_forwarder.h" 39 #include "chrome/browser/extensions/extension_renderer_state.h" 40 #include "chrome/browser/first_run/upgrade_util.h" 41 #include "chrome/browser/gpu/gl_string_manager.h" 42 #include "chrome/browser/gpu/gpu_mode_manager.h" 43 #include "chrome/browser/icon_manager.h" 44 #include "chrome/browser/idle.h" 45 #include "chrome/browser/intranet_redirect_detector.h" 46 #include "chrome/browser/io_thread.h" 47 #include "chrome/browser/lifetime/application_lifetime.h" 48 #include "chrome/browser/metrics/metrics_services_manager.h" 49 #include "chrome/browser/metrics/thread_watcher.h" 50 #include "chrome/browser/net/chrome_net_log.h" 51 #include "chrome/browser/net/crl_set_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/browser_dialogs.h" 67 #include "chrome/browser/ui/browser_finder.h" 68 #include "chrome/browser/web_resource/promo_resource_service.h" 69 #include "chrome/common/chrome_constants.h" 70 #include "chrome/common/chrome_paths.h" 71 #include "chrome/common/chrome_switches.h" 72 #include "chrome/common/extensions/chrome_extensions_client.h" 73 #include "chrome/common/pref_names.h" 74 #include "chrome/common/switch_utils.h" 75 #include "chrome/common/url_constants.h" 76 #include "chrome/installer/util/google_update_constants.h" 77 #include "chrome/installer/util/google_update_settings.h" 78 #include "components/gcm_driver/gcm_driver.h" 79 #include "components/metrics/metrics_service.h" 80 #include "components/network_time/network_time_tracker.h" 81 #include "components/policy/core/common/policy_service.h" 82 #include "components/signin/core/common/profile_management_switches.h" 83 #include "components/translate/core/browser/translate_download_manager.h" 84 #include "content/public/browser/browser_thread.h" 85 #include "content/public/browser/child_process_security_policy.h" 86 #include "content/public/browser/notification_details.h" 87 #include "content/public/browser/plugin_service.h" 88 #include "content/public/browser/render_process_host.h" 89 #include "content/public/browser/resource_dispatcher_host.h" 90 #include "content/public/browser/service_worker_context.h" 91 #include "content/public/browser/storage_partition.h" 92 #include "extensions/common/constants.h" 93 #include "extensions/common/extension_l10n_util.h" 94 #include "net/socket/client_socket_pool_manager.h" 95 #include "net/url_request/url_request_context_getter.h" 96 #include "ui/base/l10n/l10n_util.h" 97 #include "ui/message_center/message_center.h" 98 99 #if defined(OS_WIN) 100 #include "base/win/windows_version.h" 101 #include "ui/views/focus/view_storage.h" 102 #elif defined(OS_MACOSX) 103 #include "chrome/browser/chrome_browser_main_mac.h" 104 #endif 105 106 #if defined(OS_ANDROID) 107 #include "components/gcm_driver/gcm_driver_android.h" 108 #else 109 #include "chrome/browser/services/gcm/gcm_desktop_utils.h" 110 #include "components/gcm_driver/gcm_client_factory.h" 111 #endif 112 113 #if !defined(OS_ANDROID) && !defined(OS_IOS) 114 #include "chrome/browser/media_galleries/media_file_system_registry.h" 115 #include "components/storage_monitor/storage_monitor.h" 116 #endif 117 118 #if defined(USE_AURA) 119 #include "ui/aura/env.h" 120 #endif 121 122 #if defined(ENABLE_CONFIGURATION_POLICY) 123 #include "components/policy/core/browser/browser_policy_connector.h" 124 #else 125 #include "components/policy/core/common/policy_service_stub.h" 126 #endif // defined(ENABLE_CONFIGURATION_POLICY) 127 128 #if defined(ENABLE_PLUGIN_INSTALLATION) 129 #include "chrome/browser/plugins/plugins_resource_service.h" 130 #endif 131 132 #if defined(ENABLE_WEBRTC) 133 #include "chrome/browser/media/webrtc_log_uploader.h" 134 #endif 135 136 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) 137 // How often to check if the persistent instance of Chrome needs to restart 138 // to install an update. 139 static const int kUpdateCheckIntervalHours = 6; 140 #endif 141 142 #if defined(USE_X11) || defined(OS_WIN) 143 // How long to wait for the File thread to complete during EndSession, on Linux 144 // and Windows. We have a timeout here because we're unable to run the UI 145 // messageloop and there's some deadlock risk. Our only option is to exit 146 // anyway. 147 static const int kEndSessionTimeoutSeconds = 10; 148 #endif 149 150 using content::BrowserThread; 151 using content::ChildProcessSecurityPolicy; 152 using content::PluginService; 153 using content::ResourceDispatcherHost; 154 155 BrowserProcessImpl::BrowserProcessImpl( 156 base::SequencedTaskRunner* local_state_task_runner, 157 const CommandLine& command_line) 158 : created_watchdog_thread_(false), 159 created_browser_policy_connector_(false), 160 created_profile_manager_(false), 161 created_local_state_(false), 162 created_icon_manager_(false), 163 created_notification_ui_manager_(false), 164 created_safe_browsing_service_(false), 165 module_ref_count_(0), 166 did_start_(false), 167 download_status_updater_(new DownloadStatusUpdater), 168 local_state_task_runner_(local_state_task_runner) { 169 g_browser_process = this; 170 platform_part_.reset(new BrowserProcessPlatformPart()); 171 172 #if defined(ENABLE_PRINTING) 173 // Must be created after the NotificationService. 174 print_job_manager_.reset(new printing::PrintJobManager); 175 #endif 176 177 net_log_.reset(new ChromeNetLog); 178 179 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme( 180 extensions::kExtensionScheme); 181 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme( 182 extensions::kExtensionResourceScheme); 183 ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme( 184 chrome::kChromeSearchScheme); 185 186 #if defined(OS_MACOSX) 187 InitIdleMonitor(); 188 #endif 189 190 #if defined(ENABLE_EXTENSIONS) 191 apps::AppsClient::Set(ChromeAppsClient::GetInstance()); 192 #endif 193 194 extensions::ExtensionsClient::Set( 195 extensions::ChromeExtensionsClient::GetInstance()); 196 197 extensions_browser_client_.reset( 198 new extensions::ChromeExtensionsBrowserClient); 199 extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); 200 201 extension_event_router_forwarder_ = new extensions::EventRouterForwarder; 202 ExtensionRendererState::GetInstance()->Init(); 203 204 message_center::MessageCenter::Initialize(); 205 } 206 207 BrowserProcessImpl::~BrowserProcessImpl() { 208 tracked_objects::ThreadData::EnsureCleanupWasCalled(4); 209 210 g_browser_process = NULL; 211 } 212 213 void BrowserProcessImpl::StartTearDown() { 214 TRACE_EVENT0("shutdown", "BrowserProcessImpl::StartTearDown"); 215 // We need to destroy the MetricsServicesManager, IntranetRedirectDetector, 216 // PromoResourceService, and SafeBrowsing ClientSideDetectionService (owned by 217 // the SafeBrowsingService) before the io_thread_ gets destroyed, since their 218 // destructors can call the URLFetcher destructor, which does a 219 // PostDelayedTask operation on the IO thread. (The IO thread will handle that 220 // URLFetcher operation before going away.) 221 metrics_services_manager_.reset(); 222 intranet_redirect_detector_.reset(); 223 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING) 224 if (safe_browsing_service_.get()) 225 safe_browsing_service()->ShutDown(); 226 #endif 227 228 // Need to clear the desktop notification balloons before the io_thread_ and 229 // before the profiles, since if there are any still showing we will access 230 // those things during teardown. 231 notification_ui_manager_.reset(); 232 233 // Need to clear profiles (download managers) before the io_thread_. 234 { 235 TRACE_EVENT0("shutdown", 236 "BrowserProcessImpl::StartTearDown:ProfileManager"); 237 // The desktop User Manager needs to be closed before the guest profile 238 // can be destroyed. 239 if (switches::IsNewProfileManagement()) 240 chrome::HideUserManager(); 241 profile_manager_.reset(); 242 } 243 244 #if !defined(OS_ANDROID) 245 // Debugger must be cleaned up before IO thread and NotificationService. 246 remote_debugging_server_.reset(); 247 #endif 248 249 ExtensionRendererState::GetInstance()->Shutdown(); 250 251 #if !defined(OS_ANDROID) && !defined(OS_IOS) 252 media_file_system_registry_.reset(); 253 // Remove the global instance of the Storage Monitor now. Otherwise the 254 // FILE thread would be gone when we try to release it in the dtor and 255 // Valgrind would report a leak on almost every single browser_test. 256 // TODO(gbillock): Make this unnecessary. 257 storage_monitor::StorageMonitor::Destroy(); 258 #endif 259 260 message_center::MessageCenter::Shutdown(); 261 262 #if defined(ENABLE_CONFIGURATION_POLICY) 263 // The policy providers managed by |browser_policy_connector_| need to shut 264 // down while the IO and FILE threads are still alive. 265 if (browser_policy_connector_) 266 browser_policy_connector_->Shutdown(); 267 #endif 268 269 // The |gcm_driver_| must shut down while the IO thread is still alive. 270 if (gcm_driver_) 271 gcm_driver_->Shutdown(); 272 273 // Stop the watchdog thread before stopping other threads. 274 watchdog_thread_.reset(); 275 276 #if defined(USE_AURA) 277 // Delete aura after the metrics service has been deleted as it accesses 278 // monitor information. 279 aura::Env::DeleteInstance(); 280 #endif 281 282 platform_part()->StartTearDown(); 283 284 #if defined(ENABLE_WEBRTC) 285 // Cancel any uploads to release the system url request context references. 286 if (webrtc_log_uploader_) 287 webrtc_log_uploader_->StartShutdown(); 288 #endif 289 290 if (local_state()) 291 local_state()->CommitPendingWrite(); 292 } 293 294 void BrowserProcessImpl::PostDestroyThreads() { 295 // With the file_thread_ flushed, we can release any icon resources. 296 icon_manager_.reset(); 297 298 #if defined(ENABLE_WEBRTC) 299 // Must outlive the file thread. 300 webrtc_log_uploader_.reset(); 301 #endif 302 303 // Reset associated state right after actual thread is stopped, 304 // as io_thread_.global_ cleanup happens in CleanUp on the IO 305 // thread, i.e. as the thread exits its message loop. 306 // 307 // This is important also because in various places, the 308 // IOThread object being NULL is considered synonymous with the 309 // IO thread having stopped. 310 io_thread_.reset(); 311 } 312 313 #if defined(USE_X11) || defined(OS_WIN) 314 static void Signal(base::WaitableEvent* event) { 315 event->Signal(); 316 } 317 #endif 318 319 unsigned int BrowserProcessImpl::AddRefModule() { 320 DCHECK(CalledOnValidThread()); 321 322 // CHECK(!IsShuttingDown()); 323 if (IsShuttingDown()) { 324 // Copy the stacktrace which released the final reference onto our stack so 325 // it will be available in the crash report for inspection. 326 base::debug::StackTrace callstack = release_last_reference_callstack_; 327 base::debug::Alias(&callstack); 328 CHECK(false); 329 } 330 331 did_start_ = true; 332 module_ref_count_++; 333 return module_ref_count_; 334 } 335 336 static void ShutdownServiceWorkerContext(content::StoragePartition* partition) { 337 partition->GetServiceWorkerContext()->Terminate(); 338 } 339 340 unsigned int BrowserProcessImpl::ReleaseModule() { 341 DCHECK(CalledOnValidThread()); 342 DCHECK_NE(0u, module_ref_count_); 343 module_ref_count_--; 344 if (0 == module_ref_count_) { 345 release_last_reference_callstack_ = base::debug::StackTrace(); 346 347 // Stop service workers 348 ProfileManager* pm = profile_manager(); 349 std::vector<Profile*> profiles(pm->GetLoadedProfiles()); 350 for (size_t i = 0; i < profiles.size(); ++i) { 351 content::BrowserContext::ForEachStoragePartition( 352 profiles[i], base::Bind(ShutdownServiceWorkerContext)); 353 } 354 355 #if defined(ENABLE_PRINTING) 356 // Wait for the pending print jobs to finish. Don't do this later, since 357 // this might cause a nested message loop to run, and we don't want pending 358 // tasks to run once teardown has started. 359 print_job_manager_->Shutdown(); 360 #endif 361 362 #if defined(LEAK_SANITIZER) 363 // Check for memory leaks now, before we start shutting down threads. Doing 364 // this early means we won't report any shutdown-only leaks (as they have 365 // not yet happened at this point). 366 // If leaks are found, this will make the process exit immediately. 367 __lsan_do_leak_check(); 368 #endif 369 370 CHECK(base::MessageLoop::current()->is_running()); 371 372 #if defined(OS_MACOSX) 373 base::MessageLoop::current()->PostTask( 374 FROM_HERE, 375 base::Bind(ChromeBrowserMainPartsMac::DidEndMainMessageLoop)); 376 #endif 377 base::MessageLoop::current()->Quit(); 378 } 379 return module_ref_count_; 380 } 381 382 void BrowserProcessImpl::EndSession() { 383 // Mark all the profiles as clean. 384 ProfileManager* pm = profile_manager(); 385 std::vector<Profile*> profiles(pm->GetLoadedProfiles()); 386 for (size_t i = 0; i < profiles.size(); ++i) 387 profiles[i]->SetExitType(Profile::EXIT_SESSION_ENDED); 388 389 // Tell the metrics service it was cleanly shutdown. 390 MetricsService* metrics = g_browser_process->metrics_service(); 391 if (metrics && local_state()) { 392 metrics->RecordStartOfSessionEnd(); 393 #if !defined(OS_CHROMEOS) 394 // MetricsService lazily writes to prefs, force it to write now. 395 // On ChromeOS, chrome gets killed when hangs, so no need to 396 // commit metrics::prefs::kStabilitySessionEndCompleted change immediately. 397 local_state()->CommitPendingWrite(); 398 #endif 399 } 400 401 // http://crbug.com/125207 402 base::ThreadRestrictions::ScopedAllowWait allow_wait; 403 404 // We must write that the profile and metrics service shutdown cleanly, 405 // otherwise on startup we'll think we crashed. So we block until done and 406 // then proceed with normal shutdown. 407 #if defined(USE_X11) || defined(OS_WIN) 408 // Create a waitable event to block on file writing being complete. 409 // 410 // On Windows, we previously posted a message to FILE and then ran a nested 411 // message loop, waiting for that message to be processed until quitting. 412 // However, doing so means that other messages will also be processed. In 413 // particular, if the GPU process host notices that the GPU has been killed 414 // during shutdown, it races exiting the nested loop with the process host 415 // blocking the message loop attempting to re-establish a connection to the 416 // GPU process synchronously. Because the system may not be allowing 417 // processes to launch, this can result in a hang. See 418 // http://crbug.com/318527. 419 scoped_ptr<base::WaitableEvent> done_writing( 420 new base::WaitableEvent(false, false)); 421 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, 422 base::Bind(Signal, done_writing.get())); 423 // If all file writes haven't cleared in the timeout, leak the WaitableEvent 424 // so that there's no race to reference it in Signal(). 425 if (!done_writing->TimedWait( 426 base::TimeDelta::FromSeconds(kEndSessionTimeoutSeconds))) { 427 ignore_result(done_writing.release()); 428 } 429 #else 430 NOTIMPLEMENTED(); 431 #endif 432 } 433 434 MetricsServicesManager* BrowserProcessImpl::GetMetricsServicesManager() { 435 DCHECK(CalledOnValidThread()); 436 if (!metrics_services_manager_) 437 metrics_services_manager_.reset(new MetricsServicesManager(local_state())); 438 return metrics_services_manager_.get(); 439 } 440 441 MetricsService* BrowserProcessImpl::metrics_service() { 442 DCHECK(CalledOnValidThread()); 443 return GetMetricsServicesManager()->GetMetricsService(); 444 } 445 446 rappor::RapporService* BrowserProcessImpl::rappor_service() { 447 DCHECK(CalledOnValidThread()); 448 return GetMetricsServicesManager()->GetRapporService(); 449 } 450 451 IOThread* BrowserProcessImpl::io_thread() { 452 DCHECK(CalledOnValidThread()); 453 DCHECK(io_thread_.get()); 454 return io_thread_.get(); 455 } 456 457 WatchDogThread* BrowserProcessImpl::watchdog_thread() { 458 DCHECK(CalledOnValidThread()); 459 if (!created_watchdog_thread_) 460 CreateWatchdogThread(); 461 DCHECK(watchdog_thread_.get() != NULL); 462 return watchdog_thread_.get(); 463 } 464 465 ProfileManager* BrowserProcessImpl::profile_manager() { 466 DCHECK(CalledOnValidThread()); 467 if (!created_profile_manager_) 468 CreateProfileManager(); 469 return profile_manager_.get(); 470 } 471 472 PrefService* BrowserProcessImpl::local_state() { 473 DCHECK(CalledOnValidThread()); 474 if (!created_local_state_) 475 CreateLocalState(); 476 return local_state_.get(); 477 } 478 479 net::URLRequestContextGetter* BrowserProcessImpl::system_request_context() { 480 DCHECK(CalledOnValidThread()); 481 return io_thread()->system_url_request_context_getter(); 482 } 483 484 chrome_variations::VariationsService* BrowserProcessImpl::variations_service() { 485 DCHECK(CalledOnValidThread()); 486 return GetMetricsServicesManager()->GetVariationsService(); 487 } 488 489 BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() { 490 return platform_part_.get(); 491 } 492 493 extensions::EventRouterForwarder* 494 BrowserProcessImpl::extension_event_router_forwarder() { 495 return extension_event_router_forwarder_.get(); 496 } 497 498 NotificationUIManager* BrowserProcessImpl::notification_ui_manager() { 499 DCHECK(CalledOnValidThread()); 500 if (!created_notification_ui_manager_) 501 CreateNotificationUIManager(); 502 return notification_ui_manager_.get(); 503 } 504 505 message_center::MessageCenter* BrowserProcessImpl::message_center() { 506 DCHECK(CalledOnValidThread()); 507 return message_center::MessageCenter::Get(); 508 } 509 510 policy::BrowserPolicyConnector* BrowserProcessImpl::browser_policy_connector() { 511 DCHECK(CalledOnValidThread()); 512 #if defined(ENABLE_CONFIGURATION_POLICY) 513 if (!created_browser_policy_connector_) { 514 DCHECK(!browser_policy_connector_); 515 browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector(); 516 created_browser_policy_connector_ = true; 517 } 518 return browser_policy_connector_.get(); 519 #else 520 return NULL; 521 #endif 522 } 523 524 policy::PolicyService* BrowserProcessImpl::policy_service() { 525 #if defined(ENABLE_CONFIGURATION_POLICY) 526 return browser_policy_connector()->GetPolicyService(); 527 #else 528 if (!policy_service_.get()) 529 policy_service_.reset(new policy::PolicyServiceStub()); 530 return policy_service_.get(); 531 #endif 532 } 533 534 IconManager* BrowserProcessImpl::icon_manager() { 535 DCHECK(CalledOnValidThread()); 536 if (!created_icon_manager_) 537 CreateIconManager(); 538 return icon_manager_.get(); 539 } 540 541 GLStringManager* BrowserProcessImpl::gl_string_manager() { 542 DCHECK(CalledOnValidThread()); 543 if (!gl_string_manager_.get()) 544 gl_string_manager_.reset(new GLStringManager()); 545 return gl_string_manager_.get(); 546 } 547 548 GpuModeManager* BrowserProcessImpl::gpu_mode_manager() { 549 DCHECK(CalledOnValidThread()); 550 if (!gpu_mode_manager_.get()) 551 gpu_mode_manager_.reset(new GpuModeManager()); 552 return gpu_mode_manager_.get(); 553 } 554 555 void BrowserProcessImpl::CreateDevToolsHttpProtocolHandler( 556 chrome::HostDesktopType host_desktop_type, 557 const std::string& ip, 558 int port) { 559 DCHECK(CalledOnValidThread()); 560 #if !defined(OS_ANDROID) 561 // StartupBrowserCreator::LaunchBrowser can be run multiple times when browser 562 // is started with several profiles or existing browser process is reused. 563 if (!remote_debugging_server_.get()) { 564 remote_debugging_server_.reset( 565 new RemoteDebuggingServer(host_desktop_type, ip, port)); 566 } 567 #endif 568 } 569 570 bool BrowserProcessImpl::IsShuttingDown() { 571 DCHECK(CalledOnValidThread()); 572 return did_start_ && 0 == module_ref_count_; 573 } 574 575 printing::PrintJobManager* BrowserProcessImpl::print_job_manager() { 576 DCHECK(CalledOnValidThread()); 577 return print_job_manager_.get(); 578 } 579 580 printing::PrintPreviewDialogController* 581 BrowserProcessImpl::print_preview_dialog_controller() { 582 #if defined(ENABLE_FULL_PRINTING) 583 DCHECK(CalledOnValidThread()); 584 if (!print_preview_dialog_controller_.get()) 585 CreatePrintPreviewDialogController(); 586 return print_preview_dialog_controller_.get(); 587 #else 588 NOTIMPLEMENTED(); 589 return NULL; 590 #endif 591 } 592 593 printing::BackgroundPrintingManager* 594 BrowserProcessImpl::background_printing_manager() { 595 #if defined(ENABLE_FULL_PRINTING) 596 DCHECK(CalledOnValidThread()); 597 if (!background_printing_manager_.get()) 598 CreateBackgroundPrintingManager(); 599 return background_printing_manager_.get(); 600 #else 601 NOTIMPLEMENTED(); 602 return NULL; 603 #endif 604 } 605 606 IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() { 607 DCHECK(CalledOnValidThread()); 608 if (!intranet_redirect_detector_.get()) 609 CreateIntranetRedirectDetector(); 610 return intranet_redirect_detector_.get(); 611 } 612 613 const std::string& BrowserProcessImpl::GetApplicationLocale() { 614 DCHECK(!locale_.empty()); 615 return locale_; 616 } 617 618 void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) { 619 locale_ = locale; 620 extension_l10n_util::SetProcessLocale(locale); 621 chrome::ChromeContentBrowserClient::SetApplicationLocale(locale); 622 TranslateDownloadManager::GetInstance()->set_application_locale(locale); 623 } 624 625 DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() { 626 return download_status_updater_.get(); 627 } 628 629 MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() { 630 #if defined(OS_ANDROID) || defined(OS_IOS) 631 return NULL; 632 #else 633 if (!media_file_system_registry_) 634 media_file_system_registry_.reset(new MediaFileSystemRegistry()); 635 return media_file_system_registry_.get(); 636 #endif 637 } 638 639 bool BrowserProcessImpl::created_local_state() const { 640 return created_local_state_; 641 } 642 643 #if defined(ENABLE_WEBRTC) 644 WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() { 645 if (!webrtc_log_uploader_.get()) 646 webrtc_log_uploader_.reset(new WebRtcLogUploader()); 647 return webrtc_log_uploader_.get(); 648 } 649 #endif 650 651 network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() { 652 if (!network_time_tracker_) { 653 network_time_tracker_.reset(new network_time::NetworkTimeTracker( 654 scoped_ptr<base::TickClock>(new base::DefaultTickClock()), 655 local_state())); 656 } 657 return network_time_tracker_.get(); 658 } 659 660 gcm::GCMDriver* BrowserProcessImpl::gcm_driver() { 661 DCHECK(CalledOnValidThread()); 662 if (!gcm_driver_) 663 CreateGCMDriver(); 664 return gcm_driver_.get(); 665 } 666 667 // static 668 void BrowserProcessImpl::RegisterPrefs(PrefRegistrySimple* registry) { 669 registry->RegisterBooleanPref(prefs::kDefaultBrowserSettingEnabled, 670 false); 671 // This policy needs to be defined before the net subsystem is initialized, 672 // so we do it here. 673 registry->RegisterIntegerPref(prefs::kMaxConnectionsPerProxy, 674 net::kDefaultMaxSocketsPerProxyServer); 675 676 registry->RegisterBooleanPref(prefs::kAllowCrossOriginAuthPrompt, false); 677 678 #if defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS) 679 registry->RegisterBooleanPref(prefs::kEulaAccepted, false); 680 #endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) || defined(OS_IOS) 681 #if defined(OS_WIN) 682 if (base::win::GetVersion() >= base::win::VERSION_WIN8) { 683 registry->RegisterStringPref(prefs::kRelaunchMode, 684 upgrade_util::kRelaunchModeDefault); 685 } 686 #endif 687 688 // TODO(brettw,*): this comment about ResourceBundle was here since 689 // initial commit. This comment seems unrelated, bit-rotten and 690 // a candidate for removal. 691 // Initialize ResourceBundle which handles files loaded from external 692 // sources. This has to be done before uninstall code path and before prefs 693 // are registered. 694 registry->RegisterStringPref(prefs::kApplicationLocale, std::string()); 695 #if defined(OS_CHROMEOS) 696 registry->RegisterStringPref(prefs::kOwnerLocale, std::string()); 697 registry->RegisterStringPref(prefs::kHardwareKeyboardLayout, 698 std::string()); 699 #endif // defined(OS_CHROMEOS) 700 #if !defined(OS_CHROMEOS) 701 registry->RegisterBooleanPref( 702 prefs::kMetricsReportingEnabled, 703 GoogleUpdateSettings::GetCollectStatsConsent()); 704 #endif // !defined(OS_CHROMEOS) 705 706 #if defined(OS_ANDROID) 707 registry->RegisterBooleanPref( 708 prefs::kCrashReportingEnabled, false); 709 #endif // defined(OS_ANDROID) 710 } 711 712 DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() { 713 DCHECK(CalledOnValidThread()); 714 if (!download_request_limiter_.get()) 715 download_request_limiter_ = new DownloadRequestLimiter(); 716 return download_request_limiter_.get(); 717 } 718 719 BackgroundModeManager* BrowserProcessImpl::background_mode_manager() { 720 DCHECK(CalledOnValidThread()); 721 #if defined(ENABLE_BACKGROUND) 722 if (!background_mode_manager_.get()) 723 CreateBackgroundModeManager(); 724 return background_mode_manager_.get(); 725 #else 726 NOTIMPLEMENTED(); 727 return NULL; 728 #endif 729 } 730 731 void BrowserProcessImpl::set_background_mode_manager_for_test( 732 scoped_ptr<BackgroundModeManager> manager) { 733 background_mode_manager_ = manager.Pass(); 734 } 735 736 StatusTray* BrowserProcessImpl::status_tray() { 737 DCHECK(CalledOnValidThread()); 738 if (!status_tray_.get()) 739 CreateStatusTray(); 740 return status_tray_.get(); 741 } 742 743 744 SafeBrowsingService* BrowserProcessImpl::safe_browsing_service() { 745 DCHECK(CalledOnValidThread()); 746 if (!created_safe_browsing_service_) 747 CreateSafeBrowsingService(); 748 return safe_browsing_service_.get(); 749 } 750 751 safe_browsing::ClientSideDetectionService* 752 BrowserProcessImpl::safe_browsing_detection_service() { 753 DCHECK(CalledOnValidThread()); 754 if (safe_browsing_service()) 755 return safe_browsing_service()->safe_browsing_detection_service(); 756 return NULL; 757 } 758 759 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) 760 void BrowserProcessImpl::StartAutoupdateTimer() { 761 autoupdate_timer_.Start(FROM_HERE, 762 base::TimeDelta::FromHours(kUpdateCheckIntervalHours), 763 this, 764 &BrowserProcessImpl::OnAutoupdateTimer); 765 } 766 #endif 767 768 ChromeNetLog* BrowserProcessImpl::net_log() { 769 return net_log_.get(); 770 } 771 772 prerender::PrerenderTracker* BrowserProcessImpl::prerender_tracker() { 773 if (!prerender_tracker_.get()) 774 prerender_tracker_.reset(new prerender::PrerenderTracker); 775 776 return prerender_tracker_.get(); 777 } 778 779 component_updater::ComponentUpdateService* 780 BrowserProcessImpl::component_updater() { 781 if (!component_updater_.get()) { 782 if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) 783 return NULL; 784 component_updater::ComponentUpdateService::Configurator* configurator = 785 component_updater::MakeChromeComponentUpdaterConfigurator( 786 CommandLine::ForCurrentProcess(), 787 io_thread()->system_url_request_context_getter()); 788 // Creating the component updater does not do anything, components 789 // need to be registered and Start() needs to be called. 790 component_updater_.reset(ComponentUpdateServiceFactory(configurator)); 791 } 792 return component_updater_.get(); 793 } 794 795 CRLSetFetcher* BrowserProcessImpl::crl_set_fetcher() { 796 if (!crl_set_fetcher_.get()) 797 crl_set_fetcher_ = new CRLSetFetcher(); 798 return crl_set_fetcher_.get(); 799 } 800 801 component_updater::PnaclComponentInstaller* 802 BrowserProcessImpl::pnacl_component_installer() { 803 if (!pnacl_component_installer_.get()) { 804 pnacl_component_installer_.reset( 805 new component_updater::PnaclComponentInstaller()); 806 } 807 return pnacl_component_installer_.get(); 808 } 809 810 void BrowserProcessImpl::ResourceDispatcherHostCreated() { 811 resource_dispatcher_host_delegate_.reset( 812 new ChromeResourceDispatcherHostDelegate(prerender_tracker())); 813 ResourceDispatcherHost::Get()->SetDelegate( 814 resource_dispatcher_host_delegate_.get()); 815 816 pref_change_registrar_.Add( 817 prefs::kAllowCrossOriginAuthPrompt, 818 base::Bind(&BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy, 819 base::Unretained(this))); 820 ApplyAllowCrossOriginAuthPromptPolicy(); 821 } 822 823 void BrowserProcessImpl::CreateWatchdogThread() { 824 DCHECK(!created_watchdog_thread_ && watchdog_thread_.get() == NULL); 825 created_watchdog_thread_ = true; 826 827 scoped_ptr<WatchDogThread> thread(new WatchDogThread()); 828 if (!thread->Start()) 829 return; 830 watchdog_thread_.swap(thread); 831 } 832 833 void BrowserProcessImpl::CreateProfileManager() { 834 DCHECK(!created_profile_manager_ && profile_manager_.get() == NULL); 835 created_profile_manager_ = true; 836 837 base::FilePath user_data_dir; 838 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); 839 profile_manager_.reset(new ProfileManager(user_data_dir)); 840 } 841 842 void BrowserProcessImpl::CreateLocalState() { 843 DCHECK(!created_local_state_ && local_state_.get() == NULL); 844 created_local_state_ = true; 845 846 base::FilePath local_state_path; 847 CHECK(PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path)); 848 scoped_refptr<PrefRegistrySimple> pref_registry = new PrefRegistrySimple; 849 850 // Register local state preferences. 851 chrome::RegisterLocalState(pref_registry.get()); 852 853 local_state_ = 854 chrome_prefs::CreateLocalState(local_state_path, 855 local_state_task_runner_.get(), 856 policy_service(), 857 pref_registry, 858 false).Pass(); 859 860 pref_change_registrar_.Init(local_state_.get()); 861 862 // Initialize the notification for the default browser setting policy. 863 pref_change_registrar_.Add( 864 prefs::kDefaultBrowserSettingEnabled, 865 base::Bind(&BrowserProcessImpl::ApplyDefaultBrowserPolicy, 866 base::Unretained(this))); 867 868 // This preference must be kept in sync with external values; update them 869 // whenever the preference or its controlling policy changes. 870 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS) 871 pref_change_registrar_.Add( 872 prefs::kMetricsReportingEnabled, 873 base::Bind(&BrowserProcessImpl::ApplyMetricsReportingPolicy, 874 base::Unretained(this))); 875 #endif 876 877 int max_per_proxy = local_state_->GetInteger(prefs::kMaxConnectionsPerProxy); 878 net::ClientSocketPoolManager::set_max_sockets_per_proxy_server( 879 net::HttpNetworkSession::NORMAL_SOCKET_POOL, 880 std::max(std::min(max_per_proxy, 99), 881 net::ClientSocketPoolManager::max_sockets_per_group( 882 net::HttpNetworkSession::NORMAL_SOCKET_POOL))); 883 } 884 885 void BrowserProcessImpl::PreCreateThreads() { 886 io_thread_.reset(new IOThread(local_state(), policy_service(), net_log_.get(), 887 extension_event_router_forwarder_.get())); 888 } 889 890 void BrowserProcessImpl::PreMainMessageLoopRun() { 891 #if defined(ENABLE_CONFIGURATION_POLICY) 892 // browser_policy_connector() is created very early because local_state() 893 // needs policy to be initialized with the managed preference values. 894 // However, policy fetches from the network and loading of disk caches 895 // requires that threads are running; this Init() call lets the connector 896 // resume its initialization now that the loops are spinning and the 897 // system request context is available for the fetchers. 898 browser_policy_connector()->Init(local_state(), system_request_context()); 899 #endif 900 901 if (local_state_->IsManagedPreference(prefs::kDefaultBrowserSettingEnabled)) 902 ApplyDefaultBrowserPolicy(); 903 904 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS) 905 ApplyMetricsReportingPolicy(); 906 #endif 907 908 #if defined(ENABLE_PLUGINS) 909 PluginService* plugin_service = PluginService::GetInstance(); 910 plugin_service->SetFilter(ChromePluginServiceFilter::GetInstance()); 911 plugin_service->StartWatchingPlugins(); 912 913 #if defined(OS_POSIX) 914 // Also find plugins in a user-specific plugins dir, 915 // e.g. ~/.config/chromium/Plugins. 916 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); 917 if (!cmd_line.HasSwitch(switches::kDisablePluginsDiscovery)) { 918 base::FilePath user_data_dir; 919 if (PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) 920 plugin_service->AddExtraPluginDir(user_data_dir.Append("Plugins")); 921 } 922 #endif 923 924 // Triggers initialization of the singleton instance on UI thread. 925 PluginFinder::GetInstance()->Init(); 926 927 #if defined(ENABLE_PLUGIN_INSTALLATION) 928 DCHECK(!plugins_resource_service_.get()); 929 plugins_resource_service_ = new PluginsResourceService(local_state()); 930 plugins_resource_service_->Init(); 931 #endif 932 #endif // defined(ENABLE_PLUGINS) 933 934 const CommandLine& command_line = *CommandLine::ForCurrentProcess(); 935 if (!command_line.HasSwitch(switches::kDisableWebResources)) { 936 DCHECK(!promo_resource_service_.get()); 937 promo_resource_service_ = new PromoResourceService; 938 promo_resource_service_->StartAfterDelay(); 939 } 940 941 #if !defined(OS_ANDROID) && !defined(OS_IOS) 942 storage_monitor::StorageMonitor::Create(); 943 #endif 944 945 platform_part_->PreMainMessageLoopRun(); 946 } 947 948 void BrowserProcessImpl::CreateIconManager() { 949 DCHECK(!created_icon_manager_ && icon_manager_.get() == NULL); 950 created_icon_manager_ = true; 951 icon_manager_.reset(new IconManager); 952 } 953 954 void BrowserProcessImpl::CreateIntranetRedirectDetector() { 955 DCHECK(intranet_redirect_detector_.get() == NULL); 956 scoped_ptr<IntranetRedirectDetector> intranet_redirect_detector( 957 new IntranetRedirectDetector); 958 intranet_redirect_detector_.swap(intranet_redirect_detector); 959 } 960 961 void BrowserProcessImpl::CreateNotificationUIManager() { 962 #if defined(ENABLE_NOTIFICATIONS) 963 DCHECK(notification_ui_manager_.get() == NULL); 964 notification_ui_manager_.reset(NotificationUIManager::Create(local_state())); 965 created_notification_ui_manager_ = true; 966 #endif 967 } 968 969 void BrowserProcessImpl::CreateBackgroundModeManager() { 970 DCHECK(background_mode_manager_.get() == NULL); 971 background_mode_manager_.reset( 972 new BackgroundModeManager(CommandLine::ForCurrentProcess(), 973 &profile_manager()->GetProfileInfoCache())); 974 } 975 976 void BrowserProcessImpl::CreateStatusTray() { 977 DCHECK(status_tray_.get() == NULL); 978 status_tray_.reset(StatusTray::Create()); 979 } 980 981 void BrowserProcessImpl::CreatePrintPreviewDialogController() { 982 #if defined(ENABLE_FULL_PRINTING) 983 DCHECK(print_preview_dialog_controller_.get() == NULL); 984 print_preview_dialog_controller_ = 985 new printing::PrintPreviewDialogController(); 986 #else 987 NOTIMPLEMENTED(); 988 #endif 989 } 990 991 void BrowserProcessImpl::CreateBackgroundPrintingManager() { 992 #if defined(ENABLE_FULL_PRINTING) 993 DCHECK(background_printing_manager_.get() == NULL); 994 background_printing_manager_.reset(new printing::BackgroundPrintingManager()); 995 #else 996 NOTIMPLEMENTED(); 997 #endif 998 } 999 1000 void BrowserProcessImpl::CreateSafeBrowsingService() { 1001 DCHECK(safe_browsing_service_.get() == NULL); 1002 // Set this flag to true so that we don't retry indefinitely to 1003 // create the service class if there was an error. 1004 created_safe_browsing_service_ = true; 1005 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING) 1006 safe_browsing_service_ = SafeBrowsingService::CreateSafeBrowsingService(); 1007 safe_browsing_service_->Initialize(); 1008 #endif 1009 } 1010 1011 void BrowserProcessImpl::CreateGCMDriver() { 1012 DCHECK(!gcm_driver_); 1013 1014 #if defined(OS_ANDROID) 1015 gcm_driver_.reset(new gcm::GCMDriverAndroid); 1016 #else 1017 base::FilePath store_path; 1018 CHECK(PathService::Get(chrome::DIR_GLOBAL_GCM_STORE, &store_path)); 1019 gcm_driver_ = gcm::CreateGCMDriverDesktop( 1020 make_scoped_ptr(new gcm::GCMClientFactory), 1021 store_path, 1022 system_request_context()); 1023 // Sign-in is not required for device-level GCM usage. So we just call 1024 // OnSignedIn to assume always signed-in. Note that GCM will not be started 1025 // at this point since no one has asked for it yet. 1026 // TODO(jianli): To be removed when sign-in enforcement is dropped. 1027 gcm_driver_->OnSignedIn(); 1028 #endif // defined(OS_ANDROID) 1029 } 1030 1031 void BrowserProcessImpl::ApplyDefaultBrowserPolicy() { 1032 if (local_state()->GetBoolean(prefs::kDefaultBrowserSettingEnabled)) { 1033 scoped_refptr<ShellIntegration::DefaultWebClientWorker> 1034 set_browser_worker = new ShellIntegration::DefaultBrowserWorker(NULL); 1035 set_browser_worker->StartSetAsDefault(); 1036 } 1037 } 1038 1039 void BrowserProcessImpl::ApplyAllowCrossOriginAuthPromptPolicy() { 1040 bool value = local_state()->GetBoolean(prefs::kAllowCrossOriginAuthPrompt); 1041 ResourceDispatcherHost::Get()->SetAllowCrossOriginAuthPrompt(value); 1042 } 1043 1044 void BrowserProcessImpl::ApplyMetricsReportingPolicy() { 1045 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_IOS) 1046 CHECK(BrowserThread::PostTask( 1047 BrowserThread::FILE, FROM_HERE, 1048 base::Bind( 1049 base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent), 1050 local_state()->GetBoolean(prefs::kMetricsReportingEnabled)))); 1051 #endif 1052 } 1053 1054 // Mac is currently not supported. 1055 #if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) 1056 1057 bool BrowserProcessImpl::CanAutorestartForUpdate() const { 1058 // Check if browser is in the background and if it needs to be restarted to 1059 // apply a pending update. 1060 return chrome::GetTotalBrowserCount() == 0 && chrome::WillKeepAlive() && 1061 upgrade_util::IsUpdatePendingRestart(); 1062 } 1063 1064 // Switches to add when auto-restarting Chrome. 1065 const char* const kSwitchesToAddOnAutorestart[] = { 1066 switches::kNoStartupWindow 1067 }; 1068 1069 void BrowserProcessImpl::RestartBackgroundInstance() { 1070 CommandLine* old_cl = CommandLine::ForCurrentProcess(); 1071 scoped_ptr<CommandLine> new_cl(new CommandLine(old_cl->GetProgram())); 1072 1073 std::map<std::string, CommandLine::StringType> switches = 1074 old_cl->GetSwitches(); 1075 1076 switches::RemoveSwitchesForAutostart(&switches); 1077 1078 // Append the rest of the switches (along with their values, if any) 1079 // to the new command line 1080 for (std::map<std::string, CommandLine::StringType>::const_iterator i = 1081 switches.begin(); i != switches.end(); ++i) { 1082 CommandLine::StringType switch_value = i->second; 1083 if (switch_value.length() > 0) { 1084 new_cl->AppendSwitchNative(i->first, i->second); 1085 } else { 1086 new_cl->AppendSwitch(i->first); 1087 } 1088 } 1089 1090 // Ensure that our desired switches are set on the new process. 1091 for (size_t i = 0; i < arraysize(kSwitchesToAddOnAutorestart); ++i) { 1092 if (!new_cl->HasSwitch(kSwitchesToAddOnAutorestart[i])) 1093 new_cl->AppendSwitch(kSwitchesToAddOnAutorestart[i]); 1094 } 1095 1096 DLOG(WARNING) << "Shutting down current instance of the browser."; 1097 chrome::AttemptExit(); 1098 1099 // Transfer ownership to Upgrade. 1100 upgrade_util::SetNewCommandLine(new_cl.release()); 1101 } 1102 1103 void BrowserProcessImpl::OnAutoupdateTimer() { 1104 if (CanAutorestartForUpdate()) { 1105 DLOG(WARNING) << "Detected update. Restarting browser."; 1106 RestartBackgroundInstance(); 1107 } 1108 } 1109 1110 #endif // (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) 1111