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