xref: /titanic_50/usr/src/cmd/zoneadm/zoneadm.c (revision f430f59ab82e479697d158ab37aa51e306625e9a)
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 2006 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 #include <fnmatch.h>
75 
76 #include <pool.h>
77 #include <sys/pool.h>
78 
79 #define	MAXARGS	8
80 
81 /* Reflects kernel zone entries */
82 typedef struct zone_entry {
83 	zoneid_t	zid;
84 	char		zname[ZONENAME_MAX];
85 	char		*zstate_str;
86 	zone_state_t	zstate_num;
87 	char		zroot[MAXPATHLEN];
88 } zone_entry_t;
89 
90 static zone_entry_t *zents;
91 static size_t nzents;
92 
93 #if !defined(TEXT_DOMAIN)		/* should be defined by cc -D */
94 #define	TEXT_DOMAIN	"SYS_TEST"	/* Use this only if it wasn't */
95 #endif
96 
97 #define	Z_ERR	1
98 #define	Z_USAGE	2
99 
100 /* 0755 is the default directory mode. */
101 #define	DEFAULT_DIR_MODE \
102 	(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
103 
104 #define	CMD_HELP	0
105 #define	CMD_BOOT	1
106 #define	CMD_HALT	2
107 #define	CMD_READY	3
108 #define	CMD_REBOOT	4
109 #define	CMD_LIST	5
110 #define	CMD_VERIFY	6
111 #define	CMD_INSTALL	7
112 #define	CMD_UNINSTALL	8
113 #define	CMD_MOUNT	9
114 #define	CMD_UNMOUNT	10
115 #define	CMD_CLONE	11
116 #define	CMD_MOVE	12
117 
118 #define	CMD_MIN		CMD_HELP
119 #define	CMD_MAX		CMD_MOVE
120 
121 #define	SINGLE_USER_RETRY	30
122 
123 struct cmd {
124 	uint_t	cmd_num;				/* command number */
125 	char	*cmd_name;				/* command name */
126 	char	*short_usage;				/* short form help */
127 	int	(*handler)(int argc, char *argv[]);	/* function to call */
128 
129 };
130 
131 #define	SHELP_HELP	"help"
132 #define	SHELP_BOOT	"boot [-s]"
133 #define	SHELP_HALT	"halt"
134 #define	SHELP_READY	"ready"
135 #define	SHELP_REBOOT	"reboot"
136 #define	SHELP_LIST	"list [-cipv]"
137 #define	SHELP_VERIFY	"verify"
138 #define	SHELP_INSTALL	"install"
139 #define	SHELP_UNINSTALL	"uninstall [-F]"
140 #define	SHELP_CLONE	"clone [-m method] zonename"
141 #define	SHELP_MOVE	"move zonepath"
142 
143 static int help_func(int argc, char *argv[]);
144 static int ready_func(int argc, char *argv[]);
145 static int boot_func(int argc, char *argv[]);
146 static int halt_func(int argc, char *argv[]);
147 static int reboot_func(int argc, char *argv[]);
148 static int list_func(int argc, char *argv[]);
149 static int verify_func(int argc, char *argv[]);
150 static int install_func(int argc, char *argv[]);
151 static int uninstall_func(int argc, char *argv[]);
152 static int mount_func(int argc, char *argv[]);
153 static int unmount_func(int argc, char *argv[]);
154 static int clone_func(int argc, char *argv[]);
155 static int move_func(int argc, char *argv[]);
156 static int sanity_check(char *zone, int cmd_num, boolean_t running,
157     boolean_t unsafe_when_running);
158 static int cmd_match(char *cmd);
159 static int verify_details(int);
160 
161 static struct cmd cmdtab[] = {
162 	{ CMD_HELP,		"help",		SHELP_HELP,	help_func },
163 	{ CMD_BOOT,		"boot",		SHELP_BOOT,	boot_func },
164 	{ CMD_HALT,		"halt",		SHELP_HALT,	halt_func },
165 	{ CMD_READY,		"ready",	SHELP_READY,	ready_func },
166 	{ CMD_REBOOT,		"reboot",	SHELP_REBOOT,	reboot_func },
167 	{ CMD_LIST,		"list",		SHELP_LIST,	list_func },
168 	{ CMD_VERIFY,		"verify",	SHELP_VERIFY,	verify_func },
169 	{ CMD_INSTALL,		"install",	SHELP_INSTALL,	install_func },
170 	{ CMD_UNINSTALL,	"uninstall",	SHELP_UNINSTALL,
171 	    uninstall_func },
172 	/* mount and unmount are private commands for admin/install */
173 	{ CMD_MOUNT,		"mount",	NULL,		mount_func },
174 	{ CMD_UNMOUNT,		"unmount",	NULL,		unmount_func },
175 	{ CMD_CLONE,		"clone",	SHELP_CLONE,	clone_func },
176 	{ CMD_MOVE,		"move",		SHELP_MOVE,	move_func }
177 };
178 
179 /* global variables */
180 
181 /* set early in main(), never modified thereafter, used all over the place */
182 static char *execname;
183 static char *target_zone;
184 static char *locale;
185 
186 /* used in do_subproc() and signal handler */
187 static volatile boolean_t child_killed;
188 
189 static char *
190 cmd_to_str(int cmd_num)
191 {
192 	assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
193 	return (cmdtab[cmd_num].cmd_name);
194 }
195 
196 /* This is a separate function because of gettext() wrapping. */
197 static char *
198 long_help(int cmd_num)
199 {
200 	assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
201 	switch (cmd_num) {
202 		case CMD_HELP:
203 			return (gettext("Print usage message."));
204 		case CMD_BOOT:
205 			return (gettext("Activates (boots) specified zone.  "
206 			    "The -s flag can be used\n\tto boot the zone in "
207 			    "the single-user state."));
208 		case CMD_HALT:
209 			return (gettext("Halts specified zone, bypassing "
210 			    "shutdown scripts and removing runtime\n\t"
211 			    "resources of the zone."));
212 		case CMD_READY:
213 			return (gettext("Prepares a zone for running "
214 			    "applications but does not start any user\n\t"
215 			    "processes in the zone."));
216 		case CMD_REBOOT:
217 			return (gettext("Restarts the zone (equivalent to a "
218 			    "halt / boot sequence).\n\tFails if the zone is "
219 			    "not active."));
220 		case CMD_LIST:
221 			return (gettext("Lists the current zones, or a "
222 			    "specific zone if indicated.  By default,\n\tall "
223 			    "running zones are listed, though this can be "
224 			    "expanded to all\n\tinstalled zones with the -i "
225 			    "option or all configured zones with the\n\t-c "
226 			    "option.  When used with the general -z <zone> "
227 			    "option, lists only the\n\tspecified zone, but "
228 			    "lists it regardless of its state, and the -i "
229 			    "and -c\n\toptions are disallowed.  The -v option "
230 			    "can be used to display verbose\n\tinformation: "
231 			    "zone name, id, current state, root directory and "
232 			    "options.\n\tThe -p option can be used to request "
233 			    "machine-parsable output.  The -v\n\tand -p "
234 			    "options are mutually exclusive.  If neither -v "
235 			    "nor -p is used,\n\tjust the zone name is "
236 			    "listed."));
237 		case CMD_VERIFY:
238 			return (gettext("Check to make sure the configuration "
239 			    "can safely be instantiated\n\ton the machine: "
240 			    "physical network interfaces exist, etc."));
241 		case CMD_INSTALL:
242 			return (gettext("Install the configuration on to the "
243 			    "system."));
244 		case CMD_UNINSTALL:
245 			return (gettext("Uninstall the configuration from the "
246 			    "system.  The -F flag can be used\n\tto force the "
247 			    "action."));
248 		case CMD_CLONE:
249 			return (gettext("Clone the installation of another "
250 			    "zone."));
251 		case CMD_MOVE:
252 			return (gettext("Move the zone to a new zonepath."));
253 		default:
254 			return ("");
255 	}
256 	/* NOTREACHED */
257 	return (NULL);
258 }
259 
260 /*
261  * Called with explicit B_TRUE when help is explicitly requested, B_FALSE for
262  * unexpected errors.
263  */
264 
265 static int
266 usage(boolean_t explicit)
267 {
268 	int i;
269 	FILE *fd = explicit ? stdout : stderr;
270 
271 	(void) fprintf(fd, "%s:\t%s help\n", gettext("usage"), execname);
272 	(void) fprintf(fd, "\t%s [-z <zone>] list\n", execname);
273 	(void) fprintf(fd, "\t%s -z <zone> <%s>\n", execname,
274 	    gettext("subcommand"));
275 	(void) fprintf(fd, "\n%s:\n\n", gettext("Subcommands"));
276 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
277 		if (cmdtab[i].short_usage == NULL)
278 			continue;
279 		(void) fprintf(fd, "%s\n", cmdtab[i].short_usage);
280 		if (explicit)
281 			(void) fprintf(fd, "\t%s\n\n", long_help(i));
282 	}
283 	if (!explicit)
284 		(void) fputs("\n", fd);
285 	return (Z_USAGE);
286 }
287 
288 static void
289 sub_usage(char *short_usage, int cmd_num)
290 {
291 	(void) fprintf(stderr, "%s:\t%s\n", gettext("usage"), short_usage);
292 	(void) fprintf(stderr, "\t%s\n", long_help(cmd_num));
293 }
294 
295 /*
296  * zperror() is like perror(3c) except that this also prints the executable
297  * name at the start of the message, and takes a boolean indicating whether
298  * to call libc'c strerror() or that from libzonecfg.
299  */
300 
301 static void
302 zperror(const char *str, boolean_t zonecfg_error)
303 {
304 	(void) fprintf(stderr, "%s: %s: %s\n", execname, str,
305 	    zonecfg_error ? zonecfg_strerror(errno) : strerror(errno));
306 }
307 
308 /*
309  * zperror2() is very similar to zperror() above, except it also prints a
310  * supplied zone name after the executable.
311  *
312  * All current consumers of this function want libzonecfg's strerror() rather
313  * than libc's; if this ever changes, this function can be made more generic
314  * like zperror() above.
315  */
316 
317 static void
318 zperror2(const char *zone, const char *str)
319 {
320 	(void) fprintf(stderr, "%s: %s: %s: %s\n", execname, zone, str,
321 	    zonecfg_strerror(errno));
322 }
323 
324 /* PRINTFLIKE1 */
325 static void
326 zerror(const char *fmt, ...)
327 {
328 	va_list alist;
329 
330 	va_start(alist, fmt);
331 	(void) fprintf(stderr, "%s: ", execname);
332 	if (target_zone != NULL)
333 		(void) fprintf(stderr, "zone '%s': ", target_zone);
334 	(void) vfprintf(stderr, fmt, alist);
335 	(void) fprintf(stderr, "\n");
336 	va_end(alist);
337 }
338 
339 static void *
340 safe_calloc(size_t nelem, size_t elsize)
341 {
342 	void *r = calloc(nelem, elsize);
343 
344 	if (r == NULL) {
345 		zerror(gettext("failed to allocate %lu bytes: %s"),
346 		    (ulong_t)nelem * elsize, strerror(errno));
347 		exit(Z_ERR);
348 	}
349 	return (r);
350 }
351 
352 static void
353 zone_print(zone_entry_t *zent, boolean_t verbose, boolean_t parsable)
354 {
355 	static boolean_t firsttime = B_TRUE;
356 
357 	assert(!(verbose && parsable));
358 	if (firsttime && verbose) {
359 		firsttime = B_FALSE;
360 		(void) printf("%*s %-16s %-14s %-30s\n", ZONEID_WIDTH, "ID",
361 		    "NAME", "STATUS", "PATH");
362 	}
363 	if (!verbose) {
364 		if (!parsable) {
365 			(void) printf("%s\n", zent->zname);
366 			return;
367 		}
368 		if (zent->zid == ZONE_ID_UNDEFINED)
369 			(void) printf("-");
370 		else
371 			(void) printf("%lu", zent->zid);
372 		(void) printf(":%s:%s:%s\n", zent->zname, zent->zstate_str,
373 		    zent->zroot);
374 		return;
375 	}
376 	if (zent->zstate_str != NULL) {
377 		if (zent->zid == ZONE_ID_UNDEFINED)
378 			(void) printf("%*s", ZONEID_WIDTH, "-");
379 		else
380 			(void) printf("%*lu", ZONEID_WIDTH, zent->zid);
381 		(void) printf(" %-16s %-14s %-30s\n", zent->zname,
382 		    zent->zstate_str, zent->zroot);
383 	}
384 }
385 
386 static int
387 lookup_zone_info(const char *zone_name, zoneid_t zid, zone_entry_t *zent)
388 {
389 	char root[MAXPATHLEN];
390 	int err;
391 
392 	(void) strlcpy(zent->zname, zone_name, sizeof (zent->zname));
393 	(void) strlcpy(zent->zroot, "???", sizeof (zent->zroot));
394 	zent->zstate_str = "???";
395 
396 	zent->zid = zid;
397 
398 	if ((err = zone_get_zonepath(zent->zname, root, sizeof (root))) !=
399 	    Z_OK) {
400 		errno = err;
401 		zperror2(zent->zname, gettext("could not get zone path"));
402 		return (Z_ERR);
403 	}
404 	(void) strlcpy(zent->zroot, root, sizeof (zent->zroot));
405 
406 	if ((err = zone_get_state(zent->zname, &zent->zstate_num)) != Z_OK) {
407 		errno = err;
408 		zperror2(zent->zname, gettext("could not get state"));
409 		return (Z_ERR);
410 	}
411 	zent->zstate_str = zone_state_str(zent->zstate_num);
412 
413 	return (Z_OK);
414 }
415 
416 /*
417  * fetch_zents() calls zone_list(2) to find out how many zones are running
418  * (which is stored in the global nzents), then calls zone_list(2) again
419  * to fetch the list of running zones (stored in the global zents).  This
420  * function may be called multiple times, so if zents is already set, we
421  * return immediately to save work.
422  */
423 
424 static int
425 fetch_zents(void)
426 {
427 	zoneid_t *zids = NULL;
428 	uint_t nzents_saved;
429 	int i, retv;
430 	FILE *fp;
431 	boolean_t inaltroot;
432 	zone_entry_t *zentp;
433 
434 	if (nzents > 0)
435 		return (Z_OK);
436 
437 	if (zone_list(NULL, &nzents) != 0) {
438 		zperror(gettext("failed to get zoneid list"), B_FALSE);
439 		return (Z_ERR);
440 	}
441 
442 again:
443 	if (nzents == 0)
444 		return (Z_OK);
445 
446 	zids = safe_calloc(nzents, sizeof (zoneid_t));
447 	nzents_saved = nzents;
448 
449 	if (zone_list(zids, &nzents) != 0) {
450 		zperror(gettext("failed to get zone list"), B_FALSE);
451 		free(zids);
452 		return (Z_ERR);
453 	}
454 	if (nzents != nzents_saved) {
455 		/* list changed, try again */
456 		free(zids);
457 		goto again;
458 	}
459 
460 	zents = safe_calloc(nzents, sizeof (zone_entry_t));
461 
462 	inaltroot = zonecfg_in_alt_root();
463 	if (inaltroot)
464 		fp = zonecfg_open_scratch("", B_FALSE);
465 	else
466 		fp = NULL;
467 	zentp = zents;
468 	retv = Z_OK;
469 	for (i = 0; i < nzents; i++) {
470 		char name[ZONENAME_MAX];
471 		char altname[ZONENAME_MAX];
472 
473 		if (getzonenamebyid(zids[i], name, sizeof (name)) < 0) {
474 			zperror(gettext("failed to get zone name"), B_FALSE);
475 			retv = Z_ERR;
476 			continue;
477 		}
478 		if (zonecfg_is_scratch(name)) {
479 			/* Ignore scratch zones by default */
480 			if (!inaltroot)
481 				continue;
482 			if (fp == NULL ||
483 			    zonecfg_reverse_scratch(fp, name, altname,
484 			    sizeof (altname), NULL, 0) == -1) {
485 				zerror(gettext("could not resolve scratch "
486 				    "zone %s"), name);
487 				retv = Z_ERR;
488 				continue;
489 			}
490 			(void) strcpy(name, altname);
491 		} else {
492 			/* Ignore non-scratch when in an alternate root */
493 			if (inaltroot && strcmp(name, GLOBAL_ZONENAME) != 0)
494 				continue;
495 		}
496 		if (lookup_zone_info(name, zids[i], zentp) != Z_OK) {
497 			zerror(gettext("failed to get zone data"));
498 			retv = Z_ERR;
499 			continue;
500 		}
501 		zentp++;
502 	}
503 	nzents = zentp - zents;
504 	if (fp != NULL)
505 		zonecfg_close_scratch(fp);
506 
507 	free(zids);
508 	return (retv);
509 }
510 
511 static int
512 zone_print_list(zone_state_t min_state, boolean_t verbose, boolean_t parsable)
513 {
514 	int i;
515 	zone_entry_t zent;
516 	FILE *cookie;
517 	char *name;
518 
519 	/*
520 	 * First get the list of running zones from the kernel and print them.
521 	 * If that is all we need, then return.
522 	 */
523 	if ((i = fetch_zents()) != Z_OK) {
524 		/*
525 		 * No need for error messages; fetch_zents() has already taken
526 		 * care of this.
527 		 */
528 		return (i);
529 	}
530 	for (i = 0; i < nzents; i++)
531 		zone_print(&zents[i], verbose, parsable);
532 	if (min_state >= ZONE_STATE_RUNNING)
533 		return (Z_OK);
534 	/*
535 	 * Next, get the full list of zones from the configuration, skipping
536 	 * any we have already printed.
537 	 */
538 	cookie = setzoneent();
539 	while ((name = getzoneent(cookie)) != NULL) {
540 		for (i = 0; i < nzents; i++) {
541 			if (strcmp(zents[i].zname, name) == 0)
542 				break;
543 		}
544 		if (i < nzents) {
545 			free(name);
546 			continue;
547 		}
548 		if (lookup_zone_info(name, ZONE_ID_UNDEFINED, &zent) != Z_OK) {
549 			free(name);
550 			continue;
551 		}
552 		free(name);
553 		if (zent.zstate_num >= min_state)
554 			zone_print(&zent, verbose, parsable);
555 	}
556 	endzoneent(cookie);
557 	return (Z_OK);
558 }
559 
560 static zone_entry_t *
561 lookup_running_zone(char *str)
562 {
563 	zoneid_t zoneid;
564 	char *cp;
565 	int i;
566 
567 	if (fetch_zents() != Z_OK)
568 		return (NULL);
569 
570 	for (i = 0; i < nzents; i++) {
571 		if (strcmp(str, zents[i].zname) == 0)
572 			return (&zents[i]);
573 	}
574 	errno = 0;
575 	zoneid = strtol(str, &cp, 0);
576 	if (zoneid < MIN_ZONEID || zoneid > MAX_ZONEID ||
577 	    errno != 0 || *cp != '\0')
578 		return (NULL);
579 	for (i = 0; i < nzents; i++) {
580 		if (zoneid == zents[i].zid)
581 			return (&zents[i]);
582 	}
583 	return (NULL);
584 }
585 
586 /*
587  * Check a bit in a mode_t: if on is B_TRUE, that bit should be on; if
588  * B_FALSE, it should be off.  Return B_TRUE if the mode is bad (incorrect).
589  */
590 static boolean_t
591 bad_mode_bit(mode_t mode, mode_t bit, boolean_t on, char *file)
592 {
593 	char *str;
594 
595 	assert(bit == S_IRUSR || bit == S_IWUSR || bit == S_IXUSR ||
596 	    bit == S_IRGRP || bit == S_IWGRP || bit == S_IXGRP ||
597 	    bit == S_IROTH || bit == S_IWOTH || bit == S_IXOTH);
598 	/*
599 	 * TRANSLATION_NOTE
600 	 * The strings below will be used as part of a larger message,
601 	 * either:
602 	 * (file name) must be (owner|group|world) (read|writ|execut)able
603 	 * or
604 	 * (file name) must not be (owner|group|world) (read|writ|execut)able
605 	 */
606 	switch (bit) {
607 	case S_IRUSR:
608 		str = gettext("owner readable");
609 		break;
610 	case S_IWUSR:
611 		str = gettext("owner writable");
612 		break;
613 	case S_IXUSR:
614 		str = gettext("owner executable");
615 		break;
616 	case S_IRGRP:
617 		str = gettext("group readable");
618 		break;
619 	case S_IWGRP:
620 		str = gettext("group writable");
621 		break;
622 	case S_IXGRP:
623 		str = gettext("group executable");
624 		break;
625 	case S_IROTH:
626 		str = gettext("world readable");
627 		break;
628 	case S_IWOTH:
629 		str = gettext("world writable");
630 		break;
631 	case S_IXOTH:
632 		str = gettext("world executable");
633 		break;
634 	}
635 	if ((mode & bit) == (on ? 0 : bit)) {
636 		/*
637 		 * TRANSLATION_NOTE
638 		 * The first parameter below is a file name; the second
639 		 * is one of the "(owner|group|world) (read|writ|execut)able"
640 		 * strings from above.
641 		 */
642 		/*
643 		 * The code below could be simplified but not in a way
644 		 * that would easily translate to non-English locales.
645 		 */
646 		if (on) {
647 			(void) fprintf(stderr, gettext("%s must be %s.\n"),
648 			    file, str);
649 		} else {
650 			(void) fprintf(stderr, gettext("%s must not be %s.\n"),
651 			    file, str);
652 		}
653 		return (B_TRUE);
654 	}
655 	return (B_FALSE);
656 }
657 
658 /*
659  * We want to make sure that no zone has its zone path as a child node
660  * (in the directory sense) of any other.  We do that by comparing this
661  * zone's path to the path of all other (non-global) zones.  The comparison
662  * in each case is simple: add '/' to the end of the path, then do a
663  * strncmp() of the two paths, using the length of the shorter one.
664  */
665 
666 static int
667 crosscheck_zonepaths(char *path)
668 {
669 	char rpath[MAXPATHLEN];		/* resolved path */
670 	char path_copy[MAXPATHLEN];	/* copy of original path */
671 	char rpath_copy[MAXPATHLEN];	/* copy of original rpath */
672 	struct zoneent *ze;
673 	int res, err;
674 	FILE *cookie;
675 
676 	cookie = setzoneent();
677 	while ((ze = getzoneent_private(cookie)) != NULL) {
678 		/* Skip zones which are not installed. */
679 		if (ze->zone_state < ZONE_STATE_INSTALLED) {
680 			free(ze);
681 			continue;
682 		}
683 		/* Skip the global zone and the current target zone. */
684 		if (strcmp(ze->zone_name, GLOBAL_ZONENAME) == 0 ||
685 		    strcmp(ze->zone_name, target_zone) == 0) {
686 			free(ze);
687 			continue;
688 		}
689 		if (strlen(ze->zone_path) == 0) {
690 			/* old index file without path, fall back */
691 			if ((err = zone_get_zonepath(ze->zone_name,
692 			    ze->zone_path, sizeof (ze->zone_path))) != Z_OK) {
693 				errno = err;
694 				zperror2(ze->zone_name,
695 				    gettext("could not get zone path"));
696 				free(ze);
697 				continue;
698 			}
699 		}
700 		(void) snprintf(path_copy, sizeof (path_copy), "%s%s",
701 		    zonecfg_get_root(), ze->zone_path);
702 		res = resolvepath(path_copy, rpath, sizeof (rpath));
703 		if (res == -1) {
704 			if (errno != ENOENT) {
705 				zperror(path_copy, B_FALSE);
706 				free(ze);
707 				return (Z_ERR);
708 			}
709 			(void) printf(gettext("WARNING: zone %s is installed, "
710 			    "but its %s %s does not exist.\n"), ze->zone_name,
711 			    "zonepath", path_copy);
712 			free(ze);
713 			continue;
714 		}
715 		rpath[res] = '\0';
716 		(void) snprintf(path_copy, sizeof (path_copy), "%s/", path);
717 		(void) snprintf(rpath_copy, sizeof (rpath_copy), "%s/", rpath);
718 		if (strncmp(path_copy, rpath_copy,
719 		    min(strlen(path_copy), strlen(rpath_copy))) == 0) {
720 			/*
721 			 * TRANSLATION_NOTE
722 			 * zonepath is a literal that should not be translated.
723 			 */
724 			(void) fprintf(stderr, gettext("%s zonepath (%s) and "
725 			    "%s zonepath (%s) overlap.\n"),
726 			    target_zone, path, ze->zone_name, rpath);
727 			free(ze);
728 			return (Z_ERR);
729 		}
730 		free(ze);
731 	}
732 	endzoneent(cookie);
733 	return (Z_OK);
734 }
735 
736 static int
737 validate_zonepath(char *path, int cmd_num)
738 {
739 	int res;			/* result of last library/system call */
740 	boolean_t err = B_FALSE;	/* have we run into an error? */
741 	struct stat stbuf;
742 	struct statvfs vfsbuf;
743 	char rpath[MAXPATHLEN];		/* resolved path */
744 	char ppath[MAXPATHLEN];		/* parent path */
745 	char rppath[MAXPATHLEN];	/* resolved parent path */
746 	char rootpath[MAXPATHLEN];	/* root path */
747 	zone_state_t state;
748 
749 	if (path[0] != '/') {
750 		(void) fprintf(stderr,
751 		    gettext("%s is not an absolute path.\n"), path);
752 		return (Z_ERR);
753 	}
754 	if ((res = resolvepath(path, rpath, sizeof (rpath))) == -1) {
755 		if ((errno != ENOENT) ||
756 		    (cmd_num != CMD_VERIFY && cmd_num != CMD_INSTALL &&
757 		    cmd_num != CMD_CLONE && cmd_num != CMD_MOVE)) {
758 			zperror(path, B_FALSE);
759 			return (Z_ERR);
760 		}
761 		if (cmd_num == CMD_VERIFY) {
762 			/*
763 			 * TRANSLATION_NOTE
764 			 * zoneadm is a literal that should not be translated.
765 			 */
766 			(void) fprintf(stderr, gettext("WARNING: %s does not "
767 			    "exist, so it could not be verified.\nWhen "
768 			    "'zoneadm %s' is run, '%s' will try to create\n%s, "
769 			    "and '%s' will be tried again,\nbut the '%s' may "
770 			    "fail if:\nthe parent directory of %s is group- or "
771 			    "other-writable\nor\n%s overlaps with any other "
772 			    "installed zones.\n"), path,
773 			    cmd_to_str(CMD_INSTALL), cmd_to_str(CMD_INSTALL),
774 			    path, cmd_to_str(CMD_VERIFY),
775 			    cmd_to_str(CMD_VERIFY), path, path);
776 			return (Z_OK);
777 		}
778 		/*
779 		 * The zonepath is supposed to be mode 700 but its
780 		 * parent(s) 755.  So use 755 on the mkdirp() then
781 		 * chmod() the zonepath itself to 700.
782 		 */
783 		if (mkdirp(path, DEFAULT_DIR_MODE) < 0) {
784 			zperror(path, B_FALSE);
785 			return (Z_ERR);
786 		}
787 		/*
788 		 * If the chmod() fails, report the error, but might
789 		 * as well continue the verify procedure.
790 		 */
791 		if (chmod(path, S_IRWXU) != 0)
792 			zperror(path, B_FALSE);
793 		/*
794 		 * Since the mkdir() succeeded, we should not have to
795 		 * worry about a subsequent ENOENT, thus this should
796 		 * only recurse once.
797 		 */
798 		return (validate_zonepath(path, cmd_num));
799 	}
800 	rpath[res] = '\0';
801 	if (strcmp(path, rpath) != 0) {
802 		errno = Z_RESOLVED_PATH;
803 		zperror(path, B_TRUE);
804 		return (Z_ERR);
805 	}
806 	if ((res = stat(rpath, &stbuf)) != 0) {
807 		zperror(rpath, B_FALSE);
808 		return (Z_ERR);
809 	}
810 	if (!S_ISDIR(stbuf.st_mode)) {
811 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
812 		    rpath);
813 		return (Z_ERR);
814 	}
815 	if ((strcmp(stbuf.st_fstype, MNTTYPE_TMPFS) == 0) ||
816 	    (strcmp(stbuf.st_fstype, MNTTYPE_XMEMFS) == 0)) {
817 		(void) printf(gettext("WARNING: %s is on a temporary "
818 		    "file-system.\n"), rpath);
819 	}
820 	if (crosscheck_zonepaths(rpath) != Z_OK)
821 		return (Z_ERR);
822 	/*
823 	 * Try to collect and report as many minor errors as possible
824 	 * before returning, so the user can learn everything that needs
825 	 * to be fixed up front.
826 	 */
827 	if (stbuf.st_uid != 0) {
828 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
829 		    rpath);
830 		err = B_TRUE;
831 	}
832 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rpath);
833 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rpath);
834 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rpath);
835 	err |= bad_mode_bit(stbuf.st_mode, S_IRGRP, B_FALSE, rpath);
836 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rpath);
837 	err |= bad_mode_bit(stbuf.st_mode, S_IXGRP, B_FALSE, rpath);
838 	err |= bad_mode_bit(stbuf.st_mode, S_IROTH, B_FALSE, rpath);
839 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rpath);
840 	err |= bad_mode_bit(stbuf.st_mode, S_IXOTH, B_FALSE, rpath);
841 
842 	(void) snprintf(ppath, sizeof (ppath), "%s/..", path);
843 	if ((res = resolvepath(ppath, rppath, sizeof (rppath))) == -1) {
844 		zperror(ppath, B_FALSE);
845 		return (Z_ERR);
846 	}
847 	rppath[res] = '\0';
848 	if ((res = stat(rppath, &stbuf)) != 0) {
849 		zperror(rppath, B_FALSE);
850 		return (Z_ERR);
851 	}
852 	/* theoretically impossible */
853 	if (!S_ISDIR(stbuf.st_mode)) {
854 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
855 		    rppath);
856 		return (Z_ERR);
857 	}
858 	if (stbuf.st_uid != 0) {
859 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
860 		    rppath);
861 		err = B_TRUE;
862 	}
863 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rppath);
864 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rppath);
865 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rppath);
866 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rppath);
867 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rppath);
868 	if (strcmp(rpath, rppath) == 0) {
869 		(void) fprintf(stderr, gettext("%s is its own parent.\n"),
870 		    rppath);
871 		err = B_TRUE;
872 	}
873 
874 	if (statvfs(rpath, &vfsbuf) != 0) {
875 		zperror(rpath, B_FALSE);
876 		return (Z_ERR);
877 	}
878 	if (strcmp(vfsbuf.f_basetype, MNTTYPE_NFS) == 0) {
879 		/*
880 		 * TRANSLATION_NOTE
881 		 * Zonepath and NFS are literals that should not be translated.
882 		 */
883 		(void) fprintf(stderr, gettext("Zonepath %s is on an NFS "
884 		    "mounted file-system.\n"
885 		    "\tA local file-system must be used.\n"), rpath);
886 		return (Z_ERR);
887 	}
888 	if (vfsbuf.f_flag & ST_NOSUID) {
889 		/*
890 		 * TRANSLATION_NOTE
891 		 * Zonepath and nosuid are literals that should not be
892 		 * translated.
893 		 */
894 		(void) fprintf(stderr, gettext("Zonepath %s is on a nosuid "
895 		    "file-system.\n"), rpath);
896 		return (Z_ERR);
897 	}
898 
899 	if ((res = zone_get_state(target_zone, &state)) != Z_OK) {
900 		errno = res;
901 		zperror2(target_zone, gettext("could not get state"));
902 		return (Z_ERR);
903 	}
904 	/*
905 	 * The existence of the root path is only bad in the configured state,
906 	 * as it is *supposed* to be there at the installed and later states.
907 	 * State/command mismatches are caught earlier in verify_details().
908 	 */
909 	if (state == ZONE_STATE_CONFIGURED) {
910 		if (snprintf(rootpath, sizeof (rootpath), "%s/root", rpath) >=
911 		    sizeof (rootpath)) {
912 			/*
913 			 * TRANSLATION_NOTE
914 			 * Zonepath is a literal that should not be translated.
915 			 */
916 			(void) fprintf(stderr,
917 			    gettext("Zonepath %s is too long.\n"), rpath);
918 			return (Z_ERR);
919 		}
920 		if ((res = stat(rootpath, &stbuf)) == 0) {
921 			(void) fprintf(stderr, gettext("Rootpath %s exists; "
922 			    "remove or move aside prior to %s.\n"), rootpath,
923 			    cmd_to_str(CMD_INSTALL));
924 			return (Z_ERR);
925 		}
926 	}
927 
928 	return (err ? Z_ERR : Z_OK);
929 }
930 
931 static void
932 release_lock_file(int lockfd)
933 {
934 	(void) close(lockfd);
935 }
936 
937 static int
938 grab_lock_file(const char *zone_name, int *lockfd)
939 {
940 	char pathbuf[PATH_MAX];
941 	struct flock flock;
942 
943 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s", zonecfg_get_root(),
944 	    ZONES_TMPDIR) >= sizeof (pathbuf)) {
945 		zerror(gettext("alternate root path is too long"));
946 		return (Z_ERR);
947 	}
948 	if (mkdir(pathbuf, S_IRWXU) < 0 && errno != EEXIST) {
949 		zerror(gettext("could not mkdir %s: %s"), pathbuf,
950 		    strerror(errno));
951 		return (Z_ERR);
952 	}
953 	(void) chmod(pathbuf, S_IRWXU);
954 
955 	/*
956 	 * One of these lock files is created for each zone (when needed).
957 	 * The lock files are not cleaned up (except on system reboot),
958 	 * but since there is only one per zone, there is no resource
959 	 * starvation issue.
960 	 */
961 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s/%s.zoneadm.lock",
962 	    zonecfg_get_root(), ZONES_TMPDIR, zone_name) >= sizeof (pathbuf)) {
963 		zerror(gettext("alternate root path is too long"));
964 		return (Z_ERR);
965 	}
966 	if ((*lockfd = open(pathbuf, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
967 		zerror(gettext("could not open %s: %s"), pathbuf,
968 		    strerror(errno));
969 		return (Z_ERR);
970 	}
971 	/*
972 	 * Lock the file to synchronize with other zoneadmds
973 	 */
974 	flock.l_type = F_WRLCK;
975 	flock.l_whence = SEEK_SET;
976 	flock.l_start = (off_t)0;
977 	flock.l_len = (off_t)0;
978 	if (fcntl(*lockfd, F_SETLKW, &flock) < 0) {
979 		zerror(gettext("unable to lock %s: %s"), pathbuf,
980 		    strerror(errno));
981 		release_lock_file(*lockfd);
982 		return (Z_ERR);
983 	}
984 	return (Z_OK);
985 }
986 
987 static boolean_t
988 get_doorname(const char *zone_name, char *buffer)
989 {
990 	return (snprintf(buffer, PATH_MAX, "%s" ZONE_DOOR_PATH,
991 	    zonecfg_get_root(), zone_name) < PATH_MAX);
992 }
993 
994 /*
995  * system daemons are not audited.  For the global zone, this occurs
996  * "naturally" since init is started with the default audit
997  * characteristics.  Since zoneadmd is a system daemon and it starts
998  * init for a zone, it is necessary to clear out the audit
999  * characteristics inherited from whomever started zoneadmd.  This is
1000  * indicated by the audit id, which is set from the ruid parameter of
1001  * adt_set_user(), below.
1002  */
1003 
1004 static void
1005 prepare_audit_context()
1006 {
1007 	adt_session_data_t	*ah;
1008 	char			*failure = gettext("audit failure: %s");
1009 
1010 	if (adt_start_session(&ah, NULL, 0)) {
1011 		zerror(failure, strerror(errno));
1012 		return;
1013 	}
1014 	if (adt_set_user(ah, ADT_NO_AUDIT, ADT_NO_AUDIT,
1015 	    ADT_NO_AUDIT, ADT_NO_AUDIT, NULL, ADT_NEW)) {
1016 		zerror(failure, strerror(errno));
1017 		(void) adt_end_session(ah);
1018 		return;
1019 	}
1020 	if (adt_set_proc(ah))
1021 		zerror(failure, strerror(errno));
1022 
1023 	(void) adt_end_session(ah);
1024 }
1025 
1026 static int
1027 start_zoneadmd(const char *zone_name)
1028 {
1029 	char doorpath[PATH_MAX];
1030 	pid_t child_pid;
1031 	int error = Z_ERR;
1032 	int doorfd, lockfd;
1033 	struct door_info info;
1034 
1035 	if (!get_doorname(zone_name, doorpath))
1036 		return (Z_ERR);
1037 
1038 	if (grab_lock_file(zone_name, &lockfd) != Z_OK)
1039 		return (Z_ERR);
1040 
1041 	/*
1042 	 * Now that we have the lock, re-confirm that the daemon is
1043 	 * *not* up and working fine.  If it is still down, we have a green
1044 	 * light to start it.
1045 	 */
1046 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1047 		if (errno != ENOENT) {
1048 			zperror(doorpath, B_FALSE);
1049 			goto out;
1050 		}
1051 	} else {
1052 		if (door_info(doorfd, &info) == 0 &&
1053 		    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1054 			error = Z_OK;
1055 			(void) close(doorfd);
1056 			goto out;
1057 		}
1058 		(void) close(doorfd);
1059 	}
1060 
1061 	if ((child_pid = fork()) == -1) {
1062 		zperror(gettext("could not fork"), B_FALSE);
1063 		goto out;
1064 	} else if (child_pid == 0) {
1065 		const char *argv[6], **ap;
1066 
1067 		/* child process */
1068 		prepare_audit_context();
1069 
1070 		ap = argv;
1071 		*ap++ = "zoneadmd";
1072 		*ap++ = "-z";
1073 		*ap++ = zone_name;
1074 		if (zonecfg_in_alt_root()) {
1075 			*ap++ = "-R";
1076 			*ap++ = zonecfg_get_root();
1077 		}
1078 		*ap = NULL;
1079 
1080 		(void) execv("/usr/lib/zones/zoneadmd", (char * const *)argv);
1081 		/*
1082 		 * TRANSLATION_NOTE
1083 		 * zoneadmd is a literal that should not be translated.
1084 		 */
1085 		zperror(gettext("could not exec zoneadmd"), B_FALSE);
1086 		_exit(Z_ERR);
1087 	} else {
1088 		/* parent process */
1089 		pid_t retval;
1090 		int pstatus = 0;
1091 
1092 		do {
1093 			retval = waitpid(child_pid, &pstatus, 0);
1094 		} while (retval != child_pid);
1095 		if (WIFSIGNALED(pstatus) || (WIFEXITED(pstatus) &&
1096 		    WEXITSTATUS(pstatus) != 0)) {
1097 			zerror(gettext("could not start %s"), "zoneadmd");
1098 			goto out;
1099 		}
1100 	}
1101 	error = Z_OK;
1102 out:
1103 	release_lock_file(lockfd);
1104 	return (error);
1105 }
1106 
1107 static int
1108 ping_zoneadmd(const char *zone_name)
1109 {
1110 	char doorpath[PATH_MAX];
1111 	int doorfd;
1112 	struct door_info info;
1113 
1114 	if (!get_doorname(zone_name, doorpath))
1115 		return (Z_ERR);
1116 
1117 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1118 		return (Z_ERR);
1119 	}
1120 	if (door_info(doorfd, &info) == 0 &&
1121 	    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1122 		(void) close(doorfd);
1123 		return (Z_OK);
1124 	}
1125 	(void) close(doorfd);
1126 	return (Z_ERR);
1127 }
1128 
1129 static int
1130 call_zoneadmd(const char *zone_name, zone_cmd_arg_t *arg)
1131 {
1132 	char doorpath[PATH_MAX];
1133 	int doorfd, result;
1134 	door_arg_t darg;
1135 
1136 	zoneid_t zoneid;
1137 	uint64_t uniqid = 0;
1138 
1139 	zone_cmd_rval_t *rvalp;
1140 	size_t rlen;
1141 	char *cp, *errbuf;
1142 
1143 	rlen = getpagesize();
1144 	if ((rvalp = malloc(rlen)) == NULL) {
1145 		zerror(gettext("failed to allocate %lu bytes: %s"), rlen,
1146 		    strerror(errno));
1147 		return (-1);
1148 	}
1149 
1150 	if ((zoneid = getzoneidbyname(zone_name)) != ZONE_ID_UNDEFINED) {
1151 		(void) zone_getattr(zoneid, ZONE_ATTR_UNIQID, &uniqid,
1152 		    sizeof (uniqid));
1153 	}
1154 	arg->uniqid = uniqid;
1155 	(void) strlcpy(arg->locale, locale, sizeof (arg->locale));
1156 	if (!get_doorname(zone_name, doorpath)) {
1157 		zerror(gettext("alternate root path is too long"));
1158 		free(rvalp);
1159 		return (-1);
1160 	}
1161 
1162 	/*
1163 	 * Loop trying to start zoneadmd; if something goes seriously
1164 	 * wrong we break out and fail.
1165 	 */
1166 	for (;;) {
1167 		if (start_zoneadmd(zone_name) != Z_OK)
1168 			break;
1169 
1170 		if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1171 			zperror(gettext("failed to open zone door"), B_FALSE);
1172 			break;
1173 		}
1174 
1175 		darg.data_ptr = (char *)arg;
1176 		darg.data_size = sizeof (*arg);
1177 		darg.desc_ptr = NULL;
1178 		darg.desc_num = 0;
1179 		darg.rbuf = (char *)rvalp;
1180 		darg.rsize = rlen;
1181 		if (door_call(doorfd, &darg) != 0) {
1182 			(void) close(doorfd);
1183 			/*
1184 			 * We'll get EBADF if the door has been revoked.
1185 			 */
1186 			if (errno != EBADF) {
1187 				zperror(gettext("door_call failed"), B_FALSE);
1188 				break;
1189 			}
1190 			continue;	/* take another lap */
1191 		}
1192 		(void) close(doorfd);
1193 
1194 		if (darg.data_size == 0) {
1195 			/* Door server is going away; kick it again. */
1196 			continue;
1197 		}
1198 
1199 		errbuf = rvalp->errbuf;
1200 		while (*errbuf != '\0') {
1201 			/*
1202 			 * Remove any newlines since zerror()
1203 			 * will append one automatically.
1204 			 */
1205 			cp = strchr(errbuf, '\n');
1206 			if (cp != NULL)
1207 				*cp = '\0';
1208 			zerror("%s", errbuf);
1209 			if (cp == NULL)
1210 				break;
1211 			errbuf = cp + 1;
1212 		}
1213 		result = rvalp->rval == 0 ? 0 : -1;
1214 		free(rvalp);
1215 		return (result);
1216 	}
1217 
1218 	free(rvalp);
1219 	return (-1);
1220 }
1221 
1222 static int
1223 ready_func(int argc, char *argv[])
1224 {
1225 	zone_cmd_arg_t zarg;
1226 	int arg;
1227 
1228 	if (zonecfg_in_alt_root()) {
1229 		zerror(gettext("cannot ready zone in alternate root"));
1230 		return (Z_ERR);
1231 	}
1232 
1233 	optind = 0;
1234 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1235 		switch (arg) {
1236 		case '?':
1237 			sub_usage(SHELP_READY, CMD_READY);
1238 			return (optopt == '?' ? Z_OK : Z_USAGE);
1239 		default:
1240 			sub_usage(SHELP_READY, CMD_READY);
1241 			return (Z_USAGE);
1242 		}
1243 	}
1244 	if (argc > optind) {
1245 		sub_usage(SHELP_READY, CMD_READY);
1246 		return (Z_USAGE);
1247 	}
1248 	if (sanity_check(target_zone, CMD_READY, B_FALSE, B_FALSE) != Z_OK)
1249 		return (Z_ERR);
1250 	if (verify_details(CMD_READY) != Z_OK)
1251 		return (Z_ERR);
1252 
1253 	zarg.cmd = Z_READY;
1254 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1255 		zerror(gettext("call to %s failed"), "zoneadmd");
1256 		return (Z_ERR);
1257 	}
1258 	return (Z_OK);
1259 }
1260 
1261 static int
1262 boot_func(int argc, char *argv[])
1263 {
1264 	zone_cmd_arg_t zarg;
1265 	int arg;
1266 
1267 	if (zonecfg_in_alt_root()) {
1268 		zerror(gettext("cannot boot zone in alternate root"));
1269 		return (Z_ERR);
1270 	}
1271 
1272 	zarg.bootbuf[0] = '\0';
1273 
1274 	/*
1275 	 * At the current time, the only supported subargument to the
1276 	 * "boot" subcommand is "-s" which specifies a single-user boot.
1277 	 * In the future, other boot arguments should be supported
1278 	 * including "-m" for specifying alternate smf(5) milestones.
1279 	 */
1280 	optind = 0;
1281 	if ((arg = getopt(argc, argv, "?s")) != EOF) {
1282 		switch (arg) {
1283 		case '?':
1284 			sub_usage(SHELP_BOOT, CMD_BOOT);
1285 			return (optopt == '?' ? Z_OK : Z_USAGE);
1286 		case 's':
1287 			(void) strlcpy(zarg.bootbuf, "-s",
1288 			    sizeof (zarg.bootbuf));
1289 			break;
1290 		default:
1291 			sub_usage(SHELP_BOOT, CMD_BOOT);
1292 			return (Z_USAGE);
1293 		}
1294 	}
1295 	if (argc > optind) {
1296 		sub_usage(SHELP_BOOT, CMD_BOOT);
1297 		return (Z_USAGE);
1298 	}
1299 	if (sanity_check(target_zone, CMD_BOOT, B_FALSE, B_FALSE) != Z_OK)
1300 		return (Z_ERR);
1301 	if (verify_details(CMD_BOOT) != Z_OK)
1302 		return (Z_ERR);
1303 	zarg.cmd = Z_BOOT;
1304 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1305 		zerror(gettext("call to %s failed"), "zoneadmd");
1306 		return (Z_ERR);
1307 	}
1308 	return (Z_OK);
1309 }
1310 
1311 static void
1312 fake_up_local_zone(zoneid_t zid, zone_entry_t *zeptr)
1313 {
1314 	ssize_t result;
1315 
1316 	zeptr->zid = zid;
1317 	/*
1318 	 * Since we're looking up our own (non-global) zone name,
1319 	 * we can be assured that it will succeed.
1320 	 */
1321 	result = getzonenamebyid(zid, zeptr->zname, sizeof (zeptr->zname));
1322 	assert(result >= 0);
1323 	(void) strlcpy(zeptr->zroot, "/", sizeof (zeptr->zroot));
1324 	zeptr->zstate_str = "running";
1325 }
1326 
1327 static int
1328 list_func(int argc, char *argv[])
1329 {
1330 	zone_entry_t *zentp, zent;
1331 	int arg, retv;
1332 	boolean_t output = B_FALSE, verbose = B_FALSE, parsable = B_FALSE;
1333 	zone_state_t min_state = ZONE_STATE_RUNNING;
1334 	zoneid_t zone_id = getzoneid();
1335 
1336 	if (target_zone == NULL) {
1337 		/* all zones: default view to running but allow override */
1338 		optind = 0;
1339 		while ((arg = getopt(argc, argv, "?cipv")) != EOF) {
1340 			switch (arg) {
1341 			case '?':
1342 				sub_usage(SHELP_LIST, CMD_LIST);
1343 				return (optopt == '?' ? Z_OK : Z_USAGE);
1344 				/*
1345 				 * The 'i' and 'c' options are not mutually
1346 				 * exclusive so if 'c' is given, then min_state
1347 				 * is set to 0 (ZONE_STATE_CONFIGURED) which is
1348 				 * the lowest possible state.  If 'i' is given,
1349 				 * then min_state is set to be the lowest state
1350 				 * so far.
1351 				 */
1352 			case 'c':
1353 				min_state = ZONE_STATE_CONFIGURED;
1354 				break;
1355 			case 'i':
1356 				min_state = min(ZONE_STATE_INSTALLED,
1357 				    min_state);
1358 
1359 				break;
1360 			case 'p':
1361 				parsable = B_TRUE;
1362 				break;
1363 			case 'v':
1364 				verbose = B_TRUE;
1365 				break;
1366 			default:
1367 				sub_usage(SHELP_LIST, CMD_LIST);
1368 				return (Z_USAGE);
1369 			}
1370 		}
1371 		if (parsable && verbose) {
1372 			zerror(gettext("%s -p and -v are mutually exclusive."),
1373 			    cmd_to_str(CMD_LIST));
1374 			return (Z_ERR);
1375 		}
1376 		if (zone_id == GLOBAL_ZONEID) {
1377 			retv = zone_print_list(min_state, verbose, parsable);
1378 		} else {
1379 			retv = Z_OK;
1380 			fake_up_local_zone(zone_id, &zent);
1381 			zone_print(&zent, verbose, parsable);
1382 		}
1383 		return (retv);
1384 	}
1385 
1386 	/*
1387 	 * Specific target zone: disallow -i/-c suboptions.
1388 	 */
1389 	optind = 0;
1390 	while ((arg = getopt(argc, argv, "?pv")) != EOF) {
1391 		switch (arg) {
1392 		case '?':
1393 			sub_usage(SHELP_LIST, CMD_LIST);
1394 			return (optopt == '?' ? Z_OK : Z_USAGE);
1395 		case 'p':
1396 			parsable = B_TRUE;
1397 			break;
1398 		case 'v':
1399 			verbose = B_TRUE;
1400 			break;
1401 		default:
1402 			sub_usage(SHELP_LIST, CMD_LIST);
1403 			return (Z_USAGE);
1404 		}
1405 	}
1406 	if (parsable && verbose) {
1407 		zerror(gettext("%s -p and -v are mutually exclusive."),
1408 		    cmd_to_str(CMD_LIST));
1409 		return (Z_ERR);
1410 	}
1411 	if (argc > optind) {
1412 		sub_usage(SHELP_LIST, CMD_LIST);
1413 		return (Z_USAGE);
1414 	}
1415 	if (zone_id != GLOBAL_ZONEID) {
1416 		fake_up_local_zone(zone_id, &zent);
1417 		/*
1418 		 * main() will issue a Z_NO_ZONE error if it cannot get an
1419 		 * id for target_zone, which in a non-global zone should
1420 		 * happen for any zone name except `zonename`.  Thus we
1421 		 * assert() that here but don't otherwise check.
1422 		 */
1423 		assert(strcmp(zent.zname, target_zone) == 0);
1424 		zone_print(&zent, verbose, parsable);
1425 		output = B_TRUE;
1426 	} else if ((zentp = lookup_running_zone(target_zone)) != NULL) {
1427 		zone_print(zentp, verbose, parsable);
1428 		output = B_TRUE;
1429 	} else if (lookup_zone_info(target_zone, ZONE_ID_UNDEFINED,
1430 	    &zent) == Z_OK) {
1431 		zone_print(&zent, verbose, parsable);
1432 		output = B_TRUE;
1433 	}
1434 	return (output ? Z_OK : Z_ERR);
1435 }
1436 
1437 static void
1438 sigterm(int sig)
1439 {
1440 	/*
1441 	 * Ignore SIG{INT,TERM}, so we don't end up in an infinite loop,
1442 	 * then propagate the signal to our process group.
1443 	 */
1444 	(void) sigset(SIGINT, SIG_IGN);
1445 	(void) sigset(SIGTERM, SIG_IGN);
1446 	(void) kill(0, sig);
1447 	child_killed = B_TRUE;
1448 }
1449 
1450 static int
1451 do_subproc(char *cmdbuf)
1452 {
1453 	char inbuf[1024];	/* arbitrary large amount */
1454 	FILE *file;
1455 
1456 	child_killed = B_FALSE;
1457 	/*
1458 	 * We use popen(3c) to launch child processes for [un]install;
1459 	 * this library call does not return a PID, so we have to kill
1460 	 * the whole process group.  To avoid killing our parent, we
1461 	 * become a process group leader here.  But doing so can wreak
1462 	 * havoc with reading from stdin when launched by a non-job-control
1463 	 * shell, so we close stdin and reopen it as /dev/null first.
1464 	 */
1465 	(void) close(STDIN_FILENO);
1466 	(void) open("/dev/null", O_RDONLY);
1467 	(void) setpgid(0, 0);
1468 	(void) sigset(SIGINT, sigterm);
1469 	(void) sigset(SIGTERM, sigterm);
1470 	file = popen(cmdbuf, "r");
1471 	for (;;) {
1472 		if (child_killed || fgets(inbuf, sizeof (inbuf), file) == NULL)
1473 			break;
1474 		(void) fputs(inbuf, stdout);
1475 	}
1476 	(void) sigset(SIGINT, SIG_DFL);
1477 	(void) sigset(SIGTERM, SIG_DFL);
1478 	return (pclose(file));
1479 }
1480 
1481 static int
1482 subproc_status(const char *cmd, int status)
1483 {
1484 	if (WIFEXITED(status)) {
1485 		int exit_code = WEXITSTATUS(status);
1486 
1487 		if (exit_code == 0)
1488 			return (Z_OK);
1489 		zerror(gettext("'%s' failed with exit code %d."), cmd,
1490 		    exit_code);
1491 	} else if (WIFSIGNALED(status)) {
1492 		int signal = WTERMSIG(status);
1493 		char sigstr[SIG2STR_MAX];
1494 
1495 		if (sig2str(signal, sigstr) == 0) {
1496 			zerror(gettext("'%s' terminated by signal SIG%s."), cmd,
1497 			    sigstr);
1498 		} else {
1499 			zerror(gettext("'%s' terminated by an unknown signal."),
1500 			    cmd);
1501 		}
1502 	} else {
1503 		zerror(gettext("'%s' failed for unknown reasons."), cmd);
1504 	}
1505 	return (Z_ERR);
1506 }
1507 
1508 /*
1509  * Various sanity checks; make sure:
1510  * 1. We're in the global zone.
1511  * 2. The calling user has sufficient privilege.
1512  * 3. The target zone is neither the global zone nor anything starting with
1513  *    "SUNW".
1514  * 4a. If we're looking for a 'not running' (i.e., configured or installed)
1515  *     zone, the name service knows about it.
1516  * 4b. For some operations which expect a zone not to be running, that it is
1517  *     not already running (or ready).
1518  */
1519 static int
1520 sanity_check(char *zone, int cmd_num, boolean_t running,
1521     boolean_t unsafe_when_running)
1522 {
1523 	zone_entry_t *zent;
1524 	priv_set_t *privset;
1525 	zone_state_t state;
1526 	char kernzone[ZONENAME_MAX];
1527 	FILE *fp;
1528 
1529 	if (getzoneid() != GLOBAL_ZONEID) {
1530 		zerror(gettext("must be in the global zone to %s a zone."),
1531 		    cmd_to_str(cmd_num));
1532 		return (Z_ERR);
1533 	}
1534 
1535 	if ((privset = priv_allocset()) == NULL) {
1536 		zerror(gettext("%s failed"), "priv_allocset");
1537 		return (Z_ERR);
1538 	}
1539 
1540 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
1541 		zerror(gettext("%s failed"), "getppriv");
1542 		priv_freeset(privset);
1543 		return (Z_ERR);
1544 	}
1545 
1546 	if (priv_isfullset(privset) == B_FALSE) {
1547 		zerror(gettext("only a privileged user may %s a zone."),
1548 		    cmd_to_str(cmd_num));
1549 		priv_freeset(privset);
1550 		return (Z_ERR);
1551 	}
1552 	priv_freeset(privset);
1553 
1554 	if (zone == NULL) {
1555 		zerror(gettext("no zone specified"));
1556 		return (Z_ERR);
1557 	}
1558 
1559 	if (strcmp(zone, GLOBAL_ZONENAME) == 0) {
1560 		zerror(gettext("%s operation is invalid for the global zone."),
1561 		    cmd_to_str(cmd_num));
1562 		return (Z_ERR);
1563 	}
1564 
1565 	if (strncmp(zone, "SUNW", 4) == 0) {
1566 		zerror(gettext("%s operation is invalid for zones starting "
1567 		    "with SUNW."), cmd_to_str(cmd_num));
1568 		return (Z_ERR);
1569 	}
1570 
1571 	if (!zonecfg_in_alt_root()) {
1572 		zent = lookup_running_zone(zone);
1573 	} else if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
1574 		zent = NULL;
1575 	} else {
1576 		if (zonecfg_find_scratch(fp, zone, zonecfg_get_root(),
1577 		    kernzone, sizeof (kernzone)) == 0)
1578 			zent = lookup_running_zone(kernzone);
1579 		else
1580 			zent = NULL;
1581 		zonecfg_close_scratch(fp);
1582 	}
1583 
1584 	/*
1585 	 * Look up from the kernel for 'running' zones.
1586 	 */
1587 	if (running) {
1588 		if (zent == NULL) {
1589 			zerror(gettext("not running"));
1590 			return (Z_ERR);
1591 		}
1592 	} else {
1593 		int err;
1594 
1595 		if (unsafe_when_running && zent != NULL) {
1596 			/* check whether the zone is ready or running */
1597 			if ((err = zone_get_state(zent->zname,
1598 			    &zent->zstate_num)) != Z_OK) {
1599 				errno = err;
1600 				zperror2(zent->zname,
1601 				    gettext("could not get state"));
1602 				/* can't tell, so hedge */
1603 				zent->zstate_str = "ready/running";
1604 			} else {
1605 				zent->zstate_str =
1606 				    zone_state_str(zent->zstate_num);
1607 			}
1608 			zerror(gettext("%s operation is invalid for %s zones."),
1609 			    cmd_to_str(cmd_num), zent->zstate_str);
1610 			return (Z_ERR);
1611 		}
1612 		if ((err = zone_get_state(zone, &state)) != Z_OK) {
1613 			errno = err;
1614 			zperror2(zone, gettext("could not get state"));
1615 			return (Z_ERR);
1616 		}
1617 		switch (cmd_num) {
1618 		case CMD_UNINSTALL:
1619 			if (state == ZONE_STATE_CONFIGURED) {
1620 				zerror(gettext("is already in state '%s'."),
1621 				    zone_state_str(ZONE_STATE_CONFIGURED));
1622 				return (Z_ERR);
1623 			}
1624 			break;
1625 		case CMD_CLONE:
1626 		case CMD_INSTALL:
1627 			if (state == ZONE_STATE_INSTALLED) {
1628 				zerror(gettext("is already %s."),
1629 				    zone_state_str(ZONE_STATE_INSTALLED));
1630 				return (Z_ERR);
1631 			} else if (state == ZONE_STATE_INCOMPLETE) {
1632 				zerror(gettext("zone is %s; %s required."),
1633 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1634 				    cmd_to_str(CMD_UNINSTALL));
1635 				return (Z_ERR);
1636 			}
1637 			break;
1638 		case CMD_MOVE:
1639 		case CMD_READY:
1640 		case CMD_BOOT:
1641 		case CMD_MOUNT:
1642 			if (state < ZONE_STATE_INSTALLED) {
1643 				zerror(gettext("must be %s before %s."),
1644 				    zone_state_str(ZONE_STATE_INSTALLED),
1645 				    cmd_to_str(cmd_num));
1646 				return (Z_ERR);
1647 			}
1648 			break;
1649 		case CMD_VERIFY:
1650 			if (state == ZONE_STATE_INCOMPLETE) {
1651 				zerror(gettext("zone is %s; %s required."),
1652 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1653 				    cmd_to_str(CMD_UNINSTALL));
1654 				return (Z_ERR);
1655 			}
1656 			break;
1657 		case CMD_UNMOUNT:
1658 			if (state != ZONE_STATE_MOUNTED) {
1659 				zerror(gettext("must be %s before %s."),
1660 				    zone_state_str(ZONE_STATE_MOUNTED),
1661 				    cmd_to_str(cmd_num));
1662 				return (Z_ERR);
1663 			}
1664 			break;
1665 		}
1666 	}
1667 	return (Z_OK);
1668 }
1669 
1670 static int
1671 halt_func(int argc, char *argv[])
1672 {
1673 	zone_cmd_arg_t zarg;
1674 	int arg;
1675 
1676 	if (zonecfg_in_alt_root()) {
1677 		zerror(gettext("cannot halt zone in alternate root"));
1678 		return (Z_ERR);
1679 	}
1680 
1681 	optind = 0;
1682 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1683 		switch (arg) {
1684 		case '?':
1685 			sub_usage(SHELP_HALT, CMD_HALT);
1686 			return (optopt == '?' ? Z_OK : Z_USAGE);
1687 		default:
1688 			sub_usage(SHELP_HALT, CMD_HALT);
1689 			return (Z_USAGE);
1690 		}
1691 	}
1692 	if (argc > optind) {
1693 		sub_usage(SHELP_HALT, CMD_HALT);
1694 		return (Z_USAGE);
1695 	}
1696 	/*
1697 	 * zoneadmd should be the one to decide whether or not to proceed,
1698 	 * so even though it seems that the fourth parameter below should
1699 	 * perhaps be B_TRUE, it really shouldn't be.
1700 	 */
1701 	if (sanity_check(target_zone, CMD_HALT, B_FALSE, B_FALSE) != Z_OK)
1702 		return (Z_ERR);
1703 
1704 	zarg.cmd = Z_HALT;
1705 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
1706 }
1707 
1708 static int
1709 reboot_func(int argc, char *argv[])
1710 {
1711 	zone_cmd_arg_t zarg;
1712 	int arg;
1713 
1714 	if (zonecfg_in_alt_root()) {
1715 		zerror(gettext("cannot reboot zone in alternate root"));
1716 		return (Z_ERR);
1717 	}
1718 
1719 	optind = 0;
1720 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1721 		switch (arg) {
1722 		case '?':
1723 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
1724 			return (optopt == '?' ? Z_OK : Z_USAGE);
1725 		default:
1726 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
1727 			return (Z_USAGE);
1728 		}
1729 	}
1730 	if (argc > 0) {
1731 		sub_usage(SHELP_REBOOT, CMD_REBOOT);
1732 		return (Z_USAGE);
1733 	}
1734 	/*
1735 	 * zoneadmd should be the one to decide whether or not to proceed,
1736 	 * so even though it seems that the fourth parameter below should
1737 	 * perhaps be B_TRUE, it really shouldn't be.
1738 	 */
1739 	if (sanity_check(target_zone, CMD_REBOOT, B_TRUE, B_FALSE) != Z_OK)
1740 		return (Z_ERR);
1741 	if (verify_details(CMD_REBOOT) != Z_OK)
1742 		return (Z_ERR);
1743 
1744 	zarg.cmd = Z_REBOOT;
1745 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
1746 }
1747 
1748 static int
1749 verify_rctls(zone_dochandle_t handle)
1750 {
1751 	struct zone_rctltab rctltab;
1752 	size_t rbs = rctlblk_size();
1753 	rctlblk_t *rctlblk;
1754 	int error = Z_INVAL;
1755 
1756 	if ((rctlblk = malloc(rbs)) == NULL) {
1757 		zerror(gettext("failed to allocate %lu bytes: %s"), rbs,
1758 		    strerror(errno));
1759 		return (Z_NOMEM);
1760 	}
1761 
1762 	if (zonecfg_setrctlent(handle) != Z_OK) {
1763 		zerror(gettext("zonecfg_setrctlent failed"));
1764 		free(rctlblk);
1765 		return (error);
1766 	}
1767 
1768 	rctltab.zone_rctl_valptr = NULL;
1769 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
1770 		struct zone_rctlvaltab *rctlval;
1771 		const char *name = rctltab.zone_rctl_name;
1772 
1773 		if (!zonecfg_is_rctl(name)) {
1774 			zerror(gettext("WARNING: Ignoring unrecognized rctl "
1775 			    "'%s'."),  name);
1776 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1777 			rctltab.zone_rctl_valptr = NULL;
1778 			continue;
1779 		}
1780 
1781 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
1782 		    rctlval = rctlval->zone_rctlval_next) {
1783 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
1784 			    != Z_OK) {
1785 				zerror(gettext("invalid rctl value: "
1786 				    "(priv=%s,limit=%s,action%s)"),
1787 				    rctlval->zone_rctlval_priv,
1788 				    rctlval->zone_rctlval_limit,
1789 				    rctlval->zone_rctlval_action);
1790 				goto out;
1791 			}
1792 			if (!zonecfg_valid_rctl(name, rctlblk)) {
1793 				zerror(gettext("(priv=%s,limit=%s,action=%s) "
1794 				    "is not a valid value for rctl '%s'"),
1795 				    rctlval->zone_rctlval_priv,
1796 				    rctlval->zone_rctlval_limit,
1797 				    rctlval->zone_rctlval_action,
1798 				    name);
1799 				goto out;
1800 			}
1801 		}
1802 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1803 	}
1804 	rctltab.zone_rctl_valptr = NULL;
1805 	error = Z_OK;
1806 out:
1807 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1808 	(void) zonecfg_endrctlent(handle);
1809 	free(rctlblk);
1810 	return (error);
1811 }
1812 
1813 static int
1814 verify_pool(zone_dochandle_t handle)
1815 {
1816 	char poolname[MAXPATHLEN];
1817 	pool_conf_t *poolconf;
1818 	pool_t *pool;
1819 	int status;
1820 	int error;
1821 
1822 	/*
1823 	 * This ends up being very similar to the check done in zoneadmd.
1824 	 */
1825 	error = zonecfg_get_pool(handle, poolname, sizeof (poolname));
1826 	if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
1827 		/*
1828 		 * No pool specified.
1829 		 */
1830 		return (0);
1831 	}
1832 	if (error != Z_OK) {
1833 		zperror(gettext("Unable to retrieve pool name from "
1834 		    "configuration"), B_TRUE);
1835 		return (error);
1836 	}
1837 	/*
1838 	 * Don't do anything if pools aren't enabled.
1839 	 */
1840 	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
1841 		zerror(gettext("WARNING: pools facility not active; "
1842 		    "zone will not be bound to pool '%s'."), poolname);
1843 		return (Z_OK);
1844 	}
1845 	/*
1846 	 * Try to provide a sane error message if the requested pool doesn't
1847 	 * exist.  It isn't clear that pools-related failures should
1848 	 * necessarily translate to a failure to verify the zone configuration,
1849 	 * hence they are not considered errors.
1850 	 */
1851 	if ((poolconf = pool_conf_alloc()) == NULL) {
1852 		zerror(gettext("WARNING: pool_conf_alloc failed; "
1853 		    "using default pool"));
1854 		return (Z_OK);
1855 	}
1856 	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
1857 	    PO_SUCCESS) {
1858 		zerror(gettext("WARNING: pool_conf_open failed; "
1859 		    "using default pool"));
1860 		pool_conf_free(poolconf);
1861 		return (Z_OK);
1862 	}
1863 	pool = pool_get_pool(poolconf, poolname);
1864 	(void) pool_conf_close(poolconf);
1865 	pool_conf_free(poolconf);
1866 	if (pool == NULL) {
1867 		zerror(gettext("WARNING: pool '%s' not found. "
1868 		    "using default pool"), poolname);
1869 	}
1870 
1871 	return (Z_OK);
1872 }
1873 
1874 static int
1875 verify_ipd(zone_dochandle_t handle)
1876 {
1877 	int return_code = Z_OK;
1878 	struct zone_fstab fstab;
1879 	struct stat st;
1880 	char specdir[MAXPATHLEN];
1881 
1882 	if (zonecfg_setipdent(handle) != Z_OK) {
1883 		/*
1884 		 * TRANSLATION_NOTE
1885 		 * inherit-pkg-dirs is a literal that should not be translated.
1886 		 */
1887 		(void) fprintf(stderr, gettext("could not verify "
1888 		    "inherit-pkg-dirs: unable to enumerate mounts\n"));
1889 		return (Z_ERR);
1890 	}
1891 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
1892 		/*
1893 		 * Verify fs_dir exists.
1894 		 */
1895 		(void) snprintf(specdir, sizeof (specdir), "%s%s",
1896 		    zonecfg_get_root(), fstab.zone_fs_dir);
1897 		if (stat(specdir, &st) != 0) {
1898 			/*
1899 			 * TRANSLATION_NOTE
1900 			 * inherit-pkg-dir is a literal that should not be
1901 			 * translated.
1902 			 */
1903 			(void) fprintf(stderr, gettext("could not verify "
1904 			    "inherit-pkg-dir %s: %s\n"),
1905 			    fstab.zone_fs_dir, strerror(errno));
1906 			return_code = Z_ERR;
1907 		}
1908 		if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
1909 			/*
1910 			 * TRANSLATION_NOTE
1911 			 * inherit-pkg-dir and NFS are literals that should
1912 			 * not be translated.
1913 			 */
1914 			(void) fprintf(stderr, gettext("cannot verify "
1915 			    "inherit-pkg-dir %s: NFS mounted file-system.\n"
1916 			    "\tA local file-system must be used.\n"),
1917 			    fstab.zone_fs_dir);
1918 			return_code = Z_ERR;
1919 		}
1920 	}
1921 	(void) zonecfg_endipdent(handle);
1922 
1923 	return (return_code);
1924 }
1925 
1926 /* ARGSUSED */
1927 static void
1928 zfs_fs_err_handler(const char *fmt, va_list ap)
1929 {
1930 	/*
1931 	 * Do nothing - do not print the libzfs error messages.
1932 	 */
1933 }
1934 
1935 /*
1936  * Verify that the ZFS dataset exists, and its mountpoint
1937  * property is set to "legacy".
1938  */
1939 static int
1940 verify_fs_zfs(struct zone_fstab *fstab)
1941 {
1942 	zfs_handle_t *zhp;
1943 	char propbuf[ZFS_MAXPROPLEN];
1944 
1945 	zfs_set_error_handler(zfs_fs_err_handler);
1946 
1947 	if ((zhp = zfs_open(fstab->zone_fs_special, ZFS_TYPE_ANY)) == NULL) {
1948 		(void) fprintf(stderr, gettext("could not verify fs %s: "
1949 			"could not access zfs dataset '%s'\n"),
1950 			fstab->zone_fs_dir, fstab->zone_fs_special);
1951 		return (Z_ERR);
1952 	}
1953 
1954 	if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
1955 		(void) fprintf(stderr, gettext("cannot verify fs %s: "
1956 			"'%s' is not a filesystem\n"),
1957 			fstab->zone_fs_dir, fstab->zone_fs_special);
1958 		zfs_close(zhp);
1959 		return (Z_ERR);
1960 	}
1961 
1962 	if (zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, propbuf, sizeof (propbuf),
1963 	    NULL, NULL, 0, 0) != 0 || strcmp(propbuf, "legacy") != 0) {
1964 		(void) fprintf(stderr, gettext("could not verify fs %s: "
1965 			"zfs '%s' mountpoint is not \"legacy\"\n"),
1966 			fstab->zone_fs_dir, fstab->zone_fs_special);
1967 		zfs_close(zhp);
1968 		return (Z_ERR);
1969 	}
1970 
1971 	zfs_close(zhp);
1972 	return (Z_OK);
1973 }
1974 
1975 /*
1976  * Verify that the special device/filesystem exists and is valid.
1977  */
1978 static int
1979 verify_fs_special(struct zone_fstab *fstab)
1980 {
1981 	struct stat st;
1982 
1983 	if (strcmp(fstab->zone_fs_type, MNTTYPE_ZFS) == 0)
1984 		return (verify_fs_zfs(fstab));
1985 
1986 	if (stat(fstab->zone_fs_special, &st) != 0) {
1987 		(void) fprintf(stderr, gettext("could not verify fs "
1988 		    "%s: could not access %s: %s\n"), fstab->zone_fs_dir,
1989 		    fstab->zone_fs_special, strerror(errno));
1990 		return (Z_ERR);
1991 	}
1992 
1993 	if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
1994 		/*
1995 		 * TRANSLATION_NOTE
1996 		 * fs and NFS are literals that should
1997 		 * not be translated.
1998 		 */
1999 		(void) fprintf(stderr, gettext("cannot verify "
2000 		    "fs %s: NFS mounted file-system.\n"
2001 		    "\tA local file-system must be used.\n"),
2002 		    fstab->zone_fs_special);
2003 		return (Z_ERR);
2004 	}
2005 
2006 	return (Z_OK);
2007 }
2008 
2009 static int
2010 verify_filesystems(zone_dochandle_t handle)
2011 {
2012 	int return_code = Z_OK;
2013 	struct zone_fstab fstab;
2014 	char cmdbuf[MAXPATHLEN];
2015 	struct stat st;
2016 
2017 	/*
2018 	 * No need to verify inherit-pkg-dir fs types, as their type is
2019 	 * implicitly lofs, which is known.  Therefore, the types are only
2020 	 * verified for regular filesystems below.
2021 	 *
2022 	 * Since the actual mount point is not known until the dependent mounts
2023 	 * are performed, we don't attempt any path validation here: that will
2024 	 * happen later when zoneadmd actually does the mounts.
2025 	 */
2026 	if (zonecfg_setfsent(handle) != Z_OK) {
2027 		(void) fprintf(stderr, gettext("could not verify file-systems: "
2028 		    "unable to enumerate mounts\n"));
2029 		return (Z_ERR);
2030 	}
2031 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
2032 		if (!zonecfg_valid_fs_type(fstab.zone_fs_type)) {
2033 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2034 			    "type %s is not allowed.\n"), fstab.zone_fs_dir,
2035 			    fstab.zone_fs_type);
2036 			return_code = Z_ERR;
2037 			goto next_fs;
2038 		}
2039 		/*
2040 		 * Verify /usr/lib/fs/<fstype>/mount exists.
2041 		 */
2042 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount",
2043 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
2044 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2045 			    "type %s is too long.\n"), fstab.zone_fs_dir,
2046 			    fstab.zone_fs_type);
2047 			return_code = Z_ERR;
2048 			goto next_fs;
2049 		}
2050 		if (stat(cmdbuf, &st) != 0) {
2051 			(void) fprintf(stderr, gettext("could not verify fs "
2052 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2053 			    cmdbuf, strerror(errno));
2054 			return_code = Z_ERR;
2055 			goto next_fs;
2056 		}
2057 		if (!S_ISREG(st.st_mode)) {
2058 			(void) fprintf(stderr, gettext("could not verify fs "
2059 			    "%s: %s is not a regular file\n"),
2060 			    fstab.zone_fs_dir, cmdbuf);
2061 			return_code = Z_ERR;
2062 			goto next_fs;
2063 		}
2064 		/*
2065 		 * Verify /usr/lib/fs/<fstype>/fsck exists iff zone_fs_raw is
2066 		 * set.
2067 		 */
2068 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck",
2069 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
2070 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2071 			    "type %s is too long.\n"), fstab.zone_fs_dir,
2072 			    fstab.zone_fs_type);
2073 			return_code = Z_ERR;
2074 			goto next_fs;
2075 		}
2076 		if (fstab.zone_fs_raw[0] == '\0' && stat(cmdbuf, &st) == 0) {
2077 			(void) fprintf(stderr, gettext("could not verify fs "
2078 			    "%s: must specify 'raw' device for %s "
2079 			    "file-systems\n"),
2080 			    fstab.zone_fs_dir, fstab.zone_fs_type);
2081 			return_code = Z_ERR;
2082 			goto next_fs;
2083 		}
2084 		if (fstab.zone_fs_raw[0] != '\0' &&
2085 		    (stat(cmdbuf, &st) != 0 || !S_ISREG(st.st_mode))) {
2086 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2087 			    "'raw' device specified but "
2088 			    "no fsck executable exists for %s\n"),
2089 			    fstab.zone_fs_dir, fstab.zone_fs_type);
2090 			return_code = Z_ERR;
2091 			goto next_fs;
2092 		}
2093 
2094 		/* Verify fs_special. */
2095 		if ((return_code = verify_fs_special(&fstab)) != Z_OK)
2096 			goto next_fs;
2097 
2098 		/* Verify fs_raw. */
2099 		if (fstab.zone_fs_raw[0] != '\0' &&
2100 		    stat(fstab.zone_fs_raw, &st) != 0) {
2101 			/*
2102 			 * TRANSLATION_NOTE
2103 			 * fs is a literal that should not be translated.
2104 			 */
2105 			(void) fprintf(stderr, gettext("could not verify fs "
2106 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2107 			    fstab.zone_fs_raw, strerror(errno));
2108 			return_code = Z_ERR;
2109 			goto next_fs;
2110 		}
2111 next_fs:
2112 		zonecfg_free_fs_option_list(fstab.zone_fs_options);
2113 	}
2114 	(void) zonecfg_endfsent(handle);
2115 
2116 	return (return_code);
2117 }
2118 
2119 const char *current_dataset;
2120 
2121 /*
2122  * Custom error handler for errors incurred as part of the checks below.  We
2123  * want to trim off the leading 'cannot open ...' to create a better error
2124  * message.  The only other way this can fail is if we fail to set the 'zoned'
2125  * property.  In this case we just pass the error on verbatim.
2126  */
2127 static void
2128 zfs_error_handler(const char *fmt, va_list ap)
2129 {
2130 	char buf[1024];
2131 
2132 	(void) vsnprintf(buf, sizeof (buf), fmt, ap);
2133 
2134 	if (strncmp(gettext("cannot open "), buf,
2135 	    strlen(gettext("cannot open "))) == 0)
2136 		/*
2137 		 * TRANSLATION_NOTE
2138 		 * zfs and dataset are literals that should not be translated.
2139 		 */
2140 		(void) fprintf(stderr, gettext("could not verify zfs "
2141 		    "dataset %s%s\n"), current_dataset, strchr(buf, ':'));
2142 	else
2143 		(void) fprintf(stderr, gettext("could not verify zfs dataset "
2144 		    "%s: %s\n"), current_dataset, buf);
2145 }
2146 
2147 /* ARGSUSED */
2148 static int
2149 check_zvol(zfs_handle_t *zhp, void *unused)
2150 {
2151 	int ret;
2152 
2153 	if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
2154 		/*
2155 		 * TRANSLATION_NOTE
2156 		 * zfs and dataset are literals that should not be translated.
2157 		 */
2158 		(void) fprintf(stderr, gettext("cannot verify zfs dataset %s: "
2159 		    "volumes cannot be specified as a zone dataset resource\n"),
2160 		    zfs_get_name(zhp));
2161 		ret = -1;
2162 	} else {
2163 		ret = zfs_iter_children(zhp, check_zvol, NULL);
2164 	}
2165 
2166 	zfs_close(zhp);
2167 
2168 	return (ret);
2169 }
2170 
2171 /*
2172  * Validate that the given dataset exists on the system, and that neither it nor
2173  * its children are zvols.
2174  *
2175  * Note that we don't do anything with the 'zoned' property here.  All
2176  * management is done in zoneadmd when the zone is actually rebooted.  This
2177  * allows us to automatically set the zoned property even when a zone is
2178  * rebooted by the administrator.
2179  */
2180 static int
2181 verify_datasets(zone_dochandle_t handle)
2182 {
2183 	int return_code = Z_OK;
2184 	struct zone_dstab dstab;
2185 	zfs_handle_t *zhp;
2186 	char propbuf[ZFS_MAXPROPLEN];
2187 	char source[ZFS_MAXNAMELEN];
2188 	zfs_source_t srctype;
2189 
2190 	if (zonecfg_setdsent(handle) != Z_OK) {
2191 		/*
2192 		 * TRANSLATION_NOTE
2193 		 * zfs and dataset are literals that should not be translated.
2194 		 */
2195 		(void) fprintf(stderr, gettext("could not verify zfs datasets: "
2196 		    "unable to enumerate datasets\n"));
2197 		return (Z_ERR);
2198 	}
2199 
2200 	zfs_set_error_handler(zfs_error_handler);
2201 
2202 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2203 
2204 		current_dataset = dstab.zone_dataset_name;
2205 
2206 		if ((zhp = zfs_open(dstab.zone_dataset_name,
2207 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
2208 			return_code = Z_ERR;
2209 			continue;
2210 		}
2211 
2212 		if (zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, propbuf,
2213 		    sizeof (propbuf), &srctype, source,
2214 		    sizeof (source), 0) == 0 &&
2215 		    (srctype == ZFS_SRC_INHERITED)) {
2216 			(void) fprintf(stderr, gettext("could not verify zfs "
2217 			    "dataset %s: mountpoint cannot be inherited\n"),
2218 			    dstab.zone_dataset_name);
2219 			return_code = Z_ERR;
2220 			zfs_close(zhp);
2221 			continue;
2222 		}
2223 
2224 		if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
2225 			(void) fprintf(stderr, gettext("cannot verify zfs "
2226 			    "dataset %s: volumes cannot be specified as a "
2227 			    "zone dataset resource\n"),
2228 			    dstab.zone_dataset_name);
2229 			return_code = Z_ERR;
2230 		}
2231 
2232 		if (zfs_iter_children(zhp, check_zvol, NULL) != 0)
2233 			return_code = Z_ERR;
2234 
2235 		zfs_close(zhp);
2236 	}
2237 	(void) zonecfg_enddsent(handle);
2238 
2239 	return (return_code);
2240 }
2241 
2242 static int
2243 verify_details(int cmd_num)
2244 {
2245 	zone_dochandle_t handle;
2246 	struct zone_nwiftab nwiftab;
2247 	char zonepath[MAXPATHLEN], checkpath[MAXPATHLEN];
2248 	int return_code = Z_OK;
2249 	int err;
2250 	boolean_t in_alt_root;
2251 
2252 	if ((handle = zonecfg_init_handle()) == NULL) {
2253 		zperror(cmd_to_str(cmd_num), B_TRUE);
2254 		return (Z_ERR);
2255 	}
2256 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
2257 		errno = err;
2258 		zperror(cmd_to_str(cmd_num), B_TRUE);
2259 		zonecfg_fini_handle(handle);
2260 		return (Z_ERR);
2261 	}
2262 	if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
2263 	    Z_OK) {
2264 		errno = err;
2265 		zperror(cmd_to_str(cmd_num), B_TRUE);
2266 		zonecfg_fini_handle(handle);
2267 		return (Z_ERR);
2268 	}
2269 	/*
2270 	 * zonecfg_get_zonepath() gets its data from the XML repository.
2271 	 * Verify this against the index file, which is checked first by
2272 	 * zone_get_zonepath().  If they don't match, bail out.
2273 	 */
2274 	if ((err = zone_get_zonepath(target_zone, checkpath,
2275 	    sizeof (checkpath))) != Z_OK) {
2276 		errno = err;
2277 		zperror2(target_zone, gettext("could not get zone path"));
2278 		return (Z_ERR);
2279 	}
2280 	if (strcmp(zonepath, checkpath) != 0) {
2281 		/*
2282 		 * TRANSLATION_NOTE
2283 		 * XML and zonepath are literals that should not be translated.
2284 		 */
2285 		(void) fprintf(stderr, gettext("The XML repository has "
2286 		    "zonepath '%s',\nbut the index file has zonepath '%s'.\n"
2287 		    "These must match, so fix the incorrect entry.\n"),
2288 		    zonepath, checkpath);
2289 		return (Z_ERR);
2290 	}
2291 	if (validate_zonepath(zonepath, cmd_num) != Z_OK) {
2292 		(void) fprintf(stderr, gettext("could not verify zonepath %s "
2293 		    "because of the above errors.\n"), zonepath);
2294 		return_code = Z_ERR;
2295 	}
2296 
2297 	in_alt_root = zonecfg_in_alt_root();
2298 	if (in_alt_root)
2299 		goto no_net;
2300 
2301 	if ((err = zonecfg_setnwifent(handle)) != Z_OK) {
2302 		errno = err;
2303 		zperror(cmd_to_str(cmd_num), B_TRUE);
2304 		zonecfg_fini_handle(handle);
2305 		return (Z_ERR);
2306 	}
2307 	while (zonecfg_getnwifent(handle, &nwiftab) == Z_OK) {
2308 		struct lifreq lifr;
2309 		sa_family_t af;
2310 		int so, res;
2311 
2312 		/* skip any loopback interfaces */
2313 		if (strcmp(nwiftab.zone_nwif_physical, "lo0") == 0)
2314 			continue;
2315 		if ((res = zonecfg_valid_net_address(nwiftab.zone_nwif_address,
2316 		    &lifr)) != Z_OK) {
2317 			(void) fprintf(stderr, gettext("could not verify %s "
2318 			    "%s=%s %s=%s: %s\n"), "net", "address",
2319 			    nwiftab.zone_nwif_address, "physical",
2320 			    nwiftab.zone_nwif_physical, zonecfg_strerror(res));
2321 			return_code = Z_ERR;
2322 			continue;
2323 		}
2324 		af = lifr.lifr_addr.ss_family;
2325 		(void) memset(&lifr, 0, sizeof (lifr));
2326 		(void) strlcpy(lifr.lifr_name, nwiftab.zone_nwif_physical,
2327 		    sizeof (lifr.lifr_name));
2328 		lifr.lifr_addr.ss_family = af;
2329 		if ((so = socket(af, SOCK_DGRAM, 0)) < 0) {
2330 			(void) fprintf(stderr, gettext("could not verify %s "
2331 			    "%s=%s %s=%s: could not get socket: %s\n"), "net",
2332 			    "address", nwiftab.zone_nwif_address, "physical",
2333 			    nwiftab.zone_nwif_physical, strerror(errno));
2334 			return_code = Z_ERR;
2335 			continue;
2336 		}
2337 		if (ioctl(so, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2338 			(void) fprintf(stderr,
2339 			    gettext("could not verify %s %s=%s %s=%s: %s\n"),
2340 			    "net", "address", nwiftab.zone_nwif_address,
2341 			    "physical", nwiftab.zone_nwif_physical,
2342 			    strerror(errno));
2343 			return_code = Z_ERR;
2344 		}
2345 		(void) close(so);
2346 	}
2347 	(void) zonecfg_endnwifent(handle);
2348 no_net:
2349 
2350 	if (verify_filesystems(handle) != Z_OK)
2351 		return_code = Z_ERR;
2352 	if (verify_ipd(handle) != Z_OK)
2353 		return_code = Z_ERR;
2354 	if (!in_alt_root && verify_rctls(handle) != Z_OK)
2355 		return_code = Z_ERR;
2356 	if (!in_alt_root && verify_pool(handle) != Z_OK)
2357 		return_code = Z_ERR;
2358 	if (!in_alt_root && verify_datasets(handle) != Z_OK)
2359 		return_code = Z_ERR;
2360 	zonecfg_fini_handle(handle);
2361 	if (return_code == Z_ERR)
2362 		(void) fprintf(stderr,
2363 		    gettext("%s: zone %s failed to verify\n"),
2364 		    execname, target_zone);
2365 	return (return_code);
2366 }
2367 
2368 static int
2369 verify_func(int argc, char *argv[])
2370 {
2371 	int arg;
2372 
2373 	optind = 0;
2374 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2375 		switch (arg) {
2376 		case '?':
2377 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2378 			return (optopt == '?' ? Z_OK : Z_USAGE);
2379 		default:
2380 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2381 			return (Z_USAGE);
2382 		}
2383 	}
2384 	if (argc > optind) {
2385 		sub_usage(SHELP_VERIFY, CMD_VERIFY);
2386 		return (Z_USAGE);
2387 	}
2388 	if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE) != Z_OK)
2389 		return (Z_ERR);
2390 	return (verify_details(CMD_VERIFY));
2391 }
2392 
2393 #define	LUCREATEZONE	"/usr/lib/lu/lucreatezone"
2394 
2395 static int
2396 install_func(int argc, char *argv[])
2397 {
2398 	/* 9: "exec " and " -z " */
2399 	char cmdbuf[sizeof (LUCREATEZONE) + ZONENAME_MAX + 9];
2400 	int lockfd;
2401 	int err, arg;
2402 	char zonepath[MAXPATHLEN];
2403 	int status;
2404 
2405 	if (zonecfg_in_alt_root()) {
2406 		zerror(gettext("cannot install zone in alternate root"));
2407 		return (Z_ERR);
2408 	}
2409 
2410 	optind = 0;
2411 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2412 		switch (arg) {
2413 		case '?':
2414 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
2415 			return (optopt == '?' ? Z_OK : Z_USAGE);
2416 		default:
2417 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
2418 			return (Z_USAGE);
2419 		}
2420 	}
2421 	if (argc > optind) {
2422 		sub_usage(SHELP_INSTALL, CMD_INSTALL);
2423 		return (Z_USAGE);
2424 	}
2425 	if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE) != Z_OK)
2426 		return (Z_ERR);
2427 	if (verify_details(CMD_INSTALL) != Z_OK)
2428 		return (Z_ERR);
2429 
2430 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
2431 		zerror(gettext("another %s may have an operation in progress."),
2432 		    "zoneadm");
2433 		return (Z_ERR);
2434 	}
2435 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
2436 	if (err != Z_OK) {
2437 		errno = err;
2438 		zperror2(target_zone, gettext("could not set state"));
2439 		goto done;
2440 	}
2441 
2442 	/*
2443 	 * According to the Application Packaging Developer's Guide, a
2444 	 * "checkinstall" script when included in a package is executed as
2445 	 * the user "install", if such a user exists, or by the user
2446 	 * "nobody".  In order to support this dubious behavior, the path
2447 	 * to the zone being constructed is opened up during the life of
2448 	 * the command laying down the zone's root file system.  Once this
2449 	 * has completed, regardless of whether it was successful, the
2450 	 * path to the zone is again restricted.
2451 	 */
2452 	if ((err = zone_get_zonepath(target_zone, zonepath,
2453 	    sizeof (zonepath))) != Z_OK) {
2454 		errno = err;
2455 		zperror2(target_zone, gettext("could not get zone path"));
2456 		goto done;
2457 	}
2458 	if (chmod(zonepath, DEFAULT_DIR_MODE) != 0) {
2459 		zperror(zonepath, B_FALSE);
2460 		err = Z_ERR;
2461 		goto done;
2462 	}
2463 
2464 	/*
2465 	 * "exec" the command so that the returned status is that of
2466 	 * LUCREATEZONE and not the shell.
2467 	 */
2468 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " LUCREATEZONE " -z %s",
2469 	    target_zone);
2470 	status = do_subproc(cmdbuf);
2471 	if (chmod(zonepath, S_IRWXU) != 0) {
2472 		zperror(zonepath, B_FALSE);
2473 		err = Z_ERR;
2474 		goto done;
2475 	}
2476 	if ((err = subproc_status(LUCREATEZONE, status)) != Z_OK)
2477 		goto done;
2478 
2479 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
2480 		errno = err;
2481 		zperror2(target_zone, gettext("could not set state"));
2482 		goto done;
2483 	}
2484 
2485 done:
2486 	release_lock_file(lockfd);
2487 	return ((err == Z_OK) ? Z_OK : Z_ERR);
2488 }
2489 
2490 /*
2491  * Check that the inherited pkg dirs are the same for the clone and its source.
2492  * The easiest way to do that is check that the list of ipds is the same
2493  * by matching each one against the other.  This algorithm should be fine since
2494  * the list of ipds should not be that long.
2495  */
2496 static int
2497 valid_ipd_clone(zone_dochandle_t s_handle, char *source_zone,
2498 	zone_dochandle_t t_handle, char *target_zone)
2499 {
2500 	int err;
2501 	int res = Z_OK;
2502 	int s_cnt = 0;
2503 	int t_cnt = 0;
2504 	struct zone_fstab s_fstab;
2505 	struct zone_fstab t_fstab;
2506 
2507 	/*
2508 	 * First check the source of the clone against the target.
2509 	 */
2510 	if ((err = zonecfg_setipdent(s_handle)) != Z_OK) {
2511 		errno = err;
2512 		zperror2(source_zone, gettext("could not enumerate "
2513 		    "inherit-pkg-dirs"));
2514 		return (Z_ERR);
2515 	}
2516 
2517 	while (zonecfg_getipdent(s_handle, &s_fstab) == Z_OK) {
2518 		boolean_t match = B_FALSE;
2519 
2520 		s_cnt++;
2521 
2522 		if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
2523 			errno = err;
2524 			zperror2(target_zone, gettext("could not enumerate "
2525 			    "inherit-pkg-dirs"));
2526 			(void) zonecfg_endipdent(s_handle);
2527 			return (Z_ERR);
2528 		}
2529 
2530 		while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK) {
2531 			if (strcmp(s_fstab.zone_fs_dir, t_fstab.zone_fs_dir)
2532 			    == 0) {
2533 				match = B_TRUE;
2534 				break;
2535 			}
2536 		}
2537 		(void) zonecfg_endipdent(t_handle);
2538 
2539 		if (!match) {
2540 			(void) fprintf(stderr, gettext("inherit-pkg-dir "
2541 			    "'%s' is not configured in zone %s.\n"),
2542 			    s_fstab.zone_fs_dir, target_zone);
2543 			res = Z_ERR;
2544 		}
2545 	}
2546 
2547 	(void) zonecfg_endipdent(s_handle);
2548 
2549 	/* skip the next check if we already have errors */
2550 	if (res == Z_ERR)
2551 		return (res);
2552 
2553 	/*
2554 	 * Now check the number of ipds in the target so we can verify
2555 	 * that the source is not a subset of the target.
2556 	 */
2557 	if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
2558 		errno = err;
2559 		zperror2(target_zone, gettext("could not enumerate "
2560 		    "inherit-pkg-dirs"));
2561 		return (Z_ERR);
2562 	}
2563 
2564 	while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK)
2565 		t_cnt++;
2566 
2567 	(void) zonecfg_endipdent(t_handle);
2568 
2569 	if (t_cnt != s_cnt) {
2570 		(void) fprintf(stderr, gettext("Zone %s is configured "
2571 		    "with inherit-pkg-dirs that are not configured in zone "
2572 		    "%s.\n"), target_zone, source_zone);
2573 		res = Z_ERR;
2574 	}
2575 
2576 	return (res);
2577 }
2578 
2579 static void
2580 warn_dev_match(zone_dochandle_t s_handle, char *source_zone,
2581 	zone_dochandle_t t_handle, char *target_zone)
2582 {
2583 	int err;
2584 	struct zone_devtab s_devtab;
2585 	struct zone_devtab t_devtab;
2586 
2587 	if ((err = zonecfg_setdevent(t_handle)) != Z_OK) {
2588 		errno = err;
2589 		zperror2(target_zone, gettext("could not enumerate devices"));
2590 		return;
2591 	}
2592 
2593 	while (zonecfg_getdevent(t_handle, &t_devtab) == Z_OK) {
2594 		if ((err = zonecfg_setdevent(s_handle)) != Z_OK) {
2595 			errno = err;
2596 			zperror2(source_zone,
2597 			    gettext("could not enumerate devices"));
2598 			(void) zonecfg_enddevent(t_handle);
2599 			return;
2600 		}
2601 
2602 		while (zonecfg_getdevent(s_handle, &s_devtab) == Z_OK) {
2603 			/*
2604 			 * Use fnmatch to catch the case where wildcards
2605 			 * were used in one zone and the other has an
2606 			 * explicit entry (e.g. /dev/dsk/c0t0d0s6 vs.
2607 			 * /dev/\*dsk/c0t0d0s6).
2608 			 */
2609 			if (fnmatch(t_devtab.zone_dev_match,
2610 			    s_devtab.zone_dev_match, FNM_PATHNAME) == 0 ||
2611 			    fnmatch(s_devtab.zone_dev_match,
2612 			    t_devtab.zone_dev_match, FNM_PATHNAME) == 0) {
2613 				(void) fprintf(stderr,
2614 				    gettext("WARNING: device '%s' "
2615 				    "is configured in both zones.\n"),
2616 				    t_devtab.zone_dev_match);
2617 				break;
2618 			}
2619 		}
2620 		(void) zonecfg_enddevent(s_handle);
2621 	}
2622 
2623 	(void) zonecfg_enddevent(t_handle);
2624 }
2625 
2626 /*
2627  * Check if the specified mount option (opt) is contained within the
2628  * options string.
2629  */
2630 static boolean_t
2631 opt_match(char *opt, char *options)
2632 {
2633 	char *p;
2634 	char *lastp;
2635 
2636 	if ((p = strtok_r(options, ",", &lastp)) != NULL) {
2637 		if (strcmp(p, opt) == 0)
2638 			return (B_TRUE);
2639 		while ((p = strtok_r(NULL, ",", &lastp)) != NULL) {
2640 			if (strcmp(p, opt) == 0)
2641 				return (B_TRUE);
2642 		}
2643 	}
2644 
2645 	return (B_FALSE);
2646 }
2647 
2648 #define	RW_LOFS	"WARNING: read-write lofs file-system on '%s' is configured " \
2649 	"in both zones.\n"
2650 
2651 static void
2652 print_fs_warnings(struct zone_fstab *s_fstab, struct zone_fstab *t_fstab)
2653 {
2654 	/*
2655 	 * It is ok to have shared lofs mounted fs but we want to warn if
2656 	 * either is rw since this will effect the other zone.
2657 	 */
2658 	if (strcmp(t_fstab->zone_fs_type, "lofs") == 0) {
2659 		zone_fsopt_t *optp;
2660 
2661 		/* The default is rw so no options means rw */
2662 		if (t_fstab->zone_fs_options == NULL ||
2663 		    s_fstab->zone_fs_options == NULL) {
2664 			(void) fprintf(stderr, gettext(RW_LOFS),
2665 			    t_fstab->zone_fs_special);
2666 			return;
2667 		}
2668 
2669 		for (optp = s_fstab->zone_fs_options; optp != NULL;
2670 		    optp = optp->zone_fsopt_next) {
2671 			if (opt_match("rw", optp->zone_fsopt_opt)) {
2672 				(void) fprintf(stderr, gettext(RW_LOFS),
2673 				    s_fstab->zone_fs_special);
2674 				return;
2675 			}
2676 		}
2677 
2678 		for (optp = t_fstab->zone_fs_options; optp != NULL;
2679 		    optp = optp->zone_fsopt_next) {
2680 			if (opt_match("rw", optp->zone_fsopt_opt)) {
2681 				(void) fprintf(stderr, gettext(RW_LOFS),
2682 				    t_fstab->zone_fs_special);
2683 				return;
2684 			}
2685 		}
2686 
2687 		return;
2688 	}
2689 
2690 	/*
2691 	 * TRANSLATION_NOTE
2692 	 * The first variable is the file-system type and the second is
2693 	 * the file-system special device.  For example,
2694 	 * WARNING: ufs file-system on '/dev/dsk/c0t0d0s0' ...
2695 	 */
2696 	(void) fprintf(stderr, gettext("WARNING: %s file-system on '%s' "
2697 	    "is configured in both zones.\n"), t_fstab->zone_fs_type,
2698 	    t_fstab->zone_fs_special);
2699 }
2700 
2701 static void
2702 warn_fs_match(zone_dochandle_t s_handle, char *source_zone,
2703 	zone_dochandle_t t_handle, char *target_zone)
2704 {
2705 	int err;
2706 	struct zone_fstab s_fstab;
2707 	struct zone_fstab t_fstab;
2708 
2709 	if ((err = zonecfg_setfsent(t_handle)) != Z_OK) {
2710 		errno = err;
2711 		zperror2(target_zone,
2712 		    gettext("could not enumerate file-systems"));
2713 		return;
2714 	}
2715 
2716 	while (zonecfg_getfsent(t_handle, &t_fstab) == Z_OK) {
2717 		if ((err = zonecfg_setfsent(s_handle)) != Z_OK) {
2718 			errno = err;
2719 			zperror2(source_zone,
2720 			    gettext("could not enumerate file-systems"));
2721 			(void) zonecfg_endfsent(t_handle);
2722 			return;
2723 		}
2724 
2725 		while (zonecfg_getfsent(s_handle, &s_fstab) == Z_OK) {
2726 			if (strcmp(t_fstab.zone_fs_special,
2727 			    s_fstab.zone_fs_special) == 0) {
2728 				print_fs_warnings(&s_fstab, &t_fstab);
2729 				break;
2730 			}
2731 		}
2732 		(void) zonecfg_endfsent(s_handle);
2733 	}
2734 
2735 	(void) zonecfg_endfsent(t_handle);
2736 }
2737 
2738 /*
2739  * We don't catch the case where you used the same IP address but
2740  * it is not an exact string match.  For example, 192.9.0.128 vs. 192.09.0.128.
2741  * However, we're not going to worry about that but we will check for
2742  * a possible netmask on one of the addresses (e.g. 10.0.0.1 and 10.0.0.1/24)
2743  * and handle that case as a match.
2744  */
2745 static void
2746 warn_ip_match(zone_dochandle_t s_handle, char *source_zone,
2747 	zone_dochandle_t t_handle, char *target_zone)
2748 {
2749 	int err;
2750 	struct zone_nwiftab s_nwiftab;
2751 	struct zone_nwiftab t_nwiftab;
2752 
2753 	if ((err = zonecfg_setnwifent(t_handle)) != Z_OK) {
2754 		errno = err;
2755 		zperror2(target_zone,
2756 		    gettext("could not enumerate network interfaces"));
2757 		return;
2758 	}
2759 
2760 	while (zonecfg_getnwifent(t_handle, &t_nwiftab) == Z_OK) {
2761 		char *p;
2762 
2763 		/* remove an (optional) netmask from the address */
2764 		if ((p = strchr(t_nwiftab.zone_nwif_address, '/')) != NULL)
2765 			*p = '\0';
2766 
2767 		if ((err = zonecfg_setnwifent(s_handle)) != Z_OK) {
2768 			errno = err;
2769 			zperror2(source_zone,
2770 			    gettext("could not enumerate network interfaces"));
2771 			(void) zonecfg_endnwifent(t_handle);
2772 			return;
2773 		}
2774 
2775 		while (zonecfg_getnwifent(s_handle, &s_nwiftab) == Z_OK) {
2776 			/* remove an (optional) netmask from the address */
2777 			if ((p = strchr(s_nwiftab.zone_nwif_address, '/'))
2778 			    != NULL)
2779 				*p = '\0';
2780 
2781 			if (strcmp(t_nwiftab.zone_nwif_address,
2782 			    s_nwiftab.zone_nwif_address) == 0) {
2783 				(void) fprintf(stderr,
2784 				    gettext("WARNING: network address '%s' "
2785 				    "is configured in both zones.\n"),
2786 				    t_nwiftab.zone_nwif_address);
2787 				break;
2788 			}
2789 		}
2790 		(void) zonecfg_endnwifent(s_handle);
2791 	}
2792 
2793 	(void) zonecfg_endnwifent(t_handle);
2794 }
2795 
2796 static void
2797 warn_dataset_match(zone_dochandle_t s_handle, char *source_zone,
2798 	zone_dochandle_t t_handle, char *target_zone)
2799 {
2800 	int err;
2801 	struct zone_dstab s_dstab;
2802 	struct zone_dstab t_dstab;
2803 
2804 	if ((err = zonecfg_setdsent(t_handle)) != Z_OK) {
2805 		errno = err;
2806 		zperror2(target_zone, gettext("could not enumerate datasets"));
2807 		return;
2808 	}
2809 
2810 	while (zonecfg_getdsent(t_handle, &t_dstab) == Z_OK) {
2811 		if ((err = zonecfg_setdsent(s_handle)) != Z_OK) {
2812 			errno = err;
2813 			zperror2(source_zone,
2814 			    gettext("could not enumerate datasets"));
2815 			(void) zonecfg_enddsent(t_handle);
2816 			return;
2817 		}
2818 
2819 		while (zonecfg_getdsent(s_handle, &s_dstab) == Z_OK) {
2820 			if (strcmp(t_dstab.zone_dataset_name,
2821 			    s_dstab.zone_dataset_name) == 0) {
2822 				(void) fprintf(stderr,
2823 				    gettext("WARNING: dataset '%s' "
2824 				    "is configured in both zones.\n"),
2825 				    t_dstab.zone_dataset_name);
2826 				break;
2827 			}
2828 		}
2829 		(void) zonecfg_enddsent(s_handle);
2830 	}
2831 
2832 	(void) zonecfg_enddsent(t_handle);
2833 }
2834 
2835 static int
2836 validate_clone(char *source_zone, char *target_zone)
2837 {
2838 	int err = Z_OK;
2839 	zone_dochandle_t s_handle;
2840 	zone_dochandle_t t_handle;
2841 
2842 	if ((t_handle = zonecfg_init_handle()) == NULL) {
2843 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
2844 		return (Z_ERR);
2845 	}
2846 	if ((err = zonecfg_get_handle(target_zone, t_handle)) != Z_OK) {
2847 		errno = err;
2848 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
2849 		zonecfg_fini_handle(t_handle);
2850 		return (Z_ERR);
2851 	}
2852 
2853 	if ((s_handle = zonecfg_init_handle()) == NULL) {
2854 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
2855 		zonecfg_fini_handle(t_handle);
2856 		return (Z_ERR);
2857 	}
2858 	if ((err = zonecfg_get_handle(source_zone, s_handle)) != Z_OK) {
2859 		errno = err;
2860 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
2861 		goto done;
2862 	}
2863 
2864 	/* verify new zone has same inherit-pkg-dirs */
2865 	err = valid_ipd_clone(s_handle, source_zone, t_handle, target_zone);
2866 
2867 	/* warn about imported fs's which are the same */
2868 	warn_fs_match(s_handle, source_zone, t_handle, target_zone);
2869 
2870 	/* warn about imported IP addresses which are the same */
2871 	warn_ip_match(s_handle, source_zone, t_handle, target_zone);
2872 
2873 	/* warn about imported devices which are the same */
2874 	warn_dev_match(s_handle, source_zone, t_handle, target_zone);
2875 
2876 	/* warn about imported datasets which are the same */
2877 	warn_dataset_match(s_handle, source_zone, t_handle, target_zone);
2878 
2879 done:
2880 	zonecfg_fini_handle(t_handle);
2881 	zonecfg_fini_handle(s_handle);
2882 
2883 	return ((err == Z_OK) ? Z_OK : Z_ERR);
2884 }
2885 
2886 static int
2887 copy_zone(char *src, char *dst)
2888 {
2889 	boolean_t out_null = B_FALSE;
2890 	int status;
2891 	int err;
2892 	char *outfile;
2893 	char cmdbuf[MAXPATHLEN * 2 + 128];
2894 
2895 	if ((outfile = tempnam("/var/log", "zone")) == NULL) {
2896 		outfile = "/dev/null";
2897 		out_null = B_TRUE;
2898 	}
2899 
2900 	(void) snprintf(cmdbuf, sizeof (cmdbuf),
2901 	    "cd %s && /usr/bin/find . -depth -print | "
2902 	    "/usr/bin/cpio -pdmuP@ %s > %s 2>&1",
2903 	    src, dst, outfile);
2904 
2905 	status = do_subproc(cmdbuf);
2906 
2907 	if ((err = subproc_status("copy", status)) != Z_OK) {
2908 		if (!out_null)
2909 			(void) fprintf(stderr, gettext("\nThe copy failed.\n"
2910 			    "More information can be found in %s\n"), outfile);
2911 		return (err);
2912 	}
2913 
2914 	if (!out_null)
2915 		(void) unlink(outfile);
2916 
2917 	return (Z_OK);
2918 }
2919 
2920 /*
2921  * Wait until the target_zone has booted to single-user.  Return Z_OK once
2922  * the zone has booted to that level or return Z_BAD_ZONE_STATE if the zone
2923  * has not booted to single-user after the timeout.
2924  */
2925 static int
2926 zone_wait_single_user()
2927 {
2928 	char cmdbuf[ZONENAME_MAX + 256];
2929 	int retry;
2930 
2931 	(void) snprintf(cmdbuf, sizeof (cmdbuf),
2932 	    "test \"`/usr/sbin/zlogin -S %s /usr/bin/svcprop -p "
2933 	    "restarter/state svc:/milestone/single-user:default 2>/dev/null`\" "
2934 	    "= \"online\"",
2935 	    target_zone);
2936 
2937 	for (retry = 0; retry < SINGLE_USER_RETRY; retry++) {
2938 		int status;
2939 
2940 		status = do_subproc(cmdbuf);
2941 		if (WIFEXITED(status)) {
2942 			if (WEXITSTATUS(status) == 0)
2943 				return (Z_OK);
2944 
2945 			(void) sleep(2);
2946 		} else {
2947 			return (Z_BAD_ZONE_STATE);
2948 		}
2949 	}
2950 
2951 	return (Z_BAD_ZONE_STATE);
2952 }
2953 
2954 
2955 /* ARGSUSED */
2956 int
2957 zfm_print(const char *p, void *r) {
2958 	zerror("  %s\n", p);
2959 	return (0);
2960 }
2961 
2962 static int
2963 clone_func(int argc, char *argv[])
2964 {
2965 	char cmdbuf[MAXPATHLEN];
2966 	char *source_zone = NULL;
2967 	int lockfd;
2968 	int err, arg;
2969 	char zonepath[MAXPATHLEN];
2970 	char source_zonepath[MAXPATHLEN];
2971 	int status;
2972 	zone_state_t state;
2973 	zone_entry_t *zent;
2974 	char *method = "copy";
2975 	char *boot_args[] = { "-s", NULL };
2976 	char *halt_args[] = { NULL };
2977 	struct stat unconfig_buf;
2978 	boolean_t revert;
2979 
2980 	if (zonecfg_in_alt_root()) {
2981 		zerror(gettext("cannot clone zone in alternate root"));
2982 		return (Z_ERR);
2983 	}
2984 
2985 	optind = 0;
2986 	if ((arg = getopt(argc, argv, "?m:")) != EOF) {
2987 		switch (arg) {
2988 		case '?':
2989 			sub_usage(SHELP_CLONE, CMD_CLONE);
2990 			return (optopt == '?' ? Z_OK : Z_USAGE);
2991 		case 'm':
2992 			method = optarg;
2993 			break;
2994 		default:
2995 			sub_usage(SHELP_CLONE, CMD_CLONE);
2996 			return (Z_USAGE);
2997 		}
2998 	}
2999 	if (argc != (optind + 1) || strcmp(method, "copy") != 0) {
3000 		sub_usage(SHELP_CLONE, CMD_CLONE);
3001 		return (Z_USAGE);
3002 	}
3003 	source_zone = argv[optind];
3004 	if (sanity_check(target_zone, CMD_CLONE, B_FALSE, B_TRUE) != Z_OK)
3005 		return (Z_ERR);
3006 	if (verify_details(CMD_CLONE) != Z_OK)
3007 		return (Z_ERR);
3008 
3009 	/*
3010 	 * We also need to do some extra validation on the source zone.
3011 	 */
3012 
3013 	if (strcmp(source_zone, GLOBAL_ZONENAME) == 0) {
3014 		zerror(gettext("%s operation is invalid for the global zone."),
3015 		    cmd_to_str(CMD_CLONE));
3016 		return (Z_ERR);
3017 	}
3018 
3019 	if (strncmp(source_zone, "SUNW", 4) == 0) {
3020 		zerror(gettext("%s operation is invalid for zones starting "
3021 		    "with SUNW."), cmd_to_str(CMD_CLONE));
3022 		return (Z_ERR);
3023 	}
3024 
3025 	zent = lookup_running_zone(source_zone);
3026 	if (zent != NULL) {
3027 		/* check whether the zone is ready or running */
3028 		if ((err = zone_get_state(zent->zname, &zent->zstate_num))
3029 		    != Z_OK) {
3030 			errno = err;
3031 			zperror2(zent->zname, gettext("could not get state"));
3032 			/* can't tell, so hedge */
3033 			zent->zstate_str = "ready/running";
3034 		} else {
3035 			zent->zstate_str = zone_state_str(zent->zstate_num);
3036 		}
3037 		zerror(gettext("%s operation is invalid for %s zones."),
3038 		    cmd_to_str(CMD_CLONE), zent->zstate_str);
3039 		return (Z_ERR);
3040 	}
3041 
3042 	if ((err = zone_get_state(source_zone, &state)) != Z_OK) {
3043 		errno = err;
3044 		zperror2(source_zone, gettext("could not get state"));
3045 		return (Z_ERR);
3046 	}
3047 	if (state != ZONE_STATE_INSTALLED) {
3048 		(void) fprintf(stderr,
3049 		    gettext("%s: zone %s is %s; %s is required.\n"),
3050 		    execname, source_zone, zone_state_str(state),
3051 		    zone_state_str(ZONE_STATE_INSTALLED));
3052 		return (Z_ERR);
3053 	}
3054 
3055 	/*
3056 	 * The source zone checks out ok, continue with the clone.
3057 	 */
3058 
3059 	if (validate_clone(source_zone, target_zone) != Z_OK)
3060 		return (Z_ERR);
3061 
3062 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
3063 		zerror(gettext("another %s may have an operation in progress."),
3064 		    "zoneadm");
3065 		return (Z_ERR);
3066 	}
3067 
3068 	if ((err = zone_get_zonepath(source_zone, source_zonepath,
3069 	    sizeof (source_zonepath))) != Z_OK) {
3070 		errno = err;
3071 		zperror2(source_zone, gettext("could not get zone path"));
3072 		goto done;
3073 	}
3074 
3075 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3076 	    != Z_OK) {
3077 		errno = err;
3078 		zperror2(target_zone, gettext("could not get zone path"));
3079 		goto done;
3080 	}
3081 
3082 	/* Don't clone the zone if anything is still mounted there */
3083 	if (zonecfg_find_mounts(source_zonepath, NULL, NULL)) {
3084 		zerror(gettext("These file-systems are mounted on "
3085 		    "subdirectories of %s.\n"), source_zonepath);
3086 		(void) zonecfg_find_mounts(source_zonepath, zfm_print, NULL);
3087 		err = Z_ERR;
3088 		goto done;
3089 	}
3090 
3091 	if ((err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE))
3092 	    != Z_OK) {
3093 		errno = err;
3094 		zperror2(target_zone, gettext("could not set state"));
3095 		goto done;
3096 	}
3097 
3098 	(void) printf(gettext("Cloning zonepath %s..."), source_zonepath);
3099 	(void) fflush(stdout);
3100 
3101 	if ((err = copy_zone(source_zonepath, zonepath)) != Z_OK)
3102 		goto done;
3103 
3104 	/*
3105 	 * We have to set the state of the zone to installed so that we
3106 	 * can boot it and sys-unconfig it from within the zone.  However,
3107 	 * if something fails during the boot/sys-unconfig, we want to set
3108 	 * the state back to incomplete.  We use the revert flag to keep
3109 	 * track of this.
3110 	 */
3111 	revert = B_TRUE;
3112 
3113 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
3114 		errno = err;
3115 		zperror2(target_zone, gettext("\ncould not set state"));
3116 		goto done;
3117 	}
3118 
3119 	/*
3120 	 * Check if the zone is already sys-unconfiged.  This saves us
3121 	 * the work of booting the zone so we can unconfigure it.
3122 	 */
3123 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "%s/root/etc/.UNCONFIGURED",
3124 	    zonepath);
3125 	if (stat(cmdbuf, &unconfig_buf) == -1) {
3126 		if ((err = boot_func(1, boot_args)) != Z_OK) {
3127 			errno = err;
3128 			zperror2(target_zone, gettext("\nCould not boot zone "
3129 			    "for sys-unconfig\n"));
3130 			goto done;
3131 		}
3132 
3133 		if ((err = zone_wait_single_user()) != Z_OK) {
3134 			errno = err;
3135 			zperror2(target_zone, gettext("\nCould not boot zone "
3136 			    "for sys-unconfig\n"));
3137 			(void) halt_func(0, halt_args);
3138 			goto done;
3139 		}
3140 
3141 		(void) snprintf(cmdbuf, sizeof (cmdbuf),
3142 		    "echo y | /usr/sbin/zlogin -S %s /usr/sbin/sys-unconfig",
3143 		    target_zone);
3144 
3145 		status = do_subproc(cmdbuf);
3146 		if ((err = subproc_status("sys-unconfig", status)) != Z_OK) {
3147 			errno = err;
3148 			zperror2(target_zone,
3149 			    gettext("\nsys-unconfig failed\n"));
3150 			/*
3151 			 * The sys-unconfig halts the zone but if it failed,
3152 			 * for some reason, we'll try to halt it now.
3153 			 */
3154 			(void) halt_func(0, halt_args);
3155 			goto done;
3156 		}
3157 	}
3158 
3159 	revert = B_FALSE;
3160 
3161 done:
3162 	(void) printf("\n");
3163 
3164 	if (revert)
3165 		(void) zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
3166 
3167 	release_lock_file(lockfd);
3168 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3169 }
3170 
3171 #define	RMCOMMAND	"/usr/bin/rm -rf"
3172 
3173 static int
3174 move_func(int argc, char *argv[])
3175 {
3176 	/* 6: "exec " and " " */
3177 	char cmdbuf[sizeof (RMCOMMAND) + MAXPATHLEN + 6];
3178 	char *new_zonepath = NULL;
3179 	int lockfd;
3180 	int err, arg;
3181 	char zonepath[MAXPATHLEN];
3182 	zone_dochandle_t handle;
3183 	boolean_t fast;
3184 	boolean_t revert;
3185 	struct stat zonepath_buf;
3186 	struct stat new_zonepath_buf;
3187 
3188 	if (zonecfg_in_alt_root()) {
3189 		zerror(gettext("cannot move zone in alternate root"));
3190 		return (Z_ERR);
3191 	}
3192 
3193 	optind = 0;
3194 	if ((arg = getopt(argc, argv, "?")) != EOF) {
3195 		switch (arg) {
3196 		case '?':
3197 			sub_usage(SHELP_MOVE, CMD_MOVE);
3198 			return (optopt == '?' ? Z_OK : Z_USAGE);
3199 		default:
3200 			sub_usage(SHELP_MOVE, CMD_MOVE);
3201 			return (Z_USAGE);
3202 		}
3203 	}
3204 	if (argc != (optind + 1)) {
3205 		sub_usage(SHELP_MOVE, CMD_MOVE);
3206 		return (Z_USAGE);
3207 	}
3208 	new_zonepath = argv[optind];
3209 	if (sanity_check(target_zone, CMD_MOVE, B_FALSE, B_TRUE) != Z_OK)
3210 		return (Z_ERR);
3211 	if (verify_details(CMD_MOVE) != Z_OK)
3212 		return (Z_ERR);
3213 
3214 	/*
3215 	 * Check out the new zonepath.  This has the side effect of creating
3216 	 * a directory for the new zonepath.  We depend on this later when we
3217 	 * stat to see if we are doing a cross file-system move or not.
3218 	 */
3219 	if (validate_zonepath(new_zonepath, CMD_MOVE) != Z_OK)
3220 		return (Z_ERR);
3221 
3222 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3223 	    != Z_OK) {
3224 		errno = err;
3225 		zperror2(target_zone, gettext("could not get zone path"));
3226 		return (Z_ERR);
3227 	}
3228 
3229 	if (stat(zonepath, &zonepath_buf) == -1) {
3230 		zperror(gettext("could not stat zone path"), B_FALSE);
3231 		return (Z_ERR);
3232 	}
3233 
3234 	if (stat(new_zonepath, &new_zonepath_buf) == -1) {
3235 		zperror(gettext("could not stat new zone path"), B_FALSE);
3236 		return (Z_ERR);
3237 	}
3238 
3239 	/* Don't move the zone if anything is still mounted there */
3240 	if (zonecfg_find_mounts(zonepath, NULL, NULL)) {
3241 		zerror(gettext("These file-systems are mounted on "
3242 		    "subdirectories of %s.\n"), zonepath);
3243 		(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
3244 		return (Z_ERR);
3245 	}
3246 
3247 	/*
3248 	 * Check if we are moving in the same filesystem and can do a fast
3249 	 * move or if we are crossing filesystems and have to copy the data.
3250 	 */
3251 	fast = (zonepath_buf.st_dev == new_zonepath_buf.st_dev);
3252 
3253 	if ((handle = zonecfg_init_handle()) == NULL) {
3254 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
3255 		return (Z_ERR);
3256 	}
3257 
3258 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
3259 		errno = err;
3260 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
3261 		zonecfg_fini_handle(handle);
3262 		return (Z_ERR);
3263 	}
3264 
3265 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
3266 		zerror(gettext("another %s may have an operation in progress."),
3267 		    "zoneadm");
3268 		zonecfg_fini_handle(handle);
3269 		return (Z_ERR);
3270 	}
3271 
3272 	/*
3273 	 * We're making some file-system changes now so we have to clean up
3274 	 * the file-system before we are done.  This will either clean up the
3275 	 * new zonepath if the zonecfg update failed or it will clean up the
3276 	 * old zonepath if everything is ok.
3277 	 */
3278 	revert = B_TRUE;
3279 
3280 	if (fast) {
3281 		/* same filesystem, use rename for a quick move */
3282 
3283 		/*
3284 		 * Remove the new_zonepath directory that got created above
3285 		 * during the validation.  It gets in the way of the rename.
3286 		 */
3287 		if (rmdir(new_zonepath) != 0) {
3288 			zperror(gettext("could not rmdir new zone path"),
3289 			    B_FALSE);
3290 			zonecfg_fini_handle(handle);
3291 			release_lock_file(lockfd);
3292 			return (Z_ERR);
3293 		}
3294 
3295 		if (rename(zonepath, new_zonepath) != 0) {
3296 			/*
3297 			 * If this fails we don't need to do all of the
3298 			 * cleanup that happens for the rest of the code
3299 			 * so just return from this error.
3300 			 */
3301 			zperror(gettext("could not move zone"), B_FALSE);
3302 			zonecfg_fini_handle(handle);
3303 			release_lock_file(lockfd);
3304 			return (Z_ERR);
3305 		}
3306 
3307 	} else {
3308 		(void) printf(gettext(
3309 		    "Moving across file-systems; copying zonepath %s..."),
3310 		    zonepath);
3311 		(void) fflush(stdout);
3312 
3313 		err = copy_zone(zonepath, new_zonepath);
3314 
3315 		(void) printf("\n");
3316 		if (err != Z_OK)
3317 			goto done;
3318 	}
3319 
3320 	if ((err = zonecfg_set_zonepath(handle, new_zonepath)) != Z_OK) {
3321 		errno = err;
3322 		zperror(gettext("could not set new zonepath"), B_TRUE);
3323 		goto done;
3324 	}
3325 
3326 	if ((err = zonecfg_save(handle)) != Z_OK) {
3327 		errno = err;
3328 		zperror(gettext("zonecfg save failed"), B_TRUE);
3329 		goto done;
3330 	}
3331 
3332 	revert = B_FALSE;
3333 
3334 done:
3335 	zonecfg_fini_handle(handle);
3336 	release_lock_file(lockfd);
3337 
3338 	/*
3339 	 * Clean up the file-system based on how things went.  We either
3340 	 * clean up the new zonepath if the operation failed for some reason
3341 	 * or we clean up the old zonepath if everything is ok.
3342 	 */
3343 	if (revert) {
3344 		/* The zonecfg update failed, cleanup the new zonepath. */
3345 		if (fast) {
3346 			if (rename(new_zonepath, zonepath) != 0) {
3347 				zperror(gettext("could not restore zonepath"),
3348 				    B_FALSE);
3349 				/*
3350 				 * err is already != Z_OK since we're reverting
3351 				 */
3352 			}
3353 		} else {
3354 			int status;
3355 
3356 			(void) printf(gettext("Cleaning up zonepath %s..."),
3357 			    new_zonepath);
3358 			(void) fflush(stdout);
3359 
3360 			/*
3361 			 * "exec" the command so that the returned status is
3362 			 * that of rm and not the shell.
3363 			 */
3364 			(void) snprintf(cmdbuf, sizeof (cmdbuf),
3365 			    "exec " RMCOMMAND " %s", new_zonepath);
3366 
3367 			status = do_subproc(cmdbuf);
3368 
3369 			(void) printf("\n");
3370 
3371 			if ((err = subproc_status("rm", status)) != Z_OK) {
3372 				errno = err;
3373 				zperror(gettext("could not remove new "
3374 				    "zonepath"), B_TRUE);
3375 			} else {
3376 				/*
3377 				 * Because we're reverting we know the mainline
3378 				 * code failed but we just reused the err
3379 				 * variable so we reset it back to Z_ERR.
3380 				 */
3381 				err = Z_ERR;
3382 			}
3383 		}
3384 
3385 	} else {
3386 		/* The move was successful, cleanup the old zonepath. */
3387 		if (!fast) {
3388 			int status;
3389 
3390 			(void) printf(
3391 			    gettext("Cleaning up zonepath %s..."), zonepath);
3392 			(void) fflush(stdout);
3393 
3394 			/*
3395 			 * "exec" the command so that the returned status is
3396 			 * that of rm and not the shell.
3397 			 */
3398 			(void) snprintf(cmdbuf, sizeof (cmdbuf),
3399 			    "exec " RMCOMMAND " %s", zonepath);
3400 
3401 			status = do_subproc(cmdbuf);
3402 
3403 			(void) printf("\n");
3404 
3405 			if ((err = subproc_status("rm", status)) != Z_OK) {
3406 				errno = err;
3407 				zperror(gettext("could not remove zonepath"),
3408 				    B_TRUE);
3409 			}
3410 		}
3411 	}
3412 
3413 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3414 }
3415 
3416 /*
3417  * On input, TRUE => yes, FALSE => no.
3418  * On return, TRUE => 1, FALSE => 0, could not ask => -1.
3419  */
3420 
3421 static int
3422 ask_yesno(boolean_t default_answer, const char *question)
3423 {
3424 	char line[64];	/* should be large enough to answer yes or no */
3425 
3426 	if (!isatty(STDIN_FILENO))
3427 		return (-1);
3428 	for (;;) {
3429 		(void) printf("%s (%s)? ", question,
3430 		    default_answer ? "[y]/n" : "y/[n]");
3431 		if (fgets(line, sizeof (line), stdin) == NULL ||
3432 		    line[0] == '\n')
3433 			return (default_answer ? 1 : 0);
3434 		if (tolower(line[0]) == 'y')
3435 			return (1);
3436 		if (tolower(line[0]) == 'n')
3437 			return (0);
3438 	}
3439 }
3440 
3441 static int
3442 uninstall_func(int argc, char *argv[])
3443 {
3444 	/* 6: "exec " and " " */
3445 	char cmdbuf[sizeof (RMCOMMAND) + MAXPATHLEN + 6];
3446 	char line[ZONENAME_MAX + 128];	/* Enough for "Are you sure ..." */
3447 	char rootpath[MAXPATHLEN], devpath[MAXPATHLEN];
3448 	boolean_t force = B_FALSE;
3449 	int lockfd, answer;
3450 	int err, arg;
3451 	int status;
3452 
3453 	if (zonecfg_in_alt_root()) {
3454 		zerror(gettext("cannot uninstall zone in alternate root"));
3455 		return (Z_ERR);
3456 	}
3457 
3458 	optind = 0;
3459 	while ((arg = getopt(argc, argv, "?F")) != EOF) {
3460 		switch (arg) {
3461 		case '?':
3462 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
3463 			return (optopt == '?' ? Z_OK : Z_USAGE);
3464 		case 'F':
3465 			force = B_TRUE;
3466 			break;
3467 		default:
3468 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
3469 			return (Z_USAGE);
3470 		}
3471 	}
3472 	if (argc > optind) {
3473 		sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
3474 		return (Z_USAGE);
3475 	}
3476 
3477 	if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE) != Z_OK)
3478 		return (Z_ERR);
3479 
3480 	if (!force) {
3481 		(void) snprintf(line, sizeof (line),
3482 		    gettext("Are you sure you want to %s zone %s"),
3483 		    cmd_to_str(CMD_UNINSTALL), target_zone);
3484 		if ((answer = ask_yesno(B_FALSE, line)) == 0) {
3485 			return (Z_OK);
3486 		} else if (answer == -1) {
3487 			zerror(gettext("Input not from terminal and -F "
3488 			    "not specified: %s not done."),
3489 			    cmd_to_str(CMD_UNINSTALL));
3490 			return (Z_ERR);
3491 		}
3492 	}
3493 
3494 	if ((err = zone_get_zonepath(target_zone, devpath,
3495 	    sizeof (devpath))) != Z_OK) {
3496 		errno = err;
3497 		zperror2(target_zone, gettext("could not get zone path"));
3498 		return (Z_ERR);
3499 	}
3500 	(void) strlcat(devpath, "/dev", sizeof (devpath));
3501 	if ((err = zone_get_rootpath(target_zone, rootpath,
3502 	    sizeof (rootpath))) != Z_OK) {
3503 		errno = err;
3504 		zperror2(target_zone, gettext("could not get root path"));
3505 		return (Z_ERR);
3506 	}
3507 
3508 	/*
3509 	 * If there seems to be a zoneadmd running for this zone, call it
3510 	 * to tell it that an uninstall is happening; if all goes well it
3511 	 * will then shut itself down.
3512 	 */
3513 	if (ping_zoneadmd(target_zone) == Z_OK) {
3514 		zone_cmd_arg_t zarg;
3515 		zarg.cmd = Z_NOTE_UNINSTALLING;
3516 		/* we don't care too much if this fails... just plow on */
3517 		(void) call_zoneadmd(target_zone, &zarg);
3518 	}
3519 
3520 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
3521 		zerror(gettext("another %s may have an operation in progress."),
3522 		    "zoneadm");
3523 		return (Z_ERR);
3524 	}
3525 
3526 	/* Don't uninstall the zone if anything is mounted there */
3527 	err = zonecfg_find_mounts(rootpath, NULL, NULL);
3528 	if (err) {
3529 		zerror(gettext("These file-systems are mounted on "
3530 			"subdirectories of %s.\n"), rootpath);
3531 		(void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
3532 		return (Z_ERR);
3533 	}
3534 
3535 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
3536 	if (err != Z_OK) {
3537 		errno = err;
3538 		zperror2(target_zone, gettext("could not set state"));
3539 		goto bad;
3540 	}
3541 
3542 	/*
3543 	 * "exec" the command so that the returned status is that of
3544 	 * RMCOMMAND and not the shell.
3545 	 */
3546 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
3547 	    devpath);
3548 	status = do_subproc(cmdbuf);
3549 	if ((err = subproc_status(RMCOMMAND, status)) != Z_OK)
3550 		goto bad;
3551 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
3552 	    rootpath);
3553 	status = do_subproc(cmdbuf);
3554 	if ((err = subproc_status(RMCOMMAND, status)) != Z_OK)
3555 		goto bad;
3556 	err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
3557 	if (err != Z_OK) {
3558 		errno = err;
3559 		zperror2(target_zone, gettext("could not reset state"));
3560 	}
3561 bad:
3562 	release_lock_file(lockfd);
3563 	return (err);
3564 }
3565 
3566 /* ARGSUSED */
3567 static int
3568 mount_func(int argc, char *argv[])
3569 {
3570 	zone_cmd_arg_t zarg;
3571 
3572 	if (argc > 0)
3573 		return (Z_USAGE);
3574 	if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE) != Z_OK)
3575 		return (Z_ERR);
3576 	if (verify_details(CMD_MOUNT) != Z_OK)
3577 		return (Z_ERR);
3578 
3579 	zarg.cmd = Z_MOUNT;
3580 	if (call_zoneadmd(target_zone, &zarg) != 0) {
3581 		zerror(gettext("call to %s failed"), "zoneadmd");
3582 		return (Z_ERR);
3583 	}
3584 	return (Z_OK);
3585 }
3586 
3587 /* ARGSUSED */
3588 static int
3589 unmount_func(int argc, char *argv[])
3590 {
3591 	zone_cmd_arg_t zarg;
3592 
3593 	if (argc > 0)
3594 		return (Z_USAGE);
3595 	if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE) != Z_OK)
3596 		return (Z_ERR);
3597 
3598 	zarg.cmd = Z_UNMOUNT;
3599 	if (call_zoneadmd(target_zone, &zarg) != 0) {
3600 		zerror(gettext("call to %s failed"), "zoneadmd");
3601 		return (Z_ERR);
3602 	}
3603 	return (Z_OK);
3604 }
3605 
3606 static int
3607 help_func(int argc, char *argv[])
3608 {
3609 	int arg, cmd_num;
3610 
3611 	if (argc == 0) {
3612 		(void) usage(B_TRUE);
3613 		return (Z_OK);
3614 	}
3615 	optind = 0;
3616 	if ((arg = getopt(argc, argv, "?")) != EOF) {
3617 		switch (arg) {
3618 		case '?':
3619 			sub_usage(SHELP_HELP, CMD_HELP);
3620 			return (optopt == '?' ? Z_OK : Z_USAGE);
3621 		default:
3622 			sub_usage(SHELP_HELP, CMD_HELP);
3623 			return (Z_USAGE);
3624 		}
3625 	}
3626 	while (optind < argc) {
3627 		/* Private commands have NULL short_usage; omit them */
3628 		if ((cmd_num = cmd_match(argv[optind])) < 0 ||
3629 		    cmdtab[cmd_num].short_usage == NULL) {
3630 			sub_usage(SHELP_HELP, CMD_HELP);
3631 			return (Z_USAGE);
3632 		}
3633 		sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
3634 		optind++;
3635 	}
3636 	return (Z_OK);
3637 }
3638 
3639 /*
3640  * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
3641  */
3642 
3643 static int
3644 cmd_match(char *cmd)
3645 {
3646 	int i;
3647 
3648 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
3649 		/* return only if there is an exact match */
3650 		if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
3651 			return (cmdtab[i].cmd_num);
3652 	}
3653 	return (-1);
3654 }
3655 
3656 static int
3657 parse_and_run(int argc, char *argv[])
3658 {
3659 	int i = cmd_match(argv[0]);
3660 
3661 	if (i < 0)
3662 		return (usage(B_FALSE));
3663 	return (cmdtab[i].handler(argc - 1, &(argv[1])));
3664 }
3665 
3666 static char *
3667 get_execbasename(char *execfullname)
3668 {
3669 	char *last_slash, *execbasename;
3670 
3671 	/* guard against '/' at end of command invocation */
3672 	for (;;) {
3673 		last_slash = strrchr(execfullname, '/');
3674 		if (last_slash == NULL) {
3675 			execbasename = execfullname;
3676 			break;
3677 		} else {
3678 			execbasename = last_slash + 1;
3679 			if (*execbasename == '\0') {
3680 				*last_slash = '\0';
3681 				continue;
3682 			}
3683 			break;
3684 		}
3685 	}
3686 	return (execbasename);
3687 }
3688 
3689 int
3690 main(int argc, char **argv)
3691 {
3692 	int arg;
3693 	zoneid_t zid;
3694 	struct stat st;
3695 
3696 	if ((locale = setlocale(LC_ALL, "")) == NULL)
3697 		locale = "C";
3698 	(void) textdomain(TEXT_DOMAIN);
3699 	setbuf(stdout, NULL);
3700 	(void) sigset(SIGHUP, SIG_IGN);
3701 	execname = get_execbasename(argv[0]);
3702 	target_zone = NULL;
3703 	if (chdir("/") != 0) {
3704 		zerror(gettext("could not change directory to /."));
3705 		exit(Z_ERR);
3706 	}
3707 
3708 	while ((arg = getopt(argc, argv, "?z:R:")) != EOF) {
3709 		switch (arg) {
3710 		case '?':
3711 			return (usage(B_TRUE));
3712 		case 'z':
3713 			target_zone = optarg;
3714 			break;
3715 		case 'R':	/* private option for admin/install use */
3716 			if (*optarg != '/') {
3717 				zerror(gettext("root path must be absolute."));
3718 				exit(Z_ERR);
3719 			}
3720 			if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
3721 				zerror(
3722 				    gettext("root path must be a directory."));
3723 				exit(Z_ERR);
3724 			}
3725 			zonecfg_set_root(optarg);
3726 			break;
3727 		default:
3728 			return (usage(B_FALSE));
3729 		}
3730 	}
3731 
3732 	if (optind >= argc)
3733 		return (usage(B_FALSE));
3734 	if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
3735 		errno = Z_NO_ZONE;
3736 		zperror(target_zone, B_TRUE);
3737 		exit(Z_ERR);
3738 	}
3739 	return (parse_and_run(argc - optind, &argv[optind]));
3740 }
3741