-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsvcbatch.c
7298 lines (6749 loc) · 214 KB
/
svcbatch.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
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <windows.h>
#include <bcrypt.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include "svcbatch.h"
#if defined (_DEBUG)
#include <crtdbg.h>
#endif
#if defined(_MSC_VER) && (_MSC_VER < 1600)
# define va_copy(d, s) (d) = (s)
#endif
#define HAVE_NAMED_MMAP 0
#define HAVE_EXTRA_SVC_PARAMS 0
#define HAVE_LOGDIR_MUTEX 1
#define HAVE_LOGDIR_LOCK 0
#if defined(DEBUG_TRACE)
# define HAVE_DEBUG_TRACE 1
#else
# define HAVE_DEBUG_TRACE 0
#endif
#if HAVE_DEBUG_TRACE
static void xtraceprintf(LPCSTR, int, int, LPCSTR, ...);
static void xtraceprints(LPCSTR, int, int, LPCSTR);
static void xtracefopen(void);
#define XTRACE_STOPSVC_EXT L"_stop.log"
#define XTRACE_SERVICE_EXT L"_service.log"
#define DBG_PRINTF(Fmt, ...) if (xtraceservice) xtraceprintf(__FUNCTION__, __LINE__, 0, Fmt, ##__VA_ARGS__)
#define DBG_PRINTS(Msg) if (xtraceservice) xtraceprints(__FUNCTION__, __LINE__, 0, Msg)
#else
#define DBG_PRINTF(Fmt, ...) (void)0
#define DBG_PRINTS(Msg) (void)0
#endif
/**
* Error macros
*/
#define SVCBATCH_FATAL(_e) xfatalerr("!!Fatal error in svcbatch.c at line #" CPP_TOSTR(__LINE__), (_e))
#define SVCBATCH_EEXIT(_o, _e) xeexiterr("Runtime error in svcbatch.c at line #" CPP_TOSTR(__LINE__), (_o), (_e))
#define xsyserrno(_i, _d, _p) svcsyserror(__FUNCTION__, __LINE__, EVENTLOG_ERROR_TYPE, 0, wcsmessages[_i], _d, _p)
#define xsyserror(_n, _d, _p) svcsyserror(__FUNCTION__, __LINE__, EVENTLOG_ERROR_TYPE, _n, NULL, _d, _p)
#define svcerror(_e, _i, _f, ...) xerrsprintf(__FUNCTION__, __LINE__, EVENTLOG_ERROR_TYPE, _e, errmessages[_i], _f, ##__VA_ARGS__)
#define xsyswarn(_e, _i, _f, ...) xerrsprintf(__FUNCTION__, __LINE__, EVENTLOG_WARNING_TYPE, _e, errmessages[_i], _f, ##__VA_ARGS__)
#define xsysinfo(_e, _i, _f, ...) xerrsprintf(__FUNCTION__, __LINE__, EVENTLOG_INFORMATION_TYPE, _e, errmessages[_i], _f, ##__VA_ARGS__)
#define xsvcstatus(_s, _p) if (servicemode) reportsvcstatus(__FUNCTION__, __LINE__, _s, _p)
#define SZ_STATUS_PROCESS_INFO sizeof(SERVICE_STATUS_PROCESS)
#define SYSTEM_SVC_SUBKEY L"SYSTEM\\CurrentControlSet\\Services\\"
#define IS_LEAP_YEAR(_y) ((!(_y % 4)) ? (((_y % 400) && !(_y % 100)) ? 0 : 1) : 0)
#define SYSVARS_COUNT 27
#define GETSYSVAR_VAL(_i) svariables->var[_i - 64].val
#define GETSYSVAR_KEY(_i) svariables->var[_i - 64].key
#define SETSYSVAR_VAL(_i, _v) svariables->var[_i - 64].val = _v
#define SETSYSVAR_KEY(_i, _k) svariables->var[_i - 64].key = _k
#define INVALID_FILENAME_CHARS L"/\\:;<>?*|\""
#define INVALID_PATHNAME_CHARS L";<>?*|"
/**
* Misc internal buffer size definitions
*/
#define NBUFSIZ 16
#define TBUFSIZ 32
#define WBUFSIZ 64
#define SBUFSIZ 128
#define BBUFSIZ 512
#define MBUFSIZ 1024
#define HBUFSIZ 4096
typedef enum {
SVCBATCH_WORKER_THREAD = 0,
SVCBATCH_STDIN_THREAD,
SVCBATCH_STOP_THREAD,
SVCBATCH_ROTATE_THREAD,
SVCBATCH_MAX_THREADS
} SVCBATCH_THREAD_ID;
typedef enum {
SVCBATCH_REG_TYPE_NONE = 0, /* Unknown registry type */
SVCBATCH_REG_TYPE_BIN, /* [RRF_RT_]REG_BINARY */
SVCBATCH_REG_TYPE_BOOL, /* [RRF_RT_]REG_DWORD */
SVCBATCH_REG_TYPE_ESZ, /* [RRF_RT_]REG_EXPAND_SZ */
SVCBATCH_REG_TYPE_MSZ, /* [RRF_RT_]REG_MULTI_SZ */
SVCBATCH_REG_TYPE_NUM, /* [RRF_RT_]REG_DWORD */
SVCBATCH_REG_TYPE_SZ /* [RRF_RT_]REG_SZ */
} SVCBATCH_REG_TYPE;
#if HAVE_DEBUG_TRACE
static const char *xtracesvcmodes[] = {
"STOPSVC",
"SERVICE"
};
static const char *xtracesvctypes[] = {
"DEBUG",
"ERROR",
"WARN",
"0003",
"INFO",
"0005",
"0006",
"0007",
};
#endif
static const DWORD svcbrrfrtypes[] = {
0,
RRF_RT_REG_BINARY,
RRF_RT_REG_DWORD,
RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND,
RRF_RT_REG_MULTI_SZ,
RRF_RT_REG_DWORD,
RRF_RT_REG_SZ,
};
static const DWORD svcbregrtypes[] = {
0,
REG_BINARY,
REG_DWORD,
REG_EXPAND_SZ,
REG_MULTI_SZ,
REG_DWORD,
REG_SZ
};
typedef struct _SVCBATCH_WBUFFER {
int siz;
int pos;
LPWSTR buf;
} SVCBATCH_WBUFFER, *LPSVCBATCH_WBUFFER;
typedef struct _SVCBATCH_VARIABLE {
DWORD iid;
DWORD mod;
LPCWSTR key;
LPCWSTR val;
} SVCBATCH_VARIABLE, *LPSVCBATCH_VARIABLE;
typedef struct _SVCBATCH_VARIABLES {
int siz;
int pos;
SVCBATCH_VARIABLE var[SBUFSIZ];
} SVCBATCH_VARIABLES, *LPSVCBATCH_VARIABLES;
typedef struct _SVCBATCH_THREAD {
volatile HANDLE thread;
volatile LONG started;
LPTHREAD_START_ROUTINE startAddress;
LPVOID parameter;
DWORD id;
DWORD exitCode;
ULONGLONG duration;
LPCSTR name;
} SVCBATCH_THREAD, *LPSVCBATCH_THREAD;
typedef struct _SVCBATCH_PIPE {
OVERLAPPED o;
HANDLE pipe;
DWORD read;
DWORD state;
BYTE buffer[SVCBATCH_PIPE_LEN];
} SVCBATCH_PIPE, *LPSVCBATCH_PIPE;
typedef struct _SVCBATCH_PROCESS {
volatile LONG state;
PROCESS_INFORMATION pInfo;
STARTUPINFOW sInfo;
DWORD exitCode;
DWORD timeout;
DWORD argc;
DWORD optc;
LPWSTR commandLine;
LPWSTR application;
LPWSTR directory;
LPWSTR name;
LPCWSTR args[SVCBATCH_MAX_ARGS];
LPCWSTR opts[SVCBATCH_MAX_ARGS];
} SVCBATCH_PROCESS, *LPSVCBATCH_PROCESS;
typedef struct _SVCBATCH_PROCINFO
{
DWORD n;
DWORD i;
HANDLE h;
} SVCBATCH_PROCINFO, *LPSVCBATCH_PROCINFO;
typedef struct _SVCBATCH_SERVICE {
volatile LONG state;
volatile LONG check;
volatile LONG exitCode;
volatile LONG killDepth;
DWORD failMode;
DWORD timeout;
SERVICE_STATUS_HANDLE handle;
SERVICE_STATUS status;
CRITICAL_SECTION cs;
LPWSTR environment;
LPCWSTR display;
LPCWSTR name;
LPWSTR home;
LPWSTR uuid;
LPWSTR work;
LPWSTR logs;
} SVCBATCH_SERVICE, *LPSVCBATCH_SERVICE;
typedef struct _SVCBATCH_LOG {
volatile LONG64 size;
volatile HANDLE fd;
volatile LONG state;
int maxLogs;
CRITICAL_SECTION cs;
LPCWSTR logName;
LPWSTR logFile;
} SVCBATCH_LOG, *LPSVCBATCH_LOG;
/**
* Length of the shared memory data.
* Adjust this number so that SVCBATCH_IPC
* structure aligns to 64K
*/
#define SVCBATCH_DATA_LEN 32614
typedef struct _SVCBATCH_IPC {
DWORD options;
DWORD timeout;
DWORD killDepth;
DWORD maxLogs;
DWORD stdinSize;
DWORD stdinData;
DWORD display;
DWORD name;
DWORD work;
DWORD logs;
DWORD logName;
DWORD argc;
DWORD optc;
DWORD args[SVCBATCH_MAX_ARGS];
DWORD opts[SVCBATCH_MAX_ARGS];
WCHAR data[SVCBATCH_DATA_LEN];
} SVCBATCH_IPC, *LPSVCBATCH_IPC;
typedef struct _SVCBATCH_NAME_MAP {
LPCWSTR name;
int type;
int code;
} SVCBATCH_NAME_MAP, *LPSVCBATCH_NAME_MAP;
typedef struct _SVCBATCH_CONF_VALUE {
LPCWSTR name;
DWORD type;
DWORD size;
DWORD dval;
DWORD hval;
LPCWSTR sval;
LPBYTE data;
} SVCBATCH_CONF_VALUE, *LPSVCBATCH_CONF_VALUE;
typedef struct _SVCBATCH_CONF_PARAM {
int type;
int argc;
LPCWSTR key;
LPCWSTR val;
LPCWSTR args[SBUFSIZ];
} SVCBATCH_CONF_PARAM, *LPSVCBATCH_CONF_PARAM;
typedef struct _SVCBATCH_SCM_PARAMS {
int siz;
int pos;
SVCBATCH_CONF_PARAM p[SBUFSIZ];
} SVCBATCH_SCM_PARAMS, *LPSVCBATCH_SCM_PARAMS;
#if HAVE_DEBUG_TRACE
static int xtraceservice = 2;
static int xtracesvcstop = 1;
static volatile HANDLE xtracefhandle = NULL;
static CRITICAL_SECTION xtracesync;
#endif
static SYSTEM_INFO ssysteminfo;
static HANDLE processheap = NULL;
static int svcmainargc = 0;
static int stopmaxlogs = 0;
static LPCWSTR *svcmainargv = NULL;
static LPSVCBATCH_SERVICE service = NULL;
static LPSVCBATCH_PROCESS program = NULL;
static LPSVCBATCH_PROCESS cmdproc = NULL;
static LPSVCBATCH_PROCESS svcstop = NULL;
static LPSVCBATCH_LOG outputlog = NULL;
static LPSVCBATCH_IPC sharedmem = NULL;
static LPSVCBATCH_VARIABLES svariables = NULL;
static LPSVCBATCH_SCM_PARAMS scmpparams = NULL;
static LPSVCBATCH_CONF_VALUE svcpparams = NULL;
static LPSVCBATCH_CONF_VALUE svcsparams = NULL;
static LPSVCBATCH_CONF_VALUE svcparams[2];
static LPSVCBATCH_THREAD threads = NULL;
static volatile LPVOID xwsystempdir = NULL;
static volatile HANDLE wrpipehandle = NULL;
static volatile LONG runcounter = 0;
static volatile LONG uidcounter = 0;
static volatile LONG svcoptions = 0;
static volatile LONG errorreported = 0;
static LONGLONG rotateinterval = INT64_ZERO;
static LONGLONG rotatesize = INT64_ZERO;
static LARGE_INTEGER rotatetime = {{ 0, 0 }};
static DWORD svceventid = 2300;
static int servicemode = 0;
static DWORD preshutdown = 0;
static HANDLE stopstarted = NULL;
static HANDLE svcstopdone = NULL;
static HANDLE workerended = NULL;
static HANDLE dologrotate = NULL;
static HANDLE sharedmmap = NULL;
static HANDLE svclogmutex = NULL;
static LPCWSTR stoplogname = NULL;
static LPCWSTR allexportvars = L"ABDHLNRUVW";
static LPCWSTR defexportvars = L"HLNUW";
static LPCWSTR namevarset = L"BDNV";
static LPCWSTR programbase = CPP_WIDEN(SVCBATCH_BASENAME);
static LPCSTR cnamestamp = SVCBATCH_NAME " " SVCBATCH_VERSION_TXT;
static LPCWSTR hexwchars = L"0123456789abcdef";
static LPCWSTR hexuchars = L"0123456789ABCDEF";
static WCHAR zerostring[] = { 0, 0, 0, 0 };
static BYTE YCRLF[] = { 89, 13, 10, 0 };
static WCHAR CRLFW[] = { 13, 10, 0, 0 };
static LPBYTE stdindata = YCRLF;
static int stdinsize = 3;
static int xwoptind = 1;
static int xwoptend = 0;
static int xwoptarr = 0;
static LPCWSTR xwoptarg = NULL;
static LPCWSTR xwoption = NULL;
static LPCWSTR cmdoptions = L"d?hlq!s:w";
#define PROPELLER_SIZE 8
static char xpropeller[PROPELLER_SIZE] = {'|', '/', '-', '\\', '|', '/', '-', '\\'};
typedef enum {
SVCBATCH_CFG_CMD = 0,
SVCBATCH_CFG_ARGS,
SVCBATCH_CFG_HOME,
SVCBATCH_CFG_LOGS,
SVCBATCH_CFG_TEMP,
SVCBATCH_CFG_WORK,
SVCBATCH_CFG_PRESHUTDOWN,
SVCBATCH_CFG_FAILMODE,
SVCBATCH_CFG_KILLDEPTH,
SVCBATCH_CFG_SENDBREAK,
SVCBATCH_CFG_TIMEOUT,
SVCBATCH_CFG_LOCALTIME,
SVCBATCH_CFG_STDINDATA,
SVCBATCH_CFG_ENVSET,
SVCBATCH_CFG_ENVPREFIX,
SVCBATCH_CFG_ENVEXPORT,
SVCBATCH_CFG_NOLOGGING,
SVCBATCH_CFG_LOGNAME,
SVCBATCH_CFG_LOGROTATE,
SVCBATCH_CFG_ROTATEBYSIG,
SVCBATCH_CFG_ROTATEINT,
SVCBATCH_CFG_ROTATESIZE,
SVCBATCH_CFG_ROTATETIME,
SVCBATCH_CFG_MAXLOGS,
SVCBATCH_CFG_TRUNCATE,
SVCBATCH_CFG_STOP,
SVCBATCH_CFG_SLOGNAME,
SVCBATCH_CFG_SMAXLOGS,
SVCBATCH_CFG_MAX
} SVCBATCH_CFG_ID;
static SVCBATCH_NAME_MAP svccparams[] = {
{ L"Command", SVCBATCH_REG_TYPE_MSZ, SVCBATCH_CFG_CMD },
{ L"Arguments", SVCBATCH_REG_TYPE_MSZ, SVCBATCH_CFG_ARGS },
{ L"Home", SVCBATCH_REG_TYPE_SZ, SVCBATCH_CFG_HOME },
{ L"Logs", SVCBATCH_REG_TYPE_SZ, SVCBATCH_CFG_LOGS },
{ L"Temp", SVCBATCH_REG_TYPE_SZ, SVCBATCH_CFG_TEMP },
{ L"Work", SVCBATCH_REG_TYPE_SZ, SVCBATCH_CFG_WORK },
{ L"AcceptPreshutdown", SVCBATCH_REG_TYPE_BOOL, SVCBATCH_CFG_PRESHUTDOWN },
{ L"FailMode", SVCBATCH_REG_TYPE_NUM, SVCBATCH_CFG_FAILMODE },
{ L"KillDepth", SVCBATCH_REG_TYPE_NUM, SVCBATCH_CFG_KILLDEPTH },
{ L"SendBreakOnStop", SVCBATCH_REG_TYPE_BOOL, SVCBATCH_CFG_SENDBREAK },
{ L"StopTimeout", SVCBATCH_REG_TYPE_NUM, SVCBATCH_CFG_TIMEOUT },
{ L"UseLocalTime", SVCBATCH_REG_TYPE_BOOL, SVCBATCH_CFG_LOCALTIME },
{ L"StdInput", SVCBATCH_REG_TYPE_BIN, SVCBATCH_CFG_STDINDATA },
{ L"Environment", SVCBATCH_REG_TYPE_MSZ, SVCBATCH_CFG_ENVSET },
{ L"EnvironmentPrefix", SVCBATCH_REG_TYPE_SZ, SVCBATCH_CFG_ENVPREFIX },
{ L"Export", SVCBATCH_REG_TYPE_SZ, SVCBATCH_CFG_ENVEXPORT },
{ L"DisableLogging", SVCBATCH_REG_TYPE_BOOL, SVCBATCH_CFG_NOLOGGING },
{ L"LogName", SVCBATCH_REG_TYPE_SZ, SVCBATCH_CFG_LOGNAME },
{ L"LogRotate", SVCBATCH_REG_TYPE_BOOL, SVCBATCH_CFG_LOGROTATE },
{ L"LogRotateBySignal", SVCBATCH_REG_TYPE_BOOL, SVCBATCH_CFG_ROTATEBYSIG },
{ L"LogRotateInterval", SVCBATCH_REG_TYPE_NUM, SVCBATCH_CFG_ROTATEINT },
{ L"LogRotateSize", SVCBATCH_REG_TYPE_NUM, SVCBATCH_CFG_ROTATESIZE },
{ L"LogRotateTime", SVCBATCH_REG_TYPE_SZ, SVCBATCH_CFG_ROTATETIME },
{ L"MaxLogs", SVCBATCH_REG_TYPE_NUM, SVCBATCH_CFG_MAXLOGS },
{ L"TruncateLogs", SVCBATCH_REG_TYPE_BOOL, SVCBATCH_CFG_TRUNCATE },
{ L"Stop", SVCBATCH_REG_TYPE_MSZ, SVCBATCH_CFG_STOP },
{ L"StopLogName", SVCBATCH_REG_TYPE_SZ, SVCBATCH_CFG_SLOGNAME },
{ L"StopMaxLogs", SVCBATCH_REG_TYPE_NUM, SVCBATCH_CFG_SMAXLOGS },
{ NULL, 0, 0 }
};
typedef enum {
SVCBATCH_SVC_DISPLAY = 0,
SVCBATCH_SVC_PSDTIMEOUT,
#if HAVE_EXTRA_SVC_PARAMS
SVCBATCH_SVC_DESC,
SVCBATCH_SVC_IMAGEPATH,
SVCBATCH_SVC_USERNAME,
#endif
SVCBATCH_SVC_MAX
} SVCBATCH_SVC_ID;
static SVCBATCH_NAME_MAP svcbparams[] = {
{ L"DisplayName", SVCBATCH_REG_TYPE_SZ, SVCBATCH_SVC_DISPLAY },
{ L"PreshutdownTimeout", SVCBATCH_REG_TYPE_NUM, SVCBATCH_SVC_PSDTIMEOUT },
#if HAVE_EXTRA_SVC_PARAMS
{ L"Description", SVCBATCH_REG_TYPE_SZ, SVCBATCH_SVC_DESC },
{ L"ImagePath", SVCBATCH_REG_TYPE_ESZ, SVCBATCH_SVC_IMAGEPATH },
{ L"ObjectName", SVCBATCH_REG_TYPE_SZ, SVCBATCH_SVC_USERNAME },
#endif
{ NULL, 0, 0 }
};
/**
* Service Manager types
*
*/
typedef enum {
SVCBATCH_SCM_CREATE = 0,
SVCBATCH_SCM_CONFIG,
SVCBATCH_SCM_CONTROL,
SVCBATCH_SCM_DELETE,
SVCBATCH_SCM_HELP,
SVCBATCH_SCM_START,
SVCBATCH_SCM_STOP,
SVCBATCH_SCM_VERSION,
SVCBATCH_SCM_MAX
} SVCBATCH_SCM_CMD;
static LPCWSTR scmcommands[] = {
L"Create", /* SVCBATCH_SCM_CREATE */
L"Config", /* SVCBATCH_SCM_CONFIG */
L"Control", /* SVCBATCH_SCM_CONTROL */
L"Delete", /* SVCBATCH_SCM_DELETE */
L"Help", /* SVCBATCH_SCM_HELP */
L"Start", /* SVCBATCH_SCM_START */
L"Stop", /* SVCBATCH_SCM_STOP */
L"Version", /* SVCBATCH_SCM_VERSION */
NULL
};
/**
* Long options ...
*
* <option><options><option name>
*
* option: Any alphanumeric character
* mode: '.' Option without argument
* '+' Argument must be the next argument
* is empty after skipping blanks, returns ERROR_BAD_LENGTH
* ':' Argument can be part of the option separated by ':' or '='
* If the option does not end with ':' or '=', the argument is next option
* '?' Argument is optional and it must be part of the
* current option, separated by ':' or '='
*
*/
typedef struct _SVCBATCH_LONGOPT {
int option;
int mode;
LPCWSTR name;
} SVCBATCH_LONGOPT, *LPSVCBATCH_LONGOPT;
static const SVCBATCH_LONGOPT scmcoptions[] = {
{ 'b', '+', L"binpath" },
{ 'd', '+', L"description" },
{ 'D', ':', L"depend" },
{ 'n', ':', L"displayname" },
{ 'n', ':', L"name" },
{ 'p', ':', L"password" },
{ 'P', ':', L"privs" },
{ 'q', '.', L"quiet" },
{ 'r', ':', L"preshutdown" },
{ 's', '+', L"set" },
{ 't', ':', L"start" },
{ 'u', ':', L"username" },
{ 'w', '?', L"wait" },
{ 0, 0, NULL }
};
static LPCWSTR scmallowed[] = {
L"!w", /* SVCBATCH_SCM_CREATE */
L"!w", /* SVCBATCH_SCM_CONFIG */
L"q", /* SVCBATCH_SCM_CONTROL */
L"q", /* SVCBATCH_SCM_DELETE */
L"~", /* SVCBATCH_SCM_HELP */
L"qw", /* SVCBATCH_SCM_START */
L"qw", /* SVCBATCH_SCM_STOP */
L"~", /* SVCBATCH_SCM_VERSION */
NULL
};
static LPCWSTR ucenvvars[] = {
L"COMMONPROGRAMFILES",
L"COMSPEC",
L"PATH",
L"PROGRAMFILES",
L"SYSTEMDRIVE",
L"SYSTEMROOT",
L"TEMP",
L"TMP",
L"WINDIR",
NULL
};
static LPCWSTR scmsvcaccounts[] = {
L".\\LocalSystem",
L"NT AUTHORITY\\LocalService",
L"NT AUTHORITY\\NetworkService",
NULL
};
static const SVCBATCH_NAME_MAP starttypemap[] = {
{ L"Automatic", 0, SERVICE_AUTO_START },
{ L"Auto", 0, SERVICE_AUTO_START },
{ L"Delayed", 1, SERVICE_AUTO_START },
{ L"Manual", 0, SERVICE_DEMAND_START },
{ L"Demand", 0, SERVICE_DEMAND_START },
{ L"Disabled", 0, SERVICE_DISABLED },
{ NULL, 0, 0 }
};
static const SVCBATCH_NAME_MAP boolnamemap[] = {
{ L"True", 0, 1 },
{ L"False", 0, 0 },
{ L"Yes", 0, 1 },
{ L"No", 0, 0 },
{ L"On", 0, 1 },
{ L"Off", 0, 0 },
{ NULL, 0, 0 }
};
static const char *xgenerichelp =
"\nUsage:\n " SVCBATCH_NAME " [command] [service name] <option1> <option2>...\n" \
"\n Commands:" \
"\n Create.....Creates a service." \
"\n Config.....Changes the configuration of a service." \
"\n Control....Sends a control to a service." \
"\n Delete.....Deletes a service." \
"\n Help.......Print this screen and exit." \
"\n Use Help [command] for command help." \
"\n Start......Starts a service." \
"\n Stop.......Sends a STOP request to a service." \
"\n Version....Print version information." \
"\n";
#define SCM_CC_OPTIONS "\n Options:" \
"\n --binPath BinaryPathName to the .exe file." \
"\n --depend Dependencies (separated by / (forward slash))." \
"\n --description Sets the description of a service." \
"\n --displayName Sets the service display name." \
"\n --privs Sets the required privileges of a service." \
"\n --set Sets the service parameter and its value(s)." \
"\n --start Sets the service startup type." \
"\n <auto|delayed|manual|disabled> (default = manual)." \
"\n --preshutdown Sets the PreshudownTimeout in milliseconds" \
"\n used if AcceptPreshutdown is enbled." \
"\n --username The name of the account under which the service should run." \
"\n Default is LocalSystem account." \
"\n --password The password to the account name specified by the" \
"\n username parameter." \
"\n --quiet Quiet mode, do not print status or error messages."
static const char *xcommandhelp[] = {
/* Create */
"\nDescription:\n Creates a service entry in the registry and Service Database." \
"\nUsage:\n " SVCBATCH_NAME " create [service name] <options ...> <[-] arguments ...>\n" \
SCM_CC_OPTIONS \
"\n",
/* Config */
"\nDescription:\n Modifies a service entry in the registry and Service Database." \
"\nUsage:\n " SVCBATCH_NAME " config [service name] <options ...> <[-] arguments ...>\n" \
SCM_CC_OPTIONS \
"\n",
/* Control */
"\nDescription:\n Sends a CONTROL code to a service." \
"\nUsage:\n " SVCBATCH_NAME " control [service name] <options ...> [value]\n" \
"\n Options:" \
"\n --quiet Quiet mode, do not print status or error messages." \
"\n Value:" \
"\n User defined control code (128 ... 255)" \
"\n",
/* Delete */
"\nDescription:\n Deletes a service entry from the registry." \
"\nUsage:\n " SVCBATCH_NAME " delete [service name] <options ...>\n" \
"\n Options:" \
"\n --quiet Quiet mode, do not print status or error messages." \
"\n",
/* Help */
"\nDescription:\n Display command help." \
"\nUsage:\n " SVCBATCH_NAME " help <command>\n" \
"\n",
/* Start */
"\nDescription:\n Starts a service running." \
"\nUsage:\n " SVCBATCH_NAME " start [service name] <options ...> <arguments ...>\n" \
"\n Options:" \
"\n --quiet Quiet mode, do not print status or error messages." \
"\n --wait[:seconds] Wait up to seconds until the service" \
"\n enters the RUNNING state." \
"\n",
/* Stop */
"\nDescription:\n Sends a STOP control request to a service." \
"\nUsage:\n " SVCBATCH_NAME " stop [service name] <options ...> <reason> <comment>\n" \
"\n Options:" \
"\n --quiet Quiet mode, do not print status or error messages." \
"\n --wait[:seconds] Wait up to seconds for service to stop." \
"\n",
/* Version */
"\nDescription:\n Display version information." \
"\nUsage:\n " SVCBATCH_NAME " version\n" \
"\n",
NULL,
};
/**
* Message strings
*/
static const wchar_t *errmessages[] = {
NULL, /* 0 */
NULL, /* 1 */
NULL, /* 2 */
NULL, /* 3 */
NULL, /* 4 */
NULL, /* 5 */
NULL, /* 6 */
NULL, /* 7 */
NULL, /* 8 */
NULL, /* 9 */
L"The operation completed successfully", /* 10 */
L"The parameter is outside valid range", /* 11 */
NULL
};
#define XSYSTEM_MSG(_id) errmessages[_id]
static const wchar_t *wcsmessages[] = {
L"The operation completed successfully", /* 0 */
L"Service stopped", /* 1 */
L"The service is not in the RUNNING state", /* 2 */
NULL, /* 3 */
L"Environment variable prefix", /* 4 */
NULL, /* 5 */
NULL, /* 6 */
NULL, /* 7 */
NULL, /* 8 */
NULL, /* 9 */
L"The %s parameter was already defined", /* 10 */
L"The %s value is empty", /* 11 */
L"The %s value is invalid", /* 12 */
L"The %s value is outside valid range", /* 13 */
NULL, /* 14 */
NULL, /* 15 */
L"Too many arguments for the %s parameter", /* 16 */
L"Too many %s arguments", /* 17 */
NULL, /* 18 */
NULL, /* 19 */
L"The %s contains invalid characters", /* 20 */
L"The %s is too large", /* 21 */
L"Unknown command option", /* 22 */
L"The /\\:;<>?*|\" are not valid object name characters", /* 23 */
L"The maximum service name length is 256 characters", /* 24 */
NULL, /* 25 */
L"The parameter is outside valid range", /* 26 */
L"Service name starts with invalid character(s)", /* 27 */
L"The %s command option value array is not terminated", /* 28 */
L"The %s are mutually exclusive", /* 29 */
L"Unknown %s command option modifier", /* 30 */
L"The %s names are the same", /* 31 */
L"The %s are both absolute paths", /* 32 */
L"The Control code is missing. Use control [service name] [code]", /* 33 */
L"Stop the service and call Delete again", /* 34 */
L"Stop the service and call Config again", /* 35 */
NULL
};
#define SVCBATCH_MSG(_id) wcsmessages[_id]
static void xfatalerr(LPCSTR msg, int err)
{
OutputDebugStringA(">>> " SVCBATCH_NAME " " SVCBATCH_VERSION_STR "\r\n");
OutputDebugStringA(msg);
OutputDebugStringA("<<<\r\n\r\n");
_exit(err);
#if 0
TerminateProcess(GetCurrentProcess(), err);
#endif
}
static int xeexiterr(LPCSTR msg, LPCSTR opt, int err)
{
OutputDebugStringA(">>> " SVCBATCH_NAME " " SVCBATCH_VERSION_STR "\r\n");
OutputDebugStringA(msg);
OutputDebugStringA(opt);
OutputDebugStringA("<<<\r\n\r\n");
return err;
}
static void *xmmalloc(size_t size)
{
void *p;
size_t n;
n = MEM_ALIGN_DEFAULT(size);
p = HeapAlloc(processheap, HEAP_ZERO_MEMORY, n);
if (p == NULL)
SVCBATCH_FATAL(ERROR_OUTOFMEMORY);
return p;
}
static void *xmcalloc(size_t size)
{
void *p;
size_t n;
n = MEM_ALIGN_DEFAULT(size);
p = HeapAlloc(processheap, HEAP_ZERO_MEMORY, n);
if (p == NULL)
SVCBATCH_FATAL(ERROR_OUTOFMEMORY);
return p;
}
static __inline void xfree(void *m)
{
if (m != NULL)
HeapFree(processheap, 0, m);
}
static void *xrealloc(void *m, size_t size)
{
void *p;
size_t n;
if (size == 0) {
xfree(m);
return NULL;
}
n = MEM_ALIGN_DEFAULT(size);
if (m == NULL)
p = HeapAlloc( processheap, HEAP_ZERO_MEMORY, n);
else
p = HeapReAlloc(processheap, HEAP_ZERO_MEMORY, m, n);
if (p == NULL)
SVCBATCH_FATAL(ERROR_OUTOFMEMORY);
return p;
}
static __inline LPWSTR xwmalloc(size_t size)
{
return (LPWSTR)xmmalloc(size * sizeof(WCHAR));
}
static __inline LPWSTR *xwaalloc(size_t size)
{
return (LPWSTR *)xmcalloc((size + 1) * sizeof(LPWSTR));
}
static LPWSTR xwcsdup(LPCWSTR s)
{
size_t n;
LPWSTR d;
if (IS_EMPTY_WCS(s))
return NULL;
n = wcslen(s);
d = xwmalloc(n + 2);
return wmemcpy(d, s, n);
}
static LPWSTR xwcsndup(LPCWSTR s, size_t n)
{
LPWSTR d;
if (IS_EMPTY_WCS(s) || (n < 1))
return NULL;
d = xwmalloc(n + 2);
return wmemcpy(d, s, n);
}
static __inline void xmemzero(void *mem, size_t number, size_t size)
{
memset(mem, 0, number * size);
}
static __inline int xwcslen(LPCWSTR s)
{
if (IS_EMPTY_WCS(s))
return 0;
else
return (int)wcslen(s);
}
static __inline int xstrlen(LPCSTR s)
{
if (IS_EMPTY_STR(s))
return 0;
else
return (int)strlen(s);
}
static __inline int xtolower(int ch)
{
if ((ch > 64) && (ch < 91))
return ch + 32;
else
return ch;
}
static __inline int xtoupper(int ch)
{
if ((ch > 96) && (ch < 123))
return ch - 32;
else
return ch;
}
static __inline int xisupper(int ch)
{
if ((ch > 64) && (ch < 91))
return 1;
else
return 0;
}
static __inline void xwcslower(LPWSTR str)
{
for (; *str != 0; str++)
*str = xtolower(*str);
}
static __inline void xwcsupper(LPWSTR str)
{
for (; *str != 0; str++)
*str = xtoupper(*str);
}
static __inline int xisblank(int ch)
{
if ((ch > 0) && (ch < 33))
return 1;
else
return 0;
}
static __inline int xisalpha(int ch)
{
if (((ch > 64) && (ch < 91)) || ((ch > 96) && (ch < 123)))
return 1;
else
return 0;
}
static __inline int xisalnum(int ch)
{
if (((ch > 64) && (ch < 91)) || ((ch > 96) && (ch < 123)) ||
((ch > 47) && (ch < 58)))
return 1;
else
return 0;
}
static __inline int xisdigit(int ch)
{
if ((ch > 47) && (ch < 58))
return 1;
else
return 0;
}
static __inline int xisxdigit(int ch)
{
if (((ch > 47) && (ch < 58)) ||
((ch > 64) && (ch < 71)) ||
((ch > 96) && (ch < 103)))
return 1;
else
return 0;
}
static __inline int xtoxdigit(int ch)
{
if ((ch > 47) && (ch < 58))
return ch - 48;
if ((ch > 64) && (ch < 71))
return ch - 55;
if ((ch > 96) && (ch < 103))
return ch - 87;
else
return 16;
}
static __inline LPWSTR xskipblanks(LPCWSTR s)
{
if (IS_EMPTY_WCS(s))
return (LPWSTR)s;
while (xisblank(*s))
s++;
return (LPWSTR)s;
}
static __inline int xiswcschar(LPCWSTR s, WCHAR c)
{
if ((s[0] == c) && (s[1] == WNUL))
return 1;
else
return 0;
}
static __inline int xisvalidvarchar(int ch)
{
if (xisalnum(ch) || (ch == L'_'))
return 1;
else
return 0;
}
static __inline void xchrreplace(LPWSTR str, WCHAR a, WCHAR b)
{
for (; *str != WNUL; str++) {
if (*str == a)
*str = b;
}
}
static __inline void xwinpathsep(LPWSTR str)
{
for (; *str != WNUL; str++) {