forked from puppetlabs/nssm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.cpp
2400 lines (2022 loc) · 84.9 KB
/
service.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
#include "nssm.h"
bool is_admin;
bool use_critical_section;
extern imports_t imports;
extern settings_t settings[];
const TCHAR *exit_action_strings[] = { _T("Restart"), _T("Ignore"), _T("Exit"), _T("Suicide"), 0 };
const TCHAR *startup_strings[] = { _T("SERVICE_AUTO_START"), _T("SERVICE_DELAYED_AUTO_START"), _T("SERVICE_DEMAND_START"), _T("SERVICE_DISABLED"), 0 };
const TCHAR *priority_strings[] = { _T("REALTIME_PRIORITY_CLASS"), _T("HIGH_PRIORITY_CLASS"), _T("ABOVE_NORMAL_PRIORITY_CLASS"), _T("NORMAL_PRIORITY_CLASS"), _T("BELOW_NORMAL_PRIORITY_CLASS"), _T("IDLE_PRIORITY_CLASS"), 0 };
static hook_thread_t hook_threads = { NULL, 0 };
typedef struct {
int first;
int last;
} list_t;
/*
Check the status in response to a control.
Returns: 1 if the status is expected, eg STOP following CONTROL_STOP.
0 if the status is desired, eg STOPPED following CONTROL_STOP.
-1 if the status is undesired, eg STOPPED following CONTROL_START.
*/
static inline int service_control_response(unsigned long control, unsigned long status) {
switch (control) {
case NSSM_SERVICE_CONTROL_START:
switch (status) {
case SERVICE_START_PENDING:
return 1;
case SERVICE_RUNNING:
return 0;
default:
return -1;
}
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
switch (status) {
case SERVICE_RUNNING:
case SERVICE_STOP_PENDING:
return 1;
case SERVICE_STOPPED:
return 0;
default:
return -1;
}
case SERVICE_CONTROL_PAUSE:
switch (status) {
case SERVICE_PAUSE_PENDING:
return 1;
case SERVICE_PAUSED:
return 0;
default:
return -1;
}
case SERVICE_CONTROL_CONTINUE:
switch (status) {
case SERVICE_CONTINUE_PENDING:
return 1;
case SERVICE_RUNNING:
return 0;
default:
return -1;
}
case SERVICE_CONTROL_INTERROGATE:
case NSSM_SERVICE_CONTROL_ROTATE:
return 0;
}
return 0;
}
static inline int await_service_control_response(unsigned long control, SC_HANDLE service_handle, SERVICE_STATUS *service_status, unsigned long initial_status, unsigned long cutoff) {
int tries = 0;
unsigned long checkpoint = 0;
unsigned long waithint = 0;
unsigned long waited = 0;
while (QueryServiceStatus(service_handle, service_status)) {
int response = service_control_response(control, service_status->dwCurrentState);
/* Alas we can't WaitForSingleObject() on an SC_HANDLE. */
if (! response) return response;
if (response > 0 || service_status->dwCurrentState == initial_status) {
if (service_status->dwCheckPoint != checkpoint || service_status->dwWaitHint != waithint) tries = 0;
checkpoint = service_status->dwCheckPoint;
waithint = service_status->dwWaitHint;
if (++tries > 10) tries = 10;
unsigned long wait = 50 * tries;
if (cutoff) {
if (waited > cutoff) return response;
waited += wait;
}
Sleep(wait);
}
else return response;
}
return -1;
}
static inline int await_service_control_response(unsigned long control, SC_HANDLE service_handle, SERVICE_STATUS *service_status, unsigned long initial_status) {
return await_service_control_response(control, service_handle, service_status, initial_status, 0);
}
static inline void wait_for_hooks(nssm_service_t *service, bool notify) {
SERVICE_STATUS_HANDLE status_handle;
SERVICE_STATUS *status;
/* On a clean shutdown we need to keep the service's status up-to-date. */
if (notify) {
status_handle = service->status_handle;
status = &service->status;
}
else {
status_handle = NULL;
status = NULL;
}
EnterCriticalSection(&service->hook_section);
await_hook_threads(&hook_threads, status_handle, status, NSSM_HOOK_THREAD_DEADLINE);
LeaveCriticalSection(&service->hook_section);
}
int affinity_mask_to_string(__int64 mask, TCHAR **string) {
if (! string) return 1;
if (! mask) {
*string = 0;
return 0;
}
__int64 i, n;
/* SetProcessAffinityMask() accepts a mask of up to 64 processors. */
list_t set[64];
for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1;
for (i = 0, n = 0; i < _countof(set); i++) {
if (mask & (1LL << i)) {
if (set[n].first == -1) set[n].first = set[n].last = (int) i;
else if (set[n].last == (int) i - 1) set[n].last = (int) i;
else {
n++;
set[n].first = set[n].last = (int) i;
}
}
}
/* Worst case is 2x2 characters for first and last CPU plus - and/or , */
size_t len = (size_t) (n + 1) * 6;
*string = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len * sizeof(TCHAR));
if (! string) return 2;
size_t s = 0;
int ret;
for (i = 0; i <= n; i++) {
if (i) (*string)[s++] = _T(',');
ret = _sntprintf_s(*string + s, 3, _TRUNCATE, _T("%u"), set[i].first);
if (ret < 0) {
HeapFree(GetProcessHeap(), 0, *string);
*string = 0;
return 3;
}
else s += ret;
if (set[i].last != set[i].first) {
ret =_sntprintf_s(*string + s, 4, _TRUNCATE, _T("%c%u"), (set[i].last == set[i].first + 1) ? _T(',') : _T('-'), set[i].last);
if (ret < 0) {
HeapFree(GetProcessHeap(), 0, *string);
*string = 0;
return 4;
}
else s += ret;
}
}
return 0;
}
int affinity_string_to_mask(TCHAR *string, __int64 *mask) {
if (! mask) return 1;
*mask = 0LL;
if (! string) return 0;
list_t set[64];
TCHAR *s = string;
TCHAR *end;
int ret;
int i;
int n = 0;
unsigned long number;
for (n = 0; n < _countof(set); n++) set[n].first = set[n].last = -1;
n = 0;
while (*s) {
ret = str_number(s, &number, &end);
s = end;
if (ret == 0 || ret == 2) {
if (number >= _countof(set)) return 2;
set[n].first = set[n].last = (int) number;
switch (*s) {
case 0:
break;
case _T(','):
n++;
s++;
break;
case _T('-'):
if (! *(++s)) return 3;
ret = str_number(s, &number, &end);
if (ret == 0 || ret == 2) {
s = end;
if (! *s || *s == _T(',')) {
set[n].last = (int) number;
if (! *s) break;
n++;
s++;
}
else return 3;
}
else return 3;
break;
default:
return 3;
}
}
else return 4;
}
for (i = 0; i <= n; i++) {
for (int j = set[i].first; j <= set[i].last; j++) (__int64) *mask |= (1LL << (__int64) j);
}
return 0;
}
unsigned long priority_mask() {
return REALTIME_PRIORITY_CLASS | HIGH_PRIORITY_CLASS | ABOVE_NORMAL_PRIORITY_CLASS | NORMAL_PRIORITY_CLASS | BELOW_NORMAL_PRIORITY_CLASS | IDLE_PRIORITY_CLASS;
}
int priority_constant_to_index(unsigned long constant) {
switch (constant & priority_mask()) {
case REALTIME_PRIORITY_CLASS: return NSSM_REALTIME_PRIORITY;
case HIGH_PRIORITY_CLASS: return NSSM_HIGH_PRIORITY;
case ABOVE_NORMAL_PRIORITY_CLASS: return NSSM_ABOVE_NORMAL_PRIORITY;
case BELOW_NORMAL_PRIORITY_CLASS: return NSSM_BELOW_NORMAL_PRIORITY;
case IDLE_PRIORITY_CLASS: return NSSM_IDLE_PRIORITY;
}
return NSSM_NORMAL_PRIORITY;
}
unsigned long priority_index_to_constant(int index) {
switch (index) {
case NSSM_REALTIME_PRIORITY: return REALTIME_PRIORITY_CLASS;
case NSSM_HIGH_PRIORITY: return HIGH_PRIORITY_CLASS;
case NSSM_ABOVE_NORMAL_PRIORITY: return ABOVE_NORMAL_PRIORITY_CLASS;
case NSSM_BELOW_NORMAL_PRIORITY: return BELOW_NORMAL_PRIORITY_CLASS;
case NSSM_IDLE_PRIORITY: return IDLE_PRIORITY_CLASS;
}
return NORMAL_PRIORITY_CLASS;
}
static inline unsigned long throttle_milliseconds(unsigned long throttle) {
if (throttle > 7) throttle = 8;
/* pow() operates on doubles. */
unsigned long ret = 1; for (unsigned long i = 1; i < throttle; i++) ret *= 2;
return ret * 1000;
}
void set_service_environment(nssm_service_t *service) {
if (! service) return;
/*
We have to duplicate the block because this function will be called
multiple times between registry reads.
*/
if (service->env) duplicate_environment_strings(service->env);
if (! service->env_extra) return;
TCHAR *env_extra = copy_environment_block(service->env_extra);
if (! env_extra) return;
set_environment_block(env_extra);
HeapFree(GetProcessHeap(), 0, env_extra);
}
void unset_service_environment(nssm_service_t *service) {
if (! service) return;
duplicate_environment_strings(service->initial_env);
}
/*
Wrapper to be called in a new thread so that we can acknowledge a STOP
control immediately.
*/
static unsigned long WINAPI shutdown_service(void *arg) {
return stop_service((nssm_service_t *) arg, 0, true, true);
}
/*
Wrapper to be called in a new thread so that we can acknowledge start
immediately.
*/
static unsigned long WINAPI launch_service(void *arg) {
return monitor_service((nssm_service_t *) arg);
}
/* Connect to the service manager */
SC_HANDLE open_service_manager(unsigned long access) {
SC_HANDLE ret = OpenSCManager(0, SERVICES_ACTIVE_DATABASE, access);
if (! ret) {
if (is_admin) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENSCMANAGER_FAILED, 0);
return 0;
}
return ret;
}
/* Open a service by name or display name. */
SC_HANDLE open_service(SC_HANDLE services, TCHAR *service_name, unsigned long access, TCHAR *canonical_name, unsigned long canonical_namelen) {
SC_HANDLE service_handle = OpenService(services, service_name, access);
if (service_handle) {
if (canonical_name && canonical_name != service_name) {
TCHAR displayname[SERVICE_NAME_LENGTH];
unsigned long displayname_len = (unsigned long) _countof(displayname);
GetServiceDisplayName(services, service_name, displayname, &displayname_len);
unsigned long keyname_len = canonical_namelen;
GetServiceKeyName(services, displayname, canonical_name, &keyname_len);
}
return service_handle;
}
unsigned long error = GetLastError();
if (error != ERROR_SERVICE_DOES_NOT_EXIST) {
print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED, error_string(GetLastError()));
return 0;
}
/* We can't look for a display name because there's no buffer to store it. */
if (! canonical_name) {
print_message(stderr, NSSM_MESSAGE_OPENSERVICE_FAILED, error_string(GetLastError()));
return 0;
}
unsigned long bufsize, required, count, i;
unsigned long resume = 0;
EnumServicesStatusEx(services, SC_ENUM_PROCESS_INFO, SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, 0, 0, &required, &count, &resume, 0);
error = GetLastError();
if (error != ERROR_MORE_DATA) {
print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError()));
return 0;
}
ENUM_SERVICE_STATUS_PROCESS *status = (ENUM_SERVICE_STATUS_PROCESS *) HeapAlloc(GetProcessHeap(), 0, required);
if (! status) {
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("ENUM_SERVICE_STATUS_PROCESS"), _T("open_service()"));
return 0;
}
bufsize = required;
while (true) {
/*
EnumServicesStatusEx() returns:
1 when it retrieved data and there's no more data to come.
0 and sets last error to ERROR_MORE_DATA when it retrieved data and
there's more data to come.
0 and sets last error to something else on error.
*/
int ret = EnumServicesStatusEx(services, SC_ENUM_PROCESS_INFO, SERVICE_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_KERNEL_DRIVER | SERVICE_WIN32, SERVICE_STATE_ALL, (LPBYTE) status, bufsize, &required, &count, &resume, 0);
if (! ret) {
error = GetLastError();
if (error != ERROR_MORE_DATA) {
HeapFree(GetProcessHeap(), 0, status);
print_message(stderr, NSSM_MESSAGE_ENUMSERVICESSTATUS_FAILED, error_string(GetLastError()));
return 0;
}
}
for (i = 0; i < count; i++) {
if (str_equiv(status[i].lpDisplayName, service_name)) {
if (_sntprintf_s(canonical_name, canonical_namelen, _TRUNCATE, _T("%s"), status[i].lpServiceName) < 0) {
HeapFree(GetProcessHeap(), 0, status);
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("canonical_name"), _T("open_service()"));
return 0;
}
HeapFree(GetProcessHeap(), 0, status);
return open_service(services, canonical_name, access, 0, 0);
}
}
if (ret) break;
}
/* Recurse so we can get an error message. */
return open_service(services, service_name, access, 0, 0);
}
QUERY_SERVICE_CONFIG *query_service_config(const TCHAR *service_name, SC_HANDLE service_handle) {
QUERY_SERVICE_CONFIG *qsc;
unsigned long bufsize;
unsigned long error;
QueryServiceConfig(service_handle, 0, 0, &bufsize);
error = GetLastError();
if (error == ERROR_INSUFFICIENT_BUFFER) {
qsc = (QUERY_SERVICE_CONFIG *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bufsize);
if (! qsc) {
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("QUERY_SERVICE_CONFIG"), _T("query_service_config()"), 0);
return 0;
}
}
else {
print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG_FAILED, service_name, error_string(error), 0);
return 0;
}
if (! QueryServiceConfig(service_handle, qsc, bufsize, &bufsize)) {
HeapFree(GetProcessHeap(), 0, qsc);
print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG_FAILED, service_name, error_string(GetLastError()), 0);
return 0;
}
return qsc;
}
/* WILL NOT allocate a new string if the identifier is already present. */
int prepend_service_group_identifier(TCHAR *group, TCHAR **canon) {
if (! group || ! group[0] || group[0] == SC_GROUP_IDENTIFIER) {
*canon = group;
return 0;
}
size_t len = _tcslen(group) + 1;
*canon = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(TCHAR));
if (! *canon) {
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("canon"), _T("prepend_service_group_identifier()"));
return 1;
}
TCHAR *s = *canon;
*s++ = SC_GROUP_IDENTIFIER;
memmove(s, group, len * sizeof(TCHAR));
(*canon)[len] = _T('\0');
return 0;
}
int append_to_dependencies(TCHAR *dependencies, unsigned long dependencieslen, TCHAR *string, TCHAR **newdependencies, unsigned long *newlen, int type) {
*newlen = 0;
TCHAR *canon = 0;
if (type == DEPENDENCY_GROUPS) {
if (prepend_service_group_identifier(string, &canon)) return 1;
}
else canon = string;
int ret = append_to_double_null(dependencies, dependencieslen, newdependencies, newlen, canon, 0, false);
if (canon && canon != string) HeapFree(GetProcessHeap(), 0, canon);
return ret;
}
int remove_from_dependencies(TCHAR *dependencies, unsigned long dependencieslen, TCHAR *string, TCHAR **newdependencies, unsigned long *newlen, int type) {
*newlen = 0;
TCHAR *canon = 0;
if (type == DEPENDENCY_GROUPS) {
if (prepend_service_group_identifier(string, &canon)) return 1;
}
else canon = string;
int ret = remove_from_double_null(dependencies, dependencieslen, newdependencies, newlen, canon, 0, false);
if (canon && canon != string) HeapFree(GetProcessHeap(), 0, canon);
return ret;
}
int set_service_dependencies(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR *buffer) {
TCHAR *dependencies = _T("");
unsigned long num_dependencies = 0;
if (buffer && buffer[0]) {
SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE);
if (! services) {
print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
return 1;
}
/*
Count the dependencies then allocate a buffer big enough for their
canonical names, ie n * SERVICE_NAME_LENGTH.
*/
TCHAR *s;
TCHAR *groups = 0;
for (s = buffer; *s; s++) {
num_dependencies++;
if (*s == SC_GROUP_IDENTIFIER) groups = s;
while (*s) s++;
}
/* At least one dependency is a group so we need to verify them. */
if (groups) {
HKEY key;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, NSSM_REGISTRY_GROUPS, 0, KEY_READ, &key)) {
_ftprintf(stderr, _T("%s: %s\n"), NSSM_REGISTRY_GROUPS, error_string(GetLastError()));
return 2;
}
unsigned long type;
unsigned long groupslen;
unsigned long ret = RegQueryValueEx(key, NSSM_REG_GROUPS, 0, &type, NULL, &groupslen);
if (ret == ERROR_SUCCESS) {
groups = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, groupslen);
if (! groups) {
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("groups"), _T("set_service_dependencies()"));
return 3;
}
ret = RegQueryValueEx(key, NSSM_REG_GROUPS, 0, &type, (unsigned char *) groups, &groupslen);
if (ret != ERROR_SUCCESS) {
_ftprintf(stderr, _T("%s\\%s: %s"), NSSM_REGISTRY_GROUPS, NSSM_REG_GROUPS, error_string(GetLastError()));
HeapFree(GetProcessHeap(), 0, groups);
RegCloseKey(key);
return 4;
}
}
else if (ret != ERROR_FILE_NOT_FOUND) {
_ftprintf(stderr, _T("%s\\%s: %s"), NSSM_REGISTRY_GROUPS, NSSM_REG_GROUPS, error_string(GetLastError()));
RegCloseKey(key);
return 4;
}
RegCloseKey(key);
}
unsigned long dependencieslen = (num_dependencies * SERVICE_NAME_LENGTH) + 2;
dependencies = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dependencieslen * sizeof(TCHAR));
size_t i = 0;
TCHAR dependency[SERVICE_NAME_LENGTH];
for (s = buffer; *s; s++) {
/* Group? */
if (*s == SC_GROUP_IDENTIFIER) {
TCHAR *group = s + 1;
bool ok = false;
if (*group) {
for (TCHAR *g = groups; *g; g++) {
if (str_equiv(g, group)) {
ok = true;
/* Set canonical name. */
memmove(group, g, _tcslen(g) * sizeof(TCHAR));
break;
}
while (*g) g++;
}
}
if (ok) _sntprintf_s(dependency, _countof(dependency), _TRUNCATE, _T("%s"), s);
else {
HeapFree(GetProcessHeap(), 0, dependencies);
if (groups) HeapFree(GetProcessHeap(), 0, groups);
_ftprintf(stderr, _T("%s: %s"), s, error_string(ERROR_SERVICE_DEPENDENCY_DELETED));
return 5;
}
}
else {
SC_HANDLE dependency_handle = open_service(services, s, SERVICE_QUERY_STATUS, dependency, _countof(dependency));
if (! dependency_handle) {
HeapFree(GetProcessHeap(), 0, dependencies);
if (groups) HeapFree(GetProcessHeap(), 0, groups);
CloseServiceHandle(services);
_ftprintf(stderr, _T("%s: %s"), s, error_string(ERROR_SERVICE_DEPENDENCY_DELETED));
return 5;
}
}
size_t len = _tcslen(dependency) + 1;
memmove(dependencies + i, dependency, len * sizeof(TCHAR));
i += len;
while (*s) s++;
}
if (groups) HeapFree(GetProcessHeap(), 0, groups);
CloseServiceHandle(services);
}
if (! ChangeServiceConfig(service_handle, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, 0, 0, 0, dependencies, 0, 0, 0)) {
if (num_dependencies) HeapFree(GetProcessHeap(), 0, dependencies);
print_message(stderr, NSSM_MESSAGE_CHANGESERVICECONFIG_FAILED, error_string(GetLastError()));
return -1;
}
if (num_dependencies) HeapFree(GetProcessHeap(), 0, dependencies);
return 0;
}
int get_service_dependencies(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR **buffer, unsigned long *bufsize, int type) {
if (! buffer) return 1;
if (! bufsize) return 2;
*buffer = 0;
*bufsize = 0;
QUERY_SERVICE_CONFIG *qsc = query_service_config(service_name, service_handle);
if (! qsc) return 3;
if (! qsc->lpDependencies || ! qsc->lpDependencies[0]) {
HeapFree(GetProcessHeap(), 0, qsc);
return 0;
}
/* lpDependencies is doubly NULL terminated. */
while (qsc->lpDependencies[*bufsize]) {
while (qsc->lpDependencies[*bufsize]) ++*bufsize;
++*bufsize;
}
*bufsize += 2;
*buffer = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *bufsize * sizeof(TCHAR));
if (! *buffer) {
*bufsize = 0;
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("lpDependencies"), _T("get_service_dependencies()"));
HeapFree(GetProcessHeap(), 0, qsc);
return 4;
}
if (type == DEPENDENCY_ALL) memmove(*buffer, qsc->lpDependencies, *bufsize * sizeof(TCHAR));
else {
TCHAR *s;
size_t i = 0;
*bufsize = 0;
for (s = qsc->lpDependencies; *s; s++) {
/* Only copy the appropriate type of dependency. */
if ((*s == SC_GROUP_IDENTIFIER && type & DEPENDENCY_GROUPS) || (*s != SC_GROUP_IDENTIFIER && type & DEPENDENCY_SERVICES)) {
size_t len = _tcslen(s) + 1;
*bufsize += (unsigned long) len;
memmove(*buffer + i, s, len * sizeof(TCHAR));
i += len;
}
while (*s) s++;
}
++*bufsize;
}
HeapFree(GetProcessHeap(), 0, qsc);
if (! *buffer[0]) {
HeapFree(GetProcessHeap(), 0, *buffer);
*buffer = 0;
*bufsize = 0;
}
return 0;
}
int get_service_dependencies(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR **buffer, unsigned long *bufsize) {
return get_service_dependencies(service_name, service_handle, buffer, bufsize, DEPENDENCY_ALL);
}
int set_service_description(const TCHAR *service_name, SC_HANDLE service_handle, TCHAR *buffer) {
SERVICE_DESCRIPTION description;
ZeroMemory(&description, sizeof(description));
/*
lpDescription must be NULL if we aren't changing, the new description
or "".
*/
if (buffer && buffer[0]) description.lpDescription = buffer;
else description.lpDescription = _T("");
if (ChangeServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, &description)) return 0;
log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SERVICE_CONFIG_DESCRIPTION_FAILED, service_name, error_string(GetLastError()), 0);
return 1;
}
int get_service_description(const TCHAR *service_name, SC_HANDLE service_handle, unsigned long len, TCHAR *buffer) {
if (! buffer) return 1;
unsigned long bufsize;
QueryServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, 0, 0, &bufsize);
unsigned long error = GetLastError();
if (error == ERROR_INSUFFICIENT_BUFFER) {
SERVICE_DESCRIPTION *description = (SERVICE_DESCRIPTION *) HeapAlloc(GetProcessHeap(), 0, bufsize);
if (! description) {
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SERVICE_CONFIG_DESCRIPTION"), _T("get_service_description()"));
return 2;
}
if (QueryServiceConfig2(service_handle, SERVICE_CONFIG_DESCRIPTION, (unsigned char *) description, bufsize, &bufsize)) {
if (description->lpDescription) _sntprintf_s(buffer, len, _TRUNCATE, _T("%s"), description->lpDescription);
else ZeroMemory(buffer, len * sizeof(TCHAR));
HeapFree(GetProcessHeap(), 0, description);
return 0;
}
else {
HeapFree(GetProcessHeap(), 0, description);
print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DESCRIPTION"), error_string(error));
return 3;
}
}
else {
print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DESCRIPTION"), error_string(error));
return 4;
}
}
int get_service_startup(const TCHAR *service_name, SC_HANDLE service_handle, const QUERY_SERVICE_CONFIG *qsc, unsigned long *startup) {
if (! qsc) return 1;
switch (qsc->dwStartType) {
case SERVICE_DEMAND_START: *startup = NSSM_STARTUP_MANUAL; break;
case SERVICE_DISABLED: *startup = NSSM_STARTUP_DISABLED; break;
default: *startup = NSSM_STARTUP_AUTOMATIC;
}
if (*startup != NSSM_STARTUP_AUTOMATIC) return 0;
/* Check for delayed start. */
unsigned long bufsize;
unsigned long error;
QueryServiceConfig2(service_handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, 0, 0, &bufsize);
error = GetLastError();
if (error == ERROR_INSUFFICIENT_BUFFER) {
SERVICE_DELAYED_AUTO_START_INFO *info = (SERVICE_DELAYED_AUTO_START_INFO *) HeapAlloc(GetProcessHeap(), 0, bufsize);
if (! info) {
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("SERVICE_DELAYED_AUTO_START_INFO"), _T("get_service_startup()"));
return 2;
}
if (QueryServiceConfig2(service_handle, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, (unsigned char *) info, bufsize, &bufsize)) {
if (info->fDelayedAutostart) *startup = NSSM_STARTUP_DELAYED;
HeapFree(GetProcessHeap(), 0, info);
return 0;
}
else {
error = GetLastError();
if (error != ERROR_INVALID_LEVEL) {
print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_CONFIG_DELAYED_AUTO_START_INFO"), error_string(error));
return 3;
}
}
}
else if (error != ERROR_INVALID_LEVEL) {
print_message(stderr, NSSM_MESSAGE_QUERYSERVICECONFIG2_FAILED, service_name, _T("SERVICE_DELAYED_AUTO_START_INFO"), error_string(error));
return 3;
}
return 0;
}
int get_service_username(const TCHAR *service_name, const QUERY_SERVICE_CONFIG *qsc, TCHAR **username, size_t *usernamelen) {
if (! username) return 1;
if (! usernamelen) return 1;
*username = 0;
*usernamelen = 0;
if (! qsc) return 1;
if (qsc->lpServiceStartName[0]) {
if (is_localsystem(qsc->lpServiceStartName)) return 0;
size_t len = _tcslen(qsc->lpServiceStartName);
*username = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(TCHAR));
if (! *username) {
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("username"), _T("get_service_username()"));
return 2;
}
memmove(*username, qsc->lpServiceStartName, (len + 1) * sizeof(TCHAR));
*usernamelen = len;
}
return 0;
}
/* Set default values which aren't zero. */
void set_nssm_service_defaults(nssm_service_t *service) {
if (! service) return;
service->type = SERVICE_WIN32_OWN_PROCESS;
service->priority = NORMAL_PRIORITY_CLASS;
service->stdin_sharing = NSSM_STDIN_SHARING;
service->stdin_disposition = NSSM_STDIN_DISPOSITION;
service->stdin_flags = NSSM_STDIN_FLAGS;
service->stdout_sharing = NSSM_STDOUT_SHARING;
service->stdout_disposition = NSSM_STDOUT_DISPOSITION;
service->stdout_flags = NSSM_STDOUT_FLAGS;
service->stderr_sharing = NSSM_STDERR_SHARING;
service->stderr_disposition = NSSM_STDERR_DISPOSITION;
service->stderr_flags = NSSM_STDERR_FLAGS;
service->throttle_delay = NSSM_RESET_THROTTLE_RESTART;
service->stop_method = ~0;
service->kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD;
service->kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD;
service->kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD;
service->kill_process_tree = 1;
}
/* Allocate and zero memory for a service. */
nssm_service_t *alloc_nssm_service() {
nssm_service_t *service = (nssm_service_t *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(nssm_service_t));
if (! service) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("service"), _T("alloc_nssm_service()"), 0);
return service;
}
/* Free memory for a service. */
void cleanup_nssm_service(nssm_service_t *service) {
if (! service) return;
if (service->username) HeapFree(GetProcessHeap(), 0, service->username);
if (service->password) {
SecureZeroMemory(service->password, service->passwordlen * sizeof(TCHAR));
HeapFree(GetProcessHeap(), 0, service->password);
}
if (service->dependencies) HeapFree(GetProcessHeap(), 0, service->dependencies);
if (service->env) HeapFree(GetProcessHeap(), 0, service->env);
if (service->env_extra) HeapFree(GetProcessHeap(), 0, service->env_extra);
if (service->handle) CloseServiceHandle(service->handle);
if (service->process_handle) CloseHandle(service->process_handle);
if (service->wait_handle) UnregisterWait(service->wait_handle);
if (service->throttle_section_initialised) DeleteCriticalSection(&service->throttle_section);
if (service->throttle_timer) CloseHandle(service->throttle_timer);
if (service->hook_section_initialised) DeleteCriticalSection(&service->hook_section);
if (service->initial_env) HeapFree(GetProcessHeap(), 0, service->initial_env);
HeapFree(GetProcessHeap(), 0, service);
}
/* About to install the service */
int pre_install_service(int argc, TCHAR **argv) {
nssm_service_t *service = alloc_nssm_service();
set_nssm_service_defaults(service);
if (argc) _sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), argv[0]);
/* Show the dialogue box if we didn't give the service name and path */
if (argc < 2) return nssm_gui(IDD_INSTALL, service);
if (! service) {
print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("service"), _T("pre_install_service()"));
return 1;
}
_sntprintf_s(service->exe, _countof(service->exe), _TRUNCATE, _T("%s"), argv[1]);
/* Arguments are optional */
size_t flagslen = 0;
size_t s = 0;
int i;
for (i = 2; i < argc; i++) flagslen += _tcslen(argv[i]) + 1;
if (! flagslen) flagslen = 1;
if (flagslen > _countof(service->flags)) {
print_message(stderr, NSSM_MESSAGE_FLAGS_TOO_LONG);
return 2;
}
for (i = 2; i < argc; i++) {
size_t len = _tcslen(argv[i]);
memmove(service->flags + s, argv[i], len * sizeof(TCHAR));
s += len;
if (i < argc - 1) service->flags[s++] = _T(' ');
}
/* Work out directory name */
_sntprintf_s(service->dir, _countof(service->dir), _TRUNCATE, _T("%s"), service->exe);
strip_basename(service->dir);
int ret = install_service(service);
cleanup_nssm_service(service);
return ret;
}
/* About to edit the service. */
int pre_edit_service(int argc, TCHAR **argv) {
/* Require service name. */
if (argc < 2) return usage(1);
/* Are we editing on the command line? */
enum { MODE_EDITING, MODE_GETTING, MODE_SETTING, MODE_RESETTING, MODE_DUMPING } mode = MODE_EDITING;
const TCHAR *verb = argv[0];
const TCHAR *service_name = argv[1];
bool getting = false;
bool unsetting = false;
/* Minimum number of arguments. */
int mandatory = 2;
/* Index of first value. */
int remainder = 3;
int i;
if (str_equiv(verb, _T("get"))) {
mandatory = 3;
mode = MODE_GETTING;
}
else if (str_equiv(verb, _T("set"))) {
mandatory = 4;
mode = MODE_SETTING;
}
else if (str_equiv(verb, _T("reset")) || str_equiv(verb, _T("unset"))) {
mandatory = 3;
mode = MODE_RESETTING;
}
else if (str_equiv(verb, _T("dump"))) {
mandatory = 1;
remainder = 2;
mode = MODE_DUMPING;
}
if (argc < mandatory) return usage(1);
const TCHAR *parameter = 0;
settings_t *setting = 0;
TCHAR *additional;
/* Validate the parameter. */
if (mandatory > 2) {
bool additional_mandatory = false;
parameter = argv[2];
for (i = 0; settings[i].name; i++) {
setting = &settings[i];
if (! str_equiv(setting->name, parameter)) continue;
if (((setting->additional & ADDITIONAL_GETTING) && mode == MODE_GETTING) || ((setting->additional & ADDITIONAL_SETTING) && mode == MODE_SETTING) || ((setting->additional & ADDITIONAL_RESETTING) && mode == MODE_RESETTING)) {
additional_mandatory = true;
mandatory++;
}
break;
}
if (! settings[i].name) {
print_message(stderr, NSSM_MESSAGE_INVALID_PARAMETER, parameter);
for (i = 0; settings[i].name; i++) _ftprintf(stderr, _T("%s\n"), settings[i].name);
return 1;
}
additional = 0;
if (additional_mandatory) {
if (argc < mandatory) {
print_message(stderr, NSSM_MESSAGE_MISSING_SUBPARAMETER, parameter);
return 1;
}
additional = argv[3];
remainder = 4;
}
else if (str_equiv(setting->name, NSSM_NATIVE_OBJECTNAME) && mode == MODE_SETTING) {
additional = argv[3];
remainder = 4;
}
else {
additional = argv[remainder];
if (argc < mandatory) return usage(1);
}
}
nssm_service_t *service = alloc_nssm_service();
_sntprintf_s(service->name, _countof(service->name), _TRUNCATE, _T("%s"), service_name);
/* Open service manager */
SC_HANDLE services = open_service_manager(SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE);
if (! services) {
print_message(stderr, NSSM_MESSAGE_OPEN_SERVICE_MANAGER_FAILED);
return 2;
}
/* Try to open the service */
unsigned long access = SERVICE_QUERY_CONFIG;
if (mode != MODE_GETTING) access |= SERVICE_CHANGE_CONFIG;
service->handle = open_service(services, service->name, access, service->name, _countof(service->name));
if (! service->handle) {
CloseServiceHandle(services);
return 3;
}
/* Get system details. */
QUERY_SERVICE_CONFIG *qsc = query_service_config(service->name, service->handle);
if (! qsc) {
CloseServiceHandle(service->handle);
CloseServiceHandle(services);
return 4;
}
service->type = qsc->dwServiceType;
if (! (service->type & SERVICE_WIN32_OWN_PROCESS)) {
if (mode != MODE_GETTING && mode != MODE_DUMPING) {
HeapFree(GetProcessHeap(), 0, qsc);
CloseServiceHandle(service->handle);