tools: remove sparc-only chk4ubin, stabs, & tokenize
[unleashed.git] / usr / src / cmd / zoneadmd / vplat.c
blobb9b69938d1d2772aceb1f3962323ebee2a1f3fa3
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, 2016 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 libc, 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 = reallocarray(mnts, nmnt + MNTTAB_HUNK,
240 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 them.
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), they'll get
1206 * auto-verification which will let them know what's wrong. If they
1207 * modify the zone configuration of a running zone, and don't attempt
1208 * to verify that it's OK, then we won't crash but won't bother trying
1209 * to be too helpful either. zoneadm verify is only a couple keystrokes
1210 * away.
1212 if (!zonecfg_valid_fs_type(fsptr->zone_fs_type)) {
1213 zerror(zlogp, B_FALSE, "cannot mount %s on %s: "
1214 "invalid file-system type %s", fsptr->zone_fs_special,
1215 fsptr->zone_fs_dir, fsptr->zone_fs_type);
1216 return (-1);
1220 * If we're looking at an alternate root environment, then construct
1221 * read-only loopback mounts as necessary. Note that any special
1222 * paths for lofs zone mounts in an alternate root must have
1223 * already been pre-pended with any alternate root path by the
1224 * time we get here.
1226 if (zonecfg_in_alt_root()) {
1227 struct stat64 st;
1229 if (stat64(fsptr->zone_fs_special, &st) != -1 &&
1230 S_ISBLK(st.st_mode)) {
1232 * If we're going to mount a block device we need
1233 * to check if that device is already mounted
1234 * somewhere else, and if so, do a lofs mount
1235 * of the device instead of a direct mount
1237 if (check_lofs_needed(zlogp, fsptr) == -1)
1238 return (-1);
1239 } else if (strcmp(fsptr->zone_fs_type, MNTTYPE_LOFS) == 0) {
1241 * For lofs mounts, the special node is inside the
1242 * alternate root. We need lofs resolution for
1243 * this case in order to get at the underlying
1244 * read-write path.
1246 resolve_lofs(zlogp, fsptr->zone_fs_special,
1247 sizeof (fsptr->zone_fs_special));
1252 * Run 'fsck -m' if there's a device to fsck.
1254 if (fsptr->zone_fs_raw[0] != '\0' &&
1255 dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_raw) != 0) {
1256 return (-1);
1257 } else if (isregfile(fsptr->zone_fs_special) == 1 &&
1258 dofsck(zlogp, fsptr->zone_fs_type, fsptr->zone_fs_special) != 0) {
1259 return (-1);
1263 * Build up mount option string.
1265 optstr[0] = '\0';
1266 if (fsptr->zone_fs_options != NULL) {
1267 (void) strlcpy(optstr, fsptr->zone_fs_options->zone_fsopt_opt,
1268 sizeof (optstr));
1269 for (optptr = fsptr->zone_fs_options->zone_fsopt_next;
1270 optptr != NULL; optptr = optptr->zone_fsopt_next) {
1271 (void) strlcat(optstr, ",", sizeof (optstr));
1272 (void) strlcat(optstr, optptr->zone_fsopt_opt,
1273 sizeof (optstr));
1277 if ((rv = domount(zlogp, fsptr->zone_fs_type, optstr,
1278 fsptr->zone_fs_special, path)) != 0)
1279 return (rv);
1282 * The mount succeeded. If this was not a mount of /dev then
1283 * we're done.
1285 if (strcmp(fsptr->zone_fs_type, MNTTYPE_DEV) != 0)
1286 return (0);
1289 * We just mounted an instance of a /dev filesystem, so now we
1290 * need to configure it.
1292 return (mount_one_dev(zlogp, path, mount_cmd));
1295 static void
1296 free_fs_data(struct zone_fstab *fsarray, uint_t nelem)
1298 uint_t i;
1300 if (fsarray == NULL)
1301 return;
1302 for (i = 0; i < nelem; i++)
1303 zonecfg_free_fs_option_list(fsarray[i].zone_fs_options);
1304 free(fsarray);
1308 * This function initiates the creation of a small Solaris Environment for
1309 * scratch zone. The Environment creation process is split up into two
1310 * functions(build_mounted_pre_var() and build_mounted_post_var()). It
1311 * is done this way because:
1312 * We need to have both /etc and /var in the root of the scratchzone.
1313 * We loopback mount zone's own /etc and /var into the root of the
1314 * scratch zone. Unlike /etc, /var can be a seperate filesystem. So we
1315 * need to delay the mount of /var till the zone's root gets populated.
1316 * So mounting of localdirs[](/etc and /var) have been moved to the
1317 * build_mounted_post_var() which gets called only after the zone
1318 * specific filesystems are mounted.
1320 * Note that the scratch zone we set up for updating the zone (Z_MNT_UPDATE)
1321 * does not loopback mount the zone's own /etc and /var into the root of the
1322 * scratch zone.
1324 static boolean_t
1325 build_mounted_pre_var(zlog_t *zlogp, char *rootpath,
1326 size_t rootlen, const char *zonepath, char *luroot, size_t lurootlen)
1328 char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1329 const char **cpp;
1330 static const char *mkdirs[] = {
1331 "/system", "/system/contract", "/system/object", "/proc",
1332 "/dev", "/tmp", "/a", NULL
1334 char *altstr;
1335 FILE *fp;
1336 uuid_t uuid;
1338 resolve_lofs(zlogp, rootpath, rootlen);
1339 (void) snprintf(luroot, lurootlen, "%s/lu", zonepath);
1340 resolve_lofs(zlogp, luroot, lurootlen);
1341 (void) snprintf(tmp, sizeof (tmp), "%s/bin", luroot);
1342 (void) symlink("./usr/bin", tmp);
1345 * These are mostly special mount points; not handled here. (See
1346 * zone_mount_early.)
1348 for (cpp = mkdirs; *cpp != NULL; cpp++) {
1349 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1350 if (mkdir(tmp, 0755) != 0) {
1351 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1352 return (B_FALSE);
1356 * This is here to support lucopy. If there's an instance of this same
1357 * zone on the current running system, then we mount its root up as
1358 * read-only inside the scratch zone.
1360 (void) zonecfg_get_uuid(zone_name, uuid);
1361 altstr = strdup(zonecfg_get_root());
1362 if (altstr == NULL) {
1363 zerror(zlogp, B_TRUE, "memory allocation failed");
1364 return (B_FALSE);
1366 zonecfg_set_root("");
1367 (void) strlcpy(tmp, zone_name, sizeof (tmp));
1368 (void) zonecfg_get_name_by_uuid(uuid, tmp, sizeof (tmp));
1369 if (zone_get_rootpath(tmp, fromdir, sizeof (fromdir)) == Z_OK &&
1370 strcmp(fromdir, rootpath) != 0) {
1371 (void) snprintf(tmp, sizeof (tmp), "%s/b", luroot);
1372 if (mkdir(tmp, 0755) != 0) {
1373 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1374 return (B_FALSE);
1376 if (domount(zlogp, MNTTYPE_LOFS, RESOURCE_DEFAULT_OPTS, fromdir,
1377 tmp) != 0) {
1378 zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1379 fromdir);
1380 return (B_FALSE);
1383 zonecfg_set_root(altstr);
1384 free(altstr);
1386 if ((fp = zonecfg_open_scratch(luroot, B_TRUE)) == NULL) {
1387 zerror(zlogp, B_TRUE, "cannot open zone mapfile");
1388 return (B_FALSE);
1390 (void) ftruncate(fileno(fp), 0);
1391 if (zonecfg_add_scratch(fp, zone_name, kernzone, "/") == -1) {
1392 zerror(zlogp, B_TRUE, "cannot add zone mapfile entry");
1394 zonecfg_close_scratch(fp);
1395 (void) snprintf(tmp, sizeof (tmp), "%s/a", luroot);
1396 if (domount(zlogp, MNTTYPE_LOFS, "", rootpath, tmp) != 0)
1397 return (B_FALSE);
1398 (void) strlcpy(rootpath, tmp, rootlen);
1399 return (B_TRUE);
1403 static boolean_t
1404 build_mounted_post_var(zlog_t *zlogp, zone_mnt_t mount_cmd, char *rootpath,
1405 const char *luroot)
1407 char tmp[MAXPATHLEN], fromdir[MAXPATHLEN];
1408 const char **cpp;
1409 const char **loopdirs;
1410 const char **tmpdirs;
1411 static const char *localdirs[] = {
1412 "/etc", "/var", NULL
1414 static const char *scr_loopdirs[] = {
1415 "/etc/lib", "/etc/fs", "/lib", "/sbin", "/platform",
1416 "/usr", NULL
1418 static const char *upd_loopdirs[] = {
1419 "/etc", "/kernel", "/lib", "/opt", "/platform", "/sbin",
1420 "/usr", "/var", NULL
1422 static const char *scr_tmpdirs[] = {
1423 "/tmp", "/var/run", NULL
1425 static const char *upd_tmpdirs[] = {
1426 "/tmp", "/var/run", "/var/tmp", NULL
1428 struct stat st;
1430 if (mount_cmd == Z_MNT_SCRATCH) {
1432 * These are mounted read-write from the zone undergoing
1433 * upgrade. We must be careful not to 'leak' things from the
1434 * main system into the zone, and this accomplishes that goal.
1436 for (cpp = localdirs; *cpp != NULL; cpp++) {
1437 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot,
1438 *cpp);
1439 (void) snprintf(fromdir, sizeof (fromdir), "%s%s",
1440 rootpath, *cpp);
1441 if (mkdir(tmp, 0755) != 0) {
1442 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1443 return (B_FALSE);
1445 if (domount(zlogp, MNTTYPE_LOFS, "", fromdir, tmp)
1446 != 0) {
1447 zerror(zlogp, B_TRUE, "cannot mount %s on %s",
1448 tmp, *cpp);
1449 return (B_FALSE);
1454 if (mount_cmd == Z_MNT_UPDATE)
1455 loopdirs = upd_loopdirs;
1456 else
1457 loopdirs = scr_loopdirs;
1460 * These are things mounted read-only from the running system because
1461 * they contain binaries that must match system.
1463 for (cpp = loopdirs; *cpp != NULL; cpp++) {
1464 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1465 if (mkdir(tmp, 0755) != 0) {
1466 if (errno != EEXIST) {
1467 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1468 return (B_FALSE);
1470 if (lstat(tmp, &st) != 0) {
1471 zerror(zlogp, B_TRUE, "cannot stat %s", tmp);
1472 return (B_FALSE);
1475 * Ignore any non-directories encountered. These are
1476 * things that have been converted into symlinks
1477 * (/etc/fs and /etc/lib) and no longer need a lofs
1478 * fixup.
1480 if (!S_ISDIR(st.st_mode))
1481 continue;
1483 if (domount(zlogp, MNTTYPE_LOFS, RESOURCE_DEFAULT_OPTS, *cpp,
1484 tmp) != 0) {
1485 zerror(zlogp, B_TRUE, "cannot mount %s on %s", tmp,
1486 *cpp);
1487 return (B_FALSE);
1491 if (mount_cmd == Z_MNT_UPDATE)
1492 tmpdirs = upd_tmpdirs;
1493 else
1494 tmpdirs = scr_tmpdirs;
1497 * These are things with tmpfs mounted inside.
1499 for (cpp = tmpdirs; *cpp != NULL; cpp++) {
1500 (void) snprintf(tmp, sizeof (tmp), "%s%s", luroot, *cpp);
1501 if (mount_cmd == Z_MNT_SCRATCH && mkdir(tmp, 0755) != 0 &&
1502 errno != EEXIST) {
1503 zerror(zlogp, B_TRUE, "cannot create %s", tmp);
1504 return (B_FALSE);
1508 * We could set the mode for /tmp when we do the mkdir but
1509 * since that can be modified by the umask we will just set
1510 * the correct mode for /tmp now.
1512 if (strcmp(*cpp, "/tmp") == 0 && chmod(tmp, 01777) != 0) {
1513 zerror(zlogp, B_TRUE, "cannot chmod %s", tmp);
1514 return (B_FALSE);
1517 if (domount(zlogp, MNTTYPE_TMPFS, "", "swap", tmp) != 0) {
1518 zerror(zlogp, B_TRUE, "cannot mount swap on %s", *cpp);
1519 return (B_FALSE);
1522 return (B_TRUE);
1525 typedef struct plat_gmount_cb_data {
1526 zlog_t *pgcd_zlogp;
1527 struct zone_fstab **pgcd_fs_tab;
1528 int *pgcd_num_fs;
1529 } plat_gmount_cb_data_t;
1532 * plat_gmount_cb() is a callback function invoked by libbrand to iterate
1533 * through all global brand platform mounts.
1536 plat_gmount_cb(void *data, const char *spec, const char *dir,
1537 const char *fstype, const char *opt)
1539 plat_gmount_cb_data_t *cp = data;
1540 zlog_t *zlogp = cp->pgcd_zlogp;
1541 struct zone_fstab *fs_ptr = *cp->pgcd_fs_tab;
1542 int num_fs = *cp->pgcd_num_fs;
1543 struct zone_fstab *fsp, *tmp_ptr;
1545 num_fs++;
1546 if ((tmp_ptr = reallocarray(fs_ptr, num_fs,
1547 sizeof (*tmp_ptr))) == NULL) {
1548 zerror(zlogp, B_TRUE, "memory allocation failed");
1549 return (-1);
1552 fs_ptr = tmp_ptr;
1553 fsp = &fs_ptr[num_fs - 1];
1555 /* update the callback struct passed in */
1556 *cp->pgcd_fs_tab = fs_ptr;
1557 *cp->pgcd_num_fs = num_fs;
1559 fsp->zone_fs_raw[0] = '\0';
1560 (void) strlcpy(fsp->zone_fs_special, spec,
1561 sizeof (fsp->zone_fs_special));
1562 (void) strlcpy(fsp->zone_fs_dir, dir, sizeof (fsp->zone_fs_dir));
1563 (void) strlcpy(fsp->zone_fs_type, fstype, sizeof (fsp->zone_fs_type));
1564 fsp->zone_fs_options = NULL;
1565 if ((opt != NULL) &&
1566 (zonecfg_add_fs_option(fsp, (char *)opt) != Z_OK)) {
1567 zerror(zlogp, B_FALSE, "error adding property");
1568 return (-1);
1571 return (0);
1574 static int
1575 mount_filesystems_fsent(zone_dochandle_t handle, zlog_t *zlogp,
1576 struct zone_fstab **fs_tabp, int *num_fsp, zone_mnt_t mount_cmd)
1578 struct zone_fstab *tmp_ptr, *fs_ptr, *fsp, fstab;
1579 int num_fs;
1581 num_fs = *num_fsp;
1582 fs_ptr = *fs_tabp;
1584 if (zonecfg_setfsent(handle) != Z_OK) {
1585 zerror(zlogp, B_FALSE, "invalid configuration");
1586 return (-1);
1588 while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
1590 * ZFS filesystems will not be accessible under an alternate
1591 * root, since the pool will not be known. Ignore them in this
1592 * case.
1594 if (ALT_MOUNT(mount_cmd) &&
1595 strcmp(fstab.zone_fs_type, MNTTYPE_ZFS) == 0)
1596 continue;
1598 num_fs++;
1599 if ((tmp_ptr = reallocarray(fs_ptr, num_fs,
1600 sizeof (*tmp_ptr))) == NULL) {
1601 zerror(zlogp, B_TRUE, "memory allocation failed");
1602 (void) zonecfg_endfsent(handle);
1603 return (-1);
1605 /* update the pointers passed in */
1606 *fs_tabp = tmp_ptr;
1607 *num_fsp = num_fs;
1609 fs_ptr = tmp_ptr;
1610 fsp = &fs_ptr[num_fs - 1];
1611 (void) strlcpy(fsp->zone_fs_dir,
1612 fstab.zone_fs_dir, sizeof (fsp->zone_fs_dir));
1613 (void) strlcpy(fsp->zone_fs_raw, fstab.zone_fs_raw,
1614 sizeof (fsp->zone_fs_raw));
1615 (void) strlcpy(fsp->zone_fs_type, fstab.zone_fs_type,
1616 sizeof (fsp->zone_fs_type));
1617 fsp->zone_fs_options = fstab.zone_fs_options;
1620 * For all lofs mounts, make sure that the 'special'
1621 * entry points inside the alternate root. The
1622 * source path for a lofs mount in a given zone needs
1623 * to be relative to the root of the boot environment
1624 * that contains the zone. Note that we don't do this
1625 * for non-lofs mounts since they will have a device
1626 * as a backing store and device paths must always be
1627 * specified relative to the current boot environment.
1629 fsp->zone_fs_special[0] = '\0';
1630 if (strcmp(fsp->zone_fs_type, MNTTYPE_LOFS) == 0) {
1631 (void) strlcat(fsp->zone_fs_special, zonecfg_get_root(),
1632 sizeof (fsp->zone_fs_special));
1634 (void) strlcat(fsp->zone_fs_special, fstab.zone_fs_special,
1635 sizeof (fsp->zone_fs_special));
1637 (void) zonecfg_endfsent(handle);
1638 return (0);
1641 static int
1642 mount_filesystems(zlog_t *zlogp, zone_mnt_t mount_cmd)
1644 char rootpath[MAXPATHLEN];
1645 char zonepath[MAXPATHLEN];
1646 char brand[MAXNAMELEN];
1647 char luroot[MAXPATHLEN];
1648 int i, num_fs = 0;
1649 struct zone_fstab *fs_ptr = NULL;
1650 zone_dochandle_t handle = NULL;
1651 zone_state_t zstate;
1652 brand_handle_t bh;
1653 plat_gmount_cb_data_t cb;
1655 if (zone_get_state(zone_name, &zstate) != Z_OK ||
1656 (zstate != ZONE_STATE_READY && zstate != ZONE_STATE_MOUNTED)) {
1657 zerror(zlogp, B_FALSE,
1658 "zone must be in '%s' or '%s' state to mount file-systems",
1659 zone_state_str(ZONE_STATE_READY),
1660 zone_state_str(ZONE_STATE_MOUNTED));
1661 goto bad;
1664 if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
1665 zerror(zlogp, B_TRUE, "unable to determine zone path");
1666 goto bad;
1669 if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
1670 zerror(zlogp, B_TRUE, "unable to determine zone root");
1671 goto bad;
1674 if ((handle = zonecfg_init_handle()) == NULL) {
1675 zerror(zlogp, B_TRUE, "getting zone configuration handle");
1676 goto bad;
1678 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK ||
1679 zonecfg_setfsent(handle) != Z_OK) {
1680 zerror(zlogp, B_FALSE, "invalid configuration");
1681 goto bad;
1685 * If we are mounting the zone, then we must always use the default
1686 * brand global mounts.
1688 if (ALT_MOUNT(mount_cmd)) {
1689 (void) strlcpy(brand, default_brand, sizeof (brand));
1690 } else {
1691 (void) strlcpy(brand, brand_name, sizeof (brand));
1694 /* Get a handle to the brand info for this zone */
1695 if ((bh = brand_open(brand)) == NULL) {
1696 zerror(zlogp, B_FALSE, "unable to determine zone brand");
1697 zonecfg_fini_handle(handle);
1698 return (-1);
1702 * Get the list of global filesystems to mount from the brand
1703 * configuration.
1705 cb.pgcd_zlogp = zlogp;
1706 cb.pgcd_fs_tab = &fs_ptr;
1707 cb.pgcd_num_fs = &num_fs;
1708 if (brand_platform_iter_gmounts(bh, zone_name, zonepath,
1709 plat_gmount_cb, &cb) != 0) {
1710 zerror(zlogp, B_FALSE, "unable to mount filesystems");
1711 brand_close(bh);
1712 zonecfg_fini_handle(handle);
1713 return (-1);
1715 brand_close(bh);
1718 * Iterate through the rest of the filesystems. Sort them all,
1719 * then mount them in sorted order. This is to make sure the
1720 * higher level directories (e.g., /usr) get mounted before
1721 * any beneath them (e.g., /usr/local).
1723 if (mount_filesystems_fsent(handle, zlogp, &fs_ptr, &num_fs,
1724 mount_cmd) != 0)
1725 goto bad;
1727 zonecfg_fini_handle(handle);
1728 handle = NULL;
1731 * Normally when we mount a zone all the zone filesystems
1732 * get mounted relative to rootpath, which is usually
1733 * <zonepath>/root. But when mounting a zone for administration
1734 * purposes via the zone "mount" state, build_mounted_pre_var()
1735 * updates rootpath to be <zonepath>/lu/a so we'll mount all
1736 * the zones filesystems there instead.
1738 * build_mounted_pre_var() and build_mounted_post_var() will
1739 * also do some extra work to create directories and lofs mount
1740 * a bunch of global zone file system paths into <zonepath>/lu.
1742 * This allows us to be able to enter the zone (now rooted at
1743 * <zonepath>/lu) and run the upgrade/patch tools that are in the
1744 * global zone and have them upgrade the to-be-modified zone's
1745 * files mounted on /a. (Which mirrors the existing standard
1746 * upgrade environment.)
1748 * There is of course one catch. When doing the upgrade
1749 * we need <zoneroot>/lu/dev to be the /dev filesystem
1750 * for the zone and we don't want to have any /dev filesystem
1751 * mounted at <zoneroot>/lu/a/dev. Since /dev is specified
1752 * as a normal zone filesystem by default we'll try to mount
1753 * it at <zoneroot>/lu/a/dev, so we have to detect this
1754 * case and instead mount it at <zoneroot>/lu/dev.
1756 * All this work is done in three phases:
1757 * 1) Create and populate lu directory (build_mounted_pre_var()).
1758 * 2) Mount the required filesystems as per the zone configuration.
1759 * 3) Set up the rest of the scratch zone environment
1760 * (build_mounted_post_var()).
1762 if (ALT_MOUNT(mount_cmd) && !build_mounted_pre_var(zlogp,
1763 rootpath, sizeof (rootpath), zonepath, luroot, sizeof (luroot)))
1764 goto bad;
1766 qsort(fs_ptr, num_fs, sizeof (*fs_ptr), fs_compare);
1768 for (i = 0; i < num_fs; i++) {
1769 if (ALT_MOUNT(mount_cmd) &&
1770 strcmp(fs_ptr[i].zone_fs_dir, "/dev") == 0) {
1771 size_t slen = strlen(rootpath) - 2;
1774 * By default we'll try to mount /dev as /a/dev
1775 * but /dev is special and always goes at the top
1776 * so strip the trailing '/a' from the rootpath.
1778 assert(strcmp(&rootpath[slen], "/a") == 0);
1779 rootpath[slen] = '\0';
1780 if (mount_one(zlogp, &fs_ptr[i], rootpath, mount_cmd)
1781 != 0)
1782 goto bad;
1783 rootpath[slen] = '/';
1784 continue;
1786 if (mount_one(zlogp, &fs_ptr[i], rootpath, mount_cmd) != 0)
1787 goto bad;
1789 if (ALT_MOUNT(mount_cmd) &&
1790 !build_mounted_post_var(zlogp, mount_cmd, rootpath, luroot))
1791 goto bad;
1793 free_fs_data(fs_ptr, num_fs);
1796 * Everything looks fine.
1798 return (0);
1800 bad:
1801 if (handle != NULL)
1802 zonecfg_fini_handle(handle);
1803 free_fs_data(fs_ptr, num_fs);
1804 return (-1);
1807 /* caller makes sure neither parameter is NULL */
1808 static int
1809 addr2netmask(char *prefixstr, int maxprefixlen, uchar_t *maskstr)
1811 int prefixlen;
1813 prefixlen = atoi(prefixstr);
1814 if (prefixlen < 0 || prefixlen > maxprefixlen)
1815 return (1);
1816 while (prefixlen > 0) {
1817 if (prefixlen >= 8) {
1818 *maskstr++ = 0xFF;
1819 prefixlen -= 8;
1820 continue;
1822 *maskstr |= 1 << (8 - prefixlen);
1823 prefixlen--;
1825 return (0);
1829 * Tear down all interfaces belonging to the given zone. This should
1830 * be called with the zone in a state other than "running", so that
1831 * interfaces can't be assigned to the zone after this returns.
1833 * If anything goes wrong, log an error message and return an error.
1835 static int
1836 unconfigure_shared_network_interfaces(zlog_t *zlogp, zoneid_t zone_id)
1838 struct lifnum lifn;
1839 struct lifconf lifc;
1840 struct lifreq *lifrp, lifrl;
1841 int64_t lifc_flags = LIFC_NOXMIT | LIFC_ALLZONES;
1842 int num_ifs, s, i, ret_code = 0;
1843 uint_t bufsize;
1844 char *buf = NULL;
1846 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1847 zerror(zlogp, B_TRUE, "could not get socket");
1848 ret_code = -1;
1849 goto bad;
1851 lifn.lifn_family = AF_UNSPEC;
1852 lifn.lifn_flags = (int)lifc_flags;
1853 if (ioctl(s, SIOCGLIFNUM, (char *)&lifn) < 0) {
1854 zerror(zlogp, B_TRUE,
1855 "could not determine number of network interfaces");
1856 ret_code = -1;
1857 goto bad;
1859 num_ifs = lifn.lifn_count;
1860 bufsize = num_ifs * sizeof (struct lifreq);
1861 if ((buf = malloc(bufsize)) == NULL) {
1862 zerror(zlogp, B_TRUE, "memory allocation failed");
1863 ret_code = -1;
1864 goto bad;
1866 lifc.lifc_family = AF_UNSPEC;
1867 lifc.lifc_flags = (int)lifc_flags;
1868 lifc.lifc_len = bufsize;
1869 lifc.lifc_buf = buf;
1870 if (ioctl(s, SIOCGLIFCONF, (char *)&lifc) < 0) {
1871 zerror(zlogp, B_TRUE, "could not get configured network "
1872 "interfaces");
1873 ret_code = -1;
1874 goto bad;
1876 lifrp = lifc.lifc_req;
1877 for (i = lifc.lifc_len / sizeof (struct lifreq); i > 0; i--, lifrp++) {
1878 (void) close(s);
1879 if ((s = socket(lifrp->lifr_addr.ss_family, SOCK_DGRAM, 0)) <
1880 0) {
1881 zerror(zlogp, B_TRUE, "%s: could not get socket",
1882 lifrl.lifr_name);
1883 ret_code = -1;
1884 continue;
1886 (void) memset(&lifrl, 0, sizeof (lifrl));
1887 (void) strncpy(lifrl.lifr_name, lifrp->lifr_name,
1888 sizeof (lifrl.lifr_name));
1889 if (ioctl(s, SIOCGLIFZONE, (caddr_t)&lifrl) < 0) {
1890 if (errno == ENXIO)
1892 * Interface may have been removed by admin or
1893 * another zone halting.
1895 continue;
1896 zerror(zlogp, B_TRUE,
1897 "%s: could not determine the zone to which this "
1898 "network interface is bound", lifrl.lifr_name);
1899 ret_code = -1;
1900 continue;
1902 if (lifrl.lifr_zoneid == zone_id) {
1903 if (ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifrl) < 0) {
1904 zerror(zlogp, B_TRUE,
1905 "%s: could not remove network interface",
1906 lifrl.lifr_name);
1907 ret_code = -1;
1908 continue;
1912 bad:
1913 if (s > 0)
1914 (void) close(s);
1915 free(buf);
1916 return (ret_code);
1919 static union sockunion {
1920 struct sockaddr sa;
1921 struct sockaddr_in sin;
1922 struct sockaddr_dl sdl;
1923 struct sockaddr_in6 sin6;
1924 } so_dst, so_ifp;
1926 static struct {
1927 struct rt_msghdr hdr;
1928 char space[512];
1929 } rtmsg;
1931 static int
1932 salen(struct sockaddr *sa)
1934 switch (sa->sa_family) {
1935 case AF_INET:
1936 return (sizeof (struct sockaddr_in));
1937 case AF_LINK:
1938 return (sizeof (struct sockaddr_dl));
1939 case AF_INET6:
1940 return (sizeof (struct sockaddr_in6));
1941 default:
1942 return (sizeof (struct sockaddr));
1946 #define ROUNDUP_LONG(a) \
1947 ((a) > 0 ? (1 + (((a) - 1) | (sizeof (long) - 1))) : sizeof (long))
1950 * Look up which zone is using a given IP address. The address in question
1951 * is expected to have been stuffed into the structure to which lifr points
1952 * via a previous SIOCGLIFADDR ioctl().
1954 * This is done using black router socket magic.
1956 * Return the name of the zone on success or NULL on failure.
1958 * This is a lot of code for a simple task; a new ioctl request to take care
1959 * of this might be a useful RFE.
1962 static char *
1963 who_is_using(zlog_t *zlogp, struct lifreq *lifr)
1965 static char answer[ZONENAME_MAX];
1966 pid_t pid;
1967 int s, rlen, l, i;
1968 char *cp = rtmsg.space;
1969 struct sockaddr_dl *ifp = NULL;
1970 struct sockaddr *sa;
1971 char save_if_name[LIFNAMSIZ];
1973 answer[0] = '\0';
1975 pid = getpid();
1976 if ((s = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
1977 zerror(zlogp, B_TRUE, "could not get routing socket");
1978 return (NULL);
1981 if (lifr->lifr_addr.ss_family == AF_INET) {
1982 struct sockaddr_in *sin4;
1984 so_dst.sa.sa_family = AF_INET;
1985 sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
1986 so_dst.sin.sin_addr = sin4->sin_addr;
1987 } else {
1988 struct sockaddr_in6 *sin6;
1990 so_dst.sa.sa_family = AF_INET6;
1991 sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
1992 so_dst.sin6.sin6_addr = sin6->sin6_addr;
1995 so_ifp.sa.sa_family = AF_LINK;
1997 (void) memset(&rtmsg, 0, sizeof (rtmsg));
1998 rtmsg.hdr.rtm_type = RTM_GET;
1999 rtmsg.hdr.rtm_flags = RTF_UP | RTF_HOST;
2000 rtmsg.hdr.rtm_version = RTM_VERSION;
2001 rtmsg.hdr.rtm_seq = ++rts_seqno;
2002 rtmsg.hdr.rtm_addrs = RTA_IFP | RTA_DST;
2004 l = ROUNDUP_LONG(salen(&so_dst.sa));
2005 (void) memmove(cp, &(so_dst), l);
2006 cp += l;
2007 l = ROUNDUP_LONG(salen(&so_ifp.sa));
2008 (void) memmove(cp, &(so_ifp), l);
2009 cp += l;
2011 rtmsg.hdr.rtm_msglen = l = cp - (char *)&rtmsg;
2013 if ((rlen = write(s, &rtmsg, l)) < 0) {
2014 zerror(zlogp, B_TRUE, "writing to routing socket");
2015 return (NULL);
2016 } else if (rlen < (int)rtmsg.hdr.rtm_msglen) {
2017 zerror(zlogp, B_TRUE,
2018 "write to routing socket got only %d for len\n", rlen);
2019 return (NULL);
2021 do {
2022 l = read(s, &rtmsg, sizeof (rtmsg));
2023 } while (l > 0 && (rtmsg.hdr.rtm_seq != rts_seqno ||
2024 rtmsg.hdr.rtm_pid != pid));
2025 if (l < 0) {
2026 zerror(zlogp, B_TRUE, "reading from routing socket");
2027 return (NULL);
2030 if (rtmsg.hdr.rtm_version != RTM_VERSION) {
2031 zerror(zlogp, B_FALSE,
2032 "routing message version %d not understood",
2033 rtmsg.hdr.rtm_version);
2034 return (NULL);
2036 if (rtmsg.hdr.rtm_msglen != (ushort_t)l) {
2037 zerror(zlogp, B_FALSE, "message length mismatch, "
2038 "expected %d bytes, returned %d bytes",
2039 rtmsg.hdr.rtm_msglen, l);
2040 return (NULL);
2042 if (rtmsg.hdr.rtm_errno != 0) {
2043 errno = rtmsg.hdr.rtm_errno;
2044 zerror(zlogp, B_TRUE, "RTM_GET routing socket message");
2045 return (NULL);
2047 if ((rtmsg.hdr.rtm_addrs & RTA_IFP) == 0) {
2048 zerror(zlogp, B_FALSE, "network interface not found");
2049 return (NULL);
2051 cp = ((char *)(&rtmsg.hdr + 1));
2052 for (i = 1; i != 0; i <<= 1) {
2053 /* LINTED E_BAD_PTR_CAST_ALIGN */
2054 sa = (struct sockaddr *)cp;
2055 if (i != RTA_IFP) {
2056 if ((i & rtmsg.hdr.rtm_addrs) != 0)
2057 cp += ROUNDUP_LONG(salen(sa));
2058 continue;
2060 if (sa->sa_family == AF_LINK &&
2061 ((struct sockaddr_dl *)sa)->sdl_nlen != 0)
2062 ifp = (struct sockaddr_dl *)sa;
2063 break;
2065 if (ifp == NULL) {
2066 zerror(zlogp, B_FALSE, "network interface could not be "
2067 "determined");
2068 return (NULL);
2072 * We need to set the I/F name to what we got above, then do the
2073 * appropriate ioctl to get its zone name. But lifr->lifr_name is
2074 * used by the calling function to do a REMOVEIF, so if we leave the
2075 * "good" zone's I/F name in place, *that* I/F will be removed instead
2076 * of the bad one. So we save the old (bad) I/F name before over-
2077 * writing it and doing the ioctl, then restore it after the ioctl.
2079 (void) strlcpy(save_if_name, lifr->lifr_name, sizeof (save_if_name));
2080 (void) strncpy(lifr->lifr_name, ifp->sdl_data, ifp->sdl_nlen);
2081 lifr->lifr_name[ifp->sdl_nlen] = '\0';
2082 i = ioctl(s, SIOCGLIFZONE, lifr);
2083 (void) strlcpy(lifr->lifr_name, save_if_name, sizeof (save_if_name));
2084 if (i < 0) {
2085 zerror(zlogp, B_TRUE,
2086 "%s: could not determine the zone network interface "
2087 "belongs to", lifr->lifr_name);
2088 return (NULL);
2090 if (getzonenamebyid(lifr->lifr_zoneid, answer, sizeof (answer)) < 0)
2091 (void) snprintf(answer, sizeof (answer), "%d",
2092 lifr->lifr_zoneid);
2094 if (strlen(answer) > 0)
2095 return (answer);
2096 return (NULL);
2100 * Configures a single interface: a new virtual interface is added, based on
2101 * the physical interface nwiftabptr->zone_nwif_physical, with the address
2102 * specified in nwiftabptr->zone_nwif_address, for zone zone_id. Note that
2103 * the "address" can be an IPv6 address (with a /prefixlength required), an
2104 * IPv4 address (with a /prefixlength optional), or a name; for the latter,
2105 * an IPv4 name-to-address resolution will be attempted.
2107 * If anything goes wrong, we log an detailed error message, attempt to tear
2108 * down whatever we set up and return an error.
2110 static int
2111 configure_one_interface(zlog_t *zlogp, zoneid_t zone_id,
2112 struct zone_nwiftab *nwiftabptr)
2114 struct lifreq lifr;
2115 struct sockaddr_in netmask4;
2116 struct sockaddr_in6 netmask6;
2117 struct sockaddr_storage laddr;
2118 struct in_addr in4;
2119 sa_family_t af;
2120 char *slashp = strchr(nwiftabptr->zone_nwif_address, '/');
2121 int s;
2122 boolean_t got_netmask = B_FALSE;
2123 boolean_t is_loopback = B_FALSE;
2124 char addrstr4[INET_ADDRSTRLEN];
2125 int res;
2127 res = zonecfg_valid_net_address(nwiftabptr->zone_nwif_address, &lifr);
2128 if (res != Z_OK) {
2129 zerror(zlogp, B_FALSE, "%s: %s", zonecfg_strerror(res),
2130 nwiftabptr->zone_nwif_address);
2131 return (-1);
2133 af = lifr.lifr_addr.ss_family;
2134 if (af == AF_INET)
2135 in4 = ((struct sockaddr_in *)(&lifr.lifr_addr))->sin_addr;
2136 if ((s = socket(af, SOCK_DGRAM, 0)) < 0) {
2137 zerror(zlogp, B_TRUE, "could not get socket");
2138 return (-1);
2142 * This is a similar kind of "hack" like in addif() to get around
2143 * the problem of SIOCLIFADDIF. The problem is that this ioctl
2144 * does not include the netmask when adding a logical interface.
2145 * To get around this problem, we first add the logical interface
2146 * with a 0 address. After that, we set the netmask if provided.
2147 * Finally we set the interface address.
2149 laddr = lifr.lifr_addr;
2150 (void) strlcpy(lifr.lifr_name, nwiftabptr->zone_nwif_physical,
2151 sizeof (lifr.lifr_name));
2152 (void) memset(&lifr.lifr_addr, 0, sizeof (lifr.lifr_addr));
2154 if (ioctl(s, SIOCLIFADDIF, (caddr_t)&lifr) < 0) {
2156 * Here, we know that the interface can't be brought up.
2157 * A similar warning message was already printed out to
2158 * the console by zoneadm(8) so instead we log the
2159 * message to syslog and continue.
2161 zerror(&logsys, B_TRUE, "WARNING: skipping network interface "
2162 "'%s' which may not be present/plumbed in the "
2163 "global zone.", lifr.lifr_name);
2164 (void) close(s);
2165 return (Z_OK);
2168 /* Preserve literal IPv4 address for later potential printing. */
2169 if (af == AF_INET)
2170 (void) inet_ntop(AF_INET, &in4, addrstr4, INET_ADDRSTRLEN);
2172 lifr.lifr_zoneid = zone_id;
2173 if (ioctl(s, SIOCSLIFZONE, (caddr_t)&lifr) < 0) {
2174 zerror(zlogp, B_TRUE, "%s: could not place network interface "
2175 "into zone", lifr.lifr_name);
2176 goto bad;
2180 * Loopback interface will use the default netmask assigned, if no
2181 * netmask is found.
2183 if (strcmp(nwiftabptr->zone_nwif_physical, "lo0") == 0) {
2184 is_loopback = B_TRUE;
2186 if (af == AF_INET) {
2188 * The IPv4 netmask can be determined either
2189 * directly if a prefix length was supplied with
2190 * the address or via the netmasks database. Not
2191 * being able to determine it is a common failure,
2192 * but it often is not fatal to operation of the
2193 * interface. In that case, a warning will be
2194 * printed after the rest of the interface's
2195 * parameters have been configured.
2197 (void) memset(&netmask4, 0, sizeof (netmask4));
2198 if (slashp != NULL) {
2199 if (addr2netmask(slashp + 1, V4_ADDR_LEN,
2200 (uchar_t *)&netmask4.sin_addr) != 0) {
2201 *slashp = '/';
2202 zerror(zlogp, B_FALSE,
2203 "%s: invalid prefix length in %s",
2204 lifr.lifr_name,
2205 nwiftabptr->zone_nwif_address);
2206 goto bad;
2208 got_netmask = B_TRUE;
2209 } else if (getnetmaskbyaddr(in4,
2210 &netmask4.sin_addr) == 0) {
2211 got_netmask = B_TRUE;
2213 if (got_netmask) {
2214 netmask4.sin_family = af;
2215 (void) memcpy(&lifr.lifr_addr, &netmask4,
2216 sizeof (netmask4));
2218 } else {
2219 (void) memset(&netmask6, 0, sizeof (netmask6));
2220 if (addr2netmask(slashp + 1, V6_ADDR_LEN,
2221 (uchar_t *)&netmask6.sin6_addr) != 0) {
2222 *slashp = '/';
2223 zerror(zlogp, B_FALSE,
2224 "%s: invalid prefix length in %s",
2225 lifr.lifr_name,
2226 nwiftabptr->zone_nwif_address);
2227 goto bad;
2229 got_netmask = B_TRUE;
2230 netmask6.sin6_family = af;
2231 (void) memcpy(&lifr.lifr_addr, &netmask6,
2232 sizeof (netmask6));
2234 if (got_netmask &&
2235 ioctl(s, SIOCSLIFNETMASK, (caddr_t)&lifr) < 0) {
2236 zerror(zlogp, B_TRUE, "%s: could not set netmask",
2237 lifr.lifr_name);
2238 goto bad;
2241 /* Set the interface address */
2242 lifr.lifr_addr = laddr;
2243 if (ioctl(s, SIOCSLIFADDR, (caddr_t)&lifr) < 0) {
2244 zerror(zlogp, B_TRUE,
2245 "%s: could not set IP address to %s",
2246 lifr.lifr_name, nwiftabptr->zone_nwif_address);
2247 goto bad;
2250 if (ioctl(s, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2251 zerror(zlogp, B_TRUE, "%s: could not get flags",
2252 lifr.lifr_name);
2253 goto bad;
2255 lifr.lifr_flags |= IFF_UP;
2256 if (ioctl(s, SIOCSLIFFLAGS, (caddr_t)&lifr) < 0) {
2257 int save_errno = errno;
2258 char *zone_using;
2261 * If we failed with something other than EADDRNOTAVAIL,
2262 * then skip to the end. Otherwise, look up our address,
2263 * then call a function to determine which zone is already
2264 * using that address.
2266 if (errno != EADDRNOTAVAIL) {
2267 zerror(zlogp, B_TRUE,
2268 "%s: could not bring network interface up",
2269 lifr.lifr_name);
2270 goto bad;
2272 if (ioctl(s, SIOCGLIFADDR, (caddr_t)&lifr) < 0) {
2273 zerror(zlogp, B_TRUE, "%s: could not get address",
2274 lifr.lifr_name);
2275 goto bad;
2277 zone_using = who_is_using(zlogp, &lifr);
2278 errno = save_errno;
2279 if (zone_using == NULL)
2280 zerror(zlogp, B_TRUE,
2281 "%s: could not bring network interface up",
2282 lifr.lifr_name);
2283 else
2284 zerror(zlogp, B_TRUE, "%s: could not bring network "
2285 "interface up: address in use by zone '%s'",
2286 lifr.lifr_name, zone_using);
2287 goto bad;
2290 if (!got_netmask && !is_loopback) {
2292 * A common, but often non-fatal problem, is that the system
2293 * cannot find the netmask for an interface address. This is
2294 * often caused by it being only in /etc/inet/netmasks, but
2295 * /etc/nsswitch.conf says to use NIS or NIS+ and it's not
2296 * in that. This doesn't show up at boot because the netmask
2297 * is obtained from /etc/inet/netmasks when no network
2298 * interfaces are up, but isn't consulted when NIS/NIS+ is
2299 * available. We warn the user here that something like this
2300 * has happened and we're just running with a default and
2301 * possible incorrect netmask.
2303 char buffer[INET6_ADDRSTRLEN];
2304 void *addr;
2305 const char *nomatch = "no matching subnet found in netmasks(4)";
2307 if (af == AF_INET)
2308 addr = &((struct sockaddr_in *)
2309 (&lifr.lifr_addr))->sin_addr;
2310 else
2311 addr = &((struct sockaddr_in6 *)
2312 (&lifr.lifr_addr))->sin6_addr;
2315 * Find out what netmask the interface is going to be using.
2316 * If we just brought up an IPMP data address on an underlying
2317 * interface above, the address will have already migrated, so
2318 * the SIOCGLIFNETMASK won't be able to find it (but we need
2319 * to bring the address up to get the actual netmask). Just
2320 * omit printing the actual netmask in this corner-case.
2322 if (ioctl(s, SIOCGLIFNETMASK, (caddr_t)&lifr) < 0 ||
2323 inet_ntop(af, addr, buffer, sizeof (buffer)) == NULL) {
2324 zerror(zlogp, B_FALSE, "WARNING: %s; using default.",
2325 nomatch);
2326 } else {
2327 zerror(zlogp, B_FALSE,
2328 "WARNING: %s: %s: %s; using default of %s.",
2329 lifr.lifr_name, nomatch, addrstr4, buffer);
2334 * If a default router was specified for this interface
2335 * set the route now. Ignore if already set.
2337 if (strlen(nwiftabptr->zone_nwif_defrouter) > 0) {
2338 int status;
2339 char *argv[7];
2341 argv[0] = "route";
2342 argv[1] = "add";
2343 argv[2] = "-ifp";
2344 argv[3] = nwiftabptr->zone_nwif_physical;
2345 argv[4] = "default";
2346 argv[5] = nwiftabptr->zone_nwif_defrouter;
2347 argv[6] = NULL;
2349 status = forkexec(zlogp, "/usr/sbin/route", argv);
2350 if (status != 0 && status != EEXIST)
2351 zerror(zlogp, B_FALSE, "Unable to set route for "
2352 "interface %s to %s\n",
2353 nwiftabptr->zone_nwif_physical,
2354 nwiftabptr->zone_nwif_defrouter);
2357 (void) close(s);
2358 return (Z_OK);
2359 bad:
2360 (void) ioctl(s, SIOCLIFREMOVEIF, (caddr_t)&lifr);
2361 (void) close(s);
2362 return (-1);
2366 * Sets up network interfaces based on information from the zone configuration.
2367 * IPv4 and IPv6 loopback interfaces are set up "for free", modeling the global
2368 * system.
2370 * If anything goes wrong, we log a general error message, attempt to tear down
2371 * whatever we set up, and return an error.
2373 static int
2374 configure_shared_network_interfaces(zlog_t *zlogp)
2376 zone_dochandle_t handle;
2377 struct zone_nwiftab nwiftab, loopback_iftab;
2378 zoneid_t zoneid;
2380 if ((zoneid = getzoneidbyname(zone_name)) == ZONE_ID_UNDEFINED) {
2381 zerror(zlogp, B_TRUE, "unable to get zoneid");
2382 return (-1);
2385 if ((handle = zonecfg_init_handle()) == NULL) {
2386 zerror(zlogp, B_TRUE, "getting zone configuration handle");
2387 return (-1);
2389 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2390 zerror(zlogp, B_FALSE, "invalid configuration");
2391 zonecfg_fini_handle(handle);
2392 return (-1);
2394 if (zonecfg_setnwifent(handle) == Z_OK) {
2395 for (;;) {
2396 if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2397 break;
2398 if (configure_one_interface(zlogp, zoneid, &nwiftab) !=
2399 Z_OK) {
2400 (void) zonecfg_endnwifent(handle);
2401 zonecfg_fini_handle(handle);
2402 return (-1);
2405 (void) zonecfg_endnwifent(handle);
2407 zonecfg_fini_handle(handle);
2408 (void) strlcpy(loopback_iftab.zone_nwif_physical, "lo0",
2409 sizeof (loopback_iftab.zone_nwif_physical));
2410 (void) strlcpy(loopback_iftab.zone_nwif_address, "127.0.0.1",
2411 sizeof (loopback_iftab.zone_nwif_address));
2412 loopback_iftab.zone_nwif_defrouter[0] = '\0';
2413 if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2414 return (-1);
2416 /* Always plumb up the IPv6 loopback interface. */
2417 (void) strlcpy(loopback_iftab.zone_nwif_address, "::1/128",
2418 sizeof (loopback_iftab.zone_nwif_address));
2419 if (configure_one_interface(zlogp, zoneid, &loopback_iftab) != Z_OK)
2420 return (-1);
2421 return (0);
2424 static void
2425 zdlerror(zlog_t *zlogp, dladm_status_t err, const char *dlname, const char *str)
2427 char errmsg[DLADM_STRSIZE];
2429 (void) dladm_status2str(err, errmsg);
2430 zerror(zlogp, B_FALSE, "%s '%s': %s", str, dlname, errmsg);
2433 static int
2434 add_datalink(zlog_t *zlogp, char *zone_name, datalink_id_t linkid, char *dlname)
2436 dladm_status_t err;
2437 boolean_t cpuset, poolset;
2438 char *poolp;
2440 /* First check if it's in use by global zone. */
2441 if (zonecfg_ifname_exists(AF_INET, dlname) ||
2442 zonecfg_ifname_exists(AF_INET6, dlname)) {
2443 zerror(zlogp, B_FALSE, "WARNING: skipping network interface "
2444 "'%s' which is used in the global zone", dlname);
2445 return (-1);
2448 /* Set zoneid of this link. */
2449 err = dladm_set_linkprop(dld_handle, linkid, "zone", &zone_name, 1,
2450 DLADM_OPT_ACTIVE);
2451 if (err != DLADM_STATUS_OK) {
2452 zdlerror(zlogp, err, dlname,
2453 "WARNING: unable to add network interface");
2454 return (-1);
2458 * Set the pool of this link if the zone has a pool and
2459 * neither the cpus nor the pool datalink property is
2460 * already set.
2462 err = dladm_linkprop_is_set(dld_handle, linkid, DLADM_PROP_VAL_CURRENT,
2463 "cpus", &cpuset);
2464 if (err != DLADM_STATUS_OK) {
2465 zdlerror(zlogp, err, dlname,
2466 "WARNING: unable to check if cpus link property is set");
2468 err = dladm_linkprop_is_set(dld_handle, linkid, DLADM_PROP_VAL_CURRENT,
2469 "pool", &poolset);
2470 if (err != DLADM_STATUS_OK) {
2471 zdlerror(zlogp, err, dlname,
2472 "WARNING: unable to check if pool link property is set");
2475 if ((strlen(pool_name) != 0) && !cpuset && !poolset) {
2476 poolp = pool_name;
2477 err = dladm_set_linkprop(dld_handle, linkid, "pool",
2478 &poolp, 1, DLADM_OPT_ACTIVE);
2479 if (err != DLADM_STATUS_OK) {
2480 zerror(zlogp, B_FALSE, "WARNING: unable to set "
2481 "pool %s to datalink %s", pool_name, dlname);
2482 bzero(pool_name, sizeof (pool_name));
2484 } else {
2485 bzero(pool_name, sizeof (pool_name));
2487 return (0);
2490 static boolean_t
2491 sockaddr_to_str(sa_family_t af, const struct sockaddr *sockaddr,
2492 char *straddr, size_t len)
2494 struct sockaddr_in *sin;
2495 struct sockaddr_in6 *sin6;
2496 const char *str = NULL;
2498 if (af == AF_INET) {
2499 /* LINTED E_BAD_PTR_CAST_ALIGN */
2500 sin = SIN(sockaddr);
2501 str = inet_ntop(AF_INET, (void *)&sin->sin_addr, straddr, len);
2502 } else if (af == AF_INET6) {
2503 /* LINTED E_BAD_PTR_CAST_ALIGN */
2504 sin6 = SIN6(sockaddr);
2505 str = inet_ntop(AF_INET6, (void *)&sin6->sin6_addr, straddr,
2506 len);
2509 return (str != NULL);
2512 static int
2513 ipv4_prefixlen(struct sockaddr_in *sin)
2515 struct sockaddr_in *m;
2516 struct sockaddr_storage mask;
2518 m = SIN(&mask);
2519 m->sin_family = AF_INET;
2520 if (getnetmaskbyaddr(sin->sin_addr, &m->sin_addr) == 0) {
2521 return (mask2plen((struct sockaddr *)&mask));
2522 } else if (IN_CLASSA(htonl(sin->sin_addr.s_addr))) {
2523 return (8);
2524 } else if (IN_CLASSB(ntohl(sin->sin_addr.s_addr))) {
2525 return (16);
2526 } else if (IN_CLASSC(ntohl(sin->sin_addr.s_addr))) {
2527 return (24);
2529 return (0);
2532 static int
2533 zone_setattr_network(int type, zoneid_t zoneid, datalink_id_t linkid,
2534 void *buf, size_t bufsize)
2536 zone_net_data_t *zndata;
2537 size_t znsize;
2538 int err;
2540 znsize = sizeof (*zndata) + bufsize;
2541 zndata = calloc(1, znsize);
2542 if (zndata == NULL)
2543 return (ENOMEM);
2544 zndata->zn_type = type;
2545 zndata->zn_len = bufsize;
2546 zndata->zn_linkid = linkid;
2547 bcopy(buf, zndata->zn_val, zndata->zn_len);
2548 err = zone_setattr(zoneid, ZONE_ATTR_NETWORK, zndata, znsize);
2549 free(zndata);
2550 return (err);
2553 static int
2554 add_net_for_linkid(zlog_t *zlogp, zoneid_t zoneid, zone_addr_list_t *start)
2556 struct lifreq lifr;
2557 char **astr, *address;
2558 dladm_status_t dlstatus;
2559 char *ip_nospoof = "ip-nospoof";
2560 int nnet, naddr, err = 0, j;
2561 size_t zlen, cpleft;
2562 zone_addr_list_t *ptr, *end;
2563 char tmp[INET6_ADDRSTRLEN], *maskstr;
2564 char *zaddr, *cp;
2565 struct in6_addr *routes = NULL;
2566 boolean_t is_set;
2567 datalink_id_t linkid;
2569 assert(start != NULL);
2570 naddr = 0; /* number of addresses */
2571 nnet = 0; /* number of net resources */
2572 linkid = start->za_linkid;
2573 for (ptr = start; ptr != NULL && ptr->za_linkid == linkid;
2574 ptr = ptr->za_next) {
2575 nnet++;
2577 end = ptr;
2578 zlen = nnet * (INET6_ADDRSTRLEN + 1);
2579 astr = calloc(1, nnet * sizeof (uintptr_t));
2580 zaddr = calloc(1, zlen);
2581 if (astr == NULL || zaddr == NULL) {
2582 err = ENOMEM;
2583 goto done;
2585 cp = zaddr;
2586 cpleft = zlen;
2587 j = 0;
2588 for (ptr = start; ptr != end; ptr = ptr->za_next) {
2589 address = ptr->za_nwiftab.zone_nwif_allowed_address;
2590 if (address[0] == '\0')
2591 continue;
2592 (void) snprintf(tmp, sizeof (tmp), "%s", address);
2594 * Validate the data. zonecfg_valid_net_address() clobbers
2595 * the /<mask> in the address string.
2597 if (zonecfg_valid_net_address(address, &lifr) != Z_OK) {
2598 zerror(zlogp, B_FALSE, "invalid address [%s]\n",
2599 address);
2600 err = EINVAL;
2601 goto done;
2604 * convert any hostnames to numeric address strings.
2606 if (!sockaddr_to_str(lifr.lifr_addr.ss_family,
2607 (const struct sockaddr *)&lifr.lifr_addr, cp, cpleft)) {
2608 err = EINVAL;
2609 goto done;
2612 * make a copy of the numeric string for the data needed
2613 * by the "allowed-ips" datalink property.
2615 astr[j] = strdup(cp);
2616 if (astr[j] == NULL) {
2617 err = ENOMEM;
2618 goto done;
2620 j++;
2622 * compute the default netmask from the address, if necessary
2624 if ((maskstr = strchr(tmp, '/')) == NULL) {
2625 int prefixlen;
2627 if (lifr.lifr_addr.ss_family == AF_INET) {
2628 prefixlen = ipv4_prefixlen(
2629 SIN(&lifr.lifr_addr));
2630 } else {
2631 struct sockaddr_in6 *sin6;
2633 sin6 = SIN6(&lifr.lifr_addr);
2634 if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))
2635 prefixlen = 10;
2636 else
2637 prefixlen = 64;
2639 (void) snprintf(tmp, sizeof (tmp), "%d", prefixlen);
2640 maskstr = tmp;
2641 } else {
2642 maskstr++;
2644 /* append the "/<netmask>" */
2645 (void) strlcat(cp, "/", cpleft);
2646 (void) strlcat(cp, maskstr, cpleft);
2647 (void) strlcat(cp, ",", cpleft);
2648 cp += strnlen(cp, zlen);
2649 cpleft = &zaddr[INET6_ADDRSTRLEN] - cp;
2651 naddr = j; /* the actual number of addresses in the net resource */
2652 assert(naddr <= nnet);
2655 * zonecfg has already verified that the defrouter property can only
2656 * be set if there is at least one address defined for the net resource.
2657 * If j is 0, there are no addresses defined, and therefore no routers
2658 * to configure, and we are done at that point.
2660 if (j == 0)
2661 goto done;
2663 /* over-write last ',' with '\0' */
2664 zaddr[strnlen(zaddr, zlen) + 1] = '\0';
2667 * First make sure L3 protection is not already set on the link.
2669 dlstatus = dladm_linkprop_is_set(dld_handle, linkid, DLADM_OPT_ACTIVE,
2670 "protection", &is_set);
2671 if (dlstatus != DLADM_STATUS_OK) {
2672 err = EINVAL;
2673 zerror(zlogp, B_FALSE, "unable to check if protection is set");
2674 goto done;
2676 if (is_set) {
2677 err = EINVAL;
2678 zerror(zlogp, B_FALSE, "Protection is already set");
2679 goto done;
2681 dlstatus = dladm_linkprop_is_set(dld_handle, linkid, DLADM_OPT_ACTIVE,
2682 "allowed-ips", &is_set);
2683 if (dlstatus != DLADM_STATUS_OK) {
2684 err = EINVAL;
2685 zerror(zlogp, B_FALSE, "unable to check if allowed-ips is set");
2686 goto done;
2688 if (is_set) {
2689 zerror(zlogp, B_FALSE, "allowed-ips is already set");
2690 err = EINVAL;
2691 goto done;
2695 * Enable ip-nospoof for the link, and add address to the allowed-ips
2696 * list.
2698 dlstatus = dladm_set_linkprop(dld_handle, linkid, "protection",
2699 &ip_nospoof, 1, DLADM_OPT_ACTIVE);
2700 if (dlstatus != DLADM_STATUS_OK) {
2701 zerror(zlogp, B_FALSE, "could not set protection\n");
2702 err = EINVAL;
2703 goto done;
2705 dlstatus = dladm_set_linkprop(dld_handle, linkid, "allowed-ips",
2706 astr, naddr, DLADM_OPT_ACTIVE);
2707 if (dlstatus != DLADM_STATUS_OK) {
2708 zerror(zlogp, B_FALSE, "could not set allowed-ips\n");
2709 err = EINVAL;
2710 goto done;
2713 /* now set the address in the data-store */
2714 err = zone_setattr_network(ZONE_NETWORK_ADDRESS, zoneid, linkid,
2715 zaddr, strnlen(zaddr, zlen) + 1);
2716 if (err != 0)
2717 goto done;
2720 * add the defaultrouters
2722 routes = calloc(1, nnet * sizeof (*routes));
2723 j = 0;
2724 for (ptr = start; ptr != end; ptr = ptr->za_next) {
2725 address = ptr->za_nwiftab.zone_nwif_defrouter;
2726 if (address[0] == '\0')
2727 continue;
2728 if (strchr(address, '/') == NULL && strchr(address, ':') != 0) {
2730 * zonecfg_valid_net_address() expects numeric IPv6
2731 * addresses to have a CIDR format netmask.
2733 (void) snprintf(tmp, sizeof (tmp), "/%d", V6_ADDR_LEN);
2734 (void) strlcat(address, tmp, INET6_ADDRSTRLEN);
2736 if (zonecfg_valid_net_address(address, &lifr) != Z_OK) {
2737 zerror(zlogp, B_FALSE,
2738 "invalid router [%s]\n", address);
2739 err = EINVAL;
2740 goto done;
2742 if (lifr.lifr_addr.ss_family == AF_INET6) {
2743 routes[j] = SIN6(&lifr.lifr_addr)->sin6_addr;
2744 } else {
2745 IN6_INADDR_TO_V4MAPPED(&SIN(&lifr.lifr_addr)->sin_addr,
2746 &routes[j]);
2748 j++;
2750 assert(j <= nnet);
2751 if (j > 0) {
2752 err = zone_setattr_network(ZONE_NETWORK_DEFROUTER, zoneid,
2753 linkid, routes, j * sizeof (*routes));
2755 done:
2756 free(routes);
2757 for (j = 0; j < naddr; j++)
2758 free(astr[j]);
2759 free(astr);
2760 free(zaddr);
2761 return (err);
2765 static int
2766 add_net(zlog_t *zlogp, zoneid_t zoneid, zone_addr_list_t *zalist)
2768 zone_addr_list_t *ptr;
2769 datalink_id_t linkid;
2770 int err;
2772 if (zalist == NULL)
2773 return (0);
2775 linkid = zalist->za_linkid;
2777 err = add_net_for_linkid(zlogp, zoneid, zalist);
2778 if (err != 0)
2779 return (err);
2781 for (ptr = zalist; ptr != NULL; ptr = ptr->za_next) {
2782 if (ptr->za_linkid == linkid)
2783 continue;
2784 linkid = ptr->za_linkid;
2785 err = add_net_for_linkid(zlogp, zoneid, ptr);
2786 if (err != 0)
2787 return (err);
2789 return (0);
2793 * Add "new" to the list of network interfaces to be configured by
2794 * add_net on zone boot in "old". The list of interfaces in "old" is
2795 * sorted by datalink_id_t, with interfaces sorted FIFO for a given
2796 * datalink_id_t.
2798 * Returns the merged list of IP interfaces containing "old" and "new"
2800 static zone_addr_list_t *
2801 add_ip_interface(zone_addr_list_t *old, zone_addr_list_t *new)
2803 zone_addr_list_t *ptr, *next;
2804 datalink_id_t linkid = new->za_linkid;
2806 assert(old != new);
2808 if (old == NULL)
2809 return (new);
2810 for (ptr = old; ptr != NULL; ptr = ptr->za_next) {
2811 if (ptr->za_linkid == linkid)
2812 break;
2814 if (ptr == NULL) {
2815 /* linkid does not already exist, add to the beginning */
2816 new->za_next = old;
2817 return (new);
2820 * adding to the middle of the list; ptr points at the first
2821 * occurrence of linkid. Find the last occurrence.
2823 while ((next = ptr->za_next) != NULL) {
2824 if (next->za_linkid != linkid)
2825 break;
2826 ptr = next;
2828 /* insert new after ptr */
2829 new->za_next = next;
2830 ptr->za_next = new;
2831 return (old);
2834 void
2835 free_ip_interface(zone_addr_list_t *zalist)
2837 zone_addr_list_t *ptr, *new;
2839 for (ptr = zalist; ptr != NULL; ) {
2840 new = ptr;
2841 ptr = ptr->za_next;
2842 free(new);
2847 * Add the kernel access control information for the interface names.
2848 * If anything goes wrong, we log a general error message, attempt to tear down
2849 * whatever we set up, and return an error.
2851 static int
2852 configure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
2854 zone_dochandle_t handle;
2855 struct zone_nwiftab nwiftab;
2856 char rootpath[MAXPATHLEN];
2857 char path[MAXPATHLEN];
2858 datalink_id_t linkid;
2859 di_prof_t prof = NULL;
2860 boolean_t added = B_FALSE;
2861 zone_addr_list_t *zalist = NULL, *new;
2863 if ((handle = zonecfg_init_handle()) == NULL) {
2864 zerror(zlogp, B_TRUE, "getting zone configuration handle");
2865 return (-1);
2867 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
2868 zerror(zlogp, B_FALSE, "invalid configuration");
2869 zonecfg_fini_handle(handle);
2870 return (-1);
2873 if (zonecfg_setnwifent(handle) != Z_OK) {
2874 zonecfg_fini_handle(handle);
2875 return (0);
2878 for (;;) {
2879 if (zonecfg_getnwifent(handle, &nwiftab) != Z_OK)
2880 break;
2882 if (prof == NULL) {
2883 if (zone_get_devroot(zone_name, rootpath,
2884 sizeof (rootpath)) != Z_OK) {
2885 (void) zonecfg_endnwifent(handle);
2886 zonecfg_fini_handle(handle);
2887 zerror(zlogp, B_TRUE,
2888 "unable to determine dev root");
2889 return (-1);
2891 (void) snprintf(path, sizeof (path), "%s%s", rootpath,
2892 "/dev");
2893 if (di_prof_init(path, &prof) != 0) {
2894 (void) zonecfg_endnwifent(handle);
2895 zonecfg_fini_handle(handle);
2896 zerror(zlogp, B_TRUE,
2897 "failed to initialize profile");
2898 return (-1);
2903 * Create the /dev entry for backward compatibility.
2904 * Only create the /dev entry if it's not in use.
2905 * Note that the zone still boots when the assigned
2906 * interface is inaccessible, used by others, etc.
2907 * Also, when vanity naming is used, some interface do
2908 * do not have corresponding /dev node names (for example,
2909 * vanity named aggregations). The /dev entry is not
2910 * created in that case. The /dev/net entry is always
2911 * accessible.
2913 if (dladm_name2info(dld_handle, nwiftab.zone_nwif_physical,
2914 &linkid, NULL, NULL, NULL) == DLADM_STATUS_OK &&
2915 add_datalink(zlogp, zone_name, linkid,
2916 nwiftab.zone_nwif_physical) == 0) {
2917 added = B_TRUE;
2918 } else {
2919 (void) zonecfg_endnwifent(handle);
2920 zonecfg_fini_handle(handle);
2921 zerror(zlogp, B_TRUE, "failed to add network device");
2922 return (-1);
2924 /* set up the new IP interface, and add them all later */
2925 new = malloc(sizeof (*new));
2926 if (new == NULL) {
2927 zerror(zlogp, B_TRUE, "no memory for %s",
2928 nwiftab.zone_nwif_physical);
2929 zonecfg_fini_handle(handle);
2930 free_ip_interface(zalist);
2932 bzero(new, sizeof (*new));
2933 new->za_nwiftab = nwiftab;
2934 new->za_linkid = linkid;
2935 zalist = add_ip_interface(zalist, new);
2937 if (zalist != NULL) {
2938 if ((errno = add_net(zlogp, zoneid, zalist)) != 0) {
2939 (void) zonecfg_endnwifent(handle);
2940 zonecfg_fini_handle(handle);
2941 zerror(zlogp, B_TRUE, "failed to add address");
2942 free_ip_interface(zalist);
2943 return (-1);
2945 free_ip_interface(zalist);
2947 (void) zonecfg_endnwifent(handle);
2948 zonecfg_fini_handle(handle);
2950 if (prof != NULL && added) {
2951 if (di_prof_commit(prof) != 0) {
2952 zerror(zlogp, B_TRUE, "failed to commit profile");
2953 return (-1);
2956 if (prof != NULL)
2957 di_prof_fini(prof);
2959 return (0);
2962 static int
2963 remove_datalink_pool(zlog_t *zlogp, zoneid_t zoneid)
2965 ushort_t flags;
2966 zone_iptype_t iptype;
2967 int i, dlnum = 0;
2968 datalink_id_t *dllink, *dllinks = NULL;
2969 dladm_status_t err;
2971 if (strlen(pool_name) == 0)
2972 return (0);
2974 if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
2975 sizeof (flags)) < 0) {
2976 if (vplat_get_iptype(zlogp, &iptype) < 0) {
2977 zerror(zlogp, B_FALSE, "unable to determine ip-type");
2978 return (-1);
2980 } else {
2981 if (flags & ZF_NET_EXCL)
2982 iptype = ZS_EXCLUSIVE;
2983 else
2984 iptype = ZS_SHARED;
2987 if (iptype == ZS_EXCLUSIVE) {
2989 * Get the datalink count and for each datalink,
2990 * attempt to clear the pool property and clear
2991 * the pool_name.
2993 if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
2994 zerror(zlogp, B_TRUE, "unable to count network "
2995 "interfaces");
2996 return (-1);
2999 if (dlnum == 0)
3000 return (0);
3002 if ((dllinks = malloc(dlnum * sizeof (datalink_id_t)))
3003 == NULL) {
3004 zerror(zlogp, B_TRUE, "memory allocation failed");
3005 return (-1);
3007 if (zone_list_datalink(zoneid, &dlnum, dllinks) != 0) {
3008 zerror(zlogp, B_TRUE, "unable to list network "
3009 "interfaces");
3010 return (-1);
3013 bzero(pool_name, sizeof (pool_name));
3014 for (i = 0, dllink = dllinks; i < dlnum; i++, dllink++) {
3015 err = dladm_set_linkprop(dld_handle, *dllink, "pool",
3016 NULL, 0, DLADM_OPT_ACTIVE);
3017 if (err != DLADM_STATUS_OK) {
3018 zerror(zlogp, B_TRUE,
3019 "WARNING: unable to clear pool");
3022 free(dllinks);
3024 return (0);
3027 static int
3028 remove_datalink_protect(zlog_t *zlogp, zoneid_t zoneid)
3030 ushort_t flags;
3031 zone_iptype_t iptype;
3032 int i, dlnum = 0;
3033 dladm_status_t dlstatus;
3034 datalink_id_t *dllink, *dllinks = NULL;
3036 if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
3037 sizeof (flags)) < 0) {
3038 if (vplat_get_iptype(zlogp, &iptype) < 0) {
3039 zerror(zlogp, B_FALSE, "unable to determine ip-type");
3040 return (-1);
3042 } else {
3043 if (flags & ZF_NET_EXCL)
3044 iptype = ZS_EXCLUSIVE;
3045 else
3046 iptype = ZS_SHARED;
3049 if (iptype != ZS_EXCLUSIVE)
3050 return (0);
3053 * Get the datalink count and for each datalink,
3054 * attempt to clear the pool property and clear
3055 * the pool_name.
3057 if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
3058 zerror(zlogp, B_TRUE, "unable to count network interfaces");
3059 return (-1);
3062 if (dlnum == 0)
3063 return (0);
3065 if ((dllinks = malloc(dlnum * sizeof (datalink_id_t))) == NULL) {
3066 zerror(zlogp, B_TRUE, "memory allocation failed");
3067 return (-1);
3069 if (zone_list_datalink(zoneid, &dlnum, dllinks) != 0) {
3070 zerror(zlogp, B_TRUE, "unable to list network interfaces");
3071 free(dllinks);
3072 return (-1);
3075 for (i = 0, dllink = dllinks; i < dlnum; i++, dllink++) {
3076 char dlerr[DLADM_STRSIZE];
3078 dlstatus = dladm_set_linkprop(dld_handle, *dllink,
3079 "protection", NULL, 0, DLADM_OPT_ACTIVE);
3080 if (dlstatus == DLADM_STATUS_NOTFOUND) {
3081 /* datalink does not belong to the GZ */
3082 continue;
3084 if (dlstatus != DLADM_STATUS_OK) {
3085 zerror(zlogp, B_FALSE,
3086 dladm_status2str(dlstatus, dlerr));
3087 free(dllinks);
3088 return (-1);
3090 dlstatus = dladm_set_linkprop(dld_handle, *dllink,
3091 "allowed-ips", NULL, 0, DLADM_OPT_ACTIVE);
3092 if (dlstatus != DLADM_STATUS_OK) {
3093 zerror(zlogp, B_FALSE,
3094 dladm_status2str(dlstatus, dlerr));
3095 free(dllinks);
3096 return (-1);
3099 free(dllinks);
3100 return (0);
3103 static int
3104 unconfigure_exclusive_network_interfaces(zlog_t *zlogp, zoneid_t zoneid)
3106 int dlnum = 0;
3109 * The kernel shutdown callback for the dls module should have removed
3110 * all datalinks from this zone. If any remain, then there's a
3111 * problem.
3113 if (zone_list_datalink(zoneid, &dlnum, NULL) != 0) {
3114 zerror(zlogp, B_TRUE, "unable to list network interfaces");
3115 return (-1);
3117 if (dlnum != 0) {
3118 zerror(zlogp, B_FALSE,
3119 "datalinks remain in zone after shutdown");
3120 return (-1);
3122 return (0);
3125 static int
3126 tcp_abort_conn(zlog_t *zlogp, zoneid_t zoneid,
3127 const struct sockaddr_storage *local, const struct sockaddr_storage *remote)
3129 int fd;
3130 struct strioctl ioc;
3131 tcp_ioc_abort_conn_t conn;
3132 int error;
3134 conn.ac_local = *local;
3135 conn.ac_remote = *remote;
3136 conn.ac_start = TCPS_SYN_SENT;
3137 conn.ac_end = TCPS_TIME_WAIT;
3138 conn.ac_zoneid = zoneid;
3140 ioc.ic_cmd = TCP_IOC_ABORT_CONN;
3141 ioc.ic_timout = -1; /* infinite timeout */
3142 ioc.ic_len = sizeof (conn);
3143 ioc.ic_dp = (char *)&conn;
3145 if ((fd = open("/dev/tcp", O_RDONLY)) < 0) {
3146 zerror(zlogp, B_TRUE, "unable to open %s", "/dev/tcp");
3147 return (-1);
3150 error = ioctl(fd, I_STR, &ioc);
3151 (void) close(fd);
3152 if (error == 0 || errno == ENOENT) /* ENOENT is not an error */
3153 return (0);
3154 return (-1);
3157 static int
3158 tcp_abort_connections(zlog_t *zlogp, zoneid_t zoneid)
3160 struct sockaddr_storage l, r;
3161 struct sockaddr_in *local, *remote;
3162 struct sockaddr_in6 *local6, *remote6;
3163 int error;
3166 * Abort IPv4 connections.
3168 bzero(&l, sizeof (*local));
3169 local = (struct sockaddr_in *)&l;
3170 local->sin_family = AF_INET;
3171 local->sin_addr.s_addr = INADDR_ANY;
3172 local->sin_port = 0;
3174 bzero(&r, sizeof (*remote));
3175 remote = (struct sockaddr_in *)&r;
3176 remote->sin_family = AF_INET;
3177 remote->sin_addr.s_addr = INADDR_ANY;
3178 remote->sin_port = 0;
3180 if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
3181 return (error);
3184 * Abort IPv6 connections.
3186 bzero(&l, sizeof (*local6));
3187 local6 = (struct sockaddr_in6 *)&l;
3188 local6->sin6_family = AF_INET6;
3189 local6->sin6_port = 0;
3190 local6->sin6_addr = in6addr_any;
3192 bzero(&r, sizeof (*remote6));
3193 remote6 = (struct sockaddr_in6 *)&r;
3194 remote6->sin6_family = AF_INET6;
3195 remote6->sin6_port = 0;
3196 remote6->sin6_addr = in6addr_any;
3198 if ((error = tcp_abort_conn(zlogp, zoneid, &l, &r)) != 0)
3199 return (error);
3200 return (0);
3203 static int
3204 get_privset(zlog_t *zlogp, priv_set_t *privs, zone_mnt_t mount_cmd)
3206 int error = -1;
3207 zone_dochandle_t handle;
3208 char *privname = NULL;
3210 if ((handle = zonecfg_init_handle()) == NULL) {
3211 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3212 return (-1);
3214 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3215 zerror(zlogp, B_FALSE, "invalid configuration");
3216 zonecfg_fini_handle(handle);
3217 return (-1);
3220 if (ALT_MOUNT(mount_cmd)) {
3221 zone_iptype_t iptype;
3222 const char *curr_iptype;
3224 if (zonecfg_get_iptype(handle, &iptype) != Z_OK) {
3225 zerror(zlogp, B_TRUE, "unable to determine ip-type");
3226 zonecfg_fini_handle(handle);
3227 return (-1);
3230 switch (iptype) {
3231 case ZS_SHARED:
3232 curr_iptype = "shared";
3233 break;
3234 case ZS_EXCLUSIVE:
3235 curr_iptype = "exclusive";
3236 break;
3239 if (zonecfg_default_privset(privs, curr_iptype) == Z_OK) {
3240 zonecfg_fini_handle(handle);
3241 return (0);
3243 zerror(zlogp, B_FALSE,
3244 "failed to determine the zone's default privilege set");
3245 zonecfg_fini_handle(handle);
3246 return (-1);
3249 switch (zonecfg_get_privset(handle, privs, &privname)) {
3250 case Z_OK:
3251 error = 0;
3252 break;
3253 case Z_PRIV_PROHIBITED:
3254 zerror(zlogp, B_FALSE, "privilege \"%s\" is not permitted "
3255 "within the zone's privilege set", privname);
3256 break;
3257 case Z_PRIV_REQUIRED:
3258 zerror(zlogp, B_FALSE, "required privilege \"%s\" is missing "
3259 "from the zone's privilege set", privname);
3260 break;
3261 case Z_PRIV_UNKNOWN:
3262 zerror(zlogp, B_FALSE, "unknown privilege \"%s\" specified "
3263 "in the zone's privilege set", privname);
3264 break;
3265 default:
3266 zerror(zlogp, B_FALSE, "failed to determine the zone's "
3267 "privilege set");
3268 break;
3271 free(privname);
3272 zonecfg_fini_handle(handle);
3273 return (error);
3276 static int
3277 get_rctls(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3279 nvlist_t *nvl = NULL;
3280 char *nvl_packed = NULL;
3281 size_t nvl_size = 0;
3282 nvlist_t **nvlv = NULL;
3283 int rctlcount = 0;
3284 int error = -1;
3285 zone_dochandle_t handle;
3286 struct zone_rctltab rctltab;
3287 rctlblk_t *rctlblk = NULL;
3288 uint64_t maxlwps;
3289 uint64_t maxprocs;
3291 *bufp = NULL;
3292 *bufsizep = 0;
3294 if ((handle = zonecfg_init_handle()) == NULL) {
3295 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3296 return (-1);
3298 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3299 zerror(zlogp, B_FALSE, "invalid configuration");
3300 zonecfg_fini_handle(handle);
3301 return (-1);
3304 rctltab.zone_rctl_valptr = NULL;
3305 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
3306 zerror(zlogp, B_TRUE, "%s failed", "nvlist_alloc");
3307 goto out;
3311 * Allow the administrator to control both the maximum number of
3312 * process table slots and the maximum number of lwps with just the
3313 * max-processes property. If only the max-processes property is set,
3314 * we add a max-lwps property with a limit derived from max-processes.
3316 if (zonecfg_get_aliased_rctl(handle, ALIAS_MAXPROCS, &maxprocs)
3317 == Z_OK &&
3318 zonecfg_get_aliased_rctl(handle, ALIAS_MAXLWPS, &maxlwps)
3319 == Z_NO_ENTRY) {
3320 if (zonecfg_set_aliased_rctl(handle, ALIAS_MAXLWPS,
3321 maxprocs * LWPS_PER_PROCESS) != Z_OK) {
3322 zerror(zlogp, B_FALSE, "unable to set max-lwps alias");
3323 goto out;
3327 if (zonecfg_setrctlent(handle) != Z_OK) {
3328 zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setrctlent");
3329 goto out;
3332 if ((rctlblk = malloc(rctlblk_size())) == NULL) {
3333 zerror(zlogp, B_TRUE, "memory allocation failed");
3334 goto out;
3336 while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
3337 struct zone_rctlvaltab *rctlval;
3338 uint_t i, count;
3339 const char *name = rctltab.zone_rctl_name;
3341 /* zoneadm should have already warned about unknown rctls. */
3342 if (!zonecfg_is_rctl(name)) {
3343 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3344 rctltab.zone_rctl_valptr = NULL;
3345 continue;
3347 count = 0;
3348 for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
3349 rctlval = rctlval->zone_rctlval_next) {
3350 count++;
3352 if (count == 0) { /* ignore */
3353 continue; /* Nothing to free */
3355 if ((nvlv = malloc(sizeof (*nvlv) * count)) == NULL)
3356 goto out;
3357 i = 0;
3358 for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
3359 rctlval = rctlval->zone_rctlval_next, i++) {
3360 if (nvlist_alloc(&nvlv[i], NV_UNIQUE_NAME, 0) != 0) {
3361 zerror(zlogp, B_TRUE, "%s failed",
3362 "nvlist_alloc");
3363 goto out;
3365 if (zonecfg_construct_rctlblk(rctlval, rctlblk)
3366 != Z_OK) {
3367 zerror(zlogp, B_FALSE, "invalid rctl value: "
3368 "(priv=%s,limit=%s,action=%s)",
3369 rctlval->zone_rctlval_priv,
3370 rctlval->zone_rctlval_limit,
3371 rctlval->zone_rctlval_action);
3372 goto out;
3374 if (!zonecfg_valid_rctl(name, rctlblk)) {
3375 zerror(zlogp, B_FALSE,
3376 "(priv=%s,limit=%s,action=%s) is not a "
3377 "valid value for rctl '%s'",
3378 rctlval->zone_rctlval_priv,
3379 rctlval->zone_rctlval_limit,
3380 rctlval->zone_rctlval_action,
3381 name);
3382 goto out;
3384 if (nvlist_add_uint64(nvlv[i], "privilege",
3385 rctlblk_get_privilege(rctlblk)) != 0) {
3386 zerror(zlogp, B_FALSE, "%s failed",
3387 "nvlist_add_uint64");
3388 goto out;
3390 if (nvlist_add_uint64(nvlv[i], "limit",
3391 rctlblk_get_value(rctlblk)) != 0) {
3392 zerror(zlogp, B_FALSE, "%s failed",
3393 "nvlist_add_uint64");
3394 goto out;
3396 if (nvlist_add_uint64(nvlv[i], "action",
3397 (uint_t)rctlblk_get_local_action(rctlblk, NULL))
3398 != 0) {
3399 zerror(zlogp, B_FALSE, "%s failed",
3400 "nvlist_add_uint64");
3401 goto out;
3404 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3405 rctltab.zone_rctl_valptr = NULL;
3406 if (nvlist_add_nvlist_array(nvl, (char *)name, nvlv, count)
3407 != 0) {
3408 zerror(zlogp, B_FALSE, "%s failed",
3409 "nvlist_add_nvlist_array");
3410 goto out;
3412 for (i = 0; i < count; i++)
3413 nvlist_free(nvlv[i]);
3414 free(nvlv);
3415 nvlv = NULL;
3416 rctlcount++;
3418 (void) zonecfg_endrctlent(handle);
3420 if (rctlcount == 0) {
3421 error = 0;
3422 goto out;
3424 if (nvlist_pack(nvl, &nvl_packed, &nvl_size, NV_ENCODE_NATIVE, 0)
3425 != 0) {
3426 zerror(zlogp, B_FALSE, "%s failed", "nvlist_pack");
3427 goto out;
3430 error = 0;
3431 *bufp = nvl_packed;
3432 *bufsizep = nvl_size;
3434 out:
3435 free(rctlblk);
3436 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
3437 if (error)
3438 free(nvl_packed);
3439 nvlist_free(nvl);
3440 free(nvlv);
3441 if (handle != NULL)
3442 zonecfg_fini_handle(handle);
3443 return (error);
3446 static int
3447 get_implicit_datasets(zlog_t *zlogp, char **retstr)
3449 char cmdbuf[2 * MAXPATHLEN];
3451 if (query_hook[0] == '\0')
3452 return (0);
3454 if (snprintf(cmdbuf, sizeof (cmdbuf), "%s datasets", query_hook)
3455 > sizeof (cmdbuf))
3456 return (-1);
3458 if (do_subproc(zlogp, cmdbuf, retstr) != 0)
3459 return (-1);
3461 return (0);
3464 static int
3465 get_datasets(zlog_t *zlogp, char **bufp, size_t *bufsizep)
3467 zone_dochandle_t handle;
3468 struct zone_dstab dstab;
3469 size_t total, offset, len;
3470 int error = -1;
3471 char *str = NULL;
3472 char *implicit_datasets = NULL;
3473 int implicit_len = 0;
3475 *bufp = NULL;
3476 *bufsizep = 0;
3478 if ((handle = zonecfg_init_handle()) == NULL) {
3479 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3480 return (-1);
3482 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3483 zerror(zlogp, B_FALSE, "invalid configuration");
3484 zonecfg_fini_handle(handle);
3485 return (-1);
3488 if (get_implicit_datasets(zlogp, &implicit_datasets) != 0) {
3489 zerror(zlogp, B_FALSE, "getting implicit datasets failed");
3490 goto out;
3493 if (zonecfg_setdsent(handle) != Z_OK) {
3494 zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3495 goto out;
3498 total = 0;
3499 while (zonecfg_getdsent(handle, &dstab) == Z_OK)
3500 total += strlen(dstab.zone_dataset_name) + 1;
3501 (void) zonecfg_enddsent(handle);
3503 if (implicit_datasets != NULL)
3504 implicit_len = strlen(implicit_datasets);
3505 if (implicit_len > 0)
3506 total += implicit_len + 1;
3508 if (total == 0) {
3509 error = 0;
3510 goto out;
3513 if ((str = malloc(total)) == NULL) {
3514 zerror(zlogp, B_TRUE, "memory allocation failed");
3515 goto out;
3518 if (zonecfg_setdsent(handle) != Z_OK) {
3519 zerror(zlogp, B_FALSE, "%s failed", "zonecfg_setdsent");
3520 goto out;
3522 offset = 0;
3523 while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3524 len = strlen(dstab.zone_dataset_name);
3525 (void) strlcpy(str + offset, dstab.zone_dataset_name,
3526 total - offset);
3527 offset += len;
3528 if (offset < total - 1)
3529 str[offset++] = ',';
3531 (void) zonecfg_enddsent(handle);
3533 if (implicit_len > 0)
3534 (void) strlcpy(str + offset, implicit_datasets, total - offset);
3536 error = 0;
3537 *bufp = str;
3538 *bufsizep = total;
3540 out:
3541 if (error != 0)
3542 free(str);
3543 if (handle != NULL)
3544 zonecfg_fini_handle(handle);
3545 free(implicit_datasets);
3547 return (error);
3550 static int
3551 validate_datasets(zlog_t *zlogp)
3553 zone_dochandle_t handle;
3554 struct zone_dstab dstab;
3555 zfs_handle_t *zhp;
3556 libzfs_handle_t *hdl;
3558 if ((handle = zonecfg_init_handle()) == NULL) {
3559 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3560 return (-1);
3562 if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
3563 zerror(zlogp, B_FALSE, "invalid configuration");
3564 zonecfg_fini_handle(handle);
3565 return (-1);
3568 if (zonecfg_setdsent(handle) != Z_OK) {
3569 zerror(zlogp, B_FALSE, "invalid configuration");
3570 zonecfg_fini_handle(handle);
3571 return (-1);
3574 if ((hdl = libzfs_init()) == NULL) {
3575 zerror(zlogp, B_FALSE, "opening ZFS library");
3576 zonecfg_fini_handle(handle);
3577 return (-1);
3580 while (zonecfg_getdsent(handle, &dstab) == Z_OK) {
3582 if ((zhp = zfs_open(hdl, dstab.zone_dataset_name,
3583 ZFS_TYPE_FILESYSTEM)) == NULL) {
3584 zerror(zlogp, B_FALSE, "cannot open ZFS dataset '%s'",
3585 dstab.zone_dataset_name);
3586 zonecfg_fini_handle(handle);
3587 libzfs_fini(hdl);
3588 return (-1);
3592 * Automatically set the 'zoned' property. We check the value
3593 * first because we'll get EPERM if it is already set.
3595 if (!zfs_prop_get_int(zhp, ZFS_PROP_ZONED) &&
3596 zfs_prop_set(zhp, zfs_prop_to_name(ZFS_PROP_ZONED),
3597 "on") != 0) {
3598 zerror(zlogp, B_FALSE, "cannot set 'zoned' "
3599 "property for ZFS dataset '%s'\n",
3600 dstab.zone_dataset_name);
3601 zonecfg_fini_handle(handle);
3602 zfs_close(zhp);
3603 libzfs_fini(hdl);
3604 return (-1);
3607 zfs_close(zhp);
3609 (void) zonecfg_enddsent(handle);
3611 zonecfg_fini_handle(handle);
3612 libzfs_fini(hdl);
3614 return (0);
3618 * Return true if the path is its own zfs file system. We determine this
3619 * by stat-ing the path to see if it is zfs and stat-ing the parent to see
3620 * if it is a different fs.
3622 boolean_t
3623 is_zonepath_zfs(char *zonepath)
3625 int res;
3626 char *path;
3627 char *parent;
3628 struct statvfs64 buf1, buf2;
3630 if (statvfs64(zonepath, &buf1) != 0)
3631 return (B_FALSE);
3633 if (strcmp(buf1.f_basetype, "zfs") != 0)
3634 return (B_FALSE);
3636 if ((path = strdup(zonepath)) == NULL)
3637 return (B_FALSE);
3639 parent = dirname(path);
3640 res = statvfs64(parent, &buf2);
3641 free(path);
3643 if (res != 0)
3644 return (B_FALSE);
3646 if (buf1.f_fsid == buf2.f_fsid)
3647 return (B_FALSE);
3649 return (B_TRUE);
3653 prtmount(const struct mnttab *fs, void *x)
3655 zerror((zlog_t *)x, B_FALSE, " %s", fs->mnt_mountp);
3656 return (0);
3660 * Look for zones running on the main system that are using this root (or any
3661 * subdirectory of it). Return B_TRUE and print an error if a conflicting zone
3662 * is found or if we can't tell.
3664 static boolean_t
3665 duplicate_zone_root(zlog_t *zlogp, const char *rootpath)
3667 zoneid_t *zids = NULL;
3668 uint_t nzids = 0;
3669 boolean_t retv;
3670 int rlen, zlen;
3671 char zroot[MAXPATHLEN];
3672 char zonename[ZONENAME_MAX];
3674 for (;;) {
3675 nzids += 10;
3676 zids = malloc(nzids * sizeof (*zids));
3677 if (zids == NULL) {
3678 zerror(zlogp, B_TRUE, "memory allocation failed");
3679 return (B_TRUE);
3681 if (zone_list(zids, &nzids) == 0)
3682 break;
3683 free(zids);
3685 retv = B_FALSE;
3686 rlen = strlen(rootpath);
3687 while (nzids > 0) {
3689 * Ignore errors; they just mean that the zone has disappeared
3690 * while we were busy.
3692 if (zone_getattr(zids[--nzids], ZONE_ATTR_ROOT, zroot,
3693 sizeof (zroot)) == -1)
3694 continue;
3695 zlen = strlen(zroot);
3696 if (zlen > rlen)
3697 zlen = rlen;
3698 if (strncmp(rootpath, zroot, zlen) == 0 &&
3699 (zroot[zlen] == '\0' || zroot[zlen] == '/') &&
3700 (rootpath[zlen] == '\0' || rootpath[zlen] == '/')) {
3701 if (getzonenamebyid(zids[nzids], zonename,
3702 sizeof (zonename)) == -1)
3703 (void) snprintf(zonename, sizeof (zonename),
3704 "id %d", (int)zids[nzids]);
3705 zerror(zlogp, B_FALSE,
3706 "zone root %s already in use by zone %s",
3707 rootpath, zonename);
3708 retv = B_TRUE;
3709 break;
3712 free(zids);
3713 return (retv);
3717 * Search for loopback mounts that use this same source node (same device and
3718 * inode). Return B_TRUE if there is one or if we can't tell.
3720 static boolean_t
3721 duplicate_reachable_path(zlog_t *zlogp, const char *rootpath)
3723 struct stat64 rst, zst;
3724 struct mnttab *mnp;
3726 if (stat64(rootpath, &rst) == -1) {
3727 zerror(zlogp, B_TRUE, "can't stat %s", rootpath);
3728 return (B_TRUE);
3730 if (resolve_lofs_mnts == NULL && lofs_read_mnttab(zlogp) == -1)
3731 return (B_TRUE);
3732 for (mnp = resolve_lofs_mnts; mnp < resolve_lofs_mnt_max; mnp++) {
3733 if (mnp->mnt_fstype == NULL ||
3734 strcmp(MNTTYPE_LOFS, mnp->mnt_fstype) != 0)
3735 continue;
3736 /* We're looking at a loopback mount. Stat it. */
3737 if (mnp->mnt_special != NULL &&
3738 stat64(mnp->mnt_special, &zst) != -1 &&
3739 rst.st_dev == zst.st_dev && rst.st_ino == zst.st_ino) {
3740 zerror(zlogp, B_FALSE,
3741 "zone root %s is reachable through %s",
3742 rootpath, mnp->mnt_mountp);
3743 return (B_TRUE);
3746 return (B_FALSE);
3750 * Set memory cap and pool info for the zone's resource management
3751 * configuration.
3753 static int
3754 setup_zone_rm(zlog_t *zlogp, char *zone_name, zoneid_t zoneid)
3756 int res;
3757 uint64_t tmp;
3758 struct zone_mcaptab mcap;
3759 char sched[MAXNAMELEN];
3760 zone_dochandle_t handle = NULL;
3761 char pool_err[128];
3763 if ((handle = zonecfg_init_handle()) == NULL) {
3764 zerror(zlogp, B_TRUE, "getting zone configuration handle");
3765 return (Z_BAD_HANDLE);
3768 if ((res = zonecfg_get_snapshot_handle(zone_name, handle)) != Z_OK) {
3769 zerror(zlogp, B_FALSE, "invalid configuration");
3770 zonecfg_fini_handle(handle);
3771 return (res);
3775 * If a memory cap is configured, set the cap in the kernel using
3776 * zone_setattr() and make sure the rcapd SMF service is enabled.
3778 if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
3779 uint64_t num;
3780 char smf_err[128];
3782 num = (uint64_t)strtoull(mcap.zone_physmem_cap, NULL, 10);
3783 if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
3784 zerror(zlogp, B_TRUE, "could not set zone memory cap");
3785 zonecfg_fini_handle(handle);
3786 return (Z_INVAL);
3789 if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
3790 zerror(zlogp, B_FALSE, "enabling system/rcap service "
3791 "failed: %s", smf_err);
3792 zonecfg_fini_handle(handle);
3793 return (Z_INVAL);
3797 /* Get the scheduling class set in the zone configuration. */
3798 if (zonecfg_get_sched_class(handle, sched, sizeof (sched)) == Z_OK &&
3799 strlen(sched) > 0) {
3800 if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, sched,
3801 strlen(sched)) == -1)
3802 zerror(zlogp, B_TRUE, "WARNING: unable to set the "
3803 "default scheduling class");
3805 } else if (zonecfg_get_aliased_rctl(handle, ALIAS_SHARES, &tmp)
3806 == Z_OK) {
3808 * If the zone has the zone.cpu-shares rctl set then we want to
3809 * use the Fair Share Scheduler (FSS) for processes in the
3810 * zone. Check what scheduling class the zone would be running
3811 * in by default so we can print a warning and modify the class
3812 * if we wouldn't be using FSS.
3814 char class_name[PC_CLNMSZ];
3816 if (zonecfg_get_dflt_sched_class(handle, class_name,
3817 sizeof (class_name)) != Z_OK) {
3818 zerror(zlogp, B_FALSE, "WARNING: unable to determine "
3819 "the zone's scheduling class");
3821 } else if (strcmp("FSS", class_name) != 0) {
3822 zerror(zlogp, B_FALSE, "WARNING: The zone.cpu-shares "
3823 "rctl is set but\nFSS is not the default "
3824 "scheduling class for\nthis zone. FSS will be "
3825 "used for processes\nin the zone but to get the "
3826 "full benefit of FSS,\nit should be the default "
3827 "scheduling class.\nSee dispadmin(8) for more "
3828 "details.");
3830 if (zone_setattr(zoneid, ZONE_ATTR_SCHED_CLASS, "FSS",
3831 strlen("FSS")) == -1)
3832 zerror(zlogp, B_TRUE, "WARNING: unable to set "
3833 "zone scheduling class to FSS");
3838 * The next few blocks of code attempt to set up temporary pools as
3839 * well as persistent pools. In all cases we call the functions
3840 * unconditionally. Within each funtion the code will check if the
3841 * zone is actually configured for a temporary pool or persistent pool
3842 * and just return if there is nothing to do.
3844 * If we are rebooting we want to attempt to reuse any temporary pool
3845 * that was previously set up. zonecfg_bind_tmp_pool() will do the
3846 * right thing in all cases (reuse or create) based on the current
3847 * zonecfg.
3849 if ((res = zonecfg_bind_tmp_pool(handle, zoneid, pool_err,
3850 sizeof (pool_err))) != Z_OK) {
3851 if (res == Z_POOL || res == Z_POOL_CREATE || res == Z_POOL_BIND)
3852 zerror(zlogp, B_FALSE, "%s: %s\ndedicated-cpu setting "
3853 "cannot be instantiated", zonecfg_strerror(res),
3854 pool_err);
3855 else
3856 zerror(zlogp, B_FALSE, "could not bind zone to "
3857 "temporary pool: %s", zonecfg_strerror(res));
3858 zonecfg_fini_handle(handle);
3859 return (Z_POOL_BIND);
3863 * Check if we need to warn about poold not being enabled.
3865 if (zonecfg_warn_poold(handle)) {
3866 zerror(zlogp, B_FALSE, "WARNING: A range of dedicated-cpus has "
3867 "been specified\nbut the dynamic pool service is not "
3868 "enabled.\nThe system will not dynamically adjust the\n"
3869 "processor allocation within the specified range\n"
3870 "until svc:/system/pools/dynamic is enabled.\n"
3871 "See poold(8).");
3874 /* The following is a warning, not an error. */
3875 if ((res = zonecfg_bind_pool(handle, zoneid, pool_err,
3876 sizeof (pool_err))) != Z_OK) {
3877 if (res == Z_POOL_BIND)
3878 zerror(zlogp, B_FALSE, "WARNING: unable to bind to "
3879 "pool '%s'; using default pool.", pool_err);
3880 else if (res == Z_POOL)
3881 zerror(zlogp, B_FALSE, "WARNING: %s: %s",
3882 zonecfg_strerror(res), pool_err);
3883 else
3884 zerror(zlogp, B_FALSE, "WARNING: %s",
3885 zonecfg_strerror(res));
3888 /* Update saved pool name in case it has changed */
3889 (void) zonecfg_get_poolname(handle, zone_name, pool_name,
3890 sizeof (pool_name));
3892 zonecfg_fini_handle(handle);
3893 return (Z_OK);
3896 static void
3897 report_prop_err(zlog_t *zlogp, const char *name, const char *value, int res)
3899 switch (res) {
3900 case Z_TOO_BIG:
3901 zerror(zlogp, B_FALSE, "%s property value is too large.", name);
3902 break;
3904 case Z_INVALID_PROPERTY:
3905 zerror(zlogp, B_FALSE, "%s property value \"%s\" is not valid",
3906 name, value);
3907 break;
3909 default:
3910 zerror(zlogp, B_TRUE, "fetching property %s: %d", name, res);
3911 break;
3916 * Sets the hostid of the new zone based on its configured value. The zone's
3917 * zone_t structure must already exist in kernel memory. 'zlogp' refers to the
3918 * log used to report errors and warnings and must be non-NULL. 'zone_namep'
3919 * is the name of the new zone and must be non-NULL. 'zoneid' is the numeric
3920 * ID of the new zone.
3922 * This function returns zero on success and a nonzero error code on failure.
3924 static int
3925 setup_zone_hostid(zone_dochandle_t handle, zlog_t *zlogp, zoneid_t zoneid)
3927 int res;
3928 char hostidp[HW_HOSTID_LEN];
3929 unsigned int hostid;
3931 res = zonecfg_get_hostid(handle, hostidp, sizeof (hostidp));
3933 if (res == Z_BAD_PROPERTY) {
3934 return (Z_OK);
3935 } else if (res != Z_OK) {
3936 report_prop_err(zlogp, "hostid", hostidp, res);
3937 return (res);
3940 hostid = (unsigned int)strtoul(hostidp, NULL, 16);
3941 if ((res = zone_setattr(zoneid, ZONE_ATTR_HOSTID, &hostid,
3942 sizeof (hostid))) != 0) {
3943 zerror(zlogp, B_TRUE,
3944 "zone hostid is not valid: %s: %d", hostidp, res);
3945 return (Z_SYSTEM);
3948 return (res);
3951 static int
3952 setup_zone_secflags(zone_dochandle_t handle, zlog_t *zlogp, zoneid_t zoneid)
3954 psecflags_t secflags;
3955 struct zone_secflagstab tab = {0};
3956 secflagdelta_t delt;
3957 int res;
3959 res = zonecfg_lookup_secflags(handle, &tab);
3961 if ((res != Z_OK) &&
3962 /* The general defaulting code will handle this */
3963 (res != Z_NO_ENTRY) && (res != Z_BAD_PROPERTY)) {
3964 zerror(zlogp, B_FALSE, "security-flags property is "
3965 "invalid: %d", res);
3966 return (res);
3969 if (strlen(tab.zone_secflags_lower) == 0)
3970 (void) strlcpy(tab.zone_secflags_lower, "none",
3971 sizeof (tab.zone_secflags_lower));
3972 if (strlen(tab.zone_secflags_default) == 0)
3973 (void) strlcpy(tab.zone_secflags_default,
3974 tab.zone_secflags_lower,
3975 sizeof (tab.zone_secflags_default));
3976 if (strlen(tab.zone_secflags_upper) == 0)
3977 (void) strlcpy(tab.zone_secflags_upper, "all",
3978 sizeof (tab.zone_secflags_upper));
3980 if (secflags_parse(NULL, tab.zone_secflags_default,
3981 &delt) == -1) {
3982 zerror(zlogp, B_FALSE, "default security-flags: '%s'"
3983 "are invalid", tab.zone_secflags_default);
3984 return (Z_BAD_PROPERTY);
3985 } else if (delt.psd_ass_active != B_TRUE) {
3986 zerror(zlogp, B_FALSE, "relative security-flags are not "
3987 "allowed in zone configuration (default "
3988 "security-flags: '%s')",
3989 tab.zone_secflags_default);
3990 return (Z_BAD_PROPERTY);
3991 } else {
3992 secflags_copy(&secflags.psf_inherit, &delt.psd_assign);
3993 secflags_copy(&secflags.psf_effective, &delt.psd_assign);
3996 if (secflags_parse(NULL, tab.zone_secflags_lower,
3997 &delt) == -1) {
3998 zerror(zlogp, B_FALSE, "lower security-flags: '%s'"
3999 "are invalid", tab.zone_secflags_lower);
4000 return (Z_BAD_PROPERTY);
4001 } else if (delt.psd_ass_active != B_TRUE) {
4002 zerror(zlogp, B_FALSE, "relative security-flags are not "
4003 "allowed in zone configuration (lower "
4004 "security-flags: '%s')",
4005 tab.zone_secflags_lower);
4006 return (Z_BAD_PROPERTY);
4007 } else {
4008 secflags_copy(&secflags.psf_lower, &delt.psd_assign);
4011 if (secflags_parse(NULL, tab.zone_secflags_upper,
4012 &delt) == -1) {
4013 zerror(zlogp, B_FALSE, "upper security-flags: '%s'"
4014 "are invalid", tab.zone_secflags_upper);
4015 return (Z_BAD_PROPERTY);
4016 } else if (delt.psd_ass_active != B_TRUE) {
4017 zerror(zlogp, B_FALSE, "relative security-flags are not "
4018 "allowed in zone configuration (upper "
4019 "security-flags: '%s')",
4020 tab.zone_secflags_upper);
4021 return (Z_BAD_PROPERTY);
4022 } else {
4023 secflags_copy(&secflags.psf_upper, &delt.psd_assign);
4026 if (!psecflags_validate(&secflags)) {
4027 zerror(zlogp, B_TRUE, "security-flags violate invariants");
4028 return (Z_BAD_PROPERTY);
4031 if ((res = zone_setattr(zoneid, ZONE_ATTR_SECFLAGS, &secflags,
4032 sizeof (secflags))) != 0) {
4033 zerror(zlogp, B_TRUE,
4034 "security-flags couldn't be set: %d", res);
4035 return (Z_SYSTEM);
4038 return (Z_OK);
4041 static int
4042 setup_zone_fs_allowed(zone_dochandle_t handle, zlog_t *zlogp, zoneid_t zoneid)
4044 char fsallowed[ZONE_FS_ALLOWED_MAX];
4045 char *fsallowedp = fsallowed;
4046 int len = sizeof (fsallowed);
4047 int res;
4049 res = zonecfg_get_fs_allowed(handle, fsallowed, len);
4051 if (res == Z_BAD_PROPERTY) {
4052 /* No value, set the defaults */
4053 (void) strlcpy(fsallowed, DFLT_FS_ALLOWED, len);
4054 } else if (res != Z_OK) {
4055 report_prop_err(zlogp, "fs-allowed", fsallowed, res);
4056 return (res);
4057 } else if (fsallowed[0] == '-') {
4058 /* dropping default filesystems - use remaining list */
4059 if (fsallowed[1] != ',')
4060 return (Z_OK);
4061 fsallowedp += 2;
4062 len -= 2;
4063 } else {
4064 /* Has a value, append the defaults */
4065 if (strlcat(fsallowed, ",", len) >= len ||
4066 strlcat(fsallowed, DFLT_FS_ALLOWED, len) >= len) {
4067 report_prop_err(zlogp, "fs-allowed", fsallowed,
4068 Z_TOO_BIG);
4069 return (Z_TOO_BIG);
4073 if (zone_setattr(zoneid, ZONE_ATTR_FS_ALLOWED, fsallowedp, len) != 0) {
4074 zerror(zlogp, B_TRUE,
4075 "fs-allowed couldn't be set: %s: %d", fsallowedp, res);
4076 return (Z_SYSTEM);
4079 return (Z_OK);
4082 static int
4083 setup_zone_attrs(zlog_t *zlogp, char *zone_namep, zoneid_t zoneid)
4085 zone_dochandle_t handle;
4086 int res = Z_OK;
4088 if ((handle = zonecfg_init_handle()) == NULL) {
4089 zerror(zlogp, B_TRUE, "getting zone configuration handle");
4090 return (Z_BAD_HANDLE);
4092 if ((res = zonecfg_get_snapshot_handle(zone_namep, handle)) != Z_OK) {
4093 zerror(zlogp, B_FALSE, "invalid configuration");
4094 goto out;
4097 if ((res = setup_zone_hostid(handle, zlogp, zoneid)) != Z_OK)
4098 goto out;
4100 if ((res = setup_zone_fs_allowed(handle, zlogp, zoneid)) != Z_OK)
4101 goto out;
4103 if ((res = setup_zone_secflags(handle, zlogp, zoneid)) != Z_OK)
4104 goto out;
4106 out:
4107 zonecfg_fini_handle(handle);
4108 return (res);
4111 zoneid_t
4112 vplat_create(zlog_t *zlogp, zone_mnt_t mount_cmd)
4114 zoneid_t rval = -1;
4115 priv_set_t *privs;
4116 char rootpath[MAXPATHLEN];
4117 char *rctlbuf = NULL;
4118 size_t rctlbufsz = 0;
4119 char *zfsbuf = NULL;
4120 size_t zfsbufsz = 0;
4121 zoneid_t zoneid = -1;
4122 int xerr;
4123 char *kzone;
4124 FILE *fp = NULL;
4125 int flags;
4126 zone_iptype_t iptype;
4128 if (zone_get_rootpath(zone_name, rootpath, sizeof (rootpath)) != Z_OK) {
4129 zerror(zlogp, B_TRUE, "unable to determine zone root");
4130 return (-1);
4132 if (zonecfg_in_alt_root())
4133 resolve_lofs(zlogp, rootpath, sizeof (rootpath));
4135 if (vplat_get_iptype(zlogp, &iptype) < 0) {
4136 zerror(zlogp, B_TRUE, "unable to determine ip-type");
4137 return (-1);
4139 switch (iptype) {
4140 case ZS_SHARED:
4141 flags = 0;
4142 break;
4143 case ZS_EXCLUSIVE:
4144 flags = ZCF_NET_EXCL;
4145 break;
4148 if ((privs = priv_allocset()) == NULL) {
4149 zerror(zlogp, B_TRUE, "%s failed", "priv_allocset");
4150 return (-1);
4152 priv_emptyset(privs);
4153 if (get_privset(zlogp, privs, mount_cmd) != 0)
4154 goto error;
4156 if (mount_cmd == Z_MNT_BOOT &&
4157 get_rctls(zlogp, &rctlbuf, &rctlbufsz) != 0) {
4158 zerror(zlogp, B_FALSE, "Unable to get list of rctls");
4159 goto error;
4162 if (get_datasets(zlogp, &zfsbuf, &zfsbufsz) != 0) {
4163 zerror(zlogp, B_FALSE, "Unable to get list of ZFS datasets");
4164 goto error;
4167 kzone = zone_name;
4170 * We must do this scan twice. First, we look for zones running on the
4171 * main system that are using this root (or any subdirectory of it).
4172 * Next, we reduce to the shortest path and search for loopback mounts
4173 * that use this same source node (same device and inode).
4175 if (duplicate_zone_root(zlogp, rootpath))
4176 goto error;
4177 if (duplicate_reachable_path(zlogp, rootpath))
4178 goto error;
4180 if (ALT_MOUNT(mount_cmd)) {
4181 root_to_lu(zlogp, rootpath, sizeof (rootpath), B_TRUE);
4184 * Forge up a special root for this zone. When a zone is
4185 * mounted, we can't let the zone have its own root because the
4186 * tools that will be used in this "scratch zone" need access
4187 * to both the zone's resources and the running machine's
4188 * executables.
4190 * Note that the mkdir here also catches read-only filesystems.
4192 if (mkdir(rootpath, 0755) != 0 && errno != EEXIST) {
4193 zerror(zlogp, B_TRUE, "cannot create %s", rootpath);
4194 goto error;
4196 if (domount(zlogp, "tmpfs", "", "swap", rootpath) != 0)
4197 goto error;
4200 if (zonecfg_in_alt_root()) {
4202 * If we are mounting up a zone in an alternate root partition,
4203 * then we have some additional work to do before starting the
4204 * zone. First, resolve the root path down so that we're not
4205 * fooled by duplicates. Then forge up an internal name for
4206 * the zone.
4208 if ((fp = zonecfg_open_scratch("", B_TRUE)) == NULL) {
4209 zerror(zlogp, B_TRUE, "cannot open mapfile");
4210 goto error;
4212 if (zonecfg_lock_scratch(fp) != 0) {
4213 zerror(zlogp, B_TRUE, "cannot lock mapfile");
4214 goto error;
4216 if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4217 NULL, 0) == 0) {
4218 zerror(zlogp, B_FALSE, "scratch zone already running");
4219 goto error;
4221 /* This is the preferred name */
4222 (void) snprintf(kernzone, sizeof (kernzone), "SUNWlu-%s",
4223 zone_name);
4224 srandom(getpid());
4225 while (zonecfg_reverse_scratch(fp, kernzone, NULL, 0, NULL,
4226 0) == 0) {
4227 /* This is just an arbitrary name; note "." usage */
4228 (void) snprintf(kernzone, sizeof (kernzone),
4229 "SUNWlu.%08lX%08lX", random(), random());
4231 kzone = kernzone;
4234 xerr = 0;
4235 if ((zoneid = zone_create(kzone, rootpath, privs, rctlbuf,
4236 rctlbufsz, zfsbuf, zfsbufsz, &xerr, flags)) == -1) {
4237 if (xerr == ZE_AREMOUNTS) {
4238 if (zonecfg_find_mounts(rootpath, NULL, NULL) < 1) {
4239 zerror(zlogp, B_FALSE,
4240 "An unknown file-system is mounted on "
4241 "a subdirectory of %s", rootpath);
4242 } else {
4244 zerror(zlogp, B_FALSE,
4245 "These file-systems are mounted on "
4246 "subdirectories of %s:", rootpath);
4247 (void) zonecfg_find_mounts(rootpath,
4248 prtmount, zlogp);
4250 } else if (xerr == ZE_CHROOTED) {
4251 zerror(zlogp, B_FALSE, "%s: "
4252 "cannot create a zone from a chrooted "
4253 "environment", "zone_create");
4254 } else {
4255 zerror(zlogp, B_TRUE, "%s failed", "zone_create");
4257 goto error;
4260 if (zonecfg_in_alt_root() &&
4261 zonecfg_add_scratch(fp, zone_name, kernzone,
4262 zonecfg_get_root()) == -1) {
4263 zerror(zlogp, B_TRUE, "cannot add mapfile entry");
4264 goto error;
4268 * The following actions are not performed when merely mounting a zone
4269 * for administrative use.
4271 if (mount_cmd == Z_MNT_BOOT) {
4272 brand_handle_t bh;
4273 struct brand_attr attr;
4274 char modname[MAXPATHLEN];
4276 if (setup_zone_attrs(zlogp, zone_name, zoneid) != Z_OK)
4277 goto error;
4279 if ((bh = brand_open(brand_name)) == NULL) {
4280 zerror(zlogp, B_FALSE,
4281 "unable to determine brand name");
4282 goto error;
4286 * If this brand requires any kernel support, now is the time to
4287 * get it loaded and initialized.
4289 if (brand_get_modname(bh, modname, MAXPATHLEN) < 0) {
4290 brand_close(bh);
4291 zerror(zlogp, B_FALSE,
4292 "unable to determine brand kernel module");
4293 goto error;
4295 brand_close(bh);
4297 if (strlen(modname) > 0) {
4298 (void) strlcpy(attr.ba_brandname, brand_name,
4299 sizeof (attr.ba_brandname));
4300 (void) strlcpy(attr.ba_modname, modname,
4301 sizeof (attr.ba_modname));
4302 if (zone_setattr(zoneid, ZONE_ATTR_BRAND, &attr,
4303 sizeof (attr) != 0)) {
4304 zerror(zlogp, B_TRUE,
4305 "could not set zone brand attribute.");
4306 goto error;
4310 if (setup_zone_rm(zlogp, zone_name, zoneid) != Z_OK)
4311 goto error;
4314 rval = zoneid;
4315 zoneid = -1;
4317 error:
4318 if (zoneid != -1) {
4319 (void) zone_shutdown(zoneid);
4320 (void) zone_destroy(zoneid);
4322 free(rctlbuf);
4323 priv_freeset(privs);
4324 if (fp != NULL)
4325 zonecfg_close_scratch(fp);
4326 lofs_discard_mnttab();
4327 return (rval);
4331 * Enter the zone and write a /etc/zones/index file there. This allows
4332 * libzonecfg (and thus zoneadm) to report the UUID and potentially other zone
4333 * details from inside the zone.
4335 static void
4336 write_index_file(zoneid_t zoneid)
4338 FILE *zef;
4339 FILE *zet;
4340 struct zoneent *zep;
4341 pid_t child;
4342 int tmpl_fd;
4343 ctid_t ct;
4344 int fd;
4345 char uuidstr[UUID_PRINTABLE_STRING_LENGTH];
4347 /* Locate the zone entry in the global zone's index file */
4348 if ((zef = setzoneent()) == NULL)
4349 return;
4350 while ((zep = getzoneent_private(zef)) != NULL) {
4351 if (strcmp(zep->zone_name, zone_name) == 0)
4352 break;
4353 free(zep);
4355 endzoneent(zef);
4356 if (zep == NULL)
4357 return;
4359 if ((tmpl_fd = init_template()) == -1) {
4360 free(zep);
4361 return;
4364 if ((child = fork()) == -1) {
4365 (void) ct_tmpl_clear(tmpl_fd);
4366 (void) close(tmpl_fd);
4367 free(zep);
4368 return;
4371 /* parent waits for child to finish */
4372 if (child != 0) {
4373 free(zep);
4374 if (contract_latest(&ct) == -1)
4375 ct = -1;
4376 (void) ct_tmpl_clear(tmpl_fd);
4377 (void) close(tmpl_fd);
4378 (void) waitpid(child, NULL, 0);
4379 (void) contract_abandon_id(ct);
4380 return;
4383 /* child enters zone and sets up index file */
4384 (void) ct_tmpl_clear(tmpl_fd);
4385 if (zone_enter(zoneid) != -1) {
4386 (void) mkdir(ZONE_CONFIG_ROOT, ZONE_CONFIG_MODE);
4387 (void) chown(ZONE_CONFIG_ROOT, ZONE_CONFIG_UID,
4388 ZONE_CONFIG_GID);
4389 fd = open(ZONE_INDEX_FILE, O_WRONLY|O_CREAT|O_TRUNC,
4390 ZONE_INDEX_MODE);
4391 if (fd != -1 && (zet = fdopen(fd, "w")) != NULL) {
4392 (void) fchown(fd, ZONE_INDEX_UID, ZONE_INDEX_GID);
4393 if (uuid_is_null(zep->zone_uuid))
4394 uuidstr[0] = '\0';
4395 else
4396 uuid_unparse(zep->zone_uuid, uuidstr);
4397 (void) fprintf(zet, "%s:%s:/:%s\n", zep->zone_name,
4398 zone_state_str(zep->zone_state),
4399 uuidstr);
4400 (void) fclose(zet);
4403 _exit(0);
4407 vplat_bringup(zlog_t *zlogp, zone_mnt_t mount_cmd, zoneid_t zoneid)
4409 char zonepath[MAXPATHLEN];
4411 if (mount_cmd == Z_MNT_BOOT && validate_datasets(zlogp) != 0) {
4412 lofs_discard_mnttab();
4413 return (-1);
4417 * Before we try to mount filesystems we need to create the
4418 * attribute backing store for /dev
4420 if (zone_get_zonepath(zone_name, zonepath, sizeof (zonepath)) != Z_OK) {
4421 lofs_discard_mnttab();
4422 return (-1);
4424 resolve_lofs(zlogp, zonepath, sizeof (zonepath));
4426 /* Make /dev directory owned by root, grouped sys */
4427 if (make_one_dir(zlogp, zonepath, "/dev", DEFAULT_DIR_MODE,
4428 0, 3) != 0) {
4429 lofs_discard_mnttab();
4430 return (-1);
4433 if (mount_filesystems(zlogp, mount_cmd) != 0) {
4434 lofs_discard_mnttab();
4435 return (-1);
4438 if (mount_cmd == Z_MNT_BOOT) {
4439 zone_iptype_t iptype;
4441 if (vplat_get_iptype(zlogp, &iptype) < 0) {
4442 zerror(zlogp, B_TRUE, "unable to determine ip-type");
4443 lofs_discard_mnttab();
4444 return (-1);
4447 switch (iptype) {
4448 case ZS_SHARED:
4449 /* Always do this to make lo0 get configured */
4450 if (configure_shared_network_interfaces(zlogp) != 0) {
4451 lofs_discard_mnttab();
4452 return (-1);
4454 break;
4455 case ZS_EXCLUSIVE:
4456 if (configure_exclusive_network_interfaces(zlogp,
4457 zoneid) !=
4458 0) {
4459 lofs_discard_mnttab();
4460 return (-1);
4462 break;
4466 write_index_file(zoneid);
4468 lofs_discard_mnttab();
4469 return (0);
4472 static int
4473 lu_root_teardown(zlog_t *zlogp)
4475 char zroot[MAXPATHLEN];
4477 if (zone_get_rootpath(zone_name, zroot, sizeof (zroot)) != Z_OK) {
4478 zerror(zlogp, B_FALSE, "unable to determine zone root");
4479 return (-1);
4481 root_to_lu(zlogp, zroot, sizeof (zroot), B_FALSE);
4484 * At this point, the processes are gone, the filesystems (save the
4485 * root) are unmounted, and the zone is on death row. But there may
4486 * still be creds floating about in the system that reference the
4487 * zone_t, and which pin down zone_rootvp causing this call to fail
4488 * with EBUSY. Thus, we try for a little while before just giving up.
4489 * (How I wish this were not true, and umount2 just did the right
4490 * thing, or tmpfs supported MS_FORCE This is a gross hack.)
4492 if (umount2(zroot, MS_FORCE) != 0) {
4493 if (errno == ENOTSUP && umount2(zroot, 0) == 0)
4494 goto unmounted;
4495 if (errno == EBUSY) {
4496 int tries = 10;
4498 while (--tries >= 0) {
4499 (void) sleep(1);
4500 if (umount2(zroot, 0) == 0)
4501 goto unmounted;
4502 if (errno != EBUSY)
4503 break;
4506 zerror(zlogp, B_TRUE, "unable to unmount '%s'", zroot);
4507 return (-1);
4509 unmounted:
4512 * Only zones in an alternate root environment have scratch zone
4513 * entries.
4515 if (zonecfg_in_alt_root()) {
4516 FILE *fp;
4517 int retv;
4519 if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4520 zerror(zlogp, B_TRUE, "cannot open mapfile");
4521 return (-1);
4523 retv = -1;
4524 if (zonecfg_lock_scratch(fp) != 0)
4525 zerror(zlogp, B_TRUE, "cannot lock mapfile");
4526 else if (zonecfg_delete_scratch(fp, kernzone) != 0)
4527 zerror(zlogp, B_TRUE, "cannot delete map entry");
4528 else
4529 retv = 0;
4530 zonecfg_close_scratch(fp);
4531 return (retv);
4532 } else {
4533 return (0);
4538 vplat_teardown(zlog_t *zlogp, boolean_t unmount_cmd, boolean_t rebooting)
4540 char *kzone;
4541 zoneid_t zoneid;
4542 int res;
4543 char pool_err[128];
4544 char zpath[MAXPATHLEN];
4545 char cmdbuf[MAXPATHLEN];
4546 brand_handle_t bh = NULL;
4547 dladm_status_t status;
4548 char errmsg[DLADM_STRSIZE];
4549 ushort_t flags;
4551 kzone = zone_name;
4552 if (zonecfg_in_alt_root()) {
4553 FILE *fp;
4555 if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
4556 zerror(zlogp, B_TRUE, "unable to open map file");
4557 goto error;
4559 if (zonecfg_find_scratch(fp, zone_name, zonecfg_get_root(),
4560 kernzone, sizeof (kernzone)) != 0) {
4561 zerror(zlogp, B_FALSE, "unable to find scratch zone");
4562 zonecfg_close_scratch(fp);
4563 goto error;
4565 zonecfg_close_scratch(fp);
4566 kzone = kernzone;
4569 if ((zoneid = getzoneidbyname(kzone)) == ZONE_ID_UNDEFINED) {
4570 if (!bringup_failure_recovery)
4571 zerror(zlogp, B_TRUE, "unable to get zoneid");
4572 if (unmount_cmd)
4573 (void) lu_root_teardown(zlogp);
4574 goto error;
4577 if (remove_datalink_pool(zlogp, zoneid) != 0) {
4578 zerror(zlogp, B_FALSE, "unable clear datalink pool property");
4579 goto error;
4582 if (remove_datalink_protect(zlogp, zoneid) != 0) {
4583 zerror(zlogp, B_FALSE,
4584 "unable clear datalink protect property");
4585 goto error;
4589 * The datalinks assigned to the zone will be removed from the NGZ as
4590 * part of zone_shutdown() so that we need to remove protect/pool etc.
4591 * before zone_shutdown(). Even if the shutdown itself fails, the zone
4592 * will not be able to violate any constraints applied because the
4593 * datalinks are no longer available to the zone.
4595 if (zone_shutdown(zoneid) != 0) {
4596 zerror(zlogp, B_TRUE, "unable to shutdown zone");
4597 goto error;
4600 /* Get the zonepath of this zone */
4601 if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
4602 zerror(zlogp, B_FALSE, "unable to determine zone path");
4603 goto error;
4606 /* Get a handle to the brand info for this zone */
4607 if ((bh = brand_open(brand_name)) == NULL) {
4608 zerror(zlogp, B_FALSE, "unable to determine zone brand");
4609 return (-1);
4612 * If there is a brand 'halt' callback, execute it now to give the
4613 * brand a chance to cleanup any custom configuration.
4615 (void) strcpy(cmdbuf, EXEC_PREFIX);
4616 if (brand_get_halt(bh, zone_name, zpath, cmdbuf + EXEC_LEN,
4617 sizeof (cmdbuf) - EXEC_LEN) < 0) {
4618 brand_close(bh);
4619 zerror(zlogp, B_FALSE, "unable to determine branded zone's "
4620 "halt callback.");
4621 goto error;
4623 brand_close(bh);
4625 if ((strlen(cmdbuf) > EXEC_LEN) &&
4626 (do_subproc(zlogp, cmdbuf, NULL) != Z_OK)) {
4627 zerror(zlogp, B_FALSE, "%s failed", cmdbuf);
4628 goto error;
4631 if (!unmount_cmd) {
4632 zone_iptype_t iptype;
4634 if (zone_getattr(zoneid, ZONE_ATTR_FLAGS, &flags,
4635 sizeof (flags)) < 0) {
4636 if (vplat_get_iptype(zlogp, &iptype) < 0) {
4637 zerror(zlogp, B_TRUE, "unable to determine "
4638 "ip-type");
4639 goto error;
4641 } else {
4642 if (flags & ZF_NET_EXCL)
4643 iptype = ZS_EXCLUSIVE;
4644 else
4645 iptype = ZS_SHARED;
4648 switch (iptype) {
4649 case ZS_SHARED:
4650 if (unconfigure_shared_network_interfaces(zlogp,
4651 zoneid) != 0) {
4652 zerror(zlogp, B_FALSE, "unable to unconfigure "
4653 "network interfaces in zone");
4654 goto error;
4656 break;
4657 case ZS_EXCLUSIVE:
4658 if (unconfigure_exclusive_network_interfaces(zlogp,
4659 zoneid) != 0) {
4660 zerror(zlogp, B_FALSE, "unable to unconfigure "
4661 "network interfaces in zone");
4662 goto error;
4664 status = dladm_zone_halt(dld_handle, zoneid);
4665 if (status != DLADM_STATUS_OK) {
4666 zerror(zlogp, B_FALSE, "unable to notify "
4667 "dlmgmtd of zone halt: %s",
4668 dladm_status2str(status, errmsg));
4670 break;
4674 if (!unmount_cmd && tcp_abort_connections(zlogp, zoneid) != 0) {
4675 zerror(zlogp, B_TRUE, "unable to abort TCP connections");
4676 goto error;
4679 if (unmount_filesystems(zlogp, zoneid, unmount_cmd) != 0) {
4680 zerror(zlogp, B_FALSE,
4681 "unable to unmount file systems in zone");
4682 goto error;
4686 * If we are rebooting then we normally don't want to destroy an
4687 * existing temporary pool at this point so that we can just reuse it
4688 * when the zone boots back up. However, it is also possible we were
4689 * running with a temporary pool and the zone configuration has been
4690 * modified to no longer use a temporary pool. In that case we need
4691 * to destroy the temporary pool now. This case looks like the case
4692 * where we never had a temporary pool configured but
4693 * zonecfg_destroy_tmp_pool will do the right thing either way.
4695 if (!unmount_cmd) {
4696 boolean_t destroy_tmp_pool = B_TRUE;
4698 if (rebooting) {
4699 struct zone_psettab pset_tab;
4700 zone_dochandle_t handle;
4702 if ((handle = zonecfg_init_handle()) != NULL &&
4703 zonecfg_get_handle(zone_name, handle) == Z_OK &&
4704 zonecfg_lookup_pset(handle, &pset_tab) == Z_OK)
4705 destroy_tmp_pool = B_FALSE;
4707 zonecfg_fini_handle(handle);
4710 if (destroy_tmp_pool) {
4711 if ((res = zonecfg_destroy_tmp_pool(zone_name, pool_err,
4712 sizeof (pool_err))) != Z_OK) {
4713 if (res == Z_POOL)
4714 zerror(zlogp, B_FALSE, pool_err);
4719 if (zone_destroy(zoneid) != 0) {
4720 zerror(zlogp, B_TRUE, "unable to destroy zone");
4721 goto error;
4725 * Special teardown for alternate boot environments: remove the tmpfs
4726 * root for the zone and then remove it from the map file.
4728 if (unmount_cmd && lu_root_teardown(zlogp) != 0)
4729 goto error;
4731 lofs_discard_mnttab();
4732 return (0);
4734 error:
4735 lofs_discard_mnttab();
4736 return (-1);