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