chrome_restart_request.cc revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
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 "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/events/event_switches.h"
40#include "ui/gfx/switches.h"
41#include "ui/gl/gl_switches.h"
42#include "ui/views/corewm/corewm_switches.h"
43#include "url/gurl.h"
44
45using content::BrowserThread;
46
47namespace chromeos {
48
49namespace {
50
51// Increase logging level for Guest mode to avoid LOG(INFO) messages in logs.
52const char kGuestModeLoggingLevel[] = "1";
53
54// Format of command line switch.
55const char kSwitchFormatString[] = " --%s=\"%s\"";
56
57// User name which is used in the Guest session.
58const char kGuestUserName[] = "";
59
60// Derives the new command line from |base_command_line| by doing the following:
61// - Forward a given switches list to new command;
62// - Set start url if given;
63// - Append/override switches using |new_switches|;
64std::string DeriveCommandLine(const GURL& start_url,
65                              const CommandLine& base_command_line,
66                              const base::DictionaryValue& new_switches,
67                              CommandLine* command_line) {
68  DCHECK_NE(&base_command_line, command_line);
69
70  static const char* kForwardSwitches[] = {
71      ::switches::kAllowFiltersOverIPC,
72      ::switches::kAllowWebUICompositing,
73      ::switches::kDeviceManagementUrl,
74      ::switches::kDisableAccelerated2dCanvas,
75      ::switches::kDisableAcceleratedOverflowScroll,
76      ::switches::kDisableAcceleratedPlugins,
77      ::switches::kDisableAcceleratedVideoDecode,
78      ::switches::kDisableBrowserPluginCompositing,
79      ::switches::kDisableDeadlineScheduling,
80      ::switches::kDisableDelegatedRenderer,
81      ::switches::kDisableForceCompositingMode,
82      ::switches::kDisableGpuShaderDiskCache,
83      ::switches::kDisableGpuWatchdog,
84      ::switches::kDisableGpuCompositing,
85      ::switches::kDisablePrefixedEncryptedMedia,
86      ::switches::kDisablePanelFitting,
87      ::switches::kDisableSeccompFilterSandbox,
88      ::switches::kDisableSetuidSandbox,
89      ::switches::kDisableThreadedCompositing,
90      ::switches::kDisableTouchDragDrop,
91      ::switches::kDisableTouchEditing,
92      ::switches::kDisableWebKitMediaSource,
93      ::switches::kDisableAcceleratedFixedRootBackground,
94      ::switches::kEnableAcceleratedFixedRootBackground,
95      ::switches::kEnableAcceleratedOverflowScroll,
96      ::switches::kEnableBeginFrameScheduling,
97      ::switches::kEnableCompositingForFixedPosition,
98      ::switches::kEnableDeadlineScheduling,
99      ::switches::kEnableDelegatedRenderer,
100      ::switches::kEnableEncryptedMedia,
101      ::switches::kEnableGestureTapHighlight,
102      ::switches::kDisableGestureTapHighlight,
103      ::switches::kDisableGpuSandbox,
104      ::switches::kEnableLogging,
105      ::switches::kEnablePinch,
106      ::switches::kEnableThreadedCompositing,
107      ::switches::kEnableTouchDragDrop,
108      ::switches::kEnableTouchEditing,
109      ::switches::kEnableViewport,
110      ::switches::kForceDeviceScaleFactor,
111      ::switches::kGpuStartupDialog,
112      ::switches::kGpuSandboxAllowSysVShm,
113      ::switches::kMultiProfiles,
114      ::switches::kNoSandbox,
115      ::switches::kPpapiFlashArgs,
116      ::switches::kPpapiFlashInProcess,
117      ::switches::kPpapiFlashPath,
118      ::switches::kPpapiFlashVersion,
119      ::switches::kPpapiInProcess,
120      ::switches::kRendererStartupDialog,
121      ::switches::kEnableShareGroupAsyncTextureUpload,
122      ::switches::kTabCaptureUpscaleQuality,
123      ::switches::kTabCaptureDownscaleQuality,
124#if defined(USE_XI2_MT)
125      ::switches::kTouchCalibration,
126#endif
127      ::switches::kTouchDevices,
128      ::switches::kTouchEvents,
129      ::switches::kTouchOptimizedUI,
130      ::switches::kUIDisableDeadlineScheduling,
131      ::switches::kUIDisableThreadedCompositing,
132      ::switches::kUIEnableDeadlineScheduling,
133      ::switches::kUIMaxFramesPending,
134      ::switches::kUIPrioritizeInGpuProcess,
135#if defined(USE_CRAS)
136      ::switches::kUseCras,
137#endif
138      ::switches::kUseGL,
139      ::switches::kUserDataDir,
140      ::switches::kV,
141      ::switches::kVModule,
142      ::switches::kEnableWebGLDraftExtensions,
143#if defined(ENABLE_WEBRTC)
144      ::switches::kDisableWebRtcHWDecoding,
145      ::switches::kDisableWebRtcHWEncoding,
146      ::switches::kEnableWebRtcHWVp8Encoding,
147#endif
148      ash::switches::kAshDefaultWallpaperLarge,
149      ash::switches::kAshDefaultWallpaperSmall,
150#if defined(OS_CHROMEOS)
151      ash::switches::kAshDisableAudioDeviceMenu,
152#endif
153      ash::switches::kAshGuestWallpaperLarge,
154      ash::switches::kAshGuestWallpaperSmall,
155      ash::switches::kAshHostWindowBounds,
156      ash::switches::kAshTouchHud,
157      ash::switches::kAuraLegacyPowerButton,
158      // Please keep these in alphabetical order. Non-UI Compositor switches
159      // here should also be added to
160      // content/browser/renderer_host/render_process_host_impl.cc.
161      cc::switches::kBackgroundColorInsteadOfCheckerboard,
162      cc::switches::kCompositeToMailbox,
163      cc::switches::kDisableCompositedAntialiasing,
164      cc::switches::kDisableCompositorTouchHitTesting,
165      cc::switches::kDisableImplSidePainting,
166      cc::switches::kDisableMapImage,
167      cc::switches::kDisableThreadedAnimation,
168      cc::switches::kEnableImplSidePainting,
169      cc::switches::kEnableMapImage,
170      cc::switches::kEnablePartialSwap,
171      cc::switches::kEnablePerTilePainting,
172      cc::switches::kEnablePinchVirtualViewport,
173      cc::switches::kEnableTopControlsPositionCalculation,
174      cc::switches::kForceDirectLayerDrawing,
175      cc::switches::kLowResolutionContentsScaleFactor,
176      cc::switches::kMaxTilesForInterestArea,
177      cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
178      cc::switches::kNumRasterThreads,
179      cc::switches::kShowCompositedLayerBorders,
180      cc::switches::kShowFPSCounter,
181      cc::switches::kShowNonOccludingRects,
182      cc::switches::kShowOccludingRects,
183      cc::switches::kShowPropertyChangedRects,
184      cc::switches::kShowReplicaScreenSpaceRects,
185      cc::switches::kShowScreenSpaceRects,
186      cc::switches::kShowSurfaceDamageRects,
187      cc::switches::kSlowDownRasterScaleFactor,
188      cc::switches::kTraceOverdraw,
189      cc::switches::kUIDisablePartialSwap,
190      cc::switches::kUIEnablePerTilePainting,
191      chromeos::switches::kDbusStub,
192      chromeos::switches::kDisableLoginAnimations,
193      chromeos::switches::kDisableOobeAnimation,
194      chromeos::switches::kHasChromeOSDiamondKey,
195      chromeos::switches::kHasChromeOSKeyboard,
196      chromeos::switches::kLoginProfile,
197      chromeos::switches::kNaturalScrollDefault,
198      ::switches::kEnableBrowserTextSubpixelPositioning,
199      ::switches::kEnableWebkitTextSubpixelPositioning,
200      views::corewm::switches::kNoDropShadows,
201      views::corewm::switches::kWindowAnimationsDisabled,
202  };
203  command_line->CopySwitchesFrom(base_command_line,
204                                 kForwardSwitches,
205                                 arraysize(kForwardSwitches));
206
207  if (start_url.is_valid())
208    command_line->AppendArg(start_url.spec());
209
210  for (base::DictionaryValue::Iterator it(new_switches);
211       !it.IsAtEnd();
212       it.Advance()) {
213    std::string value;
214    CHECK(it.value().GetAsString(&value));
215    command_line->AppendSwitchASCII(it.key(), value);
216  }
217
218  std::string cmd_line_str = command_line->GetCommandLineString();
219  // Special workaround for the arguments that should be quoted.
220  // Copying switches won't be needed when Guest mode won't need restart
221  // http://crosbug.com/6924
222  if (base_command_line.HasSwitch(::switches::kRegisterPepperPlugins)) {
223    cmd_line_str += base::StringPrintf(
224        kSwitchFormatString,
225        ::switches::kRegisterPepperPlugins,
226        base_command_line.GetSwitchValueNative(
227            ::switches::kRegisterPepperPlugins).c_str());
228  }
229
230  // TODO(zelidrag): Remove this hack that get us around compositing bug from
231  // http://crbug.com/179256 once that bug is resolved.
232  if (command_line->HasSwitch(::switches::kForceAppMode)) {
233    std::string switch_to_remove("--");
234    switch_to_remove.append(cc::switches::kEnablePartialSwap);
235    cmd_line_str = cmd_line_str.replace(cmd_line_str.find(switch_to_remove),
236                                        switch_to_remove.length(), "");
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    const CommandLine& base_command_line,
335    CommandLine* command_line) {
336  base::DictionaryValue otr_switches;
337  otr_switches.SetString(switches::kGuestSession, std::string());
338  otr_switches.SetString(::switches::kIncognito, std::string());
339  otr_switches.SetString(::switches::kLoggingLevel, kGuestModeLoggingLevel);
340  otr_switches.SetString(switches::kLoginUser, UserManager::kGuestUserName);
341
342  // Override the home page.
343  otr_switches.SetString(::switches::kHomePage,
344                         GURL(chrome::kChromeUINewTabURL).spec());
345
346  return DeriveCommandLine(start_url,
347                           base_command_line,
348                           otr_switches,
349                           command_line);
350}
351
352void RestartChrome(const std::string& command_line) {
353  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
354
355  static bool restart_requested = false;
356  if (restart_requested) {
357    NOTREACHED() << "Request chrome restart for more than once.";
358  }
359  restart_requested = true;
360
361  if (!base::SysInfo::IsRunningOnChromeOS()) {
362    // Relaunch chrome without session manager on dev box.
363    ReLaunch(command_line);
364    return;
365  }
366
367  // ChromeRestartRequest deletes itself after request sent to session manager.
368  (new ChromeRestartRequest(command_line))->Start();
369}
370
371}  // namespace chromeos
372