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