xref: /titanic_41/usr/src/cmd/zoneadm/zoneadm.c (revision 2917a9c9c3eee6fcaedb239f5f68da01f4ed0da9)
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 
70 #include <fcntl.h>
71 #include <door.h>
72 #include <macros.h>
73 #include <libgen.h>
74 #include <fnmatch.h>
75 #include <sys/modctl.h>
76 #include <libbrand.h>
77 #include <libscf.h>
78 #include <procfs.h>
79 #include <strings.h>
80 
81 #include <pool.h>
82 #include <sys/pool.h>
83 #include <sys/priocntl.h>
84 #include <sys/fsspriocntl.h>
85 
86 #include "zoneadm.h"
87 
88 #define	MAXARGS	8
89 
90 /* Reflects kernel zone entries */
91 typedef struct zone_entry {
92 	zoneid_t	zid;
93 	char		zname[ZONENAME_MAX];
94 	char		*zstate_str;
95 	zone_state_t	zstate_num;
96 	char		zbrand[MAXNAMELEN];
97 	char		zroot[MAXPATHLEN];
98 	char		zuuid[UUID_PRINTABLE_STRING_LENGTH];
99 	zone_iptype_t	ziptype;
100 } zone_entry_t;
101 
102 #define	CLUSTER_BRAND_NAME	"cluster"
103 
104 static zone_entry_t *zents;
105 static size_t nzents;
106 static boolean_t is_native_zone = B_TRUE;
107 static boolean_t is_cluster_zone = B_FALSE;
108 
109 #define	LOOPBACK_IF	"lo0"
110 #define	SOCKET_AF(af)	(((af) == AF_UNSPEC) ? AF_INET : (af))
111 
112 struct net_if {
113 	char	*name;
114 	int	af;
115 };
116 
117 /* 0755 is the default directory mode. */
118 #define	DEFAULT_DIR_MODE \
119 	(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
120 
121 struct cmd {
122 	uint_t	cmd_num;				/* command number */
123 	char	*cmd_name;				/* command name */
124 	char	*short_usage;				/* short form help */
125 	int	(*handler)(int argc, char *argv[]);	/* function to call */
126 
127 };
128 
129 #define	SHELP_HELP	"help"
130 #define	SHELP_BOOT	"boot [-- boot_arguments]"
131 #define	SHELP_HALT	"halt"
132 #define	SHELP_READY	"ready"
133 #define	SHELP_REBOOT	"reboot [-- boot_arguments]"
134 #define	SHELP_LIST	"list [-cipv]"
135 #define	SHELP_VERIFY	"verify"
136 #define	SHELP_INSTALL	"install [-x nodataset] [brand-specific args]"
137 #define	SHELP_UNINSTALL	"uninstall [-F]"
138 #define	SHELP_CLONE	"clone [-m method] [-s <ZFS snapshot>] zonename"
139 #define	SHELP_MOVE	"move zonepath"
140 #define	SHELP_DETACH	"detach [-n]"
141 #define	SHELP_ATTACH	"attach [-F] [-n <path>]"
142 #define	SHELP_MARK	"mark incomplete"
143 
144 #define	EXEC_PREFIX	"exec "
145 #define	EXEC_LEN	(strlen(EXEC_PREFIX))
146 #define	RMCOMMAND	"/usr/bin/rm -rf"
147 
148 static int cleanup_zonepath(char *, boolean_t);
149 
150 extern int ifname_open(char *);
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 	int fd;
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 			 * Verify that the physical interface can
2912 			 * be opened
2913 			 */
2914 			fd = ifname_open(nwiftab.zone_nwif_physical);
2915 			if (fd == -1) {
2916 				(void) fprintf(stderr,
2917 				    gettext("WARNING: skipping network "
2918 				    "interface '%s' which cannot be opened.\n"),
2919 				    nwiftab.zone_nwif_physical);
2920 				break;
2921 			} else {
2922 				(void) close(fd);
2923 			}
2924 			/*
2925 			 * Verify whether the physical interface is already
2926 			 * used by a zone.
2927 			 */
2928 			dl_owner_zid = ALL_ZONES;
2929 			if (zone_check_datalink(&dl_owner_zid,
2930 			    nwiftab.zone_nwif_physical) != 0)
2931 				break;
2932 
2933 			/*
2934 			 * If the zone being verified is
2935 			 * running and owns the interface
2936 			 */
2937 			target_zid = getzoneidbyname(target_zone);
2938 			if (target_zid == dl_owner_zid)
2939 				break;
2940 
2941 			/* Zone id match failed, use name to check */
2942 			if (getzonenamebyid(dl_owner_zid, dl_owner_zname,
2943 			    ZONENAME_MAX) < 0) {
2944 				/* No name, show ID instead */
2945 				(void) snprintf(dl_owner_zname, ZONENAME_MAX,
2946 				    "<%d>", dl_owner_zid);
2947 			} else if (strcmp(dl_owner_zname, target_zone) == 0)
2948 				break;
2949 
2950 			/*
2951 			 * Note here we only report a warning that
2952 			 * the interface is already in use by another
2953 			 * running zone, and the verify process just
2954 			 * goes on, if the interface is still in use
2955 			 * when this zone really boots up, zoneadmd
2956 			 * will find it. If the name of the zone which
2957 			 * owns this interface cannot be determined,
2958 			 * then it is not possible to determine if there
2959 			 * is a conflict so just report it as a warning.
2960 			 */
2961 			(void) fprintf(stderr,
2962 			    gettext("WARNING: skipping network interface "
2963 			    "'%s' which is used by the non-global zone "
2964 			    "'%s'.\n"), nwiftab.zone_nwif_physical,
2965 			    dl_owner_zname);
2966 			break;
2967 		}
2968 	}
2969 	(void) zonecfg_endnwifent(handle);
2970 no_net:
2971 
2972 	/* verify that lofs has not been excluded from the kernel */
2973 	if (!(cmd_num == CMD_DETACH || cmd_num == CMD_ATTACH ||
2974 	    cmd_num == CMD_MOVE || cmd_num == CMD_CLONE) &&
2975 	    modctl(MODLOAD, 1, "fs/lofs", NULL) != 0) {
2976 		if (errno == ENXIO)
2977 			(void) fprintf(stderr, gettext("could not verify "
2978 			    "lofs(7FS): possibly excluded in /etc/system\n"));
2979 		else
2980 			(void) fprintf(stderr, gettext("could not verify "
2981 			    "lofs(7FS): %s\n"), strerror(errno));
2982 		return_code = Z_ERR;
2983 	}
2984 
2985 	if (verify_filesystems(handle) != Z_OK)
2986 		return_code = Z_ERR;
2987 	if (verify_ipd(handle) != Z_OK)
2988 		return_code = Z_ERR;
2989 	if (!in_alt_root && verify_rctls(handle) != Z_OK)
2990 		return_code = Z_ERR;
2991 	if (!in_alt_root && verify_pool(handle) != Z_OK)
2992 		return_code = Z_ERR;
2993 	if (!in_alt_root && verify_brand(handle, cmd_num, argv) != Z_OK)
2994 		return_code = Z_ERR;
2995 	if (!in_alt_root && verify_datasets(handle) != Z_OK)
2996 		return_code = Z_ERR;
2997 
2998 	/*
2999 	 * As the "mount" command is used for patching/upgrading of zones
3000 	 * or other maintenance processes, the zone's privilege set is not
3001 	 * checked in this case.  Instead, the default, safe set of
3002 	 * privileges will be used when this zone is created in the
3003 	 * kernel.
3004 	 */
3005 	if (!in_alt_root && cmd_num != CMD_MOUNT &&
3006 	    verify_limitpriv(handle) != Z_OK)
3007 		return_code = Z_ERR;
3008 
3009 	return (return_code);
3010 }
3011 
3012 static int
3013 verify_details(int cmd_num, char *argv[])
3014 {
3015 	zone_dochandle_t handle;
3016 	char zonepath[MAXPATHLEN], checkpath[MAXPATHLEN];
3017 	int return_code = Z_OK;
3018 	int err;
3019 
3020 	if ((handle = zonecfg_init_handle()) == NULL) {
3021 		zperror(cmd_to_str(cmd_num), B_TRUE);
3022 		return (Z_ERR);
3023 	}
3024 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
3025 		errno = err;
3026 		zperror(cmd_to_str(cmd_num), B_TRUE);
3027 		zonecfg_fini_handle(handle);
3028 		return (Z_ERR);
3029 	}
3030 	if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
3031 	    Z_OK) {
3032 		errno = err;
3033 		zperror(cmd_to_str(cmd_num), B_TRUE);
3034 		zonecfg_fini_handle(handle);
3035 		return (Z_ERR);
3036 	}
3037 	/*
3038 	 * zonecfg_get_zonepath() gets its data from the XML repository.
3039 	 * Verify this against the index file, which is checked first by
3040 	 * zone_get_zonepath().  If they don't match, bail out.
3041 	 */
3042 	if ((err = zone_get_zonepath(target_zone, checkpath,
3043 	    sizeof (checkpath))) != Z_OK) {
3044 		errno = err;
3045 		zperror2(target_zone, gettext("could not get zone path"));
3046 		zonecfg_fini_handle(handle);
3047 		return (Z_ERR);
3048 	}
3049 	if (strcmp(zonepath, checkpath) != 0) {
3050 		/*
3051 		 * TRANSLATION_NOTE
3052 		 * XML and zonepath are literals that should not be translated.
3053 		 */
3054 		(void) fprintf(stderr, gettext("The XML repository has "
3055 		    "zonepath '%s',\nbut the index file has zonepath '%s'.\n"
3056 		    "These must match, so fix the incorrect entry.\n"),
3057 		    zonepath, checkpath);
3058 		zonecfg_fini_handle(handle);
3059 		return (Z_ERR);
3060 	}
3061 	if (validate_zonepath(zonepath, cmd_num) != Z_OK) {
3062 		(void) fprintf(stderr, gettext("could not verify zonepath %s "
3063 		    "because of the above errors.\n"), zonepath);
3064 		return_code = Z_ERR;
3065 	}
3066 
3067 	if (verify_handle(cmd_num, handle, argv) != Z_OK)
3068 		return_code = Z_ERR;
3069 
3070 	zonecfg_fini_handle(handle);
3071 	if (return_code == Z_ERR)
3072 		(void) fprintf(stderr,
3073 		    gettext("%s: zone %s failed to verify\n"),
3074 		    execname, target_zone);
3075 	return (return_code);
3076 }
3077 
3078 static int
3079 verify_func(int argc, char *argv[])
3080 {
3081 	int arg;
3082 
3083 	optind = 0;
3084 	if ((arg = getopt(argc, argv, "?")) != EOF) {
3085 		switch (arg) {
3086 		case '?':
3087 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
3088 			return (optopt == '?' ? Z_OK : Z_USAGE);
3089 		default:
3090 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
3091 			return (Z_USAGE);
3092 		}
3093 	}
3094 	if (argc > optind) {
3095 		sub_usage(SHELP_VERIFY, CMD_VERIFY);
3096 		return (Z_USAGE);
3097 	}
3098 	if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE, B_FALSE)
3099 	    != Z_OK)
3100 		return (Z_ERR);
3101 	return (verify_details(CMD_VERIFY, argv));
3102 }
3103 
3104 static int
3105 addopt(char *buf, int opt, char *optarg, size_t bufsize)
3106 {
3107 	char optstring[4];
3108 
3109 	if (opt > 0)
3110 		(void) sprintf(optstring, " -%c", opt);
3111 	else
3112 		(void) strcpy(optstring, " ");
3113 
3114 	if ((strlcat(buf, optstring, bufsize) > bufsize))
3115 		return (Z_ERR);
3116 	if ((optarg != NULL) && (strlcat(buf, optarg, bufsize) > bufsize))
3117 		return (Z_ERR);
3118 	return (Z_OK);
3119 }
3120 
3121 static int
3122 install_func(int argc, char *argv[])
3123 {
3124 	char cmdbuf[MAXPATHLEN];
3125 	int lockfd;
3126 	int arg, err, subproc_err;
3127 	char zonepath[MAXPATHLEN];
3128 	brand_handle_t bh = NULL;
3129 	int status;
3130 	boolean_t nodataset = B_FALSE;
3131 	char opts[128];
3132 
3133 	if (target_zone == NULL) {
3134 		sub_usage(SHELP_INSTALL, CMD_INSTALL);
3135 		return (Z_USAGE);
3136 	}
3137 
3138 	if (zonecfg_in_alt_root()) {
3139 		zerror(gettext("cannot install zone in alternate root"));
3140 		return (Z_ERR);
3141 	}
3142 
3143 	if ((err = zone_get_zonepath(target_zone, zonepath,
3144 	    sizeof (zonepath))) != Z_OK) {
3145 		errno = err;
3146 		zperror2(target_zone, gettext("could not get zone path"));
3147 		return (Z_ERR);
3148 	}
3149 
3150 	/* Fetch the install command from the brand configuration.  */
3151 	if ((bh = brand_open(target_brand)) == NULL) {
3152 		zerror(gettext("missing or invalid brand"));
3153 		return (Z_ERR);
3154 	}
3155 
3156 	(void) strcpy(cmdbuf, EXEC_PREFIX);
3157 	if (brand_get_install(bh, target_zone, zonepath, cmdbuf + EXEC_LEN,
3158 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL) != 0) {
3159 		zerror("invalid brand configuration: missing install resource");
3160 		brand_close(bh);
3161 		return (Z_ERR);
3162 	}
3163 
3164 	(void) strcpy(opts, "?x:");
3165 	if (!is_native_zone) {
3166 		/*
3167 		 * Fetch the list of recognized command-line options from
3168 		 * the brand configuration file.
3169 		 */
3170 		if (brand_get_installopts(bh, opts + strlen(opts),
3171 		    sizeof (opts) - strlen(opts)) != 0) {
3172 			zerror("invalid brand configuration: missing "
3173 			    "install options resource");
3174 			brand_close(bh);
3175 			return (Z_ERR);
3176 		}
3177 	}
3178 	brand_close(bh);
3179 
3180 	optind = 0;
3181 	while ((arg = getopt(argc, argv, opts)) != EOF) {
3182 		switch (arg) {
3183 		case '?':
3184 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
3185 			return (optopt == '?' ? Z_OK : Z_USAGE);
3186 		case 'x':
3187 			if (strcmp(optarg, "nodataset") != 0) {
3188 				sub_usage(SHELP_INSTALL, CMD_INSTALL);
3189 				return (Z_USAGE);
3190 			}
3191 			nodataset = B_TRUE;
3192 			break;
3193 		default:
3194 			if (is_native_zone) {
3195 				sub_usage(SHELP_INSTALL, CMD_INSTALL);
3196 				return (Z_USAGE);
3197 			}
3198 
3199 			/*
3200 			 * This option isn't for zoneadm, so append it to
3201 			 * the command line passed to the brand-specific
3202 			 * install routine.
3203 			 */
3204 			if (addopt(cmdbuf, optopt, optarg,
3205 			    sizeof (cmdbuf)) != Z_OK) {
3206 				zerror("Install command line too long");
3207 				return (Z_ERR);
3208 			}
3209 			break;
3210 		}
3211 	}
3212 
3213 	if (!is_native_zone) {
3214 		for (; optind < argc; optind++) {
3215 			if (addopt(cmdbuf, 0, argv[optind],
3216 			    sizeof (cmdbuf)) != Z_OK) {
3217 				zerror("Install command line too long");
3218 				return (Z_ERR);
3219 			}
3220 		}
3221 	}
3222 
3223 	if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE, B_FALSE)
3224 	    != Z_OK)
3225 		return (Z_ERR);
3226 	if (verify_details(CMD_INSTALL, argv) != Z_OK)
3227 		return (Z_ERR);
3228 
3229 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
3230 		zerror(gettext("another %s may have an operation in progress."),
3231 		    "zoneadm");
3232 		return (Z_ERR);
3233 	}
3234 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
3235 	if (err != Z_OK) {
3236 		errno = err;
3237 		zperror2(target_zone, gettext("could not set state"));
3238 		goto done;
3239 	}
3240 
3241 	if (!nodataset)
3242 		create_zfs_zonepath(zonepath);
3243 
3244 	/*
3245 	 * According to the Application Packaging Developer's Guide, a
3246 	 * "checkinstall" script when included in a package is executed as
3247 	 * the user "install", if such a user exists, or by the user
3248 	 * "nobody".  In order to support this dubious behavior, the path
3249 	 * to the zone being constructed is opened up during the life of
3250 	 * the command laying down the zone's root file system.  Once this
3251 	 * has completed, regardless of whether it was successful, the
3252 	 * path to the zone is again restricted.
3253 	 */
3254 	if (chmod(zonepath, DEFAULT_DIR_MODE) != 0) {
3255 		zperror(zonepath, B_FALSE);
3256 		err = Z_ERR;
3257 		goto done;
3258 	}
3259 
3260 	if (is_native_zone)
3261 		status = do_subproc(cmdbuf);
3262 	else
3263 		status = do_subproc_interactive(cmdbuf);
3264 
3265 	if (chmod(zonepath, S_IRWXU) != 0) {
3266 		zperror(zonepath, B_FALSE);
3267 		err = Z_ERR;
3268 		goto done;
3269 	}
3270 	if ((subproc_err =
3271 	    subproc_status(gettext("brand-specific installation"), status,
3272 	    B_FALSE)) != ZONE_SUBPROC_OK) {
3273 		err = Z_ERR;
3274 		goto done;
3275 	}
3276 
3277 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
3278 		errno = err;
3279 		zperror2(target_zone, gettext("could not set state"));
3280 		goto done;
3281 	}
3282 
3283 done:
3284 	/*
3285 	 * If the install script exited with ZONE_SUBPROC_USAGE or
3286 	 * ZONE_SUBPROC_NOTCOMPLETE, try to clean up the zone and leave the
3287 	 * zone in the CONFIGURED state so that another install can be
3288 	 * attempted without requiring an uninstall first.
3289 	 */
3290 	if ((subproc_err == ZONE_SUBPROC_USAGE) ||
3291 	    (subproc_err == ZONE_SUBPROC_NOTCOMPLETE)) {
3292 		if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
3293 			errno = err;
3294 			zperror2(target_zone,
3295 			    gettext("cleaning up zonepath failed"));
3296 		} else if ((err = zone_set_state(target_zone,
3297 		    ZONE_STATE_CONFIGURED)) != Z_OK) {
3298 			errno = err;
3299 			zperror2(target_zone, gettext("could not set state"));
3300 		}
3301 	}
3302 
3303 	release_lock_file(lockfd);
3304 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3305 }
3306 
3307 /*
3308  * Check that the inherited pkg dirs are the same for the clone and its source.
3309  * The easiest way to do that is check that the list of ipds is the same
3310  * by matching each one against the other.  This algorithm should be fine since
3311  * the list of ipds should not be that long.
3312  */
3313 static int
3314 valid_ipd_clone(zone_dochandle_t s_handle, char *source_zone,
3315 	zone_dochandle_t t_handle, char *target_zone)
3316 {
3317 	int err;
3318 	int res = Z_OK;
3319 	int s_cnt = 0;
3320 	int t_cnt = 0;
3321 	struct zone_fstab s_fstab;
3322 	struct zone_fstab t_fstab;
3323 
3324 	/*
3325 	 * First check the source of the clone against the target.
3326 	 */
3327 	if ((err = zonecfg_setipdent(s_handle)) != Z_OK) {
3328 		errno = err;
3329 		zperror2(source_zone, gettext("could not enumerate "
3330 		    "inherit-pkg-dirs"));
3331 		return (Z_ERR);
3332 	}
3333 
3334 	while (zonecfg_getipdent(s_handle, &s_fstab) == Z_OK) {
3335 		boolean_t match = B_FALSE;
3336 
3337 		s_cnt++;
3338 
3339 		if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
3340 			errno = err;
3341 			zperror2(target_zone, gettext("could not enumerate "
3342 			    "inherit-pkg-dirs"));
3343 			(void) zonecfg_endipdent(s_handle);
3344 			return (Z_ERR);
3345 		}
3346 
3347 		while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK) {
3348 			if (strcmp(s_fstab.zone_fs_dir, t_fstab.zone_fs_dir)
3349 			    == 0) {
3350 				match = B_TRUE;
3351 				break;
3352 			}
3353 		}
3354 		(void) zonecfg_endipdent(t_handle);
3355 
3356 		if (!match) {
3357 			(void) fprintf(stderr, gettext("inherit-pkg-dir "
3358 			    "'%s' is not configured in zone %s.\n"),
3359 			    s_fstab.zone_fs_dir, target_zone);
3360 			res = Z_ERR;
3361 		}
3362 	}
3363 
3364 	(void) zonecfg_endipdent(s_handle);
3365 
3366 	/* skip the next check if we already have errors */
3367 	if (res == Z_ERR)
3368 		return (res);
3369 
3370 	/*
3371 	 * Now check the number of ipds in the target so we can verify
3372 	 * that the source is not a subset of the target.
3373 	 */
3374 	if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
3375 		errno = err;
3376 		zperror2(target_zone, gettext("could not enumerate "
3377 		    "inherit-pkg-dirs"));
3378 		return (Z_ERR);
3379 	}
3380 
3381 	while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK)
3382 		t_cnt++;
3383 
3384 	(void) zonecfg_endipdent(t_handle);
3385 
3386 	if (t_cnt != s_cnt) {
3387 		(void) fprintf(stderr, gettext("Zone %s is configured "
3388 		    "with inherit-pkg-dirs that are not configured in zone "
3389 		    "%s.\n"), target_zone, source_zone);
3390 		res = Z_ERR;
3391 	}
3392 
3393 	return (res);
3394 }
3395 
3396 static void
3397 warn_dev_match(zone_dochandle_t s_handle, char *source_zone,
3398 	zone_dochandle_t t_handle, char *target_zone)
3399 {
3400 	int err;
3401 	struct zone_devtab s_devtab;
3402 	struct zone_devtab t_devtab;
3403 
3404 	if ((err = zonecfg_setdevent(t_handle)) != Z_OK) {
3405 		errno = err;
3406 		zperror2(target_zone, gettext("could not enumerate devices"));
3407 		return;
3408 	}
3409 
3410 	while (zonecfg_getdevent(t_handle, &t_devtab) == Z_OK) {
3411 		if ((err = zonecfg_setdevent(s_handle)) != Z_OK) {
3412 			errno = err;
3413 			zperror2(source_zone,
3414 			    gettext("could not enumerate devices"));
3415 			(void) zonecfg_enddevent(t_handle);
3416 			return;
3417 		}
3418 
3419 		while (zonecfg_getdevent(s_handle, &s_devtab) == Z_OK) {
3420 			/*
3421 			 * Use fnmatch to catch the case where wildcards
3422 			 * were used in one zone and the other has an
3423 			 * explicit entry (e.g. /dev/dsk/c0t0d0s6 vs.
3424 			 * /dev/\*dsk/c0t0d0s6).
3425 			 */
3426 			if (fnmatch(t_devtab.zone_dev_match,
3427 			    s_devtab.zone_dev_match, FNM_PATHNAME) == 0 ||
3428 			    fnmatch(s_devtab.zone_dev_match,
3429 			    t_devtab.zone_dev_match, FNM_PATHNAME) == 0) {
3430 				(void) fprintf(stderr,
3431 				    gettext("WARNING: device '%s' "
3432 				    "is configured in both zones.\n"),
3433 				    t_devtab.zone_dev_match);
3434 				break;
3435 			}
3436 		}
3437 		(void) zonecfg_enddevent(s_handle);
3438 	}
3439 
3440 	(void) zonecfg_enddevent(t_handle);
3441 }
3442 
3443 /*
3444  * Check if the specified mount option (opt) is contained within the
3445  * options string.
3446  */
3447 static boolean_t
3448 opt_match(char *opt, char *options)
3449 {
3450 	char *p;
3451 	char *lastp;
3452 
3453 	if ((p = strtok_r(options, ",", &lastp)) != NULL) {
3454 		if (strcmp(p, opt) == 0)
3455 			return (B_TRUE);
3456 		while ((p = strtok_r(NULL, ",", &lastp)) != NULL) {
3457 			if (strcmp(p, opt) == 0)
3458 				return (B_TRUE);
3459 		}
3460 	}
3461 
3462 	return (B_FALSE);
3463 }
3464 
3465 #define	RW_LOFS	"WARNING: read-write lofs file system on '%s' is configured " \
3466 	"in both zones.\n"
3467 
3468 static void
3469 print_fs_warnings(struct zone_fstab *s_fstab, struct zone_fstab *t_fstab)
3470 {
3471 	/*
3472 	 * It is ok to have shared lofs mounted fs but we want to warn if
3473 	 * either is rw since this will effect the other zone.
3474 	 */
3475 	if (strcmp(t_fstab->zone_fs_type, "lofs") == 0) {
3476 		zone_fsopt_t *optp;
3477 
3478 		/* The default is rw so no options means rw */
3479 		if (t_fstab->zone_fs_options == NULL ||
3480 		    s_fstab->zone_fs_options == NULL) {
3481 			(void) fprintf(stderr, gettext(RW_LOFS),
3482 			    t_fstab->zone_fs_special);
3483 			return;
3484 		}
3485 
3486 		for (optp = s_fstab->zone_fs_options; optp != NULL;
3487 		    optp = optp->zone_fsopt_next) {
3488 			if (opt_match("rw", optp->zone_fsopt_opt)) {
3489 				(void) fprintf(stderr, gettext(RW_LOFS),
3490 				    s_fstab->zone_fs_special);
3491 				return;
3492 			}
3493 		}
3494 
3495 		for (optp = t_fstab->zone_fs_options; optp != NULL;
3496 		    optp = optp->zone_fsopt_next) {
3497 			if (opt_match("rw", optp->zone_fsopt_opt)) {
3498 				(void) fprintf(stderr, gettext(RW_LOFS),
3499 				    t_fstab->zone_fs_special);
3500 				return;
3501 			}
3502 		}
3503 
3504 		return;
3505 	}
3506 
3507 	/*
3508 	 * TRANSLATION_NOTE
3509 	 * The first variable is the file system type and the second is
3510 	 * the file system special device.  For example,
3511 	 * WARNING: ufs file system on '/dev/dsk/c0t0d0s0' ...
3512 	 */
3513 	(void) fprintf(stderr, gettext("WARNING: %s file system on '%s' "
3514 	    "is configured in both zones.\n"), t_fstab->zone_fs_type,
3515 	    t_fstab->zone_fs_special);
3516 }
3517 
3518 static void
3519 warn_fs_match(zone_dochandle_t s_handle, char *source_zone,
3520 	zone_dochandle_t t_handle, char *target_zone)
3521 {
3522 	int err;
3523 	struct zone_fstab s_fstab;
3524 	struct zone_fstab t_fstab;
3525 
3526 	if ((err = zonecfg_setfsent(t_handle)) != Z_OK) {
3527 		errno = err;
3528 		zperror2(target_zone,
3529 		    gettext("could not enumerate file systems"));
3530 		return;
3531 	}
3532 
3533 	while (zonecfg_getfsent(t_handle, &t_fstab) == Z_OK) {
3534 		if ((err = zonecfg_setfsent(s_handle)) != Z_OK) {
3535 			errno = err;
3536 			zperror2(source_zone,
3537 			    gettext("could not enumerate file systems"));
3538 			(void) zonecfg_endfsent(t_handle);
3539 			return;
3540 		}
3541 
3542 		while (zonecfg_getfsent(s_handle, &s_fstab) == Z_OK) {
3543 			if (strcmp(t_fstab.zone_fs_special,
3544 			    s_fstab.zone_fs_special) == 0) {
3545 				print_fs_warnings(&s_fstab, &t_fstab);
3546 				break;
3547 			}
3548 		}
3549 		(void) zonecfg_endfsent(s_handle);
3550 	}
3551 
3552 	(void) zonecfg_endfsent(t_handle);
3553 }
3554 
3555 /*
3556  * We don't catch the case where you used the same IP address but
3557  * it is not an exact string match.  For example, 192.9.0.128 vs. 192.09.0.128.
3558  * However, we're not going to worry about that but we will check for
3559  * a possible netmask on one of the addresses (e.g. 10.0.0.1 and 10.0.0.1/24)
3560  * and handle that case as a match.
3561  */
3562 static void
3563 warn_ip_match(zone_dochandle_t s_handle, char *source_zone,
3564 	zone_dochandle_t t_handle, char *target_zone)
3565 {
3566 	int err;
3567 	struct zone_nwiftab s_nwiftab;
3568 	struct zone_nwiftab t_nwiftab;
3569 
3570 	if ((err = zonecfg_setnwifent(t_handle)) != Z_OK) {
3571 		errno = err;
3572 		zperror2(target_zone,
3573 		    gettext("could not enumerate network interfaces"));
3574 		return;
3575 	}
3576 
3577 	while (zonecfg_getnwifent(t_handle, &t_nwiftab) == Z_OK) {
3578 		char *p;
3579 
3580 		/* remove an (optional) netmask from the address */
3581 		if ((p = strchr(t_nwiftab.zone_nwif_address, '/')) != NULL)
3582 			*p = '\0';
3583 
3584 		if ((err = zonecfg_setnwifent(s_handle)) != Z_OK) {
3585 			errno = err;
3586 			zperror2(source_zone,
3587 			    gettext("could not enumerate network interfaces"));
3588 			(void) zonecfg_endnwifent(t_handle);
3589 			return;
3590 		}
3591 
3592 		while (zonecfg_getnwifent(s_handle, &s_nwiftab) == Z_OK) {
3593 			/* remove an (optional) netmask from the address */
3594 			if ((p = strchr(s_nwiftab.zone_nwif_address, '/'))
3595 			    != NULL)
3596 				*p = '\0';
3597 
3598 			/* For exclusive-IP zones, address is not specified. */
3599 			if (strlen(s_nwiftab.zone_nwif_address) == 0)
3600 				continue;
3601 
3602 			if (strcmp(t_nwiftab.zone_nwif_address,
3603 			    s_nwiftab.zone_nwif_address) == 0) {
3604 				(void) fprintf(stderr,
3605 				    gettext("WARNING: network address '%s' "
3606 				    "is configured in both zones.\n"),
3607 				    t_nwiftab.zone_nwif_address);
3608 				break;
3609 			}
3610 		}
3611 		(void) zonecfg_endnwifent(s_handle);
3612 	}
3613 
3614 	(void) zonecfg_endnwifent(t_handle);
3615 }
3616 
3617 static void
3618 warn_dataset_match(zone_dochandle_t s_handle, char *source,
3619 	zone_dochandle_t t_handle, char *target)
3620 {
3621 	int err;
3622 	struct zone_dstab s_dstab;
3623 	struct zone_dstab t_dstab;
3624 
3625 	if ((err = zonecfg_setdsent(t_handle)) != Z_OK) {
3626 		errno = err;
3627 		zperror2(target, gettext("could not enumerate datasets"));
3628 		return;
3629 	}
3630 
3631 	while (zonecfg_getdsent(t_handle, &t_dstab) == Z_OK) {
3632 		if ((err = zonecfg_setdsent(s_handle)) != Z_OK) {
3633 			errno = err;
3634 			zperror2(source,
3635 			    gettext("could not enumerate datasets"));
3636 			(void) zonecfg_enddsent(t_handle);
3637 			return;
3638 		}
3639 
3640 		while (zonecfg_getdsent(s_handle, &s_dstab) == Z_OK) {
3641 			if (strcmp(t_dstab.zone_dataset_name,
3642 			    s_dstab.zone_dataset_name) == 0) {
3643 				target_zone = source;
3644 				zerror(gettext("WARNING: dataset '%s' "
3645 				    "is configured in both zones.\n"),
3646 				    t_dstab.zone_dataset_name);
3647 				break;
3648 			}
3649 		}
3650 		(void) zonecfg_enddsent(s_handle);
3651 	}
3652 
3653 	(void) zonecfg_enddsent(t_handle);
3654 }
3655 
3656 /*
3657  * Check that the clone and its source have the same brand type.
3658  */
3659 static int
3660 valid_brand_clone(char *source_zone, char *target_zone)
3661 {
3662 	brand_handle_t bh;
3663 	char source_brand[MAXNAMELEN];
3664 
3665 	if ((zone_get_brand(source_zone, source_brand,
3666 	    sizeof (source_brand))) != Z_OK) {
3667 		(void) fprintf(stderr, "%s: zone '%s': %s\n",
3668 		    execname, source_zone, gettext("missing or invalid brand"));
3669 		return (Z_ERR);
3670 	}
3671 
3672 	if (strcmp(source_brand, target_brand) != NULL) {
3673 		(void) fprintf(stderr,
3674 		    gettext("%s: Zones '%s' and '%s' have different brand "
3675 		    "types.\n"), execname, source_zone, target_zone);
3676 		return (Z_ERR);
3677 	}
3678 
3679 	if ((bh = brand_open(target_brand)) == NULL) {
3680 		zerror(gettext("missing or invalid brand"));
3681 		return (Z_ERR);
3682 	}
3683 	brand_close(bh);
3684 	return (Z_OK);
3685 }
3686 
3687 static int
3688 validate_clone(char *source_zone, char *target_zone)
3689 {
3690 	int err = Z_OK;
3691 	zone_dochandle_t s_handle;
3692 	zone_dochandle_t t_handle;
3693 
3694 	if ((t_handle = zonecfg_init_handle()) == NULL) {
3695 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3696 		return (Z_ERR);
3697 	}
3698 	if ((err = zonecfg_get_handle(target_zone, t_handle)) != Z_OK) {
3699 		errno = err;
3700 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3701 		zonecfg_fini_handle(t_handle);
3702 		return (Z_ERR);
3703 	}
3704 
3705 	if ((s_handle = zonecfg_init_handle()) == NULL) {
3706 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3707 		zonecfg_fini_handle(t_handle);
3708 		return (Z_ERR);
3709 	}
3710 	if ((err = zonecfg_get_handle(source_zone, s_handle)) != Z_OK) {
3711 		errno = err;
3712 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3713 		goto done;
3714 	}
3715 
3716 	/* verify new zone has same brand type */
3717 	err = valid_brand_clone(source_zone, target_zone);
3718 	if (err != Z_OK)
3719 		goto done;
3720 
3721 	/* verify new zone has same inherit-pkg-dirs */
3722 	err = valid_ipd_clone(s_handle, source_zone, t_handle, target_zone);
3723 
3724 	/* warn about imported fs's which are the same */
3725 	warn_fs_match(s_handle, source_zone, t_handle, target_zone);
3726 
3727 	/* warn about imported IP addresses which are the same */
3728 	warn_ip_match(s_handle, source_zone, t_handle, target_zone);
3729 
3730 	/* warn about imported devices which are the same */
3731 	warn_dev_match(s_handle, source_zone, t_handle, target_zone);
3732 
3733 	/* warn about imported datasets which are the same */
3734 	warn_dataset_match(s_handle, source_zone, t_handle, target_zone);
3735 
3736 done:
3737 	zonecfg_fini_handle(t_handle);
3738 	zonecfg_fini_handle(s_handle);
3739 
3740 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3741 }
3742 
3743 static int
3744 copy_zone(char *src, char *dst)
3745 {
3746 	boolean_t out_null = B_FALSE;
3747 	int status;
3748 	char *outfile;
3749 	char cmdbuf[MAXPATHLEN * 2 + 128];
3750 
3751 	if ((outfile = tempnam("/var/log", "zone")) == NULL) {
3752 		outfile = "/dev/null";
3753 		out_null = B_TRUE;
3754 	}
3755 
3756 	/*
3757 	 * Use find to get the list of files to copy.  We need to skip
3758 	 * files of type "socket" since cpio can't handle those but that
3759 	 * should be ok since the app will recreate the socket when it runs.
3760 	 * We also need to filter out anything under the .zfs subdir.  Since
3761 	 * find is running depth-first, we need the extra egrep to filter .zfs.
3762 	 */
3763 	(void) snprintf(cmdbuf, sizeof (cmdbuf),
3764 	    "cd %s && /usr/bin/find . -type s -prune -o -depth -print | "
3765 	    "/usr/bin/egrep -v '^\\./\\.zfs$|^\\./\\.zfs/' | "
3766 	    "/usr/bin/cpio -pdmuP@ %s > %s 2>&1",
3767 	    src, dst, outfile);
3768 
3769 	status = do_subproc(cmdbuf);
3770 
3771 	if (subproc_status("copy", status, B_TRUE) != ZONE_SUBPROC_OK) {
3772 		if (!out_null)
3773 			(void) fprintf(stderr, gettext("\nThe copy failed.\n"
3774 			    "More information can be found in %s\n"), outfile);
3775 		return (Z_ERR);
3776 	}
3777 
3778 	if (!out_null)
3779 		(void) unlink(outfile);
3780 
3781 	return (Z_OK);
3782 }
3783 
3784 static int
3785 zone_postclone(char *zonepath)
3786 {
3787 	char cmdbuf[MAXPATHLEN];
3788 	int status;
3789 	brand_handle_t bh;
3790 	int err = Z_OK;
3791 
3792 	/*
3793 	 * Fetch the post-clone command, if any, from the brand
3794 	 * configuration.
3795 	 */
3796 	if ((bh = brand_open(target_brand)) == NULL) {
3797 		zerror(gettext("missing or invalid brand"));
3798 		return (Z_ERR);
3799 	}
3800 	(void) strcpy(cmdbuf, EXEC_PREFIX);
3801 	err = brand_get_postclone(bh, target_zone, zonepath, cmdbuf + EXEC_LEN,
3802 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL);
3803 	brand_close(bh);
3804 
3805 	if (err == 0 && strlen(cmdbuf) > EXEC_LEN) {
3806 		status = do_subproc(cmdbuf);
3807 		if ((err = subproc_status("postclone", status, B_FALSE))
3808 		    != ZONE_SUBPROC_OK) {
3809 			zerror(gettext("post-clone configuration failed."));
3810 			err = Z_ERR;
3811 		}
3812 	}
3813 
3814 	return (err);
3815 }
3816 
3817 /* ARGSUSED */
3818 static int
3819 zfm_print(const char *p, void *r) {
3820 	zerror("  %s\n", p);
3821 	return (0);
3822 }
3823 
3824 int
3825 clone_copy(char *source_zonepath, char *zonepath)
3826 {
3827 	int err;
3828 
3829 	/* Don't clone the zone if anything is still mounted there */
3830 	if (zonecfg_find_mounts(source_zonepath, NULL, NULL)) {
3831 		zerror(gettext("These file systems are mounted on "
3832 		    "subdirectories of %s.\n"), source_zonepath);
3833 		(void) zonecfg_find_mounts(source_zonepath, zfm_print, NULL);
3834 		return (Z_ERR);
3835 	}
3836 
3837 	/*
3838 	 * Attempt to create a ZFS fs for the zonepath.  As usual, we don't
3839 	 * care if this works or not since we always have the default behavior
3840 	 * of a simple directory for the zonepath.
3841 	 */
3842 	create_zfs_zonepath(zonepath);
3843 
3844 	(void) printf(gettext("Copying %s..."), source_zonepath);
3845 	(void) fflush(stdout);
3846 
3847 	err = copy_zone(source_zonepath, zonepath);
3848 
3849 	(void) printf("\n");
3850 
3851 	return (err);
3852 }
3853 
3854 static int
3855 clone_func(int argc, char *argv[])
3856 {
3857 	char *source_zone = NULL;
3858 	int lockfd;
3859 	int err, arg;
3860 	char zonepath[MAXPATHLEN];
3861 	char source_zonepath[MAXPATHLEN];
3862 	zone_state_t state;
3863 	zone_entry_t *zent;
3864 	char *method = NULL;
3865 	char *snapshot = NULL;
3866 
3867 	if (zonecfg_in_alt_root()) {
3868 		zerror(gettext("cannot clone zone in alternate root"));
3869 		return (Z_ERR);
3870 	}
3871 
3872 	optind = 0;
3873 	if ((arg = getopt(argc, argv, "?m:s:")) != EOF) {
3874 		switch (arg) {
3875 		case '?':
3876 			sub_usage(SHELP_CLONE, CMD_CLONE);
3877 			return (optopt == '?' ? Z_OK : Z_USAGE);
3878 		case 'm':
3879 			method = optarg;
3880 			break;
3881 		case 's':
3882 			snapshot = optarg;
3883 			break;
3884 		default:
3885 			sub_usage(SHELP_CLONE, CMD_CLONE);
3886 			return (Z_USAGE);
3887 		}
3888 	}
3889 	if (argc != (optind + 1) ||
3890 	    (method != NULL && strcmp(method, "copy") != 0)) {
3891 		sub_usage(SHELP_CLONE, CMD_CLONE);
3892 		return (Z_USAGE);
3893 	}
3894 	source_zone = argv[optind];
3895 	if (sanity_check(target_zone, CMD_CLONE, B_FALSE, B_TRUE, B_FALSE)
3896 	    != Z_OK)
3897 		return (Z_ERR);
3898 	if (verify_details(CMD_CLONE, argv) != Z_OK)
3899 		return (Z_ERR);
3900 
3901 	/*
3902 	 * We also need to do some extra validation on the source zone.
3903 	 */
3904 	if (strcmp(source_zone, GLOBAL_ZONENAME) == 0) {
3905 		zerror(gettext("%s operation is invalid for the global zone."),
3906 		    cmd_to_str(CMD_CLONE));
3907 		return (Z_ERR);
3908 	}
3909 
3910 	if (strncmp(source_zone, "SUNW", 4) == 0) {
3911 		zerror(gettext("%s operation is invalid for zones starting "
3912 		    "with SUNW."), cmd_to_str(CMD_CLONE));
3913 		return (Z_ERR);
3914 	}
3915 
3916 	zent = lookup_running_zone(source_zone);
3917 	if (zent != NULL) {
3918 		/* check whether the zone is ready or running */
3919 		if ((err = zone_get_state(zent->zname, &zent->zstate_num))
3920 		    != Z_OK) {
3921 			errno = err;
3922 			zperror2(zent->zname, gettext("could not get state"));
3923 			/* can't tell, so hedge */
3924 			zent->zstate_str = "ready/running";
3925 		} else {
3926 			zent->zstate_str = zone_state_str(zent->zstate_num);
3927 		}
3928 		zerror(gettext("%s operation is invalid for %s zones."),
3929 		    cmd_to_str(CMD_CLONE), zent->zstate_str);
3930 		return (Z_ERR);
3931 	}
3932 
3933 	if ((err = zone_get_state(source_zone, &state)) != Z_OK) {
3934 		errno = err;
3935 		zperror2(source_zone, gettext("could not get state"));
3936 		return (Z_ERR);
3937 	}
3938 	if (state != ZONE_STATE_INSTALLED) {
3939 		(void) fprintf(stderr,
3940 		    gettext("%s: zone %s is %s; %s is required.\n"),
3941 		    execname, source_zone, zone_state_str(state),
3942 		    zone_state_str(ZONE_STATE_INSTALLED));
3943 		return (Z_ERR);
3944 	}
3945 
3946 	/*
3947 	 * The source zone checks out ok, continue with the clone.
3948 	 */
3949 
3950 	if (validate_clone(source_zone, target_zone) != Z_OK)
3951 		return (Z_ERR);
3952 
3953 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
3954 		zerror(gettext("another %s may have an operation in progress."),
3955 		    "zoneadm");
3956 		return (Z_ERR);
3957 	}
3958 
3959 	if ((err = zone_get_zonepath(source_zone, source_zonepath,
3960 	    sizeof (source_zonepath))) != Z_OK) {
3961 		errno = err;
3962 		zperror2(source_zone, gettext("could not get zone path"));
3963 		goto done;
3964 	}
3965 
3966 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3967 	    != Z_OK) {
3968 		errno = err;
3969 		zperror2(target_zone, gettext("could not get zone path"));
3970 		goto done;
3971 	}
3972 
3973 	if ((err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE))
3974 	    != Z_OK) {
3975 		errno = err;
3976 		zperror2(target_zone, gettext("could not set state"));
3977 		goto done;
3978 	}
3979 
3980 	if (snapshot != NULL) {
3981 		err = clone_snapshot_zfs(snapshot, zonepath);
3982 	} else {
3983 		/*
3984 		 * We always copy the clone unless the source is ZFS and a
3985 		 * ZFS clone worked.  We fallback to copying if the ZFS clone
3986 		 * fails for some reason.
3987 		 */
3988 		err = Z_ERR;
3989 		if (method == NULL && is_zonepath_zfs(source_zonepath))
3990 			err = clone_zfs(source_zone, source_zonepath, zonepath);
3991 
3992 		if (err != Z_OK)
3993 			err = clone_copy(source_zonepath, zonepath);
3994 	}
3995 
3996 	/*
3997 	 * Trusted Extensions requires that cloned zones use the same sysid
3998 	 * configuration, so it is not appropriate to perform any
3999 	 * post-clone reconfiguration.
4000 	 */
4001 	if ((err == Z_OK) && !is_system_labeled())
4002 		err = zone_postclone(zonepath);
4003 
4004 done:
4005 	/*
4006 	 * If everything went well, we mark the zone as installed.
4007 	 */
4008 	if (err == Z_OK) {
4009 		err = zone_set_state(target_zone, ZONE_STATE_INSTALLED);
4010 		if (err != Z_OK) {
4011 			errno = err;
4012 			zperror2(target_zone, gettext("could not set state"));
4013 		}
4014 	}
4015 	release_lock_file(lockfd);
4016 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4017 }
4018 
4019 /*
4020  * Used when removing a zonepath after uninstalling or cleaning up after
4021  * the move subcommand.  This handles a zonepath that has non-standard
4022  * contents so that we will only cleanup the stuff we know about and leave
4023  * any user data alone.
4024  *
4025  * If the "all" parameter is true then we should remove the whole zonepath
4026  * even if it has non-standard files/directories in it.  This can be used when
4027  * we need to cleanup after moving the zonepath across file systems.
4028  *
4029  * We "exec" the RMCOMMAND so that the returned status is that of RMCOMMAND
4030  * and not the shell.
4031  */
4032 static int
4033 cleanup_zonepath(char *zonepath, boolean_t all)
4034 {
4035 	int		status;
4036 	int		i;
4037 	boolean_t	non_std = B_FALSE;
4038 	struct dirent	*dp;
4039 	DIR		*dirp;
4040 			/*
4041 			 * The SUNWattached.xml file is expected since it might
4042 			 * exist if the zone was force-attached after a
4043 			 * migration.
4044 			 */
4045 	char		*std_entries[] = {"dev", "lu", "root",
4046 			    "SUNWattached.xml", NULL};
4047 			/* (MAXPATHLEN * 3) is for the 3 std_entries dirs */
4048 	char		cmdbuf[sizeof (RMCOMMAND) + (MAXPATHLEN * 3) + 64];
4049 
4050 	/*
4051 	 * We shouldn't need these checks but lets be paranoid since we
4052 	 * could blow away the whole system here if we got the wrong zonepath.
4053 	 */
4054 	if (*zonepath == NULL || strcmp(zonepath, "/") == 0) {
4055 		(void) fprintf(stderr, "invalid zonepath '%s'\n", zonepath);
4056 		return (Z_INVAL);
4057 	}
4058 
4059 	/*
4060 	 * If the dirpath is already gone (maybe it was manually removed) then
4061 	 * we just return Z_OK so that the cleanup is successful.
4062 	 */
4063 	if ((dirp = opendir(zonepath)) == NULL)
4064 		return (Z_OK);
4065 
4066 	/*
4067 	 * Look through the zonepath directory to see if there are any
4068 	 * non-standard files/dirs.  Also skip .zfs since that might be
4069 	 * there but we'll handle ZFS file systems as a special case.
4070 	 */
4071 	while ((dp = readdir(dirp)) != NULL) {
4072 		if (strcmp(dp->d_name, ".") == 0 ||
4073 		    strcmp(dp->d_name, "..") == 0 ||
4074 		    strcmp(dp->d_name, ".zfs") == 0)
4075 			continue;
4076 
4077 		for (i = 0; std_entries[i] != NULL; i++)
4078 			if (strcmp(dp->d_name, std_entries[i]) == 0)
4079 				break;
4080 
4081 		if (std_entries[i] == NULL)
4082 			non_std = B_TRUE;
4083 	}
4084 	(void) closedir(dirp);
4085 
4086 	if (!all && non_std) {
4087 		/*
4088 		 * There are extra, non-standard directories/files in the
4089 		 * zonepath so we don't want to remove the zonepath.  We
4090 		 * just want to remove the standard directories and leave
4091 		 * the user data alone.
4092 		 */
4093 		(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND);
4094 
4095 		for (i = 0; std_entries[i] != NULL; i++) {
4096 			char tmpbuf[MAXPATHLEN];
4097 
4098 			if (snprintf(tmpbuf, sizeof (tmpbuf), " %s/%s",
4099 			    zonepath, std_entries[i]) >= sizeof (tmpbuf) ||
4100 			    strlcat(cmdbuf, tmpbuf, sizeof (cmdbuf)) >=
4101 			    sizeof (cmdbuf)) {
4102 				(void) fprintf(stderr,
4103 				    gettext("path is too long\n"));
4104 				return (Z_INVAL);
4105 			}
4106 		}
4107 
4108 		status = do_subproc(cmdbuf);
4109 
4110 		(void) fprintf(stderr, gettext("WARNING: Unable to completely "
4111 		    "remove %s\nbecause it contains additional user data.  "
4112 		    "Only the standard directory\nentries have been "
4113 		    "removed.\n"),
4114 		    zonepath);
4115 
4116 		return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
4117 		    ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
4118 	}
4119 
4120 	/*
4121 	 * There is nothing unexpected in the zonepath, try to get rid of the
4122 	 * whole zonepath directory.
4123 	 *
4124 	 * If the zonepath is its own zfs file system, try to destroy the
4125 	 * file system.  If that fails for some reason (e.g. it has clones)
4126 	 * then we'll just remove the contents of the zonepath.
4127 	 */
4128 	if (is_zonepath_zfs(zonepath)) {
4129 		if (destroy_zfs(zonepath) == Z_OK)
4130 			return (Z_OK);
4131 		(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND
4132 		    " %s/*", zonepath);
4133 		status = do_subproc(cmdbuf);
4134 		return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
4135 		    ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
4136 	}
4137 
4138 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
4139 	    zonepath);
4140 	status = do_subproc(cmdbuf);
4141 
4142 	return ((subproc_status(RMCOMMAND, status, B_TRUE) == ZONE_SUBPROC_OK)
4143 	    ? Z_OK : Z_ERR);
4144 }
4145 
4146 static int
4147 move_func(int argc, char *argv[])
4148 {
4149 	char *new_zonepath = NULL;
4150 	int lockfd;
4151 	int err, arg;
4152 	char zonepath[MAXPATHLEN];
4153 	zone_dochandle_t handle;
4154 	boolean_t fast;
4155 	boolean_t is_zfs = B_FALSE;
4156 	struct dirent *dp;
4157 	DIR *dirp;
4158 	boolean_t empty = B_TRUE;
4159 	boolean_t revert;
4160 	struct stat zonepath_buf;
4161 	struct stat new_zonepath_buf;
4162 
4163 	if (zonecfg_in_alt_root()) {
4164 		zerror(gettext("cannot move zone in alternate root"));
4165 		return (Z_ERR);
4166 	}
4167 
4168 	optind = 0;
4169 	if ((arg = getopt(argc, argv, "?")) != EOF) {
4170 		switch (arg) {
4171 		case '?':
4172 			sub_usage(SHELP_MOVE, CMD_MOVE);
4173 			return (optopt == '?' ? Z_OK : Z_USAGE);
4174 		default:
4175 			sub_usage(SHELP_MOVE, CMD_MOVE);
4176 			return (Z_USAGE);
4177 		}
4178 	}
4179 	if (argc != (optind + 1)) {
4180 		sub_usage(SHELP_MOVE, CMD_MOVE);
4181 		return (Z_USAGE);
4182 	}
4183 	new_zonepath = argv[optind];
4184 	if (sanity_check(target_zone, CMD_MOVE, B_FALSE, B_TRUE, B_FALSE)
4185 	    != Z_OK)
4186 		return (Z_ERR);
4187 	if (verify_details(CMD_MOVE, argv) != Z_OK)
4188 		return (Z_ERR);
4189 
4190 	/*
4191 	 * Check out the new zonepath.  This has the side effect of creating
4192 	 * a directory for the new zonepath.  We depend on this later when we
4193 	 * stat to see if we are doing a cross file system move or not.
4194 	 */
4195 	if (validate_zonepath(new_zonepath, CMD_MOVE) != Z_OK)
4196 		return (Z_ERR);
4197 
4198 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4199 	    != Z_OK) {
4200 		errno = err;
4201 		zperror2(target_zone, gettext("could not get zone path"));
4202 		return (Z_ERR);
4203 	}
4204 
4205 	if (stat(zonepath, &zonepath_buf) == -1) {
4206 		zperror(gettext("could not stat zone path"), B_FALSE);
4207 		return (Z_ERR);
4208 	}
4209 
4210 	if (stat(new_zonepath, &new_zonepath_buf) == -1) {
4211 		zperror(gettext("could not stat new zone path"), B_FALSE);
4212 		return (Z_ERR);
4213 	}
4214 
4215 	/*
4216 	 * Check if the destination directory is empty.
4217 	 */
4218 	if ((dirp = opendir(new_zonepath)) == NULL) {
4219 		zperror(gettext("could not open new zone path"), B_FALSE);
4220 		return (Z_ERR);
4221 	}
4222 	while ((dp = readdir(dirp)) != (struct dirent *)0) {
4223 		if (strcmp(dp->d_name, ".") == 0 ||
4224 		    strcmp(dp->d_name, "..") == 0)
4225 			continue;
4226 		empty = B_FALSE;
4227 		break;
4228 	}
4229 	(void) closedir(dirp);
4230 
4231 	/* Error if there is anything in the destination directory. */
4232 	if (!empty) {
4233 		(void) fprintf(stderr, gettext("could not move zone to %s: "
4234 		    "directory not empty\n"), new_zonepath);
4235 		return (Z_ERR);
4236 	}
4237 
4238 	/* Don't move the zone if anything is still mounted there */
4239 	if (zonecfg_find_mounts(zonepath, NULL, NULL)) {
4240 		zerror(gettext("These file systems are mounted on "
4241 		    "subdirectories of %s.\n"), zonepath);
4242 		(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
4243 		return (Z_ERR);
4244 	}
4245 
4246 	/*
4247 	 * Check if we are moving in the same file system and can do a fast
4248 	 * move or if we are crossing file systems and have to copy the data.
4249 	 */
4250 	fast = (zonepath_buf.st_dev == new_zonepath_buf.st_dev);
4251 
4252 	if ((handle = zonecfg_init_handle()) == NULL) {
4253 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4254 		return (Z_ERR);
4255 	}
4256 
4257 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4258 		errno = err;
4259 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4260 		zonecfg_fini_handle(handle);
4261 		return (Z_ERR);
4262 	}
4263 
4264 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
4265 		zerror(gettext("another %s may have an operation in progress."),
4266 		    "zoneadm");
4267 		zonecfg_fini_handle(handle);
4268 		return (Z_ERR);
4269 	}
4270 
4271 	/*
4272 	 * We're making some file system changes now so we have to clean up
4273 	 * the file system before we are done.  This will either clean up the
4274 	 * new zonepath if the zonecfg update failed or it will clean up the
4275 	 * old zonepath if everything is ok.
4276 	 */
4277 	revert = B_TRUE;
4278 
4279 	if (is_zonepath_zfs(zonepath) &&
4280 	    move_zfs(zonepath, new_zonepath) != Z_ERR) {
4281 		is_zfs = B_TRUE;
4282 
4283 	} else if (fast) {
4284 		/* same file system, use rename for a quick move */
4285 
4286 		/*
4287 		 * Remove the new_zonepath directory that got created above
4288 		 * during the validation.  It gets in the way of the rename.
4289 		 */
4290 		if (rmdir(new_zonepath) != 0) {
4291 			zperror(gettext("could not rmdir new zone path"),
4292 			    B_FALSE);
4293 			zonecfg_fini_handle(handle);
4294 			release_lock_file(lockfd);
4295 			return (Z_ERR);
4296 		}
4297 
4298 		if (rename(zonepath, new_zonepath) != 0) {
4299 			/*
4300 			 * If this fails we don't need to do all of the
4301 			 * cleanup that happens for the rest of the code
4302 			 * so just return from this error.
4303 			 */
4304 			zperror(gettext("could not move zone"), B_FALSE);
4305 			zonecfg_fini_handle(handle);
4306 			release_lock_file(lockfd);
4307 			return (Z_ERR);
4308 		}
4309 
4310 	} else {
4311 		/*
4312 		 * Attempt to create a ZFS fs for the new zonepath.  As usual,
4313 		 * we don't care if this works or not since we always have the
4314 		 * default behavior of a simple directory for the zonepath.
4315 		 */
4316 		create_zfs_zonepath(new_zonepath);
4317 
4318 		(void) printf(gettext(
4319 		    "Moving across file systems; copying zonepath %s..."),
4320 		    zonepath);
4321 		(void) fflush(stdout);
4322 
4323 		err = copy_zone(zonepath, new_zonepath);
4324 
4325 		(void) printf("\n");
4326 		if (err != Z_OK)
4327 			goto done;
4328 	}
4329 
4330 	if ((err = zonecfg_set_zonepath(handle, new_zonepath)) != Z_OK) {
4331 		errno = err;
4332 		zperror(gettext("could not set new zonepath"), B_TRUE);
4333 		goto done;
4334 	}
4335 
4336 	if ((err = zonecfg_save(handle)) != Z_OK) {
4337 		errno = err;
4338 		zperror(gettext("zonecfg save failed"), B_TRUE);
4339 		goto done;
4340 	}
4341 
4342 	revert = B_FALSE;
4343 
4344 done:
4345 	zonecfg_fini_handle(handle);
4346 	release_lock_file(lockfd);
4347 
4348 	/*
4349 	 * Clean up the file system based on how things went.  We either
4350 	 * clean up the new zonepath if the operation failed for some reason
4351 	 * or we clean up the old zonepath if everything is ok.
4352 	 */
4353 	if (revert) {
4354 		/* The zonecfg update failed, cleanup the new zonepath. */
4355 		if (is_zfs) {
4356 			if (move_zfs(new_zonepath, zonepath) == Z_ERR) {
4357 				(void) fprintf(stderr, gettext("could not "
4358 				    "restore zonepath, the zfs mountpoint is "
4359 				    "set as:\n%s\n"), new_zonepath);
4360 				/*
4361 				 * err is already != Z_OK since we're reverting
4362 				 */
4363 			}
4364 
4365 		} else if (fast) {
4366 			if (rename(new_zonepath, zonepath) != 0) {
4367 				zperror(gettext("could not restore zonepath"),
4368 				    B_FALSE);
4369 				/*
4370 				 * err is already != Z_OK since we're reverting
4371 				 */
4372 			}
4373 		} else {
4374 			(void) printf(gettext("Cleaning up zonepath %s..."),
4375 			    new_zonepath);
4376 			(void) fflush(stdout);
4377 			err = cleanup_zonepath(new_zonepath, B_TRUE);
4378 			(void) printf("\n");
4379 
4380 			if (err != Z_OK) {
4381 				errno = err;
4382 				zperror(gettext("could not remove new "
4383 				    "zonepath"), B_TRUE);
4384 			} else {
4385 				/*
4386 				 * Because we're reverting we know the mainline
4387 				 * code failed but we just reused the err
4388 				 * variable so we reset it back to Z_ERR.
4389 				 */
4390 				err = Z_ERR;
4391 			}
4392 		}
4393 
4394 	} else {
4395 		/* The move was successful, cleanup the old zonepath. */
4396 		if (!is_zfs && !fast) {
4397 			(void) printf(
4398 			    gettext("Cleaning up zonepath %s..."), zonepath);
4399 			(void) fflush(stdout);
4400 			err = cleanup_zonepath(zonepath, B_TRUE);
4401 			(void) printf("\n");
4402 
4403 			if (err != Z_OK) {
4404 				errno = err;
4405 				zperror(gettext("could not remove zonepath"),
4406 				    B_TRUE);
4407 			}
4408 		}
4409 	}
4410 
4411 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4412 }
4413 
4414 static int
4415 detach_func(int argc, char *argv[])
4416 {
4417 	int lockfd;
4418 	int err, arg;
4419 	char zonepath[MAXPATHLEN];
4420 	zone_dochandle_t handle;
4421 	boolean_t execute = B_TRUE;
4422 
4423 	if (zonecfg_in_alt_root()) {
4424 		zerror(gettext("cannot detach zone in alternate root"));
4425 		return (Z_ERR);
4426 	}
4427 
4428 	optind = 0;
4429 	if ((arg = getopt(argc, argv, "?n")) != EOF) {
4430 		switch (arg) {
4431 		case '?':
4432 			sub_usage(SHELP_DETACH, CMD_DETACH);
4433 			return (optopt == '?' ? Z_OK : Z_USAGE);
4434 		case 'n':
4435 			execute = B_FALSE;
4436 			break;
4437 		default:
4438 			sub_usage(SHELP_DETACH, CMD_DETACH);
4439 			return (Z_USAGE);
4440 		}
4441 	}
4442 
4443 	if (execute) {
4444 		if (sanity_check(target_zone, CMD_DETACH, B_FALSE, B_TRUE,
4445 		    B_FALSE) != Z_OK)
4446 			return (Z_ERR);
4447 		if (verify_details(CMD_DETACH, argv) != Z_OK)
4448 			return (Z_ERR);
4449 	} else {
4450 		/*
4451 		 * We want a dry-run to work for a non-privileged user so we
4452 		 * only do minimal validation.
4453 		 */
4454 		if (target_zone == NULL) {
4455 			zerror(gettext("no zone specified"));
4456 			return (Z_ERR);
4457 		}
4458 
4459 		if (strcmp(target_zone, GLOBAL_ZONENAME) == 0) {
4460 			zerror(gettext("%s operation is invalid for the "
4461 			    "global zone."), cmd_to_str(CMD_DETACH));
4462 			return (Z_ERR);
4463 		}
4464 	}
4465 
4466 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4467 	    != Z_OK) {
4468 		errno = err;
4469 		zperror2(target_zone, gettext("could not get zone path"));
4470 		return (Z_ERR);
4471 	}
4472 
4473 	/* Don't detach the zone if anything is still mounted there */
4474 	if (execute && zonecfg_find_mounts(zonepath, NULL, NULL)) {
4475 		zerror(gettext("These file systems are mounted on "
4476 		    "subdirectories of %s.\n"), zonepath);
4477 		(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
4478 		return (Z_ERR);
4479 	}
4480 
4481 	if ((handle = zonecfg_init_handle()) == NULL) {
4482 		zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4483 		return (Z_ERR);
4484 	}
4485 
4486 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4487 		errno = err;
4488 		zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4489 		zonecfg_fini_handle(handle);
4490 		return (Z_ERR);
4491 	}
4492 
4493 	if (execute && grab_lock_file(target_zone, &lockfd) != Z_OK) {
4494 		zerror(gettext("another %s may have an operation in progress."),
4495 		    "zoneadm");
4496 		zonecfg_fini_handle(handle);
4497 		return (Z_ERR);
4498 	}
4499 
4500 	if ((err = zonecfg_get_detach_info(handle, B_TRUE)) != Z_OK) {
4501 		errno = err;
4502 		zperror(gettext("getting the detach information failed"),
4503 		    B_TRUE);
4504 		goto done;
4505 	}
4506 
4507 	if ((err = zonecfg_detach_save(handle, (execute ? 0 : ZONE_DRY_RUN)))
4508 	    != Z_OK) {
4509 		errno = err;
4510 		zperror(gettext("saving the detach manifest failed"), B_TRUE);
4511 		goto done;
4512 	}
4513 
4514 	/*
4515 	 * Set the zone state back to configured unless we are running with the
4516 	 * no-execute option.
4517 	 */
4518 	if (execute && (err = zone_set_state(target_zone,
4519 	    ZONE_STATE_CONFIGURED)) != Z_OK) {
4520 		errno = err;
4521 		zperror(gettext("could not reset state"), B_TRUE);
4522 	}
4523 
4524 done:
4525 	zonecfg_fini_handle(handle);
4526 	if (execute)
4527 		release_lock_file(lockfd);
4528 
4529 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4530 }
4531 
4532 /*
4533  * During attach we go through and fix up the /dev entries for the zone
4534  * we are attaching.  In order to regenerate /dev with the correct devices,
4535  * the old /dev will be removed, the zone readied (which generates a new
4536  * /dev) then halted, then we use the info from the manifest to update
4537  * the modes, owners, etc. on the new /dev.
4538  */
4539 static int
4540 dev_fix(zone_dochandle_t handle)
4541 {
4542 	int			res;
4543 	int			err;
4544 	int			status;
4545 	struct zone_devpermtab	devtab;
4546 	zone_cmd_arg_t		zarg;
4547 	char			devpath[MAXPATHLEN];
4548 				/* 6: "exec " and " " */
4549 	char			cmdbuf[sizeof (RMCOMMAND) + MAXPATHLEN + 6];
4550 
4551 	if ((res = zonecfg_get_zonepath(handle, devpath, sizeof (devpath)))
4552 	    != Z_OK)
4553 		return (res);
4554 
4555 	if (strlcat(devpath, "/dev", sizeof (devpath)) >= sizeof (devpath))
4556 		return (Z_TOO_BIG);
4557 
4558 	/*
4559 	 * "exec" the command so that the returned status is that of
4560 	 * RMCOMMAND and not the shell.
4561 	 */
4562 	(void) snprintf(cmdbuf, sizeof (cmdbuf), EXEC_PREFIX RMCOMMAND " %s",
4563 	    devpath);
4564 	status = do_subproc(cmdbuf);
4565 	if ((err = subproc_status(RMCOMMAND, status, B_TRUE)) !=
4566 	    ZONE_SUBPROC_OK) {
4567 		(void) fprintf(stderr,
4568 		    gettext("could not remove existing /dev\n"));
4569 		return (Z_ERR);
4570 	}
4571 
4572 	/* In order to ready the zone, it must be in the installed state */
4573 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
4574 		errno = err;
4575 		zperror(gettext("could not reset state"), B_TRUE);
4576 		return (Z_ERR);
4577 	}
4578 
4579 	/* We have to ready the zone to regen the dev tree */
4580 	zarg.cmd = Z_READY;
4581 	if (call_zoneadmd(target_zone, &zarg) != 0) {
4582 		zerror(gettext("call to %s failed"), "zoneadmd");
4583 		/* attempt to restore zone to configured state */
4584 		(void) zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
4585 		return (Z_ERR);
4586 	}
4587 
4588 	zarg.cmd = Z_HALT;
4589 	if (call_zoneadmd(target_zone, &zarg) != 0) {
4590 		zerror(gettext("call to %s failed"), "zoneadmd");
4591 		/* attempt to restore zone to configured state */
4592 		(void) zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
4593 		return (Z_ERR);
4594 	}
4595 
4596 	/* attempt to restore zone to configured state */
4597 	(void) zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
4598 
4599 	if (zonecfg_setdevperment(handle) != Z_OK) {
4600 		(void) fprintf(stderr,
4601 		    gettext("unable to enumerate device entries\n"));
4602 		return (Z_ERR);
4603 	}
4604 
4605 	while (zonecfg_getdevperment(handle, &devtab) == Z_OK) {
4606 		int err;
4607 
4608 		if ((err = zonecfg_devperms_apply(handle,
4609 		    devtab.zone_devperm_name, devtab.zone_devperm_uid,
4610 		    devtab.zone_devperm_gid, devtab.zone_devperm_mode,
4611 		    devtab.zone_devperm_acl)) != Z_OK && err != Z_INVAL)
4612 			(void) fprintf(stderr, gettext("error updating device "
4613 			    "%s: %s\n"), devtab.zone_devperm_name,
4614 			    zonecfg_strerror(err));
4615 
4616 		free(devtab.zone_devperm_acl);
4617 	}
4618 
4619 	(void) zonecfg_enddevperment(handle);
4620 
4621 	return (Z_OK);
4622 }
4623 
4624 /*
4625  * Validate attaching a zone but don't actually do the work.  The zone
4626  * does not have to exist, so there is some complexity getting a new zone
4627  * configuration set up so that we can perform the validation.  This is
4628  * handled within zonecfg_attach_manifest() which returns two handles; one
4629  * for the the full configuration to validate (rem_handle) and the other
4630  * (local_handle) containing only the zone configuration derived from the
4631  * manifest.
4632  */
4633 static int
4634 dryrun_attach(char *manifest_path, char *argv[])
4635 {
4636 	int fd;
4637 	int err;
4638 	int res;
4639 	zone_dochandle_t local_handle;
4640 	zone_dochandle_t rem_handle = NULL;
4641 
4642 	if (strcmp(manifest_path, "-") == 0) {
4643 		fd = 0;
4644 	} else if ((fd = open(manifest_path, O_RDONLY)) < 0) {
4645 		zperror(gettext("could not open manifest path"), B_FALSE);
4646 		return (Z_ERR);
4647 	}
4648 
4649 	if ((local_handle = zonecfg_init_handle()) == NULL) {
4650 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4651 		res = Z_ERR;
4652 		goto done;
4653 	}
4654 
4655 	if ((rem_handle = zonecfg_init_handle()) == NULL) {
4656 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4657 		res = Z_ERR;
4658 		goto done;
4659 	}
4660 
4661 	if ((err = zonecfg_attach_manifest(fd, local_handle, rem_handle))
4662 	    != Z_OK) {
4663 		res = Z_ERR;
4664 
4665 		if (err == Z_INVALID_DOCUMENT) {
4666 			struct stat st;
4667 			char buf[6];
4668 
4669 			if (strcmp(manifest_path, "-") == 0) {
4670 				zerror(gettext("Input is not a valid XML "
4671 				    "file"));
4672 				goto done;
4673 			}
4674 
4675 			if (fstat(fd, &st) == -1 || !S_ISREG(st.st_mode)) {
4676 				zerror(gettext("%s is not an XML file"),
4677 				    manifest_path);
4678 				goto done;
4679 			}
4680 
4681 			bzero(buf, sizeof (buf));
4682 			(void) lseek(fd, 0L, SEEK_SET);
4683 			if (read(fd, buf, sizeof (buf) - 1) < 0 ||
4684 			    strncmp(buf, "<?xml", 5) != 0)
4685 				zerror(gettext("%s is not an XML file"),
4686 				    manifest_path);
4687 			else
4688 				zerror(gettext("Cannot attach to an earlier "
4689 				    "release of the operating system"));
4690 		} else {
4691 			zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4692 		}
4693 		goto done;
4694 	}
4695 
4696 	/*
4697 	 * Retrieve remote handle brand type and determine whether it is
4698 	 * native or not.
4699 	 */
4700 	if (zonecfg_get_brand(rem_handle, target_brand, sizeof (target_brand))
4701 	    != Z_OK) {
4702 		zerror(gettext("missing or invalid brand"));
4703 		exit(Z_ERR);
4704 	}
4705 	is_native_zone = (strcmp(target_brand, NATIVE_BRAND_NAME) == 0);
4706 	is_cluster_zone =
4707 	    (strcmp(target_brand, CLUSTER_BRAND_NAME) == 0);
4708 
4709 	res = verify_handle(CMD_ATTACH, local_handle, argv);
4710 
4711 	/* Get the detach information for the locally defined zone. */
4712 	if ((err = zonecfg_get_detach_info(local_handle, B_FALSE)) != Z_OK) {
4713 		errno = err;
4714 		zperror(gettext("getting the attach information failed"),
4715 		    B_TRUE);
4716 		res = Z_ERR;
4717 	} else {
4718 		/* sw_cmp prints error msgs as necessary */
4719 		if (sw_cmp(local_handle, rem_handle, SW_CMP_NONE) != Z_OK)
4720 			res = Z_ERR;
4721 	}
4722 
4723 done:
4724 	if (strcmp(manifest_path, "-") != 0)
4725 		(void) close(fd);
4726 
4727 	zonecfg_fini_handle(local_handle);
4728 	zonecfg_fini_handle(rem_handle);
4729 
4730 	return ((res == Z_OK) ? Z_OK : Z_ERR);
4731 }
4732 
4733 /*
4734  * Attempt to generate the information we need to make the zone look like
4735  * it was properly detached by using the pkg information contained within
4736  * the zone itself.
4737  *
4738  * We will perform a dry-run detach within the zone to generate the xml file.
4739  * To do this we need to be able to get a handle on the zone so we can see
4740  * how it is configured.  In order to get a handle, we need a copy of the
4741  * zone configuration within the zone.  Since the zone's configuration is
4742  * not available within the zone itself, we need to temporarily copy it into
4743  * the zone.
4744  *
4745  * The sequence of actions we are doing is this:
4746  *	[set zone state to installed]
4747  *	[mount zone]
4748  *	zlogin {zone} </etc/zones/{zone}.xml 'cat >/etc/zones/{zone}.xml'
4749  *	zlogin {zone} 'zoneadm -z {zone} detach -n' >{zonepath}/SUNWdetached.xml
4750  *	zlogin {zone} 'rm -f /etc/zones/{zone}.xml'
4751  *	[unmount zone]
4752  *	[set zone state to configured]
4753  *
4754  * The successful result of this function is that we will have a
4755  * SUNWdetached.xml file in the zonepath and we can use that to attach the zone.
4756  */
4757 static boolean_t
4758 gen_detach_info(char *zonepath)
4759 {
4760 	int		status;
4761 	boolean_t	mounted = B_FALSE;
4762 	boolean_t	res = B_FALSE;
4763 	char		cmdbuf[2 * MAXPATHLEN];
4764 
4765 	/*
4766 	 * The zone has to be installed to mount and zlogin.  Temporarily set
4767 	 * the state to 'installed'.
4768 	 */
4769 	if (zone_set_state(target_zone, ZONE_STATE_INSTALLED) != Z_OK)
4770 		return (B_FALSE);
4771 
4772 	/* Mount the zone so we can zlogin. */
4773 	if (mount_func(0, NULL) != Z_OK)
4774 		goto cleanup;
4775 	mounted = B_TRUE;
4776 
4777 	/*
4778 	 * We need to copy the zones xml configuration file into the
4779 	 * zone so we can get a handle for the zone while running inside
4780 	 * the zone.
4781 	 */
4782 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/sbin/zlogin -S %s "
4783 	    "</etc/zones/%s.xml '/usr/bin/cat >/etc/zones/%s.xml'",
4784 	    target_zone, target_zone, target_zone) >= sizeof (cmdbuf))
4785 		goto cleanup;
4786 
4787 	status = do_subproc_interactive(cmdbuf);
4788 	if (subproc_status("copy", status, B_TRUE) != ZONE_SUBPROC_OK)
4789 		goto cleanup;
4790 
4791 	/* Now run the detach command within the mounted zone. */
4792 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/sbin/zlogin -S %s "
4793 	    "'/usr/sbin/zoneadm -z %s detach -n' >%s/SUNWdetached.xml",
4794 	    target_zone, target_zone, zonepath) >= sizeof (cmdbuf))
4795 		goto cleanup;
4796 
4797 	status = do_subproc_interactive(cmdbuf);
4798 	if (subproc_status("detach", status, B_TRUE) != ZONE_SUBPROC_OK)
4799 		goto cleanup;
4800 
4801 	res = B_TRUE;
4802 
4803 cleanup:
4804 	/* Cleanup from the previous actions. */
4805 	if (mounted) {
4806 		if (snprintf(cmdbuf, sizeof (cmdbuf),
4807 		    "/usr/sbin/zlogin -S %s '/usr/bin/rm -f /etc/zones/%s.xml'",
4808 		    target_zone, target_zone) >= sizeof (cmdbuf)) {
4809 			res = B_FALSE;
4810 		} else {
4811 			status = do_subproc(cmdbuf);
4812 			if (subproc_status("rm", status, B_TRUE)
4813 			    != ZONE_SUBPROC_OK)
4814 				res = B_FALSE;
4815 		}
4816 
4817 		if (unmount_func(0, NULL) != Z_OK)
4818 			res =  B_FALSE;
4819 	}
4820 
4821 	if (zone_set_state(target_zone, ZONE_STATE_CONFIGURED) != Z_OK)
4822 		res = B_FALSE;
4823 
4824 	return (res);
4825 }
4826 
4827 static int
4828 attach_func(int argc, char *argv[])
4829 {
4830 	int lockfd;
4831 	int err, arg;
4832 	boolean_t force = B_FALSE;
4833 	zone_dochandle_t handle;
4834 	zone_dochandle_t athandle = NULL;
4835 	char zonepath[MAXPATHLEN];
4836 	char brand[MAXNAMELEN], atbrand[MAXNAMELEN];
4837 	boolean_t execute = B_TRUE;
4838 	boolean_t retried = B_FALSE;
4839 	char *manifest_path;
4840 
4841 	if (zonecfg_in_alt_root()) {
4842 		zerror(gettext("cannot attach zone in alternate root"));
4843 		return (Z_ERR);
4844 	}
4845 
4846 	optind = 0;
4847 	if ((arg = getopt(argc, argv, "?Fn:")) != EOF) {
4848 		switch (arg) {
4849 		case '?':
4850 			sub_usage(SHELP_ATTACH, CMD_ATTACH);
4851 			return (optopt == '?' ? Z_OK : Z_USAGE);
4852 		case 'F':
4853 			force = B_TRUE;
4854 			break;
4855 		case 'n':
4856 			execute = B_FALSE;
4857 			manifest_path = optarg;
4858 			break;
4859 		default:
4860 			sub_usage(SHELP_ATTACH, CMD_ATTACH);
4861 			return (Z_USAGE);
4862 		}
4863 	}
4864 
4865 	/*
4866 	 * If the no-execute option was specified, we need to branch down
4867 	 * a completely different path since there is no zone required to be
4868 	 * configured for this option.
4869 	 */
4870 	if (!execute)
4871 		return (dryrun_attach(manifest_path, argv));
4872 
4873 	if (sanity_check(target_zone, CMD_ATTACH, B_FALSE, B_TRUE, B_FALSE)
4874 	    != Z_OK)
4875 		return (Z_ERR);
4876 	if (verify_details(CMD_ATTACH, argv) != Z_OK)
4877 		return (Z_ERR);
4878 
4879 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4880 	    != Z_OK) {
4881 		errno = err;
4882 		zperror2(target_zone, gettext("could not get zone path"));
4883 		return (Z_ERR);
4884 	}
4885 
4886 	if ((handle = zonecfg_init_handle()) == NULL) {
4887 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4888 		return (Z_ERR);
4889 	}
4890 
4891 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4892 		errno = err;
4893 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4894 		zonecfg_fini_handle(handle);
4895 		return (Z_ERR);
4896 	}
4897 
4898 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
4899 		zerror(gettext("another %s may have an operation in progress."),
4900 		    "zoneadm");
4901 		zonecfg_fini_handle(handle);
4902 		return (Z_ERR);
4903 	}
4904 
4905 	if (force)
4906 		goto forced;
4907 
4908 	if ((athandle = zonecfg_init_handle()) == NULL) {
4909 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4910 		goto done;
4911 	}
4912 
4913 retry:
4914 	if ((err = zonecfg_get_attach_handle(zonepath, target_zone, B_TRUE,
4915 	    athandle)) != Z_OK) {
4916 		if (err == Z_NO_ZONE) {
4917 			/*
4918 			 * Zone was not detached.  Try to fall back to getting
4919 			 * the needed information from within the zone.
4920 			 * However, we can only try to generate the attach
4921 			 * information for native branded zones, so fail if the
4922 			 * zone is not native.
4923 			 */
4924 			if (!is_native_zone) {
4925 				zerror(gettext("Not a detached zone."));
4926 				goto done;
4927 			}
4928 
4929 			if (!retried) {
4930 				zerror(gettext("The zone was not properly "
4931 				    "detached.\n\tAttempting to attach "
4932 				    "anyway."));
4933 				if (gen_detach_info(zonepath)) {
4934 					retried = B_TRUE;
4935 					goto retry;
4936 				}
4937 			}
4938 			zerror(gettext("Cannot generate the information "
4939 			    "needed to attach this zone."));
4940 		} else if (err == Z_INVALID_DOCUMENT) {
4941 			zerror(gettext("Cannot attach to an earlier release "
4942 			    "of the operating system"));
4943 		} else {
4944 			zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4945 		}
4946 		goto done;
4947 	}
4948 
4949 	/* Get the detach information for the locally defined zone. */
4950 	if ((err = zonecfg_get_detach_info(handle, B_FALSE)) != Z_OK) {
4951 		errno = err;
4952 		zperror(gettext("getting the attach information failed"),
4953 		    B_TRUE);
4954 		goto done;
4955 	}
4956 
4957 	/*
4958 	 * Ensure that the detached and locally defined zones are both of
4959 	 * the same brand.
4960 	 */
4961 	if ((zonecfg_get_brand(handle, brand, sizeof (brand)) != 0) ||
4962 	    (zonecfg_get_brand(athandle, atbrand, sizeof (atbrand)) != 0)) {
4963 		err = Z_ERR;
4964 		zerror(gettext("missing or invalid brand"));
4965 		goto done;
4966 	}
4967 
4968 	if (strcmp(atbrand, brand) != NULL) {
4969 		err = Z_ERR;
4970 		zerror(gettext("Trying to attach a '%s' zone to a '%s' "
4971 		    "configuration."), atbrand, brand);
4972 		goto done;
4973 	}
4974 
4975 	/* sw_cmp prints error msgs as necessary */
4976 	if ((err = sw_cmp(handle, athandle, SW_CMP_NONE)) != Z_OK)
4977 		goto done;
4978 
4979 	if ((err = dev_fix(athandle)) != Z_OK)
4980 		goto done;
4981 
4982 forced:
4983 
4984 	zonecfg_rm_detached(handle, force);
4985 
4986 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
4987 		errno = err;
4988 		zperror(gettext("could not reset state"), B_TRUE);
4989 	}
4990 
4991 done:
4992 	zonecfg_fini_handle(handle);
4993 	release_lock_file(lockfd);
4994 	if (athandle != NULL)
4995 		zonecfg_fini_handle(athandle);
4996 
4997 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4998 }
4999 
5000 /*
5001  * On input, TRUE => yes, FALSE => no.
5002  * On return, TRUE => 1, FALSE => 0, could not ask => -1.
5003  */
5004 
5005 static int
5006 ask_yesno(boolean_t default_answer, const char *question)
5007 {
5008 	char line[64];	/* should be large enough to answer yes or no */
5009 
5010 	if (!isatty(STDIN_FILENO))
5011 		return (-1);
5012 	for (;;) {
5013 		(void) printf("%s (%s)? ", question,
5014 		    default_answer ? "[y]/n" : "y/[n]");
5015 		if (fgets(line, sizeof (line), stdin) == NULL ||
5016 		    line[0] == '\n')
5017 			return (default_answer ? 1 : 0);
5018 		if (tolower(line[0]) == 'y')
5019 			return (1);
5020 		if (tolower(line[0]) == 'n')
5021 			return (0);
5022 	}
5023 }
5024 
5025 static int
5026 uninstall_func(int argc, char *argv[])
5027 {
5028 	char line[ZONENAME_MAX + 128];	/* Enough for "Are you sure ..." */
5029 	char rootpath[MAXPATHLEN], zonepath[MAXPATHLEN];
5030 	boolean_t force = B_FALSE;
5031 	int lockfd, answer;
5032 	int err, arg;
5033 
5034 	if (zonecfg_in_alt_root()) {
5035 		zerror(gettext("cannot uninstall zone in alternate root"));
5036 		return (Z_ERR);
5037 	}
5038 
5039 	optind = 0;
5040 	while ((arg = getopt(argc, argv, "?F")) != EOF) {
5041 		switch (arg) {
5042 		case '?':
5043 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5044 			return (optopt == '?' ? Z_OK : Z_USAGE);
5045 		case 'F':
5046 			force = B_TRUE;
5047 			break;
5048 		default:
5049 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5050 			return (Z_USAGE);
5051 		}
5052 	}
5053 	if (argc > optind) {
5054 		sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5055 		return (Z_USAGE);
5056 	}
5057 
5058 	if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE, B_FALSE)
5059 	    != Z_OK)
5060 		return (Z_ERR);
5061 
5062 	/*
5063 	 * Invoke brand-specific handler.
5064 	 */
5065 	if (invoke_brand_handler(CMD_UNINSTALL, argv) != Z_OK)
5066 		return (Z_ERR);
5067 
5068 	if (!force) {
5069 		(void) snprintf(line, sizeof (line),
5070 		    gettext("Are you sure you want to %s zone %s"),
5071 		    cmd_to_str(CMD_UNINSTALL), target_zone);
5072 		if ((answer = ask_yesno(B_FALSE, line)) == 0) {
5073 			return (Z_OK);
5074 		} else if (answer == -1) {
5075 			zerror(gettext("Input not from terminal and -F "
5076 			    "not specified: %s not done."),
5077 			    cmd_to_str(CMD_UNINSTALL));
5078 			return (Z_ERR);
5079 		}
5080 	}
5081 
5082 	if ((err = zone_get_zonepath(target_zone, zonepath,
5083 	    sizeof (zonepath))) != Z_OK) {
5084 		errno = err;
5085 		zperror2(target_zone, gettext("could not get zone path"));
5086 		return (Z_ERR);
5087 	}
5088 	if ((err = zone_get_rootpath(target_zone, rootpath,
5089 	    sizeof (rootpath))) != Z_OK) {
5090 		errno = err;
5091 		zperror2(target_zone, gettext("could not get root path"));
5092 		return (Z_ERR);
5093 	}
5094 
5095 	/*
5096 	 * If there seems to be a zoneadmd running for this zone, call it
5097 	 * to tell it that an uninstall is happening; if all goes well it
5098 	 * will then shut itself down.
5099 	 */
5100 	if (ping_zoneadmd(target_zone) == Z_OK) {
5101 		zone_cmd_arg_t zarg;
5102 		zarg.cmd = Z_NOTE_UNINSTALLING;
5103 		/* we don't care too much if this fails... just plow on */
5104 		(void) call_zoneadmd(target_zone, &zarg);
5105 	}
5106 
5107 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
5108 		zerror(gettext("another %s may have an operation in progress."),
5109 		    "zoneadm");
5110 		return (Z_ERR);
5111 	}
5112 
5113 	/* Don't uninstall the zone if anything is mounted there */
5114 	err = zonecfg_find_mounts(rootpath, NULL, NULL);
5115 	if (err) {
5116 		zerror(gettext("These file systems are mounted on "
5117 		    "subdirectories of %s.\n"), rootpath);
5118 		(void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
5119 		return (Z_ERR);
5120 	}
5121 
5122 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
5123 	if (err != Z_OK) {
5124 		errno = err;
5125 		zperror2(target_zone, gettext("could not set state"));
5126 		goto bad;
5127 	}
5128 
5129 	if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
5130 		errno = err;
5131 		zperror2(target_zone, gettext("cleaning up zonepath failed"));
5132 		goto bad;
5133 	}
5134 
5135 	err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
5136 	if (err != Z_OK) {
5137 		errno = err;
5138 		zperror2(target_zone, gettext("could not reset state"));
5139 	}
5140 bad:
5141 	release_lock_file(lockfd);
5142 	return (err);
5143 }
5144 
5145 /* ARGSUSED */
5146 static int
5147 mount_func(int argc, char *argv[])
5148 {
5149 	zone_cmd_arg_t zarg;
5150 	boolean_t force = B_FALSE;
5151 	int arg;
5152 
5153 	/*
5154 	 * The only supported subargument to the "mount" subcommand is
5155 	 * "-f", which forces us to mount a zone in the INCOMPLETE state.
5156 	 */
5157 	optind = 0;
5158 	if ((arg = getopt(argc, argv, "f")) != EOF) {
5159 		switch (arg) {
5160 		case 'f':
5161 			force = B_TRUE;
5162 			break;
5163 		default:
5164 			return (Z_USAGE);
5165 		}
5166 	}
5167 	if (argc > optind)
5168 		return (Z_USAGE);
5169 
5170 	if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE, force)
5171 	    != Z_OK)
5172 		return (Z_ERR);
5173 	if (verify_details(CMD_MOUNT, argv) != Z_OK)
5174 		return (Z_ERR);
5175 
5176 	zarg.cmd = force ? Z_FORCEMOUNT : Z_MOUNT;
5177 	if (call_zoneadmd(target_zone, &zarg) != 0) {
5178 		zerror(gettext("call to %s failed"), "zoneadmd");
5179 		return (Z_ERR);
5180 	}
5181 	return (Z_OK);
5182 }
5183 
5184 /* ARGSUSED */
5185 static int
5186 unmount_func(int argc, char *argv[])
5187 {
5188 	zone_cmd_arg_t zarg;
5189 
5190 	if (argc > 0)
5191 		return (Z_USAGE);
5192 	if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE, B_FALSE)
5193 	    != Z_OK)
5194 		return (Z_ERR);
5195 
5196 	zarg.cmd = Z_UNMOUNT;
5197 	if (call_zoneadmd(target_zone, &zarg) != 0) {
5198 		zerror(gettext("call to %s failed"), "zoneadmd");
5199 		return (Z_ERR);
5200 	}
5201 	return (Z_OK);
5202 }
5203 
5204 static int
5205 mark_func(int argc, char *argv[])
5206 {
5207 	int err, lockfd;
5208 
5209 	if (argc != 1 || strcmp(argv[0], "incomplete") != 0)
5210 		return (Z_USAGE);
5211 	if (sanity_check(target_zone, CMD_MARK, B_FALSE, B_FALSE, B_FALSE)
5212 	    != Z_OK)
5213 		return (Z_ERR);
5214 
5215 	/*
5216 	 * Invoke brand-specific handler.
5217 	 */
5218 	if (invoke_brand_handler(CMD_MARK, argv) != Z_OK)
5219 		return (Z_ERR);
5220 
5221 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
5222 		zerror(gettext("another %s may have an operation in progress."),
5223 		    "zoneadm");
5224 		return (Z_ERR);
5225 	}
5226 
5227 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
5228 	if (err != Z_OK) {
5229 		errno = err;
5230 		zperror2(target_zone, gettext("could not set state"));
5231 	}
5232 	release_lock_file(lockfd);
5233 
5234 	return (err);
5235 }
5236 
5237 /*
5238  * Check what scheduling class we're running under and print a warning if
5239  * we're not using FSS.
5240  */
5241 static int
5242 check_sched_fss(zone_dochandle_t handle)
5243 {
5244 	char class_name[PC_CLNMSZ];
5245 
5246 	if (zonecfg_get_dflt_sched_class(handle, class_name,
5247 	    sizeof (class_name)) != Z_OK) {
5248 		zerror(gettext("WARNING: unable to determine the zone's "
5249 		    "scheduling class"));
5250 	} else if (strcmp("FSS", class_name) != 0) {
5251 		zerror(gettext("WARNING: The zone.cpu-shares rctl is set but\n"
5252 		    "FSS is not the default scheduling class for this zone.  "
5253 		    "FSS will be\nused for processes in the zone but to get "
5254 		    "the full benefit of FSS,\nit should be the default "
5255 		    "scheduling class.  See dispadmin(1M) for\nmore details."));
5256 		return (Z_SYSTEM);
5257 	}
5258 
5259 	return (Z_OK);
5260 }
5261 
5262 static int
5263 check_cpu_shares_sched(zone_dochandle_t handle)
5264 {
5265 	int err;
5266 	int res = Z_OK;
5267 	struct zone_rctltab rctl;
5268 
5269 	if ((err = zonecfg_setrctlent(handle)) != Z_OK) {
5270 		errno = err;
5271 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5272 		return (err);
5273 	}
5274 
5275 	while (zonecfg_getrctlent(handle, &rctl) == Z_OK) {
5276 		if (strcmp(rctl.zone_rctl_name, "zone.cpu-shares") == 0) {
5277 			if (check_sched_fss(handle) != Z_OK)
5278 				res = Z_SYSTEM;
5279 			break;
5280 		}
5281 	}
5282 
5283 	(void) zonecfg_endrctlent(handle);
5284 
5285 	return (res);
5286 }
5287 
5288 /*
5289  * Check if there is a mix of processes running in different pools within the
5290  * zone.  This is currently only going to be called for the global zone from
5291  * apply_func but that could be generalized in the future.
5292  */
5293 static boolean_t
5294 mixed_pools(zoneid_t zoneid)
5295 {
5296 	DIR *dirp;
5297 	dirent_t *dent;
5298 	boolean_t mixed = B_FALSE;
5299 	boolean_t poolid_set = B_FALSE;
5300 	poolid_t last_poolid = 0;
5301 
5302 	if ((dirp = opendir("/proc")) == NULL) {
5303 		zerror(gettext("could not open /proc"));
5304 		return (B_FALSE);
5305 	}
5306 
5307 	while ((dent = readdir(dirp)) != NULL) {
5308 		int procfd;
5309 		psinfo_t ps;
5310 		char procpath[MAXPATHLEN];
5311 
5312 		if (dent->d_name[0] == '.')
5313 			continue;
5314 
5315 		(void) snprintf(procpath, sizeof (procpath), "/proc/%s/psinfo",
5316 		    dent->d_name);
5317 
5318 		if ((procfd = open(procpath, O_RDONLY)) == -1)
5319 			continue;
5320 
5321 		if (read(procfd, &ps, sizeof (ps)) == sizeof (psinfo_t)) {
5322 			/* skip processes in other zones and system processes */
5323 			if (zoneid != ps.pr_zoneid || ps.pr_flag & SSYS) {
5324 				(void) close(procfd);
5325 				continue;
5326 			}
5327 
5328 			if (poolid_set) {
5329 				if (ps.pr_poolid != last_poolid)
5330 					mixed = B_TRUE;
5331 			} else {
5332 				last_poolid = ps.pr_poolid;
5333 				poolid_set = B_TRUE;
5334 			}
5335 		}
5336 
5337 		(void) close(procfd);
5338 
5339 		if (mixed)
5340 			break;
5341 	}
5342 
5343 	(void) closedir(dirp);
5344 
5345 	return (mixed);
5346 }
5347 
5348 /*
5349  * Check if a persistent or temporary pool is configured for the zone.
5350  * This is currently only going to be called for the global zone from
5351  * apply_func but that could be generalized in the future.
5352  */
5353 static boolean_t
5354 pool_configured(zone_dochandle_t handle)
5355 {
5356 	int err1, err2;
5357 	struct zone_psettab pset_tab;
5358 	char poolname[MAXPATHLEN];
5359 
5360 	err1 = zonecfg_lookup_pset(handle, &pset_tab);
5361 	err2 = zonecfg_get_pool(handle, poolname, sizeof (poolname));
5362 
5363 	if (err1 == Z_NO_ENTRY &&
5364 	    (err2 == Z_NO_ENTRY || (err2 == Z_OK && strlen(poolname) == 0)))
5365 		return (B_FALSE);
5366 
5367 	return (B_TRUE);
5368 }
5369 
5370 /*
5371  * This is an undocumented interface which is currently only used to apply
5372  * the global zone resource management settings when the system boots.
5373  * This function does not yet properly handle updating a running system so
5374  * any projects running in the zone would be trashed if this function
5375  * were to run after the zone had booted.  It also does not reset any
5376  * rctl settings that were removed from zonecfg.  There is still work to be
5377  * done before we can properly support dynamically updating the resource
5378  * management settings for a running zone (global or non-global).  Thus, this
5379  * functionality is undocumented for now.
5380  */
5381 /* ARGSUSED */
5382 static int
5383 apply_func(int argc, char *argv[])
5384 {
5385 	int err;
5386 	int res = Z_OK;
5387 	priv_set_t *privset;
5388 	zoneid_t zoneid;
5389 	zone_dochandle_t handle;
5390 	struct zone_mcaptab mcap;
5391 	char pool_err[128];
5392 
5393 	zoneid = getzoneid();
5394 
5395 	if (zonecfg_in_alt_root() || zoneid != GLOBAL_ZONEID ||
5396 	    target_zone == NULL || strcmp(target_zone, GLOBAL_ZONENAME) != 0)
5397 		return (usage(B_FALSE));
5398 
5399 	if ((privset = priv_allocset()) == NULL) {
5400 		zerror(gettext("%s failed"), "priv_allocset");
5401 		return (Z_ERR);
5402 	}
5403 
5404 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
5405 		zerror(gettext("%s failed"), "getppriv");
5406 		priv_freeset(privset);
5407 		return (Z_ERR);
5408 	}
5409 
5410 	if (priv_isfullset(privset) == B_FALSE) {
5411 		(void) usage(B_FALSE);
5412 		priv_freeset(privset);
5413 		return (Z_ERR);
5414 	}
5415 	priv_freeset(privset);
5416 
5417 	if ((handle = zonecfg_init_handle()) == NULL) {
5418 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5419 		return (Z_ERR);
5420 	}
5421 
5422 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
5423 		errno = err;
5424 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5425 		zonecfg_fini_handle(handle);
5426 		return (Z_ERR);
5427 	}
5428 
5429 	/* specific error msgs are printed within apply_rctls */
5430 	if ((err = zonecfg_apply_rctls(target_zone, handle)) != Z_OK) {
5431 		errno = err;
5432 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5433 		res = Z_ERR;
5434 	}
5435 
5436 	if ((err = check_cpu_shares_sched(handle)) != Z_OK)
5437 		res = Z_ERR;
5438 
5439 	if (pool_configured(handle)) {
5440 		if (mixed_pools(zoneid)) {
5441 			zerror(gettext("Zone is using multiple resource "
5442 			    "pools.  The pool\nconfiguration cannot be "
5443 			    "applied without rebooting."));
5444 			res = Z_ERR;
5445 		} else {
5446 
5447 			/*
5448 			 * The next two blocks of code attempt to set up
5449 			 * temporary pools as well as persistent pools.  In
5450 			 * both cases we call the functions unconditionally.
5451 			 * Within each funtion the code will check if the zone
5452 			 * is actually configured for a temporary pool or
5453 			 * persistent pool and just return if there is nothing
5454 			 * to do.
5455 			 */
5456 			if ((err = zonecfg_bind_tmp_pool(handle, zoneid,
5457 			    pool_err, sizeof (pool_err))) != Z_OK) {
5458 				if (err == Z_POOL || err == Z_POOL_CREATE ||
5459 				    err == Z_POOL_BIND)
5460 					zerror("%s: %s", zonecfg_strerror(err),
5461 					    pool_err);
5462 				else
5463 					zerror(gettext("could not bind zone to "
5464 					    "temporary pool: %s"),
5465 					    zonecfg_strerror(err));
5466 				res = Z_ERR;
5467 			}
5468 
5469 			if ((err = zonecfg_bind_pool(handle, zoneid, pool_err,
5470 			    sizeof (pool_err))) != Z_OK) {
5471 				if (err == Z_POOL || err == Z_POOL_BIND)
5472 					zerror("%s: %s", zonecfg_strerror(err),
5473 					    pool_err);
5474 				else
5475 					zerror("%s", zonecfg_strerror(err));
5476 			}
5477 		}
5478 	}
5479 
5480 	/*
5481 	 * If a memory cap is configured, set the cap in the kernel using
5482 	 * zone_setattr() and make sure the rcapd SMF service is enabled.
5483 	 */
5484 	if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
5485 		uint64_t num;
5486 		char smf_err[128];
5487 
5488 		num = (uint64_t)strtoll(mcap.zone_physmem_cap, NULL, 10);
5489 		if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
5490 			zerror(gettext("could not set zone memory cap"));
5491 			res = Z_ERR;
5492 		}
5493 
5494 		if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
5495 			zerror(gettext("enabling system/rcap service failed: "
5496 			    "%s"), smf_err);
5497 			res = Z_ERR;
5498 		}
5499 	}
5500 
5501 	zonecfg_fini_handle(handle);
5502 
5503 	return (res);
5504 }
5505 
5506 static int
5507 help_func(int argc, char *argv[])
5508 {
5509 	int arg, cmd_num;
5510 
5511 	if (argc == 0) {
5512 		(void) usage(B_TRUE);
5513 		return (Z_OK);
5514 	}
5515 	optind = 0;
5516 	if ((arg = getopt(argc, argv, "?")) != EOF) {
5517 		switch (arg) {
5518 		case '?':
5519 			sub_usage(SHELP_HELP, CMD_HELP);
5520 			return (optopt == '?' ? Z_OK : Z_USAGE);
5521 		default:
5522 			sub_usage(SHELP_HELP, CMD_HELP);
5523 			return (Z_USAGE);
5524 		}
5525 	}
5526 	while (optind < argc) {
5527 		/* Private commands have NULL short_usage; omit them */
5528 		if ((cmd_num = cmd_match(argv[optind])) < 0 ||
5529 		    cmdtab[cmd_num].short_usage == NULL) {
5530 			sub_usage(SHELP_HELP, CMD_HELP);
5531 			return (Z_USAGE);
5532 		}
5533 		sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
5534 		optind++;
5535 	}
5536 	return (Z_OK);
5537 }
5538 
5539 /*
5540  * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
5541  */
5542 
5543 static int
5544 cmd_match(char *cmd)
5545 {
5546 	int i;
5547 
5548 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
5549 		/* return only if there is an exact match */
5550 		if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
5551 			return (cmdtab[i].cmd_num);
5552 	}
5553 	return (-1);
5554 }
5555 
5556 static int
5557 parse_and_run(int argc, char *argv[])
5558 {
5559 	int i = cmd_match(argv[0]);
5560 
5561 	if (i < 0)
5562 		return (usage(B_FALSE));
5563 	return (cmdtab[i].handler(argc - 1, &(argv[1])));
5564 }
5565 
5566 static char *
5567 get_execbasename(char *execfullname)
5568 {
5569 	char *last_slash, *execbasename;
5570 
5571 	/* guard against '/' at end of command invocation */
5572 	for (;;) {
5573 		last_slash = strrchr(execfullname, '/');
5574 		if (last_slash == NULL) {
5575 			execbasename = execfullname;
5576 			break;
5577 		} else {
5578 			execbasename = last_slash + 1;
5579 			if (*execbasename == '\0') {
5580 				*last_slash = '\0';
5581 				continue;
5582 			}
5583 			break;
5584 		}
5585 	}
5586 	return (execbasename);
5587 }
5588 
5589 int
5590 main(int argc, char **argv)
5591 {
5592 	int arg;
5593 	zoneid_t zid;
5594 	struct stat st;
5595 	char *zone_lock_env;
5596 	int err;
5597 
5598 	if ((locale = setlocale(LC_ALL, "")) == NULL)
5599 		locale = "C";
5600 	(void) textdomain(TEXT_DOMAIN);
5601 	setbuf(stdout, NULL);
5602 	(void) sigset(SIGHUP, SIG_IGN);
5603 	execname = get_execbasename(argv[0]);
5604 	target_zone = NULL;
5605 	if (chdir("/") != 0) {
5606 		zerror(gettext("could not change directory to /."));
5607 		exit(Z_ERR);
5608 	}
5609 
5610 	if (init_zfs() != Z_OK)
5611 		exit(Z_ERR);
5612 
5613 	while ((arg = getopt(argc, argv, "?u:z:R:")) != EOF) {
5614 		switch (arg) {
5615 		case '?':
5616 			return (usage(B_TRUE));
5617 		case 'u':
5618 			target_uuid = optarg;
5619 			break;
5620 		case 'z':
5621 			target_zone = optarg;
5622 			break;
5623 		case 'R':	/* private option for admin/install use */
5624 			if (*optarg != '/') {
5625 				zerror(gettext("root path must be absolute."));
5626 				exit(Z_ERR);
5627 			}
5628 			if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
5629 				zerror(
5630 				    gettext("root path must be a directory."));
5631 				exit(Z_ERR);
5632 			}
5633 			zonecfg_set_root(optarg);
5634 			break;
5635 		default:
5636 			return (usage(B_FALSE));
5637 		}
5638 	}
5639 
5640 	if (optind >= argc)
5641 		return (usage(B_FALSE));
5642 
5643 	if (target_uuid != NULL && *target_uuid != '\0') {
5644 		uuid_t uuid;
5645 		static char newtarget[ZONENAME_MAX];
5646 
5647 		if (uuid_parse(target_uuid, uuid) == -1) {
5648 			zerror(gettext("illegal UUID value specified"));
5649 			exit(Z_ERR);
5650 		}
5651 		if (zonecfg_get_name_by_uuid(uuid, newtarget,
5652 		    sizeof (newtarget)) == Z_OK)
5653 			target_zone = newtarget;
5654 	}
5655 
5656 	if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
5657 		errno = Z_NO_ZONE;
5658 		zperror(target_zone, B_TRUE);
5659 		exit(Z_ERR);
5660 	}
5661 
5662 	/*
5663 	 * See if we have inherited the right to manipulate this zone from
5664 	 * a zoneadm instance in our ancestry.  If so, set zone_lock_cnt to
5665 	 * indicate it.  If not, make that explicit in our environment.
5666 	 */
5667 	zone_lock_env = getenv(LOCK_ENV_VAR);
5668 	if (zone_lock_env == NULL) {
5669 		if (putenv(zoneadm_lock_not_held) != 0) {
5670 			zperror(target_zone, B_TRUE);
5671 			exit(Z_ERR);
5672 		}
5673 	} else {
5674 		zoneadm_is_nested = B_TRUE;
5675 		if (atoi(zone_lock_env) == 1)
5676 			zone_lock_cnt = 1;
5677 	}
5678 
5679 	/*
5680 	 * If we are going to be operating on a single zone, retrieve its
5681 	 * brand type and determine whether it is native or not.
5682 	 */
5683 	if ((target_zone != NULL) &&
5684 	    (strcmp(target_zone, GLOBAL_ZONENAME) != NULL)) {
5685 		if (zone_get_brand(target_zone, target_brand,
5686 		    sizeof (target_brand)) != Z_OK) {
5687 			zerror(gettext("missing or invalid brand"));
5688 			exit(Z_ERR);
5689 		}
5690 		is_native_zone = (strcmp(target_brand, NATIVE_BRAND_NAME) == 0);
5691 		is_cluster_zone =
5692 		    (strcmp(target_brand, CLUSTER_BRAND_NAME) == 0);
5693 	}
5694 
5695 	err = parse_and_run(argc - optind, &argv[optind]);
5696 
5697 	return (err);
5698 }
5699