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