xref: /titanic_41/usr/src/cmd/zoneadmd/vplat.c (revision d89fccd8788afe1e920f842edd883fe192a1b8fe)
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 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * This module contains functions used to bring up and tear down the
31  * Virtual Platform: [un]mounting file-systems, [un]plumbing network
32  * interfaces, [un]configuring devices, establishing resource controls,
33  * and creating/destroying the zone in the kernel.  These actions, on
34  * the way up, ready the zone; on the way down, they halt the zone.
35  * See the much longer block comment at the beginning of zoneadmd.c
36  * for a bigger picture of how the whole program functions.
37  *
38  * This module also has primary responsibility for the layout of "scratch
39  * zones."  These are mounted, but inactive, zones that are used during
40  * operating system upgrade and potentially other administrative action.  The
41  * scratch zone environment is similar to the miniroot environment.  The zone's
42  * actual root is mounted read-write on /a, and the standard paths (/usr,
43  * /sbin, /lib) all lead to read-only copies of the running system's binaries.
44  * This allows the administrative tools to manipulate the zone using "-R /a"
45  * without relying on any binaries in the zone itself.
46  *
47  * If the scratch zone is on an alternate root (Live Upgrade [LU] boot
48  * environment), then we must resolve the lofs mounts used there to uncover
49  * writable (unshared) resources.  Shared resources, though, are always
50  * read-only.  In addition, if the "same" zone with a different root path is
51  * currently running, then "/b" inside the zone points to the running zone's
52  * root.  This allows LU to synchronize configuration files during the upgrade
53  * process.
54  *
55  * To construct this environment, this module creates a tmpfs mount on
56  * $ZONEPATH/lu.  Inside this scratch area, the miniroot-like environment as
57  * described above is constructed on the fly.  The zone is then created using
58  * $ZONEPATH/lu as the root.
59  *
60  * Note that scratch zones are inactive.  The zone's bits are not running and
61  * likely cannot be run correctly until upgrade is done.  Init is not running
62  * there, nor is SMF.  Because of this, the "mounted" state of a scratch zone
63  * is not a part of the usual halt/ready/boot state machine.
64  */
65 
66 #include <sys/param.h>
67 #include <sys/mount.h>
68 #include <sys/mntent.h>
69 #include <sys/socket.h>
70 #include <sys/utsname.h>
71 #include <sys/types.h>
72 #include <sys/stat.h>
73 #include <sys/sockio.h>
74 #include <sys/stropts.h>
75 #include <sys/conf.h>
76 
77 #include <inet/tcp.h>
78 #include <arpa/inet.h>
79 #include <netinet/in.h>
80 #include <net/route.h>
81 #include <netdb.h>
82 
83 #include <stdio.h>
84 #include <errno.h>
85 #include <fcntl.h>
86 #include <unistd.h>
87 #include <rctl.h>
88 #include <stdlib.h>
89 #include <string.h>
90 #include <strings.h>
91 #include <wait.h>
92 #include <limits.h>
93 #include <libgen.h>
94 #include <libzfs.h>
95 #include <zone.h>
96 #include <assert.h>
97 
98 #include <sys/mntio.h>
99 #include <sys/mnttab.h>
100 #include <sys/fs/autofs.h>	/* for _autofssys() */
101 #include <sys/fs/lofs_info.h>
102 #include <sys/fs/zfs.h>
103 
104 #include <pool.h>
105 #include <sys/pool.h>
106 
107 #include <libzonecfg.h>
108 #include "zoneadmd.h"
109 #include <tsol/label.h>
110 #include <libtsnet.h>
111 #include <sys/priv.h>
112 
113 #define	V4_ADDR_LEN	32
114 #define	V6_ADDR_LEN	128
115 
116 /* 0755 is the default directory mode. */
117 #define	DEFAULT_DIR_MODE \
118 	(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
119 
120 #define	IPD_DEFAULT_OPTS \
121 	MNTOPT_RO "," MNTOPT_LOFS_NOSUB "," MNTOPT_NODEVICES
122 
123 #define	DFSTYPES	"/etc/dfs/fstypes"
124 #define	MAXTNZLEN	2048
125 
126 /*
127  * A list of directories which should be created.
128  */
129 
130 struct dir_info {
131 	char *dir_name;
132 	mode_t dir_mode;
133 };
134 
135 /*
136  * The pathnames below are relative to the zonepath
137  */
138 static struct dir_info dev_dirs[] = {
139 	{ "/dev",	0755 },
140 	{ "/dev/dsk",	0755 },
141 	{ "/dev/fd",	0555 },
142 	{ "/dev/pts",	0755 },
143 	{ "/dev/rdsk",	0755 },
144 	{ "/dev/rmt",	0755 },
145 	{ "/dev/sad",	0755 },
146 	{ "/dev/swap",	0755 },
147 	{ "/dev/term",	0755 },
148 };
149 
150 /*
151  * A list of devices which should be symlinked to /dev/zconsole.
152  */
153 
154 struct symlink_info {
155 	char *sl_source;
156 	char *sl_target;
157 };
158 
159 /*
160  * The "source" paths are relative to the zonepath
161  */
162 static struct symlink_info dev_symlinks[] = {
163 	{ "/dev/stderr",	"./fd/2" },
164 	{ "/dev/stdin",		"./fd/0" },
165 	{ "/dev/stdout",	"./fd/1" },
166 	{ "/dev/dtremote",	"/dev/null" },
167 	{ "/dev/console",	"zconsole" },
168 	{ "/dev/syscon",	"zconsole" },
169 	{ "/dev/sysmsg",	"zconsole" },
170 	{ "/dev/systty",	"zconsole" },
171 	{ "/dev/msglog",	"zconsole" },
172 };
173 
174 /* for routing socket */
175 static int rts_seqno = 0;
176 
177 /* mangled zone name when mounting in an alternate root environment */
178 static char kernzone[ZONENAME_MAX];
179 
180 /* array of cached mount entries for resolve_lofs */
181 static struct mnttab *resolve_lofs_mnts, *resolve_lofs_mnt_max;
182 
183 /* for Trusted Extensions */
184 static tsol_zcent_t *get_zone_label(zlog_t *, priv_set_t *);
185 static int tsol_mounts(zlog_t *, char *, char *);
186 static void tsol_unmounts(zlog_t *, char *);
187 static m_label_t *zlabel = NULL;
188 static m_label_t *zid_label = NULL;
189 static priv_set_t *zprivs = NULL;
190 
191 /* from libsocket, not in any header file */
192 extern int getnetmaskbyaddr(struct in_addr, struct in_addr *);
193 
194 /*
195  * An optimization for build_mnttable: reallocate (and potentially copy the
196  * data) only once every N times through the loop.
197  */
198 #define	MNTTAB_HUNK	32
199 
200 /*
201  * Private autofs system call
202  */
203 extern int _autofssys(int, void *);
204 
205 static int
206 autofs_cleanup(zoneid_t zoneid)
207 {
208 	/*
209 	 * Ask autofs to unmount all trigger nodes in the given zone.
210 	 */
211 	return (_autofssys(AUTOFS_UNMOUNTALL, (void *)zoneid));
212 }
213 
214 static void
215 free_mnttable(struct mnttab *mnt_array, uint_t nelem)
216 {
217 	uint_t i;
218 
219 	if (mnt_array == NULL)
220 		return;
221 	for (i = 0; i < nelem; i++) {
222 		free(mnt_array[i].mnt_mountp);
223 		free(mnt_array[i].mnt_fstype);
224 		free(mnt_array[i].mnt_special);
225 		free(mnt_array[i].mnt_mntopts);
226 		assert(mnt_array[i].mnt_time == NULL);
227 	}
228 	free(mnt_array);
229 }
230 
231 /*
232  * Build the mount table for the zone rooted at "zroot", storing the resulting
233  * array of struct mnttabs in "mnt_arrayp" and the number of elements in the
234  * array in "nelemp".
235  */
236 static int
237 build_mnttable(zlog_t *zlogp, const char *zroot, size_t zrootlen, FILE *mnttab,
238     struct mnttab **mnt_arrayp, uint_t *nelemp)
239 {
240 	struct mnttab mnt;
241 	struct mnttab *mnts;
242 	struct mnttab *mnp;
243 	uint_t nmnt;
244 
245 	rewind(mnttab);
246 	resetmnttab(mnttab);
247 	nmnt = 0;
248 	mnts = NULL;
249 	while (getmntent(mnttab, &mnt) == 0) {
250 		struct mnttab *tmp_array;
251 
252 		if (strncmp(mnt.mnt_mountp, zroot, zrootlen) != 0)
253 			continue;
254 		if (nmnt % MNTTAB_HUNK == 0) {
255 			tmp_array = realloc(mnts,
256 			    (nmnt + MNTTAB_HUNK) * sizeof (*mnts));
257 			if (tmp_array == NULL) {
258 				free_mnttable(mnts, nmnt);
259 				return (-1);
260 			}
261 			mnts = tmp_array;
262 		}
263 		mnp = &mnts[nmnt++];
264 
265 		/*
266 		 * Zero out any fields we're not using.
267 		 */
268 		(void) memset(mnp, 0, sizeof (*mnp));
269 
270 		if (mnt.mnt_special != NULL)
271 			mnp->mnt_special = strdup(mnt.mnt_special);
272 		if (mnt.mnt_mntopts != NULL)
273 			mnp->mnt_mntopts = strdup(mnt.mnt_mntopts);
274 		mnp->mnt_mountp = strdup(mnt.mnt_mountp);
275 		mnp->mnt_fstype = strdup(mnt.mnt_fstype);
276 		if ((mnt.mnt_special != NULL && mnp->mnt_special == NULL) ||
277 		    (mnt.mnt_mntopts != NULL && mnp->mnt_mntopts == NULL) ||
278 		    mnp->mnt_mountp == NULL || mnp->mnt_fstype == NULL) {
279 			zerror(zlogp, B_TRUE, "memory allocation failed");
280 			free_mnttable(mnts, nmnt);
281 			return (-1);
282 		}
283 	}
284 	*mnt_arrayp = mnts;
285 	*nelemp = nmnt;
286 	return (0);
287 }
288 
289 /*
290  * This is an optimization.  The resolve_lofs function is used quite frequently
291  * to manipulate file paths, and on a machine with a large number of zones,
292  * there will be a huge number of mounted file systems.  Thus, we trigger a
293  * reread of the list of mount points
294  */
295 static void
296 lofs_discard_mnttab(void)
297 {
298 	free_mnttable(resolve_lofs_mnts,
299 	    resolve_lofs_mnt_max - resolve_lofs_mnts);
300 	resolve_lofs_mnts = resolve_lofs_mnt_max = NULL;
301 }
302 
303 static int
304 lofs_read_mnttab(zlog_t *zlogp)
305 {
306 	FILE *mnttab;
307 	uint_t nmnts;
308 
309 	if ((mnttab = fopen(MNTTAB, "r")) == NULL)
310 		return (-1);
311 	if (build_mnttable(zlogp, "", 0, mnttab, &resolve_lofs_mnts,
312 	    &nmnts) == -1) {
313 		(void) fclose(mnttab);
314 		return (-1);
315 	}
316 	(void) fclose(mnttab);
317 	resolve_lofs_mnt_max = resolve_lofs_mnts + nmnts;
318 	return (0);
319 }
320 
321 /*
322  * This function loops over potential loopback mounts and symlinks in a given
323  * path and resolves them all down to an absolute path.
324  */
325 static void
326 resolve_lofs(zlog_t *zlogp, char *path, size_t pathlen)
327 {
328 	int len, arlen;
329 	const char *altroot;
330 	char tmppath[MAXPATHLEN];
331 	boolean_t outside_altroot;
332 
333 	if ((len = resolvepath(path, tmppath, sizeof (tmppath))) == -1)
334 		return;
335 	tmppath[len] = '\0';
336 	(void) strlcpy(path, tmppath, sizeof (tmppath));
337 
338 	/* This happens once per zoneadmd operation. */
339 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
340 		return;
341 
342 	altroot = zonecfg_get_root();
343 	arlen = strlen(altroot);
344 	outside_altroot = B_FALSE;
345 	for (;;) {
346 		struct mnttab *mnp;
347 
348 		for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
349 		    mnp++) {
350 			if (mnp->mnt_fstype == NULL ||
351 			    mnp->mnt_mountp == NULL ||
352 			    mnp->mnt_special == NULL ||
353 			    strcmp(mnp->mnt_fstype, MNTTYPE_LOFS) != 0)
354 				continue;
355 			len = strlen(mnp->mnt_mountp);
356 			if (strncmp(mnp->mnt_mountp, path, len) == 0 &&
357 			    (path[len] == '/' || path[len] == '\0'))
358 				break;
359 		}
360 		if (mnp >= resolve_lofs_mnt_max)
361 			break;
362 		if (outside_altroot) {
363 			char *cp;
364 			int olen = sizeof (MNTOPT_RO) - 1;
365 
366 			/*
367 			 * If we run into a read-only mount outside of the
368 			 * alternate root environment, then the user doesn't
369 			 * want this path to be made read-write.
370 			 */
371 			if (mnp->mnt_mntopts != NULL &&
372 			    (cp = strstr(mnp->mnt_mntopts, MNTOPT_RO)) !=
373 			    NULL &&
374 			    (cp == mnp->mnt_mntopts || cp[-1] == ',') &&
375 			    (cp[olen] == '\0' || cp[olen] == ',')) {
376 				break;
377 			}
378 		} else if (arlen > 0 &&
379 		    (strncmp(mnp->mnt_special, altroot, arlen) != 0 ||
380 		    (mnp->mnt_special[arlen] != '\0' &&
381 		    mnp->mnt_special[arlen] != '/'))) {
382 			outside_altroot = B_TRUE;
383 		}
384 		/* use temporary buffer because new path might be longer */
385 		(void) snprintf(tmppath, sizeof (tmppath), "%s%s",
386 		    mnp->mnt_special, path + len);
387 		if ((len = resolvepath(tmppath, path, pathlen)) == -1)
388 			break;
389 		path[len] = '\0';
390 	}
391 }
392 
393 /*
394  * For a regular mount, check if a replacement lofs mount is needed because the
395  * referenced device is already mounted somewhere.
396  */
397 static int
398 check_lofs_needed(zlog_t *zlogp, struct zone_fstab *fsptr)
399 {
400 	struct mnttab *mnp;
401 	zone_fsopt_t *optptr, *onext;
402 
403 	/* This happens once per zoneadmd operation. */
404 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
405 		return (-1);
406 
407 	/*
408 	 * If this special node isn't already in use, then it's ours alone;
409 	 * no need to worry about conflicting mounts.
410 	 */
411 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
412 	    mnp++) {
413 		if (strcmp(mnp->mnt_special, fsptr->zone_fs_special) == 0)
414 			break;
415 	}
416 	if (mnp >= resolve_lofs_mnt_max)
417 		return (0);
418 
419 	/*
420 	 * Convert this duplicate mount into a lofs mount.
421 	 */
422 	(void) strlcpy(fsptr->zone_fs_special, mnp->mnt_mountp,
423 	    sizeof (fsptr->zone_fs_special));
424 	(void) strlcpy(fsptr->zone_fs_type, MNTTYPE_LOFS,
425 	    sizeof (fsptr->zone_fs_type));
426 	fsptr->zone_fs_raw[0] = '\0';
427 
428 	/*
429 	 * Discard all but one of the original options and set that to be the
430 	 * same set of options used for inherit package directory resources.
431 	 */
432 	optptr = fsptr->zone_fs_options;
433 	if (optptr == NULL) {
434 		optptr = malloc(sizeof (*optptr));
435 		if (optptr == NULL) {
436 			zerror(zlogp, B_TRUE, "cannot mount %s",
437 			    fsptr->zone_fs_dir);
438 			return (-1);
439 		}
440 	} else {
441 		while ((onext = optptr->zone_fsopt_next) != NULL) {
442 			optptr->zone_fsopt_next = onext->zone_fsopt_next;
443 			free(onext);
444 		}
445 	}
446 	(void) strcpy(optptr->zone_fsopt_opt, IPD_DEFAULT_OPTS);
447 	optptr->zone_fsopt_next = NULL;
448 	fsptr->zone_fs_options = optptr;
449 	return (0);
450 }
451 
452 static int
453 make_one_dir(zlog_t *zlogp, const char *prefix, const char *subdir, mode_t mode)
454 {
455 	char path[MAXPATHLEN];
456 	struct stat st;
457 
458 	if (snprintf(path, sizeof (path), "%s%s", prefix, subdir) >
459 	    sizeof (path)) {
460 		zerror(zlogp, B_FALSE, "pathname %s%s is too long", prefix,
461 		    subdir);
462 		return (-1);
463 	}
464 
465 	if (lstat(path, &st) == 0) {
466 		/*
467 		 * We don't check the file mode since presumably the zone
468 		 * administrator may have had good reason to change the mode,
469 		 * and we don't need to second guess him.
470 		 */
471 		if (!S_ISDIR(st.st_mode)) {
472 			if (is_system_labeled() &&
473 			    S_ISREG(st.st_mode)) {
474 				/*
475 				 * The need to mount readonly copies of
476 				 * global zone /etc/ files is unique to
477 				 * Trusted Extensions.
478 				 */
479 				if (strncmp(subdir, "/etc/",
480 				    strlen("/etc/")) != 0) {
481 					zerror(zlogp, B_FALSE,
482 					    "%s is not in /etc", path);
483 					return (-1);
484 				}
485 			} else {
486 				zerror(zlogp, B_FALSE,
487 				    "%s is not a directory", path);
488 				return (-1);
489 			}
490 		}
491 	} else if (mkdirp(path, mode) != 0) {
492 		if (errno == EROFS)
493 			zerror(zlogp, B_FALSE, "Could not mkdir %s.\nIt is on "
494 			    "a read-only file system in this local zone.\nMake "
495 			    "sure %s exists in the global zone.", path, subdir);
496 		else
497 			zerror(zlogp, B_TRUE, "mkdirp of %s failed", path);
498 		return (-1);
499 	}
500 	return (0);
501 }
502 
503 /*
504  * Make /dev and various directories underneath it.
505  */
506 static int
507 make_dev_dirs(zlog_t *zlogp, const char *zonepath)
508 {
509 	int i;
510 
511 	for (i = 0; i < sizeof (dev_dirs) / sizeof (struct dir_info); i++) {
512 		if (make_one_dir(zlogp, zonepath, dev_dirs[i].dir_name,
513 		    dev_dirs[i].dir_mode) != 0)
514 			return (-1);
515 	}
516 	return (0);
517 }
518 
519 /*
520  * Make various sym-links underneath /dev.
521  */
522 static int
523 make_dev_links(zlog_t *zlogp, char *zonepath)
524 {
525 	int i;
526 
527 	for (i = 0; i < sizeof (dev_symlinks) / sizeof (struct symlink_info);
528 	    i++) {
529 		char dev[MAXPATHLEN];
530 		struct stat st;
531 
532 		(void) snprintf(dev, sizeof (dev), "%s%s", zonepath,
533 		    dev_symlinks[i].sl_source);
534 		if (lstat(dev, &st) == 0) {
535 			/*
536 			 * Try not to call unlink(2) on directories, since that
537 			 * makes UFS unhappy.
538 			 */
539 			if (S_ISDIR(st.st_mode)) {
540 				zerror(zlogp, B_FALSE, "symlink path %s is a "
541 				    "directory", dev_symlinks[i].sl_source);
542 				return (-1);
543 			}
544 			(void) unlink(dev);
545 		}
546 		if (symlink(dev_symlinks[i].sl_target, dev) != 0) {
547 			zerror(zlogp, B_TRUE, "could not setup %s->%s symlink",
548 			    dev_symlinks[i].sl_source,
549 			    dev_symlinks[i].sl_target);
550 			return (-1);
551 		}
552 	}
553 	return (0);
554 }
555 
556 /*
557  * Create various directories and sym-links under /dev.
558  */
559 static int
560 create_dev_files(zlog_t *zlogp)
561 {
562 	char zonepath[MAXPATHLEN];
563 
564 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
565 		zerror(zlogp, B_TRUE, "unable to determine zone root");
566 		return (-1);
567 	}
568 	if (zonecfg_in_alt_root())
569 		resolve_lofs(zlogp, zonepath, sizeof (zonepath));
570 
571 	if (make_dev_dirs(zlogp, zonepath) != 0)
572 		return (-1);
573 	if (make_dev_links(zlogp, zonepath) != 0)
574 		return (-1);
575 	return (0);
576 }
577 
578 static void
579 free_remote_fstypes(char **types)
580 {
581 	uint_t i;
582 
583 	if (types == NULL)
584 		return;
585 	for (i = 0; types[i] != NULL; i++)
586 		free(types[i]);
587 	free(types);
588 }
589 
590 static char **
591 get_remote_fstypes(zlog_t *zlogp)
592 {
593 	char **types = NULL;
594 	FILE *fp;
595 	char buf[MAXPATHLEN];
596 	char fstype[MAXPATHLEN];
597 	uint_t lines = 0;
598 	uint_t i;
599 
600 	if ((fp = fopen(DFSTYPES, "r")) == NULL) {
601 		zerror(zlogp, B_TRUE, "failed to open %s", DFSTYPES);
602 		return (NULL);
603 	}
604 	/*
605 	 * Count the number of lines
606 	 */
607 	while (fgets(buf, sizeof (buf), fp) != NULL)
608 		lines++;
609 	if (lines == 0)	/* didn't read anything; empty file */
610 		goto out;
611 	rewind(fp);
612 	/*
613 	 * Allocate enough space for a NULL-terminated array.
614 	 */
615 	types = calloc(lines + 1, sizeof (char *));
616 	if (types == NULL) {
617 		zerror(zlogp, B_TRUE, "memory allocation failed");
618 		goto out;
619 	}
620 	i = 0;
621 	while (fgets(buf, sizeof (buf), fp) != NULL) {
622 		/* LINTED - fstype is big enough to hold buf */
623 		if (sscanf(buf, "%s", fstype) == 0) {
624 			zerror(zlogp, B_FALSE, "unable to parse %s", DFSTYPES);
625 			free_remote_fstypes(types);
626 			types = NULL;
627 			goto out;
628 		}
629 		types[i] = strdup(fstype);
630 		if (types[i] == NULL) {
631 			zerror(zlogp, B_TRUE, "memory allocation failed");
632 			free_remote_fstypes(types);
633 			types = NULL;
634 			goto out;
635 		}
636 		i++;
637 	}
638 out:
639 	(void) fclose(fp);
640 	return (types);
641 }
642 
643 static boolean_t
644 is_remote_fstype(const char *fstype, char *const *remote_fstypes)
645 {
646 	uint_t i;
647 
648 	if (remote_fstypes == NULL)
649 		return (B_FALSE);
650 	for (i = 0; remote_fstypes[i] != NULL; i++) {
651 		if (strcmp(remote_fstypes[i], fstype) == 0)
652 			return (B_TRUE);
653 	}
654 	return (B_FALSE);
655 }
656 
657 /*
658  * This converts a zone root path (normally of the form .../root) to a Live
659  * Upgrade scratch zone root (of the form .../lu).
660  */
661 static void
662 root_to_lu(zlog_t *zlogp, char *zroot, size_t zrootlen, boolean_t isresolved)
663 {
664 	if (!isresolved && zonecfg_in_alt_root())
665 		resolve_lofs(zlogp, zroot, zrootlen);
666 	(void) strcpy(strrchr(zroot, '/') + 1, "lu");
667 }
668 
669 /*
670  * The general strategy for unmounting filesystems is as follows:
671  *
672  * - Remote filesystems may be dead, and attempting to contact them as
673  * part of a regular unmount may hang forever; we want to always try to
674  * forcibly unmount such filesystems and only fall back to regular
675  * unmounts if the filesystem doesn't support forced unmounts.
676  *
677  * - We don't want to unnecessarily corrupt metadata on local
678  * filesystems (ie UFS), so we want to start off with graceful unmounts,
679  * and only escalate to doing forced unmounts if we get stuck.
680  *
681  * We start off walking backwards through the mount table.  This doesn't
682  * give us strict ordering but ensures that we try to unmount submounts
683  * first.  We thus limit the number of failed umount2(2) calls.
684  *
685  * The mechanism for determining if we're stuck is to count the number
686  * of failed unmounts each iteration through the mount table.  This
687  * gives us an upper bound on the number of filesystems which remain
688  * mounted (autofs trigger nodes are dealt with separately).  If at the
689  * end of one unmount+autofs_cleanup cycle we still have the same number
690  * of mounts that we started out with, we're stuck and try a forced
691  * unmount.  If that fails (filesystem doesn't support forced unmounts)
692  * then we bail and are unable to teardown the zone.  If it succeeds,
693  * we're no longer stuck so we continue with our policy of trying
694  * graceful mounts first.
695  *
696  * Zone must be down (ie, no processes or threads active).
697  */
698 static int
699 unmount_filesystems(zlog_t *zlogp, zoneid_t zoneid, boolean_t unmount_cmd)
700 {
701 	int error = 0;
702 	FILE *mnttab;
703 	struct mnttab *mnts;
704 	uint_t nmnt;
705 	char zroot[MAXPATHLEN + 1];
706 	size_t zrootlen;
707 	uint_t oldcount = UINT_MAX;
708 	boolean_t stuck = B_FALSE;
709 	char **remote_fstypes = NULL;
710 
711 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
712 		zerror(zlogp, B_FALSE, "unable to determine zone root");
713 		return (-1);
714 	}
715 	if (unmount_cmd)
716 		root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
717 
718 	(void) strcat(zroot, "/");
719 	zrootlen = strlen(zroot);
720 
721 	/*
722 	 * For Trusted Extensions unmount each higher level zone's mount
723 	 * of our zone's /export/home
724 	 */
725 	if (!unmount_cmd)
726 		tsol_unmounts(zlogp, zone_name);
727 
728 	if ((mnttab = fopen(MNTTAB, "r")) == NULL) {
729 		zerror(zlogp, B_TRUE, "failed to open %s", MNTTAB);
730 		return (-1);
731 	}
732 	/*
733 	 * Use our hacky mntfs ioctl so we see everything, even mounts with
734 	 * MS_NOMNTTAB.
735 	 */
736 	if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0) {
737 		zerror(zlogp, B_TRUE, "unable to configure %s", MNTTAB);
738 		error++;
739 		goto out;
740 	}
741 
742 	/*
743 	 * Build the list of remote fstypes so we know which ones we
744 	 * should forcibly unmount.
745 	 */
746 	remote_fstypes = get_remote_fstypes(zlogp);
747 	for (; /* ever */; ) {
748 		uint_t newcount = 0;
749 		boolean_t unmounted;
750 		struct mnttab *mnp;
751 		char *path;
752 		uint_t i;
753 
754 		mnts = NULL;
755 		nmnt = 0;
756 		/*
757 		 * MNTTAB gives us a way to walk through mounted
758 		 * filesystems; we need to be able to walk them in
759 		 * reverse order, so we build a list of all mounted
760 		 * filesystems.
761 		 */
762 		if (build_mnttable(zlogp, zroot, zrootlen, mnttab, &mnts,
763 		    &nmnt) != 0) {
764 			error++;
765 			goto out;
766 		}
767 		for (i = 0; i < nmnt; i++) {
768 			mnp = &mnts[nmnt - i - 1]; /* access in reverse order */
769 			path = mnp->mnt_mountp;
770 			unmounted = B_FALSE;
771 			/*
772 			 * Try forced unmount first for remote filesystems.
773 			 *
774 			 * Not all remote filesystems support forced unmounts,
775 			 * so if this fails (ENOTSUP) we'll continue on
776 			 * and try a regular unmount.
777 			 */
778 			if (is_remote_fstype(mnp->mnt_fstype, remote_fstypes)) {
779 				if (umount2(path, MS_FORCE) == 0)
780 					unmounted = B_TRUE;
781 			}
782 			/*
783 			 * Try forced unmount if we're stuck.
784 			 */
785 			if (stuck) {
786 				if (umount2(path, MS_FORCE) == 0) {
787 					unmounted = B_TRUE;
788 					stuck = B_FALSE;
789 				} else {
790 					/*
791 					 * The first failure indicates a
792 					 * mount we won't be able to get
793 					 * rid of automatically, so we
794 					 * bail.
795 					 */
796 					error++;
797 					zerror(zlogp, B_FALSE,
798 					    "unable to unmount '%s'", path);
799 					free_mnttable(mnts, nmnt);
800 					goto out;
801 				}
802 			}
803 			/*
804 			 * Try regular unmounts for everything else.
805 			 */
806 			if (!unmounted && umount2(path, 0) != 0)
807 				newcount++;
808 		}
809 		free_mnttable(mnts, nmnt);
810 
811 		if (newcount == 0)
812 			break;
813 		if (newcount >= oldcount) {
814 			/*
815 			 * Last round didn't unmount anything; we're stuck and
816 			 * should start trying forced unmounts.
817 			 */
818 			stuck = B_TRUE;
819 		}
820 		oldcount = newcount;
821 
822 		/*
823 		 * Autofs doesn't let you unmount its trigger nodes from
824 		 * userland so we have to tell the kernel to cleanup for us.
825 		 */
826 		if (autofs_cleanup(zoneid) != 0) {
827 			zerror(zlogp, B_TRUE, "unable to remove autofs nodes");
828 			error++;
829 			goto out;
830 		}
831 	}
832 
833 out:
834 	free_remote_fstypes(remote_fstypes);
835 	(void) fclose(mnttab);
836 	return (error ? -1 : 0);
837 }
838 
839 static int
840 fs_compare(const void *m1, const void *m2)
841 {
842 	struct zone_fstab *i = (struct zone_fstab *)m1;
843 	struct zone_fstab *j = (struct zone_fstab *)m2;
844 
845 	return (strcmp(i->zone_fs_dir, j->zone_fs_dir));
846 }
847 
848 /*
849  * Fork and exec (and wait for) the mentioned binary with the provided
850  * arguments.  Returns (-1) if something went wrong with fork(2) or exec(2),
851  * returns the exit status otherwise.
852  *
853  * If we were unable to exec the provided pathname (for whatever
854  * reason), we return the special token ZEXIT_EXEC.  The current value
855  * of ZEXIT_EXEC doesn't conflict with legitimate exit codes of the
856  * consumers of this function; any future consumers must make sure this
857  * remains the case.
858  */
859 static int
860 forkexec(zlog_t *zlogp, const char *path, char *const argv[])
861 {
862 	pid_t child_pid;
863 	int child_status = 0;
864 
865 	/*
866 	 * Do not let another thread localize a message while we are forking.
867 	 */
868 	(void) mutex_lock(&msglock);
869 	child_pid = fork();
870 	(void) mutex_unlock(&msglock);
871 	if (child_pid == -1) {
872 		zerror(zlogp, B_TRUE, "could not fork for %s", argv[0]);
873 		return (-1);
874 	} else if (child_pid == 0) {
875 		closefrom(0);
876 		(void) execv(path, argv);
877 		/*
878 		 * Since we are in the child, there is no point calling zerror()
879 		 * since there is nobody waiting to consume it.  So exit with a
880 		 * special code that the parent will recognize and call zerror()
881 		 * accordingly.
882 		 */
883 
884 		_exit(ZEXIT_EXEC);
885 	} else {
886 		(void) waitpid(child_pid, &child_status, 0);
887 	}
888 
889 	if (WIFSIGNALED(child_status)) {
890 		zerror(zlogp, B_FALSE, "%s unexpectedly terminated due to "
891 		    "signal %d", path, WTERMSIG(child_status));
892 		return (-1);
893 	}
894 	assert(WIFEXITED(child_status));
895 	if (WEXITSTATUS(child_status) == ZEXIT_EXEC) {
896 		zerror(zlogp, B_FALSE, "failed to exec %s", path);
897 		return (-1);
898 	}
899 	return (WEXITSTATUS(child_status));
900 }
901 
902 static int
903 dofsck(zlog_t *zlogp, const char *fstype, const char *rawdev)
904 {
905 	char cmdbuf[MAXPATHLEN];
906 	char *argv[4];
907 	int status;
908 
909 	/*
910 	 * We could alternatively have called /usr/sbin/fsck -F <fstype>, but
911 	 * that would cost us an extra fork/exec without buying us anything.
912 	 */
913 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck", fstype)
914 	    > sizeof (cmdbuf)) {
915 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
916 		return (-1);
917 	}
918 
919 	argv[0] = "fsck";
920 	argv[1] = "-m";
921 	argv[2] = (char *)rawdev;
922 	argv[3] = NULL;
923 
924 	status = forkexec(zlogp, cmdbuf, argv);
925 	if (status == 0 || status == -1)
926 		return (status);
927 	zerror(zlogp, B_FALSE, "fsck of '%s' failed with exit status %d; "
928 	    "run fsck manually", rawdev, status);
929 	return (-1);
930 }
931 
932 static int
933 domount(zlog_t *zlogp, const char *fstype, const char *opts,
934     const char *special, const char *directory)
935 {
936 	char cmdbuf[MAXPATHLEN];
937 	char *argv[6];
938 	int status;
939 
940 	/*
941 	 * We could alternatively have called /usr/sbin/mount -F <fstype>, but
942 	 * that would cost us an extra fork/exec without buying us anything.
943 	 */
944 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount", fstype)
945 	    > sizeof (cmdbuf)) {
946 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
947 		return (-1);
948 	}
949 	argv[0] = "mount";
950 	if (opts[0] == '\0') {
951 		argv[1] = (char *)special;
952 		argv[2] = (char *)directory;
953 		argv[3] = NULL;
954 	} else {
955 		argv[1] = "-o";
956 		argv[2] = (char *)opts;
957 		argv[3] = (char *)special;
958 		argv[4] = (char *)directory;
959 		argv[5] = NULL;
960 	}
961 
962 	status = forkexec(zlogp, cmdbuf, argv);
963 	if (status == 0 || status == -1)
964 		return (status);
965 	if (opts[0] == '\0')
966 		zerror(zlogp, B_FALSE, "\"%s %s %s\" "
967 		    "failed with exit code %d",
968 		    cmdbuf, special, directory, status);
969 	else
970 		zerror(zlogp, B_FALSE, "\"%s -o %s %s %s\" "
971 		    "failed with exit code %d",
972 		    cmdbuf, opts, special, directory, status);
973 	return (-1);
974 }
975 
976 /*
977  * Make sure if a given path exists, it is not a sym-link, and is a directory.
978  */
979 static int
980 check_path(zlog_t *zlogp, const char *path)
981 {
982 	struct stat statbuf;
983 	char respath[MAXPATHLEN];
984 	int res;
985 
986 	if (lstat(path, &statbuf) != 0) {
987 		if (errno == ENOENT)
988 			return (0);
989 		zerror(zlogp, B_TRUE, "can't stat %s", path);
990 		return (-1);
991 	}
992 	if (S_ISLNK(statbuf.st_mode)) {
993 		zerror(zlogp, B_FALSE, "%s is a symlink", path);
994 		return (-1);
995 	}
996 	if (!S_ISDIR(statbuf.st_mode)) {
997 		if (is_system_labeled() && S_ISREG(statbuf.st_mode)) {
998 			/*
999 			 * The need to mount readonly copies of
1000 			 * global zone /etc/ files is unique to
1001 			 * Trusted Extensions.
1002 			 * The check for /etc/ via strstr() is to
1003 			 * allow paths like $ZONEROOT/etc/passwd
1004 			 */
1005 			if (strstr(path, "/etc/") == NULL) {
1006 				zerror(zlogp, B_FALSE,
1007 				    "%s is not in /etc", path);
1008 				return (-1);
1009 			}
1010 		} else {
1011 			zerror(zlogp, B_FALSE, "%s is not a directory", path);
1012 			return (-1);
1013 		}
1014 	}
1015 	if ((res = resolvepath(path, respath, sizeof (respath))) == -1) {
1016 		zerror(zlogp, B_TRUE, "unable to resolve path %s", path);
1017 		return (-1);
1018 	}
1019 	respath[res] = '\0';
1020 	if (strcmp(path, respath) != 0) {
1021 		/*
1022 		 * We don't like ".."s and "."s throwing us off
1023 		 */
1024 		zerror(zlogp, B_FALSE, "%s is not a canonical path", path);
1025 		return (-1);
1026 	}
1027 	return (0);
1028 }
1029 
1030 /*
1031  * Check every component of rootpath/relpath.  If any component fails (ie,
1032  * exists but isn't the canonical path to a directory), it is returned in
1033  * badpath, which is assumed to be at least of size MAXPATHLEN.
1034  *
1035  * Relpath must begin with '/'.
1036  */
1037 static boolean_t
1038 valid_mount_path(zlog_t *zlogp, const char *rootpath, const char *relpath)
1039 {
1040 	char abspath[MAXPATHLEN], *slashp;
1041 
1042 	/*
1043 	 * Make sure abspath has at least one '/' after its rootpath
1044 	 * component, and ends with '/'.
1045 	 */
1046 	if (snprintf(abspath, sizeof (abspath), "%s%s/", rootpath, relpath) >
1047 	    sizeof (abspath)) {
1048 		zerror(zlogp, B_FALSE, "pathname %s%s is too long", rootpath,
1049 		    relpath);
1050 		return (B_FALSE);
1051 	}
1052 
1053 	slashp = &abspath[strlen(rootpath)];
1054 	assert(*slashp == '/');
1055 	do {
1056 		*slashp = '\0';
1057 		if (check_path(zlogp, abspath) != 0)
1058 			return (B_FALSE);
1059 		*slashp = '/';
1060 		slashp++;
1061 	} while ((slashp = strchr(slashp, '/')) != NULL);
1062 	return (B_TRUE);
1063 }
1064 
1065 static int
1066 mount_one(zlog_t *zlogp, struct zone_fstab *fsptr, const char *rootpath)
1067 {
1068 	char    path[MAXPATHLEN];
1069 	char	specpath[MAXPATHLEN];
1070 	char    optstr[MAX_MNTOPT_STR];
1071 	zone_fsopt_t *optptr;
1072 
1073 	if (!valid_mount_path(zlogp, rootpath, fsptr->zone_fs_dir)) {
1074 		zerror(zlogp, B_FALSE, "%s%s is not a valid mount point",
1075 		    rootpath, fsptr->zone_fs_dir);
1076 		return (-1);
1077 	}
1078 
1079 	if (make_one_dir(zlogp, rootpath, fsptr->zone_fs_dir,
1080 	    DEFAULT_DIR_MODE) != 0)
1081 		return (-1);
1082 
1083 	(void) snprintf(path, sizeof (path), "%s%s", rootpath,
1084 	    fsptr->zone_fs_dir);
1085 
1086 	if (strlen(fsptr->zone_fs_special) == 0) {
1087 		/*
1088 		 * A zero-length special is how we distinguish IPDs from
1089 		 * general-purpose FSs.  Make sure it mounts from a place that
1090 		 * can be seen via the alternate zone's root.
1091 		 */
1092 		if (snprintf(specpath, sizeof (specpath), "%s%s",
1093 		    zonecfg_get_root(), fsptr->zone_fs_dir) >=
1094 		    sizeof (specpath)) {
1095 			zerror(zlogp, B_FALSE, "cannot mount %s: path too "
1096 			    "long in alternate root", fsptr->zone_fs_dir);
1097 			return (-1);
1098 		}
1099 		if (zonecfg_in_alt_root())
1100 			resolve_lofs(zlogp, specpath, sizeof (specpath));
1101 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS,
1102 		    specpath, path) != 0) {
1103 			zerror(zlogp, B_TRUE, "failed to loopback mount %s",
1104 			    specpath);
1105 			return (-1);
1106 		}
1107 		return (0);
1108 	}
1109 
1110 	/*
1111 	 * In general the strategy here is to do just as much verification as
1112 	 * necessary to avoid crashing or otherwise doing something bad; if the
1113 	 * administrator initiated the operation via zoneadm(1m), he'll get
1114 	 * auto-verification which will let him know what's wrong.  If he
1115 	 * modifies the zone configuration of a running zone and doesn't attempt
1116 	 * to verify that it's OK we won't crash but won't bother trying to be
1117 	 * too helpful either.  zoneadm verify is only a couple keystrokes away.
1118 	 */
1119 	if (!zonecfg_valid_fs_type(fsptr->zone_fs_type)) {
1120 		zerror(zlogp, B_FALSE, "cannot mount %s on %s: "
1121 		    "invalid file-system type %s", fsptr->zone_fs_special,
1122 		    fsptr->zone_fs_dir, fsptr->zone_fs_type);
1123 		return (-1);
1124 	}
1125 
1126 	/*
1127 	 * If we're looking at an alternate root environment, then construct
1128 	 * read-only loopback mounts as necessary.  For all lofs mounts, make
1129 	 * sure that the 'special' entry points inside the alternate root.  (We
1130 	 * don't do this with other mounts, as devfs isn't in the alternate
1131 	 * root, and we need to assume the device environment is roughly the
1132 	 * same.)
1133 	 */
1134 	if (zonecfg_in_alt_root()) {
1135 		struct stat64 st;
1136 
1137 		if (stat64(fsptr->zone_fs_special, &st) != -1 &&
1138 		    S_ISBLK(st.st_mode) &&
1139 		    check_lofs_needed(zlogp, fsptr) == -1)
1140 			return (-1);
1141 		if (strcmp(fsptr->zone_fs_type, MNTTYPE_LOFS) == 0) {
1142 			if (snprintf(specpath, sizeof (specpath), "%s%s",
1143 			    zonecfg_get_root(), fsptr->zone_fs_special) >=
1144 			    sizeof (specpath)) {
1145 				zerror(zlogp, B_FALSE, "cannot mount %s: path "
1146 				    "too long in alternate root",
1147 				    fsptr->zone_fs_special);
1148 				return (-1);
1149 			}
1150 			resolve_lofs(zlogp, specpath, sizeof (specpath));
1151 			(void) strlcpy(fsptr->zone_fs_special, specpath,
1152 			    sizeof (fsptr->zone_fs_special));
1153 		}
1154 	}
1155 
1156 	/*
1157 	 * Run 'fsck -m' if there's a device to fsck.
1158 	 */
1159 	if (fsptr->zone_fs_raw[0] != '\0' &&
1160 	    dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_raw) != 0)
1161 		return (-1);
1162 
1163 	/*
1164 	 * Build up mount option string.
1165 	 */
1166 	optstr[0] = '\0';
1167 	if (fsptr->zone_fs_options != NULL) {
1168 		(void) strlcpy(optstr, fsptr->zone_fs_options->zone_fsopt_opt,
1169 		    sizeof (optstr));
1170 		for (optptr = fsptr->zone_fs_options->zone_fsopt_next;
1171 		    optptr != NULL; optptr = optptr->zone_fsopt_next) {
1172 			(void) strlcat(optstr, ",", sizeof (optstr));
1173 			(void) strlcat(optstr, optptr->zone_fsopt_opt,
1174 			    sizeof (optstr));
1175 		}
1176 	}
1177 	return (domount(zlogp, fsptr->zone_fs_type, optstr,
1178 	    fsptr->zone_fs_special, path));
1179 }
1180 
1181 static void
1182 free_fs_data(struct zone_fstab *fsarray, uint_t nelem)
1183 {
1184 	uint_t i;
1185 
1186 	if (fsarray == NULL)
1187 		return;
1188 	for (i = 0; i < nelem; i++)
1189 		zonecfg_free_fs_option_list(fsarray[i].zone_fs_options);
1190 	free(fsarray);
1191 }
1192 
1193 /*
1194  * This function constructs the miniroot-like "scratch zone" environment.  If
1195  * it returns B_FALSE, then the error has already been logged.
1196  */
1197 static boolean_t
1198 build_mounted(zlog_t *zlogp, char *rootpath, size_t rootlen,
1199     const char *zonepath)
1200 {
1201 	char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1202 	char luroot[MAXPATHLEN];
1203 	const char **cpp;
1204 	static const char *mkdirs[] = {
1205 		"/system", "/system/contract", "/proc", "/dev", "/tmp",
1206 		"/a", NULL
1207 	};
1208 	static const char *localdirs[] = {
1209 		"/etc", "/var", NULL
1210 	};
1211 	static const char *loopdirs[] = {
1212 		"/etc/lib", "/etc/fs", "/lib", "/sbin", "/platform",
1213 		"/usr", NULL
1214 	};
1215 	static const char *tmpdirs[] = {
1216 		"/tmp", "/var/run", NULL
1217 	};
1218 	FILE *fp;
1219 	struct stat st;
1220 	char *altstr;
1221 	uuid_t uuid;
1222 
1223 	/*
1224 	 * Construct a small Solaris environment, including the zone root
1225 	 * mounted on '/a' inside that environment.
1226 	 */
1227 	resolve_lofs(zlogp, rootpath, rootlen);
1228 	(void) snprintf(luroot, sizeof (luroot), "%s/lu", zonepath);
1229 	resolve_lofs(zlogp, luroot, sizeof (luroot));
1230 	(void) snprintf(tmp, sizeof (tmp), "%s/bin", luroot);
1231 	(void) symlink("./usr/bin", tmp);
1232 
1233 	/*
1234 	 * These are mostly special mount points; not handled here.  (See
1235 	 * zone_mount_early.)
1236 	 */
1237 	for (cpp = mkdirs; *cpp != NULL; cpp++) {
1238 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1239 		if (mkdir(tmp, 0755) != 0) {
1240 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1241 			return (B_FALSE);
1242 		}
1243 	}
1244 
1245 	/*
1246 	 * These are mounted read-write from the zone undergoing upgrade.  We
1247 	 * must be careful not to 'leak' things from the main system into the
1248 	 * zone, and this accomplishes that goal.
1249 	 */
1250 	for (cpp = localdirs; *cpp != NULL; cpp++) {
1251 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1252 		(void) snprintf(fromdir, sizeof (fromdir), "%s%s", rootpath,
1253 		    *cpp);
1254 		if (mkdir(tmp, 0755) != 0) {
1255 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1256 			return (B_FALSE);
1257 		}
1258 		if (domount(zlogp, MNTTYPE_LOFS, "", fromdir, tmp) != 0) {
1259 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1260 			    *cpp);
1261 			return (B_FALSE);
1262 		}
1263 	}
1264 
1265 	/*
1266 	 * These are things mounted read-only from the running system because
1267 	 * they contain binaries that must match system.
1268 	 */
1269 	for (cpp = loopdirs; *cpp != NULL; cpp++) {
1270 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1271 		if (mkdir(tmp, 0755) != 0) {
1272 			if (errno != EEXIST) {
1273 				zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1274 				return (B_FALSE);
1275 			}
1276 			if (lstat(tmp, &st) != 0) {
1277 				zerror(zlogp, B_TRUE, "cannot stat %s", tmp);
1278 				return (B_FALSE);
1279 			}
1280 			/*
1281 			 * Ignore any non-directories encountered.  These are
1282 			 * things that have been converted into symlinks
1283 			 * (/etc/fs and /etc/lib) and no longer need a lofs
1284 			 * fixup.
1285 			 */
1286 			if (!S_ISDIR(st.st_mode))
1287 				continue;
1288 		}
1289 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, *cpp,
1290 		    tmp) != 0) {
1291 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1292 			    *cpp);
1293 			return (B_FALSE);
1294 		}
1295 	}
1296 
1297 	/*
1298 	 * These are things with tmpfs mounted inside.
1299 	 */
1300 	for (cpp = tmpdirs; *cpp != NULL; cpp++) {
1301 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1302 		if (mkdir(tmp, 0755) != 0 && errno != EEXIST) {
1303 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1304 			return (B_FALSE);
1305 		}
1306 		if (domount(zlogp, MNTTYPE_TMPFS, "", "swap", tmp) != 0) {
1307 			zerror(zlogp, B_TRUE, "cannot mount swap on %s", *cpp);
1308 			return (B_FALSE);
1309 		}
1310 	}
1311 
1312 	/*
1313 	 * This is here to support lucopy.  If there's an instance of this same
1314 	 * zone on the current running system, then we mount its root up as
1315 	 * read-only inside the scratch zone.
1316 	 */
1317 	(void) zonecfg_get_uuid(zone_name, uuid);
1318 	altstr = strdup(zonecfg_get_root());
1319 	if (altstr == NULL) {
1320 		zerror(zlogp, B_TRUE, "out of memory");
1321 		return (B_FALSE);
1322 	}
1323 	zonecfg_set_root("");
1324 	(void) strlcpy(tmp, zone_name, sizeof (tmp));
1325 	(void) zonecfg_get_name_by_uuid(uuid, tmp, sizeof (tmp));
1326 	if (zone_get_rootpath(tmp, fromdir, sizeof (fromdir)) == Z_OK &&
1327 	    strcmp(fromdir, rootpath) != 0) {
1328 		(void) snprintf(tmp, sizeof (tmp), "%s/b", luroot);
1329 		if (mkdir(tmp, 0755) != 0) {
1330 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1331 			return (B_FALSE);
1332 		}
1333 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, fromdir,
1334 		    tmp) != 0) {
1335 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1336 			    fromdir);
1337 			return (B_FALSE);
1338 		}
1339 	}
1340 	zonecfg_set_root(altstr);
1341 	free(altstr);
1342 
1343 	if ((fp = zonecfg_open_scratch(luroot, B_TRUE)) == NULL) {
1344 		zerror(zlogp, B_TRUE, "cannot open zone mapfile");
1345 		return (B_FALSE);
1346 	}
1347 	(void) ftruncate(fileno(fp), 0);
1348 	if (zonecfg_add_scratch(fp, zone_name, kernzone, "/") == -1) {
1349 		zerror(zlogp, B_TRUE, "cannot add zone mapfile entry");
1350 	}
1351 	zonecfg_close_scratch(fp);
1352 	(void) snprintf(tmp, sizeof (tmp), "%s/a", luroot);
1353 	if (domount(zlogp, MNTTYPE_LOFS, "", rootpath, tmp) != 0)
1354 		return (B_FALSE);
1355 	(void) strlcpy(rootpath, tmp, rootlen);
1356 	return (B_TRUE);
1357 }
1358 
1359 static int
1360 mount_filesystems(zlog_t *zlogp, boolean_t mount_cmd)
1361 {
1362 	char	rootpath[MAXPATHLEN];
1363 	char	zonepath[MAXPATHLEN];
1364 	int	num_fs = 0, i;
1365 	struct zone_fstab fstab, *fs_ptr = NULL, *tmp_ptr;
1366 	struct zone_fstab *fsp;
1367 	zone_dochandle_t handle = NULL;
1368 	zone_state_t zstate;
1369 
1370 	if (zone_get_state(zone_name, &zstate) != Z_OK ||
1371 	    (zstate != ZONE_STATE_READY && zstate != ZONE_STATE_MOUNTED)) {
1372 		zerror(zlogp, B_FALSE,
1373 		    "zone must be in '%s' or '%s' state to mount file-systems",
1374 		    zone_state_str(ZONE_STATE_READY),
1375 		    zone_state_str(ZONE_STATE_MOUNTED));
1376 		goto bad;
1377 	}
1378 
1379 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
1380 		zerror(zlogp, B_TRUE, "unable to determine zone path");
1381 		goto bad;
1382 	}
1383 
1384 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
1385 		zerror(zlogp, B_TRUE, "unable to determine zone root");
1386 		goto bad;
1387 	}
1388 
1389 	if ((handle = zonecfg_init_handle()) == NULL) {
1390 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
1391 		goto bad;
1392 	}
1393 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK ||
1394 	    zonecfg_setfsent(handle) != Z_OK) {
1395 		zerror(zlogp, B_FALSE, "invalid configuration");
1396 		goto bad;
1397 	}
1398 
1399 	/*
1400 	 * /dev in the zone is loopback'd from the external /dev repository,
1401 	 * in order to provide a largely read-only semantic.  But because
1402 	 * processes in the zone need to be able to chown, chmod, etc. zone
1403 	 * /dev files, we can't use a 'ro' lofs mount.  Instead we use a
1404 	 * special mode just for zones, "zonedevfs".
1405 	 *
1406 	 * In the future we should front /dev with a full-fledged filesystem.
1407 	 */
1408 	num_fs++;
1409 	if ((tmp_ptr = realloc(fs_ptr, num_fs * sizeof (*tmp_ptr))) == NULL) {
1410 		zerror(zlogp, B_TRUE, "memory allocation failed");
1411 		num_fs--;
1412 		goto bad;
1413 	}
1414 	fs_ptr = tmp_ptr;
1415 	fsp = &fs_ptr[num_fs - 1];
1416 	/*
1417 	 * Note that mount_one will prepend the alternate root to
1418 	 * zone_fs_special and do the necessary resolution, so all that is
1419 	 * needed here is to strip the root added by zone_get_zonepath.
1420 	 */
1421 	(void) strlcpy(fsp->zone_fs_dir, "/dev", sizeof (fsp->zone_fs_dir));
1422 	(void) snprintf(fsp->zone_fs_special, sizeof (fsp->zone_fs_special),
1423 	    "%s/dev", zonepath + strlen(zonecfg_get_root()));
1424 	fsp->zone_fs_raw[0] = '\0';
1425 	(void) strlcpy(fsp->zone_fs_type, MNTTYPE_LOFS,
1426 	    sizeof (fsp->zone_fs_type));
1427 	fsp->zone_fs_options = NULL;
1428 	if (zonecfg_add_fs_option(fsp, MNTOPT_LOFS_ZONEDEVFS) != Z_OK) {
1429 		zerror(zlogp, B_FALSE, "error adding property");
1430 		goto bad;
1431 	}
1432 
1433 	/*
1434 	 * Iterate through the rest of the filesystems, first the IPDs, then
1435 	 * the general FSs.  Sort them all, then mount them in sorted order.
1436 	 * This is to make sure the higher level directories (e.g., /usr)
1437 	 * get mounted before any beneath them (e.g., /usr/local).
1438 	 */
1439 	if (zonecfg_setipdent(handle) != Z_OK) {
1440 		zerror(zlogp, B_FALSE, "invalid configuration");
1441 		goto bad;
1442 	}
1443 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
1444 		num_fs++;
1445 		if ((tmp_ptr = realloc(fs_ptr,
1446 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1447 			zerror(zlogp, B_TRUE, "memory allocation failed");
1448 			num_fs--;
1449 			(void) zonecfg_endipdent(handle);
1450 			goto bad;
1451 		}
1452 		fs_ptr = tmp_ptr;
1453 		fsp = &fs_ptr[num_fs - 1];
1454 		/*
1455 		 * IPDs logically only have a mount point; all other properties
1456 		 * are implied.
1457 		 */
1458 		(void) strlcpy(fsp->zone_fs_dir,
1459 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1460 		fsp->zone_fs_special[0] = '\0';
1461 		fsp->zone_fs_raw[0] = '\0';
1462 		fsp->zone_fs_type[0] = '\0';
1463 		fsp->zone_fs_options = NULL;
1464 	}
1465 	(void) zonecfg_endipdent(handle);
1466 
1467 	if (zonecfg_setfsent(handle) != Z_OK) {
1468 		zerror(zlogp, B_FALSE, "invalid configuration");
1469 		goto bad;
1470 	}
1471 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1472 		/*
1473 		 * ZFS filesystems will not be accessible under an alternate
1474 		 * root, since the pool will not be known.  Ignore them in this
1475 		 * case.
1476 		 */
1477 		if (mount_cmd && strcmp(fstab.zone_fs_type, MNTTYPE_ZFS) == 0)
1478 			continue;
1479 
1480 		num_fs++;
1481 		if ((tmp_ptr = realloc(fs_ptr,
1482 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1483 			zerror(zlogp, B_TRUE, "memory allocation failed");
1484 			num_fs--;
1485 			(void) zonecfg_endfsent(handle);
1486 			goto bad;
1487 		}
1488 		fs_ptr = tmp_ptr;
1489 		fsp = &fs_ptr[num_fs - 1];
1490 		(void) strlcpy(fsp->zone_fs_dir,
1491 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1492 		(void) strlcpy(fsp->zone_fs_special, fstab.zone_fs_special,
1493 		    sizeof (fsp->zone_fs_special));
1494 		(void) strlcpy(fsp->zone_fs_raw, fstab.zone_fs_raw,
1495 		    sizeof (fsp->zone_fs_raw));
1496 		(void) strlcpy(fsp->zone_fs_type, fstab.zone_fs_type,
1497 		    sizeof (fsp->zone_fs_type));
1498 		fsp->zone_fs_options = fstab.zone_fs_options;
1499 	}
1500 	(void) zonecfg_endfsent(handle);
1501 	zonecfg_fini_handle(handle);
1502 	handle = NULL;
1503 
1504 	/*
1505 	 * If we're mounting a zone for administration, then we need to set up
1506 	 * the "/a" environment inside the zone so that the commands that run
1507 	 * in there have access to both the running system's utilities and the
1508 	 * to-be-modified zone's files.
1509 	 */
1510 	if (mount_cmd &&
1511 	    !build_mounted(zlogp, rootpath, sizeof (rootpath), zonepath))
1512 		goto bad;
1513 
1514 	qsort(fs_ptr, num_fs, sizeof (*fs_ptr), fs_compare);
1515 	for (i = 0; i < num_fs; i++) {
1516 		if (mount_cmd && strcmp(fs_ptr[i].zone_fs_dir, "/dev") == 0) {
1517 			size_t slen = strlen(rootpath) - 2;
1518 
1519 			/* /dev is special and always goes at the top */
1520 			rootpath[slen] = '\0';
1521 			if (mount_one(zlogp, &fs_ptr[i], rootpath) != 0)
1522 				goto bad;
1523 			rootpath[slen] = '/';
1524 			continue;
1525 		}
1526 		if (mount_one(zlogp, &fs_ptr[i], rootpath) != 0)
1527 			goto bad;
1528 	}
1529 
1530 	/*
1531 	 * For Trusted Extensions cross-mount each lower level /export/home
1532 	 */
1533 	if (!mount_cmd && tsol_mounts(zlogp, zone_name, rootpath) != 0)
1534 		goto bad;
1535 
1536 	free_fs_data(fs_ptr, num_fs);
1537 
1538 	/*
1539 	 * Everything looks fine.
1540 	 */
1541 	return (0);
1542 
1543 bad:
1544 	if (handle != NULL)
1545 		zonecfg_fini_handle(handle);
1546 	free_fs_data(fs_ptr, num_fs);
1547 	return (-1);
1548 }
1549 
1550 /* caller makes sure neither parameter is NULL */
1551 static int
1552 addr2netmask(char *prefixstr, int maxprefixlen, uchar_t *maskstr)
1553 {
1554 	int prefixlen;
1555 
1556 	prefixlen = atoi(prefixstr);
1557 	if (prefixlen < 0 || prefixlen > maxprefixlen)
1558 		return (1);
1559 	while (prefixlen > 0) {
1560 		if (prefixlen >= 8) {
1561 			*maskstr++ = 0xFF;
1562 			prefixlen -= 8;
1563 			continue;
1564 		}
1565 		*maskstr |= 1 << (8 - prefixlen);
1566 		prefixlen--;
1567 	}
1568 	return (0);
1569 }
1570 
1571 /*
1572  * Tear down all interfaces belonging to the given zone.  This should
1573  * be called with the zone in a state other than "running", so that
1574  * interfaces can't be assigned to the zone after this returns.
1575  *
1576  * If anything goes wrong, log an error message and return an error.
1577  */
1578 static int
1579 unconfigure_network_interfaces(zlog_t *zlogp, zoneid_t zone_id)
1580 {
1581 	struct lifnum lifn;
1582 	struct lifconf lifc;
1583 	struct lifreq *lifrp, lifrl;
1584 	int64_t lifc_flags = LIFC_NOXMIT | LIFC_ALLZONES;
1585 	int num_ifs, s, i, ret_code = 0;
1586 	uint_t bufsize;
1587 	char *buf = NULL;
1588 
1589 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1590 		zerror(zlogp, B_TRUE, "could not get socket");
1591 		ret_code = -1;
1592 		goto bad;
1593 	}
1594 	lifn.lifn_family = AF_UNSPEC;
1595 	lifn.lifn_flags = (int)lifc_flags;
1596 	if (ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) {
1597 		zerror(zlogp, B_TRUE,
1598 		    "could not determine number of interfaces");
1599 		ret_code = -1;
1600 		goto bad;
1601 	}
1602 	num_ifs = lifn.lifn_count;
1603 	bufsize = num_ifs * sizeof (struct lifreq);
1604 	if ((buf = malloc(bufsize)) == NULL) {
1605 		zerror(zlogp, B_TRUE, "memory allocation failed");
1606 		ret_code = -1;
1607 		goto bad;
1608 	}
1609 	lifc.lifc_family = AF_UNSPEC;
1610 	lifc.lifc_flags = (int)lifc_flags;
1611 	lifc.lifc_len = bufsize;
1612 	lifc.lifc_buf = buf;
1613 	if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) {
1614 		zerror(zlogp, B_TRUE, "could not get configured interfaces");
1615 		ret_code = -1;
1616 		goto bad;
1617 	}
1618 	lifrp = lifc.lifc_req;
1619 	for (i = lifc.lifc_len / sizeof (struct lifreq); i > 0; i--, lifrp++) {
1620 		(void) close(s);
1621 		if ((s = socket(lifrp->lifr_addr.ss_family, SOCK_DGRAM, 0)) <
1622 		    0) {
1623 			zerror(zlogp, B_TRUE, "%s: could not get socket",
1624 			    lifrl.lifr_name);
1625 			ret_code = -1;
1626 			continue;
1627 		}
1628 		(void) memset(&lifrl, 0, sizeof (lifrl));
1629 		(void) strncpy(lifrl.lifr_name, lifrp->lifr_name,
1630 		    sizeof (lifrl.lifr_name));
1631 		if (ioctl(s, SIOCGLIFZONE, (caddr_t)&lifrl) < 0) {
1632 			zerror(zlogp, B_TRUE,
1633 			    "%s: could not determine zone interface belongs to",
1634 			    lifrl.lifr_name);
1635 			ret_code = -1;
1636 			continue;
1637 		}
1638 		if (lifrl.lifr_zoneid == zone_id) {
1639 			if (ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifrl) < 0) {
1640 				zerror(zlogp, B_TRUE,
1641 				    "%s: could not remove interface",
1642 				    lifrl.lifr_name);
1643 				ret_code = -1;
1644 				continue;
1645 			}
1646 		}
1647 	}
1648 bad:
1649 	if (s > 0)
1650 		(void) close(s);
1651 	if (buf)
1652 		free(buf);
1653 	return (ret_code);
1654 }
1655 
1656 static union	sockunion {
1657 	struct	sockaddr sa;
1658 	struct	sockaddr_in sin;
1659 	struct	sockaddr_dl sdl;
1660 	struct	sockaddr_in6 sin6;
1661 } so_dst, so_ifp;
1662 
1663 static struct {
1664 	struct	rt_msghdr hdr;
1665 	char	space[512];
1666 } rtmsg;
1667 
1668 static int
1669 salen(struct sockaddr *sa)
1670 {
1671 	switch (sa->sa_family) {
1672 	case AF_INET:
1673 		return (sizeof (struct sockaddr_in));
1674 	case AF_LINK:
1675 		return (sizeof (struct sockaddr_dl));
1676 	case AF_INET6:
1677 		return (sizeof (struct sockaddr_in6));
1678 	default:
1679 		return (sizeof (struct sockaddr));
1680 	}
1681 }
1682 
1683 #define	ROUNDUP_LONG(a) \
1684 	((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
1685 
1686 /*
1687  * Look up which zone is using a given IP address.  The address in question
1688  * is expected to have been stuffed into the structure to which lifr points
1689  * via a previous SIOCGLIFADDR ioctl().
1690  *
1691  * This is done using black router socket magic.
1692  *
1693  * Return the name of the zone on success or NULL on failure.
1694  *
1695  * This is a lot of code for a simple task; a new ioctl request to take care
1696  * of this might be a useful RFE.
1697  */
1698 
1699 static char *
1700 who_is_using(zlog_t *zlogp, struct lifreq *lifr)
1701 {
1702 	static char answer[ZONENAME_MAX];
1703 	pid_t pid;
1704 	int s, rlen, l, i;
1705 	char *cp = rtmsg.space;
1706 	struct sockaddr_dl *ifp = NULL;
1707 	struct sockaddr *sa;
1708 	char save_if_name[LIFNAMSIZ];
1709 
1710 	answer[0] = '\0';
1711 
1712 	pid = getpid();
1713 	if ((s = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
1714 		zerror(zlogp, B_TRUE, "could not get routing socket");
1715 		return (NULL);
1716 	}
1717 
1718 	if (lifr->lifr_addr.ss_family == AF_INET) {
1719 		struct sockaddr_in *sin4;
1720 
1721 		so_dst.sa.sa_family = AF_INET;
1722 		sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
1723 		so_dst.sin.sin_addr = sin4->sin_addr;
1724 	} else {
1725 		struct sockaddr_in6 *sin6;
1726 
1727 		so_dst.sa.sa_family = AF_INET6;
1728 		sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
1729 		so_dst.sin6.sin6_addr = sin6->sin6_addr;
1730 	}
1731 
1732 	so_ifp.sa.sa_family = AF_LINK;
1733 
1734 	(void) memset(&rtmsg, 0, sizeof (rtmsg));
1735 	rtmsg.hdr.rtm_type = RTM_GET;
1736 	rtmsg.hdr.rtm_flags = RTF_UP | RTF_HOST;
1737 	rtmsg.hdr.rtm_version = RTM_VERSION;
1738 	rtmsg.hdr.rtm_seq = ++rts_seqno;
1739 	rtmsg.hdr.rtm_addrs = RTA_IFP | RTA_DST;
1740 
1741 	l = ROUNDUP_LONG(salen(&so_dst.sa));
1742 	(void) memmove(cp, &(so_dst), l);
1743 	cp += l;
1744 	l = ROUNDUP_LONG(salen(&so_ifp.sa));
1745 	(void) memmove(cp, &(so_ifp), l);
1746 	cp += l;
1747 
1748 	rtmsg.hdr.rtm_msglen = l = cp - (char *)&rtmsg;
1749 
1750 	if ((rlen = write(s, &rtmsg, l)) < 0) {
1751 		zerror(zlogp, B_TRUE, "writing to routing socket");
1752 		return (NULL);
1753 	} else if (rlen < (int)rtmsg.hdr.rtm_msglen) {
1754 		zerror(zlogp, B_TRUE,
1755 		    "write to routing socket got only %d for len\n", rlen);
1756 		return (NULL);
1757 	}
1758 	do {
1759 		l = read(s, &rtmsg, sizeof (rtmsg));
1760 	} while (l > 0 && (rtmsg.hdr.rtm_seq != rts_seqno ||
1761 	    rtmsg.hdr.rtm_pid != pid));
1762 	if (l < 0) {
1763 		zerror(zlogp, B_TRUE, "reading from routing socket");
1764 		return (NULL);
1765 	}
1766 
1767 	if (rtmsg.hdr.rtm_version != RTM_VERSION) {
1768 		zerror(zlogp, B_FALSE,
1769 		    "routing message version %d not understood",
1770 		    rtmsg.hdr.rtm_version);
1771 		return (NULL);
1772 	}
1773 	if (rtmsg.hdr.rtm_msglen != (ushort_t)l) {
1774 		zerror(zlogp, B_FALSE, "message length mismatch, "
1775 		    "expected %d bytes, returned %d bytes",
1776 		    rtmsg.hdr.rtm_msglen, l);
1777 		return (NULL);
1778 	}
1779 	if (rtmsg.hdr.rtm_errno != 0)  {
1780 		errno = rtmsg.hdr.rtm_errno;
1781 		zerror(zlogp, B_TRUE, "RTM_GET routing socket message");
1782 		return (NULL);
1783 	}
1784 	if ((rtmsg.hdr.rtm_addrs & RTA_IFP) == 0) {
1785 		zerror(zlogp, B_FALSE, "interface not found");
1786 		return (NULL);
1787 	}
1788 	cp = ((char *)(&rtmsg.hdr + 1));
1789 	for (i = 1; i != 0; i <<= 1) {
1790 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1791 		sa = (struct sockaddr *)cp;
1792 		if (i != RTA_IFP) {
1793 			if ((i & rtmsg.hdr.rtm_addrs) != 0)
1794 				cp += ROUNDUP_LONG(salen(sa));
1795 			continue;
1796 		}
1797 		if (sa->sa_family == AF_LINK &&
1798 		    ((struct sockaddr_dl *)sa)->sdl_nlen != 0)
1799 			ifp = (struct sockaddr_dl *)sa;
1800 		break;
1801 	}
1802 	if (ifp == NULL) {
1803 		zerror(zlogp, B_FALSE, "interface could not be determined");
1804 		return (NULL);
1805 	}
1806 
1807 	/*
1808 	 * We need to set the I/F name to what we got above, then do the
1809 	 * appropriate ioctl to get its zone name.  But lifr->lifr_name is
1810 	 * used by the calling function to do a REMOVEIF, so if we leave the
1811 	 * "good" zone's I/F name in place, *that* I/F will be removed instead
1812 	 * of the bad one.  So we save the old (bad) I/F name before over-
1813 	 * writing it and doing the ioctl, then restore it after the ioctl.
1814 	 */
1815 	(void) strlcpy(save_if_name, lifr->lifr_name, sizeof (save_if_name));
1816 	(void) strncpy(lifr->lifr_name, ifp->sdl_data, ifp->sdl_nlen);
1817 	lifr->lifr_name[ifp->sdl_nlen] = '\0';
1818 	i = ioctl(s, SIOCGLIFZONE, lifr);
1819 	(void) strlcpy(lifr->lifr_name, save_if_name, sizeof (save_if_name));
1820 	if (i < 0) {
1821 		zerror(zlogp, B_TRUE,
1822 		    "%s: could not determine the zone interface belongs to",
1823 		    lifr->lifr_name);
1824 		return (NULL);
1825 	}
1826 	if (getzonenamebyid(lifr->lifr_zoneid, answer, sizeof (answer)) < 0)
1827 		(void) snprintf(answer, sizeof (answer), "%d",
1828 		    lifr->lifr_zoneid);
1829 
1830 	if (strlen(answer) > 0)
1831 		return (answer);
1832 	return (NULL);
1833 }
1834 
1835 typedef struct mcast_rtmsg_s {
1836 	struct rt_msghdr	m_rtm;
1837 	union {
1838 		struct {
1839 			struct sockaddr_in	m_dst;
1840 			struct sockaddr_in	m_gw;
1841 			struct sockaddr_in	m_netmask;
1842 		} m_v4;
1843 		struct {
1844 			struct sockaddr_in6	m_dst;
1845 			struct sockaddr_in6	m_gw;
1846 			struct sockaddr_in6	m_netmask;
1847 		} m_v6;
1848 	} m_u;
1849 } mcast_rtmsg_t;
1850 #define	m_dst4		m_u.m_v4.m_dst
1851 #define	m_dst6		m_u.m_v6.m_dst
1852 #define	m_gw4		m_u.m_v4.m_gw
1853 #define	m_gw6		m_u.m_v6.m_gw
1854 #define	m_netmask4	m_u.m_v4.m_netmask
1855 #define	m_netmask6	m_u.m_v6.m_netmask
1856 
1857 /*
1858  * Configures a single interface: a new virtual interface is added, based on
1859  * the physical interface nwiftabptr->zone_nwif_physical, with the address
1860  * specified in nwiftabptr->zone_nwif_address, for zone zone_id.  Note that
1861  * the "address" can be an IPv6 address (with a /prefixlength required), an
1862  * IPv4 address (with a /prefixlength optional), or a name; for the latter,
1863  * an IPv4 name-to-address resolution will be attempted.
1864  *
1865  * A default interface route for multicast is created on the first IPv4 and
1866  * IPv6 interfaces (that have the IFF_MULTICAST flag set), respectively.
1867  * This should really be done in the init scripts if we ever allow zones to
1868  * modify the routing tables.
1869  *
1870  * If anything goes wrong, we log an detailed error message, attempt to tear
1871  * down whatever we set up and return an error.
1872  */
1873 static int
1874 configure_one_interface(zlog_t *zlogp, zoneid_t zone_id,
1875     struct zone_nwiftab *nwiftabptr, boolean_t *mcast_rt_v4_setp,
1876     boolean_t *mcast_rt_v6_setp)
1877 {
1878 	struct lifreq lifr;
1879 	struct sockaddr_in netmask4;
1880 	struct sockaddr_in6 netmask6;
1881 	struct in_addr in4;
1882 	struct in6_addr in6;
1883 	sa_family_t af;
1884 	char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
1885 	mcast_rtmsg_t mcast_rtmsg;
1886 	int s;
1887 	int rs;
1888 	int rlen;
1889 	boolean_t got_netmask = B_FALSE;
1890 	char addrstr4[INET_ADDRSTRLEN];
1891 	int res;
1892 
1893 	res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
1894 	if (res != Z_OK) {
1895 		zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
1896 		    nwiftabptr->zone_nwif_address);
1897 		return (-1);
1898 	}
1899 	af = lifr.lifr_addr.ss_family;
1900 	if (af == AF_INET)
1901 		in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
1902 	else
1903 		in6 = ((struct sockaddr_in6 *)(&lifr.lifr_addr))->sin6_addr;
1904 
1905 	if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
1906 		zerror(zlogp, B_TRUE, "could not get socket");
1907 		return (-1);
1908 	}
1909 
1910 	(void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
1911 	    sizeof (lifr.lifr_name));
1912 	if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
1913 		zerror(zlogp, B_TRUE, "%s: could not add interface",
1914 		    lifr.lifr_name);
1915 		(void) close(s);
1916 		return (-1);
1917 	}
1918 
1919 	if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
1920 		zerror(zlogp, B_TRUE,
1921 		    "%s: could not set IP address to %s",
1922 		    lifr.lifr_name, nwiftabptr->zone_nwif_address);
1923 		goto bad;
1924 	}
1925 
1926 	/* Preserve literal IPv4 address for later potential printing. */
1927 	if (af == AF_INET)
1928 		(void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
1929 
1930 	lifr.lifr_zoneid = zone_id;
1931 	if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
1932 		zerror(zlogp, B_TRUE, "%s: could not place interface into zone",
1933 		    lifr.lifr_name);
1934 		goto bad;
1935 	}
1936 
1937 	if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
1938 		got_netmask = B_TRUE;	/* default setting will be correct */
1939 	} else {
1940 		if (af == AF_INET) {
1941 			/*
1942 			 * The IPv4 netmask can be determined either
1943 			 * directly if a prefix length was supplied with
1944 			 * the address or via the netmasks database.  Not
1945 			 * being able to determine it is a common failure,
1946 			 * but it often is not fatal to operation of the
1947 			 * interface.  In that case, a warning will be
1948 			 * printed after the rest of the interface's
1949 			 * parameters have been configured.
1950 			 */
1951 			(void) memset(&netmask4, 0, sizeof (netmask4));
1952 			if (slashp != NULL) {
1953 				if (addr2netmask(slashp + 1, V4_ADDR_LEN,
1954 				    (uchar_t *)&netmask4.sin_addr) != 0) {
1955 					*slashp = '/';
1956 					zerror(zlogp, B_FALSE,
1957 					    "%s: invalid prefix length in %s",
1958 					    lifr.lifr_name,
1959 					    nwiftabptr->zone_nwif_address);
1960 					goto bad;
1961 				}
1962 				got_netmask = B_TRUE;
1963 			} else if (getnetmaskbyaddr(in4,
1964 			    &netmask4.sin_addr) == 0) {
1965 				got_netmask = B_TRUE;
1966 			}
1967 			if (got_netmask) {
1968 				netmask4.sin_family = af;
1969 				(void) memcpy(&lifr.lifr_addr, &netmask4,
1970 				    sizeof (netmask4));
1971 			}
1972 		} else {
1973 			(void) memset(&netmask6, 0, sizeof (netmask6));
1974 			if (addr2netmask(slashp + 1, V6_ADDR_LEN,
1975 			    (uchar_t *)&netmask6.sin6_addr) != 0) {
1976 				*slashp = '/';
1977 				zerror(zlogp, B_FALSE,
1978 				    "%s: invalid prefix length in %s",
1979 				    lifr.lifr_name,
1980 				    nwiftabptr->zone_nwif_address);
1981 				goto bad;
1982 			}
1983 			got_netmask = B_TRUE;
1984 			netmask6.sin6_family = af;
1985 			(void) memcpy(&lifr.lifr_addr, &netmask6,
1986 			    sizeof (netmask6));
1987 		}
1988 		if (got_netmask &&
1989 		    ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
1990 			zerror(zlogp, B_TRUE, "%s: could not set netmask",
1991 			    lifr.lifr_name);
1992 			goto bad;
1993 		}
1994 
1995 		/*
1996 		 * This doesn't set the broadcast address at all. Rather, it
1997 		 * gets, then sets the interface's address, relying on the fact
1998 		 * that resetting the address will reset the broadcast address.
1999 		 */
2000 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2001 			zerror(zlogp, B_TRUE, "%s: could not get address",
2002 			    lifr.lifr_name);
2003 			goto bad;
2004 		}
2005 		if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2006 			zerror(zlogp, B_TRUE,
2007 			    "%s: could not reset broadcast address",
2008 			    lifr.lifr_name);
2009 			goto bad;
2010 		}
2011 	}
2012 
2013 	if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2014 		zerror(zlogp, B_TRUE, "%s: could not get flags",
2015 		    lifr.lifr_name);
2016 		goto bad;
2017 	}
2018 	lifr.lifr_flags |= IFF_UP;
2019 	if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
2020 		int save_errno = errno;
2021 		char *zone_using;
2022 
2023 		/*
2024 		 * If we failed with something other than EADDRNOTAVAIL,
2025 		 * then skip to the end.  Otherwise, look up our address,
2026 		 * then call a function to determine which zone is already
2027 		 * using that address.
2028 		 */
2029 		if (errno != EADDRNOTAVAIL) {
2030 			zerror(zlogp, B_TRUE,
2031 			    "%s: could not bring interface up", lifr.lifr_name);
2032 			goto bad;
2033 		}
2034 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2035 			zerror(zlogp, B_TRUE, "%s: could not get address",
2036 			    lifr.lifr_name);
2037 			goto bad;
2038 		}
2039 		zone_using = who_is_using(zlogp, &lifr);
2040 		errno = save_errno;
2041 		if (zone_using == NULL)
2042 			zerror(zlogp, B_TRUE,
2043 			    "%s: could not bring interface up", lifr.lifr_name);
2044 		else
2045 			zerror(zlogp, B_TRUE, "%s: could not bring interface "
2046 			    "up: address in use by zone '%s'", lifr.lifr_name,
2047 			    zone_using);
2048 		goto bad;
2049 	}
2050 	if ((lifr.lifr_flags & IFF_MULTICAST) && ((af == AF_INET &&
2051 	    mcast_rt_v4_setp != NULL && *mcast_rt_v4_setp == B_FALSE) ||
2052 	    (af == AF_INET6 &&
2053 	    mcast_rt_v6_setp != NULL && *mcast_rt_v6_setp == B_FALSE))) {
2054 		rs = socket(PF_ROUTE, SOCK_RAW, 0);
2055 		if (rs < 0) {
2056 			zerror(zlogp, B_TRUE, "%s: could not create "
2057 			    "routing socket", lifr.lifr_name);
2058 			goto bad;
2059 		}
2060 		(void) shutdown(rs, 0);
2061 		(void) memset((void *)&mcast_rtmsg, 0, sizeof (mcast_rtmsg_t));
2062 		mcast_rtmsg.m_rtm.rtm_msglen =  sizeof (struct rt_msghdr) +
2063 		    3 * (af == AF_INET ? sizeof (struct sockaddr_in) :
2064 		    sizeof (struct sockaddr_in6));
2065 		mcast_rtmsg.m_rtm.rtm_version = RTM_VERSION;
2066 		mcast_rtmsg.m_rtm.rtm_type = RTM_ADD;
2067 		mcast_rtmsg.m_rtm.rtm_flags = RTF_UP;
2068 		mcast_rtmsg.m_rtm.rtm_addrs =
2069 		    RTA_DST | RTA_GATEWAY | RTA_NETMASK;
2070 		mcast_rtmsg.m_rtm.rtm_seq = ++rts_seqno;
2071 		if (af == AF_INET) {
2072 			mcast_rtmsg.m_dst4.sin_family = AF_INET;
2073 			mcast_rtmsg.m_dst4.sin_addr.s_addr =
2074 			    htonl(INADDR_UNSPEC_GROUP);
2075 			mcast_rtmsg.m_gw4.sin_family = AF_INET;
2076 			mcast_rtmsg.m_gw4.sin_addr = in4;
2077 			mcast_rtmsg.m_netmask4.sin_family = AF_INET;
2078 			mcast_rtmsg.m_netmask4.sin_addr.s_addr =
2079 			    htonl(IN_CLASSD_NET);
2080 		} else {
2081 			mcast_rtmsg.m_dst6.sin6_family = AF_INET6;
2082 			mcast_rtmsg.m_dst6.sin6_addr.s6_addr[0] = 0xffU;
2083 			mcast_rtmsg.m_gw6.sin6_family = AF_INET6;
2084 			mcast_rtmsg.m_gw6.sin6_addr = in6;
2085 			mcast_rtmsg.m_netmask6.sin6_family = AF_INET6;
2086 			mcast_rtmsg.m_netmask6.sin6_addr.s6_addr[0] = 0xffU;
2087 		}
2088 		rlen = write(rs, (char *)&mcast_rtmsg,
2089 		    mcast_rtmsg.m_rtm.rtm_msglen);
2090 		if (rlen < mcast_rtmsg.m_rtm.rtm_msglen) {
2091 			if (rlen < 0) {
2092 				zerror(zlogp, B_TRUE, "%s: could not set "
2093 				    "default interface for multicast",
2094 				    lifr.lifr_name);
2095 			} else {
2096 				zerror(zlogp, B_FALSE, "%s: write to routing "
2097 				    "socket returned %d", lifr.lifr_name, rlen);
2098 			}
2099 			(void) close(rs);
2100 			goto bad;
2101 		}
2102 		if (af == AF_INET) {
2103 			*mcast_rt_v4_setp = B_TRUE;
2104 		} else {
2105 			*mcast_rt_v6_setp = B_TRUE;
2106 		}
2107 		(void) close(rs);
2108 	}
2109 
2110 	if (!got_netmask) {
2111 		/*
2112 		 * A common, but often non-fatal problem, is that the system
2113 		 * cannot find the netmask for an interface address. This is
2114 		 * often caused by it being only in /etc/inet/netmasks, but
2115 		 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2116 		 * in that. This doesn't show up at boot because the netmask
2117 		 * is obtained from /etc/inet/netmasks when no network
2118 		 * interfaces are up, but isn't consulted when NIS/NIS+ is
2119 		 * available. We warn the user here that something like this
2120 		 * has happened and we're just running with a default and
2121 		 * possible incorrect netmask.
2122 		 */
2123 		char buffer[INET6_ADDRSTRLEN];
2124 		void  *addr;
2125 
2126 		if (af == AF_INET)
2127 			addr = &((struct sockaddr_in *)
2128 			    (&lifr.lifr_addr))->sin_addr;
2129 		else
2130 			addr = &((struct sockaddr_in6 *)
2131 			    (&lifr.lifr_addr))->sin6_addr;
2132 
2133 		/* Find out what netmask interface is going to be using */
2134 		if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2135 		    inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL)
2136 			goto bad;
2137 		zerror(zlogp, B_FALSE,
2138 		    "WARNING: %s: no matching subnet found in netmasks(4) for "
2139 		    "%s; using default of %s.",
2140 		    lifr.lifr_name, addrstr4, buffer);
2141 	}
2142 
2143 	(void) close(s);
2144 	return (Z_OK);
2145 bad:
2146 	(void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2147 	(void) close(s);
2148 	return (-1);
2149 }
2150 
2151 /*
2152  * Sets up network interfaces based on information from the zone configuration.
2153  * An IPv4 loopback interface is set up "for free", modeling the global system.
2154  * If any of the configuration interfaces were IPv6, then an IPv6 loopback
2155  * address is set up as well.
2156  *
2157  * If anything goes wrong, we log a general error message, attempt to tear down
2158  * whatever we set up, and return an error.
2159  */
2160 static int
2161 configure_network_interfaces(zlog_t *zlogp)
2162 {
2163 	zone_dochandle_t handle;
2164 	struct zone_nwiftab nwiftab, loopback_iftab;
2165 	boolean_t saw_v6 = B_FALSE;
2166 	boolean_t mcast_rt_v4_set = B_FALSE;
2167 	boolean_t mcast_rt_v6_set = B_FALSE;
2168 	zoneid_t zoneid;
2169 
2170 	if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2171 		zerror(zlogp, B_TRUE, "unable to get zoneid");
2172 		return (-1);
2173 	}
2174 
2175 	if ((handle = zonecfg_init_handle()) == NULL) {
2176 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2177 		return (-1);
2178 	}
2179 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2180 		zerror(zlogp, B_FALSE, "invalid configuration");
2181 		zonecfg_fini_handle(handle);
2182 		return (-1);
2183 	}
2184 	if (zonecfg_setnwifent(handle) == Z_OK) {
2185 		for (;;) {
2186 			struct in6_addr in6;
2187 
2188 			if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2189 				break;
2190 			if (configure_one_interface(zlogp, zoneid,
2191 			    &nwiftab, &mcast_rt_v4_set, &mcast_rt_v6_set) !=
2192 			    Z_OK) {
2193 				(void) zonecfg_endnwifent(handle);
2194 				zonecfg_fini_handle(handle);
2195 				return (-1);
2196 			}
2197 			if (inet_pton(AF_INET6, nwiftab.zone_nwif_address,
2198 			    &in6) == 1)
2199 				saw_v6 = B_TRUE;
2200 		}
2201 		(void) zonecfg_endnwifent(handle);
2202 	}
2203 	zonecfg_fini_handle(handle);
2204 	(void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2205 	    sizeof (loopback_iftab.zone_nwif_physical));
2206 	(void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2207 	    sizeof (loopback_iftab.zone_nwif_address));
2208 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab, NULL, NULL)
2209 	    != Z_OK) {
2210 		return (-1);
2211 	}
2212 	if (saw_v6) {
2213 		(void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2214 		    sizeof (loopback_iftab.zone_nwif_address));
2215 		if (configure_one_interface(zlogp, zoneid,
2216 		    &loopback_iftab, NULL, NULL) != Z_OK) {
2217 			return (-1);
2218 		}
2219 	}
2220 	return (0);
2221 }
2222 
2223 static int
2224 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
2225     const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
2226 {
2227 	int fd;
2228 	struct strioctl ioc;
2229 	tcp_ioc_abort_conn_t conn;
2230 	int error;
2231 
2232 	conn.ac_local = *local;
2233 	conn.ac_remote = *remote;
2234 	conn.ac_start = TCPS_SYN_SENT;
2235 	conn.ac_end = TCPS_TIME_WAIT;
2236 	conn.ac_zoneid = zoneid;
2237 
2238 	ioc.ic_cmd = TCP_IOC_ABORT_CONN;
2239 	ioc.ic_timout = -1; /* infinite timeout */
2240 	ioc.ic_len = sizeof (conn);
2241 	ioc.ic_dp = (char *)&conn;
2242 
2243 	if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
2244 		zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
2245 		return (-1);
2246 	}
2247 
2248 	error = ioctl(fd, I_STR, &ioc);
2249 	(void) close(fd);
2250 	if (error == 0 || errno == ENOENT)	/* ENOENT is not an error */
2251 		return (0);
2252 	return (-1);
2253 }
2254 
2255 static int
2256 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
2257 {
2258 	struct sockaddr_storage l, r;
2259 	struct sockaddr_in *local, *remote;
2260 	struct sockaddr_in6 *local6, *remote6;
2261 	int error;
2262 
2263 	/*
2264 	 * Abort IPv4 connections.
2265 	 */
2266 	bzero(&l, sizeof (*local));
2267 	local = (struct sockaddr_in *)&l;
2268 	local->sin_family = AF_INET;
2269 	local->sin_addr.s_addr = INADDR_ANY;
2270 	local->sin_port = 0;
2271 
2272 	bzero(&r, sizeof (*remote));
2273 	remote = (struct sockaddr_in *)&r;
2274 	remote->sin_family = AF_INET;
2275 	remote->sin_addr.s_addr = INADDR_ANY;
2276 	remote->sin_port = 0;
2277 
2278 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2279 		return (error);
2280 
2281 	/*
2282 	 * Abort IPv6 connections.
2283 	 */
2284 	bzero(&l, sizeof (*local6));
2285 	local6 = (struct sockaddr_in6 *)&l;
2286 	local6->sin6_family = AF_INET6;
2287 	local6->sin6_port = 0;
2288 	local6->sin6_addr = in6addr_any;
2289 
2290 	bzero(&r, sizeof (*remote6));
2291 	remote6 = (struct sockaddr_in6 *)&r;
2292 	remote6->sin6_family = AF_INET6;
2293 	remote6->sin6_port = 0;
2294 	remote6->sin6_addr = in6addr_any;
2295 
2296 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2297 		return (error);
2298 	return (0);
2299 }
2300 
2301 static int
2302 devfsadm_call(zlog_t *zlogp, const char *arg)
2303 {
2304 	char *argv[4];
2305 	int status;
2306 
2307 	argv[0] = DEVFSADM;
2308 	argv[1] = (char *)arg;
2309 	argv[2] = zone_name;
2310 	argv[3] = NULL;
2311 	status = forkexec(zlogp, DEVFSADM_PATH, argv);
2312 	if (status == 0 || status == -1)
2313 		return (status);
2314 	zerror(zlogp, B_FALSE, "%s call (%s %s %s) unexpectedly returned %d",
2315 	    DEVFSADM, DEVFSADM_PATH, arg, zone_name, status);
2316 	return (-1);
2317 }
2318 
2319 static int
2320 devfsadm_register(zlog_t *zlogp)
2321 {
2322 	/*
2323 	 * Ready the zone's devices.
2324 	 */
2325 	return (devfsadm_call(zlogp, "-z"));
2326 }
2327 
2328 static int
2329 devfsadm_unregister(zlog_t *zlogp)
2330 {
2331 	return (devfsadm_call(zlogp, "-Z"));
2332 }
2333 
2334 static int
2335 get_privset(zlog_t *zlogp, priv_set_t *privs, boolean_t mount_cmd)
2336 {
2337 	int error = -1;
2338 	zone_dochandle_t handle;
2339 	char *privname = NULL;
2340 
2341 	if (mount_cmd) {
2342 		if (zonecfg_default_privset(privs) == Z_OK)
2343 			return (0);
2344 		zerror(zlogp, B_FALSE,
2345 		    "failed to determine the zone's default privilege set");
2346 		return (-1);
2347 	}
2348 
2349 	if ((handle = zonecfg_init_handle()) == NULL) {
2350 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2351 		return (-1);
2352 	}
2353 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2354 		zerror(zlogp, B_FALSE, "invalid configuration");
2355 		zonecfg_fini_handle(handle);
2356 		return (-1);
2357 	}
2358 
2359 	switch (zonecfg_get_privset(handle, privs, &privname)) {
2360 	case Z_OK:
2361 		error = 0;
2362 		break;
2363 	case Z_PRIV_PROHIBITED:
2364 		zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
2365 		    "within the zone's privilege set", privname);
2366 		break;
2367 	case Z_PRIV_REQUIRED:
2368 		zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
2369 		    "from the zone's privilege set", privname);
2370 		break;
2371 	case Z_PRIV_UNKNOWN:
2372 		zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
2373 		    "in the zone's privilege set", privname);
2374 		break;
2375 	default:
2376 		zerror(zlogp, B_FALSE, "failed to determine the zone's "
2377 		    "privilege set");
2378 		break;
2379 	}
2380 
2381 	free(privname);
2382 	zonecfg_fini_handle(handle);
2383 	return (error);
2384 }
2385 
2386 static int
2387 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2388 {
2389 	nvlist_t *nvl = NULL;
2390 	char *nvl_packed = NULL;
2391 	size_t nvl_size = 0;
2392 	nvlist_t **nvlv = NULL;
2393 	int rctlcount = 0;
2394 	int error = -1;
2395 	zone_dochandle_t handle;
2396 	struct zone_rctltab rctltab;
2397 	rctlblk_t *rctlblk = NULL;
2398 
2399 	*bufp = NULL;
2400 	*bufsizep = 0;
2401 
2402 	if ((handle = zonecfg_init_handle()) == NULL) {
2403 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2404 		return (-1);
2405 	}
2406 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2407 		zerror(zlogp, B_FALSE, "invalid configuration");
2408 		zonecfg_fini_handle(handle);
2409 		return (-1);
2410 	}
2411 
2412 	rctltab.zone_rctl_valptr = NULL;
2413 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
2414 		zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
2415 		goto out;
2416 	}
2417 
2418 	if (zonecfg_setrctlent(handle) != Z_OK) {
2419 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
2420 		goto out;
2421 	}
2422 
2423 	if ((rctlblk = malloc(rctlblk_size())) == NULL) {
2424 		zerror(zlogp, B_TRUE, "memory allocation failed");
2425 		goto out;
2426 	}
2427 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2428 		struct zone_rctlvaltab *rctlval;
2429 		uint_t i, count;
2430 		const char *name = rctltab.zone_rctl_name;
2431 
2432 		/* zoneadm should have already warned about unknown rctls. */
2433 		if (!zonecfg_is_rctl(name)) {
2434 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2435 			rctltab.zone_rctl_valptr = NULL;
2436 			continue;
2437 		}
2438 		count = 0;
2439 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2440 		    rctlval = rctlval->zone_rctlval_next) {
2441 			count++;
2442 		}
2443 		if (count == 0) {	/* ignore */
2444 			continue;	/* Nothing to free */
2445 		}
2446 		if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
2447 			goto out;
2448 		i = 0;
2449 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2450 		    rctlval = rctlval->zone_rctlval_next, i++) {
2451 			if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
2452 				zerror(zlogp, B_TRUE, "%s failed",
2453 				    "nvlist_alloc");
2454 				goto out;
2455 			}
2456 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2457 			    != Z_OK) {
2458 				zerror(zlogp, B_FALSE, "invalid rctl value: "
2459 				    "(priv=%s,limit=%s,action=%s)",
2460 				    rctlval->zone_rctlval_priv,
2461 				    rctlval->zone_rctlval_limit,
2462 				    rctlval->zone_rctlval_action);
2463 				goto out;
2464 			}
2465 			if (!zonecfg_valid_rctl(name, rctlblk)) {
2466 				zerror(zlogp, B_FALSE,
2467 				    "(priv=%s,limit=%s,action=%s) is not a "
2468 				    "valid value for rctl '%s'",
2469 				    rctlval->zone_rctlval_priv,
2470 				    rctlval->zone_rctlval_limit,
2471 				    rctlval->zone_rctlval_action,
2472 				    name);
2473 				goto out;
2474 			}
2475 			if (nvlist_add_uint64(nvlv[i], "privilege",
2476 			    rctlblk_get_privilege(rctlblk)) != 0) {
2477 				zerror(zlogp, B_FALSE, "%s failed",
2478 				    "nvlist_add_uint64");
2479 				goto out;
2480 			}
2481 			if (nvlist_add_uint64(nvlv[i], "limit",
2482 			    rctlblk_get_value(rctlblk)) != 0) {
2483 				zerror(zlogp, B_FALSE, "%s failed",
2484 				    "nvlist_add_uint64");
2485 				goto out;
2486 			}
2487 			if (nvlist_add_uint64(nvlv[i], "action",
2488 			    (uint_t)rctlblk_get_local_action(rctlblk, NULL))
2489 			    != 0) {
2490 				zerror(zlogp, B_FALSE, "%s failed",
2491 				    "nvlist_add_uint64");
2492 				goto out;
2493 			}
2494 		}
2495 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2496 		rctltab.zone_rctl_valptr = NULL;
2497 		if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
2498 		    != 0) {
2499 			zerror(zlogp, B_FALSE, "%s failed",
2500 			    "nvlist_add_nvlist_array");
2501 			goto out;
2502 		}
2503 		for (i = 0; i < count; i++)
2504 			nvlist_free(nvlv[i]);
2505 		free(nvlv);
2506 		nvlv = NULL;
2507 		rctlcount++;
2508 	}
2509 	(void) zonecfg_endrctlent(handle);
2510 
2511 	if (rctlcount == 0) {
2512 		error = 0;
2513 		goto out;
2514 	}
2515 	if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
2516 	    != 0) {
2517 		zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
2518 		goto out;
2519 	}
2520 
2521 	error = 0;
2522 	*bufp = nvl_packed;
2523 	*bufsizep = nvl_size;
2524 
2525 out:
2526 	free(rctlblk);
2527 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2528 	if (error && nvl_packed != NULL)
2529 		free(nvl_packed);
2530 	if (nvl != NULL)
2531 		nvlist_free(nvl);
2532 	if (nvlv != NULL)
2533 		free(nvlv);
2534 	if (handle != NULL)
2535 		zonecfg_fini_handle(handle);
2536 	return (error);
2537 }
2538 
2539 static int
2540 get_zone_pool(zlog_t *zlogp, char *poolbuf, size_t bufsz)
2541 {
2542 	zone_dochandle_t handle;
2543 	int error;
2544 
2545 	if ((handle = zonecfg_init_handle()) == NULL) {
2546 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2547 		return (Z_NOMEM);
2548 	}
2549 	error = zonecfg_get_snapshot_handle(zone_name, handle);
2550 	if (error != Z_OK) {
2551 		zerror(zlogp, B_FALSE, "invalid configuration");
2552 		zonecfg_fini_handle(handle);
2553 		return (error);
2554 	}
2555 	error = zonecfg_get_pool(handle, poolbuf, bufsz);
2556 	zonecfg_fini_handle(handle);
2557 	return (error);
2558 }
2559 
2560 static int
2561 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2562 {
2563 	zone_dochandle_t handle;
2564 	struct zone_dstab dstab;
2565 	size_t total, offset, len;
2566 	int error = -1;
2567 	char *str;
2568 
2569 	*bufp = NULL;
2570 	*bufsizep = 0;
2571 
2572 	if ((handle = zonecfg_init_handle()) == NULL) {
2573 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2574 		return (-1);
2575 	}
2576 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2577 		zerror(zlogp, B_FALSE, "invalid configuration");
2578 		zonecfg_fini_handle(handle);
2579 		return (-1);
2580 	}
2581 
2582 	if (zonecfg_setdsent(handle) != Z_OK) {
2583 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
2584 		goto out;
2585 	}
2586 
2587 	total = 0;
2588 	while (zonecfg_getdsent(handle, &dstab) == Z_OK)
2589 		total += strlen(dstab.zone_dataset_name) + 1;
2590 	(void) zonecfg_enddsent(handle);
2591 
2592 	if (total == 0) {
2593 		error = 0;
2594 		goto out;
2595 	}
2596 
2597 	if ((str = malloc(total)) == NULL) {
2598 		zerror(zlogp, B_TRUE, "memory allocation failed");
2599 		goto out;
2600 	}
2601 
2602 	if (zonecfg_setdsent(handle) != Z_OK) {
2603 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
2604 		goto out;
2605 	}
2606 	offset = 0;
2607 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2608 		len = strlen(dstab.zone_dataset_name);
2609 		(void) strlcpy(str + offset, dstab.zone_dataset_name,
2610 		    sizeof (dstab.zone_dataset_name) - offset);
2611 		offset += len;
2612 		if (offset != total - 1)
2613 			str[offset++] = ',';
2614 	}
2615 	(void) zonecfg_enddsent(handle);
2616 
2617 	error = 0;
2618 	*bufp = str;
2619 	*bufsizep = total;
2620 
2621 out:
2622 	if (error != 0 && str != NULL)
2623 		free(str);
2624 	if (handle != NULL)
2625 		zonecfg_fini_handle(handle);
2626 
2627 	return (error);
2628 }
2629 
2630 /* ARGSUSED */
2631 static void
2632 zfs_error_handler(const char *fmt, va_list ap)
2633 {
2634 	/*
2635 	 * Do nothing - we interpret the failures from each libzfs call below.
2636 	 */
2637 }
2638 
2639 static int
2640 validate_datasets(zlog_t *zlogp)
2641 {
2642 	zone_dochandle_t handle;
2643 	struct zone_dstab dstab;
2644 	zfs_handle_t *zhp;
2645 
2646 	if ((handle = zonecfg_init_handle()) == NULL) {
2647 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2648 		return (-1);
2649 	}
2650 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2651 		zerror(zlogp, B_FALSE, "invalid configuration");
2652 		zonecfg_fini_handle(handle);
2653 		return (-1);
2654 	}
2655 
2656 	if (zonecfg_setdsent(handle) != Z_OK) {
2657 		zerror(zlogp, B_FALSE, "invalid configuration");
2658 		zonecfg_fini_handle(handle);
2659 		return (-1);
2660 	}
2661 
2662 	zfs_set_error_handler(zfs_error_handler);
2663 
2664 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
2665 
2666 		if ((zhp = zfs_open(dstab.zone_dataset_name,
2667 		    ZFS_TYPE_FILESYSTEM)) == NULL) {
2668 			zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
2669 			    dstab.zone_dataset_name);
2670 			zonecfg_fini_handle(handle);
2671 			return (-1);
2672 		}
2673 
2674 		/*
2675 		 * Automatically set the 'zoned' property.  We check the value
2676 		 * first because we'll get EPERM if it is already set.
2677 		 */
2678 		if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
2679 		    zfs_prop_set(zhp, ZFS_PROP_ZONED, "on") != 0) {
2680 			zerror(zlogp, B_FALSE, "cannot set 'zoned' "
2681 			    "property for ZFS dataset '%s'\n",
2682 			    dstab.zone_dataset_name);
2683 			zonecfg_fini_handle(handle);
2684 			zfs_close(zhp);
2685 			return (-1);
2686 		}
2687 
2688 		zfs_close(zhp);
2689 	}
2690 	(void) zonecfg_enddsent(handle);
2691 
2692 	zonecfg_fini_handle(handle);
2693 
2694 	return (0);
2695 }
2696 
2697 static int
2698 bind_to_pool(zlog_t *zlogp, zoneid_t zoneid)
2699 {
2700 	pool_conf_t *poolconf;
2701 	pool_t *pool;
2702 	char poolname[MAXPATHLEN];
2703 	int status;
2704 	int error;
2705 
2706 	/*
2707 	 * Find the pool mentioned in the zone configuration, and bind to it.
2708 	 */
2709 	error = get_zone_pool(zlogp, poolname, sizeof (poolname));
2710 	if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
2711 		/*
2712 		 * The property is not set on the zone, so the pool
2713 		 * should be bound to the default pool.  But that's
2714 		 * already done by the kernel, so we can just return.
2715 		 */
2716 		return (0);
2717 	}
2718 	if (error != Z_OK) {
2719 		/*
2720 		 * Not an error, even though it shouldn't be happening.
2721 		 */
2722 		zerror(zlogp, B_FALSE,
2723 		    "WARNING: unable to retrieve default pool.");
2724 		return (0);
2725 	}
2726 	/*
2727 	 * Don't do anything if pools aren't enabled.
2728 	 */
2729 	if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
2730 		zerror(zlogp, B_FALSE, "WARNING: pools facility not active; "
2731 		    "zone will not be bound to pool '%s'.", poolname);
2732 		return (0);
2733 	}
2734 	/*
2735 	 * Try to provide a sane error message if the requested pool doesn't
2736 	 * exist.
2737 	 */
2738 	if ((poolconf = pool_conf_alloc()) == NULL) {
2739 		zerror(zlogp, B_FALSE, "%s failed", "pool_conf_alloc");
2740 		return (-1);
2741 	}
2742 	if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
2743 	    PO_SUCCESS) {
2744 		zerror(zlogp, B_FALSE, "%s failed", "pool_conf_open");
2745 		pool_conf_free(poolconf);
2746 		return (-1);
2747 	}
2748 	pool = pool_get_pool(poolconf, poolname);
2749 	(void) pool_conf_close(poolconf);
2750 	pool_conf_free(poolconf);
2751 	if (pool == NULL) {
2752 		zerror(zlogp, B_FALSE, "WARNING: pool '%s' not found; "
2753 		    "using default pool.", poolname);
2754 		return (0);
2755 	}
2756 	/*
2757 	 * Bind the zone to the pool.
2758 	 */
2759 	if (pool_set_binding(poolname, P_ZONEID, zoneid) != PO_SUCCESS) {
2760 		zerror(zlogp, B_FALSE, "WARNING: unable to bind to pool '%s'; "
2761 		    "using default pool.", poolname);
2762 	}
2763 	return (0);
2764 }
2765 
2766 /*
2767  * Mount lower level home directories into/from current zone
2768  * Share exported directories specified in dfstab for zone
2769  */
2770 static int
2771 tsol_mounts(zlog_t *zlogp, char *zone_name, char *rootpath)
2772 {
2773 	zoneid_t *zids = NULL;
2774 	priv_set_t *zid_privs;
2775 	const priv_impl_info_t *ip = NULL;
2776 	uint_t nzents_saved;
2777 	uint_t nzents;
2778 	int i;
2779 	char readonly[] = "ro";
2780 	struct zone_fstab lower_fstab;
2781 	char *argv[4];
2782 
2783 	if (!is_system_labeled())
2784 		return (0);
2785 
2786 	if (zid_label == NULL) {
2787 		zid_label = m_label_alloc(MAC_LABEL);
2788 		if (zid_label == NULL)
2789 			return (-1);
2790 	}
2791 
2792 	/* Make sure our zone has an /export/home dir */
2793 	(void) make_one_dir(zlogp, rootpath, "/export/home",
2794 	    DEFAULT_DIR_MODE);
2795 
2796 	lower_fstab.zone_fs_raw[0] = '\0';
2797 	(void) strlcpy(lower_fstab.zone_fs_type, MNTTYPE_LOFS,
2798 	    sizeof (lower_fstab.zone_fs_type));
2799 	lower_fstab.zone_fs_options = NULL;
2800 	(void) zonecfg_add_fs_option(&lower_fstab, readonly);
2801 
2802 	/*
2803 	 * Get the list of zones from the kernel
2804 	 */
2805 	if (zone_list(NULL, &nzents) != 0) {
2806 		zerror(zlogp, B_TRUE, "unable to list zones");
2807 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
2808 		return (-1);
2809 	}
2810 again:
2811 	if (nzents == 0) {
2812 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
2813 		return (-1);
2814 	}
2815 
2816 	zids = malloc(nzents * sizeof (zoneid_t));
2817 	if (zids == NULL) {
2818 		zerror(zlogp, B_TRUE, "unable to allocate memory");
2819 		return (-1);
2820 	}
2821 	nzents_saved = nzents;
2822 
2823 	if (zone_list(zids, &nzents) != 0) {
2824 		zerror(zlogp, B_TRUE, "unable to list zones");
2825 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
2826 		free(zids);
2827 		return (-1);
2828 	}
2829 	if (nzents != nzents_saved) {
2830 		/* list changed, try again */
2831 		free(zids);
2832 		goto again;
2833 	}
2834 
2835 	ip = getprivimplinfo();
2836 	if ((zid_privs = priv_allocset()) == NULL) {
2837 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
2838 		zonecfg_free_fs_option_list(
2839 		    lower_fstab.zone_fs_options);
2840 		free(zids);
2841 		return (-1);
2842 	}
2843 
2844 	for (i = 0; i < nzents; i++) {
2845 		char zid_name[ZONENAME_MAX];
2846 		zone_state_t zid_state;
2847 		char zid_rpath[MAXPATHLEN];
2848 		struct stat stat_buf;
2849 
2850 		if (zids[i] == GLOBAL_ZONEID)
2851 			continue;
2852 
2853 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
2854 			continue;
2855 
2856 		/*
2857 		 * Do special setup for the zone we are booting
2858 		 */
2859 		if (strcmp(zid_name, zone_name) == 0) {
2860 			struct zone_fstab autofs_fstab;
2861 			char map_path[MAXPATHLEN];
2862 			int fd;
2863 
2864 			/*
2865 			 * Create auto_home_<zone> map for this zone
2866 			 * in the global zone. The local zone entry
2867 			 * will be created by automount when the zone
2868 			 * is booted.
2869 			 */
2870 
2871 			(void) snprintf(autofs_fstab.zone_fs_special,
2872 			    MAXPATHLEN, "auto_home_%s", zid_name);
2873 
2874 			(void) snprintf(autofs_fstab.zone_fs_dir, MAXPATHLEN,
2875 			    "/zone/%s/home", zid_name);
2876 
2877 			(void) snprintf(map_path, sizeof (map_path),
2878 			    "/etc/%s", autofs_fstab.zone_fs_special);
2879 			/*
2880 			 * If the map file doesn't exist create a template
2881 			 */
2882 			if ((fd = open(map_path, O_RDWR | O_CREAT | O_EXCL,
2883 			    S_IRUSR | S_IWUSR | S_IRGRP| S_IROTH)) != -1) {
2884 				int len;
2885 				char map_rec[MAXPATHLEN];
2886 
2887 				len = snprintf(map_rec, sizeof (map_rec),
2888 				    "+%s\n*\t-fstype=lofs\t:%s/export/home/&\n",
2889 				    autofs_fstab.zone_fs_special, rootpath);
2890 				(void) write(fd, map_rec, len);
2891 				(void) close(fd);
2892 			}
2893 
2894 			/*
2895 			 * Mount auto_home_<zone> in the global zone if absent.
2896 			 * If it's already of type autofs, then
2897 			 * don't mount it again.
2898 			 */
2899 			if ((stat(autofs_fstab.zone_fs_dir, &stat_buf) == -1) ||
2900 			    strcmp(stat_buf.st_fstype, MNTTYPE_AUTOFS) != 0) {
2901 				char optstr[] = "indirect,ignore,nobrowse";
2902 
2903 				(void) make_one_dir(zlogp, "",
2904 				    autofs_fstab.zone_fs_dir, DEFAULT_DIR_MODE);
2905 
2906 				/*
2907 				 * Mount will fail if automounter has already
2908 				 * processed the auto_home_<zonename> map
2909 				 */
2910 				(void) domount(zlogp, MNTTYPE_AUTOFS, optstr,
2911 				    autofs_fstab.zone_fs_special,
2912 				    autofs_fstab.zone_fs_dir);
2913 			}
2914 			continue;
2915 		}
2916 
2917 
2918 		if (zone_get_state(zid_name, &zid_state) != Z_OK ||
2919 		    (zid_state != ZONE_STATE_READY &&
2920 		    zid_state != ZONE_STATE_RUNNING))
2921 			/* Skip over zones without mounted filesystems */
2922 			continue;
2923 
2924 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
2925 		    sizeof (m_label_t)) < 0)
2926 			/* Skip over zones with unspecified label */
2927 			continue;
2928 
2929 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
2930 		    sizeof (zid_rpath)) == -1)
2931 			/* Skip over zones with bad path */
2932 			continue;
2933 
2934 		if (zone_getattr(zids[i], ZONE_ATTR_PRIVSET, zid_privs,
2935 		    sizeof (priv_chunk_t) * ip->priv_setsize) == -1)
2936 			/* Skip over zones with bad privs */
2937 			continue;
2938 
2939 		/*
2940 		 * Reading down is valid according to our label model
2941 		 * but some customers want to disable it because it
2942 		 * allows execute down and other possible attacks.
2943 		 * Therefore, we restrict this feature to zones that
2944 		 * have the NET_MAC_AWARE privilege which is required
2945 		 * for NFS read-down semantics.
2946 		 */
2947 		if ((bldominates(zlabel, zid_label)) &&
2948 		    (priv_ismember(zprivs, PRIV_NET_MAC_AWARE))) {
2949 			/*
2950 			 * Our zone dominates this one.
2951 			 * Create a lofs mount from lower zone's /export/home
2952 			 */
2953 			(void) snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
2954 			    "%s/zone/%s/export/home", rootpath, zid_name);
2955 
2956 			/*
2957 			 * If the target is already an LOFS mount
2958 			 * then don't do it again.
2959 			 */
2960 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
2961 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
2962 
2963 				if (snprintf(lower_fstab.zone_fs_special,
2964 				    MAXPATHLEN, "%s/export",
2965 				    zid_rpath) > MAXPATHLEN)
2966 					continue;
2967 
2968 				/*
2969 				 * Make sure the lower-level home exists
2970 				 */
2971 				if (make_one_dir(zlogp,
2972 				    lower_fstab.zone_fs_special,
2973 				    "/home", DEFAULT_DIR_MODE) != 0)
2974 					continue;
2975 
2976 				(void) strlcat(lower_fstab.zone_fs_special,
2977 				    "/home", MAXPATHLEN);
2978 
2979 				/*
2980 				 * Mount can fail because the lower-level
2981 				 * zone may have already done a mount up.
2982 				 */
2983 				(void) mount_one(zlogp, &lower_fstab, "");
2984 			}
2985 		} else if ((bldominates(zid_label, zlabel)) &&
2986 		    (priv_ismember(zid_privs, PRIV_NET_MAC_AWARE))) {
2987 			/*
2988 			 * This zone dominates our zone.
2989 			 * Create a lofs mount from our zone's /export/home
2990 			 */
2991 			if (snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
2992 			    "%s/zone/%s/export/home", zid_rpath,
2993 			    zone_name) > MAXPATHLEN)
2994 				continue;
2995 
2996 			/*
2997 			 * If the target is already an LOFS mount
2998 			 * then don't do it again.
2999 			 */
3000 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3001 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3002 
3003 				(void) snprintf(lower_fstab.zone_fs_special,
3004 				    MAXPATHLEN, "%s/export/home", rootpath);
3005 
3006 				/*
3007 				 * Mount can fail because the higher-level
3008 				 * zone may have already done a mount down.
3009 				 */
3010 				(void) mount_one(zlogp, &lower_fstab, "");
3011 			}
3012 		}
3013 	}
3014 	zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3015 	priv_freeset(zid_privs);
3016 	free(zids);
3017 
3018 	/*
3019 	 * Now share any exported directories from this zone.
3020 	 * Each zone can have its own dfstab.
3021 	 */
3022 
3023 	argv[0] = "zoneshare";
3024 	argv[1] = "-z";
3025 	argv[2] = zone_name;
3026 	argv[3] = NULL;
3027 
3028 	(void) forkexec(zlogp, "/usr/lib/zones/zoneshare", argv);
3029 	/* Don't check for errors since they don't affect the zone */
3030 
3031 	return (0);
3032 }
3033 
3034 /*
3035  * Unmount lofs mounts from higher level zones
3036  * Unshare nfs exported directories
3037  */
3038 static void
3039 tsol_unmounts(zlog_t *zlogp, char *zone_name)
3040 {
3041 	zoneid_t *zids = NULL;
3042 	uint_t nzents_saved;
3043 	uint_t nzents;
3044 	int i;
3045 	char *argv[4];
3046 	char path[MAXPATHLEN];
3047 
3048 	if (!is_system_labeled())
3049 		return;
3050 
3051 	/*
3052 	 * Get the list of zones from the kernel
3053 	 */
3054 	if (zone_list(NULL, &nzents) != 0) {
3055 		return;
3056 	}
3057 
3058 	if (zid_label == NULL) {
3059 		zid_label = m_label_alloc(MAC_LABEL);
3060 		if (zid_label == NULL)
3061 			return;
3062 	}
3063 
3064 again:
3065 	if (nzents == 0)
3066 		return;
3067 
3068 	zids = malloc(nzents * sizeof (zoneid_t));
3069 	if (zids == NULL) {
3070 		zerror(zlogp, B_TRUE, "unable to allocate memory");
3071 		return;
3072 	}
3073 	nzents_saved = nzents;
3074 
3075 	if (zone_list(zids, &nzents) != 0) {
3076 		free(zids);
3077 		return;
3078 	}
3079 	if (nzents != nzents_saved) {
3080 		/* list changed, try again */
3081 		free(zids);
3082 		goto again;
3083 	}
3084 
3085 	for (i = 0; i < nzents; i++) {
3086 		char zid_name[ZONENAME_MAX];
3087 		zone_state_t zid_state;
3088 		char zid_rpath[MAXPATHLEN];
3089 
3090 		if (zids[i] == GLOBAL_ZONEID)
3091 			continue;
3092 
3093 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3094 			continue;
3095 
3096 		/*
3097 		 * Skip the zone we are halting
3098 		 */
3099 		if (strcmp(zid_name, zone_name) == 0)
3100 			continue;
3101 
3102 		if ((zone_getattr(zids[i], ZONE_ATTR_STATUS, &zid_state,
3103 		    sizeof (zid_state)) < 0) ||
3104 		    (zid_state < ZONE_IS_READY))
3105 			/* Skip over zones without mounted filesystems */
3106 			continue;
3107 
3108 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3109 		    sizeof (m_label_t)) < 0)
3110 			/* Skip over zones with unspecified label */
3111 			continue;
3112 
3113 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3114 		    sizeof (zid_rpath)) == -1)
3115 			/* Skip over zones with bad path */
3116 			continue;
3117 
3118 		if (zlabel != NULL && bldominates(zid_label, zlabel)) {
3119 			/*
3120 			 * This zone dominates our zone.
3121 			 * Unmount the lofs mount of our zone's /export/home
3122 			 */
3123 
3124 			if (snprintf(path, MAXPATHLEN,
3125 			    "%s/zone/%s/export/home", zid_rpath,
3126 			    zone_name) > MAXPATHLEN)
3127 				continue;
3128 
3129 			/* Skip over mount failures */
3130 			(void) umount(path);
3131 		}
3132 	}
3133 	free(zids);
3134 
3135 	/*
3136 	 * Unmount global zone autofs trigger for this zone
3137 	 */
3138 	(void) snprintf(path, MAXPATHLEN, "/zone/%s/home", zone_name);
3139 	/* Skip over mount failures */
3140 	(void) umount(path);
3141 
3142 	/*
3143 	 * Next unshare any exported directories from this zone.
3144 	 */
3145 
3146 	argv[0] = "zoneunshare";
3147 	argv[1] = "-z";
3148 	argv[2] = zone_name;
3149 	argv[3] = NULL;
3150 
3151 	(void) forkexec(zlogp, "/usr/lib/zones/zoneunshare", argv);
3152 	/* Don't check for errors since they don't affect the zone */
3153 
3154 	/*
3155 	 * Finally, deallocate any devices in the zone.
3156 	 */
3157 
3158 	argv[0] = "deallocate";
3159 	argv[1] = "-Isz";
3160 	argv[2] = zone_name;
3161 	argv[3] = NULL;
3162 
3163 	(void) forkexec(zlogp, "/usr/sbin/deallocate", argv);
3164 	/* Don't check for errors since they don't affect the zone */
3165 }
3166 
3167 /*
3168  * Fetch the Trusted Extensions label and multi-level ports (MLPs) for
3169  * this zone.
3170  */
3171 static tsol_zcent_t *
3172 get_zone_label(zlog_t *zlogp, priv_set_t *privs)
3173 {
3174 	FILE *fp;
3175 	tsol_zcent_t *zcent = NULL;
3176 	char line[MAXTNZLEN];
3177 
3178 	if ((fp = fopen(TNZONECFG_PATH, "r")) == NULL) {
3179 		zerror(zlogp, B_TRUE, "%s", TNZONECFG_PATH);
3180 		return (NULL);
3181 	}
3182 
3183 	while (fgets(line, sizeof (line), fp) != NULL) {
3184 		/*
3185 		 * Check for malformed database
3186 		 */
3187 		if (strlen(line) == MAXTNZLEN - 1)
3188 			break;
3189 		if ((zcent = tsol_sgetzcent(line, NULL, NULL)) == NULL)
3190 			continue;
3191 		if (strcmp(zcent->zc_name, zone_name) == 0)
3192 			break;
3193 		tsol_freezcent(zcent);
3194 		zcent = NULL;
3195 	}
3196 	(void) fclose(fp);
3197 
3198 	if (zcent == NULL) {
3199 		zerror(zlogp, B_FALSE, "zone requires a label assignment. "
3200 		    "See tnzonecfg(4)");
3201 	} else {
3202 		if (zlabel == NULL)
3203 			zlabel = m_label_alloc(MAC_LABEL);
3204 		/*
3205 		 * Save this zone's privileges for later read-down processing
3206 		 */
3207 		if ((zprivs = priv_allocset()) == NULL) {
3208 			zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3209 			return (NULL);
3210 		} else {
3211 			priv_copyset(privs, zprivs);
3212 		}
3213 	}
3214 	return (zcent);
3215 }
3216 
3217 /*
3218  * Add the Trusted Extensions multi-level ports for this zone.
3219  */
3220 static void
3221 set_mlps(zlog_t *zlogp, zoneid_t zoneid, tsol_zcent_t *zcent)
3222 {
3223 	tsol_mlp_t *mlp;
3224 	tsol_mlpent_t tsme;
3225 
3226 	if (!is_system_labeled())
3227 		return;
3228 
3229 	tsme.tsme_zoneid = zoneid;
3230 	tsme.tsme_flags = 0;
3231 	for (mlp = zcent->zc_private_mlp; !TSOL_MLP_END(mlp); mlp++) {
3232 		tsme.tsme_mlp = *mlp;
3233 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3234 			zerror(zlogp, B_TRUE, "cannot set zone-specific MLP "
3235 			    "on %d-%d/%d", mlp->mlp_port,
3236 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3237 		}
3238 	}
3239 
3240 	tsme.tsme_flags = TSOL_MEF_SHARED;
3241 	for (mlp = zcent->zc_shared_mlp; !TSOL_MLP_END(mlp); mlp++) {
3242 		tsme.tsme_mlp = *mlp;
3243 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3244 			zerror(zlogp, B_TRUE, "cannot set shared MLP "
3245 			    "on %d-%d/%d", mlp->mlp_port,
3246 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3247 		}
3248 	}
3249 }
3250 
3251 static void
3252 remove_mlps(zlog_t *zlogp, zoneid_t zoneid)
3253 {
3254 	tsol_mlpent_t tsme;
3255 
3256 	if (!is_system_labeled())
3257 		return;
3258 
3259 	(void) memset(&tsme, 0, sizeof (tsme));
3260 	tsme.tsme_zoneid = zoneid;
3261 	if (tnmlp(TNDB_FLUSH, &tsme) != 0)
3262 		zerror(zlogp, B_TRUE, "cannot flush MLPs");
3263 }
3264 
3265 int
3266 prtmount(const char *fs, void *x) {
3267 	zerror((zlog_t *)x, B_FALSE, "  %s", fs);
3268 	return (0);
3269 }
3270 
3271 /*
3272  * Look for zones running on the main system that are using this root (or any
3273  * subdirectory of it).  Return B_TRUE and print an error if a conflicting zone
3274  * is found or if we can't tell.
3275  */
3276 static boolean_t
3277 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
3278 {
3279 	zoneid_t *zids = NULL;
3280 	uint_t nzids = 0;
3281 	boolean_t retv;
3282 	int rlen, zlen;
3283 	char zroot[MAXPATHLEN];
3284 	char zonename[ZONENAME_MAX];
3285 
3286 	for (;;) {
3287 		nzids += 10;
3288 		zids = malloc(nzids * sizeof (*zids));
3289 		if (zids == NULL) {
3290 			zerror(zlogp, B_TRUE, "unable to allocate memory");
3291 			return (B_TRUE);
3292 		}
3293 		if (zone_list(zids, &nzids) == 0)
3294 			break;
3295 		free(zids);
3296 	}
3297 	retv = B_FALSE;
3298 	rlen = strlen(rootpath);
3299 	while (nzids > 0) {
3300 		/*
3301 		 * Ignore errors; they just mean that the zone has disappeared
3302 		 * while we were busy.
3303 		 */
3304 		if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
3305 		    sizeof (zroot)) == -1)
3306 			continue;
3307 		zlen = strlen(zroot);
3308 		if (zlen > rlen)
3309 			zlen = rlen;
3310 		if (strncmp(rootpath, zroot, zlen) == 0 &&
3311 		    (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
3312 		    (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
3313 			if (getzonenamebyid(zids[nzids], zonename,
3314 			    sizeof (zonename)) == -1)
3315 				(void) snprintf(zonename, sizeof (zonename),
3316 				    "id %d", (int)zids[nzids]);
3317 			zerror(zlogp, B_FALSE,
3318 			    "zone root %s already in use by zone %s",
3319 			    rootpath, zonename);
3320 			retv = B_TRUE;
3321 			break;
3322 		}
3323 	}
3324 	free(zids);
3325 	return (retv);
3326 }
3327 
3328 /*
3329  * Search for loopback mounts that use this same source node (same device and
3330  * inode).  Return B_TRUE if there is one or if we can't tell.
3331  */
3332 static boolean_t
3333 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
3334 {
3335 	struct stat64 rst, zst;
3336 	struct mnttab *mnp;
3337 
3338 	if (stat64(rootpath, &rst) == -1) {
3339 		zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
3340 		return (B_TRUE);
3341 	}
3342 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
3343 		return (B_TRUE);
3344 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
3345 		if (mnp->mnt_fstype == NULL ||
3346 		    strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
3347 			continue;
3348 		/* We're looking at a loopback mount.  Stat it. */
3349 		if (mnp->mnt_special != NULL &&
3350 		    stat64(mnp->mnt_special, &zst) != -1 &&
3351 		    rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
3352 			zerror(zlogp, B_FALSE,
3353 			    "zone root %s is reachable through %s",
3354 			    rootpath, mnp->mnt_mountp);
3355 			return (B_TRUE);
3356 		}
3357 	}
3358 	return (B_FALSE);
3359 }
3360 
3361 zoneid_t
3362 vplat_create(zlog_t *zlogp, boolean_t mount_cmd)
3363 {
3364 	zoneid_t rval = -1;
3365 	priv_set_t *privs;
3366 	char rootpath[MAXPATHLEN];
3367 	char *rctlbuf = NULL;
3368 	size_t rctlbufsz = 0;
3369 	char *zfsbuf = NULL;
3370 	size_t zfsbufsz = 0;
3371 	zoneid_t zoneid = -1;
3372 	int xerr;
3373 	char *kzone;
3374 	FILE *fp = NULL;
3375 	tsol_zcent_t *zcent = NULL;
3376 	int match = 0;
3377 	int doi = 0;
3378 
3379 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
3380 		zerror(zlogp, B_TRUE, "unable to determine zone root");
3381 		return (-1);
3382 	}
3383 	if (zonecfg_in_alt_root())
3384 		resolve_lofs(zlogp, rootpath, sizeof (rootpath));
3385 
3386 	if ((privs = priv_allocset()) == NULL) {
3387 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3388 		return (-1);
3389 	}
3390 	priv_emptyset(privs);
3391 	if (get_privset(zlogp, privs, mount_cmd) != 0)
3392 		goto error;
3393 
3394 	if (!mount_cmd && get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
3395 		zerror(zlogp, B_FALSE, "Unable to get list of rctls");
3396 		goto error;
3397 	}
3398 
3399 	if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
3400 		zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
3401 		goto error;
3402 	}
3403 
3404 	if (!mount_cmd && is_system_labeled()) {
3405 		zcent = get_zone_label(zlogp, privs);
3406 		if (zcent != NULL) {
3407 			match = zcent->zc_match;
3408 			doi = zcent->zc_doi;
3409 			*zlabel = zcent->zc_label;
3410 		} else {
3411 			goto error;
3412 		}
3413 	}
3414 
3415 	kzone = zone_name;
3416 
3417 	/*
3418 	 * We must do this scan twice.  First, we look for zones running on the
3419 	 * main system that are using this root (or any subdirectory of it).
3420 	 * Next, we reduce to the shortest path and search for loopback mounts
3421 	 * that use this same source node (same device and inode).
3422 	 */
3423 	if (duplicate_zone_root(zlogp, rootpath))
3424 		goto error;
3425 	if (duplicate_reachable_path(zlogp, rootpath))
3426 		goto error;
3427 
3428 	if (mount_cmd) {
3429 		root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
3430 
3431 		/*
3432 		 * Forge up a special root for this zone.  When a zone is
3433 		 * mounted, we can't let the zone have its own root because the
3434 		 * tools that will be used in this "scratch zone" need access
3435 		 * to both the zone's resources and the running machine's
3436 		 * executables.
3437 		 *
3438 		 * Note that the mkdir here also catches read-only filesystems.
3439 		 */
3440 		if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
3441 			zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
3442 			goto error;
3443 		}
3444 		if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
3445 			goto error;
3446 	}
3447 
3448 	if (zonecfg_in_alt_root()) {
3449 		/*
3450 		 * If we are mounting up a zone in an alternate root partition,
3451 		 * then we have some additional work to do before starting the
3452 		 * zone.  First, resolve the root path down so that we're not
3453 		 * fooled by duplicates.  Then forge up an internal name for
3454 		 * the zone.
3455 		 */
3456 		if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
3457 			zerror(zlogp, B_TRUE, "cannot open mapfile");
3458 			goto error;
3459 		}
3460 		if (zonecfg_lock_scratch(fp) != 0) {
3461 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
3462 			goto error;
3463 		}
3464 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
3465 		    NULL, 0) == 0) {
3466 			zerror(zlogp, B_FALSE, "scratch zone already running");
3467 			goto error;
3468 		}
3469 		/* This is the preferred name */
3470 		(void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
3471 		    zone_name);
3472 		srandom(getpid());
3473 		while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
3474 		    0) == 0) {
3475 			/* This is just an arbitrary name; note "." usage */
3476 			(void) snprintf(kernzone, sizeof (kernzone),
3477 			    "SUNWlu.%08lX%08lX", random(), random());
3478 		}
3479 		kzone = kernzone;
3480 	}
3481 
3482 	xerr = 0;
3483 	if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
3484 	    rctlbufsz, zfsbuf, zfsbufsz, &xerr, match, doi, zlabel)) == -1) {
3485 		if (xerr == ZE_AREMOUNTS) {
3486 			if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
3487 				zerror(zlogp, B_FALSE,
3488 				    "An unknown file-system is mounted on "
3489 				    "a subdirectory of %s", rootpath);
3490 			} else {
3491 
3492 				zerror(zlogp, B_FALSE,
3493 				    "These file-systems are mounted on "
3494 				    "subdirectories of %s:", rootpath);
3495 				(void) zonecfg_find_mounts(rootpath,
3496 				    prtmount, zlogp);
3497 			}
3498 		} else if (xerr == ZE_CHROOTED) {
3499 			zerror(zlogp, B_FALSE, "%s: "
3500 			    "cannot create a zone from a chrooted "
3501 			    "environment", "zone_create");
3502 		} else {
3503 			zerror(zlogp, B_TRUE, "%s failed", "zone_create");
3504 		}
3505 		goto error;
3506 	}
3507 
3508 	if (zonecfg_in_alt_root() &&
3509 	    zonecfg_add_scratch(fp, zone_name, kernzone,
3510 	    zonecfg_get_root()) == -1) {
3511 		zerror(zlogp, B_TRUE, "cannot add mapfile entry");
3512 		goto error;
3513 	}
3514 
3515 	/*
3516 	 * The following is a warning, not an error, and is not performed when
3517 	 * merely mounting a zone for administrative use.
3518 	 */
3519 	if (!mount_cmd && bind_to_pool(zlogp, zoneid) != 0)
3520 		zerror(zlogp, B_FALSE, "WARNING: unable to bind zone to "
3521 		    "requested pool; using default pool.");
3522 	if (!mount_cmd)
3523 		set_mlps(zlogp, zoneid, zcent);
3524 	rval = zoneid;
3525 	zoneid = -1;
3526 
3527 error:
3528 	if (zoneid != -1)
3529 		(void) zone_destroy(zoneid);
3530 	if (rctlbuf != NULL)
3531 		free(rctlbuf);
3532 	priv_freeset(privs);
3533 	if (fp != NULL)
3534 		zonecfg_close_scratch(fp);
3535 	lofs_discard_mnttab();
3536 	if (zcent != NULL)
3537 		tsol_freezcent(zcent);
3538 	return (rval);
3539 }
3540 
3541 int
3542 vplat_bringup(zlog_t *zlogp, boolean_t mount_cmd)
3543 {
3544 	if (!mount_cmd && validate_datasets(zlogp) != 0) {
3545 		lofs_discard_mnttab();
3546 		return (-1);
3547 	}
3548 
3549 	if (create_dev_files(zlogp) != 0 ||
3550 	    mount_filesystems(zlogp, mount_cmd) != 0) {
3551 		lofs_discard_mnttab();
3552 		return (-1);
3553 	}
3554 	if (!mount_cmd && (devfsadm_register(zlogp) != 0 ||
3555 	    configure_network_interfaces(zlogp) != 0)) {
3556 		lofs_discard_mnttab();
3557 		return (-1);
3558 	}
3559 	lofs_discard_mnttab();
3560 	return (0);
3561 }
3562 
3563 static int
3564 lu_root_teardown(zlog_t *zlogp)
3565 {
3566 	char zroot[MAXPATHLEN];
3567 
3568 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
3569 		zerror(zlogp, B_FALSE, "unable to determine zone root");
3570 		return (-1);
3571 	}
3572 	root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
3573 
3574 	/*
3575 	 * At this point, the processes are gone, the filesystems (save the
3576 	 * root) are unmounted, and the zone is on death row.  But there may
3577 	 * still be creds floating about in the system that reference the
3578 	 * zone_t, and which pin down zone_rootvp causing this call to fail
3579 	 * with EBUSY.  Thus, we try for a little while before just giving up.
3580 	 * (How I wish this were not true, and umount2 just did the right
3581 	 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
3582 	 */
3583 	if (umount2(zroot, MS_FORCE) != 0) {
3584 		if (errno == ENOTSUP && umount2(zroot, 0) == 0)
3585 			goto unmounted;
3586 		if (errno == EBUSY) {
3587 			int tries = 10;
3588 
3589 			while (--tries >= 0) {
3590 				(void) sleep(1);
3591 				if (umount2(zroot, 0) == 0)
3592 					goto unmounted;
3593 				if (errno != EBUSY)
3594 					break;
3595 			}
3596 		}
3597 		zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
3598 		return (-1);
3599 	}
3600 unmounted:
3601 
3602 	/*
3603 	 * Only zones in an alternate root environment have scratch zone
3604 	 * entries.
3605 	 */
3606 	if (zonecfg_in_alt_root()) {
3607 		FILE *fp;
3608 		int retv;
3609 
3610 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
3611 			zerror(zlogp, B_TRUE, "cannot open mapfile");
3612 			return (-1);
3613 		}
3614 		retv = -1;
3615 		if (zonecfg_lock_scratch(fp) != 0)
3616 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
3617 		else if (zonecfg_delete_scratch(fp, kernzone) != 0)
3618 			zerror(zlogp, B_TRUE, "cannot delete map entry");
3619 		else
3620 			retv = 0;
3621 		zonecfg_close_scratch(fp);
3622 		return (retv);
3623 	} else {
3624 		return (0);
3625 	}
3626 }
3627 
3628 int
3629 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd)
3630 {
3631 	char *kzone;
3632 	zoneid_t zoneid;
3633 
3634 	kzone = zone_name;
3635 	if (zonecfg_in_alt_root()) {
3636 		FILE *fp;
3637 
3638 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
3639 			zerror(zlogp, B_TRUE, "unable to open map file");
3640 			goto error;
3641 		}
3642 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
3643 		    kernzone, sizeof (kernzone)) != 0) {
3644 			zerror(zlogp, B_FALSE, "unable to find scratch zone");
3645 			zonecfg_close_scratch(fp);
3646 			goto error;
3647 		}
3648 		zonecfg_close_scratch(fp);
3649 		kzone = kernzone;
3650 	}
3651 
3652 	if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
3653 		if (!bringup_failure_recovery)
3654 			zerror(zlogp, B_TRUE, "unable to get zoneid");
3655 		if (unmount_cmd)
3656 			(void) lu_root_teardown(zlogp);
3657 		goto error;
3658 	}
3659 
3660 	if (zone_shutdown(zoneid) != 0) {
3661 		zerror(zlogp, B_TRUE, "unable to shutdown zone");
3662 		goto error;
3663 	}
3664 
3665 	if (!unmount_cmd && devfsadm_unregister(zlogp) != 0)
3666 		goto error;
3667 
3668 	if (!unmount_cmd &&
3669 	    unconfigure_network_interfaces(zlogp, zoneid) != 0) {
3670 		zerror(zlogp, B_FALSE,
3671 		    "unable to unconfigure network interfaces in zone");
3672 		goto error;
3673 	}
3674 
3675 	if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
3676 		zerror(zlogp, B_TRUE, "unable to abort TCP connections");
3677 		goto error;
3678 	}
3679 
3680 	if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
3681 		zerror(zlogp, B_FALSE,
3682 		    "unable to unmount file systems in zone");
3683 		goto error;
3684 	}
3685 
3686 	remove_mlps(zlogp, zoneid);
3687 
3688 	if (zone_destroy(zoneid) != 0) {
3689 		zerror(zlogp, B_TRUE, "unable to destroy zone");
3690 		goto error;
3691 	}
3692 
3693 	/*
3694 	 * Special teardown for alternate boot environments: remove the tmpfs
3695 	 * root for the zone and then remove it from the map file.
3696 	 */
3697 	if (unmount_cmd && lu_root_teardown(zlogp) != 0)
3698 		goto error;
3699 
3700 	if (!unmount_cmd)
3701 		destroy_console_slave();
3702 
3703 	lofs_discard_mnttab();
3704 	return (0);
3705 
3706 error:
3707 	lofs_discard_mnttab();
3708 	return (-1);
3709 }
3710