xref: /illumos-gate/usr/src/cmd/init/init.c (revision 6d59ee37)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
28 /*	  All Rights Reserved  	*/
29 
30 /*
31  * University Copyright- Copyright (c) 1982, 1986, 1988
32  * The Regents of the University of California
33  * All Rights Reserved
34  *
35  * University Acknowledgment- Portions of this document are derived from
36  * software developed by the University of California, Berkeley, and its
37  * contributors.
38  */
39 
40 #pragma ident	"%Z%%M%	%I%	%E% SMI"
41 
42 /*
43  * init(1M) is the general process spawning program.  Its primary job is to
44  * start and restart svc.startd for smf(5).  For backwards-compatibility it also
45  * spawns and respawns processes according to /etc/inittab and the current
46  * run-level.  It reads /etc/default/inittab for general configuration.
47  *
48  * To change run-levels the system administrator runs init from the command
49  * line with a level name.  init signals svc.startd via libscf and directs the
50  * zone's init (pid 1 in the global zone) what to do by sending it a signal;
51  * these signal numbers are commonly refered to in the code as 'states'.  Valid
52  * run-levels are [sS0123456].  Additionally, init can be given directives
53  * [qQabc], which indicate actions to be taken pertaining to /etc/inittab.
54  *
55  * When init processes inittab entries, it finds processes that are to be
56  * spawned at various run-levels.  inittab contains the set of the levels for
57  * which each inittab entry is valid.
58  *
59  * State File and Restartability
60  *   Premature exit by init(1M) is handled as a special case by the kernel:
61  *   init(1M) will be immediately re-executed, retaining its original PID.  (PID
62  *   1 in the global zone.)  To track the processes it has previously spawned,
63  *   as well as other mutable state, init(1M) regularly updates a state file
64  *   such that its subsequent invocations have knowledge of its various
65  *   dependent processes and duties.
66  *
67  * Process Contracts
68  *   We start svc.startd(1M) in a contract and transfer inherited contracts when
69  *   restarting it.  Everything else is started using the legacy contract
70  *   template, and the created contracts are abandoned when they become empty.
71  *
72  * utmpx Entry Handling
73  *   Because init(1M) no longer governs the startup process, its knowledge of
74  *   when utmpx becomes writable is indirect.  However, spawned processes
75  *   expect to be constructed with valid utmpx entries.  As a result, attempts
76  *   to write normal entries will be retried until successful.
77  *
78  * Maintenance Mode
79  *   In certain failure scenarios, init(1M) will enter a maintenance mode, in
80  *   which it invokes sulogin(1M) to allow the operator an opportunity to
81  *   repair the system.  Normally, this operation is performed as a
82  *   fork(2)-exec(2)-waitpid(3C) sequence with the parent waiting for repair or
83  *   diagnosis to be completed.  In the cases that fork(2) requests themselves
84  *   fail, init(1M) will directly execute sulogin(1M), and allow the kernel to
85  *   restart init(1M) on exit from the operator session.
86  *
87  *   One scenario where init(1M) enters its maintenance mode is when
88  *   svc.startd(1M) begins to fail rapidly, defined as when the average time
89  *   between recent failures drops below a given threshold.
90  */
91 
92 #include <sys/contract/process.h>
93 #include <sys/ctfs.h>
94 #include <sys/stat.h>
95 #include <sys/statvfs.h>
96 #include <sys/stropts.h>
97 #include <sys/systeminfo.h>
98 #include <sys/time.h>
99 #include <sys/termios.h>
100 #include <sys/tty.h>
101 #include <sys/types.h>
102 #include <sys/utsname.h>
103 
104 #include <bsm/adt_event.h>
105 #include <bsm/libbsm.h>
106 #include <security/pam_appl.h>
107 
108 #include <assert.h>
109 #include <ctype.h>
110 #include <dirent.h>
111 #include <errno.h>
112 #include <fcntl.h>
113 #include <libcontract.h>
114 #include <libcontract_priv.h>
115 #include <libintl.h>
116 #include <libscf.h>
117 #include <libscf_priv.h>
118 #include <poll.h>
119 #include <procfs.h>
120 #include <signal.h>
121 #include <stdarg.h>
122 #include <stdio.h>
123 #include <stdio_ext.h>
124 #include <stdlib.h>
125 #include <string.h>
126 #include <strings.h>
127 #include <syslog.h>
128 #include <time.h>
129 #include <ulimit.h>
130 #include <unistd.h>
131 #include <utmpx.h>
132 #include <wait.h>
133 #include <zone.h>
134 #include <ucontext.h>
135 
136 #undef	sleep
137 
138 #define	fioctl(p, sptr, cmd)	ioctl(fileno(p), sptr, cmd)
139 #define	min(a, b)		(((a) < (b)) ? (a) : (b))
140 
141 #define	TRUE	1
142 #define	FALSE	0
143 #define	FAILURE	-1
144 
145 #define	UT_LINE_SZ	32	/* Size of a utmpx ut_line field */
146 
147 /*
148  * SLEEPTIME	The number of seconds "init" sleeps between wakeups if
149  *		nothing else requires this "init" wakeup.
150  */
151 #define	SLEEPTIME	(5 * 60)
152 
153 /*
154  * MAXCMDL	The maximum length of a command string in inittab.
155  */
156 #define	MAXCMDL	512
157 
158 /*
159  * EXEC		The length of the prefix string added to all comamnds
160  *		found in inittab.
161  */
162 #define	EXEC	(sizeof ("exec ") - 1)
163 
164 /*
165  * TWARN	The amount of time between warning signal, SIGTERM,
166  *		and the fatal kill signal, SIGKILL.
167  */
168 #define	TWARN	5
169 
170 #define	id_eq(x, y)	((x[0] == y[0] && x[1] == y[1] && x[2] == y[2] &&\
171 			x[3] == y[3]) ? TRUE : FALSE)
172 
173 /*
174  * The kernel's default umask is 022 these days; since some processes inherit
175  * their umask from init, init will set it from CMASK in /etc/default/init.
176  * init gets the default umask from the kernel, it sets it to 022 whenever
177  * it wants to create a file and reverts to CMASK afterwards.
178  */
179 
180 static int cmask;
181 
182 /*
183  * The following definitions, concluding with the 'lvls' array, provide a
184  * common mapping between level-name (like 'S'), signal number (state),
185  * run-level mask, and specific properties associated with a run-level.
186  * This array should be accessed using the routines lvlname_to_state(),
187  * lvlname_to_mask(), state_to_mask(), and state_to_flags().
188  */
189 
190 /*
191  * Correspondence of signals to init actions.
192  */
193 #define	LVLQ		SIGHUP
194 #define	LVL0		SIGINT
195 #define	LVL1		SIGQUIT
196 #define	LVL2		SIGILL
197 #define	LVL3		SIGTRAP
198 #define	LVL4		SIGIOT
199 #define	LVL5		SIGEMT
200 #define	LVL6		SIGFPE
201 #define	SINGLE_USER	SIGBUS
202 #define	LVLa		SIGSEGV
203 #define	LVLb		SIGSYS
204 #define	LVLc		SIGPIPE
205 
206 /*
207  * Bit Mask for each level.  Used to determine legal levels.
208  */
209 #define	MASK0	0x0001
210 #define	MASK1	0x0002
211 #define	MASK2	0x0004
212 #define	MASK3	0x0008
213 #define	MASK4	0x0010
214 #define	MASK5	0x0020
215 #define	MASK6	0x0040
216 #define	MASKSU	0x0080
217 #define	MASKa	0x0100
218 #define	MASKb	0x0200
219 #define	MASKc	0x0400
220 
221 #define	MASK_NUMERIC (MASK0 | MASK1 | MASK2 | MASK3 | MASK4 | MASK5 | MASK6)
222 #define	MASK_abc (MASKa | MASKb | MASKc)
223 
224 /*
225  * Flags to indicate properties of various states.
226  */
227 #define	LSEL_RUNLEVEL	0x0001	/* runlevels you can transition to */
228 
229 typedef struct lvl {
230 	int	lvl_state;
231 	int	lvl_mask;
232 	char	lvl_name;
233 	int	lvl_flags;
234 } lvl_t;
235 
236 static lvl_t lvls[] = {
237 	{ LVLQ,		0,	'Q', 0					},
238 	{ LVLQ,		0,	'q', 0					},
239 	{ LVL0,		MASK0,	'0', LSEL_RUNLEVEL			},
240 	{ LVL1, 	MASK1,	'1', LSEL_RUNLEVEL			},
241 	{ LVL2, 	MASK2,	'2', LSEL_RUNLEVEL			},
242 	{ LVL3, 	MASK3,	'3', LSEL_RUNLEVEL			},
243 	{ LVL4, 	MASK4,	'4', LSEL_RUNLEVEL			},
244 	{ LVL5, 	MASK5,	'5', LSEL_RUNLEVEL			},
245 	{ LVL6, 	MASK6, 	'6', LSEL_RUNLEVEL			},
246 	{ SINGLE_USER, 	MASKSU, 'S', LSEL_RUNLEVEL			},
247 	{ SINGLE_USER, 	MASKSU, 's', LSEL_RUNLEVEL			},
248 	{ LVLa,		MASKa,	'a', 0					},
249 	{ LVLb,		MASKb,	'b', 0					},
250 	{ LVLc,		MASKc,	'c', 0					}
251 };
252 
253 #define	LVL_NELEMS (sizeof (lvls) / sizeof (lvl_t))
254 
255 /*
256  * Legal action field values.
257  */
258 #define	OFF		0	/* Kill process if on, else ignore */
259 #define	RESPAWN		1	/* Continuously restart process when it dies */
260 #define	ONDEMAND	RESPAWN	/* Respawn for a, b, c type processes */
261 #define	ONCE		2	/* Start process, do not respawn when dead */
262 #define	WAIT		3	/* Perform once and wait to complete */
263 #define	BOOT		4	/* Start at boot time only */
264 #define	BOOTWAIT	5	/* Start at boot time and wait to complete */
265 #define	POWERFAIL	6	/* Start on powerfail */
266 #define	POWERWAIT	7	/* Start and wait for complete on powerfail */
267 #define	INITDEFAULT	8	/* Default level "init" should start at */
268 #define	SYSINIT		9	/* Actions performed before init speaks */
269 
270 #define	M_OFF		0001
271 #define	M_RESPAWN	0002
272 #define	M_ONDEMAND	M_RESPAWN
273 #define	M_ONCE		0004
274 #define	M_WAIT		0010
275 #define	M_BOOT		0020
276 #define	M_BOOTWAIT	0040
277 #define	M_PF		0100
278 #define	M_PWAIT		0200
279 #define	M_INITDEFAULT	0400
280 #define	M_SYSINIT	01000
281 
282 /* States for the inittab parser in getcmd(). */
283 #define	ID	1
284 #define	LEVELS	2
285 #define	ACTION	3
286 #define	COMMAND	4
287 #define	COMMENT	5
288 
289 /*
290  * Init can be in any of three main states, "normal" mode where it is
291  * processing entries for the lines file in a normal fashion, "boot" mode,
292  * where it is only interested in the boot actions, and "powerfail" mode,
293  * where it is only interested in powerfail related actions. The following
294  * masks declare the legal actions for each mode.
295  */
296 #define	NORMAL_MODES	(M_OFF | M_RESPAWN | M_ONCE | M_WAIT)
297 #define	BOOT_MODES	(M_BOOT | M_BOOTWAIT)
298 #define	PF_MODES	(M_PF | M_PWAIT)
299 
300 struct PROC_TABLE {
301 	char	p_id[4];	/* Four letter unique id of process */
302 	pid_t	p_pid;		/* Process id */
303 	short	p_count;	/* How many respawns of this command in */
304 				/*   the current series */
305 	long	p_time;		/* Start time for a series of respawns */
306 	short	p_flags;
307 	short	p_exit;		/* Exit status of a process which died */
308 };
309 
310 /*
311  * Flags for the "p_flags" word of a PROC_TABLE entry:
312  *
313  *	OCCUPIED	This slot in init's proc table is in use.
314  *
315  *	LIVING		Process is alive.
316  *
317  *	NOCLEANUP	efork() is not allowed to cleanup this entry even
318  *			if process is dead.
319  *
320  *	NAMED		This process has a name, i.e. came from inittab.
321  *
322  *	DEMANDREQUEST	Process started by a "telinit [abc]" command.  Processes
323  *			formed this way are respawnable and immune to level
324  *			changes as long as their entry exists in inittab.
325  *
326  *	TOUCHED		Flag used by remv() to determine whether it has looked
327  *			at an entry while checking for processes to be killed.
328  *
329  *	WARNED		Flag used by remv() to mark processes that have been
330  *			sent the SIGTERM signal.  If they don't die in 5
331  *			seconds, they are sent the SIGKILL signal.
332  *
333  *	KILLED		Flag used by remv() to mark procs that have been sent
334  *			the SIGTERM and SIGKILL signals.
335  *
336  *	PF_MASK		Bitwise or of legal flags, for sanity checking.
337  */
338 #define	OCCUPIED	01
339 #define	LIVING		02
340 #define	NOCLEANUP	04
341 #define	NAMED		010
342 #define	DEMANDREQUEST	020
343 #define	TOUCHED		040
344 #define	WARNED		0100
345 #define	KILLED		0200
346 #define	PF_MASK		0377
347 
348 /*
349  * Respawn limits for processes that are to be respawned:
350  *
351  *	SPAWN_INTERVAL	The number of seconds over which "init" will try to
352  *			respawn a process SPAWN_LIMIT times before it gets mad.
353  *
354  *	SPAWN_LIMIT	The number of respawns "init" will attempt in
355  *			SPAWN_INTERVAL seconds before it generates an
356  *			error message and inhibits further tries for
357  *			INHIBIT seconds.
358  *
359  *	INHIBIT		The number of seconds "init" ignores an entry it had
360  *			trouble spawning unless a "telinit Q" is received.
361  */
362 
363 #define	SPAWN_INTERVAL	(2*60)
364 #define	SPAWN_LIMIT	10
365 #define	INHIBIT		(5*60)
366 
367 /*
368  * The maximum number of decimal digits for an id_t.  (ceil(log10 (max_id)))
369  */
370 #define	ID_MAX_STR_LEN	10
371 
372 #define	NULLPROC	((struct PROC_TABLE *)(0))
373 #define	NO_ROOM		((struct PROC_TABLE *)(FAILURE))
374 
375 struct CMD_LINE {
376 	char c_id[4];	/* Four letter unique id of process to be */
377 			/*   affected by action */
378 	short c_levels;	/* Mask of legal levels for process */
379 	short c_action;	/* Mask for type of action required */
380 	char *c_command; /* Pointer to init command */
381 };
382 
383 struct	pidrec {
384 	int	pd_type;	/* Command type */
385 	pid_t	pd_pid;		/* pid to add or remove */
386 };
387 
388 /*
389  * pd_type's
390  */
391 #define	ADDPID	1
392 #define	REMPID	2
393 
394 static struct	pidlist {
395 	pid_t	pl_pid;		/* pid to watch for */
396 	int	pl_dflag;	/* Flag indicating SIGCLD from this pid */
397 	short	pl_exit;	/* Exit status of proc */
398 	struct	pidlist	*pl_next; /* Next in list */
399 } *Plhead, *Plfree;
400 
401 /*
402  * The following structure contains a set of modes for /dev/syscon
403  * and should match the default contents of /etc/ioctl.syscon.
404  */
405 static struct termios	dflt_termios = {
406 	BRKINT|ICRNL|IXON|IMAXBEL,			/* iflag */
407 	OPOST|ONLCR|TAB3,				/* oflag */
408 	CS8|CREAD|B9600,				/* cflag */
409 	ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN, /* lflag */
410 	CINTR, CQUIT, CERASE, CKILL, CEOF, 0, 0, 0,
411 	0, 0, 0, 0, 0, 0, 0, 0,
412 	0, 0, 0
413 };
414 
415 static struct termios	stored_syscon_termios;
416 static int		write_ioctl = 0;	/* Rewrite /etc/ioctl.syscon */
417 
418 static union WAKEUP {
419 	struct WAKEFLAGS {
420 		unsigned w_usersignal : 1;	/* User sent signal to "init" */
421 		unsigned w_childdeath : 1;	/* An "init" child died */
422 		unsigned w_powerhit : 1;	/* OS experienced powerfail */
423 	}	w_flags;
424 	int w_mask;
425 } wakeup;
426 
427 
428 struct init_state {
429 	int			ist_runlevel;
430 	int			ist_num_proc;
431 	int			ist_utmpx_ok;
432 	struct PROC_TABLE	ist_proc_table[1];
433 };
434 
435 #define	cur_state	(g_state->ist_runlevel)
436 #define	num_proc	(g_state->ist_num_proc)
437 #define	proc_table	(g_state->ist_proc_table)
438 #define	utmpx_ok	(g_state->ist_utmpx_ok)
439 
440 /* Contract cookies. */
441 #define	ORDINARY_COOKIE		0
442 #define	STARTD_COOKIE		1
443 
444 
445 #ifndef NDEBUG
446 #define	bad_error(func, err)	{					\
447 	(void) fprintf(stderr, "%s:%d: %s() failed with unexpected "	\
448 	    "error %d.  Aborting.\n", __FILE__, __LINE__, (func), (err)); \
449 	abort();							\
450 }
451 #else
452 #define	bad_error(func, err)	abort()
453 #endif
454 
455 
456 /*
457  * Useful file and device names.
458  */
459 static char *CONSOLE	  = "/dev/console";	/* Real system console */
460 static char *INITPIPE_DIR = "/etc";
461 static char *INITPIPE	  = "/etc/initpipe";
462 
463 #define	INIT_STATE_DIR "/etc/svc/volatile"
464 static const char * const init_state_file = INIT_STATE_DIR "/init.state";
465 static const char * const init_next_state_file =
466 	INIT_STATE_DIR "/init-next.state";
467 
468 static const int init_num_proc = 20;	/* Initial size of process table. */
469 
470 static char *UTMPX	 = UTMPX_FILE;		/* Snapshot record file */
471 static char *WTMPX	 = WTMPX_FILE;		/* Long term record file */
472 static char *INITTAB	 = "/etc/inittab";	/* Script file for "init" */
473 static char *SYSTTY	 = "/dev/systty";	/* System Console */
474 static char *SYSCON	 = "/dev/syscon";	/* Virtual System console */
475 static char *IOCTLSYSCON = "/etc/ioctl.syscon";	/* Last syscon modes */
476 static char *ENVFILE	 = "/etc/default/init";	/* Default env. */
477 static char *SU	= "/etc/sulogin";	/* Super-user program for single user */
478 static char *SH	= "/sbin/sh";		/* Standard shell */
479 
480 /*
481  * Default Path.  /sbin is included in path only during sysinit phase
482  */
483 #define	DEF_PATH	"PATH=/usr/sbin:/usr/bin"
484 #define	INIT_PATH	"PATH=/sbin:/usr/sbin:/usr/bin"
485 
486 static int	prior_state;
487 static int	prev_state;	/* State "init" was in last time it woke */
488 static int	new_state;	/* State user wants "init" to go to. */
489 static int	op_modes = BOOT_MODES; /* Current state of "init" */
490 static int	Gchild = 0;	/* Flag to indicate "godchild" died, set in */
491 				/*   childeath() and cleared in cleanaux() */
492 static int	Pfd = -1;	/* fd to receive pids thru */
493 static unsigned int	spawncnt, pausecnt;
494 static int	rsflag;		/* Set if a respawn has taken place */
495 static volatile int time_up;	/* Flag set to TRUE by the alarm interrupt */
496 				/* routine each time an alarm interrupt */
497 				/* takes place. */
498 static int	sflg = 0;	/* Set if we were booted -s to single user */
499 static int	rflg = 0;	/* Set if booted -r, reconfigure devices */
500 static int	bflg = 0;	/* Set if booted -b, don't run rc scripts */
501 static pid_t	init_pid;	/* PID of "one true" init for current zone */
502 
503 static struct init_state *g_state = NULL;
504 static size_t	g_state_sz;
505 static int	booting = 1;	/* Set while we're booting. */
506 
507 /*
508  * Array for default global environment.
509  */
510 #define	MAXENVENT	24	/* Max number of default env variables + 1 */
511 				/* init can use three itself, so this leaves */
512 				/* 20 for the administrator in ENVFILE. */
513 static char	*glob_envp[MAXENVENT];	/* Array of environment strings */
514 static int	glob_envn;		/* Number of environment strings */
515 
516 
517 static struct pollfd	poll_fds[1];
518 static int		poll_nfds = 0;	/* poll_fds is uninitialized */
519 
520 static int	legacy_tmpl = -1;	/* fd for legacy contract template */
521 static int	startd_tmpl = -1;	/* fd for svc.startd's template */
522 
523 static char	startd_cline[256] = "";	/* svc.startd's command line */
524 static int	do_restart_startd = 1;	/* Whether to restart svc.startd. */
525 static char	*smf_options = NULL;	/* Options to give to startd. */
526 static int	smf_debug = 0;		/* Messages for debugging smf(5) */
527 static time_t	init_boot_time;		/* Substitute for kernel boot time. */
528 
529 #define	NSTARTD_FAILURE_TIMES	3		/* trigger after 3 failures */
530 #define	STARTD_FAILURE_RATE_NS	5000000000LL	/* 1 failure/5 seconds */
531 
532 static hrtime_t	startd_failure_time[NSTARTD_FAILURE_TIMES];
533 static uint_t	startd_failure_index;
534 
535 
536 static char	*prog_name(char *);
537 static int	state_to_mask(int);
538 static int	lvlname_to_mask(char, int *);
539 static void	lscf_set_runlevel(char);
540 static int	state_to_flags(int);
541 static char	state_to_name(int);
542 static int	lvlname_to_state(char);
543 static int	getcmd(struct CMD_LINE *, char *);
544 static int	realcon();
545 static int	spawn_processes();
546 static int	get_ioctl_syscon();
547 static int	account(short, struct PROC_TABLE *, char *);
548 static void	alarmclk();
549 static void	childeath(int);
550 static void	cleanaux();
551 static void	clearent(pid_t, short);
552 static void	console(boolean_t, char *, ...);
553 static void	init_signals(void);
554 static void	setup_pipe();
555 static void	killproc(pid_t);
556 static void	init_env();
557 static void	boot_init();
558 static void	powerfail();
559 static void	remv();
560 static void	write_ioctl_syscon();
561 static void	spawn(struct PROC_TABLE *, struct CMD_LINE *);
562 static void	setimer(int);
563 static void	siglvl(int, siginfo_t *, ucontext_t *);
564 static void	sigpoll(int);
565 static void	enter_maintenance(void);
566 static void	timer(int);
567 static void	userinit(int, char **);
568 static void	notify_pam_dead(struct utmpx *);
569 static long	waitproc(struct PROC_TABLE *);
570 static struct PROC_TABLE *efork(int, struct PROC_TABLE *, int);
571 static struct PROC_TABLE *findpslot(struct CMD_LINE *);
572 static void	increase_proc_table_size();
573 static void	st_init();
574 static void	st_write();
575 static void	contracts_init();
576 static void	contract_event(struct pollfd *);
577 static int	startd_run(const char *, int, ctid_t);
578 static void	startd_record_failure();
579 static int	startd_failure_rate_critical();
580 static char	*audit_boot_msg();
581 static int	audit_put_record(int, int, char *);
582 static void	update_boot_archive(int new_state);
583 
584 int
585 main(int argc, char *argv[])
586 {
587 	int	chg_lvl_flag = FALSE, print_banner = FALSE;
588 	int	may_need_audit = 1;
589 	int	c;
590 	char	*msg;
591 
592 	/* Get a timestamp for use as boot time, if needed. */
593 	(void) time(&init_boot_time);
594 
595 	/* Get the default umask */
596 	cmask = umask(022);
597 	(void) umask(cmask);
598 
599 	/* Parse the arguments to init. Check for single user */
600 	opterr = 0;
601 	while ((c = getopt(argc, argv, "brsm:")) != EOF) {
602 		switch (c) {
603 		case 'b':
604 			rflg = 0;
605 			bflg = 1;
606 			if (!sflg)
607 				sflg++;
608 			break;
609 		case 'r':
610 			bflg = 0;
611 			rflg++;
612 			break;
613 		case 's':
614 			if (!bflg)
615 				sflg++;
616 			break;
617 		case 'm':
618 			smf_options = optarg;
619 			smf_debug = (strstr(smf_options, "debug") != NULL);
620 			break;
621 		}
622 	}
623 
624 	/*
625 	 * Determine if we are the main init, or a user invoked init, whose job
626 	 * it is to inform init to change levels or perform some other action.
627 	 */
628 	if (zone_getattr(getzoneid(), ZONE_ATTR_INITPID, &init_pid,
629 	    sizeof (init_pid)) != sizeof (init_pid)) {
630 		(void) fprintf(stderr, "could not get pid for init\n");
631 		return (1);
632 	}
633 
634 	/*
635 	 * If this PID is not the same as the "true" init for the zone, then we
636 	 * must be in 'user' mode.
637 	 */
638 	if (getpid() != init_pid) {
639 		userinit(argc, argv);
640 	}
641 
642 	if (getzoneid() != GLOBAL_ZONEID) {
643 		print_banner = TRUE;
644 	}
645 
646 	/*
647 	 * Initialize state (and set "booting").
648 	 */
649 	st_init();
650 
651 	if (booting && print_banner) {
652 		struct utsname un;
653 		char buf[BUFSIZ], *isa;
654 		long ret;
655 		int bits = 32;
656 
657 		/*
658 		 * We want to print the boot banner as soon as
659 		 * possible.  In the global zone, the kernel does it,
660 		 * but we do not have that luxury in non-global zones,
661 		 * so we will print it here.
662 		 */
663 		(void) uname(&un);
664 		ret = sysinfo(SI_ISALIST, buf, sizeof (buf));
665 		if (ret != -1L && ret <= sizeof (buf)) {
666 			for (isa = strtok(buf, " "); isa;
667 			    isa = strtok(NULL, " ")) {
668 				if (strcmp(isa, "sparcv9") == 0 ||
669 				    strcmp(isa, "amd64") == 0) {
670 					bits = 64;
671 					break;
672 				}
673 			}
674 		}
675 
676 		console(B_FALSE,
677 		    "\n\n%s Release %s Version %s %d-bit\r\n",
678 		    un.sysname, un.release, un.version, bits);
679 		console(B_FALSE,
680 		    "Copyright 1983-2006 Sun Microsystems, Inc. "
681 		    " All rights reserved.\r\n");
682 		console(B_FALSE,
683 		    "Use is subject to license terms.\r\n");
684 	}
685 
686 	/*
687 	 * Get the ioctl settings for /dev/syscon from /etc/ioctl.syscon
688 	 * so that it can be brought up in the state it was in when the
689 	 * system went down; or set to defaults if ioctl.syscon isn't
690 	 * valid.
691 	 *
692 	 * This needs to be done even if we're restarting so reset_modes()
693 	 * will work in case we need to go down to single user mode.
694 	 */
695 	write_ioctl = get_ioctl_syscon();
696 
697 	/*
698 	 * Set up all signals to be caught or ignored as appropriate.
699 	 */
700 	init_signals();
701 
702 	/* Load glob_envp from ENVFILE. */
703 	init_env();
704 
705 	contracts_init();
706 
707 	if (!booting) {
708 		/* cur_state should have been read in. */
709 
710 		op_modes = NORMAL_MODES;
711 
712 		/* Rewrite the ioctl file if it was bad. */
713 		if (write_ioctl)
714 			write_ioctl_syscon();
715 	} else {
716 		/*
717 		 * It's fine to boot up with state as zero, because
718 		 * startd will later tell us the real state.
719 		 */
720 		cur_state = 0;
721 		op_modes = BOOT_MODES;
722 
723 		boot_init();
724 	}
725 
726 	prev_state = prior_state = cur_state;
727 
728 	/*
729 	 * Here is the beginning of the main process loop.
730 	 */
731 	for (;;) {
732 		if (Pfd < 0)
733 			setup_pipe();
734 
735 		/*
736 		 * Clean up any accounting records for dead "godchildren".
737 		 */
738 		if (Gchild)
739 			cleanaux();
740 
741 		/*
742 		 * If in "normal" mode, check all living processes and initiate
743 		 * kill sequence on those that should not be there anymore.
744 		 */
745 		if (op_modes == NORMAL_MODES && cur_state != LVLa &&
746 		    cur_state != LVLb && cur_state != LVLc)
747 			remv();
748 
749 		/*
750 		 * If a change in run levels is the reason we awoke, now do
751 		 * the accounting to report the change in the utmp file.
752 		 * Also report the change on the system console.
753 		 */
754 		if (chg_lvl_flag) {
755 			chg_lvl_flag = FALSE;
756 
757 			if (state_to_flags(cur_state) & LSEL_RUNLEVEL) {
758 				char rl = state_to_name(cur_state);
759 
760 				if (rl != -1)
761 					lscf_set_runlevel(rl);
762 			}
763 
764 			may_need_audit = 1;
765 		}
766 
767 		/*
768 		 * Scan the inittab file and spawn and respawn processes that
769 		 * should be alive in the current state. If inittab does not
770 		 * exist default to  single user mode.
771 		 */
772 		if (spawn_processes() == FAILURE) {
773 			prior_state = prev_state;
774 			cur_state = SINGLE_USER;
775 		}
776 
777 		/* If any respawns occurred, take note. */
778 		if (rsflag) {
779 			rsflag = 0;
780 			spawncnt++;
781 		}
782 
783 		/*
784 		 * If a powerfail signal was received during the last
785 		 * sequence, set mode to powerfail.  When spawn_processes() is
786 		 * entered the first thing it does is to check "powerhit".  If
787 		 * it is in PF_MODES then it clears "powerhit" and does
788 		 * a powerfail sequence.  If it is not in PF_MODES, then it
789 		 * puts itself in PF_MODES and then clears "powerhit".  Should
790 		 * "powerhit" get set again while spawn_processes() is working
791 		 * on a powerfail sequence, the following code  will see that
792 		 * spawn_processes() tries to execute the powerfail sequence
793 		 * again.  This guarantees that the powerfail sequence will be
794 		 * successfully completed before further processing takes
795 		 * place.
796 		 */
797 		if (wakeup.w_flags.w_powerhit) {
798 			op_modes = PF_MODES;
799 			/*
800 			 * Make sure that cur_state != prev_state so that
801 			 * ONCE and WAIT types work.
802 			 */
803 			prev_state = 0;
804 		} else if (op_modes != NORMAL_MODES) {
805 			/*
806 			 * If spawn_processes() was not just called while in
807 			 * normal mode, we set the mode to normal and it will
808 			 * be called again to check normal modes.  If we have
809 			 * just finished a powerfail sequence with prev_state
810 			 * equal to zero, we set prev_state equal to cur_state
811 			 * before the next pass through.
812 			 */
813 			if (op_modes == PF_MODES)
814 				prev_state = cur_state;
815 			op_modes = NORMAL_MODES;
816 		} else if (cur_state == LVLa || cur_state == LVLb ||
817 		    cur_state == LVLc) {
818 			/*
819 			 * If it was a change of levels that awakened us and the
820 			 * new level is one of the demand levels then reset
821 			 * cur_state to the previous state and do another scan
822 			 * to take care of the usual respawn actions.
823 			 */
824 			cur_state = prior_state;
825 			prior_state = prev_state;
826 			prev_state = cur_state;
827 		} else {
828 			prev_state = cur_state;
829 
830 			if (wakeup.w_mask == 0) {
831 				int ret;
832 
833 				if (may_need_audit && (cur_state == LVL3)) {
834 					msg = audit_boot_msg();
835 
836 					may_need_audit = 0;
837 					(void) audit_put_record(ADT_SUCCESS,
838 					    ADT_SUCCESS, msg);
839 					free(msg);
840 				}
841 
842 				/*
843 				 * "init" is finished with all actions for
844 				 * the current wakeup.
845 				 */
846 				ret = poll(poll_fds, poll_nfds,
847 				    SLEEPTIME * MILLISEC);
848 				pausecnt++;
849 				if (ret > 0)
850 					contract_event(&poll_fds[0]);
851 				else if (ret < 0 && errno != EINTR)
852 					console(B_TRUE, "poll() error: %s\n",
853 					    strerror(errno));
854 			}
855 
856 			if (wakeup.w_flags.w_usersignal) {
857 				/*
858 				 * Install the new level.  This could be a real
859 				 * change in levels  or a telinit [Q|a|b|c] or
860 				 * just a telinit to the same level at which
861 				 * we are running.
862 				 */
863 				if (new_state != cur_state) {
864 					if (new_state == LVLa ||
865 					    new_state == LVLb ||
866 					    new_state == LVLc) {
867 						prev_state = prior_state;
868 						prior_state = cur_state;
869 						cur_state = new_state;
870 					} else {
871 						prev_state = cur_state;
872 						if (cur_state >= 0)
873 							prior_state = cur_state;
874 						cur_state = new_state;
875 						chg_lvl_flag = TRUE;
876 					}
877 				}
878 
879 				new_state = 0;
880 			}
881 
882 			if (wakeup.w_flags.w_powerhit)
883 				op_modes = PF_MODES;
884 
885 			/*
886 			 * Clear all wakeup reasons.
887 			 */
888 			wakeup.w_mask = 0;
889 		}
890 	}
891 
892 	/*NOTREACHED*/
893 }
894 
895 static void
896 update_boot_archive(int new_state)
897 {
898 	if (new_state != LVL0 && new_state != LVL5 && new_state != LVL6)
899 		return;
900 
901 	if (getzoneid() != GLOBAL_ZONEID)
902 		return;
903 
904 	(void) system("/sbin/bootadm -a update_all");
905 }
906 
907 /*
908  * void enter_maintenance()
909  *   A simple invocation of sulogin(1M), with no baggage, in the case that we
910  *   are unable to activate svc.startd(1M).  We fork; the child runs sulogin;
911  *   we wait for it to exit.
912  */
913 static void
914 enter_maintenance()
915 {
916 	struct PROC_TABLE	*su_process;
917 
918 	console(B_FALSE, "Requesting maintenance mode\n"
919 	    "(See /lib/svc/share/README for additional information.)\n");
920 	(void) sigset(SIGCLD, SIG_DFL);
921 	while ((su_process = efork(M_OFF, NULLPROC, NOCLEANUP)) == NO_ROOM)
922 		(void) pause();
923 	(void) sigset(SIGCLD, childeath);
924 	if (su_process == NULLPROC) {
925 		int fd;
926 
927 		(void) fclose(stdin);
928 		(void) fclose(stdout);
929 		(void) fclose(stderr);
930 		closefrom(0);
931 
932 		fd = open(SYSCON, O_RDWR | O_NOCTTY);
933 		if (fd >= 0) {
934 			(void) dup2(fd, 1);
935 			(void) dup2(fd, 2);
936 		} else {
937 			/*
938 			 * Need to issue an error message somewhere.
939 			 */
940 			syslog(LOG_CRIT, "init[%d]: cannot open %s; %s\n",
941 			    getpid(), SYSCON, strerror(errno));
942 		}
943 
944 		/*
945 		 * Execute the "su" program.
946 		 */
947 		(void) execle(SU, SU, "-", (char *)0, glob_envp);
948 		console(B_TRUE, "execle of %s failed: %s\n", SU,
949 		    strerror(errno));
950 		timer(5);
951 		exit(1);
952 	}
953 
954 	/*
955 	 * If we are the parent, wait around for the child to die
956 	 * or for "init" to be signaled to change levels.
957 	 */
958 	while (waitproc(su_process) == FAILURE) {
959 		/*
960 		 * All other reasons for waking are ignored when in
961 		 * single-user mode.  The only child we are interested
962 		 * in is being waited for explicitly by waitproc().
963 		 */
964 		wakeup.w_mask = 0;
965 	}
966 }
967 
968 /*
969  * remv() scans through "proc_table" and performs cleanup.  If
970  * there is a process in the table, which shouldn't be here at
971  * the current run level, then remv() kills the process.
972  */
973 static void
974 remv()
975 {
976 	struct PROC_TABLE	*process;
977 	struct CMD_LINE		cmd;
978 	char			cmd_string[MAXCMDL];
979 	int			change_level;
980 
981 	change_level = (cur_state != prev_state ? TRUE : FALSE);
982 
983 	/*
984 	 * Clear the TOUCHED flag on all entries so that when we have
985 	 * finished scanning inittab, we will be able to tell if we
986 	 * have any processes for which there is no entry in inittab.
987 	 */
988 	for (process = proc_table;
989 	    (process < proc_table + num_proc); process++) {
990 		process->p_flags &= ~TOUCHED;
991 	}
992 
993 	/*
994 	 * Scan all inittab entries.
995 	 */
996 	while (getcmd(&cmd, &cmd_string[0]) == TRUE) {
997 		/* Scan for process which goes with this entry in inittab. */
998 		for (process = proc_table;
999 		    (process < proc_table + num_proc); process++) {
1000 			if ((process->p_flags & OCCUPIED) == 0 ||
1001 			    !id_eq(process->p_id, cmd.c_id))
1002 				continue;
1003 
1004 			/*
1005 			 * This slot contains the process we are looking for.
1006 			 */
1007 
1008 			/*
1009 			 * Is the cur_state SINGLE_USER or is this process
1010 			 * marked as "off" or was this proc started by some
1011 			 * mechanism other than LVL{a|b|c} and the current level
1012 			 * does not support this process?
1013 			 */
1014 			if (cur_state == SINGLE_USER ||
1015 			    cmd.c_action == M_OFF ||
1016 			    ((cmd.c_levels & state_to_mask(cur_state)) == 0 &&
1017 			    (process->p_flags & DEMANDREQUEST) == 0)) {
1018 				if (process->p_flags & LIVING) {
1019 					/*
1020 					 * Touch this entry so we know we have
1021 					 * treated it.  Note that procs which
1022 					 * are already dead at this point and
1023 					 * should not be restarted are left
1024 					 * untouched.  This causes their slot to
1025 					 * be freed later after dead accounting
1026 					 * is done.
1027 					 */
1028 					process->p_flags |= TOUCHED;
1029 
1030 					if ((process->p_flags & KILLED) == 0) {
1031 						if (change_level) {
1032 							process->p_flags
1033 							    |= WARNED;
1034 							(void) kill(
1035 							    process->p_pid,
1036 							    SIGTERM);
1037 						} else {
1038 							/*
1039 							 * Fork a killing proc
1040 							 * so "init" can
1041 							 * continue without
1042 							 * having to pause for
1043 							 * TWARN seconds.
1044 							 */
1045 							killproc(
1046 							    process->p_pid);
1047 						}
1048 						process->p_flags |= KILLED;
1049 					}
1050 				}
1051 			} else {
1052 				/*
1053 				 * Process can exist at current level.  If it is
1054 				 * still alive or a DEMANDREQUEST we touch it so
1055 				 * it will be left alone.  Otherwise we leave it
1056 				 * untouched so it will be accounted for and
1057 				 * cleaned up later in remv().  Dead
1058 				 * DEMANDREQUESTs will be accounted but not
1059 				 * freed.
1060 				 */
1061 				if (process->p_flags &
1062 				    (LIVING|NOCLEANUP|DEMANDREQUEST))
1063 					process->p_flags |= TOUCHED;
1064 			}
1065 
1066 			break;
1067 		}
1068 	}
1069 
1070 	st_write();
1071 
1072 	/*
1073 	 * If this was a change of levels call, scan through the
1074 	 * process table for processes that were warned to die.  If any
1075 	 * are found that haven't left yet, sleep for TWARN seconds and
1076 	 * then send final terminations to any that haven't died yet.
1077 	 */
1078 	if (change_level) {
1079 
1080 		/*
1081 		 * Set the alarm for TWARN seconds on the assumption
1082 		 * that there will be some that need to be waited for.
1083 		 * This won't harm anything except we are guaranteed to
1084 		 * wakeup in TWARN seconds whether we need to or not.
1085 		 */
1086 		setimer(TWARN);
1087 
1088 		/*
1089 		 * Scan for processes which should be dying.  We hope they
1090 		 * will die without having to be sent a SIGKILL signal.
1091 		 */
1092 		for (process = proc_table;
1093 		    (process < proc_table + num_proc); process++) {
1094 			/*
1095 			 * If this process should die, hasn't yet, and the
1096 			 * TWARN time hasn't expired yet, wait for process
1097 			 * to die or for timer to expire.
1098 			 */
1099 			while (time_up == FALSE &&
1100 			    (process->p_flags & (WARNED|LIVING|OCCUPIED)) ==
1101 			    (WARNED|LIVING|OCCUPIED))
1102 				(void) pause();
1103 
1104 			if (time_up == TRUE)
1105 				break;
1106 		}
1107 
1108 		/*
1109 		 * If we reached the end of the table without the timer
1110 		 * expiring, then there are no procs which will have to be
1111 		 * sent the SIGKILL signal.  If the timer has expired, then
1112 		 * it is necessary to scan the table again and send signals
1113 		 * to all processes which aren't going away nicely.
1114 		 */
1115 		if (time_up == TRUE) {
1116 			for (process = proc_table;
1117 			    (process < proc_table + num_proc); process++) {
1118 				if ((process->p_flags &
1119 				    (WARNED|LIVING|OCCUPIED)) ==
1120 				    (WARNED|LIVING|OCCUPIED))
1121 					(void) kill(process->p_pid, SIGKILL);
1122 			}
1123 		}
1124 		setimer(0);
1125 	}
1126 
1127 	/*
1128 	 * Rescan the proc_table for two kinds of entry, those marked LIVING,
1129 	 * NAMED, which don't have an entry in inittab (haven't been TOUCHED
1130 	 * by the above scanning), and haven't been sent kill signals, and
1131 	 * those entries marked not LIVING, NAMED.  The former procs are killed.
1132 	 * The latter have DEAD_PROCESS accounting done and the slot cleared.
1133 	 */
1134 	for (process = proc_table;
1135 	    (process < proc_table + num_proc); process++) {
1136 		if ((process->p_flags & (LIVING|NAMED|TOUCHED|KILLED|OCCUPIED))
1137 		    == (LIVING|NAMED|OCCUPIED)) {
1138 			killproc(process->p_pid);
1139 			process->p_flags |= KILLED;
1140 		} else if ((process->p_flags & (LIVING|NAMED|OCCUPIED)) ==
1141 		    (NAMED|OCCUPIED)) {
1142 			(void) account(DEAD_PROCESS, process, NULL);
1143 			/*
1144 			 * If this named proc hasn't been TOUCHED, then free the
1145 			 * space. It has either died of it's own accord, but
1146 			 * isn't respawnable or it was killed because it
1147 			 * shouldn't exist at this level.
1148 			 */
1149 			if ((process->p_flags & TOUCHED) == 0)
1150 				process->p_flags = 0;
1151 		}
1152 	}
1153 
1154 	st_write();
1155 }
1156 
1157 /*
1158  * Extract the svc.startd command line and whether to restart it from its
1159  * inittab entry.
1160  */
1161 /*ARGSUSED*/
1162 static void
1163 process_startd_line(struct CMD_LINE *cmd, char *cmd_string)
1164 {
1165 	size_t sz;
1166 
1167 	/* Save the command line. */
1168 	if (sflg || rflg) {
1169 		/* Also append -r or -s. */
1170 		(void) strlcpy(startd_cline, cmd_string, sizeof (startd_cline));
1171 		(void) strlcat(startd_cline, " -", sizeof (startd_cline));
1172 		if (sflg)
1173 			sz = strlcat(startd_cline, "s", sizeof (startd_cline));
1174 		if (rflg)
1175 			sz = strlcat(startd_cline, "r", sizeof (startd_cline));
1176 	} else {
1177 		sz = strlcpy(startd_cline, cmd_string, sizeof (startd_cline));
1178 	}
1179 
1180 	if (sz >= sizeof (startd_cline)) {
1181 		console(B_TRUE,
1182 		    "svc.startd command line too long.  Ignoring.\n");
1183 		startd_cline[0] = '\0';
1184 		return;
1185 	}
1186 }
1187 
1188 /*
1189  * spawn_processes() scans inittab for entries which should be run at this
1190  * mode.  Processes which should be running but are not, are started.
1191  */
1192 static int
1193 spawn_processes()
1194 {
1195 	struct PROC_TABLE		*pp;
1196 	struct CMD_LINE			cmd;
1197 	char				cmd_string[MAXCMDL];
1198 	short				lvl_mask;
1199 	int				status;
1200 
1201 	/*
1202 	 * First check the "powerhit" flag.  If it is set, make sure the modes
1203 	 * are PF_MODES and clear the "powerhit" flag.  Avoid the possible race
1204 	 * on the "powerhit" flag by disallowing a new powerfail interrupt
1205 	 * between the test of the powerhit flag and the clearing of it.
1206 	 */
1207 	if (wakeup.w_flags.w_powerhit) {
1208 		wakeup.w_flags.w_powerhit = 0;
1209 		op_modes = PF_MODES;
1210 	}
1211 	lvl_mask = state_to_mask(cur_state);
1212 
1213 	/*
1214 	 * Scan through all the entries in inittab.
1215 	 */
1216 	while ((status = getcmd(&cmd, &cmd_string[0])) == TRUE) {
1217 		if (id_eq(cmd.c_id, "smf")) {
1218 			process_startd_line(&cmd, cmd_string);
1219 			continue;
1220 		}
1221 
1222 retry_for_proc_slot:
1223 
1224 		/*
1225 		 * Find out if there is a process slot for this entry already.
1226 		 */
1227 		if ((pp = findpslot(&cmd)) == NULLPROC) {
1228 			/*
1229 			 * we've run out of proc table entries
1230 			 * increase proc_table.
1231 			 */
1232 			increase_proc_table_size();
1233 
1234 			/*
1235 			 * Retry now as we have an empty proc slot.
1236 			 * In case increase_proc_table_size() fails,
1237 			 * we will keep retrying.
1238 			 */
1239 			goto retry_for_proc_slot;
1240 		}
1241 
1242 		/*
1243 		 * If there is an entry, and it is marked as DEMANDREQUEST,
1244 		 * one of the levels a, b, or c is in its levels mask, and
1245 		 * the action field is ONDEMAND and ONDEMAND is a permissable
1246 		 * mode, and the process is dead, then respawn it.
1247 		 */
1248 		if (((pp->p_flags & (LIVING|DEMANDREQUEST)) == DEMANDREQUEST) &&
1249 		    (cmd.c_levels & MASK_abc) &&
1250 		    (cmd.c_action & op_modes) == M_ONDEMAND) {
1251 			spawn(pp, &cmd);
1252 			continue;
1253 		}
1254 
1255 		/*
1256 		 * If the action is not an action we are interested in,
1257 		 * skip the entry.
1258 		 */
1259 		if ((cmd.c_action & op_modes) == 0 || pp->p_flags & LIVING ||
1260 		    (cmd.c_levels & lvl_mask) == 0)
1261 			continue;
1262 
1263 		/*
1264 		 * If the modes are the normal modes (ONCE, WAIT, RESPAWN, OFF,
1265 		 * ONDEMAND) and the action field is either OFF or the action
1266 		 * field is ONCE or WAIT and the current level is the same as
1267 		 * the last level, then skip this entry.  ONCE and WAIT only
1268 		 * get run when the level changes.
1269 		 */
1270 		if (op_modes == NORMAL_MODES &&
1271 		    (cmd.c_action == M_OFF ||
1272 			(cmd.c_action & (M_ONCE|M_WAIT)) &&
1273 			cur_state == prev_state))
1274 			continue;
1275 
1276 		/*
1277 		 * At this point we are interested in performing the action for
1278 		 * this entry.  Actions fall into two categories, spinning off
1279 		 * a process and not waiting, and spinning off a process and
1280 		 * waiting for it to die.  If the action is ONCE, RESPAWN,
1281 		 * ONDEMAND, POWERFAIL, or BOOT we don't wait for the process
1282 		 * to die, for all other actions we do wait.
1283 		 */
1284 		if (cmd.c_action & (M_ONCE | M_RESPAWN | M_PF | M_BOOT)) {
1285 			spawn(pp, &cmd);
1286 
1287 		} else {
1288 			spawn(pp, &cmd);
1289 			while (waitproc(pp) == FAILURE);
1290 			(void) account(DEAD_PROCESS, pp, NULL);
1291 			pp->p_flags = 0;
1292 		}
1293 	}
1294 	return (status);
1295 }
1296 
1297 /*
1298  * spawn() spawns a shell, inserts the information about the process
1299  * process into the proc_table, and does the startup accounting.
1300  */
1301 static void
1302 spawn(struct PROC_TABLE *process, struct CMD_LINE *cmd)
1303 {
1304 	int		i;
1305 	int		modes, maxfiles;
1306 	time_t		now;
1307 	struct PROC_TABLE tmproc, *oprocess;
1308 
1309 	/*
1310 	 * The modes to be sent to efork() are 0 unless we are
1311 	 * spawning a LVLa, LVLb, or LVLc entry or we will be
1312 	 * waiting for the death of the child before continuing.
1313 	 */
1314 	modes = NAMED;
1315 	if (process->p_flags & DEMANDREQUEST || cur_state == LVLa ||
1316 	    cur_state == LVLb || cur_state == LVLc)
1317 		modes |= DEMANDREQUEST;
1318 	if ((cmd->c_action & (M_SYSINIT | M_WAIT | M_BOOTWAIT | M_PWAIT)) != 0)
1319 		modes |= NOCLEANUP;
1320 
1321 	/*
1322 	 * If this is a respawnable process, check the threshold
1323 	 * information to avoid excessive respawns.
1324 	 */
1325 	if (cmd->c_action & M_RESPAWN) {
1326 		/*
1327 		 * Add NOCLEANUP to all respawnable commands so that the
1328 		 * information about the frequency of respawns isn't lost.
1329 		 */
1330 		modes |= NOCLEANUP;
1331 		(void) time(&now);
1332 
1333 		/*
1334 		 * If no time is assigned, then this is the first time
1335 		 * this command is being processed in this series.  Assign
1336 		 * the current time.
1337 		 */
1338 		if (process->p_time == 0L)
1339 			process->p_time = now;
1340 
1341 		if (process->p_count++ == SPAWN_LIMIT) {
1342 
1343 			if ((now - process->p_time) < SPAWN_INTERVAL) {
1344 				/*
1345 				 * Process is respawning too rapidly.  Print
1346 				 * message and refuse to respawn it for now.
1347 				 */
1348 				console(B_TRUE, "Command is respawning too "
1349 				    "rapidly. Check for possible errors.\n"
1350 				    "id:%4s \"%s\"\n",
1351 				    &cmd->c_id[0], &cmd->c_command[EXEC]);
1352 				return;
1353 			}
1354 			process->p_time = now;
1355 			process->p_count = 0;
1356 
1357 		} else if (process->p_count > SPAWN_LIMIT) {
1358 			/*
1359 			 * If process has been respawning too rapidly and
1360 			 * the inhibit time limit hasn't expired yet, we
1361 			 * refuse to respawn.
1362 			 */
1363 			if (now - process->p_time < SPAWN_INTERVAL + INHIBIT)
1364 				return;
1365 			process->p_time = now;
1366 			process->p_count = 0;
1367 		}
1368 		rsflag = TRUE;
1369 	}
1370 
1371 	/*
1372 	 * Spawn a child process to execute this command.
1373 	 */
1374 	(void) sigset(SIGCLD, SIG_DFL);
1375 	oprocess = process;
1376 	while ((process = efork(cmd->c_action, oprocess, modes)) == NO_ROOM)
1377 		(void) pause();
1378 
1379 	if (process == NULLPROC) {
1380 
1381 		/*
1382 		 * We are the child.  We must make sure we get a different
1383 		 * file pointer for our references to utmpx.  Otherwise our
1384 		 * seeks and reads will compete with those of the parent.
1385 		 */
1386 		endutxent();
1387 
1388 		/*
1389 		 * Perform the accounting for the beginning of a process.
1390 		 * Note that all processes are initially "INIT_PROCESS"es.
1391 		 */
1392 		tmproc.p_id[0] = cmd->c_id[0];
1393 		tmproc.p_id[1] = cmd->c_id[1];
1394 		tmproc.p_id[2] = cmd->c_id[2];
1395 		tmproc.p_id[3] = cmd->c_id[3];
1396 		tmproc.p_pid = getpid();
1397 		tmproc.p_exit = 0;
1398 		(void) account(INIT_PROCESS, &tmproc,
1399 		    prog_name(&cmd->c_command[EXEC]));
1400 		maxfiles = ulimit(UL_GDESLIM, 0);
1401 		for (i = 0; i < maxfiles; i++)
1402 			(void) fcntl(i, F_SETFD, FD_CLOEXEC);
1403 
1404 		/*
1405 		 * Now exec a shell with the -c option and the command
1406 		 * from inittab.
1407 		 */
1408 		(void) execle(SH, "INITSH", "-c", cmd->c_command, (char *)0,
1409 		    glob_envp);
1410 		console(B_TRUE, "Command\n\"%s\"\n failed to execute.  errno "
1411 		    "= %d (exec of shell failed)\n", cmd->c_command, errno);
1412 
1413 		/*
1414 		 * Don't come back so quickly that "init" doesn't have a
1415 		 * chance to finish putting this child in "proc_table".
1416 		 */
1417 		timer(20);
1418 		exit(1);
1419 
1420 	}
1421 
1422 	/*
1423 	 * We are the parent.  Insert the necessary
1424 	 * information in the proc_table.
1425 	 */
1426 	process->p_id[0] = cmd->c_id[0];
1427 	process->p_id[1] = cmd->c_id[1];
1428 	process->p_id[2] = cmd->c_id[2];
1429 	process->p_id[3] = cmd->c_id[3];
1430 
1431 	st_write();
1432 
1433 	(void) sigset(SIGCLD, childeath);
1434 }
1435 
1436 /*
1437  * findpslot() finds the old slot in the process table for the
1438  * command with the same id, or it finds an empty slot.
1439  */
1440 static struct PROC_TABLE *
1441 findpslot(struct CMD_LINE *cmd)
1442 {
1443 	struct PROC_TABLE	*process;
1444 	struct PROC_TABLE	*empty = NULLPROC;
1445 
1446 	for (process = proc_table;
1447 	    (process < proc_table + num_proc); process++) {
1448 		if (process->p_flags & OCCUPIED &&
1449 		    id_eq(process->p_id, cmd->c_id))
1450 			break;
1451 
1452 		/*
1453 		 * If the entry is totally empty and "empty" is still 0,
1454 		 * remember where this hole is and make sure the slot is
1455 		 * zeroed out.
1456 		 */
1457 		if (empty == NULLPROC && (process->p_flags & OCCUPIED) == 0) {
1458 			empty = process;
1459 			process->p_id[0] = '\0';
1460 			process->p_id[1] = '\0';
1461 			process->p_id[2] = '\0';
1462 			process->p_id[3] = '\0';
1463 			process->p_pid = 0;
1464 			process->p_time = 0L;
1465 			process->p_count = 0;
1466 			process->p_flags = 0;
1467 			process->p_exit = 0;
1468 		}
1469 	}
1470 
1471 	/*
1472 	 * If there is no entry for this slot, then there should be an
1473 	 * empty slot.  If there is no empty slot, then we've run out
1474 	 * of proc_table space.  If the latter is true, empty will be
1475 	 * NULL and the caller will have to complain.
1476 	 */
1477 	if (process == (proc_table + num_proc))
1478 		process = empty;
1479 
1480 	return (process);
1481 }
1482 
1483 /*
1484  * getcmd() parses lines from inittab.  Each time it finds a command line
1485  * it will return TRUE as well as fill the passed CMD_LINE structure and
1486  * the shell command string.  When the end of inittab is reached, FALSE
1487  * is returned inittab is automatically opened if it is not currently open
1488  * and is closed when the end of the file is reached.
1489  */
1490 static FILE *fp_inittab = NULL;
1491 
1492 static int
1493 getcmd(struct CMD_LINE *cmd, char *shcmd)
1494 {
1495 	char	*ptr;
1496 	int	c, lastc, state;
1497 	char 	*ptr1;
1498 	int	answer, i, proceed;
1499 	struct	stat	sbuf;
1500 	static char *actions[] = {
1501 		"off", "respawn", "ondemand", "once", "wait", "boot",
1502 		"bootwait", "powerfail", "powerwait", "initdefault",
1503 		"sysinit",
1504 	};
1505 	static short act_masks[] = {
1506 		M_OFF, M_RESPAWN, M_ONDEMAND, M_ONCE, M_WAIT, M_BOOT,
1507 		M_BOOTWAIT, M_PF, M_PWAIT, M_INITDEFAULT, M_SYSINIT,
1508 	};
1509 	/*
1510 	 * Only these actions will be allowed for entries which
1511 	 * are specified for single-user mode.
1512 	 */
1513 	short su_acts = M_INITDEFAULT | M_PF | M_PWAIT | M_WAIT;
1514 
1515 	if (fp_inittab == NULL) {
1516 		/*
1517 		 * Before attempting to open inittab we stat it to make
1518 		 * sure it currently exists and is not empty.  We try
1519 		 * several times because someone may have temporarily
1520 		 * unlinked or truncated the file.
1521 		 */
1522 		for (i = 0; i < 3; i++) {
1523 			if (stat(INITTAB, &sbuf) == -1) {
1524 				if (i == 2) {
1525 					console(B_TRUE,
1526 					    "Cannot stat %s, errno: %d\n",
1527 					    INITTAB, errno);
1528 					return (FAILURE);
1529 				} else {
1530 					timer(3);
1531 				}
1532 			} else if (sbuf.st_size < 10) {
1533 				if (i == 2) {
1534 					console(B_TRUE,
1535 					    "%s truncated or corrupted\n",
1536 					    INITTAB);
1537 					return (FAILURE);
1538 				} else {
1539 					timer(3);
1540 				}
1541 			} else {
1542 				break;
1543 			}
1544 		}
1545 
1546 		/*
1547 		 * If unable to open inittab, print error message and
1548 		 * return FAILURE to caller.
1549 		 */
1550 		if ((fp_inittab = fopen(INITTAB, "r")) == NULL) {
1551 			console(B_TRUE, "Cannot open %s errno: %d\n", INITTAB,
1552 			    errno);
1553 			return (FAILURE);
1554 		}
1555 	}
1556 
1557 	/*
1558 	 * Keep getting commands from inittab until you find a
1559 	 * good one or run out of file.
1560 	 */
1561 	for (answer = FALSE; answer == FALSE; ) {
1562 		/*
1563 		 * Zero out the cmd itself before trying next line.
1564 		 */
1565 		bzero(cmd, sizeof (struct CMD_LINE));
1566 
1567 		/*
1568 		 * Read in lines of inittab, parsing at colons, until a line is
1569 		 * read in which doesn't end with a backslash.  Do not start if
1570 		 * the first character read is an EOF.  Note that this means
1571 		 * that lines which don't end in a newline are still processed,
1572 		 * since the "for" will terminate normally once started,
1573 		 * regardless of whether line terminates with a newline or EOF.
1574 		 */
1575 		state = FAILURE;
1576 		if ((c = fgetc(fp_inittab)) == EOF) {
1577 			answer = FALSE;
1578 			(void) fclose(fp_inittab);
1579 			fp_inittab = NULL;
1580 			break;
1581 		}
1582 
1583 		for (proceed = TRUE, ptr = shcmd, state = ID, lastc = '\0';
1584 		    proceed && c != EOF;
1585 		    lastc = c, c = fgetc(fp_inittab)) {
1586 		    /* If we're not in the FAILURE state and haven't	*/
1587 		    /* yet reached the shell command field, process	*/
1588 		    /* the line, otherwise just look for a real end	*/
1589 		    /* of line.						*/
1590 		    if (state != FAILURE && state != COMMAND) {
1591 			/*
1592 			 * Squeeze out spaces and tabs.
1593 			 */
1594 			if (c == ' ' || c == '\t')
1595 				continue;
1596 
1597 			/*
1598 			 * Ignore characters in a comment, except for the \n.
1599 			 */
1600 			if (state == COMMENT) {
1601 				if (c == '\n') {
1602 					lastc = ' ';
1603 					break;
1604 				} else {
1605 					continue;
1606 				}
1607 			}
1608 
1609 			/*
1610 			 * Detect comments (lines whose first non-whitespace
1611 			 * character is '#') by checking that we're at the
1612 			 * beginning of a line, have seen a '#', and haven't
1613 			 * yet accumulated any characters.
1614 			 */
1615 			if (state == ID && c == '#' && ptr == shcmd) {
1616 				state = COMMENT;
1617 				continue;
1618 			}
1619 
1620 			/*
1621 			 * If the character is a ':', then check the
1622 			 * previous field for correctness and advance
1623 			 * to the next field.
1624 			 */
1625 			if (c == ':') {
1626 			    switch (state) {
1627 
1628 			    case ID :
1629 				/*
1630 				 * Check to see that there are only
1631 				 * 1 to 4 characters for the id.
1632 				 */
1633 				if ((i = ptr - shcmd) < 1 || i > 4) {
1634 					state = FAILURE;
1635 				} else {
1636 					bcopy(shcmd, &cmd->c_id[0], i);
1637 					ptr = shcmd;
1638 					state = LEVELS;
1639 				}
1640 				break;
1641 
1642 			    case LEVELS :
1643 				/*
1644 				 * Build a mask for all the levels for
1645 				 * which this command will be legal.
1646 				 */
1647 				for (cmd->c_levels = 0, ptr1 = shcmd;
1648 				    ptr1 < ptr; ptr1++) {
1649 					int mask;
1650 					if (lvlname_to_mask(*ptr1,
1651 					    &mask) == -1) {
1652 						state = FAILURE;
1653 						break;
1654 					}
1655 					cmd->c_levels |= mask;
1656 				}
1657 				if (state != FAILURE) {
1658 					state = ACTION;
1659 					ptr = shcmd;	/* Reset the buffer */
1660 				}
1661 				break;
1662 
1663 			    case ACTION :
1664 				/*
1665 				 * Null terminate the string in shcmd buffer and
1666 				 * then try to match against legal actions.  If
1667 				 * the field is of length 0, then the default of
1668 				 * "RESPAWN" is used if the id is numeric,
1669 				 * otherwise the default is "OFF".
1670 				 */
1671 				if (ptr == shcmd) {
1672 					if (isdigit(cmd->c_id[0]) &&
1673 					    (cmd->c_id[1] == '\0' ||
1674 						isdigit(cmd->c_id[1])) &&
1675 					    (cmd->c_id[2] == '\0' ||
1676 						isdigit(cmd->c_id[2])) &&
1677 					    (cmd->c_id[3] == '\0' ||
1678 						isdigit(cmd->c_id[3])))
1679 						    cmd->c_action = M_RESPAWN;
1680 					else
1681 						    cmd->c_action = M_OFF;
1682 				} else {
1683 				    for (cmd->c_action = 0, i = 0, *ptr = '\0';
1684 				    i < sizeof (actions)/sizeof (char *);
1685 				    i++) {
1686 					if (strcmp(shcmd, actions[i]) == 0) {
1687 					    if ((cmd->c_levels & MASKSU) &&
1688 						!(act_masks[i] & su_acts))
1689 						    cmd->c_action = 0;
1690 					    else
1691 						cmd->c_action = act_masks[i];
1692 					    break;
1693 					}
1694 				    }
1695 				}
1696 
1697 				/*
1698 				 * If the action didn't match any legal action,
1699 				 * set state to FAILURE.
1700 				 */
1701 				if (cmd->c_action == 0) {
1702 					state = FAILURE;
1703 				} else {
1704 					state = COMMAND;
1705 					(void) strcpy(shcmd, "exec ");
1706 				}
1707 				ptr = shcmd + EXEC;
1708 				break;
1709 			    }
1710 			    continue;
1711 			}
1712 		    }
1713 
1714 		    /* If the character is a '\n', then this is the end of a */
1715 		    /* line.  If the '\n' wasn't preceded by a backslash, */
1716 		    /* it is also the end of an inittab command.  If it was */
1717 		    /* preceded by a backslash then the next line is a */
1718 		    /* continuation.  Note that the continuation '\n' falls */
1719 		    /* through and is treated like other characters and is */
1720 		    /* stored in the shell command line. */
1721 		    if (c == '\n' && lastc != '\\') {
1722 				proceed = FALSE;
1723 				*ptr = '\0';
1724 				break;
1725 		    }
1726 
1727 		    /* For all other characters just stuff them into the */
1728 		    /* command as long as there aren't too many of them. */
1729 		    /* Make sure there is room for a terminating '\0' also. */
1730 		    if (ptr >= shcmd + MAXCMDL - 1)
1731 			state = FAILURE;
1732 		    else
1733 			*ptr++ = (char)c;
1734 
1735 		    /* If the character we just stored was a quoted	*/
1736 		    /* backslash, then change "c" to '\0', so that this	*/
1737 		    /* backslash will not cause a subsequent '\n' to appear */
1738 		    /* quoted.  In otherwords '\' '\' '\n' is the real end */
1739 		    /* of a command, while '\' '\n' is a continuation. */
1740 		    if (c == '\\' && lastc == '\\')
1741 			c = '\0';
1742 		}
1743 
1744 		/*
1745 		 * Make sure all the fields are properly specified
1746 		 * for a good command line.
1747 		 */
1748 		if (state == COMMAND) {
1749 			answer = TRUE;
1750 			cmd->c_command = shcmd;
1751 
1752 			/*
1753 			 * If no default level was supplied, insert
1754 			 * all numerical levels.
1755 			 */
1756 			if (cmd->c_levels == 0)
1757 				cmd->c_levels = MASK_NUMERIC;
1758 
1759 			/*
1760 			 * If no action has been supplied, declare this
1761 			 * entry to be OFF.
1762 			 */
1763 			if (cmd->c_action == 0)
1764 				cmd->c_action = M_OFF;
1765 
1766 			/*
1767 			 * If no shell command has been supplied, make sure
1768 			 * there is a null string in the command field.
1769 			 */
1770 			if (ptr == shcmd + EXEC)
1771 				*shcmd = '\0';
1772 		} else
1773 			answer = FALSE;
1774 
1775 		/*
1776 		 * If we have reached the end of inittab, then close it
1777 		 * and quit trying to find a good command line.
1778 		 */
1779 		if (c == EOF) {
1780 			(void) fclose(fp_inittab);
1781 			fp_inittab = NULL;
1782 			break;
1783 		}
1784 	}
1785 	return (answer);
1786 }
1787 
1788 /*
1789  * lvlname_to_state(): convert the character name of a state to its level
1790  * (its corresponding signal number).
1791  */
1792 static int
1793 lvlname_to_state(char name)
1794 {
1795 	int i;
1796 	for (i = 0; i < LVL_NELEMS; i++) {
1797 		if (lvls[i].lvl_name == name)
1798 			return (lvls[i].lvl_state);
1799 	}
1800 	return (-1);
1801 }
1802 
1803 /*
1804  * state_to_name(): convert the level to the character name.
1805  */
1806 static char
1807 state_to_name(int state)
1808 {
1809 	int i;
1810 	for (i = 0; i < LVL_NELEMS; i++) {
1811 		if (lvls[i].lvl_state == state)
1812 			return (lvls[i].lvl_name);
1813 	}
1814 	return (-1);
1815 }
1816 
1817 /*
1818  * state_to_mask(): return the mask corresponding to a signal number
1819  */
1820 static int
1821 state_to_mask(int state)
1822 {
1823 	int i;
1824 	for (i = 0; i < LVL_NELEMS; i++) {
1825 		if (lvls[i].lvl_state == state)
1826 			return (lvls[i].lvl_mask);
1827 	}
1828 	return (0);	/* return 0, since that represents an empty mask */
1829 }
1830 
1831 /*
1832  * lvlname_to_mask(): return the mask corresponding to a levels character name
1833  */
1834 static int
1835 lvlname_to_mask(char name, int *mask)
1836 {
1837 	int i;
1838 	for (i = 0; i < LVL_NELEMS; i++) {
1839 		if (lvls[i].lvl_name == name) {
1840 			*mask = lvls[i].lvl_mask;
1841 			return (0);
1842 		}
1843 	}
1844 	return (-1);
1845 }
1846 
1847 /*
1848  * state_to_flags(): return the flags corresponding to a runlevel.  These
1849  * indicate properties of that runlevel.
1850  */
1851 static int
1852 state_to_flags(int state)
1853 {
1854 	int i;
1855 	for (i = 0; i < LVL_NELEMS; i++) {
1856 		if (lvls[i].lvl_state == state)
1857 			return (lvls[i].lvl_flags);
1858 	}
1859 	return (0);
1860 }
1861 
1862 /*
1863  * killproc() creates a child which kills the process specified by pid.
1864  */
1865 void
1866 killproc(pid_t pid)
1867 {
1868 	struct PROC_TABLE	*process;
1869 
1870 	(void) sigset(SIGCLD, SIG_DFL);
1871 	while ((process = efork(M_OFF, NULLPROC, 0)) == NO_ROOM)
1872 		(void) pause();
1873 	(void) sigset(SIGCLD, childeath);
1874 
1875 	if (process == NULLPROC) {
1876 		/*
1877 		 * efork() sets all signal handlers to the default, so reset
1878 		 * the ALRM handler to make timer() work as expected.
1879 		 */
1880 		(void) sigset(SIGALRM, alarmclk);
1881 
1882 		/*
1883 		 * We are the child.  Try to terminate the process nicely
1884 		 * first using SIGTERM and if it refuses to die in TWARN
1885 		 * seconds kill it with SIGKILL.
1886 		 */
1887 		(void) kill(pid, SIGTERM);
1888 		(void) timer(TWARN);
1889 		(void) kill(pid, SIGKILL);
1890 		(void) exit(0);
1891 	}
1892 }
1893 
1894 /*
1895  * Set up the default environment for all procs to be forked from init.
1896  * Read the values from the /etc/default/init file, except for PATH.  If
1897  * there's not enough room in the environment array, the environment
1898  * lines that don't fit are silently discarded.
1899  */
1900 void
1901 init_env()
1902 {
1903 	char	line[MAXCMDL];
1904 	FILE	*fp;
1905 	int	inquotes, length, wslength;
1906 	char	*tokp, *cp1, *cp2;
1907 
1908 	glob_envp[0] = malloc((unsigned)(strlen(DEF_PATH)+2));
1909 	(void) strcpy(glob_envp[0], DEF_PATH);
1910 	glob_envn = 1;
1911 
1912 	if (rflg) {
1913 		glob_envp[1] =
1914 			malloc((unsigned)(strlen("_DVFS_RECONFIG=YES")+2));
1915 		(void) strcpy(glob_envp[1], "_DVFS_RECONFIG=YES");
1916 		++glob_envn;
1917 	} else if (bflg == 1) {
1918 		glob_envp[1] =
1919 			malloc((unsigned)(strlen("RB_NOBOOTRC=YES")+2));
1920 		(void) strcpy(glob_envp[1], "RB_NOBOOTRC=YES");
1921 		++glob_envn;
1922 	}
1923 
1924 	if ((fp = fopen(ENVFILE, "r")) == NULL) {
1925 		console(B_TRUE,
1926 		    "Cannot open %s. Environment not initialized.\n",
1927 		    ENVFILE);
1928 	} else {
1929 		while (fgets(line, MAXCMDL - 1, fp) != NULL &&
1930 		    glob_envn < MAXENVENT - 2) {
1931 			/*
1932 			 * Toss newline
1933 			 */
1934 			length = strlen(line);
1935 			if (line[length - 1] == '\n')
1936 				line[length - 1] = '\0';
1937 
1938 			/*
1939 			 * Ignore blank or comment lines.
1940 			 */
1941 			if (line[0] == '#' || line[0] == '\0' ||
1942 			    (wslength = strspn(line, " \t\n")) ==
1943 			    strlen(line) ||
1944 			    strchr(line, '#') == line + wslength)
1945 				continue;
1946 
1947 			/*
1948 			 * First make a pass through the line and change
1949 			 * any non-quoted semi-colons to blanks so they
1950 			 * will be treated as token separators below.
1951 			 */
1952 			inquotes = 0;
1953 			for (cp1 = line; *cp1 != '\0'; cp1++) {
1954 				if (*cp1 == '"') {
1955 					if (inquotes == 0)
1956 						inquotes = 1;
1957 					else
1958 						inquotes = 0;
1959 				} else if (*cp1 == ';') {
1960 					if (inquotes == 0)
1961 						*cp1 = ' ';
1962 				}
1963 			}
1964 
1965 			/*
1966 			 * Tokens within the line are separated by blanks
1967 			 *  and tabs.  For each token in the line which
1968 			 * contains a '=' we strip out any quotes and then
1969 			 * stick the token in the environment array.
1970 			 */
1971 			if ((tokp = strtok(line, " \t")) == NULL)
1972 				continue;
1973 			do {
1974 				if (strchr(tokp, '=') == NULL)
1975 					continue;
1976 				length = strlen(tokp);
1977 				while ((cp1 = strpbrk(tokp, "\"\'")) != NULL) {
1978 					for (cp2 = cp1;
1979 					    cp2 < &tokp[length]; cp2++)
1980 						*cp2 = *(cp2 + 1);
1981 					length--;
1982 				}
1983 
1984 				if (strncmp(tokp, "CMASK=",
1985 				    sizeof ("CMASK=") - 1) == 0) {
1986 					long t;
1987 
1988 					/* We know there's an = */
1989 					t = strtol(strchr(tokp, '=') + 1, NULL,
1990 					    8);
1991 
1992 					/* Sanity */
1993 					if (t <= 077 && t >= 0)
1994 						cmask = (int)t;
1995 					(void) umask(cmask);
1996 					continue;
1997 				}
1998 				glob_envp[glob_envn] =
1999 				    malloc((unsigned)(length + 1));
2000 				(void) strcpy(glob_envp[glob_envn], tokp);
2001 				if (++glob_envn >= MAXENVENT - 1)
2002 					break;
2003 			} while ((tokp = strtok(NULL, " \t")) != NULL);
2004 		}
2005 
2006 		/*
2007 		 * Append a null pointer to the environment array
2008 		 * to mark its end.
2009 		 */
2010 		glob_envp[glob_envn] = NULL;
2011 		(void) fclose(fp);
2012 	}
2013 }
2014 
2015 /*
2016  * boot_init(): Do initialization things that should be done at boot.
2017  */
2018 void
2019 boot_init()
2020 {
2021 	int i;
2022 	struct PROC_TABLE *process, *oprocess;
2023 	struct CMD_LINE	cmd;
2024 	char	line[MAXCMDL];
2025 	char *old_path;
2026 	int maxfiles;
2027 
2028 	/* Use INIT_PATH for sysinit cmds */
2029 	old_path = glob_envp[0];
2030 	glob_envp[0] = malloc((unsigned)(strlen(INIT_PATH)+2));
2031 	(void) strcpy(glob_envp[0], INIT_PATH);
2032 
2033 	/*
2034 	 * Scan inittab(4) and process the special svc.startd entry, initdefault
2035 	 * and sysinit entries.
2036 	 */
2037 	while (getcmd(&cmd, &line[0]) == TRUE) {
2038 		if (startd_tmpl >= 0 && id_eq(cmd.c_id, "smf"))
2039 			process_startd_line(&cmd, line);
2040 		else if (cmd.c_action == M_INITDEFAULT) {
2041 			/*
2042 			 * initdefault is no longer meaningful, as the SMF
2043 			 * milestone controls what (legacy) run level we
2044 			 * boot to.
2045 			 */
2046 			console(B_TRUE,
2047 			    "Ignoring legacy \"initdefault\" entry.\n");
2048 		} else if (cmd.c_action == M_SYSINIT) {
2049 			/*
2050 			 * Execute the "sysinit" entry and wait for it to
2051 			 * complete.  No bookkeeping is performed on these
2052 			 * entries because we avoid writing to the file system
2053 			 * until after there has been an chance to check it.
2054 			 */
2055 			if (process = findpslot(&cmd)) {
2056 				(void) sigset(SIGCLD, SIG_DFL);
2057 
2058 				for (oprocess = process;
2059 				    (process = efork(M_OFF, oprocess,
2060 				    (NAMED|NOCLEANUP))) == NO_ROOM;
2061 				    /* CSTYLED */)
2062 					;
2063 				(void) sigset(SIGCLD, childeath);
2064 
2065 				if (process == NULLPROC) {
2066 					maxfiles = ulimit(UL_GDESLIM, 0);
2067 
2068 					for (i = 0; i < maxfiles; i++)
2069 						(void) fcntl(i, F_SETFD,
2070 						    FD_CLOEXEC);
2071 					(void) execle(SH, "INITSH", "-c",
2072 					    cmd.c_command,
2073 					    (char *)0, glob_envp);
2074 					console(B_TRUE,
2075 "Command\n\"%s\"\n failed to execute.  errno = %d (exec of shell failed)\n",
2076 						cmd.c_command, errno);
2077 					exit(1);
2078 				} else while (waitproc(process) == FAILURE);
2079 				process->p_flags = 0;
2080 				st_write();
2081 			}
2082 		}
2083 	}
2084 
2085 	/* Restore the path. */
2086 	free(glob_envp[0]);
2087 	glob_envp[0] = old_path;
2088 
2089 	/*
2090 	 * This will enable st_write() to complain about init_state_file.
2091 	 */
2092 	booting = 0;
2093 
2094 	/*
2095 	 * If the /etc/ioctl.syscon didn't exist or had invalid contents write
2096 	 * out a correct version.
2097 	 */
2098 	if (write_ioctl)
2099 		write_ioctl_syscon();
2100 
2101 	/*
2102 	 * Start svc.startd(1M), which does most of the work.
2103 	 */
2104 	if (startd_cline[0] != '\0' && startd_tmpl >= 0) {
2105 		/* Start svc.startd. */
2106 		if (startd_run(startd_cline, startd_tmpl, 0) == -1)
2107 			cur_state = SINGLE_USER;
2108 	} else {
2109 		console(B_TRUE, "Absent svc.startd entry or bad "
2110 		    "contract template.  Not starting svc.startd.\n");
2111 		enter_maintenance();
2112 	}
2113 }
2114 
2115 /*
2116  * init_signals(): Initialize all signals to either be caught or ignored.
2117  */
2118 void
2119 init_signals(void)
2120 {
2121 	struct sigaction act;
2122 	int i;
2123 
2124 	/*
2125 	 * Start by ignoring all signals, then selectively re-enable some.
2126 	 * The SIG_IGN disposition will only affect asynchronous signals:
2127 	 * any signal that we trigger synchronously that doesn't end up
2128 	 * being handled by siglvl() will be forcibly delivered by the kernel.
2129 	 */
2130 	for (i = SIGHUP; i <= SIGRTMAX; i++)
2131 		(void) sigset(i, SIG_IGN);
2132 
2133 	/*
2134 	 * Handle all level-changing signals using siglvl() and set sa_mask so
2135 	 * that all level-changing signals are blocked while in siglvl().
2136 	 */
2137 	act.sa_handler = siglvl;
2138 	act.sa_flags = SA_SIGINFO;
2139 	(void) sigemptyset(&act.sa_mask);
2140 
2141 	(void) sigaddset(&act.sa_mask, LVLQ);
2142 	(void) sigaddset(&act.sa_mask, LVL0);
2143 	(void) sigaddset(&act.sa_mask, LVL1);
2144 	(void) sigaddset(&act.sa_mask, LVL2);
2145 	(void) sigaddset(&act.sa_mask, LVL3);
2146 	(void) sigaddset(&act.sa_mask, LVL4);
2147 	(void) sigaddset(&act.sa_mask, LVL5);
2148 	(void) sigaddset(&act.sa_mask, LVL6);
2149 	(void) sigaddset(&act.sa_mask, SINGLE_USER);
2150 	(void) sigaddset(&act.sa_mask, LVLa);
2151 	(void) sigaddset(&act.sa_mask, LVLb);
2152 	(void) sigaddset(&act.sa_mask, LVLc);
2153 
2154 	(void) sigaction(LVLQ, &act, NULL);
2155 	(void) sigaction(LVL0, &act, NULL);
2156 	(void) sigaction(LVL1, &act, NULL);
2157 	(void) sigaction(LVL2, &act, NULL);
2158 	(void) sigaction(LVL3, &act, NULL);
2159 	(void) sigaction(LVL4, &act, NULL);
2160 	(void) sigaction(LVL5, &act, NULL);
2161 	(void) sigaction(LVL6, &act, NULL);
2162 	(void) sigaction(SINGLE_USER, &act, NULL);
2163 	(void) sigaction(LVLa, &act, NULL);
2164 	(void) sigaction(LVLb, &act, NULL);
2165 	(void) sigaction(LVLc, &act, NULL);
2166 
2167 	(void) sigset(SIGALRM, alarmclk);
2168 	alarmclk();
2169 
2170 	(void) sigset(SIGCLD, childeath);
2171 	(void) sigset(SIGPWR, powerfail);
2172 }
2173 
2174 /*
2175  * Set up pipe for "godchildren". If the file exists and is a pipe just open
2176  * it. Else, if the file system is r/w create it.  Otherwise, defer its
2177  * creation and open until after the sysinit functions have had a chance to
2178  * make the root read/write.
2179  */
2180 void
2181 setup_pipe()
2182 {
2183 	struct stat stat_buf;
2184 	struct statvfs statvfs_buf;
2185 
2186 	if ((stat(INITPIPE, &stat_buf) == 0) &&
2187 	    ((stat_buf.st_mode & (S_IFMT|S_IRUSR)) == (S_IFIFO|S_IRUSR)))
2188 		Pfd = open(INITPIPE, O_RDWR | O_NDELAY);
2189 	else
2190 		if ((statvfs(INITPIPE_DIR, &statvfs_buf) == 0) &&
2191 		    ((statvfs_buf.f_flag & ST_RDONLY) == 0)) {
2192 			(void) unlink(INITPIPE);
2193 			(void) mknod(INITPIPE, S_IFIFO | 0600, 0);
2194 			Pfd = open(INITPIPE, O_RDWR | O_NDELAY);
2195 		}
2196 
2197 	if (Pfd >= 0) {
2198 		(void) ioctl(Pfd, I_SETSIG, S_INPUT);
2199 		/*
2200 		 * Read pipe in message discard mode.
2201 		 */
2202 		(void) ioctl(Pfd, I_SRDOPT, RMSGD);
2203 		(void) sigset(SIGPOLL, sigpoll);
2204 	}
2205 }
2206 
2207 /*
2208  * siglvl - handle an asynchronous signal from init(1M) telling us that we
2209  * should change the current run level.  We set new_state accordingly.
2210  */
2211 void
2212 siglvl(int sig, siginfo_t *sip, ucontext_t *ucp)
2213 {
2214 	struct PROC_TABLE *process;
2215 	struct sigaction act;
2216 
2217 	/*
2218 	 * If the signal was from the kernel (rather than init(1M)) then init
2219 	 * itself tripped the signal.  That is, we might have a bug and tripped
2220 	 * a real SIGSEGV instead of receiving it as an alias for SIGLVLa.  In
2221 	 * such a case we reset the disposition to SIG_DFL, block all signals
2222 	 * in uc_mask but the current one, and return to the interrupted ucp
2223 	 * to effect an appropriate death.  The kernel will then restart us.
2224 	 *
2225 	 * The one exception to SI_FROMKERNEL() is SIGFPE (a.k.a. LVL6), which
2226 	 * the kernel can send us when it wants to effect an orderly reboot.
2227 	 * For this case we must also verify si_code is zero, rather than a
2228 	 * code such as FPE_INTDIV which a bug might have triggered.
2229 	 */
2230 	if (sip != NULL && SI_FROMKERNEL(sip) &&
2231 	    (sig != SIGFPE || sip->si_code == 0)) {
2232 
2233 		(void) sigemptyset(&act.sa_mask);
2234 		act.sa_handler = SIG_DFL;
2235 		act.sa_flags = 0;
2236 		(void) sigaction(sig, &act, NULL);
2237 
2238 		(void) sigfillset(&ucp->uc_sigmask);
2239 		(void) sigdelset(&ucp->uc_sigmask, sig);
2240 		ucp->uc_flags |= UC_SIGMASK;
2241 
2242 		(void) setcontext(ucp);
2243 	}
2244 
2245 	/*
2246 	 * If the signal received is a LVLQ signal, do not really
2247 	 * change levels, just restate the current level.  If the
2248 	 * signal is not a LVLQ, set the new level to the signal
2249 	 * received.
2250 	 */
2251 	if (sig == LVLQ)
2252 		new_state = cur_state;
2253 	else
2254 		new_state = sig;
2255 
2256 	/*
2257 	 * Clear all times and repeat counts in the process table
2258 	 * since either the level is changing or the user has editted
2259 	 * the inittab file and wants us to look at it again.
2260 	 * If the user has fixed a typo, we don't want residual timing
2261 	 * data preventing the fixed command line from executing.
2262 	 */
2263 	for (process = proc_table;
2264 		(process < proc_table + num_proc); process++) {
2265 		process->p_time = 0L;
2266 		process->p_count = 0;
2267 	}
2268 
2269 	/*
2270 	 * Set the flag to indicate that a "user signal" was received.
2271 	 */
2272 	wakeup.w_flags.w_usersignal = 1;
2273 }
2274 
2275 
2276 /*
2277  * alarmclk
2278  */
2279 static void
2280 alarmclk()
2281 {
2282 	time_up = TRUE;
2283 }
2284 
2285 /*
2286  * childeath_single():
2287  *
2288  * This used to be the SIGCLD handler and it was set with signal()
2289  * (as opposed to sigset()).  When a child exited we'd come to the
2290  * handler, wait for the child, and reenable the handler with
2291  * signal() just before returning.  The implementation of signal()
2292  * checks with waitid() for waitable children and sends a SIGCLD
2293  * if there are some.  If children are exiting faster than the
2294  * handler can run we keep sending signals and the handler never
2295  * gets to return and eventually the stack runs out and init dies.
2296  * To prevent that we set the handler with sigset() so the handler
2297  * doesn't need to be reset, and in childeath() (see below) we
2298  * call childeath_single() as long as there are children to be
2299  * waited for.  If a child exits while init is in the handler a
2300  * SIGCLD will be pending and delivered on return from the handler.
2301  * If the child was already waited for the handler will have nothing
2302  * to do and return, otherwise the child will be waited for.
2303  */
2304 static void
2305 childeath_single()
2306 {
2307 	struct PROC_TABLE	*process;
2308 	struct pidlist		*pp;
2309 	pid_t			pid;
2310 	int			status;
2311 
2312 	/*
2313 	 * Perform wait to get the process id of the child that died and
2314 	 * then scan the process table to see if we are interested in
2315 	 * this process. NOTE: if a super-user sends the SIGCLD signal
2316 	 * to init, the following wait will not immediately return and
2317 	 * init will be inoperative until one of its child really does die.
2318 	 */
2319 	pid = wait(&status);
2320 
2321 	for (process = proc_table;
2322 		(process < proc_table + num_proc); process++) {
2323 		if ((process->p_flags & (LIVING|OCCUPIED)) ==
2324 		    (LIVING|OCCUPIED) && process->p_pid == pid) {
2325 
2326 			/*
2327 			 * Mark this process as having died and store the exit
2328 			 * status.  Also set the wakeup flag for a dead child
2329 			 * and break out of the loop.
2330 			 */
2331 			process->p_flags &= ~LIVING;
2332 			process->p_exit = (short)status;
2333 			wakeup.w_flags.w_childdeath = 1;
2334 
2335 			return;
2336 		}
2337 	}
2338 
2339 	/*
2340 	 * No process was found above, look through auxiliary list.
2341 	 */
2342 	(void) sighold(SIGPOLL);
2343 	pp = Plhead;
2344 	while (pp) {
2345 		if (pid > pp->pl_pid) {
2346 			/*
2347 			 * Keep on looking.
2348 			 */
2349 			pp = pp->pl_next;
2350 			continue;
2351 		} else if (pid < pp->pl_pid) {
2352 			/*
2353 			 * Not in the list.
2354 			 */
2355 			break;
2356 		} else {
2357 			/*
2358 			 * This is a dead "godchild".
2359 			 */
2360 			pp->pl_dflag = 1;
2361 			pp->pl_exit = (short)status;
2362 			wakeup.w_flags.w_childdeath = 1;
2363 			Gchild = 1;	/* Notice to call cleanaux(). */
2364 			break;
2365 		}
2366 	}
2367 
2368 	(void) sigrelse(SIGPOLL);
2369 }
2370 
2371 /* ARGSUSED */
2372 static void
2373 childeath(int signo)
2374 {
2375 	siginfo_t info;
2376 
2377 	while ((waitid(P_ALL, (id_t)0, &info, WEXITED|WNOHANG|WNOWAIT) == 0) &&
2378 	    info.si_pid != 0)
2379 		childeath_single();
2380 }
2381 
2382 static void
2383 powerfail()
2384 {
2385 	(void) nice(-19);
2386 	wakeup.w_flags.w_powerhit = 1;
2387 }
2388 
2389 /*
2390  * efork() forks a child and the parent inserts the process in its table
2391  * of processes that are directly a result of forks that it has performed.
2392  * The child just changes the "global" with the process id for this process
2393  * to it's new value.
2394  * If efork() is called with a pointer into the proc_table it uses that slot,
2395  * otherwise it searches for a free slot.  Regardless of how it was called,
2396  * it returns the pointer to the proc_table entry
2397  *
2398  * The SIGCLD handler is set to default (SIG_DFL) before calling efork().
2399  * This relies on the somewhat obscure SVR2 SIGCLD/SIG_DFL semantic
2400  * implied by the use of signal(3c).  While the meaning of SIG_DFL for
2401  * SIGCLD is nominally to ignore the signal, once the signal disposition
2402  * is set to childeath(), the kernel will post a SIGCLD if a child
2403  * exited during the period the disposition was SIG_DFL.  It acts more
2404  * like a signal block.
2405  *
2406  * Ideally, this should be rewritten to use modern signal semantics.
2407  */
2408 static struct PROC_TABLE *
2409 efork(int action, struct PROC_TABLE *process, int modes)
2410 {
2411 	pid_t	childpid;
2412 	struct PROC_TABLE *proc;
2413 	int		i;
2414 	void (*oldroutine)();
2415 	/*
2416 	 * Freshen up the proc_table, removing any entries for dead processes
2417 	 * that don't have NOCLEANUP set.  Perform the necessary accounting.
2418 	 */
2419 	for (proc = proc_table; (proc < proc_table + num_proc); proc++) {
2420 		if ((proc->p_flags & (OCCUPIED|LIVING|NOCLEANUP)) ==
2421 		    (OCCUPIED)) {
2422 			/*
2423 			 * Is this a named process?
2424 			 * If so, do the necessary bookkeeping.
2425 			 */
2426 			if (proc->p_flags & NAMED)
2427 				(void) account(DEAD_PROCESS, proc, NULL);
2428 
2429 			/*
2430 			 * Free this entry for new usage.
2431 			 */
2432 			proc->p_flags = 0;
2433 		}
2434 	}
2435 
2436 	while ((childpid = fork()) == FAILURE) {
2437 		/*
2438 		 * Shorten the alarm timer in case someone else's child dies
2439 		 * and free up a slot in the process table.
2440 		 */
2441 		setimer(5);
2442 
2443 		/*
2444 		 * Wait for some children to die.  Since efork() is normally
2445 		 * called with SIGCLD in the default state, reset it to catch
2446 		 * so that child death signals can come in.
2447 		 */
2448 		oldroutine = sigset(SIGCLD, childeath);
2449 		(void) pause();
2450 		(void) sigset(SIGCLD, oldroutine);
2451 		setimer(0);
2452 	}
2453 
2454 	if (childpid != 0) {
2455 
2456 		if (process == NULLPROC) {
2457 			/*
2458 			 * No proc table pointer specified so search
2459 			 * for a free slot.
2460 			 */
2461 			for (process = proc_table;  process->p_flags != 0 &&
2462 				(process < proc_table + num_proc); process++)
2463 					;
2464 
2465 			if (process == (proc_table + num_proc)) {
2466 				int old_proc_table_size = num_proc;
2467 
2468 				/* Increase the process table size */
2469 				increase_proc_table_size();
2470 				if (old_proc_table_size == num_proc) {
2471 					/* didn't grow: memory failure */
2472 					return (NO_ROOM);
2473 				} else {
2474 					process =
2475 					    proc_table + old_proc_table_size;
2476 				}
2477 			}
2478 
2479 			process->p_time = 0L;
2480 			process->p_count = 0;
2481 		}
2482 		process->p_id[0] = '\0';
2483 		process->p_id[1] = '\0';
2484 		process->p_id[2] = '\0';
2485 		process->p_id[3] = '\0';
2486 		process->p_pid = childpid;
2487 		process->p_flags = (LIVING | OCCUPIED | modes);
2488 		process->p_exit = 0;
2489 
2490 		st_write();
2491 	} else {
2492 		if ((action & (M_WAIT | M_BOOTWAIT)) == 0)
2493 			(void) setpgrp();
2494 
2495 		process = NULLPROC;
2496 
2497 		/*
2498 		 * Reset all signals to the system defaults.
2499 		 */
2500 		for (i = SIGHUP; i <= SIGRTMAX; i++)
2501 			(void) sigset(i, SIG_DFL);
2502 
2503 		/*
2504 		 * POSIX B.2.2.2 advises that init should set SIGTTOU,
2505 		 * SIGTTIN, and SIGTSTP to SIG_IGN.
2506 		 *
2507 		 * Make sure that SIGXCPU and SIGXFSZ also remain ignored,
2508 		 * for backward compatibility.
2509 		 */
2510 		(void) sigset(SIGTTIN, SIG_IGN);
2511 		(void) sigset(SIGTTOU, SIG_IGN);
2512 		(void) sigset(SIGTSTP, SIG_IGN);
2513 		(void) sigset(SIGXCPU, SIG_IGN);
2514 		(void) sigset(SIGXFSZ, SIG_IGN);
2515 	}
2516 	return (process);
2517 }
2518 
2519 
2520 /*
2521  * waitproc() waits for a specified process to die.  For this function to
2522  * work, the specified process must already in the proc_table.  waitproc()
2523  * returns the exit status of the specified process when it dies.
2524  */
2525 static long
2526 waitproc(struct PROC_TABLE *process)
2527 {
2528 	int		answer;
2529 	sigset_t	oldmask, newmask, zeromask;
2530 
2531 	(void) sigemptyset(&zeromask);
2532 	(void) sigemptyset(&newmask);
2533 
2534 	(void) sigaddset(&newmask, SIGCLD);
2535 
2536 	/* Block SIGCLD and save the current signal mask */
2537 	if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
2538 		perror("SIG_BLOCK error");
2539 
2540 	/*
2541 	 * Wait around until the process dies.
2542 	 */
2543 	if (process->p_flags & LIVING)
2544 		(void) sigsuspend(&zeromask);
2545 
2546 	/* Reset signal mask to unblock SIGCLD */
2547 	if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
2548 		perror("SIG_SETMASK error");
2549 
2550 	if (process->p_flags & LIVING)
2551 		return (FAILURE);
2552 
2553 	/*
2554 	 * Make sure to only return 16 bits so that answer will always
2555 	 * be positive whenever the process of interest really died.
2556 	 */
2557 	answer = (process->p_exit & 0xffff);
2558 
2559 	/*
2560 	 * Free the slot in the proc_table.
2561 	 */
2562 	process->p_flags = 0;
2563 	return (answer);
2564 }
2565 
2566 /*
2567  * notify_pam_dead(): calls into the PAM framework to close the given session.
2568  */
2569 static void
2570 notify_pam_dead(struct utmpx *up)
2571 {
2572 	pam_handle_t *pamh;
2573 	char user[sizeof (up->ut_user) + 1];
2574 	char ttyn[sizeof (up->ut_line) + 1];
2575 	char host[sizeof (up->ut_host) + 1];
2576 
2577 	/*
2578 	 * PAM does not take care of updating utmpx/wtmpx.
2579 	 */
2580 	(void) snprintf(user, sizeof (user), "%s", up->ut_user);
2581 	(void) snprintf(ttyn, sizeof (ttyn), "%s", up->ut_line);
2582 	(void) snprintf(host, sizeof (host), "%s", up->ut_host);
2583 
2584 	if (pam_start("init", user, NULL, &pamh) == PAM_SUCCESS)  {
2585 		(void) pam_set_item(pamh, PAM_TTY, ttyn);
2586 		(void) pam_set_item(pamh, PAM_RHOST, host);
2587 		(void) pam_close_session(pamh, 0);
2588 		(void) pam_end(pamh, PAM_SUCCESS);
2589 	}
2590 }
2591 
2592 /*
2593  * Check you can access utmpx (As / may be read-only and
2594  * /var may not be mounted yet).
2595  */
2596 static int
2597 access_utmpx(void)
2598 {
2599 	do {
2600 		utmpx_ok = (access(UTMPX, R_OK|W_OK) == 0);
2601 	} while (!utmpx_ok && errno == EINTR);
2602 
2603 	return (utmpx_ok);
2604 }
2605 
2606 /*
2607  * account() updates entries in utmpx and appends new entries to the end of
2608  * wtmpx (assuming they exist).  The program argument indicates the name of
2609  * program if INIT_PROCESS, otherwise should be NULL.
2610  *
2611  * account() only blocks for INIT_PROCESS requests.
2612  *
2613  * Returns non-zero if write failed.
2614  */
2615 static int
2616 account(short state, struct PROC_TABLE *process, char *program)
2617 {
2618 	struct utmpx utmpbuf, *u, *oldu;
2619 	int tmplen;
2620 	char fail_buf[UT_LINE_SZ];
2621 	sigset_t block, unblock;
2622 
2623 	if (!utmpx_ok && !access_utmpx()) {
2624 		return (-1);
2625 	}
2626 
2627 	/*
2628 	 * Set up the prototype for the utmp structure we want to write.
2629 	 */
2630 	u = &utmpbuf;
2631 	(void) memset(u, 0, sizeof (struct utmpx));
2632 
2633 	/*
2634 	 * Fill in the various fields of the utmp structure.
2635 	 */
2636 	u->ut_id[0] = process->p_id[0];
2637 	u->ut_id[1] = process->p_id[1];
2638 	u->ut_id[2] = process->p_id[2];
2639 	u->ut_id[3] = process->p_id[3];
2640 	u->ut_pid = process->p_pid;
2641 
2642 	/*
2643 	 * Fill the "ut_exit" structure.
2644 	 */
2645 	u->ut_exit.e_termination = WTERMSIG(process->p_exit);
2646 	u->ut_exit.e_exit = WEXITSTATUS(process->p_exit);
2647 	u->ut_type = state;
2648 
2649 	(void) time(&u->ut_tv.tv_sec);
2650 
2651 	/*
2652 	 * Block signals for utmp update.
2653 	 */
2654 	(void) sigfillset(&block);
2655 	(void) sigprocmask(SIG_BLOCK, &block, &unblock);
2656 
2657 	/*
2658 	 * See if there already is such an entry in the "utmpx" file.
2659 	 */
2660 	setutxent();	/* Start at beginning of utmpx file. */
2661 
2662 	if ((oldu = getutxid(u)) != NULL) {
2663 		/*
2664 		 * Copy in the old "user", "line" and "host" fields
2665 		 * to our new structure.
2666 		 */
2667 		bcopy(oldu->ut_user, u->ut_user, sizeof (u->ut_user));
2668 		bcopy(oldu->ut_line, u->ut_line, sizeof (u->ut_line));
2669 		bcopy(oldu->ut_host, u->ut_host, sizeof (u->ut_host));
2670 		u->ut_syslen = (tmplen = strlen(u->ut_host)) ?
2671 			min(tmplen + 1, sizeof (u->ut_host)) : 0;
2672 
2673 		if (oldu->ut_type == USER_PROCESS && state == DEAD_PROCESS) {
2674 			notify_pam_dead(oldu);
2675 		}
2676 	}
2677 
2678 	/*
2679 	 * Perform special accounting. Insert the special string into the
2680 	 * ut_line array. For INIT_PROCESSes put in the name of the
2681 	 * program in the "ut_user" field.
2682 	 */
2683 	switch (state) {
2684 	case INIT_PROCESS:
2685 		(void) strncpy(u->ut_user, program, sizeof (u->ut_user));
2686 		(void) strcpy(fail_buf, "INIT_PROCESS");
2687 		break;
2688 
2689 	default:
2690 		(void) strlcpy(fail_buf, u->ut_id, sizeof (u->ut_id) + 1);
2691 		break;
2692 	}
2693 
2694 	/*
2695 	 * Write out the updated entry to utmpx file.
2696 	 */
2697 	if (pututxline(u) == NULL) {
2698 		console(B_TRUE, "Failed write of utmpx entry: \"%s\": %s\n",
2699 		    fail_buf, strerror(errno));
2700 		endutxent();
2701 		(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2702 		return (-1);
2703 	}
2704 
2705 	/*
2706 	 * If we're able to write to utmpx, then attempt to add to the
2707 	 * end of the wtmpx file.
2708 	 */
2709 	updwtmpx(WTMPX, u);
2710 
2711 	endutxent();
2712 
2713 	(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2714 
2715 	return (0);
2716 }
2717 
2718 static void
2719 clearent(pid_t pid, short status)
2720 {
2721 	struct utmpx *up;
2722 	sigset_t block, unblock;
2723 
2724 	/*
2725 	 * Block signals for utmp update.
2726 	 */
2727 	(void) sigfillset(&block);
2728 	(void) sigprocmask(SIG_BLOCK, &block, &unblock);
2729 
2730 	/*
2731 	 * No error checking for now.
2732 	 */
2733 
2734 	setutxent();
2735 	while (up = getutxent()) {
2736 		if (up->ut_pid == pid) {
2737 			if (up->ut_type == DEAD_PROCESS) {
2738 				/*
2739 				 * Cleaned up elsewhere.
2740 				 */
2741 				continue;
2742 			}
2743 
2744 			notify_pam_dead(up);
2745 
2746 			up->ut_type = DEAD_PROCESS;
2747 			up->ut_exit.e_termination = WTERMSIG(status);
2748 			up->ut_exit.e_exit = WEXITSTATUS(status);
2749 			(void) time(&up->ut_tv.tv_sec);
2750 
2751 			(void) pututxline(up);
2752 			/*
2753 			 * Now attempt to add to the end of the
2754 			 * wtmp and wtmpx files.  Do not create
2755 			 * if they don't already exist.
2756 			 */
2757 			updwtmpx(WTMPX, up);
2758 
2759 			break;
2760 		}
2761 	}
2762 
2763 	endutxent();
2764 	(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2765 }
2766 
2767 /*
2768  * prog_name() searches for the word or unix path name and
2769  * returns a pointer to the last element of the pathname.
2770  */
2771 static char *
2772 prog_name(char *string)
2773 {
2774 	char	*ptr, *ptr2;
2775 	/* XXX - utmp - fix name length */
2776 	static char word[_POSIX_LOGIN_NAME_MAX];
2777 
2778 	/*
2779 	 * Search for the first word skipping leading spaces and tabs.
2780 	 */
2781 	while (*string == ' ' || *string == '\t')
2782 		string++;
2783 
2784 	/*
2785 	 * If the first non-space non-tab character is not one allowed in
2786 	 * a word, return a pointer to a null string, otherwise parse the
2787 	 * pathname.
2788 	 */
2789 	if (*string != '.' && *string != '/' && *string != '_' &&
2790 	    (*string < 'a' || *string > 'z') &&
2791 	    (*string < 'A' || * string > 'Z') &&
2792 	    (*string < '0' || *string > '9'))
2793 		return ("");
2794 
2795 	/*
2796 	 * Parse the pathname looking forward for '/', ' ', '\t', '\n' or
2797 	 * '\0'.  Each time a '/' is found, move "ptr" to one past the
2798 	 * '/', thus when a ' ', '\t', '\n', or '\0' is found, "ptr" will
2799 	 * point to the last element of the pathname.
2800 	 */
2801 	for (ptr = string;
2802 		*string != ' ' && *string != '\t' && *string != '\n' &&
2803 							*string != '\0';
2804 		string++) {
2805 		if (*string == '/')
2806 			ptr = string+1;
2807 	}
2808 
2809 	/*
2810 	 * Copy out up to the size of the "ut_user" array into "word",
2811 	 * null terminate it and return a pointer to it.
2812 	 */
2813 	/* XXX - utmp - fix name length */
2814 	for (ptr2 = &word[0]; ptr2 < &word[_POSIX_LOGIN_NAME_MAX - 1] &&
2815 	    ptr < string; /* CSTYLED */)
2816 		*ptr2++ = *ptr++;
2817 
2818 	*ptr2 = '\0';
2819 	return (&word[0]);
2820 }
2821 
2822 
2823 /*
2824  * realcon() returns a nonzero value if there is a character device
2825  * associated with SYSCON that has the same device number as CONSOLE.
2826  */
2827 static int
2828 realcon()
2829 {
2830 	struct stat sconbuf, conbuf;
2831 
2832 	if (stat(SYSCON, &sconbuf) != -1 &&
2833 	    stat(CONSOLE, &conbuf) != -1 &&
2834 	    S_ISCHR(sconbuf.st_mode) &&
2835 	    S_ISCHR(conbuf.st_mode) &&
2836 	    sconbuf.st_rdev == conbuf.st_rdev) {
2837 		return (1);
2838 	} else {
2839 		return (0);
2840 	}
2841 }
2842 
2843 
2844 /*
2845  * get_ioctl_syscon() retrieves the SYSCON settings from the IOCTLSYSCON file.
2846  * Returns true if the IOCTLSYSCON file needs to be written (with
2847  * write_ioctl_syscon() below)
2848  */
2849 static int
2850 get_ioctl_syscon()
2851 {
2852 	FILE	*fp;
2853 	unsigned int	iflags, oflags, cflags, lflags, ldisc, cc[18];
2854 	int		i, valid_format = 0;
2855 
2856 	/*
2857 	 * Read in the previous modes for SYSCON from IOCTLSYSCON.
2858 	 */
2859 	if ((fp = fopen(IOCTLSYSCON, "r")) == NULL) {
2860 		stored_syscon_termios = dflt_termios;
2861 		console(B_TRUE,
2862 		    "warning:%s does not exist, default settings assumed\n",
2863 		    IOCTLSYSCON);
2864 	} else {
2865 
2866 	    i = fscanf(fp,
2867 	    "%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x",
2868 		&iflags, &oflags, &cflags, &lflags,
2869 		&cc[0], &cc[1], &cc[2], &cc[3], &cc[4], &cc[5], &cc[6],
2870 		&cc[7], &cc[8], &cc[9], &cc[10], &cc[11], &cc[12], &cc[13],
2871 		&cc[14], &cc[15], &cc[16], &cc[17]);
2872 
2873 	    if (i == 22) {
2874 		stored_syscon_termios.c_iflag = iflags;
2875 		stored_syscon_termios.c_oflag = oflags;
2876 		stored_syscon_termios.c_cflag = cflags;
2877 		stored_syscon_termios.c_lflag = lflags;
2878 		for (i = 0; i < 18; i++)
2879 			stored_syscon_termios.c_cc[i] = (char)cc[i];
2880 		valid_format = 1;
2881 	    } else if (i == 13) {
2882 		rewind(fp);
2883 		i = fscanf(fp, "%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x:%x",
2884 		    &iflags, &oflags, &cflags, &lflags, &ldisc, &cc[0], &cc[1],
2885 		    &cc[2], &cc[3], &cc[4], &cc[5], &cc[6], &cc[7]);
2886 
2887 		/*
2888 		 * If the file is formatted properly, use the values to
2889 		 * initialize the console terminal condition.
2890 		 */
2891 		stored_syscon_termios.c_iflag = (ushort_t)iflags;
2892 		stored_syscon_termios.c_oflag = (ushort_t)oflags;
2893 		stored_syscon_termios.c_cflag = (ushort_t)cflags;
2894 		stored_syscon_termios.c_lflag = (ushort_t)lflags;
2895 		for (i = 0; i < 8; i++)
2896 			stored_syscon_termios.c_cc[i] = (char)cc[i];
2897 		valid_format = 1;
2898 	    }
2899 	    (void) fclose(fp);
2900 
2901 	    /* If the file is badly formatted, use the default settings. */
2902 	    if (!valid_format)
2903 		stored_syscon_termios = dflt_termios;
2904 	}
2905 
2906 	/* If the file had a bad format, rewrite it later. */
2907 	return (!valid_format);
2908 }
2909 
2910 
2911 static void
2912 write_ioctl_syscon()
2913 {
2914 	FILE *fp;
2915 	int i;
2916 
2917 	(void) unlink(SYSCON);
2918 	(void) link(SYSTTY, SYSCON);
2919 	(void) umask(022);
2920 	fp = fopen(IOCTLSYSCON, "w");
2921 
2922 	(void) fprintf(fp, "%x:%x:%x:%x:0", stored_syscon_termios.c_iflag,
2923 	    stored_syscon_termios.c_oflag, stored_syscon_termios.c_cflag,
2924 	    stored_syscon_termios.c_lflag);
2925 	for (i = 0; i < 8; ++i)
2926 		(void) fprintf(fp, ":%x", stored_syscon_termios.c_cc[i]);
2927 	(void) putc('\n', fp);
2928 
2929 	(void) fflush(fp);
2930 	(void) fsync(fileno(fp));
2931 	(void) fclose(fp);
2932 	(void) umask(cmask);
2933 }
2934 
2935 
2936 /*
2937  * void console(boolean_t, char *, ...)
2938  *   Outputs the requested message to the system console.  Note that the number
2939  *   of arguments passed to console() should be determined by the print format.
2940  *
2941  *   The "prefix" parameter indicates whether or not "INIT: " should precede the
2942  *   message.
2943  *
2944  *   To make sure we write to the console in a sane fashion, we use the modes
2945  *   we keep in stored_syscon_termios (which we read out of /etc/ioctl.syscon).
2946  *   Afterwards we restore whatever modes were already there.
2947  */
2948 /* PRINTFLIKE2 */
2949 static void
2950 console(boolean_t prefix, char *format, ...)
2951 {
2952 	char	outbuf[BUFSIZ];
2953 	va_list	args;
2954 	int fd, getret;
2955 	struct termios old_syscon_termios;
2956 	FILE *f;
2957 
2958 	/*
2959 	 * We open SYSCON anew each time in case it has changed (see
2960 	 * userinit()).
2961 	 */
2962 	if ((fd = open(SYSCON, O_RDWR | O_NOCTTY)) < 0 ||
2963 	    (f = fdopen(fd, "r+")) == NULL) {
2964 		if (prefix)
2965 			syslog(LOG_WARNING, "INIT: ");
2966 		va_start(args, format);
2967 		vsyslog(LOG_WARNING, format, args);
2968 		va_end(args);
2969 		if (fd >= 0)
2970 			(void) close(fd);
2971 		return;
2972 	}
2973 	setbuf(f, &outbuf[0]);
2974 
2975 	getret = tcgetattr(fd, &old_syscon_termios);
2976 	old_syscon_termios.c_cflag &= ~HUPCL;
2977 	if (realcon())
2978 		/* Don't overwrite cflag of real console. */
2979 		stored_syscon_termios.c_cflag = old_syscon_termios.c_cflag;
2980 
2981 	stored_syscon_termios.c_cflag &= ~HUPCL;
2982 
2983 	(void) tcsetattr(fd, TCSANOW, &stored_syscon_termios);
2984 
2985 	if (prefix)
2986 		(void) fprintf(f, "\nINIT: ");
2987 	va_start(args, format);
2988 	(void) vfprintf(f, format, args);
2989 	va_end(args);
2990 
2991 	if (getret == 0)
2992 		(void) tcsetattr(fd, TCSADRAIN, &old_syscon_termios);
2993 
2994 	(void) fclose(f);
2995 }
2996 
2997 /*
2998  * timer() is a substitute for sleep() which uses alarm() and pause().
2999  */
3000 static void
3001 timer(int waitime)
3002 {
3003 	setimer(waitime);
3004 	while (time_up == FALSE)
3005 		(void) pause();
3006 }
3007 
3008 static void
3009 setimer(int timelimit)
3010 {
3011 	alarmclk();
3012 	(void) alarm(timelimit);
3013 	time_up = (timelimit ? FALSE : TRUE);
3014 }
3015 
3016 /*
3017  * Fails with
3018  *   ENOMEM - out of memory
3019  *   ECONNABORTED - repository connection broken
3020  *   EPERM - permission denied
3021  *   EACCES - backend access denied
3022  *   EROFS - backend readonly
3023  */
3024 static int
3025 get_or_add_startd(scf_instance_t *inst)
3026 {
3027 	scf_handle_t *h;
3028 	scf_scope_t *scope = NULL;
3029 	scf_service_t *svc = NULL;
3030 	int ret = 0;
3031 
3032 	h = scf_instance_handle(inst);
3033 
3034 	if (scf_handle_decode_fmri(h, SCF_SERVICE_STARTD, NULL, NULL, inst,
3035 	    NULL, NULL, SCF_DECODE_FMRI_EXACT) == 0)
3036 		return (0);
3037 
3038 	switch (scf_error()) {
3039 	case SCF_ERROR_CONNECTION_BROKEN:
3040 		return (ECONNABORTED);
3041 
3042 	case SCF_ERROR_NOT_FOUND:
3043 		break;
3044 
3045 	case SCF_ERROR_HANDLE_MISMATCH:
3046 	case SCF_ERROR_INVALID_ARGUMENT:
3047 	case SCF_ERROR_CONSTRAINT_VIOLATED:
3048 	default:
3049 		bad_error("scf_handle_decode_fmri", scf_error());
3050 	}
3051 
3052 	/* Make sure we're right, since we're adding piece-by-piece. */
3053 	assert(strcmp(SCF_SERVICE_STARTD,
3054 	    "svc:/system/svc/restarter:default") == 0);
3055 
3056 	if ((scope = scf_scope_create(h)) == NULL ||
3057 	    (svc = scf_service_create(h)) == NULL) {
3058 		ret = ENOMEM;
3059 		goto out;
3060 	}
3061 
3062 get_scope:
3063 	if (scf_handle_get_scope(h, SCF_SCOPE_LOCAL, scope) != 0) {
3064 		switch (scf_error()) {
3065 		case SCF_ERROR_CONNECTION_BROKEN:
3066 			ret = ECONNABORTED;
3067 			goto out;
3068 
3069 		case SCF_ERROR_NOT_FOUND:
3070 			(void) fputs(gettext(
3071 			    "smf(5) repository missing local scope.\n"),
3072 			    stderr);
3073 			exit(1);
3074 			/* NOTREACHED */
3075 
3076 		case SCF_ERROR_HANDLE_MISMATCH:
3077 		case SCF_ERROR_INVALID_ARGUMENT:
3078 		default:
3079 			bad_error("scf_handle_get_scope", scf_error());
3080 		}
3081 	}
3082 
3083 get_svc:
3084 	if (scf_scope_get_service(scope, "system/svc/restarter", svc) != 0) {
3085 		switch (scf_error()) {
3086 		case SCF_ERROR_CONNECTION_BROKEN:
3087 			ret = ECONNABORTED;
3088 			goto out;
3089 
3090 		case SCF_ERROR_DELETED:
3091 			goto get_scope;
3092 
3093 		case SCF_ERROR_NOT_FOUND:
3094 			break;
3095 
3096 		case SCF_ERROR_HANDLE_MISMATCH:
3097 		case SCF_ERROR_INVALID_ARGUMENT:
3098 		case SCF_ERROR_NOT_SET:
3099 		default:
3100 			bad_error("scf_scope_get_service", scf_error());
3101 		}
3102 
3103 add_svc:
3104 		if (scf_scope_add_service(scope, "system/svc/restarter", svc) !=
3105 		    0) {
3106 			switch (scf_error()) {
3107 			case SCF_ERROR_CONNECTION_BROKEN:
3108 				ret = ECONNABORTED;
3109 				goto out;
3110 
3111 			case SCF_ERROR_EXISTS:
3112 				goto get_svc;
3113 
3114 			case SCF_ERROR_PERMISSION_DENIED:
3115 				ret = EPERM;
3116 				goto out;
3117 
3118 			case SCF_ERROR_BACKEND_ACCESS:
3119 				ret = EACCES;
3120 				goto out;
3121 
3122 			case SCF_ERROR_BACKEND_READONLY:
3123 				ret = EROFS;
3124 				goto out;
3125 
3126 			case SCF_ERROR_HANDLE_MISMATCH:
3127 			case SCF_ERROR_INVALID_ARGUMENT:
3128 			case SCF_ERROR_NOT_SET:
3129 			default:
3130 				bad_error("scf_scope_add_service", scf_error());
3131 			}
3132 		}
3133 	}
3134 
3135 get_inst:
3136 	if (scf_service_get_instance(svc, "default", inst) != 0) {
3137 		switch (scf_error()) {
3138 		case SCF_ERROR_CONNECTION_BROKEN:
3139 			ret = ECONNABORTED;
3140 			goto out;
3141 
3142 		case SCF_ERROR_DELETED:
3143 			goto add_svc;
3144 
3145 		case SCF_ERROR_NOT_FOUND:
3146 			break;
3147 
3148 		case SCF_ERROR_HANDLE_MISMATCH:
3149 		case SCF_ERROR_INVALID_ARGUMENT:
3150 		case SCF_ERROR_NOT_SET:
3151 		default:
3152 			bad_error("scf_service_get_instance", scf_error());
3153 		}
3154 
3155 		if (scf_service_add_instance(svc, "default", inst) !=
3156 		    0) {
3157 			switch (scf_error()) {
3158 			case SCF_ERROR_CONNECTION_BROKEN:
3159 				ret = ECONNABORTED;
3160 				goto out;
3161 
3162 			case SCF_ERROR_DELETED:
3163 				goto add_svc;
3164 
3165 			case SCF_ERROR_EXISTS:
3166 				goto get_inst;
3167 
3168 			case SCF_ERROR_PERMISSION_DENIED:
3169 				ret = EPERM;
3170 				goto out;
3171 
3172 			case SCF_ERROR_BACKEND_ACCESS:
3173 				ret = EACCES;
3174 				goto out;
3175 
3176 			case SCF_ERROR_BACKEND_READONLY:
3177 				ret = EROFS;
3178 				goto out;
3179 
3180 			case SCF_ERROR_HANDLE_MISMATCH:
3181 			case SCF_ERROR_INVALID_ARGUMENT:
3182 			case SCF_ERROR_NOT_SET:
3183 			default:
3184 				bad_error("scf_service_add_instance",
3185 				    scf_error());
3186 			}
3187 		}
3188 	}
3189 
3190 	ret = 0;
3191 
3192 out:
3193 	scf_service_destroy(svc);
3194 	scf_scope_destroy(scope);
3195 	return (ret);
3196 }
3197 
3198 /*
3199  * Fails with
3200  *   ECONNABORTED - repository connection broken
3201  *   ECANCELED - the transaction's property group was deleted
3202  */
3203 static int
3204 transaction_add_set(scf_transaction_t *tx, scf_transaction_entry_t *ent,
3205     const char *pname, scf_type_t type)
3206 {
3207 change_type:
3208 	if (scf_transaction_property_change_type(tx, ent, pname, type) == 0)
3209 		return (0);
3210 
3211 	switch (scf_error()) {
3212 	case SCF_ERROR_CONNECTION_BROKEN:
3213 		return (ECONNABORTED);
3214 
3215 	case SCF_ERROR_DELETED:
3216 		return (ECANCELED);
3217 
3218 	case SCF_ERROR_NOT_FOUND:
3219 		goto new;
3220 
3221 	case SCF_ERROR_HANDLE_MISMATCH:
3222 	case SCF_ERROR_INVALID_ARGUMENT:
3223 	case SCF_ERROR_NOT_BOUND:
3224 	case SCF_ERROR_NOT_SET:
3225 	default:
3226 		bad_error("scf_transaction_property_change_type", scf_error());
3227 	}
3228 
3229 new:
3230 	if (scf_transaction_property_new(tx, ent, pname, type) == 0)
3231 		return (0);
3232 
3233 	switch (scf_error()) {
3234 	case SCF_ERROR_CONNECTION_BROKEN:
3235 		return (ECONNABORTED);
3236 
3237 	case SCF_ERROR_DELETED:
3238 		return (ECANCELED);
3239 
3240 	case SCF_ERROR_EXISTS:
3241 		goto change_type;
3242 
3243 	case SCF_ERROR_HANDLE_MISMATCH:
3244 	case SCF_ERROR_INVALID_ARGUMENT:
3245 	case SCF_ERROR_NOT_BOUND:
3246 	case SCF_ERROR_NOT_SET:
3247 	default:
3248 		bad_error("scf_transaction_property_new", scf_error());
3249 		/* NOTREACHED */
3250 	}
3251 }
3252 
3253 static void
3254 scferr(void)
3255 {
3256 	switch (scf_error()) {
3257 	case SCF_ERROR_NO_MEMORY:
3258 		console(B_TRUE, gettext("Out of memory.\n"));
3259 		break;
3260 
3261 	case SCF_ERROR_CONNECTION_BROKEN:
3262 		console(B_TRUE, gettext(
3263 		    "Connection to smf(5) repository server broken.\n"));
3264 		break;
3265 
3266 	case SCF_ERROR_NO_RESOURCES:
3267 		console(B_TRUE, gettext(
3268 		    "smf(5) repository server is out of memory.\n"));
3269 		break;
3270 
3271 	case SCF_ERROR_PERMISSION_DENIED:
3272 		console(B_TRUE, gettext("Insufficient privileges.\n"));
3273 		break;
3274 
3275 	default:
3276 		console(B_TRUE, gettext("libscf error: %s\n"),
3277 		    scf_strerror(scf_error()));
3278 	}
3279 }
3280 
3281 static void
3282 lscf_set_runlevel(char rl)
3283 {
3284 	scf_handle_t *h;
3285 	scf_instance_t *inst = NULL;
3286 	scf_propertygroup_t *pg = NULL;
3287 	scf_transaction_t *tx = NULL;
3288 	scf_transaction_entry_t *ent = NULL;
3289 	scf_value_t *val = NULL;
3290 	char buf[2];
3291 	int r;
3292 
3293 	h = scf_handle_create(SCF_VERSION);
3294 	if (h == NULL) {
3295 		scferr();
3296 		return;
3297 	}
3298 
3299 	if (scf_handle_bind(h) != 0) {
3300 		switch (scf_error()) {
3301 		case SCF_ERROR_NO_SERVER:
3302 			console(B_TRUE,
3303 			    gettext("smf(5) repository server not running.\n"));
3304 			goto bail;
3305 
3306 		default:
3307 			scferr();
3308 			goto bail;
3309 		}
3310 	}
3311 
3312 	if ((inst = scf_instance_create(h)) == NULL ||
3313 	    (pg = scf_pg_create(h)) == NULL ||
3314 	    (val = scf_value_create(h)) == NULL ||
3315 	    (tx = scf_transaction_create(h)) == NULL ||
3316 	    (ent = scf_entry_create(h)) == NULL) {
3317 		scferr();
3318 		goto bail;
3319 	}
3320 
3321 get_inst:
3322 	r = get_or_add_startd(inst);
3323 	switch (r) {
3324 	case 0:
3325 		break;
3326 
3327 	case ENOMEM:
3328 	case ECONNABORTED:
3329 	case EPERM:
3330 	case EACCES:
3331 	case EROFS:
3332 		scferr();
3333 		goto bail;
3334 	default:
3335 		bad_error("get_or_add_startd", r);
3336 	}
3337 
3338 get_pg:
3339 	if (scf_instance_get_pg(inst, SCF_PG_OPTIONS_OVR, pg) != 0) {
3340 		switch (scf_error()) {
3341 		case SCF_ERROR_CONNECTION_BROKEN:
3342 			scferr();
3343 			goto bail;
3344 
3345 		case SCF_ERROR_DELETED:
3346 			goto get_inst;
3347 
3348 		case SCF_ERROR_NOT_FOUND:
3349 			break;
3350 
3351 		case SCF_ERROR_HANDLE_MISMATCH:
3352 		case SCF_ERROR_INVALID_ARGUMENT:
3353 		case SCF_ERROR_NOT_SET:
3354 		default:
3355 			bad_error("scf_instance_get_pg", scf_error());
3356 		}
3357 
3358 add_pg:
3359 		if (scf_instance_add_pg(inst, SCF_PG_OPTIONS_OVR,
3360 		    SCF_PG_OPTIONS_OVR_TYPE, SCF_PG_OPTIONS_OVR_FLAGS, pg) !=
3361 		    0) {
3362 			switch (scf_error()) {
3363 			case SCF_ERROR_CONNECTION_BROKEN:
3364 			case SCF_ERROR_PERMISSION_DENIED:
3365 			case SCF_ERROR_BACKEND_ACCESS:
3366 				scferr();
3367 				goto bail;
3368 
3369 			case SCF_ERROR_DELETED:
3370 				goto get_inst;
3371 
3372 			case SCF_ERROR_EXISTS:
3373 				goto get_pg;
3374 
3375 			case SCF_ERROR_HANDLE_MISMATCH:
3376 			case SCF_ERROR_INVALID_ARGUMENT:
3377 			case SCF_ERROR_NOT_SET:
3378 			default:
3379 				bad_error("scf_instance_add_pg", scf_error());
3380 			}
3381 		}
3382 	}
3383 
3384 	buf[0] = rl;
3385 	buf[1] = '\0';
3386 	r = scf_value_set_astring(val, buf);
3387 	assert(r == 0);
3388 
3389 	for (;;) {
3390 		if (scf_transaction_start(tx, pg) != 0) {
3391 			switch (scf_error()) {
3392 			case SCF_ERROR_CONNECTION_BROKEN:
3393 			case SCF_ERROR_PERMISSION_DENIED:
3394 			case SCF_ERROR_BACKEND_ACCESS:
3395 				scferr();
3396 				goto bail;
3397 
3398 			case SCF_ERROR_DELETED:
3399 				goto add_pg;
3400 
3401 			case SCF_ERROR_HANDLE_MISMATCH:
3402 			case SCF_ERROR_NOT_BOUND:
3403 			case SCF_ERROR_IN_USE:
3404 			case SCF_ERROR_NOT_SET:
3405 			default:
3406 				bad_error("scf_transaction_start", scf_error());
3407 			}
3408 		}
3409 
3410 		r = transaction_add_set(tx, ent, "runlevel", SCF_TYPE_ASTRING);
3411 		switch (r) {
3412 		case 0:
3413 			break;
3414 
3415 		case ECONNABORTED:
3416 			scferr();
3417 			goto bail;
3418 
3419 		case ECANCELED:
3420 			scf_transaction_reset(tx);
3421 			goto add_pg;
3422 
3423 		default:
3424 			bad_error("transaction_add_set", r);
3425 		}
3426 
3427 		r = scf_entry_add_value(ent, val);
3428 		assert(r == 0);
3429 
3430 		r = scf_transaction_commit(tx);
3431 		if (r == 1)
3432 			break;
3433 
3434 		if (r != 0) {
3435 			switch (scf_error()) {
3436 			case SCF_ERROR_CONNECTION_BROKEN:
3437 			case SCF_ERROR_PERMISSION_DENIED:
3438 			case SCF_ERROR_BACKEND_ACCESS:
3439 			case SCF_ERROR_BACKEND_READONLY:
3440 				scferr();
3441 				goto bail;
3442 
3443 			case SCF_ERROR_DELETED:
3444 				scf_transaction_reset(tx);
3445 				goto add_pg;
3446 
3447 			case SCF_ERROR_INVALID_ARGUMENT:
3448 			case SCF_ERROR_NOT_BOUND:
3449 			case SCF_ERROR_NOT_SET:
3450 			default:
3451 				bad_error("scf_transaction_commit",
3452 				    scf_error());
3453 			}
3454 		}
3455 
3456 		scf_transaction_reset(tx);
3457 		(void) scf_pg_update(pg);
3458 	}
3459 
3460 bail:
3461 	scf_transaction_destroy(tx);
3462 	scf_entry_destroy(ent);
3463 	scf_value_destroy(val);
3464 	scf_pg_destroy(pg);
3465 	scf_instance_destroy(inst);
3466 
3467 	(void) scf_handle_unbind(h);
3468 	scf_handle_destroy(h);
3469 }
3470 
3471 /*
3472  * Function to handle requests from users to main init running as process 1.
3473  */
3474 static void
3475 userinit(int argc, char **argv)
3476 {
3477 	FILE	*fp;
3478 	char	*ln;
3479 	int	init_signal;
3480 	struct stat	sconbuf, conbuf;
3481 	const char *usage_msg = "Usage: init [0123456SsQqabc]\n";
3482 
3483 	/*
3484 	 * We are a user invoked init.  Is there an argument and is it
3485 	 * a single character?  If not, print usage message and quit.
3486 	 */
3487 	if (argc != 2 || argv[1][1] != '\0') {
3488 		(void) fprintf(stderr, usage_msg);
3489 		exit(0);
3490 	}
3491 
3492 	if ((init_signal = lvlname_to_state((char)argv[1][0])) == -1) {
3493 		(void) fprintf(stderr, usage_msg);
3494 		(void) audit_put_record(ADT_FAILURE, ADT_FAIL_VALUE_BAD_CMD,
3495 		    argv[1]);
3496 		exit(1);
3497 	}
3498 
3499 	if (init_signal == SINGLE_USER) {
3500 		/*
3501 		 * Make sure this process is talking to a legal tty line
3502 		 * and that /dev/syscon is linked to this line.
3503 		 */
3504 		ln = ttyname(0);	/* Get the name of tty */
3505 		if (ln == NULL) {
3506 			(void) fprintf(stderr,
3507 			    "Standard input not a tty line\n");
3508 			(void) audit_put_record(ADT_FAILURE,
3509 			    ADT_FAIL_VALUE_BAD_TTY, argv[1]);
3510 			exit(1);
3511 		}
3512 		if (stat(ln, &sconbuf) != -1 &&
3513 		    stat(SYSCON, &conbuf) != -1 &&
3514 		    sconbuf.st_rdev != conbuf.st_rdev &&
3515 		    sconbuf.st_ino != conbuf.st_ino) {
3516 			/*
3517 			 * Unlink /dev/syscon and relink it to the current line.
3518 			 */
3519 			if (unlink(SYSCON) == FAILURE) {
3520 				perror("Can't unlink /dev/syscon");
3521 				(void) fprintf(stderr,
3522 				    "Run command on the system console.\n");
3523 				(void) audit_put_record(ADT_FAILURE,
3524 				    ADT_FAIL_VALUE_PROGRAM, argv[1]);
3525 				exit(1);
3526 			}
3527 			if (link(ln, SYSCON) == FAILURE) {
3528 				(void) fprintf(stderr,
3529 				    "Can't link /dev/syscon to %s: %s", ln,
3530 				    strerror(errno));
3531 
3532 				/* Try to leave a syscon */
3533 				(void) link(SYSTTY, SYSCON);
3534 				(void) audit_put_record(ADT_FAILURE,
3535 				    ADT_FAIL_VALUE_PROGRAM, argv[1]);
3536 				exit(1);
3537 			}
3538 
3539 			/*
3540 			 * Try to leave a message on system console saying where
3541 			 * /dev/syscon is currently connected.
3542 			 */
3543 			if ((fp = fopen(SYSTTY, "r+")) != NULL) {
3544 				(void) fprintf(fp,
3545 				    "\n****	SYSCON CHANGED TO %s	****\n",
3546 				    ln);
3547 				(void) fclose(fp);
3548 			}
3549 		}
3550 	}
3551 
3552 	update_boot_archive(init_signal);
3553 
3554 	(void) audit_put_record(ADT_SUCCESS, ADT_SUCCESS, argv[1]);
3555 
3556 	/*
3557 	 * Signal init; init will take care of telling svc.startd.
3558 	 */
3559 	if (kill(init_pid, init_signal) == FAILURE) {
3560 		(void) fprintf(stderr, "Must be super-user\n");
3561 		(void) audit_put_record(ADT_FAILURE,
3562 		    ADT_FAIL_VALUE_AUTH, argv[1]);
3563 		exit(1);
3564 	}
3565 
3566 	exit(0);
3567 }
3568 
3569 
3570 #define	DELTA	25	/* Number of pidlist elements to allocate at a time */
3571 
3572 /* ARGSUSED */
3573 void
3574 sigpoll(int n)
3575 {
3576 	struct pidrec prec;
3577 	struct pidrec *p = &prec;
3578 	struct pidlist *plp;
3579 	struct pidlist *tp, *savetp;
3580 	int i;
3581 
3582 	if (Pfd < 0) {
3583 		return;
3584 	}
3585 	(void) sigset(SIGCLD, SIG_DFL);
3586 	for (;;) {
3587 		/*
3588 		 * Important Note: Either read will really fail (in which case
3589 		 * return is all we can do) or will get EAGAIN (Pfd was opened
3590 		 * O_NDELAY), in which case we also want to return.
3591 		 * Always return from here!
3592 		 */
3593 		if (read(Pfd, p, sizeof (struct pidrec)) !=
3594 						sizeof (struct pidrec)) {
3595 			(void) sigset(SIGCLD, childeath);
3596 			return;
3597 		}
3598 		switch (p->pd_type) {
3599 
3600 		case ADDPID:
3601 			/*
3602 			 * New "godchild", add to list.
3603 			 */
3604 			if (Plfree == NULL) {
3605 				plp = (struct pidlist *)calloc(DELTA,
3606 				    sizeof (struct pidlist));
3607 				if (plp == NULL) {
3608 					/* Can't save pid */
3609 					break;
3610 				}
3611 				/*
3612 				 * Point at 2nd record allocated, we'll use plp.
3613 				 */
3614 				tp = plp + 1;
3615 				/*
3616 				 * Link them into a chain.
3617 				 */
3618 				Plfree = tp;
3619 				for (i = 0; i < DELTA - 2; i++) {
3620 					tp->pl_next = tp + 1;
3621 					tp++;
3622 				}
3623 			} else {
3624 				plp = Plfree;
3625 				Plfree = plp->pl_next;
3626 			}
3627 			plp->pl_pid = p->pd_pid;
3628 			plp->pl_dflag = 0;
3629 			plp->pl_next = NULL;
3630 			/*
3631 			 * Note - pid list is kept in increasing order of pids.
3632 			 */
3633 			if (Plhead == NULL) {
3634 				Plhead = plp;
3635 				/* Back up to read next record */
3636 				break;
3637 			} else {
3638 				savetp = tp = Plhead;
3639 				while (tp) {
3640 					if (plp->pl_pid > tp->pl_pid) {
3641 						savetp = tp;
3642 						tp = tp->pl_next;
3643 						continue;
3644 					} else if (plp->pl_pid < tp->pl_pid) {
3645 						if (tp == Plhead) {
3646 							plp->pl_next = Plhead;
3647 							Plhead = plp;
3648 						} else {
3649 							plp->pl_next =
3650 							    savetp->pl_next;
3651 							savetp->pl_next = plp;
3652 						}
3653 						break;
3654 					} else {
3655 						/* Already in list! */
3656 						plp->pl_next = Plfree;
3657 						Plfree = plp;
3658 						break;
3659 					}
3660 				}
3661 				if (tp == NULL) {
3662 					/* Add to end of list */
3663 					savetp->pl_next = plp;
3664 				}
3665 			}
3666 			/* Back up to read next record. */
3667 			break;
3668 
3669 		case REMPID:
3670 			/*
3671 			 * This one was handled by someone else,
3672 			 * purge it from the list.
3673 			 */
3674 			if (Plhead == NULL) {
3675 				/* Back up to read next record. */
3676 				break;
3677 			}
3678 			savetp = tp = Plhead;
3679 			while (tp) {
3680 				if (p->pd_pid > tp->pl_pid) {
3681 					/* Keep on looking. */
3682 					savetp = tp;
3683 					tp = tp->pl_next;
3684 					continue;
3685 				} else if (p->pd_pid < tp->pl_pid) {
3686 					/* Not in list. */
3687 					break;
3688 				} else {
3689 					/* Found it. */
3690 					if (tp == Plhead)
3691 						Plhead = tp->pl_next;
3692 					else
3693 						savetp->pl_next = tp->pl_next;
3694 					tp->pl_next = Plfree;
3695 					Plfree = tp;
3696 					break;
3697 				}
3698 			}
3699 			/* Back up to read next record. */
3700 			break;
3701 		default:
3702 			console(B_TRUE, "Bad message on initpipe\n");
3703 			break;
3704 		}
3705 	}
3706 }
3707 
3708 
3709 static void
3710 cleanaux()
3711 {
3712 	struct pidlist *savep, *p;
3713 	pid_t	pid;
3714 	short	status;
3715 
3716 	(void) sigset(SIGCLD, SIG_DFL);
3717 	Gchild = 0;	/* Note - Safe to do this here since no SIGCLDs */
3718 	(void) sighold(SIGPOLL);
3719 	savep = p = Plhead;
3720 	while (p) {
3721 		if (p->pl_dflag) {
3722 			/*
3723 			 * Found an entry to delete,
3724 			 * remove it from list first.
3725 			 */
3726 			pid = p->pl_pid;
3727 			status = p->pl_exit;
3728 			if (p == Plhead) {
3729 				Plhead = p->pl_next;
3730 				p->pl_next = Plfree;
3731 				Plfree = p;
3732 				savep = p = Plhead;
3733 			} else {
3734 				savep->pl_next = p->pl_next;
3735 				p->pl_next = Plfree;
3736 				Plfree = p;
3737 				p = savep->pl_next;
3738 			}
3739 			clearent(pid, status);
3740 			continue;
3741 		}
3742 		savep = p;
3743 		p = p->pl_next;
3744 	}
3745 	(void) sigrelse(SIGPOLL);
3746 	(void) sigset(SIGCLD, childeath);
3747 }
3748 
3749 
3750 /*
3751  * /etc/inittab has more entries and we have run out of room in the proc_table
3752  * array. Double the size of proc_table to accomodate the extra entries.
3753  */
3754 static void
3755 increase_proc_table_size()
3756 {
3757 	sigset_t block, unblock;
3758 	void *ptr;
3759 	size_t delta = num_proc * sizeof (struct PROC_TABLE);
3760 
3761 
3762 	/*
3763 	 * Block signals for realloc.
3764 	 */
3765 	(void) sigfillset(&block);
3766 	(void) sigprocmask(SIG_BLOCK, &block, &unblock);
3767 
3768 
3769 	/*
3770 	 * On failure we just return because callers of this function check
3771 	 * for failure.
3772 	 */
3773 	do
3774 		ptr = realloc(g_state, g_state_sz + delta);
3775 	while (ptr == NULL && errno == EAGAIN);
3776 
3777 	if (ptr != NULL) {
3778 		/* ensure that the new part is initialized to zero */
3779 		bzero((caddr_t)ptr + g_state_sz, delta);
3780 
3781 		g_state = ptr;
3782 		g_state_sz += delta;
3783 		num_proc <<= 1;
3784 	}
3785 
3786 
3787 	/* unblock our signals before returning */
3788 	(void) sigprocmask(SIG_SETMASK, &unblock, NULL);
3789 }
3790 
3791 
3792 
3793 /*
3794  * Sanity check g_state.
3795  */
3796 static int
3797 st_sane()
3798 {
3799 	int i;
3800 	struct PROC_TABLE *ptp;
3801 
3802 
3803 	/* Note: cur_state is encoded as a signal number */
3804 	if (cur_state < 1 || cur_state == 9 || cur_state > 13)
3805 		return (0);
3806 
3807 	/* Check num_proc */
3808 	if (g_state_sz != sizeof (struct init_state) + (num_proc - 1) *
3809 	    sizeof (struct PROC_TABLE))
3810 		return (0);
3811 
3812 	/* Check proc_table */
3813 	for (i = 0, ptp = proc_table; i < num_proc; ++i, ++ptp) {
3814 		/* skip unoccupied entries */
3815 		if (!(ptp->p_flags & OCCUPIED))
3816 			continue;
3817 
3818 		/* p_flags has no bits outside of PF_MASK */
3819 		if (ptp->p_flags & ~(PF_MASK))
3820 			return (0);
3821 
3822 		/* 5 <= pid <= MAXPID */
3823 		if (ptp->p_pid < 5 || ptp->p_pid > MAXPID)
3824 			return (0);
3825 
3826 		/* p_count >= 0 */
3827 		if (ptp->p_count < 0)
3828 			return (0);
3829 
3830 		/* p_time >= 0 */
3831 		if (ptp->p_time < 0)
3832 			return (0);
3833 	}
3834 
3835 	return (1);
3836 }
3837 
3838 /*
3839  * Initialize our state.
3840  *
3841  * If the system just booted, then init_state_file, which is located on an
3842  * everpresent tmpfs filesystem, should not exist.
3843  *
3844  * If we were restarted, then init_state_file should exist, in
3845  * which case we'll read it in, sanity check it, and use it.
3846  *
3847  * Note: You can't call console() until proc_table is ready.
3848  */
3849 void
3850 st_init()
3851 {
3852 	struct stat stb;
3853 	int ret, st_fd, insane = 0;
3854 	size_t to_be_read;
3855 	char *ptr;
3856 
3857 
3858 	booting = 1;
3859 
3860 	do {
3861 		/*
3862 		 * If we can exclusively create the file, then we're the
3863 		 * initial invocation of init(1M).
3864 		 */
3865 		st_fd = open(init_state_file, O_RDWR | O_CREAT | O_EXCL,
3866 		    S_IRUSR | S_IWUSR);
3867 	} while (st_fd == -1 && errno == EINTR);
3868 	if (st_fd != -1)
3869 		goto new_state;
3870 
3871 	booting = 0;
3872 
3873 	do {
3874 		st_fd = open(init_state_file, O_RDWR, S_IRUSR | S_IWUSR);
3875 	} while (st_fd == -1 && errno == EINTR);
3876 	if (st_fd == -1)
3877 		goto new_state;
3878 
3879 	/* Get the size of the file. */
3880 	do
3881 		ret = fstat(st_fd, &stb);
3882 	while (ret == -1 && errno == EINTR);
3883 	if (ret == -1)
3884 		goto new_state;
3885 
3886 	do
3887 		g_state = malloc(stb.st_size);
3888 	while (g_state == NULL && errno == EAGAIN);
3889 	if (g_state == NULL)
3890 		goto new_state;
3891 
3892 	to_be_read = stb.st_size;
3893 	ptr = (char *)g_state;
3894 	while (to_be_read > 0) {
3895 		ssize_t read_ret;
3896 
3897 		read_ret = read(st_fd, ptr, to_be_read);
3898 		if (read_ret < 0) {
3899 			if (errno == EINTR)
3900 				continue;
3901 
3902 			goto new_state;
3903 		}
3904 
3905 		to_be_read -= read_ret;
3906 		ptr += read_ret;
3907 	}
3908 
3909 	(void) close(st_fd);
3910 
3911 	g_state_sz = stb.st_size;
3912 
3913 	if (st_sane()) {
3914 		console(B_TRUE, "Restarting.\n");
3915 		return;
3916 	}
3917 
3918 	insane = 1;
3919 
3920 new_state:
3921 	if (st_fd >= 0)
3922 		(void) close(st_fd);
3923 	else
3924 		(void) unlink(init_state_file);
3925 
3926 	if (g_state != NULL)
3927 		free(g_state);
3928 
3929 	/* Something went wrong, so allocate new state. */
3930 	g_state_sz = sizeof (struct init_state) +
3931 	    ((init_num_proc - 1) * sizeof (struct PROC_TABLE));
3932 	do
3933 		g_state = calloc(1, g_state_sz);
3934 	while (g_state == NULL && errno == EAGAIN);
3935 	if (g_state == NULL) {
3936 		/* Fatal error! */
3937 		exit(errno);
3938 	}
3939 
3940 	g_state->ist_runlevel = -1;
3941 	num_proc = init_num_proc;
3942 
3943 	if (!booting) {
3944 		console(B_TRUE, "Restarting.\n");
3945 
3946 		/* Overwrite the bad state file. */
3947 		st_write();
3948 
3949 		if (!insane) {
3950 			console(B_TRUE,
3951 			    "Error accessing persistent state file `%s'.  "
3952 			    "Ignored.\n", init_state_file);
3953 		} else {
3954 			console(B_TRUE,
3955 			    "Persistent state file `%s' is invalid and was "
3956 			    "ignored.\n", init_state_file);
3957 		}
3958 	}
3959 }
3960 
3961 /*
3962  * Write g_state out to the state file.
3963  */
3964 void
3965 st_write()
3966 {
3967 	static int complained = 0;
3968 
3969 	int st_fd;
3970 	char *cp;
3971 	size_t sz;
3972 	ssize_t ret;
3973 
3974 
3975 	do {
3976 		st_fd = open(init_next_state_file,
3977 		    O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
3978 	} while (st_fd < 0 && errno == EINTR);
3979 	if (st_fd < 0)
3980 		goto err;
3981 
3982 	cp = (char *)g_state;
3983 	sz = g_state_sz;
3984 	while (sz > 0) {
3985 		ret = write(st_fd, cp, sz);
3986 		if (ret < 0) {
3987 			if (errno == EINTR)
3988 				continue;
3989 
3990 			goto err;
3991 		}
3992 
3993 		sz -= ret;
3994 		cp += ret;
3995 	}
3996 
3997 	(void) close(st_fd);
3998 	st_fd = -1;
3999 	if (rename(init_next_state_file, init_state_file)) {
4000 		(void) unlink(init_next_state_file);
4001 		goto err;
4002 	}
4003 	complained = 0;
4004 
4005 	return;
4006 
4007 err:
4008 	if (st_fd >= 0)
4009 		(void) close(st_fd);
4010 
4011 	if (!booting && !complained) {
4012 		/*
4013 		 * Only complain after the filesystem should have come up.
4014 		 * And only do it once so we don't loop between console()
4015 		 * & efork().
4016 		 */
4017 		complained = 1;
4018 		if (st_fd)
4019 			console(B_TRUE, "Couldn't write persistent state "
4020 			    "file `%s'.\n", init_state_file);
4021 		else
4022 			console(B_TRUE, "Couldn't move persistent state "
4023 			    "file `%s' to `%s'.\n", init_next_state_file,
4024 			    init_state_file);
4025 	}
4026 }
4027 
4028 /*
4029  * Create a contract with these parameters.
4030  */
4031 static int
4032 contract_make_template(uint_t info, uint_t critical, uint_t fatal,
4033     uint64_t cookie)
4034 {
4035 	int fd, err;
4036 
4037 	char *ioctl_tset_emsg =
4038 	    "Couldn't set \"%s\" contract template parameter: %s.\n";
4039 
4040 	do
4041 		fd = open64(CTFS_ROOT "/process/template", O_RDWR);
4042 	while (fd < 0 && errno == EINTR);
4043 	if (fd < 0) {
4044 		console(B_TRUE, "Couldn't create process template: %s.\n",
4045 		    strerror(errno));
4046 		return (-1);
4047 	}
4048 
4049 	if (err = ct_pr_tmpl_set_param(fd, CT_PR_INHERIT | CT_PR_REGENT))
4050 		console(B_TRUE, "Contract set template inherit, regent "
4051 		    "failed.\n");
4052 
4053 	/*
4054 	 * These errors result in a misconfigured template, which is better
4055 	 * than no template at all, so warn but don't abort.
4056 	 */
4057 	if (err = ct_tmpl_set_informative(fd, info))
4058 		console(B_TRUE, ioctl_tset_emsg, "informative", strerror(err));
4059 
4060 	if (err = ct_tmpl_set_critical(fd, critical))
4061 		console(B_TRUE, ioctl_tset_emsg, "critical", strerror(err));
4062 
4063 	if (err = ct_pr_tmpl_set_fatal(fd, fatal))
4064 		console(B_TRUE, ioctl_tset_emsg, "fatal", strerror(err));
4065 
4066 	if (err = ct_tmpl_set_cookie(fd, cookie))
4067 		console(B_TRUE, ioctl_tset_emsg, "cookie", strerror(err));
4068 
4069 	(void) fcntl(fd, F_SETFD, FD_CLOEXEC);
4070 
4071 	return (fd);
4072 }
4073 
4074 /*
4075  * Create the templates and open an event file descriptor.  We use dup2(2) to
4076  * get these descriptors away from the stdin/stdout/stderr group.
4077  */
4078 static void
4079 contracts_init()
4080 {
4081 	int err, fd;
4082 
4083 	/*
4084 	 * Create & configure a legacy template.  We only want empty events so
4085 	 * we know when to abandon them.
4086 	 */
4087 	legacy_tmpl = contract_make_template(0, CT_PR_EV_EMPTY, CT_PR_EV_HWERR,
4088 	    ORDINARY_COOKIE);
4089 	if (legacy_tmpl >= 0) {
4090 		err = ct_tmpl_activate(legacy_tmpl);
4091 		if (err != 0) {
4092 			(void) close(legacy_tmpl);
4093 			legacy_tmpl = -1;
4094 			console(B_TRUE,
4095 			    "Couldn't activate legacy template (%s); "
4096 			    "legacy services will be in init's contract.\n",
4097 			    strerror(err));
4098 		}
4099 	} else
4100 		console(B_TRUE,
4101 		    "Legacy services will be in init's contract.\n");
4102 
4103 	if (dup2(legacy_tmpl, 255) == -1) {
4104 		console(B_TRUE, "Could not duplicate legacy template: %s.\n",
4105 		    strerror(errno));
4106 	} else {
4107 		(void) close(legacy_tmpl);
4108 		legacy_tmpl = 255;
4109 	}
4110 
4111 	(void) fcntl(legacy_tmpl, F_SETFD, FD_CLOEXEC);
4112 
4113 	startd_tmpl = contract_make_template(0, CT_PR_EV_EMPTY,
4114 	    CT_PR_EV_HWERR | CT_PR_EV_SIGNAL | CT_PR_EV_CORE, STARTD_COOKIE);
4115 
4116 	if (dup2(startd_tmpl, 254) == -1) {
4117 		console(B_TRUE, "Could not duplicate startd template: %s.\n",
4118 		    strerror(errno));
4119 	} else {
4120 		(void) close(startd_tmpl);
4121