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.
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"
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();
45 std::cout
<< " -" << kInstallSwitch
;
46 std::cout
<< " [ -" << switches::kUserDataDir
<< "=DIRECTORY ]";
49 std::cout
<< " | -" << kUninstallSwitch
;
50 std::cout
<< " | -" << kStartSwitch
;
51 std::cout
<< " | -" << kStopSwitch
;
53 std::cout
<< cloud_print::LoadLocalString(IDS_COMMAND_LINE_DESCRIPTION
);
60 kInstallSwitch
, IDS_SWITCH_HELP_INSTALL
62 switches::kUserDataDir
, IDS_SWITCH_HELP_DATA_DIR
64 kUninstallSwitch
, IDS_SWITCH_HELP_UNINSTALL
66 kStartSwitch
, IDS_SWITCH_HELP_START
68 kStopSwitch
, IDS_SWITCH_HELP_STOP
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
);
80 string16
GetOption(int string_id
, const string16
& default,
82 string16 prompt_format
= cloud_print::LoadLocalString(string_id
) ;
83 std::vector
<string16
> substitutions(1, default);
84 std::cout
<< ReplaceStringPlaceholders(prompt_format
, substitutions
, NULL
);
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
);
96 std::getline(std::wcin
, tmp
);
103 HRESULT
ReportError(HRESULT hr
, int string_id
) {
104 LOG(ERROR
) << cloud_print::GetErrorMessage(hr
);
105 std::cerr
<< cloud_print::LoadLocalString(string_id
);
110 string16
StateAsString(ServiceController::State state
) {
113 case ServiceController::STATE_NOT_FOUND
:
114 string_id
= IDS_SERVICE_NOT_FOUND
;
116 case ServiceController::STATE_STOPPED
:
117 string_id
= IDS_SERVICE_STOPPED
;
119 case ServiceController::STATE_RUNNING
:
120 string_id
= IDS_SERVICE_RUNNING
;
123 return string_id
? cloud_print::LoadLocalString(string_id
) : string16();
129 class CloudPrintServiceModule
130 : public ATL::CAtlServiceModuleT
<CloudPrintServiceModule
,
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.
151 bool ParseCommandLine(LPCTSTR lpCmdLine
, HRESULT
* 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
);
164 controller_
->UpdateState();
165 std::cout
<< cloud_print::LoadLocalString(IDS_STATE_LABEL
);
166 std::cout
<< " " << StateAsString(controller_
->state());
171 HRESULT
PreMessageLoop(int nShowCmd
) {
172 HRESULT hr
= Base::PreMessageLoop(nShowCmd
);
176 if (check_requirements_
) {
179 HRESULT hr
= StartConnector();
184 LogEvent(_T("Service started/resumed"));
185 SetServiceStatus(SERVICE_RUNNING
);
190 HRESULT
PostMessageLoop() {
192 setup_listener_
.reset();
193 return Base::PostMessageLoop();
197 HRESULT
ParseCommandLine(const CommandLine
& command_line
, bool* is_service
) {
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
);
223 DCHECK(user_data_dir_switch_
.empty() ||
224 user_data_dir_switch_
== user_data_dir
);
226 hr
= SetupServiceState(user_data_dir
, printers
);
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();
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
);
246 ::SetConsoleCtrlHandler(NULL
, FALSE
);
250 if (command_line
.HasSwitch(kServiceSwitch
) ||
251 command_line
.HasSwitch(kRequirementsSwitch
)) {
253 check_requirements_
= command_line
.HasSwitch(kRequirementsSwitch
);
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
,
273 user_data_dir_switch_
);
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();
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
);
307 std::cout
<< cloud_print::LoadLocalString(IDS_SERVICE_ENV_CHECK
);
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
);
317 std::ostream_iterator
<std::string
> cout_it(std::cout
, "\n ");
318 std::copy(setup
.printers().begin(), setup
.printers().end(), cout_it
);
321 *user_data_dir
= setup
.user_data_dir();
322 *printers
= setup
.printers();
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
;
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
);
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() {
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);
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);