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