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