xref: /titanic_52/usr/src/cmd/zoneadmd/zoneadmd.c (revision f4b3ec61df05330d25f55a36b975b4d7519fdeb1)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * zoneadmd manages zones; one zoneadmd process is launched for each
31  * non-global zone on the system.  This daemon juggles four jobs:
32  *
33  * - Implement setup and teardown of the zone "virtual platform": mount and
34  *   unmount filesystems; create and destroy network interfaces; communicate
35  *   with devfsadmd to lay out devices for the zone; instantiate the zone
36  *   console device; configure process runtime attributes such as resource
37  *   controls, pool bindings, fine-grained privileges.
38  *
39  * - Launch the zone's init(1M) process.
40  *
41  * - Implement a door server; clients (like zoneadm) connect to the door
42  *   server and request zone state changes.  The kernel is also a client of
43  *   this door server.  A request to halt or reboot the zone which originates
44  *   *inside* the zone results in a door upcall from the kernel into zoneadmd.
45  *
46  *   One minor problem is that messages emitted by zoneadmd need to be passed
47  *   back to the zoneadm process making the request.  These messages need to
48  *   be rendered in the client's locale; so, this is passed in as part of the
49  *   request.  The exception is the kernel upcall to zoneadmd, in which case
50  *   messages are syslog'd.
51  *
52  *   To make all of this work, the Makefile adds -a to xgettext to extract *all*
53  *   strings, and an exclusion file (zoneadmd.xcl) is used to exclude those
54  *   strings which do not need to be translated.
55  *
56  * - Act as a console server for zlogin -C processes; see comments in zcons.c
57  *   for more information about the zone console architecture.
58  *
59  * DESIGN NOTES
60  *
61  * Restart:
62  *   A chief design constraint of zoneadmd is that it should be restartable in
63  *   the case that the administrator kills it off, or it suffers a fatal error,
64  *   without the running zone being impacted; this is akin to being able to
65  *   reboot the service processor of a server without affecting the OS instance.
66  */
67 
68 #include <sys/param.h>
69 #include <sys/mman.h>
70 #include <sys/types.h>
71 #include <sys/stat.h>
72 #include <sys/sysmacros.h>
73 
74 #include <bsm/adt.h>
75 #include <bsm/adt_event.h>
76 
77 #include <alloca.h>
78 #include <assert.h>
79 #include <errno.h>
80 #include <door.h>
81 #include <fcntl.h>
82 #include <locale.h>
83 #include <signal.h>
84 #include <stdarg.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <strings.h>
89 #include <synch.h>
90 #include <syslog.h>
91 #include <thread.h>
92 #include <unistd.h>
93 #include <wait.h>
94 #include <limits.h>
95 #include <zone.h>
96 #include <libbrand.h>
97 #include <libcontract.h>
98 #include <libcontract_priv.h>
99 #include <sys/contract/process.h>
100 #include <sys/ctfs.h>
101 
102 #include <libzonecfg.h>
103 #include "zoneadmd.h"
104 
105 static char *progname;
106 char *zone_name;	/* zone which we are managing */
107 char brand_name[MAXNAMELEN];
108 boolean_t zone_isnative;
109 static zoneid_t zone_id;
110 
111 zlog_t logsys;
112 
113 mutex_t	lock = DEFAULTMUTEX;	/* to serialize stuff */
114 mutex_t	msglock = DEFAULTMUTEX;	/* for calling setlocale() */
115 
116 static sema_t scratch_sem;	/* for scratch zones */
117 
118 static char	zone_door_path[MAXPATHLEN];
119 static int	zone_door = -1;
120 
121 boolean_t in_death_throes = B_FALSE;	/* daemon is dying */
122 boolean_t bringup_failure_recovery = B_FALSE; /* ignore certain failures */
123 
124 #if !defined(TEXT_DOMAIN)		/* should be defined by cc -D */
125 #define	TEXT_DOMAIN	"SYS_TEST"	/* Use this only if it wasn't */
126 #endif
127 
128 #define	DEFAULT_LOCALE	"C"
129 
130 static const char *
131 z_cmd_name(zone_cmd_t zcmd)
132 {
133 	/* This list needs to match the enum in sys/zone.h */
134 	static const char *zcmdstr[] = {
135 		"ready", "boot", "forceboot", "reboot", "halt",
136 		"note_uninstalling", "mount", "forcemount", "unmount"
137 	};
138 
139 	if (zcmd >= sizeof (zcmdstr) / sizeof (*zcmdstr))
140 		return ("unknown");
141 	else
142 		return (zcmdstr[(int)zcmd]);
143 }
144 
145 static char *
146 get_execbasename(char *execfullname)
147 {
148 	char *last_slash, *execbasename;
149 
150 	/* guard against '/' at end of command invocation */
151 	for (;;) {
152 		last_slash = strrchr(execfullname, '/');
153 		if (last_slash == NULL) {
154 			execbasename = execfullname;
155 			break;
156 		} else {
157 			execbasename = last_slash + 1;
158 			if (*execbasename == '\0') {
159 				*last_slash = '\0';
160 				continue;
161 			}
162 			break;
163 		}
164 	}
165 	return (execbasename);
166 }
167 
168 static void
169 usage(void)
170 {
171 	(void) fprintf(stderr, gettext("Usage: %s -z zonename\n"), progname);
172 	(void) fprintf(stderr,
173 	    gettext("\tNote: %s should not be run directly.\n"), progname);
174 	exit(2);
175 }
176 
177 /* ARGSUSED */
178 static void
179 sigchld(int sig)
180 {
181 }
182 
183 char *
184 localize_msg(char *locale, const char *msg)
185 {
186 	char *out;
187 
188 	(void) mutex_lock(&msglock);
189 	(void) setlocale(LC_MESSAGES, locale);
190 	out = gettext(msg);
191 	(void) setlocale(LC_MESSAGES, DEFAULT_LOCALE);
192 	(void) mutex_unlock(&msglock);
193 	return (out);
194 }
195 
196 /* PRINTFLIKE3 */
197 void
198 zerror(zlog_t *zlogp, boolean_t use_strerror, const char *fmt, ...)
199 {
200 	va_list alist;
201 	char buf[MAXPATHLEN * 2]; /* enough space for err msg with a path */
202 	char *bp;
203 	int saved_errno = errno;
204 
205 	if (zlogp == NULL)
206 		return;
207 	if (zlogp == &logsys)
208 		(void) snprintf(buf, sizeof (buf), "[zone '%s'] ",
209 		    zone_name);
210 	else
211 		buf[0] = '\0';
212 	bp = &(buf[strlen(buf)]);
213 
214 	/*
215 	 * In theory, the locale pointer should be set to either "C" or a
216 	 * char array, so it should never be NULL
217 	 */
218 	assert(zlogp->locale != NULL);
219 	/* Locale is per process, but we are multi-threaded... */
220 	fmt = localize_msg(zlogp->locale, fmt);
221 
222 	va_start(alist, fmt);
223 	(void) vsnprintf(bp, sizeof (buf) - (bp - buf), fmt, alist);
224 	va_end(alist);
225 	bp = &(buf[strlen(buf)]);
226 	if (use_strerror)
227 		(void) snprintf(bp, sizeof (buf) - (bp - buf), ": %s",
228 		    strerror(saved_errno));
229 	if (zlogp == &logsys) {
230 		(void) syslog(LOG_ERR, "%s", buf);
231 	} else if (zlogp->logfile != NULL) {
232 		(void) fprintf(zlogp->logfile, "%s\n", buf);
233 	} else {
234 		size_t buflen;
235 		size_t copylen;
236 
237 		buflen = snprintf(zlogp->log, zlogp->loglen, "%s\n", buf);
238 		copylen = MIN(buflen, zlogp->loglen);
239 		zlogp->log += copylen;
240 		zlogp->loglen -= copylen;
241 	}
242 }
243 
244 /*
245  * Emit a warning for any boot arguments which are unrecognized.  Since
246  * Solaris boot arguments are getopt(3c) compatible (see kernel(1m)), we
247  * put the arguments into an argv style array, use getopt to process them,
248  * and put the resultant argument string back into outargs.
249  *
250  * During the filtering, we pull out any arguments which are truly "boot"
251  * arguments, leaving only those which are to be passed intact to the
252  * progenitor process.  The one we support at the moment is -i, which
253  * indicates to the kernel which program should be launched as 'init'.
254  *
255  * A return of Z_INVAL indicates specifically that the arguments are
256  * not valid; this is a non-fatal error.  Except for Z_OK, all other return
257  * values are treated as fatal.
258  */
259 static int
260 filter_bootargs(zlog_t *zlogp, const char *inargs, char *outargs,
261     char *init_file, char *badarg)
262 {
263 	int argc = 0, argc_save;
264 	int i;
265 	int err;
266 	char *arg, *lasts, **argv = NULL, **argv_save;
267 	char zonecfg_args[BOOTARGS_MAX];
268 	char scratchargs[BOOTARGS_MAX], *sargs;
269 	char c;
270 
271 	bzero(outargs, BOOTARGS_MAX);
272 	bzero(badarg, BOOTARGS_MAX);
273 
274 	/*
275 	 * If the user didn't specify transient boot arguments, check
276 	 * to see if there were any specified in the zone configuration,
277 	 * and use them if applicable.
278 	 */
279 	if (inargs == NULL || inargs[0] == '\0')  {
280 		zone_dochandle_t handle;
281 		if ((handle = zonecfg_init_handle()) == NULL) {
282 			zerror(zlogp, B_TRUE,
283 			    "getting zone configuration handle");
284 			return (Z_BAD_HANDLE);
285 		}
286 		err = zonecfg_get_snapshot_handle(zone_name, handle);
287 		if (err != Z_OK) {
288 			zerror(zlogp, B_FALSE,
289 			    "invalid configuration snapshot");
290 			zonecfg_fini_handle(handle);
291 			return (Z_BAD_HANDLE);
292 		}
293 
294 		bzero(zonecfg_args, sizeof (zonecfg_args));
295 		(void) zonecfg_get_bootargs(handle, zonecfg_args,
296 		    sizeof (zonecfg_args));
297 		inargs = zonecfg_args;
298 		zonecfg_fini_handle(handle);
299 	}
300 
301 	if (strlen(inargs) >= BOOTARGS_MAX) {
302 		zerror(zlogp, B_FALSE, "boot argument string too long");
303 		return (Z_INVAL);
304 	}
305 
306 	(void) strlcpy(scratchargs, inargs, sizeof (scratchargs));
307 	sargs = scratchargs;
308 	while ((arg = strtok_r(sargs, " \t", &lasts)) != NULL) {
309 		sargs = NULL;
310 		argc++;
311 	}
312 
313 	if ((argv = calloc(argc + 1, sizeof (char *))) == NULL) {
314 		zerror(zlogp, B_FALSE, "memory allocation failed");
315 		return (Z_NOMEM);
316 	}
317 
318 	argv_save = argv;
319 	argc_save = argc;
320 
321 	(void) strlcpy(scratchargs, inargs, sizeof (scratchargs));
322 	sargs = scratchargs;
323 	i = 0;
324 	while ((arg = strtok_r(sargs, " \t", &lasts)) != NULL) {
325 		sargs = NULL;
326 		if ((argv[i] = strdup(arg)) == NULL) {
327 			err = Z_NOMEM;
328 			zerror(zlogp, B_FALSE, "memory allocation failed");
329 			goto done;
330 		}
331 		i++;
332 	}
333 
334 	/*
335 	 * We preserve compatibility with the Solaris system boot behavior,
336 	 * which allows:
337 	 *
338 	 * 	# reboot kernel/unix -s -m verbose
339 	 *
340 	 * In this example, kernel/unix tells the booter what file to
341 	 * boot.  We don't want reboot in a zone to be gratuitously different,
342 	 * so we silently ignore the boot file, if necessary.
343 	 */
344 	if (argv[0] == NULL)
345 		goto done;
346 
347 	assert(argv[0][0] != ' ');
348 	assert(argv[0][0] != '\t');
349 
350 	if (argv[0][0] != '-' && argv[0][0] != '\0') {
351 		argv = &argv[1];
352 		argc--;
353 	}
354 
355 	optind = 0;
356 	opterr = 0;
357 	err = Z_OK;
358 	while ((c = getopt(argc, argv, "fi:m:s")) != -1) {
359 		switch (c) {
360 		case 'i':
361 			/*
362 			 * -i is handled by the runtime and is not passed
363 			 * along to userland
364 			 */
365 			(void) strlcpy(init_file, optarg, MAXPATHLEN);
366 			break;
367 		case 'f':
368 			/* This has already been processed by zoneadm */
369 			break;
370 		case 'm':
371 		case 's':
372 			/* These pass through unmolested */
373 			(void) snprintf(outargs, BOOTARGS_MAX,
374 			    "%s -%c %s ", outargs, c, optarg ? optarg : "");
375 			break;
376 		case '?':
377 			/*
378 			 * We warn about unknown arguments but pass them
379 			 * along anyway-- if someone wants to develop their
380 			 * own init replacement, they can pass it whatever
381 			 * args they want.
382 			 */
383 			err = Z_INVAL;
384 			(void) snprintf(outargs, BOOTARGS_MAX,
385 			    "%s -%c", outargs, optopt);
386 			(void) snprintf(badarg, BOOTARGS_MAX,
387 			    "%s -%c", badarg, optopt);
388 			break;
389 		}
390 	}
391 
392 	/*
393 	 * For Solaris Zones we warn about and discard non-option arguments.
394 	 * Hence 'boot foo bar baz gub' --> 'boot'.  However, to be similar
395 	 * to the kernel, we concat up all the other remaining boot args.
396 	 * and warn on them as a group.
397 	 */
398 	if (optind < argc) {
399 		err = Z_INVAL;
400 		while (optind < argc) {
401 			(void) snprintf(badarg, BOOTARGS_MAX, "%s%s%s",
402 			    badarg, strlen(badarg) > 0 ? " " : "",
403 			    argv[optind]);
404 			optind++;
405 		}
406 		zerror(zlogp, B_FALSE, "WARNING: Unused or invalid boot "
407 		    "arguments `%s'.", badarg);
408 	}
409 
410 done:
411 	for (i = 0; i < argc_save; i++) {
412 		if (argv_save[i] != NULL)
413 			free(argv_save[i]);
414 	}
415 	free(argv_save);
416 	return (err);
417 }
418 
419 
420 static int
421 mkzonedir(zlog_t *zlogp)
422 {
423 	struct stat st;
424 	/*
425 	 * We must create and lock everyone but root out of ZONES_TMPDIR
426 	 * since anyone can open any UNIX domain socket, regardless of
427 	 * its file system permissions.  Sigh...
428 	 */
429 	if (mkdir(ZONES_TMPDIR, S_IRWXU) < 0 && errno != EEXIST) {
430 		zerror(zlogp, B_TRUE, "could not mkdir '%s'", ZONES_TMPDIR);
431 		return (-1);
432 	}
433 	/* paranoia */
434 	if ((stat(ZONES_TMPDIR, &st) < 0) || !S_ISDIR(st.st_mode)) {
435 		zerror(zlogp, B_TRUE, "'%s' is not a directory", ZONES_TMPDIR);
436 		return (-1);
437 	}
438 	(void) chmod(ZONES_TMPDIR, S_IRWXU);
439 	return (0);
440 }
441 
442 /*
443  * Bring a zone up to the pre-boot "ready" stage.  The mount_cmd argument is
444  * 'true' if this is being invoked as part of the processing for the "mount"
445  * subcommand.
446  */
447 static int
448 zone_ready(zlog_t *zlogp, boolean_t mount_cmd)
449 {
450 	int err;
451 
452 	if ((err = zonecfg_create_snapshot(zone_name)) != Z_OK) {
453 		zerror(zlogp, B_FALSE, "unable to create snapshot: %s",
454 		    zonecfg_strerror(err));
455 		return (-1);
456 	}
457 
458 	if ((zone_id = vplat_create(zlogp, mount_cmd)) == -1) {
459 		if ((err = zonecfg_destroy_snapshot(zone_name)) != Z_OK)
460 			zerror(zlogp, B_FALSE, "destroying snapshot: %s",
461 			    zonecfg_strerror(err));
462 		return (-1);
463 	}
464 	if (vplat_bringup(zlogp, mount_cmd, zone_id) != 0) {
465 		bringup_failure_recovery = B_TRUE;
466 		(void) vplat_teardown(NULL, mount_cmd, B_FALSE);
467 		if ((err = zonecfg_destroy_snapshot(zone_name)) != Z_OK)
468 			zerror(zlogp, B_FALSE, "destroying snapshot: %s",
469 			    zonecfg_strerror(err));
470 		return (-1);
471 	}
472 
473 	return (0);
474 }
475 
476 int
477 init_template(void)
478 {
479 	int fd;
480 	int err = 0;
481 
482 	fd = open64(CTFS_ROOT "/process/template", O_RDWR);
483 	if (fd == -1)
484 		return (-1);
485 
486 	/*
487 	 * For now, zoneadmd doesn't do anything with the contract.
488 	 * Deliver no events, don't inherit, and allow it to be orphaned.
489 	 */
490 	err |= ct_tmpl_set_critical(fd, 0);
491 	err |= ct_tmpl_set_informative(fd, 0);
492 	err |= ct_pr_tmpl_set_fatal(fd, CT_PR_EV_HWERR);
493 	err |= ct_pr_tmpl_set_param(fd, CT_PR_PGRPONLY | CT_PR_REGENT);
494 	if (err || ct_tmpl_activate(fd)) {
495 		(void) close(fd);
496 		return (-1);
497 	}
498 
499 	return (fd);
500 }
501 
502 typedef struct fs_callback {
503 	zlog_t		*zlogp;
504 	zoneid_t	zoneid;
505 } fs_callback_t;
506 
507 static int
508 mount_early_fs(void *data, const char *spec, const char *dir,
509     const char *fstype, const char *opt)
510 {
511 	zlog_t *zlogp = ((fs_callback_t *)data)->zlogp;
512 	zoneid_t zoneid = ((fs_callback_t *)data)->zoneid;
513 	pid_t child;
514 	int child_status;
515 	int tmpl_fd;
516 	ctid_t ct;
517 
518 	if ((tmpl_fd = init_template()) == -1) {
519 		zerror(zlogp, B_TRUE, "failed to create contract");
520 		return (-1);
521 	}
522 
523 	if ((child = fork()) == -1) {
524 		(void) ct_tmpl_clear(tmpl_fd);
525 		(void) close(tmpl_fd);
526 		zerror(zlogp, B_TRUE, "failed to fork");
527 		return (-1);
528 
529 	} else if (child == 0) {	/* child */
530 		char opt_buf[MAX_MNTOPT_STR];
531 		int optlen = 0;
532 		int mflag = MS_DATA;
533 
534 		(void) ct_tmpl_clear(tmpl_fd);
535 		/*
536 		 * Even though there are no procs running in the zone, we
537 		 * do this for paranoia's sake.
538 		 */
539 		(void) closefrom(0);
540 
541 		if (zone_enter(zoneid) == -1) {
542 			_exit(errno);
543 		}
544 		if (opt != NULL) {
545 			/*
546 			 * The mount() system call is incredibly annoying.
547 			 * If options are specified, we need to copy them
548 			 * into a temporary buffer since the mount() system
549 			 * call will overwrite the options string.  It will
550 			 * also fail if the new option string it wants to
551 			 * write is bigger than the one we passed in, so
552 			 * you must pass in a buffer of the maximum possible
553 			 * option string length.  sigh.
554 			 */
555 			(void) strlcpy(opt_buf, opt, sizeof (opt_buf));
556 			opt = opt_buf;
557 			optlen = MAX_MNTOPT_STR;
558 			mflag = MS_OPTIONSTR;
559 		}
560 		if (mount(spec, dir, mflag, fstype, NULL, 0, opt, optlen) != 0)
561 			_exit(errno);
562 		_exit(0);
563 	}
564 
565 	/* parent */
566 	if (contract_latest(&ct) == -1)
567 		ct = -1;
568 	(void) ct_tmpl_clear(tmpl_fd);
569 	(void) close(tmpl_fd);
570 	if (waitpid(child, &child_status, 0) != child) {
571 		/* unexpected: we must have been signalled */
572 		(void) contract_abandon_id(ct);
573 		return (-1);
574 	}
575 	(void) contract_abandon_id(ct);
576 	if (WEXITSTATUS(child_status) != 0) {
577 		errno = WEXITSTATUS(child_status);
578 		zerror(zlogp, B_TRUE, "mount of %s failed", dir);
579 		return (-1);
580 	}
581 
582 	return (0);
583 }
584 
585 int
586 do_subproc(zlog_t *zlogp, char *cmdbuf)
587 {
588 	char inbuf[1024];	/* arbitrary large amount */
589 	FILE *file;
590 	int status;
591 
592 	file = popen(cmdbuf, "r");
593 	if (file == NULL) {
594 		zerror(zlogp, B_TRUE, "could not launch: %s", cmdbuf);
595 		return (-1);
596 	}
597 
598 	while (fgets(inbuf, sizeof (inbuf), file) != NULL)
599 		if (zlogp != &logsys)
600 			zerror(zlogp, B_FALSE, "%s", inbuf);
601 	status = pclose(file);
602 
603 	if (WIFSIGNALED(status)) {
604 		zerror(zlogp, B_FALSE, "%s unexpectedly terminated due to "
605 		    "signal %d", cmdbuf, WTERMSIG(status));
606 		return (-1);
607 	}
608 	assert(WIFEXITED(status));
609 	if (WEXITSTATUS(status) == ZEXIT_EXEC) {
610 		zerror(zlogp, B_FALSE, "failed to exec %s", cmdbuf);
611 		return (-1);
612 	}
613 	return (WEXITSTATUS(status));
614 }
615 
616 static int
617 zone_bootup(zlog_t *zlogp, const char *bootargs)
618 {
619 	zoneid_t zoneid;
620 	struct stat st;
621 	char zroot[MAXPATHLEN], initpath[MAXPATHLEN], init_file[MAXPATHLEN];
622 	char nbootargs[BOOTARGS_MAX];
623 	char cmdbuf[MAXPATHLEN];
624 	fs_callback_t cb;
625 	brand_handle_t bh;
626 	int err;
627 
628 	if (init_console_slave(zlogp) != 0)
629 		return (-1);
630 	reset_slave_terminal(zlogp);
631 
632 	if ((zoneid = getzoneidbyname(zone_name)) == -1) {
633 		zerror(zlogp, B_TRUE, "unable to get zoneid");
634 		return (-1);
635 	}
636 
637 	cb.zlogp = zlogp;
638 	cb.zoneid = zoneid;
639 
640 	/* Get a handle to the brand info for this zone */
641 	if ((bh = brand_open(brand_name)) == NULL) {
642 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
643 		return (-1);
644 	}
645 
646 	/*
647 	 * Get the list of filesystems to mount from the brand
648 	 * configuration.  These mounts are done via a thread that will
649 	 * enter the zone, so they are done from within the context of the
650 	 * zone.
651 	 */
652 	if (brand_platform_iter_mounts(bh, mount_early_fs, &cb) != 0) {
653 		zerror(zlogp, B_FALSE, "unable to mount filesystems");
654 		brand_close(bh);
655 		return (-1);
656 	}
657 
658 	/*
659 	 * Get the brand's boot callback if it exists.
660 	 */
661 	if (zone_get_zonepath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
662 		zerror(zlogp, B_FALSE, "unable to determine zone root");
663 		return (-1);
664 	}
665 	(void) strcpy(cmdbuf, EXEC_PREFIX);
666 	if (brand_get_boot(bh, zone_name, zroot, cmdbuf + EXEC_LEN,
667 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL) != 0) {
668 		zerror(zlogp, B_FALSE,
669 		    "unable to determine branded zone's boot callback");
670 		brand_close(bh);
671 		return (-1);
672 	}
673 
674 	/* Get the path for this zone's init(1M) (or equivalent) process.  */
675 	if (brand_get_initname(bh, init_file, MAXPATHLEN) != 0) {
676 		zerror(zlogp, B_FALSE,
677 		    "unable to determine zone's init(1M) location");
678 		brand_close(bh);
679 		return (-1);
680 	}
681 
682 	brand_close(bh);
683 
684 	err = filter_bootargs(zlogp, bootargs, nbootargs, init_file,
685 	    bad_boot_arg);
686 	if (err == Z_INVAL)
687 		eventstream_write(Z_EVT_ZONE_BADARGS);
688 	else if (err != Z_OK)
689 		return (-1);
690 
691 	assert(init_file[0] != '\0');
692 
693 	/* Try to anticipate possible problems: Make sure init is executable. */
694 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
695 		zerror(zlogp, B_FALSE, "unable to determine zone root");
696 		return (-1);
697 	}
698 
699 	(void) snprintf(initpath, sizeof (initpath), "%s%s", zroot, init_file);
700 
701 	if (stat(initpath, &st) == -1) {
702 		zerror(zlogp, B_TRUE, "could not stat %s", initpath);
703 		return (-1);
704 	}
705 
706 	if ((st.st_mode & S_IXUSR) == 0) {
707 		zerror(zlogp, B_FALSE, "%s is not executable", initpath);
708 		return (-1);
709 	}
710 
711 	/*
712 	 * If there is a brand 'boot' callback, execute it now to give the
713 	 * brand one last chance to do any additional setup before the zone
714 	 * is booted.
715 	 */
716 	if ((strlen(cmdbuf) > EXEC_LEN) &&
717 	    (do_subproc(zlogp, cmdbuf) != Z_OK)) {
718 		zerror(zlogp, B_FALSE, "%s failed", cmdbuf);
719 		return (-1);
720 	}
721 
722 	if (zone_setattr(zoneid, ZONE_ATTR_INITNAME, init_file, 0) == -1) {
723 		zerror(zlogp, B_TRUE, "could not set zone boot file");
724 		return (-1);
725 	}
726 
727 	if (zone_setattr(zoneid, ZONE_ATTR_BOOTARGS, nbootargs, 0) == -1) {
728 		zerror(zlogp, B_TRUE, "could not set zone boot arguments");
729 		return (-1);
730 	}
731 
732 	if (zone_boot(zoneid) == -1) {
733 		zerror(zlogp, B_TRUE, "unable to boot zone");
734 		return (-1);
735 	}
736 
737 	return (0);
738 }
739 
740 static int
741 zone_halt(zlog_t *zlogp, boolean_t unmount_cmd, boolean_t rebooting)
742 {
743 	int err;
744 
745 	if (vplat_teardown(zlogp, unmount_cmd, rebooting) != 0) {
746 		if (!bringup_failure_recovery)
747 			zerror(zlogp, B_FALSE, "unable to destroy zone");
748 		return (-1);
749 	}
750 
751 	if ((err = zonecfg_destroy_snapshot(zone_name)) != Z_OK)
752 		zerror(zlogp, B_FALSE, "destroying snapshot: %s",
753 		    zonecfg_strerror(err));
754 
755 	return (0);
756 }
757 
758 /*
759  * Generate AUE_zone_state for a command that boots a zone.
760  */
761 static void
762 audit_put_record(zlog_t *zlogp, ucred_t *uc, int return_val,
763     char *new_state)
764 {
765 	adt_session_data_t	*ah;
766 	adt_event_data_t	*event;
767 	int			pass_fail, fail_reason;
768 
769 	if (!adt_audit_enabled())
770 		return;
771 
772 	if (return_val == 0) {
773 		pass_fail = ADT_SUCCESS;
774 		fail_reason = ADT_SUCCESS;
775 	} else {
776 		pass_fail = ADT_FAILURE;
777 		fail_reason = ADT_FAIL_VALUE_PROGRAM;
778 	}
779 
780 	if (adt_start_session(&ah, NULL, 0)) {
781 		zerror(zlogp, B_TRUE, gettext("audit failure."));
782 		return;
783 	}
784 	if (adt_set_from_ucred(ah, uc, ADT_NEW)) {
785 		zerror(zlogp, B_TRUE, gettext("audit failure."));
786 		(void) adt_end_session(ah);
787 		return;
788 	}
789 
790 	event = adt_alloc_event(ah, ADT_zone_state);
791 	if (event == NULL) {
792 		zerror(zlogp, B_TRUE, gettext("audit failure."));
793 		(void) adt_end_session(ah);
794 		return;
795 	}
796 	event->adt_zone_state.zonename = zone_name;
797 	event->adt_zone_state.new_state = new_state;
798 
799 	if (adt_put_event(event, pass_fail, fail_reason))
800 		zerror(zlogp, B_TRUE, gettext("audit failure."));
801 
802 	adt_free_event(event);
803 
804 	(void) adt_end_session(ah);
805 }
806 
807 /*
808  * The main routine for the door server that deals with zone state transitions.
809  */
810 /* ARGSUSED */
811 static void
812 server(void *cookie, char *args, size_t alen, door_desc_t *dp,
813     uint_t n_desc)
814 {
815 	ucred_t *uc = NULL;
816 	const priv_set_t *eset;
817 
818 	zone_state_t zstate;
819 	zone_cmd_t cmd;
820 	zone_cmd_arg_t *zargp;
821 
822 	boolean_t kernelcall;
823 
824 	int rval = -1;
825 	uint64_t uniqid;
826 	zoneid_t zoneid = -1;
827 	zlog_t zlog;
828 	zlog_t *zlogp;
829 	zone_cmd_rval_t *rvalp;
830 	size_t rlen = getpagesize(); /* conservative */
831 	fs_callback_t cb;
832 	brand_handle_t bh;
833 
834 	/* LINTED E_BAD_PTR_CAST_ALIGN */
835 	zargp = (zone_cmd_arg_t *)args;
836 
837 	/*
838 	 * When we get the door unref message, we've fdetach'd the door, and
839 	 * it is time for us to shut down zoneadmd.
840 	 */
841 	if (zargp == DOOR_UNREF_DATA) {
842 		/*
843 		 * See comment at end of main() for info on the last rites.
844 		 */
845 		exit(0);
846 	}
847 
848 	if (zargp == NULL) {
849 		(void) door_return(NULL, 0, 0, 0);
850 	}
851 
852 	rvalp = alloca(rlen);
853 	bzero(rvalp, rlen);
854 	zlog.logfile = NULL;
855 	zlog.buflen = zlog.loglen = rlen - sizeof (zone_cmd_rval_t) + 1;
856 	zlog.buf = rvalp->errbuf;
857 	zlog.log = zlog.buf;
858 	/* defer initialization of zlog.locale until after credential check */
859 	zlogp = &zlog;
860 
861 	if (alen != sizeof (zone_cmd_arg_t)) {
862 		/*
863 		 * This really shouldn't be happening.
864 		 */
865 		zerror(&logsys, B_FALSE, "argument size (%d bytes) "
866 		    "unexpected (expected %d bytes)", alen,
867 		    sizeof (zone_cmd_arg_t));
868 		goto out;
869 	}
870 	cmd = zargp->cmd;
871 
872 	if (door_ucred(&uc) != 0) {
873 		zerror(&logsys, B_TRUE, "door_ucred");
874 		goto out;
875 	}
876 	eset = ucred_getprivset(uc, PRIV_EFFECTIVE);
877 	if (ucred_getzoneid(uc) != GLOBAL_ZONEID ||
878 	    (eset != NULL ? !priv_ismember(eset, PRIV_SYS_CONFIG) :
879 	    ucred_geteuid(uc) != 0)) {
880 		zerror(&logsys, B_FALSE, "insufficient privileges");
881 		goto out;
882 	}
883 
884 	kernelcall = ucred_getpid(uc) == 0;
885 
886 	/*
887 	 * This is safe because we only use a zlog_t throughout the
888 	 * duration of a door call; i.e., by the time the pointer
889 	 * might become invalid, the door call would be over.
890 	 */
891 	zlog.locale = kernelcall ? DEFAULT_LOCALE : zargp->locale;
892 
893 	(void) mutex_lock(&lock);
894 
895 	/*
896 	 * Once we start to really die off, we don't want more connections.
897 	 */
898 	if (in_death_throes) {
899 		(void) mutex_unlock(&lock);
900 		ucred_free(uc);
901 		(void) door_return(NULL, 0, 0, 0);
902 		thr_exit(NULL);
903 	}
904 
905 	/*
906 	 * Check for validity of command.
907 	 */
908 	if (cmd != Z_READY && cmd != Z_BOOT && cmd != Z_FORCEBOOT &&
909 	    cmd != Z_REBOOT && cmd != Z_HALT && cmd != Z_NOTE_UNINSTALLING &&
910 	    cmd != Z_MOUNT && cmd != Z_FORCEMOUNT && cmd != Z_UNMOUNT) {
911 		zerror(&logsys, B_FALSE, "invalid command %d", (int)cmd);
912 		goto out;
913 	}
914 
915 	if (kernelcall && (cmd != Z_HALT && cmd != Z_REBOOT)) {
916 		/*
917 		 * Can't happen
918 		 */
919 		zerror(&logsys, B_FALSE, "received unexpected kernel upcall %d",
920 		    cmd);
921 		goto out;
922 	}
923 	/*
924 	 * We ignore the possibility of someone calling zone_create(2)
925 	 * explicitly; all requests must come through zoneadmd.
926 	 */
927 	if (zone_get_state(zone_name, &zstate) != Z_OK) {
928 		/*
929 		 * Something terribly wrong happened
930 		 */
931 		zerror(&logsys, B_FALSE, "unable to determine state of zone");
932 		goto out;
933 	}
934 
935 	if (kernelcall) {
936 		/*
937 		 * Kernel-initiated requests may lose their validity if the
938 		 * zone_t the kernel was referring to has gone away.
939 		 */
940 		if ((zoneid = getzoneidbyname(zone_name)) == -1 ||
941 		    zone_getattr(zoneid, ZONE_ATTR_UNIQID, &uniqid,
942 		    sizeof (uniqid)) == -1 || uniqid != zargp->uniqid) {
943 			/*
944 			 * We're not talking about the same zone. The request
945 			 * must have arrived too late.  Return error.
946 			 */
947 			rval = -1;
948 			goto out;
949 		}
950 		zlogp = &logsys;	/* Log errors to syslog */
951 	}
952 
953 	/*
954 	 * If we are being asked to forcibly mount or boot a zone, we
955 	 * pretend that an INCOMPLETE zone is actually INSTALLED.
956 	 */
957 	if (zstate == ZONE_STATE_INCOMPLETE &&
958 	    (cmd == Z_FORCEBOOT || cmd == Z_FORCEMOUNT))
959 		zstate = ZONE_STATE_INSTALLED;
960 
961 	switch (zstate) {
962 	case ZONE_STATE_CONFIGURED:
963 	case ZONE_STATE_INCOMPLETE:
964 		/*
965 		 * Not our area of expertise; we just print a nice message
966 		 * and die off.
967 		 */
968 		zerror(zlogp, B_FALSE,
969 		    "%s operation is invalid for zones in state '%s'",
970 		    z_cmd_name(cmd), zone_state_str(zstate));
971 		break;
972 
973 	case ZONE_STATE_INSTALLED:
974 		switch (cmd) {
975 		case Z_READY:
976 			rval = zone_ready(zlogp, B_FALSE);
977 			if (rval == 0)
978 				eventstream_write(Z_EVT_ZONE_READIED);
979 			break;
980 		case Z_BOOT:
981 		case Z_FORCEBOOT:
982 			eventstream_write(Z_EVT_ZONE_BOOTING);
983 			if ((rval = zone_ready(zlogp, B_FALSE)) == 0)
984 				rval = zone_bootup(zlogp, zargp->bootbuf);
985 			audit_put_record(zlogp, uc, rval, "boot");
986 			if (rval != 0) {
987 				bringup_failure_recovery = B_TRUE;
988 				(void) zone_halt(zlogp, B_FALSE, B_FALSE);
989 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
990 			}
991 			break;
992 		case Z_HALT:
993 			if (kernelcall)	/* Invalid; can't happen */
994 				abort();
995 			/*
996 			 * We could have two clients racing to halt this
997 			 * zone; the second client loses, but his request
998 			 * doesn't fail, since the zone is now in the desired
999 			 * state.
1000 			 */
1001 			zerror(zlogp, B_FALSE, "zone is already halted");
1002 			rval = 0;
1003 			break;
1004 		case Z_REBOOT:
1005 			if (kernelcall)	/* Invalid; can't happen */
1006 				abort();
1007 			zerror(zlogp, B_FALSE, "%s operation is invalid "
1008 			    "for zones in state '%s'", z_cmd_name(cmd),
1009 			    zone_state_str(zstate));
1010 			rval = -1;
1011 			break;
1012 		case Z_NOTE_UNINSTALLING:
1013 			if (kernelcall)	/* Invalid; can't happen */
1014 				abort();
1015 			/*
1016 			 * Tell the console to print out a message about this.
1017 			 * Once it does, we will be in_death_throes.
1018 			 */
1019 			eventstream_write(Z_EVT_ZONE_UNINSTALLING);
1020 			break;
1021 		case Z_MOUNT:
1022 		case Z_FORCEMOUNT:
1023 			if (kernelcall)	/* Invalid; can't happen */
1024 				abort();
1025 			if (!zone_isnative) {
1026 				zerror(zlogp, B_FALSE,
1027 				    "%s operation is invalid for branded "
1028 				    "zones", z_cmd_name(cmd));
1029 				rval = -1;
1030 				break;
1031 			}
1032 
1033 			rval = zone_ready(zlogp, B_TRUE);
1034 			if (rval != 0)
1035 				break;
1036 
1037 			eventstream_write(Z_EVT_ZONE_READIED);
1038 
1039 			/* Get a handle to the brand info for this zone */
1040 			if ((bh = brand_open(brand_name)) == NULL) {
1041 				rval = -1;
1042 				break;
1043 			}
1044 
1045 			/*
1046 			 * Get the list of filesystems to mount from
1047 			 * the brand configuration.  These mounts are done
1048 			 * via a thread that will enter the zone, so they
1049 			 * are done from within the context of the zone.
1050 			 */
1051 			cb.zlogp = zlogp;
1052 			cb.zoneid = zone_id;
1053 			rval = brand_platform_iter_mounts(bh,
1054 			    mount_early_fs, &cb);
1055 
1056 			brand_close(bh);
1057 
1058 			/*
1059 			 * Ordinarily, /dev/fd would be mounted inside the zone
1060 			 * by svc:/system/filesystem/usr:default, but since
1061 			 * we're not booting the zone, we need to do this
1062 			 * manually.
1063 			 */
1064 			if (rval == 0)
1065 				rval = mount_early_fs(&cb,
1066 				    "fd", "/dev/fd", "fd", NULL);
1067 			break;
1068 		case Z_UNMOUNT:
1069 			if (kernelcall)	/* Invalid; can't happen */
1070 				abort();
1071 			zerror(zlogp, B_FALSE, "zone is already unmounted");
1072 			rval = 0;
1073 			break;
1074 		}
1075 		break;
1076 
1077 	case ZONE_STATE_READY:
1078 		switch (cmd) {
1079 		case Z_READY:
1080 			/*
1081 			 * We could have two clients racing to ready this
1082 			 * zone; the second client loses, but his request
1083 			 * doesn't fail, since the zone is now in the desired
1084 			 * state.
1085 			 */
1086 			zerror(zlogp, B_FALSE, "zone is already ready");
1087 			rval = 0;
1088 			break;
1089 		case Z_BOOT:
1090 			(void) strlcpy(boot_args, zargp->bootbuf,
1091 			    sizeof (boot_args));
1092 			eventstream_write(Z_EVT_ZONE_BOOTING);
1093 			rval = zone_bootup(zlogp, zargp->bootbuf);
1094 			audit_put_record(zlogp, uc, rval, "boot");
1095 			if (rval != 0) {
1096 				bringup_failure_recovery = B_TRUE;
1097 				(void) zone_halt(zlogp, B_FALSE, B_TRUE);
1098 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
1099 			}
1100 			boot_args[0] = '\0';
1101 			break;
1102 		case Z_HALT:
1103 			if (kernelcall)	/* Invalid; can't happen */
1104 				abort();
1105 			if ((rval = zone_halt(zlogp, B_FALSE, B_FALSE)) != 0)
1106 				break;
1107 			eventstream_write(Z_EVT_ZONE_HALTED);
1108 			break;
1109 		case Z_REBOOT:
1110 		case Z_NOTE_UNINSTALLING:
1111 		case Z_MOUNT:
1112 		case Z_UNMOUNT:
1113 			if (kernelcall)	/* Invalid; can't happen */
1114 				abort();
1115 			zerror(zlogp, B_FALSE, "%s operation is invalid "
1116 			    "for zones in state '%s'", z_cmd_name(cmd),
1117 			    zone_state_str(zstate));
1118 			rval = -1;
1119 			break;
1120 		}
1121 		break;
1122 
1123 	case ZONE_STATE_MOUNTED:
1124 		switch (cmd) {
1125 		case Z_UNMOUNT:
1126 			if (kernelcall)	/* Invalid; can't happen */
1127 				abort();
1128 			rval = zone_halt(zlogp, B_TRUE, B_FALSE);
1129 			if (rval == 0) {
1130 				eventstream_write(Z_EVT_ZONE_HALTED);
1131 				(void) sema_post(&scratch_sem);
1132 			}
1133 			break;
1134 		default:
1135 			if (kernelcall)	/* Invalid; can't happen */
1136 				abort();
1137 			zerror(zlogp, B_FALSE, "%s operation is invalid "
1138 			    "for zones in state '%s'", z_cmd_name(cmd),
1139 			    zone_state_str(zstate));
1140 			rval = -1;
1141 			break;
1142 		}
1143 		break;
1144 
1145 	case ZONE_STATE_RUNNING:
1146 	case ZONE_STATE_SHUTTING_DOWN:
1147 	case ZONE_STATE_DOWN:
1148 		switch (cmd) {
1149 		case Z_READY:
1150 			if ((rval = zone_halt(zlogp, B_FALSE, B_TRUE)) != 0)
1151 				break;
1152 			if ((rval = zone_ready(zlogp, B_FALSE)) == 0)
1153 				eventstream_write(Z_EVT_ZONE_READIED);
1154 			else
1155 				eventstream_write(Z_EVT_ZONE_HALTED);
1156 			break;
1157 		case Z_BOOT:
1158 			/*
1159 			 * We could have two clients racing to boot this
1160 			 * zone; the second client loses, but his request
1161 			 * doesn't fail, since the zone is now in the desired
1162 			 * state.
1163 			 */
1164 			zerror(zlogp, B_FALSE, "zone is already booted");
1165 			rval = 0;
1166 			break;
1167 		case Z_HALT:
1168 			if ((rval = zone_halt(zlogp, B_FALSE, B_FALSE)) != 0)
1169 				break;
1170 			eventstream_write(Z_EVT_ZONE_HALTED);
1171 			break;
1172 		case Z_REBOOT:
1173 			(void) strlcpy(boot_args, zargp->bootbuf,
1174 			    sizeof (boot_args));
1175 			eventstream_write(Z_EVT_ZONE_REBOOTING);
1176 			if ((rval = zone_halt(zlogp, B_FALSE, B_TRUE)) != 0) {
1177 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
1178 				boot_args[0] = '\0';
1179 				break;
1180 			}
1181 			if ((rval = zone_ready(zlogp, B_FALSE)) != 0) {
1182 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
1183 				boot_args[0] = '\0';
1184 				break;
1185 			}
1186 			rval = zone_bootup(zlogp, zargp->bootbuf);
1187 			audit_put_record(zlogp, uc, rval, "reboot");
1188 			if (rval != 0) {
1189 				(void) zone_halt(zlogp, B_FALSE, B_TRUE);
1190 				eventstream_write(Z_EVT_ZONE_BOOTFAILED);
1191 			}
1192 			boot_args[0] = '\0';
1193 			break;
1194 		case Z_NOTE_UNINSTALLING:
1195 		case Z_MOUNT:
1196 		case Z_UNMOUNT:
1197 			zerror(zlogp, B_FALSE, "%s operation is invalid "
1198 			    "for zones in state '%s'", z_cmd_name(cmd),
1199 			    zone_state_str(zstate));
1200 			rval = -1;
1201 			break;
1202 		}
1203 		break;
1204 	default:
1205 		abort();
1206 	}
1207 
1208 	/*
1209 	 * Because the state of the zone may have changed, we make sure
1210 	 * to wake the console poller, which is in charge of initiating
1211 	 * the shutdown procedure as necessary.
1212 	 */
1213 	eventstream_write(Z_EVT_NULL);
1214 
1215 out:
1216 	(void) mutex_unlock(&lock);
1217 	if (kernelcall) {
1218 		rvalp = NULL;
1219 		rlen = 0;
1220 	} else {
1221 		rvalp->rval = rval;
1222 	}
1223 	if (uc != NULL)
1224 		ucred_free(uc);
1225 	(void) door_return((char *)rvalp, rlen, NULL, 0);
1226 	thr_exit(NULL);
1227 }
1228 
1229 static int
1230 setup_door(zlog_t *zlogp)
1231 {
1232 	if ((zone_door = door_create(server, NULL,
1233 	    DOOR_UNREF | DOOR_REFUSE_DESC | DOOR_NO_CANCEL)) < 0) {
1234 		zerror(zlogp, B_TRUE, "%s failed", "door_create");
1235 		return (-1);
1236 	}
1237 	(void) fdetach(zone_door_path);
1238 
1239 	if (fattach(zone_door, zone_door_path) != 0) {
1240 		zerror(zlogp, B_TRUE, "fattach to %s failed", zone_door_path);
1241 		(void) door_revoke(zone_door);
1242 		(void) fdetach(zone_door_path);
1243 		zone_door = -1;
1244 		return (-1);
1245 	}
1246 	return (0);
1247 }
1248 
1249 /*
1250  * zoneadm(1m) will start zoneadmd if it thinks it isn't running; this
1251  * is where zoneadmd itself will check to see that another instance of
1252  * zoneadmd isn't already controlling this zone.
1253  *
1254  * The idea here is that we want to open the path to which we will
1255  * attach our door, lock it, and then make sure that no-one has beat us
1256  * to fattach(3c)ing onto it.
1257  *
1258  * fattach(3c) is really a mount, so there are actually two possible
1259  * vnodes we could be dealing with.  Our strategy is as follows:
1260  *
1261  * - If the file we opened is a regular file (common case):
1262  * 	There is no fattach(3c)ed door, so we have a chance of becoming
1263  * 	the managing zoneadmd. We attempt to lock the file: if it is
1264  * 	already locked, that means someone else raced us here, so we
1265  * 	lose and give up.  zoneadm(1m) will try to contact the zoneadmd
1266  * 	that beat us to it.
1267  *
1268  * - If the file we opened is a namefs file:
1269  * 	This means there is already an established door fattach(3c)'ed
1270  * 	to the rendezvous path.  We've lost the race, so we give up.
1271  * 	Note that in this case we also try to grab the file lock, and
1272  * 	will succeed in acquiring it since the vnode locked by the
1273  * 	"winning" zoneadmd was a regular one, and the one we locked was
1274  * 	the fattach(3c)'ed door node.  At any rate, no harm is done, and
1275  * 	we just return to zoneadm(1m) which knows to retry.
1276  */
1277 static int
1278 make_daemon_exclusive(zlog_t *zlogp)
1279 {
1280 	int doorfd = -1;
1281 	int err, ret = -1;
1282 	struct stat st;
1283 	struct flock flock;
1284 	zone_state_t zstate;
1285 
1286 top:
1287 	if ((err = zone_get_state(zone_name, &zstate)) != Z_OK) {
1288 		zerror(zlogp, B_FALSE, "failed to get zone state: %s",
1289 		    zonecfg_strerror(err));
1290 		goto out;
1291 	}
1292 	if ((doorfd = open(zone_door_path, O_CREAT|O_RDWR,
1293 	    S_IREAD|S_IWRITE)) < 0) {
1294 		zerror(zlogp, B_TRUE, "failed to open %s", zone_door_path);
1295 		goto out;
1296 	}
1297 	if (fstat(doorfd, &st) < 0) {
1298 		zerror(zlogp, B_TRUE, "failed to stat %s", zone_door_path);
1299 		goto out;
1300 	}
1301 	/*
1302 	 * Lock the file to synchronize with other zoneadmd
1303 	 */
1304 	flock.l_type = F_WRLCK;
1305 	flock.l_whence = SEEK_SET;
1306 	flock.l_start = (off_t)0;
1307 	flock.l_len = (off_t)0;
1308 	if (fcntl(doorfd, F_SETLK, &flock) < 0) {
1309 		/*
1310 		 * Someone else raced us here and grabbed the lock file
1311 		 * first.  A warning here is inappropriate since nothing
1312 		 * went wrong.
1313 		 */
1314 		goto out;
1315 	}
1316 
1317 	if (strcmp(st.st_fstype, "namefs") == 0) {
1318 		struct door_info info;
1319 
1320 		/*
1321 		 * There is already something fattach()'ed to this file.
1322 		 * Lets see what the door is up to.
1323 		 */
1324 		if (door_info(doorfd, &info) == 0 && info.di_target != -1) {
1325 			/*
1326 			 * Another zoneadmd process seems to be in
1327 			 * control of the situation and we don't need to
1328 			 * be here.  A warning here is inappropriate
1329 			 * since nothing went wrong.
1330 			 *
1331 			 * If the door has been revoked, the zoneadmd
1332 			 * process currently managing the zone is going
1333 			 * away.  We'll return control to zoneadm(1m)
1334 			 * which will try again (by which time zoneadmd
1335 			 * will hopefully have exited).
1336 			 */
1337 			goto out;
1338 		}
1339 
1340 		/*
1341 		 * If we got this far, there's a fattach(3c)'ed door
1342 		 * that belongs to a process that has exited, which can
1343 		 * happen if the previous zoneadmd died unexpectedly.
1344 		 *
1345 		 * Let user know that something is amiss, but that we can
1346 		 * recover; if the zone is in the installed state, then don't
1347 		 * message, since having a running zoneadmd isn't really
1348 		 * expected/needed.  We want to keep occurences of this message
1349 		 * limited to times when zoneadmd is picking back up from a
1350 		 * zoneadmd that died while the zone was in some non-trivial
1351 		 * state.
1352 		 */
1353 		if (zstate > ZONE_STATE_INSTALLED) {
1354 			zerror(zlogp, B_FALSE,
1355 			    "zone '%s': WARNING: zone is in state '%s', but "
1356 			    "zoneadmd does not appear to be available; "
1357 			    "restarted zoneadmd to recover.",
1358 			    zone_name, zone_state_str(zstate));
1359 		}
1360 
1361 		(void) fdetach(zone_door_path);
1362 		(void) close(doorfd);
1363 		goto top;
1364 	}
1365 	ret = 0;
1366 out:
1367 	(void) close(doorfd);
1368 	return (ret);
1369 }
1370 
1371 int
1372 main(int argc, char *argv[])
1373 {
1374 	int opt;
1375 	zoneid_t zid;
1376 	priv_set_t *privset;
1377 	zone_state_t zstate;
1378 	char parents_locale[MAXPATHLEN];
1379 	brand_handle_t bh;
1380 	int err;
1381 
1382 	pid_t pid;
1383 	sigset_t blockset;
1384 	sigset_t block_cld;
1385 
1386 	struct {
1387 		sema_t sem;
1388 		int status;
1389 		zlog_t log;
1390 	} *shstate;
1391 	size_t shstatelen = getpagesize();
1392 
1393 	zlog_t errlog;
1394 	zlog_t *zlogp;
1395 
1396 	int ctfd;
1397 
1398 	progname = get_execbasename(argv[0]);
1399 
1400 	/*
1401 	 * Make sure stderr is unbuffered
1402 	 */
1403 	(void) setbuffer(stderr, NULL, 0);
1404 
1405 	/*
1406 	 * Get out of the way of mounted filesystems, since we will daemonize
1407 	 * soon.
1408 	 */
1409 	(void) chdir("/");
1410 
1411 	/*
1412 	 * Use the default system umask per PSARC 1998/110 rather than
1413 	 * anything that may have been set by the caller.
1414 	 */
1415 	(void) umask(CMASK);
1416 
1417 	/*
1418 	 * Initially we want to use our parent's locale.
1419 	 */
1420 	(void) setlocale(LC_ALL, "");
1421 	(void) textdomain(TEXT_DOMAIN);
1422 	(void) strlcpy(parents_locale, setlocale(LC_MESSAGES, NULL),
1423 	    sizeof (parents_locale));
1424 
1425 	/*
1426 	 * This zlog_t is used for writing to stderr
1427 	 */
1428 	errlog.logfile = stderr;
1429 	errlog.buflen = errlog.loglen = 0;
1430 	errlog.buf = errlog.log = NULL;
1431 	errlog.locale = parents_locale;
1432 
1433 	/*
1434 	 * We start off writing to stderr until we're ready to daemonize.
1435 	 */
1436 	zlogp = &errlog;
1437 
1438 	/*
1439 	 * Process options.
1440 	 */
1441 	while ((opt = getopt(argc, argv, "R:z:")) != EOF) {
1442 		switch (opt) {
1443 		case 'R':
1444 			zonecfg_set_root(optarg);
1445 			break;
1446 		case 'z':
1447 			zone_name = optarg;
1448 			break;
1449 		default:
1450 			usage();
1451 		}
1452 	}
1453 
1454 	if (zone_name == NULL)
1455 		usage();
1456 
1457 	/*
1458 	 * Because usage() prints directly to stderr, it has gettext()
1459 	 * wrapping, which depends on the locale.  But since zerror() calls
1460 	 * localize() which tweaks the locale, it is not safe to call zerror()
1461 	 * until after the last call to usage().  Fortunately, the last call
1462 	 * to usage() is just above and the first call to zerror() is just
1463 	 * below.  Don't mess this up.
1464 	 */
1465 	if (strcmp(zone_name, GLOBAL_ZONENAME) == 0) {
1466 		zerror(zlogp, B_FALSE, "cannot manage the %s zone",
1467 		    GLOBAL_ZONENAME);
1468 		return (1);
1469 	}
1470 
1471 	if (zone_get_id(zone_name, &zid) != 0) {
1472 		zerror(zlogp, B_FALSE, "could not manage %s: %s", zone_name,
1473 		    zonecfg_strerror(Z_NO_ZONE));
1474 		return (1);
1475 	}
1476 
1477 	if ((err = zone_get_state(zone_name, &zstate)) != Z_OK) {
1478 		zerror(zlogp, B_FALSE, "failed to get zone state: %s",
1479 		    zonecfg_strerror(err));
1480 		return (1);
1481 	}
1482 	if (zstate < ZONE_STATE_INCOMPLETE) {
1483 		zerror(zlogp, B_FALSE,
1484 		    "cannot manage a zone which is in state '%s'",
1485 		    zone_state_str(zstate));
1486 		return (1);
1487 	}
1488 
1489 	/* Get a handle to the brand info for this zone */
1490 	if ((zone_get_brand(zone_name, brand_name, sizeof (brand_name))
1491 	    != Z_OK) || (bh = brand_open(brand_name)) == NULL) {
1492 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
1493 		return (1);
1494 	}
1495 	zone_isnative = brand_is_native(bh);
1496 	brand_close(bh);
1497 
1498 	/*
1499 	 * Check that we have all privileges.  It would be nice to pare
1500 	 * this down, but this is at least a first cut.
1501 	 */
1502 	if ((privset = priv_allocset()) == NULL) {
1503 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
1504 		return (1);
1505 	}
1506 
1507 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
1508 		zerror(zlogp, B_TRUE, "%s failed", "getppriv");
1509 		priv_freeset(privset);
1510 		return (1);
1511 	}
1512 
1513 	if (priv_isfullset(privset) == B_FALSE) {
1514 		zerror(zlogp, B_FALSE, "You lack sufficient privilege to "
1515 		    "run this command (all privs required)");
1516 		priv_freeset(privset);
1517 		return (1);
1518 	}
1519 	priv_freeset(privset);
1520 
1521 	if (mkzonedir(zlogp) != 0)
1522 		return (1);
1523 
1524 	/*
1525 	 * Pre-fork: setup shared state
1526 	 */
1527 	if ((shstate = (void *)mmap(NULL, shstatelen,
1528 	    PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, (off_t)0)) ==
1529 	    MAP_FAILED) {
1530 		zerror(zlogp, B_TRUE, "%s failed", "mmap");
1531 		return (1);
1532 	}
1533 	if (sema_init(&shstate->sem, 0, USYNC_PROCESS, NULL) != 0) {
1534 		zerror(zlogp, B_TRUE, "%s failed", "sema_init()");
1535 		(void) munmap((char *)shstate, shstatelen);
1536 		return (1);
1537 	}
1538 	shstate->log.logfile = NULL;
1539 	shstate->log.buflen = shstatelen - sizeof (*shstate);
1540 	shstate->log.loglen = shstate->log.buflen;
1541 	shstate->log.buf = (char *)shstate + sizeof (*shstate);
1542 	shstate->log.log = shstate->log.buf;
1543 	shstate->log.locale = parents_locale;
1544 	shstate->status = -1;
1545 
1546 	/*
1547 	 * We need a SIGCHLD handler so the sema_wait() below will wake
1548 	 * up if the child dies without doing a sema_post().
1549 	 */
1550 	(void) sigset(SIGCHLD, sigchld);
1551 	/*
1552 	 * We must mask SIGCHLD until after we've coped with the fork
1553 	 * sufficiently to deal with it; otherwise we can race and
1554 	 * receive the signal before pid has been initialized
1555 	 * (yes, this really happens).
1556 	 */
1557 	(void) sigemptyset(&block_cld);
1558 	(void) sigaddset(&block_cld, SIGCHLD);
1559 	(void) sigprocmask(SIG_BLOCK, &block_cld, NULL);
1560 
1561 	if ((ctfd = init_template()) == -1) {
1562 		zerror(zlogp, B_TRUE, "failed to create contract");
1563 		return (1);
1564 	}
1565 
1566 	/*
1567 	 * Do not let another thread localize a message while we are forking.
1568 	 */
1569 	(void) mutex_lock(&msglock);
1570 	pid = fork();
1571 	(void) mutex_unlock(&msglock);
1572 
1573 	/*
1574 	 * In all cases (parent, child, and in the event of an error) we
1575 	 * don't want to cause creation of contracts on subsequent fork()s.
1576 	 */
1577 	(void) ct_tmpl_clear(ctfd);
1578 	(void) close(ctfd);
1579 
1580 	if (pid == -1) {
1581 		zerror(zlogp, B_TRUE, "could not fork");
1582 		return (1);
1583 
1584 	} else if (pid > 0) { /* parent */
1585 		(void) sigprocmask(SIG_UNBLOCK, &block_cld, NULL);
1586 		/*
1587 		 * This marks a window of vulnerability in which we receive
1588 		 * the SIGCLD before falling into sema_wait (normally we would
1589 		 * get woken up from sema_wait with EINTR upon receipt of
1590 		 * SIGCLD).  So we may need to use some other scheme like
1591 		 * sema_posting in the sigcld handler.
1592 		 * blech
1593 		 */
1594 		(void) sema_wait(&shstate->sem);
1595 		(void) sema_destroy(&shstate->sem);
1596 		if (shstate->status != 0)
1597 			(void) waitpid(pid, NULL, WNOHANG);
1598 		/*
1599 		 * It's ok if we die with SIGPIPE.  It's not like we could have
1600 		 * done anything about it.
1601 		 */
1602 		(void) fprintf(stderr, "%s", shstate->log.buf);
1603 		_exit(shstate->status == 0 ? 0 : 1);
1604 	}
1605 
1606 	/*
1607 	 * The child charges on.
1608 	 */
1609 	(void) sigset(SIGCHLD, SIG_DFL);
1610 	(void) sigprocmask(SIG_UNBLOCK, &block_cld, NULL);
1611 
1612 	/*
1613 	 * SIGPIPE can be delivered if we write to a socket for which the
1614 	 * peer endpoint is gone.  That can lead to too-early termination
1615 	 * of zoneadmd, and that's not good eats.
1616 	 */
1617 	(void) sigset(SIGPIPE, SIG_IGN);
1618 	/*
1619 	 * Stop using stderr
1620 	 */
1621 	zlogp = &shstate->log;
1622 
1623 	/*
1624 	 * We don't need stdout/stderr from now on.
1625 	 */
1626 	closefrom(0);
1627 
1628 	/*
1629 	 * Initialize the syslog zlog_t.  This needs to be done after
1630 	 * the call to closefrom().
1631 	 */
1632 	logsys.buf = logsys.log = NULL;
1633 	logsys.buflen = logsys.loglen = 0;
1634 	logsys.logfile = NULL;
1635 	logsys.locale = DEFAULT_LOCALE;
1636 
1637 	openlog("zoneadmd", LOG_PID, LOG_DAEMON);
1638 
1639 	/*
1640 	 * The eventstream is used to publish state changes in the zone
1641 	 * from the door threads to the console I/O poller.
1642 	 */
1643 	if (eventstream_init() == -1) {
1644 		zerror(zlogp, B_TRUE, "unable to create eventstream");
1645 		goto child_out;
1646 	}
1647 
1648 	(void) snprintf(zone_door_path, sizeof (zone_door_path),
1649 	    "%s" ZONE_DOOR_PATH, zonecfg_get_root(), zone_name);
1650 
1651 	/*
1652 	 * See if another zoneadmd is running for this zone.  If not, then we
1653 	 * can now modify system state.
1654 	 */
1655 	if (make_daemon_exclusive(zlogp) == -1)
1656 		goto child_out;
1657 
1658 
1659 	/*
1660 	 * Create/join a new session; we need to be careful of what we do with
1661 	 * the console from now on so we don't end up being the session leader
1662 	 * for the terminal we're going to be handing out.
1663 	 */
1664 	(void) setsid();
1665 
1666 	/*
1667 	 * This thread shouldn't be receiving any signals; in particular,
1668 	 * SIGCHLD should be received by the thread doing the fork().
1669 	 */
1670 	(void) sigfillset(&blockset);
1671 	(void) thr_sigsetmask(SIG_BLOCK, &blockset, NULL);
1672 
1673 	/*
1674 	 * Setup the console device and get ready to serve the console;
1675 	 * once this has completed, we're ready to let console clients
1676 	 * make an attempt to connect (they will block until
1677 	 * serve_console_sock() below gets called, and any pending
1678 	 * connection is accept()ed).
1679 	 */
1680 	if (!zonecfg_in_alt_root() && init_console(zlogp) == -1)
1681 		goto child_out;
1682 
1683 	/*
1684 	 * Take the lock now, so that when the door server gets going, we
1685 	 * are guaranteed that it won't take a request until we are sure
1686 	 * that everything is completely set up.  See the child_out: label
1687 	 * below to see why this matters.
1688 	 */
1689 	(void) mutex_lock(&lock);
1690 
1691 	/* Init semaphore for scratch zones. */
1692 	if (sema_init(&scratch_sem, 0, USYNC_THREAD, NULL) == -1) {
1693 		zerror(zlogp, B_TRUE,
1694 		    "failed to initialize semaphore for scratch zone");
1695 		goto child_out;
1696 	}
1697 
1698 	/*
1699 	 * Note: door setup must occur *after* the console is setup.
1700 	 * This is so that as zlogin tests the door to see if zoneadmd
1701 	 * is ready yet, we know that the console will get serviced
1702 	 * once door_info() indicates that the door is "up".
1703 	 */
1704 	if (setup_door(zlogp) == -1)
1705 		goto child_out;
1706 
1707 	/*
1708 	 * Things seem OK so far; tell the parent process that we're done
1709 	 * with setup tasks.  This will cause the parent to exit, signalling
1710 	 * to zoneadm, zlogin, or whatever forked it that we are ready to
1711 	 * service requests.
1712 	 */
1713 	shstate->status = 0;
1714 	(void) sema_post(&shstate->sem);
1715 	(void) munmap((char *)shstate, shstatelen);
1716 	shstate = NULL;
1717 
1718 	(void) mutex_unlock(&lock);
1719 
1720 	/*
1721 	 * zlogp is now invalid, so reset it to the syslog logger.
1722 	 */
1723 	zlogp = &logsys;
1724 
1725 	/*
1726 	 * Now that we are free of any parents, switch to the default locale.
1727 	 */
1728 	(void) setlocale(LC_ALL, DEFAULT_LOCALE);
1729 
1730 	/*
1731 	 * At this point the setup portion of main() is basically done, so
1732 	 * we reuse this thread to manage the zone console.  When
1733 	 * serve_console() has returned, we are past the point of no return
1734 	 * in the life of this zoneadmd.
1735 	 */
1736 	if (zonecfg_in_alt_root()) {
1737 		/*
1738 		 * This is just awful, but mounted scratch zones don't (and
1739 		 * can't) have consoles.  We just wait for unmount instead.
1740 		 */
1741 		while (sema_wait(&scratch_sem) == EINTR)
1742 			;
1743 	} else {
1744 		serve_console(zlogp);
1745 		assert(in_death_throes);
1746 	}
1747 
1748 	/*
1749 	 * This is the next-to-last part of the exit interlock.  Upon calling
1750 	 * fdetach(), the door will go unreferenced; once any
1751 	 * outstanding requests (like the door thread doing Z_HALT) are
1752 	 * done, the door will get an UNREF notification; when it handles
1753 	 * the UNREF, the door server will cause the exit.
1754 	 */
1755 	assert(!MUTEX_HELD(&lock));
1756 	(void) fdetach(zone_door_path);
1757 	for (;;)
1758 		(void) pause();
1759 
1760 child_out:
1761 	assert(pid == 0);
1762 	if (shstate != NULL) {
1763 		shstate->status = -1;
1764 		(void) sema_post(&shstate->sem);
1765 		(void) munmap((char *)shstate, shstatelen);
1766 	}
1767 
1768 	/*
1769 	 * This might trigger an unref notification, but if so,
1770 	 * we are still holding the lock, so our call to exit will
1771 	 * ultimately win the race and will publish the right exit
1772 	 * code.
1773 	 */
1774 	if (zone_door != -1) {
1775 		assert(MUTEX_HELD(&lock));
1776 		(void) door_revoke(zone_door);
1777 		(void) fdetach(zone_door_path);
1778 	}
1779 	return (1); /* return from main() forcibly exits an MT process */
1780 }
1781