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