aboutsummaryrefslogtreecommitdiff
path: root/src/runscript.c
blob: c82c5f9a808745a037c7a9a2b074797826e63c8d (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
/*
 * runscript.c
 * Handle launching of Gentoo init scripts.
 *
 * Copyright 1999-2007 Gentoo Foundation
 * Distributed under the terms of the GNU General Public License v2
 */

#define APPLET "runscript"

#include <sys/types.h>
#include <sys/signal.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <dlfcn.h>
#include <errno.h>
#include <getopt.h>
#include <libgen.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "einfo.h"
#include "rc.h"
#include "rc-misc.h"
#include "rc-plugin.h"
#include "strlist.h"

#define RCSCRIPT_HELP   RC_LIBDIR "/sh/rc-help.sh"
#define SELINUX_LIB     RC_LIBDIR "/runscript_selinux.so"

static char *applet = NULL;
static char *exclusive = NULL;
static char *mtime_test = NULL;
static rc_depinfo_t *deptree = NULL;
static char **services = NULL;
static char **svclist = NULL;
static char **tmplist = NULL;
static char **providelist = NULL;
static char **types = NULL;
static char **restart_services = NULL;
static char **need_services = NULL;
static char **env = NULL;
static char *tmp = NULL;
static char *softlevel = NULL;
static bool sighup = false;
static char *ibsave = NULL;
static bool in_background = false;
static rc_hook_t hook_out = 0;

extern char **environ;

#ifdef __linux__
static void (*selinux_run_init_old) (void);
static void (*selinux_run_init_new) (int argc, char **argv);

void setup_selinux (int argc, char **argv);
#endif

#ifdef __linux__
void setup_selinux (int argc, char **argv)
{
	void *lib_handle = NULL;

	lib_handle = dlopen (SELINUX_LIB, RTLD_NOW | RTLD_GLOBAL);
	if (lib_handle) {
		/*
		 * FIXME: the below code generates the warning
		 * ISO C forbids assignment between function pointer and 'void *'
		 * which sucks ass
		 * http://www.opengroup.org/onlinepubs/009695399/functions/dlsym.html
		 */
		selinux_run_init_old = dlsym (lib_handle, "selinux_runscript");
		selinux_run_init_new = dlsym (lib_handle, "selinux_runscript2");

		/* Use new run_init if it rc_exists, else fall back to old */
		if (selinux_run_init_new)
			selinux_run_init_new (argc, argv);
		else if (selinux_run_init_old)
			selinux_run_init_old ();
		else
			/* This shouldnt happen... probably corrupt lib */
			eerrorx ("run_init is missing from runscript_selinux.so!");
	}
}
#endif

static void handle_signal (int sig)
{
	pid_t pid;
	int status;
	int serrno = errno;
	char signame[10] = { '\0' };

	switch (sig) {
		case SIGHUP:
			sighup = true;
			break;

		case SIGCHLD:
			do {
				pid = waitpid (-1, &status, WNOHANG);
				if (pid < 0) {
					if (errno != ECHILD)
						eerror ("waitpid: %s", strerror (errno));
					return;
				}
			} while (! WIFEXITED (status) && ! WIFSIGNALED (status));
			break;

		case SIGINT:
			if (! signame[0])
				snprintf (signame, sizeof (signame), "SIGINT");
		case SIGTERM:
			if (! signame[0])
				snprintf (signame, sizeof (signame), "SIGTERM");
		case SIGQUIT:
			if (! signame[0])
				snprintf (signame, sizeof (signame), "SIGQUIT");
			eerrorx ("%s: caught %s, aborting", applet, signame);

		default:
			eerror ("%s: caught unknown signal %d", applet, sig);
	}

	/* Restore errno */
	errno = serrno;
}

static time_t get_mtime (const char *pathname, bool follow_link)
{
	struct stat buf;
	int retval;

	if (! pathname)
		return (0);

	retval = follow_link ? stat (pathname, &buf) : lstat (pathname, &buf);
	if (! retval)
		return (buf.st_mtime);

	errno = 0;
	return (0);
}

static bool in_control ()
{
	char *path;
	time_t mtime;
	const char *tests[] = { "starting", "started", "stopping",
		"inactive", "wasinactive", NULL };
	int i = 0;

	if (sighup)
		return (false);

	if (! mtime_test || ! rc_exists (mtime_test))
		return (false);

	if (rc_service_state (applet, rc_service_stopped))
		return (false);

	if (! (mtime = get_mtime (mtime_test, false)))
		return (false);

	while (tests[i]) {
		path = rc_strcatpaths (RC_SVCDIR, tests[i], applet, (char *) NULL);
		if (rc_exists (path)) {
			time_t m = get_mtime (path, false);
			if (mtime < m && m != 0) {
				free (path);
				return (false);
			}
		}
		free (path);
		i++;
	}

	return (true);
}

static void uncoldplug (char *service)
{
	char *cold = rc_strcatpaths (RC_SVCDIR "coldplugged", basename (service),
								 (char *) NULL);
	if (rc_exists (cold) && unlink (cold) != 0)
		eerror ("%s: unlink `%s': %s", applet, cold, strerror (errno));
	free (cold);
}

static void cleanup (void)
{
	/* Flush our buffered output if any */
	eflush ();

	if (hook_out)
		rc_plugin_run (hook_out, applet);
	rc_plugin_unload ();

	if (deptree)
		rc_free_deptree (deptree);
	if (services)
		rc_strlist_free (services);
	if (types)
		rc_strlist_free (types);
	if (svclist)
		rc_strlist_free (svclist);
	if (providelist)
		rc_strlist_free (providelist);
	if (restart_services)
		rc_strlist_free (restart_services);
	if (need_services)
		rc_strlist_free (need_services);
	if (tmplist)
		rc_strlist_free (tmplist);
	if (ibsave)
		free (ibsave);

	if (in_control ()) {
		if (rc_service_state (applet, rc_service_stopping)) {
			/* If the we're shutting down, do it cleanly */
			if ((softlevel &&
				 rc_runlevel_stopping () &&
				 (strcmp (softlevel, RC_LEVEL_SHUTDOWN) == 0 ||
				  strcmp (softlevel, RC_LEVEL_REBOOT) == 0)))
				rc_mark_service (applet, rc_service_stopped);
			else if (rc_service_state (applet, rc_service_wasinactive))
				rc_mark_service (applet, rc_service_inactive);
			else
				rc_mark_service (applet, rc_service_started);
		}
		else if (rc_service_state (applet, rc_service_starting))
		{
			if (rc_service_state (applet, rc_service_wasinactive))
				rc_mark_service (applet, rc_service_inactive);
			else 
				rc_mark_service (applet, rc_service_stopped);
		}
		if (exclusive && rc_exists (exclusive))
			unlink (exclusive);
	}

	if (env)
		rc_strlist_free (env);

	if (mtime_test)
	{
		unlink (mtime_test);
		free (mtime_test);
	}
	if (exclusive)
		free (exclusive);

	if (applet)
		free (applet);
}

static bool svc_exec (const char *service, const char *arg1, const char *arg2)
{
	int status = 0;
	pid_t pid;

	/* We need to disable our child signal handler now so we block
	   until our script returns. */
	signal (SIGCHLD, NULL);

	pid = vfork();

	if (pid == -1)
		eerrorx ("%s: vfork: %s", service, strerror (errno));
	if (pid == 0) {
		if (rc_exists (RC_SVCDIR "runscript.sh")) {
			execl (RC_SVCDIR "runscript.sh", service, service, arg1, arg2,
				   (char *) NULL);
			eerror ("%s: exec `" RC_SVCDIR "runscript.sh': %s",
					 service, strerror (errno));
			_exit (EXIT_FAILURE);
		} else {
			execl (RC_LIBDIR "sh/runscript.sh", service, service, arg1, arg2,
				   (char *) NULL);
			eerror ("%s: exec `" RC_LIBDIR "sh/runscript.sh': %s",
					 service, strerror (errno));
			_exit (EXIT_FAILURE);
		}
	}

	do {
		if (waitpid (pid, &status, 0) < 0) {
			if (errno != ECHILD)
				eerror ("waitpid: %s", strerror (errno));
			break;
		}
	} while (! WIFEXITED (status) && ! WIFSIGNALED (status));

	/* Done, so restore the signal handler */
	signal (SIGCHLD, handle_signal);

	if (WIFEXITED (status))
		return (WEXITSTATUS (status) ? false : true);

	return (false);
}

static rc_service_state_t svc_status (const char *service)
{
	char status[10];
	int (*e) (const char *fmt, ...) = &einfo;

	rc_service_state_t retval = rc_service_stopped;

	if (rc_service_state (service, rc_service_stopping)) {
		snprintf (status, sizeof (status), "stopping");
		e = &ewarn;
		retval = rc_service_stopping;
	} else if (rc_service_state (service, rc_service_starting)) {
		snprintf (status, sizeof (status), "starting");
		e = &ewarn;
		retval = rc_service_starting;
	} else if (rc_service_state (service, rc_service_inactive)) {
		snprintf (status, sizeof (status), "inactive");
		e = &ewarn;
		retval = rc_service_inactive;
	} else if (rc_service_state (service, rc_service_crashed)) {
		snprintf (status, sizeof (status), "crashed");
		e = &eerror;
		retval = rc_service_crashed;
	} else if (rc_service_state (service, rc_service_started)) {
		snprintf (status, sizeof (status), "started");
		retval = rc_service_started;
	} else
		snprintf (status, sizeof (status), "stopped");

	e ("status: %s", status);
	return (retval);
}

static void make_exclusive (const char *service)
{
	char *path;
	int i;

	/* We create a fifo so that other services can wait until we complete */
	if (! exclusive)
		exclusive = rc_strcatpaths (RC_SVCDIR, "exclusive", applet, (char *) NULL);

	if (mkfifo (exclusive, 0600) != 0 && errno != EEXIST &&
		(errno != EACCES || geteuid () == 0))
		eerrorx ("%s: unable to create fifo `%s': %s",
				 applet, exclusive, strerror (errno));

	path = rc_strcatpaths (RC_SVCDIR, "exclusive", applet, (char *) NULL);
	i = strlen (path) + 16;
	mtime_test = rc_xmalloc (sizeof (char *) * i);
	snprintf (mtime_test, i, "%s.%d", path, getpid ());
	free (path);

	if (rc_exists (mtime_test) && unlink (mtime_test) != 0) {
		eerror ("%s: unlink `%s': %s",
				applet, mtime_test, strerror (errno));
		free (mtime_test);
		mtime_test = NULL;
		return;
	}

	if (symlink (service, mtime_test) != 0) {
		eerror ("%s: symlink `%s' to `%s': %s",
				applet, service, mtime_test, strerror (errno));
		free (mtime_test);
		mtime_test = NULL;
	}
}

static void unlink_mtime_test ()
{
	if (unlink (mtime_test) != 0)
		eerror ("%s: unlink `%s': %s", applet, mtime_test, strerror (errno));
	free (mtime_test);
	mtime_test = NULL;
}

static void get_started_services ()
{
	char *service;
	int i;

	rc_strlist_free (tmplist);
	tmplist = rc_services_in_state (rc_service_inactive);

	rc_strlist_free (restart_services);
	restart_services = rc_services_in_state (rc_service_started);

	STRLIST_FOREACH (tmplist, service, i)
		restart_services = rc_strlist_addsort (restart_services, service);

	rc_strlist_free (tmplist);
	tmplist = NULL;
}

static void svc_start (const char *service, bool deps)
{
	bool started;
	bool background = false;
	char *svc;
	char *svc2;
	int i;
	int j;
	int depoptions = RC_DEP_TRACE;

	rc_plugin_run (rc_hook_service_start_in, applet);
	hook_out = rc_hook_service_start_out;

	if (rc_is_env ("RC_STRICT_DEPEND", "yes"))
		depoptions |= RC_DEP_STRICT;

	if (rc_is_env ("IN_HOTPLUG", "1") || in_background) {
		if (! rc_service_state (service, rc_service_inactive) &&
			! rc_service_state (service, rc_service_stopped))
			exit (EXIT_FAILURE);
		background = true;
	}

	if (rc_service_state (service, rc_service_started))
		ewarnx ("WARNING: %s has already been started", applet);
	else if (rc_service_state (service, rc_service_starting))
		ewarnx ("WARNING: %s is already starting", applet);
	else if (rc_service_state (service, rc_service_stopping))
		ewarnx ("WARNING: %s is stopping", applet);
	else if (rc_service_state (service, rc_service_inactive) && ! background)
		ewarnx ("WARNING: %s has already started, but is inactive", applet);

	if (! rc_mark_service (service, rc_service_starting))
		eerrorx ("ERROR: %s has been started by something else", applet);

	make_exclusive (service);

	if (deps) {
		if (! deptree && ((deptree = rc_load_deptree ()) == NULL))
			eerrorx ("failed to load deptree");

		rc_strlist_free (types);
		types = rc_strlist_add (NULL, "broken");
		rc_strlist_free (svclist);
		svclist = rc_strlist_add (NULL, applet);
		rc_strlist_free (services);
		services = rc_get_depends (deptree, types, svclist, softlevel, 0);
		if (services) {
			eerrorn ("ERROR: `%s' needs ", applet);
			STRLIST_FOREACH (services, svc, i) {
				if (i > 0)
					fprintf (stderr, ", ");
				fprintf (stderr, "%s", svc);
			}
			exit (EXIT_FAILURE);
		}
		rc_strlist_free (services);
		services = NULL;

		rc_strlist_free (types);
		types = rc_strlist_add (NULL, "ineed");
		rc_strlist_free (need_services);
		need_services = rc_get_depends (deptree, types, svclist,
										softlevel, depoptions);
		types = rc_strlist_add (types, "iuse");
		if (! rc_runlevel_starting ()) {
			services = rc_get_depends (deptree, types, svclist,
									   softlevel, depoptions);
			STRLIST_FOREACH (services, svc, i)
				if (rc_service_state (svc, rc_service_stopped))
					rc_start_service (svc);

			rc_strlist_free (services);
		}

		/* Now wait for them to start */
		types = rc_strlist_add (types, "iafter");
		services = rc_get_depends (deptree, types, svclist,
								   softlevel, depoptions);

		/* We use tmplist to hold our scheduled by list */
		rc_strlist_free (tmplist);
		tmplist = NULL;

		STRLIST_FOREACH (services, svc, i) {
			if (rc_service_state (svc, rc_service_started))
				continue;
			if (! rc_wait_service (svc))
				eerror ("%s: timed out waiting for %s", applet, svc);
			if (rc_service_state (svc, rc_service_started))
				continue;

			STRLIST_FOREACH (need_services, svc2, j)
				if (strcmp (svc, svc2) == 0) {
					if (rc_service_state (svc, rc_service_inactive) ||
						rc_service_state (svc, rc_service_wasinactive))
						tmplist = rc_strlist_add (tmplist, svc);
					else
						eerrorx ("ERROR: cannot start %s as %s would not start",
								 applet, svc);
				}
		}

		if (tmplist) {
			int n = 0;
			int len = 0;
			char *p;

			/* Set the state now, then unlink our exclusive so that
			   our scheduled list is preserved */
			rc_mark_service (service, rc_service_stopped);
			unlink_mtime_test ();

			rc_strlist_free (types);
			types = rc_strlist_add (NULL, "iprovide");
			STRLIST_FOREACH (tmplist, svc, i) {
				rc_schedule_start_service (svc, service);

				rc_strlist_free (svclist);
				svclist = rc_strlist_add (NULL, svc);
				rc_strlist_free (providelist);
				providelist = rc_get_depends (deptree, types, svclist,
											  softlevel, depoptions);
				STRLIST_FOREACH (providelist, svc2, j) 
					rc_schedule_start_service (svc2, service);

				len += strlen (svc) + 2;
				n++;
			}

			len += 5;
			tmp = rc_xmalloc (sizeof (char *) * len);
			p = tmp;
			STRLIST_FOREACH (tmplist, svc, i) {
				if (i > 1) {
					if (i == n - 1)
						p += snprintf (p, len, " or ");
					else
						p += snprintf (p, len, ", ");
				}
				p += snprintf (p, len, "%s", svc);
			}
			ewarnx ("WARNING: %s is scheduled to start when %s has started",
					applet, tmp);
		}

		rc_strlist_free (services);
		services = NULL;
		rc_strlist_free (types);
		types = NULL;
		rc_strlist_free (svclist);
		svclist = NULL;
	}

	if (ibsave)
		setenv ("IN_BACKGROUND", ibsave, 1);
	rc_plugin_run (rc_hook_service_start_now, applet);
	started = svc_exec (service, "start", NULL);
	if (ibsave)
		unsetenv ("IN_BACKGROUND");

	if (in_control ()) {
		if (! started) {
			if (rc_service_state (service, rc_service_wasinactive))
				rc_mark_service (service, rc_service_inactive);
			else {
				rc_mark_service (service, rc_service_stopped);
				if (rc_runlevel_starting ())
					rc_mark_service (service, rc_service_failed);
			}
			rc_plugin_run (rc_hook_service_start_done, applet);
			eerrorx ("ERROR: %s failed to start", applet);
		}
		rc_mark_service (service, rc_service_started);
		unlink_mtime_test ();
		rc_plugin_run (rc_hook_service_start_done, applet);
	} else {
		rc_plugin_run (rc_hook_service_start_done, applet);
		if (rc_service_state (service, rc_service_inactive))
			ewarnx ("WARNING: %s has started, but is inactive", applet);
		else
			ewarnx ("WARNING: %s not under our control, aborting", applet);
	}

	/* Now start any scheduled services */
	rc_strlist_free (services);
	services = rc_services_scheduled (service);
	STRLIST_FOREACH (services, svc, i)
		if (rc_service_state (svc, rc_service_stopped))
			rc_start_service (svc);
	rc_strlist_free (services);
	services = NULL;

	/* Do the same for any services we provide */
	rc_strlist_free (types);
	types = rc_strlist_add (NULL, "iprovide");
	rc_strlist_free (svclist);
	svclist = rc_strlist_add (NULL, applet);
	rc_strlist_free (tmplist);
	tmplist = rc_get_depends (deptree, types, svclist, softlevel, depoptions);

	STRLIST_FOREACH (tmplist, svc2, j) {
		rc_strlist_free (services);
		services = rc_services_scheduled (svc2);
		STRLIST_FOREACH (services, svc, i)
			if (rc_service_state (svc, rc_service_stopped))
				rc_start_service (svc);
	}

	hook_out = 0;
	rc_plugin_run (rc_hook_service_start_out, applet);
}

static void svc_stop (const char *service, bool deps)
{
	bool stopped;

	hook_out = rc_hook_service_stop_out;

	if (rc_runlevel_stopping () &&
		rc_service_state (service, rc_service_failed))
		exit (EXIT_FAILURE);

	if (rc_is_env ("IN_HOTPLUG", "1") || in_background)
		if (! rc_service_state (service, rc_service_started) && 
			! rc_service_state (service, rc_service_inactive))
			exit (EXIT_FAILURE);

	if (rc_service_state (service, rc_service_stopped))
		ewarnx ("WARNING: %s is already stopped", applet);
	else if (rc_service_state (service, rc_service_stopping))
		ewarnx ("WARNING: %s is already stopping", applet);

	if (! rc_mark_service (service, rc_service_stopping))
		eerrorx ("ERROR: %s has been stopped by something else", applet);

	make_exclusive (service);

	if (! rc_runlevel_stopping () &&
		rc_service_in_runlevel (service, RC_LEVEL_BOOT))
		ewarn ("WARNING: you are stopping a boot service");

	if (deps || ! rc_service_state (service, rc_service_wasinactive)) {
		int depoptions = RC_DEP_TRACE;
		char *svc;
		int i;

		if (rc_is_env ("RC_STRICT_DEPEND", "yes"))
			depoptions |= RC_DEP_STRICT;

		if (! deptree && ((deptree = rc_load_deptree ()) == NULL))
			eerrorx ("failed to load deptree");

		rc_strlist_free (types);
		types = rc_strlist_add (NULL, "needsme");
		rc_strlist_free (svclist);
		svclist = rc_strlist_add (NULL, applet);
		rc_strlist_free (tmplist);
		tmplist = NULL;
		rc_strlist_free (services);
		services = rc_get_depends (deptree, types, svclist,
								   softlevel, depoptions);
		rc_strlist_reverse (services);
		STRLIST_FOREACH (services, svc, i) {
			if (rc_service_state (svc, rc_service_started) || 
				rc_service_state (svc, rc_service_inactive))
			{
				rc_wait_service (svc);
				if (rc_service_state (svc, rc_service_started) || 
					rc_service_state (svc, rc_service_inactive))
				{
					rc_stop_service (svc);
					tmplist = rc_strlist_add (tmplist, svc);
				}
			}
		}
		rc_strlist_free (services);
		services = NULL;

		STRLIST_FOREACH (tmplist, svc, i) {
			if (rc_service_state (svc, rc_service_stopped))
				continue;

			/* We used to loop 3 times here - maybe re-do this if needed */
			rc_wait_service (svc);
			if (! rc_service_state (svc, rc_service_stopped)) {
				if (rc_runlevel_stopping ())
					rc_mark_service (svc, rc_service_failed);
				eerrorx ("ERROR:  cannot stop %s as %s is still up",
						 applet, svc);
			}
		}
		rc_strlist_free (tmplist);
		tmplist = NULL;

		/* We now wait for other services that may use us and are stopping
		   This is important when a runlevel stops */
		types = rc_strlist_add (types, "usesme");
		types = rc_strlist_add (types, "ibefore");
		services = rc_get_depends (deptree, types, svclist,
								   softlevel, depoptions);
		STRLIST_FOREACH (services, svc, i) {
			if (rc_service_state (svc, rc_service_stopped))
				continue;
			rc_wait_service (svc);
		}

		rc_strlist_free (services);
		services = NULL;
		rc_strlist_free (types);
		types = NULL;
	}

	if (ibsave)
		setenv ("IN_BACKGROUND", ibsave, 1);
	rc_plugin_run (rc_hook_service_stop_now, applet);
	stopped = svc_exec (service, "stop", NULL);
	if (ibsave)
		unsetenv ("IN_BACKGROUND");

	if (! in_control ()) {
		rc_plugin_run (rc_hook_service_stop_done, applet);
		ewarnx ("WARNING: %s not under our control, aborting", applet);
	}

	if (! stopped) {
		if (rc_service_state (service, rc_service_wasinactive))
			rc_mark_service (service, rc_service_inactive);
		else
			rc_mark_service (service, rc_service_started);
		rc_plugin_run (rc_hook_service_stop_done, applet);
		eerrorx ("ERROR: %s failed to stop", applet);
	}

	if (in_background)
		rc_mark_service (service, rc_service_inactive);
	else
		rc_mark_service (service, rc_service_stopped);

	unlink_mtime_test ();
	rc_plugin_run (rc_hook_service_stop_done, applet);
	hook_out = 0;
	rc_plugin_run (rc_hook_service_stop_out, applet);
}

static void svc_restart (const char *service, bool deps)
{
	char *svc;
	int i;
	bool inactive = false;

	/* This is hairly and a better way needs to be found I think!
	   The issue is this - openvpn need net and dns. net can restart
	   dns via resolvconf, so you could have openvpn trying to restart dnsmasq
	   which in turn is waiting on net which in turn is waiting on dnsmasq.
	   The work around is for resolvconf to restart it's services with --nodeps
	   which means just that. The downside is that there is a small window when
	   our status is invalid.
	   One workaround would be to introduce a new status, or status locking. */
	if (! deps) {
		if (rc_service_state (service, rc_service_started) ||
			rc_service_state (service, rc_service_inactive))
			svc_exec (service, "stop", "start");
		else
			svc_exec (service, "start", NULL);
		return;
	}

	if (! rc_service_state (service, rc_service_stopped)) {
		get_started_services ();
		svc_stop (service, deps);

		/* Flush our buffered output if any */
		eflush ();
	}

	svc_start (service, deps);

	inactive = rc_service_state (service, rc_service_inactive);
	if (! inactive)
		inactive = rc_service_state (service, rc_service_wasinactive);

	if (inactive ||
		rc_service_state (service, rc_service_starting) ||
		rc_service_state (service, rc_service_started))
	{
		STRLIST_FOREACH (restart_services, svc, i) {
			if (rc_service_state (svc, rc_service_stopped)) {
				if (inactive) {
					rc_schedule_start_service (service, svc);
					ewarn ("WARNING: %s is scheduled to started when %s has started",
						   svc, applet);
				} else
					rc_start_service (svc);
			}
		}
	}
}

#define getoptstring "dCDNqvh"
static struct option longopts[] = {
	{ "debug",      0, NULL, 'd'},
	{ "nocolor",    0, NULL, 'C'},
	{ "nocolour",   0, NULL, 'C'},
	{ "nodeps",     0, NULL, 'D'},
	{ "quiet",      0, NULL, 'q'},
	{ "verbose",    0, NULL, 'v'},
	{ "help",       0, NULL, 'h'},
	{ NULL,         0, NULL, 0}
};
// #include "_usage.c"

int main (int argc, char **argv)
{
	char *service = argv[1];
	int i;
	bool deps = true;
	bool doneone = false;
	char pid[16];
	int retval;
	char c;

	/* Show help if insufficient args */
	if (argc < 3) {
		execl (RCSCRIPT_HELP, RCSCRIPT_HELP, service, (char *) NULL);
		eerrorx ("%s: failed to exec `" RCSCRIPT_HELP "': %s",
				 applet, strerror (errno));
	}

	applet = rc_xstrdup (basename (service));
	atexit (cleanup);

#ifdef __linux__
	/* coldplug events can trigger init scripts, but we don't want to run them
	   until after rc sysinit has completed so we punt them to the boot runlevel */
	if (rc_exists ("/dev/.rcsysinit")) {
		eerror ("%s: cannot run until sysvinit completes", applet);
		if (mkdir ("/dev/.rcboot", 0755) != 0 && errno != EEXIST)
			eerrorx ("%s: mkdir `/dev/.rcboot': %s", applet, strerror (errno));
		tmp = rc_strcatpaths ("/dev/.rcboot", applet, (char *) NULL);
		symlink (service, tmp);
		exit (EXIT_FAILURE);
	}
#endif

	if ((softlevel = getenv ("RC_SOFTLEVEL")) == NULL) {
		/* Ensure our environment is pure
		   Also, add our configuration to it */
		env = rc_filter_env ();
		env = rc_config_env (env);

		if (env) {
			char *p;

#ifdef __linux__
			/* clearenv isn't portable, but there's no harm in using it
			   if we have it */
			clearenv ();
#else
			char *var;
			/* No clearenv present here then.
			   We could manipulate environ directly ourselves, but it seems that
			   some kernels bitch about this according to the environ man pages
			   so we walk though environ and call unsetenv for each value. */
			while (environ[0]) {
				tmp = rc_xstrdup (environ[0]);
				p = tmp;
				var = strsep (&p, "=");
				unsetenv (var);
				free (tmp);
			}
			tmp = NULL;
#endif

			STRLIST_FOREACH (env, p, i)
				putenv (p);

			/* We don't free our list as that would be null in environ */
		}

		softlevel = rc_get_runlevel ();

		/* If not called from RC or another service then don't be parallel */
		unsetenv ("RC_PARALLEL_STARTUP");
	}

	setenv ("RC_ELOG", service, 1);
	setenv ("SVCNAME", applet, 1);

	/* Set an env var so that we always know our pid regardless of any
	   subshells the init script may create so that our mark_service_*
	   functions can always instruct us of this change */
	snprintf (pid, sizeof (pid), "%d", (int) getpid ());
	setenv ("RC_RUNSCRIPT_PID", pid, 1);

	if (rc_is_env ("RC_PARALLEL_STARTUP", "yes")) {
		char ebname[PATH_MAX];
		char *eb;

		snprintf (ebname, sizeof (ebname), "%s.%s", applet, pid);
		eb = rc_strcatpaths (RC_SVCDIR "ebuffer", ebname, (char *) NULL);
		setenv ("RC_EBUFFER", eb, 1);
		free (eb);
	}

#ifdef __linux__
	/* Ok, we are ready to go, so setup selinux if applicable */
	setup_selinux (argc, argv);
#endif

	/* Punt the first arg as it's our service name */
	argc--;
	argv++;

	/* Right then, parse any options there may be */
	while ((c = getopt_long (argc, argv, getoptstring,
							 longopts, (int *) 0)) != -1)
		switch (c) {
			case 'd':
				setenv ("RC_DEBUG", "yes", 1);
				break;
			case 'h':
				execl (RCSCRIPT_HELP, RCSCRIPT_HELP, service, (char *) NULL);
				eerrorx ("%s: failed to exec `" RCSCRIPT_HELP "': %s",
						 applet, strerror (errno));
			case 'C':
				setenv ("RC_NOCOLOR", "yes", 1);
				break;
			case 'D':
				deps = false;
				break;
			case 'q':
				setenv ("RC_QUIET", "yes", 1);
				break;
			case 'v':
				setenv ("RC_VERBOSE", "yes", 1);
				break;
			default:
				exit (EXIT_FAILURE);
		}

	/* Save the IN_BACKGROUND env flag so it's ONLY passed to the service
	   that is being called and not any dependents */
	if (getenv ("IN_BACKGROUND")) {
		in_background = rc_is_env ("IN_BACKGROUND", "true");
		ibsave = rc_xstrdup (getenv ("IN_BACKGROUND"));
		unsetenv ("IN_BACKGROUND");
	}

	if (rc_is_env ("IN_HOTPLUG", "1")) {
		if (! rc_is_env ("RC_HOTPLUG", "yes") || ! rc_allow_plug (applet))
			eerrorx ("%s: not allowed to be hotplugged", applet);
	}

	/* Setup a signal handler */
	signal (SIGHUP, handle_signal);
	signal (SIGINT, handle_signal);
	signal (SIGQUIT, handle_signal);
	signal (SIGTERM, handle_signal);
	signal (SIGCHLD, handle_signal);

	/* Load our plugins */
	rc_plugin_load ();

	/* Now run each option */
	retval = EXIT_SUCCESS;
	while (optind < argc) {
		optarg = argv[optind++];

		/* Abort on a sighup here */
		if (sighup)
			exit (EXIT_FAILURE);

		/* Export the command we're running.
		   This is important as we stamp on the restart function now but
		   some start/stop routines still need to behave differently if
		   restarting. */
		unsetenv ("RC_CMD");
		setenv ("RC_CMD", optarg, 1);

		doneone = true;
		if (strcmp (optarg, "conditionalrestart") == 0 ||
			strcmp (optarg, "condrestart") == 0)
		{
			if (rc_service_state (service, rc_service_started))
				svc_restart (service, deps);
		}
		else if (strcmp (optarg, "restart") == 0)
			svc_restart (service, deps);
		else if (strcmp (optarg, "start") == 0)
			svc_start (service, deps);
		else if (strcmp (optarg, "status") == 0) {
			rc_service_state_t r = svc_status (service);
			retval = (int) r;
		} else if (strcmp (optarg, "stop") == 0) {
			if (in_background)
				get_started_services ();

			svc_stop (service, deps);

			if (! in_background &&
				! rc_runlevel_stopping () &&
				rc_service_state (service, rc_service_stopped))
				uncoldplug (applet);

			if (in_background &&
				rc_service_state (service, rc_service_inactive))
			{
				char *svc;
				int j;
				STRLIST_FOREACH (restart_services, svc, j)
					if (rc_service_state (svc, rc_service_stopped))
						rc_schedule_start_service (service, svc);
			}
		} else if (strcmp (optarg, "zap") == 0) {
			einfo ("Manually resetting %s to stopped state", applet);
			rc_mark_service (applet, rc_service_stopped);
			uncoldplug (applet);
		} else if (strcmp (optarg, "help") == 0) {
			execl (RCSCRIPT_HELP, RCSCRIPT_HELP, service, "help", (char *) NULL);
			eerrorx ("%s: failed to exec `" RCSCRIPT_HELP "': %s",
					 applet, strerror (errno));
		}else
			svc_exec (service, optarg, NULL);

		/* Flush our buffered output if any */
		eflush ();

		/* We should ensure this list is empty after an action is done */
		rc_strlist_free (restart_services);
		restart_services = NULL;
	}

	if (! doneone) {
		execl (RCSCRIPT_HELP, RCSCRIPT_HELP, service, (char *) NULL);
		eerrorx ("%s: failed to exec `" RCSCRIPT_HELP "': %s",
				 applet, strerror (errno));
	}

	return (retval);
}