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