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