-
Notifications
You must be signed in to change notification settings - Fork 4
/
SrvCtrl.cpp
360 lines (282 loc) · 9.74 KB
/
SrvCtrl.cpp
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
/* Copyright (C) 2016-2020 Thomas Hauck - All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
The author would be happy if changes and
improvements were reported back to him.
Author: Thomas Hauck
Email: [email protected]
*/
#if defined(_WIN32) || defined(_WIN64)
#include "SrvCtrl.h"
#include <string>
#include <VersionHelpers.h>
using namespace std;
CSvrCtrl::CSvrCtrl(void) noexcept : m_hSCManager(OpenSCManager(
nullptr, // local machine
nullptr, // ServicesActive database
SC_MANAGER_ALL_ACCESS)) // full access rights
{
}
CSvrCtrl::~CSvrCtrl(void)
{
if (m_hSCManager != nullptr)
CloseServiceHandle(m_hSCManager);
}
int CSvrCtrl::Install(const wchar_t* szSvrName, const wchar_t* szDisplayName, const wchar_t* szDescription/* = nullptr*/)
{
if (SelfElevat() == true)
return 0;
wchar_t szPath[MAX_PATH];
if(GetModuleFileName(nullptr, &szPath[0], MAX_PATH) == 0)
{
// printf("GetModuleFileName failed (%d)\n", GetLastError());
return -2;
}
SC_HANDLE schService = CreateService(
m_hSCManager, // SCManager database
szSvrName, // name of service
szDisplayName, // service name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_AUTO_START, // start type
SERVICE_ERROR_NORMAL, // error control type
&szPath[0], // path to service's binary
nullptr, // no load ordering group
nullptr, // no tag identifier
nullptr, // no dependencies
nullptr, // LocalSystem account
nullptr); // no password
if (schService == nullptr)
{
// printf("CreateService failed (%d)\n", GetLastError());
return -1;
}
else
{
CloseServiceHandle(schService);
if (szDescription != nullptr)
SetServiceDescription(szSvrName, szDescription);
return 0;
}
}
int CSvrCtrl::Remove(const wchar_t* szSvrName)
{
if (SelfElevat() == true)
return 0;
SC_HANDLE schService = OpenService(
m_hSCManager, // SCManager database
szSvrName, // name of service
DELETE); // only need DELETE access
if (schService == nullptr)
{
// printf("OpenService failed (%d)\n", GetLastError());
return -3;
}
if (DeleteService(schService) == 0)
{
// printf("DeleteService failed (%d)\n", GetLastError());
CloseServiceHandle(schService);
return -4;
}
CloseServiceHandle(schService);
return 0;
}
int CSvrCtrl::Start(const wchar_t* szSvrName)
{
if (SelfElevat() == true)
return 0;
SC_HANDLE schService{};
SERVICE_STATUS_PROCESS ssStatus{};
DWORD dwOldCheckPoint{};
DWORD dwStartTickCount{};
DWORD dwBytesNeeded{};
schService = OpenService(m_hSCManager, szSvrName, SERVICE_ALL_ACCESS);
if (schService == nullptr)
return -5;
if (StartService(schService, 0, nullptr) == 0)
{
CloseServiceHandle(schService);
return 6;
}
// Check the status until the service is no longer start pending.
if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // info level
(LPBYTE)&ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // if buffer too small
{
CloseServiceHandle(schService);
return 0;
}
// Save the tick count and initial checkpoint.
dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
while (ssStatus.dwCurrentState == SERVICE_START_PENDING)
{
// Do not wait longer than the wait hint. A good interval is
// one tenth the wait hint, but no less than 1 second and no
// more than 10 seconds.
DWORD dwWaitTime = ssStatus.dwWaitHint / 10;
if( dwWaitTime < 1000 )
dwWaitTime = 1000;
else if ( dwWaitTime > 10000 )
dwWaitTime = 10000;
Sleep( dwWaitTime );
// Check the status again.
if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // info level
(LPBYTE)&ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // if buffer too small
break;
if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
{
// The service is making progress.
dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
}
else
{
if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
{
// No progress made within the wait hint
break;
}
}
}
CloseServiceHandle(schService);
if (ssStatus.dwCurrentState == SERVICE_RUNNING)
return 1;
return 0;
}
int CSvrCtrl::Stop(const wchar_t* szSvrName)
{
if (SelfElevat() == true)
return 0;
SC_HANDLE schService = OpenService(m_hSCManager, szSvrName, SERVICE_ALL_ACCESS);
if (schService == nullptr)
return -5;
DWORD dwError{};
SERVICE_STATUS ssStatus;
if (ControlService(schService, SERVICE_CONTROL_STOP, &ssStatus) == 0)
dwError = GetLastError();
CloseServiceHandle(schService);
return dwError;
}
int CSvrCtrl::Pause(const wchar_t* szSvrName)
{
if (SelfElevat() == true)
return 0;
SC_HANDLE schService = OpenService(m_hSCManager, szSvrName, SERVICE_ALL_ACCESS);
if (schService == nullptr)
return -5;
DWORD dwError{};
SERVICE_STATUS ssStatus;
if (ControlService(schService, SERVICE_CONTROL_PAUSE, &ssStatus) == 0)
dwError = GetLastError();
CloseServiceHandle(schService);
return dwError;
}
int CSvrCtrl::Continue(const wchar_t* szSvrName)
{
if (SelfElevat() == true)
return 0;
SC_HANDLE schService = OpenService(m_hSCManager, szSvrName, SERVICE_ALL_ACCESS);
if (schService == nullptr)
return -5;
DWORD dwError{};
SERVICE_STATUS ssStatus;
if (ControlService(schService, SERVICE_CONTROL_CONTINUE, &ssStatus) == 0)
dwError = GetLastError();
CloseServiceHandle(schService);
return dwError;
}
bool CSvrCtrl::SetServiceDescription(const wchar_t* szSvrName, const wchar_t* szDescription) noexcept
{
// Need to acquire database lock before reconfiguring.
SC_LOCK sclLock = LockServiceDatabase(m_hSCManager);
// If the database cannot be locked, report the details.
if (sclLock == nullptr)
{
// Exit if the database is not locked by another process.
if (GetLastError() != ERROR_SERVICE_DATABASE_LOCKED)
{
return false;
}
// Allocate a buffer to get details about the lock.
LPQUERY_SERVICE_LOCK_STATUS lpqslsBuf = static_cast<LPQUERY_SERVICE_LOCK_STATUS>(LocalAlloc(LPTR, sizeof(QUERY_SERVICE_LOCK_STATUS) + 256));
if (lpqslsBuf == nullptr)
{
return false;
}
// Get and print the lock status information.
DWORD dwBytesNeeded;
if (!QueryServiceLockStatus(m_hSCManager, lpqslsBuf, sizeof(QUERY_SERVICE_LOCK_STATUS) + 256, &dwBytesNeeded))
{
return FALSE;
}
LocalFree(lpqslsBuf);
}
// The database is locked, so it is safe to make changes.
bool bRet{ true};
// Open a handle to the service.
SC_HANDLE schService = OpenService(m_hSCManager, szSvrName, SERVICE_CHANGE_CONFIG); // need CHANGE access
if (schService == nullptr)
{
// Release the database lock.
UnlockServiceDatabase(sclLock);
return false;
}
SERVICE_DESCRIPTION sdBuf;
sdBuf.lpDescription = const_cast<wchar_t*>(szDescription);
if( !ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdBuf)) // value: new description
{
bRet = false;
}
// Release the database lock.
UnlockServiceDatabase(sclLock);
// Close the handle to the service.
CloseServiceHandle(schService);
return bRet;
}
bool CSvrCtrl::SelfElevat()
{
// check Windows version
if (!IsWindowsVistaOrGreater())
return false;
// check if elevated on Vista and 7
HANDLE Token{};
TOKEN_ELEVATION Elevation{}; // Token type only available with Vista/7
DWORD ReturnSize{};
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &Token) ||
!GetTokenInformation(Token, TokenElevation, &Elevation, sizeof(Elevation), &ReturnSize))
return false;
if (Elevation.TokenIsElevated) // process is elevated
return false;
wstring FileName(MAX_PATH, 0);
GetModuleFileName(nullptr, &FileName[0], MAX_PATH);
FileName.erase(FileName.find_first_of(L'\0'));
wstring pStrCmdLine = GetCommandLine();
size_t nPos = pStrCmdLine.find(FileName);
if (nPos != string::npos)
{
nPos += pStrCmdLine.substr(nPos + FileName.size()).find_first_of(L' ') + 1 + FileName.size();
pStrCmdLine.erase(0, nPos);
}
SHELLEXECUTEINFO Info;
Info.hwnd = nullptr;
Info.cbSize = sizeof(Info);
Info.fMask = 0;
Info.hwnd = nullptr;
Info.lpVerb = L"runas";
Info.lpFile = &FileName[0];
Info.lpParameters = &pStrCmdLine[0];
Info.lpDirectory = nullptr;
Info.nShow = 0;// SW_HIDE;
Info.hInstApp = nullptr;
while (!ShellExecuteEx(&Info));
return true;
}
#endif