xref: /titanic_51/usr/src/cmd/zoneadm/zoneadm.c (revision 1e1e1eec7b6c75bbae2bca96dbbc420e6f85ca3f)
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 (validate_zonepath(zonepath, cmd_num) != Z_OK) {
2778 		(void) fprintf(stderr, gettext("could not verify zonepath %s "
2779 		    "because of the above errors.\n"), zonepath);
2780 		return_code = Z_ERR;
2781 	}
2782 
2783 	if (verify_handle(cmd_num, handle, argv) != Z_OK)
2784 		return_code = Z_ERR;
2785 
2786 	zonecfg_fini_handle(handle);
2787 	if (return_code == Z_ERR)
2788 		(void) fprintf(stderr,
2789 		    gettext("%s: zone %s failed to verify\n"),
2790 		    execname, target_zone);
2791 	return (return_code);
2792 }
2793 
2794 static int
2795 verify_func(int argc, char *argv[])
2796 {
2797 	int arg;
2798 
2799 	optind = 0;
2800 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2801 		switch (arg) {
2802 		case '?':
2803 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2804 			return (optopt == '?' ? Z_OK : Z_USAGE);
2805 		default:
2806 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2807 			return (Z_USAGE);
2808 		}
2809 	}
2810 	if (argc > optind) {
2811 		sub_usage(SHELP_VERIFY, CMD_VERIFY);
2812 		return (Z_USAGE);
2813 	}
2814 	if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE, B_FALSE)
2815 	    != Z_OK)
2816 		return (Z_ERR);
2817 	return (verify_details(CMD_VERIFY, argv));
2818 }
2819 
2820 static int
2821 addoptions(char *buf, char *argv[], size_t len)
2822 {
2823 	int i = 0;
2824 
2825 	if (buf[0] == '\0')
2826 		return (Z_OK);
2827 
2828 	while (argv[i] != NULL) {
2829 		if (strlcat(buf, " ", len) >= len ||
2830 		    strlcat(buf, argv[i++], len) >= len) {
2831 			zerror("Command line too long");
2832 			return (Z_ERR);
2833 		}
2834 	}
2835 
2836 	return (Z_OK);
2837 }
2838 
2839 static int
2840 addopt(char *buf, int opt, char *optarg, size_t bufsize)
2841 {
2842 	char optstring[4];
2843 
2844 	if (opt > 0)
2845 		(void) sprintf(optstring, " -%c", opt);
2846 	else
2847 		(void) strcpy(optstring, " ");
2848 
2849 	if ((strlcat(buf, optstring, bufsize) > bufsize))
2850 		return (Z_ERR);
2851 
2852 	if ((optarg != NULL) && (strlcat(buf, optarg, bufsize) > bufsize))
2853 		return (Z_ERR);
2854 
2855 	return (Z_OK);
2856 }
2857 
2858 /* ARGSUSED */
2859 static int
2860 install_func(int argc, char *argv[])
2861 {
2862 	char cmdbuf[MAXPATHLEN];
2863 	char postcmdbuf[MAXPATHLEN];
2864 	int lockfd;
2865 	int arg, err, subproc_err;
2866 	char zonepath[MAXPATHLEN];
2867 	brand_handle_t bh = NULL;
2868 	int status;
2869 	boolean_t nodataset = B_FALSE;
2870 	boolean_t do_postinstall = B_FALSE;
2871 	boolean_t brand_help = B_FALSE;
2872 	char opts[128];
2873 
2874 	if (target_zone == NULL) {
2875 		sub_usage(SHELP_INSTALL, CMD_INSTALL);
2876 		return (Z_USAGE);
2877 	}
2878 
2879 	if (zonecfg_in_alt_root()) {
2880 		zerror(gettext("cannot install zone in alternate root"));
2881 		return (Z_ERR);
2882 	}
2883 
2884 	if ((err = zone_get_zonepath(target_zone, zonepath,
2885 	    sizeof (zonepath))) != Z_OK) {
2886 		errno = err;
2887 		zperror2(target_zone, gettext("could not get zone path"));
2888 		return (Z_ERR);
2889 	}
2890 
2891 	/* Fetch the install command from the brand configuration.  */
2892 	if ((bh = brand_open(target_brand)) == NULL) {
2893 		zerror(gettext("missing or invalid brand"));
2894 		return (Z_ERR);
2895 	}
2896 
2897 	if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_install,
2898 	    target_zone, zonepath) != Z_OK) {
2899 		zerror("invalid brand configuration: missing install resource");
2900 		brand_close(bh);
2901 		return (Z_ERR);
2902 	}
2903 
2904 	if (get_hook(bh, postcmdbuf, sizeof (postcmdbuf), brand_get_postinstall,
2905 	    target_zone, zonepath) != Z_OK) {
2906 		zerror("invalid brand configuration: missing postinstall "
2907 		    "resource");
2908 		brand_close(bh);
2909 		return (Z_ERR);
2910 	}
2911 
2912 	if (postcmdbuf[0] != '\0')
2913 		do_postinstall = B_TRUE;
2914 
2915 	(void) strcpy(opts, "?x:");
2916 	/*
2917 	 * Fetch the list of recognized command-line options from
2918 	 * the brand configuration file.
2919 	 */
2920 	if (brand_get_installopts(bh, opts + strlen(opts),
2921 	    sizeof (opts) - strlen(opts)) != 0) {
2922 		zerror("invalid brand configuration: missing "
2923 		    "install options resource");
2924 		brand_close(bh);
2925 		return (Z_ERR);
2926 	}
2927 
2928 	brand_close(bh);
2929 
2930 	if (cmdbuf[0] == '\0') {
2931 		zerror("Missing brand install command");
2932 		return (Z_ERR);
2933 	}
2934 
2935 	/* Check the argv string for args we handle internally */
2936 	optind = 0;
2937 	opterr = 0;
2938 	while ((arg = getopt(argc, argv, opts)) != EOF) {
2939 		switch (arg) {
2940 		case '?':
2941 			if (optopt == '?') {
2942 				sub_usage(SHELP_INSTALL, CMD_INSTALL);
2943 				brand_help = B_TRUE;
2944 			}
2945 			/* Ignore unknown options - may be brand specific. */
2946 			break;
2947 		case 'x':
2948 			/* Handle this option internally, don't pass to brand */
2949 			if (strcmp(optarg, "nodataset") == 0) {
2950 				/* Handle this option internally */
2951 				nodataset = B_TRUE;
2952 			}
2953 			continue;
2954 		default:
2955 			/* Ignore unknown options - may be brand specific. */
2956 			break;
2957 		}
2958 
2959 		/*
2960 		 * Append the option to the command line passed to the
2961 		 * brand-specific install and postinstall routines.
2962 		 */
2963 		if (addopt(cmdbuf, optopt, optarg, sizeof (cmdbuf)) != Z_OK) {
2964 			zerror("Install command line too long");
2965 			return (Z_ERR);
2966 		}
2967 		if (addopt(postcmdbuf, optopt, optarg, sizeof (postcmdbuf))
2968 		    != Z_OK) {
2969 			zerror("Post-Install command line too long");
2970 			return (Z_ERR);
2971 		}
2972 	}
2973 
2974 	for (; optind < argc; optind++) {
2975 		if (addopt(cmdbuf, 0, argv[optind], sizeof (cmdbuf)) != Z_OK) {
2976 			zerror("Install command line too long");
2977 			return (Z_ERR);
2978 		}
2979 
2980 		if (addopt(postcmdbuf, 0, argv[optind], sizeof (postcmdbuf))
2981 		    != Z_OK) {
2982 			zerror("Post-Install command line too long");
2983 			return (Z_ERR);
2984 		}
2985 	}
2986 
2987 	if (!brand_help) {
2988 		if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE,
2989 		    B_FALSE) != Z_OK)
2990 			return (Z_ERR);
2991 		if (verify_details(CMD_INSTALL, argv) != Z_OK)
2992 			return (Z_ERR);
2993 
2994 		if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
2995 			zerror(gettext("another %s may have an operation in "
2996 			    "progress."), "zoneadm");
2997 			return (Z_ERR);
2998 		}
2999 		err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
3000 		if (err != Z_OK) {
3001 			errno = err;
3002 			zperror2(target_zone, gettext("could not set state"));
3003 			goto done;
3004 		}
3005 
3006 		if (!nodataset)
3007 			create_zfs_zonepath(zonepath);
3008 	}
3009 
3010 	status = do_subproc_interactive(cmdbuf);
3011 	if ((subproc_err =
3012 	    subproc_status(gettext("brand-specific installation"), status,
3013 	    B_FALSE)) != ZONE_SUBPROC_OK) {
3014 		if (subproc_err == ZONE_SUBPROC_USAGE && !brand_help) {
3015 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
3016 			zonecfg_release_lock_file(target_zone, lockfd);
3017 			return (Z_ERR);
3018 		}
3019 		err = Z_ERR;
3020 		goto done;
3021 	}
3022 
3023 	if (brand_help)
3024 		return (Z_OK);
3025 
3026 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
3027 		errno = err;
3028 		zperror2(target_zone, gettext("could not set state"));
3029 		goto done;
3030 	}
3031 
3032 	if (do_postinstall) {
3033 		status = do_subproc(postcmdbuf);
3034 
3035 		if ((subproc_err =
3036 		    subproc_status(gettext("brand-specific post-install"),
3037 		    status, B_FALSE)) != ZONE_SUBPROC_OK) {
3038 			err = Z_ERR;
3039 			(void) zone_set_state(target_zone,
3040 			    ZONE_STATE_INCOMPLETE);
3041 		}
3042 	}
3043 
3044 done:
3045 	/*
3046 	 * If the install script exited with ZONE_SUBPROC_NOTCOMPLETE, try to
3047 	 * clean up the zone and leave the zone in the CONFIGURED state so that
3048 	 * another install can be attempted without requiring an uninstall
3049 	 * first.
3050 	 */
3051 	if (subproc_err == ZONE_SUBPROC_NOTCOMPLETE) {
3052 		if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
3053 			errno = err;
3054 			zperror2(target_zone,
3055 			    gettext("cleaning up zonepath failed"));
3056 		} else if ((err = zone_set_state(target_zone,
3057 		    ZONE_STATE_CONFIGURED)) != Z_OK) {
3058 			errno = err;
3059 			zperror2(target_zone, gettext("could not set state"));
3060 		}
3061 	}
3062 
3063 	if (!brand_help)
3064 		zonecfg_release_lock_file(target_zone, lockfd);
3065 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3066 }
3067 
3068 /*
3069  * Check that the inherited pkg dirs are the same for the clone and its source.
3070  * The easiest way to do that is check that the list of ipds is the same
3071  * by matching each one against the other.  This algorithm should be fine since
3072  * the list of ipds should not be that long.
3073  */
3074 static int
3075 valid_ipd_clone(zone_dochandle_t s_handle, char *source_zone,
3076 	zone_dochandle_t t_handle, char *target_zone)
3077 {
3078 	int err;
3079 	int res = Z_OK;
3080 	int s_cnt = 0;
3081 	int t_cnt = 0;
3082 	struct zone_fstab s_fstab;
3083 	struct zone_fstab t_fstab;
3084 
3085 	/*
3086 	 * First check the source of the clone against the target.
3087 	 */
3088 	if ((err = zonecfg_setipdent(s_handle)) != Z_OK) {
3089 		errno = err;
3090 		zperror2(source_zone, gettext("could not enumerate "
3091 		    "inherit-pkg-dirs"));
3092 		return (Z_ERR);
3093 	}
3094 
3095 	while (zonecfg_getipdent(s_handle, &s_fstab) == Z_OK) {
3096 		boolean_t match = B_FALSE;
3097 
3098 		s_cnt++;
3099 
3100 		if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
3101 			errno = err;
3102 			zperror2(target_zone, gettext("could not enumerate "
3103 			    "inherit-pkg-dirs"));
3104 			(void) zonecfg_endipdent(s_handle);
3105 			return (Z_ERR);
3106 		}
3107 
3108 		while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK) {
3109 			if (strcmp(s_fstab.zone_fs_dir, t_fstab.zone_fs_dir)
3110 			    == 0) {
3111 				match = B_TRUE;
3112 				break;
3113 			}
3114 		}
3115 		(void) zonecfg_endipdent(t_handle);
3116 
3117 		if (!match) {
3118 			(void) fprintf(stderr, gettext("inherit-pkg-dir "
3119 			    "'%s' is not configured in zone %s.\n"),
3120 			    s_fstab.zone_fs_dir, target_zone);
3121 			res = Z_ERR;
3122 		}
3123 	}
3124 
3125 	(void) zonecfg_endipdent(s_handle);
3126 
3127 	/* skip the next check if we already have errors */
3128 	if (res == Z_ERR)
3129 		return (res);
3130 
3131 	/*
3132 	 * Now check the number of ipds in the target so we can verify
3133 	 * that the source is not a subset of the target.
3134 	 */
3135 	if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
3136 		errno = err;
3137 		zperror2(target_zone, gettext("could not enumerate "
3138 		    "inherit-pkg-dirs"));
3139 		return (Z_ERR);
3140 	}
3141 
3142 	while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK)
3143 		t_cnt++;
3144 
3145 	(void) zonecfg_endipdent(t_handle);
3146 
3147 	if (t_cnt != s_cnt) {
3148 		(void) fprintf(stderr, gettext("Zone %s is configured "
3149 		    "with inherit-pkg-dirs that are not configured in zone "
3150 		    "%s.\n"), target_zone, source_zone);
3151 		res = Z_ERR;
3152 	}
3153 
3154 	return (res);
3155 }
3156 
3157 static void
3158 warn_dev_match(zone_dochandle_t s_handle, char *source_zone,
3159 	zone_dochandle_t t_handle, char *target_zone)
3160 {
3161 	int err;
3162 	struct zone_devtab s_devtab;
3163 	struct zone_devtab t_devtab;
3164 
3165 	if ((err = zonecfg_setdevent(t_handle)) != Z_OK) {
3166 		errno = err;
3167 		zperror2(target_zone, gettext("could not enumerate devices"));
3168 		return;
3169 	}
3170 
3171 	while (zonecfg_getdevent(t_handle, &t_devtab) == Z_OK) {
3172 		if ((err = zonecfg_setdevent(s_handle)) != Z_OK) {
3173 			errno = err;
3174 			zperror2(source_zone,
3175 			    gettext("could not enumerate devices"));
3176 			(void) zonecfg_enddevent(t_handle);
3177 			return;
3178 		}
3179 
3180 		while (zonecfg_getdevent(s_handle, &s_devtab) == Z_OK) {
3181 			/*
3182 			 * Use fnmatch to catch the case where wildcards
3183 			 * were used in one zone and the other has an
3184 			 * explicit entry (e.g. /dev/dsk/c0t0d0s6 vs.
3185 			 * /dev/\*dsk/c0t0d0s6).
3186 			 */
3187 			if (fnmatch(t_devtab.zone_dev_match,
3188 			    s_devtab.zone_dev_match, FNM_PATHNAME) == 0 ||
3189 			    fnmatch(s_devtab.zone_dev_match,
3190 			    t_devtab.zone_dev_match, FNM_PATHNAME) == 0) {
3191 				(void) fprintf(stderr,
3192 				    gettext("WARNING: device '%s' "
3193 				    "is configured in both zones.\n"),
3194 				    t_devtab.zone_dev_match);
3195 				break;
3196 			}
3197 		}
3198 		(void) zonecfg_enddevent(s_handle);
3199 	}
3200 
3201 	(void) zonecfg_enddevent(t_handle);
3202 }
3203 
3204 /*
3205  * Check if the specified mount option (opt) is contained within the
3206  * options string.
3207  */
3208 static boolean_t
3209 opt_match(char *opt, char *options)
3210 {
3211 	char *p;
3212 	char *lastp;
3213 
3214 	if ((p = strtok_r(options, ",", &lastp)) != NULL) {
3215 		if (strcmp(p, opt) == 0)
3216 			return (B_TRUE);
3217 		while ((p = strtok_r(NULL, ",", &lastp)) != NULL) {
3218 			if (strcmp(p, opt) == 0)
3219 				return (B_TRUE);
3220 		}
3221 	}
3222 
3223 	return (B_FALSE);
3224 }
3225 
3226 #define	RW_LOFS	"WARNING: read-write lofs file system on '%s' is configured " \
3227 	"in both zones.\n"
3228 
3229 static void
3230 print_fs_warnings(struct zone_fstab *s_fstab, struct zone_fstab *t_fstab)
3231 {
3232 	/*
3233 	 * It is ok to have shared lofs mounted fs but we want to warn if
3234 	 * either is rw since this will effect the other zone.
3235 	 */
3236 	if (strcmp(t_fstab->zone_fs_type, "lofs") == 0) {
3237 		zone_fsopt_t *optp;
3238 
3239 		/* The default is rw so no options means rw */
3240 		if (t_fstab->zone_fs_options == NULL ||
3241 		    s_fstab->zone_fs_options == NULL) {
3242 			(void) fprintf(stderr, gettext(RW_LOFS),
3243 			    t_fstab->zone_fs_special);
3244 			return;
3245 		}
3246 
3247 		for (optp = s_fstab->zone_fs_options; optp != NULL;
3248 		    optp = optp->zone_fsopt_next) {
3249 			if (opt_match("rw", optp->zone_fsopt_opt)) {
3250 				(void) fprintf(stderr, gettext(RW_LOFS),
3251 				    s_fstab->zone_fs_special);
3252 				return;
3253 			}
3254 		}
3255 
3256 		for (optp = t_fstab->zone_fs_options; optp != NULL;
3257 		    optp = optp->zone_fsopt_next) {
3258 			if (opt_match("rw", optp->zone_fsopt_opt)) {
3259 				(void) fprintf(stderr, gettext(RW_LOFS),
3260 				    t_fstab->zone_fs_special);
3261 				return;
3262 			}
3263 		}
3264 
3265 		return;
3266 	}
3267 
3268 	/*
3269 	 * TRANSLATION_NOTE
3270 	 * The first variable is the file system type and the second is
3271 	 * the file system special device.  For example,
3272 	 * WARNING: ufs file system on '/dev/dsk/c0t0d0s0' ...
3273 	 */
3274 	(void) fprintf(stderr, gettext("WARNING: %s file system on '%s' "
3275 	    "is configured in both zones.\n"), t_fstab->zone_fs_type,
3276 	    t_fstab->zone_fs_special);
3277 }
3278 
3279 static void
3280 warn_fs_match(zone_dochandle_t s_handle, char *source_zone,
3281 	zone_dochandle_t t_handle, char *target_zone)
3282 {
3283 	int err;
3284 	struct zone_fstab s_fstab;
3285 	struct zone_fstab t_fstab;
3286 
3287 	if ((err = zonecfg_setfsent(t_handle)) != Z_OK) {
3288 		errno = err;
3289 		zperror2(target_zone,
3290 		    gettext("could not enumerate file systems"));
3291 		return;
3292 	}
3293 
3294 	while (zonecfg_getfsent(t_handle, &t_fstab) == Z_OK) {
3295 		if ((err = zonecfg_setfsent(s_handle)) != Z_OK) {
3296 			errno = err;
3297 			zperror2(source_zone,
3298 			    gettext("could not enumerate file systems"));
3299 			(void) zonecfg_endfsent(t_handle);
3300 			return;
3301 		}
3302 
3303 		while (zonecfg_getfsent(s_handle, &s_fstab) == Z_OK) {
3304 			if (strcmp(t_fstab.zone_fs_special,
3305 			    s_fstab.zone_fs_special) == 0) {
3306 				print_fs_warnings(&s_fstab, &t_fstab);
3307 				break;
3308 			}
3309 		}
3310 		(void) zonecfg_endfsent(s_handle);
3311 	}
3312 
3313 	(void) zonecfg_endfsent(t_handle);
3314 }
3315 
3316 /*
3317  * We don't catch the case where you used the same IP address but
3318  * it is not an exact string match.  For example, 192.9.0.128 vs. 192.09.0.128.
3319  * However, we're not going to worry about that but we will check for
3320  * a possible netmask on one of the addresses (e.g. 10.0.0.1 and 10.0.0.1/24)
3321  * and handle that case as a match.
3322  */
3323 static void
3324 warn_ip_match(zone_dochandle_t s_handle, char *source_zone,
3325 	zone_dochandle_t t_handle, char *target_zone)
3326 {
3327 	int err;
3328 	struct zone_nwiftab s_nwiftab;
3329 	struct zone_nwiftab t_nwiftab;
3330 
3331 	if ((err = zonecfg_setnwifent(t_handle)) != Z_OK) {
3332 		errno = err;
3333 		zperror2(target_zone,
3334 		    gettext("could not enumerate network interfaces"));
3335 		return;
3336 	}
3337 
3338 	while (zonecfg_getnwifent(t_handle, &t_nwiftab) == Z_OK) {
3339 		char *p;
3340 
3341 		/* remove an (optional) netmask from the address */
3342 		if ((p = strchr(t_nwiftab.zone_nwif_address, '/')) != NULL)
3343 			*p = '\0';
3344 
3345 		if ((err = zonecfg_setnwifent(s_handle)) != Z_OK) {
3346 			errno = err;
3347 			zperror2(source_zone,
3348 			    gettext("could not enumerate network interfaces"));
3349 			(void) zonecfg_endnwifent(t_handle);
3350 			return;
3351 		}
3352 
3353 		while (zonecfg_getnwifent(s_handle, &s_nwiftab) == Z_OK) {
3354 			/* remove an (optional) netmask from the address */
3355 			if ((p = strchr(s_nwiftab.zone_nwif_address, '/'))
3356 			    != NULL)
3357 				*p = '\0';
3358 
3359 			/* For exclusive-IP zones, address is not specified. */
3360 			if (strlen(s_nwiftab.zone_nwif_address) == 0)
3361 				continue;
3362 
3363 			if (strcmp(t_nwiftab.zone_nwif_address,
3364 			    s_nwiftab.zone_nwif_address) == 0) {
3365 				(void) fprintf(stderr,
3366 				    gettext("WARNING: network address '%s' "
3367 				    "is configured in both zones.\n"),
3368 				    t_nwiftab.zone_nwif_address);
3369 				break;
3370 			}
3371 		}
3372 		(void) zonecfg_endnwifent(s_handle);
3373 	}
3374 
3375 	(void) zonecfg_endnwifent(t_handle);
3376 }
3377 
3378 static void
3379 warn_dataset_match(zone_dochandle_t s_handle, char *source,
3380 	zone_dochandle_t t_handle, char *target)
3381 {
3382 	int err;
3383 	struct zone_dstab s_dstab;
3384 	struct zone_dstab t_dstab;
3385 
3386 	if ((err = zonecfg_setdsent(t_handle)) != Z_OK) {
3387 		errno = err;
3388 		zperror2(target, gettext("could not enumerate datasets"));
3389 		return;
3390 	}
3391 
3392 	while (zonecfg_getdsent(t_handle, &t_dstab) == Z_OK) {
3393 		if ((err = zonecfg_setdsent(s_handle)) != Z_OK) {
3394 			errno = err;
3395 			zperror2(source,
3396 			    gettext("could not enumerate datasets"));
3397 			(void) zonecfg_enddsent(t_handle);
3398 			return;
3399 		}
3400 
3401 		while (zonecfg_getdsent(s_handle, &s_dstab) == Z_OK) {
3402 			if (strcmp(t_dstab.zone_dataset_name,
3403 			    s_dstab.zone_dataset_name) == 0) {
3404 				target_zone = source;
3405 				zerror(gettext("WARNING: dataset '%s' "
3406 				    "is configured in both zones.\n"),
3407 				    t_dstab.zone_dataset_name);
3408 				break;
3409 			}
3410 		}
3411 		(void) zonecfg_enddsent(s_handle);
3412 	}
3413 
3414 	(void) zonecfg_enddsent(t_handle);
3415 }
3416 
3417 /*
3418  * Check that the clone and its source have the same brand type.
3419  */
3420 static int
3421 valid_brand_clone(char *source_zone, char *target_zone)
3422 {
3423 	brand_handle_t bh;
3424 	char source_brand[MAXNAMELEN];
3425 
3426 	if ((zone_get_brand(source_zone, source_brand,
3427 	    sizeof (source_brand))) != Z_OK) {
3428 		(void) fprintf(stderr, "%s: zone '%s': %s\n",
3429 		    execname, source_zone, gettext("missing or invalid brand"));
3430 		return (Z_ERR);
3431 	}
3432 
3433 	if (strcmp(source_brand, target_brand) != NULL) {
3434 		(void) fprintf(stderr,
3435 		    gettext("%s: Zones '%s' and '%s' have different brand "
3436 		    "types.\n"), execname, source_zone, target_zone);
3437 		return (Z_ERR);
3438 	}
3439 
3440 	if ((bh = brand_open(target_brand)) == NULL) {
3441 		zerror(gettext("missing or invalid brand"));
3442 		return (Z_ERR);
3443 	}
3444 	brand_close(bh);
3445 	return (Z_OK);
3446 }
3447 
3448 static int
3449 validate_clone(char *source_zone, char *target_zone)
3450 {
3451 	int err = Z_OK;
3452 	zone_dochandle_t s_handle;
3453 	zone_dochandle_t t_handle;
3454 
3455 	if ((t_handle = zonecfg_init_handle()) == NULL) {
3456 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3457 		return (Z_ERR);
3458 	}
3459 	if ((err = zonecfg_get_handle(target_zone, t_handle)) != Z_OK) {
3460 		errno = err;
3461 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3462 		zonecfg_fini_handle(t_handle);
3463 		return (Z_ERR);
3464 	}
3465 
3466 	if ((s_handle = zonecfg_init_handle()) == NULL) {
3467 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3468 		zonecfg_fini_handle(t_handle);
3469 		return (Z_ERR);
3470 	}
3471 	if ((err = zonecfg_get_handle(source_zone, s_handle)) != Z_OK) {
3472 		errno = err;
3473 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3474 		goto done;
3475 	}
3476 
3477 	/* verify new zone has same brand type */
3478 	err = valid_brand_clone(source_zone, target_zone);
3479 	if (err != Z_OK)
3480 		goto done;
3481 
3482 	/* verify new zone has same inherit-pkg-dirs */
3483 	err = valid_ipd_clone(s_handle, source_zone, t_handle, target_zone);
3484 
3485 	/* warn about imported fs's which are the same */
3486 	warn_fs_match(s_handle, source_zone, t_handle, target_zone);
3487 
3488 	/* warn about imported IP addresses which are the same */
3489 	warn_ip_match(s_handle, source_zone, t_handle, target_zone);
3490 
3491 	/* warn about imported devices which are the same */
3492 	warn_dev_match(s_handle, source_zone, t_handle, target_zone);
3493 
3494 	/* warn about imported datasets which are the same */
3495 	warn_dataset_match(s_handle, source_zone, t_handle, target_zone);
3496 
3497 done:
3498 	zonecfg_fini_handle(t_handle);
3499 	zonecfg_fini_handle(s_handle);
3500 
3501 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3502 }
3503 
3504 static int
3505 copy_zone(char *src, char *dst)
3506 {
3507 	boolean_t out_null = B_FALSE;
3508 	int status;
3509 	char *outfile;
3510 	char cmdbuf[MAXPATHLEN * 2 + 128];
3511 
3512 	if ((outfile = tempnam("/var/log", "zone")) == NULL) {
3513 		outfile = "/dev/null";
3514 		out_null = B_TRUE;
3515 	}
3516 
3517 	/*
3518 	 * Use find to get the list of files to copy.  We need to skip
3519 	 * files of type "socket" since cpio can't handle those but that
3520 	 * should be ok since the app will recreate the socket when it runs.
3521 	 * We also need to filter out anything under the .zfs subdir.  Since
3522 	 * find is running depth-first, we need the extra egrep to filter .zfs.
3523 	 */
3524 	(void) snprintf(cmdbuf, sizeof (cmdbuf),
3525 	    "cd %s && /usr/bin/find . -type s -prune -o -depth -print | "
3526 	    "/usr/bin/egrep -v '^\\./\\.zfs$|^\\./\\.zfs/' | "
3527 	    "/usr/bin/cpio -pdmuP@ %s > %s 2>&1",
3528 	    src, dst, outfile);
3529 
3530 	status = do_subproc(cmdbuf);
3531 
3532 	if (subproc_status("copy", status, B_TRUE) != ZONE_SUBPROC_OK) {
3533 		if (!out_null)
3534 			(void) fprintf(stderr, gettext("\nThe copy failed.\n"
3535 			    "More information can be found in %s\n"), outfile);
3536 		return (Z_ERR);
3537 	}
3538 
3539 	if (!out_null)
3540 		(void) unlink(outfile);
3541 
3542 	return (Z_OK);
3543 }
3544 
3545 /* ARGSUSED */
3546 static int
3547 zfm_print(const char *p, void *r) {
3548 	zerror("  %s\n", p);
3549 	return (0);
3550 }
3551 
3552 int
3553 clone_copy(char *source_zonepath, char *zonepath)
3554 {
3555 	int err;
3556 
3557 	/* Don't clone the zone if anything is still mounted there */
3558 	if (zonecfg_find_mounts(source_zonepath, NULL, NULL)) {
3559 		zerror(gettext("These file systems are mounted on "
3560 		    "subdirectories of %s.\n"), source_zonepath);
3561 		(void) zonecfg_find_mounts(source_zonepath, zfm_print, NULL);
3562 		return (Z_ERR);
3563 	}
3564 
3565 	/*
3566 	 * Attempt to create a ZFS fs for the zonepath.  As usual, we don't
3567 	 * care if this works or not since we always have the default behavior
3568 	 * of a simple directory for the zonepath.
3569 	 */
3570 	create_zfs_zonepath(zonepath);
3571 
3572 	(void) printf(gettext("Copying %s..."), source_zonepath);
3573 	(void) fflush(stdout);
3574 
3575 	err = copy_zone(source_zonepath, zonepath);
3576 
3577 	(void) printf("\n");
3578 
3579 	return (err);
3580 }
3581 
3582 static int
3583 clone_func(int argc, char *argv[])
3584 {
3585 	char *source_zone = NULL;
3586 	int lockfd;
3587 	int err, arg;
3588 	char zonepath[MAXPATHLEN];
3589 	char source_zonepath[MAXPATHLEN];
3590 	zone_state_t state;
3591 	zone_entry_t *zent;
3592 	char *method = NULL;
3593 	char *snapshot = NULL;
3594 	char cmdbuf[MAXPATHLEN];
3595 	char postcmdbuf[MAXPATHLEN];
3596 	char presnapbuf[MAXPATHLEN];
3597 	char postsnapbuf[MAXPATHLEN];
3598 	char validsnapbuf[MAXPATHLEN];
3599 	brand_handle_t bh = NULL;
3600 	int status;
3601 	boolean_t brand_help = B_FALSE;
3602 
3603 	if (zonecfg_in_alt_root()) {
3604 		zerror(gettext("cannot clone zone in alternate root"));
3605 		return (Z_ERR);
3606 	}
3607 
3608 	/* Check the argv string for args we handle internally */
3609 	optind = 0;
3610 	opterr = 0;
3611 	while ((arg = getopt(argc, argv, "?m:s:")) != EOF) {
3612 		switch (arg) {
3613 		case '?':
3614 			if (optopt == '?') {
3615 				sub_usage(SHELP_CLONE, CMD_CLONE);
3616 				brand_help = B_TRUE;
3617 			}
3618 			/* Ignore unknown options - may be brand specific. */
3619 			break;
3620 		case 'm':
3621 			method = optarg;
3622 			break;
3623 		case 's':
3624 			snapshot = optarg;
3625 			break;
3626 		default:
3627 			/* Ignore unknown options - may be brand specific. */
3628 			break;
3629 		}
3630 	}
3631 
3632 	if (argc != (optind + 1)) {
3633 		sub_usage(SHELP_CLONE, CMD_CLONE);
3634 		return (Z_USAGE);
3635 	}
3636 
3637 	source_zone = argv[optind];
3638 
3639 	if (!brand_help) {
3640 		if (sanity_check(target_zone, CMD_CLONE, B_FALSE, B_TRUE,
3641 		    B_FALSE) != Z_OK)
3642 			return (Z_ERR);
3643 		if (verify_details(CMD_CLONE, argv) != Z_OK)
3644 			return (Z_ERR);
3645 
3646 		/*
3647 		 * We also need to do some extra validation on the source zone.
3648 		 */
3649 		if (strcmp(source_zone, GLOBAL_ZONENAME) == 0) {
3650 			zerror(gettext("%s operation is invalid for the "
3651 			    "global zone."), cmd_to_str(CMD_CLONE));
3652 			return (Z_ERR);
3653 		}
3654 
3655 		if (strncmp(source_zone, "SUNW", 4) == 0) {
3656 			zerror(gettext("%s operation is invalid for zones "
3657 			    "starting with SUNW."), cmd_to_str(CMD_CLONE));
3658 			return (Z_ERR);
3659 		}
3660 
3661 		zent = lookup_running_zone(source_zone);
3662 		if (zent != NULL) {
3663 			/* check whether the zone is ready or running */
3664 			if ((err = zone_get_state(zent->zname,
3665 			    &zent->zstate_num)) != Z_OK) {
3666 				errno = err;
3667 				zperror2(zent->zname, gettext("could not get "
3668 				    "state"));
3669 				/* can't tell, so hedge */
3670 				zent->zstate_str = "ready/running";
3671 			} else {
3672 				zent->zstate_str =
3673 				    zone_state_str(zent->zstate_num);
3674 			}
3675 			zerror(gettext("%s operation is invalid for %s zones."),
3676 			    cmd_to_str(CMD_CLONE), zent->zstate_str);
3677 			return (Z_ERR);
3678 		}
3679 
3680 		if ((err = zone_get_state(source_zone, &state)) != Z_OK) {
3681 			errno = err;
3682 			zperror2(source_zone, gettext("could not get state"));
3683 			return (Z_ERR);
3684 		}
3685 		if (state != ZONE_STATE_INSTALLED) {
3686 			(void) fprintf(stderr,
3687 			    gettext("%s: zone %s is %s; %s is required.\n"),
3688 			    execname, source_zone, zone_state_str(state),
3689 			    zone_state_str(ZONE_STATE_INSTALLED));
3690 			return (Z_ERR);
3691 		}
3692 
3693 		/*
3694 		 * The source zone checks out ok, continue with the clone.
3695 		 */
3696 
3697 		if (validate_clone(source_zone, target_zone) != Z_OK)
3698 			return (Z_ERR);
3699 
3700 		if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
3701 			zerror(gettext("another %s may have an operation in "
3702 			    "progress."), "zoneadm");
3703 			return (Z_ERR);
3704 		}
3705 	}
3706 
3707 	if ((err = zone_get_zonepath(source_zone, source_zonepath,
3708 	    sizeof (source_zonepath))) != Z_OK) {
3709 		errno = err;
3710 		zperror2(source_zone, gettext("could not get zone path"));
3711 		goto done;
3712 	}
3713 
3714 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3715 	    != Z_OK) {
3716 		errno = err;
3717 		zperror2(target_zone, gettext("could not get zone path"));
3718 		goto done;
3719 	}
3720 
3721 	/*
3722 	 * Fetch the clone and postclone hooks from the brand configuration.
3723 	 */
3724 	if ((bh = brand_open(target_brand)) == NULL) {
3725 		zerror(gettext("missing or invalid brand"));
3726 		err = Z_ERR;
3727 		goto done;
3728 	}
3729 
3730 	if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_clone, target_zone,
3731 	    zonepath) != Z_OK) {
3732 		zerror("invalid brand configuration: missing clone resource");
3733 		brand_close(bh);
3734 		err = Z_ERR;
3735 		goto done;
3736 	}
3737 
3738 	if (get_hook(bh, postcmdbuf, sizeof (postcmdbuf), brand_get_postclone,
3739 	    target_zone, zonepath) != Z_OK) {
3740 		zerror("invalid brand configuration: missing postclone "
3741 		    "resource");
3742 		brand_close(bh);
3743 		err = Z_ERR;
3744 		goto done;
3745 	}
3746 
3747 	if (get_hook(bh, presnapbuf, sizeof (presnapbuf), brand_get_presnap,
3748 	    source_zone, source_zonepath) != Z_OK) {
3749 		zerror("invalid brand configuration: missing presnap "
3750 		    "resource");
3751 		brand_close(bh);
3752 		err = Z_ERR;
3753 		goto done;
3754 	}
3755 
3756 	if (get_hook(bh, postsnapbuf, sizeof (postsnapbuf), brand_get_postsnap,
3757 	    source_zone, source_zonepath) != Z_OK) {
3758 		zerror("invalid brand configuration: missing postsnap "
3759 		    "resource");
3760 		brand_close(bh);
3761 		err = Z_ERR;
3762 		goto done;
3763 	}
3764 
3765 	if (get_hook(bh, validsnapbuf, sizeof (validsnapbuf),
3766 	    brand_get_validatesnap, target_zone, zonepath) != Z_OK) {
3767 		zerror("invalid brand configuration: missing validatesnap "
3768 		    "resource");
3769 		brand_close(bh);
3770 		err = Z_ERR;
3771 		goto done;
3772 	}
3773 	brand_close(bh);
3774 
3775 	/* Append all options to clone hook. */
3776 	if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK) {
3777 		err = Z_ERR;
3778 		goto done;
3779 	}
3780 
3781 	/* Append all options to postclone hook. */
3782 	if (addoptions(postcmdbuf, argv, sizeof (postcmdbuf)) != Z_OK) {
3783 		err = Z_ERR;
3784 		goto done;
3785 	}
3786 
3787 	if (!brand_help) {
3788 		if ((err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE))
3789 		    != Z_OK) {
3790 			errno = err;
3791 			zperror2(target_zone, gettext("could not set state"));
3792 			goto done;
3793 		}
3794 	}
3795 
3796 	/*
3797 	 * The clone hook is optional.  If it exists, use the hook for
3798 	 * cloning, otherwise use the built-in clone support
3799 	 */
3800 	if (cmdbuf[0] != '\0') {
3801 		/* Run the clone hook */
3802 		status = do_subproc_interactive(cmdbuf);
3803 		if ((status = subproc_status(gettext("brand-specific clone"),
3804 		    status, B_FALSE)) != ZONE_SUBPROC_OK) {
3805 			if (status == ZONE_SUBPROC_USAGE && !brand_help)
3806 				sub_usage(SHELP_CLONE, CMD_CLONE);
3807 			err = Z_ERR;
3808 			goto done;
3809 		}
3810 
3811 		if (brand_help)
3812 			return (Z_OK);
3813 
3814 	} else {
3815 		/* If just help, we're done since there is no brand help. */
3816 		if (brand_help)
3817 			return (Z_OK);
3818 
3819 		/* Run the built-in clone support. */
3820 
3821 		/* The only explicit built-in method is "copy". */
3822 		if (method != NULL && strcmp(method, "copy") != 0) {
3823 			sub_usage(SHELP_CLONE, CMD_CLONE);
3824 			err = Z_USAGE;
3825 			goto done;
3826 		}
3827 
3828 		if (snapshot != NULL) {
3829 			err = clone_snapshot_zfs(snapshot, zonepath,
3830 			    validsnapbuf);
3831 		} else {
3832 			/*
3833 			 * We always copy the clone unless the source is ZFS
3834 			 * and a ZFS clone worked.  We fallback to copying if
3835 			 * the ZFS clone fails for some reason.
3836 			 */
3837 			err = Z_ERR;
3838 			if (method == NULL && is_zonepath_zfs(source_zonepath))
3839 				err = clone_zfs(source_zonepath, zonepath,
3840 				    presnapbuf, postsnapbuf);
3841 
3842 			if (err != Z_OK)
3843 				err = clone_copy(source_zonepath, zonepath);
3844 		}
3845 	}
3846 
3847 	if (err == Z_OK && postcmdbuf[0] != '\0') {
3848 		status = do_subproc(postcmdbuf);
3849 		if ((err = subproc_status("postclone", status, B_FALSE))
3850 		    != ZONE_SUBPROC_OK) {
3851 			zerror(gettext("post-clone configuration failed."));
3852 			err = Z_ERR;
3853 		}
3854 	}
3855 
3856 done:
3857 	/*
3858 	 * If everything went well, we mark the zone as installed.
3859 	 */
3860 	if (err == Z_OK) {
3861 		err = zone_set_state(target_zone, ZONE_STATE_INSTALLED);
3862 		if (err != Z_OK) {
3863 			errno = err;
3864 			zperror2(target_zone, gettext("could not set state"));
3865 		}
3866 	}
3867 	if (!brand_help)
3868 		zonecfg_release_lock_file(target_zone, lockfd);
3869 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3870 }
3871 
3872 /*
3873  * Used when removing a zonepath after uninstalling or cleaning up after
3874  * the move subcommand.  This handles a zonepath that has non-standard
3875  * contents so that we will only cleanup the stuff we know about and leave
3876  * any user data alone.
3877  *
3878  * If the "all" parameter is true then we should remove the whole zonepath
3879  * even if it has non-standard files/directories in it.  This can be used when
3880  * we need to cleanup after moving the zonepath across file systems.
3881  *
3882  * We "exec" the RMCOMMAND so that the returned status is that of RMCOMMAND
3883  * and not the shell.
3884  */
3885 static int
3886 cleanup_zonepath(char *zonepath, boolean_t all)
3887 {
3888 	int		status;
3889 	int		i;
3890 	boolean_t	non_std = B_FALSE;
3891 	struct dirent	*dp;
3892 	DIR		*dirp;
3893 			/*
3894 			 * The SUNWattached.xml file is expected since it might
3895 			 * exist if the zone was force-attached after a
3896 			 * migration.
3897 			 */
3898 	char		*std_entries[] = {"dev", "lu", "root",
3899 			    "SUNWattached.xml", NULL};
3900 			/* (MAXPATHLEN * 3) is for the 3 std_entries dirs */
3901 	char		cmdbuf[sizeof (RMCOMMAND) + (MAXPATHLEN * 3) + 64];
3902 
3903 	/*
3904 	 * We shouldn't need these checks but lets be paranoid since we
3905 	 * could blow away the whole system here if we got the wrong zonepath.
3906 	 */
3907 	if (*zonepath == NULL || strcmp(zonepath, "/") == 0) {
3908 		(void) fprintf(stderr, "invalid zonepath '%s'\n", zonepath);
3909 		return (Z_INVAL);
3910 	}
3911 
3912 	/*
3913 	 * If the dirpath is already gone (maybe it was manually removed) then
3914 	 * we just return Z_OK so that the cleanup is successful.
3915 	 */
3916 	if ((dirp = opendir(zonepath)) == NULL)
3917 		return (Z_OK);
3918 
3919 	/*
3920 	 * Look through the zonepath directory to see if there are any
3921 	 * non-standard files/dirs.  Also skip .zfs since that might be
3922 	 * there but we'll handle ZFS file systems as a special case.
3923 	 */
3924 	while ((dp = readdir(dirp)) != NULL) {
3925 		if (strcmp(dp->d_name, ".") == 0 ||
3926 		    strcmp(dp->d_name, "..") == 0 ||
3927 		    strcmp(dp->d_name, ".zfs") == 0)
3928 			continue;
3929 
3930 		for (i = 0; std_entries[i] != NULL; i++)
3931 			if (strcmp(dp->d_name, std_entries[i]) == 0)
3932 				break;
3933 
3934 		if (std_entries[i] == NULL)
3935 			non_std = B_TRUE;
3936 	}
3937 	(void) closedir(dirp);
3938 
3939 	if (!all && non_std) {
3940 		/*
3941 		 * There are extra, non-standard directories/files in the
3942 		 * zonepath so we don't want to remove the zonepath.  We
3943 		 * just want to remove the standard directories and leave
3944 		 * the user data alone.
3945 		 */
3946 		(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND);
3947 
3948 		for (i = 0; std_entries[i] != NULL; i++) {
3949 			char tmpbuf[MAXPATHLEN];
3950 
3951 			if (snprintf(tmpbuf, sizeof (tmpbuf), " %s/%s",
3952 			    zonepath, std_entries[i]) >= sizeof (tmpbuf) ||
3953 			    strlcat(cmdbuf, tmpbuf, sizeof (cmdbuf)) >=
3954 			    sizeof (cmdbuf)) {
3955 				(void) fprintf(stderr,
3956 				    gettext("path is too long\n"));
3957 				return (Z_INVAL);
3958 			}
3959 		}
3960 
3961 		status = do_subproc(cmdbuf);
3962 
3963 		(void) fprintf(stderr, gettext("WARNING: Unable to completely "
3964 		    "remove %s\nbecause it contains additional user data.  "
3965 		    "Only the standard directory\nentries have been "
3966 		    "removed.\n"),
3967 		    zonepath);
3968 
3969 		return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
3970 		    ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
3971 	}
3972 
3973 	/*
3974 	 * There is nothing unexpected in the zonepath, try to get rid of the
3975 	 * whole zonepath directory.
3976 	 *
3977 	 * If the zonepath is its own zfs file system, try to destroy the
3978 	 * file system.  If that fails for some reason (e.g. it has clones)
3979 	 * then we'll just remove the contents of the zonepath.
3980 	 */
3981 	if (is_zonepath_zfs(zonepath)) {
3982 		if (destroy_zfs(zonepath) == Z_OK)
3983 			return (Z_OK);
3984 		(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND
3985 		    " %s/*", zonepath);
3986 		status = do_subproc(cmdbuf);
3987 		return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
3988 		    ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
3989 	}
3990 
3991 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
3992 	    zonepath);
3993 	status = do_subproc(cmdbuf);
3994 
3995 	return ((subproc_status(RMCOMMAND, status, B_TRUE) == ZONE_SUBPROC_OK)
3996 	    ? Z_OK : Z_ERR);
3997 }
3998 
3999 static int
4000 move_func(int argc, char *argv[])
4001 {
4002 	char *new_zonepath = NULL;
4003 	int lockfd;
4004 	int err, arg;
4005 	char zonepath[MAXPATHLEN];
4006 	zone_dochandle_t handle;
4007 	boolean_t fast;
4008 	boolean_t is_zfs = B_FALSE;
4009 	struct dirent *dp;
4010 	DIR *dirp;
4011 	boolean_t empty = B_TRUE;
4012 	boolean_t revert;
4013 	struct stat zonepath_buf;
4014 	struct stat new_zonepath_buf;
4015 
4016 	if (zonecfg_in_alt_root()) {
4017 		zerror(gettext("cannot move zone in alternate root"));
4018 		return (Z_ERR);
4019 	}
4020 
4021 	optind = 0;
4022 	if ((arg = getopt(argc, argv, "?")) != EOF) {
4023 		switch (arg) {
4024 		case '?':
4025 			sub_usage(SHELP_MOVE, CMD_MOVE);
4026 			return (optopt == '?' ? Z_OK : Z_USAGE);
4027 		default:
4028 			sub_usage(SHELP_MOVE, CMD_MOVE);
4029 			return (Z_USAGE);
4030 		}
4031 	}
4032 	if (argc != (optind + 1)) {
4033 		sub_usage(SHELP_MOVE, CMD_MOVE);
4034 		return (Z_USAGE);
4035 	}
4036 	new_zonepath = argv[optind];
4037 	if (sanity_check(target_zone, CMD_MOVE, B_FALSE, B_TRUE, B_FALSE)
4038 	    != Z_OK)
4039 		return (Z_ERR);
4040 	if (verify_details(CMD_MOVE, argv) != Z_OK)
4041 		return (Z_ERR);
4042 
4043 	/*
4044 	 * Check out the new zonepath.  This has the side effect of creating
4045 	 * a directory for the new zonepath.  We depend on this later when we
4046 	 * stat to see if we are doing a cross file system move or not.
4047 	 */
4048 	if (validate_zonepath(new_zonepath, CMD_MOVE) != Z_OK)
4049 		return (Z_ERR);
4050 
4051 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4052 	    != Z_OK) {
4053 		errno = err;
4054 		zperror2(target_zone, gettext("could not get zone path"));
4055 		return (Z_ERR);
4056 	}
4057 
4058 	if (stat(zonepath, &zonepath_buf) == -1) {
4059 		zperror(gettext("could not stat zone path"), B_FALSE);
4060 		return (Z_ERR);
4061 	}
4062 
4063 	if (stat(new_zonepath, &new_zonepath_buf) == -1) {
4064 		zperror(gettext("could not stat new zone path"), B_FALSE);
4065 		return (Z_ERR);
4066 	}
4067 
4068 	/*
4069 	 * Check if the destination directory is empty.
4070 	 */
4071 	if ((dirp = opendir(new_zonepath)) == NULL) {
4072 		zperror(gettext("could not open new zone path"), B_FALSE);
4073 		return (Z_ERR);
4074 	}
4075 	while ((dp = readdir(dirp)) != (struct dirent *)0) {
4076 		if (strcmp(dp->d_name, ".") == 0 ||
4077 		    strcmp(dp->d_name, "..") == 0)
4078 			continue;
4079 		empty = B_FALSE;
4080 		break;
4081 	}
4082 	(void) closedir(dirp);
4083 
4084 	/* Error if there is anything in the destination directory. */
4085 	if (!empty) {
4086 		(void) fprintf(stderr, gettext("could not move zone to %s: "
4087 		    "directory not empty\n"), new_zonepath);
4088 		return (Z_ERR);
4089 	}
4090 
4091 	/* Don't move the zone if anything is still mounted there */
4092 	if (zonecfg_find_mounts(zonepath, NULL, NULL)) {
4093 		zerror(gettext("These file systems are mounted on "
4094 		    "subdirectories of %s.\n"), zonepath);
4095 		(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
4096 		return (Z_ERR);
4097 	}
4098 
4099 	/*
4100 	 * Check if we are moving in the same file system and can do a fast
4101 	 * move or if we are crossing file systems and have to copy the data.
4102 	 */
4103 	fast = (zonepath_buf.st_dev == new_zonepath_buf.st_dev);
4104 
4105 	if ((handle = zonecfg_init_handle()) == NULL) {
4106 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4107 		return (Z_ERR);
4108 	}
4109 
4110 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4111 		errno = err;
4112 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4113 		zonecfg_fini_handle(handle);
4114 		return (Z_ERR);
4115 	}
4116 
4117 	if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4118 		zerror(gettext("another %s may have an operation in progress."),
4119 		    "zoneadm");
4120 		zonecfg_fini_handle(handle);
4121 		return (Z_ERR);
4122 	}
4123 
4124 	/*
4125 	 * We're making some file system changes now so we have to clean up
4126 	 * the file system before we are done.  This will either clean up the
4127 	 * new zonepath if the zonecfg update failed or it will clean up the
4128 	 * old zonepath if everything is ok.
4129 	 */
4130 	revert = B_TRUE;
4131 
4132 	if (is_zonepath_zfs(zonepath) &&
4133 	    move_zfs(zonepath, new_zonepath) != Z_ERR) {
4134 		is_zfs = B_TRUE;
4135 
4136 	} else if (fast) {
4137 		/* same file system, use rename for a quick move */
4138 
4139 		/*
4140 		 * Remove the new_zonepath directory that got created above
4141 		 * during the validation.  It gets in the way of the rename.
4142 		 */
4143 		if (rmdir(new_zonepath) != 0) {
4144 			zperror(gettext("could not rmdir new zone path"),
4145 			    B_FALSE);
4146 			zonecfg_fini_handle(handle);
4147 			zonecfg_release_lock_file(target_zone, lockfd);
4148 			return (Z_ERR);
4149 		}
4150 
4151 		if (rename(zonepath, new_zonepath) != 0) {
4152 			/*
4153 			 * If this fails we don't need to do all of the
4154 			 * cleanup that happens for the rest of the code
4155 			 * so just return from this error.
4156 			 */
4157 			zperror(gettext("could not move zone"), B_FALSE);
4158 			zonecfg_fini_handle(handle);
4159 			zonecfg_release_lock_file(target_zone, lockfd);
4160 			return (Z_ERR);
4161 		}
4162 
4163 	} else {
4164 		/*
4165 		 * Attempt to create a ZFS fs for the new zonepath.  As usual,
4166 		 * we don't care if this works or not since we always have the
4167 		 * default behavior of a simple directory for the zonepath.
4168 		 */
4169 		create_zfs_zonepath(new_zonepath);
4170 
4171 		(void) printf(gettext(
4172 		    "Moving across file systems; copying zonepath %s..."),
4173 		    zonepath);
4174 		(void) fflush(stdout);
4175 
4176 		err = copy_zone(zonepath, new_zonepath);
4177 
4178 		(void) printf("\n");
4179 		if (err != Z_OK)
4180 			goto done;
4181 	}
4182 
4183 	if ((err = zonecfg_set_zonepath(handle, new_zonepath)) != Z_OK) {
4184 		errno = err;
4185 		zperror(gettext("could not set new zonepath"), B_TRUE);
4186 		goto done;
4187 	}
4188 
4189 	if ((err = zonecfg_save(handle)) != Z_OK) {
4190 		errno = err;
4191 		zperror(gettext("zonecfg save failed"), B_TRUE);
4192 		goto done;
4193 	}
4194 
4195 	revert = B_FALSE;
4196 
4197 done:
4198 	zonecfg_fini_handle(handle);
4199 	zonecfg_release_lock_file(target_zone, lockfd);
4200 
4201 	/*
4202 	 * Clean up the file system based on how things went.  We either
4203 	 * clean up the new zonepath if the operation failed for some reason
4204 	 * or we clean up the old zonepath if everything is ok.
4205 	 */
4206 	if (revert) {
4207 		/* The zonecfg update failed, cleanup the new zonepath. */
4208 		if (is_zfs) {
4209 			if (move_zfs(new_zonepath, zonepath) == Z_ERR) {
4210 				(void) fprintf(stderr, gettext("could not "
4211 				    "restore zonepath, the zfs mountpoint is "
4212 				    "set as:\n%s\n"), new_zonepath);
4213 				/*
4214 				 * err is already != Z_OK since we're reverting
4215 				 */
4216 			}
4217 
4218 		} else if (fast) {
4219 			if (rename(new_zonepath, zonepath) != 0) {
4220 				zperror(gettext("could not restore zonepath"),
4221 				    B_FALSE);
4222 				/*
4223 				 * err is already != Z_OK since we're reverting
4224 				 */
4225 			}
4226 		} else {
4227 			(void) printf(gettext("Cleaning up zonepath %s..."),
4228 			    new_zonepath);
4229 			(void) fflush(stdout);
4230 			err = cleanup_zonepath(new_zonepath, B_TRUE);
4231 			(void) printf("\n");
4232 
4233 			if (err != Z_OK) {
4234 				errno = err;
4235 				zperror(gettext("could not remove new "
4236 				    "zonepath"), B_TRUE);
4237 			} else {
4238 				/*
4239 				 * Because we're reverting we know the mainline
4240 				 * code failed but we just reused the err
4241 				 * variable so we reset it back to Z_ERR.
4242 				 */
4243 				err = Z_ERR;
4244 			}
4245 		}
4246 
4247 	} else {
4248 		/* The move was successful, cleanup the old zonepath. */
4249 		if (!is_zfs && !fast) {
4250 			(void) printf(
4251 			    gettext("Cleaning up zonepath %s..."), zonepath);
4252 			(void) fflush(stdout);
4253 			err = cleanup_zonepath(zonepath, B_TRUE);
4254 			(void) printf("\n");
4255 
4256 			if (err != Z_OK) {
4257 				errno = err;
4258 				zperror(gettext("could not remove zonepath"),
4259 				    B_TRUE);
4260 			}
4261 		}
4262 	}
4263 
4264 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4265 }
4266 
4267 /* ARGSUSED */
4268 static int
4269 detach_func(int argc, char *argv[])
4270 {
4271 	int lockfd = -1;
4272 	int err, arg;
4273 	char zonepath[MAXPATHLEN];
4274 	char cmdbuf[MAXPATHLEN];
4275 	char precmdbuf[MAXPATHLEN];
4276 	boolean_t execute = B_TRUE;
4277 	boolean_t brand_help = B_FALSE;
4278 	brand_handle_t bh = NULL;
4279 	int status;
4280 
4281 	if (zonecfg_in_alt_root()) {
4282 		zerror(gettext("cannot detach zone in alternate root"));
4283 		return (Z_ERR);
4284 	}
4285 
4286 	/* Check the argv string for args we handle internally */
4287 	optind = 0;
4288 	opterr = 0;
4289 	while ((arg = getopt(argc, argv, "?n")) != EOF) {
4290 		switch (arg) {
4291 		case '?':
4292 			if (optopt == '?') {
4293 				sub_usage(SHELP_DETACH, CMD_DETACH);
4294 				brand_help = B_TRUE;
4295 			}
4296 			/* Ignore unknown options - may be brand specific. */
4297 			break;
4298 		case 'n':
4299 			execute = B_FALSE;
4300 			break;
4301 		default:
4302 			/* Ignore unknown options - may be brand specific. */
4303 			break;
4304 		}
4305 	}
4306 
4307 	if (brand_help)
4308 		execute = B_FALSE;
4309 
4310 	if (execute) {
4311 		if (sanity_check(target_zone, CMD_DETACH, B_FALSE, B_TRUE,
4312 		    B_FALSE) != Z_OK)
4313 			return (Z_ERR);
4314 		if (verify_details(CMD_DETACH, argv) != Z_OK)
4315 			return (Z_ERR);
4316 	} else {
4317 		/*
4318 		 * We want a dry-run to work for a non-privileged user so we
4319 		 * only do minimal validation.
4320 		 */
4321 		if (target_zone == NULL) {
4322 			zerror(gettext("no zone specified"));
4323 			return (Z_ERR);
4324 		}
4325 
4326 		if (strcmp(target_zone, GLOBAL_ZONENAME) == 0) {
4327 			zerror(gettext("%s operation is invalid for the "
4328 			    "global zone."), cmd_to_str(CMD_DETACH));
4329 			return (Z_ERR);
4330 		}
4331 	}
4332 
4333 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4334 	    != Z_OK) {
4335 		errno = err;
4336 		zperror2(target_zone, gettext("could not get zone path"));
4337 		return (Z_ERR);
4338 	}
4339 
4340 	/* Fetch the detach and predetach hooks from the brand configuration. */
4341 	if ((bh = brand_open(target_brand)) == NULL) {
4342 		zerror(gettext("missing or invalid brand"));
4343 		return (Z_ERR);
4344 	}
4345 
4346 	if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_detach, target_zone,
4347 	    zonepath) != Z_OK) {
4348 		zerror("invalid brand configuration: missing detach resource");
4349 		brand_close(bh);
4350 		return (Z_ERR);
4351 	}
4352 
4353 	if (get_hook(bh, precmdbuf, sizeof (precmdbuf), brand_get_predetach,
4354 	    target_zone, zonepath) != Z_OK) {
4355 		zerror("invalid brand configuration: missing predetach "
4356 		    "resource");
4357 		brand_close(bh);
4358 		return (Z_ERR);
4359 	}
4360 	brand_close(bh);
4361 
4362 	/* Append all options to predetach hook. */
4363 	if (addoptions(precmdbuf, argv, sizeof (precmdbuf)) != Z_OK)
4364 		return (Z_ERR);
4365 
4366 	/* Append all options to detach hook. */
4367 	if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK)
4368 		return (Z_ERR);
4369 
4370 	if (execute && zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4371 		zerror(gettext("another %s may have an operation in progress."),
4372 		    "zoneadm");
4373 		return (Z_ERR);
4374 	}
4375 
4376 	/* If we have a brand predetach hook, run it. */
4377 	if (!brand_help && precmdbuf[0] != '\0') {
4378 		status = do_subproc(precmdbuf);
4379 		if (subproc_status(gettext("brand-specific predetach"),
4380 		    status, B_FALSE) != ZONE_SUBPROC_OK) {
4381 
4382 			if (execute) {
4383 				assert(lockfd >= 0);
4384 				zonecfg_release_lock_file(target_zone, lockfd);
4385 				lockfd = -1;
4386 			}
4387 
4388 			assert(lockfd == -1);
4389 			return (Z_ERR);
4390 		}
4391 	}
4392 
4393 	if (cmdbuf[0] != '\0') {
4394 		/* Run the detach hook */
4395 		status = do_subproc_interactive(cmdbuf);
4396 		if ((status = subproc_status(gettext("brand-specific detach"),
4397 		    status, B_FALSE)) != ZONE_SUBPROC_OK) {
4398 			if (status == ZONE_SUBPROC_USAGE && !brand_help)
4399 				sub_usage(SHELP_DETACH, CMD_DETACH);
4400 
4401 			if (execute) {
4402 				assert(lockfd >= 0);
4403 				zonecfg_release_lock_file(target_zone, lockfd);
4404 				lockfd = -1;
4405 			}
4406 
4407 			assert(lockfd == -1);
4408 			return (Z_ERR);
4409 		}
4410 
4411 	} else {
4412 		zone_dochandle_t handle;
4413 
4414 		/* If just help, we're done since there is no brand help. */
4415 		if (brand_help) {
4416 			assert(lockfd == -1);
4417 			return (Z_OK);
4418 		}
4419 
4420 		/*
4421 		 * Run the built-in detach support.  Just generate a simple
4422 		 * zone definition XML file and detach.
4423 		 */
4424 
4425 		/* Don't detach the zone if anything is still mounted there */
4426 		if (execute && zonecfg_find_mounts(zonepath, NULL, NULL)) {
4427 			(void) fprintf(stderr, gettext("These file systems are "
4428 			    "mounted on subdirectories of %s.\n"), zonepath);
4429 			(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
4430 			err = ZONE_SUBPROC_NOTCOMPLETE;
4431 			goto done;
4432 		}
4433 
4434 		if ((handle = zonecfg_init_handle()) == NULL) {
4435 			zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4436 			err = ZONE_SUBPROC_NOTCOMPLETE;
4437 			goto done;
4438 		}
4439 
4440 		if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4441 			errno = err;
4442 			zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4443 
4444 		} else if ((err = zonecfg_detach_save(handle,
4445 		    (execute ? 0 : ZONE_DRY_RUN))) != Z_OK) {
4446 			errno = err;
4447 			zperror(gettext("saving the detach manifest failed"),
4448 			    B_TRUE);
4449 		}
4450 
4451 		zonecfg_fini_handle(handle);
4452 		if (err != Z_OK)
4453 			goto done;
4454 	}
4455 
4456 	/*
4457 	 * Set the zone state back to configured unless we are running with the
4458 	 * no-execute option.
4459 	 */
4460 	if (execute && (err = zone_set_state(target_zone,
4461 	    ZONE_STATE_CONFIGURED)) != Z_OK) {
4462 		errno = err;
4463 		zperror(gettext("could not reset state"), B_TRUE);
4464 	}
4465 
4466 done:
4467 	if (execute) {
4468 		assert(lockfd >= 0);
4469 		zonecfg_release_lock_file(target_zone, lockfd);
4470 		lockfd = -1;
4471 	}
4472 
4473 	assert(lockfd == -1);
4474 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4475 }
4476 
4477 /*
4478  * Determine the brand when doing a dry-run attach.  The zone does not have to
4479  * exist, so we have to read the incoming manifest to determine the zone's
4480  * brand.
4481  *
4482  * Because the manifest has to be processed twice; once to determine the brand
4483  * and once to do the brand-specific attach logic, we always read it into a tmp
4484  * file.  This handles the manifest coming from stdin or a regular file.  The
4485  * tmpname parameter returns the name of the temporary file that the manifest
4486  * was read into.
4487  */
4488 static int
4489 dryrun_get_brand(char *manifest_path, char *tmpname, int size)
4490 {
4491 	int fd;
4492 	int err;
4493 	int res = Z_OK;
4494 	zone_dochandle_t local_handle;
4495 	zone_dochandle_t rem_handle = NULL;
4496 	int len;
4497 	int ofd;
4498 	char buf[512];
4499 
4500 	if (strcmp(manifest_path, "-") == 0) {
4501 		fd = STDIN_FILENO;
4502 	} else {
4503 		if ((fd = open(manifest_path, O_RDONLY)) < 0) {
4504 			if (getcwd(buf, sizeof (buf)) == NULL)
4505 				(void) strlcpy(buf, "/", sizeof (buf));
4506 			zerror(gettext("could not open manifest path %s%s: %s"),
4507 			    (*manifest_path == '/' ? "" : buf), manifest_path,
4508 			    strerror(errno));
4509 			return (Z_ERR);
4510 		}
4511 	}
4512 
4513 	(void) snprintf(tmpname, size, "/var/run/zone.%d", getpid());
4514 
4515 	if ((ofd = open(tmpname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) < 0) {
4516 		zperror(gettext("could not save manifest"), B_FALSE);
4517 		(void) close(fd);
4518 		return (Z_ERR);
4519 	}
4520 
4521 	while ((len = read(fd, buf, sizeof (buf))) > 0) {
4522 		if (write(ofd, buf, len) == -1) {
4523 			zperror(gettext("could not save manifest"), B_FALSE);
4524 			(void) close(ofd);
4525 			(void) close(fd);
4526 			return (Z_ERR);
4527 		}
4528 	}
4529 
4530 	if (close(ofd) != 0) {
4531 		zperror(gettext("could not save manifest"), B_FALSE);
4532 		(void) close(fd);
4533 		return (Z_ERR);
4534 	}
4535 
4536 	(void) close(fd);
4537 
4538 	if ((fd = open(tmpname, O_RDONLY)) < 0) {
4539 		zperror(gettext("could not open manifest path"), B_FALSE);
4540 		return (Z_ERR);
4541 	}
4542 
4543 	if ((local_handle = zonecfg_init_handle()) == NULL) {
4544 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4545 		res = Z_ERR;
4546 		goto done;
4547 	}
4548 
4549 	if ((rem_handle = zonecfg_init_handle()) == NULL) {
4550 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4551 		res = Z_ERR;
4552 		goto done;
4553 	}
4554 
4555 	if ((err = zonecfg_attach_manifest(fd, local_handle, rem_handle))
4556 	    != Z_OK) {
4557 		res = Z_ERR;
4558 
4559 		if (err == Z_INVALID_DOCUMENT) {
4560 			struct stat st;
4561 			char buf[6];
4562 
4563 			if (strcmp(manifest_path, "-") == 0) {
4564 				zerror(gettext("Input is not a valid XML "
4565 				    "file"));
4566 				goto done;
4567 			}
4568 
4569 			if (fstat(fd, &st) == -1 || !S_ISREG(st.st_mode)) {
4570 				zerror(gettext("%s is not an XML file"),
4571 				    manifest_path);
4572 				goto done;
4573 			}
4574 
4575 			bzero(buf, sizeof (buf));
4576 			(void) lseek(fd, 0L, SEEK_SET);
4577 			if (read(fd, buf, sizeof (buf) - 1) < 0 ||
4578 			    strncmp(buf, "<?xml", 5) != 0)
4579 				zerror(gettext("%s is not an XML file"),
4580 				    manifest_path);
4581 			else
4582 				zerror(gettext("Cannot attach to an earlier "
4583 				    "release of the operating system"));
4584 		} else {
4585 			zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4586 		}
4587 		goto done;
4588 	}
4589 
4590 	/* Retrieve remote handle brand type. */
4591 	if (zonecfg_get_brand(rem_handle, target_brand, sizeof (target_brand))
4592 	    != Z_OK) {
4593 		zerror(gettext("missing or invalid brand"));
4594 		exit(Z_ERR);
4595 	}
4596 
4597 done:
4598 	zonecfg_fini_handle(local_handle);
4599 	zonecfg_fini_handle(rem_handle);
4600 	(void) close(fd);
4601 
4602 	return ((res == Z_OK) ? Z_OK : Z_ERR);
4603 }
4604 
4605 /* ARGSUSED */
4606 static int
4607 attach_func(int argc, char *argv[])
4608 {
4609 	int lockfd = -1;
4610 	int err, arg;
4611 	boolean_t force = B_FALSE;
4612 	zone_dochandle_t handle;
4613 	char zonepath[MAXPATHLEN];
4614 	char cmdbuf[MAXPATHLEN];
4615 	char postcmdbuf[MAXPATHLEN];
4616 	boolean_t execute = B_TRUE;
4617 	boolean_t brand_help = B_FALSE;
4618 	char *manifest_path;
4619 	char tmpmanifest[80];
4620 	int manifest_pos;
4621 	brand_handle_t bh = NULL;
4622 	int status;
4623 	int last_index = 0;
4624 	int offset;
4625 	char *up;
4626 	boolean_t forced_update = B_FALSE;
4627 
4628 	if (zonecfg_in_alt_root()) {
4629 		zerror(gettext("cannot attach zone in alternate root"));
4630 		return (Z_ERR);
4631 	}
4632 
4633 	/* Check the argv string for args we handle internally */
4634 	optind = 0;
4635 	opterr = 0;
4636 	while ((arg = getopt(argc, argv, "?Fn:U")) != EOF) {
4637 		switch (arg) {
4638 		case '?':
4639 			if (optopt == '?') {
4640 				sub_usage(SHELP_ATTACH, CMD_ATTACH);
4641 				brand_help = B_TRUE;
4642 			}
4643 			/* Ignore unknown options - may be brand specific. */
4644 			break;
4645 		case 'F':
4646 			force = B_TRUE;
4647 			break;
4648 		case 'n':
4649 			execute = B_FALSE;
4650 			manifest_path = optarg;
4651 			manifest_pos = optind - 1;
4652 			break;
4653 		case 'U':
4654 			/*
4655 			 * Undocumented 'force update' option for p2v update on
4656 			 * attach when zone is in the incomplete state.  Change
4657 			 * the option back to 'u' and set forced_update flag.
4658 			 */
4659 			if (optind == last_index)
4660 				offset = optind;
4661 			else
4662 				offset = optind - 1;
4663 			if ((up = index(argv[offset], 'U')) != NULL)
4664 				*up = 'u';
4665 			forced_update = B_TRUE;
4666 			break;
4667 		default:
4668 			/* Ignore unknown options - may be brand specific. */
4669 			break;
4670 		}
4671 		last_index = optind;
4672 	}
4673 
4674 	if (brand_help) {
4675 		force = B_FALSE;
4676 		execute = B_TRUE;
4677 	}
4678 
4679 	/* dry-run and force flags are mutually exclusive */
4680 	if (!execute && force) {
4681 		zerror(gettext("-F and -n flags are mutually exclusive"));
4682 		return (Z_ERR);
4683 	}
4684 
4685 	/*
4686 	 * If the no-execute option was specified, we don't do validation and
4687 	 * need to figure out the brand, since there is no zone required to be
4688 	 * configured for this option.
4689 	 */
4690 	if (execute) {
4691 		if (!brand_help) {
4692 			if (sanity_check(target_zone, CMD_ATTACH, B_FALSE,
4693 			    B_TRUE, forced_update) != Z_OK)
4694 				return (Z_ERR);
4695 			if (verify_details(CMD_ATTACH, argv) != Z_OK)
4696 				return (Z_ERR);
4697 		}
4698 
4699 		if ((err = zone_get_zonepath(target_zone, zonepath,
4700 		    sizeof (zonepath))) != Z_OK) {
4701 			errno = err;
4702 			zperror2(target_zone,
4703 			    gettext("could not get zone path"));
4704 			return (Z_ERR);
4705 		}
4706 	} else {
4707 		if (dryrun_get_brand(manifest_path, tmpmanifest,
4708 		    sizeof (tmpmanifest)) != Z_OK)
4709 			return (Z_ERR);
4710 
4711 		argv[manifest_pos] = tmpmanifest;
4712 		target_zone = "-";
4713 		(void) strlcpy(zonepath, "-", sizeof (zonepath));
4714 
4715 		/* Run the brand's verify_adm hook. */
4716 		if (verify_brand(NULL, CMD_ATTACH, argv) != Z_OK)
4717 			return (Z_ERR);
4718 	}
4719 
4720 	/*
4721 	 * Fetch the attach and postattach hooks from the brand configuration.
4722 	 */
4723 	if ((bh = brand_open(target_brand)) == NULL) {
4724 		zerror(gettext("missing or invalid brand"));
4725 		return (Z_ERR);
4726 	}
4727 
4728 	if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_attach, target_zone,
4729 	    zonepath) != Z_OK) {
4730 		zerror("invalid brand configuration: missing attach resource");
4731 		brand_close(bh);
4732 		return (Z_ERR);
4733 	}
4734 
4735 	if (get_hook(bh, postcmdbuf, sizeof (postcmdbuf), brand_get_postattach,
4736 	    target_zone, zonepath) != Z_OK) {
4737 		zerror("invalid brand configuration: missing postattach "
4738 		    "resource");
4739 		brand_close(bh);
4740 		return (Z_ERR);
4741 	}
4742 	brand_close(bh);
4743 
4744 	/* Append all options to attach hook. */
4745 	if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK)
4746 		return (Z_ERR);
4747 
4748 	/* Append all options to postattach hook. */
4749 	if (addoptions(postcmdbuf, argv, sizeof (postcmdbuf)) != Z_OK)
4750 		return (Z_ERR);
4751 
4752 	if (execute && !brand_help) {
4753 		if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4754 			zerror(gettext("another %s may have an operation in "
4755 			    "progress."), "zoneadm");
4756 			return (Z_ERR);
4757 		}
4758 	}
4759 
4760 	if (!force) {
4761 		/*
4762 		 * Not a force-attach, so we need to actually do the work.
4763 		 */
4764 		if (cmdbuf[0] != '\0') {
4765 			/* Run the attach hook */
4766 			status = do_subproc(cmdbuf);
4767 			if ((status = subproc_status(gettext("brand-specific "
4768 			    "attach"), status, B_FALSE)) != ZONE_SUBPROC_OK) {
4769 				if (status == ZONE_SUBPROC_USAGE && !brand_help)
4770 					sub_usage(SHELP_ATTACH, CMD_ATTACH);
4771 
4772 				if (execute && !brand_help) {
4773 					assert(zonecfg_lock_file_held(&lockfd));
4774 					zonecfg_release_lock_file(target_zone,
4775 					    lockfd);
4776 					lockfd = -1;
4777 				}
4778 
4779 				assert(lockfd == -1);
4780 				return (Z_ERR);
4781 			}
4782 		}
4783 
4784 		/*
4785 		 * Else run the built-in attach support.
4786 		 * This is a no-op since there is nothing to validate.
4787 		 */
4788 
4789 		/* If dry-run or help, then we're done. */
4790 		if (!execute || brand_help) {
4791 			if (!execute)
4792 				(void) unlink(tmpmanifest);
4793 			assert(lockfd == -1);
4794 			return (Z_OK);
4795 		}
4796 	}
4797 
4798 	if ((handle = zonecfg_init_handle()) == NULL) {
4799 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4800 		err = Z_ERR;
4801 	} else if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4802 		errno = err;
4803 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4804 		zonecfg_fini_handle(handle);
4805 	} else {
4806 		zonecfg_rm_detached(handle, force);
4807 		zonecfg_fini_handle(handle);
4808 	}
4809 
4810 	if (err == Z_OK &&
4811 	    (err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
4812 		errno = err;
4813 		zperror(gettext("could not reset state"), B_TRUE);
4814 	}
4815 
4816 	assert(zonecfg_lock_file_held(&lockfd));
4817 	zonecfg_release_lock_file(target_zone, lockfd);
4818 	lockfd = -1;
4819 
4820 	/* If we have a brand postattach hook, run it. */
4821 	if (err == Z_OK && !force && postcmdbuf[0] != '\0') {
4822 		status = do_subproc(postcmdbuf);
4823 		if (subproc_status(gettext("brand-specific postattach"),
4824 		    status, B_FALSE) != ZONE_SUBPROC_OK) {
4825 			if ((err = zone_set_state(target_zone,
4826 			    ZONE_STATE_CONFIGURED)) != Z_OK) {
4827 				errno = err;
4828 				zperror(gettext("could not reset state"),
4829 				    B_TRUE);
4830 			}
4831 		}
4832 	}
4833 
4834 	assert(lockfd == -1);
4835 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4836 }
4837 
4838 /*
4839  * On input, TRUE => yes, FALSE => no.
4840  * On return, TRUE => 1, FALSE => 0, could not ask => -1.
4841  */
4842 
4843 static int
4844 ask_yesno(boolean_t default_answer, const char *question)
4845 {
4846 	char line[64];	/* should be large enough to answer yes or no */
4847 
4848 	if (!isatty(STDIN_FILENO))
4849 		return (-1);
4850 	for (;;) {
4851 		(void) printf("%s (%s)? ", question,
4852 		    default_answer ? "[y]/n" : "y/[n]");
4853 		if (fgets(line, sizeof (line), stdin) == NULL ||
4854 		    line[0] == '\n')
4855 			return (default_answer ? 1 : 0);
4856 		if (tolower(line[0]) == 'y')
4857 			return (1);
4858 		if (tolower(line[0]) == 'n')
4859 			return (0);
4860 	}
4861 }
4862 
4863 /* ARGSUSED */
4864 static int
4865 uninstall_func(int argc, char *argv[])
4866 {
4867 	char line[ZONENAME_MAX + 128];	/* Enough for "Are you sure ..." */
4868 	char rootpath[MAXPATHLEN], zonepath[MAXPATHLEN];
4869 	char cmdbuf[MAXPATHLEN];
4870 	char precmdbuf[MAXPATHLEN];
4871 	boolean_t force = B_FALSE;
4872 	int lockfd, answer;
4873 	int err, arg;
4874 	boolean_t brand_help = B_FALSE;
4875 	brand_handle_t bh = NULL;
4876 	int status;
4877 
4878 	if (zonecfg_in_alt_root()) {
4879 		zerror(gettext("cannot uninstall zone in alternate root"));
4880 		return (Z_ERR);
4881 	}
4882 
4883 	/* Check the argv string for args we handle internally */
4884 	optind = 0;
4885 	opterr = 0;
4886 	while ((arg = getopt(argc, argv, "?F")) != EOF) {
4887 		switch (arg) {
4888 		case '?':
4889 			if (optopt == '?') {
4890 				sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
4891 				brand_help = B_TRUE;
4892 			}
4893 			/* Ignore unknown options - may be brand specific. */
4894 			break;
4895 		case 'F':
4896 			force = B_TRUE;
4897 			break;
4898 		default:
4899 			/* Ignore unknown options - may be brand specific. */
4900 			break;
4901 		}
4902 	}
4903 
4904 	if (!brand_help) {
4905 		if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE,
4906 		    B_FALSE) != Z_OK)
4907 			return (Z_ERR);
4908 
4909 		/*
4910 		 * Invoke brand-specific handler.
4911 		 */
4912 		if (invoke_brand_handler(CMD_UNINSTALL, argv) != Z_OK)
4913 			return (Z_ERR);
4914 
4915 		if (!force) {
4916 			(void) snprintf(line, sizeof (line),
4917 			    gettext("Are you sure you want to %s zone %s"),
4918 			    cmd_to_str(CMD_UNINSTALL), target_zone);
4919 			if ((answer = ask_yesno(B_FALSE, line)) == 0) {
4920 				return (Z_OK);
4921 			} else if (answer == -1) {
4922 				zerror(gettext("Input not from terminal and -F "
4923 				    "not specified: %s not done."),
4924 				    cmd_to_str(CMD_UNINSTALL));
4925 				return (Z_ERR);
4926 			}
4927 		}
4928 	}
4929 
4930 	if ((err = zone_get_zonepath(target_zone, zonepath,
4931 	    sizeof (zonepath))) != Z_OK) {
4932 		errno = err;
4933 		zperror2(target_zone, gettext("could not get zone path"));
4934 		return (Z_ERR);
4935 	}
4936 
4937 	/*
4938 	 * Fetch the uninstall and preuninstall hooks from the brand
4939 	 * configuration.
4940 	 */
4941 	if ((bh = brand_open(target_brand)) == NULL) {
4942 		zerror(gettext("missing or invalid brand"));
4943 		return (Z_ERR);
4944 	}
4945 
4946 	if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_uninstall,
4947 	    target_zone, zonepath) != Z_OK) {
4948 		zerror("invalid brand configuration: missing uninstall "
4949 		    "resource");
4950 		brand_close(bh);
4951 		return (Z_ERR);
4952 	}
4953 
4954 	if (get_hook(bh, precmdbuf, sizeof (precmdbuf), brand_get_preuninstall,
4955 	    target_zone, zonepath) != Z_OK) {
4956 		zerror("invalid brand configuration: missing preuninstall "
4957 		    "resource");
4958 		brand_close(bh);
4959 		return (Z_ERR);
4960 	}
4961 	brand_close(bh);
4962 
4963 	/* Append all options to preuninstall hook. */
4964 	if (addoptions(precmdbuf, argv, sizeof (precmdbuf)) != Z_OK)
4965 		return (Z_ERR);
4966 
4967 	/* Append all options to uninstall hook. */
4968 	if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK)
4969 		return (Z_ERR);
4970 
4971 	if (!brand_help) {
4972 		if ((err = zone_get_rootpath(target_zone, rootpath,
4973 		    sizeof (rootpath))) != Z_OK) {
4974 			errno = err;
4975 			zperror2(target_zone, gettext("could not get root "
4976 			    "path"));
4977 			return (Z_ERR);
4978 		}
4979 
4980 		/*
4981 		 * If there seems to be a zoneadmd running for this zone, call
4982 		 * it to tell it that an uninstall is happening; if all goes
4983 		 * well it will then shut itself down.
4984 		 */
4985 		if (zonecfg_ping_zoneadmd(target_zone) == Z_OK) {
4986 			zone_cmd_arg_t zarg;
4987 			zarg.cmd = Z_NOTE_UNINSTALLING;
4988 			/* we don't care too much if this fails, just plow on */
4989 			(void) zonecfg_call_zoneadmd(target_zone, &zarg, locale,
4990 			    B_TRUE);
4991 		}
4992 
4993 		if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4994 			zerror(gettext("another %s may have an operation in "
4995 			    "progress."), "zoneadm");
4996 			return (Z_ERR);
4997 		}
4998 
4999 		/* Don't uninstall the zone if anything is mounted there */
5000 		err = zonecfg_find_mounts(rootpath, NULL, NULL);
5001 		if (err) {
5002 			zerror(gettext("These file systems are mounted on "
5003 			    "subdirectories of %s.\n"), rootpath);
5004 			(void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
5005 			zonecfg_release_lock_file(target_zone, lockfd);
5006 			return (Z_ERR);
5007 		}
5008 	}
5009 
5010 	/* If we have a brand preuninstall hook, run it. */
5011 	if (!brand_help && precmdbuf[0] != '\0') {
5012 		status = do_subproc(cmdbuf);
5013 		if (subproc_status(gettext("brand-specific preuninstall"),
5014 		    status, B_FALSE) != ZONE_SUBPROC_OK) {
5015 			zonecfg_release_lock_file(target_zone, lockfd);
5016 			return (Z_ERR);
5017 		}
5018 	}
5019 
5020 	if (!brand_help) {
5021 		err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
5022 		if (err != Z_OK) {
5023 			errno = err;
5024 			zperror2(target_zone, gettext("could not set state"));
5025 			goto bad;
5026 		}
5027 	}
5028 
5029 	/*
5030 	 * If there is a brand uninstall hook, use it, otherwise use the
5031 	 * built-in uninstall code.
5032 	 */
5033 	if (cmdbuf[0] != '\0') {
5034 		/* Run the uninstall hook */
5035 		status = do_subproc_interactive(cmdbuf);
5036 		if ((status = subproc_status(gettext("brand-specific "
5037 		    "uninstall"), status, B_FALSE)) != ZONE_SUBPROC_OK) {
5038 			if (status == ZONE_SUBPROC_USAGE && !brand_help)
5039 				sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5040 			if (!brand_help)
5041 				zonecfg_release_lock_file(target_zone, lockfd);
5042 			return (Z_ERR);
5043 		}
5044 
5045 		if (brand_help)
5046 			return (Z_OK);
5047 	} else {
5048 		/* If just help, we're done since there is no brand help. */
5049 		if (brand_help)
5050 			return (Z_OK);
5051 
5052 		/* Run the built-in uninstall support. */
5053 		if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
5054 			errno = err;
5055 			zperror2(target_zone, gettext("cleaning up zonepath "
5056 			    "failed"));
5057 			goto bad;
5058 		}
5059 	}
5060 
5061 	err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
5062 	if (err != Z_OK) {
5063 		errno = err;
5064 		zperror2(target_zone, gettext("could not reset state"));
5065 	}
5066 bad:
5067 	zonecfg_release_lock_file(target_zone, lockfd);
5068 	return (err);
5069 }
5070 
5071 /* ARGSUSED */
5072 static int
5073 mount_func(int argc, char *argv[])
5074 {
5075 	zone_cmd_arg_t zarg;
5076 	boolean_t force = B_FALSE;
5077 	int arg;
5078 
5079 	/*
5080 	 * The only supported subargument to the "mount" subcommand is
5081 	 * "-f", which forces us to mount a zone in the INCOMPLETE state.
5082 	 */
5083 	optind = 0;
5084 	if ((arg = getopt(argc, argv, "f")) != EOF) {
5085 		switch (arg) {
5086 		case 'f':
5087 			force = B_TRUE;
5088 			break;
5089 		default:
5090 			return (Z_USAGE);
5091 		}
5092 	}
5093 	if (argc > optind)
5094 		return (Z_USAGE);
5095 
5096 	if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE, force)
5097 	    != Z_OK)
5098 		return (Z_ERR);
5099 	if (verify_details(CMD_MOUNT, argv) != Z_OK)
5100 		return (Z_ERR);
5101 
5102 	zarg.cmd = force ? Z_FORCEMOUNT : Z_MOUNT;
5103 	zarg.bootbuf[0] = '\0';
5104 	if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
5105 		zerror(gettext("call to %s failed"), "zoneadmd");
5106 		return (Z_ERR);
5107 	}
5108 	return (Z_OK);
5109 }
5110 
5111 /* ARGSUSED */
5112 static int
5113 unmount_func(int argc, char *argv[])
5114 {
5115 	zone_cmd_arg_t zarg;
5116 
5117 	if (argc > 0)
5118 		return (Z_USAGE);
5119 	if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE, B_FALSE)
5120 	    != Z_OK)
5121 		return (Z_ERR);
5122 
5123 	zarg.cmd = Z_UNMOUNT;
5124 	if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
5125 		zerror(gettext("call to %s failed"), "zoneadmd");
5126 		return (Z_ERR);
5127 	}
5128 	return (Z_OK);
5129 }
5130 
5131 static int
5132 mark_func(int argc, char *argv[])
5133 {
5134 	int err, lockfd;
5135 	int arg;
5136 	boolean_t force = B_FALSE;
5137 	int state;
5138 
5139 	optind = 0;
5140 	opterr = 0;
5141 	while ((arg = getopt(argc, argv, "F")) != EOF) {
5142 		switch (arg) {
5143 		case 'F':
5144 			force = B_TRUE;
5145 			break;
5146 		default:
5147 			return (Z_USAGE);
5148 		}
5149 	}
5150 
5151 	if (argc != (optind + 1))
5152 		return (Z_USAGE);
5153 
5154 	if (strcmp(argv[optind], "configured") == 0)
5155 		state = ZONE_STATE_CONFIGURED;
5156 	else if (strcmp(argv[optind], "incomplete") == 0)
5157 		state = ZONE_STATE_INCOMPLETE;
5158 	else if (strcmp(argv[optind], "installed") == 0)
5159 		state = ZONE_STATE_INSTALLED;
5160 	else
5161 		return (Z_USAGE);
5162 
5163 	if (state != ZONE_STATE_INCOMPLETE && !force)
5164 		return (Z_USAGE);
5165 
5166 	if (sanity_check(target_zone, CMD_MARK, B_FALSE, B_TRUE, B_FALSE)
5167 	    != Z_OK)
5168 		return (Z_ERR);
5169 
5170 	/*
5171 	 * Invoke brand-specific handler.
5172 	 */
5173 	if (invoke_brand_handler(CMD_MARK, argv) != Z_OK)
5174 		return (Z_ERR);
5175 
5176 	if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
5177 		zerror(gettext("another %s may have an operation in progress."),
5178 		    "zoneadm");
5179 		return (Z_ERR);
5180 	}
5181 
5182 	err = zone_set_state(target_zone, state);
5183 	if (err != Z_OK) {
5184 		errno = err;
5185 		zperror2(target_zone, gettext("could not set state"));
5186 	}
5187 	zonecfg_release_lock_file(target_zone, lockfd);
5188 
5189 	return (err);
5190 }
5191 
5192 /*
5193  * Check what scheduling class we're running under and print a warning if
5194  * we're not using FSS.
5195  */
5196 static int
5197 check_sched_fss(zone_dochandle_t handle)
5198 {
5199 	char class_name[PC_CLNMSZ];
5200 
5201 	if (zonecfg_get_dflt_sched_class(handle, class_name,
5202 	    sizeof (class_name)) != Z_OK) {
5203 		zerror(gettext("WARNING: unable to determine the zone's "
5204 		    "scheduling class"));
5205 	} else if (strcmp("FSS", class_name) != 0) {
5206 		zerror(gettext("WARNING: The zone.cpu-shares rctl is set but\n"
5207 		    "FSS is not the default scheduling class for this zone.  "
5208 		    "FSS will be\nused for processes in the zone but to get "
5209 		    "the full benefit of FSS,\nit should be the default "
5210 		    "scheduling class.  See dispadmin(1M) for\nmore details."));
5211 		return (Z_SYSTEM);
5212 	}
5213 
5214 	return (Z_OK);
5215 }
5216 
5217 static int
5218 check_cpu_shares_sched(zone_dochandle_t handle)
5219 {
5220 	int err;
5221 	int res = Z_OK;
5222 	struct zone_rctltab rctl;
5223 
5224 	if ((err = zonecfg_setrctlent(handle)) != Z_OK) {
5225 		errno = err;
5226 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5227 		return (err);
5228 	}
5229 
5230 	while (zonecfg_getrctlent(handle, &rctl) == Z_OK) {
5231 		if (strcmp(rctl.zone_rctl_name, "zone.cpu-shares") == 0) {
5232 			if (check_sched_fss(handle) != Z_OK)
5233 				res = Z_SYSTEM;
5234 			break;
5235 		}
5236 	}
5237 
5238 	(void) zonecfg_endrctlent(handle);
5239 
5240 	return (res);
5241 }
5242 
5243 /*
5244  * Check if there is a mix of processes running in different pools within the
5245  * zone.  This is currently only going to be called for the global zone from
5246  * apply_func but that could be generalized in the future.
5247  */
5248 static boolean_t
5249 mixed_pools(zoneid_t zoneid)
5250 {
5251 	DIR *dirp;
5252 	dirent_t *dent;
5253 	boolean_t mixed = B_FALSE;
5254 	boolean_t poolid_set = B_FALSE;
5255 	poolid_t last_poolid = 0;
5256 
5257 	if ((dirp = opendir("/proc")) == NULL) {
5258 		zerror(gettext("could not open /proc"));
5259 		return (B_FALSE);
5260 	}
5261 
5262 	while ((dent = readdir(dirp)) != NULL) {
5263 		int procfd;
5264 		psinfo_t ps;
5265 		char procpath[MAXPATHLEN];
5266 
5267 		if (dent->d_name[0] == '.')
5268 			continue;
5269 
5270 		(void) snprintf(procpath, sizeof (procpath), "/proc/%s/psinfo",
5271 		    dent->d_name);
5272 
5273 		if ((procfd = open(procpath, O_RDONLY)) == -1)
5274 			continue;
5275 
5276 		if (read(procfd, &ps, sizeof (ps)) == sizeof (psinfo_t)) {
5277 			/* skip processes in other zones and system processes */
5278 			if (zoneid != ps.pr_zoneid || ps.pr_flag & SSYS) {
5279 				(void) close(procfd);
5280 				continue;
5281 			}
5282 
5283 			if (poolid_set) {
5284 				if (ps.pr_poolid != last_poolid)
5285 					mixed = B_TRUE;
5286 			} else {
5287 				last_poolid = ps.pr_poolid;
5288 				poolid_set = B_TRUE;
5289 			}
5290 		}
5291 
5292 		(void) close(procfd);
5293 
5294 		if (mixed)
5295 			break;
5296 	}
5297 
5298 	(void) closedir(dirp);
5299 
5300 	return (mixed);
5301 }
5302 
5303 /*
5304  * Check if a persistent or temporary pool is configured for the zone.
5305  * This is currently only going to be called for the global zone from
5306  * apply_func but that could be generalized in the future.
5307  */
5308 static boolean_t
5309 pool_configured(zone_dochandle_t handle)
5310 {
5311 	int err1, err2;
5312 	struct zone_psettab pset_tab;
5313 	char poolname[MAXPATHLEN];
5314 
5315 	err1 = zonecfg_lookup_pset(handle, &pset_tab);
5316 	err2 = zonecfg_get_pool(handle, poolname, sizeof (poolname));
5317 
5318 	if (err1 == Z_NO_ENTRY &&
5319 	    (err2 == Z_NO_ENTRY || (err2 == Z_OK && strlen(poolname) == 0)))
5320 		return (B_FALSE);
5321 
5322 	return (B_TRUE);
5323 }
5324 
5325 /*
5326  * This is an undocumented interface which is currently only used to apply
5327  * the global zone resource management settings when the system boots.
5328  * This function does not yet properly handle updating a running system so
5329  * any projects running in the zone would be trashed if this function
5330  * were to run after the zone had booted.  It also does not reset any
5331  * rctl settings that were removed from zonecfg.  There is still work to be
5332  * done before we can properly support dynamically updating the resource
5333  * management settings for a running zone (global or non-global).  Thus, this
5334  * functionality is undocumented for now.
5335  */
5336 /* ARGSUSED */
5337 static int
5338 apply_func(int argc, char *argv[])
5339 {
5340 	int err;
5341 	int res = Z_OK;
5342 	priv_set_t *privset;
5343 	zoneid_t zoneid;
5344 	zone_dochandle_t handle;
5345 	struct zone_mcaptab mcap;
5346 	char pool_err[128];
5347 
5348 	zoneid = getzoneid();
5349 
5350 	if (zonecfg_in_alt_root() || zoneid != GLOBAL_ZONEID ||
5351 	    target_zone == NULL || strcmp(target_zone, GLOBAL_ZONENAME) != 0)
5352 		return (usage(B_FALSE));
5353 
5354 	if ((privset = priv_allocset()) == NULL) {
5355 		zerror(gettext("%s failed"), "priv_allocset");
5356 		return (Z_ERR);
5357 	}
5358 
5359 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
5360 		zerror(gettext("%s failed"), "getppriv");
5361 		priv_freeset(privset);
5362 		return (Z_ERR);
5363 	}
5364 
5365 	if (priv_isfullset(privset) == B_FALSE) {
5366 		(void) usage(B_FALSE);
5367 		priv_freeset(privset);
5368 		return (Z_ERR);
5369 	}
5370 	priv_freeset(privset);
5371 
5372 	if ((handle = zonecfg_init_handle()) == NULL) {
5373 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5374 		return (Z_ERR);
5375 	}
5376 
5377 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
5378 		errno = err;
5379 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5380 		zonecfg_fini_handle(handle);
5381 		return (Z_ERR);
5382 	}
5383 
5384 	/* specific error msgs are printed within apply_rctls */
5385 	if ((err = zonecfg_apply_rctls(target_zone, handle)) != Z_OK) {
5386 		errno = err;
5387 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5388 		res = Z_ERR;
5389 	}
5390 
5391 	if ((err = check_cpu_shares_sched(handle)) != Z_OK)
5392 		res = Z_ERR;
5393 
5394 	if (pool_configured(handle)) {
5395 		if (mixed_pools(zoneid)) {
5396 			zerror(gettext("Zone is using multiple resource "
5397 			    "pools.  The pool\nconfiguration cannot be "
5398 			    "applied without rebooting."));
5399 			res = Z_ERR;
5400 		} else {
5401 
5402 			/*
5403 			 * The next two blocks of code attempt to set up
5404 			 * temporary pools as well as persistent pools.  In
5405 			 * both cases we call the functions unconditionally.
5406 			 * Within each funtion the code will check if the zone
5407 			 * is actually configured for a temporary pool or
5408 			 * persistent pool and just return if there is nothing
5409 			 * to do.
5410 			 */
5411 			if ((err = zonecfg_bind_tmp_pool(handle, zoneid,
5412 			    pool_err, sizeof (pool_err))) != Z_OK) {
5413 				if (err == Z_POOL || err == Z_POOL_CREATE ||
5414 				    err == Z_POOL_BIND)
5415 					zerror("%s: %s", zonecfg_strerror(err),
5416 					    pool_err);
5417 				else
5418 					zerror(gettext("could not bind zone to "
5419 					    "temporary pool: %s"),
5420 					    zonecfg_strerror(err));
5421 				res = Z_ERR;
5422 			}
5423 
5424 			if ((err = zonecfg_bind_pool(handle, zoneid, pool_err,
5425 			    sizeof (pool_err))) != Z_OK) {
5426 				if (err == Z_POOL || err == Z_POOL_BIND)
5427 					zerror("%s: %s", zonecfg_strerror(err),
5428 					    pool_err);
5429 				else
5430 					zerror("%s", zonecfg_strerror(err));
5431 			}
5432 		}
5433 	}
5434 
5435 	/*
5436 	 * If a memory cap is configured, set the cap in the kernel using
5437 	 * zone_setattr() and make sure the rcapd SMF service is enabled.
5438 	 */
5439 	if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
5440 		uint64_t num;
5441 		char smf_err[128];
5442 
5443 		num = (uint64_t)strtoll(mcap.zone_physmem_cap, NULL, 10);
5444 		if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
5445 			zerror(gettext("could not set zone memory cap"));
5446 			res = Z_ERR;
5447 		}
5448 
5449 		if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
5450 			zerror(gettext("enabling system/rcap service failed: "
5451 			    "%s"), smf_err);
5452 			res = Z_ERR;
5453 		}
5454 	}
5455 
5456 	zonecfg_fini_handle(handle);
5457 
5458 	return (res);
5459 }
5460 
5461 static int
5462 help_func(int argc, char *argv[])
5463 {
5464 	int arg, cmd_num;
5465 
5466 	if (argc == 0) {
5467 		(void) usage(B_TRUE);
5468 		return (Z_OK);
5469 	}
5470 	optind = 0;
5471 	if ((arg = getopt(argc, argv, "?")) != EOF) {
5472 		switch (arg) {
5473 		case '?':
5474 			sub_usage(SHELP_HELP, CMD_HELP);
5475 			return (optopt == '?' ? Z_OK : Z_USAGE);
5476 		default:
5477 			sub_usage(SHELP_HELP, CMD_HELP);
5478 			return (Z_USAGE);
5479 		}
5480 	}
5481 	while (optind < argc) {
5482 		/* Private commands have NULL short_usage; omit them */
5483 		if ((cmd_num = cmd_match(argv[optind])) < 0 ||
5484 		    cmdtab[cmd_num].short_usage == NULL) {
5485 			sub_usage(SHELP_HELP, CMD_HELP);
5486 			return (Z_USAGE);
5487 		}
5488 		sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
5489 		optind++;
5490 	}
5491 	return (Z_OK);
5492 }
5493 
5494 /*
5495  * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
5496  */
5497 
5498 static int
5499 cmd_match(char *cmd)
5500 {
5501 	int i;
5502 
5503 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
5504 		/* return only if there is an exact match */
5505 		if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
5506 			return (cmdtab[i].cmd_num);
5507 	}
5508 	return (-1);
5509 }
5510 
5511 static int
5512 parse_and_run(int argc, char *argv[])
5513 {
5514 	int i = cmd_match(argv[0]);
5515 
5516 	if (i < 0)
5517 		return (usage(B_FALSE));
5518 	return (cmdtab[i].handler(argc - 1, &(argv[1])));
5519 }
5520 
5521 static char *
5522 get_execbasename(char *execfullname)
5523 {
5524 	char *last_slash, *execbasename;
5525 
5526 	/* guard against '/' at end of command invocation */
5527 	for (;;) {
5528 		last_slash = strrchr(execfullname, '/');
5529 		if (last_slash == NULL) {
5530 			execbasename = execfullname;
5531 			break;
5532 		} else {
5533 			execbasename = last_slash + 1;
5534 			if (*execbasename == '\0') {
5535 				*last_slash = '\0';
5536 				continue;
5537 			}
5538 			break;
5539 		}
5540 	}
5541 	return (execbasename);
5542 }
5543 
5544 int
5545 main(int argc, char **argv)
5546 {
5547 	int arg;
5548 	zoneid_t zid;
5549 	struct stat st;
5550 	char *zone_lock_env;
5551 	int err;
5552 
5553 	if ((locale = setlocale(LC_ALL, "")) == NULL)
5554 		locale = "C";
5555 	(void) textdomain(TEXT_DOMAIN);
5556 	setbuf(stdout, NULL);
5557 	(void) sigset(SIGHUP, SIG_IGN);
5558 	execname = get_execbasename(argv[0]);
5559 	target_zone = NULL;
5560 	if (chdir("/") != 0) {
5561 		zerror(gettext("could not change directory to /."));
5562 		exit(Z_ERR);
5563 	}
5564 
5565 	if (init_zfs() != Z_OK)
5566 		exit(Z_ERR);
5567 
5568 	while ((arg = getopt(argc, argv, "?u:z:R:")) != EOF) {
5569 		switch (arg) {
5570 		case '?':
5571 			return (usage(B_TRUE));
5572 		case 'u':
5573 			target_uuid = optarg;
5574 			break;
5575 		case 'z':
5576 			target_zone = optarg;
5577 			break;
5578 		case 'R':	/* private option for admin/install use */
5579 			if (*optarg != '/') {
5580 				zerror(gettext("root path must be absolute."));
5581 				exit(Z_ERR);
5582 			}
5583 			if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
5584 				zerror(
5585 				    gettext("root path must be a directory."));
5586 				exit(Z_ERR);
5587 			}
5588 			zonecfg_set_root(optarg);
5589 			break;
5590 		default:
5591 			return (usage(B_FALSE));
5592 		}
5593 	}
5594 
5595 	if (optind >= argc)
5596 		return (usage(B_FALSE));
5597 
5598 	if (target_uuid != NULL && *target_uuid != '\0') {
5599 		uuid_t uuid;
5600 		static char newtarget[ZONENAME_MAX];
5601 
5602 		if (uuid_parse(target_uuid, uuid) == -1) {
5603 			zerror(gettext("illegal UUID value specified"));
5604 			exit(Z_ERR);
5605 		}
5606 		if (zonecfg_get_name_by_uuid(uuid, newtarget,
5607 		    sizeof (newtarget)) == Z_OK)
5608 			target_zone = newtarget;
5609 	}
5610 
5611 	if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
5612 		errno = Z_NO_ZONE;
5613 		zperror(target_zone, B_TRUE);
5614 		exit(Z_ERR);
5615 	}
5616 
5617 	/*
5618 	 * See if we have inherited the right to manipulate this zone from
5619 	 * a zoneadm instance in our ancestry.  If so, set zone_lock_cnt to
5620 	 * indicate it.  If not, make that explicit in our environment.
5621 	 */
5622 	zonecfg_init_lock_file(target_zone, &zone_lock_env);
5623 	if (zone_lock_env != NULL)
5624 		zoneadm_is_nested = B_TRUE;
5625 
5626 	/*
5627 	 * If we are going to be operating on a single zone, retrieve its
5628 	 * brand type and determine whether it is native or not.
5629 	 */
5630 	if ((target_zone != NULL) &&
5631 	    (strcmp(target_zone, GLOBAL_ZONENAME) != 0)) {
5632 		if (zone_get_brand(target_zone, target_brand,
5633 		    sizeof (target_brand)) != Z_OK) {
5634 			zerror(gettext("missing or invalid brand"));
5635 			exit(Z_ERR);
5636 		}
5637 	}
5638 
5639 	err = parse_and_run(argc - optind, &argv[optind]);
5640 
5641 	return (err);
5642 }
5643