xref: /titanic_44/usr/src/cmd/zoneadm/zoneadm.c (revision afbc45417fe46ac092547adfe04ef4966809b862)
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 stat64 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 (stat64(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 isregfile(const char *path)
2478 {
2479 	struct stat64 st;
2480 
2481 	if (stat64(path, &st) == -1)
2482 		return (-1);
2483 
2484 	return (S_ISREG(st.st_mode));
2485 }
2486 
2487 static int
2488 verify_filesystems(zone_dochandle_t handle)
2489 {
2490 	int return_code = Z_OK;
2491 	struct zone_fstab fstab;
2492 	char cmdbuf[MAXPATHLEN];
2493 	struct stat st;
2494 
2495 	/*
2496 	 * No need to verify inherit-pkg-dir fs types, as their type is
2497 	 * implicitly lofs, which is known.  Therefore, the types are only
2498 	 * verified for regular file systems below.
2499 	 *
2500 	 * Since the actual mount point is not known until the dependent mounts
2501 	 * are performed, we don't attempt any path validation here: that will
2502 	 * happen later when zoneadmd actually does the mounts.
2503 	 */
2504 	if (zonecfg_setfsent(handle) != Z_OK) {
2505 		(void) fprintf(stderr, gettext("could not verify file systems: "
2506 		    "unable to enumerate mounts\n"));
2507 		return (Z_ERR);
2508 	}
2509 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
2510 		if (!zonecfg_valid_fs_type(fstab.zone_fs_type)) {
2511 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2512 			    "type %s is not allowed.\n"), fstab.zone_fs_dir,
2513 			    fstab.zone_fs_type);
2514 			return_code = Z_ERR;
2515 			goto next_fs;
2516 		}
2517 		/*
2518 		 * Verify /usr/lib/fs/<fstype>/mount exists.
2519 		 */
2520 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount",
2521 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
2522 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2523 			    "type %s is too long.\n"), fstab.zone_fs_dir,
2524 			    fstab.zone_fs_type);
2525 			return_code = Z_ERR;
2526 			goto next_fs;
2527 		}
2528 		if (stat(cmdbuf, &st) != 0) {
2529 			(void) fprintf(stderr, gettext("could not verify fs "
2530 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2531 			    cmdbuf, strerror(errno));
2532 			return_code = Z_ERR;
2533 			goto next_fs;
2534 		}
2535 		if (!S_ISREG(st.st_mode)) {
2536 			(void) fprintf(stderr, gettext("could not verify fs "
2537 			    "%s: %s is not a regular file\n"),
2538 			    fstab.zone_fs_dir, cmdbuf);
2539 			return_code = Z_ERR;
2540 			goto next_fs;
2541 		}
2542 		/*
2543 		 * If zone_fs_raw is set, verify that there's an fsck
2544 		 * binary for it.  If zone_fs_raw is not set, and it's
2545 		 * not a regular file (lofi mount), and there's an fsck
2546 		 * binary for it, complain.
2547 		 */
2548 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck",
2549 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
2550 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2551 			    "type %s is too long.\n"), fstab.zone_fs_dir,
2552 			    fstab.zone_fs_type);
2553 			return_code = Z_ERR;
2554 			goto next_fs;
2555 		}
2556 		if (fstab.zone_fs_raw[0] != '\0' &&
2557 		    (stat(cmdbuf, &st) != 0 || !S_ISREG(st.st_mode))) {
2558 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
2559 			    "'raw' device specified but "
2560 			    "no fsck executable exists for %s\n"),
2561 			    fstab.zone_fs_dir, fstab.zone_fs_type);
2562 			return_code = Z_ERR;
2563 			goto next_fs;
2564 		} else if (fstab.zone_fs_raw[0] == '\0' &&
2565 		    stat(cmdbuf, &st) == 0 &&
2566 		    isregfile(fstab.zone_fs_special) != 1) {
2567 			(void) fprintf(stderr, gettext("could not verify fs "
2568 			    "%s: must specify 'raw' device for %s "
2569 			    "file systems\n"),
2570 			    fstab.zone_fs_dir, fstab.zone_fs_type);
2571 			return_code = Z_ERR;
2572 			goto next_fs;
2573 		}
2574 
2575 		/* Verify fs_special. */
2576 		if ((return_code = verify_fs_special(&fstab)) != Z_OK)
2577 			goto next_fs;
2578 
2579 		/* Verify fs_raw. */
2580 		if (fstab.zone_fs_raw[0] != '\0' &&
2581 		    stat(fstab.zone_fs_raw, &st) != 0) {
2582 			/*
2583 			 * TRANSLATION_NOTE
2584 			 * fs is a literal that should not be translated.
2585 			 */
2586 			(void) fprintf(stderr, gettext("could not verify fs "
2587 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2588 			    fstab.zone_fs_raw, strerror(errno));
2589 			return_code = Z_ERR;
2590 			goto next_fs;
2591 		}
2592 next_fs:
2593 		zonecfg_free_fs_option_list(fstab.zone_fs_options);
2594 	}
2595 	(void) zonecfg_endfsent(handle);
2596 
2597 	return (return_code);
2598 }
2599 
2600 static int
2601 verify_limitpriv(zone_dochandle_t handle)
2602 {
2603 	char *privname = NULL;
2604 	int err;
2605 	priv_set_t *privs;
2606 
2607 	if ((privs = priv_allocset()) == NULL) {
2608 		zperror(gettext("failed to allocate privilege set"), B_FALSE);
2609 		return (Z_NOMEM);
2610 	}
2611 	err = zonecfg_get_privset(handle, privs, &privname);
2612 	switch (err) {
2613 	case Z_OK:
2614 		break;
2615 	case Z_PRIV_PROHIBITED:
2616 		(void) fprintf(stderr, gettext("privilege \"%s\" is not "
2617 		    "permitted within the zone's privilege set\n"), privname);
2618 		break;
2619 	case Z_PRIV_REQUIRED:
2620 		(void) fprintf(stderr, gettext("required privilege \"%s\" is "
2621 		    "missing from the zone's privilege set\n"), privname);
2622 		break;
2623 	case Z_PRIV_UNKNOWN:
2624 		(void) fprintf(stderr, gettext("unknown privilege \"%s\" "
2625 		    "specified in the zone's privilege set\n"), privname);
2626 		break;
2627 	default:
2628 		zperror(
2629 		    gettext("failed to determine the zone's privilege set"),
2630 		    B_TRUE);
2631 		break;
2632 	}
2633 	free(privname);
2634 	priv_freeset(privs);
2635 	return (err);
2636 }
2637 
2638 static void
2639 free_local_netifs(int if_cnt, struct net_if **if_list)
2640 {
2641 	int		i;
2642 
2643 	for (i = 0; i < if_cnt; i++) {
2644 		free(if_list[i]->name);
2645 		free(if_list[i]);
2646 	}
2647 	free(if_list);
2648 }
2649 
2650 /*
2651  * Get a list of the network interfaces, along with their address families,
2652  * that are plumbed in the global zone.  See if_tcp(7p) for a description
2653  * of the ioctls used here.
2654  */
2655 static int
2656 get_local_netifs(int *if_cnt, struct net_if ***if_list)
2657 {
2658 	int		s;
2659 	int		i;
2660 	int		res = Z_OK;
2661 	int		space_needed;
2662 	int		cnt = 0;
2663 	struct		lifnum if_num;
2664 	struct		lifconf if_conf;
2665 	struct		lifreq *if_reqp;
2666 	char		*if_buf;
2667 	struct net_if	**local_ifs = NULL;
2668 
2669 	*if_cnt = 0;
2670 	*if_list = NULL;
2671 
2672 	if ((s = socket(SOCKET_AF(AF_INET), SOCK_DGRAM, 0)) < 0)
2673 		return (Z_ERR);
2674 
2675 	/*
2676 	 * Come back here in the unlikely event that the number of interfaces
2677 	 * increases between the time we get the count and the time we do the
2678 	 * SIOCGLIFCONF ioctl.
2679 	 */
2680 retry:
2681 	/* Get the number of interfaces. */
2682 	if_num.lifn_family = AF_UNSPEC;
2683 	if_num.lifn_flags = LIFC_NOXMIT;
2684 	if (ioctl(s, SIOCGLIFNUM, &if_num) < 0) {
2685 		(void) close(s);
2686 		return (Z_ERR);
2687 	}
2688 
2689 	/* Get the interface configuration list. */
2690 	space_needed = if_num.lifn_count * sizeof (struct lifreq);
2691 	if ((if_buf = malloc(space_needed)) == NULL) {
2692 		(void) close(s);
2693 		return (Z_ERR);
2694 	}
2695 	if_conf.lifc_family = AF_UNSPEC;
2696 	if_conf.lifc_flags = LIFC_NOXMIT;
2697 	if_conf.lifc_len = space_needed;
2698 	if_conf.lifc_buf = if_buf;
2699 	if (ioctl(s, SIOCGLIFCONF, &if_conf) < 0) {
2700 		free(if_buf);
2701 		/*
2702 		 * SIOCGLIFCONF returns EINVAL if the buffer we passed in is
2703 		 * too small.  In this case go back and get the new if cnt.
2704 		 */
2705 		if (errno == EINVAL)
2706 			goto retry;
2707 
2708 		(void) close(s);
2709 		return (Z_ERR);
2710 	}
2711 	(void) close(s);
2712 
2713 	/* Get the name and address family for each interface. */
2714 	if_reqp = if_conf.lifc_req;
2715 	for (i = 0; i < (if_conf.lifc_len / sizeof (struct lifreq)); i++) {
2716 		struct net_if	**p;
2717 		struct lifreq	req;
2718 
2719 		if (strcmp(LOOPBACK_IF, if_reqp->lifr_name) == 0) {
2720 			if_reqp++;
2721 			continue;
2722 		}
2723 
2724 		if ((s = socket(SOCKET_AF(if_reqp->lifr_addr.ss_family),
2725 		    SOCK_DGRAM, 0)) == -1) {
2726 			res = Z_ERR;
2727 			break;
2728 		}
2729 
2730 		(void) strncpy(req.lifr_name, if_reqp->lifr_name,
2731 		    sizeof (req.lifr_name));
2732 		if (ioctl(s, SIOCGLIFADDR, &req) < 0) {
2733 			(void) close(s);
2734 			if_reqp++;
2735 			continue;
2736 		}
2737 
2738 		if ((p = (struct net_if **)realloc(local_ifs,
2739 		    sizeof (struct net_if *) * (cnt + 1))) == NULL) {
2740 			res = Z_ERR;
2741 			break;
2742 		}
2743 		local_ifs = p;
2744 
2745 		if ((local_ifs[cnt] = malloc(sizeof (struct net_if))) == NULL) {
2746 			res = Z_ERR;
2747 			break;
2748 		}
2749 
2750 		if ((local_ifs[cnt]->name = strdup(if_reqp->lifr_name))
2751 		    == NULL) {
2752 			free(local_ifs[cnt]);
2753 			res = Z_ERR;
2754 			break;
2755 		}
2756 		local_ifs[cnt]->af = req.lifr_addr.ss_family;
2757 		cnt++;
2758 
2759 		(void) close(s);
2760 		if_reqp++;
2761 	}
2762 
2763 	free(if_buf);
2764 
2765 	if (res != Z_OK) {
2766 		free_local_netifs(cnt, local_ifs);
2767 	} else {
2768 		*if_cnt = cnt;
2769 		*if_list = local_ifs;
2770 	}
2771 
2772 	return (res);
2773 }
2774 
2775 static char *
2776 af2str(int af)
2777 {
2778 	switch (af) {
2779 	case AF_INET:
2780 		return ("IPv4");
2781 	case AF_INET6:
2782 		return ("IPv6");
2783 	default:
2784 		return ("Unknown");
2785 	}
2786 }
2787 
2788 /*
2789  * Cross check the network interface name and address family with the
2790  * interfaces that are set up in the global zone so that we can print the
2791  * appropriate error message.
2792  */
2793 static void
2794 print_net_err(char *phys, char *addr, int af, char *msg)
2795 {
2796 	int		i;
2797 	int		local_if_cnt = 0;
2798 	struct net_if	**local_ifs = NULL;
2799 	boolean_t	found_if = B_FALSE;
2800 	boolean_t	found_af = B_FALSE;
2801 
2802 	if (get_local_netifs(&local_if_cnt, &local_ifs) != Z_OK) {
2803 		(void) fprintf(stderr,
2804 		    gettext("could not verify %s %s=%s %s=%s\n\t%s\n"),
2805 		    "net", "address", addr, "physical", phys, msg);
2806 		return;
2807 	}
2808 
2809 	for (i = 0; i < local_if_cnt; i++) {
2810 		if (strcmp(phys, local_ifs[i]->name) == 0) {
2811 			found_if = B_TRUE;
2812 			if (af == local_ifs[i]->af) {
2813 				found_af = B_TRUE;
2814 				break;
2815 			}
2816 		}
2817 	}
2818 
2819 	free_local_netifs(local_if_cnt, local_ifs);
2820 
2821 	if (!found_if) {
2822 		(void) fprintf(stderr,
2823 		    gettext("could not verify %s %s=%s\n\t"
2824 		    "network interface %s is not plumbed in the global zone\n"),
2825 		    "net", "physical", phys, phys);
2826 		return;
2827 	}
2828 
2829 	/*
2830 	 * Print this error if we were unable to find the address family
2831 	 * for this interface.  If the af variable is not initialized to
2832 	 * to something meaningful by the caller (not AF_UNSPEC) then we
2833 	 * also skip this message since it wouldn't be informative.
2834 	 */
2835 	if (!found_af && af != AF_UNSPEC) {
2836 		(void) fprintf(stderr,
2837 		    gettext("could not verify %s %s=%s %s=%s\n\tthe %s address "
2838 		    "family is not configured on this network interface in "
2839 		    "the\n\tglobal zone\n"),
2840 		    "net", "address", addr, "physical", phys, af2str(af));
2841 		return;
2842 	}
2843 
2844 	(void) fprintf(stderr,
2845 	    gettext("could not verify %s %s=%s %s=%s\n\t%s\n"),
2846 	    "net", "address", addr, "physical", phys, msg);
2847 }
2848 
2849 static int
2850 verify_handle(int cmd_num, zone_dochandle_t handle, char *argv[])
2851 {
2852 	struct zone_nwiftab nwiftab;
2853 	int return_code = Z_OK;
2854 	int err;
2855 	boolean_t in_alt_root;
2856 	zone_iptype_t iptype;
2857 	dlpi_handle_t dh;
2858 
2859 	in_alt_root = zonecfg_in_alt_root();
2860 	if (in_alt_root)
2861 		goto no_net;
2862 
2863 	if ((err = zonecfg_get_iptype(handle, &iptype)) != Z_OK) {
2864 		errno = err;
2865 		zperror(cmd_to_str(cmd_num), B_TRUE);
2866 		zonecfg_fini_handle(handle);
2867 		return (Z_ERR);
2868 	}
2869 	if ((err = zonecfg_setnwifent(handle)) != Z_OK) {
2870 		errno = err;
2871 		zperror(cmd_to_str(cmd_num), B_TRUE);
2872 		zonecfg_fini_handle(handle);
2873 		return (Z_ERR);
2874 	}
2875 	while (zonecfg_getnwifent(handle, &nwiftab) == Z_OK) {
2876 		struct lifreq lifr;
2877 		sa_family_t af = AF_UNSPEC;
2878 		char dl_owner_zname[ZONENAME_MAX];
2879 		zoneid_t dl_owner_zid;
2880 		zoneid_t target_zid;
2881 		int res;
2882 
2883 		/* skip any loopback interfaces */
2884 		if (strcmp(nwiftab.zone_nwif_physical, "lo0") == 0)
2885 			continue;
2886 		switch (iptype) {
2887 		case ZS_SHARED:
2888 			if ((res = zonecfg_valid_net_address(
2889 			    nwiftab.zone_nwif_address, &lifr)) != Z_OK) {
2890 				print_net_err(nwiftab.zone_nwif_physical,
2891 				    nwiftab.zone_nwif_address, af,
2892 				    zonecfg_strerror(res));
2893 				return_code = Z_ERR;
2894 				continue;
2895 			}
2896 			af = lifr.lifr_addr.ss_family;
2897 			if (!zonecfg_ifname_exists(af,
2898 			    nwiftab.zone_nwif_physical)) {
2899 				/*
2900 				 * The interface failed to come up. We continue
2901 				 * on anyway for the sake of consistency: a
2902 				 * zone is not shut down if the interface fails
2903 				 * any time after boot, nor does the global zone
2904 				 * fail to boot if an interface fails.
2905 				 */
2906 				(void) fprintf(stderr,
2907 				    gettext("WARNING: skipping network "
2908 				    "interface '%s' which may not be "
2909 				    "present/plumbed in the global "
2910 				    "zone.\n"),
2911 				    nwiftab.zone_nwif_physical);
2912 			}
2913 			break;
2914 		case ZS_EXCLUSIVE:
2915 			/* Warning if it exists for either IPv4 or IPv6 */
2916 
2917 			if (zonecfg_ifname_exists(AF_INET,
2918 			    nwiftab.zone_nwif_physical) ||
2919 			    zonecfg_ifname_exists(AF_INET6,
2920 			    nwiftab.zone_nwif_physical)) {
2921 				(void) fprintf(stderr,
2922 				    gettext("WARNING: skipping network "
2923 				    "interface '%s' which is used in the "
2924 				    "global zone.\n"),
2925 				    nwiftab.zone_nwif_physical);
2926 				break;
2927 			}
2928 
2929 			/*
2930 			 * Verify that the physical interface can be opened.
2931 			 */
2932 			err = dlpi_open(nwiftab.zone_nwif_physical, &dh, 0);
2933 			if (err != DLPI_SUCCESS) {
2934 				(void) fprintf(stderr,
2935 				    gettext("WARNING: skipping network "
2936 				    "interface '%s' which cannot be opened: "
2937 				    "dlpi error (%s).\n"),
2938 				    nwiftab.zone_nwif_physical,
2939 				    dlpi_strerror(err));
2940 				break;
2941 			} else {
2942 				dlpi_close(dh);
2943 			}
2944 			/*
2945 			 * Verify whether the physical interface is already
2946 			 * used by a zone.
2947 			 */
2948 			dl_owner_zid = ALL_ZONES;
2949 			if (zone_check_datalink(&dl_owner_zid,
2950 			    nwiftab.zone_nwif_physical) != 0)
2951 				break;
2952 
2953 			/*
2954 			 * If the zone being verified is
2955 			 * running and owns the interface
2956 			 */
2957 			target_zid = getzoneidbyname(target_zone);
2958 			if (target_zid == dl_owner_zid)
2959 				break;
2960 
2961 			/* Zone id match failed, use name to check */
2962 			if (getzonenamebyid(dl_owner_zid, dl_owner_zname,
2963 			    ZONENAME_MAX) < 0) {
2964 				/* No name, show ID instead */
2965 				(void) snprintf(dl_owner_zname, ZONENAME_MAX,
2966 				    "<%d>", dl_owner_zid);
2967 			} else if (strcmp(dl_owner_zname, target_zone) == 0)
2968 				break;
2969 
2970 			/*
2971 			 * Note here we only report a warning that
2972 			 * the interface is already in use by another
2973 			 * running zone, and the verify process just
2974 			 * goes on, if the interface is still in use
2975 			 * when this zone really boots up, zoneadmd
2976 			 * will find it. If the name of the zone which
2977 			 * owns this interface cannot be determined,
2978 			 * then it is not possible to determine if there
2979 			 * is a conflict so just report it as a warning.
2980 			 */
2981 			(void) fprintf(stderr,
2982 			    gettext("WARNING: skipping network interface "
2983 			    "'%s' which is used by the non-global zone "
2984 			    "'%s'.\n"), nwiftab.zone_nwif_physical,
2985 			    dl_owner_zname);
2986 			break;
2987 		}
2988 	}
2989 	(void) zonecfg_endnwifent(handle);
2990 no_net:
2991 
2992 	/* verify that lofs has not been excluded from the kernel */
2993 	if (!(cmd_num == CMD_DETACH || cmd_num == CMD_ATTACH ||
2994 	    cmd_num == CMD_MOVE || cmd_num == CMD_CLONE) &&
2995 	    modctl(MODLOAD, 1, "fs/lofs", NULL) != 0) {
2996 		if (errno == ENXIO)
2997 			(void) fprintf(stderr, gettext("could not verify "
2998 			    "lofs(7FS): possibly excluded in /etc/system\n"));
2999 		else
3000 			(void) fprintf(stderr, gettext("could not verify "
3001 			    "lofs(7FS): %s\n"), strerror(errno));
3002 		return_code = Z_ERR;
3003 	}
3004 
3005 	if (verify_filesystems(handle) != Z_OK)
3006 		return_code = Z_ERR;
3007 	if (verify_ipd(handle) != Z_OK)
3008 		return_code = Z_ERR;
3009 	if (!in_alt_root && verify_rctls(handle) != Z_OK)
3010 		return_code = Z_ERR;
3011 	if (!in_alt_root && verify_pool(handle) != Z_OK)
3012 		return_code = Z_ERR;
3013 	if (!in_alt_root && verify_brand(handle, cmd_num, argv) != Z_OK)
3014 		return_code = Z_ERR;
3015 	if (!in_alt_root && verify_datasets(handle) != Z_OK)
3016 		return_code = Z_ERR;
3017 
3018 	/*
3019 	 * As the "mount" command is used for patching/upgrading of zones
3020 	 * or other maintenance processes, the zone's privilege set is not
3021 	 * checked in this case.  Instead, the default, safe set of
3022 	 * privileges will be used when this zone is created in the
3023 	 * kernel.
3024 	 */
3025 	if (!in_alt_root && cmd_num != CMD_MOUNT &&
3026 	    verify_limitpriv(handle) != Z_OK)
3027 		return_code = Z_ERR;
3028 
3029 	return (return_code);
3030 }
3031 
3032 static int
3033 verify_details(int cmd_num, char *argv[])
3034 {
3035 	zone_dochandle_t handle;
3036 	char zonepath[MAXPATHLEN], checkpath[MAXPATHLEN];
3037 	int return_code = Z_OK;
3038 	int err;
3039 
3040 	if ((handle = zonecfg_init_handle()) == NULL) {
3041 		zperror(cmd_to_str(cmd_num), B_TRUE);
3042 		return (Z_ERR);
3043 	}
3044 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
3045 		errno = err;
3046 		zperror(cmd_to_str(cmd_num), B_TRUE);
3047 		zonecfg_fini_handle(handle);
3048 		return (Z_ERR);
3049 	}
3050 	if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
3051 	    Z_OK) {
3052 		errno = err;
3053 		zperror(cmd_to_str(cmd_num), B_TRUE);
3054 		zonecfg_fini_handle(handle);
3055 		return (Z_ERR);
3056 	}
3057 	/*
3058 	 * zonecfg_get_zonepath() gets its data from the XML repository.
3059 	 * Verify this against the index file, which is checked first by
3060 	 * zone_get_zonepath().  If they don't match, bail out.
3061 	 */
3062 	if ((err = zone_get_zonepath(target_zone, checkpath,
3063 	    sizeof (checkpath))) != Z_OK) {
3064 		errno = err;
3065 		zperror2(target_zone, gettext("could not get zone path"));
3066 		zonecfg_fini_handle(handle);
3067 		return (Z_ERR);
3068 	}
3069 	if (strcmp(zonepath, checkpath) != 0) {
3070 		/*
3071 		 * TRANSLATION_NOTE
3072 		 * XML and zonepath are literals that should not be translated.
3073 		 */
3074 		(void) fprintf(stderr, gettext("The XML repository has "
3075 		    "zonepath '%s',\nbut the index file has zonepath '%s'.\n"
3076 		    "These must match, so fix the incorrect entry.\n"),
3077 		    zonepath, checkpath);
3078 		zonecfg_fini_handle(handle);
3079 		return (Z_ERR);
3080 	}
3081 	if (validate_zonepath(zonepath, cmd_num) != Z_OK) {
3082 		(void) fprintf(stderr, gettext("could not verify zonepath %s "
3083 		    "because of the above errors.\n"), zonepath);
3084 		return_code = Z_ERR;
3085 	}
3086 
3087 	if (verify_handle(cmd_num, handle, argv) != Z_OK)
3088 		return_code = Z_ERR;
3089 
3090 	zonecfg_fini_handle(handle);
3091 	if (return_code == Z_ERR)
3092 		(void) fprintf(stderr,
3093 		    gettext("%s: zone %s failed to verify\n"),
3094 		    execname, target_zone);
3095 	return (return_code);
3096 }
3097 
3098 static int
3099 verify_func(int argc, char *argv[])
3100 {
3101 	int arg;
3102 
3103 	optind = 0;
3104 	if ((arg = getopt(argc, argv, "?")) != EOF) {
3105 		switch (arg) {
3106 		case '?':
3107 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
3108 			return (optopt == '?' ? Z_OK : Z_USAGE);
3109 		default:
3110 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
3111 			return (Z_USAGE);
3112 		}
3113 	}
3114 	if (argc > optind) {
3115 		sub_usage(SHELP_VERIFY, CMD_VERIFY);
3116 		return (Z_USAGE);
3117 	}
3118 	if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE, B_FALSE)
3119 	    != Z_OK)
3120 		return (Z_ERR);
3121 	return (verify_details(CMD_VERIFY, argv));
3122 }
3123 
3124 static int
3125 addopt(char *buf, int opt, char *optarg, size_t bufsize)
3126 {
3127 	char optstring[4];
3128 
3129 	if (opt > 0)
3130 		(void) sprintf(optstring, " -%c", opt);
3131 	else
3132 		(void) strcpy(optstring, " ");
3133 
3134 	if ((strlcat(buf, optstring, bufsize) > bufsize))
3135 		return (Z_ERR);
3136 	if ((optarg != NULL) && (strlcat(buf, optarg, bufsize) > bufsize))
3137 		return (Z_ERR);
3138 	return (Z_OK);
3139 }
3140 
3141 static int
3142 install_func(int argc, char *argv[])
3143 {
3144 	char cmdbuf[MAXPATHLEN];
3145 	char postcmdbuf[MAXPATHLEN];
3146 	int lockfd;
3147 	int arg, err, subproc_err;
3148 	char zonepath[MAXPATHLEN];
3149 	brand_handle_t bh = NULL;
3150 	int status;
3151 	boolean_t nodataset = B_FALSE;
3152 	boolean_t do_postinstall = B_FALSE;
3153 	char opts[128];
3154 
3155 	if (target_zone == NULL) {
3156 		sub_usage(SHELP_INSTALL, CMD_INSTALL);
3157 		return (Z_USAGE);
3158 	}
3159 
3160 	if (zonecfg_in_alt_root()) {
3161 		zerror(gettext("cannot install zone in alternate root"));
3162 		return (Z_ERR);
3163 	}
3164 
3165 	if ((err = zone_get_zonepath(target_zone, zonepath,
3166 	    sizeof (zonepath))) != Z_OK) {
3167 		errno = err;
3168 		zperror2(target_zone, gettext("could not get zone path"));
3169 		return (Z_ERR);
3170 	}
3171 
3172 	/* Fetch the install command from the brand configuration.  */
3173 	if ((bh = brand_open(target_brand)) == NULL) {
3174 		zerror(gettext("missing or invalid brand"));
3175 		return (Z_ERR);
3176 	}
3177 
3178 	(void) strcpy(cmdbuf, EXEC_PREFIX);
3179 	if (brand_get_install(bh, target_zone, zonepath, cmdbuf + EXEC_LEN,
3180 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL) != 0) {
3181 		zerror("invalid brand configuration: missing install resource");
3182 		brand_close(bh);
3183 		return (Z_ERR);
3184 	}
3185 
3186 	(void) strcpy(postcmdbuf, EXEC_PREFIX);
3187 	if (brand_get_postinstall(bh, target_zone, zonepath,
3188 	    postcmdbuf + EXEC_LEN, sizeof (postcmdbuf) - EXEC_LEN, 0, NULL)
3189 	    != 0) {
3190 		zerror("invalid brand configuration: missing postinstall "
3191 		    "resource");
3192 		brand_close(bh);
3193 		return (Z_ERR);
3194 	} else if (strlen(postcmdbuf) > EXEC_LEN) {
3195 		do_postinstall = B_TRUE;
3196 	}
3197 
3198 	(void) strcpy(opts, "?x:");
3199 	if (!is_native_zone) {
3200 		/*
3201 		 * Fetch the list of recognized command-line options from
3202 		 * the brand configuration file.
3203 		 */
3204 		if (brand_get_installopts(bh, opts + strlen(opts),
3205 		    sizeof (opts) - strlen(opts)) != 0) {
3206 			zerror("invalid brand configuration: missing "
3207 			    "install options resource");
3208 			brand_close(bh);
3209 			return (Z_ERR);
3210 		}
3211 	}
3212 	brand_close(bh);
3213 
3214 	optind = 0;
3215 	while ((arg = getopt(argc, argv, opts)) != EOF) {
3216 		switch (arg) {
3217 		case '?':
3218 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
3219 			return (optopt == '?' ? Z_OK : Z_USAGE);
3220 		case 'x':
3221 			if (strcmp(optarg, "nodataset") != 0) {
3222 				sub_usage(SHELP_INSTALL, CMD_INSTALL);
3223 				return (Z_USAGE);
3224 			}
3225 			nodataset = B_TRUE;
3226 			break;
3227 		default:
3228 			if (is_native_zone) {
3229 				sub_usage(SHELP_INSTALL, CMD_INSTALL);
3230 				return (Z_USAGE);
3231 			}
3232 
3233 			/*
3234 			 * This option isn't for zoneadm, so append it to
3235 			 * the command line passed to the brand-specific
3236 			 * install and postinstall routines.
3237 			 */
3238 			if (addopt(cmdbuf, optopt, optarg,
3239 			    sizeof (cmdbuf)) != Z_OK) {
3240 				zerror("Install command line too long");
3241 				return (Z_ERR);
3242 			}
3243 			if (addopt(postcmdbuf, optopt, optarg,
3244 			    sizeof (postcmdbuf)) != Z_OK) {
3245 				zerror("Post-Install command line too long");
3246 				return (Z_ERR);
3247 			}
3248 			break;
3249 		}
3250 	}
3251 
3252 	if (!is_native_zone) {
3253 		for (; optind < argc; optind++) {
3254 			if (addopt(cmdbuf, 0, argv[optind],
3255 			    sizeof (cmdbuf)) != Z_OK) {
3256 				zerror("Install command line too long");
3257 				return (Z_ERR);
3258 			}
3259 			if (addopt(postcmdbuf, 0, argv[optind],
3260 			    sizeof (postcmdbuf)) != Z_OK) {
3261 				zerror("Post-Install command line too long");
3262 				return (Z_ERR);
3263 			}
3264 		}
3265 	}
3266 
3267 	if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE, B_FALSE)
3268 	    != Z_OK)
3269 		return (Z_ERR);
3270 	if (verify_details(CMD_INSTALL, argv) != Z_OK)
3271 		return (Z_ERR);
3272 
3273 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
3274 		zerror(gettext("another %s may have an operation in progress."),
3275 		    "zoneadm");
3276 		return (Z_ERR);
3277 	}
3278 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
3279 	if (err != Z_OK) {
3280 		errno = err;
3281 		zperror2(target_zone, gettext("could not set state"));
3282 		goto done;
3283 	}
3284 
3285 	if (!nodataset)
3286 		create_zfs_zonepath(zonepath);
3287 
3288 	/*
3289 	 * According to the Application Packaging Developer's Guide, a
3290 	 * "checkinstall" script when included in a package is executed as
3291 	 * the user "install", if such a user exists, or by the user
3292 	 * "nobody".  In order to support this dubious behavior, the path
3293 	 * to the zone being constructed is opened up during the life of
3294 	 * the command laying down the zone's root file system.  Once this
3295 	 * has completed, regardless of whether it was successful, the
3296 	 * path to the zone is again restricted.
3297 	 */
3298 	if (chmod(zonepath, DEFAULT_DIR_MODE) != 0) {
3299 		zperror(zonepath, B_FALSE);
3300 		err = Z_ERR;
3301 		goto done;
3302 	}
3303 
3304 	if (is_native_zone)
3305 		status = do_subproc(cmdbuf);
3306 	else
3307 		status = do_subproc_interactive(cmdbuf);
3308 
3309 	if (chmod(zonepath, S_IRWXU) != 0) {
3310 		zperror(zonepath, B_FALSE);
3311 		err = Z_ERR;
3312 		goto done;
3313 	}
3314 	if ((subproc_err =
3315 	    subproc_status(gettext("brand-specific installation"), status,
3316 	    B_FALSE)) != ZONE_SUBPROC_OK) {
3317 		err = Z_ERR;
3318 		goto done;
3319 	}
3320 
3321 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
3322 		errno = err;
3323 		zperror2(target_zone, gettext("could not set state"));
3324 		goto done;
3325 	}
3326 
3327 	if (do_postinstall) {
3328 		status = do_subproc(postcmdbuf);
3329 
3330 		if ((subproc_err =
3331 		    subproc_status(gettext("brand-specific post-install"),
3332 		    status, B_FALSE)) != ZONE_SUBPROC_OK) {
3333 			err = Z_ERR;
3334 			(void) zone_set_state(target_zone,
3335 			    ZONE_STATE_INCOMPLETE);
3336 		}
3337 	}
3338 
3339 done:
3340 	/*
3341 	 * If the install script exited with ZONE_SUBPROC_USAGE or
3342 	 * ZONE_SUBPROC_NOTCOMPLETE, try to clean up the zone and leave the
3343 	 * zone in the CONFIGURED state so that another install can be
3344 	 * attempted without requiring an uninstall first.
3345 	 */
3346 	if ((subproc_err == ZONE_SUBPROC_USAGE) ||
3347 	    (subproc_err == ZONE_SUBPROC_NOTCOMPLETE)) {
3348 		if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
3349 			errno = err;
3350 			zperror2(target_zone,
3351 			    gettext("cleaning up zonepath failed"));
3352 		} else if ((err = zone_set_state(target_zone,
3353 		    ZONE_STATE_CONFIGURED)) != Z_OK) {
3354 			errno = err;
3355 			zperror2(target_zone, gettext("could not set state"));
3356 		}
3357 	}
3358 
3359 	release_lock_file(lockfd);
3360 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3361 }
3362 
3363 /*
3364  * Check that the inherited pkg dirs are the same for the clone and its source.
3365  * The easiest way to do that is check that the list of ipds is the same
3366  * by matching each one against the other.  This algorithm should be fine since
3367  * the list of ipds should not be that long.
3368  */
3369 static int
3370 valid_ipd_clone(zone_dochandle_t s_handle, char *source_zone,
3371 	zone_dochandle_t t_handle, char *target_zone)
3372 {
3373 	int err;
3374 	int res = Z_OK;
3375 	int s_cnt = 0;
3376 	int t_cnt = 0;
3377 	struct zone_fstab s_fstab;
3378 	struct zone_fstab t_fstab;
3379 
3380 	/*
3381 	 * First check the source of the clone against the target.
3382 	 */
3383 	if ((err = zonecfg_setipdent(s_handle)) != Z_OK) {
3384 		errno = err;
3385 		zperror2(source_zone, gettext("could not enumerate "
3386 		    "inherit-pkg-dirs"));
3387 		return (Z_ERR);
3388 	}
3389 
3390 	while (zonecfg_getipdent(s_handle, &s_fstab) == Z_OK) {
3391 		boolean_t match = B_FALSE;
3392 
3393 		s_cnt++;
3394 
3395 		if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
3396 			errno = err;
3397 			zperror2(target_zone, gettext("could not enumerate "
3398 			    "inherit-pkg-dirs"));
3399 			(void) zonecfg_endipdent(s_handle);
3400 			return (Z_ERR);
3401 		}
3402 
3403 		while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK) {
3404 			if (strcmp(s_fstab.zone_fs_dir, t_fstab.zone_fs_dir)
3405 			    == 0) {
3406 				match = B_TRUE;
3407 				break;
3408 			}
3409 		}
3410 		(void) zonecfg_endipdent(t_handle);
3411 
3412 		if (!match) {
3413 			(void) fprintf(stderr, gettext("inherit-pkg-dir "
3414 			    "'%s' is not configured in zone %s.\n"),
3415 			    s_fstab.zone_fs_dir, target_zone);
3416 			res = Z_ERR;
3417 		}
3418 	}
3419 
3420 	(void) zonecfg_endipdent(s_handle);
3421 
3422 	/* skip the next check if we already have errors */
3423 	if (res == Z_ERR)
3424 		return (res);
3425 
3426 	/*
3427 	 * Now check the number of ipds in the target so we can verify
3428 	 * that the source is not a subset of the target.
3429 	 */
3430 	if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
3431 		errno = err;
3432 		zperror2(target_zone, gettext("could not enumerate "
3433 		    "inherit-pkg-dirs"));
3434 		return (Z_ERR);
3435 	}
3436 
3437 	while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK)
3438 		t_cnt++;
3439 
3440 	(void) zonecfg_endipdent(t_handle);
3441 
3442 	if (t_cnt != s_cnt) {
3443 		(void) fprintf(stderr, gettext("Zone %s is configured "
3444 		    "with inherit-pkg-dirs that are not configured in zone "
3445 		    "%s.\n"), target_zone, source_zone);
3446 		res = Z_ERR;
3447 	}
3448 
3449 	return (res);
3450 }
3451 
3452 static void
3453 warn_dev_match(zone_dochandle_t s_handle, char *source_zone,
3454 	zone_dochandle_t t_handle, char *target_zone)
3455 {
3456 	int err;
3457 	struct zone_devtab s_devtab;
3458 	struct zone_devtab t_devtab;
3459 
3460 	if ((err = zonecfg_setdevent(t_handle)) != Z_OK) {
3461 		errno = err;
3462 		zperror2(target_zone, gettext("could not enumerate devices"));
3463 		return;
3464 	}
3465 
3466 	while (zonecfg_getdevent(t_handle, &t_devtab) == Z_OK) {
3467 		if ((err = zonecfg_setdevent(s_handle)) != Z_OK) {
3468 			errno = err;
3469 			zperror2(source_zone,
3470 			    gettext("could not enumerate devices"));
3471 			(void) zonecfg_enddevent(t_handle);
3472 			return;
3473 		}
3474 
3475 		while (zonecfg_getdevent(s_handle, &s_devtab) == Z_OK) {
3476 			/*
3477 			 * Use fnmatch to catch the case where wildcards
3478 			 * were used in one zone and the other has an
3479 			 * explicit entry (e.g. /dev/dsk/c0t0d0s6 vs.
3480 			 * /dev/\*dsk/c0t0d0s6).
3481 			 */
3482 			if (fnmatch(t_devtab.zone_dev_match,
3483 			    s_devtab.zone_dev_match, FNM_PATHNAME) == 0 ||
3484 			    fnmatch(s_devtab.zone_dev_match,
3485 			    t_devtab.zone_dev_match, FNM_PATHNAME) == 0) {
3486 				(void) fprintf(stderr,
3487 				    gettext("WARNING: device '%s' "
3488 				    "is configured in both zones.\n"),
3489 				    t_devtab.zone_dev_match);
3490 				break;
3491 			}
3492 		}
3493 		(void) zonecfg_enddevent(s_handle);
3494 	}
3495 
3496 	(void) zonecfg_enddevent(t_handle);
3497 }
3498 
3499 /*
3500  * Check if the specified mount option (opt) is contained within the
3501  * options string.
3502  */
3503 static boolean_t
3504 opt_match(char *opt, char *options)
3505 {
3506 	char *p;
3507 	char *lastp;
3508 
3509 	if ((p = strtok_r(options, ",", &lastp)) != NULL) {
3510 		if (strcmp(p, opt) == 0)
3511 			return (B_TRUE);
3512 		while ((p = strtok_r(NULL, ",", &lastp)) != NULL) {
3513 			if (strcmp(p, opt) == 0)
3514 				return (B_TRUE);
3515 		}
3516 	}
3517 
3518 	return (B_FALSE);
3519 }
3520 
3521 #define	RW_LOFS	"WARNING: read-write lofs file system on '%s' is configured " \
3522 	"in both zones.\n"
3523 
3524 static void
3525 print_fs_warnings(struct zone_fstab *s_fstab, struct zone_fstab *t_fstab)
3526 {
3527 	/*
3528 	 * It is ok to have shared lofs mounted fs but we want to warn if
3529 	 * either is rw since this will effect the other zone.
3530 	 */
3531 	if (strcmp(t_fstab->zone_fs_type, "lofs") == 0) {
3532 		zone_fsopt_t *optp;
3533 
3534 		/* The default is rw so no options means rw */
3535 		if (t_fstab->zone_fs_options == NULL ||
3536 		    s_fstab->zone_fs_options == NULL) {
3537 			(void) fprintf(stderr, gettext(RW_LOFS),
3538 			    t_fstab->zone_fs_special);
3539 			return;
3540 		}
3541 
3542 		for (optp = s_fstab->zone_fs_options; optp != NULL;
3543 		    optp = optp->zone_fsopt_next) {
3544 			if (opt_match("rw", optp->zone_fsopt_opt)) {
3545 				(void) fprintf(stderr, gettext(RW_LOFS),
3546 				    s_fstab->zone_fs_special);
3547 				return;
3548 			}
3549 		}
3550 
3551 		for (optp = t_fstab->zone_fs_options; optp != NULL;
3552 		    optp = optp->zone_fsopt_next) {
3553 			if (opt_match("rw", optp->zone_fsopt_opt)) {
3554 				(void) fprintf(stderr, gettext(RW_LOFS),
3555 				    t_fstab->zone_fs_special);
3556 				return;
3557 			}
3558 		}
3559 
3560 		return;
3561 	}
3562 
3563 	/*
3564 	 * TRANSLATION_NOTE
3565 	 * The first variable is the file system type and the second is
3566 	 * the file system special device.  For example,
3567 	 * WARNING: ufs file system on '/dev/dsk/c0t0d0s0' ...
3568 	 */
3569 	(void) fprintf(stderr, gettext("WARNING: %s file system on '%s' "
3570 	    "is configured in both zones.\n"), t_fstab->zone_fs_type,
3571 	    t_fstab->zone_fs_special);
3572 }
3573 
3574 static void
3575 warn_fs_match(zone_dochandle_t s_handle, char *source_zone,
3576 	zone_dochandle_t t_handle, char *target_zone)
3577 {
3578 	int err;
3579 	struct zone_fstab s_fstab;
3580 	struct zone_fstab t_fstab;
3581 
3582 	if ((err = zonecfg_setfsent(t_handle)) != Z_OK) {
3583 		errno = err;
3584 		zperror2(target_zone,
3585 		    gettext("could not enumerate file systems"));
3586 		return;
3587 	}
3588 
3589 	while (zonecfg_getfsent(t_handle, &t_fstab) == Z_OK) {
3590 		if ((err = zonecfg_setfsent(s_handle)) != Z_OK) {
3591 			errno = err;
3592 			zperror2(source_zone,
3593 			    gettext("could not enumerate file systems"));
3594 			(void) zonecfg_endfsent(t_handle);
3595 			return;
3596 		}
3597 
3598 		while (zonecfg_getfsent(s_handle, &s_fstab) == Z_OK) {
3599 			if (strcmp(t_fstab.zone_fs_special,
3600 			    s_fstab.zone_fs_special) == 0) {
3601 				print_fs_warnings(&s_fstab, &t_fstab);
3602 				break;
3603 			}
3604 		}
3605 		(void) zonecfg_endfsent(s_handle);
3606 	}
3607 
3608 	(void) zonecfg_endfsent(t_handle);
3609 }
3610 
3611 /*
3612  * We don't catch the case where you used the same IP address but
3613  * it is not an exact string match.  For example, 192.9.0.128 vs. 192.09.0.128.
3614  * However, we're not going to worry about that but we will check for
3615  * a possible netmask on one of the addresses (e.g. 10.0.0.1 and 10.0.0.1/24)
3616  * and handle that case as a match.
3617  */
3618 static void
3619 warn_ip_match(zone_dochandle_t s_handle, char *source_zone,
3620 	zone_dochandle_t t_handle, char *target_zone)
3621 {
3622 	int err;
3623 	struct zone_nwiftab s_nwiftab;
3624 	struct zone_nwiftab t_nwiftab;
3625 
3626 	if ((err = zonecfg_setnwifent(t_handle)) != Z_OK) {
3627 		errno = err;
3628 		zperror2(target_zone,
3629 		    gettext("could not enumerate network interfaces"));
3630 		return;
3631 	}
3632 
3633 	while (zonecfg_getnwifent(t_handle, &t_nwiftab) == Z_OK) {
3634 		char *p;
3635 
3636 		/* remove an (optional) netmask from the address */
3637 		if ((p = strchr(t_nwiftab.zone_nwif_address, '/')) != NULL)
3638 			*p = '\0';
3639 
3640 		if ((err = zonecfg_setnwifent(s_handle)) != Z_OK) {
3641 			errno = err;
3642 			zperror2(source_zone,
3643 			    gettext("could not enumerate network interfaces"));
3644 			(void) zonecfg_endnwifent(t_handle);
3645 			return;
3646 		}
3647 
3648 		while (zonecfg_getnwifent(s_handle, &s_nwiftab) == Z_OK) {
3649 			/* remove an (optional) netmask from the address */
3650 			if ((p = strchr(s_nwiftab.zone_nwif_address, '/'))
3651 			    != NULL)
3652 				*p = '\0';
3653 
3654 			/* For exclusive-IP zones, address is not specified. */
3655 			if (strlen(s_nwiftab.zone_nwif_address) == 0)
3656 				continue;
3657 
3658 			if (strcmp(t_nwiftab.zone_nwif_address,
3659 			    s_nwiftab.zone_nwif_address) == 0) {
3660 				(void) fprintf(stderr,
3661 				    gettext("WARNING: network address '%s' "
3662 				    "is configured in both zones.\n"),
3663 				    t_nwiftab.zone_nwif_address);
3664 				break;
3665 			}
3666 		}
3667 		(void) zonecfg_endnwifent(s_handle);
3668 	}
3669 
3670 	(void) zonecfg_endnwifent(t_handle);
3671 }
3672 
3673 static void
3674 warn_dataset_match(zone_dochandle_t s_handle, char *source,
3675 	zone_dochandle_t t_handle, char *target)
3676 {
3677 	int err;
3678 	struct zone_dstab s_dstab;
3679 	struct zone_dstab t_dstab;
3680 
3681 	if ((err = zonecfg_setdsent(t_handle)) != Z_OK) {
3682 		errno = err;
3683 		zperror2(target, gettext("could not enumerate datasets"));
3684 		return;
3685 	}
3686 
3687 	while (zonecfg_getdsent(t_handle, &t_dstab) == Z_OK) {
3688 		if ((err = zonecfg_setdsent(s_handle)) != Z_OK) {
3689 			errno = err;
3690 			zperror2(source,
3691 			    gettext("could not enumerate datasets"));
3692 			(void) zonecfg_enddsent(t_handle);
3693 			return;
3694 		}
3695 
3696 		while (zonecfg_getdsent(s_handle, &s_dstab) == Z_OK) {
3697 			if (strcmp(t_dstab.zone_dataset_name,
3698 			    s_dstab.zone_dataset_name) == 0) {
3699 				target_zone = source;
3700 				zerror(gettext("WARNING: dataset '%s' "
3701 				    "is configured in both zones.\n"),
3702 				    t_dstab.zone_dataset_name);
3703 				break;
3704 			}
3705 		}
3706 		(void) zonecfg_enddsent(s_handle);
3707 	}
3708 
3709 	(void) zonecfg_enddsent(t_handle);
3710 }
3711 
3712 /*
3713  * Check that the clone and its source have the same brand type.
3714  */
3715 static int
3716 valid_brand_clone(char *source_zone, char *target_zone)
3717 {
3718 	brand_handle_t bh;
3719 	char source_brand[MAXNAMELEN];
3720 
3721 	if ((zone_get_brand(source_zone, source_brand,
3722 	    sizeof (source_brand))) != Z_OK) {
3723 		(void) fprintf(stderr, "%s: zone '%s': %s\n",
3724 		    execname, source_zone, gettext("missing or invalid brand"));
3725 		return (Z_ERR);
3726 	}
3727 
3728 	if (strcmp(source_brand, target_brand) != NULL) {
3729 		(void) fprintf(stderr,
3730 		    gettext("%s: Zones '%s' and '%s' have different brand "
3731 		    "types.\n"), execname, source_zone, target_zone);
3732 		return (Z_ERR);
3733 	}
3734 
3735 	if ((bh = brand_open(target_brand)) == NULL) {
3736 		zerror(gettext("missing or invalid brand"));
3737 		return (Z_ERR);
3738 	}
3739 	brand_close(bh);
3740 	return (Z_OK);
3741 }
3742 
3743 static int
3744 validate_clone(char *source_zone, char *target_zone)
3745 {
3746 	int err = Z_OK;
3747 	zone_dochandle_t s_handle;
3748 	zone_dochandle_t t_handle;
3749 
3750 	if ((t_handle = zonecfg_init_handle()) == NULL) {
3751 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3752 		return (Z_ERR);
3753 	}
3754 	if ((err = zonecfg_get_handle(target_zone, t_handle)) != Z_OK) {
3755 		errno = err;
3756 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3757 		zonecfg_fini_handle(t_handle);
3758 		return (Z_ERR);
3759 	}
3760 
3761 	if ((s_handle = zonecfg_init_handle()) == NULL) {
3762 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3763 		zonecfg_fini_handle(t_handle);
3764 		return (Z_ERR);
3765 	}
3766 	if ((err = zonecfg_get_handle(source_zone, s_handle)) != Z_OK) {
3767 		errno = err;
3768 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3769 		goto done;
3770 	}
3771 
3772 	/* verify new zone has same brand type */
3773 	err = valid_brand_clone(source_zone, target_zone);
3774 	if (err != Z_OK)
3775 		goto done;
3776 
3777 	/* verify new zone has same inherit-pkg-dirs */
3778 	err = valid_ipd_clone(s_handle, source_zone, t_handle, target_zone);
3779 
3780 	/* warn about imported fs's which are the same */
3781 	warn_fs_match(s_handle, source_zone, t_handle, target_zone);
3782 
3783 	/* warn about imported IP addresses which are the same */
3784 	warn_ip_match(s_handle, source_zone, t_handle, target_zone);
3785 
3786 	/* warn about imported devices which are the same */
3787 	warn_dev_match(s_handle, source_zone, t_handle, target_zone);
3788 
3789 	/* warn about imported datasets which are the same */
3790 	warn_dataset_match(s_handle, source_zone, t_handle, target_zone);
3791 
3792 done:
3793 	zonecfg_fini_handle(t_handle);
3794 	zonecfg_fini_handle(s_handle);
3795 
3796 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3797 }
3798 
3799 static int
3800 copy_zone(char *src, char *dst)
3801 {
3802 	boolean_t out_null = B_FALSE;
3803 	int status;
3804 	char *outfile;
3805 	char cmdbuf[MAXPATHLEN * 2 + 128];
3806 
3807 	if ((outfile = tempnam("/var/log", "zone")) == NULL) {
3808 		outfile = "/dev/null";
3809 		out_null = B_TRUE;
3810 	}
3811 
3812 	/*
3813 	 * Use find to get the list of files to copy.  We need to skip
3814 	 * files of type "socket" since cpio can't handle those but that
3815 	 * should be ok since the app will recreate the socket when it runs.
3816 	 * We also need to filter out anything under the .zfs subdir.  Since
3817 	 * find is running depth-first, we need the extra egrep to filter .zfs.
3818 	 */
3819 	(void) snprintf(cmdbuf, sizeof (cmdbuf),
3820 	    "cd %s && /usr/bin/find . -type s -prune -o -depth -print | "
3821 	    "/usr/bin/egrep -v '^\\./\\.zfs$|^\\./\\.zfs/' | "
3822 	    "/usr/bin/cpio -pdmuP@ %s > %s 2>&1",
3823 	    src, dst, outfile);
3824 
3825 	status = do_subproc(cmdbuf);
3826 
3827 	if (subproc_status("copy", status, B_TRUE) != ZONE_SUBPROC_OK) {
3828 		if (!out_null)
3829 			(void) fprintf(stderr, gettext("\nThe copy failed.\n"
3830 			    "More information can be found in %s\n"), outfile);
3831 		return (Z_ERR);
3832 	}
3833 
3834 	if (!out_null)
3835 		(void) unlink(outfile);
3836 
3837 	return (Z_OK);
3838 }
3839 
3840 static int
3841 zone_postclone(char *zonepath)
3842 {
3843 	char cmdbuf[MAXPATHLEN];
3844 	int status;
3845 	brand_handle_t bh;
3846 	int err = Z_OK;
3847 
3848 	/*
3849 	 * Fetch the post-clone command, if any, from the brand
3850 	 * configuration.
3851 	 */
3852 	if ((bh = brand_open(target_brand)) == NULL) {
3853 		zerror(gettext("missing or invalid brand"));
3854 		return (Z_ERR);
3855 	}
3856 	(void) strcpy(cmdbuf, EXEC_PREFIX);
3857 	err = brand_get_postclone(bh, target_zone, zonepath, cmdbuf + EXEC_LEN,
3858 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL);
3859 	brand_close(bh);
3860 
3861 	if (err == 0 && strlen(cmdbuf) > EXEC_LEN) {
3862 		status = do_subproc(cmdbuf);
3863 		if ((err = subproc_status("postclone", status, B_FALSE))
3864 		    != ZONE_SUBPROC_OK) {
3865 			zerror(gettext("post-clone configuration failed."));
3866 			err = Z_ERR;
3867 		}
3868 	}
3869 
3870 	return (err);
3871 }
3872 
3873 /* ARGSUSED */
3874 static int
3875 zfm_print(const char *p, void *r) {
3876 	zerror("  %s\n", p);
3877 	return (0);
3878 }
3879 
3880 int
3881 clone_copy(char *source_zonepath, char *zonepath)
3882 {
3883 	int err;
3884 
3885 	/* Don't clone the zone if anything is still mounted there */
3886 	if (zonecfg_find_mounts(source_zonepath, NULL, NULL)) {
3887 		zerror(gettext("These file systems are mounted on "
3888 		    "subdirectories of %s.\n"), source_zonepath);
3889 		(void) zonecfg_find_mounts(source_zonepath, zfm_print, NULL);
3890 		return (Z_ERR);
3891 	}
3892 
3893 	/*
3894 	 * Attempt to create a ZFS fs for the zonepath.  As usual, we don't
3895 	 * care if this works or not since we always have the default behavior
3896 	 * of a simple directory for the zonepath.
3897 	 */
3898 	create_zfs_zonepath(zonepath);
3899 
3900 	(void) printf(gettext("Copying %s..."), source_zonepath);
3901 	(void) fflush(stdout);
3902 
3903 	err = copy_zone(source_zonepath, zonepath);
3904 
3905 	(void) printf("\n");
3906 
3907 	return (err);
3908 }
3909 
3910 static int
3911 clone_func(int argc, char *argv[])
3912 {
3913 	char *source_zone = NULL;
3914 	int lockfd;
3915 	int err, arg;
3916 	char zonepath[MAXPATHLEN];
3917 	char source_zonepath[MAXPATHLEN];
3918 	zone_state_t state;
3919 	zone_entry_t *zent;
3920 	char *method = NULL;
3921 	char *snapshot = NULL;
3922 
3923 	if (zonecfg_in_alt_root()) {
3924 		zerror(gettext("cannot clone zone in alternate root"));
3925 		return (Z_ERR);
3926 	}
3927 
3928 	optind = 0;
3929 	if ((arg = getopt(argc, argv, "?m:s:")) != EOF) {
3930 		switch (arg) {
3931 		case '?':
3932 			sub_usage(SHELP_CLONE, CMD_CLONE);
3933 			return (optopt == '?' ? Z_OK : Z_USAGE);
3934 		case 'm':
3935 			method = optarg;
3936 			break;
3937 		case 's':
3938 			snapshot = optarg;
3939 			break;
3940 		default:
3941 			sub_usage(SHELP_CLONE, CMD_CLONE);
3942 			return (Z_USAGE);
3943 		}
3944 	}
3945 	if (argc != (optind + 1) ||
3946 	    (method != NULL && strcmp(method, "copy") != 0)) {
3947 		sub_usage(SHELP_CLONE, CMD_CLONE);
3948 		return (Z_USAGE);
3949 	}
3950 	source_zone = argv[optind];
3951 	if (sanity_check(target_zone, CMD_CLONE, B_FALSE, B_TRUE, B_FALSE)
3952 	    != Z_OK)
3953 		return (Z_ERR);
3954 	if (verify_details(CMD_CLONE, argv) != Z_OK)
3955 		return (Z_ERR);
3956 
3957 	/*
3958 	 * We also need to do some extra validation on the source zone.
3959 	 */
3960 	if (strcmp(source_zone, GLOBAL_ZONENAME) == 0) {
3961 		zerror(gettext("%s operation is invalid for the global zone."),
3962 		    cmd_to_str(CMD_CLONE));
3963 		return (Z_ERR);
3964 	}
3965 
3966 	if (strncmp(source_zone, "SUNW", 4) == 0) {
3967 		zerror(gettext("%s operation is invalid for zones starting "
3968 		    "with SUNW."), cmd_to_str(CMD_CLONE));
3969 		return (Z_ERR);
3970 	}
3971 
3972 	zent = lookup_running_zone(source_zone);
3973 	if (zent != NULL) {
3974 		/* check whether the zone is ready or running */
3975 		if ((err = zone_get_state(zent->zname, &zent->zstate_num))
3976 		    != Z_OK) {
3977 			errno = err;
3978 			zperror2(zent->zname, gettext("could not get state"));
3979 			/* can't tell, so hedge */
3980 			zent->zstate_str = "ready/running";
3981 		} else {
3982 			zent->zstate_str = zone_state_str(zent->zstate_num);
3983 		}
3984 		zerror(gettext("%s operation is invalid for %s zones."),
3985 		    cmd_to_str(CMD_CLONE), zent->zstate_str);
3986 		return (Z_ERR);
3987 	}
3988 
3989 	if ((err = zone_get_state(source_zone, &state)) != Z_OK) {
3990 		errno = err;
3991 		zperror2(source_zone, gettext("could not get state"));
3992 		return (Z_ERR);
3993 	}
3994 	if (state != ZONE_STATE_INSTALLED) {
3995 		(void) fprintf(stderr,
3996 		    gettext("%s: zone %s is %s; %s is required.\n"),
3997 		    execname, source_zone, zone_state_str(state),
3998 		    zone_state_str(ZONE_STATE_INSTALLED));
3999 		return (Z_ERR);
4000 	}
4001 
4002 	/*
4003 	 * The source zone checks out ok, continue with the clone.
4004 	 */
4005 
4006 	if (validate_clone(source_zone, target_zone) != Z_OK)
4007 		return (Z_ERR);
4008 
4009 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
4010 		zerror(gettext("another %s may have an operation in progress."),
4011 		    "zoneadm");
4012 		return (Z_ERR);
4013 	}
4014 
4015 	if ((err = zone_get_zonepath(source_zone, source_zonepath,
4016 	    sizeof (source_zonepath))) != Z_OK) {
4017 		errno = err;
4018 		zperror2(source_zone, gettext("could not get zone path"));
4019 		goto done;
4020 	}
4021 
4022 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4023 	    != Z_OK) {
4024 		errno = err;
4025 		zperror2(target_zone, gettext("could not get zone path"));
4026 		goto done;
4027 	}
4028 
4029 	if ((err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE))
4030 	    != Z_OK) {
4031 		errno = err;
4032 		zperror2(target_zone, gettext("could not set state"));
4033 		goto done;
4034 	}
4035 
4036 	if (snapshot != NULL) {
4037 		err = clone_snapshot_zfs(snapshot, zonepath);
4038 	} else {
4039 		/*
4040 		 * We always copy the clone unless the source is ZFS and a
4041 		 * ZFS clone worked.  We fallback to copying if the ZFS clone
4042 		 * fails for some reason.
4043 		 */
4044 		err = Z_ERR;
4045 		if (method == NULL && is_zonepath_zfs(source_zonepath))
4046 			err = clone_zfs(source_zone, source_zonepath, zonepath);
4047 
4048 		if (err != Z_OK)
4049 			err = clone_copy(source_zonepath, zonepath);
4050 	}
4051 
4052 	/*
4053 	 * Trusted Extensions requires that cloned zones use the same sysid
4054 	 * configuration, so it is not appropriate to perform any
4055 	 * post-clone reconfiguration.
4056 	 */
4057 	if ((err == Z_OK) && !is_system_labeled())
4058 		err = zone_postclone(zonepath);
4059 
4060 done:
4061 	/*
4062 	 * If everything went well, we mark the zone as installed.
4063 	 */
4064 	if (err == Z_OK) {
4065 		err = zone_set_state(target_zone, ZONE_STATE_INSTALLED);
4066 		if (err != Z_OK) {
4067 			errno = err;
4068 			zperror2(target_zone, gettext("could not set state"));
4069 		}
4070 	}
4071 	release_lock_file(lockfd);
4072 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4073 }
4074 
4075 /*
4076  * Used when removing a zonepath after uninstalling or cleaning up after
4077  * the move subcommand.  This handles a zonepath that has non-standard
4078  * contents so that we will only cleanup the stuff we know about and leave
4079  * any user data alone.
4080  *
4081  * If the "all" parameter is true then we should remove the whole zonepath
4082  * even if it has non-standard files/directories in it.  This can be used when
4083  * we need to cleanup after moving the zonepath across file systems.
4084  *
4085  * We "exec" the RMCOMMAND so that the returned status is that of RMCOMMAND
4086  * and not the shell.
4087  */
4088 static int
4089 cleanup_zonepath(char *zonepath, boolean_t all)
4090 {
4091 	int		status;
4092 	int		i;
4093 	boolean_t	non_std = B_FALSE;
4094 	struct dirent	*dp;
4095 	DIR		*dirp;
4096 			/*
4097 			 * The SUNWattached.xml file is expected since it might
4098 			 * exist if the zone was force-attached after a
4099 			 * migration.
4100 			 */
4101 	char		*std_entries[] = {"dev", "lu", "root",
4102 			    "SUNWattached.xml", NULL};
4103 			/* (MAXPATHLEN * 3) is for the 3 std_entries dirs */
4104 	char		cmdbuf[sizeof (RMCOMMAND) + (MAXPATHLEN * 3) + 64];
4105 
4106 	/*
4107 	 * We shouldn't need these checks but lets be paranoid since we
4108 	 * could blow away the whole system here if we got the wrong zonepath.
4109 	 */
4110 	if (*zonepath == NULL || strcmp(zonepath, "/") == 0) {
4111 		(void) fprintf(stderr, "invalid zonepath '%s'\n", zonepath);
4112 		return (Z_INVAL);
4113 	}
4114 
4115 	/*
4116 	 * If the dirpath is already gone (maybe it was manually removed) then
4117 	 * we just return Z_OK so that the cleanup is successful.
4118 	 */
4119 	if ((dirp = opendir(zonepath)) == NULL)
4120 		return (Z_OK);
4121 
4122 	/*
4123 	 * Look through the zonepath directory to see if there are any
4124 	 * non-standard files/dirs.  Also skip .zfs since that might be
4125 	 * there but we'll handle ZFS file systems as a special case.
4126 	 */
4127 	while ((dp = readdir(dirp)) != NULL) {
4128 		if (strcmp(dp->d_name, ".") == 0 ||
4129 		    strcmp(dp->d_name, "..") == 0 ||
4130 		    strcmp(dp->d_name, ".zfs") == 0)
4131 			continue;
4132 
4133 		for (i = 0; std_entries[i] != NULL; i++)
4134 			if (strcmp(dp->d_name, std_entries[i]) == 0)
4135 				break;
4136 
4137 		if (std_entries[i] == NULL)
4138 			non_std = B_TRUE;
4139 	}
4140 	(void) closedir(dirp);
4141 
4142 	if (!all && non_std) {
4143 		/*
4144 		 * There are extra, non-standard directories/files in the
4145 		 * zonepath so we don't want to remove the zonepath.  We
4146 		 * just want to remove the standard directories and leave
4147 		 * the user data alone.
4148 		 */
4149 		(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND);
4150 
4151 		for (i = 0; std_entries[i] != NULL; i++) {
4152 			char tmpbuf[MAXPATHLEN];
4153 
4154 			if (snprintf(tmpbuf, sizeof (tmpbuf), " %s/%s",
4155 			    zonepath, std_entries[i]) >= sizeof (tmpbuf) ||
4156 			    strlcat(cmdbuf, tmpbuf, sizeof (cmdbuf)) >=
4157 			    sizeof (cmdbuf)) {
4158 				(void) fprintf(stderr,
4159 				    gettext("path is too long\n"));
4160 				return (Z_INVAL);
4161 			}
4162 		}
4163 
4164 		status = do_subproc(cmdbuf);
4165 
4166 		(void) fprintf(stderr, gettext("WARNING: Unable to completely "
4167 		    "remove %s\nbecause it contains additional user data.  "
4168 		    "Only the standard directory\nentries have been "
4169 		    "removed.\n"),
4170 		    zonepath);
4171 
4172 		return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
4173 		    ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
4174 	}
4175 
4176 	/*
4177 	 * There is nothing unexpected in the zonepath, try to get rid of the
4178 	 * whole zonepath directory.
4179 	 *
4180 	 * If the zonepath is its own zfs file system, try to destroy the
4181 	 * file system.  If that fails for some reason (e.g. it has clones)
4182 	 * then we'll just remove the contents of the zonepath.
4183 	 */
4184 	if (is_zonepath_zfs(zonepath)) {
4185 		if (destroy_zfs(zonepath) == Z_OK)
4186 			return (Z_OK);
4187 		(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND
4188 		    " %s/*", zonepath);
4189 		status = do_subproc(cmdbuf);
4190 		return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
4191 		    ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
4192 	}
4193 
4194 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
4195 	    zonepath);
4196 	status = do_subproc(cmdbuf);
4197 
4198 	return ((subproc_status(RMCOMMAND, status, B_TRUE) == ZONE_SUBPROC_OK)
4199 	    ? Z_OK : Z_ERR);
4200 }
4201 
4202 static int
4203 move_func(int argc, char *argv[])
4204 {
4205 	char *new_zonepath = NULL;
4206 	int lockfd;
4207 	int err, arg;
4208 	char zonepath[MAXPATHLEN];
4209 	zone_dochandle_t handle;
4210 	boolean_t fast;
4211 	boolean_t is_zfs = B_FALSE;
4212 	struct dirent *dp;
4213 	DIR *dirp;
4214 	boolean_t empty = B_TRUE;
4215 	boolean_t revert;
4216 	struct stat zonepath_buf;
4217 	struct stat new_zonepath_buf;
4218 
4219 	if (zonecfg_in_alt_root()) {
4220 		zerror(gettext("cannot move zone in alternate root"));
4221 		return (Z_ERR);
4222 	}
4223 
4224 	optind = 0;
4225 	if ((arg = getopt(argc, argv, "?")) != EOF) {
4226 		switch (arg) {
4227 		case '?':
4228 			sub_usage(SHELP_MOVE, CMD_MOVE);
4229 			return (optopt == '?' ? Z_OK : Z_USAGE);
4230 		default:
4231 			sub_usage(SHELP_MOVE, CMD_MOVE);
4232 			return (Z_USAGE);
4233 		}
4234 	}
4235 	if (argc != (optind + 1)) {
4236 		sub_usage(SHELP_MOVE, CMD_MOVE);
4237 		return (Z_USAGE);
4238 	}
4239 	new_zonepath = argv[optind];
4240 	if (sanity_check(target_zone, CMD_MOVE, B_FALSE, B_TRUE, B_FALSE)
4241 	    != Z_OK)
4242 		return (Z_ERR);
4243 	if (verify_details(CMD_MOVE, argv) != Z_OK)
4244 		return (Z_ERR);
4245 
4246 	/*
4247 	 * Check out the new zonepath.  This has the side effect of creating
4248 	 * a directory for the new zonepath.  We depend on this later when we
4249 	 * stat to see if we are doing a cross file system move or not.
4250 	 */
4251 	if (validate_zonepath(new_zonepath, CMD_MOVE) != Z_OK)
4252 		return (Z_ERR);
4253 
4254 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4255 	    != Z_OK) {
4256 		errno = err;
4257 		zperror2(target_zone, gettext("could not get zone path"));
4258 		return (Z_ERR);
4259 	}
4260 
4261 	if (stat(zonepath, &zonepath_buf) == -1) {
4262 		zperror(gettext("could not stat zone path"), B_FALSE);
4263 		return (Z_ERR);
4264 	}
4265 
4266 	if (stat(new_zonepath, &new_zonepath_buf) == -1) {
4267 		zperror(gettext("could not stat new zone path"), B_FALSE);
4268 		return (Z_ERR);
4269 	}
4270 
4271 	/*
4272 	 * Check if the destination directory is empty.
4273 	 */
4274 	if ((dirp = opendir(new_zonepath)) == NULL) {
4275 		zperror(gettext("could not open new zone path"), B_FALSE);
4276 		return (Z_ERR);
4277 	}
4278 	while ((dp = readdir(dirp)) != (struct dirent *)0) {
4279 		if (strcmp(dp->d_name, ".") == 0 ||
4280 		    strcmp(dp->d_name, "..") == 0)
4281 			continue;
4282 		empty = B_FALSE;
4283 		break;
4284 	}
4285 	(void) closedir(dirp);
4286 
4287 	/* Error if there is anything in the destination directory. */
4288 	if (!empty) {
4289 		(void) fprintf(stderr, gettext("could not move zone to %s: "
4290 		    "directory not empty\n"), new_zonepath);
4291 		return (Z_ERR);
4292 	}
4293 
4294 	/* Don't move the zone if anything is still mounted there */
4295 	if (zonecfg_find_mounts(zonepath, NULL, NULL)) {
4296 		zerror(gettext("These file systems are mounted on "
4297 		    "subdirectories of %s.\n"), zonepath);
4298 		(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
4299 		return (Z_ERR);
4300 	}
4301 
4302 	/*
4303 	 * Check if we are moving in the same file system and can do a fast
4304 	 * move or if we are crossing file systems and have to copy the data.
4305 	 */
4306 	fast = (zonepath_buf.st_dev == new_zonepath_buf.st_dev);
4307 
4308 	if ((handle = zonecfg_init_handle()) == NULL) {
4309 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4310 		return (Z_ERR);
4311 	}
4312 
4313 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4314 		errno = err;
4315 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4316 		zonecfg_fini_handle(handle);
4317 		return (Z_ERR);
4318 	}
4319 
4320 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
4321 		zerror(gettext("another %s may have an operation in progress."),
4322 		    "zoneadm");
4323 		zonecfg_fini_handle(handle);
4324 		return (Z_ERR);
4325 	}
4326 
4327 	/*
4328 	 * We're making some file system changes now so we have to clean up
4329 	 * the file system before we are done.  This will either clean up the
4330 	 * new zonepath if the zonecfg update failed or it will clean up the
4331 	 * old zonepath if everything is ok.
4332 	 */
4333 	revert = B_TRUE;
4334 
4335 	if (is_zonepath_zfs(zonepath) &&
4336 	    move_zfs(zonepath, new_zonepath) != Z_ERR) {
4337 		is_zfs = B_TRUE;
4338 
4339 	} else if (fast) {
4340 		/* same file system, use rename for a quick move */
4341 
4342 		/*
4343 		 * Remove the new_zonepath directory that got created above
4344 		 * during the validation.  It gets in the way of the rename.
4345 		 */
4346 		if (rmdir(new_zonepath) != 0) {
4347 			zperror(gettext("could not rmdir new zone path"),
4348 			    B_FALSE);
4349 			zonecfg_fini_handle(handle);
4350 			release_lock_file(lockfd);
4351 			return (Z_ERR);
4352 		}
4353 
4354 		if (rename(zonepath, new_zonepath) != 0) {
4355 			/*
4356 			 * If this fails we don't need to do all of the
4357 			 * cleanup that happens for the rest of the code
4358 			 * so just return from this error.
4359 			 */
4360 			zperror(gettext("could not move zone"), B_FALSE);
4361 			zonecfg_fini_handle(handle);
4362 			release_lock_file(lockfd);
4363 			return (Z_ERR);
4364 		}
4365 
4366 	} else {
4367 		/*
4368 		 * Attempt to create a ZFS fs for the new zonepath.  As usual,
4369 		 * we don't care if this works or not since we always have the
4370 		 * default behavior of a simple directory for the zonepath.
4371 		 */
4372 		create_zfs_zonepath(new_zonepath);
4373 
4374 		(void) printf(gettext(
4375 		    "Moving across file systems; copying zonepath %s..."),
4376 		    zonepath);
4377 		(void) fflush(stdout);
4378 
4379 		err = copy_zone(zonepath, new_zonepath);
4380 
4381 		(void) printf("\n");
4382 		if (err != Z_OK)
4383 			goto done;
4384 	}
4385 
4386 	if ((err = zonecfg_set_zonepath(handle, new_zonepath)) != Z_OK) {
4387 		errno = err;
4388 		zperror(gettext("could not set new zonepath"), B_TRUE);
4389 		goto done;
4390 	}
4391 
4392 	if ((err = zonecfg_save(handle)) != Z_OK) {
4393 		errno = err;
4394 		zperror(gettext("zonecfg save failed"), B_TRUE);
4395 		goto done;
4396 	}
4397 
4398 	revert = B_FALSE;
4399 
4400 done:
4401 	zonecfg_fini_handle(handle);
4402 	release_lock_file(lockfd);
4403 
4404 	/*
4405 	 * Clean up the file system based on how things went.  We either
4406 	 * clean up the new zonepath if the operation failed for some reason
4407 	 * or we clean up the old zonepath if everything is ok.
4408 	 */
4409 	if (revert) {
4410 		/* The zonecfg update failed, cleanup the new zonepath. */
4411 		if (is_zfs) {
4412 			if (move_zfs(new_zonepath, zonepath) == Z_ERR) {
4413 				(void) fprintf(stderr, gettext("could not "
4414 				    "restore zonepath, the zfs mountpoint is "
4415 				    "set as:\n%s\n"), new_zonepath);
4416 				/*
4417 				 * err is already != Z_OK since we're reverting
4418 				 */
4419 			}
4420 
4421 		} else if (fast) {
4422 			if (rename(new_zonepath, zonepath) != 0) {
4423 				zperror(gettext("could not restore zonepath"),
4424 				    B_FALSE);
4425 				/*
4426 				 * err is already != Z_OK since we're reverting
4427 				 */
4428 			}
4429 		} else {
4430 			(void) printf(gettext("Cleaning up zonepath %s..."),
4431 			    new_zonepath);
4432 			(void) fflush(stdout);
4433 			err = cleanup_zonepath(new_zonepath, B_TRUE);
4434 			(void) printf("\n");
4435 
4436 			if (err != Z_OK) {
4437 				errno = err;
4438 				zperror(gettext("could not remove new "
4439 				    "zonepath"), B_TRUE);
4440 			} else {
4441 				/*
4442 				 * Because we're reverting we know the mainline
4443 				 * code failed but we just reused the err
4444 				 * variable so we reset it back to Z_ERR.
4445 				 */
4446 				err = Z_ERR;
4447 			}
4448 		}
4449 
4450 	} else {
4451 		/* The move was successful, cleanup the old zonepath. */
4452 		if (!is_zfs && !fast) {
4453 			(void) printf(
4454 			    gettext("Cleaning up zonepath %s..."), zonepath);
4455 			(void) fflush(stdout);
4456 			err = cleanup_zonepath(zonepath, B_TRUE);
4457 			(void) printf("\n");
4458 
4459 			if (err != Z_OK) {
4460 				errno = err;
4461 				zperror(gettext("could not remove zonepath"),
4462 				    B_TRUE);
4463 			}
4464 		}
4465 	}
4466 
4467 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4468 }
4469 
4470 static int
4471 detach_func(int argc, char *argv[])
4472 {
4473 	int lockfd;
4474 	int err, arg;
4475 	char zonepath[MAXPATHLEN];
4476 	char cmdbuf[MAXPATHLEN];
4477 	zone_dochandle_t handle;
4478 	boolean_t execute = B_TRUE;
4479 	brand_handle_t bh = NULL;
4480 
4481 	if (zonecfg_in_alt_root()) {
4482 		zerror(gettext("cannot detach zone in alternate root"));
4483 		return (Z_ERR);
4484 	}
4485 
4486 	optind = 0;
4487 	if ((arg = getopt(argc, argv, "?n")) != EOF) {
4488 		switch (arg) {
4489 		case '?':
4490 			sub_usage(SHELP_DETACH, CMD_DETACH);
4491 			return (optopt == '?' ? Z_OK : Z_USAGE);
4492 		case 'n':
4493 			execute = B_FALSE;
4494 			break;
4495 		default:
4496 			sub_usage(SHELP_DETACH, CMD_DETACH);
4497 			return (Z_USAGE);
4498 		}
4499 	}
4500 
4501 	if (execute) {
4502 		if (sanity_check(target_zone, CMD_DETACH, B_FALSE, B_TRUE,
4503 		    B_FALSE) != Z_OK)
4504 			return (Z_ERR);
4505 		if (verify_details(CMD_DETACH, argv) != Z_OK)
4506 			return (Z_ERR);
4507 	} else {
4508 		/*
4509 		 * We want a dry-run to work for a non-privileged user so we
4510 		 * only do minimal validation.
4511 		 */
4512 		if (target_zone == NULL) {
4513 			zerror(gettext("no zone specified"));
4514 			return (Z_ERR);
4515 		}
4516 
4517 		if (strcmp(target_zone, GLOBAL_ZONENAME) == 0) {
4518 			zerror(gettext("%s operation is invalid for the "
4519 			    "global zone."), cmd_to_str(CMD_DETACH));
4520 			return (Z_ERR);
4521 		}
4522 	}
4523 
4524 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4525 	    != Z_OK) {
4526 		errno = err;
4527 		zperror2(target_zone, gettext("could not get zone path"));
4528 		return (Z_ERR);
4529 	}
4530 
4531 	/* Don't detach the zone if anything is still mounted there */
4532 	if (execute && zonecfg_find_mounts(zonepath, NULL, NULL)) {
4533 		zerror(gettext("These file systems are mounted on "
4534 		    "subdirectories of %s.\n"), zonepath);
4535 		(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
4536 		return (Z_ERR);
4537 	}
4538 
4539 	if ((handle = zonecfg_init_handle()) == NULL) {
4540 		zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4541 		return (Z_ERR);
4542 	}
4543 
4544 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4545 		errno = err;
4546 		zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4547 		zonecfg_fini_handle(handle);
4548 		return (Z_ERR);
4549 	}
4550 
4551 	/* Fetch the predetach hook from the brand configuration.  */
4552 	if ((bh = brand_open(target_brand)) == NULL) {
4553 		zerror(gettext("missing or invalid brand"));
4554 		return (Z_ERR);
4555 	}
4556 
4557 	(void) strcpy(cmdbuf, EXEC_PREFIX);
4558 	if (brand_get_predetach(bh, target_zone, zonepath, cmdbuf + EXEC_LEN,
4559 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL) != 0) {
4560 		zerror("invalid brand configuration: missing predetach "
4561 		    "resource");
4562 		brand_close(bh);
4563 		return (Z_ERR);
4564 	}
4565 	brand_close(bh);
4566 
4567 	/* If we have a brand predetach hook, run it. */
4568 	if (strlen(cmdbuf) > EXEC_LEN) {
4569 		int status;
4570 
4571 		/* If this is a dry-run, pass that flag to the hook. */
4572 		if (!execute && addopt(cmdbuf, 0, "-n", sizeof (cmdbuf))
4573 		    != Z_OK) {
4574 			zerror("Predetach command line too long");
4575 			return (Z_ERR);
4576 		}
4577 
4578 		status = do_subproc(cmdbuf);
4579 		if (subproc_status(gettext("brand-specific predetach"),
4580 		    status, B_FALSE) != ZONE_SUBPROC_OK) {
4581 			return (Z_ERR);
4582 		}
4583 	}
4584 
4585 	if (execute && grab_lock_file(target_zone, &lockfd) != Z_OK) {
4586 		zerror(gettext("another %s may have an operation in progress."),
4587 		    "zoneadm");
4588 		zonecfg_fini_handle(handle);
4589 		return (Z_ERR);
4590 	}
4591 
4592 	if ((err = zonecfg_get_detach_info(handle, B_TRUE)) != Z_OK) {
4593 		errno = err;
4594 		zperror(gettext("getting the detach information failed"),
4595 		    B_TRUE);
4596 		goto done;
4597 	}
4598 
4599 	if ((err = zonecfg_detach_save(handle, (execute ? 0 : ZONE_DRY_RUN)))
4600 	    != Z_OK) {
4601 		errno = err;
4602 		zperror(gettext("saving the detach manifest failed"), B_TRUE);
4603 		goto done;
4604 	}
4605 
4606 	/*
4607 	 * Set the zone state back to configured unless we are running with the
4608 	 * no-execute option.
4609 	 */
4610 	if (execute && (err = zone_set_state(target_zone,
4611 	    ZONE_STATE_CONFIGURED)) != Z_OK) {
4612 		errno = err;
4613 		zperror(gettext("could not reset state"), B_TRUE);
4614 	}
4615 
4616 done:
4617 	zonecfg_fini_handle(handle);
4618 	if (execute)
4619 		release_lock_file(lockfd);
4620 
4621 	return ((err == Z_OK) ? Z_OK : Z_ERR);
4622 }
4623 
4624 /*
4625  * During attach we go through and fix up the /dev entries for the zone
4626  * we are attaching.  In order to regenerate /dev with the correct devices,
4627  * the old /dev will be removed, the zone readied (which generates a new
4628  * /dev) then halted, then we use the info from the manifest to update
4629  * the modes, owners, etc. on the new /dev.
4630  */
4631 static int
4632 dev_fix(zone_dochandle_t handle)
4633 {
4634 	int			res;
4635 	int			err;
4636 	int			status;
4637 	struct zone_devpermtab	devtab;
4638 	zone_cmd_arg_t		zarg;
4639 	char			devpath[MAXPATHLEN];
4640 				/* 6: "exec " and " " */
4641 	char			cmdbuf[sizeof (RMCOMMAND) + MAXPATHLEN + 6];
4642 
4643 	if ((res = zonecfg_get_zonepath(handle, devpath, sizeof (devpath)))
4644 	    != Z_OK)
4645 		return (res);
4646 
4647 	if (strlcat(devpath, "/dev", sizeof (devpath)) >= sizeof (devpath))
4648 		return (Z_TOO_BIG);
4649 
4650 	/*
4651 	 * "exec" the command so that the returned status is that of
4652 	 * RMCOMMAND and not the shell.
4653 	 */
4654 	(void) snprintf(cmdbuf, sizeof (cmdbuf), EXEC_PREFIX RMCOMMAND " %s",
4655 	    devpath);
4656 	status = do_subproc(cmdbuf);
4657 	if ((err = subproc_status(RMCOMMAND, status, B_TRUE)) !=
4658 	    ZONE_SUBPROC_OK) {
4659 		(void) fprintf(stderr,
4660 		    gettext("could not remove existing /dev\n"));
4661 		return (Z_ERR);
4662 	}
4663 
4664 	/* In order to ready the zone, it must be in the installed state */
4665 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
4666 		errno = err;
4667 		zperror(gettext("could not reset state"), B_TRUE);
4668 		return (Z_ERR);
4669 	}
4670 
4671 	/* We have to ready the zone to regen the dev tree */
4672 	zarg.cmd = Z_READY;
4673 	if (call_zoneadmd(target_zone, &zarg) != 0) {
4674 		zerror(gettext("call to %s failed"), "zoneadmd");
4675 		/* attempt to restore zone to configured state */
4676 		(void) zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
4677 		return (Z_ERR);
4678 	}
4679 
4680 	zarg.cmd = Z_HALT;
4681 	if (call_zoneadmd(target_zone, &zarg) != 0) {
4682 		zerror(gettext("call to %s failed"), "zoneadmd");
4683 		/* attempt to restore zone to configured state */
4684 		(void) zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
4685 		return (Z_ERR);
4686 	}
4687 
4688 	/* attempt to restore zone to configured state */
4689 	(void) zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
4690 
4691 	if (zonecfg_setdevperment(handle) != Z_OK) {
4692 		(void) fprintf(stderr,
4693 		    gettext("unable to enumerate device entries\n"));
4694 		return (Z_ERR);
4695 	}
4696 
4697 	while (zonecfg_getdevperment(handle, &devtab) == Z_OK) {
4698 		int err;
4699 
4700 		if ((err = zonecfg_devperms_apply(handle,
4701 		    devtab.zone_devperm_name, devtab.zone_devperm_uid,
4702 		    devtab.zone_devperm_gid, devtab.zone_devperm_mode,
4703 		    devtab.zone_devperm_acl)) != Z_OK && err != Z_INVAL)
4704 			(void) fprintf(stderr, gettext("error updating device "
4705 			    "%s: %s\n"), devtab.zone_devperm_name,
4706 			    zonecfg_strerror(err));
4707 
4708 		free(devtab.zone_devperm_acl);
4709 	}
4710 
4711 	(void) zonecfg_enddevperment(handle);
4712 
4713 	return (Z_OK);
4714 }
4715 
4716 /*
4717  * Validate attaching a zone but don't actually do the work.  The zone
4718  * does not have to exist, so there is some complexity getting a new zone
4719  * configuration set up so that we can perform the validation.  This is
4720  * handled within zonecfg_attach_manifest() which returns two handles; one
4721  * for the the full configuration to validate (rem_handle) and the other
4722  * (local_handle) containing only the zone configuration derived from the
4723  * manifest.
4724  */
4725 static int
4726 dryrun_attach(char *manifest_path, char *argv[])
4727 {
4728 	int fd;
4729 	int err;
4730 	int res;
4731 	zone_dochandle_t local_handle;
4732 	zone_dochandle_t rem_handle = NULL;
4733 
4734 	if (strcmp(manifest_path, "-") == 0) {
4735 		fd = 0;
4736 	} else if ((fd = open(manifest_path, O_RDONLY)) < 0) {
4737 		zperror(gettext("could not open manifest path"), B_FALSE);
4738 		return (Z_ERR);
4739 	}
4740 
4741 	if ((local_handle = zonecfg_init_handle()) == NULL) {
4742 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4743 		res = Z_ERR;
4744 		goto done;
4745 	}
4746 
4747 	if ((rem_handle = zonecfg_init_handle()) == NULL) {
4748 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4749 		res = Z_ERR;
4750 		goto done;
4751 	}
4752 
4753 	if ((err = zonecfg_attach_manifest(fd, local_handle, rem_handle))
4754 	    != Z_OK) {
4755 		res = Z_ERR;
4756 
4757 		if (err == Z_INVALID_DOCUMENT) {
4758 			struct stat st;
4759 			char buf[6];
4760 
4761 			if (strcmp(manifest_path, "-") == 0) {
4762 				zerror(gettext("Input is not a valid XML "
4763 				    "file"));
4764 				goto done;
4765 			}
4766 
4767 			if (fstat(fd, &st) == -1 || !S_ISREG(st.st_mode)) {
4768 				zerror(gettext("%s is not an XML file"),
4769 				    manifest_path);
4770 				goto done;
4771 			}
4772 
4773 			bzero(buf, sizeof (buf));
4774 			(void) lseek(fd, 0L, SEEK_SET);
4775 			if (read(fd, buf, sizeof (buf) - 1) < 0 ||
4776 			    strncmp(buf, "<?xml", 5) != 0)
4777 				zerror(gettext("%s is not an XML file"),
4778 				    manifest_path);
4779 			else
4780 				zerror(gettext("Cannot attach to an earlier "
4781 				    "release of the operating system"));
4782 		} else {
4783 			zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4784 		}
4785 		goto done;
4786 	}
4787 
4788 	/*
4789 	 * Retrieve remote handle brand type and determine whether it is
4790 	 * native or not.
4791 	 */
4792 	if (zonecfg_get_brand(rem_handle, target_brand, sizeof (target_brand))
4793 	    != Z_OK) {
4794 		zerror(gettext("missing or invalid brand"));
4795 		exit(Z_ERR);
4796 	}
4797 	is_native_zone = (strcmp(target_brand, NATIVE_BRAND_NAME) == 0);
4798 	is_cluster_zone =
4799 	    (strcmp(target_brand, CLUSTER_BRAND_NAME) == 0);
4800 
4801 	res = verify_handle(CMD_ATTACH, local_handle, argv);
4802 
4803 	/* Get the detach information for the locally defined zone. */
4804 	if ((err = zonecfg_get_detach_info(local_handle, B_FALSE)) != Z_OK) {
4805 		errno = err;
4806 		zperror(gettext("getting the attach information failed"),
4807 		    B_TRUE);
4808 		res = Z_ERR;
4809 	} else {
4810 		/* sw_cmp prints error msgs as necessary */
4811 		if (sw_cmp(local_handle, rem_handle, SW_CMP_NONE) != Z_OK)
4812 			res = Z_ERR;
4813 	}
4814 
4815 done:
4816 	if (strcmp(manifest_path, "-") != 0)
4817 		(void) close(fd);
4818 
4819 	zonecfg_fini_handle(local_handle);
4820 	zonecfg_fini_handle(rem_handle);
4821 
4822 	return ((res == Z_OK) ? Z_OK : Z_ERR);
4823 }
4824 
4825 /*
4826  * Attempt to generate the information we need to make the zone look like
4827  * it was properly detached by using the pkg information contained within
4828  * the zone itself.
4829  *
4830  * We will perform a dry-run detach within the zone to generate the xml file.
4831  * To do this we need to be able to get a handle on the zone so we can see
4832  * how it is configured.  In order to get a handle, we need a copy of the
4833  * zone configuration within the zone.  Since the zone's configuration is
4834  * not available within the zone itself, we need to temporarily copy it into
4835  * the zone.
4836  *
4837  * The sequence of actions we are doing is this:
4838  *	[set zone state to installed]
4839  *	[mount zone]
4840  *	zlogin {zone} </etc/zones/{zone}.xml 'cat >/etc/zones/{zone}.xml'
4841  *	zlogin {zone} 'zoneadm -z {zone} detach -n' >{zonepath}/SUNWdetached.xml
4842  *	zlogin {zone} 'rm -f /etc/zones/{zone}.xml'
4843  *	[unmount zone]
4844  *	[set zone state to configured]
4845  *
4846  * The successful result of this function is that we will have a
4847  * SUNWdetached.xml file in the zonepath and we can use that to attach the zone.
4848  */
4849 static boolean_t
4850 gen_detach_info(char *zonepath)
4851 {
4852 	int		status;
4853 	boolean_t	mounted = B_FALSE;
4854 	boolean_t	res = B_FALSE;
4855 	char		cmdbuf[2 * MAXPATHLEN];
4856 
4857 	/*
4858 	 * The zone has to be installed to mount and zlogin.  Temporarily set
4859 	 * the state to 'installed'.
4860 	 */
4861 	if (zone_set_state(target_zone, ZONE_STATE_INSTALLED) != Z_OK)
4862 		return (B_FALSE);
4863 
4864 	/* Mount the zone so we can zlogin. */
4865 	if (mount_func(0, NULL) != Z_OK)
4866 		goto cleanup;
4867 	mounted = B_TRUE;
4868 
4869 	/*
4870 	 * We need to copy the zones xml configuration file into the
4871 	 * zone so we can get a handle for the zone while running inside
4872 	 * the zone.
4873 	 */
4874 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/sbin/zlogin -S %s "
4875 	    "</etc/zones/%s.xml '/usr/bin/cat >/etc/zones/%s.xml'",
4876 	    target_zone, target_zone, target_zone) >= sizeof (cmdbuf))
4877 		goto cleanup;
4878 
4879 	status = do_subproc_interactive(cmdbuf);
4880 	if (subproc_status("copy", status, B_TRUE) != ZONE_SUBPROC_OK)
4881 		goto cleanup;
4882 
4883 	/* Now run the detach command within the mounted zone. */
4884 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/sbin/zlogin -S %s "
4885 	    "'/usr/sbin/zoneadm -z %s detach -n' >%s/SUNWdetached.xml",
4886 	    target_zone, target_zone, zonepath) >= sizeof (cmdbuf))
4887 		goto cleanup;
4888 
4889 	status = do_subproc_interactive(cmdbuf);
4890 	if (subproc_status("detach", status, B_TRUE) != ZONE_SUBPROC_OK)
4891 		goto cleanup;
4892 
4893 	res = B_TRUE;
4894 
4895 cleanup:
4896 	/* Cleanup from the previous actions. */
4897 	if (mounted) {
4898 		if (snprintf(cmdbuf, sizeof (cmdbuf),
4899 		    "/usr/sbin/zlogin -S %s '/usr/bin/rm -f /etc/zones/%s.xml'",
4900 		    target_zone, target_zone) >= sizeof (cmdbuf)) {
4901 			res = B_FALSE;
4902 		} else {
4903 			status = do_subproc_interactive(cmdbuf);
4904 			if (subproc_status("rm", status, B_TRUE)
4905 			    != ZONE_SUBPROC_OK)
4906 				res = B_FALSE;
4907 		}
4908 
4909 		if (unmount_func(0, NULL) != Z_OK)
4910 			res =  B_FALSE;
4911 	}
4912 
4913 	if (zone_set_state(target_zone, ZONE_STATE_CONFIGURED) != Z_OK)
4914 		res = B_FALSE;
4915 
4916 	return (res);
4917 }
4918 
4919 /*
4920  * The zone needs to be updated so set it up for the update and initiate the
4921  * update within the scratch zone.  First set the state to incomplete so we can
4922  * force-mount the zone for the update operation.  We pass the -U option to the
4923  * mount so that the scratch zone is mounted without the zone's /etc and /var
4924  * being lofs mounted back into the scratch zone root.  This is done by
4925  * overloading the bootbuf string in the zone_cmd_arg_t to pass -U as an option
4926  * to the mount cmd.
4927  */
4928 static int
4929 attach_update(zone_dochandle_t handle, char *zonepath)
4930 {
4931 	int err;
4932 	int update_res;
4933 	int status;
4934 	zone_cmd_arg_t zarg;
4935 	FILE *fp;
4936 	struct zone_fstab fstab;
4937 	char cmdbuf[(4 * MAXPATHLEN) + 20];
4938 
4939 	if ((err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE))
4940 	    != Z_OK) {
4941 		errno = err;
4942 		zperror(gettext("could not set state"), B_TRUE);
4943 		return (Z_ERR);
4944 	}
4945 
4946 	zarg.cmd = Z_FORCEMOUNT;
4947 	(void) strlcpy(zarg.bootbuf, "-U",  sizeof (zarg.bootbuf));
4948 	if (call_zoneadmd(target_zone, &zarg) != 0) {
4949 		zerror(gettext("could not mount zone"));
4950 
4951 		/* We reset the state since the zone wasn't modified yet. */
4952 		if ((err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED))
4953 		    != Z_OK) {
4954 			errno = err;
4955 			zperror(gettext("could not reset state"), B_TRUE);
4956 		}
4957 		return (Z_ERR);
4958 	}
4959 
4960 	/*
4961 	 * Move data files generated by sw_up_to_date() into the scratch
4962 	 * zone's /tmp.
4963 	 */
4964 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec /usr/bin/mv "
4965 	    "%s/pkg_add %s/pkg_rm %s/lu/tmp",
4966 	    zonepath, zonepath, zonepath);
4967 
4968 	status = do_subproc_interactive(cmdbuf);
4969 	if (subproc_status("mv", status, B_TRUE) != ZONE_SUBPROC_OK) {
4970 		zperror(gettext("could not mv data files"), B_FALSE);
4971 		goto fail;
4972 	}
4973 
4974 	/*
4975 	 * Save list of inherit-pkg-dirs into zone.  Since the file is in
4976 	 * /tmp we don't have to worry about deleting it.
4977 	 */
4978 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "%s/lu/tmp/inherited",
4979 	    zonepath);
4980 	if ((fp = fopen(cmdbuf, "w")) == NULL) {
4981 		zperror(gettext("could not save inherit-pkg-dirs"), B_FALSE);
4982 		goto fail;
4983 	}
4984 	if (zonecfg_setipdent(handle) != Z_OK) {
4985 		zperror(gettext("could not enumerate inherit-pkg-dirs"),
4986 		    B_TRUE);
4987 		goto fail;
4988 	}
4989 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
4990 		if (fprintf(fp, "%s\n", fstab.zone_fs_dir) < 0) {
4991 			zperror(gettext("could not save inherit-pkg-dirs"),
4992 			    B_FALSE);
4993 			(void) fclose(fp);
4994 			goto fail;
4995 		}
4996 	}
4997 	(void) zonecfg_endipdent(handle);
4998 	if (fclose(fp) != 0) {
4999 		zperror(gettext("could not save inherit-pkg-dirs"), B_FALSE);
5000 		goto fail;
5001 	}
5002 
5003 	/* run the updater inside the scratch zone */
5004 	(void) snprintf(cmdbuf, sizeof (cmdbuf),
5005 	    "exec /usr/sbin/zlogin -S %s "
5006 	    "/usr/lib/brand/native/attach_update %s", target_zone, target_zone);
5007 
5008 	update_res = Z_OK;
5009 	status = do_subproc_interactive(cmdbuf);
5010 	if (subproc_status("attach_update", status, B_TRUE)
5011 	    != ZONE_SUBPROC_OK) {
5012 		zerror(gettext("could not update zone"));
5013 		update_res = Z_ERR;
5014 	}
5015 
5016 	zarg.cmd = Z_UNMOUNT;
5017 	if (call_zoneadmd(target_zone, &zarg) != 0) {
5018 		zerror(gettext("could not unmount zone"));
5019 		return (Z_ERR);
5020 	}
5021 
5022 	/*
5023 	 * If the update script within the scratch zone failed for some reason
5024 	 * we will now leave the zone in the incomplete state since we no
5025 	 * longer know the state of the files within the zonepath.
5026 	 */
5027 	if (update_res == Z_ERR)
5028 		return (Z_ERR);
5029 
5030 	zonecfg_rm_detached(handle, B_FALSE);
5031 
5032 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
5033 		errno = err;
5034 		zperror(gettext("could not set state"), B_TRUE);
5035 		return (Z_ERR);
5036 	}
5037 
5038 	return (Z_OK);
5039 
5040 fail:
5041 	zarg.cmd = Z_UNMOUNT;
5042 	if (call_zoneadmd(target_zone, &zarg) != 0)
5043 		zerror(gettext("could not unmount zone"));
5044 
5045 	/* We reset the state since the zone wasn't modified yet. */
5046 	if ((err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED))
5047 	    != Z_OK) {
5048 		errno = err;
5049 		zperror(gettext("could not reset state"), B_TRUE);
5050 	}
5051 
5052 	return (Z_ERR);
5053 }
5054 
5055 /* ARGSUSED */
5056 static void
5057 sigcleanup(int sig)
5058 {
5059 	attach_interupted = B_TRUE;
5060 }
5061 
5062 
5063 static int
5064 attach_func(int argc, char *argv[])
5065 {
5066 	int lockfd;
5067 	int err, arg;
5068 	boolean_t force = B_FALSE;
5069 	zone_dochandle_t handle;
5070 	zone_dochandle_t athandle = NULL;
5071 	char zonepath[MAXPATHLEN];
5072 	char brand[MAXNAMELEN], atbrand[MAXNAMELEN];
5073 	char cmdbuf[MAXPATHLEN];
5074 	boolean_t execute = B_TRUE;
5075 	boolean_t retried = B_FALSE;
5076 	boolean_t update = B_FALSE;
5077 	char *manifest_path;
5078 	brand_handle_t bh = NULL;
5079 
5080 	if (zonecfg_in_alt_root()) {
5081 		zerror(gettext("cannot attach zone in alternate root"));
5082 		return (Z_ERR);
5083 	}
5084 
5085 	optind = 0;
5086 	if ((arg = getopt(argc, argv, "?Fn:u")) != EOF) {
5087 		switch (arg) {
5088 		case '?':
5089 			sub_usage(SHELP_ATTACH, CMD_ATTACH);
5090 			return (optopt == '?' ? Z_OK : Z_USAGE);
5091 		case 'F':
5092 			force = B_TRUE;
5093 			break;
5094 		case 'n':
5095 			execute = B_FALSE;
5096 			manifest_path = optarg;
5097 			break;
5098 		case 'u':
5099 			update = B_TRUE;
5100 			break;
5101 		default:
5102 			sub_usage(SHELP_ATTACH, CMD_ATTACH);
5103 			return (Z_USAGE);
5104 		}
5105 	}
5106 
5107 	/* dry-run and update flags are mutually exclusive */
5108 	if (!execute && update) {
5109 		zerror(gettext("-n and -u flags are mutually exclusive"));
5110 		return (Z_ERR);
5111 	}
5112 
5113 	/*
5114 	 * If the no-execute option was specified, we need to branch down
5115 	 * a completely different path since there is no zone required to be
5116 	 * configured for this option.
5117 	 */
5118 	if (!execute)
5119 		return (dryrun_attach(manifest_path, argv));
5120 
5121 	if (sanity_check(target_zone, CMD_ATTACH, B_FALSE, B_TRUE, B_FALSE)
5122 	    != Z_OK)
5123 		return (Z_ERR);
5124 	if (verify_details(CMD_ATTACH, argv) != Z_OK)
5125 		return (Z_ERR);
5126 
5127 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
5128 	    != Z_OK) {
5129 		errno = err;
5130 		zperror2(target_zone, gettext("could not get zone path"));
5131 		return (Z_ERR);
5132 	}
5133 
5134 	if ((handle = zonecfg_init_handle()) == NULL) {
5135 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
5136 		return (Z_ERR);
5137 	}
5138 
5139 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
5140 		errno = err;
5141 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
5142 		zonecfg_fini_handle(handle);
5143 		return (Z_ERR);
5144 	}
5145 
5146 	/* Fetch the postattach hook from the brand configuration.  */
5147 	if ((bh = brand_open(target_brand)) == NULL) {
5148 		zerror(gettext("missing or invalid brand"));
5149 		return (Z_ERR);
5150 	}
5151 
5152 	(void) strcpy(cmdbuf, EXEC_PREFIX);
5153 	if (brand_get_postattach(bh, target_zone, zonepath, cmdbuf + EXEC_LEN,
5154 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL) != 0) {
5155 		zerror("invalid brand configuration: missing postattach "
5156 		    "resource");
5157 		brand_close(bh);
5158 		return (Z_ERR);
5159 	}
5160 	brand_close(bh);
5161 
5162 	/* If we have a brand postattach hook and the force flag, append it. */
5163 	if (strlen(cmdbuf) > EXEC_LEN && force) {
5164 		if (addopt(cmdbuf, 0, "-F", sizeof (cmdbuf)) != Z_OK) {
5165 			zerror("Postattach command line too long");
5166 			return (Z_ERR);
5167 		}
5168 	}
5169 
5170 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
5171 		zerror(gettext("another %s may have an operation in progress."),
5172 		    "zoneadm");
5173 		zonecfg_fini_handle(handle);
5174 		return (Z_ERR);
5175 	}
5176 
5177 	if (force)
5178 		goto forced;
5179 
5180 	if ((athandle = zonecfg_init_handle()) == NULL) {
5181 		zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
5182 		goto done;
5183 	}
5184 
5185 retry:
5186 	if ((err = zonecfg_get_attach_handle(zonepath, target_zone, B_TRUE,
5187 	    athandle)) != Z_OK) {
5188 		if (err == Z_NO_ZONE) {
5189 			/*
5190 			 * Zone was not detached.  Try to fall back to getting
5191 			 * the needed information from within the zone.
5192 			 * However, we can only try to generate the attach
5193 			 * information for native branded zones, so fail if the
5194 			 * zone is not native.
5195 			 */
5196 			if (!is_native_zone) {
5197 				zerror(gettext("Not a detached zone."));
5198 				goto done;
5199 			}
5200 
5201 			if (!retried) {
5202 				zerror(gettext("The zone was not properly "
5203 				    "detached.\n\tAttempting to attach "
5204 				    "anyway."));
5205 				if (gen_detach_info(zonepath)) {
5206 					retried = B_TRUE;
5207 					goto retry;
5208 				}
5209 			}
5210 			zerror(gettext("Cannot generate the information "
5211 			    "needed to attach this zone."));
5212 		} else if (err == Z_INVALID_DOCUMENT) {
5213 			zerror(gettext("Cannot attach to an earlier release "
5214 			    "of the operating system"));
5215 		} else {
5216 			zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
5217 		}
5218 		goto done;
5219 	}
5220 
5221 	/* Get the detach information for the locally defined zone. */
5222 	if ((err = zonecfg_get_detach_info(handle, B_FALSE)) != Z_OK) {
5223 		errno = err;
5224 		zperror(gettext("getting the attach information failed"),
5225 		    B_TRUE);
5226 		goto done;
5227 	}
5228 
5229 	/*
5230 	 * Ensure that the detached and locally defined zones are both of
5231 	 * the same brand.
5232 	 */
5233 	if ((zonecfg_get_brand(handle, brand, sizeof (brand)) != 0) ||
5234 	    (zonecfg_get_brand(athandle, atbrand, sizeof (atbrand)) != 0)) {
5235 		err = Z_ERR;
5236 		zerror(gettext("missing or invalid brand"));
5237 		goto done;
5238 	}
5239 
5240 	if (strcmp(atbrand, brand) != NULL) {
5241 		err = Z_ERR;
5242 		zerror(gettext("Trying to attach a '%s' zone to a '%s' "
5243 		    "configuration."), atbrand, brand);
5244 		goto done;
5245 	}
5246 
5247 	/*
5248 	 * If we're doing an update on attach, and the zone does need to be
5249 	 * updated, then run the update.
5250 	 */
5251 	if (update) {
5252 		char fname[MAXPATHLEN];
5253 
5254 		(void) sigset(SIGINT, sigcleanup);
5255 
5256 		if ((err = sw_up_to_date(handle, athandle, zonepath)) != Z_OK) {
5257 			if (err != Z_FATAL && !attach_interupted) {
5258 				err = Z_FATAL;
5259 				err = attach_update(handle, zonepath);
5260 			}
5261 			if (!attach_interupted || err == Z_OK)
5262 				goto done;
5263 		}
5264 
5265 		(void) sigset(SIGINT, SIG_DFL);
5266 
5267 		/* clean up data files left behind by sw_up_to_date() */
5268 		(void) snprintf(fname, sizeof (fname), "%s/pkg_add", zonepath);
5269 		(void) unlink(fname);
5270 		(void) snprintf(fname, sizeof (fname), "%s/pkg_rm", zonepath);
5271 		(void) unlink(fname);
5272 
5273 		if (attach_interupted) {
5274 			err = Z_FATAL;
5275 			goto done;
5276 		}
5277 
5278 	} else {
5279 		/* sw_cmp prints error msgs as necessary */
5280 		if ((err = sw_cmp(handle, athandle, SW_CMP_NONE)) != Z_OK)
5281 			goto done;
5282 
5283 		if ((err = dev_fix(athandle)) != Z_OK)
5284 			goto done;
5285 	}
5286 
5287 forced:
5288 
5289 	zonecfg_rm_detached(handle, force);
5290 
5291 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
5292 		errno = err;
5293 		zperror(gettext("could not reset state"), B_TRUE);
5294 	}
5295 
5296 done:
5297 	zonecfg_fini_handle(handle);
5298 	release_lock_file(lockfd);
5299 	if (athandle != NULL)
5300 		zonecfg_fini_handle(athandle);
5301 
5302 	/* If we have a brand postattach hook, run it. */
5303 	if (err == Z_OK && strlen(cmdbuf) > EXEC_LEN) {
5304 		int status;
5305 
5306 		status = do_subproc(cmdbuf);
5307 		if (subproc_status(gettext("brand-specific postattach"),
5308 		    status, B_FALSE) != ZONE_SUBPROC_OK) {
5309 			if ((err = zone_set_state(target_zone,
5310 			    ZONE_STATE_CONFIGURED)) != Z_OK) {
5311 				errno = err;
5312 				zperror(gettext("could not reset state"),
5313 				    B_TRUE);
5314 			}
5315 			return (Z_ERR);
5316 		}
5317 	}
5318 
5319 	return ((err == Z_OK) ? Z_OK : Z_ERR);
5320 }
5321 
5322 /*
5323  * On input, TRUE => yes, FALSE => no.
5324  * On return, TRUE => 1, FALSE => 0, could not ask => -1.
5325  */
5326 
5327 static int
5328 ask_yesno(boolean_t default_answer, const char *question)
5329 {
5330 	char line[64];	/* should be large enough to answer yes or no */
5331 
5332 	if (!isatty(STDIN_FILENO))
5333 		return (-1);
5334 	for (;;) {
5335 		(void) printf("%s (%s)? ", question,
5336 		    default_answer ? "[y]/n" : "y/[n]");
5337 		if (fgets(line, sizeof (line), stdin) == NULL ||
5338 		    line[0] == '\n')
5339 			return (default_answer ? 1 : 0);
5340 		if (tolower(line[0]) == 'y')
5341 			return (1);
5342 		if (tolower(line[0]) == 'n')
5343 			return (0);
5344 	}
5345 }
5346 
5347 static int
5348 uninstall_func(int argc, char *argv[])
5349 {
5350 	char line[ZONENAME_MAX + 128];	/* Enough for "Are you sure ..." */
5351 	char rootpath[MAXPATHLEN], zonepath[MAXPATHLEN];
5352 	char cmdbuf[MAXPATHLEN];
5353 	boolean_t force = B_FALSE;
5354 	int lockfd, answer;
5355 	int err, arg;
5356 	brand_handle_t bh = NULL;
5357 
5358 	if (zonecfg_in_alt_root()) {
5359 		zerror(gettext("cannot uninstall zone in alternate root"));
5360 		return (Z_ERR);
5361 	}
5362 
5363 	optind = 0;
5364 	while ((arg = getopt(argc, argv, "?F")) != EOF) {
5365 		switch (arg) {
5366 		case '?':
5367 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5368 			return (optopt == '?' ? Z_OK : Z_USAGE);
5369 		case 'F':
5370 			force = B_TRUE;
5371 			break;
5372 		default:
5373 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5374 			return (Z_USAGE);
5375 		}
5376 	}
5377 	if (argc > optind) {
5378 		sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5379 		return (Z_USAGE);
5380 	}
5381 
5382 	if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE, B_FALSE)
5383 	    != Z_OK)
5384 		return (Z_ERR);
5385 
5386 	/*
5387 	 * Invoke brand-specific handler.
5388 	 */
5389 	if (invoke_brand_handler(CMD_UNINSTALL, argv) != Z_OK)
5390 		return (Z_ERR);
5391 
5392 	if (!force) {
5393 		(void) snprintf(line, sizeof (line),
5394 		    gettext("Are you sure you want to %s zone %s"),
5395 		    cmd_to_str(CMD_UNINSTALL), target_zone);
5396 		if ((answer = ask_yesno(B_FALSE, line)) == 0) {
5397 			return (Z_OK);
5398 		} else if (answer == -1) {
5399 			zerror(gettext("Input not from terminal and -F "
5400 			    "not specified: %s not done."),
5401 			    cmd_to_str(CMD_UNINSTALL));
5402 			return (Z_ERR);
5403 		}
5404 	}
5405 
5406 	if ((err = zone_get_zonepath(target_zone, zonepath,
5407 	    sizeof (zonepath))) != Z_OK) {
5408 		errno = err;
5409 		zperror2(target_zone, gettext("could not get zone path"));
5410 		return (Z_ERR);
5411 	}
5412 	if ((err = zone_get_rootpath(target_zone, rootpath,
5413 	    sizeof (rootpath))) != Z_OK) {
5414 		errno = err;
5415 		zperror2(target_zone, gettext("could not get root path"));
5416 		return (Z_ERR);
5417 	}
5418 
5419 	/*
5420 	 * If there seems to be a zoneadmd running for this zone, call it
5421 	 * to tell it that an uninstall is happening; if all goes well it
5422 	 * will then shut itself down.
5423 	 */
5424 	if (ping_zoneadmd(target_zone) == Z_OK) {
5425 		zone_cmd_arg_t zarg;
5426 		zarg.cmd = Z_NOTE_UNINSTALLING;
5427 		/* we don't care too much if this fails... just plow on */
5428 		(void) call_zoneadmd(target_zone, &zarg);
5429 	}
5430 
5431 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
5432 		zerror(gettext("another %s may have an operation in progress."),
5433 		    "zoneadm");
5434 		return (Z_ERR);
5435 	}
5436 
5437 	/* Don't uninstall the zone if anything is mounted there */
5438 	err = zonecfg_find_mounts(rootpath, NULL, NULL);
5439 	if (err) {
5440 		zerror(gettext("These file systems are mounted on "
5441 		    "subdirectories of %s.\n"), rootpath);
5442 		(void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
5443 		return (Z_ERR);
5444 	}
5445 
5446 	/* Fetch the uninstall hook from the brand configuration.  */
5447 	if ((bh = brand_open(target_brand)) == NULL) {
5448 		zerror(gettext("missing or invalid brand"));
5449 		return (Z_ERR);
5450 	}
5451 
5452 	(void) strcpy(cmdbuf, EXEC_PREFIX);
5453 	if (brand_get_preuninstall(bh, target_zone, zonepath,
5454 	    cmdbuf + EXEC_LEN, sizeof (cmdbuf) - EXEC_LEN, 0, NULL)
5455 	    != 0) {
5456 		zerror("invalid brand configuration: missing preuninstall "
5457 		    "resource");
5458 		brand_close(bh);
5459 		return (Z_ERR);
5460 	}
5461 	brand_close(bh);
5462 
5463 	if (strlen(cmdbuf) > EXEC_LEN) {
5464 		int status;
5465 
5466 		/* If we have the force flag, append it. */
5467 		if (force && addopt(cmdbuf, 0, "-F", sizeof (cmdbuf)) != Z_OK) {
5468 			zerror("Preuninstall command line too long");
5469 			return (Z_ERR);
5470 		}
5471 
5472 		status = do_subproc(cmdbuf);
5473 		if (subproc_status(gettext("brand-specific preuninstall"),
5474 		    status, B_FALSE) != ZONE_SUBPROC_OK) {
5475 			return (Z_ERR);
5476 		}
5477 	}
5478 
5479 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
5480 	if (err != Z_OK) {
5481 		errno = err;
5482 		zperror2(target_zone, gettext("could not set state"));
5483 		goto bad;
5484 	}
5485 
5486 	if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
5487 		errno = err;
5488 		zperror2(target_zone, gettext("cleaning up zonepath failed"));
5489 		goto bad;
5490 	}
5491 
5492 	err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
5493 	if (err != Z_OK) {
5494 		errno = err;
5495 		zperror2(target_zone, gettext("could not reset state"));
5496 	}
5497 bad:
5498 	release_lock_file(lockfd);
5499 	return (err);
5500 }
5501 
5502 /* ARGSUSED */
5503 static int
5504 mount_func(int argc, char *argv[])
5505 {
5506 	zone_cmd_arg_t zarg;
5507 	boolean_t force = B_FALSE;
5508 	int arg;
5509 
5510 	/*
5511 	 * The only supported subargument to the "mount" subcommand is
5512 	 * "-f", which forces us to mount a zone in the INCOMPLETE state.
5513 	 */
5514 	optind = 0;
5515 	if ((arg = getopt(argc, argv, "f")) != EOF) {
5516 		switch (arg) {
5517 		case 'f':
5518 			force = B_TRUE;
5519 			break;
5520 		default:
5521 			return (Z_USAGE);
5522 		}
5523 	}
5524 	if (argc > optind)
5525 		return (Z_USAGE);
5526 
5527 	if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE, force)
5528 	    != Z_OK)
5529 		return (Z_ERR);
5530 	if (verify_details(CMD_MOUNT, argv) != Z_OK)
5531 		return (Z_ERR);
5532 
5533 	zarg.cmd = force ? Z_FORCEMOUNT : Z_MOUNT;
5534 	zarg.bootbuf[0] = '\0';
5535 	if (call_zoneadmd(target_zone, &zarg) != 0) {
5536 		zerror(gettext("call to %s failed"), "zoneadmd");
5537 		return (Z_ERR);
5538 	}
5539 	return (Z_OK);
5540 }
5541 
5542 /* ARGSUSED */
5543 static int
5544 unmount_func(int argc, char *argv[])
5545 {
5546 	zone_cmd_arg_t zarg;
5547 
5548 	if (argc > 0)
5549 		return (Z_USAGE);
5550 	if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE, B_FALSE)
5551 	    != Z_OK)
5552 		return (Z_ERR);
5553 
5554 	zarg.cmd = Z_UNMOUNT;
5555 	if (call_zoneadmd(target_zone, &zarg) != 0) {
5556 		zerror(gettext("call to %s failed"), "zoneadmd");
5557 		return (Z_ERR);
5558 	}
5559 	return (Z_OK);
5560 }
5561 
5562 static int
5563 mark_func(int argc, char *argv[])
5564 {
5565 	int err, lockfd;
5566 
5567 	if (argc != 1 || strcmp(argv[0], "incomplete") != 0)
5568 		return (Z_USAGE);
5569 	if (sanity_check(target_zone, CMD_MARK, B_FALSE, B_FALSE, B_FALSE)
5570 	    != Z_OK)
5571 		return (Z_ERR);
5572 
5573 	/*
5574 	 * Invoke brand-specific handler.
5575 	 */
5576 	if (invoke_brand_handler(CMD_MARK, argv) != Z_OK)
5577 		return (Z_ERR);
5578 
5579 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
5580 		zerror(gettext("another %s may have an operation in progress."),
5581 		    "zoneadm");
5582 		return (Z_ERR);
5583 	}
5584 
5585 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
5586 	if (err != Z_OK) {
5587 		errno = err;
5588 		zperror2(target_zone, gettext("could not set state"));
5589 	}
5590 	release_lock_file(lockfd);
5591 
5592 	return (err);
5593 }
5594 
5595 /*
5596  * Check what scheduling class we're running under and print a warning if
5597  * we're not using FSS.
5598  */
5599 static int
5600 check_sched_fss(zone_dochandle_t handle)
5601 {
5602 	char class_name[PC_CLNMSZ];
5603 
5604 	if (zonecfg_get_dflt_sched_class(handle, class_name,
5605 	    sizeof (class_name)) != Z_OK) {
5606 		zerror(gettext("WARNING: unable to determine the zone's "
5607 		    "scheduling class"));
5608 	} else if (strcmp("FSS", class_name) != 0) {
5609 		zerror(gettext("WARNING: The zone.cpu-shares rctl is set but\n"
5610 		    "FSS is not the default scheduling class for this zone.  "
5611 		    "FSS will be\nused for processes in the zone but to get "
5612 		    "the full benefit of FSS,\nit should be the default "
5613 		    "scheduling class.  See dispadmin(1M) for\nmore details."));
5614 		return (Z_SYSTEM);
5615 	}
5616 
5617 	return (Z_OK);
5618 }
5619 
5620 static int
5621 check_cpu_shares_sched(zone_dochandle_t handle)
5622 {
5623 	int err;
5624 	int res = Z_OK;
5625 	struct zone_rctltab rctl;
5626 
5627 	if ((err = zonecfg_setrctlent(handle)) != Z_OK) {
5628 		errno = err;
5629 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5630 		return (err);
5631 	}
5632 
5633 	while (zonecfg_getrctlent(handle, &rctl) == Z_OK) {
5634 		if (strcmp(rctl.zone_rctl_name, "zone.cpu-shares") == 0) {
5635 			if (check_sched_fss(handle) != Z_OK)
5636 				res = Z_SYSTEM;
5637 			break;
5638 		}
5639 	}
5640 
5641 	(void) zonecfg_endrctlent(handle);
5642 
5643 	return (res);
5644 }
5645 
5646 /*
5647  * Check if there is a mix of processes running in different pools within the
5648  * zone.  This is currently only going to be called for the global zone from
5649  * apply_func but that could be generalized in the future.
5650  */
5651 static boolean_t
5652 mixed_pools(zoneid_t zoneid)
5653 {
5654 	DIR *dirp;
5655 	dirent_t *dent;
5656 	boolean_t mixed = B_FALSE;
5657 	boolean_t poolid_set = B_FALSE;
5658 	poolid_t last_poolid = 0;
5659 
5660 	if ((dirp = opendir("/proc")) == NULL) {
5661 		zerror(gettext("could not open /proc"));
5662 		return (B_FALSE);
5663 	}
5664 
5665 	while ((dent = readdir(dirp)) != NULL) {
5666 		int procfd;
5667 		psinfo_t ps;
5668 		char procpath[MAXPATHLEN];
5669 
5670 		if (dent->d_name[0] == '.')
5671 			continue;
5672 
5673 		(void) snprintf(procpath, sizeof (procpath), "/proc/%s/psinfo",
5674 		    dent->d_name);
5675 
5676 		if ((procfd = open(procpath, O_RDONLY)) == -1)
5677 			continue;
5678 
5679 		if (read(procfd, &ps, sizeof (ps)) == sizeof (psinfo_t)) {
5680 			/* skip processes in other zones and system processes */
5681 			if (zoneid != ps.pr_zoneid || ps.pr_flag & SSYS) {
5682 				(void) close(procfd);
5683 				continue;
5684 			}
5685 
5686 			if (poolid_set) {
5687 				if (ps.pr_poolid != last_poolid)
5688 					mixed = B_TRUE;
5689 			} else {
5690 				last_poolid = ps.pr_poolid;
5691 				poolid_set = B_TRUE;
5692 			}
5693 		}
5694 
5695 		(void) close(procfd);
5696 
5697 		if (mixed)
5698 			break;
5699 	}
5700 
5701 	(void) closedir(dirp);
5702 
5703 	return (mixed);
5704 }
5705 
5706 /*
5707  * Check if a persistent or temporary pool is configured for the zone.
5708  * This is currently only going to be called for the global zone from
5709  * apply_func but that could be generalized in the future.
5710  */
5711 static boolean_t
5712 pool_configured(zone_dochandle_t handle)
5713 {
5714 	int err1, err2;
5715 	struct zone_psettab pset_tab;
5716 	char poolname[MAXPATHLEN];
5717 
5718 	err1 = zonecfg_lookup_pset(handle, &pset_tab);
5719 	err2 = zonecfg_get_pool(handle, poolname, sizeof (poolname));
5720 
5721 	if (err1 == Z_NO_ENTRY &&
5722 	    (err2 == Z_NO_ENTRY || (err2 == Z_OK && strlen(poolname) == 0)))
5723 		return (B_FALSE);
5724 
5725 	return (B_TRUE);
5726 }
5727 
5728 /*
5729  * This is an undocumented interface which is currently only used to apply
5730  * the global zone resource management settings when the system boots.
5731  * This function does not yet properly handle updating a running system so
5732  * any projects running in the zone would be trashed if this function
5733  * were to run after the zone had booted.  It also does not reset any
5734  * rctl settings that were removed from zonecfg.  There is still work to be
5735  * done before we can properly support dynamically updating the resource
5736  * management settings for a running zone (global or non-global).  Thus, this
5737  * functionality is undocumented for now.
5738  */
5739 /* ARGSUSED */
5740 static int
5741 apply_func(int argc, char *argv[])
5742 {
5743 	int err;
5744 	int res = Z_OK;
5745 	priv_set_t *privset;
5746 	zoneid_t zoneid;
5747 	zone_dochandle_t handle;
5748 	struct zone_mcaptab mcap;
5749 	char pool_err[128];
5750 
5751 	zoneid = getzoneid();
5752 
5753 	if (zonecfg_in_alt_root() || zoneid != GLOBAL_ZONEID ||
5754 	    target_zone == NULL || strcmp(target_zone, GLOBAL_ZONENAME) != 0)
5755 		return (usage(B_FALSE));
5756 
5757 	if ((privset = priv_allocset()) == NULL) {
5758 		zerror(gettext("%s failed"), "priv_allocset");
5759 		return (Z_ERR);
5760 	}
5761 
5762 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
5763 		zerror(gettext("%s failed"), "getppriv");
5764 		priv_freeset(privset);
5765 		return (Z_ERR);
5766 	}
5767 
5768 	if (priv_isfullset(privset) == B_FALSE) {
5769 		(void) usage(B_FALSE);
5770 		priv_freeset(privset);
5771 		return (Z_ERR);
5772 	}
5773 	priv_freeset(privset);
5774 
5775 	if ((handle = zonecfg_init_handle()) == NULL) {
5776 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5777 		return (Z_ERR);
5778 	}
5779 
5780 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
5781 		errno = err;
5782 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5783 		zonecfg_fini_handle(handle);
5784 		return (Z_ERR);
5785 	}
5786 
5787 	/* specific error msgs are printed within apply_rctls */
5788 	if ((err = zonecfg_apply_rctls(target_zone, handle)) != Z_OK) {
5789 		errno = err;
5790 		zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5791 		res = Z_ERR;
5792 	}
5793 
5794 	if ((err = check_cpu_shares_sched(handle)) != Z_OK)
5795 		res = Z_ERR;
5796 
5797 	if (pool_configured(handle)) {
5798 		if (mixed_pools(zoneid)) {
5799 			zerror(gettext("Zone is using multiple resource "
5800 			    "pools.  The pool\nconfiguration cannot be "
5801 			    "applied without rebooting."));
5802 			res = Z_ERR;
5803 		} else {
5804 
5805 			/*
5806 			 * The next two blocks of code attempt to set up
5807 			 * temporary pools as well as persistent pools.  In
5808 			 * both cases we call the functions unconditionally.
5809 			 * Within each funtion the code will check if the zone
5810 			 * is actually configured for a temporary pool or
5811 			 * persistent pool and just return if there is nothing
5812 			 * to do.
5813 			 */
5814 			if ((err = zonecfg_bind_tmp_pool(handle, zoneid,
5815 			    pool_err, sizeof (pool_err))) != Z_OK) {
5816 				if (err == Z_POOL || err == Z_POOL_CREATE ||
5817 				    err == Z_POOL_BIND)
5818 					zerror("%s: %s", zonecfg_strerror(err),
5819 					    pool_err);
5820 				else
5821 					zerror(gettext("could not bind zone to "
5822 					    "temporary pool: %s"),
5823 					    zonecfg_strerror(err));
5824 				res = Z_ERR;
5825 			}
5826 
5827 			if ((err = zonecfg_bind_pool(handle, zoneid, pool_err,
5828 			    sizeof (pool_err))) != Z_OK) {
5829 				if (err == Z_POOL || err == Z_POOL_BIND)
5830 					zerror("%s: %s", zonecfg_strerror(err),
5831 					    pool_err);
5832 				else
5833 					zerror("%s", zonecfg_strerror(err));
5834 			}
5835 		}
5836 	}
5837 
5838 	/*
5839 	 * If a memory cap is configured, set the cap in the kernel using
5840 	 * zone_setattr() and make sure the rcapd SMF service is enabled.
5841 	 */
5842 	if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
5843 		uint64_t num;
5844 		char smf_err[128];
5845 
5846 		num = (uint64_t)strtoll(mcap.zone_physmem_cap, NULL, 10);
5847 		if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
5848 			zerror(gettext("could not set zone memory cap"));
5849 			res = Z_ERR;
5850 		}
5851 
5852 		if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
5853 			zerror(gettext("enabling system/rcap service failed: "
5854 			    "%s"), smf_err);
5855 			res = Z_ERR;
5856 		}
5857 	}
5858 
5859 	zonecfg_fini_handle(handle);
5860 
5861 	return (res);
5862 }
5863 
5864 static int
5865 help_func(int argc, char *argv[])
5866 {
5867 	int arg, cmd_num;
5868 
5869 	if (argc == 0) {
5870 		(void) usage(B_TRUE);
5871 		return (Z_OK);
5872 	}
5873 	optind = 0;
5874 	if ((arg = getopt(argc, argv, "?")) != EOF) {
5875 		switch (arg) {
5876 		case '?':
5877 			sub_usage(SHELP_HELP, CMD_HELP);
5878 			return (optopt == '?' ? Z_OK : Z_USAGE);
5879 		default:
5880 			sub_usage(SHELP_HELP, CMD_HELP);
5881 			return (Z_USAGE);
5882 		}
5883 	}
5884 	while (optind < argc) {
5885 		/* Private commands have NULL short_usage; omit them */
5886 		if ((cmd_num = cmd_match(argv[optind])) < 0 ||
5887 		    cmdtab[cmd_num].short_usage == NULL) {
5888 			sub_usage(SHELP_HELP, CMD_HELP);
5889 			return (Z_USAGE);
5890 		}
5891 		sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
5892 		optind++;
5893 	}
5894 	return (Z_OK);
5895 }
5896 
5897 /*
5898  * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
5899  */
5900 
5901 static int
5902 cmd_match(char *cmd)
5903 {
5904 	int i;
5905 
5906 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
5907 		/* return only if there is an exact match */
5908 		if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
5909 			return (cmdtab[i].cmd_num);
5910 	}
5911 	return (-1);
5912 }
5913 
5914 static int
5915 parse_and_run(int argc, char *argv[])
5916 {
5917 	int i = cmd_match(argv[0]);
5918 
5919 	if (i < 0)
5920 		return (usage(B_FALSE));
5921 	return (cmdtab[i].handler(argc - 1, &(argv[1])));
5922 }
5923 
5924 static char *
5925 get_execbasename(char *execfullname)
5926 {
5927 	char *last_slash, *execbasename;
5928 
5929 	/* guard against '/' at end of command invocation */
5930 	for (;;) {
5931 		last_slash = strrchr(execfullname, '/');
5932 		if (last_slash == NULL) {
5933 			execbasename = execfullname;
5934 			break;
5935 		} else {
5936 			execbasename = last_slash + 1;
5937 			if (*execbasename == '\0') {
5938 				*last_slash = '\0';
5939 				continue;
5940 			}
5941 			break;
5942 		}
5943 	}
5944 	return (execbasename);
5945 }
5946 
5947 int
5948 main(int argc, char **argv)
5949 {
5950 	int arg;
5951 	zoneid_t zid;
5952 	struct stat st;
5953 	char *zone_lock_env;
5954 	int err;
5955 
5956 	if ((locale = setlocale(LC_ALL, "")) == NULL)
5957 		locale = "C";
5958 	(void) textdomain(TEXT_DOMAIN);
5959 	setbuf(stdout, NULL);
5960 	(void) sigset(SIGHUP, SIG_IGN);
5961 	execname = get_execbasename(argv[0]);
5962 	target_zone = NULL;
5963 	if (chdir("/") != 0) {
5964 		zerror(gettext("could not change directory to /."));
5965 		exit(Z_ERR);
5966 	}
5967 
5968 	if (init_zfs() != Z_OK)
5969 		exit(Z_ERR);
5970 
5971 	while ((arg = getopt(argc, argv, "?u:z:R:")) != EOF) {
5972 		switch (arg) {
5973 		case '?':
5974 			return (usage(B_TRUE));
5975 		case 'u':
5976 			target_uuid = optarg;
5977 			break;
5978 		case 'z':
5979 			target_zone = optarg;
5980 			break;
5981 		case 'R':	/* private option for admin/install use */
5982 			if (*optarg != '/') {
5983 				zerror(gettext("root path must be absolute."));
5984 				exit(Z_ERR);
5985 			}
5986 			if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
5987 				zerror(
5988 				    gettext("root path must be a directory."));
5989 				exit(Z_ERR);
5990 			}
5991 			zonecfg_set_root(optarg);
5992 			break;
5993 		default:
5994 			return (usage(B_FALSE));
5995 		}
5996 	}
5997 
5998 	if (optind >= argc)
5999 		return (usage(B_FALSE));
6000 
6001 	if (target_uuid != NULL && *target_uuid != '\0') {
6002 		uuid_t uuid;
6003 		static char newtarget[ZONENAME_MAX];
6004 
6005 		if (uuid_parse(target_uuid, uuid) == -1) {
6006 			zerror(gettext("illegal UUID value specified"));
6007 			exit(Z_ERR);
6008 		}
6009 		if (zonecfg_get_name_by_uuid(uuid, newtarget,
6010 		    sizeof (newtarget)) == Z_OK)
6011 			target_zone = newtarget;
6012 	}
6013 
6014 	if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
6015 		errno = Z_NO_ZONE;
6016 		zperror(target_zone, B_TRUE);
6017 		exit(Z_ERR);
6018 	}
6019 
6020 	/*
6021 	 * See if we have inherited the right to manipulate this zone from
6022 	 * a zoneadm instance in our ancestry.  If so, set zone_lock_cnt to
6023 	 * indicate it.  If not, make that explicit in our environment.
6024 	 */
6025 	zone_lock_env = getenv(LOCK_ENV_VAR);
6026 	if (zone_lock_env == NULL) {
6027 		if (putenv(zoneadm_lock_not_held) != 0) {
6028 			zperror(target_zone, B_TRUE);
6029 			exit(Z_ERR);
6030 		}
6031 	} else {
6032 		zoneadm_is_nested = B_TRUE;
6033 		if (atoi(zone_lock_env) == 1)
6034 			zone_lock_cnt = 1;
6035 	}
6036 
6037 	/*
6038 	 * If we are going to be operating on a single zone, retrieve its
6039 	 * brand type and determine whether it is native or not.
6040 	 */
6041 	if ((target_zone != NULL) &&
6042 	    (strcmp(target_zone, GLOBAL_ZONENAME) != NULL)) {
6043 		if (zone_get_brand(target_zone, target_brand,
6044 		    sizeof (target_brand)) != Z_OK) {
6045 			zerror(gettext("missing or invalid brand"));
6046 			exit(Z_ERR);
6047 		}
6048 		is_native_zone = (strcmp(target_brand, NATIVE_BRAND_NAME) == 0);
6049 		is_cluster_zone =
6050 		    (strcmp(target_brand, CLUSTER_BRAND_NAME) == 0);
6051 	}
6052 
6053 	err = parse_and_run(argc - optind, &argv[optind]);
6054 
6055 	return (err);
6056 }
6057