xref: /illumos-gate/usr/src/cmd/zoneadm/zoneadm.c (revision 865e09a46b399ddcc8d4eec1badf3470c04f0f9a)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 /*
31  * zoneadm is a command interpreter for zone administration.  It is all in
32  * C (i.e., no lex/yacc), and all the argument passing is argc/argv based.
33  * main() calls parse_and_run() which calls cmd_match(), then invokes the
34  * appropriate command's handler function.  The rest of the program is the
35  * handler functions and their helper functions.
36  *
37  * Some of the helper functions are used largely to simplify I18N: reducing
38  * the need for translation notes.  This is particularly true of many of
39  * the zerror() calls: doing e.g. zerror(gettext("%s failed"), "foo") rather
40  * than zerror(gettext("foo failed")) with a translation note indicating
41  * that "foo" need not be translated.
42  */
43 
44 #include <stdio.h>
45 #include <errno.h>
46 #include <unistd.h>
47 #include <signal.h>
48 #include <stdarg.h>
49 #include <ctype.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <wait.h>
53 #include <zone.h>
54 #include <priv.h>
55 #include <locale.h>
56 #include <libintl.h>
57 #include <libzonecfg.h>
58 #include <bsm/adt.h>
59 #include <sys/utsname.h>
60 #include <sys/param.h>
61 #include <sys/types.h>
62 #include <sys/stat.h>
63 #include <sys/statvfs.h>
64 #include <assert.h>
65 #include <sys/sockio.h>
66 #include <sys/mntent.h>
67 #include <limits.h>
68 #include <libzfs.h>
69 
70 #include <fcntl.h>
71 #include <door.h>
72 #include <macros.h>
73 #include <libgen.h>
74 #include <fnmatch.h>
75 
76 #include <pool.h>
77 #include <sys/pool.h>
78 
79 #define	MAXARGS	8
80 
81 /* Reflects kernel zone entries */
82 typedef struct zone_entry {
83 	zoneid_t	zid;
84 	char		zname[ZONENAME_MAX];
85 	char		*zstate_str;
86 	zone_state_t	zstate_num;
87 	char		zroot[MAXPATHLEN];
88 } zone_entry_t;
89 
90 static zone_entry_t *zents;
91 static size_t nzents;
92 
93 #if !defined(TEXT_DOMAIN)		/* should be defined by cc -D */
94 #define	TEXT_DOMAIN	"SYS_TEST"	/* Use this only if it wasn't */
95 #endif
96 
97 #define	Z_ERR	1
98 #define	Z_USAGE	2
99 
100 /* 0755 is the default directory mode. */
101 #define	DEFAULT_DIR_MODE \
102 	(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
103 
104 #define	CMD_HELP	0
105 #define	CMD_BOOT	1
106 #define	CMD_HALT	2
107 #define	CMD_READY	3
108 #define	CMD_REBOOT	4
109 #define	CMD_LIST	5
110 #define	CMD_VERIFY	6
111 #define	CMD_INSTALL	7
112 #define	CMD_UNINSTALL	8
113 #define	CMD_MOUNT	9
114 #define	CMD_UNMOUNT	10
115 #define	CMD_CLONE	11
116 #define	CMD_MOVE	12
117 
118 #define	CMD_MIN		CMD_HELP
119 #define	CMD_MAX		CMD_MOVE
120 
121 #define	SINGLE_USER_RETRY	30
122 
123 struct cmd {
124 	uint_t	cmd_num;				/* command number */
125 	char	*cmd_name;				/* command name */
126 	char	*short_usage;				/* short form help */
127 	int	(*handler)(int argc, char *argv[]);	/* function to call */
128 
129 };
130 
131 #define	SHELP_HELP	"help"
132 #define	SHELP_BOOT	"boot [-s]"
133 #define	SHELP_HALT	"halt"
134 #define	SHELP_READY	"ready"
135 #define	SHELP_REBOOT	"reboot"
136 #define	SHELP_LIST	"list [-cipv]"
137 #define	SHELP_VERIFY	"verify"
138 #define	SHELP_INSTALL	"install"
139 #define	SHELP_UNINSTALL	"uninstall [-F]"
140 #define	SHELP_CLONE	"clone [-m method] zonename"
141 #define	SHELP_MOVE	"move zonepath"
142 
143 static int help_func(int argc, char *argv[]);
144 static int ready_func(int argc, char *argv[]);
145 static int boot_func(int argc, char *argv[]);
146 static int halt_func(int argc, char *argv[]);
147 static int reboot_func(int argc, char *argv[]);
148 static int list_func(int argc, char *argv[]);
149 static int verify_func(int argc, char *argv[]);
150 static int install_func(int argc, char *argv[]);
151 static int uninstall_func(int argc, char *argv[]);
152 static int mount_func(int argc, char *argv[]);
153 static int unmount_func(int argc, char *argv[]);
154 static int clone_func(int argc, char *argv[]);
155 static int move_func(int argc, char *argv[]);
156 static int sanity_check(char *zone, int cmd_num, boolean_t running,
157     boolean_t unsafe_when_running);
158 static int cmd_match(char *cmd);
159 static int verify_details(int);
160 
161 static struct cmd cmdtab[] = {
162 	{ CMD_HELP,		"help",		SHELP_HELP,	help_func },
163 	{ CMD_BOOT,		"boot",		SHELP_BOOT,	boot_func },
164 	{ CMD_HALT,		"halt",		SHELP_HALT,	halt_func },
165 	{ CMD_READY,		"ready",	SHELP_READY,	ready_func },
166 	{ CMD_REBOOT,		"reboot",	SHELP_REBOOT,	reboot_func },
167 	{ CMD_LIST,		"list",		SHELP_LIST,	list_func },
168 	{ CMD_VERIFY,		"verify",	SHELP_VERIFY,	verify_func },
169 	{ CMD_INSTALL,		"install",	SHELP_INSTALL,	install_func },
170 	{ CMD_UNINSTALL,	"uninstall",	SHELP_UNINSTALL,
171 	    uninstall_func },
172 	/* mount and unmount are private commands for admin/install */
173 	{ CMD_MOUNT,		"mount",	NULL,		mount_func },
174 	{ CMD_UNMOUNT,		"unmount",	NULL,		unmount_func },
175 	{ CMD_CLONE,		"clone",	SHELP_CLONE,	clone_func },
176 	{ CMD_MOVE,		"move",		SHELP_MOVE,	move_func }
177 };
178 
179 /* global variables */
180 
181 /* set early in main(), never modified thereafter, used all over the place */
182 static char *execname;
183 static char *target_zone;
184 static char *locale;
185 
186 /* used in do_subproc() and signal handler */
187 static volatile boolean_t child_killed;
188 
189 static char *
190 cmd_to_str(int cmd_num)
191 {
192 	assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
193 	return (cmdtab[cmd_num].cmd_name);
194 }
195 
196 /* This is a separate function because of gettext() wrapping. */
197 static char *
198 long_help(int cmd_num)
199 {
200 	assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
201 	switch (cmd_num) {
202 		case CMD_HELP:
203 			return (gettext("Print usage message."));
204 		case CMD_BOOT:
205 			return (gettext("Activates (boots) specified zone.  "
206 			    "The -s flag can be used\n\tto boot the zone in "
207 			    "the single-user state."));
208 		case CMD_HALT:
209 			return (gettext("Halts specified zone, bypassing "
210 			    "shutdown scripts and removing runtime\n\t"
211 			    "resources of the zone."));
212 		case CMD_READY:
213 			return (gettext("Prepares a zone for running "
214 			    "applications but does not start any user\n\t"
215 			    "processes in the zone."));
216 		case CMD_REBOOT:
217 			return (gettext("Restarts the zone (equivalent to a "
218 			    "halt / boot sequence).\n\tFails if the zone is "
219 			    "not active."));
220 		case CMD_LIST:
221 			return (gettext("Lists the current zones, or a "
222 			    "specific zone if indicated.  By default,\n\tall "
223 			    "running zones are listed, though this can be "
224 			    "expanded to all\n\tinstalled zones with the -i "
225 			    "option or all configured zones with the\n\t-c "
226 			    "option.  When used with the general -z <zone> "
227 			    "option, lists only the\n\tspecified zone, but "
228 			    "lists it regardless of its state, and the -i "
229 			    "and -c\n\toptions are disallowed.  The -v option "
230 			    "can be used to display verbose\n\tinformation: "
231 			    "zone name, id, current state, root directory and "
232 			    "options.\n\tThe -p option can be used to request "
233 			    "machine-parsable output.  The -v\n\tand -p "
234 			    "options are mutually exclusive.  If neither -v "
235 			    "nor -p is used,\n\tjust the zone name is "
236 			    "listed."));
237 		case CMD_VERIFY:
238 			return (gettext("Check to make sure the configuration "
239 			    "can safely be instantiated\n\ton the machine: "
240 			    "physical network interfaces exist, etc."));
241 		case CMD_INSTALL:
242 			return (gettext("Install the configuration on to the "
243 			    "system."));
244 		case CMD_UNINSTALL:
245 			return (gettext("Uninstall the configuration from the "
246 			    "system.  The -F flag can be used\n\tto force the "
247 			    "action."));
248 		case CMD_CLONE:
249 			return (gettext("Clone the installation of another "
250 			    "zone."));
251 		case CMD_MOVE:
252 			return (gettext("Move the zone to a new zonepath."));
253 		default:
254 			return ("");
255 	}
256 	/* NOTREACHED */
257 	return (NULL);
258 }
259 
260 /*
261  * Called with explicit B_TRUE when help is explicitly requested, B_FALSE for
262  * unexpected errors.
263  */
264 
265 static int
266 usage(boolean_t explicit)
267 {
268 	int i;
269 	FILE *fd = explicit ? stdout : stderr;
270 
271 	(void) fprintf(fd, "%s:\t%s help\n", gettext("usage"), execname);
272 	(void) fprintf(fd, "\t%s [-z <zone>] list\n", execname);
273 	(void) fprintf(fd, "\t%s -z <zone> <%s>\n", execname,
274 	    gettext("subcommand"));
275 	(void) fprintf(fd, "\n%s:\n\n", gettext("Subcommands"));
276 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
277 		if (cmdtab[i].short_usage == NULL)
278 			continue;
279 		(void) fprintf(fd, "%s\n", cmdtab[i].short_usage);
280 		if (explicit)
281 			(void) fprintf(fd, "\t%s\n\n", long_help(i));
282 	}
283 	if (!explicit)
284 		(void) fputs("\n", fd);
285 	return (Z_USAGE);
286 }
287 
288 static void
289 sub_usage(char *short_usage, int cmd_num)
290 {
291 	(void) fprintf(stderr, "%s:\t%s\n", gettext("usage"), short_usage);
292 	(void) fprintf(stderr, "\t%s\n", long_help(cmd_num));
293 }
294 
295 /*
296  * zperror() is like perror(3c) except that this also prints the executable
297  * name at the start of the message, and takes a boolean indicating whether
298  * to call libc'c strerror() or that from libzonecfg.
299  */
300 
301 static void
302 zperror(const char *str, boolean_t zonecfg_error)
303 {
304 	(void) fprintf(stderr, "%s: %s: %s\n", execname, str,
305 	    zonecfg_error ? zonecfg_strerror(errno) : strerror(errno));
306 }
307 
308 /*
309  * zperror2() is very similar to zperror() above, except it also prints a
310  * supplied zone name after the executable.
311  *
312  * All current consumers of this function want libzonecfg's strerror() rather
313  * than libc's; if this ever changes, this function can be made more generic
314  * like zperror() above.
315  */
316 
317 static void
318 zperror2(const char *zone, const char *str)
319 {
320 	(void) fprintf(stderr, "%s: %s: %s: %s\n", execname, zone, str,
321 	    zonecfg_strerror(errno));
322 }
323 
324 /* PRINTFLIKE1 */
325 static void
326 zerror(const char *fmt, ...)
327 {
328 	va_list alist;
329 
330 	va_start(alist, fmt);
331 	(void) fprintf(stderr, "%s: ", execname);
332 	if (target_zone != NULL)
333 		(void) fprintf(stderr, "zone '%s': ", target_zone);
334 	(void) vfprintf(stderr, fmt, alist);
335 	(void) fprintf(stderr, "\n");
336 	va_end(alist);
337 }
338 
339 static void *
340 safe_calloc(size_t nelem, size_t elsize)
341 {
342 	void *r = calloc(nelem, elsize);
343 
344 	if (r == NULL) {
345 		zerror(gettext("failed to allocate %lu bytes: %s"),
346 		    (ulong_t)nelem * elsize, strerror(errno));
347 		exit(Z_ERR);
348 	}
349 	return (r);
350 }
351 
352 static void
353 zone_print(zone_entry_t *zent, boolean_t verbose, boolean_t parsable)
354 {
355 	static boolean_t firsttime = B_TRUE;
356 
357 	assert(!(verbose && parsable));
358 	if (firsttime && verbose) {
359 		firsttime = B_FALSE;
360 		(void) printf("%*s %-16s %-14s %-30s\n", ZONEID_WIDTH, "ID",
361 		    "NAME", "STATUS", "PATH");
362 	}
363 	if (!verbose) {
364 		if (!parsable) {
365 			(void) printf("%s\n", zent->zname);
366 			return;
367 		}
368 		if (zent->zid == ZONE_ID_UNDEFINED)
369 			(void) printf("-");
370 		else
371 			(void) printf("%lu", zent->zid);
372 		(void) printf(":%s:%s:%s\n", zent->zname, zent->zstate_str,
373 		    zent->zroot);
374 		return;
375 	}
376 	if (zent->zstate_str != NULL) {
377 		if (zent->zid == ZONE_ID_UNDEFINED)
378 			(void) printf("%*s", ZONEID_WIDTH, "-");
379 		else
380 			(void) printf("%*lu", ZONEID_WIDTH, zent->zid);
381 		(void) printf(" %-16s %-14s %-30s\n", zent->zname,
382 		    zent->zstate_str, zent->zroot);
383 	}
384 }
385 
386 static int
387 lookup_zone_info(const char *zone_name, zoneid_t zid, zone_entry_t *zent)
388 {
389 	char root[MAXPATHLEN];
390 	int err;
391 
392 	(void) strlcpy(zent->zname, zone_name, sizeof (zent->zname));
393 	(void) strlcpy(zent->zroot, "???", sizeof (zent->zroot));
394 	zent->zstate_str = "???";
395 
396 	zent->zid = zid;
397 
398 	if ((err = zone_get_zonepath(zent->zname, root, sizeof (root))) !=
399 	    Z_OK) {
400 		errno = err;
401 		zperror2(zent->zname, gettext("could not get zone path"));
402 		return (Z_ERR);
403 	}
404 	(void) strlcpy(zent->zroot, root, sizeof (zent->zroot));
405 
406 	if ((err = zone_get_state(zent->zname, &zent->zstate_num)) != Z_OK) {
407 		errno = err;
408 		zperror2(zent->zname, gettext("could not get state"));
409 		return (Z_ERR);
410 	}
411 	zent->zstate_str = zone_state_str(zent->zstate_num);
412 
413 	return (Z_OK);
414 }
415 
416 /*
417  * fetch_zents() calls zone_list(2) to find out how many zones are running
418  * (which is stored in the global nzents), then calls zone_list(2) again
419  * to fetch the list of running zones (stored in the global zents).  This
420  * function may be called multiple times, so if zents is already set, we
421  * return immediately to save work.
422  */
423 
424 static int
425 fetch_zents(void)
426 {
427 	zoneid_t *zids = NULL;
428 	uint_t nzents_saved;
429 	int i, retv;
430 	FILE *fp;
431 	boolean_t inaltroot;
432 	zone_entry_t *zentp;
433 
434 	if (nzents > 0)
435 		return (Z_OK);
436 
437 	if (zone_list(NULL, &nzents) != 0) {
438 		zperror(gettext("failed to get zoneid list"), B_FALSE);
439 		return (Z_ERR);
440 	}
441 
442 again:
443 	if (nzents == 0)
444 		return (Z_OK);
445 
446 	zids = safe_calloc(nzents, sizeof (zoneid_t));
447 	nzents_saved = nzents;
448 
449 	if (zone_list(zids, &nzents) != 0) {
450 		zperror(gettext("failed to get zone list"), B_FALSE);
451 		free(zids);
452 		return (Z_ERR);
453 	}
454 	if (nzents != nzents_saved) {
455 		/* list changed, try again */
456 		free(zids);
457 		goto again;
458 	}
459 
460 	zents = safe_calloc(nzents, sizeof (zone_entry_t));
461 
462 	inaltroot = zonecfg_in_alt_root();
463 	if (inaltroot)
464 		fp = zonecfg_open_scratch("", B_FALSE);
465 	else
466 		fp = NULL;
467 	zentp = zents;
468 	retv = Z_OK;
469 	for (i = 0; i < nzents; i++) {
470 		char name[ZONENAME_MAX];
471 		char altname[ZONENAME_MAX];
472 
473 		if (getzonenamebyid(zids[i], name, sizeof (name)) < 0) {
474 			zperror(gettext("failed to get zone name"), B_FALSE);
475 			retv = Z_ERR;
476 			continue;
477 		}
478 		if (zonecfg_is_scratch(name)) {
479 			/* Ignore scratch zones by default */
480 			if (!inaltroot)
481 				continue;
482 			if (fp == NULL ||
483 			    zonecfg_reverse_scratch(fp, name, altname,
484 			    sizeof (altname), NULL, 0) == -1) {
485 				zerror(gettext("could not resolve scratch "
486 				    "zone %s"), name);
487 				retv = Z_ERR;
488 				continue;
489 			}
490 			(void) strcpy(name, altname);
491 		} else {
492 			/* Ignore non-scratch when in an alternate root */
493 			if (inaltroot && strcmp(name, GLOBAL_ZONENAME) != 0)
494 				continue;
495 		}
496 		if (lookup_zone_info(name, zids[i], zentp) != Z_OK) {
497 			zerror(gettext("failed to get zone data"));
498 			retv = Z_ERR;
499 			continue;
500 		}
501 		zentp++;
502 	}
503 	nzents = zentp - zents;
504 	if (fp != NULL)
505 		zonecfg_close_scratch(fp);
506 
507 	free(zids);
508 	return (retv);
509 }
510 
511 static int
512 zone_print_list(zone_state_t min_state, boolean_t verbose, boolean_t parsable)
513 {
514 	int i;
515 	zone_entry_t zent;
516 	FILE *cookie;
517 	char *name;
518 
519 	/*
520 	 * First get the list of running zones from the kernel and print them.
521 	 * If that is all we need, then return.
522 	 */
523 	if ((i = fetch_zents()) != Z_OK) {
524 		/*
525 		 * No need for error messages; fetch_zents() has already taken
526 		 * care of this.
527 		 */
528 		return (i);
529 	}
530 	for (i = 0; i < nzents; i++)
531 		zone_print(&zents[i], verbose, parsable);
532 	if (min_state >= ZONE_STATE_RUNNING)
533 		return (Z_OK);
534 	/*
535 	 * Next, get the full list of zones from the configuration, skipping
536 	 * any we have already printed.
537 	 */
538 	cookie = setzoneent();
539 	while ((name = getzoneent(cookie)) != NULL) {
540 		for (i = 0; i < nzents; i++) {
541 			if (strcmp(zents[i].zname, name) == 0)
542 				break;
543 		}
544 		if (i < nzents) {
545 			free(name);
546 			continue;
547 		}
548 		if (lookup_zone_info(name, ZONE_ID_UNDEFINED, &zent) != Z_OK) {
549 			free(name);
550 			continue;
551 		}
552 		free(name);
553 		if (zent.zstate_num >= min_state)
554 			zone_print(&zent, verbose, parsable);
555 	}
556 	endzoneent(cookie);
557 	return (Z_OK);
558 }
559 
560 static zone_entry_t *
561 lookup_running_zone(char *str)
562 {
563 	zoneid_t zoneid;
564 	char *cp;
565 	int i;
566 
567 	if (fetch_zents() != Z_OK)
568 		return (NULL);
569 
570 	for (i = 0; i < nzents; i++) {
571 		if (strcmp(str, zents[i].zname) == 0)
572 			return (&zents[i]);
573 	}
574 	errno = 0;
575 	zoneid = strtol(str, &cp, 0);
576 	if (zoneid < MIN_ZONEID || zoneid > MAX_ZONEID ||
577 	    errno != 0 || *cp != '\0')
578 		return (NULL);
579 	for (i = 0; i < nzents; i++) {
580 		if (zoneid == zents[i].zid)
581 			return (&zents[i]);
582 	}
583 	return (NULL);
584 }
585 
586 /*
587  * Check a bit in a mode_t: if on is B_TRUE, that bit should be on; if
588  * B_FALSE, it should be off.  Return B_TRUE if the mode is bad (incorrect).
589  */
590 static boolean_t
591 bad_mode_bit(mode_t mode, mode_t bit, boolean_t on, char *file)
592 {
593 	char *str;
594 
595 	assert(bit == S_IRUSR || bit == S_IWUSR || bit == S_IXUSR ||
596 	    bit == S_IRGRP || bit == S_IWGRP || bit == S_IXGRP ||
597 	    bit == S_IROTH || bit == S_IWOTH || bit == S_IXOTH);
598 	/*
599 	 * TRANSLATION_NOTE
600 	 * The strings below will be used as part of a larger message,
601 	 * either:
602 	 * (file name) must be (owner|group|world) (read|writ|execut)able
603 	 * or
604 	 * (file name) must not be (owner|group|world) (read|writ|execut)able
605 	 */
606 	switch (bit) {
607 	case S_IRUSR:
608 		str = gettext("owner readable");
609 		break;
610 	case S_IWUSR:
611 		str = gettext("owner writable");
612 		break;
613 	case S_IXUSR:
614 		str = gettext("owner executable");
615 		break;
616 	case S_IRGRP:
617 		str = gettext("group readable");
618 		break;
619 	case S_IWGRP:
620 		str = gettext("group writable");
621 		break;
622 	case S_IXGRP:
623 		str = gettext("group executable");
624 		break;
625 	case S_IROTH:
626 		str = gettext("world readable");
627 		break;
628 	case S_IWOTH:
629 		str = gettext("world writable");
630 		break;
631 	case S_IXOTH:
632 		str = gettext("world executable");
633 		break;
634 	}
635 	if ((mode & bit) == (on ? 0 : bit)) {
636 		/*
637 		 * TRANSLATION_NOTE
638 		 * The first parameter below is a file name; the second
639 		 * is one of the "(owner|group|world) (read|writ|execut)able"
640 		 * strings from above.
641 		 */
642 		/*
643 		 * The code below could be simplified but not in a way
644 		 * that would easily translate to non-English locales.
645 		 */
646 		if (on) {
647 			(void) fprintf(stderr, gettext("%s must be %s.\n"),
648 			    file, str);
649 		} else {
650 			(void) fprintf(stderr, gettext("%s must not be %s.\n"),
651 			    file, str);
652 		}
653 		return (B_TRUE);
654 	}
655 	return (B_FALSE);
656 }
657 
658 /*
659  * We want to make sure that no zone has its zone path as a child node
660  * (in the directory sense) of any other.  We do that by comparing this
661  * zone's path to the path of all other (non-global) zones.  The comparison
662  * in each case is simple: add '/' to the end of the path, then do a
663  * strncmp() of the two paths, using the length of the shorter one.
664  */
665 
666 static int
667 crosscheck_zonepaths(char *path)
668 {
669 	char rpath[MAXPATHLEN];		/* resolved path */
670 	char path_copy[MAXPATHLEN];	/* copy of original path */
671 	char rpath_copy[MAXPATHLEN];	/* copy of original rpath */
672 	struct zoneent *ze;
673 	int res, err;
674 	FILE *cookie;
675 
676 	cookie = setzoneent();
677 	while ((ze = getzoneent_private(cookie)) != NULL) {
678 		/* Skip zones which are not installed. */
679 		if (ze->zone_state < ZONE_STATE_INSTALLED) {
680 			free(ze);
681 			continue;
682 		}
683 		/* Skip the global zone and the current target zone. */
684 		if (strcmp(ze->zone_name, GLOBAL_ZONENAME) == 0 ||
685 		    strcmp(ze->zone_name, target_zone) == 0) {
686 			free(ze);
687 			continue;
688 		}
689 		if (strlen(ze->zone_path) == 0) {
690 			/* old index file without path, fall back */
691 			if ((err = zone_get_zonepath(ze->zone_name,
692 			    ze->zone_path, sizeof (ze->zone_path))) != Z_OK) {
693 				errno = err;
694 				zperror2(ze->zone_name,
695 				    gettext("could not get zone path"));
696 				free(ze);
697 				continue;
698 			}
699 		}
700 		(void) snprintf(path_copy, sizeof (path_copy), "%s%s",
701 		    zonecfg_get_root(), ze->zone_path);
702 		res = resolvepath(path_copy, rpath, sizeof (rpath));
703 		if (res == -1) {
704 			if (errno != ENOENT) {
705 				zperror(path_copy, B_FALSE);
706 				free(ze);
707 				return (Z_ERR);
708 			}
709 			(void) printf(gettext("WARNING: zone %s is installed, "
710 			    "but its %s %s does not exist.\n"), ze->zone_name,
711 			    "zonepath", path_copy);
712 			free(ze);
713 			continue;
714 		}
715 		rpath[res] = '\0';
716 		(void) snprintf(path_copy, sizeof (path_copy), "%s/", path);
717 		(void) snprintf(rpath_copy, sizeof (rpath_copy), "%s/", rpath);
718 		if (strncmp(path_copy, rpath_copy,
719 		    min(strlen(path_copy), strlen(rpath_copy))) == 0) {
720 			/*
721 			 * TRANSLATION_NOTE
722 			 * zonepath is a literal that should not be translated.
723 			 */
724 			(void) fprintf(stderr, gettext("%s zonepath (%s) and "
725 			    "%s zonepath (%s) overlap.\n"),
726 			    target_zone, path, ze->zone_name, rpath);
727 			free(ze);
728 			return (Z_ERR);
729 		}
730 		free(ze);
731 	}
732 	endzoneent(cookie);
733 	return (Z_OK);
734 }
735 
736 static int
737 validate_zonepath(char *path, int cmd_num)
738 {
739 	int res;			/* result of last library/system call */
740 	boolean_t err = B_FALSE;	/* have we run into an error? */
741 	struct stat stbuf;
742 	struct statvfs vfsbuf;
743 	char rpath[MAXPATHLEN];		/* resolved path */
744 	char ppath[MAXPATHLEN];		/* parent path */
745 	char rppath[MAXPATHLEN];	/* resolved parent path */
746 	char rootpath[MAXPATHLEN];	/* root path */
747 	zone_state_t state;
748 
749 	if (path[0] != '/') {
750 		(void) fprintf(stderr,
751 		    gettext("%s is not an absolute path.\n"), path);
752 		return (Z_ERR);
753 	}
754 	if ((res = resolvepath(path, rpath, sizeof (rpath))) == -1) {
755 		if ((errno != ENOENT) ||
756 		    (cmd_num != CMD_VERIFY && cmd_num != CMD_INSTALL &&
757 		    cmd_num != CMD_CLONE && cmd_num != CMD_MOVE)) {
758 			zperror(path, B_FALSE);
759 			return (Z_ERR);
760 		}
761 		if (cmd_num == CMD_VERIFY) {
762 			/*
763 			 * TRANSLATION_NOTE
764 			 * zoneadm is a literal that should not be translated.
765 			 */
766 			(void) fprintf(stderr, gettext("WARNING: %s does not "
767 			    "exist, so it could not be verified.\nWhen "
768 			    "'zoneadm %s' is run, '%s' will try to create\n%s, "
769 			    "and '%s' will be tried again,\nbut the '%s' may "
770 			    "fail if:\nthe parent directory of %s is group- or "
771 			    "other-writable\nor\n%s overlaps with any other "
772 			    "installed zones.\n"), path,
773 			    cmd_to_str(CMD_INSTALL), cmd_to_str(CMD_INSTALL),
774 			    path, cmd_to_str(CMD_VERIFY),
775 			    cmd_to_str(CMD_VERIFY), path, path);
776 			return (Z_OK);
777 		}
778 		/*
779 		 * The zonepath is supposed to be mode 700 but its
780 		 * parent(s) 755.  So use 755 on the mkdirp() then
781 		 * chmod() the zonepath itself to 700.
782 		 */
783 		if (mkdirp(path, DEFAULT_DIR_MODE) < 0) {
784 			zperror(path, B_FALSE);
785 			return (Z_ERR);
786 		}
787 		/*
788 		 * If the chmod() fails, report the error, but might
789 		 * as well continue the verify procedure.
790 		 */
791 		if (chmod(path, S_IRWXU) != 0)
792 			zperror(path, B_FALSE);
793 		/*
794 		 * Since the mkdir() succeeded, we should not have to
795 		 * worry about a subsequent ENOENT, thus this should
796 		 * only recurse once.
797 		 */
798 		return (validate_zonepath(path, cmd_num));
799 	}
800 	rpath[res] = '\0';
801 	if (strcmp(path, rpath) != 0) {
802 		errno = Z_RESOLVED_PATH;
803 		zperror(path, B_TRUE);
804 		return (Z_ERR);
805 	}
806 	if ((res = stat(rpath, &stbuf)) != 0) {
807 		zperror(rpath, B_FALSE);
808 		return (Z_ERR);
809 	}
810 	if (!S_ISDIR(stbuf.st_mode)) {
811 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
812 		    rpath);
813 		return (Z_ERR);
814 	}
815 	if ((strcmp(stbuf.st_fstype, MNTTYPE_TMPFS) == 0) ||
816 	    (strcmp(stbuf.st_fstype, MNTTYPE_XMEMFS) == 0)) {
817 		(void) printf(gettext("WARNING: %s is on a temporary "
818 		    "file-system.\n"), rpath);
819 	}
820 	if (crosscheck_zonepaths(rpath) != Z_OK)
821 		return (Z_ERR);
822 	/*
823 	 * Try to collect and report as many minor errors as possible
824 	 * before returning, so the user can learn everything that needs
825 	 * to be fixed up front.
826 	 */
827 	if (stbuf.st_uid != 0) {
828 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
829 		    rpath);
830 		err = B_TRUE;
831 	}
832 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rpath);
833 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rpath);
834 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rpath);
835 	err |= bad_mode_bit(stbuf.st_mode, S_IRGRP, B_FALSE, rpath);
836 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rpath);
837 	err |= bad_mode_bit(stbuf.st_mode, S_IXGRP, B_FALSE, rpath);
838 	err |= bad_mode_bit(stbuf.st_mode, S_IROTH, B_FALSE, rpath);
839 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rpath);
840 	err |= bad_mode_bit(stbuf.st_mode, S_IXOTH, B_FALSE, rpath);
841 
842 	(void) snprintf(ppath, sizeof (ppath), "%s/..", path);
843 	if ((res = resolvepath(ppath, rppath, sizeof (rppath))) == -1) {
844 		zperror(ppath, B_FALSE);
845 		return (Z_ERR);
846 	}
847 	rppath[res] = '\0';
848 	if ((res = stat(rppath, &stbuf)) != 0) {
849 		zperror(rppath, B_FALSE);
850 		return (Z_ERR);
851 	}
852 	/* theoretically impossible */
853 	if (!S_ISDIR(stbuf.st_mode)) {
854 		(void) fprintf(stderr, gettext("%s is not a directory.\n"),
855 		    rppath);
856 		return (Z_ERR);
857 	}
858 	if (stbuf.st_uid != 0) {
859 		(void) fprintf(stderr, gettext("%s is not owned by root.\n"),
860 		    rppath);
861 		err = B_TRUE;
862 	}
863 	err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rppath);
864 	err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rppath);
865 	err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rppath);
866 	err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rppath);
867 	err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rppath);
868 	if (strcmp(rpath, rppath) == 0) {
869 		(void) fprintf(stderr, gettext("%s is its own parent.\n"),
870 		    rppath);
871 		err = B_TRUE;
872 	}
873 
874 	if (statvfs(rpath, &vfsbuf) != 0) {
875 		zperror(rpath, B_FALSE);
876 		return (Z_ERR);
877 	}
878 	if (strcmp(vfsbuf.f_basetype, MNTTYPE_NFS) == 0) {
879 		/*
880 		 * TRANSLATION_NOTE
881 		 * Zonepath and NFS are literals that should not be translated.
882 		 */
883 		(void) fprintf(stderr, gettext("Zonepath %s is on an NFS "
884 		    "mounted file-system.\n"
885 		    "\tA local file-system must be used.\n"), rpath);
886 		return (Z_ERR);
887 	}
888 	if (vfsbuf.f_flag & ST_NOSUID) {
889 		/*
890 		 * TRANSLATION_NOTE
891 		 * Zonepath and nosuid are literals that should not be
892 		 * translated.
893 		 */
894 		(void) fprintf(stderr, gettext("Zonepath %s is on a nosuid "
895 		    "file-system.\n"), rpath);
896 		return (Z_ERR);
897 	}
898 
899 	if ((res = zone_get_state(target_zone, &state)) != Z_OK) {
900 		errno = res;
901 		zperror2(target_zone, gettext("could not get state"));
902 		return (Z_ERR);
903 	}
904 	/*
905 	 * The existence of the root path is only bad in the configured state,
906 	 * as it is *supposed* to be there at the installed and later states.
907 	 * State/command mismatches are caught earlier in verify_details().
908 	 */
909 	if (state == ZONE_STATE_CONFIGURED) {
910 		if (snprintf(rootpath, sizeof (rootpath), "%s/root", rpath) >=
911 		    sizeof (rootpath)) {
912 			/*
913 			 * TRANSLATION_NOTE
914 			 * Zonepath is a literal that should not be translated.
915 			 */
916 			(void) fprintf(stderr,
917 			    gettext("Zonepath %s is too long.\n"), rpath);
918 			return (Z_ERR);
919 		}
920 		if ((res = stat(rootpath, &stbuf)) == 0) {
921 			(void) fprintf(stderr, gettext("Rootpath %s exists; "
922 			    "remove or move aside prior to %s.\n"), rootpath,
923 			    cmd_to_str(CMD_INSTALL));
924 			return (Z_ERR);
925 		}
926 	}
927 
928 	return (err ? Z_ERR : Z_OK);
929 }
930 
931 static void
932 release_lock_file(int lockfd)
933 {
934 	(void) close(lockfd);
935 }
936 
937 static int
938 grab_lock_file(const char *zone_name, int *lockfd)
939 {
940 	char pathbuf[PATH_MAX];
941 	struct flock flock;
942 
943 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s", zonecfg_get_root(),
944 	    ZONES_TMPDIR) >= sizeof (pathbuf)) {
945 		zerror(gettext("alternate root path is too long"));
946 		return (Z_ERR);
947 	}
948 	if (mkdir(pathbuf, S_IRWXU) < 0 && errno != EEXIST) {
949 		zerror(gettext("could not mkdir %s: %s"), pathbuf,
950 		    strerror(errno));
951 		return (Z_ERR);
952 	}
953 	(void) chmod(pathbuf, S_IRWXU);
954 
955 	/*
956 	 * One of these lock files is created for each zone (when needed).
957 	 * The lock files are not cleaned up (except on system reboot),
958 	 * but since there is only one per zone, there is no resource
959 	 * starvation issue.
960 	 */
961 	if (snprintf(pathbuf, sizeof (pathbuf), "%s%s/%s.zoneadm.lock",
962 	    zonecfg_get_root(), ZONES_TMPDIR, zone_name) >= sizeof (pathbuf)) {
963 		zerror(gettext("alternate root path is too long"));
964 		return (Z_ERR);
965 	}
966 	if ((*lockfd = open(pathbuf, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
967 		zerror(gettext("could not open %s: %s"), pathbuf,
968 		    strerror(errno));
969 		return (Z_ERR);
970 	}
971 	/*
972 	 * Lock the file to synchronize with other zoneadmds
973 	 */
974 	flock.l_type = F_WRLCK;
975 	flock.l_whence = SEEK_SET;
976 	flock.l_start = (off_t)0;
977 	flock.l_len = (off_t)0;
978 	if (fcntl(*lockfd, F_SETLKW, &flock) < 0) {
979 		zerror(gettext("unable to lock %s: %s"), pathbuf,
980 		    strerror(errno));
981 		release_lock_file(*lockfd);
982 		return (Z_ERR);
983 	}
984 	return (Z_OK);
985 }
986 
987 static boolean_t
988 get_doorname(const char *zone_name, char *buffer)
989 {
990 	return (snprintf(buffer, PATH_MAX, "%s" ZONE_DOOR_PATH,
991 	    zonecfg_get_root(), zone_name) < PATH_MAX);
992 }
993 
994 /*
995  * system daemons are not audited.  For the global zone, this occurs
996  * "naturally" since init is started with the default audit
997  * characteristics.  Since zoneadmd is a system daemon and it starts
998  * init for a zone, it is necessary to clear out the audit
999  * characteristics inherited from whomever started zoneadmd.  This is
1000  * indicated by the audit id, which is set from the ruid parameter of
1001  * adt_set_user(), below.
1002  */
1003 
1004 static void
1005 prepare_audit_context()
1006 {
1007 	adt_session_data_t	*ah;
1008 	char			*failure = gettext("audit failure: %s");
1009 
1010 	if (adt_start_session(&ah, NULL, 0)) {
1011 		zerror(failure, strerror(errno));
1012 		return;
1013 	}
1014 	if (adt_set_user(ah, ADT_NO_AUDIT, ADT_NO_AUDIT,
1015 	    ADT_NO_AUDIT, ADT_NO_AUDIT, NULL, ADT_NEW)) {
1016 		zerror(failure, strerror(errno));
1017 		(void) adt_end_session(ah);
1018 		return;
1019 	}
1020 	if (adt_set_proc(ah))
1021 		zerror(failure, strerror(errno));
1022 
1023 	(void) adt_end_session(ah);
1024 }
1025 
1026 static int
1027 start_zoneadmd(const char *zone_name)
1028 {
1029 	char doorpath[PATH_MAX];
1030 	pid_t child_pid;
1031 	int error = Z_ERR;
1032 	int doorfd, lockfd;
1033 	struct door_info info;
1034 
1035 	if (!get_doorname(zone_name, doorpath))
1036 		return (Z_ERR);
1037 
1038 	if (grab_lock_file(zone_name, &lockfd) != Z_OK)
1039 		return (Z_ERR);
1040 
1041 	/*
1042 	 * Now that we have the lock, re-confirm that the daemon is
1043 	 * *not* up and working fine.  If it is still down, we have a green
1044 	 * light to start it.
1045 	 */
1046 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1047 		if (errno != ENOENT) {
1048 			zperror(doorpath, B_FALSE);
1049 			goto out;
1050 		}
1051 	} else {
1052 		if (door_info(doorfd, &info) == 0 &&
1053 		    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1054 			error = Z_OK;
1055 			(void) close(doorfd);
1056 			goto out;
1057 		}
1058 		(void) close(doorfd);
1059 	}
1060 
1061 	if ((child_pid = fork()) == -1) {
1062 		zperror(gettext("could not fork"), B_FALSE);
1063 		goto out;
1064 	} else if (child_pid == 0) {
1065 		const char *argv[6], **ap;
1066 
1067 		/* child process */
1068 		prepare_audit_context();
1069 
1070 		ap = argv;
1071 		*ap++ = "zoneadmd";
1072 		*ap++ = "-z";
1073 		*ap++ = zone_name;
1074 		if (zonecfg_in_alt_root()) {
1075 			*ap++ = "-R";
1076 			*ap++ = zonecfg_get_root();
1077 		}
1078 		*ap = NULL;
1079 
1080 		(void) execv("/usr/lib/zones/zoneadmd", (char * const *)argv);
1081 		/*
1082 		 * TRANSLATION_NOTE
1083 		 * zoneadmd is a literal that should not be translated.
1084 		 */
1085 		zperror(gettext("could not exec zoneadmd"), B_FALSE);
1086 		_exit(Z_ERR);
1087 	} else {
1088 		/* parent process */
1089 		pid_t retval;
1090 		int pstatus = 0;
1091 
1092 		do {
1093 			retval = waitpid(child_pid, &pstatus, 0);
1094 		} while (retval != child_pid);
1095 		if (WIFSIGNALED(pstatus) || (WIFEXITED(pstatus) &&
1096 		    WEXITSTATUS(pstatus) != 0)) {
1097 			zerror(gettext("could not start %s"), "zoneadmd");
1098 			goto out;
1099 		}
1100 	}
1101 	error = Z_OK;
1102 out:
1103 	release_lock_file(lockfd);
1104 	return (error);
1105 }
1106 
1107 static int
1108 ping_zoneadmd(const char *zone_name)
1109 {
1110 	char doorpath[PATH_MAX];
1111 	int doorfd;
1112 	struct door_info info;
1113 
1114 	if (!get_doorname(zone_name, doorpath))
1115 		return (Z_ERR);
1116 
1117 	if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1118 		return (Z_ERR);
1119 	}
1120 	if (door_info(doorfd, &info) == 0 &&
1121 	    ((info.di_attributes & DOOR_REVOKED) == 0)) {
1122 		(void) close(doorfd);
1123 		return (Z_OK);
1124 	}
1125 	(void) close(doorfd);
1126 	return (Z_ERR);
1127 }
1128 
1129 static int
1130 call_zoneadmd(const char *zone_name, zone_cmd_arg_t *arg)
1131 {
1132 	char doorpath[PATH_MAX];
1133 	int doorfd, result;
1134 	door_arg_t darg;
1135 
1136 	zoneid_t zoneid;
1137 	uint64_t uniqid = 0;
1138 
1139 	zone_cmd_rval_t *rvalp;
1140 	size_t rlen;
1141 	char *cp, *errbuf;
1142 
1143 	rlen = getpagesize();
1144 	if ((rvalp = malloc(rlen)) == NULL) {
1145 		zerror(gettext("failed to allocate %lu bytes: %s"), rlen,
1146 		    strerror(errno));
1147 		return (-1);
1148 	}
1149 
1150 	if ((zoneid = getzoneidbyname(zone_name)) != ZONE_ID_UNDEFINED) {
1151 		(void) zone_getattr(zoneid, ZONE_ATTR_UNIQID, &uniqid,
1152 		    sizeof (uniqid));
1153 	}
1154 	arg->uniqid = uniqid;
1155 	(void) strlcpy(arg->locale, locale, sizeof (arg->locale));
1156 	if (!get_doorname(zone_name, doorpath)) {
1157 		zerror(gettext("alternate root path is too long"));
1158 		free(rvalp);
1159 		return (-1);
1160 	}
1161 
1162 	/*
1163 	 * Loop trying to start zoneadmd; if something goes seriously
1164 	 * wrong we break out and fail.
1165 	 */
1166 	for (;;) {
1167 		if (start_zoneadmd(zone_name) != Z_OK)
1168 			break;
1169 
1170 		if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
1171 			zperror(gettext("failed to open zone door"), B_FALSE);
1172 			break;
1173 		}
1174 
1175 		darg.data_ptr = (char *)arg;
1176 		darg.data_size = sizeof (*arg);
1177 		darg.desc_ptr = NULL;
1178 		darg.desc_num = 0;
1179 		darg.rbuf = (char *)rvalp;
1180 		darg.rsize = rlen;
1181 		if (door_call(doorfd, &darg) != 0) {
1182 			(void) close(doorfd);
1183 			/*
1184 			 * We'll get EBADF if the door has been revoked.
1185 			 */
1186 			if (errno != EBADF) {
1187 				zperror(gettext("door_call failed"), B_FALSE);
1188 				break;
1189 			}
1190 			continue;	/* take another lap */
1191 		}
1192 		(void) close(doorfd);
1193 
1194 		if (darg.data_size == 0) {
1195 			/* Door server is going away; kick it again. */
1196 			continue;
1197 		}
1198 
1199 		errbuf = rvalp->errbuf;
1200 		while (*errbuf != '\0') {
1201 			/*
1202 			 * Remove any newlines since zerror()
1203 			 * will append one automatically.
1204 			 */
1205 			cp = strchr(errbuf, '\n');
1206 			if (cp != NULL)
1207 				*cp = '\0';
1208 			zerror("%s", errbuf);
1209 			if (cp == NULL)
1210 				break;
1211 			errbuf = cp + 1;
1212 		}
1213 		result = rvalp->rval == 0 ? 0 : -1;
1214 		free(rvalp);
1215 		return (result);
1216 	}
1217 
1218 	free(rvalp);
1219 	return (-1);
1220 }
1221 
1222 static int
1223 ready_func(int argc, char *argv[])
1224 {
1225 	zone_cmd_arg_t zarg;
1226 	int arg;
1227 
1228 	if (zonecfg_in_alt_root()) {
1229 		zerror(gettext("cannot ready zone in alternate root"));
1230 		return (Z_ERR);
1231 	}
1232 
1233 	optind = 0;
1234 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1235 		switch (arg) {
1236 		case '?':
1237 			sub_usage(SHELP_READY, CMD_READY);
1238 			return (optopt == '?' ? Z_OK : Z_USAGE);
1239 		default:
1240 			sub_usage(SHELP_READY, CMD_READY);
1241 			return (Z_USAGE);
1242 		}
1243 	}
1244 	if (argc > optind) {
1245 		sub_usage(SHELP_READY, CMD_READY);
1246 		return (Z_USAGE);
1247 	}
1248 	if (sanity_check(target_zone, CMD_READY, B_FALSE, B_FALSE) != Z_OK)
1249 		return (Z_ERR);
1250 	if (verify_details(CMD_READY) != Z_OK)
1251 		return (Z_ERR);
1252 
1253 	zarg.cmd = Z_READY;
1254 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1255 		zerror(gettext("call to %s failed"), "zoneadmd");
1256 		return (Z_ERR);
1257 	}
1258 	return (Z_OK);
1259 }
1260 
1261 static int
1262 boot_func(int argc, char *argv[])
1263 {
1264 	zone_cmd_arg_t zarg;
1265 	int arg;
1266 
1267 	if (zonecfg_in_alt_root()) {
1268 		zerror(gettext("cannot boot zone in alternate root"));
1269 		return (Z_ERR);
1270 	}
1271 
1272 	zarg.bootbuf[0] = '\0';
1273 
1274 	/*
1275 	 * At the current time, the only supported subargument to the
1276 	 * "boot" subcommand is "-s" which specifies a single-user boot.
1277 	 * In the future, other boot arguments should be supported
1278 	 * including "-m" for specifying alternate smf(5) milestones.
1279 	 */
1280 	optind = 0;
1281 	if ((arg = getopt(argc, argv, "?s")) != EOF) {
1282 		switch (arg) {
1283 		case '?':
1284 			sub_usage(SHELP_BOOT, CMD_BOOT);
1285 			return (optopt == '?' ? Z_OK : Z_USAGE);
1286 		case 's':
1287 			(void) strlcpy(zarg.bootbuf, "-s",
1288 			    sizeof (zarg.bootbuf));
1289 			break;
1290 		default:
1291 			sub_usage(SHELP_BOOT, CMD_BOOT);
1292 			return (Z_USAGE);
1293 		}
1294 	}
1295 	if (argc > optind) {
1296 		sub_usage(SHELP_BOOT, CMD_BOOT);
1297 		return (Z_USAGE);
1298 	}
1299 	if (sanity_check(target_zone, CMD_BOOT, B_FALSE, B_FALSE) != Z_OK)
1300 		return (Z_ERR);
1301 	if (verify_details(CMD_BOOT) != Z_OK)
1302 		return (Z_ERR);
1303 	zarg.cmd = Z_BOOT;
1304 	if (call_zoneadmd(target_zone, &zarg) != 0) {
1305 		zerror(gettext("call to %s failed"), "zoneadmd");
1306 		return (Z_ERR);
1307 	}
1308 	return (Z_OK);
1309 }
1310 
1311 static void
1312 fake_up_local_zone(zoneid_t zid, zone_entry_t *zeptr)
1313 {
1314 	ssize_t result;
1315 
1316 	zeptr->zid = zid;
1317 	/*
1318 	 * Since we're looking up our own (non-global) zone name,
1319 	 * we can be assured that it will succeed.
1320 	 */
1321 	result = getzonenamebyid(zid, zeptr->zname, sizeof (zeptr->zname));
1322 	assert(result >= 0);
1323 	(void) strlcpy(zeptr->zroot, "/", sizeof (zeptr->zroot));
1324 	zeptr->zstate_str = "running";
1325 }
1326 
1327 static int
1328 list_func(int argc, char *argv[])
1329 {
1330 	zone_entry_t *zentp, zent;
1331 	int arg, retv;
1332 	boolean_t output = B_FALSE, verbose = B_FALSE, parsable = B_FALSE;
1333 	zone_state_t min_state = ZONE_STATE_RUNNING;
1334 	zoneid_t zone_id = getzoneid();
1335 
1336 	if (target_zone == NULL) {
1337 		/* all zones: default view to running but allow override */
1338 		optind = 0;
1339 		while ((arg = getopt(argc, argv, "?cipv")) != EOF) {
1340 			switch (arg) {
1341 			case '?':
1342 				sub_usage(SHELP_LIST, CMD_LIST);
1343 				return (optopt == '?' ? Z_OK : Z_USAGE);
1344 			case 'c':
1345 				min_state = ZONE_STATE_CONFIGURED;
1346 				break;
1347 			case 'i':
1348 				min_state = ZONE_STATE_INSTALLED;
1349 				break;
1350 			case 'p':
1351 				parsable = B_TRUE;
1352 				break;
1353 			case 'v':
1354 				verbose = B_TRUE;
1355 				break;
1356 			default:
1357 				sub_usage(SHELP_LIST, CMD_LIST);
1358 				return (Z_USAGE);
1359 			}
1360 		}
1361 		if (parsable && verbose) {
1362 			zerror(gettext("%s -p and -v are mutually exclusive."),
1363 			    cmd_to_str(CMD_LIST));
1364 			return (Z_ERR);
1365 		}
1366 		if (zone_id == GLOBAL_ZONEID) {
1367 			retv = zone_print_list(min_state, verbose, parsable);
1368 		} else {
1369 			retv = Z_OK;
1370 			fake_up_local_zone(zone_id, &zent);
1371 			zone_print(&zent, verbose, parsable);
1372 		}
1373 		return (retv);
1374 	}
1375 
1376 	/*
1377 	 * Specific target zone: disallow -i/-c suboptions.
1378 	 */
1379 	optind = 0;
1380 	while ((arg = getopt(argc, argv, "?pv")) != EOF) {
1381 		switch (arg) {
1382 		case '?':
1383 			sub_usage(SHELP_LIST, CMD_LIST);
1384 			return (optopt == '?' ? Z_OK : Z_USAGE);
1385 		case 'p':
1386 			parsable = B_TRUE;
1387 			break;
1388 		case 'v':
1389 			verbose = B_TRUE;
1390 			break;
1391 		default:
1392 			sub_usage(SHELP_LIST, CMD_LIST);
1393 			return (Z_USAGE);
1394 		}
1395 	}
1396 	if (parsable && verbose) {
1397 		zerror(gettext("%s -p and -v are mutually exclusive."),
1398 		    cmd_to_str(CMD_LIST));
1399 		return (Z_ERR);
1400 	}
1401 	if (argc > optind) {
1402 		sub_usage(SHELP_LIST, CMD_LIST);
1403 		return (Z_USAGE);
1404 	}
1405 	if (zone_id != GLOBAL_ZONEID) {
1406 		fake_up_local_zone(zone_id, &zent);
1407 		/*
1408 		 * main() will issue a Z_NO_ZONE error if it cannot get an
1409 		 * id for target_zone, which in a non-global zone should
1410 		 * happen for any zone name except `zonename`.  Thus we
1411 		 * assert() that here but don't otherwise check.
1412 		 */
1413 		assert(strcmp(zent.zname, target_zone) == 0);
1414 		zone_print(&zent, verbose, parsable);
1415 		output = B_TRUE;
1416 	} else if ((zentp = lookup_running_zone(target_zone)) != NULL) {
1417 		zone_print(zentp, verbose, parsable);
1418 		output = B_TRUE;
1419 	} else if (lookup_zone_info(target_zone, ZONE_ID_UNDEFINED,
1420 	    &zent) == Z_OK) {
1421 		zone_print(&zent, verbose, parsable);
1422 		output = B_TRUE;
1423 	}
1424 	return (output ? Z_OK : Z_ERR);
1425 }
1426 
1427 static void
1428 sigterm(int sig)
1429 {
1430 	/*
1431 	 * Ignore SIG{INT,TERM}, so we don't end up in an infinite loop,
1432 	 * then propagate the signal to our process group.
1433 	 */
1434 	(void) sigset(SIGINT, SIG_IGN);
1435 	(void) sigset(SIGTERM, SIG_IGN);
1436 	(void) kill(0, sig);
1437 	child_killed = B_TRUE;
1438 }
1439 
1440 static int
1441 do_subproc(char *cmdbuf)
1442 {
1443 	char inbuf[1024];	/* arbitrary large amount */
1444 	FILE *file;
1445 
1446 	child_killed = B_FALSE;
1447 	/*
1448 	 * We use popen(3c) to launch child processes for [un]install;
1449 	 * this library call does not return a PID, so we have to kill
1450 	 * the whole process group.  To avoid killing our parent, we
1451 	 * become a process group leader here.  But doing so can wreak
1452 	 * havoc with reading from stdin when launched by a non-job-control
1453 	 * shell, so we close stdin and reopen it as /dev/null first.
1454 	 */
1455 	(void) close(STDIN_FILENO);
1456 	(void) open("/dev/null", O_RDONLY);
1457 	(void) setpgid(0, 0);
1458 	(void) sigset(SIGINT, sigterm);
1459 	(void) sigset(SIGTERM, sigterm);
1460 	file = popen(cmdbuf, "r");
1461 	for (;;) {
1462 		if (child_killed || fgets(inbuf, sizeof (inbuf), file) == NULL)
1463 			break;
1464 		(void) fputs(inbuf, stdout);
1465 	}
1466 	(void) sigset(SIGINT, SIG_DFL);
1467 	(void) sigset(SIGTERM, SIG_DFL);
1468 	return (pclose(file));
1469 }
1470 
1471 static int
1472 subproc_status(const char *cmd, int status)
1473 {
1474 	if (WIFEXITED(status)) {
1475 		int exit_code = WEXITSTATUS(status);
1476 
1477 		if (exit_code == 0)
1478 			return (Z_OK);
1479 		zerror(gettext("'%s' failed with exit code %d."), cmd,
1480 		    exit_code);
1481 	} else if (WIFSIGNALED(status)) {
1482 		int signal = WTERMSIG(status);
1483 		char sigstr[SIG2STR_MAX];
1484 
1485 		if (sig2str(signal, sigstr) == 0) {
1486 			zerror(gettext("'%s' terminated by signal SIG%s."), cmd,
1487 			    sigstr);
1488 		} else {
1489 			zerror(gettext("'%s' terminated by an unknown signal."),
1490 			    cmd);
1491 		}
1492 	} else {
1493 		zerror(gettext("'%s' failed for unknown reasons."), cmd);
1494 	}
1495 	return (Z_ERR);
1496 }
1497 
1498 /*
1499  * Various sanity checks; make sure:
1500  * 1. We're in the global zone.
1501  * 2. The calling user has sufficient privilege.
1502  * 3. The target zone is neither the global zone nor anything starting with
1503  *    "SUNW".
1504  * 4a. If we're looking for a 'not running' (i.e., configured or installed)
1505  *     zone, the name service knows about it.
1506  * 4b. For some operations which expect a zone not to be running, that it is
1507  *     not already running (or ready).
1508  */
1509 static int
1510 sanity_check(char *zone, int cmd_num, boolean_t running,
1511     boolean_t unsafe_when_running)
1512 {
1513 	zone_entry_t *zent;
1514 	priv_set_t *privset;
1515 	zone_state_t state;
1516 	char kernzone[ZONENAME_MAX];
1517 	FILE *fp;
1518 
1519 	if (getzoneid() != GLOBAL_ZONEID) {
1520 		zerror(gettext("must be in the global zone to %s a zone."),
1521 		    cmd_to_str(cmd_num));
1522 		return (Z_ERR);
1523 	}
1524 
1525 	if ((privset = priv_allocset()) == NULL) {
1526 		zerror(gettext("%s failed"), "priv_allocset");
1527 		return (Z_ERR);
1528 	}
1529 
1530 	if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
1531 		zerror(gettext("%s failed"), "getppriv");
1532 		priv_freeset(privset);
1533 		return (Z_ERR);
1534 	}
1535 
1536 	if (priv_isfullset(privset) == B_FALSE) {
1537 		zerror(gettext("only a privileged user may %s a zone."),
1538 		    cmd_to_str(cmd_num));
1539 		priv_freeset(privset);
1540 		return (Z_ERR);
1541 	}
1542 	priv_freeset(privset);
1543 
1544 	if (zone == NULL) {
1545 		zerror(gettext("no zone specified"));
1546 		return (Z_ERR);
1547 	}
1548 
1549 	if (strcmp(zone, GLOBAL_ZONENAME) == 0) {
1550 		zerror(gettext("%s operation is invalid for the global zone."),
1551 		    cmd_to_str(cmd_num));
1552 		return (Z_ERR);
1553 	}
1554 
1555 	if (strncmp(zone, "SUNW", 4) == 0) {
1556 		zerror(gettext("%s operation is invalid for zones starting "
1557 		    "with SUNW."), cmd_to_str(cmd_num));
1558 		return (Z_ERR);
1559 	}
1560 
1561 	if (!zonecfg_in_alt_root()) {
1562 		zent = lookup_running_zone(zone);
1563 	} else if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
1564 		zent = NULL;
1565 	} else {
1566 		if (zonecfg_find_scratch(fp, zone, zonecfg_get_root(),
1567 		    kernzone, sizeof (kernzone)) == 0)
1568 			zent = lookup_running_zone(kernzone);
1569 		else
1570 			zent = NULL;
1571 		zonecfg_close_scratch(fp);
1572 	}
1573 
1574 	/*
1575 	 * Look up from the kernel for 'running' zones.
1576 	 */
1577 	if (running) {
1578 		if (zent == NULL) {
1579 			zerror(gettext("not running"));
1580 			return (Z_ERR);
1581 		}
1582 	} else {
1583 		int err;
1584 
1585 		if (unsafe_when_running && zent != NULL) {
1586 			/* check whether the zone is ready or running */
1587 			if ((err = zone_get_state(zent->zname,
1588 			    &zent->zstate_num)) != Z_OK) {
1589 				errno = err;
1590 				zperror2(zent->zname,
1591 				    gettext("could not get state"));
1592 				/* can't tell, so hedge */
1593 				zent->zstate_str = "ready/running";
1594 			} else {
1595 				zent->zstate_str =
1596 				    zone_state_str(zent->zstate_num);
1597 			}
1598 			zerror(gettext("%s operation is invalid for %s zones."),
1599 			    cmd_to_str(cmd_num), zent->zstate_str);
1600 			return (Z_ERR);
1601 		}
1602 		if ((err = zone_get_state(zone, &state)) != Z_OK) {
1603 			errno = err;
1604 			zperror2(zone, gettext("could not get state"));
1605 			return (Z_ERR);
1606 		}
1607 		switch (cmd_num) {
1608 		case CMD_UNINSTALL:
1609 			if (state == ZONE_STATE_CONFIGURED) {
1610 				zerror(gettext("is already in state '%s'."),
1611 				    zone_state_str(ZONE_STATE_CONFIGURED));
1612 				return (Z_ERR);
1613 			}
1614 			break;
1615 		case CMD_CLONE:
1616 		case CMD_INSTALL:
1617 			if (state == ZONE_STATE_INSTALLED) {
1618 				zerror(gettext("is already %s."),
1619 				    zone_state_str(ZONE_STATE_INSTALLED));
1620 				return (Z_ERR);
1621 			} else if (state == ZONE_STATE_INCOMPLETE) {
1622 				zerror(gettext("zone is %s; %s required."),
1623 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1624 				    cmd_to_str(CMD_UNINSTALL));
1625 				return (Z_ERR);
1626 			}
1627 			break;
1628 		case CMD_MOVE:
1629 		case CMD_READY:
1630 		case CMD_BOOT:
1631 		case CMD_MOUNT:
1632 			if (state < ZONE_STATE_INSTALLED) {
1633 				zerror(gettext("must be %s before %s."),
1634 				    zone_state_str(ZONE_STATE_INSTALLED),
1635 				    cmd_to_str(cmd_num));
1636 				return (Z_ERR);
1637 			}
1638 			break;
1639 		case CMD_VERIFY:
1640 			if (state == ZONE_STATE_INCOMPLETE) {
1641 				zerror(gettext("zone is %s; %s required."),
1642 				    zone_state_str(ZONE_STATE_INCOMPLETE),
1643 				    cmd_to_str(CMD_UNINSTALL));
1644 				return (Z_ERR);
1645 			}
1646 			break;
1647 		case CMD_UNMOUNT:
1648 			if (state != ZONE_STATE_MOUNTED) {
1649 				zerror(gettext("must be %s before %s."),
1650 				    zone_state_str(ZONE_STATE_MOUNTED),
1651 				    cmd_to_str(cmd_num));
1652 				return (Z_ERR);
1653 			}
1654 			break;
1655 		}
1656 	}
1657 	return (Z_OK);
1658 }
1659 
1660 static int
1661 halt_func(int argc, char *argv[])
1662 {
1663 	zone_cmd_arg_t zarg;
1664 	int arg;
1665 
1666 	if (zonecfg_in_alt_root()) {
1667 		zerror(gettext("cannot halt zone in alternate root"));
1668 		return (Z_ERR);
1669 	}
1670 
1671 	optind = 0;
1672 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1673 		switch (arg) {
1674 		case '?':
1675 			sub_usage(SHELP_HALT, CMD_HALT);
1676 			return (optopt == '?' ? Z_OK : Z_USAGE);
1677 		default:
1678 			sub_usage(SHELP_HALT, CMD_HALT);
1679 			return (Z_USAGE);
1680 		}
1681 	}
1682 	if (argc > optind) {
1683 		sub_usage(SHELP_HALT, CMD_HALT);
1684 		return (Z_USAGE);
1685 	}
1686 	/*
1687 	 * zoneadmd should be the one to decide whether or not to proceed,
1688 	 * so even though it seems that the fourth parameter below should
1689 	 * perhaps be B_TRUE, it really shouldn't be.
1690 	 */
1691 	if (sanity_check(target_zone, CMD_HALT, B_FALSE, B_FALSE) != Z_OK)
1692 		return (Z_ERR);
1693 
1694 	zarg.cmd = Z_HALT;
1695 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
1696 }
1697 
1698 static int
1699 reboot_func(int argc, char *argv[])
1700 {
1701 	zone_cmd_arg_t zarg;
1702 	int arg;
1703 
1704 	if (zonecfg_in_alt_root()) {
1705 		zerror(gettext("cannot reboot zone in alternate root"));
1706 		return (Z_ERR);
1707 	}
1708 
1709 	optind = 0;
1710 	if ((arg = getopt(argc, argv, "?")) != EOF) {
1711 		switch (arg) {
1712 		case '?':
1713 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
1714 			return (optopt == '?' ? Z_OK : Z_USAGE);
1715 		default:
1716 			sub_usage(SHELP_REBOOT, CMD_REBOOT);
1717 			return (Z_USAGE);
1718 		}
1719 	}
1720 	if (argc > 0) {
1721 		sub_usage(SHELP_REBOOT, CMD_REBOOT);
1722 		return (Z_USAGE);
1723 	}
1724 	/*
1725 	 * zoneadmd should be the one to decide whether or not to proceed,
1726 	 * so even though it seems that the fourth parameter below should
1727 	 * perhaps be B_TRUE, it really shouldn't be.
1728 	 */
1729 	if (sanity_check(target_zone, CMD_REBOOT, B_TRUE, B_FALSE) != Z_OK)
1730 		return (Z_ERR);
1731 	if (verify_details(CMD_REBOOT) != Z_OK)
1732 		return (Z_ERR);
1733 
1734 	zarg.cmd = Z_REBOOT;
1735 	return ((call_zoneadmd(target_zone, &zarg) == 0) ? Z_OK : Z_ERR);
1736 }
1737 
1738 static int
1739 verify_rctls(zone_dochandle_t handle)
1740 {
1741 	struct zone_rctltab rctltab;
1742 	size_t rbs = rctlblk_size();
1743 	rctlblk_t *rctlblk;
1744 	int error = Z_INVAL;
1745 
1746 	if ((rctlblk = malloc(rbs)) == NULL) {
1747 		zerror(gettext("failed to allocate %lu bytes: %s"), rbs,
1748 		    strerror(errno));
1749 		return (Z_NOMEM);
1750 	}
1751 
1752 	if (zonecfg_setrctlent(handle) != Z_OK) {
1753 		zerror(gettext("zonecfg_setrctlent failed"));
1754 		free(rctlblk);
1755 		return (error);
1756 	}
1757 
1758 	rctltab.zone_rctl_valptr = NULL;
1759 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
1760 		struct zone_rctlvaltab *rctlval;
1761 		const char *name = rctltab.zone_rctl_name;
1762 
1763 		if (!zonecfg_is_rctl(name)) {
1764 			zerror(gettext("WARNING: Ignoring unrecognized rctl "
1765 			    "'%s'."),  name);
1766 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1767 			rctltab.zone_rctl_valptr = NULL;
1768 			continue;
1769 		}
1770 
1771 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
1772 		    rctlval = rctlval->zone_rctlval_next) {
1773 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
1774 			    != Z_OK) {
1775 				zerror(gettext("invalid rctl value: "
1776 				    "(priv=%s,limit=%s,action%s)"),
1777 				    rctlval->zone_rctlval_priv,
1778 				    rctlval->zone_rctlval_limit,
1779 				    rctlval->zone_rctlval_action);
1780 				goto out;
1781 			}
1782 			if (!zonecfg_valid_rctl(name, rctlblk)) {
1783 				zerror(gettext("(priv=%s,limit=%s,action=%s) "
1784 				    "is not a valid value for rctl '%s'"),
1785 				    rctlval->zone_rctlval_priv,
1786 				    rctlval->zone_rctlval_limit,
1787 				    rctlval->zone_rctlval_action,
1788 				    name);
1789 				goto out;
1790 			}
1791 		}
1792 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1793 	}
1794 	rctltab.zone_rctl_valptr = NULL;
1795 	error = Z_OK;
1796 out:
1797 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
1798 	(void) zonecfg_endrctlent(handle);
1799 	free(rctlblk);
1800 	return (error);
1801 }
1802 
1803 static int
1804 verify_pool(zone_dochandle_t handle)
1805 {
1806 	char poolname[MAXPATHLEN];
1807 	pool_conf_t *poolconf;
1808 	pool_t *pool;
1809 	int status;
1810 	int error;
1811 
1812 	/*
1813 	 * This ends up being very similar to the check done in zoneadmd.
1814 	 */
1815 	error = zonecfg_get_pool(handle, poolname, sizeof (poolname));
1816 	if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
1817 		/*
1818 		 * No pool specified.
1819 		 */
1820 		return (0);
1821 	}
1822 	if (error != Z_OK) {
1823 		zperror(gettext("Unable to retrieve pool name from "
1824 		    "configuration"), B_TRUE);
1825 		return (error);
1826 	}
1827 	/*
1828 	 * Don't do anything if pools aren't enabled.
1829 	 */
1830 	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
1831 		zerror(gettext("WARNING: pools facility not active; "
1832 		    "zone will not be bound to pool '%s'."), poolname);
1833 		return (Z_OK);
1834 	}
1835 	/*
1836 	 * Try to provide a sane error message if the requested pool doesn't
1837 	 * exist.  It isn't clear that pools-related failures should
1838 	 * necessarily translate to a failure to verify the zone configuration,
1839 	 * hence they are not considered errors.
1840 	 */
1841 	if ((poolconf = pool_conf_alloc()) == NULL) {
1842 		zerror(gettext("WARNING: pool_conf_alloc failed; "
1843 		    "using default pool"));
1844 		return (Z_OK);
1845 	}
1846 	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
1847 	    PO_SUCCESS) {
1848 		zerror(gettext("WARNING: pool_conf_open failed; "
1849 		    "using default pool"));
1850 		pool_conf_free(poolconf);
1851 		return (Z_OK);
1852 	}
1853 	pool = pool_get_pool(poolconf, poolname);
1854 	(void) pool_conf_close(poolconf);
1855 	pool_conf_free(poolconf);
1856 	if (pool == NULL) {
1857 		zerror(gettext("WARNING: pool '%s' not found. "
1858 		    "using default pool"), poolname);
1859 	}
1860 
1861 	return (Z_OK);
1862 }
1863 
1864 static int
1865 verify_ipd(zone_dochandle_t handle)
1866 {
1867 	int return_code = Z_OK;
1868 	struct zone_fstab fstab;
1869 	struct stat st;
1870 	char specdir[MAXPATHLEN];
1871 
1872 	if (zonecfg_setipdent(handle) != Z_OK) {
1873 		/*
1874 		 * TRANSLATION_NOTE
1875 		 * inherit-pkg-dirs is a literal that should not be translated.
1876 		 */
1877 		(void) fprintf(stderr, gettext("could not verify "
1878 		    "inherit-pkg-dirs: unable to enumerate mounts\n"));
1879 		return (Z_ERR);
1880 	}
1881 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
1882 		/*
1883 		 * Verify fs_dir exists.
1884 		 */
1885 		(void) snprintf(specdir, sizeof (specdir), "%s%s",
1886 		    zonecfg_get_root(), fstab.zone_fs_dir);
1887 		if (stat(specdir, &st) != 0) {
1888 			/*
1889 			 * TRANSLATION_NOTE
1890 			 * inherit-pkg-dir is a literal that should not be
1891 			 * translated.
1892 			 */
1893 			(void) fprintf(stderr, gettext("could not verify "
1894 			    "inherit-pkg-dir %s: %s\n"),
1895 			    fstab.zone_fs_dir, strerror(errno));
1896 			return_code = Z_ERR;
1897 		}
1898 		if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
1899 			/*
1900 			 * TRANSLATION_NOTE
1901 			 * inherit-pkg-dir and NFS are literals that should
1902 			 * not be translated.
1903 			 */
1904 			(void) fprintf(stderr, gettext("cannot verify "
1905 			    "inherit-pkg-dir %s: NFS mounted file-system.\n"
1906 			    "\tA local file-system must be used.\n"),
1907 			    fstab.zone_fs_dir);
1908 			return_code = Z_ERR;
1909 		}
1910 	}
1911 	(void) zonecfg_endipdent(handle);
1912 
1913 	return (return_code);
1914 }
1915 
1916 static int
1917 verify_filesystems(zone_dochandle_t handle)
1918 {
1919 	int return_code = Z_OK;
1920 	struct zone_fstab fstab;
1921 	char cmdbuf[MAXPATHLEN];
1922 	struct stat st;
1923 
1924 	/*
1925 	 * No need to verify inherit-pkg-dir fs types, as their type is
1926 	 * implicitly lofs, which is known.  Therefore, the types are only
1927 	 * verified for regular filesystems below.
1928 	 *
1929 	 * Since the actual mount point is not known until the dependent mounts
1930 	 * are performed, we don't attempt any path validation here: that will
1931 	 * happen later when zoneadmd actually does the mounts.
1932 	 */
1933 	if (zonecfg_setfsent(handle) != Z_OK) {
1934 		(void) fprintf(stderr, gettext("could not verify file-systems: "
1935 		    "unable to enumerate mounts\n"));
1936 		return (Z_ERR);
1937 	}
1938 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1939 		if (!zonecfg_valid_fs_type(fstab.zone_fs_type)) {
1940 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1941 			    "type %s is not allowed.\n"), fstab.zone_fs_dir,
1942 			    fstab.zone_fs_type);
1943 			return_code = Z_ERR;
1944 			goto next_fs;
1945 		}
1946 		/*
1947 		 * Verify /usr/lib/fs/<fstype>/mount exists.
1948 		 */
1949 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount",
1950 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
1951 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1952 			    "type %s is too long.\n"), fstab.zone_fs_dir,
1953 			    fstab.zone_fs_type);
1954 			return_code = Z_ERR;
1955 			goto next_fs;
1956 		}
1957 		if (stat(cmdbuf, &st) != 0) {
1958 			(void) fprintf(stderr, gettext("could not verify fs "
1959 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
1960 			    cmdbuf, strerror(errno));
1961 			return_code = Z_ERR;
1962 			goto next_fs;
1963 		}
1964 		if (!S_ISREG(st.st_mode)) {
1965 			(void) fprintf(stderr, gettext("could not verify fs "
1966 			    "%s: %s is not a regular file\n"),
1967 			    fstab.zone_fs_dir, cmdbuf);
1968 			return_code = Z_ERR;
1969 			goto next_fs;
1970 		}
1971 		/*
1972 		 * Verify /usr/lib/fs/<fstype>/fsck exists iff zone_fs_raw is
1973 		 * set.
1974 		 */
1975 		if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck",
1976 		    fstab.zone_fs_type) > sizeof (cmdbuf)) {
1977 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1978 			    "type %s is too long.\n"), fstab.zone_fs_dir,
1979 			    fstab.zone_fs_type);
1980 			return_code = Z_ERR;
1981 			goto next_fs;
1982 		}
1983 		if (fstab.zone_fs_raw[0] == '\0' && stat(cmdbuf, &st) == 0) {
1984 			(void) fprintf(stderr, gettext("could not verify fs "
1985 			    "%s: must specify 'raw' device for %s "
1986 			    "file-systems\n"),
1987 			    fstab.zone_fs_dir, fstab.zone_fs_type);
1988 			return_code = Z_ERR;
1989 			goto next_fs;
1990 		}
1991 		if (fstab.zone_fs_raw[0] != '\0' &&
1992 		    (stat(cmdbuf, &st) != 0 || !S_ISREG(st.st_mode))) {
1993 			(void) fprintf(stderr, gettext("cannot verify fs %s: "
1994 			    "'raw' device specified but "
1995 			    "no fsck executable exists for %s\n"),
1996 			    fstab.zone_fs_dir, fstab.zone_fs_type);
1997 			return_code = Z_ERR;
1998 			goto next_fs;
1999 		}
2000 		/*
2001 		 * Verify fs_special and optionally fs_raw, exists.
2002 		 */
2003 		if (stat(fstab.zone_fs_special, &st) != 0) {
2004 			(void) fprintf(stderr, gettext("could not verify fs "
2005 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2006 			    fstab.zone_fs_special, strerror(errno));
2007 			return_code = Z_ERR;
2008 			goto next_fs;
2009 		}
2010 		if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
2011 			/*
2012 			 * TRANSLATION_NOTE
2013 			 * fs and NFS are literals that should
2014 			 * not be translated.
2015 			 */
2016 			(void) fprintf(stderr, gettext("cannot verify "
2017 			    "fs %s: NFS mounted file-system.\n"
2018 			    "\tA local file-system must be used.\n"),
2019 			    fstab.zone_fs_special);
2020 			return_code = Z_ERR;
2021 			goto next_fs;
2022 		}
2023 		if (fstab.zone_fs_raw[0] != '\0' &&
2024 		    stat(fstab.zone_fs_raw, &st) != 0) {
2025 			/*
2026 			 * TRANSLATION_NOTE
2027 			 * fs is a literal that should not be translated.
2028 			 */
2029 			(void) fprintf(stderr, gettext("could not verify fs "
2030 			    "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2031 			    fstab.zone_fs_raw, strerror(errno));
2032 			return_code = Z_ERR;
2033 			goto next_fs;
2034 		}
2035 next_fs:
2036 		zonecfg_free_fs_option_list(fstab.zone_fs_options);
2037 	}
2038 	(void) zonecfg_endfsent(handle);
2039 
2040 	return (return_code);
2041 }
2042 
2043 const char *current_dataset;
2044 
2045 /*
2046  * Custom error handler for errors incurred as part of the checks below.  We
2047  * want to trim off the leading 'cannot open ...' to create a better error
2048  * message.  The only other way this can fail is if we fail to set the 'zoned'
2049  * property.  In this case we just pass the error on verbatim.
2050  */
2051 static void
2052 zfs_error_handler(const char *fmt, va_list ap)
2053 {
2054 	char buf[1024];
2055 
2056 	(void) vsnprintf(buf, sizeof (buf), fmt, ap);
2057 
2058 	if (strncmp(gettext("cannot open "), buf,
2059 	    strlen(gettext("cannot open "))) == 0)
2060 		/*
2061 		 * TRANSLATION_NOTE
2062 		 * zfs and dataset are literals that should not be translated.
2063 		 */
2064 		(void) fprintf(stderr, gettext("could not verify zfs "
2065 		    "dataset %s%s\n"), current_dataset, strchr(buf, ':'));
2066 	else
2067 		(void) fprintf(stderr, gettext("could not verify zfs dataset "
2068 		    "%s: %s\n"), current_dataset, buf);
2069 }
2070 
2071 /* ARGSUSED */
2072 static int
2073 check_zvol(zfs_handle_t *zhp, void *unused)
2074 {
2075 	int ret;
2076 
2077 	if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
2078 		/*
2079 		 * TRANSLATION_NOTE
2080 		 * zfs and dataset are literals that should not be translated.
2081 		 */
2082 		(void) fprintf(stderr, gettext("cannot verify zfs dataset %s: "
2083 		    "volumes cannot be specified as a zone dataset resource\n"),
2084 		    zfs_get_name(zhp));
2085 		ret = -1;
2086 	} else {
2087 		ret = zfs_iter_children(zhp, check_zvol, NULL);
2088 	}
2089 
2090 	zfs_close(zhp);
2091 
2092 	return (ret);
2093 }
2094 
2095 /*
2096  * Validate that the given dataset exists on the system, and that neither it nor
2097  * its children are zvols.
2098  *
2099  * Note that we don't do anything with the 'zoned' property here.  All
2100  * management is done in zoneadmd when the zone is actually rebooted.  This
2101  * allows us to automatically set the zoned property even when a zone is
2102  * rebooted by the administrator.
2103  */
2104 static int
2105 verify_datasets(zone_dochandle_t handle)
2106 {
2107 	int return_code = Z_OK;
2108 	struct zone_dstab dstab;
2109 	zfs_handle_t *zhp;
2110 	char propbuf[ZFS_MAXPROPLEN];
2111 	char source[ZFS_MAXNAMELEN];
2112 	zfs_source_t srctype;
2113 
2114 	if (zonecfg_setdsent(handle) != Z_OK) {
2115 		/*
2116 		 * TRANSLATION_NOTE
2117 		 * zfs and dataset are literals that should not be translated.
2118 		 */
2119 		(void) fprintf(stderr, gettext("could not verify zfs datasets: "
2120 		    "unable to enumerate datasets\n"));
2121 		return (Z_ERR);
2122 	}
2123 
2124 	zfs_set_error_handler(zfs_error_handler);
2125 
2126 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2127 
2128 		current_dataset = dstab.zone_dataset_name;
2129 
2130 		if ((zhp = zfs_open(dstab.zone_dataset_name,
2131 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
2132 			return_code = Z_ERR;
2133 			continue;
2134 		}
2135 
2136 		if (zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, propbuf,
2137 		    sizeof (propbuf), &srctype, source,
2138 		    sizeof (source), 0) == 0 &&
2139 		    (srctype == ZFS_SRC_INHERITED)) {
2140 			(void) fprintf(stderr, gettext("could not verify zfs "
2141 			    "dataset %s: mountpoint cannot be inherited\n"),
2142 			    dstab.zone_dataset_name);
2143 			return_code = Z_ERR;
2144 			zfs_close(zhp);
2145 			continue;
2146 		}
2147 
2148 		if (zfs_get_type(zhp) == ZFS_TYPE_VOLUME) {
2149 			(void) fprintf(stderr, gettext("cannot verify zfs "
2150 			    "dataset %s: volumes cannot be specified as a "
2151 			    "zone dataset resource\n"),
2152 			    dstab.zone_dataset_name);
2153 			return_code = Z_ERR;
2154 		}
2155 
2156 		if (zfs_iter_children(zhp, check_zvol, NULL) != 0)
2157 			return_code = Z_ERR;
2158 
2159 		zfs_close(zhp);
2160 	}
2161 	(void) zonecfg_enddsent(handle);
2162 
2163 	return (return_code);
2164 }
2165 
2166 static int
2167 verify_details(int cmd_num)
2168 {
2169 	zone_dochandle_t handle;
2170 	struct zone_nwiftab nwiftab;
2171 	char zonepath[MAXPATHLEN], checkpath[MAXPATHLEN];
2172 	int return_code = Z_OK;
2173 	int err;
2174 	boolean_t in_alt_root;
2175 
2176 	if ((handle = zonecfg_init_handle()) == NULL) {
2177 		zperror(cmd_to_str(cmd_num), B_TRUE);
2178 		return (Z_ERR);
2179 	}
2180 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
2181 		errno = err;
2182 		zperror(cmd_to_str(cmd_num), B_TRUE);
2183 		zonecfg_fini_handle(handle);
2184 		return (Z_ERR);
2185 	}
2186 	if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
2187 	    Z_OK) {
2188 		errno = err;
2189 		zperror(cmd_to_str(cmd_num), B_TRUE);
2190 		zonecfg_fini_handle(handle);
2191 		return (Z_ERR);
2192 	}
2193 	/*
2194 	 * zonecfg_get_zonepath() gets its data from the XML repository.
2195 	 * Verify this against the index file, which is checked first by
2196 	 * zone_get_zonepath().  If they don't match, bail out.
2197 	 */
2198 	if ((err = zone_get_zonepath(target_zone, checkpath,
2199 	    sizeof (checkpath))) != Z_OK) {
2200 		errno = err;
2201 		zperror2(target_zone, gettext("could not get zone path"));
2202 		return (Z_ERR);
2203 	}
2204 	if (strcmp(zonepath, checkpath) != 0) {
2205 		/*
2206 		 * TRANSLATION_NOTE
2207 		 * XML and zonepath are literals that should not be translated.
2208 		 */
2209 		(void) fprintf(stderr, gettext("The XML repository has "
2210 		    "zonepath '%s',\nbut the index file has zonepath '%s'.\n"
2211 		    "These must match, so fix the incorrect entry.\n"),
2212 		    zonepath, checkpath);
2213 		return (Z_ERR);
2214 	}
2215 	if (validate_zonepath(zonepath, cmd_num) != Z_OK) {
2216 		(void) fprintf(stderr, gettext("could not verify zonepath %s "
2217 		    "because of the above errors.\n"), zonepath);
2218 		return_code = Z_ERR;
2219 	}
2220 
2221 	in_alt_root = zonecfg_in_alt_root();
2222 	if (in_alt_root)
2223 		goto no_net;
2224 
2225 	if ((err = zonecfg_setnwifent(handle)) != Z_OK) {
2226 		errno = err;
2227 		zperror(cmd_to_str(cmd_num), B_TRUE);
2228 		zonecfg_fini_handle(handle);
2229 		return (Z_ERR);
2230 	}
2231 	while (zonecfg_getnwifent(handle, &nwiftab) == Z_OK) {
2232 		struct lifreq lifr;
2233 		sa_family_t af;
2234 		int so, res;
2235 
2236 		/* skip any loopback interfaces */
2237 		if (strcmp(nwiftab.zone_nwif_physical, "lo0") == 0)
2238 			continue;
2239 		if ((res = zonecfg_valid_net_address(nwiftab.zone_nwif_address,
2240 		    &lifr)) != Z_OK) {
2241 			(void) fprintf(stderr, gettext("could not verify %s "
2242 			    "%s=%s %s=%s: %s\n"), "net", "address",
2243 			    nwiftab.zone_nwif_address, "physical",
2244 			    nwiftab.zone_nwif_physical, zonecfg_strerror(res));
2245 			return_code = Z_ERR;
2246 			continue;
2247 		}
2248 		af = lifr.lifr_addr.ss_family;
2249 		(void) memset(&lifr, 0, sizeof (lifr));
2250 		(void) strlcpy(lifr.lifr_name, nwiftab.zone_nwif_physical,
2251 		    sizeof (lifr.lifr_name));
2252 		lifr.lifr_addr.ss_family = af;
2253 		if ((so = socket(af, SOCK_DGRAM, 0)) < 0) {
2254 			(void) fprintf(stderr, gettext("could not verify %s "
2255 			    "%s=%s %s=%s: could not get socket: %s\n"), "net",
2256 			    "address", nwiftab.zone_nwif_address, "physical",
2257 			    nwiftab.zone_nwif_physical, strerror(errno));
2258 			return_code = Z_ERR;
2259 			continue;
2260 		}
2261 		if (ioctl(so, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2262 			(void) fprintf(stderr,
2263 			    gettext("could not verify %s %s=%s %s=%s: %s\n"),
2264 			    "net", "address", nwiftab.zone_nwif_address,
2265 			    "physical", nwiftab.zone_nwif_physical,
2266 			    strerror(errno));
2267 			return_code = Z_ERR;
2268 		}
2269 		(void) close(so);
2270 	}
2271 	(void) zonecfg_endnwifent(handle);
2272 no_net:
2273 
2274 	if (verify_filesystems(handle) != Z_OK)
2275 		return_code = Z_ERR;
2276 	if (verify_ipd(handle) != Z_OK)
2277 		return_code = Z_ERR;
2278 	if (!in_alt_root && verify_rctls(handle) != Z_OK)
2279 		return_code = Z_ERR;
2280 	if (!in_alt_root && verify_pool(handle) != Z_OK)
2281 		return_code = Z_ERR;
2282 	if (!in_alt_root && verify_datasets(handle) != Z_OK)
2283 		return_code = Z_ERR;
2284 	zonecfg_fini_handle(handle);
2285 	if (return_code == Z_ERR)
2286 		(void) fprintf(stderr,
2287 		    gettext("%s: zone %s failed to verify\n"),
2288 		    execname, target_zone);
2289 	return (return_code);
2290 }
2291 
2292 static int
2293 verify_func(int argc, char *argv[])
2294 {
2295 	int arg;
2296 
2297 	optind = 0;
2298 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2299 		switch (arg) {
2300 		case '?':
2301 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2302 			return (optopt == '?' ? Z_OK : Z_USAGE);
2303 		default:
2304 			sub_usage(SHELP_VERIFY, CMD_VERIFY);
2305 			return (Z_USAGE);
2306 		}
2307 	}
2308 	if (argc > optind) {
2309 		sub_usage(SHELP_VERIFY, CMD_VERIFY);
2310 		return (Z_USAGE);
2311 	}
2312 	if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE) != Z_OK)
2313 		return (Z_ERR);
2314 	return (verify_details(CMD_VERIFY));
2315 }
2316 
2317 #define	LUCREATEZONE	"/usr/lib/lu/lucreatezone"
2318 
2319 static int
2320 install_func(int argc, char *argv[])
2321 {
2322 	/* 9: "exec " and " -z " */
2323 	char cmdbuf[sizeof (LUCREATEZONE) + ZONENAME_MAX + 9];
2324 	int lockfd;
2325 	int err, arg;
2326 	char zonepath[MAXPATHLEN];
2327 	int status;
2328 
2329 	if (zonecfg_in_alt_root()) {
2330 		zerror(gettext("cannot install zone in alternate root"));
2331 		return (Z_ERR);
2332 	}
2333 
2334 	optind = 0;
2335 	if ((arg = getopt(argc, argv, "?")) != EOF) {
2336 		switch (arg) {
2337 		case '?':
2338 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
2339 			return (optopt == '?' ? Z_OK : Z_USAGE);
2340 		default:
2341 			sub_usage(SHELP_INSTALL, CMD_INSTALL);
2342 			return (Z_USAGE);
2343 		}
2344 	}
2345 	if (argc > optind) {
2346 		sub_usage(SHELP_INSTALL, CMD_INSTALL);
2347 		return (Z_USAGE);
2348 	}
2349 	if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE) != Z_OK)
2350 		return (Z_ERR);
2351 	if (verify_details(CMD_INSTALL) != Z_OK)
2352 		return (Z_ERR);
2353 
2354 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
2355 		zerror(gettext("another %s may have an operation in progress."),
2356 		    "zoneadm");
2357 		return (Z_ERR);
2358 	}
2359 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
2360 	if (err != Z_OK) {
2361 		errno = err;
2362 		zperror2(target_zone, gettext("could not set state"));
2363 		goto done;
2364 	}
2365 
2366 	/*
2367 	 * According to the Application Packaging Developer's Guide, a
2368 	 * "checkinstall" script when included in a package is executed as
2369 	 * the user "install", if such a user exists, or by the user
2370 	 * "nobody".  In order to support this dubious behavior, the path
2371 	 * to the zone being constructed is opened up during the life of
2372 	 * the command laying down the zone's root file system.  Once this
2373 	 * has completed, regardless of whether it was successful, the
2374 	 * path to the zone is again restricted.
2375 	 */
2376 	if ((err = zone_get_zonepath(target_zone, zonepath,
2377 	    sizeof (zonepath))) != Z_OK) {
2378 		errno = err;
2379 		zperror2(target_zone, gettext("could not get zone path"));
2380 		goto done;
2381 	}
2382 	if (chmod(zonepath, DEFAULT_DIR_MODE) != 0) {
2383 		zperror(zonepath, B_FALSE);
2384 		err = Z_ERR;
2385 		goto done;
2386 	}
2387 
2388 	/*
2389 	 * "exec" the command so that the returned status is that of
2390 	 * LUCREATEZONE and not the shell.
2391 	 */
2392 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " LUCREATEZONE " -z %s",
2393 	    target_zone);
2394 	status = do_subproc(cmdbuf);
2395 	if (chmod(zonepath, S_IRWXU) != 0) {
2396 		zperror(zonepath, B_FALSE);
2397 		err = Z_ERR;
2398 		goto done;
2399 	}
2400 	if ((err = subproc_status(LUCREATEZONE, status)) != Z_OK)
2401 		goto done;
2402 
2403 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
2404 		errno = err;
2405 		zperror2(target_zone, gettext("could not set state"));
2406 		goto done;
2407 	}
2408 
2409 done:
2410 	release_lock_file(lockfd);
2411 	return ((err == Z_OK) ? Z_OK : Z_ERR);
2412 }
2413 
2414 /*
2415  * Check that the inherited pkg dirs are the same for the clone and its source.
2416  * The easiest way to do that is check that the list of ipds is the same
2417  * by matching each one against the other.  This algorithm should be fine since
2418  * the list of ipds should not be that long.
2419  */
2420 static int
2421 valid_ipd_clone(zone_dochandle_t s_handle, char *source_zone,
2422 	zone_dochandle_t t_handle, char *target_zone)
2423 {
2424 	int err;
2425 	int res = Z_OK;
2426 	int s_cnt = 0;
2427 	int t_cnt = 0;
2428 	struct zone_fstab s_fstab;
2429 	struct zone_fstab t_fstab;
2430 
2431 	/*
2432 	 * First check the source of the clone against the target.
2433 	 */
2434 	if ((err = zonecfg_setipdent(s_handle)) != Z_OK) {
2435 		errno = err;
2436 		zperror2(source_zone, gettext("could not enumerate "
2437 		    "inherit-pkg-dirs"));
2438 		return (Z_ERR);
2439 	}
2440 
2441 	while (zonecfg_getipdent(s_handle, &s_fstab) == Z_OK) {
2442 		boolean_t match = B_FALSE;
2443 
2444 		s_cnt++;
2445 
2446 		if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
2447 			errno = err;
2448 			zperror2(target_zone, gettext("could not enumerate "
2449 			    "inherit-pkg-dirs"));
2450 			(void) zonecfg_endipdent(s_handle);
2451 			return (Z_ERR);
2452 		}
2453 
2454 		while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK) {
2455 			if (strcmp(s_fstab.zone_fs_dir, t_fstab.zone_fs_dir)
2456 			    == 0) {
2457 				match = B_TRUE;
2458 				break;
2459 			}
2460 		}
2461 		(void) zonecfg_endipdent(t_handle);
2462 
2463 		if (!match) {
2464 			(void) fprintf(stderr, gettext("inherit-pkg-dir "
2465 			    "'%s' is not configured in zone %s.\n"),
2466 			    s_fstab.zone_fs_dir, target_zone);
2467 			res = Z_ERR;
2468 		}
2469 	}
2470 
2471 	(void) zonecfg_endipdent(s_handle);
2472 
2473 	/* skip the next check if we already have errors */
2474 	if (res == Z_ERR)
2475 		return (res);
2476 
2477 	/*
2478 	 * Now check the number of ipds in the target so we can verify
2479 	 * that the source is not a subset of the target.
2480 	 */
2481 	if ((err = zonecfg_setipdent(t_handle)) != Z_OK) {
2482 		errno = err;
2483 		zperror2(target_zone, gettext("could not enumerate "
2484 		    "inherit-pkg-dirs"));
2485 		return (Z_ERR);
2486 	}
2487 
2488 	while (zonecfg_getipdent(t_handle, &t_fstab) == Z_OK)
2489 		t_cnt++;
2490 
2491 	(void) zonecfg_endipdent(t_handle);
2492 
2493 	if (t_cnt != s_cnt) {
2494 		(void) fprintf(stderr, gettext("Zone %s is configured "
2495 		    "with inherit-pkg-dirs that are not configured in zone "
2496 		    "%s.\n"), target_zone, source_zone);
2497 		res = Z_ERR;
2498 	}
2499 
2500 	return (res);
2501 }
2502 
2503 static void
2504 warn_dev_match(zone_dochandle_t s_handle, char *source_zone,
2505 	zone_dochandle_t t_handle, char *target_zone)
2506 {
2507 	int err;
2508 	struct zone_devtab s_devtab;
2509 	struct zone_devtab t_devtab;
2510 
2511 	if ((err = zonecfg_setdevent(t_handle)) != Z_OK) {
2512 		errno = err;
2513 		zperror2(target_zone, gettext("could not enumerate devices"));
2514 		return;
2515 	}
2516 
2517 	while (zonecfg_getdevent(t_handle, &t_devtab) == Z_OK) {
2518 		if ((err = zonecfg_setdevent(s_handle)) != Z_OK) {
2519 			errno = err;
2520 			zperror2(source_zone,
2521 			    gettext("could not enumerate devices"));
2522 			(void) zonecfg_enddevent(t_handle);
2523 			return;
2524 		}
2525 
2526 		while (zonecfg_getdevent(s_handle, &s_devtab) == Z_OK) {
2527 			/*
2528 			 * Use fnmatch to catch the case where wildcards
2529 			 * were used in one zone and the other has an
2530 			 * explicit entry (e.g. /dev/dsk/c0t0d0s6 vs.
2531 			 * /dev/\*dsk/c0t0d0s6).
2532 			 */
2533 			if (fnmatch(t_devtab.zone_dev_match,
2534 			    s_devtab.zone_dev_match, FNM_PATHNAME) == 0 ||
2535 			    fnmatch(s_devtab.zone_dev_match,
2536 			    t_devtab.zone_dev_match, FNM_PATHNAME) == 0) {
2537 				(void) fprintf(stderr,
2538 				    gettext("WARNING: device '%s' "
2539 				    "is configured in both zones.\n"),
2540 				    t_devtab.zone_dev_match);
2541 				break;
2542 			}
2543 		}
2544 		(void) zonecfg_enddevent(s_handle);
2545 	}
2546 
2547 	(void) zonecfg_enddevent(t_handle);
2548 }
2549 
2550 /*
2551  * Check if the specified mount option (opt) is contained within the
2552  * options string.
2553  */
2554 static boolean_t
2555 opt_match(char *opt, char *options)
2556 {
2557 	char *p;
2558 	char *lastp;
2559 
2560 	if ((p = strtok_r(options, ",", &lastp)) != NULL) {
2561 		if (strcmp(p, opt) == 0)
2562 			return (B_TRUE);
2563 		while ((p = strtok_r(NULL, ",", &lastp)) != NULL) {
2564 			if (strcmp(p, opt) == 0)
2565 				return (B_TRUE);
2566 		}
2567 	}
2568 
2569 	return (B_FALSE);
2570 }
2571 
2572 #define	RW_LOFS	"WARNING: read-write lofs file-system on '%s' is configured " \
2573 	"in both zones.\n"
2574 
2575 static void
2576 print_fs_warnings(struct zone_fstab *s_fstab, struct zone_fstab *t_fstab)
2577 {
2578 	/*
2579 	 * It is ok to have shared lofs mounted fs but we want to warn if
2580 	 * either is rw since this will effect the other zone.
2581 	 */
2582 	if (strcmp(t_fstab->zone_fs_type, "lofs") == 0) {
2583 		zone_fsopt_t *optp;
2584 
2585 		/* The default is rw so no options means rw */
2586 		if (t_fstab->zone_fs_options == NULL ||
2587 		    s_fstab->zone_fs_options == NULL) {
2588 			(void) fprintf(stderr, gettext(RW_LOFS),
2589 			    t_fstab->zone_fs_special);
2590 			return;
2591 		}
2592 
2593 		for (optp = s_fstab->zone_fs_options; optp != NULL;
2594 		    optp = optp->zone_fsopt_next) {
2595 			if (opt_match("rw", optp->zone_fsopt_opt)) {
2596 				(void) fprintf(stderr, gettext(RW_LOFS),
2597 				    s_fstab->zone_fs_special);
2598 				return;
2599 			}
2600 		}
2601 
2602 		for (optp = t_fstab->zone_fs_options; optp != NULL;
2603 		    optp = optp->zone_fsopt_next) {
2604 			if (opt_match("rw", optp->zone_fsopt_opt)) {
2605 				(void) fprintf(stderr, gettext(RW_LOFS),
2606 				    t_fstab->zone_fs_special);
2607 				return;
2608 			}
2609 		}
2610 
2611 		return;
2612 	}
2613 
2614 	/*
2615 	 * TRANSLATION_NOTE
2616 	 * The first variable is the file-system type and the second is
2617 	 * the file-system special device.  For example,
2618 	 * WARNING: ufs file-system on '/dev/dsk/c0t0d0s0' ...
2619 	 */
2620 	(void) fprintf(stderr, gettext("WARNING: %s file-system on '%s' "
2621 	    "is configured in both zones.\n"), t_fstab->zone_fs_type,
2622 	    t_fstab->zone_fs_special);
2623 }
2624 
2625 static void
2626 warn_fs_match(zone_dochandle_t s_handle, char *source_zone,
2627 	zone_dochandle_t t_handle, char *target_zone)
2628 {
2629 	int err;
2630 	struct zone_fstab s_fstab;
2631 	struct zone_fstab t_fstab;
2632 
2633 	if ((err = zonecfg_setfsent(t_handle)) != Z_OK) {
2634 		errno = err;
2635 		zperror2(target_zone,
2636 		    gettext("could not enumerate file-systems"));
2637 		return;
2638 	}
2639 
2640 	while (zonecfg_getfsent(t_handle, &t_fstab) == Z_OK) {
2641 		if ((err = zonecfg_setfsent(s_handle)) != Z_OK) {
2642 			errno = err;
2643 			zperror2(source_zone,
2644 			    gettext("could not enumerate file-systems"));
2645 			(void) zonecfg_endfsent(t_handle);
2646 			return;
2647 		}
2648 
2649 		while (zonecfg_getfsent(s_handle, &s_fstab) == Z_OK) {
2650 			if (strcmp(t_fstab.zone_fs_special,
2651 			    s_fstab.zone_fs_special) == 0) {
2652 				print_fs_warnings(&s_fstab, &t_fstab);
2653 				break;
2654 			}
2655 		}
2656 		(void) zonecfg_endfsent(s_handle);
2657 	}
2658 
2659 	(void) zonecfg_endfsent(t_handle);
2660 }
2661 
2662 /*
2663  * We don't catch the case where you used the same IP address but
2664  * it is not an exact string match.  For example, 192.9.0.128 vs. 192.09.0.128.
2665  * However, we're not going to worry about that but we will check for
2666  * a possible netmask on one of the addresses (e.g. 10.0.0.1 and 10.0.0.1/24)
2667  * and handle that case as a match.
2668  */
2669 static void
2670 warn_ip_match(zone_dochandle_t s_handle, char *source_zone,
2671 	zone_dochandle_t t_handle, char *target_zone)
2672 {
2673 	int err;
2674 	struct zone_nwiftab s_nwiftab;
2675 	struct zone_nwiftab t_nwiftab;
2676 
2677 	if ((err = zonecfg_setnwifent(t_handle)) != Z_OK) {
2678 		errno = err;
2679 		zperror2(target_zone,
2680 		    gettext("could not enumerate network interfaces"));
2681 		return;
2682 	}
2683 
2684 	while (zonecfg_getnwifent(t_handle, &t_nwiftab) == Z_OK) {
2685 		char *p;
2686 
2687 		/* remove an (optional) netmask from the address */
2688 		if ((p = strchr(t_nwiftab.zone_nwif_address, '/')) != NULL)
2689 			*p = '\0';
2690 
2691 		if ((err = zonecfg_setnwifent(s_handle)) != Z_OK) {
2692 			errno = err;
2693 			zperror2(source_zone,
2694 			    gettext("could not enumerate network interfaces"));
2695 			(void) zonecfg_endnwifent(t_handle);
2696 			return;
2697 		}
2698 
2699 		while (zonecfg_getnwifent(s_handle, &s_nwiftab) == Z_OK) {
2700 			/* remove an (optional) netmask from the address */
2701 			if ((p = strchr(s_nwiftab.zone_nwif_address, '/'))
2702 			    != NULL)
2703 				*p = '\0';
2704 
2705 			if (strcmp(t_nwiftab.zone_nwif_address,
2706 			    s_nwiftab.zone_nwif_address) == 0) {
2707 				(void) fprintf(stderr,
2708 				    gettext("WARNING: network address '%s' "
2709 				    "is configured in both zones.\n"),
2710 				    t_nwiftab.zone_nwif_address);
2711 				break;
2712 			}
2713 		}
2714 		(void) zonecfg_endnwifent(s_handle);
2715 	}
2716 
2717 	(void) zonecfg_endnwifent(t_handle);
2718 }
2719 
2720 static void
2721 warn_dataset_match(zone_dochandle_t s_handle, char *source_zone,
2722 	zone_dochandle_t t_handle, char *target_zone)
2723 {
2724 	int err;
2725 	struct zone_dstab s_dstab;
2726 	struct zone_dstab t_dstab;
2727 
2728 	if ((err = zonecfg_setdsent(t_handle)) != Z_OK) {
2729 		errno = err;
2730 		zperror2(target_zone, gettext("could not enumerate datasets"));
2731 		return;
2732 	}
2733 
2734 	while (zonecfg_getdsent(t_handle, &t_dstab) == Z_OK) {
2735 		if ((err = zonecfg_setdsent(s_handle)) != Z_OK) {
2736 			errno = err;
2737 			zperror2(source_zone,
2738 			    gettext("could not enumerate datasets"));
2739 			(void) zonecfg_enddsent(t_handle);
2740 			return;
2741 		}
2742 
2743 		while (zonecfg_getdsent(s_handle, &s_dstab) == Z_OK) {
2744 			if (strcmp(t_dstab.zone_dataset_name,
2745 			    s_dstab.zone_dataset_name) == 0) {
2746 				(void) fprintf(stderr,
2747 				    gettext("WARNING: dataset '%s' "
2748 				    "is configured in both zones.\n"),
2749 				    t_dstab.zone_dataset_name);
2750 				break;
2751 			}
2752 		}
2753 		(void) zonecfg_enddsent(s_handle);
2754 	}
2755 
2756 	(void) zonecfg_enddsent(t_handle);
2757 }
2758 
2759 static int
2760 validate_clone(char *source_zone, char *target_zone)
2761 {
2762 	int err = Z_OK;
2763 	zone_dochandle_t s_handle;
2764 	zone_dochandle_t t_handle;
2765 
2766 	if ((t_handle = zonecfg_init_handle()) == NULL) {
2767 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
2768 		return (Z_ERR);
2769 	}
2770 	if ((err = zonecfg_get_handle(target_zone, t_handle)) != Z_OK) {
2771 		errno = err;
2772 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
2773 		zonecfg_fini_handle(t_handle);
2774 		return (Z_ERR);
2775 	}
2776 
2777 	if ((s_handle = zonecfg_init_handle()) == NULL) {
2778 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
2779 		zonecfg_fini_handle(t_handle);
2780 		return (Z_ERR);
2781 	}
2782 	if ((err = zonecfg_get_handle(source_zone, s_handle)) != Z_OK) {
2783 		errno = err;
2784 		zperror(cmd_to_str(CMD_CLONE), B_TRUE);
2785 		goto done;
2786 	}
2787 
2788 	/* verify new zone has same inherit-pkg-dirs */
2789 	err = valid_ipd_clone(s_handle, source_zone, t_handle, target_zone);
2790 
2791 	/* warn about imported fs's which are the same */
2792 	warn_fs_match(s_handle, source_zone, t_handle, target_zone);
2793 
2794 	/* warn about imported IP addresses which are the same */
2795 	warn_ip_match(s_handle, source_zone, t_handle, target_zone);
2796 
2797 	/* warn about imported devices which are the same */
2798 	warn_dev_match(s_handle, source_zone, t_handle, target_zone);
2799 
2800 	/* warn about imported datasets which are the same */
2801 	warn_dataset_match(s_handle, source_zone, t_handle, target_zone);
2802 
2803 done:
2804 	zonecfg_fini_handle(t_handle);
2805 	zonecfg_fini_handle(s_handle);
2806 
2807 	return ((err == Z_OK) ? Z_OK : Z_ERR);
2808 }
2809 
2810 static int
2811 copy_zone(char *src, char *dst)
2812 {
2813 	boolean_t out_null = B_FALSE;
2814 	int status;
2815 	int err;
2816 	char *outfile;
2817 	char cmdbuf[MAXPATHLEN * 2 + 128];
2818 
2819 	if ((outfile = tempnam("/var/log", "zone")) == NULL) {
2820 		outfile = "/dev/null";
2821 		out_null = B_TRUE;
2822 	}
2823 
2824 	(void) snprintf(cmdbuf, sizeof (cmdbuf),
2825 	    "cd %s && /usr/bin/find . -depth -print | "
2826 	    "/usr/bin/cpio -pdmuP@ %s > %s 2>&1",
2827 	    src, dst, outfile);
2828 
2829 	status = do_subproc(cmdbuf);
2830 
2831 	if ((err = subproc_status("copy", status)) != Z_OK) {
2832 		if (!out_null)
2833 			(void) fprintf(stderr, gettext("\nThe copy failed.\n"
2834 			    "More information can be found in %s\n"), outfile);
2835 		return (err);
2836 	}
2837 
2838 	if (!out_null)
2839 		(void) unlink(outfile);
2840 
2841 	return (Z_OK);
2842 }
2843 
2844 /*
2845  * Wait until the target_zone has booted to single-user.  Return Z_OK once
2846  * the zone has booted to that level or return Z_BAD_ZONE_STATE if the zone
2847  * has not booted to single-user after the timeout.
2848  */
2849 static int
2850 zone_wait_single_user()
2851 {
2852 	char cmdbuf[ZONENAME_MAX + 256];
2853 	int retry;
2854 
2855 	(void) snprintf(cmdbuf, sizeof (cmdbuf),
2856 	    "test \"`/usr/sbin/zlogin -S %s /usr/bin/svcprop -p "
2857 	    "restarter/state svc:/milestone/single-user:default 2>/dev/null`\" "
2858 	    "= \"online\"",
2859 	    target_zone);
2860 
2861 	for (retry = 0; retry < SINGLE_USER_RETRY; retry++) {
2862 		int status;
2863 
2864 		status = do_subproc(cmdbuf);
2865 		if (WIFEXITED(status)) {
2866 			if (WEXITSTATUS(status) == 0)
2867 				return (Z_OK);
2868 
2869 			(void) sleep(2);
2870 		} else {
2871 			return (Z_BAD_ZONE_STATE);
2872 		}
2873 	}
2874 
2875 	return (Z_BAD_ZONE_STATE);
2876 }
2877 
2878 
2879 /* ARGSUSED */
2880 int
2881 zfm_print(const char *p, void *r) {
2882 	zerror("  %s\n", p);
2883 	return (0);
2884 }
2885 
2886 static int
2887 clone_func(int argc, char *argv[])
2888 {
2889 	char cmdbuf[MAXPATHLEN];
2890 	char *source_zone = NULL;
2891 	int lockfd;
2892 	int err, arg;
2893 	char zonepath[MAXPATHLEN];
2894 	char source_zonepath[MAXPATHLEN];
2895 	int status;
2896 	zone_state_t state;
2897 	zone_entry_t *zent;
2898 	char *method = "copy";
2899 	char *boot_args[] = { "-s", NULL };
2900 	char *halt_args[] = { NULL };
2901 	struct stat unconfig_buf;
2902 	boolean_t revert;
2903 
2904 	if (zonecfg_in_alt_root()) {
2905 		zerror(gettext("cannot clone zone in alternate root"));
2906 		return (Z_ERR);
2907 	}
2908 
2909 	optind = 0;
2910 	if ((arg = getopt(argc, argv, "?m:")) != EOF) {
2911 		switch (arg) {
2912 		case '?':
2913 			sub_usage(SHELP_CLONE, CMD_CLONE);
2914 			return (optopt == '?' ? Z_OK : Z_USAGE);
2915 		case 'm':
2916 			method = optarg;
2917 			break;
2918 		default:
2919 			sub_usage(SHELP_CLONE, CMD_CLONE);
2920 			return (Z_USAGE);
2921 		}
2922 	}
2923 	if (argc != (optind + 1) || strcmp(method, "copy") != 0) {
2924 		sub_usage(SHELP_CLONE, CMD_CLONE);
2925 		return (Z_USAGE);
2926 	}
2927 	source_zone = argv[optind];
2928 	if (sanity_check(target_zone, CMD_CLONE, B_FALSE, B_TRUE) != Z_OK)
2929 		return (Z_ERR);
2930 	if (verify_details(CMD_CLONE) != Z_OK)
2931 		return (Z_ERR);
2932 
2933 	/*
2934 	 * We also need to do some extra validation on the source zone.
2935 	 */
2936 
2937 	if (strcmp(source_zone, GLOBAL_ZONENAME) == 0) {
2938 		zerror(gettext("%s operation is invalid for the global zone."),
2939 		    cmd_to_str(CMD_CLONE));
2940 		return (Z_ERR);
2941 	}
2942 
2943 	if (strncmp(source_zone, "SUNW", 4) == 0) {
2944 		zerror(gettext("%s operation is invalid for zones starting "
2945 		    "with SUNW."), cmd_to_str(CMD_CLONE));
2946 		return (Z_ERR);
2947 	}
2948 
2949 	zent = lookup_running_zone(source_zone);
2950 	if (zent != NULL) {
2951 		/* check whether the zone is ready or running */
2952 		if ((err = zone_get_state(zent->zname, &zent->zstate_num))
2953 		    != Z_OK) {
2954 			errno = err;
2955 			zperror2(zent->zname, gettext("could not get state"));
2956 			/* can't tell, so hedge */
2957 			zent->zstate_str = "ready/running";
2958 		} else {
2959 			zent->zstate_str = zone_state_str(zent->zstate_num);
2960 		}
2961 		zerror(gettext("%s operation is invalid for %s zones."),
2962 		    cmd_to_str(CMD_CLONE), zent->zstate_str);
2963 		return (Z_ERR);
2964 	}
2965 
2966 	if ((err = zone_get_state(source_zone, &state)) != Z_OK) {
2967 		errno = err;
2968 		zperror2(source_zone, gettext("could not get state"));
2969 		return (Z_ERR);
2970 	}
2971 	if (state != ZONE_STATE_INSTALLED) {
2972 		(void) fprintf(stderr,
2973 		    gettext("%s: zone %s is %s; %s is required.\n"),
2974 		    execname, source_zone, zone_state_str(state),
2975 		    zone_state_str(ZONE_STATE_INSTALLED));
2976 		return (Z_ERR);
2977 	}
2978 
2979 	/*
2980 	 * The source zone checks out ok, continue with the clone.
2981 	 */
2982 
2983 	if (validate_clone(source_zone, target_zone) != Z_OK)
2984 		return (Z_ERR);
2985 
2986 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
2987 		zerror(gettext("another %s may have an operation in progress."),
2988 		    "zoneadm");
2989 		return (Z_ERR);
2990 	}
2991 
2992 	if ((err = zone_get_zonepath(source_zone, source_zonepath,
2993 	    sizeof (source_zonepath))) != Z_OK) {
2994 		errno = err;
2995 		zperror2(source_zone, gettext("could not get zone path"));
2996 		goto done;
2997 	}
2998 
2999 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3000 	    != Z_OK) {
3001 		errno = err;
3002 		zperror2(target_zone, gettext("could not get zone path"));
3003 		goto done;
3004 	}
3005 
3006 	/* Don't clone the zone if anything is still mounted there */
3007 	if (zonecfg_find_mounts(source_zonepath, NULL, NULL)) {
3008 		zerror(gettext("These file-systems are mounted on "
3009 		    "subdirectories of %s.\n"), source_zonepath);
3010 		(void) zonecfg_find_mounts(source_zonepath, zfm_print, NULL);
3011 		err = Z_ERR;
3012 		goto done;
3013 	}
3014 
3015 	if ((err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE))
3016 	    != Z_OK) {
3017 		errno = err;
3018 		zperror2(target_zone, gettext("could not set state"));
3019 		goto done;
3020 	}
3021 
3022 	(void) printf(gettext("Cloning zonepath %s..."), source_zonepath);
3023 	(void) fflush(stdout);
3024 
3025 	if ((err = copy_zone(source_zonepath, zonepath)) != Z_OK)
3026 		goto done;
3027 
3028 	/*
3029 	 * We have to set the state of the zone to installed so that we
3030 	 * can boot it and sys-unconfig it from within the zone.  However,
3031 	 * if something fails during the boot/sys-unconfig, we want to set
3032 	 * the state back to incomplete.  We use the revert flag to keep
3033 	 * track of this.
3034 	 */
3035 	revert = B_TRUE;
3036 
3037 	if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
3038 		errno = err;
3039 		zperror2(target_zone, gettext("\ncould not set state"));
3040 		goto done;
3041 	}
3042 
3043 	/*
3044 	 * Check if the zone is already sys-unconfiged.  This saves us
3045 	 * the work of booting the zone so we can unconfigure it.
3046 	 */
3047 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "%s/root/etc/.UNCONFIGURED",
3048 	    zonepath);
3049 	if (stat(cmdbuf, &unconfig_buf) == -1) {
3050 		if ((err = boot_func(1, boot_args)) != Z_OK) {
3051 			errno = err;
3052 			zperror2(target_zone, gettext("\nCould not boot zone "
3053 			    "for sys-unconfig\n"));
3054 			goto done;
3055 		}
3056 
3057 		if ((err = zone_wait_single_user()) != Z_OK) {
3058 			errno = err;
3059 			zperror2(target_zone, gettext("\nCould not boot zone "
3060 			    "for sys-unconfig\n"));
3061 			(void) halt_func(0, halt_args);
3062 			goto done;
3063 		}
3064 
3065 		(void) snprintf(cmdbuf, sizeof (cmdbuf),
3066 		    "echo y | /usr/sbin/zlogin -S %s /usr/sbin/sys-unconfig",
3067 		    target_zone);
3068 
3069 		status = do_subproc(cmdbuf);
3070 		if ((err = subproc_status("sys-unconfig", status)) != Z_OK) {
3071 			errno = err;
3072 			zperror2(target_zone,
3073 			    gettext("\nsys-unconfig failed\n"));
3074 			/*
3075 			 * The sys-unconfig halts the zone but if it failed,
3076 			 * for some reason, we'll try to halt it now.
3077 			 */
3078 			(void) halt_func(0, halt_args);
3079 			goto done;
3080 		}
3081 	}
3082 
3083 	revert = B_FALSE;
3084 
3085 done:
3086 	(void) printf("\n");
3087 
3088 	if (revert)
3089 		(void) zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
3090 
3091 	release_lock_file(lockfd);
3092 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3093 }
3094 
3095 #define	RMCOMMAND	"/usr/bin/rm -rf"
3096 
3097 static int
3098 move_func(int argc, char *argv[])
3099 {
3100 	/* 6: "exec " and " " */
3101 	char cmdbuf[sizeof (RMCOMMAND) + MAXPATHLEN + 6];
3102 	char *new_zonepath = NULL;
3103 	int lockfd;
3104 	int err, arg;
3105 	char zonepath[MAXPATHLEN];
3106 	zone_dochandle_t handle;
3107 	boolean_t fast;
3108 	boolean_t revert;
3109 	struct stat zonepath_buf;
3110 	struct stat new_zonepath_buf;
3111 
3112 	if (zonecfg_in_alt_root()) {
3113 		zerror(gettext("cannot move zone in alternate root"));
3114 		return (Z_ERR);
3115 	}
3116 
3117 	optind = 0;
3118 	if ((arg = getopt(argc, argv, "?")) != EOF) {
3119 		switch (arg) {
3120 		case '?':
3121 			sub_usage(SHELP_MOVE, CMD_MOVE);
3122 			return (optopt == '?' ? Z_OK : Z_USAGE);
3123 		default:
3124 			sub_usage(SHELP_MOVE, CMD_MOVE);
3125 			return (Z_USAGE);
3126 		}
3127 	}
3128 	if (argc != (optind + 1)) {
3129 		sub_usage(SHELP_MOVE, CMD_MOVE);
3130 		return (Z_USAGE);
3131 	}
3132 	new_zonepath = argv[optind];
3133 	if (sanity_check(target_zone, CMD_MOVE, B_FALSE, B_TRUE) != Z_OK)
3134 		return (Z_ERR);
3135 	if (verify_details(CMD_MOVE) != Z_OK)
3136 		return (Z_ERR);
3137 
3138 	/*
3139 	 * Check out the new zonepath.  This has the side effect of creating
3140 	 * a directory for the new zonepath.  We depend on this later when we
3141 	 * stat to see if we are doing a cross file-system move or not.
3142 	 */
3143 	if (validate_zonepath(new_zonepath, CMD_MOVE) != Z_OK)
3144 		return (Z_ERR);
3145 
3146 	if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3147 	    != Z_OK) {
3148 		errno = err;
3149 		zperror2(target_zone, gettext("could not get zone path"));
3150 		return (Z_ERR);
3151 	}
3152 
3153 	if (stat(zonepath, &zonepath_buf) == -1) {
3154 		zperror(gettext("could not stat zone path"), B_FALSE);
3155 		return (Z_ERR);
3156 	}
3157 
3158 	if (stat(new_zonepath, &new_zonepath_buf) == -1) {
3159 		zperror(gettext("could not stat new zone path"), B_FALSE);
3160 		return (Z_ERR);
3161 	}
3162 
3163 	/* Don't move the zone if anything is still mounted there */
3164 	if (zonecfg_find_mounts(zonepath, NULL, NULL)) {
3165 		zerror(gettext("These file-systems are mounted on "
3166 		    "subdirectories of %s.\n"), zonepath);
3167 		(void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
3168 		return (Z_ERR);
3169 	}
3170 
3171 	/*
3172 	 * Check if we are moving in the same filesystem and can do a fast
3173 	 * move or if we are crossing filesystems and have to copy the data.
3174 	 */
3175 	fast = (zonepath_buf.st_dev == new_zonepath_buf.st_dev);
3176 
3177 	if ((handle = zonecfg_init_handle()) == NULL) {
3178 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
3179 		return (Z_ERR);
3180 	}
3181 
3182 	if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
3183 		errno = err;
3184 		zperror(cmd_to_str(CMD_MOVE), B_TRUE);
3185 		zonecfg_fini_handle(handle);
3186 		return (Z_ERR);
3187 	}
3188 
3189 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
3190 		zerror(gettext("another %s may have an operation in progress."),
3191 		    "zoneadm");
3192 		zonecfg_fini_handle(handle);
3193 		return (Z_ERR);
3194 	}
3195 
3196 	/*
3197 	 * We're making some file-system changes now so we have to clean up
3198 	 * the file-system before we are done.  This will either clean up the
3199 	 * new zonepath if the zonecfg update failed or it will clean up the
3200 	 * old zonepath if everything is ok.
3201 	 */
3202 	revert = B_TRUE;
3203 
3204 	if (fast) {
3205 		/* same filesystem, use rename for a quick move */
3206 
3207 		/*
3208 		 * Remove the new_zonepath directory that got created above
3209 		 * during the validation.  It gets in the way of the rename.
3210 		 */
3211 		if (rmdir(new_zonepath) != 0) {
3212 			zperror(gettext("could not rmdir new zone path"),
3213 			    B_FALSE);
3214 			zonecfg_fini_handle(handle);
3215 			release_lock_file(lockfd);
3216 			return (Z_ERR);
3217 		}
3218 
3219 		if (rename(zonepath, new_zonepath) != 0) {
3220 			/*
3221 			 * If this fails we don't need to do all of the
3222 			 * cleanup that happens for the rest of the code
3223 			 * so just return from this error.
3224 			 */
3225 			zperror(gettext("could not move zone"), B_FALSE);
3226 			zonecfg_fini_handle(handle);
3227 			release_lock_file(lockfd);
3228 			return (Z_ERR);
3229 		}
3230 
3231 	} else {
3232 		(void) printf(gettext(
3233 		    "Moving across file-systems; copying zonepath %s..."),
3234 		    zonepath);
3235 		(void) fflush(stdout);
3236 
3237 		err = copy_zone(zonepath, new_zonepath);
3238 
3239 		(void) printf("\n");
3240 		if (err != Z_OK)
3241 			goto done;
3242 	}
3243 
3244 	if ((err = zonecfg_set_zonepath(handle, new_zonepath)) != Z_OK) {
3245 		errno = err;
3246 		zperror(gettext("could not set new zonepath"), B_TRUE);
3247 		goto done;
3248 	}
3249 
3250 	if ((err = zonecfg_save(handle)) != Z_OK) {
3251 		errno = err;
3252 		zperror(gettext("zonecfg save failed"), B_TRUE);
3253 		goto done;
3254 	}
3255 
3256 	revert = B_FALSE;
3257 
3258 done:
3259 	zonecfg_fini_handle(handle);
3260 	release_lock_file(lockfd);
3261 
3262 	/*
3263 	 * Clean up the file-system based on how things went.  We either
3264 	 * clean up the new zonepath if the operation failed for some reason
3265 	 * or we clean up the old zonepath if everything is ok.
3266 	 */
3267 	if (revert) {
3268 		/* The zonecfg update failed, cleanup the new zonepath. */
3269 		if (fast) {
3270 			if (rename(new_zonepath, zonepath) != 0) {
3271 				zperror(gettext("could not restore zonepath"),
3272 				    B_FALSE);
3273 				/*
3274 				 * err is already != Z_OK since we're reverting
3275 				 */
3276 			}
3277 		} else {
3278 			int status;
3279 
3280 			(void) printf(gettext("Cleaning up zonepath %s..."),
3281 			    new_zonepath);
3282 			(void) fflush(stdout);
3283 
3284 			/*
3285 			 * "exec" the command so that the returned status is
3286 			 * that of rm and not the shell.
3287 			 */
3288 			(void) snprintf(cmdbuf, sizeof (cmdbuf),
3289 			    "exec " RMCOMMAND " %s", new_zonepath);
3290 
3291 			status = do_subproc(cmdbuf);
3292 
3293 			(void) printf("\n");
3294 
3295 			if ((err = subproc_status("rm", status)) != Z_OK) {
3296 				errno = err;
3297 				zperror(gettext("could not remove new "
3298 				    "zonepath"), B_TRUE);
3299 			} else {
3300 				/*
3301 				 * Because we're reverting we know the mainline
3302 				 * code failed but we just reused the err
3303 				 * variable so we reset it back to Z_ERR.
3304 				 */
3305 				err = Z_ERR;
3306 			}
3307 		}
3308 
3309 	} else {
3310 		/* The move was successful, cleanup the old zonepath. */
3311 		if (!fast) {
3312 			int status;
3313 
3314 			(void) printf(
3315 			    gettext("Cleaning up zonepath %s..."), zonepath);
3316 			(void) fflush(stdout);
3317 
3318 			/*
3319 			 * "exec" the command so that the returned status is
3320 			 * that of rm and not the shell.
3321 			 */
3322 			(void) snprintf(cmdbuf, sizeof (cmdbuf),
3323 			    "exec " RMCOMMAND " %s", zonepath);
3324 
3325 			status = do_subproc(cmdbuf);
3326 
3327 			(void) printf("\n");
3328 
3329 			if ((err = subproc_status("rm", status)) != Z_OK) {
3330 				errno = err;
3331 				zperror(gettext("could not remove zonepath"),
3332 				    B_TRUE);
3333 			}
3334 		}
3335 	}
3336 
3337 	return ((err == Z_OK) ? Z_OK : Z_ERR);
3338 }
3339 
3340 /*
3341  * On input, TRUE => yes, FALSE => no.
3342  * On return, TRUE => 1, FALSE => 0, could not ask => -1.
3343  */
3344 
3345 static int
3346 ask_yesno(boolean_t default_answer, const char *question)
3347 {
3348 	char line[64];	/* should be large enough to answer yes or no */
3349 
3350 	if (!isatty(STDIN_FILENO))
3351 		return (-1);
3352 	for (;;) {
3353 		(void) printf("%s (%s)? ", question,
3354 		    default_answer ? "[y]/n" : "y/[n]");
3355 		if (fgets(line, sizeof (line), stdin) == NULL ||
3356 		    line[0] == '\n')
3357 			return (default_answer ? 1 : 0);
3358 		if (tolower(line[0]) == 'y')
3359 			return (1);
3360 		if (tolower(line[0]) == 'n')
3361 			return (0);
3362 	}
3363 }
3364 
3365 static int
3366 uninstall_func(int argc, char *argv[])
3367 {
3368 	/* 6: "exec " and " " */
3369 	char cmdbuf[sizeof (RMCOMMAND) + MAXPATHLEN + 6];
3370 	char line[ZONENAME_MAX + 128];	/* Enough for "Are you sure ..." */
3371 	char rootpath[MAXPATHLEN], devpath[MAXPATHLEN];
3372 	boolean_t force = B_FALSE;
3373 	int lockfd, answer;
3374 	int err, arg;
3375 	int status;
3376 
3377 	if (zonecfg_in_alt_root()) {
3378 		zerror(gettext("cannot uninstall zone in alternate root"));
3379 		return (Z_ERR);
3380 	}
3381 
3382 	optind = 0;
3383 	while ((arg = getopt(argc, argv, "?F")) != EOF) {
3384 		switch (arg) {
3385 		case '?':
3386 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
3387 			return (optopt == '?' ? Z_OK : Z_USAGE);
3388 		case 'F':
3389 			force = B_TRUE;
3390 			break;
3391 		default:
3392 			sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
3393 			return (Z_USAGE);
3394 		}
3395 	}
3396 	if (argc > optind) {
3397 		sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
3398 		return (Z_USAGE);
3399 	}
3400 
3401 	if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE) != Z_OK)
3402 		return (Z_ERR);
3403 
3404 	if (!force) {
3405 		(void) snprintf(line, sizeof (line),
3406 		    gettext("Are you sure you want to %s zone %s"),
3407 		    cmd_to_str(CMD_UNINSTALL), target_zone);
3408 		if ((answer = ask_yesno(B_FALSE, line)) == 0) {
3409 			return (Z_OK);
3410 		} else if (answer == -1) {
3411 			zerror(gettext("Input not from terminal and -F "
3412 			    "not specified: %s not done."),
3413 			    cmd_to_str(CMD_UNINSTALL));
3414 			return (Z_ERR);
3415 		}
3416 	}
3417 
3418 	if ((err = zone_get_zonepath(target_zone, devpath,
3419 	    sizeof (devpath))) != Z_OK) {
3420 		errno = err;
3421 		zperror2(target_zone, gettext("could not get zone path"));
3422 		return (Z_ERR);
3423 	}
3424 	(void) strlcat(devpath, "/dev", sizeof (devpath));
3425 	if ((err = zone_get_rootpath(target_zone, rootpath,
3426 	    sizeof (rootpath))) != Z_OK) {
3427 		errno = err;
3428 		zperror2(target_zone, gettext("could not get root path"));
3429 		return (Z_ERR);
3430 	}
3431 
3432 	/*
3433 	 * If there seems to be a zoneadmd running for this zone, call it
3434 	 * to tell it that an uninstall is happening; if all goes well it
3435 	 * will then shut itself down.
3436 	 */
3437 	if (ping_zoneadmd(target_zone) == Z_OK) {
3438 		zone_cmd_arg_t zarg;
3439 		zarg.cmd = Z_NOTE_UNINSTALLING;
3440 		/* we don't care too much if this fails... just plow on */
3441 		(void) call_zoneadmd(target_zone, &zarg);
3442 	}
3443 
3444 	if (grab_lock_file(target_zone, &lockfd) != Z_OK) {
3445 		zerror(gettext("another %s may have an operation in progress."),
3446 		    "zoneadm");
3447 		return (Z_ERR);
3448 	}
3449 
3450 	/* Don't uninstall the zone if anything is mounted there */
3451 	err = zonecfg_find_mounts(rootpath, NULL, NULL);
3452 	if (err) {
3453 		zerror(gettext("These file-systems are mounted on "
3454 			"subdirectories of %s.\n"), rootpath);
3455 		(void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
3456 		return (Z_ERR);
3457 	}
3458 
3459 	err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
3460 	if (err != Z_OK) {
3461 		errno = err;
3462 		zperror2(target_zone, gettext("could not set state"));
3463 		goto bad;
3464 	}
3465 
3466 	/*
3467 	 * "exec" the command so that the returned status is that of
3468 	 * RMCOMMAND and not the shell.
3469 	 */
3470 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
3471 	    devpath);
3472 	status = do_subproc(cmdbuf);
3473 	if ((err = subproc_status(RMCOMMAND, status)) != Z_OK)
3474 		goto bad;
3475 	(void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
3476 	    rootpath);
3477 	status = do_subproc(cmdbuf);
3478 	if ((err = subproc_status(RMCOMMAND, status)) != Z_OK)
3479 		goto bad;
3480 	err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
3481 	if (err != Z_OK) {
3482 		errno = err;
3483 		zperror2(target_zone, gettext("could not reset state"));
3484 	}
3485 bad:
3486 	release_lock_file(lockfd);
3487 	return (err);
3488 }
3489 
3490 /* ARGSUSED */
3491 static int
3492 mount_func(int argc, char *argv[])
3493 {
3494 	zone_cmd_arg_t zarg;
3495 
3496 	if (argc > 0)
3497 		return (Z_USAGE);
3498 	if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE) != Z_OK)
3499 		return (Z_ERR);
3500 	if (verify_details(CMD_MOUNT) != Z_OK)
3501 		return (Z_ERR);
3502 
3503 	zarg.cmd = Z_MOUNT;
3504 	if (call_zoneadmd(target_zone, &zarg) != 0) {
3505 		zerror(gettext("call to %s failed"), "zoneadmd");
3506 		return (Z_ERR);
3507 	}
3508 	return (Z_OK);
3509 }
3510 
3511 /* ARGSUSED */
3512 static int
3513 unmount_func(int argc, char *argv[])
3514 {
3515 	zone_cmd_arg_t zarg;
3516 
3517 	if (argc > 0)
3518 		return (Z_USAGE);
3519 	if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE) != Z_OK)
3520 		return (Z_ERR);
3521 
3522 	zarg.cmd = Z_UNMOUNT;
3523 	if (call_zoneadmd(target_zone, &zarg) != 0) {
3524 		zerror(gettext("call to %s failed"), "zoneadmd");
3525 		return (Z_ERR);
3526 	}
3527 	return (Z_OK);
3528 }
3529 
3530 static int
3531 help_func(int argc, char *argv[])
3532 {
3533 	int arg, cmd_num;
3534 
3535 	if (argc == 0) {
3536 		(void) usage(B_TRUE);
3537 		return (Z_OK);
3538 	}
3539 	optind = 0;
3540 	if ((arg = getopt(argc, argv, "?")) != EOF) {
3541 		switch (arg) {
3542 		case '?':
3543 			sub_usage(SHELP_HELP, CMD_HELP);
3544 			return (optopt == '?' ? Z_OK : Z_USAGE);
3545 		default:
3546 			sub_usage(SHELP_HELP, CMD_HELP);
3547 			return (Z_USAGE);
3548 		}
3549 	}
3550 	while (optind < argc) {
3551 		/* Private commands have NULL short_usage; omit them */
3552 		if ((cmd_num = cmd_match(argv[optind])) < 0 ||
3553 		    cmdtab[cmd_num].short_usage == NULL) {
3554 			sub_usage(SHELP_HELP, CMD_HELP);
3555 			return (Z_USAGE);
3556 		}
3557 		sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
3558 		optind++;
3559 	}
3560 	return (Z_OK);
3561 }
3562 
3563 /*
3564  * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
3565  */
3566 
3567 static int
3568 cmd_match(char *cmd)
3569 {
3570 	int i;
3571 
3572 	for (i = CMD_MIN; i <= CMD_MAX; i++) {
3573 		/* return only if there is an exact match */
3574 		if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
3575 			return (cmdtab[i].cmd_num);
3576 	}
3577 	return (-1);
3578 }
3579 
3580 static int
3581 parse_and_run(int argc, char *argv[])
3582 {
3583 	int i = cmd_match(argv[0]);
3584 
3585 	if (i < 0)
3586 		return (usage(B_FALSE));
3587 	return (cmdtab[i].handler(argc - 1, &(argv[1])));
3588 }
3589 
3590 static char *
3591 get_execbasename(char *execfullname)
3592 {
3593 	char *last_slash, *execbasename;
3594 
3595 	/* guard against '/' at end of command invocation */
3596 	for (;;) {
3597 		last_slash = strrchr(execfullname, '/');
3598 		if (last_slash == NULL) {
3599 			execbasename = execfullname;
3600 			break;
3601 		} else {
3602 			execbasename = last_slash + 1;
3603 			if (*execbasename == '\0') {
3604 				*last_slash = '\0';
3605 				continue;
3606 			}
3607 			break;
3608 		}
3609 	}
3610 	return (execbasename);
3611 }
3612 
3613 int
3614 main(int argc, char **argv)
3615 {
3616 	int arg;
3617 	zoneid_t zid;
3618 	struct stat st;
3619 
3620 	if ((locale = setlocale(LC_ALL, "")) == NULL)
3621 		locale = "C";
3622 	(void) textdomain(TEXT_DOMAIN);
3623 	setbuf(stdout, NULL);
3624 	(void) sigset(SIGHUP, SIG_IGN);
3625 	execname = get_execbasename(argv[0]);
3626 	target_zone = NULL;
3627 	if (chdir("/") != 0) {
3628 		zerror(gettext("could not change directory to /."));
3629 		exit(Z_ERR);
3630 	}
3631 
3632 	while ((arg = getopt(argc, argv, "?z:R:")) != EOF) {
3633 		switch (arg) {
3634 		case '?':
3635 			return (usage(B_TRUE));
3636 		case 'z':
3637 			target_zone = optarg;
3638 			break;
3639 		case 'R':	/* private option for admin/install use */
3640 			if (*optarg != '/') {
3641 				zerror(gettext("root path must be absolute."));
3642 				exit(Z_ERR);
3643 			}
3644 			if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
3645 				zerror(
3646 				    gettext("root path must be a directory."));
3647 				exit(Z_ERR);
3648 			}
3649 			zonecfg_set_root(optarg);
3650 			break;
3651 		default:
3652 			return (usage(B_FALSE));
3653 		}
3654 	}
3655 
3656 	if (optind >= argc)
3657 		return (usage(B_FALSE));
3658 	if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
3659 		errno = Z_NO_ZONE;
3660 		zperror(target_zone, B_TRUE);
3661 		exit(Z_ERR);
3662 	}
3663 	return (parse_and_run(argc - optind, &argv[optind]));
3664 }
3665