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