xref: /illumos-gate/usr/src/cmd/zoneadm/zoneadm.c (revision 88f8b78a88cbdc6d8c1af5c3e54bc49d25095c98)
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("cannot 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 			(void) fprintf(stderr, gettext("%s zonepath (%s) and "
705 			    "%s zonepath (%s) overlap.\n"),
706 			    target_zone, path, ze->zone_name, rpath);
707 			free(ze);
708 			return (Z_ERR);
709 		}
710 		free(ze);
711 	}
712 	endzoneent(cookie);
713 	return (Z_OK);
714 }
715 
716 static int
717 validate_zonepath(char *path, int cmd_num)
718 {
719 	int res;			/* result of last library/system call */
720 	boolean_t err = B_FALSE;	/* have we run into an error? */
721 	struct stat stbuf;
722 	struct statvfs vfsbuf;
723 	char rpath[MAXPATHLEN];		/* resolved path */
724 	char ppath[MAXPATHLEN];		/* parent path */
725 	char rppath[MAXPATHLEN];	/* resolved parent path */
726 	char rootpath[MAXPATHLEN];	/* root path */
727 	zone_state_t state;
728 
729 	if (path[0] != '/') {
730 		(void) fprintf(stderr,
731 		    gettext("%s is not an absolute path.\n"), path);
732 		return (Z_ERR);
733 	}
734 	if ((res = resolvepath(path, rpath, sizeof (rpath))) == -1) {
735 		if ((errno != ENOENT) ||
736 		    (cmd_num != CMD_VERIFY && cmd_num != CMD_INSTALL)) {
737 			zperror(path, B_FALSE);
738 			return (Z_ERR);
739 		}
740 		if (cmd_num == CMD_VERIFY) {
741 			(void) fprintf(stderr, gettext("WARNING: %s does not "
742 			    "exist, so it cannot be verified.\nWhen 'zoneadm "
743 			    "%s' is run, '%s' will try to create\n%s, and '%s' "
744 			    "will be tried again,\nbut the '%s' may fail if:\n"
745 			    "the parent directory of %s is group- or other-"
746 			    "writable\nor\n%s overlaps with any other "
747 			    "installed zones.\n"), path,
748 			    cmd_to_str(CMD_INSTALL), cmd_to_str(CMD_INSTALL),
749 			    path, cmd_to_str(CMD_VERIFY),
750 			    cmd_to_str(CMD_VERIFY), path, path);
751 			return (Z_OK);
752 		}
753 		/*
754 		 * The zonepath is supposed to be mode 700 but its
755 		 * parent(s) 755.  So use 755 on the mkdirp() then
756 		 * chmod() the zonepath itself to 700.
757 		 */
758 		if (mkdirp(path, DEFAULT_DIR_MODE) < 0) {
759 			zperror(path, B_FALSE);
760 			return (Z_ERR);
761 		}
762 		/*
763 		 * If the chmod() fails, report the error, but might
764 		 * as well continue the verify procedure.
765 		 */
766 		if (chmod(path, S_IRWXU) != 0)
767 			zperror(path, B_FALSE);
768 		/*
769 		 * Since the mkdir() succeeded, we should not have to
770 		 * worry about a subsequent ENOENT, thus this should
771 		 * only recurse once.
772 		 */
773 		return (validate_zonepath(path, CMD_INSTALL));
774 	}
775 	rpath[res] = '\0';
776 	if (strcmp(path, rpath) != 0) {
777 		errno = Z_RESOLVED_PATH;
778 		zperror(path, B_TRUE);
779 		return (Z_ERR);
780 	}
781 	if ((res = stat(rpath, &stbuf)) != 0) {
782 		zperror(rpath, B_FALSE);
783 		return (Z_ERR);
784 	}
785 	if (!S_ISDIR(stbuf.st_mode)) {
786 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
787 		    rpath);
788 		return (Z_ERR);
789 	}
790 	if ((strcmp(stbuf.st_fstype, MNTTYPE_TMPFS) == 0) ||
791 	    (strcmp(stbuf.st_fstype, MNTTYPE_XMEMFS) == 0)) {
792 		(void) printf(gettext("WARNING: %s is on a temporary "
793 		    "file-system.\n"), rpath);
794 	}
795 	if (crosscheck_zonepaths(rpath) != Z_OK)
796 		return (Z_ERR);
797 	/*
798 	 * Try to collect and report as many minor errors as possible
799 	 * before returning, so the user can learn everything that needs
800 	 * to be fixed up front.
801 	 */
802 	if (stbuf.st_uid != 0) {
803 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
804 		    rpath);
805 		err = B_TRUE;
806 	}
807 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rpath);
808 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rpath);
809 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rpath);
810 	err |= bad_mode_bit(stbuf.st_mode, S_IRGRP, B_FALSE, rpath);
811 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rpath);
812 	err |= bad_mode_bit(stbuf.st_mode, S_IXGRP, B_FALSE, rpath);
813 	err |= bad_mode_bit(stbuf.st_mode, S_IROTH, B_FALSE, rpath);
814 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rpath);
815 	err |= bad_mode_bit(stbuf.st_mode, S_IXOTH, B_FALSE, rpath);
816 
817 	(void) snprintf(ppath, sizeof (ppath), "%s/..", path);
818 	if ((res = resolvepath(ppath, rppath, sizeof (rppath))) == -1) {
819 		zperror(ppath, B_FALSE);
820 		return (Z_ERR);
821 	}
822 	rppath[res] = '\0';
823 	if ((res = stat(rppath, &stbuf)) != 0) {
824 		zperror(rppath, B_FALSE);
825 		return (Z_ERR);
826 	}
827 	/* theoretically impossible */
828 	if (!S_ISDIR(stbuf.st_mode)) {
829 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
830 		    rppath);
831 		return (Z_ERR);
832 	}
833 	if (stbuf.st_uid != 0) {
834 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
835 		    rppath);
836 		err = B_TRUE;
837 	}
838 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rppath);
839 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rppath);
840 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rppath);
841 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rppath);
842 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rppath);
843 	if (strcmp(rpath, rppath) == 0) {
844 		(void) fprintf(stderr, gettext("%s is its own parent.\n"),
845 		    rppath);
846 		err = B_TRUE;
847 	}
848 
849 	if (statvfs(rpath, &vfsbuf) != 0) {
850 		zperror(rpath, B_FALSE);
851 		return (Z_ERR);
852 	}
853 	if (strcmp(vfsbuf.f_basetype, MNTTYPE_NFS) == 0) {
854 		(void) fprintf(stderr, gettext("Zonepath %s is on a NFS "
855 		    "mounted file system.\n"
856 		    "\tA local file system must be used.\n"), rpath);
857 		return (Z_ERR);
858 	}
859 	if (vfsbuf.f_flag & ST_NOSUID) {
860 		(void) fprintf(stderr, gettext("Zonepath %s is on a nosuid "
861 		    "file system.\n"), rpath);
862 		return (Z_ERR);
863 	}
864 
865 	if ((res = zone_get_state(target_zone, &state)) != Z_OK) {
866 		errno = res;
867 		zperror2(target_zone, gettext("could not get state"));
868 		return (Z_ERR);
869 	}
870 	/*
871 	 * The existence of the root path is only bad in the configured state,
872 	 * as it is *supposed* to be there at the installed and later states.
873 	 * State/command mismatches are caught earlier in verify_details().
874 	 */
875 	if (state == ZONE_STATE_CONFIGURED) {
876 		if (snprintf(rootpath, sizeof (rootpath), "%s/root", rpath) >=
877 		    sizeof (rootpath)) {
878 			(void) fprintf(stderr,
879 			    gettext("Zonepath %s is too long.\n"), rpath);
880 			return (Z_ERR);
881 		}
882 		if ((res = stat(rootpath, &stbuf)) == 0) {
883 			(void) fprintf(stderr, gettext("Rootpath %s exists; "
884 			    "remove or move aside prior to %s.\n"), rootpath,
885 			    cmd_to_str(CMD_INSTALL));
886 			return (Z_ERR);
887 		}
888 	}
889 
890 	return (err ? Z_ERR : Z_OK);
891 }
892 
893 static void
894 release_lock_file(int lockfd)
895 {
896 	(void) close(lockfd);
897 }
898 
899 static int
900 grab_lock_file(const char *zone_name, int *lockfd)
901 {
902 	char pathbuf[PATH_MAX];
903 	struct flock flock;
904 
905 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s", zonecfg_get_root(),
906 	    ZONES_TMPDIR) >= sizeof (pathbuf)) {
907 		zerror(gettext("alternate root path is too long"));
908 		return (Z_ERR);
909 	}
910 	if (mkdir(pathbuf, S_IRWXU) < 0 && errno != EEXIST) {
911 		zerror(gettext("could not mkdir %s: %s"), pathbuf,
912 		    strerror(errno));
913 		return (Z_ERR);
914 	}
915 	(void) chmod(pathbuf, S_IRWXU);
916 
917 	/*
918 	 * One of these lock files is created for each zone (when needed).
919 	 * The lock files are not cleaned up (except on system reboot),
920 	 * but since there is only one per zone, there is no resource
921 	 * starvation issue.
922 	 */
923 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s/%s.zoneadm.lock",
924 	    zonecfg_get_root(), ZONES_TMPDIR, zone_name) >= sizeof (pathbuf)) {
925 		zerror(gettext("alternate root path is too long"));
926 		return (Z_ERR);
927 	}
928 	if ((*lockfd = open(pathbuf, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
929 		zerror(gettext("could not open %s: %s"), pathbuf,
930 		    strerror(errno));
931 		return (Z_ERR);
932 	}
933 	/*
934 	 * Lock the file to synchronize with other zoneadmds
935 	 */
936 	flock.l_type = F_WRLCK;
937 	flock.l_whence = SEEK_SET;
938 	flock.l_start = (off_t)0;
939 	flock.l_len = (off_t)0;
940 	if (fcntl(*lockfd, F_SETLKW, &flock) < 0) {
941 		zerror(gettext("unable to lock %s: %s"), pathbuf,
942 		    strerror(errno));
943 		release_lock_file(*lockfd);
944 		return (Z_ERR);
945 	}
946 	return (Z_OK);
947 }
948 
949 static boolean_t
950 get_doorname(const char *zone_name, char *buffer)
951 {
952 	return (snprintf(buffer, PATH_MAX, "%s" ZONE_DOOR_PATH,
953 	    zonecfg_get_root(), zone_name) < PATH_MAX);
954 }
955 
956 /*
957  * system daemons are not audited.  For the global zone, this occurs
958  * "naturally" since init is started with the default audit
959  * characteristics.  Since zoneadmd is a system daemon and it starts
960  * init for a zone, it is necessary to clear out the audit
961  * characteristics inherited from whomever started zoneadmd.  This is
962  * indicated by the audit id, which is set from the ruid parameter of
963  * adt_set_user(), below.
964  */
965 
966 static void
967 prepare_audit_context()
968 {
969 	adt_session_data_t	*ah;
970 	char			*failure = gettext("audit failure: %s");
971 
972 	if (adt_start_session(&ah, NULL, 0)) {
973 		zerror(failure, strerror(errno));
974 		return;
975 	}
976 	if (adt_set_user(ah, ADT_NO_AUDIT, ADT_NO_AUDIT,
977 	    ADT_NO_AUDIT, ADT_NO_AUDIT, NULL, ADT_NEW)) {
978 		zerror(failure, strerror(errno));
979 		(void) adt_end_session(ah);
980 		return;
981 	}
982 	if (adt_set_proc(ah))
983 		zerror(failure, strerror(errno));
984 
985 	(void) adt_end_session(ah);
986 }
987 
988 static int
989 start_zoneadmd(const char *zone_name)
990 {
991 	char doorpath[PATH_MAX];
992 	pid_t child_pid;
993 	int error = Z_ERR;
994 	int doorfd, lockfd;
995 	struct door_info info;
996 
997 	if (!get_doorname(zone_name, doorpath))
998 		return (Z_ERR);
999 
1000 	if (grab_lock_file(zone_name, &lockfd) != Z_OK)
1001 		return (Z_ERR);
1002 
1003 	/*
1004 	 * Now that we have the lock, re-confirm that the daemon is
1005 	 * *not* up and working fine.  If it is still down, we have a green
1006 	 * light to start it.
1007 	 */
1008 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1009 		if (errno != ENOENT) {
1010 			zperror(doorpath, B_FALSE);
1011 			goto out;
1012 		}
1013 	} else {
1014 		if (door_info(doorfd, &info) == 0 &&
1015 		    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1016 			error = Z_OK;
1017 			(void) close(doorfd);
1018 			goto out;
1019 		}
1020 		(void) close(doorfd);
1021 	}
1022 
1023 	if ((child_pid = fork()) == -1) {
1024 		zperror(gettext("could not fork"), B_FALSE);
1025 		goto out;
1026 	} else if (child_pid == 0) {
1027 		const char *argv[6], **ap;
1028 
1029 		/* child process */
1030 		prepare_audit_context();
1031 
1032 		ap = argv;
1033 		*ap++ = "zoneadmd";
1034 		*ap++ = "-z";
1035 		*ap++ = zone_name;
1036 		if (zonecfg_in_alt_root()) {
1037 			*ap++ = "-R";
1038 			*ap++ = zonecfg_get_root();
1039 		}
1040 		*ap = NULL;
1041 
1042 		(void) execv("/usr/lib/zones/zoneadmd", (char * const *)argv);
1043 		zperror(gettext("could not exec zoneadmd"), B_FALSE);
1044 		_exit(Z_ERR);
1045 	} else {
1046 		/* parent process */
1047 		pid_t retval;
1048 		int pstatus = 0;
1049 
1050 		do {
1051 			retval = waitpid(child_pid, &pstatus, 0);
1052 		} while (retval != child_pid);
1053 		if (WIFSIGNALED(pstatus) || (WIFEXITED(pstatus) &&
1054 		    WEXITSTATUS(pstatus) != 0)) {
1055 			zerror(gettext("could not start %s"), "zoneadmd");
1056 			goto out;
1057 		}
1058 	}
1059 	error = Z_OK;
1060 out:
1061 	release_lock_file(lockfd);
1062 	return (error);
1063 }
1064 
1065 static int
1066 ping_zoneadmd(const char *zone_name)
1067 {
1068 	char doorpath[PATH_MAX];
1069 	int doorfd;
1070 	struct door_info info;
1071 
1072 	if (!get_doorname(zone_name, doorpath))
1073 		return (Z_ERR);
1074 
1075 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1076 		return (Z_ERR);
1077 	}
1078 	if (door_info(doorfd, &info) == 0 &&
1079 	    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1080 		(void) close(doorfd);
1081 		return (Z_OK);
1082 	}
1083 	(void) close(doorfd);
1084 	return (Z_ERR);
1085 }
1086 
1087 static int
1088 call_zoneadmd(const char *zone_name, zone_cmd_arg_t *arg)
1089 {
1090 	char doorpath[PATH_MAX];
1091 	int doorfd, result;
1092 	door_arg_t darg;
1093 
1094 	zoneid_t zoneid;
1095 	uint64_t uniqid = 0;
1096 
1097 	zone_cmd_rval_t *rvalp;
1098 	size_t rlen;
1099 	char *cp, *errbuf;
1100 
1101 	rlen = getpagesize();
1102 	if ((rvalp = malloc(rlen)) == NULL) {
1103 		zerror(gettext("failed to allocate %lu bytes: %s"), rlen,
1104 		    strerror(errno));
1105 		return (-1);
1106 	}
1107 
1108 	if ((zoneid = getzoneidbyname(zone_name)) != ZONE_ID_UNDEFINED) {
1109 		(void) zone_getattr(zoneid, ZONE_ATTR_UNIQID, &uniqid,
1110 		    sizeof (uniqid));
1111 	}
1112 	arg->uniqid = uniqid;
1113 	(void) strlcpy(arg->locale, locale, sizeof (arg->locale));
1114 	if (!get_doorname(zone_name, doorpath)) {
1115 		zerror(gettext("alternate root path is too long"));
1116 		free(rvalp);
1117 		return (-1);
1118 	}
1119 
1120 	/*
1121 	 * Loop trying to start zoneadmd; if something goes seriously
1122 	 * wrong we break out and fail.
1123 	 */
1124 	for (;;) {
1125 		if (start_zoneadmd(zone_name) != Z_OK)
1126 			break;
1127 
1128 		if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1129 			zperror(gettext("failed to open zone door"), B_FALSE);
1130 			break;
1131 		}
1132 
1133 		darg.data_ptr = (char *)arg;
1134 		darg.data_size = sizeof (*arg);
1135 		darg.desc_ptr = NULL;
1136 		darg.desc_num = 0;
1137 		darg.rbuf = (char *)rvalp;
1138 		darg.rsize = rlen;
1139 		if (door_call(doorfd, &darg) != 0) {
1140 			(void) close(doorfd);
1141 			/*
1142 			 * We'll get EBADF if the door has been revoked.
1143 			 */
1144 			if (errno != EBADF) {
1145 				zperror(gettext("door_call failed"), B_FALSE);
1146 				break;
1147 			}
1148 			continue;	/* take another lap */
1149 		}
1150 		(void) close(doorfd);
1151 
1152 		if (darg.data_size == 0) {
1153 			/* Door server is going away; kick it again. */
1154 			continue;
1155 		}
1156 
1157 		errbuf = rvalp->errbuf;
1158 		while (*errbuf != '\0') {
1159 			/*
1160 			 * Remove any newlines since zerror()
1161 			 * will append one automatically.
1162 			 */
1163 			cp = strchr(errbuf, '\n');
1164 			if (cp != NULL)
1165 				*cp = '\0';
1166 			zerror("%s", errbuf);
1167 			if (cp == NULL)
1168 				break;
1169 			errbuf = cp + 1;
1170 		}
1171 		result = rvalp->rval == 0 ? 0 : -1;
1172 		free(rvalp);
1173 		return (result);
1174 	}
1175 
1176 	free(rvalp);
1177 	return (-1);
1178 }
1179 
1180 static int
1181 ready_func(int argc, char *argv[])
1182 {
1183 	zone_cmd_arg_t zarg;
1184 	int arg;
1185 
1186 	if (zonecfg_in_alt_root()) {
1187 		zerror(gettext("cannot ready zone in alternate root"));
1188 		return (Z_ERR);
1189 	}
1190 
1191 	optind = 0;
1192 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1193 		switch (arg) {
1194 		case '?':
1195 			sub_usage(SHELP_READY, CMD_READY);
1196 			return (optopt == '?' ? Z_OK : Z_USAGE);
1197 		default:
1198 			sub_usage(SHELP_READY, CMD_READY);
1199 			return (Z_USAGE);
1200 		}
1201 	}
1202 	if (argc > optind) {
1203 		sub_usage(SHELP_READY, CMD_READY);
1204 		return (Z_USAGE);
1205 	}
1206 	if (sanity_check(target_zone, CMD_READY, B_FALSE, B_FALSE) != Z_OK)
1207 		return (Z_ERR);
1208 	if (verify_details(CMD_READY) != Z_OK)
1209 		return (Z_ERR);
1210 
1211 	zarg.cmd = Z_READY;
1212 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1213 		zerror(gettext("call to %s failed"), "zoneadmd");
1214 		return (Z_ERR);
1215 	}
1216 	return (Z_OK);
1217 }
1218 
1219 static int
1220 boot_func(int argc, char *argv[])
1221 {
1222 	zone_cmd_arg_t zarg;
1223 	int arg;
1224 
1225 	if (zonecfg_in_alt_root()) {
1226 		zerror(gettext("cannot boot zone in alternate root"));
1227 		return (Z_ERR);
1228 	}
1229 
1230 	zarg.bootbuf[0] = '\0';
1231 
1232 	/*
1233 	 * At the current time, the only supported subargument to the
1234 	 * "boot" subcommand is "-s" which specifies a single-user boot.
1235 	 * In the future, other boot arguments should be supported
1236 	 * including "-m" for specifying alternate smf(5) milestones.
1237 	 */
1238 	optind = 0;
1239 	if ((arg = getopt(argc, argv, "?s")) != EOF) {
1240 		switch (arg) {
1241 		case '?':
1242 			sub_usage(SHELP_BOOT, CMD_BOOT);
1243 			return (optopt == '?' ? Z_OK : Z_USAGE);
1244 		case 's':
1245 			(void) strlcpy(zarg.bootbuf, "-s",
1246 			    sizeof (zarg.bootbuf));
1247 			break;
1248 		default:
1249 			sub_usage(SHELP_BOOT, CMD_BOOT);
1250 			return (Z_USAGE);
1251 		}
1252 	}
1253 	if (argc > optind) {
1254 		sub_usage(SHELP_BOOT, CMD_BOOT);
1255 		return (Z_USAGE);
1256 	}
1257 	if (sanity_check(target_zone, CMD_BOOT, B_FALSE, B_FALSE) != Z_OK)
1258 		return (Z_ERR);
1259 	if (verify_details(CMD_BOOT) != Z_OK)
1260 		return (Z_ERR);
1261 	zarg.cmd = Z_BOOT;
1262 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1263 		zerror(gettext("call to %s failed"), "zoneadmd");
1264 		return (Z_ERR);
1265 	}
1266 	return (Z_OK);
1267 }
1268 
1269 static void
1270 fake_up_local_zone(zoneid_t zid, zone_entry_t *zeptr)
1271 {
1272 	ssize_t result;
1273 
1274 	zeptr->zid = zid;
1275 	/*
1276 	 * Since we're looking up our own (non-global) zone name,
1277 	 * we can be assured that it will succeed.
1278 	 */
1279 	result = getzonenamebyid(zid, zeptr->zname, sizeof (zeptr->zname));
1280 	assert(result >= 0);
1281 	(void) strlcpy(zeptr->zroot, "/", sizeof (zeptr->zroot));
1282 	zeptr->zstate_str = "running";
1283 }
1284 
1285 static int
1286 list_func(int argc, char *argv[])
1287 {
1288 	zone_entry_t *zentp, zent;
1289 	int arg, retv;
1290 	boolean_t output = B_FALSE, verbose = B_FALSE, parsable = B_FALSE;
1291 	zone_state_t min_state = ZONE_STATE_RUNNING;
1292 	zoneid_t zone_id = getzoneid();
1293 
1294 	if (target_zone == NULL) {
1295 		/* all zones: default view to running but allow override */
1296 		optind = 0;
1297 		while ((arg = getopt(argc, argv, "?cipv")) != EOF) {
1298 			switch (arg) {
1299 			case '?':
1300 				sub_usage(SHELP_LIST, CMD_LIST);
1301 				return (optopt == '?' ? Z_OK : Z_USAGE);
1302 			case 'c':
1303 				min_state = ZONE_STATE_CONFIGURED;
1304 				break;
1305 			case 'i':
1306 				min_state = ZONE_STATE_INSTALLED;
1307 				break;
1308 			case 'p':
1309 				parsable = B_TRUE;
1310 				break;
1311 			case 'v':
1312 				verbose = B_TRUE;
1313 				break;
1314 			default:
1315 				sub_usage(SHELP_LIST, CMD_LIST);
1316 				return (Z_USAGE);
1317 			}
1318 		}
1319 		if (parsable && verbose) {
1320 			zerror(gettext("%s -p and -v are mutually exclusive."),
1321 			    cmd_to_str(CMD_LIST));
1322 			return (Z_ERR);
1323 		}
1324 		if (zone_id == GLOBAL_ZONEID) {
1325 			retv = zone_print_list(min_state, verbose, parsable);
1326 		} else {
1327 			retv = Z_OK;
1328 			fake_up_local_zone(zone_id, &zent);
1329 			zone_print(&zent, verbose, parsable);
1330 		}
1331 		return (retv);
1332 	}
1333 
1334 	/*
1335 	 * Specific target zone: disallow -i/-c suboptions.
1336 	 */
1337 	optind = 0;
1338 	while ((arg = getopt(argc, argv, "?pv")) != EOF) {
1339 		switch (arg) {
1340 		case '?':
1341 			sub_usage(SHELP_LIST, CMD_LIST);
1342 			return (optopt == '?' ? Z_OK : Z_USAGE);
1343 		case 'p':
1344 			parsable = B_TRUE;
1345 			break;
1346 		case 'v':
1347 			verbose = B_TRUE;
1348 			break;
1349 		default:
1350 			sub_usage(SHELP_LIST, CMD_LIST);
1351 			return (Z_USAGE);
1352 		}
1353 	}
1354 	if (parsable && verbose) {
1355 		zerror(gettext("%s -p and -v are mutually exclusive."),
1356 		    cmd_to_str(CMD_LIST));
1357 		return (Z_ERR);
1358 	}
1359 	if (argc > optind) {
1360 		sub_usage(SHELP_LIST, CMD_LIST);
1361 		return (Z_USAGE);
1362 	}
1363 	if (zone_id != GLOBAL_ZONEID) {
1364 		fake_up_local_zone(zone_id, &zent);
1365 		/*
1366 		 * main() will issue a Z_NO_ZONE error if it cannot get an
1367 		 * id for target_zone, which in a non-global zone should
1368 		 * happen for any zone name except `zonename`.  Thus we
1369 		 * assert() that here but don't otherwise check.
1370 		 */
1371 		assert(strcmp(zent.zname, target_zone) == 0);
1372 		zone_print(&zent, verbose, parsable);
1373 		output = B_TRUE;
1374 	} else if ((zentp = lookup_running_zone(target_zone)) != NULL) {
1375 		zone_print(zentp, verbose, parsable);
1376 		output = B_TRUE;
1377 	} else if (lookup_zone_info(target_zone, ZONE_ID_UNDEFINED,
1378 	    &zent) == Z_OK) {
1379 		zone_print(&zent, verbose, parsable);
1380 		output = B_TRUE;
1381 	}
1382 	return (output ? Z_OK : Z_ERR);
1383 }
1384 
1385 static void
1386 sigterm(int sig)
1387 {
1388 	/*
1389 	 * Ignore SIG{INT,TERM}, so we don't end up in an infinite loop,
1390 	 * then propagate the signal to our process group.
1391 	 */
1392 	(void) sigset(SIGINT, SIG_IGN);
1393 	(void) sigset(SIGTERM, SIG_IGN);
1394 	(void) kill(0, sig);
1395 	child_killed = B_TRUE;
1396 }
1397 
1398 static int
1399 do_subproc(char *cmdbuf)
1400 {
1401 	char inbuf[1024];	/* arbitrary large amount */
1402 	FILE *file;
1403 
1404 	child_killed = B_FALSE;
1405 	/*
1406 	 * We use popen(3c) to launch child processes for [un]install;
1407 	 * this library call does not return a PID, so we have to kill
1408 	 * the whole process group.  To avoid killing our parent, we
1409 	 * become a process group leader here.  But doing so can wreak
1410 	 * havoc with reading from stdin when launched by a non-job-control
1411 	 * shell, so we close stdin and reopen it as /dev/null first.
1412 	 */
1413 	(void) close(STDIN_FILENO);
1414 	(void) open("/dev/null", O_RDONLY);
1415 	(void) setpgid(0, 0);
1416 	(void) sigset(SIGINT, sigterm);
1417 	(void) sigset(SIGTERM, sigterm);
1418 	file = popen(cmdbuf, "r");
1419 	for (;;) {
1420 		if (child_killed || fgets(inbuf, sizeof (inbuf), file) == NULL)
1421 			break;
1422 		(void) fputs(inbuf, stdout);
1423 	}
1424 	(void) sigset(SIGINT, SIG_DFL);
1425 	(void) sigset(SIGTERM, SIG_DFL);
1426 	return (pclose(file));
1427 }
1428 
1429 static int
1430 subproc_status(const char *cmd, int status)
1431 {
1432 	if (WIFEXITED(status)) {
1433 		int exit_code = WEXITSTATUS(status);
1434 
1435 		if (exit_code == 0)
1436 			return (Z_OK);
1437 		zerror(gettext("'%s' failed with exit code %d."), cmd,
1438 		    exit_code);
1439 	} else if (WIFSIGNALED(status)) {
1440 		int signal = WTERMSIG(status);
1441 		char sigstr[SIG2STR_MAX];
1442 
1443 		if (sig2str(signal, sigstr) == 0) {
1444 			zerror(gettext("'%s' terminated by signal SIG%s."), cmd,
1445 			    sigstr);
1446 		} else {
1447 			zerror(gettext("'%s' terminated by an unknown signal."),
1448 			    cmd);
1449 		}
1450 	} else {
1451 		zerror(gettext("'%s' failed for unknown reasons."), cmd);
1452 	}
1453 	return (Z_ERR);
1454 }
1455 
1456 /*
1457  * Various sanity checks; make sure:
1458  * 1. We're in the global zone.
1459  * 2. The calling user has sufficient privilege.
1460  * 3. The target zone is neither the global zone nor anything starting with
1461  *    "SUNW".
1462  * 4a. If we're looking for a 'not running' (i.e., configured or installed)
1463  *     zone, the name service knows about it.
1464  * 4b. For some operations which expect a zone not to be running, that it is
1465  *     not already running (or ready).
1466  */
1467 static int
1468 sanity_check(char *zone, int cmd_num, boolean_t running,
1469     boolean_t unsafe_when_running)
1470 {
1471 	zone_entry_t *zent;
1472 	priv_set_t *privset;
1473 	zone_state_t state;
1474 	char kernzone[ZONENAME_MAX];
1475 	FILE *fp;
1476 
1477 	if (getzoneid() != GLOBAL_ZONEID) {
1478 		zerror(gettext("must be in the global zone to %s a zone."),
1479 		    cmd_to_str(cmd_num));
1480 		return (Z_ERR);
1481 	}
1482 
1483 	if ((privset = priv_allocset()) == NULL) {
1484 		zerror(gettext("%s failed"), "priv_allocset");
1485 		return (Z_ERR);
1486 	}
1487 
1488 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
1489 		zerror(gettext("%s failed"), "getppriv");
1490 		priv_freeset(privset);
1491 		return (Z_ERR);
1492 	}
1493 
1494 	if (priv_isfullset(privset) == B_FALSE) {
1495 		zerror(gettext("only a privileged user may %s a zone."),
1496 		    cmd_to_str(cmd_num));
1497 		priv_freeset(privset);
1498 		return (Z_ERR);
1499 	}
1500 	priv_freeset(privset);
1501 
1502 	if (zone == NULL) {
1503 		zerror(gettext("no zone specified"));
1504 		return (Z_ERR);
1505 	}
1506 
1507 	if (strcmp(zone, GLOBAL_ZONENAME) == 0) {
1508 		zerror(gettext("%s operation is invalid for the global zone."),
1509 		    cmd_to_str(cmd_num));
1510 		return (Z_ERR);
1511 	}
1512 
1513 	if (strncmp(zone, "SUNW", 4) == 0) {
1514 		zerror(gettext("%s operation is invalid for zones starting "
1515 		    "with SUNW."), cmd_to_str(cmd_num));
1516 		return (Z_ERR);
1517 	}
1518 
1519 	if (!zonecfg_in_alt_root()) {
1520 		zent = lookup_running_zone(zone);
1521 	} else if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
1522 		zent = NULL;
1523 	} else {
1524 		if (zonecfg_find_scratch(fp, zone, zonecfg_get_root(),
1525 		    kernzone, sizeof (kernzone)) == 0)
1526 			zent = lookup_running_zone(kernzone);
1527 		else
1528 			zent = NULL;
1529 		zonecfg_close_scratch(fp);
1530 	}
1531 
1532 	/*
1533 	 * Look up from the kernel for 'running' zones.
1534 	 */
1535 	if (running) {
1536 		if (zent == NULL) {
1537 			zerror(gettext("not running"));
1538 			return (Z_ERR);
1539 		}
1540 	} else {
1541 		int err;
1542 
1543 		if (unsafe_when_running && zent != NULL) {
1544 			/* check whether the zone is ready or running */
1545 			if ((err = zone_get_state(zent->zname,
1546 			    &zent->zstate_num)) != Z_OK) {
1547 				errno = err;
1548 				zperror2(zent->zname,
1549 				    gettext("could not get state"));
1550 				/* can't tell, so hedge */
1551 				zent->zstate_str = "ready/running";
1552 			} else {
1553 				zent->zstate_str =
1554 				    zone_state_str(zent->zstate_num);
1555 			}
1556 			zerror(gettext("%s operation is invalid for %s zones."),
1557 			    cmd_to_str(cmd_num), zent->zstate_str);
1558 			return (Z_ERR);
1559 		}
1560 		if ((err = zone_get_state(zone, &state)) != Z_OK) {
1561 			errno = err;
1562 			zperror2(zone, gettext("could not get state"));
1563 			return (Z_ERR);
1564 		}
1565 		switch (cmd_num) {
1566 		case CMD_UNINSTALL:
1567 			if (state == ZONE_STATE_CONFIGURED) {
1568 				zerror(gettext("is already in state '%s'."),
1569 				    zone_state_str(ZONE_STATE_CONFIGURED));
1570 				return (Z_ERR);
1571 			}
1572 			break;
1573 		case CMD_INSTALL:
1574 			if (state == ZONE_STATE_INSTALLED) {
1575 				zerror(gettext("is already %s."),
1576 				    zone_state_str(ZONE_STATE_INSTALLED));
1577 				return (Z_ERR);
1578 			} else if (state == ZONE_STATE_INCOMPLETE) {
1579 				zerror(gettext("zone is %s; %s required."),
1580 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1581 				    cmd_to_str(CMD_UNINSTALL));
1582 				return (Z_ERR);
1583 			}
1584 			break;
1585 		case CMD_READY:
1586 		case CMD_BOOT:
1587 		case CMD_MOUNT:
1588 			if (state < ZONE_STATE_INSTALLED) {
1589 				zerror(gettext("must be %s before %s."),
1590 				    zone_state_str(ZONE_STATE_INSTALLED),
1591 				    cmd_to_str(cmd_num));
1592 				return (Z_ERR);
1593 			}
1594 			break;
1595 		case CMD_VERIFY:
1596 			if (state == ZONE_STATE_INCOMPLETE) {
1597 				zerror(gettext("zone is %s; %s required."),
1598 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1599 				    cmd_to_str(CMD_UNINSTALL));
1600 				return (Z_ERR);
1601 			}
1602 			break;
1603 		case CMD_UNMOUNT:
1604 			if (state != ZONE_STATE_MOUNTED) {
1605 				zerror(gettext("must be %s before %s."),
1606 				    zone_state_str(ZONE_STATE_MOUNTED),
1607 				    cmd_to_str(cmd_num));
1608 				return (Z_ERR);
1609 			}
1610 			break;
1611 		}
1612 	}
1613 	return (Z_OK);
1614 }
1615 
1616 static int
1617 halt_func(int argc, char *argv[])
1618 {
1619 	zone_cmd_arg_t zarg;
1620 	int arg;
1621 
1622 	if (zonecfg_in_alt_root()) {
1623 		zerror(gettext("cannot halt zone in alternate root"));
1624 		return (Z_ERR);
1625 	}
1626 
1627 	optind = 0;
1628 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1629 		switch (arg) {
1630 		case '?':
1631 			sub_usage(SHELP_HALT, CMD_HALT);
1632 			return (optopt == '?' ? Z_OK : Z_USAGE);
1633 		default:
1634 			sub_usage(SHELP_HALT, CMD_HALT);
1635 			return (Z_USAGE);
1636 		}
1637 	}
1638 	if (argc > optind) {
1639 		sub_usage(SHELP_HALT, CMD_HALT);
1640 		return (Z_USAGE);
1641 	}
1642 	/*
1643 	 * zoneadmd should be the one to decide whether or not to proceed,
1644 	 * so even though it seems that the fourth parameter below should
1645 	 * perhaps be B_TRUE, it really shouldn't be.
1646 	 */
1647 	if (sanity_check(target_zone, CMD_HALT, B_FALSE, B_FALSE) != Z_OK)
1648 		return (Z_ERR);
1649 
1650 	zarg.cmd = Z_HALT;
1651 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
1652 }
1653 
1654 static int
1655 reboot_func(int argc, char *argv[])
1656 {
1657 	zone_cmd_arg_t zarg;
1658 	int arg;
1659 
1660 	if (zonecfg_in_alt_root()) {
1661 		zerror(gettext("cannot reboot zone in alternate root"));
1662 		return (Z_ERR);
1663 	}
1664 
1665 	optind = 0;
1666 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1667 		switch (arg) {
1668 		case '?':
1669 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
1670 			return (optopt == '?' ? Z_OK : Z_USAGE);
1671 		default:
1672 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
1673 			return (Z_USAGE);
1674 		}
1675 	}
1676 	if (argc > 0) {
1677 		sub_usage(SHELP_REBOOT, CMD_REBOOT);
1678 		return (Z_USAGE);
1679 	}
1680 	/*
1681 	 * zoneadmd should be the one to decide whether or not to proceed,
1682 	 * so even though it seems that the fourth parameter below should
1683 	 * perhaps be B_TRUE, it really shouldn't be.
1684 	 */
1685 	if (sanity_check(target_zone, CMD_REBOOT, B_TRUE, B_FALSE) != Z_OK)
1686 		return (Z_ERR);
1687 	if (verify_details(CMD_REBOOT) != Z_OK)
1688 		return (Z_ERR);
1689 
1690 	zarg.cmd = Z_REBOOT;
1691 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
1692 }
1693 
1694 static int
1695 verify_rctls(zone_dochandle_t handle)
1696 {
1697 	struct zone_rctltab rctltab;
1698 	size_t rbs = rctlblk_size();
1699 	rctlblk_t *rctlblk;
1700 	int error = Z_INVAL;
1701 
1702 	if ((rctlblk = malloc(rbs)) == NULL) {
1703 		zerror(gettext("failed to allocate %lu bytes: %s"), rbs,
1704 		    strerror(errno));
1705 		return (Z_NOMEM);
1706 	}
1707 
1708 	if (zonecfg_setrctlent(handle) != Z_OK) {
1709 		zerror(gettext("zonecfg_setrctlent failed"));
1710 		free(rctlblk);
1711 		return (error);
1712 	}
1713 
1714 	rctltab.zone_rctl_valptr = NULL;
1715 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
1716 		struct zone_rctlvaltab *rctlval;
1717 		const char *name = rctltab.zone_rctl_name;
1718 
1719 		if (!zonecfg_is_rctl(name)) {
1720 			zerror(gettext("WARNING: Ignoring unrecognized rctl "
1721 			    "'%s'."),  name);
1722 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1723 			rctltab.zone_rctl_valptr = NULL;
1724 			continue;
1725 		}
1726 
1727 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
1728 		    rctlval = rctlval->zone_rctlval_next) {
1729 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
1730 			    != Z_OK) {
1731 				zerror(gettext("invalid rctl value: "
1732 				    "(priv=%s,limit=%s,action%s)"),
1733 				    rctlval->zone_rctlval_priv,
1734 				    rctlval->zone_rctlval_limit,
1735 				    rctlval->zone_rctlval_action);
1736 				goto out;
1737 			}
1738 			if (!zonecfg_valid_rctl(name, rctlblk)) {
1739 				zerror(gettext("(priv=%s,limit=%s,action=%s) "
1740 				    "is not a valid value for rctl '%s'"),
1741 				    rctlval->zone_rctlval_priv,
1742 				    rctlval->zone_rctlval_limit,
1743 				    rctlval->zone_rctlval_action,
1744 				    name);
1745 				goto out;
1746 			}
1747 		}
1748 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1749 	}
1750 	rctltab.zone_rctl_valptr = NULL;
1751 	error = Z_OK;
1752 out:
1753 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1754 	(void) zonecfg_endrctlent(handle);
1755 	free(rctlblk);
1756 	return (error);
1757 }
1758 
1759 static int
1760 verify_pool(zone_dochandle_t handle)
1761 {
1762 	char poolname[MAXPATHLEN];
1763 	pool_conf_t *poolconf;
1764 	pool_t *pool;
1765 	int status;
1766 	int error;
1767 
1768 	/*
1769 	 * This ends up being very similar to the check done in zoneadmd.
1770 	 */
1771 	error = zonecfg_get_pool(handle, poolname, sizeof (poolname));
1772 	if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
1773 		/*
1774 		 * No pool specified.
1775 		 */
1776 		return (0);
1777 	}
1778 	if (error != Z_OK) {
1779 		zperror(gettext("Unable to retrieve pool name from "
1780 		    "configuration"), B_TRUE);
1781 		return (error);
1782 	}
1783 	/*
1784 	 * Don't do anything if pools aren't enabled.
1785 	 */
1786 	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
1787 		zerror(gettext("WARNING: pools facility not active; "
1788 		    "zone will not be bound to pool '%s'."), poolname);
1789 		return (Z_OK);
1790 	}
1791 	/*
1792 	 * Try to provide a sane error message if the requested pool doesn't
1793 	 * exist.  It isn't clear that pools-related failures should
1794 	 * necessarily translate to a failure to verify the zone configuration,
1795 	 * hence they are not considered errors.
1796 	 */
1797 	if ((poolconf = pool_conf_alloc()) == NULL) {
1798 		zerror(gettext("WARNING: pool_conf_alloc failed; "
1799 		    "using default pool"));
1800 		return (Z_OK);
1801 	}
1802 	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
1803 	    PO_SUCCESS) {
1804 		zerror(gettext("WARNING: pool_conf_open failed; "
1805 		    "using default pool"));
1806 		pool_conf_free(poolconf);
1807 		return (Z_OK);
1808 	}
1809 	pool = pool_get_pool(poolconf, poolname);
1810 	(void) pool_conf_close(poolconf);
1811 	pool_conf_free(poolconf);
1812 	if (pool == NULL) {
1813 		zerror(gettext("WARNING: pool '%s' not found. "
1814 		    "using default pool"), poolname);
1815 	}
1816 
1817 	return (Z_OK);
1818 }
1819 
1820 static int
1821 verify_ipd(zone_dochandle_t handle)
1822 {
1823 	int return_code = Z_OK;
1824 	struct zone_fstab fstab;
1825 	struct stat st;
1826 	char specdir[MAXPATHLEN];
1827 
1828 	if (zonecfg_setipdent(handle) != Z_OK) {
1829 		(void) fprintf(stderr, gettext("cannot verify "
1830 		    "inherit-pkg-dirs: unable to enumerate mounts\n"));
1831 		return (Z_ERR);
1832 	}
1833 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
1834 		/*
1835 		 * Verify fs_dir exists.
1836 		 */
1837 		(void) snprintf(specdir, sizeof (specdir), "%s%s",
1838 		    zonecfg_get_root(), fstab.zone_fs_dir);
1839 		if (stat(specdir, &st) != 0) {
1840 			(void) fprintf(stderr, gettext("cannot verify "
1841 			    "inherit-pkg-dir %s: %s\n"),
1842 			    fstab.zone_fs_dir, strerror(errno));
1843 			return_code = Z_ERR;
1844 		}
1845 		if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
1846 			(void) fprintf(stderr, gettext("cannot verify "
1847 			    "inherit-pkg-dir %s: NFS mounted file system.\n"
1848 			    "\tA local file system must be used.\n"),
1849 			    fstab.zone_fs_dir);
1850 			return_code = Z_ERR;
1851 		}
1852 	}
1853 	(void) zonecfg_endipdent(handle);
1854 
1855 	return (return_code);
1856 }
1857 
1858 static int
1859 verify_filesystems(zone_dochandle_t handle)
1860 {
1861 	int return_code = Z_OK;
1862 	struct zone_fstab fstab;
1863 	char cmdbuf[MAXPATHLEN];
1864 	struct stat st;
1865 
1866 	/*
1867 	 * No need to verify inherit-pkg-dir fs types, as their type is
1868 	 * implicitly lofs, which is known.  Therefore, the types are only
1869 	 * verified for regular filesystems below.
1870 	 *
1871 	 * Since the actual mount point is not known until the dependent mounts
1872 	 * are performed, we don't attempt any path validation here: that will
1873 	 * happen later when zoneadmd actually does the mounts.
1874 	 */
1875 	if (zonecfg_setfsent(handle) != Z_OK) {
1876 		(void) fprintf(stderr, gettext("cannot verify file-systems: "
1877 		    "unable to enumerate mounts\n"));
1878 		return (Z_ERR);
1879 	}
1880 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1881 		if (!zonecfg_valid_fs_type(fstab.zone_fs_type)) {
1882 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1883 			    "type %s is not allowed.\n"), fstab.zone_fs_dir,
1884 			    fstab.zone_fs_type);
1885 			return_code = Z_ERR;
1886 			goto next_fs;
1887 		}
1888 		/*
1889 		 * Verify /usr/lib/fs/<fstype>/mount exists.
1890 		 */
1891 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount",
1892 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
1893 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1894 			    "type %s is too long.\n"), fstab.zone_fs_dir,
1895 			    fstab.zone_fs_type);
1896 			return_code = Z_ERR;
1897 			goto next_fs;
1898 		}
1899 		if (stat(cmdbuf, &st) != 0) {
1900 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1901 			    "can't access %s: %s\n"), fstab.zone_fs_dir,
1902 			    cmdbuf, strerror(errno));
1903 			return_code = Z_ERR;
1904 			goto next_fs;
1905 		}
1906 		if (!S_ISREG(st.st_mode)) {
1907 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1908 			    "%s is not a regular file\n"), fstab.zone_fs_dir,
1909 			    cmdbuf);
1910 			return_code = Z_ERR;
1911 			goto next_fs;
1912 		}
1913 		/*
1914 		 * Verify /usr/lib/fs/<fstype>/fsck exists iff zone_fs_raw is
1915 		 * set.
1916 		 */
1917 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck",
1918 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
1919 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1920 			    "type %s is too long.\n"), fstab.zone_fs_dir,
1921 			    fstab.zone_fs_type);
1922 			return_code = Z_ERR;
1923 			goto next_fs;
1924 		}
1925 		if (fstab.zone_fs_raw[0] == '\0' && stat(cmdbuf, &st) == 0) {
1926 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1927 			    "must specify 'raw' device for %s file-systems\n"),
1928 			    fstab.zone_fs_dir, fstab.zone_fs_type);
1929 			return_code = Z_ERR;
1930 			goto next_fs;
1931 		}
1932 		if (fstab.zone_fs_raw[0] != '\0' &&
1933 		    (stat(cmdbuf, &st) != 0 || !S_ISREG(st.st_mode))) {
1934 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1935 			    "'raw' device specified but "
1936 			    "no fsck executable exists for %s\n"),
1937 			    fstab.zone_fs_dir, fstab.zone_fs_type);
1938 			return_code = Z_ERR;
1939 			goto next_fs;
1940 		}
1941 		/*
1942 		 * Verify fs_special and optionally fs_raw, exists.
1943 		 */
1944 		if (stat(fstab.zone_fs_special, &st) != 0) {
1945 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1946 			    "can't access %s: %s\n"), fstab.zone_fs_dir,
1947 			    fstab.zone_fs_special, strerror(errno));
1948 			return_code = Z_ERR;
1949 			goto next_fs;
1950 		}
1951 		if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
1952 			(void) fprintf(stderr, gettext("cannot verify "
1953 			    "fs %s: NFS mounted file system.\n"
1954 			    "\tA local file system must be used.\n"),
1955 			    fstab.zone_fs_special);
1956 			return_code = Z_ERR;
1957 			goto next_fs;
1958 		}
1959 		if (fstab.zone_fs_raw[0] != '\0' &&
1960 		    stat(fstab.zone_fs_raw, &st) != 0) {
1961 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1962 			    "can't access %s: %s\n"), fstab.zone_fs_dir,
1963 			    fstab.zone_fs_raw, strerror(errno));
1964 			return_code = Z_ERR;
1965 			goto next_fs;
1966 		}
1967 next_fs:
1968 		zonecfg_free_fs_option_list(fstab.zone_fs_options);
1969 	}
1970 	(void) zonecfg_endfsent(handle);
1971 
1972 	return (return_code);
1973 }
1974 
1975 const char *current_dataset;
1976 
1977 /*
1978  * Custom error handler for errors incurred as part of the checks below.  We
1979  * want to trim off the leading 'cannot open ...' to create a better error
1980  * message.  The only other way this can fail is if we fail to set the 'zoned'
1981  * property.  In this case we just pass the error on verbatim.
1982  */
1983 static void
1984 zfs_error_handler(const char *fmt, va_list ap)
1985 {
1986 	char buf[1024];
1987 
1988 	(void) vsnprintf(buf, sizeof (buf), fmt, ap);
1989 
1990 	if (strncmp(gettext("cannot open "), buf,
1991 	    strlen(gettext("cannot open "))) == 0)
1992 		(void) fprintf(stderr, gettext("cannot verify zfs "
1993 		    "dataset %s%s\n"), current_dataset, strchr(buf, ':'));
1994 	else
1995 		(void) fprintf(stderr, gettext("cannot verify zfs dataset "
1996 		    "%s: %s\n"), current_dataset, buf);
1997 }
1998 
1999 /* ARGSUSED */
2000 static int
2001 check_zvol(zfs_handle_t *zhp, void *unused)
2002 {
2003 	int ret;
2004 
2005 	if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
2006 		(void) fprintf(stderr, gettext("cannot verify zfs dataset %s: "
2007 		    "volumes cannot be specified as a zone dataset resource\n"),
2008 		    zfs_get_name(zhp));
2009 		ret = -1;
2010 	} else {
2011 		ret = zfs_iter_children(zhp, check_zvol, NULL);
2012 	}
2013 
2014 	zfs_close(zhp);
2015 
2016 	return (ret);
2017 }
2018 
2019 /*
2020  * Validate that the given dataset exists on the system, and that neither it nor
2021  * its children are zvols.
2022  *
2023  * Note that we don't do anything with the 'zoned' property here.  All
2024  * management is done in zoneadmd when the zone is actually rebooted.  This
2025  * allows us to automatically set the zoned property even when a zone is
2026  * rebooted by the administrator.
2027  */
2028 static int
2029 verify_datasets(zone_dochandle_t handle)
2030 {
2031 	int return_code = Z_OK;
2032 	struct zone_dstab dstab;
2033 	zfs_handle_t *zhp;
2034 	char propbuf[ZFS_MAXPROPLEN];
2035 	char source[ZFS_MAXNAMELEN];
2036 	zfs_source_t srctype;
2037 
2038 	if (zonecfg_setdsent(handle) != Z_OK) {
2039 		(void) fprintf(stderr, gettext("cannot verify zfs datasets: "
2040 		    "unable to enumerate datasets\n"));
2041 		return (Z_ERR);
2042 	}
2043 
2044 	zfs_set_error_handler(zfs_error_handler);
2045 
2046 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2047 
2048 		current_dataset = dstab.zone_dataset_name;
2049 
2050 		if ((zhp = zfs_open(dstab.zone_dataset_name,
2051 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
2052 			return_code = Z_ERR;
2053 			continue;
2054 		}
2055 
2056 		if (zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, propbuf,
2057 		    sizeof (propbuf), &srctype, source,
2058 		    sizeof (source), 0) == 0 &&
2059 		    (srctype == ZFS_SRC_INHERITED)) {
2060 			(void) fprintf(stderr, gettext("cannot verify zfs "
2061 			    "dataset %s: mountpoint cannot be inherited\n"),
2062 			    dstab.zone_dataset_name);
2063 			return_code = Z_ERR;
2064 			zfs_close(zhp);
2065 			continue;
2066 		}
2067 
2068 		if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
2069 			(void) fprintf(stderr, gettext("cannot verify zfs "
2070 			    "dataset %s: volumes cannot be specified as a "
2071 			    "zone dataset resource\n"),
2072 			    dstab.zone_dataset_name);
2073 			return_code = Z_ERR;
2074 		}
2075 
2076 		if (zfs_iter_children(zhp, check_zvol, NULL) != 0)
2077 			return_code = Z_ERR;
2078 
2079 		zfs_close(zhp);
2080 	}
2081 	(void) zonecfg_enddsent(handle);
2082 
2083 	return (return_code);
2084 }
2085 
2086 static int
2087 verify_details(int cmd_num)
2088 {
2089 	zone_dochandle_t handle;
2090 	struct zone_nwiftab nwiftab;
2091 	char zonepath[MAXPATHLEN], checkpath[MAXPATHLEN];
2092 	int return_code = Z_OK;
2093 	int err;
2094 	boolean_t in_alt_root;
2095 
2096 	if ((handle = zonecfg_init_handle()) == NULL) {
2097 		zperror(cmd_to_str(cmd_num), B_TRUE);
2098 		return (Z_ERR);
2099 	}
2100 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
2101 		errno = err;
2102 		zperror(cmd_to_str(cmd_num), B_TRUE);
2103 		zonecfg_fini_handle(handle);
2104 		return (Z_ERR);
2105 	}
2106 	if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
2107 	    Z_OK) {
2108 		errno = err;
2109 		zperror(cmd_to_str(cmd_num), B_TRUE);
2110 		zonecfg_fini_handle(handle);
2111 		return (Z_ERR);
2112 	}
2113 	/*
2114 	 * zonecfg_get_zonepath() gets its data from the XML repository.
2115 	 * Verify this against the index file, which is checked first by
2116 	 * zone_get_zonepath().  If they don't match, bail out.
2117 	 */
2118 	if ((err = zone_get_zonepath(target_zone, checkpath,
2119 	    sizeof (checkpath))) != Z_OK) {
2120 		errno = err;
2121 		zperror2(target_zone, gettext("could not get zone path"));
2122 		return (Z_ERR);
2123 	}
2124 	if (strcmp(zonepath, checkpath) != 0) {
2125 		(void) fprintf(stderr, gettext("The XML repository has "
2126 		    "zonepath '%s',\nbut the index file has zonepath '%s'.\n"
2127 		    "These must match, so fix the incorrect entry.\n"),
2128 		    zonepath, checkpath);
2129 		return (Z_ERR);
2130 	}
2131 	if (validate_zonepath(zonepath, cmd_num) != Z_OK) {
2132 		(void) fprintf(stderr, gettext("could not verify zonepath %s "
2133 		    "because of the above errors.\n"), zonepath);
2134 		return_code = Z_ERR;
2135 	}
2136 
2137 	in_alt_root = zonecfg_in_alt_root();
2138 	if (in_alt_root)
2139 		goto no_net;
2140 
2141 	if ((err = zonecfg_setnwifent(handle)) != Z_OK) {
2142 		errno = err;
2143 		zperror(cmd_to_str(cmd_num), B_TRUE);
2144 		zonecfg_fini_handle(handle);
2145 		return (Z_ERR);
2146 	}
2147 	while (zonecfg_getnwifent(handle, &nwiftab) == Z_OK) {
2148 		struct lifreq lifr;
2149 		sa_family_t af;
2150 		int so, res;
2151 
2152 		/* skip any loopback interfaces */
2153 		if (strcmp(nwiftab.zone_nwif_physical, "lo0") == 0)
2154 			continue;
2155 		if ((res = zonecfg_valid_net_address(nwiftab.zone_nwif_address,
2156 		    &lifr)) != Z_OK) {
2157 			(void) fprintf(stderr, gettext("could not verify %s "
2158 			    "%s=%s %s=%s: %s\n"), "net", "address",
2159 			    nwiftab.zone_nwif_address, "physical",
2160 			    nwiftab.zone_nwif_physical, zonecfg_strerror(res));
2161 			return_code = Z_ERR;
2162 			continue;
2163 		}
2164 		af = lifr.lifr_addr.ss_family;
2165 		(void) memset(&lifr, 0, sizeof (lifr));
2166 		(void) strlcpy(lifr.lifr_name, nwiftab.zone_nwif_physical,
2167 		    sizeof (lifr.lifr_name));
2168 		lifr.lifr_addr.ss_family = af;
2169 		if ((so = socket(af, SOCK_DGRAM, 0)) < 0) {
2170 			(void) fprintf(stderr, gettext("could not verify %s "
2171 			    "%s=%s %s=%s: could not get socket: %s\n"), "net",
2172 			    "address", nwiftab.zone_nwif_address, "physical",
2173 			    nwiftab.zone_nwif_physical, strerror(errno));
2174 			return_code = Z_ERR;
2175 			continue;
2176 		}
2177 		if (ioctl(so, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2178 			(void) fprintf(stderr,
2179 			    gettext("could not verify %s %s=%s %s=%s: %s\n"),
2180 			    "net", "address", nwiftab.zone_nwif_address,
2181 			    "physical", nwiftab.zone_nwif_physical,
2182 			    strerror(errno));
2183 			return_code = Z_ERR;
2184 		}
2185 		(void) close(so);
2186 	}
2187 	(void) zonecfg_endnwifent(handle);
2188 no_net:
2189 
2190 	if (verify_filesystems(handle) != Z_OK)
2191 		return_code = Z_ERR;
2192 	if (verify_ipd(handle) != Z_OK)
2193 		return_code = Z_ERR;
2194 	if (!in_alt_root && verify_rctls(handle) != Z_OK)
2195 		return_code = Z_ERR;
2196 	if (!in_alt_root && verify_pool(handle) != Z_OK)
2197 		return_code = Z_ERR;
2198 	if (!in_alt_root && verify_datasets(handle) != Z_OK)
2199 		return_code = Z_ERR;
2200 	zonecfg_fini_handle(handle);
2201 	if (return_code == Z_ERR)
2202 		(void) fprintf(stderr,
2203 		    gettext("%s: zone %s failed to verify\n"),
2204 		    execname, target_zone);
2205 	return (return_code);
2206 }
2207 
2208 static int
2209 verify_func(int argc, char *argv[])
2210 {
2211 	int arg;
2212 
2213 	optind = 0;
2214 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2215 		switch (arg) {
2216 		case '?':
2217 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2218 			return (optopt == '?' ? Z_OK : Z_USAGE);
2219 		default:
2220 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2221 			return (Z_USAGE);
2222 		}
2223 	}
2224 	if (argc > optind) {
2225 		sub_usage(SHELP_VERIFY, CMD_VERIFY);
2226 		return (Z_USAGE);
2227 	}
2228 	if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE) != Z_OK)
2229 		return (Z_ERR);
2230 	return (verify_details(CMD_VERIFY));
2231 }
2232 
2233 #define	LUCREATEZONE	"/usr/lib/lu/lucreatezone"
2234 
2235 static int
2236 install_func(int argc, char *argv[])
2237 {
2238 	/* 9: "exec " and " -z " */
2239 	char cmdbuf[sizeof (LUCREATEZONE) + ZONENAME_MAX + 9];
2240 	int lockfd;
2241 	int err, arg;
2242 	char zonepath[MAXPATHLEN];
2243 	int status;
2244 
2245 	if (zonecfg_in_alt_root()) {
2246 		zerror(gettext("cannot install zone in alternate root"));
2247 		return (Z_ERR);
2248 	}
2249 
2250 	optind = 0;
2251 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2252 		switch (arg) {
2253 		case '?':
2254 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
2255 			return (optopt == '?' ? Z_OK : Z_USAGE);
2256 		default:
2257 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
2258 			return (Z_USAGE);
2259 		}
2260 	}
2261 	if (argc > optind) {
2262 		sub_usage(SHELP_INSTALL, CMD_INSTALL);
2263 		return (Z_USAGE);
2264 	}
2265 	if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE) != Z_OK)
2266 		return (Z_ERR);
2267 	if (verify_details(CMD_INSTALL) != Z_OK)
2268 		return (Z_ERR);
2269 
2270 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
2271 		zerror(gettext("another %s may have an operation in progress."),
2272 		    "zoneadmd");
2273 		return (Z_ERR);
2274 	}
2275 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
2276 	if (err != Z_OK) {
2277 		errno = err;
2278 		zperror2(target_zone, gettext("could not set state"));
2279 		goto done;
2280 	}
2281 
2282 	/*
2283 	 * According to the Application Packaging Developer's Guide, a
2284 	 * "checkinstall" script when included in a package is executed as
2285 	 * the user "install", if such a user exists, or by the user
2286 	 * "nobody".  In order to support this dubious behavior, the path
2287 	 * to the zone being constructed is opened up during the life of
2288 	 * the command laying down the zone's root file system.  Once this
2289 	 * has completed, regardless of whether it was successful, the
2290 	 * path to the zone is again restricted.
2291 	 */
2292 	if ((err = zone_get_zonepath(target_zone, zonepath,
2293 	    sizeof (zonepath))) != Z_OK) {
2294 		errno = err;
2295 		zperror2(target_zone, gettext("could not get zone path"));
2296 		goto done;
2297 	}
2298 	if (chmod(zonepath, DEFAULT_DIR_MODE) != 0) {
2299 		zperror(zonepath, B_FALSE);
2300 		err = Z_ERR;
2301 		goto done;
2302 	}
2303 
2304 	/*
2305 	 * "exec" the command so that the returned status is that of
2306 	 * LUCREATEZONE and not the shell.
2307 	 */
2308 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " LUCREATEZONE " -z %s",
2309 	    target_zone);
2310 	status = do_subproc(cmdbuf);
2311 	if (chmod(zonepath, S_IRWXU) != 0) {
2312 		zperror(zonepath, B_FALSE);
2313 		err = Z_ERR;
2314 		goto done;
2315 	}
2316 	if ((err = subproc_status(LUCREATEZONE, status)) != Z_OK)
2317 		goto done;
2318 
2319 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
2320 		errno = err;
2321 		zperror2(target_zone, gettext("could not set state"));
2322 		goto done;
2323 	}
2324 
2325 done:
2326 	release_lock_file(lockfd);
2327 	return ((err == Z_OK) ? Z_OK : Z_ERR);
2328 }
2329 
2330 /*
2331  * On input, TRUE => yes, FALSE => no.
2332  * On return, TRUE => 1, FALSE => 0, could not ask => -1.
2333  */
2334 
2335 static int
2336 ask_yesno(boolean_t default_answer, const char *question)
2337 {
2338 	char line[64];	/* should be large enough to answer yes or no */
2339 
2340 	if (!isatty(STDIN_FILENO))
2341 		return (-1);
2342 	for (;;) {
2343 		(void) printf("%s (%s)? ", question,
2344 		    default_answer ? "[y]/n" : "y/[n]");
2345 		if (fgets(line, sizeof (line), stdin) == NULL ||
2346 		    line[0] == '\n')
2347 			return (default_answer ? 1 : 0);
2348 		if (tolower(line[0]) == 'y')
2349 			return (1);
2350 		if (tolower(line[0]) == 'n')
2351 			return (0);
2352 	}
2353 }
2354 
2355 #define	RMCOMMAND	"/usr/bin/rm -rf"
2356 
2357 /* ARGSUSED */
2358 int
2359 zfm_print(const char *p, void *r) {
2360 	zerror("  %s\n", p);
2361 	return (0);
2362 }
2363 
2364 static int
2365 uninstall_func(int argc, char *argv[])
2366 {
2367 	/* 6: "exec " and " " */
2368 	char cmdbuf[sizeof (RMCOMMAND) + MAXPATHLEN + 6];
2369 	char line[ZONENAME_MAX + 128];	/* Enough for "Are you sure ..." */
2370 	char rootpath[MAXPATHLEN], devpath[MAXPATHLEN];
2371 	boolean_t force = B_FALSE;
2372 	int lockfd, answer;
2373 	int err, arg;
2374 	int status;
2375 
2376 	if (zonecfg_in_alt_root()) {
2377 		zerror(gettext("cannot uninstall zone in alternate root"));
2378 		return (Z_ERR);
2379 	}
2380 
2381 	optind = 0;
2382 	while ((arg = getopt(argc, argv, "?F")) != EOF) {
2383 		switch (arg) {
2384 		case '?':
2385 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
2386 			return (optopt == '?' ? Z_OK : Z_USAGE);
2387 		case 'F':
2388 			force = B_TRUE;
2389 			break;
2390 		default:
2391 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
2392 			return (Z_USAGE);
2393 		}
2394 	}
2395 	if (argc > optind) {
2396 		sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
2397 		return (Z_USAGE);
2398 	}
2399 
2400 	if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE) != Z_OK)
2401 		return (Z_ERR);
2402 
2403 	if (!force) {
2404 		(void) snprintf(line, sizeof (line),
2405 		    gettext("Are you sure you want to %s zone %s"),
2406 		    cmd_to_str(CMD_UNINSTALL), target_zone);
2407 		if ((answer = ask_yesno(B_FALSE, line)) == 0) {
2408 			return (Z_OK);
2409 		} else if (answer == -1) {
2410 			zerror(gettext("Input not from terminal and -F "
2411 			    "not specified: %s not done."),
2412 			    cmd_to_str(CMD_UNINSTALL));
2413 			return (Z_ERR);
2414 		}
2415 	}
2416 
2417 	if ((err = zone_get_zonepath(target_zone, devpath,
2418 	    sizeof (devpath))) != Z_OK) {
2419 		errno = err;
2420 		zperror2(target_zone, gettext("could not get zone path"));
2421 		return (Z_ERR);
2422 	}
2423 	(void) strlcat(devpath, "/dev", sizeof (devpath));
2424 	if ((err = zone_get_rootpath(target_zone, rootpath,
2425 	    sizeof (rootpath))) != Z_OK) {
2426 		errno = err;
2427 		zperror2(target_zone, gettext("could not get root path"));
2428 		return (Z_ERR);
2429 	}
2430 
2431 	/*
2432 	 * If there seems to be a zoneadmd running for this zone, call it
2433 	 * to tell it that an uninstall is happening; if all goes well it
2434 	 * will then shut itself down.
2435 	 */
2436 	if (ping_zoneadmd(target_zone) == Z_OK) {
2437 		zone_cmd_arg_t zarg;
2438 		zarg.cmd = Z_NOTE_UNINSTALLING;
2439 		/* we don't care too much if this fails... just plow on */
2440 		(void) call_zoneadmd(target_zone, &zarg);
2441 	}
2442 
2443 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
2444 		zerror(gettext("another %s may have an operation in progress."),
2445 		    "zoneadmd");
2446 		return (Z_ERR);
2447 	}
2448 
2449 	/* Don't uninstall the zone if anything is mounted there */
2450 	err = zonecfg_find_mounts(rootpath, NULL, NULL);
2451 	if (err) {
2452 		zerror(gettext("These file-systems are mounted on "
2453 			"subdirectories of %s.\n"), rootpath);
2454 		(void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
2455 		return (Z_ERR);
2456 	}
2457 
2458 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
2459 	if (err != Z_OK) {
2460 		errno = err;
2461 		zperror2(target_zone, gettext("could not set state"));
2462 		goto bad;
2463 	}
2464 
2465 	/*
2466 	 * "exec" the command so that the returned status is that of
2467 	 * RMCOMMAND and not the shell.
2468 	 */
2469 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
2470 	    devpath);
2471 	status = do_subproc(cmdbuf);
2472 	if ((err = subproc_status(RMCOMMAND, status)) != Z_OK)
2473 		goto bad;
2474 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
2475 	    rootpath);
2476 	status = do_subproc(cmdbuf);
2477 	if ((err = subproc_status(RMCOMMAND, status)) != Z_OK)
2478 		goto bad;
2479 	err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
2480 	if (err != Z_OK) {
2481 		errno = err;
2482 		zperror2(target_zone, gettext("could not reset state"));
2483 	}
2484 bad:
2485 	release_lock_file(lockfd);
2486 	return (err);
2487 }
2488 
2489 /* ARGSUSED */
2490 static int
2491 mount_func(int argc, char *argv[])
2492 {
2493 	zone_cmd_arg_t zarg;
2494 
2495 	if (argc > 0)
2496 		return (Z_USAGE);
2497 	if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE) != Z_OK)
2498 		return (Z_ERR);
2499 	if (verify_details(CMD_MOUNT) != Z_OK)
2500 		return (Z_ERR);
2501 
2502 	zarg.cmd = Z_MOUNT;
2503 	if (call_zoneadmd(target_zone, &zarg) != 0) {
2504 		zerror(gettext("call to %s failed"), "zoneadmd");
2505 		return (Z_ERR);
2506 	}
2507 	return (Z_OK);
2508 }
2509 
2510 /* ARGSUSED */
2511 static int
2512 unmount_func(int argc, char *argv[])
2513 {
2514 	zone_cmd_arg_t zarg;
2515 
2516 	if (argc > 0)
2517 		return (Z_USAGE);
2518 	if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE) != Z_OK)
2519 		return (Z_ERR);
2520 
2521 	zarg.cmd = Z_UNMOUNT;
2522 	if (call_zoneadmd(target_zone, &zarg) != 0) {
2523 		zerror(gettext("call to %s failed"), "zoneadmd");
2524 		return (Z_ERR);
2525 	}
2526 	return (Z_OK);
2527 }
2528 
2529 static int
2530 help_func(int argc, char *argv[])
2531 {
2532 	int arg, cmd_num;
2533 
2534 	if (argc == 0) {
2535 		(void) usage(B_TRUE);
2536 		return (Z_OK);
2537 	}
2538 	optind = 0;
2539 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2540 		switch (arg) {
2541 		case '?':
2542 			sub_usage(SHELP_HELP, CMD_HELP);
2543 			return (optopt == '?' ? Z_OK : Z_USAGE);
2544 		default:
2545 			sub_usage(SHELP_HELP, CMD_HELP);
2546 			return (Z_USAGE);
2547 		}
2548 	}
2549 	while (optind < argc) {
2550 		if ((cmd_num = cmd_match(argv[optind])) < 0) {
2551 			sub_usage(SHELP_HELP, CMD_HELP);
2552 			return (Z_USAGE);
2553 		}
2554 		sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
2555 		optind++;
2556 	}
2557 	return (Z_OK);
2558 }
2559 
2560 /*
2561  * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
2562  */
2563 
2564 static int
2565 cmd_match(char *cmd)
2566 {
2567 	int i;
2568 
2569 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
2570 		/* return only if there is an exact match */
2571 		if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
2572 			return (cmdtab[i].cmd_num);
2573 	}
2574 	return (-1);
2575 }
2576 
2577 static int
2578 parse_and_run(int argc, char *argv[])
2579 {
2580 	int i = cmd_match(argv[0]);
2581 
2582 	if (i < 0)
2583 		return (usage(B_FALSE));
2584 	return (cmdtab[i].handler(argc - 1, &(argv[1])));
2585 }
2586 
2587 static char *
2588 get_execbasename(char *execfullname)
2589 {
2590 	char *last_slash, *execbasename;
2591 
2592 	/* guard against '/' at end of command invocation */
2593 	for (;;) {
2594 		last_slash = strrchr(execfullname, '/');
2595 		if (last_slash == NULL) {
2596 			execbasename = execfullname;
2597 			break;
2598 		} else {
2599 			execbasename = last_slash + 1;
2600 			if (*execbasename == '\0') {
2601 				*last_slash = '\0';
2602 				continue;
2603 			}
2604 			break;
2605 		}
2606 	}
2607 	return (execbasename);
2608 }
2609 
2610 int
2611 main(int argc, char **argv)
2612 {
2613 	int arg;
2614 	zoneid_t zid;
2615 	struct stat st;
2616 
2617 	if ((locale = setlocale(LC_ALL, "")) == NULL)
2618 		locale = "C";
2619 	(void) textdomain(TEXT_DOMAIN);
2620 	setbuf(stdout, NULL);
2621 	(void) sigset(SIGHUP, SIG_IGN);
2622 	execname = get_execbasename(argv[0]);
2623 	target_zone = NULL;
2624 	if (chdir("/") != 0) {
2625 		zerror(gettext("could not change directory to /."));
2626 		exit(Z_ERR);
2627 	}
2628 
2629 	while ((arg = getopt(argc, argv, "?z:R:")) != EOF) {
2630 		switch (arg) {
2631 		case '?':
2632 			return (usage(B_TRUE));
2633 		case 'z':
2634 			target_zone = optarg;
2635 			break;
2636 		case 'R':	/* private option for admin/install use */
2637 			if (*optarg != '/') {
2638 				zerror(gettext("root path must be absolute."));
2639 				exit(Z_ERR);
2640 			}
2641 			if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
2642 				zerror(
2643 				    gettext("root path must be a directory."));
2644 				exit(Z_ERR);
2645 			}
2646 			zonecfg_set_root(optarg);
2647 			break;
2648 		default:
2649 			return (usage(B_FALSE));
2650 		}
2651 	}
2652 
2653 	if (optind >= argc)
2654 		return (usage(B_FALSE));
2655 	if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
2656 		errno = Z_NO_ZONE;
2657 		zperror(target_zone, B_TRUE);
2658 		exit(Z_ERR);
2659 	}
2660 	return (parse_and_run(argc - optind, &argv[optind]));
2661 }
2662