-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.c
executable file
·1280 lines (1032 loc) · 41.8 KB
/
main.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
/*******************************************************************************
* Concrete Server *
* Copyright (c) 2005-2023 Raphael Prevost <raph@el.bzh> *
* *
* This software is a computer program whose purpose is to provide a *
* framework for developing and prototyping network services. *
* *
* This software is governed by the CeCILL license under French law and *
* abiding by the rules of distribution of free software. You can use, *
* modify and/ or redistribute the software under the terms of the CeCILL *
* license as circulated by CEA, CNRS and INRIA at the following URL *
* "http://www.cecill.info". *
* *
* As a counterpart to the access to the source code and rights to copy, *
* modify and redistribute granted by the license, users are provided only *
* with a limited warranty and the software's author, the holder of the *
* economic rights, and the successive licensors have only limited *
* liability. *
* *
* In this respect, the user's attention is drawn to the risks associated *
* with loading, using, modifying and/or developing or reproducing the *
* software by the user in light of its specific status of free software, *
* that may mean that it is complicated to manipulate, and that also *
* therefore means that it is reserved for developers and experienced *
* professionals having in-depth computer knowledge. Users are therefore *
* encouraged to load and test the software's suitability as regards their *
* requirements in conditions enabling the security of their systems and/or *
* data to be ensured and, more generally, to use and operate it in the *
* same conditions as regards security. *
* *
* The fact that you are presently reading this means that you have had *
* knowledge of the CeCILL license and that you accept its terms. *
* *
******************************************************************************/
#include "m_core_def.h"
#include "m_socket.h"
#include "m_plugin.h"
/* -------------------------------------------------------------------------- */
#ifndef WIN32 /* UNIX */
/* -------------------------------------------------------------------------- */
static int interrupt = 0;
/* UNIX daemon functions */
static void daemonize(int forcefork);
static void _sigusr1_handler(UNUSED int _dummy);
#ifdef __APPLE__
#define CONCRETE_OS " for Mac OS X"
#else
#define CONCRETE_OS ""
#endif
#define MAIN_PRINTVER \
"\nConcrete Server\n" \
"version "CONCRETE_VERSION" ["__DATE__"]"CONCRETE_OS"\n" \
"Copyright (c) 2005-2023 Raphael Prevost, all rights reserved.\n\n"
#define MAIN_OPTSHRT_DAEMON "-d"
#define MAIN_OPTLONG_DAEMON "--daemon"
#define MAIN_OPTSHRT_PRINTV "-v"
#define MAIN_OPTLONG_PRINTV "--version"
#if defined(_ENABLE_CONFIG) && defined(HAS_LIBXML)
#define MAIN_OPTIONS_CNFDBG "--debug"
#define MAIN_OPTIONS_CNFPRD "--production"
#endif
#define MAIN_OPTSHRT_PRINTH "-h"
#define MAIN_OPTLONG_PRINTH "--help"
#if defined(_ENABLE_CONFIG) && defined(HAS_LIBXML)
#define MAIN_PRINTHLP \
"\nConcrete Server\n" \
"version "CONCRETE_VERSION" ["__DATE__"]"CONCRETE_OS"\n" \
"Copyright (c) 2005-2023 Raphael Prevost, all rights reserved.\n\n" \
"Usage: %s [OPTION]\n" \
"Start the Concrete Server.\n" \
"\nOptions:\n\n" \
"\t"MAIN_OPTSHRT_DAEMON", "MAIN_OPTLONG_DAEMON \
"\t\tstart the server as a background process\n" \
"\t"MAIN_OPTSHRT_PRINTV", "MAIN_OPTLONG_PRINTV \
"\t\toutput version information and exit\n" \
"\t"MAIN_OPTSHRT_PRINTH", "MAIN_OPTLONG_PRINTH \
"\t\tdisplay this help and exit\n" \
"\t"MAIN_OPTIONS_CNFDBG \
"\t\t\tforcefully select the debug configuration\n" \
"\t"MAIN_OPTIONS_CNFPRD \
"\t\tforcefully select the production configuration\n\n"
#else
#define MAIN_PRINTHLP \
"\nConcrete Server\n" \
"version "CONCRETE_VERSION" ["__DATE__"]"CONCRETE_OS"\n" \
"Copyright (c) 2005-2023 Raphael Prevost, all rights reserved.\n\n" \
"Usage: %s [OPTION]\n" \
"Start the Concrete Server.\n" \
"\nOptions:\n\n" \
"\t"MAIN_OPTSHRT_DAEMON", "MAIN_OPTLONG_DAEMON \
"\t\tstart the server as a background process\n" \
"\t"MAIN_OPTSHRT_PRINTV", "MAIN_OPTLONG_PRINTV \
"\t\toutput version information and exit\n" \
"\t"MAIN_OPTSHRT_PRINTH", "MAIN_OPTLONG_PRINTH \
"\t\tdisplay this help and exit\n\n"
#endif
/* -------------------------------------------------------------------------- */
#else /* WIN32 */
/* -------------------------------------------------------------------------- */
/* WIN32 specifics */
#ifndef DISABLE_MAX_PRIVILEGE
#define DISABLE_MAX_PRIVILEGE 0x01
#endif
#define WINMAIN_SERVICENAME \
"Concrete"
#define WINMAIN_REGISTRYKEY \
"SYSTEM\\CurrentControlSet\\Services\\Concrete\\Parameters"
typedef BOOL(WINAPI * fpCreateRestrictedToken) (HANDLE, DWORD, DWORD,
PSID_AND_ATTRIBUTES,
DWORD,
PLUID_AND_ATTRIBUTES,
DWORD,
PSID_AND_ATTRIBUTES, PHANDLE);
static LPSTR service_name = NULL;
static SERVICE_STATUS_HANDLE service_controller;
static HANDLE termination_event;
/* NT service functions */
static BOOL _service_install(VOID);
static BOOL _service_uninstall(VOID);
static BOOL _service_start(VOID);
static BOOL _service_stop(VOID);
static VOID _service_status(DWORD s, DWORD r);
static VOID _service_die(VOID);
static void WINAPI _service_ctl(DWORD cmd);
static VOID WINAPI _service_main(DWORD argc, LPSTR *argv);
#define MAIN_PRINTVER \
"\nConcrete Server\n" \
"version "CONCRETE_VERSION" ["__DATE__"] for Windows NT\n" \
"Copyright (c) 2005-2023 Raphael Prevost, all rights reserved.\n\n"
#define MAIN_OPTSHRT_DAEMON "/d"
#define MAIN_OPTLONG_DAEMON "/daemon"
#define MAIN_OPTSHRT_PRINTV "/v"
#define MAIN_OPTLONG_PRINTV "/version"
#define MAIN_OPTSHRT_PRINTH "/h"
#define MAIN_OPTLONG_PRINTH "/help"
#define MAIN_OPTSHRT_INSTAL "/i"
#define MAIN_OPTLONG_INSTAL "/install"
#define MAIN_OPTSHRT_UNINST "/u"
#define MAIN_OPTLONG_UNINST "/uninstall"
#define _WIN32_OPTLONG_STRT "/start"
#define _WIN32_OPTSHRT_STRT "/s"
#define _WIN32_OPTLONG_STOP "/stop"
#define _WIN32_OPTSHRT_STOP "/q"
#define _WIN32_OPTLONG_PRIV "/privileged"
#define _WIN32_OPTSHRT_PRIV "/p"
#if defined(_ENABLE_CONFIG) && defined(HAS_LIBXML)
#define MAIN_OPTIONS_CNFDBG "/debug"
#define MAIN_OPTIONS_CNFPRD "/production"
#endif
#if defined(_ENABLE_CONFIG) && defined(HAS_LIBXML)
#define MAIN_PRINTHLP \
"\nConcrete Server\n" \
"version "CONCRETE_VERSION" ["__DATE__"] for Windows NT\n" \
"Copyright (c) 2005-2023 Raphael Prevost, all rights reserved.\n\n" \
"Usage: %s [OPTION]\n" \
"Start the Concrete Server.\n" \
"\nOptions:\n\n" \
"\t"MAIN_OPTSHRT_INSTAL", "MAIN_OPTLONG_INSTAL \
"\t\tinstall the NT service\n" \
"\t"MAIN_OPTSHRT_UNINST", "MAIN_OPTLONG_UNINST \
"\t\tuninstall the NT service\n" \
"\t"_WIN32_OPTSHRT_STRT", "_WIN32_OPTLONG_STRT \
"\t\tstart the NT service\n" \
"\t"_WIN32_OPTSHRT_STOP", "_WIN32_OPTLONG_STOP \
"\t\tstop the NT service\n" \
"\t"MAIN_OPTSHRT_PRINTV", "MAIN_OPTLONG_PRINTV \
"\t\toutput version information and exit\n" \
"\t"MAIN_OPTSHRT_PRINTH", "MAIN_OPTLONG_PRINTH \
"\t\tdisplay this help and exit\n" \
"\t"MAIN_OPTIONS_CNFDBG \
"\t\t\tforcefully select the debug configuration\n" \
"\t"MAIN_OPTIONS_CNFPRD \
"\t\tforcefully select the production configuration\n\n"
#else
#define MAIN_PRINTHLP \
"\nConcrete Server\n" \
"version "CONCRETE_VERSION" ["__DATE__"] for Windows NT\n" \
"Copyright (c) 2005-2023 Raphael Prevost, all rights reserved.\n\n" \
"Usage: %s [OPTION]\n" \
"Start the Concrete Server.\n" \
"\nOptions:\n\n" \
"\t"MAIN_OPTSHRT_INSTAL", "MAIN_OPTLONG_INSTAL \
"\t\tinstall the NT service\n" \
"\t"MAIN_OPTSHRT_UNINST", "MAIN_OPTLONG_UNINST \
"\t\tuninstall the NT service\n" \
"\t"_WIN32_OPTSHRT_STRT", "_WIN32_OPTLONG_STRT \
"\t\tstart the NT service\n" \
"\t"_WIN32_OPTSHRT_STOP", "_WIN32_OPTLONG_STOP \
"\t\tstop the NT service\n" \
"\t"MAIN_OPTSHRT_PRINTV", "MAIN_OPTLONG_PRINTV \
"\t\toutput version information and exit\n" \
"\t"MAIN_OPTSHRT_PRINTH", "MAIN_OPTLONG_PRINTH \
"\t\tdisplay this help and exit\n\n"
#endif
#ifdef _ENABLE_PRIVILEGE_SEPARATION
struct _child {
SOCKET in, out;
} child;
static VOID _spawn_child(UNUSED VOID *dummy);
#endif
/* -------------------------------------------------------------------------- */
#endif
/* -------------------------------------------------------------------------- */
/* COMMON */
static void main_process(int option_daemon, int argc, char **argv);
/* -------------------------------------------------------------------------- */
/* CONCRETE SERVER MAIN */
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
/* command line options */
int option_daemon = 0, option_version = 0, option_help = 0;
#if defined(HAS_LIBXML) && defined(_ENABLE_XML)
LIBXML_TEST_VERSION
#endif
/* eval the command line options */
while (argc --) {
if (! strcmp(argv[argc], MAIN_OPTSHRT_DAEMON) ||
! strcmp(argv[argc], MAIN_OPTLONG_DAEMON)) {
option_daemon = 1;
break;
}
#if defined(_ENABLE_CONFIG) && defined(HAS_LIBXML)
if (! strcmp(argv[argc], MAIN_OPTIONS_CNFDBG)) {
config_force_profile(CONFIG_PROFILE_DBG);
}
if (! strcmp(argv[argc], MAIN_OPTIONS_CNFPRD)) {
config_force_profile(CONFIG_PROFILE_PRD);
}
#endif
if (! strcmp(argv[argc], MAIN_OPTSHRT_PRINTV) ||
! strcmp(argv[argc], MAIN_OPTLONG_PRINTV))
option_version = 1;
if (! strcmp(argv[argc], MAIN_OPTSHRT_PRINTH) ||
! strcmp(argv[argc], MAIN_OPTLONG_PRINTH))
option_help = 1;
#ifdef WIN32
if (! strcmp(argv[argc], MAIN_OPTSHRT_INSTAL) ||
! strcmp(argv[argc], MAIN_OPTLONG_INSTAL)) {
if (_service_install()) {
printf(WINMAIN_SERVICENAME " was successfully installed.\n");
exit(EXIT_SUCCESS);
} else {
printf(WINMAIN_SERVICENAME " installation failed.\n");
exit(EXIT_FAILURE);
}
}
if (! strcmp(argv[argc], MAIN_OPTSHRT_UNINST) ||
! strcmp(argv[argc], MAIN_OPTLONG_UNINST)) {
if (_service_uninstall()) {
printf(WINMAIN_SERVICENAME " was successfully uninstalled.\n");
exit(EXIT_SUCCESS);
} else {
printf(WINMAIN_SERVICENAME " uninstallation failed.\n");
exit(EXIT_FAILURE);
}
}
if (! strcmp(argv[argc], _WIN32_OPTSHRT_STRT) ||
! strcmp(argv[argc], _WIN32_OPTLONG_STRT)) {
if (_service_start()) {
printf(WINMAIN_SERVICENAME " was successfully started.\n");
exit(EXIT_SUCCESS);
} else {
printf(WINMAIN_SERVICENAME " cannot be started.\n");
exit(EXIT_FAILURE);
}
}
if (! strcmp(argv[argc], _WIN32_OPTSHRT_STOP) ||
! strcmp(argv[argc], _WIN32_OPTLONG_STOP)) {
if (_service_uninstall()) {
printf(WINMAIN_SERVICENAME " was successfully stopped.\n");
exit(EXIT_SUCCESS);
} else {
printf(WINMAIN_SERVICENAME " cannot be stopped.\n");
exit(EXIT_FAILURE);
}
}
if (! strcmp(argv[argc], _WIN32_OPTSHRT_PRIV) ||
! strcmp(argv[argc], _WIN32_OPTLONG_PRIV)) {
option_daemon = 2;
break;
}
#endif
}
if (option_version) {
/* greeting message ! */
printf(MAIN_PRINTVER);
exit(EXIT_SUCCESS);
}
if (option_help) {
printf(MAIN_PRINTHLP, argv[0]);
exit(EXIT_SUCCESS);
}
main_process(option_daemon, argc, argv);
exit(EXIT_SUCCESS);
}
/* -------------------------------------------------------------------------- */
#ifndef WIN32
/* -------------------------------------------------------------------------- */
static void main_process(int option_daemon, UNUSED int argc, UNUSED char **argv)
{
#ifdef _ENABLE_PRIVILEGE_SEPARATION
pid_t pid = 0;
int sockpair[2];
struct passwd *nobody = NULL;
#endif
char cwd[PATH_MAX];
int syslog[2]; pid_t logger = 0;
sigset_t mask, oldmask;
/* timezone */
tzset();
if (option_daemon) daemonize(1);
else {
/* save the current directory */
if (getcwd(cwd, sizeof(cwd))) {
if (! (working_directory = malloc(strlen(cwd) + 1))) {
perror(ERR(daemonize, malloc));
} else memcpy(working_directory, cwd, strlen(cwd) + 1);
} else perror(ERR(daemonize, getcwd));
}
#ifdef _ENABLE_PRIVILEGE_SEPARATION
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockpair) == -1) {
perror(ERR(main, socketpair)); exit(EXIT_FAILURE);
}
/* fork an unprivileged child */
pid = fork();
switch (pid) {
case -1:
#ifdef DEBUG
perror(ERR(main, fork));
#endif
exit(EXIT_FAILURE);
case 0:
close(sockpair[1]);
__server_set_privileged_channel(sockpair[0]);
/* child, drop privileges */
if ( (nobody = getpwnam("nobody")) && nobody->pw_uid) {
if (setuid(nobody->pw_uid) == -1) {
perror(ERR(main, setuid));
/* try to drop to the original uid, at least */
if (setuid(getuid()) == -1) {
perror(ERR(main, setuid));
exit(EXIT_FAILURE);
}
}
} else {
/* there is no 'nobody', try to fallback to the original uid */
if (setuid(getuid()) == -1) {
perror(ERR(main, setuid));
exit(EXIT_FAILURE);
}
}
#endif
if (option_daemon) {
/* redirect stderr to syslog using the 'logger' system command */
if (pipe(syslog)) { perror(ERR(main, pipe)); exit(EXIT_FAILURE); }
if ( (logger = fork()) == 0) {
/* close the unused write descriptor of the pipe */
close(syslog[1]);
/* redirect stdin to the pipe */
if (dup2(syslog[0], STDIN_FILENO)) {
perror(ERR(main, dup2)); exit(EXIT_FAILURE);
}
/* start the logger */
if (execlp("logger", "logger", "-p", "daemon.alert", NULL)) {
perror(ERR(main, execlp)); exit(EXIT_FAILURE);
}
/* NOTREACHED */
exit(EXIT_SUCCESS);
} else if (logger == -1) {
perror(ERR(main, fork)); exit(EXIT_FAILURE);
} else {
/* close the unused read descriptor of the pipe */
close(syslog[0]);
/* redirect stderr to the logger stdin */
dup2(syslog[1], STDERR_FILENO);
}
}
if (server_init() == 0) {
if (! option_daemon) {
fprintf(stderr, "-- Interactive session - Press Q to exit.\n");
while (getchar() != 'q');
fprintf(stderr, "-- End of the interactive session\n");
} else {
/* wait for the SIGUSR1 signal */
sigemptyset(& mask); sigaddset(& mask, SIGUSR1);
signal(SIGUSR1, _sigusr1_handler);
sigprocmask(SIG_BLOCK, & mask, & oldmask);
while (! interrupt) sigsuspend(& oldmask);
sigprocmask(SIG_UNBLOCK, & mask, NULL);
}
}
server_fini();
if (option_daemon) {
/* give enough time to logger to print the
last stderr lines then kill it */
fflush(stderr); sleep(1);
kill(logger, SIGKILL); wait(NULL);
}
#ifdef _ENABLE_PRIVILEGE_SEPARATION
server_privileged_call(OP_EXIT, NULL, 0);
/* we used the same descriptor, clean only once */
close(sockpair[0]);
break;
default:
/* ignore SIGUSR1, so the child handle it */
signal(SIGUSR1, SIG_IGN);
/* father, handle privileges requests and wait for the child */
close(sockpair[0]);
__server_privileged_process(sockpair[1]);
wait(NULL);
}
#endif
free(working_directory);
}
/* -------------------------------------------------------------------------- */
static void daemonize(int forcefork)
{
/** @brief This daemonizes the current process */
pid_t pid;
struct rlimit limit;
char cwd[PATH_MAX];
/* set to background */
if (forcefork || getppid() != 1) {
switch( (pid = fork()) ) {
case -1: perror(ERR(daemonize, fork)); exit(EXIT_FAILURE); break;
case 0: break;
default: exit(EXIT_SUCCESS);
}
/* run the processus in a new session */
setpgid(0, 0);
switch( (pid = fork()) ) {
case -1: perror(ERR(daemonize, fork)); exit(EXIT_FAILURE); break;
case 0: break;
default: exit(EXIT_SUCCESS);
}
/* ignore terminal signals */
if (signal(SIGTTIN, SIG_IGN) == SIG_ERR) {
perror(ERR(daemonize, signal)); exit(EXIT_FAILURE);
}
if (signal(SIGTTOU, SIG_IGN) == SIG_ERR) {
perror(ERR(daemonize, signal)); exit(EXIT_FAILURE);
}
if (signal(SIGTSTP, SIG_IGN) == SIG_ERR) {
perror(ERR(daemonize, signal)); exit(EXIT_FAILURE);
}
if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
perror(ERR(daemonize, signal)); exit(EXIT_FAILURE);
}
}
/* save the current directory */
if (getcwd(cwd, sizeof(cwd))) {
if (! (working_directory = malloc(strlen(cwd) + 1))) {
perror(ERR(daemonize, malloc));
} else memcpy(working_directory, cwd, strlen(cwd) + 1);
} else perror(ERR(daemonize, getcwd));
/* change directory to / and close all file descriptors */
if (chdir("/")) {
perror(ERR(daemonize, chdir)); exit(EXIT_FAILURE);
}
if (getrlimit(RLIMIT_NOFILE, & limit) == -1) {
perror(ERR(daemonize, getrlimit)); exit(EXIT_FAILURE);
}
while (limit.rlim_cur --) { close(limit.rlim_cur); }
}
/* -------------------------------------------------------------------------- */
static void _sigusr1_handler(UNUSED int _dummy)
{
interrupt = 1;
}
/* -------------------------------------------------------------------------- */
#else /* WIN32 */
/* -------------------------------------------------------------------------- */
static void main_process(int option_daemon, int argc, char **argv)
{
WSADATA winsock;
HKEY key;
DWORD error = 0, len = PATH_MAX, type = 0;
char _working_directory[PATH_MAX];
#ifdef _ENABLE_PRIVILEGE_SEPARATION
SOCKET sockpair[2];
#endif
SERVICE_TABLE_ENTRY service_table[] =
{
{ WINMAIN_SERVICENAME, _service_main },
{ NULL, NULL }
};
WSAStartup(MAKEWORD(2, 0), & winsock);
/* get the working directory */
error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WINMAIN_REGISTRYKEY,
0, KEY_QUERY_VALUE, & key);
if (error != ERROR_SUCCESS) {
working_directory = ".";
fprintf(stderr, ERR(main_process, RegOpenKeyEx)": %s\n",
strerror(error));
} else {
error = RegQueryValueEx(key, "ConcretePath", 0, & type,
_working_directory, & len);
if (error != ERROR_SUCCESS) {
working_directory = ".";
fprintf(stderr, ERR(main_process, RegQueryValueEx)": %s\n",
strerror(error));
} else working_directory = (type == REG_SZ) ? _working_directory : ".";
RegCloseKey(key);
}
if (option_daemon == 1) {
#ifdef _ENABLE_PRIVILEGE_SEPARATION
/* check if the handles have been set */
if (argc - 2 <= 0) goto _end;
sockpair[1] = (SOCKET) atoi(argv[argc - 1]);
/* get the unprivileged socket */
__server_set_privileged_channel(sockpair[1]);
/* get the termination event */
termination_event = (HANDLE) atoi(argv[argc - 2]);
if (server_init() == 0) {
WaitForSingleObject(termination_event, INFINITE);
CloseHandle(termination_event);
}
server_fini();
/* tell the NT service we are shutting down */
server_privileged_call(OP_EXIT, NULL, 0);
/* close the unprivileged socket */
closesocket(sockpair[1]);
#else
printf("Please start the " WINMAIN_SERVICENAME " service "
"using the Microsoft Windows Administrative Tools.\n");
#endif
} else if (option_daemon == 2) {
#ifdef _ENABLE_PRIVILEGE_SEPARATION
/* check if the pipe handles have been set */
if (argc - 1 <= 0) goto _end;
sockpair[0] = (SOCKET) atoi(argv[argc - 1]);
/* process privilege elevation requests from the unprivileged process */
__server_privileged_process(sockpair[0]);
/* close the privileged end of the connection */
closesocket(sockpair[0]);
#else
printf("Please start the " WINMAIN_SERVICENAME " service "
"using the Microsoft Windows Administrative Tools.\n");
#endif
} else if (! StartServiceCtrlDispatcher(service_table)) {
if (GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
/* start as a regular WIN32 console application */
#ifdef _ENABLE_PRIVILEGE_SEPARATION
/* create the channel between privileged and unprivileged processes */
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockpair) == -1) goto _end;
child.in = sockpair[0]; child.out = sockpair[1];
_beginthread(_spawn_child, 0, NULL);
/* hand the unprivileged end of the connection to the server */
__server_set_privileged_channel(child.out);
if (server_init() == 0) {
fprintf(stderr, "-- Interactive session - Press Q to exit.\n");
while (getchar() != 'q');
fprintf(stderr, "-- End of the interactive session\n");
}
server_fini();
/* tell the NT service we are shutting down */
server_privileged_call(OP_EXIT, NULL, 0);
/* close the unprivileged end of the connection */
closesocket(child.out);
#else
if (server_init() == 0) {
fprintf(stderr, "-- Interactive session - Press Q to exit.\n");
while (getchar() != 'q');
fprintf(stderr, "-- End of the interactive session\n");
}
server_fini();
#endif
}
}
_end:
WSACleanup();
}
/* -------------------------------------------------------------------------- */
#ifdef _ENABLE_PRIVILEGE_SEPARATION
/* -------------------------------------------------------------------------- */
static VOID _spawn_child(UNUSED VOID *dummy)
{
CHAR buffer[PATH_MAX];
int bufsize = 0;
STARTUPINFO startup_info;
PROCESS_INFORMATION process_info;
CHAR command[PATH_MAX + PATH_MAX];
DEBUG_EVENT dbg;
/* get the current binary path */
bufsize = GetModuleFileName(NULL, buffer, sizeof(buffer));
if (bufsize == sizeof(buffer)) {
debug("_spawn_child(): path too long.\n");
_endthread();
} else if (bufsize == 0) {
debug("main_process(): cannot get path to the executable.\n");
_endthread();
}
/* build the command, passing the event and privileged socket */
_snprintf(command, sizeof(command), "\"%s\" %i /p",
buffer, child.in);
memset(& startup_info, 0, sizeof(startup_info));
memset(& process_info, 0, sizeof(process_info));
startup_info.cb = sizeof(startup_info);
if (! CreateProcess(buffer, /* module name */
command, /* command line */
NULL, /* process attr */
NULL, /* thread attr */
TRUE, /* inherit handles */
CREATE_NO_WINDOW | DEBUG_PROCESS, /* creation flags */
NULL, /* environment */
NULL, /* current directory */
& startup_info, /* startup info */
& process_info)) { /* process info */
debug("main_process(): cannot create privileged process.\n");
closesocket(child.in); closesocket(child.out);
_endthread();
}
/* useless socket */
closesocket(child.in);
do {
memset(& dbg, 0, sizeof(dbg));
WaitForDebugEvent(& dbg, INFINITE);
ContinueDebugEvent(dbg.dwProcessId, dbg.dwThreadId, DBG_CONTINUE);
} while (1);
_endthread();
}
/* -------------------------------------------------------------------------- */
#endif
/* -------------------------------------------------------------------------- */
static BOOL _service_install(VOID)
{
SC_HANDLE manager = NULL, service = NULL;
CHAR buffer[PATH_MAX];
int ret = 0;
/* get the current binary path */
ret = GetModuleFileName(NULL, buffer, sizeof(buffer));
if (ret == sizeof(buffer)) {
debug("_service_install(): path too long.\n");
return FALSE;
} else if (ret == 0) {
debug("_service_install(): cannot get path to the executable.\n");
return FALSE;
}
/* open the service control manager */
manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (! manager) {
debug("_service_install(): cannot open the SCManager.\n");
return FALSE;
}
/* try to register the new service */
service = CreateService(manager,
WINMAIN_SERVICENAME,
WINMAIN_SERVICENAME,
GENERIC_READ | GENERIC_EXECUTE,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,
buffer,
NULL,
NULL,
NULL,
NULL,
NULL);
if (! service) {
const char *err = NULL;
switch (GetLastError()) {
case ERROR_ACCESS_DENIED: err = "access denied.\n"; break;
case ERROR_DUPLICATE_SERVICE_NAME: err = "duplicate name.\n"; break;
case ERROR_SERVICE_EXISTS: err = "already installed.\n"; break;
default: err = "unknown error.\n";
}
fprintf(stderr, ERR(_service_install, CreateService)": %s", err);
CloseServiceHandle(manager);
return FALSE;
}
CloseServiceHandle(service); CloseServiceHandle(manager);
return TRUE;
}
/* -------------------------------------------------------------------------- */
static BOOL _service_uninstall(VOID)
{
SC_HANDLE manager = NULL, service = NULL;
SERVICE_STATUS status;
manager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if (! manager) {
debug("_service_uninstall(): cannot connect to the SCManager.\n");
return FALSE;
}
service = OpenService(manager,
WINMAIN_SERVICENAME, SERVICE_QUERY_STATUS | DELETE);
if (! service) {
debug("_service_uninstall(): cannot open the service.\n");
CloseServiceHandle(manager);
return FALSE;
}
if (! QueryServiceStatus(service, & status)) {
debug("_service_uninstall(): cannot get service status.\n");
CloseServiceHandle(service); CloseServiceHandle(manager);
return FALSE;
}
if (status.dwCurrentState != SERVICE_STOPPED) {
debug("_service_uninstall(): the service is still running.\n");
CloseServiceHandle(service); CloseServiceHandle(manager);
return FALSE;
}
if (! DeleteService(service)) {
const char *err = NULL;
switch (GetLastError()) {
case ERROR_ACCESS_DENIED: err = "access denied.\n"; break;
case ERROR_INVALID_HANDLE: err = "invalid handle.\n"; break;
case ERROR_SERVICE_MARKED_FOR_DELETE: err = "already deleted.\n"; break;
default: "unknown error.\n";
}
fprintf(stderr, ERR(_service_uninstall, DeleteService)": %s", err);
CloseServiceHandle(service); CloseServiceHandle(manager);
return FALSE;
}
CloseServiceHandle(service); CloseServiceHandle(manager);
return TRUE;
}
/* -------------------------------------------------------------------------- */
static BOOL _service_start(VOID)
{
SC_HANDLE manager = NULL, service = NULL;
manager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if (! manager) {
debug("_service_start(): cannot connect to the SCManager.\n");
return FALSE;
}
service = OpenService(manager, WINMAIN_SERVICENAME, SERVICE_START);
if (! service) {
debug("_service_start(): cannot open the service.\n");
CloseServiceHandle(manager);
return FALSE;
}
if (! StartService(service, 0, 0)) {
debug("_service_start(): cannot start the service.\n");
CloseServiceHandle(service);
CloseServiceHandle(manager);
return FALSE;
}
CloseServiceHandle(service);
CloseServiceHandle(manager);
return TRUE;
}
/* -------------------------------------------------------------------------- */
static BOOL _service_stop(VOID)
{
SC_HANDLE manager = NULL, service = NULL;
SERVICE_STATUS status;
manager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if (! manager) {
debug("_service_stop(): cannot connect to the SCManager.\n");
return FALSE;
}
service = OpenService(manager, WINMAIN_SERVICENAME, SERVICE_STOP);
if (! service) {
debug("_service_stop(): cannot open the service.\n");
CloseServiceHandle(manager);
return FALSE;
}
if (! ControlService(service, SERVICE_CONTROL_STOP, & status)) {
debug("_service_stop(): cannot stop the service.\n");
CloseServiceHandle(service);
CloseServiceHandle(manager);
return FALSE;
}
CloseServiceHandle(service);
CloseServiceHandle(manager);
return TRUE;
}
/* -------------------------------------------------------------------------- */
static VOID _service_status(DWORD s, DWORD r)
{
SERVICE_STATUS state;
if (s == SERVICE_START_PENDING)
state.dwControlsAccepted = 0;
else
state.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
state.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
state.dwServiceSpecificExitCode = 0;
state.dwCurrentState = s; state.dwWin32ExitCode = r;
state.dwCheckPoint = 0; state.dwWaitHint = 0;
/* report service status to the service controller */
if (! SetServiceStatus(service_controller, & state)) _service_die();
}
/* -------------------------------------------------------------------------- */
static VOID _service_die(VOID)
{
_service_status(SERVICE_STOP_PENDING, NO_ERROR);
if (termination_event) CloseHandle(termination_event);
_service_status(SERVICE_STOPPED, GetLastError());
/* is that right ? */
exit(EXIT_FAILURE);
}
/* -------------------------------------------------------------------------- */
static void WINAPI _service_ctl(DWORD cmd)
{
DWORD state = SERVICE_RUNNING;
if (cmd == SERVICE_CONTROL_STOP || cmd == SERVICE_CONTROL_SHUTDOWN)
state = SERVICE_STOP_PENDING;
_service_status(state, NO_ERROR);
if (state == SERVICE_STOP_PENDING)
SetEvent(termination_event);
}
/* -------------------------------------------------------------------------- */
static VOID WINAPI _service_main(DWORD argc, LPSTR *argv)
{
SECURITY_ATTRIBUTES sec_attr;
#ifdef _ENABLE_PRIVILEGE_SEPARATION
HANDLE advapi32;
fpCreateRestrictedToken _CreateRestrictedToken = NULL;
HANDLE process_token, restricted_token;
SID_IDENTIFIER_AUTHORITY nt = { SECURITY_NT_AUTHORITY };
SID_AND_ATTRIBUTES drop_sids[2];