forked from tromgy/service-base
/
ServiceBase.cpp
630 lines (540 loc) · 18.8 KB
/
ServiceBase.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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/****************************** Module Header ******************************\
* Module Name: ServiceBase.cpp
* Project: service-base
* Copyright (c) Microsoft Corporation.
* Copyright (c) Tromgy (tromgy@yahoo.com)
*
* Provides a base class for a service that will exist as part of a service
* application. CServiceBase must be derived from when creating a new service
* class.
*
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/en-us/openness/resources/licenses.aspx#MPL.
* All other rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/
#pragma region Includes
#include "ServiceBase.h"
#include <assert.h>
#include <strsafe.h>
#pragma endregion
#pragma region Static Members
// Initialize the singleton service instance.
CServiceBase *CServiceBase::s_service = nullptr;
//
// FUNCTION: CServiceBase::Run(CServiceBase &)
//
// PURPOSE: Register the executable for a service with the Service Control
// Manager (SCM). After you call Run(ServiceBase), the SCM issues a Start
// command, which results in a call to the OnStart method in the service.
// This method blocks until the service has stopped.
//
// PARAMETERS:
// * service - the reference to a CServiceBase object. It will become the
// singleton service instance of this service application.
//
// RETURN VALUE: If the function succeeds, the return value is TRUE. If the
// function fails, the return value is FALSE. To get extended error
// information, call GetLastError.
//
BOOL CServiceBase::Run(CServiceBase &service)
{
s_service = &service;
SERVICE_TABLE_ENTRYW serviceTable[] =
{
{ const_cast<LPWSTR>(service.m_name), ServiceMain },
{ nullptr, nullptr }
};
// Connects the main thread of a service process to the service control
// manager, which causes the thread to be the service control dispatcher
// thread for the calling process. This call returns when the service has
// stopped. The process should simply terminate when the call returns.
return StartServiceCtrlDispatcherW(serviceTable);
}
//
// FUNCTION: CServiceBase::ServiceMain(DWORD, PWSTR *)
//
// PURPOSE: Entry point for the service. It registers the handler function
// for the service and starts the service.
//
// PARAMETERS:
// * dwArgc - number of command line arguments
// * lpszArgv - array of command line arguments
//
void WINAPI CServiceBase::ServiceMain(DWORD dwArgc, PWSTR *pszArgv)
{
assert(s_service != nullptr);
// Register the handler function for the service
s_service->m_statusHandle = RegisterServiceCtrlHandlerW(
s_service->m_name, ServiceCtrlHandler);
if (s_service->m_statusHandle == nullptr)
{
throw GetLastError();
}
// Start the service.
s_service->Start(dwArgc, pszArgv);
}
//
// FUNCTION: CServiceBase::ServiceCtrlHandler(DWORD)
//
// PURPOSE: The function is called by the SCM whenever a control code is
// sent to the service.
//
// PARAMETERS:
// * dwCtrlCode - the control code. This parameter can be one of the
// following values:
//
// SERVICE_CONTROL_CONTINUE
// SERVICE_CONTROL_INTERROGATE
// SERVICE_CONTROL_NETBINDADD
// SERVICE_CONTROL_NETBINDDISABLE
// SERVICE_CONTROL_NETBINDREMOVE
// SERVICE_CONTROL_PARAMCHANGE
// SERVICE_CONTROL_PAUSE
// SERVICE_CONTROL_SHUTDOWN
// SERVICE_CONTROL_STOP
//
// This parameter can also be a user-defined control code ranges from 128
// to 255.
//
void WINAPI CServiceBase::ServiceCtrlHandler(DWORD dwCtrl)
{
switch (dwCtrl)
{
case SERVICE_CONTROL_STOP:
s_service->Stop();
break;
case SERVICE_CONTROL_PAUSE:
s_service->Pause();
break;
case SERVICE_CONTROL_CONTINUE:
s_service->Continue();
break;
case SERVICE_CONTROL_SHUTDOWN:
s_service->Shutdown();
break;
case SERVICE_CONTROL_INTERROGATE:
break;
default:
break;
}
}
#pragma endregion
#pragma region Service Constructor and Destructor
//
// FUNCTION: CServiceBase::CServiceBase(PWSTR, BOOL, BOOL, BOOL)
//
// PURPOSE: The constructor of CServiceBase. It initializes a new instance
// of the CServiceBase class. The optional parameters (fCanStop,
/// fCanShutdown and fCanPauseContinue) allow you to specify whether the
// service can be stopped, paused and continued, or be notified when system
// shutdown occurs.
//
// PARAMETERS:
// * pszServiceName - the name of the service
// * fCanStop - the service can be stopped
// * fCanShutdown - the service is notified when system shutdown occurs
// * fCanPauseContinue - the service can be paused and continued
// * dwErrorEventId - the event id for the error log messages
// * wErrorCategoryId - the event category for the error log messages.
//
CServiceBase::CServiceBase(PCWSTR pszServiceName,
BOOL fCanStop,
BOOL fCanShutdown,
BOOL fCanPauseContinue,
DWORD dwErrorEventId,
WORD wErrorCategoryId)
{
// Service name must be a valid string and cannot be nullptr.
m_name = (pszServiceName == nullptr) ? const_cast<PWSTR>(L"") : pszServiceName;
m_statusHandle = nullptr;
// The service runs in its own process.
m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
// The service is starting.
m_status.dwCurrentState = SERVICE_START_PENDING;
// The accepted commands of the service.
DWORD dwControlsAccepted = 0;
if (fCanStop)
dwControlsAccepted |= SERVICE_ACCEPT_STOP;
if (fCanShutdown)
dwControlsAccepted |= SERVICE_ACCEPT_SHUTDOWN;
if (fCanPauseContinue)
dwControlsAccepted |= SERVICE_ACCEPT_PAUSE_CONTINUE;
m_status.dwControlsAccepted = dwControlsAccepted;
m_status.dwWin32ExitCode = NO_ERROR;
m_status.dwServiceSpecificExitCode = 0;
m_status.dwCheckPoint = 0;
m_status.dwWaitHint = 0;
m_dwErrorEventId = dwErrorEventId;
m_wErrorCategoryId = wErrorCategoryId;
}
//
// FUNCTION: CServiceBase::~CServiceBase()
//
// PURPOSE: The virtual destructor of CServiceBase.
//
CServiceBase::~CServiceBase(void)
{
}
#pragma endregion
#pragma region Service Start, Stop, Pause, Continue, and Shutdown
//
// FUNCTION: CServiceBase::Start(DWORD, PWSTR *)
//
// PURPOSE: The function starts the service. It calls the OnStart virtual
// function in which you can specify the actions to take when the service
// starts. If an error occurs during the startup, the error will be logged
// in the Application event log, and the service will be stopped.
//
// PARAMETERS:
// * dwArgc - number of command line arguments
// * lpszArgv - array of command line arguments
//
void CServiceBase::Start(DWORD dwArgc, PWSTR *pszArgv)
{
try
{
// Tell SCM that the service is starting.
SetServiceStatus(SERVICE_START_PENDING);
// Perform service-specific initialization.
OnStart(dwArgc, pszArgv);
// Tell SCM that the service is started.
SetServiceStatus(SERVICE_RUNNING);
}
catch (DWORD dwError)
{
// Log the error.
WriteErrorLogEntry(L"Service Start", dwError);
// Set the service status to be stopped.
SetServiceStatus(SERVICE_STOPPED, dwError);
}
catch (...)
{
// Log the error.
WriteLogEntry(L"Service failed to start.", EVENTLOG_ERROR_TYPE, m_dwErrorEventId, m_wErrorCategoryId);
// Set the service status to be stopped.
SetServiceStatus(SERVICE_STOPPED);
}
}
//
// FUNCTION: CServiceBase::OnStart(DWORD, PWSTR *)
//
// PURPOSE: When implemented in a derived class, executes when a Start
// command is sent to the service by the SCM or when the operating system
// starts (for a service that starts automatically). Specifies actions to
// take when the service starts. Be sure to periodically call
// CServiceBase::SetServiceStatus() with SERVICE_START_PENDING if the
// procedure is going to take long time. You may also consider spawning a
// new thread in OnStart to perform time-consuming initialization tasks.
//
// PARAMETERS:
// * dwArgc - number of command line arguments
// * lpszArgv - array of command line arguments
//
void CServiceBase::OnStart(DWORD dwArgc, PWSTR *pszArgv)
{
}
//
// FUNCTION: CServiceBase::Stop()
//
// PURPOSE: The function stops the service. It calls the OnStop virtual
// function in which you can specify the actions to take when the service
// stops. If an error occurs, the error will be logged in the Application
// event log, and the service will be restored to the original state.
//
void CServiceBase::Stop()
{
DWORD dwOriginalState = m_status.dwCurrentState;
try
{
// Tell SCM that the service is stopping.
SetServiceStatus(SERVICE_STOP_PENDING);
// Perform service-specific stop operations.
OnStop();
// Tell SCM that the service is stopped.
SetServiceStatus(SERVICE_STOPPED);
}
catch (DWORD dwError)
{
// Log the error.
WriteErrorLogEntry(L"Service Stop", dwError);
// Set the orginal service status.
SetServiceStatus(dwOriginalState);
}
catch (...)
{
// Log the error.
WriteLogEntry(L"Service failed to stop.", EVENTLOG_ERROR_TYPE, m_dwErrorEventId, m_wErrorCategoryId);
// Set the orginal service status.
SetServiceStatus(dwOriginalState);
}
}
//
// FUNCTION: CServiceBase::OnStop()
//
// PURPOSE: When implemented in a derived class, executes when a Stop
// command is sent to the service by the SCM. Specifies actions to take
// when a service stops running. Be sure to periodically call
// CServiceBase::SetServiceStatus() with SERVICE_STOP_PENDING if the
// procedure is going to take long time.
//
void CServiceBase::OnStop()
{
}
//
// FUNCTION: CServiceBase::Pause()
//
// PURPOSE: The function pauses the service if the service supports pause
// and continue. It calls the OnPause virtual function in which you can
// specify the actions to take when the service pauses. If an error occurs,
// the error will be logged in the Application event log, and the service
// will become running.
//
void CServiceBase::Pause()
{
try
{
// Tell SCM that the service is pausing.
SetServiceStatus(SERVICE_PAUSE_PENDING);
// Perform service-specific pause operations.
OnPause();
// Tell SCM that the service is paused.
SetServiceStatus(SERVICE_PAUSED);
}
catch (DWORD dwError)
{
// Log the error.
WriteErrorLogEntry(L"Service Pause", dwError);
// Tell SCM that the service is still running.
SetServiceStatus(SERVICE_RUNNING);
}
catch (...)
{
// Log the error.
WriteLogEntry(L"Service failed to pause.", EVENTLOG_ERROR_TYPE, m_dwErrorEventId, m_wErrorCategoryId);
// Tell SCM that the service is still running.
SetServiceStatus(SERVICE_RUNNING);
}
}
//
// FUNCTION: CServiceBase::OnPause()
//
// PURPOSE: When implemented in a derived class, executes when a Pause
// command is sent to the service by the SCM. Specifies actions to take
// when a service pauses.
//
void CServiceBase::OnPause()
{
}
//
// FUNCTION: CServiceBase::Continue()
//
// PURPOSE: The function resumes normal functioning after being paused if
// the service supports pause and continue. It calls the OnContinue virtual
// function in which you can specify the actions to take when the service
// continues. If an error occurs, the error will be logged in the
// Application event log, and the service will still be paused.
//
void CServiceBase::Continue()
{
try
{
// Tell SCM that the service is resuming.
SetServiceStatus(SERVICE_CONTINUE_PENDING);
// Perform service-specific continue operations.
OnContinue();
// Tell SCM that the service is running.
SetServiceStatus(SERVICE_RUNNING);
}
catch (DWORD dwError)
{
// Log the error.
WriteErrorLogEntry(L"Service Continue", dwError);
// Tell SCM that the service is still paused.
SetServiceStatus(SERVICE_PAUSED);
}
catch (...)
{
// Log the error.
WriteLogEntry(L"Service failed to resume.", EVENTLOG_ERROR_TYPE, m_dwErrorEventId, m_wErrorCategoryId);
// Tell SCM that the service is still paused.
SetServiceStatus(SERVICE_PAUSED);
}
}
//
// FUNCTION: CServiceBase::OnContinue()
//
// PURPOSE: When implemented in a derived class, OnContinue runs when a
// Continue command is sent to the service by the SCM. Specifies actions to
// take when a service resumes normal functioning after being paused.
//
void CServiceBase::OnContinue()
{
}
//
// FUNCTION: CServiceBase::Shutdown()
//
// PURPOSE: The function executes when the system is shutting down. It
// calls the OnShutdown virtual function in which you can specify what
// should occur immediately prior to the system shutting down. If an error
// occurs, the error will be logged in the Application event log.
//
void CServiceBase::Shutdown()
{
try
{
// Perform service-specific shutdown operations.
OnShutdown();
// Tell SCM that the service is stopped.
SetServiceStatus(SERVICE_STOPPED);
}
catch (DWORD dwError)
{
// Log the error.
WriteErrorLogEntry(L"Service Shutdown", dwError);
}
catch (...)
{
// Log the error.
WriteLogEntry(L"Service failed to shut down.", EVENTLOG_ERROR_TYPE, m_dwErrorEventId, m_wErrorCategoryId);
}
}
//
// FUNCTION: CServiceBase::OnShutdown()
//
// PURPOSE: When implemented in a derived class, executes when the system
// is shutting down. Specifies what should occur immediately prior to the
// system shutting down.
//
void CServiceBase::OnShutdown()
{
}
#pragma endregion
#pragma region Helper Functions
//
// FUNCTION: CServiceBase::SetServiceStatus(DWORD, DWORD, DWORD)
//
// PURPOSE: The function sets the service status and reports the status to
// the SCM.
//
// PARAMETERS:
// * dwCurrentState - the state of the service
// * dwWin32ExitCode - error code to report
// * dwWaitHint - estimated time for pending operation, in milliseconds
//
void CServiceBase::SetServiceStatus(DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwWaitHint)
{
static DWORD dwCheckPoint = 1;
// Fill in the SERVICE_STATUS structure of the service.
m_status.dwCurrentState = dwCurrentState;
m_status.dwWin32ExitCode = dwWin32ExitCode;
m_status.dwWaitHint = dwWaitHint;
m_status.dwCheckPoint =
((dwCurrentState == SERVICE_RUNNING) ||
(dwCurrentState == SERVICE_STOPPED)) ?
0 : dwCheckPoint++;
// Report the status of the service to the SCM.
::SetServiceStatus(m_statusHandle, &m_status);
}
//
// FUNCTION: CServiceBase::WriteEventLogEntry(PWSTR, WORD)
//
// PURPOSE: Log a message to the Application event log.
//
// PARAMETERS:
// * pszMessage - string(s) of the message to be logged.
// to display multiple strings in Windows Event Viewer "Details" page separate them with '\n'
// * wType - the type of event to be logged. The parameter can be one of
// the following values.
//
// EVENTLOG_SUCCESS
// EVENTLOG_AUDIT_FAILURE
// EVENTLOG_AUDIT_SUCCESS
// EVENTLOG_ERROR_TYPE
// EVENTLOG_INFORMATION_TYPE
// EVENTLOG_WARNING_TYPE
// * dwEventId - event id. A string with this id should exist in the message file
// that gets compiled into the resources. The file that contains those resources
// is then supposed to be registered with the system.
// * wCategory - category id. This is similar to event id, but the corresponding string
// is shown in a separate column in Windows Event Viewer.
//
// NOTE: It can be overriden to do any other kind of logging in a sublcass
//
void CServiceBase::WriteLogEntry(PCWSTR pszMessage, WORD wType, DWORD dwEventId, WORD wCategory)
{
HANDLE hEventSource = nullptr;
PWSTR pszSource; // Copy of pszMessage for splitting
PCWSTR* pszStrings; // Message strings to shown on the "Details" tab in Event Viewer
WCHAR* pContext; // Tokenization context
PCWSTR delimiter = L"\n"; // Strings are delimited by new lines
WORD nStrings = 1; // Number of strings in the message
// Prepare event strings by splitting the message at new lines
// Copy the input string as tokenizing modifies the source
pszSource = _wcsdup(pszMessage);
if (pszSource == nullptr)
{
return;
}
// First find the number of strings
for (PCWSTR pOccur = wcschr(pszMessage, delimiter[0]); pOccur != nullptr; pOccur = wcschr(++pOccur, delimiter[0]))
{
nStrings++;
}
try
{
// Allocate the array of strings
pszStrings = new PCWSTR[nStrings];
}
catch (...)
{
delete pszSource;
return;
}
// Token index
WORD i = 0;
for (LPCWSTR token = wcstok_s(pszSource, delimiter, &pContext); token != nullptr; token = wcstok_s(nullptr, delimiter, &pContext))
{
pszStrings[i++] = token;
}
hEventSource = RegisterEventSourceW(nullptr, m_name);
if (hEventSource)
{
ReportEventW(hEventSource, // Event log handle
wType, // Event type
wCategory, // Event category
dwEventId, // Event identifier
nullptr, // No security identifier
nStrings, // Size of lpszStrings array
0, // No binary data
pszStrings, // Array of strings
nullptr // No binary data
);
DeregisterEventSource(hEventSource);
}
// Free heap memory
delete[] pszStrings;
delete pszSource;
}
//
// FUNCTION: CServiceBase::WriteErrorLogEntry(PWSTR, DWORD)
//
// PURPOSE: Log an error message to the Application event log.
//
// PARAMETERS:
// * pszFunction - the function that gives the error
// * dwError - the error code
//
void CServiceBase::WriteErrorLogEntry(PCWSTR pszFunction, DWORD dwError)
{
wchar_t szMessage[260];
StringCchPrintfW(szMessage, ARRAYSIZE(szMessage),
L"%s failed with error code 0x%08lx", pszFunction, dwError);
WriteLogEntry(szMessage, EVENTLOG_ERROR_TYPE, m_dwErrorEventId, m_wErrorCategoryId);
}
#pragma endregion