xref: /titanic_52/usr/src/cmd/zoneadmd/vplat.c (revision 28406508b3a9fa1994317b410fa4afd93b3f8cc4)
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 2007 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 <sys/dlpi.h>
78 #include <libdlpi.h>
79 #include <libdladm.h>
80 
81 #include <inet/tcp.h>
82 #include <arpa/inet.h>
83 #include <netinet/in.h>
84 #include <net/route.h>
85 
86 #include <stdio.h>
87 #include <errno.h>
88 #include <fcntl.h>
89 #include <unistd.h>
90 #include <rctl.h>
91 #include <stdlib.h>
92 #include <string.h>
93 #include <strings.h>
94 #include <wait.h>
95 #include <limits.h>
96 #include <libgen.h>
97 #include <libzfs.h>
98 #include <libdevinfo.h>
99 #include <zone.h>
100 #include <assert.h>
101 #include <libcontract.h>
102 #include <libcontract_priv.h>
103 #include <uuid/uuid.h>
104 
105 #include <sys/mntio.h>
106 #include <sys/mnttab.h>
107 #include <sys/fs/autofs.h>	/* for _autofssys() */
108 #include <sys/fs/lofs_info.h>
109 #include <sys/fs/zfs.h>
110 
111 #include <pool.h>
112 #include <sys/pool.h>
113 #include <sys/priocntl.h>
114 
115 #include <libbrand.h>
116 #include <sys/brand.h>
117 #include <libzonecfg.h>
118 #include <synch.h>
119 
120 #include "zoneadmd.h"
121 #include <tsol/label.h>
122 #include <libtsnet.h>
123 #include <sys/priv.h>
124 
125 #define	V4_ADDR_LEN	32
126 #define	V6_ADDR_LEN	128
127 
128 /* 0755 is the default directory mode. */
129 #define	DEFAULT_DIR_MODE \
130 	(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
131 
132 #define	IPD_DEFAULT_OPTS \
133 	MNTOPT_RO "," MNTOPT_LOFS_NOSUB "," MNTOPT_NODEVICES
134 
135 #define	DFSTYPES	"/etc/dfs/fstypes"
136 #define	MAXTNZLEN	2048
137 
138 /* for routing socket */
139 static int rts_seqno = 0;
140 
141 /* mangled zone name when mounting in an alternate root environment */
142 static char kernzone[ZONENAME_MAX];
143 
144 /* array of cached mount entries for resolve_lofs */
145 static struct mnttab *resolve_lofs_mnts, *resolve_lofs_mnt_max;
146 
147 /* for Trusted Extensions */
148 static tsol_zcent_t *get_zone_label(zlog_t *, priv_set_t *);
149 static int tsol_mounts(zlog_t *, char *, char *);
150 static void tsol_unmounts(zlog_t *, char *);
151 static m_label_t *zlabel = NULL;
152 static m_label_t *zid_label = NULL;
153 static priv_set_t *zprivs = NULL;
154 
155 /* from libsocket, not in any header file */
156 extern int getnetmaskbyaddr(struct in_addr, struct in_addr *);
157 
158 /*
159  * An optimization for build_mnttable: reallocate (and potentially copy the
160  * data) only once every N times through the loop.
161  */
162 #define	MNTTAB_HUNK	32
163 
164 /*
165  * Private autofs system call
166  */
167 extern int _autofssys(int, void *);
168 
169 static int
170 autofs_cleanup(zoneid_t zoneid)
171 {
172 	/*
173 	 * Ask autofs to unmount all trigger nodes in the given zone.
174 	 */
175 	return (_autofssys(AUTOFS_UNMOUNTALL, (void *)zoneid));
176 }
177 
178 static void
179 free_mnttable(struct mnttab *mnt_array, uint_t nelem)
180 {
181 	uint_t i;
182 
183 	if (mnt_array == NULL)
184 		return;
185 	for (i = 0; i < nelem; i++) {
186 		free(mnt_array[i].mnt_mountp);
187 		free(mnt_array[i].mnt_fstype);
188 		free(mnt_array[i].mnt_special);
189 		free(mnt_array[i].mnt_mntopts);
190 		assert(mnt_array[i].mnt_time == NULL);
191 	}
192 	free(mnt_array);
193 }
194 
195 /*
196  * Build the mount table for the zone rooted at "zroot", storing the resulting
197  * array of struct mnttabs in "mnt_arrayp" and the number of elements in the
198  * array in "nelemp".
199  */
200 static int
201 build_mnttable(zlog_t *zlogp, const char *zroot, size_t zrootlen, FILE *mnttab,
202     struct mnttab **mnt_arrayp, uint_t *nelemp)
203 {
204 	struct mnttab mnt;
205 	struct mnttab *mnts;
206 	struct mnttab *mnp;
207 	uint_t nmnt;
208 
209 	rewind(mnttab);
210 	resetmnttab(mnttab);
211 	nmnt = 0;
212 	mnts = NULL;
213 	while (getmntent(mnttab, &mnt) == 0) {
214 		struct mnttab *tmp_array;
215 
216 		if (strncmp(mnt.mnt_mountp, zroot, zrootlen) != 0)
217 			continue;
218 		if (nmnt % MNTTAB_HUNK == 0) {
219 			tmp_array = realloc(mnts,
220 			    (nmnt + MNTTAB_HUNK) * sizeof (*mnts));
221 			if (tmp_array == NULL) {
222 				free_mnttable(mnts, nmnt);
223 				return (-1);
224 			}
225 			mnts = tmp_array;
226 		}
227 		mnp = &mnts[nmnt++];
228 
229 		/*
230 		 * Zero out any fields we're not using.
231 		 */
232 		(void) memset(mnp, 0, sizeof (*mnp));
233 
234 		if (mnt.mnt_special != NULL)
235 			mnp->mnt_special = strdup(mnt.mnt_special);
236 		if (mnt.mnt_mntopts != NULL)
237 			mnp->mnt_mntopts = strdup(mnt.mnt_mntopts);
238 		mnp->mnt_mountp = strdup(mnt.mnt_mountp);
239 		mnp->mnt_fstype = strdup(mnt.mnt_fstype);
240 		if ((mnt.mnt_special != NULL && mnp->mnt_special == NULL) ||
241 		    (mnt.mnt_mntopts != NULL && mnp->mnt_mntopts == NULL) ||
242 		    mnp->mnt_mountp == NULL || mnp->mnt_fstype == NULL) {
243 			zerror(zlogp, B_TRUE, "memory allocation failed");
244 			free_mnttable(mnts, nmnt);
245 			return (-1);
246 		}
247 	}
248 	*mnt_arrayp = mnts;
249 	*nelemp = nmnt;
250 	return (0);
251 }
252 
253 /*
254  * This is an optimization.  The resolve_lofs function is used quite frequently
255  * to manipulate file paths, and on a machine with a large number of zones,
256  * there will be a huge number of mounted file systems.  Thus, we trigger a
257  * reread of the list of mount points
258  */
259 static void
260 lofs_discard_mnttab(void)
261 {
262 	free_mnttable(resolve_lofs_mnts,
263 	    resolve_lofs_mnt_max - resolve_lofs_mnts);
264 	resolve_lofs_mnts = resolve_lofs_mnt_max = NULL;
265 }
266 
267 static int
268 lofs_read_mnttab(zlog_t *zlogp)
269 {
270 	FILE *mnttab;
271 	uint_t nmnts;
272 
273 	if ((mnttab = fopen(MNTTAB, "r")) == NULL)
274 		return (-1);
275 	if (build_mnttable(zlogp, "", 0, mnttab, &resolve_lofs_mnts,
276 	    &nmnts) == -1) {
277 		(void) fclose(mnttab);
278 		return (-1);
279 	}
280 	(void) fclose(mnttab);
281 	resolve_lofs_mnt_max = resolve_lofs_mnts + nmnts;
282 	return (0);
283 }
284 
285 /*
286  * This function loops over potential loopback mounts and symlinks in a given
287  * path and resolves them all down to an absolute path.
288  */
289 static void
290 resolve_lofs(zlog_t *zlogp, char *path, size_t pathlen)
291 {
292 	int len, arlen;
293 	const char *altroot;
294 	char tmppath[MAXPATHLEN];
295 	boolean_t outside_altroot;
296 
297 	if ((len = resolvepath(path, tmppath, sizeof (tmppath))) == -1)
298 		return;
299 	tmppath[len] = '\0';
300 	(void) strlcpy(path, tmppath, sizeof (tmppath));
301 
302 	/* This happens once per zoneadmd operation. */
303 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
304 		return;
305 
306 	altroot = zonecfg_get_root();
307 	arlen = strlen(altroot);
308 	outside_altroot = B_FALSE;
309 	for (;;) {
310 		struct mnttab *mnp;
311 
312 		/* Search in reverse order to find longest match */
313 		for (mnp = resolve_lofs_mnt_max - 1; mnp >= resolve_lofs_mnts;
314 		    mnp--) {
315 			if (mnp->mnt_fstype == NULL ||
316 			    mnp->mnt_mountp == NULL ||
317 			    mnp->mnt_special == NULL)
318 				continue;
319 			len = strlen(mnp->mnt_mountp);
320 			if (strncmp(mnp->mnt_mountp, path, len) == 0 &&
321 			    (path[len] == '/' || path[len] == '\0'))
322 				break;
323 		}
324 		if (mnp < resolve_lofs_mnts)
325 			break;
326 		/* If it's not a lofs then we're done */
327 		if (strcmp(mnp->mnt_fstype, MNTTYPE_LOFS) != 0)
328 			break;
329 		if (outside_altroot) {
330 			char *cp;
331 			int olen = sizeof (MNTOPT_RO) - 1;
332 
333 			/*
334 			 * If we run into a read-only mount outside of the
335 			 * alternate root environment, then the user doesn't
336 			 * want this path to be made read-write.
337 			 */
338 			if (mnp->mnt_mntopts != NULL &&
339 			    (cp = strstr(mnp->mnt_mntopts, MNTOPT_RO)) !=
340 			    NULL &&
341 			    (cp == mnp->mnt_mntopts || cp[-1] == ',') &&
342 			    (cp[olen] == '\0' || cp[olen] == ',')) {
343 				break;
344 			}
345 		} else if (arlen > 0 &&
346 		    (strncmp(mnp->mnt_special, altroot, arlen) != 0 ||
347 		    (mnp->mnt_special[arlen] != '\0' &&
348 		    mnp->mnt_special[arlen] != '/'))) {
349 			outside_altroot = B_TRUE;
350 		}
351 		/* use temporary buffer because new path might be longer */
352 		(void) snprintf(tmppath, sizeof (tmppath), "%s%s",
353 		    mnp->mnt_special, path + len);
354 		if ((len = resolvepath(tmppath, path, pathlen)) == -1)
355 			break;
356 		path[len] = '\0';
357 	}
358 }
359 
360 /*
361  * For a regular mount, check if a replacement lofs mount is needed because the
362  * referenced device is already mounted somewhere.
363  */
364 static int
365 check_lofs_needed(zlog_t *zlogp, struct zone_fstab *fsptr)
366 {
367 	struct mnttab *mnp;
368 	zone_fsopt_t *optptr, *onext;
369 
370 	/* This happens once per zoneadmd operation. */
371 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
372 		return (-1);
373 
374 	/*
375 	 * If this special node isn't already in use, then it's ours alone;
376 	 * no need to worry about conflicting mounts.
377 	 */
378 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
379 	    mnp++) {
380 		if (strcmp(mnp->mnt_special, fsptr->zone_fs_special) == 0)
381 			break;
382 	}
383 	if (mnp >= resolve_lofs_mnt_max)
384 		return (0);
385 
386 	/*
387 	 * Convert this duplicate mount into a lofs mount.
388 	 */
389 	(void) strlcpy(fsptr->zone_fs_special, mnp->mnt_mountp,
390 	    sizeof (fsptr->zone_fs_special));
391 	(void) strlcpy(fsptr->zone_fs_type, MNTTYPE_LOFS,
392 	    sizeof (fsptr->zone_fs_type));
393 	fsptr->zone_fs_raw[0] = '\0';
394 
395 	/*
396 	 * Discard all but one of the original options and set that to be the
397 	 * same set of options used for inherit package directory resources.
398 	 */
399 	optptr = fsptr->zone_fs_options;
400 	if (optptr == NULL) {
401 		optptr = malloc(sizeof (*optptr));
402 		if (optptr == NULL) {
403 			zerror(zlogp, B_TRUE, "cannot mount %s",
404 			    fsptr->zone_fs_dir);
405 			return (-1);
406 		}
407 	} else {
408 		while ((onext = optptr->zone_fsopt_next) != NULL) {
409 			optptr->zone_fsopt_next = onext->zone_fsopt_next;
410 			free(onext);
411 		}
412 	}
413 	(void) strcpy(optptr->zone_fsopt_opt, IPD_DEFAULT_OPTS);
414 	optptr->zone_fsopt_next = NULL;
415 	fsptr->zone_fs_options = optptr;
416 	return (0);
417 }
418 
419 static int
420 make_one_dir(zlog_t *zlogp, const char *prefix, const char *subdir, mode_t mode)
421 {
422 	char path[MAXPATHLEN];
423 	struct stat st;
424 
425 	if (snprintf(path, sizeof (path), "%s%s", prefix, subdir) >
426 	    sizeof (path)) {
427 		zerror(zlogp, B_FALSE, "pathname %s%s is too long", prefix,
428 		    subdir);
429 		return (-1);
430 	}
431 
432 	if (lstat(path, &st) == 0) {
433 		/*
434 		 * We don't check the file mode since presumably the zone
435 		 * administrator may have had good reason to change the mode,
436 		 * and we don't need to second guess him.
437 		 */
438 		if (!S_ISDIR(st.st_mode)) {
439 			if (is_system_labeled() &&
440 			    S_ISREG(st.st_mode)) {
441 				/*
442 				 * The need to mount readonly copies of
443 				 * global zone /etc/ files is unique to
444 				 * Trusted Extensions.
445 				 */
446 				if (strncmp(subdir, "/etc/",
447 				    strlen("/etc/")) != 0) {
448 					zerror(zlogp, B_FALSE,
449 					    "%s is not in /etc", path);
450 					return (-1);
451 				}
452 			} else {
453 				zerror(zlogp, B_FALSE,
454 				    "%s is not a directory", path);
455 				return (-1);
456 			}
457 		}
458 	} else if (mkdirp(path, mode) != 0) {
459 		if (errno == EROFS)
460 			zerror(zlogp, B_FALSE, "Could not mkdir %s.\nIt is on "
461 			    "a read-only file system in this local zone.\nMake "
462 			    "sure %s exists in the global zone.", path, subdir);
463 		else
464 			zerror(zlogp, B_TRUE, "mkdirp of %s failed", path);
465 		return (-1);
466 	}
467 	return (0);
468 }
469 
470 static void
471 free_remote_fstypes(char **types)
472 {
473 	uint_t i;
474 
475 	if (types == NULL)
476 		return;
477 	for (i = 0; types[i] != NULL; i++)
478 		free(types[i]);
479 	free(types);
480 }
481 
482 static char **
483 get_remote_fstypes(zlog_t *zlogp)
484 {
485 	char **types = NULL;
486 	FILE *fp;
487 	char buf[MAXPATHLEN];
488 	char fstype[MAXPATHLEN];
489 	uint_t lines = 0;
490 	uint_t i;
491 
492 	if ((fp = fopen(DFSTYPES, "r")) == NULL) {
493 		zerror(zlogp, B_TRUE, "failed to open %s", DFSTYPES);
494 		return (NULL);
495 	}
496 	/*
497 	 * Count the number of lines
498 	 */
499 	while (fgets(buf, sizeof (buf), fp) != NULL)
500 		lines++;
501 	if (lines == 0)	/* didn't read anything; empty file */
502 		goto out;
503 	rewind(fp);
504 	/*
505 	 * Allocate enough space for a NULL-terminated array.
506 	 */
507 	types = calloc(lines + 1, sizeof (char *));
508 	if (types == NULL) {
509 		zerror(zlogp, B_TRUE, "memory allocation failed");
510 		goto out;
511 	}
512 	i = 0;
513 	while (fgets(buf, sizeof (buf), fp) != NULL) {
514 		/* LINTED - fstype is big enough to hold buf */
515 		if (sscanf(buf, "%s", fstype) == 0) {
516 			zerror(zlogp, B_FALSE, "unable to parse %s", DFSTYPES);
517 			free_remote_fstypes(types);
518 			types = NULL;
519 			goto out;
520 		}
521 		types[i] = strdup(fstype);
522 		if (types[i] == NULL) {
523 			zerror(zlogp, B_TRUE, "memory allocation failed");
524 			free_remote_fstypes(types);
525 			types = NULL;
526 			goto out;
527 		}
528 		i++;
529 	}
530 out:
531 	(void) fclose(fp);
532 	return (types);
533 }
534 
535 static boolean_t
536 is_remote_fstype(const char *fstype, char *const *remote_fstypes)
537 {
538 	uint_t i;
539 
540 	if (remote_fstypes == NULL)
541 		return (B_FALSE);
542 	for (i = 0; remote_fstypes[i] != NULL; i++) {
543 		if (strcmp(remote_fstypes[i], fstype) == 0)
544 			return (B_TRUE);
545 	}
546 	return (B_FALSE);
547 }
548 
549 /*
550  * This converts a zone root path (normally of the form .../root) to a Live
551  * Upgrade scratch zone root (of the form .../lu).
552  */
553 static void
554 root_to_lu(zlog_t *zlogp, char *zroot, size_t zrootlen, boolean_t isresolved)
555 {
556 	assert(zone_isnative);
557 
558 	if (!isresolved && zonecfg_in_alt_root())
559 		resolve_lofs(zlogp, zroot, zrootlen);
560 	(void) strcpy(strrchr(zroot, '/') + 1, "lu");
561 }
562 
563 /*
564  * The general strategy for unmounting filesystems is as follows:
565  *
566  * - Remote filesystems may be dead, and attempting to contact them as
567  * part of a regular unmount may hang forever; we want to always try to
568  * forcibly unmount such filesystems and only fall back to regular
569  * unmounts if the filesystem doesn't support forced unmounts.
570  *
571  * - We don't want to unnecessarily corrupt metadata on local
572  * filesystems (ie UFS), so we want to start off with graceful unmounts,
573  * and only escalate to doing forced unmounts if we get stuck.
574  *
575  * We start off walking backwards through the mount table.  This doesn't
576  * give us strict ordering but ensures that we try to unmount submounts
577  * first.  We thus limit the number of failed umount2(2) calls.
578  *
579  * The mechanism for determining if we're stuck is to count the number
580  * of failed unmounts each iteration through the mount table.  This
581  * gives us an upper bound on the number of filesystems which remain
582  * mounted (autofs trigger nodes are dealt with separately).  If at the
583  * end of one unmount+autofs_cleanup cycle we still have the same number
584  * of mounts that we started out with, we're stuck and try a forced
585  * unmount.  If that fails (filesystem doesn't support forced unmounts)
586  * then we bail and are unable to teardown the zone.  If it succeeds,
587  * we're no longer stuck so we continue with our policy of trying
588  * graceful mounts first.
589  *
590  * Zone must be down (ie, no processes or threads active).
591  */
592 static int
593 unmount_filesystems(zlog_t *zlogp, zoneid_t zoneid, boolean_t unmount_cmd)
594 {
595 	int error = 0;
596 	FILE *mnttab;
597 	struct mnttab *mnts;
598 	uint_t nmnt;
599 	char zroot[MAXPATHLEN + 1];
600 	size_t zrootlen;
601 	uint_t oldcount = UINT_MAX;
602 	boolean_t stuck = B_FALSE;
603 	char **remote_fstypes = NULL;
604 
605 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
606 		zerror(zlogp, B_FALSE, "unable to determine zone root");
607 		return (-1);
608 	}
609 	if (unmount_cmd)
610 		root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
611 
612 	(void) strcat(zroot, "/");
613 	zrootlen = strlen(zroot);
614 
615 	/*
616 	 * For Trusted Extensions unmount each higher level zone's mount
617 	 * of our zone's /export/home
618 	 */
619 	if (!unmount_cmd)
620 		tsol_unmounts(zlogp, zone_name);
621 
622 	if ((mnttab = fopen(MNTTAB, "r")) == NULL) {
623 		zerror(zlogp, B_TRUE, "failed to open %s", MNTTAB);
624 		return (-1);
625 	}
626 	/*
627 	 * Use our hacky mntfs ioctl so we see everything, even mounts with
628 	 * MS_NOMNTTAB.
629 	 */
630 	if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0) {
631 		zerror(zlogp, B_TRUE, "unable to configure %s", MNTTAB);
632 		error++;
633 		goto out;
634 	}
635 
636 	/*
637 	 * Build the list of remote fstypes so we know which ones we
638 	 * should forcibly unmount.
639 	 */
640 	remote_fstypes = get_remote_fstypes(zlogp);
641 	for (; /* ever */; ) {
642 		uint_t newcount = 0;
643 		boolean_t unmounted;
644 		struct mnttab *mnp;
645 		char *path;
646 		uint_t i;
647 
648 		mnts = NULL;
649 		nmnt = 0;
650 		/*
651 		 * MNTTAB gives us a way to walk through mounted
652 		 * filesystems; we need to be able to walk them in
653 		 * reverse order, so we build a list of all mounted
654 		 * filesystems.
655 		 */
656 		if (build_mnttable(zlogp, zroot, zrootlen, mnttab, &mnts,
657 		    &nmnt) != 0) {
658 			error++;
659 			goto out;
660 		}
661 		for (i = 0; i < nmnt; i++) {
662 			mnp = &mnts[nmnt - i - 1]; /* access in reverse order */
663 			path = mnp->mnt_mountp;
664 			unmounted = B_FALSE;
665 			/*
666 			 * Try forced unmount first for remote filesystems.
667 			 *
668 			 * Not all remote filesystems support forced unmounts,
669 			 * so if this fails (ENOTSUP) we'll continue on
670 			 * and try a regular unmount.
671 			 */
672 			if (is_remote_fstype(mnp->mnt_fstype, remote_fstypes)) {
673 				if (umount2(path, MS_FORCE) == 0)
674 					unmounted = B_TRUE;
675 			}
676 			/*
677 			 * Try forced unmount if we're stuck.
678 			 */
679 			if (stuck) {
680 				if (umount2(path, MS_FORCE) == 0) {
681 					unmounted = B_TRUE;
682 					stuck = B_FALSE;
683 				} else {
684 					/*
685 					 * The first failure indicates a
686 					 * mount we won't be able to get
687 					 * rid of automatically, so we
688 					 * bail.
689 					 */
690 					error++;
691 					zerror(zlogp, B_FALSE,
692 					    "unable to unmount '%s'", path);
693 					free_mnttable(mnts, nmnt);
694 					goto out;
695 				}
696 			}
697 			/*
698 			 * Try regular unmounts for everything else.
699 			 */
700 			if (!unmounted && umount2(path, 0) != 0)
701 				newcount++;
702 		}
703 		free_mnttable(mnts, nmnt);
704 
705 		if (newcount == 0)
706 			break;
707 		if (newcount >= oldcount) {
708 			/*
709 			 * Last round didn't unmount anything; we're stuck and
710 			 * should start trying forced unmounts.
711 			 */
712 			stuck = B_TRUE;
713 		}
714 		oldcount = newcount;
715 
716 		/*
717 		 * Autofs doesn't let you unmount its trigger nodes from
718 		 * userland so we have to tell the kernel to cleanup for us.
719 		 */
720 		if (autofs_cleanup(zoneid) != 0) {
721 			zerror(zlogp, B_TRUE, "unable to remove autofs nodes");
722 			error++;
723 			goto out;
724 		}
725 	}
726 
727 out:
728 	free_remote_fstypes(remote_fstypes);
729 	(void) fclose(mnttab);
730 	return (error ? -1 : 0);
731 }
732 
733 static int
734 fs_compare(const void *m1, const void *m2)
735 {
736 	struct zone_fstab *i = (struct zone_fstab *)m1;
737 	struct zone_fstab *j = (struct zone_fstab *)m2;
738 
739 	return (strcmp(i->zone_fs_dir, j->zone_fs_dir));
740 }
741 
742 /*
743  * Fork and exec (and wait for) the mentioned binary with the provided
744  * arguments.  Returns (-1) if something went wrong with fork(2) or exec(2),
745  * returns the exit status otherwise.
746  *
747  * If we were unable to exec the provided pathname (for whatever
748  * reason), we return the special token ZEXIT_EXEC.  The current value
749  * of ZEXIT_EXEC doesn't conflict with legitimate exit codes of the
750  * consumers of this function; any future consumers must make sure this
751  * remains the case.
752  */
753 static int
754 forkexec(zlog_t *zlogp, const char *path, char *const argv[])
755 {
756 	pid_t child_pid;
757 	int child_status = 0;
758 
759 	/*
760 	 * Do not let another thread localize a message while we are forking.
761 	 */
762 	(void) mutex_lock(&msglock);
763 	child_pid = fork();
764 	(void) mutex_unlock(&msglock);
765 	if (child_pid == -1) {
766 		zerror(zlogp, B_TRUE, "could not fork for %s", argv[0]);
767 		return (-1);
768 	} else if (child_pid == 0) {
769 		closefrom(0);
770 		/* redirect stdin, stdout & stderr to /dev/null */
771 		(void) open("/dev/null", O_RDONLY);	/* stdin */
772 		(void) open("/dev/null", O_WRONLY);	/* stdout */
773 		(void) open("/dev/null", O_WRONLY);	/* stderr */
774 		(void) execv(path, argv);
775 		/*
776 		 * Since we are in the child, there is no point calling zerror()
777 		 * since there is nobody waiting to consume it.  So exit with a
778 		 * special code that the parent will recognize and call zerror()
779 		 * accordingly.
780 		 */
781 
782 		_exit(ZEXIT_EXEC);
783 	} else {
784 		(void) waitpid(child_pid, &child_status, 0);
785 	}
786 
787 	if (WIFSIGNALED(child_status)) {
788 		zerror(zlogp, B_FALSE, "%s unexpectedly terminated due to "
789 		    "signal %d", path, WTERMSIG(child_status));
790 		return (-1);
791 	}
792 	assert(WIFEXITED(child_status));
793 	if (WEXITSTATUS(child_status) == ZEXIT_EXEC) {
794 		zerror(zlogp, B_FALSE, "failed to exec %s", path);
795 		return (-1);
796 	}
797 	return (WEXITSTATUS(child_status));
798 }
799 
800 static int
801 dofsck(zlog_t *zlogp, const char *fstype, const char *rawdev)
802 {
803 	char cmdbuf[MAXPATHLEN];
804 	char *argv[4];
805 	int status;
806 
807 	/*
808 	 * We could alternatively have called /usr/sbin/fsck -F <fstype>, but
809 	 * that would cost us an extra fork/exec without buying us anything.
810 	 */
811 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck", fstype)
812 	    >= sizeof (cmdbuf)) {
813 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
814 		return (-1);
815 	}
816 
817 	argv[0] = "fsck";
818 	argv[1] = "-m";
819 	argv[2] = (char *)rawdev;
820 	argv[3] = NULL;
821 
822 	status = forkexec(zlogp, cmdbuf, argv);
823 	if (status == 0 || status == -1)
824 		return (status);
825 	zerror(zlogp, B_FALSE, "fsck of '%s' failed with exit status %d; "
826 	    "run fsck manually", rawdev, status);
827 	return (-1);
828 }
829 
830 static int
831 domount(zlog_t *zlogp, const char *fstype, const char *opts,
832     const char *special, const char *directory)
833 {
834 	char cmdbuf[MAXPATHLEN];
835 	char *argv[6];
836 	int status;
837 
838 	/*
839 	 * We could alternatively have called /usr/sbin/mount -F <fstype>, but
840 	 * that would cost us an extra fork/exec without buying us anything.
841 	 */
842 	if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount", fstype)
843 	    >= sizeof (cmdbuf)) {
844 		zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
845 		return (-1);
846 	}
847 	argv[0] = "mount";
848 	if (opts[0] == '\0') {
849 		argv[1] = (char *)special;
850 		argv[2] = (char *)directory;
851 		argv[3] = NULL;
852 	} else {
853 		argv[1] = "-o";
854 		argv[2] = (char *)opts;
855 		argv[3] = (char *)special;
856 		argv[4] = (char *)directory;
857 		argv[5] = NULL;
858 	}
859 
860 	status = forkexec(zlogp, cmdbuf, argv);
861 	if (status == 0 || status == -1)
862 		return (status);
863 	if (opts[0] == '\0')
864 		zerror(zlogp, B_FALSE, "\"%s %s %s\" "
865 		    "failed with exit code %d",
866 		    cmdbuf, special, directory, status);
867 	else
868 		zerror(zlogp, B_FALSE, "\"%s -o %s %s %s\" "
869 		    "failed with exit code %d",
870 		    cmdbuf, opts, special, directory, status);
871 	return (-1);
872 }
873 
874 /*
875  * Make sure if a given path exists, it is not a sym-link, and is a directory.
876  */
877 static int
878 check_path(zlog_t *zlogp, const char *path)
879 {
880 	struct stat statbuf;
881 	char respath[MAXPATHLEN];
882 	int res;
883 
884 	if (lstat(path, &statbuf) != 0) {
885 		if (errno == ENOENT)
886 			return (0);
887 		zerror(zlogp, B_TRUE, "can't stat %s", path);
888 		return (-1);
889 	}
890 	if (S_ISLNK(statbuf.st_mode)) {
891 		zerror(zlogp, B_FALSE, "%s is a symlink", path);
892 		return (-1);
893 	}
894 	if (!S_ISDIR(statbuf.st_mode)) {
895 		if (is_system_labeled() && S_ISREG(statbuf.st_mode)) {
896 			/*
897 			 * The need to mount readonly copies of
898 			 * global zone /etc/ files is unique to
899 			 * Trusted Extensions.
900 			 * The check for /etc/ via strstr() is to
901 			 * allow paths like $ZONEROOT/etc/passwd
902 			 */
903 			if (strstr(path, "/etc/") == NULL) {
904 				zerror(zlogp, B_FALSE,
905 				    "%s is not in /etc", path);
906 				return (-1);
907 			}
908 		} else {
909 			zerror(zlogp, B_FALSE, "%s is not a directory", path);
910 			return (-1);
911 		}
912 	}
913 	if ((res = resolvepath(path, respath, sizeof (respath))) == -1) {
914 		zerror(zlogp, B_TRUE, "unable to resolve path %s", path);
915 		return (-1);
916 	}
917 	respath[res] = '\0';
918 	if (strcmp(path, respath) != 0) {
919 		/*
920 		 * We don't like ".."s and "."s throwing us off
921 		 */
922 		zerror(zlogp, B_FALSE, "%s is not a canonical path", path);
923 		return (-1);
924 	}
925 	return (0);
926 }
927 
928 /*
929  * Check every component of rootpath/relpath.  If any component fails (ie,
930  * exists but isn't the canonical path to a directory), it is returned in
931  * badpath, which is assumed to be at least of size MAXPATHLEN.
932  *
933  * Relpath must begin with '/'.
934  */
935 static boolean_t
936 valid_mount_path(zlog_t *zlogp, const char *rootpath, const char *relpath)
937 {
938 	char abspath[MAXPATHLEN], *slashp;
939 
940 	/*
941 	 * Make sure abspath has at least one '/' after its rootpath
942 	 * component, and ends with '/'.
943 	 */
944 	if (snprintf(abspath, sizeof (abspath), "%s%s/", rootpath, relpath) >=
945 	    sizeof (abspath)) {
946 		zerror(zlogp, B_FALSE, "pathname %s%s is too long", rootpath,
947 		    relpath);
948 		return (B_FALSE);
949 	}
950 
951 	slashp = &abspath[strlen(rootpath)];
952 	assert(*slashp == '/');
953 	do {
954 		*slashp = '\0';
955 		if (check_path(zlogp, abspath) != 0)
956 			return (B_FALSE);
957 		*slashp = '/';
958 		slashp++;
959 	} while ((slashp = strchr(slashp, '/')) != NULL);
960 	return (B_TRUE);
961 }
962 
963 static int
964 mount_one_dev_device_cb(void *arg, const char *match, const char *name)
965 {
966 	di_prof_t prof = arg;
967 
968 	if (name == NULL)
969 		return (di_prof_add_dev(prof, match));
970 	return (di_prof_add_map(prof, match, name));
971 }
972 
973 static int
974 mount_one_dev_symlink_cb(void *arg, const char *source, const char *target)
975 {
976 	di_prof_t prof = arg;
977 
978 	return (di_prof_add_symlink(prof, source, target));
979 }
980 
981 static int
982 get_iptype(zlog_t *zlogp, zone_iptype_t *iptypep)
983 {
984 	zone_dochandle_t handle;
985 
986 	if ((handle = zonecfg_init_handle()) == NULL) {
987 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
988 		return (-1);
989 	}
990 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
991 		zerror(zlogp, B_FALSE, "invalid configuration");
992 		zonecfg_fini_handle(handle);
993 		return (-1);
994 	}
995 	if (zonecfg_get_iptype(handle, iptypep) != Z_OK) {
996 		zerror(zlogp, B_FALSE, "invalid ip-type configuration");
997 		zonecfg_fini_handle(handle);
998 		return (-1);
999 	}
1000 	zonecfg_fini_handle(handle);
1001 	return (0);
1002 }
1003 
1004 /*
1005  * Apply the standard lists of devices/symlinks/mappings and the user-specified
1006  * list of devices (via zonecfg) to the /dev filesystem.  The filesystem will
1007  * use these as a profile/filter to determine what exists in /dev.
1008  */
1009 static int
1010 mount_one_dev(zlog_t *zlogp, char *devpath)
1011 {
1012 	char			brand[MAXNAMELEN];
1013 	zone_dochandle_t	handle = NULL;
1014 	brand_handle_t		bh = NULL;
1015 	struct zone_devtab	ztab;
1016 	di_prof_t		prof = NULL;
1017 	int			err;
1018 	int			retval = -1;
1019 	zone_iptype_t		iptype;
1020 	const char 		*curr_iptype;
1021 
1022 	if (di_prof_init(devpath, &prof)) {
1023 		zerror(zlogp, B_TRUE, "failed to initialize profile");
1024 		goto cleanup;
1025 	}
1026 
1027 	/* Get a handle to the brand info for this zone */
1028 	if ((zone_get_brand(zone_name, brand, sizeof (brand)) != Z_OK) ||
1029 	    (bh = brand_open(brand)) == NULL) {
1030 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
1031 		goto cleanup;
1032 	}
1033 
1034 	if (get_iptype(zlogp, &iptype) < 0) {
1035 		zerror(zlogp, B_TRUE, "unable to determine ip-type");
1036 		goto cleanup;
1037 	}
1038 	switch (iptype) {
1039 	case ZS_SHARED:
1040 		curr_iptype = "shared";
1041 		break;
1042 	case ZS_EXCLUSIVE:
1043 		curr_iptype = "exclusive";
1044 		break;
1045 	}
1046 
1047 	if (brand_platform_iter_devices(bh, zone_name,
1048 	    mount_one_dev_device_cb, prof, curr_iptype) != 0) {
1049 		zerror(zlogp, B_TRUE, "failed to add standard device");
1050 		goto cleanup;
1051 	}
1052 
1053 	if (brand_platform_iter_link(bh,
1054 	    mount_one_dev_symlink_cb, prof) != 0) {
1055 		zerror(zlogp, B_TRUE, "failed to add standard symlink");
1056 		goto cleanup;
1057 	}
1058 
1059 	/* Add user-specified devices and directories */
1060 	if ((handle = zonecfg_init_handle()) == NULL) {
1061 		zerror(zlogp, B_FALSE, "can't initialize zone handle");
1062 		goto cleanup;
1063 	}
1064 	if (err = zonecfg_get_handle(zone_name, handle)) {
1065 		zerror(zlogp, B_FALSE, "can't get handle for zone "
1066 		    "%s: %s", zone_name, zonecfg_strerror(err));
1067 		goto cleanup;
1068 	}
1069 	if (err = zonecfg_setdevent(handle)) {
1070 		zerror(zlogp, B_FALSE, "%s: %s", zone_name,
1071 		    zonecfg_strerror(err));
1072 		goto cleanup;
1073 	}
1074 	while (zonecfg_getdevent(handle, &ztab) == Z_OK) {
1075 		if (di_prof_add_dev(prof, ztab.zone_dev_match)) {
1076 			zerror(zlogp, B_TRUE, "failed to add "
1077 			    "user-specified device");
1078 			goto cleanup;
1079 		}
1080 	}
1081 	(void) zonecfg_enddevent(handle);
1082 
1083 	/* Send profile to kernel */
1084 	if (di_prof_commit(prof)) {
1085 		zerror(zlogp, B_TRUE, "failed to commit profile");
1086 		goto cleanup;
1087 	}
1088 
1089 	retval = 0;
1090 
1091 cleanup:
1092 	if (bh != NULL)
1093 		brand_close(bh);
1094 	if (handle)
1095 		zonecfg_fini_handle(handle);
1096 	if (prof)
1097 		di_prof_fini(prof);
1098 	return (retval);
1099 }
1100 
1101 static int
1102 mount_one(zlog_t *zlogp, struct zone_fstab *fsptr, const char *rootpath)
1103 {
1104 	char path[MAXPATHLEN];
1105 	char specpath[MAXPATHLEN];
1106 	char optstr[MAX_MNTOPT_STR];
1107 	zone_fsopt_t *optptr;
1108 	int rv;
1109 
1110 	if (!valid_mount_path(zlogp, rootpath, fsptr->zone_fs_dir)) {
1111 		zerror(zlogp, B_FALSE, "%s%s is not a valid mount point",
1112 		    rootpath, fsptr->zone_fs_dir);
1113 		return (-1);
1114 	}
1115 
1116 	if (make_one_dir(zlogp, rootpath, fsptr->zone_fs_dir,
1117 	    DEFAULT_DIR_MODE) != 0)
1118 		return (-1);
1119 
1120 	(void) snprintf(path, sizeof (path), "%s%s", rootpath,
1121 	    fsptr->zone_fs_dir);
1122 
1123 	if (strlen(fsptr->zone_fs_special) == 0) {
1124 		/*
1125 		 * A zero-length special is how we distinguish IPDs from
1126 		 * general-purpose FSs.  Make sure it mounts from a place that
1127 		 * can be seen via the alternate zone's root.
1128 		 */
1129 		if (snprintf(specpath, sizeof (specpath), "%s%s",
1130 		    zonecfg_get_root(), fsptr->zone_fs_dir) >=
1131 		    sizeof (specpath)) {
1132 			zerror(zlogp, B_FALSE, "cannot mount %s: path too "
1133 			    "long in alternate root", fsptr->zone_fs_dir);
1134 			return (-1);
1135 		}
1136 		if (zonecfg_in_alt_root())
1137 			resolve_lofs(zlogp, specpath, sizeof (specpath));
1138 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS,
1139 		    specpath, path) != 0) {
1140 			zerror(zlogp, B_TRUE, "failed to loopback mount %s",
1141 			    specpath);
1142 			return (-1);
1143 		}
1144 		return (0);
1145 	}
1146 
1147 	/*
1148 	 * In general the strategy here is to do just as much verification as
1149 	 * necessary to avoid crashing or otherwise doing something bad; if the
1150 	 * administrator initiated the operation via zoneadm(1m), he'll get
1151 	 * auto-verification which will let him know what's wrong.  If he
1152 	 * modifies the zone configuration of a running zone and doesn't attempt
1153 	 * to verify that it's OK we won't crash but won't bother trying to be
1154 	 * too helpful either.  zoneadm verify is only a couple keystrokes away.
1155 	 */
1156 	if (!zonecfg_valid_fs_type(fsptr->zone_fs_type)) {
1157 		zerror(zlogp, B_FALSE, "cannot mount %s on %s: "
1158 		    "invalid file-system type %s", fsptr->zone_fs_special,
1159 		    fsptr->zone_fs_dir, fsptr->zone_fs_type);
1160 		return (-1);
1161 	}
1162 
1163 	/*
1164 	 * If we're looking at an alternate root environment, then construct
1165 	 * read-only loopback mounts as necessary.  For all lofs mounts, make
1166 	 * sure that the 'special' entry points inside the alternate root.  (We
1167 	 * don't do this with other mounts, as devfs isn't in the alternate
1168 	 * root, and we need to assume the device environment is roughly the
1169 	 * same.)
1170 	 */
1171 	if (zonecfg_in_alt_root()) {
1172 		struct stat64 st;
1173 
1174 		if (stat64(fsptr->zone_fs_special, &st) != -1 &&
1175 		    S_ISBLK(st.st_mode)) {
1176 			if (check_lofs_needed(zlogp, fsptr) == -1)
1177 				return (-1);
1178 		} else if (strcmp(fsptr->zone_fs_type, MNTTYPE_LOFS) == 0) {
1179 			if (snprintf(specpath, sizeof (specpath), "%s%s",
1180 			    zonecfg_get_root(), fsptr->zone_fs_special) >=
1181 			    sizeof (specpath)) {
1182 				zerror(zlogp, B_FALSE, "cannot mount %s: path "
1183 				    "too long in alternate root",
1184 				    fsptr->zone_fs_special);
1185 				return (-1);
1186 			}
1187 			resolve_lofs(zlogp, specpath, sizeof (specpath));
1188 			(void) strlcpy(fsptr->zone_fs_special, specpath,
1189 			    sizeof (fsptr->zone_fs_special));
1190 		}
1191 	}
1192 
1193 	/*
1194 	 * Run 'fsck -m' if there's a device to fsck.
1195 	 */
1196 	if (fsptr->zone_fs_raw[0] != '\0' &&
1197 	    dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_raw) != 0)
1198 		return (-1);
1199 
1200 	/*
1201 	 * Build up mount option string.
1202 	 */
1203 	optstr[0] = '\0';
1204 	if (fsptr->zone_fs_options != NULL) {
1205 		(void) strlcpy(optstr, fsptr->zone_fs_options->zone_fsopt_opt,
1206 		    sizeof (optstr));
1207 		for (optptr = fsptr->zone_fs_options->zone_fsopt_next;
1208 		    optptr != NULL; optptr = optptr->zone_fsopt_next) {
1209 			(void) strlcat(optstr, ",", sizeof (optstr));
1210 			(void) strlcat(optstr, optptr->zone_fsopt_opt,
1211 			    sizeof (optstr));
1212 		}
1213 	}
1214 
1215 	if ((rv = domount(zlogp, fsptr->zone_fs_type, optstr,
1216 	    fsptr->zone_fs_special, path)) != 0)
1217 		return (rv);
1218 
1219 	/*
1220 	 * The mount succeeded.  If this was not a mount of /dev then
1221 	 * we're done.
1222 	 */
1223 	if (strcmp(fsptr->zone_fs_type, MNTTYPE_DEV) != 0)
1224 		return (0);
1225 
1226 	/*
1227 	 * We just mounted an instance of a /dev filesystem, so now we
1228 	 * need to configure it.
1229 	 */
1230 	return (mount_one_dev(zlogp, path));
1231 }
1232 
1233 static void
1234 free_fs_data(struct zone_fstab *fsarray, uint_t nelem)
1235 {
1236 	uint_t i;
1237 
1238 	if (fsarray == NULL)
1239 		return;
1240 	for (i = 0; i < nelem; i++)
1241 		zonecfg_free_fs_option_list(fsarray[i].zone_fs_options);
1242 	free(fsarray);
1243 }
1244 
1245 /*
1246  * This function initiates the creation of a small Solaris Environment for
1247  * scratch zone. The Environment creation process is split up into two
1248  * functions(build_mounted_pre_var() and build_mounted_post_var()). It
1249  * is done this way because:
1250  * 	We need to have both /etc and /var in the root of the scratchzone.
1251  * 	We loopback mount zone's own /etc and /var into the root of the
1252  * 	scratch zone. Unlike /etc, /var can be a seperate filesystem. So we
1253  * 	need to delay the mount of /var till the zone's root gets populated.
1254  *	So mounting of localdirs[](/etc and /var) have been moved to the
1255  * 	build_mounted_post_var() which gets called only after the zone
1256  * 	specific filesystems are mounted.
1257  */
1258 static boolean_t
1259 build_mounted_pre_var(zlog_t *zlogp, char *rootpath,
1260     size_t rootlen, const char *zonepath, char *luroot, size_t lurootlen)
1261 {
1262 	char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1263 	const char **cpp;
1264 	static const char *mkdirs[] = {
1265 		"/system", "/system/contract", "/system/object", "/proc",
1266 		"/dev", "/tmp", "/a", NULL
1267 	};
1268 	char *altstr;
1269 	FILE *fp;
1270 	uuid_t uuid;
1271 
1272 	assert(zone_isnative);
1273 
1274 	resolve_lofs(zlogp, rootpath, rootlen);
1275 	(void) snprintf(luroot, lurootlen, "%s/lu", zonepath);
1276 	resolve_lofs(zlogp, luroot, lurootlen);
1277 	(void) snprintf(tmp, sizeof (tmp), "%s/bin", luroot);
1278 	(void) symlink("./usr/bin", tmp);
1279 
1280 	/*
1281 	 * These are mostly special mount points; not handled here.  (See
1282 	 * zone_mount_early.)
1283 	 */
1284 	for (cpp = mkdirs; *cpp != NULL; cpp++) {
1285 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1286 		if (mkdir(tmp, 0755) != 0) {
1287 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1288 			return (B_FALSE);
1289 		}
1290 	}
1291 	/*
1292 	 * This is here to support lucopy.  If there's an instance of this same
1293 	 * zone on the current running system, then we mount its root up as
1294 	 * read-only inside the scratch zone.
1295 	 */
1296 	(void) zonecfg_get_uuid(zone_name, uuid);
1297 	altstr = strdup(zonecfg_get_root());
1298 	if (altstr == NULL) {
1299 		zerror(zlogp, B_TRUE, "memory allocation failed");
1300 		return (B_FALSE);
1301 	}
1302 	zonecfg_set_root("");
1303 	(void) strlcpy(tmp, zone_name, sizeof (tmp));
1304 	(void) zonecfg_get_name_by_uuid(uuid, tmp, sizeof (tmp));
1305 	if (zone_get_rootpath(tmp, fromdir, sizeof (fromdir)) == Z_OK &&
1306 	    strcmp(fromdir, rootpath) != 0) {
1307 		(void) snprintf(tmp, sizeof (tmp), "%s/b", luroot);
1308 		if (mkdir(tmp, 0755) != 0) {
1309 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1310 			return (B_FALSE);
1311 		}
1312 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, fromdir,
1313 		    tmp) != 0) {
1314 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1315 			    fromdir);
1316 			return (B_FALSE);
1317 		}
1318 	}
1319 	zonecfg_set_root(altstr);
1320 	free(altstr);
1321 
1322 	if ((fp = zonecfg_open_scratch(luroot, B_TRUE)) == NULL) {
1323 		zerror(zlogp, B_TRUE, "cannot open zone mapfile");
1324 		return (B_FALSE);
1325 	}
1326 	(void) ftruncate(fileno(fp), 0);
1327 	if (zonecfg_add_scratch(fp, zone_name, kernzone, "/") == -1) {
1328 		zerror(zlogp, B_TRUE, "cannot add zone mapfile entry");
1329 	}
1330 	zonecfg_close_scratch(fp);
1331 	(void) snprintf(tmp, sizeof (tmp), "%s/a", luroot);
1332 	if (domount(zlogp, MNTTYPE_LOFS, "", rootpath, tmp) != 0)
1333 		return (B_FALSE);
1334 	(void) strlcpy(rootpath, tmp, rootlen);
1335 	return (B_TRUE);
1336 }
1337 
1338 
1339 static boolean_t
1340 build_mounted_post_var(zlog_t *zlogp, char *rootpath, const char *luroot)
1341 {
1342 	char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1343 	const char **cpp;
1344 	static const char *localdirs[] = {
1345 		"/etc", "/var", NULL
1346 	};
1347 	static const char *loopdirs[] = {
1348 		"/etc/lib", "/etc/fs", "/lib", "/sbin", "/platform",
1349 		"/usr", NULL
1350 	};
1351 	static const char *tmpdirs[] = {
1352 		"/tmp", "/var/run", NULL
1353 	};
1354 	struct stat st;
1355 
1356 	/*
1357 	 * These are mounted read-write from the zone undergoing upgrade.  We
1358 	 * must be careful not to 'leak' things from the main system into the
1359 	 * zone, and this accomplishes that goal.
1360 	 */
1361 	for (cpp = localdirs; *cpp != NULL; cpp++) {
1362 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1363 		(void) snprintf(fromdir, sizeof (fromdir), "%s%s", rootpath,
1364 		    *cpp);
1365 		if (mkdir(tmp, 0755) != 0) {
1366 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1367 			return (B_FALSE);
1368 		}
1369 		if (domount(zlogp, MNTTYPE_LOFS, "", fromdir, tmp) != 0) {
1370 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1371 			    *cpp);
1372 			return (B_FALSE);
1373 		}
1374 	}
1375 
1376 	/*
1377 	 * These are things mounted read-only from the running system because
1378 	 * they contain binaries that must match system.
1379 	 */
1380 	for (cpp = loopdirs; *cpp != NULL; cpp++) {
1381 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1382 		if (mkdir(tmp, 0755) != 0) {
1383 			if (errno != EEXIST) {
1384 				zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1385 				return (B_FALSE);
1386 			}
1387 			if (lstat(tmp, &st) != 0) {
1388 				zerror(zlogp, B_TRUE, "cannot stat %s", tmp);
1389 				return (B_FALSE);
1390 			}
1391 			/*
1392 			 * Ignore any non-directories encountered.  These are
1393 			 * things that have been converted into symlinks
1394 			 * (/etc/fs and /etc/lib) and no longer need a lofs
1395 			 * fixup.
1396 			 */
1397 			if (!S_ISDIR(st.st_mode))
1398 				continue;
1399 		}
1400 		if (domount(zlogp, MNTTYPE_LOFS, IPD_DEFAULT_OPTS, *cpp,
1401 		    tmp) != 0) {
1402 			zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1403 			    *cpp);
1404 			return (B_FALSE);
1405 		}
1406 	}
1407 
1408 	/*
1409 	 * These are things with tmpfs mounted inside.
1410 	 */
1411 	for (cpp = tmpdirs; *cpp != NULL; cpp++) {
1412 		(void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1413 		if (mkdir(tmp, 0755) != 0 && errno != EEXIST) {
1414 			zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1415 			return (B_FALSE);
1416 		}
1417 
1418 		/*
1419 		 * We could set the mode for /tmp when we do the mkdir but
1420 		 * since that can be modified by the umask we will just set
1421 		 * the correct mode for /tmp now.
1422 		 */
1423 		if (strcmp(*cpp, "/tmp") == 0 && chmod(tmp, 01777) != 0) {
1424 			zerror(zlogp, B_TRUE, "cannot chmod %s", tmp);
1425 			return (B_FALSE);
1426 		}
1427 
1428 		if (domount(zlogp, MNTTYPE_TMPFS, "", "swap", tmp) != 0) {
1429 			zerror(zlogp, B_TRUE, "cannot mount swap on %s", *cpp);
1430 			return (B_FALSE);
1431 		}
1432 	}
1433 	return (B_TRUE);
1434 }
1435 
1436 typedef struct plat_gmount_cb_data {
1437 	zlog_t			*pgcd_zlogp;
1438 	struct zone_fstab	**pgcd_fs_tab;
1439 	int			*pgcd_num_fs;
1440 } plat_gmount_cb_data_t;
1441 
1442 /*
1443  * plat_gmount_cb() is a callback function invoked by libbrand to iterate
1444  * through all global brand platform mounts.
1445  */
1446 int
1447 plat_gmount_cb(void *data, const char *spec, const char *dir,
1448     const char *fstype, const char *opt)
1449 {
1450 	plat_gmount_cb_data_t	*cp = data;
1451 	zlog_t			*zlogp = cp->pgcd_zlogp;
1452 	struct zone_fstab	*fs_ptr = *cp->pgcd_fs_tab;
1453 	int			num_fs = *cp->pgcd_num_fs;
1454 	struct zone_fstab	*fsp, *tmp_ptr;
1455 
1456 	num_fs++;
1457 	if ((tmp_ptr = realloc(fs_ptr, num_fs * sizeof (*tmp_ptr))) == NULL) {
1458 		zerror(zlogp, B_TRUE, "memory allocation failed");
1459 		return (-1);
1460 	}
1461 
1462 	fs_ptr = tmp_ptr;
1463 	fsp = &fs_ptr[num_fs - 1];
1464 
1465 	/* update the callback struct passed in */
1466 	*cp->pgcd_fs_tab = fs_ptr;
1467 	*cp->pgcd_num_fs = num_fs;
1468 
1469 	fsp->zone_fs_raw[0] = '\0';
1470 	(void) strlcpy(fsp->zone_fs_special, spec,
1471 	    sizeof (fsp->zone_fs_special));
1472 	(void) strlcpy(fsp->zone_fs_dir, dir, sizeof (fsp->zone_fs_dir));
1473 	(void) strlcpy(fsp->zone_fs_type, fstype, sizeof (fsp->zone_fs_type));
1474 	fsp->zone_fs_options = NULL;
1475 	if (zonecfg_add_fs_option(fsp, (char *)opt) != Z_OK) {
1476 		zerror(zlogp, B_FALSE, "error adding property");
1477 		return (-1);
1478 	}
1479 
1480 	return (0);
1481 }
1482 
1483 static int
1484 mount_filesystems_ipdent(zone_dochandle_t handle, zlog_t *zlogp,
1485     struct zone_fstab **fs_tabp, int *num_fsp)
1486 {
1487 	struct zone_fstab *tmp_ptr, *fs_ptr, *fsp, fstab;
1488 	int num_fs;
1489 
1490 	num_fs = *num_fsp;
1491 	fs_ptr = *fs_tabp;
1492 
1493 	if (zonecfg_setipdent(handle) != Z_OK) {
1494 		zerror(zlogp, B_FALSE, "invalid configuration");
1495 		return (-1);
1496 	}
1497 	while (zonecfg_getipdent(handle, &fstab) == Z_OK) {
1498 		num_fs++;
1499 		if ((tmp_ptr = realloc(fs_ptr,
1500 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1501 			zerror(zlogp, B_TRUE, "memory allocation failed");
1502 			(void) zonecfg_endipdent(handle);
1503 			return (-1);
1504 		}
1505 
1506 		/* update the pointers passed in */
1507 		*fs_tabp = tmp_ptr;
1508 		*num_fsp = num_fs;
1509 
1510 		/*
1511 		 * IPDs logically only have a mount point; all other properties
1512 		 * are implied.
1513 		 */
1514 		fs_ptr = tmp_ptr;
1515 		fsp = &fs_ptr[num_fs - 1];
1516 		(void) strlcpy(fsp->zone_fs_dir,
1517 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1518 		fsp->zone_fs_special[0] = '\0';
1519 		fsp->zone_fs_raw[0] = '\0';
1520 		fsp->zone_fs_type[0] = '\0';
1521 		fsp->zone_fs_options = NULL;
1522 	}
1523 	(void) zonecfg_endipdent(handle);
1524 	return (0);
1525 }
1526 
1527 static int
1528 mount_filesystems_fsent(zone_dochandle_t handle, zlog_t *zlogp,
1529     struct zone_fstab **fs_tabp, int *num_fsp, int mount_cmd)
1530 {
1531 	struct zone_fstab *tmp_ptr, *fs_ptr, *fsp, fstab;
1532 	int num_fs;
1533 
1534 	num_fs = *num_fsp;
1535 	fs_ptr = *fs_tabp;
1536 
1537 	if (zonecfg_setfsent(handle) != Z_OK) {
1538 		zerror(zlogp, B_FALSE, "invalid configuration");
1539 		return (-1);
1540 	}
1541 	while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1542 		/*
1543 		 * ZFS filesystems will not be accessible under an alternate
1544 		 * root, since the pool will not be known.  Ignore them in this
1545 		 * case.
1546 		 */
1547 		if (mount_cmd && strcmp(fstab.zone_fs_type, MNTTYPE_ZFS) == 0)
1548 			continue;
1549 
1550 		num_fs++;
1551 		if ((tmp_ptr = realloc(fs_ptr,
1552 		    num_fs * sizeof (*tmp_ptr))) == NULL) {
1553 			zerror(zlogp, B_TRUE, "memory allocation failed");
1554 			(void) zonecfg_endfsent(handle);
1555 			return (-1);
1556 		}
1557 		/* update the pointers passed in */
1558 		*fs_tabp = tmp_ptr;
1559 		*num_fsp = num_fs;
1560 
1561 		fs_ptr = tmp_ptr;
1562 		fsp = &fs_ptr[num_fs - 1];
1563 		(void) strlcpy(fsp->zone_fs_dir,
1564 		    fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1565 		(void) strlcpy(fsp->zone_fs_special, fstab.zone_fs_special,
1566 		    sizeof (fsp->zone_fs_special));
1567 		(void) strlcpy(fsp->zone_fs_raw, fstab.zone_fs_raw,
1568 		    sizeof (fsp->zone_fs_raw));
1569 		(void) strlcpy(fsp->zone_fs_type, fstab.zone_fs_type,
1570 		    sizeof (fsp->zone_fs_type));
1571 		fsp->zone_fs_options = fstab.zone_fs_options;
1572 	}
1573 	(void) zonecfg_endfsent(handle);
1574 	return (0);
1575 }
1576 
1577 static int
1578 mount_filesystems(zlog_t *zlogp, boolean_t mount_cmd)
1579 {
1580 	char rootpath[MAXPATHLEN];
1581 	char zonepath[MAXPATHLEN];
1582 	char brand[MAXNAMELEN];
1583 	char luroot[MAXPATHLEN];
1584 	int i, num_fs = 0;
1585 	struct zone_fstab *fs_ptr = NULL;
1586 	zone_dochandle_t handle = NULL;
1587 	zone_state_t zstate;
1588 	brand_handle_t bh;
1589 	plat_gmount_cb_data_t cb;
1590 
1591 	if (zone_get_state(zone_name, &zstate) != Z_OK ||
1592 	    (zstate != ZONE_STATE_READY && zstate != ZONE_STATE_MOUNTED)) {
1593 		zerror(zlogp, B_FALSE,
1594 		    "zone must be in '%s' or '%s' state to mount file-systems",
1595 		    zone_state_str(ZONE_STATE_READY),
1596 		    zone_state_str(ZONE_STATE_MOUNTED));
1597 		goto bad;
1598 	}
1599 
1600 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
1601 		zerror(zlogp, B_TRUE, "unable to determine zone path");
1602 		goto bad;
1603 	}
1604 
1605 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
1606 		zerror(zlogp, B_TRUE, "unable to determine zone root");
1607 		goto bad;
1608 	}
1609 
1610 	if ((handle = zonecfg_init_handle()) == NULL) {
1611 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
1612 		goto bad;
1613 	}
1614 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK ||
1615 	    zonecfg_setfsent(handle) != Z_OK) {
1616 		zerror(zlogp, B_FALSE, "invalid configuration");
1617 		goto bad;
1618 	}
1619 
1620 	/* Get a handle to the brand info for this zone */
1621 	if ((zone_get_brand(zone_name, brand, sizeof (brand)) != Z_OK) ||
1622 	    (bh = brand_open(brand)) == NULL) {
1623 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
1624 		return (-1);
1625 	}
1626 
1627 	/*
1628 	 * Get the list of global filesystems to mount from the brand
1629 	 * configuration.
1630 	 */
1631 	cb.pgcd_zlogp = zlogp;
1632 	cb.pgcd_fs_tab = &fs_ptr;
1633 	cb.pgcd_num_fs = &num_fs;
1634 	if (brand_platform_iter_gmounts(bh, zonepath,
1635 	    plat_gmount_cb, &cb) != 0) {
1636 		zerror(zlogp, B_FALSE, "unable to mount filesystems");
1637 		brand_close(bh);
1638 		return (-1);
1639 	}
1640 	brand_close(bh);
1641 
1642 	/*
1643 	 * Iterate through the rest of the filesystems, first the IPDs, then
1644 	 * the general FSs.  Sort them all, then mount them in sorted order.
1645 	 * This is to make sure the higher level directories (e.g., /usr)
1646 	 * get mounted before any beneath them (e.g., /usr/local).
1647 	 */
1648 	if (mount_filesystems_ipdent(handle, zlogp, &fs_ptr, &num_fs) != 0)
1649 		goto bad;
1650 
1651 	if (mount_filesystems_fsent(handle, zlogp, &fs_ptr, &num_fs,
1652 	    mount_cmd) != 0)
1653 		goto bad;
1654 
1655 	zonecfg_fini_handle(handle);
1656 	handle = NULL;
1657 
1658 	/*
1659 	 * Normally when we mount a zone all the zone filesystems
1660 	 * get mounted relative to rootpath, which is usually
1661 	 * <zonepath>/root.  But when mounting a zone for administration
1662 	 * purposes via the zone "mount" state, build_mounted_pre_var()
1663 	 * updates rootpath to be <zonepath>/lu/a so we'll mount all
1664 	 * the zones filesystems there instead.
1665 	 *
1666 	 * build_mounted_pre_var() and build_mounted_post_var() will
1667 	 * also do some extra work to create directories and lofs mount
1668 	 * a bunch of global zone file system paths into <zonepath>/lu.
1669 	 *
1670 	 * This allows us to be able to enter the zone (now rooted at
1671 	 * <zonepath>/lu) and run the upgrade/patch tools that are in the
1672 	 * global zone and have them upgrade the to-be-modified zone's
1673 	 * files mounted on /a.  (Which mirrors the existing standard
1674 	 * upgrade environment.)
1675 	 *
1676 	 * There is of course one catch.  When doing the upgrade
1677 	 * we need <zoneroot>/lu/dev to be the /dev filesystem
1678 	 * for the zone and we don't want to have any /dev filesystem
1679 	 * mounted at <zoneroot>/lu/a/dev.  Since /dev is specified
1680 	 * as a normal zone filesystem by default we'll try to mount
1681 	 * it at <zoneroot>/lu/a/dev, so we have to detect this
1682 	 * case and instead mount it at <zoneroot>/lu/dev.
1683 	 *
1684 	 * All this work is done in three phases:
1685 	 *   1) Create and populate lu directory (build_mounted_pre_var()).
1686 	 *   2) Mount the required filesystems as per the zone configuration.
1687 	 *   3) Set up the rest of the scratch zone environment
1688 	 *	(build_mounted_post_var()).
1689 	 */
1690 	if (mount_cmd &&
1691 	    !build_mounted_pre_var(zlogp,
1692 	    rootpath, sizeof (rootpath), zonepath, luroot, sizeof (luroot)))
1693 		goto bad;
1694 
1695 	qsort(fs_ptr, num_fs, sizeof (*fs_ptr), fs_compare);
1696 
1697 	for (i = 0; i < num_fs; i++) {
1698 		if (mount_cmd &&
1699 		    strcmp(fs_ptr[i].zone_fs_dir, "/dev") == 0) {
1700 			size_t slen = strlen(rootpath) - 2;
1701 
1702 			/*
1703 			 * By default we'll try to mount /dev as /a/dev
1704 			 * but /dev is special and always goes at the top
1705 			 * so strip the trailing '/a' from the rootpath.
1706 			 */
1707 			assert(zone_isnative);
1708 			assert(strcmp(&rootpath[slen], "/a") == 0);
1709 			rootpath[slen] = '\0';
1710 			if (mount_one(zlogp, &fs_ptr[i], rootpath) != 0)
1711 				goto bad;
1712 			rootpath[slen] = '/';
1713 			continue;
1714 		}
1715 		if (mount_one(zlogp, &fs_ptr[i], rootpath) != 0)
1716 			goto bad;
1717 	}
1718 	if (mount_cmd &&
1719 	    !build_mounted_post_var(zlogp, rootpath, luroot))
1720 		goto bad;
1721 
1722 	/*
1723 	 * For Trusted Extensions cross-mount each lower level /export/home
1724 	 */
1725 	if (!mount_cmd && tsol_mounts(zlogp, zone_name, rootpath) != 0)
1726 		goto bad;
1727 
1728 	free_fs_data(fs_ptr, num_fs);
1729 
1730 	/*
1731 	 * Everything looks fine.
1732 	 */
1733 	return (0);
1734 
1735 bad:
1736 	if (handle != NULL)
1737 		zonecfg_fini_handle(handle);
1738 	free_fs_data(fs_ptr, num_fs);
1739 	return (-1);
1740 }
1741 
1742 /* caller makes sure neither parameter is NULL */
1743 static int
1744 addr2netmask(char *prefixstr, int maxprefixlen, uchar_t *maskstr)
1745 {
1746 	int prefixlen;
1747 
1748 	prefixlen = atoi(prefixstr);
1749 	if (prefixlen < 0 || prefixlen > maxprefixlen)
1750 		return (1);
1751 	while (prefixlen > 0) {
1752 		if (prefixlen >= 8) {
1753 			*maskstr++ = 0xFF;
1754 			prefixlen -= 8;
1755 			continue;
1756 		}
1757 		*maskstr |= 1 << (8 - prefixlen);
1758 		prefixlen--;
1759 	}
1760 	return (0);
1761 }
1762 
1763 /*
1764  * Tear down all interfaces belonging to the given zone.  This should
1765  * be called with the zone in a state other than "running", so that
1766  * interfaces can't be assigned to the zone after this returns.
1767  *
1768  * If anything goes wrong, log an error message and return an error.
1769  */
1770 static int
1771 unconfigure_shared_network_interfaces(zlog_t *zlogp, zoneid_t zone_id)
1772 {
1773 	struct lifnum lifn;
1774 	struct lifconf lifc;
1775 	struct lifreq *lifrp, lifrl;
1776 	int64_t lifc_flags = LIFC_NOXMIT | LIFC_ALLZONES;
1777 	int num_ifs, s, i, ret_code = 0;
1778 	uint_t bufsize;
1779 	char *buf = NULL;
1780 
1781 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1782 		zerror(zlogp, B_TRUE, "could not get socket");
1783 		ret_code = -1;
1784 		goto bad;
1785 	}
1786 	lifn.lifn_family = AF_UNSPEC;
1787 	lifn.lifn_flags = (int)lifc_flags;
1788 	if (ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) {
1789 		zerror(zlogp, B_TRUE,
1790 		    "could not determine number of network interfaces");
1791 		ret_code = -1;
1792 		goto bad;
1793 	}
1794 	num_ifs = lifn.lifn_count;
1795 	bufsize = num_ifs * sizeof (struct lifreq);
1796 	if ((buf = malloc(bufsize)) == NULL) {
1797 		zerror(zlogp, B_TRUE, "memory allocation failed");
1798 		ret_code = -1;
1799 		goto bad;
1800 	}
1801 	lifc.lifc_family = AF_UNSPEC;
1802 	lifc.lifc_flags = (int)lifc_flags;
1803 	lifc.lifc_len = bufsize;
1804 	lifc.lifc_buf = buf;
1805 	if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) {
1806 		zerror(zlogp, B_TRUE, "could not get configured network "
1807 		    "interfaces");
1808 		ret_code = -1;
1809 		goto bad;
1810 	}
1811 	lifrp = lifc.lifc_req;
1812 	for (i = lifc.lifc_len / sizeof (struct lifreq); i > 0; i--, lifrp++) {
1813 		(void) close(s);
1814 		if ((s = socket(lifrp->lifr_addr.ss_family, SOCK_DGRAM, 0)) <
1815 		    0) {
1816 			zerror(zlogp, B_TRUE, "%s: could not get socket",
1817 			    lifrl.lifr_name);
1818 			ret_code = -1;
1819 			continue;
1820 		}
1821 		(void) memset(&lifrl, 0, sizeof (lifrl));
1822 		(void) strncpy(lifrl.lifr_name, lifrp->lifr_name,
1823 		    sizeof (lifrl.lifr_name));
1824 		if (ioctl(s, SIOCGLIFZONE, (caddr_t)&lifrl) < 0) {
1825 			if (errno == ENXIO)
1826 				/*
1827 				 * Interface may have been removed by admin or
1828 				 * another zone halting.
1829 				 */
1830 				continue;
1831 			zerror(zlogp, B_TRUE,
1832 			    "%s: could not determine the zone to which this "
1833 			    "network interface is bound", lifrl.lifr_name);
1834 			ret_code = -1;
1835 			continue;
1836 		}
1837 		if (lifrl.lifr_zoneid == zone_id) {
1838 			if (ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifrl) < 0) {
1839 				zerror(zlogp, B_TRUE,
1840 				    "%s: could not remove network interface",
1841 				    lifrl.lifr_name);
1842 				ret_code = -1;
1843 				continue;
1844 			}
1845 		}
1846 	}
1847 bad:
1848 	if (s > 0)
1849 		(void) close(s);
1850 	if (buf)
1851 		free(buf);
1852 	return (ret_code);
1853 }
1854 
1855 static union	sockunion {
1856 	struct	sockaddr sa;
1857 	struct	sockaddr_in sin;
1858 	struct	sockaddr_dl sdl;
1859 	struct	sockaddr_in6 sin6;
1860 } so_dst, so_ifp;
1861 
1862 static struct {
1863 	struct	rt_msghdr hdr;
1864 	char	space[512];
1865 } rtmsg;
1866 
1867 static int
1868 salen(struct sockaddr *sa)
1869 {
1870 	switch (sa->sa_family) {
1871 	case AF_INET:
1872 		return (sizeof (struct sockaddr_in));
1873 	case AF_LINK:
1874 		return (sizeof (struct sockaddr_dl));
1875 	case AF_INET6:
1876 		return (sizeof (struct sockaddr_in6));
1877 	default:
1878 		return (sizeof (struct sockaddr));
1879 	}
1880 }
1881 
1882 #define	ROUNDUP_LONG(a) \
1883 	((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
1884 
1885 /*
1886  * Look up which zone is using a given IP address.  The address in question
1887  * is expected to have been stuffed into the structure to which lifr points
1888  * via a previous SIOCGLIFADDR ioctl().
1889  *
1890  * This is done using black router socket magic.
1891  *
1892  * Return the name of the zone on success or NULL on failure.
1893  *
1894  * This is a lot of code for a simple task; a new ioctl request to take care
1895  * of this might be a useful RFE.
1896  */
1897 
1898 static char *
1899 who_is_using(zlog_t *zlogp, struct lifreq *lifr)
1900 {
1901 	static char answer[ZONENAME_MAX];
1902 	pid_t pid;
1903 	int s, rlen, l, i;
1904 	char *cp = rtmsg.space;
1905 	struct sockaddr_dl *ifp = NULL;
1906 	struct sockaddr *sa;
1907 	char save_if_name[LIFNAMSIZ];
1908 
1909 	answer[0] = '\0';
1910 
1911 	pid = getpid();
1912 	if ((s = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
1913 		zerror(zlogp, B_TRUE, "could not get routing socket");
1914 		return (NULL);
1915 	}
1916 
1917 	if (lifr->lifr_addr.ss_family == AF_INET) {
1918 		struct sockaddr_in *sin4;
1919 
1920 		so_dst.sa.sa_family = AF_INET;
1921 		sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
1922 		so_dst.sin.sin_addr = sin4->sin_addr;
1923 	} else {
1924 		struct sockaddr_in6 *sin6;
1925 
1926 		so_dst.sa.sa_family = AF_INET6;
1927 		sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
1928 		so_dst.sin6.sin6_addr = sin6->sin6_addr;
1929 	}
1930 
1931 	so_ifp.sa.sa_family = AF_LINK;
1932 
1933 	(void) memset(&rtmsg, 0, sizeof (rtmsg));
1934 	rtmsg.hdr.rtm_type = RTM_GET;
1935 	rtmsg.hdr.rtm_flags = RTF_UP | RTF_HOST;
1936 	rtmsg.hdr.rtm_version = RTM_VERSION;
1937 	rtmsg.hdr.rtm_seq = ++rts_seqno;
1938 	rtmsg.hdr.rtm_addrs = RTA_IFP | RTA_DST;
1939 
1940 	l = ROUNDUP_LONG(salen(&so_dst.sa));
1941 	(void) memmove(cp, &(so_dst), l);
1942 	cp += l;
1943 	l = ROUNDUP_LONG(salen(&so_ifp.sa));
1944 	(void) memmove(cp, &(so_ifp), l);
1945 	cp += l;
1946 
1947 	rtmsg.hdr.rtm_msglen = l = cp - (char *)&rtmsg;
1948 
1949 	if ((rlen = write(s, &rtmsg, l)) < 0) {
1950 		zerror(zlogp, B_TRUE, "writing to routing socket");
1951 		return (NULL);
1952 	} else if (rlen < (int)rtmsg.hdr.rtm_msglen) {
1953 		zerror(zlogp, B_TRUE,
1954 		    "write to routing socket got only %d for len\n", rlen);
1955 		return (NULL);
1956 	}
1957 	do {
1958 		l = read(s, &rtmsg, sizeof (rtmsg));
1959 	} while (l > 0 && (rtmsg.hdr.rtm_seq != rts_seqno ||
1960 	    rtmsg.hdr.rtm_pid != pid));
1961 	if (l < 0) {
1962 		zerror(zlogp, B_TRUE, "reading from routing socket");
1963 		return (NULL);
1964 	}
1965 
1966 	if (rtmsg.hdr.rtm_version != RTM_VERSION) {
1967 		zerror(zlogp, B_FALSE,
1968 		    "routing message version %d not understood",
1969 		    rtmsg.hdr.rtm_version);
1970 		return (NULL);
1971 	}
1972 	if (rtmsg.hdr.rtm_msglen != (ushort_t)l) {
1973 		zerror(zlogp, B_FALSE, "message length mismatch, "
1974 		    "expected %d bytes, returned %d bytes",
1975 		    rtmsg.hdr.rtm_msglen, l);
1976 		return (NULL);
1977 	}
1978 	if (rtmsg.hdr.rtm_errno != 0)  {
1979 		errno = rtmsg.hdr.rtm_errno;
1980 		zerror(zlogp, B_TRUE, "RTM_GET routing socket message");
1981 		return (NULL);
1982 	}
1983 	if ((rtmsg.hdr.rtm_addrs & RTA_IFP) == 0) {
1984 		zerror(zlogp, B_FALSE, "network interface not found");
1985 		return (NULL);
1986 	}
1987 	cp = ((char *)(&rtmsg.hdr + 1));
1988 	for (i = 1; i != 0; i <<= 1) {
1989 		/* LINTED E_BAD_PTR_CAST_ALIGN */
1990 		sa = (struct sockaddr *)cp;
1991 		if (i != RTA_IFP) {
1992 			if ((i & rtmsg.hdr.rtm_addrs) != 0)
1993 				cp += ROUNDUP_LONG(salen(sa));
1994 			continue;
1995 		}
1996 		if (sa->sa_family == AF_LINK &&
1997 		    ((struct sockaddr_dl *)sa)->sdl_nlen != 0)
1998 			ifp = (struct sockaddr_dl *)sa;
1999 		break;
2000 	}
2001 	if (ifp == NULL) {
2002 		zerror(zlogp, B_FALSE, "network interface could not be "
2003 		    "determined");
2004 		return (NULL);
2005 	}
2006 
2007 	/*
2008 	 * We need to set the I/F name to what we got above, then do the
2009 	 * appropriate ioctl to get its zone name.  But lifr->lifr_name is
2010 	 * used by the calling function to do a REMOVEIF, so if we leave the
2011 	 * "good" zone's I/F name in place, *that* I/F will be removed instead
2012 	 * of the bad one.  So we save the old (bad) I/F name before over-
2013 	 * writing it and doing the ioctl, then restore it after the ioctl.
2014 	 */
2015 	(void) strlcpy(save_if_name, lifr->lifr_name, sizeof (save_if_name));
2016 	(void) strncpy(lifr->lifr_name, ifp->sdl_data, ifp->sdl_nlen);
2017 	lifr->lifr_name[ifp->sdl_nlen] = '\0';
2018 	i = ioctl(s, SIOCGLIFZONE, lifr);
2019 	(void) strlcpy(lifr->lifr_name, save_if_name, sizeof (save_if_name));
2020 	if (i < 0) {
2021 		zerror(zlogp, B_TRUE,
2022 		    "%s: could not determine the zone network interface "
2023 		    "belongs to", lifr->lifr_name);
2024 		return (NULL);
2025 	}
2026 	if (getzonenamebyid(lifr->lifr_zoneid, answer, sizeof (answer)) < 0)
2027 		(void) snprintf(answer, sizeof (answer), "%d",
2028 		    lifr->lifr_zoneid);
2029 
2030 	if (strlen(answer) > 0)
2031 		return (answer);
2032 	return (NULL);
2033 }
2034 
2035 typedef struct mcast_rtmsg_s {
2036 	struct rt_msghdr	m_rtm;
2037 	union {
2038 		struct {
2039 			struct sockaddr_in	m_dst;
2040 			struct sockaddr_in	m_gw;
2041 			struct sockaddr_in	m_netmask;
2042 		} m_v4;
2043 		struct {
2044 			struct sockaddr_in6	m_dst;
2045 			struct sockaddr_in6	m_gw;
2046 			struct sockaddr_in6	m_netmask;
2047 		} m_v6;
2048 	} m_u;
2049 } mcast_rtmsg_t;
2050 #define	m_dst4		m_u.m_v4.m_dst
2051 #define	m_dst6		m_u.m_v6.m_dst
2052 #define	m_gw4		m_u.m_v4.m_gw
2053 #define	m_gw6		m_u.m_v6.m_gw
2054 #define	m_netmask4	m_u.m_v4.m_netmask
2055 #define	m_netmask6	m_u.m_v6.m_netmask
2056 
2057 /*
2058  * Configures a single interface: a new virtual interface is added, based on
2059  * the physical interface nwiftabptr->zone_nwif_physical, with the address
2060  * specified in nwiftabptr->zone_nwif_address, for zone zone_id.  Note that
2061  * the "address" can be an IPv6 address (with a /prefixlength required), an
2062  * IPv4 address (with a /prefixlength optional), or a name; for the latter,
2063  * an IPv4 name-to-address resolution will be attempted.
2064  *
2065  * A default interface route for multicast is created on the first IPv4 and
2066  * IPv6 interfaces (that have the IFF_MULTICAST flag set), respectively.
2067  * This should really be done in the init scripts if we ever allow zones to
2068  * modify the routing tables.
2069  *
2070  * If anything goes wrong, we log an detailed error message, attempt to tear
2071  * down whatever we set up and return an error.
2072  */
2073 static int
2074 configure_one_interface(zlog_t *zlogp, zoneid_t zone_id,
2075     struct zone_nwiftab *nwiftabptr, boolean_t *mcast_rt_v4_setp,
2076     boolean_t *mcast_rt_v6_setp)
2077 {
2078 	struct lifreq lifr;
2079 	struct sockaddr_in netmask4;
2080 	struct sockaddr_in6 netmask6;
2081 	struct in_addr in4;
2082 	struct in6_addr in6;
2083 	sa_family_t af;
2084 	char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
2085 	mcast_rtmsg_t mcast_rtmsg;
2086 	int s;
2087 	int rs;
2088 	int rlen;
2089 	boolean_t got_netmask = B_FALSE;
2090 	char addrstr4[INET_ADDRSTRLEN];
2091 	int res;
2092 
2093 	res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
2094 	if (res != Z_OK) {
2095 		zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
2096 		    nwiftabptr->zone_nwif_address);
2097 		return (-1);
2098 	}
2099 	af = lifr.lifr_addr.ss_family;
2100 	if (af == AF_INET)
2101 		in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
2102 	else
2103 		in6 = ((struct sockaddr_in6 *)(&lifr.lifr_addr))->sin6_addr;
2104 
2105 	if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
2106 		zerror(zlogp, B_TRUE, "could not get socket");
2107 		return (-1);
2108 	}
2109 
2110 	(void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
2111 	    sizeof (lifr.lifr_name));
2112 	if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
2113 		/*
2114 		 * Here, we know that the interface can't be brought up.
2115 		 * A similar warning message was already printed out to
2116 		 * the console by zoneadm(1M) so instead we log the
2117 		 * message to syslog and continue.
2118 		 */
2119 		zerror(&logsys, B_TRUE, "WARNING: skipping network interface "
2120 		    "'%s' which may not be present/plumbed in the "
2121 		    "global zone.", lifr.lifr_name);
2122 		(void) close(s);
2123 		return (Z_OK);
2124 	}
2125 
2126 	if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2127 		zerror(zlogp, B_TRUE,
2128 		    "%s: could not set IP address to %s",
2129 		    lifr.lifr_name, nwiftabptr->zone_nwif_address);
2130 		goto bad;
2131 	}
2132 
2133 	/* Preserve literal IPv4 address for later potential printing. */
2134 	if (af == AF_INET)
2135 		(void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
2136 
2137 	lifr.lifr_zoneid = zone_id;
2138 	if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
2139 		zerror(zlogp, B_TRUE, "%s: could not place network interface "
2140 		    "into zone", lifr.lifr_name);
2141 		goto bad;
2142 	}
2143 
2144 	if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
2145 		got_netmask = B_TRUE;	/* default setting will be correct */
2146 	} else {
2147 		if (af == AF_INET) {
2148 			/*
2149 			 * The IPv4 netmask can be determined either
2150 			 * directly if a prefix length was supplied with
2151 			 * the address or via the netmasks database.  Not
2152 			 * being able to determine it is a common failure,
2153 			 * but it often is not fatal to operation of the
2154 			 * interface.  In that case, a warning will be
2155 			 * printed after the rest of the interface's
2156 			 * parameters have been configured.
2157 			 */
2158 			(void) memset(&netmask4, 0, sizeof (netmask4));
2159 			if (slashp != NULL) {
2160 				if (addr2netmask(slashp + 1, V4_ADDR_LEN,
2161 				    (uchar_t *)&netmask4.sin_addr) != 0) {
2162 					*slashp = '/';
2163 					zerror(zlogp, B_FALSE,
2164 					    "%s: invalid prefix length in %s",
2165 					    lifr.lifr_name,
2166 					    nwiftabptr->zone_nwif_address);
2167 					goto bad;
2168 				}
2169 				got_netmask = B_TRUE;
2170 			} else if (getnetmaskbyaddr(in4,
2171 			    &netmask4.sin_addr) == 0) {
2172 				got_netmask = B_TRUE;
2173 			}
2174 			if (got_netmask) {
2175 				netmask4.sin_family = af;
2176 				(void) memcpy(&lifr.lifr_addr, &netmask4,
2177 				    sizeof (netmask4));
2178 			}
2179 		} else {
2180 			(void) memset(&netmask6, 0, sizeof (netmask6));
2181 			if (addr2netmask(slashp + 1, V6_ADDR_LEN,
2182 			    (uchar_t *)&netmask6.sin6_addr) != 0) {
2183 				*slashp = '/';
2184 				zerror(zlogp, B_FALSE,
2185 				    "%s: invalid prefix length in %s",
2186 				    lifr.lifr_name,
2187 				    nwiftabptr->zone_nwif_address);
2188 				goto bad;
2189 			}
2190 			got_netmask = B_TRUE;
2191 			netmask6.sin6_family = af;
2192 			(void) memcpy(&lifr.lifr_addr, &netmask6,
2193 			    sizeof (netmask6));
2194 		}
2195 		if (got_netmask &&
2196 		    ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
2197 			zerror(zlogp, B_TRUE, "%s: could not set netmask",
2198 			    lifr.lifr_name);
2199 			goto bad;
2200 		}
2201 
2202 		/*
2203 		 * This doesn't set the broadcast address at all. Rather, it
2204 		 * gets, then sets the interface's address, relying on the fact
2205 		 * that resetting the address will reset the broadcast address.
2206 		 */
2207 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2208 			zerror(zlogp, B_TRUE, "%s: could not get address",
2209 			    lifr.lifr_name);
2210 			goto bad;
2211 		}
2212 		if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2213 			zerror(zlogp, B_TRUE,
2214 			    "%s: could not reset broadcast address",
2215 			    lifr.lifr_name);
2216 			goto bad;
2217 		}
2218 	}
2219 
2220 	if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2221 		zerror(zlogp, B_TRUE, "%s: could not get flags",
2222 		    lifr.lifr_name);
2223 		goto bad;
2224 	}
2225 	lifr.lifr_flags |= IFF_UP;
2226 	if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
2227 		int save_errno = errno;
2228 		char *zone_using;
2229 
2230 		/*
2231 		 * If we failed with something other than EADDRNOTAVAIL,
2232 		 * then skip to the end.  Otherwise, look up our address,
2233 		 * then call a function to determine which zone is already
2234 		 * using that address.
2235 		 */
2236 		if (errno != EADDRNOTAVAIL) {
2237 			zerror(zlogp, B_TRUE,
2238 			    "%s: could not bring network interface up",
2239 			    lifr.lifr_name);
2240 			goto bad;
2241 		}
2242 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2243 			zerror(zlogp, B_TRUE, "%s: could not get address",
2244 			    lifr.lifr_name);
2245 			goto bad;
2246 		}
2247 		zone_using = who_is_using(zlogp, &lifr);
2248 		errno = save_errno;
2249 		if (zone_using == NULL)
2250 			zerror(zlogp, B_TRUE,
2251 			    "%s: could not bring network interface up",
2252 			    lifr.lifr_name);
2253 		else
2254 			zerror(zlogp, B_TRUE, "%s: could not bring network "
2255 			    "interface up: address in use by zone '%s'",
2256 			    lifr.lifr_name, zone_using);
2257 		goto bad;
2258 	}
2259 	if ((lifr.lifr_flags & IFF_MULTICAST) && ((af == AF_INET &&
2260 	    mcast_rt_v4_setp != NULL && *mcast_rt_v4_setp == B_FALSE) ||
2261 	    (af == AF_INET6 &&
2262 	    mcast_rt_v6_setp != NULL && *mcast_rt_v6_setp == B_FALSE))) {
2263 		rs = socket(PF_ROUTE, SOCK_RAW, 0);
2264 		if (rs < 0) {
2265 			zerror(zlogp, B_TRUE, "%s: could not create "
2266 			    "routing socket", lifr.lifr_name);
2267 			goto bad;
2268 		}
2269 		(void) shutdown(rs, 0);
2270 		(void) memset((void *)&mcast_rtmsg, 0, sizeof (mcast_rtmsg_t));
2271 		mcast_rtmsg.m_rtm.rtm_msglen =  sizeof (struct rt_msghdr) +
2272 		    3 * (af == AF_INET ? sizeof (struct sockaddr_in) :
2273 		    sizeof (struct sockaddr_in6));
2274 		mcast_rtmsg.m_rtm.rtm_version = RTM_VERSION;
2275 		mcast_rtmsg.m_rtm.rtm_type = RTM_ADD;
2276 		mcast_rtmsg.m_rtm.rtm_flags = RTF_UP;
2277 		mcast_rtmsg.m_rtm.rtm_addrs =
2278 		    RTA_DST | RTA_GATEWAY | RTA_NETMASK;
2279 		mcast_rtmsg.m_rtm.rtm_seq = ++rts_seqno;
2280 		if (af == AF_INET) {
2281 			mcast_rtmsg.m_dst4.sin_family = AF_INET;
2282 			mcast_rtmsg.m_dst4.sin_addr.s_addr =
2283 			    htonl(INADDR_UNSPEC_GROUP);
2284 			mcast_rtmsg.m_gw4.sin_family = AF_INET;
2285 			mcast_rtmsg.m_gw4.sin_addr = in4;
2286 			mcast_rtmsg.m_netmask4.sin_family = AF_INET;
2287 			mcast_rtmsg.m_netmask4.sin_addr.s_addr =
2288 			    htonl(IN_CLASSD_NET);
2289 		} else {
2290 			mcast_rtmsg.m_dst6.sin6_family = AF_INET6;
2291 			mcast_rtmsg.m_dst6.sin6_addr.s6_addr[0] = 0xffU;
2292 			mcast_rtmsg.m_gw6.sin6_family = AF_INET6;
2293 			mcast_rtmsg.m_gw6.sin6_addr = in6;
2294 			mcast_rtmsg.m_netmask6.sin6_family = AF_INET6;
2295 			mcast_rtmsg.m_netmask6.sin6_addr.s6_addr[0] = 0xffU;
2296 		}
2297 		rlen = write(rs, (char *)&mcast_rtmsg,
2298 		    mcast_rtmsg.m_rtm.rtm_msglen);
2299 		/*
2300 		 * The write to the multicast socket will fail if the
2301 		 * interface belongs to a failed IPMP group. This is a
2302 		 * non-fatal error and the zone will continue booting.
2303 		 * While the zone is running, if any interface in the
2304 		 * failed IPMP group recovers, the zone will fallback to
2305 		 * using that interface.
2306 		 */
2307 		if (rlen < mcast_rtmsg.m_rtm.rtm_msglen) {
2308 			if (rlen < 0) {
2309 				zerror(zlogp, B_TRUE, "WARNING: network "
2310 				    "interface '%s' not available as default "
2311 				    "for multicast.", lifr.lifr_name);
2312 			} else {
2313 				zerror(zlogp, B_FALSE, "WARNING: network "
2314 				    "interface '%s' not available as default "
2315 				    "for multicast; routing socket returned "
2316 				    "unexpected %d bytes.",
2317 				    lifr.lifr_name, rlen);
2318 			}
2319 		} else {
2320 
2321 			if (af == AF_INET) {
2322 				*mcast_rt_v4_setp = B_TRUE;
2323 			} else {
2324 				*mcast_rt_v6_setp = B_TRUE;
2325 			}
2326 		}
2327 		(void) close(rs);
2328 	}
2329 
2330 	if (!got_netmask) {
2331 		/*
2332 		 * A common, but often non-fatal problem, is that the system
2333 		 * cannot find the netmask for an interface address. This is
2334 		 * often caused by it being only in /etc/inet/netmasks, but
2335 		 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2336 		 * in that. This doesn't show up at boot because the netmask
2337 		 * is obtained from /etc/inet/netmasks when no network
2338 		 * interfaces are up, but isn't consulted when NIS/NIS+ is
2339 		 * available. We warn the user here that something like this
2340 		 * has happened and we're just running with a default and
2341 		 * possible incorrect netmask.
2342 		 */
2343 		char buffer[INET6_ADDRSTRLEN];
2344 		void  *addr;
2345 
2346 		if (af == AF_INET)
2347 			addr = &((struct sockaddr_in *)
2348 			    (&lifr.lifr_addr))->sin_addr;
2349 		else
2350 			addr = &((struct sockaddr_in6 *)
2351 			    (&lifr.lifr_addr))->sin6_addr;
2352 
2353 		/* Find out what netmask interface is going to be using */
2354 		if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2355 		    inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL)
2356 			goto bad;
2357 		zerror(zlogp, B_FALSE,
2358 		    "WARNING: %s: no matching subnet found in netmasks(4) for "
2359 		    "%s; using default of %s.",
2360 		    lifr.lifr_name, addrstr4, buffer);
2361 	}
2362 
2363 	(void) close(s);
2364 	return (Z_OK);
2365 bad:
2366 	(void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2367 	(void) close(s);
2368 	return (-1);
2369 }
2370 
2371 /*
2372  * Sets up network interfaces based on information from the zone configuration.
2373  * An IPv4 loopback interface is set up "for free", modeling the global system.
2374  * If any of the configuration interfaces were IPv6, then an IPv6 loopback
2375  * address is set up as well.
2376  *
2377  * If anything goes wrong, we log a general error message, attempt to tear down
2378  * whatever we set up, and return an error.
2379  */
2380 static int
2381 configure_shared_network_interfaces(zlog_t *zlogp)
2382 {
2383 	zone_dochandle_t handle;
2384 	struct zone_nwiftab nwiftab, loopback_iftab;
2385 	boolean_t saw_v6 = B_FALSE;
2386 	boolean_t mcast_rt_v4_set = B_FALSE;
2387 	boolean_t mcast_rt_v6_set = B_FALSE;
2388 	zoneid_t zoneid;
2389 
2390 	if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2391 		zerror(zlogp, B_TRUE, "unable to get zoneid");
2392 		return (-1);
2393 	}
2394 
2395 	if ((handle = zonecfg_init_handle()) == NULL) {
2396 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2397 		return (-1);
2398 	}
2399 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2400 		zerror(zlogp, B_FALSE, "invalid configuration");
2401 		zonecfg_fini_handle(handle);
2402 		return (-1);
2403 	}
2404 	if (zonecfg_setnwifent(handle) == Z_OK) {
2405 		for (;;) {
2406 			struct in6_addr in6;
2407 
2408 			if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2409 				break;
2410 			if (configure_one_interface(zlogp, zoneid,
2411 			    &nwiftab, &mcast_rt_v4_set, &mcast_rt_v6_set) !=
2412 			    Z_OK) {
2413 				(void) zonecfg_endnwifent(handle);
2414 				zonecfg_fini_handle(handle);
2415 				return (-1);
2416 			}
2417 			if (inet_pton(AF_INET6, nwiftab.zone_nwif_address,
2418 			    &in6) == 1)
2419 				saw_v6 = B_TRUE;
2420 		}
2421 		(void) zonecfg_endnwifent(handle);
2422 	}
2423 	zonecfg_fini_handle(handle);
2424 	(void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2425 	    sizeof (loopback_iftab.zone_nwif_physical));
2426 	(void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2427 	    sizeof (loopback_iftab.zone_nwif_address));
2428 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab, NULL, NULL)
2429 	    != Z_OK) {
2430 		return (-1);
2431 	}
2432 	if (saw_v6) {
2433 		(void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2434 		    sizeof (loopback_iftab.zone_nwif_address));
2435 		if (configure_one_interface(zlogp, zoneid,
2436 		    &loopback_iftab, NULL, NULL) != Z_OK) {
2437 			return (-1);
2438 		}
2439 	}
2440 	return (0);
2441 }
2442 
2443 static void
2444 show_owner(zlog_t *zlogp, char *dlname)
2445 {
2446 	zoneid_t dl_owner_zid;
2447 	char dl_owner_zname[ZONENAME_MAX];
2448 
2449 	dl_owner_zid = ALL_ZONES;
2450 	if (zone_check_datalink(&dl_owner_zid, dlname) != 0)
2451 		(void) snprintf(dl_owner_zname, ZONENAME_MAX, "<unknown>");
2452 	else if (getzonenamebyid(dl_owner_zid, dl_owner_zname, ZONENAME_MAX)
2453 	    < 0)
2454 		(void) snprintf(dl_owner_zname, ZONENAME_MAX, "<%d>",
2455 		    dl_owner_zid);
2456 
2457 	errno = EPERM;
2458 	zerror(zlogp, B_TRUE, "WARNING: skipping network interface '%s' "
2459 	    "which is used by the non-global zone '%s'.\n",
2460 	    dlname, dl_owner_zname);
2461 }
2462 
2463 static int
2464 add_datalink(zlog_t *zlogp, zoneid_t zoneid, char *dlname)
2465 {
2466 	/* First check if it's in use by global zone. */
2467 	if (zonecfg_ifname_exists(AF_INET, dlname) ||
2468 	    zonecfg_ifname_exists(AF_INET6, dlname)) {
2469 		errno = EPERM;
2470 		zerror(zlogp, B_TRUE, "WARNING: skipping network interface "
2471 		    "'%s' which is used in the global zone.", dlname);
2472 		return (-1);
2473 	}
2474 
2475 	/* Add access control information */
2476 	if (zone_add_datalink(zoneid, dlname) != 0) {
2477 		/* If someone got this link before us, show its name */
2478 		if (errno == EPERM)
2479 			show_owner(zlogp, dlname);
2480 		else
2481 			zerror(zlogp, B_TRUE, "WARNING: unable to add network "
2482 			    "interface '%s'.", dlname);
2483 		return (-1);
2484 	}
2485 
2486 	/* Hold the link for this zone */
2487 	if (dladm_hold_link(dlname, zoneid, B_FALSE) < 0) {
2488 		zerror(zlogp, B_TRUE, "WARNING: unable to hold network "
2489 		    "interface '%s'.", dlname);
2490 		(void) zone_remove_datalink(zoneid, dlname);
2491 		return (-1);
2492 	}
2493 
2494 	return (0);
2495 }
2496 
2497 static int
2498 remove_datalink(zlog_t *zlogp, zoneid_t zoneid, char *dlname)
2499 {
2500 	/*
2501 	 * Remove access control information.
2502 	 * If the errno is ENXIO, the interface is not added yet,
2503 	 * nothing to report then.
2504 	 */
2505 	if (zone_remove_datalink(zoneid, dlname) != 0) {
2506 		if (errno == ENXIO)
2507 			return (0);
2508 		zerror(zlogp, B_TRUE, "unable to remove network interface '%s'",
2509 		    dlname);
2510 		return (-1);
2511 	}
2512 
2513 	if (dladm_rele_link(dlname, 0, B_FALSE) < 0) {
2514 		zerror(zlogp, B_TRUE, "unable to release network "
2515 		    "interface '%s'", dlname);
2516 		return (-1);
2517 	}
2518 	return (0);
2519 }
2520 
2521 /*
2522  * Add the kernel access control information for the interface names.
2523  * If anything goes wrong, we log a general error message, attempt to tear down
2524  * whatever we set up, and return an error.
2525  */
2526 static int
2527 configure_exclusive_network_interfaces(zlog_t *zlogp)
2528 {
2529 	zone_dochandle_t handle;
2530 	struct zone_nwiftab nwiftab;
2531 	zoneid_t zoneid;
2532 	char rootpath[MAXPATHLEN];
2533 	char path[MAXPATHLEN];
2534 	di_prof_t prof = NULL;
2535 	boolean_t added = B_FALSE;
2536 
2537 	if ((zoneid = getzoneidbyname(zone_name)) == -1) {
2538 		zerror(zlogp, B_TRUE, "unable to get zoneid");
2539 		return (-1);
2540 	}
2541 
2542 	if ((handle = zonecfg_init_handle()) == NULL) {
2543 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2544 		return (-1);
2545 	}
2546 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2547 		zerror(zlogp, B_FALSE, "invalid configuration");
2548 		zonecfg_fini_handle(handle);
2549 		return (-1);
2550 	}
2551 
2552 	if (zonecfg_setnwifent(handle) != Z_OK) {
2553 		zonecfg_fini_handle(handle);
2554 		return (0);
2555 	}
2556 
2557 	for (;;) {
2558 		if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2559 			break;
2560 
2561 		if (prof == NULL) {
2562 			if (zone_get_devroot(zone_name, rootpath,
2563 			    sizeof (rootpath)) != Z_OK) {
2564 				(void) zonecfg_endnwifent(handle);
2565 				zonecfg_fini_handle(handle);
2566 				zerror(zlogp, B_TRUE,
2567 				    "unable to determine dev root");
2568 				return (-1);
2569 			}
2570 			(void) snprintf(path, sizeof (path), "%s%s", rootpath,
2571 			    "/dev");
2572 			if (di_prof_init(path, &prof) != 0) {
2573 				(void) zonecfg_endnwifent(handle);
2574 				zonecfg_fini_handle(handle);
2575 				zerror(zlogp, B_TRUE,
2576 				    "failed to initialize profile");
2577 				return (-1);
2578 			}
2579 		}
2580 
2581 		/*
2582 		 * Only create the /dev entry if it's not in use.
2583 		 * Note here the zone still boots when the interfaces
2584 		 * assigned is inaccessible, used by others, etc.
2585 		 */
2586 		if (add_datalink(zlogp, zoneid, nwiftab.zone_nwif_physical)
2587 		    == 0) {
2588 			if (di_prof_add_dev(prof, nwiftab.zone_nwif_physical)
2589 			    != 0) {
2590 				(void) zonecfg_endnwifent(handle);
2591 				zonecfg_fini_handle(handle);
2592 				zerror(zlogp, B_TRUE,
2593 				    "failed to add network device");
2594 				return (-1);
2595 			}
2596 			added = B_TRUE;
2597 		}
2598 	}
2599 	(void) zonecfg_endnwifent(handle);
2600 	zonecfg_fini_handle(handle);
2601 
2602 	if (prof != NULL && added) {
2603 		if (di_prof_commit(prof) != 0) {
2604 			zerror(zlogp, B_TRUE, "failed to commit profile");
2605 			return (-1);
2606 		}
2607 	}
2608 	if (prof != NULL)
2609 		di_prof_fini(prof);
2610 
2611 	return (0);
2612 }
2613 
2614 /*
2615  * Get the list of the data-links from kernel, and try to remove it
2616  */
2617 static int
2618 unconfigure_exclusive_network_interfaces_run(zlog_t *zlogp, zoneid_t zoneid)
2619 {
2620 	char *dlnames, *ptr;
2621 	int dlnum, dlnum_saved, i;
2622 
2623 	dlnum = 0;
2624 	if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
2625 		zerror(zlogp, B_TRUE, "unable to list network interfaces");
2626 		return (-1);
2627 	}
2628 again:
2629 	/* this zone doesn't have any data-links */
2630 	if (dlnum == 0)
2631 		return (0);
2632 
2633 	dlnames = malloc(dlnum * LIFNAMSIZ);
2634 	if (dlnames == NULL) {
2635 		zerror(zlogp, B_TRUE, "memory allocation failed");
2636 		return (-1);
2637 	}
2638 	dlnum_saved = dlnum;
2639 
2640 	if (zone_list_datalink(zoneid, &dlnum, dlnames) != 0) {
2641 		zerror(zlogp, B_TRUE, "unable to list network interfaces");
2642 		free(dlnames);
2643 		return (-1);
2644 	}
2645 	if (dlnum_saved < dlnum) {
2646 		/* list increased, try again */
2647 		free(dlnames);
2648 		goto again;
2649 	}
2650 	ptr = dlnames;
2651 	for (i = 0; i < dlnum; i++) {
2652 		/* Remove access control information */
2653 		if (remove_datalink(zlogp, zoneid, ptr) != 0) {
2654 			free(dlnames);
2655 			return (-1);
2656 		}
2657 		ptr += LIFNAMSIZ;
2658 	}
2659 	free(dlnames);
2660 	return (0);
2661 }
2662 
2663 /*
2664  * Get the list of the data-links from configuration, and try to remove it
2665  */
2666 static int
2667 unconfigure_exclusive_network_interfaces_static(zlog_t *zlogp, zoneid_t zoneid)
2668 {
2669 	zone_dochandle_t handle;
2670 	struct zone_nwiftab nwiftab;
2671 
2672 	if ((handle = zonecfg_init_handle()) == NULL) {
2673 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2674 		return (-1);
2675 	}
2676 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2677 		zerror(zlogp, B_FALSE, "invalid configuration");
2678 		zonecfg_fini_handle(handle);
2679 		return (-1);
2680 	}
2681 	if (zonecfg_setnwifent(handle) != Z_OK) {
2682 		zonecfg_fini_handle(handle);
2683 		return (0);
2684 	}
2685 	for (;;) {
2686 		if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2687 			break;
2688 		/* Remove access control information */
2689 		if (remove_datalink(zlogp, zoneid, nwiftab.zone_nwif_physical)
2690 		    != 0) {
2691 			(void) zonecfg_endnwifent(handle);
2692 			zonecfg_fini_handle(handle);
2693 			return (-1);
2694 		}
2695 	}
2696 	(void) zonecfg_endnwifent(handle);
2697 	zonecfg_fini_handle(handle);
2698 	return (0);
2699 }
2700 
2701 /*
2702  * Remove the access control information from the kernel for the exclusive
2703  * network interfaces.
2704  */
2705 static int
2706 unconfigure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
2707 {
2708 	if (unconfigure_exclusive_network_interfaces_run(zlogp, zoneid) != 0) {
2709 		return (unconfigure_exclusive_network_interfaces_static(zlogp,
2710 		    zoneid));
2711 	}
2712 
2713 	return (0);
2714 }
2715 
2716 static int
2717 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
2718     const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
2719 {
2720 	int fd;
2721 	struct strioctl ioc;
2722 	tcp_ioc_abort_conn_t conn;
2723 	int error;
2724 
2725 	conn.ac_local = *local;
2726 	conn.ac_remote = *remote;
2727 	conn.ac_start = TCPS_SYN_SENT;
2728 	conn.ac_end = TCPS_TIME_WAIT;
2729 	conn.ac_zoneid = zoneid;
2730 
2731 	ioc.ic_cmd = TCP_IOC_ABORT_CONN;
2732 	ioc.ic_timout = -1; /* infinite timeout */
2733 	ioc.ic_len = sizeof (conn);
2734 	ioc.ic_dp = (char *)&conn;
2735 
2736 	if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
2737 		zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
2738 		return (-1);
2739 	}
2740 
2741 	error = ioctl(fd, I_STR, &ioc);
2742 	(void) close(fd);
2743 	if (error == 0 || errno == ENOENT)	/* ENOENT is not an error */
2744 		return (0);
2745 	return (-1);
2746 }
2747 
2748 static int
2749 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
2750 {
2751 	struct sockaddr_storage l, r;
2752 	struct sockaddr_in *local, *remote;
2753 	struct sockaddr_in6 *local6, *remote6;
2754 	int error;
2755 
2756 	/*
2757 	 * Abort IPv4 connections.
2758 	 */
2759 	bzero(&l, sizeof (*local));
2760 	local = (struct sockaddr_in *)&l;
2761 	local->sin_family = AF_INET;
2762 	local->sin_addr.s_addr = INADDR_ANY;
2763 	local->sin_port = 0;
2764 
2765 	bzero(&r, sizeof (*remote));
2766 	remote = (struct sockaddr_in *)&r;
2767 	remote->sin_family = AF_INET;
2768 	remote->sin_addr.s_addr = INADDR_ANY;
2769 	remote->sin_port = 0;
2770 
2771 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2772 		return (error);
2773 
2774 	/*
2775 	 * Abort IPv6 connections.
2776 	 */
2777 	bzero(&l, sizeof (*local6));
2778 	local6 = (struct sockaddr_in6 *)&l;
2779 	local6->sin6_family = AF_INET6;
2780 	local6->sin6_port = 0;
2781 	local6->sin6_addr = in6addr_any;
2782 
2783 	bzero(&r, sizeof (*remote6));
2784 	remote6 = (struct sockaddr_in6 *)&r;
2785 	remote6->sin6_family = AF_INET6;
2786 	remote6->sin6_port = 0;
2787 	remote6->sin6_addr = in6addr_any;
2788 
2789 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2790 		return (error);
2791 	return (0);
2792 }
2793 
2794 static int
2795 get_privset(zlog_t *zlogp, priv_set_t *privs, boolean_t mount_cmd)
2796 {
2797 	int error = -1;
2798 	zone_dochandle_t handle;
2799 	char *privname = NULL;
2800 
2801 	if ((handle = zonecfg_init_handle()) == NULL) {
2802 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2803 		return (-1);
2804 	}
2805 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2806 		zerror(zlogp, B_FALSE, "invalid configuration");
2807 		zonecfg_fini_handle(handle);
2808 		return (-1);
2809 	}
2810 
2811 	if (mount_cmd) {
2812 		zone_iptype_t	iptype;
2813 		const char	*curr_iptype;
2814 
2815 		if (zonecfg_get_iptype(handle, &iptype) != Z_OK) {
2816 			zerror(zlogp, B_TRUE, "unable to determine ip-type");
2817 			zonecfg_fini_handle(handle);
2818 			return (-1);
2819 		}
2820 
2821 		switch (iptype) {
2822 		case ZS_SHARED:
2823 			curr_iptype = "shared";
2824 			break;
2825 		case ZS_EXCLUSIVE:
2826 			curr_iptype = "exclusive";
2827 			break;
2828 		}
2829 
2830 		if (zonecfg_default_privset(privs, curr_iptype) == Z_OK)
2831 			return (0);
2832 		zerror(zlogp, B_FALSE,
2833 		    "failed to determine the zone's default privilege set");
2834 		zonecfg_fini_handle(handle);
2835 		return (-1);
2836 	}
2837 
2838 	switch (zonecfg_get_privset(handle, privs, &privname)) {
2839 	case Z_OK:
2840 		error = 0;
2841 		break;
2842 	case Z_PRIV_PROHIBITED:
2843 		zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
2844 		    "within the zone's privilege set", privname);
2845 		break;
2846 	case Z_PRIV_REQUIRED:
2847 		zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
2848 		    "from the zone's privilege set", privname);
2849 		break;
2850 	case Z_PRIV_UNKNOWN:
2851 		zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
2852 		    "in the zone's privilege set", privname);
2853 		break;
2854 	default:
2855 		zerror(zlogp, B_FALSE, "failed to determine the zone's "
2856 		    "privilege set");
2857 		break;
2858 	}
2859 
2860 	free(privname);
2861 	zonecfg_fini_handle(handle);
2862 	return (error);
2863 }
2864 
2865 static int
2866 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2867 {
2868 	nvlist_t *nvl = NULL;
2869 	char *nvl_packed = NULL;
2870 	size_t nvl_size = 0;
2871 	nvlist_t **nvlv = NULL;
2872 	int rctlcount = 0;
2873 	int error = -1;
2874 	zone_dochandle_t handle;
2875 	struct zone_rctltab rctltab;
2876 	rctlblk_t *rctlblk = NULL;
2877 
2878 	*bufp = NULL;
2879 	*bufsizep = 0;
2880 
2881 	if ((handle = zonecfg_init_handle()) == NULL) {
2882 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2883 		return (-1);
2884 	}
2885 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2886 		zerror(zlogp, B_FALSE, "invalid configuration");
2887 		zonecfg_fini_handle(handle);
2888 		return (-1);
2889 	}
2890 
2891 	rctltab.zone_rctl_valptr = NULL;
2892 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
2893 		zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
2894 		goto out;
2895 	}
2896 
2897 	if (zonecfg_setrctlent(handle) != Z_OK) {
2898 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
2899 		goto out;
2900 	}
2901 
2902 	if ((rctlblk = malloc(rctlblk_size())) == NULL) {
2903 		zerror(zlogp, B_TRUE, "memory allocation failed");
2904 		goto out;
2905 	}
2906 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2907 		struct zone_rctlvaltab *rctlval;
2908 		uint_t i, count;
2909 		const char *name = rctltab.zone_rctl_name;
2910 
2911 		/* zoneadm should have already warned about unknown rctls. */
2912 		if (!zonecfg_is_rctl(name)) {
2913 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2914 			rctltab.zone_rctl_valptr = NULL;
2915 			continue;
2916 		}
2917 		count = 0;
2918 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2919 		    rctlval = rctlval->zone_rctlval_next) {
2920 			count++;
2921 		}
2922 		if (count == 0) {	/* ignore */
2923 			continue;	/* Nothing to free */
2924 		}
2925 		if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
2926 			goto out;
2927 		i = 0;
2928 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2929 		    rctlval = rctlval->zone_rctlval_next, i++) {
2930 			if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
2931 				zerror(zlogp, B_TRUE, "%s failed",
2932 				    "nvlist_alloc");
2933 				goto out;
2934 			}
2935 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2936 			    != Z_OK) {
2937 				zerror(zlogp, B_FALSE, "invalid rctl value: "
2938 				    "(priv=%s,limit=%s,action=%s)",
2939 				    rctlval->zone_rctlval_priv,
2940 				    rctlval->zone_rctlval_limit,
2941 				    rctlval->zone_rctlval_action);
2942 				goto out;
2943 			}
2944 			if (!zonecfg_valid_rctl(name, rctlblk)) {
2945 				zerror(zlogp, B_FALSE,
2946 				    "(priv=%s,limit=%s,action=%s) is not a "
2947 				    "valid value for rctl '%s'",
2948 				    rctlval->zone_rctlval_priv,
2949 				    rctlval->zone_rctlval_limit,
2950 				    rctlval->zone_rctlval_action,
2951 				    name);
2952 				goto out;
2953 			}
2954 			if (nvlist_add_uint64(nvlv[i], "privilege",
2955 			    rctlblk_get_privilege(rctlblk)) != 0) {
2956 				zerror(zlogp, B_FALSE, "%s failed",
2957 				    "nvlist_add_uint64");
2958 				goto out;
2959 			}
2960 			if (nvlist_add_uint64(nvlv[i], "limit",
2961 			    rctlblk_get_value(rctlblk)) != 0) {
2962 				zerror(zlogp, B_FALSE, "%s failed",
2963 				    "nvlist_add_uint64");
2964 				goto out;
2965 			}
2966 			if (nvlist_add_uint64(nvlv[i], "action",
2967 			    (uint_t)rctlblk_get_local_action(rctlblk, NULL))
2968 			    != 0) {
2969 				zerror(zlogp, B_FALSE, "%s failed",
2970 				    "nvlist_add_uint64");
2971 				goto out;
2972 			}
2973 		}
2974 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2975 		rctltab.zone_rctl_valptr = NULL;
2976 		if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
2977 		    != 0) {
2978 			zerror(zlogp, B_FALSE, "%s failed",
2979 			    "nvlist_add_nvlist_array");
2980 			goto out;
2981 		}
2982 		for (i = 0; i < count; i++)
2983 			nvlist_free(nvlv[i]);
2984 		free(nvlv);
2985 		nvlv = NULL;
2986 		rctlcount++;
2987 	}
2988 	(void) zonecfg_endrctlent(handle);
2989 
2990 	if (rctlcount == 0) {
2991 		error = 0;
2992 		goto out;
2993 	}
2994 	if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
2995 	    != 0) {
2996 		zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
2997 		goto out;
2998 	}
2999 
3000 	error = 0;
3001 	*bufp = nvl_packed;
3002 	*bufsizep = nvl_size;
3003 
3004 out:
3005 	free(rctlblk);
3006 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3007 	if (error && nvl_packed != NULL)
3008 		free(nvl_packed);
3009 	if (nvl != NULL)
3010 		nvlist_free(nvl);
3011 	if (nvlv != NULL)
3012 		free(nvlv);
3013 	if (handle != NULL)
3014 		zonecfg_fini_handle(handle);
3015 	return (error);
3016 }
3017 
3018 static int
3019 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3020 {
3021 	zone_dochandle_t handle;
3022 	struct zone_dstab dstab;
3023 	size_t total, offset, len;
3024 	int error = -1;
3025 	char *str;
3026 
3027 	*bufp = NULL;
3028 	*bufsizep = 0;
3029 
3030 	if ((handle = zonecfg_init_handle()) == NULL) {
3031 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3032 		return (-1);
3033 	}
3034 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3035 		zerror(zlogp, B_FALSE, "invalid configuration");
3036 		zonecfg_fini_handle(handle);
3037 		return (-1);
3038 	}
3039 
3040 	if (zonecfg_setdsent(handle) != Z_OK) {
3041 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3042 		goto out;
3043 	}
3044 
3045 	total = 0;
3046 	while (zonecfg_getdsent(handle, &dstab) == Z_OK)
3047 		total += strlen(dstab.zone_dataset_name) + 1;
3048 	(void) zonecfg_enddsent(handle);
3049 
3050 	if (total == 0) {
3051 		error = 0;
3052 		goto out;
3053 	}
3054 
3055 	if ((str = malloc(total)) == NULL) {
3056 		zerror(zlogp, B_TRUE, "memory allocation failed");
3057 		goto out;
3058 	}
3059 
3060 	if (zonecfg_setdsent(handle) != Z_OK) {
3061 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3062 		goto out;
3063 	}
3064 	offset = 0;
3065 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3066 		len = strlen(dstab.zone_dataset_name);
3067 		(void) strlcpy(str + offset, dstab.zone_dataset_name,
3068 		    sizeof (dstab.zone_dataset_name) - offset);
3069 		offset += len;
3070 		if (offset != total - 1)
3071 			str[offset++] = ',';
3072 	}
3073 	(void) zonecfg_enddsent(handle);
3074 
3075 	error = 0;
3076 	*bufp = str;
3077 	*bufsizep = total;
3078 
3079 out:
3080 	if (error != 0 && str != NULL)
3081 		free(str);
3082 	if (handle != NULL)
3083 		zonecfg_fini_handle(handle);
3084 
3085 	return (error);
3086 }
3087 
3088 static int
3089 validate_datasets(zlog_t *zlogp)
3090 {
3091 	zone_dochandle_t handle;
3092 	struct zone_dstab dstab;
3093 	zfs_handle_t *zhp;
3094 	libzfs_handle_t *hdl;
3095 
3096 	if ((handle = zonecfg_init_handle()) == NULL) {
3097 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3098 		return (-1);
3099 	}
3100 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3101 		zerror(zlogp, B_FALSE, "invalid configuration");
3102 		zonecfg_fini_handle(handle);
3103 		return (-1);
3104 	}
3105 
3106 	if (zonecfg_setdsent(handle) != Z_OK) {
3107 		zerror(zlogp, B_FALSE, "invalid configuration");
3108 		zonecfg_fini_handle(handle);
3109 		return (-1);
3110 	}
3111 
3112 	if ((hdl = libzfs_init()) == NULL) {
3113 		zerror(zlogp, B_FALSE, "opening ZFS library");
3114 		zonecfg_fini_handle(handle);
3115 		return (-1);
3116 	}
3117 
3118 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3119 
3120 		if ((zhp = zfs_open(hdl, dstab.zone_dataset_name,
3121 		    ZFS_TYPE_FILESYSTEM)) == NULL) {
3122 			zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
3123 			    dstab.zone_dataset_name);
3124 			zonecfg_fini_handle(handle);
3125 			libzfs_fini(hdl);
3126 			return (-1);
3127 		}
3128 
3129 		/*
3130 		 * Automatically set the 'zoned' property.  We check the value
3131 		 * first because we'll get EPERM if it is already set.
3132 		 */
3133 		if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
3134 		    zfs_prop_set(zhp, zfs_prop_to_name(ZFS_PROP_ZONED),
3135 		    "on") != 0) {
3136 			zerror(zlogp, B_FALSE, "cannot set 'zoned' "
3137 			    "property for ZFS dataset '%s'\n",
3138 			    dstab.zone_dataset_name);
3139 			zonecfg_fini_handle(handle);
3140 			zfs_close(zhp);
3141 			libzfs_fini(hdl);
3142 			return (-1);
3143 		}
3144 
3145 		zfs_close(zhp);
3146 	}
3147 	(void) zonecfg_enddsent(handle);
3148 
3149 	zonecfg_fini_handle(handle);
3150 	libzfs_fini(hdl);
3151 
3152 	return (0);
3153 }
3154 
3155 /*
3156  * Mount lower level home directories into/from current zone
3157  * Share exported directories specified in dfstab for zone
3158  */
3159 static int
3160 tsol_mounts(zlog_t *zlogp, char *zone_name, char *rootpath)
3161 {
3162 	zoneid_t *zids = NULL;
3163 	priv_set_t *zid_privs;
3164 	const priv_impl_info_t *ip = NULL;
3165 	uint_t nzents_saved;
3166 	uint_t nzents;
3167 	int i;
3168 	char readonly[] = "ro";
3169 	struct zone_fstab lower_fstab;
3170 	char *argv[4];
3171 
3172 	if (!is_system_labeled())
3173 		return (0);
3174 
3175 	if (zid_label == NULL) {
3176 		zid_label = m_label_alloc(MAC_LABEL);
3177 		if (zid_label == NULL)
3178 			return (-1);
3179 	}
3180 
3181 	/* Make sure our zone has an /export/home dir */
3182 	(void) make_one_dir(zlogp, rootpath, "/export/home",
3183 	    DEFAULT_DIR_MODE);
3184 
3185 	lower_fstab.zone_fs_raw[0] = '\0';
3186 	(void) strlcpy(lower_fstab.zone_fs_type, MNTTYPE_LOFS,
3187 	    sizeof (lower_fstab.zone_fs_type));
3188 	lower_fstab.zone_fs_options = NULL;
3189 	(void) zonecfg_add_fs_option(&lower_fstab, readonly);
3190 
3191 	/*
3192 	 * Get the list of zones from the kernel
3193 	 */
3194 	if (zone_list(NULL, &nzents) != 0) {
3195 		zerror(zlogp, B_TRUE, "unable to list zones");
3196 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3197 		return (-1);
3198 	}
3199 again:
3200 	if (nzents == 0) {
3201 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3202 		return (-1);
3203 	}
3204 
3205 	zids = malloc(nzents * sizeof (zoneid_t));
3206 	if (zids == NULL) {
3207 		zerror(zlogp, B_TRUE, "memory allocation failed");
3208 		return (-1);
3209 	}
3210 	nzents_saved = nzents;
3211 
3212 	if (zone_list(zids, &nzents) != 0) {
3213 		zerror(zlogp, B_TRUE, "unable to list zones");
3214 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3215 		free(zids);
3216 		return (-1);
3217 	}
3218 	if (nzents != nzents_saved) {
3219 		/* list changed, try again */
3220 		free(zids);
3221 		goto again;
3222 	}
3223 
3224 	ip = getprivimplinfo();
3225 	if ((zid_privs = priv_allocset()) == NULL) {
3226 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3227 		zonecfg_free_fs_option_list(
3228 		    lower_fstab.zone_fs_options);
3229 		free(zids);
3230 		return (-1);
3231 	}
3232 
3233 	for (i = 0; i < nzents; i++) {
3234 		char zid_name[ZONENAME_MAX];
3235 		zone_state_t zid_state;
3236 		char zid_rpath[MAXPATHLEN];
3237 		struct stat stat_buf;
3238 
3239 		if (zids[i] == GLOBAL_ZONEID)
3240 			continue;
3241 
3242 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3243 			continue;
3244 
3245 		/*
3246 		 * Do special setup for the zone we are booting
3247 		 */
3248 		if (strcmp(zid_name, zone_name) == 0) {
3249 			struct zone_fstab autofs_fstab;
3250 			char map_path[MAXPATHLEN];
3251 			int fd;
3252 
3253 			/*
3254 			 * Create auto_home_<zone> map for this zone
3255 			 * in the global zone. The non-global zone entry
3256 			 * will be created by automount when the zone
3257 			 * is booted.
3258 			 */
3259 
3260 			(void) snprintf(autofs_fstab.zone_fs_special,
3261 			    MAXPATHLEN, "auto_home_%s", zid_name);
3262 
3263 			(void) snprintf(autofs_fstab.zone_fs_dir, MAXPATHLEN,
3264 			    "/zone/%s/home", zid_name);
3265 
3266 			(void) snprintf(map_path, sizeof (map_path),
3267 			    "/etc/%s", autofs_fstab.zone_fs_special);
3268 			/*
3269 			 * If the map file doesn't exist create a template
3270 			 */
3271 			if ((fd = open(map_path, O_RDWR | O_CREAT | O_EXCL,
3272 			    S_IRUSR | S_IWUSR | S_IRGRP| S_IROTH)) != -1) {
3273 				int len;
3274 				char map_rec[MAXPATHLEN];
3275 
3276 				len = snprintf(map_rec, sizeof (map_rec),
3277 				    "+%s\n*\t-fstype=lofs\t:%s/export/home/&\n",
3278 				    autofs_fstab.zone_fs_special, rootpath);
3279 				(void) write(fd, map_rec, len);
3280 				(void) close(fd);
3281 			}
3282 
3283 			/*
3284 			 * Mount auto_home_<zone> in the global zone if absent.
3285 			 * If it's already of type autofs, then
3286 			 * don't mount it again.
3287 			 */
3288 			if ((stat(autofs_fstab.zone_fs_dir, &stat_buf) == -1) ||
3289 			    strcmp(stat_buf.st_fstype, MNTTYPE_AUTOFS) != 0) {
3290 				char optstr[] = "indirect,ignore,nobrowse";
3291 
3292 				(void) make_one_dir(zlogp, "",
3293 				    autofs_fstab.zone_fs_dir, DEFAULT_DIR_MODE);
3294 
3295 				/*
3296 				 * Mount will fail if automounter has already
3297 				 * processed the auto_home_<zonename> map
3298 				 */
3299 				(void) domount(zlogp, MNTTYPE_AUTOFS, optstr,
3300 				    autofs_fstab.zone_fs_special,
3301 				    autofs_fstab.zone_fs_dir);
3302 			}
3303 			continue;
3304 		}
3305 
3306 
3307 		if (zone_get_state(zid_name, &zid_state) != Z_OK ||
3308 		    (zid_state != ZONE_STATE_READY &&
3309 		    zid_state != ZONE_STATE_RUNNING))
3310 			/* Skip over zones without mounted filesystems */
3311 			continue;
3312 
3313 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3314 		    sizeof (m_label_t)) < 0)
3315 			/* Skip over zones with unspecified label */
3316 			continue;
3317 
3318 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3319 		    sizeof (zid_rpath)) == -1)
3320 			/* Skip over zones with bad path */
3321 			continue;
3322 
3323 		if (zone_getattr(zids[i], ZONE_ATTR_PRIVSET, zid_privs,
3324 		    sizeof (priv_chunk_t) * ip->priv_setsize) == -1)
3325 			/* Skip over zones with bad privs */
3326 			continue;
3327 
3328 		/*
3329 		 * Reading down is valid according to our label model
3330 		 * but some customers want to disable it because it
3331 		 * allows execute down and other possible attacks.
3332 		 * Therefore, we restrict this feature to zones that
3333 		 * have the NET_MAC_AWARE privilege which is required
3334 		 * for NFS read-down semantics.
3335 		 */
3336 		if ((bldominates(zlabel, zid_label)) &&
3337 		    (priv_ismember(zprivs, PRIV_NET_MAC_AWARE))) {
3338 			/*
3339 			 * Our zone dominates this one.
3340 			 * Create a lofs mount from lower zone's /export/home
3341 			 */
3342 			(void) snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
3343 			    "%s/zone/%s/export/home", rootpath, zid_name);
3344 
3345 			/*
3346 			 * If the target is already an LOFS mount
3347 			 * then don't do it again.
3348 			 */
3349 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3350 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3351 
3352 				if (snprintf(lower_fstab.zone_fs_special,
3353 				    MAXPATHLEN, "%s/export",
3354 				    zid_rpath) > MAXPATHLEN)
3355 					continue;
3356 
3357 				/*
3358 				 * Make sure the lower-level home exists
3359 				 */
3360 				if (make_one_dir(zlogp,
3361 				    lower_fstab.zone_fs_special,
3362 				    "/home", DEFAULT_DIR_MODE) != 0)
3363 					continue;
3364 
3365 				(void) strlcat(lower_fstab.zone_fs_special,
3366 				    "/home", MAXPATHLEN);
3367 
3368 				/*
3369 				 * Mount can fail because the lower-level
3370 				 * zone may have already done a mount up.
3371 				 */
3372 				(void) mount_one(zlogp, &lower_fstab, "");
3373 			}
3374 		} else if ((bldominates(zid_label, zlabel)) &&
3375 		    (priv_ismember(zid_privs, PRIV_NET_MAC_AWARE))) {
3376 			/*
3377 			 * This zone dominates our zone.
3378 			 * Create a lofs mount from our zone's /export/home
3379 			 */
3380 			if (snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
3381 			    "%s/zone/%s/export/home", zid_rpath,
3382 			    zone_name) > MAXPATHLEN)
3383 				continue;
3384 
3385 			/*
3386 			 * If the target is already an LOFS mount
3387 			 * then don't do it again.
3388 			 */
3389 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3390 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3391 
3392 				(void) snprintf(lower_fstab.zone_fs_special,
3393 				    MAXPATHLEN, "%s/export/home", rootpath);
3394 
3395 				/*
3396 				 * Mount can fail because the higher-level
3397 				 * zone may have already done a mount down.
3398 				 */
3399 				(void) mount_one(zlogp, &lower_fstab, "");
3400 			}
3401 		}
3402 	}
3403 	zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3404 	priv_freeset(zid_privs);
3405 	free(zids);
3406 
3407 	/*
3408 	 * Now share any exported directories from this zone.
3409 	 * Each zone can have its own dfstab.
3410 	 */
3411 
3412 	argv[0] = "zoneshare";
3413 	argv[1] = "-z";
3414 	argv[2] = zone_name;
3415 	argv[3] = NULL;
3416 
3417 	(void) forkexec(zlogp, "/usr/lib/zones/zoneshare", argv);
3418 	/* Don't check for errors since they don't affect the zone */
3419 
3420 	return (0);
3421 }
3422 
3423 /*
3424  * Unmount lofs mounts from higher level zones
3425  * Unshare nfs exported directories
3426  */
3427 static void
3428 tsol_unmounts(zlog_t *zlogp, char *zone_name)
3429 {
3430 	zoneid_t *zids = NULL;
3431 	uint_t nzents_saved;
3432 	uint_t nzents;
3433 	int i;
3434 	char *argv[4];
3435 	char path[MAXPATHLEN];
3436 
3437 	if (!is_system_labeled())
3438 		return;
3439 
3440 	/*
3441 	 * Get the list of zones from the kernel
3442 	 */
3443 	if (zone_list(NULL, &nzents) != 0) {
3444 		return;
3445 	}
3446 
3447 	if (zid_label == NULL) {
3448 		zid_label = m_label_alloc(MAC_LABEL);
3449 		if (zid_label == NULL)
3450 			return;
3451 	}
3452 
3453 again:
3454 	if (nzents == 0)
3455 		return;
3456 
3457 	zids = malloc(nzents * sizeof (zoneid_t));
3458 	if (zids == NULL) {
3459 		zerror(zlogp, B_TRUE, "memory allocation failed");
3460 		return;
3461 	}
3462 	nzents_saved = nzents;
3463 
3464 	if (zone_list(zids, &nzents) != 0) {
3465 		free(zids);
3466 		return;
3467 	}
3468 	if (nzents != nzents_saved) {
3469 		/* list changed, try again */
3470 		free(zids);
3471 		goto again;
3472 	}
3473 
3474 	for (i = 0; i < nzents; i++) {
3475 		char zid_name[ZONENAME_MAX];
3476 		zone_state_t zid_state;
3477 		char zid_rpath[MAXPATHLEN];
3478 
3479 		if (zids[i] == GLOBAL_ZONEID)
3480 			continue;
3481 
3482 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3483 			continue;
3484 
3485 		/*
3486 		 * Skip the zone we are halting
3487 		 */
3488 		if (strcmp(zid_name, zone_name) == 0)
3489 			continue;
3490 
3491 		if ((zone_getattr(zids[i], ZONE_ATTR_STATUS, &zid_state,
3492 		    sizeof (zid_state)) < 0) ||
3493 		    (zid_state < ZONE_IS_READY))
3494 			/* Skip over zones without mounted filesystems */
3495 			continue;
3496 
3497 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3498 		    sizeof (m_label_t)) < 0)
3499 			/* Skip over zones with unspecified label */
3500 			continue;
3501 
3502 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3503 		    sizeof (zid_rpath)) == -1)
3504 			/* Skip over zones with bad path */
3505 			continue;
3506 
3507 		if (zlabel != NULL && bldominates(zid_label, zlabel)) {
3508 			/*
3509 			 * This zone dominates our zone.
3510 			 * Unmount the lofs mount of our zone's /export/home
3511 			 */
3512 
3513 			if (snprintf(path, MAXPATHLEN,
3514 			    "%s/zone/%s/export/home", zid_rpath,
3515 			    zone_name) > MAXPATHLEN)
3516 				continue;
3517 
3518 			/* Skip over mount failures */
3519 			(void) umount(path);
3520 		}
3521 	}
3522 	free(zids);
3523 
3524 	/*
3525 	 * Unmount global zone autofs trigger for this zone
3526 	 */
3527 	(void) snprintf(path, MAXPATHLEN, "/zone/%s/home", zone_name);
3528 	/* Skip over mount failures */
3529 	(void) umount(path);
3530 
3531 	/*
3532 	 * Next unshare any exported directories from this zone.
3533 	 */
3534 
3535 	argv[0] = "zoneunshare";
3536 	argv[1] = "-z";
3537 	argv[2] = zone_name;
3538 	argv[3] = NULL;
3539 
3540 	(void) forkexec(zlogp, "/usr/lib/zones/zoneunshare", argv);
3541 	/* Don't check for errors since they don't affect the zone */
3542 
3543 	/*
3544 	 * Finally, deallocate any devices in the zone.
3545 	 */
3546 
3547 	argv[0] = "deallocate";
3548 	argv[1] = "-Isz";
3549 	argv[2] = zone_name;
3550 	argv[3] = NULL;
3551 
3552 	(void) forkexec(zlogp, "/usr/sbin/deallocate", argv);
3553 	/* Don't check for errors since they don't affect the zone */
3554 }
3555 
3556 /*
3557  * Fetch the Trusted Extensions label and multi-level ports (MLPs) for
3558  * this zone.
3559  */
3560 static tsol_zcent_t *
3561 get_zone_label(zlog_t *zlogp, priv_set_t *privs)
3562 {
3563 	FILE *fp;
3564 	tsol_zcent_t *zcent = NULL;
3565 	char line[MAXTNZLEN];
3566 
3567 	if ((fp = fopen(TNZONECFG_PATH, "r")) == NULL) {
3568 		zerror(zlogp, B_TRUE, "%s", TNZONECFG_PATH);
3569 		return (NULL);
3570 	}
3571 
3572 	while (fgets(line, sizeof (line), fp) != NULL) {
3573 		/*
3574 		 * Check for malformed database
3575 		 */
3576 		if (strlen(line) == MAXTNZLEN - 1)
3577 			break;
3578 		if ((zcent = tsol_sgetzcent(line, NULL, NULL)) == NULL)
3579 			continue;
3580 		if (strcmp(zcent->zc_name, zone_name) == 0)
3581 			break;
3582 		tsol_freezcent(zcent);
3583 		zcent = NULL;
3584 	}
3585 	(void) fclose(fp);
3586 
3587 	if (zcent == NULL) {
3588 		zerror(zlogp, B_FALSE, "zone requires a label assignment. "
3589 		    "See tnzonecfg(4)");
3590 	} else {
3591 		if (zlabel == NULL)
3592 			zlabel = m_label_alloc(MAC_LABEL);
3593 		/*
3594 		 * Save this zone's privileges for later read-down processing
3595 		 */
3596 		if ((zprivs = priv_allocset()) == NULL) {
3597 			zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3598 			return (NULL);
3599 		} else {
3600 			priv_copyset(privs, zprivs);
3601 		}
3602 	}
3603 	return (zcent);
3604 }
3605 
3606 /*
3607  * Add the Trusted Extensions multi-level ports for this zone.
3608  */
3609 static void
3610 set_mlps(zlog_t *zlogp, zoneid_t zoneid, tsol_zcent_t *zcent)
3611 {
3612 	tsol_mlp_t *mlp;
3613 	tsol_mlpent_t tsme;
3614 
3615 	if (!is_system_labeled())
3616 		return;
3617 
3618 	tsme.tsme_zoneid = zoneid;
3619 	tsme.tsme_flags = 0;
3620 	for (mlp = zcent->zc_private_mlp; !TSOL_MLP_END(mlp); mlp++) {
3621 		tsme.tsme_mlp = *mlp;
3622 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3623 			zerror(zlogp, B_TRUE, "cannot set zone-specific MLP "
3624 			    "on %d-%d/%d", mlp->mlp_port,
3625 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3626 		}
3627 	}
3628 
3629 	tsme.tsme_flags = TSOL_MEF_SHARED;
3630 	for (mlp = zcent->zc_shared_mlp; !TSOL_MLP_END(mlp); mlp++) {
3631 		tsme.tsme_mlp = *mlp;
3632 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3633 			zerror(zlogp, B_TRUE, "cannot set shared MLP "
3634 			    "on %d-%d/%d", mlp->mlp_port,
3635 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3636 		}
3637 	}
3638 }
3639 
3640 static void
3641 remove_mlps(zlog_t *zlogp, zoneid_t zoneid)
3642 {
3643 	tsol_mlpent_t tsme;
3644 
3645 	if (!is_system_labeled())
3646 		return;
3647 
3648 	(void) memset(&tsme, 0, sizeof (tsme));
3649 	tsme.tsme_zoneid = zoneid;
3650 	if (tnmlp(TNDB_FLUSH, &tsme) != 0)
3651 		zerror(zlogp, B_TRUE, "cannot flush MLPs");
3652 }
3653 
3654 int
3655 prtmount(const char *fs, void *x) {
3656 	zerror((zlog_t *)x, B_FALSE, "  %s", fs);
3657 	return (0);
3658 }
3659 
3660 /*
3661  * Look for zones running on the main system that are using this root (or any
3662  * subdirectory of it).  Return B_TRUE and print an error if a conflicting zone
3663  * is found or if we can't tell.
3664  */
3665 static boolean_t
3666 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
3667 {
3668 	zoneid_t *zids = NULL;
3669 	uint_t nzids = 0;
3670 	boolean_t retv;
3671 	int rlen, zlen;
3672 	char zroot[MAXPATHLEN];
3673 	char zonename[ZONENAME_MAX];
3674 
3675 	for (;;) {
3676 		nzids += 10;
3677 		zids = malloc(nzids * sizeof (*zids));
3678 		if (zids == NULL) {
3679 			zerror(zlogp, B_TRUE, "memory allocation failed");
3680 			return (B_TRUE);
3681 		}
3682 		if (zone_list(zids, &nzids) == 0)
3683 			break;
3684 		free(zids);
3685 	}
3686 	retv = B_FALSE;
3687 	rlen = strlen(rootpath);
3688 	while (nzids > 0) {
3689 		/*
3690 		 * Ignore errors; they just mean that the zone has disappeared
3691 		 * while we were busy.
3692 		 */
3693 		if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
3694 		    sizeof (zroot)) == -1)
3695 			continue;
3696 		zlen = strlen(zroot);
3697 		if (zlen > rlen)
3698 			zlen = rlen;
3699 		if (strncmp(rootpath, zroot, zlen) == 0 &&
3700 		    (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
3701 		    (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
3702 			if (getzonenamebyid(zids[nzids], zonename,
3703 			    sizeof (zonename)) == -1)
3704 				(void) snprintf(zonename, sizeof (zonename),
3705 				    "id %d", (int)zids[nzids]);
3706 			zerror(zlogp, B_FALSE,
3707 			    "zone root %s already in use by zone %s",
3708 			    rootpath, zonename);
3709 			retv = B_TRUE;
3710 			break;
3711 		}
3712 	}
3713 	free(zids);
3714 	return (retv);
3715 }
3716 
3717 /*
3718  * Search for loopback mounts that use this same source node (same device and
3719  * inode).  Return B_TRUE if there is one or if we can't tell.
3720  */
3721 static boolean_t
3722 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
3723 {
3724 	struct stat64 rst, zst;
3725 	struct mnttab *mnp;
3726 
3727 	if (stat64(rootpath, &rst) == -1) {
3728 		zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
3729 		return (B_TRUE);
3730 	}
3731 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
3732 		return (B_TRUE);
3733 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
3734 		if (mnp->mnt_fstype == NULL ||
3735 		    strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
3736 			continue;
3737 		/* We're looking at a loopback mount.  Stat it. */
3738 		if (mnp->mnt_special != NULL &&
3739 		    stat64(mnp->mnt_special, &zst) != -1 &&
3740 		    rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
3741 			zerror(zlogp, B_FALSE,
3742 			    "zone root %s is reachable through %s",
3743 			    rootpath, mnp->mnt_mountp);
3744 			return (B_TRUE);
3745 		}
3746 	}
3747 	return (B_FALSE);
3748 }
3749 
3750 /*
3751  * Set memory cap and pool info for the zone's resource management
3752  * configuration.
3753  */
3754 static int
3755 setup_zone_rm(zlog_t *zlogp, char *zone_name, zoneid_t zoneid)
3756 {
3757 	int res;
3758 	uint64_t tmp;
3759 	struct zone_mcaptab mcap;
3760 	char sched[MAXNAMELEN];
3761 	zone_dochandle_t handle = NULL;
3762 	char pool_err[128];
3763 
3764 	if ((handle = zonecfg_init_handle()) == NULL) {
3765 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3766 		return (Z_BAD_HANDLE);
3767 	}
3768 
3769 	if ((res = zonecfg_get_snapshot_handle(zone_name, handle)) != Z_OK) {
3770 		zerror(zlogp, B_FALSE, "invalid configuration");
3771 		zonecfg_fini_handle(handle);
3772 		return (res);
3773 	}
3774 
3775 	/*
3776 	 * If a memory cap is configured, set the cap in the kernel using
3777 	 * zone_setattr() and make sure the rcapd SMF service is enabled.
3778 	 */
3779 	if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
3780 		uint64_t num;
3781 		char smf_err[128];
3782 
3783 		num = (uint64_t)strtoull(mcap.zone_physmem_cap, NULL, 10);
3784 		if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
3785 			zerror(zlogp, B_TRUE, "could not set zone memory cap");
3786 			zonecfg_fini_handle(handle);
3787 			return (Z_INVAL);
3788 		}
3789 
3790 		if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
3791 			zerror(zlogp, B_FALSE, "enabling system/rcap service "
3792 			    "failed: %s", smf_err);
3793 			zonecfg_fini_handle(handle);
3794 			return (Z_INVAL);
3795 		}
3796 	}
3797 
3798 	/* Get the scheduling class set in the zone configuration. */
3799 	if (zonecfg_get_sched_class(handle, sched, sizeof (sched)) == Z_OK &&
3800 	    strlen(sched) > 0) {
3801 		if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, sched,
3802 		    strlen(sched)) == -1)
3803 			zerror(zlogp, B_TRUE, "WARNING: unable to set the "
3804 			    "default scheduling class");
3805 
3806 	} else if (zonecfg_get_aliased_rctl(handle, ALIAS_SHARES, &tmp)
3807 	    == Z_OK) {
3808 		/*
3809 		 * If the zone has the zone.cpu-shares rctl set then we want to
3810 		 * use the Fair Share Scheduler (FSS) for processes in the
3811 		 * zone.  Check what scheduling class the zone would be running
3812 		 * in by default so we can print a warning and modify the class
3813 		 * if we wouldn't be using FSS.
3814 		 */
3815 		char class_name[PC_CLNMSZ];
3816 
3817 		if (zonecfg_get_dflt_sched_class(handle, class_name,
3818 		    sizeof (class_name)) != Z_OK) {
3819 			zerror(zlogp, B_FALSE, "WARNING: unable to determine "
3820 			    "the zone's scheduling class");
3821 
3822 		} else if (strcmp("FSS", class_name) != 0) {
3823 			zerror(zlogp, B_FALSE, "WARNING: The zone.cpu-shares "
3824 			    "rctl is set but\nFSS is not the default "
3825 			    "scheduling class for\nthis zone.  FSS will be "
3826 			    "used for processes\nin the zone but to get the "
3827 			    "full benefit of FSS,\nit should be the default "
3828 			    "scheduling class.\nSee dispadmin(1M) for more "
3829 			    "details.");
3830 
3831 			if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, "FSS",
3832 			    strlen("FSS")) == -1)
3833 				zerror(zlogp, B_TRUE, "WARNING: unable to set "
3834 				    "zone scheduling class to FSS");
3835 		}
3836 	}
3837 
3838 	/*
3839 	 * The next few blocks of code attempt to set up temporary pools as
3840 	 * well as persistent pools.  In all cases we call the functions
3841 	 * unconditionally.  Within each funtion the code will check if the
3842 	 * zone is actually configured for a temporary pool or persistent pool
3843 	 * and just return if there is nothing to do.
3844 	 *
3845 	 * If we are rebooting we want to attempt to reuse any temporary pool
3846 	 * that was previously set up.  zonecfg_bind_tmp_pool() will do the
3847 	 * right thing in all cases (reuse or create) based on the current
3848 	 * zonecfg.
3849 	 */
3850 	if ((res = zonecfg_bind_tmp_pool(handle, zoneid, pool_err,
3851 	    sizeof (pool_err))) != Z_OK) {
3852 		if (res == Z_POOL || res == Z_POOL_CREATE || res == Z_POOL_BIND)
3853 			zerror(zlogp, B_FALSE, "%s: %s\ndedicated-cpu setting "
3854 			    "cannot be instantiated", zonecfg_strerror(res),
3855 			    pool_err);
3856 		else
3857 			zerror(zlogp, B_FALSE, "could not bind zone to "
3858 			    "temporary pool: %s", zonecfg_strerror(res));
3859 		zonecfg_fini_handle(handle);
3860 		return (Z_POOL_BIND);
3861 	}
3862 
3863 	/*
3864 	 * Check if we need to warn about poold not being enabled.
3865 	 */
3866 	if (zonecfg_warn_poold(handle)) {
3867 		zerror(zlogp, B_FALSE, "WARNING: A range of dedicated-cpus has "
3868 		    "been specified\nbut the dynamic pool service is not "
3869 		    "enabled.\nThe system will not dynamically adjust the\n"
3870 		    "processor allocation within the specified range\n"
3871 		    "until svc:/system/pools/dynamic is enabled.\n"
3872 		    "See poold(1M).");
3873 	}
3874 
3875 	/* The following is a warning, not an error. */
3876 	if ((res = zonecfg_bind_pool(handle, zoneid, pool_err,
3877 	    sizeof (pool_err))) != Z_OK) {
3878 		if (res == Z_POOL_BIND)
3879 			zerror(zlogp, B_FALSE, "WARNING: unable to bind to "
3880 			    "pool '%s'; using default pool.", pool_err);
3881 		else if (res == Z_POOL)
3882 			zerror(zlogp, B_FALSE, "WARNING: %s: %s",
3883 			    zonecfg_strerror(res), pool_err);
3884 		else
3885 			zerror(zlogp, B_FALSE, "WARNING: %s",
3886 			    zonecfg_strerror(res));
3887 	}
3888 
3889 	zonecfg_fini_handle(handle);
3890 	return (Z_OK);
3891 }
3892 
3893 zoneid_t
3894 vplat_create(zlog_t *zlogp, boolean_t mount_cmd)
3895 {
3896 	zoneid_t rval = -1;
3897 	priv_set_t *privs;
3898 	char rootpath[MAXPATHLEN];
3899 	char modname[MAXPATHLEN];
3900 	struct brand_attr attr;
3901 	brand_handle_t bh;
3902 	char *rctlbuf = NULL;
3903 	size_t rctlbufsz = 0;
3904 	char *zfsbuf = NULL;
3905 	size_t zfsbufsz = 0;
3906 	zoneid_t zoneid = -1;
3907 	int xerr;
3908 	char *kzone;
3909 	FILE *fp = NULL;
3910 	tsol_zcent_t *zcent = NULL;
3911 	int match = 0;
3912 	int doi = 0;
3913 	int flags;
3914 	zone_iptype_t iptype;
3915 
3916 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
3917 		zerror(zlogp, B_TRUE, "unable to determine zone root");
3918 		return (-1);
3919 	}
3920 	if (zonecfg_in_alt_root())
3921 		resolve_lofs(zlogp, rootpath, sizeof (rootpath));
3922 
3923 	if (get_iptype(zlogp, &iptype) < 0) {
3924 		zerror(zlogp, B_TRUE, "unable to determine ip-type");
3925 		return (-1);
3926 	}
3927 	switch (iptype) {
3928 	case ZS_SHARED:
3929 		flags = 0;
3930 		break;
3931 	case ZS_EXCLUSIVE:
3932 		flags = ZCF_NET_EXCL;
3933 		break;
3934 	}
3935 
3936 	if ((privs = priv_allocset()) == NULL) {
3937 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3938 		return (-1);
3939 	}
3940 	priv_emptyset(privs);
3941 	if (get_privset(zlogp, privs, mount_cmd) != 0)
3942 		goto error;
3943 
3944 	if (!mount_cmd && get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
3945 		zerror(zlogp, B_FALSE, "Unable to get list of rctls");
3946 		goto error;
3947 	}
3948 
3949 	if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
3950 		zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
3951 		goto error;
3952 	}
3953 
3954 	if (!mount_cmd && is_system_labeled()) {
3955 		zcent = get_zone_label(zlogp, privs);
3956 		if (zcent != NULL) {
3957 			match = zcent->zc_match;
3958 			doi = zcent->zc_doi;
3959 			*zlabel = zcent->zc_label;
3960 		} else {
3961 			goto error;
3962 		}
3963 	}
3964 
3965 	kzone = zone_name;
3966 
3967 	/*
3968 	 * We must do this scan twice.  First, we look for zones running on the
3969 	 * main system that are using this root (or any subdirectory of it).
3970 	 * Next, we reduce to the shortest path and search for loopback mounts
3971 	 * that use this same source node (same device and inode).
3972 	 */
3973 	if (duplicate_zone_root(zlogp, rootpath))
3974 		goto error;
3975 	if (duplicate_reachable_path(zlogp, rootpath))
3976 		goto error;
3977 
3978 	if (mount_cmd) {
3979 		assert(zone_isnative);
3980 		root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
3981 
3982 		/*
3983 		 * Forge up a special root for this zone.  When a zone is
3984 		 * mounted, we can't let the zone have its own root because the
3985 		 * tools that will be used in this "scratch zone" need access
3986 		 * to both the zone's resources and the running machine's
3987 		 * executables.
3988 		 *
3989 		 * Note that the mkdir here also catches read-only filesystems.
3990 		 */
3991 		if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
3992 			zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
3993 			goto error;
3994 		}
3995 		if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
3996 			goto error;
3997 	}
3998 
3999 	if (zonecfg_in_alt_root()) {
4000 		/*
4001 		 * If we are mounting up a zone in an alternate root partition,
4002 		 * then we have some additional work to do before starting the
4003 		 * zone.  First, resolve the root path down so that we're not
4004 		 * fooled by duplicates.  Then forge up an internal name for
4005 		 * the zone.
4006 		 */
4007 		if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
4008 			zerror(zlogp, B_TRUE, "cannot open mapfile");
4009 			goto error;
4010 		}
4011 		if (zonecfg_lock_scratch(fp) != 0) {
4012 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
4013 			goto error;
4014 		}
4015 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4016 		    NULL, 0) == 0) {
4017 			zerror(zlogp, B_FALSE, "scratch zone already running");
4018 			goto error;
4019 		}
4020 		/* This is the preferred name */
4021 		(void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
4022 		    zone_name);
4023 		srandom(getpid());
4024 		while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
4025 		    0) == 0) {
4026 			/* This is just an arbitrary name; note "." usage */
4027 			(void) snprintf(kernzone, sizeof (kernzone),
4028 			    "SUNWlu.%08lX%08lX", random(), random());
4029 		}
4030 		kzone = kernzone;
4031 	}
4032 
4033 	xerr = 0;
4034 	if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
4035 	    rctlbufsz, zfsbuf, zfsbufsz, &xerr, match, doi, zlabel,
4036 	    flags)) == -1) {
4037 		if (xerr == ZE_AREMOUNTS) {
4038 			if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
4039 				zerror(zlogp, B_FALSE,
4040 				    "An unknown file-system is mounted on "
4041 				    "a subdirectory of %s", rootpath);
4042 			} else {
4043 
4044 				zerror(zlogp, B_FALSE,
4045 				    "These file-systems are mounted on "
4046 				    "subdirectories of %s:", rootpath);
4047 				(void) zonecfg_find_mounts(rootpath,
4048 				    prtmount, zlogp);
4049 			}
4050 		} else if (xerr == ZE_CHROOTED) {
4051 			zerror(zlogp, B_FALSE, "%s: "
4052 			    "cannot create a zone from a chrooted "
4053 			    "environment", "zone_create");
4054 		} else {
4055 			zerror(zlogp, B_TRUE, "%s failed", "zone_create");
4056 		}
4057 		goto error;
4058 	}
4059 
4060 	if (zonecfg_in_alt_root() &&
4061 	    zonecfg_add_scratch(fp, zone_name, kernzone,
4062 	    zonecfg_get_root()) == -1) {
4063 		zerror(zlogp, B_TRUE, "cannot add mapfile entry");
4064 		goto error;
4065 	}
4066 
4067 	if ((zone_get_brand(zone_name, attr.ba_brandname,
4068 	    MAXNAMELEN) != Z_OK) ||
4069 	    (bh = brand_open(attr.ba_brandname)) == NULL) {
4070 		zerror(zlogp, B_FALSE, "unable to determine brand name");
4071 		return (-1);
4072 	}
4073 
4074 	/*
4075 	 * If this brand requires any kernel support, now is the time to
4076 	 * get it loaded and initialized.
4077 	 */
4078 	if (brand_get_modname(bh, modname, MAXPATHLEN) < 0) {
4079 		zerror(zlogp, B_FALSE, "unable to determine brand kernel "
4080 		    "module");
4081 		return (-1);
4082 	}
4083 
4084 	if (strlen(modname) > 0) {
4085 		(void) strlcpy(attr.ba_modname, modname, MAXPATHLEN);
4086 		if (zone_setattr(zoneid, ZONE_ATTR_BRAND, &attr,
4087 		    sizeof (attr) != 0)) {
4088 			zerror(zlogp, B_TRUE, "could not set zone brand "
4089 			    "attribute.");
4090 			goto error;
4091 		}
4092 	}
4093 
4094 	/*
4095 	 * The following actions are not performed when merely mounting a zone
4096 	 * for administrative use.
4097 	 */
4098 	if (!mount_cmd) {
4099 		if (setup_zone_rm(zlogp, zone_name, zoneid) != Z_OK) {
4100 			(void) zone_shutdown(zoneid);
4101 			goto error;
4102 		}
4103 
4104 		set_mlps(zlogp, zoneid, zcent);
4105 	}
4106 
4107 	rval = zoneid;
4108 	zoneid = -1;
4109 
4110 error:
4111 	if (zoneid != -1)
4112 		(void) zone_destroy(zoneid);
4113 	if (rctlbuf != NULL)
4114 		free(rctlbuf);
4115 	priv_freeset(privs);
4116 	if (fp != NULL)
4117 		zonecfg_close_scratch(fp);
4118 	lofs_discard_mnttab();
4119 	if (zcent != NULL)
4120 		tsol_freezcent(zcent);
4121 	return (rval);
4122 }
4123 
4124 /*
4125  * Enter the zone and write a /etc/zones/index file there.  This allows
4126  * libzonecfg (and thus zoneadm) to report the UUID and potentially other zone
4127  * details from inside the zone.
4128  */
4129 static void
4130 write_index_file(zoneid_t zoneid)
4131 {
4132 	FILE *zef;
4133 	FILE *zet;
4134 	struct zoneent *zep;
4135 	pid_t child;
4136 	int tmpl_fd;
4137 	ctid_t ct;
4138 	int fd;
4139 	char uuidstr[UUID_PRINTABLE_STRING_LENGTH];
4140 
4141 	/* Locate the zone entry in the global zone's index file */
4142 	if ((zef = setzoneent()) == NULL)
4143 		return;
4144 	while ((zep = getzoneent_private(zef)) != NULL) {
4145 		if (strcmp(zep->zone_name, zone_name) == 0)
4146 			break;
4147 		free(zep);
4148 	}
4149 	endzoneent(zef);
4150 	if (zep == NULL)
4151 		return;
4152 
4153 	if ((tmpl_fd = init_template()) == -1) {
4154 		free(zep);
4155 		return;
4156 	}
4157 
4158 	if ((child = fork()) == -1) {
4159 		(void) ct_tmpl_clear(tmpl_fd);
4160 		(void) close(tmpl_fd);
4161 		free(zep);
4162 		return;
4163 	}
4164 
4165 	/* parent waits for child to finish */
4166 	if (child != 0) {
4167 		free(zep);
4168 		if (contract_latest(&ct) == -1)
4169 			ct = -1;
4170 		(void) ct_tmpl_clear(tmpl_fd);
4171 		(void) close(tmpl_fd);
4172 		(void) waitpid(child, NULL, 0);
4173 		(void) contract_abandon_id(ct);
4174 		return;
4175 	}
4176 
4177 	/* child enters zone and sets up index file */
4178 	(void) ct_tmpl_clear(tmpl_fd);
4179 	if (zone_enter(zoneid) != -1) {
4180 		(void) mkdir(ZONE_CONFIG_ROOT, ZONE_CONFIG_MODE);
4181 		(void) chown(ZONE_CONFIG_ROOT, ZONE_CONFIG_UID,
4182 		    ZONE_CONFIG_GID);
4183 		fd = open(ZONE_INDEX_FILE, O_WRONLY|O_CREAT|O_TRUNC,
4184 		    ZONE_INDEX_MODE);
4185 		if (fd != -1 && (zet = fdopen(fd, "w")) != NULL) {
4186 			(void) fchown(fd, ZONE_INDEX_UID, ZONE_INDEX_GID);
4187 			if (uuid_is_null(zep->zone_uuid))
4188 				uuidstr[0] = '\0';
4189 			else
4190 				uuid_unparse(zep->zone_uuid, uuidstr);
4191 			(void) fprintf(zet, "%s:%s:/:%s\n", zep->zone_name,
4192 			    zone_state_str(zep->zone_state),
4193 			    uuidstr);
4194 			(void) fclose(zet);
4195 		}
4196 	}
4197 	_exit(0);
4198 }
4199 
4200 int
4201 vplat_bringup(zlog_t *zlogp, boolean_t mount_cmd, zoneid_t zoneid)
4202 {
4203 	char zonepath[MAXPATHLEN];
4204 
4205 	if (!mount_cmd && validate_datasets(zlogp) != 0) {
4206 		lofs_discard_mnttab();
4207 		return (-1);
4208 	}
4209 
4210 	/*
4211 	 * Before we try to mount filesystems we need to create the
4212 	 * attribute backing store for /dev
4213 	 */
4214 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
4215 		lofs_discard_mnttab();
4216 		return (-1);
4217 	}
4218 
4219 	resolve_lofs(zlogp, zonepath, sizeof (zonepath));
4220 	if (make_one_dir(zlogp, zonepath, "/dev", DEFAULT_DIR_MODE) != 0) {
4221 		lofs_discard_mnttab();
4222 		return (-1);
4223 	}
4224 
4225 	if (mount_filesystems(zlogp, mount_cmd) != 0) {
4226 		lofs_discard_mnttab();
4227 		return (-1);
4228 	}
4229 
4230 	if (!mount_cmd) {
4231 		zone_iptype_t iptype;
4232 
4233 		if (get_iptype(zlogp, &iptype) < 0) {
4234 			zerror(zlogp, B_TRUE, "unable to determine ip-type");
4235 			lofs_discard_mnttab();
4236 			return (-1);
4237 		}
4238 
4239 		switch (iptype) {
4240 		case ZS_SHARED:
4241 			/* Always do this to make lo0 get configured */
4242 			if (configure_shared_network_interfaces(zlogp) != 0) {
4243 				lofs_discard_mnttab();
4244 				return (-1);
4245 			}
4246 			break;
4247 		case ZS_EXCLUSIVE:
4248 			if (configure_exclusive_network_interfaces(zlogp) !=
4249 			    0) {
4250 				lofs_discard_mnttab();
4251 				return (-1);
4252 			}
4253 			break;
4254 		}
4255 	}
4256 
4257 	write_index_file(zoneid);
4258 
4259 	lofs_discard_mnttab();
4260 	return (0);
4261 }
4262 
4263 static int
4264 lu_root_teardown(zlog_t *zlogp)
4265 {
4266 	char zroot[MAXPATHLEN];
4267 
4268 	assert(zone_isnative);
4269 
4270 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
4271 		zerror(zlogp, B_FALSE, "unable to determine zone root");
4272 		return (-1);
4273 	}
4274 	root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
4275 
4276 	/*
4277 	 * At this point, the processes are gone, the filesystems (save the
4278 	 * root) are unmounted, and the zone is on death row.  But there may
4279 	 * still be creds floating about in the system that reference the
4280 	 * zone_t, and which pin down zone_rootvp causing this call to fail
4281 	 * with EBUSY.  Thus, we try for a little while before just giving up.
4282 	 * (How I wish this were not true, and umount2 just did the right
4283 	 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
4284 	 */
4285 	if (umount2(zroot, MS_FORCE) != 0) {
4286 		if (errno == ENOTSUP && umount2(zroot, 0) == 0)
4287 			goto unmounted;
4288 		if (errno == EBUSY) {
4289 			int tries = 10;
4290 
4291 			while (--tries >= 0) {
4292 				(void) sleep(1);
4293 				if (umount2(zroot, 0) == 0)
4294 					goto unmounted;
4295 				if (errno != EBUSY)
4296 					break;
4297 			}
4298 		}
4299 		zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
4300 		return (-1);
4301 	}
4302 unmounted:
4303 
4304 	/*
4305 	 * Only zones in an alternate root environment have scratch zone
4306 	 * entries.
4307 	 */
4308 	if (zonecfg_in_alt_root()) {
4309 		FILE *fp;
4310 		int retv;
4311 
4312 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4313 			zerror(zlogp, B_TRUE, "cannot open mapfile");
4314 			return (-1);
4315 		}
4316 		retv = -1;
4317 		if (zonecfg_lock_scratch(fp) != 0)
4318 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
4319 		else if (zonecfg_delete_scratch(fp, kernzone) != 0)
4320 			zerror(zlogp, B_TRUE, "cannot delete map entry");
4321 		else
4322 			retv = 0;
4323 		zonecfg_close_scratch(fp);
4324 		return (retv);
4325 	} else {
4326 		return (0);
4327 	}
4328 }
4329 
4330 int
4331 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd, boolean_t rebooting)
4332 {
4333 	char *kzone;
4334 	zoneid_t zoneid;
4335 	int res;
4336 	char pool_err[128];
4337 	char zroot[MAXPATHLEN];
4338 	char cmdbuf[MAXPATHLEN];
4339 	char brand[MAXNAMELEN];
4340 	brand_handle_t bh = NULL;
4341 	ushort_t flags;
4342 
4343 	kzone = zone_name;
4344 	if (zonecfg_in_alt_root()) {
4345 		FILE *fp;
4346 
4347 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4348 			zerror(zlogp, B_TRUE, "unable to open map file");
4349 			goto error;
4350 		}
4351 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4352 		    kernzone, sizeof (kernzone)) != 0) {
4353 			zerror(zlogp, B_FALSE, "unable to find scratch zone");
4354 			zonecfg_close_scratch(fp);
4355 			goto error;
4356 		}
4357 		zonecfg_close_scratch(fp);
4358 		kzone = kernzone;
4359 	}
4360 
4361 	if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
4362 		if (!bringup_failure_recovery)
4363 			zerror(zlogp, B_TRUE, "unable to get zoneid");
4364 		if (unmount_cmd)
4365 			(void) lu_root_teardown(zlogp);
4366 		goto error;
4367 	}
4368 
4369 	if (zone_shutdown(zoneid) != 0) {
4370 		zerror(zlogp, B_TRUE, "unable to shutdown zone");
4371 		goto error;
4372 	}
4373 
4374 	/* Get the path to the root of this zone */
4375 	if (zone_get_zonepath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
4376 		zerror(zlogp, B_FALSE, "unable to determine zone root");
4377 		goto error;
4378 	}
4379 
4380 	/* Get a handle to the brand info for this zone */
4381 	if ((zone_get_brand(zone_name, brand, sizeof (brand)) != Z_OK) ||
4382 	    (bh = brand_open(brand)) == NULL) {
4383 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
4384 		return (-1);
4385 	}
4386 	/*
4387 	 * If there is a brand 'halt' callback, execute it now to give the
4388 	 * brand a chance to cleanup any custom configuration.
4389 	 */
4390 	(void) strcpy(cmdbuf, EXEC_PREFIX);
4391 	if (brand_get_halt(bh, zone_name, zroot, cmdbuf + EXEC_LEN,
4392 	    sizeof (cmdbuf) - EXEC_LEN, 0, NULL) < 0) {
4393 		brand_close(bh);
4394 		zerror(zlogp, B_FALSE, "unable to determine branded zone's "
4395 		    "halt callback.");
4396 		goto error;
4397 	}
4398 	brand_close(bh);
4399 
4400 	if ((strlen(cmdbuf) > EXEC_LEN) &&
4401 	    (do_subproc(zlogp, cmdbuf) != Z_OK)) {
4402 		zerror(zlogp, B_FALSE, "%s failed", cmdbuf);
4403 		goto error;
4404 	}
4405 
4406 	if (!unmount_cmd) {
4407 		zone_iptype_t iptype;
4408 
4409 		if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
4410 		    sizeof (flags)) < 0) {
4411 			if (get_iptype(zlogp, &iptype) < 0) {
4412 				zerror(zlogp, B_TRUE, "unable to determine "
4413 				    "ip-type");
4414 				goto error;
4415 			}
4416 		} else {
4417 			if (flags & ZF_NET_EXCL)
4418 				iptype = ZS_EXCLUSIVE;
4419 			else
4420 				iptype = ZS_SHARED;
4421 		}
4422 
4423 		switch (iptype) {
4424 		case ZS_SHARED:
4425 			if (unconfigure_shared_network_interfaces(zlogp,
4426 			    zoneid) != 0) {
4427 				zerror(zlogp, B_FALSE, "unable to unconfigure "
4428 				    "network interfaces in zone");
4429 				goto error;
4430 			}
4431 			break;
4432 		case ZS_EXCLUSIVE:
4433 			if (unconfigure_exclusive_network_interfaces(zlogp,
4434 			    zoneid) != 0) {
4435 				zerror(zlogp, B_FALSE, "unable to unconfigure "
4436 				    "network interfaces in zone");
4437 				goto error;
4438 			}
4439 			break;
4440 		}
4441 	}
4442 
4443 	if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
4444 		zerror(zlogp, B_TRUE, "unable to abort TCP connections");
4445 		goto error;
4446 	}
4447 
4448 	/* destroy zconsole before umount /dev */
4449 	if (!unmount_cmd)
4450 		destroy_console_slave();
4451 
4452 	if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
4453 		zerror(zlogp, B_FALSE,
4454 		    "unable to unmount file systems in zone");
4455 		goto error;
4456 	}
4457 
4458 	/*
4459 	 * If we are rebooting then we normally don't want to destroy an
4460 	 * existing temporary pool at this point so that we can just reuse it
4461 	 * when the zone boots back up.  However, it is also possible we were
4462 	 * running with a temporary pool and the zone configuration has been
4463 	 * modified to no longer use a temporary pool.  In that case we need
4464 	 * to destroy the temporary pool now.  This case looks like the case
4465 	 * where we never had a temporary pool configured but
4466 	 * zonecfg_destroy_tmp_pool will do the right thing either way.
4467 	 */
4468 	if (!unmount_cmd) {
4469 		boolean_t destroy_tmp_pool = B_TRUE;
4470 
4471 		if (rebooting) {
4472 			struct zone_psettab pset_tab;
4473 			zone_dochandle_t handle;
4474 
4475 			if ((handle = zonecfg_init_handle()) != NULL &&
4476 			    zonecfg_get_handle(zone_name, handle) == Z_OK &&
4477 			    zonecfg_lookup_pset(handle, &pset_tab) == Z_OK)
4478 				destroy_tmp_pool = B_FALSE;
4479 		}
4480 
4481 		if (destroy_tmp_pool) {
4482 			if ((res = zonecfg_destroy_tmp_pool(zone_name, pool_err,
4483 			    sizeof (pool_err))) != Z_OK) {
4484 				if (res == Z_POOL)
4485 					zerror(zlogp, B_FALSE, pool_err);
4486 			}
4487 		}
4488 	}
4489 
4490 	remove_mlps(zlogp, zoneid);
4491 
4492 	if (zone_destroy(zoneid) != 0) {
4493 		zerror(zlogp, B_TRUE, "unable to destroy zone");
4494 		goto error;
4495 	}
4496 
4497 	/*
4498 	 * Special teardown for alternate boot environments: remove the tmpfs
4499 	 * root for the zone and then remove it from the map file.
4500 	 */
4501 	if (unmount_cmd && lu_root_teardown(zlogp) != 0)
4502 		goto error;
4503 
4504 	lofs_discard_mnttab();
4505 	return (0);
4506 
4507 error:
4508 	lofs_discard_mnttab();
4509 	return (-1);
4510 }
4511