forked from vjanelle/nprobe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.c
1138 lines (916 loc) · 30.4 KB
/
service.c
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
#include "nprobe.h"
#include <windows.h>
#include <winsock2.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <stdarg.h>
#include <tchar.h>
char thisIsAservice;
/*
See also:
http://www.muukka.net/programming/service.html
http://www.mailbag.com/users/pengel/index.html
*/
/* *************************************************************
Windown NT/2K Service Registration Routines
Copyright 2001 by Bill Giel/KC Multimedia and Design Group, Inc.
************************************************************* */
#ifdef __cplusplus
extern "C" {
#endif
//
// FUNCTION: convertArgStringToArgList()
//
// PURPOSE: Return an array of strings containing all arguments that
// are parsed from a tab-delimited argument string.
//
// PARAMETERS:
// args - The string array address to be allocated and receive the data
// len - pointer to an int that will contain the returned array length
// argstring - string containing arguments to be parsed.
//
// RETURN VALUE:
// String array address containing the filtered arguments
// NULL on failure
//
LPTSTR* convertArgStringToArgList(LPTSTR *args, PDWORD pdwLen, LPTSTR lpszArgstring);
//
// FUNCTION: convertArgListToArgString()
//
// PURPOSE: Create a single tab-delimited string of arguments from
// an argument list
//
// PARAMETERS:
// target - pointer to the string to be allocated and created
// start - zero-based offest into the list to the first arg value used to
// build the list.
// argc - length of the argument list
// argv - array of strings, the argument list.
//
// RETURN VALUE:
// Character pointer to the target string.
// NULL on failure
//
LPTSTR convertArgListToArgString(LPTSTR lpszTarget, DWORD dwStart, DWORD dwArgc, LPTSTR *lpszArgv);
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
extern "C" {
#endif
//
// FUNCTION: getStringValue()
//
// PURPOSE: Fetches a REG_SZ or REG_EXPAND_SZ string value
// from a specified registry key
//
// PARAMETERS:
// lpVal - a string buffer for the desired value
// lpcbLen - pointer to LONG value with buffer length
// hkRoot - the primary root key, e.g. HKEY_LOCAL_MACHINE
// lpszPath - the registry path to the subkey containing th desired value
// lpszValue - the name of the desired value
//
// RETURN VALUE:
// 0 on success, 1 on failure
//
int getStringValue(LPBYTE lpVal, LPDWORD lpcbLen, HKEY hkRoot, LPCTSTR lpszPath, LPTSTR lpszValue);
//
// FUNCTION: setStringValue()
//
// PURPOSE: Assigns a REG_SZ value to a
// specified registry key
//
// PARAMETERS:
// lpVal - Constant byte array containing the value
// cbLen - data length
// hkRoot - the primary root key, e.g. HKEY_LOCAL_MACHINE
// lpszPath - the registry path to the subkey containing th desired value
// lpszValue - the name of the desired value
//
// RETURN VALUE:
// 0 on success, 1 on failure
//
int setStringValue(CONST BYTE *lpVal, DWORD cbLen, HKEY hkRoot, LPCTSTR lpszPath, LPCTSTR lpszValue);
//
// FUNCTION: makeNewKey()
//
// PURPOSE: Creates a new key at the specified path
//
// PARAMETERS:
// hkRoot - the primary root key, e.g. HKEY_LOCAL_MACHINE
// lpszPath - the registry path to the new subkey
//
// RETURN VALUE:
// 0 on success, 1 on failure
//
int makeNewKey(HKEY hkRoot, LPCTSTR lpszPath);
int setDwordValue(DWORD data, HKEY hkRoot, LPCTSTR lpszPath, LPCTSTR lpszValue);
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
extern "C" {
#endif
// =========================================================
// TO DO: change as needed for specific Java app and service
// =========================================================
// internal name of the service
#define SZSERVICENAME "nProbe"
// displayed name of the service
#define SZSERVICEDISPLAYNAME "nProbe for Win32"
// Service TYPE Permissable values:
// SERVICE_AUTO_START
// SERVICE_DEMAND_START
// SERVICE_DISABLED
#define SERVICESTARTTYPE SERVICE_AUTO_START
// =========================================================
// You should not need any changes below this line
// =========================================================
// Value name for app parameters
#define SZAPPPARAMS "AppParameters"
// list of service dependencies - "dep1\0dep2\0\0"
// If none, use ""
#define SZDEPENDENCIES ""
//
// FUNCTION: getConsoleMode()
//
// PURPOSE: Is the app running as a service or a console app.
//
// RETURN VALUE:
// TRUE - if running as a console application
// FALSE - if running as a service
//
BOOL getConsoleMode();
//
// FUNCTION: ReportStatusToSCMgr()
//
// PURPOSE: Sets the current status of the service and
// reports it to the Service Control Manager
//
// PARAMETERS:
// dwCurrentState - the state of the service
// dwWin32ExitCode - error code to report
// dwWaitHint - worst case estimate to next checkpoint
//
// RETURN VALUE:
// TRUE - success
// FALSE - failure
//
BOOL ReportStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint);
//
// FUNCTION: AddToMessageLog(LPTSTR lpszMsg)
//
// PURPOSE: Allows any thread to log an error message
//
// PARAMETERS:
// lpszMsg - text for message
//
// RETURN VALUE:
// none
//
void AddToMessageLog(LPTSTR lpszMsg);
VOID ServiceStart(DWORD dwArgc, LPTSTR *lpszArgv);
VOID ServiceStop();
#ifdef __cplusplus
}
#endif
//
// Values are 32 bit values layed out as follows:
//
// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +---+-+-+-----------------------+-------------------------------+
// |Sev|C|R| Facility | Code |
// +---+-+-+-----------------------+-------------------------------+
//
// where
//
// Sev - is the severity code
//
// 00 - Success
// 01 - Informational
// 10 - Warning
// 11 - Error
//
// C - is the Customer code flag
//
// R - is a reserved bit
//
// Facility - is the facility code
//
// Code - is the facility's status code
//
//
// Define the facility codes
//
//
// Define the severity codes
//
//
// MessageId: EVENT_GENERIC_INFORMATION
//
// MessageText:
//
// %1
//
#define EVENT_GENERIC_INFORMATION 0x40000001L
//global variables
SERVICE_STATUS ssStatus;
SERVICE_STATUS_HANDLE sshStatusHandle;
DWORD dwErr = 0;
BOOL bConsole = FALSE;
TCHAR szErr[256];
#define SZFAILURE "StartServiceControlDispatcher failed!"
#define SZSCMGRFAILURE "OpenSCManager failed - %s\n"
int getStringValue(LPBYTE lpVal, LPDWORD lpcbLen, HKEY hkRoot, LPCTSTR lpszPath, LPTSTR lpszValue)
{
LONG result;
HKEY hKey;
DWORD dwType;
result = RegOpenKeyEx(
hkRoot,
lpszPath,
(DWORD)0,
KEY_EXECUTE | KEY_QUERY_VALUE,
(PHKEY)&hKey);
if(result != ERROR_SUCCESS){
return 1;
}
result = RegQueryValueEx(
hKey,
lpszValue,
NULL,
(LPDWORD)&dwType,
lpVal,
lpcbLen);
RegCloseKey(hKey);
return !(result == ERROR_SUCCESS &&
(dwType == REG_SZ || dwType == REG_EXPAND_SZ));
}
int setStringValue(CONST BYTE *lpVal, DWORD cbLen, HKEY hkRoot, LPCTSTR lpszPath, LPCTSTR lpszValue)
{
LONG result;
HKEY hKey;
DWORD dwType = REG_SZ;
result = RegOpenKeyEx(
hkRoot,
lpszPath,
(DWORD)0,
KEY_WRITE,
(PHKEY)&hKey);
if(result != ERROR_SUCCESS){
return 1;
}
result = RegSetValueEx(
hKey,
lpszValue,
(DWORD)0,
dwType,
lpVal,
cbLen);
RegCloseKey(hKey);
return !(result == ERROR_SUCCESS);
}
int makeNewKey(HKEY hkRoot, LPCTSTR lpszPath)
{
char *classname = "LocalSystem";
LONG result;
HKEY hKey;
DWORD disposition;
result = RegCreateKeyEx(
hkRoot,
lpszPath,
(DWORD)0,
classname,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
(PHKEY)&hKey,
(LPDWORD) &disposition);
if(result != ERROR_SUCCESS){
return 1;
}
RegCloseKey(hKey);
return !(result == ERROR_SUCCESS);
}
int setDwordValue(DWORD data, HKEY hkRoot, LPCTSTR lpszPath, LPCTSTR lpszValue)
{
LONG result;
HKEY hKey;
result = RegOpenKeyEx(hkRoot, lpszPath, (DWORD) 0, KEY_WRITE, (PHKEY) & hKey);
if(result != ERROR_SUCCESS)
{
return 1;
}
result = RegSetValueEx(
hKey,
lpszValue,
0,
REG_DWORD,
(CONST BYTE*)&data,
sizeof(DWORD));
RegCloseKey(hKey);
return !(result == ERROR_SUCCESS);
}
BOOL getConsoleMode()
{
return bConsole;
}
// Create an error message from GetLastError() using the
// FormatMessage API Call...
LPTSTR GetLastErrorText( LPTSTR lpszBuf, DWORD dwSize )
{
DWORD dwRet;
LPTSTR lpszTemp = NULL;
dwRet = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ARGUMENT_ARRAY,
NULL,
GetLastError(),
LANG_NEUTRAL,
(LPTSTR)&lpszTemp,
0,
NULL);
// supplied buffer is not long enough
if (!dwRet || ((long)dwSize < (long)dwRet+14)){
lpszBuf[0] = TEXT('\0');
}
else{
lpszTemp[lstrlen(lpszTemp)-2] = TEXT('\0'); //remove cr and newline character
_stprintf( lpszBuf, TEXT("%s (0x%x)"), lpszTemp, GetLastError());
}
if (lpszTemp){
GlobalFree((HGLOBAL) lpszTemp);
}
return lpszBuf;
}
// We'll try to install the service with this function, and save any
// runtime args for the service itself as a REG_SZ value in a registry
// subkey
void installService(char *service_name, int argc, char **argv)
{
SC_HANDLE schService;
SC_HANDLE schSCManager;
TCHAR szPath[512], szDescr[256];
TCHAR szAppParameters[8192];
SERVICE_DESCRIPTION sdBuf;
char szParamKey[1025], szParamKey2[1025];
LPWSTR ptr;
#if 0
thisIsAservice = 1; bConsole = 0;
if(argc >=1) traceEvent(TRACE_ERROR, "argv[1] = %s", argv[1]);
if(argc >=2) traceEvent(TRACE_ERROR, "argv[2] = %s", argv[2]);
if (argc >= 3) traceEvent(TRACE_ERROR, "argv[3] = %s", argv[3]);
#endif
AddToMessageLog(service_name);
sprintf(szParamKey, "SYSTEM\\CurrentControlSet\\Services\\%s\\Parameters", service_name);
// Get the full path and filename of this program
if ( GetModuleFileName( NULL, szPath, 512 ) == 0 ){
_tprintf(TEXT("Unable to install %s - %s\n"), service_name, GetLastErrorText(szErr, 256));
return;
}
// Next, get a handle to the service control manager
schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if ( schSCManager ) {
schService = CreateService(schSCManager, // SCManager database
service_name, // name of service
service_name, // name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICESTARTTYPE, // start type
SERVICE_ERROR_NORMAL, // error control type
szPath, // service's binary
NULL, // no load ordering group
NULL, // no tag identifier
TEXT(SZDEPENDENCIES), // dependencies
NULL, // LocalSystem account
NULL); // no password
if (schService){
_tprintf(TEXT("%s installed.\n"), service_name);
//Create an argument string from the argument list
// J. R. Duarte: modified it to store the full command line
convertArgListToArgString((LPTSTR) szAppParameters, 0, argc, argv);
/* Modify the service description string */
if(szAppParameters != NULL) {
sdBuf.lpDescription = szAppParameters;
if( !ChangeServiceConfig2(
schService, // handle to service
SERVICE_CONFIG_DESCRIPTION, // change: description
&sdBuf) ) // value: new description
{
; /* Failed */
}
}
// Close the handle to this service object
CloseServiceHandle(schService);
/* ****************************************** */
// Set the service name. Courtesy of Yuri Francalacci <yuri@ntop.org>
sprintf(szParamKey2, "SYSTEM\\CurrentControlSet\\Services\\%s",service_name);
snprintf(szDescr, sizeof(szDescr), "nProbe v.%s - NetFlow/IPFIX Probe. http://www.ntop.org/",
version);
// Set the file value (where the message resources are located.... in this case, our runfile.)
if(0 != setStringValue((const unsigned char *)szDescr,
strlen(szDescr) + 1,HKEY_LOCAL_MACHINE, szParamKey2,TEXT("Description")))
{
_tprintf(TEXT("Unable to set service description .\n"));
}
/* ********************************************** */
//Make a registry key to support logging messages using the service name.
sprintf(szParamKey2, "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\%s", service_name);
if(0 != makeNewKey(HKEY_LOCAL_MACHINE, szParamKey2)){
_tprintf(TEXT("The EventLog subkey could not be created.\n"));
}
// Set the file value (where the message resources are located.... in this case, our runfile.)
if(0 != setStringValue((const unsigned char *) szPath,
strlen(szPath) + 1,HKEY_LOCAL_MACHINE,
szParamKey2,TEXT("EventMessageFile")))
{
_tprintf(TEXT("The Message File value could\nnot be assigned.\n"));
}
// Set the supported types flags.
if(0 != setDwordValue(EVENTLOG_INFORMATION_TYPE,HKEY_LOCAL_MACHINE, szParamKey2,TEXT("TypesSupported"))){
_tprintf(TEXT("The Types Supported value could\nnot be assigned.\n"));
}
// Try to create a subkey to hold the runtime args for the JavaVM and
// Java application
if(0 != makeNewKey(HKEY_LOCAL_MACHINE, szParamKey)){
_tprintf(TEXT("Could not create Parameters subkey.\n"));
} else {
if(NULL == szAppParameters){
_tprintf(TEXT("Could not create AppParameters string.\n"));
} else{
// Try to save the argument string under the new subkey
if(0 != setStringValue(szAppParameters, strlen(szAppParameters)+1,
HKEY_LOCAL_MACHINE, szParamKey, SZAPPPARAMS)){
_tprintf(TEXT("Could not save AppParameters value.\n"));
}
}
}
}
else{
_tprintf(TEXT("CreateService failed - %s\n"), GetLastErrorText(szErr, 256));
}
// Close the handle to the service control manager database
CloseServiceHandle(schSCManager);
}
else{
_tprintf(TEXT(SZSCMGRFAILURE), GetLastErrorText(szErr,256));
}
}
// We'll try to stop, and then remove the service using this function.
void removeService(char *service_name)
{
SC_HANDLE schService;
SC_HANDLE schSCManager;
char szParamKey2[1025];
// First, get a handle to the service control manager
schSCManager = OpenSCManager(NULL,
NULL,
SC_MANAGER_ALL_ACCESS);
if (schSCManager){
// Next get the handle to this service...
schService = OpenService(schSCManager, service_name, SERVICE_ALL_ACCESS);
if (schService){
// Now, try to stop the service by passing a STOP code thru the control manager
if (ControlService( schService, SERVICE_CONTROL_STOP, &ssStatus)){
_tprintf(TEXT("Stopping %s."), service_name);
// Wait a second...
Sleep( 1000 );
// Poll the status of the service for SERVICE_STOP_PENDING
while(QueryServiceStatus( schService, &ssStatus)){
// If the service has not stopped, wait another second
if ( ssStatus.dwCurrentState == SERVICE_STOP_PENDING ){
_tprintf(TEXT("."));
Sleep( 1000 );
}
else
break;
}
if ( ssStatus.dwCurrentState == SERVICE_STOPPED )
_tprintf(TEXT("\n%s stopped.\n"), service_name);
else
_tprintf(TEXT("\n%s failed to stop.\n"), service_name);
}
// Now try to remove the service...
if(DeleteService(schService)){
_tprintf(TEXT("%s removed.\n"), service_name);
// Delete our eventlog registry key
sprintf(szParamKey2, "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\%s", service_name);
RegDeleteKey(HKEY_LOCAL_MACHINE,szParamKey2);
}else{
_tprintf(TEXT("DeleteService failed - %s\n"), GetLastErrorText(szErr,256));
}
//Close this service object's handle to the service control manager
CloseServiceHandle(schService);
}
else{
_tprintf(TEXT("OpenService failed - %s\n"), GetLastErrorText(szErr,256));
}
// Finally, close the handle to the service control manager's database
CloseServiceHandle(schSCManager);
} else {
_tprintf(TEXT(SZSCMGRFAILURE), GetLastErrorText(szErr,256));
}
}
/* ********************************************* */
extern int nprobe_main(int argc, char *argv[]);
extern void usage (FILE * fd);
DWORD _dwArgc;
LPTSTR *_lpszArgv;
HANDLE hServerStopEvent = NULL;
void* invokenProbe(void* _szAppParameters) {
DWORD dwNewArgc, i;
LPTSTR szAppParameters = (LPTSTR)_szAppParameters;
LPTSTR *lpszNewArgv = NULL;
LPTSTR *lpszTmpArgv;
// SetConsoleCtrlHandler(logoffHandler, TRUE);
// J. R. Duarte: convert the string argument back to argc & argv
lpszNewArgv = convertArgStringToArgList(lpszNewArgv, &dwNewArgc, szAppParameters);
// J. R. Duarte: to handle removing the Windows-specific command
// line option when running from the command line or as a service
if (!stricmp(lpszNewArgv[1],"/c") || !stricmp(lpszNewArgv[1],"/i") || !stricmp(lpszNewArgv[1],"/r"))
{
int displ;
lpszTmpArgv = lpszNewArgv; // make a copy of argv
if(!stricmp(lpszNewArgv[1],"/c")) displ = 1; else displ = 2;
for(i=0; i < dwNewArgc ;i++) {
if (i == 0)
lpszNewArgv[0] = lpszTmpArgv[0];
else if (i > displ)
lpszNewArgv[i - displ] = lpszTmpArgv[i];
}
dwNewArgc--;
}
/* Example: C:\ntop\nprobe\Release\nprobe.exe */
GetModuleFileName(GetModuleHandle(NULL), readOnlyGlobals.base_installation_path, MAX_PATH);
for(i = strlen(readOnlyGlobals.base_installation_path)-1; i>0; i--)
if(readOnlyGlobals.base_installation_path[i] == '\\') {
readOnlyGlobals.base_installation_path[i+1] = '\0';
break;
}
nprobe_main(dwNewArgc, lpszNewArgv);
SetEvent(hServerStopEvent); // Signal main thread that we're leaving
return(NULL);
}
// This method is called from ServiceMain() when NT starts the service
// or by runService() if run from the console.
VOID ServiceStart (DWORD dwArgc, LPTSTR *lpszArgv)
{
pthread_t nProbeThread;
TCHAR szAppParameters[8192];
// Let the service control manager know that the service is
// initializing.
if (!ReportStatus(SERVICE_START_PENDING,
NO_ERROR,
3000))
//goto cleanup;
return;
// Create a Stop Event
hServerStopEvent = CreateEvent(
NULL,
TRUE,
FALSE,
NULL);
if ( hServerStopEvent == NULL)
goto cleanup;
if(dwArgc > 0)
_dwArgc = dwArgc, _lpszArgv = lpszArgv;
else {
char *progName = SZSERVICENAME;
_dwArgc = 1, _lpszArgv = &progName;
}
if (!ReportStatus(SERVICE_RUNNING,NO_ERROR,0)){
goto cleanup;
}
// createThread(&nProbeThread, invokenProbe, NULL);
// J. R. Duarte: Create an argument string from the argument list
convertArgListToArgString((LPTSTR)szAppParameters,0, dwArgc, lpszArgv);
if(NULL == szAppParameters){
_tprintf(TEXT("Could not create AppParameters string.\n"));
}
AddToMessageLog(TEXT("About to start nProbe"));
pthread_create(&nProbeThread, NULL, invokenProbe, (void*)strdup(szAppParameters));
AddToMessageLog(TEXT("nProbe started"));
// Wait for the stop event to be signalled.
WaitForSingleObject(hServerStopEvent,INFINITE);
AddToMessageLog(TEXT("nProbe terminated"));
cleanup:
if (hServerStopEvent)
CloseHandle(hServerStopEvent);
}
/* ********************************************* */
VOID ServiceStop() {
SetEvent(hServerStopEvent);
}
/* ************************************ */
// This function permits running the application from the
// console.
void runService(int argc, char ** argv)
{
DWORD dwArgc;
LPTSTR *lpszArgv;
#ifdef UNICODE
lpszArgv = CommandLineToArgvW(GetCommandLineW(), &(dwArgc) );
#else
dwArgc = (DWORD) argc;
lpszArgv = argv;
#endif
_tprintf(TEXT("Running %s.\n"), TEXT(SZSERVICEDISPLAYNAME));
ServiceStart(dwArgc, lpszArgv);
}
/* ************************************ */
// If running as a service, use event logging to post a message
// If not, display the message on the console.
VOID AddToMessageLog(LPTSTR lpszMsg)
{
HANDLE hEventSource;
TCHAR szMsg[4096];
#ifdef UNICODE
LPCWSTR lpszStrings[1];
#else
LPCSTR lpszStrings[1];
#endif
if(!isWinNT()) {
char *msg = (char*)lpszMsg;
printf("%s", msg);
if(msg[strlen(msg)-1] != '\n')
printf("\n");
return;
}
if (!bConsole)
{
hEventSource = RegisterEventSource(NULL, TEXT(SZSERVICENAME));
_stprintf(szMsg, TEXT("%s: %s"), SZSERVICENAME, lpszMsg);
lpszStrings[0] = szMsg;
if (hEventSource != NULL) {
ReportEvent(hEventSource,
EVENTLOG_INFORMATION_TYPE,
0,
EVENT_GENERIC_INFORMATION,
NULL,
1,
0,
lpszStrings,
NULL);
DeregisterEventSource(hEventSource);
}
} else {
_tprintf(TEXT("%s\n"), lpszMsg);
}
}
/* ************************************ */
// Throughout the program, calls to SetServiceStatus are required
// which are handled by calling this function. Here, the non-constant
// members of the SERVICE_STATUS struct are assigned and SetServiceStatus
// is called with the struct. Note that we will not report to the service
// control manager if we are running as console application.
BOOL ReportStatus(DWORD dwCurrentState,
DWORD dwWin32ExitCode,
DWORD dwWaitHint)
{
static DWORD dwCheckPoint = 1;
BOOL bResult = TRUE;
if ( !bConsole )
{
if (dwCurrentState == SERVICE_START_PENDING)
ssStatus.dwControlsAccepted = 0;
else
ssStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
ssStatus.dwCurrentState = dwCurrentState;
ssStatus.dwWin32ExitCode = dwWin32ExitCode;
ssStatus.dwWaitHint = dwWaitHint;
if ( ( dwCurrentState == SERVICE_RUNNING ) ||
( dwCurrentState == SERVICE_STOPPED ) )
ssStatus.dwCheckPoint = 0;
else
ssStatus.dwCheckPoint = dwCheckPoint++;
if (!(bResult = SetServiceStatus( sshStatusHandle, &ssStatus))) {
AddToMessageLog(TEXT("SetServiceStatus"));
}
}
return bResult;
}
/* ************************************ */
// Each Win32 service must have a control handler to respond to
// control requests from the dispatcher.
VOID WINAPI controlHandler(DWORD dwCtrlCode)
{
switch(dwCtrlCode)
{
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP:
// Request to stop the service. Report SERVICE_STOP_PENDING
// to the service control manager before calling ServiceStop()
// to avoid a "Service did not respond" error.
ReportStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
ServiceStop();
return;
case SERVICE_CONTROL_INTERROGATE:
// This case MUST be processed, even though we are not
// obligated to do anything substantial in the process.
break;
default:
// Any other cases...
break;
}
// After invocation of this function, we MUST call the SetServiceStatus
// function, which is accomplished through our ReportStatus function. We
// must do this even if the current status has not changed.
ReportStatus(ssStatus.dwCurrentState, NO_ERROR, 0);
}
/* ************************************ */
// The ServiceMain function is the entry point for the service.
void WINAPI serviceMain(DWORD dwArgc, LPTSTR *lpszArgv)
{
TCHAR szAppParameters[8192];
LONG lLen = 8192;
LPTSTR *lpszNewArgv = NULL;
DWORD dwNewArgc;
UINT i;
char szParamKey[1025];
sprintf(szParamKey,"SYSTEM\\CurrentControlSet\\Services\\%s\\Parameters", lpszArgv[0]);
// Call RegisterServiceCtrlHandler immediately to register a service control
// handler function. The returned SERVICE_STATUS_HANDLE is saved with global
// scope, and used as a service id in calls to SetServiceStatus.
sshStatusHandle = RegisterServiceCtrlHandler( TEXT(SZSERVICENAME), controlHandler);
if (!sshStatusHandle)
goto finally;
// The global ssStatus SERVICE_STATUS structure contains information about the
// service, and is used throughout the program in calls made to SetStatus through
// the ReportStatus function.
ssStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
ssStatus.dwServiceSpecificExitCode = 0;
// If we could guarantee that all initialization would occur in less than one
// second, we would not have to report our status to the service control manager.
// For good measure, we will assign SERVICE_START_PENDING to the current service
// state and inform the service control manager through our ReportStatus function.
if (!ReportStatus(SERVICE_START_PENDING, NO_ERROR, 3000))
goto finally;
// When we installed this service, we probably saved a list of runtime args
// in the registry as a subkey of the key for this service. We'll try to get
// it here...
if(0 != getStringValue(szAppParameters,(LPDWORD)&lLen, HKEY_LOCAL_MACHINE, szParamKey, SZAPPPARAMS)){
dwNewArgc = 0;
lpszNewArgv = NULL;
} else {
//If we have an argument string, convert it to a list of argc/argv type...
lpszNewArgv = convertArgStringToArgList(lpszNewArgv, &dwNewArgc, szAppParameters);
}
// Do it! In ServiceStart, we'll send additional status reports to the
// service control manager, especially the SERVICE_RUNNING report once
// our JVM is initiallized and ready to be invoked.
ServiceStart(dwNewArgc, lpszNewArgv);
// Release the allocated storage used by our arg list. Java programmers
// might remember this kind of stuff.
for(i=0; i<dwNewArgc; i++){
GlobalFree((HGLOBAL)lpszNewArgv[i]);
}
if(dwNewArgc > 0)
GlobalFree((HGLOBAL)lpszNewArgv);
finally:
// Report the stopped status to the service control manager, if we have
// a valid server status handle.
if (sshStatusHandle)
(VOID)ReportStatus( SERVICE_STOPPED, dwErr, 0);
}
/* ************************************ */
void main(int argc, char **argv)
{
// The StartServiceCtrlDispatcher requires this table to specify
// the ServiceMain function to run in the calling process. The first
// member in this example is actually ignored, since we will install
// our service as a SERVICE_WIN32_OWN_PROCESS service type. The NULL
// members of the last entry are necessary to indicate the end of
// the table;
SERVICE_TABLE_ENTRY serviceTable[] =
{
{ TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)serviceMain },
{ NULL, NULL }
};
TCHAR szAppParameters[8192];
// pthread_win32_process_attach_np();
if(!isWinNT()) {
convertArgListToArgString((LPTSTR) szAppParameters,0, argc, argv);
if(NULL == szAppParameters){