xref: /titanic_51/usr/src/cmd/zoneadmd/vplat.c (revision dfa03ef6809f806ad32c097e1f909a56bcaa247e)
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 sockaddr_storage laddr;
2215 	struct in_addr in4;
2216 	sa_family_t af;
2217 	char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
2218 	int s;
2219 	boolean_t got_netmask = B_FALSE;
2220 	boolean_t is_loopback = B_FALSE;
2221 	char addrstr4[INET_ADDRSTRLEN];
2222 	int res;
2223 
2224 	res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
2225 	if (res != Z_OK) {
2226 		zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
2227 		    nwiftabptr->zone_nwif_address);
2228 		return (-1);
2229 	}
2230 	af = lifr.lifr_addr.ss_family;
2231 	if (af == AF_INET)
2232 		in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
2233 	if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
2234 		zerror(zlogp, B_TRUE, "could not get socket");
2235 		return (-1);
2236 	}
2237 
2238 	/*
2239 	 * This is a similar kind of "hack" like in addif() to get around
2240 	 * the problem of SIOCLIFADDIF.  The problem is that this ioctl
2241 	 * does not include the netmask when adding a logical interface.
2242 	 * To get around this problem, we first add the logical interface
2243 	 * with a 0 address.  After that, we set the netmask if provided.
2244 	 * Finally we set the interface address.
2245 	 */
2246 	laddr = lifr.lifr_addr;
2247 	(void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
2248 	    sizeof (lifr.lifr_name));
2249 	(void) memset(&lifr.lifr_addr, 0, sizeof (lifr.lifr_addr));
2250 
2251 	if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
2252 		/*
2253 		 * Here, we know that the interface can't be brought up.
2254 		 * A similar warning message was already printed out to
2255 		 * the console by zoneadm(1M) so instead we log the
2256 		 * message to syslog and continue.
2257 		 */
2258 		zerror(&logsys, B_TRUE, "WARNING: skipping network interface "
2259 		    "'%s' which may not be present/plumbed in the "
2260 		    "global zone.", lifr.lifr_name);
2261 		(void) close(s);
2262 		return (Z_OK);
2263 	}
2264 
2265 	/* Preserve literal IPv4 address for later potential printing. */
2266 	if (af == AF_INET)
2267 		(void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
2268 
2269 	lifr.lifr_zoneid = zone_id;
2270 	if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
2271 		zerror(zlogp, B_TRUE, "%s: could not place network interface "
2272 		    "into zone", lifr.lifr_name);
2273 		goto bad;
2274 	}
2275 
2276 	/*
2277 	 * Loopback interface will use the default netmask assigned, if no
2278 	 * netmask is found.
2279 	 */
2280 	if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
2281 		is_loopback = B_TRUE;
2282 	}
2283 	if (af == AF_INET) {
2284 		/*
2285 		 * The IPv4 netmask can be determined either
2286 		 * directly if a prefix length was supplied with
2287 		 * the address or via the netmasks database.  Not
2288 		 * being able to determine it is a common failure,
2289 		 * but it often is not fatal to operation of the
2290 		 * interface.  In that case, a warning will be
2291 		 * printed after the rest of the interface's
2292 		 * parameters have been configured.
2293 		 */
2294 		(void) memset(&netmask4, 0, sizeof (netmask4));
2295 		if (slashp != NULL) {
2296 			if (addr2netmask(slashp + 1, V4_ADDR_LEN,
2297 			    (uchar_t *)&netmask4.sin_addr) != 0) {
2298 				*slashp = '/';
2299 				zerror(zlogp, B_FALSE,
2300 				    "%s: invalid prefix length in %s",
2301 				    lifr.lifr_name,
2302 				    nwiftabptr->zone_nwif_address);
2303 				goto bad;
2304 			}
2305 			got_netmask = B_TRUE;
2306 		} else if (getnetmaskbyaddr(in4,
2307 		    &netmask4.sin_addr) == 0) {
2308 			got_netmask = B_TRUE;
2309 		}
2310 		if (got_netmask) {
2311 			netmask4.sin_family = af;
2312 			(void) memcpy(&lifr.lifr_addr, &netmask4,
2313 			    sizeof (netmask4));
2314 		}
2315 	} else {
2316 		(void) memset(&netmask6, 0, sizeof (netmask6));
2317 		if (addr2netmask(slashp + 1, V6_ADDR_LEN,
2318 		    (uchar_t *)&netmask6.sin6_addr) != 0) {
2319 			*slashp = '/';
2320 			zerror(zlogp, B_FALSE,
2321 			    "%s: invalid prefix length in %s",
2322 			    lifr.lifr_name,
2323 			    nwiftabptr->zone_nwif_address);
2324 			goto bad;
2325 		}
2326 		got_netmask = B_TRUE;
2327 		netmask6.sin6_family = af;
2328 		(void) memcpy(&lifr.lifr_addr, &netmask6,
2329 		    sizeof (netmask6));
2330 	}
2331 	if (got_netmask &&
2332 	    ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
2333 		zerror(zlogp, B_TRUE, "%s: could not set netmask",
2334 		    lifr.lifr_name);
2335 		goto bad;
2336 	}
2337 
2338 	/* Set the interface address */
2339 	lifr.lifr_addr = laddr;
2340 	if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2341 		zerror(zlogp, B_TRUE,
2342 		    "%s: could not set IP address to %s",
2343 		    lifr.lifr_name, nwiftabptr->zone_nwif_address);
2344 		goto bad;
2345 	}
2346 
2347 	if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2348 		zerror(zlogp, B_TRUE, "%s: could not get flags",
2349 		    lifr.lifr_name);
2350 		goto bad;
2351 	}
2352 	lifr.lifr_flags |= IFF_UP;
2353 	if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
2354 		int save_errno = errno;
2355 		char *zone_using;
2356 
2357 		/*
2358 		 * If we failed with something other than EADDRNOTAVAIL,
2359 		 * then skip to the end.  Otherwise, look up our address,
2360 		 * then call a function to determine which zone is already
2361 		 * using that address.
2362 		 */
2363 		if (errno != EADDRNOTAVAIL) {
2364 			zerror(zlogp, B_TRUE,
2365 			    "%s: could not bring network interface up",
2366 			    lifr.lifr_name);
2367 			goto bad;
2368 		}
2369 		if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2370 			zerror(zlogp, B_TRUE, "%s: could not get address",
2371 			    lifr.lifr_name);
2372 			goto bad;
2373 		}
2374 		zone_using = who_is_using(zlogp, &lifr);
2375 		errno = save_errno;
2376 		if (zone_using == NULL)
2377 			zerror(zlogp, B_TRUE,
2378 			    "%s: could not bring network interface up",
2379 			    lifr.lifr_name);
2380 		else
2381 			zerror(zlogp, B_TRUE, "%s: could not bring network "
2382 			    "interface up: address in use by zone '%s'",
2383 			    lifr.lifr_name, zone_using);
2384 		goto bad;
2385 	}
2386 
2387 	if (!got_netmask && !is_loopback) {
2388 		/*
2389 		 * A common, but often non-fatal problem, is that the system
2390 		 * cannot find the netmask for an interface address. This is
2391 		 * often caused by it being only in /etc/inet/netmasks, but
2392 		 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2393 		 * in that. This doesn't show up at boot because the netmask
2394 		 * is obtained from /etc/inet/netmasks when no network
2395 		 * interfaces are up, but isn't consulted when NIS/NIS+ is
2396 		 * available. We warn the user here that something like this
2397 		 * has happened and we're just running with a default and
2398 		 * possible incorrect netmask.
2399 		 */
2400 		char buffer[INET6_ADDRSTRLEN];
2401 		void  *addr;
2402 		const char *nomatch = "no matching subnet found in netmasks(4)";
2403 
2404 		if (af == AF_INET)
2405 			addr = &((struct sockaddr_in *)
2406 			    (&lifr.lifr_addr))->sin_addr;
2407 		else
2408 			addr = &((struct sockaddr_in6 *)
2409 			    (&lifr.lifr_addr))->sin6_addr;
2410 
2411 		/*
2412 		 * Find out what netmask the interface is going to be using.
2413 		 * If we just brought up an IPMP data address on an underlying
2414 		 * interface above, the address will have already migrated, so
2415 		 * the SIOCGLIFNETMASK won't be able to find it (but we need
2416 		 * to bring the address up to get the actual netmask).  Just
2417 		 * omit printing the actual netmask in this corner-case.
2418 		 */
2419 		if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2420 		    inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL) {
2421 			zerror(zlogp, B_FALSE, "WARNING: %s; using default.",
2422 			    nomatch);
2423 		} else {
2424 			zerror(zlogp, B_FALSE,
2425 			    "WARNING: %s: %s: %s; using default of %s.",
2426 			    lifr.lifr_name, nomatch, addrstr4, buffer);
2427 		}
2428 	}
2429 
2430 	/*
2431 	 * If a default router was specified for this interface
2432 	 * set the route now. Ignore if already set.
2433 	 */
2434 	if (strlen(nwiftabptr->zone_nwif_defrouter) > 0) {
2435 		int status;
2436 		char *argv[7];
2437 
2438 		argv[0] = "route";
2439 		argv[1] = "add";
2440 		argv[2] = "-ifp";
2441 		argv[3] = nwiftabptr->zone_nwif_physical;
2442 		argv[4] = "default";
2443 		argv[5] = nwiftabptr->zone_nwif_defrouter;
2444 		argv[6] = NULL;
2445 
2446 		status = forkexec(zlogp, "/usr/sbin/route", argv);
2447 		if (status != 0 && status != EEXIST)
2448 			zerror(zlogp, B_FALSE, "Unable to set route for "
2449 			    "interface %s to %s\n",
2450 			    nwiftabptr->zone_nwif_physical,
2451 			    nwiftabptr->zone_nwif_defrouter);
2452 	}
2453 
2454 	(void) close(s);
2455 	return (Z_OK);
2456 bad:
2457 	(void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2458 	(void) close(s);
2459 	return (-1);
2460 }
2461 
2462 /*
2463  * Sets up network interfaces based on information from the zone configuration.
2464  * IPv4 and IPv6 loopback interfaces are set up "for free", modeling the global
2465  * system.
2466  *
2467  * If anything goes wrong, we log a general error message, attempt to tear down
2468  * whatever we set up, and return an error.
2469  */
2470 static int
2471 configure_shared_network_interfaces(zlog_t *zlogp)
2472 {
2473 	zone_dochandle_t handle;
2474 	struct zone_nwiftab nwiftab, loopback_iftab;
2475 	zoneid_t zoneid;
2476 
2477 	if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2478 		zerror(zlogp, B_TRUE, "unable to get zoneid");
2479 		return (-1);
2480 	}
2481 
2482 	if ((handle = zonecfg_init_handle()) == NULL) {
2483 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2484 		return (-1);
2485 	}
2486 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2487 		zerror(zlogp, B_FALSE, "invalid configuration");
2488 		zonecfg_fini_handle(handle);
2489 		return (-1);
2490 	}
2491 	if (zonecfg_setnwifent(handle) == Z_OK) {
2492 		for (;;) {
2493 			if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2494 				break;
2495 			if (configure_one_interface(zlogp, zoneid, &nwiftab) !=
2496 			    Z_OK) {
2497 				(void) zonecfg_endnwifent(handle);
2498 				zonecfg_fini_handle(handle);
2499 				return (-1);
2500 			}
2501 		}
2502 		(void) zonecfg_endnwifent(handle);
2503 	}
2504 	zonecfg_fini_handle(handle);
2505 	if (is_system_labeled()) {
2506 		/*
2507 		 * Labeled zones share the loopback interface
2508 		 * so it is not plumbed for shared stack instances.
2509 		 */
2510 		return (0);
2511 	}
2512 	(void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2513 	    sizeof (loopback_iftab.zone_nwif_physical));
2514 	(void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2515 	    sizeof (loopback_iftab.zone_nwif_address));
2516 	loopback_iftab.zone_nwif_defrouter[0] = '\0';
2517 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2518 		return (-1);
2519 
2520 	/* Always plumb up the IPv6 loopback interface. */
2521 	(void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2522 	    sizeof (loopback_iftab.zone_nwif_address));
2523 	if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2524 		return (-1);
2525 	return (0);
2526 }
2527 
2528 static void
2529 zdlerror(zlog_t *zlogp, dladm_status_t err, const char *dlname, const char *str)
2530 {
2531 	char errmsg[DLADM_STRSIZE];
2532 
2533 	(void) dladm_status2str(err, errmsg);
2534 	zerror(zlogp, B_FALSE, "%s '%s': %s", str, dlname, errmsg);
2535 }
2536 
2537 static int
2538 add_datalink(zlog_t *zlogp, char *zone_name, char *dlname)
2539 {
2540 	dladm_status_t err;
2541 
2542 	/* First check if it's in use by global zone. */
2543 	if (zonecfg_ifname_exists(AF_INET, dlname) ||
2544 	    zonecfg_ifname_exists(AF_INET6, dlname)) {
2545 		zerror(zlogp, B_FALSE, "WARNING: skipping network interface "
2546 		    "'%s' which is used in the global zone", dlname);
2547 		return (-1);
2548 	}
2549 
2550 	/* Set zoneid of this link. */
2551 	err = dladm_setzid(dld_handle, dlname, zone_name);
2552 	if (err != DLADM_STATUS_OK) {
2553 		zdlerror(zlogp, err, dlname,
2554 		    "WARNING: unable to add network interface");
2555 		return (-1);
2556 	}
2557 
2558 	return (0);
2559 }
2560 
2561 static int
2562 remove_datalink(zlog_t *zlogp, char *dlname)
2563 {
2564 	dladm_status_t err;
2565 
2566 	err = dladm_setzid(dld_handle, dlname, GLOBAL_ZONENAME);
2567 	if (err != DLADM_STATUS_OK) {
2568 		zdlerror(zlogp, err, dlname,
2569 		    "unable to release network interface");
2570 		return (-1);
2571 	}
2572 	return (0);
2573 }
2574 
2575 /*
2576  * Add the kernel access control information for the interface names.
2577  * If anything goes wrong, we log a general error message, attempt to tear down
2578  * whatever we set up, and return an error.
2579  */
2580 static int
2581 configure_exclusive_network_interfaces(zlog_t *zlogp)
2582 {
2583 	zone_dochandle_t handle;
2584 	struct zone_nwiftab nwiftab;
2585 	char rootpath[MAXPATHLEN];
2586 	char path[MAXPATHLEN];
2587 	di_prof_t prof = NULL;
2588 	boolean_t added = B_FALSE;
2589 
2590 	if ((handle = zonecfg_init_handle()) == NULL) {
2591 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2592 		return (-1);
2593 	}
2594 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2595 		zerror(zlogp, B_FALSE, "invalid configuration");
2596 		zonecfg_fini_handle(handle);
2597 		return (-1);
2598 	}
2599 
2600 	if (zonecfg_setnwifent(handle) != Z_OK) {
2601 		zonecfg_fini_handle(handle);
2602 		return (0);
2603 	}
2604 
2605 	for (;;) {
2606 		if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2607 			break;
2608 
2609 		if (prof == NULL) {
2610 			if (zone_get_devroot(zone_name, rootpath,
2611 			    sizeof (rootpath)) != Z_OK) {
2612 				(void) zonecfg_endnwifent(handle);
2613 				zonecfg_fini_handle(handle);
2614 				zerror(zlogp, B_TRUE,
2615 				    "unable to determine dev root");
2616 				return (-1);
2617 			}
2618 			(void) snprintf(path, sizeof (path), "%s%s", rootpath,
2619 			    "/dev");
2620 			if (di_prof_init(path, &prof) != 0) {
2621 				(void) zonecfg_endnwifent(handle);
2622 				zonecfg_fini_handle(handle);
2623 				zerror(zlogp, B_TRUE,
2624 				    "failed to initialize profile");
2625 				return (-1);
2626 			}
2627 		}
2628 
2629 		/*
2630 		 * Create the /dev entry for backward compatibility.
2631 		 * Only create the /dev entry if it's not in use.
2632 		 * Note that the zone still boots when the assigned
2633 		 * interface is inaccessible, used by others, etc.
2634 		 * Also, when vanity naming is used, some interface do
2635 		 * do not have corresponding /dev node names (for example,
2636 		 * vanity named aggregations).  The /dev entry is not
2637 		 * created in that case.  The /dev/net entry is always
2638 		 * accessible.
2639 		 */
2640 		if (add_datalink(zlogp, zone_name, nwiftab.zone_nwif_physical)
2641 		    == 0) {
2642 			added = B_TRUE;
2643 		} else {
2644 			(void) zonecfg_endnwifent(handle);
2645 			zonecfg_fini_handle(handle);
2646 			zerror(zlogp, B_TRUE, "failed to add network device");
2647 			return (-1);
2648 		}
2649 	}
2650 	(void) zonecfg_endnwifent(handle);
2651 	zonecfg_fini_handle(handle);
2652 
2653 	if (prof != NULL && added) {
2654 		if (di_prof_commit(prof) != 0) {
2655 			zerror(zlogp, B_TRUE, "failed to commit profile");
2656 			return (-1);
2657 		}
2658 	}
2659 	if (prof != NULL)
2660 		di_prof_fini(prof);
2661 
2662 	return (0);
2663 }
2664 
2665 /*
2666  * Get the list of the data-links from kernel, and try to remove it
2667  */
2668 static int
2669 unconfigure_exclusive_network_interfaces_run(zlog_t *zlogp, zoneid_t zoneid)
2670 {
2671 	char *dlnames, *ptr;
2672 	int dlnum, dlnum_saved, i;
2673 
2674 	dlnum = 0;
2675 	if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
2676 		zerror(zlogp, B_TRUE, "unable to list network interfaces");
2677 		return (-1);
2678 	}
2679 again:
2680 	/* this zone doesn't have any data-links */
2681 	if (dlnum == 0)
2682 		return (0);
2683 
2684 	dlnames = malloc(dlnum * LIFNAMSIZ);
2685 	if (dlnames == NULL) {
2686 		zerror(zlogp, B_TRUE, "memory allocation failed");
2687 		return (-1);
2688 	}
2689 	dlnum_saved = dlnum;
2690 
2691 	if (zone_list_datalink(zoneid, &dlnum, dlnames) != 0) {
2692 		zerror(zlogp, B_TRUE, "unable to list network interfaces");
2693 		free(dlnames);
2694 		return (-1);
2695 	}
2696 	if (dlnum_saved < dlnum) {
2697 		/* list increased, try again */
2698 		free(dlnames);
2699 		goto again;
2700 	}
2701 	ptr = dlnames;
2702 	for (i = 0; i < dlnum; i++) {
2703 		/* Remove access control information */
2704 		if (remove_datalink(zlogp, ptr) != 0) {
2705 			free(dlnames);
2706 			return (-1);
2707 		}
2708 		ptr += LIFNAMSIZ;
2709 	}
2710 	free(dlnames);
2711 	return (0);
2712 }
2713 
2714 /*
2715  * Get the list of the data-links from configuration, and try to remove it
2716  */
2717 static int
2718 unconfigure_exclusive_network_interfaces_static(zlog_t *zlogp)
2719 {
2720 	zone_dochandle_t handle;
2721 	struct zone_nwiftab nwiftab;
2722 
2723 	if ((handle = zonecfg_init_handle()) == NULL) {
2724 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2725 		return (-1);
2726 	}
2727 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2728 		zerror(zlogp, B_FALSE, "invalid configuration");
2729 		zonecfg_fini_handle(handle);
2730 		return (-1);
2731 	}
2732 	if (zonecfg_setnwifent(handle) != Z_OK) {
2733 		zonecfg_fini_handle(handle);
2734 		return (0);
2735 	}
2736 	for (;;) {
2737 		if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2738 			break;
2739 		/* Remove access control information */
2740 		if (remove_datalink(zlogp, nwiftab.zone_nwif_physical)
2741 		    != 0) {
2742 			(void) zonecfg_endnwifent(handle);
2743 			zonecfg_fini_handle(handle);
2744 			return (-1);
2745 		}
2746 	}
2747 	(void) zonecfg_endnwifent(handle);
2748 	zonecfg_fini_handle(handle);
2749 	return (0);
2750 }
2751 
2752 /*
2753  * Remove the access control information from the kernel for the exclusive
2754  * network interfaces.
2755  */
2756 static int
2757 unconfigure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
2758 {
2759 	if (unconfigure_exclusive_network_interfaces_run(zlogp, zoneid) != 0) {
2760 		return (unconfigure_exclusive_network_interfaces_static(zlogp));
2761 	}
2762 
2763 	return (0);
2764 }
2765 
2766 static int
2767 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
2768     const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
2769 {
2770 	int fd;
2771 	struct strioctl ioc;
2772 	tcp_ioc_abort_conn_t conn;
2773 	int error;
2774 
2775 	conn.ac_local = *local;
2776 	conn.ac_remote = *remote;
2777 	conn.ac_start = TCPS_SYN_SENT;
2778 	conn.ac_end = TCPS_TIME_WAIT;
2779 	conn.ac_zoneid = zoneid;
2780 
2781 	ioc.ic_cmd = TCP_IOC_ABORT_CONN;
2782 	ioc.ic_timout = -1; /* infinite timeout */
2783 	ioc.ic_len = sizeof (conn);
2784 	ioc.ic_dp = (char *)&conn;
2785 
2786 	if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
2787 		zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
2788 		return (-1);
2789 	}
2790 
2791 	error = ioctl(fd, I_STR, &ioc);
2792 	(void) close(fd);
2793 	if (error == 0 || errno == ENOENT)	/* ENOENT is not an error */
2794 		return (0);
2795 	return (-1);
2796 }
2797 
2798 static int
2799 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
2800 {
2801 	struct sockaddr_storage l, r;
2802 	struct sockaddr_in *local, *remote;
2803 	struct sockaddr_in6 *local6, *remote6;
2804 	int error;
2805 
2806 	/*
2807 	 * Abort IPv4 connections.
2808 	 */
2809 	bzero(&l, sizeof (*local));
2810 	local = (struct sockaddr_in *)&l;
2811 	local->sin_family = AF_INET;
2812 	local->sin_addr.s_addr = INADDR_ANY;
2813 	local->sin_port = 0;
2814 
2815 	bzero(&r, sizeof (*remote));
2816 	remote = (struct sockaddr_in *)&r;
2817 	remote->sin_family = AF_INET;
2818 	remote->sin_addr.s_addr = INADDR_ANY;
2819 	remote->sin_port = 0;
2820 
2821 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2822 		return (error);
2823 
2824 	/*
2825 	 * Abort IPv6 connections.
2826 	 */
2827 	bzero(&l, sizeof (*local6));
2828 	local6 = (struct sockaddr_in6 *)&l;
2829 	local6->sin6_family = AF_INET6;
2830 	local6->sin6_port = 0;
2831 	local6->sin6_addr = in6addr_any;
2832 
2833 	bzero(&r, sizeof (*remote6));
2834 	remote6 = (struct sockaddr_in6 *)&r;
2835 	remote6->sin6_family = AF_INET6;
2836 	remote6->sin6_port = 0;
2837 	remote6->sin6_addr = in6addr_any;
2838 
2839 	if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
2840 		return (error);
2841 	return (0);
2842 }
2843 
2844 static int
2845 get_privset(zlog_t *zlogp, priv_set_t *privs, zone_mnt_t mount_cmd)
2846 {
2847 	int error = -1;
2848 	zone_dochandle_t handle;
2849 	char *privname = NULL;
2850 
2851 	if ((handle = zonecfg_init_handle()) == NULL) {
2852 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2853 		return (-1);
2854 	}
2855 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2856 		zerror(zlogp, B_FALSE, "invalid configuration");
2857 		zonecfg_fini_handle(handle);
2858 		return (-1);
2859 	}
2860 
2861 	if (ALT_MOUNT(mount_cmd)) {
2862 		zone_iptype_t	iptype;
2863 		const char	*curr_iptype;
2864 
2865 		if (zonecfg_get_iptype(handle, &iptype) != Z_OK) {
2866 			zerror(zlogp, B_TRUE, "unable to determine ip-type");
2867 			zonecfg_fini_handle(handle);
2868 			return (-1);
2869 		}
2870 
2871 		switch (iptype) {
2872 		case ZS_SHARED:
2873 			curr_iptype = "shared";
2874 			break;
2875 		case ZS_EXCLUSIVE:
2876 			curr_iptype = "exclusive";
2877 			break;
2878 		}
2879 
2880 		if (zonecfg_default_privset(privs, curr_iptype) == Z_OK) {
2881 			zonecfg_fini_handle(handle);
2882 			return (0);
2883 		}
2884 		zerror(zlogp, B_FALSE,
2885 		    "failed to determine the zone's default privilege set");
2886 		zonecfg_fini_handle(handle);
2887 		return (-1);
2888 	}
2889 
2890 	switch (zonecfg_get_privset(handle, privs, &privname)) {
2891 	case Z_OK:
2892 		error = 0;
2893 		break;
2894 	case Z_PRIV_PROHIBITED:
2895 		zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
2896 		    "within the zone's privilege set", privname);
2897 		break;
2898 	case Z_PRIV_REQUIRED:
2899 		zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
2900 		    "from the zone's privilege set", privname);
2901 		break;
2902 	case Z_PRIV_UNKNOWN:
2903 		zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
2904 		    "in the zone's privilege set", privname);
2905 		break;
2906 	default:
2907 		zerror(zlogp, B_FALSE, "failed to determine the zone's "
2908 		    "privilege set");
2909 		break;
2910 	}
2911 
2912 	free(privname);
2913 	zonecfg_fini_handle(handle);
2914 	return (error);
2915 }
2916 
2917 static int
2918 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
2919 {
2920 	nvlist_t *nvl = NULL;
2921 	char *nvl_packed = NULL;
2922 	size_t nvl_size = 0;
2923 	nvlist_t **nvlv = NULL;
2924 	int rctlcount = 0;
2925 	int error = -1;
2926 	zone_dochandle_t handle;
2927 	struct zone_rctltab rctltab;
2928 	rctlblk_t *rctlblk = NULL;
2929 
2930 	*bufp = NULL;
2931 	*bufsizep = 0;
2932 
2933 	if ((handle = zonecfg_init_handle()) == NULL) {
2934 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
2935 		return (-1);
2936 	}
2937 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2938 		zerror(zlogp, B_FALSE, "invalid configuration");
2939 		zonecfg_fini_handle(handle);
2940 		return (-1);
2941 	}
2942 
2943 	rctltab.zone_rctl_valptr = NULL;
2944 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
2945 		zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
2946 		goto out;
2947 	}
2948 
2949 	if (zonecfg_setrctlent(handle) != Z_OK) {
2950 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
2951 		goto out;
2952 	}
2953 
2954 	if ((rctlblk = malloc(rctlblk_size())) == NULL) {
2955 		zerror(zlogp, B_TRUE, "memory allocation failed");
2956 		goto out;
2957 	}
2958 	while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2959 		struct zone_rctlvaltab *rctlval;
2960 		uint_t i, count;
2961 		const char *name = rctltab.zone_rctl_name;
2962 
2963 		/* zoneadm should have already warned about unknown rctls. */
2964 		if (!zonecfg_is_rctl(name)) {
2965 			zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2966 			rctltab.zone_rctl_valptr = NULL;
2967 			continue;
2968 		}
2969 		count = 0;
2970 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2971 		    rctlval = rctlval->zone_rctlval_next) {
2972 			count++;
2973 		}
2974 		if (count == 0) {	/* ignore */
2975 			continue;	/* Nothing to free */
2976 		}
2977 		if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
2978 			goto out;
2979 		i = 0;
2980 		for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2981 		    rctlval = rctlval->zone_rctlval_next, i++) {
2982 			if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
2983 				zerror(zlogp, B_TRUE, "%s failed",
2984 				    "nvlist_alloc");
2985 				goto out;
2986 			}
2987 			if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2988 			    != Z_OK) {
2989 				zerror(zlogp, B_FALSE, "invalid rctl value: "
2990 				    "(priv=%s,limit=%s,action=%s)",
2991 				    rctlval->zone_rctlval_priv,
2992 				    rctlval->zone_rctlval_limit,
2993 				    rctlval->zone_rctlval_action);
2994 				goto out;
2995 			}
2996 			if (!zonecfg_valid_rctl(name, rctlblk)) {
2997 				zerror(zlogp, B_FALSE,
2998 				    "(priv=%s,limit=%s,action=%s) is not a "
2999 				    "valid value for rctl '%s'",
3000 				    rctlval->zone_rctlval_priv,
3001 				    rctlval->zone_rctlval_limit,
3002 				    rctlval->zone_rctlval_action,
3003 				    name);
3004 				goto out;
3005 			}
3006 			if (nvlist_add_uint64(nvlv[i], "privilege",
3007 			    rctlblk_get_privilege(rctlblk)) != 0) {
3008 				zerror(zlogp, B_FALSE, "%s failed",
3009 				    "nvlist_add_uint64");
3010 				goto out;
3011 			}
3012 			if (nvlist_add_uint64(nvlv[i], "limit",
3013 			    rctlblk_get_value(rctlblk)) != 0) {
3014 				zerror(zlogp, B_FALSE, "%s failed",
3015 				    "nvlist_add_uint64");
3016 				goto out;
3017 			}
3018 			if (nvlist_add_uint64(nvlv[i], "action",
3019 			    (uint_t)rctlblk_get_local_action(rctlblk, NULL))
3020 			    != 0) {
3021 				zerror(zlogp, B_FALSE, "%s failed",
3022 				    "nvlist_add_uint64");
3023 				goto out;
3024 			}
3025 		}
3026 		zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3027 		rctltab.zone_rctl_valptr = NULL;
3028 		if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
3029 		    != 0) {
3030 			zerror(zlogp, B_FALSE, "%s failed",
3031 			    "nvlist_add_nvlist_array");
3032 			goto out;
3033 		}
3034 		for (i = 0; i < count; i++)
3035 			nvlist_free(nvlv[i]);
3036 		free(nvlv);
3037 		nvlv = NULL;
3038 		rctlcount++;
3039 	}
3040 	(void) zonecfg_endrctlent(handle);
3041 
3042 	if (rctlcount == 0) {
3043 		error = 0;
3044 		goto out;
3045 	}
3046 	if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
3047 	    != 0) {
3048 		zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
3049 		goto out;
3050 	}
3051 
3052 	error = 0;
3053 	*bufp = nvl_packed;
3054 	*bufsizep = nvl_size;
3055 
3056 out:
3057 	free(rctlblk);
3058 	zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3059 	if (error && nvl_packed != NULL)
3060 		free(nvl_packed);
3061 	if (nvl != NULL)
3062 		nvlist_free(nvl);
3063 	if (nvlv != NULL)
3064 		free(nvlv);
3065 	if (handle != NULL)
3066 		zonecfg_fini_handle(handle);
3067 	return (error);
3068 }
3069 
3070 static int
3071 get_implicit_datasets(zlog_t *zlogp, char **retstr)
3072 {
3073 	char cmdbuf[2 * MAXPATHLEN];
3074 
3075 	if (query_hook[0] == '\0')
3076 		return (0);
3077 
3078 	if (snprintf(cmdbuf, sizeof (cmdbuf), "%s datasets", query_hook)
3079 	    > sizeof (cmdbuf))
3080 		return (-1);
3081 
3082 	if (do_subproc(zlogp, cmdbuf, retstr) != 0)
3083 		return (-1);
3084 
3085 	return (0);
3086 }
3087 
3088 static int
3089 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3090 {
3091 	zone_dochandle_t handle;
3092 	struct zone_dstab dstab;
3093 	size_t total, offset, len;
3094 	int error = -1;
3095 	char *str = NULL;
3096 	char *implicit_datasets = NULL;
3097 	int implicit_len = 0;
3098 
3099 	*bufp = NULL;
3100 	*bufsizep = 0;
3101 
3102 	if ((handle = zonecfg_init_handle()) == NULL) {
3103 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3104 		return (-1);
3105 	}
3106 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3107 		zerror(zlogp, B_FALSE, "invalid configuration");
3108 		zonecfg_fini_handle(handle);
3109 		return (-1);
3110 	}
3111 
3112 	if (get_implicit_datasets(zlogp, &implicit_datasets) != 0) {
3113 		zerror(zlogp, B_FALSE, "getting implicit datasets failed");
3114 		goto out;
3115 	}
3116 
3117 	if (zonecfg_setdsent(handle) != Z_OK) {
3118 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3119 		goto out;
3120 	}
3121 
3122 	total = 0;
3123 	while (zonecfg_getdsent(handle, &dstab) == Z_OK)
3124 		total += strlen(dstab.zone_dataset_name) + 1;
3125 	(void) zonecfg_enddsent(handle);
3126 
3127 	if (implicit_datasets != NULL)
3128 		implicit_len = strlen(implicit_datasets);
3129 	if (implicit_len > 0)
3130 		total += implicit_len + 1;
3131 
3132 	if (total == 0) {
3133 		error = 0;
3134 		goto out;
3135 	}
3136 
3137 	if ((str = malloc(total)) == NULL) {
3138 		zerror(zlogp, B_TRUE, "memory allocation failed");
3139 		goto out;
3140 	}
3141 
3142 	if (zonecfg_setdsent(handle) != Z_OK) {
3143 		zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3144 		goto out;
3145 	}
3146 	offset = 0;
3147 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3148 		len = strlen(dstab.zone_dataset_name);
3149 		(void) strlcpy(str + offset, dstab.zone_dataset_name,
3150 		    total - offset);
3151 		offset += len;
3152 		if (offset < total - 1)
3153 			str[offset++] = ',';
3154 	}
3155 	(void) zonecfg_enddsent(handle);
3156 
3157 	if (implicit_len > 0)
3158 		(void) strlcpy(str + offset, implicit_datasets, total - offset);
3159 
3160 	error = 0;
3161 	*bufp = str;
3162 	*bufsizep = total;
3163 
3164 out:
3165 	if (error != 0 && str != NULL)
3166 		free(str);
3167 	if (handle != NULL)
3168 		zonecfg_fini_handle(handle);
3169 	if (implicit_datasets != NULL)
3170 		free(implicit_datasets);
3171 
3172 	return (error);
3173 }
3174 
3175 static int
3176 validate_datasets(zlog_t *zlogp)
3177 {
3178 	zone_dochandle_t handle;
3179 	struct zone_dstab dstab;
3180 	zfs_handle_t *zhp;
3181 	libzfs_handle_t *hdl;
3182 
3183 	if ((handle = zonecfg_init_handle()) == NULL) {
3184 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3185 		return (-1);
3186 	}
3187 	if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3188 		zerror(zlogp, B_FALSE, "invalid configuration");
3189 		zonecfg_fini_handle(handle);
3190 		return (-1);
3191 	}
3192 
3193 	if (zonecfg_setdsent(handle) != Z_OK) {
3194 		zerror(zlogp, B_FALSE, "invalid configuration");
3195 		zonecfg_fini_handle(handle);
3196 		return (-1);
3197 	}
3198 
3199 	if ((hdl = libzfs_init()) == NULL) {
3200 		zerror(zlogp, B_FALSE, "opening ZFS library");
3201 		zonecfg_fini_handle(handle);
3202 		return (-1);
3203 	}
3204 
3205 	while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3206 
3207 		if ((zhp = zfs_open(hdl, dstab.zone_dataset_name,
3208 		    ZFS_TYPE_FILESYSTEM)) == NULL) {
3209 			zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
3210 			    dstab.zone_dataset_name);
3211 			zonecfg_fini_handle(handle);
3212 			libzfs_fini(hdl);
3213 			return (-1);
3214 		}
3215 
3216 		/*
3217 		 * Automatically set the 'zoned' property.  We check the value
3218 		 * first because we'll get EPERM if it is already set.
3219 		 */
3220 		if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
3221 		    zfs_prop_set(zhp, zfs_prop_to_name(ZFS_PROP_ZONED),
3222 		    "on") != 0) {
3223 			zerror(zlogp, B_FALSE, "cannot set 'zoned' "
3224 			    "property for ZFS dataset '%s'\n",
3225 			    dstab.zone_dataset_name);
3226 			zonecfg_fini_handle(handle);
3227 			zfs_close(zhp);
3228 			libzfs_fini(hdl);
3229 			return (-1);
3230 		}
3231 
3232 		zfs_close(zhp);
3233 	}
3234 	(void) zonecfg_enddsent(handle);
3235 
3236 	zonecfg_fini_handle(handle);
3237 	libzfs_fini(hdl);
3238 
3239 	return (0);
3240 }
3241 
3242 /*
3243  * Mount lower level home directories into/from current zone
3244  * Share exported directories specified in dfstab for zone
3245  */
3246 static int
3247 tsol_mounts(zlog_t *zlogp, char *zone_name, char *rootpath)
3248 {
3249 	zoneid_t *zids = NULL;
3250 	priv_set_t *zid_privs;
3251 	const priv_impl_info_t *ip = NULL;
3252 	uint_t nzents_saved;
3253 	uint_t nzents;
3254 	int i;
3255 	char readonly[] = "ro";
3256 	struct zone_fstab lower_fstab;
3257 	char *argv[4];
3258 
3259 	if (!is_system_labeled())
3260 		return (0);
3261 
3262 	if (zid_label == NULL) {
3263 		zid_label = m_label_alloc(MAC_LABEL);
3264 		if (zid_label == NULL)
3265 			return (-1);
3266 	}
3267 
3268 	/* Make sure our zone has an /export/home dir */
3269 	(void) make_one_dir(zlogp, rootpath, "/export/home",
3270 	    DEFAULT_DIR_MODE, DEFAULT_DIR_USER, DEFAULT_DIR_GROUP);
3271 
3272 	lower_fstab.zone_fs_raw[0] = '\0';
3273 	(void) strlcpy(lower_fstab.zone_fs_type, MNTTYPE_LOFS,
3274 	    sizeof (lower_fstab.zone_fs_type));
3275 	lower_fstab.zone_fs_options = NULL;
3276 	(void) zonecfg_add_fs_option(&lower_fstab, readonly);
3277 
3278 	/*
3279 	 * Get the list of zones from the kernel
3280 	 */
3281 	if (zone_list(NULL, &nzents) != 0) {
3282 		zerror(zlogp, B_TRUE, "unable to list zones");
3283 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3284 		return (-1);
3285 	}
3286 again:
3287 	if (nzents == 0) {
3288 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3289 		return (-1);
3290 	}
3291 
3292 	zids = malloc(nzents * sizeof (zoneid_t));
3293 	if (zids == NULL) {
3294 		zerror(zlogp, B_TRUE, "memory allocation failed");
3295 		return (-1);
3296 	}
3297 	nzents_saved = nzents;
3298 
3299 	if (zone_list(zids, &nzents) != 0) {
3300 		zerror(zlogp, B_TRUE, "unable to list zones");
3301 		zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3302 		free(zids);
3303 		return (-1);
3304 	}
3305 	if (nzents != nzents_saved) {
3306 		/* list changed, try again */
3307 		free(zids);
3308 		goto again;
3309 	}
3310 
3311 	ip = getprivimplinfo();
3312 	if ((zid_privs = priv_allocset()) == NULL) {
3313 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3314 		zonecfg_free_fs_option_list(
3315 		    lower_fstab.zone_fs_options);
3316 		free(zids);
3317 		return (-1);
3318 	}
3319 
3320 	for (i = 0; i < nzents; i++) {
3321 		char zid_name[ZONENAME_MAX];
3322 		zone_state_t zid_state;
3323 		char zid_rpath[MAXPATHLEN];
3324 		struct stat stat_buf;
3325 
3326 		if (zids[i] == GLOBAL_ZONEID)
3327 			continue;
3328 
3329 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3330 			continue;
3331 
3332 		/*
3333 		 * Do special setup for the zone we are booting
3334 		 */
3335 		if (strcmp(zid_name, zone_name) == 0) {
3336 			struct zone_fstab autofs_fstab;
3337 			char map_path[MAXPATHLEN];
3338 			int fd;
3339 
3340 			/*
3341 			 * Create auto_home_<zone> map for this zone
3342 			 * in the global zone. The non-global zone entry
3343 			 * will be created by automount when the zone
3344 			 * is booted.
3345 			 */
3346 
3347 			(void) snprintf(autofs_fstab.zone_fs_special,
3348 			    MAXPATHLEN, "auto_home_%s", zid_name);
3349 
3350 			(void) snprintf(autofs_fstab.zone_fs_dir, MAXPATHLEN,
3351 			    "/zone/%s/home", zid_name);
3352 
3353 			(void) snprintf(map_path, sizeof (map_path),
3354 			    "/etc/%s", autofs_fstab.zone_fs_special);
3355 			/*
3356 			 * If the map file doesn't exist create a template
3357 			 */
3358 			if ((fd = open(map_path, O_RDWR | O_CREAT | O_EXCL,
3359 			    S_IRUSR | S_IWUSR | S_IRGRP| S_IROTH)) != -1) {
3360 				int len;
3361 				char map_rec[MAXPATHLEN];
3362 
3363 				len = snprintf(map_rec, sizeof (map_rec),
3364 				    "+%s\n*\t-fstype=lofs\t:%s/export/home/&\n",
3365 				    autofs_fstab.zone_fs_special, rootpath);
3366 				(void) write(fd, map_rec, len);
3367 				(void) close(fd);
3368 			}
3369 
3370 			/*
3371 			 * Mount auto_home_<zone> in the global zone if absent.
3372 			 * If it's already of type autofs, then
3373 			 * don't mount it again.
3374 			 */
3375 			if ((stat(autofs_fstab.zone_fs_dir, &stat_buf) == -1) ||
3376 			    strcmp(stat_buf.st_fstype, MNTTYPE_AUTOFS) != 0) {
3377 				char optstr[] = "indirect,ignore,nobrowse";
3378 
3379 				(void) make_one_dir(zlogp, "",
3380 				    autofs_fstab.zone_fs_dir, DEFAULT_DIR_MODE,
3381 				    DEFAULT_DIR_USER, DEFAULT_DIR_GROUP);
3382 
3383 				/*
3384 				 * Mount will fail if automounter has already
3385 				 * processed the auto_home_<zonename> map
3386 				 */
3387 				(void) domount(zlogp, MNTTYPE_AUTOFS, optstr,
3388 				    autofs_fstab.zone_fs_special,
3389 				    autofs_fstab.zone_fs_dir);
3390 			}
3391 			continue;
3392 		}
3393 
3394 
3395 		if (zone_get_state(zid_name, &zid_state) != Z_OK ||
3396 		    (zid_state != ZONE_STATE_READY &&
3397 		    zid_state != ZONE_STATE_RUNNING))
3398 			/* Skip over zones without mounted filesystems */
3399 			continue;
3400 
3401 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3402 		    sizeof (m_label_t)) < 0)
3403 			/* Skip over zones with unspecified label */
3404 			continue;
3405 
3406 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3407 		    sizeof (zid_rpath)) == -1)
3408 			/* Skip over zones with bad path */
3409 			continue;
3410 
3411 		if (zone_getattr(zids[i], ZONE_ATTR_PRIVSET, zid_privs,
3412 		    sizeof (priv_chunk_t) * ip->priv_setsize) == -1)
3413 			/* Skip over zones with bad privs */
3414 			continue;
3415 
3416 		/*
3417 		 * Reading down is valid according to our label model
3418 		 * but some customers want to disable it because it
3419 		 * allows execute down and other possible attacks.
3420 		 * Therefore, we restrict this feature to zones that
3421 		 * have the NET_MAC_AWARE privilege which is required
3422 		 * for NFS read-down semantics.
3423 		 */
3424 		if ((bldominates(zlabel, zid_label)) &&
3425 		    (priv_ismember(zprivs, PRIV_NET_MAC_AWARE))) {
3426 			/*
3427 			 * Our zone dominates this one.
3428 			 * Create a lofs mount from lower zone's /export/home
3429 			 */
3430 			(void) snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
3431 			    "%s/zone/%s/export/home", rootpath, zid_name);
3432 
3433 			/*
3434 			 * If the target is already an LOFS mount
3435 			 * then don't do it again.
3436 			 */
3437 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3438 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3439 
3440 				if (snprintf(lower_fstab.zone_fs_special,
3441 				    MAXPATHLEN, "%s/export",
3442 				    zid_rpath) > MAXPATHLEN)
3443 					continue;
3444 
3445 				/*
3446 				 * Make sure the lower-level home exists
3447 				 */
3448 				if (make_one_dir(zlogp,
3449 				    lower_fstab.zone_fs_special, "/home",
3450 				    DEFAULT_DIR_MODE, DEFAULT_DIR_USER,
3451 				    DEFAULT_DIR_GROUP) != 0)
3452 					continue;
3453 
3454 				(void) strlcat(lower_fstab.zone_fs_special,
3455 				    "/home", MAXPATHLEN);
3456 
3457 				/*
3458 				 * Mount can fail because the lower-level
3459 				 * zone may have already done a mount up.
3460 				 */
3461 				(void) mount_one(zlogp, &lower_fstab, "",
3462 				    Z_MNT_BOOT);
3463 			}
3464 		} else if ((bldominates(zid_label, zlabel)) &&
3465 		    (priv_ismember(zid_privs, PRIV_NET_MAC_AWARE))) {
3466 			/*
3467 			 * This zone dominates our zone.
3468 			 * Create a lofs mount from our zone's /export/home
3469 			 */
3470 			if (snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
3471 			    "%s/zone/%s/export/home", zid_rpath,
3472 			    zone_name) > MAXPATHLEN)
3473 				continue;
3474 
3475 			/*
3476 			 * If the target is already an LOFS mount
3477 			 * then don't do it again.
3478 			 */
3479 			if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3480 			    strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3481 
3482 				(void) snprintf(lower_fstab.zone_fs_special,
3483 				    MAXPATHLEN, "%s/export/home", rootpath);
3484 
3485 				/*
3486 				 * Mount can fail because the higher-level
3487 				 * zone may have already done a mount down.
3488 				 */
3489 				(void) mount_one(zlogp, &lower_fstab, "",
3490 				    Z_MNT_BOOT);
3491 			}
3492 		}
3493 	}
3494 	zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3495 	priv_freeset(zid_privs);
3496 	free(zids);
3497 
3498 	/*
3499 	 * Now share any exported directories from this zone.
3500 	 * Each zone can have its own dfstab.
3501 	 */
3502 
3503 	argv[0] = "zoneshare";
3504 	argv[1] = "-z";
3505 	argv[2] = zone_name;
3506 	argv[3] = NULL;
3507 
3508 	(void) forkexec(zlogp, "/usr/lib/zones/zoneshare", argv);
3509 	/* Don't check for errors since they don't affect the zone */
3510 
3511 	return (0);
3512 }
3513 
3514 /*
3515  * Unmount lofs mounts from higher level zones
3516  * Unshare nfs exported directories
3517  */
3518 static void
3519 tsol_unmounts(zlog_t *zlogp, char *zone_name)
3520 {
3521 	zoneid_t *zids = NULL;
3522 	uint_t nzents_saved;
3523 	uint_t nzents;
3524 	int i;
3525 	char *argv[4];
3526 	char path[MAXPATHLEN];
3527 
3528 	if (!is_system_labeled())
3529 		return;
3530 
3531 	/*
3532 	 * Get the list of zones from the kernel
3533 	 */
3534 	if (zone_list(NULL, &nzents) != 0) {
3535 		return;
3536 	}
3537 
3538 	if (zid_label == NULL) {
3539 		zid_label = m_label_alloc(MAC_LABEL);
3540 		if (zid_label == NULL)
3541 			return;
3542 	}
3543 
3544 again:
3545 	if (nzents == 0)
3546 		return;
3547 
3548 	zids = malloc(nzents * sizeof (zoneid_t));
3549 	if (zids == NULL) {
3550 		zerror(zlogp, B_TRUE, "memory allocation failed");
3551 		return;
3552 	}
3553 	nzents_saved = nzents;
3554 
3555 	if (zone_list(zids, &nzents) != 0) {
3556 		free(zids);
3557 		return;
3558 	}
3559 	if (nzents != nzents_saved) {
3560 		/* list changed, try again */
3561 		free(zids);
3562 		goto again;
3563 	}
3564 
3565 	for (i = 0; i < nzents; i++) {
3566 		char zid_name[ZONENAME_MAX];
3567 		zone_state_t zid_state;
3568 		char zid_rpath[MAXPATHLEN];
3569 
3570 		if (zids[i] == GLOBAL_ZONEID)
3571 			continue;
3572 
3573 		if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3574 			continue;
3575 
3576 		/*
3577 		 * Skip the zone we are halting
3578 		 */
3579 		if (strcmp(zid_name, zone_name) == 0)
3580 			continue;
3581 
3582 		if ((zone_getattr(zids[i], ZONE_ATTR_STATUS, &zid_state,
3583 		    sizeof (zid_state)) < 0) ||
3584 		    (zid_state < ZONE_IS_READY))
3585 			/* Skip over zones without mounted filesystems */
3586 			continue;
3587 
3588 		if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3589 		    sizeof (m_label_t)) < 0)
3590 			/* Skip over zones with unspecified label */
3591 			continue;
3592 
3593 		if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3594 		    sizeof (zid_rpath)) == -1)
3595 			/* Skip over zones with bad path */
3596 			continue;
3597 
3598 		if (zlabel != NULL && bldominates(zid_label, zlabel)) {
3599 			/*
3600 			 * This zone dominates our zone.
3601 			 * Unmount the lofs mount of our zone's /export/home
3602 			 */
3603 
3604 			if (snprintf(path, MAXPATHLEN,
3605 			    "%s/zone/%s/export/home", zid_rpath,
3606 			    zone_name) > MAXPATHLEN)
3607 				continue;
3608 
3609 			/* Skip over mount failures */
3610 			(void) umount(path);
3611 		}
3612 	}
3613 	free(zids);
3614 
3615 	/*
3616 	 * Unmount global zone autofs trigger for this zone
3617 	 */
3618 	(void) snprintf(path, MAXPATHLEN, "/zone/%s/home", zone_name);
3619 	/* Skip over mount failures */
3620 	(void) umount(path);
3621 
3622 	/*
3623 	 * Next unshare any exported directories from this zone.
3624 	 */
3625 
3626 	argv[0] = "zoneunshare";
3627 	argv[1] = "-z";
3628 	argv[2] = zone_name;
3629 	argv[3] = NULL;
3630 
3631 	(void) forkexec(zlogp, "/usr/lib/zones/zoneunshare", argv);
3632 	/* Don't check for errors since they don't affect the zone */
3633 
3634 	/*
3635 	 * Finally, deallocate any devices in the zone.
3636 	 */
3637 
3638 	argv[0] = "deallocate";
3639 	argv[1] = "-Isz";
3640 	argv[2] = zone_name;
3641 	argv[3] = NULL;
3642 
3643 	(void) forkexec(zlogp, "/usr/sbin/deallocate", argv);
3644 	/* Don't check for errors since they don't affect the zone */
3645 }
3646 
3647 /*
3648  * Fetch the Trusted Extensions label and multi-level ports (MLPs) for
3649  * this zone.
3650  */
3651 static tsol_zcent_t *
3652 get_zone_label(zlog_t *zlogp, priv_set_t *privs)
3653 {
3654 	FILE *fp;
3655 	tsol_zcent_t *zcent = NULL;
3656 	char line[MAXTNZLEN];
3657 
3658 	if ((fp = fopen(TNZONECFG_PATH, "r")) == NULL) {
3659 		zerror(zlogp, B_TRUE, "%s", TNZONECFG_PATH);
3660 		return (NULL);
3661 	}
3662 
3663 	while (fgets(line, sizeof (line), fp) != NULL) {
3664 		/*
3665 		 * Check for malformed database
3666 		 */
3667 		if (strlen(line) == MAXTNZLEN - 1)
3668 			break;
3669 		if ((zcent = tsol_sgetzcent(line, NULL, NULL)) == NULL)
3670 			continue;
3671 		if (strcmp(zcent->zc_name, zone_name) == 0)
3672 			break;
3673 		tsol_freezcent(zcent);
3674 		zcent = NULL;
3675 	}
3676 	(void) fclose(fp);
3677 
3678 	if (zcent == NULL) {
3679 		zerror(zlogp, B_FALSE, "zone requires a label assignment. "
3680 		    "See tnzonecfg(4)");
3681 	} else {
3682 		if (zlabel == NULL)
3683 			zlabel = m_label_alloc(MAC_LABEL);
3684 		/*
3685 		 * Save this zone's privileges for later read-down processing
3686 		 */
3687 		if ((zprivs = priv_allocset()) == NULL) {
3688 			zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3689 			return (NULL);
3690 		} else {
3691 			priv_copyset(privs, zprivs);
3692 		}
3693 	}
3694 	return (zcent);
3695 }
3696 
3697 /*
3698  * Add the Trusted Extensions multi-level ports for this zone.
3699  */
3700 static void
3701 set_mlps(zlog_t *zlogp, zoneid_t zoneid, tsol_zcent_t *zcent)
3702 {
3703 	tsol_mlp_t *mlp;
3704 	tsol_mlpent_t tsme;
3705 
3706 	if (!is_system_labeled())
3707 		return;
3708 
3709 	tsme.tsme_zoneid = zoneid;
3710 	tsme.tsme_flags = 0;
3711 	for (mlp = zcent->zc_private_mlp; !TSOL_MLP_END(mlp); mlp++) {
3712 		tsme.tsme_mlp = *mlp;
3713 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3714 			zerror(zlogp, B_TRUE, "cannot set zone-specific MLP "
3715 			    "on %d-%d/%d", mlp->mlp_port,
3716 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3717 		}
3718 	}
3719 
3720 	tsme.tsme_flags = TSOL_MEF_SHARED;
3721 	for (mlp = zcent->zc_shared_mlp; !TSOL_MLP_END(mlp); mlp++) {
3722 		tsme.tsme_mlp = *mlp;
3723 		if (tnmlp(TNDB_LOAD, &tsme) != 0) {
3724 			zerror(zlogp, B_TRUE, "cannot set shared MLP "
3725 			    "on %d-%d/%d", mlp->mlp_port,
3726 			    mlp->mlp_port_upper, mlp->mlp_ipp);
3727 		}
3728 	}
3729 }
3730 
3731 static void
3732 remove_mlps(zlog_t *zlogp, zoneid_t zoneid)
3733 {
3734 	tsol_mlpent_t tsme;
3735 
3736 	if (!is_system_labeled())
3737 		return;
3738 
3739 	(void) memset(&tsme, 0, sizeof (tsme));
3740 	tsme.tsme_zoneid = zoneid;
3741 	if (tnmlp(TNDB_FLUSH, &tsme) != 0)
3742 		zerror(zlogp, B_TRUE, "cannot flush MLPs");
3743 }
3744 
3745 int
3746 prtmount(const char *fs, void *x) {
3747 	zerror((zlog_t *)x, B_FALSE, "  %s", fs);
3748 	return (0);
3749 }
3750 
3751 /*
3752  * Look for zones running on the main system that are using this root (or any
3753  * subdirectory of it).  Return B_TRUE and print an error if a conflicting zone
3754  * is found or if we can't tell.
3755  */
3756 static boolean_t
3757 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
3758 {
3759 	zoneid_t *zids = NULL;
3760 	uint_t nzids = 0;
3761 	boolean_t retv;
3762 	int rlen, zlen;
3763 	char zroot[MAXPATHLEN];
3764 	char zonename[ZONENAME_MAX];
3765 
3766 	for (;;) {
3767 		nzids += 10;
3768 		zids = malloc(nzids * sizeof (*zids));
3769 		if (zids == NULL) {
3770 			zerror(zlogp, B_TRUE, "memory allocation failed");
3771 			return (B_TRUE);
3772 		}
3773 		if (zone_list(zids, &nzids) == 0)
3774 			break;
3775 		free(zids);
3776 	}
3777 	retv = B_FALSE;
3778 	rlen = strlen(rootpath);
3779 	while (nzids > 0) {
3780 		/*
3781 		 * Ignore errors; they just mean that the zone has disappeared
3782 		 * while we were busy.
3783 		 */
3784 		if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
3785 		    sizeof (zroot)) == -1)
3786 			continue;
3787 		zlen = strlen(zroot);
3788 		if (zlen > rlen)
3789 			zlen = rlen;
3790 		if (strncmp(rootpath, zroot, zlen) == 0 &&
3791 		    (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
3792 		    (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
3793 			if (getzonenamebyid(zids[nzids], zonename,
3794 			    sizeof (zonename)) == -1)
3795 				(void) snprintf(zonename, sizeof (zonename),
3796 				    "id %d", (int)zids[nzids]);
3797 			zerror(zlogp, B_FALSE,
3798 			    "zone root %s already in use by zone %s",
3799 			    rootpath, zonename);
3800 			retv = B_TRUE;
3801 			break;
3802 		}
3803 	}
3804 	free(zids);
3805 	return (retv);
3806 }
3807 
3808 /*
3809  * Search for loopback mounts that use this same source node (same device and
3810  * inode).  Return B_TRUE if there is one or if we can't tell.
3811  */
3812 static boolean_t
3813 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
3814 {
3815 	struct stat64 rst, zst;
3816 	struct mnttab *mnp;
3817 
3818 	if (stat64(rootpath, &rst) == -1) {
3819 		zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
3820 		return (B_TRUE);
3821 	}
3822 	if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
3823 		return (B_TRUE);
3824 	for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
3825 		if (mnp->mnt_fstype == NULL ||
3826 		    strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
3827 			continue;
3828 		/* We're looking at a loopback mount.  Stat it. */
3829 		if (mnp->mnt_special != NULL &&
3830 		    stat64(mnp->mnt_special, &zst) != -1 &&
3831 		    rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
3832 			zerror(zlogp, B_FALSE,
3833 			    "zone root %s is reachable through %s",
3834 			    rootpath, mnp->mnt_mountp);
3835 			return (B_TRUE);
3836 		}
3837 	}
3838 	return (B_FALSE);
3839 }
3840 
3841 /*
3842  * Set memory cap and pool info for the zone's resource management
3843  * configuration.
3844  */
3845 static int
3846 setup_zone_rm(zlog_t *zlogp, char *zone_name, zoneid_t zoneid)
3847 {
3848 	int res;
3849 	uint64_t tmp;
3850 	struct zone_mcaptab mcap;
3851 	char sched[MAXNAMELEN];
3852 	zone_dochandle_t handle = NULL;
3853 	char pool_err[128];
3854 
3855 	if ((handle = zonecfg_init_handle()) == NULL) {
3856 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
3857 		return (Z_BAD_HANDLE);
3858 	}
3859 
3860 	if ((res = zonecfg_get_snapshot_handle(zone_name, handle)) != Z_OK) {
3861 		zerror(zlogp, B_FALSE, "invalid configuration");
3862 		zonecfg_fini_handle(handle);
3863 		return (res);
3864 	}
3865 
3866 	/*
3867 	 * If a memory cap is configured, set the cap in the kernel using
3868 	 * zone_setattr() and make sure the rcapd SMF service is enabled.
3869 	 */
3870 	if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
3871 		uint64_t num;
3872 		char smf_err[128];
3873 
3874 		num = (uint64_t)strtoull(mcap.zone_physmem_cap, NULL, 10);
3875 		if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
3876 			zerror(zlogp, B_TRUE, "could not set zone memory cap");
3877 			zonecfg_fini_handle(handle);
3878 			return (Z_INVAL);
3879 		}
3880 
3881 		if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
3882 			zerror(zlogp, B_FALSE, "enabling system/rcap service "
3883 			    "failed: %s", smf_err);
3884 			zonecfg_fini_handle(handle);
3885 			return (Z_INVAL);
3886 		}
3887 	}
3888 
3889 	/* Get the scheduling class set in the zone configuration. */
3890 	if (zonecfg_get_sched_class(handle, sched, sizeof (sched)) == Z_OK &&
3891 	    strlen(sched) > 0) {
3892 		if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, sched,
3893 		    strlen(sched)) == -1)
3894 			zerror(zlogp, B_TRUE, "WARNING: unable to set the "
3895 			    "default scheduling class");
3896 
3897 	} else if (zonecfg_get_aliased_rctl(handle, ALIAS_SHARES, &tmp)
3898 	    == Z_OK) {
3899 		/*
3900 		 * If the zone has the zone.cpu-shares rctl set then we want to
3901 		 * use the Fair Share Scheduler (FSS) for processes in the
3902 		 * zone.  Check what scheduling class the zone would be running
3903 		 * in by default so we can print a warning and modify the class
3904 		 * if we wouldn't be using FSS.
3905 		 */
3906 		char class_name[PC_CLNMSZ];
3907 
3908 		if (zonecfg_get_dflt_sched_class(handle, class_name,
3909 		    sizeof (class_name)) != Z_OK) {
3910 			zerror(zlogp, B_FALSE, "WARNING: unable to determine "
3911 			    "the zone's scheduling class");
3912 
3913 		} else if (strcmp("FSS", class_name) != 0) {
3914 			zerror(zlogp, B_FALSE, "WARNING: The zone.cpu-shares "
3915 			    "rctl is set but\nFSS is not the default "
3916 			    "scheduling class for\nthis zone.  FSS will be "
3917 			    "used for processes\nin the zone but to get the "
3918 			    "full benefit of FSS,\nit should be the default "
3919 			    "scheduling class.\nSee dispadmin(1M) for more "
3920 			    "details.");
3921 
3922 			if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, "FSS",
3923 			    strlen("FSS")) == -1)
3924 				zerror(zlogp, B_TRUE, "WARNING: unable to set "
3925 				    "zone scheduling class to FSS");
3926 		}
3927 	}
3928 
3929 	/*
3930 	 * The next few blocks of code attempt to set up temporary pools as
3931 	 * well as persistent pools.  In all cases we call the functions
3932 	 * unconditionally.  Within each funtion the code will check if the
3933 	 * zone is actually configured for a temporary pool or persistent pool
3934 	 * and just return if there is nothing to do.
3935 	 *
3936 	 * If we are rebooting we want to attempt to reuse any temporary pool
3937 	 * that was previously set up.  zonecfg_bind_tmp_pool() will do the
3938 	 * right thing in all cases (reuse or create) based on the current
3939 	 * zonecfg.
3940 	 */
3941 	if ((res = zonecfg_bind_tmp_pool(handle, zoneid, pool_err,
3942 	    sizeof (pool_err))) != Z_OK) {
3943 		if (res == Z_POOL || res == Z_POOL_CREATE || res == Z_POOL_BIND)
3944 			zerror(zlogp, B_FALSE, "%s: %s\ndedicated-cpu setting "
3945 			    "cannot be instantiated", zonecfg_strerror(res),
3946 			    pool_err);
3947 		else
3948 			zerror(zlogp, B_FALSE, "could not bind zone to "
3949 			    "temporary pool: %s", zonecfg_strerror(res));
3950 		zonecfg_fini_handle(handle);
3951 		return (Z_POOL_BIND);
3952 	}
3953 
3954 	/*
3955 	 * Check if we need to warn about poold not being enabled.
3956 	 */
3957 	if (zonecfg_warn_poold(handle)) {
3958 		zerror(zlogp, B_FALSE, "WARNING: A range of dedicated-cpus has "
3959 		    "been specified\nbut the dynamic pool service is not "
3960 		    "enabled.\nThe system will not dynamically adjust the\n"
3961 		    "processor allocation within the specified range\n"
3962 		    "until svc:/system/pools/dynamic is enabled.\n"
3963 		    "See poold(1M).");
3964 	}
3965 
3966 	/* The following is a warning, not an error. */
3967 	if ((res = zonecfg_bind_pool(handle, zoneid, pool_err,
3968 	    sizeof (pool_err))) != Z_OK) {
3969 		if (res == Z_POOL_BIND)
3970 			zerror(zlogp, B_FALSE, "WARNING: unable to bind to "
3971 			    "pool '%s'; using default pool.", pool_err);
3972 		else if (res == Z_POOL)
3973 			zerror(zlogp, B_FALSE, "WARNING: %s: %s",
3974 			    zonecfg_strerror(res), pool_err);
3975 		else
3976 			zerror(zlogp, B_FALSE, "WARNING: %s",
3977 			    zonecfg_strerror(res));
3978 	}
3979 
3980 	zonecfg_fini_handle(handle);
3981 	return (Z_OK);
3982 }
3983 
3984 /*
3985  * Sets the hostid of the new zone based on its configured value.  The zone's
3986  * zone_t structure must already exist in kernel memory.  'zlogp' refers to the
3987  * log used to report errors and warnings and must be non-NULL.  'zone_namep'
3988  * is the name of the new zone and must be non-NULL.  'zoneid' is the numeric
3989  * ID of the new zone.
3990  *
3991  * This function returns zero on success and a nonzero error code on failure.
3992  */
3993 static int
3994 setup_zone_hostid(zlog_t *zlogp, char *zone_namep, zoneid_t zoneid)
3995 {
3996 	int res;
3997 	zone_dochandle_t handle;
3998 	char hostidp[HW_HOSTID_LEN];
3999 	unsigned int hostid;
4000 
4001 	if ((handle = zonecfg_init_handle()) == NULL) {
4002 		zerror(zlogp, B_TRUE, "getting zone configuration handle");
4003 		return (Z_BAD_HANDLE);
4004 	}
4005 	if ((res = zonecfg_get_snapshot_handle(zone_namep, handle)) != Z_OK) {
4006 		zerror(zlogp, B_FALSE, "invalid configuration");
4007 		zonecfg_fini_handle(handle);
4008 		return (res);
4009 	}
4010 
4011 	if ((res = zonecfg_get_hostid(handle, hostidp, sizeof (hostidp))) ==
4012 	    Z_OK) {
4013 		if (zonecfg_valid_hostid(hostidp) != Z_OK) {
4014 			zerror(zlogp, B_FALSE,
4015 			    "zone hostid is not valid: %s", hostidp);
4016 			zonecfg_fini_handle(handle);
4017 			return (Z_HOSTID_FUBAR);
4018 		}
4019 		hostid = (unsigned int)strtoul(hostidp, NULL, 16);
4020 		if (zone_setattr(zoneid, ZONE_ATTR_HOSTID, &hostid,
4021 		    sizeof (hostid)) != 0) {
4022 			zerror(zlogp, B_TRUE,
4023 			    "zone hostid is not valid: %s", hostidp);
4024 			zonecfg_fini_handle(handle);
4025 			return (Z_SYSTEM);
4026 		}
4027 	} else if (res != Z_BAD_PROPERTY) {
4028 		/*
4029 		 * Z_BAD_PROPERTY is an acceptable error value (from
4030 		 * zonecfg_get_hostid()) because it indicates that the zone
4031 		 * doesn't have a hostid.
4032 		 */
4033 		if (res == Z_TOO_BIG)
4034 			zerror(zlogp, B_FALSE, "hostid string in zone "
4035 			    "configuration is too large.");
4036 		else
4037 			zerror(zlogp, B_TRUE, "fetching zone hostid from "
4038 			    "configuration");
4039 		zonecfg_fini_handle(handle);
4040 		return (res);
4041 	}
4042 
4043 	zonecfg_fini_handle(handle);
4044 	return (Z_OK);
4045 }
4046 
4047 zoneid_t
4048 vplat_create(zlog_t *zlogp, zone_mnt_t mount_cmd)
4049 {
4050 	zoneid_t rval = -1;
4051 	priv_set_t *privs;
4052 	char rootpath[MAXPATHLEN];
4053 	char *rctlbuf = NULL;
4054 	size_t rctlbufsz = 0;
4055 	char *zfsbuf = NULL;
4056 	size_t zfsbufsz = 0;
4057 	zoneid_t zoneid = -1;
4058 	int xerr;
4059 	char *kzone;
4060 	FILE *fp = NULL;
4061 	tsol_zcent_t *zcent = NULL;
4062 	int match = 0;
4063 	int doi = 0;
4064 	int flags;
4065 	zone_iptype_t iptype;
4066 
4067 	if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
4068 		zerror(zlogp, B_TRUE, "unable to determine zone root");
4069 		return (-1);
4070 	}
4071 	if (zonecfg_in_alt_root())
4072 		resolve_lofs(zlogp, rootpath, sizeof (rootpath));
4073 
4074 	if (get_iptype(zlogp, &iptype) < 0) {
4075 		zerror(zlogp, B_TRUE, "unable to determine ip-type");
4076 		return (-1);
4077 	}
4078 	switch (iptype) {
4079 	case ZS_SHARED:
4080 		flags = 0;
4081 		break;
4082 	case ZS_EXCLUSIVE:
4083 		flags = ZCF_NET_EXCL;
4084 		break;
4085 	}
4086 
4087 	if ((privs = priv_allocset()) == NULL) {
4088 		zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
4089 		return (-1);
4090 	}
4091 	priv_emptyset(privs);
4092 	if (get_privset(zlogp, privs, mount_cmd) != 0)
4093 		goto error;
4094 
4095 	if (mount_cmd == Z_MNT_BOOT &&
4096 	    get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
4097 		zerror(zlogp, B_FALSE, "Unable to get list of rctls");
4098 		goto error;
4099 	}
4100 
4101 	if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
4102 		zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
4103 		goto error;
4104 	}
4105 
4106 	if (mount_cmd == Z_MNT_BOOT && is_system_labeled()) {
4107 		zcent = get_zone_label(zlogp, privs);
4108 		if (zcent != NULL) {
4109 			match = zcent->zc_match;
4110 			doi = zcent->zc_doi;
4111 			*zlabel = zcent->zc_label;
4112 		} else {
4113 			goto error;
4114 		}
4115 	}
4116 
4117 	kzone = zone_name;
4118 
4119 	/*
4120 	 * We must do this scan twice.  First, we look for zones running on the
4121 	 * main system that are using this root (or any subdirectory of it).
4122 	 * Next, we reduce to the shortest path and search for loopback mounts
4123 	 * that use this same source node (same device and inode).
4124 	 */
4125 	if (duplicate_zone_root(zlogp, rootpath))
4126 		goto error;
4127 	if (duplicate_reachable_path(zlogp, rootpath))
4128 		goto error;
4129 
4130 	if (ALT_MOUNT(mount_cmd)) {
4131 		root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
4132 
4133 		/*
4134 		 * Forge up a special root for this zone.  When a zone is
4135 		 * mounted, we can't let the zone have its own root because the
4136 		 * tools that will be used in this "scratch zone" need access
4137 		 * to both the zone's resources and the running machine's
4138 		 * executables.
4139 		 *
4140 		 * Note that the mkdir here also catches read-only filesystems.
4141 		 */
4142 		if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
4143 			zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
4144 			goto error;
4145 		}
4146 		if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
4147 			goto error;
4148 	}
4149 
4150 	if (zonecfg_in_alt_root()) {
4151 		/*
4152 		 * If we are mounting up a zone in an alternate root partition,
4153 		 * then we have some additional work to do before starting the
4154 		 * zone.  First, resolve the root path down so that we're not
4155 		 * fooled by duplicates.  Then forge up an internal name for
4156 		 * the zone.
4157 		 */
4158 		if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
4159 			zerror(zlogp, B_TRUE, "cannot open mapfile");
4160 			goto error;
4161 		}
4162 		if (zonecfg_lock_scratch(fp) != 0) {
4163 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
4164 			goto error;
4165 		}
4166 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4167 		    NULL, 0) == 0) {
4168 			zerror(zlogp, B_FALSE, "scratch zone already running");
4169 			goto error;
4170 		}
4171 		/* This is the preferred name */
4172 		(void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
4173 		    zone_name);
4174 		srandom(getpid());
4175 		while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
4176 		    0) == 0) {
4177 			/* This is just an arbitrary name; note "." usage */
4178 			(void) snprintf(kernzone, sizeof (kernzone),
4179 			    "SUNWlu.%08lX%08lX", random(), random());
4180 		}
4181 		kzone = kernzone;
4182 	}
4183 
4184 	xerr = 0;
4185 	if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
4186 	    rctlbufsz, zfsbuf, zfsbufsz, &xerr, match, doi, zlabel,
4187 	    flags)) == -1) {
4188 		if (xerr == ZE_AREMOUNTS) {
4189 			if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
4190 				zerror(zlogp, B_FALSE,
4191 				    "An unknown file-system is mounted on "
4192 				    "a subdirectory of %s", rootpath);
4193 			} else {
4194 
4195 				zerror(zlogp, B_FALSE,
4196 				    "These file-systems are mounted on "
4197 				    "subdirectories of %s:", rootpath);
4198 				(void) zonecfg_find_mounts(rootpath,
4199 				    prtmount, zlogp);
4200 			}
4201 		} else if (xerr == ZE_CHROOTED) {
4202 			zerror(zlogp, B_FALSE, "%s: "
4203 			    "cannot create a zone from a chrooted "
4204 			    "environment", "zone_create");
4205 		} else if (xerr == ZE_LABELINUSE) {
4206 			char zonename[ZONENAME_MAX];
4207 			(void) getzonenamebyid(getzoneidbylabel(zlabel),
4208 			    zonename, ZONENAME_MAX);
4209 			zerror(zlogp, B_FALSE, "The zone label is already "
4210 			    "used by the zone '%s'.", zonename);
4211 		} else {
4212 			zerror(zlogp, B_TRUE, "%s failed", "zone_create");
4213 		}
4214 		goto error;
4215 	}
4216 
4217 	if (zonecfg_in_alt_root() &&
4218 	    zonecfg_add_scratch(fp, zone_name, kernzone,
4219 	    zonecfg_get_root()) == -1) {
4220 		zerror(zlogp, B_TRUE, "cannot add mapfile entry");
4221 		goto error;
4222 	}
4223 
4224 	/*
4225 	 * The following actions are not performed when merely mounting a zone
4226 	 * for administrative use.
4227 	 */
4228 	if (mount_cmd == Z_MNT_BOOT) {
4229 		brand_handle_t bh;
4230 		struct brand_attr attr;
4231 		char modname[MAXPATHLEN];
4232 
4233 		if (setup_zone_hostid(zlogp, zone_name, zoneid) != Z_OK)
4234 			goto error;
4235 
4236 		if ((zone_get_brand(zone_name, attr.ba_brandname,
4237 		    MAXNAMELEN) != Z_OK) ||
4238 		    (bh = brand_open(attr.ba_brandname)) == NULL) {
4239 			zerror(zlogp, B_FALSE,
4240 			    "unable to determine brand name");
4241 			goto error;
4242 		}
4243 
4244 		if (!is_system_labeled() &&
4245 		    (strcmp(attr.ba_brandname, LABELED_BRAND_NAME) == 0)) {
4246 			brand_close(bh);
4247 			zerror(zlogp, B_FALSE,
4248 			    "cannot boot labeled zone on unlabeled system");
4249 			goto error;
4250 		}
4251 
4252 		/*
4253 		 * If this brand requires any kernel support, now is the time to
4254 		 * get it loaded and initialized.
4255 		 */
4256 		if (brand_get_modname(bh, modname, MAXPATHLEN) < 0) {
4257 			brand_close(bh);
4258 			zerror(zlogp, B_FALSE,
4259 			    "unable to determine brand kernel module");
4260 			goto error;
4261 		}
4262 		brand_close(bh);
4263 
4264 		if (strlen(modname) > 0) {
4265 			(void) strlcpy(attr.ba_modname, modname, MAXPATHLEN);
4266 			if (zone_setattr(zoneid, ZONE_ATTR_BRAND, &attr,
4267 			    sizeof (attr) != 0)) {
4268 				zerror(zlogp, B_TRUE,
4269 				    "could not set zone brand attribute.");
4270 				goto error;
4271 			}
4272 		}
4273 
4274 		if (setup_zone_rm(zlogp, zone_name, zoneid) != Z_OK)
4275 			goto error;
4276 
4277 		set_mlps(zlogp, zoneid, zcent);
4278 	}
4279 
4280 	rval = zoneid;
4281 	zoneid = -1;
4282 
4283 error:
4284 	if (zoneid != -1) {
4285 		(void) zone_shutdown(zoneid);
4286 		(void) zone_destroy(zoneid);
4287 	}
4288 	if (rctlbuf != NULL)
4289 		free(rctlbuf);
4290 	priv_freeset(privs);
4291 	if (fp != NULL)
4292 		zonecfg_close_scratch(fp);
4293 	lofs_discard_mnttab();
4294 	if (zcent != NULL)
4295 		tsol_freezcent(zcent);
4296 	return (rval);
4297 }
4298 
4299 /*
4300  * Enter the zone and write a /etc/zones/index file there.  This allows
4301  * libzonecfg (and thus zoneadm) to report the UUID and potentially other zone
4302  * details from inside the zone.
4303  */
4304 static void
4305 write_index_file(zoneid_t zoneid)
4306 {
4307 	FILE *zef;
4308 	FILE *zet;
4309 	struct zoneent *zep;
4310 	pid_t child;
4311 	int tmpl_fd;
4312 	ctid_t ct;
4313 	int fd;
4314 	char uuidstr[UUID_PRINTABLE_STRING_LENGTH];
4315 
4316 	/* Locate the zone entry in the global zone's index file */
4317 	if ((zef = setzoneent()) == NULL)
4318 		return;
4319 	while ((zep = getzoneent_private(zef)) != NULL) {
4320 		if (strcmp(zep->zone_name, zone_name) == 0)
4321 			break;
4322 		free(zep);
4323 	}
4324 	endzoneent(zef);
4325 	if (zep == NULL)
4326 		return;
4327 
4328 	if ((tmpl_fd = init_template()) == -1) {
4329 		free(zep);
4330 		return;
4331 	}
4332 
4333 	if ((child = fork()) == -1) {
4334 		(void) ct_tmpl_clear(tmpl_fd);
4335 		(void) close(tmpl_fd);
4336 		free(zep);
4337 		return;
4338 	}
4339 
4340 	/* parent waits for child to finish */
4341 	if (child != 0) {
4342 		free(zep);
4343 		if (contract_latest(&ct) == -1)
4344 			ct = -1;
4345 		(void) ct_tmpl_clear(tmpl_fd);
4346 		(void) close(tmpl_fd);
4347 		(void) waitpid(child, NULL, 0);
4348 		(void) contract_abandon_id(ct);
4349 		return;
4350 	}
4351 
4352 	/* child enters zone and sets up index file */
4353 	(void) ct_tmpl_clear(tmpl_fd);
4354 	if (zone_enter(zoneid) != -1) {
4355 		(void) mkdir(ZONE_CONFIG_ROOT, ZONE_CONFIG_MODE);
4356 		(void) chown(ZONE_CONFIG_ROOT, ZONE_CONFIG_UID,
4357 		    ZONE_CONFIG_GID);
4358 		fd = open(ZONE_INDEX_FILE, O_WRONLY|O_CREAT|O_TRUNC,
4359 		    ZONE_INDEX_MODE);
4360 		if (fd != -1 && (zet = fdopen(fd, "w")) != NULL) {
4361 			(void) fchown(fd, ZONE_INDEX_UID, ZONE_INDEX_GID);
4362 			if (uuid_is_null(zep->zone_uuid))
4363 				uuidstr[0] = '\0';
4364 			else
4365 				uuid_unparse(zep->zone_uuid, uuidstr);
4366 			(void) fprintf(zet, "%s:%s:/:%s\n", zep->zone_name,
4367 			    zone_state_str(zep->zone_state),
4368 			    uuidstr);
4369 			(void) fclose(zet);
4370 		}
4371 	}
4372 	_exit(0);
4373 }
4374 
4375 int
4376 vplat_bringup(zlog_t *zlogp, zone_mnt_t mount_cmd, zoneid_t zoneid)
4377 {
4378 	char zonepath[MAXPATHLEN];
4379 
4380 	if (mount_cmd == Z_MNT_BOOT && validate_datasets(zlogp) != 0) {
4381 		lofs_discard_mnttab();
4382 		return (-1);
4383 	}
4384 
4385 	/*
4386 	 * Before we try to mount filesystems we need to create the
4387 	 * attribute backing store for /dev
4388 	 */
4389 	if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
4390 		lofs_discard_mnttab();
4391 		return (-1);
4392 	}
4393 	resolve_lofs(zlogp, zonepath, sizeof (zonepath));
4394 
4395 	/* Make /dev directory owned by root, grouped sys */
4396 	if (make_one_dir(zlogp, zonepath, "/dev", DEFAULT_DIR_MODE,
4397 	    0, 3) != 0) {
4398 		lofs_discard_mnttab();
4399 		return (-1);
4400 	}
4401 
4402 	if (mount_filesystems(zlogp, mount_cmd) != 0) {
4403 		lofs_discard_mnttab();
4404 		return (-1);
4405 	}
4406 
4407 	if (mount_cmd == Z_MNT_BOOT) {
4408 		zone_iptype_t iptype;
4409 
4410 		if (get_iptype(zlogp, &iptype) < 0) {
4411 			zerror(zlogp, B_TRUE, "unable to determine ip-type");
4412 			lofs_discard_mnttab();
4413 			return (-1);
4414 		}
4415 
4416 		switch (iptype) {
4417 		case ZS_SHARED:
4418 			/* Always do this to make lo0 get configured */
4419 			if (configure_shared_network_interfaces(zlogp) != 0) {
4420 				lofs_discard_mnttab();
4421 				return (-1);
4422 			}
4423 			break;
4424 		case ZS_EXCLUSIVE:
4425 			if (configure_exclusive_network_interfaces(zlogp) !=
4426 			    0) {
4427 				lofs_discard_mnttab();
4428 				return (-1);
4429 			}
4430 			break;
4431 		}
4432 	}
4433 
4434 	write_index_file(zoneid);
4435 
4436 	lofs_discard_mnttab();
4437 	return (0);
4438 }
4439 
4440 static int
4441 lu_root_teardown(zlog_t *zlogp)
4442 {
4443 	char zroot[MAXPATHLEN];
4444 
4445 	if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
4446 		zerror(zlogp, B_FALSE, "unable to determine zone root");
4447 		return (-1);
4448 	}
4449 	root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
4450 
4451 	/*
4452 	 * At this point, the processes are gone, the filesystems (save the
4453 	 * root) are unmounted, and the zone is on death row.  But there may
4454 	 * still be creds floating about in the system that reference the
4455 	 * zone_t, and which pin down zone_rootvp causing this call to fail
4456 	 * with EBUSY.  Thus, we try for a little while before just giving up.
4457 	 * (How I wish this were not true, and umount2 just did the right
4458 	 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
4459 	 */
4460 	if (umount2(zroot, MS_FORCE) != 0) {
4461 		if (errno == ENOTSUP && umount2(zroot, 0) == 0)
4462 			goto unmounted;
4463 		if (errno == EBUSY) {
4464 			int tries = 10;
4465 
4466 			while (--tries >= 0) {
4467 				(void) sleep(1);
4468 				if (umount2(zroot, 0) == 0)
4469 					goto unmounted;
4470 				if (errno != EBUSY)
4471 					break;
4472 			}
4473 		}
4474 		zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
4475 		return (-1);
4476 	}
4477 unmounted:
4478 
4479 	/*
4480 	 * Only zones in an alternate root environment have scratch zone
4481 	 * entries.
4482 	 */
4483 	if (zonecfg_in_alt_root()) {
4484 		FILE *fp;
4485 		int retv;
4486 
4487 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4488 			zerror(zlogp, B_TRUE, "cannot open mapfile");
4489 			return (-1);
4490 		}
4491 		retv = -1;
4492 		if (zonecfg_lock_scratch(fp) != 0)
4493 			zerror(zlogp, B_TRUE, "cannot lock mapfile");
4494 		else if (zonecfg_delete_scratch(fp, kernzone) != 0)
4495 			zerror(zlogp, B_TRUE, "cannot delete map entry");
4496 		else
4497 			retv = 0;
4498 		zonecfg_close_scratch(fp);
4499 		return (retv);
4500 	} else {
4501 		return (0);
4502 	}
4503 }
4504 
4505 int
4506 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd, boolean_t rebooting)
4507 {
4508 	char *kzone;
4509 	zoneid_t zoneid;
4510 	int res;
4511 	char pool_err[128];
4512 	char zpath[MAXPATHLEN];
4513 	char cmdbuf[MAXPATHLEN];
4514 	char brand[MAXNAMELEN];
4515 	brand_handle_t bh = NULL;
4516 	ushort_t flags;
4517 
4518 	kzone = zone_name;
4519 	if (zonecfg_in_alt_root()) {
4520 		FILE *fp;
4521 
4522 		if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4523 			zerror(zlogp, B_TRUE, "unable to open map file");
4524 			goto error;
4525 		}
4526 		if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4527 		    kernzone, sizeof (kernzone)) != 0) {
4528 			zerror(zlogp, B_FALSE, "unable to find scratch zone");
4529 			zonecfg_close_scratch(fp);
4530 			goto error;
4531 		}
4532 		zonecfg_close_scratch(fp);
4533 		kzone = kernzone;
4534 	}
4535 
4536 	if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
4537 		if (!bringup_failure_recovery)
4538 			zerror(zlogp, B_TRUE, "unable to get zoneid");
4539 		if (unmount_cmd)
4540 			(void) lu_root_teardown(zlogp);
4541 		goto error;
4542 	}
4543 
4544 	if (zone_shutdown(zoneid) != 0) {
4545 		zerror(zlogp, B_TRUE, "unable to shutdown zone");
4546 		goto error;
4547 	}
4548 
4549 	/* Get the zonepath of this zone */
4550 	if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
4551 		zerror(zlogp, B_FALSE, "unable to determine zone path");
4552 		goto error;
4553 	}
4554 
4555 	/* Get a handle to the brand info for this zone */
4556 	if ((zone_get_brand(zone_name, brand, sizeof (brand)) != Z_OK) ||
4557 	    (bh = brand_open(brand)) == NULL) {
4558 		zerror(zlogp, B_FALSE, "unable to determine zone brand");
4559 		return (-1);
4560 	}
4561 	/*
4562 	 * If there is a brand 'halt' callback, execute it now to give the
4563 	 * brand a chance to cleanup any custom configuration.
4564 	 */
4565 	(void) strcpy(cmdbuf, EXEC_PREFIX);
4566 	if (brand_get_halt(bh, zone_name, zpath, cmdbuf + EXEC_LEN,
4567 	    sizeof (cmdbuf) - EXEC_LEN) < 0) {
4568 		brand_close(bh);
4569 		zerror(zlogp, B_FALSE, "unable to determine branded zone's "
4570 		    "halt callback.");
4571 		goto error;
4572 	}
4573 	brand_close(bh);
4574 
4575 	if ((strlen(cmdbuf) > EXEC_LEN) &&
4576 	    (do_subproc(zlogp, cmdbuf, NULL) != Z_OK)) {
4577 		zerror(zlogp, B_FALSE, "%s failed", cmdbuf);
4578 		goto error;
4579 	}
4580 
4581 	if (!unmount_cmd) {
4582 		zone_iptype_t iptype;
4583 
4584 		if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
4585 		    sizeof (flags)) < 0) {
4586 			if (get_iptype(zlogp, &iptype) < 0) {
4587 				zerror(zlogp, B_TRUE, "unable to determine "
4588 				    "ip-type");
4589 				goto error;
4590 			}
4591 		} else {
4592 			if (flags & ZF_NET_EXCL)
4593 				iptype = ZS_EXCLUSIVE;
4594 			else
4595 				iptype = ZS_SHARED;
4596 		}
4597 
4598 		switch (iptype) {
4599 		case ZS_SHARED:
4600 			if (unconfigure_shared_network_interfaces(zlogp,
4601 			    zoneid) != 0) {
4602 				zerror(zlogp, B_FALSE, "unable to unconfigure "
4603 				    "network interfaces in zone");
4604 				goto error;
4605 			}
4606 			break;
4607 		case ZS_EXCLUSIVE:
4608 			if (unconfigure_exclusive_network_interfaces(zlogp,
4609 			    zoneid) != 0) {
4610 				zerror(zlogp, B_FALSE, "unable to unconfigure "
4611 				    "network interfaces in zone");
4612 				goto error;
4613 			}
4614 			break;
4615 		}
4616 	}
4617 
4618 	if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
4619 		zerror(zlogp, B_TRUE, "unable to abort TCP connections");
4620 		goto error;
4621 	}
4622 
4623 	if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
4624 		zerror(zlogp, B_FALSE,
4625 		    "unable to unmount file systems in zone");
4626 		goto error;
4627 	}
4628 
4629 	/*
4630 	 * If we are rebooting then we normally don't want to destroy an
4631 	 * existing temporary pool at this point so that we can just reuse it
4632 	 * when the zone boots back up.  However, it is also possible we were
4633 	 * running with a temporary pool and the zone configuration has been
4634 	 * modified to no longer use a temporary pool.  In that case we need
4635 	 * to destroy the temporary pool now.  This case looks like the case
4636 	 * where we never had a temporary pool configured but
4637 	 * zonecfg_destroy_tmp_pool will do the right thing either way.
4638 	 */
4639 	if (!unmount_cmd) {
4640 		boolean_t destroy_tmp_pool = B_TRUE;
4641 
4642 		if (rebooting) {
4643 			struct zone_psettab pset_tab;
4644 			zone_dochandle_t handle;
4645 
4646 			if ((handle = zonecfg_init_handle()) != NULL &&
4647 			    zonecfg_get_handle(zone_name, handle) == Z_OK &&
4648 			    zonecfg_lookup_pset(handle, &pset_tab) == Z_OK)
4649 				destroy_tmp_pool = B_FALSE;
4650 
4651 			zonecfg_fini_handle(handle);
4652 		}
4653 
4654 		if (destroy_tmp_pool) {
4655 			if ((res = zonecfg_destroy_tmp_pool(zone_name, pool_err,
4656 			    sizeof (pool_err))) != Z_OK) {
4657 				if (res == Z_POOL)
4658 					zerror(zlogp, B_FALSE, pool_err);
4659 			}
4660 		}
4661 	}
4662 
4663 	remove_mlps(zlogp, zoneid);
4664 
4665 	if (zone_destroy(zoneid) != 0) {
4666 		zerror(zlogp, B_TRUE, "unable to destroy zone");
4667 		goto error;
4668 	}
4669 
4670 	/*
4671 	 * Special teardown for alternate boot environments: remove the tmpfs
4672 	 * root for the zone and then remove it from the map file.
4673 	 */
4674 	if (unmount_cmd && lu_root_teardown(zlogp) != 0)
4675 		goto error;
4676 
4677 	lofs_discard_mnttab();
4678 	return (0);
4679 
4680 error:
4681 	lofs_discard_mnttab();
4682 	return (-1);
4683 }
4684