1 /*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22 /*
23 * Copyright (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 2015, Joyent Inc. All rights reserved.
27 */
28
29 /*
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.
35 *
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.
41 */
42
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 <bsm/adt.h>
58 #include <sys/brand.h>
59 #include <sys/param.h>
60 #include <sys/types.h>
61 #include <sys/stat.h>
62 #include <sys/statvfs.h>
63 #include <assert.h>
64 #include <sys/sockio.h>
65 #include <sys/mntent.h>
66 #include <limits.h>
67 #include <dirent.h>
68 #include <uuid/uuid.h>
69 #include <fcntl.h>
70 #include <door.h>
71 #include <macros.h>
72 #include <libgen.h>
73 #include <fnmatch.h>
74 #include <sys/modctl.h>
75 #include <libbrand.h>
76 #include <libscf.h>
77 #include <procfs.h>
78 #include <strings.h>
79 #include <pool.h>
80 #include <sys/pool.h>
81 #include <sys/priocntl.h>
82 #include <sys/fsspriocntl.h>
83 #include <libdladm.h>
84 #include <libdllink.h>
85 #include <pwd.h>
86 #include <auth_list.h>
87 #include <auth_attr.h>
88 #include <secdb.h>
89
90 #include "zoneadm.h"
91
92 #define MAXARGS 8
93 #define SOURCE_ZONE (CMD_MAX + 1)
94
95 /* Reflects kernel zone entries */
96 typedef struct zone_entry {
97 zoneid_t zid;
98 char zname[ZONENAME_MAX];
99 char *zstate_str;
100 zone_state_t zstate_num;
101 char zbrand[MAXNAMELEN];
102 char zroot[MAXPATHLEN];
103 char zuuid[UUID_PRINTABLE_STRING_LENGTH];
104 zone_iptype_t ziptype;
105 zoneid_t zdid;
106 } zone_entry_t;
107
108 #define CLUSTER_BRAND_NAME "cluster"
109
110 static zone_entry_t *zents;
111 static size_t nzents;
112
113 #define LOOPBACK_IF "lo0"
114 #define SOCKET_AF(af) (((af) == AF_UNSPEC) ? AF_INET : (af))
115
116 struct net_if {
117 char *name;
118 int af;
119 };
120
121 /* 0755 is the default directory mode. */
122 #define DEFAULT_DIR_MODE \
123 (S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
124
125 struct cmd {
126 uint_t cmd_num; /* command number */
127 char *cmd_name; /* command name */
128 char *short_usage; /* short form help */
129 int (*handler)(int argc, char *argv[]); /* function to call */
130
131 };
132
133 #define SHELP_HELP "help"
134 #define SHELP_BOOT "boot [-- boot_arguments]"
135 #define SHELP_HALT "halt"
136 #define SHELP_READY "ready"
137 #define SHELP_SHUTDOWN "shutdown [-r [-- boot_arguments]]"
138 #define SHELP_REBOOT "reboot [-- boot_arguments]"
139 #define SHELP_LIST "list [-cipv]"
140 #define SHELP_VERIFY "verify"
141 #define SHELP_INSTALL "install [brand-specific args]"
142 #define SHELP_UNINSTALL "uninstall [-F] [brand-specific args]"
143 #define SHELP_CLONE "clone [-m method] [-s <ZFS snapshot>] "\
144 "[brand-specific args] zonename"
145 #define SHELP_MOVE "move zonepath"
146 #define SHELP_DETACH "detach [-n] [brand-specific args]"
147 #define SHELP_ATTACH "attach [-F] [-n <path>] [brand-specific args]"
148 #define SHELP_MARK "mark incomplete"
149
150 #define EXEC_PREFIX "exec "
151 #define EXEC_LEN (strlen(EXEC_PREFIX))
152 #define RMCOMMAND "/usr/bin/rm -rf"
153
154 static int cleanup_zonepath(char *, boolean_t);
155
156
157 static int help_func(int argc, char *argv[]);
158 static int ready_func(int argc, char *argv[]);
159 static int boot_func(int argc, char *argv[]);
160 static int shutdown_func(int argc, char *argv[]);
161 static int halt_func(int argc, char *argv[]);
162 static int reboot_func(int argc, char *argv[]);
163 static int list_func(int argc, char *argv[]);
164 static int verify_func(int argc, char *argv[]);
165 static int install_func(int argc, char *argv[]);
166 static int uninstall_func(int argc, char *argv[]);
167 static int mount_func(int argc, char *argv[]);
168 static int unmount_func(int argc, char *argv[]);
169 static int clone_func(int argc, char *argv[]);
170 static int move_func(int argc, char *argv[]);
171 static int detach_func(int argc, char *argv[]);
172 static int attach_func(int argc, char *argv[]);
173 static int mark_func(int argc, char *argv[]);
174 static int apply_func(int argc, char *argv[]);
175 static int sysboot_func(int argc, char *argv[]);
176 static int sanity_check(char *zone, int cmd_num, boolean_t running,
177 boolean_t unsafe_when_running, boolean_t force);
178 static int cmd_match(char *cmd);
179 static int verify_details(int, char *argv[]);
180 static int verify_brand(zone_dochandle_t, int, char *argv[]);
181 static int invoke_brand_handler(int, char *argv[]);
182
183 static struct cmd cmdtab[] = {
184 { CMD_HELP, "help", SHELP_HELP, help_func },
185 { CMD_BOOT, "boot", SHELP_BOOT, boot_func },
186 { CMD_HALT, "halt", SHELP_HALT, halt_func },
187 { CMD_READY, "ready", SHELP_READY, ready_func },
188 { CMD_SHUTDOWN, "shutdown", SHELP_SHUTDOWN, shutdown_func },
189 { CMD_REBOOT, "reboot", SHELP_REBOOT, reboot_func },
190 { CMD_LIST, "list", SHELP_LIST, list_func },
191 { CMD_VERIFY, "verify", SHELP_VERIFY, verify_func },
192 { CMD_INSTALL, "install", SHELP_INSTALL, install_func },
193 { CMD_UNINSTALL, "uninstall", SHELP_UNINSTALL,
194 uninstall_func },
195 /* mount and unmount are private commands for admin/install */
196 { CMD_MOUNT, "mount", NULL, mount_func },
197 { CMD_UNMOUNT, "unmount", NULL, unmount_func },
198 { CMD_CLONE, "clone", SHELP_CLONE, clone_func },
199 { CMD_MOVE, "move", SHELP_MOVE, move_func },
200 { CMD_DETACH, "detach", SHELP_DETACH, detach_func },
201 { CMD_ATTACH, "attach", SHELP_ATTACH, attach_func },
202 { CMD_MARK, "mark", SHELP_MARK, mark_func },
203 { CMD_APPLY, "apply", NULL, apply_func },
204 { CMD_SYSBOOT, "sysboot", NULL, sysboot_func }
205 };
206
207 /* global variables */
208
209 /* set early in main(), never modified thereafter, used all over the place */
210 static char *execname;
211 static char target_brand[MAXNAMELEN];
212 static char default_brand[MAXPATHLEN];
213 static char *locale;
214 char *target_zone;
215 static char *target_uuid;
216 char *username;
217
218 char *
219 cmd_to_str(int cmd_num)
220 {
221 assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
222 return (cmdtab[cmd_num].cmd_name);
223 }
224
225 /* This is a separate function because of gettext() wrapping. */
226 static char *
227 long_help(int cmd_num)
228 {
229 assert(cmd_num >= CMD_MIN && cmd_num <= CMD_MAX);
230 switch (cmd_num) {
231 case CMD_HELP:
232 return (gettext("Print usage message."));
233 case CMD_BOOT:
234 return (gettext("Activates (boots) specified zone. See "
235 "zoneadm(1m) for valid boot\n\targuments."));
236 case CMD_HALT:
237 return (gettext("Halts specified zone, bypassing shutdown "
238 "scripts and removing runtime\n\tresources of the zone."));
239 case CMD_READY:
240 return (gettext("Prepares a zone for running applications but "
241 "does not start any user\n\tprocesses in the zone."));
242 case CMD_SHUTDOWN:
243 return (gettext("Gracefully shutdown the zone or reboot if "
244 "the '-r' option is specified.\n\t"
245 "See zoneadm(1m) for valid boot arguments."));
246 case CMD_REBOOT:
247 return (gettext("Restarts the zone (equivalent to a halt / "
248 "boot sequence).\n\tFails if the zone is not active. "
249 "See zoneadm(1m) for valid boot\n\targuments."));
250 case CMD_LIST:
251 return (gettext("Lists the current zones, or a "
252 "specific zone if indicated. By default,\n\tall "
253 "running zones are listed, though this can be "
254 "expanded to all\n\tinstalled zones with the -i "
255 "option or all configured zones with the\n\t-c "
256 "option. When used with the general -z <zone> and/or -u "
257 "<uuid-match>\n\toptions, lists only the specified "
258 "matching zone, but lists it\n\tregardless of its state, "
259 "and the -i and -c options are disallowed. The\n\t-v "
260 "option can be used to display verbose information: zone "
261 "name, id,\n\tcurrent state, root directory and options. "
262 "The -p option can be used\n\tto request machine-parsable "
263 "output. The -v and -p options are mutually\n\texclusive."
264 " If neither -v nor -p is used, just the zone name is "
265 "listed."));
266 case CMD_VERIFY:
267 return (gettext("Check to make sure the configuration "
268 "can safely be instantiated\n\ton the machine: "
269 "physical network interfaces exist, etc."));
270 case CMD_INSTALL:
271 return (gettext("Install the configuration on to the system. "
272 "All arguments are passed to the brand installation "
273 "function;\n\tsee brands(5) for more information."));
274 case CMD_UNINSTALL:
275 return (gettext("Uninstall the configuration from the system. "
276 "The -F flag can be used\n\tto force the action. All "
277 "other arguments are passed to the brand\n\tuninstall "
278 "function; see brands(5) for more information."));
279 case CMD_CLONE:
280 return (gettext("Clone the installation of another zone. "
281 "The -m option can be used to\n\tspecify 'copy' which "
282 "forces a copy of the source zone. The -s option\n\t"
283 "can be used to specify the name of a ZFS snapshot "
284 "that was taken from\n\ta previous clone command. The "
285 "snapshot will be used as the source\n\tinstead of "
286 "creating a new ZFS snapshot. All other arguments are "
287 "passed\n\tto the brand clone function; see "
288 "brands(5) for more information."));
289 case CMD_MOVE:
290 return (gettext("Move the zone to a new zonepath."));
291 case CMD_DETACH:
292 return (gettext("Detach the zone from the system. The zone "
293 "state is changed to\n\t'configured' (but the files under "
294 "the zonepath are untouched).\n\tThe zone can subsequently "
295 "be attached, or can be moved to another\n\tsystem and "
296 "attached there. The -n option can be used to specify\n\t"
297 "'no-execute' mode. When -n is used, the information "
298 "needed to attach\n\tthe zone is sent to standard output "
299 "but the zone is not actually\n\tdetached. All other "
300 "arguments are passed to the brand detach function;\n\tsee "
301 "brands(5) for more information."));
302 case CMD_ATTACH:
303 return (gettext("Attach the zone to the system. The zone "
304 "state must be 'configured'\n\tprior to attach; upon "
305 "successful completion, the zone state will be\n\t"
306 "'installed'. The system software on the current "
307 "system must be\n\tcompatible with the software on the "
308 "zone's original system.\n\tSpecify -F "
309 "to force the attach and skip software compatibility "
310 "tests.\n\tThe -n option can be used to specify "
311 "'no-execute' mode. When -n is\n\tused, the information "
312 "needed to attach the zone is read from the\n\tspecified "
313 "path and the configuration is only validated. The path "
314 "can\n\tbe '-' to specify standard input. The -F and -n "
315 "options are mutually\n\texclusive. All other arguments "
316 "are passed to the brand attach\n\tfunction; see "
317 "brands(5) for more information."));
318 case CMD_MARK:
319 return (gettext("Set the state of the zone. This can be used "
320 "to force the zone\n\tstate to 'incomplete' "
321 "administratively if some activity has rendered\n\tthe "
322 "zone permanently unusable. The only valid state that "
323 "may be\n\tspecified is 'incomplete'."));
324 default:
325 return ("");
326 }
327 /* NOTREACHED */
328 return (NULL);
329 }
330
331 /*
332 * Called with explicit B_TRUE when help is explicitly requested, B_FALSE for
333 * unexpected errors.
334 */
335
336 static int
337 usage(boolean_t explicit)
338 {
339 int i;
340 FILE *fd = explicit ? stdout : stderr;
341
342 (void) fprintf(fd, "%s:\t%s help\n", gettext("usage"), execname);
343 (void) fprintf(fd, "\t%s [-z <zone>] [-u <uuid-match>] list\n",
344 execname);
345 (void) fprintf(fd, "\t%s {-z <zone>|-u <uuid-match>} <%s>\n", execname,
346 gettext("subcommand"));
347 (void) fprintf(fd, "\n%s:\n\n", gettext("Subcommands"));
348 for (i = CMD_MIN; i <= CMD_MAX; i++) {
349 if (cmdtab[i].short_usage == NULL)
350 continue;
351 (void) fprintf(fd, "%s\n", cmdtab[i].short_usage);
352 if (explicit)
353 (void) fprintf(fd, "\t%s\n\n", long_help(i));
354 }
355 if (!explicit)
356 (void) fputs("\n", fd);
357 return (Z_USAGE);
358 }
359
360 static void
361 sub_usage(char *short_usage, int cmd_num)
362 {
363 (void) fprintf(stderr, "%s:\t%s\n", gettext("usage"), short_usage);
364 (void) fprintf(stderr, "\t%s\n", long_help(cmd_num));
365 }
366
367 /*
368 * zperror() is like perror(3c) except that this also prints the executable
369 * name at the start of the message, and takes a boolean indicating whether
370 * to call libc'c strerror() or that from libzonecfg.
371 */
372
373 void
374 zperror(const char *str, boolean_t zonecfg_error)
375 {
376 (void) fprintf(stderr, "%s: %s: %s\n", execname, str,
377 zonecfg_error ? zonecfg_strerror(errno) : strerror(errno));
378 }
379
380 /*
381 * zperror2() is very similar to zperror() above, except it also prints a
382 * supplied zone name after the executable.
383 *
384 * All current consumers of this function want libzonecfg's strerror() rather
385 * than libc's; if this ever changes, this function can be made more generic
386 * like zperror() above.
387 */
388
389 void
390 zperror2(const char *zone, const char *str)
391 {
392 (void) fprintf(stderr, "%s: %s: %s: %s\n", execname, zone, str,
393 zonecfg_strerror(errno));
394 }
395
396 /* PRINTFLIKE1 */
397 void
398 zerror(const char *fmt, ...)
399 {
400 va_list alist;
401
402 va_start(alist, fmt);
403 (void) fprintf(stderr, "%s: ", execname);
404 if (target_zone != NULL)
405 (void) fprintf(stderr, "zone '%s': ", target_zone);
406 (void) vfprintf(stderr, fmt, alist);
407 (void) fprintf(stderr, "\n");
408 va_end(alist);
409 }
410
411 static void *
412 safe_calloc(size_t nelem, size_t elsize)
413 {
414 void *r = calloc(nelem, elsize);
415
416 if (r == NULL) {
417 zerror(gettext("failed to allocate %lu bytes: %s"),
418 (ulong_t)nelem * elsize, strerror(errno));
419 exit(Z_ERR);
420 }
421 return (r);
422 }
423
424 static void
425 zone_print(zone_entry_t *zent, boolean_t verbose, boolean_t parsable)
426 {
427 static boolean_t firsttime = B_TRUE;
428 char *ip_type_str;
429
430 /* Skip a zone that shutdown while we were collecting data. */
431 if (zent->zname[0] == '\0')
432 return;
433
434 if (zent->ziptype == ZS_EXCLUSIVE)
435 ip_type_str = "excl";
436 else
437 ip_type_str = "shared";
438
439 assert(!(verbose && parsable));
440 if (firsttime && verbose) {
441 firsttime = B_FALSE;
442 (void) printf("%*s %-16s %-10s %-30s %-8s %-6s\n",
443 ZONEID_WIDTH, "ID", "NAME", "STATUS", "PATH", "BRAND",
444 "IP");
445 }
446 if (!verbose) {
447 char *cp, *clim;
448 char zdid[80];
449
450 if (!parsable) {
451 (void) printf("%s\n", zent->zname);
452 return;
453 }
454 if (zent->zid == ZONE_ID_UNDEFINED)
455 (void) printf("-");
456 else
457 (void) printf("%lu", zent->zid);
458 (void) printf(":%s:%s:", zent->zname, zent->zstate_str);
459 cp = zent->zroot;
460 while ((clim = strchr(cp, ':')) != NULL) {
461 (void) printf("%.*s\\:", clim - cp, cp);
462 cp = clim + 1;
463 }
464 if (zent->zdid == -1)
465 zdid[0] = '\0';
466 else
467 (void) snprintf(zdid, sizeof (zdid), "%d", zent->zdid);
468 (void) printf("%s:%s:%s:%s:%s\n", cp, zent->zuuid, zent->zbrand,
469 ip_type_str, zdid);
470 return;
471 }
472 if (zent->zstate_str != NULL) {
473 if (zent->zid == ZONE_ID_UNDEFINED)
474 (void) printf("%*s", ZONEID_WIDTH, "-");
475 else
476 (void) printf("%*lu", ZONEID_WIDTH, zent->zid);
477 (void) printf(" %-16s %-10s %-30s %-8s %-6s\n", zent->zname,
478 zent->zstate_str, zent->zroot, zent->zbrand, ip_type_str);
479 }
480 }
481
482 static int
483 lookup_zone_info(const char *zone_name, zoneid_t zid, zone_entry_t *zent)
484 {
485 char root[MAXPATHLEN], *cp;
486 int err;
487 uuid_t uuid;
488 zone_dochandle_t handle;
489
490 (void) strlcpy(zent->zname, zone_name, sizeof (zent->zname));
491 (void) strlcpy(zent->zroot, "???", sizeof (zent->zroot));
492 (void) strlcpy(zent->zbrand, "???", sizeof (zent->zbrand));
493 zent->zstate_str = "???";
494
495 zent->zid = zid;
496
497 if (zonecfg_get_uuid(zone_name, uuid) == Z_OK &&
498 !uuid_is_null(uuid))
499 uuid_unparse(uuid, zent->zuuid);
500 else
501 zent->zuuid[0] = '\0';
502
503 /*
504 * For labeled zones which query the zone path of lower-level
505 * zones, the path needs to be adjusted to drop the final
506 * "/root" component. This adjusted path is then useful
507 * for reading down any exported directories from the
508 * lower-level zone.
509 */
510 if (is_system_labeled() && zent->zid != ZONE_ID_UNDEFINED) {
511 if (zone_getattr(zent->zid, ZONE_ATTR_ROOT, zent->zroot,
512 sizeof (zent->zroot)) == -1) {
513 zperror2(zent->zname,
514 gettext("could not get zone path."));
515 return (Z_ERR);
516 }
517 cp = zent->zroot + strlen(zent->zroot) - 5;
518 if (cp > zent->zroot && strcmp(cp, "/root") == 0)
519 *cp = 0;
520 } else {
521 if ((err = zone_get_zonepath(zent->zname, root,
522 sizeof (root))) != Z_OK) {
523 errno = err;
524 zperror2(zent->zname,
525 gettext("could not get zone path."));
526 return (Z_ERR);
527 }
528 (void) strlcpy(zent->zroot, root, sizeof (zent->zroot));
529 }
530
531 if ((err = zone_get_state(zent->zname, &zent->zstate_num)) != Z_OK) {
532 errno = err;
533 zperror2(zent->zname, gettext("could not get state"));
534 return (Z_ERR);
535 }
536 zent->zstate_str = zone_state_str(zent->zstate_num);
537
538 /*
539 * A zone's brand is only available in the .xml file describing it,
540 * which is only visible to the global zone. This causes
541 * zone_get_brand() to fail when called from within a non-global
542 * zone. Fortunately we only do this on labeled systems, where we
543 * know all zones are native.
544 */
545 if (getzoneid() != GLOBAL_ZONEID) {
546 assert(is_system_labeled() != 0);
547 (void) strlcpy(zent->zbrand, default_brand,
548 sizeof (zent->zbrand));
549 } else if (zone_get_brand(zent->zname, zent->zbrand,
550 sizeof (zent->zbrand)) != Z_OK) {
551 zperror2(zent->zname, gettext("could not get brand name"));
552 return (Z_ERR);
553 }
554
555 /*
556 * Get ip type of the zone.
557 * Note for global zone, ZS_SHARED is set always.
558 */
559 if (zid == GLOBAL_ZONEID) {
560 zent->ziptype = ZS_SHARED;
561 return (Z_OK);
562 }
563
564 if ((handle = zonecfg_init_handle()) == NULL) {
565 zperror2(zent->zname, gettext("could not init handle"));
566 return (Z_ERR);
567 }
568 if ((err = zonecfg_get_handle(zent->zname, handle)) != Z_OK) {
569 zperror2(zent->zname, gettext("could not get handle"));
570 zonecfg_fini_handle(handle);
571 return (Z_ERR);
572 }
573
574 if ((err = zonecfg_get_iptype(handle, &zent->ziptype)) != Z_OK) {
575 zperror2(zent->zname, gettext("could not get ip-type"));
576 zonecfg_fini_handle(handle);
577 return (Z_ERR);
578 }
579
580 /*
581 * There is a race condition where the zone could boot while
582 * we're walking the index file. In this case the zone state
583 * could be seen as running from the call above, but the zoneid
584 * would be undefined.
585 *
586 * There is also a race condition where the zone could shutdown after
587 * we got its running state above. This is also not an error and
588 * we fall back to getting the ziptype from the zone configuration.
589 */
590 if (zent->zstate_num == ZONE_STATE_RUNNING &&
591 zid != ZONE_ID_UNDEFINED) {
592 ushort_t flags;
593
594 if (zone_getattr(zid, ZONE_ATTR_FLAGS, &flags,
595 sizeof (flags)) >= 0) {
596 if (flags & ZF_NET_EXCL)
597 zent->ziptype = ZS_EXCLUSIVE;
598 else
599 zent->ziptype = ZS_SHARED;
600 }
601 }
602
603 zent->zdid = zonecfg_get_did(handle);
604
605 zonecfg_fini_handle(handle);
606
607 return (Z_OK);
608 }
609
610 /*
611 * fetch_zents() calls zone_list(2) to find out how many zones are running
612 * (which is stored in the global nzents), then calls zone_list(2) again
613 * to fetch the list of running zones (stored in the global zents). This
614 * function may be called multiple times, so if zents is already set, we
615 * return immediately to save work.
616 *
617 * Note that the data about running zones can change while this function
618 * is running, so its possible that the list of zones will have empty slots
619 * at the end.
620 */
621
622 static int
623 fetch_zents(void)
624 {
625 zoneid_t *zids = NULL;
626 uint_t nzents_saved;
627 int i, retv;
628 FILE *fp;
629 boolean_t inaltroot;
630 zone_entry_t *zentp;
631 const char *altroot;
632
633 if (nzents > 0)
634 return (Z_OK);
635
636 if (zone_list(NULL, &nzents) != 0) {
637 zperror(gettext("failed to get zoneid list"), B_FALSE);
638 return (Z_ERR);
639 }
640
641 again:
642 if (nzents == 0)
643 return (Z_OK);
644
645 zids = safe_calloc(nzents, sizeof (zoneid_t));
646 nzents_saved = nzents;
647
648 if (zone_list(zids, &nzents) != 0) {
649 zperror(gettext("failed to get zone list"), B_FALSE);
650 free(zids);
651 return (Z_ERR);
652 }
653 if (nzents != nzents_saved) {
654 /* list changed, try again */
655 free(zids);
656 goto again;
657 }
658
659 zents = safe_calloc(nzents, sizeof (zone_entry_t));
660
661 inaltroot = zonecfg_in_alt_root();
662 if (inaltroot) {
663 fp = zonecfg_open_scratch("", B_FALSE);
664 altroot = zonecfg_get_root();
665 } else {
666 fp = NULL;
667 }
668 zentp = zents;
669 retv = Z_OK;
670 for (i = 0; i < nzents; i++) {
671 char name[ZONENAME_MAX];
672 char altname[ZONENAME_MAX];
673 char rev_altroot[MAXPATHLEN];
674
675 if (getzonenamebyid(zids[i], name, sizeof (name)) < 0) {
676 /*
677 * There is a race condition where the zone may have
678 * shutdown since we retrieved the number of running
679 * zones above. This is not an error, there will be
680 * an empty slot at the end of the list.
681 */
682 continue;
683 }
684 if (zonecfg_is_scratch(name)) {
685 /* Ignore scratch zones by default */
686 if (!inaltroot)
687 continue;
688 if (fp == NULL ||
689 zonecfg_reverse_scratch(fp, name, altname,
690 sizeof (altname), rev_altroot,
691 sizeof (rev_altroot)) == -1) {
692 zerror(gettext("could not resolve scratch "
693 "zone %s"), name);
694 retv = Z_ERR;
695 continue;
696 }
697 /* Ignore zones in other alternate roots */
698 if (strcmp(rev_altroot, altroot) != 0)
699 continue;
700 (void) strcpy(name, altname);
701 } else {
702 /* Ignore non-scratch when in an alternate root */
703 if (inaltroot && strcmp(name, GLOBAL_ZONENAME) != 0)
704 continue;
705 }
706 if (lookup_zone_info(name, zids[i], zentp) != Z_OK) {
707 /*
708 * There is a race condition where the zone may have
709 * shutdown since we retrieved the number of running
710 * zones above. This is not an error, there will be
711 * an empty slot at the end of the list.
712 */
713 continue;
714 }
715 zentp++;
716 }
717 nzents = zentp - zents;
718 if (fp != NULL)
719 zonecfg_close_scratch(fp);
720
721 free(zids);
722 return (retv);
723 }
724
725 static int
726 zone_print_list(zone_state_t min_state, boolean_t verbose, boolean_t parsable)
727 {
728 int i;
729 zone_entry_t zent;
730 FILE *cookie;
731 char *name;
732
733 /*
734 * First get the list of running zones from the kernel and print them.
735 * If that is all we need, then return.
736 */
737 if ((i = fetch_zents()) != Z_OK) {
738 /*
739 * No need for error messages; fetch_zents() has already taken
740 * care of this.
741 */
742 return (i);
743 }
744 for (i = 0; i < nzents; i++)
745 zone_print(&zents[i], verbose, parsable);
746 if (min_state >= ZONE_STATE_RUNNING)
747 return (Z_OK);
748 /*
749 * Next, get the full list of zones from the configuration, skipping
750 * any we have already printed.
751 */
752 cookie = setzoneent();
753 while ((name = getzoneent(cookie)) != NULL) {
754 for (i = 0; i < nzents; i++) {
755 if (strcmp(zents[i].zname, name) == 0)
756 break;
757 }
758 if (i < nzents) {
759 free(name);
760 continue;
761 }
762 if (lookup_zone_info(name, ZONE_ID_UNDEFINED, &zent) != Z_OK) {
763 free(name);
764 continue;
765 }
766 free(name);
767 if (zent.zstate_num >= min_state)
768 zone_print(&zent, verbose, parsable);
769 }
770 endzoneent(cookie);
771 return (Z_OK);
772 }
773
774 /*
775 * Retrieve a zone entry by name. Returns NULL if no such zone exists.
776 */
777 static zone_entry_t *
778 lookup_running_zone(const char *name)
779 {
780 zoneid_t zid;
781 zone_entry_t *zent;
782
783 if ((zid = getzoneidbyname(name)) == -1)
784 return (NULL);
785
786 if ((zent = malloc(sizeof (zone_entry_t))) == NULL)
787 return (NULL);
788
789 if (lookup_zone_info(name, zid, zent) != Z_OK) {
790 free(zent);
791 return (NULL);
792 }
793 return (zent);
794 }
795
796 /*
797 * Check a bit in a mode_t: if on is B_TRUE, that bit should be on; if
798 * B_FALSE, it should be off. Return B_TRUE if the mode is bad (incorrect).
799 */
800 static boolean_t
801 bad_mode_bit(mode_t mode, mode_t bit, boolean_t on, char *file)
802 {
803 char *str;
804
805 assert(bit == S_IRUSR || bit == S_IWUSR || bit == S_IXUSR ||
806 bit == S_IRGRP || bit == S_IWGRP || bit == S_IXGRP ||
807 bit == S_IROTH || bit == S_IWOTH || bit == S_IXOTH);
808 /*
809 * TRANSLATION_NOTE
810 * The strings below will be used as part of a larger message,
811 * either:
812 * (file name) must be (owner|group|world) (read|writ|execut)able
813 * or
814 * (file name) must not be (owner|group|world) (read|writ|execut)able
815 */
816 switch (bit) {
817 case S_IRUSR:
818 str = gettext("owner readable");
819 break;
820 case S_IWUSR:
821 str = gettext("owner writable");
822 break;
823 case S_IXUSR:
824 str = gettext("owner executable");
825 break;
826 case S_IRGRP:
827 str = gettext("group readable");
828 break;
829 case S_IWGRP:
830 str = gettext("group writable");
831 break;
832 case S_IXGRP:
833 str = gettext("group executable");
834 break;
835 case S_IROTH:
836 str = gettext("world readable");
837 break;
838 case S_IWOTH:
839 str = gettext("world writable");
840 break;
841 case S_IXOTH:
842 str = gettext("world executable");
843 break;
844 }
845 if ((mode & bit) == (on ? 0 : bit)) {
846 /*
847 * TRANSLATION_NOTE
848 * The first parameter below is a file name; the second
849 * is one of the "(owner|group|world) (read|writ|execut)able"
850 * strings from above.
851 */
852 /*
853 * The code below could be simplified but not in a way
854 * that would easily translate to non-English locales.
855 */
856 if (on) {
857 (void) fprintf(stderr, gettext("%s must be %s.\n"),
858 file, str);
859 } else {
860 (void) fprintf(stderr, gettext("%s must not be %s.\n"),
861 file, str);
862 }
863 return (B_TRUE);
864 }
865 return (B_FALSE);
866 }
867
868 /*
869 * We want to make sure that no zone has its zone path as a child node
870 * (in the directory sense) of any other. We do that by comparing this
871 * zone's path to the path of all other (non-global) zones. The comparison
872 * in each case is simple: add '/' to the end of the path, then do a
873 * strncmp() of the two paths, using the length of the shorter one.
874 */
875
876 static int
877 crosscheck_zonepaths(char *path)
878 {
879 char rpath[MAXPATHLEN]; /* resolved path */
880 char path_copy[MAXPATHLEN]; /* copy of original path */
881 char rpath_copy[MAXPATHLEN]; /* copy of original rpath */
882 struct zoneent *ze;
883 int res, err;
884 FILE *cookie;
885
886 cookie = setzoneent();
887 while ((ze = getzoneent_private(cookie)) != NULL) {
888 /* Skip zones which are not installed. */
889 if (ze->zone_state < ZONE_STATE_INSTALLED) {
890 free(ze);
891 continue;
892 }
893 /* Skip the global zone and the current target zone. */
894 if (strcmp(ze->zone_name, GLOBAL_ZONENAME) == 0 ||
895 strcmp(ze->zone_name, target_zone) == 0) {
896 free(ze);
897 continue;
898 }
899 if (strlen(ze->zone_path) == 0) {
900 /* old index file without path, fall back */
901 if ((err = zone_get_zonepath(ze->zone_name,
902 ze->zone_path, sizeof (ze->zone_path))) != Z_OK) {
903 errno = err;
904 zperror2(ze->zone_name,
905 gettext("could not get zone path"));
906 free(ze);
907 continue;
908 }
909 }
910 (void) snprintf(path_copy, sizeof (path_copy), "%s%s",
911 zonecfg_get_root(), ze->zone_path);
912 res = resolvepath(path_copy, rpath, sizeof (rpath));
913 if (res == -1) {
914 if (errno != ENOENT) {
915 zperror(path_copy, B_FALSE);
916 free(ze);
917 return (Z_ERR);
918 }
919 (void) printf(gettext("WARNING: zone %s is installed, "
920 "but its %s %s does not exist.\n"), ze->zone_name,
921 "zonepath", path_copy);
922 free(ze);
923 continue;
924 }
925 rpath[res] = '\0';
926 (void) snprintf(path_copy, sizeof (path_copy), "%s/", path);
927 (void) snprintf(rpath_copy, sizeof (rpath_copy), "%s/", rpath);
928 if (strncmp(path_copy, rpath_copy,
929 min(strlen(path_copy), strlen(rpath_copy))) == 0) {
930 /*
931 * TRANSLATION_NOTE
932 * zonepath is a literal that should not be translated.
933 */
934 (void) fprintf(stderr, gettext("%s zonepath (%s) and "
935 "%s zonepath (%s) overlap.\n"),
936 target_zone, path, ze->zone_name, rpath);
937 free(ze);
938 return (Z_ERR);
939 }
940 free(ze);
941 }
942 endzoneent(cookie);
943 return (Z_OK);
944 }
945
946 static int
947 validate_zonepath(char *path, int cmd_num)
948 {
949 int res; /* result of last library/system call */
950 boolean_t err = B_FALSE; /* have we run into an error? */
951 struct stat stbuf;
952 struct statvfs64 vfsbuf;
953 char rpath[MAXPATHLEN]; /* resolved path */
954 char ppath[MAXPATHLEN]; /* parent path */
955 char rppath[MAXPATHLEN]; /* resolved parent path */
956 char rootpath[MAXPATHLEN]; /* root path */
957 zone_state_t state;
958
959 if (path[0] != '/') {
960 (void) fprintf(stderr,
961 gettext("%s is not an absolute path.\n"), path);
962 return (Z_ERR);
963 }
964 if ((res = resolvepath(path, rpath, sizeof (rpath))) == -1) {
965 if ((errno != ENOENT) ||
966 (cmd_num != CMD_VERIFY && cmd_num != CMD_INSTALL &&
967 cmd_num != CMD_CLONE && cmd_num != CMD_MOVE)) {
968 zperror(path, B_FALSE);
969 return (Z_ERR);
970 }
971 if (cmd_num == CMD_VERIFY) {
972 /*
973 * TRANSLATION_NOTE
974 * zoneadm is a literal that should not be translated.
975 */
976 (void) fprintf(stderr, gettext("WARNING: %s does not "
977 "exist, so it could not be verified.\nWhen "
978 "'zoneadm %s' is run, '%s' will try to create\n%s, "
979 "and '%s' will be tried again,\nbut the '%s' may "
980 "fail if:\nthe parent directory of %s is group- or "
981 "other-writable\nor\n%s overlaps with any other "
982 "installed zones.\n"), path,
983 cmd_to_str(CMD_INSTALL), cmd_to_str(CMD_INSTALL),
984 path, cmd_to_str(CMD_VERIFY),
985 cmd_to_str(CMD_VERIFY), path, path);
986 return (Z_OK);
987 }
988 /*
989 * The zonepath is supposed to be mode 700 but its
990 * parent(s) 755. So use 755 on the mkdirp() then
991 * chmod() the zonepath itself to 700.
992 */
993 if (mkdirp(path, DEFAULT_DIR_MODE) < 0) {
994 zperror(path, B_FALSE);
995 return (Z_ERR);
996 }
997 /*
998 * If the chmod() fails, report the error, but might
999 * as well continue the verify procedure.
1000 */
1001 if (chmod(path, S_IRWXU) != 0)
1002 zperror(path, B_FALSE);
1003 /*
1004 * Since the mkdir() succeeded, we should not have to
1005 * worry about a subsequent ENOENT, thus this should
1006 * only recurse once.
1007 */
1008 return (validate_zonepath(path, cmd_num));
1009 }
1010 rpath[res] = '\0';
1011 if (strcmp(path, rpath) != 0) {
1012 errno = Z_RESOLVED_PATH;
1013 zperror(path, B_TRUE);
1014 return (Z_ERR);
1015 }
1016 if ((res = stat(rpath, &stbuf)) != 0) {
1017 zperror(rpath, B_FALSE);
1018 return (Z_ERR);
1019 }
1020 if (!S_ISDIR(stbuf.st_mode)) {
1021 (void) fprintf(stderr, gettext("%s is not a directory.\n"),
1022 rpath);
1023 return (Z_ERR);
1024 }
1025 if (strcmp(stbuf.st_fstype, MNTTYPE_TMPFS) == 0) {
1026 (void) printf(gettext("WARNING: %s is on a temporary "
1027 "file system.\n"), rpath);
1028 }
1029 if (crosscheck_zonepaths(rpath) != Z_OK)
1030 return (Z_ERR);
1031 /*
1032 * Try to collect and report as many minor errors as possible
1033 * before returning, so the user can learn everything that needs
1034 * to be fixed up front.
1035 */
1036 if (stbuf.st_uid != 0) {
1037 (void) fprintf(stderr, gettext("%s is not owned by root.\n"),
1038 rpath);
1039 err = B_TRUE;
1040
1041 /* Try to change owner */
1042 if (cmd_num != CMD_VERIFY) {
1043 (void) fprintf(stderr, gettext("%s: changing owner "
1044 "to root.\n"), rpath);
1045 if (chown(rpath, 0, -1) != 0) {
1046 zperror(rpath, B_FALSE);
1047 return (Z_ERR);
1048 } else {
1049 err = B_FALSE;
1050 }
1051 }
1052 }
1053 err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rpath);
1054 err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rpath);
1055 err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rpath);
1056 err |= bad_mode_bit(stbuf.st_mode, S_IRGRP, B_FALSE, rpath);
1057 err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rpath);
1058 err |= bad_mode_bit(stbuf.st_mode, S_IXGRP, B_FALSE, rpath);
1059 err |= bad_mode_bit(stbuf.st_mode, S_IROTH, B_FALSE, rpath);
1060 err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rpath);
1061 err |= bad_mode_bit(stbuf.st_mode, S_IXOTH, B_FALSE, rpath);
1062
1063 /* If the group perms are wrong, fix them */
1064 if (err && (cmd_num != CMD_VERIFY)) {
1065 (void) fprintf(stderr, gettext("%s: changing permissions "
1066 "to 0700.\n"), rpath);
1067 if (chmod(rpath, S_IRWXU) != 0) {
1068 zperror(path, B_FALSE);
1069 } else {
1070 err = B_FALSE;
1071 }
1072 }
1073
1074 (void) snprintf(ppath, sizeof (ppath), "%s/..", path);
1075 if ((res = resolvepath(ppath, rppath, sizeof (rppath))) == -1) {
1076 zperror(ppath, B_FALSE);
1077 return (Z_ERR);
1078 }
1079 rppath[res] = '\0';
1080 if ((res = stat(rppath, &stbuf)) != 0) {
1081 zperror(rppath, B_FALSE);
1082 return (Z_ERR);
1083 }
1084 /* theoretically impossible */
1085 if (!S_ISDIR(stbuf.st_mode)) {
1086 (void) fprintf(stderr, gettext("%s is not a directory.\n"),
1087 rppath);
1088 return (Z_ERR);
1089 }
1090 if (stbuf.st_uid != 0) {
1091 (void) fprintf(stderr, gettext("%s is not owned by root.\n"),
1092 rppath);
1093 err = B_TRUE;
1094 }
1095 err |= bad_mode_bit(stbuf.st_mode, S_IRUSR, B_TRUE, rppath);
1096 err |= bad_mode_bit(stbuf.st_mode, S_IWUSR, B_TRUE, rppath);
1097 err |= bad_mode_bit(stbuf.st_mode, S_IXUSR, B_TRUE, rppath);
1098 err |= bad_mode_bit(stbuf.st_mode, S_IWGRP, B_FALSE, rppath);
1099 err |= bad_mode_bit(stbuf.st_mode, S_IWOTH, B_FALSE, rppath);
1100 if (strcmp(rpath, rppath) == 0) {
1101 (void) fprintf(stderr, gettext("%s is its own parent.\n"),
1102 rppath);
1103 err = B_TRUE;
1104 }
1105
1106 if (statvfs64(rpath, &vfsbuf) != 0) {
1107 zperror(rpath, B_FALSE);
1108 return (Z_ERR);
1109 }
1110 if (strcmp(vfsbuf.f_basetype, MNTTYPE_NFS) == 0) {
1111 /*
1112 * TRANSLATION_NOTE
1113 * Zonepath and NFS are literals that should not be translated.
1114 */
1115 (void) fprintf(stderr, gettext("Zonepath %s is on an NFS "
1116 "mounted file system.\n"
1117 "\tA local file system must be used.\n"), rpath);
1118 return (Z_ERR);
1119 }
1120 if (vfsbuf.f_flag & ST_NOSUID) {
1121 /*
1122 * TRANSLATION_NOTE
1123 * Zonepath and nosuid are literals that should not be
1124 * translated.
1125 */
1126 (void) fprintf(stderr, gettext("Zonepath %s is on a nosuid "
1127 "file system.\n"), rpath);
1128 return (Z_ERR);
1129 }
1130
1131 if ((res = zone_get_state(target_zone, &state)) != Z_OK) {
1132 errno = res;
1133 zperror2(target_zone, gettext("could not get state"));
1134 return (Z_ERR);
1135 }
1136 /*
1137 * The existence of the root path is only bad in the configured state,
1138 * as it is *supposed* to be there at the installed and later states.
1139 * However, the root path is expected to be there if the zone is
1140 * detached.
1141 * State/command mismatches are caught earlier in verify_details().
1142 */
1143 if (state == ZONE_STATE_CONFIGURED && cmd_num != CMD_ATTACH) {
1144 if (snprintf(rootpath, sizeof (rootpath), "%s/root", rpath) >=
1145 sizeof (rootpath)) {
1146 /*
1147 * TRANSLATION_NOTE
1148 * Zonepath is a literal that should not be translated.
1149 */
1150 (void) fprintf(stderr,
1151 gettext("Zonepath %s is too long.\n"), rpath);
1152 return (Z_ERR);
1153 }
1154 if ((res = stat(rootpath, &stbuf)) == 0) {
1155 if (zonecfg_detached(rpath)) {
1156 (void) fprintf(stderr,
1157 gettext("Cannot %s detached "
1158 "zone.\nUse attach or remove %s "
1159 "directory.\n"), cmd_to_str(cmd_num),
1160 rpath);
1161 return (Z_ERR);
1162 }
1163
1164 /* Not detached, check if it really looks ok. */
1165
1166 if (!S_ISDIR(stbuf.st_mode)) {
1167 (void) fprintf(stderr, gettext("%s is not a "
1168 "directory.\n"), rootpath);
1169 return (Z_ERR);
1170 }
1171
1172 if (stbuf.st_uid != 0) {
1173 (void) fprintf(stderr, gettext("%s is not "
1174 "owned by root.\n"), rootpath);
1175 return (Z_ERR);
1176 }
1177
1178 if ((stbuf.st_mode & 0777) != 0755) {
1179 (void) fprintf(stderr, gettext("%s mode is not "
1180 "0755.\n"), rootpath);
1181 return (Z_ERR);
1182 }
1183 }
1184 }
1185
1186 return (err ? Z_ERR : Z_OK);
1187 }
1188
1189 static int
1190 invoke_brand_handler(int cmd_num, char *argv[])
1191 {
1192 zone_dochandle_t handle;
1193 int err;
1194
1195 if ((handle = zonecfg_init_handle()) == NULL) {
1196 zperror(cmd_to_str(cmd_num), B_TRUE);
1197 return (Z_ERR);
1198 }
1199 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
1200 errno = err;
1201 zperror(cmd_to_str(cmd_num), B_TRUE);
1202 zonecfg_fini_handle(handle);
1203 return (Z_ERR);
1204 }
1205 if (verify_brand(handle, cmd_num, argv) != Z_OK) {
1206 zonecfg_fini_handle(handle);
1207 return (Z_ERR);
1208 }
1209 zonecfg_fini_handle(handle);
1210 return (Z_OK);
1211 }
1212
1213 static int
1214 ready_func(int argc, char *argv[])
1215 {
1216 zone_cmd_arg_t zarg;
1217 int arg;
1218
1219 if (zonecfg_in_alt_root()) {
1220 zerror(gettext("cannot ready zone in alternate root"));
1221 return (Z_ERR);
1222 }
1223
1224 optind = 0;
1225 if ((arg = getopt(argc, argv, "?")) != EOF) {
1226 switch (arg) {
1227 case '?':
1228 sub_usage(SHELP_READY, CMD_READY);
1229 return (optopt == '?' ? Z_OK : Z_USAGE);
1230 default:
1231 sub_usage(SHELP_READY, CMD_READY);
1232 return (Z_USAGE);
1233 }
1234 }
1235 if (argc > optind) {
1236 sub_usage(SHELP_READY, CMD_READY);
1237 return (Z_USAGE);
1238 }
1239 if (sanity_check(target_zone, CMD_READY, B_FALSE, B_FALSE, B_FALSE)
1240 != Z_OK)
1241 return (Z_ERR);
1242 if (verify_details(CMD_READY, argv) != Z_OK)
1243 return (Z_ERR);
1244
1245 zarg.cmd = Z_READY;
1246 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
1247 zerror(gettext("call to %s failed"), "zoneadmd");
1248 return (Z_ERR);
1249 }
1250 return (Z_OK);
1251 }
1252
1253 static int
1254 boot_func(int argc, char *argv[])
1255 {
1256 zone_cmd_arg_t zarg;
1257 boolean_t force = B_FALSE;
1258 int arg;
1259
1260 if (zonecfg_in_alt_root()) {
1261 zerror(gettext("cannot boot zone in alternate root"));
1262 return (Z_ERR);
1263 }
1264
1265 zarg.bootbuf[0] = '\0';
1266
1267 /*
1268 * The following getopt processes arguments to zone boot; that
1269 * is to say, the [here] portion of the argument string:
1270 *
1271 * zoneadm -z myzone boot [here] -- -v -m verbose
1272 *
1273 * Where [here] can either be nothing, -? (in which case we bail
1274 * and print usage), -f (a private option to indicate that the
1275 * boot operation should be 'forced'), or -s. Support for -s is
1276 * vestigal and obsolete, but is retained because it was a
1277 * documented interface and there are known consumers including
1278 * admin/install; the proper way to specify boot arguments like -s
1279 * is:
1280 *
1281 * zoneadm -z myzone boot -- -s -v -m verbose.
1282 */
1283 optind = 0;
1284 while ((arg = getopt(argc, argv, "?fs")) != EOF) {
1285 switch (arg) {
1286 case '?':
1287 sub_usage(SHELP_BOOT, CMD_BOOT);
1288 return (optopt == '?' ? Z_OK : Z_USAGE);
1289 case 's':
1290 (void) strlcpy(zarg.bootbuf, "-s",
1291 sizeof (zarg.bootbuf));
1292 break;
1293 case 'f':
1294 force = B_TRUE;
1295 break;
1296 default:
1297 sub_usage(SHELP_BOOT, CMD_BOOT);
1298 return (Z_USAGE);
1299 }
1300 }
1301
1302 for (; optind < argc; optind++) {
1303 if (strlcat(zarg.bootbuf, argv[optind],
1304 sizeof (zarg.bootbuf)) >= sizeof (zarg.bootbuf)) {
1305 zerror(gettext("Boot argument list too long"));
1306 return (Z_ERR);
1307 }
1308 if (optind < argc - 1)
1309 if (strlcat(zarg.bootbuf, " ", sizeof (zarg.bootbuf)) >=
1310 sizeof (zarg.bootbuf)) {
1311 zerror(gettext("Boot argument list too long"));
1312 return (Z_ERR);
1313 }
1314 }
1315 if (sanity_check(target_zone, CMD_BOOT, B_FALSE, B_FALSE, force)
1316 != Z_OK)
1317 return (Z_ERR);
1318 if (verify_details(CMD_BOOT, argv) != Z_OK)
1319 return (Z_ERR);
1320 zarg.cmd = force ? Z_FORCEBOOT : Z_BOOT;
1321 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
1322 zerror(gettext("call to %s failed"), "zoneadmd");
1323 return (Z_ERR);
1324 }
1325
1326 return (Z_OK);
1327 }
1328
1329 static void
1330 fake_up_local_zone(zoneid_t zid, zone_entry_t *zeptr)
1331 {
1332 ssize_t result;
1333 uuid_t uuid;
1334 FILE *fp;
1335 ushort_t flags;
1336
1337 (void) memset(zeptr, 0, sizeof (*zeptr));
1338
1339 zeptr->zid = zid;
1340
1341 /*
1342 * Since we're looking up our own (non-global) zone name,
1343 * we can be assured that it will succeed.
1344 */
1345 result = getzonenamebyid(zid, zeptr->zname, sizeof (zeptr->zname));
1346 assert(result >= 0);
1347 if (zonecfg_is_scratch(zeptr->zname) &&
1348 (fp = zonecfg_open_scratch("", B_FALSE)) != NULL) {
1349 (void) zonecfg_reverse_scratch(fp, zeptr->zname, zeptr->zname,
1350 sizeof (zeptr->zname), NULL, 0);
1351 zonecfg_close_scratch(fp);
1352 }
1353
1354 if (is_system_labeled()) {
1355 (void) zone_getattr(zid, ZONE_ATTR_ROOT, zeptr->zroot,
1356 sizeof (zeptr->zroot));
1357 (void) strlcpy(zeptr->zbrand, NATIVE_BRAND_NAME,
1358 sizeof (zeptr->zbrand));
1359 } else {
1360 (void) strlcpy(zeptr->zroot, "/", sizeof (zeptr->zroot));
1361 (void) zone_getattr(zid, ZONE_ATTR_BRAND, zeptr->zbrand,
1362 sizeof (zeptr->zbrand));
1363 }
1364
1365 zeptr->zstate_str = "running";
1366 if (zonecfg_get_uuid(zeptr->zname, uuid) == Z_OK &&
1367 !uuid_is_null(uuid))
1368 uuid_unparse(uuid, zeptr->zuuid);
1369
1370 if (zone_getattr(zid, ZONE_ATTR_FLAGS, &flags, sizeof (flags)) < 0) {
1371 zperror2(zeptr->zname, gettext("could not get zone flags"));
1372 exit(Z_ERR);
1373 }
1374 if (flags & ZF_NET_EXCL)
1375 zeptr->ziptype = ZS_EXCLUSIVE;
1376 else
1377 zeptr->ziptype = ZS_SHARED;
1378 }
1379
1380 static int
1381 list_func(int argc, char *argv[])
1382 {
1383 zone_entry_t *zentp, zent;
1384 int arg, retv;
1385 boolean_t output = B_FALSE, verbose = B_FALSE, parsable = B_FALSE;
1386 zone_state_t min_state = ZONE_STATE_RUNNING;
1387 zoneid_t zone_id = getzoneid();
1388
1389 if (target_zone == NULL) {
1390 /* all zones: default view to running but allow override */
1391 optind = 0;
1392 while ((arg = getopt(argc, argv, "?cipv")) != EOF) {
1393 switch (arg) {
1394 case '?':
1395 sub_usage(SHELP_LIST, CMD_LIST);
1396 return (optopt == '?' ? Z_OK : Z_USAGE);
1397 /*
1398 * The 'i' and 'c' options are not mutually
1399 * exclusive so if 'c' is given, then min_state
1400 * is set to 0 (ZONE_STATE_CONFIGURED) which is
1401 * the lowest possible state. If 'i' is given,
1402 * then min_state is set to be the lowest state
1403 * so far.
1404 */
1405 case 'c':
1406 min_state = ZONE_STATE_CONFIGURED;
1407 break;
1408 case 'i':
1409 min_state = min(ZONE_STATE_INSTALLED,
1410 min_state);
1411
1412 break;
1413 case 'p':
1414 parsable = B_TRUE;
1415 break;
1416 case 'v':
1417 verbose = B_TRUE;
1418 break;
1419 default:
1420 sub_usage(SHELP_LIST, CMD_LIST);
1421 return (Z_USAGE);
1422 }
1423 }
1424 if (parsable && verbose) {
1425 zerror(gettext("%s -p and -v are mutually exclusive."),
1426 cmd_to_str(CMD_LIST));
1427 return (Z_ERR);
1428 }
1429 if (zone_id == GLOBAL_ZONEID || is_system_labeled()) {
1430 retv = zone_print_list(min_state, verbose, parsable);
1431 } else {
1432 fake_up_local_zone(zone_id, &zent);
1433 retv = Z_OK;
1434 zone_print(&zent, verbose, parsable);
1435 }
1436 return (retv);
1437 }
1438
1439 /*
1440 * Specific target zone: disallow -i/-c suboptions.
1441 */
1442 optind = 0;
1443 while ((arg = getopt(argc, argv, "?pv")) != EOF) {
1444 switch (arg) {
1445 case '?':
1446 sub_usage(SHELP_LIST, CMD_LIST);
1447 return (optopt == '?' ? Z_OK : Z_USAGE);
1448 case 'p':
1449 parsable = B_TRUE;
1450 break;
1451 case 'v':
1452 verbose = B_TRUE;
1453 break;
1454 default:
1455 sub_usage(SHELP_LIST, CMD_LIST);
1456 return (Z_USAGE);
1457 }
1458 }
1459 if (parsable && verbose) {
1460 zerror(gettext("%s -p and -v are mutually exclusive."),
1461 cmd_to_str(CMD_LIST));
1462 return (Z_ERR);
1463 }
1464 if (argc > optind) {
1465 sub_usage(SHELP_LIST, CMD_LIST);
1466 return (Z_USAGE);
1467 }
1468 if (zone_id != GLOBAL_ZONEID && !is_system_labeled()) {
1469 fake_up_local_zone(zone_id, &zent);
1470 /*
1471 * main() will issue a Z_NO_ZONE error if it cannot get an
1472 * id for target_zone, which in a non-global zone should
1473 * happen for any zone name except `zonename`. Thus we
1474 * assert() that here but don't otherwise check.
1475 */
1476 assert(strcmp(zent.zname, target_zone) == 0);
1477 zone_print(&zent, verbose, parsable);
1478 output = B_TRUE;
1479 } else if ((zentp = lookup_running_zone(target_zone)) != NULL) {
1480 zone_print(zentp, verbose, parsable);
1481 output = B_TRUE;
1482 } else if (lookup_zone_info(target_zone, ZONE_ID_UNDEFINED,
1483 &zent) == Z_OK) {
1484 zone_print(&zent, verbose, parsable);
1485 output = B_TRUE;
1486 }
1487
1488 /*
1489 * Invoke brand-specific handler. Note that we do this
1490 * only if we're in the global zone, and target_zone is specified
1491 * and it is not the global zone.
1492 */
1493 if (zone_id == GLOBAL_ZONEID && target_zone != NULL &&
1494 strcmp(target_zone, GLOBAL_ZONENAME) != 0)
1495 if (invoke_brand_handler(CMD_LIST, argv) != Z_OK)
1496 return (Z_ERR);
1497
1498 return (output ? Z_OK : Z_ERR);
1499 }
1500
1501 int
1502 do_subproc(char *cmdbuf)
1503 {
1504 void (*saveint)(int);
1505 void (*saveterm)(int);
1506 void (*savequit)(int);
1507 void (*savehup)(int);
1508 int pid, child, status;
1509
1510 if ((child = vfork()) == 0) {
1511 (void) execl("/bin/sh", "sh", "-c", cmdbuf, (char *)NULL);
1512 }
1513
1514 if (child == -1)
1515 return (-1);
1516
1517 saveint = sigset(SIGINT, SIG_IGN);
1518 saveterm = sigset(SIGTERM, SIG_IGN);
1519 savequit = sigset(SIGQUIT, SIG_IGN);
1520 savehup = sigset(SIGHUP, SIG_IGN);
1521
1522 while ((pid = waitpid(child, &status, 0)) != child && pid != -1)
1523 ;
1524
1525 (void) sigset(SIGINT, saveint);
1526 (void) sigset(SIGTERM, saveterm);
1527 (void) sigset(SIGQUIT, savequit);
1528 (void) sigset(SIGHUP, savehup);
1529
1530 return (pid == -1 ? -1 : status);
1531 }
1532
1533 int
1534 subproc_status(const char *cmd, int status, boolean_t verbose_failure)
1535 {
1536 if (WIFEXITED(status)) {
1537 int exit_code = WEXITSTATUS(status);
1538
1539 if ((verbose_failure) && (exit_code != ZONE_SUBPROC_OK))
1540 zerror(gettext("'%s' failed with exit code %d."), cmd,
1541 exit_code);
1542
1543 return (exit_code);
1544 } else if (WIFSIGNALED(status)) {
1545 int signal = WTERMSIG(status);
1546 char sigstr[SIG2STR_MAX];
1547
1548 if (sig2str(signal, sigstr) == 0) {
1549 zerror(gettext("'%s' terminated by signal SIG%s."), cmd,
1550 sigstr);
1551 } else {
1552 zerror(gettext("'%s' terminated by an unknown signal."),
1553 cmd);
1554 }
1555 } else {
1556 zerror(gettext("'%s' failed for unknown reasons."), cmd);
1557 }
1558
1559 /*
1560 * Assume a subprocess that died due to a signal or an unknown error
1561 * should be considered an exit code of ZONE_SUBPROC_FATAL, as the
1562 * user will likely need to do some manual cleanup.
1563 */
1564 return (ZONE_SUBPROC_FATAL);
1565 }
1566
1567 static int
1568 auth_check(char *user, char *zone, int cmd_num)
1569 {
1570 char authname[MAXAUTHS];
1571
1572 switch (cmd_num) {
1573 case CMD_LIST:
1574 case CMD_HELP:
1575 return (Z_OK);
1576 case SOURCE_ZONE:
1577 (void) strlcpy(authname, ZONE_CLONEFROM_AUTH, MAXAUTHS);
1578 break;
1579 case CMD_BOOT:
1580 case CMD_HALT:
1581 case CMD_READY:
1582 case CMD_SHUTDOWN:
1583 case CMD_REBOOT:
1584 case CMD_SYSBOOT:
1585 case CMD_VERIFY:
1586 case CMD_INSTALL:
1587 case CMD_UNINSTALL:
1588 case CMD_MOUNT:
1589 case CMD_UNMOUNT:
1590 case CMD_CLONE:
1591 case CMD_MOVE:
1592 case CMD_DETACH:
1593 case CMD_ATTACH:
1594 case CMD_MARK:
1595 case CMD_APPLY:
1596 default:
1597 (void) strlcpy(authname, ZONE_MANAGE_AUTH, MAXAUTHS);
1598 break;
1599 }
1600 (void) strlcat(authname, KV_OBJECT, MAXAUTHS);
1601 (void) strlcat(authname, zone, MAXAUTHS);
1602 if (chkauthattr(authname, user) == 0) {
1603 return (Z_ERR);
1604 } else {
1605 /*
1606 * Some subcommands, e.g. install, run subcommands,
1607 * e.g. sysidcfg, that require a real uid of root,
1608 * so switch to root, here.
1609 */
1610 if (setuid(0) == -1) {
1611 zperror(gettext("insufficient privilege"), B_TRUE);
1612 return (Z_ERR);
1613 }
1614 return (Z_OK);
1615 }
1616 }
1617
1618 /*
1619 * Various sanity checks; make sure:
1620 * 1. We're in the global zone.
1621 * 2. The calling user has sufficient privilege.
1622 * 3. The target zone is neither the global zone nor anything starting with
1623 * "SUNW".
1624 * 4a. If we're looking for a 'not running' (i.e., configured or installed)
1625 * zone, the name service knows about it.
1626 * 4b. For some operations which expect a zone not to be running, that it is
1627 * not already running (or ready).
1628 */
1629 static int
1630 sanity_check(char *zone, int cmd_num, boolean_t running,
1631 boolean_t unsafe_when_running, boolean_t force)
1632 {
1633 zone_entry_t *zent;
1634 priv_set_t *privset;
1635 zone_state_t state, min_state;
1636 char kernzone[ZONENAME_MAX];
1637 FILE *fp;
1638
1639 if (getzoneid() != GLOBAL_ZONEID) {
1640 switch (cmd_num) {
1641 case CMD_HALT:
1642 zerror(gettext("use %s to %s this zone."), "halt(1M)",
1643 cmd_to_str(cmd_num));
1644 break;
1645 case CMD_SHUTDOWN:
1646 zerror(gettext("use %s to %s this zone."),
1647 "shutdown(1M)", cmd_to_str(cmd_num));
1648 break;
1649 case CMD_REBOOT:
1650 zerror(gettext("use %s to %s this zone."),
1651 "reboot(1M)", cmd_to_str(cmd_num));
1652 break;
1653 default:
1654 zerror(gettext("must be in the global zone to %s a "
1655 "zone."), cmd_to_str(cmd_num));
1656 break;
1657 }
1658 return (Z_ERR);
1659 }
1660
1661 if ((privset = priv_allocset()) == NULL) {
1662 zerror(gettext("%s failed"), "priv_allocset");
1663 return (Z_ERR);
1664 }
1665
1666 if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
1667 zerror(gettext("%s failed"), "getppriv");
1668 priv_freeset(privset);
1669 return (Z_ERR);
1670 }
1671
1672 if (priv_isfullset(privset) == B_FALSE) {
1673 zerror(gettext("only a privileged user may %s a zone."),
1674 cmd_to_str(cmd_num));
1675 priv_freeset(privset);
1676 return (Z_ERR);
1677 }
1678 priv_freeset(privset);
1679
1680 if (zone == NULL) {
1681 zerror(gettext("no zone specified"));
1682 return (Z_ERR);
1683 }
1684
1685 if (auth_check(username, zone, cmd_num) == Z_ERR) {
1686 zerror(gettext("User %s is not authorized to %s this zone."),
1687 username, cmd_to_str(cmd_num));
1688 return (Z_ERR);
1689 }
1690
1691 if (strcmp(zone, GLOBAL_ZONENAME) == 0) {
1692 zerror(gettext("%s operation is invalid for the global zone."),
1693 cmd_to_str(cmd_num));
1694 return (Z_ERR);
1695 }
1696
1697 if (strncmp(zone, "SUNW", 4) == 0) {
1698 zerror(gettext("%s operation is invalid for zones starting "
1699 "with SUNW."), cmd_to_str(cmd_num));
1700 return (Z_ERR);
1701 }
1702
1703 if (!zonecfg_in_alt_root()) {
1704 zent = lookup_running_zone(zone);
1705 } else if ((fp = zonecfg_open_scratch("", B_FALSE)) == NULL) {
1706 zent = NULL;
1707 } else {
1708 if (zonecfg_find_scratch(fp, zone, zonecfg_get_root(),
1709 kernzone, sizeof (kernzone)) == 0)
1710 zent = lookup_running_zone(kernzone);
1711 else
1712 zent = NULL;
1713 zonecfg_close_scratch(fp);
1714 }
1715
1716 /*
1717 * Look up from the kernel for 'running' zones.
1718 */
1719 if (running && !force) {
1720 if (zent == NULL) {
1721 zerror(gettext("not running"));
1722 return (Z_ERR);
1723 }
1724 } else {
1725 int err;
1726
1727 if (unsafe_when_running && zent != NULL) {
1728 /* check whether the zone is ready or running */
1729 if ((err = zone_get_state(zent->zname,
1730 &zent->zstate_num)) != Z_OK) {
1731 errno = err;
1732 zperror2(zent->zname,
1733 gettext("could not get state"));
1734 /* can't tell, so hedge */
1735 zent->zstate_str = "ready/running";
1736 } else {
1737 zent->zstate_str =
1738 zone_state_str(zent->zstate_num);
1739 }
1740 zerror(gettext("%s operation is invalid for %s zones."),
1741 cmd_to_str(cmd_num), zent->zstate_str);
1742 return (Z_ERR);
1743 }
1744 if ((err = zone_get_state(zone, &state)) != Z_OK) {
1745 errno = err;
1746 zperror2(zone, gettext("could not get state"));
1747 return (Z_ERR);
1748 }
1749 switch (cmd_num) {
1750 case CMD_UNINSTALL:
1751 if (state == ZONE_STATE_CONFIGURED) {
1752 zerror(gettext("is already in state '%s'."),
1753 zone_state_str(ZONE_STATE_CONFIGURED));
1754 return (Z_ERR);
1755 }
1756 break;
1757 case CMD_ATTACH:
1758 if (state == ZONE_STATE_INSTALLED) {
1759 zerror(gettext("is already %s."),
1760 zone_state_str(ZONE_STATE_INSTALLED));
1761 return (Z_ERR);
1762 } else if (state == ZONE_STATE_INCOMPLETE && !force) {
1763 zerror(gettext("zone is %s; %s required."),
1764 zone_state_str(ZONE_STATE_INCOMPLETE),
1765 cmd_to_str(CMD_UNINSTALL));
1766 return (Z_ERR);
1767 }
1768 break;
1769 case CMD_CLONE:
1770 case CMD_INSTALL:
1771 if (state == ZONE_STATE_INSTALLED) {
1772 zerror(gettext("is already %s."),
1773 zone_state_str(ZONE_STATE_INSTALLED));
1774 return (Z_ERR);
1775 } else if (state == ZONE_STATE_INCOMPLETE) {
1776 zerror(gettext("zone is %s; %s required."),
1777 zone_state_str(ZONE_STATE_INCOMPLETE),
1778 cmd_to_str(CMD_UNINSTALL));
1779 return (Z_ERR);
1780 }
1781 break;
1782 case CMD_DETACH:
1783 case CMD_MOVE:
1784 case CMD_READY:
1785 case CMD_BOOT:
1786 case CMD_MOUNT:
1787 case CMD_MARK:
1788 if ((cmd_num == CMD_BOOT || cmd_num == CMD_MOUNT) &&
1789 force)
1790 min_state = ZONE_STATE_INCOMPLETE;
1791 else if (cmd_num == CMD_MARK)
1792 min_state = ZONE_STATE_CONFIGURED;
1793 else
1794 min_state = ZONE_STATE_INSTALLED;
1795
1796 if (state < min_state) {
1797 zerror(gettext("must be %s before %s."),
1798 zone_state_str(min_state),
1799 cmd_to_str(cmd_num));
1800 return (Z_ERR);
1801 }
1802 break;
1803 case CMD_VERIFY:
1804 if (state == ZONE_STATE_INCOMPLETE) {
1805 zerror(gettext("zone is %s; %s required."),
1806 zone_state_str(ZONE_STATE_INCOMPLETE),
1807 cmd_to_str(CMD_UNINSTALL));
1808 return (Z_ERR);
1809 }
1810 break;
1811 case CMD_UNMOUNT:
1812 if (state != ZONE_STATE_MOUNTED) {
1813 zerror(gettext("must be %s before %s."),
1814 zone_state_str(ZONE_STATE_MOUNTED),
1815 cmd_to_str(cmd_num));
1816 return (Z_ERR);
1817 }
1818 break;
1819 case CMD_SYSBOOT:
1820 if (state != ZONE_STATE_INSTALLED) {
1821 zerror(gettext("%s operation is invalid for %s "
1822 "zones."), cmd_to_str(cmd_num),
1823 zone_state_str(state));
1824 return (Z_ERR);
1825 }
1826 break;
1827 }
1828 }
1829 return (Z_OK);
1830 }
1831
1832 static int
1833 halt_func(int argc, char *argv[])
1834 {
1835 zone_cmd_arg_t zarg;
1836 int arg;
1837
1838 if (zonecfg_in_alt_root()) {
1839 zerror(gettext("cannot halt zone in alternate root"));
1840 return (Z_ERR);
1841 }
1842
1843 optind = 0;
1844 if ((arg = getopt(argc, argv, "?")) != EOF) {
1845 switch (arg) {
1846 case '?':
1847 sub_usage(SHELP_HALT, CMD_HALT);
1848 return (optopt == '?' ? Z_OK : Z_USAGE);
1849 default:
1850 sub_usage(SHELP_HALT, CMD_HALT);
1851 return (Z_USAGE);
1852 }
1853 }
1854 if (argc > optind) {
1855 sub_usage(SHELP_HALT, CMD_HALT);
1856 return (Z_USAGE);
1857 }
1858 /*
1859 * zoneadmd should be the one to decide whether or not to proceed,
1860 * so even though it seems that the fourth parameter below should
1861 * perhaps be B_TRUE, it really shouldn't be.
1862 */
1863 if (sanity_check(target_zone, CMD_HALT, B_FALSE, B_FALSE, B_FALSE)
1864 != Z_OK)
1865 return (Z_ERR);
1866
1867 /*
1868 * Invoke brand-specific handler.
1869 */
1870 if (invoke_brand_handler(CMD_HALT, argv) != Z_OK)
1871 return (Z_ERR);
1872
1873 zarg.cmd = Z_HALT;
1874 return ((zonecfg_call_zoneadmd(target_zone, &zarg, locale,
1875 B_TRUE) == 0) ? Z_OK : Z_ERR);
1876 }
1877
1878 static int
1879 shutdown_func(int argc, char *argv[])
1880 {
1881 zone_cmd_arg_t zarg;
1882 int arg;
1883 boolean_t reboot = B_FALSE;
1884
1885 zarg.cmd = Z_SHUTDOWN;
1886
1887 if (zonecfg_in_alt_root()) {
1888 zerror(gettext("cannot shut down zone in alternate root"));
1889 return (Z_ERR);
1890 }
1891
1892 optind = 0;
1893 while ((arg = getopt(argc, argv, "?r")) != EOF) {
1894 switch (arg) {
1895 case '?':
1896 sub_usage(SHELP_SHUTDOWN, CMD_SHUTDOWN);
1897 return (optopt == '?' ? Z_OK : Z_USAGE);
1898 case 'r':
1899 reboot = B_TRUE;
1900 break;
1901 default:
1902 sub_usage(SHELP_SHUTDOWN, CMD_SHUTDOWN);
1903 return (Z_USAGE);
1904 }
1905 }
1906
1907 zarg.bootbuf[0] = '\0';
1908 for (; optind < argc; optind++) {
1909 if (strlcat(zarg.bootbuf, argv[optind],
1910 sizeof (zarg.bootbuf)) >= sizeof (zarg.bootbuf)) {
1911 zerror(gettext("Boot argument list too long"));
1912 return (Z_ERR);
1913 }
1914 if (optind < argc - 1)
1915 if (strlcat(zarg.bootbuf, " ", sizeof (zarg.bootbuf)) >=
1916 sizeof (zarg.bootbuf)) {
1917 zerror(gettext("Boot argument list too long"));
1918 return (Z_ERR);
1919 }
1920 }
1921
1922 /*
1923 * zoneadmd should be the one to decide whether or not to proceed,
1924 * so even though it seems that the third parameter below should
1925 * perhaps be B_TRUE, it really shouldn't be.
1926 */
1927 if (sanity_check(target_zone, CMD_SHUTDOWN, B_TRUE, B_FALSE, B_FALSE)
1928 != Z_OK)
1929 return (Z_ERR);
1930
1931 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != Z_OK)
1932 return (Z_ERR);
1933
1934 if (reboot) {
1935 if (sanity_check(target_zone, CMD_BOOT, B_FALSE, B_FALSE,
1936 B_FALSE) != Z_OK)
1937 return (Z_ERR);
1938
1939 zarg.cmd = Z_BOOT;
1940 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale,
1941 B_TRUE) != Z_OK)
1942 return (Z_ERR);
1943 }
1944 return (Z_OK);
1945 }
1946
1947 static int
1948 reboot_func(int argc, char *argv[])
1949 {
1950 zone_cmd_arg_t zarg;
1951 int arg;
1952
1953 if (zonecfg_in_alt_root()) {
1954 zerror(gettext("cannot reboot zone in alternate root"));
1955 return (Z_ERR);
1956 }
1957
1958 optind = 0;
1959 if ((arg = getopt(argc, argv, "?")) != EOF) {
1960 switch (arg) {
1961 case '?':
1962 sub_usage(SHELP_REBOOT, CMD_REBOOT);
1963 return (optopt == '?' ? Z_OK : Z_USAGE);
1964 default:
1965 sub_usage(SHELP_REBOOT, CMD_REBOOT);
1966 return (Z_USAGE);
1967 }
1968 }
1969
1970 zarg.bootbuf[0] = '\0';
1971 for (; optind < argc; optind++) {
1972 if (strlcat(zarg.bootbuf, argv[optind],
1973 sizeof (zarg.bootbuf)) >= sizeof (zarg.bootbuf)) {
1974 zerror(gettext("Boot argument list too long"));
1975 return (Z_ERR);
1976 }
1977 if (optind < argc - 1)
1978 if (strlcat(zarg.bootbuf, " ", sizeof (zarg.bootbuf)) >=
1979 sizeof (zarg.bootbuf)) {
1980 zerror(gettext("Boot argument list too long"));
1981 return (Z_ERR);
1982 }
1983 }
1984
1985
1986 /*
1987 * zoneadmd should be the one to decide whether or not to proceed,
1988 * so even though it seems that the fourth parameter below should
1989 * perhaps be B_TRUE, it really shouldn't be.
1990 */
1991 if (sanity_check(target_zone, CMD_REBOOT, B_TRUE, B_FALSE, B_FALSE)
1992 != Z_OK)
1993 return (Z_ERR);
1994 if (verify_details(CMD_REBOOT, argv) != Z_OK)
1995 return (Z_ERR);
1996
1997 zarg.cmd = Z_REBOOT;
1998 return ((zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) == 0)
1999 ? Z_OK : Z_ERR);
2000 }
2001
2002 static int
2003 get_hook(brand_handle_t bh, char *cmd, size_t len, int (*bp)(brand_handle_t,
2004 const char *, const char *, char *, size_t), char *zonename, char *zonepath)
2005 {
2006 if (strlcpy(cmd, EXEC_PREFIX, len) >= len)
2007 return (Z_ERR);
2008
2009 if (bp(bh, zonename, zonepath, cmd + EXEC_LEN, len - EXEC_LEN) != 0)
2010 return (Z_ERR);
2011
2012 if (strlen(cmd) <= EXEC_LEN)
2013 cmd[0] = '\0';
2014
2015 return (Z_OK);
2016 }
2017
2018 static int
2019 verify_brand(zone_dochandle_t handle, int cmd_num, char *argv[])
2020 {
2021 char cmdbuf[MAXPATHLEN];
2022 int err;
2023 char zonepath[MAXPATHLEN];
2024 brand_handle_t bh = NULL;
2025 int status, i;
2026
2027 /*
2028 * Fetch the verify command from the brand configuration.
2029 * "exec" the command so that the returned status is that of
2030 * the command and not the shell.
2031 */
2032 if (handle == NULL) {
2033 (void) strlcpy(zonepath, "-", sizeof (zonepath));
2034 } else if ((err = zonecfg_get_zonepath(handle, zonepath,
2035 sizeof (zonepath))) != Z_OK) {
2036 errno = err;
2037 zperror(cmd_to_str(cmd_num), B_TRUE);
2038 return (Z_ERR);
2039 }
2040 if ((bh = brand_open(target_brand)) == NULL) {
2041 zerror(gettext("missing or invalid brand"));
2042 return (Z_ERR);
2043 }
2044
2045 /*
2046 * If the brand has its own verification routine, execute it now.
2047 * The verification routine validates the intended zoneadm
2048 * operation for the specific brand. The zoneadm subcommand and
2049 * all its arguments are passed to the routine.
2050 */
2051 err = get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_verify_adm,
2052 target_zone, zonepath);
2053 brand_close(bh);
2054 if (err != Z_OK)
2055 return (Z_BRAND_ERROR);
2056 if (cmdbuf[0] == '\0')
2057 return (Z_OK);
2058
2059 if (strlcat(cmdbuf, cmd_to_str(cmd_num),
2060 sizeof (cmdbuf)) >= sizeof (cmdbuf))
2061 return (Z_ERR);
2062
2063 /* Build the argv string */
2064 i = 0;
2065 while (argv[i] != NULL) {
2066 if ((strlcat(cmdbuf, " ",
2067 sizeof (cmdbuf)) >= sizeof (cmdbuf)) ||
2068 (strlcat(cmdbuf, argv[i++],
2069 sizeof (cmdbuf)) >= sizeof (cmdbuf)))
2070 return (Z_ERR);
2071 }
2072
2073 status = do_subproc(cmdbuf);
2074 err = subproc_status(gettext("brand-specific verification"),
2075 status, B_FALSE);
2076
2077 return ((err == ZONE_SUBPROC_OK) ? Z_OK : Z_BRAND_ERROR);
2078 }
2079
2080 static int
2081 verify_rctls(zone_dochandle_t handle)
2082 {
2083 struct zone_rctltab rctltab;
2084 size_t rbs = rctlblk_size();
2085 rctlblk_t *rctlblk;
2086 int error = Z_INVAL;
2087
2088 if ((rctlblk = malloc(rbs)) == NULL) {
2089 zerror(gettext("failed to allocate %lu bytes: %s"), rbs,
2090 strerror(errno));
2091 return (Z_NOMEM);
2092 }
2093
2094 if (zonecfg_setrctlent(handle) != Z_OK) {
2095 zerror(gettext("zonecfg_setrctlent failed"));
2096 free(rctlblk);
2097 return (error);
2098 }
2099
2100 rctltab.zone_rctl_valptr = NULL;
2101 while (zonecfg_getrctlent(handle, &rctltab) == Z_OK) {
2102 struct zone_rctlvaltab *rctlval;
2103 const char *name = rctltab.zone_rctl_name;
2104
2105 if (!zonecfg_is_rctl(name)) {
2106 zerror(gettext("WARNING: Ignoring unrecognized rctl "
2107 "'%s'."), name);
2108 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2109 rctltab.zone_rctl_valptr = NULL;
2110 continue;
2111 }
2112
2113 for (rctlval = rctltab.zone_rctl_valptr; rctlval != NULL;
2114 rctlval = rctlval->zone_rctlval_next) {
2115 if (zonecfg_construct_rctlblk(rctlval, rctlblk)
2116 != Z_OK) {
2117 zerror(gettext("invalid rctl value: "
2118 "(priv=%s,limit=%s,action%s)"),
2119 rctlval->zone_rctlval_priv,
2120 rctlval->zone_rctlval_limit,
2121 rctlval->zone_rctlval_action);
2122 goto out;
2123 }
2124 if (!zonecfg_valid_rctl(name, rctlblk)) {
2125 zerror(gettext("(priv=%s,limit=%s,action=%s) "
2126 "is not a valid value for rctl '%s'"),
2127 rctlval->zone_rctlval_priv,
2128 rctlval->zone_rctlval_limit,
2129 rctlval->zone_rctlval_action,
2130 name);
2131 goto out;
2132 }
2133 }
2134 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2135 }
2136 rctltab.zone_rctl_valptr = NULL;
2137 error = Z_OK;
2138 out:
2139 zonecfg_free_rctl_value_list(rctltab.zone_rctl_valptr);
2140 (void) zonecfg_endrctlent(handle);
2141 free(rctlblk);
2142 return (error);
2143 }
2144
2145 static int
2146 verify_pool(zone_dochandle_t handle)
2147 {
2148 char poolname[MAXPATHLEN];
2149 pool_conf_t *poolconf;
2150 pool_t *pool;
2151 int status;
2152 int error;
2153
2154 /*
2155 * This ends up being very similar to the check done in zoneadmd.
2156 */
2157 error = zonecfg_get_pool(handle, poolname, sizeof (poolname));
2158 if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
2159 /*
2160 * No pool specified.
2161 */
2162 return (0);
2163 }
2164 if (error != Z_OK) {
2165 zperror(gettext("Unable to retrieve pool name from "
2166 "configuration"), B_TRUE);
2167 return (error);
2168 }
2169 /*
2170 * Don't do anything if pools aren't enabled.
2171 */
2172 if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
2173 zerror(gettext("WARNING: pools facility not active; "
2174 "zone will not be bound to pool '%s'."), poolname);
2175 return (Z_OK);
2176 }
2177 /*
2178 * Try to provide a sane error message if the requested pool doesn't
2179 * exist. It isn't clear that pools-related failures should
2180 * necessarily translate to a failure to verify the zone configuration,
2181 * hence they are not considered errors.
2182 */
2183 if ((poolconf = pool_conf_alloc()) == NULL) {
2184 zerror(gettext("WARNING: pool_conf_alloc failed; "
2185 "using default pool"));
2186 return (Z_OK);
2187 }
2188 if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
2189 PO_SUCCESS) {
2190 zerror(gettext("WARNING: pool_conf_open failed; "
2191 "using default pool"));
2192 pool_conf_free(poolconf);
2193 return (Z_OK);
2194 }
2195 pool = pool_get_pool(poolconf, poolname);
2196 (void) pool_conf_close(poolconf);
2197 pool_conf_free(poolconf);
2198 if (pool == NULL) {
2199 zerror(gettext("WARNING: pool '%s' not found. "
2200 "using default pool"), poolname);
2201 }
2202
2203 return (Z_OK);
2204 }
2205
2206 /*
2207 * Verify that the special device/file system exists and is valid.
2208 */
2209 static int
2210 verify_fs_special(struct zone_fstab *fstab)
2211 {
2212 struct stat64 st;
2213
2214 /*
2215 * This validation is really intended for standard zone administration.
2216 * If we are in a mini-root or some other upgrade situation where
2217 * we are using the scratch zone, just by-pass this.
2218 */
2219 if (zonecfg_in_alt_root())
2220 return (Z_OK);
2221
2222 if (strcmp(fstab->zone_fs_type, MNTTYPE_ZFS) == 0)
2223 return (verify_fs_zfs(fstab));
2224
2225 if (stat64(fstab->zone_fs_special, &st) != 0) {
2226 (void) fprintf(stderr, gettext("could not verify fs "
2227 "%s: could not access %s: %s\n"), fstab->zone_fs_dir,
2228 fstab->zone_fs_special, strerror(errno));
2229 return (Z_ERR);
2230 }
2231
2232 if (strcmp(st.st_fstype, MNTTYPE_NFS) == 0) {
2233 /*
2234 * TRANSLATION_NOTE
2235 * fs and NFS are literals that should
2236 * not be translated.
2237 */
2238 (void) fprintf(stderr, gettext("cannot verify "
2239 "fs %s: NFS mounted file system.\n"
2240 "\tA local file system must be used.\n"),
2241 fstab->zone_fs_special);
2242 return (Z_ERR);
2243 }
2244
2245 return (Z_OK);
2246 }
2247
2248 static int
2249 isregfile(const char *path)
2250 {
2251 struct stat64 st;
2252
2253 if (stat64(path, &st) == -1)
2254 return (-1);
2255
2256 return (S_ISREG(st.st_mode));
2257 }
2258
2259 static int
2260 verify_filesystems(zone_dochandle_t handle)
2261 {
2262 int return_code = Z_OK;
2263 struct zone_fstab fstab;
2264 char cmdbuf[MAXPATHLEN];
2265 struct stat st;
2266
2267 /*
2268 * Since the actual mount point is not known until the dependent mounts
2269 * are performed, we don't attempt any path validation here: that will
2270 * happen later when zoneadmd actually does the mounts.
2271 */
2272 if (zonecfg_setfsent(handle) != Z_OK) {
2273 (void) fprintf(stderr, gettext("could not verify file systems: "
2274 "unable to enumerate mounts\n"));
2275 return (Z_ERR);
2276 }
2277 while (zonecfg_getfsent(handle, &fstab) == Z_OK) {
2278 if (!zonecfg_valid_fs_type(fstab.zone_fs_type)) {
2279 (void) fprintf(stderr, gettext("cannot verify fs %s: "
2280 "type %s is not allowed.\n"), fstab.zone_fs_dir,
2281 fstab.zone_fs_type);
2282 return_code = Z_ERR;
2283 goto next_fs;
2284 }
2285 /*
2286 * Verify /usr/lib/fs/<fstype>/mount exists.
2287 */
2288 if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/mount",
2289 fstab.zone_fs_type) > sizeof (cmdbuf)) {
2290 (void) fprintf(stderr, gettext("cannot verify fs %s: "
2291 "type %s is too long.\n"), fstab.zone_fs_dir,
2292 fstab.zone_fs_type);
2293 return_code = Z_ERR;
2294 goto next_fs;
2295 }
2296 if (stat(cmdbuf, &st) != 0) {
2297 (void) fprintf(stderr, gettext("could not verify fs "
2298 "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2299 cmdbuf, strerror(errno));
2300 return_code = Z_ERR;
2301 goto next_fs;
2302 }
2303 if (!S_ISREG(st.st_mode)) {
2304 (void) fprintf(stderr, gettext("could not verify fs "
2305 "%s: %s is not a regular file\n"),
2306 fstab.zone_fs_dir, cmdbuf);
2307 return_code = Z_ERR;
2308 goto next_fs;
2309 }
2310 /*
2311 * If zone_fs_raw is set, verify that there's an fsck
2312 * binary for it. If zone_fs_raw is not set, and it's
2313 * not a regular file (lofi mount), and there's an fsck
2314 * binary for it, complain.
2315 */
2316 if (snprintf(cmdbuf, sizeof (cmdbuf), "/usr/lib/fs/%s/fsck",
2317 fstab.zone_fs_type) > sizeof (cmdbuf)) {
2318 (void) fprintf(stderr, gettext("cannot verify fs %s: "
2319 "type %s is too long.\n"), fstab.zone_fs_dir,
2320 fstab.zone_fs_type);
2321 return_code = Z_ERR;
2322 goto next_fs;
2323 }
2324 if (fstab.zone_fs_raw[0] != '\0' &&
2325 (stat(cmdbuf, &st) != 0 || !S_ISREG(st.st_mode))) {
2326 (void) fprintf(stderr, gettext("cannot verify fs %s: "
2327 "'raw' device specified but "
2328 "no fsck executable exists for %s\n"),
2329 fstab.zone_fs_dir, fstab.zone_fs_type);
2330 return_code = Z_ERR;
2331 goto next_fs;
2332 } else if (fstab.zone_fs_raw[0] == '\0' &&
2333 stat(cmdbuf, &st) == 0 &&
2334 isregfile(fstab.zone_fs_special) != 1) {
2335 (void) fprintf(stderr, gettext("could not verify fs "
2336 "%s: must specify 'raw' device for %s "
2337 "file systems\n"),
2338 fstab.zone_fs_dir, fstab.zone_fs_type);
2339 return_code = Z_ERR;
2340 goto next_fs;
2341 }
2342
2343 /* Verify fs_special. */
2344 if ((return_code = verify_fs_special(&fstab)) != Z_OK)
2345 goto next_fs;
2346
2347 /* Verify fs_raw. */
2348 if (fstab.zone_fs_raw[0] != '\0' &&
2349 stat(fstab.zone_fs_raw, &st) != 0) {
2350 /*
2351 * TRANSLATION_NOTE
2352 * fs is a literal that should not be translated.
2353 */
2354 (void) fprintf(stderr, gettext("could not verify fs "
2355 "%s: could not access %s: %s\n"), fstab.zone_fs_dir,
2356 fstab.zone_fs_raw, strerror(errno));
2357 return_code = Z_ERR;
2358 goto next_fs;
2359 }
2360 next_fs:
2361 zonecfg_free_fs_option_list(fstab.zone_fs_options);
2362 }
2363 (void) zonecfg_endfsent(handle);
2364
2365 return (return_code);
2366 }
2367
2368 static int
2369 verify_limitpriv(zone_dochandle_t handle)
2370 {
2371 char *privname = NULL;
2372 int err;
2373 priv_set_t *privs;
2374
2375 if ((privs = priv_allocset()) == NULL) {
2376 zperror(gettext("failed to allocate privilege set"), B_FALSE);
2377 return (Z_NOMEM);
2378 }
2379 err = zonecfg_get_privset(handle, privs, &privname);
2380 switch (err) {
2381 case Z_OK:
2382 break;
2383 case Z_PRIV_PROHIBITED:
2384 (void) fprintf(stderr, gettext("privilege \"%s\" is not "
2385 "permitted within the zone's privilege set\n"), privname);
2386 break;
2387 case Z_PRIV_REQUIRED:
2388 (void) fprintf(stderr, gettext("required privilege \"%s\" is "
2389 "missing from the zone's privilege set\n"), privname);
2390 break;
2391 case Z_PRIV_UNKNOWN:
2392 (void) fprintf(stderr, gettext("unknown privilege \"%s\" "
2393 "specified in the zone's privilege set\n"), privname);
2394 break;
2395 default:
2396 zperror(
2397 gettext("failed to determine the zone's privilege set"),
2398 B_TRUE);
2399 break;
2400 }
2401 free(privname);
2402 priv_freeset(privs);
2403 return (err);
2404 }
2405
2406 static void
2407 free_local_netifs(int if_cnt, struct net_if **if_list)
2408 {
2409 int i;
2410
2411 for (i = 0; i < if_cnt; i++) {
2412 free(if_list[i]->name);
2413 free(if_list[i]);
2414 }
2415 free(if_list);
2416 }
2417
2418 /*
2419 * Get a list of the network interfaces, along with their address families,
2420 * that are plumbed in the global zone. See if_tcp(7p) for a description
2421 * of the ioctls used here.
2422 */
2423 static int
2424 get_local_netifs(int *if_cnt, struct net_if ***if_list)
2425 {
2426 int s;
2427 int i;
2428 int res = Z_OK;
2429 int space_needed;
2430 int cnt = 0;
2431 struct lifnum if_num;
2432 struct lifconf if_conf;
2433 struct lifreq *if_reqp;
2434 char *if_buf;
2435 struct net_if **local_ifs = NULL;
2436
2437 *if_cnt = 0;
2438 *if_list = NULL;
2439
2440 if ((s = socket(SOCKET_AF(AF_INET), SOCK_DGRAM, 0)) < 0)
2441 return (Z_ERR);
2442
2443 /*
2444 * Come back here in the unlikely event that the number of interfaces
2445 * increases between the time we get the count and the time we do the
2446 * SIOCGLIFCONF ioctl.
2447 */
2448 retry:
2449 /* Get the number of interfaces. */
2450 if_num.lifn_family = AF_UNSPEC;
2451 if_num.lifn_flags = LIFC_NOXMIT;
2452 if (ioctl(s, SIOCGLIFNUM, &if_num) < 0) {
2453 (void) close(s);
2454 return (Z_ERR);
2455 }
2456
2457 /* Get the interface configuration list. */
2458 space_needed = if_num.lifn_count * sizeof (struct lifreq);
2459 if ((if_buf = malloc(space_needed)) == NULL) {
2460 (void) close(s);
2461 return (Z_ERR);
2462 }
2463 if_conf.lifc_family = AF_UNSPEC;
2464 if_conf.lifc_flags = LIFC_NOXMIT;
2465 if_conf.lifc_len = space_needed;
2466 if_conf.lifc_buf = if_buf;
2467 if (ioctl(s, SIOCGLIFCONF, &if_conf) < 0) {
2468 free(if_buf);
2469 /*
2470 * SIOCGLIFCONF returns EINVAL if the buffer we passed in is
2471 * too small. In this case go back and get the new if cnt.
2472 */
2473 if (errno == EINVAL)
2474 goto retry;
2475
2476 (void) close(s);
2477 return (Z_ERR);
2478 }
2479 (void) close(s);
2480
2481 /* Get the name and address family for each interface. */
2482 if_reqp = if_conf.lifc_req;
2483 for (i = 0; i < (if_conf.lifc_len / sizeof (struct lifreq)); i++) {
2484 struct net_if **p;
2485 struct lifreq req;
2486
2487 if (strcmp(LOOPBACK_IF, if_reqp->lifr_name) == 0) {
2488 if_reqp++;
2489 continue;
2490 }
2491
2492 if ((s = socket(SOCKET_AF(if_reqp->lifr_addr.ss_family),
2493 SOCK_DGRAM, 0)) == -1) {
2494 res = Z_ERR;
2495 break;
2496 }
2497
2498 (void) strncpy(req.lifr_name, if_reqp->lifr_name,
2499 sizeof (req.lifr_name));
2500 if (ioctl(s, SIOCGLIFADDR, &req) < 0) {
2501 (void) close(s);
2502 if_reqp++;
2503 continue;
2504 }
2505
2506 if ((p = (struct net_if **)realloc(local_ifs,
2507 sizeof (struct net_if *) * (cnt + 1))) == NULL) {
2508 res = Z_ERR;
2509 break;
2510 }
2511 local_ifs = p;
2512
2513 if ((local_ifs[cnt] = malloc(sizeof (struct net_if))) == NULL) {
2514 res = Z_ERR;
2515 break;
2516 }
2517
2518 if ((local_ifs[cnt]->name = strdup(if_reqp->lifr_name))
2519 == NULL) {
2520 free(local_ifs[cnt]);
2521 res = Z_ERR;
2522 break;
2523 }
2524 local_ifs[cnt]->af = req.lifr_addr.ss_family;
2525 cnt++;
2526
2527 (void) close(s);
2528 if_reqp++;
2529 }
2530
2531 free(if_buf);
2532
2533 if (res != Z_OK) {
2534 free_local_netifs(cnt, local_ifs);
2535 } else {
2536 *if_cnt = cnt;
2537 *if_list = local_ifs;
2538 }
2539
2540 return (res);
2541 }
2542
2543 static char *
2544 af2str(int af)
2545 {
2546 switch (af) {
2547 case AF_INET:
2548 return ("IPv4");
2549 case AF_INET6:
2550 return ("IPv6");
2551 default:
2552 return ("Unknown");
2553 }
2554 }
2555
2556 /*
2557 * Cross check the network interface name and address family with the
2558 * interfaces that are set up in the global zone so that we can print the
2559 * appropriate error message.
2560 */
2561 static void
2562 print_net_err(char *phys, char *addr, int af, char *msg)
2563 {
2564 int i;
2565 int local_if_cnt = 0;
2566 struct net_if **local_ifs = NULL;
2567 boolean_t found_if = B_FALSE;
2568 boolean_t found_af = B_FALSE;
2569
2570 if (get_local_netifs(&local_if_cnt, &local_ifs) != Z_OK) {
2571 (void) fprintf(stderr,
2572 gettext("could not verify %s %s=%s %s=%s\n\t%s\n"),
2573 "net", "address", addr, "physical", phys, msg);
2574 return;
2575 }
2576
2577 for (i = 0; i < local_if_cnt; i++) {
2578 if (strcmp(phys, local_ifs[i]->name) == 0) {
2579 found_if = B_TRUE;
2580 if (af == local_ifs[i]->af) {
2581 found_af = B_TRUE;
2582 break;
2583 }
2584 }
2585 }
2586
2587 free_local_netifs(local_if_cnt, local_ifs);
2588
2589 if (!found_if) {
2590 (void) fprintf(stderr,
2591 gettext("could not verify %s %s=%s\n\t"
2592 "network interface %s is not plumbed in the global zone\n"),
2593 "net", "physical", phys, phys);
2594 return;
2595 }
2596
2597 /*
2598 * Print this error if we were unable to find the address family
2599 * for this interface. If the af variable is not initialized to
2600 * to something meaningful by the caller (not AF_UNSPEC) then we
2601 * also skip this message since it wouldn't be informative.
2602 */
2603 if (!found_af && af != AF_UNSPEC) {
2604 (void) fprintf(stderr,
2605 gettext("could not verify %s %s=%s %s=%s\n\tthe %s address "
2606 "family is not configured on this network interface in "
2607 "the\n\tglobal zone\n"),
2608 "net", "address", addr, "physical", phys, af2str(af));
2609 return;
2610 }
2611
2612 (void) fprintf(stderr,
2613 gettext("could not verify %s %s=%s %s=%s\n\t%s\n"),
2614 "net", "address", addr, "physical", phys, msg);
2615 }
2616
2617 static int
2618 verify_handle(int cmd_num, zone_dochandle_t handle, char *argv[])
2619 {
2620 struct zone_nwiftab nwiftab;
2621 int return_code = Z_OK;
2622 int err;
2623 boolean_t in_alt_root;
2624 zone_iptype_t iptype;
2625 dladm_handle_t dh;
2626 dladm_status_t status;
2627 datalink_id_t linkid;
2628 char errmsg[DLADM_STRSIZE];
2629
2630 in_alt_root = zonecfg_in_alt_root();
2631 if (in_alt_root)
2632 goto no_net;
2633
2634 if ((err = zonecfg_get_iptype(handle, &iptype)) != Z_OK) {
2635 errno = err;
2636 zperror(cmd_to_str(cmd_num), B_TRUE);
2637 zonecfg_fini_handle(handle);
2638 return (Z_ERR);
2639 }
2640 if ((err = zonecfg_setnwifent(handle)) != Z_OK) {
2641 errno = err;
2642 zperror(cmd_to_str(cmd_num), B_TRUE);
2643 zonecfg_fini_handle(handle);
2644 return (Z_ERR);
2645 }
2646 while (zonecfg_getnwifent(handle, &nwiftab) == Z_OK) {
2647 struct lifreq lifr;
2648 sa_family_t af = AF_UNSPEC;
2649 char dl_owner_zname[ZONENAME_MAX];
2650 zoneid_t dl_owner_zid;
2651 zoneid_t target_zid;
2652 int res;
2653
2654 /* skip any loopback interfaces */
2655 if (strcmp(nwiftab.zone_nwif_physical, "lo0") == 0)
2656 continue;
2657 switch (iptype) {
2658 case ZS_SHARED:
2659 if ((res = zonecfg_valid_net_address(
2660 nwiftab.zone_nwif_address, &lifr)) != Z_OK) {
2661 print_net_err(nwiftab.zone_nwif_physical,
2662 nwiftab.zone_nwif_address, af,
2663 zonecfg_strerror(res));
2664 return_code = Z_ERR;
2665 continue;
2666 }
2667 af = lifr.lifr_addr.ss_family;
2668 if (!zonecfg_ifname_exists(af,
2669 nwiftab.zone_nwif_physical)) {
2670 /*
2671 * The interface failed to come up. We continue
2672 * on anyway for the sake of consistency: a
2673 * zone is not shut down if the interface fails
2674 * any time after boot, nor does the global zone
2675 * fail to boot if an interface fails.
2676 */
2677 (void) fprintf(stderr,
2678 gettext("WARNING: skipping network "
2679 "interface '%s' which may not be "
2680 "present/plumbed in the global "
2681 "zone.\n"),
2682 nwiftab.zone_nwif_physical);
2683 }
2684 break;
2685 case ZS_EXCLUSIVE:
2686 /* Warning if it exists for either IPv4 or IPv6 */
2687
2688 if (zonecfg_ifname_exists(AF_INET,
2689 nwiftab.zone_nwif_physical) ||
2690 zonecfg_ifname_exists(AF_INET6,
2691 nwiftab.zone_nwif_physical)) {
2692 (void) fprintf(stderr,
2693 gettext("WARNING: skipping network "
2694 "interface '%s' which is used in the "
2695 "global zone.\n"),
2696 nwiftab.zone_nwif_physical);
2697 break;
2698 }
2699
2700 /*
2701 * Verify that the datalink exists and that it isn't
2702 * already assigned to a zone.
2703 */
2704 if ((status = dladm_open(&dh)) == DLADM_STATUS_OK) {
2705 status = dladm_name2info(dh,
2706 nwiftab.zone_nwif_physical, &linkid, NULL,
2707 NULL, NULL);
2708 dladm_close(dh);
2709 }
2710 if (status != DLADM_STATUS_OK) {
2711 (void) fprintf(stderr,
2712 gettext("WARNING: skipping network "
2713 "interface '%s': %s\n"),
2714 nwiftab.zone_nwif_physical,
2715 dladm_status2str(status, errmsg));
2716 break;
2717 }
2718 dl_owner_zid = ALL_ZONES;
2719 if (zone_check_datalink(&dl_owner_zid, linkid) != 0)
2720 break;
2721
2722 /*
2723 * If the zone being verified is
2724 * running and owns the interface
2725 */
2726 target_zid = getzoneidbyname(target_zone);
2727 if (target_zid == dl_owner_zid)
2728 break;
2729
2730 /* Zone id match failed, use name to check */
2731 if (getzonenamebyid(dl_owner_zid, dl_owner_zname,
2732 ZONENAME_MAX) < 0) {
2733 /* No name, show ID instead */
2734 (void) snprintf(dl_owner_zname, ZONENAME_MAX,
2735 "<%d>", dl_owner_zid);
2736 } else if (strcmp(dl_owner_zname, target_zone) == 0)
2737 break;
2738
2739 /*
2740 * Note here we only report a warning that
2741 * the interface is already in use by another
2742 * running zone, and the verify process just
2743 * goes on, if the interface is still in use
2744 * when this zone really boots up, zoneadmd
2745 * will find it. If the name of the zone which
2746 * owns this interface cannot be determined,
2747 * then it is not possible to determine if there
2748 * is a conflict so just report it as a warning.
2749 */
2750 (void) fprintf(stderr,
2751 gettext("WARNING: skipping network interface "
2752 "'%s' which is used by the non-global zone "
2753 "'%s'.\n"), nwiftab.zone_nwif_physical,
2754 dl_owner_zname);
2755 break;
2756 }
2757 }
2758 (void) zonecfg_endnwifent(handle);
2759 no_net:
2760
2761 /* verify that lofs has not been excluded from the kernel */
2762 if (!(cmd_num == CMD_DETACH || cmd_num == CMD_ATTACH ||
2763 cmd_num == CMD_MOVE || cmd_num == CMD_CLONE) &&
2764 modctl(MODLOAD, 1, "fs/lofs", NULL) != 0) {
2765 if (errno == ENXIO)
2766 (void) fprintf(stderr, gettext("could not verify "
2767 "lofs(7FS): possibly excluded in /etc/system\n"));
2768 else
2769 (void) fprintf(stderr, gettext("could not verify "
2770 "lofs(7FS): %s\n"), strerror(errno));
2771 return_code = Z_ERR;
2772 }
2773
2774 if (verify_filesystems(handle) != Z_OK)
2775 return_code = Z_ERR;
2776 if (!in_alt_root && verify_rctls(handle) != Z_OK)
2777 return_code = Z_ERR;
2778 if (!in_alt_root && verify_pool(handle) != Z_OK)
2779 return_code = Z_ERR;
2780 if (!in_alt_root && verify_brand(handle, cmd_num, argv) != Z_OK)
2781 return_code = Z_ERR;
2782 if (!in_alt_root && verify_datasets(handle) != Z_OK)
2783 return_code = Z_ERR;
2784
2785 /*
2786 * As the "mount" command is used for patching/upgrading of zones
2787 * or other maintenance processes, the zone's privilege set is not
2788 * checked in this case. Instead, the default, safe set of
2789 * privileges will be used when this zone is created in the
2790 * kernel.
2791 */
2792 if (!in_alt_root && cmd_num != CMD_MOUNT &&
2793 verify_limitpriv(handle) != Z_OK)
2794 return_code = Z_ERR;
2795
2796 return (return_code);
2797 }
2798
2799 /*
2800 * Called when readying or booting a zone. We double check that the zone's
2801 * debug ID is set and is unique. This covers the case of pre-existing zones
2802 * with no ID. Also, its possible that a zone was migrated to this host
2803 * and as a result it has a duplicate ID. In this case we preserve the ID
2804 * of the first zone we match on in the index file (since it was there before
2805 * the current zone) and we assign a new unique ID to the current zone.
2806 * Return true if we assigned a new ID, indicating that the zone configuration
2807 * needs to be saved.
2808 */
2809 static boolean_t
2810 verify_fix_did(zone_dochandle_t handle)
2811 {
2812 zoneid_t mydid;
2813 zone_entry_t zent;
2814 FILE *cookie;
2815 char *name;
2816 boolean_t fix = B_FALSE;
2817
2818 mydid = zonecfg_get_did(handle);
2819 if (mydid == -1) {
2820 zonecfg_set_did(handle);
2821 return (B_TRUE);
2822 }
2823
2824 /* Get the full list of zones from the configuration. */
2825 cookie = setzoneent();
2826 while ((name = getzoneent(cookie)) != NULL) {
2827 if (strcmp(target_zone, name) == 0) {
2828 free(name);
2829 break; /* Once we find our entry, stop. */
2830 }
2831
2832 if (strcmp(name, "global") == 0 ||
2833 lookup_zone_info(name, ZONE_ID_UNDEFINED, &zent) != Z_OK) {
2834 free(name);
2835 continue;
2836 }
2837
2838 free(name);
2839 if (zent.zdid == mydid) {
2840 fix = B_TRUE;
2841 break;
2842 }
2843 }
2844 endzoneent(cookie);
2845
2846 if (fix) {
2847 zonecfg_set_did(handle);
2848 return (B_TRUE);
2849 }
2850
2851 return (B_FALSE);
2852 }
2853
2854 static int
2855 verify_details(int cmd_num, char *argv[])
2856 {
2857 zone_dochandle_t handle;
2858 char zonepath[MAXPATHLEN], checkpath[MAXPATHLEN];
2859 int return_code = Z_OK;
2860 int err;
2861
2862 if ((handle = zonecfg_init_handle()) == NULL) {
2863 zperror(cmd_to_str(cmd_num), B_TRUE);
2864 return (Z_ERR);
2865 }
2866 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
2867 errno = err;
2868 zperror(cmd_to_str(cmd_num), B_TRUE);
2869 zonecfg_fini_handle(handle);
2870 return (Z_ERR);
2871 }
2872 if ((err = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath))) !=
2873 Z_OK) {
2874 errno = err;
2875 zperror(cmd_to_str(cmd_num), B_TRUE);
2876 zonecfg_fini_handle(handle);
2877 return (Z_ERR);
2878 }
2879 /*
2880 * zonecfg_get_zonepath() gets its data from the XML repository.
2881 * Verify this against the index file, which is checked first by
2882 * zone_get_zonepath(). If they don't match, bail out.
2883 */
2884 if ((err = zone_get_zonepath(target_zone, checkpath,
2885 sizeof (checkpath))) != Z_OK) {
2886 errno = err;
2887 zperror2(target_zone, gettext("could not get zone path"));
2888 zonecfg_fini_handle(handle);
2889 return (Z_ERR);
2890 }
2891 if (strcmp(zonepath, checkpath) != 0) {
2892 /*
2893 * TRANSLATION_NOTE
2894 * XML and zonepath are literals that should not be translated.
2895 */
2896 (void) fprintf(stderr, gettext("The XML repository has "
2897 "zonepath '%s',\nbut the index file has zonepath '%s'.\n"
2898 "These must match, so fix the incorrect entry.\n"),
2899 zonepath, checkpath);
2900 zonecfg_fini_handle(handle);
2901 return (Z_ERR);
2902 }
2903 if (cmd_num != CMD_ATTACH &&
2904 validate_zonepath(zonepath, cmd_num) != Z_OK) {
2905 (void) fprintf(stderr, gettext("could not verify zonepath %s "
2906 "because of the above errors.\n"), zonepath);
2907 return_code = Z_ERR;
2908 }
2909
2910 if (verify_handle(cmd_num, handle, argv) != Z_OK)
2911 return_code = Z_ERR;
2912
2913 if (cmd_num == CMD_READY || cmd_num == CMD_BOOT) {
2914 int vcommit = 0, obscommit = 0;
2915
2916 vcommit = verify_fix_did(handle);
2917 obscommit = zonecfg_fix_obsolete(handle);
2918
2919 if (vcommit || obscommit)
2920 if (zonecfg_save(handle) != Z_OK)
2921 (void) fprintf(stderr, gettext("Could not save "
2922 "updated configuration.\n"));
2923 }
2924
2925 zonecfg_fini_handle(handle);
2926 if (return_code == Z_ERR)
2927 (void) fprintf(stderr,
2928 gettext("%s: zone %s failed to verify\n"),
2929 execname, target_zone);
2930 return (return_code);
2931 }
2932
2933 static int
2934 verify_func(int argc, char *argv[])
2935 {
2936 int arg;
2937
2938 optind = 0;
2939 if ((arg = getopt(argc, argv, "?")) != EOF) {
2940 switch (arg) {
2941 case '?':
2942 sub_usage(SHELP_VERIFY, CMD_VERIFY);
2943 return (optopt == '?' ? Z_OK : Z_USAGE);
2944 default:
2945 sub_usage(SHELP_VERIFY, CMD_VERIFY);
2946 return (Z_USAGE);
2947 }
2948 }
2949 if (argc > optind) {
2950 sub_usage(SHELP_VERIFY, CMD_VERIFY);
2951 return (Z_USAGE);
2952 }
2953 if (sanity_check(target_zone, CMD_VERIFY, B_FALSE, B_FALSE, B_FALSE)
2954 != Z_OK)
2955 return (Z_ERR);
2956 return (verify_details(CMD_VERIFY, argv));
2957 }
2958
2959 static int
2960 addoptions(char *buf, char *argv[], size_t len)
2961 {
2962 int i = 0;
2963
2964 if (buf[0] == '\0')
2965 return (Z_OK);
2966
2967 while (argv[i] != NULL) {
2968 if (strlcat(buf, " ", len) >= len ||
2969 strlcat(buf, argv[i++], len) >= len) {
2970 zerror("Command line too long");
2971 return (Z_ERR);
2972 }
2973 }
2974
2975 return (Z_OK);
2976 }
2977
2978 static int
2979 addopt(char *buf, int opt, char *optarg, size_t bufsize)
2980 {
2981 char optstring[4];
2982
2983 if (opt > 0)
2984 (void) sprintf(optstring, " -%c", opt);
2985 else
2986 (void) strcpy(optstring, " ");
2987
2988 if ((strlcat(buf, optstring, bufsize) > bufsize))
2989 return (Z_ERR);
2990
2991 if ((optarg != NULL) && (strlcat(buf, optarg, bufsize) > bufsize))
2992 return (Z_ERR);
2993
2994 return (Z_OK);
2995 }
2996
2997 /* ARGSUSED */
2998 static int
2999 install_func(int argc, char *argv[])
3000 {
3001 char cmdbuf[MAXPATHLEN];
3002 char postcmdbuf[MAXPATHLEN];
3003 int lockfd;
3004 int arg, err, subproc_err;
3005 char zonepath[MAXPATHLEN];
3006 brand_handle_t bh = NULL;
3007 int status;
3008 boolean_t do_postinstall = B_FALSE;
3009 boolean_t brand_help = B_FALSE;
3010 char opts[128];
3011
3012 if (target_zone == NULL) {
3013 sub_usage(SHELP_INSTALL, CMD_INSTALL);
3014 return (Z_USAGE);
3015 }
3016
3017 if (zonecfg_in_alt_root()) {
3018 zerror(gettext("cannot install zone in alternate root"));
3019 return (Z_ERR);
3020 }
3021
3022 if ((err = zone_get_zonepath(target_zone, zonepath,
3023 sizeof (zonepath))) != Z_OK) {
3024 errno = err;
3025 zperror2(target_zone, gettext("could not get zone path"));
3026 return (Z_ERR);
3027 }
3028
3029 /* Fetch the install command from the brand configuration. */
3030 if ((bh = brand_open(target_brand)) == NULL) {
3031 zerror(gettext("missing or invalid brand"));
3032 return (Z_ERR);
3033 }
3034
3035 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_install,
3036 target_zone, zonepath) != Z_OK) {
3037 zerror("invalid brand configuration: missing install resource");
3038 brand_close(bh);
3039 return (Z_ERR);
3040 }
3041
3042 if (get_hook(bh, postcmdbuf, sizeof (postcmdbuf), brand_get_postinstall,
3043 target_zone, zonepath) != Z_OK) {
3044 zerror("invalid brand configuration: missing postinstall "
3045 "resource");
3046 brand_close(bh);
3047 return (Z_ERR);
3048 }
3049
3050 if (postcmdbuf[0] != '\0')
3051 do_postinstall = B_TRUE;
3052
3053 (void) strcpy(opts, "?x:");
3054 /*
3055 * Fetch the list of recognized command-line options from
3056 * the brand configuration file.
3057 */
3058 if (brand_get_installopts(bh, opts + strlen(opts),
3059 sizeof (opts) - strlen(opts)) != 0) {
3060 zerror("invalid brand configuration: missing "
3061 "install options resource");
3062 brand_close(bh);
3063 return (Z_ERR);
3064 }
3065
3066 brand_close(bh);
3067
3068 if (cmdbuf[0] == '\0') {
3069 zerror("Missing brand install command");
3070 return (Z_ERR);
3071 }
3072
3073 /* Check the argv string for args we handle internally */
3074 optind = 0;
3075 opterr = 0;
3076 while ((arg = getopt(argc, argv, opts)) != EOF) {
3077 switch (arg) {
3078 case '?':
3079 if (optopt == '?') {
3080 sub_usage(SHELP_INSTALL, CMD_INSTALL);
3081 brand_help = B_TRUE;
3082 }
3083 /* Ignore unknown options - may be brand specific. */
3084 break;
3085 default:
3086 /* Ignore unknown options - may be brand specific. */
3087 break;
3088 }
3089
3090 /*
3091 * Append the option to the command line passed to the
3092 * brand-specific install and postinstall routines.
3093 */
3094 if (addopt(cmdbuf, optopt, optarg, sizeof (cmdbuf)) != Z_OK) {
3095 zerror("Install command line too long");
3096 return (Z_ERR);
3097 }
3098 if (addopt(postcmdbuf, optopt, optarg, sizeof (postcmdbuf))
3099 != Z_OK) {
3100 zerror("Post-Install command line too long");
3101 return (Z_ERR);
3102 }
3103 }
3104
3105 for (; optind < argc; optind++) {
3106 if (addopt(cmdbuf, 0, argv[optind], sizeof (cmdbuf)) != Z_OK) {
3107 zerror("Install command line too long");
3108 return (Z_ERR);
3109 }
3110
3111 if (addopt(postcmdbuf, 0, argv[optind], sizeof (postcmdbuf))
3112 != Z_OK) {
3113 zerror("Post-Install command line too long");
3114 return (Z_ERR);
3115 }
3116 }
3117
3118 if (!brand_help) {
3119 if (sanity_check(target_zone, CMD_INSTALL, B_FALSE, B_TRUE,
3120 B_FALSE) != Z_OK)
3121 return (Z_ERR);
3122 if (verify_details(CMD_INSTALL, argv) != Z_OK)
3123 return (Z_ERR);
3124
3125 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
3126 zerror(gettext("another %s may have an operation in "
3127 "progress."), "zoneadm");
3128 return (Z_ERR);
3129 }
3130 err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
3131 if (err != Z_OK) {
3132 errno = err;
3133 zperror2(target_zone, gettext("could not set state"));
3134 goto done;
3135 }
3136
3137 create_zfs_zonepath(zonepath);
3138 }
3139
3140 status = do_subproc(cmdbuf);
3141 if ((subproc_err =
3142 subproc_status(gettext("brand-specific installation"), status,
3143 B_FALSE)) != ZONE_SUBPROC_OK) {
3144 if (subproc_err == ZONE_SUBPROC_USAGE && !brand_help) {
3145 sub_usage(SHELP_INSTALL, CMD_INSTALL);
3146 zonecfg_release_lock_file(target_zone, lockfd);
3147 return (Z_ERR);
3148 }
3149 errno = subproc_err;
3150 err = Z_ERR;
3151 goto done;
3152 }
3153
3154 if (brand_help)
3155 return (Z_OK);
3156
3157 if ((err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
3158 errno = err;
3159 zperror2(target_zone, gettext("could not set state"));
3160 goto done;
3161 }
3162
3163 if (do_postinstall) {
3164 status = do_subproc(postcmdbuf);
3165
3166 if ((subproc_err =
3167 subproc_status(gettext("brand-specific post-install"),
3168 status, B_FALSE)) != ZONE_SUBPROC_OK) {
3169 errno = subproc_err;
3170 err = Z_ERR;
3171 (void) zone_set_state(target_zone,
3172 ZONE_STATE_INCOMPLETE);
3173 }
3174 }
3175
3176 done:
3177 /*
3178 * If the install script exited with ZONE_SUBPROC_NOTCOMPLETE, try to
3179 * clean up the zone and leave the zone in the CONFIGURED state so that
3180 * another install can be attempted without requiring an uninstall
3181 * first.
3182 */
3183 if (subproc_err == ZONE_SUBPROC_NOTCOMPLETE) {
3184 int temp_err;
3185
3186 if ((temp_err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
3187 errno = err = temp_err;
3188 zperror2(target_zone,
3189 gettext("cleaning up zonepath failed"));
3190 } else if ((temp_err = zone_set_state(target_zone,
3191 ZONE_STATE_CONFIGURED)) != Z_OK) {
3192 errno = err = temp_err;
3193 zperror2(target_zone, gettext("could not set state"));
3194 }
3195 }
3196
3197 if (!brand_help)
3198 zonecfg_release_lock_file(target_zone, lockfd);
3199 return ((err == Z_OK) ? Z_OK : Z_ERR);
3200 }
3201
3202 static void
3203 warn_dev_match(zone_dochandle_t s_handle, char *source_zone,
3204 zone_dochandle_t t_handle, char *target_zone)
3205 {
3206 int err;
3207 struct zone_devtab s_devtab;
3208 struct zone_devtab t_devtab;
3209
3210 if ((err = zonecfg_setdevent(t_handle)) != Z_OK) {
3211 errno = err;
3212 zperror2(target_zone, gettext("could not enumerate devices"));
3213 return;
3214 }
3215
3216 while (zonecfg_getdevent(t_handle, &t_devtab) == Z_OK) {
3217 if ((err = zonecfg_setdevent(s_handle)) != Z_OK) {
3218 errno = err;
3219 zperror2(source_zone,
3220 gettext("could not enumerate devices"));
3221 (void) zonecfg_enddevent(t_handle);
3222 return;
3223 }
3224
3225 while (zonecfg_getdevent(s_handle, &s_devtab) == Z_OK) {
3226 /*
3227 * Use fnmatch to catch the case where wildcards
3228 * were used in one zone and the other has an
3229 * explicit entry (e.g. /dev/dsk/c0t0d0s6 vs.
3230 * /dev/\*dsk/c0t0d0s6).
3231 */
3232 if (fnmatch(t_devtab.zone_dev_match,
3233 s_devtab.zone_dev_match, FNM_PATHNAME) == 0 ||
3234 fnmatch(s_devtab.zone_dev_match,
3235 t_devtab.zone_dev_match, FNM_PATHNAME) == 0) {
3236 (void) fprintf(stderr,
3237 gettext("WARNING: device '%s' "
3238 "is configured in both zones.\n"),
3239 t_devtab.zone_dev_match);
3240 break;
3241 }
3242 }
3243 (void) zonecfg_enddevent(s_handle);
3244 }
3245
3246 (void) zonecfg_enddevent(t_handle);
3247 }
3248
3249 /*
3250 * Check if the specified mount option (opt) is contained within the
3251 * options string.
3252 */
3253 static boolean_t
3254 opt_match(char *opt, char *options)
3255 {
3256 char *p;
3257 char *lastp;
3258
3259 if ((p = strtok_r(options, ",", &lastp)) != NULL) {
3260 if (strcmp(p, opt) == 0)
3261 return (B_TRUE);
3262 while ((p = strtok_r(NULL, ",", &lastp)) != NULL) {
3263 if (strcmp(p, opt) == 0)
3264 return (B_TRUE);
3265 }
3266 }
3267
3268 return (B_FALSE);
3269 }
3270
3271 #define RW_LOFS "WARNING: read-write lofs file system on '%s' is configured " \
3272 "in both zones.\n"
3273
3274 static void
3275 print_fs_warnings(struct zone_fstab *s_fstab, struct zone_fstab *t_fstab)
3276 {
3277 /*
3278 * It is ok to have shared lofs mounted fs but we want to warn if
3279 * either is rw since this will effect the other zone.
3280 */
3281 if (strcmp(t_fstab->zone_fs_type, "lofs") == 0) {
3282 zone_fsopt_t *optp;
3283
3284 /* The default is rw so no options means rw */
3285 if (t_fstab->zone_fs_options == NULL ||
3286 s_fstab->zone_fs_options == NULL) {
3287 (void) fprintf(stderr, gettext(RW_LOFS),
3288 t_fstab->zone_fs_special);
3289 return;
3290 }
3291
3292 for (optp = s_fstab->zone_fs_options; optp != NULL;
3293 optp = optp->zone_fsopt_next) {
3294 if (opt_match("rw", optp->zone_fsopt_opt)) {
3295 (void) fprintf(stderr, gettext(RW_LOFS),
3296 s_fstab->zone_fs_special);
3297 return;
3298 }
3299 }
3300
3301 for (optp = t_fstab->zone_fs_options; optp != NULL;
3302 optp = optp->zone_fsopt_next) {
3303 if (opt_match("rw", optp->zone_fsopt_opt)) {
3304 (void) fprintf(stderr, gettext(RW_LOFS),
3305 t_fstab->zone_fs_special);
3306 return;
3307 }
3308 }
3309
3310 return;
3311 }
3312
3313 /*
3314 * TRANSLATION_NOTE
3315 * The first variable is the file system type and the second is
3316 * the file system special device. For example,
3317 * WARNING: ufs file system on '/dev/dsk/c0t0d0s0' ...
3318 */
3319 (void) fprintf(stderr, gettext("WARNING: %s file system on '%s' "
3320 "is configured in both zones.\n"), t_fstab->zone_fs_type,
3321 t_fstab->zone_fs_special);
3322 }
3323
3324 static void
3325 warn_fs_match(zone_dochandle_t s_handle, char *source_zone,
3326 zone_dochandle_t t_handle, char *target_zone)
3327 {
3328 int err;
3329 struct zone_fstab s_fstab;
3330 struct zone_fstab t_fstab;
3331
3332 if ((err = zonecfg_setfsent(t_handle)) != Z_OK) {
3333 errno = err;
3334 zperror2(target_zone,
3335 gettext("could not enumerate file systems"));
3336 return;
3337 }
3338
3339 while (zonecfg_getfsent(t_handle, &t_fstab) == Z_OK) {
3340 if ((err = zonecfg_setfsent(s_handle)) != Z_OK) {
3341 errno = err;
3342 zperror2(source_zone,
3343 gettext("could not enumerate file systems"));
3344 (void) zonecfg_endfsent(t_handle);
3345 return;
3346 }
3347
3348 while (zonecfg_getfsent(s_handle, &s_fstab) == Z_OK) {
3349 if (strcmp(t_fstab.zone_fs_special,
3350 s_fstab.zone_fs_special) == 0) {
3351 print_fs_warnings(&s_fstab, &t_fstab);
3352 break;
3353 }
3354 }
3355 (void) zonecfg_endfsent(s_handle);
3356 }
3357
3358 (void) zonecfg_endfsent(t_handle);
3359 }
3360
3361 /*
3362 * We don't catch the case where you used the same IP address but
3363 * it is not an exact string match. For example, 192.9.0.128 vs. 192.09.0.128.
3364 * However, we're not going to worry about that but we will check for
3365 * a possible netmask on one of the addresses (e.g. 10.0.0.1 and 10.0.0.1/24)
3366 * and handle that case as a match.
3367 */
3368 static void
3369 warn_ip_match(zone_dochandle_t s_handle, char *source_zone,
3370 zone_dochandle_t t_handle, char *target_zone)
3371 {
3372 int err;
3373 struct zone_nwiftab s_nwiftab;
3374 struct zone_nwiftab t_nwiftab;
3375
3376 if ((err = zonecfg_setnwifent(t_handle)) != Z_OK) {
3377 errno = err;
3378 zperror2(target_zone,
3379 gettext("could not enumerate network interfaces"));
3380 return;
3381 }
3382
3383 while (zonecfg_getnwifent(t_handle, &t_nwiftab) == Z_OK) {
3384 char *p;
3385
3386 /* remove an (optional) netmask from the address */
3387 if ((p = strchr(t_nwiftab.zone_nwif_address, '/')) != NULL)
3388 *p = '\0';
3389
3390 if ((err = zonecfg_setnwifent(s_handle)) != Z_OK) {
3391 errno = err;
3392 zperror2(source_zone,
3393 gettext("could not enumerate network interfaces"));
3394 (void) zonecfg_endnwifent(t_handle);
3395 return;
3396 }
3397
3398 while (zonecfg_getnwifent(s_handle, &s_nwiftab) == Z_OK) {
3399 /* remove an (optional) netmask from the address */
3400 if ((p = strchr(s_nwiftab.zone_nwif_address, '/'))
3401 != NULL)
3402 *p = '\0';
3403
3404 /* For exclusive-IP zones, address is not specified. */
3405 if (strlen(s_nwiftab.zone_nwif_address) == 0)
3406 continue;
3407
3408 if (strcmp(t_nwiftab.zone_nwif_address,
3409 s_nwiftab.zone_nwif_address) == 0) {
3410 (void) fprintf(stderr,
3411 gettext("WARNING: network address '%s' "
3412 "is configured in both zones.\n"),
3413 t_nwiftab.zone_nwif_address);
3414 break;
3415 }
3416 }
3417 (void) zonecfg_endnwifent(s_handle);
3418 }
3419
3420 (void) zonecfg_endnwifent(t_handle);
3421 }
3422
3423 static void
3424 warn_dataset_match(zone_dochandle_t s_handle, char *source,
3425 zone_dochandle_t t_handle, char *target)
3426 {
3427 int err;
3428 struct zone_dstab s_dstab;
3429 struct zone_dstab t_dstab;
3430
3431 if ((err = zonecfg_setdsent(t_handle)) != Z_OK) {
3432 errno = err;
3433 zperror2(target, gettext("could not enumerate datasets"));
3434 return;
3435 }
3436
3437 while (zonecfg_getdsent(t_handle, &t_dstab) == Z_OK) {
3438 if ((err = zonecfg_setdsent(s_handle)) != Z_OK) {
3439 errno = err;
3440 zperror2(source,
3441 gettext("could not enumerate datasets"));
3442 (void) zonecfg_enddsent(t_handle);
3443 return;
3444 }
3445
3446 while (zonecfg_getdsent(s_handle, &s_dstab) == Z_OK) {
3447 if (strcmp(t_dstab.zone_dataset_name,
3448 s_dstab.zone_dataset_name) == 0) {
3449 target_zone = source;
3450 zerror(gettext("WARNING: dataset '%s' "
3451 "is configured in both zones.\n"),
3452 t_dstab.zone_dataset_name);
3453 break;
3454 }
3455 }
3456 (void) zonecfg_enddsent(s_handle);
3457 }
3458
3459 (void) zonecfg_enddsent(t_handle);
3460 }
3461
3462 /*
3463 * Check that the clone and its source have the same brand type.
3464 */
3465 static int
3466 valid_brand_clone(char *source_zone, char *target_zone)
3467 {
3468 brand_handle_t bh;
3469 char source_brand[MAXNAMELEN];
3470
3471 if ((zone_get_brand(source_zone, source_brand,
3472 sizeof (source_brand))) != Z_OK) {
3473 (void) fprintf(stderr, "%s: zone '%s': %s\n",
3474 execname, source_zone, gettext("missing or invalid brand"));
3475 return (Z_ERR);
3476 }
3477
3478 if (strcmp(source_brand, target_brand) != 0) {
3479 (void) fprintf(stderr,
3480 gettext("%s: Zones '%s' and '%s' have different brand "
3481 "types.\n"), execname, source_zone, target_zone);
3482 return (Z_ERR);
3483 }
3484
3485 if ((bh = brand_open(target_brand)) == NULL) {
3486 zerror(gettext("missing or invalid brand"));
3487 return (Z_ERR);
3488 }
3489 brand_close(bh);
3490 return (Z_OK);
3491 }
3492
3493 static int
3494 validate_clone(char *source_zone, char *target_zone)
3495 {
3496 int err = Z_OK;
3497 zone_dochandle_t s_handle;
3498 zone_dochandle_t t_handle;
3499
3500 if ((t_handle = zonecfg_init_handle()) == NULL) {
3501 zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3502 return (Z_ERR);
3503 }
3504 if ((err = zonecfg_get_handle(target_zone, t_handle)) != Z_OK) {
3505 errno = err;
3506 zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3507 zonecfg_fini_handle(t_handle);
3508 return (Z_ERR);
3509 }
3510
3511 if ((s_handle = zonecfg_init_handle()) == NULL) {
3512 zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3513 zonecfg_fini_handle(t_handle);
3514 return (Z_ERR);
3515 }
3516 if ((err = zonecfg_get_handle(source_zone, s_handle)) != Z_OK) {
3517 errno = err;
3518 zperror(cmd_to_str(CMD_CLONE), B_TRUE);
3519 goto done;
3520 }
3521
3522 /* verify new zone has same brand type */
3523 err = valid_brand_clone(source_zone, target_zone);
3524 if (err != Z_OK)
3525 goto done;
3526
3527 /* warn about imported fs's which are the same */
3528 warn_fs_match(s_handle, source_zone, t_handle, target_zone);
3529
3530 /* warn about imported IP addresses which are the same */
3531 warn_ip_match(s_handle, source_zone, t_handle, target_zone);
3532
3533 /* warn about imported devices which are the same */
3534 warn_dev_match(s_handle, source_zone, t_handle, target_zone);
3535
3536 /* warn about imported datasets which are the same */
3537 warn_dataset_match(s_handle, source_zone, t_handle, target_zone);
3538
3539 done:
3540 zonecfg_fini_handle(t_handle);
3541 zonecfg_fini_handle(s_handle);
3542
3543 return ((err == Z_OK) ? Z_OK : Z_ERR);
3544 }
3545
3546 static int
3547 copy_zone(char *src, char *dst)
3548 {
3549 boolean_t out_null = B_FALSE;
3550 int status;
3551 char *outfile;
3552 char cmdbuf[MAXPATHLEN * 2 + 128];
3553
3554 if ((outfile = tempnam("/var/log", "zone")) == NULL) {
3555 outfile = "/dev/null";
3556 out_null = B_TRUE;
3557 }
3558
3559 /*
3560 * Use find to get the list of files to copy. We need to skip
3561 * files of type "socket" since cpio can't handle those but that
3562 * should be ok since the app will recreate the socket when it runs.
3563 * We also need to filter out anything under the .zfs subdir. Since
3564 * find is running depth-first, we need the extra egrep to filter .zfs.
3565 */
3566 (void) snprintf(cmdbuf, sizeof (cmdbuf),
3567 "cd %s && /usr/bin/find . -type s -prune -o -depth -print | "
3568 "/usr/bin/egrep -v '^\\./\\.zfs$|^\\./\\.zfs/' | "
3569 "/usr/bin/cpio -pdmuP@ %s > %s 2>&1",
3570 src, dst, outfile);
3571
3572 status = do_subproc(cmdbuf);
3573
3574 if (subproc_status("copy", status, B_TRUE) != ZONE_SUBPROC_OK) {
3575 if (!out_null)
3576 (void) fprintf(stderr, gettext("\nThe copy failed.\n"
3577 "More information can be found in %s\n"), outfile);
3578 return (Z_ERR);
3579 }
3580
3581 if (!out_null)
3582 (void) unlink(outfile);
3583
3584 return (Z_OK);
3585 }
3586
3587 /* ARGSUSED */
3588 int
3589 zfm_print(const struct mnttab *p, void *r)
3590 {
3591 zerror(" %s\n", p->mnt_mountp);
3592 return (0);
3593 }
3594
3595 int
3596 clone_copy(char *source_zonepath, char *zonepath)
3597 {
3598 int err;
3599
3600 /* Don't clone the zone if anything is still mounted there */
3601 if (zonecfg_find_mounts(source_zonepath, NULL, NULL)) {
3602 zerror(gettext("These file systems are mounted on "
3603 "subdirectories of %s.\n"), source_zonepath);
3604 (void) zonecfg_find_mounts(source_zonepath, zfm_print, NULL);
3605 return (Z_ERR);
3606 }
3607
3608 /*
3609 * Attempt to create a ZFS fs for the zonepath. As usual, we don't
3610 * care if this works or not since we always have the default behavior
3611 * of a simple directory for the zonepath.
3612 */
3613 create_zfs_zonepath(zonepath);
3614
3615 (void) printf(gettext("Copying %s..."), source_zonepath);
3616 (void) fflush(stdout);
3617
3618 err = copy_zone(source_zonepath, zonepath);
3619
3620 (void) printf("\n");
3621
3622 return (err);
3623 }
3624
3625 static int
3626 clone_func(int argc, char *argv[])
3627 {
3628 char *source_zone = NULL;
3629 int lockfd;
3630 int err, arg;
3631 char zonepath[MAXPATHLEN];
3632 char source_zonepath[MAXPATHLEN];
3633 zone_state_t state;
3634 zone_entry_t *zent;
3635 char *method = NULL;
3636 char *snapshot = NULL;
3637 char cmdbuf[MAXPATHLEN];
3638 char postcmdbuf[MAXPATHLEN];
3639 char presnapbuf[MAXPATHLEN];
3640 char postsnapbuf[MAXPATHLEN];
3641 char validsnapbuf[MAXPATHLEN];
3642 brand_handle_t bh = NULL;
3643 int status;
3644 boolean_t brand_help = B_FALSE;
3645
3646 if (zonecfg_in_alt_root()) {
3647 zerror(gettext("cannot clone zone in alternate root"));
3648 return (Z_ERR);
3649 }
3650
3651 /* Check the argv string for args we handle internally */
3652 optind = 0;
3653 opterr = 0;
3654 while ((arg = getopt(argc, argv, "?m:s:")) != EOF) {
3655 switch (arg) {
3656 case '?':
3657 if (optopt == '?') {
3658 sub_usage(SHELP_CLONE, CMD_CLONE);
3659 brand_help = B_TRUE;
3660 }
3661 /* Ignore unknown options - may be brand specific. */
3662 break;
3663 case 'm':
3664 method = optarg;
3665 break;
3666 case 's':
3667 snapshot = optarg;
3668 break;
3669 default:
3670 /* Ignore unknown options - may be brand specific. */
3671 break;
3672 }
3673 }
3674
3675 if (argc != (optind + 1)) {
3676 sub_usage(SHELP_CLONE, CMD_CLONE);
3677 return (Z_USAGE);
3678 }
3679
3680 source_zone = argv[optind];
3681
3682 if (!brand_help) {
3683 if (sanity_check(target_zone, CMD_CLONE, B_FALSE, B_TRUE,
3684 B_FALSE) != Z_OK)
3685 return (Z_ERR);
3686 if (verify_details(CMD_CLONE, argv) != Z_OK)
3687 return (Z_ERR);
3688
3689 /*
3690 * We also need to do some extra validation on the source zone.
3691 */
3692 if (strcmp(source_zone, GLOBAL_ZONENAME) == 0) {
3693 zerror(gettext("%s operation is invalid for the "
3694 "global zone."), cmd_to_str(CMD_CLONE));
3695 return (Z_ERR);
3696 }
3697
3698 if (strncmp(source_zone, "SUNW", 4) == 0) {
3699 zerror(gettext("%s operation is invalid for zones "
3700 "starting with SUNW."), cmd_to_str(CMD_CLONE));
3701 return (Z_ERR);
3702 }
3703
3704 if (auth_check(username, source_zone, SOURCE_ZONE) == Z_ERR) {
3705 zerror(gettext("%s operation is invalid because "
3706 "user is not authorized to read source zone."),
3707 cmd_to_str(CMD_CLONE));
3708 return (Z_ERR);
3709 }
3710
3711 zent = lookup_running_zone(source_zone);
3712 if (zent != NULL) {
3713 /* check whether the zone is ready or running */
3714 if ((err = zone_get_state(zent->zname,
3715 &zent->zstate_num)) != Z_OK) {
3716 errno = err;
3717 zperror2(zent->zname, gettext("could not get "
3718 "state"));
3719 /* can't tell, so hedge */
3720 zent->zstate_str = "ready/running";
3721 } else {
3722 zent->zstate_str =
3723 zone_state_str(zent->zstate_num);
3724 }
3725 zerror(gettext("%s operation is invalid for %s zones."),
3726 cmd_to_str(CMD_CLONE), zent->zstate_str);
3727 return (Z_ERR);
3728 }
3729
3730 if ((err = zone_get_state(source_zone, &state)) != Z_OK) {
3731 errno = err;
3732 zperror2(source_zone, gettext("could not get state"));
3733 return (Z_ERR);
3734 }
3735 if (state != ZONE_STATE_INSTALLED) {
3736 (void) fprintf(stderr,
3737 gettext("%s: zone %s is %s; %s is required.\n"),
3738 execname, source_zone, zone_state_str(state),
3739 zone_state_str(ZONE_STATE_INSTALLED));
3740 return (Z_ERR);
3741 }
3742
3743 /*
3744 * The source zone checks out ok, continue with the clone.
3745 */
3746
3747 if (validate_clone(source_zone, target_zone) != Z_OK)
3748 return (Z_ERR);
3749
3750 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
3751 zerror(gettext("another %s may have an operation in "
3752 "progress."), "zoneadm");
3753 return (Z_ERR);
3754 }
3755 }
3756
3757 if ((err = zone_get_zonepath(source_zone, source_zonepath,
3758 sizeof (source_zonepath))) != Z_OK) {
3759 errno = err;
3760 zperror2(source_zone, gettext("could not get zone path"));
3761 goto done;
3762 }
3763
3764 if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
3765 != Z_OK) {
3766 errno = err;
3767 zperror2(target_zone, gettext("could not get zone path"));
3768 goto done;
3769 }
3770
3771 /*
3772 * Fetch the clone and postclone hooks from the brand configuration.
3773 */
3774 if ((bh = brand_open(target_brand)) == NULL) {
3775 zerror(gettext("missing or invalid brand"));
3776 err = Z_ERR;
3777 goto done;
3778 }
3779
3780 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_clone, target_zone,
3781 zonepath) != Z_OK) {
3782 zerror("invalid brand configuration: missing clone resource");
3783 brand_close(bh);
3784 err = Z_ERR;
3785 goto done;
3786 }
3787
3788 if (get_hook(bh, postcmdbuf, sizeof (postcmdbuf), brand_get_postclone,
3789 target_zone, zonepath) != Z_OK) {
3790 zerror("invalid brand configuration: missing postclone "
3791 "resource");
3792 brand_close(bh);
3793 err = Z_ERR;
3794 goto done;
3795 }
3796
3797 if (get_hook(bh, presnapbuf, sizeof (presnapbuf), brand_get_presnap,
3798 source_zone, source_zonepath) != Z_OK) {
3799 zerror("invalid brand configuration: missing presnap "
3800 "resource");
3801 brand_close(bh);
3802 err = Z_ERR;
3803 goto done;
3804 }
3805
3806 if (get_hook(bh, postsnapbuf, sizeof (postsnapbuf), brand_get_postsnap,
3807 source_zone, source_zonepath) != Z_OK) {
3808 zerror("invalid brand configuration: missing postsnap "
3809 "resource");
3810 brand_close(bh);
3811 err = Z_ERR;
3812 goto done;
3813 }
3814
3815 if (get_hook(bh, validsnapbuf, sizeof (validsnapbuf),
3816 brand_get_validatesnap, target_zone, zonepath) != Z_OK) {
3817 zerror("invalid brand configuration: missing validatesnap "
3818 "resource");
3819 brand_close(bh);
3820 err = Z_ERR;
3821 goto done;
3822 }
3823 brand_close(bh);
3824
3825 /* Append all options to clone hook. */
3826 if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK) {
3827 err = Z_ERR;
3828 goto done;
3829 }
3830
3831 /* Append all options to postclone hook. */
3832 if (addoptions(postcmdbuf, argv, sizeof (postcmdbuf)) != Z_OK) {
3833 err = Z_ERR;
3834 goto done;
3835 }
3836
3837 if (!brand_help) {
3838 if ((err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE))
3839 != Z_OK) {
3840 errno = err;
3841 zperror2(target_zone, gettext("could not set state"));
3842 goto done;
3843 }
3844 }
3845
3846 /*
3847 * The clone hook is optional. If it exists, use the hook for
3848 * cloning, otherwise use the built-in clone support
3849 */
3850 if (cmdbuf[0] != '\0') {
3851 /* Run the clone hook */
3852 status = do_subproc(cmdbuf);
3853 if ((status = subproc_status(gettext("brand-specific clone"),
3854 status, B_FALSE)) != ZONE_SUBPROC_OK) {
3855 if (status == ZONE_SUBPROC_USAGE && !brand_help)
3856 sub_usage(SHELP_CLONE, CMD_CLONE);
3857 err = Z_ERR;
3858 goto done;
3859 }
3860
3861 if (brand_help)
3862 return (Z_OK);
3863
3864 } else {
3865 /* If just help, we're done since there is no brand help. */
3866 if (brand_help)
3867 return (Z_OK);
3868
3869 /* Run the built-in clone support. */
3870
3871 /* The only explicit built-in method is "copy". */
3872 if (method != NULL && strcmp(method, "copy") != 0) {
3873 sub_usage(SHELP_CLONE, CMD_CLONE);
3874 err = Z_USAGE;
3875 goto done;
3876 }
3877
3878 if (snapshot != NULL) {
3879 err = clone_snapshot_zfs(snapshot, zonepath,
3880 validsnapbuf);
3881 } else {
3882 /*
3883 * We always copy the clone unless the source is ZFS
3884 * and a ZFS clone worked. We fallback to copying if
3885 * the ZFS clone fails for some reason.
3886 */
3887 err = Z_ERR;
3888 if (method == NULL && is_zonepath_zfs(source_zonepath))
3889 err = clone_zfs(source_zonepath, zonepath,
3890 presnapbuf, postsnapbuf);
3891
3892 if (err != Z_OK)
3893 err = clone_copy(source_zonepath, zonepath);
3894 }
3895 }
3896
3897 if (err == Z_OK && postcmdbuf[0] != '\0') {
3898 status = do_subproc(postcmdbuf);
3899 if ((err = subproc_status("postclone", status, B_FALSE))
3900 != ZONE_SUBPROC_OK) {
3901 zerror(gettext("post-clone configuration failed."));
3902 err = Z_ERR;
3903 }
3904 }
3905
3906 done:
3907 /*
3908 * If everything went well, we mark the zone as installed.
3909 */
3910 if (err == Z_OK) {
3911 err = zone_set_state(target_zone, ZONE_STATE_INSTALLED);
3912 if (err != Z_OK) {
3913 errno = err;
3914 zperror2(target_zone, gettext("could not set state"));
3915 }
3916 }
3917 if (!brand_help)
3918 zonecfg_release_lock_file(target_zone, lockfd);
3919 return ((err == Z_OK) ? Z_OK : Z_ERR);
3920 }
3921
3922 /*
3923 * Used when removing a zonepath after uninstalling or cleaning up after
3924 * the move subcommand. This handles a zonepath that has non-standard
3925 * contents so that we will only cleanup the stuff we know about and leave
3926 * any user data alone.
3927 *
3928 * If the "all" parameter is true then we should remove the whole zonepath
3929 * even if it has non-standard files/directories in it. This can be used when
3930 * we need to cleanup after moving the zonepath across file systems.
3931 *
3932 * We "exec" the RMCOMMAND so that the returned status is that of RMCOMMAND
3933 * and not the shell.
3934 */
3935 static int
3936 cleanup_zonepath(char *zonepath, boolean_t all)
3937 {
3938 int status;
3939 int i;
3940 boolean_t non_std = B_FALSE;
3941 struct dirent *dp;
3942 DIR *dirp;
3943 /*
3944 * The SUNWattached.xml file is expected since it might
3945 * exist if the zone was force-attached after a
3946 * migration.
3947 */
3948 char *std_entries[] = {"dev", "lastexited", "logs", "lu",
3949 "root", "SUNWattached.xml", NULL};
3950 /* (MAXPATHLEN * 5) is for the 5 std_entries dirs */
3951 char cmdbuf[sizeof (RMCOMMAND) + (MAXPATHLEN * 5) + 64];
3952
3953 /*
3954 * We shouldn't need these checks but lets be paranoid since we
3955 * could blow away the whole system here if we got the wrong zonepath.
3956 */
3957 if (*zonepath == NULL || strcmp(zonepath, "/") == 0) {
3958 (void) fprintf(stderr, "invalid zonepath '%s'\n", zonepath);
3959 return (Z_INVAL);
3960 }
3961
3962 /*
3963 * If the dirpath is already gone (maybe it was manually removed) then
3964 * we just return Z_OK so that the cleanup is successful.
3965 */
3966 if ((dirp = opendir(zonepath)) == NULL)
3967 return (Z_OK);
3968
3969 /*
3970 * Look through the zonepath directory to see if there are any
3971 * non-standard files/dirs. Also skip .zfs since that might be
3972 * there but we'll handle ZFS file systems as a special case.
3973 */
3974 while ((dp = readdir(dirp)) != NULL) {
3975 if (strcmp(dp->d_name, ".") == 0 ||
3976 strcmp(dp->d_name, "..") == 0 ||
3977 strcmp(dp->d_name, ".zfs") == 0)
3978 continue;
3979
3980 for (i = 0; std_entries[i] != NULL; i++)
3981 if (strcmp(dp->d_name, std_entries[i]) == 0)
3982 break;
3983
3984 if (std_entries[i] == NULL)
3985 non_std = B_TRUE;
3986 }
3987 (void) closedir(dirp);
3988
3989 if (!all && non_std) {
3990 /*
3991 * There are extra, non-standard directories/files in the
3992 * zonepath so we don't want to remove the zonepath. We
3993 * just want to remove the standard directories and leave
3994 * the user data alone.
3995 */
3996 (void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND);
3997
3998 for (i = 0; std_entries[i] != NULL; i++) {
3999 char tmpbuf[MAXPATHLEN];
4000
4001 if (snprintf(tmpbuf, sizeof (tmpbuf), " %s/%s",
4002 zonepath, std_entries[i]) >= sizeof (tmpbuf) ||
4003 strlcat(cmdbuf, tmpbuf, sizeof (cmdbuf)) >=
4004 sizeof (cmdbuf)) {
4005 (void) fprintf(stderr,
4006 gettext("path is too long\n"));
4007 return (Z_INVAL);
4008 }
4009 }
4010
4011 status = do_subproc(cmdbuf);
4012
4013 (void) fprintf(stderr, gettext("WARNING: Unable to completely "
4014 "remove %s\nbecause it contains additional user data. "
4015 "Only the standard directory\nentries have been "
4016 "removed.\n"),
4017 zonepath);
4018
4019 return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
4020 ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
4021 }
4022
4023 /*
4024 * There is nothing unexpected in the zonepath, try to get rid of the
4025 * whole zonepath directory.
4026 *
4027 * If the zonepath is its own zfs file system, try to destroy the
4028 * file system. If that fails for some reason (e.g. it has clones)
4029 * then we'll just remove the contents of the zonepath.
4030 */
4031 if (is_zonepath_zfs(zonepath)) {
4032 if (destroy_zfs(zonepath) == Z_OK)
4033 return (Z_OK);
4034 (void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND
4035 " %s/*", zonepath);
4036 status = do_subproc(cmdbuf);
4037 return ((subproc_status(RMCOMMAND, status, B_TRUE) ==
4038 ZONE_SUBPROC_OK) ? Z_OK : Z_ERR);
4039 }
4040
4041 (void) snprintf(cmdbuf, sizeof (cmdbuf), "exec " RMCOMMAND " %s",
4042 zonepath);
4043 status = do_subproc(cmdbuf);
4044
4045 return ((subproc_status(RMCOMMAND, status, B_TRUE) == ZONE_SUBPROC_OK)
4046 ? Z_OK : Z_ERR);
4047 }
4048
4049 static int
4050 move_func(int argc, char *argv[])
4051 {
4052 char *new_zonepath = NULL;
4053 int lockfd;
4054 int err, arg;
4055 char zonepath[MAXPATHLEN];
4056 zone_dochandle_t handle;
4057 boolean_t fast;
4058 boolean_t is_zfs = B_FALSE;
4059 boolean_t root_fs_mounted = B_FALSE;
4060 struct dirent *dp;
4061 DIR *dirp;
4062 boolean_t empty = B_TRUE;
4063 boolean_t revert;
4064 struct stat zonepath_buf;
4065 struct stat new_zonepath_buf;
4066 zone_mounts_t mounts;
4067
4068 if (zonecfg_in_alt_root()) {
4069 zerror(gettext("cannot move zone in alternate root"));
4070 return (Z_ERR);
4071 }
4072
4073 optind = 0;
4074 if ((arg = getopt(argc, argv, "?")) != EOF) {
4075 switch (arg) {
4076 case '?':
4077 sub_usage(SHELP_MOVE, CMD_MOVE);
4078 return (optopt == '?' ? Z_OK : Z_USAGE);
4079 default:
4080 sub_usage(SHELP_MOVE, CMD_MOVE);
4081 return (Z_USAGE);
4082 }
4083 }
4084 if (argc != (optind + 1)) {
4085 sub_usage(SHELP_MOVE, CMD_MOVE);
4086 return (Z_USAGE);
4087 }
4088 new_zonepath = argv[optind];
4089 if (sanity_check(target_zone, CMD_MOVE, B_FALSE, B_TRUE, B_FALSE)
4090 != Z_OK)
4091 return (Z_ERR);
4092 if (verify_details(CMD_MOVE, argv) != Z_OK)
4093 return (Z_ERR);
4094
4095 /*
4096 * Check out the new zonepath. This has the side effect of creating
4097 * a directory for the new zonepath. We depend on this later when we
4098 * stat to see if we are doing a cross file system move or not.
4099 */
4100 if (validate_zonepath(new_zonepath, CMD_MOVE) != Z_OK)
4101 return (Z_ERR);
4102
4103 if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4104 != Z_OK) {
4105 errno = err;
4106 zperror2(target_zone, gettext("could not get zone path"));
4107 return (Z_ERR);
4108 }
4109
4110 if (stat(zonepath, &zonepath_buf) == -1) {
4111 zperror(gettext("could not stat zone path"), B_FALSE);
4112 return (Z_ERR);
4113 }
4114
4115 if (stat(new_zonepath, &new_zonepath_buf) == -1) {
4116 zperror(gettext("could not stat new zone path"), B_FALSE);
4117 return (Z_ERR);
4118 }
4119
4120 /*
4121 * Check if the destination directory is empty.
4122 */
4123 if ((dirp = opendir(new_zonepath)) == NULL) {
4124 zperror(gettext("could not open new zone path"), B_FALSE);
4125 return (Z_ERR);
4126 }
4127 while ((dp = readdir(dirp)) != (struct dirent *)0) {
4128 if (strcmp(dp->d_name, ".") == 0 ||
4129 strcmp(dp->d_name, "..") == 0)
4130 continue;
4131 empty = B_FALSE;
4132 break;
4133 }
4134 (void) closedir(dirp);
4135
4136 /* Error if there is anything in the destination directory. */
4137 if (!empty) {
4138 (void) fprintf(stderr, gettext("could not move zone to %s: "
4139 "directory not empty\n"), new_zonepath);
4140 return (Z_ERR);
4141 }
4142
4143 /*
4144 * Collect information about mounts within the zone's zonepath.
4145 * Overlay mounts on the zone's root directory are erroneous.
4146 * Bail if we encounter any unexpected mounts.
4147 */
4148 if (zone_mounts_init(&mounts, zonepath) != 0)
4149 return (Z_ERR);
4150 if (mounts.num_root_overlay_mounts != 0) {
4151 zerror(gettext("%d overlay mount(s) detected on %s/root."),
4152 mounts.num_root_overlay_mounts, zonepath);
4153 goto err_and_mounts_destroy;
4154 }
4155 if (mounts.num_unexpected_mounts != 0)
4156 goto err_and_mounts_destroy;
4157
4158 /*
4159 * Check if we are moving in the same file system and can do a fast
4160 * move or if we are crossing file systems and have to copy the data.
4161 */
4162 fast = (zonepath_buf.st_dev == new_zonepath_buf.st_dev);
4163
4164 if ((handle = zonecfg_init_handle()) == NULL) {
4165 zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4166 goto err_and_mounts_destroy;
4167 }
4168
4169 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4170 errno = err;
4171 zperror(cmd_to_str(CMD_MOVE), B_TRUE);
4172 goto err_and_fini_handle;
4173 }
4174
4175 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4176 zerror(gettext("another %s may have an operation in progress."),
4177 "zoneadm");
4178 goto err_and_fini_handle;
4179 }
4180
4181 /*
4182 * Unmount the zone's root filesystem before we move the zone's
4183 * zonepath.
4184 */
4185 if (zone_unmount_rootfs(&mounts, zonepath, B_FALSE) != 0)
4186 goto err_and_rele_lockfile;
4187
4188 /*
4189 * We're making some file system changes now so we have to clean up
4190 * the file system before we are done. This will either clean up the
4191 * new zonepath if the zonecfg update failed or it will clean up the
4192 * old zonepath if everything is ok.
4193 */
4194 revert = B_TRUE;
4195
4196 if (is_zonepath_zfs(zonepath) &&
4197 move_zfs(zonepath, new_zonepath) != Z_ERR) {
4198 is_zfs = B_TRUE;
4199
4200 } else if (fast) {
4201 /* same file system, use rename for a quick move */
4202
4203 /*
4204 * Remove the new_zonepath directory that got created above
4205 * during the validation. It gets in the way of the rename.
4206 */
4207 if (rmdir(new_zonepath) != 0) {
4208 zperror(gettext("could not rmdir new zone path"),
4209 B_FALSE);
4210 (void) zone_mount_rootfs(&mounts, zonepath);
4211 goto err_and_rele_lockfile;
4212 }
4213
4214 if (rename(zonepath, new_zonepath) != 0) {
4215 /*
4216 * If this fails we don't need to do all of the
4217 * cleanup that happens for the rest of the code
4218 * so just return from this error.
4219 */
4220 zperror(gettext("could not move zone"), B_FALSE);
4221 (void) zone_mount_rootfs(&mounts, zonepath);
4222 goto err_and_rele_lockfile;
4223 }
4224
4225 } else {
4226 /*
4227 * Attempt to create a ZFS fs for the new zonepath. As usual,
4228 * we don't care if this works or not since we always have the
4229 * default behavior of a simple directory for the zonepath.
4230 */
4231 create_zfs_zonepath(new_zonepath);
4232
4233 (void) printf(gettext(
4234 "Moving across file systems; copying zonepath %s..."),
4235 zonepath);
4236 (void) fflush(stdout);
4237
4238 err = copy_zone(zonepath, new_zonepath);
4239
4240 (void) printf("\n");
4241 if (err != Z_OK)
4242 goto done;
4243 }
4244
4245 /*
4246 * Mount the zone's root filesystem in the new zonepath if there was
4247 * a root mount prior to the move.
4248 */
4249 if (zone_mount_rootfs(&mounts, new_zonepath) != 0) {
4250 err = Z_ERR;
4251 goto done;
4252 }
4253 root_fs_mounted = B_TRUE;
4254
4255 if ((err = zonecfg_set_zonepath(handle, new_zonepath)) != Z_OK) {
4256 errno = err;
4257 zperror(gettext("could not set new zonepath"), B_TRUE);
4258 goto done;
4259 }
4260
4261 if ((err = zonecfg_save(handle)) != Z_OK) {
4262 errno = err;
4263 zperror(gettext("zonecfg save failed"), B_TRUE);
4264 goto done;
4265 }
4266
4267 revert = B_FALSE;
4268
4269 done:
4270 zonecfg_fini_handle(handle);
4271 zonecfg_release_lock_file(target_zone, lockfd);
4272
4273 /*
4274 * Clean up the file system based on how things went. We either
4275 * clean up the new zonepath if the operation failed for some reason
4276 * or we clean up the old zonepath if everything is ok.
4277 */
4278 if (revert) {
4279 /*
4280 * Check for the unlikely scenario in which the zone's
4281 * zonepath and its root file system moved but libzonecfg
4282 * couldn't save the new zonepath to the zone's configuration
4283 * file. The mounted root filesystem must be unmounted before
4284 * zoneadm restores the zone's zonepath.
4285 */
4286 if (root_fs_mounted && zone_unmount_rootfs(&mounts,
4287 new_zonepath, B_TRUE) != 0) {
4288 /*
4289 * We can't forcibly unmount the zone's root file system
4290 * from the new zonepath. Bail!
4291 */
4292 zerror(gettext("fatal error: cannot unmount %s/root\n"),
4293 new_zonepath);
4294 goto err_and_mounts_destroy;
4295 }
4296
4297 /* The zonecfg update failed, cleanup the new zonepath. */
4298 if (is_zfs) {
4299 if (move_zfs(new_zonepath, zonepath) == Z_ERR) {
4300 (void) fprintf(stderr, gettext("could not "
4301 "restore zonepath, the zfs mountpoint is "
4302 "set as:\n%s\n"), new_zonepath);
4303 /*
4304 * err is already != Z_OK since we're reverting
4305 */
4306 } else {
4307 (void) zone_mount_rootfs(&mounts, zonepath);
4308 }
4309 } else if (fast) {
4310 if (rename(new_zonepath, zonepath) != 0) {
4311 zperror(gettext("could not restore zonepath"),
4312 B_FALSE);
4313 /*
4314 * err is already != Z_OK since we're reverting
4315 */
4316 } else {
4317 (void) zone_mount_rootfs(&mounts, zonepath);
4318 }
4319 } else {
4320 (void) printf(gettext("Cleaning up zonepath %s..."),
4321 new_zonepath);
4322 (void) fflush(stdout);
4323 err = cleanup_zonepath(new_zonepath, B_TRUE);
4324 (void) printf("\n");
4325
4326 if (err != Z_OK) {
4327 errno = err;
4328 zperror(gettext("could not remove new "
4329 "zonepath"), B_TRUE);
4330 } else {
4331 /*
4332 * Because we're reverting we know the mainline
4333 * code failed but we just reused the err
4334 * variable so we reset it back to Z_ERR.
4335 */
4336 err = Z_ERR;
4337 }
4338
4339 (void) zone_mount_rootfs(&mounts, zonepath);
4340 }
4341 } else {
4342 /* The move was successful, cleanup the old zonepath. */
4343 if (!is_zfs && !fast) {
4344 (void) printf(
4345 gettext("Cleaning up zonepath %s..."), zonepath);
4346 (void) fflush(stdout);
4347 err = cleanup_zonepath(zonepath, B_TRUE);
4348 (void) printf("\n");
4349
4350 if (err != Z_OK) {
4351 errno = err;
4352 zperror(gettext("could not remove zonepath"),
4353 B_TRUE);
4354 }
4355 }
4356 }
4357
4358 zone_mounts_destroy(&mounts);
4359 return ((err == Z_OK) ? Z_OK : Z_ERR);
4360
4361 err_and_rele_lockfile:
4362 zonecfg_release_lock_file(target_zone, lockfd);
4363 err_and_fini_handle:
4364 zonecfg_fini_handle(handle);
4365 err_and_mounts_destroy:
4366 zone_mounts_destroy(&mounts);
4367 return (Z_ERR);
4368 }
4369
4370 /* ARGSUSED */
4371 static int
4372 detach_func(int argc, char *argv[])
4373 {
4374 int lockfd = -1;
4375 int err, arg;
4376 char zonepath[MAXPATHLEN];
4377 char cmdbuf[MAXPATHLEN];
4378 char precmdbuf[MAXPATHLEN];
4379 boolean_t execute = B_TRUE;
4380 boolean_t brand_help = B_FALSE;
4381 brand_handle_t bh = NULL;
4382 int status;
4383
4384 if (zonecfg_in_alt_root()) {
4385 zerror(gettext("cannot detach zone in alternate root"));
4386 return (Z_ERR);
4387 }
4388
4389 /* Check the argv string for args we handle internally */
4390 optind = 0;
4391 opterr = 0;
4392 while ((arg = getopt(argc, argv, "?n")) != EOF) {
4393 switch (arg) {
4394 case '?':
4395 if (optopt == '?') {
4396 sub_usage(SHELP_DETACH, CMD_DETACH);
4397 brand_help = B_TRUE;
4398 }
4399 /* Ignore unknown options - may be brand specific. */
4400 break;
4401 case 'n':
4402 execute = B_FALSE;
4403 break;
4404 default:
4405 /* Ignore unknown options - may be brand specific. */
4406 break;
4407 }
4408 }
4409
4410 if (brand_help)
4411 execute = B_FALSE;
4412
4413 if (execute) {
4414 if (sanity_check(target_zone, CMD_DETACH, B_FALSE, B_TRUE,
4415 B_FALSE) != Z_OK)
4416 return (Z_ERR);
4417 if (verify_details(CMD_DETACH, argv) != Z_OK)
4418 return (Z_ERR);
4419 } else {
4420 /*
4421 * We want a dry-run to work for a non-privileged user so we
4422 * only do minimal validation.
4423 */
4424 if (target_zone == NULL) {
4425 zerror(gettext("no zone specified"));
4426 return (Z_ERR);
4427 }
4428
4429 if (strcmp(target_zone, GLOBAL_ZONENAME) == 0) {
4430 zerror(gettext("%s operation is invalid for the "
4431 "global zone."), cmd_to_str(CMD_DETACH));
4432 return (Z_ERR);
4433 }
4434 }
4435
4436 if ((err = zone_get_zonepath(target_zone, zonepath, sizeof (zonepath)))
4437 != Z_OK) {
4438 errno = err;
4439 zperror2(target_zone, gettext("could not get zone path"));
4440 return (Z_ERR);
4441 }
4442
4443 /* Fetch the detach and predetach hooks from the brand configuration. */
4444 if ((bh = brand_open(target_brand)) == NULL) {
4445 zerror(gettext("missing or invalid brand"));
4446 return (Z_ERR);
4447 }
4448
4449 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_detach, target_zone,
4450 zonepath) != Z_OK) {
4451 zerror("invalid brand configuration: missing detach resource");
4452 brand_close(bh);
4453 return (Z_ERR);
4454 }
4455
4456 if (get_hook(bh, precmdbuf, sizeof (precmdbuf), brand_get_predetach,
4457 target_zone, zonepath) != Z_OK) {
4458 zerror("invalid brand configuration: missing predetach "
4459 "resource");
4460 brand_close(bh);
4461 return (Z_ERR);
4462 }
4463 brand_close(bh);
4464
4465 /* Append all options to predetach hook. */
4466 if (addoptions(precmdbuf, argv, sizeof (precmdbuf)) != Z_OK)
4467 return (Z_ERR);
4468
4469 /* Append all options to detach hook. */
4470 if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK)
4471 return (Z_ERR);
4472
4473 if (execute && zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4474 zerror(gettext("another %s may have an operation in progress."),
4475 "zoneadm");
4476 return (Z_ERR);
4477 }
4478
4479 /* If we have a brand predetach hook, run it. */
4480 if (!brand_help && precmdbuf[0] != '\0') {
4481 status = do_subproc(precmdbuf);
4482 if (subproc_status(gettext("brand-specific predetach"),
4483 status, B_FALSE) != ZONE_SUBPROC_OK) {
4484
4485 if (execute) {
4486 assert(lockfd >= 0);
4487 zonecfg_release_lock_file(target_zone, lockfd);
4488 lockfd = -1;
4489 }
4490
4491 assert(lockfd == -1);
4492 return (Z_ERR);
4493 }
4494 }
4495
4496 if (cmdbuf[0] != '\0') {
4497 /* Run the detach hook */
4498 status = do_subproc(cmdbuf);
4499 if ((status = subproc_status(gettext("brand-specific detach"),
4500 status, B_FALSE)) != ZONE_SUBPROC_OK) {
4501 if (status == ZONE_SUBPROC_USAGE && !brand_help)
4502 sub_usage(SHELP_DETACH, CMD_DETACH);
4503
4504 if (execute) {
4505 assert(lockfd >= 0);
4506 zonecfg_release_lock_file(target_zone, lockfd);
4507 lockfd = -1;
4508 }
4509
4510 assert(lockfd == -1);
4511 return (Z_ERR);
4512 }
4513
4514 } else {
4515 zone_dochandle_t handle;
4516
4517 /* If just help, we're done since there is no brand help. */
4518 if (brand_help) {
4519 assert(lockfd == -1);
4520 return (Z_OK);
4521 }
4522
4523 /*
4524 * Run the built-in detach support. Just generate a simple
4525 * zone definition XML file and detach.
4526 */
4527
4528 /* Don't detach the zone if anything is still mounted there */
4529 if (execute && zonecfg_find_mounts(zonepath, NULL, NULL)) {
4530 (void) fprintf(stderr, gettext("These file systems are "
4531 "mounted on subdirectories of %s.\n"), zonepath);
4532 (void) zonecfg_find_mounts(zonepath, zfm_print, NULL);
4533 err = ZONE_SUBPROC_NOTCOMPLETE;
4534 goto done;
4535 }
4536
4537 if ((handle = zonecfg_init_handle()) == NULL) {
4538 zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4539 err = ZONE_SUBPROC_NOTCOMPLETE;
4540 goto done;
4541 }
4542
4543 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4544 errno = err;
4545 zperror(cmd_to_str(CMD_DETACH), B_TRUE);
4546
4547 } else if ((err = zonecfg_detach_save(handle,
4548 (execute ? 0 : ZONE_DRY_RUN))) != Z_OK) {
4549 errno = err;
4550 zperror(gettext("saving the detach manifest failed"),
4551 B_TRUE);
4552 }
4553
4554 zonecfg_fini_handle(handle);
4555 if (err != Z_OK)
4556 goto done;
4557 }
4558
4559 /*
4560 * Set the zone state back to configured unless we are running with the
4561 * no-execute option.
4562 */
4563 if (execute && (err = zone_set_state(target_zone,
4564 ZONE_STATE_CONFIGURED)) != Z_OK) {
4565 errno = err;
4566 zperror(gettext("could not reset state"), B_TRUE);
4567 }
4568
4569 done:
4570 if (execute) {
4571 assert(lockfd >= 0);
4572 zonecfg_release_lock_file(target_zone, lockfd);
4573 lockfd = -1;
4574 }
4575
4576 assert(lockfd == -1);
4577 return ((err == Z_OK) ? Z_OK : Z_ERR);
4578 }
4579
4580 /*
4581 * Determine the brand when doing a dry-run attach. The zone does not have to
4582 * exist, so we have to read the incoming manifest to determine the zone's
4583 * brand.
4584 *
4585 * Because the manifest has to be processed twice; once to determine the brand
4586 * and once to do the brand-specific attach logic, we always read it into a tmp
4587 * file. This handles the manifest coming from stdin or a regular file. The
4588 * tmpname parameter returns the name of the temporary file that the manifest
4589 * was read into.
4590 */
4591 static int
4592 dryrun_get_brand(char *manifest_path, char *tmpname, int size)
4593 {
4594 int fd;
4595 int err;
4596 int res = Z_OK;
4597 zone_dochandle_t local_handle;
4598 zone_dochandle_t rem_handle = NULL;
4599 int len;
4600 int ofd;
4601 char buf[512];
4602
4603 if (strcmp(manifest_path, "-") == 0) {
4604 fd = STDIN_FILENO;
4605 } else {
4606 if ((fd = open(manifest_path, O_RDONLY)) < 0) {
4607 if (getcwd(buf, sizeof (buf)) == NULL)
4608 (void) strlcpy(buf, "/", sizeof (buf));
4609 zerror(gettext("could not open manifest path %s%s: %s"),
4610 (*manifest_path == '/' ? "" : buf), manifest_path,
4611 strerror(errno));
4612 return (Z_ERR);
4613 }
4614 }
4615
4616 (void) snprintf(tmpname, size, "/var/run/zone.%d", getpid());
4617
4618 if ((ofd = open(tmpname, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) < 0) {
4619 zperror(gettext("could not save manifest"), B_FALSE);
4620 (void) close(fd);
4621 return (Z_ERR);
4622 }
4623
4624 while ((len = read(fd, buf, sizeof (buf))) > 0) {
4625 if (write(ofd, buf, len) == -1) {
4626 zperror(gettext("could not save manifest"), B_FALSE);
4627 (void) close(ofd);
4628 (void) close(fd);
4629 return (Z_ERR);
4630 }
4631 }
4632
4633 if (close(ofd) != 0) {
4634 zperror(gettext("could not save manifest"), B_FALSE);
4635 (void) close(fd);
4636 return (Z_ERR);
4637 }
4638
4639 (void) close(fd);
4640
4641 if ((fd = open(tmpname, O_RDONLY)) < 0) {
4642 zperror(gettext("could not open manifest path"), B_FALSE);
4643 return (Z_ERR);
4644 }
4645
4646 if ((local_handle = zonecfg_init_handle()) == NULL) {
4647 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4648 res = Z_ERR;
4649 goto done;
4650 }
4651
4652 if ((rem_handle = zonecfg_init_handle()) == NULL) {
4653 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4654 res = Z_ERR;
4655 goto done;
4656 }
4657
4658 if ((err = zonecfg_attach_manifest(fd, local_handle, rem_handle))
4659 != Z_OK) {
4660 res = Z_ERR;
4661
4662 if (err == Z_INVALID_DOCUMENT) {
4663 struct stat st;
4664 char buf[6];
4665
4666 if (strcmp(manifest_path, "-") == 0) {
4667 zerror(gettext("Input is not a valid XML "
4668 "file"));
4669 goto done;
4670 }
4671
4672 if (fstat(fd, &st) == -1 || !S_ISREG(st.st_mode)) {
4673 zerror(gettext("%s is not an XML file"),
4674 manifest_path);
4675 goto done;
4676 }
4677
4678 bzero(buf, sizeof (buf));
4679 (void) lseek(fd, 0L, SEEK_SET);
4680 if (read(fd, buf, sizeof (buf) - 1) < 0 ||
4681 strncmp(buf, "<?xml", 5) != 0)
4682 zerror(gettext("%s is not an XML file"),
4683 manifest_path);
4684 else
4685 zerror(gettext("Cannot attach to an earlier "
4686 "release of the operating system"));
4687 } else {
4688 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4689 }
4690 goto done;
4691 }
4692
4693 /* Retrieve remote handle brand type. */
4694 if (zonecfg_get_brand(rem_handle, target_brand, sizeof (target_brand))
4695 != Z_OK) {
4696 zerror(gettext("missing or invalid brand"));
4697 exit(Z_ERR);
4698 }
4699
4700 done:
4701 zonecfg_fini_handle(local_handle);
4702 zonecfg_fini_handle(rem_handle);
4703 (void) close(fd);
4704
4705 return ((res == Z_OK) ? Z_OK : Z_ERR);
4706 }
4707
4708 /* ARGSUSED */
4709 static int
4710 attach_func(int argc, char *argv[])
4711 {
4712 int lockfd = -1;
4713 int err, arg;
4714 boolean_t force = B_FALSE;
4715 zone_dochandle_t handle;
4716 char zonepath[MAXPATHLEN];
4717 char cmdbuf[MAXPATHLEN];
4718 char postcmdbuf[MAXPATHLEN];
4719 boolean_t execute = B_TRUE;
4720 boolean_t brand_help = B_FALSE;
4721 char *manifest_path;
4722 char tmpmanifest[80];
4723 int manifest_pos;
4724 brand_handle_t bh = NULL;
4725 int status;
4726 int last_index = 0;
4727 int offset;
4728 char *up;
4729 boolean_t forced_update = B_FALSE;
4730
4731 if (zonecfg_in_alt_root()) {
4732 zerror(gettext("cannot attach zone in alternate root"));
4733 return (Z_ERR);
4734 }
4735
4736 /* Check the argv string for args we handle internally */
4737 optind = 0;
4738 opterr = 0;
4739 while ((arg = getopt(argc, argv, "?Fn:U")) != EOF) {
4740 switch (arg) {
4741 case '?':
4742 if (optopt == '?') {
4743 sub_usage(SHELP_ATTACH, CMD_ATTACH);
4744 brand_help = B_TRUE;
4745 }
4746 /* Ignore unknown options - may be brand specific. */
4747 break;
4748 case 'F':
4749 force = B_TRUE;
4750 break;
4751 case 'n':
4752 execute = B_FALSE;
4753 manifest_path = optarg;
4754 manifest_pos = optind - 1;
4755 break;
4756 case 'U':
4757 /*
4758 * Undocumented 'force update' option for p2v update on
4759 * attach when zone is in the incomplete state. Change
4760 * the option back to 'u' and set forced_update flag.
4761 */
4762 if (optind == last_index)
4763 offset = optind;
4764 else
4765 offset = optind - 1;
4766 if ((up = index(argv[offset], 'U')) != NULL)
4767 *up = 'u';
4768 forced_update = B_TRUE;
4769 break;
4770 default:
4771 /* Ignore unknown options - may be brand specific. */
4772 break;
4773 }
4774 last_index = optind;
4775 }
4776
4777 if (brand_help) {
4778 force = B_FALSE;
4779 execute = B_TRUE;
4780 }
4781
4782 /* dry-run and force flags are mutually exclusive */
4783 if (!execute && force) {
4784 zerror(gettext("-F and -n flags are mutually exclusive"));
4785 return (Z_ERR);
4786 }
4787
4788 /*
4789 * If the no-execute option was specified, we don't do validation and
4790 * need to figure out the brand, since there is no zone required to be
4791 * configured for this option.
4792 */
4793 if (execute) {
4794 if (!brand_help) {
4795 if (sanity_check(target_zone, CMD_ATTACH, B_FALSE,
4796 B_TRUE, forced_update) != Z_OK)
4797 return (Z_ERR);
4798 if (verify_details(CMD_ATTACH, argv) != Z_OK)
4799 return (Z_ERR);
4800 }
4801
4802 if ((err = zone_get_zonepath(target_zone, zonepath,
4803 sizeof (zonepath))) != Z_OK) {
4804 errno = err;
4805 zperror2(target_zone,
4806 gettext("could not get zone path"));
4807 return (Z_ERR);
4808 }
4809 } else {
4810 if (dryrun_get_brand(manifest_path, tmpmanifest,
4811 sizeof (tmpmanifest)) != Z_OK)
4812 return (Z_ERR);
4813
4814 argv[manifest_pos] = tmpmanifest;
4815 target_zone = "-";
4816 (void) strlcpy(zonepath, "-", sizeof (zonepath));
4817
4818 /* Run the brand's verify_adm hook. */
4819 if (verify_brand(NULL, CMD_ATTACH, argv) != Z_OK)
4820 return (Z_ERR);
4821 }
4822
4823 /*
4824 * Fetch the attach and postattach hooks from the brand configuration.
4825 */
4826 if ((bh = brand_open(target_brand)) == NULL) {
4827 zerror(gettext("missing or invalid brand"));
4828 return (Z_ERR);
4829 }
4830
4831 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_attach, target_zone,
4832 zonepath) != Z_OK) {
4833 zerror("invalid brand configuration: missing attach resource");
4834 brand_close(bh);
4835 return (Z_ERR);
4836 }
4837
4838 if (get_hook(bh, postcmdbuf, sizeof (postcmdbuf), brand_get_postattach,
4839 target_zone, zonepath) != Z_OK) {
4840 zerror("invalid brand configuration: missing postattach "
4841 "resource");
4842 brand_close(bh);
4843 return (Z_ERR);
4844 }
4845 brand_close(bh);
4846
4847 /* Append all options to attach hook. */
4848 if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK)
4849 return (Z_ERR);
4850
4851 /* Append all options to postattach hook. */
4852 if (addoptions(postcmdbuf, argv, sizeof (postcmdbuf)) != Z_OK)
4853 return (Z_ERR);
4854
4855 if (execute && !brand_help) {
4856 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
4857 zerror(gettext("another %s may have an operation in "
4858 "progress."), "zoneadm");
4859 return (Z_ERR);
4860 }
4861 }
4862
4863 if (!force) {
4864 /*
4865 * Not a force-attach, so we need to actually do the work.
4866 */
4867 if (cmdbuf[0] != '\0') {
4868 /* Run the attach hook */
4869 status = do_subproc(cmdbuf);
4870 if ((status = subproc_status(gettext("brand-specific "
4871 "attach"), status, B_FALSE)) != ZONE_SUBPROC_OK) {
4872 if (status == ZONE_SUBPROC_USAGE && !brand_help)
4873 sub_usage(SHELP_ATTACH, CMD_ATTACH);
4874
4875 if (execute && !brand_help) {
4876 assert(zonecfg_lock_file_held(&lockfd));
4877 zonecfg_release_lock_file(target_zone,
4878 lockfd);
4879 lockfd = -1;
4880 }
4881
4882 assert(lockfd == -1);
4883 return (Z_ERR);
4884 }
4885 }
4886
4887 /*
4888 * Else run the built-in attach support.
4889 * This is a no-op since there is nothing to validate.
4890 */
4891
4892 /* If dry-run or help, then we're done. */
4893 if (!execute || brand_help) {
4894 if (!execute)
4895 (void) unlink(tmpmanifest);
4896 assert(lockfd == -1);
4897 return (Z_OK);
4898 }
4899 }
4900
4901 /* Now we can validate that the zonepath exists. */
4902 if (validate_zonepath(zonepath, CMD_ATTACH) != Z_OK) {
4903 (void) fprintf(stderr, gettext("could not verify zonepath %s "
4904 "because of the above errors.\n"), zonepath);
4905
4906 assert(zonecfg_lock_file_held(&lockfd));
4907 zonecfg_release_lock_file(target_zone, lockfd);
4908 return (Z_ERR);
4909 }
4910
4911 if ((handle = zonecfg_init_handle()) == NULL) {
4912 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4913 err = Z_ERR;
4914 } else if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
4915 errno = err;
4916 zperror(cmd_to_str(CMD_ATTACH), B_TRUE);
4917 zonecfg_fini_handle(handle);
4918 } else {
4919 zonecfg_rm_detached(handle, force);
4920 zonecfg_fini_handle(handle);
4921 }
4922
4923 if (err == Z_OK &&
4924 (err = zone_set_state(target_zone, ZONE_STATE_INSTALLED)) != Z_OK) {
4925 errno = err;
4926 zperror(gettext("could not reset state"), B_TRUE);
4927 }
4928
4929 assert(zonecfg_lock_file_held(&lockfd));
4930 zonecfg_release_lock_file(target_zone, lockfd);
4931 lockfd = -1;
4932
4933 /* If we have a brand postattach hook, run it. */
4934 if (err == Z_OK && !force && postcmdbuf[0] != '\0') {
4935 status = do_subproc(postcmdbuf);
4936 if (subproc_status(gettext("brand-specific postattach"),
4937 status, B_FALSE) != ZONE_SUBPROC_OK) {
4938 if ((err = zone_set_state(target_zone,
4939 ZONE_STATE_CONFIGURED)) != Z_OK) {
4940 errno = err;
4941 zperror(gettext("could not reset state"),
4942 B_TRUE);
4943 }
4944 }
4945 }
4946
4947 assert(lockfd == -1);
4948 return ((err == Z_OK) ? Z_OK : Z_ERR);
4949 }
4950
4951 /*
4952 * On input, TRUE => yes, FALSE => no.
4953 * On return, TRUE => 1, FALSE => 0, could not ask => -1.
4954 */
4955
4956 static int
4957 ask_yesno(boolean_t default_answer, const char *question)
4958 {
4959 char line[64]; /* should be large enough to answer yes or no */
4960
4961 if (!isatty(STDIN_FILENO))
4962 return (-1);
4963 for (;;) {
4964 (void) printf("%s (%s)? ", question,
4965 default_answer ? "[y]/n" : "y/[n]");
4966 if (fgets(line, sizeof (line), stdin) == NULL ||
4967 line[0] == '\n')
4968 return (default_answer ? 1 : 0);
4969 if (tolower(line[0]) == 'y')
4970 return (1);
4971 if (tolower(line[0]) == 'n')
4972 return (0);
4973 }
4974 }
4975
4976 /* ARGSUSED */
4977 static int
4978 uninstall_func(int argc, char *argv[])
4979 {
4980 char line[ZONENAME_MAX + 128]; /* Enough for "Are you sure ..." */
4981 char rootpath[MAXPATHLEN], zonepath[MAXPATHLEN];
4982 char cmdbuf[MAXPATHLEN];
4983 char precmdbuf[MAXPATHLEN];
4984 boolean_t force = B_FALSE;
4985 int lockfd, answer;
4986 int err, arg;
4987 boolean_t brand_help = B_FALSE;
4988 brand_handle_t bh = NULL;
4989 int status;
4990
4991 if (zonecfg_in_alt_root()) {
4992 zerror(gettext("cannot uninstall zone in alternate root"));
4993 return (Z_ERR);
4994 }
4995
4996 /* Check the argv string for args we handle internally */
4997 optind = 0;
4998 opterr = 0;
4999 while ((arg = getopt(argc, argv, "?F")) != EOF) {
5000 switch (arg) {
5001 case '?':
5002 if (optopt == '?') {
5003 sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5004 brand_help = B_TRUE;
5005 }
5006 /* Ignore unknown options - may be brand specific. */
5007 break;
5008 case 'F':
5009 force = B_TRUE;
5010 break;
5011 default:
5012 /* Ignore unknown options - may be brand specific. */
5013 break;
5014 }
5015 }
5016
5017 if (!brand_help) {
5018 if (sanity_check(target_zone, CMD_UNINSTALL, B_FALSE, B_TRUE,
5019 B_FALSE) != Z_OK)
5020 return (Z_ERR);
5021
5022 /*
5023 * Invoke brand-specific handler.
5024 */
5025 if (invoke_brand_handler(CMD_UNINSTALL, argv) != Z_OK)
5026 return (Z_ERR);
5027
5028 if (!force) {
5029 (void) snprintf(line, sizeof (line),
5030 gettext("Are you sure you want to %s zone %s"),
5031 cmd_to_str(CMD_UNINSTALL), target_zone);
5032 if ((answer = ask_yesno(B_FALSE, line)) == 0) {
5033 return (Z_OK);
5034 } else if (answer == -1) {
5035 zerror(gettext("Input not from terminal and -F "
5036 "not specified: %s not done."),
5037 cmd_to_str(CMD_UNINSTALL));
5038 return (Z_ERR);
5039 }
5040 }
5041 }
5042
5043 if ((err = zone_get_zonepath(target_zone, zonepath,
5044 sizeof (zonepath))) != Z_OK) {
5045 errno = err;
5046 zperror2(target_zone, gettext("could not get zone path"));
5047 return (Z_ERR);
5048 }
5049
5050 /*
5051 * Fetch the uninstall and preuninstall hooks from the brand
5052 * configuration.
5053 */
5054 if ((bh = brand_open(target_brand)) == NULL) {
5055 zerror(gettext("missing or invalid brand"));
5056 return (Z_ERR);
5057 }
5058
5059 if (get_hook(bh, cmdbuf, sizeof (cmdbuf), brand_get_uninstall,
5060 target_zone, zonepath) != Z_OK) {
5061 zerror("invalid brand configuration: missing uninstall "
5062 "resource");
5063 brand_close(bh);
5064 return (Z_ERR);
5065 }
5066
5067 if (get_hook(bh, precmdbuf, sizeof (precmdbuf), brand_get_preuninstall,
5068 target_zone, zonepath) != Z_OK) {
5069 zerror("invalid brand configuration: missing preuninstall "
5070 "resource");
5071 brand_close(bh);
5072 return (Z_ERR);
5073 }
5074 brand_close(bh);
5075
5076 /* Append all options to preuninstall hook. */
5077 if (addoptions(precmdbuf, argv, sizeof (precmdbuf)) != Z_OK)
5078 return (Z_ERR);
5079
5080 /* Append all options to uninstall hook. */
5081 if (addoptions(cmdbuf, argv, sizeof (cmdbuf)) != Z_OK)
5082 return (Z_ERR);
5083
5084 if (!brand_help) {
5085 if ((err = zone_get_rootpath(target_zone, rootpath,
5086 sizeof (rootpath))) != Z_OK) {
5087 errno = err;
5088 zperror2(target_zone, gettext("could not get root "
5089 "path"));
5090 return (Z_ERR);
5091 }
5092
5093 /*
5094 * If there seems to be a zoneadmd running for this zone, call
5095 * it to tell it that an uninstall is happening; if all goes
5096 * well it will then shut itself down.
5097 */
5098 if (zonecfg_ping_zoneadmd(target_zone) == Z_OK) {
5099 zone_cmd_arg_t zarg;
5100 zarg.cmd = Z_NOTE_UNINSTALLING;
5101 /* we don't care too much if this fails, just plow on */
5102 (void) zonecfg_call_zoneadmd(target_zone, &zarg, locale,
5103 B_TRUE);
5104 }
5105
5106 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
5107 zerror(gettext("another %s may have an operation in "
5108 "progress."), "zoneadm");
5109 return (Z_ERR);
5110 }
5111
5112 /* Don't uninstall the zone if anything is mounted there */
5113 err = zonecfg_find_mounts(rootpath, NULL, NULL);
5114 if (err) {
5115 zerror(gettext("These file systems are mounted on "
5116 "subdirectories of %s.\n"), rootpath);
5117 (void) zonecfg_find_mounts(rootpath, zfm_print, NULL);
5118 zonecfg_release_lock_file(target_zone, lockfd);
5119 return (Z_ERR);
5120 }
5121 }
5122
5123 /* If we have a brand preuninstall hook, run it. */
5124 if (!brand_help && precmdbuf[0] != '\0') {
5125 status = do_subproc(precmdbuf);
5126 if (subproc_status(gettext("brand-specific preuninstall"),
5127 status, B_FALSE) != ZONE_SUBPROC_OK) {
5128 zonecfg_release_lock_file(target_zone, lockfd);
5129 return (Z_ERR);
5130 }
5131 }
5132
5133 if (!brand_help) {
5134 err = zone_set_state(target_zone, ZONE_STATE_INCOMPLETE);
5135 if (err != Z_OK) {
5136 errno = err;
5137 zperror2(target_zone, gettext("could not set state"));
5138 goto bad;
5139 }
5140 }
5141
5142 /*
5143 * If there is a brand uninstall hook, use it, otherwise use the
5144 * built-in uninstall code.
5145 */
5146 if (cmdbuf[0] != '\0') {
5147 /* Run the uninstall hook */
5148 status = do_subproc(cmdbuf);
5149 if ((status = subproc_status(gettext("brand-specific "
5150 "uninstall"), status, B_FALSE)) != ZONE_SUBPROC_OK) {
5151 if (status == ZONE_SUBPROC_USAGE && !brand_help)
5152 sub_usage(SHELP_UNINSTALL, CMD_UNINSTALL);
5153 if (!brand_help)
5154 zonecfg_release_lock_file(target_zone, lockfd);
5155 return (Z_ERR);
5156 }
5157
5158 if (brand_help)
5159 return (Z_OK);
5160 } else {
5161 /* If just help, we're done since there is no brand help. */
5162 if (brand_help)
5163 return (Z_OK);
5164
5165 /* Run the built-in uninstall support. */
5166 if ((err = cleanup_zonepath(zonepath, B_FALSE)) != Z_OK) {
5167 errno = err;
5168 zperror2(target_zone, gettext("cleaning up zonepath "
5169 "failed"));
5170 goto bad;
5171 }
5172 }
5173
5174 err = zone_set_state(target_zone, ZONE_STATE_CONFIGURED);
5175 if (err != Z_OK) {
5176 errno = err;
5177 zperror2(target_zone, gettext("could not reset state"));
5178 }
5179 bad:
5180 zonecfg_release_lock_file(target_zone, lockfd);
5181 return (err);
5182 }
5183
5184 /* ARGSUSED */
5185 static int
5186 mount_func(int argc, char *argv[])
5187 {
5188 zone_cmd_arg_t zarg;
5189 boolean_t force = B_FALSE;
5190 int arg;
5191
5192 /*
5193 * The only supported subargument to the "mount" subcommand is
5194 * "-f", which forces us to mount a zone in the INCOMPLETE state.
5195 */
5196 optind = 0;
5197 if ((arg = getopt(argc, argv, "f")) != EOF) {
5198 switch (arg) {
5199 case 'f':
5200 force = B_TRUE;
5201 break;
5202 default:
5203 return (Z_USAGE);
5204 }
5205 }
5206 if (argc > optind)
5207 return (Z_USAGE);
5208
5209 if (sanity_check(target_zone, CMD_MOUNT, B_FALSE, B_FALSE, force)
5210 != Z_OK)
5211 return (Z_ERR);
5212 if (verify_details(CMD_MOUNT, argv) != Z_OK)
5213 return (Z_ERR);
5214
5215 zarg.cmd = force ? Z_FORCEMOUNT : Z_MOUNT;
5216 zarg.bootbuf[0] = '\0';
5217 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
5218 zerror(gettext("call to %s failed"), "zoneadmd");
5219 return (Z_ERR);
5220 }
5221 return (Z_OK);
5222 }
5223
5224 /* ARGSUSED */
5225 static int
5226 unmount_func(int argc, char *argv[])
5227 {
5228 zone_cmd_arg_t zarg;
5229
5230 if (argc > 0)
5231 return (Z_USAGE);
5232 if (sanity_check(target_zone, CMD_UNMOUNT, B_FALSE, B_FALSE, B_FALSE)
5233 != Z_OK)
5234 return (Z_ERR);
5235
5236 zarg.cmd = Z_UNMOUNT;
5237 if (zonecfg_call_zoneadmd(target_zone, &zarg, locale, B_TRUE) != 0) {
5238 zerror(gettext("call to %s failed"), "zoneadmd");
5239 return (Z_ERR);
5240 }
5241 return (Z_OK);
5242 }
5243
5244 static int
5245 mark_func(int argc, char *argv[])
5246 {
5247 int err, lockfd;
5248 int arg;
5249 boolean_t force = B_FALSE;
5250 int state;
5251
5252 optind = 0;
5253 opterr = 0;
5254 while ((arg = getopt(argc, argv, "F")) != EOF) {
5255 switch (arg) {
5256 case 'F':
5257 force = B_TRUE;
5258 break;
5259 default:
5260 return (Z_USAGE);
5261 }
5262 }
5263
5264 if (argc != (optind + 1))
5265 return (Z_USAGE);
5266
5267 if (strcmp(argv[optind], "configured") == 0)
5268 state = ZONE_STATE_CONFIGURED;
5269 else if (strcmp(argv[optind], "incomplete") == 0)
5270 state = ZONE_STATE_INCOMPLETE;
5271 else if (strcmp(argv[optind], "installed") == 0)
5272 state = ZONE_STATE_INSTALLED;
5273 else
5274 return (Z_USAGE);
5275
5276 if (state != ZONE_STATE_INCOMPLETE && !force)
5277 return (Z_USAGE);
5278
5279 if (sanity_check(target_zone, CMD_MARK, B_FALSE, B_TRUE, B_FALSE)
5280 != Z_OK)
5281 return (Z_ERR);
5282
5283 /*
5284 * Invoke brand-specific handler.
5285 */
5286 if (invoke_brand_handler(CMD_MARK, argv) != Z_OK)
5287 return (Z_ERR);
5288
5289 if (zonecfg_grab_lock_file(target_zone, &lockfd) != Z_OK) {
5290 zerror(gettext("another %s may have an operation in progress."),
5291 "zoneadm");
5292 return (Z_ERR);
5293 }
5294
5295 err = zone_set_state(target_zone, state);
5296 if (err != Z_OK) {
5297 errno = err;
5298 zperror2(target_zone, gettext("could not set state"));
5299 }
5300 zonecfg_release_lock_file(target_zone, lockfd);
5301
5302 return (err);
5303 }
5304
5305 /*
5306 * Check what scheduling class we're running under and print a warning if
5307 * we're not using FSS.
5308 */
5309 static int
5310 check_sched_fss(zone_dochandle_t handle)
5311 {
5312 char class_name[PC_CLNMSZ];
5313
5314 if (zonecfg_get_dflt_sched_class(handle, class_name,
5315 sizeof (class_name)) != Z_OK) {
5316 zerror(gettext("WARNING: unable to determine the zone's "
5317 "scheduling class"));
5318 } else if (strcmp("FSS", class_name) != 0) {
5319 zerror(gettext("WARNING: The zone.cpu-shares rctl is set but\n"
5320 "FSS is not the default scheduling class for this zone. "
5321 "FSS will be\nused for processes in the zone but to get "
5322 "the full benefit of FSS,\nit should be the default "
5323 "scheduling class. See dispadmin(1M) for\nmore details."));
5324 return (Z_SYSTEM);
5325 }
5326
5327 return (Z_OK);
5328 }
5329
5330 static int
5331 check_cpu_shares_sched(zone_dochandle_t handle)
5332 {
5333 int err;
5334 int res = Z_OK;
5335 struct zone_rctltab rctl;
5336
5337 if ((err = zonecfg_setrctlent(handle)) != Z_OK) {
5338 errno = err;
5339 zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5340 return (err);
5341 }
5342
5343 while (zonecfg_getrctlent(handle, &rctl) == Z_OK) {
5344 if (strcmp(rctl.zone_rctl_name, "zone.cpu-shares") == 0) {
5345 if (check_sched_fss(handle) != Z_OK)
5346 res = Z_SYSTEM;
5347 break;
5348 }
5349 }
5350
5351 (void) zonecfg_endrctlent(handle);
5352
5353 return (res);
5354 }
5355
5356 /*
5357 * Check if there is a mix of processes running in different pools within the
5358 * zone. This is currently only going to be called for the global zone from
5359 * apply_func but that could be generalized in the future.
5360 */
5361 static boolean_t
5362 mixed_pools(zoneid_t zoneid)
5363 {
5364 DIR *dirp;
5365 dirent_t *dent;
5366 boolean_t mixed = B_FALSE;
5367 boolean_t poolid_set = B_FALSE;
5368 poolid_t last_poolid = 0;
5369
5370 if ((dirp = opendir("/proc")) == NULL) {
5371 zerror(gettext("could not open /proc"));
5372 return (B_FALSE);
5373 }
5374
5375 while ((dent = readdir(dirp)) != NULL) {
5376 int procfd;
5377 psinfo_t ps;
5378 char procpath[MAXPATHLEN];
5379
5380 if (dent->d_name[0] == '.')
5381 continue;
5382
5383 (void) snprintf(procpath, sizeof (procpath), "/proc/%s/psinfo",
5384 dent->d_name);
5385
5386 if ((procfd = open(procpath, O_RDONLY)) == -1)
5387 continue;
5388
5389 if (read(procfd, &ps, sizeof (ps)) == sizeof (psinfo_t)) {
5390 /* skip processes in other zones and system processes */
5391 if (zoneid != ps.pr_zoneid || ps.pr_flag & SSYS) {
5392 (void) close(procfd);
5393 continue;
5394 }
5395
5396 if (poolid_set) {
5397 if (ps.pr_poolid != last_poolid)
5398 mixed = B_TRUE;
5399 } else {
5400 last_poolid = ps.pr_poolid;
5401 poolid_set = B_TRUE;
5402 }
5403 }
5404
5405 (void) close(procfd);
5406
5407 if (mixed)
5408 break;
5409 }
5410
5411 (void) closedir(dirp);
5412
5413 return (mixed);
5414 }
5415
5416 /*
5417 * Check if a persistent or temporary pool is configured for the zone.
5418 * This is currently only going to be called for the global zone from
5419 * apply_func but that could be generalized in the future.
5420 */
5421 static boolean_t
5422 pool_configured(zone_dochandle_t handle)
5423 {
5424 int err1, err2;
5425 struct zone_psettab pset_tab;
5426 char poolname[MAXPATHLEN];
5427
5428 err1 = zonecfg_lookup_pset(handle, &pset_tab);
5429 err2 = zonecfg_get_pool(handle, poolname, sizeof (poolname));
5430
5431 if (err1 == Z_NO_ENTRY &&
5432 (err2 == Z_NO_ENTRY || (err2 == Z_OK && strlen(poolname) == 0)))
5433 return (B_FALSE);
5434
5435 return (B_TRUE);
5436 }
5437
5438 /*
5439 * This is an undocumented interface which is currently only used to apply
5440 * the global zone resource management settings when the system boots.
5441 * This function does not yet properly handle updating a running system so
5442 * any projects running in the zone would be trashed if this function
5443 * were to run after the zone had booted. It also does not reset any
5444 * rctl settings that were removed from zonecfg. There is still work to be
5445 * done before we can properly support dynamically updating the resource
5446 * management settings for a running zone (global or non-global). Thus, this
5447 * functionality is undocumented for now.
5448 */
5449 /* ARGSUSED */
5450 static int
5451 apply_func(int argc, char *argv[])
5452 {
5453 int err;
5454 int res = Z_OK;
5455 priv_set_t *privset;
5456 zoneid_t zoneid;
5457 zone_dochandle_t handle;
5458 uint64_t mcap;
5459 char pool_err[128];
5460
5461 zoneid = getzoneid();
5462
5463 if (zonecfg_in_alt_root() || zoneid != GLOBAL_ZONEID ||
5464 target_zone == NULL || strcmp(target_zone, GLOBAL_ZONENAME) != 0)
5465 return (usage(B_FALSE));
5466
5467 if ((privset = priv_allocset()) == NULL) {
5468 zerror(gettext("%s failed"), "priv_allocset");
5469 return (Z_ERR);
5470 }
5471
5472 if (getppriv(PRIV_EFFECTIVE, privset) != 0) {
5473 zerror(gettext("%s failed"), "getppriv");
5474 priv_freeset(privset);
5475 return (Z_ERR);
5476 }
5477
5478 if (priv_isfullset(privset) == B_FALSE) {
5479 (void) usage(B_FALSE);
5480 priv_freeset(privset);
5481 return (Z_ERR);
5482 }
5483 priv_freeset(privset);
5484
5485 if ((handle = zonecfg_init_handle()) == NULL) {
5486 zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5487 return (Z_ERR);
5488 }
5489
5490 if ((err = zonecfg_get_handle(target_zone, handle)) != Z_OK) {
5491 errno = err;
5492 zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5493 zonecfg_fini_handle(handle);
5494 return (Z_ERR);
5495 }
5496
5497 /* specific error msgs are printed within apply_rctls */
5498 if ((err = zonecfg_apply_rctls(target_zone, handle)) != Z_OK) {
5499 errno = err;
5500 zperror(cmd_to_str(CMD_APPLY), B_TRUE);
5501 res = Z_ERR;
5502 }
5503
5504 if ((err = check_cpu_shares_sched(handle)) != Z_OK)
5505 res = Z_ERR;
5506
5507 if (pool_configured(handle)) {
5508 if (mixed_pools(zoneid)) {
5509 zerror(gettext("Zone is using multiple resource "
5510 "pools. The pool\nconfiguration cannot be "
5511 "applied without rebooting."));
5512 res = Z_ERR;
5513 } else {
5514
5515 /*
5516 * The next two blocks of code attempt to set up
5517 * temporary pools as well as persistent pools. In
5518 * both cases we call the functions unconditionally.
5519 * Within each funtion the code will check if the zone
5520 * is actually configured for a temporary pool or
5521 * persistent pool and just return if there is nothing
5522 * to do.
5523 */
5524 if ((err = zonecfg_bind_tmp_pool(handle, zoneid,
5525 pool_err, sizeof (pool_err))) != Z_OK) {
5526 if (err == Z_POOL || err == Z_POOL_CREATE ||
5527 err == Z_POOL_BIND)
5528 zerror("%s: %s", zonecfg_strerror(err),
5529 pool_err);
5530 else
5531 zerror(gettext("could not bind zone to "
5532 "temporary pool: %s"),
5533 zonecfg_strerror(err));
5534 res = Z_ERR;
5535 }
5536
5537 if ((err = zonecfg_bind_pool(handle, zoneid, pool_err,
5538 sizeof (pool_err))) != Z_OK) {
5539 if (err == Z_POOL || err == Z_POOL_BIND)
5540 zerror("%s: %s", zonecfg_strerror(err),
5541 pool_err);
5542 else
5543 zerror("%s", zonecfg_strerror(err));
5544 }
5545 }
5546 }
5547
5548 /*
5549 * If a memory cap is configured, make sure the rcapd SMF service is
5550 * enabled.
5551 */
5552 if (zonecfg_get_aliased_rctl(handle, ALIAS_MAXPHYSMEM, &mcap) == Z_OK) {
5553 char smf_err[128];
5554
5555 if (zonecfg_enable_rcapd(smf_err, sizeof (smf_err)) != Z_OK) {
5556 zerror(gettext("enabling system/rcap service failed: "
5557 "%s"), smf_err);
5558 res = Z_ERR;
5559 }
5560 }
5561
5562 zonecfg_fini_handle(handle);
5563
5564 return (res);
5565 }
5566
5567 /*
5568 * This is an undocumented interface that is invoked by the zones SMF service
5569 * for installed zones that won't automatically boot.
5570 */
5571 /* ARGSUSED */
5572 static int
5573 sysboot_func(int argc, char *argv[])
5574 {
5575 int err;
5576 zone_dochandle_t zone_handle;
5577 brand_handle_t brand_handle;
5578 char cmdbuf[MAXPATHLEN];
5579 char zonepath[MAXPATHLEN];
5580
5581 /*
5582 * This subcommand can only be executed in the global zone on non-global
5583 * zones.
5584 */
5585 if (zonecfg_in_alt_root())
5586 return (usage(B_FALSE));
5587 if (sanity_check(target_zone, CMD_SYSBOOT, B_FALSE, B_TRUE, B_FALSE) !=
5588 Z_OK)
5589 return (Z_ERR);
5590
5591 /*
5592 * Fetch the sysboot hook from the target zone's brand.
5593 */
5594 if ((zone_handle = zonecfg_init_handle()) == NULL) {
5595 zperror(cmd_to_str(CMD_SYSBOOT), B_TRUE);
5596 return (Z_ERR);
5597 }
5598 if ((err = zonecfg_get_handle(target_zone, zone_handle)) != Z_OK) {
5599 errno = err;
5600 zperror(cmd_to_str(CMD_SYSBOOT), B_TRUE);
5601 zonecfg_fini_handle(zone_handle);
5602 return (Z_ERR);
5603 }
5604 if ((err = zonecfg_get_zonepath(zone_handle, zonepath,
5605 sizeof (zonepath))) != Z_OK) {
5606 errno = err;
5607 zperror(cmd_to_str(CMD_SYSBOOT), B_TRUE);
5608 zonecfg_fini_handle(zone_handle);
5609 return (Z_ERR);
5610 }
5611 if ((brand_handle = brand_open(target_brand)) == NULL) {
5612 zerror(gettext("missing or invalid brand during %s operation: "
5613 "%s"), cmd_to_str(CMD_SYSBOOT), target_brand);
5614 zonecfg_fini_handle(zone_handle);
5615 return (Z_ERR);
5616 }
5617 err = get_hook(brand_handle, cmdbuf, sizeof (cmdbuf), brand_get_sysboot,
5618 target_zone, zonepath);
5619 brand_close(brand_handle);
5620 zonecfg_fini_handle(zone_handle);
5621 if (err != Z_OK) {
5622 zerror(gettext("unable to get brand hook from brand %s for %s "
5623 "operation"), target_brand, cmd_to_str(CMD_SYSBOOT));
5624 return (Z_ERR);
5625 }
5626
5627 /*
5628 * If the hook wasn't defined (which is OK), then indicate success and
5629 * return. Otherwise, execute the hook.
5630 */
5631 if (cmdbuf[0] != '\0')
5632 return ((subproc_status(gettext("brand sysboot operation"),
5633 do_subproc(cmdbuf), B_FALSE) == ZONE_SUBPROC_OK) ? Z_OK :
5634 Z_BRAND_ERROR);
5635 return (Z_OK);
5636 }
5637
5638 static int
5639 help_func(int argc, char *argv[])
5640 {
5641 int arg, cmd_num;
5642
5643 if (argc == 0) {
5644 (void) usage(B_TRUE);
5645 return (Z_OK);
5646 }
5647 optind = 0;
5648 if ((arg = getopt(argc, argv, "?")) != EOF) {
5649 switch (arg) {
5650 case '?':
5651 sub_usage(SHELP_HELP, CMD_HELP);
5652 return (optopt == '?' ? Z_OK : Z_USAGE);
5653 default:
5654 sub_usage(SHELP_HELP, CMD_HELP);
5655 return (Z_USAGE);
5656 }
5657 }
5658 while (optind < argc) {
5659 /* Private commands have NULL short_usage; omit them */
5660 if ((cmd_num = cmd_match(argv[optind])) < 0 ||
5661 cmdtab[cmd_num].short_usage == NULL) {
5662 sub_usage(SHELP_HELP, CMD_HELP);
5663 return (Z_USAGE);
5664 }
5665 sub_usage(cmdtab[cmd_num].short_usage, cmd_num);
5666 optind++;
5667 }
5668 return (Z_OK);
5669 }
5670
5671 /*
5672 * Returns: CMD_MIN thru CMD_MAX on success, -1 on error
5673 */
5674
5675 static int
5676 cmd_match(char *cmd)
5677 {
5678 int i;
5679
5680 for (i = CMD_MIN; i <= CMD_MAX; i++) {
5681 /* return only if there is an exact match */
5682 if (strcmp(cmd, cmdtab[i].cmd_name) == 0)
5683 return (cmdtab[i].cmd_num);
5684 }
5685 return (-1);
5686 }
5687
5688 static int
5689 parse_and_run(int argc, char *argv[])
5690 {
5691 int i = cmd_match(argv[0]);
5692
5693 if (i < 0)
5694 return (usage(B_FALSE));
5695 return (cmdtab[i].handler(argc - 1, &(argv[1])));
5696 }
5697
5698 static char *
5699 get_execbasename(char *execfullname)
5700 {
5701 char *last_slash, *execbasename;
5702
5703 /* guard against '/' at end of command invocation */
5704 for (;;) {
5705 last_slash = strrchr(execfullname, '/');
5706 if (last_slash == NULL) {
5707 execbasename = execfullname;
5708 break;
5709 } else {
5710 execbasename = last_slash + 1;
5711 if (*execbasename == '\0') {
5712 *last_slash = '\0';
5713 continue;
5714 }
5715 break;
5716 }
5717 }
5718 return (execbasename);
5719 }
5720
5721 static char *
5722 get_username()
5723 {
5724 uid_t uid;
5725 struct passwd *nptr;
5726
5727
5728 /*
5729 * Authorizations are checked to restrict access based on the
5730 * requested operation and zone name, It is assumed that the
5731 * program is running with all privileges, but that the real
5732 * user ID is that of the user or role on whose behalf we are
5733 * operating. So we start by getting the username that will be
5734 * used for subsequent authorization checks.
5735 */
5736
5737 uid = getuid();
5738 if ((nptr = getpwuid(uid)) == NULL) {
5739 zerror(gettext("could not get user name."));
5740 exit(Z_ERR);
5741 }
5742 return (nptr->pw_name);
5743 }
5744
5745 int
5746 main(int argc, char **argv)
5747 {
5748 int arg;
5749 zoneid_t zid;
5750 struct stat st;
5751 char *zone_lock_env;
5752 int err;
5753
5754 if ((locale = setlocale(LC_ALL, "")) == NULL)
5755 locale = "C";
5756 (void) textdomain(TEXT_DOMAIN);
5757 setbuf(stdout, NULL);
5758 (void) sigset(SIGHUP, SIG_IGN);
5759 execname = get_execbasename(argv[0]);
5760 username = get_username();
5761 target_zone = NULL;
5762 if (chdir("/") != 0) {
5763 zerror(gettext("could not change directory to /."));
5764 exit(Z_ERR);
5765 }
5766
5767 /*
5768 * Use the default system mask rather than anything that may have been
5769 * set by the caller.
5770 */
5771 (void) umask(CMASK);
5772
5773 if (init_zfs() != Z_OK)
5774 exit(Z_ERR);
5775
5776 while ((arg = getopt(argc, argv, "?u:z:R:")) != EOF) {
5777 switch (arg) {
5778 case '?':
5779 return (usage(B_TRUE));
5780 case 'u':
5781 target_uuid = optarg;
5782 break;
5783 case 'z':
5784 target_zone = optarg;
5785 break;
5786 case 'R': /* private option for admin/install use */
5787 if (*optarg != '/') {
5788 zerror(gettext("root path must be absolute."));
5789 exit(Z_ERR);
5790 }
5791 if (stat(optarg, &st) == -1 || !S_ISDIR(st.st_mode)) {
5792 zerror(
5793 gettext("root path must be a directory."));
5794 exit(Z_ERR);
5795 }
5796 zonecfg_set_root(optarg);
5797 break;
5798 default:
5799 return (usage(B_FALSE));
5800 }
5801 }
5802
5803 if (optind >= argc)
5804 return (usage(B_FALSE));
5805
5806 if (target_uuid != NULL && *target_uuid != '\0') {
5807 uuid_t uuid;
5808 static char newtarget[ZONENAME_MAX];
5809
5810 if (uuid_parse(target_uuid, uuid) == -1) {
5811 zerror(gettext("illegal UUID value specified"));
5812 exit(Z_ERR);
5813 }
5814 if (zonecfg_get_name_by_uuid(uuid, newtarget,
5815 sizeof (newtarget)) == Z_OK)
5816 target_zone = newtarget;
5817 }
5818
5819 if (target_zone != NULL && zone_get_id(target_zone, &zid) != 0) {
5820 errno = Z_NO_ZONE;
5821 zperror(target_zone, B_TRUE);
5822 exit(Z_ERR);
5823 }
5824
5825 /*
5826 * See if we have inherited the right to manipulate this zone from
5827 * a zoneadm instance in our ancestry. If so, set zone_lock_cnt to
5828 * indicate it. If not, make that explicit in our environment.
5829 */
5830 zonecfg_init_lock_file(target_zone, &zone_lock_env);
5831
5832 /* Figure out what the system's default brand is */
5833 if (zonecfg_default_brand(default_brand,
5834 sizeof (default_brand)) != Z_OK) {
5835 zerror(gettext("unable to determine default brand"));
5836 return (Z_ERR);
5837 }
5838
5839 /*
5840 * If we are going to be operating on a single zone, retrieve its
5841 * brand type and determine whether it is native or not.
5842 */
5843 if ((target_zone != NULL) &&
5844 (strcmp(target_zone, GLOBAL_ZONENAME) != 0)) {
5845 if (zone_get_brand(target_zone, target_brand,
5846 sizeof (target_brand)) != Z_OK) {
5847 zerror(gettext("missing or invalid brand"));
5848 exit(Z_ERR);
5849 }
5850 /*
5851 * In the alternate root environment, the only supported
5852 * operations are mount and unmount. In this case, just treat
5853 * the zone as native if it is cluster. Cluster zones can be
5854 * native for the purpose of LU or upgrade, and the cluster
5855 * brand may not exist in the miniroot (such as in net install
5856 * upgrade).
5857 */
5858 if (strcmp(target_brand, CLUSTER_BRAND_NAME) == 0) {
5859 if (zonecfg_in_alt_root()) {
5860 (void) strlcpy(target_brand, default_brand,
5861 sizeof (target_brand));
5862 }
5863 }
5864 }
5865
5866 err = parse_and_run(argc - optind, &argv[optind]);
5867
5868 return (err);
5869 }