1 // Copyright (c) 2013 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/chromeos/chrome_browser_main_chromeos.h"
6 
7 #include <stddef.h>
8 
9 #include <string>
10 #include <utility>
11 #include <vector>
12 
13 #include "ash/keyboard/ui/resources/keyboard_resource_util.h"
14 #include "ash/public/ash_interfaces.h"
15 #include "ash/public/cpp/event_rewriter_controller.h"
16 #include "ash/public/cpp/keyboard/keyboard_controller.h"
17 #include "ash/shell.h"
18 #include "base/bind.h"
19 #include "base/callback.h"
20 #include "base/command_line.h"
21 #include "base/files/file_util.h"
22 #include "base/lazy_instance.h"
23 #include "base/linux_util.h"
24 #include "base/logging.h"
25 #include "base/macros.h"
26 #include "base/path_service.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_split.h"
29 #include "base/system/sys_info.h"
30 #include "base/task/task_traits.h"
31 #include "base/task/thread_pool.h"
32 #include "base/task/thread_pool/thread_pool_instance.h"
33 #include "build/branding_buildflags.h"
34 #include "chrome/browser/browser_process.h"
35 #include "chrome/browser/browser_process_platform_part_chromeos.h"
36 #include "chrome/browser/chrome_notification_types.h"
37 #include "chrome/browser/chromeos/accessibility/accessibility_event_rewriter_delegate.h"
38 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
39 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
40 #include "chrome/browser/chromeos/app_mode/arc/arc_kiosk_app_manager.h"
41 #include "chrome/browser/chromeos/app_mode/kiosk_app_launch_error.h"
42 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
43 #include "chrome/browser/chromeos/app_mode/kiosk_mode_idle_app_name_notification.h"
44 #include "chrome/browser/chromeos/app_mode/web_app/web_kiosk_app_manager.h"
45 #include "chrome/browser/chromeos/arc/session/arc_service_launcher.h"
46 #include "chrome/browser/chromeos/boot_times_recorder.h"
47 #include "chrome/browser/chromeos/crosapi/browser_manager.h"
48 #include "chrome/browser/chromeos/crostini/crostini_unsupported_action_notifier.h"
49 #include "chrome/browser/chromeos/crostini/crosvm_metrics.h"
50 #include "chrome/browser/chromeos/dbus/chrome_features_service_provider.h"
51 #include "chrome/browser/chromeos/dbus/component_updater_service_provider.h"
52 #include "chrome/browser/chromeos/dbus/cryptohome_key_delegate_service_provider.h"
53 #include "chrome/browser/chromeos/dbus/dbus_helper.h"
54 #include "chrome/browser/chromeos/dbus/drive_file_stream_service_provider.h"
55 #include "chrome/browser/chromeos/dbus/kiosk_info_service_provider.h"
56 #include "chrome/browser/chromeos/dbus/libvda_service_provider.h"
57 #include "chrome/browser/chromeos/dbus/lock_to_single_user_service_provider.h"
58 #include "chrome/browser/chromeos/dbus/machine_learning_decision_service_provider.h"
59 #include "chrome/browser/chromeos/dbus/memory_pressure_service_provider.h"
60 #include "chrome/browser/chromeos/dbus/metrics_event_service_provider.h"
61 #include "chrome/browser/chromeos/dbus/mojo_connection_service_provider.h"
62 #include "chrome/browser/chromeos/dbus/plugin_vm_service_provider.h"
63 #include "chrome/browser/chromeos/dbus/printers_service_provider.h"
64 #include "chrome/browser/chromeos/dbus/proxy_resolution_service_provider.h"
65 #include "chrome/browser/chromeos/dbus/screen_lock_service_provider.h"
66 #include "chrome/browser/chromeos/dbus/smb_fs_service_provider.h"
67 #include "chrome/browser/chromeos/dbus/virtual_file_request_service_provider.h"
68 #include "chrome/browser/chromeos/dbus/vm/vm_permission_service_provider.h"
69 #include "chrome/browser/chromeos/dbus/vm_applications_service_provider.h"
70 #include "chrome/browser/chromeos/device_name_store.h"
71 #include "chrome/browser/chromeos/display/quirks_manager_delegate_impl.h"
72 #include "chrome/browser/chromeos/events/event_rewriter_delegate_impl.h"
73 #include "chrome/browser/chromeos/extensions/default_app_order.h"
74 #include "chrome/browser/chromeos/extensions/login_screen/login_screen_ui/ui_handler.h"
75 #include "chrome/browser/chromeos/external_metrics.h"
76 #include "chrome/browser/chromeos/input_method/input_method_configuration.h"
77 #include "chrome/browser/chromeos/language_preferences.h"
78 #include "chrome/browser/chromeos/lock_screen_apps/state_controller.h"
79 #include "chrome/browser/chromeos/logging.h"
80 #include "chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.h"
81 #include "chrome/browser/chromeos/login/demo_mode/demo_session.h"
82 #include "chrome/browser/chromeos/login/helper.h"
83 #include "chrome/browser/chromeos/login/lock/screen_locker.h"
84 #include "chrome/browser/chromeos/login/login_screen_extensions_lifetime_manager.h"
85 #include "chrome/browser/chromeos/login/login_screen_extensions_storage_cleaner.h"
86 #include "chrome/browser/chromeos/login/login_wizard.h"
87 #include "chrome/browser/chromeos/login/session/chrome_session_manager.h"
88 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
89 #include "chrome/browser/chromeos/login/startup_utils.h"
90 #include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
91 #include "chrome/browser/chromeos/login/wizard_controller.h"
92 #include "chrome/browser/chromeos/net/network_health/network_health_service.h"
93 #include "chrome/browser/chromeos/net/network_portal_detector_impl.h"
94 #include "chrome/browser/chromeos/net/network_pref_state_observer.h"
95 #include "chrome/browser/chromeos/net/network_throttling_observer.h"
96 #include "chrome/browser/chromeos/network_change_manager_client.h"
97 #include "chrome/browser/chromeos/note_taking_helper.h"
98 #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h"
99 #include "chrome/browser/chromeos/platform_keys/key_permissions/key_permissions_manager_impl.h"
100 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
101 #include "chrome/browser/chromeos/policy/device_local_account.h"
102 #include "chrome/browser/chromeos/policy/lock_to_single_user_manager.h"
103 #include "chrome/browser/chromeos/power/auto_screen_brightness/controller.h"
104 #include "chrome/browser/chromeos/power/freezer_cgroup_process_manager.h"
105 #include "chrome/browser/chromeos/power/idle_action_warning_observer.h"
106 #include "chrome/browser/chromeos/power/ml/adaptive_screen_brightness_manager.h"
107 #include "chrome/browser/chromeos/power/power_data_collector.h"
108 #include "chrome/browser/chromeos/power/power_metrics_reporter.h"
109 #include "chrome/browser/chromeos/power/process_data_collector.h"
110 #include "chrome/browser/chromeos/power/renderer_freezer.h"
111 #include "chrome/browser/chromeos/power/smart_charging/smart_charging_manager.h"
112 #include "chrome/browser/chromeos/printing/bulk_printers_calculator_factory.h"
113 #include "chrome/browser/chromeos/profiles/profile_helper.h"
114 #include "chrome/browser/chromeos/scheduler_configuration_manager.h"
115 #include "chrome/browser/chromeos/settings/device_settings_service.h"
116 #include "chrome/browser/chromeos/settings/shutdown_policy_forwarder.h"
117 #include "chrome/browser/chromeos/startup_settings_cache.h"
118 #include "chrome/browser/chromeos/system/breakpad_consent_watcher.h"
119 #include "chrome/browser/chromeos/system/input_device_settings.h"
120 #include "chrome/browser/chromeos/system/user_removal_manager.h"
121 #include "chrome/browser/chromeos/system_token_cert_db_initializer.h"
122 #include "chrome/browser/chromeos/ui/gnubby_notification.h"
123 #include "chrome/browser/chromeos/ui/low_disk_notification.h"
124 #include "chrome/browser/chromeos/usb/cros_usb_detector.h"
125 #include "chrome/browser/chromeos/wilco_dtc_supportd/wilco_dtc_supportd_manager.h"
126 #include "chrome/browser/component_updater/cros_component_installer_chromeos.h"
127 #include "chrome/browser/defaults.h"
128 #include "chrome/browser/device_identity/device_oauth2_token_service_factory.h"
129 #include "chrome/browser/lifetime/application_lifetime.h"
130 #include "chrome/browser/net/chrome_network_delegate.h"
131 #include "chrome/browser/net/system_network_context_manager.h"
132 #include "chrome/browser/profiles/profile.h"
133 #include "chrome/browser/profiles/profile_manager.h"
134 #include "chrome/browser/task_manager/task_manager_interface.h"
135 #include "chrome/browser/ui/ash/assistant/assistant_client_impl.h"
136 #include "chrome/browser/ui/ash/assistant/assistant_state_client.h"
137 #include "chrome/browser/ui/ash/image_downloader_impl.h"
138 #include "chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.h"
139 #include "chrome/browser/ui/webui/chromeos/login/discover/discover_manager.h"
140 #include "chrome/common/channel_info.h"
141 #include "chrome/common/chrome_constants.h"
142 #include "chrome/common/chrome_features.h"
143 #include "chrome/common/chrome_paths.h"
144 #include "chrome/common/chrome_switches.h"
145 #include "chrome/common/logging_chrome.h"
146 #include "chrome/common/pref_names.h"
147 #include "chromeos/audio/audio_devices_pref_handler_impl.h"
148 #include "chromeos/audio/cras_audio_handler.h"
149 #include "chromeos/components/chromebox_for_meetings/buildflags/buildflags.h"  // PLATFORM_CFM
150 #include "chromeos/components/drivefs/fake_drivefs_launcher_client.h"
151 #include "chromeos/components/power/dark_resume_controller.h"
152 #include "chromeos/components/sensors/sensor_hal_dispatcher.h"
153 #include "chromeos/constants/chromeos_features.h"
154 #include "chromeos/constants/chromeos_switches.h"
155 #include "chromeos/cryptohome/async_method_caller.h"
156 #include "chromeos/cryptohome/cryptohome_parameters.h"
157 #include "chromeos/cryptohome/homedir_methods.h"
158 #include "chromeos/cryptohome/system_salt_getter.h"
159 #include "chromeos/dbus/constants/cryptohome_key_delegate_constants.h"
160 #include "chromeos/dbus/dbus_thread_manager.h"
161 #include "chromeos/dbus/power/power_manager_client.h"
162 #include "chromeos/dbus/power/power_policy_controller.h"
163 #include "chromeos/dbus/services/cros_dbus_service.h"
164 #include "chromeos/dbus/session_manager/session_manager_client.h"
165 #include "chromeos/dbus/util/version_loader.h"
166 #include "chromeos/disks/disk_mount_manager.h"
167 #include "chromeos/login/auth/login_event_recorder.h"
168 #include "chromeos/login/login_state/login_state.h"
169 #include "chromeos/login/session/session_termination_manager.h"
170 #include "chromeos/network/fast_transition_observer.h"
171 #include "chromeos/network/network_cert_loader.h"
172 #include "chromeos/network/network_handler.h"
173 #include "chromeos/network/portal_detector/network_portal_detector_stub.h"
174 #include "chromeos/services/cros_healthd/public/cpp/service_connection.h"
175 #include "chromeos/system/statistics_provider.h"
176 #include "chromeos/tpm/install_attributes.h"
177 #include "chromeos/tpm/tpm_token_loader.h"
178 #include "components/account_id/account_id.h"
179 #include "components/arc/arc_util.h"
180 #include "components/arc/enterprise/arc_data_snapshotd_manager.h"
181 #include "components/device_event_log/device_event_log.h"
182 #include "components/language/core/browser/pref_names.h"
183 #include "components/metrics/metrics_service.h"
184 #include "components/ownership/owner_key_util.h"
185 #include "components/prefs/pref_service.h"
186 #include "components/quirks/quirks_manager.h"
187 #include "components/session_manager/core/session_manager.h"
188 #include "components/sync/driver/sync_driver_switches.h"
189 #include "components/user_manager/user.h"
190 #include "components/user_manager/user_manager.h"
191 #include "components/user_manager/user_names.h"
192 #include "content/public/browser/audio_service.h"
193 #include "content/public/browser/browser_task_traits.h"
194 #include "content/public/browser/browser_thread.h"
195 #include "content/public/browser/device_service.h"
196 #include "content/public/browser/media_capture_devices.h"
197 #include "content/public/browser/media_session_service.h"
198 #include "content/public/browser/network_service_instance.h"
199 #include "content/public/browser/notification_service.h"
200 #include "content/public/common/content_switches.h"
201 #include "content/public/common/main_function_params.h"
202 #include "dbus/object_path.h"
203 #include "device/bluetooth/bluetooth_adapter_factory.h"
204 #include "net/base/network_change_notifier.h"
205 #include "net/base/network_change_notifier_posix.h"
206 #include "printing/backend/print_backend.h"
207 #include "rlz/buildflags/buildflags.h"
208 #include "services/audio/public/cpp/sounds/sounds_manager.h"
209 #include "third_party/cros_system_api/dbus/service_constants.h"
210 #include "ui/base/ime/chromeos/ime_keyboard.h"
211 #include "ui/base/ime/chromeos/input_method_manager.h"
212 #include "ui/base/ime/chromeos/input_method_util.h"
213 #include "ui/base/pointer/pointer_device.h"
214 #include "ui/base/ui_base_features.h"
215 #include "ui/chromeos/events/pref_names.h"
216 #include "ui/events/event_utils.h"
217 
218 #if BUILDFLAG(PLATFORM_CFM)
219 #include "chrome/browser/chromeos/chromebox_for_meetings/cfm_chrome_services.h"
220 #endif
221 
222 #if BUILDFLAG(ENABLE_RLZ)
223 #include "components/rlz/rlz_tracker.h"
224 #endif
225 
226 namespace chromeos {
227 
228 namespace {
229 
ChromeOSVersionCallback(const std::string & version)230 void ChromeOSVersionCallback(const std::string& version) {
231   base::SetLinuxDistro(std::string("CrOS ") + version);
232 }
233 
ShouldAutoLaunchKioskApp(const base::CommandLine & command_line)234 bool ShouldAutoLaunchKioskApp(const base::CommandLine& command_line) {
235   KioskAppManager* app_manager = KioskAppManager::Get();
236   WebKioskAppManager* web_app_manager = WebKioskAppManager::Get();
237   ArcKioskAppManager* arc_app_manager = ArcKioskAppManager::Get();
238   return command_line.HasSwitch(switches::kLoginManager) &&
239          (app_manager->IsAutoLaunchEnabled() ||
240           web_app_manager->GetAutoLaunchAccountId().is_valid() ||
241           arc_app_manager->GetAutoLaunchAccountId().is_valid()) &&
242          KioskAppLaunchError::Get() == KioskAppLaunchError::NONE;
243 }
244 
245 // Creates an instance of the NetworkPortalDetector implementation or a stub.
InitializeNetworkPortalDetector()246 void InitializeNetworkPortalDetector() {
247   if (network_portal_detector::SetForTesting())
248     return;
249   if (base::CommandLine::ForCurrentProcess()->HasSwitch(
250           ::switches::kTestType)) {
251     network_portal_detector::SetNetworkPortalDetector(
252         new NetworkPortalDetectorStub());
253   } else {
254     network_portal_detector::SetNetworkPortalDetector(
255         new NetworkPortalDetectorImpl());
256   }
257 }
258 
259 }  // namespace
260 
261 namespace internal {
262 
263 // Wrapper class for initializing D-Bus services and shutting them down.
264 class DBusServices {
265  public:
DBusServices(const content::MainFunctionParams & parameters)266   explicit DBusServices(const content::MainFunctionParams& parameters) {
267     PowerPolicyController::Initialize(PowerManagerClient::Get());
268 
269     dbus::Bus* system_bus = DBusThreadManager::Get()->IsUsingFakes()
270                                 ? nullptr
271                                 : DBusThreadManager::Get()->GetSystemBus();
272 
273     // See also PostBrowserStart() where machine_learning_decision_service_ is
274     // initialized.
275 
276     proxy_resolution_service_ = CrosDBusService::Create(
277         system_bus, kNetworkProxyServiceName,
278         dbus::ObjectPath(kNetworkProxyServicePath),
279         CrosDBusService::CreateServiceProviderList(
280             std::make_unique<ProxyResolutionServiceProvider>()));
281 
282     kiosk_info_service_ =
283         CrosDBusService::Create(system_bus, kKioskAppServiceName,
284                                 dbus::ObjectPath(kKioskAppServicePath),
285                                 CrosDBusService::CreateServiceProviderList(
286                                     std::make_unique<KioskInfoService>()));
287 
288     metrics_event_service_ = CrosDBusService::Create(
289         system_bus, kMetricsEventServiceName,
290         dbus::ObjectPath(kMetricsEventServicePath),
291         CrosDBusService::CreateServiceProviderList(
292             std::make_unique<MetricsEventServiceProvider>()));
293 
294     plugin_vm_service_ = CrosDBusService::Create(
295         system_bus, kPluginVmServiceName,
296         dbus::ObjectPath(kPluginVmServicePath),
297         CrosDBusService::CreateServiceProviderList(
298             std::make_unique<PluginVmServiceProvider>()));
299 
300     screen_lock_service_ = CrosDBusService::Create(
301         system_bus, kScreenLockServiceName,
302         dbus::ObjectPath(kScreenLockServicePath),
303         CrosDBusService::CreateServiceProviderList(
304             std::make_unique<ScreenLockServiceProvider>()));
305 
306     virtual_file_request_service_ = CrosDBusService::Create(
307         system_bus, kVirtualFileRequestServiceName,
308         dbus::ObjectPath(kVirtualFileRequestServicePath),
309         CrosDBusService::CreateServiceProviderList(
310             std::make_unique<VirtualFileRequestServiceProvider>()));
311 
312     component_updater_service_ = CrosDBusService::Create(
313         system_bus, kComponentUpdaterServiceName,
314         dbus::ObjectPath(kComponentUpdaterServicePath),
315         CrosDBusService::CreateServiceProviderList(
316             std::make_unique<ComponentUpdaterServiceProvider>(
317                 g_browser_process->platform_part()
318                     ->cros_component_manager()
319                     .get())));
320 
321     chrome_features_service_ = CrosDBusService::Create(
322         system_bus, kChromeFeaturesServiceName,
323         dbus::ObjectPath(kChromeFeaturesServicePath),
324         CrosDBusService::CreateServiceProviderList(
325             std::make_unique<ChromeFeaturesServiceProvider>()));
326 
327     printers_service_ = CrosDBusService::Create(
328         system_bus, kPrintersServiceName,
329         dbus::ObjectPath(kPrintersServicePath),
330         CrosDBusService::CreateServiceProviderList(
331             std::make_unique<PrintersServiceProvider>()));
332 
333     vm_applications_service_ = CrosDBusService::Create(
334         system_bus, vm_tools::apps::kVmApplicationsServiceName,
335         dbus::ObjectPath(vm_tools::apps::kVmApplicationsServicePath),
336         CrosDBusService::CreateServiceProviderList(
337             std::make_unique<VmApplicationsServiceProvider>()));
338 
339     vm_permission_service_ = CrosDBusService::Create(
340         system_bus, kVmPermissionServiceName,
341         dbus::ObjectPath(kVmPermissionServicePath),
342         CrosDBusService::CreateServiceProviderList(
343             std::make_unique<VmPermissionServiceProvider>()));
344 
345     drive_file_stream_service_ = CrosDBusService::Create(
346         system_bus, drivefs::kDriveFileStreamServiceName,
347         dbus::ObjectPath(drivefs::kDriveFileStreamServicePath),
348         CrosDBusService::CreateServiceProviderList(
349             std::make_unique<DriveFileStreamServiceProvider>()));
350 
351     cryptohome_key_delegate_service_ = CrosDBusService::Create(
352         system_bus, cryptohome::kCryptohomeKeyDelegateServiceName,
353         dbus::ObjectPath(cryptohome::kCryptohomeKeyDelegateServicePath),
354         CrosDBusService::CreateServiceProviderList(
355             std::make_unique<CryptohomeKeyDelegateServiceProvider>()));
356 
357     smb_fs_service_ =
358         CrosDBusService::Create(system_bus, smbfs::kSmbFsServiceName,
359                                 dbus::ObjectPath(smbfs::kSmbFsServicePath),
360                                 CrosDBusService::CreateServiceProviderList(
361                                     std::make_unique<SmbFsServiceProvider>()));
362     lock_to_single_user_service_ = CrosDBusService::Create(
363         system_bus, lock_to_single_user::kLockToSingleUserServiceName,
364         dbus::ObjectPath(lock_to_single_user::kLockToSingleUserServicePath),
365         CrosDBusService::CreateServiceProviderList(
366             std::make_unique<LockToSingleUserServiceProvider>()));
367 
368     memory_pressure_service_ = CrosDBusService::Create(
369         system_bus, memory_pressure::kMemoryPressureServiceName,
370         dbus::ObjectPath(memory_pressure::kMemoryPressureServicePath),
371         CrosDBusService::CreateServiceProviderList(
372             std::make_unique<MemoryPressureServiceProvider>()));
373 
374     mojo_connection_service_ = CrosDBusService::Create(
375         system_bus,
376         ::mojo_connection_service::kMojoConnectionServiceServiceName,
377         dbus::ObjectPath(
378             ::mojo_connection_service::kMojoConnectionServiceServicePath),
379         CrosDBusService::CreateServiceProviderList(
380             std::make_unique<MojoConnectionServiceProvider>()));
381 
382     if (arc::IsArcVmEnabled()) {
383       libvda_service_ = CrosDBusService::Create(
384           system_bus, libvda::kLibvdaServiceName,
385           dbus::ObjectPath(libvda::kLibvdaServicePath),
386           CrosDBusService::CreateServiceProviderList(
387               std::make_unique<LibvdaServiceProvider>()));
388     }
389 
390     // Initialize PowerDataCollector after DBusThreadManager is initialized.
391     PowerDataCollector::Initialize();
392     ProcessDataCollector::Initialize();
393 
394     LoginState::Initialize();
395     TPMTokenLoader::Initialize();
396     NetworkCertLoader::Initialize();
397 
398     disks::DiskMountManager::Initialize();
399     cryptohome::AsyncMethodCaller::Initialize();
400     cryptohome::HomedirMethods::Initialize();
401 
402     NetworkHandler::Initialize();
403 
404     sensors::SensorHalDispatcher::Initialize();
405 
406     DeviceSettingsService::Get()->SetSessionManager(
407         SessionManagerClient::Get(),
408         OwnerSettingsServiceChromeOSFactory::GetInstance()->GetOwnerKeyUtil());
409   }
410 
CreateMachineLearningDecisionProvider()411   void CreateMachineLearningDecisionProvider() {
412     dbus::Bus* system_bus = DBusThreadManager::Get()->IsUsingFakes()
413                                 ? nullptr
414                                 : DBusThreadManager::Get()->GetSystemBus();
415     // TODO(alanlxl): update Ml here to MachineLearning after powerd is
416     // uprevved.
417     machine_learning_decision_service_ = CrosDBusService::Create(
418         system_bus, kMlDecisionServiceName,
419         dbus::ObjectPath(kMlDecisionServicePath),
420         CrosDBusService::CreateServiceProviderList(
421             std::make_unique<MachineLearningDecisionServiceProvider>()));
422   }
423 
~DBusServices()424   ~DBusServices() {
425     sensors::SensorHalDispatcher::Shutdown();
426     NetworkHandler::Shutdown();
427     cryptohome::AsyncMethodCaller::Shutdown();
428     disks::DiskMountManager::Shutdown();
429     LoginState::Shutdown();
430     NetworkCertLoader::Shutdown();
431     TPMTokenLoader::Shutdown();
432     proxy_resolution_service_.reset();
433     kiosk_info_service_.reset();
434     metrics_event_service_.reset();
435     plugin_vm_service_.reset();
436     printers_service_.reset();
437     virtual_file_request_service_.reset();
438     component_updater_service_.reset();
439     chrome_features_service_.reset();
440     vm_applications_service_.reset();
441     vm_permission_service_.reset();
442     drive_file_stream_service_.reset();
443     cryptohome_key_delegate_service_.reset();
444     lock_to_single_user_service_.reset();
445     memory_pressure_service_.reset();
446     mojo_connection_service_.reset();
447     ProcessDataCollector::Shutdown();
448     PowerDataCollector::Shutdown();
449     PowerPolicyController::Shutdown();
450     device::BluetoothAdapterFactory::Shutdown();
451   }
452 
PreAshShutdown()453   void PreAshShutdown() {
454     // Services depending on ash should be released here.
455     machine_learning_decision_service_.reset();
456   }
457 
458  private:
459   std::unique_ptr<CrosDBusService> proxy_resolution_service_;
460   std::unique_ptr<CrosDBusService> kiosk_info_service_;
461   std::unique_ptr<CrosDBusService> metrics_event_service_;
462   std::unique_ptr<CrosDBusService> plugin_vm_service_;
463   std::unique_ptr<CrosDBusService> printers_service_;
464   std::unique_ptr<CrosDBusService> screen_lock_service_;
465   std::unique_ptr<CrosDBusService> virtual_file_request_service_;
466   std::unique_ptr<CrosDBusService> component_updater_service_;
467   std::unique_ptr<CrosDBusService> chrome_features_service_;
468   std::unique_ptr<CrosDBusService> vm_applications_service_;
469   std::unique_ptr<CrosDBusService> vm_permission_service_;
470   std::unique_ptr<CrosDBusService> drive_file_stream_service_;
471   std::unique_ptr<CrosDBusService> cryptohome_key_delegate_service_;
472   std::unique_ptr<CrosDBusService> libvda_service_;
473   std::unique_ptr<CrosDBusService> machine_learning_decision_service_;
474   std::unique_ptr<CrosDBusService> smb_fs_service_;
475   std::unique_ptr<CrosDBusService> lock_to_single_user_service_;
476   std::unique_ptr<CrosDBusService> memory_pressure_service_;
477   std::unique_ptr<CrosDBusService> mojo_connection_service_;
478 
479   DISALLOW_COPY_AND_ASSIGN(DBusServices);
480 };
481 
482 }  // namespace internal
483 
484 // ChromeBrowserMainPartsChromeos ----------------------------------------------
485 
ChromeBrowserMainPartsChromeos(const content::MainFunctionParams & parameters,StartupData * startup_data)486 ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
487     const content::MainFunctionParams& parameters,
488     StartupData* startup_data)
489     : ChromeBrowserMainPartsLinux(parameters, startup_data) {}
490 
~ChromeBrowserMainPartsChromeos()491 ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
492   // To be precise, logout (browser shutdown) is not yet done, but the
493   // remaining work is negligible, hence we say LogoutDone here.
494   BootTimesRecorder::Get()->AddLogoutTimeMarker("LogoutDone", false);
495   BootTimesRecorder::Get()->WriteLogoutTimes();
496 }
497 
498 // content::BrowserMainParts and ChromeBrowserMainExtraParts overrides ---------
499 
PreEarlyInitialization()500 int ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
501   base::CommandLine* singleton_command_line =
502       base::CommandLine::ForCurrentProcess();
503 
504   if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
505     // Disable sync and extensions if we're in "browse without sign-in" mode.
506     singleton_command_line->AppendSwitch(::switches::kDisableSync);
507     singleton_command_line->AppendSwitch(::switches::kDisableExtensions);
508     browser_defaults::bookmarks_enabled = false;
509   }
510 
511   // If we're not running on real Chrome OS hardware (or under VM), and are not
512   // showing the login manager or attempting a command line login, login with a
513   // stub user.
514   if (!base::SysInfo::IsRunningOnChromeOS() &&
515       !parsed_command_line().HasSwitch(switches::kLoginManager) &&
516       !parsed_command_line().HasSwitch(switches::kLoginUser) &&
517       !parsed_command_line().HasSwitch(switches::kGuestSession)) {
518     singleton_command_line->AppendSwitchASCII(
519         switches::kLoginUser,
520         cryptohome::Identification(user_manager::StubAccountId()).id());
521     if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) {
522       singleton_command_line->AppendSwitchASCII(switches::kLoginProfile,
523                                                 chrome::kTestUserProfileDir);
524     }
525     LOG(WARNING) << "Running as stub user with profile dir: "
526                  << singleton_command_line
527                         ->GetSwitchValuePath(switches::kLoginProfile)
528                         .value();
529   }
530 
531   // DBus is initialized in ChromeMainDelegate::PostEarlyInitialization().
532   CHECK(DBusThreadManager::IsInitialized());
533 
534 #if !defined(USE_REAL_DBUS_CLIENTS)
535   if (!base::SysInfo::IsRunningOnChromeOS() &&
536       parsed_command_line().HasSwitch(
537           switches::kFakeDriveFsLauncherChrootPath) &&
538       parsed_command_line().HasSwitch(
539           switches::kFakeDriveFsLauncherSocketPath)) {
540     drivefs::FakeDriveFsLauncherClient::Init(
541         parsed_command_line().GetSwitchValuePath(
542             switches::kFakeDriveFsLauncherChrootPath),
543         parsed_command_line().GetSwitchValuePath(
544             switches::kFakeDriveFsLauncherSocketPath));
545   }
546 #endif  // !defined(USE_REAL_DBUS_CLIENTS)
547 
548   return ChromeBrowserMainPartsLinux::PreEarlyInitialization();
549 }
550 
PreMainMessageLoopStart()551 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
552   // Initialize session manager in early stage in case others want to listen
553   // to session state change right after browser is started.
554   g_browser_process->platform_part()->InitializeSessionManager();
555 
556   ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
557 }
558 
PostMainMessageLoopStart()559 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
560   // device_event_log must be initialized after the message loop.
561   device_event_log::Initialize(0 /* default max entries */);
562 
563   // This has to be initialized before DBusServices
564   // (ComponentUpdaterServiceProvider).
565   g_browser_process->platform_part()->InitializeCrosComponentManager();
566 
567   dbus_services_.reset(new internal::DBusServices(parameters()));
568 
569   // Need to be done after LoginState has been initialized in DBusServices().
570   ::memory::MemoryKillsMonitor::Initialize();
571 
572   ChromeBrowserMainPartsLinux::PostMainMessageLoopStart();
573 }
574 
575 // Threads are initialized between MainMessageLoopStart and MainMessageLoopRun.
576 // about_flags settings are applied in ChromeBrowserMainParts::PreCreateThreads.
PreMainMessageLoopRun()577 void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
578   network_change_manager_client_.reset(new NetworkChangeManagerClient(
579       static_cast<net::NetworkChangeNotifierPosix*>(
580           content::GetNetworkChangeNotifier())));
581 
582   // Set the crypto thread after the IO thread has been created/started.
583   TPMTokenLoader::Get()->SetCryptoTaskRunner(
584       content::GetIOThreadTaskRunner({}));
585 
586   // Initialize NSS database for system token.
587   system_token_certdb_initializer_ =
588       std::make_unique<SystemTokenCertDBInitializer>();
589 
590   system_token_key_permissions_manager_ = platform_keys::
591       KeyPermissionsManagerImpl::CreateSystemTokenKeyPermissionsManager();
592 
593   mojo::PendingRemote<media_session::mojom::MediaControllerManager>
594       media_controller_manager;
595   content::GetMediaSessionService().BindMediaControllerManager(
596       media_controller_manager.InitWithNewPipeAndPassReceiver());
597   CrasAudioHandler::Initialize(
598       std::move(media_controller_manager),
599       new AudioDevicesPrefHandlerImpl(g_browser_process->local_state()));
600 
601   content::MediaCaptureDevices::GetInstance()->AddVideoCaptureObserver(
602       CrasAudioHandler::Get());
603 
604   quirks::QuirksManager::Initialize(
605       std::unique_ptr<quirks::QuirksManager::Delegate>(
606           new quirks::QuirksManagerDelegateImpl()),
607       g_browser_process->local_state(),
608       g_browser_process->system_network_context_manager()
609           ->GetSharedURLLoaderFactory());
610 
611   // Start loading machine statistics here. StatisticsProvider::Shutdown()
612   // will ensure that loading is aborted on early exit.
613   bool load_oem_statistics = !StartupUtils::IsOobeCompleted();
614   system::StatisticsProvider::GetInstance()->StartLoadingMachineStatistics(
615       load_oem_statistics);
616 
617   base::FilePath downloads_directory;
618   CHECK(base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
619                                &downloads_directory));
620 
621   DeviceOAuth2TokenServiceFactory::Initialize(
622       g_browser_process->system_network_context_manager()
623           ->GetSharedURLLoaderFactory(),
624       g_browser_process->local_state());
625 
626   fast_transition_observer_.reset(
627       new FastTransitionObserver(g_browser_process->local_state()));
628   network_throttling_observer_.reset(
629       new NetworkThrottlingObserver(g_browser_process->local_state()));
630 
631   discover_manager_ = std::make_unique<DiscoverManager>();
632 
633   g_browser_process->platform_part()->InitializeSchedulerConfigurationManager();
634   arc_service_launcher_ = std::make_unique<arc::ArcServiceLauncher>(
635       g_browser_process->platform_part()->scheduler_configuration_manager());
636 
637   session_termination_manager_ =
638       std::make_unique<chromeos::SessionTerminationManager>();
639 
640   // This should be in PreProfileInit but it needs to be created before the
641   // policy connector is started.
642   bulk_printers_calculator_factory_ =
643       std::make_unique<BulkPrintersCalculatorFactory>();
644 
645   // StatsReportingController is created in
646   // ChromeBrowserMainParts::PreCreateThreads, so this must come afterwards.
647   chromeos::StatsReportingController* stats_controller =
648       chromeos::StatsReportingController::Get();
649   // |stats_controller| can be nullptr if ChromeBrowserMainParts's
650   // browser_process_->GetApplicationLocale() returns empty. We're trying to
651   // show an error message in that case, so don't just crash. (See
652   // ChromeBrowserMainParts::PreCreateThreadsImpl()).
653   if (stats_controller != nullptr) {
654     breakpad_consent_watcher_ =
655         system::BreakpadConsentWatcher::Initialize(stats_controller);
656   }
657 
658 #if BUILDFLAG(PLATFORM_CFM)
659   chromeos::cfm::InitializeCfmServices();
660 #endif  // BUILDFLAG(PLATFORM_CFM)
661 
662   ChromeBrowserMainPartsLinux::PreMainMessageLoopRun();
663 }
664 
PreProfileInit()665 void ChromeBrowserMainPartsChromeos::PreProfileInit() {
666   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
667   // -- immediately before Profile creation().
668 
669   // PreProfileInit() is not always called if no browser process is started
670   // (e.g. during some browser tests). Set a boolean so that we do not try to
671   // destroy singletons that are initialized here.
672   pre_profile_init_called_ = true;
673 
674   // Now that the file thread exists we can record our stats.
675   BootTimesRecorder::Get()->RecordChromeMainStats();
676   LoginEventRecorder::Get()->SetDelegate(BootTimesRecorder::Get());
677 
678   // Trigger prefetching of ownership status.
679   DeviceSettingsService::Get()->Load();
680 
681   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
682   // -- just before CreateProfile().
683 
684   g_browser_process->platform_part()->InitializeChromeUserManager();
685 
686   arc_data_snapshotd_manager_ =
687       std::make_unique<arc::data_snapshotd::ArcDataSnapshotdManager>(
688           g_browser_process->local_state(),
689           base::BindOnce(chrome::AttemptUserExit));
690   if (base::FeatureList::IsEnabled(::features::kWilcoDtc))
691     wilco_dtc_supportd_manager_ = std::make_unique<WilcoDtcSupportdManager>();
692 
693   ScreenLocker::InitClass();
694 
695   // This forces the ProfileManager to be created and register for the
696   // notification it needs to track the logged in user.
697   g_browser_process->profile_manager();
698 
699   // Must come after User Manager is inited.
700   lock_to_single_user_manager_ =
701       std::make_unique<policy::LockToSingleUserManager>();
702 
703   // AccessibilityManager and SystemKeyEventListener use InputMethodManager.
704   input_method::Initialize();
705 
706   // keyboard::KeyboardController initializes ChromeKeyboardUI which depends
707   // on ChromeKeyboardControllerClient.
708   chrome_keyboard_controller_client_ = ChromeKeyboardControllerClient::Create();
709 
710   // ProfileHelper has to be initialized after UserManager instance is created.
711   ProfileHelper::Get()->Initialize();
712 
713   // If kLoginUser is passed this indicates that user has already
714   // logged in and we should behave accordingly.
715   bool immediate_login = parsed_command_line().HasSwitch(switches::kLoginUser);
716   if (immediate_login) {
717     // Redirects Chrome logging to the user data dir.
718     logging::RedirectChromeLogging(parsed_command_line());
719 
720     // Load the default app order synchronously for restarting case.
721     app_order_loader_.reset(
722         new default_app_order::ExternalLoader(false /* async */));
723   }
724 
725   if (!app_order_loader_) {
726     app_order_loader_.reset(
727         new default_app_order::ExternalLoader(true /* async */));
728   }
729 
730   audio::SoundsManager::Create(content::GetAudioServiceStreamFactoryBinder());
731 
732   // |arc_service_launcher_| must be initialized before NoteTakingHelper.
733   NoteTakingHelper::Initialize();
734 
735   AccessibilityManager::Initialize();
736 
737   // Initialize magnification manager before ash tray is created. And this
738   // must be placed after UserManager initialization.
739   MagnificationManager::Initialize();
740 
741   // Has to be initialized before |assistant_client_|;
742   image_downloader_ = std::make_unique<ImageDownloaderImpl>();
743 
744   // Requires UserManager.
745   assistant_state_client_ = std::make_unique<AssistantStateClient>();
746 
747   // Assistant has to be initialized before
748   // ChromeBrowserMainExtraPartsAsh::session_controller_client_ to avoid race of
749   // SessionChanged event and assistant_client initialization. It must come
750   // after AssistantStateClient.
751   assistant_client_ = std::make_unique<AssistantClientImpl>();
752 
753   base::ThreadPool::PostTaskAndReplyWithResult(
754       FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
755       base::BindOnce(&version_loader::GetVersion, version_loader::VERSION_FULL),
756       base::BindOnce(&ChromeOSVersionCallback));
757 
758   arc_kiosk_app_manager_.reset(new ArcKioskAppManager());
759   web_kiosk_app_manager_.reset(new WebKioskAppManager());
760 
761   if (base::FeatureList::IsEnabled(features::kEnableHostnameSetting)) {
762     DeviceNameStore::GetInstance()->Initialize(
763         g_browser_process->local_state());
764   }
765 
766   // Make sure that wallpaper boot transition and other delays in OOBE
767   // are disabled for tests and kiosk app launch by default.
768   // Individual tests may enable them if they want.
769   if (parsed_command_line().HasSwitch(::switches::kTestType) ||
770       ShouldAutoLaunchKioskApp(parsed_command_line())) {
771     WizardController::SetZeroDelays();
772   }
773 
774   // On Chrome OS, Chrome does not exit when all browser windows are closed.
775   // UnregisterKeepAlive is called from chrome::HandleAppExitingForPlatform.
776   if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
777           ::switches::kDisableZeroBrowsersOpenForTests)) {
778     g_browser_process->platform_part()->RegisterKeepAlive();
779   }
780 
781   // NOTE: Calls ChromeBrowserMainParts::PreProfileInit() which calls
782   // ChromeBrowserMainExtraPartsAsh::PreProfileInit() which initializes
783   // ash::Shell.
784   ChromeBrowserMainPartsLinux::PreProfileInit();
785 
786   // ash::Shell must be initialized before we can ask Ash to bind a
787   // CrosDisplayConfigController.
788   mojo::PendingRemote<ash::mojom::CrosDisplayConfigController> display_config;
789   ash::BindCrosDisplayConfigController(
790       display_config.InitWithNewPipeAndPassReceiver());
791   arc_service_launcher_->Initialize(std::move(display_config));
792 
793   // Needs to be initialized after ash::Shell.
794   chrome_keyboard_controller_client_->Init(ash::KeyboardController::Get());
795 
796   // Initialize the keyboard before any session state changes (i.e. before
797   // loading the default profile).
798   keyboard::InitializeKeyboardResources();
799 
800   lock_screen_apps_state_controller_ =
801       std::make_unique<lock_screen_apps::StateController>();
802   lock_screen_apps_state_controller_->Initialize();
803 
804   // Always construct BrowserManager, even if the lacros flag is disabled, so
805   // it can do cleanup work if needed. Initialized in PreProfileInit because the
806   // profile-keyed service AppService can call into it.
807   browser_manager_ = std::make_unique<crosapi::BrowserManager>(
808       g_browser_process->platform_part()->cros_component_manager());
809 
810   if (immediate_login) {
811     const std::string cryptohome_id =
812         parsed_command_line().GetSwitchValueASCII(switches::kLoginUser);
813     const AccountId account_id(
814         cryptohome::Identification::FromString(cryptohome_id).GetAccountId());
815 
816     user_manager::UserManager* user_manager = user_manager::UserManager::Get();
817 
818     if (policy::IsDeviceLocalAccountUser(account_id.GetUserEmail(), nullptr) &&
819         !user_manager->IsKnownUser(account_id)) {
820       // When a device-local account is removed, its policy is deleted from disk
821       // immediately. If a session using this account happens to be in progress,
822       // the session is allowed to continue with policy served from an in-memory
823       // cache. If Chrome crashes later in the session, the policy becomes
824       // completely unavailable. Exit the session in that case, rather than
825       // allowing it to continue without policy.
826       chrome::AttemptUserExit();
827       return;
828     }
829 
830     // In case of multi-profiles --login-profile will contain user_id_hash.
831     std::string user_id_hash =
832         parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile);
833     session_manager::SessionManager::Get()->CreateSessionForRestart(
834         account_id, user_id_hash);
835 
836     // If restarting demo session, mark demo session as started before primary
837     // profile starts initialization so browser context keyed services created
838     // with the browser context (for example ExtensionService) can use
839     // DemoSession::started().
840     DemoSession::StartIfInDemoMode();
841 
842     VLOG(1) << "Relaunching browser for user: " << account_id.Serialize()
843             << " with hash: " << user_id_hash;
844   }
845 }
846 
847 class GuestLanguageSetCallbackData {
848  public:
GuestLanguageSetCallbackData(Profile * profile)849   explicit GuestLanguageSetCallbackData(Profile* profile) : profile(profile) {}
850 
851   // Must match SwitchLanguageCallback type.
852   static void Callback(
853       const std::unique_ptr<GuestLanguageSetCallbackData>& self,
854       const locale_util::LanguageSwitchResult& result);
855 
856   Profile* profile;
857 };
858 
859 // static
Callback(const std::unique_ptr<GuestLanguageSetCallbackData> & self,const locale_util::LanguageSwitchResult & result)860 void GuestLanguageSetCallbackData::Callback(
861     const std::unique_ptr<GuestLanguageSetCallbackData>& self,
862     const locale_util::LanguageSwitchResult& result) {
863   input_method::InputMethodManager* manager =
864       input_method::InputMethodManager::Get();
865   scoped_refptr<input_method::InputMethodManager::State> ime_state =
866       manager->GetActiveIMEState();
867   // For guest mode, we should always use the first login input methods.
868   // This is to keep consistency with UserSessionManager::SetFirstLoginPrefs().
869   // See crbug.com/530808.
870   std::vector<std::string> input_methods;
871   manager->GetInputMethodUtil()->GetFirstLoginInputMethodIds(
872       result.loaded_locale, ime_state->GetCurrentInputMethod(), &input_methods);
873   ime_state->ReplaceEnabledInputMethods(input_methods);
874 
875   // Active layout must be hardware "login layout".
876   // The previous one must be "locale default layout".
877   // First, enable all hardware input methods.
878   input_methods = manager->GetInputMethodUtil()->GetHardwareInputMethodIds();
879   for (size_t i = 0; i < input_methods.size(); ++i)
880     ime_state->EnableInputMethod(input_methods[i]);
881 
882   // Second, enable locale based input methods.
883   const std::string locale_default_input_method =
884       manager->GetInputMethodUtil()->GetLanguageDefaultInputMethodId(
885           result.loaded_locale);
886   if (!locale_default_input_method.empty()) {
887     PrefService* user_prefs = self->profile->GetPrefs();
888     user_prefs->SetString(prefs::kLanguagePreviousInputMethod,
889                           locale_default_input_method);
890     ime_state->EnableInputMethod(locale_default_input_method);
891   }
892 
893   // Finally, activate the first login input method.
894   const std::vector<std::string>& login_input_methods =
895       manager->GetInputMethodUtil()->GetHardwareLoginInputMethodIds();
896   ime_state->ChangeInputMethod(login_input_methods[0],
897                                false /* show_message */);
898 }
899 
SetGuestLocale(Profile * const profile)900 void SetGuestLocale(Profile* const profile) {
901   std::unique_ptr<GuestLanguageSetCallbackData> data(
902       new GuestLanguageSetCallbackData(profile));
903   locale_util::SwitchLanguageCallback callback(base::Bind(
904       &GuestLanguageSetCallbackData::Callback, base::Passed(std::move(data))));
905   const user_manager::User* const user =
906       ProfileHelper::Get()->GetUserByProfile(profile);
907   UserSessionManager::GetInstance()->RespectLocalePreference(profile, user,
908                                                              callback);
909 }
910 
PostProfileInit()911 void ChromeBrowserMainPartsChromeos::PostProfileInit() {
912   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
913   // -- just after CreateProfile().
914 
915   if (ProfileHelper::IsSigninProfile(profile())) {
916     // Flush signin profile if it is just created (new device or after recovery)
917     // to ensure it is correctly persisted.
918     if (profile()->IsNewProfile())
919       ProfileHelper::Get()->FlushProfile(profile());
920   } else {
921     // Force loading of signin profile if it was not loaded before. It is
922     // possible when we are restoring session or skipping login screen for some
923     // other reason.
924     ProfileHelper::GetSigninProfile();
925   }
926 
927   BootTimesRecorder::Get()->OnChromeProcessStart();
928 
929   // Initialize the network portal detector for Chrome OS. The network
930   // portal detector starts to listen for notifications from
931   // NetworkStateHandler and initiates captive portal detection for
932   // active networks. Should be called before call to initialize
933   // ChromeSessionManager because it depends on NetworkPortalDetector.
934   InitializeNetworkPortalDetector();
935   {
936 #if BUILDFLAG(GOOGLE_CHROME_BRANDING)
937     bool is_official_build = true;
938 #else
939     bool is_official_build = false;
940 #endif
941     // Enable portal detector if EULA was previously accepted or if
942     // this is an unofficial build.
943     if (!is_official_build || StartupUtils::IsEulaAccepted())
944       network_portal_detector::GetInstance()->Enable(true);
945   }
946 
947   // Initialize an observer to update NetworkHandler's pref based services.
948   network_pref_state_observer_ = std::make_unique<NetworkPrefStateObserver>();
949 
950   // Initialize the NetworkHealth aggregator.
951   network_health::NetworkHealthService::GetInstance();
952 
953   // Create the service connection to CrosHealthd platform service instance.
954   auto* cros_healthd = cros_healthd::ServiceConnection::GetInstance();
955 
956   // Pass a callback to the CrosHealthd service connection that binds a pending
957   // remote to service.
958   cros_healthd->SetBindNetworkHealthServiceCallback(base::BindRepeating([] {
959     return network_health::NetworkHealthService::GetInstance()
960         ->GetHealthRemoteAndBindReceiver();
961   }));
962 
963   // Pass a callback to the CrosHealthd service connection that binds a pending
964   // remote to the interface.
965   cros_healthd->SetBindNetworkDiagnosticsRoutinesCallback(
966       base::BindRepeating([] {
967         return network_health::NetworkHealthService::GetInstance()
968             ->GetDiagnosticsRemoteAndBindReceiver();
969       }));
970 
971   // Initialize input methods.
972   input_method::InputMethodManager* manager =
973       input_method::InputMethodManager::Get();
974   UserSessionManager* session_manager = UserSessionManager::GetInstance();
975   DCHECK(manager);
976   DCHECK(session_manager);
977 
978   manager->SetState(session_manager->GetDefaultIMEState(profile()));
979 
980   bool is_running_test = parameters().ui_task != nullptr;
981   g_browser_process->platform_part()->session_manager()->Initialize(
982       parsed_command_line(), profile(), is_running_test);
983 
984   // Guest user profile is never initialized with locale settings,
985   // so we need special handling for Guest session.
986   if (user_manager::UserManager::Get()->IsLoggedInAsGuest())
987     SetGuestLocale(profile());
988 
989   renderer_freezer_ = std::make_unique<RendererFreezer>(
990       std::make_unique<FreezerCgroupProcessManager>());
991 
992   power_metrics_reporter_ = std::make_unique<PowerMetricsReporter>(
993       PowerManagerClient::Get(), g_browser_process->local_state());
994 
995   g_browser_process->platform_part()->InitializeAutomaticRebootManager();
996   user_removal_manager::RemoveUsersIfNeeded();
997 
998   // This observer cannot be created earlier because it requires the shell to be
999   // available.
1000   idle_action_warning_observer_ = std::make_unique<IdleActionWarningObserver>();
1001 
1002   // Start watching for low disk space events to notify the user if it is not a
1003   // guest profile.
1004   if (!user_manager::UserManager::Get()->IsLoggedInAsGuest())
1005     low_disk_notification_ = std::make_unique<LowDiskNotification>();
1006 
1007   gnubby_notification_ = std::make_unique<GnubbyNotification>();
1008   demo_mode_resources_remover_ = DemoModeResourcesRemover::CreateIfNeeded(
1009       g_browser_process->local_state());
1010   // Start measuring crosvm processes resource usage.
1011   crosvm_metrics_ = std::make_unique<crostini::CrosvmMetrics>();
1012   crosvm_metrics_->Start();
1013 
1014   login_screen_extensions_lifetime_manager_ =
1015       std::make_unique<LoginScreenExtensionsLifetimeManager>();
1016   login_screen_extensions_storage_cleaner_ =
1017       std::make_unique<LoginScreenExtensionsStorageCleaner>();
1018 
1019   ChromeBrowserMainPartsLinux::PostProfileInit();
1020 }
1021 
PreBrowserStart()1022 void ChromeBrowserMainPartsChromeos::PreBrowserStart() {
1023   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
1024   // -- just before MetricsService::LogNeedForCleanShutdown().
1025 
1026   // Start the external metrics service, which collects metrics from Chrome OS
1027   // and passes them to the browser process.
1028   external_metrics_ = new ExternalMetrics;
1029   external_metrics_->Start();
1030 
1031   // -- This used to be in ChromeBrowserMainParts::PreMainMessageLoopRun()
1032   // -- immediately after ChildProcess::WaitForDebugger().
1033 
1034   if (ui::ShouldDefaultToNaturalScroll()) {
1035     base::CommandLine::ForCurrentProcess()->AppendSwitch(
1036         switches::kNaturalScrollDefault);
1037     system::InputDeviceSettings::Get()->SetTapToClick(true);
1038   }
1039 
1040   ChromeBrowserMainPartsLinux::PreBrowserStart();
1041 }
1042 
PostBrowserStart()1043 void ChromeBrowserMainPartsChromeos::PostBrowserStart() {
1044   // Construct a delegate to connect the accessibility component extensions and
1045   // AccessibilityEventRewriter.
1046   accessibility_event_rewriter_delegate_ =
1047       std::make_unique<AccessibilityEventRewriterDelegate>();
1048 
1049   event_rewriter_delegate_ = std::make_unique<EventRewriterDelegateImpl>(
1050       ash::Shell::Get()->activation_client());
1051 
1052   // Set up the EventRewriterController after ash itself has finished
1053   // initialization.
1054   auto* event_rewriter_controller = ash::EventRewriterController::Get();
1055   event_rewriter_controller->Initialize(
1056       event_rewriter_delegate_.get(),
1057       accessibility_event_rewriter_delegate_.get());
1058 
1059   // Enable the KeyboardDrivenEventRewriter if the OEM manifest flag is on.
1060   if (system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation())
1061     event_rewriter_controller->SetKeyboardDrivenEventRewriterEnabled(true);
1062 
1063   // Add MagnificationManager as a pretarget handler after ash:Shell is
1064   // initialized.
1065   ash::Shell::Get()->AddPreTargetHandler(MagnificationManager::Get());
1066 
1067   // In classic ash must occur after ash::Shell is initialized. Triggers a
1068   // fetch of the initial CrosSettings DeviceRebootOnShutdown policy.
1069   shutdown_policy_forwarder_ = std::make_unique<ShutdownPolicyForwarder>();
1070 
1071   smart_charging_manager_ = power::SmartChargingManager::CreateInstance();
1072 
1073   if (base::FeatureList::IsEnabled(
1074           ::features::kAdaptiveScreenBrightnessLogging)) {
1075     adaptive_screen_brightness_manager_ =
1076         power::ml::AdaptiveScreenBrightnessManager::CreateInstance();
1077   }
1078 
1079   if (base::FeatureList::IsEnabled(::features::kUserActivityEventLogging)) {
1080     // MachineLearningDecisionServiceProvider needs to be created after
1081     // UserActivityController which depends on UserActivityDetector, not
1082     // available until PostBrowserStart.
1083     dbus_services_->CreateMachineLearningDecisionProvider();
1084   }
1085 
1086   auto_screen_brightness_controller_ =
1087       std::make_unique<power::auto_screen_brightness::Controller>();
1088 
1089   // Enable Chrome OS USB detection.
1090   cros_usb_detector_ = std::make_unique<CrosUsbDetector>();
1091   content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
1092       ->PostTask(FROM_HERE,
1093                  base::BindOnce(&CrosUsbDetector::ConnectToDeviceManager,
1094                                 base::Unretained(cros_usb_detector_.get())));
1095 
1096   crostini_unsupported_action_notifier_ =
1097       std::make_unique<crostini::CrostiniUnsupportedActionNotifier>();
1098 
1099   mojo::PendingRemote<device::mojom::WakeLockProvider> wake_lock_provider;
1100   content::GetDeviceService().BindWakeLockProvider(
1101       wake_lock_provider.InitWithNewPipeAndPassReceiver());
1102   dark_resume_controller_ = std::make_unique<system::DarkResumeController>(
1103       std::move(wake_lock_provider));
1104 
1105   ChromeBrowserMainPartsLinux::PostBrowserStart();
1106 }
1107 
1108 // Shut down services before the browser process, etc are destroyed.
1109 // NOTE: This may get called without PreProfileInit() (or other
1110 // PreMainMessageLoopRun sub-stages) getting called, so be careful with
1111 // shutdown calls and test |pre_profile_init_called_| if necessary. See
1112 // crbug.com/702403 for details.
PostMainMessageLoopRun()1113 void ChromeBrowserMainPartsChromeos::PostMainMessageLoopRun() {
1114   crostini_unsupported_action_notifier_.reset();
1115 
1116   BootTimesRecorder::Get()->AddLogoutTimeMarker("UIMessageLoopEnded", true);
1117 
1118   browser_manager_.reset();
1119 
1120   if (lock_screen_apps_state_controller_)
1121     lock_screen_apps_state_controller_->Shutdown();
1122 
1123   // This must be shut down before |arc_service_launcher_|.
1124   if (pre_profile_init_called_)
1125     NoteTakingHelper::Shutdown();
1126 
1127   arc_data_snapshotd_manager_.reset();
1128 
1129   arc_service_launcher_->Shutdown();
1130 
1131   // Assistant has to shut down before voice interaction controller client to
1132   // correctly remove the observer.
1133   assistant_client_.reset();
1134 
1135   assistant_state_client_.reset();
1136 
1137   ash::Shell::Get()->RemovePreTargetHandler(MagnificationManager::Get());
1138 
1139   // Unregister CrosSettings observers before CrosSettings is destroyed.
1140   shutdown_policy_forwarder_.reset();
1141 
1142   // Destroy the application name notifier for Kiosk mode.
1143   if (pre_profile_init_called_)
1144     KioskModeIdleAppNameNotification::Shutdown();
1145 
1146   // Tell DeviceSettingsService to stop talking to session_manager. Do not
1147   // shutdown DeviceSettingsService yet, it might still be accessed by
1148   // BrowserPolicyConnector (owned by g_browser_process).
1149   DeviceSettingsService::Get()->UnsetSessionManager();
1150 
1151   // Destroy the CrosUsb detector so it stops trying to reconnect to the
1152   // UsbDeviceManager
1153   cros_usb_detector_.reset();
1154 
1155   // We should remove observers attached to D-Bus clients before
1156   // DBusThreadManager is shut down.
1157   network_pref_state_observer_.reset();
1158   power_metrics_reporter_.reset();
1159   renderer_freezer_.reset();
1160   fast_transition_observer_.reset();
1161   network_throttling_observer_.reset();
1162   if (pre_profile_init_called_)
1163     ScreenLocker::ShutDownClass();
1164   low_disk_notification_.reset();
1165   demo_mode_resources_remover_.reset();
1166   smart_charging_manager_.reset();
1167   adaptive_screen_brightness_manager_.reset();
1168   auto_screen_brightness_controller_.reset();
1169   dark_resume_controller_.reset();
1170   lock_to_single_user_manager_.reset();
1171   wilco_dtc_supportd_manager_.reset();
1172   gnubby_notification_.reset();
1173   login_screen_extensions_lifetime_manager_.reset();
1174   login_screen_extensions_storage_cleaner_.reset();
1175 
1176   // Detach D-Bus clients before DBusThreadManager is shut down.
1177   idle_action_warning_observer_.reset();
1178 
1179   if (login_screen_extension_ui::UiHandler::Get(false /*can_create*/))
1180     login_screen_extension_ui::UiHandler::Shutdown();
1181 
1182   if (pre_profile_init_called_) {
1183     MagnificationManager::Shutdown();
1184     audio::SoundsManager::Shutdown();
1185   }
1186   system::StatisticsProvider::GetInstance()->Shutdown();
1187 
1188   DemoSession::ShutDownIfInitialized();
1189 
1190   // Inform |NetworkCertLoader| that it should not notify observers anymore.
1191   // TODO(https://crbug.com/894867): Remove this when the root cause of the
1192   // crash is found.
1193   if (NetworkCertLoader::IsInitialized())
1194     NetworkCertLoader::Get()->set_is_shutting_down();
1195 
1196   // Tear down BulkPrintersCalculators while we still have threads.
1197   bulk_printers_calculator_factory_.reset();
1198 
1199   CHECK(g_browser_process);
1200   CHECK(g_browser_process->platform_part());
1201 
1202   // Let the UserManager unregister itself as an observer of the CrosSettings
1203   // singleton before it is destroyed. This also ensures that the UserManager
1204   // has no URLRequest pending (see http://crbug.com/276659).
1205   if (g_browser_process->platform_part()->user_manager())
1206     g_browser_process->platform_part()->user_manager()->Shutdown();
1207 
1208   // Let the DeviceDisablingManager unregister itself as an observer of the
1209   // CrosSettings singleton before it is destroyed.
1210   g_browser_process->platform_part()->ShutdownDeviceDisablingManager();
1211 
1212   // Let the AutomaticRebootManager unregister itself as an observer of several
1213   // subsystems.
1214   g_browser_process->platform_part()->ShutdownAutomaticRebootManager();
1215 
1216   // Clean up dependency on CrosSettings and stop pending data fetches.
1217   KioskAppManager::Shutdown();
1218 
1219   // Make sure that there is no pending URLRequests.
1220   if (pre_profile_init_called_)
1221     UserSessionManager::GetInstance()->Shutdown();
1222 
1223   // Give BrowserPolicyConnectorChromeOS a chance to unregister any observers
1224   // on services that are going to be deleted later but before its Shutdown()
1225   // is called.
1226   g_browser_process->platform_part()
1227       ->browser_policy_connector_chromeos()
1228       ->PreShutdown();
1229 
1230   // Shutdown the virtual keyboard UI before destroying ash::Shell or the
1231   // primary profile.
1232   if (chrome_keyboard_controller_client_)
1233     chrome_keyboard_controller_client_->Shutdown();
1234 
1235   // Must occur before BrowserProcessImpl::StartTearDown() destroys the
1236   // ProfileManager.
1237   if (pre_profile_init_called_) {
1238     Profile* primary_user = ProfileManager::GetPrimaryUserProfile();
1239     if (primary_user) {
1240       // See startup_settings_cache::ReadAppLocale() comment for why we do this.
1241       startup_settings_cache::WriteAppLocale(
1242           primary_user->GetPrefs()->GetString(
1243               language::prefs::kApplicationLocale));
1244     }
1245   }
1246 
1247   // Cleans up dbus services depending on ash.
1248   dbus_services_->PreAshShutdown();
1249 
1250   // NOTE: Closes ash and destroys ash::Shell.
1251   ChromeBrowserMainPartsLinux::PostMainMessageLoopRun();
1252 
1253   // Destroy classes that may have ash observers or dependencies.
1254   arc_kiosk_app_manager_.reset();
1255   web_kiosk_app_manager_.reset();
1256   chrome_keyboard_controller_client_.reset();
1257 
1258   // All ARC related modules should have been shut down by this point, so
1259   // destroy ARC.
1260   // Specifically, this should be done after Profile destruction run in
1261   // ChromeBrowserMainPartsLinux::PostMainMessageLoopRun().
1262   arc_service_launcher_.reset();
1263   // |arc_service_launcher_| uses SchedulerConfigurationManager.
1264   g_browser_process->platform_part()->ShutdownSchedulerConfigurationManager();
1265 
1266   if (pre_profile_init_called_) {
1267     AccessibilityManager::Shutdown();
1268     input_method::Shutdown();
1269   }
1270 
1271   // Stops all in-flight OAuth2 token fetchers before the IO thread stops.
1272   DeviceOAuth2TokenServiceFactory::Shutdown();
1273 
1274   content::MediaCaptureDevices::GetInstance()->RemoveAllVideoCaptureObservers();
1275 
1276   // Shutdown after PostMainMessageLoopRun() which should destroy all observers.
1277   CrasAudioHandler::Shutdown();
1278 
1279   quirks::QuirksManager::Shutdown();
1280 
1281   // Called after ChromeBrowserMainPartsLinux::PostMainMessageLoopRun() (which
1282   // calls chrome::CloseAsh()) because some parts of WebUI depend on
1283   // NetworkPortalDetector.
1284   if (pre_profile_init_called_)
1285     network_portal_detector::Shutdown();
1286 
1287   g_browser_process->platform_part()->ShutdownSessionManager();
1288   // Ash needs to be closed before UserManager is destroyed.
1289   g_browser_process->platform_part()->DestroyChromeUserManager();
1290 }
1291 
PostDestroyThreads()1292 void ChromeBrowserMainPartsChromeos::PostDestroyThreads() {
1293   // Destroy crosvm_metrics_ after threads are stopped so that no weak_ptr is
1294   // held by any task.
1295   crosvm_metrics_.reset();
1296 
1297   network_change_manager_client_.reset();
1298   session_termination_manager_.reset();
1299 
1300   // The cert database initializer must be shut down before DBus services are
1301   // destroyed.
1302   system_token_certdb_initializer_->ShutDown();
1303 
1304   // Destroy DBus services immediately after threads are stopped.
1305   dbus_services_.reset();
1306 
1307   // This has to be destroyed after DBusServices
1308   // (ComponentUpdaterServiceProvider).
1309   g_browser_process->platform_part()->ShutdownCrosComponentManager();
1310 
1311   ShutdownDBus();
1312 
1313   // Reset SystemTokenCertDBInitializer after DBus services because it should
1314   // outlive NetworkCertLoader.
1315   system_token_certdb_initializer_.reset();
1316 
1317   ChromeBrowserMainPartsLinux::PostDestroyThreads();
1318 
1319   // Shutdown these services after g_browser_process.
1320   InstallAttributes::Shutdown();
1321   DeviceSettingsService::Shutdown();
1322 }
1323 
1324 }  //  namespace chromeos
1325