~ubuntu-branches/ubuntu/precise/upstart/precise

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
/* upstart
 *
 * Copyright © 2009-2011 Canonical Ltd.
 * Author: Scott James Remnant <scott@netsplit.com>.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */


#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/reboot.h>
#include <sys/resource.h>

#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <limits.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>

#include <linux/kd.h>

#include <nih/macros.h>
#include <nih/alloc.h>
#include <nih/list.h>
#include <nih/timer.h>
#include <nih/signal.h>
#include <nih/child.h>
#include <nih/option.h>
#include <nih/main.h>
#include <nih/error.h>
#include <nih/logging.h>

#include "paths.h"
#include "events.h"
#include "system.h"
#include "job_class.h"
#include "job_process.h"
#include "event.h"
#include "conf.h"
#include "control.h"


/* Prototypes for static functions */
#ifndef DEBUG
static int  logger_kmsg     (NihLogLevel priority, const char *message);
static void crash_handler   (int signum);
#endif /* DEBUG */
static void term_handler    (void *data, NihSignal *signal);
#ifndef DEBUG
static void cad_handler     (void *data, NihSignal *signal);
static void kbd_handler     (void *data, NihSignal *signal);
static void pwr_handler     (void *data, NihSignal *signal);
static void hup_handler     (void *data, NihSignal *signal);
static void usr1_handler    (void *data, NihSignal *signal);
#endif /* DEBUG */

static void handle_confdir      (void);
static void handle_logdir       (void);
static int  console_type_setter (NihOption *option, const char *arg);


/**
 * argv0:
 *
 * Path to program executed, used for re-executing the init binary from the
 * same location we were executed from.
 **/
static const char *argv0 = NULL;

/**
 * restart:
 *
 * This is set to TRUE if we're being re-exec'd by an existing init
 * process.
 **/
static int restart = FALSE;

/**
 * conf_dir:
 *
 * Full path to job configuration file directory.
 *
 **/
static char *conf_dir = NULL;

/**
 * initial_event:
 *
 * Alternate event to emit at startup (rather than STARTUP_EVENT).
 **/
static char *initial_event = NULL;

/**
 * disable_startup_event:
 *
 * If TRUE, do not emit a startup event.
 **/
static int disable_startup_event = FALSE;

extern int          disable_sessions;
extern int          disable_job_logging;
int                 force_logging;
extern int          use_session_bus;
extern int          default_console;
extern char        *log_dir;


/**
 * options:
 *
 * Command-line options we accept.
 **/
static NihOption options[] = {
	{ 0, "confdir", N_("specify alternative directory to load configuration files from"),
		NULL, "DIR", &conf_dir, NULL },

	{ 0, "default-console", N_("default value for console stanza"),
		NULL, "VALUE", NULL, console_type_setter },

	{ 0, "log", N_("enable job logging"),
		NULL, NULL, &force_logging, NULL },

	{ 0, "logdir", N_("specify alternative directory to store job output logs in"),
		NULL, "DIR", &log_dir, NULL },

	{ 0, "no-log", N_("disable job logging"),
		NULL, NULL, &disable_job_logging, NULL },

	{ 0, "no-sessions", N_("disable user and chroot sessions"),
		NULL, NULL, &disable_sessions, NULL },

	{ 0, "no-startup-event", N_("do not emit any startup event (for testing)"),
		NULL, NULL, &disable_startup_event, NULL },

	{ 0, "restart", NULL, NULL, NULL, &restart, NULL },

	{ 0, "session", N_("use D-Bus session bus rather than system bus (for testing)"),
		NULL, NULL, &use_session_bus, NULL },

	{ 0, "startup-event", N_("specify an alternative initial event (for testing)"),
		NULL, "NAME", &initial_event, NULL },

	/* Ignore invalid options */
	{ '-', "--", NULL, NULL, NULL, NULL, NULL },

	NIH_OPTION_LAST
};


int
main (int   argc,
      char *argv[])
{
	char **args;
	int    ret;

	argv0 = argv[0];
	nih_main_init (argv0);

	nih_option_set_synopsis (_("Process management daemon."));
	nih_option_set_help (
		_("This daemon is normally executed by the kernel and given "
		  "process id 1 to denote its special status.  When executed "
		  "by a user process, it will actually run /sbin/telinit."));

	/* Temporarily disable job logging (bug 912558) */
	disable_job_logging = 1;

	args = nih_option_parser (NULL, argc, argv, options, FALSE);
	if (! args)
		exit (1);

	handle_confdir ();
	handle_logdir ();

	if (force_logging)
		disable_job_logging = 0;

	if (disable_job_logging)
		nih_debug ("Job logging disabled");

	control_handle_bus_type ();

#ifndef DEBUG
	if (use_session_bus == FALSE) {

		/* Check we're root */
		if (getuid ()) {
			nih_fatal (_("Need to be root"));
			exit (1);
		}

		/* Check we're process #1 */
		if (getpid () > 1) {
			execv (TELINIT, argv);
			/* Ignore failure, probably just that telinit doesn't exist */

			nih_fatal (_("Not being executed as init"));
			exit (1);
		}

		/* Clear our arguments from the command-line, so that we show up in
		 * ps or top output as /sbin/init, with no extra flags.
		 *
		 * This is a very Linux-specific trick; by deleting the NULL
		 * terminator at the end of the last argument, we fool the kernel
		 * into believing we used a setproctitle()-a-like to extend the
		 * argument space into the environment space, and thus make it use
		 * strlen() instead of its own assumed length.  In fact, we've done
		 * the exact opposite, and shrunk the command line length to just that
		 * of whatever is in argv[0].
		 *
		 * If we don't do this, and just write \0 over the rest of argv, for
		 * example; the command-line length still includes those \0s, and ps
		 * will show whitespace in their place.
		 */
		if (argc > 1) {
			char *arg_end;

			arg_end = argv[argc-1] + strlen (argv[argc-1]);
			*arg_end = ' ';
		}


		/* Become the leader of a new session and process group, shedding
		 * any controlling tty (which we shouldn't have had anyway - but
		 * you never know what initramfs did).
		 */
		setsid ();

		/* Set the standard file descriptors to the ordinary console device,
		 * resetting it to sane defaults unless we're inheriting from another
		 * init process which we know left it in a sane state.
		 */
		if (system_setup_console (CONSOLE_OUTPUT, (! restart)) < 0) {
			NihError *err;
	
			err = nih_error_get ();
			nih_warn ("%s: %s", _("Unable to initialize console, will try /dev/null"),
				  err->message);
			nih_free (err);
	
			if (system_setup_console (CONSOLE_NONE, FALSE) < 0) {
				err = nih_error_get ();
				nih_fatal ("%s: %s", _("Unable to initialize console as /dev/null"),
					   err->message);
				nih_free (err);
	
				exit (1);
			}
		}

		/* Set the PATH environment variable */
		setenv ("PATH", PATH, TRUE);

		/* Switch to the root directory in case we were started from some
		 * strange place, or worse, some directory in the initramfs that's
		 * going to go away soon.
		 */
		if (chdir ("/"))
			nih_warn ("%s: %s", _("Unable to set root directory"),
				strerror (errno));

		/* Mount the /proc and /sys filesystems, which are pretty much
		 * essential for any Linux system; not to mention used by
		 * ourselves.
		 */
		if (system_mount ("proc", "/proc") < 0) {
			NihError *err;

			err = nih_error_get ();
			nih_warn ("%s: %s", _("Unable to mount /proc filesystem"),
				err->message);
			nih_free (err);
		}

		if (system_mount ("sysfs", "/sys") < 0) {
			NihError *err;

			err = nih_error_get ();
			nih_warn ("%s: %s", _("Unable to mount /sys filesystem"),
				err->message);
			nih_free (err);
		}
	} else {
		nih_log_set_priority (NIH_LOG_DEBUG);
		nih_debug ("Running with UID %d as PID %d (PPID %d)",
				(int)getuid (), (int)getpid (), (int)getppid ());
	}

#else /* DEBUG */
	nih_log_set_priority (NIH_LOG_DEBUG);
	nih_debug ("Running with UID %d as PID %d (PPID %d)",
		(int)getuid (), (int)getpid (), (int)getppid ());
#endif /* DEBUG */


	/* Reset the signal state and install the signal handler for those
	 * signals we actually want to catch; this also sets those that
	 * can be sent to us, because we're special
	 */
	if (! restart)
		nih_signal_reset ();

#ifndef DEBUG
	if (use_session_bus == FALSE) {
		/* Catch fatal errors immediately rather than waiting for a new
		 * iteration through the main loop.
		 */
		nih_signal_set_handler (SIGSEGV, crash_handler);
		nih_signal_set_handler (SIGABRT, crash_handler);
	}
#endif /* DEBUG */

	/* Don't ignore SIGCHLD or SIGALRM, but don't respond to them
	 * directly; it's enough that they interrupt the main loop and
	 * get dealt with during it.
	 */
	nih_signal_set_handler (SIGCHLD, nih_signal_handler);
	nih_signal_set_handler (SIGALRM, nih_signal_handler);

#ifndef DEBUG
	if (use_session_bus == FALSE) {
		/* Ask the kernel to send us SIGINT when control-alt-delete is
		 * pressed; generate an event with the same name.
		 */
		reboot (RB_DISABLE_CAD);
		nih_signal_set_handler (SIGINT, nih_signal_handler);
		NIH_MUST (nih_signal_add_handler (NULL, SIGINT, cad_handler, NULL));

		/* Ask the kernel to send us SIGWINCH when alt-uparrow is pressed;
		 * generate a keyboard-request event.
		 */
		if (ioctl (0, KDSIGACCEPT, SIGWINCH) == 0) {
			nih_signal_set_handler (SIGWINCH, nih_signal_handler);
			NIH_MUST (nih_signal_add_handler (NULL, SIGWINCH,
						kbd_handler, NULL));
		}

		/* powstatd sends us SIGPWR when it changes /etc/powerstatus */
		nih_signal_set_handler (SIGPWR, nih_signal_handler);
		NIH_MUST (nih_signal_add_handler (NULL, SIGPWR, pwr_handler, NULL));

		/* SIGHUP instructs us to re-load our configuration */
		nih_signal_set_handler (SIGHUP, nih_signal_handler);
		NIH_MUST (nih_signal_add_handler (NULL, SIGHUP, hup_handler, NULL));

		/* SIGUSR1 instructs us to reconnect to D-Bus */
		nih_signal_set_handler (SIGUSR1, nih_signal_handler);
		NIH_MUST (nih_signal_add_handler (NULL, SIGUSR1, usr1_handler, NULL));

		/* SIGTERM instructs us to re-exec ourselves; this should be the
		 * last in the list to ensure that all other signals are handled
		 * before a SIGTERM.
		 */
		nih_signal_set_handler (SIGTERM, nih_signal_handler);
		NIH_MUST (nih_signal_add_handler (NULL, SIGTERM, term_handler, NULL));
	}
#endif /* DEBUG */


	/* Watch children for events */
	NIH_MUST (nih_child_add_watch (NULL, -1, NIH_CHILD_ALL,
				       job_process_handler, NULL));

	/* Process the event queue each time through the main loop */
	NIH_MUST (nih_main_loop_add_func (NULL, (NihMainLoopCb)event_poll,
					  NULL));


	/* Adjust our OOM priority to the default, which will be inherited
	 * by all jobs.
	 */
	if (JOB_DEFAULT_OOM_SCORE_ADJ) {
		char  filename[PATH_MAX];
		int   oom_value;
		FILE *fd;

		snprintf (filename, sizeof (filename),
			  "/proc/%d/oom_score_adj", getpid ());
		oom_value = JOB_DEFAULT_OOM_SCORE_ADJ;
		fd = fopen (filename, "w");
		if ((! fd) && (errno == ENOENT)) {
			snprintf (filename, sizeof (filename),
				  "/proc/%d/oom_adj", getpid ());
			oom_value = (JOB_DEFAULT_OOM_SCORE_ADJ
				     * ((JOB_DEFAULT_OOM_SCORE_ADJ < 0) ? 17 : 15)) / 1000;
			fd = fopen (filename, "w");
		}
		if (! fd) {
			nih_warn ("%s: %s", _("Unable to set default oom score"),
				  strerror (errno));
		} else {
			fprintf (fd, "%d\n", oom_value);

			if (fclose (fd))
				nih_warn ("%s: %s", _("Unable to set default oom score"),
					  strerror (errno));
		}
	}


	/* Read configuration */
	NIH_MUST (conf_source_new (NULL, CONFFILE, CONF_FILE));
	NIH_MUST (conf_source_new (NULL, conf_dir, CONF_JOB_DIR));

	conf_reload ();

	/* Create a listening server for private connections. */
	if (use_session_bus == FALSE) {
		while (control_server_open () < 0) {
			NihError *err;

			err = nih_error_get ();
			if (err->number != ENOMEM) {
				nih_warn ("%s: %s", _("Unable to listen for private connections"),
					err->message);
				nih_free (err);
				break;
			}
			nih_free (err);
		}
	}

	/* Open connection to the appropriate D-Bus bus; we normally expect this to
	 * fail and will try again later - don't let ENOMEM stop us though.
	 */
	while (control_bus_open () < 0) {
		NihError *err;
		int       number;

		err = nih_error_get ();
		number = err->number;
		nih_free (err);

		if (number != ENOMEM)
			break;
	}

#ifndef DEBUG
	if (use_session_bus == FALSE) {
		/* Now that the startup is complete, send all further logging output
		 * to kmsg instead of to the console.
		 */
		if (system_setup_console (CONSOLE_NONE, FALSE) < 0) {
			NihError *err;
			
			err = nih_error_get ();
			nih_fatal ("%s: %s", _("Unable to setup standard file descriptors"),
				   err->message);
			nih_free (err);
	
			exit (1);
		}

		nih_log_set_logger (logger_kmsg);
	}
#endif /* DEBUG */


	/* Generate and run the startup event or read the state from the
	 * init daemon that exec'd us
	 */
	if (! restart) {
		DIR                *piddir;

		/* Look in well-known locations for pid files.
		 *
		 * Try /run (the newer) location first, but fall back to
		 * the original location for older systems.
		 */
		const char * const  pid_paths[] = { "/run/initramfs/", "/dev/.initramfs/", NULL };
		const char * const *pid_path;

		if (disable_startup_event) {
			nih_debug ("Startup event disabled");
		} else {
			NIH_MUST (event_new (NULL,
				initial_event
				? initial_event
				: STARTUP_EVENT,
				NULL));
                }

		for (pid_path = pid_paths; pid_path && *pid_path; pid_path++) {
			struct dirent *ent;

			/* Total hack, look for .pid files in known
			 * locations - if there's a job config for them pretend
			 * that we started it and it has that pid.
			 */
			piddir = opendir (*pid_path);
			if (! piddir)
				continue;

			while ((ent = readdir (piddir)) != NULL) {
				char      path[PATH_MAX];
				char *    ptr;
				FILE *    pidfile;
				pid_t     pid;
				JobClass *class;
				Job *     job;

				if (ent->d_name[0] == '.')
					continue;

				strcpy (path, *pid_path);
				strcat (path, ent->d_name);

				ptr = strrchr (ent->d_name, '.');
				if ((! ptr) || strcmp (ptr, ".pid"))
					continue;

				*ptr = '\0';
				pidfile = fopen (path, "r");
				if (! pidfile)
					continue;

				pid = -1;
				if (fscanf (pidfile, "%d", &pid))
					;
				fclose (pidfile);

				if ((pid < 0) || (kill (pid, 0) < 0))
					continue;

				class = (JobClass *)nih_hash_lookup (job_classes, ent->d_name);
				if (! class)
					continue;
				if (! class->process[PROCESS_MAIN])
					continue;
				if (strlen (class->instance))
					continue;

				job = NIH_MUST (job_new (class, ""));
				job->goal = JOB_START;
				job->state = JOB_RUNNING;
				job->pid[PROCESS_MAIN] = pid;

				nih_debug ("%s inherited from initramfs with pid %d", class->name, pid);
			}

			closedir (piddir);
			break;
		}

	} else {
		sigset_t mask;

		/* We're ok to receive signals again */
		sigemptyset (&mask);
		sigprocmask (SIG_SETMASK, &mask, NULL);
	}

	if (disable_sessions)
		nih_debug ("Sessions disabled");

	/* Run through the loop at least once to deal with signals that were
	 * delivered to the previous process while the mask was set or to
	 * process the startup event we emitted.
	 */
	nih_main_loop_interrupt ();
	ret = nih_main_loop ();

	return ret;
}


#ifndef DEBUG
/**
 * logger_kmsg:
 * @priority: priority of message being logged,
 * @message: message to log.
 *
 * Outputs the @message to the kernel log message socket prefixed with an
 * appropriate tag based on @priority, the program name and terminated with
 * a new line.
 *
 * Returns: zero on success, negative value on error.
 **/
static int
logger_kmsg (NihLogLevel priority,
	     const char *message)
{
	int   tag;
	FILE *kmsg;

	nih_assert (message != NULL);

	switch (priority) {
	case NIH_LOG_DEBUG:
		tag = '7';
		break;
	case NIH_LOG_INFO:
		tag = '6';
		break;
	case NIH_LOG_MESSAGE:
		tag = '5';
		break;
	case NIH_LOG_WARN:
		tag = '4';
		break;
	case NIH_LOG_ERROR:
		tag = '3';
		break;
	case NIH_LOG_FATAL:
		tag = '2';
		break;
	default:
		tag = 'd';
	}

	kmsg = fopen ("/dev/kmsg", "w");
	if (! kmsg)
		return -1;

	if (fprintf (kmsg, "<%c>%s: %s\n", tag, program_name, message) < 0) {
		int saved_errno = errno;
		fclose (kmsg);
		errno = saved_errno;
		return -1;
	}

	if (fclose (kmsg) < 0)
		return -1;

	return 0;
}


/**
 * crash_handler:
 * @signum: signal number received.
 *
 * Handle receiving the SEGV or ABRT signal, usually caused by one of
 * our own mistakes.  We deal with it by dumping core in a child process
 * and then killing the parent.
 *
 * Sadly there's no real alternative to the ensuing kernel panic.  Our
 * state is likely in tatters, so we can't sigjmp() anywhere "safe" or
 * re-exec since the system will be suddenly lobotomised.  We definitely
 * don't want to start a root shell or anything like that.  Best thing is
 * to just stop the whole thing and hope that bug report comes quickly.
 **/
static void
crash_handler (int signum)
{
	pid_t pid;

	nih_assert (argv0 != NULL);

	pid = fork ();
	if (pid == 0) {
		struct sigaction act;
		struct rlimit    limit;
		sigset_t         mask;

		/* Mask out all signals */
		sigfillset (&mask);
		sigprocmask (SIG_SETMASK, &mask, NULL);

		/* Set the handler to the default so core is dumped */
		act.sa_handler = SIG_DFL;
		act.sa_flags = 0;
		sigemptyset (&act.sa_mask);
		sigaction (signum, &act, NULL);

		/* Don't limit the core dump size */
		limit.rlim_cur = RLIM_INFINITY;
		limit.rlim_max = RLIM_INFINITY;
		setrlimit (RLIMIT_CORE, &limit);

		/* Dump in the root directory */
		if (chdir ("/"))
			nih_warn ("%s: %s", _("Unable to set root directory"),
				  strerror (errno));

		/* Raise the signal again */
		raise (signum);

		/* Unmask so that we receive it */
		sigdelset (&mask, signum);
		sigprocmask (SIG_SETMASK, &mask, NULL);

		/* Wait for death */
		pause ();
		exit (0);
	} else if (pid > 0) {
		/* Wait for the core to be generated */
		waitpid (pid, NULL, 0);

		nih_fatal (_("Caught %s, core dumped"),
			   (signum == SIGSEGV
			    ? "segmentation fault" : "abort"));
	} else {
		nih_fatal (_("Caught %s, unable to dump core"),
			   (signum == SIGSEGV
			    ? "segmentation fault" : "abort"));
	}

	/* Goodbye, cruel world. */
	exit (signum);
}
#endif

/**
 * term_handler:
 * @data: unused,
 * @signal: signal caught.
 *
 * This is called when we receive the TERM signal, which instructs us
 * to reexec ourselves.
 **/
static void
term_handler (void      *data,
	      NihSignal *signal)
{
	NihError   *err;
	const char *loglevel;
	sigset_t    mask, oldmask;

	nih_assert (argv0 != NULL);
	nih_assert (signal != NULL);

	nih_warn (_("Re-executing %s"), argv0);

	/* Block signals while we work.  We're the last signal handler
	 * installed so this should mean that they're all handled now.
	 *
	 * The child must make sure that it unblocks these again when
	 * it's ready.
	 */
	sigfillset (&mask);
	sigprocmask (SIG_BLOCK, &mask, &oldmask);

	/* Argument list */
	if (nih_log_priority <= NIH_LOG_DEBUG) {
		loglevel = "--debug";
	} else if (nih_log_priority <= NIH_LOG_INFO) {
		loglevel = "--verbose";
	} else if (nih_log_priority >= NIH_LOG_ERROR) {
		loglevel = "--error";
	} else {
		loglevel = NULL;
	}
	execl (argv0, argv0, "--restart", loglevel, NULL);
	nih_error_raise_system ();

	err = nih_error_get ();
	nih_error (_("Failed to re-execute %s: %s"), argv0, err->message);
	nih_free (err);

	sigprocmask (SIG_SETMASK, &oldmask, NULL);
}


#ifndef DEBUG
/**
 * cad_handler:
 * @data: unused,
 * @signal: signal that called this handler.
 *
 * Handle having recieved the SIGINT signal, sent to us when somebody
 * presses Ctrl-Alt-Delete on the console.  We just generate a
 * ctrlaltdel event.
 **/
static void
cad_handler (void      *data,
	     NihSignal *signal)
{
	NIH_MUST (event_new (NULL, CTRLALTDEL_EVENT, NULL));
}

/**
 * kbd_handler:
 * @data: unused,
 * @signal: signal that called this handler.
 *
 * Handle having recieved the SIGWINCH signal, sent to us when somebody
 * presses Alt-UpArrow on the console.  We just generate a
 * kbdrequest event.
 **/
static void
kbd_handler (void      *data,
	     NihSignal *signal)
{
	NIH_MUST (event_new (NULL, KBDREQUEST_EVENT, NULL));
}

/**
 * pwr_handler:
 * @data: unused,
 * @signal: signal that called this handler.
 *
 * Handle having recieved the SIGPWR signal, sent to us when powstatd
 * changes the /etc/powerstatus file.  We just generate a
 * power-status-changed event and jobs read the file.
 **/
static void
pwr_handler (void      *data,
	     NihSignal *signal)
{
	NIH_MUST (event_new (NULL, PWRSTATUS_EVENT, NULL));
}

/**
 * hup_handler:
 * @data: unused,
 * @signal: signal that called this handler.
 *
 * Handle having recieved the SIGHUP signal, which we use to instruct us to
 * reload our configuration.
 **/
static void
hup_handler (void      *data,
	     NihSignal *signal)
{
	nih_info (_("Reloading configuration"));
	conf_reload ();
}

/**
 * usr1_handler:
 * @data: unused,
 * @signal: signal that called this handler.
 *
 * Handle having recieved the SIGUSR signal, which we use to instruct us to
 * reconnect to D-Bus.
 **/
static void
usr1_handler (void      *data,
	      NihSignal *signal)
{
	if (! control_bus) {
		nih_info (_("Reconnecting to system bus"));

		if (control_bus_open () < 0) {
			NihError *err;

			err = nih_error_get ();
			nih_warn ("%s: %s", _("Unable to connect to the system bus"),
				  err->message);
			nih_free (err);
		}
	}
}
#endif /* DEBUG */

/**
 * handle_confdir:
 *
 * Determine where system configuration files should be loaded from.
 **/
static void
handle_confdir (void)
{
	char *dir;

	/* user has already specified directory on command-line */
	if (conf_dir)
		goto out;

	conf_dir = CONFDIR;

	dir = getenv (CONFDIR_ENV);
	if (! dir)
		return;

	conf_dir = dir;

out:
	nih_debug ("Using alternate configuration directory %s",
			conf_dir);
}

/**
 * handle_logdir:
 *
 * Determine directory where job log files should be written to.
 **/
static void
handle_logdir (void)
{
	char *dir;

	/* user has already specified directory on command-line */
	if (log_dir)
		goto out;

	log_dir = JOB_LOGDIR;

	dir = getenv (LOGDIR_ENV);
	if (! dir)
		return;

	log_dir = dir;

out:
	nih_debug ("Using alternate log directory %s",
			log_dir);
}

/**  
 * NihOption setter function to handle selection of default console
 * type.
 *
 * Returns 0 on success, -1 on invalid console type.
 **/
static int
console_type_setter (NihOption *option, const char *arg)
{
	 nih_assert (option);

	 default_console = (int)job_class_console_type (arg);

	 if (default_console == -1) {
		 nih_fatal ("%s: %s", _("invalid console type specified"), arg);
		 return -1;
	 }

	 return 0;
}