kill tsol ("Trusted Solaris") aka TX ("Trusted Extensions")
[unleashed.git] / usr / src / cmd / zoneadmd / vplat.c
blobb5ccebcc75752523399ffb37b84a961c572c1712
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 <sys/priv.h>
127 #include <libinetutil.h>
129 #define V4_ADDR_LEN 32
130 #define V6_ADDR_LEN 128
132 #define RESOURCE_DEFAULT_OPTS \
133 MNTOPT_RO "," MNTOPT_LOFS_NOSUB "," MNTOPT_NODEVICES
135 #define DFSTYPES "/etc/dfs/fstypes"
136 #define MAXTNZLEN 2048
138 #define ALT_MOUNT(mount_cmd) ((mount_cmd) != Z_MNT_BOOT)
140 /* a reasonable estimate for the number of lwps per process */
141 #define LWPS_PER_PROCESS 10
143 /* for routing socket */
144 static int rts_seqno = 0;
146 /* mangled zone name when mounting in an alternate root environment */
147 static char kernzone[ZONENAME_MAX];
149 /* array of cached mount entries for resolve_lofs */
150 static struct mnttab *resolve_lofs_mnts, *resolve_lofs_mnt_max;
152 static const char *DFLT_FS_ALLOWED = "hsfs,smbfs,nfs,nfs3,nfs4,nfsdyn";
154 /* from libsocket, not in any header file */
155 extern int getnetmaskbyaddr(struct in_addr, struct in_addr *);
157 /* from zoneadmd */
158 extern char query_hook[];
161 * For each "net" resource configured in zonecfg, we track a zone_addr_list_t
162 * node in a linked list that is sorted by linkid. The list is constructed as
163 * the xml configuration file is parsed, and the information
164 * contained in each node is added to the kernel before the zone is
165 * booted, to be retrieved and applied from within the exclusive-IP NGZ
166 * on boot.
168 typedef struct zone_addr_list {
169 struct zone_addr_list *za_next;
170 datalink_id_t za_linkid; /* datalink_id_t of interface */
171 struct zone_nwiftab za_nwiftab; /* address, defrouter properties */
172 } zone_addr_list_t;
175 * An optimization for build_mnttable: reallocate (and potentially copy the
176 * data) only once every N times through the loop.
178 #define MNTTAB_HUNK 32
180 /* some handy macros */
181 #define SIN(s) ((struct sockaddr_in *)s)
182 #define SIN6(s) ((struct sockaddr_in6 *)s)
185 * Private autofs system call
187 extern int _autofssys(int, void *);
189 static int
190 autofs_cleanup(zoneid_t zoneid)
193 * Ask autofs to unmount all trigger nodes in the given zone.
195 return (_autofssys(AUTOFS_UNMOUNTALL, (void *)zoneid));
198 static void
199 free_mnttable(struct mnttab *mnt_array, uint_t nelem)
201 uint_t i;
203 if (mnt_array == NULL)
204 return;
205 for (i = 0; i < nelem; i++) {
206 free(mnt_array[i].mnt_mountp);
207 free(mnt_array[i].mnt_fstype);
208 free(mnt_array[i].mnt_special);
209 free(mnt_array[i].mnt_mntopts);
210 assert(mnt_array[i].mnt_time == NULL);
212 free(mnt_array);
216 * Build the mount table for the zone rooted at "zroot", storing the resulting
217 * array of struct mnttabs in "mnt_arrayp" and the number of elements in the
218 * array in "nelemp".
220 static int
221 build_mnttable(zlog_t *zlogp, const char *zroot, size_t zrootlen, FILE *mnttab,
222 struct mnttab **mnt_arrayp, uint_t *nelemp)
224 struct mnttab mnt;
225 struct mnttab *mnts;
226 struct mnttab *mnp;
227 uint_t nmnt;
229 rewind(mnttab);
230 resetmnttab(mnttab);
231 nmnt = 0;
232 mnts = NULL;
233 while (getmntent(mnttab, &mnt) == 0) {
234 struct mnttab *tmp_array;
236 if (strncmp(mnt.mnt_mountp, zroot, zrootlen) != 0)
237 continue;
238 if (nmnt % MNTTAB_HUNK == 0) {
239 tmp_array = realloc(mnts,
240 (nmnt + MNTTAB_HUNK) * sizeof (*mnts));
241 if (tmp_array == NULL) {
242 free_mnttable(mnts, nmnt);
243 return (-1);
245 mnts = tmp_array;
247 mnp = &mnts[nmnt++];
250 * Zero out any fields we're not using.
252 (void) memset(mnp, 0, sizeof (*mnp));
254 if (mnt.mnt_special != NULL)
255 mnp->mnt_special = strdup(mnt.mnt_special);
256 if (mnt.mnt_mntopts != NULL)
257 mnp->mnt_mntopts = strdup(mnt.mnt_mntopts);
258 mnp->mnt_mountp = strdup(mnt.mnt_mountp);
259 mnp->mnt_fstype = strdup(mnt.mnt_fstype);
260 if ((mnt.mnt_special != NULL && mnp->mnt_special == NULL) ||
261 (mnt.mnt_mntopts != NULL && mnp->mnt_mntopts == NULL) ||
262 mnp->mnt_mountp == NULL || mnp->mnt_fstype == NULL) {
263 zerror(zlogp, B_TRUE, "memory allocation failed");
264 free_mnttable(mnts, nmnt);
265 return (-1);
268 *mnt_arrayp = mnts;
269 *nelemp = nmnt;
270 return (0);
274 * This is an optimization. The resolve_lofs function is used quite frequently
275 * to manipulate file paths, and on a machine with a large number of zones,
276 * there will be a huge number of mounted file systems. Thus, we trigger a
277 * reread of the list of mount points
279 static void
280 lofs_discard_mnttab(void)
282 free_mnttable(resolve_lofs_mnts,
283 resolve_lofs_mnt_max - resolve_lofs_mnts);
284 resolve_lofs_mnts = resolve_lofs_mnt_max = NULL;
287 static int
288 lofs_read_mnttab(zlog_t *zlogp)
290 FILE *mnttab;
291 uint_t nmnts;
293 if ((mnttab = fopen(MNTTAB, "r")) == NULL)
294 return (-1);
295 if (build_mnttable(zlogp, "", 0, mnttab, &resolve_lofs_mnts,
296 &nmnts) == -1) {
297 (void) fclose(mnttab);
298 return (-1);
300 (void) fclose(mnttab);
301 resolve_lofs_mnt_max = resolve_lofs_mnts + nmnts;
302 return (0);
306 * This function loops over potential loopback mounts and symlinks in a given
307 * path and resolves them all down to an absolute path.
309 void
310 resolve_lofs(zlog_t *zlogp, char *path, size_t pathlen)
312 int len, arlen;
313 const char *altroot;
314 char tmppath[MAXPATHLEN];
315 boolean_t outside_altroot;
317 if ((len = resolvepath(path, tmppath, sizeof (tmppath))) == -1)
318 return;
319 tmppath[len] = '\0';
320 (void) strlcpy(path, tmppath, sizeof (tmppath));
322 /* This happens once per zoneadmd operation. */
323 if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
324 return;
326 altroot = zonecfg_get_root();
327 arlen = strlen(altroot);
328 outside_altroot = B_FALSE;
329 for (;;) {
330 struct mnttab *mnp;
332 /* Search in reverse order to find longest match */
333 for (mnp = resolve_lofs_mnt_max - 1; mnp >= resolve_lofs_mnts;
334 mnp--) {
335 if (mnp->mnt_fstype == NULL ||
336 mnp->mnt_mountp == NULL ||
337 mnp->mnt_special == NULL)
338 continue;
339 len = strlen(mnp->mnt_mountp);
340 if (strncmp(mnp->mnt_mountp, path, len) == 0 &&
341 (path[len] == '/' || path[len] == '\0'))
342 break;
344 if (mnp < resolve_lofs_mnts)
345 break;
346 /* If it's not a lofs then we're done */
347 if (strcmp(mnp->mnt_fstype, MNTTYPE_LOFS) != 0)
348 break;
349 if (outside_altroot) {
350 char *cp;
351 int olen = sizeof (MNTOPT_RO) - 1;
354 * If we run into a read-only mount outside of the
355 * alternate root environment, then the user doesn't
356 * want this path to be made read-write.
358 if (mnp->mnt_mntopts != NULL &&
359 (cp = strstr(mnp->mnt_mntopts, MNTOPT_RO)) !=
360 NULL &&
361 (cp == mnp->mnt_mntopts || cp[-1] == ',') &&
362 (cp[olen] == '\0' || cp[olen] == ',')) {
363 break;
365 } else if (arlen > 0 &&
366 (strncmp(mnp->mnt_special, altroot, arlen) != 0 ||
367 (mnp->mnt_special[arlen] != '\0' &&
368 mnp->mnt_special[arlen] != '/'))) {
369 outside_altroot = B_TRUE;
371 /* use temporary buffer because new path might be longer */
372 (void) snprintf(tmppath, sizeof (tmppath), "%s%s",
373 mnp->mnt_special, path + len);
374 if ((len = resolvepath(tmppath, path, pathlen)) == -1)
375 break;
376 path[len] = '\0';
381 * For a regular mount, check if a replacement lofs mount is needed because the
382 * referenced device is already mounted somewhere.
384 static int
385 check_lofs_needed(zlog_t *zlogp, struct zone_fstab *fsptr)
387 struct mnttab *mnp;
388 zone_fsopt_t *optptr, *onext;
390 /* This happens once per zoneadmd operation. */
391 if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
392 return (-1);
395 * If this special node isn't already in use, then it's ours alone;
396 * no need to worry about conflicting mounts.
398 for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max;
399 mnp++) {
400 if (strcmp(mnp->mnt_special, fsptr->zone_fs_special) == 0)
401 break;
403 if (mnp >= resolve_lofs_mnt_max)
404 return (0);
407 * Convert this duplicate mount into a lofs mount.
409 (void) strlcpy(fsptr->zone_fs_special, mnp->mnt_mountp,
410 sizeof (fsptr->zone_fs_special));
411 (void) strlcpy(fsptr->zone_fs_type, MNTTYPE_LOFS,
412 sizeof (fsptr->zone_fs_type));
413 fsptr->zone_fs_raw[0] = '\0';
416 * Discard all but one of the original options and set that to our
417 * default set of options used for resources.
419 optptr = fsptr->zone_fs_options;
420 if (optptr == NULL) {
421 optptr = malloc(sizeof (*optptr));
422 if (optptr == NULL) {
423 zerror(zlogp, B_TRUE, "cannot mount %s",
424 fsptr->zone_fs_dir);
425 return (-1);
427 } else {
428 while ((onext = optptr->zone_fsopt_next) != NULL) {
429 optptr->zone_fsopt_next = onext->zone_fsopt_next;
430 free(onext);
433 (void) strcpy(optptr->zone_fsopt_opt, RESOURCE_DEFAULT_OPTS);
434 optptr->zone_fsopt_next = NULL;
435 fsptr->zone_fs_options = optptr;
436 return (0);
440 make_one_dir(zlog_t *zlogp, const char *prefix, const char *subdir, mode_t mode,
441 uid_t userid, gid_t groupid)
443 char path[MAXPATHLEN];
444 struct stat st;
446 if (snprintf(path, sizeof (path), "%s%s", prefix, subdir) >
447 sizeof (path)) {
448 zerror(zlogp, B_FALSE, "pathname %s%s is too long", prefix,
449 subdir);
450 return (-1);
453 if (lstat(path, &st) == 0) {
455 * We don't check the file mode since presumably the zone
456 * administrator may have had good reason to change the mode,
457 * and we don't need to second guess him.
459 if (!S_ISDIR(st.st_mode)) {
460 zerror(zlogp, B_FALSE, "%s is not a directory", path);
461 return (-1);
463 return (0);
466 if (mkdirp(path, mode) != 0) {
467 if (errno == EROFS)
468 zerror(zlogp, B_FALSE, "Could not mkdir %s.\nIt is on "
469 "a read-only file system in this local zone.\nMake "
470 "sure %s exists in the global zone.", path, subdir);
471 else
472 zerror(zlogp, B_TRUE, "mkdirp of %s failed", path);
473 return (-1);
476 (void) chown(path, userid, groupid);
477 return (0);
480 static void
481 free_remote_fstypes(char **types)
483 uint_t i;
485 if (types == NULL)
486 return;
487 for (i = 0; types[i] != NULL; i++)
488 free(types[i]);
489 free(types);
492 static char **
493 get_remote_fstypes(zlog_t *zlogp)
495 char **types = NULL;
496 FILE *fp;
497 char buf[MAXPATHLEN];
498 char fstype[MAXPATHLEN];
499 uint_t lines = 0;
500 uint_t i;
502 if ((fp = fopen(DFSTYPES, "r")) == NULL) {
503 zerror(zlogp, B_TRUE, "failed to open %s", DFSTYPES);
504 return (NULL);
507 * Count the number of lines
509 while (fgets(buf, sizeof (buf), fp) != NULL)
510 lines++;
511 if (lines == 0) /* didn't read anything; empty file */
512 goto out;
513 rewind(fp);
515 * Allocate enough space for a NULL-terminated array.
517 types = calloc(lines + 1, sizeof (char *));
518 if (types == NULL) {
519 zerror(zlogp, B_TRUE, "memory allocation failed");
520 goto out;
522 i = 0;
523 while (fgets(buf, sizeof (buf), fp) != NULL) {
524 /* LINTED - fstype is big enough to hold buf */
525 if (sscanf(buf, "%s", fstype) == 0) {
526 zerror(zlogp, B_FALSE, "unable to parse %s", DFSTYPES);
527 free_remote_fstypes(types);
528 types = NULL;
529 goto out;
531 types[i] = strdup(fstype);
532 if (types[i] == NULL) {
533 zerror(zlogp, B_TRUE, "memory allocation failed");
534 free_remote_fstypes(types);
535 types = NULL;
536 goto out;
538 i++;
540 out:
541 (void) fclose(fp);
542 return (types);
545 static boolean_t
546 is_remote_fstype(const char *fstype, char *const *remote_fstypes)
548 uint_t i;
550 if (remote_fstypes == NULL)
551 return (B_FALSE);
552 for (i = 0; remote_fstypes[i] != NULL; i++) {
553 if (strcmp(remote_fstypes[i], fstype) == 0)
554 return (B_TRUE);
556 return (B_FALSE);
560 * This converts a zone root path (normally of the form .../root) to a Live
561 * Upgrade scratch zone root (of the form .../lu).
563 static void
564 root_to_lu(zlog_t *zlogp, char *zroot, size_t zrootlen, boolean_t isresolved)
566 if (!isresolved && zonecfg_in_alt_root())
567 resolve_lofs(zlogp, zroot, zrootlen);
568 (void) strcpy(strrchr(zroot, '/') + 1, "lu");
572 * The general strategy for unmounting filesystems is as follows:
574 * - Remote filesystems may be dead, and attempting to contact them as
575 * part of a regular unmount may hang forever; we want to always try to
576 * forcibly unmount such filesystems and only fall back to regular
577 * unmounts if the filesystem doesn't support forced unmounts.
579 * - We don't want to unnecessarily corrupt metadata on local
580 * filesystems (ie UFS), so we want to start off with graceful unmounts,
581 * and only escalate to doing forced unmounts if we get stuck.
583 * We start off walking backwards through the mount table. This doesn't
584 * give us strict ordering but ensures that we try to unmount submounts
585 * first. We thus limit the number of failed umount2(2) calls.
587 * The mechanism for determining if we're stuck is to count the number
588 * of failed unmounts each iteration through the mount table. This
589 * gives us an upper bound on the number of filesystems which remain
590 * mounted (autofs trigger nodes are dealt with separately). If at the
591 * end of one unmount+autofs_cleanup cycle we still have the same number
592 * of mounts that we started out with, we're stuck and try a forced
593 * unmount. If that fails (filesystem doesn't support forced unmounts)
594 * then we bail and are unable to teardown the zone. If it succeeds,
595 * we're no longer stuck so we continue with our policy of trying
596 * graceful mounts first.
598 * Zone must be down (ie, no processes or threads active).
600 static int
601 unmount_filesystems(zlog_t *zlogp, zoneid_t zoneid, boolean_t unmount_cmd)
603 int error = 0;
604 FILE *mnttab;
605 struct mnttab *mnts;
606 uint_t nmnt;
607 char zroot[MAXPATHLEN + 1];
608 size_t zrootlen;
609 uint_t oldcount = UINT_MAX;
610 boolean_t stuck = B_FALSE;
611 char **remote_fstypes = NULL;
613 if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
614 zerror(zlogp, B_FALSE, "unable to determine zone root");
615 return (-1);
617 if (unmount_cmd)
618 root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
620 (void) strcat(zroot, "/");
621 zrootlen = strlen(zroot);
623 if ((mnttab = fopen(MNTTAB, "r")) == NULL) {
624 zerror(zlogp, B_TRUE, "failed to open %s", MNTTAB);
625 return (-1);
628 * Use our hacky mntfs ioctl so we see everything, even mounts with
629 * MS_NOMNTTAB.
631 if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0) {
632 zerror(zlogp, B_TRUE, "unable to configure %s", MNTTAB);
633 error++;
634 goto out;
638 * Build the list of remote fstypes so we know which ones we
639 * should forcibly unmount.
641 remote_fstypes = get_remote_fstypes(zlogp);
642 for (; /* ever */; ) {
643 uint_t newcount = 0;
644 boolean_t unmounted;
645 struct mnttab *mnp;
646 char *path;
647 uint_t i;
649 mnts = NULL;
650 nmnt = 0;
652 * MNTTAB gives us a way to walk through mounted
653 * filesystems; we need to be able to walk them in
654 * reverse order, so we build a list of all mounted
655 * filesystems.
657 if (build_mnttable(zlogp, zroot, zrootlen, mnttab, &mnts,
658 &nmnt) != 0) {
659 error++;
660 goto out;
662 for (i = 0; i < nmnt; i++) {
663 mnp = &mnts[nmnt - i - 1]; /* access in reverse order */
664 path = mnp->mnt_mountp;
665 unmounted = B_FALSE;
667 * Try forced unmount first for remote filesystems.
669 * Not all remote filesystems support forced unmounts,
670 * so if this fails (ENOTSUP) we'll continue on
671 * and try a regular unmount.
673 if (is_remote_fstype(mnp->mnt_fstype, remote_fstypes)) {
674 if (umount2(path, MS_FORCE) == 0)
675 unmounted = B_TRUE;
678 * Try forced unmount if we're stuck.
680 if (stuck) {
681 if (umount2(path, MS_FORCE) == 0) {
682 unmounted = B_TRUE;
683 stuck = B_FALSE;
684 } else {
686 * The first failure indicates a
687 * mount we won't be able to get
688 * rid of automatically, so we
689 * bail.
691 error++;
692 zerror(zlogp, B_FALSE,
693 "unable to unmount '%s'", path);
694 free_mnttable(mnts, nmnt);
695 goto out;
699 * Try regular unmounts for everything else.
701 if (!unmounted && umount2(path, 0) != 0)
702 newcount++;
704 free_mnttable(mnts, nmnt);
706 if (newcount == 0)
707 break;
708 if (newcount >= oldcount) {
710 * Last round didn't unmount anything; we're stuck and
711 * should start trying forced unmounts.
713 stuck = B_TRUE;
715 oldcount = newcount;
718 * Autofs doesn't let you unmount its trigger nodes from
719 * userland so we have to tell the kernel to cleanup for us.
721 if (autofs_cleanup(zoneid) != 0) {
722 zerror(zlogp, B_TRUE, "unable to remove autofs nodes");
723 error++;
724 goto out;
728 out:
729 free_remote_fstypes(remote_fstypes);
730 (void) fclose(mnttab);
731 return (error ? -1 : 0);
734 static int
735 fs_compare(const void *m1, const void *m2)
737 struct zone_fstab *i = (struct zone_fstab *)m1;
738 struct zone_fstab *j = (struct zone_fstab *)m2;
740 return (strcmp(i->zone_fs_dir, j->zone_fs_dir));
744 * Fork and exec (and wait for) the mentioned binary with the provided
745 * arguments. Returns (-1) if something went wrong with fork(2) or exec(2),
746 * returns the exit status otherwise.
748 * If we were unable to exec the provided pathname (for whatever
749 * reason), we return the special token ZEXIT_EXEC. The current value
750 * of ZEXIT_EXEC doesn't conflict with legitimate exit codes of the
751 * consumers of this function; any future consumers must make sure this
752 * remains the case.
754 static int
755 forkexec(zlog_t *zlogp, const char *path, char *const argv[])
757 pid_t child_pid;
758 int child_status = 0;
761 * Do not let another thread localize a message while we are forking.
763 (void) mutex_lock(&msglock);
764 child_pid = fork();
765 (void) mutex_unlock(&msglock);
766 if (child_pid == -1) {
767 zerror(zlogp, B_TRUE, "could not fork for %s", argv[0]);
768 return (-1);
769 } else if (child_pid == 0) {
770 closefrom(0);
771 /* redirect stdin, stdout & stderr to /dev/null */
772 (void) open("/dev/null", O_RDONLY); /* stdin */
773 (void) open("/dev/null", O_WRONLY); /* stdout */
774 (void) open("/dev/null", O_WRONLY); /* stderr */
775 (void) execv(path, argv);
777 * Since we are in the child, there is no point calling zerror()
778 * since there is nobody waiting to consume it. So exit with a
779 * special code that the parent will recognize and call zerror()
780 * accordingly.
783 _exit(ZEXIT_EXEC);
784 } else {
785 (void) waitpid(child_pid, &child_status, 0);
788 if (WIFSIGNALED(child_status)) {
789 zerror(zlogp, B_FALSE, "%s unexpectedly terminated due to "
790 "signal %d", path, WTERMSIG(child_status));
791 return (-1);
793 assert(WIFEXITED(child_status));
794 if (WEXITSTATUS(child_status) == ZEXIT_EXEC) {
795 zerror(zlogp, B_FALSE, "failed to exec %s", path);
796 return (-1);
798 return (WEXITSTATUS(child_status));
801 static int
802 isregfile(const char *path)
804 struct stat64 st;
806 if (stat64(path, &st) == -1)
807 return (-1);
809 return (S_ISREG(st.st_mode));
812 static int
813 dofsck(zlog_t *zlogp, const char *fstype, const char *rawdev)
815 char cmdbuf[MAXPATHLEN];
816 char *argv[5];
817 int status;
820 * We could alternatively have called /usr/sbin/fsck -F <fstype>, but
821 * that would cost us an extra fork/exec without buying us anything.
823 if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck", fstype)
824 >= sizeof (cmdbuf)) {
825 zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
826 return (-1);
830 * If it doesn't exist, that's OK: we verified this previously
831 * in zoneadm.
833 if (isregfile(cmdbuf) == -1)
834 return (0);
836 argv[0] = "fsck";
837 argv[1] = "-o";
838 argv[2] = "p";
839 argv[3] = (char *)rawdev;
840 argv[4] = NULL;
842 status = forkexec(zlogp, cmdbuf, argv);
843 if (status == 0 || status == -1)
844 return (status);
845 zerror(zlogp, B_FALSE, "fsck of '%s' failed with exit status %d; "
846 "run fsck manually", rawdev, status);
847 return (-1);
850 static int
851 domount(zlog_t *zlogp, const char *fstype, const char *opts,
852 const char *special, const char *directory)
854 char cmdbuf[MAXPATHLEN];
855 char *argv[6];
856 int status;
859 * We could alternatively have called /usr/sbin/mount -F <fstype>, but
860 * that would cost us an extra fork/exec without buying us anything.
862 if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount", fstype)
863 >= sizeof (cmdbuf)) {
864 zerror(zlogp, B_FALSE, "file-system type %s too long", fstype);
865 return (-1);
867 argv[0] = "mount";
868 if (opts[0] == '\0') {
869 argv[1] = (char *)special;
870 argv[2] = (char *)directory;
871 argv[3] = NULL;
872 } else {
873 argv[1] = "-o";
874 argv[2] = (char *)opts;
875 argv[3] = (char *)special;
876 argv[4] = (char *)directory;
877 argv[5] = NULL;
880 status = forkexec(zlogp, cmdbuf, argv);
881 if (status == 0 || status == -1)
882 return (status);
883 if (opts[0] == '\0')
884 zerror(zlogp, B_FALSE, "\"%s %s %s\" "
885 "failed with exit code %d",
886 cmdbuf, special, directory, status);
887 else
888 zerror(zlogp, B_FALSE, "\"%s -o %s %s %s\" "
889 "failed with exit code %d",
890 cmdbuf, opts, special, directory, status);
891 return (-1);
895 * Check if a given mount point path exists.
896 * If it does, make sure it doesn't contain any symlinks.
897 * Note that if "leaf" is false we're checking an intermediate
898 * component of the mount point path, so it must be a directory.
899 * If "leaf" is true, then we're checking the entire mount point
900 * path, so the mount point itself can be anything aside from a
901 * symbolic link.
903 * If the path is invalid then a negative value is returned. If the
904 * path exists and is a valid mount point path then 0 is returned.
905 * If the path doesn't exist return a positive value.
907 static int
908 valid_mount_point(zlog_t *zlogp, const char *path, const boolean_t leaf)
910 struct stat statbuf;
911 char respath[MAXPATHLEN];
912 int res;
914 if (lstat(path, &statbuf) != 0) {
915 if (errno == ENOENT)
916 return (1);
917 zerror(zlogp, B_TRUE, "can't stat %s", path);
918 return (-1);
920 if (S_ISLNK(statbuf.st_mode)) {
921 zerror(zlogp, B_FALSE, "%s is a symlink", path);
922 return (-1);
924 if (!leaf && !S_ISDIR(statbuf.st_mode)) {
925 zerror(zlogp, B_FALSE, "%s is not a directory", path);
926 return (-1);
928 if ((res = resolvepath(path, respath, sizeof (respath))) == -1) {
929 zerror(zlogp, B_TRUE, "unable to resolve path %s", path);
930 return (-1);
932 respath[res] = '\0';
933 if (strcmp(path, respath) != 0) {
935 * We don't like ".."s, "."s, or "//"s throwing us off
937 zerror(zlogp, B_FALSE, "%s is not a canonical path", path);
938 return (-1);
940 return (0);
944 * Validate a mount point path. A valid mount point path is an
945 * absolute path that either doesn't exist, or, if it does exists it
946 * must be an absolute canonical path that doesn't have any symbolic
947 * links in it. The target of a mount point path can be any filesystem
948 * object. (Different filesystems can support different mount points,
949 * for example "lofs" and "mntfs" both support files and directories
950 * while "ufs" just supports directories.)
952 * If the path is invalid then a negative value is returned. If the
953 * path exists and is a valid mount point path then 0 is returned.
954 * If the path doesn't exist return a positive value.
957 valid_mount_path(zlog_t *zlogp, const char *rootpath, const char *spec,
958 const char *dir, const char *fstype)
960 char abspath[MAXPATHLEN], *slashp, *slashp_next;
961 int rv;
964 * Sanity check the target mount point path.
965 * It must be a non-null string that starts with a '/'.
967 if (dir[0] != '/') {
968 /* Something went wrong. */
969 zerror(zlogp, B_FALSE, "invalid mount directory, "
970 "type: \"%s\", special: \"%s\", dir: \"%s\"",
971 fstype, spec, dir);
972 return (-1);
976 * Join rootpath and dir. Make sure abspath ends with '/', this
977 * is added to all paths (even non-directory paths) to allow us
978 * to detect the end of paths below. If the path already ends
979 * in a '/', then that's ok too (although we'll fail the
980 * cannonical path check in valid_mount_point()).
982 if (snprintf(abspath, sizeof (abspath),
983 "%s%s/", rootpath, dir) >= sizeof (abspath)) {
984 zerror(zlogp, B_FALSE, "pathname %s%s is too long",
985 rootpath, dir);
986 return (-1);
990 * Starting with rootpath, verify the mount path one component
991 * at a time. Continue until we've evaluated all of abspath.
993 slashp = &abspath[strlen(rootpath)];
994 assert(*slashp == '/');
995 do {
996 slashp_next = strchr(slashp + 1, '/');
997 *slashp = '\0';
998 if (slashp_next != NULL) {
999 /* This is an intermediary mount path component. */
1000 rv = valid_mount_point(zlogp, abspath, B_FALSE);
1001 } else {
1002 /* This is the last component of the mount path. */
1003 rv = valid_mount_point(zlogp, abspath, B_TRUE);
1005 if (rv < 0)
1006 return (rv);
1007 *slashp = '/';
1008 } while ((slashp = slashp_next) != NULL);
1009 return (rv);
1012 static int
1013 mount_one_dev_device_cb(void *arg, const char *match, const char *name)
1015 di_prof_t prof = arg;
1017 if (name == NULL)
1018 return (di_prof_add_dev(prof, match));
1019 return (di_prof_add_map(prof, match, name));
1022 static int
1023 mount_one_dev_symlink_cb(void *arg, const char *source, const char *target)
1025 di_prof_t prof = arg;
1027 return (di_prof_add_symlink(prof, source, target));
1031 vplat_get_iptype(zlog_t *zlogp, zone_iptype_t *iptypep)
1033 zone_dochandle_t handle;
1035 if ((handle = zonecfg_init_handle()) == NULL) {
1036 zerror(zlogp, B_TRUE, "getting zone configuration handle");
1037 return (-1);
1039 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
1040 zerror(zlogp, B_FALSE, "invalid configuration");
1041 zonecfg_fini_handle(handle);
1042 return (-1);
1044 if (zonecfg_get_iptype(handle, iptypep) != Z_OK) {
1045 zerror(zlogp, B_FALSE, "invalid ip-type configuration");
1046 zonecfg_fini_handle(handle);
1047 return (-1);
1049 zonecfg_fini_handle(handle);
1050 return (0);
1054 * Apply the standard lists of devices/symlinks/mappings and the user-specified
1055 * list of devices (via zonecfg) to the /dev filesystem. The filesystem will
1056 * use these as a profile/filter to determine what exists in /dev.
1058 static int
1059 mount_one_dev(zlog_t *zlogp, char *devpath, zone_mnt_t mount_cmd)
1061 char brand[MAXNAMELEN];
1062 zone_dochandle_t handle = NULL;
1063 brand_handle_t bh = NULL;
1064 struct zone_devtab ztab;
1065 di_prof_t prof = NULL;
1066 int err;
1067 int retval = -1;
1068 zone_iptype_t iptype;
1069 const char *curr_iptype;
1071 if (di_prof_init(devpath, &prof)) {
1072 zerror(zlogp, B_TRUE, "failed to initialize profile");
1073 goto cleanup;
1077 * Get a handle to the brand info for this zone.
1078 * If we are mounting the zone, then we must always use the default
1079 * brand device mounts.
1081 if (ALT_MOUNT(mount_cmd)) {
1082 (void) strlcpy(brand, default_brand, sizeof (brand));
1083 } else {
1084 (void) strlcpy(brand, brand_name, sizeof (brand));
1087 if ((bh = brand_open(brand)) == NULL) {
1088 zerror(zlogp, B_FALSE, "unable to determine zone brand");
1089 goto cleanup;
1092 if (vplat_get_iptype(zlogp, &iptype) < 0) {
1093 zerror(zlogp, B_TRUE, "unable to determine ip-type");
1094 goto cleanup;
1096 switch (iptype) {
1097 case ZS_SHARED:
1098 curr_iptype = "shared";
1099 break;
1100 case ZS_EXCLUSIVE:
1101 curr_iptype = "exclusive";
1102 break;
1105 if (brand_platform_iter_devices(bh, zone_name,
1106 mount_one_dev_device_cb, prof, curr_iptype) != 0) {
1107 zerror(zlogp, B_TRUE, "failed to add standard device");
1108 goto cleanup;
1111 if (brand_platform_iter_link(bh,
1112 mount_one_dev_symlink_cb, prof) != 0) {
1113 zerror(zlogp, B_TRUE, "failed to add standard symlink");
1114 goto cleanup;
1117 /* Add user-specified devices and directories */
1118 if ((handle = zonecfg_init_handle()) == NULL) {
1119 zerror(zlogp, B_FALSE, "can't initialize zone handle");
1120 goto cleanup;
1122 if (err = zonecfg_get_handle(zone_name, handle)) {
1123 zerror(zlogp, B_FALSE, "can't get handle for zone "
1124 "%s: %s", zone_name, zonecfg_strerror(err));
1125 goto cleanup;
1127 if (err = zonecfg_setdevent(handle)) {
1128 zerror(zlogp, B_FALSE, "%s: %s", zone_name,
1129 zonecfg_strerror(err));
1130 goto cleanup;
1132 while (zonecfg_getdevent(handle, &ztab) == Z_OK) {
1133 if (di_prof_add_dev(prof, ztab.zone_dev_match)) {
1134 zerror(zlogp, B_TRUE, "failed to add "
1135 "user-specified device");
1136 goto cleanup;
1139 (void) zonecfg_enddevent(handle);
1141 /* Send profile to kernel */
1142 if (di_prof_commit(prof)) {
1143 zerror(zlogp, B_TRUE, "failed to commit profile");
1144 goto cleanup;
1147 retval = 0;
1149 cleanup:
1150 if (bh != NULL)
1151 brand_close(bh);
1152 if (handle != NULL)
1153 zonecfg_fini_handle(handle);
1154 if (prof)
1155 di_prof_fini(prof);
1156 return (retval);
1159 static int
1160 mount_one(zlog_t *zlogp, struct zone_fstab *fsptr, const char *rootpath,
1161 zone_mnt_t mount_cmd)
1163 char path[MAXPATHLEN];
1164 char optstr[MAX_MNTOPT_STR];
1165 zone_fsopt_t *optptr;
1166 int rv;
1168 if ((rv = valid_mount_path(zlogp, rootpath, fsptr->zone_fs_special,
1169 fsptr->zone_fs_dir, fsptr->zone_fs_type)) < 0) {
1170 zerror(zlogp, B_FALSE, "%s%s is not a valid mount point",
1171 rootpath, fsptr->zone_fs_dir);
1172 return (-1);
1173 } else if (rv > 0) {
1174 /* The mount point path doesn't exist, create it now. */
1175 if (make_one_dir(zlogp, rootpath, fsptr->zone_fs_dir,
1176 DEFAULT_DIR_MODE, DEFAULT_DIR_USER,
1177 DEFAULT_DIR_GROUP) != 0) {
1178 zerror(zlogp, B_FALSE, "failed to create mount point");
1179 return (-1);
1183 * Now this might seem weird, but we need to invoke
1184 * valid_mount_path() again. Why? Because it checks
1185 * to make sure that the mount point path is canonical,
1186 * which it can only do if the path exists, so now that
1187 * we've created the path we have to verify it again.
1189 if ((rv = valid_mount_path(zlogp, rootpath,
1190 fsptr->zone_fs_special, fsptr->zone_fs_dir,
1191 fsptr->zone_fs_type)) < 0) {
1192 zerror(zlogp, B_FALSE,
1193 "%s%s is not a valid mount point",
1194 rootpath, fsptr->zone_fs_dir);
1195 return (-1);
1199 (void) snprintf(path, sizeof (path), "%s%s", rootpath,
1200 fsptr->zone_fs_dir);
1203 * In general the strategy here is to do just as much verification as
1204 * necessary to avoid crashing or otherwise doing something bad; if the
1205 * administrator initiated the operation via zoneadm(1m), he'll get
1206 * auto-verification which will let him know what's wrong. If he
1207 * modifies the zone configuration of a running zone and doesn't attempt
1208 * to verify that it's OK we won't crash but won't bother trying to be
1209 * too helpful either. zoneadm verify is only a couple keystrokes away.
1211 if (!zonecfg_valid_fs_type(fsptr->zone_fs_type)) {
1212 zerror(zlogp, B_FALSE, "cannot mount %s on %s: "
1213 "invalid file-system type %s", fsptr->zone_fs_special,
1214 fsptr->zone_fs_dir, fsptr->zone_fs_type);
1215 return (-1);
1219 * If we're looking at an alternate root environment, then construct
1220 * read-only loopback mounts as necessary. Note that any special
1221 * paths for lofs zone mounts in an alternate root must have
1222 * already been pre-pended with any alternate root path by the
1223 * time we get here.
1225 if (zonecfg_in_alt_root()) {
1226 struct stat64 st;
1228 if (stat64(fsptr->zone_fs_special, &st) != -1 &&
1229 S_ISBLK(st.st_mode)) {
1231 * If we're going to mount a block device we need
1232 * to check if that device is already mounted
1233 * somewhere else, and if so, do a lofs mount
1234 * of the device instead of a direct mount
1236 if (check_lofs_needed(zlogp, fsptr) == -1)
1237 return (-1);
1238 } else if (strcmp(fsptr->zone_fs_type, MNTTYPE_LOFS) == 0) {
1240 * For lofs mounts, the special node is inside the
1241 * alternate root. We need lofs resolution for
1242 * this case in order to get at the underlying
1243 * read-write path.
1245 resolve_lofs(zlogp, fsptr->zone_fs_special,
1246 sizeof (fsptr->zone_fs_special));
1251 * Run 'fsck -m' if there's a device to fsck.
1253 if (fsptr->zone_fs_raw[0] != '\0' &&
1254 dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_raw) != 0) {
1255 return (-1);
1256 } else if (isregfile(fsptr->zone_fs_special) == 1 &&
1257 dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_special) != 0) {
1258 return (-1);
1262 * Build up mount option string.
1264 optstr[0] = '\0';
1265 if (fsptr->zone_fs_options != NULL) {
1266 (void) strlcpy(optstr, fsptr->zone_fs_options->zone_fsopt_opt,
1267 sizeof (optstr));
1268 for (optptr = fsptr->zone_fs_options->zone_fsopt_next;
1269 optptr != NULL; optptr = optptr->zone_fsopt_next) {
1270 (void) strlcat(optstr, ",", sizeof (optstr));
1271 (void) strlcat(optstr, optptr->zone_fsopt_opt,
1272 sizeof (optstr));
1276 if ((rv = domount(zlogp, fsptr->zone_fs_type, optstr,
1277 fsptr->zone_fs_special, path)) != 0)
1278 return (rv);
1281 * The mount succeeded. If this was not a mount of /dev then
1282 * we're done.
1284 if (strcmp(fsptr->zone_fs_type, MNTTYPE_DEV) != 0)
1285 return (0);
1288 * We just mounted an instance of a /dev filesystem, so now we
1289 * need to configure it.
1291 return (mount_one_dev(zlogp, path, mount_cmd));
1294 static void
1295 free_fs_data(struct zone_fstab *fsarray, uint_t nelem)
1297 uint_t i;
1299 if (fsarray == NULL)
1300 return;
1301 for (i = 0; i < nelem; i++)
1302 zonecfg_free_fs_option_list(fsarray[i].zone_fs_options);
1303 free(fsarray);
1307 * This function initiates the creation of a small Solaris Environment for
1308 * scratch zone. The Environment creation process is split up into two
1309 * functions(build_mounted_pre_var() and build_mounted_post_var()). It
1310 * is done this way because:
1311 * We need to have both /etc and /var in the root of the scratchzone.
1312 * We loopback mount zone's own /etc and /var into the root of the
1313 * scratch zone. Unlike /etc, /var can be a seperate filesystem. So we
1314 * need to delay the mount of /var till the zone's root gets populated.
1315 * So mounting of localdirs[](/etc and /var) have been moved to the
1316 * build_mounted_post_var() which gets called only after the zone
1317 * specific filesystems are mounted.
1319 * Note that the scratch zone we set up for updating the zone (Z_MNT_UPDATE)
1320 * does not loopback mount the zone's own /etc and /var into the root of the
1321 * scratch zone.
1323 static boolean_t
1324 build_mounted_pre_var(zlog_t *zlogp, char *rootpath,
1325 size_t rootlen, const char *zonepath, char *luroot, size_t lurootlen)
1327 char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1328 const char **cpp;
1329 static const char *mkdirs[] = {
1330 "/system", "/system/contract", "/system/object", "/proc",
1331 "/dev", "/tmp", "/a", NULL
1333 char *altstr;
1334 FILE *fp;
1335 uuid_t uuid;
1337 resolve_lofs(zlogp, rootpath, rootlen);
1338 (void) snprintf(luroot, lurootlen, "%s/lu", zonepath);
1339 resolve_lofs(zlogp, luroot, lurootlen);
1340 (void) snprintf(tmp, sizeof (tmp), "%s/bin", luroot);
1341 (void) symlink("./usr/bin", tmp);
1344 * These are mostly special mount points; not handled here. (See
1345 * zone_mount_early.)
1347 for (cpp = mkdirs; *cpp != NULL; cpp++) {
1348 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1349 if (mkdir(tmp, 0755) != 0) {
1350 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1351 return (B_FALSE);
1355 * This is here to support lucopy. If there's an instance of this same
1356 * zone on the current running system, then we mount its root up as
1357 * read-only inside the scratch zone.
1359 (void) zonecfg_get_uuid(zone_name, uuid);
1360 altstr = strdup(zonecfg_get_root());
1361 if (altstr == NULL) {
1362 zerror(zlogp, B_TRUE, "memory allocation failed");
1363 return (B_FALSE);
1365 zonecfg_set_root("");
1366 (void) strlcpy(tmp, zone_name, sizeof (tmp));
1367 (void) zonecfg_get_name_by_uuid(uuid, tmp, sizeof (tmp));
1368 if (zone_get_rootpath(tmp, fromdir, sizeof (fromdir)) == Z_OK &&
1369 strcmp(fromdir, rootpath) != 0) {
1370 (void) snprintf(tmp, sizeof (tmp), "%s/b", luroot);
1371 if (mkdir(tmp, 0755) != 0) {
1372 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1373 return (B_FALSE);
1375 if (domount(zlogp, MNTTYPE_LOFS, RESOURCE_DEFAULT_OPTS, fromdir,
1376 tmp) != 0) {
1377 zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1378 fromdir);
1379 return (B_FALSE);
1382 zonecfg_set_root(altstr);
1383 free(altstr);
1385 if ((fp = zonecfg_open_scratch(luroot, B_TRUE)) == NULL) {
1386 zerror(zlogp, B_TRUE, "cannot open zone mapfile");
1387 return (B_FALSE);
1389 (void) ftruncate(fileno(fp), 0);
1390 if (zonecfg_add_scratch(fp, zone_name, kernzone, "/") == -1) {
1391 zerror(zlogp, B_TRUE, "cannot add zone mapfile entry");
1393 zonecfg_close_scratch(fp);
1394 (void) snprintf(tmp, sizeof (tmp), "%s/a", luroot);
1395 if (domount(zlogp, MNTTYPE_LOFS, "", rootpath, tmp) != 0)
1396 return (B_FALSE);
1397 (void) strlcpy(rootpath, tmp, rootlen);
1398 return (B_TRUE);
1402 static boolean_t
1403 build_mounted_post_var(zlog_t *zlogp, zone_mnt_t mount_cmd, char *rootpath,
1404 const char *luroot)
1406 char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1407 const char **cpp;
1408 const char **loopdirs;
1409 const char **tmpdirs;
1410 static const char *localdirs[] = {
1411 "/etc", "/var", NULL
1413 static const char *scr_loopdirs[] = {
1414 "/etc/lib", "/etc/fs", "/lib", "/sbin", "/platform",
1415 "/usr", NULL
1417 static const char *upd_loopdirs[] = {
1418 "/etc", "/kernel", "/lib", "/opt", "/platform", "/sbin",
1419 "/usr", "/var", NULL
1421 static const char *scr_tmpdirs[] = {
1422 "/tmp", "/var/run", NULL
1424 static const char *upd_tmpdirs[] = {
1425 "/tmp", "/var/run", "/var/tmp", NULL
1427 struct stat st;
1429 if (mount_cmd == Z_MNT_SCRATCH) {
1431 * These are mounted read-write from the zone undergoing
1432 * upgrade. We must be careful not to 'leak' things from the
1433 * main system into the zone, and this accomplishes that goal.
1435 for (cpp = localdirs; *cpp != NULL; cpp++) {
1436 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot,
1437 *cpp);
1438 (void) snprintf(fromdir, sizeof (fromdir), "%s%s",
1439 rootpath, *cpp);
1440 if (mkdir(tmp, 0755) != 0) {
1441 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1442 return (B_FALSE);
1444 if (domount(zlogp, MNTTYPE_LOFS, "", fromdir, tmp)
1445 != 0) {
1446 zerror(zlogp, B_TRUE, "cannot mount %s on %s",
1447 tmp, *cpp);
1448 return (B_FALSE);
1453 if (mount_cmd == Z_MNT_UPDATE)
1454 loopdirs = upd_loopdirs;
1455 else
1456 loopdirs = scr_loopdirs;
1459 * These are things mounted read-only from the running system because
1460 * they contain binaries that must match system.
1462 for (cpp = loopdirs; *cpp != NULL; cpp++) {
1463 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1464 if (mkdir(tmp, 0755) != 0) {
1465 if (errno != EEXIST) {
1466 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1467 return (B_FALSE);
1469 if (lstat(tmp, &st) != 0) {
1470 zerror(zlogp, B_TRUE, "cannot stat %s", tmp);
1471 return (B_FALSE);
1474 * Ignore any non-directories encountered. These are
1475 * things that have been converted into symlinks
1476 * (/etc/fs and /etc/lib) and no longer need a lofs
1477 * fixup.
1479 if (!S_ISDIR(st.st_mode))
1480 continue;
1482 if (domount(zlogp, MNTTYPE_LOFS, RESOURCE_DEFAULT_OPTS, *cpp,
1483 tmp) != 0) {
1484 zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1485 *cpp);
1486 return (B_FALSE);
1490 if (mount_cmd == Z_MNT_UPDATE)
1491 tmpdirs = upd_tmpdirs;
1492 else
1493 tmpdirs = scr_tmpdirs;
1496 * These are things with tmpfs mounted inside.
1498 for (cpp = tmpdirs; *cpp != NULL; cpp++) {
1499 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1500 if (mount_cmd == Z_MNT_SCRATCH && mkdir(tmp, 0755) != 0 &&
1501 errno != EEXIST) {
1502 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1503 return (B_FALSE);
1507 * We could set the mode for /tmp when we do the mkdir but
1508 * since that can be modified by the umask we will just set
1509 * the correct mode for /tmp now.
1511 if (strcmp(*cpp, "/tmp") == 0 && chmod(tmp, 01777) != 0) {
1512 zerror(zlogp, B_TRUE, "cannot chmod %s", tmp);
1513 return (B_FALSE);
1516 if (domount(zlogp, MNTTYPE_TMPFS, "", "swap", tmp) != 0) {
1517 zerror(zlogp, B_TRUE, "cannot mount swap on %s", *cpp);
1518 return (B_FALSE);
1521 return (B_TRUE);
1524 typedef struct plat_gmount_cb_data {
1525 zlog_t *pgcd_zlogp;
1526 struct zone_fstab **pgcd_fs_tab;
1527 int *pgcd_num_fs;
1528 } plat_gmount_cb_data_t;
1531 * plat_gmount_cb() is a callback function invoked by libbrand to iterate
1532 * through all global brand platform mounts.
1535 plat_gmount_cb(void *data, const char *spec, const char *dir,
1536 const char *fstype, const char *opt)
1538 plat_gmount_cb_data_t *cp = data;
1539 zlog_t *zlogp = cp->pgcd_zlogp;
1540 struct zone_fstab *fs_ptr = *cp->pgcd_fs_tab;
1541 int num_fs = *cp->pgcd_num_fs;
1542 struct zone_fstab *fsp, *tmp_ptr;
1544 num_fs++;
1545 if ((tmp_ptr = realloc(fs_ptr, num_fs * sizeof (*tmp_ptr))) == NULL) {
1546 zerror(zlogp, B_TRUE, "memory allocation failed");
1547 return (-1);
1550 fs_ptr = tmp_ptr;
1551 fsp = &fs_ptr[num_fs - 1];
1553 /* update the callback struct passed in */
1554 *cp->pgcd_fs_tab = fs_ptr;
1555 *cp->pgcd_num_fs = num_fs;
1557 fsp->zone_fs_raw[0] = '\0';
1558 (void) strlcpy(fsp->zone_fs_special, spec,
1559 sizeof (fsp->zone_fs_special));
1560 (void) strlcpy(fsp->zone_fs_dir, dir, sizeof (fsp->zone_fs_dir));
1561 (void) strlcpy(fsp->zone_fs_type, fstype, sizeof (fsp->zone_fs_type));
1562 fsp->zone_fs_options = NULL;
1563 if ((opt != NULL) &&
1564 (zonecfg_add_fs_option(fsp, (char *)opt) != Z_OK)) {
1565 zerror(zlogp, B_FALSE, "error adding property");
1566 return (-1);
1569 return (0);
1572 static int
1573 mount_filesystems_fsent(zone_dochandle_t handle, zlog_t *zlogp,
1574 struct zone_fstab **fs_tabp, int *num_fsp, zone_mnt_t mount_cmd)
1576 struct zone_fstab *tmp_ptr, *fs_ptr, *fsp, fstab;
1577 int num_fs;
1579 num_fs = *num_fsp;
1580 fs_ptr = *fs_tabp;
1582 if (zonecfg_setfsent(handle) != Z_OK) {
1583 zerror(zlogp, B_FALSE, "invalid configuration");
1584 return (-1);
1586 while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1588 * ZFS filesystems will not be accessible under an alternate
1589 * root, since the pool will not be known. Ignore them in this
1590 * case.
1592 if (ALT_MOUNT(mount_cmd) &&
1593 strcmp(fstab.zone_fs_type, MNTTYPE_ZFS) == 0)
1594 continue;
1596 num_fs++;
1597 if ((tmp_ptr = realloc(fs_ptr,
1598 num_fs * sizeof (*tmp_ptr))) == NULL) {
1599 zerror(zlogp, B_TRUE, "memory allocation failed");
1600 (void) zonecfg_endfsent(handle);
1601 return (-1);
1603 /* update the pointers passed in */
1604 *fs_tabp = tmp_ptr;
1605 *num_fsp = num_fs;
1607 fs_ptr = tmp_ptr;
1608 fsp = &fs_ptr[num_fs - 1];
1609 (void) strlcpy(fsp->zone_fs_dir,
1610 fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1611 (void) strlcpy(fsp->zone_fs_raw, fstab.zone_fs_raw,
1612 sizeof (fsp->zone_fs_raw));
1613 (void) strlcpy(fsp->zone_fs_type, fstab.zone_fs_type,
1614 sizeof (fsp->zone_fs_type));
1615 fsp->zone_fs_options = fstab.zone_fs_options;
1618 * For all lofs mounts, make sure that the 'special'
1619 * entry points inside the alternate root. The
1620 * source path for a lofs mount in a given zone needs
1621 * to be relative to the root of the boot environment
1622 * that contains the zone. Note that we don't do this
1623 * for non-lofs mounts since they will have a device
1624 * as a backing store and device paths must always be
1625 * specified relative to the current boot environment.
1627 fsp->zone_fs_special[0] = '\0';
1628 if (strcmp(fsp->zone_fs_type, MNTTYPE_LOFS) == 0) {
1629 (void) strlcat(fsp->zone_fs_special, zonecfg_get_root(),
1630 sizeof (fsp->zone_fs_special));
1632 (void) strlcat(fsp->zone_fs_special, fstab.zone_fs_special,
1633 sizeof (fsp->zone_fs_special));
1635 (void) zonecfg_endfsent(handle);
1636 return (0);
1639 static int
1640 mount_filesystems(zlog_t *zlogp, zone_mnt_t mount_cmd)
1642 char rootpath[MAXPATHLEN];
1643 char zonepath[MAXPATHLEN];
1644 char brand[MAXNAMELEN];
1645 char luroot[MAXPATHLEN];
1646 int i, num_fs = 0;
1647 struct zone_fstab *fs_ptr = NULL;
1648 zone_dochandle_t handle = NULL;
1649 zone_state_t zstate;
1650 brand_handle_t bh;
1651 plat_gmount_cb_data_t cb;
1653 if (zone_get_state(zone_name, &zstate) != Z_OK ||
1654 (zstate != ZONE_STATE_READY && zstate != ZONE_STATE_MOUNTED)) {
1655 zerror(zlogp, B_FALSE,
1656 "zone must be in '%s' or '%s' state to mount file-systems",
1657 zone_state_str(ZONE_STATE_READY),
1658 zone_state_str(ZONE_STATE_MOUNTED));
1659 goto bad;
1662 if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
1663 zerror(zlogp, B_TRUE, "unable to determine zone path");
1664 goto bad;
1667 if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
1668 zerror(zlogp, B_TRUE, "unable to determine zone root");
1669 goto bad;
1672 if ((handle = zonecfg_init_handle()) == NULL) {
1673 zerror(zlogp, B_TRUE, "getting zone configuration handle");
1674 goto bad;
1676 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK ||
1677 zonecfg_setfsent(handle) != Z_OK) {
1678 zerror(zlogp, B_FALSE, "invalid configuration");
1679 goto bad;
1683 * If we are mounting the zone, then we must always use the default
1684 * brand global mounts.
1686 if (ALT_MOUNT(mount_cmd)) {
1687 (void) strlcpy(brand, default_brand, sizeof (brand));
1688 } else {
1689 (void) strlcpy(brand, brand_name, sizeof (brand));
1692 /* Get a handle to the brand info for this zone */
1693 if ((bh = brand_open(brand)) == NULL) {
1694 zerror(zlogp, B_FALSE, "unable to determine zone brand");
1695 zonecfg_fini_handle(handle);
1696 return (-1);
1700 * Get the list of global filesystems to mount from the brand
1701 * configuration.
1703 cb.pgcd_zlogp = zlogp;
1704 cb.pgcd_fs_tab = &fs_ptr;
1705 cb.pgcd_num_fs = &num_fs;
1706 if (brand_platform_iter_gmounts(bh, zone_name, zonepath,
1707 plat_gmount_cb, &cb) != 0) {
1708 zerror(zlogp, B_FALSE, "unable to mount filesystems");
1709 brand_close(bh);
1710 zonecfg_fini_handle(handle);
1711 return (-1);
1713 brand_close(bh);
1716 * Iterate through the rest of the filesystems. Sort them all,
1717 * then mount them in sorted order. This is to make sure the
1718 * higher level directories (e.g., /usr) get mounted before
1719 * any beneath them (e.g., /usr/local).
1721 if (mount_filesystems_fsent(handle, zlogp, &fs_ptr, &num_fs,
1722 mount_cmd) != 0)
1723 goto bad;
1725 zonecfg_fini_handle(handle);
1726 handle = NULL;
1729 * Normally when we mount a zone all the zone filesystems
1730 * get mounted relative to rootpath, which is usually
1731 * <zonepath>/root. But when mounting a zone for administration
1732 * purposes via the zone "mount" state, build_mounted_pre_var()
1733 * updates rootpath to be <zonepath>/lu/a so we'll mount all
1734 * the zones filesystems there instead.
1736 * build_mounted_pre_var() and build_mounted_post_var() will
1737 * also do some extra work to create directories and lofs mount
1738 * a bunch of global zone file system paths into <zonepath>/lu.
1740 * This allows us to be able to enter the zone (now rooted at
1741 * <zonepath>/lu) and run the upgrade/patch tools that are in the
1742 * global zone and have them upgrade the to-be-modified zone's
1743 * files mounted on /a. (Which mirrors the existing standard
1744 * upgrade environment.)
1746 * There is of course one catch. When doing the upgrade
1747 * we need <zoneroot>/lu/dev to be the /dev filesystem
1748 * for the zone and we don't want to have any /dev filesystem
1749 * mounted at <zoneroot>/lu/a/dev. Since /dev is specified
1750 * as a normal zone filesystem by default we'll try to mount
1751 * it at <zoneroot>/lu/a/dev, so we have to detect this
1752 * case and instead mount it at <zoneroot>/lu/dev.
1754 * All this work is done in three phases:
1755 * 1) Create and populate lu directory (build_mounted_pre_var()).
1756 * 2) Mount the required filesystems as per the zone configuration.
1757 * 3) Set up the rest of the scratch zone environment
1758 * (build_mounted_post_var()).
1760 if (ALT_MOUNT(mount_cmd) && !build_mounted_pre_var(zlogp,
1761 rootpath, sizeof (rootpath), zonepath, luroot, sizeof (luroot)))
1762 goto bad;
1764 qsort(fs_ptr, num_fs, sizeof (*fs_ptr), fs_compare);
1766 for (i = 0; i < num_fs; i++) {
1767 if (ALT_MOUNT(mount_cmd) &&
1768 strcmp(fs_ptr[i].zone_fs_dir, "/dev") == 0) {
1769 size_t slen = strlen(rootpath) - 2;
1772 * By default we'll try to mount /dev as /a/dev
1773 * but /dev is special and always goes at the top
1774 * so strip the trailing '/a' from the rootpath.
1776 assert(strcmp(&rootpath[slen], "/a") == 0);
1777 rootpath[slen] = '\0';
1778 if (mount_one(zlogp, &fs_ptr[i], rootpath, mount_cmd)
1779 != 0)
1780 goto bad;
1781 rootpath[slen] = '/';
1782 continue;
1784 if (mount_one(zlogp, &fs_ptr[i], rootpath, mount_cmd) != 0)
1785 goto bad;
1787 if (ALT_MOUNT(mount_cmd) &&
1788 !build_mounted_post_var(zlogp, mount_cmd, rootpath, luroot))
1789 goto bad;
1791 free_fs_data(fs_ptr, num_fs);
1794 * Everything looks fine.
1796 return (0);
1798 bad:
1799 if (handle != NULL)
1800 zonecfg_fini_handle(handle);
1801 free_fs_data(fs_ptr, num_fs);
1802 return (-1);
1805 /* caller makes sure neither parameter is NULL */
1806 static int
1807 addr2netmask(char *prefixstr, int maxprefixlen, uchar_t *maskstr)
1809 int prefixlen;
1811 prefixlen = atoi(prefixstr);
1812 if (prefixlen < 0 || prefixlen > maxprefixlen)
1813 return (1);
1814 while (prefixlen > 0) {
1815 if (prefixlen >= 8) {
1816 *maskstr++ = 0xFF;
1817 prefixlen -= 8;
1818 continue;
1820 *maskstr |= 1 << (8 - prefixlen);
1821 prefixlen--;
1823 return (0);
1827 * Tear down all interfaces belonging to the given zone. This should
1828 * be called with the zone in a state other than "running", so that
1829 * interfaces can't be assigned to the zone after this returns.
1831 * If anything goes wrong, log an error message and return an error.
1833 static int
1834 unconfigure_shared_network_interfaces(zlog_t *zlogp, zoneid_t zone_id)
1836 struct lifnum lifn;
1837 struct lifconf lifc;
1838 struct lifreq *lifrp, lifrl;
1839 int64_t lifc_flags = LIFC_NOXMIT | LIFC_ALLZONES;
1840 int num_ifs, s, i, ret_code = 0;
1841 uint_t bufsize;
1842 char *buf = NULL;
1844 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1845 zerror(zlogp, B_TRUE, "could not get socket");
1846 ret_code = -1;
1847 goto bad;
1849 lifn.lifn_family = AF_UNSPEC;
1850 lifn.lifn_flags = (int)lifc_flags;
1851 if (ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) {
1852 zerror(zlogp, B_TRUE,
1853 "could not determine number of network interfaces");
1854 ret_code = -1;
1855 goto bad;
1857 num_ifs = lifn.lifn_count;
1858 bufsize = num_ifs * sizeof (struct lifreq);
1859 if ((buf = malloc(bufsize)) == NULL) {
1860 zerror(zlogp, B_TRUE, "memory allocation failed");
1861 ret_code = -1;
1862 goto bad;
1864 lifc.lifc_family = AF_UNSPEC;
1865 lifc.lifc_flags = (int)lifc_flags;
1866 lifc.lifc_len = bufsize;
1867 lifc.lifc_buf = buf;
1868 if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) {
1869 zerror(zlogp, B_TRUE, "could not get configured network "
1870 "interfaces");
1871 ret_code = -1;
1872 goto bad;
1874 lifrp = lifc.lifc_req;
1875 for (i = lifc.lifc_len / sizeof (struct lifreq); i > 0; i--, lifrp++) {
1876 (void) close(s);
1877 if ((s = socket(lifrp->lifr_addr.ss_family, SOCK_DGRAM, 0)) <
1878 0) {
1879 zerror(zlogp, B_TRUE, "%s: could not get socket",
1880 lifrl.lifr_name);
1881 ret_code = -1;
1882 continue;
1884 (void) memset(&lifrl, 0, sizeof (lifrl));
1885 (void) strncpy(lifrl.lifr_name, lifrp->lifr_name,
1886 sizeof (lifrl.lifr_name));
1887 if (ioctl(s, SIOCGLIFZONE, (caddr_t)&lifrl) < 0) {
1888 if (errno == ENXIO)
1890 * Interface may have been removed by admin or
1891 * another zone halting.
1893 continue;
1894 zerror(zlogp, B_TRUE,
1895 "%s: could not determine the zone to which this "
1896 "network interface is bound", lifrl.lifr_name);
1897 ret_code = -1;
1898 continue;
1900 if (lifrl.lifr_zoneid == zone_id) {
1901 if (ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifrl) < 0) {
1902 zerror(zlogp, B_TRUE,
1903 "%s: could not remove network interface",
1904 lifrl.lifr_name);
1905 ret_code = -1;
1906 continue;
1910 bad:
1911 if (s > 0)
1912 (void) close(s);
1913 free(buf);
1914 return (ret_code);
1917 static union sockunion {
1918 struct sockaddr sa;
1919 struct sockaddr_in sin;
1920 struct sockaddr_dl sdl;
1921 struct sockaddr_in6 sin6;
1922 } so_dst, so_ifp;
1924 static struct {
1925 struct rt_msghdr hdr;
1926 char space[512];
1927 } rtmsg;
1929 static int
1930 salen(struct sockaddr *sa)
1932 switch (sa->sa_family) {
1933 case AF_INET:
1934 return (sizeof (struct sockaddr_in));
1935 case AF_LINK:
1936 return (sizeof (struct sockaddr_dl));
1937 case AF_INET6:
1938 return (sizeof (struct sockaddr_in6));
1939 default:
1940 return (sizeof (struct sockaddr));
1944 #define ROUNDUP_LONG(a) \
1945 ((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
1948 * Look up which zone is using a given IP address. The address in question
1949 * is expected to have been stuffed into the structure to which lifr points
1950 * via a previous SIOCGLIFADDR ioctl().
1952 * This is done using black router socket magic.
1954 * Return the name of the zone on success or NULL on failure.
1956 * This is a lot of code for a simple task; a new ioctl request to take care
1957 * of this might be a useful RFE.
1960 static char *
1961 who_is_using(zlog_t *zlogp, struct lifreq *lifr)
1963 static char answer[ZONENAME_MAX];
1964 pid_t pid;
1965 int s, rlen, l, i;
1966 char *cp = rtmsg.space;
1967 struct sockaddr_dl *ifp = NULL;
1968 struct sockaddr *sa;
1969 char save_if_name[LIFNAMSIZ];
1971 answer[0] = '\0';
1973 pid = getpid();
1974 if ((s = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
1975 zerror(zlogp, B_TRUE, "could not get routing socket");
1976 return (NULL);
1979 if (lifr->lifr_addr.ss_family == AF_INET) {
1980 struct sockaddr_in *sin4;
1982 so_dst.sa.sa_family = AF_INET;
1983 sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
1984 so_dst.sin.sin_addr = sin4->sin_addr;
1985 } else {
1986 struct sockaddr_in6 *sin6;
1988 so_dst.sa.sa_family = AF_INET6;
1989 sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
1990 so_dst.sin6.sin6_addr = sin6->sin6_addr;
1993 so_ifp.sa.sa_family = AF_LINK;
1995 (void) memset(&rtmsg, 0, sizeof (rtmsg));
1996 rtmsg.hdr.rtm_type = RTM_GET;
1997 rtmsg.hdr.rtm_flags = RTF_UP | RTF_HOST;
1998 rtmsg.hdr.rtm_version = RTM_VERSION;
1999 rtmsg.hdr.rtm_seq = ++rts_seqno;
2000 rtmsg.hdr.rtm_addrs = RTA_IFP | RTA_DST;
2002 l = ROUNDUP_LONG(salen(&so_dst.sa));
2003 (void) memmove(cp, &(so_dst), l);
2004 cp += l;
2005 l = ROUNDUP_LONG(salen(&so_ifp.sa));
2006 (void) memmove(cp, &(so_ifp), l);
2007 cp += l;
2009 rtmsg.hdr.rtm_msglen = l = cp - (char *)&rtmsg;
2011 if ((rlen = write(s, &rtmsg, l)) < 0) {
2012 zerror(zlogp, B_TRUE, "writing to routing socket");
2013 return (NULL);
2014 } else if (rlen < (int)rtmsg.hdr.rtm_msglen) {
2015 zerror(zlogp, B_TRUE,
2016 "write to routing socket got only %d for len\n", rlen);
2017 return (NULL);
2019 do {
2020 l = read(s, &rtmsg, sizeof (rtmsg));
2021 } while (l > 0 && (rtmsg.hdr.rtm_seq != rts_seqno ||
2022 rtmsg.hdr.rtm_pid != pid));
2023 if (l < 0) {
2024 zerror(zlogp, B_TRUE, "reading from routing socket");
2025 return (NULL);
2028 if (rtmsg.hdr.rtm_version != RTM_VERSION) {
2029 zerror(zlogp, B_FALSE,
2030 "routing message version %d not understood",
2031 rtmsg.hdr.rtm_version);
2032 return (NULL);
2034 if (rtmsg.hdr.rtm_msglen != (ushort_t)l) {
2035 zerror(zlogp, B_FALSE, "message length mismatch, "
2036 "expected %d bytes, returned %d bytes",
2037 rtmsg.hdr.rtm_msglen, l);
2038 return (NULL);
2040 if (rtmsg.hdr.rtm_errno != 0) {
2041 errno = rtmsg.hdr.rtm_errno;
2042 zerror(zlogp, B_TRUE, "RTM_GET routing socket message");
2043 return (NULL);
2045 if ((rtmsg.hdr.rtm_addrs & RTA_IFP) == 0) {
2046 zerror(zlogp, B_FALSE, "network interface not found");
2047 return (NULL);
2049 cp = ((char *)(&rtmsg.hdr + 1));
2050 for (i = 1; i != 0; i <<= 1) {
2051 /* LINTED E_BAD_PTR_CAST_ALIGN */
2052 sa = (struct sockaddr *)cp;
2053 if (i != RTA_IFP) {
2054 if ((i & rtmsg.hdr.rtm_addrs) != 0)
2055 cp += ROUNDUP_LONG(salen(sa));
2056 continue;
2058 if (sa->sa_family == AF_LINK &&
2059 ((struct sockaddr_dl *)sa)->sdl_nlen != 0)
2060 ifp = (struct sockaddr_dl *)sa;
2061 break;
2063 if (ifp == NULL) {
2064 zerror(zlogp, B_FALSE, "network interface could not be "
2065 "determined");
2066 return (NULL);
2070 * We need to set the I/F name to what we got above, then do the
2071 * appropriate ioctl to get its zone name. But lifr->lifr_name is
2072 * used by the calling function to do a REMOVEIF, so if we leave the
2073 * "good" zone's I/F name in place, *that* I/F will be removed instead
2074 * of the bad one. So we save the old (bad) I/F name before over-
2075 * writing it and doing the ioctl, then restore it after the ioctl.
2077 (void) strlcpy(save_if_name, lifr->lifr_name, sizeof (save_if_name));
2078 (void) strncpy(lifr->lifr_name, ifp->sdl_data, ifp->sdl_nlen);
2079 lifr->lifr_name[ifp->sdl_nlen] = '\0';
2080 i = ioctl(s, SIOCGLIFZONE, lifr);
2081 (void) strlcpy(lifr->lifr_name, save_if_name, sizeof (save_if_name));
2082 if (i < 0) {
2083 zerror(zlogp, B_TRUE,
2084 "%s: could not determine the zone network interface "
2085 "belongs to", lifr->lifr_name);
2086 return (NULL);
2088 if (getzonenamebyid(lifr->lifr_zoneid, answer, sizeof (answer)) < 0)
2089 (void) snprintf(answer, sizeof (answer), "%d",
2090 lifr->lifr_zoneid);
2092 if (strlen(answer) > 0)
2093 return (answer);
2094 return (NULL);
2098 * Configures a single interface: a new virtual interface is added, based on
2099 * the physical interface nwiftabptr->zone_nwif_physical, with the address
2100 * specified in nwiftabptr->zone_nwif_address, for zone zone_id. Note that
2101 * the "address" can be an IPv6 address (with a /prefixlength required), an
2102 * IPv4 address (with a /prefixlength optional), or a name; for the latter,
2103 * an IPv4 name-to-address resolution will be attempted.
2105 * If anything goes wrong, we log an detailed error message, attempt to tear
2106 * down whatever we set up and return an error.
2108 static int
2109 configure_one_interface(zlog_t *zlogp, zoneid_t zone_id,
2110 struct zone_nwiftab *nwiftabptr)
2112 struct lifreq lifr;
2113 struct sockaddr_in netmask4;
2114 struct sockaddr_in6 netmask6;
2115 struct sockaddr_storage laddr;
2116 struct in_addr in4;
2117 sa_family_t af;
2118 char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
2119 int s;
2120 boolean_t got_netmask = B_FALSE;
2121 boolean_t is_loopback = B_FALSE;
2122 char addrstr4[INET_ADDRSTRLEN];
2123 int res;
2125 res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
2126 if (res != Z_OK) {
2127 zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
2128 nwiftabptr->zone_nwif_address);
2129 return (-1);
2131 af = lifr.lifr_addr.ss_family;
2132 if (af == AF_INET)
2133 in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
2134 if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
2135 zerror(zlogp, B_TRUE, "could not get socket");
2136 return (-1);
2140 * This is a similar kind of "hack" like in addif() to get around
2141 * the problem of SIOCLIFADDIF. The problem is that this ioctl
2142 * does not include the netmask when adding a logical interface.
2143 * To get around this problem, we first add the logical interface
2144 * with a 0 address. After that, we set the netmask if provided.
2145 * Finally we set the interface address.
2147 laddr = lifr.lifr_addr;
2148 (void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
2149 sizeof (lifr.lifr_name));
2150 (void) memset(&lifr.lifr_addr, 0, sizeof (lifr.lifr_addr));
2152 if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
2154 * Here, we know that the interface can't be brought up.
2155 * A similar warning message was already printed out to
2156 * the console by zoneadm(1M) so instead we log the
2157 * message to syslog and continue.
2159 zerror(&logsys, B_TRUE, "WARNING: skipping network interface "
2160 "'%s' which may not be present/plumbed in the "
2161 "global zone.", lifr.lifr_name);
2162 (void) close(s);
2163 return (Z_OK);
2166 /* Preserve literal IPv4 address for later potential printing. */
2167 if (af == AF_INET)
2168 (void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
2170 lifr.lifr_zoneid = zone_id;
2171 if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
2172 zerror(zlogp, B_TRUE, "%s: could not place network interface "
2173 "into zone", lifr.lifr_name);
2174 goto bad;
2178 * Loopback interface will use the default netmask assigned, if no
2179 * netmask is found.
2181 if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
2182 is_loopback = B_TRUE;
2184 if (af == AF_INET) {
2186 * The IPv4 netmask can be determined either
2187 * directly if a prefix length was supplied with
2188 * the address or via the netmasks database. Not
2189 * being able to determine it is a common failure,
2190 * but it often is not fatal to operation of the
2191 * interface. In that case, a warning will be
2192 * printed after the rest of the interface's
2193 * parameters have been configured.
2195 (void) memset(&netmask4, 0, sizeof (netmask4));
2196 if (slashp != NULL) {
2197 if (addr2netmask(slashp + 1, V4_ADDR_LEN,
2198 (uchar_t *)&netmask4.sin_addr) != 0) {
2199 *slashp = '/';
2200 zerror(zlogp, B_FALSE,
2201 "%s: invalid prefix length in %s",
2202 lifr.lifr_name,
2203 nwiftabptr->zone_nwif_address);
2204 goto bad;
2206 got_netmask = B_TRUE;
2207 } else if (getnetmaskbyaddr(in4,
2208 &netmask4.sin_addr) == 0) {
2209 got_netmask = B_TRUE;
2211 if (got_netmask) {
2212 netmask4.sin_family = af;
2213 (void) memcpy(&lifr.lifr_addr, &netmask4,
2214 sizeof (netmask4));
2216 } else {
2217 (void) memset(&netmask6, 0, sizeof (netmask6));
2218 if (addr2netmask(slashp + 1, V6_ADDR_LEN,
2219 (uchar_t *)&netmask6.sin6_addr) != 0) {
2220 *slashp = '/';
2221 zerror(zlogp, B_FALSE,
2222 "%s: invalid prefix length in %s",
2223 lifr.lifr_name,
2224 nwiftabptr->zone_nwif_address);
2225 goto bad;
2227 got_netmask = B_TRUE;
2228 netmask6.sin6_family = af;
2229 (void) memcpy(&lifr.lifr_addr, &netmask6,
2230 sizeof (netmask6));
2232 if (got_netmask &&
2233 ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
2234 zerror(zlogp, B_TRUE, "%s: could not set netmask",
2235 lifr.lifr_name);
2236 goto bad;
2239 /* Set the interface address */
2240 lifr.lifr_addr = laddr;
2241 if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2242 zerror(zlogp, B_TRUE,
2243 "%s: could not set IP address to %s",
2244 lifr.lifr_name, nwiftabptr->zone_nwif_address);
2245 goto bad;
2248 if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2249 zerror(zlogp, B_TRUE, "%s: could not get flags",
2250 lifr.lifr_name);
2251 goto bad;
2253 lifr.lifr_flags |= IFF_UP;
2254 if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
2255 int save_errno = errno;
2256 char *zone_using;
2259 * If we failed with something other than EADDRNOTAVAIL,
2260 * then skip to the end. Otherwise, look up our address,
2261 * then call a function to determine which zone is already
2262 * using that address.
2264 if (errno != EADDRNOTAVAIL) {
2265 zerror(zlogp, B_TRUE,
2266 "%s: could not bring network interface up",
2267 lifr.lifr_name);
2268 goto bad;
2270 if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2271 zerror(zlogp, B_TRUE, "%s: could not get address",
2272 lifr.lifr_name);
2273 goto bad;
2275 zone_using = who_is_using(zlogp, &lifr);
2276 errno = save_errno;
2277 if (zone_using == NULL)
2278 zerror(zlogp, B_TRUE,
2279 "%s: could not bring network interface up",
2280 lifr.lifr_name);
2281 else
2282 zerror(zlogp, B_TRUE, "%s: could not bring network "
2283 "interface up: address in use by zone '%s'",
2284 lifr.lifr_name, zone_using);
2285 goto bad;
2288 if (!got_netmask && !is_loopback) {
2290 * A common, but often non-fatal problem, is that the system
2291 * cannot find the netmask for an interface address. This is
2292 * often caused by it being only in /etc/inet/netmasks, but
2293 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2294 * in that. This doesn't show up at boot because the netmask
2295 * is obtained from /etc/inet/netmasks when no network
2296 * interfaces are up, but isn't consulted when NIS/NIS+ is
2297 * available. We warn the user here that something like this
2298 * has happened and we're just running with a default and
2299 * possible incorrect netmask.
2301 char buffer[INET6_ADDRSTRLEN];
2302 void *addr;
2303 const char *nomatch = "no matching subnet found in netmasks(4)";
2305 if (af == AF_INET)
2306 addr = &((struct sockaddr_in *)
2307 (&lifr.lifr_addr))->sin_addr;
2308 else
2309 addr = &((struct sockaddr_in6 *)
2310 (&lifr.lifr_addr))->sin6_addr;
2313 * Find out what netmask the interface is going to be using.
2314 * If we just brought up an IPMP data address on an underlying
2315 * interface above, the address will have already migrated, so
2316 * the SIOCGLIFNETMASK won't be able to find it (but we need
2317 * to bring the address up to get the actual netmask). Just
2318 * omit printing the actual netmask in this corner-case.
2320 if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2321 inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL) {
2322 zerror(zlogp, B_FALSE, "WARNING: %s; using default.",
2323 nomatch);
2324 } else {
2325 zerror(zlogp, B_FALSE,
2326 "WARNING: %s: %s: %s; using default of %s.",
2327 lifr.lifr_name, nomatch, addrstr4, buffer);
2332 * If a default router was specified for this interface
2333 * set the route now. Ignore if already set.
2335 if (strlen(nwiftabptr->zone_nwif_defrouter) > 0) {
2336 int status;
2337 char *argv[7];
2339 argv[0] = "route";
2340 argv[1] = "add";
2341 argv[2] = "-ifp";
2342 argv[3] = nwiftabptr->zone_nwif_physical;
2343 argv[4] = "default";
2344 argv[5] = nwiftabptr->zone_nwif_defrouter;
2345 argv[6] = NULL;
2347 status = forkexec(zlogp, "/usr/sbin/route", argv);
2348 if (status != 0 && status != EEXIST)
2349 zerror(zlogp, B_FALSE, "Unable to set route for "
2350 "interface %s to %s\n",
2351 nwiftabptr->zone_nwif_physical,
2352 nwiftabptr->zone_nwif_defrouter);
2355 (void) close(s);
2356 return (Z_OK);
2357 bad:
2358 (void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2359 (void) close(s);
2360 return (-1);
2364 * Sets up network interfaces based on information from the zone configuration.
2365 * IPv4 and IPv6 loopback interfaces are set up "for free", modeling the global
2366 * system.
2368 * If anything goes wrong, we log a general error message, attempt to tear down
2369 * whatever we set up, and return an error.
2371 static int
2372 configure_shared_network_interfaces(zlog_t *zlogp)
2374 zone_dochandle_t handle;
2375 struct zone_nwiftab nwiftab, loopback_iftab;
2376 zoneid_t zoneid;
2378 if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2379 zerror(zlogp, B_TRUE, "unable to get zoneid");
2380 return (-1);
2383 if ((handle = zonecfg_init_handle()) == NULL) {
2384 zerror(zlogp, B_TRUE, "getting zone configuration handle");
2385 return (-1);
2387 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2388 zerror(zlogp, B_FALSE, "invalid configuration");
2389 zonecfg_fini_handle(handle);
2390 return (-1);
2392 if (zonecfg_setnwifent(handle) == Z_OK) {
2393 for (;;) {
2394 if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2395 break;
2396 if (configure_one_interface(zlogp, zoneid, &nwiftab) !=
2397 Z_OK) {
2398 (void) zonecfg_endnwifent(handle);
2399 zonecfg_fini_handle(handle);
2400 return (-1);
2403 (void) zonecfg_endnwifent(handle);
2405 zonecfg_fini_handle(handle);
2406 (void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2407 sizeof (loopback_iftab.zone_nwif_physical));
2408 (void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2409 sizeof (loopback_iftab.zone_nwif_address));
2410 loopback_iftab.zone_nwif_defrouter[0] = '\0';
2411 if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2412 return (-1);
2414 /* Always plumb up the IPv6 loopback interface. */
2415 (void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2416 sizeof (loopback_iftab.zone_nwif_address));
2417 if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2418 return (-1);
2419 return (0);
2422 static void
2423 zdlerror(zlog_t *zlogp, dladm_status_t err, const char *dlname, const char *str)
2425 char errmsg[DLADM_STRSIZE];
2427 (void) dladm_status2str(err, errmsg);
2428 zerror(zlogp, B_FALSE, "%s '%s': %s", str, dlname, errmsg);
2431 static int
2432 add_datalink(zlog_t *zlogp, char *zone_name, datalink_id_t linkid, char *dlname)
2434 dladm_status_t err;
2435 boolean_t cpuset, poolset;
2436 char *poolp;
2438 /* First check if it's in use by global zone. */
2439 if (zonecfg_ifname_exists(AF_INET, dlname) ||
2440 zonecfg_ifname_exists(AF_INET6, dlname)) {
2441 zerror(zlogp, B_FALSE, "WARNING: skipping network interface "
2442 "'%s' which is used in the global zone", dlname);
2443 return (-1);
2446 /* Set zoneid of this link. */
2447 err = dladm_set_linkprop(dld_handle, linkid, "zone", &zone_name, 1,
2448 DLADM_OPT_ACTIVE);
2449 if (err != DLADM_STATUS_OK) {
2450 zdlerror(zlogp, err, dlname,
2451 "WARNING: unable to add network interface");
2452 return (-1);
2456 * Set the pool of this link if the zone has a pool and
2457 * neither the cpus nor the pool datalink property is
2458 * already set.
2460 err = dladm_linkprop_is_set(dld_handle, linkid, DLADM_PROP_VAL_CURRENT,
2461 "cpus", &cpuset);
2462 if (err != DLADM_STATUS_OK) {
2463 zdlerror(zlogp, err, dlname,
2464 "WARNING: unable to check if cpus link property is set");
2466 err = dladm_linkprop_is_set(dld_handle, linkid, DLADM_PROP_VAL_CURRENT,
2467 "pool", &poolset);
2468 if (err != DLADM_STATUS_OK) {
2469 zdlerror(zlogp, err, dlname,
2470 "WARNING: unable to check if pool link property is set");
2473 if ((strlen(pool_name) != 0) && !cpuset && !poolset) {
2474 poolp = pool_name;
2475 err = dladm_set_linkprop(dld_handle, linkid, "pool",
2476 &poolp, 1, DLADM_OPT_ACTIVE);
2477 if (err != DLADM_STATUS_OK) {
2478 zerror(zlogp, B_FALSE, "WARNING: unable to set "
2479 "pool %s to datalink %s", pool_name, dlname);
2480 bzero(pool_name, sizeof (pool_name));
2482 } else {
2483 bzero(pool_name, sizeof (pool_name));
2485 return (0);
2488 static boolean_t
2489 sockaddr_to_str(sa_family_t af, const struct sockaddr *sockaddr,
2490 char *straddr, size_t len)
2492 struct sockaddr_in *sin;
2493 struct sockaddr_in6 *sin6;
2494 const char *str = NULL;
2496 if (af == AF_INET) {
2497 /* LINTED E_BAD_PTR_CAST_ALIGN */
2498 sin = SIN(sockaddr);
2499 str = inet_ntop(AF_INET, (void *)&sin->sin_addr, straddr, len);
2500 } else if (af == AF_INET6) {
2501 /* LINTED E_BAD_PTR_CAST_ALIGN */
2502 sin6 = SIN6(sockaddr);
2503 str = inet_ntop(AF_INET6, (void *)&sin6->sin6_addr, straddr,
2504 len);
2507 return (str != NULL);
2510 static int
2511 ipv4_prefixlen(struct sockaddr_in *sin)
2513 struct sockaddr_in *m;
2514 struct sockaddr_storage mask;
2516 m = SIN(&mask);
2517 m->sin_family = AF_INET;
2518 if (getnetmaskbyaddr(sin->sin_addr, &m->sin_addr) == 0) {
2519 return (mask2plen((struct sockaddr *)&mask));
2520 } else if (IN_CLASSA(htonl(sin->sin_addr.s_addr))) {
2521 return (8);
2522 } else if (IN_CLASSB(ntohl(sin->sin_addr.s_addr))) {
2523 return (16);
2524 } else if (IN_CLASSC(ntohl(sin->sin_addr.s_addr))) {
2525 return (24);
2527 return (0);
2530 static int
2531 zone_setattr_network(int type, zoneid_t zoneid, datalink_id_t linkid,
2532 void *buf, size_t bufsize)
2534 zone_net_data_t *zndata;
2535 size_t znsize;
2536 int err;
2538 znsize = sizeof (*zndata) + bufsize;
2539 zndata = calloc(1, znsize);
2540 if (zndata == NULL)
2541 return (ENOMEM);
2542 zndata->zn_type = type;
2543 zndata->zn_len = bufsize;
2544 zndata->zn_linkid = linkid;
2545 bcopy(buf, zndata->zn_val, zndata->zn_len);
2546 err = zone_setattr(zoneid, ZONE_ATTR_NETWORK, zndata, znsize);
2547 free(zndata);
2548 return (err);
2551 static int
2552 add_net_for_linkid(zlog_t *zlogp, zoneid_t zoneid, zone_addr_list_t *start)
2554 struct lifreq lifr;
2555 char **astr, *address;
2556 dladm_status_t dlstatus;
2557 char *ip_nospoof = "ip-nospoof";
2558 int nnet, naddr, err = 0, j;
2559 size_t zlen, cpleft;
2560 zone_addr_list_t *ptr, *end;
2561 char tmp[INET6_ADDRSTRLEN], *maskstr;
2562 char *zaddr, *cp;
2563 struct in6_addr *routes = NULL;
2564 boolean_t is_set;
2565 datalink_id_t linkid;
2567 assert(start != NULL);
2568 naddr = 0; /* number of addresses */
2569 nnet = 0; /* number of net resources */
2570 linkid = start->za_linkid;
2571 for (ptr = start; ptr != NULL && ptr->za_linkid == linkid;
2572 ptr = ptr->za_next) {
2573 nnet++;
2575 end = ptr;
2576 zlen = nnet * (INET6_ADDRSTRLEN + 1);
2577 astr = calloc(1, nnet * sizeof (uintptr_t));
2578 zaddr = calloc(1, zlen);
2579 if (astr == NULL || zaddr == NULL) {
2580 err = ENOMEM;
2581 goto done;
2583 cp = zaddr;
2584 cpleft = zlen;
2585 j = 0;
2586 for (ptr = start; ptr != end; ptr = ptr->za_next) {
2587 address = ptr->za_nwiftab.zone_nwif_allowed_address;
2588 if (address[0] == '\0')
2589 continue;
2590 (void) snprintf(tmp, sizeof (tmp), "%s", address);
2592 * Validate the data. zonecfg_valid_net_address() clobbers
2593 * the /<mask> in the address string.
2595 if (zonecfg_valid_net_address(address, &lifr) != Z_OK) {
2596 zerror(zlogp, B_FALSE, "invalid address [%s]\n",
2597 address);
2598 err = EINVAL;
2599 goto done;
2602 * convert any hostnames to numeric address strings.
2604 if (!sockaddr_to_str(lifr.lifr_addr.ss_family,
2605 (const struct sockaddr *)&lifr.lifr_addr, cp, cpleft)) {
2606 err = EINVAL;
2607 goto done;
2610 * make a copy of the numeric string for the data needed
2611 * by the "allowed-ips" datalink property.
2613 astr[j] = strdup(cp);
2614 if (astr[j] == NULL) {
2615 err = ENOMEM;
2616 goto done;
2618 j++;
2620 * compute the default netmask from the address, if necessary
2622 if ((maskstr = strchr(tmp, '/')) == NULL) {
2623 int prefixlen;
2625 if (lifr.lifr_addr.ss_family == AF_INET) {
2626 prefixlen = ipv4_prefixlen(
2627 SIN(&lifr.lifr_addr));
2628 } else {
2629 struct sockaddr_in6 *sin6;
2631 sin6 = SIN6(&lifr.lifr_addr);
2632 if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
2633 prefixlen = 10;
2634 else
2635 prefixlen = 64;
2637 (void) snprintf(tmp, sizeof (tmp), "%d", prefixlen);
2638 maskstr = tmp;
2639 } else {
2640 maskstr++;
2642 /* append the "/<netmask>" */
2643 (void) strlcat(cp, "/", cpleft);
2644 (void) strlcat(cp, maskstr, cpleft);
2645 (void) strlcat(cp, ",", cpleft);
2646 cp += strnlen(cp, zlen);
2647 cpleft = &zaddr[INET6_ADDRSTRLEN] - cp;
2649 naddr = j; /* the actual number of addresses in the net resource */
2650 assert(naddr <= nnet);
2653 * zonecfg has already verified that the defrouter property can only
2654 * be set if there is at least one address defined for the net resource.
2655 * If j is 0, there are no addresses defined, and therefore no routers
2656 * to configure, and we are done at that point.
2658 if (j == 0)
2659 goto done;
2661 /* over-write last ',' with '\0' */
2662 zaddr[strnlen(zaddr, zlen) + 1] = '\0';
2665 * First make sure L3 protection is not already set on the link.
2667 dlstatus = dladm_linkprop_is_set(dld_handle, linkid, DLADM_OPT_ACTIVE,
2668 "protection", &is_set);
2669 if (dlstatus != DLADM_STATUS_OK) {
2670 err = EINVAL;
2671 zerror(zlogp, B_FALSE, "unable to check if protection is set");
2672 goto done;
2674 if (is_set) {
2675 err = EINVAL;
2676 zerror(zlogp, B_FALSE, "Protection is already set");
2677 goto done;
2679 dlstatus = dladm_linkprop_is_set(dld_handle, linkid, DLADM_OPT_ACTIVE,
2680 "allowed-ips", &is_set);
2681 if (dlstatus != DLADM_STATUS_OK) {
2682 err = EINVAL;
2683 zerror(zlogp, B_FALSE, "unable to check if allowed-ips is set");
2684 goto done;
2686 if (is_set) {
2687 zerror(zlogp, B_FALSE, "allowed-ips is already set");
2688 err = EINVAL;
2689 goto done;
2693 * Enable ip-nospoof for the link, and add address to the allowed-ips
2694 * list.
2696 dlstatus = dladm_set_linkprop(dld_handle, linkid, "protection",
2697 &ip_nospoof, 1, DLADM_OPT_ACTIVE);
2698 if (dlstatus != DLADM_STATUS_OK) {
2699 zerror(zlogp, B_FALSE, "could not set protection\n");
2700 err = EINVAL;
2701 goto done;
2703 dlstatus = dladm_set_linkprop(dld_handle, linkid, "allowed-ips",
2704 astr, naddr, DLADM_OPT_ACTIVE);
2705 if (dlstatus != DLADM_STATUS_OK) {
2706 zerror(zlogp, B_FALSE, "could not set allowed-ips\n");
2707 err = EINVAL;
2708 goto done;
2711 /* now set the address in the data-store */
2712 err = zone_setattr_network(ZONE_NETWORK_ADDRESS, zoneid, linkid,
2713 zaddr, strnlen(zaddr, zlen) + 1);
2714 if (err != 0)
2715 goto done;
2718 * add the defaultrouters
2720 routes = calloc(1, nnet * sizeof (*routes));
2721 j = 0;
2722 for (ptr = start; ptr != end; ptr = ptr->za_next) {
2723 address = ptr->za_nwiftab.zone_nwif_defrouter;
2724 if (address[0] == '\0')
2725 continue;
2726 if (strchr(address, '/') == NULL && strchr(address, ':') != 0) {
2728 * zonecfg_valid_net_address() expects numeric IPv6
2729 * addresses to have a CIDR format netmask.
2731 (void) snprintf(tmp, sizeof (tmp), "/%d", V6_ADDR_LEN);
2732 (void) strlcat(address, tmp, INET6_ADDRSTRLEN);
2734 if (zonecfg_valid_net_address(address, &lifr) != Z_OK) {
2735 zerror(zlogp, B_FALSE,
2736 "invalid router [%s]\n", address);
2737 err = EINVAL;
2738 goto done;
2740 if (lifr.lifr_addr.ss_family == AF_INET6) {
2741 routes[j] = SIN6(&lifr.lifr_addr)->sin6_addr;
2742 } else {
2743 IN6_INADDR_TO_V4MAPPED(&SIN(&lifr.lifr_addr)->sin_addr,
2744 &routes[j]);
2746 j++;
2748 assert(j <= nnet);
2749 if (j > 0) {
2750 err = zone_setattr_network(ZONE_NETWORK_DEFROUTER, zoneid,
2751 linkid, routes, j * sizeof (*routes));
2753 done:
2754 free(routes);
2755 for (j = 0; j < naddr; j++)
2756 free(astr[j]);
2757 free(astr);
2758 free(zaddr);
2759 return (err);
2763 static int
2764 add_net(zlog_t *zlogp, zoneid_t zoneid, zone_addr_list_t *zalist)
2766 zone_addr_list_t *ptr;
2767 datalink_id_t linkid;
2768 int err;
2770 if (zalist == NULL)
2771 return (0);
2773 linkid = zalist->za_linkid;
2775 err = add_net_for_linkid(zlogp, zoneid, zalist);
2776 if (err != 0)
2777 return (err);
2779 for (ptr = zalist; ptr != NULL; ptr = ptr->za_next) {
2780 if (ptr->za_linkid == linkid)
2781 continue;
2782 linkid = ptr->za_linkid;
2783 err = add_net_for_linkid(zlogp, zoneid, ptr);
2784 if (err != 0)
2785 return (err);
2787 return (0);
2791 * Add "new" to the list of network interfaces to be configured by
2792 * add_net on zone boot in "old". The list of interfaces in "old" is
2793 * sorted by datalink_id_t, with interfaces sorted FIFO for a given
2794 * datalink_id_t.
2796 * Returns the merged list of IP interfaces containing "old" and "new"
2798 static zone_addr_list_t *
2799 add_ip_interface(zone_addr_list_t *old, zone_addr_list_t *new)
2801 zone_addr_list_t *ptr, *next;
2802 datalink_id_t linkid = new->za_linkid;
2804 assert(old != new);
2806 if (old == NULL)
2807 return (new);
2808 for (ptr = old; ptr != NULL; ptr = ptr->za_next) {
2809 if (ptr->za_linkid == linkid)
2810 break;
2812 if (ptr == NULL) {
2813 /* linkid does not already exist, add to the beginning */
2814 new->za_next = old;
2815 return (new);
2818 * adding to the middle of the list; ptr points at the first
2819 * occurrence of linkid. Find the last occurrence.
2821 while ((next = ptr->za_next) != NULL) {
2822 if (next->za_linkid != linkid)
2823 break;
2824 ptr = next;
2826 /* insert new after ptr */
2827 new->za_next = next;
2828 ptr->za_next = new;
2829 return (old);
2832 void
2833 free_ip_interface(zone_addr_list_t *zalist)
2835 zone_addr_list_t *ptr, *new;
2837 for (ptr = zalist; ptr != NULL; ) {
2838 new = ptr;
2839 ptr = ptr->za_next;
2840 free(new);
2845 * Add the kernel access control information for the interface names.
2846 * If anything goes wrong, we log a general error message, attempt to tear down
2847 * whatever we set up, and return an error.
2849 static int
2850 configure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
2852 zone_dochandle_t handle;
2853 struct zone_nwiftab nwiftab;
2854 char rootpath[MAXPATHLEN];
2855 char path[MAXPATHLEN];
2856 datalink_id_t linkid;
2857 di_prof_t prof = NULL;
2858 boolean_t added = B_FALSE;
2859 zone_addr_list_t *zalist = NULL, *new;
2861 if ((handle = zonecfg_init_handle()) == NULL) {
2862 zerror(zlogp, B_TRUE, "getting zone configuration handle");
2863 return (-1);
2865 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2866 zerror(zlogp, B_FALSE, "invalid configuration");
2867 zonecfg_fini_handle(handle);
2868 return (-1);
2871 if (zonecfg_setnwifent(handle) != Z_OK) {
2872 zonecfg_fini_handle(handle);
2873 return (0);
2876 for (;;) {
2877 if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2878 break;
2880 if (prof == NULL) {
2881 if (zone_get_devroot(zone_name, rootpath,
2882 sizeof (rootpath)) != Z_OK) {
2883 (void) zonecfg_endnwifent(handle);
2884 zonecfg_fini_handle(handle);
2885 zerror(zlogp, B_TRUE,
2886 "unable to determine dev root");
2887 return (-1);
2889 (void) snprintf(path, sizeof (path), "%s%s", rootpath,
2890 "/dev");
2891 if (di_prof_init(path, &prof) != 0) {
2892 (void) zonecfg_endnwifent(handle);
2893 zonecfg_fini_handle(handle);
2894 zerror(zlogp, B_TRUE,
2895 "failed to initialize profile");
2896 return (-1);
2901 * Create the /dev entry for backward compatibility.
2902 * Only create the /dev entry if it's not in use.
2903 * Note that the zone still boots when the assigned
2904 * interface is inaccessible, used by others, etc.
2905 * Also, when vanity naming is used, some interface do
2906 * do not have corresponding /dev node names (for example,
2907 * vanity named aggregations). The /dev entry is not
2908 * created in that case. The /dev/net entry is always
2909 * accessible.
2911 if (dladm_name2info(dld_handle, nwiftab.zone_nwif_physical,
2912 &linkid, NULL, NULL, NULL) == DLADM_STATUS_OK &&
2913 add_datalink(zlogp, zone_name, linkid,
2914 nwiftab.zone_nwif_physical) == 0) {
2915 added = B_TRUE;
2916 } else {
2917 (void) zonecfg_endnwifent(handle);
2918 zonecfg_fini_handle(handle);
2919 zerror(zlogp, B_TRUE, "failed to add network device");
2920 return (-1);
2922 /* set up the new IP interface, and add them all later */
2923 new = malloc(sizeof (*new));
2924 if (new == NULL) {
2925 zerror(zlogp, B_TRUE, "no memory for %s",
2926 nwiftab.zone_nwif_physical);
2927 zonecfg_fini_handle(handle);
2928 free_ip_interface(zalist);
2930 bzero(new, sizeof (*new));
2931 new->za_nwiftab = nwiftab;
2932 new->za_linkid = linkid;
2933 zalist = add_ip_interface(zalist, new);
2935 if (zalist != NULL) {
2936 if ((errno = add_net(zlogp, zoneid, zalist)) != 0) {
2937 (void) zonecfg_endnwifent(handle);
2938 zonecfg_fini_handle(handle);
2939 zerror(zlogp, B_TRUE, "failed to add address");
2940 free_ip_interface(zalist);
2941 return (-1);
2943 free_ip_interface(zalist);
2945 (void) zonecfg_endnwifent(handle);
2946 zonecfg_fini_handle(handle);
2948 if (prof != NULL && added) {
2949 if (di_prof_commit(prof) != 0) {
2950 zerror(zlogp, B_TRUE, "failed to commit profile");
2951 return (-1);
2954 if (prof != NULL)
2955 di_prof_fini(prof);
2957 return (0);
2960 static int
2961 remove_datalink_pool(zlog_t *zlogp, zoneid_t zoneid)
2963 ushort_t flags;
2964 zone_iptype_t iptype;
2965 int i, dlnum = 0;
2966 datalink_id_t *dllink, *dllinks = NULL;
2967 dladm_status_t err;
2969 if (strlen(pool_name) == 0)
2970 return (0);
2972 if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
2973 sizeof (flags)) < 0) {
2974 if (vplat_get_iptype(zlogp, &iptype) < 0) {
2975 zerror(zlogp, B_FALSE, "unable to determine ip-type");
2976 return (-1);
2978 } else {
2979 if (flags & ZF_NET_EXCL)
2980 iptype = ZS_EXCLUSIVE;
2981 else
2982 iptype = ZS_SHARED;
2985 if (iptype == ZS_EXCLUSIVE) {
2987 * Get the datalink count and for each datalink,
2988 * attempt to clear the pool property and clear
2989 * the pool_name.
2991 if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
2992 zerror(zlogp, B_TRUE, "unable to count network "
2993 "interfaces");
2994 return (-1);
2997 if (dlnum == 0)
2998 return (0);
3000 if ((dllinks = malloc(dlnum * sizeof (datalink_id_t)))
3001 == NULL) {
3002 zerror(zlogp, B_TRUE, "memory allocation failed");
3003 return (-1);
3005 if (zone_list_datalink(zoneid, &dlnum, dllinks) != 0) {
3006 zerror(zlogp, B_TRUE, "unable to list network "
3007 "interfaces");
3008 return (-1);
3011 bzero(pool_name, sizeof (pool_name));
3012 for (i = 0, dllink = dllinks; i < dlnum; i++, dllink++) {
3013 err = dladm_set_linkprop(dld_handle, *dllink, "pool",
3014 NULL, 0, DLADM_OPT_ACTIVE);
3015 if (err != DLADM_STATUS_OK) {
3016 zerror(zlogp, B_TRUE,
3017 "WARNING: unable to clear pool");
3020 free(dllinks);
3022 return (0);
3025 static int
3026 remove_datalink_protect(zlog_t *zlogp, zoneid_t zoneid)
3028 ushort_t flags;
3029 zone_iptype_t iptype;
3030 int i, dlnum = 0;
3031 dladm_status_t dlstatus;
3032 datalink_id_t *dllink, *dllinks = NULL;
3034 if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
3035 sizeof (flags)) < 0) {
3036 if (vplat_get_iptype(zlogp, &iptype) < 0) {
3037 zerror(zlogp, B_FALSE, "unable to determine ip-type");
3038 return (-1);
3040 } else {
3041 if (flags & ZF_NET_EXCL)
3042 iptype = ZS_EXCLUSIVE;
3043 else
3044 iptype = ZS_SHARED;
3047 if (iptype != ZS_EXCLUSIVE)
3048 return (0);
3051 * Get the datalink count and for each datalink,
3052 * attempt to clear the pool property and clear
3053 * the pool_name.
3055 if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
3056 zerror(zlogp, B_TRUE, "unable to count network interfaces");
3057 return (-1);
3060 if (dlnum == 0)
3061 return (0);
3063 if ((dllinks = malloc(dlnum * sizeof (datalink_id_t))) == NULL) {
3064 zerror(zlogp, B_TRUE, "memory allocation failed");
3065 return (-1);
3067 if (zone_list_datalink(zoneid, &dlnum, dllinks) != 0) {
3068 zerror(zlogp, B_TRUE, "unable to list network interfaces");
3069 free(dllinks);
3070 return (-1);
3073 for (i = 0, dllink = dllinks; i < dlnum; i++, dllink++) {
3074 char dlerr[DLADM_STRSIZE];
3076 dlstatus = dladm_set_linkprop(dld_handle, *dllink,
3077 "protection", NULL, 0, DLADM_OPT_ACTIVE);
3078 if (dlstatus == DLADM_STATUS_NOTFOUND) {
3079 /* datalink does not belong to the GZ */
3080 continue;
3082 if (dlstatus != DLADM_STATUS_OK) {
3083 zerror(zlogp, B_FALSE,
3084 dladm_status2str(dlstatus, dlerr));
3085 free(dllinks);
3086 return (-1);
3088 dlstatus = dladm_set_linkprop(dld_handle, *dllink,
3089 "allowed-ips", NULL, 0, DLADM_OPT_ACTIVE);
3090 if (dlstatus != DLADM_STATUS_OK) {
3091 zerror(zlogp, B_FALSE,
3092 dladm_status2str(dlstatus, dlerr));
3093 free(dllinks);
3094 return (-1);
3097 free(dllinks);
3098 return (0);
3101 static int
3102 unconfigure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
3104 int dlnum = 0;
3107 * The kernel shutdown callback for the dls module should have removed
3108 * all datalinks from this zone. If any remain, then there's a
3109 * problem.
3111 if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
3112 zerror(zlogp, B_TRUE, "unable to list network interfaces");
3113 return (-1);
3115 if (dlnum != 0) {
3116 zerror(zlogp, B_FALSE,
3117 "datalinks remain in zone after shutdown");
3118 return (-1);
3120 return (0);
3123 static int
3124 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
3125 const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
3127 int fd;
3128 struct strioctl ioc;
3129 tcp_ioc_abort_conn_t conn;
3130 int error;
3132 conn.ac_local = *local;
3133 conn.ac_remote = *remote;
3134 conn.ac_start = TCPS_SYN_SENT;
3135 conn.ac_end = TCPS_TIME_WAIT;
3136 conn.ac_zoneid = zoneid;
3138 ioc.ic_cmd = TCP_IOC_ABORT_CONN;
3139 ioc.ic_timout = -1; /* infinite timeout */
3140 ioc.ic_len = sizeof (conn);
3141 ioc.ic_dp = (char *)&conn;
3143 if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
3144 zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
3145 return (-1);
3148 error = ioctl(fd, I_STR, &ioc);
3149 (void) close(fd);
3150 if (error == 0 || errno == ENOENT) /* ENOENT is not an error */
3151 return (0);
3152 return (-1);
3155 static int
3156 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
3158 struct sockaddr_storage l, r;
3159 struct sockaddr_in *local, *remote;
3160 struct sockaddr_in6 *local6, *remote6;
3161 int error;
3164 * Abort IPv4 connections.
3166 bzero(&l, sizeof (*local));
3167 local = (struct sockaddr_in *)&l;
3168 local->sin_family = AF_INET;
3169 local->sin_addr.s_addr = INADDR_ANY;
3170 local->sin_port = 0;
3172 bzero(&r, sizeof (*remote));
3173 remote = (struct sockaddr_in *)&r;
3174 remote->sin_family = AF_INET;
3175 remote->sin_addr.s_addr = INADDR_ANY;
3176 remote->sin_port = 0;
3178 if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
3179 return (error);
3182 * Abort IPv6 connections.
3184 bzero(&l, sizeof (*local6));
3185 local6 = (struct sockaddr_in6 *)&l;
3186 local6->sin6_family = AF_INET6;
3187 local6->sin6_port = 0;
3188 local6->sin6_addr = in6addr_any;
3190 bzero(&r, sizeof (*remote6));
3191 remote6 = (struct sockaddr_in6 *)&r;
3192 remote6->sin6_family = AF_INET6;
3193 remote6->sin6_port = 0;
3194 remote6->sin6_addr = in6addr_any;
3196 if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
3197 return (error);
3198 return (0);
3201 static int
3202 get_privset(zlog_t *zlogp, priv_set_t *privs, zone_mnt_t mount_cmd)
3204 int error = -1;
3205 zone_dochandle_t handle;
3206 char *privname = NULL;
3208 if ((handle = zonecfg_init_handle()) == NULL) {
3209 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3210 return (-1);
3212 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3213 zerror(zlogp, B_FALSE, "invalid configuration");
3214 zonecfg_fini_handle(handle);
3215 return (-1);
3218 if (ALT_MOUNT(mount_cmd)) {
3219 zone_iptype_t iptype;
3220 const char *curr_iptype;
3222 if (zonecfg_get_iptype(handle, &iptype) != Z_OK) {
3223 zerror(zlogp, B_TRUE, "unable to determine ip-type");
3224 zonecfg_fini_handle(handle);
3225 return (-1);
3228 switch (iptype) {
3229 case ZS_SHARED:
3230 curr_iptype = "shared";
3231 break;
3232 case ZS_EXCLUSIVE:
3233 curr_iptype = "exclusive";
3234 break;
3237 if (zonecfg_default_privset(privs, curr_iptype) == Z_OK) {
3238 zonecfg_fini_handle(handle);
3239 return (0);
3241 zerror(zlogp, B_FALSE,
3242 "failed to determine the zone's default privilege set");
3243 zonecfg_fini_handle(handle);
3244 return (-1);
3247 switch (zonecfg_get_privset(handle, privs, &privname)) {
3248 case Z_OK:
3249 error = 0;
3250 break;
3251 case Z_PRIV_PROHIBITED:
3252 zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
3253 "within the zone's privilege set", privname);
3254 break;
3255 case Z_PRIV_REQUIRED:
3256 zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
3257 "from the zone's privilege set", privname);
3258 break;
3259 case Z_PRIV_UNKNOWN:
3260 zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
3261 "in the zone's privilege set", privname);
3262 break;
3263 default:
3264 zerror(zlogp, B_FALSE, "failed to determine the zone's "
3265 "privilege set");
3266 break;
3269 free(privname);
3270 zonecfg_fini_handle(handle);
3271 return (error);
3274 static int
3275 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3277 nvlist_t *nvl = NULL;
3278 char *nvl_packed = NULL;
3279 size_t nvl_size = 0;
3280 nvlist_t **nvlv = NULL;
3281 int rctlcount = 0;
3282 int error = -1;
3283 zone_dochandle_t handle;
3284 struct zone_rctltab rctltab;
3285 rctlblk_t *rctlblk = NULL;
3286 uint64_t maxlwps;
3287 uint64_t maxprocs;
3289 *bufp = NULL;
3290 *bufsizep = 0;
3292 if ((handle = zonecfg_init_handle()) == NULL) {
3293 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3294 return (-1);
3296 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3297 zerror(zlogp, B_FALSE, "invalid configuration");
3298 zonecfg_fini_handle(handle);
3299 return (-1);
3302 rctltab.zone_rctl_valptr = NULL;
3303 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
3304 zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
3305 goto out;
3309 * Allow the administrator to control both the maximum number of
3310 * process table slots and the maximum number of lwps with just the
3311 * max-processes property. If only the max-processes property is set,
3312 * we add a max-lwps property with a limit derived from max-processes.
3314 if (zonecfg_get_aliased_rctl(handle, ALIAS_MAXPROCS, &maxprocs)
3315 == Z_OK &&
3316 zonecfg_get_aliased_rctl(handle, ALIAS_MAXLWPS, &maxlwps)
3317 == Z_NO_ENTRY) {
3318 if (zonecfg_set_aliased_rctl(handle, ALIAS_MAXLWPS,
3319 maxprocs * LWPS_PER_PROCESS) != Z_OK) {
3320 zerror(zlogp, B_FALSE, "unable to set max-lwps alias");
3321 goto out;
3325 if (zonecfg_setrctlent(handle) != Z_OK) {
3326 zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
3327 goto out;
3330 if ((rctlblk = malloc(rctlblk_size())) == NULL) {
3331 zerror(zlogp, B_TRUE, "memory allocation failed");
3332 goto out;
3334 while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
3335 struct zone_rctlvaltab *rctlval;
3336 uint_t i, count;
3337 const char *name = rctltab.zone_rctl_name;
3339 /* zoneadm should have already warned about unknown rctls. */
3340 if (!zonecfg_is_rctl(name)) {
3341 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3342 rctltab.zone_rctl_valptr = NULL;
3343 continue;
3345 count = 0;
3346 for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
3347 rctlval = rctlval->zone_rctlval_next) {
3348 count++;
3350 if (count == 0) { /* ignore */
3351 continue; /* Nothing to free */
3353 if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
3354 goto out;
3355 i = 0;
3356 for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
3357 rctlval = rctlval->zone_rctlval_next, i++) {
3358 if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
3359 zerror(zlogp, B_TRUE, "%s failed",
3360 "nvlist_alloc");
3361 goto out;
3363 if (zonecfg_construct_rctlblk(rctlval, rctlblk)
3364 != Z_OK) {
3365 zerror(zlogp, B_FALSE, "invalid rctl value: "
3366 "(priv=%s,limit=%s,action=%s)",
3367 rctlval->zone_rctlval_priv,
3368 rctlval->zone_rctlval_limit,
3369 rctlval->zone_rctlval_action);
3370 goto out;
3372 if (!zonecfg_valid_rctl(name, rctlblk)) {
3373 zerror(zlogp, B_FALSE,
3374 "(priv=%s,limit=%s,action=%s) is not a "
3375 "valid value for rctl '%s'",
3376 rctlval->zone_rctlval_priv,
3377 rctlval->zone_rctlval_limit,
3378 rctlval->zone_rctlval_action,
3379 name);
3380 goto out;
3382 if (nvlist_add_uint64(nvlv[i], "privilege",
3383 rctlblk_get_privilege(rctlblk)) != 0) {
3384 zerror(zlogp, B_FALSE, "%s failed",
3385 "nvlist_add_uint64");
3386 goto out;
3388 if (nvlist_add_uint64(nvlv[i], "limit",
3389 rctlblk_get_value(rctlblk)) != 0) {
3390 zerror(zlogp, B_FALSE, "%s failed",
3391 "nvlist_add_uint64");
3392 goto out;
3394 if (nvlist_add_uint64(nvlv[i], "action",
3395 (uint_t)rctlblk_get_local_action(rctlblk, NULL))
3396 != 0) {
3397 zerror(zlogp, B_FALSE, "%s failed",
3398 "nvlist_add_uint64");
3399 goto out;
3402 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3403 rctltab.zone_rctl_valptr = NULL;
3404 if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
3405 != 0) {
3406 zerror(zlogp, B_FALSE, "%s failed",
3407 "nvlist_add_nvlist_array");
3408 goto out;
3410 for (i = 0; i < count; i++)
3411 nvlist_free(nvlv[i]);
3412 free(nvlv);
3413 nvlv = NULL;
3414 rctlcount++;
3416 (void) zonecfg_endrctlent(handle);
3418 if (rctlcount == 0) {
3419 error = 0;
3420 goto out;
3422 if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
3423 != 0) {
3424 zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
3425 goto out;
3428 error = 0;
3429 *bufp = nvl_packed;
3430 *bufsizep = nvl_size;
3432 out:
3433 free(rctlblk);
3434 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3435 if (error)
3436 free(nvl_packed);
3437 nvlist_free(nvl);
3438 free(nvlv);
3439 if (handle != NULL)
3440 zonecfg_fini_handle(handle);
3441 return (error);
3444 static int
3445 get_implicit_datasets(zlog_t *zlogp, char **retstr)
3447 char cmdbuf[2 * MAXPATHLEN];
3449 if (query_hook[0] == '\0')
3450 return (0);
3452 if (snprintf(cmdbuf, sizeof (cmdbuf), "%s datasets", query_hook)
3453 > sizeof (cmdbuf))
3454 return (-1);
3456 if (do_subproc(zlogp, cmdbuf, retstr) != 0)
3457 return (-1);
3459 return (0);
3462 static int
3463 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3465 zone_dochandle_t handle;
3466 struct zone_dstab dstab;
3467 size_t total, offset, len;
3468 int error = -1;
3469 char *str = NULL;
3470 char *implicit_datasets = NULL;
3471 int implicit_len = 0;
3473 *bufp = NULL;
3474 *bufsizep = 0;
3476 if ((handle = zonecfg_init_handle()) == NULL) {
3477 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3478 return (-1);
3480 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3481 zerror(zlogp, B_FALSE, "invalid configuration");
3482 zonecfg_fini_handle(handle);
3483 return (-1);
3486 if (get_implicit_datasets(zlogp, &implicit_datasets) != 0) {
3487 zerror(zlogp, B_FALSE, "getting implicit datasets failed");
3488 goto out;
3491 if (zonecfg_setdsent(handle) != Z_OK) {
3492 zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3493 goto out;
3496 total = 0;
3497 while (zonecfg_getdsent(handle, &dstab) == Z_OK)
3498 total += strlen(dstab.zone_dataset_name) + 1;
3499 (void) zonecfg_enddsent(handle);
3501 if (implicit_datasets != NULL)
3502 implicit_len = strlen(implicit_datasets);
3503 if (implicit_len > 0)
3504 total += implicit_len + 1;
3506 if (total == 0) {
3507 error = 0;
3508 goto out;
3511 if ((str = malloc(total)) == NULL) {
3512 zerror(zlogp, B_TRUE, "memory allocation failed");
3513 goto out;
3516 if (zonecfg_setdsent(handle) != Z_OK) {
3517 zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3518 goto out;
3520 offset = 0;
3521 while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3522 len = strlen(dstab.zone_dataset_name);
3523 (void) strlcpy(str + offset, dstab.zone_dataset_name,
3524 total - offset);
3525 offset += len;
3526 if (offset < total - 1)
3527 str[offset++] = ',';
3529 (void) zonecfg_enddsent(handle);
3531 if (implicit_len > 0)
3532 (void) strlcpy(str + offset, implicit_datasets, total - offset);
3534 error = 0;
3535 *bufp = str;
3536 *bufsizep = total;
3538 out:
3539 if (error != 0)
3540 free(str);
3541 if (handle != NULL)
3542 zonecfg_fini_handle(handle);
3543 free(implicit_datasets);
3545 return (error);
3548 static int
3549 validate_datasets(zlog_t *zlogp)
3551 zone_dochandle_t handle;
3552 struct zone_dstab dstab;
3553 zfs_handle_t *zhp;
3554 libzfs_handle_t *hdl;
3556 if ((handle = zonecfg_init_handle()) == NULL) {
3557 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3558 return (-1);
3560 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3561 zerror(zlogp, B_FALSE, "invalid configuration");
3562 zonecfg_fini_handle(handle);
3563 return (-1);
3566 if (zonecfg_setdsent(handle) != Z_OK) {
3567 zerror(zlogp, B_FALSE, "invalid configuration");
3568 zonecfg_fini_handle(handle);
3569 return (-1);
3572 if ((hdl = libzfs_init()) == NULL) {
3573 zerror(zlogp, B_FALSE, "opening ZFS library");
3574 zonecfg_fini_handle(handle);
3575 return (-1);
3578 while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3580 if ((zhp = zfs_open(hdl, dstab.zone_dataset_name,
3581 ZFS_TYPE_FILESYSTEM)) == NULL) {
3582 zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
3583 dstab.zone_dataset_name);
3584 zonecfg_fini_handle(handle);
3585 libzfs_fini(hdl);
3586 return (-1);
3590 * Automatically set the 'zoned' property. We check the value
3591 * first because we'll get EPERM if it is already set.
3593 if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
3594 zfs_prop_set(zhp, zfs_prop_to_name(ZFS_PROP_ZONED),
3595 "on") != 0) {
3596 zerror(zlogp, B_FALSE, "cannot set 'zoned' "
3597 "property for ZFS dataset '%s'\n",
3598 dstab.zone_dataset_name);
3599 zonecfg_fini_handle(handle);
3600 zfs_close(zhp);
3601 libzfs_fini(hdl);
3602 return (-1);
3605 zfs_close(zhp);
3607 (void) zonecfg_enddsent(handle);
3609 zonecfg_fini_handle(handle);
3610 libzfs_fini(hdl);
3612 return (0);
3616 * Return true if the path is its own zfs file system. We determine this
3617 * by stat-ing the path to see if it is zfs and stat-ing the parent to see
3618 * if it is a different fs.
3620 boolean_t
3621 is_zonepath_zfs(char *zonepath)
3623 int res;
3624 char *path;
3625 char *parent;
3626 struct statvfs64 buf1, buf2;
3628 if (statvfs64(zonepath, &buf1) != 0)
3629 return (B_FALSE);
3631 if (strcmp(buf1.f_basetype, "zfs") != 0)
3632 return (B_FALSE);
3634 if ((path = strdup(zonepath)) == NULL)
3635 return (B_FALSE);
3637 parent = dirname(path);
3638 res = statvfs64(parent, &buf2);
3639 free(path);
3641 if (res != 0)
3642 return (B_FALSE);
3644 if (buf1.f_fsid == buf2.f_fsid)
3645 return (B_FALSE);
3647 return (B_TRUE);
3651 prtmount(const struct mnttab *fs, void *x)
3653 zerror((zlog_t *)x, B_FALSE, " %s", fs->mnt_mountp);
3654 return (0);
3658 * Look for zones running on the main system that are using this root (or any
3659 * subdirectory of it). Return B_TRUE and print an error if a conflicting zone
3660 * is found or if we can't tell.
3662 static boolean_t
3663 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
3665 zoneid_t *zids = NULL;
3666 uint_t nzids = 0;
3667 boolean_t retv;
3668 int rlen, zlen;
3669 char zroot[MAXPATHLEN];
3670 char zonename[ZONENAME_MAX];
3672 for (;;) {
3673 nzids += 10;
3674 zids = malloc(nzids * sizeof (*zids));
3675 if (zids == NULL) {
3676 zerror(zlogp, B_TRUE, "memory allocation failed");
3677 return (B_TRUE);
3679 if (zone_list(zids, &nzids) == 0)
3680 break;
3681 free(zids);
3683 retv = B_FALSE;
3684 rlen = strlen(rootpath);
3685 while (nzids > 0) {
3687 * Ignore errors; they just mean that the zone has disappeared
3688 * while we were busy.
3690 if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
3691 sizeof (zroot)) == -1)
3692 continue;
3693 zlen = strlen(zroot);
3694 if (zlen > rlen)
3695 zlen = rlen;
3696 if (strncmp(rootpath, zroot, zlen) == 0 &&
3697 (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
3698 (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
3699 if (getzonenamebyid(zids[nzids], zonename,
3700 sizeof (zonename)) == -1)
3701 (void) snprintf(zonename, sizeof (zonename),
3702 "id %d", (int)zids[nzids]);
3703 zerror(zlogp, B_FALSE,
3704 "zone root %s already in use by zone %s",
3705 rootpath, zonename);
3706 retv = B_TRUE;
3707 break;
3710 free(zids);
3711 return (retv);
3715 * Search for loopback mounts that use this same source node (same device and
3716 * inode). Return B_TRUE if there is one or if we can't tell.
3718 static boolean_t
3719 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
3721 struct stat64 rst, zst;
3722 struct mnttab *mnp;
3724 if (stat64(rootpath, &rst) == -1) {
3725 zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
3726 return (B_TRUE);
3728 if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
3729 return (B_TRUE);
3730 for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
3731 if (mnp->mnt_fstype == NULL ||
3732 strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
3733 continue;
3734 /* We're looking at a loopback mount. Stat it. */
3735 if (mnp->mnt_special != NULL &&
3736 stat64(mnp->mnt_special, &zst) != -1 &&
3737 rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
3738 zerror(zlogp, B_FALSE,
3739 "zone root %s is reachable through %s",
3740 rootpath, mnp->mnt_mountp);
3741 return (B_TRUE);
3744 return (B_FALSE);
3748 * Set memory cap and pool info for the zone's resource management
3749 * configuration.
3751 static int
3752 setup_zone_rm(zlog_t *zlogp, char *zone_name, zoneid_t zoneid)
3754 int res;
3755 uint64_t tmp;
3756 struct zone_mcaptab mcap;
3757 char sched[MAXNAMELEN];
3758 zone_dochandle_t handle = NULL;
3759 char pool_err[128];
3761 if ((handle = zonecfg_init_handle()) == NULL) {
3762 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3763 return (Z_BAD_HANDLE);
3766 if ((res = zonecfg_get_snapshot_handle(zone_name, handle)) != Z_OK) {
3767 zerror(zlogp, B_FALSE, "invalid configuration");
3768 zonecfg_fini_handle(handle);
3769 return (res);
3773 * If a memory cap is configured, set the cap in the kernel using
3774 * zone_setattr() and make sure the rcapd SMF service is enabled.
3776 if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
3777 uint64_t num;
3778 char smf_err[128];
3780 num = (uint64_t)strtoull(mcap.zone_physmem_cap, NULL, 10);
3781 if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
3782 zerror(zlogp, B_TRUE, "could not set zone memory cap");
3783 zonecfg_fini_handle(handle);
3784 return (Z_INVAL);
3787 if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
3788 zerror(zlogp, B_FALSE, "enabling system/rcap service "
3789 "failed: %s", smf_err);
3790 zonecfg_fini_handle(handle);
3791 return (Z_INVAL);
3795 /* Get the scheduling class set in the zone configuration. */
3796 if (zonecfg_get_sched_class(handle, sched, sizeof (sched)) == Z_OK &&
3797 strlen(sched) > 0) {
3798 if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, sched,
3799 strlen(sched)) == -1)
3800 zerror(zlogp, B_TRUE, "WARNING: unable to set the "
3801 "default scheduling class");
3803 } else if (zonecfg_get_aliased_rctl(handle, ALIAS_SHARES, &tmp)
3804 == Z_OK) {
3806 * If the zone has the zone.cpu-shares rctl set then we want to
3807 * use the Fair Share Scheduler (FSS) for processes in the
3808 * zone. Check what scheduling class the zone would be running
3809 * in by default so we can print a warning and modify the class
3810 * if we wouldn't be using FSS.
3812 char class_name[PC_CLNMSZ];
3814 if (zonecfg_get_dflt_sched_class(handle, class_name,
3815 sizeof (class_name)) != Z_OK) {
3816 zerror(zlogp, B_FALSE, "WARNING: unable to determine "
3817 "the zone's scheduling class");
3819 } else if (strcmp("FSS", class_name) != 0) {
3820 zerror(zlogp, B_FALSE, "WARNING: The zone.cpu-shares "
3821 "rctl is set but\nFSS is not the default "
3822 "scheduling class for\nthis zone. FSS will be "
3823 "used for processes\nin the zone but to get the "
3824 "full benefit of FSS,\nit should be the default "
3825 "scheduling class.\nSee dispadmin(1M) for more "
3826 "details.");
3828 if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, "FSS",
3829 strlen("FSS")) == -1)
3830 zerror(zlogp, B_TRUE, "WARNING: unable to set "
3831 "zone scheduling class to FSS");
3836 * The next few blocks of code attempt to set up temporary pools as
3837 * well as persistent pools. In all cases we call the functions
3838 * unconditionally. Within each funtion the code will check if the
3839 * zone is actually configured for a temporary pool or persistent pool
3840 * and just return if there is nothing to do.
3842 * If we are rebooting we want to attempt to reuse any temporary pool
3843 * that was previously set up. zonecfg_bind_tmp_pool() will do the
3844 * right thing in all cases (reuse or create) based on the current
3845 * zonecfg.
3847 if ((res = zonecfg_bind_tmp_pool(handle, zoneid, pool_err,
3848 sizeof (pool_err))) != Z_OK) {
3849 if (res == Z_POOL || res == Z_POOL_CREATE || res == Z_POOL_BIND)
3850 zerror(zlogp, B_FALSE, "%s: %s\ndedicated-cpu setting "
3851 "cannot be instantiated", zonecfg_strerror(res),
3852 pool_err);
3853 else
3854 zerror(zlogp, B_FALSE, "could not bind zone to "
3855 "temporary pool: %s", zonecfg_strerror(res));
3856 zonecfg_fini_handle(handle);
3857 return (Z_POOL_BIND);
3861 * Check if we need to warn about poold not being enabled.
3863 if (zonecfg_warn_poold(handle)) {
3864 zerror(zlogp, B_FALSE, "WARNING: A range of dedicated-cpus has "
3865 "been specified\nbut the dynamic pool service is not "
3866 "enabled.\nThe system will not dynamically adjust the\n"
3867 "processor allocation within the specified range\n"
3868 "until svc:/system/pools/dynamic is enabled.\n"
3869 "See poold(1M).");
3872 /* The following is a warning, not an error. */
3873 if ((res = zonecfg_bind_pool(handle, zoneid, pool_err,
3874 sizeof (pool_err))) != Z_OK) {
3875 if (res == Z_POOL_BIND)
3876 zerror(zlogp, B_FALSE, "WARNING: unable to bind to "
3877 "pool '%s'; using default pool.", pool_err);
3878 else if (res == Z_POOL)
3879 zerror(zlogp, B_FALSE, "WARNING: %s: %s",
3880 zonecfg_strerror(res), pool_err);
3881 else
3882 zerror(zlogp, B_FALSE, "WARNING: %s",
3883 zonecfg_strerror(res));
3886 /* Update saved pool name in case it has changed */
3887 (void) zonecfg_get_poolname(handle, zone_name, pool_name,
3888 sizeof (pool_name));
3890 zonecfg_fini_handle(handle);
3891 return (Z_OK);
3894 static void
3895 report_prop_err(zlog_t *zlogp, const char *name, const char *value, int res)
3897 switch (res) {
3898 case Z_TOO_BIG:
3899 zerror(zlogp, B_FALSE, "%s property value is too large.", name);
3900 break;
3902 case Z_INVALID_PROPERTY:
3903 zerror(zlogp, B_FALSE, "%s property value \"%s\" is not valid",
3904 name, value);
3905 break;
3907 default:
3908 zerror(zlogp, B_TRUE, "fetching property %s: %d", name, res);
3909 break;
3914 * Sets the hostid of the new zone based on its configured value. The zone's
3915 * zone_t structure must already exist in kernel memory. 'zlogp' refers to the
3916 * log used to report errors and warnings and must be non-NULL. 'zone_namep'
3917 * is the name of the new zone and must be non-NULL. 'zoneid' is the numeric
3918 * ID of the new zone.
3920 * This function returns zero on success and a nonzero error code on failure.
3922 static int
3923 setup_zone_hostid(zone_dochandle_t handle, zlog_t *zlogp, zoneid_t zoneid)
3925 int res;
3926 char hostidp[HW_HOSTID_LEN];
3927 unsigned int hostid;
3929 res = zonecfg_get_hostid(handle, hostidp, sizeof (hostidp));
3931 if (res == Z_BAD_PROPERTY) {
3932 return (Z_OK);
3933 } else if (res != Z_OK) {
3934 report_prop_err(zlogp, "hostid", hostidp, res);
3935 return (res);
3938 hostid = (unsigned int)strtoul(hostidp, NULL, 16);
3939 if ((res = zone_setattr(zoneid, ZONE_ATTR_HOSTID, &hostid,
3940 sizeof (hostid))) != 0) {
3941 zerror(zlogp, B_TRUE,
3942 "zone hostid is not valid: %s: %d", hostidp, res);
3943 return (Z_SYSTEM);
3946 return (res);
3949 static int
3950 setup_zone_secflags(zone_dochandle_t handle, zlog_t *zlogp, zoneid_t zoneid)
3952 psecflags_t secflags;
3953 struct zone_secflagstab tab = {0};
3954 secflagdelta_t delt;
3955 int res;
3957 res = zonecfg_lookup_secflags(handle, &tab);
3959 if ((res != Z_OK) &&
3960 /* The general defaulting code will handle this */
3961 (res != Z_NO_ENTRY) && (res != Z_BAD_PROPERTY)) {
3962 zerror(zlogp, B_FALSE, "security-flags property is "
3963 "invalid: %d", res);
3964 return (res);
3967 if (strlen(tab.zone_secflags_lower) == 0)
3968 (void) strlcpy(tab.zone_secflags_lower, "none",
3969 sizeof (tab.zone_secflags_lower));
3970 if (strlen(tab.zone_secflags_default) == 0)
3971 (void) strlcpy(tab.zone_secflags_default,
3972 tab.zone_secflags_lower,
3973 sizeof (tab.zone_secflags_default));
3974 if (strlen(tab.zone_secflags_upper) == 0)
3975 (void) strlcpy(tab.zone_secflags_upper, "all",
3976 sizeof (tab.zone_secflags_upper));
3978 if (secflags_parse(NULL, tab.zone_secflags_default,
3979 &delt) == -1) {
3980 zerror(zlogp, B_FALSE, "default security-flags: '%s'"
3981 "are invalid", tab.zone_secflags_default);
3982 return (Z_BAD_PROPERTY);
3983 } else if (delt.psd_ass_active != B_TRUE) {
3984 zerror(zlogp, B_FALSE, "relative security-flags are not "
3985 "allowed in zone configuration (default "
3986 "security-flags: '%s')",
3987 tab.zone_secflags_default);
3988 return (Z_BAD_PROPERTY);
3989 } else {
3990 secflags_copy(&secflags.psf_inherit, &delt.psd_assign);
3991 secflags_copy(&secflags.psf_effective, &delt.psd_assign);
3994 if (secflags_parse(NULL, tab.zone_secflags_lower,
3995 &delt) == -1) {
3996 zerror(zlogp, B_FALSE, "lower security-flags: '%s'"
3997 "are invalid", tab.zone_secflags_lower);
3998 return (Z_BAD_PROPERTY);
3999 } else if (delt.psd_ass_active != B_TRUE) {
4000 zerror(zlogp, B_FALSE, "relative security-flags are not "
4001 "allowed in zone configuration (lower "
4002 "security-flags: '%s')",
4003 tab.zone_secflags_lower);
4004 return (Z_BAD_PROPERTY);
4005 } else {
4006 secflags_copy(&secflags.psf_lower, &delt.psd_assign);
4009 if (secflags_parse(NULL, tab.zone_secflags_upper,
4010 &delt) == -1) {
4011 zerror(zlogp, B_FALSE, "upper security-flags: '%s'"
4012 "are invalid", tab.zone_secflags_upper);
4013 return (Z_BAD_PROPERTY);
4014 } else if (delt.psd_ass_active != B_TRUE) {
4015 zerror(zlogp, B_FALSE, "relative security-flags are not "
4016 "allowed in zone configuration (upper "
4017 "security-flags: '%s')",
4018 tab.zone_secflags_upper);
4019 return (Z_BAD_PROPERTY);
4020 } else {
4021 secflags_copy(&secflags.psf_upper, &delt.psd_assign);
4024 if (!psecflags_validate(&secflags)) {
4025 zerror(zlogp, B_TRUE, "security-flags violate invariants");
4026 return (Z_BAD_PROPERTY);
4029 if ((res = zone_setattr(zoneid, ZONE_ATTR_SECFLAGS, &secflags,
4030 sizeof (secflags))) != 0) {
4031 zerror(zlogp, B_TRUE,
4032 "security-flags couldn't be set: %d", res);
4033 return (Z_SYSTEM);
4036 return (Z_OK);
4039 static int
4040 setup_zone_fs_allowed(zone_dochandle_t handle, zlog_t *zlogp, zoneid_t zoneid)
4042 char fsallowed[ZONE_FS_ALLOWED_MAX];
4043 char *fsallowedp = fsallowed;
4044 int len = sizeof (fsallowed);
4045 int res;
4047 res = zonecfg_get_fs_allowed(handle, fsallowed, len);
4049 if (res == Z_BAD_PROPERTY) {
4050 /* No value, set the defaults */
4051 (void) strlcpy(fsallowed, DFLT_FS_ALLOWED, len);
4052 } else if (res != Z_OK) {
4053 report_prop_err(zlogp, "fs-allowed", fsallowed, res);
4054 return (res);
4055 } else if (fsallowed[0] == '-') {
4056 /* dropping default filesystems - use remaining list */
4057 if (fsallowed[1] != ',')
4058 return (Z_OK);
4059 fsallowedp += 2;
4060 len -= 2;
4061 } else {
4062 /* Has a value, append the defaults */
4063 if (strlcat(fsallowed, ",", len) >= len ||
4064 strlcat(fsallowed, DFLT_FS_ALLOWED, len) >= len) {
4065 report_prop_err(zlogp, "fs-allowed", fsallowed,
4066 Z_TOO_BIG);
4067 return (Z_TOO_BIG);
4071 if (zone_setattr(zoneid, ZONE_ATTR_FS_ALLOWED, fsallowedp, len) != 0) {
4072 zerror(zlogp, B_TRUE,
4073 "fs-allowed couldn't be set: %s: %d", fsallowedp, res);
4074 return (Z_SYSTEM);
4077 return (Z_OK);
4080 static int
4081 setup_zone_attrs(zlog_t *zlogp, char *zone_namep, zoneid_t zoneid)
4083 zone_dochandle_t handle;
4084 int res = Z_OK;
4086 if ((handle = zonecfg_init_handle()) == NULL) {
4087 zerror(zlogp, B_TRUE, "getting zone configuration handle");
4088 return (Z_BAD_HANDLE);
4090 if ((res = zonecfg_get_snapshot_handle(zone_namep, handle)) != Z_OK) {
4091 zerror(zlogp, B_FALSE, "invalid configuration");
4092 goto out;
4095 if ((res = setup_zone_hostid(handle, zlogp, zoneid)) != Z_OK)
4096 goto out;
4098 if ((res = setup_zone_fs_allowed(handle, zlogp, zoneid)) != Z_OK)
4099 goto out;
4101 if ((res = setup_zone_secflags(handle, zlogp, zoneid)) != Z_OK)
4102 goto out;
4104 out:
4105 zonecfg_fini_handle(handle);
4106 return (res);
4109 zoneid_t
4110 vplat_create(zlog_t *zlogp, zone_mnt_t mount_cmd)
4112 zoneid_t rval = -1;
4113 priv_set_t *privs;
4114 char rootpath[MAXPATHLEN];
4115 char *rctlbuf = NULL;
4116 size_t rctlbufsz = 0;
4117 char *zfsbuf = NULL;
4118 size_t zfsbufsz = 0;
4119 zoneid_t zoneid = -1;
4120 int xerr;
4121 char *kzone;
4122 FILE *fp = NULL;
4123 int flags;
4124 zone_iptype_t iptype;
4126 if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
4127 zerror(zlogp, B_TRUE, "unable to determine zone root");
4128 return (-1);
4130 if (zonecfg_in_alt_root())
4131 resolve_lofs(zlogp, rootpath, sizeof (rootpath));
4133 if (vplat_get_iptype(zlogp, &iptype) < 0) {
4134 zerror(zlogp, B_TRUE, "unable to determine ip-type");
4135 return (-1);
4137 switch (iptype) {
4138 case ZS_SHARED:
4139 flags = 0;
4140 break;
4141 case ZS_EXCLUSIVE:
4142 flags = ZCF_NET_EXCL;
4143 break;
4146 if ((privs = priv_allocset()) == NULL) {
4147 zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
4148 return (-1);
4150 priv_emptyset(privs);
4151 if (get_privset(zlogp, privs, mount_cmd) != 0)
4152 goto error;
4154 if (mount_cmd == Z_MNT_BOOT &&
4155 get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
4156 zerror(zlogp, B_FALSE, "Unable to get list of rctls");
4157 goto error;
4160 if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
4161 zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
4162 goto error;
4165 kzone = zone_name;
4168 * We must do this scan twice. First, we look for zones running on the
4169 * main system that are using this root (or any subdirectory of it).
4170 * Next, we reduce to the shortest path and search for loopback mounts
4171 * that use this same source node (same device and inode).
4173 if (duplicate_zone_root(zlogp, rootpath))
4174 goto error;
4175 if (duplicate_reachable_path(zlogp, rootpath))
4176 goto error;
4178 if (ALT_MOUNT(mount_cmd)) {
4179 root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
4182 * Forge up a special root for this zone. When a zone is
4183 * mounted, we can't let the zone have its own root because the
4184 * tools that will be used in this "scratch zone" need access
4185 * to both the zone's resources and the running machine's
4186 * executables.
4188 * Note that the mkdir here also catches read-only filesystems.
4190 if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
4191 zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
4192 goto error;
4194 if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
4195 goto error;
4198 if (zonecfg_in_alt_root()) {
4200 * If we are mounting up a zone in an alternate root partition,
4201 * then we have some additional work to do before starting the
4202 * zone. First, resolve the root path down so that we're not
4203 * fooled by duplicates. Then forge up an internal name for
4204 * the zone.
4206 if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
4207 zerror(zlogp, B_TRUE, "cannot open mapfile");
4208 goto error;
4210 if (zonecfg_lock_scratch(fp) != 0) {
4211 zerror(zlogp, B_TRUE, "cannot lock mapfile");
4212 goto error;
4214 if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4215 NULL, 0) == 0) {
4216 zerror(zlogp, B_FALSE, "scratch zone already running");
4217 goto error;
4219 /* This is the preferred name */
4220 (void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
4221 zone_name);
4222 srandom(getpid());
4223 while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
4224 0) == 0) {
4225 /* This is just an arbitrary name; note "." usage */
4226 (void) snprintf(kernzone, sizeof (kernzone),
4227 "SUNWlu.%08lX%08lX", random(), random());
4229 kzone = kernzone;
4232 xerr = 0;
4233 if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
4234 rctlbufsz, zfsbuf, zfsbufsz, &xerr, flags)) == -1) {
4235 if (xerr == ZE_AREMOUNTS) {
4236 if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
4237 zerror(zlogp, B_FALSE,
4238 "An unknown file-system is mounted on "
4239 "a subdirectory of %s", rootpath);
4240 } else {
4242 zerror(zlogp, B_FALSE,
4243 "These file-systems are mounted on "
4244 "subdirectories of %s:", rootpath);
4245 (void) zonecfg_find_mounts(rootpath,
4246 prtmount, zlogp);
4248 } else if (xerr == ZE_CHROOTED) {
4249 zerror(zlogp, B_FALSE, "%s: "
4250 "cannot create a zone from a chrooted "
4251 "environment", "zone_create");
4252 } else {
4253 zerror(zlogp, B_TRUE, "%s failed", "zone_create");
4255 goto error;
4258 if (zonecfg_in_alt_root() &&
4259 zonecfg_add_scratch(fp, zone_name, kernzone,
4260 zonecfg_get_root()) == -1) {
4261 zerror(zlogp, B_TRUE, "cannot add mapfile entry");
4262 goto error;
4266 * The following actions are not performed when merely mounting a zone
4267 * for administrative use.
4269 if (mount_cmd == Z_MNT_BOOT) {
4270 brand_handle_t bh;
4271 struct brand_attr attr;
4272 char modname[MAXPATHLEN];
4274 if (setup_zone_attrs(zlogp, zone_name, zoneid) != Z_OK)
4275 goto error;
4277 if ((bh = brand_open(brand_name)) == NULL) {
4278 zerror(zlogp, B_FALSE,
4279 "unable to determine brand name");
4280 goto error;
4284 * If this brand requires any kernel support, now is the time to
4285 * get it loaded and initialized.
4287 if (brand_get_modname(bh, modname, MAXPATHLEN) < 0) {
4288 brand_close(bh);
4289 zerror(zlogp, B_FALSE,
4290 "unable to determine brand kernel module");
4291 goto error;
4293 brand_close(bh);
4295 if (strlen(modname) > 0) {
4296 (void) strlcpy(attr.ba_brandname, brand_name,
4297 sizeof (attr.ba_brandname));
4298 (void) strlcpy(attr.ba_modname, modname,
4299 sizeof (attr.ba_modname));
4300 if (zone_setattr(zoneid, ZONE_ATTR_BRAND, &attr,
4301 sizeof (attr) != 0)) {
4302 zerror(zlogp, B_TRUE,
4303 "could not set zone brand attribute.");
4304 goto error;
4308 if (setup_zone_rm(zlogp, zone_name, zoneid) != Z_OK)
4309 goto error;
4312 rval = zoneid;
4313 zoneid = -1;
4315 error:
4316 if (zoneid != -1) {
4317 (void) zone_shutdown(zoneid);
4318 (void) zone_destroy(zoneid);
4320 free(rctlbuf);
4321 priv_freeset(privs);
4322 if (fp != NULL)
4323 zonecfg_close_scratch(fp);
4324 lofs_discard_mnttab();
4325 return (rval);
4329 * Enter the zone and write a /etc/zones/index file there. This allows
4330 * libzonecfg (and thus zoneadm) to report the UUID and potentially other zone
4331 * details from inside the zone.
4333 static void
4334 write_index_file(zoneid_t zoneid)
4336 FILE *zef;
4337 FILE *zet;
4338 struct zoneent *zep;
4339 pid_t child;
4340 int tmpl_fd;
4341 ctid_t ct;
4342 int fd;
4343 char uuidstr[UUID_PRINTABLE_STRING_LENGTH];
4345 /* Locate the zone entry in the global zone's index file */
4346 if ((zef = setzoneent()) == NULL)
4347 return;
4348 while ((zep = getzoneent_private(zef)) != NULL) {
4349 if (strcmp(zep->zone_name, zone_name) == 0)
4350 break;
4351 free(zep);
4353 endzoneent(zef);
4354 if (zep == NULL)
4355 return;
4357 if ((tmpl_fd = init_template()) == -1) {
4358 free(zep);
4359 return;
4362 if ((child = fork()) == -1) {
4363 (void) ct_tmpl_clear(tmpl_fd);
4364 (void) close(tmpl_fd);
4365 free(zep);
4366 return;
4369 /* parent waits for child to finish */
4370 if (child != 0) {
4371 free(zep);
4372 if (contract_latest(&ct) == -1)
4373 ct = -1;
4374 (void) ct_tmpl_clear(tmpl_fd);
4375 (void) close(tmpl_fd);
4376 (void) waitpid(child, NULL, 0);
4377 (void) contract_abandon_id(ct);
4378 return;
4381 /* child enters zone and sets up index file */
4382 (void) ct_tmpl_clear(tmpl_fd);
4383 if (zone_enter(zoneid) != -1) {
4384 (void) mkdir(ZONE_CONFIG_ROOT, ZONE_CONFIG_MODE);
4385 (void) chown(ZONE_CONFIG_ROOT, ZONE_CONFIG_UID,
4386 ZONE_CONFIG_GID);
4387 fd = open(ZONE_INDEX_FILE, O_WRONLY|O_CREAT|O_TRUNC,
4388 ZONE_INDEX_MODE);
4389 if (fd != -1 && (zet = fdopen(fd, "w")) != NULL) {
4390 (void) fchown(fd, ZONE_INDEX_UID, ZONE_INDEX_GID);
4391 if (uuid_is_null(zep->zone_uuid))
4392 uuidstr[0] = '\0';
4393 else
4394 uuid_unparse(zep->zone_uuid, uuidstr);
4395 (void) fprintf(zet, "%s:%s:/:%s\n", zep->zone_name,
4396 zone_state_str(zep->zone_state),
4397 uuidstr);
4398 (void) fclose(zet);
4401 _exit(0);
4405 vplat_bringup(zlog_t *zlogp, zone_mnt_t mount_cmd, zoneid_t zoneid)
4407 char zonepath[MAXPATHLEN];
4409 if (mount_cmd == Z_MNT_BOOT && validate_datasets(zlogp) != 0) {
4410 lofs_discard_mnttab();
4411 return (-1);
4415 * Before we try to mount filesystems we need to create the
4416 * attribute backing store for /dev
4418 if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
4419 lofs_discard_mnttab();
4420 return (-1);
4422 resolve_lofs(zlogp, zonepath, sizeof (zonepath));
4424 /* Make /dev directory owned by root, grouped sys */
4425 if (make_one_dir(zlogp, zonepath, "/dev", DEFAULT_DIR_MODE,
4426 0, 3) != 0) {
4427 lofs_discard_mnttab();
4428 return (-1);
4431 if (mount_filesystems(zlogp, mount_cmd) != 0) {
4432 lofs_discard_mnttab();
4433 return (-1);
4436 if (mount_cmd == Z_MNT_BOOT) {
4437 zone_iptype_t iptype;
4439 if (vplat_get_iptype(zlogp, &iptype) < 0) {
4440 zerror(zlogp, B_TRUE, "unable to determine ip-type");
4441 lofs_discard_mnttab();
4442 return (-1);
4445 switch (iptype) {
4446 case ZS_SHARED:
4447 /* Always do this to make lo0 get configured */
4448 if (configure_shared_network_interfaces(zlogp) != 0) {
4449 lofs_discard_mnttab();
4450 return (-1);
4452 break;
4453 case ZS_EXCLUSIVE:
4454 if (configure_exclusive_network_interfaces(zlogp,
4455 zoneid) !=
4456 0) {
4457 lofs_discard_mnttab();
4458 return (-1);
4460 break;
4464 write_index_file(zoneid);
4466 lofs_discard_mnttab();
4467 return (0);
4470 static int
4471 lu_root_teardown(zlog_t *zlogp)
4473 char zroot[MAXPATHLEN];
4475 if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
4476 zerror(zlogp, B_FALSE, "unable to determine zone root");
4477 return (-1);
4479 root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
4482 * At this point, the processes are gone, the filesystems (save the
4483 * root) are unmounted, and the zone is on death row. But there may
4484 * still be creds floating about in the system that reference the
4485 * zone_t, and which pin down zone_rootvp causing this call to fail
4486 * with EBUSY. Thus, we try for a little while before just giving up.
4487 * (How I wish this were not true, and umount2 just did the right
4488 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
4490 if (umount2(zroot, MS_FORCE) != 0) {
4491 if (errno == ENOTSUP && umount2(zroot, 0) == 0)
4492 goto unmounted;
4493 if (errno == EBUSY) {
4494 int tries = 10;
4496 while (--tries >= 0) {
4497 (void) sleep(1);
4498 if (umount2(zroot, 0) == 0)
4499 goto unmounted;
4500 if (errno != EBUSY)
4501 break;
4504 zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
4505 return (-1);
4507 unmounted:
4510 * Only zones in an alternate root environment have scratch zone
4511 * entries.
4513 if (zonecfg_in_alt_root()) {
4514 FILE *fp;
4515 int retv;
4517 if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4518 zerror(zlogp, B_TRUE, "cannot open mapfile");
4519 return (-1);
4521 retv = -1;
4522 if (zonecfg_lock_scratch(fp) != 0)
4523 zerror(zlogp, B_TRUE, "cannot lock mapfile");
4524 else if (zonecfg_delete_scratch(fp, kernzone) != 0)
4525 zerror(zlogp, B_TRUE, "cannot delete map entry");
4526 else
4527 retv = 0;
4528 zonecfg_close_scratch(fp);
4529 return (retv);
4530 } else {
4531 return (0);
4536 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd, boolean_t rebooting)
4538 char *kzone;
4539 zoneid_t zoneid;
4540 int res;
4541 char pool_err[128];
4542 char zpath[MAXPATHLEN];
4543 char cmdbuf[MAXPATHLEN];
4544 brand_handle_t bh = NULL;
4545 dladm_status_t status;
4546 char errmsg[DLADM_STRSIZE];
4547 ushort_t flags;
4549 kzone = zone_name;
4550 if (zonecfg_in_alt_root()) {
4551 FILE *fp;
4553 if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4554 zerror(zlogp, B_TRUE, "unable to open map file");
4555 goto error;
4557 if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4558 kernzone, sizeof (kernzone)) != 0) {
4559 zerror(zlogp, B_FALSE, "unable to find scratch zone");
4560 zonecfg_close_scratch(fp);
4561 goto error;
4563 zonecfg_close_scratch(fp);
4564 kzone = kernzone;
4567 if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
4568 if (!bringup_failure_recovery)
4569 zerror(zlogp, B_TRUE, "unable to get zoneid");
4570 if (unmount_cmd)
4571 (void) lu_root_teardown(zlogp);
4572 goto error;
4575 if (remove_datalink_pool(zlogp, zoneid) != 0) {
4576 zerror(zlogp, B_FALSE, "unable clear datalink pool property");
4577 goto error;
4580 if (remove_datalink_protect(zlogp, zoneid) != 0) {
4581 zerror(zlogp, B_FALSE,
4582 "unable clear datalink protect property");
4583 goto error;
4587 * The datalinks assigned to the zone will be removed from the NGZ as
4588 * part of zone_shutdown() so that we need to remove protect/pool etc.
4589 * before zone_shutdown(). Even if the shutdown itself fails, the zone
4590 * will not be able to violate any constraints applied because the
4591 * datalinks are no longer available to the zone.
4593 if (zone_shutdown(zoneid) != 0) {
4594 zerror(zlogp, B_TRUE, "unable to shutdown zone");
4595 goto error;
4598 /* Get the zonepath of this zone */
4599 if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
4600 zerror(zlogp, B_FALSE, "unable to determine zone path");
4601 goto error;
4604 /* Get a handle to the brand info for this zone */
4605 if ((bh = brand_open(brand_name)) == NULL) {
4606 zerror(zlogp, B_FALSE, "unable to determine zone brand");
4607 return (-1);
4610 * If there is a brand 'halt' callback, execute it now to give the
4611 * brand a chance to cleanup any custom configuration.
4613 (void) strcpy(cmdbuf, EXEC_PREFIX);
4614 if (brand_get_halt(bh, zone_name, zpath, cmdbuf + EXEC_LEN,
4615 sizeof (cmdbuf) - EXEC_LEN) < 0) {
4616 brand_close(bh);
4617 zerror(zlogp, B_FALSE, "unable to determine branded zone's "
4618 "halt callback.");
4619 goto error;
4621 brand_close(bh);
4623 if ((strlen(cmdbuf) > EXEC_LEN) &&
4624 (do_subproc(zlogp, cmdbuf, NULL) != Z_OK)) {
4625 zerror(zlogp, B_FALSE, "%s failed", cmdbuf);
4626 goto error;
4629 if (!unmount_cmd) {
4630 zone_iptype_t iptype;
4632 if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
4633 sizeof (flags)) < 0) {
4634 if (vplat_get_iptype(zlogp, &iptype) < 0) {
4635 zerror(zlogp, B_TRUE, "unable to determine "
4636 "ip-type");
4637 goto error;
4639 } else {
4640 if (flags & ZF_NET_EXCL)
4641 iptype = ZS_EXCLUSIVE;
4642 else
4643 iptype = ZS_SHARED;
4646 switch (iptype) {
4647 case ZS_SHARED:
4648 if (unconfigure_shared_network_interfaces(zlogp,
4649 zoneid) != 0) {
4650 zerror(zlogp, B_FALSE, "unable to unconfigure "
4651 "network interfaces in zone");
4652 goto error;
4654 break;
4655 case ZS_EXCLUSIVE:
4656 if (unconfigure_exclusive_network_interfaces(zlogp,
4657 zoneid) != 0) {
4658 zerror(zlogp, B_FALSE, "unable to unconfigure "
4659 "network interfaces in zone");
4660 goto error;
4662 status = dladm_zone_halt(dld_handle, zoneid);
4663 if (status != DLADM_STATUS_OK) {
4664 zerror(zlogp, B_FALSE, "unable to notify "
4665 "dlmgmtd of zone halt: %s",
4666 dladm_status2str(status, errmsg));
4668 break;
4672 if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
4673 zerror(zlogp, B_TRUE, "unable to abort TCP connections");
4674 goto error;
4677 if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
4678 zerror(zlogp, B_FALSE,
4679 "unable to unmount file systems in zone");
4680 goto error;
4684 * If we are rebooting then we normally don't want to destroy an
4685 * existing temporary pool at this point so that we can just reuse it
4686 * when the zone boots back up. However, it is also possible we were
4687 * running with a temporary pool and the zone configuration has been
4688 * modified to no longer use a temporary pool. In that case we need
4689 * to destroy the temporary pool now. This case looks like the case
4690 * where we never had a temporary pool configured but
4691 * zonecfg_destroy_tmp_pool will do the right thing either way.
4693 if (!unmount_cmd) {
4694 boolean_t destroy_tmp_pool = B_TRUE;
4696 if (rebooting) {
4697 struct zone_psettab pset_tab;
4698 zone_dochandle_t handle;
4700 if ((handle = zonecfg_init_handle()) != NULL &&
4701 zonecfg_get_handle(zone_name, handle) == Z_OK &&
4702 zonecfg_lookup_pset(handle, &pset_tab) == Z_OK)
4703 destroy_tmp_pool = B_FALSE;
4705 zonecfg_fini_handle(handle);
4708 if (destroy_tmp_pool) {
4709 if ((res = zonecfg_destroy_tmp_pool(zone_name, pool_err,
4710 sizeof (pool_err))) != Z_OK) {
4711 if (res == Z_POOL)
4712 zerror(zlogp, B_FALSE, pool_err);
4717 if (zone_destroy(zoneid) != 0) {
4718 zerror(zlogp, B_TRUE, "unable to destroy zone");
4719 goto error;
4723 * Special teardown for alternate boot environments: remove the tmpfs
4724 * root for the zone and then remove it from the map file.
4726 if (unmount_cmd && lu_root_teardown(zlogp) != 0)
4727 goto error;
4729 lofs_discard_mnttab();
4730 return (0);
4732 error:
4733 lofs_discard_mnttab();
4734 return (-1);