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