Reamove grub support.
[unleashed.git] / usr / src / cmd / zoneadmd / vplat.c
blobf3013486085797258b896402a6772b9b3dc6ac46
1 /*
2 * CDDL HEADER START
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.
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.
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]
19 * CDDL HEADER END
23 * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2013, Joyent Inc. All rights reserved.
25 * Copyright (c) 2015 by Delphix. All rights reserved.
29 * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
33 * This module contains functions used to bring up and tear down the
34 * Virtual Platform: [un]mounting file-systems, [un]plumbing network
35 * interfaces, [un]configuring devices, establishing resource controls,
36 * and creating/destroying the zone in the kernel. These actions, on
37 * the way up, ready the zone; on the way down, they halt the zone.
38 * See the much longer block comment at the beginning of zoneadmd.c
39 * for a bigger picture of how the whole program functions.
41 * This module also has primary responsibility for the layout of "scratch
42 * zones." These are mounted, but inactive, zones that are used during
43 * operating system upgrade and potentially other administrative action. The
44 * scratch zone environment is similar to the miniroot environment. The zone's
45 * actual root is mounted read-write on /a, and the standard paths (/usr,
46 * /sbin, /lib) all lead to read-only copies of the running system's binaries.
47 * This allows the administrative tools to manipulate the zone using "-R /a"
48 * without relying on any binaries in the zone itself.
50 * If the scratch zone is on an alternate root (Live Upgrade [LU] boot
51 * environment), then we must resolve the lofs mounts used there to uncover
52 * writable (unshared) resources. Shared resources, though, are always
53 * read-only. In addition, if the "same" zone with a different root path is
54 * currently running, then "/b" inside the zone points to the running zone's
55 * root. This allows LU to synchronize configuration files during the upgrade
56 * process.
58 * To construct this environment, this module creates a tmpfs mount on
59 * $ZONEPATH/lu. Inside this scratch area, the miniroot-like environment as
60 * described above is constructed on the fly. The zone is then created using
61 * $ZONEPATH/lu as the root.
63 * Note that scratch zones are inactive. The zone's bits are not running and
64 * likely cannot be run correctly until upgrade is done. Init is not running
65 * there, nor is SMF. Because of this, the "mounted" state of a scratch zone
66 * is not a part of the usual halt/ready/boot state machine.
69 #include <sys/param.h>
70 #include <sys/mount.h>
71 #include <sys/mntent.h>
72 #include <sys/socket.h>
73 #include <sys/utsname.h>
74 #include <sys/types.h>
75 #include <sys/stat.h>
76 #include <sys/sockio.h>
77 #include <sys/stropts.h>
78 #include <sys/conf.h>
79 #include <sys/systeminfo.h>
80 #include <sys/secflags.h>
82 #include <libdlpi.h>
83 #include <libdllink.h>
84 #include <libdlvlan.h>
86 #include <inet/tcp.h>
87 #include <arpa/inet.h>
88 #include <netinet/in.h>
89 #include <net/route.h>
91 #include <stdio.h>
92 #include <errno.h>
93 #include <fcntl.h>
94 #include <unistd.h>
95 #include <rctl.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <strings.h>
99 #include <wait.h>
100 #include <limits.h>
101 #include <libgen.h>
102 #include <libzfs.h>
103 #include <libdevinfo.h>
104 #include <zone.h>
105 #include <assert.h>
106 #include <libcontract.h>
107 #include <libcontract_priv.h>
108 #include <uuid/uuid.h>
110 #include <sys/mntio.h>
111 #include <sys/mnttab.h>
112 #include <sys/fs/autofs.h> /* for _autofssys() */
113 #include <sys/fs/lofs_info.h>
114 #include <sys/fs/zfs.h>
116 #include <pool.h>
117 #include <sys/pool.h>
118 #include <sys/priocntl.h>
120 #include <libbrand.h>
121 #include <sys/brand.h>
122 #include <libzonecfg.h>
123 #include <synch.h>
125 #include "zoneadmd.h"
126 #include <tsol/label.h>
127 #include <libtsnet.h>
128 #include <sys/priv.h>
129 #include <libinetutil.h>
131 #define V4_ADDR_LEN 32
132 #define V6_ADDR_LEN 128
134 #define RESOURCE_DEFAULT_OPTS \
135 MNTOPT_RO "," MNTOPT_LOFS_NOSUB "," MNTOPT_NODEVICES
137 #define DFSTYPES "/etc/dfs/fstypes"
138 #define MAXTNZLEN 2048
140 #define ALT_MOUNT(mount_cmd) ((mount_cmd) != Z_MNT_BOOT)
142 /* a reasonable estimate for the number of lwps per process */
143 #define LWPS_PER_PROCESS 10
145 /* for routing socket */
146 static int rts_seqno = 0;
148 /* mangled zone name when mounting in an alternate root environment */
149 static char kernzone[ZONENAME_MAX];
151 /* array of cached mount entries for resolve_lofs */
152 static struct mnttab *resolve_lofs_mnts, *resolve_lofs_mnt_max;
154 /* for Trusted Extensions */
155 static tsol_zcent_t *get_zone_label(zlog_t *, priv_set_t *);
156 static int tsol_mounts(zlog_t *, char *, char *);
157 static void tsol_unmounts(zlog_t *, char *);
159 static m_label_t *zlabel = NULL;
160 static m_label_t *zid_label = NULL;
161 static priv_set_t *zprivs = NULL;
163 static const char *DFLT_FS_ALLOWED = "hsfs,smbfs,nfs,nfs3,nfs4,nfsdyn";
165 /* from libsocket, not in any header file */
166 extern int getnetmaskbyaddr(struct in_addr, struct in_addr *);
168 /* from zoneadmd */
169 extern char query_hook[];
172 * For each "net" resource configured in zonecfg, we track a zone_addr_list_t
173 * node in a linked list that is sorted by linkid. The list is constructed as
174 * the xml configuration file is parsed, and the information
175 * contained in each node is added to the kernel before the zone is
176 * booted, to be retrieved and applied from within the exclusive-IP NGZ
177 * on boot.
179 typedef struct zone_addr_list {
180 struct zone_addr_list *za_next;
181 datalink_id_t za_linkid; /* datalink_id_t of interface */
182 struct zone_nwiftab za_nwiftab; /* address, defrouter properties */
183 } zone_addr_list_t;
186 * An optimization for build_mnttable: reallocate (and potentially copy the
187 * data) only once every N times through the loop.
189 #define MNTTAB_HUNK 32
191 /* some handy macros */
192 #define SIN(s) ((struct sockaddr_in *)s)
193 #define SIN6(s) ((struct sockaddr_in6 *)s)
196 * Private autofs system call
198 extern int _autofssys(int, void *);
200 static int
201 autofs_cleanup(zoneid_t zoneid)
204 * Ask autofs to unmount all trigger nodes in the given zone.
206 return (_autofssys(AUTOFS_UNMOUNTALL, (void *)zoneid));
209 static void
210 free_mnttable(struct mnttab *mnt_array, uint_t nelem)
212 uint_t i;
214 if (mnt_array == NULL)
215 return;
216 for (i = 0; i < nelem; i++) {
217 free(mnt_array[i].mnt_mountp);
218 free(mnt_array[i].mnt_fstype);
219 free(mnt_array[i].mnt_special);
220 free(mnt_array[i].mnt_mntopts);
221 assert(mnt_array[i].mnt_time == NULL);
223 free(mnt_array);
227 * Build the mount table for the zone rooted at "zroot", storing the resulting
228 * array of struct mnttabs in "mnt_arrayp" and the number of elements in the
229 * array in "nelemp".
231 static int
232 build_mnttable(zlog_t *zlogp, const char *zroot, size_t zrootlen, FILE *mnttab,
233 struct mnttab **mnt_arrayp, uint_t *nelemp)
235 struct mnttab mnt;
236 struct mnttab *mnts;
237 struct mnttab *mnp;
238 uint_t nmnt;
240 rewind(mnttab);
241 resetmnttab(mnttab);
242 nmnt = 0;
243 mnts = NULL;
244 while (getmntent(mnttab, &mnt) == 0) {
245 struct mnttab *tmp_array;
247 if (strncmp(mnt.mnt_mountp, zroot, zrootlen) != 0)
248 continue;
249 if (nmnt % MNTTAB_HUNK == 0) {
250 tmp_array = realloc(mnts,
251 (nmnt + MNTTAB_HUNK) * sizeof (*mnts));
252 if (tmp_array == NULL) {
253 free_mnttable(mnts, nmnt);
254 return (-1);
256 mnts = tmp_array;
258 mnp = &mnts[nmnt++];
261 * Zero out any fields we're not using.
263 (void) memset(mnp, 0, sizeof (*mnp));
265 if (mnt.mnt_special != NULL)
266 mnp->mnt_special = strdup(mnt.mnt_special);
267 if (mnt.mnt_mntopts != NULL)
268 mnp->mnt_mntopts = strdup(mnt.mnt_mntopts);
269 mnp->mnt_mountp = strdup(mnt.mnt_mountp);
270 mnp->mnt_fstype = strdup(mnt.mnt_fstype);
271 if ((mnt.mnt_special != NULL && mnp->mnt_special == NULL) ||
272 (mnt.mnt_mntopts != NULL && mnp->mnt_mntopts == NULL) ||
273 mnp->mnt_mountp == NULL || mnp->mnt_fstype == NULL) {
274 zerror(zlogp, B_TRUE, "memory allocation failed");
275 free_mnttable(mnts, nmnt);
276 return (-1);
279 *mnt_arrayp = mnts;
280 *nelemp = nmnt;
281 return (0);
285 * This is an optimization. The resolve_lofs function is used quite frequently
286 * to manipulate file paths, and on a machine with a large number of zones,
287 * there will be a huge number of mounted file systems. Thus, we trigger a
288 * reread of the list of mount points
290 static void
291 lofs_discard_mnttab(void)
293 free_mnttable(resolve_lofs_mnts,
294 resolve_lofs_mnt_max - resolve_lofs_mnts);
295 resolve_lofs_mnts = resolve_lofs_mnt_max = NULL;
298 static int
299 lofs_read_mnttab(zlog_t *zlogp)
301 FILE *mnttab;
302 uint_t nmnts;
304 if ((mnttab = fopen(MNTTAB, "r")) == NULL)
305 return (-1);
306 if (build_mnttable(zlogp, "", 0, mnttab, &resolve_lofs_mnts,
307 &nmnts) == -1) {
308 (void) fclose(mnttab);
309 return (-1);
311 (void) fclose(mnttab);
312 resolve_lofs_mnt_max = resolve_lofs_mnts + nmnts;
313 return (0);
317 * This function loops over potential loopback mounts and symlinks in a given
318 * path and resolves them all down to an absolute path.
320 void
321 resolve_lofs(zlog_t *zlogp, char *path, size_t pathlen)
323 int len, arlen;
324 const char *altroot;
325 char tmppath[MAXPATHLEN];
326 boolean_t outside_altroot;
328 if ((len = resolvepath(path, tmppath, sizeof (tmppath))) == -1)
329 return;
330 tmppath[len] = '\0';
331 (void) strlcpy(path, tmppath, sizeof (tmppath));
333 /* This happens once per zoneadmd operation. */
334 if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
335 return;
337 altroot = zonecfg_get_root();
338 arlen = strlen(altroot);
339 outside_altroot = B_FALSE;
340 for (;;) {
341 struct mnttab *mnp;
343 /* Search in reverse order to find longest match */
344 for (mnp = resolve_lofs_mnt_max - 1; mnp >= resolve_lofs_mnts;
345 mnp--) {
346 if (mnp->mnt_fstype == NULL ||
347 mnp->mnt_mountp == NULL ||
348 mnp->mnt_special == NULL)
349 continue;
350 len = strlen(mnp->mnt_mountp);
351 if (strncmp(mnp->mnt_mountp, path, len) == 0 &&
352 (path[len] == '/' || path[len] == '\0'))
353 break;
355 if (mnp < resolve_lofs_mnts)
356 break;
357 /* If it's not a lofs then we're done */
358 if (strcmp(mnp->mnt_fstype, MNTTYPE_LOFS) != 0)
359 break;
360 if (outside_altroot) {
361 char *cp;
362 int olen = sizeof (MNTOPT_RO) - 1;
365 * If we run into a read-only mount outside of the
366 * alternate root environment, then the user doesn't
367 * want this path to be made read-write.
369 if (mnp->mnt_mntopts != NULL &&
370 (cp = strstr(mnp->mnt_mntopts, MNTOPT_RO)) !=
371 NULL &&
372 (cp == mnp->mnt_mntopts || cp[-1] == ',') &&
373 (cp[olen] == '\0' || cp[olen] == ',')) {
374 break;
376 } else if (arlen > 0 &&
377 (strncmp(mnp->mnt_special, altroot, arlen) != 0 ||
378 (mnp->mnt_special[arlen] != '\0' &&
379 mnp->mnt_special[arlen] != '/'))) {
380 outside_altroot = B_TRUE;
382 /* use temporary buffer because new path might be longer */
383 (void) snprintf(tmppath, sizeof (tmppath), "%s%s",
384 mnp->mnt_special, path + len);
385 if ((len = resolvepath(tmppath, path, pathlen)) == -1)
386 break;
387 path[len] = '\0';
392 * For a regular mount, check if a replacement lofs mount is needed because the
393 * referenced device is already mounted somewhere.
395 static int
396 check_lofs_needed(zlog_t *zlogp, struct zone_fstab *fsptr)
398 struct mnttab *mnp;
399 zone_fsopt_t *optptr, *onext;
401 /* This happens once per zoneadmd operation. */
402 if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
403 return (-1);
406 * If this special node isn't already in use, then it's ours alone;
407 * no need to worry about conflicting mounts.
409 for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
410 mnp++) {
411 if (strcmp(mnp->mnt_special, fsptr->zone_fs_special) == 0)
412 break;
414 if (mnp >= resolve_lofs_mnt_max)
415 return (0);
418 * Convert this duplicate mount into a lofs mount.
420 (void) strlcpy(fsptr->zone_fs_special, mnp->mnt_mountp,
421 sizeof (fsptr->zone_fs_special));
422 (void) strlcpy(fsptr->zone_fs_type, MNTTYPE_LOFS,
423 sizeof (fsptr->zone_fs_type));
424 fsptr->zone_fs_raw[0] = '\0';
427 * Discard all but one of the original options and set that to our
428 * default set of options used for resources.
430 optptr = fsptr->zone_fs_options;
431 if (optptr == NULL) {
432 optptr = malloc(sizeof (*optptr));
433 if (optptr == NULL) {
434 zerror(zlogp, B_TRUE, "cannot mount %s",
435 fsptr->zone_fs_dir);
436 return (-1);
438 } else {
439 while ((onext = optptr->zone_fsopt_next) != NULL) {
440 optptr->zone_fsopt_next = onext->zone_fsopt_next;
441 free(onext);
444 (void) strcpy(optptr->zone_fsopt_opt, RESOURCE_DEFAULT_OPTS);
445 optptr->zone_fsopt_next = NULL;
446 fsptr->zone_fs_options = optptr;
447 return (0);
451 make_one_dir(zlog_t *zlogp, const char *prefix, const char *subdir, mode_t mode,
452 uid_t userid, gid_t groupid)
454 char path[MAXPATHLEN];
455 struct stat st;
457 if (snprintf(path, sizeof (path), "%s%s", prefix, subdir) >
458 sizeof (path)) {
459 zerror(zlogp, B_FALSE, "pathname %s%s is too long", prefix,
460 subdir);
461 return (-1);
464 if (lstat(path, &st) == 0) {
466 * We don't check the file mode since presumably the zone
467 * administrator may have had good reason to change the mode,
468 * and we don't need to second guess him.
470 if (!S_ISDIR(st.st_mode)) {
471 if (S_ISREG(st.st_mode)) {
473 * Allow readonly mounts of /etc/ files; this
474 * is needed most by Trusted Extensions.
476 if (strncmp(subdir, "/etc/",
477 strlen("/etc/")) != 0) {
478 zerror(zlogp, B_FALSE,
479 "%s is not in /etc", path);
480 return (-1);
482 } else {
483 zerror(zlogp, B_FALSE,
484 "%s is not a directory", path);
485 return (-1);
488 return (0);
491 if (mkdirp(path, mode) != 0) {
492 if (errno == EROFS)
493 zerror(zlogp, B_FALSE, "Could not mkdir %s.\nIt is on "
494 "a read-only file system in this local zone.\nMake "
495 "sure %s exists in the global zone.", path, subdir);
496 else
497 zerror(zlogp, B_TRUE, "mkdirp of %s failed", path);
498 return (-1);
501 (void) chown(path, userid, groupid);
502 return (0);
505 static void
506 free_remote_fstypes(char **types)
508 uint_t i;
510 if (types == NULL)
511 return;
512 for (i = 0; types[i] != NULL; i++)
513 free(types[i]);
514 free(types);
517 static char **
518 get_remote_fstypes(zlog_t *zlogp)
520 char **types = NULL;
521 FILE *fp;
522 char buf[MAXPATHLEN];
523 char fstype[MAXPATHLEN];
524 uint_t lines = 0;
525 uint_t i;
527 if ((fp = fopen(DFSTYPES, "r")) == NULL) {
528 zerror(zlogp, B_TRUE, "failed to open %s", DFSTYPES);
529 return (NULL);
532 * Count the number of lines
534 while (fgets(buf, sizeof (buf), fp) != NULL)
535 lines++;
536 if (lines == 0) /* didn't read anything; empty file */
537 goto out;
538 rewind(fp);
540 * Allocate enough space for a NULL-terminated array.
542 types = calloc(lines + 1, sizeof (char *));
543 if (types == NULL) {
544 zerror(zlogp, B_TRUE, "memory allocation failed");
545 goto out;
547 i = 0;
548 while (fgets(buf, sizeof (buf), fp) != NULL) {
549 /* LINTED - fstype is big enough to hold buf */
550 if (sscanf(buf, "%s", fstype) == 0) {
551 zerror(zlogp, B_FALSE, "unable to parse %s", DFSTYPES);
552 free_remote_fstypes(types);
553 types = NULL;
554 goto out;
556 types[i] = strdup(fstype);
557 if (types[i] == NULL) {
558 zerror(zlogp, B_TRUE, "memory allocation failed");
559 free_remote_fstypes(types);
560 types = NULL;
561 goto out;
563 i++;
565 out:
566 (void) fclose(fp);
567 return (types);
570 static boolean_t
571 is_remote_fstype(const char *fstype, char *const *remote_fstypes)
573 uint_t i;
575 if (remote_fstypes == NULL)
576 return (B_FALSE);
577 for (i = 0; remote_fstypes[i] != NULL; i++) {
578 if (strcmp(remote_fstypes[i], fstype) == 0)
579 return (B_TRUE);
581 return (B_FALSE);
585 * This converts a zone root path (normally of the form .../root) to a Live
586 * Upgrade scratch zone root (of the form .../lu).
588 static void
589 root_to_lu(zlog_t *zlogp, char *zroot, size_t zrootlen, boolean_t isresolved)
591 if (!isresolved && zonecfg_in_alt_root())
592 resolve_lofs(zlogp, zroot, zrootlen);
593 (void) strcpy(strrchr(zroot, '/') + 1, "lu");
597 * The general strategy for unmounting filesystems is as follows:
599 * - Remote filesystems may be dead, and attempting to contact them as
600 * part of a regular unmount may hang forever; we want to always try to
601 * forcibly unmount such filesystems and only fall back to regular
602 * unmounts if the filesystem doesn't support forced unmounts.
604 * - We don't want to unnecessarily corrupt metadata on local
605 * filesystems (ie UFS), so we want to start off with graceful unmounts,
606 * and only escalate to doing forced unmounts if we get stuck.
608 * We start off walking backwards through the mount table. This doesn't
609 * give us strict ordering but ensures that we try to unmount submounts
610 * first. We thus limit the number of failed umount2(2) calls.
612 * The mechanism for determining if we're stuck is to count the number
613 * of failed unmounts each iteration through the mount table. This
614 * gives us an upper bound on the number of filesystems which remain
615 * mounted (autofs trigger nodes are dealt with separately). If at the
616 * end of one unmount+autofs_cleanup cycle we still have the same number
617 * of mounts that we started out with, we're stuck and try a forced
618 * unmount. If that fails (filesystem doesn't support forced unmounts)
619 * then we bail and are unable to teardown the zone. If it succeeds,
620 * we're no longer stuck so we continue with our policy of trying
621 * graceful mounts first.
623 * Zone must be down (ie, no processes or threads active).
625 static int
626 unmount_filesystems(zlog_t *zlogp, zoneid_t zoneid, boolean_t unmount_cmd)
628 int error = 0;
629 FILE *mnttab;
630 struct mnttab *mnts;
631 uint_t nmnt;
632 char zroot[MAXPATHLEN + 1];
633 size_t zrootlen;
634 uint_t oldcount = UINT_MAX;
635 boolean_t stuck = B_FALSE;
636 char **remote_fstypes = NULL;
638 if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
639 zerror(zlogp, B_FALSE, "unable to determine zone root");
640 return (-1);
642 if (unmount_cmd)
643 root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
645 (void) strcat(zroot, "/");
646 zrootlen = strlen(zroot);
649 * For Trusted Extensions unmount each higher level zone's mount
650 * of our zone's /export/home
652 if (!unmount_cmd)
653 tsol_unmounts(zlogp, zone_name);
655 if ((mnttab = fopen(MNTTAB, "r")) == NULL) {
656 zerror(zlogp, B_TRUE, "failed to open %s", MNTTAB);
657 return (-1);
660 * Use our hacky mntfs ioctl so we see everything, even mounts with
661 * MS_NOMNTTAB.
663 if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0) {
664 zerror(zlogp, B_TRUE, "unable to configure %s", MNTTAB);
665 error++;
666 goto out;
670 * Build the list of remote fstypes so we know which ones we
671 * should forcibly unmount.
673 remote_fstypes = get_remote_fstypes(zlogp);
674 for (; /* ever */; ) {
675 uint_t newcount = 0;
676 boolean_t unmounted;
677 struct mnttab *mnp;
678 char *path;
679 uint_t i;
681 mnts = NULL;
682 nmnt = 0;
684 * MNTTAB gives us a way to walk through mounted
685 * filesystems; we need to be able to walk them in
686 * reverse order, so we build a list of all mounted
687 * filesystems.
689 if (build_mnttable(zlogp, zroot, zrootlen, mnttab, &mnts,
690 &nmnt) != 0) {
691 error++;
692 goto out;
694 for (i = 0; i < nmnt; i++) {
695 mnp = &mnts[nmnt - i - 1]; /* access in reverse order */
696 path = mnp->mnt_mountp;
697 unmounted = B_FALSE;
699 * Try forced unmount first for remote filesystems.
701 * Not all remote filesystems support forced unmounts,
702 * so if this fails (ENOTSUP) we'll continue on
703 * and try a regular unmount.
705 if (is_remote_fstype(mnp->mnt_fstype, remote_fstypes)) {
706 if (umount2(path, MS_FORCE) == 0)
707 unmounted = B_TRUE;
710 * Try forced unmount if we're stuck.
712 if (stuck) {
713 if (umount2(path, MS_FORCE) == 0) {
714 unmounted = B_TRUE;
715 stuck = B_FALSE;
716 } else {
718 * The first failure indicates a
719 * mount we won't be able to get
720 * rid of automatically, so we
721 * bail.
723 error++;
724 zerror(zlogp, B_FALSE,
725 "unable to unmount '%s'", path);
726 free_mnttable(mnts, nmnt);
727 goto out;
731 * Try regular unmounts for everything else.
733 if (!unmounted && umount2(path, 0) != 0)
734 newcount++;
736 free_mnttable(mnts, nmnt);
738 if (newcount == 0)
739 break;
740 if (newcount >= oldcount) {
742 * Last round didn't unmount anything; we're stuck and
743 * should start trying forced unmounts.
745 stuck = B_TRUE;
747 oldcount = newcount;
750 * Autofs doesn't let you unmount its trigger nodes from
751 * userland so we have to tell the kernel to cleanup for us.
753 if (autofs_cleanup(zoneid) != 0) {
754 zerror(zlogp, B_TRUE, "unable to remove autofs nodes");
755 error++;
756 goto out;
760 out:
761 free_remote_fstypes(remote_fstypes);
762 (void) fclose(mnttab);
763 return (error ? -1 : 0);
766 static int
767 fs_compare(const void *m1, const void *m2)
769 struct zone_fstab *i = (struct zone_fstab *)m1;
770 struct zone_fstab *j = (struct zone_fstab *)m2;
772 return (strcmp(i->zone_fs_dir, j->zone_fs_dir));
776 * Fork and exec (and wait for) the mentioned binary with the provided
777 * arguments. Returns (-1) if something went wrong with fork(2) or exec(2),
778 * returns the exit status otherwise.
780 * If we were unable to exec the provided pathname (for whatever
781 * reason), we return the special token ZEXIT_EXEC. The current value
782 * of ZEXIT_EXEC doesn't conflict with legitimate exit codes of the
783 * consumers of this function; any future consumers must make sure this
784 * remains the case.
786 static int
787 forkexec(zlog_t *zlogp, const char *path, char *const argv[])
789 pid_t child_pid;
790 int child_status = 0;
793 * Do not let another thread localize a message while we are forking.
795 (void) mutex_lock(&msglock);
796 child_pid = fork();
797 (void) mutex_unlock(&msglock);
798 if (child_pid == -1) {
799 zerror(zlogp, B_TRUE, "could not fork for %s", argv[0]);
800 return (-1);
801 } else if (child_pid == 0) {
802 closefrom(0);
803 /* redirect stdin, stdout & stderr to /dev/null */
804 (void) open("/dev/null", O_RDONLY); /* stdin */
805 (void) open("/dev/null", O_WRONLY); /* stdout */
806 (void) open("/dev/null", O_WRONLY); /* stderr */
807 (void) execv(path, argv);
809 * Since we are in the child, there is no point calling zerror()
810 * since there is nobody waiting to consume it. So exit with a
811 * special code that the parent will recognize and call zerror()
812 * accordingly.
815 _exit(ZEXIT_EXEC);
816 } else {
817 (void) waitpid(child_pid, &child_status, 0);
820 if (WIFSIGNALED(child_status)) {
821 zerror(zlogp, B_FALSE, "%s unexpectedly terminated due to "
822 "signal %d", path, WTERMSIG(child_status));
823 return (-1);
825 assert(WIFEXITED(child_status));
826 if (WEXITSTATUS(child_status) == ZEXIT_EXEC) {
827 zerror(zlogp, B_FALSE, "failed to exec %s", path);
828 return (-1);
830 return (WEXITSTATUS(child_status));
833 static int
834 isregfile(const char *path)
836 struct stat64 st;
838 if (stat64(path, &st) == -1)
839 return (-1);
841 return (S_ISREG(st.st_mode));
844 static int
845 dofsck(zlog_t *zlogp, const char *fstype, const char *rawdev)
847 char cmdbuf[MAXPATHLEN];
848 char *argv[5];
849 int status;
852 * We could alternatively have called /usr/sbin/fsck -F <fstype>, but
853 * that would cost us an extra fork/exec without buying us anything.
855 if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck", fstype)
856 >= sizeof (cmdbuf)) {
857 zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
858 return (-1);
862 * If it doesn't exist, that's OK: we verified this previously
863 * in zoneadm.
865 if (isregfile(cmdbuf) == -1)
866 return (0);
868 argv[0] = "fsck";
869 argv[1] = "-o";
870 argv[2] = "p";
871 argv[3] = (char *)rawdev;
872 argv[4] = NULL;
874 status = forkexec(zlogp, cmdbuf, argv);
875 if (status == 0 || status == -1)
876 return (status);
877 zerror(zlogp, B_FALSE, "fsck of '%s' failed with exit status %d; "
878 "run fsck manually", rawdev, status);
879 return (-1);
882 static int
883 domount(zlog_t *zlogp, const char *fstype, const char *opts,
884 const char *special, const char *directory)
886 char cmdbuf[MAXPATHLEN];
887 char *argv[6];
888 int status;
891 * We could alternatively have called /usr/sbin/mount -F <fstype>, but
892 * that would cost us an extra fork/exec without buying us anything.
894 if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount", fstype)
895 >= sizeof (cmdbuf)) {
896 zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
897 return (-1);
899 argv[0] = "mount";
900 if (opts[0] == '\0') {
901 argv[1] = (char *)special;
902 argv[2] = (char *)directory;
903 argv[3] = NULL;
904 } else {
905 argv[1] = "-o";
906 argv[2] = (char *)opts;
907 argv[3] = (char *)special;
908 argv[4] = (char *)directory;
909 argv[5] = NULL;
912 status = forkexec(zlogp, cmdbuf, argv);
913 if (status == 0 || status == -1)
914 return (status);
915 if (opts[0] == '\0')
916 zerror(zlogp, B_FALSE, "\"%s %s %s\" "
917 "failed with exit code %d",
918 cmdbuf, special, directory, status);
919 else
920 zerror(zlogp, B_FALSE, "\"%s -o %s %s %s\" "
921 "failed with exit code %d",
922 cmdbuf, opts, special, directory, status);
923 return (-1);
927 * Check if a given mount point path exists.
928 * If it does, make sure it doesn't contain any symlinks.
929 * Note that if "leaf" is false we're checking an intermediate
930 * component of the mount point path, so it must be a directory.
931 * If "leaf" is true, then we're checking the entire mount point
932 * path, so the mount point itself can be anything aside from a
933 * symbolic link.
935 * If the path is invalid then a negative value is returned. If the
936 * path exists and is a valid mount point path then 0 is returned.
937 * If the path doesn't exist return a positive value.
939 static int
940 valid_mount_point(zlog_t *zlogp, const char *path, const boolean_t leaf)
942 struct stat statbuf;
943 char respath[MAXPATHLEN];
944 int res;
946 if (lstat(path, &statbuf) != 0) {
947 if (errno == ENOENT)
948 return (1);
949 zerror(zlogp, B_TRUE, "can't stat %s", path);
950 return (-1);
952 if (S_ISLNK(statbuf.st_mode)) {
953 zerror(zlogp, B_FALSE, "%s is a symlink", path);
954 return (-1);
956 if (!leaf && !S_ISDIR(statbuf.st_mode)) {
957 zerror(zlogp, B_FALSE, "%s is not a directory", path);
958 return (-1);
960 if ((res = resolvepath(path, respath, sizeof (respath))) == -1) {
961 zerror(zlogp, B_TRUE, "unable to resolve path %s", path);
962 return (-1);
964 respath[res] = '\0';
965 if (strcmp(path, respath) != 0) {
967 * We don't like ".."s, "."s, or "//"s throwing us off
969 zerror(zlogp, B_FALSE, "%s is not a canonical path", path);
970 return (-1);
972 return (0);
976 * Validate a mount point path. A valid mount point path is an
977 * absolute path that either doesn't exist, or, if it does exists it
978 * must be an absolute canonical path that doesn't have any symbolic
979 * links in it. The target of a mount point path can be any filesystem
980 * object. (Different filesystems can support different mount points,
981 * for example "lofs" and "mntfs" both support files and directories
982 * while "ufs" just supports directories.)
984 * If the path is invalid then a negative value is returned. If the
985 * path exists and is a valid mount point path then 0 is returned.
986 * If the path doesn't exist return a positive value.
989 valid_mount_path(zlog_t *zlogp, const char *rootpath, const char *spec,
990 const char *dir, const char *fstype)
992 char abspath[MAXPATHLEN], *slashp, *slashp_next;
993 int rv;
996 * Sanity check the target mount point path.
997 * It must be a non-null string that starts with a '/'.
999 if (dir[0] != '/') {
1000 /* Something went wrong. */
1001 zerror(zlogp, B_FALSE, "invalid mount directory, "
1002 "type: \"%s\", special: \"%s\", dir: \"%s\"",
1003 fstype, spec, dir);
1004 return (-1);
1008 * Join rootpath and dir. Make sure abspath ends with '/', this
1009 * is added to all paths (even non-directory paths) to allow us
1010 * to detect the end of paths below. If the path already ends
1011 * in a '/', then that's ok too (although we'll fail the
1012 * cannonical path check in valid_mount_point()).
1014 if (snprintf(abspath, sizeof (abspath),
1015 "%s%s/", rootpath, dir) >= sizeof (abspath)) {
1016 zerror(zlogp, B_FALSE, "pathname %s%s is too long",
1017 rootpath, dir);
1018 return (-1);
1022 * Starting with rootpath, verify the mount path one component
1023 * at a time. Continue until we've evaluated all of abspath.
1025 slashp = &abspath[strlen(rootpath)];
1026 assert(*slashp == '/');
1027 do {
1028 slashp_next = strchr(slashp + 1, '/');
1029 *slashp = '\0';
1030 if (slashp_next != NULL) {
1031 /* This is an intermediary mount path component. */
1032 rv = valid_mount_point(zlogp, abspath, B_FALSE);
1033 } else {
1034 /* This is the last component of the mount path. */
1035 rv = valid_mount_point(zlogp, abspath, B_TRUE);
1037 if (rv < 0)
1038 return (rv);
1039 *slashp = '/';
1040 } while ((slashp = slashp_next) != NULL);
1041 return (rv);
1044 static int
1045 mount_one_dev_device_cb(void *arg, const char *match, const char *name)
1047 di_prof_t prof = arg;
1049 if (name == NULL)
1050 return (di_prof_add_dev(prof, match));
1051 return (di_prof_add_map(prof, match, name));
1054 static int
1055 mount_one_dev_symlink_cb(void *arg, const char *source, const char *target)
1057 di_prof_t prof = arg;
1059 return (di_prof_add_symlink(prof, source, target));
1063 vplat_get_iptype(zlog_t *zlogp, zone_iptype_t *iptypep)
1065 zone_dochandle_t handle;
1067 if ((handle = zonecfg_init_handle()) == NULL) {
1068 zerror(zlogp, B_TRUE, "getting zone configuration handle");
1069 return (-1);
1071 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
1072 zerror(zlogp, B_FALSE, "invalid configuration");
1073 zonecfg_fini_handle(handle);
1074 return (-1);
1076 if (zonecfg_get_iptype(handle, iptypep) != Z_OK) {
1077 zerror(zlogp, B_FALSE, "invalid ip-type configuration");
1078 zonecfg_fini_handle(handle);
1079 return (-1);
1081 zonecfg_fini_handle(handle);
1082 return (0);
1086 * Apply the standard lists of devices/symlinks/mappings and the user-specified
1087 * list of devices (via zonecfg) to the /dev filesystem. The filesystem will
1088 * use these as a profile/filter to determine what exists in /dev.
1090 static int
1091 mount_one_dev(zlog_t *zlogp, char *devpath, zone_mnt_t mount_cmd)
1093 char brand[MAXNAMELEN];
1094 zone_dochandle_t handle = NULL;
1095 brand_handle_t bh = NULL;
1096 struct zone_devtab ztab;
1097 di_prof_t prof = NULL;
1098 int err;
1099 int retval = -1;
1100 zone_iptype_t iptype;
1101 const char *curr_iptype;
1103 if (di_prof_init(devpath, &prof)) {
1104 zerror(zlogp, B_TRUE, "failed to initialize profile");
1105 goto cleanup;
1109 * Get a handle to the brand info for this zone.
1110 * If we are mounting the zone, then we must always use the default
1111 * brand device mounts.
1113 if (ALT_MOUNT(mount_cmd)) {
1114 (void) strlcpy(brand, default_brand, sizeof (brand));
1115 } else {
1116 (void) strlcpy(brand, brand_name, sizeof (brand));
1119 if ((bh = brand_open(brand)) == NULL) {
1120 zerror(zlogp, B_FALSE, "unable to determine zone brand");
1121 goto cleanup;
1124 if (vplat_get_iptype(zlogp, &iptype) < 0) {
1125 zerror(zlogp, B_TRUE, "unable to determine ip-type");
1126 goto cleanup;
1128 switch (iptype) {
1129 case ZS_SHARED:
1130 curr_iptype = "shared";
1131 break;
1132 case ZS_EXCLUSIVE:
1133 curr_iptype = "exclusive";
1134 break;
1137 if (brand_platform_iter_devices(bh, zone_name,
1138 mount_one_dev_device_cb, prof, curr_iptype) != 0) {
1139 zerror(zlogp, B_TRUE, "failed to add standard device");
1140 goto cleanup;
1143 if (brand_platform_iter_link(bh,
1144 mount_one_dev_symlink_cb, prof) != 0) {
1145 zerror(zlogp, B_TRUE, "failed to add standard symlink");
1146 goto cleanup;
1149 /* Add user-specified devices and directories */
1150 if ((handle = zonecfg_init_handle()) == NULL) {
1151 zerror(zlogp, B_FALSE, "can't initialize zone handle");
1152 goto cleanup;
1154 if (err = zonecfg_get_handle(zone_name, handle)) {
1155 zerror(zlogp, B_FALSE, "can't get handle for zone "
1156 "%s: %s", zone_name, zonecfg_strerror(err));
1157 goto cleanup;
1159 if (err = zonecfg_setdevent(handle)) {
1160 zerror(zlogp, B_FALSE, "%s: %s", zone_name,
1161 zonecfg_strerror(err));
1162 goto cleanup;
1164 while (zonecfg_getdevent(handle, &ztab) == Z_OK) {
1165 if (di_prof_add_dev(prof, ztab.zone_dev_match)) {
1166 zerror(zlogp, B_TRUE, "failed to add "
1167 "user-specified device");
1168 goto cleanup;
1171 (void) zonecfg_enddevent(handle);
1173 /* Send profile to kernel */
1174 if (di_prof_commit(prof)) {
1175 zerror(zlogp, B_TRUE, "failed to commit profile");
1176 goto cleanup;
1179 retval = 0;
1181 cleanup:
1182 if (bh != NULL)
1183 brand_close(bh);
1184 if (handle != NULL)
1185 zonecfg_fini_handle(handle);
1186 if (prof)
1187 di_prof_fini(prof);
1188 return (retval);
1191 static int
1192 mount_one(zlog_t *zlogp, struct zone_fstab *fsptr, const char *rootpath,
1193 zone_mnt_t mount_cmd)
1195 char path[MAXPATHLEN];
1196 char optstr[MAX_MNTOPT_STR];
1197 zone_fsopt_t *optptr;
1198 int rv;
1200 if ((rv = valid_mount_path(zlogp, rootpath, fsptr->zone_fs_special,
1201 fsptr->zone_fs_dir, fsptr->zone_fs_type)) < 0) {
1202 zerror(zlogp, B_FALSE, "%s%s is not a valid mount point",
1203 rootpath, fsptr->zone_fs_dir);
1204 return (-1);
1205 } else if (rv > 0) {
1206 /* The mount point path doesn't exist, create it now. */
1207 if (make_one_dir(zlogp, rootpath, fsptr->zone_fs_dir,
1208 DEFAULT_DIR_MODE, DEFAULT_DIR_USER,
1209 DEFAULT_DIR_GROUP) != 0) {
1210 zerror(zlogp, B_FALSE, "failed to create mount point");
1211 return (-1);
1215 * Now this might seem weird, but we need to invoke
1216 * valid_mount_path() again. Why? Because it checks
1217 * to make sure that the mount point path is canonical,
1218 * which it can only do if the path exists, so now that
1219 * we've created the path we have to verify it again.
1221 if ((rv = valid_mount_path(zlogp, rootpath,
1222 fsptr->zone_fs_special, fsptr->zone_fs_dir,
1223 fsptr->zone_fs_type)) < 0) {
1224 zerror(zlogp, B_FALSE,
1225 "%s%s is not a valid mount point",
1226 rootpath, fsptr->zone_fs_dir);
1227 return (-1);
1231 (void) snprintf(path, sizeof (path), "%s%s", rootpath,
1232 fsptr->zone_fs_dir);
1235 * In general the strategy here is to do just as much verification as
1236 * necessary to avoid crashing or otherwise doing something bad; if the
1237 * administrator initiated the operation via zoneadm(1m), he'll get
1238 * auto-verification which will let him know what's wrong. If he
1239 * modifies the zone configuration of a running zone and doesn't attempt
1240 * to verify that it's OK we won't crash but won't bother trying to be
1241 * too helpful either. zoneadm verify is only a couple keystrokes away.
1243 if (!zonecfg_valid_fs_type(fsptr->zone_fs_type)) {
1244 zerror(zlogp, B_FALSE, "cannot mount %s on %s: "
1245 "invalid file-system type %s", fsptr->zone_fs_special,
1246 fsptr->zone_fs_dir, fsptr->zone_fs_type);
1247 return (-1);
1251 * If we're looking at an alternate root environment, then construct
1252 * read-only loopback mounts as necessary. Note that any special
1253 * paths for lofs zone mounts in an alternate root must have
1254 * already been pre-pended with any alternate root path by the
1255 * time we get here.
1257 if (zonecfg_in_alt_root()) {
1258 struct stat64 st;
1260 if (stat64(fsptr->zone_fs_special, &st) != -1 &&
1261 S_ISBLK(st.st_mode)) {
1263 * If we're going to mount a block device we need
1264 * to check if that device is already mounted
1265 * somewhere else, and if so, do a lofs mount
1266 * of the device instead of a direct mount
1268 if (check_lofs_needed(zlogp, fsptr) == -1)
1269 return (-1);
1270 } else if (strcmp(fsptr->zone_fs_type, MNTTYPE_LOFS) == 0) {
1272 * For lofs mounts, the special node is inside the
1273 * alternate root. We need lofs resolution for
1274 * this case in order to get at the underlying
1275 * read-write path.
1277 resolve_lofs(zlogp, fsptr->zone_fs_special,
1278 sizeof (fsptr->zone_fs_special));
1283 * Run 'fsck -m' if there's a device to fsck.
1285 if (fsptr->zone_fs_raw[0] != '\0' &&
1286 dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_raw) != 0) {
1287 return (-1);
1288 } else if (isregfile(fsptr->zone_fs_special) == 1 &&
1289 dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_special) != 0) {
1290 return (-1);
1294 * Build up mount option string.
1296 optstr[0] = '\0';
1297 if (fsptr->zone_fs_options != NULL) {
1298 (void) strlcpy(optstr, fsptr->zone_fs_options->zone_fsopt_opt,
1299 sizeof (optstr));
1300 for (optptr = fsptr->zone_fs_options->zone_fsopt_next;
1301 optptr != NULL; optptr = optptr->zone_fsopt_next) {
1302 (void) strlcat(optstr, ",", sizeof (optstr));
1303 (void) strlcat(optstr, optptr->zone_fsopt_opt,
1304 sizeof (optstr));
1308 if ((rv = domount(zlogp, fsptr->zone_fs_type, optstr,
1309 fsptr->zone_fs_special, path)) != 0)
1310 return (rv);
1313 * The mount succeeded. If this was not a mount of /dev then
1314 * we're done.
1316 if (strcmp(fsptr->zone_fs_type, MNTTYPE_DEV) != 0)
1317 return (0);
1320 * We just mounted an instance of a /dev filesystem, so now we
1321 * need to configure it.
1323 return (mount_one_dev(zlogp, path, mount_cmd));
1326 static void
1327 free_fs_data(struct zone_fstab *fsarray, uint_t nelem)
1329 uint_t i;
1331 if (fsarray == NULL)
1332 return;
1333 for (i = 0; i < nelem; i++)
1334 zonecfg_free_fs_option_list(fsarray[i].zone_fs_options);
1335 free(fsarray);
1339 * This function initiates the creation of a small Solaris Environment for
1340 * scratch zone. The Environment creation process is split up into two
1341 * functions(build_mounted_pre_var() and build_mounted_post_var()). It
1342 * is done this way because:
1343 * We need to have both /etc and /var in the root of the scratchzone.
1344 * We loopback mount zone's own /etc and /var into the root of the
1345 * scratch zone. Unlike /etc, /var can be a seperate filesystem. So we
1346 * need to delay the mount of /var till the zone's root gets populated.
1347 * So mounting of localdirs[](/etc and /var) have been moved to the
1348 * build_mounted_post_var() which gets called only after the zone
1349 * specific filesystems are mounted.
1351 * Note that the scratch zone we set up for updating the zone (Z_MNT_UPDATE)
1352 * does not loopback mount the zone's own /etc and /var into the root of the
1353 * scratch zone.
1355 static boolean_t
1356 build_mounted_pre_var(zlog_t *zlogp, char *rootpath,
1357 size_t rootlen, const char *zonepath, char *luroot, size_t lurootlen)
1359 char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1360 const char **cpp;
1361 static const char *mkdirs[] = {
1362 "/system", "/system/contract", "/system/object", "/proc",
1363 "/dev", "/tmp", "/a", NULL
1365 char *altstr;
1366 FILE *fp;
1367 uuid_t uuid;
1369 resolve_lofs(zlogp, rootpath, rootlen);
1370 (void) snprintf(luroot, lurootlen, "%s/lu", zonepath);
1371 resolve_lofs(zlogp, luroot, lurootlen);
1372 (void) snprintf(tmp, sizeof (tmp), "%s/bin", luroot);
1373 (void) symlink("./usr/bin", tmp);
1376 * These are mostly special mount points; not handled here. (See
1377 * zone_mount_early.)
1379 for (cpp = mkdirs; *cpp != NULL; cpp++) {
1380 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1381 if (mkdir(tmp, 0755) != 0) {
1382 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1383 return (B_FALSE);
1387 * This is here to support lucopy. If there's an instance of this same
1388 * zone on the current running system, then we mount its root up as
1389 * read-only inside the scratch zone.
1391 (void) zonecfg_get_uuid(zone_name, uuid);
1392 altstr = strdup(zonecfg_get_root());
1393 if (altstr == NULL) {
1394 zerror(zlogp, B_TRUE, "memory allocation failed");
1395 return (B_FALSE);
1397 zonecfg_set_root("");
1398 (void) strlcpy(tmp, zone_name, sizeof (tmp));
1399 (void) zonecfg_get_name_by_uuid(uuid, tmp, sizeof (tmp));
1400 if (zone_get_rootpath(tmp, fromdir, sizeof (fromdir)) == Z_OK &&
1401 strcmp(fromdir, rootpath) != 0) {
1402 (void) snprintf(tmp, sizeof (tmp), "%s/b", luroot);
1403 if (mkdir(tmp, 0755) != 0) {
1404 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1405 return (B_FALSE);
1407 if (domount(zlogp, MNTTYPE_LOFS, RESOURCE_DEFAULT_OPTS, fromdir,
1408 tmp) != 0) {
1409 zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1410 fromdir);
1411 return (B_FALSE);
1414 zonecfg_set_root(altstr);
1415 free(altstr);
1417 if ((fp = zonecfg_open_scratch(luroot, B_TRUE)) == NULL) {
1418 zerror(zlogp, B_TRUE, "cannot open zone mapfile");
1419 return (B_FALSE);
1421 (void) ftruncate(fileno(fp), 0);
1422 if (zonecfg_add_scratch(fp, zone_name, kernzone, "/") == -1) {
1423 zerror(zlogp, B_TRUE, "cannot add zone mapfile entry");
1425 zonecfg_close_scratch(fp);
1426 (void) snprintf(tmp, sizeof (tmp), "%s/a", luroot);
1427 if (domount(zlogp, MNTTYPE_LOFS, "", rootpath, tmp) != 0)
1428 return (B_FALSE);
1429 (void) strlcpy(rootpath, tmp, rootlen);
1430 return (B_TRUE);
1434 static boolean_t
1435 build_mounted_post_var(zlog_t *zlogp, zone_mnt_t mount_cmd, char *rootpath,
1436 const char *luroot)
1438 char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1439 const char **cpp;
1440 const char **loopdirs;
1441 const char **tmpdirs;
1442 static const char *localdirs[] = {
1443 "/etc", "/var", NULL
1445 static const char *scr_loopdirs[] = {
1446 "/etc/lib", "/etc/fs", "/lib", "/sbin", "/platform",
1447 "/usr", NULL
1449 static const char *upd_loopdirs[] = {
1450 "/etc", "/kernel", "/lib", "/opt", "/platform", "/sbin",
1451 "/usr", "/var", NULL
1453 static const char *scr_tmpdirs[] = {
1454 "/tmp", "/var/run", NULL
1456 static const char *upd_tmpdirs[] = {
1457 "/tmp", "/var/run", "/var/tmp", NULL
1459 struct stat st;
1461 if (mount_cmd == Z_MNT_SCRATCH) {
1463 * These are mounted read-write from the zone undergoing
1464 * upgrade. We must be careful not to 'leak' things from the
1465 * main system into the zone, and this accomplishes that goal.
1467 for (cpp = localdirs; *cpp != NULL; cpp++) {
1468 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot,
1469 *cpp);
1470 (void) snprintf(fromdir, sizeof (fromdir), "%s%s",
1471 rootpath, *cpp);
1472 if (mkdir(tmp, 0755) != 0) {
1473 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1474 return (B_FALSE);
1476 if (domount(zlogp, MNTTYPE_LOFS, "", fromdir, tmp)
1477 != 0) {
1478 zerror(zlogp, B_TRUE, "cannot mount %s on %s",
1479 tmp, *cpp);
1480 return (B_FALSE);
1485 if (mount_cmd == Z_MNT_UPDATE)
1486 loopdirs = upd_loopdirs;
1487 else
1488 loopdirs = scr_loopdirs;
1491 * These are things mounted read-only from the running system because
1492 * they contain binaries that must match system.
1494 for (cpp = loopdirs; *cpp != NULL; cpp++) {
1495 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1496 if (mkdir(tmp, 0755) != 0) {
1497 if (errno != EEXIST) {
1498 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1499 return (B_FALSE);
1501 if (lstat(tmp, &st) != 0) {
1502 zerror(zlogp, B_TRUE, "cannot stat %s", tmp);
1503 return (B_FALSE);
1506 * Ignore any non-directories encountered. These are
1507 * things that have been converted into symlinks
1508 * (/etc/fs and /etc/lib) and no longer need a lofs
1509 * fixup.
1511 if (!S_ISDIR(st.st_mode))
1512 continue;
1514 if (domount(zlogp, MNTTYPE_LOFS, RESOURCE_DEFAULT_OPTS, *cpp,
1515 tmp) != 0) {
1516 zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1517 *cpp);
1518 return (B_FALSE);
1522 if (mount_cmd == Z_MNT_UPDATE)
1523 tmpdirs = upd_tmpdirs;
1524 else
1525 tmpdirs = scr_tmpdirs;
1528 * These are things with tmpfs mounted inside.
1530 for (cpp = tmpdirs; *cpp != NULL; cpp++) {
1531 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1532 if (mount_cmd == Z_MNT_SCRATCH && mkdir(tmp, 0755) != 0 &&
1533 errno != EEXIST) {
1534 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1535 return (B_FALSE);
1539 * We could set the mode for /tmp when we do the mkdir but
1540 * since that can be modified by the umask we will just set
1541 * the correct mode for /tmp now.
1543 if (strcmp(*cpp, "/tmp") == 0 && chmod(tmp, 01777) != 0) {
1544 zerror(zlogp, B_TRUE, "cannot chmod %s", tmp);
1545 return (B_FALSE);
1548 if (domount(zlogp, MNTTYPE_TMPFS, "", "swap", tmp) != 0) {
1549 zerror(zlogp, B_TRUE, "cannot mount swap on %s", *cpp);
1550 return (B_FALSE);
1553 return (B_TRUE);
1556 typedef struct plat_gmount_cb_data {
1557 zlog_t *pgcd_zlogp;
1558 struct zone_fstab **pgcd_fs_tab;
1559 int *pgcd_num_fs;
1560 } plat_gmount_cb_data_t;
1563 * plat_gmount_cb() is a callback function invoked by libbrand to iterate
1564 * through all global brand platform mounts.
1567 plat_gmount_cb(void *data, const char *spec, const char *dir,
1568 const char *fstype, const char *opt)
1570 plat_gmount_cb_data_t *cp = data;
1571 zlog_t *zlogp = cp->pgcd_zlogp;
1572 struct zone_fstab *fs_ptr = *cp->pgcd_fs_tab;
1573 int num_fs = *cp->pgcd_num_fs;
1574 struct zone_fstab *fsp, *tmp_ptr;
1576 num_fs++;
1577 if ((tmp_ptr = realloc(fs_ptr, num_fs * sizeof (*tmp_ptr))) == NULL) {
1578 zerror(zlogp, B_TRUE, "memory allocation failed");
1579 return (-1);
1582 fs_ptr = tmp_ptr;
1583 fsp = &fs_ptr[num_fs - 1];
1585 /* update the callback struct passed in */
1586 *cp->pgcd_fs_tab = fs_ptr;
1587 *cp->pgcd_num_fs = num_fs;
1589 fsp->zone_fs_raw[0] = '\0';
1590 (void) strlcpy(fsp->zone_fs_special, spec,
1591 sizeof (fsp->zone_fs_special));
1592 (void) strlcpy(fsp->zone_fs_dir, dir, sizeof (fsp->zone_fs_dir));
1593 (void) strlcpy(fsp->zone_fs_type, fstype, sizeof (fsp->zone_fs_type));
1594 fsp->zone_fs_options = NULL;
1595 if ((opt != NULL) &&
1596 (zonecfg_add_fs_option(fsp, (char *)opt) != Z_OK)) {
1597 zerror(zlogp, B_FALSE, "error adding property");
1598 return (-1);
1601 return (0);
1604 static int
1605 mount_filesystems_fsent(zone_dochandle_t handle, zlog_t *zlogp,
1606 struct zone_fstab **fs_tabp, int *num_fsp, zone_mnt_t mount_cmd)
1608 struct zone_fstab *tmp_ptr, *fs_ptr, *fsp, fstab;
1609 int num_fs;
1611 num_fs = *num_fsp;
1612 fs_ptr = *fs_tabp;
1614 if (zonecfg_setfsent(handle) != Z_OK) {
1615 zerror(zlogp, B_FALSE, "invalid configuration");
1616 return (-1);
1618 while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1620 * ZFS filesystems will not be accessible under an alternate
1621 * root, since the pool will not be known. Ignore them in this
1622 * case.
1624 if (ALT_MOUNT(mount_cmd) &&
1625 strcmp(fstab.zone_fs_type, MNTTYPE_ZFS) == 0)
1626 continue;
1628 num_fs++;
1629 if ((tmp_ptr = realloc(fs_ptr,
1630 num_fs * sizeof (*tmp_ptr))) == NULL) {
1631 zerror(zlogp, B_TRUE, "memory allocation failed");
1632 (void) zonecfg_endfsent(handle);
1633 return (-1);
1635 /* update the pointers passed in */
1636 *fs_tabp = tmp_ptr;
1637 *num_fsp = num_fs;
1639 fs_ptr = tmp_ptr;
1640 fsp = &fs_ptr[num_fs - 1];
1641 (void) strlcpy(fsp->zone_fs_dir,
1642 fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1643 (void) strlcpy(fsp->zone_fs_raw, fstab.zone_fs_raw,
1644 sizeof (fsp->zone_fs_raw));
1645 (void) strlcpy(fsp->zone_fs_type, fstab.zone_fs_type,
1646 sizeof (fsp->zone_fs_type));
1647 fsp->zone_fs_options = fstab.zone_fs_options;
1650 * For all lofs mounts, make sure that the 'special'
1651 * entry points inside the alternate root. The
1652 * source path for a lofs mount in a given zone needs
1653 * to be relative to the root of the boot environment
1654 * that contains the zone. Note that we don't do this
1655 * for non-lofs mounts since they will have a device
1656 * as a backing store and device paths must always be
1657 * specified relative to the current boot environment.
1659 fsp->zone_fs_special[0] = '\0';
1660 if (strcmp(fsp->zone_fs_type, MNTTYPE_LOFS) == 0) {
1661 (void) strlcat(fsp->zone_fs_special, zonecfg_get_root(),
1662 sizeof (fsp->zone_fs_special));
1664 (void) strlcat(fsp->zone_fs_special, fstab.zone_fs_special,
1665 sizeof (fsp->zone_fs_special));
1667 (void) zonecfg_endfsent(handle);
1668 return (0);
1671 static int
1672 mount_filesystems(zlog_t *zlogp, zone_mnt_t mount_cmd)
1674 char rootpath[MAXPATHLEN];
1675 char zonepath[MAXPATHLEN];
1676 char brand[MAXNAMELEN];
1677 char luroot[MAXPATHLEN];
1678 int i, num_fs = 0;
1679 struct zone_fstab *fs_ptr = NULL;
1680 zone_dochandle_t handle = NULL;
1681 zone_state_t zstate;
1682 brand_handle_t bh;
1683 plat_gmount_cb_data_t cb;
1685 if (zone_get_state(zone_name, &zstate) != Z_OK ||
1686 (zstate != ZONE_STATE_READY && zstate != ZONE_STATE_MOUNTED)) {
1687 zerror(zlogp, B_FALSE,
1688 "zone must be in '%s' or '%s' state to mount file-systems",
1689 zone_state_str(ZONE_STATE_READY),
1690 zone_state_str(ZONE_STATE_MOUNTED));
1691 goto bad;
1694 if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
1695 zerror(zlogp, B_TRUE, "unable to determine zone path");
1696 goto bad;
1699 if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
1700 zerror(zlogp, B_TRUE, "unable to determine zone root");
1701 goto bad;
1704 if ((handle = zonecfg_init_handle()) == NULL) {
1705 zerror(zlogp, B_TRUE, "getting zone configuration handle");
1706 goto bad;
1708 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK ||
1709 zonecfg_setfsent(handle) != Z_OK) {
1710 zerror(zlogp, B_FALSE, "invalid configuration");
1711 goto bad;
1715 * If we are mounting the zone, then we must always use the default
1716 * brand global mounts.
1718 if (ALT_MOUNT(mount_cmd)) {
1719 (void) strlcpy(brand, default_brand, sizeof (brand));
1720 } else {
1721 (void) strlcpy(brand, brand_name, sizeof (brand));
1724 /* Get a handle to the brand info for this zone */
1725 if ((bh = brand_open(brand)) == NULL) {
1726 zerror(zlogp, B_FALSE, "unable to determine zone brand");
1727 zonecfg_fini_handle(handle);
1728 return (-1);
1732 * Get the list of global filesystems to mount from the brand
1733 * configuration.
1735 cb.pgcd_zlogp = zlogp;
1736 cb.pgcd_fs_tab = &fs_ptr;
1737 cb.pgcd_num_fs = &num_fs;
1738 if (brand_platform_iter_gmounts(bh, zone_name, zonepath,
1739 plat_gmount_cb, &cb) != 0) {
1740 zerror(zlogp, B_FALSE, "unable to mount filesystems");
1741 brand_close(bh);
1742 zonecfg_fini_handle(handle);
1743 return (-1);
1745 brand_close(bh);
1748 * Iterate through the rest of the filesystems. Sort them all,
1749 * then mount them in sorted order. This is to make sure the
1750 * higher level directories (e.g., /usr) get mounted before
1751 * any beneath them (e.g., /usr/local).
1753 if (mount_filesystems_fsent(handle, zlogp, &fs_ptr, &num_fs,
1754 mount_cmd) != 0)
1755 goto bad;
1757 zonecfg_fini_handle(handle);
1758 handle = NULL;
1761 * Normally when we mount a zone all the zone filesystems
1762 * get mounted relative to rootpath, which is usually
1763 * <zonepath>/root. But when mounting a zone for administration
1764 * purposes via the zone "mount" state, build_mounted_pre_var()
1765 * updates rootpath to be <zonepath>/lu/a so we'll mount all
1766 * the zones filesystems there instead.
1768 * build_mounted_pre_var() and build_mounted_post_var() will
1769 * also do some extra work to create directories and lofs mount
1770 * a bunch of global zone file system paths into <zonepath>/lu.
1772 * This allows us to be able to enter the zone (now rooted at
1773 * <zonepath>/lu) and run the upgrade/patch tools that are in the
1774 * global zone and have them upgrade the to-be-modified zone's
1775 * files mounted on /a. (Which mirrors the existing standard
1776 * upgrade environment.)
1778 * There is of course one catch. When doing the upgrade
1779 * we need <zoneroot>/lu/dev to be the /dev filesystem
1780 * for the zone and we don't want to have any /dev filesystem
1781 * mounted at <zoneroot>/lu/a/dev. Since /dev is specified
1782 * as a normal zone filesystem by default we'll try to mount
1783 * it at <zoneroot>/lu/a/dev, so we have to detect this
1784 * case and instead mount it at <zoneroot>/lu/dev.
1786 * All this work is done in three phases:
1787 * 1) Create and populate lu directory (build_mounted_pre_var()).
1788 * 2) Mount the required filesystems as per the zone configuration.
1789 * 3) Set up the rest of the scratch zone environment
1790 * (build_mounted_post_var()).
1792 if (ALT_MOUNT(mount_cmd) && !build_mounted_pre_var(zlogp,
1793 rootpath, sizeof (rootpath), zonepath, luroot, sizeof (luroot)))
1794 goto bad;
1796 qsort(fs_ptr, num_fs, sizeof (*fs_ptr), fs_compare);
1798 for (i = 0; i < num_fs; i++) {
1799 if (ALT_MOUNT(mount_cmd) &&
1800 strcmp(fs_ptr[i].zone_fs_dir, "/dev") == 0) {
1801 size_t slen = strlen(rootpath) - 2;
1804 * By default we'll try to mount /dev as /a/dev
1805 * but /dev is special and always goes at the top
1806 * so strip the trailing '/a' from the rootpath.
1808 assert(strcmp(&rootpath[slen], "/a") == 0);
1809 rootpath[slen] = '\0';
1810 if (mount_one(zlogp, &fs_ptr[i], rootpath, mount_cmd)
1811 != 0)
1812 goto bad;
1813 rootpath[slen] = '/';
1814 continue;
1816 if (mount_one(zlogp, &fs_ptr[i], rootpath, mount_cmd) != 0)
1817 goto bad;
1819 if (ALT_MOUNT(mount_cmd) &&
1820 !build_mounted_post_var(zlogp, mount_cmd, rootpath, luroot))
1821 goto bad;
1824 * For Trusted Extensions cross-mount each lower level /export/home
1826 if (mount_cmd == Z_MNT_BOOT &&
1827 tsol_mounts(zlogp, zone_name, rootpath) != 0)
1828 goto bad;
1830 free_fs_data(fs_ptr, num_fs);
1833 * Everything looks fine.
1835 return (0);
1837 bad:
1838 if (handle != NULL)
1839 zonecfg_fini_handle(handle);
1840 free_fs_data(fs_ptr, num_fs);
1841 return (-1);
1844 /* caller makes sure neither parameter is NULL */
1845 static int
1846 addr2netmask(char *prefixstr, int maxprefixlen, uchar_t *maskstr)
1848 int prefixlen;
1850 prefixlen = atoi(prefixstr);
1851 if (prefixlen < 0 || prefixlen > maxprefixlen)
1852 return (1);
1853 while (prefixlen > 0) {
1854 if (prefixlen >= 8) {
1855 *maskstr++ = 0xFF;
1856 prefixlen -= 8;
1857 continue;
1859 *maskstr |= 1 << (8 - prefixlen);
1860 prefixlen--;
1862 return (0);
1866 * Tear down all interfaces belonging to the given zone. This should
1867 * be called with the zone in a state other than "running", so that
1868 * interfaces can't be assigned to the zone after this returns.
1870 * If anything goes wrong, log an error message and return an error.
1872 static int
1873 unconfigure_shared_network_interfaces(zlog_t *zlogp, zoneid_t zone_id)
1875 struct lifnum lifn;
1876 struct lifconf lifc;
1877 struct lifreq *lifrp, lifrl;
1878 int64_t lifc_flags = LIFC_NOXMIT | LIFC_ALLZONES;
1879 int num_ifs, s, i, ret_code = 0;
1880 uint_t bufsize;
1881 char *buf = NULL;
1883 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1884 zerror(zlogp, B_TRUE, "could not get socket");
1885 ret_code = -1;
1886 goto bad;
1888 lifn.lifn_family = AF_UNSPEC;
1889 lifn.lifn_flags = (int)lifc_flags;
1890 if (ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) {
1891 zerror(zlogp, B_TRUE,
1892 "could not determine number of network interfaces");
1893 ret_code = -1;
1894 goto bad;
1896 num_ifs = lifn.lifn_count;
1897 bufsize = num_ifs * sizeof (struct lifreq);
1898 if ((buf = malloc(bufsize)) == NULL) {
1899 zerror(zlogp, B_TRUE, "memory allocation failed");
1900 ret_code = -1;
1901 goto bad;
1903 lifc.lifc_family = AF_UNSPEC;
1904 lifc.lifc_flags = (int)lifc_flags;
1905 lifc.lifc_len = bufsize;
1906 lifc.lifc_buf = buf;
1907 if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) {
1908 zerror(zlogp, B_TRUE, "could not get configured network "
1909 "interfaces");
1910 ret_code = -1;
1911 goto bad;
1913 lifrp = lifc.lifc_req;
1914 for (i = lifc.lifc_len / sizeof (struct lifreq); i > 0; i--, lifrp++) {
1915 (void) close(s);
1916 if ((s = socket(lifrp->lifr_addr.ss_family, SOCK_DGRAM, 0)) <
1917 0) {
1918 zerror(zlogp, B_TRUE, "%s: could not get socket",
1919 lifrl.lifr_name);
1920 ret_code = -1;
1921 continue;
1923 (void) memset(&lifrl, 0, sizeof (lifrl));
1924 (void) strncpy(lifrl.lifr_name, lifrp->lifr_name,
1925 sizeof (lifrl.lifr_name));
1926 if (ioctl(s, SIOCGLIFZONE, (caddr_t)&lifrl) < 0) {
1927 if (errno == ENXIO)
1929 * Interface may have been removed by admin or
1930 * another zone halting.
1932 continue;
1933 zerror(zlogp, B_TRUE,
1934 "%s: could not determine the zone to which this "
1935 "network interface is bound", lifrl.lifr_name);
1936 ret_code = -1;
1937 continue;
1939 if (lifrl.lifr_zoneid == zone_id) {
1940 if (ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifrl) < 0) {
1941 zerror(zlogp, B_TRUE,
1942 "%s: could not remove network interface",
1943 lifrl.lifr_name);
1944 ret_code = -1;
1945 continue;
1949 bad:
1950 if (s > 0)
1951 (void) close(s);
1952 free(buf);
1953 return (ret_code);
1956 static union sockunion {
1957 struct sockaddr sa;
1958 struct sockaddr_in sin;
1959 struct sockaddr_dl sdl;
1960 struct sockaddr_in6 sin6;
1961 } so_dst, so_ifp;
1963 static struct {
1964 struct rt_msghdr hdr;
1965 char space[512];
1966 } rtmsg;
1968 static int
1969 salen(struct sockaddr *sa)
1971 switch (sa->sa_family) {
1972 case AF_INET:
1973 return (sizeof (struct sockaddr_in));
1974 case AF_LINK:
1975 return (sizeof (struct sockaddr_dl));
1976 case AF_INET6:
1977 return (sizeof (struct sockaddr_in6));
1978 default:
1979 return (sizeof (struct sockaddr));
1983 #define ROUNDUP_LONG(a) \
1984 ((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
1987 * Look up which zone is using a given IP address. The address in question
1988 * is expected to have been stuffed into the structure to which lifr points
1989 * via a previous SIOCGLIFADDR ioctl().
1991 * This is done using black router socket magic.
1993 * Return the name of the zone on success or NULL on failure.
1995 * This is a lot of code for a simple task; a new ioctl request to take care
1996 * of this might be a useful RFE.
1999 static char *
2000 who_is_using(zlog_t *zlogp, struct lifreq *lifr)
2002 static char answer[ZONENAME_MAX];
2003 pid_t pid;
2004 int s, rlen, l, i;
2005 char *cp = rtmsg.space;
2006 struct sockaddr_dl *ifp = NULL;
2007 struct sockaddr *sa;
2008 char save_if_name[LIFNAMSIZ];
2010 answer[0] = '\0';
2012 pid = getpid();
2013 if ((s = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
2014 zerror(zlogp, B_TRUE, "could not get routing socket");
2015 return (NULL);
2018 if (lifr->lifr_addr.ss_family == AF_INET) {
2019 struct sockaddr_in *sin4;
2021 so_dst.sa.sa_family = AF_INET;
2022 sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
2023 so_dst.sin.sin_addr = sin4->sin_addr;
2024 } else {
2025 struct sockaddr_in6 *sin6;
2027 so_dst.sa.sa_family = AF_INET6;
2028 sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
2029 so_dst.sin6.sin6_addr = sin6->sin6_addr;
2032 so_ifp.sa.sa_family = AF_LINK;
2034 (void) memset(&rtmsg, 0, sizeof (rtmsg));
2035 rtmsg.hdr.rtm_type = RTM_GET;
2036 rtmsg.hdr.rtm_flags = RTF_UP | RTF_HOST;
2037 rtmsg.hdr.rtm_version = RTM_VERSION;
2038 rtmsg.hdr.rtm_seq = ++rts_seqno;
2039 rtmsg.hdr.rtm_addrs = RTA_IFP | RTA_DST;
2041 l = ROUNDUP_LONG(salen(&so_dst.sa));
2042 (void) memmove(cp, &(so_dst), l);
2043 cp += l;
2044 l = ROUNDUP_LONG(salen(&so_ifp.sa));
2045 (void) memmove(cp, &(so_ifp), l);
2046 cp += l;
2048 rtmsg.hdr.rtm_msglen = l = cp - (char *)&rtmsg;
2050 if ((rlen = write(s, &rtmsg, l)) < 0) {
2051 zerror(zlogp, B_TRUE, "writing to routing socket");
2052 return (NULL);
2053 } else if (rlen < (int)rtmsg.hdr.rtm_msglen) {
2054 zerror(zlogp, B_TRUE,
2055 "write to routing socket got only %d for len\n", rlen);
2056 return (NULL);
2058 do {
2059 l = read(s, &rtmsg, sizeof (rtmsg));
2060 } while (l > 0 && (rtmsg.hdr.rtm_seq != rts_seqno ||
2061 rtmsg.hdr.rtm_pid != pid));
2062 if (l < 0) {
2063 zerror(zlogp, B_TRUE, "reading from routing socket");
2064 return (NULL);
2067 if (rtmsg.hdr.rtm_version != RTM_VERSION) {
2068 zerror(zlogp, B_FALSE,
2069 "routing message version %d not understood",
2070 rtmsg.hdr.rtm_version);
2071 return (NULL);
2073 if (rtmsg.hdr.rtm_msglen != (ushort_t)l) {
2074 zerror(zlogp, B_FALSE, "message length mismatch, "
2075 "expected %d bytes, returned %d bytes",
2076 rtmsg.hdr.rtm_msglen, l);
2077 return (NULL);
2079 if (rtmsg.hdr.rtm_errno != 0) {
2080 errno = rtmsg.hdr.rtm_errno;
2081 zerror(zlogp, B_TRUE, "RTM_GET routing socket message");
2082 return (NULL);
2084 if ((rtmsg.hdr.rtm_addrs & RTA_IFP) == 0) {
2085 zerror(zlogp, B_FALSE, "network interface not found");
2086 return (NULL);
2088 cp = ((char *)(&rtmsg.hdr + 1));
2089 for (i = 1; i != 0; i <<= 1) {
2090 /* LINTED E_BAD_PTR_CAST_ALIGN */
2091 sa = (struct sockaddr *)cp;
2092 if (i != RTA_IFP) {
2093 if ((i & rtmsg.hdr.rtm_addrs) != 0)
2094 cp += ROUNDUP_LONG(salen(sa));
2095 continue;
2097 if (sa->sa_family == AF_LINK &&
2098 ((struct sockaddr_dl *)sa)->sdl_nlen != 0)
2099 ifp = (struct sockaddr_dl *)sa;
2100 break;
2102 if (ifp == NULL) {
2103 zerror(zlogp, B_FALSE, "network interface could not be "
2104 "determined");
2105 return (NULL);
2109 * We need to set the I/F name to what we got above, then do the
2110 * appropriate ioctl to get its zone name. But lifr->lifr_name is
2111 * used by the calling function to do a REMOVEIF, so if we leave the
2112 * "good" zone's I/F name in place, *that* I/F will be removed instead
2113 * of the bad one. So we save the old (bad) I/F name before over-
2114 * writing it and doing the ioctl, then restore it after the ioctl.
2116 (void) strlcpy(save_if_name, lifr->lifr_name, sizeof (save_if_name));
2117 (void) strncpy(lifr->lifr_name, ifp->sdl_data, ifp->sdl_nlen);
2118 lifr->lifr_name[ifp->sdl_nlen] = '\0';
2119 i = ioctl(s, SIOCGLIFZONE, lifr);
2120 (void) strlcpy(lifr->lifr_name, save_if_name, sizeof (save_if_name));
2121 if (i < 0) {
2122 zerror(zlogp, B_TRUE,
2123 "%s: could not determine the zone network interface "
2124 "belongs to", lifr->lifr_name);
2125 return (NULL);
2127 if (getzonenamebyid(lifr->lifr_zoneid, answer, sizeof (answer)) < 0)
2128 (void) snprintf(answer, sizeof (answer), "%d",
2129 lifr->lifr_zoneid);
2131 if (strlen(answer) > 0)
2132 return (answer);
2133 return (NULL);
2137 * Configures a single interface: a new virtual interface is added, based on
2138 * the physical interface nwiftabptr->zone_nwif_physical, with the address
2139 * specified in nwiftabptr->zone_nwif_address, for zone zone_id. Note that
2140 * the "address" can be an IPv6 address (with a /prefixlength required), an
2141 * IPv4 address (with a /prefixlength optional), or a name; for the latter,
2142 * an IPv4 name-to-address resolution will be attempted.
2144 * If anything goes wrong, we log an detailed error message, attempt to tear
2145 * down whatever we set up and return an error.
2147 static int
2148 configure_one_interface(zlog_t *zlogp, zoneid_t zone_id,
2149 struct zone_nwiftab *nwiftabptr)
2151 struct lifreq lifr;
2152 struct sockaddr_in netmask4;
2153 struct sockaddr_in6 netmask6;
2154 struct sockaddr_storage laddr;
2155 struct in_addr in4;
2156 sa_family_t af;
2157 char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
2158 int s;
2159 boolean_t got_netmask = B_FALSE;
2160 boolean_t is_loopback = B_FALSE;
2161 char addrstr4[INET_ADDRSTRLEN];
2162 int res;
2164 res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
2165 if (res != Z_OK) {
2166 zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
2167 nwiftabptr->zone_nwif_address);
2168 return (-1);
2170 af = lifr.lifr_addr.ss_family;
2171 if (af == AF_INET)
2172 in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
2173 if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
2174 zerror(zlogp, B_TRUE, "could not get socket");
2175 return (-1);
2179 * This is a similar kind of "hack" like in addif() to get around
2180 * the problem of SIOCLIFADDIF. The problem is that this ioctl
2181 * does not include the netmask when adding a logical interface.
2182 * To get around this problem, we first add the logical interface
2183 * with a 0 address. After that, we set the netmask if provided.
2184 * Finally we set the interface address.
2186 laddr = lifr.lifr_addr;
2187 (void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
2188 sizeof (lifr.lifr_name));
2189 (void) memset(&lifr.lifr_addr, 0, sizeof (lifr.lifr_addr));
2191 if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
2193 * Here, we know that the interface can't be brought up.
2194 * A similar warning message was already printed out to
2195 * the console by zoneadm(1M) so instead we log the
2196 * message to syslog and continue.
2198 zerror(&logsys, B_TRUE, "WARNING: skipping network interface "
2199 "'%s' which may not be present/plumbed in the "
2200 "global zone.", lifr.lifr_name);
2201 (void) close(s);
2202 return (Z_OK);
2205 /* Preserve literal IPv4 address for later potential printing. */
2206 if (af == AF_INET)
2207 (void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
2209 lifr.lifr_zoneid = zone_id;
2210 if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
2211 zerror(zlogp, B_TRUE, "%s: could not place network interface "
2212 "into zone", lifr.lifr_name);
2213 goto bad;
2217 * Loopback interface will use the default netmask assigned, if no
2218 * netmask is found.
2220 if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
2221 is_loopback = B_TRUE;
2223 if (af == AF_INET) {
2225 * The IPv4 netmask can be determined either
2226 * directly if a prefix length was supplied with
2227 * the address or via the netmasks database. Not
2228 * being able to determine it is a common failure,
2229 * but it often is not fatal to operation of the
2230 * interface. In that case, a warning will be
2231 * printed after the rest of the interface's
2232 * parameters have been configured.
2234 (void) memset(&netmask4, 0, sizeof (netmask4));
2235 if (slashp != NULL) {
2236 if (addr2netmask(slashp + 1, V4_ADDR_LEN,
2237 (uchar_t *)&netmask4.sin_addr) != 0) {
2238 *slashp = '/';
2239 zerror(zlogp, B_FALSE,
2240 "%s: invalid prefix length in %s",
2241 lifr.lifr_name,
2242 nwiftabptr->zone_nwif_address);
2243 goto bad;
2245 got_netmask = B_TRUE;
2246 } else if (getnetmaskbyaddr(in4,
2247 &netmask4.sin_addr) == 0) {
2248 got_netmask = B_TRUE;
2250 if (got_netmask) {
2251 netmask4.sin_family = af;
2252 (void) memcpy(&lifr.lifr_addr, &netmask4,
2253 sizeof (netmask4));
2255 } else {
2256 (void) memset(&netmask6, 0, sizeof (netmask6));
2257 if (addr2netmask(slashp + 1, V6_ADDR_LEN,
2258 (uchar_t *)&netmask6.sin6_addr) != 0) {
2259 *slashp = '/';
2260 zerror(zlogp, B_FALSE,
2261 "%s: invalid prefix length in %s",
2262 lifr.lifr_name,
2263 nwiftabptr->zone_nwif_address);
2264 goto bad;
2266 got_netmask = B_TRUE;
2267 netmask6.sin6_family = af;
2268 (void) memcpy(&lifr.lifr_addr, &netmask6,
2269 sizeof (netmask6));
2271 if (got_netmask &&
2272 ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
2273 zerror(zlogp, B_TRUE, "%s: could not set netmask",
2274 lifr.lifr_name);
2275 goto bad;
2278 /* Set the interface address */
2279 lifr.lifr_addr = laddr;
2280 if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2281 zerror(zlogp, B_TRUE,
2282 "%s: could not set IP address to %s",
2283 lifr.lifr_name, nwiftabptr->zone_nwif_address);
2284 goto bad;
2287 if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2288 zerror(zlogp, B_TRUE, "%s: could not get flags",
2289 lifr.lifr_name);
2290 goto bad;
2292 lifr.lifr_flags |= IFF_UP;
2293 if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
2294 int save_errno = errno;
2295 char *zone_using;
2298 * If we failed with something other than EADDRNOTAVAIL,
2299 * then skip to the end. Otherwise, look up our address,
2300 * then call a function to determine which zone is already
2301 * using that address.
2303 if (errno != EADDRNOTAVAIL) {
2304 zerror(zlogp, B_TRUE,
2305 "%s: could not bring network interface up",
2306 lifr.lifr_name);
2307 goto bad;
2309 if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2310 zerror(zlogp, B_TRUE, "%s: could not get address",
2311 lifr.lifr_name);
2312 goto bad;
2314 zone_using = who_is_using(zlogp, &lifr);
2315 errno = save_errno;
2316 if (zone_using == NULL)
2317 zerror(zlogp, B_TRUE,
2318 "%s: could not bring network interface up",
2319 lifr.lifr_name);
2320 else
2321 zerror(zlogp, B_TRUE, "%s: could not bring network "
2322 "interface up: address in use by zone '%s'",
2323 lifr.lifr_name, zone_using);
2324 goto bad;
2327 if (!got_netmask && !is_loopback) {
2329 * A common, but often non-fatal problem, is that the system
2330 * cannot find the netmask for an interface address. This is
2331 * often caused by it being only in /etc/inet/netmasks, but
2332 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2333 * in that. This doesn't show up at boot because the netmask
2334 * is obtained from /etc/inet/netmasks when no network
2335 * interfaces are up, but isn't consulted when NIS/NIS+ is
2336 * available. We warn the user here that something like this
2337 * has happened and we're just running with a default and
2338 * possible incorrect netmask.
2340 char buffer[INET6_ADDRSTRLEN];
2341 void *addr;
2342 const char *nomatch = "no matching subnet found in netmasks(4)";
2344 if (af == AF_INET)
2345 addr = &((struct sockaddr_in *)
2346 (&lifr.lifr_addr))->sin_addr;
2347 else
2348 addr = &((struct sockaddr_in6 *)
2349 (&lifr.lifr_addr))->sin6_addr;
2352 * Find out what netmask the interface is going to be using.
2353 * If we just brought up an IPMP data address on an underlying
2354 * interface above, the address will have already migrated, so
2355 * the SIOCGLIFNETMASK won't be able to find it (but we need
2356 * to bring the address up to get the actual netmask). Just
2357 * omit printing the actual netmask in this corner-case.
2359 if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2360 inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL) {
2361 zerror(zlogp, B_FALSE, "WARNING: %s; using default.",
2362 nomatch);
2363 } else {
2364 zerror(zlogp, B_FALSE,
2365 "WARNING: %s: %s: %s; using default of %s.",
2366 lifr.lifr_name, nomatch, addrstr4, buffer);
2371 * If a default router was specified for this interface
2372 * set the route now. Ignore if already set.
2374 if (strlen(nwiftabptr->zone_nwif_defrouter) > 0) {
2375 int status;
2376 char *argv[7];
2378 argv[0] = "route";
2379 argv[1] = "add";
2380 argv[2] = "-ifp";
2381 argv[3] = nwiftabptr->zone_nwif_physical;
2382 argv[4] = "default";
2383 argv[5] = nwiftabptr->zone_nwif_defrouter;
2384 argv[6] = NULL;
2386 status = forkexec(zlogp, "/usr/sbin/route", argv);
2387 if (status != 0 && status != EEXIST)
2388 zerror(zlogp, B_FALSE, "Unable to set route for "
2389 "interface %s to %s\n",
2390 nwiftabptr->zone_nwif_physical,
2391 nwiftabptr->zone_nwif_defrouter);
2394 (void) close(s);
2395 return (Z_OK);
2396 bad:
2397 (void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2398 (void) close(s);
2399 return (-1);
2403 * Sets up network interfaces based on information from the zone configuration.
2404 * IPv4 and IPv6 loopback interfaces are set up "for free", modeling the global
2405 * system.
2407 * If anything goes wrong, we log a general error message, attempt to tear down
2408 * whatever we set up, and return an error.
2410 static int
2411 configure_shared_network_interfaces(zlog_t *zlogp)
2413 zone_dochandle_t handle;
2414 struct zone_nwiftab nwiftab, loopback_iftab;
2415 zoneid_t zoneid;
2417 if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2418 zerror(zlogp, B_TRUE, "unable to get zoneid");
2419 return (-1);
2422 if ((handle = zonecfg_init_handle()) == NULL) {
2423 zerror(zlogp, B_TRUE, "getting zone configuration handle");
2424 return (-1);
2426 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2427 zerror(zlogp, B_FALSE, "invalid configuration");
2428 zonecfg_fini_handle(handle);
2429 return (-1);
2431 if (zonecfg_setnwifent(handle) == Z_OK) {
2432 for (;;) {
2433 if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2434 break;
2435 if (configure_one_interface(zlogp, zoneid, &nwiftab) !=
2436 Z_OK) {
2437 (void) zonecfg_endnwifent(handle);
2438 zonecfg_fini_handle(handle);
2439 return (-1);
2442 (void) zonecfg_endnwifent(handle);
2444 zonecfg_fini_handle(handle);
2445 if (is_system_labeled()) {
2447 * Labeled zones share the loopback interface
2448 * so it is not plumbed for shared stack instances.
2450 return (0);
2452 (void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2453 sizeof (loopback_iftab.zone_nwif_physical));
2454 (void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2455 sizeof (loopback_iftab.zone_nwif_address));
2456 loopback_iftab.zone_nwif_defrouter[0] = '\0';
2457 if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2458 return (-1);
2460 /* Always plumb up the IPv6 loopback interface. */
2461 (void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2462 sizeof (loopback_iftab.zone_nwif_address));
2463 if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2464 return (-1);
2465 return (0);
2468 static void
2469 zdlerror(zlog_t *zlogp, dladm_status_t err, const char *dlname, const char *str)
2471 char errmsg[DLADM_STRSIZE];
2473 (void) dladm_status2str(err, errmsg);
2474 zerror(zlogp, B_FALSE, "%s '%s': %s", str, dlname, errmsg);
2477 static int
2478 add_datalink(zlog_t *zlogp, char *zone_name, datalink_id_t linkid, char *dlname)
2480 dladm_status_t err;
2481 boolean_t cpuset, poolset;
2482 char *poolp;
2484 /* First check if it's in use by global zone. */
2485 if (zonecfg_ifname_exists(AF_INET, dlname) ||
2486 zonecfg_ifname_exists(AF_INET6, dlname)) {
2487 zerror(zlogp, B_FALSE, "WARNING: skipping network interface "
2488 "'%s' which is used in the global zone", dlname);
2489 return (-1);
2492 /* Set zoneid of this link. */
2493 err = dladm_set_linkprop(dld_handle, linkid, "zone", &zone_name, 1,
2494 DLADM_OPT_ACTIVE);
2495 if (err != DLADM_STATUS_OK) {
2496 zdlerror(zlogp, err, dlname,
2497 "WARNING: unable to add network interface");
2498 return (-1);
2502 * Set the pool of this link if the zone has a pool and
2503 * neither the cpus nor the pool datalink property is
2504 * already set.
2506 err = dladm_linkprop_is_set(dld_handle, linkid, DLADM_PROP_VAL_CURRENT,
2507 "cpus", &cpuset);
2508 if (err != DLADM_STATUS_OK) {
2509 zdlerror(zlogp, err, dlname,
2510 "WARNING: unable to check if cpus link property is set");
2512 err = dladm_linkprop_is_set(dld_handle, linkid, DLADM_PROP_VAL_CURRENT,
2513 "pool", &poolset);
2514 if (err != DLADM_STATUS_OK) {
2515 zdlerror(zlogp, err, dlname,
2516 "WARNING: unable to check if pool link property is set");
2519 if ((strlen(pool_name) != 0) && !cpuset && !poolset) {
2520 poolp = pool_name;
2521 err = dladm_set_linkprop(dld_handle, linkid, "pool",
2522 &poolp, 1, DLADM_OPT_ACTIVE);
2523 if (err != DLADM_STATUS_OK) {
2524 zerror(zlogp, B_FALSE, "WARNING: unable to set "
2525 "pool %s to datalink %s", pool_name, dlname);
2526 bzero(pool_name, sizeof (pool_name));
2528 } else {
2529 bzero(pool_name, sizeof (pool_name));
2531 return (0);
2534 static boolean_t
2535 sockaddr_to_str(sa_family_t af, const struct sockaddr *sockaddr,
2536 char *straddr, size_t len)
2538 struct sockaddr_in *sin;
2539 struct sockaddr_in6 *sin6;
2540 const char *str = NULL;
2542 if (af == AF_INET) {
2543 /* LINTED E_BAD_PTR_CAST_ALIGN */
2544 sin = SIN(sockaddr);
2545 str = inet_ntop(AF_INET, (void *)&sin->sin_addr, straddr, len);
2546 } else if (af == AF_INET6) {
2547 /* LINTED E_BAD_PTR_CAST_ALIGN */
2548 sin6 = SIN6(sockaddr);
2549 str = inet_ntop(AF_INET6, (void *)&sin6->sin6_addr, straddr,
2550 len);
2553 return (str != NULL);
2556 static int
2557 ipv4_prefixlen(struct sockaddr_in *sin)
2559 struct sockaddr_in *m;
2560 struct sockaddr_storage mask;
2562 m = SIN(&mask);
2563 m->sin_family = AF_INET;
2564 if (getnetmaskbyaddr(sin->sin_addr, &m->sin_addr) == 0) {
2565 return (mask2plen((struct sockaddr *)&mask));
2566 } else if (IN_CLASSA(htonl(sin->sin_addr.s_addr))) {
2567 return (8);
2568 } else if (IN_CLASSB(ntohl(sin->sin_addr.s_addr))) {
2569 return (16);
2570 } else if (IN_CLASSC(ntohl(sin->sin_addr.s_addr))) {
2571 return (24);
2573 return (0);
2576 static int
2577 zone_setattr_network(int type, zoneid_t zoneid, datalink_id_t linkid,
2578 void *buf, size_t bufsize)
2580 zone_net_data_t *zndata;
2581 size_t znsize;
2582 int err;
2584 znsize = sizeof (*zndata) + bufsize;
2585 zndata = calloc(1, znsize);
2586 if (zndata == NULL)
2587 return (ENOMEM);
2588 zndata->zn_type = type;
2589 zndata->zn_len = bufsize;
2590 zndata->zn_linkid = linkid;
2591 bcopy(buf, zndata->zn_val, zndata->zn_len);
2592 err = zone_setattr(zoneid, ZONE_ATTR_NETWORK, zndata, znsize);
2593 free(zndata);
2594 return (err);
2597 static int
2598 add_net_for_linkid(zlog_t *zlogp, zoneid_t zoneid, zone_addr_list_t *start)
2600 struct lifreq lifr;
2601 char **astr, *address;
2602 dladm_status_t dlstatus;
2603 char *ip_nospoof = "ip-nospoof";
2604 int nnet, naddr, err = 0, j;
2605 size_t zlen, cpleft;
2606 zone_addr_list_t *ptr, *end;
2607 char tmp[INET6_ADDRSTRLEN], *maskstr;
2608 char *zaddr, *cp;
2609 struct in6_addr *routes = NULL;
2610 boolean_t is_set;
2611 datalink_id_t linkid;
2613 assert(start != NULL);
2614 naddr = 0; /* number of addresses */
2615 nnet = 0; /* number of net resources */
2616 linkid = start->za_linkid;
2617 for (ptr = start; ptr != NULL && ptr->za_linkid == linkid;
2618 ptr = ptr->za_next) {
2619 nnet++;
2621 end = ptr;
2622 zlen = nnet * (INET6_ADDRSTRLEN + 1);
2623 astr = calloc(1, nnet * sizeof (uintptr_t));
2624 zaddr = calloc(1, zlen);
2625 if (astr == NULL || zaddr == NULL) {
2626 err = ENOMEM;
2627 goto done;
2629 cp = zaddr;
2630 cpleft = zlen;
2631 j = 0;
2632 for (ptr = start; ptr != end; ptr = ptr->za_next) {
2633 address = ptr->za_nwiftab.zone_nwif_allowed_address;
2634 if (address[0] == '\0')
2635 continue;
2636 (void) snprintf(tmp, sizeof (tmp), "%s", address);
2638 * Validate the data. zonecfg_valid_net_address() clobbers
2639 * the /<mask> in the address string.
2641 if (zonecfg_valid_net_address(address, &lifr) != Z_OK) {
2642 zerror(zlogp, B_FALSE, "invalid address [%s]\n",
2643 address);
2644 err = EINVAL;
2645 goto done;
2648 * convert any hostnames to numeric address strings.
2650 if (!sockaddr_to_str(lifr.lifr_addr.ss_family,
2651 (const struct sockaddr *)&lifr.lifr_addr, cp, cpleft)) {
2652 err = EINVAL;
2653 goto done;
2656 * make a copy of the numeric string for the data needed
2657 * by the "allowed-ips" datalink property.
2659 astr[j] = strdup(cp);
2660 if (astr[j] == NULL) {
2661 err = ENOMEM;
2662 goto done;
2664 j++;
2666 * compute the default netmask from the address, if necessary
2668 if ((maskstr = strchr(tmp, '/')) == NULL) {
2669 int prefixlen;
2671 if (lifr.lifr_addr.ss_family == AF_INET) {
2672 prefixlen = ipv4_prefixlen(
2673 SIN(&lifr.lifr_addr));
2674 } else {
2675 struct sockaddr_in6 *sin6;
2677 sin6 = SIN6(&lifr.lifr_addr);
2678 if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
2679 prefixlen = 10;
2680 else
2681 prefixlen = 64;
2683 (void) snprintf(tmp, sizeof (tmp), "%d", prefixlen);
2684 maskstr = tmp;
2685 } else {
2686 maskstr++;
2688 /* append the "/<netmask>" */
2689 (void) strlcat(cp, "/", cpleft);
2690 (void) strlcat(cp, maskstr, cpleft);
2691 (void) strlcat(cp, ",", cpleft);
2692 cp += strnlen(cp, zlen);
2693 cpleft = &zaddr[INET6_ADDRSTRLEN] - cp;
2695 naddr = j; /* the actual number of addresses in the net resource */
2696 assert(naddr <= nnet);
2699 * zonecfg has already verified that the defrouter property can only
2700 * be set if there is at least one address defined for the net resource.
2701 * If j is 0, there are no addresses defined, and therefore no routers
2702 * to configure, and we are done at that point.
2704 if (j == 0)
2705 goto done;
2707 /* over-write last ',' with '\0' */
2708 zaddr[strnlen(zaddr, zlen) + 1] = '\0';
2711 * First make sure L3 protection is not already set on the link.
2713 dlstatus = dladm_linkprop_is_set(dld_handle, linkid, DLADM_OPT_ACTIVE,
2714 "protection", &is_set);
2715 if (dlstatus != DLADM_STATUS_OK) {
2716 err = EINVAL;
2717 zerror(zlogp, B_FALSE, "unable to check if protection is set");
2718 goto done;
2720 if (is_set) {
2721 err = EINVAL;
2722 zerror(zlogp, B_FALSE, "Protection is already set");
2723 goto done;
2725 dlstatus = dladm_linkprop_is_set(dld_handle, linkid, DLADM_OPT_ACTIVE,
2726 "allowed-ips", &is_set);
2727 if (dlstatus != DLADM_STATUS_OK) {
2728 err = EINVAL;
2729 zerror(zlogp, B_FALSE, "unable to check if allowed-ips is set");
2730 goto done;
2732 if (is_set) {
2733 zerror(zlogp, B_FALSE, "allowed-ips is already set");
2734 err = EINVAL;
2735 goto done;
2739 * Enable ip-nospoof for the link, and add address to the allowed-ips
2740 * list.
2742 dlstatus = dladm_set_linkprop(dld_handle, linkid, "protection",
2743 &ip_nospoof, 1, DLADM_OPT_ACTIVE);
2744 if (dlstatus != DLADM_STATUS_OK) {
2745 zerror(zlogp, B_FALSE, "could not set protection\n");
2746 err = EINVAL;
2747 goto done;
2749 dlstatus = dladm_set_linkprop(dld_handle, linkid, "allowed-ips",
2750 astr, naddr, DLADM_OPT_ACTIVE);
2751 if (dlstatus != DLADM_STATUS_OK) {
2752 zerror(zlogp, B_FALSE, "could not set allowed-ips\n");
2753 err = EINVAL;
2754 goto done;
2757 /* now set the address in the data-store */
2758 err = zone_setattr_network(ZONE_NETWORK_ADDRESS, zoneid, linkid,
2759 zaddr, strnlen(zaddr, zlen) + 1);
2760 if (err != 0)
2761 goto done;
2764 * add the defaultrouters
2766 routes = calloc(1, nnet * sizeof (*routes));
2767 j = 0;
2768 for (ptr = start; ptr != end; ptr = ptr->za_next) {
2769 address = ptr->za_nwiftab.zone_nwif_defrouter;
2770 if (address[0] == '\0')
2771 continue;
2772 if (strchr(address, '/') == NULL && strchr(address, ':') != 0) {
2774 * zonecfg_valid_net_address() expects numeric IPv6
2775 * addresses to have a CIDR format netmask.
2777 (void) snprintf(tmp, sizeof (tmp), "/%d", V6_ADDR_LEN);
2778 (void) strlcat(address, tmp, INET6_ADDRSTRLEN);
2780 if (zonecfg_valid_net_address(address, &lifr) != Z_OK) {
2781 zerror(zlogp, B_FALSE,
2782 "invalid router [%s]\n", address);
2783 err = EINVAL;
2784 goto done;
2786 if (lifr.lifr_addr.ss_family == AF_INET6) {
2787 routes[j] = SIN6(&lifr.lifr_addr)->sin6_addr;
2788 } else {
2789 IN6_INADDR_TO_V4MAPPED(&SIN(&lifr.lifr_addr)->sin_addr,
2790 &routes[j]);
2792 j++;
2794 assert(j <= nnet);
2795 if (j > 0) {
2796 err = zone_setattr_network(ZONE_NETWORK_DEFROUTER, zoneid,
2797 linkid, routes, j * sizeof (*routes));
2799 done:
2800 free(routes);
2801 for (j = 0; j < naddr; j++)
2802 free(astr[j]);
2803 free(astr);
2804 free(zaddr);
2805 return (err);
2809 static int
2810 add_net(zlog_t *zlogp, zoneid_t zoneid, zone_addr_list_t *zalist)
2812 zone_addr_list_t *ptr;
2813 datalink_id_t linkid;
2814 int err;
2816 if (zalist == NULL)
2817 return (0);
2819 linkid = zalist->za_linkid;
2821 err = add_net_for_linkid(zlogp, zoneid, zalist);
2822 if (err != 0)
2823 return (err);
2825 for (ptr = zalist; ptr != NULL; ptr = ptr->za_next) {
2826 if (ptr->za_linkid == linkid)
2827 continue;
2828 linkid = ptr->za_linkid;
2829 err = add_net_for_linkid(zlogp, zoneid, ptr);
2830 if (err != 0)
2831 return (err);
2833 return (0);
2837 * Add "new" to the list of network interfaces to be configured by
2838 * add_net on zone boot in "old". The list of interfaces in "old" is
2839 * sorted by datalink_id_t, with interfaces sorted FIFO for a given
2840 * datalink_id_t.
2842 * Returns the merged list of IP interfaces containing "old" and "new"
2844 static zone_addr_list_t *
2845 add_ip_interface(zone_addr_list_t *old, zone_addr_list_t *new)
2847 zone_addr_list_t *ptr, *next;
2848 datalink_id_t linkid = new->za_linkid;
2850 assert(old != new);
2852 if (old == NULL)
2853 return (new);
2854 for (ptr = old; ptr != NULL; ptr = ptr->za_next) {
2855 if (ptr->za_linkid == linkid)
2856 break;
2858 if (ptr == NULL) {
2859 /* linkid does not already exist, add to the beginning */
2860 new->za_next = old;
2861 return (new);
2864 * adding to the middle of the list; ptr points at the first
2865 * occurrence of linkid. Find the last occurrence.
2867 while ((next = ptr->za_next) != NULL) {
2868 if (next->za_linkid != linkid)
2869 break;
2870 ptr = next;
2872 /* insert new after ptr */
2873 new->za_next = next;
2874 ptr->za_next = new;
2875 return (old);
2878 void
2879 free_ip_interface(zone_addr_list_t *zalist)
2881 zone_addr_list_t *ptr, *new;
2883 for (ptr = zalist; ptr != NULL; ) {
2884 new = ptr;
2885 ptr = ptr->za_next;
2886 free(new);
2891 * Add the kernel access control information for the interface names.
2892 * If anything goes wrong, we log a general error message, attempt to tear down
2893 * whatever we set up, and return an error.
2895 static int
2896 configure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
2898 zone_dochandle_t handle;
2899 struct zone_nwiftab nwiftab;
2900 char rootpath[MAXPATHLEN];
2901 char path[MAXPATHLEN];
2902 datalink_id_t linkid;
2903 di_prof_t prof = NULL;
2904 boolean_t added = B_FALSE;
2905 zone_addr_list_t *zalist = NULL, *new;
2907 if ((handle = zonecfg_init_handle()) == NULL) {
2908 zerror(zlogp, B_TRUE, "getting zone configuration handle");
2909 return (-1);
2911 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2912 zerror(zlogp, B_FALSE, "invalid configuration");
2913 zonecfg_fini_handle(handle);
2914 return (-1);
2917 if (zonecfg_setnwifent(handle) != Z_OK) {
2918 zonecfg_fini_handle(handle);
2919 return (0);
2922 for (;;) {
2923 if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2924 break;
2926 if (prof == NULL) {
2927 if (zone_get_devroot(zone_name, rootpath,
2928 sizeof (rootpath)) != Z_OK) {
2929 (void) zonecfg_endnwifent(handle);
2930 zonecfg_fini_handle(handle);
2931 zerror(zlogp, B_TRUE,
2932 "unable to determine dev root");
2933 return (-1);
2935 (void) snprintf(path, sizeof (path), "%s%s", rootpath,
2936 "/dev");
2937 if (di_prof_init(path, &prof) != 0) {
2938 (void) zonecfg_endnwifent(handle);
2939 zonecfg_fini_handle(handle);
2940 zerror(zlogp, B_TRUE,
2941 "failed to initialize profile");
2942 return (-1);
2947 * Create the /dev entry for backward compatibility.
2948 * Only create the /dev entry if it's not in use.
2949 * Note that the zone still boots when the assigned
2950 * interface is inaccessible, used by others, etc.
2951 * Also, when vanity naming is used, some interface do
2952 * do not have corresponding /dev node names (for example,
2953 * vanity named aggregations). The /dev entry is not
2954 * created in that case. The /dev/net entry is always
2955 * accessible.
2957 if (dladm_name2info(dld_handle, nwiftab.zone_nwif_physical,
2958 &linkid, NULL, NULL, NULL) == DLADM_STATUS_OK &&
2959 add_datalink(zlogp, zone_name, linkid,
2960 nwiftab.zone_nwif_physical) == 0) {
2961 added = B_TRUE;
2962 } else {
2963 (void) zonecfg_endnwifent(handle);
2964 zonecfg_fini_handle(handle);
2965 zerror(zlogp, B_TRUE, "failed to add network device");
2966 return (-1);
2968 /* set up the new IP interface, and add them all later */
2969 new = malloc(sizeof (*new));
2970 if (new == NULL) {
2971 zerror(zlogp, B_TRUE, "no memory for %s",
2972 nwiftab.zone_nwif_physical);
2973 zonecfg_fini_handle(handle);
2974 free_ip_interface(zalist);
2976 bzero(new, sizeof (*new));
2977 new->za_nwiftab = nwiftab;
2978 new->za_linkid = linkid;
2979 zalist = add_ip_interface(zalist, new);
2981 if (zalist != NULL) {
2982 if ((errno = add_net(zlogp, zoneid, zalist)) != 0) {
2983 (void) zonecfg_endnwifent(handle);
2984 zonecfg_fini_handle(handle);
2985 zerror(zlogp, B_TRUE, "failed to add address");
2986 free_ip_interface(zalist);
2987 return (-1);
2989 free_ip_interface(zalist);
2991 (void) zonecfg_endnwifent(handle);
2992 zonecfg_fini_handle(handle);
2994 if (prof != NULL && added) {
2995 if (di_prof_commit(prof) != 0) {
2996 zerror(zlogp, B_TRUE, "failed to commit profile");
2997 return (-1);
3000 if (prof != NULL)
3001 di_prof_fini(prof);
3003 return (0);
3006 static int
3007 remove_datalink_pool(zlog_t *zlogp, zoneid_t zoneid)
3009 ushort_t flags;
3010 zone_iptype_t iptype;
3011 int i, dlnum = 0;
3012 datalink_id_t *dllink, *dllinks = NULL;
3013 dladm_status_t err;
3015 if (strlen(pool_name) == 0)
3016 return (0);
3018 if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
3019 sizeof (flags)) < 0) {
3020 if (vplat_get_iptype(zlogp, &iptype) < 0) {
3021 zerror(zlogp, B_FALSE, "unable to determine ip-type");
3022 return (-1);
3024 } else {
3025 if (flags & ZF_NET_EXCL)
3026 iptype = ZS_EXCLUSIVE;
3027 else
3028 iptype = ZS_SHARED;
3031 if (iptype == ZS_EXCLUSIVE) {
3033 * Get the datalink count and for each datalink,
3034 * attempt to clear the pool property and clear
3035 * the pool_name.
3037 if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
3038 zerror(zlogp, B_TRUE, "unable to count network "
3039 "interfaces");
3040 return (-1);
3043 if (dlnum == 0)
3044 return (0);
3046 if ((dllinks = malloc(dlnum * sizeof (datalink_id_t)))
3047 == NULL) {
3048 zerror(zlogp, B_TRUE, "memory allocation failed");
3049 return (-1);
3051 if (zone_list_datalink(zoneid, &dlnum, dllinks) != 0) {
3052 zerror(zlogp, B_TRUE, "unable to list network "
3053 "interfaces");
3054 return (-1);
3057 bzero(pool_name, sizeof (pool_name));
3058 for (i = 0, dllink = dllinks; i < dlnum; i++, dllink++) {
3059 err = dladm_set_linkprop(dld_handle, *dllink, "pool",
3060 NULL, 0, DLADM_OPT_ACTIVE);
3061 if (err != DLADM_STATUS_OK) {
3062 zerror(zlogp, B_TRUE,
3063 "WARNING: unable to clear pool");
3066 free(dllinks);
3068 return (0);
3071 static int
3072 remove_datalink_protect(zlog_t *zlogp, zoneid_t zoneid)
3074 ushort_t flags;
3075 zone_iptype_t iptype;
3076 int i, dlnum = 0;
3077 dladm_status_t dlstatus;
3078 datalink_id_t *dllink, *dllinks = NULL;
3080 if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
3081 sizeof (flags)) < 0) {
3082 if (vplat_get_iptype(zlogp, &iptype) < 0) {
3083 zerror(zlogp, B_FALSE, "unable to determine ip-type");
3084 return (-1);
3086 } else {
3087 if (flags & ZF_NET_EXCL)
3088 iptype = ZS_EXCLUSIVE;
3089 else
3090 iptype = ZS_SHARED;
3093 if (iptype != ZS_EXCLUSIVE)
3094 return (0);
3097 * Get the datalink count and for each datalink,
3098 * attempt to clear the pool property and clear
3099 * the pool_name.
3101 if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
3102 zerror(zlogp, B_TRUE, "unable to count network interfaces");
3103 return (-1);
3106 if (dlnum == 0)
3107 return (0);
3109 if ((dllinks = malloc(dlnum * sizeof (datalink_id_t))) == NULL) {
3110 zerror(zlogp, B_TRUE, "memory allocation failed");
3111 return (-1);
3113 if (zone_list_datalink(zoneid, &dlnum, dllinks) != 0) {
3114 zerror(zlogp, B_TRUE, "unable to list network interfaces");
3115 free(dllinks);
3116 return (-1);
3119 for (i = 0, dllink = dllinks; i < dlnum; i++, dllink++) {
3120 char dlerr[DLADM_STRSIZE];
3122 dlstatus = dladm_set_linkprop(dld_handle, *dllink,
3123 "protection", NULL, 0, DLADM_OPT_ACTIVE);
3124 if (dlstatus == DLADM_STATUS_NOTFOUND) {
3125 /* datalink does not belong to the GZ */
3126 continue;
3128 if (dlstatus != DLADM_STATUS_OK) {
3129 zerror(zlogp, B_FALSE,
3130 dladm_status2str(dlstatus, dlerr));
3131 free(dllinks);
3132 return (-1);
3134 dlstatus = dladm_set_linkprop(dld_handle, *dllink,
3135 "allowed-ips", NULL, 0, DLADM_OPT_ACTIVE);
3136 if (dlstatus != DLADM_STATUS_OK) {
3137 zerror(zlogp, B_FALSE,
3138 dladm_status2str(dlstatus, dlerr));
3139 free(dllinks);
3140 return (-1);
3143 free(dllinks);
3144 return (0);
3147 static int
3148 unconfigure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
3150 int dlnum = 0;
3153 * The kernel shutdown callback for the dls module should have removed
3154 * all datalinks from this zone. If any remain, then there's a
3155 * problem.
3157 if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
3158 zerror(zlogp, B_TRUE, "unable to list network interfaces");
3159 return (-1);
3161 if (dlnum != 0) {
3162 zerror(zlogp, B_FALSE,
3163 "datalinks remain in zone after shutdown");
3164 return (-1);
3166 return (0);
3169 static int
3170 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
3171 const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
3173 int fd;
3174 struct strioctl ioc;
3175 tcp_ioc_abort_conn_t conn;
3176 int error;
3178 conn.ac_local = *local;
3179 conn.ac_remote = *remote;
3180 conn.ac_start = TCPS_SYN_SENT;
3181 conn.ac_end = TCPS_TIME_WAIT;
3182 conn.ac_zoneid = zoneid;
3184 ioc.ic_cmd = TCP_IOC_ABORT_CONN;
3185 ioc.ic_timout = -1; /* infinite timeout */
3186 ioc.ic_len = sizeof (conn);
3187 ioc.ic_dp = (char *)&conn;
3189 if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
3190 zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
3191 return (-1);
3194 error = ioctl(fd, I_STR, &ioc);
3195 (void) close(fd);
3196 if (error == 0 || errno == ENOENT) /* ENOENT is not an error */
3197 return (0);
3198 return (-1);
3201 static int
3202 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
3204 struct sockaddr_storage l, r;
3205 struct sockaddr_in *local, *remote;
3206 struct sockaddr_in6 *local6, *remote6;
3207 int error;
3210 * Abort IPv4 connections.
3212 bzero(&l, sizeof (*local));
3213 local = (struct sockaddr_in *)&l;
3214 local->sin_family = AF_INET;
3215 local->sin_addr.s_addr = INADDR_ANY;
3216 local->sin_port = 0;
3218 bzero(&r, sizeof (*remote));
3219 remote = (struct sockaddr_in *)&r;
3220 remote->sin_family = AF_INET;
3221 remote->sin_addr.s_addr = INADDR_ANY;
3222 remote->sin_port = 0;
3224 if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
3225 return (error);
3228 * Abort IPv6 connections.
3230 bzero(&l, sizeof (*local6));
3231 local6 = (struct sockaddr_in6 *)&l;
3232 local6->sin6_family = AF_INET6;
3233 local6->sin6_port = 0;
3234 local6->sin6_addr = in6addr_any;
3236 bzero(&r, sizeof (*remote6));
3237 remote6 = (struct sockaddr_in6 *)&r;
3238 remote6->sin6_family = AF_INET6;
3239 remote6->sin6_port = 0;
3240 remote6->sin6_addr = in6addr_any;
3242 if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
3243 return (error);
3244 return (0);
3247 static int
3248 get_privset(zlog_t *zlogp, priv_set_t *privs, zone_mnt_t mount_cmd)
3250 int error = -1;
3251 zone_dochandle_t handle;
3252 char *privname = NULL;
3254 if ((handle = zonecfg_init_handle()) == NULL) {
3255 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3256 return (-1);
3258 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3259 zerror(zlogp, B_FALSE, "invalid configuration");
3260 zonecfg_fini_handle(handle);
3261 return (-1);
3264 if (ALT_MOUNT(mount_cmd)) {
3265 zone_iptype_t iptype;
3266 const char *curr_iptype;
3268 if (zonecfg_get_iptype(handle, &iptype) != Z_OK) {
3269 zerror(zlogp, B_TRUE, "unable to determine ip-type");
3270 zonecfg_fini_handle(handle);
3271 return (-1);
3274 switch (iptype) {
3275 case ZS_SHARED:
3276 curr_iptype = "shared";
3277 break;
3278 case ZS_EXCLUSIVE:
3279 curr_iptype = "exclusive";
3280 break;
3283 if (zonecfg_default_privset(privs, curr_iptype) == Z_OK) {
3284 zonecfg_fini_handle(handle);
3285 return (0);
3287 zerror(zlogp, B_FALSE,
3288 "failed to determine the zone's default privilege set");
3289 zonecfg_fini_handle(handle);
3290 return (-1);
3293 switch (zonecfg_get_privset(handle, privs, &privname)) {
3294 case Z_OK:
3295 error = 0;
3296 break;
3297 case Z_PRIV_PROHIBITED:
3298 zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
3299 "within the zone's privilege set", privname);
3300 break;
3301 case Z_PRIV_REQUIRED:
3302 zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
3303 "from the zone's privilege set", privname);
3304 break;
3305 case Z_PRIV_UNKNOWN:
3306 zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
3307 "in the zone's privilege set", privname);
3308 break;
3309 default:
3310 zerror(zlogp, B_FALSE, "failed to determine the zone's "
3311 "privilege set");
3312 break;
3315 free(privname);
3316 zonecfg_fini_handle(handle);
3317 return (error);
3320 static int
3321 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3323 nvlist_t *nvl = NULL;
3324 char *nvl_packed = NULL;
3325 size_t nvl_size = 0;
3326 nvlist_t **nvlv = NULL;
3327 int rctlcount = 0;
3328 int error = -1;
3329 zone_dochandle_t handle;
3330 struct zone_rctltab rctltab;
3331 rctlblk_t *rctlblk = NULL;
3332 uint64_t maxlwps;
3333 uint64_t maxprocs;
3335 *bufp = NULL;
3336 *bufsizep = 0;
3338 if ((handle = zonecfg_init_handle()) == NULL) {
3339 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3340 return (-1);
3342 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3343 zerror(zlogp, B_FALSE, "invalid configuration");
3344 zonecfg_fini_handle(handle);
3345 return (-1);
3348 rctltab.zone_rctl_valptr = NULL;
3349 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
3350 zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
3351 goto out;
3355 * Allow the administrator to control both the maximum number of
3356 * process table slots and the maximum number of lwps with just the
3357 * max-processes property. If only the max-processes property is set,
3358 * we add a max-lwps property with a limit derived from max-processes.
3360 if (zonecfg_get_aliased_rctl(handle, ALIAS_MAXPROCS, &maxprocs)
3361 == Z_OK &&
3362 zonecfg_get_aliased_rctl(handle, ALIAS_MAXLWPS, &maxlwps)
3363 == Z_NO_ENTRY) {
3364 if (zonecfg_set_aliased_rctl(handle, ALIAS_MAXLWPS,
3365 maxprocs * LWPS_PER_PROCESS) != Z_OK) {
3366 zerror(zlogp, B_FALSE, "unable to set max-lwps alias");
3367 goto out;
3371 if (zonecfg_setrctlent(handle) != Z_OK) {
3372 zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
3373 goto out;
3376 if ((rctlblk = malloc(rctlblk_size())) == NULL) {
3377 zerror(zlogp, B_TRUE, "memory allocation failed");
3378 goto out;
3380 while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
3381 struct zone_rctlvaltab *rctlval;
3382 uint_t i, count;
3383 const char *name = rctltab.zone_rctl_name;
3385 /* zoneadm should have already warned about unknown rctls. */
3386 if (!zonecfg_is_rctl(name)) {
3387 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3388 rctltab.zone_rctl_valptr = NULL;
3389 continue;
3391 count = 0;
3392 for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
3393 rctlval = rctlval->zone_rctlval_next) {
3394 count++;
3396 if (count == 0) { /* ignore */
3397 continue; /* Nothing to free */
3399 if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
3400 goto out;
3401 i = 0;
3402 for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
3403 rctlval = rctlval->zone_rctlval_next, i++) {
3404 if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
3405 zerror(zlogp, B_TRUE, "%s failed",
3406 "nvlist_alloc");
3407 goto out;
3409 if (zonecfg_construct_rctlblk(rctlval, rctlblk)
3410 != Z_OK) {
3411 zerror(zlogp, B_FALSE, "invalid rctl value: "
3412 "(priv=%s,limit=%s,action=%s)",
3413 rctlval->zone_rctlval_priv,
3414 rctlval->zone_rctlval_limit,
3415 rctlval->zone_rctlval_action);
3416 goto out;
3418 if (!zonecfg_valid_rctl(name, rctlblk)) {
3419 zerror(zlogp, B_FALSE,
3420 "(priv=%s,limit=%s,action=%s) is not a "
3421 "valid value for rctl '%s'",
3422 rctlval->zone_rctlval_priv,
3423 rctlval->zone_rctlval_limit,
3424 rctlval->zone_rctlval_action,
3425 name);
3426 goto out;
3428 if (nvlist_add_uint64(nvlv[i], "privilege",
3429 rctlblk_get_privilege(rctlblk)) != 0) {
3430 zerror(zlogp, B_FALSE, "%s failed",
3431 "nvlist_add_uint64");
3432 goto out;
3434 if (nvlist_add_uint64(nvlv[i], "limit",
3435 rctlblk_get_value(rctlblk)) != 0) {
3436 zerror(zlogp, B_FALSE, "%s failed",
3437 "nvlist_add_uint64");
3438 goto out;
3440 if (nvlist_add_uint64(nvlv[i], "action",
3441 (uint_t)rctlblk_get_local_action(rctlblk, NULL))
3442 != 0) {
3443 zerror(zlogp, B_FALSE, "%s failed",
3444 "nvlist_add_uint64");
3445 goto out;
3448 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3449 rctltab.zone_rctl_valptr = NULL;
3450 if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
3451 != 0) {
3452 zerror(zlogp, B_FALSE, "%s failed",
3453 "nvlist_add_nvlist_array");
3454 goto out;
3456 for (i = 0; i < count; i++)
3457 nvlist_free(nvlv[i]);
3458 free(nvlv);
3459 nvlv = NULL;
3460 rctlcount++;
3462 (void) zonecfg_endrctlent(handle);
3464 if (rctlcount == 0) {
3465 error = 0;
3466 goto out;
3468 if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
3469 != 0) {
3470 zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
3471 goto out;
3474 error = 0;
3475 *bufp = nvl_packed;
3476 *bufsizep = nvl_size;
3478 out:
3479 free(rctlblk);
3480 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3481 if (error)
3482 free(nvl_packed);
3483 nvlist_free(nvl);
3484 free(nvlv);
3485 if (handle != NULL)
3486 zonecfg_fini_handle(handle);
3487 return (error);
3490 static int
3491 get_implicit_datasets(zlog_t *zlogp, char **retstr)
3493 char cmdbuf[2 * MAXPATHLEN];
3495 if (query_hook[0] == '\0')
3496 return (0);
3498 if (snprintf(cmdbuf, sizeof (cmdbuf), "%s datasets", query_hook)
3499 > sizeof (cmdbuf))
3500 return (-1);
3502 if (do_subproc(zlogp, cmdbuf, retstr) != 0)
3503 return (-1);
3505 return (0);
3508 static int
3509 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3511 zone_dochandle_t handle;
3512 struct zone_dstab dstab;
3513 size_t total, offset, len;
3514 int error = -1;
3515 char *str = NULL;
3516 char *implicit_datasets = NULL;
3517 int implicit_len = 0;
3519 *bufp = NULL;
3520 *bufsizep = 0;
3522 if ((handle = zonecfg_init_handle()) == NULL) {
3523 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3524 return (-1);
3526 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3527 zerror(zlogp, B_FALSE, "invalid configuration");
3528 zonecfg_fini_handle(handle);
3529 return (-1);
3532 if (get_implicit_datasets(zlogp, &implicit_datasets) != 0) {
3533 zerror(zlogp, B_FALSE, "getting implicit datasets failed");
3534 goto out;
3537 if (zonecfg_setdsent(handle) != Z_OK) {
3538 zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3539 goto out;
3542 total = 0;
3543 while (zonecfg_getdsent(handle, &dstab) == Z_OK)
3544 total += strlen(dstab.zone_dataset_name) + 1;
3545 (void) zonecfg_enddsent(handle);
3547 if (implicit_datasets != NULL)
3548 implicit_len = strlen(implicit_datasets);
3549 if (implicit_len > 0)
3550 total += implicit_len + 1;
3552 if (total == 0) {
3553 error = 0;
3554 goto out;
3557 if ((str = malloc(total)) == NULL) {
3558 zerror(zlogp, B_TRUE, "memory allocation failed");
3559 goto out;
3562 if (zonecfg_setdsent(handle) != Z_OK) {
3563 zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3564 goto out;
3566 offset = 0;
3567 while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3568 len = strlen(dstab.zone_dataset_name);
3569 (void) strlcpy(str + offset, dstab.zone_dataset_name,
3570 total - offset);
3571 offset += len;
3572 if (offset < total - 1)
3573 str[offset++] = ',';
3575 (void) zonecfg_enddsent(handle);
3577 if (implicit_len > 0)
3578 (void) strlcpy(str + offset, implicit_datasets, total - offset);
3580 error = 0;
3581 *bufp = str;
3582 *bufsizep = total;
3584 out:
3585 if (error != 0)
3586 free(str);
3587 if (handle != NULL)
3588 zonecfg_fini_handle(handle);
3589 free(implicit_datasets);
3591 return (error);
3594 static int
3595 validate_datasets(zlog_t *zlogp)
3597 zone_dochandle_t handle;
3598 struct zone_dstab dstab;
3599 zfs_handle_t *zhp;
3600 libzfs_handle_t *hdl;
3602 if ((handle = zonecfg_init_handle()) == NULL) {
3603 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3604 return (-1);
3606 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3607 zerror(zlogp, B_FALSE, "invalid configuration");
3608 zonecfg_fini_handle(handle);
3609 return (-1);
3612 if (zonecfg_setdsent(handle) != Z_OK) {
3613 zerror(zlogp, B_FALSE, "invalid configuration");
3614 zonecfg_fini_handle(handle);
3615 return (-1);
3618 if ((hdl = libzfs_init()) == NULL) {
3619 zerror(zlogp, B_FALSE, "opening ZFS library");
3620 zonecfg_fini_handle(handle);
3621 return (-1);
3624 while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3626 if ((zhp = zfs_open(hdl, dstab.zone_dataset_name,
3627 ZFS_TYPE_FILESYSTEM)) == NULL) {
3628 zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
3629 dstab.zone_dataset_name);
3630 zonecfg_fini_handle(handle);
3631 libzfs_fini(hdl);
3632 return (-1);
3636 * Automatically set the 'zoned' property. We check the value
3637 * first because we'll get EPERM if it is already set.
3639 if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
3640 zfs_prop_set(zhp, zfs_prop_to_name(ZFS_PROP_ZONED),
3641 "on") != 0) {
3642 zerror(zlogp, B_FALSE, "cannot set 'zoned' "
3643 "property for ZFS dataset '%s'\n",
3644 dstab.zone_dataset_name);
3645 zonecfg_fini_handle(handle);
3646 zfs_close(zhp);
3647 libzfs_fini(hdl);
3648 return (-1);
3651 zfs_close(zhp);
3653 (void) zonecfg_enddsent(handle);
3655 zonecfg_fini_handle(handle);
3656 libzfs_fini(hdl);
3658 return (0);
3662 * Return true if the path is its own zfs file system. We determine this
3663 * by stat-ing the path to see if it is zfs and stat-ing the parent to see
3664 * if it is a different fs.
3666 boolean_t
3667 is_zonepath_zfs(char *zonepath)
3669 int res;
3670 char *path;
3671 char *parent;
3672 struct statvfs64 buf1, buf2;
3674 if (statvfs64(zonepath, &buf1) != 0)
3675 return (B_FALSE);
3677 if (strcmp(buf1.f_basetype, "zfs") != 0)
3678 return (B_FALSE);
3680 if ((path = strdup(zonepath)) == NULL)
3681 return (B_FALSE);
3683 parent = dirname(path);
3684 res = statvfs64(parent, &buf2);
3685 free(path);
3687 if (res != 0)
3688 return (B_FALSE);
3690 if (buf1.f_fsid == buf2.f_fsid)
3691 return (B_FALSE);
3693 return (B_TRUE);
3697 * Verify the MAC label in the root dataset for the zone.
3698 * If the label exists, it must match the label configured for the zone.
3699 * Otherwise if there's no label on the dataset, create one here.
3702 static int
3703 validate_rootds_label(zlog_t *zlogp, char *rootpath, m_label_t *zone_sl)
3705 int error = -1;
3706 zfs_handle_t *zhp;
3707 libzfs_handle_t *hdl;
3708 m_label_t ds_sl;
3709 char zonepath[MAXPATHLEN];
3710 char ds_hexsl[MAXNAMELEN];
3712 if (!is_system_labeled())
3713 return (0);
3715 if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
3716 zerror(zlogp, B_TRUE, "unable to determine zone path");
3717 return (-1);
3720 if (!is_zonepath_zfs(zonepath))
3721 return (0);
3723 if ((hdl = libzfs_init()) == NULL) {
3724 zerror(zlogp, B_FALSE, "opening ZFS library");
3725 return (-1);
3728 if ((zhp = zfs_path_to_zhandle(hdl, rootpath,
3729 ZFS_TYPE_FILESYSTEM)) == NULL) {
3730 zerror(zlogp, B_FALSE, "cannot open ZFS dataset for path '%s'",
3731 rootpath);
3732 libzfs_fini(hdl);
3733 return (-1);
3736 /* Get the mlslabel property if it exists. */
3737 if ((zfs_prop_get(zhp, ZFS_PROP_MLSLABEL, ds_hexsl, MAXNAMELEN,
3738 NULL, NULL, 0, B_TRUE) != 0) ||
3739 (strcmp(ds_hexsl, ZFS_MLSLABEL_DEFAULT) == 0)) {
3740 char *str2 = NULL;
3743 * No label on the dataset (or default only); create one.
3744 * (Only do this automatic labeling for the labeled brand.)
3746 if (strcmp(brand_name, LABELED_BRAND_NAME) != 0) {
3747 error = 0;
3748 goto out;
3751 error = l_to_str_internal(zone_sl, &str2);
3752 if (error)
3753 goto out;
3754 if (str2 == NULL) {
3755 error = -1;
3756 goto out;
3758 if ((error = zfs_prop_set(zhp,
3759 zfs_prop_to_name(ZFS_PROP_MLSLABEL), str2)) != 0) {
3760 zerror(zlogp, B_FALSE, "cannot set 'mlslabel' "
3761 "property for root dataset at '%s'\n", rootpath);
3763 free(str2);
3764 goto out;
3767 /* Convert the retrieved dataset label to binary form. */
3768 error = hexstr_to_label(ds_hexsl, &ds_sl);
3769 if (error) {
3770 zerror(zlogp, B_FALSE, "invalid 'mlslabel' "
3771 "property on root dataset at '%s'\n", rootpath);
3772 goto out; /* exit with error */
3776 * Perform a MAC check by comparing the zone label with the
3777 * dataset label.
3779 error = (!blequal(zone_sl, &ds_sl));
3780 if (error)
3781 zerror(zlogp, B_FALSE, "Rootpath dataset has mismatched label");
3782 out:
3783 zfs_close(zhp);
3784 libzfs_fini(hdl);
3786 return (error);
3790 * Mount lower level home directories into/from current zone
3791 * Share exported directories specified in dfstab for zone
3793 static int
3794 tsol_mounts(zlog_t *zlogp, char *zone_name, char *rootpath)
3796 zoneid_t *zids = NULL;
3797 priv_set_t *zid_privs;
3798 const priv_impl_info_t *ip = NULL;
3799 uint_t nzents_saved;
3800 uint_t nzents;
3801 int i;
3802 char readonly[] = "ro";
3803 struct zone_fstab lower_fstab;
3804 char *argv[4];
3806 if (!is_system_labeled())
3807 return (0);
3809 if (zid_label == NULL) {
3810 zid_label = m_label_alloc(MAC_LABEL);
3811 if (zid_label == NULL)
3812 return (-1);
3815 /* Make sure our zone has an /export/home dir */
3816 (void) make_one_dir(zlogp, rootpath, "/export/home",
3817 DEFAULT_DIR_MODE, DEFAULT_DIR_USER, DEFAULT_DIR_GROUP);
3819 lower_fstab.zone_fs_raw[0] = '\0';
3820 (void) strlcpy(lower_fstab.zone_fs_type, MNTTYPE_LOFS,
3821 sizeof (lower_fstab.zone_fs_type));
3822 lower_fstab.zone_fs_options = NULL;
3823 (void) zonecfg_add_fs_option(&lower_fstab, readonly);
3826 * Get the list of zones from the kernel
3828 if (zone_list(NULL, &nzents) != 0) {
3829 zerror(zlogp, B_TRUE, "unable to list zones");
3830 zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3831 return (-1);
3833 again:
3834 if (nzents == 0) {
3835 zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3836 return (-1);
3839 zids = malloc(nzents * sizeof (zoneid_t));
3840 if (zids == NULL) {
3841 zerror(zlogp, B_TRUE, "memory allocation failed");
3842 return (-1);
3844 nzents_saved = nzents;
3846 if (zone_list(zids, &nzents) != 0) {
3847 zerror(zlogp, B_TRUE, "unable to list zones");
3848 zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
3849 free(zids);
3850 return (-1);
3852 if (nzents != nzents_saved) {
3853 /* list changed, try again */
3854 free(zids);
3855 goto again;
3858 ip = getprivimplinfo();
3859 if ((zid_privs = priv_allocset()) == NULL) {
3860 zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
3861 zonecfg_free_fs_option_list(
3862 lower_fstab.zone_fs_options);
3863 free(zids);
3864 return (-1);
3867 for (i = 0; i < nzents; i++) {
3868 char zid_name[ZONENAME_MAX];
3869 zone_state_t zid_state;
3870 char zid_rpath[MAXPATHLEN];
3871 struct stat stat_buf;
3873 if (zids[i] == GLOBAL_ZONEID)
3874 continue;
3876 if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
3877 continue;
3880 * Do special setup for the zone we are booting
3882 if (strcmp(zid_name, zone_name) == 0) {
3883 struct zone_fstab autofs_fstab;
3884 char map_path[MAXPATHLEN];
3885 int fd;
3888 * Create auto_home_<zone> map for this zone
3889 * in the global zone. The non-global zone entry
3890 * will be created by automount when the zone
3891 * is booted.
3894 (void) snprintf(autofs_fstab.zone_fs_special,
3895 MAXPATHLEN, "auto_home_%s", zid_name);
3897 (void) snprintf(autofs_fstab.zone_fs_dir, MAXPATHLEN,
3898 "/zone/%s/home", zid_name);
3900 (void) snprintf(map_path, sizeof (map_path),
3901 "/etc/%s", autofs_fstab.zone_fs_special);
3903 * If the map file doesn't exist create a template
3905 if ((fd = open(map_path, O_RDWR | O_CREAT | O_EXCL,
3906 S_IRUSR | S_IWUSR | S_IRGRP| S_IROTH)) != -1) {
3907 int len;
3908 char map_rec[MAXPATHLEN];
3910 len = snprintf(map_rec, sizeof (map_rec),
3911 "+%s\n*\t-fstype=lofs\t:%s/export/home/&\n",
3912 autofs_fstab.zone_fs_special, rootpath);
3913 (void) write(fd, map_rec, len);
3914 (void) close(fd);
3918 * Mount auto_home_<zone> in the global zone if absent.
3919 * If it's already of type autofs, then
3920 * don't mount it again.
3922 if ((stat(autofs_fstab.zone_fs_dir, &stat_buf) == -1) ||
3923 strcmp(stat_buf.st_fstype, MNTTYPE_AUTOFS) != 0) {
3924 char optstr[] = "indirect,ignore,nobrowse";
3926 (void) make_one_dir(zlogp, "",
3927 autofs_fstab.zone_fs_dir, DEFAULT_DIR_MODE,
3928 DEFAULT_DIR_USER, DEFAULT_DIR_GROUP);
3931 * Mount will fail if automounter has already
3932 * processed the auto_home_<zonename> map
3934 (void) domount(zlogp, MNTTYPE_AUTOFS, optstr,
3935 autofs_fstab.zone_fs_special,
3936 autofs_fstab.zone_fs_dir);
3938 continue;
3942 if (zone_get_state(zid_name, &zid_state) != Z_OK ||
3943 (zid_state != ZONE_STATE_READY &&
3944 zid_state != ZONE_STATE_RUNNING))
3945 /* Skip over zones without mounted filesystems */
3946 continue;
3948 if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
3949 sizeof (m_label_t)) < 0)
3950 /* Skip over zones with unspecified label */
3951 continue;
3953 if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
3954 sizeof (zid_rpath)) == -1)
3955 /* Skip over zones with bad path */
3956 continue;
3958 if (zone_getattr(zids[i], ZONE_ATTR_PRIVSET, zid_privs,
3959 sizeof (priv_chunk_t) * ip->priv_setsize) == -1)
3960 /* Skip over zones with bad privs */
3961 continue;
3964 * Reading down is valid according to our label model
3965 * but some customers want to disable it because it
3966 * allows execute down and other possible attacks.
3967 * Therefore, we restrict this feature to zones that
3968 * have the NET_MAC_AWARE privilege which is required
3969 * for NFS read-down semantics.
3971 if ((bldominates(zlabel, zid_label)) &&
3972 (priv_ismember(zprivs, PRIV_NET_MAC_AWARE))) {
3974 * Our zone dominates this one.
3975 * Create a lofs mount from lower zone's /export/home
3977 (void) snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
3978 "%s/zone/%s/export/home", rootpath, zid_name);
3981 * If the target is already an LOFS mount
3982 * then don't do it again.
3984 if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
3985 strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
3987 if (snprintf(lower_fstab.zone_fs_special,
3988 MAXPATHLEN, "%s/export",
3989 zid_rpath) > MAXPATHLEN)
3990 continue;
3993 * Make sure the lower-level home exists
3995 if (make_one_dir(zlogp,
3996 lower_fstab.zone_fs_special, "/home",
3997 DEFAULT_DIR_MODE, DEFAULT_DIR_USER,
3998 DEFAULT_DIR_GROUP) != 0)
3999 continue;
4001 (void) strlcat(lower_fstab.zone_fs_special,
4002 "/home", MAXPATHLEN);
4005 * Mount can fail because the lower-level
4006 * zone may have already done a mount up.
4008 (void) mount_one(zlogp, &lower_fstab, "",
4009 Z_MNT_BOOT);
4011 } else if ((bldominates(zid_label, zlabel)) &&
4012 (priv_ismember(zid_privs, PRIV_NET_MAC_AWARE))) {
4014 * This zone dominates our zone.
4015 * Create a lofs mount from our zone's /export/home
4017 if (snprintf(lower_fstab.zone_fs_dir, MAXPATHLEN,
4018 "%s/zone/%s/export/home", zid_rpath,
4019 zone_name) > MAXPATHLEN)
4020 continue;
4023 * If the target is already an LOFS mount
4024 * then don't do it again.
4026 if ((stat(lower_fstab.zone_fs_dir, &stat_buf) == -1) ||
4027 strcmp(stat_buf.st_fstype, MNTTYPE_LOFS) != 0) {
4029 (void) snprintf(lower_fstab.zone_fs_special,
4030 MAXPATHLEN, "%s/export/home", rootpath);
4033 * Mount can fail because the higher-level
4034 * zone may have already done a mount down.
4036 (void) mount_one(zlogp, &lower_fstab, "",
4037 Z_MNT_BOOT);
4041 zonecfg_free_fs_option_list(lower_fstab.zone_fs_options);
4042 priv_freeset(zid_privs);
4043 free(zids);
4046 * Now share any exported directories from this zone.
4047 * Each zone can have its own dfstab.
4050 argv[0] = "zoneshare";
4051 argv[1] = "-z";
4052 argv[2] = zone_name;
4053 argv[3] = NULL;
4055 (void) forkexec(zlogp, "/usr/lib/zones/zoneshare", argv);
4056 /* Don't check for errors since they don't affect the zone */
4058 return (0);
4062 * Unmount lofs mounts from higher level zones
4063 * Unshare nfs exported directories
4065 static void
4066 tsol_unmounts(zlog_t *zlogp, char *zone_name)
4068 zoneid_t *zids = NULL;
4069 uint_t nzents_saved;
4070 uint_t nzents;
4071 int i;
4072 char *argv[4];
4073 char path[MAXPATHLEN];
4075 if (!is_system_labeled())
4076 return;
4079 * Get the list of zones from the kernel
4081 if (zone_list(NULL, &nzents) != 0) {
4082 return;
4085 if (zid_label == NULL) {
4086 zid_label = m_label_alloc(MAC_LABEL);
4087 if (zid_label == NULL)
4088 return;
4091 again:
4092 if (nzents == 0)
4093 return;
4095 zids = malloc(nzents * sizeof (zoneid_t));
4096 if (zids == NULL) {
4097 zerror(zlogp, B_TRUE, "memory allocation failed");
4098 return;
4100 nzents_saved = nzents;
4102 if (zone_list(zids, &nzents) != 0) {
4103 free(zids);
4104 return;
4106 if (nzents != nzents_saved) {
4107 /* list changed, try again */
4108 free(zids);
4109 goto again;
4112 for (i = 0; i < nzents; i++) {
4113 char zid_name[ZONENAME_MAX];
4114 zone_state_t zid_state;
4115 char zid_rpath[MAXPATHLEN];
4117 if (zids[i] == GLOBAL_ZONEID)
4118 continue;
4120 if (getzonenamebyid(zids[i], zid_name, ZONENAME_MAX) == -1)
4121 continue;
4124 * Skip the zone we are halting
4126 if (strcmp(zid_name, zone_name) == 0)
4127 continue;
4129 if ((zone_getattr(zids[i], ZONE_ATTR_STATUS, &zid_state,
4130 sizeof (zid_state)) < 0) ||
4131 (zid_state < ZONE_IS_READY))
4132 /* Skip over zones without mounted filesystems */
4133 continue;
4135 if (zone_getattr(zids[i], ZONE_ATTR_SLBL, zid_label,
4136 sizeof (m_label_t)) < 0)
4137 /* Skip over zones with unspecified label */
4138 continue;
4140 if (zone_getattr(zids[i], ZONE_ATTR_ROOT, zid_rpath,
4141 sizeof (zid_rpath)) == -1)
4142 /* Skip over zones with bad path */
4143 continue;
4145 if (zlabel != NULL && bldominates(zid_label, zlabel)) {
4147 * This zone dominates our zone.
4148 * Unmount the lofs mount of our zone's /export/home
4151 if (snprintf(path, MAXPATHLEN,
4152 "%s/zone/%s/export/home", zid_rpath,
4153 zone_name) > MAXPATHLEN)
4154 continue;
4156 /* Skip over mount failures */
4157 (void) umount(path);
4160 free(zids);
4163 * Unmount global zone autofs trigger for this zone
4165 (void) snprintf(path, MAXPATHLEN, "/zone/%s/home", zone_name);
4166 /* Skip over mount failures */
4167 (void) umount(path);
4170 * Next unshare any exported directories from this zone.
4173 argv[0] = "zoneunshare";
4174 argv[1] = "-z";
4175 argv[2] = zone_name;
4176 argv[3] = NULL;
4178 (void) forkexec(zlogp, "/usr/lib/zones/zoneunshare", argv);
4179 /* Don't check for errors since they don't affect the zone */
4182 * Finally, deallocate any devices in the zone.
4185 argv[0] = "deallocate";
4186 argv[1] = "-Isz";
4187 argv[2] = zone_name;
4188 argv[3] = NULL;
4190 (void) forkexec(zlogp, "/usr/sbin/deallocate", argv);
4191 /* Don't check for errors since they don't affect the zone */
4195 * Fetch the Trusted Extensions label and multi-level ports (MLPs) for
4196 * this zone.
4198 static tsol_zcent_t *
4199 get_zone_label(zlog_t *zlogp, priv_set_t *privs)
4201 FILE *fp;
4202 tsol_zcent_t *zcent = NULL;
4203 char line[MAXTNZLEN];
4205 if ((fp = fopen(TNZONECFG_PATH, "r")) == NULL) {
4206 zerror(zlogp, B_TRUE, "%s", TNZONECFG_PATH);
4207 return (NULL);
4210 while (fgets(line, sizeof (line), fp) != NULL) {
4212 * Check for malformed database
4214 if (strlen(line) == MAXTNZLEN - 1)
4215 break;
4216 if ((zcent = tsol_sgetzcent(line, NULL, NULL)) == NULL)
4217 continue;
4218 if (strcmp(zcent->zc_name, zone_name) == 0)
4219 break;
4220 tsol_freezcent(zcent);
4221 zcent = NULL;
4223 (void) fclose(fp);
4225 if (zcent == NULL) {
4226 zerror(zlogp, B_FALSE, "zone requires a label assignment. "
4227 "See tnzonecfg(4)");
4228 } else {
4229 if (zlabel == NULL)
4230 zlabel = m_label_alloc(MAC_LABEL);
4232 * Save this zone's privileges for later read-down processing
4234 if ((zprivs = priv_allocset()) == NULL) {
4235 zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
4236 return (NULL);
4237 } else {
4238 priv_copyset(privs, zprivs);
4241 return (zcent);
4245 * Add the Trusted Extensions multi-level ports for this zone.
4247 static void
4248 set_mlps(zlog_t *zlogp, zoneid_t zoneid, tsol_zcent_t *zcent)
4250 tsol_mlp_t *mlp;
4251 tsol_mlpent_t tsme;
4253 if (!is_system_labeled())
4254 return;
4256 tsme.tsme_zoneid = zoneid;
4257 tsme.tsme_flags = 0;
4258 for (mlp = zcent->zc_private_mlp; !TSOL_MLP_END(mlp); mlp++) {
4259 tsme.tsme_mlp = *mlp;
4260 if (tnmlp(TNDB_LOAD, &tsme) != 0) {
4261 zerror(zlogp, B_TRUE, "cannot set zone-specific MLP "
4262 "on %d-%d/%d", mlp->mlp_port,
4263 mlp->mlp_port_upper, mlp->mlp_ipp);
4267 tsme.tsme_flags = TSOL_MEF_SHARED;
4268 for (mlp = zcent->zc_shared_mlp; !TSOL_MLP_END(mlp); mlp++) {
4269 tsme.tsme_mlp = *mlp;
4270 if (tnmlp(TNDB_LOAD, &tsme) != 0) {
4271 zerror(zlogp, B_TRUE, "cannot set shared MLP "
4272 "on %d-%d/%d", mlp->mlp_port,
4273 mlp->mlp_port_upper, mlp->mlp_ipp);
4278 static void
4279 remove_mlps(zlog_t *zlogp, zoneid_t zoneid)
4281 tsol_mlpent_t tsme;
4283 if (!is_system_labeled())
4284 return;
4286 (void) memset(&tsme, 0, sizeof (tsme));
4287 tsme.tsme_zoneid = zoneid;
4288 if (tnmlp(TNDB_FLUSH, &tsme) != 0)
4289 zerror(zlogp, B_TRUE, "cannot flush MLPs");
4293 prtmount(const struct mnttab *fs, void *x)
4295 zerror((zlog_t *)x, B_FALSE, " %s", fs->mnt_mountp);
4296 return (0);
4300 * Look for zones running on the main system that are using this root (or any
4301 * subdirectory of it). Return B_TRUE and print an error if a conflicting zone
4302 * is found or if we can't tell.
4304 static boolean_t
4305 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
4307 zoneid_t *zids = NULL;
4308 uint_t nzids = 0;
4309 boolean_t retv;
4310 int rlen, zlen;
4311 char zroot[MAXPATHLEN];
4312 char zonename[ZONENAME_MAX];
4314 for (;;) {
4315 nzids += 10;
4316 zids = malloc(nzids * sizeof (*zids));
4317 if (zids == NULL) {
4318 zerror(zlogp, B_TRUE, "memory allocation failed");
4319 return (B_TRUE);
4321 if (zone_list(zids, &nzids) == 0)
4322 break;
4323 free(zids);
4325 retv = B_FALSE;
4326 rlen = strlen(rootpath);
4327 while (nzids > 0) {
4329 * Ignore errors; they just mean that the zone has disappeared
4330 * while we were busy.
4332 if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
4333 sizeof (zroot)) == -1)
4334 continue;
4335 zlen = strlen(zroot);
4336 if (zlen > rlen)
4337 zlen = rlen;
4338 if (strncmp(rootpath, zroot, zlen) == 0 &&
4339 (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
4340 (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
4341 if (getzonenamebyid(zids[nzids], zonename,
4342 sizeof (zonename)) == -1)
4343 (void) snprintf(zonename, sizeof (zonename),
4344 "id %d", (int)zids[nzids]);
4345 zerror(zlogp, B_FALSE,
4346 "zone root %s already in use by zone %s",
4347 rootpath, zonename);
4348 retv = B_TRUE;
4349 break;
4352 free(zids);
4353 return (retv);
4357 * Search for loopback mounts that use this same source node (same device and
4358 * inode). Return B_TRUE if there is one or if we can't tell.
4360 static boolean_t
4361 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
4363 struct stat64 rst, zst;
4364 struct mnttab *mnp;
4366 if (stat64(rootpath, &rst) == -1) {
4367 zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
4368 return (B_TRUE);
4370 if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
4371 return (B_TRUE);
4372 for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
4373 if (mnp->mnt_fstype == NULL ||
4374 strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
4375 continue;
4376 /* We're looking at a loopback mount. Stat it. */
4377 if (mnp->mnt_special != NULL &&
4378 stat64(mnp->mnt_special, &zst) != -1 &&
4379 rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
4380 zerror(zlogp, B_FALSE,
4381 "zone root %s is reachable through %s",
4382 rootpath, mnp->mnt_mountp);
4383 return (B_TRUE);
4386 return (B_FALSE);
4390 * Set memory cap and pool info for the zone's resource management
4391 * configuration.
4393 static int
4394 setup_zone_rm(zlog_t *zlogp, char *zone_name, zoneid_t zoneid)
4396 int res;
4397 uint64_t tmp;
4398 struct zone_mcaptab mcap;
4399 char sched[MAXNAMELEN];
4400 zone_dochandle_t handle = NULL;
4401 char pool_err[128];
4403 if ((handle = zonecfg_init_handle()) == NULL) {
4404 zerror(zlogp, B_TRUE, "getting zone configuration handle");
4405 return (Z_BAD_HANDLE);
4408 if ((res = zonecfg_get_snapshot_handle(zone_name, handle)) != Z_OK) {
4409 zerror(zlogp, B_FALSE, "invalid configuration");
4410 zonecfg_fini_handle(handle);
4411 return (res);
4415 * If a memory cap is configured, set the cap in the kernel using
4416 * zone_setattr() and make sure the rcapd SMF service is enabled.
4418 if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
4419 uint64_t num;
4420 char smf_err[128];
4422 num = (uint64_t)strtoull(mcap.zone_physmem_cap, NULL, 10);
4423 if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
4424 zerror(zlogp, B_TRUE, "could not set zone memory cap");
4425 zonecfg_fini_handle(handle);
4426 return (Z_INVAL);
4429 if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
4430 zerror(zlogp, B_FALSE, "enabling system/rcap service "
4431 "failed: %s", smf_err);
4432 zonecfg_fini_handle(handle);
4433 return (Z_INVAL);
4437 /* Get the scheduling class set in the zone configuration. */
4438 if (zonecfg_get_sched_class(handle, sched, sizeof (sched)) == Z_OK &&
4439 strlen(sched) > 0) {
4440 if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, sched,
4441 strlen(sched)) == -1)
4442 zerror(zlogp, B_TRUE, "WARNING: unable to set the "
4443 "default scheduling class");
4445 } else if (zonecfg_get_aliased_rctl(handle, ALIAS_SHARES, &tmp)
4446 == Z_OK) {
4448 * If the zone has the zone.cpu-shares rctl set then we want to
4449 * use the Fair Share Scheduler (FSS) for processes in the
4450 * zone. Check what scheduling class the zone would be running
4451 * in by default so we can print a warning and modify the class
4452 * if we wouldn't be using FSS.
4454 char class_name[PC_CLNMSZ];
4456 if (zonecfg_get_dflt_sched_class(handle, class_name,
4457 sizeof (class_name)) != Z_OK) {
4458 zerror(zlogp, B_FALSE, "WARNING: unable to determine "
4459 "the zone's scheduling class");
4461 } else if (strcmp("FSS", class_name) != 0) {
4462 zerror(zlogp, B_FALSE, "WARNING: The zone.cpu-shares "
4463 "rctl is set but\nFSS is not the default "
4464 "scheduling class for\nthis zone. FSS will be "
4465 "used for processes\nin the zone but to get the "
4466 "full benefit of FSS,\nit should be the default "
4467 "scheduling class.\nSee dispadmin(1M) for more "
4468 "details.");
4470 if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, "FSS",
4471 strlen("FSS")) == -1)
4472 zerror(zlogp, B_TRUE, "WARNING: unable to set "
4473 "zone scheduling class to FSS");
4478 * The next few blocks of code attempt to set up temporary pools as
4479 * well as persistent pools. In all cases we call the functions
4480 * unconditionally. Within each funtion the code will check if the
4481 * zone is actually configured for a temporary pool or persistent pool
4482 * and just return if there is nothing to do.
4484 * If we are rebooting we want to attempt to reuse any temporary pool
4485 * that was previously set up. zonecfg_bind_tmp_pool() will do the
4486 * right thing in all cases (reuse or create) based on the current
4487 * zonecfg.
4489 if ((res = zonecfg_bind_tmp_pool(handle, zoneid, pool_err,
4490 sizeof (pool_err))) != Z_OK) {
4491 if (res == Z_POOL || res == Z_POOL_CREATE || res == Z_POOL_BIND)
4492 zerror(zlogp, B_FALSE, "%s: %s\ndedicated-cpu setting "
4493 "cannot be instantiated", zonecfg_strerror(res),
4494 pool_err);
4495 else
4496 zerror(zlogp, B_FALSE, "could not bind zone to "
4497 "temporary pool: %s", zonecfg_strerror(res));
4498 zonecfg_fini_handle(handle);
4499 return (Z_POOL_BIND);
4503 * Check if we need to warn about poold not being enabled.
4505 if (zonecfg_warn_poold(handle)) {
4506 zerror(zlogp, B_FALSE, "WARNING: A range of dedicated-cpus has "
4507 "been specified\nbut the dynamic pool service is not "
4508 "enabled.\nThe system will not dynamically adjust the\n"
4509 "processor allocation within the specified range\n"
4510 "until svc:/system/pools/dynamic is enabled.\n"
4511 "See poold(1M).");
4514 /* The following is a warning, not an error. */
4515 if ((res = zonecfg_bind_pool(handle, zoneid, pool_err,
4516 sizeof (pool_err))) != Z_OK) {
4517 if (res == Z_POOL_BIND)
4518 zerror(zlogp, B_FALSE, "WARNING: unable to bind to "
4519 "pool '%s'; using default pool.", pool_err);
4520 else if (res == Z_POOL)
4521 zerror(zlogp, B_FALSE, "WARNING: %s: %s",
4522 zonecfg_strerror(res), pool_err);
4523 else
4524 zerror(zlogp, B_FALSE, "WARNING: %s",
4525 zonecfg_strerror(res));
4528 /* Update saved pool name in case it has changed */
4529 (void) zonecfg_get_poolname(handle, zone_name, pool_name,
4530 sizeof (pool_name));
4532 zonecfg_fini_handle(handle);
4533 return (Z_OK);
4536 static void
4537 report_prop_err(zlog_t *zlogp, const char *name, const char *value, int res)
4539 switch (res) {
4540 case Z_TOO_BIG:
4541 zerror(zlogp, B_FALSE, "%s property value is too large.", name);
4542 break;
4544 case Z_INVALID_PROPERTY:
4545 zerror(zlogp, B_FALSE, "%s property value \"%s\" is not valid",
4546 name, value);
4547 break;
4549 default:
4550 zerror(zlogp, B_TRUE, "fetching property %s: %d", name, res);
4551 break;
4556 * Sets the hostid of the new zone based on its configured value. The zone's
4557 * zone_t structure must already exist in kernel memory. 'zlogp' refers to the
4558 * log used to report errors and warnings and must be non-NULL. 'zone_namep'
4559 * is the name of the new zone and must be non-NULL. 'zoneid' is the numeric
4560 * ID of the new zone.
4562 * This function returns zero on success and a nonzero error code on failure.
4564 static int
4565 setup_zone_hostid(zone_dochandle_t handle, zlog_t *zlogp, zoneid_t zoneid)
4567 int res;
4568 char hostidp[HW_HOSTID_LEN];
4569 unsigned int hostid;
4571 res = zonecfg_get_hostid(handle, hostidp, sizeof (hostidp));
4573 if (res == Z_BAD_PROPERTY) {
4574 return (Z_OK);
4575 } else if (res != Z_OK) {
4576 report_prop_err(zlogp, "hostid", hostidp, res);
4577 return (res);
4580 hostid = (unsigned int)strtoul(hostidp, NULL, 16);
4581 if ((res = zone_setattr(zoneid, ZONE_ATTR_HOSTID, &hostid,
4582 sizeof (hostid))) != 0) {
4583 zerror(zlogp, B_TRUE,
4584 "zone hostid is not valid: %s: %d", hostidp, res);
4585 return (Z_SYSTEM);
4588 return (res);
4591 static int
4592 setup_zone_secflags(zone_dochandle_t handle, zlog_t *zlogp, zoneid_t zoneid)
4594 psecflags_t secflags;
4595 struct zone_secflagstab tab = {0};
4596 secflagdelta_t delt;
4597 int res;
4599 res = zonecfg_lookup_secflags(handle, &tab);
4601 if ((res != Z_OK) &&
4602 /* The general defaulting code will handle this */
4603 (res != Z_NO_ENTRY) && (res != Z_BAD_PROPERTY)) {
4604 zerror(zlogp, B_FALSE, "security-flags property is "
4605 "invalid: %d", res);
4606 return (res);
4609 if (strlen(tab.zone_secflags_lower) == 0)
4610 (void) strlcpy(tab.zone_secflags_lower, "none",
4611 sizeof (tab.zone_secflags_lower));
4612 if (strlen(tab.zone_secflags_default) == 0)
4613 (void) strlcpy(tab.zone_secflags_default,
4614 tab.zone_secflags_lower,
4615 sizeof (tab.zone_secflags_default));
4616 if (strlen(tab.zone_secflags_upper) == 0)
4617 (void) strlcpy(tab.zone_secflags_upper, "all",
4618 sizeof (tab.zone_secflags_upper));
4620 if (secflags_parse(NULL, tab.zone_secflags_default,
4621 &delt) == -1) {
4622 zerror(zlogp, B_FALSE, "default security-flags: '%s'"
4623 "are invalid", tab.zone_secflags_default);
4624 return (Z_BAD_PROPERTY);
4625 } else if (delt.psd_ass_active != B_TRUE) {
4626 zerror(zlogp, B_FALSE, "relative security-flags are not "
4627 "allowed in zone configuration (default "
4628 "security-flags: '%s')",
4629 tab.zone_secflags_default);
4630 return (Z_BAD_PROPERTY);
4631 } else {
4632 secflags_copy(&secflags.psf_inherit, &delt.psd_assign);
4633 secflags_copy(&secflags.psf_effective, &delt.psd_assign);
4636 if (secflags_parse(NULL, tab.zone_secflags_lower,
4637 &delt) == -1) {
4638 zerror(zlogp, B_FALSE, "lower security-flags: '%s'"
4639 "are invalid", tab.zone_secflags_lower);
4640 return (Z_BAD_PROPERTY);
4641 } else if (delt.psd_ass_active != B_TRUE) {
4642 zerror(zlogp, B_FALSE, "relative security-flags are not "
4643 "allowed in zone configuration (lower "
4644 "security-flags: '%s')",
4645 tab.zone_secflags_lower);
4646 return (Z_BAD_PROPERTY);
4647 } else {
4648 secflags_copy(&secflags.psf_lower, &delt.psd_assign);
4651 if (secflags_parse(NULL, tab.zone_secflags_upper,
4652 &delt) == -1) {
4653 zerror(zlogp, B_FALSE, "upper security-flags: '%s'"
4654 "are invalid", tab.zone_secflags_upper);
4655 return (Z_BAD_PROPERTY);
4656 } else if (delt.psd_ass_active != B_TRUE) {
4657 zerror(zlogp, B_FALSE, "relative security-flags are not "
4658 "allowed in zone configuration (upper "
4659 "security-flags: '%s')",
4660 tab.zone_secflags_upper);
4661 return (Z_BAD_PROPERTY);
4662 } else {
4663 secflags_copy(&secflags.psf_upper, &delt.psd_assign);
4666 if (!psecflags_validate(&secflags)) {
4667 zerror(zlogp, B_TRUE, "security-flags violate invariants");
4668 return (Z_BAD_PROPERTY);
4671 if ((res = zone_setattr(zoneid, ZONE_ATTR_SECFLAGS, &secflags,
4672 sizeof (secflags))) != 0) {
4673 zerror(zlogp, B_TRUE,
4674 "security-flags couldn't be set: %d", res);
4675 return (Z_SYSTEM);
4678 return (Z_OK);
4681 static int
4682 setup_zone_fs_allowed(zone_dochandle_t handle, zlog_t *zlogp, zoneid_t zoneid)
4684 char fsallowed[ZONE_FS_ALLOWED_MAX];
4685 char *fsallowedp = fsallowed;
4686 int len = sizeof (fsallowed);
4687 int res;
4689 res = zonecfg_get_fs_allowed(handle, fsallowed, len);
4691 if (res == Z_BAD_PROPERTY) {
4692 /* No value, set the defaults */
4693 (void) strlcpy(fsallowed, DFLT_FS_ALLOWED, len);
4694 } else if (res != Z_OK) {
4695 report_prop_err(zlogp, "fs-allowed", fsallowed, res);
4696 return (res);
4697 } else if (fsallowed[0] == '-') {
4698 /* dropping default filesystems - use remaining list */
4699 if (fsallowed[1] != ',')
4700 return (Z_OK);
4701 fsallowedp += 2;
4702 len -= 2;
4703 } else {
4704 /* Has a value, append the defaults */
4705 if (strlcat(fsallowed, ",", len) >= len ||
4706 strlcat(fsallowed, DFLT_FS_ALLOWED, len) >= len) {
4707 report_prop_err(zlogp, "fs-allowed", fsallowed,
4708 Z_TOO_BIG);
4709 return (Z_TOO_BIG);
4713 if (zone_setattr(zoneid, ZONE_ATTR_FS_ALLOWED, fsallowedp, len) != 0) {
4714 zerror(zlogp, B_TRUE,
4715 "fs-allowed couldn't be set: %s: %d", fsallowedp, res);
4716 return (Z_SYSTEM);
4719 return (Z_OK);
4722 static int
4723 setup_zone_attrs(zlog_t *zlogp, char *zone_namep, zoneid_t zoneid)
4725 zone_dochandle_t handle;
4726 int res = Z_OK;
4728 if ((handle = zonecfg_init_handle()) == NULL) {
4729 zerror(zlogp, B_TRUE, "getting zone configuration handle");
4730 return (Z_BAD_HANDLE);
4732 if ((res = zonecfg_get_snapshot_handle(zone_namep, handle)) != Z_OK) {
4733 zerror(zlogp, B_FALSE, "invalid configuration");
4734 goto out;
4737 if ((res = setup_zone_hostid(handle, zlogp, zoneid)) != Z_OK)
4738 goto out;
4740 if ((res = setup_zone_fs_allowed(handle, zlogp, zoneid)) != Z_OK)
4741 goto out;
4743 if ((res = setup_zone_secflags(handle, zlogp, zoneid)) != Z_OK)
4744 goto out;
4746 out:
4747 zonecfg_fini_handle(handle);
4748 return (res);
4751 zoneid_t
4752 vplat_create(zlog_t *zlogp, zone_mnt_t mount_cmd)
4754 zoneid_t rval = -1;
4755 priv_set_t *privs;
4756 char rootpath[MAXPATHLEN];
4757 char *rctlbuf = NULL;
4758 size_t rctlbufsz = 0;
4759 char *zfsbuf = NULL;
4760 size_t zfsbufsz = 0;
4761 zoneid_t zoneid = -1;
4762 int xerr;
4763 char *kzone;
4764 FILE *fp = NULL;
4765 tsol_zcent_t *zcent = NULL;
4766 int match = 0;
4767 int doi = 0;
4768 int flags;
4769 zone_iptype_t iptype;
4771 if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
4772 zerror(zlogp, B_TRUE, "unable to determine zone root");
4773 return (-1);
4775 if (zonecfg_in_alt_root())
4776 resolve_lofs(zlogp, rootpath, sizeof (rootpath));
4778 if (vplat_get_iptype(zlogp, &iptype) < 0) {
4779 zerror(zlogp, B_TRUE, "unable to determine ip-type");
4780 return (-1);
4782 switch (iptype) {
4783 case ZS_SHARED:
4784 flags = 0;
4785 break;
4786 case ZS_EXCLUSIVE:
4787 flags = ZCF_NET_EXCL;
4788 break;
4791 if ((privs = priv_allocset()) == NULL) {
4792 zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
4793 return (-1);
4795 priv_emptyset(privs);
4796 if (get_privset(zlogp, privs, mount_cmd) != 0)
4797 goto error;
4799 if (mount_cmd == Z_MNT_BOOT &&
4800 get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
4801 zerror(zlogp, B_FALSE, "Unable to get list of rctls");
4802 goto error;
4805 if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
4806 zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
4807 goto error;
4810 if (mount_cmd == Z_MNT_BOOT && is_system_labeled()) {
4811 zcent = get_zone_label(zlogp, privs);
4812 if (zcent != NULL) {
4813 match = zcent->zc_match;
4814 doi = zcent->zc_doi;
4815 *zlabel = zcent->zc_label;
4816 } else {
4817 goto error;
4819 if (validate_rootds_label(zlogp, rootpath, zlabel) != 0)
4820 goto error;
4823 kzone = zone_name;
4826 * We must do this scan twice. First, we look for zones running on the
4827 * main system that are using this root (or any subdirectory of it).
4828 * Next, we reduce to the shortest path and search for loopback mounts
4829 * that use this same source node (same device and inode).
4831 if (duplicate_zone_root(zlogp, rootpath))
4832 goto error;
4833 if (duplicate_reachable_path(zlogp, rootpath))
4834 goto error;
4836 if (ALT_MOUNT(mount_cmd)) {
4837 root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
4840 * Forge up a special root for this zone. When a zone is
4841 * mounted, we can't let the zone have its own root because the
4842 * tools that will be used in this "scratch zone" need access
4843 * to both the zone's resources and the running machine's
4844 * executables.
4846 * Note that the mkdir here also catches read-only filesystems.
4848 if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
4849 zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
4850 goto error;
4852 if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
4853 goto error;
4856 if (zonecfg_in_alt_root()) {
4858 * If we are mounting up a zone in an alternate root partition,
4859 * then we have some additional work to do before starting the
4860 * zone. First, resolve the root path down so that we're not
4861 * fooled by duplicates. Then forge up an internal name for
4862 * the zone.
4864 if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
4865 zerror(zlogp, B_TRUE, "cannot open mapfile");
4866 goto error;
4868 if (zonecfg_lock_scratch(fp) != 0) {
4869 zerror(zlogp, B_TRUE, "cannot lock mapfile");
4870 goto error;
4872 if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4873 NULL, 0) == 0) {
4874 zerror(zlogp, B_FALSE, "scratch zone already running");
4875 goto error;
4877 /* This is the preferred name */
4878 (void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
4879 zone_name);
4880 srandom(getpid());
4881 while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
4882 0) == 0) {
4883 /* This is just an arbitrary name; note "." usage */
4884 (void) snprintf(kernzone, sizeof (kernzone),
4885 "SUNWlu.%08lX%08lX", random(), random());
4887 kzone = kernzone;
4890 xerr = 0;
4891 if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
4892 rctlbufsz, zfsbuf, zfsbufsz, &xerr, match, doi, zlabel,
4893 flags)) == -1) {
4894 if (xerr == ZE_AREMOUNTS) {
4895 if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
4896 zerror(zlogp, B_FALSE,
4897 "An unknown file-system is mounted on "
4898 "a subdirectory of %s", rootpath);
4899 } else {
4901 zerror(zlogp, B_FALSE,
4902 "These file-systems are mounted on "
4903 "subdirectories of %s:", rootpath);
4904 (void) zonecfg_find_mounts(rootpath,
4905 prtmount, zlogp);
4907 } else if (xerr == ZE_CHROOTED) {
4908 zerror(zlogp, B_FALSE, "%s: "
4909 "cannot create a zone from a chrooted "
4910 "environment", "zone_create");
4911 } else if (xerr == ZE_LABELINUSE) {
4912 char zonename[ZONENAME_MAX];
4913 (void) getzonenamebyid(getzoneidbylabel(zlabel),
4914 zonename, ZONENAME_MAX);
4915 zerror(zlogp, B_FALSE, "The zone label is already "
4916 "used by the zone '%s'.", zonename);
4917 } else {
4918 zerror(zlogp, B_TRUE, "%s failed", "zone_create");
4920 goto error;
4923 if (zonecfg_in_alt_root() &&
4924 zonecfg_add_scratch(fp, zone_name, kernzone,
4925 zonecfg_get_root()) == -1) {
4926 zerror(zlogp, B_TRUE, "cannot add mapfile entry");
4927 goto error;
4931 * The following actions are not performed when merely mounting a zone
4932 * for administrative use.
4934 if (mount_cmd == Z_MNT_BOOT) {
4935 brand_handle_t bh;
4936 struct brand_attr attr;
4937 char modname[MAXPATHLEN];
4939 if (setup_zone_attrs(zlogp, zone_name, zoneid) != Z_OK)
4940 goto error;
4942 if ((bh = brand_open(brand_name)) == NULL) {
4943 zerror(zlogp, B_FALSE,
4944 "unable to determine brand name");
4945 goto error;
4948 if (!is_system_labeled() &&
4949 (strcmp(brand_name, LABELED_BRAND_NAME) == 0)) {
4950 brand_close(bh);
4951 zerror(zlogp, B_FALSE,
4952 "cannot boot labeled zone on unlabeled system");
4953 goto error;
4957 * If this brand requires any kernel support, now is the time to
4958 * get it loaded and initialized.
4960 if (brand_get_modname(bh, modname, MAXPATHLEN) < 0) {
4961 brand_close(bh);
4962 zerror(zlogp, B_FALSE,
4963 "unable to determine brand kernel module");
4964 goto error;
4966 brand_close(bh);
4968 if (strlen(modname) > 0) {
4969 (void) strlcpy(attr.ba_brandname, brand_name,
4970 sizeof (attr.ba_brandname));
4971 (void) strlcpy(attr.ba_modname, modname,
4972 sizeof (attr.ba_modname));
4973 if (zone_setattr(zoneid, ZONE_ATTR_BRAND, &attr,
4974 sizeof (attr) != 0)) {
4975 zerror(zlogp, B_TRUE,
4976 "could not set zone brand attribute.");
4977 goto error;
4981 if (setup_zone_rm(zlogp, zone_name, zoneid) != Z_OK)
4982 goto error;
4984 set_mlps(zlogp, zoneid, zcent);
4987 rval = zoneid;
4988 zoneid = -1;
4990 error:
4991 if (zoneid != -1) {
4992 (void) zone_shutdown(zoneid);
4993 (void) zone_destroy(zoneid);
4995 free(rctlbuf);
4996 priv_freeset(privs);
4997 if (fp != NULL)
4998 zonecfg_close_scratch(fp);
4999 lofs_discard_mnttab();
5000 if (zcent != NULL)
5001 tsol_freezcent(zcent);
5002 return (rval);
5006 * Enter the zone and write a /etc/zones/index file there. This allows
5007 * libzonecfg (and thus zoneadm) to report the UUID and potentially other zone
5008 * details from inside the zone.
5010 static void
5011 write_index_file(zoneid_t zoneid)
5013 FILE *zef;
5014 FILE *zet;
5015 struct zoneent *zep;
5016 pid_t child;
5017 int tmpl_fd;
5018 ctid_t ct;
5019 int fd;
5020 char uuidstr[UUID_PRINTABLE_STRING_LENGTH];
5022 /* Locate the zone entry in the global zone's index file */
5023 if ((zef = setzoneent()) == NULL)
5024 return;
5025 while ((zep = getzoneent_private(zef)) != NULL) {
5026 if (strcmp(zep->zone_name, zone_name) == 0)
5027 break;
5028 free(zep);
5030 endzoneent(zef);
5031 if (zep == NULL)
5032 return;
5034 if ((tmpl_fd = init_template()) == -1) {
5035 free(zep);
5036 return;
5039 if ((child = fork()) == -1) {
5040 (void) ct_tmpl_clear(tmpl_fd);
5041 (void) close(tmpl_fd);
5042 free(zep);
5043 return;
5046 /* parent waits for child to finish */
5047 if (child != 0) {
5048 free(zep);
5049 if (contract_latest(&ct) == -1)
5050 ct = -1;
5051 (void) ct_tmpl_clear(tmpl_fd);
5052 (void) close(tmpl_fd);
5053 (void) waitpid(child, NULL, 0);
5054 (void) contract_abandon_id(ct);
5055 return;
5058 /* child enters zone and sets up index file */
5059 (void) ct_tmpl_clear(tmpl_fd);
5060 if (zone_enter(zoneid) != -1) {
5061 (void) mkdir(ZONE_CONFIG_ROOT, ZONE_CONFIG_MODE);
5062 (void) chown(ZONE_CONFIG_ROOT, ZONE_CONFIG_UID,
5063 ZONE_CONFIG_GID);
5064 fd = open(ZONE_INDEX_FILE, O_WRONLY|O_CREAT|O_TRUNC,
5065 ZONE_INDEX_MODE);
5066 if (fd != -1 && (zet = fdopen(fd, "w")) != NULL) {
5067 (void) fchown(fd, ZONE_INDEX_UID, ZONE_INDEX_GID);
5068 if (uuid_is_null(zep->zone_uuid))
5069 uuidstr[0] = '\0';
5070 else
5071 uuid_unparse(zep->zone_uuid, uuidstr);
5072 (void) fprintf(zet, "%s:%s:/:%s\n", zep->zone_name,
5073 zone_state_str(zep->zone_state),
5074 uuidstr);
5075 (void) fclose(zet);
5078 _exit(0);
5082 vplat_bringup(zlog_t *zlogp, zone_mnt_t mount_cmd, zoneid_t zoneid)
5084 char zonepath[MAXPATHLEN];
5086 if (mount_cmd == Z_MNT_BOOT && validate_datasets(zlogp) != 0) {
5087 lofs_discard_mnttab();
5088 return (-1);
5092 * Before we try to mount filesystems we need to create the
5093 * attribute backing store for /dev
5095 if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
5096 lofs_discard_mnttab();
5097 return (-1);
5099 resolve_lofs(zlogp, zonepath, sizeof (zonepath));
5101 /* Make /dev directory owned by root, grouped sys */
5102 if (make_one_dir(zlogp, zonepath, "/dev", DEFAULT_DIR_MODE,
5103 0, 3) != 0) {
5104 lofs_discard_mnttab();
5105 return (-1);
5108 if (mount_filesystems(zlogp, mount_cmd) != 0) {
5109 lofs_discard_mnttab();
5110 return (-1);
5113 if (mount_cmd == Z_MNT_BOOT) {
5114 zone_iptype_t iptype;
5116 if (vplat_get_iptype(zlogp, &iptype) < 0) {
5117 zerror(zlogp, B_TRUE, "unable to determine ip-type");
5118 lofs_discard_mnttab();
5119 return (-1);
5122 switch (iptype) {
5123 case ZS_SHARED:
5124 /* Always do this to make lo0 get configured */
5125 if (configure_shared_network_interfaces(zlogp) != 0) {
5126 lofs_discard_mnttab();
5127 return (-1);
5129 break;
5130 case ZS_EXCLUSIVE:
5131 if (configure_exclusive_network_interfaces(zlogp,
5132 zoneid) !=
5133 0) {
5134 lofs_discard_mnttab();
5135 return (-1);
5137 break;
5141 write_index_file(zoneid);
5143 lofs_discard_mnttab();
5144 return (0);
5147 static int
5148 lu_root_teardown(zlog_t *zlogp)
5150 char zroot[MAXPATHLEN];
5152 if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
5153 zerror(zlogp, B_FALSE, "unable to determine zone root");
5154 return (-1);
5156 root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
5159 * At this point, the processes are gone, the filesystems (save the
5160 * root) are unmounted, and the zone is on death row. But there may
5161 * still be creds floating about in the system that reference the
5162 * zone_t, and which pin down zone_rootvp causing this call to fail
5163 * with EBUSY. Thus, we try for a little while before just giving up.
5164 * (How I wish this were not true, and umount2 just did the right
5165 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
5167 if (umount2(zroot, MS_FORCE) != 0) {
5168 if (errno == ENOTSUP && umount2(zroot, 0) == 0)
5169 goto unmounted;
5170 if (errno == EBUSY) {
5171 int tries = 10;
5173 while (--tries >= 0) {
5174 (void) sleep(1);
5175 if (umount2(zroot, 0) == 0)
5176 goto unmounted;
5177 if (errno != EBUSY)
5178 break;
5181 zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
5182 return (-1);
5184 unmounted:
5187 * Only zones in an alternate root environment have scratch zone
5188 * entries.
5190 if (zonecfg_in_alt_root()) {
5191 FILE *fp;
5192 int retv;
5194 if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
5195 zerror(zlogp, B_TRUE, "cannot open mapfile");
5196 return (-1);
5198 retv = -1;
5199 if (zonecfg_lock_scratch(fp) != 0)
5200 zerror(zlogp, B_TRUE, "cannot lock mapfile");
5201 else if (zonecfg_delete_scratch(fp, kernzone) != 0)
5202 zerror(zlogp, B_TRUE, "cannot delete map entry");
5203 else
5204 retv = 0;
5205 zonecfg_close_scratch(fp);
5206 return (retv);
5207 } else {
5208 return (0);
5213 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd, boolean_t rebooting)
5215 char *kzone;
5216 zoneid_t zoneid;
5217 int res;
5218 char pool_err[128];
5219 char zpath[MAXPATHLEN];
5220 char cmdbuf[MAXPATHLEN];
5221 brand_handle_t bh = NULL;
5222 dladm_status_t status;
5223 char errmsg[DLADM_STRSIZE];
5224 ushort_t flags;
5226 kzone = zone_name;
5227 if (zonecfg_in_alt_root()) {
5228 FILE *fp;
5230 if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
5231 zerror(zlogp, B_TRUE, "unable to open map file");
5232 goto error;
5234 if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
5235 kernzone, sizeof (kernzone)) != 0) {
5236 zerror(zlogp, B_FALSE, "unable to find scratch zone");
5237 zonecfg_close_scratch(fp);
5238 goto error;
5240 zonecfg_close_scratch(fp);
5241 kzone = kernzone;
5244 if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
5245 if (!bringup_failure_recovery)
5246 zerror(zlogp, B_TRUE, "unable to get zoneid");
5247 if (unmount_cmd)
5248 (void) lu_root_teardown(zlogp);
5249 goto error;
5252 if (remove_datalink_pool(zlogp, zoneid) != 0) {
5253 zerror(zlogp, B_FALSE, "unable clear datalink pool property");
5254 goto error;
5257 if (remove_datalink_protect(zlogp, zoneid) != 0) {
5258 zerror(zlogp, B_FALSE,
5259 "unable clear datalink protect property");
5260 goto error;
5264 * The datalinks assigned to the zone will be removed from the NGZ as
5265 * part of zone_shutdown() so that we need to remove protect/pool etc.
5266 * before zone_shutdown(). Even if the shutdown itself fails, the zone
5267 * will not be able to violate any constraints applied because the
5268 * datalinks are no longer available to the zone.
5270 if (zone_shutdown(zoneid) != 0) {
5271 zerror(zlogp, B_TRUE, "unable to shutdown zone");
5272 goto error;
5275 /* Get the zonepath of this zone */
5276 if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
5277 zerror(zlogp, B_FALSE, "unable to determine zone path");
5278 goto error;
5281 /* Get a handle to the brand info for this zone */
5282 if ((bh = brand_open(brand_name)) == NULL) {
5283 zerror(zlogp, B_FALSE, "unable to determine zone brand");
5284 return (-1);
5287 * If there is a brand 'halt' callback, execute it now to give the
5288 * brand a chance to cleanup any custom configuration.
5290 (void) strcpy(cmdbuf, EXEC_PREFIX);
5291 if (brand_get_halt(bh, zone_name, zpath, cmdbuf + EXEC_LEN,
5292 sizeof (cmdbuf) - EXEC_LEN) < 0) {
5293 brand_close(bh);
5294 zerror(zlogp, B_FALSE, "unable to determine branded zone's "
5295 "halt callback.");
5296 goto error;
5298 brand_close(bh);
5300 if ((strlen(cmdbuf) > EXEC_LEN) &&
5301 (do_subproc(zlogp, cmdbuf, NULL) != Z_OK)) {
5302 zerror(zlogp, B_FALSE, "%s failed", cmdbuf);
5303 goto error;
5306 if (!unmount_cmd) {
5307 zone_iptype_t iptype;
5309 if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
5310 sizeof (flags)) < 0) {
5311 if (vplat_get_iptype(zlogp, &iptype) < 0) {
5312 zerror(zlogp, B_TRUE, "unable to determine "
5313 "ip-type");
5314 goto error;
5316 } else {
5317 if (flags & ZF_NET_EXCL)
5318 iptype = ZS_EXCLUSIVE;
5319 else
5320 iptype = ZS_SHARED;
5323 switch (iptype) {
5324 case ZS_SHARED:
5325 if (unconfigure_shared_network_interfaces(zlogp,
5326 zoneid) != 0) {
5327 zerror(zlogp, B_FALSE, "unable to unconfigure "
5328 "network interfaces in zone");
5329 goto error;
5331 break;
5332 case ZS_EXCLUSIVE:
5333 if (unconfigure_exclusive_network_interfaces(zlogp,
5334 zoneid) != 0) {
5335 zerror(zlogp, B_FALSE, "unable to unconfigure "
5336 "network interfaces in zone");
5337 goto error;
5339 status = dladm_zone_halt(dld_handle, zoneid);
5340 if (status != DLADM_STATUS_OK) {
5341 zerror(zlogp, B_FALSE, "unable to notify "
5342 "dlmgmtd of zone halt: %s",
5343 dladm_status2str(status, errmsg));
5345 break;
5349 if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
5350 zerror(zlogp, B_TRUE, "unable to abort TCP connections");
5351 goto error;
5354 if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
5355 zerror(zlogp, B_FALSE,
5356 "unable to unmount file systems in zone");
5357 goto error;
5361 * If we are rebooting then we normally don't want to destroy an
5362 * existing temporary pool at this point so that we can just reuse it
5363 * when the zone boots back up. However, it is also possible we were
5364 * running with a temporary pool and the zone configuration has been
5365 * modified to no longer use a temporary pool. In that case we need
5366 * to destroy the temporary pool now. This case looks like the case
5367 * where we never had a temporary pool configured but
5368 * zonecfg_destroy_tmp_pool will do the right thing either way.
5370 if (!unmount_cmd) {
5371 boolean_t destroy_tmp_pool = B_TRUE;
5373 if (rebooting) {
5374 struct zone_psettab pset_tab;
5375 zone_dochandle_t handle;
5377 if ((handle = zonecfg_init_handle()) != NULL &&
5378 zonecfg_get_handle(zone_name, handle) == Z_OK &&
5379 zonecfg_lookup_pset(handle, &pset_tab) == Z_OK)
5380 destroy_tmp_pool = B_FALSE;
5382 zonecfg_fini_handle(handle);
5385 if (destroy_tmp_pool) {
5386 if ((res = zonecfg_destroy_tmp_pool(zone_name, pool_err,
5387 sizeof (pool_err))) != Z_OK) {
5388 if (res == Z_POOL)
5389 zerror(zlogp, B_FALSE, pool_err);
5394 remove_mlps(zlogp, zoneid);
5396 if (zone_destroy(zoneid) != 0) {
5397 zerror(zlogp, B_TRUE, "unable to destroy zone");
5398 goto error;
5402 * Special teardown for alternate boot environments: remove the tmpfs
5403 * root for the zone and then remove it from the map file.
5405 if (unmount_cmd && lu_root_teardown(zlogp) != 0)
5406 goto error;
5408 lofs_discard_mnttab();
5409 return (0);
5411 error:
5412 lofs_discard_mnttab();
5413 return (-1);