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