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