36f55e59c48182259e03f9bc0a82d38e8a4017c2
[platform/framework/web/crosswalk.git] / src / remoting / host / setup / daemon_controller_delegate_win.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 "remoting/host/setup/daemon_controller_delegate_win.h"
6
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/bind_helpers.h"
10 #include "base/compiler_specific.h"
11 #include "base/json/json_reader.h"
12 #include "base/json/json_writer.h"
13 #include "base/logging.h"
14 #include "base/strings/string16.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/time/time.h"
18 #include "base/timer/timer.h"
19 #include "base/values.h"
20 #include "base/win/scoped_bstr.h"
21 #include "base/win/scoped_comptr.h"
22 #include "base/win/windows_version.h"
23 #include "remoting/base/scoped_sc_handle_win.h"
24 #include "remoting/host/branding.h"
25 // chromoting_lib.h contains MIDL-generated declarations.
26 #include "remoting/host/chromoting_lib.h"
27 #include "remoting/host/usage_stats_consent.h"
28
29 using base::win::ScopedBstr;
30 using base::win::ScopedComPtr;
31
32 namespace remoting {
33
34 namespace {
35
36 // ProgID of the daemon controller.
37 const wchar_t kDaemonController[] =
38     L"ChromotingElevatedController.ElevatedController";
39
40 // The COM elevation moniker for the Elevated Controller.
41 const wchar_t kDaemonControllerElevationMoniker[] =
42     L"Elevation:Administrator!new:"
43     L"ChromotingElevatedController.ElevatedController";
44
45 // The maximum duration of keeping a reference to a privileged instance of
46 // the Daemon Controller. This effectively reduces number of UAC prompts a user
47 // sees.
48 const int kPrivilegedTimeoutSec = 5 * 60;
49
50 // The maximum duration of keeping a reference to an unprivileged instance of
51 // the Daemon Controller. This interval should not be too long. If upgrade
52 // happens while there is a live reference to a Daemon Controller instance
53 // the old binary still can be used. So dropping the references often makes sure
54 // that the old binary will go away sooner.
55 const int kUnprivilegedTimeoutSec = 60;
56
57 void ConfigToString(const base::DictionaryValue& config, ScopedBstr* out) {
58   std::string config_str;
59   base::JSONWriter::Write(&config, &config_str);
60   ScopedBstr config_scoped_bstr(base::UTF8ToUTF16(config_str).c_str());
61   out->Swap(config_scoped_bstr);
62 }
63
64 DaemonController::State ConvertToDaemonState(DWORD service_state) {
65   switch (service_state) {
66   case SERVICE_RUNNING:
67     return DaemonController::STATE_STARTED;
68
69   case SERVICE_CONTINUE_PENDING:
70   case SERVICE_START_PENDING:
71     return DaemonController::STATE_STARTING;
72     break;
73
74   case SERVICE_PAUSE_PENDING:
75   case SERVICE_STOP_PENDING:
76     return DaemonController::STATE_STOPPING;
77     break;
78
79   case SERVICE_PAUSED:
80   case SERVICE_STOPPED:
81     return DaemonController::STATE_STOPPED;
82     break;
83
84   default:
85     NOTREACHED();
86     return DaemonController::STATE_UNKNOWN;
87   }
88 }
89
90 DWORD OpenService(ScopedScHandle* service_out) {
91   // Open the service and query its current state.
92   ScopedScHandle scmanager(
93       ::OpenSCManagerW(NULL, SERVICES_ACTIVE_DATABASE,
94                        SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE));
95   if (!scmanager.IsValid()) {
96     DWORD error = GetLastError();
97     PLOG(ERROR) << "Failed to connect to the service control manager";
98     return error;
99   }
100
101   ScopedScHandle service(::OpenServiceW(scmanager.Get(), kWindowsServiceName,
102                                         SERVICE_QUERY_STATUS));
103   if (!service.IsValid()) {
104     DWORD error = GetLastError();
105     if (error != ERROR_SERVICE_DOES_NOT_EXIST) {
106       PLOG(ERROR) << "Failed to open to the '" << kWindowsServiceName
107                   << "' service";
108     }
109     return error;
110   }
111
112   service_out->Set(service.Take());
113   return ERROR_SUCCESS;
114 }
115
116 DaemonController::AsyncResult HResultToAsyncResult(
117     HRESULT hr) {
118   if (SUCCEEDED(hr)) {
119     return DaemonController::RESULT_OK;
120   } else if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED)) {
121     return DaemonController::RESULT_CANCELLED;
122   } else {
123     // TODO(sergeyu): Report other errors to the webapp once it knows
124     // how to handle them.
125     return DaemonController::RESULT_FAILED;
126   }
127 }
128
129 void InvokeCompletionCallback(
130     const DaemonController::CompletionCallback& done, HRESULT hr) {
131   done.Run(HResultToAsyncResult(hr));
132 }
133
134 }  // namespace
135
136 DaemonControllerDelegateWin::DaemonControllerDelegateWin()
137     : control_is_elevated_(false),
138       window_handle_(NULL) {
139 }
140
141 DaemonControllerDelegateWin::~DaemonControllerDelegateWin() {
142 }
143
144 DaemonController::State DaemonControllerDelegateWin::GetState() {
145   if (base::win::GetVersion() < base::win::VERSION_XP) {
146     return DaemonController::STATE_NOT_IMPLEMENTED;
147   }
148   // TODO(alexeypa): Make the thread alertable, so we can switch to APC
149   // notifications rather than polling.
150   ScopedScHandle service;
151   DWORD error = OpenService(&service);
152
153   switch (error) {
154     case ERROR_SUCCESS: {
155       SERVICE_STATUS status;
156       if (::QueryServiceStatus(service.Get(), &status)) {
157         return ConvertToDaemonState(status.dwCurrentState);
158       } else {
159         PLOG(ERROR) << "Failed to query the state of the '"
160                     << kWindowsServiceName << "' service";
161         return DaemonController::STATE_UNKNOWN;
162       }
163       break;
164     }
165     case ERROR_SERVICE_DOES_NOT_EXIST:
166       return DaemonController::STATE_NOT_INSTALLED;
167     default:
168       return DaemonController::STATE_UNKNOWN;
169   }
170 }
171
172 scoped_ptr<base::DictionaryValue> DaemonControllerDelegateWin::GetConfig() {
173   // Configure and start the Daemon Controller if it is installed already.
174   HRESULT hr = ActivateController();
175   if (FAILED(hr))
176     return nullptr;
177
178   // Get the host configuration.
179   ScopedBstr host_config;
180   hr = control_->GetConfig(host_config.Receive());
181   if (FAILED(hr))
182     return nullptr;
183
184   // Parse the string into a dictionary.
185   base::string16 file_content(
186       static_cast<BSTR>(host_config), host_config.Length());
187   scoped_ptr<base::Value> config(
188       base::JSONReader::Read(base::UTF16ToUTF8(file_content),
189           base::JSON_ALLOW_TRAILING_COMMAS));
190
191   if (!config || !config->IsType(base::Value::TYPE_DICTIONARY))
192     return nullptr;
193
194   return make_scoped_ptr(static_cast<base::DictionaryValue*>(config.release()));
195 }
196
197 void DaemonControllerDelegateWin::InstallHost(
198     const DaemonController::CompletionCallback& done) {
199   DoInstallHost(base::Bind(&InvokeCompletionCallback, done));
200 }
201
202 void DaemonControllerDelegateWin::SetConfigAndStart(
203     scoped_ptr<base::DictionaryValue> config,
204     bool consent,
205     const DaemonController::CompletionCallback& done) {
206   DoInstallHost(
207       base::Bind(&DaemonControllerDelegateWin::StartHostWithConfig,
208                  base::Unretained(this), base::Passed(&config), consent, done));
209 }
210
211 void DaemonControllerDelegateWin::DoInstallHost(
212     const DaemonInstallerWin::CompletionCallback& done) {
213   // Configure and start the Daemon Controller if it is installed already.
214   HRESULT hr = ActivateElevatedController();
215   if (SUCCEEDED(hr)) {
216     done.Run(S_OK);
217     return;
218   }
219
220   // Otherwise, install it if its COM registration entry is missing.
221   if (hr == CO_E_CLASSSTRING) {
222     DCHECK(!installer_);
223
224     installer_ = DaemonInstallerWin::Create(
225         GetTopLevelWindow(window_handle_), done);
226     installer_->Install();
227     return;
228   }
229
230   LOG(ERROR) << "Failed to initiate the Chromoting Host installation "
231              << "(error: 0x" << std::hex << hr << std::dec << ").";
232   done.Run(hr);
233 }
234
235 void DaemonControllerDelegateWin::UpdateConfig(
236     scoped_ptr<base::DictionaryValue> config,
237     const DaemonController::CompletionCallback& done) {
238   HRESULT hr = ActivateElevatedController();
239   if (FAILED(hr)) {
240     InvokeCompletionCallback(done, hr);
241     return;
242   }
243
244   // Update the configuration.
245   ScopedBstr config_str(NULL);
246   ConfigToString(*config, &config_str);
247   if (config_str == NULL) {
248     InvokeCompletionCallback(done, E_OUTOFMEMORY);
249     return;
250   }
251
252   // Make sure that the PIN confirmation dialog is focused properly.
253   hr = control_->SetOwnerWindow(
254       reinterpret_cast<LONG_PTR>(GetTopLevelWindow(window_handle_)));
255   if (FAILED(hr)) {
256     InvokeCompletionCallback(done, hr);
257     return;
258   }
259
260   hr = control_->UpdateConfig(config_str);
261   InvokeCompletionCallback(done, hr);
262 }
263
264 void DaemonControllerDelegateWin::Stop(
265     const DaemonController::CompletionCallback& done) {
266   HRESULT hr = ActivateElevatedController();
267   if (SUCCEEDED(hr))
268     hr = control_->StopDaemon();
269
270   InvokeCompletionCallback(done, hr);
271 }
272
273 void DaemonControllerDelegateWin::SetWindow(void* window_handle) {
274   window_handle_ = reinterpret_cast<HWND>(window_handle);
275 }
276
277 std::string DaemonControllerDelegateWin::GetVersion() {
278   // Configure and start the Daemon Controller if it is installed already.
279   HRESULT hr = ActivateController();
280   if (FAILED(hr))
281     return std::string();
282
283   // Get the version string.
284   ScopedBstr version;
285   hr = control_->GetVersion(version.Receive());
286   if (FAILED(hr))
287     return std::string();
288
289   return base::UTF16ToUTF8(
290       base::string16(static_cast<BSTR>(version), version.Length()));
291 }
292
293 DaemonController::UsageStatsConsent
294 DaemonControllerDelegateWin::GetUsageStatsConsent() {
295   DaemonController::UsageStatsConsent consent;
296   consent.supported = true;
297   consent.allowed = false;
298   consent.set_by_policy = false;
299
300   // Activate the Daemon Controller and see if it supports |IDaemonControl2|.
301   HRESULT hr = ActivateController();
302   if (FAILED(hr)) {
303     // The host is not installed yet. Assume that the user didn't consent to
304     // collecting crash dumps.
305     return consent;
306   }
307
308   if (control2_.get() == NULL) {
309     // The host is installed and does not support crash dump reporting.
310     return consent;
311   }
312
313   // Get the recorded user's consent.
314   BOOL allowed;
315   BOOL set_by_policy;
316   hr = control2_->GetUsageStatsConsent(&allowed, &set_by_policy);
317   if (FAILED(hr)) {
318     // If the user's consent is not recorded yet, assume that the user didn't
319     // consent to collecting crash dumps.
320     return consent;
321   }
322
323   consent.allowed = !!allowed;
324   consent.set_by_policy = !!set_by_policy;
325   return consent;
326 }
327
328 HRESULT DaemonControllerDelegateWin::ActivateController() {
329   if (!control_) {
330     CLSID class_id;
331     HRESULT hr = CLSIDFromProgID(kDaemonController, &class_id);
332     if (FAILED(hr)) {
333       return hr;
334     }
335
336     hr = CoCreateInstance(class_id, NULL, CLSCTX_LOCAL_SERVER,
337                           IID_IDaemonControl, control_.ReceiveVoid());
338     if (FAILED(hr)) {
339       return hr;
340     }
341
342     // Ignore the error. IID_IDaemonControl2 is optional.
343     control_.QueryInterface(IID_IDaemonControl2, control2_.ReceiveVoid());
344
345     // Release |control_| upon expiration of the timeout.
346     release_timer_.reset(new base::OneShotTimer<DaemonControllerDelegateWin>());
347     release_timer_->Start(FROM_HERE,
348                           base::TimeDelta::FromSeconds(kUnprivilegedTimeoutSec),
349                           this,
350                           &DaemonControllerDelegateWin::ReleaseController);
351   }
352
353   return S_OK;
354 }
355
356 HRESULT DaemonControllerDelegateWin::ActivateElevatedController() {
357   // The COM elevation is supported on Vista and above.
358   if (base::win::GetVersion() < base::win::VERSION_VISTA)
359     return ActivateController();
360
361   // Release an unprivileged instance of the daemon controller if any.
362   if (!control_is_elevated_)
363     ReleaseController();
364
365   if (!control_) {
366     BIND_OPTS3 bind_options;
367     memset(&bind_options, 0, sizeof(bind_options));
368     bind_options.cbStruct = sizeof(bind_options);
369     bind_options.hwnd = GetTopLevelWindow(window_handle_);
370     bind_options.dwClassContext  = CLSCTX_LOCAL_SERVER;
371
372     HRESULT hr = ::CoGetObject(
373         kDaemonControllerElevationMoniker,
374         &bind_options,
375         IID_IDaemonControl,
376         control_.ReceiveVoid());
377     if (FAILED(hr)) {
378       return hr;
379     }
380
381     // Ignore the error. IID_IDaemonControl2 is optional.
382     control_.QueryInterface(IID_IDaemonControl2, control2_.ReceiveVoid());
383
384     // Note that we hold a reference to an elevated instance now.
385     control_is_elevated_ = true;
386
387     // Release |control_| upon expiration of the timeout.
388     release_timer_.reset(new base::OneShotTimer<DaemonControllerDelegateWin>());
389     release_timer_->Start(FROM_HERE,
390                           base::TimeDelta::FromSeconds(kPrivilegedTimeoutSec),
391                           this,
392                           &DaemonControllerDelegateWin::ReleaseController);
393   }
394
395   return S_OK;
396 }
397
398 void DaemonControllerDelegateWin::ReleaseController() {
399   control_.Release();
400   control2_.Release();
401   release_timer_.reset();
402   control_is_elevated_ = false;
403 }
404
405 void DaemonControllerDelegateWin::StartHostWithConfig(
406     scoped_ptr<base::DictionaryValue> config,
407     bool consent,
408     const DaemonController::CompletionCallback& done,
409     HRESULT hr) {
410   installer_.reset();
411
412   if (FAILED(hr)) {
413     LOG(ERROR) << "Failed to install the Chromoting Host "
414                << "(error: 0x" << std::hex << hr << std::dec << ").";
415     InvokeCompletionCallback(done, hr);
416     return;
417   }
418
419   hr = ActivateElevatedController();
420   if (FAILED(hr)) {
421     InvokeCompletionCallback(done, hr);
422     return;
423   }
424
425   // Record the user's consent.
426   if (control2_) {
427     hr = control2_->SetUsageStatsConsent(consent);
428     if (FAILED(hr)) {
429       InvokeCompletionCallback(done, hr);
430       return;
431     }
432   }
433
434   // Set the configuration.
435   ScopedBstr config_str(NULL);
436   ConfigToString(*config, &config_str);
437   if (config_str == NULL) {
438     InvokeCompletionCallback(done, E_OUTOFMEMORY);
439     return;
440   }
441
442   hr = control_->SetOwnerWindow(
443       reinterpret_cast<LONG_PTR>(GetTopLevelWindow(window_handle_)));
444   if (FAILED(hr)) {
445     InvokeCompletionCallback(done, hr);
446     return;
447   }
448
449   hr = control_->SetConfig(config_str);
450   if (FAILED(hr)) {
451     InvokeCompletionCallback(done, hr);
452     return;
453   }
454
455   // Start daemon.
456   hr = control_->StartDaemon();
457   InvokeCompletionCallback(done, hr);
458 }
459
460 scoped_refptr<DaemonController> DaemonController::Create() {
461   scoped_ptr<DaemonController::Delegate> delegate(
462       new DaemonControllerDelegateWin());
463   return new DaemonController(delegate.Pass());
464 }
465
466 }  // namespace remoting