c34e699002309e4ec9c30f86e148de261fbebc43
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / login / chrome_restart_request.cc
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 "ui/base/ui_base_switches.h"
39 #include "ui/compositor/compositor_switches.h"
40 #include "ui/events/event_switches.h"
41 #include "ui/gfx/switches.h"
42 #include "ui/gl/gl_switches.h"
43 #include "ui/ozone/ozone_switches.h"
44 #include "ui/wm/core/wm_core_switches.h"
45 #include "url/gurl.h"
46
47 using content::BrowserThread;
48
49 namespace chromeos {
50
51 namespace {
52
53 // Increase logging level for Guest mode to avoid INFO messages in logs.
54 const char kGuestModeLoggingLevel[] = "1";
55
56 // Format of command line switch.
57 const char kSwitchFormatString[] = " --%s=\"%s\"";
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|;
63 std::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::kDisableAccelerated2dCanvas,
71     ::switches::kDisableAcceleratedOverflowScroll,
72     ::switches::kDisableAcceleratedVideoDecode,
73     ::switches::kDisableBrowserPluginCompositing,
74     ::switches::kDisableDelegatedRenderer,
75     ::switches::kDisableFastTextAutosizing,
76     ::switches::kDisableFiltersOverIPC,
77     ::switches::kDisableForceCompositingMode,
78     ::switches::kDisableGpuShaderDiskCache,
79     ::switches::kDisableGpuWatchdog,
80     ::switches::kDisableGpuCompositing,
81     ::switches::kDisableGpuRasterization,
82     ::switches::kDisableImplSidePainting,
83     ::switches::kDisableLowResTiling,
84     ::switches::kDisableMapImage,
85     ::switches::kDisablePrefixedEncryptedMedia,
86     ::switches::kDisablePanelFitting,
87     ::switches::kDisableRepaintAfterLayout,
88     ::switches::kDisableSeccompFilterSandbox,
89     ::switches::kDisableSetuidSandbox,
90     ::switches::kDisableThreadedCompositing,
91     ::switches::kDisableTouchDragDrop,
92     ::switches::kDisableTouchEditing,
93     ::switches::kDisableUniversalAcceleratedOverflowScroll,
94     ::switches::kDisableUnprefixedMediaSource,
95     ::switches::kDisableWebKitMediaSource,
96     ::switches::kDisableAcceleratedFixedRootBackground,
97     ::switches::kEnableAcceleratedFixedRootBackground,
98     ::switches::kEnableAcceleratedOverflowScroll,
99     ::switches::kEnableBeginFrameScheduling,
100     ::switches::kEnableCompositingForFixedPosition,
101     ::switches::kEnableDelegatedRenderer,
102     ::switches::kEnableEncryptedMedia,
103     ::switches::kEnableFastTextAutosizing,
104     ::switches::kEnableGestureTapHighlight,
105     ::switches::kDisableGestureTapHighlight,
106     ::switches::kDisableGpuSandbox,
107     ::switches::kEnableDeferredFilters,
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     ash::switches::kAshDefaultWallpaperLarge,
167     ash::switches::kAshDefaultWallpaperSmall,
168     ash::switches::kAshGuestWallpaperLarge,
169     ash::switches::kAshGuestWallpaperSmall,
170     ash::switches::kAshHostWindowBounds,
171     ash::switches::kAshTouchHud,
172     ash::switches::kAuraLegacyPowerButton,
173     // Please keep these in alphabetical order. Non-UI Compositor switches
174     // here should also be added to
175     // content/browser/renderer_host/render_process_host_impl.cc.
176     cc::switches::kCompositeToMailbox,
177     cc::switches::kDisableCompositedAntialiasing,
178     cc::switches::kDisableCompositorTouchHitTesting,
179     cc::switches::kDisableMainFrameBeforeActivation,
180     cc::switches::kDisableMainFrameBeforeDraw,
181     cc::switches::kDisableThreadedAnimation,
182     cc::switches::kEnableGpuBenchmarking,
183     cc::switches::kEnablePinchVirtualViewport,
184     cc::switches::kEnableMainFrameBeforeActivation,
185     cc::switches::kEnableTopControlsPositionCalculation,
186     cc::switches::kMaxTilesForInterestArea,
187     cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
188     cc::switches::kShowCompositedLayerBorders,
189     cc::switches::kShowFPSCounter,
190     cc::switches::kShowLayerAnimationBounds,
191     cc::switches::kShowNonOccludingRects,
192     cc::switches::kShowOccludingRects,
193     cc::switches::kShowPropertyChangedRects,
194     cc::switches::kShowReplicaScreenSpaceRects,
195     cc::switches::kShowScreenSpaceRects,
196     cc::switches::kShowSurfaceDamageRects,
197     cc::switches::kSlowDownRasterScaleFactor,
198     cc::switches::kUIDisablePartialSwap,
199     chromeos::switches::kDbusStub,
200     chromeos::switches::kDisableLoginAnimations,
201     chromeos::switches::kHasChromeOSDiamondKey,
202     chromeos::switches::kHasChromeOSKeyboard,
203     chromeos::switches::kLoginProfile,
204     chromeos::switches::kNaturalScrollDefault,
205     ::switches::kEnableBrowserTextSubpixelPositioning,
206     ::switches::kEnableWebkitTextSubpixelPositioning,
207     policy::switches::kDeviceManagementUrl,
208     wm::switches::kWindowAnimationsDisabled,
209   };
210   command_line->CopySwitchesFrom(base_command_line,
211                                  kForwardSwitches,
212                                  arraysize(kForwardSwitches));
213
214   if (start_url.is_valid())
215     command_line->AppendArg(start_url.spec());
216
217   for (base::DictionaryValue::Iterator it(new_switches);
218        !it.IsAtEnd();
219        it.Advance()) {
220     std::string value;
221     CHECK(it.value().GetAsString(&value));
222     command_line->AppendSwitchASCII(it.key(), value);
223   }
224
225   std::string cmd_line_str = command_line->GetCommandLineString();
226   // Special workaround for the arguments that should be quoted.
227   // Copying switches won't be needed when Guest mode won't need restart
228   // http://crosbug.com/6924
229   if (base_command_line.HasSwitch(::switches::kRegisterPepperPlugins)) {
230     cmd_line_str += base::StringPrintf(
231         kSwitchFormatString,
232         ::switches::kRegisterPepperPlugins,
233         base_command_line.GetSwitchValueNative(
234             ::switches::kRegisterPepperPlugins).c_str());
235   }
236
237   return cmd_line_str;
238 }
239
240 // Simulates a session manager restart by launching give command line
241 // and exit current process.
242 void ReLaunch(const std::string& command_line) {
243   std::vector<std::string> argv;
244
245   // This is not a proper way to get |argv| but it's good enough for debugging.
246   base::SplitString(command_line, ' ', &argv);
247
248   base::LaunchProcess(argv, base::LaunchOptions(), NULL);
249   chrome::AttemptUserExit();
250 }
251
252 // Empty function that run by the local state task runner to ensure last
253 // commit goes through.
254 void EnsureLocalStateIsWritten() {}
255
256 // Wraps the work of sending chrome restart request to session manager.
257 // If local state is present, try to commit it first. The request is fired when
258 // the commit goes through or some time (3 seconds) has elapsed.
259 class ChromeRestartRequest
260     : public base::SupportsWeakPtr<ChromeRestartRequest> {
261  public:
262   explicit ChromeRestartRequest(const std::string& command_line);
263   ~ChromeRestartRequest();
264
265   // Starts the request.
266   void Start();
267
268  private:
269   // Fires job restart request to session manager.
270   void RestartJob();
271
272   const int pid_;
273   const std::string command_line_;
274   base::OneShotTimer<ChromeRestartRequest> timer_;
275
276   DISALLOW_COPY_AND_ASSIGN(ChromeRestartRequest);
277 };
278
279 ChromeRestartRequest::ChromeRestartRequest(const std::string& command_line)
280     : pid_(getpid()),
281       command_line_(command_line) {}
282
283 ChromeRestartRequest::~ChromeRestartRequest() {}
284
285 void ChromeRestartRequest::Start() {
286   VLOG(1) << "Requesting a restart with PID " << pid_
287           << " and command line: " << command_line_;
288
289   // Session Manager may kill the chrome anytime after this point.
290   // Write exit_cleanly and other stuff to the disk here.
291   g_browser_process->EndSession();
292
293   PrefService* local_state = g_browser_process->local_state();
294   if (!local_state) {
295     RestartJob();
296     return;
297   }
298
299   // XXX: normally this call must not be needed, however RestartJob
300   // just kills us so settings may be lost. See http://crosbug.com/13102
301   local_state->CommitPendingWrite();
302   timer_.Start(
303       FROM_HERE, base::TimeDelta::FromSeconds(3), this,
304       &ChromeRestartRequest::RestartJob);
305
306   // Post a task to local state task runner thus it occurs last on the task
307   // queue, so it would be executed after committing pending write on that
308   // thread.
309   scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
310       JsonPrefStore::GetTaskRunnerForFile(
311           base::FilePath(chrome::kLocalStorePoolName),
312           BrowserThread::GetBlockingPool());
313   local_state_task_runner->PostTaskAndReply(
314       FROM_HERE,
315       base::Bind(&EnsureLocalStateIsWritten),
316       base::Bind(&ChromeRestartRequest::RestartJob, AsWeakPtr()));
317 }
318
319 void ChromeRestartRequest::RestartJob() {
320   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
321
322   DBusThreadManager::Get()->GetSessionManagerClient()->RestartJob(
323       pid_, command_line_);
324
325   delete this;
326 }
327
328 }  // namespace
329
330 std::string GetOffTheRecordCommandLine(
331     const GURL& start_url,
332     bool is_oobe_completed,
333     const CommandLine& base_command_line,
334     CommandLine* command_line) {
335   base::DictionaryValue otr_switches;
336   otr_switches.SetString(switches::kGuestSession, std::string());
337   otr_switches.SetString(::switches::kIncognito, std::string());
338   otr_switches.SetString(::switches::kLoggingLevel, kGuestModeLoggingLevel);
339   otr_switches.SetString(switches::kLoginUser, UserManager::kGuestUserName);
340
341   // Override the home page.
342   otr_switches.SetString(::switches::kHomePage,
343                          GURL(chrome::kChromeUINewTabURL).spec());
344
345   // If OOBE is not finished yet, lock down the guest session to not allow
346   // surfing the web. Guest mode is still useful to inspect logs and run network
347   // diagnostics.
348   if (!is_oobe_completed)
349     otr_switches.SetString(switches::kOobeGuestSession, std::string());
350
351   return DeriveCommandLine(start_url,
352                            base_command_line,
353                            otr_switches,
354                            command_line);
355 }
356
357 void RestartChrome(const std::string& command_line) {
358   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
359
360   static bool restart_requested = false;
361   if (restart_requested) {
362     NOTREACHED() << "Request chrome restart for more than once.";
363   }
364   restart_requested = true;
365
366   if (!base::SysInfo::IsRunningOnChromeOS()) {
367     // Relaunch chrome without session manager on dev box.
368     ReLaunch(command_line);
369     return;
370   }
371
372   // ChromeRestartRequest deletes itself after request sent to session manager.
373   (new ChromeRestartRequest(command_line))->Start();
374 }
375
376 }  // namespace chromeos