xref: /illumos-gate/usr/src/cmd/zoneadm/zoneadm.c (revision 60405de4d8688d96dd05157c28db3ade5c9bc234)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * zoneadm is a command interpreter for zone administration.  It is all in
31  * C (i.e., no lex/yacc), and all the argument passing is argc/argv based.
32  * main() calls parse_and_run() which calls cmd_match(), then invokes the
33  * appropriate command's handler function.  The rest of the program is the
34  * handler functions and their helper functions.
35  *
36  * Some of the helper functions are used largely to simplify I18N: reducing
37  * the need for translation notes.  This is particularly true of many of
38  * the zerror() calls: doing e.g. zerror(gettext("%s failed"), "foo") rather
39  * than zerror(gettext("foo failed")) with a translation note indicating
40  * that "foo" need not be translated.
41  */
42 
43 #include <stdio.h>
44 #include <errno.h>
45 #include <unistd.h>
46 #include <signal.h>
47 #include <stdarg.h>
48 #include <ctype.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <wait.h>
52 #include <zone.h>
53 #include <priv.h>
54 #include <locale.h>
55 #include <libintl.h>
56 #include <libzonecfg.h>
57 #include <bsm/adt.h>
58 #include <sys/brand.h>
59 #include <sys/param.h>
60 #include <sys/types.h>
61 #include <sys/stat.h>
62 #include <sys/statvfs.h>
63 #include <assert.h>
64 #include <sys/sockio.h>
65 #include <sys/mntent.h>
66 #include <limits.h>
67 #include <dirent.h>
68 #include <uuid/uuid.h>
69 
70 #include <fcntl.h>
71 #include <door.h>
72 #include <macros.h>
73 #include <libgen.h>
74 #include <fnmatch.h>
75 #include <sys/modctl.h>
76 #include <libbrand.h>
77 
78 #include <pool.h>
79 #include <sys/pool.h>
80 
81 #include "zoneadm.h"
82 
83 #define	MAXARGS	8
84 
85 /* Reflects kernel zone entries */
86 typedef struct zone_entry {
87 	zoneid_t	zid;
88 	char		zname[ZONENAME_MAX];
89 	char		*zstate_str;
90 	zone_state_t	zstate_num;
91 	char		zbrand[MAXNAMELEN];
92 	char		zroot[MAXPATHLEN];
93 	char		zuuid[UUID_PRINTABLE_STRING_LENGTH];
94 } zone_entry_t;
95 
96 static zone_entry_t *zents;
97 static size_t nzents;
98 static boolean_t is_native_zone = B_TRUE;
99 
100 #define	LOOPBACK_IF	"lo0"
101 #define	SOCKET_AF(af)	(((af) == AF_UNSPEC) ? AF_INET : (af))
102 
103 struct net_if {
104 	char	*name;
105 	int	af;
106 };
107 
108 /* 0755 is the default directory mode. */
109 #define	DEFAULT_DIR_MODE \
110 	(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
111 
112 struct cmd {
113 	uint_t	cmd_num;				/* command number */
114 	char	*cmd_name;				/* command name */
115 	char	*short_usage;				/* short form help */
116 	int	(*handler)(int argc, char *argv[]);	/* function to call */
117 
118 };
119 
120 #define	SHELP_HELP	"help"
121 #define	SHELP_BOOT	"boot [-- boot_arguments]"
122 #define	SHELP_HALT	"halt"
123 #define	SHELP_READY	"ready"
124 #define	SHELP_REBOOT	"reboot [-- boot_arguments]"
125 #define	SHELP_LIST	"list [-cipv]"
126 #define	SHELP_VERIFY	"verify"
127 #define	SHELP_INSTALL	"install [-x nodataset] [brand-specific args]"
128 #define	SHELP_UNINSTALL	"uninstall [-F]"
129 #define	SHELP_CLONE	"clone [-m method] [-s <ZFS snapshot>] zonename"
130 #define	SHELP_MOVE	"move zonepath"
131 #define	SHELP_DETACH	"detach [-n]"
132 #define	SHELP_ATTACH	"attach [-F] [-n <path>]"
133 #define	SHELP_MARK	"mark incomplete"
134 
135 #define	EXEC_PREFIX	"exec "
136 #define	EXEC_LEN	(strlen(EXEC_PREFIX))
137 #define	RMCOMMAND	"/usr/bin/rm -rf"
138 
139 static int cleanup_zonepath(char *, boolean_t);
140 
141 static int help_func(int argc, char *argv[]);
142 static int ready_func(int argc, char *argv[]);
143 static int boot_func(int argc, char *argv[]);
144 static int halt_func(int argc, char *argv[]);
145 static int reboot_func(int argc, char *argv[]);
146 static int list_func(int argc, char *argv[]);
147 static int verify_func(int argc, char *argv[]);
148 static int install_func(int argc, char *argv[]);
149 static int uninstall_func(int argc, char *argv[]);
150 static int mount_func(int argc, char *argv[]);
151 static int unmount_func(int argc, char *argv[]);
152 static int clone_func(int argc, char *argv[]);
153 static int move_func(int argc, char *argv[]);
154 static int detach_func(int argc, char *argv[]);
155 static int attach_func(int argc, char *argv[]);
156 static int mark_func(int argc, char *argv[]);
157 static int sanity_check(char *zone, int cmd_num, boolean_t running,
158     boolean_t unsafe_when_running, boolean_t force);
159 static int cmd_match(char *cmd);
160 static int verify_details(int);
161 
162 static struct cmd cmdtab[] = {
163 	{ CMD_HELP,		"help",		SHELP_HELP,	help_func },
164 	{ CMD_BOOT,		"boot",		SHELP_BOOT,	boot_func },
165 	{ CMD_HALT,		"halt",		SHELP_HALT,	halt_func },
166 	{ CMD_READY,		"ready",	SHELP_READY,	ready_func },
167 	{ CMD_REBOOT,		"reboot",	SHELP_REBOOT,	reboot_func },
168 	{ CMD_LIST,		"list",		SHELP_LIST,	list_func },
169 	{ CMD_VERIFY,		"verify",	SHELP_VERIFY,	verify_func },
170 	{ CMD_INSTALL,		"install",	SHELP_INSTALL,	install_func },
171 	{ CMD_UNINSTALL,	"uninstall",	SHELP_UNINSTALL,
172 	    uninstall_func },
173 	/* mount and unmount are private commands for admin/install */
174 	{ CMD_MOUNT,		"mount",	NULL,		mount_func },
175 	{ CMD_UNMOUNT,		"unmount",	NULL,		unmount_func },
176 	{ CMD_CLONE,		"clone",	SHELP_CLONE,	clone_func },
177 	{ CMD_MOVE,		"move",		SHELP_MOVE,	move_func },
178 	{ CMD_DETACH,		"detach",	SHELP_DETACH,	detach_func },
179 	{ CMD_ATTACH,		"attach",	SHELP_ATTACH,	attach_func },
180 	{ CMD_MARK,		"mark",		SHELP_MARK,	mark_func }
181 };
182 
183 /* global variables */
184 
185 /* set early in main(), never modified thereafter, used all over the place */
186 static char *execname;
187 static char target_brand[MAXNAMELEN];
188 static char *locale;
189 char *target_zone;
190 static char *target_uuid;
191 
192 /* used in do_subproc() and signal handler */
193 static volatile boolean_t child_killed;
194 static int do_subproc_cnt = 0;
195 
196 /*
197  * Used to indicate whether this zoneadm instance has another zoneadm
198  * instance in its ancestry.
199  */
200 static boolean_t zoneadm_is_nested = B_FALSE;
201 
202 /* used to track nested zone-lock operations */
203 static int zone_lock_cnt = 0;
204 
205 /* used to communicate lock status to children */
206 #define	LOCK_ENV_VAR	"_ZONEADM_LOCK_HELD"
207 static char zoneadm_lock_held[] = LOCK_ENV_VAR"=1";
208 static char zoneadm_lock_not_held[] = LOCK_ENV_VAR"=0";
209 
210 char *
211 cmd_to_str(int cmd_num)
212 {
213 	assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
214 	return (cmdtab[cmd_num].cmd_name);
215 }
216 
217 /* This is a separate function because of gettext() wrapping. */
218 static char *
219 long_help(int cmd_num)
220 {
221 	assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
222 	switch (cmd_num) {
223 	case CMD_HELP:
224 		return (gettext("Print usage message."));
225 	case CMD_BOOT:
226 		return (gettext("Activates (boots) specified zone.  See "
227 		    "zoneadm(1m) for valid boot\n\targuments."));
228 	case CMD_HALT:
229 		return (gettext("Halts specified zone, bypassing shutdown "
230 		    "scripts and removing runtime\n\tresources of the zone."));
231 	case CMD_READY:
232 		return (gettext("Prepares a zone for running applications but "
233 		    "does not start any user\n\tprocesses in the zone."));
234 	case CMD_REBOOT:
235 		return (gettext("Restarts the zone (equivalent to a halt / "
236 		    "boot sequence).\n\tFails if the zone is not active.  "
237 		    "See zoneadm(1m) for valid boot\n\targuments."));
238 	case CMD_LIST:
239 		return (gettext("Lists the current zones, or a "
240 		    "specific zone if indicated.  By default,\n\tall "
241 		    "running zones are listed, though this can be "
242 		    "expanded to all\n\tinstalled zones with the -i "
243 		    "option or all configured zones with the\n\t-c "
244 		    "option.  When used with the general -z <zone> and/or -u "
245 		    "<uuid-match>\n\toptions, lists only the specified "
246 		    "matching zone, but lists it\n\tregardless of its state, "
247 		    "and the -i and -c options are disallowed.  The\n\t-v "
248 		    "option can be used to display verbose information: zone "
249 		    "name, id,\n\tcurrent state, root directory and options.  "
250 		    "The -p option can be used\n\tto request machine-parsable "
251 		    "output.  The -v and -p options are mutually\n\texclusive."
252 		    "  If neither -v nor -p is used, just the zone name is "
253 		    "listed."));
254 	case CMD_VERIFY:
255 		return (gettext("Check to make sure the configuration "
256 		    "can safely be instantiated\n\ton the machine: "
257 		    "physical network interfaces exist, etc."));
258 	case CMD_INSTALL:
259 		return (gettext("Install the configuration on to the system.  "
260 		    "The -x nodataset option\n\tcan be used to prevent the "
261 		    "creation of a new ZFS file system for the\n\tzone "
262 		    "(assuming the zonepath is within a ZFS file system).\n\t"
263 		    "All other arguments are passed to the brand installation "
264 		    "function;\n\tsee brand(4) for more information."));
265 	case CMD_UNINSTALL:
266 		return (gettext("Uninstall the configuration from the system.  "
267 		    "The -F flag can be used\n\tto force the action."));
268 	case CMD_CLONE:
269 		return (gettext("Clone the installation of another zone.  "
270 		    "The -m option can be used to\n\tspecify 'copy' which "
271 		    "forces a copy of the source zone.  The -s option\n\t"
272 		    "can be used to specify the name of a ZFS snapshot "
273 		    "that was taken from\n\ta previous clone command.  The "
274 		    "snapshot will be used as the source\n\tinstead of "
275 		    "creating a new ZFS snapshot."));
276 	case CMD_MOVE:
277 		return (gettext("Move the zone to a new zonepath."));
278 	case CMD_DETACH:
279 		return (gettext("Detach the zone from the system. The zone "
280 		    "state is changed to\n\t'configured' (but the files under "
281 		    "the zonepath are untouched).\n\tThe zone can subsequently "
282 		    "be attached, or can be moved to another\n\tsystem and "
283 		    "attached there.  The -n option can be used to specify\n\t"
284 		    "'no-execute' mode.  When -n is used, the information "
285 		    "needed to attach\n\tthe zone is sent to standard output "
286 		    "but the zone is not actually\n\tdetached."));
287 	case CMD_ATTACH:
288 		return (gettext("Attach the zone to the system.  The zone "
289 		    "state must be 'configured'\n\tprior to attach; upon "
290 		    "successful completion, the zone state will be\n\t"
291 		    "'installed'.  The system software on the current "
292 		    "system must be\n\tcompatible with the software on the "
293 		    "zone's original system.\n\tSpecify -F to force the attach "
294 		    "and skip software compatibility tests.\n\tThe -n option "
295 		    "can be used to specify 'no-execute' mode.  When -n is\n\t"
296 		    "used, the information needed to attach the zone is read "
297 		    "from the\n\tspecified path and the configuration is only "
298 		    "validated.  The path can\n\tbe '-' to specify standard "
299 		    "input."));
300 	case CMD_MARK:
301 		return (gettext("Set the state of the zone.  This can be used "
302 		    "to force the zone\n\tstate to 'incomplete' "
303 		    "administratively if some activity has rendered\n\tthe "
304 		    "zone permanently unusable.  The only valid state that "
305 		    "may be\n\tspecified is 'incomplete'."));
306 	default:
307 		return ("");
308 	}
309 	/* NOTREACHED */
310 	return (NULL);
311 }
312 
313 /*
314  * Called with explicit B_TRUE when help is explicitly requested, B_FALSE for
315  * unexpected errors.
316  */
317 
318 static int
319 usage(boolean_t explicit)
320 {
321 	int i;
322 	FILE *fd = explicit ? stdout : stderr;
323 
324 	(void) fprintf(fd, "%s:\t%s help\n", gettext("usage"), execname);
325 	(void) fprintf(fd, "\t%s [-z <zone>] [-u <uuid-match>] list\n",
326 	    execname);
327 	(void) fprintf(fd, "\t%s {-z <zone>|-u <uuid-match>} <%s>\n", execname,
328 	    gettext("subcommand"));
329 	(void) fprintf(fd, "\n%s:\n\n", gettext("Subcommands"));
330 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
331 		if (cmdtab[i].short_usage == NULL)
332 			continue;
333 		(void) fprintf(fd, "%s\n", cmdtab[i].short_usage);
334 		if (explicit)
335 			(void) fprintf(fd, "\t%s\n\n", long_help(i));
336 	}
337 	if (!explicit)
338 		(void) fputs("\n", fd);
339 	return (Z_USAGE);
340 }
341 
342 static void
343 sub_usage(char *short_usage, int cmd_num)
344 {
345 	(void) fprintf(stderr, "%s:\t%s\n", gettext("usage"), short_usage);
346 	(void) fprintf(stderr, "\t%s\n", long_help(cmd_num));
347 }
348 
349 /*
350  * zperror() is like perror(3c) except that this also prints the executable
351  * name at the start of the message, and takes a boolean indicating whether
352  * to call libc'c strerror() or that from libzonecfg.
353  */
354 
355 void
356 zperror(const char *str, boolean_t zonecfg_error)
357 {
358 	(void) fprintf(stderr, "%s: %s: %s\n", execname, str,
359 	    zonecfg_error ? zonecfg_strerror(errno) : strerror(errno));
360 }
361 
362 /*
363  * zperror2() is very similar to zperror() above, except it also prints a
364  * supplied zone name after the executable.
365  *
366  * All current consumers of this function want libzonecfg's strerror() rather
367  * than libc's; if this ever changes, this function can be made more generic
368  * like zperror() above.
369  */
370 
371 void
372 zperror2(const char *zone, const char *str)
373 {
374 	(void) fprintf(stderr, "%s: %s: %s: %s\n", execname, zone, str,
375 	    zonecfg_strerror(errno));
376 }
377 
378 /* PRINTFLIKE1 */
379 void
380 zerror(const char *fmt, ...)
381 {
382 	va_list alist;
383 
384 	va_start(alist, fmt);
385 	(void) fprintf(stderr, "%s: ", execname);
386 	if (target_zone != NULL)
387 		(void) fprintf(stderr, "zone '%s': ", target_zone);
388 	(void) vfprintf(stderr, fmt, alist);
389 	(void) fprintf(stderr, "\n");
390 	va_end(alist);
391 }
392 
393 static void *
394 safe_calloc(size_t nelem, size_t elsize)
395 {
396 	void *r = calloc(nelem, elsize);
397 
398 	if (r == NULL) {
399 		zerror(gettext("failed to allocate %lu bytes: %s"),
400 		    (ulong_t)nelem * elsize, strerror(errno));
401 		exit(Z_ERR);
402 	}
403 	return (r);
404 }
405 
406 static void
407 zone_print(zone_entry_t *zent, boolean_t verbose, boolean_t parsable)
408 {
409 	static boolean_t firsttime = B_TRUE;
410 
411 	assert(!(verbose && parsable));
412 	if (firsttime && verbose) {
413 		firsttime = B_FALSE;
414 		(void) printf("%*s %-16s %-14s %-30s %-10s\n", ZONEID_WIDTH,
415 		    "ID", "NAME", "STATUS", "PATH", "BRAND");
416 	}
417 	if (!verbose) {
418 		char *cp, *clim;
419 
420 		if (!parsable) {
421 			(void) printf("%s\n", zent->zname);
422 			return;
423 		}
424 		if (zent->zid == ZONE_ID_UNDEFINED)
425 			(void) printf("-");
426 		else
427 			(void) printf("%lu", zent->zid);
428 		(void) printf(":%s:%s:", zent->zname, zent->zstate_str);
429 		cp = zent->zroot;
430 		while ((clim = strchr(cp, ':')) != NULL) {
431 			(void) printf("%.*s\\:", clim - cp, cp);
432 			cp = clim + 1;
433 		}
434 		(void) printf("%s:%s:%s\n", cp, zent->zuuid, zent->zbrand);
435 		return;
436 	}
437 	if (zent->zstate_str != NULL) {
438 		if (zent->zid == ZONE_ID_UNDEFINED)
439 			(void) printf("%*s", ZONEID_WIDTH, "-");
440 		else
441 			(void) printf("%*lu", ZONEID_WIDTH, zent->zid);
442 		(void) printf(" %-16s %-14s %-30s %-10s\n", zent->zname,
443 		    zent->zstate_str, zent->zroot, zent->zbrand);
444 	}
445 }
446 
447 static int
448 lookup_zone_info(const char *zone_name, zoneid_t zid, zone_entry_t *zent)
449 {
450 	char root[MAXPATHLEN], *cp;
451 	int err;
452 	uuid_t uuid;
453 
454 	(void) strlcpy(zent->zname, zone_name, sizeof (zent->zname));
455 	(void) strlcpy(zent->zroot, "???", sizeof (zent->zroot));
456 	(void) strlcpy(zent->zbrand, "???", sizeof (zent->zbrand));
457 	zent->zstate_str = "???";
458 
459 	zent->zid = zid;
460 
461 	if (zonecfg_get_uuid(zone_name, uuid) == Z_OK &&
462 	    !uuid_is_null(uuid))
463 		uuid_unparse(uuid, zent->zuuid);
464 	else
465 		zent->zuuid[0] = '\0';
466 
467 	/*
468 	 * For labeled zones which query the zone path of lower-level
469 	 * zones, the path needs to be adjusted to drop the final
470 	 * "/root" component. This adjusted path is then useful
471 	 * for reading down any exported directories from the
472 	 * lower-level zone.
473 	 */
474 	if (is_system_labeled() && zent->zid != ZONE_ID_UNDEFINED) {
475 		if (zone_getattr(zent->zid, ZONE_ATTR_ROOT, zent->zroot,
476 		    sizeof (zent->zroot)) == -1) {
477 			zperror2(zent->zname,
478 			    gettext("could not get zone path."));
479 			return (Z_ERR);
480 		}
481 		cp = zent->zroot + strlen(zent->zroot) - 5;
482 		if (cp > zent->zroot && strcmp(cp, "/root") == 0)
483 			*cp = 0;
484 	} else {
485 		if ((err = zone_get_zonepath(zent->zname, root,
486 		    sizeof (root))) != Z_OK) {
487 			errno = err;
488 			zperror2(zent->zname,
489 			    gettext("could not get zone path."));
490 			return (Z_ERR);
491 		}
492 		(void) strlcpy(zent->zroot, root, sizeof (zent->zroot));
493 	}
494 
495 	if ((err = zone_get_state(zent->zname, &zent->zstate_num)) != Z_OK) {
496 		errno = err;
497 		zperror2(zent->zname, gettext("could not get state"));
498 		return (Z_ERR);
499 	}
500 	zent->zstate_str = zone_state_str(zent->zstate_num);
501 	if (zone_get_brand(zent->zname, zent->zbrand,
502 	    sizeof (zent->zbrand)) != Z_OK) {
503 		zperror2(zent->zname, gettext("could not get brand name"));
504 		return (Z_ERR);
505 	}
506 
507 	return (Z_OK);
508 }
509 
510 /*
511  * fetch_zents() calls zone_list(2) to find out how many zones are running
512  * (which is stored in the global nzents), then calls zone_list(2) again
513  * to fetch the list of running zones (stored in the global zents).  This
514  * function may be called multiple times, so if zents is already set, we
515  * return immediately to save work.
516  */
517 
518 static int
519 fetch_zents(void)
520 {
521 	zoneid_t *zids = NULL;
522 	uint_t nzents_saved;
523 	int i, retv;
524 	FILE *fp;
525 	boolean_t inaltroot;
526 	zone_entry_t *zentp;
527 
528 	if (nzents > 0)
529 		return (Z_OK);
530 
531 	if (zone_list(NULL, &nzents) != 0) {
532 		zperror(gettext("failed to get zoneid list"), B_FALSE);
533 		return (Z_ERR);
534 	}
535 
536 again:
537 	if (nzents == 0)
538 		return (Z_OK);
539 
540 	zids = safe_calloc(nzents, sizeof (zoneid_t));
541 	nzents_saved = nzents;
542 
543 	if (zone_list(zids, &nzents) != 0) {
544 		zperror(gettext("failed to get zone list"), B_FALSE);
545 		free(zids);
546 		return (Z_ERR);
547 	}
548 	if (nzents != nzents_saved) {
549 		/* list changed, try again */
550 		free(zids);
551 		goto again;
552 	}
553 
554 	zents = safe_calloc(nzents, sizeof (zone_entry_t));
555 
556 	inaltroot = zonecfg_in_alt_root();
557 	if (inaltroot)
558 		fp = zonecfg_open_scratch("", B_FALSE);
559 	else
560 		fp = NULL;
561 	zentp = zents;
562 	retv = Z_OK;
563 	for (i = 0; i < nzents; i++) {
564 		char name[ZONENAME_MAX];
565 		char altname[ZONENAME_MAX];
566 
567 		if (getzonenamebyid(zids[i], name, sizeof (name)) < 0) {
568 			zperror(gettext("failed to get zone name"), B_FALSE);
569 			retv = Z_ERR;
570 			continue;
571 		}
572 		if (zonecfg_is_scratch(name)) {
573 			/* Ignore scratch zones by default */
574 			if (!inaltroot)
575 				continue;
576 			if (fp == NULL ||
577 			    zonecfg_reverse_scratch(fp, name, altname,
578 			    sizeof (altname), NULL, 0) == -1) {
579 				zerror(gettext("could not resolve scratch "
580 				    "zone %s"), name);
581 				retv = Z_ERR;
582 				continue;
583 			}
584 			(void) strcpy(name, altname);
585 		} else {
586 			/* Ignore non-scratch when in an alternate root */
587 			if (inaltroot && strcmp(name, GLOBAL_ZONENAME) != 0)
588 				continue;
589 		}
590 		if (lookup_zone_info(name, zids[i], zentp) != Z_OK) {
591 			zerror(gettext("failed to get zone data"));
592 			retv = Z_ERR;
593 			continue;
594 		}
595 		zentp++;
596 	}
597 	nzents = zentp - zents;
598 	if (fp != NULL)
599 		zonecfg_close_scratch(fp);
600 
601 	free(zids);
602 	return (retv);
603 }
604 
605 static int
606 zone_print_list(zone_state_t min_state, boolean_t verbose, boolean_t parsable)
607 {
608 	int i;
609 	zone_entry_t zent;
610 	FILE *cookie;
611 	char *name;
612 
613 	/*
614 	 * First get the list of running zones from the kernel and print them.
615 	 * If that is all we need, then return.
616 	 */
617 	if ((i = fetch_zents()) != Z_OK) {
618 		/*
619 		 * No need for error messages; fetch_zents() has already taken
620 		 * care of this.
621 		 */
622 		return (i);
623 	}
624 	for (i = 0; i < nzents; i++)
625 		zone_print(&zents[i], verbose, parsable);
626 	if (min_state >= ZONE_STATE_RUNNING)
627 		return (Z_OK);
628 	/*
629 	 * Next, get the full list of zones from the configuration, skipping
630 	 * any we have already printed.
631 	 */
632 	cookie = setzoneent();
633 	while ((name = getzoneent(cookie)) != NULL) {
634 		for (i = 0; i < nzents; i++) {
635 			if (strcmp(zents[i].zname, name) == 0)
636 				break;
637 		}
638 		if (i < nzents) {
639 			free(name);
640 			continue;
641 		}
642 		if (lookup_zone_info(name, ZONE_ID_UNDEFINED, &zent) != Z_OK) {
643 			free(name);
644 			continue;
645 		}
646 		free(name);
647 		if (zent.zstate_num >= min_state)
648 			zone_print(&zent, verbose, parsable);
649 	}
650 	endzoneent(cookie);
651 	return (Z_OK);
652 }
653 
654 static zone_entry_t *
655 lookup_running_zone(char *str)
656 {
657 	zoneid_t zoneid;
658 	char *cp;
659 	int i;
660 
661 	if (fetch_zents() != Z_OK)
662 		return (NULL);
663 
664 	for (i = 0; i < nzents; i++) {
665 		if (strcmp(str, zents[i].zname) == 0)
666 			return (&zents[i]);
667 	}
668 	errno = 0;
669 	zoneid = strtol(str, &cp, 0);
670 	if (zoneid < MIN_ZONEID || zoneid > MAX_ZONEID ||
671 	    errno != 0 || *cp != '\0')
672 		return (NULL);
673 	for (i = 0; i < nzents; i++) {
674 		if (zoneid == zents[i].zid)
675 			return (&zents[i]);
676 	}
677 	return (NULL);
678 }
679 
680 /*
681  * Check a bit in a mode_t: if on is B_TRUE, that bit should be on; if
682  * B_FALSE, it should be off.  Return B_TRUE if the mode is bad (incorrect).
683  */
684 static boolean_t
685 bad_mode_bit(mode_t mode, mode_t bit, boolean_t on, char *file)
686 {
687 	char *str;
688 
689 	assert(bit == S_IRUSR || bit == S_IWUSR || bit == S_IXUSR ||
690 	    bit == S_IRGRP || bit == S_IWGRP || bit == S_IXGRP ||
691 	    bit == S_IROTH || bit == S_IWOTH || bit == S_IXOTH);
692 	/*
693 	 * TRANSLATION_NOTE
694 	 * The strings below will be used as part of a larger message,
695 	 * either:
696 	 * (file name) must be (owner|group|world) (read|writ|execut)able
697 	 * or
698 	 * (file name) must not be (owner|group|world) (read|writ|execut)able
699 	 */
700 	switch (bit) {
701 	case S_IRUSR:
702 		str = gettext("owner readable");
703 		break;
704 	case S_IWUSR:
705 		str = gettext("owner writable");
706 		break;
707 	case S_IXUSR:
708 		str = gettext("owner executable");
709 		break;
710 	case S_IRGRP:
711 		str = gettext("group readable");
712 		break;
713 	case S_IWGRP:
714 		str = gettext("group writable");
715 		break;
716 	case S_IXGRP:
717 		str = gettext("group executable");
718 		break;
719 	case S_IROTH:
720 		str = gettext("world readable");
721 		break;
722 	case S_IWOTH:
723 		str = gettext("world writable");
724 		break;
725 	case S_IXOTH:
726 		str = gettext("world executable");
727 		break;
728 	}
729 	if ((mode & bit) == (on ? 0 : bit)) {
730 		/*
731 		 * TRANSLATION_NOTE
732 		 * The first parameter below is a file name; the second
733 		 * is one of the "(owner|group|world) (read|writ|execut)able"
734 		 * strings from above.
735 		 */
736 		/*
737 		 * The code below could be simplified but not in a way
738 		 * that would easily translate to non-English locales.
739 		 */
740 		if (on) {
741 			(void) fprintf(stderr, gettext("%s must be %s.\n"),
742 			    file, str);
743 		} else {
744 			(void) fprintf(stderr, gettext("%s must not be %s.\n"),
745 			    file, str);
746 		}
747 		return (B_TRUE);
748 	}
749 	return (B_FALSE);
750 }
751 
752 /*
753  * We want to make sure that no zone has its zone path as a child node
754  * (in the directory sense) of any other.  We do that by comparing this
755  * zone's path to the path of all other (non-global) zones.  The comparison
756  * in each case is simple: add '/' to the end of the path, then do a
757  * strncmp() of the two paths, using the length of the shorter one.
758  */
759 
760 static int
761 crosscheck_zonepaths(char *path)
762 {
763 	char rpath[MAXPATHLEN];		/* resolved path */
764 	char path_copy[MAXPATHLEN];	/* copy of original path */
765 	char rpath_copy[MAXPATHLEN];	/* copy of original rpath */
766 	struct zoneent *ze;
767 	int res, err;
768 	FILE *cookie;
769 
770 	cookie = setzoneent();
771 	while ((ze = getzoneent_private(cookie)) != NULL) {
772 		/* Skip zones which are not installed. */
773 		if (ze->zone_state < ZONE_STATE_INSTALLED) {
774 			free(ze);
775 			continue;
776 		}
777 		/* Skip the global zone and the current target zone. */
778 		if (strcmp(ze->zone_name, GLOBAL_ZONENAME) == 0 ||
779 		    strcmp(ze->zone_name, target_zone) == 0) {
780 			free(ze);
781 			continue;
782 		}
783 		if (strlen(ze->zone_path) == 0) {
784 			/* old index file without path, fall back */
785 			if ((err = zone_get_zonepath(ze->zone_name,
786 			    ze->zone_path, sizeof (ze->zone_path))) != Z_OK) {
787 				errno = err;
788 				zperror2(ze->zone_name,
789 				    gettext("could not get zone path"));
790 				free(ze);
791 				continue;
792 			}
793 		}
794 		(void) snprintf(path_copy, sizeof (path_copy), "%s%s",
795 		    zonecfg_get_root(), ze->zone_path);
796 		res = resolvepath(path_copy, rpath, sizeof (rpath));
797 		if (res == -1) {
798 			if (errno != ENOENT) {
799 				zperror(path_copy, B_FALSE);
800 				free(ze);
801 				return (Z_ERR);
802 			}
803 			(void) printf(gettext("WARNING: zone %s is installed, "
804 			    "but its %s %s does not exist.\n"), ze->zone_name,
805 			    "zonepath", path_copy);
806 			free(ze);
807 			continue;
808 		}
809 		rpath[res] = '\0';
810 		(void) snprintf(path_copy, sizeof (path_copy), "%s/", path);
811 		(void) snprintf(rpath_copy, sizeof (rpath_copy), "%s/", rpath);
812 		if (strncmp(path_copy, rpath_copy,
813 		    min(strlen(path_copy), strlen(rpath_copy))) == 0) {
814 			/*
815 			 * TRANSLATION_NOTE
816 			 * zonepath is a literal that should not be translated.
817 			 */
818 			(void) fprintf(stderr, gettext("%s zonepath (%s) and "
819 			    "%s zonepath (%s) overlap.\n"),
820 			    target_zone, path, ze->zone_name, rpath);
821 			free(ze);
822 			return (Z_ERR);
823 		}
824 		free(ze);
825 	}
826 	endzoneent(cookie);
827 	return (Z_OK);
828 }
829 
830 static int
831 validate_zonepath(char *path, int cmd_num)
832 {
833 	int res;			/* result of last library/system call */
834 	boolean_t err = B_FALSE;	/* have we run into an error? */
835 	struct stat stbuf;
836 	struct statvfs64 vfsbuf;
837 	char rpath[MAXPATHLEN];		/* resolved path */
838 	char ppath[MAXPATHLEN];		/* parent path */
839 	char rppath[MAXPATHLEN];	/* resolved parent path */
840 	char rootpath[MAXPATHLEN];	/* root path */
841 	zone_state_t state;
842 
843 	if (path[0] != '/') {
844 		(void) fprintf(stderr,
845 		    gettext("%s is not an absolute path.\n"), path);
846 		return (Z_ERR);
847 	}
848 	if ((res = resolvepath(path, rpath, sizeof (rpath))) == -1) {
849 		if ((errno != ENOENT) ||
850 		    (cmd_num != CMD_VERIFY && cmd_num != CMD_INSTALL &&
851 		    cmd_num != CMD_CLONE && cmd_num != CMD_MOVE)) {
852 			zperror(path, B_FALSE);
853 			return (Z_ERR);
854 		}
855 		if (cmd_num == CMD_VERIFY) {
856 			/*
857 			 * TRANSLATION_NOTE
858 			 * zoneadm is a literal that should not be translated.
859 			 */
860 			(void) fprintf(stderr, gettext("WARNING: %s does not "
861 			    "exist, so it could not be verified.\nWhen "
862 			    "'zoneadm %s' is run, '%s' will try to create\n%s, "
863 			    "and '%s' will be tried again,\nbut the '%s' may "
864 			    "fail if:\nthe parent directory of %s is group- or "
865 			    "other-writable\nor\n%s overlaps with any other "
866 			    "installed zones.\n"), path,
867 			    cmd_to_str(CMD_INSTALL), cmd_to_str(CMD_INSTALL),
868 			    path, cmd_to_str(CMD_VERIFY),
869 			    cmd_to_str(CMD_VERIFY), path, path);
870 			return (Z_OK);
871 		}
872 		/*
873 		 * The zonepath is supposed to be mode 700 but its
874 		 * parent(s) 755.  So use 755 on the mkdirp() then
875 		 * chmod() the zonepath itself to 700.
876 		 */
877 		if (mkdirp(path, DEFAULT_DIR_MODE) < 0) {
878 			zperror(path, B_FALSE);
879 			return (Z_ERR);
880 		}
881 		/*
882 		 * If the chmod() fails, report the error, but might
883 		 * as well continue the verify procedure.
884 		 */
885 		if (chmod(path, S_IRWXU) != 0)
886 			zperror(path, B_FALSE);
887 		/*
888 		 * Since the mkdir() succeeded, we should not have to
889 		 * worry about a subsequent ENOENT, thus this should
890 		 * only recurse once.
891 		 */
892 		return (validate_zonepath(path, cmd_num));
893 	}
894 	rpath[res] = '\0';
895 	if (strcmp(path, rpath) != 0) {
896 		errno = Z_RESOLVED_PATH;
897 		zperror(path, B_TRUE);
898 		return (Z_ERR);
899 	}
900 	if ((res = stat(rpath, &stbuf)) != 0) {
901 		zperror(rpath, B_FALSE);
902 		return (Z_ERR);
903 	}
904 	if (!S_ISDIR(stbuf.st_mode)) {
905 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
906 		    rpath);
907 		return (Z_ERR);
908 	}
909 	if ((strcmp(stbuf.st_fstype, MNTTYPE_TMPFS) == 0) ||
910 	    (strcmp(stbuf.st_fstype, MNTTYPE_XMEMFS) == 0)) {
911 		(void) printf(gettext("WARNING: %s is on a temporary "
912 		    "file system.\n"), rpath);
913 	}
914 	if (crosscheck_zonepaths(rpath) != Z_OK)
915 		return (Z_ERR);
916 	/*
917 	 * Try to collect and report as many minor errors as possible
918 	 * before returning, so the user can learn everything that needs
919 	 * to be fixed up front.
920 	 */
921 	if (stbuf.st_uid != 0) {
922 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
923 		    rpath);
924 		err = B_TRUE;
925 	}
926 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rpath);
927 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rpath);
928 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rpath);
929 	err |= bad_mode_bit(stbuf.st_mode, S_IRGRP, B_FALSE, rpath);
930 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rpath);
931 	err |= bad_mode_bit(stbuf.st_mode, S_IXGRP, B_FALSE, rpath);
932 	err |= bad_mode_bit(stbuf.st_mode, S_IROTH, B_FALSE, rpath);
933 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rpath);
934 	err |= bad_mode_bit(stbuf.st_mode, S_IXOTH, B_FALSE, rpath);
935 
936 	(void) snprintf(ppath, sizeof (ppath), "%s/..", path);
937 	if ((res = resolvepath(ppath, rppath, sizeof (rppath))) == -1) {
938 		zperror(ppath, B_FALSE);
939 		return (Z_ERR);
940 	}
941 	rppath[res] = '\0';
942 	if ((res = stat(rppath, &stbuf)) != 0) {
943 		zperror(rppath, B_FALSE);
944 		return (Z_ERR);
945 	}
946 	/* theoretically impossible */
947 	if (!S_ISDIR(stbuf.st_mode)) {
948 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
949 		    rppath);
950 		return (Z_ERR);
951 	}
952 	if (stbuf.st_uid != 0) {
953 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
954 		    rppath);
955 		err = B_TRUE;
956 	}
957 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rppath);
958 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rppath);
959 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rppath);
960 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rppath);
961 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rppath);
962 	if (strcmp(rpath, rppath) == 0) {
963 		(void) fprintf(stderr, gettext("%s is its own parent.\n"),
964 		    rppath);
965 		err = B_TRUE;
966 	}
967 
968 	if (statvfs64(rpath, &vfsbuf) != 0) {
969 		zperror(rpath, B_FALSE);
970 		return (Z_ERR);
971 	}
972 	if (strcmp(vfsbuf.f_basetype, MNTTYPE_NFS) == 0) {
973 		/*
974 		 * TRANSLATION_NOTE
975 		 * Zonepath and NFS are literals that should not be translated.
976 		 */
977 		(void) fprintf(stderr, gettext("Zonepath %s is on an NFS "
978 		    "mounted file system.\n"
979 		    "\tA local file system must be used.\n"), rpath);
980 		return (Z_ERR);
981 	}
982 	if (vfsbuf.f_flag & ST_NOSUID) {
983 		/*
984 		 * TRANSLATION_NOTE
985 		 * Zonepath and nosuid are literals that should not be
986 		 * translated.
987 		 */
988 		(void) fprintf(stderr, gettext("Zonepath %s is on a nosuid "
989 		    "file system.\n"), rpath);
990 		return (Z_ERR);
991 	}
992 
993 	if ((res = zone_get_state(target_zone, &state)) != Z_OK) {
994 		errno = res;
995 		zperror2(target_zone, gettext("could not get state"));
996 		return (Z_ERR);
997 	}
998 	/*
999 	 * The existence of the root path is only bad in the configured state,
1000 	 * as it is *supposed* to be there at the installed and later states.
1001 	 * However, the root path is expected to be there if the zone is
1002 	 * detached.
1003 	 * State/command mismatches are caught earlier in verify_details().
1004 	 */
1005 	if (state == ZONE_STATE_CONFIGURED && cmd_num != CMD_ATTACH) {
1006 		if (snprintf(rootpath, sizeof (rootpath), "%s/root", rpath) >=
1007 		    sizeof (rootpath)) {
1008 			/*
1009 			 * TRANSLATION_NOTE
1010 			 * Zonepath is a literal that should not be translated.
1011 			 */
1012 			(void) fprintf(stderr,
1013 			    gettext("Zonepath %s is too long.\n"), rpath);
1014 			return (Z_ERR);
1015 		}
1016 		if ((res = stat(rootpath, &stbuf)) == 0) {
1017 			if (zonecfg_detached(rpath))
1018 				(void) fprintf(stderr,
1019 				    gettext("Cannot %s detached "
1020 				    "zone.\nUse attach or remove %s "
1021 				    "directory.\n"), cmd_to_str(cmd_num),
1022 				    rpath);
1023 			else
1024 				(void) fprintf(stderr,
1025 				    gettext("Rootpath %s exists; "
1026 				    "remove or move aside prior to %s.\n"),
1027 				    rootpath, cmd_to_str(cmd_num));
1028 			return (Z_ERR);
1029 		}
1030 	}
1031 
1032 	return (err ? Z_ERR : Z_OK);
1033 }
1034 
1035 /*
1036  * The following two routines implement a simple locking mechanism to
1037  * ensure that only one instance of zoneadm at a time is able to manipulate
1038  * a given zone.  The lock is built on top of an fcntl(2) lock of
1039  * [<altroot>]/var/run/zones/<zonename>.zoneadm.lock.  If a zoneadm instance
1040  * can grab that lock, it is allowed to manipulate the zone.
1041  *
1042  * Since zoneadm may call external applications which in turn invoke
1043  * zoneadm again, we introduce the notion of "lock inheritance".  Any
1044  * instance of zoneadm that has another instance in its ancestry is assumed
1045  * to be acting on behalf of the original zoneadm, and is thus allowed to
1046  * manipulate its zone.
1047  *
1048  * This inheritance is implemented via the _ZONEADM_LOCK_HELD environment
1049  * variable.  When zoneadm is granted a lock on its zone, this environment
1050  * variable is set to 1.  When it releases the lock, the variable is set to
1051  * 0.  Since a child process inherits its parent's environment, checking
1052  * the state of this variable indicates whether or not any ancestor owns
1053  * the lock.
1054  */
1055 static void
1056 release_lock_file(int lockfd)
1057 {
1058 	/*
1059 	 * If we are cleaning up from a failed attempt to lock the zone for
1060 	 * the first time, we might have a zone_lock_cnt of 0.  In that
1061 	 * error case, we don't want to do anything but close the lock
1062 	 * file.
1063 	 */
1064 	assert(zone_lock_cnt >= 0);
1065 	if (zone_lock_cnt > 0) {
1066 		assert(getenv(LOCK_ENV_VAR) != NULL);
1067 		assert(atoi(getenv(LOCK_ENV_VAR)) == 1);
1068 		if (--zone_lock_cnt > 0) {
1069 			assert(lockfd == -1);
1070 			return;
1071 		}
1072 		if (putenv(zoneadm_lock_not_held) != 0) {
1073 			zperror(target_zone, B_TRUE);
1074 			exit(Z_ERR);
1075 		}
1076 	}
1077 	assert(lockfd >= 0);
1078 	(void) close(lockfd);
1079 }
1080 
1081 static int
1082 grab_lock_file(const char *zone_name, int *lockfd)
1083 {
1084 	char pathbuf[PATH_MAX];
1085 	struct flock flock;
1086 
1087 	/*
1088 	 * If we already have the lock, we can skip this expensive song
1089 	 * and dance.
1090 	 */
1091 	if (zone_lock_cnt > 0) {
1092 		zone_lock_cnt++;
1093 		*lockfd = -1;
1094 		return (Z_OK);
1095 	}
1096 	assert(getenv(LOCK_ENV_VAR) != NULL);
1097 	assert(atoi(getenv(LOCK_ENV_VAR)) == 0);
1098 
1099 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s", zonecfg_get_root(),
1100 	    ZONES_TMPDIR) >= sizeof (pathbuf)) {
1101 		zerror(gettext("alternate root path is too long"));
1102 		return (Z_ERR);
1103 	}
1104 	if (mkdir(pathbuf, S_IRWXU) < 0 && errno != EEXIST) {
1105 		zerror(gettext("could not mkdir %s: %s"), pathbuf,
1106 		    strerror(errno));
1107 		return (Z_ERR);
1108 	}
1109 	(void) chmod(pathbuf, S_IRWXU);
1110 
1111 	/*
1112 	 * One of these lock files is created for each zone (when needed).
1113 	 * The lock files are not cleaned up (except on system reboot),
1114 	 * but since there is only one per zone, there is no resource
1115 	 * starvation issue.
1116 	 */
1117 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s/%s.zoneadm.lock",
1118 	    zonecfg_get_root(), ZONES_TMPDIR, zone_name) >= sizeof (pathbuf)) {
1119 		zerror(gettext("alternate root path is too long"));
1120 		return (Z_ERR);
1121 	}
1122 	if ((*lockfd = open(pathbuf, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
1123 		zerror(gettext("could not open %s: %s"), pathbuf,
1124 		    strerror(errno));
1125 		return (Z_ERR);
1126 	}
1127 	/*
1128 	 * Lock the file to synchronize with other zoneadmds
1129 	 */
1130 	flock.l_type = F_WRLCK;
1131 	flock.l_whence = SEEK_SET;
1132 	flock.l_start = (off_t)0;
1133 	flock.l_len = (off_t)0;
1134 	if ((fcntl(*lockfd, F_SETLKW, &flock) < 0) ||
1135 	    (putenv(zoneadm_lock_held) != 0)) {
1136 		zerror(gettext("unable to lock %s: %s"), pathbuf,
1137 		    strerror(errno));
1138 		release_lock_file(*lockfd);
1139 		return (Z_ERR);
1140 	}
1141 	zone_lock_cnt = 1;
1142 	return (Z_OK);
1143 }
1144 
1145 static boolean_t
1146 get_doorname(const char *zone_name, char *buffer)
1147 {
1148 	return (snprintf(buffer, PATH_MAX, "%s" ZONE_DOOR_PATH,
1149 	    zonecfg_get_root(), zone_name) < PATH_MAX);
1150 }
1151 
1152 /*
1153  * system daemons are not audited.  For the global zone, this occurs
1154  * "naturally" since init is started with the default audit
1155  * characteristics.  Since zoneadmd is a system daemon and it starts
1156  * init for a zone, it is necessary to clear out the audit
1157  * characteristics inherited from whomever started zoneadmd.  This is
1158  * indicated by the audit id, which is set from the ruid parameter of
1159  * adt_set_user(), below.
1160  */
1161 
1162 static void
1163 prepare_audit_context()
1164 {
1165 	adt_session_data_t	*ah;
1166 	char			*failure = gettext("audit failure: %s");
1167 
1168 	if (adt_start_session(&ah, NULL, 0)) {
1169 		zerror(failure, strerror(errno));
1170 		return;
1171 	}
1172 	if (adt_set_user(ah, ADT_NO_AUDIT, ADT_NO_AUDIT,
1173 	    ADT_NO_AUDIT, ADT_NO_AUDIT, NULL, ADT_NEW)) {
1174 		zerror(failure, strerror(errno));
1175 		(void) adt_end_session(ah);
1176 		return;
1177 	}
1178 	if (adt_set_proc(ah))
1179 		zerror(failure, strerror(errno));
1180 
1181 	(void) adt_end_session(ah);
1182 }
1183 
1184 static int
1185 start_zoneadmd(const char *zone_name)
1186 {
1187 	char doorpath[PATH_MAX];
1188 	pid_t child_pid;
1189 	int error = Z_ERR;
1190 	int doorfd, lockfd;
1191 	struct door_info info;
1192 
1193 	if (!get_doorname(zone_name, doorpath))
1194 		return (Z_ERR);
1195 
1196 	if (grab_lock_file(zone_name, &lockfd) != Z_OK)
1197 		return (Z_ERR);
1198 
1199 	/*
1200 	 * Now that we have the lock, re-confirm that the daemon is
1201 	 * *not* up and working fine.  If it is still down, we have a green
1202 	 * light to start it.
1203 	 */
1204 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1205 		if (errno != ENOENT) {
1206 			zperror(doorpath, B_FALSE);
1207 			goto out;
1208 		}
1209 	} else {
1210 		if (door_info(doorfd, &info) == 0 &&
1211 		    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1212 			error = Z_OK;
1213 			(void) close(doorfd);
1214 			goto out;
1215 		}
1216 		(void) close(doorfd);
1217 	}
1218 
1219 	if ((child_pid = fork()) == -1) {
1220 		zperror(gettext("could not fork"), B_FALSE);
1221 		goto out;
1222 	} else if (child_pid == 0) {
1223 		const char *argv[6], **ap;
1224 
1225 		/* child process */
1226 		prepare_audit_context();
1227 
1228 		ap = argv;
1229 		*ap++ = "zoneadmd";
1230 		*ap++ = "-z";
1231 		*ap++ = zone_name;
1232 		if (zonecfg_in_alt_root()) {
1233 			*ap++ = "-R";
1234 			*ap++ = zonecfg_get_root();
1235 		}
1236 		*ap = NULL;
1237 
1238 		(void) execv("/usr/lib/zones/zoneadmd", (char * const *)argv);
1239 		/*
1240 		 * TRANSLATION_NOTE
1241 		 * zoneadmd is a literal that should not be translated.
1242 		 */
1243 		zperror(gettext("could not exec zoneadmd"), B_FALSE);
1244 		_exit(Z_ERR);
1245 	} else {
1246 		/* parent process */
1247 		pid_t retval;
1248 		int pstatus = 0;
1249 
1250 		do {
1251 			retval = waitpid(child_pid, &pstatus, 0);
1252 		} while (retval != child_pid);
1253 		if (WIFSIGNALED(pstatus) || (WIFEXITED(pstatus) &&
1254 		    WEXITSTATUS(pstatus) != 0)) {
1255 			zerror(gettext("could not start %s"), "zoneadmd");
1256 			goto out;
1257 		}
1258 	}
1259 	error = Z_OK;
1260 out:
1261 	release_lock_file(lockfd);
1262 	return (error);
1263 }
1264 
1265 static int
1266 ping_zoneadmd(const char *zone_name)
1267 {
1268 	char doorpath[PATH_MAX];
1269 	int doorfd;
1270 	struct door_info info;
1271 
1272 	if (!get_doorname(zone_name, doorpath))
1273 		return (Z_ERR);
1274 
1275 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1276 		return (Z_ERR);
1277 	}
1278 	if (door_info(doorfd, &info) == 0 &&
1279 	    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1280 		(void) close(doorfd);
1281 		return (Z_OK);
1282 	}
1283 	(void) close(doorfd);
1284 	return (Z_ERR);
1285 }
1286 
1287 static int
1288 call_zoneadmd(const char *zone_name, zone_cmd_arg_t *arg)
1289 {
1290 	char doorpath[PATH_MAX];
1291 	int doorfd, result;
1292 	door_arg_t darg;
1293 
1294 	zoneid_t zoneid;
1295 	uint64_t uniqid = 0;
1296 
1297 	zone_cmd_rval_t *rvalp;
1298 	size_t rlen;
1299 	char *cp, *errbuf;
1300 
1301 	rlen = getpagesize();
1302 	if ((rvalp = malloc(rlen)) == NULL) {
1303 		zerror(gettext("failed to allocate %lu bytes: %s"), rlen,
1304 		    strerror(errno));
1305 		return (-1);
1306 	}
1307 
1308 	if ((zoneid = getzoneidbyname(zone_name)) != ZONE_ID_UNDEFINED) {
1309 		(void) zone_getattr(zoneid, ZONE_ATTR_UNIQID, &uniqid,
1310 		    sizeof (uniqid));
1311 	}
1312 	arg->uniqid = uniqid;
1313 	(void) strlcpy(arg->locale, locale, sizeof (arg->locale));
1314 	if (!get_doorname(zone_name, doorpath)) {
1315 		zerror(gettext("alternate root path is too long"));
1316 		free(rvalp);
1317 		return (-1);
1318 	}
1319 
1320 	/*
1321 	 * Loop trying to start zoneadmd; if something goes seriously
1322 	 * wrong we break out and fail.
1323 	 */
1324 	for (;;) {
1325 		if (start_zoneadmd(zone_name) != Z_OK)
1326 			break;
1327 
1328 		if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1329 			zperror(gettext("failed to open zone door"), B_FALSE);
1330 			break;
1331 		}
1332 
1333 		darg.data_ptr = (char *)arg;
1334 		darg.data_size = sizeof (*arg);
1335 		darg.desc_ptr = NULL;
1336 		darg.desc_num = 0;
1337 		darg.rbuf = (char *)rvalp;
1338 		darg.rsize = rlen;
1339 		if (door_call(doorfd, &darg) != 0) {
1340 			(void) close(doorfd);
1341 			/*
1342 			 * We'll get EBADF if the door has been revoked.
1343 			 */
1344 			if (errno != EBADF) {
1345 				zperror(gettext("door_call failed"), B_FALSE);
1346 				break;
1347 			}
1348 			continue;	/* take another lap */
1349 		}
1350 		(void) close(doorfd);
1351 
1352 		if (darg.data_size == 0) {
1353 			/* Door server is going away; kick it again. */
1354 			continue;
1355 		}
1356 
1357 		errbuf = rvalp->errbuf;
1358 		while (*errbuf != '\0') {
1359 			/*
1360 			 * Remove any newlines since zerror()
1361 			 * will append one automatically.
1362 			 */
1363 			cp = strchr(errbuf, '\n');
1364 			if (cp != NULL)
1365 				*cp = '\0';
1366 			zerror("%s", errbuf);
1367 			if (cp == NULL)
1368 				break;
1369 			errbuf = cp + 1;
1370 		}
1371 		result = rvalp->rval == 0 ? 0 : -1;
1372 		free(rvalp);
1373 		return (result);
1374 	}
1375 
1376 	free(rvalp);
1377 	return (-1);
1378 }
1379 
1380 static int
1381 ready_func(int argc, char *argv[])
1382 {
1383 	zone_cmd_arg_t zarg;
1384 	int arg;
1385 
1386 	if (zonecfg_in_alt_root()) {
1387 		zerror(gettext("cannot ready zone in alternate root"));
1388 		return (Z_ERR);
1389 	}
1390 
1391 	optind = 0;
1392 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1393 		switch (arg) {
1394 		case '?':
1395 			sub_usage(SHELP_READY, CMD_READY);
1396 			return (optopt == '?' ? Z_OK : Z_USAGE);
1397 		default:
1398 			sub_usage(SHELP_READY, CMD_READY);
1399 			return (Z_USAGE);
1400 		}
1401 	}
1402 	if (argc > optind) {
1403 		sub_usage(SHELP_READY, CMD_READY);
1404 		return (Z_USAGE);
1405 	}
1406 	if (sanity_check(target_zone, CMD_READY, B_FALSE, B_FALSE, B_FALSE)
1407 	    != Z_OK)
1408 		return (Z_ERR);
1409 	if (verify_details(CMD_READY) != Z_OK)
1410 		return (Z_ERR);
1411 
1412 	zarg.cmd = Z_READY;
1413 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1414 		zerror(gettext("call to %s failed"), "zoneadmd");
1415 		return (Z_ERR);
1416 	}
1417 	return (Z_OK);
1418 }
1419 
1420 static int
1421 boot_func(int argc, char *argv[])
1422 {
1423 	zone_cmd_arg_t zarg;
1424 	boolean_t force = B_FALSE;
1425 	int arg;
1426 
1427 	if (zonecfg_in_alt_root()) {
1428 		zerror(gettext("cannot boot zone in alternate root"));
1429 		return (Z_ERR);
1430 	}
1431 
1432 	zarg.bootbuf[0] = '\0';
1433 
1434 	/*
1435 	 * The following getopt processes arguments to zone boot; that
1436 	 * is to say, the [here] portion of the argument string:
1437 	 *
1438 	 *	zoneadm -z myzone boot [here] -- -v -m verbose
1439 	 *
1440 	 * Where [here] can either be nothing, -? (in which case we bail
1441 	 * and print usage), -f (a private option to indicate that the
1442 	 * boot operation should be 'forced'), or -s.  Support for -s is
1443 	 * vestigal and obsolete, but is retained because it was a
1444 	 * documented interface and there are known consumers including
1445 	 * admin/install; the proper way to specify boot arguments like -s
1446 	 * is:
1447 	 *
1448 	 *	zoneadm -z myzone boot -- -s -v -m verbose.
1449 	 */
1450 	optind = 0;
1451 	while ((arg = getopt(argc, argv, "?fs")) != EOF) {
1452 		switch (arg) {
1453 		case '?':
1454 			sub_usage(SHELP_BOOT, CMD_BOOT);
1455 			return (optopt == '?' ? Z_OK : Z_USAGE);
1456 		case 's':
1457 			(void) strlcpy(zarg.bootbuf, "-s",
1458 			    sizeof (zarg.bootbuf));
1459 			break;
1460 		case 'f':
1461 			force = B_TRUE;
1462 			break;
1463 		default:
1464 			sub_usage(SHELP_BOOT, CMD_BOOT);
1465 			return (Z_USAGE);
1466 		}
1467 	}
1468 
1469 	for (; optind < argc; optind++) {
1470 		if (strlcat(zarg.bootbuf, argv[optind],
1471 		    sizeof (zarg.bootbuf)) >= sizeof (zarg.bootbuf)) {
1472 			zerror(gettext("Boot argument list too long"));
1473 			return (Z_ERR);
1474 		}
1475 		if (optind < argc - 1)
1476 			if (strlcat(zarg.bootbuf, " ", sizeof (zarg.bootbuf)) >=
1477 			    sizeof (zarg.bootbuf)) {
1478 				zerror(gettext("Boot argument list too long"));
1479 				return (Z_ERR);
1480 			}
1481 	}
1482 	if (sanity_check(target_zone, CMD_BOOT, B_FALSE, B_FALSE, force)
1483 	    != Z_OK)
1484 		return (Z_ERR);
1485 	if (verify_details(CMD_BOOT) != Z_OK)
1486 		return (Z_ERR);
1487 	zarg.cmd = force ? Z_FORCEBOOT : Z_BOOT;
1488 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1489 		zerror(gettext("call to %s failed"), "zoneadmd");
1490 		return (Z_ERR);
1491 	}
1492 	return (Z_OK);
1493 }
1494 
1495 static void
1496 fake_up_local_zone(zoneid_t zid, zone_entry_t *zeptr)
1497 {
1498 	ssize_t result;
1499 	uuid_t uuid;
1500 	FILE *fp;
1501 
1502 	(void) memset(zeptr, 0, sizeof (*zeptr));
1503 
1504 	zeptr->zid = zid;
1505 
1506 	/*
1507 	 * Since we're looking up our own (non-global) zone name,
1508 	 * we can be assured that it will succeed.
1509 	 */
1510 	result = getzonenamebyid(zid, zeptr->zname, sizeof (zeptr->zname));
1511 	assert(result >= 0);
1512 	if (zonecfg_is_scratch(zeptr->zname) &&
1513 	    (fp = zonecfg_open_scratch("", B_FALSE)) != NULL) {
1514 		(void) zonecfg_reverse_scratch(fp, zeptr->zname, zeptr->zname,
1515 		    sizeof (zeptr->zname), NULL, 0);
1516 		zonecfg_close_scratch(fp);
1517 	}
1518 
1519 	if (is_system_labeled()) {
1520 		(void) zone_getattr(zid, ZONE_ATTR_ROOT, zeptr->zroot,
1521 		    sizeof (zeptr->zroot));
1522 		(void) strlcpy(zeptr->zbrand, NATIVE_BRAND_NAME,
1523 			    sizeof (zeptr->zbrand));
1524 	} else {
1525 		(void) strlcpy(zeptr->zroot, "/", sizeof (zeptr->zroot));
1526 		(void) zone_getattr(zid, ZONE_ATTR_BRAND, zeptr->zbrand,
1527 		    sizeof (zeptr->zbrand));
1528 	}
1529 
1530 	zeptr->zstate_str = "running";
1531 	if (zonecfg_get_uuid(zeptr->zname, uuid) == Z_OK &&
1532 	    !uuid_is_null(uuid))
1533 		uuid_unparse(uuid, zeptr->zuuid);
1534 }
1535 
1536 static int
1537 list_func(int argc, char *argv[])
1538 {
1539 	zone_entry_t *zentp, zent;
1540 	int arg, retv;
1541 	boolean_t output = B_FALSE, verbose = B_FALSE, parsable = B_FALSE;
1542 	zone_state_t min_state = ZONE_STATE_RUNNING;
1543 	zoneid_t zone_id = getzoneid();
1544 
1545 	if (target_zone == NULL) {
1546 		/* all zones: default view to running but allow override */
1547 		optind = 0;
1548 		while ((arg = getopt(argc, argv, "?cipv")) != EOF) {
1549 			switch (arg) {
1550 			case '?':
1551 				sub_usage(SHELP_LIST, CMD_LIST);
1552 				return (optopt == '?' ? Z_OK : Z_USAGE);
1553 				/*
1554 				 * The 'i' and 'c' options are not mutually
1555 				 * exclusive so if 'c' is given, then min_state
1556 				 * is set to 0 (ZONE_STATE_CONFIGURED) which is
1557 				 * the lowest possible state.  If 'i' is given,
1558 				 * then min_state is set to be the lowest state
1559 				 * so far.
1560 				 */
1561 			case 'c':
1562 				min_state = ZONE_STATE_CONFIGURED;
1563 				break;
1564 			case 'i':
1565 				min_state = min(ZONE_STATE_INSTALLED,
1566 				    min_state);
1567 
1568 				break;
1569 			case 'p':
1570 				parsable = B_TRUE;
1571 				break;
1572 			case 'v':
1573 				verbose = B_TRUE;
1574 				break;
1575 			default:
1576 				sub_usage(SHELP_LIST, CMD_LIST);
1577 				return (Z_USAGE);
1578 			}
1579 		}
1580 		if (parsable && verbose) {
1581 			zerror(gettext("%s -p and -v are mutually exclusive."),
1582 			    cmd_to_str(CMD_LIST));
1583 			return (Z_ERR);
1584 		}
1585 		if (zone_id == GLOBAL_ZONEID || is_system_labeled()) {
1586 			retv = zone_print_list(min_state, verbose, parsable);
1587 		} else {
1588 			fake_up_local_zone(zone_id, &zent);
1589 			retv = Z_OK;
1590 			zone_print(&zent, verbose, parsable);
1591 		}
1592 		return (retv);
1593 	}
1594 
1595 	/*
1596 	 * Specific target zone: disallow -i/-c suboptions.
1597 	 */
1598 	optind = 0;
1599 	while ((arg = getopt(argc, argv, "?pv")) != EOF) {
1600 		switch (arg) {
1601 		case '?':
1602 			sub_usage(SHELP_LIST, CMD_LIST);
1603 			return (optopt == '?' ? Z_OK : Z_USAGE);
1604 		case 'p':
1605 			parsable = B_TRUE;
1606 			break;
1607 		case 'v':
1608 			verbose = B_TRUE;
1609 			break;
1610 		default:
1611 			sub_usage(SHELP_LIST, CMD_LIST);
1612 			return (Z_USAGE);
1613 		}
1614 	}
1615 	if (parsable && verbose) {
1616 		zerror(gettext("%s -p and -v are mutually exclusive."),
1617 		    cmd_to_str(CMD_LIST));
1618 		return (Z_ERR);
1619 	}
1620 	if (argc > optind) {
1621 		sub_usage(SHELP_LIST, CMD_LIST);
1622 		return (Z_USAGE);
1623 	}
1624 	if (zone_id != GLOBAL_ZONEID) {
1625 		fake_up_local_zone(zone_id, &zent);
1626 		/*
1627 		 * main() will issue a Z_NO_ZONE error if it cannot get an
1628 		 * id for target_zone, which in a non-global zone should
1629 		 * happen for any zone name except `zonename`.  Thus we
1630 		 * assert() that here but don't otherwise check.
1631 		 */
1632 		assert(strcmp(zent.zname, target_zone) == 0);
1633 		zone_print(&zent, verbose, parsable);
1634 		output = B_TRUE;
1635 	} else if ((zentp = lookup_running_zone(target_zone)) != NULL) {
1636 		zone_print(zentp, verbose, parsable);
1637 		output = B_TRUE;
1638 	} else if (lookup_zone_info(target_zone, ZONE_ID_UNDEFINED,
1639 	    &zent) == Z_OK) {
1640 		zone_print(&zent, verbose, parsable);
1641 		output = B_TRUE;
1642 	}
1643 	return (output ? Z_OK : Z_ERR);
1644 }
1645 
1646 static void
1647 sigterm(int sig)
1648 {
1649 	/*
1650 	 * Ignore SIG{INT,TERM}, so we don't end up in an infinite loop,
1651 	 * then propagate the signal to our process group.
1652 	 */
1653 	assert(sig == SIGINT || sig == SIGTERM);
1654 	(void) sigset(SIGINT, SIG_IGN);
1655 	(void) sigset(SIGTERM, SIG_IGN);
1656 	(void) kill(0, sig);
1657 	child_killed = B_TRUE;
1658 }
1659 
1660 static int
1661 do_subproc(char *cmdbuf)
1662 {
1663 	char inbuf[1024];	/* arbitrary large amount */
1664 	FILE *file;
1665 
1666 	do_subproc_cnt++;
1667 	child_killed = B_FALSE;
1668 	/*
1669 	 * We use popen(3c) to launch child processes for [un]install;
1670 	 * this library call does not return a PID, so we have to kill
1671 	 * the whole process group.  To avoid killing our parent, we
1672 	 * become a process group leader here.  But doing so can wreak
1673 	 * havoc with reading from stdin when launched by a non-job-control
1674 	 * shell, so we close stdin and reopen it as /dev/null first.
1675 	 */
1676 	(void) close(STDIN_FILENO);
1677 	(void) openat(STDIN_FILENO, "/dev/null", O_RDONLY);
1678 	if (!zoneadm_is_nested)
1679 		(void) setpgid(0, 0);
1680 	(void) sigset(SIGINT, sigterm);
1681 	(void) sigset(SIGTERM, sigterm);
1682 	file = popen(cmdbuf, "r");
1683 	for (;;) {
1684 		if (child_killed || fgets(inbuf, sizeof (inbuf), file) == NULL)
1685 			break;
1686 		(void) fputs(inbuf, stdout);
1687 	}
1688 	(void) sigset(SIGINT, SIG_DFL);
1689 	(void) sigset(SIGTERM, SIG_DFL);
1690 	return (pclose(file));
1691 }
1692 
1693 static int
1694 do_subproc_interactive(char *cmdbuf)
1695 {
1696 	void (*saveint)(int);
1697 	void (*saveterm)(int);
1698 	void (*savequit)(int);
1699 	void (*savehup)(int);
1700 	int pid, child, status;
1701 
1702 	/*
1703 	 * do_subproc() links stdin to /dev/null, which would break any
1704 	 * interactive subprocess we try to launch here.  Similarly, we
1705 	 * can't have been launched as a subprocess ourselves.
1706 	 */
1707 	assert(do_subproc_cnt == 0 && !zoneadm_is_nested);
1708 
1709 	if ((child = vfork()) == 0) {
1710 		(void) execl("/bin/sh", "sh", "-c", cmdbuf, (char *)NULL);
1711 	}
1712 
1713 	if (child == -1)
1714 		return (-1);
1715 
1716 	saveint = sigset(SIGINT, SIG_IGN);
1717 	saveterm = sigset(SIGTERM, SIG_IGN);
1718 	savequit = sigset(SIGQUIT, SIG_IGN);
1719 	savehup = sigset(SIGHUP, SIG_IGN);
1720 
1721 	while ((pid = waitpid(child, &status, 0)) != child && pid != -1)
1722 		;
1723 
1724 	(void) sigset(SIGINT, saveint);
1725 	(void) sigset(SIGTERM, saveterm);
1726 	(void) sigset(SIGQUIT, savequit);
1727 	(void) sigset(SIGHUP, savehup);
1728 
1729 	return (pid == -1 ? -1 : status);
1730 }
1731 
1732 static int
1733 subproc_status(const char *cmd, int status, boolean_t verbose_failure)
1734 {
1735 	if (WIFEXITED(status)) {
1736 		int exit_code = WEXITSTATUS(status);
1737 
1738 		if ((verbose_failure) && (exit_code != ZONE_SUBPROC_OK))
1739 			zerror(gettext("'%s' failed with exit code %d."), cmd,
1740 			    exit_code);
1741 
1742 		return (exit_code);
1743 	} else if (WIFSIGNALED(status)) {
1744 		int signal = WTERMSIG(status);
1745 		char sigstr[SIG2STR_MAX];
1746 
1747 		if (sig2str(signal, sigstr) == 0) {
1748 			zerror(gettext("'%s' terminated by signal SIG%s."), cmd,
1749 			    sigstr);
1750 		} else {
1751 			zerror(gettext("'%s' terminated by an unknown signal."),
1752 			    cmd);
1753 		}
1754 	} else {
1755 		zerror(gettext("'%s' failed for unknown reasons."), cmd);
1756 	}
1757 
1758 	/*
1759 	 * Assume a subprocess that died due to a signal or an unknown error
1760 	 * should be considered an exit code of ZONE_SUBPROC_FATAL, as the
1761 	 * user will likely need to do some manual cleanup.
1762 	 */
1763 	return (ZONE_SUBPROC_FATAL);
1764 }
1765 
1766 /*
1767  * Various sanity checks; make sure:
1768  * 1. We're in the global zone.
1769  * 2. The calling user has sufficient privilege.
1770  * 3. The target zone is neither the global zone nor anything starting with
1771  *    "SUNW".
1772  * 4a. If we're looking for a 'not running' (i.e., configured or installed)
1773  *     zone, the name service knows about it.
1774  * 4b. For some operations which expect a zone not to be running, that it is
1775  *     not already running (or ready).
1776  */
1777 static int
1778 sanity_check(char *zone, int cmd_num, boolean_t running,
1779     boolean_t unsafe_when_running, boolean_t force)
1780 {
1781 	zone_entry_t *zent;
1782 	priv_set_t *privset;
1783 	zone_state_t state, min_state;
1784 	char kernzone[ZONENAME_MAX];
1785 	FILE *fp;
1786 
1787 	if (getzoneid() != GLOBAL_ZONEID) {
1788 		switch (cmd_num) {
1789 		case CMD_HALT:
1790 			zerror(gettext("use %s to %s this zone."), "halt(1M)",
1791 			    cmd_to_str(cmd_num));
1792 			break;
1793 		case CMD_REBOOT:
1794 			zerror(gettext("use %s to %s this zone."),
1795 			    "reboot(1M)", cmd_to_str(cmd_num));
1796 			break;
1797 		default:
1798 			zerror(gettext("must be in the global zone to %s a "
1799 			    "zone."), cmd_to_str(cmd_num));
1800 			break;
1801 		}
1802 		return (Z_ERR);
1803 	}
1804 
1805 	if ((privset = priv_allocset()) == NULL) {
1806 		zerror(gettext("%s failed"), "priv_allocset");
1807 		return (Z_ERR);
1808 	}
1809 
1810 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
1811 		zerror(gettext("%s failed"), "getppriv");
1812 		priv_freeset(privset);
1813 		return (Z_ERR);
1814 	}
1815 
1816 	if (priv_isfullset(privset) == B_FALSE) {
1817 		zerror(gettext("only a privileged user may %s a zone."),
1818 		    cmd_to_str(cmd_num));
1819 		priv_freeset(privset);
1820 		return (Z_ERR);
1821 	}
1822 	priv_freeset(privset);
1823 
1824 	if (zone == NULL) {
1825 		zerror(gettext("no zone specified"));
1826 		return (Z_ERR);
1827 	}
1828 
1829 	if (strcmp(zone, GLOBAL_ZONENAME) == 0) {
1830 		zerror(gettext("%s operation is invalid for the global zone."),
1831 		    cmd_to_str(cmd_num));
1832 		return (Z_ERR);
1833 	}
1834 
1835 	if (strncmp(zone, "SUNW", 4) == 0) {
1836 		zerror(gettext("%s operation is invalid for zones starting "
1837 		    "with SUNW."), cmd_to_str(cmd_num));
1838 		return (Z_ERR);
1839 	}
1840 
1841 	if (!is_native_zone && cmd_num == CMD_MOUNT) {
1842 		zerror(gettext("%s operation is invalid for branded zones."),
1843 		    cmd_to_str(cmd_num));
1844 			return (Z_ERR);
1845 	}
1846 
1847 	if (!zonecfg_in_alt_root()) {
1848 		zent = lookup_running_zone(zone);
1849 	} else if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
1850 		zent = NULL;
1851 	} else {
1852 		if (zonecfg_find_scratch(fp, zone, zonecfg_get_root(),
1853 		    kernzone, sizeof (kernzone)) == 0)
1854 			zent = lookup_running_zone(kernzone);
1855 		else
1856 			zent = NULL;
1857 		zonecfg_close_scratch(fp);
1858 	}
1859 
1860 	/*
1861 	 * Look up from the kernel for 'running' zones.
1862 	 */
1863 	if (running && !force) {
1864 		if (zent == NULL) {
1865 			zerror(gettext("not running"));
1866 			return (Z_ERR);
1867 		}
1868 	} else {
1869 		int err;
1870 
1871 		if (unsafe_when_running && zent != NULL) {
1872 			/* check whether the zone is ready or running */
1873 			if ((err = zone_get_state(zent->zname,
1874 			    &zent->zstate_num)) != Z_OK) {
1875 				errno = err;
1876 				zperror2(zent->zname,
1877 				    gettext("could not get state"));
1878 				/* can't tell, so hedge */
1879 				zent->zstate_str = "ready/running";
1880 			} else {
1881 				zent->zstate_str =
1882 				    zone_state_str(zent->zstate_num);
1883 			}
1884 			zerror(gettext("%s operation is invalid for %s zones."),
1885 			    cmd_to_str(cmd_num), zent->zstate_str);
1886 			return (Z_ERR);
1887 		}
1888 		if ((err = zone_get_state(zone, &state)) != Z_OK) {
1889 			errno = err;
1890 			zperror2(zone, gettext("could not get state"));
1891 			return (Z_ERR);
1892 		}
1893 		switch (cmd_num) {
1894 		case CMD_UNINSTALL:
1895 			if (state == ZONE_STATE_CONFIGURED) {
1896 				zerror(gettext("is already in state '%s'."),
1897 				    zone_state_str(ZONE_STATE_CONFIGURED));
1898 				return (Z_ERR);
1899 			}
1900 			break;
1901 		case CMD_ATTACH:
1902 		case CMD_CLONE:
1903 		case CMD_INSTALL:
1904 			if (state == ZONE_STATE_INSTALLED) {
1905 				zerror(gettext("is already %s."),
1906 				    zone_state_str(ZONE_STATE_INSTALLED));
1907 				return (Z_ERR);
1908 			} else if (state == ZONE_STATE_INCOMPLETE) {
1909 				zerror(gettext("zone is %s; %s required."),
1910 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1911 				    cmd_to_str(CMD_UNINSTALL));
1912 				return (Z_ERR);
1913 			}
1914 			break;
1915 		case CMD_DETACH:
1916 		case CMD_MOVE:
1917 		case CMD_READY:
1918 		case CMD_BOOT:
1919 		case CMD_MOUNT:
1920 		case CMD_MARK:
1921 			if ((cmd_num == CMD_BOOT || cmd_num == CMD_MOUNT) &&
1922 			    force)
1923 				min_state = ZONE_STATE_INCOMPLETE;
1924 			else
1925 				min_state = ZONE_STATE_INSTALLED;
1926 
1927 			if (force && cmd_num == CMD_BOOT && is_native_zone) {
1928 				zerror(gettext("Only branded zones may be "
1929 				    "force-booted."));
1930 				return (Z_ERR);
1931 			}
1932 
1933 			if (state < min_state) {
1934 				zerror(gettext("must be %s before %s."),
1935 				    zone_state_str(min_state),
1936 				    cmd_to_str(cmd_num));
1937 				return (Z_ERR);
1938 			}
1939 			break;
1940 		case CMD_VERIFY:
1941 			if (state == ZONE_STATE_INCOMPLETE) {
1942 				zerror(gettext("zone is %s; %s required."),
1943 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1944 				    cmd_to_str(CMD_UNINSTALL));
1945 				return (Z_ERR);
1946 			}
1947 			break;
1948 		case CMD_UNMOUNT:
1949 			if (state != ZONE_STATE_MOUNTED) {
1950 				zerror(gettext("must be %s before %s."),
1951 				    zone_state_str(ZONE_STATE_MOUNTED),
1952 				    cmd_to_str(cmd_num));
1953 				return (Z_ERR);
1954 			}
1955 			break;
1956 		}
1957 	}
1958 	return (Z_OK);
1959 }
1960 
1961 static int
1962 halt_func(int argc, char *argv[])
1963 {
1964 	zone_cmd_arg_t zarg;
1965 	int arg;
1966 
1967 	if (zonecfg_in_alt_root()) {
1968 		zerror(gettext("cannot halt zone in alternate root"));
1969 		return (Z_ERR);
1970 	}
1971 
1972 	optind = 0;
1973 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1974 		switch (arg) {
1975 		case '?':
1976 			sub_usage(SHELP_HALT, CMD_HALT);
1977 			return (optopt == '?' ? Z_OK : Z_USAGE);
1978 		default:
1979 			sub_usage(SHELP_HALT, CMD_HALT);
1980 			return (Z_USAGE);
1981 		}
1982 	}
1983 	if (argc > optind) {
1984 		sub_usage(SHELP_HALT, CMD_HALT);
1985 		return (Z_USAGE);
1986 	}
1987 	/*
1988 	 * zoneadmd should be the one to decide whether or not to proceed,
1989 	 * so even though it seems that the fourth parameter below should
1990 	 * perhaps be B_TRUE, it really shouldn't be.
1991 	 */
1992 	if (sanity_check(target_zone, CMD_HALT, B_FALSE, B_FALSE, B_FALSE)
1993 	    != Z_OK)
1994 		return (Z_ERR);
1995 
1996 	zarg.cmd = Z_HALT;
1997 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
1998 }
1999 
2000 static int
2001 reboot_func(int argc, char *argv[])
2002 {
2003 	zone_cmd_arg_t zarg;
2004 	int arg;
2005 
2006 	if (zonecfg_in_alt_root()) {
2007 		zerror(gettext("cannot reboot zone in alternate root"));
2008 		return (Z_ERR);
2009 	}
2010 
2011 	optind = 0;
2012 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2013 		switch (arg) {
2014 		case '?':
2015 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
2016 			return (optopt == '?' ? Z_OK : Z_USAGE);
2017 		default:
2018 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
2019 			return (Z_USAGE);
2020 		}
2021 	}
2022 
2023 	zarg.bootbuf[0] = '\0';
2024 	for (; optind < argc; optind++) {
2025 		if (strlcat(zarg.bootbuf, argv[optind],
2026 		    sizeof (zarg.bootbuf)) >= sizeof (zarg.bootbuf)) {
2027 			zerror(gettext("Boot argument list too long"));
2028 			return (Z_ERR);
2029 		}
2030 		if (optind < argc - 1)
2031 			if (strlcat(zarg.bootbuf, " ", sizeof (zarg.bootbuf)) >=
2032 			    sizeof (zarg.bootbuf)) {
2033 				zerror(gettext("Boot argument list too long"));
2034 				return (Z_ERR);
2035 			}
2036 	}
2037 
2038 
2039 	/*
2040 	 * zoneadmd should be the one to decide whether or not to proceed,
2041 	 * so even though it seems that the fourth parameter below should
2042 	 * perhaps be B_TRUE, it really shouldn't be.
2043 	 */
2044 	if (sanity_check(target_zone, CMD_REBOOT, B_TRUE, B_FALSE, B_FALSE)
2045 	    != Z_OK)
2046 		return (Z_ERR);
2047 	if (verify_details(CMD_REBOOT) != Z_OK)
2048 		return (Z_ERR);
2049 
2050 	zarg.cmd = Z_REBOOT;
2051 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
2052 }
2053 
2054 static int
2055 verify_brand(zone_dochandle_t handle)
2056 {
2057 	char cmdbuf[MAXPATHLEN];
2058 	int err;
2059 	char zonepath[MAXPATHLEN];
2060 	brand_handle_t bh = NULL;
2061 	int status;
2062 
2063 	/*
2064 	 * Fetch the verify command from the brand configuration.
2065 	 * "exec" the command so that the returned status is that of
2066 	 * the command and not the shell.
2067 	 */
2068 	if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
2069 	    Z_OK) {
2070 		errno = err;
2071 		zperror(cmd_to_str(CMD_VERIFY), B_TRUE);
2072 		return (Z_ERR);
2073 	}
2074 	if ((bh = brand_open(target_brand)) == NULL) {
2075 		zerror(gettext("missing or invalid brand"));
2076 		return (Z_ERR);
2077 	}
2078 
2079 	/*
2080 	 * If the brand has its own verification routine, execute it now.
2081 	 */
2082 	(void) strcpy(cmdbuf, EXEC_PREFIX);
2083 	err = brand_get_verify_adm(bh, target_zone, zonepath,
2084 	    cmdbuf + EXEC_LEN, sizeof (cmdbuf) - EXEC_LEN, 0, NULL);
2085 	brand_close(bh);
2086 	if (err == 0 && strlen(cmdbuf) > EXEC_LEN) {
2087 		status = do_subproc_interactive(cmdbuf);
2088 		err = subproc_status(gettext("brand-specific verification"),
2089 		    status, B_FALSE);
2090 		return ((err == ZONE_SUBPROC_OK) ? Z_OK : Z_BRAND_ERROR);
2091 	}
2092 
2093 	return ((err == Z_OK) ? Z_OK : Z_BRAND_ERROR);
2094 }
2095 
2096 static int
2097 verify_rctls(zone_dochandle_t handle)
2098 {
2099 	struct zone_rctltab rctltab;
2100 	size_t rbs = rctlblk_size();
2101 	rctlblk_t *rctlblk;
2102 	int error = Z_INVAL;
2103 
2104 	if ((rctlblk = malloc(rbs)) == NULL) {
2105 		zerror(gettext("failed to allocate %lu bytes: %s"), rbs,
2106 		    strerror(errno));
2107 		return (Z_NOMEM);
2108 	}
2109 
2110 	if (zonecfg_setrctlent(handle) != Z_OK) {
2111 		zerror(gettext("zonecfg_setrctlent failed"));
2112 		free(rctlblk);
2113 		return (error);
2114 	}
2115 
2116 	rctltab.zone_rctl_valptr = NULL;
2117 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2118 		struct zone_rctlvaltab *rctlval;
2119 		const char *name = rctltab.zone_rctl_name;
2120 
2121 		if (!zonecfg_is_rctl(name)) {
2122 			zerror(gettext("WARNING: Ignoring unrecognized rctl "
2123 			    "'%s'."),  name);
2124 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2125 			rctltab.zone_rctl_valptr = NULL;
2126 			continue;
2127 		}
2128 
2129 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2130 		    rctlval = rctlval->zone_rctlval_next) {
2131 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2132 			    != Z_OK) {
2133 				zerror(gettext("invalid rctl value: "
2134 				    "(priv=%s,limit=%s,action%s)"),
2135 				    rctlval->zone_rctlval_priv,
2136 				    rctlval->zone_rctlval_limit,
2137 				    rctlval->zone_rctlval_action);
2138 				goto out;
2139 			}
2140 			if (!zonecfg_valid_rctl(name, rctlblk)) {
2141 				zerror(gettext("(priv=%s,limit=%s,action=%s) "
2142 				    "is not a valid value for rctl '%s'"),
2143 				    rctlval->zone_rctlval_priv,
2144 				    rctlval->zone_rctlval_limit,
2145 				    rctlval->zone_rctlval_action,
2146 				    name);
2147 				goto out;
2148 			}
2149 		}
2150 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2151 	}
2152 	rctltab.zone_rctl_valptr = NULL;
2153 	error = Z_OK;
2154 out:
2155 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2156 	(void) zonecfg_endrctlent(handle);
2157 	free(rctlblk);
2158 	return (error);
2159 }
2160 
2161 static int
2162 verify_pool(zone_dochandle_t handle)
2163 {
2164 	char poolname[MAXPATHLEN];
2165 	pool_conf_t *poolconf;
2166 	pool_t *pool;
2167 	int status;
2168 	int error;
2169 
2170 	/*
2171 	 * This ends up being very similar to the check done in zoneadmd.
2172 	 */
2173 	error = zonecfg_get_pool(handle, poolname, sizeof (poolname));
2174 	if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
2175 		/*
2176 		 * No pool specified.
2177 		 */
2178 		return (0);
2179 	}
2180 	if (error != Z_OK) {
2181 		zperror(gettext("Unable to retrieve pool name from "
2182 		    "configuration"), B_TRUE);
2183 		return (error);
2184 	}
2185 	/*
2186 	 * Don't do anything if pools aren't enabled.
2187 	 */
2188 	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
2189 		zerror(gettext("WARNING: pools facility not active; "
2190 		    "zone will not be bound to pool '%s'."), poolname);
2191 		return (Z_OK);
2192 	}
2193 	/*
2194 	 * Try to provide a sane error message if the requested pool doesn't
2195 	 * exist.  It isn't clear that pools-related failures should
2196 	 * necessarily translate to a failure to verify the zone configuration,
2197 	 * hence they are not considered errors.
2198 	 */
2199 	if ((poolconf = pool_conf_alloc()) == NULL) {
2200 		zerror(gettext("WARNING: pool_conf_alloc failed; "
2201 		    "using default pool"));
2202 		return (Z_OK);
2203 	}
2204 	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
2205 	    PO_SUCCESS) {
2206 		zerror(gettext("WARNING: pool_conf_open failed; "
2207 		    "using default pool"));
2208 		pool_conf_free(poolconf);
2209 		return (Z_OK);
2210 	}
2211 	pool = pool_get_pool(poolconf, poolname);
2212 	(void) pool_conf_close(poolconf);
2213 	pool_conf_free(poolconf);
2214 	if (pool == NULL) {
2215 		zerror(gettext("WARNING: pool '%s' not found. "
2216 		    "using default pool"), poolname);
2217 	}
2218 
2219 	return (Z_OK);
2220 }
2221 
2222 static int
2223 verify_ipd(zone_dochandle_t handle)
2224 {
2225 	int return_code = Z_OK;
2226 	struct zone_fstab fstab;
2227 	struct stat st;
2228 	char specdir[MAXPATHLEN];
2229 
2230 	if (zonecfg_setipdent(handle) != Z_OK) {
2231 		/*
2232 		 * TRANSLATION_NOTE
2233 		 * inherit-pkg-dirs is a literal that should not be translated.
2234 		 */
2235 		(void) fprintf(stderr, gettext("could not verify "
2236 		    "inherit-pkg-dirs: unable to enumerate mounts\n"));
2237 		return (Z_ERR);
2238 	}
2239 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
2240 		/*
2241 		 * Verify fs_dir exists.
2242 		 */
2243 		(void) snprintf(specdir, sizeof (specdir), "%s%s",
2244 		    zonecfg_get_root(), fstab.zone_fs_dir);
2245 		if (stat(specdir, &st) != 0) {
2246 			/*
2247 			 * TRANSLATION_NOTE
2248 			 * inherit-pkg-dir is a literal that should not be
2249 			 * translated.
2250 			 */
2251 			(void) fprintf(stderr, gettext("could not verify "
2252 			    "inherit-pkg-dir %s: %s\n"),
2253 			    fstab.zone_fs_dir, strerror(errno));
2254 			return_code = Z_ERR;
2255 		}
2256 		if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
2257 			/*
2258 			 * TRANSLATION_NOTE
2259 			 * inherit-pkg-dir and NFS are literals that should
2260 			 * not be translated.
2261 			 */
2262 			(void) fprintf(stderr, gettext("cannot verify "
2263 			    "inherit-pkg-dir %s: NFS mounted file system.\n"
2264 			    "\tA local file system must be used.\n"),
2265 			    fstab.zone_fs_dir);
2266 			return_code = Z_ERR;
2267 		}
2268 	}
2269 	(void) zonecfg_endipdent(handle);
2270 
2271 	return (return_code);
2272 }
2273 
2274 /*
2275  * Verify that the special device/file system exists and is valid.
2276  */
2277 static int
2278 verify_fs_special(struct zone_fstab *fstab)
2279 {
2280 	struct stat st;
2281 
2282 	if (strcmp(fstab->zone_fs_type, MNTTYPE_ZFS) == 0)
2283 		return (verify_fs_zfs(fstab));
2284 
2285 	if (stat(fstab->zone_fs_special, &st) != 0) {
2286 		(void) fprintf(stderr, gettext("could not verify fs "
2287 		    "%s: could not access %s: %s\n"), fstab->zone_fs_dir,
2288 		    fstab->zone_fs_special, strerror(errno));
2289 		return (Z_ERR);
2290 	}
2291 
2292 	if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
2293 		/*
2294 		 * TRANSLATION_NOTE
2295 		 * fs and NFS are literals that should
2296 		 * not be translated.
2297 		 */
2298 		(void) fprintf(stderr, gettext("cannot verify "
2299 		    "fs %s: NFS mounted file system.\n"
2300 		    "\tA local file system must be used.\n"),
2301 		    fstab->zone_fs_special);
2302 		return (Z_ERR);
2303 	}
2304 
2305 	return (Z_OK);
2306 }
2307 
2308 static int
2309 verify_filesystems(zone_dochandle_t handle)
2310 {
2311 	int return_code = Z_OK;
2312 	struct zone_fstab fstab;
2313 	char cmdbuf[MAXPATHLEN];
2314 	struct stat st;
2315 
2316 	/*
2317 	 * No need to verify inherit-pkg-dir fs types, as their type is
2318 	 * implicitly lofs, which is known.  Therefore, the types are only
2319 	 * verified for regular file systems below.
2320 	 *
2321 	 * Since the actual mount point is not known until the dependent mounts
2322 	 * are performed, we don't attempt any path validation here: that will
2323 	 * happen later when zoneadmd actually does the mounts.
2324 	 */
2325 	if (zonecfg_setfsent(handle) != Z_OK) {
2326 		(void) fprintf(stderr, gettext("could not verify file systems: "
2327 		    "unable to enumerate mounts\n"));
2328 		return (Z_ERR);
2329 	}
2330 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
2331 		if (!zonecfg_valid_fs_type(fstab.zone_fs_type)) {
2332 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2333 			    "type %s is not allowed.\n"), fstab.zone_fs_dir,
2334 			    fstab.zone_fs_type);
2335 			return_code = Z_ERR;
2336 			goto next_fs;
2337 		}
2338 		/*
2339 		 * Verify /usr/lib/fs/<fstype>/mount exists.
2340 		 */
2341 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount",
2342 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
2343 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2344 			    "type %s is too long.\n"), fstab.zone_fs_dir,
2345 			    fstab.zone_fs_type);
2346 			return_code = Z_ERR;
2347 			goto next_fs;
2348 		}
2349 		if (stat(cmdbuf, &st) != 0) {
2350 			(void) fprintf(stderr, gettext("could not verify fs "
2351 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2352 			    cmdbuf, strerror(errno));
2353 			return_code = Z_ERR;
2354 			goto next_fs;
2355 		}
2356 		if (!S_ISREG(st.st_mode)) {
2357 			(void) fprintf(stderr, gettext("could not verify fs "
2358 			    "%s: %s is not a regular file\n"),
2359 			    fstab.zone_fs_dir, cmdbuf);
2360 			return_code = Z_ERR;
2361 			goto next_fs;
2362 		}
2363 		/*
2364 		 * Verify /usr/lib/fs/<fstype>/fsck exists iff zone_fs_raw is
2365 		 * set.
2366 		 */
2367 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck",
2368 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
2369 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2370 			    "type %s is too long.\n"), fstab.zone_fs_dir,
2371 			    fstab.zone_fs_type);
2372 			return_code = Z_ERR;
2373 			goto next_fs;
2374 		}
2375 		if (fstab.zone_fs_raw[0] == '\0' && stat(cmdbuf, &st) == 0) {
2376 			(void) fprintf(stderr, gettext("could not verify fs "
2377 			    "%s: must specify 'raw' device for %s "
2378 			    "file systems\n"),
2379 			    fstab.zone_fs_dir, fstab.zone_fs_type);
2380 			return_code = Z_ERR;
2381 			goto next_fs;
2382 		}
2383 		if (fstab.zone_fs_raw[0] != '\0' &&
2384 		    (stat(cmdbuf, &st) != 0 || !S_ISREG(st.st_mode))) {
2385 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2386 			    "'raw' device specified but "
2387 			    "no fsck executable exists for %s\n"),
2388 			    fstab.zone_fs_dir, fstab.zone_fs_type);
2389 			return_code = Z_ERR;
2390 			goto next_fs;
2391 		}
2392 
2393 		/* Verify fs_special. */
2394 		if ((return_code = verify_fs_special(&fstab)) != Z_OK)
2395 			goto next_fs;
2396 
2397 		/* Verify fs_raw. */
2398 		if (fstab.zone_fs_raw[0] != '\0' &&
2399 		    stat(fstab.zone_fs_raw, &st) != 0) {
2400 			/*
2401 			 * TRANSLATION_NOTE
2402 			 * fs is a literal that should not be translated.
2403 			 */
2404 			(void) fprintf(stderr, gettext("could not verify fs "
2405 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2406 			    fstab.zone_fs_raw, strerror(errno));
2407 			return_code = Z_ERR;
2408 			goto next_fs;
2409 		}
2410 next_fs:
2411 		zonecfg_free_fs_option_list(fstab.zone_fs_options);
2412 	}
2413 	(void) zonecfg_endfsent(handle);
2414 
2415 	return (return_code);
2416 }
2417 
2418 static int
2419 verify_limitpriv(zone_dochandle_t handle)
2420 {
2421 	char *privname = NULL;
2422 	int err;
2423 	priv_set_t *privs;
2424 
2425 	if ((privs = priv_allocset()) == NULL) {
2426 		zperror(gettext("failed to allocate privilege set"), B_FALSE);
2427 		return (Z_NOMEM);
2428 	}
2429 	err = zonecfg_get_privset(handle, privs, &privname);
2430 	switch (err) {
2431 	case Z_OK:
2432 		break;
2433 	case Z_PRIV_PROHIBITED:
2434 		(void) fprintf(stderr, gettext("privilege \"%s\" is not "
2435 		    "permitted within the zone's privilege set\n"), privname);
2436 		break;
2437 	case Z_PRIV_REQUIRED:
2438 		(void) fprintf(stderr, gettext("required privilege \"%s\" is "
2439 		    "missing from the zone's privilege set\n"), privname);
2440 		break;
2441 	case Z_PRIV_UNKNOWN:
2442 		(void) fprintf(stderr, gettext("unknown privilege \"%s\" "
2443 		    "specified in the zone's privilege set\n"), privname);
2444 		break;
2445 	default:
2446 		zperror(
2447 		    gettext("failed to determine the zone's privilege set"),
2448 		    B_TRUE);
2449 		break;
2450 	}
2451 	free(privname);
2452 	priv_freeset(privs);
2453 	return (err);
2454 }
2455 
2456 static void
2457 free_local_netifs(int if_cnt, struct net_if **if_list)
2458 {
2459 	int		i;
2460 
2461 	for (i = 0; i < if_cnt; i++) {
2462 		free(if_list[i]->name);
2463 		free(if_list[i]);
2464 	}
2465 	free(if_list);
2466 }
2467 
2468 /*
2469  * Get a list of the network interfaces, along with their address families,
2470  * that are plumbed in the global zone.  See if_tcp(7p) for a description
2471  * of the ioctls used here.
2472  */
2473 static int
2474 get_local_netifs(int *if_cnt, struct net_if ***if_list)
2475 {
2476 	int		s;
2477 	int		i;
2478 	int		res = Z_OK;
2479 	int		space_needed;
2480 	int		cnt = 0;
2481 	struct		lifnum if_num;
2482 	struct		lifconf if_conf;
2483 	struct		lifreq *if_reqp;
2484 	char		*if_buf;
2485 	struct net_if	**local_ifs = NULL;
2486 
2487 	*if_cnt = 0;
2488 	*if_list = NULL;
2489 
2490 	if ((s = socket(SOCKET_AF(AF_INET), SOCK_DGRAM, 0)) < 0)
2491 		return (Z_ERR);
2492 
2493 	/*
2494 	 * Come back here in the unlikely event that the number of interfaces
2495 	 * increases between the time we get the count and the time we do the
2496 	 * SIOCGLIFCONF ioctl.
2497 	 */
2498 retry:
2499 	/* Get the number of interfaces. */
2500 	if_num.lifn_family = AF_UNSPEC;
2501 	if_num.lifn_flags = LIFC_NOXMIT;
2502 	if (ioctl(s, SIOCGLIFNUM, &if_num) < 0) {
2503 		(void) close(s);
2504 		return (Z_ERR);
2505 	}
2506 
2507 	/* Get the interface configuration list. */
2508 	space_needed = if_num.lifn_count * sizeof (struct lifreq);
2509 	if ((if_buf = malloc(space_needed)) == NULL) {
2510 		(void) close(s);
2511 		return (Z_ERR);
2512 	}
2513 	if_conf.lifc_family = AF_UNSPEC;
2514 	if_conf.lifc_flags = LIFC_NOXMIT;
2515 	if_conf.lifc_len = space_needed;
2516 	if_conf.lifc_buf = if_buf;
2517 	if (ioctl(s, SIOCGLIFCONF, &if_conf) < 0) {
2518 		free(if_buf);
2519 		/*
2520 		 * SIOCGLIFCONF returns EINVAL if the buffer we passed in is
2521 		 * too small.  In this case go back and get the new if cnt.
2522 		 */
2523 		if (errno == EINVAL)
2524 			goto retry;
2525 
2526 		(void) close(s);
2527 		return (Z_ERR);
2528 	}
2529 	(void) close(s);
2530 
2531 	/* Get the name and address family for each interface. */
2532 	if_reqp = if_conf.lifc_req;
2533 	for (i = 0; i < (if_conf.lifc_len / sizeof (struct lifreq)); i++) {
2534 		struct net_if	**p;
2535 		struct lifreq	req;
2536 
2537 		if (strcmp(LOOPBACK_IF, if_reqp->lifr_name) == 0) {
2538 			if_reqp++;
2539 			continue;
2540 		}
2541 
2542 		if ((s = socket(SOCKET_AF(if_reqp->lifr_addr.ss_family),
2543 		    SOCK_DGRAM, 0)) == -1) {
2544 			res = Z_ERR;
2545 			break;
2546 		}
2547 
2548 		(void) strncpy(req.lifr_name, if_reqp->lifr_name,
2549 		    sizeof (req.lifr_name));
2550 		if (ioctl(s, SIOCGLIFADDR, &req) < 0) {
2551 			(void) close(s);
2552 			if_reqp++;
2553 			continue;
2554 		}
2555 
2556 		if ((p = (struct net_if **)realloc(local_ifs,
2557 		    sizeof (struct net_if *) * (cnt + 1))) == NULL) {
2558 			res = Z_ERR;
2559 			break;
2560 		}
2561 		local_ifs = p;
2562 
2563 		if ((local_ifs[cnt] = malloc(sizeof (struct net_if))) == NULL) {
2564 			res = Z_ERR;
2565 			break;
2566 		}
2567 
2568 		if ((local_ifs[cnt]->name = strdup(if_reqp->lifr_name))
2569 		    == NULL) {
2570 			free(local_ifs[cnt]);
2571 			res = Z_ERR;
2572 			break;
2573 		}
2574 		local_ifs[cnt]->af = req.lifr_addr.ss_family;
2575 		cnt++;
2576 
2577 		(void) close(s);
2578 		if_reqp++;
2579 	}
2580 
2581 	free(if_buf);
2582 
2583 	if (res != Z_OK) {
2584 		free_local_netifs(cnt, local_ifs);
2585 	} else {
2586 		*if_cnt = cnt;
2587 		*if_list = local_ifs;
2588 	}
2589 
2590 	return (res);
2591 }
2592 
2593 static char *
2594 af2str(int af)
2595 {
2596 	switch (af) {
2597 	case AF_INET:
2598 		return ("IPv4");
2599 	case AF_INET6:
2600 		return ("IPv6");
2601 	default:
2602 		return ("Unknown");
2603 	}
2604 }
2605 
2606 /*
2607  * Cross check the network interface name and address family with the
2608  * interfaces that are set up in the global zone so that we can print the
2609  * appropriate error message.
2610  */
2611 static void
2612 print_net_err(char *phys, char *addr, int af, char *msg)
2613 {
2614 	int		i;
2615 	int		local_if_cnt = 0;
2616 	struct net_if	**local_ifs = NULL;
2617 	boolean_t	found_if = B_FALSE;
2618 	boolean_t	found_af = B_FALSE;
2619 
2620 	if (get_local_netifs(&local_if_cnt, &local_ifs) != Z_OK) {
2621 		(void) fprintf(stderr,
2622 		    gettext("could not verify %s %s=%s %s=%s\n\t%s\n"),
2623 		    "net", "address", addr, "physical", phys, msg);
2624 		return;
2625 	}
2626 
2627 	for (i = 0; i < local_if_cnt; i++) {
2628 		if (strcmp(phys, local_ifs[i]->name) == 0) {
2629 			found_if = B_TRUE;
2630 			if (af == local_ifs[i]->af) {
2631 				found_af = B_TRUE;
2632 				break;
2633 			}
2634 		}
2635 	}
2636 
2637 	free_local_netifs(local_if_cnt, local_ifs);
2638 
2639 	if (!found_if) {
2640 		(void) fprintf(stderr,
2641 		    gettext("could not verify %s %s=%s\n\t"
2642 		    "network interface %s is not plumbed in the global zone\n"),
2643 		    "net", "physical", phys, phys);
2644 		return;
2645 	}
2646 
2647 	/*
2648 	 * Print this error if we were unable to find the address family
2649 	 * for this interface.  If the af variable is not initialized to
2650 	 * to something meaningful by the caller (not AF_UNSPEC) then we
2651 	 * also skip this message since it wouldn't be informative.
2652 	 */
2653 	if (!found_af && af != AF_UNSPEC) {
2654 		(void) fprintf(stderr,
2655 		    gettext("could not verify %s %s=%s %s=%s\n\tthe %s address "
2656 		    "family is not configured on this interface in the\n\t"
2657 		    "global zone\n"),
2658 		    "net", "address", addr, "physical", phys, af2str(af));
2659 		return;
2660 	}
2661 
2662 	(void) fprintf(stderr,
2663 	    gettext("could not verify %s %s=%s %s=%s\n\t%s\n"),
2664 	    "net", "address", addr, "physical", phys, msg);
2665 }
2666 
2667 static int
2668 verify_handle(int cmd_num, zone_dochandle_t handle)
2669 {
2670 	struct zone_nwiftab nwiftab;
2671 	int return_code = Z_OK;
2672 	int err;
2673 	boolean_t in_alt_root;
2674 
2675 	in_alt_root = zonecfg_in_alt_root();
2676 	if (in_alt_root)
2677 		goto no_net;
2678 
2679 	if ((err = zonecfg_setnwifent(handle)) != Z_OK) {
2680 		errno = err;
2681 		zperror(cmd_to_str(cmd_num), B_TRUE);
2682 		zonecfg_fini_handle(handle);
2683 		return (Z_ERR);
2684 	}
2685 	while (zonecfg_getnwifent(handle, &nwiftab) == Z_OK) {
2686 		struct lifreq lifr;
2687 		sa_family_t af = AF_UNSPEC;
2688 		int so, res;
2689 
2690 		/* skip any loopback interfaces */
2691 		if (strcmp(nwiftab.zone_nwif_physical, "lo0") == 0)
2692 			continue;
2693 		if ((res = zonecfg_valid_net_address(nwiftab.zone_nwif_address,
2694 		    &lifr)) != Z_OK) {
2695 			print_net_err(nwiftab.zone_nwif_physical,
2696 			    nwiftab.zone_nwif_address, af,
2697 			    zonecfg_strerror(res));
2698 			return_code = Z_ERR;
2699 			continue;
2700 		}
2701 		af = lifr.lifr_addr.ss_family;
2702 		(void) memset(&lifr, 0, sizeof (lifr));
2703 		(void) strlcpy(lifr.lifr_name, nwiftab.zone_nwif_physical,
2704 		    sizeof (lifr.lifr_name));
2705 		lifr.lifr_addr.ss_family = af;
2706 		if ((so = socket(af, SOCK_DGRAM, 0)) < 0) {
2707 			(void) fprintf(stderr, gettext("could not verify %s "
2708 			    "%s=%s %s=%s: could not get socket: %s\n"), "net",
2709 			    "address", nwiftab.zone_nwif_address, "physical",
2710 			    nwiftab.zone_nwif_physical, strerror(errno));
2711 			return_code = Z_ERR;
2712 			continue;
2713 		}
2714 		if (ioctl(so, SIOCGLIFFLAGS, &lifr) < 0) {
2715 			/*
2716 			 * The interface failed to come up.  We continue on
2717 			 * anyway for the sake of consistency: a zone is not
2718 			 * shut down if the interface fails any time after
2719 			 * boot, nor does the global zone fail to boot if an
2720 			 * interface fails.
2721 			 */
2722 			(void) fprintf(stderr,
2723 			    gettext("WARNING: skipping interface '%s' which "
2724 			    "may not be present/plumbed in the global zone.\n"),
2725 			    nwiftab.zone_nwif_physical);
2726 
2727 		}
2728 		(void) close(so);
2729 	}
2730 	(void) zonecfg_endnwifent(handle);
2731 no_net:
2732 
2733 	/* verify that lofs has not been excluded from the kernel */
2734 	if (!(cmd_num == CMD_DETACH || cmd_num == CMD_ATTACH ||
2735 	    cmd_num == CMD_MOVE || cmd_num == CMD_CLONE) &&
2736 	    modctl(MODLOAD, 1, "fs/lofs", NULL) != 0) {
2737 		if (errno == ENXIO)
2738 			(void) fprintf(stderr, gettext("could not verify "
2739 			    "lofs(7FS): possibly excluded in /etc/system\n"));
2740 		else
2741 			(void) fprintf(stderr, gettext("could not verify "
2742 			    "lofs(7FS): %s\n"), strerror(errno));
2743 		return_code = Z_ERR;
2744 	}
2745 
2746 	if (verify_filesystems(handle) != Z_OK)
2747 		return_code = Z_ERR;
2748 	if (verify_ipd(handle) != Z_OK)
2749 		return_code = Z_ERR;
2750 	if (!in_alt_root && verify_rctls(handle) != Z_OK)
2751 		return_code = Z_ERR;
2752 	if (!in_alt_root && verify_pool(handle) != Z_OK)
2753 		return_code = Z_ERR;
2754 	if (!in_alt_root && verify_brand(handle) != Z_OK)
2755 		return_code = Z_ERR;
2756 	if (!in_alt_root && verify_datasets(handle) != Z_OK)
2757 		return_code = Z_ERR;
2758 
2759 	/*
2760 	 * As the "mount" command is used for patching/upgrading of zones
2761 	 * or other maintenance processes, the zone's privilege set is not
2762 	 * checked in this case.  Instead, the default, safe set of
2763 	 * privileges will be used when this zone is created in the
2764 	 * kernel.
2765 	 */
2766 	if (!in_alt_root && cmd_num != CMD_MOUNT &&
2767 	    verify_limitpriv(handle) != Z_OK)
2768 		return_code = Z_ERR;
2769 
2770 	return (return_code);
2771 }
2772 
2773 static int
2774 verify_details(int cmd_num)
2775 {
2776 	zone_dochandle_t handle;
2777 	char zonepath[MAXPATHLEN], checkpath[MAXPATHLEN];
2778 	int return_code = Z_OK;
2779 	int err;
2780 
2781 	if ((handle = zonecfg_init_handle()) == NULL) {
2782 		zperror(cmd_to_str(cmd_num), B_TRUE);
2783 		return (Z_ERR);
2784 	}
2785 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
2786 		errno = err;
2787 		zperror(cmd_to_str(cmd_num), B_TRUE);
2788 		zonecfg_fini_handle(handle);
2789 		return (Z_ERR);
2790 	}
2791 	if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
2792 	    Z_OK) {
2793 		errno = err;
2794 		zperror(cmd_to_str(cmd_num), B_TRUE);
2795 		zonecfg_fini_handle(handle);
2796 		return (Z_ERR);
2797 	}
2798 	/*
2799 	 * zonecfg_get_zonepath() gets its data from the XML repository.
2800 	 * Verify this against the index file, which is checked first by
2801 	 * zone_get_zonepath().  If they don't match, bail out.
2802 	 */
2803 	if ((err = zone_get_zonepath(target_zone, checkpath,
2804 	    sizeof (checkpath))) != Z_OK) {
2805 		errno = err;
2806 		zperror2(target_zone, gettext("could not get zone path"));
2807 		return (Z_ERR);
2808 	}
2809 	if (strcmp(zonepath, checkpath) != 0) {
2810 		/*
2811 		 * TRANSLATION_NOTE
2812 		 * XML and zonepath are literals that should not be translated.
2813 		 */
2814 		(void) fprintf(stderr, gettext("The XML repository has "
2815 		    "zonepath '%s',\nbut the index file has zonepath '%s'.\n"
2816 		    "These must match, so fix the incorrect entry.\n"),
2817 		    zonepath, checkpath);
2818 		return (Z_ERR);
2819 	}
2820 	if (validate_zonepath(zonepath, cmd_num) != Z_OK) {
2821 		(void) fprintf(stderr, gettext("could not verify zonepath %s "
2822 		    "because of the above errors.\n"), zonepath);
2823 		return_code = Z_ERR;
2824 	}
2825 
2826 	if (verify_handle(cmd_num, handle) != Z_OK)
2827 		return_code = Z_ERR;
2828 
2829 	zonecfg_fini_handle(handle);
2830 	if (return_code == Z_ERR)
2831 		(void) fprintf(stderr,
2832 		    gettext("%s: zone %s failed to verify\n"),
2833 		    execname, target_zone);
2834 	return (return_code);
2835 }
2836 
2837 static int
2838 verify_func(int argc, char *argv[])
2839 {
2840 	int arg;
2841 
2842 	optind = 0;
2843 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2844 		switch (arg) {
2845 		case '?':
2846 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2847 			return (optopt == '?' ? Z_OK : Z_USAGE);
2848 		default:
2849 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2850 			return (Z_USAGE);
2851 		}
2852 	}
2853 	if (argc > optind) {
2854 		sub_usage(SHELP_VERIFY, CMD_VERIFY);
2855 		return (Z_USAGE);
2856 	}
2857 	if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE, B_FALSE)
2858 	    != Z_OK)
2859 		return (Z_ERR);
2860 	return (verify_details(CMD_VERIFY));
2861 }
2862 
2863 static int
2864 addopt(char *buf, int opt, char *optarg, size_t bufsize)
2865 {
2866 	char optstring[4];
2867 
2868 	if (opt > 0)
2869 		(void) sprintf(optstring, " -%c", opt);
2870 	else
2871 		(void) strcpy(optstring, " ");
2872 
2873 	if ((strlcat(buf, optstring, bufsize) > bufsize))
2874 		return (Z_ERR);
2875 	if ((optarg != NULL) && (strlcat(buf, optarg, bufsize) > bufsize))
2876 		return (Z_ERR);
2877 	return (Z_OK);
2878 }
2879 
2880 static int
2881 install_func(int argc, char *argv[])
2882 {
2883 	char cmdbuf[MAXPATHLEN];
2884 	int lockfd;
2885 	int arg, err, subproc_err;
2886 	char zonepath[MAXPATHLEN];
2887 	brand_handle_t bh = NULL;
2888 	int status;
2889 	boolean_t nodataset = B_FALSE;
2890 	char opts[128];
2891 
2892 	if (target_zone == NULL) {
2893 		sub_usage(SHELP_INSTALL, CMD_INSTALL);
2894 		return (Z_USAGE);
2895 	}
2896 
2897 	if (zonecfg_in_alt_root()) {
2898 		zerror(gettext("cannot install zone in alternate root"));
2899 		return (Z_ERR);
2900 	}
2901 
2902 	if ((err = zone_get_zonepath(target_zone, zonepath,
2903 	    sizeof (zonepath))) != Z_OK) {
2904 		errno = err;
2905 		zperror2(target_zone, gettext("could not get zone path"));
2906 		return (Z_ERR);
2907 	}
2908 
2909 	/* Fetch the install command from the brand configuration.  */
2910 	if ((bh = brand_open(target_brand)) == NULL) {
2911 		zerror(gettext("missing or invalid brand"));
2912 		return (Z_ERR);
2913 	}
2914 
2915 	(void) strcpy(cmdbuf, EXEC_PREFIX);
2916 	if (brand_get_install(bh, target_zone, zonepath, cmdbuf + EXEC_LEN,
2917 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL) != 0) {
2918 		zerror("invalid brand configuration: missing install resource");
2919 		brand_close(bh);
2920 		return (Z_ERR);
2921 	}
2922 
2923 	(void) strcpy(opts, "?x:");
2924 	if (!is_native_zone) {
2925 		/*
2926 		 * Fetch the list of recognized command-line options from
2927 		 * the brand configuration file.
2928 		 */
2929 		if (brand_get_installopts(bh, opts + strlen(opts),
2930 		    sizeof (opts) - strlen(opts)) != 0) {
2931 			zerror("invalid brand configuration: missing "
2932 			    "install options resource");
2933 			brand_close(bh);
2934 			return (Z_ERR);
2935 		}
2936 	}
2937 	brand_close(bh);
2938 
2939 	optind = 0;
2940 	while ((arg = getopt(argc, argv, opts)) != EOF) {
2941 		switch (arg) {
2942 		case '?':
2943 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
2944 			return (optopt == '?' ? Z_OK : Z_USAGE);
2945 		case 'x':
2946 			if (strcmp(optarg, "nodataset") != 0) {
2947 				sub_usage(SHELP_INSTALL, CMD_INSTALL);
2948 				return (Z_USAGE);
2949 			}
2950 			nodataset = B_TRUE;
2951 			break;
2952 		default:
2953 			if (is_native_zone) {
2954 				sub_usage(SHELP_INSTALL, CMD_INSTALL);
2955 				return (Z_USAGE);
2956 			}
2957 
2958 			/*
2959 			 * This option isn't for zoneadm, so append it to
2960 			 * the command line passed to the brand-specific
2961 			 * install routine.
2962 			 */
2963 			if (addopt(cmdbuf, optopt, optarg,
2964 			    sizeof (cmdbuf)) != Z_OK) {
2965 				zerror("Install command line too long");
2966 				return (Z_ERR);
2967 			}
2968 			break;
2969 		}
2970 	}
2971 
2972 	if (!is_native_zone) {
2973 		for (; optind < argc; optind++) {
2974 			if (addopt(cmdbuf, 0, argv[optind],
2975 			    sizeof (cmdbuf)) != Z_OK) {
2976 				zerror("Install command line too long");
2977 				return (Z_ERR);
2978 			}
2979 		}
2980 	}
2981 
2982 	if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE, B_FALSE)
2983 	    != Z_OK)
2984 		return (Z_ERR);
2985 	if (verify_details(CMD_INSTALL) != Z_OK)
2986 		return (Z_ERR);
2987 
2988 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
2989 		zerror(gettext("another %s may have an operation in progress."),
2990 		    "zoneadm");
2991 		return (Z_ERR);
2992 	}
2993 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
2994 	if (err != Z_OK) {
2995 		errno = err;
2996 		zperror2(target_zone, gettext("could not set state"));
2997 		goto done;
2998 	}
2999 
3000 	if (!nodataset)
3001 		create_zfs_zonepath(zonepath);
3002 
3003 	/*
3004 	 * According to the Application Packaging Developer's Guide, a
3005 	 * "checkinstall" script when included in a package is executed as
3006 	 * the user "install", if such a user exists, or by the user
3007 	 * "nobody".  In order to support this dubious behavior, the path
3008 	 * to the zone being constructed is opened up during the life of
3009 	 * the command laying down the zone's root file system.  Once this
3010 	 * has completed, regardless of whether it was successful, the
3011 	 * path to the zone is again restricted.
3012 	 */
3013 	if (chmod(zonepath, DEFAULT_DIR_MODE) != 0) {
3014 		zperror(zonepath, B_FALSE);
3015 		err = Z_ERR;
3016 		goto done;
3017 	}
3018 
3019 	if (is_native_zone)
3020 		status = do_subproc(cmdbuf);
3021 	else
3022 		status = do_subproc_interactive(cmdbuf);
3023 
3024 	if (chmod(zonepath, S_IRWXU) != 0) {
3025 		zperror(zonepath, B_FALSE);
3026 		err = Z_ERR;
3027 		goto done;
3028 	}
3029 	if ((subproc_err =
3030 	    subproc_status(gettext("brand-specific installation"), status,
3031 	    B_FALSE)) != ZONE_SUBPROC_OK) {
3032 		err = Z_ERR;
3033 		goto done;
3034 	}
3035 
3036 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
3037 		errno = err;
3038 		zperror2(target_zone, gettext("could not set state"));
3039 		goto done;
3040 	}
3041 
3042 done:
3043 	/*
3044 	 * If the install script exited with ZONE_SUBPROC_USAGE or
3045 	 * ZONE_SUBPROC_NOTCOMPLETE, try to clean up the zone and leave the
3046 	 * zone in the CONFIGURED state so that another install can be
3047 	 * attempted without requiring an uninstall first.
3048 	 */
3049 	if ((subproc_err == ZONE_SUBPROC_USAGE) ||
3050 	    (subproc_err == ZONE_SUBPROC_NOTCOMPLETE)) {
3051 		if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
3052 			errno = err;
3053 			zperror2(target_zone,
3054 			    gettext("cleaning up zonepath failed"));
3055 		} else if ((err = zone_set_state(target_zone,
3056 		    ZONE_STATE_CONFIGURED)) != Z_OK) {
3057 			errno = err;
3058 			zperror2(target_zone, gettext("could not set state"));
3059 		}
3060 	}
3061 
3062 	release_lock_file(lockfd);
3063 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3064 }
3065 
3066 /*
3067  * Check that the inherited pkg dirs are the same for the clone and its source.
3068  * The easiest way to do that is check that the list of ipds is the same
3069  * by matching each one against the other.  This algorithm should be fine since
3070  * the list of ipds should not be that long.
3071  */
3072 static int
3073 valid_ipd_clone(zone_dochandle_t s_handle, char *source_zone,
3074 	zone_dochandle_t t_handle, char *target_zone)
3075 {
3076 	int err;
3077 	int res = Z_OK;
3078 	int s_cnt = 0;
3079 	int t_cnt = 0;
3080 	struct zone_fstab s_fstab;
3081 	struct zone_fstab t_fstab;
3082 
3083 	/*
3084 	 * First check the source of the clone against the target.
3085 	 */
3086 	if ((err = zonecfg_setipdent(s_handle)) != Z_OK) {
3087 		errno = err;
3088 		zperror2(source_zone, gettext("could not enumerate "
3089 		    "inherit-pkg-dirs"));
3090 		return (Z_ERR);
3091 	}
3092 
3093 	while (zonecfg_getipdent(s_handle, &s_fstab) == Z_OK) {
3094 		boolean_t match = B_FALSE;
3095 
3096 		s_cnt++;
3097 
3098 		if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
3099 			errno = err;
3100 			zperror2(target_zone, gettext("could not enumerate "
3101 			    "inherit-pkg-dirs"));
3102 			(void) zonecfg_endipdent(s_handle);
3103 			return (Z_ERR);
3104 		}
3105 
3106 		while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK) {
3107 			if (strcmp(s_fstab.zone_fs_dir, t_fstab.zone_fs_dir)
3108 			    == 0) {
3109 				match = B_TRUE;
3110 				break;
3111 			}
3112 		}
3113 		(void) zonecfg_endipdent(t_handle);
3114 
3115 		if (!match) {
3116 			(void) fprintf(stderr, gettext("inherit-pkg-dir "
3117 			    "'%s' is not configured in zone %s.\n"),
3118 			    s_fstab.zone_fs_dir, target_zone);
3119 			res = Z_ERR;
3120 		}
3121 	}
3122 
3123 	(void) zonecfg_endipdent(s_handle);
3124 
3125 	/* skip the next check if we already have errors */
3126 	if (res == Z_ERR)
3127 		return (res);
3128 
3129 	/*
3130 	 * Now check the number of ipds in the target so we can verify
3131 	 * that the source is not a subset of the target.
3132 	 */
3133 	if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
3134 		errno = err;
3135 		zperror2(target_zone, gettext("could not enumerate "
3136 		    "inherit-pkg-dirs"));
3137 		return (Z_ERR);
3138 	}
3139 
3140 	while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK)
3141 		t_cnt++;
3142 
3143 	(void) zonecfg_endipdent(t_handle);
3144 
3145 	if (t_cnt != s_cnt) {
3146 		(void) fprintf(stderr, gettext("Zone %s is configured "
3147 		    "with inherit-pkg-dirs that are not configured in zone "
3148 		    "%s.\n"), target_zone, source_zone);
3149 		res = Z_ERR;
3150 	}
3151 
3152 	return (res);
3153 }
3154 
3155 static void
3156 warn_dev_match(zone_dochandle_t s_handle, char *source_zone,
3157 	zone_dochandle_t t_handle, char *target_zone)
3158 {
3159 	int err;
3160 	struct zone_devtab s_devtab;
3161 	struct zone_devtab t_devtab;
3162 
3163 	if ((err = zonecfg_setdevent(t_handle)) != Z_OK) {
3164 		errno = err;
3165 		zperror2(target_zone, gettext("could not enumerate devices"));
3166 		return;
3167 	}
3168 
3169 	while (zonecfg_getdevent(t_handle, &t_devtab) == Z_OK) {
3170 		if ((err = zonecfg_setdevent(s_handle)) != Z_OK) {
3171 			errno = err;
3172 			zperror2(source_zone,
3173 			    gettext("could not enumerate devices"));
3174 			(void) zonecfg_enddevent(t_handle);
3175 			return;
3176 		}
3177 
3178 		while (zonecfg_getdevent(s_handle, &s_devtab) == Z_OK) {
3179 			/*
3180 			 * Use fnmatch to catch the case where wildcards
3181 			 * were used in one zone and the other has an
3182 			 * explicit entry (e.g. /dev/dsk/c0t0d0s6 vs.
3183 			 * /dev/\*dsk/c0t0d0s6).
3184 			 */
3185 			if (fnmatch(t_devtab.zone_dev_match,
3186 			    s_devtab.zone_dev_match, FNM_PATHNAME) == 0 ||
3187 			    fnmatch(s_devtab.zone_dev_match,
3188 			    t_devtab.zone_dev_match, FNM_PATHNAME) == 0) {
3189 				(void) fprintf(stderr,
3190 				    gettext("WARNING: device '%s' "
3191 				    "is configured in both zones.\n"),
3192 				    t_devtab.zone_dev_match);
3193 				break;
3194 			}
3195 		}
3196 		(void) zonecfg_enddevent(s_handle);
3197 	}
3198 
3199 	(void) zonecfg_enddevent(t_handle);
3200 }
3201 
3202 /*
3203  * Check if the specified mount option (opt) is contained within the
3204  * options string.
3205  */
3206 static boolean_t
3207 opt_match(char *opt, char *options)
3208 {
3209 	char *p;
3210 	char *lastp;
3211 
3212 	if ((p = strtok_r(options, ",", &lastp)) != NULL) {
3213 		if (strcmp(p, opt) == 0)
3214 			return (B_TRUE);
3215 		while ((p = strtok_r(NULL, ",", &lastp)) != NULL) {
3216 			if (strcmp(p, opt) == 0)
3217 				return (B_TRUE);
3218 		}
3219 	}
3220 
3221 	return (B_FALSE);
3222 }
3223 
3224 #define	RW_LOFS	"WARNING: read-write lofs file system on '%s' is configured " \
3225 	"in both zones.\n"
3226 
3227 static void
3228 print_fs_warnings(struct zone_fstab *s_fstab, struct zone_fstab *t_fstab)
3229 {
3230 	/*
3231 	 * It is ok to have shared lofs mounted fs but we want to warn if
3232 	 * either is rw since this will effect the other zone.
3233 	 */
3234 	if (strcmp(t_fstab->zone_fs_type, "lofs") == 0) {
3235 		zone_fsopt_t *optp;
3236 
3237 		/* The default is rw so no options means rw */
3238 		if (t_fstab->zone_fs_options == NULL ||
3239 		    s_fstab->zone_fs_options == NULL) {
3240 			(void) fprintf(stderr, gettext(RW_LOFS),
3241 			    t_fstab->zone_fs_special);
3242 			return;
3243 		}
3244 
3245 		for (optp = s_fstab->zone_fs_options; optp != NULL;
3246 		    optp = optp->zone_fsopt_next) {
3247 			if (opt_match("rw", optp->zone_fsopt_opt)) {
3248 				(void) fprintf(stderr, gettext(RW_LOFS),
3249 				    s_fstab->zone_fs_special);
3250 				return;
3251 			}
3252 		}
3253 
3254 		for (optp = t_fstab->zone_fs_options; optp != NULL;
3255 		    optp = optp->zone_fsopt_next) {
3256 			if (opt_match("rw", optp->zone_fsopt_opt)) {
3257 				(void) fprintf(stderr, gettext(RW_LOFS),
3258 				    t_fstab->zone_fs_special);
3259 				return;
3260 			}
3261 		}
3262 
3263 		return;
3264 	}
3265 
3266 	/*
3267 	 * TRANSLATION_NOTE
3268 	 * The first variable is the file system type and the second is
3269 	 * the file system special device.  For example,
3270 	 * WARNING: ufs file system on '/dev/dsk/c0t0d0s0' ...
3271 	 */
3272 	(void) fprintf(stderr, gettext("WARNING: %s file system on '%s' "
3273 	    "is configured in both zones.\n"), t_fstab->zone_fs_type,
3274 	    t_fstab->zone_fs_special);
3275 }
3276 
3277 static void
3278 warn_fs_match(zone_dochandle_t s_handle, char *source_zone,
3279 	zone_dochandle_t t_handle, char *target_zone)
3280 {
3281 	int err;
3282 	struct zone_fstab s_fstab;
3283 	struct zone_fstab t_fstab;
3284 
3285 	if ((err = zonecfg_setfsent(t_handle)) != Z_OK) {
3286 		errno = err;
3287 		zperror2(target_zone,
3288 		    gettext("could not enumerate file systems"));
3289 		return;
3290 	}
3291 
3292 	while (zonecfg_getfsent(t_handle, &t_fstab) == Z_OK) {
3293 		if ((err = zonecfg_setfsent(s_handle)) != Z_OK) {
3294 			errno = err;
3295 			zperror2(source_zone,
3296 			    gettext("could not enumerate file systems"));
3297 			(void) zonecfg_endfsent(t_handle);
3298 			return;
3299 		}
3300 
3301 		while (zonecfg_getfsent(s_handle, &s_fstab) == Z_OK) {
3302 			if (strcmp(t_fstab.zone_fs_special,
3303 			    s_fstab.zone_fs_special) == 0) {
3304 				print_fs_warnings(&s_fstab, &t_fstab);
3305 				break;
3306 			}
3307 		}
3308 		(void) zonecfg_endfsent(s_handle);
3309 	}
3310 
3311 	(void) zonecfg_endfsent(t_handle);
3312 }
3313 
3314 /*
3315  * We don't catch the case where you used the same IP address but
3316  * it is not an exact string match.  For example, 192.9.0.128 vs. 192.09.0.128.
3317  * However, we're not going to worry about that but we will check for
3318  * a possible netmask on one of the addresses (e.g. 10.0.0.1 and 10.0.0.1/24)
3319  * and handle that case as a match.
3320  */
3321 static void
3322 warn_ip_match(zone_dochandle_t s_handle, char *source_zone,
3323 	zone_dochandle_t t_handle, char *target_zone)
3324 {
3325 	int err;
3326 	struct zone_nwiftab s_nwiftab;
3327 	struct zone_nwiftab t_nwiftab;
3328 
3329 	if ((err = zonecfg_setnwifent(t_handle)) != Z_OK) {
3330 		errno = err;
3331 		zperror2(target_zone,
3332 		    gettext("could not enumerate network interfaces"));
3333 		return;
3334 	}
3335 
3336 	while (zonecfg_getnwifent(t_handle, &t_nwiftab) == Z_OK) {
3337 		char *p;
3338 
3339 		/* remove an (optional) netmask from the address */
3340 		if ((p = strchr(t_nwiftab.zone_nwif_address, '/')) != NULL)
3341 			*p = '\0';
3342 
3343 		if ((err = zonecfg_setnwifent(s_handle)) != Z_OK) {
3344 			errno = err;
3345 			zperror2(source_zone,
3346 			    gettext("could not enumerate network interfaces"));
3347 			(void) zonecfg_endnwifent(t_handle);
3348 			return;
3349 		}
3350 
3351 		while (zonecfg_getnwifent(s_handle, &s_nwiftab) == Z_OK) {
3352 			/* remove an (optional) netmask from the address */
3353 			if ((p = strchr(s_nwiftab.zone_nwif_address, '/'))
3354 			    != NULL)
3355 				*p = '\0';
3356 
3357 			if (strcmp(t_nwiftab.zone_nwif_address,
3358 			    s_nwiftab.zone_nwif_address) == 0) {
3359 				(void) fprintf(stderr,
3360 				    gettext("WARNING: network address '%s' "
3361 				    "is configured in both zones.\n"),
3362 				    t_nwiftab.zone_nwif_address);
3363 				break;
3364 			}
3365 		}
3366 		(void) zonecfg_endnwifent(s_handle);
3367 	}
3368 
3369 	(void) zonecfg_endnwifent(t_handle);
3370 }
3371 
3372 static void
3373 warn_dataset_match(zone_dochandle_t s_handle, char *source,
3374 	zone_dochandle_t t_handle, char *target)
3375 {
3376 	int err;
3377 	struct zone_dstab s_dstab;
3378 	struct zone_dstab t_dstab;
3379 
3380 	if ((err = zonecfg_setdsent(t_handle)) != Z_OK) {
3381 		errno = err;
3382 		zperror2(target, gettext("could not enumerate datasets"));
3383 		return;
3384 	}
3385 
3386 	while (zonecfg_getdsent(t_handle, &t_dstab) == Z_OK) {
3387 		if ((err = zonecfg_setdsent(s_handle)) != Z_OK) {
3388 			errno = err;
3389 			zperror2(source,
3390 			    gettext("could not enumerate datasets"));
3391 			(void) zonecfg_enddsent(t_handle);
3392 			return;
3393 		}
3394 
3395 		while (zonecfg_getdsent(s_handle, &s_dstab) == Z_OK) {
3396 			if (strcmp(t_dstab.zone_dataset_name,
3397 			    s_dstab.zone_dataset_name) == 0) {
3398 				target_zone = source;
3399 				zerror(gettext("WARNING: dataset '%s' "
3400 				    "is configured in both zones.\n"),
3401 				    t_dstab.zone_dataset_name);
3402 				break;
3403 			}
3404 		}
3405 		(void) zonecfg_enddsent(s_handle);
3406 	}
3407 
3408 	(void) zonecfg_enddsent(t_handle);
3409 }
3410 
3411 /*
3412  * Check that the clone and its source have the same brand type.
3413  */
3414 static int
3415 valid_brand_clone(char *source_zone, char *target_zone)
3416 {
3417 	brand_handle_t bh;
3418 	char source_brand[MAXNAMELEN];
3419 
3420 	if ((zone_get_brand(source_zone, source_brand,
3421 	    sizeof (source_brand))) != Z_OK) {
3422 		(void) fprintf(stderr, "%s: zone '%s': %s\n",
3423 		    execname, source_zone, gettext("missing or invalid brand"));
3424 		return (Z_ERR);
3425 	}
3426 
3427 	if (strcmp(source_brand, target_brand) != NULL) {
3428 		(void) fprintf(stderr,
3429 		    gettext("%s: Zones '%s' and '%s' have different brand "
3430 		    "types.\n"), execname, source_zone, target_zone);
3431 		return (Z_ERR);
3432 	}
3433 
3434 	if ((bh = brand_open(target_brand)) == NULL) {
3435 		zerror(gettext("missing or invalid brand"));
3436 		return (Z_ERR);
3437 	}
3438 	brand_close(bh);
3439 	return (Z_OK);
3440 }
3441 
3442 static int
3443 validate_clone(char *source_zone, char *target_zone)
3444 {
3445 	int err = Z_OK;
3446 	zone_dochandle_t s_handle;
3447 	zone_dochandle_t t_handle;
3448 
3449 	if ((t_handle = zonecfg_init_handle()) == NULL) {
3450 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3451 		return (Z_ERR);
3452 	}
3453 	if ((err = zonecfg_get_handle(target_zone, t_handle)) != Z_OK) {
3454 		errno = err;
3455 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3456 		zonecfg_fini_handle(t_handle);
3457 		return (Z_ERR);
3458 	}
3459 
3460 	if ((s_handle = zonecfg_init_handle()) == NULL) {
3461 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3462 		zonecfg_fini_handle(t_handle);
3463 		return (Z_ERR);
3464 	}
3465 	if ((err = zonecfg_get_handle(source_zone, s_handle)) != Z_OK) {
3466 		errno = err;
3467 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3468 		goto done;
3469 	}
3470 
3471 	/* verify new zone has same brand type */
3472 	err = valid_brand_clone(source_zone, target_zone);
3473 	if (err != Z_OK)
3474 		goto done;
3475 
3476 	/* verify new zone has same inherit-pkg-dirs */
3477 	err = valid_ipd_clone(s_handle, source_zone, t_handle, target_zone);
3478 
3479 	/* warn about imported fs's which are the same */
3480 	warn_fs_match(s_handle, source_zone, t_handle, target_zone);
3481 
3482 	/* warn about imported IP addresses which are the same */
3483 	warn_ip_match(s_handle, source_zone, t_handle, target_zone);
3484 
3485 	/* warn about imported devices which are the same */
3486 	warn_dev_match(s_handle, source_zone, t_handle, target_zone);
3487 
3488 	/* warn about imported datasets which are the same */
3489 	warn_dataset_match(s_handle, source_zone, t_handle, target_zone);
3490 
3491 done:
3492 	zonecfg_fini_handle(t_handle);
3493 	zonecfg_fini_handle(s_handle);
3494 
3495 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3496 }
3497 
3498 static int
3499 copy_zone(char *src, char *dst)
3500 {
3501 	boolean_t out_null = B_FALSE;
3502 	int status;
3503 	char *outfile;
3504 	char cmdbuf[MAXPATHLEN * 2 + 128];
3505 
3506 	if ((outfile = tempnam("/var/log", "zone")) == NULL) {
3507 		outfile = "/dev/null";
3508 		out_null = B_TRUE;
3509 	}
3510 
3511 	/*
3512 	 * Use find to get the list of files to copy.  We need to skip
3513 	 * files of type "socket" since cpio can't handle those but that
3514 	 * should be ok since the app will recreate the socket when it runs.
3515 	 * We also need to filter out anything under the .zfs subdir.  Since
3516 	 * find is running depth-first, we need the extra egrep to filter .zfs.
3517 	 */
3518 	(void) snprintf(cmdbuf, sizeof (cmdbuf),
3519 	    "cd %s && /usr/bin/find . -type s -prune -o -depth -print | "
3520 	    "/usr/bin/egrep -v '^\\./\\.zfs$|^\\./\\.zfs/' | "
3521 	    "/usr/bin/cpio -pdmuP@ %s > %s 2>&1",
3522 	    src, dst, outfile);
3523 
3524 	status = do_subproc(cmdbuf);
3525 
3526 	if (subproc_status("copy", status, B_TRUE) != ZONE_SUBPROC_OK) {
3527 		if (!out_null)
3528 			(void) fprintf(stderr, gettext("\nThe copy failed.\n"
3529 			    "More information can be found in %s\n"), outfile);
3530 		return (Z_ERR);
3531 	}
3532 
3533 	if (!out_null)
3534 		(void) unlink(outfile);
3535 
3536 	return (Z_OK);
3537 }
3538 
3539 static int
3540 zone_postclone(char *zonepath)
3541 {
3542 	char cmdbuf[MAXPATHLEN];
3543 	int status;
3544 	brand_handle_t bh;
3545 	int err = Z_OK;
3546 
3547 	/*
3548 	 * Fetch the post-clone command, if any, from the brand
3549 	 * configuration.
3550 	 */
3551 	if ((bh = brand_open(target_brand)) == NULL) {
3552 		zerror(gettext("missing or invalid brand"));
3553 		return (Z_ERR);
3554 	}
3555 	(void) strcpy(cmdbuf, EXEC_PREFIX);
3556 	err = brand_get_postclone(bh, target_zone, zonepath, cmdbuf + EXEC_LEN,
3557 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL);
3558 	brand_close(bh);
3559 
3560 	if (err == 0 && strlen(cmdbuf) > EXEC_LEN) {
3561 		status = do_subproc(cmdbuf);
3562 		if ((err = subproc_status("postclone", status, B_FALSE))
3563 		    != ZONE_SUBPROC_OK) {
3564 			zerror(gettext("post-clone configuration failed."));
3565 			err = Z_ERR;
3566 		}
3567 	}
3568 
3569 	return (err);
3570 }
3571 
3572 /* ARGSUSED */
3573 static int
3574 zfm_print(const char *p, void *r) {
3575 	zerror("  %s\n", p);
3576 	return (0);
3577 }
3578 
3579 int
3580 clone_copy(char *source_zonepath, char *zonepath)
3581 {
3582 	int err;
3583 
3584 	/* Don't clone the zone if anything is still mounted there */
3585 	if (zonecfg_find_mounts(source_zonepath, NULL, NULL)) {
3586 		zerror(gettext("These file systems are mounted on "
3587 		    "subdirectories of %s.\n"), source_zonepath);
3588 		(void) zonecfg_find_mounts(source_zonepath, zfm_print, NULL);
3589 		return (Z_ERR);
3590 	}
3591 
3592 	/*
3593 	 * Attempt to create a ZFS fs for the zonepath.  As usual, we don't
3594 	 * care if this works or not since we always have the default behavior
3595 	 * of a simple directory for the zonepath.
3596 	 */
3597 	create_zfs_zonepath(zonepath);
3598 
3599 	(void) printf(gettext("Copying %s..."), source_zonepath);
3600 	(void) fflush(stdout);
3601 
3602 	err = copy_zone(source_zonepath, zonepath);
3603 
3604 	(void) printf("\n");
3605 
3606 	return (err);
3607 }
3608 
3609 static int
3610 clone_func(int argc, char *argv[])
3611 {
3612 	char *source_zone = NULL;
3613 	int lockfd;
3614 	int err, arg;
3615 	char zonepath[MAXPATHLEN];
3616 	char source_zonepath[MAXPATHLEN];
3617 	zone_state_t state;
3618 	zone_entry_t *zent;
3619 	char *method = NULL;
3620 	char *snapshot = NULL;
3621 
3622 	if (zonecfg_in_alt_root()) {
3623 		zerror(gettext("cannot clone zone in alternate root"));
3624 		return (Z_ERR);
3625 	}
3626 
3627 	optind = 0;
3628 	if ((arg = getopt(argc, argv, "?m:s:")) != EOF) {
3629 		switch (arg) {
3630 		case '?':
3631 			sub_usage(SHELP_CLONE, CMD_CLONE);
3632 			return (optopt == '?' ? Z_OK : Z_USAGE);
3633 		case 'm':
3634 			method = optarg;
3635 			break;
3636 		case 's':
3637 			snapshot = optarg;
3638 			break;
3639 		default:
3640 			sub_usage(SHELP_CLONE, CMD_CLONE);
3641 			return (Z_USAGE);
3642 		}
3643 	}
3644 	if (argc != (optind + 1) ||
3645 	    (method != NULL && strcmp(method, "copy") != 0)) {
3646 		sub_usage(SHELP_CLONE, CMD_CLONE);
3647 		return (Z_USAGE);
3648 	}
3649 	source_zone = argv[optind];
3650 	if (sanity_check(target_zone, CMD_CLONE, B_FALSE, B_TRUE, B_FALSE)
3651 	    != Z_OK)
3652 		return (Z_ERR);
3653 	if (verify_details(CMD_CLONE) != Z_OK)
3654 		return (Z_ERR);
3655 
3656 	/*
3657 	 * We also need to do some extra validation on the source zone.
3658 	 */
3659 	if (strcmp(source_zone, GLOBAL_ZONENAME) == 0) {
3660 		zerror(gettext("%s operation is invalid for the global zone."),
3661 		    cmd_to_str(CMD_CLONE));
3662 		return (Z_ERR);
3663 	}
3664 
3665 	if (strncmp(source_zone, "SUNW", 4) == 0) {
3666 		zerror(gettext("%s operation is invalid for zones starting "
3667 		    "with SUNW."), cmd_to_str(CMD_CLONE));
3668 		return (Z_ERR);
3669 	}
3670 
3671 	zent = lookup_running_zone(source_zone);
3672 	if (zent != NULL) {
3673 		/* check whether the zone is ready or running */
3674 		if ((err = zone_get_state(zent->zname, &zent->zstate_num))
3675 		    != Z_OK) {
3676 			errno = err;
3677 			zperror2(zent->zname, gettext("could not get state"));
3678 			/* can't tell, so hedge */
3679 			zent->zstate_str = "ready/running";
3680 		} else {
3681 			zent->zstate_str = zone_state_str(zent->zstate_num);
3682 		}
3683 		zerror(gettext("%s operation is invalid for %s zones."),
3684 		    cmd_to_str(CMD_CLONE), zent->zstate_str);
3685 		return (Z_ERR);
3686 	}
3687 
3688 	if ((err = zone_get_state(source_zone, &state)) != Z_OK) {
3689 		errno = err;
3690 		zperror2(source_zone, gettext("could not get state"));
3691 		return (Z_ERR);
3692 	}
3693 	if (state != ZONE_STATE_INSTALLED) {
3694 		(void) fprintf(stderr,
3695 		    gettext("%s: zone %s is %s; %s is required.\n"),
3696 		    execname, source_zone, zone_state_str(state),
3697 		    zone_state_str(ZONE_STATE_INSTALLED));
3698 		return (Z_ERR);
3699 	}
3700 
3701 	/*
3702 	 * The source zone checks out ok, continue with the clone.
3703 	 */
3704 
3705 	if (validate_clone(source_zone, target_zone) != Z_OK)
3706 		return (Z_ERR);
3707 
3708 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
3709 		zerror(gettext("another %s may have an operation in progress."),
3710 		    "zoneadm");
3711 		return (Z_ERR);
3712 	}
3713 
3714 	if ((err = zone_get_zonepath(source_zone, source_zonepath,
3715 	    sizeof (source_zonepath))) != Z_OK) {
3716 		errno = err;
3717 		zperror2(source_zone, gettext("could not get zone path"));
3718 		goto done;
3719 	}
3720 
3721 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3722 	    != Z_OK) {
3723 		errno = err;
3724 		zperror2(target_zone, gettext("could not get zone path"));
3725 		goto done;
3726 	}
3727 
3728 	if ((err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE))
3729 	    != Z_OK) {
3730 		errno = err;
3731 		zperror2(target_zone, gettext("could not set state"));
3732 		goto done;
3733 	}
3734 
3735 	if (snapshot != NULL) {
3736 		err = clone_snapshot_zfs(snapshot, zonepath);
3737 	} else {
3738 		/*
3739 		 * We always copy the clone unless the source is ZFS and a
3740 		 * ZFS clone worked.  We fallback to copying if the ZFS clone
3741 		 * fails for some reason.
3742 		 */
3743 		err = Z_ERR;
3744 		if (method == NULL && is_zonepath_zfs(source_zonepath))
3745 			err = clone_zfs(source_zone, source_zonepath, zonepath);
3746 
3747 		if (err != Z_OK)
3748 			err = clone_copy(source_zonepath, zonepath);
3749 	}
3750 
3751 	/*
3752 	 * Trusted Extensions requires that cloned zones use the same sysid
3753 	 * configuration, so it is not appropriate to perform any
3754 	 * post-clone reconfiguration.
3755 	 */
3756 	if ((err == Z_OK) && !is_system_labeled())
3757 		err = zone_postclone(zonepath);
3758 
3759 done:
3760 	/*
3761 	 * If everything went well, we mark the zone as installed.
3762 	 */
3763 	if (err == Z_OK) {
3764 		err = zone_set_state(target_zone, ZONE_STATE_INSTALLED);
3765 		if (err != Z_OK) {
3766 			errno = err;
3767 			zperror2(target_zone, gettext("could not set state"));
3768 		}
3769 	}
3770 	release_lock_file(lockfd);
3771 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3772 }
3773 
3774 /*
3775  * Used when removing a zonepath after uninstalling or cleaning up after
3776  * the move subcommand.  This handles a zonepath that has non-standard
3777  * contents so that we will only cleanup the stuff we know about and leave
3778  * any user data alone.
3779  *
3780  * If the "all" parameter is true then we should remove the whole zonepath
3781  * even if it has non-standard files/directories in it.  This can be used when
3782  * we need to cleanup after moving the zonepath across file systems.
3783  *
3784  * We "exec" the RMCOMMAND so that the returned status is that of RMCOMMAND
3785  * and not the shell.
3786  */
3787 static int
3788 cleanup_zonepath(char *zonepath, boolean_t all)
3789 {
3790 	int		status;
3791 	int		i;
3792 	boolean_t	non_std = B_FALSE;
3793 	struct dirent	*dp;
3794 	DIR		*dirp;
3795 	char		*std_entries[] = {"dev", "lu", "root", NULL};
3796 			/* (MAXPATHLEN * 3) is for the 3 std_entries dirs */
3797 	char		cmdbuf[sizeof (RMCOMMAND) + (MAXPATHLEN * 3) + 64];
3798 
3799 	/*
3800 	 * We shouldn't need these checks but lets be paranoid since we
3801 	 * could blow away the whole system here if we got the wrong zonepath.
3802 	 */
3803 	if (*zonepath == NULL || strcmp(zonepath, "/") == 0) {
3804 		(void) fprintf(stderr, "invalid zonepath '%s'\n", zonepath);
3805 		return (Z_INVAL);
3806 	}
3807 
3808 	/*
3809 	 * If the dirpath is already gone (maybe it was manually removed) then
3810 	 * we just return Z_OK so that the cleanup is successful.
3811 	 */
3812 	if ((dirp = opendir(zonepath)) == NULL)
3813 		return (Z_OK);
3814 
3815 	/*
3816 	 * Look through the zonepath directory to see if there are any
3817 	 * non-standard files/dirs.  Also skip .zfs since that might be
3818 	 * there but we'll handle ZFS file systems as a special case.
3819 	 */
3820 	while ((dp = readdir(dirp)) != NULL) {
3821 		if (strcmp(dp->d_name, ".") == 0 ||
3822 		    strcmp(dp->d_name, "..") == 0 ||
3823 		    strcmp(dp->d_name, ".zfs") == 0)
3824 			continue;
3825 
3826 		for (i = 0; std_entries[i] != NULL; i++)
3827 			if (strcmp(dp->d_name, std_entries[i]) == 0)
3828 				break;
3829 
3830 		if (std_entries[i] == NULL)
3831 			non_std = B_TRUE;
3832 	}
3833 	(void) closedir(dirp);
3834 
3835 	if (!all && non_std) {
3836 		/*
3837 		 * There are extra, non-standard directories/files in the
3838 		 * zonepath so we don't want to remove the zonepath.  We
3839 		 * just want to remove the standard directories and leave
3840 		 * the user data alone.
3841 		 */
3842 		(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND);
3843 
3844 		for (i = 0; std_entries[i] != NULL; i++) {
3845 			char tmpbuf[MAXPATHLEN];
3846 
3847 			if (snprintf(tmpbuf, sizeof (tmpbuf), " %s/%s",
3848 			    zonepath, std_entries[i]) >= sizeof (tmpbuf) ||
3849 			    strlcat(cmdbuf, tmpbuf, sizeof (cmdbuf)) >=
3850 			    sizeof (cmdbuf)) {
3851 				(void) fprintf(stderr,
3852 				    gettext("path is too long\n"));
3853 				return (Z_INVAL);
3854 			}
3855 		}
3856 
3857 		status = do_subproc(cmdbuf);
3858 
3859 		(void) fprintf(stderr, gettext("WARNING: Unable to completely "
3860 		    "remove %s\nbecause it contains additional user data.  "
3861 		    "Only the standard directory\nentries have been "
3862 		    "removed.\n"),
3863 		    zonepath);
3864 
3865 		return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
3866 		    ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
3867 	}
3868 
3869 	/*
3870 	 * There is nothing unexpected in the zonepath, try to get rid of the
3871 	 * whole zonepath directory.
3872 	 *
3873 	 * If the zonepath is its own zfs file system, try to destroy the
3874 	 * file system.  If that fails for some reason (e.g. it has clones)
3875 	 * then we'll just remove the contents of the zonepath.
3876 	 */
3877 	if (is_zonepath_zfs(zonepath)) {
3878 		if (destroy_zfs(zonepath) == Z_OK)
3879 			return (Z_OK);
3880 		(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND
3881 		    " %s/*", zonepath);
3882 		status = do_subproc(cmdbuf);
3883 		return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
3884 		    ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
3885 	}
3886 
3887 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
3888 	    zonepath);
3889 	status = do_subproc(cmdbuf);
3890 
3891 	return ((subproc_status(RMCOMMAND, status, B_TRUE) == ZONE_SUBPROC_OK)
3892 	    ? Z_OK : Z_ERR);
3893 }
3894 
3895 static int
3896 move_func(int argc, char *argv[])
3897 {
3898 	char *new_zonepath = NULL;
3899 	int lockfd;
3900 	int err, arg;
3901 	char zonepath[MAXPATHLEN];
3902 	zone_dochandle_t handle;
3903 	boolean_t fast;
3904 	boolean_t is_zfs = B_FALSE;
3905 	struct dirent *dp;
3906 	DIR *dirp;
3907 	boolean_t empty = B_TRUE;
3908 	boolean_t revert;
3909 	struct stat zonepath_buf;
3910 	struct stat new_zonepath_buf;
3911 
3912 	if (zonecfg_in_alt_root()) {
3913 		zerror(gettext("cannot move zone in alternate root"));
3914 		return (Z_ERR);
3915 	}
3916 
3917 	optind = 0;
3918 	if ((arg = getopt(argc, argv, "?")) != EOF) {
3919 		switch (arg) {
3920 		case '?':
3921 			sub_usage(SHELP_MOVE, CMD_MOVE);
3922 			return (optopt == '?' ? Z_OK : Z_USAGE);
3923 		default:
3924 			sub_usage(SHELP_MOVE, CMD_MOVE);
3925 			return (Z_USAGE);
3926 		}
3927 	}
3928 	if (argc != (optind + 1)) {
3929 		sub_usage(SHELP_MOVE, CMD_MOVE);
3930 		return (Z_USAGE);
3931 	}
3932 	new_zonepath = argv[optind];
3933 	if (sanity_check(target_zone, CMD_MOVE, B_FALSE, B_TRUE, B_FALSE)
3934 	    != Z_OK)
3935 		return (Z_ERR);
3936 	if (verify_details(CMD_MOVE) != Z_OK)
3937 		return (Z_ERR);
3938 
3939 	/*
3940 	 * Check out the new zonepath.  This has the side effect of creating
3941 	 * a directory for the new zonepath.  We depend on this later when we
3942 	 * stat to see if we are doing a cross file system move or not.
3943 	 */
3944 	if (validate_zonepath(new_zonepath, CMD_MOVE) != Z_OK)
3945 		return (Z_ERR);
3946 
3947 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3948 	    != Z_OK) {
3949 		errno = err;
3950 		zperror2(target_zone, gettext("could not get zone path"));
3951 		return (Z_ERR);
3952 	}
3953 
3954 	if (stat(zonepath, &zonepath_buf) == -1) {
3955 		zperror(gettext("could not stat zone path"), B_FALSE);
3956 		return (Z_ERR);
3957 	}
3958 
3959 	if (stat(new_zonepath, &new_zonepath_buf) == -1) {
3960 		zperror(gettext("could not stat new zone path"), B_FALSE);
3961 		return (Z_ERR);
3962 	}
3963 
3964 	/*
3965 	 * Check if the destination directory is empty.
3966 	 */
3967 	if ((dirp = opendir(new_zonepath)) == NULL) {
3968 		zperror(gettext("could not open new zone path"), B_FALSE);
3969 		return (Z_ERR);
3970 	}
3971 	while ((dp = readdir(dirp)) != (struct dirent *)0) {
3972 		if (strcmp(dp->d_name, ".") == 0 ||
3973 		    strcmp(dp->d_name, "..") == 0)
3974 			continue;
3975 		empty = B_FALSE;
3976 		break;
3977 	}
3978 	(void) closedir(dirp);
3979 
3980 	/* Error if there is anything in the destination directory. */
3981 	if (!empty) {
3982 		(void) fprintf(stderr, gettext("could not move zone to %s: "
3983 		    "directory not empty\n"), new_zonepath);
3984 		return (Z_ERR);
3985 	}
3986 
3987 	/* Don't move the zone if anything is still mounted there */
3988 	if (zonecfg_find_mounts(zonepath, NULL, NULL)) {
3989 		zerror(gettext("These file systems are mounted on "
3990 		    "subdirectories of %s.\n"), zonepath);
3991 		(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
3992 		return (Z_ERR);
3993 	}
3994 
3995 	/*
3996 	 * Check if we are moving in the same file system and can do a fast
3997 	 * move or if we are crossing file systems and have to copy the data.
3998 	 */
3999 	fast = (zonepath_buf.st_dev == new_zonepath_buf.st_dev);
4000 
4001 	if ((handle = zonecfg_init_handle()) == NULL) {
4002 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4003 		return (Z_ERR);
4004 	}
4005 
4006 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4007 		errno = err;
4008 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4009 		zonecfg_fini_handle(handle);
4010 		return (Z_ERR);
4011 	}
4012 
4013 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
4014 		zerror(gettext("another %s may have an operation in progress."),
4015 		    "zoneadm");
4016 		zonecfg_fini_handle(handle);
4017 		return (Z_ERR);
4018 	}
4019 
4020 	/*
4021 	 * We're making some file system changes now so we have to clean up
4022 	 * the file system before we are done.  This will either clean up the
4023 	 * new zonepath if the zonecfg update failed or it will clean up the
4024 	 * old zonepath if everything is ok.
4025 	 */
4026 	revert = B_TRUE;
4027 
4028 	if (is_zonepath_zfs(zonepath) &&
4029 	    move_zfs(zonepath, new_zonepath) != Z_ERR) {
4030 		is_zfs = B_TRUE;
4031 
4032 	} else if (fast) {
4033 		/* same file system, use rename for a quick move */
4034 
4035 		/*
4036 		 * Remove the new_zonepath directory that got created above
4037 		 * during the validation.  It gets in the way of the rename.
4038 		 */
4039 		if (rmdir(new_zonepath) != 0) {
4040 			zperror(gettext("could not rmdir new zone path"),
4041 			    B_FALSE);
4042 			zonecfg_fini_handle(handle);
4043 			release_lock_file(lockfd);
4044 			return (Z_ERR);
4045 		}
4046 
4047 		if (rename(zonepath, new_zonepath) != 0) {
4048 			/*
4049 			 * If this fails we don't need to do all of the
4050 			 * cleanup that happens for the rest of the code
4051 			 * so just return from this error.
4052 			 */
4053 			zperror(gettext("could not move zone"), B_FALSE);
4054 			zonecfg_fini_handle(handle);
4055 			release_lock_file(lockfd);
4056 			return (Z_ERR);
4057 		}
4058 
4059 	} else {
4060 		/*
4061 		 * Attempt to create a ZFS fs for the new zonepath.  As usual,
4062 		 * we don't care if this works or not since we always have the
4063 		 * default behavior of a simple directory for the zonepath.
4064 		 */
4065 		create_zfs_zonepath(new_zonepath);
4066 
4067 		(void) printf(gettext(
4068 		    "Moving across file systems; copying zonepath %s..."),
4069 		    zonepath);
4070 		(void) fflush(stdout);
4071 
4072 		err = copy_zone(zonepath, new_zonepath);
4073 
4074 		(void) printf("\n");
4075 		if (err != Z_OK)
4076 			goto done;
4077 	}
4078 
4079 	if ((err = zonecfg_set_zonepath(handle, new_zonepath)) != Z_OK) {
4080 		errno = err;
4081 		zperror(gettext("could not set new zonepath"), B_TRUE);
4082 		goto done;
4083 	}
4084 
4085 	if ((err = zonecfg_save(handle)) != Z_OK) {
4086 		errno = err;
4087 		zperror(gettext("zonecfg save failed"), B_TRUE);
4088 		goto done;
4089 	}
4090 
4091 	revert = B_FALSE;
4092 
4093 done:
4094 	zonecfg_fini_handle(handle);
4095 	release_lock_file(lockfd);
4096 
4097 	/*
4098 	 * Clean up the file system based on how things went.  We either
4099 	 * clean up the new zonepath if the operation failed for some reason
4100 	 * or we clean up the old zonepath if everything is ok.
4101 	 */
4102 	if (revert) {
4103 		/* The zonecfg update failed, cleanup the new zonepath. */
4104 		if (is_zfs) {
4105 			if (move_zfs(new_zonepath, zonepath) == Z_ERR) {
4106 				(void) fprintf(stderr, gettext("could not "
4107 				    "restore zonepath, the zfs mountpoint is "
4108 				    "set as:\n%s\n"), new_zonepath);
4109 				/*
4110 				 * err is already != Z_OK since we're reverting
4111 				 */
4112 			}
4113 
4114 		} else if (fast) {
4115 			if (rename(new_zonepath, zonepath) != 0) {
4116 				zperror(gettext("could not restore zonepath"),
4117 				    B_FALSE);
4118 				/*
4119 				 * err is already != Z_OK since we're reverting
4120 				 */
4121 			}
4122 		} else {
4123 			(void) printf(gettext("Cleaning up zonepath %s..."),
4124 			    new_zonepath);
4125 			(void) fflush(stdout);
4126 			err = cleanup_zonepath(new_zonepath, B_TRUE);
4127 			(void) printf("\n");
4128 
4129 			if (err != Z_OK) {
4130 				errno = err;
4131 				zperror(gettext("could not remove new "
4132 				    "zonepath"), B_TRUE);
4133 			} else {
4134 				/*
4135 				 * Because we're reverting we know the mainline
4136 				 * code failed but we just reused the err
4137 				 * variable so we reset it back to Z_ERR.
4138 				 */
4139 				err = Z_ERR;
4140 			}
4141 		}
4142 
4143 	} else {
4144 		/* The move was successful, cleanup the old zonepath. */
4145 		if (!is_zfs && !fast) {
4146 			(void) printf(
4147 			    gettext("Cleaning up zonepath %s..."), zonepath);
4148 			(void) fflush(stdout);
4149 			err = cleanup_zonepath(zonepath, B_TRUE);
4150 			(void) printf("\n");
4151 
4152 			if (err != Z_OK) {
4153 				errno = err;
4154 				zperror(gettext("could not remove zonepath"),
4155 				    B_TRUE);
4156 			}
4157 		}
4158 	}
4159 
4160 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4161 }
4162 
4163 static int
4164 detach_func(int argc, char *argv[])
4165 {
4166 	int lockfd;
4167 	int err, arg;
4168 	char zonepath[MAXPATHLEN];
4169 	zone_dochandle_t handle;
4170 	boolean_t execute = B_TRUE;
4171 
4172 	if (zonecfg_in_alt_root()) {
4173 		zerror(gettext("cannot detach zone in alternate root"));
4174 		return (Z_ERR);
4175 	}
4176 
4177 	optind = 0;
4178 	if ((arg = getopt(argc, argv, "?n")) != EOF) {
4179 		switch (arg) {
4180 		case '?':
4181 			sub_usage(SHELP_DETACH, CMD_DETACH);
4182 			return (optopt == '?' ? Z_OK : Z_USAGE);
4183 		case 'n':
4184 			execute = B_FALSE;
4185 			break;
4186 		default:
4187 			sub_usage(SHELP_DETACH, CMD_DETACH);
4188 			return (Z_USAGE);
4189 		}
4190 	}
4191 
4192 	if (execute) {
4193 		if (sanity_check(target_zone, CMD_DETACH, B_FALSE, B_TRUE,
4194 		    B_FALSE) != Z_OK)
4195 			return (Z_ERR);
4196 		if (verify_details(CMD_DETACH) != Z_OK)
4197 			return (Z_ERR);
4198 	} else {
4199 		/*
4200 		 * We want a dry-run to work for a non-privileged user so we
4201 		 * only do minimal validation.
4202 		 */
4203 		if (getzoneid() != GLOBAL_ZONEID) {
4204 			zerror(gettext("must be in the global zone to %s a "
4205 			    "zone."), cmd_to_str(CMD_DETACH));
4206 			return (Z_ERR);
4207 		}
4208 
4209 		if (target_zone == NULL) {
4210 			zerror(gettext("no zone specified"));
4211 			return (Z_ERR);
4212 		}
4213 
4214 		if (strcmp(target_zone, GLOBAL_ZONENAME) == 0) {
4215 			zerror(gettext("%s operation is invalid for the "
4216 			    "global zone."), cmd_to_str(CMD_DETACH));
4217 			return (Z_ERR);
4218 		}
4219 	}
4220 
4221 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4222 	    != Z_OK) {
4223 		errno = err;
4224 		zperror2(target_zone, gettext("could not get zone path"));
4225 		return (Z_ERR);
4226 	}
4227 
4228 	/* Don't detach the zone if anything is still mounted there */
4229 	if (execute && zonecfg_find_mounts(zonepath, NULL, NULL)) {
4230 		zerror(gettext("These file systems are mounted on "
4231 		    "subdirectories of %s.\n"), zonepath);
4232 		(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
4233 		return (Z_ERR);
4234 	}
4235 
4236 	if ((handle = zonecfg_init_handle()) == NULL) {
4237 		zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4238 		return (Z_ERR);
4239 	}
4240 
4241 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4242 		errno = err;
4243 		zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4244 		zonecfg_fini_handle(handle);
4245 		return (Z_ERR);
4246 	}
4247 
4248 	if (execute && grab_lock_file(target_zone, &lockfd) != Z_OK) {
4249 		zerror(gettext("another %s may have an operation in progress."),
4250 		    "zoneadm");
4251 		zonecfg_fini_handle(handle);
4252 		return (Z_ERR);
4253 	}
4254 
4255 	if ((err = zonecfg_get_detach_info(handle, B_TRUE)) != Z_OK) {
4256 		errno = err;
4257 		zperror(gettext("getting the detach information failed"),
4258 		    B_TRUE);
4259 		goto done;
4260 	}
4261 
4262 	if ((err = zonecfg_detach_save(handle, (execute ? 0 : ZONE_DRY_RUN)))
4263 	    != Z_OK) {
4264 		errno = err;
4265 		zperror(gettext("saving the detach manifest failed"), B_TRUE);
4266 		goto done;
4267 	}
4268 
4269 	/*
4270 	 * Set the zone state back to configured unless we are running with the
4271 	 * no-execute option.
4272 	 */
4273 	if (execute && (err = zone_set_state(target_zone,
4274 	    ZONE_STATE_CONFIGURED)) != Z_OK) {
4275 		errno = err;
4276 		zperror(gettext("could not reset state"), B_TRUE);
4277 	}
4278 
4279 done:
4280 	zonecfg_fini_handle(handle);
4281 	if (execute)
4282 		release_lock_file(lockfd);
4283 
4284 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4285 }
4286 
4287 /*
4288  * During attach we go through and fix up the /dev entries for the zone
4289  * we are attaching.  In order to regenerate /dev with the correct devices,
4290  * the old /dev will be removed, the zone readied (which generates a new
4291  * /dev) then halted, then we use the info from the manifest to update
4292  * the modes, owners, etc. on the new /dev.
4293  */
4294 static int
4295 dev_fix(zone_dochandle_t handle)
4296 {
4297 	int			res;
4298 	int			err;
4299 	int			status;
4300 	struct zone_devpermtab	devtab;
4301 	zone_cmd_arg_t		zarg;
4302 	char			devpath[MAXPATHLEN];
4303 				/* 6: "exec " and " " */
4304 	char			cmdbuf[sizeof (RMCOMMAND) + MAXPATHLEN + 6];
4305 
4306 	if ((res = zonecfg_get_zonepath(handle, devpath, sizeof (devpath)))
4307 	    != Z_OK)
4308 		return (res);
4309 
4310 	if (strlcat(devpath, "/dev", sizeof (devpath)) >= sizeof (devpath))
4311 		return (Z_TOO_BIG);
4312 
4313 	/*
4314 	 * "exec" the command so that the returned status is that of
4315 	 * RMCOMMAND and not the shell.
4316 	 */
4317 	(void) snprintf(cmdbuf, sizeof (cmdbuf), EXEC_PREFIX RMCOMMAND " %s",
4318 	    devpath);
4319 	status = do_subproc(cmdbuf);
4320 	if ((err = subproc_status(RMCOMMAND, status, B_TRUE)) !=
4321 	    ZONE_SUBPROC_OK) {
4322 		(void) fprintf(stderr,
4323 		    gettext("could not remove existing /dev\n"));
4324 		return (Z_ERR);
4325 	}
4326 
4327 	/* In order to ready the zone, it must be in the installed state */
4328 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
4329 		errno = err;
4330 		zperror(gettext("could not reset state"), B_TRUE);
4331 		return (Z_ERR);
4332 	}
4333 
4334 	/* We have to ready the zone to regen the dev tree */
4335 	zarg.cmd = Z_READY;
4336 	if (call_zoneadmd(target_zone, &zarg) != 0) {
4337 		zerror(gettext("call to %s failed"), "zoneadmd");
4338 		return (Z_ERR);
4339 	}
4340 
4341 	zarg.cmd = Z_HALT;
4342 	if (call_zoneadmd(target_zone, &zarg) != 0) {
4343 		zerror(gettext("call to %s failed"), "zoneadmd");
4344 		return (Z_ERR);
4345 	}
4346 
4347 	if (zonecfg_setdevperment(handle) != Z_OK) {
4348 		(void) fprintf(stderr,
4349 		    gettext("unable to enumerate device entries\n"));
4350 		return (Z_ERR);
4351 	}
4352 
4353 	while (zonecfg_getdevperment(handle, &devtab) == Z_OK) {
4354 		int err;
4355 
4356 		if ((err = zonecfg_devperms_apply(handle,
4357 		    devtab.zone_devperm_name, devtab.zone_devperm_uid,
4358 		    devtab.zone_devperm_gid, devtab.zone_devperm_mode,
4359 		    devtab.zone_devperm_acl)) != Z_OK && err != Z_INVAL)
4360 			(void) fprintf(stderr, gettext("error updating device "
4361 			    "%s: %s\n"), devtab.zone_devperm_name,
4362 			    zonecfg_strerror(err));
4363 
4364 		free(devtab.zone_devperm_acl);
4365 	}
4366 
4367 	(void) zonecfg_enddevperment(handle);
4368 
4369 	return (Z_OK);
4370 }
4371 
4372 /*
4373  * Validate attaching a zone but don't actually do the work.  The zone
4374  * does not have to exist, so there is some complexity getting a new zone
4375  * configuration set up so that we can perform the validation.  This is
4376  * handled within zonecfg_attach_manifest() which returns two handles; one
4377  * for the the full configuration to validate (rem_handle) and the other
4378  * (local_handle) containing only the zone configuration derived from the
4379  * manifest.
4380  */
4381 static int
4382 dryrun_attach(char *manifest_path)
4383 {
4384 	int fd;
4385 	int err;
4386 	int res;
4387 	zone_dochandle_t local_handle;
4388 	zone_dochandle_t rem_handle = NULL;
4389 
4390 	if (strcmp(manifest_path, "-") == 0) {
4391 		fd = 0;
4392 	} else if ((fd = open(manifest_path, O_RDONLY)) < 0) {
4393 		zperror(gettext("could not open manifest path"), B_FALSE);
4394 		return (Z_ERR);
4395 	}
4396 
4397 	if ((local_handle = zonecfg_init_handle()) == NULL) {
4398 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4399 		res = Z_ERR;
4400 		goto done;
4401 	}
4402 
4403 	if ((rem_handle = zonecfg_init_handle()) == NULL) {
4404 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4405 		res = Z_ERR;
4406 		goto done;
4407 	}
4408 
4409 	if ((err = zonecfg_attach_manifest(fd, local_handle, rem_handle))
4410 	    != Z_OK) {
4411 		if (err == Z_INVALID_DOCUMENT)
4412 			zerror(gettext("Cannot attach to an earlier release "
4413 			    "of the operating system"));
4414 		else
4415 			zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4416 		res = Z_ERR;
4417 		goto done;
4418 	}
4419 
4420 	res = verify_handle(CMD_ATTACH, local_handle);
4421 
4422 	/* Get the detach information for the locally defined zone. */
4423 	if ((err = zonecfg_get_detach_info(local_handle, B_FALSE)) != Z_OK) {
4424 		errno = err;
4425 		zperror(gettext("getting the attach information failed"),
4426 		    B_TRUE);
4427 		res = Z_ERR;
4428 	} else {
4429 		/* sw_cmp prints error msgs as necessary */
4430 		if (sw_cmp(local_handle, rem_handle, SW_CMP_NONE) != Z_OK)
4431 			res = Z_ERR;
4432 	}
4433 
4434 done:
4435 	if (strcmp(manifest_path, "-") != 0)
4436 		(void) close(fd);
4437 
4438 	zonecfg_fini_handle(local_handle);
4439 	zonecfg_fini_handle(rem_handle);
4440 
4441 	return ((res == Z_OK) ? Z_OK : Z_ERR);
4442 }
4443 
4444 static int
4445 attach_func(int argc, char *argv[])
4446 {
4447 	int lockfd;
4448 	int err, arg;
4449 	boolean_t force = B_FALSE;
4450 	zone_dochandle_t handle;
4451 	zone_dochandle_t athandle = NULL;
4452 	char zonepath[MAXPATHLEN];
4453 	char brand[MAXNAMELEN], atbrand[MAXNAMELEN];
4454 	boolean_t execute = B_TRUE;
4455 	char *manifest_path;
4456 
4457 	if (zonecfg_in_alt_root()) {
4458 		zerror(gettext("cannot attach zone in alternate root"));
4459 		return (Z_ERR);
4460 	}
4461 
4462 	optind = 0;
4463 	if ((arg = getopt(argc, argv, "?Fn:")) != EOF) {
4464 		switch (arg) {
4465 		case '?':
4466 			sub_usage(SHELP_ATTACH, CMD_ATTACH);
4467 			return (optopt == '?' ? Z_OK : Z_USAGE);
4468 		case 'F':
4469 			force = B_TRUE;
4470 			break;
4471 		case 'n':
4472 			execute = B_FALSE;
4473 			manifest_path = optarg;
4474 			break;
4475 		default:
4476 			sub_usage(SHELP_ATTACH, CMD_ATTACH);
4477 			return (Z_USAGE);
4478 		}
4479 	}
4480 
4481 	/*
4482 	 * If the no-execute option was specified, we need to branch down
4483 	 * a completely different path since there is no zone required to be
4484 	 * configured for this option.
4485 	 */
4486 	if (!execute)
4487 		return (dryrun_attach(manifest_path));
4488 
4489 	if (sanity_check(target_zone, CMD_ATTACH, B_FALSE, B_TRUE, B_FALSE)
4490 	    != Z_OK)
4491 		return (Z_ERR);
4492 	if (verify_details(CMD_ATTACH) != Z_OK)
4493 		return (Z_ERR);
4494 
4495 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4496 	    != Z_OK) {
4497 		errno = err;
4498 		zperror2(target_zone, gettext("could not get zone path"));
4499 		return (Z_ERR);
4500 	}
4501 
4502 	if ((handle = zonecfg_init_handle()) == NULL) {
4503 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4504 		return (Z_ERR);
4505 	}
4506 
4507 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4508 		errno = err;
4509 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4510 		zonecfg_fini_handle(handle);
4511 		return (Z_ERR);
4512 	}
4513 
4514 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
4515 		zerror(gettext("another %s may have an operation in progress."),
4516 		    "zoneadm");
4517 		zonecfg_fini_handle(handle);
4518 		return (Z_ERR);
4519 	}
4520 
4521 	if (force)
4522 		goto forced;
4523 
4524 	if ((athandle = zonecfg_init_handle()) == NULL) {
4525 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4526 		goto done;
4527 	}
4528 
4529 	if ((err = zonecfg_get_attach_handle(zonepath, target_zone, B_TRUE,
4530 	    athandle)) != Z_OK) {
4531 		if (err == Z_NO_ZONE)
4532 			zerror(gettext("Not a detached zone"));
4533 		else if (err == Z_INVALID_DOCUMENT)
4534 			zerror(gettext("Cannot attach to an earlier release "
4535 			    "of the operating system"));
4536 		else
4537 			zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4538 		goto done;
4539 	}
4540 
4541 	/* Get the detach information for the locally defined zone. */
4542 	if ((err = zonecfg_get_detach_info(handle, B_FALSE)) != Z_OK) {
4543 		errno = err;
4544 		zperror(gettext("getting the attach information failed"),
4545 		    B_TRUE);
4546 		goto done;
4547 	}
4548 
4549 	/*
4550 	 * Ensure that the detached and locally defined zones are both of
4551 	 * the same brand.
4552 	 */
4553 	if ((zonecfg_get_brand(handle, brand, sizeof (brand)) != 0) ||
4554 	    (zonecfg_get_brand(athandle, atbrand, sizeof (atbrand)) != 0)) {
4555 		err = Z_ERR;
4556 		zerror(gettext("missing or invalid brand"));
4557 		goto done;
4558 	}
4559 
4560 	if (strcmp(atbrand, brand) != NULL) {
4561 		err = Z_ERR;
4562 		zerror(gettext("Trying to attach a '%s' zone to a '%s' "
4563 		    "configuration."), atbrand, brand);
4564 		goto done;
4565 	}
4566 
4567 	/* sw_cmp prints error msgs as necessary */
4568 	if ((err = sw_cmp(handle, athandle, SW_CMP_NONE)) != Z_OK)
4569 		goto done;
4570 
4571 	if ((err = dev_fix(athandle)) != Z_OK)
4572 		goto done;
4573 
4574 forced:
4575 
4576 	zonecfg_rm_detached(handle, force);
4577 
4578 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
4579 		errno = err;
4580 		zperror(gettext("could not reset state"), B_TRUE);
4581 	}
4582 
4583 done:
4584 	zonecfg_fini_handle(handle);
4585 	release_lock_file(lockfd);
4586 	if (athandle != NULL)
4587 		zonecfg_fini_handle(athandle);
4588 
4589 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4590 }
4591 
4592 /*
4593  * On input, TRUE => yes, FALSE => no.
4594  * On return, TRUE => 1, FALSE => 0, could not ask => -1.
4595  */
4596 
4597 static int
4598 ask_yesno(boolean_t default_answer, const char *question)
4599 {
4600 	char line[64];	/* should be large enough to answer yes or no */
4601 
4602 	if (!isatty(STDIN_FILENO))
4603 		return (-1);
4604 	for (;;) {
4605 		(void) printf("%s (%s)? ", question,
4606 		    default_answer ? "[y]/n" : "y/[n]");
4607 		if (fgets(line, sizeof (line), stdin) == NULL ||
4608 		    line[0] == '\n')
4609 			return (default_answer ? 1 : 0);
4610 		if (tolower(line[0]) == 'y')
4611 			return (1);
4612 		if (tolower(line[0]) == 'n')
4613 			return (0);
4614 	}
4615 }
4616 
4617 static int
4618 uninstall_func(int argc, char *argv[])
4619 {
4620 	char line[ZONENAME_MAX + 128];	/* Enough for "Are you sure ..." */
4621 	char rootpath[MAXPATHLEN], zonepath[MAXPATHLEN];
4622 	boolean_t force = B_FALSE;
4623 	int lockfd, answer;
4624 	int err, arg;
4625 
4626 	if (zonecfg_in_alt_root()) {
4627 		zerror(gettext("cannot uninstall zone in alternate root"));
4628 		return (Z_ERR);
4629 	}
4630 
4631 	optind = 0;
4632 	while ((arg = getopt(argc, argv, "?F")) != EOF) {
4633 		switch (arg) {
4634 		case '?':
4635 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
4636 			return (optopt == '?' ? Z_OK : Z_USAGE);
4637 		case 'F':
4638 			force = B_TRUE;
4639 			break;
4640 		default:
4641 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
4642 			return (Z_USAGE);
4643 		}
4644 	}
4645 	if (argc > optind) {
4646 		sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
4647 		return (Z_USAGE);
4648 	}
4649 
4650 	if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE, B_FALSE)
4651 	    != Z_OK)
4652 		return (Z_ERR);
4653 
4654 	if (!force) {
4655 		(void) snprintf(line, sizeof (line),
4656 		    gettext("Are you sure you want to %s zone %s"),
4657 		    cmd_to_str(CMD_UNINSTALL), target_zone);
4658 		if ((answer = ask_yesno(B_FALSE, line)) == 0) {
4659 			return (Z_OK);
4660 		} else if (answer == -1) {
4661 			zerror(gettext("Input not from terminal and -F "
4662 			    "not specified: %s not done."),
4663 			    cmd_to_str(CMD_UNINSTALL));
4664 			return (Z_ERR);
4665 		}
4666 	}
4667 
4668 	if ((err = zone_get_zonepath(target_zone, zonepath,
4669 	    sizeof (zonepath))) != Z_OK) {
4670 		errno = err;
4671 		zperror2(target_zone, gettext("could not get zone path"));
4672 		return (Z_ERR);
4673 	}
4674 	if ((err = zone_get_rootpath(target_zone, rootpath,
4675 	    sizeof (rootpath))) != Z_OK) {
4676 		errno = err;
4677 		zperror2(target_zone, gettext("could not get root path"));
4678 		return (Z_ERR);
4679 	}
4680 
4681 	/*
4682 	 * If there seems to be a zoneadmd running for this zone, call it
4683 	 * to tell it that an uninstall is happening; if all goes well it
4684 	 * will then shut itself down.
4685 	 */
4686 	if (ping_zoneadmd(target_zone) == Z_OK) {
4687 		zone_cmd_arg_t zarg;
4688 		zarg.cmd = Z_NOTE_UNINSTALLING;
4689 		/* we don't care too much if this fails... just plow on */
4690 		(void) call_zoneadmd(target_zone, &zarg);
4691 	}
4692 
4693 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
4694 		zerror(gettext("another %s may have an operation in progress."),
4695 		    "zoneadm");
4696 		return (Z_ERR);
4697 	}
4698 
4699 	/* Don't uninstall the zone if anything is mounted there */
4700 	err = zonecfg_find_mounts(rootpath, NULL, NULL);
4701 	if (err) {
4702 		zerror(gettext("These file systems are mounted on "
4703 		    "subdirectories of %s.\n"), rootpath);
4704 		(void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
4705 		return (Z_ERR);
4706 	}
4707 
4708 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
4709 	if (err != Z_OK) {
4710 		errno = err;
4711 		zperror2(target_zone, gettext("could not set state"));
4712 		goto bad;
4713 	}
4714 
4715 	if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
4716 		errno = err;
4717 		zperror2(target_zone, gettext("cleaning up zonepath failed"));
4718 		goto bad;
4719 	}
4720 
4721 	err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
4722 	if (err != Z_OK) {
4723 		errno = err;
4724 		zperror2(target_zone, gettext("could not reset state"));
4725 	}
4726 bad:
4727 	release_lock_file(lockfd);
4728 	return (err);
4729 }
4730 
4731 /* ARGSUSED */
4732 static int
4733 mount_func(int argc, char *argv[])
4734 {
4735 	zone_cmd_arg_t zarg;
4736 	boolean_t force = B_FALSE;
4737 	int arg;
4738 
4739 	/*
4740 	 * The only supported subargument to the "mount" subcommand is
4741 	 * "-f", which forces us to mount a zone in the INCOMPLETE state.
4742 	 */
4743 	optind = 0;
4744 	if ((arg = getopt(argc, argv, "f")) != EOF) {
4745 		switch (arg) {
4746 		case 'f':
4747 			force = B_TRUE;
4748 			break;
4749 		default:
4750 			return (Z_USAGE);
4751 		}
4752 	}
4753 	if (argc > optind)
4754 		return (Z_USAGE);
4755 
4756 	if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE, force)
4757 	    != Z_OK)
4758 		return (Z_ERR);
4759 	if (verify_details(CMD_MOUNT) != Z_OK)
4760 		return (Z_ERR);
4761 
4762 	zarg.cmd = force ? Z_FORCEMOUNT : Z_MOUNT;
4763 	if (call_zoneadmd(target_zone, &zarg) != 0) {
4764 		zerror(gettext("call to %s failed"), "zoneadmd");
4765 		return (Z_ERR);
4766 	}
4767 	return (Z_OK);
4768 }
4769 
4770 /* ARGSUSED */
4771 static int
4772 unmount_func(int argc, char *argv[])
4773 {
4774 	zone_cmd_arg_t zarg;
4775 
4776 	if (argc > 0)
4777 		return (Z_USAGE);
4778 	if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE, B_FALSE)
4779 	    != Z_OK)
4780 		return (Z_ERR);
4781 
4782 	zarg.cmd = Z_UNMOUNT;
4783 	if (call_zoneadmd(target_zone, &zarg) != 0) {
4784 		zerror(gettext("call to %s failed"), "zoneadmd");
4785 		return (Z_ERR);
4786 	}
4787 	return (Z_OK);
4788 }
4789 
4790 static int
4791 mark_func(int argc, char *argv[])
4792 {
4793 	int err, lockfd;
4794 
4795 	if (argc != 1 || strcmp(argv[0], "incomplete") != 0)
4796 		return (Z_USAGE);
4797 	if (sanity_check(target_zone, CMD_MARK, B_FALSE, B_FALSE, B_FALSE)
4798 	    != Z_OK)
4799 		return (Z_ERR);
4800 
4801 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
4802 		zerror(gettext("another %s may have an operation in progress."),
4803 		    "zoneadm");
4804 		return (Z_ERR);
4805 	}
4806 
4807 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
4808 	if (err != Z_OK) {
4809 		errno = err;
4810 		zperror2(target_zone, gettext("could not set state"));
4811 	}
4812 	release_lock_file(lockfd);
4813 
4814 	return (err);
4815 }
4816 
4817 static int
4818 help_func(int argc, char *argv[])
4819 {
4820 	int arg, cmd_num;
4821 
4822 	if (argc == 0) {
4823 		(void) usage(B_TRUE);
4824 		return (Z_OK);
4825 	}
4826 	optind = 0;
4827 	if ((arg = getopt(argc, argv, "?")) != EOF) {
4828 		switch (arg) {
4829 		case '?':
4830 			sub_usage(SHELP_HELP, CMD_HELP);
4831 			return (optopt == '?' ? Z_OK : Z_USAGE);
4832 		default:
4833 			sub_usage(SHELP_HELP, CMD_HELP);
4834 			return (Z_USAGE);
4835 		}
4836 	}
4837 	while (optind < argc) {
4838 		/* Private commands have NULL short_usage; omit them */
4839 		if ((cmd_num = cmd_match(argv[optind])) < 0 ||
4840 		    cmdtab[cmd_num].short_usage == NULL) {
4841 			sub_usage(SHELP_HELP, CMD_HELP);
4842 			return (Z_USAGE);
4843 		}
4844 		sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
4845 		optind++;
4846 	}
4847 	return (Z_OK);
4848 }
4849 
4850 /*
4851  * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
4852  */
4853 
4854 static int
4855 cmd_match(char *cmd)
4856 {
4857 	int i;
4858 
4859 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
4860 		/* return only if there is an exact match */
4861 		if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
4862 			return (cmdtab[i].cmd_num);
4863 	}
4864 	return (-1);
4865 }
4866 
4867 static int
4868 parse_and_run(int argc, char *argv[])
4869 {
4870 	int i = cmd_match(argv[0]);
4871 
4872 	if (i < 0)
4873 		return (usage(B_FALSE));
4874 	return (cmdtab[i].handler(argc - 1, &(argv[1])));
4875 }
4876 
4877 static char *
4878 get_execbasename(char *execfullname)
4879 {
4880 	char *last_slash, *execbasename;
4881 
4882 	/* guard against '/' at end of command invocation */
4883 	for (;;) {
4884 		last_slash = strrchr(execfullname, '/');
4885 		if (last_slash == NULL) {
4886 			execbasename = execfullname;
4887 			break;
4888 		} else {
4889 			execbasename = last_slash + 1;
4890 			if (*execbasename == '\0') {
4891 				*last_slash = '\0';
4892 				continue;
4893 			}
4894 			break;
4895 		}
4896 	}
4897 	return (execbasename);
4898 }
4899 
4900 int
4901 main(int argc, char **argv)
4902 {
4903 	int arg;
4904 	zoneid_t zid;
4905 	struct stat st;
4906 	char *zone_lock_env;
4907 	int err;
4908 
4909 	if ((locale = setlocale(LC_ALL, "")) == NULL)
4910 		locale = "C";
4911 	(void) textdomain(TEXT_DOMAIN);
4912 	setbuf(stdout, NULL);
4913 	(void) sigset(SIGHUP, SIG_IGN);
4914 	execname = get_execbasename(argv[0]);
4915 	target_zone = NULL;
4916 	if (chdir("/") != 0) {
4917 		zerror(gettext("could not change directory to /."));
4918 		exit(Z_ERR);
4919 	}
4920 
4921 	if (init_zfs() != Z_OK)
4922 		exit(Z_ERR);
4923 
4924 	while ((arg = getopt(argc, argv, "?u:z:R:")) != EOF) {
4925 		switch (arg) {
4926 		case '?':
4927 			return (usage(B_TRUE));
4928 		case 'u':
4929 			target_uuid = optarg;
4930 			break;
4931 		case 'z':
4932 			target_zone = optarg;
4933 			break;
4934 		case 'R':	/* private option for admin/install use */
4935 			if (*optarg != '/') {
4936 				zerror(gettext("root path must be absolute."));
4937 				exit(Z_ERR);
4938 			}
4939 			if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
4940 				zerror(
4941 				    gettext("root path must be a directory."));
4942 				exit(Z_ERR);
4943 			}
4944 			zonecfg_set_root(optarg);
4945 			break;
4946 		default:
4947 			return (usage(B_FALSE));
4948 		}
4949 	}
4950 
4951 	if (optind >= argc)
4952 		return (usage(B_FALSE));
4953 
4954 	if (target_uuid != NULL && *target_uuid != '\0') {
4955 		uuid_t uuid;
4956 		static char newtarget[ZONENAME_MAX];
4957 
4958 		if (uuid_parse(target_uuid, uuid) == -1) {
4959 			zerror(gettext("illegal UUID value specified"));
4960 			exit(Z_ERR);
4961 		}
4962 		if (zonecfg_get_name_by_uuid(uuid, newtarget,
4963 		    sizeof (newtarget)) == Z_OK)
4964 			target_zone = newtarget;
4965 	}
4966 
4967 	if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
4968 		errno = Z_NO_ZONE;
4969 		zperror(target_zone, B_TRUE);
4970 		exit(Z_ERR);
4971 	}
4972 
4973 	/*
4974 	 * See if we have inherited the right to manipulate this zone from
4975 	 * a zoneadm instance in our ancestry.  If so, set zone_lock_cnt to
4976 	 * indicate it.  If not, make that explicit in our environment.
4977 	 */
4978 	zone_lock_env = getenv(LOCK_ENV_VAR);
4979 	if (zone_lock_env == NULL) {
4980 		if (putenv(zoneadm_lock_not_held) != 0) {
4981 			zperror(target_zone, B_TRUE);
4982 			exit(Z_ERR);
4983 		}
4984 	} else {
4985 		zoneadm_is_nested = B_TRUE;
4986 		if (atoi(zone_lock_env) == 1)
4987 			zone_lock_cnt = 1;
4988 	}
4989 
4990 	/*
4991 	 * If we are going to be operating on a single zone, retrieve its
4992 	 * brand type and determine whether it is native or not.
4993 	 */
4994 	if ((target_zone != NULL) &&
4995 	    (strcmp(target_zone, GLOBAL_ZONENAME) != NULL)) {
4996 		if (zone_get_brand(target_zone, target_brand,
4997 		    sizeof (target_brand)) != Z_OK) {
4998 			zerror(gettext("missing or invalid brand"));
4999 			exit(Z_ERR);
5000 		}
5001 		is_native_zone = (strcmp(target_brand, NATIVE_BRAND_NAME) == 0);
5002 	}
5003 
5004 	err = parse_and_run(argc - optind, &argv[optind]);
5005 
5006 	return (err);
5007 }
5008