Move /var/svc/log to /var/log/svc
[unleashed/lotheac.git] / usr / src / cmd / zoneadm / zoneadm.c
blob669343773974d67f560f4e2d178970f709f8ac44
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 2014 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2015 by Delphix. All rights reserved.
26 * Copyright (c) 2015 Josef 'Jeff' Sipek <jeffpc@josefsipek.net>
30 * zoneadm is a command interpreter for zone administration. It is all in
31 * C (i.e., no lex/yacc), and all the argument passing is argc/argv based.
32 * main() calls parse_and_run() which calls cmd_match(), then invokes the
33 * appropriate command's handler function. The rest of the program is the
34 * handler functions and their helper functions.
36 * Some of the helper functions are used largely to simplify I18N: reducing
37 * the need for translation notes. This is particularly true of many of
38 * the zerror() calls: doing e.g. zerror(gettext("%s failed"), "foo") rather
39 * than zerror(gettext("foo failed")) with a translation note indicating
40 * that "foo" need not be translated.
43 #include <stdio.h>
44 #include <errno.h>
45 #include <unistd.h>
46 #include <signal.h>
47 #include <stdarg.h>
48 #include <ctype.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <wait.h>
52 #include <zone.h>
53 #include <priv.h>
54 #include <locale.h>
55 #include <libintl.h>
56 #include <libzonecfg.h>
57 #include <sys/brand.h>
58 #include <sys/param.h>
59 #include <sys/types.h>
60 #include <sys/stat.h>
61 #include <sys/statvfs.h>
62 #include <assert.h>
63 #include <sys/sockio.h>
64 #include <sys/mntent.h>
65 #include <limits.h>
66 #include <dirent.h>
67 #include <uuid/uuid.h>
68 #include <fcntl.h>
69 #include <door.h>
70 #include <macros.h>
71 #include <libgen.h>
72 #include <fnmatch.h>
73 #include <sys/modctl.h>
74 #include <libbrand.h>
75 #include <libscf.h>
76 #include <procfs.h>
77 #include <strings.h>
78 #include <pool.h>
79 #include <sys/pool.h>
80 #include <sys/priocntl.h>
81 #include <sys/fsspriocntl.h>
82 #include <libdladm.h>
83 #include <libdllink.h>
84 #include <pwd.h>
85 #include <auth_list.h>
86 #include <auth_attr.h>
87 #include <secdb.h>
89 #include "zoneadm.h"
91 #define MAXARGS 8
92 #define SOURCE_ZONE (CMD_MAX + 1)
94 /* Reflects kernel zone entries */
95 typedef struct zone_entry {
96 zoneid_t zid;
97 char zname[ZONENAME_MAX];
98 char *zstate_str;
99 zone_state_t zstate_num;
100 char zbrand[MAXNAMELEN];
101 char zroot[MAXPATHLEN];
102 char zuuid[UUID_PRINTABLE_STRING_LENGTH];
103 zone_iptype_t ziptype;
104 } zone_entry_t;
106 #define CLUSTER_BRAND_NAME "cluster"
108 static zone_entry_t *zents;
109 static size_t nzents;
111 #define LOOPBACK_IF "lo0"
112 #define SOCKET_AF(af) (((af) == AF_UNSPEC) ? AF_INET : (af))
114 struct net_if {
115 char *name;
116 int af;
119 /* 0755 is the default directory mode. */
120 #define DEFAULT_DIR_MODE \
121 (S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
123 struct cmd {
124 uint_t cmd_num; /* command number */
125 char *cmd_name; /* command name */
126 char *short_usage; /* short form help */
127 int (*handler)(int argc, char *argv[]); /* function to call */
131 #define SHELP_HELP "help"
132 #define SHELP_BOOT "boot [-- boot_arguments]"
133 #define SHELP_HALT "halt"
134 #define SHELP_READY "ready"
135 #define SHELP_SHUTDOWN "shutdown [-r [-- boot_arguments]]"
136 #define SHELP_REBOOT "reboot [-- boot_arguments]"
137 #define SHELP_LIST "list [-cipv]"
138 #define SHELP_VERIFY "verify"
139 #define SHELP_INSTALL "install [brand-specific args]"
140 #define SHELP_UNINSTALL "uninstall [-F] [brand-specific args]"
141 #define SHELP_CLONE "clone [-m method] [-s <ZFS snapshot>] "\
142 "[brand-specific args] zonename"
143 #define SHELP_MOVE "move zonepath"
144 #define SHELP_DETACH "detach [-n] [brand-specific args]"
145 #define SHELP_ATTACH "attach [-F] [-n <path>] [brand-specific args]"
146 #define SHELP_MARK "mark incomplete"
148 #define EXEC_PREFIX "exec "
149 #define EXEC_LEN (strlen(EXEC_PREFIX))
150 #define RMCOMMAND "/usr/bin/rm -rf"
152 static int cleanup_zonepath(char *, boolean_t);
155 static int help_func(int argc, char *argv[]);
156 static int ready_func(int argc, char *argv[]);
157 static int boot_func(int argc, char *argv[]);
158 static int shutdown_func(int argc, char *argv[]);
159 static int halt_func(int argc, char *argv[]);
160 static int reboot_func(int argc, char *argv[]);
161 static int list_func(int argc, char *argv[]);
162 static int verify_func(int argc, char *argv[]);
163 static int install_func(int argc, char *argv[]);
164 static int uninstall_func(int argc, char *argv[]);
165 static int mount_func(int argc, char *argv[]);
166 static int unmount_func(int argc, char *argv[]);
167 static int clone_func(int argc, char *argv[]);
168 static int move_func(int argc, char *argv[]);
169 static int detach_func(int argc, char *argv[]);
170 static int attach_func(int argc, char *argv[]);
171 static int mark_func(int argc, char *argv[]);
172 static int apply_func(int argc, char *argv[]);
173 static int sysboot_func(int argc, char *argv[]);
174 static int sanity_check(char *zone, int cmd_num, boolean_t running,
175 boolean_t unsafe_when_running, boolean_t force);
176 static int cmd_match(char *cmd);
177 static int verify_details(int, char *argv[]);
178 static int verify_brand(zone_dochandle_t, int, char *argv[]);
179 static int invoke_brand_handler(int, char *argv[]);
181 static struct cmd cmdtab[] = {
182 { CMD_HELP, "help", SHELP_HELP, help_func },
183 { CMD_BOOT, "boot", SHELP_BOOT, boot_func },
184 { CMD_HALT, "halt", SHELP_HALT, halt_func },
185 { CMD_READY, "ready", SHELP_READY, ready_func },
186 { CMD_SHUTDOWN, "shutdown", SHELP_SHUTDOWN, shutdown_func },
187 { CMD_REBOOT, "reboot", SHELP_REBOOT, reboot_func },
188 { CMD_LIST, "list", SHELP_LIST, list_func },
189 { CMD_VERIFY, "verify", SHELP_VERIFY, verify_func },
190 { CMD_INSTALL, "install", SHELP_INSTALL, install_func },
191 { CMD_UNINSTALL, "uninstall", SHELP_UNINSTALL,
192 uninstall_func },
193 /* mount and unmount are private commands for admin/install */
194 { CMD_MOUNT, "mount", NULL, mount_func },
195 { CMD_UNMOUNT, "umount", NULL, unmount_func },
196 { CMD_UNMOUNT, "unmount", NULL, unmount_func },
197 { CMD_CLONE, "clone", SHELP_CLONE, clone_func },
198 { CMD_MOVE, "move", SHELP_MOVE, move_func },
199 { CMD_DETACH, "detach", SHELP_DETACH, detach_func },
200 { CMD_ATTACH, "attach", SHELP_ATTACH, attach_func },
201 { CMD_MARK, "mark", SHELP_MARK, mark_func },
202 { CMD_APPLY, "apply", NULL, apply_func },
203 { CMD_SYSBOOT, "sysboot", NULL, sysboot_func }
206 /* global variables */
208 /* set early in main(), never modified thereafter, used all over the place */
209 static char *execname;
210 static char target_brand[MAXNAMELEN];
211 static char default_brand[MAXPATHLEN];
212 static char *locale;
213 char *target_zone;
214 static char *target_uuid;
215 char *username;
217 char *
218 cmd_to_str(int cmd_num)
220 assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
221 return (cmdtab[cmd_num].cmd_name);
224 /* This is a separate function because of gettext() wrapping. */
225 static char *
226 long_help(int cmd_num)
228 assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
229 switch (cmd_num) {
230 case CMD_HELP:
231 return (gettext("Print usage message."));
232 case CMD_BOOT:
233 return (gettext("Activates (boots) specified zone. See "
234 "zoneadm(1m) for valid boot\n\targuments."));
235 case CMD_HALT:
236 return (gettext("Halts specified zone, bypassing shutdown "
237 "scripts and removing runtime\n\tresources of the zone."));
238 case CMD_READY:
239 return (gettext("Prepares a zone for running applications but "
240 "does not start any user\n\tprocesses in the zone."));
241 case CMD_SHUTDOWN:
242 return (gettext("Gracefully shutdown the zone or reboot if "
243 "the '-r' option is specified.\n\t"
244 "See zoneadm(1m) for valid boot arguments."));
245 case CMD_REBOOT:
246 return (gettext("Restarts the zone (equivalent to a halt / "
247 "boot sequence).\n\tFails if the zone is not active. "
248 "See zoneadm(1m) for valid boot\n\targuments."));
249 case CMD_LIST:
250 return (gettext("Lists the current zones, or a "
251 "specific zone if indicated. By default,\n\tall "
252 "running zones are listed, though this can be "
253 "expanded to all\n\tinstalled zones with the -i "
254 "option or all configured zones with the\n\t-c "
255 "option. When used with the general -z <zone> and/or -u "
256 "<uuid-match>\n\toptions, lists only the specified "
257 "matching zone, but lists it\n\tregardless of its state, "
258 "and the -i and -c options are disallowed. The\n\t-v "
259 "option can be used to display verbose information: zone "
260 "name, id,\n\tcurrent state, root directory and options. "
261 "The -p option can be used\n\tto request machine-parsable "
262 "output. The -v and -p options are mutually\n\texclusive."
263 " If neither -v nor -p is used, just the zone name is "
264 "listed."));
265 case CMD_VERIFY:
266 return (gettext("Check to make sure the configuration "
267 "can safely be instantiated\n\ton the machine: "
268 "physical network interfaces exist, etc."));
269 case CMD_INSTALL:
270 return (gettext("Install the configuration on to the system. "
271 "All arguments are passed to the brand installation "
272 "function;\n\tsee brands(5) for more information."));
273 case CMD_UNINSTALL:
274 return (gettext("Uninstall the configuration from the system. "
275 "The -F flag can be used\n\tto force the action. All "
276 "other arguments are passed to the brand\n\tuninstall "
277 "function; see brands(5) for more information."));
278 case CMD_CLONE:
279 return (gettext("Clone the installation of another zone. "
280 "The -m option can be used to\n\tspecify 'copy' which "
281 "forces a copy of the source zone. The -s option\n\t"
282 "can be used to specify the name of a ZFS snapshot "
283 "that was taken from\n\ta previous clone command. The "
284 "snapshot will be used as the source\n\tinstead of "
285 "creating a new ZFS snapshot. All other arguments are "
286 "passed\n\tto the brand clone function; see "
287 "brands(5) for more information."));
288 case CMD_MOVE:
289 return (gettext("Move the zone to a new zonepath."));
290 case CMD_DETACH:
291 return (gettext("Detach the zone from the system. The zone "
292 "state is changed to\n\t'configured' (but the files under "
293 "the zonepath are untouched).\n\tThe zone can subsequently "
294 "be attached, or can be moved to another\n\tsystem and "
295 "attached there. The -n option can be used to specify\n\t"
296 "'no-execute' mode. When -n is used, the information "
297 "needed to attach\n\tthe zone is sent to standard output "
298 "but the zone is not actually\n\tdetached. All other "
299 "arguments are passed to the brand detach function;\n\tsee "
300 "brands(5) for more information."));
301 case CMD_ATTACH:
302 return (gettext("Attach the zone to the system. The zone "
303 "state must be 'configured'\n\tprior to attach; upon "
304 "successful completion, the zone state will be\n\t"
305 "'installed'. The system software on the current "
306 "system must be\n\tcompatible with the software on the "
307 "zone's original system.\n\tSpecify -F "
308 "to force the attach and skip software compatibility "
309 "tests.\n\tThe -n option can be used to specify "
310 "'no-execute' mode. When -n is\n\tused, the information "
311 "needed to attach the zone is read from the\n\tspecified "
312 "path and the configuration is only validated. The path "
313 "can\n\tbe '-' to specify standard input. The -F and -n "
314 "options are mutually\n\texclusive. All other arguments "
315 "are passed to the brand attach\n\tfunction; see "
316 "brands(5) for more information."));
317 case CMD_MARK:
318 return (gettext("Set the state of the zone. This can be used "
319 "to force the zone\n\tstate to 'incomplete' "
320 "administratively if some activity has rendered\n\tthe "
321 "zone permanently unusable. The only valid state that "
322 "may be\n\tspecified is 'incomplete'."));
323 default:
324 return ("");
326 /* NOTREACHED */
327 return (NULL);
331 * Called with explicit B_TRUE when help is explicitly requested, B_FALSE for
332 * unexpected errors.
335 static int
336 usage(boolean_t explicit)
338 int i;
339 FILE *fd = explicit ? stdout : stderr;
341 (void) fprintf(fd, "%s:\t%s help\n", gettext("usage"), execname);
342 (void) fprintf(fd, "\t%s [-z <zone>] [-u <uuid-match>] list\n",
343 execname);
344 (void) fprintf(fd, "\t%s {-z <zone>|-u <uuid-match>} <%s>\n", execname,
345 gettext("subcommand"));
346 (void) fprintf(fd, "\n%s:\n\n", gettext("Subcommands"));
347 for (i = CMD_MIN; i <= CMD_MAX; i++) {
348 if (cmdtab[i].short_usage == NULL)
349 continue;
350 (void) fprintf(fd, "%s\n", cmdtab[i].short_usage);
351 if (explicit)
352 (void) fprintf(fd, "\t%s\n\n", long_help(i));
354 if (!explicit)
355 (void) fputs("\n", fd);
356 return (Z_USAGE);
359 static void
360 sub_usage(char *short_usage, int cmd_num)
362 (void) fprintf(stderr, "%s:\t%s\n", gettext("usage"), short_usage);
363 (void) fprintf(stderr, "\t%s\n", long_help(cmd_num));
367 * zperror() is like perror(3c) except that this also prints the executable
368 * name at the start of the message, and takes a boolean indicating whether
369 * to call libc'c strerror() or that from libzonecfg.
372 void
373 zperror(const char *str, boolean_t zonecfg_error)
375 (void) fprintf(stderr, "%s: %s: %s\n", execname, str,
376 zonecfg_error ? zonecfg_strerror(errno) : strerror(errno));
380 * zperror2() is very similar to zperror() above, except it also prints a
381 * supplied zone name after the executable.
383 * All current consumers of this function want libzonecfg's strerror() rather
384 * than libc's; if this ever changes, this function can be made more generic
385 * like zperror() above.
388 void
389 zperror2(const char *zone, const char *str)
391 (void) fprintf(stderr, "%s: %s: %s: %s\n", execname, zone, str,
392 zonecfg_strerror(errno));
395 /* PRINTFLIKE1 */
396 void
397 zerror(const char *fmt, ...)
399 va_list alist;
401 va_start(alist, fmt);
402 (void) fprintf(stderr, "%s: ", execname);
403 if (target_zone != NULL)
404 (void) fprintf(stderr, "zone '%s': ", target_zone);
405 (void) vfprintf(stderr, fmt, alist);
406 (void) fprintf(stderr, "\n");
407 va_end(alist);
410 static void *
411 safe_calloc(size_t nelem, size_t elsize)
413 void *r = calloc(nelem, elsize);
415 if (r == NULL) {
416 zerror(gettext("failed to allocate %lu bytes: %s"),
417 (ulong_t)nelem * elsize, strerror(errno));
418 exit(Z_ERR);
420 return (r);
423 static void
424 zone_print(zone_entry_t *zent, boolean_t verbose, boolean_t parsable)
426 static boolean_t firsttime = B_TRUE;
427 char *ip_type_str;
429 /* Skip a zone that shutdown while we were collecting data. */
430 if (zent->zname[0] == '\0')
431 return;
433 if (zent->ziptype == ZS_EXCLUSIVE)
434 ip_type_str = "excl";
435 else
436 ip_type_str = "shared";
438 assert(!(verbose && parsable));
439 if (firsttime && verbose) {
440 firsttime = B_FALSE;
441 (void) printf("%*s %-16s %-10s %-30s %-8s %-6s\n",
442 ZONEID_WIDTH, "ID", "NAME", "STATUS", "PATH", "BRAND",
443 "IP");
445 if (!verbose) {
446 char *cp, *clim;
448 if (!parsable) {
449 (void) printf("%s\n", zent->zname);
450 return;
452 if (zent->zid == ZONE_ID_UNDEFINED)
453 (void) printf("-");
454 else
455 (void) printf("%lu", zent->zid);
456 (void) printf(":%s:%s:", zent->zname, zent->zstate_str);
457 cp = zent->zroot;
458 while ((clim = strchr(cp, ':')) != NULL) {
459 (void) printf("%.*s\\:", clim - cp, cp);
460 cp = clim + 1;
462 (void) printf("%s:%s:%s:%s\n", cp, zent->zuuid, zent->zbrand,
463 ip_type_str);
464 return;
466 if (zent->zstate_str != NULL) {
467 if (zent->zid == ZONE_ID_UNDEFINED)
468 (void) printf("%*s", ZONEID_WIDTH, "-");
469 else
470 (void) printf("%*lu", ZONEID_WIDTH, zent->zid);
471 (void) printf(" %-16s %-10s %-30s %-8s %-6s\n", zent->zname,
472 zent->zstate_str, zent->zroot, zent->zbrand, ip_type_str);
476 static int
477 lookup_zone_info(const char *zone_name, zoneid_t zid, zone_entry_t *zent)
479 char root[MAXPATHLEN];
480 int err;
481 uuid_t uuid;
482 zone_dochandle_t handle;
484 (void) strlcpy(zent->zname, zone_name, sizeof (zent->zname));
485 (void) strlcpy(zent->zroot, "???", sizeof (zent->zroot));
486 (void) strlcpy(zent->zbrand, "???", sizeof (zent->zbrand));
487 zent->zstate_str = "???";
489 zent->zid = zid;
491 if (zonecfg_get_uuid(zone_name, uuid) == Z_OK &&
492 !uuid_is_null(uuid))
493 uuid_unparse(uuid, zent->zuuid);
494 else
495 zent->zuuid[0] = '\0';
497 if ((err = zone_get_zonepath(zent->zname, root,
498 sizeof (root))) != Z_OK) {
499 errno = err;
500 zperror2(zent->zname,
501 gettext("could not get zone path."));
502 return (Z_ERR);
504 (void) strlcpy(zent->zroot, root, sizeof (zent->zroot));
506 if ((err = zone_get_state(zent->zname, &zent->zstate_num)) != Z_OK) {
507 errno = err;
508 zperror2(zent->zname, gettext("could not get state"));
509 return (Z_ERR);
511 zent->zstate_str = zone_state_str(zent->zstate_num);
513 if (zone_get_brand(zent->zname, zent->zbrand,
514 sizeof (zent->zbrand)) != Z_OK) {
515 zperror2(zent->zname, gettext("could not get brand name"));
516 return (Z_ERR);
520 * Get ip type of the zone.
521 * Note for global zone, ZS_SHARED is set always.
523 if (zid == GLOBAL_ZONEID) {
524 zent->ziptype = ZS_SHARED;
525 return (Z_OK);
529 * There is a race condition where the zone could boot while
530 * we're walking the index file. In this case the zone state
531 * could be seen as running from the call above, but the zoneid
532 * would be undefined.
534 * There is also a race condition where the zone could shutdown after
535 * we got its running state above. This is also not an error and
536 * we fall back to getting the ziptype from the zone configuration.
538 if (zent->zstate_num == ZONE_STATE_RUNNING &&
539 zid != ZONE_ID_UNDEFINED) {
540 ushort_t flags;
542 if (zone_getattr(zid, ZONE_ATTR_FLAGS, &flags,
543 sizeof (flags)) >= 0) {
544 if (flags & ZF_NET_EXCL)
545 zent->ziptype = ZS_EXCLUSIVE;
546 else
547 zent->ziptype = ZS_SHARED;
548 return (Z_OK);
552 if ((handle = zonecfg_init_handle()) == NULL) {
553 zperror2(zent->zname, gettext("could not init handle"));
554 return (Z_ERR);
556 if ((err = zonecfg_get_handle(zent->zname, handle)) != Z_OK) {
557 zperror2(zent->zname, gettext("could not get handle"));
558 zonecfg_fini_handle(handle);
559 return (Z_ERR);
562 if ((err = zonecfg_get_iptype(handle, &zent->ziptype)) != Z_OK) {
563 zperror2(zent->zname, gettext("could not get ip-type"));
564 zonecfg_fini_handle(handle);
565 return (Z_ERR);
567 zonecfg_fini_handle(handle);
569 return (Z_OK);
573 * fetch_zents() calls zone_list(2) to find out how many zones are running
574 * (which is stored in the global nzents), then calls zone_list(2) again
575 * to fetch the list of running zones (stored in the global zents). This
576 * function may be called multiple times, so if zents is already set, we
577 * return immediately to save work.
579 * Note that the data about running zones can change while this function
580 * is running, so its possible that the list of zones will have empty slots
581 * at the end.
584 static int
585 fetch_zents(void)
587 zoneid_t *zids = NULL;
588 uint_t nzents_saved;
589 int i, retv;
590 FILE *fp;
591 boolean_t inaltroot;
592 zone_entry_t *zentp;
593 const char *altroot;
595 if (nzents > 0)
596 return (Z_OK);
598 if (zone_list(NULL, &nzents) != 0) {
599 zperror(gettext("failed to get zoneid list"), B_FALSE);
600 return (Z_ERR);
603 again:
604 if (nzents == 0)
605 return (Z_OK);
607 zids = safe_calloc(nzents, sizeof (zoneid_t));
608 nzents_saved = nzents;
610 if (zone_list(zids, &nzents) != 0) {
611 zperror(gettext("failed to get zone list"), B_FALSE);
612 free(zids);
613 return (Z_ERR);
615 if (nzents != nzents_saved) {
616 /* list changed, try again */
617 free(zids);
618 goto again;
621 zents = safe_calloc(nzents, sizeof (zone_entry_t));
623 inaltroot = zonecfg_in_alt_root();
624 if (inaltroot) {
625 fp = zonecfg_open_scratch("", B_FALSE);
626 altroot = zonecfg_get_root();
627 } else {
628 fp = NULL;
630 zentp = zents;
631 retv = Z_OK;
632 for (i = 0; i < nzents; i++) {
633 char name[ZONENAME_MAX];
634 char altname[ZONENAME_MAX];
635 char rev_altroot[MAXPATHLEN];
637 if (getzonenamebyid(zids[i], name, sizeof (name)) < 0) {
639 * There is a race condition where the zone may have
640 * shutdown since we retrieved the number of running
641 * zones above. This is not an error, there will be
642 * an empty slot at the end of the list.
644 continue;
646 if (zonecfg_is_scratch(name)) {
647 /* Ignore scratch zones by default */
648 if (!inaltroot)
649 continue;
650 if (fp == NULL ||
651 zonecfg_reverse_scratch(fp, name, altname,
652 sizeof (altname), rev_altroot,
653 sizeof (rev_altroot)) == -1) {
654 zerror(gettext("could not resolve scratch "
655 "zone %s"), name);
656 retv = Z_ERR;
657 continue;
659 /* Ignore zones in other alternate roots */
660 if (strcmp(rev_altroot, altroot) != 0)
661 continue;
662 (void) strcpy(name, altname);
663 } else {
664 /* Ignore non-scratch when in an alternate root */
665 if (inaltroot && strcmp(name, GLOBAL_ZONENAME) != 0)
666 continue;
668 if (lookup_zone_info(name, zids[i], zentp) != Z_OK) {
670 * There is a race condition where the zone may have
671 * shutdown since we retrieved the number of running
672 * zones above. This is not an error, there will be
673 * an empty slot at the end of the list.
675 continue;
677 zentp++;
679 nzents = zentp - zents;
680 if (fp != NULL)
681 zonecfg_close_scratch(fp);
683 free(zids);
684 return (retv);
687 static int
688 zone_print_list(zone_state_t min_state, boolean_t verbose, boolean_t parsable)
690 int i;
691 zone_entry_t zent;
692 FILE *cookie;
693 char *name;
696 * First get the list of running zones from the kernel and print them.
697 * If that is all we need, then return.
699 if ((i = fetch_zents()) != Z_OK) {
701 * No need for error messages; fetch_zents() has already taken
702 * care of this.
704 return (i);
706 for (i = 0; i < nzents; i++)
707 zone_print(&zents[i], verbose, parsable);
708 if (min_state >= ZONE_STATE_RUNNING)
709 return (Z_OK);
711 * Next, get the full list of zones from the configuration, skipping
712 * any we have already printed.
714 cookie = setzoneent();
715 while ((name = getzoneent(cookie)) != NULL) {
716 for (i = 0; i < nzents; i++) {
717 if (strcmp(zents[i].zname, name) == 0)
718 break;
720 if (i < nzents) {
721 free(name);
722 continue;
724 if (lookup_zone_info(name, ZONE_ID_UNDEFINED, &zent) != Z_OK) {
725 free(name);
726 continue;
728 free(name);
729 if (zent.zstate_num >= min_state)
730 zone_print(&zent, verbose, parsable);
732 endzoneent(cookie);
733 return (Z_OK);
737 * Retrieve a zone entry by name. Returns NULL if no such zone exists.
739 static zone_entry_t *
740 lookup_running_zone(const char *str)
742 int i;
744 if (fetch_zents() != Z_OK)
745 return (NULL);
747 for (i = 0; i < nzents; i++) {
748 if (strcmp(str, zents[i].zname) == 0)
749 return (&zents[i]);
751 return (NULL);
755 * Check a bit in a mode_t: if on is B_TRUE, that bit should be on; if
756 * B_FALSE, it should be off. Return B_TRUE if the mode is bad (incorrect).
758 static boolean_t
759 bad_mode_bit(mode_t mode, mode_t bit, boolean_t on, char *file)
761 char *str;
763 assert(bit == S_IRUSR || bit == S_IWUSR || bit == S_IXUSR ||
764 bit == S_IRGRP || bit == S_IWGRP || bit == S_IXGRP ||
765 bit == S_IROTH || bit == S_IWOTH || bit == S_IXOTH);
767 * TRANSLATION_NOTE
768 * The strings below will be used as part of a larger message,
769 * either:
770 * (file name) must be (owner|group|world) (read|writ|execut)able
771 * or
772 * (file name) must not be (owner|group|world) (read|writ|execut)able
774 switch (bit) {
775 case S_IRUSR:
776 str = gettext("owner readable");
777 break;
778 case S_IWUSR:
779 str = gettext("owner writable");
780 break;
781 case S_IXUSR:
782 str = gettext("owner executable");
783 break;
784 case S_IRGRP:
785 str = gettext("group readable");
786 break;
787 case S_IWGRP:
788 str = gettext("group writable");
789 break;
790 case S_IXGRP:
791 str = gettext("group executable");
792 break;
793 case S_IROTH:
794 str = gettext("world readable");
795 break;
796 case S_IWOTH:
797 str = gettext("world writable");
798 break;
799 case S_IXOTH:
800 str = gettext("world executable");
801 break;
803 if ((mode & bit) == (on ? 0 : bit)) {
805 * TRANSLATION_NOTE
806 * The first parameter below is a file name; the second
807 * is one of the "(owner|group|world) (read|writ|execut)able"
808 * strings from above.
811 * The code below could be simplified but not in a way
812 * that would easily translate to non-English locales.
814 if (on) {
815 (void) fprintf(stderr, gettext("%s must be %s.\n"),
816 file, str);
817 } else {
818 (void) fprintf(stderr, gettext("%s must not be %s.\n"),
819 file, str);
821 return (B_TRUE);
823 return (B_FALSE);
827 * We want to make sure that no zone has its zone path as a child node
828 * (in the directory sense) of any other. We do that by comparing this
829 * zone's path to the path of all other (non-global) zones. The comparison
830 * in each case is simple: add '/' to the end of the path, then do a
831 * strncmp() of the two paths, using the length of the shorter one.
834 static int
835 crosscheck_zonepaths(char *path)
837 char rpath[MAXPATHLEN]; /* resolved path */
838 char path_copy[MAXPATHLEN]; /* copy of original path */
839 char rpath_copy[MAXPATHLEN]; /* copy of original rpath */
840 struct zoneent *ze;
841 int res, err;
842 FILE *cookie;
844 cookie = setzoneent();
845 while ((ze = getzoneent_private(cookie)) != NULL) {
846 /* Skip zones which are not installed. */
847 if (ze->zone_state < ZONE_STATE_INSTALLED) {
848 free(ze);
849 continue;
851 /* Skip the global zone and the current target zone. */
852 if (strcmp(ze->zone_name, GLOBAL_ZONENAME) == 0 ||
853 strcmp(ze->zone_name, target_zone) == 0) {
854 free(ze);
855 continue;
857 if (strlen(ze->zone_path) == 0) {
858 /* old index file without path, fall back */
859 if ((err = zone_get_zonepath(ze->zone_name,
860 ze->zone_path, sizeof (ze->zone_path))) != Z_OK) {
861 errno = err;
862 zperror2(ze->zone_name,
863 gettext("could not get zone path"));
864 free(ze);
865 continue;
868 (void) snprintf(path_copy, sizeof (path_copy), "%s%s",
869 zonecfg_get_root(), ze->zone_path);
870 res = resolvepath(path_copy, rpath, sizeof (rpath));
871 if (res == -1) {
872 if (errno != ENOENT) {
873 zperror(path_copy, B_FALSE);
874 free(ze);
875 return (Z_ERR);
877 (void) printf(gettext("WARNING: zone %s is installed, "
878 "but its %s %s does not exist.\n"), ze->zone_name,
879 "zonepath", path_copy);
880 free(ze);
881 continue;
883 rpath[res] = '\0';
884 (void) snprintf(path_copy, sizeof (path_copy), "%s/", path);
885 (void) snprintf(rpath_copy, sizeof (rpath_copy), "%s/", rpath);
886 if (strncmp(path_copy, rpath_copy,
887 min(strlen(path_copy), strlen(rpath_copy))) == 0) {
889 * TRANSLATION_NOTE
890 * zonepath is a literal that should not be translated.
892 (void) fprintf(stderr, gettext("%s zonepath (%s) and "
893 "%s zonepath (%s) overlap.\n"),
894 target_zone, path, ze->zone_name, rpath);
895 free(ze);
896 return (Z_ERR);
898 free(ze);
900 endzoneent(cookie);
901 return (Z_OK);
904 static int
905 validate_zonepath(char *path, int cmd_num)
907 int res; /* result of last library/system call */
908 boolean_t err = B_FALSE; /* have we run into an error? */
909 struct stat stbuf;
910 struct statvfs64 vfsbuf;
911 char rpath[MAXPATHLEN]; /* resolved path */
912 char ppath[MAXPATHLEN]; /* parent path */
913 char rppath[MAXPATHLEN]; /* resolved parent path */
914 char rootpath[MAXPATHLEN]; /* root path */
915 zone_state_t state;
917 if (path[0] != '/') {
918 (void) fprintf(stderr,
919 gettext("%s is not an absolute path.\n"), path);
920 return (Z_ERR);
922 if ((res = resolvepath(path, rpath, sizeof (rpath))) == -1) {
923 if ((errno != ENOENT) ||
924 (cmd_num != CMD_VERIFY && cmd_num != CMD_INSTALL &&
925 cmd_num != CMD_CLONE && cmd_num != CMD_MOVE)) {
926 zperror(path, B_FALSE);
927 return (Z_ERR);
929 if (cmd_num == CMD_VERIFY) {
931 * TRANSLATION_NOTE
932 * zoneadm is a literal that should not be translated.
934 (void) fprintf(stderr, gettext("WARNING: %s does not "
935 "exist, so it could not be verified.\nWhen "
936 "'zoneadm %s' is run, '%s' will try to create\n%s, "
937 "and '%s' will be tried again,\nbut the '%s' may "
938 "fail if:\nthe parent directory of %s is group- or "
939 "other-writable\nor\n%s overlaps with any other "
940 "installed zones.\n"), path,
941 cmd_to_str(CMD_INSTALL), cmd_to_str(CMD_INSTALL),
942 path, cmd_to_str(CMD_VERIFY),
943 cmd_to_str(CMD_VERIFY), path, path);
944 return (Z_OK);
947 * The zonepath is supposed to be mode 700 but its
948 * parent(s) 755. So use 755 on the mkdirp() then
949 * chmod() the zonepath itself to 700.
951 if (mkdirp(path, DEFAULT_DIR_MODE) < 0) {
952 zperror(path, B_FALSE);
953 return (Z_ERR);
956 * If the chmod() fails, report the error, but might
957 * as well continue the verify procedure.
959 if (chmod(path, S_IRWXU) != 0)
960 zperror(path, B_FALSE);
962 * Since the mkdir() succeeded, we should not have to
963 * worry about a subsequent ENOENT, thus this should
964 * only recurse once.
966 return (validate_zonepath(path, cmd_num));
968 rpath[res] = '\0';
969 if (strcmp(path, rpath) != 0) {
970 errno = Z_RESOLVED_PATH;
971 zperror(path, B_TRUE);
972 return (Z_ERR);
974 if ((res = stat(rpath, &stbuf)) != 0) {
975 zperror(rpath, B_FALSE);
976 return (Z_ERR);
978 if (!S_ISDIR(stbuf.st_mode)) {
979 (void) fprintf(stderr, gettext("%s is not a directory.\n"),
980 rpath);
981 return (Z_ERR);
983 if (strcmp(stbuf.st_fstype, MNTTYPE_TMPFS) == 0) {
984 (void) printf(gettext("WARNING: %s is on a temporary "
985 "file system.\n"), rpath);
987 if (crosscheck_zonepaths(rpath) != Z_OK)
988 return (Z_ERR);
990 * Try to collect and report as many minor errors as possible
991 * before returning, so the user can learn everything that needs
992 * to be fixed up front.
994 if (stbuf.st_uid != 0) {
995 (void) fprintf(stderr, gettext("%s is not owned by root.\n"),
996 rpath);
997 err = B_TRUE;
999 /* Try to change owner */
1000 if (cmd_num != CMD_VERIFY) {
1001 (void) fprintf(stderr, gettext("%s: changing owner "
1002 "to root.\n"), rpath);
1003 if (chown(rpath, 0, -1) != 0) {
1004 zperror(rpath, B_FALSE);
1005 return (Z_ERR);
1006 } else {
1007 err = B_FALSE;
1011 err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rpath);
1012 err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rpath);
1013 err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rpath);
1014 err |= bad_mode_bit(stbuf.st_mode, S_IRGRP, B_FALSE, rpath);
1015 err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rpath);
1016 err |= bad_mode_bit(stbuf.st_mode, S_IXGRP, B_FALSE, rpath);
1017 err |= bad_mode_bit(stbuf.st_mode, S_IROTH, B_FALSE, rpath);
1018 err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rpath);
1019 err |= bad_mode_bit(stbuf.st_mode, S_IXOTH, B_FALSE, rpath);
1021 /* If the group perms are wrong, fix them */
1022 if (err && (cmd_num != CMD_VERIFY)) {
1023 (void) fprintf(stderr, gettext("%s: changing permissions "
1024 "to 0700.\n"), rpath);
1025 if (chmod(rpath, S_IRWXU) != 0) {
1026 zperror(path, B_FALSE);
1027 } else {
1028 err = B_FALSE;
1032 (void) snprintf(ppath, sizeof (ppath), "%s/..", path);
1033 if ((res = resolvepath(ppath, rppath, sizeof (rppath))) == -1) {
1034 zperror(ppath, B_FALSE);
1035 return (Z_ERR);
1037 rppath[res] = '\0';
1038 if ((res = stat(rppath, &stbuf)) != 0) {
1039 zperror(rppath, B_FALSE);
1040 return (Z_ERR);
1042 /* theoretically impossible */
1043 if (!S_ISDIR(stbuf.st_mode)) {
1044 (void) fprintf(stderr, gettext("%s is not a directory.\n"),
1045 rppath);
1046 return (Z_ERR);
1048 if (stbuf.st_uid != 0) {
1049 (void) fprintf(stderr, gettext("%s is not owned by root.\n"),
1050 rppath);
1051 err = B_TRUE;
1053 err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rppath);
1054 err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rppath);
1055 err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rppath);
1056 err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rppath);
1057 err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rppath);
1058 if (strcmp(rpath, rppath) == 0) {
1059 (void) fprintf(stderr, gettext("%s is its own parent.\n"),
1060 rppath);
1061 err = B_TRUE;
1064 if (statvfs(rpath, &vfsbuf) != 0) {
1065 zperror(rpath, B_FALSE);
1066 return (Z_ERR);
1068 if (strcmp(vfsbuf.f_basetype, MNTTYPE_NFS) == 0) {
1070 * TRANSLATION_NOTE
1071 * Zonepath and NFS are literals that should not be translated.
1073 (void) fprintf(stderr, gettext("Zonepath %s is on an NFS "
1074 "mounted file system.\n"
1075 "\tA local file system must be used.\n"), rpath);
1076 return (Z_ERR);
1078 if (vfsbuf.f_flag & ST_NOSUID) {
1080 * TRANSLATION_NOTE
1081 * Zonepath and nosuid are literals that should not be
1082 * translated.
1084 (void) fprintf(stderr, gettext("Zonepath %s is on a nosuid "
1085 "file system.\n"), rpath);
1086 return (Z_ERR);
1089 if ((res = zone_get_state(target_zone, &state)) != Z_OK) {
1090 errno = res;
1091 zperror2(target_zone, gettext("could not get state"));
1092 return (Z_ERR);
1095 * The existence of the root path is only bad in the configured state,
1096 * as it is *supposed* to be there at the installed and later states.
1097 * However, the root path is expected to be there if the zone is
1098 * detached.
1099 * State/command mismatches are caught earlier in verify_details().
1101 if (state == ZONE_STATE_CONFIGURED && cmd_num != CMD_ATTACH) {
1102 if (snprintf(rootpath, sizeof (rootpath), "%s/root", rpath) >=
1103 sizeof (rootpath)) {
1105 * TRANSLATION_NOTE
1106 * Zonepath is a literal that should not be translated.
1108 (void) fprintf(stderr,
1109 gettext("Zonepath %s is too long.\n"), rpath);
1110 return (Z_ERR);
1112 if ((res = stat(rootpath, &stbuf)) == 0) {
1113 if (zonecfg_detached(rpath)) {
1114 (void) fprintf(stderr,
1115 gettext("Cannot %s detached "
1116 "zone.\nUse attach or remove %s "
1117 "directory.\n"), cmd_to_str(cmd_num),
1118 rpath);
1119 return (Z_ERR);
1122 /* Not detached, check if it really looks ok. */
1124 if (!S_ISDIR(stbuf.st_mode)) {
1125 (void) fprintf(stderr, gettext("%s is not a "
1126 "directory.\n"), rootpath);
1127 return (Z_ERR);
1130 if (stbuf.st_uid != 0) {
1131 (void) fprintf(stderr, gettext("%s is not "
1132 "owned by root.\n"), rootpath);
1133 return (Z_ERR);
1136 if ((stbuf.st_mode & 0777) != 0755) {
1137 (void) fprintf(stderr, gettext("%s mode is not "
1138 "0755.\n"), rootpath);
1139 return (Z_ERR);
1144 return (err ? Z_ERR : Z_OK);
1147 static int
1148 invoke_brand_handler(int cmd_num, char *argv[])
1150 zone_dochandle_t handle;
1151 int err;
1153 if ((handle = zonecfg_init_handle()) == NULL) {
1154 zperror(cmd_to_str(cmd_num), B_TRUE);
1155 return (Z_ERR);
1157 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
1158 errno = err;
1159 zperror(cmd_to_str(cmd_num), B_TRUE);
1160 zonecfg_fini_handle(handle);
1161 return (Z_ERR);
1163 if (verify_brand(handle, cmd_num, argv) != Z_OK) {
1164 zonecfg_fini_handle(handle);
1165 return (Z_ERR);
1167 zonecfg_fini_handle(handle);
1168 return (Z_OK);
1171 static int
1172 ready_func(int argc, char *argv[])
1174 zone_cmd_arg_t zarg;
1175 int arg;
1177 if (zonecfg_in_alt_root()) {
1178 zerror(gettext("cannot ready zone in alternate root"));
1179 return (Z_ERR);
1182 optind = 0;
1183 if ((arg = getopt(argc, argv, "?")) != EOF) {
1184 switch (arg) {
1185 case '?':
1186 sub_usage(SHELP_READY, CMD_READY);
1187 return (optopt == '?' ? Z_OK : Z_USAGE);
1188 default:
1189 sub_usage(SHELP_READY, CMD_READY);
1190 return (Z_USAGE);
1193 if (argc > optind) {
1194 sub_usage(SHELP_READY, CMD_READY);
1195 return (Z_USAGE);
1197 if (sanity_check(target_zone, CMD_READY, B_FALSE, B_FALSE, B_FALSE)
1198 != Z_OK)
1199 return (Z_ERR);
1200 if (verify_details(CMD_READY, argv) != Z_OK)
1201 return (Z_ERR);
1203 zarg.cmd = Z_READY;
1204 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
1205 zerror(gettext("call to %s failed"), "zoneadmd");
1206 return (Z_ERR);
1208 return (Z_OK);
1211 static int
1212 boot_func(int argc, char *argv[])
1214 zone_cmd_arg_t zarg;
1215 boolean_t force = B_FALSE;
1216 int arg;
1218 if (zonecfg_in_alt_root()) {
1219 zerror(gettext("cannot boot zone in alternate root"));
1220 return (Z_ERR);
1223 zarg.bootbuf[0] = '\0';
1226 * The following getopt processes arguments to zone boot; that
1227 * is to say, the [here] portion of the argument string:
1229 * zoneadm -z myzone boot [here] -- -v -m verbose
1231 * Where [here] can either be nothing, -? (in which case we bail
1232 * and print usage), -f (a private option to indicate that the
1233 * boot operation should be 'forced'), or -s. Support for -s is
1234 * vestigal and obsolete, but is retained because it was a
1235 * documented interface and there are known consumers including
1236 * admin/install; the proper way to specify boot arguments like -s
1237 * is:
1239 * zoneadm -z myzone boot -- -s -v -m verbose.
1241 optind = 0;
1242 while ((arg = getopt(argc, argv, "?fs")) != EOF) {
1243 switch (arg) {
1244 case '?':
1245 sub_usage(SHELP_BOOT, CMD_BOOT);
1246 return (optopt == '?' ? Z_OK : Z_USAGE);
1247 case 's':
1248 (void) strlcpy(zarg.bootbuf, "-s",
1249 sizeof (zarg.bootbuf));
1250 break;
1251 case 'f':
1252 force = B_TRUE;
1253 break;
1254 default:
1255 sub_usage(SHELP_BOOT, CMD_BOOT);
1256 return (Z_USAGE);
1260 for (; optind < argc; optind++) {
1261 if (strlcat(zarg.bootbuf, argv[optind],
1262 sizeof (zarg.bootbuf)) >= sizeof (zarg.bootbuf)) {
1263 zerror(gettext("Boot argument list too long"));
1264 return (Z_ERR);
1266 if (optind < argc - 1)
1267 if (strlcat(zarg.bootbuf, " ", sizeof (zarg.bootbuf)) >=
1268 sizeof (zarg.bootbuf)) {
1269 zerror(gettext("Boot argument list too long"));
1270 return (Z_ERR);
1273 if (sanity_check(target_zone, CMD_BOOT, B_FALSE, B_FALSE, force)
1274 != Z_OK)
1275 return (Z_ERR);
1276 if (verify_details(CMD_BOOT, argv) != Z_OK)
1277 return (Z_ERR);
1278 zarg.cmd = force ? Z_FORCEBOOT : Z_BOOT;
1279 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
1280 zerror(gettext("call to %s failed"), "zoneadmd");
1281 return (Z_ERR);
1284 return (Z_OK);
1287 static void
1288 fake_up_local_zone(zoneid_t zid, zone_entry_t *zeptr)
1290 ssize_t result;
1291 uuid_t uuid;
1292 FILE *fp;
1293 ushort_t flags;
1295 (void) memset(zeptr, 0, sizeof (*zeptr));
1297 zeptr->zid = zid;
1300 * Since we're looking up our own (non-global) zone name,
1301 * we can be assured that it will succeed.
1303 result = getzonenamebyid(zid, zeptr->zname, sizeof (zeptr->zname));
1304 assert(result >= 0);
1305 if (zonecfg_is_scratch(zeptr->zname) &&
1306 (fp = zonecfg_open_scratch("", B_FALSE)) != NULL) {
1307 (void) zonecfg_reverse_scratch(fp, zeptr->zname, zeptr->zname,
1308 sizeof (zeptr->zname), NULL, 0);
1309 zonecfg_close_scratch(fp);
1312 (void) strlcpy(zeptr->zroot, "/", sizeof (zeptr->zroot));
1313 (void) zone_getattr(zid, ZONE_ATTR_BRAND, zeptr->zbrand,
1314 sizeof (zeptr->zbrand));
1316 zeptr->zstate_str = "running";
1317 if (zonecfg_get_uuid(zeptr->zname, uuid) == Z_OK &&
1318 !uuid_is_null(uuid))
1319 uuid_unparse(uuid, zeptr->zuuid);
1321 if (zone_getattr(zid, ZONE_ATTR_FLAGS, &flags, sizeof (flags)) < 0) {
1322 zperror2(zeptr->zname, gettext("could not get zone flags"));
1323 exit(Z_ERR);
1325 if (flags & ZF_NET_EXCL)
1326 zeptr->ziptype = ZS_EXCLUSIVE;
1327 else
1328 zeptr->ziptype = ZS_SHARED;
1331 static int
1332 list_func(int argc, char *argv[])
1334 zone_entry_t *zentp, zent;
1335 int arg, retv;
1336 boolean_t output = B_FALSE, verbose = B_FALSE, parsable = B_FALSE;
1337 zone_state_t min_state = ZONE_STATE_RUNNING;
1338 zoneid_t zone_id = getzoneid();
1340 if (target_zone == NULL) {
1341 /* all zones: default view to running but allow override */
1342 optind = 0;
1343 while ((arg = getopt(argc, argv, "?cipv")) != EOF) {
1344 switch (arg) {
1345 case '?':
1346 sub_usage(SHELP_LIST, CMD_LIST);
1347 return (optopt == '?' ? Z_OK : Z_USAGE);
1349 * The 'i' and 'c' options are not mutually
1350 * exclusive so if 'c' is given, then min_state
1351 * is set to 0 (ZONE_STATE_CONFIGURED) which is
1352 * the lowest possible state. If 'i' is given,
1353 * then min_state is set to be the lowest state
1354 * so far.
1356 case 'c':
1357 min_state = ZONE_STATE_CONFIGURED;
1358 break;
1359 case 'i':
1360 min_state = min(ZONE_STATE_INSTALLED,
1361 min_state);
1363 break;
1364 case 'p':
1365 parsable = B_TRUE;
1366 break;
1367 case 'v':
1368 verbose = B_TRUE;
1369 break;
1370 default:
1371 sub_usage(SHELP_LIST, CMD_LIST);
1372 return (Z_USAGE);
1375 if (parsable && verbose) {
1376 zerror(gettext("%s -p and -v are mutually exclusive."),
1377 cmd_to_str(CMD_LIST));
1378 return (Z_ERR);
1380 if (zone_id == GLOBAL_ZONEID) {
1381 retv = zone_print_list(min_state, verbose, parsable);
1382 } else {
1383 fake_up_local_zone(zone_id, &zent);
1384 retv = Z_OK;
1385 zone_print(&zent, verbose, parsable);
1387 return (retv);
1391 * Specific target zone: disallow -i/-c suboptions.
1393 optind = 0;
1394 while ((arg = getopt(argc, argv, "?pv")) != EOF) {
1395 switch (arg) {
1396 case '?':
1397 sub_usage(SHELP_LIST, CMD_LIST);
1398 return (optopt == '?' ? Z_OK : Z_USAGE);
1399 case 'p':
1400 parsable = B_TRUE;
1401 break;
1402 case 'v':
1403 verbose = B_TRUE;
1404 break;
1405 default:
1406 sub_usage(SHELP_LIST, CMD_LIST);
1407 return (Z_USAGE);
1410 if (parsable && verbose) {
1411 zerror(gettext("%s -p and -v are mutually exclusive."),
1412 cmd_to_str(CMD_LIST));
1413 return (Z_ERR);
1415 if (argc > optind) {
1416 sub_usage(SHELP_LIST, CMD_LIST);
1417 return (Z_USAGE);
1419 if (zone_id != GLOBAL_ZONEID) {
1420 fake_up_local_zone(zone_id, &zent);
1422 * main() will issue a Z_NO_ZONE error if it cannot get an
1423 * id for target_zone, which in a non-global zone should
1424 * happen for any zone name except `zonename`. Thus we
1425 * assert() that here but don't otherwise check.
1427 assert(strcmp(zent.zname, target_zone) == 0);
1428 zone_print(&zent, verbose, parsable);
1429 output = B_TRUE;
1430 } else if ((zentp = lookup_running_zone(target_zone)) != NULL) {
1431 zone_print(zentp, verbose, parsable);
1432 output = B_TRUE;
1433 } else if (lookup_zone_info(target_zone, ZONE_ID_UNDEFINED,
1434 &zent) == Z_OK) {
1435 zone_print(&zent, verbose, parsable);
1436 output = B_TRUE;
1440 * Invoke brand-specific handler. Note that we do this
1441 * only if we're in the global zone, and target_zone is specified
1442 * and it is not the global zone.
1444 if (zone_id == GLOBAL_ZONEID && target_zone != NULL &&
1445 strcmp(target_zone, GLOBAL_ZONENAME) != 0)
1446 if (invoke_brand_handler(CMD_LIST, argv) != Z_OK)
1447 return (Z_ERR);
1449 return (output ? Z_OK : Z_ERR);
1453 do_subproc(char *cmdbuf)
1455 void (*saveint)(int);
1456 void (*saveterm)(int);
1457 void (*savequit)(int);
1458 void (*savehup)(int);
1459 int pid, child, status;
1461 if ((child = vfork()) == 0) {
1462 (void) execl("/bin/sh", "sh", "-c", cmdbuf, NULL);
1465 if (child == -1)
1466 return (-1);
1468 saveint = sigset(SIGINT, SIG_IGN);
1469 saveterm = sigset(SIGTERM, SIG_IGN);
1470 savequit = sigset(SIGQUIT, SIG_IGN);
1471 savehup = sigset(SIGHUP, SIG_IGN);
1473 while ((pid = waitpid(child, &status, 0)) != child && pid != -1)
1476 (void) sigset(SIGINT, saveint);
1477 (void) sigset(SIGTERM, saveterm);
1478 (void) sigset(SIGQUIT, savequit);
1479 (void) sigset(SIGHUP, savehup);
1481 return (pid == -1 ? -1 : status);
1485 subproc_status(const char *cmd, int status, boolean_t verbose_failure)
1487 if (WIFEXITED(status)) {
1488 int exit_code = WEXITSTATUS(status);
1490 if ((verbose_failure) && (exit_code != ZONE_SUBPROC_OK))
1491 zerror(gettext("'%s' failed with exit code %d."), cmd,
1492 exit_code);
1494 return (exit_code);
1495 } else if (WIFSIGNALED(status)) {
1496 int signal = WTERMSIG(status);
1497 char sigstr[SIG2STR_MAX];
1499 if (sig2str(signal, sigstr) == 0) {
1500 zerror(gettext("'%s' terminated by signal SIG%s."), cmd,
1501 sigstr);
1502 } else {
1503 zerror(gettext("'%s' terminated by an unknown signal."),
1504 cmd);
1506 } else {
1507 zerror(gettext("'%s' failed for unknown reasons."), cmd);
1511 * Assume a subprocess that died due to a signal or an unknown error
1512 * should be considered an exit code of ZONE_SUBPROC_FATAL, as the
1513 * user will likely need to do some manual cleanup.
1515 return (ZONE_SUBPROC_FATAL);
1518 static int
1519 auth_check(char *user, char *zone, int cmd_num)
1521 char authname[MAXAUTHS];
1523 switch (cmd_num) {
1524 case CMD_LIST:
1525 case CMD_HELP:
1526 return (Z_OK);
1527 case SOURCE_ZONE:
1528 (void) strlcpy(authname, ZONE_CLONEFROM_AUTH, MAXAUTHS);
1529 break;
1530 case CMD_BOOT:
1531 case CMD_HALT:
1532 case CMD_READY:
1533 case CMD_SHUTDOWN:
1534 case CMD_REBOOT:
1535 case CMD_SYSBOOT:
1536 case CMD_VERIFY:
1537 case CMD_INSTALL:
1538 case CMD_UNINSTALL:
1539 case CMD_MOUNT:
1540 case CMD_UNMOUNT:
1541 case CMD_CLONE:
1542 case CMD_MOVE:
1543 case CMD_DETACH:
1544 case CMD_ATTACH:
1545 case CMD_MARK:
1546 case CMD_APPLY:
1547 default:
1548 (void) strlcpy(authname, ZONE_MANAGE_AUTH, MAXAUTHS);
1549 break;
1551 (void) strlcat(authname, KV_OBJECT, MAXAUTHS);
1552 (void) strlcat(authname, zone, MAXAUTHS);
1553 if (chkauthattr(authname, user) == 0) {
1554 return (Z_ERR);
1555 } else {
1557 * Some subcommands, e.g. install, run subcommands,
1558 * e.g. sysidcfg, that require a real uid of root,
1559 * so switch to root, here.
1561 if (setuid(0) == -1) {
1562 zperror(gettext("insufficient privilege"), B_TRUE);
1563 return (Z_ERR);
1565 return (Z_OK);
1570 * Various sanity checks; make sure:
1571 * 1. We're in the global zone.
1572 * 2. The calling user has sufficient privilege.
1573 * 3. The target zone is neither the global zone nor anything starting with
1574 * "SUNW".
1575 * 4a. If we're looking for a 'not running' (i.e., configured or installed)
1576 * zone, the name service knows about it.
1577 * 4b. For some operations which expect a zone not to be running, that it is
1578 * not already running (or ready).
1580 static int
1581 sanity_check(char *zone, int cmd_num, boolean_t running,
1582 boolean_t unsafe_when_running, boolean_t force)
1584 zone_entry_t *zent;
1585 priv_set_t *privset;
1586 zone_state_t state, min_state;
1587 char kernzone[ZONENAME_MAX];
1588 FILE *fp;
1590 if (getzoneid() != GLOBAL_ZONEID) {
1591 switch (cmd_num) {
1592 case CMD_HALT:
1593 zerror(gettext("use %s to %s this zone."), "halt(8)",
1594 cmd_to_str(cmd_num));
1595 break;
1596 case CMD_SHUTDOWN:
1597 zerror(gettext("use %s to %s this zone."),
1598 "shutdown(8)", cmd_to_str(cmd_num));
1599 break;
1600 case CMD_REBOOT:
1601 zerror(gettext("use %s to %s this zone."),
1602 "reboot(8)", cmd_to_str(cmd_num));
1603 break;
1604 default:
1605 zerror(gettext("must be in the global zone to %s a "
1606 "zone."), cmd_to_str(cmd_num));
1607 break;
1609 return (Z_ERR);
1612 if ((privset = priv_allocset()) == NULL) {
1613 zerror(gettext("%s failed"), "priv_allocset");
1614 return (Z_ERR);
1617 if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
1618 zerror(gettext("%s failed"), "getppriv");
1619 priv_freeset(privset);
1620 return (Z_ERR);
1623 if (priv_isfullset(privset) == B_FALSE) {
1624 zerror(gettext("only a privileged user may %s a zone."),
1625 cmd_to_str(cmd_num));
1626 priv_freeset(privset);
1627 return (Z_ERR);
1629 priv_freeset(privset);
1631 if (zone == NULL) {
1632 zerror(gettext("no zone specified"));
1633 return (Z_ERR);
1636 if (auth_check(username, zone, cmd_num) == Z_ERR) {
1637 zerror(gettext("User %s is not authorized to %s this zone."),
1638 username, cmd_to_str(cmd_num));
1639 return (Z_ERR);
1642 if (strcmp(zone, GLOBAL_ZONENAME) == 0) {
1643 zerror(gettext("%s operation is invalid for the global zone."),
1644 cmd_to_str(cmd_num));
1645 return (Z_ERR);
1648 if (strncmp(zone, "SUNW", 4) == 0) {
1649 zerror(gettext("%s operation is invalid for zones starting "
1650 "with SUNW."), cmd_to_str(cmd_num));
1651 return (Z_ERR);
1654 if (!zonecfg_in_alt_root()) {
1655 zent = lookup_running_zone(zone);
1656 } else if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
1657 zent = NULL;
1658 } else {
1659 if (zonecfg_find_scratch(fp, zone, zonecfg_get_root(),
1660 kernzone, sizeof (kernzone)) == 0)
1661 zent = lookup_running_zone(kernzone);
1662 else
1663 zent = NULL;
1664 zonecfg_close_scratch(fp);
1668 * Look up from the kernel for 'running' zones.
1670 if (running && !force) {
1671 if (zent == NULL) {
1672 zerror(gettext("not running"));
1673 return (Z_ERR);
1675 } else {
1676 int err;
1678 if (unsafe_when_running && zent != NULL) {
1679 /* check whether the zone is ready or running */
1680 if ((err = zone_get_state(zent->zname,
1681 &zent->zstate_num)) != Z_OK) {
1682 errno = err;
1683 zperror2(zent->zname,
1684 gettext("could not get state"));
1685 /* can't tell, so hedge */
1686 zent->zstate_str = "ready/running";
1687 } else {
1688 zent->zstate_str =
1689 zone_state_str(zent->zstate_num);
1691 zerror(gettext("%s operation is invalid for %s zones."),
1692 cmd_to_str(cmd_num), zent->zstate_str);
1693 return (Z_ERR);
1695 if ((err = zone_get_state(zone, &state)) != Z_OK) {
1696 errno = err;
1697 zperror2(zone, gettext("could not get state"));
1698 return (Z_ERR);
1700 switch (cmd_num) {
1701 case CMD_UNINSTALL:
1702 if (state == ZONE_STATE_CONFIGURED) {
1703 zerror(gettext("is already in state '%s'."),
1704 zone_state_str(ZONE_STATE_CONFIGURED));
1705 return (Z_ERR);
1707 break;
1708 case CMD_ATTACH:
1709 if (state == ZONE_STATE_INSTALLED) {
1710 zerror(gettext("is already %s."),
1711 zone_state_str(ZONE_STATE_INSTALLED));
1712 return (Z_ERR);
1713 } else if (state == ZONE_STATE_INCOMPLETE && !force) {
1714 zerror(gettext("zone is %s; %s required."),
1715 zone_state_str(ZONE_STATE_INCOMPLETE),
1716 cmd_to_str(CMD_UNINSTALL));
1717 return (Z_ERR);
1719 break;
1720 case CMD_CLONE:
1721 case CMD_INSTALL:
1722 if (state == ZONE_STATE_INSTALLED) {
1723 zerror(gettext("is already %s."),
1724 zone_state_str(ZONE_STATE_INSTALLED));
1725 return (Z_ERR);
1726 } else if (state == ZONE_STATE_INCOMPLETE) {
1727 zerror(gettext("zone is %s; %s required."),
1728 zone_state_str(ZONE_STATE_INCOMPLETE),
1729 cmd_to_str(CMD_UNINSTALL));
1730 return (Z_ERR);
1732 break;
1733 case CMD_DETACH:
1734 case CMD_MOVE:
1735 case CMD_READY:
1736 case CMD_BOOT:
1737 case CMD_MOUNT:
1738 case CMD_MARK:
1739 if ((cmd_num == CMD_BOOT || cmd_num == CMD_MOUNT) &&
1740 force)
1741 min_state = ZONE_STATE_INCOMPLETE;
1742 else if (cmd_num == CMD_MARK)
1743 min_state = ZONE_STATE_CONFIGURED;
1744 else
1745 min_state = ZONE_STATE_INSTALLED;
1747 if (state < min_state) {
1748 zerror(gettext("must be %s before %s."),
1749 zone_state_str(min_state),
1750 cmd_to_str(cmd_num));
1751 return (Z_ERR);
1753 break;
1754 case CMD_VERIFY:
1755 if (state == ZONE_STATE_INCOMPLETE) {
1756 zerror(gettext("zone is %s; %s required."),
1757 zone_state_str(ZONE_STATE_INCOMPLETE),
1758 cmd_to_str(CMD_UNINSTALL));
1759 return (Z_ERR);
1761 break;
1762 case CMD_UNMOUNT:
1763 if (state != ZONE_STATE_MOUNTED) {
1764 zerror(gettext("must be %s before %s."),
1765 zone_state_str(ZONE_STATE_MOUNTED),
1766 cmd_to_str(cmd_num));
1767 return (Z_ERR);
1769 break;
1770 case CMD_SYSBOOT:
1771 if (state != ZONE_STATE_INSTALLED) {
1772 zerror(gettext("%s operation is invalid for %s "
1773 "zones."), cmd_to_str(cmd_num),
1774 zone_state_str(state));
1775 return (Z_ERR);
1777 break;
1780 return (Z_OK);
1783 static int
1784 halt_func(int argc, char *argv[])
1786 zone_cmd_arg_t zarg;
1787 int arg;
1789 if (zonecfg_in_alt_root()) {
1790 zerror(gettext("cannot halt zone in alternate root"));
1791 return (Z_ERR);
1794 optind = 0;
1795 if ((arg = getopt(argc, argv, "?")) != EOF) {
1796 switch (arg) {
1797 case '?':
1798 sub_usage(SHELP_HALT, CMD_HALT);
1799 return (optopt == '?' ? Z_OK : Z_USAGE);
1800 default:
1801 sub_usage(SHELP_HALT, CMD_HALT);
1802 return (Z_USAGE);
1805 if (argc > optind) {
1806 sub_usage(SHELP_HALT, CMD_HALT);
1807 return (Z_USAGE);
1810 * zoneadmd should be the one to decide whether or not to proceed,
1811 * so even though it seems that the fourth parameter below should
1812 * perhaps be B_TRUE, it really shouldn't be.
1814 if (sanity_check(target_zone, CMD_HALT, B_FALSE, B_FALSE, B_FALSE)
1815 != Z_OK)
1816 return (Z_ERR);
1819 * Invoke brand-specific handler.
1821 if (invoke_brand_handler(CMD_HALT, argv) != Z_OK)
1822 return (Z_ERR);
1824 zarg.cmd = Z_HALT;
1825 return ((zonecfg_call_zoneadmd(target_zone, &zarg, locale,
1826 B_TRUE) == 0) ? Z_OK : Z_ERR);
1829 static int
1830 shutdown_func(int argc, char *argv[])
1832 zone_cmd_arg_t zarg;
1833 int arg;
1834 boolean_t reboot = B_FALSE;
1836 zarg.cmd = Z_SHUTDOWN;
1838 if (zonecfg_in_alt_root()) {
1839 zerror(gettext("cannot shut down zone in alternate root"));
1840 return (Z_ERR);
1843 optind = 0;
1844 while ((arg = getopt(argc, argv, "?r")) != EOF) {
1845 switch (arg) {
1846 case '?':
1847 sub_usage(SHELP_SHUTDOWN, CMD_SHUTDOWN);
1848 return (optopt == '?' ? Z_OK : Z_USAGE);
1849 case 'r':
1850 reboot = B_TRUE;
1851 break;
1852 default:
1853 sub_usage(SHELP_SHUTDOWN, CMD_SHUTDOWN);
1854 return (Z_USAGE);
1858 zarg.bootbuf[0] = '\0';
1859 for (; optind < argc; optind++) {
1860 if (strlcat(zarg.bootbuf, argv[optind],
1861 sizeof (zarg.bootbuf)) >= sizeof (zarg.bootbuf)) {
1862 zerror(gettext("Boot argument list too long"));
1863 return (Z_ERR);
1865 if (optind < argc - 1)
1866 if (strlcat(zarg.bootbuf, " ", sizeof (zarg.bootbuf)) >=
1867 sizeof (zarg.bootbuf)) {
1868 zerror(gettext("Boot argument list too long"));
1869 return (Z_ERR);
1874 * zoneadmd should be the one to decide whether or not to proceed,
1875 * so even though it seems that the third parameter below should
1876 * perhaps be B_TRUE, it really shouldn't be.
1878 if (sanity_check(target_zone, CMD_SHUTDOWN, B_TRUE, B_FALSE, B_FALSE)
1879 != Z_OK)
1880 return (Z_ERR);
1882 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != Z_OK)
1883 return (Z_ERR);
1885 if (reboot) {
1886 if (sanity_check(target_zone, CMD_BOOT, B_FALSE, B_FALSE,
1887 B_FALSE) != Z_OK)
1888 return (Z_ERR);
1890 zarg.cmd = Z_BOOT;
1891 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale,
1892 B_TRUE) != Z_OK)
1893 return (Z_ERR);
1895 return (Z_OK);
1898 static int
1899 reboot_func(int argc, char *argv[])
1901 zone_cmd_arg_t zarg;
1902 int arg;
1904 if (zonecfg_in_alt_root()) {
1905 zerror(gettext("cannot reboot zone in alternate root"));
1906 return (Z_ERR);
1909 optind = 0;
1910 if ((arg = getopt(argc, argv, "?")) != EOF) {
1911 switch (arg) {
1912 case '?':
1913 sub_usage(SHELP_REBOOT, CMD_REBOOT);
1914 return (optopt == '?' ? Z_OK : Z_USAGE);
1915 default:
1916 sub_usage(SHELP_REBOOT, CMD_REBOOT);
1917 return (Z_USAGE);
1921 zarg.bootbuf[0] = '\0';
1922 for (; optind < argc; optind++) {
1923 if (strlcat(zarg.bootbuf, argv[optind],
1924 sizeof (zarg.bootbuf)) >= sizeof (zarg.bootbuf)) {
1925 zerror(gettext("Boot argument list too long"));
1926 return (Z_ERR);
1928 if (optind < argc - 1)
1929 if (strlcat(zarg.bootbuf, " ", sizeof (zarg.bootbuf)) >=
1930 sizeof (zarg.bootbuf)) {
1931 zerror(gettext("Boot argument list too long"));
1932 return (Z_ERR);
1938 * zoneadmd should be the one to decide whether or not to proceed,
1939 * so even though it seems that the fourth parameter below should
1940 * perhaps be B_TRUE, it really shouldn't be.
1942 if (sanity_check(target_zone, CMD_REBOOT, B_TRUE, B_FALSE, B_FALSE)
1943 != Z_OK)
1944 return (Z_ERR);
1945 if (verify_details(CMD_REBOOT, argv) != Z_OK)
1946 return (Z_ERR);
1948 zarg.cmd = Z_REBOOT;
1949 return ((zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) == 0)
1950 ? Z_OK : Z_ERR);
1953 static int
1954 get_hook(brand_handle_t bh, char *cmd, size_t len, int (*bp)(brand_handle_t,
1955 const char *, const char *, char *, size_t), char *zonename, char *zonepath)
1957 if (strlcpy(cmd, EXEC_PREFIX, len) >= len)
1958 return (Z_ERR);
1960 if (bp(bh, zonename, zonepath, cmd + EXEC_LEN, len - EXEC_LEN) != 0)
1961 return (Z_ERR);
1963 if (strlen(cmd) <= EXEC_LEN)
1964 cmd[0] = '\0';
1966 return (Z_OK);
1969 static int
1970 verify_brand(zone_dochandle_t handle, int cmd_num, char *argv[])
1972 char cmdbuf[MAXPATHLEN];
1973 int err;
1974 char zonepath[MAXPATHLEN];
1975 brand_handle_t bh = NULL;
1976 int status, i;
1979 * Fetch the verify command from the brand configuration.
1980 * "exec" the command so that the returned status is that of
1981 * the command and not the shell.
1983 if (handle == NULL) {
1984 (void) strlcpy(zonepath, "-", sizeof (zonepath));
1985 } else if ((err = zonecfg_get_zonepath(handle, zonepath,
1986 sizeof (zonepath))) != Z_OK) {
1987 errno = err;
1988 zperror(cmd_to_str(cmd_num), B_TRUE);
1989 return (Z_ERR);
1991 if ((bh = brand_open(target_brand)) == NULL) {
1992 zerror(gettext("missing or invalid brand"));
1993 return (Z_ERR);
1997 * If the brand has its own verification routine, execute it now.
1998 * The verification routine validates the intended zoneadm
1999 * operation for the specific brand. The zoneadm subcommand and
2000 * all its arguments are passed to the routine.
2002 err = get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_verify_adm,
2003 target_zone, zonepath);
2004 brand_close(bh);
2005 if (err != Z_OK)
2006 return (Z_BRAND_ERROR);
2007 if (cmdbuf[0] == '\0')
2008 return (Z_OK);
2010 if (strlcat(cmdbuf, cmd_to_str(cmd_num),
2011 sizeof (cmdbuf)) >= sizeof (cmdbuf))
2012 return (Z_ERR);
2014 /* Build the argv string */
2015 i = 0;
2016 while (argv[i] != NULL) {
2017 if ((strlcat(cmdbuf, " ",
2018 sizeof (cmdbuf)) >= sizeof (cmdbuf)) ||
2019 (strlcat(cmdbuf, argv[i++],
2020 sizeof (cmdbuf)) >= sizeof (cmdbuf)))
2021 return (Z_ERR);
2024 status = do_subproc(cmdbuf);
2025 err = subproc_status(gettext("brand-specific verification"),
2026 status, B_FALSE);
2028 return ((err == ZONE_SUBPROC_OK) ? Z_OK : Z_BRAND_ERROR);
2031 static int
2032 verify_rctls(zone_dochandle_t handle)
2034 struct zone_rctltab rctltab;
2035 size_t rbs = rctlblk_size();
2036 rctlblk_t *rctlblk;
2037 int error = Z_INVAL;
2039 if ((rctlblk = malloc(rbs)) == NULL) {
2040 zerror(gettext("failed to allocate %lu bytes: %s"), rbs,
2041 strerror(errno));
2042 return (Z_NOMEM);
2045 if (zonecfg_setrctlent(handle) != Z_OK) {
2046 zerror(gettext("zonecfg_setrctlent failed"));
2047 free(rctlblk);
2048 return (error);
2051 rctltab.zone_rctl_valptr = NULL;
2052 while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2053 struct zone_rctlvaltab *rctlval;
2054 const char *name = rctltab.zone_rctl_name;
2056 if (!zonecfg_is_rctl(name)) {
2057 zerror(gettext("WARNING: Ignoring unrecognized rctl "
2058 "'%s'."), name);
2059 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2060 rctltab.zone_rctl_valptr = NULL;
2061 continue;
2064 for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2065 rctlval = rctlval->zone_rctlval_next) {
2066 if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2067 != Z_OK) {
2068 zerror(gettext("invalid rctl value: "
2069 "(priv=%s,limit=%s,action%s)"),
2070 rctlval->zone_rctlval_priv,
2071 rctlval->zone_rctlval_limit,
2072 rctlval->zone_rctlval_action);
2073 goto out;
2075 if (!zonecfg_valid_rctl(name, rctlblk)) {
2076 zerror(gettext("(priv=%s,limit=%s,action=%s) "
2077 "is not a valid value for rctl '%s'"),
2078 rctlval->zone_rctlval_priv,
2079 rctlval->zone_rctlval_limit,
2080 rctlval->zone_rctlval_action,
2081 name);
2082 goto out;
2085 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2087 rctltab.zone_rctl_valptr = NULL;
2088 error = Z_OK;
2089 out:
2090 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2091 (void) zonecfg_endrctlent(handle);
2092 free(rctlblk);
2093 return (error);
2096 static int
2097 verify_pool(zone_dochandle_t handle)
2099 char poolname[MAXPATHLEN];
2100 pool_conf_t *poolconf;
2101 pool_t *pool;
2102 int status;
2103 int error;
2106 * This ends up being very similar to the check done in zoneadmd.
2108 error = zonecfg_get_pool(handle, poolname, sizeof (poolname));
2109 if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
2111 * No pool specified.
2113 return (0);
2115 if (error != Z_OK) {
2116 zperror(gettext("Unable to retrieve pool name from "
2117 "configuration"), B_TRUE);
2118 return (error);
2121 * Don't do anything if pools aren't enabled.
2123 if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
2124 zerror(gettext("WARNING: pools facility not active; "
2125 "zone will not be bound to pool '%s'."), poolname);
2126 return (Z_OK);
2129 * Try to provide a sane error message if the requested pool doesn't
2130 * exist. It isn't clear that pools-related failures should
2131 * necessarily translate to a failure to verify the zone configuration,
2132 * hence they are not considered errors.
2134 if ((poolconf = pool_conf_alloc()) == NULL) {
2135 zerror(gettext("WARNING: pool_conf_alloc failed; "
2136 "using default pool"));
2137 return (Z_OK);
2139 if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
2140 PO_SUCCESS) {
2141 zerror(gettext("WARNING: pool_conf_open failed; "
2142 "using default pool"));
2143 pool_conf_free(poolconf);
2144 return (Z_OK);
2146 pool = pool_get_pool(poolconf, poolname);
2147 (void) pool_conf_close(poolconf);
2148 pool_conf_free(poolconf);
2149 if (pool == NULL) {
2150 zerror(gettext("WARNING: pool '%s' not found. "
2151 "using default pool"), poolname);
2154 return (Z_OK);
2158 * Verify that the special device/file system exists and is valid.
2160 static int
2161 verify_fs_special(struct zone_fstab *fstab)
2163 struct stat st;
2166 * This validation is really intended for standard zone administration.
2167 * If we are in a mini-root or some other upgrade situation where
2168 * we are using the scratch zone, just by-pass this.
2170 if (zonecfg_in_alt_root())
2171 return (Z_OK);
2173 if (strcmp(fstab->zone_fs_type, MNTTYPE_ZFS) == 0)
2174 return (verify_fs_zfs(fstab));
2176 if (stat(fstab->zone_fs_special, &st) != 0) {
2177 (void) fprintf(stderr, gettext("could not verify fs "
2178 "%s: could not access %s: %s\n"), fstab->zone_fs_dir,
2179 fstab->zone_fs_special, strerror(errno));
2180 return (Z_ERR);
2183 if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
2185 * TRANSLATION_NOTE
2186 * fs and NFS are literals that should
2187 * not be translated.
2189 (void) fprintf(stderr, gettext("cannot verify "
2190 "fs %s: NFS mounted file system.\n"
2191 "\tA local file system must be used.\n"),
2192 fstab->zone_fs_special);
2193 return (Z_ERR);
2196 return (Z_OK);
2199 static int
2200 isregfile(const char *path)
2202 struct stat st;
2204 if (stat(path, &st) == -1)
2205 return (-1);
2207 return (S_ISREG(st.st_mode));
2210 static int
2211 verify_filesystems(zone_dochandle_t handle)
2213 int return_code = Z_OK;
2214 struct zone_fstab fstab;
2215 char cmdbuf[MAXPATHLEN];
2216 struct stat st;
2219 * Since the actual mount point is not known until the dependent mounts
2220 * are performed, we don't attempt any path validation here: that will
2221 * happen later when zoneadmd actually does the mounts.
2223 if (zonecfg_setfsent(handle) != Z_OK) {
2224 (void) fprintf(stderr, gettext("could not verify file systems: "
2225 "unable to enumerate mounts\n"));
2226 return (Z_ERR);
2228 while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
2229 if (!zonecfg_valid_fs_type(fstab.zone_fs_type)) {
2230 (void) fprintf(stderr, gettext("cannot verify fs %s: "
2231 "type %s is not allowed.\n"), fstab.zone_fs_dir,
2232 fstab.zone_fs_type);
2233 return_code = Z_ERR;
2234 goto next_fs;
2237 * Verify /usr/lib/fs/<fstype>/mount exists.
2239 if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount",
2240 fstab.zone_fs_type) > sizeof (cmdbuf)) {
2241 (void) fprintf(stderr, gettext("cannot verify fs %s: "
2242 "type %s is too long.\n"), fstab.zone_fs_dir,
2243 fstab.zone_fs_type);
2244 return_code = Z_ERR;
2245 goto next_fs;
2247 if (stat(cmdbuf, &st) != 0) {
2248 (void) fprintf(stderr, gettext("could not verify fs "
2249 "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2250 cmdbuf, strerror(errno));
2251 return_code = Z_ERR;
2252 goto next_fs;
2254 if (!S_ISREG(st.st_mode)) {
2255 (void) fprintf(stderr, gettext("could not verify fs "
2256 "%s: %s is not a regular file\n"),
2257 fstab.zone_fs_dir, cmdbuf);
2258 return_code = Z_ERR;
2259 goto next_fs;
2262 * If zone_fs_raw is set, verify that there's an fsck
2263 * binary for it. If zone_fs_raw is not set, and it's
2264 * not a regular file (lofi mount), and there's an fsck
2265 * binary for it, complain.
2267 if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck",
2268 fstab.zone_fs_type) > sizeof (cmdbuf)) {
2269 (void) fprintf(stderr, gettext("cannot verify fs %s: "
2270 "type %s is too long.\n"), fstab.zone_fs_dir,
2271 fstab.zone_fs_type);
2272 return_code = Z_ERR;
2273 goto next_fs;
2275 if (fstab.zone_fs_raw[0] != '\0' &&
2276 (stat(cmdbuf, &st) != 0 || !S_ISREG(st.st_mode))) {
2277 (void) fprintf(stderr, gettext("cannot verify fs %s: "
2278 "'raw' device specified but "
2279 "no fsck executable exists for %s\n"),
2280 fstab.zone_fs_dir, fstab.zone_fs_type);
2281 return_code = Z_ERR;
2282 goto next_fs;
2283 } else if (fstab.zone_fs_raw[0] == '\0' &&
2284 stat(cmdbuf, &st) == 0 &&
2285 isregfile(fstab.zone_fs_special) != 1) {
2286 (void) fprintf(stderr, gettext("could not verify fs "
2287 "%s: must specify 'raw' device for %s "
2288 "file systems\n"),
2289 fstab.zone_fs_dir, fstab.zone_fs_type);
2290 return_code = Z_ERR;
2291 goto next_fs;
2294 /* Verify fs_special. */
2295 if ((return_code = verify_fs_special(&fstab)) != Z_OK)
2296 goto next_fs;
2298 /* Verify fs_raw. */
2299 if (fstab.zone_fs_raw[0] != '\0' &&
2300 stat(fstab.zone_fs_raw, &st) != 0) {
2302 * TRANSLATION_NOTE
2303 * fs is a literal that should not be translated.
2305 (void) fprintf(stderr, gettext("could not verify fs "
2306 "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2307 fstab.zone_fs_raw, strerror(errno));
2308 return_code = Z_ERR;
2309 goto next_fs;
2311 next_fs:
2312 zonecfg_free_fs_option_list(fstab.zone_fs_options);
2314 (void) zonecfg_endfsent(handle);
2316 return (return_code);
2319 static int
2320 verify_limitpriv(zone_dochandle_t handle)
2322 char *privname = NULL;
2323 int err;
2324 priv_set_t *privs;
2326 if ((privs = priv_allocset()) == NULL) {
2327 zperror(gettext("failed to allocate privilege set"), B_FALSE);
2328 return (Z_NOMEM);
2330 err = zonecfg_get_privset(handle, privs, &privname);
2331 switch (err) {
2332 case Z_OK:
2333 break;
2334 case Z_PRIV_PROHIBITED:
2335 (void) fprintf(stderr, gettext("privilege \"%s\" is not "
2336 "permitted within the zone's privilege set\n"), privname);
2337 break;
2338 case Z_PRIV_REQUIRED:
2339 (void) fprintf(stderr, gettext("required privilege \"%s\" is "
2340 "missing from the zone's privilege set\n"), privname);
2341 break;
2342 case Z_PRIV_UNKNOWN:
2343 (void) fprintf(stderr, gettext("unknown privilege \"%s\" "
2344 "specified in the zone's privilege set\n"), privname);
2345 break;
2346 default:
2347 zperror(
2348 gettext("failed to determine the zone's privilege set"),
2349 B_TRUE);
2350 break;
2352 free(privname);
2353 priv_freeset(privs);
2354 return (err);
2357 static void
2358 free_local_netifs(int if_cnt, struct net_if **if_list)
2360 int i;
2362 for (i = 0; i < if_cnt; i++) {
2363 free(if_list[i]->name);
2364 free(if_list[i]);
2366 free(if_list);
2370 * Get a list of the network interfaces, along with their address families,
2371 * that are plumbed in the global zone. See if_tcp(7p) for a description
2372 * of the ioctls used here.
2374 static int
2375 get_local_netifs(int *if_cnt, struct net_if ***if_list)
2377 int s;
2378 int i;
2379 int res = Z_OK;
2380 int space_needed;
2381 int cnt = 0;
2382 struct lifnum if_num;
2383 struct lifconf if_conf;
2384 struct lifreq *if_reqp;
2385 char *if_buf;
2386 struct net_if **local_ifs = NULL;
2388 *if_cnt = 0;
2389 *if_list = NULL;
2391 if ((s = socket(SOCKET_AF(AF_INET), SOCK_DGRAM, 0)) < 0)
2392 return (Z_ERR);
2395 * Come back here in the unlikely event that the number of interfaces
2396 * increases between the time we get the count and the time we do the
2397 * SIOCGLIFCONF ioctl.
2399 retry:
2400 /* Get the number of interfaces. */
2401 if_num.lifn_family = AF_UNSPEC;
2402 if_num.lifn_flags = LIFC_NOXMIT;
2403 if (ioctl(s, SIOCGLIFNUM, &if_num) < 0) {
2404 (void) close(s);
2405 return (Z_ERR);
2408 /* Get the interface configuration list. */
2409 space_needed = if_num.lifn_count * sizeof (struct lifreq);
2410 if ((if_buf = malloc(space_needed)) == NULL) {
2411 (void) close(s);
2412 return (Z_ERR);
2414 if_conf.lifc_family = AF_UNSPEC;
2415 if_conf.lifc_flags = LIFC_NOXMIT;
2416 if_conf.lifc_len = space_needed;
2417 if_conf.lifc_buf = if_buf;
2418 if (ioctl(s, SIOCGLIFCONF, &if_conf) < 0) {
2419 free(if_buf);
2421 * SIOCGLIFCONF returns EINVAL if the buffer we passed in is
2422 * too small. In this case go back and get the new if cnt.
2424 if (errno == EINVAL)
2425 goto retry;
2427 (void) close(s);
2428 return (Z_ERR);
2430 (void) close(s);
2432 /* Get the name and address family for each interface. */
2433 if_reqp = if_conf.lifc_req;
2434 for (i = 0; i < (if_conf.lifc_len / sizeof (struct lifreq)); i++) {
2435 struct net_if **p;
2436 struct lifreq req;
2438 if (strcmp(LOOPBACK_IF, if_reqp->lifr_name) == 0) {
2439 if_reqp++;
2440 continue;
2443 if ((s = socket(SOCKET_AF(if_reqp->lifr_addr.ss_family),
2444 SOCK_DGRAM, 0)) == -1) {
2445 res = Z_ERR;
2446 break;
2449 (void) strncpy(req.lifr_name, if_reqp->lifr_name,
2450 sizeof (req.lifr_name));
2451 if (ioctl(s, SIOCGLIFADDR, &req) < 0) {
2452 (void) close(s);
2453 if_reqp++;
2454 continue;
2457 if ((p = reallocarray(local_ifs, cnt + 1,
2458 sizeof (struct net_if *))) == NULL) {
2459 res = Z_ERR;
2460 break;
2462 local_ifs = p;
2464 if ((local_ifs[cnt] = malloc(sizeof (struct net_if))) == NULL) {
2465 res = Z_ERR;
2466 break;
2469 if ((local_ifs[cnt]->name = strdup(if_reqp->lifr_name))
2470 == NULL) {
2471 free(local_ifs[cnt]);
2472 res = Z_ERR;
2473 break;
2475 local_ifs[cnt]->af = req.lifr_addr.ss_family;
2476 cnt++;
2478 (void) close(s);
2479 if_reqp++;
2482 free(if_buf);
2484 if (res != Z_OK) {
2485 free_local_netifs(cnt, local_ifs);
2486 } else {
2487 *if_cnt = cnt;
2488 *if_list = local_ifs;
2491 return (res);
2494 static char *
2495 af2str(int af)
2497 switch (af) {
2498 case AF_INET:
2499 return ("IPv4");
2500 case AF_INET6:
2501 return ("IPv6");
2502 default:
2503 return ("Unknown");
2508 * Cross check the network interface name and address family with the
2509 * interfaces that are set up in the global zone so that we can print the
2510 * appropriate error message.
2512 static void
2513 print_net_err(char *phys, char *addr, int af, char *msg)
2515 int i;
2516 int local_if_cnt = 0;
2517 struct net_if **local_ifs = NULL;
2518 boolean_t found_if = B_FALSE;
2519 boolean_t found_af = B_FALSE;
2521 if (get_local_netifs(&local_if_cnt, &local_ifs) != Z_OK) {
2522 (void) fprintf(stderr,
2523 gettext("could not verify %s %s=%s %s=%s\n\t%s\n"),
2524 "net", "address", addr, "physical", phys, msg);
2525 return;
2528 for (i = 0; i < local_if_cnt; i++) {
2529 if (strcmp(phys, local_ifs[i]->name) == 0) {
2530 found_if = B_TRUE;
2531 if (af == local_ifs[i]->af) {
2532 found_af = B_TRUE;
2533 break;
2538 free_local_netifs(local_if_cnt, local_ifs);
2540 if (!found_if) {
2541 (void) fprintf(stderr,
2542 gettext("could not verify %s %s=%s\n\t"
2543 "network interface %s is not plumbed in the global zone\n"),
2544 "net", "physical", phys, phys);
2545 return;
2549 * Print this error if we were unable to find the address family
2550 * for this interface. If the af variable is not initialized to
2551 * to something meaningful by the caller (not AF_UNSPEC) then we
2552 * also skip this message since it wouldn't be informative.
2554 if (!found_af && af != AF_UNSPEC) {
2555 (void) fprintf(stderr,
2556 gettext("could not verify %s %s=%s %s=%s\n\tthe %s address "
2557 "family is not configured on this network interface in "
2558 "the\n\tglobal zone\n"),
2559 "net", "address", addr, "physical", phys, af2str(af));
2560 return;
2563 (void) fprintf(stderr,
2564 gettext("could not verify %s %s=%s %s=%s\n\t%s\n"),
2565 "net", "address", addr, "physical", phys, msg);
2568 static int
2569 verify_handle(int cmd_num, zone_dochandle_t handle, char *argv[])
2571 struct zone_nwiftab nwiftab;
2572 int return_code = Z_OK;
2573 int err;
2574 boolean_t in_alt_root;
2575 zone_iptype_t iptype;
2576 dladm_handle_t dh;
2577 dladm_status_t status;
2578 datalink_id_t linkid;
2579 char errmsg[DLADM_STRSIZE];
2581 in_alt_root = zonecfg_in_alt_root();
2582 if (in_alt_root)
2583 goto no_net;
2585 if ((err = zonecfg_get_iptype(handle, &iptype)) != Z_OK) {
2586 errno = err;
2587 zperror(cmd_to_str(cmd_num), B_TRUE);
2588 zonecfg_fini_handle(handle);
2589 return (Z_ERR);
2591 if ((err = zonecfg_setnwifent(handle)) != Z_OK) {
2592 errno = err;
2593 zperror(cmd_to_str(cmd_num), B_TRUE);
2594 zonecfg_fini_handle(handle);
2595 return (Z_ERR);
2597 while (zonecfg_getnwifent(handle, &nwiftab) == Z_OK) {
2598 struct lifreq lifr;
2599 sa_family_t af = AF_UNSPEC;
2600 char dl_owner_zname[ZONENAME_MAX];
2601 zoneid_t dl_owner_zid;
2602 zoneid_t target_zid;
2603 int res;
2605 /* skip any loopback interfaces */
2606 if (strcmp(nwiftab.zone_nwif_physical, "lo0") == 0)
2607 continue;
2608 switch (iptype) {
2609 case ZS_SHARED:
2610 if ((res = zonecfg_valid_net_address(
2611 nwiftab.zone_nwif_address, &lifr)) != Z_OK) {
2612 print_net_err(nwiftab.zone_nwif_physical,
2613 nwiftab.zone_nwif_address, af,
2614 zonecfg_strerror(res));
2615 return_code = Z_ERR;
2616 continue;
2618 af = lifr.lifr_addr.ss_family;
2619 if (!zonecfg_ifname_exists(af,
2620 nwiftab.zone_nwif_physical)) {
2622 * The interface failed to come up. We continue
2623 * on anyway for the sake of consistency: a
2624 * zone is not shut down if the interface fails
2625 * any time after boot, nor does the global zone
2626 * fail to boot if an interface fails.
2628 (void) fprintf(stderr,
2629 gettext("WARNING: skipping network "
2630 "interface '%s' which may not be "
2631 "present/plumbed in the global "
2632 "zone.\n"),
2633 nwiftab.zone_nwif_physical);
2635 break;
2636 case ZS_EXCLUSIVE:
2637 /* Warning if it exists for either IPv4 or IPv6 */
2639 if (zonecfg_ifname_exists(AF_INET,
2640 nwiftab.zone_nwif_physical) ||
2641 zonecfg_ifname_exists(AF_INET6,
2642 nwiftab.zone_nwif_physical)) {
2643 (void) fprintf(stderr,
2644 gettext("WARNING: skipping network "
2645 "interface '%s' which is used in the "
2646 "global zone.\n"),
2647 nwiftab.zone_nwif_physical);
2648 break;
2652 * Verify that the datalink exists and that it isn't
2653 * already assigned to a zone.
2655 if ((status = dladm_open(&dh)) == DLADM_STATUS_OK) {
2656 status = dladm_name2info(dh,
2657 nwiftab.zone_nwif_physical, &linkid, NULL,
2658 NULL, NULL);
2659 dladm_close(dh);
2661 if (status != DLADM_STATUS_OK) {
2662 (void) fprintf(stderr,
2663 gettext("WARNING: skipping network "
2664 "interface '%s': %s\n"),
2665 nwiftab.zone_nwif_physical,
2666 dladm_status2str(status, errmsg));
2667 break;
2669 dl_owner_zid = ALL_ZONES;
2670 if (zone_check_datalink(&dl_owner_zid, linkid) != 0)
2671 break;
2674 * If the zone being verified is
2675 * running and owns the interface
2677 target_zid = getzoneidbyname(target_zone);
2678 if (target_zid == dl_owner_zid)
2679 break;
2681 /* Zone id match failed, use name to check */
2682 if (getzonenamebyid(dl_owner_zid, dl_owner_zname,
2683 ZONENAME_MAX) < 0) {
2684 /* No name, show ID instead */
2685 (void) snprintf(dl_owner_zname, ZONENAME_MAX,
2686 "<%d>", dl_owner_zid);
2687 } else if (strcmp(dl_owner_zname, target_zone) == 0)
2688 break;
2691 * Note here we only report a warning that
2692 * the interface is already in use by another
2693 * running zone, and the verify process just
2694 * goes on, if the interface is still in use
2695 * when this zone really boots up, zoneadmd
2696 * will find it. If the name of the zone which
2697 * owns this interface cannot be determined,
2698 * then it is not possible to determine if there
2699 * is a conflict so just report it as a warning.
2701 (void) fprintf(stderr,
2702 gettext("WARNING: skipping network interface "
2703 "'%s' which is used by the non-global zone "
2704 "'%s'.\n"), nwiftab.zone_nwif_physical,
2705 dl_owner_zname);
2706 break;
2709 (void) zonecfg_endnwifent(handle);
2710 no_net:
2712 /* verify that lofs has not been excluded from the kernel */
2713 if (!(cmd_num == CMD_DETACH || cmd_num == CMD_ATTACH ||
2714 cmd_num == CMD_MOVE || cmd_num == CMD_CLONE) &&
2715 modctl(MODLOAD, 1, "fs/lofs", NULL) != 0) {
2716 if (errno == ENXIO)
2717 (void) fprintf(stderr, gettext("could not verify "
2718 "lofs(7FS): possibly excluded in /etc/system\n"));
2719 else
2720 (void) fprintf(stderr, gettext("could not verify "
2721 "lofs(7FS): %s\n"), strerror(errno));
2722 return_code = Z_ERR;
2725 if (verify_filesystems(handle) != Z_OK)
2726 return_code = Z_ERR;
2727 if (!in_alt_root && verify_rctls(handle) != Z_OK)
2728 return_code = Z_ERR;
2729 if (!in_alt_root && verify_pool(handle) != Z_OK)
2730 return_code = Z_ERR;
2731 if (!in_alt_root && verify_brand(handle, cmd_num, argv) != Z_OK)
2732 return_code = Z_ERR;
2733 if (!in_alt_root && verify_datasets(handle) != Z_OK)
2734 return_code = Z_ERR;
2737 * As the "mount" command is used for patching/upgrading of zones
2738 * or other maintenance processes, the zone's privilege set is not
2739 * checked in this case. Instead, the default, safe set of
2740 * privileges will be used when this zone is created in the
2741 * kernel.
2743 if (!in_alt_root && cmd_num != CMD_MOUNT &&
2744 verify_limitpriv(handle) != Z_OK)
2745 return_code = Z_ERR;
2747 return (return_code);
2750 static int
2751 verify_details(int cmd_num, char *argv[])
2753 zone_dochandle_t handle;
2754 char zonepath[MAXPATHLEN], checkpath[MAXPATHLEN];
2755 int return_code = Z_OK;
2756 int err;
2758 if ((handle = zonecfg_init_handle()) == NULL) {
2759 zperror(cmd_to_str(cmd_num), B_TRUE);
2760 return (Z_ERR);
2762 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
2763 errno = err;
2764 zperror(cmd_to_str(cmd_num), B_TRUE);
2765 zonecfg_fini_handle(handle);
2766 return (Z_ERR);
2768 if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
2769 Z_OK) {
2770 errno = err;
2771 zperror(cmd_to_str(cmd_num), B_TRUE);
2772 zonecfg_fini_handle(handle);
2773 return (Z_ERR);
2776 * zonecfg_get_zonepath() gets its data from the XML repository.
2777 * Verify this against the index file, which is checked first by
2778 * zone_get_zonepath(). If they don't match, bail out.
2780 if ((err = zone_get_zonepath(target_zone, checkpath,
2781 sizeof (checkpath))) != Z_OK) {
2782 errno = err;
2783 zperror2(target_zone, gettext("could not get zone path"));
2784 zonecfg_fini_handle(handle);
2785 return (Z_ERR);
2787 if (strcmp(zonepath, checkpath) != 0) {
2789 * TRANSLATION_NOTE
2790 * XML and zonepath are literals that should not be translated.
2792 (void) fprintf(stderr, gettext("The XML repository has "
2793 "zonepath '%s',\nbut the index file has zonepath '%s'.\n"
2794 "These must match, so fix the incorrect entry.\n"),
2795 zonepath, checkpath);
2796 zonecfg_fini_handle(handle);
2797 return (Z_ERR);
2799 if (cmd_num != CMD_ATTACH &&
2800 validate_zonepath(zonepath, cmd_num) != Z_OK) {
2801 (void) fprintf(stderr, gettext("could not verify zonepath %s "
2802 "because of the above errors.\n"), zonepath);
2803 return_code = Z_ERR;
2806 if (verify_handle(cmd_num, handle, argv) != Z_OK)
2807 return_code = Z_ERR;
2809 zonecfg_fini_handle(handle);
2810 if (return_code == Z_ERR)
2811 (void) fprintf(stderr,
2812 gettext("%s: zone %s failed to verify\n"),
2813 execname, target_zone);
2814 return (return_code);
2817 static int
2818 verify_func(int argc, char *argv[])
2820 int arg;
2822 optind = 0;
2823 if ((arg = getopt(argc, argv, "?")) != EOF) {
2824 switch (arg) {
2825 case '?':
2826 sub_usage(SHELP_VERIFY, CMD_VERIFY);
2827 return (optopt == '?' ? Z_OK : Z_USAGE);
2828 default:
2829 sub_usage(SHELP_VERIFY, CMD_VERIFY);
2830 return (Z_USAGE);
2833 if (argc > optind) {
2834 sub_usage(SHELP_VERIFY, CMD_VERIFY);
2835 return (Z_USAGE);
2837 if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE, B_FALSE)
2838 != Z_OK)
2839 return (Z_ERR);
2840 return (verify_details(CMD_VERIFY, argv));
2843 static int
2844 addoptions(char *buf, char *argv[], size_t len)
2846 int i = 0;
2848 if (buf[0] == '\0')
2849 return (Z_OK);
2851 while (argv[i] != NULL) {
2852 if (strlcat(buf, " ", len) >= len ||
2853 strlcat(buf, argv[i++], len) >= len) {
2854 zerror("Command line too long");
2855 return (Z_ERR);
2859 return (Z_OK);
2862 static int
2863 addopt(char *buf, int opt, char *optarg, size_t bufsize)
2865 char optstring[4];
2867 if (opt > 0)
2868 (void) sprintf(optstring, " -%c", opt);
2869 else
2870 (void) strcpy(optstring, " ");
2872 if ((strlcat(buf, optstring, bufsize) > bufsize))
2873 return (Z_ERR);
2875 if ((optarg != NULL) && (strlcat(buf, optarg, bufsize) > bufsize))
2876 return (Z_ERR);
2878 return (Z_OK);
2881 /* ARGSUSED */
2882 static int
2883 install_func(int argc, char *argv[])
2885 char cmdbuf[MAXPATHLEN];
2886 char postcmdbuf[MAXPATHLEN];
2887 int lockfd;
2888 int arg, err, subproc_err;
2889 char zonepath[MAXPATHLEN];
2890 brand_handle_t bh = NULL;
2891 int status;
2892 boolean_t do_postinstall = B_FALSE;
2893 boolean_t brand_help = B_FALSE;
2894 char opts[128];
2896 if (target_zone == NULL) {
2897 sub_usage(SHELP_INSTALL, CMD_INSTALL);
2898 return (Z_USAGE);
2901 if (zonecfg_in_alt_root()) {
2902 zerror(gettext("cannot install zone in alternate root"));
2903 return (Z_ERR);
2906 if ((err = zone_get_zonepath(target_zone, zonepath,
2907 sizeof (zonepath))) != Z_OK) {
2908 errno = err;
2909 zperror2(target_zone, gettext("could not get zone path"));
2910 return (Z_ERR);
2913 /* Fetch the install command from the brand configuration. */
2914 if ((bh = brand_open(target_brand)) == NULL) {
2915 zerror(gettext("missing or invalid brand"));
2916 return (Z_ERR);
2919 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_install,
2920 target_zone, zonepath) != Z_OK) {
2921 zerror("invalid brand configuration: missing install resource");
2922 brand_close(bh);
2923 return (Z_ERR);
2926 if (get_hook(bh, postcmdbuf, sizeof (postcmdbuf), brand_get_postinstall,
2927 target_zone, zonepath) != Z_OK) {
2928 zerror("invalid brand configuration: missing postinstall "
2929 "resource");
2930 brand_close(bh);
2931 return (Z_ERR);
2934 if (postcmdbuf[0] != '\0')
2935 do_postinstall = B_TRUE;
2937 (void) strcpy(opts, "?x:");
2939 * Fetch the list of recognized command-line options from
2940 * the brand configuration file.
2942 if (brand_get_installopts(bh, opts + strlen(opts),
2943 sizeof (opts) - strlen(opts)) != 0) {
2944 zerror("invalid brand configuration: missing "
2945 "install options resource");
2946 brand_close(bh);
2947 return (Z_ERR);
2950 brand_close(bh);
2952 if (cmdbuf[0] == '\0') {
2953 zerror("Missing brand install command");
2954 return (Z_ERR);
2957 /* Check the argv string for args we handle internally */
2958 optind = 0;
2959 opterr = 0;
2960 while ((arg = getopt(argc, argv, opts)) != EOF) {
2961 switch (arg) {
2962 case '?':
2963 if (optopt == '?') {
2964 sub_usage(SHELP_INSTALL, CMD_INSTALL);
2965 brand_help = B_TRUE;
2967 /* Ignore unknown options - may be brand specific. */
2968 break;
2969 default:
2970 /* Ignore unknown options - may be brand specific. */
2971 break;
2975 * Append the option to the command line passed to the
2976 * brand-specific install and postinstall routines.
2978 if (addopt(cmdbuf, optopt, optarg, sizeof (cmdbuf)) != Z_OK) {
2979 zerror("Install command line too long");
2980 return (Z_ERR);
2982 if (addopt(postcmdbuf, optopt, optarg, sizeof (postcmdbuf))
2983 != Z_OK) {
2984 zerror("Post-Install command line too long");
2985 return (Z_ERR);
2989 for (; optind < argc; optind++) {
2990 if (addopt(cmdbuf, 0, argv[optind], sizeof (cmdbuf)) != Z_OK) {
2991 zerror("Install command line too long");
2992 return (Z_ERR);
2995 if (addopt(postcmdbuf, 0, argv[optind], sizeof (postcmdbuf))
2996 != Z_OK) {
2997 zerror("Post-Install command line too long");
2998 return (Z_ERR);
3002 if (!brand_help) {
3003 if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE,
3004 B_FALSE) != Z_OK)
3005 return (Z_ERR);
3006 if (verify_details(CMD_INSTALL, argv) != Z_OK)
3007 return (Z_ERR);
3009 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
3010 zerror(gettext("another %s may have an operation in "
3011 "progress."), "zoneadm");
3012 return (Z_ERR);
3014 err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
3015 if (err != Z_OK) {
3016 errno = err;
3017 zperror2(target_zone, gettext("could not set state"));
3018 goto done;
3021 create_zfs_zonepath(zonepath);
3024 status = do_subproc(cmdbuf);
3025 if ((subproc_err =
3026 subproc_status(gettext("brand-specific installation"), status,
3027 B_FALSE)) != ZONE_SUBPROC_OK) {
3028 if (subproc_err == ZONE_SUBPROC_USAGE && !brand_help) {
3029 sub_usage(SHELP_INSTALL, CMD_INSTALL);
3030 zonecfg_release_lock_file(target_zone, lockfd);
3031 return (Z_ERR);
3033 errno = subproc_err;
3034 err = Z_ERR;
3035 goto done;
3038 if (brand_help)
3039 return (Z_OK);
3041 if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
3042 errno = err;
3043 zperror2(target_zone, gettext("could not set state"));
3044 goto done;
3047 if (do_postinstall) {
3048 status = do_subproc(postcmdbuf);
3050 if ((subproc_err =
3051 subproc_status(gettext("brand-specific post-install"),
3052 status, B_FALSE)) != ZONE_SUBPROC_OK) {
3053 errno = subproc_err;
3054 err = Z_ERR;
3055 (void) zone_set_state(target_zone,
3056 ZONE_STATE_INCOMPLETE);
3060 done:
3062 * If the install script exited with ZONE_SUBPROC_NOTCOMPLETE, try to
3063 * clean up the zone and leave the zone in the CONFIGURED state so that
3064 * another install can be attempted without requiring an uninstall
3065 * first.
3067 if (subproc_err == ZONE_SUBPROC_NOTCOMPLETE) {
3068 int temp_err;
3070 if ((temp_err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
3071 errno = err = temp_err;
3072 zperror2(target_zone,
3073 gettext("cleaning up zonepath failed"));
3074 } else if ((temp_err = zone_set_state(target_zone,
3075 ZONE_STATE_CONFIGURED)) != Z_OK) {
3076 errno = err = temp_err;
3077 zperror2(target_zone, gettext("could not set state"));
3081 if (!brand_help)
3082 zonecfg_release_lock_file(target_zone, lockfd);
3083 return ((err == Z_OK) ? Z_OK : Z_ERR);
3086 static void
3087 warn_dev_match(zone_dochandle_t s_handle, char *source_zone,
3088 zone_dochandle_t t_handle, char *target_zone)
3090 int err;
3091 struct zone_devtab s_devtab;
3092 struct zone_devtab t_devtab;
3094 if ((err = zonecfg_setdevent(t_handle)) != Z_OK) {
3095 errno = err;
3096 zperror2(target_zone, gettext("could not enumerate devices"));
3097 return;
3100 while (zonecfg_getdevent(t_handle, &t_devtab) == Z_OK) {
3101 if ((err = zonecfg_setdevent(s_handle)) != Z_OK) {
3102 errno = err;
3103 zperror2(source_zone,
3104 gettext("could not enumerate devices"));
3105 (void) zonecfg_enddevent(t_handle);
3106 return;
3109 while (zonecfg_getdevent(s_handle, &s_devtab) == Z_OK) {
3111 * Use fnmatch to catch the case where wildcards
3112 * were used in one zone and the other has an
3113 * explicit entry (e.g. /dev/dsk/c0t0d0s6 vs.
3114 * /dev/\*dsk/c0t0d0s6).
3116 if (fnmatch(t_devtab.zone_dev_match,
3117 s_devtab.zone_dev_match, FNM_PATHNAME) == 0 ||
3118 fnmatch(s_devtab.zone_dev_match,
3119 t_devtab.zone_dev_match, FNM_PATHNAME) == 0) {
3120 (void) fprintf(stderr,
3121 gettext("WARNING: device '%s' "
3122 "is configured in both zones.\n"),
3123 t_devtab.zone_dev_match);
3124 break;
3127 (void) zonecfg_enddevent(s_handle);
3130 (void) zonecfg_enddevent(t_handle);
3134 * Check if the specified mount option (opt) is contained within the
3135 * options string.
3137 static boolean_t
3138 opt_match(char *opt, char *options)
3140 char *p;
3141 char *lastp;
3143 if ((p = strtok_r(options, ",", &lastp)) != NULL) {
3144 if (strcmp(p, opt) == 0)
3145 return (B_TRUE);
3146 while ((p = strtok_r(NULL, ",", &lastp)) != NULL) {
3147 if (strcmp(p, opt) == 0)
3148 return (B_TRUE);
3152 return (B_FALSE);
3155 #define RW_LOFS "WARNING: read-write lofs file system on '%s' is configured " \
3156 "in both zones.\n"
3158 static void
3159 print_fs_warnings(struct zone_fstab *s_fstab, struct zone_fstab *t_fstab)
3162 * It is ok to have shared lofs mounted fs but we want to warn if
3163 * either is rw since this will effect the other zone.
3165 if (strcmp(t_fstab->zone_fs_type, "lofs") == 0) {
3166 zone_fsopt_t *optp;
3168 /* The default is rw so no options means rw */
3169 if (t_fstab->zone_fs_options == NULL ||
3170 s_fstab->zone_fs_options == NULL) {
3171 (void) fprintf(stderr, gettext(RW_LOFS),
3172 t_fstab->zone_fs_special);
3173 return;
3176 for (optp = s_fstab->zone_fs_options; optp != NULL;
3177 optp = optp->zone_fsopt_next) {
3178 if (opt_match("rw", optp->zone_fsopt_opt)) {
3179 (void) fprintf(stderr, gettext(RW_LOFS),
3180 s_fstab->zone_fs_special);
3181 return;
3185 for (optp = t_fstab->zone_fs_options; optp != NULL;
3186 optp = optp->zone_fsopt_next) {
3187 if (opt_match("rw", optp->zone_fsopt_opt)) {
3188 (void) fprintf(stderr, gettext(RW_LOFS),
3189 t_fstab->zone_fs_special);
3190 return;
3194 return;
3198 * TRANSLATION_NOTE
3199 * The first variable is the file system type and the second is
3200 * the file system special device. For example,
3201 * WARNING: ufs file system on '/dev/dsk/c0t0d0s0' ...
3203 (void) fprintf(stderr, gettext("WARNING: %s file system on '%s' "
3204 "is configured in both zones.\n"), t_fstab->zone_fs_type,
3205 t_fstab->zone_fs_special);
3208 static void
3209 warn_fs_match(zone_dochandle_t s_handle, char *source_zone,
3210 zone_dochandle_t t_handle, char *target_zone)
3212 int err;
3213 struct zone_fstab s_fstab;
3214 struct zone_fstab t_fstab;
3216 if ((err = zonecfg_setfsent(t_handle)) != Z_OK) {
3217 errno = err;
3218 zperror2(target_zone,
3219 gettext("could not enumerate file systems"));
3220 return;
3223 while (zonecfg_getfsent(t_handle, &t_fstab) == Z_OK) {
3224 if ((err = zonecfg_setfsent(s_handle)) != Z_OK) {
3225 errno = err;
3226 zperror2(source_zone,
3227 gettext("could not enumerate file systems"));
3228 (void) zonecfg_endfsent(t_handle);
3229 return;
3232 while (zonecfg_getfsent(s_handle, &s_fstab) == Z_OK) {
3233 if (strcmp(t_fstab.zone_fs_special,
3234 s_fstab.zone_fs_special) == 0) {
3235 print_fs_warnings(&s_fstab, &t_fstab);
3236 break;
3239 (void) zonecfg_endfsent(s_handle);
3242 (void) zonecfg_endfsent(t_handle);
3246 * We don't catch the case where you used the same IP address but
3247 * it is not an exact string match. For example, 192.9.0.128 vs. 192.09.0.128.
3248 * However, we're not going to worry about that but we will check for
3249 * a possible netmask on one of the addresses (e.g. 10.0.0.1 and 10.0.0.1/24)
3250 * and handle that case as a match.
3252 static void
3253 warn_ip_match(zone_dochandle_t s_handle, char *source_zone,
3254 zone_dochandle_t t_handle, char *target_zone)
3256 int err;
3257 struct zone_nwiftab s_nwiftab;
3258 struct zone_nwiftab t_nwiftab;
3260 if ((err = zonecfg_setnwifent(t_handle)) != Z_OK) {
3261 errno = err;
3262 zperror2(target_zone,
3263 gettext("could not enumerate network interfaces"));
3264 return;
3267 while (zonecfg_getnwifent(t_handle, &t_nwiftab) == Z_OK) {
3268 char *p;
3270 /* remove an (optional) netmask from the address */
3271 if ((p = strchr(t_nwiftab.zone_nwif_address, '/')) != NULL)
3272 *p = '\0';
3274 if ((err = zonecfg_setnwifent(s_handle)) != Z_OK) {
3275 errno = err;
3276 zperror2(source_zone,
3277 gettext("could not enumerate network interfaces"));
3278 (void) zonecfg_endnwifent(t_handle);
3279 return;
3282 while (zonecfg_getnwifent(s_handle, &s_nwiftab) == Z_OK) {
3283 /* remove an (optional) netmask from the address */
3284 if ((p = strchr(s_nwiftab.zone_nwif_address, '/'))
3285 != NULL)
3286 *p = '\0';
3288 /* For exclusive-IP zones, address is not specified. */
3289 if (strlen(s_nwiftab.zone_nwif_address) == 0)
3290 continue;
3292 if (strcmp(t_nwiftab.zone_nwif_address,
3293 s_nwiftab.zone_nwif_address) == 0) {
3294 (void) fprintf(stderr,
3295 gettext("WARNING: network address '%s' "
3296 "is configured in both zones.\n"),
3297 t_nwiftab.zone_nwif_address);
3298 break;
3301 (void) zonecfg_endnwifent(s_handle);
3304 (void) zonecfg_endnwifent(t_handle);
3307 static void
3308 warn_dataset_match(zone_dochandle_t s_handle, char *source,
3309 zone_dochandle_t t_handle, char *target)
3311 int err;
3312 struct zone_dstab s_dstab;
3313 struct zone_dstab t_dstab;
3315 if ((err = zonecfg_setdsent(t_handle)) != Z_OK) {
3316 errno = err;
3317 zperror2(target, gettext("could not enumerate datasets"));
3318 return;
3321 while (zonecfg_getdsent(t_handle, &t_dstab) == Z_OK) {
3322 if ((err = zonecfg_setdsent(s_handle)) != Z_OK) {
3323 errno = err;
3324 zperror2(source,
3325 gettext("could not enumerate datasets"));
3326 (void) zonecfg_enddsent(t_handle);
3327 return;
3330 while (zonecfg_getdsent(s_handle, &s_dstab) == Z_OK) {
3331 if (strcmp(t_dstab.zone_dataset_name,
3332 s_dstab.zone_dataset_name) == 0) {
3333 target_zone = source;
3334 zerror(gettext("WARNING: dataset '%s' "
3335 "is configured in both zones.\n"),
3336 t_dstab.zone_dataset_name);
3337 break;
3340 (void) zonecfg_enddsent(s_handle);
3343 (void) zonecfg_enddsent(t_handle);
3347 * Check that the clone and its source have the same brand type.
3349 static int
3350 valid_brand_clone(char *source_zone, char *target_zone)
3352 brand_handle_t bh;
3353 char source_brand[MAXNAMELEN];
3355 if ((zone_get_brand(source_zone, source_brand,
3356 sizeof (source_brand))) != Z_OK) {
3357 (void) fprintf(stderr, "%s: zone '%s': %s\n",
3358 execname, source_zone, gettext("missing or invalid brand"));
3359 return (Z_ERR);
3362 if (strcmp(source_brand, target_brand) != 0) {
3363 (void) fprintf(stderr,
3364 gettext("%s: Zones '%s' and '%s' have different brand "
3365 "types.\n"), execname, source_zone, target_zone);
3366 return (Z_ERR);
3369 if ((bh = brand_open(target_brand)) == NULL) {
3370 zerror(gettext("missing or invalid brand"));
3371 return (Z_ERR);
3373 brand_close(bh);
3374 return (Z_OK);
3377 static int
3378 validate_clone(char *source_zone, char *target_zone)
3380 int err = Z_OK;
3381 zone_dochandle_t s_handle;
3382 zone_dochandle_t t_handle;
3384 if ((t_handle = zonecfg_init_handle()) == NULL) {
3385 zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3386 return (Z_ERR);
3388 if ((err = zonecfg_get_handle(target_zone, t_handle)) != Z_OK) {
3389 errno = err;
3390 zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3391 zonecfg_fini_handle(t_handle);
3392 return (Z_ERR);
3395 if ((s_handle = zonecfg_init_handle()) == NULL) {
3396 zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3397 zonecfg_fini_handle(t_handle);
3398 return (Z_ERR);
3400 if ((err = zonecfg_get_handle(source_zone, s_handle)) != Z_OK) {
3401 errno = err;
3402 zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3403 goto done;
3406 /* verify new zone has same brand type */
3407 err = valid_brand_clone(source_zone, target_zone);
3408 if (err != Z_OK)
3409 goto done;
3411 /* warn about imported fs's which are the same */
3412 warn_fs_match(s_handle, source_zone, t_handle, target_zone);
3414 /* warn about imported IP addresses which are the same */
3415 warn_ip_match(s_handle, source_zone, t_handle, target_zone);
3417 /* warn about imported devices which are the same */
3418 warn_dev_match(s_handle, source_zone, t_handle, target_zone);
3420 /* warn about imported datasets which are the same */
3421 warn_dataset_match(s_handle, source_zone, t_handle, target_zone);
3423 done:
3424 zonecfg_fini_handle(t_handle);
3425 zonecfg_fini_handle(s_handle);
3427 return ((err == Z_OK) ? Z_OK : Z_ERR);
3430 static int
3431 copy_zone(char *src, char *dst)
3433 boolean_t out_null = B_FALSE;
3434 int status;
3435 char *outfile;
3436 char cmdbuf[MAXPATHLEN * 2 + 128];
3438 if ((outfile = tempnam("/var/log", "zone")) == NULL) {
3439 outfile = "/dev/null";
3440 out_null = B_TRUE;
3444 * Use find to get the list of files to copy. We need to skip
3445 * files of type "socket" since cpio can't handle those but that
3446 * should be ok since the app will recreate the socket when it runs.
3447 * We also need to filter out anything under the .zfs subdir. Since
3448 * find is running depth-first, we need the extra egrep to filter .zfs.
3450 (void) snprintf(cmdbuf, sizeof (cmdbuf),
3451 "cd %s && /usr/bin/find . -type s -prune -o -depth -print | "
3452 "/usr/bin/egrep -v '^\\./\\.zfs$|^\\./\\.zfs/' | "
3453 "/usr/bin/cpio -pdmuP@ %s > %s 2>&1",
3454 src, dst, outfile);
3456 status = do_subproc(cmdbuf);
3458 if (subproc_status("copy", status, B_TRUE) != ZONE_SUBPROC_OK) {
3459 if (!out_null)
3460 (void) fprintf(stderr, gettext("\nThe copy failed.\n"
3461 "More information can be found in %s\n"), outfile);
3462 return (Z_ERR);
3465 if (!out_null)
3466 (void) unlink(outfile);
3468 return (Z_OK);
3471 /* ARGSUSED */
3473 zfm_print(const struct mnttab *p, void *r)
3475 zerror(" %s\n", p->mnt_mountp);
3476 return (0);
3480 clone_copy(char *source_zonepath, char *zonepath)
3482 int err;
3484 /* Don't clone the zone if anything is still mounted there */
3485 if (zonecfg_find_mounts(source_zonepath, NULL, NULL)) {
3486 zerror(gettext("These file systems are mounted on "
3487 "subdirectories of %s.\n"), source_zonepath);
3488 (void) zonecfg_find_mounts(source_zonepath, zfm_print, NULL);
3489 return (Z_ERR);
3493 * Attempt to create a ZFS fs for the zonepath. As usual, we don't
3494 * care if this works or not since we always have the default behavior
3495 * of a simple directory for the zonepath.
3497 create_zfs_zonepath(zonepath);
3499 (void) printf(gettext("Copying %s..."), source_zonepath);
3500 (void) fflush(stdout);
3502 err = copy_zone(source_zonepath, zonepath);
3504 (void) printf("\n");
3506 return (err);
3509 static int
3510 clone_func(int argc, char *argv[])
3512 char *source_zone = NULL;
3513 int lockfd;
3514 int err, arg;
3515 char zonepath[MAXPATHLEN];
3516 char source_zonepath[MAXPATHLEN];
3517 zone_state_t state;
3518 zone_entry_t *zent;
3519 char *method = NULL;
3520 char *snapshot = NULL;
3521 char cmdbuf[MAXPATHLEN];
3522 char postcmdbuf[MAXPATHLEN];
3523 char presnapbuf[MAXPATHLEN];
3524 char postsnapbuf[MAXPATHLEN];
3525 char validsnapbuf[MAXPATHLEN];
3526 brand_handle_t bh = NULL;
3527 int status;
3528 boolean_t brand_help = B_FALSE;
3530 if (zonecfg_in_alt_root()) {
3531 zerror(gettext("cannot clone zone in alternate root"));
3532 return (Z_ERR);
3535 /* Check the argv string for args we handle internally */
3536 optind = 0;
3537 opterr = 0;
3538 while ((arg = getopt(argc, argv, "?m:s:")) != EOF) {
3539 switch (arg) {
3540 case '?':
3541 if (optopt == '?') {
3542 sub_usage(SHELP_CLONE, CMD_CLONE);
3543 brand_help = B_TRUE;
3545 /* Ignore unknown options - may be brand specific. */
3546 break;
3547 case 'm':
3548 method = optarg;
3549 break;
3550 case 's':
3551 snapshot = optarg;
3552 break;
3553 default:
3554 /* Ignore unknown options - may be brand specific. */
3555 break;
3559 if (argc != (optind + 1)) {
3560 sub_usage(SHELP_CLONE, CMD_CLONE);
3561 return (Z_USAGE);
3564 source_zone = argv[optind];
3566 if (!brand_help) {
3567 if (sanity_check(target_zone, CMD_CLONE, B_FALSE, B_TRUE,
3568 B_FALSE) != Z_OK)
3569 return (Z_ERR);
3570 if (verify_details(CMD_CLONE, argv) != Z_OK)
3571 return (Z_ERR);
3574 * We also need to do some extra validation on the source zone.
3576 if (strcmp(source_zone, GLOBAL_ZONENAME) == 0) {
3577 zerror(gettext("%s operation is invalid for the "
3578 "global zone."), cmd_to_str(CMD_CLONE));
3579 return (Z_ERR);
3582 if (strncmp(source_zone, "SUNW", 4) == 0) {
3583 zerror(gettext("%s operation is invalid for zones "
3584 "starting with SUNW."), cmd_to_str(CMD_CLONE));
3585 return (Z_ERR);
3588 if (auth_check(username, source_zone, SOURCE_ZONE) == Z_ERR) {
3589 zerror(gettext("%s operation is invalid because "
3590 "user is not authorized to read source zone."),
3591 cmd_to_str(CMD_CLONE));
3592 return (Z_ERR);
3595 zent = lookup_running_zone(source_zone);
3596 if (zent != NULL) {
3597 /* check whether the zone is ready or running */
3598 if ((err = zone_get_state(zent->zname,
3599 &zent->zstate_num)) != Z_OK) {
3600 errno = err;
3601 zperror2(zent->zname, gettext("could not get "
3602 "state"));
3603 /* can't tell, so hedge */
3604 zent->zstate_str = "ready/running";
3605 } else {
3606 zent->zstate_str =
3607 zone_state_str(zent->zstate_num);
3609 zerror(gettext("%s operation is invalid for %s zones."),
3610 cmd_to_str(CMD_CLONE), zent->zstate_str);
3611 return (Z_ERR);
3614 if ((err = zone_get_state(source_zone, &state)) != Z_OK) {
3615 errno = err;
3616 zperror2(source_zone, gettext("could not get state"));
3617 return (Z_ERR);
3619 if (state != ZONE_STATE_INSTALLED) {
3620 (void) fprintf(stderr,
3621 gettext("%s: zone %s is %s; %s is required.\n"),
3622 execname, source_zone, zone_state_str(state),
3623 zone_state_str(ZONE_STATE_INSTALLED));
3624 return (Z_ERR);
3628 * The source zone checks out ok, continue with the clone.
3631 if (validate_clone(source_zone, target_zone) != Z_OK)
3632 return (Z_ERR);
3634 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
3635 zerror(gettext("another %s may have an operation in "
3636 "progress."), "zoneadm");
3637 return (Z_ERR);
3641 if ((err = zone_get_zonepath(source_zone, source_zonepath,
3642 sizeof (source_zonepath))) != Z_OK) {
3643 errno = err;
3644 zperror2(source_zone, gettext("could not get zone path"));
3645 goto done;
3648 if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3649 != Z_OK) {
3650 errno = err;
3651 zperror2(target_zone, gettext("could not get zone path"));
3652 goto done;
3656 * Fetch the clone and postclone hooks from the brand configuration.
3658 if ((bh = brand_open(target_brand)) == NULL) {
3659 zerror(gettext("missing or invalid brand"));
3660 err = Z_ERR;
3661 goto done;
3664 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_clone, target_zone,
3665 zonepath) != Z_OK) {
3666 zerror("invalid brand configuration: missing clone resource");
3667 brand_close(bh);
3668 err = Z_ERR;
3669 goto done;
3672 if (get_hook(bh, postcmdbuf, sizeof (postcmdbuf), brand_get_postclone,
3673 target_zone, zonepath) != Z_OK) {
3674 zerror("invalid brand configuration: missing postclone "
3675 "resource");
3676 brand_close(bh);
3677 err = Z_ERR;
3678 goto done;
3681 if (get_hook(bh, presnapbuf, sizeof (presnapbuf), brand_get_presnap,
3682 source_zone, source_zonepath) != Z_OK) {
3683 zerror("invalid brand configuration: missing presnap "
3684 "resource");
3685 brand_close(bh);
3686 err = Z_ERR;
3687 goto done;
3690 if (get_hook(bh, postsnapbuf, sizeof (postsnapbuf), brand_get_postsnap,
3691 source_zone, source_zonepath) != Z_OK) {
3692 zerror("invalid brand configuration: missing postsnap "
3693 "resource");
3694 brand_close(bh);
3695 err = Z_ERR;
3696 goto done;
3699 if (get_hook(bh, validsnapbuf, sizeof (validsnapbuf),
3700 brand_get_validatesnap, target_zone, zonepath) != Z_OK) {
3701 zerror("invalid brand configuration: missing validatesnap "
3702 "resource");
3703 brand_close(bh);
3704 err = Z_ERR;
3705 goto done;
3707 brand_close(bh);
3709 /* Append all options to clone hook. */
3710 if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK) {
3711 err = Z_ERR;
3712 goto done;
3715 /* Append all options to postclone hook. */
3716 if (addoptions(postcmdbuf, argv, sizeof (postcmdbuf)) != Z_OK) {
3717 err = Z_ERR;
3718 goto done;
3721 if (!brand_help) {
3722 if ((err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE))
3723 != Z_OK) {
3724 errno = err;
3725 zperror2(target_zone, gettext("could not set state"));
3726 goto done;
3731 * The clone hook is optional. If it exists, use the hook for
3732 * cloning, otherwise use the built-in clone support
3734 if (cmdbuf[0] != '\0') {
3735 /* Run the clone hook */
3736 status = do_subproc(cmdbuf);
3737 if ((status = subproc_status(gettext("brand-specific clone"),
3738 status, B_FALSE)) != ZONE_SUBPROC_OK) {
3739 if (status == ZONE_SUBPROC_USAGE && !brand_help)
3740 sub_usage(SHELP_CLONE, CMD_CLONE);
3741 err = Z_ERR;
3742 goto done;
3745 if (brand_help)
3746 return (Z_OK);
3748 } else {
3749 /* If just help, we're done since there is no brand help. */
3750 if (brand_help)
3751 return (Z_OK);
3753 /* Run the built-in clone support. */
3755 /* The only explicit built-in method is "copy". */
3756 if (method != NULL && strcmp(method, "copy") != 0) {
3757 sub_usage(SHELP_CLONE, CMD_CLONE);
3758 err = Z_USAGE;
3759 goto done;
3762 if (snapshot != NULL) {
3763 err = clone_snapshot_zfs(snapshot, zonepath,
3764 validsnapbuf);
3765 } else {
3767 * We always copy the clone unless the source is ZFS
3768 * and a ZFS clone worked. We fallback to copying if
3769 * the ZFS clone fails for some reason.
3771 err = Z_ERR;
3772 if (method == NULL && is_zonepath_zfs(source_zonepath))
3773 err = clone_zfs(source_zonepath, zonepath,
3774 presnapbuf, postsnapbuf);
3776 if (err != Z_OK)
3777 err = clone_copy(source_zonepath, zonepath);
3781 if (err == Z_OK && postcmdbuf[0] != '\0') {
3782 status = do_subproc(postcmdbuf);
3783 if ((err = subproc_status("postclone", status, B_FALSE))
3784 != ZONE_SUBPROC_OK) {
3785 zerror(gettext("post-clone configuration failed."));
3786 err = Z_ERR;
3790 done:
3792 * If everything went well, we mark the zone as installed.
3794 if (err == Z_OK) {
3795 err = zone_set_state(target_zone, ZONE_STATE_INSTALLED);
3796 if (err != Z_OK) {
3797 errno = err;
3798 zperror2(target_zone, gettext("could not set state"));
3801 if (!brand_help)
3802 zonecfg_release_lock_file(target_zone, lockfd);
3803 return ((err == Z_OK) ? Z_OK : Z_ERR);
3807 * Used when removing a zonepath after uninstalling or cleaning up after
3808 * the move subcommand. This handles a zonepath that has non-standard
3809 * contents so that we will only cleanup the stuff we know about and leave
3810 * any user data alone.
3812 * If the "all" parameter is true then we should remove the whole zonepath
3813 * even if it has non-standard files/directories in it. This can be used when
3814 * we need to cleanup after moving the zonepath across file systems.
3816 * We "exec" the RMCOMMAND so that the returned status is that of RMCOMMAND
3817 * and not the shell.
3819 static int
3820 cleanup_zonepath(char *zonepath, boolean_t all)
3822 int status;
3823 int i;
3824 boolean_t non_std = B_FALSE;
3825 struct dirent *dp;
3826 DIR *dirp;
3828 * The SUNWattached.xml file is expected since it might
3829 * exist if the zone was force-attached after a
3830 * migration.
3832 char *std_entries[] = {"dev", "lu", "root",
3833 "SUNWattached.xml", NULL};
3834 /* (MAXPATHLEN * 3) is for the 3 std_entries dirs */
3835 char cmdbuf[sizeof (RMCOMMAND) + (MAXPATHLEN * 3) + 64];
3838 * We shouldn't need these checks but lets be paranoid since we
3839 * could blow away the whole system here if we got the wrong zonepath.
3841 if (*zonepath == '\0'|| strcmp(zonepath, "/") == 0) {
3842 (void) fprintf(stderr, "invalid zonepath '%s'\n", zonepath);
3843 return (Z_INVAL);
3847 * If the dirpath is already gone (maybe it was manually removed) then
3848 * we just return Z_OK so that the cleanup is successful.
3850 if ((dirp = opendir(zonepath)) == NULL)
3851 return (Z_OK);
3854 * Look through the zonepath directory to see if there are any
3855 * non-standard files/dirs. Also skip .zfs since that might be
3856 * there but we'll handle ZFS file systems as a special case.
3858 while ((dp = readdir(dirp)) != NULL) {
3859 if (strcmp(dp->d_name, ".") == 0 ||
3860 strcmp(dp->d_name, "..") == 0 ||
3861 strcmp(dp->d_name, ".zfs") == 0)
3862 continue;
3864 for (i = 0; std_entries[i] != NULL; i++)
3865 if (strcmp(dp->d_name, std_entries[i]) == 0)
3866 break;
3868 if (std_entries[i] == NULL)
3869 non_std = B_TRUE;
3871 (void) closedir(dirp);
3873 if (!all && non_std) {
3875 * There are extra, non-standard directories/files in the
3876 * zonepath so we don't want to remove the zonepath. We
3877 * just want to remove the standard directories and leave
3878 * the user data alone.
3880 (void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND);
3882 for (i = 0; std_entries[i] != NULL; i++) {
3883 char tmpbuf[MAXPATHLEN];
3885 if (snprintf(tmpbuf, sizeof (tmpbuf), " %s/%s",
3886 zonepath, std_entries[i]) >= sizeof (tmpbuf) ||
3887 strlcat(cmdbuf, tmpbuf, sizeof (cmdbuf)) >=
3888 sizeof (cmdbuf)) {
3889 (void) fprintf(stderr,
3890 gettext("path is too long\n"));
3891 return (Z_INVAL);
3895 status = do_subproc(cmdbuf);
3897 (void) fprintf(stderr, gettext("WARNING: Unable to completely "
3898 "remove %s\nbecause it contains additional user data. "
3899 "Only the standard directory\nentries have been "
3900 "removed.\n"),
3901 zonepath);
3903 return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
3904 ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
3908 * There is nothing unexpected in the zonepath, try to get rid of the
3909 * whole zonepath directory.
3911 * If the zonepath is its own zfs file system, try to destroy the
3912 * file system. If that fails for some reason (e.g. it has clones)
3913 * then we'll just remove the contents of the zonepath.
3915 if (is_zonepath_zfs(zonepath)) {
3916 if (destroy_zfs(zonepath) == Z_OK)
3917 return (Z_OK);
3918 (void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND
3919 " %s/*", zonepath);
3920 status = do_subproc(cmdbuf);
3921 return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
3922 ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
3925 (void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
3926 zonepath);
3927 status = do_subproc(cmdbuf);
3929 return ((subproc_status(RMCOMMAND, status, B_TRUE) == ZONE_SUBPROC_OK)
3930 ? Z_OK : Z_ERR);
3933 static int
3934 move_func(int argc, char *argv[])
3936 char *new_zonepath = NULL;
3937 int lockfd;
3938 int err, arg;
3939 char zonepath[MAXPATHLEN];
3940 zone_dochandle_t handle;
3941 boolean_t fast;
3942 boolean_t is_zfs = B_FALSE;
3943 boolean_t root_fs_mounted = B_FALSE;
3944 struct dirent *dp;
3945 DIR *dirp;
3946 boolean_t empty = B_TRUE;
3947 boolean_t revert;
3948 struct stat zonepath_buf;
3949 struct stat new_zonepath_buf;
3950 zone_mounts_t mounts;
3952 if (zonecfg_in_alt_root()) {
3953 zerror(gettext("cannot move zone in alternate root"));
3954 return (Z_ERR);
3957 optind = 0;
3958 if ((arg = getopt(argc, argv, "?")) != EOF) {
3959 switch (arg) {
3960 case '?':
3961 sub_usage(SHELP_MOVE, CMD_MOVE);
3962 return (optopt == '?' ? Z_OK : Z_USAGE);
3963 default:
3964 sub_usage(SHELP_MOVE, CMD_MOVE);
3965 return (Z_USAGE);
3968 if (argc != (optind + 1)) {
3969 sub_usage(SHELP_MOVE, CMD_MOVE);
3970 return (Z_USAGE);
3972 new_zonepath = argv[optind];
3973 if (sanity_check(target_zone, CMD_MOVE, B_FALSE, B_TRUE, B_FALSE)
3974 != Z_OK)
3975 return (Z_ERR);
3976 if (verify_details(CMD_MOVE, argv) != Z_OK)
3977 return (Z_ERR);
3980 * Check out the new zonepath. This has the side effect of creating
3981 * a directory for the new zonepath. We depend on this later when we
3982 * stat to see if we are doing a cross file system move or not.
3984 if (validate_zonepath(new_zonepath, CMD_MOVE) != Z_OK)
3985 return (Z_ERR);
3987 if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3988 != Z_OK) {
3989 errno = err;
3990 zperror2(target_zone, gettext("could not get zone path"));
3991 return (Z_ERR);
3994 if (stat(zonepath, &zonepath_buf) == -1) {
3995 zperror(gettext("could not stat zone path"), B_FALSE);
3996 return (Z_ERR);
3999 if (stat(new_zonepath, &new_zonepath_buf) == -1) {
4000 zperror(gettext("could not stat new zone path"), B_FALSE);
4001 return (Z_ERR);
4005 * Check if the destination directory is empty.
4007 if ((dirp = opendir(new_zonepath)) == NULL) {
4008 zperror(gettext("could not open new zone path"), B_FALSE);
4009 return (Z_ERR);
4011 while ((dp = readdir(dirp)) != NULL) {
4012 if (strcmp(dp->d_name, ".") == 0 ||
4013 strcmp(dp->d_name, "..") == 0)
4014 continue;
4015 empty = B_FALSE;
4016 break;
4018 (void) closedir(dirp);
4020 /* Error if there is anything in the destination directory. */
4021 if (!empty) {
4022 (void) fprintf(stderr, gettext("could not move zone to %s: "
4023 "directory not empty\n"), new_zonepath);
4024 return (Z_ERR);
4028 * Collect information about mounts within the zone's zonepath.
4029 * Overlay mounts on the zone's root directory are erroneous.
4030 * Bail if we encounter any unexpected mounts.
4032 if (zone_mounts_init(&mounts, zonepath) != 0)
4033 return (Z_ERR);
4034 if (mounts.num_root_overlay_mounts != 0) {
4035 zerror(gettext("%d overlay mount(s) detected on %s/root."),
4036 mounts.num_root_overlay_mounts, zonepath);
4037 goto err_and_mounts_destroy;
4039 if (mounts.num_unexpected_mounts != 0)
4040 goto err_and_mounts_destroy;
4043 * Check if we are moving in the same file system and can do a fast
4044 * move or if we are crossing file systems and have to copy the data.
4046 fast = (zonepath_buf.st_dev == new_zonepath_buf.st_dev);
4048 if ((handle = zonecfg_init_handle()) == NULL) {
4049 zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4050 goto err_and_mounts_destroy;
4053 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4054 errno = err;
4055 zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4056 goto err_and_fini_handle;
4059 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4060 zerror(gettext("another %s may have an operation in progress."),
4061 "zoneadm");
4062 goto err_and_fini_handle;
4066 * Unmount the zone's root filesystem before we move the zone's
4067 * zonepath.
4069 if (zone_unmount_rootfs(&mounts, zonepath, B_FALSE) != 0)
4070 goto err_and_rele_lockfile;
4073 * We're making some file system changes now so we have to clean up
4074 * the file system before we are done. This will either clean up the
4075 * new zonepath if the zonecfg update failed or it will clean up the
4076 * old zonepath if everything is ok.
4078 revert = B_TRUE;
4080 if (is_zonepath_zfs(zonepath) &&
4081 move_zfs(zonepath, new_zonepath) != Z_ERR) {
4082 is_zfs = B_TRUE;
4084 } else if (fast) {
4085 /* same file system, use rename for a quick move */
4088 * Remove the new_zonepath directory that got created above
4089 * during the validation. It gets in the way of the rename.
4091 if (rmdir(new_zonepath) != 0) {
4092 zperror(gettext("could not rmdir new zone path"),
4093 B_FALSE);
4094 (void) zone_mount_rootfs(&mounts, zonepath);
4095 goto err_and_rele_lockfile;
4098 if (rename(zonepath, new_zonepath) != 0) {
4100 * If this fails we don't need to do all of the
4101 * cleanup that happens for the rest of the code
4102 * so just return from this error.
4104 zperror(gettext("could not move zone"), B_FALSE);
4105 (void) zone_mount_rootfs(&mounts, zonepath);
4106 goto err_and_rele_lockfile;
4109 } else {
4111 * Attempt to create a ZFS fs for the new zonepath. As usual,
4112 * we don't care if this works or not since we always have the
4113 * default behavior of a simple directory for the zonepath.
4115 create_zfs_zonepath(new_zonepath);
4117 (void) printf(gettext(
4118 "Moving across file systems; copying zonepath %s..."),
4119 zonepath);
4120 (void) fflush(stdout);
4122 err = copy_zone(zonepath, new_zonepath);
4124 (void) printf("\n");
4125 if (err != Z_OK)
4126 goto done;
4130 * Mount the zone's root filesystem in the new zonepath if there was
4131 * a root mount prior to the move.
4133 if (zone_mount_rootfs(&mounts, new_zonepath) != 0) {
4134 err = Z_ERR;
4135 goto done;
4137 root_fs_mounted = B_TRUE;
4139 if ((err = zonecfg_set_zonepath(handle, new_zonepath)) != Z_OK) {
4140 errno = err;
4141 zperror(gettext("could not set new zonepath"), B_TRUE);
4142 goto done;
4145 if ((err = zonecfg_save(handle)) != Z_OK) {
4146 errno = err;
4147 zperror(gettext("zonecfg save failed"), B_TRUE);
4148 goto done;
4151 revert = B_FALSE;
4153 done:
4154 zonecfg_fini_handle(handle);
4155 zonecfg_release_lock_file(target_zone, lockfd);
4158 * Clean up the file system based on how things went. We either
4159 * clean up the new zonepath if the operation failed for some reason
4160 * or we clean up the old zonepath if everything is ok.
4162 if (revert) {
4164 * Check for the unlikely scenario in which the zone's
4165 * zonepath and its root file system moved but libzonecfg
4166 * couldn't save the new zonepath to the zone's configuration
4167 * file. The mounted root filesystem must be unmounted before
4168 * zoneadm restores the zone's zonepath.
4170 if (root_fs_mounted && zone_unmount_rootfs(&mounts,
4171 new_zonepath, B_TRUE) != 0) {
4173 * We can't forcibly unmount the zone's root file system
4174 * from the new zonepath. Bail!
4176 zerror(gettext("fatal error: cannot unmount %s/root\n"),
4177 new_zonepath);
4178 goto err_and_mounts_destroy;
4181 /* The zonecfg update failed, cleanup the new zonepath. */
4182 if (is_zfs) {
4183 if (move_zfs(new_zonepath, zonepath) == Z_ERR) {
4184 (void) fprintf(stderr, gettext("could not "
4185 "restore zonepath, the zfs mountpoint is "
4186 "set as:\n%s\n"), new_zonepath);
4188 * err is already != Z_OK since we're reverting
4190 } else {
4191 (void) zone_mount_rootfs(&mounts, zonepath);
4193 } else if (fast) {
4194 if (rename(new_zonepath, zonepath) != 0) {
4195 zperror(gettext("could not restore zonepath"),
4196 B_FALSE);
4198 * err is already != Z_OK since we're reverting
4200 } else {
4201 (void) zone_mount_rootfs(&mounts, zonepath);
4203 } else {
4204 (void) printf(gettext("Cleaning up zonepath %s..."),
4205 new_zonepath);
4206 (void) fflush(stdout);
4207 err = cleanup_zonepath(new_zonepath, B_TRUE);
4208 (void) printf("\n");
4210 if (err != Z_OK) {
4211 errno = err;
4212 zperror(gettext("could not remove new "
4213 "zonepath"), B_TRUE);
4214 } else {
4216 * Because we're reverting we know the mainline
4217 * code failed but we just reused the err
4218 * variable so we reset it back to Z_ERR.
4220 err = Z_ERR;
4223 (void) zone_mount_rootfs(&mounts, zonepath);
4225 } else {
4226 /* The move was successful, cleanup the old zonepath. */
4227 if (!is_zfs && !fast) {
4228 (void) printf(
4229 gettext("Cleaning up zonepath %s..."), zonepath);
4230 (void) fflush(stdout);
4231 err = cleanup_zonepath(zonepath, B_TRUE);
4232 (void) printf("\n");
4234 if (err != Z_OK) {
4235 errno = err;
4236 zperror(gettext("could not remove zonepath"),
4237 B_TRUE);
4242 zone_mounts_destroy(&mounts);
4243 return ((err == Z_OK) ? Z_OK : Z_ERR);
4245 err_and_rele_lockfile:
4246 zonecfg_release_lock_file(target_zone, lockfd);
4247 err_and_fini_handle:
4248 zonecfg_fini_handle(handle);
4249 err_and_mounts_destroy:
4250 zone_mounts_destroy(&mounts);
4251 return (Z_ERR);
4254 /* ARGSUSED */
4255 static int
4256 detach_func(int argc, char *argv[])
4258 int lockfd = -1;
4259 int err, arg;
4260 char zonepath[MAXPATHLEN];
4261 char cmdbuf[MAXPATHLEN];
4262 char precmdbuf[MAXPATHLEN];
4263 boolean_t execute = B_TRUE;
4264 boolean_t brand_help = B_FALSE;
4265 brand_handle_t bh = NULL;
4266 int status;
4268 if (zonecfg_in_alt_root()) {
4269 zerror(gettext("cannot detach zone in alternate root"));
4270 return (Z_ERR);
4273 /* Check the argv string for args we handle internally */
4274 optind = 0;
4275 opterr = 0;
4276 while ((arg = getopt(argc, argv, "?n")) != EOF) {
4277 switch (arg) {
4278 case '?':
4279 if (optopt == '?') {
4280 sub_usage(SHELP_DETACH, CMD_DETACH);
4281 brand_help = B_TRUE;
4283 /* Ignore unknown options - may be brand specific. */
4284 break;
4285 case 'n':
4286 execute = B_FALSE;
4287 break;
4288 default:
4289 /* Ignore unknown options - may be brand specific. */
4290 break;
4294 if (brand_help)
4295 execute = B_FALSE;
4297 if (execute) {
4298 if (sanity_check(target_zone, CMD_DETACH, B_FALSE, B_TRUE,
4299 B_FALSE) != Z_OK)
4300 return (Z_ERR);
4301 if (verify_details(CMD_DETACH, argv) != Z_OK)
4302 return (Z_ERR);
4303 } else {
4305 * We want a dry-run to work for a non-privileged user so we
4306 * only do minimal validation.
4308 if (target_zone == NULL) {
4309 zerror(gettext("no zone specified"));
4310 return (Z_ERR);
4313 if (strcmp(target_zone, GLOBAL_ZONENAME) == 0) {
4314 zerror(gettext("%s operation is invalid for the "
4315 "global zone."), cmd_to_str(CMD_DETACH));
4316 return (Z_ERR);
4320 if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4321 != Z_OK) {
4322 errno = err;
4323 zperror2(target_zone, gettext("could not get zone path"));
4324 return (Z_ERR);
4327 /* Fetch the detach and predetach hooks from the brand configuration. */
4328 if ((bh = brand_open(target_brand)) == NULL) {
4329 zerror(gettext("missing or invalid brand"));
4330 return (Z_ERR);
4333 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_detach, target_zone,
4334 zonepath) != Z_OK) {
4335 zerror("invalid brand configuration: missing detach resource");
4336 brand_close(bh);
4337 return (Z_ERR);
4340 if (get_hook(bh, precmdbuf, sizeof (precmdbuf), brand_get_predetach,
4341 target_zone, zonepath) != Z_OK) {
4342 zerror("invalid brand configuration: missing predetach "
4343 "resource");
4344 brand_close(bh);
4345 return (Z_ERR);
4347 brand_close(bh);
4349 /* Append all options to predetach hook. */
4350 if (addoptions(precmdbuf, argv, sizeof (precmdbuf)) != Z_OK)
4351 return (Z_ERR);
4353 /* Append all options to detach hook. */
4354 if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK)
4355 return (Z_ERR);
4357 if (execute && zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4358 zerror(gettext("another %s may have an operation in progress."),
4359 "zoneadm");
4360 return (Z_ERR);
4363 /* If we have a brand predetach hook, run it. */
4364 if (!brand_help && precmdbuf[0] != '\0') {
4365 status = do_subproc(precmdbuf);
4366 if (subproc_status(gettext("brand-specific predetach"),
4367 status, B_FALSE) != ZONE_SUBPROC_OK) {
4369 if (execute) {
4370 assert(lockfd >= 0);
4371 zonecfg_release_lock_file(target_zone, lockfd);
4372 lockfd = -1;
4375 assert(lockfd == -1);
4376 return (Z_ERR);
4380 if (cmdbuf[0] != '\0') {
4381 /* Run the detach hook */
4382 status = do_subproc(cmdbuf);
4383 if ((status = subproc_status(gettext("brand-specific detach"),
4384 status, B_FALSE)) != ZONE_SUBPROC_OK) {
4385 if (status == ZONE_SUBPROC_USAGE && !brand_help)
4386 sub_usage(SHELP_DETACH, CMD_DETACH);
4388 if (execute) {
4389 assert(lockfd >= 0);
4390 zonecfg_release_lock_file(target_zone, lockfd);
4391 lockfd = -1;
4394 assert(lockfd == -1);
4395 return (Z_ERR);
4398 } else {
4399 zone_dochandle_t handle;
4401 /* If just help, we're done since there is no brand help. */
4402 if (brand_help) {
4403 assert(lockfd == -1);
4404 return (Z_OK);
4408 * Run the built-in detach support. Just generate a simple
4409 * zone definition XML file and detach.
4412 /* Don't detach the zone if anything is still mounted there */
4413 if (execute && zonecfg_find_mounts(zonepath, NULL, NULL)) {
4414 (void) fprintf(stderr, gettext("These file systems are "
4415 "mounted on subdirectories of %s.\n"), zonepath);
4416 (void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
4417 err = ZONE_SUBPROC_NOTCOMPLETE;
4418 goto done;
4421 if ((handle = zonecfg_init_handle()) == NULL) {
4422 zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4423 err = ZONE_SUBPROC_NOTCOMPLETE;
4424 goto done;
4427 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4428 errno = err;
4429 zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4431 } else if ((err = zonecfg_detach_save(handle,
4432 (execute ? 0 : ZONE_DRY_RUN))) != Z_OK) {
4433 errno = err;
4434 zperror(gettext("saving the detach manifest failed"),
4435 B_TRUE);
4438 zonecfg_fini_handle(handle);
4439 if (err != Z_OK)
4440 goto done;
4444 * Set the zone state back to configured unless we are running with the
4445 * no-execute option.
4447 if (execute && (err = zone_set_state(target_zone,
4448 ZONE_STATE_CONFIGURED)) != Z_OK) {
4449 errno = err;
4450 zperror(gettext("could not reset state"), B_TRUE);
4453 done:
4454 if (execute) {
4455 assert(lockfd >= 0);
4456 zonecfg_release_lock_file(target_zone, lockfd);
4457 lockfd = -1;
4460 assert(lockfd == -1);
4461 return ((err == Z_OK) ? Z_OK : Z_ERR);
4465 * Determine the brand when doing a dry-run attach. The zone does not have to
4466 * exist, so we have to read the incoming manifest to determine the zone's
4467 * brand.
4469 * Because the manifest has to be processed twice; once to determine the brand
4470 * and once to do the brand-specific attach logic, we always read it into a tmp
4471 * file. This handles the manifest coming from stdin or a regular file. The
4472 * tmpname parameter returns the name of the temporary file that the manifest
4473 * was read into.
4475 static int
4476 dryrun_get_brand(char *manifest_path, char *tmpname, int size)
4478 int fd;
4479 int err;
4480 int res = Z_OK;
4481 zone_dochandle_t local_handle;
4482 zone_dochandle_t rem_handle = NULL;
4483 int len;
4484 int ofd;
4485 char buf[512];
4487 if (strcmp(manifest_path, "-") == 0) {
4488 fd = STDIN_FILENO;
4489 } else {
4490 if ((fd = open(manifest_path, O_RDONLY)) < 0) {
4491 if (getcwd(buf, sizeof (buf)) == NULL)
4492 (void) strlcpy(buf, "/", sizeof (buf));
4493 zerror(gettext("could not open manifest path %s%s: %s"),
4494 (*manifest_path == '/' ? "" : buf), manifest_path,
4495 strerror(errno));
4496 return (Z_ERR);
4500 (void) snprintf(tmpname, size, "/var/run/zone.%d", getpid());
4502 if ((ofd = open(tmpname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) < 0) {
4503 zperror(gettext("could not save manifest"), B_FALSE);
4504 (void) close(fd);
4505 return (Z_ERR);
4508 while ((len = read(fd, buf, sizeof (buf))) > 0) {
4509 if (write(ofd, buf, len) == -1) {
4510 zperror(gettext("could not save manifest"), B_FALSE);
4511 (void) close(ofd);
4512 (void) close(fd);
4513 return (Z_ERR);
4517 if (close(ofd) != 0) {
4518 zperror(gettext("could not save manifest"), B_FALSE);
4519 (void) close(fd);
4520 return (Z_ERR);
4523 (void) close(fd);
4525 if ((fd = open(tmpname, O_RDONLY)) < 0) {
4526 zperror(gettext("could not open manifest path"), B_FALSE);
4527 return (Z_ERR);
4530 if ((local_handle = zonecfg_init_handle()) == NULL) {
4531 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4532 res = Z_ERR;
4533 goto done;
4536 if ((rem_handle = zonecfg_init_handle()) == NULL) {
4537 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4538 res = Z_ERR;
4539 goto done;
4542 if ((err = zonecfg_attach_manifest(fd, local_handle, rem_handle))
4543 != Z_OK) {
4544 res = Z_ERR;
4546 if (err == Z_INVALID_DOCUMENT) {
4547 struct stat st;
4548 char buf[6];
4550 if (strcmp(manifest_path, "-") == 0) {
4551 zerror(gettext("Input is not a valid XML "
4552 "file"));
4553 goto done;
4556 if (fstat(fd, &st) == -1 || !S_ISREG(st.st_mode)) {
4557 zerror(gettext("%s is not an XML file"),
4558 manifest_path);
4559 goto done;
4562 bzero(buf, sizeof (buf));
4563 (void) lseek(fd, 0L, SEEK_SET);
4564 if (read(fd, buf, sizeof (buf) - 1) < 0 ||
4565 strncmp(buf, "<?xml", 5) != 0)
4566 zerror(gettext("%s is not an XML file"),
4567 manifest_path);
4568 else
4569 zerror(gettext("Cannot attach to an earlier "
4570 "release of the operating system"));
4571 } else {
4572 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4574 goto done;
4577 /* Retrieve remote handle brand type. */
4578 if (zonecfg_get_brand(rem_handle, target_brand, sizeof (target_brand))
4579 != Z_OK) {
4580 zerror(gettext("missing or invalid brand"));
4581 exit(Z_ERR);
4584 done:
4585 zonecfg_fini_handle(local_handle);
4586 zonecfg_fini_handle(rem_handle);
4587 (void) close(fd);
4589 return ((res == Z_OK) ? Z_OK : Z_ERR);
4592 /* ARGSUSED */
4593 static int
4594 attach_func(int argc, char *argv[])
4596 int lockfd = -1;
4597 int err, arg;
4598 boolean_t force = B_FALSE;
4599 zone_dochandle_t handle;
4600 char zonepath[MAXPATHLEN];
4601 char cmdbuf[MAXPATHLEN];
4602 char postcmdbuf[MAXPATHLEN];
4603 boolean_t execute = B_TRUE;
4604 boolean_t brand_help = B_FALSE;
4605 char *manifest_path;
4606 char tmpmanifest[80];
4607 int manifest_pos;
4608 brand_handle_t bh = NULL;
4609 int status;
4610 int last_index = 0;
4611 int offset;
4612 char *up;
4613 boolean_t forced_update = B_FALSE;
4615 if (zonecfg_in_alt_root()) {
4616 zerror(gettext("cannot attach zone in alternate root"));
4617 return (Z_ERR);
4620 /* Check the argv string for args we handle internally */
4621 optind = 0;
4622 opterr = 0;
4623 while ((arg = getopt(argc, argv, "?Fn:U")) != EOF) {
4624 switch (arg) {
4625 case '?':
4626 if (optopt == '?') {
4627 sub_usage(SHELP_ATTACH, CMD_ATTACH);
4628 brand_help = B_TRUE;
4630 /* Ignore unknown options - may be brand specific. */
4631 break;
4632 case 'F':
4633 force = B_TRUE;
4634 break;
4635 case 'n':
4636 execute = B_FALSE;
4637 manifest_path = optarg;
4638 manifest_pos = optind - 1;
4639 break;
4640 case 'U':
4642 * Undocumented 'force update' option for p2v update on
4643 * attach when zone is in the incomplete state. Change
4644 * the option back to 'u' and set forced_update flag.
4646 if (optind == last_index)
4647 offset = optind;
4648 else
4649 offset = optind - 1;
4650 if ((up = index(argv[offset], 'U')) != NULL)
4651 *up = 'u';
4652 forced_update = B_TRUE;
4653 break;
4654 default:
4655 /* Ignore unknown options - may be brand specific. */
4656 break;
4658 last_index = optind;
4661 if (brand_help) {
4662 force = B_FALSE;
4663 execute = B_TRUE;
4666 /* dry-run and force flags are mutually exclusive */
4667 if (!execute && force) {
4668 zerror(gettext("-F and -n flags are mutually exclusive"));
4669 return (Z_ERR);
4673 * If the no-execute option was specified, we don't do validation and
4674 * need to figure out the brand, since there is no zone required to be
4675 * configured for this option.
4677 if (execute) {
4678 if (!brand_help) {
4679 if (sanity_check(target_zone, CMD_ATTACH, B_FALSE,
4680 B_TRUE, forced_update) != Z_OK)
4681 return (Z_ERR);
4682 if (verify_details(CMD_ATTACH, argv) != Z_OK)
4683 return (Z_ERR);
4686 if ((err = zone_get_zonepath(target_zone, zonepath,
4687 sizeof (zonepath))) != Z_OK) {
4688 errno = err;
4689 zperror2(target_zone,
4690 gettext("could not get zone path"));
4691 return (Z_ERR);
4693 } else {
4694 if (dryrun_get_brand(manifest_path, tmpmanifest,
4695 sizeof (tmpmanifest)) != Z_OK)
4696 return (Z_ERR);
4698 argv[manifest_pos] = tmpmanifest;
4699 target_zone = "-";
4700 (void) strlcpy(zonepath, "-", sizeof (zonepath));
4702 /* Run the brand's verify_adm hook. */
4703 if (verify_brand(NULL, CMD_ATTACH, argv) != Z_OK)
4704 return (Z_ERR);
4708 * Fetch the attach and postattach hooks from the brand configuration.
4710 if ((bh = brand_open(target_brand)) == NULL) {
4711 zerror(gettext("missing or invalid brand"));
4712 return (Z_ERR);
4715 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_attach, target_zone,
4716 zonepath) != Z_OK) {
4717 zerror("invalid brand configuration: missing attach resource");
4718 brand_close(bh);
4719 return (Z_ERR);
4722 if (get_hook(bh, postcmdbuf, sizeof (postcmdbuf), brand_get_postattach,
4723 target_zone, zonepath) != Z_OK) {
4724 zerror("invalid brand configuration: missing postattach "
4725 "resource");
4726 brand_close(bh);
4727 return (Z_ERR);
4729 brand_close(bh);
4731 /* Append all options to attach hook. */
4732 if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK)
4733 return (Z_ERR);
4735 /* Append all options to postattach hook. */
4736 if (addoptions(postcmdbuf, argv, sizeof (postcmdbuf)) != Z_OK)
4737 return (Z_ERR);
4739 if (execute && !brand_help) {
4740 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4741 zerror(gettext("another %s may have an operation in "
4742 "progress."), "zoneadm");
4743 return (Z_ERR);
4747 if (!force) {
4749 * Not a force-attach, so we need to actually do the work.
4751 if (cmdbuf[0] != '\0') {
4752 /* Run the attach hook */
4753 status = do_subproc(cmdbuf);
4754 if ((status = subproc_status(gettext("brand-specific "
4755 "attach"), status, B_FALSE)) != ZONE_SUBPROC_OK) {
4756 if (status == ZONE_SUBPROC_USAGE && !brand_help)
4757 sub_usage(SHELP_ATTACH, CMD_ATTACH);
4759 if (execute && !brand_help) {
4760 assert(zonecfg_lock_file_held(&lockfd));
4761 zonecfg_release_lock_file(target_zone,
4762 lockfd);
4763 lockfd = -1;
4766 assert(lockfd == -1);
4767 return (Z_ERR);
4772 * Else run the built-in attach support.
4773 * This is a no-op since there is nothing to validate.
4776 /* If dry-run or help, then we're done. */
4777 if (!execute || brand_help) {
4778 if (!execute)
4779 (void) unlink(tmpmanifest);
4780 assert(lockfd == -1);
4781 return (Z_OK);
4785 /* Now we can validate that the zonepath exists. */
4786 if (validate_zonepath(zonepath, CMD_ATTACH) != Z_OK) {
4787 (void) fprintf(stderr, gettext("could not verify zonepath %s "
4788 "because of the above errors.\n"), zonepath);
4790 assert(zonecfg_lock_file_held(&lockfd));
4791 zonecfg_release_lock_file(target_zone, lockfd);
4792 return (Z_ERR);
4795 if ((handle = zonecfg_init_handle()) == NULL) {
4796 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4797 err = Z_ERR;
4798 } else if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4799 errno = err;
4800 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4801 zonecfg_fini_handle(handle);
4802 } else {
4803 zonecfg_rm_detached(handle, force);
4804 zonecfg_fini_handle(handle);
4807 if (err == Z_OK &&
4808 (err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
4809 errno = err;
4810 zperror(gettext("could not reset state"), B_TRUE);
4813 assert(zonecfg_lock_file_held(&lockfd));
4814 zonecfg_release_lock_file(target_zone, lockfd);
4815 lockfd = -1;
4817 /* If we have a brand postattach hook, run it. */
4818 if (err == Z_OK && !force && postcmdbuf[0] != '\0') {
4819 status = do_subproc(postcmdbuf);
4820 if (subproc_status(gettext("brand-specific postattach"),
4821 status, B_FALSE) != ZONE_SUBPROC_OK) {
4822 if ((err = zone_set_state(target_zone,
4823 ZONE_STATE_CONFIGURED)) != Z_OK) {
4824 errno = err;
4825 zperror(gettext("could not reset state"),
4826 B_TRUE);
4831 assert(lockfd == -1);
4832 return ((err == Z_OK) ? Z_OK : Z_ERR);
4836 * On input, TRUE => yes, FALSE => no.
4837 * On return, TRUE => 1, FALSE => 0, could not ask => -1.
4840 static int
4841 ask_yesno(boolean_t default_answer, const char *question)
4843 char line[64]; /* should be large enough to answer yes or no */
4845 if (!isatty(STDIN_FILENO))
4846 return (-1);
4847 for (;;) {
4848 (void) printf("%s (%s)? ", question,
4849 default_answer ? "[y]/n" : "y/[n]");
4850 if (fgets(line, sizeof (line), stdin) == NULL ||
4851 line[0] == '\n')
4852 return (default_answer ? 1 : 0);
4853 if (tolower(line[0]) == 'y')
4854 return (1);
4855 if (tolower(line[0]) == 'n')
4856 return (0);
4860 /* ARGSUSED */
4861 static int
4862 uninstall_func(int argc, char *argv[])
4864 char line[ZONENAME_MAX + 128]; /* Enough for "Are you sure ..." */
4865 char rootpath[MAXPATHLEN], zonepath[MAXPATHLEN];
4866 char cmdbuf[MAXPATHLEN];
4867 char precmdbuf[MAXPATHLEN];
4868 boolean_t force = B_FALSE;
4869 int lockfd, answer;
4870 int err, arg;
4871 boolean_t brand_help = B_FALSE;
4872 brand_handle_t bh = NULL;
4873 int status;
4875 if (zonecfg_in_alt_root()) {
4876 zerror(gettext("cannot uninstall zone in alternate root"));
4877 return (Z_ERR);
4880 /* Check the argv string for args we handle internally */
4881 optind = 0;
4882 opterr = 0;
4883 while ((arg = getopt(argc, argv, "?F")) != EOF) {
4884 switch (arg) {
4885 case '?':
4886 if (optopt == '?') {
4887 sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
4888 brand_help = B_TRUE;
4890 /* Ignore unknown options - may be brand specific. */
4891 break;
4892 case 'F':
4893 force = B_TRUE;
4894 break;
4895 default:
4896 /* Ignore unknown options - may be brand specific. */
4897 break;
4901 if (!brand_help) {
4902 if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE,
4903 B_FALSE) != Z_OK)
4904 return (Z_ERR);
4907 * Invoke brand-specific handler.
4909 if (invoke_brand_handler(CMD_UNINSTALL, argv) != Z_OK)
4910 return (Z_ERR);
4912 if (!force) {
4913 (void) snprintf(line, sizeof (line),
4914 gettext("Are you sure you want to %s zone %s"),
4915 cmd_to_str(CMD_UNINSTALL), target_zone);
4916 if ((answer = ask_yesno(B_FALSE, line)) == 0) {
4917 return (Z_OK);
4918 } else if (answer == -1) {
4919 zerror(gettext("Input not from terminal and -F "
4920 "not specified: %s not done."),
4921 cmd_to_str(CMD_UNINSTALL));
4922 return (Z_ERR);
4927 if ((err = zone_get_zonepath(target_zone, zonepath,
4928 sizeof (zonepath))) != Z_OK) {
4929 errno = err;
4930 zperror2(target_zone, gettext("could not get zone path"));
4931 return (Z_ERR);
4935 * Fetch the uninstall and preuninstall hooks from the brand
4936 * configuration.
4938 if ((bh = brand_open(target_brand)) == NULL) {
4939 zerror(gettext("missing or invalid brand"));
4940 return (Z_ERR);
4943 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_uninstall,
4944 target_zone, zonepath) != Z_OK) {
4945 zerror("invalid brand configuration: missing uninstall "
4946 "resource");
4947 brand_close(bh);
4948 return (Z_ERR);
4951 if (get_hook(bh, precmdbuf, sizeof (precmdbuf), brand_get_preuninstall,
4952 target_zone, zonepath) != Z_OK) {
4953 zerror("invalid brand configuration: missing preuninstall "
4954 "resource");
4955 brand_close(bh);
4956 return (Z_ERR);
4958 brand_close(bh);
4960 /* Append all options to preuninstall hook. */
4961 if (addoptions(precmdbuf, argv, sizeof (precmdbuf)) != Z_OK)
4962 return (Z_ERR);
4964 /* Append all options to uninstall hook. */
4965 if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK)
4966 return (Z_ERR);
4968 if (!brand_help) {
4969 if ((err = zone_get_rootpath(target_zone, rootpath,
4970 sizeof (rootpath))) != Z_OK) {
4971 errno = err;
4972 zperror2(target_zone, gettext("could not get root "
4973 "path"));
4974 return (Z_ERR);
4978 * If there seems to be a zoneadmd running for this zone, call
4979 * it to tell it that an uninstall is happening; if all goes
4980 * well it will then shut itself down.
4982 if (zonecfg_ping_zoneadmd(target_zone) == Z_OK) {
4983 zone_cmd_arg_t zarg;
4984 zarg.cmd = Z_NOTE_UNINSTALLING;
4985 /* we don't care too much if this fails, just plow on */
4986 (void) zonecfg_call_zoneadmd(target_zone, &zarg, locale,
4987 B_TRUE);
4990 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4991 zerror(gettext("another %s may have an operation in "
4992 "progress."), "zoneadm");
4993 return (Z_ERR);
4996 /* Don't uninstall the zone if anything is mounted there */
4997 err = zonecfg_find_mounts(rootpath, NULL, NULL);
4998 if (err) {
4999 zerror(gettext("These file systems are mounted on "
5000 "subdirectories of %s.\n"), rootpath);
5001 (void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
5002 zonecfg_release_lock_file(target_zone, lockfd);
5003 return (Z_ERR);
5007 /* If we have a brand preuninstall hook, run it. */
5008 if (!brand_help && precmdbuf[0] != '\0') {
5009 status = do_subproc(precmdbuf);
5010 if (subproc_status(gettext("brand-specific preuninstall"),
5011 status, B_FALSE) != ZONE_SUBPROC_OK) {
5012 zonecfg_release_lock_file(target_zone, lockfd);
5013 return (Z_ERR);
5017 if (!brand_help) {
5018 err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
5019 if (err != Z_OK) {
5020 errno = err;
5021 zperror2(target_zone, gettext("could not set state"));
5022 goto bad;
5027 * If there is a brand uninstall hook, use it, otherwise use the
5028 * built-in uninstall code.
5030 if (cmdbuf[0] != '\0') {
5031 /* Run the uninstall hook */
5032 status = do_subproc(cmdbuf);
5033 if ((status = subproc_status(gettext("brand-specific "
5034 "uninstall"), status, B_FALSE)) != ZONE_SUBPROC_OK) {
5035 if (status == ZONE_SUBPROC_USAGE && !brand_help)
5036 sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5037 if (!brand_help)
5038 zonecfg_release_lock_file(target_zone, lockfd);
5039 return (Z_ERR);
5042 if (brand_help)
5043 return (Z_OK);
5044 } else {
5045 /* If just help, we're done since there is no brand help. */
5046 if (brand_help)
5047 return (Z_OK);
5049 /* Run the built-in uninstall support. */
5050 if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
5051 errno = err;
5052 zperror2(target_zone, gettext("cleaning up zonepath "
5053 "failed"));
5054 goto bad;
5058 err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
5059 if (err != Z_OK) {
5060 errno = err;
5061 zperror2(target_zone, gettext("could not reset state"));
5063 bad:
5064 zonecfg_release_lock_file(target_zone, lockfd);
5065 return (err);
5068 /* ARGSUSED */
5069 static int
5070 mount_func(int argc, char *argv[])
5072 zone_cmd_arg_t zarg;
5073 boolean_t force = B_FALSE;
5074 int arg;
5077 * The only supported subargument to the "mount" subcommand is
5078 * "-f", which forces us to mount a zone in the INCOMPLETE state.
5080 optind = 0;
5081 if ((arg = getopt(argc, argv, "f")) != EOF) {
5082 switch (arg) {
5083 case 'f':
5084 force = B_TRUE;
5085 break;
5086 default:
5087 return (Z_USAGE);
5090 if (argc > optind)
5091 return (Z_USAGE);
5093 if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE, force)
5094 != Z_OK)
5095 return (Z_ERR);
5096 if (verify_details(CMD_MOUNT, argv) != Z_OK)
5097 return (Z_ERR);
5099 zarg.cmd = force ? Z_FORCEMOUNT : Z_MOUNT;
5100 zarg.bootbuf[0] = '\0';
5101 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
5102 zerror(gettext("call to %s failed"), "zoneadmd");
5103 return (Z_ERR);
5105 return (Z_OK);
5108 /* ARGSUSED */
5109 static int
5110 unmount_func(int argc, char *argv[])
5112 zone_cmd_arg_t zarg;
5114 if (argc > 0)
5115 return (Z_USAGE);
5116 if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE, B_FALSE)
5117 != Z_OK)
5118 return (Z_ERR);
5120 zarg.cmd = Z_UNMOUNT;
5121 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
5122 zerror(gettext("call to %s failed"), "zoneadmd");
5123 return (Z_ERR);
5125 return (Z_OK);
5128 static int
5129 mark_func(int argc, char *argv[])
5131 int err, lockfd;
5132 int arg;
5133 boolean_t force = B_FALSE;
5134 int state;
5136 optind = 0;
5137 opterr = 0;
5138 while ((arg = getopt(argc, argv, "F")) != EOF) {
5139 switch (arg) {
5140 case 'F':
5141 force = B_TRUE;
5142 break;
5143 default:
5144 return (Z_USAGE);
5148 if (argc != (optind + 1))
5149 return (Z_USAGE);
5151 if (strcmp(argv[optind], "configured") == 0)
5152 state = ZONE_STATE_CONFIGURED;
5153 else if (strcmp(argv[optind], "incomplete") == 0)
5154 state = ZONE_STATE_INCOMPLETE;
5155 else if (strcmp(argv[optind], "installed") == 0)
5156 state = ZONE_STATE_INSTALLED;
5157 else
5158 return (Z_USAGE);
5160 if (state != ZONE_STATE_INCOMPLETE && !force)
5161 return (Z_USAGE);
5163 if (sanity_check(target_zone, CMD_MARK, B_FALSE, B_TRUE, B_FALSE)
5164 != Z_OK)
5165 return (Z_ERR);
5168 * Invoke brand-specific handler.
5170 if (invoke_brand_handler(CMD_MARK, argv) != Z_OK)
5171 return (Z_ERR);
5173 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
5174 zerror(gettext("another %s may have an operation in progress."),
5175 "zoneadm");
5176 return (Z_ERR);
5179 err = zone_set_state(target_zone, state);
5180 if (err != Z_OK) {
5181 errno = err;
5182 zperror2(target_zone, gettext("could not set state"));
5184 zonecfg_release_lock_file(target_zone, lockfd);
5186 return (err);
5190 * Check what scheduling class we're running under and print a warning if
5191 * we're not using FSS.
5193 static int
5194 check_sched_fss(zone_dochandle_t handle)
5196 char class_name[PC_CLNMSZ];
5198 if (zonecfg_get_dflt_sched_class(handle, class_name,
5199 sizeof (class_name)) != Z_OK) {
5200 zerror(gettext("WARNING: unable to determine the zone's "
5201 "scheduling class"));
5202 } else if (strcmp("FSS", class_name) != 0) {
5203 zerror(gettext("WARNING: The zone.cpu-shares rctl is set but\n"
5204 "FSS is not the default scheduling class for this zone. "
5205 "FSS will be\nused for processes in the zone but to get "
5206 "the full benefit of FSS,\nit should be the default "
5207 "scheduling class. See dispadmin(8) for\nmore details."));
5208 return (Z_SYSTEM);
5211 return (Z_OK);
5214 static int
5215 check_cpu_shares_sched(zone_dochandle_t handle)
5217 int err;
5218 int res = Z_OK;
5219 struct zone_rctltab rctl;
5221 if ((err = zonecfg_setrctlent(handle)) != Z_OK) {
5222 errno = err;
5223 zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5224 return (err);
5227 while (zonecfg_getrctlent(handle, &rctl) == Z_OK) {
5228 if (strcmp(rctl.zone_rctl_name, "zone.cpu-shares") == 0) {
5229 if (check_sched_fss(handle) != Z_OK)
5230 res = Z_SYSTEM;
5231 break;
5235 (void) zonecfg_endrctlent(handle);
5237 return (res);
5241 * Check if there is a mix of processes running in different pools within the
5242 * zone. This is currently only going to be called for the global zone from
5243 * apply_func but that could be generalized in the future.
5245 static boolean_t
5246 mixed_pools(zoneid_t zoneid)
5248 DIR *dirp;
5249 dirent_t *dent;
5250 boolean_t mixed = B_FALSE;
5251 boolean_t poolid_set = B_FALSE;
5252 poolid_t last_poolid = 0;
5254 if ((dirp = opendir("/proc")) == NULL) {
5255 zerror(gettext("could not open /proc"));
5256 return (B_FALSE);
5259 while ((dent = readdir(dirp)) != NULL) {
5260 int procfd;
5261 psinfo_t ps;
5262 char procpath[MAXPATHLEN];
5264 if (dent->d_name[0] == '.')
5265 continue;
5267 (void) snprintf(procpath, sizeof (procpath), "/proc/%s/psinfo",
5268 dent->d_name);
5270 if ((procfd = open(procpath, O_RDONLY)) == -1)
5271 continue;
5273 if (read(procfd, &ps, sizeof (ps)) == sizeof (psinfo_t)) {
5274 /* skip processes in other zones and system processes */
5275 if (zoneid != ps.pr_zoneid || ps.pr_flag & SSYS) {
5276 (void) close(procfd);
5277 continue;
5280 if (poolid_set) {
5281 if (ps.pr_poolid != last_poolid)
5282 mixed = B_TRUE;
5283 } else {
5284 last_poolid = ps.pr_poolid;
5285 poolid_set = B_TRUE;
5289 (void) close(procfd);
5291 if (mixed)
5292 break;
5295 (void) closedir(dirp);
5297 return (mixed);
5301 * Check if a persistent or temporary pool is configured for the zone.
5302 * This is currently only going to be called for the global zone from
5303 * apply_func but that could be generalized in the future.
5305 static boolean_t
5306 pool_configured(zone_dochandle_t handle)
5308 int err1, err2;
5309 struct zone_psettab pset_tab;
5310 char poolname[MAXPATHLEN];
5312 err1 = zonecfg_lookup_pset(handle, &pset_tab);
5313 err2 = zonecfg_get_pool(handle, poolname, sizeof (poolname));
5315 if (err1 == Z_NO_ENTRY &&
5316 (err2 == Z_NO_ENTRY || (err2 == Z_OK && strlen(poolname) == 0)))
5317 return (B_FALSE);
5319 return (B_TRUE);
5323 * This is an undocumented interface which is currently only used to apply
5324 * the global zone resource management settings when the system boots.
5325 * This function does not yet properly handle updating a running system so
5326 * any projects running in the zone would be trashed if this function
5327 * were to run after the zone had booted. It also does not reset any
5328 * rctl settings that were removed from zonecfg. There is still work to be
5329 * done before we can properly support dynamically updating the resource
5330 * management settings for a running zone (global or non-global). Thus, this
5331 * functionality is undocumented for now.
5333 /* ARGSUSED */
5334 static int
5335 apply_func(int argc, char *argv[])
5337 int err;
5338 int res = Z_OK;
5339 priv_set_t *privset;
5340 zoneid_t zoneid;
5341 zone_dochandle_t handle;
5342 struct zone_mcaptab mcap;
5343 char pool_err[128];
5345 zoneid = getzoneid();
5347 if (zonecfg_in_alt_root() || zoneid != GLOBAL_ZONEID ||
5348 target_zone == NULL || strcmp(target_zone, GLOBAL_ZONENAME) != 0)
5349 return (usage(B_FALSE));
5351 if ((privset = priv_allocset()) == NULL) {
5352 zerror(gettext("%s failed"), "priv_allocset");
5353 return (Z_ERR);
5356 if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
5357 zerror(gettext("%s failed"), "getppriv");
5358 priv_freeset(privset);
5359 return (Z_ERR);
5362 if (priv_isfullset(privset) == B_FALSE) {
5363 (void) usage(B_FALSE);
5364 priv_freeset(privset);
5365 return (Z_ERR);
5367 priv_freeset(privset);
5369 if ((handle = zonecfg_init_handle()) == NULL) {
5370 zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5371 return (Z_ERR);
5374 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
5375 errno = err;
5376 zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5377 zonecfg_fini_handle(handle);
5378 return (Z_ERR);
5381 /* specific error msgs are printed within apply_rctls */
5382 if ((err = zonecfg_apply_rctls(target_zone, handle)) != Z_OK) {
5383 errno = err;
5384 zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5385 res = Z_ERR;
5388 if ((err = check_cpu_shares_sched(handle)) != Z_OK)
5389 res = Z_ERR;
5391 if (pool_configured(handle)) {
5392 if (mixed_pools(zoneid)) {
5393 zerror(gettext("Zone is using multiple resource "
5394 "pools. The pool\nconfiguration cannot be "
5395 "applied without rebooting."));
5396 res = Z_ERR;
5397 } else {
5400 * The next two blocks of code attempt to set up
5401 * temporary pools as well as persistent pools. In
5402 * both cases we call the functions unconditionally.
5403 * Within each funtion the code will check if the zone
5404 * is actually configured for a temporary pool or
5405 * persistent pool and just return if there is nothing
5406 * to do.
5408 if ((err = zonecfg_bind_tmp_pool(handle, zoneid,
5409 pool_err, sizeof (pool_err))) != Z_OK) {
5410 if (err == Z_POOL || err == Z_POOL_CREATE ||
5411 err == Z_POOL_BIND)
5412 zerror("%s: %s", zonecfg_strerror(err),
5413 pool_err);
5414 else
5415 zerror(gettext("could not bind zone to "
5416 "temporary pool: %s"),
5417 zonecfg_strerror(err));
5418 res = Z_ERR;
5421 if ((err = zonecfg_bind_pool(handle, zoneid, pool_err,
5422 sizeof (pool_err))) != Z_OK) {
5423 if (err == Z_POOL || err == Z_POOL_BIND)
5424 zerror("%s: %s", zonecfg_strerror(err),
5425 pool_err);
5426 else
5427 zerror("%s", zonecfg_strerror(err));
5433 * If a memory cap is configured, set the cap in the kernel using
5434 * zone_setattr() and make sure the rcapd SMF service is enabled.
5436 if (zonecfg_getmcapent(handle, &mcap) == Z_OK) {
5437 uint64_t num;
5438 char smf_err[128];
5440 num = (uint64_t)strtoll(mcap.zone_physmem_cap, NULL, 10);
5441 if (zone_setattr(zoneid, ZONE_ATTR_PHYS_MCAP, &num, 0) == -1) {
5442 zerror(gettext("could not set zone memory cap"));
5443 res = Z_ERR;
5446 if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
5447 zerror(gettext("enabling system/rcap service failed: "
5448 "%s"), smf_err);
5449 res = Z_ERR;
5453 zonecfg_fini_handle(handle);
5455 return (res);
5459 * This is an undocumented interface that is invoked by the zones SMF service
5460 * for installed zones that won't automatically boot.
5462 /* ARGSUSED */
5463 static int
5464 sysboot_func(int argc, char *argv[])
5466 int err;
5467 zone_dochandle_t zone_handle;
5468 brand_handle_t brand_handle;
5469 char cmdbuf[MAXPATHLEN];
5470 char zonepath[MAXPATHLEN];
5473 * This subcommand can only be executed in the global zone on non-global
5474 * zones.
5476 if (zonecfg_in_alt_root())
5477 return (usage(B_FALSE));
5478 if (sanity_check(target_zone, CMD_SYSBOOT, B_FALSE, B_TRUE, B_FALSE) !=
5479 Z_OK)
5480 return (Z_ERR);
5483 * Fetch the sysboot hook from the target zone's brand.
5485 if ((zone_handle = zonecfg_init_handle()) == NULL) {
5486 zperror(cmd_to_str(CMD_SYSBOOT), B_TRUE);
5487 return (Z_ERR);
5489 if ((err = zonecfg_get_handle(target_zone, zone_handle)) != Z_OK) {
5490 errno = err;
5491 zperror(cmd_to_str(CMD_SYSBOOT), B_TRUE);
5492 zonecfg_fini_handle(zone_handle);
5493 return (Z_ERR);
5495 if ((err = zonecfg_get_zonepath(zone_handle, zonepath,
5496 sizeof (zonepath))) != Z_OK) {
5497 errno = err;
5498 zperror(cmd_to_str(CMD_SYSBOOT), B_TRUE);
5499 zonecfg_fini_handle(zone_handle);
5500 return (Z_ERR);
5502 if ((brand_handle = brand_open(target_brand)) == NULL) {
5503 zerror(gettext("missing or invalid brand during %s operation: "
5504 "%s"), cmd_to_str(CMD_SYSBOOT), target_brand);
5505 zonecfg_fini_handle(zone_handle);
5506 return (Z_ERR);
5508 err = get_hook(brand_handle, cmdbuf, sizeof (cmdbuf), brand_get_sysboot,
5509 target_zone, zonepath);
5510 brand_close(brand_handle);
5511 zonecfg_fini_handle(zone_handle);
5512 if (err != Z_OK) {
5513 zerror(gettext("unable to get brand hook from brand %s for %s "
5514 "operation"), target_brand, cmd_to_str(CMD_SYSBOOT));
5515 return (Z_ERR);
5519 * If the hook wasn't defined (which is OK), then indicate success and
5520 * return. Otherwise, execute the hook.
5522 if (cmdbuf[0] != '\0')
5523 return ((subproc_status(gettext("brand sysboot operation"),
5524 do_subproc(cmdbuf), B_FALSE) == ZONE_SUBPROC_OK) ? Z_OK :
5525 Z_BRAND_ERROR);
5526 return (Z_OK);
5529 static int
5530 help_func(int argc, char *argv[])
5532 int arg, cmd_num;
5534 if (argc == 0) {
5535 (void) usage(B_TRUE);
5536 return (Z_OK);
5538 optind = 0;
5539 if ((arg = getopt(argc, argv, "?")) != EOF) {
5540 switch (arg) {
5541 case '?':
5542 sub_usage(SHELP_HELP, CMD_HELP);
5543 return (optopt == '?' ? Z_OK : Z_USAGE);
5544 default:
5545 sub_usage(SHELP_HELP, CMD_HELP);
5546 return (Z_USAGE);
5549 while (optind < argc) {
5550 /* Private commands have NULL short_usage; omit them */
5551 if ((cmd_num = cmd_match(argv[optind])) < 0 ||
5552 cmdtab[cmd_num].short_usage == NULL) {
5553 sub_usage(SHELP_HELP, CMD_HELP);
5554 return (Z_USAGE);
5556 sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
5557 optind++;
5559 return (Z_OK);
5563 * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
5566 static int
5567 cmd_match(char *cmd)
5569 int i;
5571 for (i = CMD_MIN; i <= CMD_MAX; i++) {
5572 /* return only if there is an exact match */
5573 if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
5574 return (cmdtab[i].cmd_num);
5576 return (-1);
5579 static int
5580 parse_and_run(int argc, char *argv[])
5582 int i = cmd_match(argv[0]);
5584 if (i < 0)
5585 return (usage(B_FALSE));
5586 return (cmdtab[i].handler(argc - 1, &(argv[1])));
5589 static char *
5590 get_execbasename(char *execfullname)
5592 char *last_slash, *execbasename;
5594 /* guard against '/' at end of command invocation */
5595 for (;;) {
5596 last_slash = strrchr(execfullname, '/');
5597 if (last_slash == NULL) {
5598 execbasename = execfullname;
5599 break;
5600 } else {
5601 execbasename = last_slash + 1;
5602 if (*execbasename == '\0') {
5603 *last_slash = '\0';
5604 continue;
5606 break;
5609 return (execbasename);
5612 static char *
5613 get_username()
5615 uid_t uid;
5616 struct passwd *nptr;
5620 * Authorizations are checked to restrict access based on the
5621 * requested operation and zone name, It is assumed that the
5622 * program is running with all privileges, but that the real
5623 * user ID is that of the user or role on whose behalf we are
5624 * operating. So we start by getting the username that will be
5625 * used for subsequent authorization checks.
5628 uid = getuid();
5629 if ((nptr = getpwuid(uid)) == NULL) {
5630 zerror(gettext("could not get user name."));
5631 exit(Z_ERR);
5633 return (nptr->pw_name);
5637 main(int argc, char **argv)
5639 int arg;
5640 zoneid_t zid;
5641 struct stat st;
5642 char *zone_lock_env;
5643 int err;
5645 if ((locale = setlocale(LC_ALL, "")) == NULL)
5646 locale = "C";
5647 (void) textdomain(TEXT_DOMAIN);
5648 setbuf(stdout, NULL);
5649 (void) sigset(SIGHUP, SIG_IGN);
5650 execname = get_execbasename(argv[0]);
5651 username = get_username();
5652 target_zone = NULL;
5653 if (chdir("/") != 0) {
5654 zerror(gettext("could not change directory to /."));
5655 exit(Z_ERR);
5659 * Use the default system mask rather than anything that may have been
5660 * set by the caller.
5662 (void) umask(CMASK);
5664 if (init_zfs() != Z_OK)
5665 exit(Z_ERR);
5667 while ((arg = getopt(argc, argv, "?u:z:R:")) != EOF) {
5668 switch (arg) {
5669 case '?':
5670 return (usage(B_TRUE));
5671 case 'u':
5672 target_uuid = optarg;
5673 break;
5674 case 'z':
5675 target_zone = optarg;
5676 break;
5677 case 'R': /* private option for admin/install use */
5678 if (*optarg != '/') {
5679 zerror(gettext("root path must be absolute."));
5680 exit(Z_ERR);
5682 if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
5683 zerror(
5684 gettext("root path must be a directory."));
5685 exit(Z_ERR);
5687 zonecfg_set_root(optarg);
5688 break;
5689 default:
5690 return (usage(B_FALSE));
5694 if (optind >= argc)
5695 return (usage(B_FALSE));
5697 if (target_uuid != NULL && *target_uuid != '\0') {
5698 uuid_t uuid;
5699 static char newtarget[ZONENAME_MAX];
5701 if (uuid_parse(target_uuid, uuid) == -1) {
5702 zerror(gettext("illegal UUID value specified"));
5703 exit(Z_ERR);
5705 if (zonecfg_get_name_by_uuid(uuid, newtarget,
5706 sizeof (newtarget)) == Z_OK)
5707 target_zone = newtarget;
5710 if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
5711 errno = Z_NO_ZONE;
5712 zperror(target_zone, B_TRUE);
5713 exit(Z_ERR);
5717 * See if we have inherited the right to manipulate this zone from
5718 * a zoneadm instance in our ancestry. If so, set zone_lock_cnt to
5719 * indicate it. If not, make that explicit in our environment.
5721 zonecfg_init_lock_file(target_zone, &zone_lock_env);
5723 /* Figure out what the system's default brand is */
5724 if (zonecfg_default_brand(default_brand,
5725 sizeof (default_brand)) != Z_OK) {
5726 zerror(gettext("unable to determine default brand"));
5727 return (Z_ERR);
5731 * If we are going to be operating on a single zone, retrieve its
5732 * brand type and determine whether it is native or not.
5734 if ((target_zone != NULL) &&
5735 (strcmp(target_zone, GLOBAL_ZONENAME) != 0)) {
5736 if (zone_get_brand(target_zone, target_brand,
5737 sizeof (target_brand)) != Z_OK) {
5738 zerror(gettext("missing or invalid brand"));
5739 exit(Z_ERR);
5742 * In the alternate root environment, the only supported
5743 * operations are mount and unmount. In this case, just treat
5744 * the zone as native if it is cluster. Cluster zones can be
5745 * native for the purpose of LU or upgrade, and the cluster
5746 * brand may not exist in the miniroot (such as in net install
5747 * upgrade).
5749 if (strcmp(target_brand, CLUSTER_BRAND_NAME) == 0) {
5750 if (zonecfg_in_alt_root()) {
5751 (void) strlcpy(target_brand, default_brand,
5752 sizeof (target_brand));
5757 err = parse_and_run(argc - optind, &argv[optind]);
5759 return (err);