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