xref: /titanic_41/usr/src/cmd/zoneadm/zoneadm.c (revision 4f85d229295a756a4e6f1759b47df7b97412db7d)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 /*
31  * zoneadm is a command interpreter for zone administration.  It is all in
32  * C (i.e., no lex/yacc), and all the argument passing is argc/argv based.
33  * main() calls parse_and_run() which calls cmd_match(), then invokes the
34  * appropriate command's handler function.  The rest of the program is the
35  * handler functions and their helper functions.
36  *
37  * Some of the helper functions are used largely to simplify I18N: reducing
38  * the need for translation notes.  This is particularly true of many of
39  * the zerror() calls: doing e.g. zerror(gettext("%s failed"), "foo") rather
40  * than zerror(gettext("foo failed")) with a translation note indicating
41  * that "foo" need not be translated.
42  */
43 
44 #include <stdio.h>
45 #include <errno.h>
46 #include <unistd.h>
47 #include <signal.h>
48 #include <stdarg.h>
49 #include <ctype.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <wait.h>
53 #include <zone.h>
54 #include <priv.h>
55 #include <locale.h>
56 #include <libintl.h>
57 #include <libzonecfg.h>
58 #include <bsm/adt.h>
59 #include <sys/utsname.h>
60 #include <sys/param.h>
61 #include <sys/types.h>
62 #include <sys/stat.h>
63 #include <sys/statvfs.h>
64 #include <assert.h>
65 #include <sys/sockio.h>
66 #include <sys/mntent.h>
67 #include <limits.h>
68 #include <libzfs.h>
69 
70 #include <fcntl.h>
71 #include <door.h>
72 #include <macros.h>
73 #include <libgen.h>
74 
75 #include <pool.h>
76 #include <sys/pool.h>
77 
78 #define	MAXARGS	8
79 
80 /* Reflects kernel zone entries */
81 typedef struct zone_entry {
82 	zoneid_t	zid;
83 	char		zname[ZONENAME_MAX];
84 	char		*zstate_str;
85 	zone_state_t	zstate_num;
86 	char		zroot[MAXPATHLEN];
87 } zone_entry_t;
88 
89 static zone_entry_t *zents;
90 static size_t nzents;
91 
92 #if !defined(TEXT_DOMAIN)		/* should be defined by cc -D */
93 #define	TEXT_DOMAIN	"SYS_TEST"	/* Use this only if it wasn't */
94 #endif
95 
96 #define	Z_ERR	1
97 #define	Z_USAGE	2
98 
99 /* 0755 is the default directory mode. */
100 #define	DEFAULT_DIR_MODE \
101 	(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
102 
103 #define	CMD_HELP	0
104 #define	CMD_BOOT	1
105 #define	CMD_HALT	2
106 #define	CMD_READY	3
107 #define	CMD_REBOOT	4
108 #define	CMD_LIST	5
109 #define	CMD_VERIFY	6
110 #define	CMD_INSTALL	7
111 #define	CMD_UNINSTALL	8
112 #define	CMD_MOUNT	9
113 #define	CMD_UNMOUNT	10
114 
115 #define	CMD_MIN		CMD_HELP
116 #define	CMD_MAX		CMD_UNMOUNT
117 
118 struct cmd {
119 	uint_t	cmd_num;				/* command number */
120 	char	*cmd_name;				/* command name */
121 	char	*short_usage;				/* short form help */
122 	int	(*handler)(int argc, char *argv[]);	/* function to call */
123 
124 };
125 
126 #define	SHELP_HELP	"help"
127 #define	SHELP_BOOT	"boot [-s]"
128 #define	SHELP_HALT	"halt"
129 #define	SHELP_READY	"ready"
130 #define	SHELP_REBOOT	"reboot"
131 #define	SHELP_LIST	"list [-cipv]"
132 #define	SHELP_VERIFY	"verify"
133 #define	SHELP_INSTALL	"install"
134 #define	SHELP_UNINSTALL	"uninstall [-F]"
135 
136 static int help_func(int argc, char *argv[]);
137 static int ready_func(int argc, char *argv[]);
138 static int boot_func(int argc, char *argv[]);
139 static int halt_func(int argc, char *argv[]);
140 static int reboot_func(int argc, char *argv[]);
141 static int list_func(int argc, char *argv[]);
142 static int verify_func(int argc, char *argv[]);
143 static int install_func(int argc, char *argv[]);
144 static int uninstall_func(int argc, char *argv[]);
145 static int mount_func(int argc, char *argv[]);
146 static int unmount_func(int argc, char *argv[]);
147 static int sanity_check(char *zone, int cmd_num, boolean_t running,
148     boolean_t unsafe_when_running);
149 static int cmd_match(char *cmd);
150 static int verify_details(int);
151 
152 static struct cmd cmdtab[] = {
153 	{ CMD_HELP,		"help",		SHELP_HELP,	help_func },
154 	{ CMD_BOOT,		"boot",		SHELP_BOOT,	boot_func },
155 	{ CMD_HALT,		"halt",		SHELP_HALT,	halt_func },
156 	{ CMD_READY,		"ready",	SHELP_READY,	ready_func },
157 	{ CMD_REBOOT,		"reboot",	SHELP_REBOOT,	reboot_func },
158 	{ CMD_LIST,		"list",		SHELP_LIST,	list_func },
159 	{ CMD_VERIFY,		"verify",	SHELP_VERIFY,	verify_func },
160 	{ CMD_INSTALL,		"install",	SHELP_INSTALL,	install_func },
161 	{ CMD_UNINSTALL,	"uninstall",	SHELP_UNINSTALL,
162 	    uninstall_func },
163 	/* Private commands for admin/install */
164 	{ CMD_MOUNT,		"mount",	NULL,		mount_func },
165 	{ CMD_UNMOUNT,		"unmount",	NULL,		unmount_func }
166 };
167 
168 /* global variables */
169 
170 /* set early in main(), never modified thereafter, used all over the place */
171 static char *execname;
172 static char *target_zone;
173 static char *locale;
174 
175 /* used in do_subproc() and signal handler */
176 static volatile boolean_t child_killed;
177 
178 static char *
179 cmd_to_str(int cmd_num)
180 {
181 	assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
182 	return (cmdtab[cmd_num].cmd_name);
183 }
184 
185 /* This is a separate function because of gettext() wrapping. */
186 static char *
187 long_help(int cmd_num)
188 {
189 	assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
190 	switch (cmd_num) {
191 		case CMD_HELP:
192 			return (gettext("Print usage message."));
193 		case CMD_BOOT:
194 			return (gettext("Activates (boots) specified zone.  "
195 			    "The -s flag can be used\n\tto boot the zone in "
196 			    "the single-user state."));
197 		case CMD_HALT:
198 			return (gettext("Halts specified zone, bypassing "
199 			    "shutdown scripts and removing runtime\n\t"
200 			    "resources of the zone."));
201 		case CMD_READY:
202 			return (gettext("Prepares a zone for running "
203 			    "applications but does not start any user\n\t"
204 			    "processes in the zone."));
205 		case CMD_REBOOT:
206 			return (gettext("Restarts the zone (equivalent to a "
207 			    "halt / boot sequence).\n\tFails if the zone is "
208 			    "not active."));
209 		case CMD_LIST:
210 			return (gettext("Lists the current zones, or a "
211 			    "specific zone if indicated.  By default,\n\tall "
212 			    "running zones are listed, though this can be "
213 			    "expanded to all\n\tinstalled zones with the -i "
214 			    "option or all configured zones with the\n\t-c "
215 			    "option.  When used with the general -z <zone> "
216 			    "option, lists only the\n\tspecified zone, but "
217 			    "lists it regardless of its state, and the -i "
218 			    "and -c\n\toptions are disallowed.  The -v option "
219 			    "can be used to display verbose\n\tinformation: "
220 			    "zone name, id, current state, root directory and "
221 			    "options.\n\tThe -p option can be used to request "
222 			    "machine-parsable output.  The -v\n\tand -p "
223 			    "options are mutually exclusive.  If neither -v "
224 			    "nor -p is used,\n\tjust the zone name is "
225 			    "listed."));
226 		case CMD_VERIFY:
227 			return (gettext("Check to make sure the configuration "
228 			    "can safely be instantiated\n\ton the machine: "
229 			    "physical network interfaces exist, etc."));
230 		case CMD_INSTALL:
231 			return (gettext("Install the configuration on to the "
232 			    "system."));
233 		case CMD_UNINSTALL:
234 			return (gettext("Uninstall the configuration from the "
235 			    "system.  The -F flag can be used\n\tto force the "
236 			    "action."));
237 		default:
238 			return ("");
239 	}
240 	/* NOTREACHED */
241 	return (NULL);
242 }
243 
244 /*
245  * Called with explicit B_TRUE when help is explicitly requested, B_FALSE for
246  * unexpected errors.
247  */
248 
249 static int
250 usage(boolean_t explicit)
251 {
252 	int i;
253 	FILE *fd = explicit ? stdout : stderr;
254 
255 	(void) fprintf(fd, "%s:\t%s help\n", gettext("usage"), execname);
256 	(void) fprintf(fd, "\t%s [-z <zone>] list\n", execname);
257 	(void) fprintf(fd, "\t%s -z <zone> <%s>\n", execname,
258 	    gettext("subcommand"));
259 	(void) fprintf(fd, "\n%s:\n\n", gettext("Subcommands"));
260 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
261 		if (cmdtab[i].short_usage == NULL)
262 			continue;
263 		(void) fprintf(fd, "%s\n", cmdtab[i].short_usage);
264 		if (explicit)
265 			(void) fprintf(fd, "\t%s\n\n", long_help(i));
266 	}
267 	if (!explicit)
268 		(void) fputs("\n", fd);
269 	return (Z_USAGE);
270 }
271 
272 static void
273 sub_usage(char *short_usage, int cmd_num)
274 {
275 	(void) fprintf(stderr, "%s:\t%s\n", gettext("usage"), short_usage);
276 	(void) fprintf(stderr, "\t%s\n", long_help(cmd_num));
277 }
278 
279 /*
280  * zperror() is like perror(3c) except that this also prints the executable
281  * name at the start of the message, and takes a boolean indicating whether
282  * to call libc'c strerror() or that from libzonecfg.
283  */
284 
285 static void
286 zperror(const char *str, boolean_t zonecfg_error)
287 {
288 	(void) fprintf(stderr, "%s: %s: %s\n", execname, str,
289 	    zonecfg_error ? zonecfg_strerror(errno) : strerror(errno));
290 }
291 
292 /*
293  * zperror2() is very similar to zperror() above, except it also prints a
294  * supplied zone name after the executable.
295  *
296  * All current consumers of this function want libzonecfg's strerror() rather
297  * than libc's; if this ever changes, this function can be made more generic
298  * like zperror() above.
299  */
300 
301 static void
302 zperror2(const char *zone, const char *str)
303 {
304 	(void) fprintf(stderr, "%s: %s: %s: %s\n", execname, zone, str,
305 	    zonecfg_strerror(errno));
306 }
307 
308 /* PRINTFLIKE1 */
309 static void
310 zerror(const char *fmt, ...)
311 {
312 	va_list alist;
313 
314 	va_start(alist, fmt);
315 	(void) fprintf(stderr, "%s: ", execname);
316 	if (target_zone != NULL)
317 		(void) fprintf(stderr, "zone '%s': ", target_zone);
318 	(void) vfprintf(stderr, fmt, alist);
319 	(void) fprintf(stderr, "\n");
320 	va_end(alist);
321 }
322 
323 static void *
324 safe_calloc(size_t nelem, size_t elsize)
325 {
326 	void *r = calloc(nelem, elsize);
327 
328 	if (r == NULL) {
329 		zerror(gettext("failed to allocate %lu bytes: %s"),
330 		    (ulong_t)nelem * elsize, strerror(errno));
331 		exit(Z_ERR);
332 	}
333 	return (r);
334 }
335 
336 static void
337 zone_print(zone_entry_t *zent, boolean_t verbose, boolean_t parsable)
338 {
339 	static boolean_t firsttime = B_TRUE;
340 
341 	assert(!(verbose && parsable));
342 	if (firsttime && verbose) {
343 		firsttime = B_FALSE;
344 		(void) printf("%*s %-16s %-14s %-30s\n", ZONEID_WIDTH, "ID",
345 		    "NAME", "STATUS", "PATH");
346 	}
347 	if (!verbose) {
348 		if (!parsable) {
349 			(void) printf("%s\n", zent->zname);
350 			return;
351 		}
352 		if (zent->zid == ZONE_ID_UNDEFINED)
353 			(void) printf("-");
354 		else
355 			(void) printf("%lu", zent->zid);
356 		(void) printf(":%s:%s:%s\n", zent->zname, zent->zstate_str,
357 		    zent->zroot);
358 		return;
359 	}
360 	if (zent->zstate_str != NULL) {
361 		if (zent->zid == ZONE_ID_UNDEFINED)
362 			(void) printf("%*s", ZONEID_WIDTH, "-");
363 		else
364 			(void) printf("%*lu", ZONEID_WIDTH, zent->zid);
365 		(void) printf(" %-16s %-14s %-30s\n", zent->zname,
366 		    zent->zstate_str, zent->zroot);
367 	}
368 }
369 
370 static int
371 lookup_zone_info(const char *zone_name, zoneid_t zid, zone_entry_t *zent)
372 {
373 	char root[MAXPATHLEN];
374 	int err;
375 
376 	(void) strlcpy(zent->zname, zone_name, sizeof (zent->zname));
377 	(void) strlcpy(zent->zroot, "???", sizeof (zent->zroot));
378 	zent->zstate_str = "???";
379 
380 	zent->zid = zid;
381 
382 	if ((err = zone_get_zonepath(zent->zname, root, sizeof (root))) !=
383 	    Z_OK) {
384 		errno = err;
385 		zperror2(zent->zname, gettext("could not get zone path"));
386 		return (Z_ERR);
387 	}
388 	(void) strlcpy(zent->zroot, root, sizeof (zent->zroot));
389 
390 	if ((err = zone_get_state(zent->zname, &zent->zstate_num)) != Z_OK) {
391 		errno = err;
392 		zperror2(zent->zname, gettext("could not get state"));
393 		return (Z_ERR);
394 	}
395 	zent->zstate_str = zone_state_str(zent->zstate_num);
396 
397 	return (Z_OK);
398 }
399 
400 /*
401  * fetch_zents() calls zone_list(2) to find out how many zones are running
402  * (which is stored in the global nzents), then calls zone_list(2) again
403  * to fetch the list of running zones (stored in the global zents).  This
404  * function may be called multiple times, so if zents is already set, we
405  * return immediately to save work.
406  */
407 
408 static int
409 fetch_zents(void)
410 {
411 	zoneid_t *zids = NULL;
412 	uint_t nzents_saved;
413 	int i, retv;
414 	FILE *fp;
415 	boolean_t inaltroot;
416 	zone_entry_t *zentp;
417 
418 	if (nzents > 0)
419 		return (Z_OK);
420 
421 	if (zone_list(NULL, &nzents) != 0) {
422 		zperror(gettext("failed to get zoneid list"), B_FALSE);
423 		return (Z_ERR);
424 	}
425 
426 again:
427 	if (nzents == 0)
428 		return (Z_OK);
429 
430 	zids = safe_calloc(nzents, sizeof (zoneid_t));
431 	nzents_saved = nzents;
432 
433 	if (zone_list(zids, &nzents) != 0) {
434 		zperror(gettext("failed to get zone list"), B_FALSE);
435 		free(zids);
436 		return (Z_ERR);
437 	}
438 	if (nzents != nzents_saved) {
439 		/* list changed, try again */
440 		free(zids);
441 		goto again;
442 	}
443 
444 	zents = safe_calloc(nzents, sizeof (zone_entry_t));
445 
446 	inaltroot = zonecfg_in_alt_root();
447 	if (inaltroot)
448 		fp = zonecfg_open_scratch("", B_FALSE);
449 	else
450 		fp = NULL;
451 	zentp = zents;
452 	retv = Z_OK;
453 	for (i = 0; i < nzents; i++) {
454 		char name[ZONENAME_MAX];
455 		char altname[ZONENAME_MAX];
456 
457 		if (getzonenamebyid(zids[i], name, sizeof (name)) < 0) {
458 			zperror(gettext("failed to get zone name"), B_FALSE);
459 			retv = Z_ERR;
460 			continue;
461 		}
462 		if (zonecfg_is_scratch(name)) {
463 			/* Ignore scratch zones by default */
464 			if (!inaltroot)
465 				continue;
466 			if (fp == NULL ||
467 			    zonecfg_reverse_scratch(fp, name, altname,
468 			    sizeof (altname), NULL, 0) == -1) {
469 				zerror(gettext("could not resolve scratch "
470 				    "zone %s"), name);
471 				retv = Z_ERR;
472 				continue;
473 			}
474 			(void) strcpy(name, altname);
475 		} else {
476 			/* Ignore non-scratch when in an alternate root */
477 			if (inaltroot && strcmp(name, GLOBAL_ZONENAME) != 0)
478 				continue;
479 		}
480 		if (lookup_zone_info(name, zids[i], zentp) != Z_OK) {
481 			zerror(gettext("failed to get zone data"));
482 			retv = Z_ERR;
483 			continue;
484 		}
485 		zentp++;
486 	}
487 	nzents = zentp - zents;
488 	if (fp != NULL)
489 		zonecfg_close_scratch(fp);
490 
491 	free(zids);
492 	return (retv);
493 }
494 
495 static int
496 zone_print_list(zone_state_t min_state, boolean_t verbose, boolean_t parsable)
497 {
498 	int i;
499 	zone_entry_t zent;
500 	FILE *cookie;
501 	char *name;
502 
503 	/*
504 	 * First get the list of running zones from the kernel and print them.
505 	 * If that is all we need, then return.
506 	 */
507 	if ((i = fetch_zents()) != Z_OK) {
508 		/*
509 		 * No need for error messages; fetch_zents() has already taken
510 		 * care of this.
511 		 */
512 		return (i);
513 	}
514 	for (i = 0; i < nzents; i++)
515 		zone_print(&zents[i], verbose, parsable);
516 	if (min_state >= ZONE_STATE_RUNNING)
517 		return (Z_OK);
518 	/*
519 	 * Next, get the full list of zones from the configuration, skipping
520 	 * any we have already printed.
521 	 */
522 	cookie = setzoneent();
523 	while ((name = getzoneent(cookie)) != NULL) {
524 		for (i = 0; i < nzents; i++) {
525 			if (strcmp(zents[i].zname, name) == 0)
526 				break;
527 		}
528 		if (i < nzents) {
529 			free(name);
530 			continue;
531 		}
532 		if (lookup_zone_info(name, ZONE_ID_UNDEFINED, &zent) != Z_OK) {
533 			free(name);
534 			continue;
535 		}
536 		free(name);
537 		if (zent.zstate_num >= min_state)
538 			zone_print(&zent, verbose, parsable);
539 	}
540 	endzoneent(cookie);
541 	return (Z_OK);
542 }
543 
544 static zone_entry_t *
545 lookup_running_zone(char *str)
546 {
547 	zoneid_t zoneid;
548 	char *cp;
549 	int i;
550 
551 	if (fetch_zents() != Z_OK)
552 		return (NULL);
553 
554 	for (i = 0; i < nzents; i++) {
555 		if (strcmp(str, zents[i].zname) == 0)
556 			return (&zents[i]);
557 	}
558 	errno = 0;
559 	zoneid = strtol(str, &cp, 0);
560 	if (zoneid < MIN_ZONEID || zoneid > MAX_ZONEID ||
561 	    errno != 0 || *cp != '\0')
562 		return (NULL);
563 	for (i = 0; i < nzents; i++) {
564 		if (zoneid == zents[i].zid)
565 			return (&zents[i]);
566 	}
567 	return (NULL);
568 }
569 
570 /*
571  * Check a bit in a mode_t: if on is B_TRUE, that bit should be on; if
572  * B_FALSE, it should be off.  Return B_TRUE if the mode is bad (incorrect).
573  */
574 static boolean_t
575 bad_mode_bit(mode_t mode, mode_t bit, boolean_t on, char *file)
576 {
577 	char *str;
578 
579 	assert(bit == S_IRUSR || bit == S_IWUSR || bit == S_IXUSR ||
580 	    bit == S_IRGRP || bit == S_IWGRP || bit == S_IXGRP ||
581 	    bit == S_IROTH || bit == S_IWOTH || bit == S_IXOTH);
582 	/*
583 	 * TRANSLATION_NOTE
584 	 * The strings below will be used as part of a larger message,
585 	 * either:
586 	 * (file name) must be (owner|group|world) (read|writ|execut)able
587 	 * or
588 	 * (file name) must not be (owner|group|world) (read|writ|execut)able
589 	 */
590 	switch (bit) {
591 	case S_IRUSR:
592 		str = gettext("owner readable");
593 		break;
594 	case S_IWUSR:
595 		str = gettext("owner writable");
596 		break;
597 	case S_IXUSR:
598 		str = gettext("owner executable");
599 		break;
600 	case S_IRGRP:
601 		str = gettext("group readable");
602 		break;
603 	case S_IWGRP:
604 		str = gettext("group writable");
605 		break;
606 	case S_IXGRP:
607 		str = gettext("group executable");
608 		break;
609 	case S_IROTH:
610 		str = gettext("world readable");
611 		break;
612 	case S_IWOTH:
613 		str = gettext("world writable");
614 		break;
615 	case S_IXOTH:
616 		str = gettext("world executable");
617 		break;
618 	}
619 	if ((mode & bit) == (on ? 0 : bit)) {
620 		/*
621 		 * TRANSLATION_NOTE
622 		 * The first parameter below is a file name; the second
623 		 * is one of the "(owner|group|world) (read|writ|execut)able"
624 		 * strings from above.
625 		 */
626 		/*
627 		 * The code below could be simplified but not in a way
628 		 * that would easily translate to non-English locales.
629 		 */
630 		if (on) {
631 			(void) fprintf(stderr, gettext("%s must be %s.\n"),
632 			    file, str);
633 		} else {
634 			(void) fprintf(stderr, gettext("%s must not be %s.\n"),
635 			    file, str);
636 		}
637 		return (B_TRUE);
638 	}
639 	return (B_FALSE);
640 }
641 
642 /*
643  * We want to make sure that no zone has its zone path as a child node
644  * (in the directory sense) of any other.  We do that by comparing this
645  * zone's path to the path of all other (non-global) zones.  The comparison
646  * in each case is simple: add '/' to the end of the path, then do a
647  * strncmp() of the two paths, using the length of the shorter one.
648  */
649 
650 static int
651 crosscheck_zonepaths(char *path)
652 {
653 	char rpath[MAXPATHLEN];		/* resolved path */
654 	char path_copy[MAXPATHLEN];	/* copy of original path */
655 	char rpath_copy[MAXPATHLEN];	/* copy of original rpath */
656 	struct zoneent *ze;
657 	int res, err;
658 	FILE *cookie;
659 
660 	cookie = setzoneent();
661 	while ((ze = getzoneent_private(cookie)) != NULL) {
662 		/* Skip zones which are not installed. */
663 		if (ze->zone_state < ZONE_STATE_INSTALLED) {
664 			free(ze);
665 			continue;
666 		}
667 		/* Skip the global zone and the current target zone. */
668 		if (strcmp(ze->zone_name, GLOBAL_ZONENAME) == 0 ||
669 		    strcmp(ze->zone_name, target_zone) == 0) {
670 			free(ze);
671 			continue;
672 		}
673 		if (strlen(ze->zone_path) == 0) {
674 			/* old index file without path, fall back */
675 			if ((err = zone_get_zonepath(ze->zone_name,
676 			    ze->zone_path, sizeof (ze->zone_path))) != Z_OK) {
677 				errno = err;
678 				zperror2(ze->zone_name,
679 				    gettext("could not get zone path"));
680 				free(ze);
681 				continue;
682 			}
683 		}
684 		(void) snprintf(path_copy, sizeof (path_copy), "%s%s",
685 		    zonecfg_get_root(), ze->zone_path);
686 		res = resolvepath(path_copy, rpath, sizeof (rpath));
687 		if (res == -1) {
688 			if (errno != ENOENT) {
689 				zperror(path_copy, B_FALSE);
690 				free(ze);
691 				return (Z_ERR);
692 			}
693 			(void) printf(gettext("WARNING: zone %s is installed, "
694 			    "but its %s %s does not exist.\n"), ze->zone_name,
695 			    "zonepath", path_copy);
696 			free(ze);
697 			continue;
698 		}
699 		rpath[res] = '\0';
700 		(void) snprintf(path_copy, sizeof (path_copy), "%s/", path);
701 		(void) snprintf(rpath_copy, sizeof (rpath_copy), "%s/", rpath);
702 		if (strncmp(path_copy, rpath_copy,
703 		    min(strlen(path_copy), strlen(rpath_copy))) == 0) {
704 			/*
705 			 * TRANSLATION_NOTE
706 			 * zonepath is a literal that should not be translated.
707 			 */
708 			(void) fprintf(stderr, gettext("%s zonepath (%s) and "
709 			    "%s zonepath (%s) overlap.\n"),
710 			    target_zone, path, ze->zone_name, rpath);
711 			free(ze);
712 			return (Z_ERR);
713 		}
714 		free(ze);
715 	}
716 	endzoneent(cookie);
717 	return (Z_OK);
718 }
719 
720 static int
721 validate_zonepath(char *path, int cmd_num)
722 {
723 	int res;			/* result of last library/system call */
724 	boolean_t err = B_FALSE;	/* have we run into an error? */
725 	struct stat stbuf;
726 	struct statvfs vfsbuf;
727 	char rpath[MAXPATHLEN];		/* resolved path */
728 	char ppath[MAXPATHLEN];		/* parent path */
729 	char rppath[MAXPATHLEN];	/* resolved parent path */
730 	char rootpath[MAXPATHLEN];	/* root path */
731 	zone_state_t state;
732 
733 	if (path[0] != '/') {
734 		(void) fprintf(stderr,
735 		    gettext("%s is not an absolute path.\n"), path);
736 		return (Z_ERR);
737 	}
738 	if ((res = resolvepath(path, rpath, sizeof (rpath))) == -1) {
739 		if ((errno != ENOENT) ||
740 		    (cmd_num != CMD_VERIFY && cmd_num != CMD_INSTALL)) {
741 			zperror(path, B_FALSE);
742 			return (Z_ERR);
743 		}
744 		if (cmd_num == CMD_VERIFY) {
745 			/*
746 			 * TRANSLATION_NOTE
747 			 * zoneadm is a literal that should not be translated.
748 			 */
749 			(void) fprintf(stderr, gettext("WARNING: %s does not "
750 			    "exist, so it could not be verified.\nWhen "
751 			    "'zoneadm %s' is run, '%s' will try to create\n%s, "
752 			    "and '%s' will be tried again,\nbut the '%s' may "
753 			    "fail if:\nthe parent directory of %s is group- or "
754 			    "other-writable\nor\n%s overlaps with any other "
755 			    "installed zones.\n"), path,
756 			    cmd_to_str(CMD_INSTALL), cmd_to_str(CMD_INSTALL),
757 			    path, cmd_to_str(CMD_VERIFY),
758 			    cmd_to_str(CMD_VERIFY), path, path);
759 			return (Z_OK);
760 		}
761 		/*
762 		 * The zonepath is supposed to be mode 700 but its
763 		 * parent(s) 755.  So use 755 on the mkdirp() then
764 		 * chmod() the zonepath itself to 700.
765 		 */
766 		if (mkdirp(path, DEFAULT_DIR_MODE) < 0) {
767 			zperror(path, B_FALSE);
768 			return (Z_ERR);
769 		}
770 		/*
771 		 * If the chmod() fails, report the error, but might
772 		 * as well continue the verify procedure.
773 		 */
774 		if (chmod(path, S_IRWXU) != 0)
775 			zperror(path, B_FALSE);
776 		/*
777 		 * Since the mkdir() succeeded, we should not have to
778 		 * worry about a subsequent ENOENT, thus this should
779 		 * only recurse once.
780 		 */
781 		return (validate_zonepath(path, CMD_INSTALL));
782 	}
783 	rpath[res] = '\0';
784 	if (strcmp(path, rpath) != 0) {
785 		errno = Z_RESOLVED_PATH;
786 		zperror(path, B_TRUE);
787 		return (Z_ERR);
788 	}
789 	if ((res = stat(rpath, &stbuf)) != 0) {
790 		zperror(rpath, B_FALSE);
791 		return (Z_ERR);
792 	}
793 	if (!S_ISDIR(stbuf.st_mode)) {
794 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
795 		    rpath);
796 		return (Z_ERR);
797 	}
798 	if ((strcmp(stbuf.st_fstype, MNTTYPE_TMPFS) == 0) ||
799 	    (strcmp(stbuf.st_fstype, MNTTYPE_XMEMFS) == 0)) {
800 		(void) printf(gettext("WARNING: %s is on a temporary "
801 		    "file-system.\n"), rpath);
802 	}
803 	if (crosscheck_zonepaths(rpath) != Z_OK)
804 		return (Z_ERR);
805 	/*
806 	 * Try to collect and report as many minor errors as possible
807 	 * before returning, so the user can learn everything that needs
808 	 * to be fixed up front.
809 	 */
810 	if (stbuf.st_uid != 0) {
811 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
812 		    rpath);
813 		err = B_TRUE;
814 	}
815 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rpath);
816 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rpath);
817 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rpath);
818 	err |= bad_mode_bit(stbuf.st_mode, S_IRGRP, B_FALSE, rpath);
819 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rpath);
820 	err |= bad_mode_bit(stbuf.st_mode, S_IXGRP, B_FALSE, rpath);
821 	err |= bad_mode_bit(stbuf.st_mode, S_IROTH, B_FALSE, rpath);
822 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rpath);
823 	err |= bad_mode_bit(stbuf.st_mode, S_IXOTH, B_FALSE, rpath);
824 
825 	(void) snprintf(ppath, sizeof (ppath), "%s/..", path);
826 	if ((res = resolvepath(ppath, rppath, sizeof (rppath))) == -1) {
827 		zperror(ppath, B_FALSE);
828 		return (Z_ERR);
829 	}
830 	rppath[res] = '\0';
831 	if ((res = stat(rppath, &stbuf)) != 0) {
832 		zperror(rppath, B_FALSE);
833 		return (Z_ERR);
834 	}
835 	/* theoretically impossible */
836 	if (!S_ISDIR(stbuf.st_mode)) {
837 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
838 		    rppath);
839 		return (Z_ERR);
840 	}
841 	if (stbuf.st_uid != 0) {
842 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
843 		    rppath);
844 		err = B_TRUE;
845 	}
846 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rppath);
847 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rppath);
848 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rppath);
849 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rppath);
850 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rppath);
851 	if (strcmp(rpath, rppath) == 0) {
852 		(void) fprintf(stderr, gettext("%s is its own parent.\n"),
853 		    rppath);
854 		err = B_TRUE;
855 	}
856 
857 	if (statvfs(rpath, &vfsbuf) != 0) {
858 		zperror(rpath, B_FALSE);
859 		return (Z_ERR);
860 	}
861 	if (strcmp(vfsbuf.f_basetype, MNTTYPE_NFS) == 0) {
862 		/*
863 		 * TRANSLATION_NOTE
864 		 * Zonepath and NFS are literals that should not be translated.
865 		 */
866 		(void) fprintf(stderr, gettext("Zonepath %s is on an NFS "
867 		    "mounted file-system.\n"
868 		    "\tA local file-system must be used.\n"), rpath);
869 		return (Z_ERR);
870 	}
871 	if (vfsbuf.f_flag & ST_NOSUID) {
872 		/*
873 		 * TRANSLATION_NOTE
874 		 * Zonepath and nosuid are literals that should not be
875 		 * translated.
876 		 */
877 		(void) fprintf(stderr, gettext("Zonepath %s is on a nosuid "
878 		    "file-system.\n"), rpath);
879 		return (Z_ERR);
880 	}
881 
882 	if ((res = zone_get_state(target_zone, &state)) != Z_OK) {
883 		errno = res;
884 		zperror2(target_zone, gettext("could not get state"));
885 		return (Z_ERR);
886 	}
887 	/*
888 	 * The existence of the root path is only bad in the configured state,
889 	 * as it is *supposed* to be there at the installed and later states.
890 	 * State/command mismatches are caught earlier in verify_details().
891 	 */
892 	if (state == ZONE_STATE_CONFIGURED) {
893 		if (snprintf(rootpath, sizeof (rootpath), "%s/root", rpath) >=
894 		    sizeof (rootpath)) {
895 			/*
896 			 * TRANSLATION_NOTE
897 			 * Zonepath is a literal that should not be translated.
898 			 */
899 			(void) fprintf(stderr,
900 			    gettext("Zonepath %s is too long.\n"), rpath);
901 			return (Z_ERR);
902 		}
903 		if ((res = stat(rootpath, &stbuf)) == 0) {
904 			(void) fprintf(stderr, gettext("Rootpath %s exists; "
905 			    "remove or move aside prior to %s.\n"), rootpath,
906 			    cmd_to_str(CMD_INSTALL));
907 			return (Z_ERR);
908 		}
909 	}
910 
911 	return (err ? Z_ERR : Z_OK);
912 }
913 
914 static void
915 release_lock_file(int lockfd)
916 {
917 	(void) close(lockfd);
918 }
919 
920 static int
921 grab_lock_file(const char *zone_name, int *lockfd)
922 {
923 	char pathbuf[PATH_MAX];
924 	struct flock flock;
925 
926 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s", zonecfg_get_root(),
927 	    ZONES_TMPDIR) >= sizeof (pathbuf)) {
928 		zerror(gettext("alternate root path is too long"));
929 		return (Z_ERR);
930 	}
931 	if (mkdir(pathbuf, S_IRWXU) < 0 && errno != EEXIST) {
932 		zerror(gettext("could not mkdir %s: %s"), pathbuf,
933 		    strerror(errno));
934 		return (Z_ERR);
935 	}
936 	(void) chmod(pathbuf, S_IRWXU);
937 
938 	/*
939 	 * One of these lock files is created for each zone (when needed).
940 	 * The lock files are not cleaned up (except on system reboot),
941 	 * but since there is only one per zone, there is no resource
942 	 * starvation issue.
943 	 */
944 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s/%s.zoneadm.lock",
945 	    zonecfg_get_root(), ZONES_TMPDIR, zone_name) >= sizeof (pathbuf)) {
946 		zerror(gettext("alternate root path is too long"));
947 		return (Z_ERR);
948 	}
949 	if ((*lockfd = open(pathbuf, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
950 		zerror(gettext("could not open %s: %s"), pathbuf,
951 		    strerror(errno));
952 		return (Z_ERR);
953 	}
954 	/*
955 	 * Lock the file to synchronize with other zoneadmds
956 	 */
957 	flock.l_type = F_WRLCK;
958 	flock.l_whence = SEEK_SET;
959 	flock.l_start = (off_t)0;
960 	flock.l_len = (off_t)0;
961 	if (fcntl(*lockfd, F_SETLKW, &flock) < 0) {
962 		zerror(gettext("unable to lock %s: %s"), pathbuf,
963 		    strerror(errno));
964 		release_lock_file(*lockfd);
965 		return (Z_ERR);
966 	}
967 	return (Z_OK);
968 }
969 
970 static boolean_t
971 get_doorname(const char *zone_name, char *buffer)
972 {
973 	return (snprintf(buffer, PATH_MAX, "%s" ZONE_DOOR_PATH,
974 	    zonecfg_get_root(), zone_name) < PATH_MAX);
975 }
976 
977 /*
978  * system daemons are not audited.  For the global zone, this occurs
979  * "naturally" since init is started with the default audit
980  * characteristics.  Since zoneadmd is a system daemon and it starts
981  * init for a zone, it is necessary to clear out the audit
982  * characteristics inherited from whomever started zoneadmd.  This is
983  * indicated by the audit id, which is set from the ruid parameter of
984  * adt_set_user(), below.
985  */
986 
987 static void
988 prepare_audit_context()
989 {
990 	adt_session_data_t	*ah;
991 	char			*failure = gettext("audit failure: %s");
992 
993 	if (adt_start_session(&ah, NULL, 0)) {
994 		zerror(failure, strerror(errno));
995 		return;
996 	}
997 	if (adt_set_user(ah, ADT_NO_AUDIT, ADT_NO_AUDIT,
998 	    ADT_NO_AUDIT, ADT_NO_AUDIT, NULL, ADT_NEW)) {
999 		zerror(failure, strerror(errno));
1000 		(void) adt_end_session(ah);
1001 		return;
1002 	}
1003 	if (adt_set_proc(ah))
1004 		zerror(failure, strerror(errno));
1005 
1006 	(void) adt_end_session(ah);
1007 }
1008 
1009 static int
1010 start_zoneadmd(const char *zone_name)
1011 {
1012 	char doorpath[PATH_MAX];
1013 	pid_t child_pid;
1014 	int error = Z_ERR;
1015 	int doorfd, lockfd;
1016 	struct door_info info;
1017 
1018 	if (!get_doorname(zone_name, doorpath))
1019 		return (Z_ERR);
1020 
1021 	if (grab_lock_file(zone_name, &lockfd) != Z_OK)
1022 		return (Z_ERR);
1023 
1024 	/*
1025 	 * Now that we have the lock, re-confirm that the daemon is
1026 	 * *not* up and working fine.  If it is still down, we have a green
1027 	 * light to start it.
1028 	 */
1029 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1030 		if (errno != ENOENT) {
1031 			zperror(doorpath, B_FALSE);
1032 			goto out;
1033 		}
1034 	} else {
1035 		if (door_info(doorfd, &info) == 0 &&
1036 		    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1037 			error = Z_OK;
1038 			(void) close(doorfd);
1039 			goto out;
1040 		}
1041 		(void) close(doorfd);
1042 	}
1043 
1044 	if ((child_pid = fork()) == -1) {
1045 		zperror(gettext("could not fork"), B_FALSE);
1046 		goto out;
1047 	} else if (child_pid == 0) {
1048 		const char *argv[6], **ap;
1049 
1050 		/* child process */
1051 		prepare_audit_context();
1052 
1053 		ap = argv;
1054 		*ap++ = "zoneadmd";
1055 		*ap++ = "-z";
1056 		*ap++ = zone_name;
1057 		if (zonecfg_in_alt_root()) {
1058 			*ap++ = "-R";
1059 			*ap++ = zonecfg_get_root();
1060 		}
1061 		*ap = NULL;
1062 
1063 		(void) execv("/usr/lib/zones/zoneadmd", (char * const *)argv);
1064 		/*
1065 		 * TRANSLATION_NOTE
1066 		 * zoneadmd is a literal that should not be translated.
1067 		 */
1068 		zperror(gettext("could not exec zoneadmd"), B_FALSE);
1069 		_exit(Z_ERR);
1070 	} else {
1071 		/* parent process */
1072 		pid_t retval;
1073 		int pstatus = 0;
1074 
1075 		do {
1076 			retval = waitpid(child_pid, &pstatus, 0);
1077 		} while (retval != child_pid);
1078 		if (WIFSIGNALED(pstatus) || (WIFEXITED(pstatus) &&
1079 		    WEXITSTATUS(pstatus) != 0)) {
1080 			zerror(gettext("could not start %s"), "zoneadmd");
1081 			goto out;
1082 		}
1083 	}
1084 	error = Z_OK;
1085 out:
1086 	release_lock_file(lockfd);
1087 	return (error);
1088 }
1089 
1090 static int
1091 ping_zoneadmd(const char *zone_name)
1092 {
1093 	char doorpath[PATH_MAX];
1094 	int doorfd;
1095 	struct door_info info;
1096 
1097 	if (!get_doorname(zone_name, doorpath))
1098 		return (Z_ERR);
1099 
1100 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1101 		return (Z_ERR);
1102 	}
1103 	if (door_info(doorfd, &info) == 0 &&
1104 	    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1105 		(void) close(doorfd);
1106 		return (Z_OK);
1107 	}
1108 	(void) close(doorfd);
1109 	return (Z_ERR);
1110 }
1111 
1112 static int
1113 call_zoneadmd(const char *zone_name, zone_cmd_arg_t *arg)
1114 {
1115 	char doorpath[PATH_MAX];
1116 	int doorfd, result;
1117 	door_arg_t darg;
1118 
1119 	zoneid_t zoneid;
1120 	uint64_t uniqid = 0;
1121 
1122 	zone_cmd_rval_t *rvalp;
1123 	size_t rlen;
1124 	char *cp, *errbuf;
1125 
1126 	rlen = getpagesize();
1127 	if ((rvalp = malloc(rlen)) == NULL) {
1128 		zerror(gettext("failed to allocate %lu bytes: %s"), rlen,
1129 		    strerror(errno));
1130 		return (-1);
1131 	}
1132 
1133 	if ((zoneid = getzoneidbyname(zone_name)) != ZONE_ID_UNDEFINED) {
1134 		(void) zone_getattr(zoneid, ZONE_ATTR_UNIQID, &uniqid,
1135 		    sizeof (uniqid));
1136 	}
1137 	arg->uniqid = uniqid;
1138 	(void) strlcpy(arg->locale, locale, sizeof (arg->locale));
1139 	if (!get_doorname(zone_name, doorpath)) {
1140 		zerror(gettext("alternate root path is too long"));
1141 		free(rvalp);
1142 		return (-1);
1143 	}
1144 
1145 	/*
1146 	 * Loop trying to start zoneadmd; if something goes seriously
1147 	 * wrong we break out and fail.
1148 	 */
1149 	for (;;) {
1150 		if (start_zoneadmd(zone_name) != Z_OK)
1151 			break;
1152 
1153 		if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1154 			zperror(gettext("failed to open zone door"), B_FALSE);
1155 			break;
1156 		}
1157 
1158 		darg.data_ptr = (char *)arg;
1159 		darg.data_size = sizeof (*arg);
1160 		darg.desc_ptr = NULL;
1161 		darg.desc_num = 0;
1162 		darg.rbuf = (char *)rvalp;
1163 		darg.rsize = rlen;
1164 		if (door_call(doorfd, &darg) != 0) {
1165 			(void) close(doorfd);
1166 			/*
1167 			 * We'll get EBADF if the door has been revoked.
1168 			 */
1169 			if (errno != EBADF) {
1170 				zperror(gettext("door_call failed"), B_FALSE);
1171 				break;
1172 			}
1173 			continue;	/* take another lap */
1174 		}
1175 		(void) close(doorfd);
1176 
1177 		if (darg.data_size == 0) {
1178 			/* Door server is going away; kick it again. */
1179 			continue;
1180 		}
1181 
1182 		errbuf = rvalp->errbuf;
1183 		while (*errbuf != '\0') {
1184 			/*
1185 			 * Remove any newlines since zerror()
1186 			 * will append one automatically.
1187 			 */
1188 			cp = strchr(errbuf, '\n');
1189 			if (cp != NULL)
1190 				*cp = '\0';
1191 			zerror("%s", errbuf);
1192 			if (cp == NULL)
1193 				break;
1194 			errbuf = cp + 1;
1195 		}
1196 		result = rvalp->rval == 0 ? 0 : -1;
1197 		free(rvalp);
1198 		return (result);
1199 	}
1200 
1201 	free(rvalp);
1202 	return (-1);
1203 }
1204 
1205 static int
1206 ready_func(int argc, char *argv[])
1207 {
1208 	zone_cmd_arg_t zarg;
1209 	int arg;
1210 
1211 	if (zonecfg_in_alt_root()) {
1212 		zerror(gettext("cannot ready zone in alternate root"));
1213 		return (Z_ERR);
1214 	}
1215 
1216 	optind = 0;
1217 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1218 		switch (arg) {
1219 		case '?':
1220 			sub_usage(SHELP_READY, CMD_READY);
1221 			return (optopt == '?' ? Z_OK : Z_USAGE);
1222 		default:
1223 			sub_usage(SHELP_READY, CMD_READY);
1224 			return (Z_USAGE);
1225 		}
1226 	}
1227 	if (argc > optind) {
1228 		sub_usage(SHELP_READY, CMD_READY);
1229 		return (Z_USAGE);
1230 	}
1231 	if (sanity_check(target_zone, CMD_READY, B_FALSE, B_FALSE) != Z_OK)
1232 		return (Z_ERR);
1233 	if (verify_details(CMD_READY) != Z_OK)
1234 		return (Z_ERR);
1235 
1236 	zarg.cmd = Z_READY;
1237 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1238 		zerror(gettext("call to %s failed"), "zoneadmd");
1239 		return (Z_ERR);
1240 	}
1241 	return (Z_OK);
1242 }
1243 
1244 static int
1245 boot_func(int argc, char *argv[])
1246 {
1247 	zone_cmd_arg_t zarg;
1248 	int arg;
1249 
1250 	if (zonecfg_in_alt_root()) {
1251 		zerror(gettext("cannot boot zone in alternate root"));
1252 		return (Z_ERR);
1253 	}
1254 
1255 	zarg.bootbuf[0] = '\0';
1256 
1257 	/*
1258 	 * At the current time, the only supported subargument to the
1259 	 * "boot" subcommand is "-s" which specifies a single-user boot.
1260 	 * In the future, other boot arguments should be supported
1261 	 * including "-m" for specifying alternate smf(5) milestones.
1262 	 */
1263 	optind = 0;
1264 	if ((arg = getopt(argc, argv, "?s")) != EOF) {
1265 		switch (arg) {
1266 		case '?':
1267 			sub_usage(SHELP_BOOT, CMD_BOOT);
1268 			return (optopt == '?' ? Z_OK : Z_USAGE);
1269 		case 's':
1270 			(void) strlcpy(zarg.bootbuf, "-s",
1271 			    sizeof (zarg.bootbuf));
1272 			break;
1273 		default:
1274 			sub_usage(SHELP_BOOT, CMD_BOOT);
1275 			return (Z_USAGE);
1276 		}
1277 	}
1278 	if (argc > optind) {
1279 		sub_usage(SHELP_BOOT, CMD_BOOT);
1280 		return (Z_USAGE);
1281 	}
1282 	if (sanity_check(target_zone, CMD_BOOT, B_FALSE, B_FALSE) != Z_OK)
1283 		return (Z_ERR);
1284 	if (verify_details(CMD_BOOT) != Z_OK)
1285 		return (Z_ERR);
1286 	zarg.cmd = Z_BOOT;
1287 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1288 		zerror(gettext("call to %s failed"), "zoneadmd");
1289 		return (Z_ERR);
1290 	}
1291 	return (Z_OK);
1292 }
1293 
1294 static void
1295 fake_up_local_zone(zoneid_t zid, zone_entry_t *zeptr)
1296 {
1297 	ssize_t result;
1298 
1299 	zeptr->zid = zid;
1300 	/*
1301 	 * Since we're looking up our own (non-global) zone name,
1302 	 * we can be assured that it will succeed.
1303 	 */
1304 	result = getzonenamebyid(zid, zeptr->zname, sizeof (zeptr->zname));
1305 	assert(result >= 0);
1306 	(void) strlcpy(zeptr->zroot, "/", sizeof (zeptr->zroot));
1307 	zeptr->zstate_str = "running";
1308 }
1309 
1310 static int
1311 list_func(int argc, char *argv[])
1312 {
1313 	zone_entry_t *zentp, zent;
1314 	int arg, retv;
1315 	boolean_t output = B_FALSE, verbose = B_FALSE, parsable = B_FALSE;
1316 	zone_state_t min_state = ZONE_STATE_RUNNING;
1317 	zoneid_t zone_id = getzoneid();
1318 
1319 	if (target_zone == NULL) {
1320 		/* all zones: default view to running but allow override */
1321 		optind = 0;
1322 		while ((arg = getopt(argc, argv, "?cipv")) != EOF) {
1323 			switch (arg) {
1324 			case '?':
1325 				sub_usage(SHELP_LIST, CMD_LIST);
1326 				return (optopt == '?' ? Z_OK : Z_USAGE);
1327 			case 'c':
1328 				min_state = ZONE_STATE_CONFIGURED;
1329 				break;
1330 			case 'i':
1331 				min_state = ZONE_STATE_INSTALLED;
1332 				break;
1333 			case 'p':
1334 				parsable = B_TRUE;
1335 				break;
1336 			case 'v':
1337 				verbose = B_TRUE;
1338 				break;
1339 			default:
1340 				sub_usage(SHELP_LIST, CMD_LIST);
1341 				return (Z_USAGE);
1342 			}
1343 		}
1344 		if (parsable && verbose) {
1345 			zerror(gettext("%s -p and -v are mutually exclusive."),
1346 			    cmd_to_str(CMD_LIST));
1347 			return (Z_ERR);
1348 		}
1349 		if (zone_id == GLOBAL_ZONEID) {
1350 			retv = zone_print_list(min_state, verbose, parsable);
1351 		} else {
1352 			retv = Z_OK;
1353 			fake_up_local_zone(zone_id, &zent);
1354 			zone_print(&zent, verbose, parsable);
1355 		}
1356 		return (retv);
1357 	}
1358 
1359 	/*
1360 	 * Specific target zone: disallow -i/-c suboptions.
1361 	 */
1362 	optind = 0;
1363 	while ((arg = getopt(argc, argv, "?pv")) != EOF) {
1364 		switch (arg) {
1365 		case '?':
1366 			sub_usage(SHELP_LIST, CMD_LIST);
1367 			return (optopt == '?' ? Z_OK : Z_USAGE);
1368 		case 'p':
1369 			parsable = B_TRUE;
1370 			break;
1371 		case 'v':
1372 			verbose = B_TRUE;
1373 			break;
1374 		default:
1375 			sub_usage(SHELP_LIST, CMD_LIST);
1376 			return (Z_USAGE);
1377 		}
1378 	}
1379 	if (parsable && verbose) {
1380 		zerror(gettext("%s -p and -v are mutually exclusive."),
1381 		    cmd_to_str(CMD_LIST));
1382 		return (Z_ERR);
1383 	}
1384 	if (argc > optind) {
1385 		sub_usage(SHELP_LIST, CMD_LIST);
1386 		return (Z_USAGE);
1387 	}
1388 	if (zone_id != GLOBAL_ZONEID) {
1389 		fake_up_local_zone(zone_id, &zent);
1390 		/*
1391 		 * main() will issue a Z_NO_ZONE error if it cannot get an
1392 		 * id for target_zone, which in a non-global zone should
1393 		 * happen for any zone name except `zonename`.  Thus we
1394 		 * assert() that here but don't otherwise check.
1395 		 */
1396 		assert(strcmp(zent.zname, target_zone) == 0);
1397 		zone_print(&zent, verbose, parsable);
1398 		output = B_TRUE;
1399 	} else if ((zentp = lookup_running_zone(target_zone)) != NULL) {
1400 		zone_print(zentp, verbose, parsable);
1401 		output = B_TRUE;
1402 	} else if (lookup_zone_info(target_zone, ZONE_ID_UNDEFINED,
1403 	    &zent) == Z_OK) {
1404 		zone_print(&zent, verbose, parsable);
1405 		output = B_TRUE;
1406 	}
1407 	return (output ? Z_OK : Z_ERR);
1408 }
1409 
1410 static void
1411 sigterm(int sig)
1412 {
1413 	/*
1414 	 * Ignore SIG{INT,TERM}, so we don't end up in an infinite loop,
1415 	 * then propagate the signal to our process group.
1416 	 */
1417 	(void) sigset(SIGINT, SIG_IGN);
1418 	(void) sigset(SIGTERM, SIG_IGN);
1419 	(void) kill(0, sig);
1420 	child_killed = B_TRUE;
1421 }
1422 
1423 static int
1424 do_subproc(char *cmdbuf)
1425 {
1426 	char inbuf[1024];	/* arbitrary large amount */
1427 	FILE *file;
1428 
1429 	child_killed = B_FALSE;
1430 	/*
1431 	 * We use popen(3c) to launch child processes for [un]install;
1432 	 * this library call does not return a PID, so we have to kill
1433 	 * the whole process group.  To avoid killing our parent, we
1434 	 * become a process group leader here.  But doing so can wreak
1435 	 * havoc with reading from stdin when launched by a non-job-control
1436 	 * shell, so we close stdin and reopen it as /dev/null first.
1437 	 */
1438 	(void) close(STDIN_FILENO);
1439 	(void) open("/dev/null", O_RDONLY);
1440 	(void) setpgid(0, 0);
1441 	(void) sigset(SIGINT, sigterm);
1442 	(void) sigset(SIGTERM, sigterm);
1443 	file = popen(cmdbuf, "r");
1444 	for (;;) {
1445 		if (child_killed || fgets(inbuf, sizeof (inbuf), file) == NULL)
1446 			break;
1447 		(void) fputs(inbuf, stdout);
1448 	}
1449 	(void) sigset(SIGINT, SIG_DFL);
1450 	(void) sigset(SIGTERM, SIG_DFL);
1451 	return (pclose(file));
1452 }
1453 
1454 static int
1455 subproc_status(const char *cmd, int status)
1456 {
1457 	if (WIFEXITED(status)) {
1458 		int exit_code = WEXITSTATUS(status);
1459 
1460 		if (exit_code == 0)
1461 			return (Z_OK);
1462 		zerror(gettext("'%s' failed with exit code %d."), cmd,
1463 		    exit_code);
1464 	} else if (WIFSIGNALED(status)) {
1465 		int signal = WTERMSIG(status);
1466 		char sigstr[SIG2STR_MAX];
1467 
1468 		if (sig2str(signal, sigstr) == 0) {
1469 			zerror(gettext("'%s' terminated by signal SIG%s."), cmd,
1470 			    sigstr);
1471 		} else {
1472 			zerror(gettext("'%s' terminated by an unknown signal."),
1473 			    cmd);
1474 		}
1475 	} else {
1476 		zerror(gettext("'%s' failed for unknown reasons."), cmd);
1477 	}
1478 	return (Z_ERR);
1479 }
1480 
1481 /*
1482  * Various sanity checks; make sure:
1483  * 1. We're in the global zone.
1484  * 2. The calling user has sufficient privilege.
1485  * 3. The target zone is neither the global zone nor anything starting with
1486  *    "SUNW".
1487  * 4a. If we're looking for a 'not running' (i.e., configured or installed)
1488  *     zone, the name service knows about it.
1489  * 4b. For some operations which expect a zone not to be running, that it is
1490  *     not already running (or ready).
1491  */
1492 static int
1493 sanity_check(char *zone, int cmd_num, boolean_t running,
1494     boolean_t unsafe_when_running)
1495 {
1496 	zone_entry_t *zent;
1497 	priv_set_t *privset;
1498 	zone_state_t state;
1499 	char kernzone[ZONENAME_MAX];
1500 	FILE *fp;
1501 
1502 	if (getzoneid() != GLOBAL_ZONEID) {
1503 		zerror(gettext("must be in the global zone to %s a zone."),
1504 		    cmd_to_str(cmd_num));
1505 		return (Z_ERR);
1506 	}
1507 
1508 	if ((privset = priv_allocset()) == NULL) {
1509 		zerror(gettext("%s failed"), "priv_allocset");
1510 		return (Z_ERR);
1511 	}
1512 
1513 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
1514 		zerror(gettext("%s failed"), "getppriv");
1515 		priv_freeset(privset);
1516 		return (Z_ERR);
1517 	}
1518 
1519 	if (priv_isfullset(privset) == B_FALSE) {
1520 		zerror(gettext("only a privileged user may %s a zone."),
1521 		    cmd_to_str(cmd_num));
1522 		priv_freeset(privset);
1523 		return (Z_ERR);
1524 	}
1525 	priv_freeset(privset);
1526 
1527 	if (zone == NULL) {
1528 		zerror(gettext("no zone specified"));
1529 		return (Z_ERR);
1530 	}
1531 
1532 	if (strcmp(zone, GLOBAL_ZONENAME) == 0) {
1533 		zerror(gettext("%s operation is invalid for the global zone."),
1534 		    cmd_to_str(cmd_num));
1535 		return (Z_ERR);
1536 	}
1537 
1538 	if (strncmp(zone, "SUNW", 4) == 0) {
1539 		zerror(gettext("%s operation is invalid for zones starting "
1540 		    "with SUNW."), cmd_to_str(cmd_num));
1541 		return (Z_ERR);
1542 	}
1543 
1544 	if (!zonecfg_in_alt_root()) {
1545 		zent = lookup_running_zone(zone);
1546 	} else if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
1547 		zent = NULL;
1548 	} else {
1549 		if (zonecfg_find_scratch(fp, zone, zonecfg_get_root(),
1550 		    kernzone, sizeof (kernzone)) == 0)
1551 			zent = lookup_running_zone(kernzone);
1552 		else
1553 			zent = NULL;
1554 		zonecfg_close_scratch(fp);
1555 	}
1556 
1557 	/*
1558 	 * Look up from the kernel for 'running' zones.
1559 	 */
1560 	if (running) {
1561 		if (zent == NULL) {
1562 			zerror(gettext("not running"));
1563 			return (Z_ERR);
1564 		}
1565 	} else {
1566 		int err;
1567 
1568 		if (unsafe_when_running && zent != NULL) {
1569 			/* check whether the zone is ready or running */
1570 			if ((err = zone_get_state(zent->zname,
1571 			    &zent->zstate_num)) != Z_OK) {
1572 				errno = err;
1573 				zperror2(zent->zname,
1574 				    gettext("could not get state"));
1575 				/* can't tell, so hedge */
1576 				zent->zstate_str = "ready/running";
1577 			} else {
1578 				zent->zstate_str =
1579 				    zone_state_str(zent->zstate_num);
1580 			}
1581 			zerror(gettext("%s operation is invalid for %s zones."),
1582 			    cmd_to_str(cmd_num), zent->zstate_str);
1583 			return (Z_ERR);
1584 		}
1585 		if ((err = zone_get_state(zone, &state)) != Z_OK) {
1586 			errno = err;
1587 			zperror2(zone, gettext("could not get state"));
1588 			return (Z_ERR);
1589 		}
1590 		switch (cmd_num) {
1591 		case CMD_UNINSTALL:
1592 			if (state == ZONE_STATE_CONFIGURED) {
1593 				zerror(gettext("is already in state '%s'."),
1594 				    zone_state_str(ZONE_STATE_CONFIGURED));
1595 				return (Z_ERR);
1596 			}
1597 			break;
1598 		case CMD_INSTALL:
1599 			if (state == ZONE_STATE_INSTALLED) {
1600 				zerror(gettext("is already %s."),
1601 				    zone_state_str(ZONE_STATE_INSTALLED));
1602 				return (Z_ERR);
1603 			} else if (state == ZONE_STATE_INCOMPLETE) {
1604 				zerror(gettext("zone is %s; %s required."),
1605 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1606 				    cmd_to_str(CMD_UNINSTALL));
1607 				return (Z_ERR);
1608 			}
1609 			break;
1610 		case CMD_READY:
1611 		case CMD_BOOT:
1612 		case CMD_MOUNT:
1613 			if (state < ZONE_STATE_INSTALLED) {
1614 				zerror(gettext("must be %s before %s."),
1615 				    zone_state_str(ZONE_STATE_INSTALLED),
1616 				    cmd_to_str(cmd_num));
1617 				return (Z_ERR);
1618 			}
1619 			break;
1620 		case CMD_VERIFY:
1621 			if (state == ZONE_STATE_INCOMPLETE) {
1622 				zerror(gettext("zone is %s; %s required."),
1623 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1624 				    cmd_to_str(CMD_UNINSTALL));
1625 				return (Z_ERR);
1626 			}
1627 			break;
1628 		case CMD_UNMOUNT:
1629 			if (state != ZONE_STATE_MOUNTED) {
1630 				zerror(gettext("must be %s before %s."),
1631 				    zone_state_str(ZONE_STATE_MOUNTED),
1632 				    cmd_to_str(cmd_num));
1633 				return (Z_ERR);
1634 			}
1635 			break;
1636 		}
1637 	}
1638 	return (Z_OK);
1639 }
1640 
1641 static int
1642 halt_func(int argc, char *argv[])
1643 {
1644 	zone_cmd_arg_t zarg;
1645 	int arg;
1646 
1647 	if (zonecfg_in_alt_root()) {
1648 		zerror(gettext("cannot halt zone in alternate root"));
1649 		return (Z_ERR);
1650 	}
1651 
1652 	optind = 0;
1653 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1654 		switch (arg) {
1655 		case '?':
1656 			sub_usage(SHELP_HALT, CMD_HALT);
1657 			return (optopt == '?' ? Z_OK : Z_USAGE);
1658 		default:
1659 			sub_usage(SHELP_HALT, CMD_HALT);
1660 			return (Z_USAGE);
1661 		}
1662 	}
1663 	if (argc > optind) {
1664 		sub_usage(SHELP_HALT, CMD_HALT);
1665 		return (Z_USAGE);
1666 	}
1667 	/*
1668 	 * zoneadmd should be the one to decide whether or not to proceed,
1669 	 * so even though it seems that the fourth parameter below should
1670 	 * perhaps be B_TRUE, it really shouldn't be.
1671 	 */
1672 	if (sanity_check(target_zone, CMD_HALT, B_FALSE, B_FALSE) != Z_OK)
1673 		return (Z_ERR);
1674 
1675 	zarg.cmd = Z_HALT;
1676 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
1677 }
1678 
1679 static int
1680 reboot_func(int argc, char *argv[])
1681 {
1682 	zone_cmd_arg_t zarg;
1683 	int arg;
1684 
1685 	if (zonecfg_in_alt_root()) {
1686 		zerror(gettext("cannot reboot zone in alternate root"));
1687 		return (Z_ERR);
1688 	}
1689 
1690 	optind = 0;
1691 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1692 		switch (arg) {
1693 		case '?':
1694 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
1695 			return (optopt == '?' ? Z_OK : Z_USAGE);
1696 		default:
1697 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
1698 			return (Z_USAGE);
1699 		}
1700 	}
1701 	if (argc > 0) {
1702 		sub_usage(SHELP_REBOOT, CMD_REBOOT);
1703 		return (Z_USAGE);
1704 	}
1705 	/*
1706 	 * zoneadmd should be the one to decide whether or not to proceed,
1707 	 * so even though it seems that the fourth parameter below should
1708 	 * perhaps be B_TRUE, it really shouldn't be.
1709 	 */
1710 	if (sanity_check(target_zone, CMD_REBOOT, B_TRUE, B_FALSE) != Z_OK)
1711 		return (Z_ERR);
1712 	if (verify_details(CMD_REBOOT) != Z_OK)
1713 		return (Z_ERR);
1714 
1715 	zarg.cmd = Z_REBOOT;
1716 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
1717 }
1718 
1719 static int
1720 verify_rctls(zone_dochandle_t handle)
1721 {
1722 	struct zone_rctltab rctltab;
1723 	size_t rbs = rctlblk_size();
1724 	rctlblk_t *rctlblk;
1725 	int error = Z_INVAL;
1726 
1727 	if ((rctlblk = malloc(rbs)) == NULL) {
1728 		zerror(gettext("failed to allocate %lu bytes: %s"), rbs,
1729 		    strerror(errno));
1730 		return (Z_NOMEM);
1731 	}
1732 
1733 	if (zonecfg_setrctlent(handle) != Z_OK) {
1734 		zerror(gettext("zonecfg_setrctlent failed"));
1735 		free(rctlblk);
1736 		return (error);
1737 	}
1738 
1739 	rctltab.zone_rctl_valptr = NULL;
1740 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
1741 		struct zone_rctlvaltab *rctlval;
1742 		const char *name = rctltab.zone_rctl_name;
1743 
1744 		if (!zonecfg_is_rctl(name)) {
1745 			zerror(gettext("WARNING: Ignoring unrecognized rctl "
1746 			    "'%s'."),  name);
1747 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1748 			rctltab.zone_rctl_valptr = NULL;
1749 			continue;
1750 		}
1751 
1752 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
1753 		    rctlval = rctlval->zone_rctlval_next) {
1754 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
1755 			    != Z_OK) {
1756 				zerror(gettext("invalid rctl value: "
1757 				    "(priv=%s,limit=%s,action%s)"),
1758 				    rctlval->zone_rctlval_priv,
1759 				    rctlval->zone_rctlval_limit,
1760 				    rctlval->zone_rctlval_action);
1761 				goto out;
1762 			}
1763 			if (!zonecfg_valid_rctl(name, rctlblk)) {
1764 				zerror(gettext("(priv=%s,limit=%s,action=%s) "
1765 				    "is not a valid value for rctl '%s'"),
1766 				    rctlval->zone_rctlval_priv,
1767 				    rctlval->zone_rctlval_limit,
1768 				    rctlval->zone_rctlval_action,
1769 				    name);
1770 				goto out;
1771 			}
1772 		}
1773 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1774 	}
1775 	rctltab.zone_rctl_valptr = NULL;
1776 	error = Z_OK;
1777 out:
1778 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1779 	(void) zonecfg_endrctlent(handle);
1780 	free(rctlblk);
1781 	return (error);
1782 }
1783 
1784 static int
1785 verify_pool(zone_dochandle_t handle)
1786 {
1787 	char poolname[MAXPATHLEN];
1788 	pool_conf_t *poolconf;
1789 	pool_t *pool;
1790 	int status;
1791 	int error;
1792 
1793 	/*
1794 	 * This ends up being very similar to the check done in zoneadmd.
1795 	 */
1796 	error = zonecfg_get_pool(handle, poolname, sizeof (poolname));
1797 	if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
1798 		/*
1799 		 * No pool specified.
1800 		 */
1801 		return (0);
1802 	}
1803 	if (error != Z_OK) {
1804 		zperror(gettext("Unable to retrieve pool name from "
1805 		    "configuration"), B_TRUE);
1806 		return (error);
1807 	}
1808 	/*
1809 	 * Don't do anything if pools aren't enabled.
1810 	 */
1811 	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
1812 		zerror(gettext("WARNING: pools facility not active; "
1813 		    "zone will not be bound to pool '%s'."), poolname);
1814 		return (Z_OK);
1815 	}
1816 	/*
1817 	 * Try to provide a sane error message if the requested pool doesn't
1818 	 * exist.  It isn't clear that pools-related failures should
1819 	 * necessarily translate to a failure to verify the zone configuration,
1820 	 * hence they are not considered errors.
1821 	 */
1822 	if ((poolconf = pool_conf_alloc()) == NULL) {
1823 		zerror(gettext("WARNING: pool_conf_alloc failed; "
1824 		    "using default pool"));
1825 		return (Z_OK);
1826 	}
1827 	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
1828 	    PO_SUCCESS) {
1829 		zerror(gettext("WARNING: pool_conf_open failed; "
1830 		    "using default pool"));
1831 		pool_conf_free(poolconf);
1832 		return (Z_OK);
1833 	}
1834 	pool = pool_get_pool(poolconf, poolname);
1835 	(void) pool_conf_close(poolconf);
1836 	pool_conf_free(poolconf);
1837 	if (pool == NULL) {
1838 		zerror(gettext("WARNING: pool '%s' not found. "
1839 		    "using default pool"), poolname);
1840 	}
1841 
1842 	return (Z_OK);
1843 }
1844 
1845 static int
1846 verify_ipd(zone_dochandle_t handle)
1847 {
1848 	int return_code = Z_OK;
1849 	struct zone_fstab fstab;
1850 	struct stat st;
1851 	char specdir[MAXPATHLEN];
1852 
1853 	if (zonecfg_setipdent(handle) != Z_OK) {
1854 		/*
1855 		 * TRANSLATION_NOTE
1856 		 * inherit-pkg-dirs is a literal that should not be translated.
1857 		 */
1858 		(void) fprintf(stderr, gettext("could not verify "
1859 		    "inherit-pkg-dirs: unable to enumerate mounts\n"));
1860 		return (Z_ERR);
1861 	}
1862 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
1863 		/*
1864 		 * Verify fs_dir exists.
1865 		 */
1866 		(void) snprintf(specdir, sizeof (specdir), "%s%s",
1867 		    zonecfg_get_root(), fstab.zone_fs_dir);
1868 		if (stat(specdir, &st) != 0) {
1869 			/*
1870 			 * TRANSLATION_NOTE
1871 			 * inherit-pkg-dir is a literal that should not be
1872 			 * translated.
1873 			 */
1874 			(void) fprintf(stderr, gettext("could not verify "
1875 			    "inherit-pkg-dir %s: %s\n"),
1876 			    fstab.zone_fs_dir, strerror(errno));
1877 			return_code = Z_ERR;
1878 		}
1879 		if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
1880 			/*
1881 			 * TRANSLATION_NOTE
1882 			 * inherit-pkg-dir and NFS are literals that should
1883 			 * not be translated.
1884 			 */
1885 			(void) fprintf(stderr, gettext("cannot verify "
1886 			    "inherit-pkg-dir %s: NFS mounted file-system.\n"
1887 			    "\tA local file-system must be used.\n"),
1888 			    fstab.zone_fs_dir);
1889 			return_code = Z_ERR;
1890 		}
1891 	}
1892 	(void) zonecfg_endipdent(handle);
1893 
1894 	return (return_code);
1895 }
1896 
1897 static int
1898 verify_filesystems(zone_dochandle_t handle)
1899 {
1900 	int return_code = Z_OK;
1901 	struct zone_fstab fstab;
1902 	char cmdbuf[MAXPATHLEN];
1903 	struct stat st;
1904 
1905 	/*
1906 	 * No need to verify inherit-pkg-dir fs types, as their type is
1907 	 * implicitly lofs, which is known.  Therefore, the types are only
1908 	 * verified for regular filesystems below.
1909 	 *
1910 	 * Since the actual mount point is not known until the dependent mounts
1911 	 * are performed, we don't attempt any path validation here: that will
1912 	 * happen later when zoneadmd actually does the mounts.
1913 	 */
1914 	if (zonecfg_setfsent(handle) != Z_OK) {
1915 		(void) fprintf(stderr, gettext("could not verify file-systems: "
1916 		    "unable to enumerate mounts\n"));
1917 		return (Z_ERR);
1918 	}
1919 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1920 		if (!zonecfg_valid_fs_type(fstab.zone_fs_type)) {
1921 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1922 			    "type %s is not allowed.\n"), fstab.zone_fs_dir,
1923 			    fstab.zone_fs_type);
1924 			return_code = Z_ERR;
1925 			goto next_fs;
1926 		}
1927 		/*
1928 		 * Verify /usr/lib/fs/<fstype>/mount exists.
1929 		 */
1930 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount",
1931 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
1932 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1933 			    "type %s is too long.\n"), fstab.zone_fs_dir,
1934 			    fstab.zone_fs_type);
1935 			return_code = Z_ERR;
1936 			goto next_fs;
1937 		}
1938 		if (stat(cmdbuf, &st) != 0) {
1939 			(void) fprintf(stderr, gettext("could not verify fs "
1940 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
1941 			    cmdbuf, strerror(errno));
1942 			return_code = Z_ERR;
1943 			goto next_fs;
1944 		}
1945 		if (!S_ISREG(st.st_mode)) {
1946 			(void) fprintf(stderr, gettext("could not verify fs "
1947 			    "%s: %s is not a regular file\n"),
1948 			    fstab.zone_fs_dir, cmdbuf);
1949 			return_code = Z_ERR;
1950 			goto next_fs;
1951 		}
1952 		/*
1953 		 * Verify /usr/lib/fs/<fstype>/fsck exists iff zone_fs_raw is
1954 		 * set.
1955 		 */
1956 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck",
1957 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
1958 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1959 			    "type %s is too long.\n"), fstab.zone_fs_dir,
1960 			    fstab.zone_fs_type);
1961 			return_code = Z_ERR;
1962 			goto next_fs;
1963 		}
1964 		if (fstab.zone_fs_raw[0] == '\0' && stat(cmdbuf, &st) == 0) {
1965 			(void) fprintf(stderr, gettext("could not verify fs "
1966 			    "%s: must specify 'raw' device for %s "
1967 			    "file-systems\n"),
1968 			    fstab.zone_fs_dir, fstab.zone_fs_type);
1969 			return_code = Z_ERR;
1970 			goto next_fs;
1971 		}
1972 		if (fstab.zone_fs_raw[0] != '\0' &&
1973 		    (stat(cmdbuf, &st) != 0 || !S_ISREG(st.st_mode))) {
1974 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1975 			    "'raw' device specified but "
1976 			    "no fsck executable exists for %s\n"),
1977 			    fstab.zone_fs_dir, fstab.zone_fs_type);
1978 			return_code = Z_ERR;
1979 			goto next_fs;
1980 		}
1981 		/*
1982 		 * Verify fs_special and optionally fs_raw, exists.
1983 		 */
1984 		if (stat(fstab.zone_fs_special, &st) != 0) {
1985 			(void) fprintf(stderr, gettext("could not verify fs "
1986 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
1987 			    fstab.zone_fs_special, strerror(errno));
1988 			return_code = Z_ERR;
1989 			goto next_fs;
1990 		}
1991 		if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
1992 			/*
1993 			 * TRANSLATION_NOTE
1994 			 * fs and NFS are literals that should
1995 			 * not be translated.
1996 			 */
1997 			(void) fprintf(stderr, gettext("cannot verify "
1998 			    "fs %s: NFS mounted file-system.\n"
1999 			    "\tA local file-system must be used.\n"),
2000 			    fstab.zone_fs_special);
2001 			return_code = Z_ERR;
2002 			goto next_fs;
2003 		}
2004 		if (fstab.zone_fs_raw[0] != '\0' &&
2005 		    stat(fstab.zone_fs_raw, &st) != 0) {
2006 			/*
2007 			 * TRANSLATION_NOTE
2008 			 * fs is a literal that should not be translated.
2009 			 */
2010 			(void) fprintf(stderr, gettext("could not verify fs "
2011 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2012 			    fstab.zone_fs_raw, strerror(errno));
2013 			return_code = Z_ERR;
2014 			goto next_fs;
2015 		}
2016 next_fs:
2017 		zonecfg_free_fs_option_list(fstab.zone_fs_options);
2018 	}
2019 	(void) zonecfg_endfsent(handle);
2020 
2021 	return (return_code);
2022 }
2023 
2024 const char *current_dataset;
2025 
2026 /*
2027  * Custom error handler for errors incurred as part of the checks below.  We
2028  * want to trim off the leading 'cannot open ...' to create a better error
2029  * message.  The only other way this can fail is if we fail to set the 'zoned'
2030  * property.  In this case we just pass the error on verbatim.
2031  */
2032 static void
2033 zfs_error_handler(const char *fmt, va_list ap)
2034 {
2035 	char buf[1024];
2036 
2037 	(void) vsnprintf(buf, sizeof (buf), fmt, ap);
2038 
2039 	if (strncmp(gettext("cannot open "), buf,
2040 	    strlen(gettext("cannot open "))) == 0)
2041 		/*
2042 		 * TRANSLATION_NOTE
2043 		 * zfs and dataset are literals that should not be translated.
2044 		 */
2045 		(void) fprintf(stderr, gettext("could not verify zfs "
2046 		    "dataset %s%s\n"), current_dataset, strchr(buf, ':'));
2047 	else
2048 		(void) fprintf(stderr, gettext("could not verify zfs dataset "
2049 		    "%s: %s\n"), current_dataset, buf);
2050 }
2051 
2052 /* ARGSUSED */
2053 static int
2054 check_zvol(zfs_handle_t *zhp, void *unused)
2055 {
2056 	int ret;
2057 
2058 	if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
2059 		/*
2060 		 * TRANSLATION_NOTE
2061 		 * zfs and dataset are literals that should not be translated.
2062 		 */
2063 		(void) fprintf(stderr, gettext("cannot verify zfs dataset %s: "
2064 		    "volumes cannot be specified as a zone dataset resource\n"),
2065 		    zfs_get_name(zhp));
2066 		ret = -1;
2067 	} else {
2068 		ret = zfs_iter_children(zhp, check_zvol, NULL);
2069 	}
2070 
2071 	zfs_close(zhp);
2072 
2073 	return (ret);
2074 }
2075 
2076 /*
2077  * Validate that the given dataset exists on the system, and that neither it nor
2078  * its children are zvols.
2079  *
2080  * Note that we don't do anything with the 'zoned' property here.  All
2081  * management is done in zoneadmd when the zone is actually rebooted.  This
2082  * allows us to automatically set the zoned property even when a zone is
2083  * rebooted by the administrator.
2084  */
2085 static int
2086 verify_datasets(zone_dochandle_t handle)
2087 {
2088 	int return_code = Z_OK;
2089 	struct zone_dstab dstab;
2090 	zfs_handle_t *zhp;
2091 	char propbuf[ZFS_MAXPROPLEN];
2092 	char source[ZFS_MAXNAMELEN];
2093 	zfs_source_t srctype;
2094 
2095 	if (zonecfg_setdsent(handle) != Z_OK) {
2096 		/*
2097 		 * TRANSLATION_NOTE
2098 		 * zfs and dataset are literals that should not be translated.
2099 		 */
2100 		(void) fprintf(stderr, gettext("could not verify zfs datasets: "
2101 		    "unable to enumerate datasets\n"));
2102 		return (Z_ERR);
2103 	}
2104 
2105 	zfs_set_error_handler(zfs_error_handler);
2106 
2107 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2108 
2109 		current_dataset = dstab.zone_dataset_name;
2110 
2111 		if ((zhp = zfs_open(dstab.zone_dataset_name,
2112 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
2113 			return_code = Z_ERR;
2114 			continue;
2115 		}
2116 
2117 		if (zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, propbuf,
2118 		    sizeof (propbuf), &srctype, source,
2119 		    sizeof (source), 0) == 0 &&
2120 		    (srctype == ZFS_SRC_INHERITED)) {
2121 			(void) fprintf(stderr, gettext("could not verify zfs "
2122 			    "dataset %s: mountpoint cannot be inherited\n"),
2123 			    dstab.zone_dataset_name);
2124 			return_code = Z_ERR;
2125 			zfs_close(zhp);
2126 			continue;
2127 		}
2128 
2129 		if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
2130 			(void) fprintf(stderr, gettext("cannot verify zfs "
2131 			    "dataset %s: volumes cannot be specified as a "
2132 			    "zone dataset resource\n"),
2133 			    dstab.zone_dataset_name);
2134 			return_code = Z_ERR;
2135 		}
2136 
2137 		if (zfs_iter_children(zhp, check_zvol, NULL) != 0)
2138 			return_code = Z_ERR;
2139 
2140 		zfs_close(zhp);
2141 	}
2142 	(void) zonecfg_enddsent(handle);
2143 
2144 	return (return_code);
2145 }
2146 
2147 static int
2148 verify_details(int cmd_num)
2149 {
2150 	zone_dochandle_t handle;
2151 	struct zone_nwiftab nwiftab;
2152 	char zonepath[MAXPATHLEN], checkpath[MAXPATHLEN];
2153 	int return_code = Z_OK;
2154 	int err;
2155 	boolean_t in_alt_root;
2156 
2157 	if ((handle = zonecfg_init_handle()) == NULL) {
2158 		zperror(cmd_to_str(cmd_num), B_TRUE);
2159 		return (Z_ERR);
2160 	}
2161 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
2162 		errno = err;
2163 		zperror(cmd_to_str(cmd_num), B_TRUE);
2164 		zonecfg_fini_handle(handle);
2165 		return (Z_ERR);
2166 	}
2167 	if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
2168 	    Z_OK) {
2169 		errno = err;
2170 		zperror(cmd_to_str(cmd_num), B_TRUE);
2171 		zonecfg_fini_handle(handle);
2172 		return (Z_ERR);
2173 	}
2174 	/*
2175 	 * zonecfg_get_zonepath() gets its data from the XML repository.
2176 	 * Verify this against the index file, which is checked first by
2177 	 * zone_get_zonepath().  If they don't match, bail out.
2178 	 */
2179 	if ((err = zone_get_zonepath(target_zone, checkpath,
2180 	    sizeof (checkpath))) != Z_OK) {
2181 		errno = err;
2182 		zperror2(target_zone, gettext("could not get zone path"));
2183 		return (Z_ERR);
2184 	}
2185 	if (strcmp(zonepath, checkpath) != 0) {
2186 		/*
2187 		 * TRANSLATION_NOTE
2188 		 * XML and zonepath are literals that should not be translated.
2189 		 */
2190 		(void) fprintf(stderr, gettext("The XML repository has "
2191 		    "zonepath '%s',\nbut the index file has zonepath '%s'.\n"
2192 		    "These must match, so fix the incorrect entry.\n"),
2193 		    zonepath, checkpath);
2194 		return (Z_ERR);
2195 	}
2196 	if (validate_zonepath(zonepath, cmd_num) != Z_OK) {
2197 		(void) fprintf(stderr, gettext("could not verify zonepath %s "
2198 		    "because of the above errors.\n"), zonepath);
2199 		return_code = Z_ERR;
2200 	}
2201 
2202 	in_alt_root = zonecfg_in_alt_root();
2203 	if (in_alt_root)
2204 		goto no_net;
2205 
2206 	if ((err = zonecfg_setnwifent(handle)) != Z_OK) {
2207 		errno = err;
2208 		zperror(cmd_to_str(cmd_num), B_TRUE);
2209 		zonecfg_fini_handle(handle);
2210 		return (Z_ERR);
2211 	}
2212 	while (zonecfg_getnwifent(handle, &nwiftab) == Z_OK) {
2213 		struct lifreq lifr;
2214 		sa_family_t af;
2215 		int so, res;
2216 
2217 		/* skip any loopback interfaces */
2218 		if (strcmp(nwiftab.zone_nwif_physical, "lo0") == 0)
2219 			continue;
2220 		if ((res = zonecfg_valid_net_address(nwiftab.zone_nwif_address,
2221 		    &lifr)) != Z_OK) {
2222 			(void) fprintf(stderr, gettext("could not verify %s "
2223 			    "%s=%s %s=%s: %s\n"), "net", "address",
2224 			    nwiftab.zone_nwif_address, "physical",
2225 			    nwiftab.zone_nwif_physical, zonecfg_strerror(res));
2226 			return_code = Z_ERR;
2227 			continue;
2228 		}
2229 		af = lifr.lifr_addr.ss_family;
2230 		(void) memset(&lifr, 0, sizeof (lifr));
2231 		(void) strlcpy(lifr.lifr_name, nwiftab.zone_nwif_physical,
2232 		    sizeof (lifr.lifr_name));
2233 		lifr.lifr_addr.ss_family = af;
2234 		if ((so = socket(af, SOCK_DGRAM, 0)) < 0) {
2235 			(void) fprintf(stderr, gettext("could not verify %s "
2236 			    "%s=%s %s=%s: could not get socket: %s\n"), "net",
2237 			    "address", nwiftab.zone_nwif_address, "physical",
2238 			    nwiftab.zone_nwif_physical, strerror(errno));
2239 			return_code = Z_ERR;
2240 			continue;
2241 		}
2242 		if (ioctl(so, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2243 			(void) fprintf(stderr,
2244 			    gettext("could not verify %s %s=%s %s=%s: %s\n"),
2245 			    "net", "address", nwiftab.zone_nwif_address,
2246 			    "physical", nwiftab.zone_nwif_physical,
2247 			    strerror(errno));
2248 			return_code = Z_ERR;
2249 		}
2250 		(void) close(so);
2251 	}
2252 	(void) zonecfg_endnwifent(handle);
2253 no_net:
2254 
2255 	if (verify_filesystems(handle) != Z_OK)
2256 		return_code = Z_ERR;
2257 	if (verify_ipd(handle) != Z_OK)
2258 		return_code = Z_ERR;
2259 	if (!in_alt_root && verify_rctls(handle) != Z_OK)
2260 		return_code = Z_ERR;
2261 	if (!in_alt_root && verify_pool(handle) != Z_OK)
2262 		return_code = Z_ERR;
2263 	if (!in_alt_root && verify_datasets(handle) != Z_OK)
2264 		return_code = Z_ERR;
2265 	zonecfg_fini_handle(handle);
2266 	if (return_code == Z_ERR)
2267 		(void) fprintf(stderr,
2268 		    gettext("%s: zone %s failed to verify\n"),
2269 		    execname, target_zone);
2270 	return (return_code);
2271 }
2272 
2273 static int
2274 verify_func(int argc, char *argv[])
2275 {
2276 	int arg;
2277 
2278 	optind = 0;
2279 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2280 		switch (arg) {
2281 		case '?':
2282 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2283 			return (optopt == '?' ? Z_OK : Z_USAGE);
2284 		default:
2285 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2286 			return (Z_USAGE);
2287 		}
2288 	}
2289 	if (argc > optind) {
2290 		sub_usage(SHELP_VERIFY, CMD_VERIFY);
2291 		return (Z_USAGE);
2292 	}
2293 	if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE) != Z_OK)
2294 		return (Z_ERR);
2295 	return (verify_details(CMD_VERIFY));
2296 }
2297 
2298 #define	LUCREATEZONE	"/usr/lib/lu/lucreatezone"
2299 
2300 static int
2301 install_func(int argc, char *argv[])
2302 {
2303 	/* 9: "exec " and " -z " */
2304 	char cmdbuf[sizeof (LUCREATEZONE) + ZONENAME_MAX + 9];
2305 	int lockfd;
2306 	int err, arg;
2307 	char zonepath[MAXPATHLEN];
2308 	int status;
2309 
2310 	if (zonecfg_in_alt_root()) {
2311 		zerror(gettext("cannot install zone in alternate root"));
2312 		return (Z_ERR);
2313 	}
2314 
2315 	optind = 0;
2316 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2317 		switch (arg) {
2318 		case '?':
2319 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
2320 			return (optopt == '?' ? Z_OK : Z_USAGE);
2321 		default:
2322 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
2323 			return (Z_USAGE);
2324 		}
2325 	}
2326 	if (argc > optind) {
2327 		sub_usage(SHELP_INSTALL, CMD_INSTALL);
2328 		return (Z_USAGE);
2329 	}
2330 	if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE) != Z_OK)
2331 		return (Z_ERR);
2332 	if (verify_details(CMD_INSTALL) != Z_OK)
2333 		return (Z_ERR);
2334 
2335 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
2336 		zerror(gettext("another %s may have an operation in progress."),
2337 		    "zoneadmd");
2338 		return (Z_ERR);
2339 	}
2340 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
2341 	if (err != Z_OK) {
2342 		errno = err;
2343 		zperror2(target_zone, gettext("could not set state"));
2344 		goto done;
2345 	}
2346 
2347 	/*
2348 	 * According to the Application Packaging Developer's Guide, a
2349 	 * "checkinstall" script when included in a package is executed as
2350 	 * the user "install", if such a user exists, or by the user
2351 	 * "nobody".  In order to support this dubious behavior, the path
2352 	 * to the zone being constructed is opened up during the life of
2353 	 * the command laying down the zone's root file system.  Once this
2354 	 * has completed, regardless of whether it was successful, the
2355 	 * path to the zone is again restricted.
2356 	 */
2357 	if ((err = zone_get_zonepath(target_zone, zonepath,
2358 	    sizeof (zonepath))) != Z_OK) {
2359 		errno = err;
2360 		zperror2(target_zone, gettext("could not get zone path"));
2361 		goto done;
2362 	}
2363 	if (chmod(zonepath, DEFAULT_DIR_MODE) != 0) {
2364 		zperror(zonepath, B_FALSE);
2365 		err = Z_ERR;
2366 		goto done;
2367 	}
2368 
2369 	/*
2370 	 * "exec" the command so that the returned status is that of
2371 	 * LUCREATEZONE and not the shell.
2372 	 */
2373 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " LUCREATEZONE " -z %s",
2374 	    target_zone);
2375 	status = do_subproc(cmdbuf);
2376 	if (chmod(zonepath, S_IRWXU) != 0) {
2377 		zperror(zonepath, B_FALSE);
2378 		err = Z_ERR;
2379 		goto done;
2380 	}
2381 	if ((err = subproc_status(LUCREATEZONE, status)) != Z_OK)
2382 		goto done;
2383 
2384 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
2385 		errno = err;
2386 		zperror2(target_zone, gettext("could not set state"));
2387 		goto done;
2388 	}
2389 
2390 done:
2391 	release_lock_file(lockfd);
2392 	return ((err == Z_OK) ? Z_OK : Z_ERR);
2393 }
2394 
2395 /*
2396  * On input, TRUE => yes, FALSE => no.
2397  * On return, TRUE => 1, FALSE => 0, could not ask => -1.
2398  */
2399 
2400 static int
2401 ask_yesno(boolean_t default_answer, const char *question)
2402 {
2403 	char line[64];	/* should be large enough to answer yes or no */
2404 
2405 	if (!isatty(STDIN_FILENO))
2406 		return (-1);
2407 	for (;;) {
2408 		(void) printf("%s (%s)? ", question,
2409 		    default_answer ? "[y]/n" : "y/[n]");
2410 		if (fgets(line, sizeof (line), stdin) == NULL ||
2411 		    line[0] == '\n')
2412 			return (default_answer ? 1 : 0);
2413 		if (tolower(line[0]) == 'y')
2414 			return (1);
2415 		if (tolower(line[0]) == 'n')
2416 			return (0);
2417 	}
2418 }
2419 
2420 #define	RMCOMMAND	"/usr/bin/rm -rf"
2421 
2422 /* ARGSUSED */
2423 int
2424 zfm_print(const char *p, void *r) {
2425 	zerror("  %s\n", p);
2426 	return (0);
2427 }
2428 
2429 static int
2430 uninstall_func(int argc, char *argv[])
2431 {
2432 	/* 6: "exec " and " " */
2433 	char cmdbuf[sizeof (RMCOMMAND) + MAXPATHLEN + 6];
2434 	char line[ZONENAME_MAX + 128];	/* Enough for "Are you sure ..." */
2435 	char rootpath[MAXPATHLEN], devpath[MAXPATHLEN];
2436 	boolean_t force = B_FALSE;
2437 	int lockfd, answer;
2438 	int err, arg;
2439 	int status;
2440 
2441 	if (zonecfg_in_alt_root()) {
2442 		zerror(gettext("cannot uninstall zone in alternate root"));
2443 		return (Z_ERR);
2444 	}
2445 
2446 	optind = 0;
2447 	while ((arg = getopt(argc, argv, "?F")) != EOF) {
2448 		switch (arg) {
2449 		case '?':
2450 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
2451 			return (optopt == '?' ? Z_OK : Z_USAGE);
2452 		case 'F':
2453 			force = B_TRUE;
2454 			break;
2455 		default:
2456 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
2457 			return (Z_USAGE);
2458 		}
2459 	}
2460 	if (argc > optind) {
2461 		sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
2462 		return (Z_USAGE);
2463 	}
2464 
2465 	if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE) != Z_OK)
2466 		return (Z_ERR);
2467 
2468 	if (!force) {
2469 		(void) snprintf(line, sizeof (line),
2470 		    gettext("Are you sure you want to %s zone %s"),
2471 		    cmd_to_str(CMD_UNINSTALL), target_zone);
2472 		if ((answer = ask_yesno(B_FALSE, line)) == 0) {
2473 			return (Z_OK);
2474 		} else if (answer == -1) {
2475 			zerror(gettext("Input not from terminal and -F "
2476 			    "not specified: %s not done."),
2477 			    cmd_to_str(CMD_UNINSTALL));
2478 			return (Z_ERR);
2479 		}
2480 	}
2481 
2482 	if ((err = zone_get_zonepath(target_zone, devpath,
2483 	    sizeof (devpath))) != Z_OK) {
2484 		errno = err;
2485 		zperror2(target_zone, gettext("could not get zone path"));
2486 		return (Z_ERR);
2487 	}
2488 	(void) strlcat(devpath, "/dev", sizeof (devpath));
2489 	if ((err = zone_get_rootpath(target_zone, rootpath,
2490 	    sizeof (rootpath))) != Z_OK) {
2491 		errno = err;
2492 		zperror2(target_zone, gettext("could not get root path"));
2493 		return (Z_ERR);
2494 	}
2495 
2496 	/*
2497 	 * If there seems to be a zoneadmd running for this zone, call it
2498 	 * to tell it that an uninstall is happening; if all goes well it
2499 	 * will then shut itself down.
2500 	 */
2501 	if (ping_zoneadmd(target_zone) == Z_OK) {
2502 		zone_cmd_arg_t zarg;
2503 		zarg.cmd = Z_NOTE_UNINSTALLING;
2504 		/* we don't care too much if this fails... just plow on */
2505 		(void) call_zoneadmd(target_zone, &zarg);
2506 	}
2507 
2508 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
2509 		zerror(gettext("another %s may have an operation in progress."),
2510 		    "zoneadmd");
2511 		return (Z_ERR);
2512 	}
2513 
2514 	/* Don't uninstall the zone if anything is mounted there */
2515 	err = zonecfg_find_mounts(rootpath, NULL, NULL);
2516 	if (err) {
2517 		zerror(gettext("These file-systems are mounted on "
2518 			"subdirectories of %s.\n"), rootpath);
2519 		(void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
2520 		return (Z_ERR);
2521 	}
2522 
2523 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
2524 	if (err != Z_OK) {
2525 		errno = err;
2526 		zperror2(target_zone, gettext("could not set state"));
2527 		goto bad;
2528 	}
2529 
2530 	/*
2531 	 * "exec" the command so that the returned status is that of
2532 	 * RMCOMMAND and not the shell.
2533 	 */
2534 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
2535 	    devpath);
2536 	status = do_subproc(cmdbuf);
2537 	if ((err = subproc_status(RMCOMMAND, status)) != Z_OK)
2538 		goto bad;
2539 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
2540 	    rootpath);
2541 	status = do_subproc(cmdbuf);
2542 	if ((err = subproc_status(RMCOMMAND, status)) != Z_OK)
2543 		goto bad;
2544 	err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
2545 	if (err != Z_OK) {
2546 		errno = err;
2547 		zperror2(target_zone, gettext("could not reset state"));
2548 	}
2549 bad:
2550 	release_lock_file(lockfd);
2551 	return (err);
2552 }
2553 
2554 /* ARGSUSED */
2555 static int
2556 mount_func(int argc, char *argv[])
2557 {
2558 	zone_cmd_arg_t zarg;
2559 
2560 	if (argc > 0)
2561 		return (Z_USAGE);
2562 	if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE) != Z_OK)
2563 		return (Z_ERR);
2564 	if (verify_details(CMD_MOUNT) != Z_OK)
2565 		return (Z_ERR);
2566 
2567 	zarg.cmd = Z_MOUNT;
2568 	if (call_zoneadmd(target_zone, &zarg) != 0) {
2569 		zerror(gettext("call to %s failed"), "zoneadmd");
2570 		return (Z_ERR);
2571 	}
2572 	return (Z_OK);
2573 }
2574 
2575 /* ARGSUSED */
2576 static int
2577 unmount_func(int argc, char *argv[])
2578 {
2579 	zone_cmd_arg_t zarg;
2580 
2581 	if (argc > 0)
2582 		return (Z_USAGE);
2583 	if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE) != Z_OK)
2584 		return (Z_ERR);
2585 
2586 	zarg.cmd = Z_UNMOUNT;
2587 	if (call_zoneadmd(target_zone, &zarg) != 0) {
2588 		zerror(gettext("call to %s failed"), "zoneadmd");
2589 		return (Z_ERR);
2590 	}
2591 	return (Z_OK);
2592 }
2593 
2594 static int
2595 help_func(int argc, char *argv[])
2596 {
2597 	int arg, cmd_num;
2598 
2599 	if (argc == 0) {
2600 		(void) usage(B_TRUE);
2601 		return (Z_OK);
2602 	}
2603 	optind = 0;
2604 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2605 		switch (arg) {
2606 		case '?':
2607 			sub_usage(SHELP_HELP, CMD_HELP);
2608 			return (optopt == '?' ? Z_OK : Z_USAGE);
2609 		default:
2610 			sub_usage(SHELP_HELP, CMD_HELP);
2611 			return (Z_USAGE);
2612 		}
2613 	}
2614 	while (optind < argc) {
2615 		if ((cmd_num = cmd_match(argv[optind])) < 0) {
2616 			sub_usage(SHELP_HELP, CMD_HELP);
2617 			return (Z_USAGE);
2618 		}
2619 		sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
2620 		optind++;
2621 	}
2622 	return (Z_OK);
2623 }
2624 
2625 /*
2626  * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
2627  */
2628 
2629 static int
2630 cmd_match(char *cmd)
2631 {
2632 	int i;
2633 
2634 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
2635 		/* return only if there is an exact match */
2636 		if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
2637 			return (cmdtab[i].cmd_num);
2638 	}
2639 	return (-1);
2640 }
2641 
2642 static int
2643 parse_and_run(int argc, char *argv[])
2644 {
2645 	int i = cmd_match(argv[0]);
2646 
2647 	if (i < 0)
2648 		return (usage(B_FALSE));
2649 	return (cmdtab[i].handler(argc - 1, &(argv[1])));
2650 }
2651 
2652 static char *
2653 get_execbasename(char *execfullname)
2654 {
2655 	char *last_slash, *execbasename;
2656 
2657 	/* guard against '/' at end of command invocation */
2658 	for (;;) {
2659 		last_slash = strrchr(execfullname, '/');
2660 		if (last_slash == NULL) {
2661 			execbasename = execfullname;
2662 			break;
2663 		} else {
2664 			execbasename = last_slash + 1;
2665 			if (*execbasename == '\0') {
2666 				*last_slash = '\0';
2667 				continue;
2668 			}
2669 			break;
2670 		}
2671 	}
2672 	return (execbasename);
2673 }
2674 
2675 int
2676 main(int argc, char **argv)
2677 {
2678 	int arg;
2679 	zoneid_t zid;
2680 	struct stat st;
2681 
2682 	if ((locale = setlocale(LC_ALL, "")) == NULL)
2683 		locale = "C";
2684 	(void) textdomain(TEXT_DOMAIN);
2685 	setbuf(stdout, NULL);
2686 	(void) sigset(SIGHUP, SIG_IGN);
2687 	execname = get_execbasename(argv[0]);
2688 	target_zone = NULL;
2689 	if (chdir("/") != 0) {
2690 		zerror(gettext("could not change directory to /."));
2691 		exit(Z_ERR);
2692 	}
2693 
2694 	while ((arg = getopt(argc, argv, "?z:R:")) != EOF) {
2695 		switch (arg) {
2696 		case '?':
2697 			return (usage(B_TRUE));
2698 		case 'z':
2699 			target_zone = optarg;
2700 			break;
2701 		case 'R':	/* private option for admin/install use */
2702 			if (*optarg != '/') {
2703 				zerror(gettext("root path must be absolute."));
2704 				exit(Z_ERR);
2705 			}
2706 			if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
2707 				zerror(
2708 				    gettext("root path must be a directory."));
2709 				exit(Z_ERR);
2710 			}
2711 			zonecfg_set_root(optarg);
2712 			break;
2713 		default:
2714 			return (usage(B_FALSE));
2715 		}
2716 	}
2717 
2718 	if (optind >= argc)
2719 		return (usage(B_FALSE));
2720 	if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
2721 		errno = Z_NO_ZONE;
2722 		zperror(target_zone, B_TRUE);
2723 		exit(Z_ERR);
2724 	}
2725 	return (parse_and_run(argc - optind, &argv[optind]));
2726 }
2727