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