-
Notifications
You must be signed in to change notification settings - Fork 2
/
NTService.cpp
1054 lines (867 loc) · 29.5 KB
/
NTService.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/////////////////////////////////////////////////////////////////////////////
// Copyright (C) 1997 by Joerg Koenig and the ADG mbH, Mannheim, Germany
// All rights reserved
//
// Distribute freely, except: don't remove my name from the source or
// documentation (don't take credit for my work), mark your changes (don't
// get me blamed for your possible bugs), don't alter or remove this
// notice.
// No warrantee of any kind, express or implied, is included with this
// software; use at your own risk, responsibility for damages (if any) to
// anyone resulting from the use of this software rests entirely with the
// user.
//
// Send bug reports, bug fixes, enhancements, requests, flames, etc., and
// I'll try to keep a version up to date. I can be reached as follows:
// J.Koenig@adg.de (company site)
// Joerg.Koenig@rhein-neckar.de (private site)
/////////////////////////////////////////////////////////////////////////////
//
// MODIFIED BY TODD C. WILSON FOR THE ROAD RUNNER NT LOGIN SERVICE.
// HOWEVER, THESE MODIFICATIONS ARE BROADER IN SCOPE AND USAGE AND CAN BE USED
// IN OTHER PROJECTS WITH NO CHANGES.
// MODIFIED LINES FLAGGED/BRACKETED BY "//!! TCW MOD"
//
/////////////////////////////////////////////////////////////////////////////
// last revised: $Date: 11.05.98 21:09 $, $Revision: 3 $
/////////////////////////////////////////////////////////////////////////////
// Acknoledgements:
// o Thanks to Victor Vogelpoel (VictorV@Telic.nl) for his bug-fixes
// and enhancements.
// o Thanks to Todd C. Wilson (todd@mediatec.com) for the
// "service" on Win95
//
// Changes:
// 04/30/98
// o Added two more switches to handle command line arguments:
// -e will force a running service to stop (corresponding
// method in this class: virtual BOOL EndService();) and
// -s will force the service to start (method:
// virtual BOOL StartupService())
//
// 02/05/98
// o Added the methods "RegisterApplicationLog()" and
// "DeregisterApplicationLog()" (both virtual). The first one will be
// called from "InstallService()" and creates some registry-entries
// for a better event-log. The second one removes these entries when
// the service will uninstall (see "RemoveService()")
// o The service now obtains the security identifier of the current user
// and uses this SID for event-logging.
// o The memory allocated by "CommandLineToArgvW()" will now release
// (UNICODE version only)
// o The service now uses a simple message catalogue for a nicer
// event logging
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <crtdbg.h>
#include <io.h> //!! TCW MOD
#include <fcntl.h> //!! TCW MOD
#include <VersionHelpers.h>
#include "NTService.h"
#include "NTServiceEventLogMsg.h"
#ifndef RSP_SIMPLE_SERVICE
#define RSP_SIMPLE_SERVICE 1
#endif
#ifndef RSP_UNREGISTER_SERVICE
#define RSP_UNREGISTER_SERVICE 0
#endif
BOOL CNTService::m_bInstance = FALSE;
static CNTService * gpTheService = 0; // the one and only instance
CNTService * AfxGetService() { return gpTheService; }
static LPCTSTR gszAppRegKey = TEXT("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\");
static LPCTSTR gszWin95ServKey = TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\RunServices"); //!! TCW MOD
/////////////////////////////////////////////////////////////////////////////
// class CNTService -- construction/destruction
CNTService::CNTService(const CString& lpServiceName, const CString& lpDisplayName)
: m_lpServiceName(lpServiceName)
, m_lpDisplayName(lpDisplayName ? lpDisplayName : lpServiceName)
, m_dwCheckPoint(0)
, m_dwErr(0)
, m_bDebug(FALSE)
, m_sshStatusHandle(0)
, m_dwControlsAccepted(SERVICE_ACCEPT_STOP)
, m_pUserSID(0)
, m_fConsoleReady(FALSE)
// parameters to the "CreateService()" function:
, m_dwDesiredAccess(SERVICE_ALL_ACCESS)
, m_dwServiceType(SERVICE_WIN32_OWN_PROCESS)
, m_dwStartType(SERVICE_AUTO_START)
, m_dwErrorControl(SERVICE_ERROR_NORMAL)
, m_pszLoadOrderGroup(L"")
, m_dwTagID(0)
, m_pszDependencies(L"")
, m_pszStartName(L"")
, m_pszPassword(L"")
{
_ASSERTE(!m_bInstance);
m_bWinNT = IsWindows10OrGreater();
m_bInstance = TRUE;
gpTheService = this;
// SERVICE_STATUS members that rarely change
m_ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
m_ssStatus.dwServiceSpecificExitCode = 0;
if (m_bWinNT) {
/////////////////////////////////////////////////////////////////////////
// Providing a SID (security identifier) was contributed by Victor
// Vogelpoel (VictorV@Telic.nl).
// The code from Victor was slightly modified.
// Get security information of current user
BYTE security_identifier_buffer[4096];
DWORD dwSizeSecurityIdBuffer = sizeof(security_identifier_buffer);
PSID user_security_identifier = NULL;
TCHAR sUserName[256];
DWORD dwSizeUserName = 255;
TCHAR sDomainName[256];
DWORD dwSizeDomainName = 255;
SID_NAME_USE sidTypeSecurityId;
::ZeroMemory(sUserName, sizeof(sUserName));
::ZeroMemory(sDomainName, sizeof(sDomainName));
::ZeroMemory(security_identifier_buffer, dwSizeSecurityIdBuffer);
::GetUserName(sUserName, &dwSizeUserName);
if (::LookupAccountName(
0,
sUserName,
&security_identifier_buffer,
&dwSizeSecurityIdBuffer,
sDomainName,
&dwSizeDomainName,
&sidTypeSecurityId
)) {
if (::IsValidSid(PSID(security_identifier_buffer))) {
DWORD dwSidLen = ::GetLengthSid(PSID(security_identifier_buffer));
m_pUserSID = PSID(new BYTE[dwSidLen]);
::CopySid(dwSidLen, m_pUserSID, security_identifier_buffer);
_ASSERTE(::EqualSid(m_pUserSID, security_identifier_buffer));
}
}
}
/////////////////////////////////////////////////////////////////////////
}
CNTService :: ~CNTService() {
_ASSERTE(m_bInstance);
delete[] LPBYTE(m_pUserSID);
m_bInstance = FALSE;
gpTheService = 0;
}
/////////////////////////////////////////////////////////////////////////////
// class CNTService -- overridables
#define NEXT_ARG ((((*Argv)[2])==TEXT('\0'))?(--Argc,*++Argv):(*Argv)+2)
BOOL CNTService::RegisterService(int argc, TCHAR ** argv) {
BOOL(CNTService::* fnc)() = &CNTService::StartDispatcher;
int Argc;
LPWSTR * Argv;
Argv = CommandLineToArgvW(GetCommandLineW(), &Argc);
LPWSTR *szArglist = Argv;
while (++Argv, --Argc) {
if (Argv[0][0] == TEXT('-')) {
switch (Argv[0][1]) {
case TEXT('i'): // install the service
fnc = &CNTService::InstallService;
break;
case TEXT('l'): // login-account (only useful with -i)
m_pszStartName = NEXT_ARG;
break;
case TEXT('p'): // password (only useful with -i)
m_pszPassword = NEXT_ARG;
break;
case TEXT('u'): // uninstall the service
fnc = &CNTService::RemoveService;
break;
case TEXT('s'): // start the service
fnc = &CNTService::StartupService;
break;
case TEXT('e'): // end the service
fnc = &CNTService::EndService;
break;
case TEXT('d'): // debug the service
case TEXT('f'): //!! TCW MOD faceless non-service (Win95) mode
::LocalFree(szArglist);
m_bDebug = TRUE;
// pass original parameters to DebugService()
return DebugService(argc, argv, (Argv[0][1] == TEXT('f'))); //!! TCW MOD faceless non-service (Win95) mode
}
}
}
::LocalFree(szArglist);
////!! TCW MOD START - if Win95, run as faceless app.
//if (fnc == &CNTService::StartDispatcher) {
// // act as if -f was passed anyways.
// _tprintf(TEXT("DebugService."));
// m_bDebug = TRUE;
// return DebugService(argc, argv, TRUE);
//}
////!! TCW MOD END - if Win95, run as faceless app.
if (fnc == &CNTService::StartupService)
{
StartDispatcher();
}
return (this->*fnc)();
}
BOOL CNTService::StartDispatcher() {
// Default implementation creates a single threaded service.
// Override this method and provide more table entries for
// a multithreaded service (one entry for each thread).
SERVICE_TABLE_ENTRY dispatchTable[] =
{
{ LPWSTR(LPCWSTR(m_lpServiceName)), (LPSERVICE_MAIN_FUNCTION)ServiceMain },
{ 0, 0 }
};
BOOL bRet = StartServiceCtrlDispatcher(dispatchTable);
if (!bRet) {
TCHAR szBuf[256];
AddToMessageLog(GetLastErrorText(szBuf, 255));
#ifdef _DEBUG
_tprintf(TEXT("StartServiceCtrlDispatcher failed! : %s\n"), szBuf);
#endif
}
_tprintf(TEXT("StartDispatcher done.\n"));
return bRet;
}
BOOL CNTService::InstallService() {
CString szPath;
SetupConsole(); //!! TCW MOD - have to show the console here for the
// diagnostic or error reason: orignal class assumed
// that we were using _main for entry (a console app).
// This particular usage is a Windows app (no console),
// so we need to create it. Using SetupConsole with _main
// is ok - does nothing, since you only get one console.
szPath.Preallocate(MAX_PATH);
if (GetModuleFileName(0, szPath.LockBuffer(), MAX_PATH) == 0) {
TCHAR szErr[256];
_tprintf(TEXT("Unable to install %s - %s\n"), LPCWSTR(m_lpDisplayName), GetLastErrorText(szErr, 256));
return FALSE;
}
szPath.UnlockBuffer();
BOOL bRet = FALSE;
{
// Real NT services go here.
SC_HANDLE schSCManager = OpenSCManager(
NULL, // machine (NULL == local)
NULL, // database (NULL == default)
SC_MANAGER_ALL_ACCESS // access required
);
if (schSCManager) {
SC_HANDLE schService = CreateService(
schSCManager,
m_lpServiceName,
m_lpDisplayName,
m_dwDesiredAccess,
m_dwServiceType,
m_dwStartType,
m_dwErrorControl,
szPath,
NULL,
((m_dwServiceType == SERVICE_KERNEL_DRIVER ||
m_dwServiceType == SERVICE_FILE_SYSTEM_DRIVER) &&
(m_dwStartType == SERVICE_BOOT_START ||
m_dwStartType == SERVICE_SYSTEM_START)) ?
&m_dwTagID : NULL,
NULL, //m_pszDependencies,
NULL, //m_pszStartName,
NULL //m_pszPassword
);
if (schService) {
_tprintf(TEXT("%s installed.\n"), LPCWSTR(m_lpDisplayName));
CloseServiceHandle(schService);
bRet = TRUE;
}
else {
TCHAR szErr[256];
_tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText(szErr, 256));
}
CloseServiceHandle(schSCManager);
}
else {
TCHAR szErr[256];
_tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr, 256));
}
if (bRet) {
// installation succeeded. Now register the message file
RegisterApplicationLog(
szPath, // the path to the application itself
EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE // supported types
);
AddToMessageLog(TEXT("Service installed"), EVENTLOG_INFORMATION_TYPE);
}
} //!! TCW MOD
return bRet;
}
BOOL CNTService::RemoveService() {
BOOL bRet = FALSE;
SetupConsole(); //!! TCW MOD - have to show the console here for the
// diagnostic or error reason: orignal class assumed
// that we were using _main for entry (a console app).
// This particular usage is a Windows app (no console),
// so we need to create it. Using SetupConsole with _main
// is ok - does nothing, since you only get one console.
if (OsIsWin95()) { //!! TCW MOD - code added to install as Win95 service
HKEY hKey = 0;
LONG lRet = ERROR_SUCCESS;
if (::RegCreateKey(HKEY_LOCAL_MACHINE, gszWin95ServKey, &hKey) == ERROR_SUCCESS) {
lRet = ::RegDeleteValue(hKey, m_lpServiceName);
::RegCloseKey(hKey);
bRet = TRUE;
}
}
else {
// Real NT services go here.
SC_HANDLE schSCManager = OpenSCManager(
0, // machine (NULL == local)
0, // database (NULL == default)
SC_MANAGER_ALL_ACCESS // access required
);
if (schSCManager) {
SC_HANDLE schService = OpenService(
schSCManager,
m_lpServiceName,
SERVICE_ALL_ACCESS
);
if (schService) {
// try to stop the service
if (ControlService(schService, SERVICE_CONTROL_STOP, &m_ssStatus)) {
_tprintf(TEXT("Stopping %s.\n"), LPCWSTR(m_lpDisplayName));
Sleep(1000);
while (QueryServiceStatus(schService, &m_ssStatus)) {
if (m_ssStatus.dwCurrentState == SERVICE_STOP_PENDING) {
_tprintf(TEXT("."));
Sleep(1000);
}
else
break;
}
if (m_ssStatus.dwCurrentState == SERVICE_STOPPED)
_tprintf(TEXT("\n%s stopped.\n"), LPCWSTR(m_lpDisplayName));
else
_tprintf(TEXT("\n%s failed to stop.\n"), LPCWSTR(m_lpDisplayName));
}
// now remove the service
if (DeleteService(schService)) {
_tprintf(TEXT("%s removed.\n"), LPCWSTR(m_lpDisplayName));
bRet = TRUE;
}
else {
TCHAR szErr[256];
_tprintf(TEXT("DeleteService failed - %s\n"), GetLastErrorText(szErr, 256));
}
CloseServiceHandle(schService);
}
else {
TCHAR szErr[256];
_tprintf(TEXT("OpenService failed - %s\n"), GetLastErrorText(szErr, 256));
}
CloseServiceHandle(schSCManager);
}
else {
TCHAR szErr[256];
_tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr, 256));
}
if (bRet)
DeregisterApplicationLog();
}
return bRet;
}
BOOL CNTService::EndService() {
BOOL bRet = FALSE;
SC_HANDLE schSCManager = ::OpenSCManager(
0, // machine (NULL == local)
0, // database (NULL == default)
SC_MANAGER_ALL_ACCESS // access required
);
if (schSCManager) {
SC_HANDLE schService = ::OpenService(
schSCManager,
m_lpServiceName,
SERVICE_ALL_ACCESS
);
if (schService) {
// try to stop the service
if (::ControlService(schService, SERVICE_CONTROL_STOP, &m_ssStatus)) {
_tprintf(TEXT("Stopping %s.\n"), LPCWSTR(m_lpDisplayName));
::Sleep(1000);
while (::QueryServiceStatus(schService, &m_ssStatus)) {
if (m_ssStatus.dwCurrentState == SERVICE_STOP_PENDING) {
_tprintf(TEXT("."));
::Sleep(1000);
}
else
break;
}
if (m_ssStatus.dwCurrentState == SERVICE_STOPPED)
bRet = TRUE, _tprintf(TEXT("\n%s stopped.\n"), LPCWSTR(m_lpDisplayName));
else
_tprintf(TEXT("\n%s failed to stop.\n"), LPCWSTR(m_lpDisplayName));
}
::CloseServiceHandle(schService);
}
else {
TCHAR szErr[256];
_tprintf(TEXT("OpenService failed - %s\n"), GetLastErrorText(szErr, 256));
}
::CloseServiceHandle(schSCManager);
}
else {
TCHAR szErr[256];
_tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr, 256));
}
return bRet;
}
BOOL CNTService::StartupService() {
BOOL bRet = FALSE;
DWORD dwBytesNeeded;
SC_HANDLE schSCManager = ::OpenSCManager(
0, // machine (NULL == local)
0, // database (NULL == default)
SC_MANAGER_ALL_ACCESS // access required
);
if (schSCManager) {
SC_HANDLE schService = ::OpenService(
schSCManager,
m_lpServiceName,
SERVICE_ALL_ACCESS
);
if (schService) {
// try to start the service
_tprintf(TEXT("Starting up %s.\n"), LPCWSTR(m_lpDisplayName));
if (StartService(schService, 0, NULL)) {
Sleep(100);
while (::QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&m_ssStatus, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) {
if (m_ssStatus.dwCurrentState == SERVICE_START_PENDING) {
_tprintf(TEXT("."));
Sleep(100);
}
else
break;
}
if (m_ssStatus.dwCurrentState == SERVICE_RUNNING)
bRet = TRUE, _tprintf(TEXT("\n%s started.\n"), LPCWSTR(m_lpDisplayName));
else
_tprintf(TEXT("\n%s failed to start.\n"), LPCWSTR(m_lpDisplayName));
}
else {
// StartService failed
TCHAR szErr[256];
_tprintf(TEXT("\n%s failed to start: %s\n"), LPCWSTR(m_lpDisplayName), GetLastErrorText(szErr, 256));
}
::CloseServiceHandle(schService);
}
else {
TCHAR szErr[256];
_tprintf(TEXT("OpenService failed - %s\n"), GetLastErrorText(szErr, 256));
}
::CloseServiceHandle(schSCManager);
}
else {
TCHAR szErr[256];
_tprintf(TEXT("OpenSCManager failed - %s\n"), GetLastErrorText(szErr, 256));
}
return bRet;
}
////////////////////////////////////////////////////////////////////////////
//!! TCW MOD - faceless window procedure for usage within Win95 (mostly),
// but can be invoked under NT by using -f
LRESULT CALLBACK _FacelessWndProc_(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
if (uMsg == WM_QUERYENDSESSION || uMsg == WM_ENDSESSION || uMsg == WM_QUIT) {
if (lParam == NULL || uMsg == WM_QUIT) {
DestroyWindow(hwnd); // kill me
if (AfxGetService() != NULL)
AfxGetService()->Stop(); // stop me.
return TRUE;
}
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
////////////////////////////////////////////////////////////////////////////
BOOL CNTService::DebugService(int argc, TCHAR ** argv, BOOL faceless) {
int dwArgc;
LPWSTR *lpszArgv;
lpszArgv = CommandLineToArgvW(GetCommandLineW(), &(dwArgc));
if (!faceless) { //!! TCW MOD - no faceless, so give it a face.
SetupConsole(); //!! TCW MOD - make the console for debugging
_tprintf(TEXT("Debugging %s.\n"), LPCWSTR(m_lpDisplayName));
SetConsoleCtrlHandler(ControlHandler, TRUE);
}
//!! TCW MOD START - if Win95, register server
typedef DWORD(WINAPI *fp_RegServProc)(DWORD dwProcessId, DWORD dwType);
fp_RegServProc fncptr = NULL;
if (faceless /*&& OsIsWin95()*/) {
WNDCLASS wndclass;
memset(&wndclass, 0, sizeof(WNDCLASS));
wndclass.lpfnWndProc = _FacelessWndProc_;
wndclass.hInstance = HINSTANCE(::GetModuleHandle(0));
wndclass.lpszClassName = TEXT("RRL__FacelessWndProc_");
ATOM atom = ::RegisterClass(&wndclass);
HWND hwnd = ::CreateWindow(wndclass.lpszClassName, TEXT(""), 0, 0, 0, 0, 0, 0, 0, wndclass.hInstance, 0);
HMODULE hModule = ::GetModuleHandle(TEXT("kernel32.dll"));
// punch F1 on "RegisterServiceProcess" for what it does and when to use it.
fncptr = (fp_RegServProc)::GetProcAddress(hModule, "RegisterServiceProcess");
if (fncptr != NULL)
(*fncptr)(0, RSP_SIMPLE_SERVICE);
}
//!! TCW MOD END - if Win95, register server
Run(dwArgc, lpszArgv);
#ifdef UNICODE
::GlobalFree((HGLOBAL)lpszArgv);
#endif
if (fncptr != NULL) //!! TCW MOD - if it's there, remove it: our run is over
(*fncptr)(0, RSP_UNREGISTER_SERVICE);
return TRUE;
}
void CNTService::Pause() {
}
void CNTService::Continue() {
}
void CNTService::Shutdown() {
}
/////////////////////////////////////////////////////////////////////////////
// class CNTService -- default handlers
void WINAPI CNTService::ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv) {
_ASSERTE(gpTheService != 0);
_tprintf(TEXT("ServiceMain %s.\n"), LPCWSTR(lpszArgv));
// register our service control handler:
gpTheService->m_sshStatusHandle = RegisterServiceCtrlHandler(
LPCWSTR(gpTheService->m_lpServiceName),
CNTService::ServiceCtrl
);
if (gpTheService->m_sshStatusHandle)
// report the status to the service control manager.
if (gpTheService->ReportStatus(SERVICE_START_PENDING)) {
gpTheService->Run(dwArgc, lpszArgv);
}
// try to report the stopped status to the service control manager.
if (gpTheService->m_sshStatusHandle)
gpTheService->ReportStatus(SERVICE_STOPPED);
}
void WINAPI CNTService::ServiceCtrl(DWORD dwCtrlCode) {
_ASSERTE(gpTheService != 0);
_tprintf(TEXT("ServiceCtrl %u.\n"), dwCtrlCode);
// Handle the requested control code.
switch (dwCtrlCode) {
case SERVICE_CONTROL_STOP:
// Stop the service.
gpTheService->m_ssStatus.dwCurrentState = SERVICE_STOP_PENDING;
gpTheService->Stop();
break;
case SERVICE_CONTROL_PAUSE:
gpTheService->m_ssStatus.dwCurrentState = SERVICE_PAUSE_PENDING;
gpTheService->Pause();
break;
case SERVICE_CONTROL_CONTINUE:
gpTheService->m_ssStatus.dwCurrentState = SERVICE_CONTINUE_PENDING;
gpTheService->Continue();
break;
case SERVICE_CONTROL_SHUTDOWN:
gpTheService->Shutdown();
break;
case SERVICE_CONTROL_INTERROGATE:
// Update the service status.
gpTheService->ReportStatus(gpTheService->m_ssStatus.dwCurrentState);
break;
default:
// invalid control code
break;
}
}
BOOL WINAPI CNTService::ControlHandler(DWORD dwCtrlType) {
_ASSERTE(gpTheService != 0);
switch (dwCtrlType) {
case CTRL_BREAK_EVENT: // use Ctrl+C or Ctrl+Break to simulate
case CTRL_C_EVENT: // SERVICE_CONTROL_STOP in debug mode
_tprintf(TEXT("Stopping %s.\n"), LPCWSTR(gpTheService->m_lpDisplayName));
gpTheService->Stop();
return TRUE;
}
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// class CNTService -- helpers
//!! TCW MOD - added DWORD dwErrExit for error exit value. Defaults to zero
BOOL CNTService::ReportStatus(
DWORD dwCurrentState,
DWORD dwWaitHint,
DWORD dwErrExit) {
BOOL fResult = TRUE;
if (!m_bDebug) { // when debugging we don't report to the SCM
if (dwCurrentState == SERVICE_START_PENDING)
m_ssStatus.dwControlsAccepted = 0;
else
m_ssStatus.dwControlsAccepted = m_dwControlsAccepted;
m_ssStatus.dwCurrentState = dwCurrentState;
m_ssStatus.dwWin32ExitCode = NO_ERROR;
m_ssStatus.dwWaitHint = dwWaitHint;
//!! TCW MOD START - added code to support error exiting
m_ssStatus.dwServiceSpecificExitCode = dwErrExit;
if (dwErrExit != 0)
m_ssStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
//!! TCW MOD END - added code to support error exiting
if (dwCurrentState == SERVICE_RUNNING ||
dwCurrentState == SERVICE_STOPPED)
m_ssStatus.dwCheckPoint = 0;
else
m_ssStatus.dwCheckPoint = ++m_dwCheckPoint;
// Report the status of the service to the service control manager.
if (!(fResult = SetServiceStatus(m_sshStatusHandle, &m_ssStatus))) {
AddToMessageLog(TEXT("SetServiceStatus() failed"));
}
}
return fResult;
}
void CNTService::AddToMessageLog(const CString& lpszMsg, WORD wEventType, DWORD dwEventID) {
m_dwErr = GetLastError();
// use default message-IDs
if (dwEventID == DWORD(-1)) {
switch (wEventType) {
case EVENTLOG_ERROR_TYPE:
dwEventID = MSG_ERROR_1;
break;
case EVENTLOG_WARNING_TYPE:
dwEventID = MSG_WARNING_1;
break;
case EVENTLOG_INFORMATION_TYPE:
dwEventID = MSG_INFO_1;
break;
case EVENTLOG_AUDIT_SUCCESS:
dwEventID = MSG_INFO_1;
break;
case EVENTLOG_AUDIT_FAILURE:
dwEventID = MSG_INFO_1;
break;
default:
dwEventID = MSG_INFO_1;
break;
}
}
// Use event logging to log the error.
HANDLE hEventSource = RegisterEventSource(0, m_lpServiceName);
if (hEventSource != 0) {
LPCTSTR lpszMessage = lpszMsg;
ReportEvent(
hEventSource, // handle of event source
wEventType, // event type
0, // event category
dwEventID, // event ID
m_pUserSID, // current user's SID
1, // strings in lpszStrings
0, // no bytes of raw data
&lpszMessage, // array of error strings
0 // no raw data
);
::DeregisterEventSource(hEventSource);
}
}
LPTSTR CNTService::GetLastErrorText(LPTSTR lpszBuf, DWORD dwSize) {
LPTSTR lpszTemp = 0;
DWORD dwRet = ::FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
0,
GetLastError(),
LANG_NEUTRAL,
(LPTSTR)&lpszTemp,
0,
0
);
if (!dwRet || (dwSize < dwRet + 14))
lpszBuf[0] = TEXT('\0');
else {
lpszTemp[_tcsclen(lpszTemp) - 2] = TEXT('\0'); //remove cr/nl characters
wcscpy_s(lpszBuf, dwSize, lpszTemp);
}
if (lpszTemp)
LocalFree(HLOCAL(lpszTemp));
return lpszBuf;
}
/////////////////////////////////////////////////////////////////////////////
// class CNTService -- implementation
void CNTService::RegisterApplicationLog(CString& lpszFileName, DWORD dwTypes) {
TCHAR szKey[256];
wcscpy_s(szKey, 255, gszAppRegKey);
wcscat_s(szKey, 255, m_lpServiceName);
HKEY hKey = 0;
LONG lRet = ERROR_SUCCESS;
lpszFileName.Preallocate(MAX_PATH);
// Create a key for that application and insert values for
// "EventMessageFile" and "TypesSupported"
if (::RegCreateKey(HKEY_LOCAL_MACHINE, szKey, &hKey) == ERROR_SUCCESS) {
lRet = ::RegSetValueEx(
hKey, // handle of key to set value for
TEXT("EventMessageFile"), // address of value to set
0, // reserved
REG_EXPAND_SZ, // flag for value type
(const BYTE *)lpszFileName.LockBuffer(), // address of value data
MAX_PATH // size of value data
);
lpszFileName.UnlockBuffer();
// Set the supported types flags.
lRet = ::RegSetValueEx(
hKey, // handle of key to set value for
TEXT("TypesSupported"), // address of value to set
0, // reserved
REG_DWORD, // flag for value type
(CONST BYTE*)&dwTypes, // address of value data
sizeof(DWORD) // size of value data
);
::RegCloseKey(hKey);
}
// Add the service to the "Sources" value
lRet = ::RegOpenKeyEx(
HKEY_LOCAL_MACHINE, // handle of open key
gszAppRegKey, // address of name of subkey to open
0, // reserved
KEY_ALL_ACCESS, // security access mask
&hKey // address of handle of open key
);
if (lRet == ERROR_SUCCESS) {
DWORD dwSize;
// retrieve the size of the needed value
lRet = ::RegQueryValueEx(
hKey, // handle of key to query
TEXT("Sources"),// address of name of value to query
0, // reserved
0, // address of buffer for value type
0, // address of data buffer
&dwSize // address of data buffer size
);
if (lRet == ERROR_SUCCESS) {
DWORD dwType;
DWORD dwNewSize = DWORD(dwSize + _tcslen(m_lpServiceName) + 1);
LPBYTE Buffer = LPBYTE(::GlobalAlloc(GPTR, dwNewSize));
lRet = ::RegQueryValueEx(
hKey, // handle of key to query
TEXT("Sources"),// address of name of value to query
0, // reserved
&dwType, // address of buffer for value type
Buffer, // address of data buffer
&dwSize // address of data buffer size
);
if (lRet == ERROR_SUCCESS) {
_ASSERTE(dwType == REG_MULTI_SZ);
// check whether this service is already a known source
register LPTSTR p = LPTSTR(Buffer);
for (; *p; p += _tcslen(p) + 1) {
if (_tcscmp(p, m_lpServiceName) == 0)
break;
}
if (!* p) {
// We're standing at the end of the stringarray
// and the service does still not exist in the "Sources".
// Now insert it at this point.
// Note that we have already enough memory allocated
// (see GlobalAlloc() above). We also don't need to append
// an additional '\0'. This is done in GlobalAlloc() above
// too.
wcscpy_s(p, dwNewSize, m_lpServiceName);
// OK - now store the modified value back into the
// registry.
lRet = ::RegSetValueEx(
hKey, // handle of key to set value for
TEXT("Sources"),// address of value to set
0, // reserved
dwType, // flag for value type
Buffer, // address of value data
dwNewSize // size of value data
);
}
}
::GlobalFree(HGLOBAL(Buffer));
}
::RegCloseKey(hKey);
}
}
void CNTService::DeregisterApplicationLog() {
TCHAR szKey[256];
wcscpy_s(szKey, 255, gszAppRegKey);
wcscat_s(szKey, 255, m_lpServiceName);
HKEY hKey = 0;
LONG lRet = ERROR_SUCCESS;
lRet = ::RegDeleteKey(HKEY_LOCAL_MACHINE, szKey);
// now we have to delete the application from the "Sources" value too.
lRet = ::RegOpenKeyEx(
HKEY_LOCAL_MACHINE, // handle of open key
gszAppRegKey, // address of name of subkey to open
0, // reserved
KEY_ALL_ACCESS, // security access mask
&hKey // address of handle of open key
);
if (lRet == ERROR_SUCCESS) {
DWORD dwSize;
// retrieve the size of the needed value
lRet = ::RegQueryValueEx(
hKey, // handle of key to query
TEXT("Sources"),// address of name of value to query
0, // reserved
0, // address of buffer for value type
0, // address of data buffer
&dwSize // address of data buffer size
);
if (lRet == ERROR_SUCCESS) {
DWORD dwType;
LPBYTE Buffer = LPBYTE(::GlobalAlloc(GPTR, dwSize));
LPBYTE NewBuffer = LPBYTE(::GlobalAlloc(GPTR, dwSize));
lRet = ::RegQueryValueEx(
hKey, // handle of key to query
TEXT("Sources"),// address of name of value to query
0, // reserved
&dwType, // address of buffer for value type
Buffer, // address of data buffer
&dwSize // address of data buffer size
);
if (lRet == ERROR_SUCCESS) {
_ASSERTE(dwType == REG_MULTI_SZ);
// check whether this service is already a known source
register LPTSTR p = LPTSTR(Buffer);
register LPTSTR pNew = LPTSTR(NewBuffer);
BOOL bNeedSave = FALSE; // assume the value is already correct
for (; *p; p += _tcslen(p) + 1, pNew += _tcslen(pNew) + 1) {
// except ourself: copy the source string into the destination
if (_tcscmp(p, m_lpServiceName) != 0)
wcscpy_s(pNew, dwSize, p);
else {