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