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