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