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