-
Notifications
You must be signed in to change notification settings - Fork 11
/
service.c
644 lines (513 loc) · 13.5 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
/*
** This file is part of "zebedee"
**
** Copyright 1999 by Neil Winton. All rights reserved.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
** $Id: service.c,v 1.1.1.1 2001-04-12 18:07:12 ndwinton Exp $
**
** $Log: service.c,v $
** Revision 1.1.1.1 2001-04-12 18:07:12 ndwinton
** Imported source of Zebedee 2.2.1
**
** Revision 1.1.1.1 2001/04/12 18:07:12 ndwinton
** Imported source of Zebedee 2.2.1
**
** Revision 1.2 2000/01/08 21:35:22 nwinton
** Version 1.3.0
**
** Revision 1.1 1999/09/24 20:20:58 nwinton
** Cleanup of compiler warnings
**
** Revision 1.0 1999/09/18 21:35:06 nwinton
** Initial revision
**
*/
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
char *service_c_rcsid = "$Id: service.c,v 1.1.1.1 2001-04-12 18:07:12 ndwinton Exp $";
extern void message(unsigned short, int, char *, ...);
#define MAX_BUF_SIZE 2048
HANDLE SvcFinishEvent = NULL;
SERVICE_STATUS SvcStatus; /* Current status of service */
SERVICE_STATUS_HANDLE SvcStatusHandle;
DWORD SvcError;
HANDLE SvcThreadHandle = NULL;
char *SvcName = NULL;
DWORD (*SvcFunction)(VOID *) = NULL;
VOID *SvcArg = NULL;
DWORD svcPlatform(void);
VOID svcRun(char *name, DWORD (*function)(VOID *), VOID *arg);
VOID svcRun9X(char *name);
VOID svcRunNT(char *name);
VOID svcMain(DWORD argc, LPTSTR *argv);
VOID svcControl(DWORD ctrlCode);
BOOL svcReport(DWORD currentState, DWORD exitCode, DWORD checkPoint,
DWORD waitHint);
VOID svcStop(LPTSTR msg);
int svcInstall(char *name, char *configFile);
int svcInstall9X(char *name, char *configFile);
int svcInstallNT(char *name, char *configFile);
int svcRemove(char *name);
int svcRemove9X(char *name);
int svcRemoveNT(char *name);
DWORD
svcPlatform(void)
{
OSVERSIONINFO info;
info.dwOSVersionInfoSize = sizeof(info);
if (!GetVersionEx(&info))
{
message(0, 0, "can't get OS version info");
return 0;
}
return info.dwPlatformId;
}
VOID
svcRun(char *name, DWORD (*function)(VOID *), VOID *arg)
{
DWORD platform = svcPlatform();
SvcName = name;
SvcFunction = function;
SvcArg = arg;
switch (platform)
{
case VER_PLATFORM_WIN32_WINDOWS:
svcRun9X(name);
break;
case VER_PLATFORM_WIN32_NT:
svcRunNT(name);
break;
default:
message(0, 0, "unsupported OS platform (type %d)", platform);
break;
}
}
VOID
svcRunNT(char *name)
{
SERVICE_TABLE_ENTRY dispatchTable[] = {
{ TEXT(name), (LPSERVICE_MAIN_FUNCTION)svcMain },
{ NULL, NULL }
};
if (!StartServiceCtrlDispatcher(dispatchTable))
{
svcStop("StartServiceCtrlDispatcher failed");
}
}
VOID
svcRun9X(char *name)
{
HINSTANCE kernelDll;
DWORD (*regFn)(void *, DWORD);
/* Obtain a handle to the kernel library */
if ((kernelDll = LoadLibrary("KERNEL32.DLL")) == NULL)
{
message(0, 0, "can't get handle to kernel library");
return;
}
/* Find the address of the RegisterServiceProcess function */
regFn = (DWORD (*)(void *, DWORD))GetProcAddress(kernelDll, "RegisterServiceProcess");
if (regFn == NULL)
{
message(0, 0, "can't get the address of RegisterServiceProcess()");
return;
}
/* Register this process with the OS as a service */
if ((*regFn)(NULL, 1 /* RSP_SIMPLE_SERVICE */) == 0)
{
message(0, 0, "failed to register service process");
exit(EXIT_FAILURE);
}
/* Run the main routine */
(*SvcFunction)(SvcArg);
/* Unregister the process */
if ((*regFn)(NULL, 0 /* RSP_UNREGISTER_SERVICE */) == 0)
{
message(0, 0, "failed to unregister service process");
exit(EXIT_FAILURE);
}
/* Free the kernel library */
FreeLibrary(kernelDll);
exit(EXIT_SUCCESS);
}
/*
** svcMain
**
** This function starts the service worker thread proper. It then waits
** for the worker to terminate.
**
*/
VOID
svcMain(DWORD argc, LPTSTR *argv)
{
DWORD wait;
/* Register the control handler */
SvcStatusHandle = RegisterServiceCtrlHandler(TEXT(SvcName),
(LPHANDLER_FUNCTION)svcControl);
if (!SvcStatusHandle)
{
message(0, 0, "failed to register service control handler");
goto finish;
}
/* Initialise static service status values */
SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
SvcStatus.dwServiceSpecificExitCode = 0;
/* Report to SCM */
if (!svcReport(SERVICE_START_PENDING, /* Service state */
NO_ERROR, /* Exit code */
1, /* Checkpoint number */
5000)) /* Wait hint -- 5 secs */
{
message(0, 0, "failed to report status to SCM");
goto finish;
}
/*
** Create the "stop event" object. The arguments indicate a manually
** reset event whose initial state is unset.
*/
if ((SvcFinishEvent = CreateEvent(NULL, 1, 0, NULL)) == NULL)
{
goto finish;
}
/* Report next checkpoint to SCM */
if (!svcReport(SERVICE_START_PENDING, NO_ERROR, 2, 5000))
{
message(0, 0, "failed to report status to SCM");
goto finish;
}
/* Start the worker thread */
SvcThreadHandle = (HANDLE)CreateThread(NULL, 65536, SvcFunction, SvcArg, 0, NULL);
if (!SvcThreadHandle)
{
message(0, 0, "failed to create worker thread");
goto finish;
}
/* Report all systems GO! */
if (!svcReport(SERVICE_RUNNING, NO_ERROR, 0, 0))
{
message(0, 0, "failed to report status to SCM");
goto finish;
}
/* Wait until SvcFinishEvent is set */
wait = WaitForSingleObject(SvcFinishEvent, INFINITE);
finish:
if (SvcFinishEvent != NULL)
{
CloseHandle(SvcFinishEvent);
}
/* Report to SCM if possible */
if (SvcStatusHandle != 0)
{
svcReport(SERVICE_STOPPED, SvcError, 0, 0);
}
return;
}
/*
** svcControl
**
** Handle SCM service control requests
*/
VOID
svcControl(DWORD code)
{
DWORD state = SERVICE_RUNNING;
switch(code)
{
case SERVICE_CONTROL_PAUSE:
if (SvcStatus.dwCurrentState == SERVICE_RUNNING)
{
SuspendThread(SvcThreadHandle);
state = SERVICE_PAUSED;
}
break;
case SERVICE_CONTROL_CONTINUE:
if (SvcStatus.dwCurrentState == SERVICE_PAUSED)
{
ResumeThread(SvcThreadHandle);
state = SERVICE_RUNNING;
}
break;
case SERVICE_CONTROL_STOP:
state = SERVICE_STOP_PENDING;
svcReport(SERVICE_STOP_PENDING, NO_ERROR, 1, 5000);
SetEvent(SvcFinishEvent);
return;
case SERVICE_CONTROL_INTERROGATE:
break;
default:
break;
}
svcReport(state, NO_ERROR, 0, 0);
}
/*
** svcReport
**
** Update the SCM with the current state of the service.
*/
BOOL
svcReport(DWORD currentState, DWORD exitCode, DWORD checkPoint, DWORD waitHint)
{
BOOL result;
/* Disable control requests while starting */
if (currentState == SERVICE_START_PENDING)
{
SvcStatus.dwControlsAccepted = 0;
}
else
{
SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_PAUSE_CONTINUE;
}
SvcStatus.dwCurrentState = currentState;
SvcStatus.dwWin32ExitCode = exitCode;
SvcStatus.dwCheckPoint = checkPoint;
SvcStatus.dwWaitHint = waitHint;
/* Make the report */
if (!(result = SetServiceStatus(SvcStatusHandle, &SvcStatus)))
{
/* If there is an error then bail out */
svcStop("SetServiceStatus failed!");
}
return result;
}
/*
** svcStop
**
** Report an error and stop the service
*/
VOID
svcStop(LPTSTR msg)
{
SvcError = GetLastError();
message(0, 0, "failed in Win32 service routines: code %#0x", SvcError);
/* Signal the main routine to finish */
SetEvent(SvcFinishEvent);
}
int
svcInstall(char *name, char *configFile)
{
const char *runArg = "-Srun";
char path[MAX_BUF_SIZE];
char cmd[MAX_BUF_SIZE];
const char *flag = "-f";
const char *quote = "\"";
DWORD platform = svcPlatform();
if (configFile == NULL)
{
flag = "";
quote = "";
configFile = "";
}
/*
** Get the filename of the running executable. We need to leave
** space in the buffer for additional arguments, whitespace and
** quotes ...
*/
if (GetModuleFileName(NULL, path,
MAX_BUF_SIZE - (strlen(configFile) + 20)) == 0)
{
message(0, 0, "can't get executable path");
return EXIT_FAILURE;
}
/*
** Build the command string. If a config file was specified
** this will be of the form:
**
** "program path" -f "config file" -Srun
*/
sprintf(cmd, "\"%s\" %s %s%s%s %s", path,
flag, quote, configFile, quote, runArg);
switch (platform)
{
case VER_PLATFORM_WIN32_WINDOWS:
return svcInstall9X(name, cmd);
break;
case VER_PLATFORM_WIN32_NT:
return svcInstallNT(name, cmd);
break;
default:
message(0, 0, "unsupported OS platform (type %d)", platform);
break;
}
return EXIT_FAILURE;
}
int
svcInstallNT(char *name, char *cmd)
{
SC_HANDLE svcHandle;
SC_HANDLE scmHandle;
/* Open the local SCM database */
if ((scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) == NULL)
{
message(0, 0, "can't open SCM database");
return EXIT_FAILURE;
}
/* Now create the service entry */
svcHandle = CreateService(scmHandle, /* SCM database handle */
name, /* Name of service */
name, /* Display name */
SERVICE_ALL_ACCESS, /* Desired access */
SERVICE_WIN32_OWN_PROCESS,/* Run in own process */
SERVICE_AUTO_START, /* Start during boot */
SERVICE_ERROR_NORMAL, /* Show message but continue boot */
cmd, /* Program plus arguments */
NULL, /* No load ordering group */
NULL, /* No tag identifier */
NULL, /* No dependencies */
NULL, /* Use LocalSystem account */
NULL); /* No password */
CloseServiceHandle(scmHandle);
if (svcHandle == NULL)
{
message(0, 0, "can't create service");
return EXIT_FAILURE;
}
CloseServiceHandle(svcHandle);
message(1, 0, "%s service installed to run '%s'", name, cmd);
return EXIT_SUCCESS;
}
int
svcInstall9X(char *name, char *cmd)
{
HKEY runKey;
/* Open RunServices registry key */
if (RegCreateKey(HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows\\CurrentVersion\\RunServices",
&runKey) != ERROR_SUCCESS)
{
message(0, 0, "can't locate registry key");
return EXIT_FAILURE;
}
/* Add value for this service */
if (RegSetValueEx(runKey, name, 0, REG_SZ, cmd, strlen(cmd) + 1) != ERROR_SUCCESS)
{
RegCloseKey(runKey);
message(0, 0, "failed to add value to registry");
return EXIT_FAILURE;
}
RegCloseKey(runKey);
message(1, 0, "%s service installed to run '%s'", name, cmd);
return EXIT_SUCCESS;
}
int
svcRemove(char *name)
{
DWORD platform = svcPlatform();
switch (platform)
{
case VER_PLATFORM_WIN32_WINDOWS:
return svcRemove9X(name);
break;
case VER_PLATFORM_WIN32_NT:
return svcRemoveNT(name);
break;
default:
message(0, 0, "unsupported OS platform (type %d)", platform);
break;
}
return EXIT_FAILURE;
}
int
svcRemoveNT(char *name)
{
SC_HANDLE svcHandle;
SC_HANDLE scmHandle;
SERVICE_STATUS status;
int retStatus = EXIT_SUCCESS;
/* Open the SCM */
if ((scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) != NULL)
{
svcHandle = OpenService(scmHandle, name, SERVICE_ALL_ACCESS);
if (svcHandle != NULL)
{
/* Try to stop the service */
if (ControlService(svcHandle, SERVICE_CONTROL_STOP, &status))
{
while (QueryServiceStatus(svcHandle, &status))
{
if (status.dwCurrentState == SERVICE_STOP_PENDING)
{
Sleep(1000);
}
else
{
break;
}
}
if (status.dwCurrentState != SERVICE_STOPPED)
{
message(0, 0, "failed to stop the '%s' service", name);
retStatus = EXIT_FAILURE;
}
}
/* Now remove the service from the SCM */
if (DeleteService(svcHandle))
{
message(1, 0, "successfully removed the '%s' service", name);
}
else
{
message(0, 0, "failed to remove the '%s' service", name);
retStatus = EXIT_FAILURE;
}
CloseServiceHandle(svcHandle);
}
else
{
message(0, 0, "can't find the '%s' service", name);
retStatus = EXIT_FAILURE;
}
CloseServiceHandle(scmHandle);
}
else
{
message(0, 0, "can't contact Service Control Manager");
retStatus = EXIT_FAILURE;
}
return retStatus;
}
int
svcRemove9X(char *name)
{
HKEY runKey;
int status = EXIT_SUCCESS;
/* Locate the RunServices registry entry */
if (RegOpenKey(HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows\\CurrentVersion\\RunServices",
&runKey) != ERROR_SUCCESS)
{
message(0, 0, "can't find the RunServices registry key");
status = EXIT_FAILURE;
}
else
{
/* Delete the key value for our service */
if (RegDeleteValue(runKey, name) != ERROR_SUCCESS)
{
message(0, 0, "failed to delete registry RunServices entry for '%s'", name);
status = EXIT_FAILURE;
}
else
{
message(1, 0, "successfully removed the '%s' service", name);
}
RegCloseKey(runKey);
}
return status;
}