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