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