forked from pocoproject/poco
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWinService.cpp
More file actions
426 lines (358 loc) · 9.64 KB
/
WinService.cpp
File metadata and controls
426 lines (358 loc) · 9.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//
// WinService.cpp
//
// Library: Util
// Package: Windows
// Module: WinService
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#if !defined(_WIN32_WCE)
#include "Poco/Util/WinService.h"
#include "Poco/Util/WinRegistryKey.h"
#include "Poco/Thread.h"
#include "Poco/Exception.h"
#include "Poco/UnicodeConverter.h"
using Poco::Thread;
using Poco::SystemException;
using Poco::NotFoundException;
using Poco::OutOfMemoryException;
namespace Poco {
namespace Util {
const int WinService::STARTUP_TIMEOUT = 30000;
const std::string WinService::REGISTRY_KEY("SYSTEM\\CurrentControlSet\\Services\\");
const std::string WinService::REGISTRY_DESCRIPTION("Description");
WinService::WinService(const std::string& name):
_name(name),
_svcHandle(0)
{
_scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (!_scmHandle) throw SystemException("cannot open Service Control Manager");
}
WinService::WinService(SC_HANDLE scmHandle, const std::string& name):
_scmHandle(scmHandle),
_name(name),
_svcHandle(0)
{
if (!_scmHandle) throw SystemException("Service Control Manager not connected");
}
WinService::~WinService()
{
close();
CloseServiceHandle(_scmHandle);
}
const std::string& WinService::name() const
{
return _name;
}
std::string WinService::displayName() const
{
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = config();
std::wstring udispName(pSvcConfig->lpDisplayName);
std::string dispName;
Poco::UnicodeConverter::toUTF8(udispName, dispName);
LocalFree(pSvcConfig);
return dispName;
}
std::string WinService::path() const
{
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = config();
std::wstring upath(pSvcConfig->lpBinaryPathName);
std::string path;
UnicodeConverter::toUTF8(upath, path);
LocalFree(pSvcConfig);
return path;
}
void WinService::registerService(const std::string& path, const std::string& displayName)
{
close();
std::wstring uname;
Poco::UnicodeConverter::toUTF16(_name, uname);
std::wstring udisplayName;
Poco::UnicodeConverter::toUTF16(displayName, udisplayName);
std::wstring upath;
Poco::UnicodeConverter::toUTF16(path, upath);
_svcHandle = CreateServiceW(
_scmHandle,
uname.c_str(),
udisplayName.c_str(),
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
upath.c_str(),
NULL, NULL, NULL, NULL, NULL);
if (!_svcHandle)
throw SystemException("cannot register service", _name);
}
void WinService::registerService(const std::string& path)
{
registerService(path, _name);
}
void WinService::unregisterService()
{
open();
if (!DeleteService(_svcHandle))
throw SystemException("cannot unregister service", _name);
close();
}
bool WinService::isRegistered() const
{
return tryOpen();
}
bool WinService::isRunning() const
{
open();
SERVICE_STATUS ss;
if (!QueryServiceStatus(_svcHandle, &ss))
throw SystemException("cannot query service status", _name);
return ss.dwCurrentState == SERVICE_RUNNING;
}
bool WinService::isStopped() const
{
open();
SERVICE_STATUS ss;
if (!QueryServiceStatus(_svcHandle, &ss))
throw SystemException("cannot query service status", _name);
return ss.dwCurrentState == SERVICE_STOPPED;
}
void WinService::start()
{
open();
if (!StartService(_svcHandle, 0, NULL))
throw SystemException("cannot start service", _name);
SERVICE_STATUS svcStatus;
long msecs = 0;
while (msecs < STARTUP_TIMEOUT)
{
if (!QueryServiceStatus(_svcHandle, &svcStatus)) break;
if (svcStatus.dwCurrentState != SERVICE_START_PENDING) break;
Thread::sleep(250);
msecs += 250;
}
if (!QueryServiceStatus(_svcHandle, &svcStatus))
throw SystemException("cannot query status of starting service", _name);
else if (svcStatus.dwCurrentState != SERVICE_RUNNING)
throw SystemException("service failed to start within a reasonable time", _name);
}
void WinService::stop()
{
open();
SERVICE_STATUS svcStatus;
if (!ControlService(_svcHandle, SERVICE_CONTROL_STOP, &svcStatus))
throw SystemException("cannot stop service", _name);
}
void WinService::setStartup(WinService::Startup startup)
{
open();
DWORD startType;
switch (startup)
{
case SVC_AUTO_START:
startType = SERVICE_AUTO_START;
break;
case SVC_MANUAL_START:
startType = SERVICE_DEMAND_START;
break;
case SVC_DISABLED:
startType = SERVICE_DISABLED;
break;
default:
startType = SERVICE_NO_CHANGE;
}
if (!ChangeServiceConfig(_svcHandle, SERVICE_NO_CHANGE, startType, SERVICE_NO_CHANGE, NULL, NULL, NULL, NULL, NULL, NULL, NULL))
{
throw SystemException("cannot change service startup mode");
}
}
WinService::Startup WinService::getStartup() const
{
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = config();
Startup result;
switch (pSvcConfig->dwStartType)
{
case SERVICE_AUTO_START:
case SERVICE_BOOT_START:
case SERVICE_SYSTEM_START:
result = SVC_AUTO_START;
break;
case SERVICE_DEMAND_START:
result = SVC_MANUAL_START;
break;
case SERVICE_DISABLED:
result = SVC_DISABLED;
break;
default:
poco_debugger();
result = SVC_MANUAL_START;
}
LocalFree(pSvcConfig);
return result;
}
void WinService::setFailureActions(FailureActionVector failureActions, const std::string& command, const std::string& rebootMessage)
{
if (failureActions.size() > 3) {
throw InvalidArgumentException{ "Only 0-3 Failure Actions are supported" };
}
open();
auto actions = new SC_ACTION[failureActions.size()];
SERVICE_FAILURE_ACTIONSW ac;
ac.lpCommand = NULL;
ac.lpRebootMsg = NULL;
std::wstring urebootMessage;
Poco::UnicodeConverter::toUTF16(rebootMessage, urebootMessage);
std::vector<wchar_t> rebootMessageVector{ urebootMessage.begin(), urebootMessage.end() };
rebootMessageVector.push_back('\0');
std::wstring uComamnd;
Poco::UnicodeConverter::toUTF16(command, uComamnd);
std::vector<wchar_t> commandVector{ uComamnd.begin(), uComamnd.end() };
commandVector.push_back('\0');
for (auto i = 0; i < failureActions.size(); i++)
{
switch (failureActions[i].type)
{
case SVC_REBOOT:
actions[i].Type = SC_ACTION_REBOOT;
actions[i].Delay = failureActions[i].delay;
ac.lpRebootMsg = &rebootMessageVector[0];
break;
case SVC_RESTART:
actions[i].Type = SC_ACTION_RESTART;
actions[i].Delay = failureActions[i].delay;
break;
case SVC_RUN_COMMAND:
actions[i].Type = SC_ACTION_RUN_COMMAND;
actions[i].Delay = failureActions[i].delay;
ac.lpCommand = &commandVector[0];
break;
default:
actions[i].Type = SC_ACTION_NONE;
actions[i].Delay = 0;
break;
}
}
ac.dwResetPeriod = 0;
ac.cActions = failureActions.size();
ac.lpsaActions = actions;
if (!ChangeServiceConfig2W(_svcHandle, SERVICE_CONFIG_FAILURE_ACTIONS, &ac))
{
delete[] actions;
throw SystemException("cannot configure service", _name);
}
delete[] actions;
}
WinService::FailureActionTypeVector WinService::getFailureActions() const {
open();
int size = 4096;
DWORD bytesNeeded;
POCO_LPSERVICE_FAILURE_ACTION pSvcFailureAction = (POCO_LPSERVICE_FAILURE_ACTION)LocalAlloc(LPTR, size);
if (!pSvcFailureAction) throw OutOfMemoryException("cannot allocate service failure action buffer");
try {
while (!QueryServiceConfig2W(_svcHandle, SERVICE_CONFIG_FAILURE_ACTIONS, (LPBYTE)pSvcFailureAction, size, &bytesNeeded))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
LocalFree(pSvcFailureAction);
size = bytesNeeded;
pSvcFailureAction = (POCO_LPSERVICE_FAILURE_ACTION)LocalAlloc(LPTR, size);
} else throw SystemException("cannot query service configuration", _name);
}
}
catch (...)
{
LocalFree(pSvcFailureAction);
throw;
}
FailureActionTypeVector result(3, SVC_NONE);
for (auto i = 0; i < pSvcFailureAction->cActions; i++)
{
switch (pSvcFailureAction->lpsaActions->Type)
{
case SC_ACTION_NONE:
result[i] = SVC_NONE;
break;
case SC_ACTION_RESTART:
result[i] = SVC_RESTART;
break;
case SC_ACTION_REBOOT:
result[i] = SVC_REBOOT;
break;
case SC_ACTION_RUN_COMMAND:
result[i] = SVC_RUN_COMMAND;
break;
default:
result[i] = SVC_NONE;
}
++pSvcFailureAction->lpsaActions;
}
LocalFree(pSvcFailureAction);
return result;
}
void WinService::setDescription(const std::string& description)
{
std::string key(REGISTRY_KEY);
key += _name;
WinRegistryKey regKey(HKEY_LOCAL_MACHINE, key);
regKey.setString(REGISTRY_DESCRIPTION, description);
}
std::string WinService::getDescription() const
{
std::string key(REGISTRY_KEY);
key += _name;
WinRegistryKey regKey(HKEY_LOCAL_MACHINE, key, true);
return regKey.getString(REGISTRY_DESCRIPTION);
}
void WinService::open() const
{
if (!tryOpen())
throw NotFoundException("service does not exist", _name);
}
bool WinService::tryOpen() const
{
if (!_svcHandle)
{
std::wstring uname;
Poco::UnicodeConverter::toUTF16(_name, uname);
_svcHandle = OpenServiceW(_scmHandle, uname.c_str(), SERVICE_ALL_ACCESS);
}
return _svcHandle != 0;
}
void WinService::close() const
{
if (_svcHandle)
{
CloseServiceHandle(_svcHandle);
_svcHandle = 0;
}
}
POCO_LPQUERY_SERVICE_CONFIG WinService::config() const
{
open();
int size = 4096;
DWORD bytesNeeded;
POCO_LPQUERY_SERVICE_CONFIG pSvcConfig = (POCO_LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, size);
if (!pSvcConfig) throw OutOfMemoryException("cannot allocate service config buffer");
try
{
while (!QueryServiceConfigW(_svcHandle, pSvcConfig, size, &bytesNeeded))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
LocalFree(pSvcConfig);
size = bytesNeeded;
pSvcConfig = (POCO_LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, size);
}
else throw SystemException("cannot query service configuration", _name);
}
}
catch (...)
{
LocalFree(pSvcConfig);
throw;
}
return pSvcConfig;
}
} } // namespace Poco::Util
#endif // !defined(_WIN32_WCE)