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