chrome_restart_request.cc revision 5f1c94371a64b3196d4be9466099bb892df9b88e
1// Copyright 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/login/chrome_restart_request.h"
6
7#include <vector>
8
9#include "ash/ash_switches.h"
10#include "base/command_line.h"
11#include "base/memory/weak_ptr.h"
12#include "base/message_loop/message_loop.h"
13#include "base/path_service.h"
14#include "base/prefs/json_pref_store.h"
15#include "base/prefs/pref_service.h"
16#include "base/process/launch.h"
17#include "base/strings/string_split.h"
18#include "base/strings/stringprintf.h"
19#include "base/sys_info.h"
20#include "base/timer/timer.h"
21#include "base/values.h"
22#include "cc/base/switches.h"
23#include "chrome/browser/browser_process.h"
24#include "chrome/browser/chromeos/boot_times_loader.h"
25#include "chrome/browser/chromeos/login/users/user_manager.h"
26#include "chrome/browser/lifetime/application_lifetime.h"
27#include "chrome/common/chrome_constants.h"
28#include "chrome/common/chrome_paths.h"
29#include "chrome/common/chrome_switches.h"
30#include "chrome/common/url_constants.h"
31#include "chromeos/chromeos_switches.h"
32#include "chromeos/dbus/dbus_thread_manager.h"
33#include "chromeos/dbus/session_manager_client.h"
34#include "chromeos/login/user_names.h"
35#include "components/policy/core/common/policy_switches.h"
36#include "content/public/browser/browser_thread.h"
37#include "content/public/common/content_switches.h"
38#include "gpu/command_buffer/service/gpu_switches.h"
39#include "media/base/media_switches.h"
40#include "third_party/cros_system_api/switches/chrome_switches.h"
41#include "ui/app_list/app_list_switches.h"
42#include "ui/base/ui_base_switches.h"
43#include "ui/compositor/compositor_switches.h"
44#include "ui/events/event_switches.h"
45#include "ui/gfx/switches.h"
46#include "ui/gl/gl_switches.h"
47#include "ui/ozone/public/ozone_switches.h"
48#include "ui/wm/core/wm_core_switches.h"
49#include "url/gurl.h"
50
51using content::BrowserThread;
52
53namespace chromeos {
54
55namespace {
56
57// Increase logging level for Guest mode to avoid INFO messages in logs.
58const char kGuestModeLoggingLevel[] = "1";
59
60// Format of command line switch.
61const char kSwitchFormatString[] = " --%s=\"%s\"";
62
63// Derives the new command line from |base_command_line| by doing the following:
64// - Forward a given switches list to new command;
65// - Set start url if given;
66// - Append/override switches using |new_switches|;
67std::string DeriveCommandLine(const GURL& start_url,
68                              const CommandLine& base_command_line,
69                              const base::DictionaryValue& new_switches,
70                              CommandLine* command_line) {
71  DCHECK_NE(&base_command_line, command_line);
72
73  static const char* kForwardSwitches[] = {
74    ::switches::kDisableAccelerated2dCanvas,
75    ::switches::kDisableAcceleratedOverflowScroll,
76    ::switches::kDisableAcceleratedVideoDecode,
77    ::switches::kDisableDelegatedRenderer,
78    ::switches::kDisableDistanceFieldText,
79    ::switches::kDisableGpu,
80    ::switches::kDisableGpuShaderDiskCache,
81    ::switches::kDisableGpuWatchdog,
82    ::switches::kDisableGpuCompositing,
83    ::switches::kDisableGpuRasterization,
84    ::switches::kDisableImplSidePainting,
85    ::switches::kDisableLowResTiling,
86    ::switches::kDisableMediaSource,
87    ::switches::kDisablePrefixedEncryptedMedia,
88    ::switches::kDisablePanelFitting,
89    ::switches::kDisableSeccompFilterSandbox,
90    ::switches::kDisableSetuidSandbox,
91    ::switches::kDisableTouchDragDrop,
92    ::switches::kDisableTouchEditing,
93    ::switches::kDisableAcceleratedFixedRootBackground,
94    ::switches::kDisableZeroCopy,
95    ::switches::kEnableAcceleratedFixedRootBackground,
96    ::switches::kEnableAcceleratedOverflowScroll,
97    ::switches::kEnableBeginFrameScheduling,
98    ::switches::kEnableCompositingForFixedPosition,
99    ::switches::kEnableDelegatedRenderer,
100    ::switches::kEnableDisplayList2dCanvas,
101    ::switches::kEnableEncryptedMedia,
102    ::switches::kDisableGpuSandbox,
103    ::switches::kDisableDeferredFilters,
104    ::switches::kEnableContainerCulling,
105    ::switches::kEnableDistanceFieldText,
106    ::switches::kEnableGpuRasterization,
107    ::switches::kEnableImplSidePainting,
108    ::switches::kEnableLogging,
109    ::switches::kEnableLowResTiling,
110    ::switches::kEnableOneCopy,
111    ::switches::kEnablePinch,
112    ::switches::kEnableTouchDragDrop,
113    ::switches::kEnableTouchEditing,
114    ::switches::kEnableViewport,
115    ::switches::kEnableViewportMeta,
116    ::switches::kEnableZeroCopy,
117    ::switches::kMainFrameResizesAreOrientationChanges,
118    ::switches::kForceDeviceScaleFactor,
119    ::switches::kForceGpuRasterization,
120    ::switches::kGpuStartupDialog,
121    ::switches::kGpuSandboxAllowSysVShm,
122    ::switches::kGpuSandboxFailuresFatal,
123    ::switches::kGpuSandboxStartEarly,
124    ::switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode,
125    ::switches::kNoSandbox,
126    ::switches::kNumRasterThreads,
127    ::switches::kPpapiFlashArgs,
128    ::switches::kPpapiFlashPath,
129    ::switches::kPpapiFlashVersion,
130    ::switches::kPpapiInProcess,
131    ::switches::kRendererStartupDialog,
132    ::switches::kEnableShareGroupAsyncTextureUpload,
133    ::switches::kTabCaptureUpscaleQuality,
134    ::switches::kTabCaptureDownscaleQuality,
135#if defined(USE_XI2_MT)
136    ::switches::kTouchCalibration,
137#endif
138    ::switches::kTouchDevices,
139    ::switches::kTouchEvents,
140    ::switches::kUIDisableThreadedCompositing,
141    ::switches::kUIPrioritizeInGpuProcess,
142#if defined(USE_CRAS)
143    ::switches::kUseCras,
144#endif
145    ::switches::kUseDiscardableMemory,
146    ::switches::kUseGL,
147    ::switches::kUserDataDir,
148    ::switches::kV,
149    ::switches::kVModule,
150    ::switches::kEnableWebGLDraftExtensions,
151    ::switches::kEnableWebGLImageChromium,
152#if defined(ENABLE_WEBRTC)
153    ::switches::kDisableAudioTrackProcessing,
154    ::switches::kDisableWebRtcHWDecoding,
155    ::switches::kDisableWebRtcHWEncoding,
156    ::switches::kEnableWebRtcHWVp8Encoding,
157#endif
158    ::switches::kEnableVaapiAcceleratedVideoEncode,
159#if defined(USE_OZONE)
160    ::switches::kOzonePlatform,
161#endif
162    app_list::switches::kDisableSyncAppList,
163    app_list::switches::kEnableSyncAppList,
164    ash::switches::kAshDefaultWallpaperLarge,
165    ash::switches::kAshDefaultWallpaperSmall,
166    ash::switches::kAshGuestWallpaperLarge,
167    ash::switches::kAshGuestWallpaperSmall,
168    ash::switches::kAshHostWindowBounds,
169    ash::switches::kAshTouchHud,
170    ash::switches::kAuraLegacyPowerButton,
171    // Please keep these in alphabetical order. Non-UI Compositor switches
172    // here should also be added to
173    // content/browser/renderer_host/render_process_host_impl.cc.
174    cc::switches::kCompositeToMailbox,
175    cc::switches::kDisableCompositedAntialiasing,
176    cc::switches::kDisableMainFrameBeforeActivation,
177    cc::switches::kDisableMainFrameBeforeDraw,
178    cc::switches::kDisablePinchVirtualViewport,
179    cc::switches::kDisableThreadedAnimation,
180    cc::switches::kEnableGpuBenchmarking,
181    cc::switches::kEnablePinchVirtualViewport,
182    cc::switches::kEnableMainFrameBeforeActivation,
183    cc::switches::kEnableTopControlsPositionCalculation,
184    cc::switches::kMaxTilesForInterestArea,
185    cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
186    cc::switches::kShowCompositedLayerBorders,
187    cc::switches::kShowFPSCounter,
188    cc::switches::kShowLayerAnimationBounds,
189    cc::switches::kShowNonOccludingRects,
190    cc::switches::kShowOccludingRects,
191    cc::switches::kShowPropertyChangedRects,
192    cc::switches::kShowReplicaScreenSpaceRects,
193    cc::switches::kShowScreenSpaceRects,
194    cc::switches::kShowSurfaceDamageRects,
195    cc::switches::kSlowDownRasterScaleFactor,
196    cc::switches::kUIDisablePartialSwap,
197    chromeos::switches::kConsumerDeviceManagementUrl,
198    chromeos::switches::kDbusStub,
199    chromeos::switches::kDisableLoginAnimations,
200    chromeos::switches::kEnableConsumerManagement,
201    chromeos::switches::kEnterpriseEnableForcedReEnrollment,
202    chromeos::switches::kHasChromeOSDiamondKey,
203    chromeos::switches::kHasChromeOSKeyboard,
204    chromeos::switches::kLoginProfile,
205    chromeos::switches::kNaturalScrollDefault,
206    chromeos::switches::kSystemInDevMode,
207    policy::switches::kDeviceManagementUrl,
208    ::switches::kEnableBrowserTextSubpixelPositioning,
209    ::switches::kEnableWebkitTextSubpixelPositioning,
210    wm::switches::kWindowAnimationsDisabled,
211  };
212  command_line->CopySwitchesFrom(base_command_line,
213                                 kForwardSwitches,
214                                 arraysize(kForwardSwitches));
215
216  if (start_url.is_valid())
217    command_line->AppendArg(start_url.spec());
218
219  for (base::DictionaryValue::Iterator it(new_switches);
220       !it.IsAtEnd();
221       it.Advance()) {
222    std::string value;
223    CHECK(it.value().GetAsString(&value));
224    command_line->AppendSwitchASCII(it.key(), value);
225  }
226
227  std::string cmd_line_str = command_line->GetCommandLineString();
228  // Special workaround for the arguments that should be quoted.
229  // Copying switches won't be needed when Guest mode won't need restart
230  // http://crosbug.com/6924
231  if (base_command_line.HasSwitch(::switches::kRegisterPepperPlugins)) {
232    cmd_line_str += base::StringPrintf(
233        kSwitchFormatString,
234        ::switches::kRegisterPepperPlugins,
235        base_command_line.GetSwitchValueNative(
236            ::switches::kRegisterPepperPlugins).c_str());
237  }
238
239  return cmd_line_str;
240}
241
242// Simulates a session manager restart by launching give command line
243// and exit current process.
244void ReLaunch(const std::string& command_line) {
245  std::vector<std::string> argv;
246
247  // This is not a proper way to get |argv| but it's good enough for debugging.
248  base::SplitString(command_line, ' ', &argv);
249
250  base::LaunchProcess(argv, base::LaunchOptions(), NULL);
251  chrome::AttemptUserExit();
252}
253
254// Empty function that run by the local state task runner to ensure last
255// commit goes through.
256void EnsureLocalStateIsWritten() {}
257
258// Wraps the work of sending chrome restart request to session manager.
259// If local state is present, try to commit it first. The request is fired when
260// the commit goes through or some time (3 seconds) has elapsed.
261class ChromeRestartRequest
262    : public base::SupportsWeakPtr<ChromeRestartRequest> {
263 public:
264  explicit ChromeRestartRequest(const std::string& command_line);
265  ~ChromeRestartRequest();
266
267  // Starts the request.
268  void Start();
269
270 private:
271  // Fires job restart request to session manager.
272  void RestartJob();
273
274  const int pid_;
275  const std::string command_line_;
276  base::OneShotTimer<ChromeRestartRequest> timer_;
277
278  DISALLOW_COPY_AND_ASSIGN(ChromeRestartRequest);
279};
280
281ChromeRestartRequest::ChromeRestartRequest(const std::string& command_line)
282    : pid_(getpid()),
283      command_line_(command_line) {}
284
285ChromeRestartRequest::~ChromeRestartRequest() {}
286
287void ChromeRestartRequest::Start() {
288  VLOG(1) << "Requesting a restart with PID " << pid_
289          << " and command line: " << command_line_;
290
291  // Session Manager may kill the chrome anytime after this point.
292  // Write exit_cleanly and other stuff to the disk here.
293  g_browser_process->EndSession();
294
295  PrefService* local_state = g_browser_process->local_state();
296  if (!local_state) {
297    RestartJob();
298    return;
299  }
300
301  // XXX: normally this call must not be needed, however RestartJob
302  // just kills us so settings may be lost. See http://crosbug.com/13102
303  local_state->CommitPendingWrite();
304  timer_.Start(
305      FROM_HERE, base::TimeDelta::FromSeconds(3), this,
306      &ChromeRestartRequest::RestartJob);
307
308  // Post a task to local state task runner thus it occurs last on the task
309  // queue, so it would be executed after committing pending write on that
310  // thread.
311  scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
312      JsonPrefStore::GetTaskRunnerForFile(
313          base::FilePath(chrome::kLocalStorePoolName),
314          BrowserThread::GetBlockingPool());
315  local_state_task_runner->PostTaskAndReply(
316      FROM_HERE,
317      base::Bind(&EnsureLocalStateIsWritten),
318      base::Bind(&ChromeRestartRequest::RestartJob, AsWeakPtr()));
319}
320
321void ChromeRestartRequest::RestartJob() {
322  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
323
324  DBusThreadManager::Get()->GetSessionManagerClient()->RestartJob(
325      pid_, command_line_);
326
327  delete this;
328}
329
330}  // namespace
331
332std::string GetOffTheRecordCommandLine(
333    const GURL& start_url,
334    bool is_oobe_completed,
335    const CommandLine& base_command_line,
336    CommandLine* command_line) {
337  base::DictionaryValue otr_switches;
338  otr_switches.SetString(switches::kGuestSession, std::string());
339  otr_switches.SetString(::switches::kIncognito, std::string());
340  otr_switches.SetString(::switches::kLoggingLevel, kGuestModeLoggingLevel);
341  otr_switches.SetString(switches::kLoginUser, chromeos::login::kGuestUserName);
342
343  // Override the home page.
344  otr_switches.SetString(::switches::kHomePage,
345                         GURL(chrome::kChromeUINewTabURL).spec());
346
347  // If OOBE is not finished yet, lock down the guest session to not allow
348  // surfing the web. Guest mode is still useful to inspect logs and run network
349  // diagnostics.
350  if (!is_oobe_completed)
351    otr_switches.SetString(switches::kOobeGuestSession, std::string());
352
353  return DeriveCommandLine(start_url,
354                           base_command_line,
355                           otr_switches,
356                           command_line);
357}
358
359void RestartChrome(const std::string& command_line) {
360  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
361  BootTimesLoader::Get()->set_restart_requested();
362
363  static bool restart_requested = false;
364  if (restart_requested) {
365    NOTREACHED() << "Request chrome restart for more than once.";
366  }
367  restart_requested = true;
368
369  if (!base::SysInfo::IsRunningOnChromeOS()) {
370    // Relaunch chrome without session manager on dev box.
371    ReLaunch(command_line);
372    return;
373  }
374
375  // ChromeRestartRequest deletes itself after request sent to session manager.
376  (new ChromeRestartRequest(command_line))->Start();
377}
378
379}  // namespace chromeos
380