cc: Added inline to Tile::IsReadyToDraw
[chromium-blink-merge.git] / cloud_print / service / win / cloud_print_service.cc
blob058cf5445db6f4a87651a7d67cff23eec322a8d7
1 // Copyright (c) 2012 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.
5 #include <atlbase.h>
6 #include <security.h>
8 #include <iomanip>
9 #include <iostream>
11 #include "base/at_exit.h"
12 #include "base/bind.h"
13 #include "base/callback_helpers.h"
14 #include "base/command_line.h"
15 #include "base/file_util.h"
16 #include "base/guid.h"
17 #include "base/logging.h"
18 #include "base/path_service.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/win/scoped_handle.h"
22 #include "chrome/common/chrome_constants.h"
23 #include "chrome/common/chrome_switches.h"
24 #include "cloud_print/common/win/cloud_print_utils.h"
25 #include "cloud_print/service/service_constants.h"
26 #include "cloud_print/service/service_state.h"
27 #include "cloud_print/service/service_switches.h"
28 #include "cloud_print/service/win/chrome_launcher.h"
29 #include "cloud_print/service/win/service_controller.h"
30 #include "cloud_print/service/win/service_listener.h"
31 #include "cloud_print/service/win/service_utils.h"
32 #include "cloud_print/service/win/setup_listener.h"
34 namespace {
36 void InvalidUsage() {
37 base::FilePath service_path;
38 CHECK(PathService::Get(base::FILE_EXE, &service_path));
40 std::cout << cloud_print::LoadLocalString(IDS_COMMAND_LINE_HELP_TITLE);
41 std::cout << " " << service_path.BaseName().value();
42 std::cout << " [";
43 std::cout << "[";
44 std::cout << "[";
45 std::cout << " -" << kInstallSwitch;
46 std::cout << " [ -" << switches::kUserDataDir << "=DIRECTORY ]";
47 std::cout << "]";
48 std::cout << "]";
49 std::cout << " | -" << kUninstallSwitch;
50 std::cout << " | -" << kStartSwitch;
51 std::cout << " | -" << kStopSwitch;
52 std::cout << " ]\n";
53 std::cout << cloud_print::LoadLocalString(IDS_COMMAND_LINE_DESCRIPTION);
54 std::cout << "\n\n";
56 struct {
57 const char* name;
58 int description;
59 } kSwitchHelp[] = {{
60 kInstallSwitch, IDS_SWITCH_HELP_INSTALL
61 }, {
62 switches::kUserDataDir, IDS_SWITCH_HELP_DATA_DIR
63 }, {
64 kUninstallSwitch, IDS_SWITCH_HELP_UNINSTALL
65 }, {
66 kStartSwitch, IDS_SWITCH_HELP_START
67 }, {
68 kStopSwitch, IDS_SWITCH_HELP_STOP
69 }};
71 for (size_t i = 0; i < arraysize(kSwitchHelp); ++i) {
72 std::cout << std::setiosflags(std::ios::left);
73 std::cout << " -" << std::setw(16) << kSwitchHelp[i].name;
74 std::cout << cloud_print::LoadLocalString(kSwitchHelp[i].description);
75 std::cout << "\n";
77 std::cout << "\n";
80 string16 GetOption(int string_id, const string16& default,
81 bool secure) {
82 string16 prompt_format = cloud_print::LoadLocalString(string_id) ;
83 std::vector<string16> substitutions(1, default);
84 std::cout << ReplaceStringPlaceholders(prompt_format, substitutions, NULL);
85 string16 tmp;
86 if (secure) {
87 DWORD saved_mode = 0;
88 // Don't close.
89 HANDLE stdin_handle = ::GetStdHandle(STD_INPUT_HANDLE);
90 ::GetConsoleMode(stdin_handle, &saved_mode);
91 ::SetConsoleMode(stdin_handle, saved_mode & ~ENABLE_ECHO_INPUT);
92 std::getline(std::wcin, tmp);
93 ::SetConsoleMode(stdin_handle, saved_mode);
94 std::cout << "\n";
95 } else {
96 std::getline(std::wcin, tmp);
98 if (tmp.empty())
99 return default;
100 return tmp;
103 HRESULT ReportError(HRESULT hr, int string_id) {
104 LOG(ERROR) << cloud_print::GetErrorMessage(hr);
105 std::cerr << cloud_print::LoadLocalString(string_id);
106 std::cerr << "\n";
107 return hr;
110 string16 StateAsString(ServiceController::State state) {
111 DWORD string_id = 0;
112 switch(state) {
113 case ServiceController::STATE_NOT_FOUND:
114 string_id = IDS_SERVICE_NOT_FOUND;
115 break;
116 case ServiceController::STATE_STOPPED:
117 string_id = IDS_SERVICE_STOPPED;
118 break;
119 case ServiceController::STATE_RUNNING:
120 string_id = IDS_SERVICE_RUNNING;
121 break;
123 return string_id ? cloud_print::LoadLocalString(string_id) : string16();
126 } // namespace
129 class CloudPrintServiceModule
130 : public ATL::CAtlServiceModuleT<CloudPrintServiceModule,
131 IDS_SERVICE_NAME> {
132 public:
133 typedef ATL::CAtlServiceModuleT<CloudPrintServiceModule,
134 IDS_SERVICE_NAME> Base;
136 CloudPrintServiceModule()
137 : check_requirements_(false),
138 controller_(new ServiceController()) {
141 static wchar_t* GetAppIdT() {
142 return ServiceController::GetAppIdT();
145 HRESULT InitializeSecurity() {
146 // TODO(gene): Check if we need to call CoInitializeSecurity and provide
147 // the appropriate security settings for service.
148 return S_OK;
151 bool ParseCommandLine(LPCTSTR lpCmdLine, HRESULT* pnRetCode) {
152 CHECK(pnRetCode);
153 CommandLine command_line(CommandLine::NO_PROGRAM);
154 command_line.ParseFromString(lpCmdLine);
156 LOG(INFO) << command_line.GetCommandLineString();
158 bool is_service = false;
159 *pnRetCode = ParseCommandLine(command_line, &is_service);
160 if (FAILED(*pnRetCode)) {
161 ReportError(*pnRetCode, IDS_OPERATION_FAILED_TITLE);
163 if (!is_service) {
164 controller_->UpdateState();
165 std::cout << cloud_print::LoadLocalString(IDS_STATE_LABEL);
166 std::cout << " " << StateAsString(controller_->state());
168 return is_service;
171 HRESULT PreMessageLoop(int nShowCmd) {
172 HRESULT hr = Base::PreMessageLoop(nShowCmd);
173 if (FAILED(hr))
174 return hr;
176 if (check_requirements_) {
177 CheckRequirements();
178 } else {
179 HRESULT hr = StartConnector();
180 if (FAILED(hr))
181 return hr;
184 LogEvent(_T("Service started/resumed"));
185 SetServiceStatus(SERVICE_RUNNING);
187 return hr;
190 HRESULT PostMessageLoop() {
191 StopConnector();
192 setup_listener_.reset();
193 return Base::PostMessageLoop();
196 private:
197 HRESULT ParseCommandLine(const CommandLine& command_line, bool* is_service) {
198 if (!is_service)
199 return E_INVALIDARG;
200 *is_service = false;
202 user_data_dir_switch_ =
203 command_line.GetSwitchValuePath(switches::kUserDataDir);
204 if (!user_data_dir_switch_.empty())
205 user_data_dir_switch_ = base::MakeAbsoluteFilePath(user_data_dir_switch_);
207 if (command_line.HasSwitch(kStopSwitch))
208 return controller_->StopService();
210 if (command_line.HasSwitch(kUninstallSwitch))
211 return controller_->UninstallService();
213 if (command_line.HasSwitch(kInstallSwitch)) {
214 string16 run_as_user;
215 string16 run_as_password;
216 base::FilePath user_data_dir;
217 std::vector<std::string> printers;
218 HRESULT hr = SelectWindowsAccount(&run_as_user, &run_as_password,
219 &user_data_dir, &printers);
220 if (FAILED(hr))
221 return hr;
223 DCHECK(user_data_dir_switch_.empty() ||
224 user_data_dir_switch_ == user_data_dir);
226 hr = SetupServiceState(user_data_dir, printers);
227 if (FAILED(hr))
228 return hr;
230 hr = controller_->InstallConnectorService(
231 run_as_user, run_as_password, user_data_dir_switch_,
232 command_line.HasSwitch(switches::kEnableLogging));
233 if (SUCCEEDED(hr) && command_line.HasSwitch(kStartSwitch))
234 return controller_->StartService();
236 return hr;
239 if (command_line.HasSwitch(kStartSwitch))
240 return controller_->StartService();
242 if (command_line.HasSwitch(kConsoleSwitch)) {
243 check_requirements_ = command_line.HasSwitch(kRequirementsSwitch);
244 ::SetConsoleCtrlHandler(&ConsoleCtrlHandler, TRUE);
245 HRESULT hr = Run();
246 ::SetConsoleCtrlHandler(NULL, FALSE);
247 return hr;
250 if (command_line.HasSwitch(kServiceSwitch) ||
251 command_line.HasSwitch(kRequirementsSwitch)) {
252 *is_service = true;
253 check_requirements_ = command_line.HasSwitch(kRequirementsSwitch);
254 return S_OK;
258 InvalidUsage();
259 return S_FALSE;
262 HRESULT SelectWindowsAccount(string16* run_as_user, string16* run_as_password,
263 base::FilePath* user_data_dir,
264 std::vector<std::string>* printers) {
265 *run_as_user = GetCurrentUserName();
266 std::cout << cloud_print::LoadLocalString(IDS_WINDOWS_USER_PROMPT1) << "\n";
267 *run_as_user = GetOption(IDS_WINDOWS_USER_PROMPT2, *run_as_user, false);
268 *run_as_user = ReplaceLocalHostInName(*run_as_user);
269 *run_as_password = GetOption(IDS_WINDOWS_PASSWORD_PROMPT, L"", true);
270 SetupListener setup(*run_as_user);
271 HRESULT hr = controller_->InstallCheckService(*run_as_user,
272 *run_as_password,
273 user_data_dir_switch_);
274 if (FAILED(hr)) {
275 return ReportError(hr, IDS_ERROR_FAILED_INSTALL_SERVICE);
279 // Always uninstall service after requirements check.
280 base::ScopedClosureRunner scoped_uninstall(
281 base::Bind(base::IgnoreResult(&ServiceController::UninstallService),
282 base::Unretained(controller_.get())));
284 hr = controller_->StartService();
285 if (FAILED(hr)) {
286 return ReportError(hr, IDS_ERROR_FAILED_START_SERVICE);
289 if (!setup.WaitResponce(base::TimeDelta::FromSeconds(30))) {
290 return ReportError(E_FAIL, IDS_ERROR_FAILED_START_SERVICE);
294 if (setup.user_data_dir().empty()) {
295 return ReportError(E_FAIL, IDS_ERROR_NO_DATA_DIR);
298 if (setup.chrome_path().empty()) {
299 return ReportError(E_FAIL, IDS_ERROR_NO_CHROME);
302 if (!setup.is_xps_available()) {
303 return ReportError(E_FAIL, IDS_ERROR_NO_XPS);
306 std::cout << "\n";
307 std::cout << cloud_print::LoadLocalString(IDS_SERVICE_ENV_CHECK);
308 std::cout << "\n";
309 std::cout << cloud_print::LoadLocalString(IDS_SERVICE_ENV_USER);
310 std::cout << "\n " << setup.user_name() << "\n";
311 std::cout << cloud_print::LoadLocalString(IDS_SERVICE_ENV_CHROME);
312 std::cout << "\n " << setup.chrome_path().value() << "\n";
313 std::cout << cloud_print::LoadLocalString(IDS_SERVICE_ENV_DATADIR);
314 std::cout << "\n " << setup.user_data_dir().value() << "\n";
315 std::cout << cloud_print::LoadLocalString(IDS_SERVICE_ENV_PRINTERS);
316 std::cout << "\n ";
317 std::ostream_iterator<std::string> cout_it(std::cout, "\n ");
318 std::copy(setup.printers().begin(), setup.printers().end(), cout_it);
319 std::cout << "\n";
321 *user_data_dir = setup.user_data_dir();
322 *printers = setup.printers();
323 return S_OK;
326 HRESULT SetupServiceState(const base::FilePath& user_data_dir,
327 const std::vector<std::string>& printers) {
328 base::FilePath file = user_data_dir.Append(chrome::kServiceStateFileName);
330 std::string contents;
331 ServiceState service_state;
333 bool is_valid = base::ReadFileToString(file, &contents) &&
334 service_state.FromString(contents);
335 std::string proxy_id = service_state.proxy_id();
337 LOG(INFO) << file.value() << ": " << contents;
339 string16 message =
340 cloud_print::LoadLocalString(IDS_ADD_PRINTERS_USING_CHROME);
341 std::cout << "\n" << message.c_str() << "\n" ;
342 std::string new_contents =
343 ChromeLauncher::CreateServiceStateFile(proxy_id, printers);
345 if (new_contents.empty()) {
346 return ReportError(E_FAIL, IDS_ERROR_FAILED_CREATE_CONFIG);
349 if (new_contents != contents) {
350 size_t written = file_util::WriteFile(file, new_contents.c_str(),
351 new_contents.size());
352 if (written != new_contents.size()) {
353 return ReportError(cloud_print::GetLastHResult(),
354 IDS_ERROR_FAILED_CREATE_CONFIG);
358 return S_OK;
361 void CheckRequirements() {
362 setup_listener_.reset(new ServiceListener(GetUserDataDir()));
365 HRESULT StartConnector() {
366 chrome_.reset(new ChromeLauncher(GetUserDataDir()));
367 return chrome_->Start() ? S_OK : E_FAIL;
370 void StopConnector() {
371 if (chrome_.get()) {
372 chrome_->Stop();
373 chrome_.reset();
377 base::FilePath GetUserDataDir() const {
378 if (!user_data_dir_switch_.empty())
379 return user_data_dir_switch_;
380 base::FilePath result;
381 CHECK(PathService::Get(base::DIR_LOCAL_APP_DATA, &result));
382 return result.Append(kSubDirectory);
385 static BOOL WINAPI ConsoleCtrlHandler(DWORD type);
387 bool check_requirements_;
388 base::FilePath user_data_dir_switch_;
389 scoped_ptr<ChromeLauncher> chrome_;
390 scoped_ptr<ServiceController> controller_;
391 scoped_ptr<ServiceListener> setup_listener_;
394 CloudPrintServiceModule _AtlModule;
396 BOOL CloudPrintServiceModule::ConsoleCtrlHandler(DWORD type) {
397 PostThreadMessage(_AtlModule.m_dwThreadID, WM_QUIT, 0, 0);
398 return TRUE;
401 int main(int argc, char** argv) {
402 CommandLine::Init(argc, argv);
403 base::AtExitManager at_exit;
405 logging::LoggingSettings settings;
406 settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
407 logging::InitLogging(settings);
409 logging::SetMinLogLevel(
410 CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableLogging) ?
411 logging::LOG_INFO : logging::LOG_FATAL);
413 return _AtlModule.WinMain(0);