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 2014 Gary Mills
  24  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
  25  * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
  26  * Copyright 2015 Joyent Inc.
  27  */
  28 
  29 #include <libsysevent.h>
  30 #include <pthread.h>
  31 #include <stdlib.h>
  32 #include <errno.h>
  33 #include <fnmatch.h>
  34 #include <strings.h>
  35 #include <unistd.h>
  36 #include <assert.h>
  37 #include <libgen.h>
  38 #include <libintl.h>
  39 #include <alloca.h>
  40 #include <ctype.h>
  41 #include <sys/acl.h>
  42 #include <sys/stat.h>
  43 #include <sys/brand.h>
  44 #include <sys/mntio.h>
  45 #include <sys/mnttab.h>
  46 #include <sys/nvpair.h>
  47 #include <sys/types.h>
  48 #include <sys/sockio.h>
  49 #include <sys/systeminfo.h>
  50 #include <ftw.h>
  51 #include <pool.h>
  52 #include <libscf.h>
  53 #include <libproc.h>
  54 #include <sys/priocntl.h>
  55 #include <libuutil.h>
  56 #include <wait.h>
  57 #include <bsm/adt.h>
  58 #include <auth_attr.h>
  59 #include <auth_list.h>
  60 #include <secdb.h>
  61 #include <user_attr.h>
  62 #include <prof_attr.h>
  63 #include <sys/debug.h>
  64 #include <os_dtd.h>
  65 
  66 #include <arpa/inet.h>
  67 #include <netdb.h>
  68 
  69 #include <libxml/xmlmemory.h>
  70 #include <libxml/parser.h>
  71 
  72 #include <libdevinfo.h>
  73 #include <uuid/uuid.h>
  74 #include <dirent.h>
  75 #include <libbrand.h>
  76 
  77 #include <libzonecfg.h>
  78 #include "zonecfg_impl.h"
  79 
  80 #define _PATH_TMPFILE   "/zonecfg.XXXXXX"
  81 #define ZONE_CB_RETRY_COUNT             10
  82 #define ZONE_EVENT_PING_SUBCLASS        "ping"
  83 #define ZONE_EVENT_PING_PUBLISHER       "solaris"
  84 
  85 /* Hard-code the DTD element/attribute/entity names just once, here. */
  86 #define DTD_ELEM_ATTR           (const xmlChar *) "attr"
  87 #define DTD_ELEM_COMMENT        (const xmlChar *) "comment"
  88 #define DTD_ELEM_DEVICE         (const xmlChar *) "device"
  89 #define DTD_ELEM_FS             (const xmlChar *) "filesystem"
  90 #define DTD_ELEM_FSOPTION       (const xmlChar *) "fsoption"
  91 #define DTD_ELEM_NET            (const xmlChar *) "network"
  92 #define DTD_ELEM_RCTL           (const xmlChar *) "rctl"
  93 #define DTD_ELEM_RCTLVALUE      (const xmlChar *) "rctl-value"
  94 #define DTD_ELEM_ZONE           (const xmlChar *) "zone"
  95 #define DTD_ELEM_DATASET        (const xmlChar *) "dataset"
  96 #define DTD_ELEM_TMPPOOL        (const xmlChar *) "tmp_pool"
  97 #define DTD_ELEM_PSET           (const xmlChar *) "pset"
  98 #define DTD_ELEM_MCAP           (const xmlChar *) "mcap"
  99 #define DTD_ELEM_PACKAGE        (const xmlChar *) "package"
 100 #define DTD_ELEM_OBSOLETES      (const xmlChar *) "obsoletes"
 101 #define DTD_ELEM_DEV_PERM       (const xmlChar *) "dev-perm"
 102 #define DTD_ELEM_ADMIN          (const xmlChar *) "admin"
 103 
 104 #define DTD_ATTR_ACTION         (const xmlChar *) "action"
 105 #define DTD_ATTR_ADDRESS        (const xmlChar *) "address"
 106 #define DTD_ATTR_ALLOWED_ADDRESS        (const xmlChar *) "allowed-address"
 107 #define DTD_ATTR_AUTOBOOT       (const xmlChar *) "autoboot"
 108 #define DTD_ATTR_IPTYPE         (const xmlChar *) "ip-type"
 109 #define DTD_ATTR_DEFROUTER      (const xmlChar *) "defrouter"
 110 #define DTD_ATTR_DIR            (const xmlChar *) "directory"
 111 #define DTD_ATTR_LIMIT          (const xmlChar *) "limit"
 112 #define DTD_ATTR_LIMITPRIV      (const xmlChar *) "limitpriv"
 113 #define DTD_ATTR_BOOTARGS       (const xmlChar *) "bootargs"
 114 #define DTD_ATTR_SCHED          (const xmlChar *) "scheduling-class"
 115 #define DTD_ATTR_MATCH          (const xmlChar *) "match"
 116 #define DTD_ATTR_NAME           (const xmlChar *) "name"
 117 #define DTD_ATTR_PHYSICAL       (const xmlChar *) "physical"
 118 #define DTD_ATTR_POOL           (const xmlChar *) "pool"
 119 #define DTD_ATTR_PRIV           (const xmlChar *) "priv"
 120 #define DTD_ATTR_RAW            (const xmlChar *) "raw"
 121 #define DTD_ATTR_SPECIAL        (const xmlChar *) "special"
 122 #define DTD_ATTR_TYPE           (const xmlChar *) "type"
 123 #define DTD_ATTR_VALUE          (const xmlChar *) "value"
 124 #define DTD_ATTR_ZONEPATH       (const xmlChar *) "zonepath"
 125 #define DTD_ATTR_NCPU_MIN       (const xmlChar *) "ncpu_min"
 126 #define DTD_ATTR_NCPU_MAX       (const xmlChar *) "ncpu_max"
 127 #define DTD_ATTR_IMPORTANCE     (const xmlChar *) "importance"
 128 #define DTD_ATTR_PHYSCAP        (const xmlChar *) "physcap"
 129 #define DTD_ATTR_VERSION        (const xmlChar *) "version"
 130 #define DTD_ATTR_ID             (const xmlChar *) "id"
 131 #define DTD_ATTR_UID            (const xmlChar *) "uid"
 132 #define DTD_ATTR_GID            (const xmlChar *) "gid"
 133 #define DTD_ATTR_MODE           (const xmlChar *) "mode"
 134 #define DTD_ATTR_ACL            (const xmlChar *) "acl"
 135 #define DTD_ATTR_BRAND          (const xmlChar *) "brand"
 136 #define DTD_ATTR_HOSTID         (const xmlChar *) "hostid"
 137 #define DTD_ATTR_USER           (const xmlChar *) "user"
 138 #define DTD_ATTR_AUTHS          (const xmlChar *) "auths"
 139 #define DTD_ATTR_FS_ALLOWED     (const xmlChar *) "fs-allowed"
 140 
 141 #define DTD_ENTITY_BOOLEAN      "boolean"
 142 #define DTD_ENTITY_DEVPATH      "devpath"
 143 #define DTD_ENTITY_DRIVER       "driver"
 144 #define DTD_ENTITY_DRVMIN       "drv_min"
 145 #define DTD_ENTITY_FALSE        "false"
 146 #define DTD_ENTITY_INT          "int"
 147 #define DTD_ENTITY_STRING       "string"
 148 #define DTD_ENTITY_TRUE         "true"
 149 #define DTD_ENTITY_UINT         "uint"
 150 
 151 #define DTD_ENTITY_BOOL_LEN     6       /* "false" */
 152 
 153 #define ATTACH_FORCED   "SUNWattached.xml"
 154 
 155 #define TMP_POOL_NAME   "SUNWtmp_%s"
 156 #define MAX_TMP_POOL_NAME       (ZONENAME_MAX + 9)
 157 #define RCAP_SERVICE    "system/rcap:default"
 158 #define POOLD_SERVICE   "system/pools/dynamic:default"
 159 
 160 /*
 161  * rctl alias definitions
 162  *
 163  * This holds the alias, the full rctl name, the default priv value, action
 164  * and lower limit.  The functions that handle rctl aliases step through
 165  * this table, matching on the alias, and using the full values for setting
 166  * the rctl entry as well the limit for validation.
 167  */
 168 static struct alias {
 169         char *shortname;
 170         char *realname;
 171         char *priv;
 172         char *action;
 173         uint64_t low_limit;
 174 } aliases[] = {
 175         {ALIAS_MAXLWPS, "zone.max-lwps", "privileged", "deny", 100},
 176         {ALIAS_MAXSHMMEM, "zone.max-shm-memory", "privileged", "deny", 0},
 177         {ALIAS_MAXSHMIDS, "zone.max-shm-ids", "privileged", "deny", 0},
 178         {ALIAS_MAXMSGIDS, "zone.max-msg-ids", "privileged", "deny", 0},
 179         {ALIAS_MAXSEMIDS, "zone.max-sem-ids", "privileged", "deny", 0},
 180         {ALIAS_MAXLOCKEDMEM, "zone.max-locked-memory", "privileged", "deny", 0},
 181         {ALIAS_MAXSWAP, "zone.max-swap", "privileged", "deny", 0},
 182         {ALIAS_MAXPHYSMEM, "zone.max-physical-memory", "privileged", "deny",
 183             1048576},
 184         {ALIAS_SHARES, "zone.cpu-shares", "privileged", "none", 0},
 185         {ALIAS_CPUCAP, "zone.cpu-cap", "privileged", "deny", 0},
 186         {ALIAS_MAXPROCS, "zone.max-processes", "privileged", "deny", 100},
 187         {NULL, NULL, NULL, NULL, 0}
 188 };
 189 
 190 /*
 191  * Structure for applying rctls to a running zone.  It allows important
 192  * process values to be passed together easily.
 193  */
 194 typedef struct pr_info_handle {
 195         struct ps_prochandle *pr;
 196         pid_t pid;
 197 } pr_info_handle_t;
 198 
 199 struct zone_dochandle {
 200         char            *zone_dh_rootdir;
 201         xmlDocPtr       zone_dh_doc;
 202         xmlNodePtr      zone_dh_cur;
 203         xmlNodePtr      zone_dh_top;
 204         boolean_t       zone_dh_newzone;
 205         boolean_t       zone_dh_snapshot;
 206         boolean_t       zone_dh_sw_inv;
 207         zone_userauths_t        *zone_dh_userauths;
 208         char            zone_dh_delete_name[ZONENAME_MAX];
 209 };
 210 
 211 struct znotify {
 212         void * zn_private;
 213         evchan_t *zn_eventchan;
 214         int (*zn_callback)(const  char *zonename, zoneid_t zid,
 215             const char *newstate, const char *oldstate, hrtime_t when, void *p);
 216         pthread_mutex_t zn_mutex;
 217         pthread_cond_t zn_cond;
 218         pthread_mutex_t zn_bigmutex;
 219         volatile enum {ZN_UNLOCKED, ZN_LOCKED, ZN_PING_INFLIGHT,
 220             ZN_PING_RECEIVED} zn_state;
 221         char zn_subscriber_id[MAX_SUBID_LEN];
 222         volatile boolean_t zn_failed;
 223         int zn_failure_count;
 224 };
 225 
 226 /* used to track nested zone-lock operations */
 227 static int zone_lock_cnt = 0;
 228 
 229 /* used to communicate lock status to children */
 230 #define LOCK_ENV_VAR    "_ZONEADM_LOCK_HELD"
 231 static char zoneadm_lock_held[] = LOCK_ENV_VAR"=1";
 232 static char zoneadm_lock_not_held[] = LOCK_ENV_VAR"=0";
 233 
 234 char *zonecfg_root = "";
 235 
 236 /*
 237  * For functions which return int, which is most of the functions herein,
 238  * the return values should be from the Z_foo set defined in <libzonecfg.h>.
 239  * In some instances, we take pains mapping some libc errno values to Z_foo
 240  * values from this set.
 241  */
 242 
 243 /*
 244  * Set the root (/) path for all zonecfg configuration files.  This is a
 245  * private interface used by Live Upgrade extensions to access zone
 246  * configuration inside mounted alternate boot environments.
 247  * This interface is also used by zoneadm mount and unmount subcommands.
 248  */
 249 void
 250 zonecfg_set_root(const char *rootpath)
 251 {
 252         if (*zonecfg_root != '\0')
 253                 free(zonecfg_root);
 254         if (rootpath == NULL || rootpath[0] == '\0' || rootpath[1] == '\0' ||
 255             (zonecfg_root = strdup(rootpath)) == NULL)
 256                 zonecfg_root = "";
 257 }
 258 
 259 const char *
 260 zonecfg_get_root(void)
 261 {
 262         return (zonecfg_root);
 263 }
 264 
 265 boolean_t
 266 zonecfg_in_alt_root(void)
 267 {
 268         return (*zonecfg_root != '\0');
 269 }
 270 
 271 /*
 272  * Callers of the _file_path() functions are expected to have the second
 273  * parameter be a (char foo[MAXPATHLEN]).
 274  */
 275 
 276 static boolean_t
 277 file_path_common(const char *zonename, const char *subdir, const char *stem,
 278     char *answer, size_t answer_size)
 279 {
 280         const char *native_root = zone_get_nroot();
 281 
 282         if (native_root == NULL || zonecfg_in_alt_root()) {
 283                 /*
 284                  * Do not prepend the native system root (e.g. "/native") if an
 285                  * alternative configuration root has been selected.
 286                  */
 287                 native_root = "";
 288         }
 289 
 290         return (snprintf(answer, answer_size, "%s%s%s/%s.%s", native_root,
 291             zonecfg_root, subdir, zonename, stem) < answer_size);
 292 }
 293 
 294 static boolean_t
 295 config_file_path(const char *zonename, char *answer, size_t answer_size)
 296 {
 297         return (file_path_common(zonename, ZONE_CONFIG_ROOT, "xml", answer,
 298             answer_size));
 299 }
 300 
 301 static boolean_t
 302 snap_file_path(const char *zonename, char *answer, size_t answer_size)
 303 {
 304         return (file_path_common(zonename, ZONE_SNAPSHOT_ROOT, "snapshot.xml",
 305             answer, answer_size));
 306 }
 307 
 308 /*ARGSUSED*/
 309 static void
 310 zonecfg_error_func(void *ctx, const char *msg, ...)
 311 {
 312         /*
 313          * This function does nothing by design.  Its purpose is to prevent
 314          * libxml from dumping unwanted messages to stdout/stderr.
 315          */
 316 }
 317 
 318 zone_dochandle_t
 319 zonecfg_init_handle(void)
 320 {
 321         zone_dochandle_t handle = calloc(1, sizeof (struct zone_dochandle));
 322         if (handle == NULL) {
 323                 errno = Z_NOMEM;
 324                 return (NULL);
 325         }
 326 
 327         /* generic libxml initialization */
 328         (void) xmlLineNumbersDefault(1);
 329         xmlLoadExtDtdDefaultValue |= XML_DETECT_IDS;
 330         xmlDoValidityCheckingDefaultValue = 1;
 331         (void) xmlKeepBlanksDefault(0);
 332         xmlGetWarningsDefaultValue = 0;
 333         xmlSetGenericErrorFunc(NULL, zonecfg_error_func);
 334 
 335         return (handle);
 336 }
 337 
 338 int
 339 zonecfg_check_handle(zone_dochandle_t handle)
 340 {
 341         if (handle == NULL || handle->zone_dh_doc == NULL)
 342                 return (Z_BAD_HANDLE);
 343         return (Z_OK);
 344 }
 345 
 346 void
 347 zonecfg_fini_handle(zone_dochandle_t handle)
 348 {
 349         if (zonecfg_check_handle(handle) == Z_OK)
 350                 xmlFreeDoc(handle->zone_dh_doc);
 351         if (handle != NULL)
 352                 free(handle);
 353 }
 354 
 355 static int
 356 zonecfg_destroy_impl(char *filename)
 357 {
 358         if (unlink(filename) == -1) {
 359                 if (errno == EACCES)
 360                         return (Z_ACCES);
 361                 if (errno == ENOENT)
 362                         return (Z_NO_ZONE);
 363                 return (Z_MISC_FS);
 364         }
 365         return (Z_OK);
 366 }
 367 
 368 int
 369 zonecfg_destroy(const char *zonename, boolean_t force)
 370 {
 371         char path[MAXPATHLEN];
 372         struct zoneent ze;
 373         int err, state_err;
 374         zone_state_t state;
 375 
 376         if (!config_file_path(zonename, path, sizeof (path)))
 377                 return (Z_MISC_FS);
 378 
 379         state_err = zone_get_state((char *)zonename, &state);
 380         err = access(path, W_OK);
 381 
 382         /*
 383          * If there is no file, and no index entry, reliably indicate that no
 384          * such zone exists.
 385          */
 386         if ((state_err == Z_NO_ZONE) && (err == -1) && (errno == ENOENT))
 387                 return (Z_NO_ZONE);
 388 
 389         /*
 390          * Handle any other filesystem related errors (except if the XML
 391          * file is missing, which we treat silently), unless we're forcing,
 392          * in which case we plow on.
 393          */
 394         if (err == -1 && errno != ENOENT) {
 395                 if (errno == EACCES)
 396                         return (Z_ACCES);
 397                 else if (!force)
 398                         return (Z_MISC_FS);
 399         }
 400 
 401         if (state > ZONE_STATE_INSTALLED)
 402                 return (Z_BAD_ZONE_STATE);
 403 
 404         if (!force && state > ZONE_STATE_CONFIGURED)
 405                 return (Z_BAD_ZONE_STATE);
 406 
 407         /*
 408          * Index deletion succeeds even if the entry doesn't exist.  So this
 409          * will fail only if we've had some more severe problem.
 410          */
 411         bzero(&ze, sizeof (ze));
 412         (void) strlcpy(ze.zone_name, zonename, sizeof (ze.zone_name));
 413         if ((err = putzoneent(&ze, PZE_REMOVE)) != Z_OK)
 414                 if (!force)
 415                         return (err);
 416 
 417         err = zonecfg_destroy_impl(path);
 418 
 419         /*
 420          * Treat failure to find the XML file silently, since, well, it's
 421          * gone, and with the index file cleaned up, we're done.
 422          */
 423         if (err == Z_OK || err == Z_NO_ZONE)
 424                 return (Z_OK);
 425         return (err);
 426 }
 427 
 428 int
 429 zonecfg_destroy_snapshot(const char *zonename)
 430 {
 431         char path[MAXPATHLEN];
 432 
 433         if (!snap_file_path(zonename, path, sizeof (path)))
 434                 return (Z_MISC_FS);
 435         return (zonecfg_destroy_impl(path));
 436 }
 437 
 438 static int
 439 getroot(zone_dochandle_t handle, xmlNodePtr *root)
 440 {
 441         if (zonecfg_check_handle(handle) == Z_BAD_HANDLE)
 442                 return (Z_BAD_HANDLE);
 443 
 444         *root = xmlDocGetRootElement(handle->zone_dh_doc);
 445 
 446         if (*root == NULL)
 447                 return (Z_EMPTY_DOCUMENT);
 448 
 449         if (xmlStrcmp((*root)->name, DTD_ELEM_ZONE))
 450                 return (Z_WRONG_DOC_TYPE);
 451 
 452         return (Z_OK);
 453 }
 454 
 455 static int
 456 operation_prep(zone_dochandle_t handle)
 457 {
 458         xmlNodePtr root;
 459         int err;
 460 
 461         if ((err = getroot(handle, &root)) != 0)
 462                 return (err);
 463 
 464         handle->zone_dh_cur = root;
 465         handle->zone_dh_top = root;
 466         return (Z_OK);
 467 }
 468 
 469 static int
 470 fetchprop(xmlNodePtr cur, const xmlChar *propname, char *dst, size_t dstsize)
 471 {
 472         xmlChar *property;
 473         size_t srcsize;
 474 
 475         if ((property = xmlGetProp(cur, propname)) == NULL)
 476                 return (Z_BAD_PROPERTY);
 477         srcsize = strlcpy(dst, (char *)property, dstsize);
 478         xmlFree(property);
 479         if (srcsize >= dstsize)
 480                 return (Z_TOO_BIG);
 481         return (Z_OK);
 482 }
 483 
 484 static int
 485 fetch_alloc_prop(xmlNodePtr cur, const xmlChar *propname, char **dst)
 486 {
 487         xmlChar *property;
 488 
 489         if ((property = xmlGetProp(cur, propname)) == NULL)
 490                 return (Z_BAD_PROPERTY);
 491         if ((*dst = strdup((char *)property)) == NULL) {
 492                 xmlFree(property);
 493                 return (Z_NOMEM);
 494         }
 495         xmlFree(property);
 496         return (Z_OK);
 497 }
 498 
 499 static int
 500 getrootattr(zone_dochandle_t handle, const xmlChar *propname,
 501     char *propval, size_t propsize)
 502 {
 503         xmlNodePtr root;
 504         int err;
 505 
 506         if ((err = getroot(handle, &root)) != 0)
 507                 return (err);
 508 
 509         return (fetchprop(root, propname, propval, propsize));
 510 }
 511 
 512 static int
 513 get_alloc_rootattr(zone_dochandle_t handle, const xmlChar *propname,
 514     char **propval)
 515 {
 516         xmlNodePtr root;
 517         int err;
 518 
 519         if ((err = getroot(handle, &root)) != 0)
 520                 return (err);
 521 
 522         return (fetch_alloc_prop(root, propname, propval));
 523 }
 524 
 525 static int
 526 setrootattr(zone_dochandle_t handle, const xmlChar *propname,
 527     const char *propval)
 528 {
 529         int err;
 530         xmlNodePtr root;
 531 
 532         if ((err = getroot(handle, &root)) != Z_OK)
 533                 return (err);
 534 
 535         /*
 536          * If we get a null propval remove the property (ignore return since it
 537          * may not be set to begin with).
 538          */
 539         if (propval == NULL) {
 540                 (void) xmlUnsetProp(root, propname);
 541         } else {
 542                 if (xmlSetProp(root, propname, (const xmlChar *) propval)
 543                     == NULL)
 544                         return (Z_INVAL);
 545         }
 546         return (Z_OK);
 547 }
 548 
 549 static void
 550 addcomment(zone_dochandle_t handle, const char *comment)
 551 {
 552         xmlNodePtr node;
 553         node = xmlNewComment((xmlChar *) comment);
 554 
 555         if (node != NULL)
 556                 (void) xmlAddPrevSibling(handle->zone_dh_top, node);
 557 }
 558 
 559 static void
 560 stripcomments(zone_dochandle_t handle)
 561 {
 562         xmlDocPtr top;
 563         xmlNodePtr child, next;
 564 
 565         top = handle->zone_dh_doc;
 566         for (child = top->xmlChildrenNode; child != NULL; child = next) {
 567                 next = child->next;
 568                 if (child->name == NULL)
 569                         continue;
 570                 if (xmlStrcmp(child->name, DTD_ELEM_COMMENT) == 0) {
 571                         next = child->next;
 572                         xmlUnlinkNode(child);
 573                         xmlFreeNode(child);
 574                 }
 575         }
 576 }
 577 
 578 static void
 579 strip_sw_inv(zone_dochandle_t handle)
 580 {
 581         xmlNodePtr root, child, next;
 582 
 583         root = xmlDocGetRootElement(handle->zone_dh_doc);
 584         for (child = root->xmlChildrenNode; child != NULL; child = next) {
 585                 next = child->next;
 586                 if (child->name == NULL)
 587                         continue;
 588                 if (xmlStrcmp(child->name, DTD_ELEM_PACKAGE) == 0) {
 589                         next = child->next;
 590                         xmlUnlinkNode(child);
 591                         xmlFreeNode(child);
 592                 }
 593         }
 594 }
 595 
 596 static int
 597 zonecfg_get_handle_impl(const char *zonename, const char *filename,
 598     zone_dochandle_t handle)
 599 {
 600         struct stat statbuf;
 601         boolean_t valid;
 602 
 603         if (zonename == NULL)
 604                 return (Z_NO_ZONE);
 605 
 606         if ((handle->zone_dh_doc = xmlParseFile(filename)) == NULL) {
 607                 /* distinguish file not found vs. found but not parsed */
 608                 if (stat(filename, &statbuf) == 0)
 609                         return (Z_INVALID_DOCUMENT);
 610                 return (Z_NO_ZONE);
 611         }
 612 
 613         if (os_dtd_validate(handle->zone_dh_doc, B_FALSE, &valid) != 0) {
 614                 return (Z_NOMEM);
 615         }
 616         if (!valid) {
 617                 return (Z_INVALID_DOCUMENT);
 618         }
 619 
 620         /* delete any comments such as inherited Sun copyright / ident str */
 621         stripcomments(handle);
 622         return (Z_OK);
 623 }
 624 
 625 int
 626 zonecfg_get_handle(const char *zonename, zone_dochandle_t handle)
 627 {
 628         char path[MAXPATHLEN];
 629 
 630         if (!config_file_path(zonename, path, sizeof (path)))
 631                 return (Z_MISC_FS);
 632         handle->zone_dh_newzone = B_FALSE;
 633 
 634         return (zonecfg_get_handle_impl(zonename, path, handle));
 635 }
 636 
 637 int
 638 zonecfg_get_attach_handle(const char *path, const char *fname,
 639     const char *zonename, boolean_t preserve_sw, zone_dochandle_t handle)
 640 {
 641         char            migpath[MAXPATHLEN];
 642         int             err;
 643         struct stat     buf;
 644 
 645         if (snprintf(migpath, sizeof (migpath), "%s/root", path) >=
 646             sizeof (migpath))
 647                 return (Z_NOMEM);
 648 
 649         if (stat(migpath, &buf) == -1 || !S_ISDIR(buf.st_mode))
 650                 return (Z_NO_ZONE);
 651 
 652         if (snprintf(migpath, sizeof (migpath), "%s/%s", path, fname) >=
 653             sizeof (migpath))
 654                 return (Z_NOMEM);
 655 
 656         if ((err = zonecfg_get_handle_impl(zonename, migpath, handle)) != Z_OK)
 657                 return (err);
 658 
 659         if (!preserve_sw)
 660                 strip_sw_inv(handle);
 661 
 662         handle->zone_dh_newzone = B_TRUE;
 663         if ((err = setrootattr(handle, DTD_ATTR_ZONEPATH, path)) != Z_OK)
 664                 return (err);
 665 
 666         return (setrootattr(handle, DTD_ATTR_NAME, zonename));
 667 }
 668 
 669 int
 670 zonecfg_get_snapshot_handle(const char *zonename, zone_dochandle_t handle)
 671 {
 672         char path[MAXPATHLEN];
 673 
 674         if (!snap_file_path(zonename, path, sizeof (path)))
 675                 return (Z_MISC_FS);
 676         handle->zone_dh_newzone = B_FALSE;
 677         return (zonecfg_get_handle_impl(zonename, path, handle));
 678 }
 679 
 680 int
 681 zonecfg_get_template_handle(const char *template, const char *zonename,
 682     zone_dochandle_t handle)
 683 {
 684         char path[MAXPATHLEN];
 685         int err;
 686 
 687         if (!config_file_path(template, path, sizeof (path)))
 688                 return (Z_MISC_FS);
 689 
 690         if ((err = zonecfg_get_handle_impl(template, path, handle)) != Z_OK)
 691                 return (err);
 692         handle->zone_dh_newzone = B_TRUE;
 693         return (setrootattr(handle, DTD_ATTR_NAME, zonename));
 694 }
 695 
 696 int
 697 zonecfg_get_xml_handle(const char *path, zone_dochandle_t handle)
 698 {
 699         struct stat buf;
 700         int err;
 701 
 702         if (stat(path, &buf) == -1)
 703                 return (Z_MISC_FS);
 704 
 705         if ((err = zonecfg_get_handle_impl("xml", path, handle)) != Z_OK)
 706                 return (err);
 707         handle->zone_dh_newzone = B_TRUE;
 708         return (Z_OK);
 709 }
 710 
 711 /*
 712  * Initialize two handles from the manifest read on fd.  The rem_handle
 713  * is initialized from the input file, including the sw inventory.  The
 714  * local_handle is initialized with the same zone configuration but with
 715  * no sw inventory.
 716  */
 717 int
 718 zonecfg_attach_manifest(int fd, zone_dochandle_t local_handle,
 719     zone_dochandle_t rem_handle)
 720 {
 721         boolean_t valid;
 722 
 723         /* load the manifest into the handle for the remote system */
 724         if ((rem_handle->zone_dh_doc = xmlReadFd(fd, NULL, NULL, 0)) == NULL) {
 725                 return (Z_INVALID_DOCUMENT);
 726         }
 727 
 728         if (os_dtd_validate(rem_handle->zone_dh_doc, B_FALSE, &valid) != 0) {
 729                 return (Z_NOMEM);
 730         }
 731         if (!valid) {
 732                 return (Z_INVALID_DOCUMENT);
 733         }
 734 
 735         /* delete any comments such as inherited Sun copyright / ident str */
 736         stripcomments(rem_handle);
 737 
 738         rem_handle->zone_dh_newzone = B_TRUE;
 739         rem_handle->zone_dh_sw_inv = B_TRUE;
 740 
 741         /*
 742          * Now use the remote system handle to generate a local system handle
 743          * with an identical zones configuration but no sw inventory.
 744          */
 745         if ((local_handle->zone_dh_doc = xmlCopyDoc(rem_handle->zone_dh_doc,
 746             1)) == NULL) {
 747                 return (Z_INVALID_DOCUMENT);
 748         }
 749 
 750         /*
 751          * We need to re-run xmlValidateDocument on local_handle to properly
 752          * update the in-core representation of the configuration.
 753          */
 754         if (os_dtd_validate(local_handle->zone_dh_doc, B_FALSE, &valid) != 0) {
 755                 return (Z_NOMEM);
 756         }
 757         if (!valid) {
 758                 return (Z_INVALID_DOCUMENT);
 759         }
 760 
 761         strip_sw_inv(local_handle);
 762 
 763         local_handle->zone_dh_newzone = B_TRUE;
 764         local_handle->zone_dh_sw_inv = B_FALSE;
 765 
 766         return (Z_OK);
 767 }
 768 
 769 static boolean_t
 770 is_renaming(zone_dochandle_t handle)
 771 {
 772         if (handle->zone_dh_newzone)
 773                 return (B_FALSE);
 774         if (strlen(handle->zone_dh_delete_name) > 0)
 775                 return (B_TRUE);
 776         return (B_FALSE);
 777 }
 778 
 779 static boolean_t
 780 is_new(zone_dochandle_t handle)
 781 {
 782         return (handle->zone_dh_newzone || handle->zone_dh_snapshot);
 783 }
 784 
 785 static boolean_t
 786 is_snapshot(zone_dochandle_t handle)
 787 {
 788         return (handle->zone_dh_snapshot);
 789 }
 790 
 791 /*
 792  * It would be great to be able to use libc's ctype(3c) macros, but we
 793  * can't, as they are locale sensitive, and it would break our limited thread
 794  * safety if this routine had to change the app locale on the fly.
 795  */
 796 int
 797 zonecfg_validate_zonename(const char *zone)
 798 {
 799         int i;
 800 
 801         if (strcmp(zone, GLOBAL_ZONENAME) == 0)
 802                 return (Z_BOGUS_ZONE_NAME);
 803 
 804         if (strlen(zone) >= ZONENAME_MAX)
 805                 return (Z_BOGUS_ZONE_NAME);
 806 
 807         if (!((zone[0] >= 'a' && zone[0] <= 'z') ||
 808             (zone[0] >= 'A' && zone[0] <= 'Z') ||
 809             (zone[0] >= '0' && zone[0] <= '9')))
 810                 return (Z_BOGUS_ZONE_NAME);
 811 
 812         for (i = 1; zone[i] != '\0'; i++) {
 813                 if (!((zone[i] >= 'a' && zone[i] <= 'z') ||
 814                     (zone[i] >= 'A' && zone[i] <= 'Z') ||
 815                     (zone[i] >= '0' && zone[i] <= '9') ||
 816                     (zone[i] == '-') || (zone[i] == '_') || (zone[i] == '.')))
 817                         return (Z_BOGUS_ZONE_NAME);
 818         }
 819 
 820         return (Z_OK);
 821 }
 822 
 823 /*
 824  * Changing the zone name requires us to track both the old and new
 825  * name of the zone until commit time.
 826  */
 827 int
 828 zonecfg_get_name(zone_dochandle_t handle, char *name, size_t namesize)
 829 {
 830         return (getrootattr(handle, DTD_ATTR_NAME, name, namesize));
 831 }
 832 
 833 static int
 834 insert_admins(zone_dochandle_t handle, char *zonename)
 835 {
 836         int err;
 837         struct zone_admintab admintab;
 838 
 839         if ((err = zonecfg_setadminent(handle)) != Z_OK) {
 840                 return (err);
 841         }
 842         while (zonecfg_getadminent(handle, &admintab) == Z_OK) {
 843                 err = zonecfg_insert_userauths(handle,
 844                     admintab.zone_admin_user, zonename);
 845                 if (err != Z_OK) {
 846                         (void) zonecfg_endadminent(handle);
 847                         return (err);
 848                 }
 849         }
 850         (void) zonecfg_endadminent(handle);
 851         return (Z_OK);
 852 }
 853 
 854 int
 855 zonecfg_set_name(zone_dochandle_t handle, char *name)
 856 {
 857         zone_state_t state;
 858         char curname[ZONENAME_MAX], old_delname[ZONENAME_MAX];
 859         int err;
 860 
 861         if ((err = getrootattr(handle, DTD_ATTR_NAME, curname,
 862             sizeof (curname))) != Z_OK)
 863                 return (err);
 864 
 865         if (strcmp(name, curname) == 0)
 866                 return (Z_OK);
 867 
 868         /*
 869          * Switching zone names to one beginning with SUNW is not permitted.
 870          */
 871         if (strncmp(name, "SUNW", 4) == 0)
 872                 return (Z_BOGUS_ZONE_NAME);
 873 
 874         if ((err = zonecfg_validate_zonename(name)) != Z_OK)
 875                 return (err);
 876 
 877         /*
 878          * Setting the name back to the original name (effectively a revert of
 879          * the name) is fine.  But if we carry on, we'll falsely identify the
 880          * name as "in use," so special case here.
 881          */
 882         if (strcmp(name, handle->zone_dh_delete_name) == 0) {
 883                 err = setrootattr(handle, DTD_ATTR_NAME, name);
 884                 handle->zone_dh_delete_name[0] = '\0';
 885                 return (err);
 886         }
 887 
 888         /* Check to see if new name chosen is already in use */
 889         if (zone_get_state(name, &state) != Z_NO_ZONE)
 890                 return (Z_NAME_IN_USE);
 891 
 892         /*
 893          * If this isn't already "new" or in a renaming transition, then
 894          * we're initiating a rename here; so stash the "delete name"
 895          * (i.e. the name of the zone we'll be removing) for the rename.
 896          */
 897         (void) strlcpy(old_delname, handle->zone_dh_delete_name,
 898             sizeof (old_delname));
 899         if (!is_new(handle) && !is_renaming(handle)) {
 900                 /*
 901                  * Name change is allowed only when the zone we're altering
 902                  * is not ready or running.
 903                  */
 904                 err = zone_get_state(curname, &state);
 905                 if (err == Z_OK) {
 906                         if (state > ZONE_STATE_INSTALLED)
 907                                 return (Z_BAD_ZONE_STATE);
 908                 } else if (err != Z_NO_ZONE) {
 909                         return (err);
 910                 }
 911 
 912                 (void) strlcpy(handle->zone_dh_delete_name, curname,
 913                     sizeof (handle->zone_dh_delete_name));
 914                 assert(is_renaming(handle));
 915         } else if (is_renaming(handle)) {
 916                 err = zone_get_state(handle->zone_dh_delete_name, &state);
 917                 if (err == Z_OK) {
 918                         if (state > ZONE_STATE_INSTALLED)
 919                                 return (Z_BAD_ZONE_STATE);
 920                 } else if (err != Z_NO_ZONE) {
 921                         return (err);
 922                 }
 923         }
 924 
 925         if ((err = setrootattr(handle, DTD_ATTR_NAME, name)) != Z_OK) {
 926                 /*
 927                  * Restore the deletename to whatever it was at the
 928                  * top of the routine, since we've had a failure.
 929                  */
 930                 (void) strlcpy(handle->zone_dh_delete_name, old_delname,
 931                     sizeof (handle->zone_dh_delete_name));
 932                 return (err);
 933         }
 934 
 935         /*
 936          * Record the old admins from the old zonename
 937          * so that they can be deleted when the operation is committed.
 938          */
 939         if ((err = insert_admins(handle, curname)) != Z_OK)
 940                 return (err);
 941         else
 942                 return (Z_OK);
 943 }
 944 
 945 int
 946 zonecfg_get_zonepath(zone_dochandle_t handle, char *path, size_t pathsize)
 947 {
 948         size_t len;
 949 
 950         if ((len = strlcpy(path, zonecfg_root, pathsize)) >= pathsize)
 951                 return (Z_TOO_BIG);
 952         return (getrootattr(handle, DTD_ATTR_ZONEPATH, path + len,
 953             pathsize - len));
 954 }
 955 
 956 int
 957 zonecfg_set_zonepath(zone_dochandle_t handle, char *zonepath)
 958 {
 959         size_t len;
 960         char *modpath, *copy_mp, *curr_mp;      /* modified path ptrs */
 961         char last_copied;
 962         int ret;
 963 
 964         /*
 965          * Collapse multiple contiguous slashes and remove trailing slash.
 966          */
 967         modpath = strdup(zonepath);
 968         if (modpath == NULL)
 969                 return (Z_NOMEM);
 970         last_copied = '\0';
 971         for (copy_mp = curr_mp = modpath; *curr_mp != '\0'; curr_mp++) {
 972                 if (*curr_mp != '/' || last_copied != '/') {
 973                         last_copied = *copy_mp = *curr_mp;
 974                         copy_mp++;
 975                 }
 976         }
 977         if (last_copied == '/')
 978                 copy_mp--;
 979         *copy_mp = '\0';
 980 
 981         /*
 982          * The user deals in absolute paths in the running global zone, but the
 983          * internal configuration files deal with boot environment relative
 984          * paths.  Strip out the alternate root when specified.
 985          */
 986         len = strlen(zonecfg_root);
 987         if (strncmp(modpath, zonecfg_root, len) != 0 || modpath[len] != '/') {
 988                 free(modpath);
 989                 return (Z_BAD_PROPERTY);
 990         }
 991         curr_mp = modpath + len;
 992         ret = setrootattr(handle, DTD_ATTR_ZONEPATH, curr_mp);
 993         free(modpath);
 994         return (ret);
 995 }
 996 
 997 static int
 998 i_zonecfg_get_brand(zone_dochandle_t handle, char *brand, size_t brandsize,
 999     boolean_t default_query)
1000 {
1001         int ret, sz;
1002 
1003         ret = getrootattr(handle, DTD_ATTR_BRAND, brand, brandsize);
1004 
1005         /*
1006          * If the lookup failed, or succeeded in finding a non-null brand
1007          * string then return.
1008          */
1009         if (ret != Z_OK || brand[0] != '\0')
1010                 return (ret);
1011 
1012         if (!default_query) {
1013                 /* If the zone has no brand, it is the default brand. */
1014                 return (zonecfg_default_brand(brand, brandsize));
1015         }
1016 
1017         /* if SUNWdefault didn't specify a brand, fallback to "native" */
1018         sz = strlcpy(brand, NATIVE_BRAND_NAME, brandsize);
1019         if (sz >= brandsize)
1020                 return (Z_TOO_BIG);
1021         return (Z_OK);
1022 }
1023 
1024 int
1025 zonecfg_get_brand(zone_dochandle_t handle, char *brand, size_t brandsize)
1026 {
1027         return (i_zonecfg_get_brand(handle, brand, brandsize, B_FALSE));
1028 }
1029 
1030 int
1031 zonecfg_set_brand(zone_dochandle_t handle, char *brand)
1032 {
1033         return (setrootattr(handle, DTD_ATTR_BRAND, brand));
1034 }
1035 
1036 int
1037 zonecfg_get_autoboot(zone_dochandle_t handle, boolean_t *autoboot)
1038 {
1039         char autobootstr[DTD_ENTITY_BOOL_LEN];
1040         int ret;
1041 
1042         if ((ret = getrootattr(handle, DTD_ATTR_AUTOBOOT, autobootstr,
1043             sizeof (autobootstr))) != Z_OK)
1044                 return (ret);
1045 
1046         if (strcmp(autobootstr, DTD_ENTITY_TRUE) == 0)
1047                 *autoboot = B_TRUE;
1048         else if (strcmp(autobootstr, DTD_ENTITY_FALSE) == 0)
1049                 *autoboot = B_FALSE;
1050         else
1051                 ret = Z_BAD_PROPERTY;
1052         return (ret);
1053 }
1054 
1055 int
1056 zonecfg_set_autoboot(zone_dochandle_t handle, boolean_t autoboot)
1057 {
1058         return (setrootattr(handle, DTD_ATTR_AUTOBOOT,
1059             autoboot ? DTD_ENTITY_TRUE : DTD_ENTITY_FALSE));
1060 }
1061 
1062 int
1063 zonecfg_get_pool(zone_dochandle_t handle, char *pool, size_t poolsize)
1064 {
1065         return (getrootattr(handle, DTD_ATTR_POOL, pool, poolsize));
1066 }
1067 
1068 int
1069 zonecfg_set_pool(zone_dochandle_t handle, char *pool)
1070 {
1071         return (setrootattr(handle, DTD_ATTR_POOL, pool));
1072 }
1073 
1074 int
1075 zonecfg_get_limitpriv(zone_dochandle_t handle, char **limitpriv)
1076 {
1077         return (get_alloc_rootattr(handle, DTD_ATTR_LIMITPRIV, limitpriv));
1078 }
1079 
1080 int
1081 zonecfg_set_limitpriv(zone_dochandle_t handle, char *limitpriv)
1082 {
1083         return (setrootattr(handle, DTD_ATTR_LIMITPRIV, limitpriv));
1084 }
1085 
1086 int
1087 zonecfg_get_bootargs(zone_dochandle_t handle, char *bargs, size_t bargssize)
1088 {
1089         return (getrootattr(handle, DTD_ATTR_BOOTARGS, bargs, bargssize));
1090 }
1091 
1092 int
1093 zonecfg_set_bootargs(zone_dochandle_t handle, char *bargs)
1094 {
1095         return (setrootattr(handle, DTD_ATTR_BOOTARGS, bargs));
1096 }
1097 
1098 int
1099 zonecfg_get_sched_class(zone_dochandle_t handle, char *sched, size_t schedsize)
1100 {
1101         return (getrootattr(handle, DTD_ATTR_SCHED, sched, schedsize));
1102 }
1103 
1104 int
1105 zonecfg_set_sched(zone_dochandle_t handle, char *sched)
1106 {
1107         return (setrootattr(handle, DTD_ATTR_SCHED, sched));
1108 }
1109 
1110 /*
1111  * /etc/zones/index caches a vital piece of information which is also
1112  * in the <zonename>.xml file: the path to the zone.  This is for performance,
1113  * since we need to walk all zonepath's in order to be able to detect conflicts
1114  * (see crosscheck_zonepaths() in the zoneadm command).
1115  *
1116  * An additional complexity is that when doing a rename, we'd like the entire
1117  * index update operation (rename, and potential state changes) to be atomic.
1118  * In general, the operation of this function should succeed or fail as
1119  * a unit.
1120  */
1121 int
1122 zonecfg_refresh_index_file(zone_dochandle_t handle)
1123 {
1124         char name[ZONENAME_MAX], zonepath[MAXPATHLEN];
1125         struct zoneent ze;
1126         int err;
1127         int opcode;
1128         char *zn;
1129 
1130         bzero(&ze, sizeof (ze));
1131         ze.zone_state = -1;     /* Preserve existing state in index */
1132 
1133         if ((err = zonecfg_get_name(handle, name, sizeof (name))) != Z_OK)
1134                 return (err);
1135         (void) strlcpy(ze.zone_name, name, sizeof (ze.zone_name));
1136 
1137         if ((err = zonecfg_get_zonepath(handle, zonepath,
1138             sizeof (zonepath))) != Z_OK)
1139                 return (err);
1140         (void) strlcpy(ze.zone_path, zonepath + strlen(zonecfg_root),
1141             sizeof (ze.zone_path));
1142 
1143         if (is_renaming(handle)) {
1144                 opcode = PZE_MODIFY;
1145                 (void) strlcpy(ze.zone_name, handle->zone_dh_delete_name,
1146                     sizeof (ze.zone_name));
1147                 (void) strlcpy(ze.zone_newname, name, sizeof (ze.zone_newname));
1148         } else if (is_new(handle)) {
1149                 FILE *cookie;
1150                 /*
1151                  * Be tolerant of the zone already existing in the index file,
1152                  * since we might be forcibly overwriting an existing
1153                  * configuration with a new one (for example 'create -F'
1154                  * in zonecfg).
1155                  */
1156                 opcode = PZE_ADD;
1157                 cookie = setzoneent();
1158                 while ((zn = getzoneent(cookie)) != NULL) {
1159                         if (strcmp(zn, name) == 0) {
1160                                 opcode = PZE_MODIFY;
1161                                 free(zn);
1162                                 break;
1163                         }
1164                         free(zn);
1165                 }
1166                 endzoneent(cookie);
1167                 ze.zone_state = ZONE_STATE_CONFIGURED;
1168         } else {
1169                 opcode = PZE_MODIFY;
1170         }
1171 
1172         if ((err = putzoneent(&ze, opcode)) != Z_OK)
1173                 return (err);
1174 
1175         return (Z_OK);
1176 }
1177 
1178 /*
1179  * The goal of this routine is to cause the index file update and the
1180  * document save to happen as an atomic operation.  We do the document
1181  * first, saving a backup copy using a hard link; if that succeeds, we go
1182  * on to the index.  If that fails, we roll the document back into place.
1183  *
1184  * Strategy:
1185  *
1186  * New zone 'foo' configuration:
1187  *      Create tmpfile (zonecfg.xxxxxx)
1188  *      Write XML to tmpfile
1189  *      Rename tmpfile to xmlfile (zonecfg.xxxxxx -> foo.xml)
1190  *      Add entry to index file
1191  *      If it fails, delete foo.xml, leaving nothing behind.
1192  *
1193  * Save existing zone 'foo':
1194  *      Make backup of foo.xml -> .backup
1195  *      Create tmpfile (zonecfg.xxxxxx)
1196  *      Write XML to tmpfile
1197  *      Rename tmpfile to xmlfile (zonecfg.xxxxxx -> foo.xml)
1198  *      Modify index file as needed
1199  *      If it fails, recover from .backup -> foo.xml
1200  *
1201  * Rename 'foo' to 'bar':
1202  *      Create tmpfile (zonecfg.xxxxxx)
1203  *      Write XML to tmpfile
1204  *      Rename tmpfile to xmlfile (zonecfg.xxxxxx -> bar.xml)
1205  *      Add entry for 'bar' to index file, Remove entry for 'foo' (refresh)
1206  *      If it fails, delete bar.xml; foo.xml is left behind.
1207  */
1208 static int
1209 zonecfg_save_impl(zone_dochandle_t handle, char *filename)
1210 {
1211         char tmpfile[MAXPATHLEN];
1212         char bakdir[MAXPATHLEN], bakbase[MAXPATHLEN], bakfile[MAXPATHLEN];
1213         int tmpfd, err;
1214         boolean_t backup;
1215         boolean_t valid;
1216 
1217         (void) strlcpy(tmpfile, filename, sizeof (tmpfile));
1218         (void) dirname(tmpfile);
1219         (void) strlcat(tmpfile, _PATH_TMPFILE, sizeof (tmpfile));
1220 
1221         tmpfd = mkstemp(tmpfile);
1222         if (tmpfd == -1) {
1223                 (void) unlink(tmpfile);
1224                 return (Z_TEMP_FILE);
1225         }
1226         (void) close(tmpfd);
1227 
1228         /*
1229          * We do a final validation of the document.  Since the library has
1230          * malfunctioned if it fails to validate, we follow-up with an
1231          * assert() that the doc is valid.
1232          */
1233         VERIFY0(os_dtd_validate(handle->zone_dh_doc, B_FALSE, &valid));
1234         VERIFY(valid == B_TRUE);
1235 
1236         if (xmlSaveFormatFile(tmpfile, handle->zone_dh_doc, 1) <= 0)
1237                 goto err;
1238 
1239         (void) chmod(tmpfile, 0644);
1240 
1241         /*
1242          * In the event we are doing a standard save, hard link a copy of the
1243          * original file in .backup.<pid>.filename so we can restore it if
1244          * something goes wrong.
1245          */
1246         if (!is_new(handle) && !is_renaming(handle)) {
1247                 backup = B_TRUE;
1248 
1249                 (void) strlcpy(bakdir, filename, sizeof (bakdir));
1250                 (void) strlcpy(bakbase, filename, sizeof (bakbase));
1251                 (void) snprintf(bakfile, sizeof (bakfile), "%s/.backup.%d.%s",
1252                     dirname(bakdir), getpid(), basename(bakbase));
1253 
1254                 if (link(filename, bakfile) == -1) {
1255                         err = errno;
1256                         (void) unlink(tmpfile);
1257                         if (errno == EACCES)
1258                                 return (Z_ACCES);
1259                         return (Z_MISC_FS);
1260                 }
1261         }
1262 
1263         /*
1264          * Move the new document over top of the old.
1265          * i.e.:   zonecfg.XXXXXX  ->  myzone.xml
1266          */
1267         if (rename(tmpfile, filename) == -1) {
1268                 err = errno;
1269                 (void) unlink(tmpfile);
1270                 if (backup)
1271                         (void) unlink(bakfile);
1272                 if (err == EACCES)
1273                         return (Z_ACCES);
1274                 return (Z_MISC_FS);
1275         }
1276 
1277         /*
1278          * If this is a snapshot, we're done-- don't add an index entry.
1279          */
1280         if (is_snapshot(handle))
1281                 return (Z_OK);
1282 
1283         /* now update the index file to reflect whatever we just did */
1284         if ((err = zonecfg_refresh_index_file(handle)) != Z_OK) {
1285                 if (backup) {
1286                         /*
1287                          * Try to restore from our backup.
1288                          */
1289                         (void) rename(bakfile, filename);
1290                 } else {
1291                         /*
1292                          * Either the zone is new, in which case we can delete
1293                          * new.xml, or we're doing a rename, so ditto.
1294                          */
1295                         assert(is_new(handle) || is_renaming(handle));
1296                         (void) unlink(filename);
1297                 }
1298                 return (Z_UPDATING_INDEX);
1299         }
1300 
1301         if (backup)
1302                 (void) unlink(bakfile);
1303 
1304         return (Z_OK);
1305 
1306 err:
1307         (void) unlink(tmpfile);
1308         return (Z_SAVING_FILE);
1309 }
1310 
1311 int
1312 zonecfg_save(zone_dochandle_t handle)
1313 {
1314         char zname[ZONENAME_MAX], path[MAXPATHLEN];
1315         char delpath[MAXPATHLEN];
1316         int err = Z_SAVING_FILE;
1317 
1318         if (zonecfg_check_handle(handle) != Z_OK)
1319                 return (Z_BAD_HANDLE);
1320 
1321         /*
1322          * We don't support saving snapshots or a tree containing a sw
1323          * inventory at this time.
1324          */
1325         if (handle->zone_dh_snapshot || handle->zone_dh_sw_inv)
1326                 return (Z_INVAL);
1327 
1328         if ((err = zonecfg_get_name(handle, zname, sizeof (zname))) != Z_OK)
1329                 return (err);
1330 
1331         if (!config_file_path(zname, path, sizeof (path)))
1332                 return (Z_MISC_FS);
1333 
1334         addcomment(handle, "\n    DO NOT EDIT THIS "
1335             "FILE.  Use zonecfg(1M) instead.\n");
1336 
1337         /*
1338          * Update user_attr first so that it will be older
1339          * than the config file.
1340          */
1341         (void) zonecfg_authorize_users(handle, zname);
1342         err = zonecfg_save_impl(handle, path);
1343 
1344         stripcomments(handle);
1345 
1346         if (err != Z_OK)
1347                 return (err);
1348 
1349         handle->zone_dh_newzone = B_FALSE;
1350 
1351         if (is_renaming(handle)) {
1352                 if (config_file_path(handle->zone_dh_delete_name, delpath,
1353                     sizeof (delpath))) {
1354                         (void) unlink(delpath);
1355                 }
1356                 handle->zone_dh_delete_name[0] = '\0';
1357         }
1358 
1359         return (Z_OK);
1360 }
1361 
1362 int
1363 zonecfg_verify_save(zone_dochandle_t handle, char *filename)
1364 {
1365         boolean_t valid;
1366 
1367         if (zonecfg_check_handle(handle) != Z_OK)
1368                 return (Z_BAD_HANDLE);
1369 
1370         /*
1371          * We do a final validation of the document.  Since the library has
1372          * malfunctioned if it fails to validate, we follow-up with an
1373          * assert() that the doc is valid.
1374          */
1375         VERIFY0(os_dtd_validate(handle->zone_dh_doc, B_FALSE, &valid));
1376         VERIFY(valid == B_TRUE);
1377 
1378         if (xmlSaveFormatFile(filename, handle->zone_dh_doc, 1) <= 0)
1379                 return (Z_SAVING_FILE);
1380 
1381         return (Z_OK);
1382 }
1383 
1384 int
1385 zonecfg_detach_save(zone_dochandle_t handle, uint_t flags)
1386 {
1387         char zname[ZONENAME_MAX];
1388         char path[MAXPATHLEN];
1389         char migpath[MAXPATHLEN];
1390         int err = Z_SAVING_FILE;
1391         boolean_t valid;
1392 
1393         if (zonecfg_check_handle(handle) != Z_OK)
1394                 return (Z_BAD_HANDLE);
1395 
1396         if (flags & ZONE_DRY_RUN) {
1397                 (void) strlcpy(migpath, "-", sizeof (migpath));
1398         } else {
1399                 if ((err = zonecfg_get_name(handle, zname, sizeof (zname)))
1400                     != Z_OK)
1401                         return (err);
1402 
1403                 if ((err = zone_get_zonepath(zname, path, sizeof (path)))
1404                     != Z_OK)
1405                         return (err);
1406 
1407                 if (snprintf(migpath, sizeof (migpath), "%s/%s", path,
1408                     ZONE_DETACHED) >= sizeof (migpath))
1409                         return (Z_NOMEM);
1410         }
1411 
1412         if ((err = operation_prep(handle)) != Z_OK)
1413                 return (err);
1414 
1415         addcomment(handle, "\n    DO NOT EDIT THIS FILE.  "
1416             "Use zonecfg(1M) and zoneadm(1M) attach.\n");
1417 
1418         /*
1419          * We do a final validation of the document.  Since the library has
1420          * malfunctioned if it fails to validate, we follow-up with an
1421          * assert() that the doc is valid.
1422          */
1423         VERIFY0(os_dtd_validate(handle->zone_dh_doc, B_FALSE, &valid));
1424         VERIFY(valid == B_TRUE);
1425 
1426         if (xmlSaveFormatFile(migpath, handle->zone_dh_doc, 1) <= 0)
1427                 return (Z_SAVING_FILE);
1428 
1429         if (!(flags & ZONE_DRY_RUN))
1430                 (void) chmod(migpath, 0644);
1431 
1432         stripcomments(handle);
1433 
1434         handle->zone_dh_newzone = B_FALSE;
1435 
1436         return (Z_OK);
1437 }
1438 
1439 boolean_t
1440 zonecfg_detached(const char *path)
1441 {
1442         char            migpath[MAXPATHLEN];
1443         struct stat     buf;
1444 
1445         if (snprintf(migpath, sizeof (migpath), "%s/%s", path, ZONE_DETACHED) >=
1446             sizeof (migpath))
1447                 return (B_FALSE);
1448 
1449         if (stat(migpath, &buf) != -1)
1450                 return (B_TRUE);
1451 
1452         return (B_FALSE);
1453 }
1454 
1455 void
1456 zonecfg_rm_detached(zone_dochandle_t handle, boolean_t forced)
1457 {
1458         char zname[ZONENAME_MAX];
1459         char path[MAXPATHLEN];
1460         char detached[MAXPATHLEN];
1461         char attached[MAXPATHLEN];
1462 
1463         if (zonecfg_check_handle(handle) != Z_OK)
1464                 return;
1465 
1466         if (zonecfg_get_name(handle, zname, sizeof (zname)) != Z_OK)
1467                 return;
1468 
1469         if (zone_get_zonepath(zname, path, sizeof (path)) != Z_OK)
1470                 return;
1471 
1472         (void) snprintf(detached, sizeof (detached), "%s/%s", path,
1473             ZONE_DETACHED);
1474         (void) snprintf(attached, sizeof (attached), "%s/%s", path,
1475             ATTACH_FORCED);
1476 
1477         if (forced) {
1478                 (void) rename(detached, attached);
1479         } else {
1480                 (void) unlink(attached);
1481                 (void) unlink(detached);
1482         }
1483 }
1484 
1485 /*
1486  * Special case: if access(2) fails with ENOENT, then try again using
1487  * ZONE_CONFIG_ROOT instead of config_file_path(zonename).  This is how we
1488  * work around the case of a config file which has not been created yet:
1489  * the user will need access to the directory so use that as a heuristic.
1490  */
1491 
1492 int
1493 zonecfg_access(const char *zonename, int amode)
1494 {
1495         char path[MAXPATHLEN];
1496 
1497         if (!config_file_path(zonename, path, sizeof (path)))
1498                 return (Z_INVAL);
1499         if (access(path, amode) == 0)
1500                 return (Z_OK);
1501         if (errno == ENOENT) {
1502                 if (snprintf(path, sizeof (path), "%s%s", zonecfg_root,
1503                     ZONE_CONFIG_ROOT) >= sizeof (path))
1504                         return (Z_INVAL);
1505                 if (access(path, amode) == 0)
1506                         return (Z_OK);
1507         }
1508         if (errno == EACCES)
1509                 return (Z_ACCES);
1510         if (errno == EINVAL)
1511                 return (Z_INVAL);
1512         return (Z_MISC_FS);
1513 }
1514 
1515 int
1516 zonecfg_create_snapshot(const char *zonename)
1517 {
1518         zone_dochandle_t handle;
1519         char path[MAXPATHLEN], zonepath[MAXPATHLEN], rpath[MAXPATHLEN];
1520         int error = Z_OK, res;
1521 
1522         if ((handle = zonecfg_init_handle()) == NULL) {
1523                 return (Z_NOMEM);
1524         }
1525 
1526         handle->zone_dh_newzone = B_TRUE;
1527         handle->zone_dh_snapshot = B_TRUE;
1528 
1529         if ((error = zonecfg_get_handle(zonename, handle)) != Z_OK)
1530                 goto out;
1531         if ((error = operation_prep(handle)) != Z_OK)
1532                 goto out;
1533         error = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath));
1534         if (error != Z_OK)
1535                 goto out;
1536         if ((res = resolvepath(zonepath, rpath, sizeof (rpath))) == -1) {
1537                 error = Z_RESOLVED_PATH;
1538                 goto out;
1539         }
1540         /*
1541          * If the resolved path is not the same as the original path, then
1542          * save the resolved path in the snapshot, thus preventing any
1543          * potential problems down the line when zoneadmd goes to unmount
1544          * file systems and depends on initial string matches with resolved
1545          * paths.
1546          */
1547         rpath[res] = '\0';
1548         if (strcmp(zonepath, rpath) != 0) {
1549                 if ((error = zonecfg_set_zonepath(handle, rpath)) != Z_OK)
1550                         goto out;
1551         }
1552         if (snprintf(path, sizeof (path), "%s%s", zonecfg_root,
1553             ZONE_SNAPSHOT_ROOT) >= sizeof (path)) {
1554                 error = Z_MISC_FS;
1555                 goto out;
1556         }
1557         if ((mkdir(path, S_IRWXU) == -1) && (errno != EEXIST)) {
1558                 error = Z_MISC_FS;
1559                 goto out;
1560         }
1561 
1562         if (!snap_file_path(zonename, path, sizeof (path))) {
1563                 error = Z_MISC_FS;
1564                 goto out;
1565         }
1566 
1567         addcomment(handle, "\n    DO NOT EDIT THIS FILE.  "
1568             "It is a snapshot of running zone state.\n");
1569 
1570         error = zonecfg_save_impl(handle, path);
1571 
1572         stripcomments(handle);
1573 
1574 out:
1575         zonecfg_fini_handle(handle);
1576         return (error);
1577 }
1578 
1579 int
1580 zonecfg_get_iptype(zone_dochandle_t handle, zone_iptype_t *iptypep)
1581 {
1582         char property[10]; /* 10 is big enough for "shared"/"exclusive" */
1583         int err;
1584 
1585         err = getrootattr(handle, DTD_ATTR_IPTYPE, property, sizeof (property));
1586         if (err == Z_BAD_PROPERTY) {
1587                 /* Return default value */
1588                 *iptypep = ZS_SHARED;
1589                 return (Z_OK);
1590         } else if (err != Z_OK) {
1591                 return (err);
1592         }
1593 
1594         if (strlen(property) == 0 ||
1595             strcmp(property, "shared") == 0)
1596                 *iptypep = ZS_SHARED;
1597         else if (strcmp(property, "exclusive") == 0)
1598                 *iptypep = ZS_EXCLUSIVE;
1599         else
1600                 return (Z_INVAL);
1601 
1602         return (Z_OK);
1603 }
1604 
1605 int
1606 zonecfg_set_iptype(zone_dochandle_t handle, zone_iptype_t iptype)
1607 {
1608         xmlNodePtr cur;
1609 
1610         if (handle == NULL)
1611                 return (Z_INVAL);
1612 
1613         cur = xmlDocGetRootElement(handle->zone_dh_doc);
1614         if (cur == NULL) {
1615                 return (Z_EMPTY_DOCUMENT);
1616         }
1617 
1618         if (xmlStrcmp(cur->name, DTD_ELEM_ZONE) != 0) {
1619                 return (Z_WRONG_DOC_TYPE);
1620         }
1621         switch (iptype) {
1622         case ZS_SHARED:
1623                 /*
1624                  * Since "shared" is the default, we don't write it to the
1625                  * configuration file, so that it's easier to migrate those
1626                  * zones elsewhere, eg., to systems which are not IP-Instances
1627                  * aware.
1628                  * xmlUnsetProp only fails when the attribute doesn't exist,
1629                  * which we don't care.
1630                  */
1631                 (void) xmlUnsetProp(cur, DTD_ATTR_IPTYPE);
1632                 break;
1633         case ZS_EXCLUSIVE:
1634                 if (xmlSetProp(cur, DTD_ATTR_IPTYPE,
1635                     (const xmlChar *) "exclusive") == NULL)
1636                         return (Z_INVAL);
1637                 break;
1638         }
1639         return (Z_OK);
1640 }
1641 
1642 static int
1643 newprop(xmlNodePtr node, const xmlChar *attrname, char *src)
1644 {
1645         xmlAttrPtr newattr;
1646 
1647         newattr = xmlNewProp(node, attrname, (xmlChar *)src);
1648         if (newattr == NULL) {
1649                 xmlUnlinkNode(node);
1650                 xmlFreeNode(node);
1651                 return (Z_BAD_PROPERTY);
1652         }
1653         return (Z_OK);
1654 }
1655 
1656 static int
1657 zonecfg_add_filesystem_core(zone_dochandle_t handle, struct zone_fstab *tabptr)
1658 {
1659         xmlNodePtr newnode, cur = handle->zone_dh_cur, options_node;
1660         zone_fsopt_t *ptr;
1661         int err;
1662 
1663         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_FS, NULL);
1664         if ((err = newprop(newnode, DTD_ATTR_SPECIAL,
1665             tabptr->zone_fs_special)) != Z_OK)
1666                 return (err);
1667         if (tabptr->zone_fs_raw[0] != '\0' &&
1668             (err = newprop(newnode, DTD_ATTR_RAW, tabptr->zone_fs_raw)) != Z_OK)
1669                 return (err);
1670         if ((err = newprop(newnode, DTD_ATTR_DIR, tabptr->zone_fs_dir)) != Z_OK)
1671                 return (err);
1672         if ((err = newprop(newnode, DTD_ATTR_TYPE,
1673             tabptr->zone_fs_type)) != Z_OK)
1674                 return (err);
1675         if (tabptr->zone_fs_options != NULL) {
1676                 for (ptr = tabptr->zone_fs_options; ptr != NULL;
1677                     ptr = ptr->zone_fsopt_next) {
1678                         options_node = xmlNewTextChild(newnode, NULL,
1679                             DTD_ELEM_FSOPTION, NULL);
1680                         if ((err = newprop(options_node, DTD_ATTR_NAME,
1681                             ptr->zone_fsopt_opt)) != Z_OK)
1682                                 return (err);
1683                 }
1684         }
1685         return (Z_OK);
1686 }
1687 
1688 int
1689 zonecfg_add_filesystem(zone_dochandle_t handle, struct zone_fstab *tabptr)
1690 {
1691         int err;
1692 
1693         if (tabptr == NULL)
1694                 return (Z_INVAL);
1695 
1696         if ((err = operation_prep(handle)) != Z_OK)
1697                 return (err);
1698 
1699         if ((err = zonecfg_add_filesystem_core(handle, tabptr)) != Z_OK)
1700                 return (err);
1701 
1702         return (Z_OK);
1703 }
1704 
1705 int
1706 zonecfg_add_fs_option(struct zone_fstab *tabptr, char *option)
1707 {
1708         zone_fsopt_t *last, *old, *new;
1709 
1710         last = tabptr->zone_fs_options;
1711         for (old = last; old != NULL; old = old->zone_fsopt_next)
1712                 last = old;     /* walk to the end of the list */
1713         new = (zone_fsopt_t *)malloc(sizeof (zone_fsopt_t));
1714         if (new == NULL)
1715                 return (Z_NOMEM);
1716         (void) strlcpy(new->zone_fsopt_opt, option,
1717             sizeof (new->zone_fsopt_opt));
1718         new->zone_fsopt_next = NULL;
1719         if (last == NULL)
1720                 tabptr->zone_fs_options = new;
1721         else
1722                 last->zone_fsopt_next = new;
1723         return (Z_OK);
1724 }
1725 
1726 int
1727 zonecfg_remove_fs_option(struct zone_fstab *tabptr, char *option)
1728 {
1729         zone_fsopt_t *last, *this, *next;
1730 
1731         last = tabptr->zone_fs_options;
1732         for (this = last; this != NULL; this = this->zone_fsopt_next) {
1733                 if (strcmp(this->zone_fsopt_opt, option) == 0) {
1734                         next = this->zone_fsopt_next;
1735                         if (this == tabptr->zone_fs_options)
1736                                 tabptr->zone_fs_options = next;
1737                         else
1738                                 last->zone_fsopt_next = next;
1739                         free(this);
1740                         return (Z_OK);
1741                 } else
1742                         last = this;
1743         }
1744         return (Z_NO_PROPERTY_ID);
1745 }
1746 
1747 void
1748 zonecfg_free_fs_option_list(zone_fsopt_t *list)
1749 {
1750         zone_fsopt_t *this, *next;
1751 
1752         for (this = list; this != NULL; this = next) {
1753                 next = this->zone_fsopt_next;
1754                 free(this);
1755         }
1756 }
1757 
1758 void
1759 zonecfg_free_rctl_value_list(struct zone_rctlvaltab *valtab)
1760 {
1761         if (valtab == NULL)
1762                 return;
1763         zonecfg_free_rctl_value_list(valtab->zone_rctlval_next);
1764         free(valtab);
1765 }
1766 
1767 static boolean_t
1768 match_prop(xmlNodePtr cur, const xmlChar *attr, char *user_prop)
1769 {
1770         xmlChar *gotten_prop;
1771         int prop_result;
1772 
1773         gotten_prop = xmlGetProp(cur, attr);
1774         if (gotten_prop == NULL)        /* shouldn't happen */
1775                 return (B_FALSE);
1776         prop_result = xmlStrcmp(gotten_prop, (const xmlChar *) user_prop);
1777         xmlFree(gotten_prop);
1778         return ((prop_result == 0));    /* empty strings will match */
1779 }
1780 
1781 static int
1782 zonecfg_delete_filesystem_core(zone_dochandle_t handle,
1783     struct zone_fstab *tabptr)
1784 {
1785         xmlNodePtr cur = handle->zone_dh_cur;
1786         boolean_t dir_match, spec_match, raw_match, type_match;
1787 
1788         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
1789                 if (xmlStrcmp(cur->name, DTD_ELEM_FS))
1790                         continue;
1791                 dir_match = match_prop(cur, DTD_ATTR_DIR, tabptr->zone_fs_dir);
1792                 spec_match = match_prop(cur, DTD_ATTR_SPECIAL,
1793                     tabptr->zone_fs_special);
1794                 raw_match = match_prop(cur, DTD_ATTR_RAW,
1795                     tabptr->zone_fs_raw);
1796                 type_match = match_prop(cur, DTD_ATTR_TYPE,
1797                     tabptr->zone_fs_type);
1798                 if (dir_match && spec_match && raw_match && type_match) {
1799                         xmlUnlinkNode(cur);
1800                         xmlFreeNode(cur);
1801                         return (Z_OK);
1802                 }
1803         }
1804         return (Z_NO_RESOURCE_ID);
1805 }
1806 
1807 int
1808 zonecfg_delete_filesystem(zone_dochandle_t handle, struct zone_fstab *tabptr)
1809 {
1810         int err;
1811 
1812         if (tabptr == NULL)
1813                 return (Z_INVAL);
1814 
1815         if ((err = operation_prep(handle)) != Z_OK)
1816                 return (err);
1817 
1818         if ((err = zonecfg_delete_filesystem_core(handle, tabptr)) != Z_OK)
1819                 return (err);
1820 
1821         return (Z_OK);
1822 }
1823 
1824 int
1825 zonecfg_modify_filesystem(
1826         zone_dochandle_t handle,
1827         struct zone_fstab *oldtabptr,
1828         struct zone_fstab *newtabptr)
1829 {
1830         int err;
1831 
1832         if (oldtabptr == NULL || newtabptr == NULL)
1833                 return (Z_INVAL);
1834 
1835         if ((err = operation_prep(handle)) != Z_OK)
1836                 return (err);
1837 
1838         if ((err = zonecfg_delete_filesystem_core(handle, oldtabptr)) != Z_OK)
1839                 return (err);
1840 
1841         if ((err = zonecfg_add_filesystem_core(handle, newtabptr)) != Z_OK)
1842                 return (err);
1843 
1844         return (Z_OK);
1845 }
1846 
1847 int
1848 zonecfg_lookup_filesystem(
1849         zone_dochandle_t handle,
1850         struct zone_fstab *tabptr)
1851 {
1852         xmlNodePtr cur, options, firstmatch;
1853         int err;
1854         char dirname[MAXPATHLEN], special[MAXPATHLEN], raw[MAXPATHLEN];
1855         char type[FSTYPSZ];
1856         char options_str[MAX_MNTOPT_STR];
1857 
1858         if (tabptr == NULL)
1859                 return (Z_INVAL);
1860 
1861         if ((err = operation_prep(handle)) != Z_OK)
1862                 return (err);
1863 
1864         /*
1865          * Walk the list of children looking for matches on any properties
1866          * specified in the fstab parameter.  If more than one resource
1867          * matches, we return Z_INSUFFICIENT_SPEC; if none match, we return
1868          * Z_NO_RESOURCE_ID.
1869          */
1870         cur = handle->zone_dh_cur;
1871         firstmatch = NULL;
1872         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
1873                 if (xmlStrcmp(cur->name, DTD_ELEM_FS))
1874                         continue;
1875                 if (strlen(tabptr->zone_fs_dir) > 0) {
1876                         if ((fetchprop(cur, DTD_ATTR_DIR, dirname,
1877                             sizeof (dirname)) == Z_OK) &&
1878                             (strcmp(tabptr->zone_fs_dir, dirname) == 0)) {
1879                                 if (firstmatch == NULL)
1880                                         firstmatch = cur;
1881                                 else
1882                                         return (Z_INSUFFICIENT_SPEC);
1883                         }
1884                 }
1885                 if (strlen(tabptr->zone_fs_special) > 0) {
1886                         if ((fetchprop(cur, DTD_ATTR_SPECIAL, special,
1887                             sizeof (special)) == Z_OK)) {
1888                                 if (strcmp(tabptr->zone_fs_special,
1889                                     special) == 0) {
1890                                         if (firstmatch == NULL)
1891                                                 firstmatch = cur;
1892                                         else if (firstmatch != cur)
1893                                                 return (Z_INSUFFICIENT_SPEC);
1894                                 } else {
1895                                         /*
1896                                          * If another property matched but this
1897                                          * one doesn't then reset firstmatch.
1898                                          */
1899                                         if (firstmatch == cur)
1900                                                 firstmatch = NULL;
1901                                 }
1902                         }
1903                 }
1904                 if (strlen(tabptr->zone_fs_raw) > 0) {
1905                         if ((fetchprop(cur, DTD_ATTR_RAW, raw,
1906                             sizeof (raw)) == Z_OK)) {
1907                                 if (strcmp(tabptr->zone_fs_raw, raw) == 0) {
1908                                         if (firstmatch == NULL)
1909                                                 firstmatch = cur;
1910                                         else if (firstmatch != cur)
1911                                                 return (Z_INSUFFICIENT_SPEC);
1912                                 } else {
1913                                         /*
1914                                          * If another property matched but this
1915                                          * one doesn't then reset firstmatch.
1916                                          */
1917                                         if (firstmatch == cur)
1918                                                 firstmatch = NULL;
1919                                 }
1920                         }
1921                 }
1922                 if (strlen(tabptr->zone_fs_type) > 0) {
1923                         if ((fetchprop(cur, DTD_ATTR_TYPE, type,
1924                             sizeof (type)) == Z_OK)) {
1925                                 if (strcmp(tabptr->zone_fs_type, type) == 0) {
1926                                         if (firstmatch == NULL)
1927                                                 firstmatch = cur;
1928                                         else if (firstmatch != cur)
1929                                                 return (Z_INSUFFICIENT_SPEC);
1930                                 } else {
1931                                         /*
1932                                          * If another property matched but this
1933                                          * one doesn't then reset firstmatch.
1934                                          */
1935                                         if (firstmatch == cur)
1936                                                 firstmatch = NULL;
1937                                 }
1938                         }
1939                 }
1940         }
1941 
1942         if (firstmatch == NULL)
1943                 return (Z_NO_RESOURCE_ID);
1944 
1945         cur = firstmatch;
1946 
1947         if ((err = fetchprop(cur, DTD_ATTR_DIR, tabptr->zone_fs_dir,
1948             sizeof (tabptr->zone_fs_dir))) != Z_OK)
1949                 return (err);
1950 
1951         if ((err = fetchprop(cur, DTD_ATTR_SPECIAL, tabptr->zone_fs_special,
1952             sizeof (tabptr->zone_fs_special))) != Z_OK)
1953                 return (err);
1954 
1955         if ((err = fetchprop(cur, DTD_ATTR_RAW, tabptr->zone_fs_raw,
1956             sizeof (tabptr->zone_fs_raw))) != Z_OK)
1957                 return (err);
1958 
1959         if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_fs_type,
1960             sizeof (tabptr->zone_fs_type))) != Z_OK)
1961                 return (err);
1962 
1963         /* options are optional */
1964         tabptr->zone_fs_options = NULL;
1965         for (options = cur->xmlChildrenNode; options != NULL;
1966             options = options->next) {
1967                 if ((fetchprop(options, DTD_ATTR_NAME, options_str,
1968                     sizeof (options_str)) != Z_OK))
1969                         break;
1970                 if (zonecfg_add_fs_option(tabptr, options_str) != Z_OK)
1971                         break;
1972         }
1973         return (Z_OK);
1974 }
1975 
1976 /*
1977  * Compare two IP addresses in string form.  Allow for the possibility that
1978  * one might have "/<prefix-length>" at the end: allow a match on just the
1979  * IP address (or host name) part.
1980  */
1981 
1982 boolean_t
1983 zonecfg_same_net_address(char *a1, char *a2)
1984 {
1985         char *slashp, *slashp1, *slashp2;
1986         int result;
1987 
1988         if (strcmp(a1, a2) == 0)
1989                 return (B_TRUE);
1990 
1991         /*
1992          * If neither has a slash or both do, they need to match to be
1993          * considered the same, but they did not match above, so fail.
1994          */
1995         slashp1 = strchr(a1, '/');
1996         slashp2 = strchr(a2, '/');
1997         if ((slashp1 == NULL && slashp2 == NULL) ||
1998             (slashp1 != NULL && slashp2 != NULL))
1999                 return (B_FALSE);
2000 
2001         /*
2002          * Only one had a slash: pick that one, zero out the slash, compare
2003          * the "address only" strings, restore the slash, and return the
2004          * result of the comparison.
2005          */
2006         slashp = (slashp1 == NULL) ? slashp2 : slashp1;
2007         *slashp = '\0';
2008         result = strcmp(a1, a2);
2009         *slashp = '/';
2010         return ((result == 0));
2011 }
2012 
2013 int
2014 zonecfg_valid_net_address(char *address, struct lifreq *lifr)
2015 {
2016         struct sockaddr_in *sin4;
2017         struct sockaddr_in6 *sin6;
2018         struct addrinfo hints, *result;
2019         char *slashp = strchr(address, '/');
2020 
2021         bzero(lifr, sizeof (struct lifreq));
2022         sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
2023         sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
2024         if (slashp != NULL)
2025                 *slashp = '\0';
2026         if (inet_pton(AF_INET, address, &sin4->sin_addr) == 1) {
2027                 sin4->sin_family = AF_INET;
2028         } else if (inet_pton(AF_INET6, address, &sin6->sin6_addr) == 1) {
2029                 if (slashp == NULL)
2030                         return (Z_IPV6_ADDR_PREFIX_LEN);
2031                 sin6->sin6_family = AF_INET6;
2032         } else {
2033                 /* "address" may be a host name */
2034                 (void) memset(&hints, 0, sizeof (hints));
2035                 hints.ai_family = PF_INET;
2036                 if (getaddrinfo(address, NULL, &hints, &result) != 0)
2037                         return (Z_BOGUS_ADDRESS);
2038                 sin4->sin_family = result->ai_family;
2039 
2040                 (void) memcpy(&sin4->sin_addr,
2041                     /* LINTED E_BAD_PTR_CAST_ALIGN */
2042                     &((struct sockaddr_in *)result->ai_addr)->sin_addr,
2043                     sizeof (struct in_addr));
2044 
2045                 freeaddrinfo(result);
2046         }
2047         return (Z_OK);
2048 }
2049 
2050 boolean_t
2051 zonecfg_ifname_exists(sa_family_t af, char *ifname)
2052 {
2053         struct lifreq lifr;
2054         int so;
2055         int save_errno;
2056 
2057         (void) memset(&lifr, 0, sizeof (lifr));
2058         (void) strlcpy(lifr.lifr_name, ifname, sizeof (lifr.lifr_name));
2059         lifr.lifr_addr.ss_family = af;
2060         if ((so = socket(af, SOCK_DGRAM, 0)) < 0) {
2061                 /* Odd - can't tell if the ifname exists */
2062                 return (B_FALSE);
2063         }
2064         if (ioctl(so, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2065                 save_errno = errno;
2066                 (void) close(so);
2067                 errno = save_errno;
2068                 return (B_FALSE);
2069         }
2070         (void) close(so);
2071         return (B_TRUE);
2072 }
2073 
2074 /*
2075  * Determines whether there is a net resource with the physical interface, IP
2076  * address, and default router specified by 'tabptr' in the zone configuration
2077  * to which 'handle' refers.  'tabptr' must have an interface, an address, a
2078  * default router, or a combination of the three.  This function returns Z_OK
2079  * iff there is exactly one net resource matching the query specified by
2080  * 'tabptr'.  The function returns Z_INSUFFICIENT_SPEC if there are multiple
2081  * matches or 'tabptr' does not specify a physical interface, address, or
2082  * default router.  The function returns Z_NO_RESOURCE_ID if are no matches.
2083  *
2084  * Errors might also be returned if the entry that exactly matches the
2085  * query lacks critical network resource information.
2086  *
2087  * If there is a single match, then the matching entry's physical interface, IP
2088  * address, and default router information are stored in 'tabptr'.
2089  */
2090 int
2091 zonecfg_lookup_nwif(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2092 {
2093         xmlNodePtr cur;
2094         xmlNodePtr firstmatch;
2095         int err;
2096         char address[INET6_ADDRSTRLEN];
2097         char physical[LIFNAMSIZ];
2098         size_t addrspec;                /* nonzero if tabptr has IP addr */
2099         size_t physspec;                /* nonzero if tabptr has interface */
2100         size_t defrouterspec;           /* nonzero if tabptr has def. router */
2101         size_t allowed_addrspec;
2102         zone_iptype_t iptype;
2103 
2104         if (tabptr == NULL)
2105                 return (Z_INVAL);
2106 
2107         /*
2108          * Determine the fields that will be searched.  There must be at least
2109          * one.
2110          *
2111          * zone_nwif_address, zone_nwif_physical, and zone_nwif_defrouter are
2112          * arrays, so no NULL checks are necessary.
2113          */
2114         addrspec = strlen(tabptr->zone_nwif_address);
2115         physspec = strlen(tabptr->zone_nwif_physical);
2116         defrouterspec = strlen(tabptr->zone_nwif_defrouter);
2117         allowed_addrspec = strlen(tabptr->zone_nwif_allowed_address);
2118         if (addrspec != 0 && allowed_addrspec != 0)
2119                 return (Z_INVAL); /* can't specify both */
2120         if (addrspec == 0 && physspec == 0 && defrouterspec == 0 &&
2121             allowed_addrspec == 0)
2122                 return (Z_INSUFFICIENT_SPEC);
2123 
2124         if ((err = operation_prep(handle)) != Z_OK)
2125                 return (err);
2126 
2127         if ((err = zonecfg_get_iptype(handle, &iptype)) != Z_OK)
2128                 return (err);
2129         /*
2130          * Iterate over the configuration's elements and look for net elements
2131          * that match the query.
2132          */
2133         firstmatch = NULL;
2134         cur = handle->zone_dh_cur;
2135         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2136                 /* Skip non-net elements */
2137                 if (xmlStrcmp(cur->name, DTD_ELEM_NET))
2138                         continue;
2139 
2140                 /*
2141                  * If any relevant fields don't match the query, then skip
2142                  * the current net element.
2143                  */
2144                 if (physspec != 0 && (fetchprop(cur, DTD_ATTR_PHYSICAL,
2145                     physical, sizeof (physical)) != Z_OK ||
2146                     strcmp(tabptr->zone_nwif_physical, physical) != 0))
2147                         continue;
2148                 if (iptype == ZS_SHARED && addrspec != 0 &&
2149                     (fetchprop(cur, DTD_ATTR_ADDRESS, address,
2150                     sizeof (address)) != Z_OK ||
2151                     !zonecfg_same_net_address(tabptr->zone_nwif_address,
2152                     address)))
2153                         continue;
2154                 if (iptype == ZS_EXCLUSIVE && allowed_addrspec != 0 &&
2155                     (fetchprop(cur, DTD_ATTR_ALLOWED_ADDRESS, address,
2156                     sizeof (address)) != Z_OK ||
2157                     !zonecfg_same_net_address(tabptr->zone_nwif_allowed_address,
2158                     address)))
2159                         continue;
2160                 if (defrouterspec != 0 && (fetchprop(cur, DTD_ATTR_DEFROUTER,
2161                     address, sizeof (address)) != Z_OK ||
2162                     !zonecfg_same_net_address(tabptr->zone_nwif_defrouter,
2163                     address)))
2164                         continue;
2165 
2166                 /*
2167                  * The current net element matches the query.  Select it if
2168                  * it's the first match; otherwise, abort the search.
2169                  */
2170                 if (firstmatch == NULL)
2171                         firstmatch = cur;
2172                 else
2173                         return (Z_INSUFFICIENT_SPEC);
2174         }
2175         if (firstmatch == NULL)
2176                 return (Z_NO_RESOURCE_ID);
2177 
2178         cur = firstmatch;
2179 
2180         if ((err = fetchprop(cur, DTD_ATTR_PHYSICAL, tabptr->zone_nwif_physical,
2181             sizeof (tabptr->zone_nwif_physical))) != Z_OK)
2182                 return (err);
2183 
2184         if (iptype == ZS_SHARED &&
2185             (err = fetchprop(cur, DTD_ATTR_ADDRESS, tabptr->zone_nwif_address,
2186             sizeof (tabptr->zone_nwif_address))) != Z_OK)
2187                 return (err);
2188 
2189         if (iptype == ZS_EXCLUSIVE &&
2190             (err = fetchprop(cur, DTD_ATTR_ALLOWED_ADDRESS,
2191             tabptr->zone_nwif_allowed_address,
2192             sizeof (tabptr->zone_nwif_allowed_address))) != Z_OK)
2193                 return (err);
2194 
2195         if ((err = fetchprop(cur, DTD_ATTR_DEFROUTER,
2196             tabptr->zone_nwif_defrouter,
2197             sizeof (tabptr->zone_nwif_defrouter))) != Z_OK)
2198                 return (err);
2199 
2200         return (Z_OK);
2201 }
2202 
2203 static int
2204 zonecfg_add_nwif_core(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2205 {
2206         xmlNodePtr newnode, cur = handle->zone_dh_cur;
2207         int err;
2208 
2209         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_NET, NULL);
2210         if (strlen(tabptr->zone_nwif_address) > 0 &&
2211             (err = newprop(newnode, DTD_ATTR_ADDRESS,
2212             tabptr->zone_nwif_address)) != Z_OK)
2213                 return (err);
2214         if (strlen(tabptr->zone_nwif_allowed_address) > 0 &&
2215             (err = newprop(newnode, DTD_ATTR_ALLOWED_ADDRESS,
2216             tabptr->zone_nwif_allowed_address)) != Z_OK)
2217                 return (err);
2218         if ((err = newprop(newnode, DTD_ATTR_PHYSICAL,
2219             tabptr->zone_nwif_physical)) != Z_OK)
2220                 return (err);
2221         /*
2222          * Do not add this property when it is not set, for backwards
2223          * compatibility and because it is optional.
2224          */
2225         if ((strlen(tabptr->zone_nwif_defrouter) > 0) &&
2226             ((err = newprop(newnode, DTD_ATTR_DEFROUTER,
2227             tabptr->zone_nwif_defrouter)) != Z_OK))
2228                 return (err);
2229         return (Z_OK);
2230 }
2231 
2232 int
2233 zonecfg_add_nwif(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2234 {
2235         int err;
2236 
2237         if (tabptr == NULL)
2238                 return (Z_INVAL);
2239 
2240         if ((err = operation_prep(handle)) != Z_OK)
2241                 return (err);
2242 
2243         if ((err = zonecfg_add_nwif_core(handle, tabptr)) != Z_OK)
2244                 return (err);
2245 
2246         return (Z_OK);
2247 }
2248 
2249 static int
2250 zonecfg_delete_nwif_core(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2251 {
2252         xmlNodePtr cur = handle->zone_dh_cur;
2253         boolean_t addr_match, phys_match, allowed_addr_match;
2254 
2255         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2256                 if (xmlStrcmp(cur->name, DTD_ELEM_NET))
2257                         continue;
2258 
2259                 addr_match = match_prop(cur, DTD_ATTR_ADDRESS,
2260                     tabptr->zone_nwif_address);
2261                 allowed_addr_match = match_prop(cur, DTD_ATTR_ALLOWED_ADDRESS,
2262                     tabptr->zone_nwif_allowed_address);
2263                 phys_match = match_prop(cur, DTD_ATTR_PHYSICAL,
2264                     tabptr->zone_nwif_physical);
2265 
2266                 if (addr_match && allowed_addr_match && phys_match) {
2267                         xmlUnlinkNode(cur);
2268                         xmlFreeNode(cur);
2269                         return (Z_OK);
2270                 }
2271         }
2272         return (Z_NO_RESOURCE_ID);
2273 }
2274 
2275 int
2276 zonecfg_delete_nwif(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2277 {
2278         int err;
2279 
2280         if (tabptr == NULL)
2281                 return (Z_INVAL);
2282 
2283         if ((err = operation_prep(handle)) != Z_OK)
2284                 return (err);
2285 
2286         if ((err = zonecfg_delete_nwif_core(handle, tabptr)) != Z_OK)
2287                 return (err);
2288 
2289         return (Z_OK);
2290 }
2291 
2292 int
2293 zonecfg_modify_nwif(
2294         zone_dochandle_t handle,
2295         struct zone_nwiftab *oldtabptr,
2296         struct zone_nwiftab *newtabptr)
2297 {
2298         int err;
2299 
2300         if (oldtabptr == NULL || newtabptr == NULL)
2301                 return (Z_INVAL);
2302 
2303         if ((err = operation_prep(handle)) != Z_OK)
2304                 return (err);
2305 
2306         if ((err = zonecfg_delete_nwif_core(handle, oldtabptr)) != Z_OK)
2307                 return (err);
2308 
2309         if ((err = zonecfg_add_nwif_core(handle, newtabptr)) != Z_OK)
2310                 return (err);
2311 
2312         return (Z_OK);
2313 }
2314 
2315 /*
2316  * Must be a comma-separated list of alpha-numeric file system names.
2317  */
2318 static int
2319 zonecfg_valid_fs_allowed(const char *fsallowedp)
2320 {
2321         char tmp[ZONE_FS_ALLOWED_MAX];
2322         char *cp = tmp;
2323         char *p;
2324 
2325         if (strlen(fsallowedp) > ZONE_FS_ALLOWED_MAX)
2326                 return (Z_TOO_BIG);
2327 
2328         (void) strlcpy(tmp, fsallowedp, sizeof (tmp));
2329 
2330         while (*cp != '\0') {
2331                 p = cp;
2332                 while (*p != '\0' && *p != ',') {
2333                         if (!isalnum(*p) && *p != '-')
2334                                 return (Z_INVALID_PROPERTY);
2335                         p++;
2336                 }
2337 
2338                 if (*p == ',') {
2339                         if (p == cp)
2340                                 return (Z_INVALID_PROPERTY);
2341 
2342                         p++;
2343 
2344                         if (*p == '\0')
2345                                 return (Z_INVALID_PROPERTY);
2346                 }
2347 
2348                 cp = p;
2349         }
2350 
2351         return (Z_OK);
2352 }
2353 
2354 int
2355 zonecfg_get_fs_allowed(zone_dochandle_t handle, char *bufp, size_t buflen)
2356 {
2357         int err;
2358 
2359         if ((err = getrootattr(handle, DTD_ATTR_FS_ALLOWED,
2360             bufp, buflen)) != Z_OK)
2361                 return (err);
2362         if (bufp[0] == '\0')
2363                 return (Z_BAD_PROPERTY);
2364         return (zonecfg_valid_fs_allowed(bufp));
2365 }
2366 
2367 int
2368 zonecfg_set_fs_allowed(zone_dochandle_t handle, const char *bufp)
2369 {
2370         int err;
2371 
2372         if (bufp == NULL || (err = zonecfg_valid_fs_allowed(bufp)) == Z_OK)
2373                 return (setrootattr(handle, DTD_ATTR_FS_ALLOWED, bufp));
2374         return (err);
2375 }
2376 
2377 /*
2378  * Determines if the specified string is a valid hostid string.  This function
2379  * returns Z_OK if the string is a valid hostid string.  It returns Z_INVAL if
2380  * 'hostidp' is NULL, Z_TOO_BIG if 'hostidp' refers to a string buffer
2381  * containing a hex string with more than 8 digits, and Z_INVALID_PROPERTY if
2382  * the string has an invalid format.
2383  */
2384 static int
2385 zonecfg_valid_hostid(const char *hostidp)
2386 {
2387         char *currentp;
2388         u_longlong_t hostidval;
2389         size_t len;
2390 
2391         if (hostidp == NULL)
2392                 return (Z_INVAL);
2393 
2394         /* Empty strings and strings with whitespace are invalid. */
2395         if (*hostidp == '\0')
2396                 return (Z_INVALID_PROPERTY);
2397         for (currentp = (char *)hostidp; *currentp != '\0'; ++currentp) {
2398                 if (isspace(*currentp))
2399                         return (Z_INVALID_PROPERTY);
2400         }
2401         len = (size_t)(currentp - hostidp);
2402 
2403         /*
2404          * The caller might pass a hostid that is larger than the maximum
2405          * unsigned 32-bit integral value.  Check for this!  Also, make sure
2406          * that the whole string is converted (this helps us find illegal
2407          * characters) and that the whole string fits within a buffer of size
2408          * HW_HOSTID_LEN.
2409          */
2410         currentp = (char *)hostidp;
2411         if (strncmp(hostidp, "0x", 2) == 0 || strncmp(hostidp, "0X", 2) == 0)
2412                 currentp += 2;
2413         hostidval = strtoull(currentp, &currentp, 16);
2414         if ((size_t)(currentp - hostidp) >= HW_HOSTID_LEN)
2415                 return (Z_TOO_BIG);
2416         if (hostidval > UINT_MAX || hostidval == HW_INVALID_HOSTID ||
2417             currentp != hostidp + len)
2418                 return (Z_INVALID_PROPERTY);
2419         return (Z_OK);
2420 }
2421 
2422 /*
2423  * Gets the zone hostid string stored in the specified zone configuration
2424  * document.  This function returns Z_OK on success.  Z_BAD_PROPERTY is returned
2425  * if the config file doesn't specify a hostid or if the hostid is blank.
2426  *
2427  * Note that buflen should be at least HW_HOSTID_LEN.
2428  */
2429 int
2430 zonecfg_get_hostid(zone_dochandle_t handle, char *bufp, size_t buflen)
2431 {
2432         int err;
2433 
2434         if ((err = getrootattr(handle, DTD_ATTR_HOSTID, bufp, buflen)) != Z_OK)
2435                 return (err);
2436         if (bufp[0] == '\0')
2437                 return (Z_BAD_PROPERTY);
2438         return (zonecfg_valid_hostid(bufp));
2439 }
2440 
2441 /*
2442  * Sets the hostid string in the specified zone config document to the given
2443  * string value.  If 'hostidp' is NULL, then the config document's hostid
2444  * attribute is cleared.  Non-NULL hostids are validated.  This function returns
2445  * Z_OK on success.  Any other return value indicates failure.
2446  */
2447 int
2448 zonecfg_set_hostid(zone_dochandle_t handle, const char *hostidp)
2449 {
2450         int err;
2451 
2452         /*
2453          * A NULL hostid string is interpreted as a request to clear the
2454          * hostid.
2455          */
2456         if (hostidp == NULL || (err = zonecfg_valid_hostid(hostidp)) == Z_OK)
2457                 return (setrootattr(handle, DTD_ATTR_HOSTID, hostidp));
2458         return (err);
2459 }
2460 
2461 int
2462 zonecfg_lookup_dev(zone_dochandle_t handle, struct zone_devtab *tabptr)
2463 {
2464         xmlNodePtr cur, firstmatch;
2465         int err;
2466         char match[MAXPATHLEN];
2467 
2468         if (tabptr == NULL)
2469                 return (Z_INVAL);
2470 
2471         if ((err = operation_prep(handle)) != Z_OK)
2472                 return (err);
2473 
2474         cur = handle->zone_dh_cur;
2475         firstmatch = NULL;
2476         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2477                 if (xmlStrcmp(cur->name, DTD_ELEM_DEVICE))
2478                         continue;
2479                 if (strlen(tabptr->zone_dev_match) == 0)
2480                         continue;
2481 
2482                 if ((fetchprop(cur, DTD_ATTR_MATCH, match,
2483                     sizeof (match)) == Z_OK)) {
2484                         if (strcmp(tabptr->zone_dev_match,
2485                             match) == 0) {
2486                                 if (firstmatch == NULL)
2487                                         firstmatch = cur;
2488                                 else if (firstmatch != cur)
2489                                         return (Z_INSUFFICIENT_SPEC);
2490                         } else {
2491                                 /*
2492                                  * If another property matched but this
2493                                  * one doesn't then reset firstmatch.
2494                                  */
2495                                 if (firstmatch == cur)
2496                                         firstmatch = NULL;
2497                         }
2498                 }
2499         }
2500         if (firstmatch == NULL)
2501                 return (Z_NO_RESOURCE_ID);
2502 
2503         cur = firstmatch;
2504 
2505         if ((err = fetchprop(cur, DTD_ATTR_MATCH, tabptr->zone_dev_match,
2506             sizeof (tabptr->zone_dev_match))) != Z_OK)
2507                 return (err);
2508 
2509         return (Z_OK);
2510 }
2511 
2512 static int
2513 zonecfg_add_dev_core(zone_dochandle_t handle, struct zone_devtab *tabptr)
2514 {
2515         xmlNodePtr newnode, cur = handle->zone_dh_cur;
2516         int err;
2517 
2518         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_DEVICE, NULL);
2519 
2520         if ((err = newprop(newnode, DTD_ATTR_MATCH,
2521             tabptr->zone_dev_match)) != Z_OK)
2522                 return (err);
2523 
2524         return (Z_OK);
2525 }
2526 
2527 int
2528 zonecfg_add_dev(zone_dochandle_t handle, struct zone_devtab *tabptr)
2529 {
2530         int err;
2531 
2532         if (tabptr == NULL)
2533                 return (Z_INVAL);
2534 
2535         if ((err = operation_prep(handle)) != Z_OK)
2536                 return (err);
2537 
2538         if ((err = zonecfg_add_dev_core(handle, tabptr)) != Z_OK)
2539                 return (err);
2540 
2541         return (Z_OK);
2542 }
2543 
2544 static int
2545 zonecfg_delete_dev_core(zone_dochandle_t handle, struct zone_devtab *tabptr)
2546 {
2547         xmlNodePtr cur = handle->zone_dh_cur;
2548         int match_match;
2549 
2550         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2551                 if (xmlStrcmp(cur->name, DTD_ELEM_DEVICE))
2552                         continue;
2553 
2554                 match_match = match_prop(cur, DTD_ATTR_MATCH,
2555                     tabptr->zone_dev_match);
2556 
2557                 if (match_match) {
2558                         xmlUnlinkNode(cur);
2559                         xmlFreeNode(cur);
2560                         return (Z_OK);
2561                 }
2562         }
2563         return (Z_NO_RESOURCE_ID);
2564 }
2565 
2566 int
2567 zonecfg_delete_dev(zone_dochandle_t handle, struct zone_devtab *tabptr)
2568 {
2569         int err;
2570 
2571         if (tabptr == NULL)
2572                 return (Z_INVAL);
2573 
2574         if ((err = operation_prep(handle)) != Z_OK)
2575                 return (err);
2576 
2577         if ((err = zonecfg_delete_dev_core(handle, tabptr)) != Z_OK)
2578                 return (err);
2579 
2580         return (Z_OK);
2581 }
2582 
2583 int
2584 zonecfg_modify_dev(
2585         zone_dochandle_t handle,
2586         struct zone_devtab *oldtabptr,
2587         struct zone_devtab *newtabptr)
2588 {
2589         int err;
2590 
2591         if (oldtabptr == NULL || newtabptr == NULL)
2592                 return (Z_INVAL);
2593 
2594         if ((err = operation_prep(handle)) != Z_OK)
2595                 return (err);
2596 
2597         if ((err = zonecfg_delete_dev_core(handle, oldtabptr)) != Z_OK)
2598                 return (err);
2599 
2600         if ((err = zonecfg_add_dev_core(handle, newtabptr)) != Z_OK)
2601                 return (err);
2602 
2603         return (Z_OK);
2604 }
2605 
2606 static int
2607 zonecfg_add_auth_core(zone_dochandle_t handle, struct zone_admintab *tabptr,
2608     char *zonename)
2609 {
2610         xmlNodePtr newnode, cur = handle->zone_dh_cur;
2611         int err;
2612 
2613         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_ADMIN, NULL);
2614         err = newprop(newnode, DTD_ATTR_USER, tabptr->zone_admin_user);
2615         if (err != Z_OK)
2616                 return (err);
2617         err = newprop(newnode, DTD_ATTR_AUTHS, tabptr->zone_admin_auths);
2618         if (err != Z_OK)
2619                 return (err);
2620         if ((err = zonecfg_remove_userauths(
2621             handle, tabptr->zone_admin_user, zonename, B_FALSE)) != Z_OK)
2622                 return (err);
2623         return (Z_OK);
2624 }
2625 
2626 int
2627 zonecfg_add_admin(zone_dochandle_t handle, struct zone_admintab *tabptr,
2628     char *zonename)
2629 {
2630         int err;
2631 
2632         if (tabptr == NULL)
2633                 return (Z_INVAL);
2634 
2635         if ((err = operation_prep(handle)) != Z_OK)
2636                 return (err);
2637 
2638         if ((err = zonecfg_add_auth_core(handle, tabptr,
2639             zonename)) != Z_OK)
2640                 return (err);
2641 
2642         return (Z_OK);
2643 }
2644 static int
2645 zonecfg_delete_auth_core(zone_dochandle_t handle, struct zone_admintab *tabptr,
2646     char *zonename)
2647 {
2648         xmlNodePtr cur = handle->zone_dh_cur;
2649         boolean_t auth_match;
2650         int err;
2651 
2652         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2653                 if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
2654                         continue;
2655                 auth_match = match_prop(cur, DTD_ATTR_USER,
2656                     tabptr->zone_admin_user);
2657                 if (auth_match) {
2658                         if ((err = zonecfg_insert_userauths(
2659                             handle, tabptr->zone_admin_user,
2660                             zonename)) != Z_OK)
2661                                 return (err);
2662                         xmlUnlinkNode(cur);
2663                         xmlFreeNode(cur);
2664                         return (Z_OK);
2665                 }
2666         }
2667         return (Z_NO_RESOURCE_ID);
2668 }
2669 
2670 int
2671 zonecfg_delete_admin(zone_dochandle_t handle, struct zone_admintab *tabptr,
2672     char *zonename)
2673 {
2674         int err;
2675 
2676         if (tabptr == NULL)
2677                 return (Z_INVAL);
2678 
2679         if ((err = operation_prep(handle)) != Z_OK)
2680                 return (err);
2681 
2682         if ((err = zonecfg_delete_auth_core(handle, tabptr, zonename)) != Z_OK)
2683                 return (err);
2684 
2685         return (Z_OK);
2686 }
2687 
2688 int
2689 zonecfg_modify_admin(zone_dochandle_t handle, struct zone_admintab *oldtabptr,
2690     struct zone_admintab *newtabptr, char *zonename)
2691 {
2692         int err;
2693 
2694         if (oldtabptr == NULL || newtabptr == NULL)
2695                 return (Z_INVAL);
2696 
2697         if ((err = operation_prep(handle)) != Z_OK)
2698                 return (err);
2699 
2700         if ((err = zonecfg_delete_auth_core(handle, oldtabptr, zonename))
2701             != Z_OK)
2702                 return (err);
2703 
2704         if ((err = zonecfg_add_auth_core(handle, newtabptr,
2705             zonename)) != Z_OK)
2706                 return (err);
2707 
2708         return (Z_OK);
2709 }
2710 
2711 int
2712 zonecfg_lookup_admin(zone_dochandle_t handle, struct zone_admintab *tabptr)
2713 {
2714         xmlNodePtr cur, firstmatch;
2715         int err;
2716         char user[MAXUSERNAME];
2717 
2718         if (tabptr == NULL)
2719                 return (Z_INVAL);
2720 
2721         if ((err = operation_prep(handle)) != Z_OK)
2722                 return (err);
2723 
2724         cur = handle->zone_dh_cur;
2725         firstmatch = NULL;
2726         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2727                 if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
2728                         continue;
2729                 if (strlen(tabptr->zone_admin_user) > 0) {
2730                         if ((fetchprop(cur, DTD_ATTR_USER, user,
2731                             sizeof (user)) == Z_OK) &&
2732                             (strcmp(tabptr->zone_admin_user, user) == 0)) {
2733                                 if (firstmatch == NULL)
2734                                         firstmatch = cur;
2735                                 else
2736                                         return (Z_INSUFFICIENT_SPEC);
2737                         }
2738                 }
2739         }
2740         if (firstmatch == NULL)
2741                 return (Z_NO_RESOURCE_ID);
2742 
2743         cur = firstmatch;
2744 
2745         if ((err = fetchprop(cur, DTD_ATTR_USER, tabptr->zone_admin_user,
2746             sizeof (tabptr->zone_admin_user))) != Z_OK)
2747                 return (err);
2748 
2749         if ((err = fetchprop(cur, DTD_ATTR_AUTHS, tabptr->zone_admin_auths,
2750             sizeof (tabptr->zone_admin_auths))) != Z_OK)
2751                 return (err);
2752 
2753         return (Z_OK);
2754 }
2755 
2756 
2757 /* Lock to serialize all devwalks */
2758 static pthread_mutex_t zonecfg_devwalk_lock = PTHREAD_MUTEX_INITIALIZER;
2759 /*
2760  * Global variables used to pass data from zonecfg_dev_manifest to the nftw
2761  * call-back (zonecfg_devwalk_cb).  g_devwalk_data is really the void*
2762  * parameter and g_devwalk_cb is really the *cb parameter from
2763  * zonecfg_dev_manifest.
2764  */
2765 typedef struct __g_devwalk_data *g_devwalk_data_t;
2766 static g_devwalk_data_t g_devwalk_data;
2767 static int (*g_devwalk_cb)(const char *, uid_t, gid_t, mode_t, const char *,
2768     void *);
2769 static size_t g_devwalk_skip_prefix;
2770 
2771 /*
2772  * zonecfg_dev_manifest call-back function used during detach to generate the
2773  * dev info in the manifest.
2774  */
2775 static int
2776 get_detach_dev_entry(const char *name, uid_t uid, gid_t gid, mode_t mode,
2777     const char *acl, void *hdl)
2778 {
2779         zone_dochandle_t handle = (zone_dochandle_t)hdl;
2780         xmlNodePtr newnode;
2781         xmlNodePtr cur;
2782         int err;
2783         char buf[128];
2784 
2785         if ((err = operation_prep(handle)) != Z_OK)
2786                 return (err);
2787 
2788         cur = handle->zone_dh_cur;
2789         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_DEV_PERM, NULL);
2790         if ((err = newprop(newnode, DTD_ATTR_NAME, (char *)name)) != Z_OK)
2791                 return (err);
2792         (void) snprintf(buf, sizeof (buf), "%lu", uid);
2793         if ((err = newprop(newnode, DTD_ATTR_UID, buf)) != Z_OK)
2794                 return (err);
2795         (void) snprintf(buf, sizeof (buf), "%lu", gid);
2796         if ((err = newprop(newnode, DTD_ATTR_GID, buf)) != Z_OK)
2797                 return (err);
2798         (void) snprintf(buf, sizeof (buf), "%o", mode);
2799         if ((err = newprop(newnode, DTD_ATTR_MODE, buf)) != Z_OK)
2800                 return (err);
2801         if ((err = newprop(newnode, DTD_ATTR_ACL, (char *)acl)) != Z_OK)
2802                 return (err);
2803         return (Z_OK);
2804 }
2805 
2806 /*
2807  * This is the nftw call-back function used by zonecfg_dev_manifest.  It is
2808  * responsible for calling the actual call-back.
2809  */
2810 /* ARGSUSED2 */
2811 static int
2812 zonecfg_devwalk_cb(const char *path, const struct stat *st, int f,
2813     struct FTW *ftw)
2814 {
2815         acl_t *acl;
2816         char *acl_txt = NULL;
2817 
2818         /* skip all but character and block devices */
2819         if (!S_ISBLK(st->st_mode) && !S_ISCHR(st->st_mode))
2820                 return (0);
2821 
2822         if ((acl_get(path, ACL_NO_TRIVIAL, &acl) == 0) &&
2823             acl != NULL) {
2824                 acl_txt = acl_totext(acl, ACL_NORESOLVE);
2825                 acl_free(acl);
2826         }
2827 
2828         if (strlen(path) <= g_devwalk_skip_prefix)
2829                 return (0);
2830 
2831         g_devwalk_cb(path + g_devwalk_skip_prefix, st->st_uid, st->st_gid,
2832             st->st_mode & S_IAMB, acl_txt != NULL ? acl_txt : "",
2833             g_devwalk_data);
2834         free(acl_txt);
2835         return (0);
2836 }
2837 
2838 /*
2839  * Walk the dev tree for the zone specified by hdl and call the
2840  * get_detach_dev_entry call-back function for each entry in the tree.  The
2841  * call-back will be passed the name, uid, gid, mode, acl string and the
2842  * handle input parameter for each dev entry.
2843  *
2844  * Data is passed to get_detach_dev_entry through the global variables
2845  * g_devwalk_data, *g_devwalk_cb, and g_devwalk_skip_prefix.  The
2846  * zonecfg_devwalk_cb function will actually call get_detach_dev_entry.
2847  */
2848 int
2849 zonecfg_dev_manifest(zone_dochandle_t hdl)
2850 {
2851         char path[MAXPATHLEN];
2852         int ret;
2853 
2854         if ((ret = zonecfg_get_zonepath(hdl, path, sizeof (path))) != Z_OK)
2855                 return (ret);
2856 
2857         if (strlcat(path, "/dev", sizeof (path)) >= sizeof (path))
2858                 return (Z_TOO_BIG);
2859 
2860         /*
2861          * We have to serialize all devwalks in the same process
2862          * (which should be fine), since nftw() is so badly designed.
2863          */
2864         (void) pthread_mutex_lock(&zonecfg_devwalk_lock);
2865 
2866         g_devwalk_skip_prefix = strlen(path) + 1;
2867         g_devwalk_data = (g_devwalk_data_t)hdl;
2868         g_devwalk_cb = get_detach_dev_entry;
2869         (void) nftw(path, zonecfg_devwalk_cb, 0, FTW_PHYS);
2870 
2871         (void) pthread_mutex_unlock(&zonecfg_devwalk_lock);
2872         return (Z_OK);
2873 }
2874 
2875 /*
2876  * Update the owner, group, mode and acl on the specified dev (inpath) for
2877  * the zone (hdl).  This function can be used to fix up the dev tree after
2878  * attaching a migrated zone.
2879  */
2880 int
2881 zonecfg_devperms_apply(zone_dochandle_t hdl, const char *inpath, uid_t owner,
2882     gid_t group, mode_t mode, const char *acltxt)
2883 {
2884         int ret;
2885         char path[MAXPATHLEN];
2886         struct stat st;
2887         acl_t *aclp;
2888 
2889         if ((ret = zonecfg_get_zonepath(hdl, path, sizeof (path))) != Z_OK)
2890                 return (ret);
2891 
2892         if (strlcat(path, "/dev/", sizeof (path)) >= sizeof (path))
2893                 return (Z_TOO_BIG);
2894         if (strlcat(path, inpath, sizeof (path)) >= sizeof (path))
2895                 return (Z_TOO_BIG);
2896 
2897         if (stat(path, &st) == -1)
2898                 return (Z_INVAL);
2899 
2900         /* make sure we're only touching device nodes */
2901         if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode))
2902                 return (Z_INVAL);
2903 
2904         if (chown(path, owner, group) == -1)
2905                 return (Z_SYSTEM);
2906 
2907         if (chmod(path, mode) == -1)
2908                 return (Z_SYSTEM);
2909 
2910         if ((acltxt == NULL) || (strcmp(acltxt, "") == 0))
2911                 return (Z_OK);
2912 
2913         if (acl_fromtext(acltxt, &aclp) != 0) {
2914                 errno = EINVAL;
2915                 return (Z_SYSTEM);
2916         }
2917 
2918         errno = 0;
2919         if (acl_set(path, aclp) == -1) {
2920                 free(aclp);
2921                 return (Z_SYSTEM);
2922         }
2923 
2924         free(aclp);
2925         return (Z_OK);
2926 }
2927 
2928 /*
2929  * This function finds everything mounted under a zone's rootpath.
2930  * This returns the number of mounts under rootpath, or -1 on error.
2931  * callback is called once per mount found with the first argument
2932  * pointing to a mnttab structure containing the mount's information.
2933  *
2934  * If the callback function returns non-zero zonecfg_find_mounts
2935  * aborts with an error.
2936  */
2937 int
2938 zonecfg_find_mounts(char *rootpath, int (*callback)(const struct mnttab *,
2939     void *), void *priv) {
2940         FILE *mnttab;
2941         struct mnttab m;
2942         size_t l;
2943         int zfsl;
2944         int rv = 0;
2945         char zfs_path[MAXPATHLEN];
2946 
2947         assert(rootpath != NULL);
2948 
2949         if ((zfsl = snprintf(zfs_path, sizeof (zfs_path), "%s/.zfs/", rootpath))
2950             >= sizeof (zfs_path))
2951                 return (-1);
2952 
2953         l = strlen(rootpath);
2954 
2955         mnttab = fopen("/etc/mnttab", "r");
2956 
2957         if (mnttab == NULL)
2958                 return (-1);
2959 
2960         if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0)  {
2961                 rv = -1;
2962                 goto out;
2963         }
2964 
2965         while (!getmntent(mnttab, &m)) {
2966                 if ((strncmp(rootpath, m.mnt_mountp, l) == 0) &&
2967                     (m.mnt_mountp[l] == '/') &&
2968                     (strncmp(zfs_path, m.mnt_mountp, zfsl) != 0)) {
2969                         rv++;
2970                         if (callback == NULL)
2971                                 continue;
2972                         if (callback(&m, priv)) {
2973                                 rv = -1;
2974                                 goto out;
2975 
2976                         }
2977                 }
2978         }
2979 
2980 out:
2981         (void) fclose(mnttab);
2982         return (rv);
2983 }
2984 
2985 int
2986 zonecfg_lookup_attr(zone_dochandle_t handle, struct zone_attrtab *tabptr)
2987 {
2988         xmlNodePtr cur, firstmatch;
2989         int err;
2990         char name[MAXNAMELEN], type[MAXNAMELEN], value[MAXNAMELEN];
2991 
2992         if (tabptr == NULL)
2993                 return (Z_INVAL);
2994 
2995         if ((err = operation_prep(handle)) != Z_OK)
2996                 return (err);
2997 
2998         cur = handle->zone_dh_cur;
2999         firstmatch = NULL;
3000         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
3001                 if (xmlStrcmp(cur->name, DTD_ELEM_ATTR))
3002                         continue;
3003                 if (strlen(tabptr->zone_attr_name) > 0) {
3004                         if ((fetchprop(cur, DTD_ATTR_NAME, name,
3005                             sizeof (name)) == Z_OK) &&
3006                             (strcmp(tabptr->zone_attr_name, name) == 0)) {
3007                                 if (firstmatch == NULL)
3008                                         firstmatch = cur;
3009                                 else
3010                                         return (Z_INSUFFICIENT_SPEC);
3011                         }
3012                 }
3013                 if (strlen(tabptr->zone_attr_type) > 0) {
3014                         if ((fetchprop(cur, DTD_ATTR_TYPE, type,
3015                             sizeof (type)) == Z_OK)) {
3016                                 if (strcmp(tabptr->zone_attr_type, type) == 0) {
3017                                         if (firstmatch == NULL)
3018                                                 firstmatch = cur;
3019                                         else if (firstmatch != cur)
3020                                                 return (Z_INSUFFICIENT_SPEC);
3021                                 } else {
3022                                         /*
3023                                          * If another property matched but this
3024                                          * one doesn't then reset firstmatch.
3025                                          */
3026                                         if (firstmatch == cur)
3027                                                 firstmatch = NULL;
3028                                 }
3029                         }
3030                 }
3031                 if (strlen(tabptr->zone_attr_value) > 0) {
3032                         if ((fetchprop(cur, DTD_ATTR_VALUE, value,
3033                             sizeof (value)) == Z_OK)) {
3034                                 if (strcmp(tabptr->zone_attr_value, value) ==
3035                                     0) {
3036                                         if (firstmatch == NULL)
3037                                                 firstmatch = cur;
3038                                         else if (firstmatch != cur)
3039                                                 return (Z_INSUFFICIENT_SPEC);
3040                                 } else {
3041                                         /*
3042                                          * If another property matched but this
3043                                          * one doesn't then reset firstmatch.
3044                                          */
3045                                         if (firstmatch == cur)
3046                                                 firstmatch = NULL;
3047                                 }
3048                         }
3049                 }
3050         }
3051         if (firstmatch == NULL)
3052                 return (Z_NO_RESOURCE_ID);
3053 
3054         cur = firstmatch;
3055 
3056         if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_attr_name,
3057             sizeof (tabptr->zone_attr_name))) != Z_OK)
3058                 return (err);
3059 
3060         if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_attr_type,
3061             sizeof (tabptr->zone_attr_type))) != Z_OK)
3062                 return (err);
3063 
3064         if ((err = fetchprop(cur, DTD_ATTR_VALUE, tabptr->zone_attr_value,
3065             sizeof (tabptr->zone_attr_value))) != Z_OK)
3066                 return (err);
3067 
3068         return (Z_OK);
3069 }
3070 
3071 static int
3072 zonecfg_add_attr_core(zone_dochandle_t handle, struct zone_attrtab *tabptr)
3073 {
3074         xmlNodePtr newnode, cur = handle->zone_dh_cur;
3075         int err;
3076 
3077         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_ATTR, NULL);
3078         err = newprop(newnode, DTD_ATTR_NAME, tabptr->zone_attr_name);
3079         if (err != Z_OK)
3080                 return (err);
3081         err = newprop(newnode, DTD_ATTR_TYPE, tabptr->zone_attr_type);
3082         if (err != Z_OK)
3083                 return (err);
3084         err = newprop(newnode, DTD_ATTR_VALUE, tabptr->zone_attr_value);
3085         if (err != Z_OK)
3086                 return (err);
3087         return (Z_OK);
3088 }
3089 
3090 int
3091 zonecfg_add_attr(zone_dochandle_t handle, struct zone_attrtab *tabptr)
3092 {
3093         int err;
3094 
3095         if (tabptr == NULL)
3096                 return (Z_INVAL);
3097 
3098         if ((err = operation_prep(handle)) != Z_OK)
3099                 return (err);
3100 
3101         if ((err = zonecfg_add_attr_core(handle, tabptr)) != Z_OK)
3102                 return (err);
3103 
3104         return (Z_OK);
3105 }
3106 
3107 static int
3108 zonecfg_delete_attr_core(zone_dochandle_t handle, struct zone_attrtab *tabptr)
3109 {
3110         xmlNodePtr cur = handle->zone_dh_cur;
3111         int name_match, type_match, value_match;
3112 
3113         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
3114                 if (xmlStrcmp(cur->name, DTD_ELEM_ATTR))
3115                         continue;
3116 
3117                 name_match = match_prop(cur, DTD_ATTR_NAME,
3118                     tabptr->zone_attr_name);
3119                 type_match = match_prop(cur, DTD_ATTR_TYPE,
3120                     tabptr->zone_attr_type);
3121                 value_match = match_prop(cur, DTD_ATTR_VALUE,
3122                     tabptr->zone_attr_value);
3123 
3124                 if (name_match && type_match && value_match) {
3125                         xmlUnlinkNode(cur);
3126                         xmlFreeNode(cur);
3127                         return (Z_OK);
3128                 }
3129         }
3130         return (Z_NO_RESOURCE_ID);
3131 }
3132 
3133 int
3134 zonecfg_delete_attr(zone_dochandle_t handle, struct zone_attrtab *tabptr)
3135 {
3136         int err;
3137 
3138         if (tabptr == NULL)
3139                 return (Z_INVAL);
3140 
3141         if ((err = operation_prep(handle)) != Z_OK)
3142                 return (err);
3143 
3144         if ((err = zonecfg_delete_attr_core(handle, tabptr)) != Z_OK)
3145                 return (err);
3146 
3147         return (Z_OK);
3148 }
3149 
3150 int
3151 zonecfg_modify_attr(
3152         zone_dochandle_t handle,
3153         struct zone_attrtab *oldtabptr,
3154         struct zone_attrtab *newtabptr)
3155 {
3156         int err;
3157 
3158         if (oldtabptr == NULL || newtabptr == NULL)
3159                 return (Z_INVAL);
3160 
3161         if ((err = operation_prep(handle)) != Z_OK)
3162                 return (err);
3163 
3164         if ((err = zonecfg_delete_attr_core(handle, oldtabptr)) != Z_OK)
3165                 return (err);
3166 
3167         if ((err = zonecfg_add_attr_core(handle, newtabptr)) != Z_OK)
3168                 return (err);
3169 
3170         return (Z_OK);
3171 }
3172 
3173 int
3174 zonecfg_get_attr_boolean(const struct zone_attrtab *attr, boolean_t *value)
3175 {
3176         if (attr == NULL)
3177                 return (Z_INVAL);
3178 
3179         if (strcmp(attr->zone_attr_type, DTD_ENTITY_BOOLEAN) != 0)
3180                 return (Z_INVAL);
3181 
3182         if (strcmp(attr->zone_attr_value, DTD_ENTITY_TRUE) == 0) {
3183                 *value = B_TRUE;
3184                 return (Z_OK);
3185         }
3186         if (strcmp(attr->zone_attr_value, DTD_ENTITY_FALSE) == 0) {
3187                 *value = B_FALSE;
3188                 return (Z_OK);
3189         }
3190         return (Z_INVAL);
3191 }
3192 
3193 int
3194 zonecfg_get_attr_int(const struct zone_attrtab *attr, int64_t *value)
3195 {
3196         long long result;
3197         char *endptr;
3198 
3199         if (attr == NULL)
3200                 return (Z_INVAL);
3201 
3202         if (strcmp(attr->zone_attr_type, DTD_ENTITY_INT) != 0)
3203                 return (Z_INVAL);
3204 
3205         errno = 0;
3206         result = strtoll(attr->zone_attr_value, &endptr, 10);
3207         if (errno != 0 || *endptr != '\0')
3208                 return (Z_INVAL);
3209         *value = result;
3210         return (Z_OK);
3211 }
3212 
3213 int
3214 zonecfg_get_attr_string(const struct zone_attrtab *attr, char *value,
3215     size_t val_sz)
3216 {
3217         if (attr == NULL)
3218                 return (Z_INVAL);
3219 
3220         if (strcmp(attr->zone_attr_type, DTD_ENTITY_STRING) != 0)
3221                 return (Z_INVAL);
3222 
3223         if (strlcpy(value, attr->zone_attr_value, val_sz) >= val_sz)
3224                 return (Z_TOO_BIG);
3225         return (Z_OK);
3226 }
3227 
3228 int
3229 zonecfg_get_attr_uint(const struct zone_attrtab *attr, uint64_t *value)
3230 {
3231         unsigned long long result;
3232         long long neg_result;
3233         char *endptr;
3234 
3235         if (attr == NULL)
3236                 return (Z_INVAL);
3237 
3238         if (strcmp(attr->zone_attr_type, DTD_ENTITY_UINT) != 0)
3239                 return (Z_INVAL);
3240 
3241         errno = 0;
3242         result = strtoull(attr->zone_attr_value, &endptr, 10);
3243         if (errno != 0 || *endptr != '\0')
3244                 return (Z_INVAL);
3245         errno = 0;
3246         neg_result = strtoll(attr->zone_attr_value, &endptr, 10);
3247         /*
3248          * Incredibly, strtoull("<negative number>", ...) will not fail but
3249          * return whatever (negative) number cast as a u_longlong_t, so we
3250          * need to look for this here.
3251          */
3252         if (errno == 0 && neg_result < 0)
3253                 return (Z_INVAL);
3254         *value = result;
3255         return (Z_OK);
3256 }
3257 
3258 int
3259 zonecfg_lookup_rctl(zone_dochandle_t handle, struct zone_rctltab *tabptr)
3260 {
3261         xmlNodePtr cur, val;
3262         char savedname[MAXNAMELEN];
3263         struct zone_rctlvaltab *valptr;
3264         int err;
3265 
3266         if (strlen(tabptr->zone_rctl_name) == 0)
3267                 return (Z_INVAL);
3268 
3269         if ((err = operation_prep(handle)) != Z_OK)
3270                 return (err);
3271 
3272         cur = handle->zone_dh_cur;
3273         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
3274                 if (xmlStrcmp(cur->name, DTD_ELEM_RCTL))
3275                         continue;
3276                 if ((fetchprop(cur, DTD_ATTR_NAME, savedname,
3277                     sizeof (savedname)) == Z_OK) &&
3278                     (strcmp(savedname, tabptr->zone_rctl_name) == 0)) {
3279                         tabptr->zone_rctl_valptr = NULL;
3280                         for (val = cur->xmlChildrenNode; val != NULL;
3281                             val = val->next) {
3282                                 valptr = (struct zone_rctlvaltab *)malloc(
3283                                     sizeof (struct zone_rctlvaltab));
3284                                 if (valptr == NULL)
3285                                         return (Z_NOMEM);
3286                                 if ((fetchprop(val, DTD_ATTR_PRIV,
3287                                     valptr->zone_rctlval_priv,
3288                                     sizeof (valptr->zone_rctlval_priv)) !=
3289                                     Z_OK))
3290                                         break;
3291                                 if ((fetchprop(val, DTD_ATTR_LIMIT,
3292                                     valptr->zone_rctlval_limit,
3293                                     sizeof (valptr->zone_rctlval_limit)) !=
3294                                     Z_OK))
3295                                         break;
3296                                 if ((fetchprop(val, DTD_ATTR_ACTION,
3297                                     valptr->zone_rctlval_action,
3298                                     sizeof (valptr->zone_rctlval_action)) !=
3299                                     Z_OK))
3300                                         break;
3301                                 if (zonecfg_add_rctl_value(tabptr, valptr) !=
3302                                     Z_OK)
3303                                         break;
3304                         }
3305                         return (Z_OK);
3306                 }
3307         }
3308         return (Z_NO_RESOURCE_ID);
3309 }
3310 
3311 static int
3312 zonecfg_add_rctl_core(zone_dochandle_t handle, struct zone_rctltab *tabptr)
3313 {
3314         xmlNodePtr newnode, cur = handle->zone_dh_cur, valnode;
3315         struct zone_rctlvaltab *valptr;
3316         int err;
3317 
3318         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_RCTL, NULL);
3319         err = newprop(newnode, DTD_ATTR_NAME, tabptr->zone_rctl_name);
3320         if (err != Z_OK)
3321                 return (err);
3322         for (valptr = tabptr->zone_rctl_valptr; valptr != NULL;
3323             valptr = valptr->zone_rctlval_next) {
3324                 valnode = xmlNewTextChild(newnode, NULL,
3325                     DTD_ELEM_RCTLVALUE, NULL);
3326                 err = newprop(valnode, DTD_ATTR_PRIV,
3327                     valptr->zone_rctlval_priv);
3328                 if (err != Z_OK)
3329                         return (err);
3330                 err = newprop(valnode, DTD_ATTR_LIMIT,
3331                     valptr->zone_rctlval_limit);
3332                 if (err != Z_OK)
3333                         return (err);
3334                 err = newprop(valnode, DTD_ATTR_ACTION,
3335                     valptr->zone_rctlval_action);
3336                 if (err != Z_OK)
3337                         return (err);
3338         }
3339         return (Z_OK);
3340 }
3341 
3342 int
3343 zonecfg_add_rctl(zone_dochandle_t handle, struct zone_rctltab *tabptr)
3344 {
3345         int err;
3346 
3347         if (tabptr == NULL)
3348                 return (Z_INVAL);
3349 
3350         if ((err = operation_prep(handle)) != Z_OK)
3351                 return (err);
3352 
3353         if ((err = zonecfg_add_rctl_core(handle, tabptr)) != Z_OK)
3354                 return (err);
3355 
3356         return (Z_OK);
3357 }
3358 
3359 static int
3360 zonecfg_delete_rctl_core(zone_dochandle_t handle, struct zone_rctltab *tabptr)
3361 {
3362         xmlNodePtr cur = handle->zone_dh_cur;
3363         xmlChar *savedname;
3364         int name_result;
3365 
3366         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
3367                 if (xmlStrcmp(cur->name, DTD_ELEM_RCTL))
3368                         continue;
3369 
3370                 savedname = xmlGetProp(cur, DTD_ATTR_NAME);
3371                 if (savedname == NULL)  /* shouldn't happen */
3372                         continue;
3373                 name_result = xmlStrcmp(savedname,
3374                     (const xmlChar *) tabptr->zone_rctl_name);
3375                 xmlFree(savedname);
3376 
3377                 if (name_result == 0) {
3378                         xmlUnlinkNode(cur);
3379                         xmlFreeNode(cur);
3380                         return (Z_OK);
3381                 }
3382         }
3383         return (Z_NO_RESOURCE_ID);
3384 }
3385 
3386 int
3387 zonecfg_delete_rctl(zone_dochandle_t handle, struct zone_rctltab *tabptr)
3388 {
3389         int err;
3390 
3391         if (tabptr == NULL)
3392                 return (Z_INVAL);
3393 
3394         if ((err = operation_prep(handle)) != Z_OK)
3395                 return (err);
3396 
3397         if ((err = zonecfg_delete_rctl_core(handle, tabptr)) != Z_OK)
3398                 return (err);
3399 
3400         return (Z_OK);
3401 }
3402 
3403 int
3404 zonecfg_modify_rctl(
3405         zone_dochandle_t handle,
3406         struct zone_rctltab *oldtabptr,
3407         struct zone_rctltab *newtabptr)
3408 {
3409         int err;
3410 
3411         if (oldtabptr == NULL || newtabptr == NULL)
3412                 return (Z_INVAL);
3413 
3414         if ((err = operation_prep(handle)) != Z_OK)
3415                 return (err);
3416 
3417         if ((err = zonecfg_delete_rctl_core(handle, oldtabptr)) != Z_OK)
3418                 return (err);
3419 
3420         if ((err = zonecfg_add_rctl_core(handle, newtabptr)) != Z_OK)
3421                 return (err);
3422 
3423         return (Z_OK);
3424 }
3425 
3426 int
3427 zonecfg_add_rctl_value(
3428         struct zone_rctltab *tabptr,
3429         struct zone_rctlvaltab *valtabptr)
3430 {
3431         struct zone_rctlvaltab *last, *old, *new;
3432         rctlblk_t *rctlblk = alloca(rctlblk_size());
3433 
3434         last = tabptr->zone_rctl_valptr;
3435         for (old = last; old != NULL; old = old->zone_rctlval_next)
3436                 last = old;     /* walk to the end of the list */
3437         new = valtabptr;        /* alloc'd by caller */
3438         new->zone_rctlval_next = NULL;
3439         if (zonecfg_construct_rctlblk(valtabptr, rctlblk) != Z_OK)
3440                 return (Z_INVAL);
3441         if (!zonecfg_valid_rctlblk(rctlblk))
3442                 return (Z_INVAL);
3443         if (last == NULL)
3444                 tabptr->zone_rctl_valptr = new;
3445         else
3446                 last->zone_rctlval_next = new;
3447         return (Z_OK);
3448 }
3449 
3450 int
3451 zonecfg_remove_rctl_value(
3452         struct zone_rctltab *tabptr,
3453         struct zone_rctlvaltab *valtabptr)
3454 {
3455         struct zone_rctlvaltab *last, *this, *next;
3456 
3457         last = tabptr->zone_rctl_valptr;
3458         for (this = last; this != NULL; this = this->zone_rctlval_next) {
3459                 if (strcmp(this->zone_rctlval_priv,
3460                     valtabptr->zone_rctlval_priv) == 0 &&
3461                     strcmp(this->zone_rctlval_limit,
3462                     valtabptr->zone_rctlval_limit) == 0 &&
3463                     strcmp(this->zone_rctlval_action,
3464                     valtabptr->zone_rctlval_action) == 0) {
3465                         next = this->zone_rctlval_next;
3466                         if (this == tabptr->zone_rctl_valptr)
3467                                 tabptr->zone_rctl_valptr = next;
3468                         else
3469                                 last->zone_rctlval_next = next;
3470                         free(this);
3471                         return (Z_OK);
3472                 } else
3473                         last = this;
3474         }
3475         return (Z_NO_PROPERTY_ID);
3476 }
3477 
3478 void
3479 zonecfg_set_swinv(zone_dochandle_t handle)
3480 {
3481         handle->zone_dh_sw_inv = B_TRUE;
3482 }
3483 
3484 /*
3485  * Add the pkg to the sw inventory on the handle.
3486  */
3487 int
3488 zonecfg_add_pkg(zone_dochandle_t handle, char *name, char *version)
3489 {
3490         xmlNodePtr newnode;
3491         xmlNodePtr cur;
3492         int err;
3493 
3494         if ((err = operation_prep(handle)) != Z_OK)
3495                 return (err);
3496 
3497         cur = handle->zone_dh_cur;
3498         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_PACKAGE, NULL);
3499         if ((err = newprop(newnode, DTD_ATTR_NAME, name)) != Z_OK)
3500                 return (err);
3501         if ((err = newprop(newnode, DTD_ATTR_VERSION, version)) != Z_OK)
3502                 return (err);
3503         return (Z_OK);
3504 }
3505 
3506 char *
3507 zonecfg_strerror(int errnum)
3508 {
3509         switch (errnum) {
3510         case Z_OK:
3511                 return (dgettext(TEXT_DOMAIN, "OK"));
3512         case Z_EMPTY_DOCUMENT:
3513                 return (dgettext(TEXT_DOMAIN, "Empty document"));
3514         case Z_WRONG_DOC_TYPE:
3515                 return (dgettext(TEXT_DOMAIN, "Wrong document type"));
3516         case Z_BAD_PROPERTY:
3517                 return (dgettext(TEXT_DOMAIN, "Bad document property"));
3518         case Z_TEMP_FILE:
3519                 return (dgettext(TEXT_DOMAIN,
3520                     "Problem creating temporary file"));
3521         case Z_SAVING_FILE:
3522                 return (dgettext(TEXT_DOMAIN, "Problem saving file"));
3523         case Z_NO_ENTRY:
3524                 return (dgettext(TEXT_DOMAIN, "No such entry"));
3525         case Z_BOGUS_ZONE_NAME:
3526                 return (dgettext(TEXT_DOMAIN, "Bogus zone name"));
3527         case Z_REQD_RESOURCE_MISSING:
3528                 return (dgettext(TEXT_DOMAIN, "Required resource missing"));
3529         case Z_REQD_PROPERTY_MISSING:
3530                 return (dgettext(TEXT_DOMAIN, "Required property missing"));
3531         case Z_BAD_HANDLE:
3532                 return (dgettext(TEXT_DOMAIN, "Bad handle"));
3533         case Z_NOMEM:
3534                 return (dgettext(TEXT_DOMAIN, "Out of memory"));
3535         case Z_INVAL:
3536                 return (dgettext(TEXT_DOMAIN, "Invalid argument"));
3537         case Z_ACCES:
3538                 return (dgettext(TEXT_DOMAIN, "Permission denied"));
3539         case Z_TOO_BIG:
3540                 return (dgettext(TEXT_DOMAIN, "Argument list too long"));
3541         case Z_MISC_FS:
3542                 return (dgettext(TEXT_DOMAIN,
3543                     "Miscellaneous file system error"));
3544         case Z_NO_ZONE:
3545                 return (dgettext(TEXT_DOMAIN, "No such zone configured"));
3546         case Z_NO_RESOURCE_TYPE:
3547                 return (dgettext(TEXT_DOMAIN, "No such resource type"));
3548         case Z_NO_RESOURCE_ID:
3549                 return (dgettext(TEXT_DOMAIN, "No such resource with that id"));
3550         case Z_NO_PROPERTY_TYPE:
3551                 return (dgettext(TEXT_DOMAIN, "No such property type"));
3552         case Z_NO_PROPERTY_ID:
3553                 return (dgettext(TEXT_DOMAIN, "No such property with that id"));
3554         case Z_BAD_ZONE_STATE:
3555                 return (dgettext(TEXT_DOMAIN,
3556                     "Zone state is invalid for the requested operation"));
3557         case Z_INVALID_DOCUMENT:
3558                 return (dgettext(TEXT_DOMAIN, "Invalid document"));
3559         case Z_NAME_IN_USE:
3560                 return (dgettext(TEXT_DOMAIN, "Zone name already in use"));
3561         case Z_NO_SUCH_ID:
3562                 return (dgettext(TEXT_DOMAIN, "No such zone ID"));
3563         case Z_UPDATING_INDEX:
3564                 return (dgettext(TEXT_DOMAIN, "Problem updating index file"));
3565         case Z_LOCKING_FILE:
3566                 return (dgettext(TEXT_DOMAIN, "Locking index file"));
3567         case Z_UNLOCKING_FILE:
3568                 return (dgettext(TEXT_DOMAIN, "Unlocking index file"));
3569         case Z_INSUFFICIENT_SPEC:
3570                 return (dgettext(TEXT_DOMAIN, "Insufficient specification"));
3571         case Z_RESOLVED_PATH:
3572                 return (dgettext(TEXT_DOMAIN, "Resolved path mismatch"));
3573         case Z_IPV6_ADDR_PREFIX_LEN:
3574                 return (dgettext(TEXT_DOMAIN,
3575                     "IPv6 address missing required prefix length"));
3576         case Z_BOGUS_ADDRESS:
3577                 return (dgettext(TEXT_DOMAIN,
3578                     "Neither an IPv4 nor an IPv6 address nor a host name"));
3579         case Z_PRIV_PROHIBITED:
3580                 return (dgettext(TEXT_DOMAIN,
3581                     "Specified privilege is prohibited"));
3582         case Z_PRIV_REQUIRED:
3583                 return (dgettext(TEXT_DOMAIN,
3584                     "Required privilege is missing"));
3585         case Z_PRIV_UNKNOWN:
3586                 return (dgettext(TEXT_DOMAIN,
3587                     "Specified privilege is unknown"));
3588         case Z_BRAND_ERROR:
3589                 return (dgettext(TEXT_DOMAIN,
3590                     "Brand-specific error"));
3591         case Z_INCOMPATIBLE:
3592                 return (dgettext(TEXT_DOMAIN, "Incompatible settings"));
3593         case Z_ALIAS_DISALLOW:
3594                 return (dgettext(TEXT_DOMAIN,
3595                     "An incompatible rctl already exists for this property"));
3596         case Z_CLEAR_DISALLOW:
3597                 return (dgettext(TEXT_DOMAIN,
3598                     "Clearing this property is not allowed"));
3599         case Z_POOL:
3600                 return (dgettext(TEXT_DOMAIN, "libpool(3LIB) error"));
3601         case Z_POOLS_NOT_ACTIVE:
3602                 return (dgettext(TEXT_DOMAIN, "Pools facility not active; "
3603                     "zone will not be bound to pool"));
3604         case Z_POOL_ENABLE:
3605                 return (dgettext(TEXT_DOMAIN,
3606                     "Could not enable pools facility"));
3607         case Z_NO_POOL:
3608                 return (dgettext(TEXT_DOMAIN,
3609                     "Pool not found; using default pool"));
3610         case Z_POOL_CREATE:
3611                 return (dgettext(TEXT_DOMAIN,
3612                     "Could not create a temporary pool"));
3613         case Z_POOL_BIND:
3614                 return (dgettext(TEXT_DOMAIN, "Could not bind zone to pool"));
3615         case Z_INVALID_PROPERTY:
3616                 return (dgettext(TEXT_DOMAIN, "Specified property is invalid"));
3617         case Z_SYSTEM:
3618                 return (strerror(errno));
3619         default:
3620                 return (dgettext(TEXT_DOMAIN, "Unknown error"));
3621         }
3622 }
3623 
3624 /*
3625  * Note that the zonecfg_setXent() and zonecfg_endXent() calls are all the
3626  * same, as they just turn around and call zonecfg_setent() / zonecfg_endent().
3627  */
3628 
3629 static int
3630 zonecfg_setent(zone_dochandle_t handle)
3631 {
3632         xmlNodePtr cur;
3633         int err;
3634 
3635         if (handle == NULL)
3636                 return (Z_INVAL);
3637 
3638         if ((err = operation_prep(handle)) != Z_OK) {
3639                 handle->zone_dh_cur = NULL;
3640                 return (err);
3641         }
3642         cur = handle->zone_dh_cur;
3643         cur = cur->xmlChildrenNode;
3644         handle->zone_dh_cur = cur;
3645         return (Z_OK);
3646 }
3647 
3648 static int
3649 zonecfg_endent(zone_dochandle_t handle)
3650 {
3651         if (handle == NULL)
3652                 return (Z_INVAL);
3653 
3654         handle->zone_dh_cur = handle->zone_dh_top;
3655         return (Z_OK);
3656 }
3657 
3658 /*
3659  * Do the work required to manipulate a process through libproc.
3660  * If grab_process() returns no errors (0), then release_process()
3661  * must eventually be called.
3662  *
3663  * Return values:
3664  *      0 Successful creation of agent thread
3665  *      1 Error grabbing
3666  *      2 Error creating agent
3667  */
3668 static int
3669 grab_process(pr_info_handle_t *p)
3670 {
3671         int ret;
3672 
3673         if ((p->pr = Pgrab(p->pid, 0, &ret)) != NULL) {
3674 
3675                 if (Psetflags(p->pr, PR_RLC) != 0) {
3676                         Prelease(p->pr, 0);
3677                         return (1);
3678                 }
3679                 if (Pcreate_agent(p->pr) == 0) {
3680                         return (0);
3681 
3682                 } else {
3683                         Prelease(p->pr, 0);
3684                         return (2);
3685                 }
3686         } else {
3687                 return (1);
3688         }
3689 }
3690 
3691 /*
3692  * Release the specified process. This destroys the agent
3693  * and releases the process. If the process is NULL, nothing
3694  * is done. This function should only be called if grab_process()
3695  * has previously been called and returned success.
3696  *
3697  * This function is Pgrab-safe.
3698  */
3699 static void
3700 release_process(struct ps_prochandle *Pr)
3701 {
3702         if (Pr == NULL)
3703                 return;
3704 
3705         Pdestroy_agent(Pr);
3706         Prelease(Pr, 0);
3707 }
3708 
3709 static boolean_t
3710 grab_zone_proc(char *zonename, pr_info_handle_t *p)
3711 {
3712         DIR *dirp;
3713         struct dirent *dentp;
3714         zoneid_t zoneid;
3715         int pid_self;
3716         psinfo_t psinfo;
3717 
3718         if (zone_get_id(zonename, &zoneid) != 0)
3719                 return (B_FALSE);
3720 
3721         pid_self = getpid();
3722 
3723         if ((dirp = opendir("/proc")) == NULL)
3724                 return (B_FALSE);
3725 
3726         while (dentp = readdir(dirp)) {
3727                 p->pid = atoi(dentp->d_name);
3728 
3729                 /* Skip self */
3730                 if (p->pid == pid_self)
3731                         continue;
3732 
3733                 if (proc_get_psinfo(p->pid, &psinfo) != 0)
3734                         continue;
3735 
3736                 if (psinfo.pr_zoneid != zoneid)
3737                         continue;
3738 
3739                 /* attempt to grab process */
3740                 if (grab_process(p) != 0)
3741                         continue;
3742 
3743                 if (pr_getzoneid(p->pr) != zoneid) {
3744                         release_process(p->pr);
3745                         continue;
3746                 }
3747 
3748                 (void) closedir(dirp);
3749                 return (B_TRUE);
3750         }
3751 
3752         (void) closedir(dirp);
3753         return (B_FALSE);
3754 }
3755 
3756 static boolean_t
3757 get_priv_rctl(struct ps_prochandle *pr, char *name, rctlblk_t *rblk)
3758 {
3759         if (pr_getrctl(pr, name, NULL, rblk, RCTL_FIRST))
3760                 return (B_FALSE);
3761 
3762         if (rctlblk_get_privilege(rblk) == RCPRIV_PRIVILEGED)
3763                 return (B_TRUE);
3764 
3765         while (pr_getrctl(pr, name, rblk, rblk, RCTL_NEXT) == 0) {
3766                 if (rctlblk_get_privilege(rblk) == RCPRIV_PRIVILEGED)
3767                         return (B_TRUE);
3768         }
3769 
3770         return (B_FALSE);
3771 }
3772 
3773 /*
3774  * Apply the current rctl settings to the specified, running zone.
3775  */
3776 int
3777 zonecfg_apply_rctls(char *zone_name, zone_dochandle_t handle)
3778 {
3779         int err;
3780         int res = Z_OK;
3781         rctlblk_t *rblk;
3782         pr_info_handle_t p;
3783         struct zone_rctltab rctl;
3784 
3785         if ((err = zonecfg_setrctlent(handle)) != Z_OK)
3786                 return (err);
3787 
3788         if ((rblk = (rctlblk_t *)malloc(rctlblk_size())) == NULL) {
3789                 (void) zonecfg_endrctlent(handle);
3790                 return (Z_NOMEM);
3791         }
3792 
3793         if (!grab_zone_proc(zone_name, &p)) {
3794                 (void) zonecfg_endrctlent(handle);
3795                 free(rblk);
3796                 return (Z_SYSTEM);
3797         }
3798 
3799         while (zonecfg_getrctlent(handle, &rctl) == Z_OK) {
3800                 char *rname;
3801                 struct zone_rctlvaltab *valptr;
3802 
3803                 rname = rctl.zone_rctl_name;
3804 
3805                 /* first delete all current privileged settings for this rctl */
3806                 while (get_priv_rctl(p.pr, rname, rblk)) {
3807                         if (pr_setrctl(p.pr, rname, NULL, rblk, RCTL_DELETE) !=
3808                             0) {
3809                                 res = Z_SYSTEM;
3810                                 goto done;
3811                         }
3812                 }
3813 
3814                 /* now set each new value for the rctl */
3815                 for (valptr = rctl.zone_rctl_valptr; valptr != NULL;
3816                     valptr = valptr->zone_rctlval_next) {
3817                         if ((err = zonecfg_construct_rctlblk(valptr, rblk))
3818                             != Z_OK) {
3819                                 res = errno = err;
3820                                 goto done;
3821                         }
3822 
3823                         if (pr_setrctl(p.pr, rname, NULL, rblk, RCTL_INSERT)) {
3824                                 res = Z_SYSTEM;
3825                                 goto done;
3826                         }
3827                 }
3828         }
3829 
3830 done:
3831         release_process(p.pr);
3832         free(rblk);
3833         (void) zonecfg_endrctlent(handle);
3834 
3835         return (res);
3836 }
3837 
3838 static const xmlChar *
3839 nm_to_dtd(char *nm)
3840 {
3841         if (strcmp(nm, "device") == 0)
3842                 return (DTD_ELEM_DEVICE);
3843         if (strcmp(nm, "fs") == 0)
3844                 return (DTD_ELEM_FS);
3845         if (strcmp(nm, "net") == 0)
3846                 return (DTD_ELEM_NET);
3847         if (strcmp(nm, "attr") == 0)
3848                 return (DTD_ELEM_ATTR);
3849         if (strcmp(nm, "rctl") == 0)
3850                 return (DTD_ELEM_RCTL);
3851         if (strcmp(nm, "dataset") == 0)
3852                 return (DTD_ELEM_DATASET);
3853         if (strcmp(nm, "admin") == 0)
3854                 return (DTD_ELEM_ADMIN);
3855 
3856         return (NULL);
3857 }
3858 
3859 int
3860 zonecfg_num_resources(zone_dochandle_t handle, char *rsrc)
3861 {
3862         int num = 0;
3863         const xmlChar *dtd;
3864         xmlNodePtr cur;
3865 
3866         if ((dtd = nm_to_dtd(rsrc)) == NULL)
3867                 return (num);
3868 
3869         if (zonecfg_setent(handle) != Z_OK)
3870                 return (num);
3871 
3872         for (cur = handle->zone_dh_cur; cur != NULL; cur = cur->next)
3873                 if (xmlStrcmp(cur->name, dtd) == 0)
3874                         num++;
3875 
3876         (void) zonecfg_endent(handle);
3877 
3878         return (num);
3879 }
3880 
3881 int
3882 zonecfg_del_all_resources(zone_dochandle_t handle, char *rsrc)
3883 {
3884         int err;
3885         const xmlChar *dtd;
3886         xmlNodePtr cur;
3887 
3888         if ((dtd = nm_to_dtd(rsrc)) == NULL)
3889                 return (Z_NO_RESOURCE_TYPE);
3890 
3891         if ((err = zonecfg_setent(handle)) != Z_OK)
3892                 return (err);
3893 
3894         cur = handle->zone_dh_cur;
3895         while (cur != NULL) {
3896                 xmlNodePtr tmp;
3897 
3898                 if (xmlStrcmp(cur->name, dtd)) {
3899                         cur = cur->next;
3900                         continue;
3901                 }
3902 
3903                 tmp = cur->next;
3904                 xmlUnlinkNode(cur);
3905                 xmlFreeNode(cur);
3906                 cur = tmp;
3907         }
3908 
3909         (void) zonecfg_endent(handle);
3910         return (Z_OK);
3911 }
3912 
3913 static boolean_t
3914 valid_uint(char *s, uint64_t *n)
3915 {
3916         char *endp;
3917 
3918         /* strtoull accepts '-'?! so we want to flag that as an error */
3919         if (strchr(s, '-') != NULL)
3920                 return (B_FALSE);
3921 
3922         errno = 0;
3923         *n = strtoull(s, &endp, 10);
3924 
3925         if (errno != 0 || *endp != '\0')
3926                 return (B_FALSE);
3927         return (B_TRUE);
3928 }
3929 
3930 /*
3931  * Convert a string representing a number (possibly a fraction) into an integer.
3932  * The string can have a modifier (K, M, G or T).   The modifiers are treated
3933  * as powers of two (not 10).
3934  */
3935 int
3936 zonecfg_str_to_bytes(char *str, uint64_t *bytes)
3937 {
3938         long double val;
3939         char *unitp;
3940         uint64_t scale;
3941 
3942         if ((val = strtold(str, &unitp)) < 0)
3943                 return (-1);
3944 
3945         /* remove any leading white space from units string */
3946         while (isspace(*unitp) != 0)
3947                 ++unitp;
3948 
3949         /* if no units explicitly set, error */
3950         if (unitp == NULL || *unitp == '\0') {
3951                 scale = 1;
3952         } else {
3953                 int i;
3954                 char *units[] = {"K", "M", "G", "T", NULL};
3955 
3956                 scale = 1024;
3957 
3958                 /* update scale based on units */
3959                 for (i = 0; units[i] != NULL; i++) {
3960                         if (strcasecmp(unitp, units[i]) == 0)
3961                                 break;
3962                         scale <<= 10;
3963                 }
3964 
3965                 if (units[i] == NULL)
3966                         return (-1);
3967         }
3968 
3969         *bytes = (uint64_t)(val * scale);
3970         return (0);
3971 }
3972 
3973 boolean_t
3974 zonecfg_valid_ncpus(char *lowstr, char *highstr)
3975 {
3976         uint64_t low, high;
3977 
3978         if (!valid_uint(lowstr, &low) || !valid_uint(highstr, &high) ||
3979             low < 1 || low > high)
3980                 return (B_FALSE);
3981 
3982         return (B_TRUE);
3983 }
3984 
3985 boolean_t
3986 zonecfg_valid_importance(char *impstr)
3987 {
3988         uint64_t num;
3989 
3990         if (!valid_uint(impstr, &num))
3991                 return (B_FALSE);
3992 
3993         return (B_TRUE);
3994 }
3995 
3996 boolean_t
3997 zonecfg_valid_alias_limit(char *name, char *limitstr, uint64_t *limit)
3998 {
3999         int i;
4000 
4001         for (i = 0; aliases[i].shortname != NULL; i++)
4002                 if (strcmp(name, aliases[i].shortname) == 0)
4003                         break;
4004 
4005         if (aliases[i].shortname == NULL)
4006                 return (B_FALSE);
4007 
4008         if (!valid_uint(limitstr, limit) || *limit < aliases[i].low_limit)
4009                 return (B_FALSE);
4010 
4011         return (B_TRUE);
4012 }
4013 
4014 boolean_t
4015 zonecfg_valid_memlimit(char *memstr, uint64_t *mem_val)
4016 {
4017         if (zonecfg_str_to_bytes(memstr, mem_val) != 0)
4018                 return (B_FALSE);
4019 
4020         return (B_TRUE);
4021 }
4022 
4023 static int
4024 zerr_pool(char *pool_err, int err_size, int res)
4025 {
4026         (void) strlcpy(pool_err, pool_strerror(pool_error()), err_size);
4027         return (res);
4028 }
4029 
4030 static int
4031 create_tmp_pset(char *pool_err, int err_size, pool_conf_t *pconf, pool_t *pool,
4032     char *name, int min, int max)
4033 {
4034         pool_resource_t *res;
4035         pool_elem_t *elem;
4036         pool_value_t *val;
4037 
4038         if ((res = pool_resource_create(pconf, "pset", name)) == NULL)
4039                 return (zerr_pool(pool_err, err_size, Z_POOL));
4040 
4041         if (pool_associate(pconf, pool, res) != PO_SUCCESS)
4042                 return (zerr_pool(pool_err, err_size, Z_POOL));
4043 
4044         if ((elem = pool_resource_to_elem(pconf, res)) == NULL)
4045                 return (zerr_pool(pool_err, err_size, Z_POOL));
4046 
4047         if ((val = pool_value_alloc()) == NULL)
4048                 return (zerr_pool(pool_err, err_size, Z_POOL));
4049 
4050         /* set the maximum number of cpus for the pset */
4051         pool_value_set_uint64(val, (uint64_t)max);
4052 
4053         if (pool_put_property(pconf, elem, "pset.max", val) != PO_SUCCESS) {
4054                 pool_value_free(val);
4055                 return (zerr_pool(pool_err, err_size, Z_POOL));
4056         }
4057 
4058         /* set the minimum number of cpus for the pset */
4059         pool_value_set_uint64(val, (uint64_t)min);
4060 
4061         if (pool_put_property(pconf, elem, "pset.min", val) != PO_SUCCESS) {
4062                 pool_value_free(val);
4063                 return (zerr_pool(pool_err, err_size, Z_POOL));
4064         }
4065 
4066         pool_value_free(val);
4067 
4068         return (Z_OK);
4069 }
4070 
4071 static int
4072 create_tmp_pool(char *pool_err, int err_size, pool_conf_t *pconf, char *name,
4073     struct zone_psettab *pset_tab)
4074 {
4075         pool_t *pool;
4076         int res = Z_OK;
4077 
4078         /* create a temporary pool configuration */
4079         if (pool_conf_open(pconf, NULL, PO_TEMP) != PO_SUCCESS) {
4080                 res = zerr_pool(pool_err, err_size, Z_POOL);
4081                 return (res);
4082         }
4083 
4084         if ((pool = pool_create(pconf, name)) == NULL) {
4085                 res = zerr_pool(pool_err, err_size, Z_POOL_CREATE);
4086                 goto done;
4087         }
4088 
4089         /* set pool importance */
4090         if (pset_tab->zone_importance[0] != '\0') {
4091                 pool_elem_t *elem;
4092                 pool_value_t *val;
4093 
4094                 if ((elem = pool_to_elem(pconf, pool)) == NULL) {
4095                         res = zerr_pool(pool_err, err_size, Z_POOL);
4096                         goto done;
4097                 }
4098 
4099                 if ((val = pool_value_alloc()) == NULL) {
4100                         res = zerr_pool(pool_err, err_size, Z_POOL);
4101                         goto done;
4102                 }
4103 
4104                 pool_value_set_int64(val,
4105                     (int64_t)atoi(pset_tab->zone_importance));
4106 
4107                 if (pool_put_property(pconf, elem, "pool.importance", val)
4108                     != PO_SUCCESS) {
4109                         res = zerr_pool(pool_err, err_size, Z_POOL);
4110                         pool_value_free(val);
4111                         goto done;
4112                 }
4113 
4114                 pool_value_free(val);
4115         }
4116 
4117         if ((res = create_tmp_pset(pool_err, err_size, pconf, pool, name,
4118             atoi(pset_tab->zone_ncpu_min),
4119             atoi(pset_tab->zone_ncpu_max))) != Z_OK)
4120                 goto done;
4121 
4122         /* validation */
4123         if (pool_conf_status(pconf) == POF_INVALID) {
4124                 res = zerr_pool(pool_err, err_size, Z_POOL);
4125                 goto done;
4126         }
4127 
4128         /*
4129          * This validation is the one we expect to fail if the user specified
4130          * an invalid configuration (too many cpus) for this system.
4131          */
4132         if (pool_conf_validate(pconf, POV_RUNTIME) != PO_SUCCESS) {
4133                 res = zerr_pool(pool_err, err_size, Z_POOL_CREATE);
4134                 goto done;
4135         }
4136 
4137         /*
4138          * Commit the dynamic configuration but not the pool configuration
4139          * file.
4140          */
4141         if (pool_conf_commit(pconf, 1) != PO_SUCCESS)
4142                 res = zerr_pool(pool_err, err_size, Z_POOL);
4143 
4144 done:
4145         (void) pool_conf_close(pconf);
4146         return (res);
4147 }
4148 
4149 static int
4150 get_running_tmp_pset(pool_conf_t *pconf, pool_t *pool, pool_resource_t *pset,
4151     struct zone_psettab *pset_tab)
4152 {
4153         int nfound = 0;
4154         pool_elem_t *pe;
4155         pool_value_t *pv = pool_value_alloc();
4156         uint64_t val_uint;
4157 
4158         if (pool != NULL) {
4159                 pe = pool_to_elem(pconf, pool);
4160                 if (pool_get_property(pconf, pe, "pool.importance", pv)
4161                     != POC_INVAL) {
4162                         int64_t val_int;
4163 
4164                         (void) pool_value_get_int64(pv, &val_int);
4165                         (void) snprintf(pset_tab->zone_importance,
4166                             sizeof (pset_tab->zone_importance), "%d", val_int);
4167                         nfound++;
4168                 }
4169         }
4170 
4171         if (pset != NULL) {
4172                 pe = pool_resource_to_elem(pconf, pset);
4173                 if (pool_get_property(pconf, pe, "pset.min", pv) != POC_INVAL) {
4174                         (void) pool_value_get_uint64(pv, &val_uint);
4175                         (void) snprintf(pset_tab->zone_ncpu_min,
4176                             sizeof (pset_tab->zone_ncpu_min), "%u", val_uint);
4177                         nfound++;
4178                 }
4179 
4180                 if (pool_get_property(pconf, pe, "pset.max", pv) != POC_INVAL) {
4181                         (void) pool_value_get_uint64(pv, &val_uint);
4182                         (void) snprintf(pset_tab->zone_ncpu_max,
4183                             sizeof (pset_tab->zone_ncpu_max), "%u", val_uint);
4184                         nfound++;
4185                 }
4186         }
4187 
4188         pool_value_free(pv);
4189 
4190         if (nfound == 3)
4191                 return (PO_SUCCESS);
4192 
4193         return (PO_FAIL);
4194 }
4195 
4196 /*
4197  * Determine if a tmp pool is configured and if so, if the configuration is
4198  * still valid or if it has been changed since the tmp pool was created.
4199  * If the tmp pool configuration is no longer valid, delete the tmp pool.
4200  *
4201  * Set *valid=B_TRUE if there is an existing, valid tmp pool configuration.
4202  */
4203 static int
4204 verify_del_tmp_pool(pool_conf_t *pconf, char *tmp_name, char *pool_err,
4205     int err_size, struct zone_psettab *pset_tab, boolean_t *exists)
4206 {
4207         int res = Z_OK;
4208         pool_t *pool;
4209         pool_resource_t *pset;
4210         struct zone_psettab pset_current;
4211 
4212         *exists = B_FALSE;
4213 
4214         if (pool_conf_open(pconf, pool_dynamic_location(), PO_RDWR)
4215             != PO_SUCCESS) {
4216                 res = zerr_pool(pool_err, err_size, Z_POOL);
4217                 return (res);
4218         }
4219 
4220         pool = pool_get_pool(pconf, tmp_name);
4221         pset = pool_get_resource(pconf, "pset", tmp_name);
4222 
4223         if (pool == NULL && pset == NULL) {
4224                 /* no tmp pool configured */
4225                 goto done;
4226         }
4227 
4228         /*
4229          * If an existing tmp pool for this zone is configured with the proper
4230          * settings, then the tmp pool is valid.
4231          */
4232         if (get_running_tmp_pset(pconf, pool, pset, &pset_current)
4233             == PO_SUCCESS &&
4234             strcmp(pset_tab->zone_ncpu_min,
4235             pset_current.zone_ncpu_min) == 0 &&
4236             strcmp(pset_tab->zone_ncpu_max,
4237             pset_current.zone_ncpu_max) == 0 &&
4238             strcmp(pset_tab->zone_importance,
4239             pset_current.zone_importance) == 0) {
4240                 *exists = B_TRUE;
4241 
4242         } else {
4243                 /*
4244                  * An out-of-date tmp pool configuration exists.  Delete it
4245                  * so that we can create the correct tmp pool config.
4246                  */
4247                 if (pset != NULL &&
4248                     pool_resource_destroy(pconf, pset) != PO_SUCCESS) {
4249                         res = zerr_pool(pool_err, err_size, Z_POOL);
4250                         goto done;
4251                 }
4252 
4253                 if (pool != NULL &&
4254                     pool_destroy(pconf, pool) != PO_SUCCESS) {
4255                         res = zerr_pool(pool_err, err_size, Z_POOL);
4256                         goto done;
4257                 }
4258 
4259                 /* commit dynamic config */
4260                 if (pool_conf_commit(pconf, 0) != PO_SUCCESS)
4261                         res = zerr_pool(pool_err, err_size, Z_POOL);
4262         }
4263 
4264 done:
4265         (void) pool_conf_close(pconf);
4266 
4267         return (res);
4268 }
4269 
4270 /*
4271  * Destroy any existing tmp pool.
4272  */
4273 int
4274 zonecfg_destroy_tmp_pool(char *zone_name, char *pool_err, int err_size)
4275 {
4276         int status;
4277         int res = Z_OK;
4278         pool_conf_t *pconf;
4279         pool_t *pool;
4280         pool_resource_t *pset;
4281         char tmp_name[MAX_TMP_POOL_NAME];
4282 
4283         /* if pools not enabled then nothing to do */
4284         if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED)
4285                 return (Z_OK);
4286 
4287         if ((pconf = pool_conf_alloc()) == NULL)
4288                 return (zerr_pool(pool_err, err_size, Z_POOL));
4289 
4290         (void) snprintf(tmp_name, sizeof (tmp_name), TMP_POOL_NAME, zone_name);
4291 
4292         if (pool_conf_open(pconf, pool_dynamic_location(), PO_RDWR)
4293             != PO_SUCCESS) {
4294                 res = zerr_pool(pool_err, err_size, Z_POOL);
4295                 pool_conf_free(pconf);
4296                 return (res);
4297         }
4298 
4299         pool = pool_get_pool(pconf, tmp_name);
4300         pset = pool_get_resource(pconf, "pset", tmp_name);
4301 
4302         if (pool == NULL && pset == NULL) {
4303                 /* nothing to destroy, we're done */
4304                 goto done;
4305         }
4306 
4307         if (pset != NULL && pool_resource_destroy(pconf, pset) != PO_SUCCESS) {
4308                 res = zerr_pool(pool_err, err_size, Z_POOL);
4309                 goto done;
4310         }
4311 
4312         if (pool != NULL && pool_destroy(pconf, pool) != PO_SUCCESS) {
4313                 res = zerr_pool(pool_err, err_size, Z_POOL);
4314                 goto done;
4315         }
4316 
4317         /* commit dynamic config */
4318         if (pool_conf_commit(pconf, 0) != PO_SUCCESS)
4319                 res = zerr_pool(pool_err, err_size, Z_POOL);
4320 
4321 done:
4322         (void) pool_conf_close(pconf);
4323         pool_conf_free(pconf);
4324 
4325         return (res);
4326 }
4327 
4328 /*
4329  * Attempt to bind to a tmp pool for this zone.  If there is no tmp pool
4330  * configured, we just return Z_OK.
4331  *
4332  * We either attempt to create the tmp pool for this zone or rebind to an
4333  * existing tmp pool for this zone.
4334  *
4335  * Rebinding is used when a zone with a tmp pool reboots so that we don't have
4336  * to recreate the tmp pool.  To do this we need to be sure we work correctly
4337  * for the following cases:
4338  *
4339  *      - there is an existing, properly configured tmp pool.
4340  *      - zonecfg added tmp pool after zone was booted, must now create.
4341  *      - zonecfg updated tmp pool config after zone was booted, in this case
4342  *        we destroy the old tmp pool and create a new one.
4343  */
4344 int
4345 zonecfg_bind_tmp_pool(zone_dochandle_t handle, zoneid_t zoneid, char *pool_err,
4346     int err_size)
4347 {
4348         struct zone_psettab pset_tab;
4349         int err;
4350         int status;
4351         pool_conf_t *pconf;
4352         boolean_t exists;
4353         char zone_name[ZONENAME_MAX];
4354         char tmp_name[MAX_TMP_POOL_NAME];
4355 
4356         (void) getzonenamebyid(zoneid, zone_name, sizeof (zone_name));
4357 
4358         err = zonecfg_lookup_pset(handle, &pset_tab);
4359 
4360         /* if no temporary pool configured, we're done */
4361         if (err == Z_NO_ENTRY)
4362                 return (Z_OK);
4363 
4364         /*
4365          * importance might not have a value but we need to validate it here,
4366          * so set the default.
4367          */
4368         if (pset_tab.zone_importance[0] == '\0')
4369                 (void) strlcpy(pset_tab.zone_importance, "1",
4370                     sizeof (pset_tab.zone_importance));
4371 
4372         /* if pools not enabled, enable them now */
4373         if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED) {
4374                 if (pool_set_status(POOL_ENABLED) != PO_SUCCESS)
4375                         return (Z_POOL_ENABLE);
4376         }
4377 
4378         if ((pconf = pool_conf_alloc()) == NULL)
4379                 return (zerr_pool(pool_err, err_size, Z_POOL));
4380 
4381         (void) snprintf(tmp_name, sizeof (tmp_name), TMP_POOL_NAME, zone_name);
4382 
4383         /*
4384          * Check if a valid tmp pool/pset already exists.  If so, we just
4385          * reuse it.
4386          */
4387         if ((err = verify_del_tmp_pool(pconf, tmp_name, pool_err, err_size,
4388             &pset_tab, &exists)) != Z_OK) {
4389                 pool_conf_free(pconf);
4390                 return (err);
4391         }
4392 
4393         if (!exists)
4394                 err = create_tmp_pool(pool_err, err_size, pconf, tmp_name,
4395                     &pset_tab);
4396 
4397         pool_conf_free(pconf);
4398 
4399         if (err != Z_OK)
4400                 return (err);
4401 
4402         /* Bind the zone to the pool. */
4403         if (pool_set_binding(tmp_name, P_ZONEID, zoneid) != PO_SUCCESS)
4404                 return (zerr_pool(pool_err, err_size, Z_POOL_BIND));
4405 
4406         return (Z_OK);
4407 }
4408 
4409 /*
4410  * Attempt to bind to a permanent pool for this zone.  If there is no
4411  * permanent pool configured, we just return Z_OK.
4412  */
4413 int
4414 zonecfg_bind_pool(zone_dochandle_t handle, zoneid_t zoneid, char *pool_err,
4415     int err_size)
4416 {
4417         pool_conf_t *poolconf;
4418         pool_t *pool;
4419         char poolname[MAXPATHLEN];
4420         int status;
4421         int error;
4422 
4423         /*
4424          * Find the pool mentioned in the zone configuration, and bind to it.
4425          */
4426         error = zonecfg_get_pool(handle, poolname, sizeof (poolname));
4427         if (error == Z_NO_ENTRY || (error == Z_OK && strlen(poolname) == 0)) {
4428                 /*
4429                  * The property is not set on the zone, so the pool
4430                  * should be bound to the default pool.  But that's
4431                  * already done by the kernel, so we can just return.
4432                  */
4433                 return (Z_OK);
4434         }
4435         if (error != Z_OK) {
4436                 /*
4437                  * Not an error, even though it shouldn't be happening.
4438                  */
4439                 return (Z_OK);
4440         }
4441         /*
4442          * Don't do anything if pools aren't enabled.
4443          */
4444         if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED)
4445                 return (Z_POOLS_NOT_ACTIVE);
4446 
4447         /*
4448          * Try to provide a sane error message if the requested pool doesn't
4449          * exist.
4450          */
4451         if ((poolconf = pool_conf_alloc()) == NULL)
4452                 return (zerr_pool(pool_err, err_size, Z_POOL));
4453 
4454         if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
4455             PO_SUCCESS) {
4456                 pool_conf_free(poolconf);
4457                 return (zerr_pool(pool_err, err_size, Z_POOL));
4458         }
4459         pool = pool_get_pool(poolconf, poolname);
4460         (void) pool_conf_close(poolconf);
4461         pool_conf_free(poolconf);
4462         if (pool == NULL)
4463                 return (Z_NO_POOL);
4464 
4465         /*
4466          * Bind the zone to the pool.
4467          */
4468         if (pool_set_binding(poolname, P_ZONEID, zoneid) != PO_SUCCESS) {
4469                 /* if bind fails, return poolname for the error msg */
4470                 (void) strlcpy(pool_err, poolname, err_size);
4471                 return (Z_POOL_BIND);
4472         }
4473 
4474         return (Z_OK);
4475 }
4476 
4477 int
4478 zonecfg_get_poolname(zone_dochandle_t handle, char *zone, char *pool,
4479     size_t poolsize)
4480 {
4481         int err;
4482         struct zone_psettab pset_tab;
4483 
4484         err = zonecfg_lookup_pset(handle, &pset_tab);
4485         if ((err != Z_NO_ENTRY) && (err != Z_OK))
4486                 return (err);
4487 
4488         /* pset was found so a temporary pool was created */
4489         if (err == Z_OK) {
4490                 (void) snprintf(pool, poolsize, TMP_POOL_NAME, zone);
4491                 return (Z_OK);
4492         }
4493 
4494         /* lookup the poolname in zonecfg */
4495         return (zonecfg_get_pool(handle, pool, poolsize));
4496 }
4497 
4498 static boolean_t
4499 svc_enabled(char *svc_name)
4500 {
4501         scf_simple_prop_t       *prop;
4502         boolean_t               found = B_FALSE;
4503 
4504         prop = scf_simple_prop_get(NULL, svc_name, SCF_PG_GENERAL,
4505             SCF_PROPERTY_ENABLED);
4506 
4507         if (scf_simple_prop_numvalues(prop) == 1 &&
4508             *scf_simple_prop_next_boolean(prop) != 0)
4509                 found = B_TRUE;
4510 
4511         scf_simple_prop_free(prop);
4512 
4513         return (found);
4514 }
4515 
4516 /*
4517  * If the zone has capped-memory, make sure the rcap service is enabled.
4518  */
4519 int
4520 zonecfg_enable_rcapd(char *err, int size)
4521 {
4522         if (!svc_enabled(RCAP_SERVICE) &&
4523             smf_enable_instance(RCAP_SERVICE, 0) == -1) {
4524                 (void) strlcpy(err, scf_strerror(scf_error()), size);
4525                 return (Z_SYSTEM);
4526         }
4527 
4528         return (Z_OK);
4529 }
4530 
4531 /*
4532  * Return true if pset has cpu range specified and poold is not enabled.
4533  */
4534 boolean_t
4535 zonecfg_warn_poold(zone_dochandle_t handle)
4536 {
4537         struct zone_psettab pset_tab;
4538         int min, max;
4539         int err;
4540 
4541         err = zonecfg_lookup_pset(handle, &pset_tab);
4542 
4543         /* if no temporary pool configured, we're done */
4544         if (err == Z_NO_ENTRY)
4545                 return (B_FALSE);
4546 
4547         min = atoi(pset_tab.zone_ncpu_min);
4548         max = atoi(pset_tab.zone_ncpu_max);
4549 
4550         /* range not specified, no need for poold */
4551         if (min == max)
4552                 return (B_FALSE);
4553 
4554         /* we have a range, check if poold service is enabled */
4555         if (svc_enabled(POOLD_SERVICE))
4556                 return (B_FALSE);
4557 
4558         return (B_TRUE);
4559 }
4560 
4561 /*
4562  * Retrieve the specified pool's thread scheduling class.  'poolname' must
4563  * refer to the name of a configured resource pool.  The thread scheduling
4564  * class specified by the pool will be stored in the buffer to which 'class'
4565  * points.  'clsize' is the byte size of the buffer to which 'class' points.
4566  *
4567  * This function returns Z_OK if it successfully stored the specified pool's
4568  * thread scheduling class into the buffer to which 'class' points.  It returns
4569  * Z_NO_POOL if resource pools are not enabled, the function is unable to
4570  * access the system's resource pools configuration, or the specified pool
4571  * does not exist.  The function returns Z_TOO_BIG if the buffer to which
4572  * 'class' points is not large enough to contain the thread scheduling class'
4573  * name.  The function returns Z_NO_ENTRY if the pool does not specify a thread
4574  * scheduling class.
4575  */
4576 static int
4577 get_pool_sched_class(char *poolname, char *class, int clsize)
4578 {
4579         int status;
4580         pool_conf_t *poolconf;
4581         pool_t *pool;
4582         pool_elem_t *pe;
4583         pool_value_t *pv = pool_value_alloc();
4584         const char *sched_str;
4585 
4586         if (pool_get_status(&status) != PO_SUCCESS || status != POOL_ENABLED)
4587                 return (Z_NO_POOL);
4588 
4589         if ((poolconf = pool_conf_alloc()) == NULL)
4590                 return (Z_NO_POOL);
4591 
4592         if (pool_conf_open(poolconf, pool_dynamic_location(), PO_RDONLY) !=
4593             PO_SUCCESS) {
4594                 pool_conf_free(poolconf);
4595                 return (Z_NO_POOL);
4596         }
4597 
4598         if ((pool = pool_get_pool(poolconf, poolname)) == NULL) {
4599                 (void) pool_conf_close(poolconf);
4600                 pool_conf_free(poolconf);
4601                 return (Z_NO_POOL);
4602         }
4603 
4604         pe = pool_to_elem(poolconf, pool);
4605         if (pool_get_property(poolconf, pe, "pool.scheduler", pv) !=
4606             POC_STRING) {
4607                 (void) pool_conf_close(poolconf);
4608                 pool_conf_free(poolconf);
4609                 return (Z_NO_ENTRY);
4610         }
4611         (void) pool_value_get_string(pv, &sched_str);
4612         (void) pool_conf_close(poolconf);
4613         pool_conf_free(poolconf);
4614         if (strlcpy(class, sched_str, clsize) >= clsize)
4615                 return (Z_TOO_BIG);
4616         return (Z_OK);
4617 }
4618 
4619 /*
4620  * Get the default scheduling class for the zone.  This will either be the
4621  * class set on the zone's pool or the system default scheduling class.
4622  */
4623 int
4624 zonecfg_get_dflt_sched_class(zone_dochandle_t handle, char *class, int clsize)
4625 {
4626         char poolname[MAXPATHLEN];
4627 
4628         if (zonecfg_get_pool(handle, poolname, sizeof (poolname)) == Z_OK) {
4629                 /* check if the zone's pool specified a sched class */
4630                 if (get_pool_sched_class(poolname, class, clsize) == Z_OK)
4631                         return (Z_OK);
4632         }
4633 
4634         if (priocntl(0, 0, PC_GETDFLCL, class, (uint64_t)clsize) == -1)
4635                 return (Z_TOO_BIG);
4636 
4637         return (Z_OK);
4638 }
4639 
4640 int
4641 zonecfg_setfsent(zone_dochandle_t handle)
4642 {
4643         return (zonecfg_setent(handle));
4644 }
4645 
4646 int
4647 zonecfg_getfsent(zone_dochandle_t handle, struct zone_fstab *tabptr)
4648 {
4649         xmlNodePtr cur, options;
4650         char options_str[MAX_MNTOPT_STR];
4651         int err;
4652 
4653         if (handle == NULL)
4654                 return (Z_INVAL);
4655 
4656         if ((cur = handle->zone_dh_cur) == NULL)
4657                 return (Z_NO_ENTRY);
4658 
4659         for (; cur != NULL; cur = cur->next)
4660                 if (!xmlStrcmp(cur->name, DTD_ELEM_FS))
4661                         break;
4662         if (cur == NULL) {
4663                 handle->zone_dh_cur = handle->zone_dh_top;
4664                 return (Z_NO_ENTRY);
4665         }
4666 
4667         if ((err = fetchprop(cur, DTD_ATTR_SPECIAL, tabptr->zone_fs_special,
4668             sizeof (tabptr->zone_fs_special))) != Z_OK) {
4669                 handle->zone_dh_cur = handle->zone_dh_top;
4670                 return (err);
4671         }
4672 
4673         if ((err = fetchprop(cur, DTD_ATTR_RAW, tabptr->zone_fs_raw,
4674             sizeof (tabptr->zone_fs_raw))) != Z_OK) {
4675                 handle->zone_dh_cur = handle->zone_dh_top;
4676                 return (err);
4677         }
4678 
4679         if ((err = fetchprop(cur, DTD_ATTR_DIR, tabptr->zone_fs_dir,
4680             sizeof (tabptr->zone_fs_dir))) != Z_OK) {
4681                 handle->zone_dh_cur = handle->zone_dh_top;
4682                 return (err);
4683         }
4684 
4685         if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_fs_type,
4686             sizeof (tabptr->zone_fs_type))) != Z_OK) {
4687                 handle->zone_dh_cur = handle->zone_dh_top;
4688                 return (err);
4689         }
4690 
4691         /* OK for options to be NULL */
4692         tabptr->zone_fs_options = NULL;
4693         for (options = cur->xmlChildrenNode; options != NULL;
4694             options = options->next) {
4695                 if (fetchprop(options, DTD_ATTR_NAME, options_str,
4696                     sizeof (options_str)) != Z_OK)
4697                         break;
4698                 if (zonecfg_add_fs_option(tabptr, options_str) != Z_OK)
4699                         break;
4700         }
4701 
4702         handle->zone_dh_cur = cur->next;
4703         return (Z_OK);
4704 }
4705 
4706 int
4707 zonecfg_endfsent(zone_dochandle_t handle)
4708 {
4709         return (zonecfg_endent(handle));
4710 }
4711 
4712 int
4713 zonecfg_setnwifent(zone_dochandle_t handle)
4714 {
4715         return (zonecfg_setent(handle));
4716 }
4717 
4718 int
4719 zonecfg_getnwifent(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
4720 {
4721         xmlNodePtr cur;
4722         int err;
4723 
4724         if (handle == NULL)
4725                 return (Z_INVAL);
4726 
4727         if ((cur = handle->zone_dh_cur) == NULL)
4728                 return (Z_NO_ENTRY);
4729 
4730         for (; cur != NULL; cur = cur->next)
4731                 if (!xmlStrcmp(cur->name, DTD_ELEM_NET))
4732                         break;
4733         if (cur == NULL) {
4734                 handle->zone_dh_cur = handle->zone_dh_top;
4735                 return (Z_NO_ENTRY);
4736         }
4737 
4738         if ((err = fetchprop(cur, DTD_ATTR_ADDRESS, tabptr->zone_nwif_address,
4739             sizeof (tabptr->zone_nwif_address))) != Z_OK) {
4740                 handle->zone_dh_cur = handle->zone_dh_top;
4741                 return (err);
4742         }
4743 
4744         if ((err = fetchprop(cur, DTD_ATTR_ALLOWED_ADDRESS,
4745             tabptr->zone_nwif_allowed_address,
4746             sizeof (tabptr->zone_nwif_allowed_address))) != Z_OK) {
4747                 handle->zone_dh_cur = handle->zone_dh_top;
4748                 return (err);
4749         }
4750 
4751         if ((err = fetchprop(cur, DTD_ATTR_PHYSICAL, tabptr->zone_nwif_physical,
4752             sizeof (tabptr->zone_nwif_physical))) != Z_OK) {
4753                 handle->zone_dh_cur = handle->zone_dh_top;
4754                 return (err);
4755         }
4756 
4757         if ((err = fetchprop(cur, DTD_ATTR_DEFROUTER,
4758             tabptr->zone_nwif_defrouter,
4759             sizeof (tabptr->zone_nwif_defrouter))) != Z_OK) {
4760                 handle->zone_dh_cur = handle->zone_dh_top;
4761                 return (err);
4762         }
4763 
4764         handle->zone_dh_cur = cur->next;
4765         return (Z_OK);
4766 }
4767 
4768 int
4769 zonecfg_endnwifent(zone_dochandle_t handle)
4770 {
4771         return (zonecfg_endent(handle));
4772 }
4773 
4774 int
4775 zonecfg_setdevent(zone_dochandle_t handle)
4776 {
4777         return (zonecfg_setent(handle));
4778 }
4779 
4780 int
4781 zonecfg_getdevent(zone_dochandle_t handle, struct zone_devtab *tabptr)
4782 {
4783         xmlNodePtr cur;
4784         int err;
4785 
4786         if (handle == NULL)
4787                 return (Z_INVAL);
4788 
4789         if ((cur = handle->zone_dh_cur) == NULL)
4790                 return (Z_NO_ENTRY);
4791 
4792         for (; cur != NULL; cur = cur->next)
4793                 if (!xmlStrcmp(cur->name, DTD_ELEM_DEVICE))
4794                         break;
4795         if (cur == NULL) {
4796                 handle->zone_dh_cur = handle->zone_dh_top;
4797                 return (Z_NO_ENTRY);
4798         }
4799 
4800         if ((err = fetchprop(cur, DTD_ATTR_MATCH, tabptr->zone_dev_match,
4801             sizeof (tabptr->zone_dev_match))) != Z_OK) {
4802                 handle->zone_dh_cur = handle->zone_dh_top;
4803                 return (err);
4804         }
4805 
4806         handle->zone_dh_cur = cur->next;
4807         return (Z_OK);
4808 }
4809 
4810 int
4811 zonecfg_enddevent(zone_dochandle_t handle)
4812 {
4813         return (zonecfg_endent(handle));
4814 }
4815 
4816 int
4817 zonecfg_setrctlent(zone_dochandle_t handle)
4818 {
4819         return (zonecfg_setent(handle));
4820 }
4821 
4822 int
4823 zonecfg_getrctlent(zone_dochandle_t handle, struct zone_rctltab *tabptr)
4824 {
4825         xmlNodePtr cur, val;
4826         struct zone_rctlvaltab *valptr;
4827         int err;
4828 
4829         if (handle == NULL)
4830                 return (Z_INVAL);
4831 
4832         if ((cur = handle->zone_dh_cur) == NULL)
4833                 return (Z_NO_ENTRY);
4834 
4835         for (; cur != NULL; cur = cur->next)
4836                 if (!xmlStrcmp(cur->name, DTD_ELEM_RCTL))
4837                         break;
4838         if (cur == NULL) {
4839                 handle->zone_dh_cur = handle->zone_dh_top;
4840                 return (Z_NO_ENTRY);
4841         }
4842 
4843         if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_rctl_name,
4844             sizeof (tabptr->zone_rctl_name))) != Z_OK) {
4845                 handle->zone_dh_cur = handle->zone_dh_top;
4846                 return (err);
4847         }
4848 
4849         tabptr->zone_rctl_valptr = NULL;
4850         for (val = cur->xmlChildrenNode; val != NULL; val = val->next) {
4851                 valptr = (struct zone_rctlvaltab *)malloc(
4852                     sizeof (struct zone_rctlvaltab));
4853                 if (valptr == NULL)
4854                         return (Z_NOMEM);
4855                 if (fetchprop(val, DTD_ATTR_PRIV, valptr->zone_rctlval_priv,
4856                     sizeof (valptr->zone_rctlval_priv)) != Z_OK)
4857                         break;
4858                 if (fetchprop(val, DTD_ATTR_LIMIT, valptr->zone_rctlval_limit,
4859                     sizeof (valptr->zone_rctlval_limit)) != Z_OK)
4860                         break;
4861                 if (fetchprop(val, DTD_ATTR_ACTION, valptr->zone_rctlval_action,
4862                     sizeof (valptr->zone_rctlval_action)) != Z_OK)
4863                         break;
4864                 if (zonecfg_add_rctl_value(tabptr, valptr) != Z_OK)
4865                         break;
4866         }
4867 
4868         handle->zone_dh_cur = cur->next;
4869         return (Z_OK);
4870 }
4871 
4872 int
4873 zonecfg_endrctlent(zone_dochandle_t handle)
4874 {
4875         return (zonecfg_endent(handle));
4876 }
4877 
4878 int
4879 zonecfg_setattrent(zone_dochandle_t handle)
4880 {
4881         return (zonecfg_setent(handle));
4882 }
4883 
4884 int
4885 zonecfg_getattrent(zone_dochandle_t handle, struct zone_attrtab *tabptr)
4886 {
4887         xmlNodePtr cur;
4888         int err;
4889 
4890         if (handle == NULL)
4891                 return (Z_INVAL);
4892 
4893         if ((cur = handle->zone_dh_cur) == NULL)
4894                 return (Z_NO_ENTRY);
4895 
4896         for (; cur != NULL; cur = cur->next)
4897                 if (!xmlStrcmp(cur->name, DTD_ELEM_ATTR))
4898                         break;
4899         if (cur == NULL) {
4900                 handle->zone_dh_cur = handle->zone_dh_top;
4901                 return (Z_NO_ENTRY);
4902         }
4903 
4904         if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_attr_name,
4905             sizeof (tabptr->zone_attr_name))) != Z_OK) {
4906                 handle->zone_dh_cur = handle->zone_dh_top;
4907                 return (err);
4908         }
4909 
4910         if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_attr_type,
4911             sizeof (tabptr->zone_attr_type))) != Z_OK) {
4912                 handle->zone_dh_cur = handle->zone_dh_top;
4913                 return (err);
4914         }
4915 
4916         if ((err = fetchprop(cur, DTD_ATTR_VALUE, tabptr->zone_attr_value,
4917             sizeof (tabptr->zone_attr_value))) != Z_OK) {
4918                 handle->zone_dh_cur = handle->zone_dh_top;
4919                 return (err);
4920         }
4921 
4922         handle->zone_dh_cur = cur->next;
4923         return (Z_OK);
4924 }
4925 
4926 int
4927 zonecfg_endattrent(zone_dochandle_t handle)
4928 {
4929         return (zonecfg_endent(handle));
4930 }
4931 
4932 int
4933 zonecfg_setadminent(zone_dochandle_t handle)
4934 {
4935         return (zonecfg_setent(handle));
4936 }
4937 
4938 int
4939 zonecfg_getadminent(zone_dochandle_t handle, struct zone_admintab *tabptr)
4940 {
4941         xmlNodePtr cur;
4942         int err;
4943 
4944         if (handle == NULL)
4945                 return (Z_INVAL);
4946 
4947         if ((cur = handle->zone_dh_cur) == NULL)
4948                 return (Z_NO_ENTRY);
4949 
4950         for (; cur != NULL; cur = cur->next)
4951                 if (!xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
4952                         break;
4953         if (cur == NULL) {
4954                 handle->zone_dh_cur = handle->zone_dh_top;
4955                 return (Z_NO_ENTRY);
4956         }
4957 
4958         if ((err = fetchprop(cur, DTD_ATTR_USER, tabptr->zone_admin_user,
4959             sizeof (tabptr->zone_admin_user))) != Z_OK) {
4960                 handle->zone_dh_cur = handle->zone_dh_top;
4961                 return (err);
4962         }
4963 
4964 
4965         if ((err = fetchprop(cur, DTD_ATTR_AUTHS, tabptr->zone_admin_auths,
4966             sizeof (tabptr->zone_admin_auths))) != Z_OK) {
4967                 handle->zone_dh_cur = handle->zone_dh_top;
4968                 return (err);
4969         }
4970 
4971         handle->zone_dh_cur = cur->next;
4972         return (Z_OK);
4973 }
4974 
4975 int
4976 zonecfg_endadminent(zone_dochandle_t handle)
4977 {
4978         return (zonecfg_endent(handle));
4979 }
4980 
4981 /*
4982  * The privileges available on the system and described in privileges(5)
4983  * fall into four categories with respect to non-global zones:
4984  *
4985  *      Default set of privileges considered safe for all non-global
4986  *      zones.  These privileges are "safe" in the sense that a
4987  *      privileged process in the zone cannot affect processes in any
4988  *      other zone on the system.
4989  *
4990  *      Set of privileges not currently permitted within a non-global
4991  *      zone.  These privileges are considered by default, "unsafe,"
4992  *      and include ones which affect global resources (such as the
4993  *      system clock or physical memory) or are overly broad and cover
4994  *      more than one mechanism in the system.  In other cases, there
4995  *      has not been sufficient virtualization in the parts of the
4996  *      system the privilege covers to allow its use within a
4997  *      non-global zone.
4998  *
4999  *      Set of privileges required in order to get a zone booted and
5000  *      init(1M) started.  These cannot be removed from the zone's
5001  *      privilege set.
5002  *
5003  * All other privileges are optional and are potentially useful for
5004  * processes executing inside a non-global zone.
5005  *
5006  * When privileges are added to the system, a determination needs to be
5007  * made as to which category the privilege belongs to.  Ideally,
5008  * privileges should be fine-grained enough and the mechanisms they cover
5009  * virtualized enough so that they can be made available to non-global
5010  * zones.
5011  */
5012 
5013 /*
5014  * Define some of the tokens that priv_str_to_set(3C) recognizes.  Since
5015  * the privilege string separator can be any character, although it is
5016  * usually a comma character, define these here as well in the event that
5017  * they change or are augmented in the future.
5018  */
5019 #define BASIC_TOKEN             "basic"
5020 #define DEFAULT_TOKEN           "default"
5021 #define ZONE_TOKEN              "zone"
5022 #define TOKEN_PRIV_CHAR         ','
5023 #define TOKEN_PRIV_STR          ","
5024 
5025 typedef struct priv_node {
5026         struct priv_node        *pn_next;       /* Next privilege */
5027         char                    *pn_priv;       /* Privileges name */
5028 } priv_node_t;
5029 
5030 /* Privileges lists can differ across brands */
5031 typedef struct priv_lists {
5032         /* Privileges considered safe for all non-global zones of a brand */
5033         struct priv_node        *pl_default;
5034 
5035         /* Privileges not permitted for all non-global zones of a brand */
5036         struct priv_node        *pl_prohibited;
5037 
5038         /* Privileges required for all non-global zones of a brand */
5039         struct priv_node        *pl_required;
5040 
5041         /*
5042          * ip-type of the zone these privileges lists apply to.
5043          * It is used to pass ip-type to the callback function,
5044          * priv_lists_cb, which has no way of getting the ip-type.
5045          */
5046         const char              *pl_iptype;
5047 } priv_lists_t;
5048 
5049 static int
5050 priv_lists_cb(void *data, priv_iter_t *priv_iter)
5051 {
5052         priv_lists_t *plp = (priv_lists_t *)data;
5053         priv_node_t *pnp;
5054 
5055         /* Skip this privilege if ip-type does not match */
5056         if ((strcmp(priv_iter->pi_iptype, "all") != 0) &&
5057             (strcmp(priv_iter->pi_iptype, plp->pl_iptype) != 0))
5058                 return (0);
5059 
5060         /* Allocate a new priv list node. */
5061         if ((pnp = malloc(sizeof (*pnp))) == NULL)
5062                 return (-1);
5063         if ((pnp->pn_priv = strdup(priv_iter->pi_name)) == NULL) {
5064                 free(pnp);
5065                 return (-1);
5066         }
5067 
5068         /* Insert the new priv list node into the right list */
5069         if (strcmp(priv_iter->pi_set, "default") == 0) {
5070                 pnp->pn_next = plp->pl_default;
5071                 plp->pl_default = pnp;
5072         } else if (strcmp(priv_iter->pi_set, "prohibited") == 0) {
5073                 pnp->pn_next = plp->pl_prohibited;
5074                 plp->pl_prohibited = pnp;
5075         } else if (strcmp(priv_iter->pi_set, "required") == 0) {
5076                 pnp->pn_next = plp->pl_required;
5077                 plp->pl_required = pnp;
5078         } else {
5079                 free(pnp->pn_priv);
5080                 free(pnp);
5081                 return (-1);
5082         }
5083         return (0);
5084 }
5085 
5086 static void
5087 priv_lists_destroy(priv_lists_t *plp)
5088 {
5089         priv_node_t *pnp;
5090 
5091         assert(plp != NULL);
5092 
5093         while ((pnp = plp->pl_default) != NULL) {
5094                 plp->pl_default = pnp->pn_next;
5095                 free(pnp->pn_priv);
5096                 free(pnp);
5097         }
5098         while ((pnp = plp->pl_prohibited) != NULL) {
5099                 plp->pl_prohibited = pnp->pn_next;
5100                 free(pnp->pn_priv);
5101                 free(pnp);
5102         }
5103         while ((pnp = plp->pl_required) != NULL) {
5104                 plp->pl_required = pnp->pn_next;
5105                 free(pnp->pn_priv);
5106                 free(pnp);
5107         }
5108         free(plp);
5109 }
5110 
5111 static int
5112 priv_lists_create(zone_dochandle_t handle, char *brand, priv_lists_t **plpp,
5113     const char *curr_iptype)
5114 {
5115         priv_lists_t *plp;
5116         brand_handle_t bh;
5117         char brand_str[MAXNAMELEN];
5118 
5119         /* handle or brand must be set, but never both */
5120         assert((handle != NULL) || (brand != NULL));
5121         assert((handle == NULL) || (brand == NULL));
5122 
5123         if (handle != NULL) {
5124                 brand = brand_str;
5125                 if (zonecfg_get_brand(handle, brand, sizeof (brand_str)) != 0)
5126                         return (Z_BRAND_ERROR);
5127         }
5128 
5129         if ((bh = brand_open(brand)) == NULL)
5130                 return (Z_BRAND_ERROR);
5131 
5132         if ((plp = calloc(1, sizeof (priv_lists_t))) == NULL) {
5133                 brand_close(bh);
5134                 return (Z_NOMEM);
5135         }
5136 
5137         plp->pl_iptype = curr_iptype;
5138 
5139         /* construct the privilege lists */
5140         if (brand_config_iter_privilege(bh, priv_lists_cb, plp) != 0) {
5141                 priv_lists_destroy(plp);
5142                 brand_close(bh);
5143                 return (Z_BRAND_ERROR);
5144         }
5145 
5146         brand_close(bh);
5147         *plpp = plp;
5148         return (Z_OK);
5149 }
5150 
5151 static int
5152 get_default_privset(priv_set_t *privs, priv_lists_t *plp)
5153 {
5154         priv_node_t *pnp;
5155         priv_set_t *basic;
5156 
5157         basic = priv_str_to_set(BASIC_TOKEN, TOKEN_PRIV_STR, NULL);
5158         if (basic == NULL)
5159                 return (errno == ENOMEM ? Z_NOMEM : Z_INVAL);
5160 
5161         priv_union(basic, privs);
5162         priv_freeset(basic);
5163 
5164         for (pnp = plp->pl_default; pnp != NULL; pnp = pnp->pn_next) {
5165                 if (priv_addset(privs, pnp->pn_priv) != 0)
5166                         return (Z_INVAL);
5167         }
5168 
5169         return (Z_OK);
5170 }
5171 
5172 int
5173 zonecfg_default_brand(char *brand, size_t brandsize)
5174 {
5175         zone_dochandle_t handle;
5176         int myzoneid = getzoneid();
5177         int ret;
5178 
5179         /*
5180          * If we're running within a zone, then the default brand is the
5181          * current zone's brand.
5182          */
5183         if (myzoneid != GLOBAL_ZONEID) {
5184                 ret = zone_getattr(myzoneid, ZONE_ATTR_BRAND, brand, brandsize);
5185                 if (ret < 0)
5186                         return ((errno == EFAULT) ? Z_TOO_BIG : Z_INVAL);
5187                 return (Z_OK);
5188         }
5189 
5190         if ((handle = zonecfg_init_handle()) == NULL)
5191                 return (Z_NOMEM);
5192         if ((ret = zonecfg_get_handle("SUNWdefault", handle)) == Z_OK) {
5193                 ret = i_zonecfg_get_brand(handle, brand, brandsize, B_TRUE);
5194                 zonecfg_fini_handle(handle);
5195                 return (ret);
5196         }
5197         return (ret);
5198 }
5199 
5200 int
5201 zonecfg_default_privset(priv_set_t *privs, const char *curr_iptype)
5202 {
5203         priv_lists_t *plp;
5204         char buf[MAXNAMELEN];
5205         int ret;
5206 
5207         if ((ret = zonecfg_default_brand(buf, sizeof (buf))) != Z_OK)
5208                 return (ret);
5209         if ((ret = priv_lists_create(NULL, buf, &plp, curr_iptype)) != Z_OK)
5210                 return (ret);
5211         ret = get_default_privset(privs, plp);
5212         priv_lists_destroy(plp);
5213         return (ret);
5214 }
5215 
5216 void
5217 append_priv_token(char *priv, char *str, size_t strlen)
5218 {
5219         if (*str != '\0')
5220                 (void) strlcat(str, TOKEN_PRIV_STR, strlen);
5221         (void) strlcat(str, priv, strlen);
5222 }
5223 
5224 /*
5225  * Verify that the supplied string is a valid privilege limit set for a
5226  * non-global zone.  This string must not only be acceptable to
5227  * priv_str_to_set(3C) which parses it, but it also must resolve to a
5228  * privilege set that includes certain required privileges and lacks
5229  * certain prohibited privileges.
5230  */
5231 static int
5232 verify_privset(char *privbuf, priv_set_t *privs, char **privname,
5233     boolean_t add_default, priv_lists_t *plp)
5234 {
5235         priv_node_t *pnp;
5236         char *tmp, *cp, *lasts;
5237         size_t len;
5238         priv_set_t *mergeset;
5239         const char *token;
5240 
5241         /*
5242          * The verification of the privilege string occurs in several
5243          * phases.  In the first phase, the supplied string is scanned for
5244          * the ZONE_TOKEN token which is not support as part of the
5245          * "limitpriv" property.
5246          *
5247          * Duplicate the supplied privilege string since strtok_r(3C)
5248          * tokenizes its input by null-terminating the tokens.
5249          */
5250         if ((tmp = strdup(privbuf)) == NULL)
5251                 return (Z_NOMEM);
5252         for (cp = strtok_r(tmp, TOKEN_PRIV_STR, &lasts); cp != NULL;
5253             cp = strtok_r(NULL, TOKEN_PRIV_STR, &lasts)) {
5254                 if (strcmp(cp, ZONE_TOKEN) == 0) {
5255                         free(tmp);
5256                         if ((*privname = strdup(ZONE_TOKEN)) == NULL)
5257                                 return (Z_NOMEM);
5258                         else
5259                                 return (Z_PRIV_UNKNOWN);
5260                 }
5261         }
5262         free(tmp);
5263 
5264         if (add_default) {
5265                 /*
5266                  * If DEFAULT_TOKEN was specified, a string needs to be
5267                  * built containing the privileges from the default, safe
5268                  * set along with those of the "limitpriv" property.
5269                  */
5270                 len = strlen(privbuf) + sizeof (BASIC_TOKEN) + 2;
5271 
5272                 for (pnp = plp->pl_default; pnp != NULL; pnp = pnp->pn_next)
5273                         len += strlen(pnp->pn_priv) + 1;
5274                 tmp = alloca(len);
5275                 *tmp = '\0';
5276 
5277                 append_priv_token(BASIC_TOKEN, tmp, len);
5278                 for (pnp = plp->pl_default; pnp != NULL; pnp = pnp->pn_next)
5279                         append_priv_token(pnp->pn_priv, tmp, len);
5280                 (void) strlcat(tmp, TOKEN_PRIV_STR, len);
5281                 (void) strlcat(tmp, privbuf, len);
5282         } else {
5283                 tmp = privbuf;
5284         }
5285 
5286 
5287         /*
5288          * In the next phase, attempt to convert the merged privilege
5289          * string into a privilege set.  In the case of an error, either
5290          * there was a memory allocation failure or there was an invalid
5291          * privilege token in the string.  In either case, return an
5292          * appropriate error code but in the event of an invalid token,
5293          * allocate a string containing its name and return that back to
5294          * the caller.
5295          */
5296         mergeset = priv_str_to_set(tmp, TOKEN_PRIV_STR, &token);
5297         if (mergeset == NULL) {
5298                 if (token == NULL)
5299                         return (Z_NOMEM);
5300                 if ((cp = strchr(token, TOKEN_PRIV_CHAR)) != NULL)
5301                         *cp = '\0';
5302                 if ((*privname = strdup(token)) == NULL)
5303                         return (Z_NOMEM);
5304                 else
5305                         return (Z_PRIV_UNKNOWN);
5306         }
5307 
5308         /*
5309          * Next, verify that none of the prohibited zone privileges are
5310          * present in the merged privilege set.
5311          */
5312         for (pnp = plp->pl_prohibited; pnp != NULL; pnp = pnp->pn_next) {
5313                 if (priv_ismember(mergeset, pnp->pn_priv)) {
5314                         priv_freeset(mergeset);
5315                         if ((*privname = strdup(pnp->pn_priv)) == NULL)
5316                                 return (Z_NOMEM);
5317                         else
5318                                 return (Z_PRIV_PROHIBITED);
5319                 }
5320         }
5321 
5322         /*
5323          * Finally, verify that all of the required zone privileges are
5324          * present in the merged privilege set.
5325          */
5326         for (pnp = plp->pl_required; pnp != NULL; pnp = pnp->pn_next) {
5327                 if (!priv_ismember(mergeset, pnp->pn_priv)) {
5328                         priv_freeset(mergeset);
5329                         if ((*privname = strdup(pnp->pn_priv)) == NULL)
5330                                 return (Z_NOMEM);
5331                         else
5332                                 return (Z_PRIV_REQUIRED);
5333                 }
5334         }
5335 
5336         priv_copyset(mergeset, privs);
5337         priv_freeset(mergeset);
5338         return (Z_OK);
5339 }
5340 
5341 /*
5342  * Fill in the supplied privilege set with either the default, safe set of
5343  * privileges suitable for a non-global zone, or one based on the
5344  * "limitpriv" property in the zone's configuration.
5345  *
5346  * In the event of an invalid privilege specification in the
5347  * configuration, a string is allocated and returned containing the
5348  * "privilege" causing the issue.  It is the caller's responsibility to
5349  * free this memory when it is done with it.
5350  */
5351 int
5352 zonecfg_get_privset(zone_dochandle_t handle, priv_set_t *privs,
5353     char **privname)
5354 {
5355         priv_lists_t *plp;
5356         char *cp, *limitpriv = NULL;
5357         int err, limitlen;
5358         zone_iptype_t iptype;
5359         const char *curr_iptype;
5360 
5361         /*
5362          * Attempt to lookup the "limitpriv" property.  If it does not
5363          * exist or matches the string DEFAULT_TOKEN exactly, then the
5364          * default, safe privilege set is returned.
5365          */
5366         if ((err = zonecfg_get_limitpriv(handle, &limitpriv)) != Z_OK)
5367                 return (err);
5368 
5369         if ((err = zonecfg_get_iptype(handle, &iptype)) != Z_OK)
5370                 return (err);
5371 
5372         switch (iptype) {
5373         case ZS_SHARED:
5374                 curr_iptype = "shared";
5375                 break;
5376         case ZS_EXCLUSIVE:
5377                 curr_iptype = "exclusive";
5378                 break;
5379         }
5380 
5381         if ((err = priv_lists_create(handle, NULL, &plp, curr_iptype)) != Z_OK)
5382                 return (err);
5383 
5384         limitlen = strlen(limitpriv);
5385         if (limitlen == 0 || strcmp(limitpriv, DEFAULT_TOKEN) == 0) {
5386                 free(limitpriv);
5387                 err = get_default_privset(privs, plp);
5388                 priv_lists_destroy(plp);
5389                 return (err);
5390         }
5391 
5392         /*
5393          * Check if the string DEFAULT_TOKEN is the first token in a list
5394          * of privileges.
5395          */
5396         cp = strchr(limitpriv, TOKEN_PRIV_CHAR);
5397         if (cp != NULL &&
5398             strncmp(limitpriv, DEFAULT_TOKEN, cp - limitpriv) == 0)
5399                 err = verify_privset(cp + 1, privs, privname, B_TRUE, plp);
5400         else
5401                 err = verify_privset(limitpriv, privs, privname, B_FALSE, plp);
5402 
5403         free(limitpriv);
5404         priv_lists_destroy(plp);
5405         return (err);
5406 }
5407 
5408 int
5409 zone_get_zonepath(char *zone_name, char *zonepath, size_t rp_sz)
5410 {
5411         zone_dochandle_t handle;
5412         boolean_t found = B_FALSE;
5413         struct zoneent *ze;
5414         FILE *cookie;
5415         int err;
5416         char *cp;
5417 
5418         if (zone_name == NULL)
5419                 return (Z_INVAL);
5420 
5421         (void) strlcpy(zonepath, zonecfg_root, rp_sz);
5422         cp = zonepath + strlen(zonepath);
5423         while (cp > zonepath && cp[-1] == '/')
5424                 *--cp = '\0';
5425 
5426         if (strcmp(zone_name, GLOBAL_ZONENAME) == 0) {
5427                 if (zonepath[0] == '\0')
5428                         (void) strlcpy(zonepath, "/", rp_sz);
5429                 return (Z_OK);
5430         }
5431 
5432         /*
5433          * First check the index file.  Because older versions did not have
5434          * a copy of the zone path, allow for it to be zero length, in which
5435          * case we ignore this result and fall back to the XML files.
5436          */
5437         cookie = setzoneent();
5438         while ((ze = getzoneent_private(cookie)) != NULL) {
5439                 if (strcmp(ze->zone_name, zone_name) == 0) {
5440                         found = B_TRUE;
5441                         if (ze->zone_path[0] != '\0')
5442                                 (void) strlcpy(cp, ze->zone_path,
5443                                     rp_sz - (cp - zonepath));
5444                 }
5445                 free(ze);
5446                 if (found)
5447                         break;
5448         }
5449         endzoneent(cookie);
5450         if (found && *cp != '\0')
5451                 return (Z_OK);
5452 
5453         /* Fall back to the XML files. */
5454         if ((handle = zonecfg_init_handle()) == NULL)
5455                 return (Z_NOMEM);
5456 
5457         /*
5458          * Check the snapshot first: if a zone is running, its zonepath
5459          * may have changed.
5460          */
5461         if (zonecfg_get_snapshot_handle(zone_name, handle) != Z_OK) {
5462                 if ((err = zonecfg_get_handle(zone_name, handle)) != Z_OK) {
5463                         zonecfg_fini_handle(handle);
5464                         return (err);
5465                 }
5466         }
5467         err = zonecfg_get_zonepath(handle, zonepath, rp_sz);
5468         zonecfg_fini_handle(handle);
5469         return (err);
5470 }
5471 
5472 int
5473 zone_get_rootpath(char *zone_name, char *rootpath, size_t rp_sz)
5474 {
5475         int err;
5476 
5477         /* This function makes sense for non-global zones only. */
5478         if (strcmp(zone_name, GLOBAL_ZONENAME) == 0)
5479                 return (Z_BOGUS_ZONE_NAME);
5480         if ((err = zone_get_zonepath(zone_name, rootpath, rp_sz)) != Z_OK)
5481                 return (err);
5482         if (strlcat(rootpath, "/root", rp_sz) >= rp_sz)
5483                 return (Z_TOO_BIG);
5484         return (Z_OK);
5485 }
5486 
5487 int
5488 zone_get_brand(char *zone_name, char *brandname, size_t rp_sz)
5489 {
5490         int err;
5491         zone_dochandle_t handle;
5492         char myzone[MAXNAMELEN];
5493         int myzoneid = getzoneid();
5494 
5495         /*
5496          * If we are not in the global zone, then we don't have the zone
5497          * .xml files with the brand name available.  Thus, we are going to
5498          * have to ask the kernel for the information.
5499          */
5500         if (myzoneid != GLOBAL_ZONEID) {
5501                 if (is_system_labeled()) {
5502                         (void) strlcpy(brandname, NATIVE_BRAND_NAME, rp_sz);
5503                         return (Z_OK);
5504                 }
5505                 if (zone_getattr(myzoneid, ZONE_ATTR_NAME, myzone,
5506                     sizeof (myzone)) < 0)
5507                         return (Z_NO_ZONE);
5508                 if (!zonecfg_is_scratch(myzone)) {
5509                         if (strncmp(zone_name, myzone, MAXNAMELEN) != 0)
5510                                 return (Z_NO_ZONE);
5511                 }
5512                 err = zone_getattr(myzoneid, ZONE_ATTR_BRAND, brandname, rp_sz);
5513                 if (err < 0)
5514                         return ((errno == EFAULT) ? Z_TOO_BIG : Z_INVAL);
5515 
5516                 return (Z_OK);
5517         }
5518 
5519         if (strcmp(zone_name, "global") == 0)
5520                 return (zonecfg_default_brand(brandname, rp_sz));
5521 
5522         if ((handle = zonecfg_init_handle()) == NULL)
5523                 return (Z_NOMEM);
5524 
5525         err = zonecfg_get_handle((char *)zone_name, handle);
5526         if (err == Z_OK)
5527                 err = zonecfg_get_brand(handle, brandname, rp_sz);
5528 
5529         zonecfg_fini_handle(handle);
5530         return (err);
5531 }
5532 
5533 /*
5534  * Return the appropriate root for the active /dev.
5535  * For normal zone, the path is $ZONEPATH/root;
5536  * for scratch zone, the dev path is $ZONEPATH/lu.
5537  */
5538 int
5539 zone_get_devroot(char *zone_name, char *devroot, size_t rp_sz)
5540 {
5541         int err;
5542         char *suffix;
5543         zone_state_t state;
5544 
5545         /* This function makes sense for non-global zones only. */
5546         if (strcmp(zone_name, GLOBAL_ZONENAME) == 0)
5547                 return (Z_BOGUS_ZONE_NAME);
5548         if ((err = zone_get_zonepath(zone_name, devroot, rp_sz)) != Z_OK)
5549                 return (err);
5550 
5551         if (zone_get_state(zone_name, &state) == Z_OK &&
5552             state == ZONE_STATE_MOUNTED)
5553                 suffix = "/lu";
5554         else
5555                 suffix = "/root";
5556         if (strlcat(devroot, suffix, rp_sz) >= rp_sz)
5557                 return (Z_TOO_BIG);
5558         return (Z_OK);
5559 }
5560 
5561 static zone_state_t
5562 kernel_state_to_user_state(zoneid_t zoneid, zone_status_t kernel_state)
5563 {
5564         char zoneroot[MAXPATHLEN];
5565         size_t zlen;
5566 
5567         assert(kernel_state <= ZONE_MAX_STATE);
5568         switch (kernel_state) {
5569                 case ZONE_IS_UNINITIALIZED:
5570                 case ZONE_IS_INITIALIZED:
5571                         /* The kernel will not return these two states */
5572                         return (ZONE_STATE_READY);
5573                 case ZONE_IS_READY:
5574                         /*
5575                          * If the zone's root is mounted on $ZONEPATH/lu, then
5576                          * it's a mounted scratch zone.
5577                          */
5578                         if (zone_getattr(zoneid, ZONE_ATTR_ROOT, zoneroot,
5579                             sizeof (zoneroot)) >= 0) {
5580                                 zlen = strlen(zoneroot);
5581                                 if (zlen > 3 &&
5582                                     strcmp(zoneroot + zlen - 3, "/lu") == 0)
5583                                         return (ZONE_STATE_MOUNTED);
5584                         }
5585                         return (ZONE_STATE_READY);
5586                 case ZONE_IS_BOOTING:
5587                 case ZONE_IS_RUNNING:
5588                         return (ZONE_STATE_RUNNING);
5589                 case ZONE_IS_SHUTTING_DOWN:
5590                 case ZONE_IS_EMPTY:
5591                         return (ZONE_STATE_SHUTTING_DOWN);
5592                 case ZONE_IS_DOWN:
5593                 case ZONE_IS_DYING:
5594                 case ZONE_IS_DEAD:
5595                 default:
5596                         return (ZONE_STATE_DOWN);
5597         }
5598         /* NOTREACHED */
5599 }
5600 
5601 int
5602 zone_get_state(char *zone_name, zone_state_t *state_num)
5603 {
5604         zone_status_t status;
5605         zoneid_t zone_id;
5606         struct zoneent *ze;
5607         boolean_t found = B_FALSE;
5608         FILE *cookie;
5609         char kernzone[ZONENAME_MAX];
5610         FILE *fp;
5611 
5612         if (zone_name == NULL)
5613                 return (Z_INVAL);
5614 
5615         /*
5616          * If we're looking at an alternate root, then we need to query the
5617          * kernel using the scratch zone name.
5618          */
5619         zone_id = -1;
5620         if (*zonecfg_root != '\0' && !zonecfg_is_scratch(zone_name)) {
5621                 if ((fp = zonecfg_open_scratch("", B_FALSE)) != NULL) {
5622                         if (zonecfg_find_scratch(fp, zone_name, zonecfg_root,
5623                             kernzone, sizeof (kernzone)) == 0)
5624                                 zone_id = getzoneidbyname(kernzone);
5625                         zonecfg_close_scratch(fp);
5626                 }
5627         } else {
5628                 zone_id = getzoneidbyname(zone_name);
5629         }
5630 
5631         /* check to see if zone is running */
5632         if (zone_id != -1 &&
5633             zone_getattr(zone_id, ZONE_ATTR_STATUS, &status,
5634             sizeof (status)) >= 0) {
5635                 *state_num = kernel_state_to_user_state(zone_id, status);
5636                 return (Z_OK);
5637         }
5638 
5639         cookie = setzoneent();
5640         while ((ze = getzoneent_private(cookie)) != NULL) {
5641                 if (strcmp(ze->zone_name, zone_name) == 0) {
5642                         found = B_TRUE;
5643                         *state_num = ze->zone_state;
5644                 }
5645                 free(ze);
5646                 if (found)
5647                         break;
5648         }
5649         endzoneent(cookie);
5650         return ((found) ? Z_OK : Z_NO_ZONE);
5651 }
5652 
5653 int
5654 zone_set_state(char *zone, zone_state_t state)
5655 {
5656         struct zoneent ze;
5657 
5658         if (state != ZONE_STATE_CONFIGURED && state != ZONE_STATE_INSTALLED &&
5659             state != ZONE_STATE_INCOMPLETE)
5660                 return (Z_INVAL);
5661 
5662         bzero(&ze, sizeof (ze));
5663         (void) strlcpy(ze.zone_name, zone, sizeof (ze.zone_name));
5664         ze.zone_state = state;
5665         (void) strlcpy(ze.zone_path, "", sizeof (ze.zone_path));
5666         return (putzoneent(&ze, PZE_MODIFY));
5667 }
5668 
5669 /*
5670  * Get id (if any) for specified zone.  There are four possible outcomes:
5671  * - If the string corresponds to the numeric id of an active (booted)
5672  *   zone, sets *zip to the zone id and returns 0.
5673  * - If the string corresponds to the name of an active (booted) zone,
5674  *   sets *zip to the zone id and returns 0.
5675  * - If the string is a name in the configuration but is not booted,
5676  *   sets *zip to ZONE_ID_UNDEFINED and returns 0.
5677  * - Otherwise, leaves *zip unchanged and returns -1.
5678  *
5679  * This function acts as an auxiliary filter on the function of the same
5680  * name in libc; the linker binds to this version if libzonecfg exists,
5681  * and the libc version if it doesn't.  Any changes to this version of
5682  * the function should probably be reflected in the libc version as well.
5683  */
5684 int
5685 zone_get_id(const char *str, zoneid_t *zip)
5686 {
5687         zone_dochandle_t hdl;
5688         zoneid_t zoneid;
5689         char *cp;
5690         int err;
5691 
5692         /* first try looking for active zone by id */
5693         errno = 0;
5694         zoneid = (zoneid_t)strtol(str, &cp, 0);
5695         if (errno == 0 && cp != str && *cp == '\0' &&
5696             getzonenamebyid(zoneid, NULL, 0) != -1) {
5697                 *zip = zoneid;
5698                 return (0);
5699         }
5700 
5701         /* then look for active zone by name */
5702         if ((zoneid = getzoneidbyname(str)) != -1) {
5703                 *zip = zoneid;
5704                 return (0);
5705         }
5706 
5707         /* if in global zone, try looking up name in configuration database */
5708         if (getzoneid() != GLOBAL_ZONEID ||
5709             (hdl = zonecfg_init_handle()) == NULL)
5710                 return (-1);
5711 
5712         if (zonecfg_get_handle(str, hdl) == Z_OK) {
5713                 /* zone exists but isn't active */
5714                 *zip = ZONE_ID_UNDEFINED;
5715                 err = 0;
5716         } else {
5717                 err = -1;
5718         }
5719 
5720         zonecfg_fini_handle(hdl);
5721         return (err);
5722 }
5723 
5724 char *
5725 zone_state_str(zone_state_t state_num)
5726 {
5727         switch (state_num) {
5728         case ZONE_STATE_CONFIGURED:
5729                 return (ZONE_STATE_STR_CONFIGURED);
5730         case ZONE_STATE_INCOMPLETE:
5731                 return (ZONE_STATE_STR_INCOMPLETE);
5732         case ZONE_STATE_INSTALLED:
5733                 return (ZONE_STATE_STR_INSTALLED);
5734         case ZONE_STATE_READY:
5735                 return (ZONE_STATE_STR_READY);
5736         case ZONE_STATE_MOUNTED:
5737                 return (ZONE_STATE_STR_MOUNTED);
5738         case ZONE_STATE_RUNNING:
5739                 return (ZONE_STATE_STR_RUNNING);
5740         case ZONE_STATE_SHUTTING_DOWN:
5741                 return (ZONE_STATE_STR_SHUTTING_DOWN);
5742         case ZONE_STATE_DOWN:
5743                 return (ZONE_STATE_STR_DOWN);
5744         default:
5745                 return ("unknown");
5746         }
5747 }
5748 
5749 /*
5750  * Given a UUID value, find an associated zone name.  This is intended to be
5751  * used by callers who set up some 'default' name (corresponding to the
5752  * expected name for the zone) in the zonename buffer, and thus the function
5753  * doesn't touch this buffer on failure.
5754  */
5755 int
5756 zonecfg_get_name_by_uuid(const uuid_t uuidin, char *zonename, size_t namelen)
5757 {
5758         FILE *fp;
5759         struct zoneent *ze;
5760         uchar_t *uuid;
5761 
5762         /*
5763          * A small amount of subterfuge via casts is necessary here because
5764          * libuuid doesn't use const correctly, but we don't want to export
5765          * this brokenness to our clients.
5766          */
5767         uuid = (uchar_t *)uuidin;
5768         if (uuid_is_null(uuid))
5769                 return (Z_NO_ZONE);
5770         if ((fp = setzoneent()) == NULL)
5771                 return (Z_NO_ZONE);
5772         while ((ze = getzoneent_private(fp)) != NULL) {
5773                 if (uuid_compare(uuid, ze->zone_uuid) == 0)
5774                         break;
5775                 free(ze);
5776         }
5777         endzoneent(fp);
5778         if (ze != NULL) {
5779                 (void) strlcpy(zonename, ze->zone_name, namelen);
5780                 free(ze);
5781                 return (Z_OK);
5782         } else {
5783                 return (Z_NO_ZONE);
5784         }
5785 }
5786 
5787 /*
5788  * Given a zone name, get its UUID.  Returns a "NULL" UUID value if the zone
5789  * exists but the file doesn't have a value set yet.  Returns an error if the
5790  * zone cannot be located.
5791  */
5792 int
5793 zonecfg_get_uuid(const char *zonename, uuid_t uuid)
5794 {
5795         FILE *fp;
5796         struct zoneent *ze;
5797 
5798         if ((fp = setzoneent()) == NULL)
5799                 return (Z_NO_ZONE);
5800         while ((ze = getzoneent_private(fp)) != NULL) {
5801                 if (strcmp(ze->zone_name, zonename) == 0)
5802                         break;
5803                 free(ze);
5804         }
5805         endzoneent(fp);
5806         if (ze != NULL) {
5807                 uuid_copy(uuid, ze->zone_uuid);
5808                 free(ze);
5809                 return (Z_OK);
5810         } else {
5811                 return (Z_NO_ZONE);
5812         }
5813 }
5814 
5815 /*
5816  * File-system convenience functions.
5817  */
5818 boolean_t
5819 zonecfg_valid_fs_type(const char *type)
5820 {
5821         /*
5822          * We already know which FS types don't work.
5823          */
5824         if (strcmp(type, "proc") == 0 ||
5825             strcmp(type, "mntfs") == 0 ||
5826             strcmp(type, "autofs") == 0 ||
5827             strncmp(type, "nfs", sizeof ("nfs") - 1) == 0)
5828                 return (B_FALSE);
5829         /*
5830          * The caller may do more detailed verification to make sure other
5831          * aspects of this filesystem type make sense.
5832          */
5833         return (B_TRUE);
5834 }
5835 
5836 /*
5837  * Generally uninteresting rctl convenience functions.
5838  */
5839 
5840 int
5841 zonecfg_construct_rctlblk(const struct zone_rctlvaltab *rctlval,
5842     rctlblk_t *rctlblk)
5843 {
5844         unsigned long long ull;
5845         char *endp;
5846         rctl_priv_t priv;
5847         rctl_qty_t limit;
5848         uint_t action;
5849 
5850         /* Get the privilege */
5851         if (strcmp(rctlval->zone_rctlval_priv, "basic") == 0) {
5852                 priv = RCPRIV_BASIC;
5853         } else if (strcmp(rctlval->zone_rctlval_priv, "privileged") == 0) {
5854                 priv = RCPRIV_PRIVILEGED;
5855         } else {
5856                 /* Invalid privilege */
5857                 return (Z_INVAL);
5858         }
5859 
5860         /* deal with negative input; strtoull(3c) doesn't do what we want */
5861         if (rctlval->zone_rctlval_limit[0] == '-')
5862                 return (Z_INVAL);
5863         /* Get the limit */
5864         errno = 0;
5865         ull = strtoull(rctlval->zone_rctlval_limit, &endp, 0);
5866         if (errno != 0 || *endp != '\0') {
5867                 /* parse failed */
5868                 return (Z_INVAL);
5869         }
5870         limit = (rctl_qty_t)ull;
5871 
5872         /* Get the action */
5873         if (strcmp(rctlval->zone_rctlval_action, "none") == 0) {
5874                 action = RCTL_LOCAL_NOACTION;
5875         } else if (strcmp(rctlval->zone_rctlval_action, "signal") == 0) {
5876                 action = RCTL_LOCAL_SIGNAL;
5877         } else if (strcmp(rctlval->zone_rctlval_action, "deny") == 0) {
5878                 action = RCTL_LOCAL_DENY;
5879         } else {
5880                 /* Invalid Action */
5881                 return (Z_INVAL);
5882         }
5883         rctlblk_set_local_action(rctlblk, action, 0);
5884         rctlblk_set_privilege(rctlblk, priv);
5885         rctlblk_set_value(rctlblk, limit);
5886         return (Z_OK);
5887 }
5888 
5889 static int
5890 rctl_check(const char *rctlname, void *arg)
5891 {
5892         const char *attrname = arg;
5893 
5894         /*
5895          * Returning 1 here is our signal to zonecfg_is_rctl() that it is
5896          * indeed an rctl name recognized by the system.
5897          */
5898         return (strcmp(rctlname, attrname) == 0 ? 1 : 0);
5899 }
5900 
5901 boolean_t
5902 zonecfg_is_rctl(const char *name)
5903 {
5904         return (rctl_walk(rctl_check, (void *)name) == 1);
5905 }
5906 
5907 boolean_t
5908 zonecfg_valid_rctlname(const char *name)
5909 {
5910         const char *c;
5911 
5912         if (strncmp(name, "zone.", sizeof ("zone.") - 1) != 0)
5913                 return (B_FALSE);
5914         if (strlen(name) == sizeof ("zone.") - 1)
5915                 return (B_FALSE);
5916         for (c = name + sizeof ("zone.") - 1; *c != '\0'; c++) {
5917                 if (!isalpha(*c) && *c != '-')
5918                         return (B_FALSE);
5919         }
5920         return (B_TRUE);
5921 }
5922 
5923 boolean_t
5924 zonecfg_valid_rctlblk(const rctlblk_t *rctlblk)
5925 {
5926         rctl_priv_t priv = rctlblk_get_privilege((rctlblk_t *)rctlblk);
5927         uint_t action = rctlblk_get_local_action((rctlblk_t *)rctlblk, NULL);
5928 
5929         if (priv != RCPRIV_PRIVILEGED)
5930                 return (B_FALSE);
5931         if (action != RCTL_LOCAL_NOACTION && action != RCTL_LOCAL_DENY)
5932                 return (B_FALSE);
5933         return (B_TRUE);
5934 }
5935 
5936 boolean_t
5937 zonecfg_valid_rctl(const char *name, const rctlblk_t *rctlblk)
5938 {
5939         rctlblk_t *current, *next;
5940         rctl_qty_t limit = rctlblk_get_value((rctlblk_t *)rctlblk);
5941         uint_t action = rctlblk_get_local_action((rctlblk_t *)rctlblk, NULL);
5942         uint_t global_flags;
5943 
5944         if (!zonecfg_valid_rctlblk(rctlblk))
5945                 return (B_FALSE);
5946         if (!zonecfg_valid_rctlname(name))
5947                 return (B_FALSE);
5948 
5949         current = alloca(rctlblk_size());
5950         if (getrctl(name, NULL, current, RCTL_FIRST) != 0)
5951                 return (B_TRUE);        /* not an rctl on this system */
5952         /*
5953          * Make sure the proposed value isn't greater than the current system
5954          * value.
5955          */
5956         next = alloca(rctlblk_size());
5957         while (rctlblk_get_privilege(current) != RCPRIV_SYSTEM) {
5958                 rctlblk_t *tmp;
5959 
5960                 if (getrctl(name, current, next, RCTL_NEXT) != 0)
5961                         return (B_FALSE);       /* shouldn't happen */
5962                 tmp = current;
5963                 current = next;
5964                 next = tmp;
5965         }
5966         if (limit > rctlblk_get_value(current))
5967                 return (B_FALSE);
5968 
5969         /*
5970          * Make sure the proposed action is allowed.
5971          */
5972         global_flags = rctlblk_get_global_flags(current);
5973         if ((global_flags & RCTL_GLOBAL_DENY_NEVER) &&
5974             action == RCTL_LOCAL_DENY)
5975                 return (B_FALSE);
5976         if ((global_flags & RCTL_GLOBAL_DENY_ALWAYS) &&
5977             action == RCTL_LOCAL_NOACTION)
5978                 return (B_FALSE);
5979 
5980         return (B_TRUE);
5981 }
5982 
5983 /*
5984  * There is always a race condition between reading the initial copy of
5985  * a zones state and its state changing.  We address this by providing
5986  * zonecfg_notify_critical_enter and zonecfg_noticy_critical_exit functions.
5987  * When zonecfg_critical_enter is called, sets the state field to LOCKED
5988  * and aquires biglock. Biglock protects against other threads executing
5989  * critical_enter and the state field protects against state changes during
5990  * the critical period.
5991  *
5992  * If any state changes occur, zn_cb will set the failed field of the znotify
5993  * structure.  This will cause the critical_exit function to re-lock the
5994  * channel and return an error. Since evsnts may be delayed, the critical_exit
5995  * function "flushes" the queue by putting an event on the queue and waiting for
5996  * zn_cb to notify critical_exit that it received the ping event.
5997  */
5998 static const char *
5999 string_get_tok(const char *in, char delim, int num)
6000 {
6001         int i = 0;
6002 
6003         for (; i < num; in++) {
6004                 if (*in == delim)
6005                         i++;
6006                 if (*in == 0)
6007                         return (NULL);
6008         }
6009         return (in);
6010 }
6011 
6012 static boolean_t
6013 is_ping(sysevent_t *ev)
6014 {
6015         if (strcmp(sysevent_get_subclass_name(ev),
6016             ZONE_EVENT_PING_SUBCLASS) == 0) {
6017                 return (B_TRUE);
6018         } else {
6019                 return (B_FALSE);
6020         }
6021 }
6022 
6023 static boolean_t
6024 is_my_ping(sysevent_t *ev)
6025 {
6026         const char *sender;
6027         char mypid[sizeof (pid_t) * 3 + 1];
6028 
6029         (void) snprintf(mypid, sizeof (mypid), "%i", getpid());
6030         sender = string_get_tok(sysevent_get_pub(ev), ':', 3);
6031         if (sender == NULL)
6032                 return (B_FALSE);
6033         if (strcmp(sender, mypid) != 0)
6034                 return (B_FALSE);
6035         return (B_TRUE);
6036 }
6037 
6038 static int
6039 do_callback(struct znotify *zevtchan, sysevent_t *ev)
6040 {
6041         nvlist_t *l;
6042         int zid;
6043         char *zonename;
6044         char *newstate;
6045         char *oldstate;
6046         int ret;
6047         hrtime_t when;
6048 
6049         if (strcmp(sysevent_get_subclass_name(ev),
6050             ZONE_EVENT_STATUS_SUBCLASS) == 0) {
6051 
6052                 if (sysevent_get_attr_list(ev, &l) != 0) {
6053                         if (errno == ENOMEM) {
6054                                 zevtchan->zn_failure_count++;
6055                                 return (EAGAIN);
6056                         }
6057                         return (0);
6058                 }
6059                 ret = 0;
6060 
6061                 if ((nvlist_lookup_string(l, ZONE_CB_NAME, &zonename) == 0) &&
6062                     (nvlist_lookup_string(l, ZONE_CB_NEWSTATE, &newstate)
6063                     == 0) &&
6064                     (nvlist_lookup_string(l, ZONE_CB_OLDSTATE, &oldstate)
6065                     == 0) &&
6066                     (nvlist_lookup_uint64(l, ZONE_CB_TIMESTAMP,
6067                     (uint64_t *)&when) == 0) &&
6068                     (nvlist_lookup_int32(l, ZONE_CB_ZONEID, &zid) == 0)) {
6069                         ret = zevtchan->zn_callback(zonename, zid, newstate,
6070                             oldstate, when, zevtchan->zn_private);
6071                 }
6072 
6073                 zevtchan->zn_failure_count = 0;
6074                 nvlist_free(l);
6075                 return (ret);
6076         } else {
6077                 /*
6078                  * We have received an event in an unknown subclass. Ignore.
6079                  */
6080                 zevtchan->zn_failure_count = 0;
6081                 return (0);
6082         }
6083 }
6084 
6085 static int
6086 zn_cb(sysevent_t *ev, void *p)
6087 {
6088         struct znotify *zevtchan = p;
6089         int error;
6090 
6091         (void) pthread_mutex_lock(&(zevtchan->zn_mutex));
6092 
6093         if (is_ping(ev) && !is_my_ping(ev)) {
6094                 (void) pthread_mutex_unlock((&zevtchan->zn_mutex));
6095                 return (0);
6096         }
6097 
6098         if (zevtchan->zn_state == ZN_LOCKED) {
6099                 assert(!is_ping(ev));
6100                 zevtchan->zn_failed = B_TRUE;
6101                 (void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
6102                 return (0);
6103         }
6104 
6105         if (zevtchan->zn_state == ZN_PING_INFLIGHT) {
6106                 if (is_ping(ev)) {
6107                         zevtchan->zn_state = ZN_PING_RECEIVED;
6108                         (void) pthread_cond_signal(&(zevtchan->zn_cond));
6109                         (void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
6110                         return (0);
6111                 } else {
6112                         zevtchan->zn_failed = B_TRUE;
6113                         (void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
6114                         return (0);
6115                 }
6116         }
6117 
6118         if (zevtchan->zn_state == ZN_UNLOCKED) {
6119 
6120                 error = do_callback(zevtchan, ev);
6121                 (void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
6122                 /*
6123                  * Every ENOMEM failure causes do_callback to increment
6124                  * zn_failure_count and every success causes it to
6125                  * set zn_failure_count to zero.  If we got EAGAIN,
6126                  * we will sleep for zn_failure_count seconds and return
6127                  * EAGAIN to gpec to try again.
6128                  *
6129                  * After 55 seconds, or 10 try's we give up and drop the
6130                  * event.
6131                  */
6132                 if (error == EAGAIN) {
6133                         if (zevtchan->zn_failure_count > ZONE_CB_RETRY_COUNT) {
6134                                 return (0);
6135                         }
6136                         (void) sleep(zevtchan->zn_failure_count);
6137                 }
6138                 return (error);
6139         }
6140 
6141         if (zevtchan->zn_state == ZN_PING_RECEIVED) {
6142                 (void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
6143                 return (0);
6144         }
6145 
6146         abort();
6147         return (0);
6148 }
6149 
6150 void
6151 zonecfg_notify_critical_enter(void *h)
6152 {
6153         struct znotify *zevtchan = h;
6154 
6155         (void) pthread_mutex_lock(&(zevtchan->zn_bigmutex));
6156         zevtchan->zn_state = ZN_LOCKED;
6157 }
6158 
6159 int
6160 zonecfg_notify_critical_exit(void * h)
6161 {
6162 
6163         struct znotify *zevtchan = h;
6164 
6165         if (zevtchan->zn_state == ZN_UNLOCKED)
6166                 return (0);
6167 
6168         (void) pthread_mutex_lock(&(zevtchan->zn_mutex));
6169         zevtchan->zn_state = ZN_PING_INFLIGHT;
6170 
6171         (void) sysevent_evc_publish(zevtchan->zn_eventchan,
6172             ZONE_EVENT_STATUS_CLASS,
6173             ZONE_EVENT_PING_SUBCLASS, ZONE_EVENT_PING_PUBLISHER,
6174             zevtchan->zn_subscriber_id, NULL, EVCH_SLEEP);
6175 
6176         while (zevtchan->zn_state != ZN_PING_RECEIVED) {
6177                 (void) pthread_cond_wait(&(zevtchan->zn_cond),
6178                     &(zevtchan->zn_mutex));
6179         }
6180 
6181         if (zevtchan->zn_failed == B_TRUE) {
6182                 zevtchan->zn_state = ZN_LOCKED;
6183                 zevtchan->zn_failed = B_FALSE;
6184                 (void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
6185                 return (1);
6186         }
6187 
6188         zevtchan->zn_state = ZN_UNLOCKED;
6189         (void) pthread_mutex_unlock(&(zevtchan->zn_mutex));
6190         (void) pthread_mutex_unlock(&(zevtchan->zn_bigmutex));
6191         return (0);
6192 }
6193 
6194 void
6195 zonecfg_notify_critical_abort(void *h)
6196 {
6197         struct znotify *zevtchan = h;
6198 
6199         zevtchan->zn_state = ZN_UNLOCKED;
6200         zevtchan->zn_failed = B_FALSE;
6201         /*
6202          * Don't do anything about zn_lock. If it is held, it could only be
6203          * held by zn_cb and it will be unlocked soon.
6204          */
6205         (void) pthread_mutex_unlock(&(zevtchan->zn_bigmutex));
6206 }
6207 
6208 void *
6209 zonecfg_notify_bind(int(*func)(const char *zonename, zoneid_t zid,
6210     const char *newstate, const char *oldstate, hrtime_t when, void *p),
6211     void *p)
6212 {
6213         struct znotify *zevtchan;
6214         int i = 1;
6215         int r;
6216 
6217         zevtchan = malloc(sizeof (struct znotify));
6218 
6219         if (zevtchan == NULL)
6220                 return (NULL);
6221 
6222         zevtchan->zn_private = p;
6223         zevtchan->zn_callback = func;
6224         zevtchan->zn_state = ZN_UNLOCKED;
6225         zevtchan->zn_failed = B_FALSE;
6226 
6227         if (pthread_mutex_init(&(zevtchan->zn_mutex), NULL))
6228                 goto out3;
6229         if (pthread_cond_init(&(zevtchan->zn_cond), NULL)) {
6230                 (void) pthread_mutex_destroy(&(zevtchan->zn_mutex));
6231                 goto out3;
6232         }
6233         if (pthread_mutex_init(&(zevtchan->zn_bigmutex), NULL)) {
6234                 (void) pthread_mutex_destroy(&(zevtchan->zn_mutex));
6235                 (void) pthread_cond_destroy(&(zevtchan->zn_cond));
6236                 goto out3;
6237         }
6238 
6239         if (sysevent_evc_bind(ZONE_EVENT_CHANNEL, &(zevtchan->zn_eventchan),
6240             0) != 0)
6241                 goto out2;
6242 
6243         do {
6244                 /*
6245                  * At 4 digits the subscriber ID gets too long and we have
6246                  * no chance of successfully registering.
6247                  */
6248                 if (i > 999)
6249                         goto out1;
6250 
6251                 (void) sprintf(zevtchan->zn_subscriber_id, "zone_%li_%i",
6252                     getpid() % 999999l, i);
6253 
6254                 r = sysevent_evc_subscribe(zevtchan->zn_eventchan,
6255                     zevtchan->zn_subscriber_id, ZONE_EVENT_STATUS_CLASS, zn_cb,
6256                     zevtchan, 0);
6257 
6258                 i++;
6259 
6260         } while (r);
6261 
6262         return (zevtchan);
6263 out1:
6264         (void) sysevent_evc_unbind(zevtchan->zn_eventchan);
6265 out2:
6266         (void) pthread_mutex_destroy(&zevtchan->zn_mutex);
6267         (void) pthread_cond_destroy(&zevtchan->zn_cond);
6268         (void) pthread_mutex_destroy(&(zevtchan->zn_bigmutex));
6269 out3:
6270         free(zevtchan);
6271 
6272         return (NULL);
6273 }
6274 
6275 void
6276 zonecfg_notify_unbind(void *handle)
6277 {
6278 
6279         int ret;
6280 
6281         (void) sysevent_evc_unbind(((struct znotify *)handle)->zn_eventchan);
6282         /*
6283          * Check that all evc threads have gone away. This should be
6284          * enforced by sysevent_evc_unbind.
6285          */
6286         ret = pthread_mutex_trylock(&((struct znotify *)handle)->zn_mutex);
6287 
6288         if (ret)
6289                 abort();
6290 
6291         (void) pthread_mutex_unlock(&((struct znotify *)handle)->zn_mutex);
6292         (void) pthread_mutex_destroy(&((struct znotify *)handle)->zn_mutex);
6293         (void) pthread_cond_destroy(&((struct znotify *)handle)->zn_cond);
6294         (void) pthread_mutex_destroy(&((struct znotify *)handle)->zn_bigmutex);
6295 
6296         free(handle);
6297 }
6298 
6299 static int
6300 zonecfg_add_ds_core(zone_dochandle_t handle, struct zone_dstab *tabptr)
6301 {
6302         xmlNodePtr newnode, cur = handle->zone_dh_cur;
6303         int err;
6304 
6305         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_DATASET, NULL);
6306         if ((err = newprop(newnode, DTD_ATTR_NAME,
6307             tabptr->zone_dataset_name)) != Z_OK)
6308                 return (err);
6309         return (Z_OK);
6310 }
6311 
6312 int
6313 zonecfg_add_ds(zone_dochandle_t handle, struct zone_dstab *tabptr)
6314 {
6315         int err;
6316 
6317         if (tabptr == NULL)
6318                 return (Z_INVAL);
6319 
6320         if ((err = operation_prep(handle)) != Z_OK)
6321                 return (err);
6322 
6323         if ((err = zonecfg_add_ds_core(handle, tabptr)) != Z_OK)
6324                 return (err);
6325 
6326         return (Z_OK);
6327 }
6328 
6329 static int
6330 zonecfg_delete_ds_core(zone_dochandle_t handle, struct zone_dstab *tabptr)
6331 {
6332         xmlNodePtr cur = handle->zone_dh_cur;
6333 
6334         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
6335                 if (xmlStrcmp(cur->name, DTD_ELEM_DATASET))
6336                         continue;
6337 
6338                 if (match_prop(cur, DTD_ATTR_NAME,
6339                     tabptr->zone_dataset_name)) {
6340                         xmlUnlinkNode(cur);
6341                         xmlFreeNode(cur);
6342                         return (Z_OK);
6343                 }
6344         }
6345         return (Z_NO_RESOURCE_ID);
6346 }
6347 
6348 int
6349 zonecfg_delete_ds(zone_dochandle_t handle, struct zone_dstab *tabptr)
6350 {
6351         int err;
6352 
6353         if (tabptr == NULL)
6354                 return (Z_INVAL);
6355 
6356         if ((err = operation_prep(handle)) != Z_OK)
6357                 return (err);
6358 
6359         if ((err = zonecfg_delete_ds_core(handle, tabptr)) != Z_OK)
6360                 return (err);
6361 
6362         return (Z_OK);
6363 }
6364 
6365 int
6366 zonecfg_modify_ds(
6367         zone_dochandle_t handle,
6368         struct zone_dstab *oldtabptr,
6369         struct zone_dstab *newtabptr)
6370 {
6371         int err;
6372 
6373         if (oldtabptr == NULL || newtabptr == NULL)
6374                 return (Z_INVAL);
6375 
6376         if ((err = operation_prep(handle)) != Z_OK)
6377                 return (err);
6378 
6379         if ((err = zonecfg_delete_ds_core(handle, oldtabptr)) != Z_OK)
6380                 return (err);
6381 
6382         if ((err = zonecfg_add_ds_core(handle, newtabptr)) != Z_OK)
6383                 return (err);
6384 
6385         return (Z_OK);
6386 }
6387 
6388 int
6389 zonecfg_lookup_ds(zone_dochandle_t handle, struct zone_dstab *tabptr)
6390 {
6391         xmlNodePtr cur, firstmatch;
6392         int err;
6393         char dataset[MAXNAMELEN];
6394 
6395         if (tabptr == NULL)
6396                 return (Z_INVAL);
6397 
6398         if ((err = operation_prep(handle)) != Z_OK)
6399                 return (err);
6400 
6401         cur = handle->zone_dh_cur;
6402         firstmatch = NULL;
6403         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
6404                 if (xmlStrcmp(cur->name, DTD_ELEM_DATASET))
6405                         continue;
6406                 if (strlen(tabptr->zone_dataset_name) > 0) {
6407                         if ((fetchprop(cur, DTD_ATTR_NAME, dataset,
6408                             sizeof (dataset)) == Z_OK) &&
6409                             (strcmp(tabptr->zone_dataset_name,
6410                             dataset) == 0)) {
6411                                 if (firstmatch == NULL)
6412                                         firstmatch = cur;
6413                                 else
6414                                         return (Z_INSUFFICIENT_SPEC);
6415                         }
6416                 }
6417         }
6418         if (firstmatch == NULL)
6419                 return (Z_NO_RESOURCE_ID);
6420 
6421         cur = firstmatch;
6422 
6423         if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_dataset_name,
6424             sizeof (tabptr->zone_dataset_name))) != Z_OK)
6425                 return (err);
6426 
6427         return (Z_OK);
6428 }
6429 
6430 int
6431 zonecfg_setdsent(zone_dochandle_t handle)
6432 {
6433         return (zonecfg_setent(handle));
6434 }
6435 
6436 int
6437 zonecfg_getdsent(zone_dochandle_t handle, struct zone_dstab *tabptr)
6438 {
6439         xmlNodePtr cur;
6440         int err;
6441 
6442         if (handle == NULL)
6443                 return (Z_INVAL);
6444 
6445         if ((cur = handle->zone_dh_cur) == NULL)
6446                 return (Z_NO_ENTRY);
6447 
6448         for (; cur != NULL; cur = cur->next)
6449                 if (!xmlStrcmp(cur->name, DTD_ELEM_DATASET))
6450                         break;
6451         if (cur == NULL) {
6452                 handle->zone_dh_cur = handle->zone_dh_top;
6453                 return (Z_NO_ENTRY);
6454         }
6455 
6456         if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_dataset_name,
6457             sizeof (tabptr->zone_dataset_name))) != Z_OK) {
6458                 handle->zone_dh_cur = handle->zone_dh_top;
6459                 return (err);
6460         }
6461 
6462         handle->zone_dh_cur = cur->next;
6463         return (Z_OK);
6464 }
6465 
6466 int
6467 zonecfg_enddsent(zone_dochandle_t handle)
6468 {
6469         return (zonecfg_endent(handle));
6470 }
6471 
6472 /*
6473  * Support for aliased rctls; that is, rctls that have simplified names in
6474  * zonecfg.  For example, max-lwps is an alias for a well defined zone.max-lwps
6475  * rctl.  If there are multiple existing values for one of these rctls or if
6476  * there is a single value that does not match the well defined template (i.e.
6477  * it has a different action) then we cannot treat the rctl as having an alias
6478  * so we return Z_ALIAS_DISALLOW.  That means that the rctl cannot be
6479  * managed in zonecfg via an alias and that the standard rctl syntax must be
6480  * used.
6481  *
6482  * The possible return values are:
6483  *      Z_NO_PROPERTY_ID - invalid alias name
6484  *      Z_ALIAS_DISALLOW - pre-existing, incompatible rctl definition
6485  *      Z_NO_ENTRY - no rctl is configured for this alias
6486  *      Z_OK - we got a valid rctl for the specified alias
6487  */
6488 int
6489 zonecfg_get_aliased_rctl(zone_dochandle_t handle, char *name, uint64_t *rval)
6490 {
6491         boolean_t found = B_FALSE;
6492         boolean_t found_val = B_FALSE;
6493         xmlNodePtr cur, val;
6494         char savedname[MAXNAMELEN];
6495         struct zone_rctlvaltab rctl;
6496         int i;
6497         int err;
6498 
6499         for (i = 0; aliases[i].shortname != NULL; i++)
6500                 if (strcmp(name, aliases[i].shortname) == 0)
6501                         break;
6502 
6503         if (aliases[i].shortname == NULL)
6504                 return (Z_NO_PROPERTY_ID);
6505 
6506         if ((err = operation_prep(handle)) != Z_OK)
6507                 return (err);
6508 
6509         cur = handle->zone_dh_cur;
6510         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
6511                 if (xmlStrcmp(cur->name, DTD_ELEM_RCTL) != 0)
6512                         continue;
6513                 if ((fetchprop(cur, DTD_ATTR_NAME, savedname,
6514                     sizeof (savedname)) == Z_OK) &&
6515                     (strcmp(savedname, aliases[i].realname) == 0)) {
6516 
6517                         /*
6518                          * If we already saw one of these, we can't have an
6519                          * alias since we just found another.
6520                          */
6521                         if (found)
6522                                 return (Z_ALIAS_DISALLOW);
6523                         found = B_TRUE;
6524 
6525                         for (val = cur->xmlChildrenNode; val != NULL;
6526                             val = val->next) {
6527                                 /*
6528                                  * If we already have one value, we can't have
6529                                  * an alias since we just found another.
6530                                  */
6531                                 if (found_val)
6532                                         return (Z_ALIAS_DISALLOW);
6533                                 found_val = B_TRUE;
6534 
6535                                 if ((fetchprop(val, DTD_ATTR_PRIV,
6536                                     rctl.zone_rctlval_priv,
6537                                     sizeof (rctl.zone_rctlval_priv)) != Z_OK))
6538                                         break;
6539                                 if ((fetchprop(val, DTD_ATTR_LIMIT,
6540                                     rctl.zone_rctlval_limit,
6541                                     sizeof (rctl.zone_rctlval_limit)) != Z_OK))
6542                                         break;
6543                                 if ((fetchprop(val, DTD_ATTR_ACTION,
6544                                     rctl.zone_rctlval_action,
6545                                     sizeof (rctl.zone_rctlval_action)) != Z_OK))
6546                                         break;
6547                         }
6548 
6549                         /* check priv and action match the expected vals */
6550                         if (strcmp(rctl.zone_rctlval_priv,
6551                             aliases[i].priv) != 0 ||
6552                             strcmp(rctl.zone_rctlval_action,
6553                             aliases[i].action) != 0)
6554                                 return (Z_ALIAS_DISALLOW);
6555                 }
6556         }
6557 
6558         if (found) {
6559                 *rval = strtoull(rctl.zone_rctlval_limit, NULL, 10);
6560                 return (Z_OK);
6561         }
6562 
6563         return (Z_NO_ENTRY);
6564 }
6565 
6566 int
6567 zonecfg_rm_aliased_rctl(zone_dochandle_t handle, char *name)
6568 {
6569         int i;
6570         uint64_t val;
6571         struct zone_rctltab rctltab;
6572 
6573         /*
6574          * First check that we have a valid aliased rctl to remove.
6575          * This will catch an rctl entry with non-standard values or
6576          * multiple rctl values for this name.  We need to ignore those
6577          * rctl entries.
6578          */
6579         if (zonecfg_get_aliased_rctl(handle, name, &val) != Z_OK)
6580                 return (Z_OK);
6581 
6582         for (i = 0; aliases[i].shortname != NULL; i++)
6583                 if (strcmp(name, aliases[i].shortname) == 0)
6584                         break;
6585 
6586         if (aliases[i].shortname == NULL)
6587                 return (Z_NO_RESOURCE_ID);
6588 
6589         (void) strlcpy(rctltab.zone_rctl_name, aliases[i].realname,
6590             sizeof (rctltab.zone_rctl_name));
6591 
6592         return (zonecfg_delete_rctl(handle, &rctltab));
6593 }
6594 
6595 boolean_t
6596 zonecfg_aliased_rctl_ok(zone_dochandle_t handle, char *name)
6597 {
6598         uint64_t tmp_val;
6599 
6600         switch (zonecfg_get_aliased_rctl(handle, name, &tmp_val)) {
6601         case Z_OK:
6602                 /*FALLTHRU*/
6603         case Z_NO_ENTRY:
6604                 return (B_TRUE);
6605         default:
6606                 return (B_FALSE);
6607         }
6608 }
6609 
6610 int
6611 zonecfg_set_aliased_rctl(zone_dochandle_t handle, char *name, uint64_t val)
6612 {
6613         int i;
6614         int err;
6615         struct zone_rctltab rctltab;
6616         struct zone_rctlvaltab *rctlvaltab;
6617         char buf[128];
6618 
6619         if (!zonecfg_aliased_rctl_ok(handle, name))
6620                 return (Z_ALIAS_DISALLOW);
6621 
6622         for (i = 0; aliases[i].shortname != NULL; i++)
6623                 if (strcmp(name, aliases[i].shortname) == 0)
6624                         break;
6625 
6626         if (aliases[i].shortname == NULL)
6627                 return (Z_NO_RESOURCE_ID);
6628 
6629         /* remove any pre-existing definition for this rctl */
6630         (void) zonecfg_rm_aliased_rctl(handle, name);
6631 
6632         (void) strlcpy(rctltab.zone_rctl_name, aliases[i].realname,
6633             sizeof (rctltab.zone_rctl_name));
6634 
6635         rctltab.zone_rctl_valptr = NULL;
6636 
6637         if ((rctlvaltab = calloc(1, sizeof (struct zone_rctlvaltab))) == NULL)
6638                 return (Z_NOMEM);
6639 
6640         (void) snprintf(buf, sizeof (buf), "%llu", (long long)val);
6641 
6642         (void) strlcpy(rctlvaltab->zone_rctlval_priv, aliases[i].priv,
6643             sizeof (rctlvaltab->zone_rctlval_priv));
6644         (void) strlcpy(rctlvaltab->zone_rctlval_limit, buf,
6645             sizeof (rctlvaltab->zone_rctlval_limit));
6646         (void) strlcpy(rctlvaltab->zone_rctlval_action, aliases[i].action,
6647             sizeof (rctlvaltab->zone_rctlval_action));
6648 
6649         rctlvaltab->zone_rctlval_next = NULL;
6650 
6651         if ((err = zonecfg_add_rctl_value(&rctltab, rctlvaltab)) != Z_OK)
6652                 return (err);
6653 
6654         return (zonecfg_add_rctl(handle, &rctltab));
6655 }
6656 
6657 static int
6658 delete_tmp_pool(zone_dochandle_t handle)
6659 {
6660         int err;
6661         xmlNodePtr cur = handle->zone_dh_cur;
6662 
6663         if ((err = operation_prep(handle)) != Z_OK)
6664                 return (err);
6665 
6666         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
6667                 if (xmlStrcmp(cur->name, DTD_ELEM_TMPPOOL) == 0) {
6668                         xmlUnlinkNode(cur);
6669                         xmlFreeNode(cur);
6670                         return (Z_OK);
6671                 }
6672         }
6673 
6674         return (Z_NO_RESOURCE_ID);
6675 }
6676 
6677 static int
6678 modify_tmp_pool(zone_dochandle_t handle, char *pool_importance)
6679 {
6680         int err;
6681         xmlNodePtr cur = handle->zone_dh_cur;
6682         xmlNodePtr newnode;
6683 
6684         err = delete_tmp_pool(handle);
6685         if (err != Z_OK && err != Z_NO_RESOURCE_ID)
6686                 return (err);
6687 
6688         if (*pool_importance != '\0') {
6689                 if ((err = operation_prep(handle)) != Z_OK)
6690                         return (err);
6691 
6692                 newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_TMPPOOL, NULL);
6693                 if ((err = newprop(newnode, DTD_ATTR_IMPORTANCE,
6694                     pool_importance)) != Z_OK)
6695                         return (err);
6696         }
6697 
6698         return (Z_OK);
6699 }
6700 
6701 static int
6702 add_pset_core(zone_dochandle_t handle, struct zone_psettab *tabptr)
6703 {
6704         xmlNodePtr newnode, cur = handle->zone_dh_cur;
6705         int err;
6706 
6707         newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_PSET, NULL);
6708         if ((err = newprop(newnode, DTD_ATTR_NCPU_MIN,
6709             tabptr->zone_ncpu_min)) != Z_OK)
6710                 return (err);
6711         if ((err = newprop(newnode, DTD_ATTR_NCPU_MAX,
6712             tabptr->zone_ncpu_max)) != Z_OK)
6713                 return (err);
6714 
6715         if ((err = modify_tmp_pool(handle, tabptr->zone_importance)) != Z_OK)
6716                 return (err);
6717 
6718         return (Z_OK);
6719 }
6720 
6721 int
6722 zonecfg_add_pset(zone_dochandle_t handle, struct zone_psettab *tabptr)
6723 {
6724         int err;
6725 
6726         if (tabptr == NULL)
6727                 return (Z_INVAL);
6728 
6729         if ((err = operation_prep(handle)) != Z_OK)
6730                 return (err);
6731 
6732         if ((err = add_pset_core(handle, tabptr)) != Z_OK)
6733                 return (err);
6734 
6735         return (Z_OK);
6736 }
6737 
6738 int
6739 zonecfg_delete_pset(zone_dochandle_t handle)
6740 {
6741         int err;
6742         int res = Z_NO_RESOURCE_ID;
6743         xmlNodePtr cur = handle->zone_dh_cur;
6744 
6745         if ((err = operation_prep(handle)) != Z_OK)
6746                 return (err);
6747 
6748         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
6749                 if (xmlStrcmp(cur->name, DTD_ELEM_PSET) == 0) {
6750                         xmlUnlinkNode(cur);
6751                         xmlFreeNode(cur);
6752                         res = Z_OK;
6753                         break;
6754                 }
6755         }
6756 
6757         /*
6758          * Once we have msets, we should check that a mset
6759          * do not exist before we delete the tmp_pool data.
6760          */
6761         err = delete_tmp_pool(handle);
6762         if (err != Z_OK && err != Z_NO_RESOURCE_ID)
6763                 return (err);
6764 
6765         return (res);
6766 }
6767 
6768 int
6769 zonecfg_modify_pset(zone_dochandle_t handle, struct zone_psettab *tabptr)
6770 {
6771         int err;
6772 
6773         if (tabptr == NULL)
6774                 return (Z_INVAL);
6775 
6776         if ((err = zonecfg_delete_pset(handle)) != Z_OK)
6777                 return (err);
6778 
6779         if ((err = add_pset_core(handle, tabptr)) != Z_OK)
6780                 return (err);
6781 
6782         return (Z_OK);
6783 }
6784 
6785 int
6786 zonecfg_lookup_pset(zone_dochandle_t handle, struct zone_psettab *tabptr)
6787 {
6788         xmlNodePtr cur;
6789         int err;
6790         int res = Z_NO_ENTRY;
6791 
6792         if (tabptr == NULL)
6793                 return (Z_INVAL);
6794 
6795         if ((err = operation_prep(handle)) != Z_OK)
6796                 return (err);
6797 
6798         /* this is an optional component */
6799         tabptr->zone_importance[0] = '\0';
6800 
6801         cur = handle->zone_dh_cur;
6802         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
6803                 if (xmlStrcmp(cur->name, DTD_ELEM_PSET) == 0) {
6804                         if ((err = fetchprop(cur, DTD_ATTR_NCPU_MIN,
6805                             tabptr->zone_ncpu_min,
6806                             sizeof (tabptr->zone_ncpu_min))) != Z_OK) {
6807                                 handle->zone_dh_cur = handle->zone_dh_top;
6808                                 return (err);
6809                         }
6810 
6811                         if ((err = fetchprop(cur, DTD_ATTR_NCPU_MAX,
6812                             tabptr->zone_ncpu_max,
6813                             sizeof (tabptr->zone_ncpu_max))) != Z_OK) {
6814                                 handle->zone_dh_cur = handle->zone_dh_top;
6815                                 return (err);
6816                         }
6817 
6818                         res = Z_OK;
6819 
6820                 } else if (xmlStrcmp(cur->name, DTD_ELEM_TMPPOOL) == 0) {
6821                         if ((err = fetchprop(cur, DTD_ATTR_IMPORTANCE,
6822                             tabptr->zone_importance,
6823                             sizeof (tabptr->zone_importance))) != Z_OK) {
6824                                 handle->zone_dh_cur = handle->zone_dh_top;
6825                                 return (err);
6826                         }
6827                 }
6828         }
6829 
6830         return (res);
6831 }
6832 
6833 int
6834 zonecfg_getpsetent(zone_dochandle_t handle, struct zone_psettab *tabptr)
6835 {
6836         int err;
6837 
6838         if ((err = zonecfg_setent(handle)) != Z_OK)
6839                 return (err);
6840 
6841         err = zonecfg_lookup_pset(handle, tabptr);
6842 
6843         (void) zonecfg_endent(handle);
6844 
6845         return (err);
6846 }
6847 
6848 /*
6849  * Cleanup obsolete constructs in the configuration.
6850  * Return true of the config has been updated and must be commited.
6851  */
6852 int
6853 zonecfg_fix_obsolete(zone_dochandle_t handle)
6854 {
6855         int res = 0;
6856         int add_physmem_rctl = 0;
6857         xmlNodePtr cur;
6858         char    zone_physmem_cap[MAXNAMELEN];
6859 
6860         if (operation_prep(handle) != Z_OK)
6861                 return (res);
6862 
6863         /*
6864          * If an obsolete mcap entry exists, convert it to the rctl.
6865          */
6866         cur = handle->zone_dh_cur;
6867         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
6868                 if (xmlStrcmp(cur->name, DTD_ELEM_MCAP) != 0)
6869                         continue;
6870 
6871                 if (fetchprop(cur, DTD_ATTR_PHYSCAP,
6872                     zone_physmem_cap, sizeof (zone_physmem_cap)) == Z_OK) {
6873                         res = 1;
6874                         add_physmem_rctl = 1;
6875                 }
6876 
6877                 xmlUnlinkNode(cur);
6878                 xmlFreeNode(cur);
6879                 break;
6880         }
6881 
6882         if (add_physmem_rctl) {
6883                 uint64_t cap;
6884                 char *endp;
6885 
6886                 cap = strtoull(zone_physmem_cap, &endp, 10);
6887                 (void) zonecfg_set_aliased_rctl(handle, ALIAS_MAXPHYSMEM, cap);
6888         }
6889 
6890         return (res);
6891 }
6892 
6893 /*
6894  * Get the full tree of pkg metadata in a set of nested AVL trees.
6895  * pkgs_avl is an AVL tree of pkgs.
6896  *
6897  * The zone xml data contains DTD_ELEM_PACKAGE elements.
6898  */
6899 int
6900 zonecfg_getpkgdata(zone_dochandle_t handle, uu_avl_pool_t *pkg_pool,
6901     uu_avl_t *pkgs_avl)
6902 {
6903         xmlNodePtr cur;
6904         int res;
6905         zone_pkg_entry_t *pkg;
6906         char name[MAXNAMELEN];
6907         char version[ZONE_PKG_VERSMAX];
6908 
6909         if (handle == NULL)
6910                 return (Z_INVAL);
6911 
6912         if ((res = zonecfg_setent(handle)) != Z_OK)
6913                 return (res);
6914 
6915         if ((cur = handle->zone_dh_cur) == NULL) {
6916                 res = Z_NO_ENTRY;
6917                 goto done;
6918         }
6919 
6920         for (; cur != NULL; cur = cur->next) {
6921                 if (xmlStrcmp(cur->name, DTD_ELEM_PACKAGE) == 0) {
6922                         uu_avl_index_t where;
6923 
6924                         if ((res = fetchprop(cur, DTD_ATTR_NAME, name,
6925                             sizeof (name))) != Z_OK)
6926                                 goto done;
6927 
6928                         if ((res = fetchprop(cur, DTD_ATTR_VERSION, version,
6929                             sizeof (version))) != Z_OK)
6930                                 goto done;
6931 
6932                         if ((pkg = (zone_pkg_entry_t *)
6933                             malloc(sizeof (zone_pkg_entry_t))) == NULL) {
6934                                 res = Z_NOMEM;
6935                                 goto done;
6936                         }
6937 
6938                         if ((pkg->zpe_name = strdup(name)) == NULL) {
6939                                 free(pkg);
6940                                 res = Z_NOMEM;
6941                                 goto done;
6942                         }
6943 
6944                         if ((pkg->zpe_vers = strdup(version)) == NULL) {
6945                                 free(pkg->zpe_name);
6946                                 free(pkg);
6947                                 res = Z_NOMEM;
6948                                 goto done;
6949                         }
6950 
6951                         uu_avl_node_init(pkg, &pkg->zpe_entry, pkg_pool);
6952                         if (uu_avl_find(pkgs_avl, pkg, NULL, &where) != NULL) {
6953                                 free(pkg->zpe_name);
6954                                 free(pkg->zpe_vers);
6955                                 free(pkg);
6956                         } else {
6957                                 uu_avl_insert(pkgs_avl, pkg, where);
6958                         }
6959                 }
6960         }
6961 
6962 done:
6963         (void) zonecfg_endent(handle);
6964         return (res);
6965 }
6966 
6967 int
6968 zonecfg_setdevperment(zone_dochandle_t handle)
6969 {
6970         return (zonecfg_setent(handle));
6971 }
6972 
6973 int
6974 zonecfg_getdevperment(zone_dochandle_t handle, struct zone_devpermtab *tabptr)
6975 {
6976         xmlNodePtr cur;
6977         int err;
6978         char buf[128];
6979 
6980         tabptr->zone_devperm_acl = NULL;
6981 
6982         if (handle == NULL)
6983                 return (Z_INVAL);
6984 
6985         if ((cur = handle->zone_dh_cur) == NULL)
6986                 return (Z_NO_ENTRY);
6987 
6988         for (; cur != NULL; cur = cur->next)
6989                 if (!xmlStrcmp(cur->name, DTD_ELEM_DEV_PERM))
6990                         break;
6991         if (cur == NULL) {
6992                 handle->zone_dh_cur = handle->zone_dh_top;
6993                 return (Z_NO_ENTRY);
6994         }
6995 
6996         if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_devperm_name,
6997             sizeof (tabptr->zone_devperm_name))) != Z_OK) {
6998                 handle->zone_dh_cur = handle->zone_dh_top;
6999                 return (err);
7000         }
7001 
7002         if ((err = fetchprop(cur, DTD_ATTR_UID, buf, sizeof (buf))) != Z_OK) {
7003                 handle->zone_dh_cur = handle->zone_dh_top;
7004                 return (err);
7005         }
7006         tabptr->zone_devperm_uid = (uid_t)atol(buf);
7007 
7008         if ((err = fetchprop(cur, DTD_ATTR_GID, buf, sizeof (buf))) != Z_OK) {
7009                 handle->zone_dh_cur = handle->zone_dh_top;
7010                 return (err);
7011         }
7012         tabptr->zone_devperm_gid = (gid_t)atol(buf);
7013 
7014         if ((err = fetchprop(cur, DTD_ATTR_MODE, buf, sizeof (buf))) != Z_OK) {
7015                 handle->zone_dh_cur = handle->zone_dh_top;
7016                 return (err);
7017         }
7018         tabptr->zone_devperm_mode = (mode_t)strtol(buf, (char **)NULL, 8);
7019 
7020         if ((err = fetch_alloc_prop(cur, DTD_ATTR_ACL,
7021             &(tabptr->zone_devperm_acl))) != Z_OK) {
7022                 handle->zone_dh_cur = handle->zone_dh_top;
7023                 return (err);
7024         }
7025 
7026         handle->zone_dh_cur = cur->next;
7027         return (Z_OK);
7028 }
7029 
7030 int
7031 zonecfg_enddevperment(zone_dochandle_t handle)
7032 {
7033         return (zonecfg_endent(handle));
7034 }
7035 
7036 /* PRINTFLIKE1 */
7037 static void
7038 zerror(const char *zone_name, const char *fmt, ...)
7039 {
7040         va_list alist;
7041 
7042         va_start(alist, fmt);
7043         (void) fprintf(stderr, "zone '%s': ", zone_name);
7044         (void) vfprintf(stderr, fmt, alist);
7045         (void) fprintf(stderr, "\n");
7046         va_end(alist);
7047 }
7048 
7049 static void
7050 zperror(const char *str)
7051 {
7052         (void) fprintf(stderr, "%s: %s\n", str, strerror(errno));
7053 }
7054 
7055 /*
7056  * The following three routines implement a simple locking mechanism to
7057  * ensure that only one instance of zoneadm at a time is able to manipulate
7058  * a given zone.  The lock is built on top of an fcntl(2) lock of
7059  * [<altroot>]/var/run/zones/<zonename>.zoneadm.lock.  If a zoneadm instance
7060  * can grab that lock, it is allowed to manipulate the zone.
7061  *
7062  * Since zoneadm may call external applications which in turn invoke
7063  * zoneadm again, we introduce the notion of "lock inheritance".  Any
7064  * instance of zoneadm that has another instance in its ancestry is assumed
7065  * to be acting on behalf of the original zoneadm, and is thus allowed to
7066  * manipulate its zone.
7067  *
7068  * This inheritance is implemented via the _ZONEADM_LOCK_HELD environment
7069  * variable.  When zoneadm is granted a lock on its zone, this environment
7070  * variable is set to 1.  When it releases the lock, the variable is set to
7071  * 0.  Since a child process inherits its parent's environment, checking
7072  * the state of this variable indicates whether or not any ancestor owns
7073  * the lock.
7074  */
7075 void
7076 zonecfg_init_lock_file(const char *zone_name, char **lock_env)
7077 {
7078         *lock_env = getenv(LOCK_ENV_VAR);
7079         if (*lock_env == NULL) {
7080                 if (putenv(zoneadm_lock_not_held) != 0) {
7081                         zerror(zone_name, gettext("could not set env: %s"),
7082                             strerror(errno));
7083                         exit(1);
7084                 }
7085         } else {
7086                 if (atoi(*lock_env) == 1)
7087                         zone_lock_cnt = 1;
7088         }
7089 }
7090 
7091 void
7092 zonecfg_release_lock_file(const char *zone_name, int lockfd)
7093 {
7094         /*
7095          * If we are cleaning up from a failed attempt to lock the zone for
7096          * the first time, we might have a zone_lock_cnt of 0.  In that
7097          * error case, we don't want to do anything but close the lock
7098          * file.
7099          */
7100         assert(zone_lock_cnt >= 0);
7101         if (zone_lock_cnt > 0) {
7102                 assert(getenv(LOCK_ENV_VAR) != NULL);
7103                 assert(atoi(getenv(LOCK_ENV_VAR)) == 1);
7104                 if (--zone_lock_cnt > 0) {
7105                         assert(lockfd == -1);
7106                         return;
7107                 }
7108                 if (putenv(zoneadm_lock_not_held) != 0) {
7109                         zerror(zone_name, gettext("could not set env: %s"),
7110                             strerror(errno));
7111                         exit(1);
7112                 }
7113         }
7114         assert(lockfd >= 0);
7115         (void) close(lockfd);
7116 }
7117 
7118 int
7119 zonecfg_grab_lock_file(const char *zone_name, int *lockfd)
7120 {
7121         char pathbuf[PATH_MAX];
7122         struct flock flock;
7123 
7124         /*
7125          * If we already have the lock, we can skip this expensive song
7126          * and dance.
7127          */
7128         assert(zone_lock_cnt >= 0);
7129         assert(getenv(LOCK_ENV_VAR) != NULL);
7130         if (zone_lock_cnt > 0) {
7131                 assert(atoi(getenv(LOCK_ENV_VAR)) == 1);
7132                 zone_lock_cnt++;
7133                 *lockfd = -1;
7134                 return (Z_OK);
7135         }
7136         assert(getenv(LOCK_ENV_VAR) != NULL);
7137         assert(atoi(getenv(LOCK_ENV_VAR)) == 0);
7138 
7139         if (snprintf(pathbuf, sizeof (pathbuf), "%s%s", zonecfg_get_root(),
7140             ZONES_TMPDIR) >= sizeof (pathbuf)) {
7141                 zerror(zone_name, gettext("alternate root path is too long"));
7142                 return (-1);
7143         }
7144         if (mkdir(pathbuf, S_IRWXU) < 0 && errno != EEXIST) {
7145                 zerror(zone_name, gettext("could not mkdir %s: %s"), pathbuf,
7146                     strerror(errno));
7147                 return (-1);
7148         }
7149         (void) chmod(pathbuf, S_IRWXU);
7150 
7151         /*
7152          * One of these lock files is created for each zone (when needed).
7153          * The lock files are not cleaned up (except on system reboot),
7154          * but since there is only one per zone, there is no resource
7155          * starvation issue.
7156          */
7157         if (snprintf(pathbuf, sizeof (pathbuf), "%s%s/%s.zoneadm.lock",
7158             zonecfg_get_root(), ZONES_TMPDIR, zone_name) >= sizeof (pathbuf)) {
7159                 zerror(zone_name, gettext("alternate root path is too long"));
7160                 return (-1);
7161         }
7162         if ((*lockfd = open(pathbuf, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
7163                 zerror(zone_name, gettext("could not open %s: %s"), pathbuf,
7164                     strerror(errno));
7165                 return (-1);
7166         }
7167         /*
7168          * Lock the file to synchronize with other zoneadmds
7169          */
7170         flock.l_type = F_WRLCK;
7171         flock.l_whence = SEEK_SET;
7172         flock.l_start = (off_t)0;
7173         flock.l_len = (off_t)0;
7174         if ((fcntl(*lockfd, F_SETLKW, &flock) < 0) ||
7175             (putenv(zoneadm_lock_held) != 0)) {
7176                 zerror(zone_name, gettext("unable to lock %s: %s"), pathbuf,
7177                     strerror(errno));
7178                 zonecfg_release_lock_file(zone_name, *lockfd);
7179                 return (-1);
7180         }
7181         zone_lock_cnt = 1;
7182         return (Z_OK);
7183 }
7184 
7185 boolean_t
7186 zonecfg_lock_file_held(int *lockfd)
7187 {
7188         if (*lockfd >= 0 || zone_lock_cnt > 0)
7189                 return (B_TRUE);
7190         return (B_FALSE);
7191 }
7192 
7193 static boolean_t
7194 get_doorname(const char *zone_name, char *buffer)
7195 {
7196         return (snprintf(buffer, PATH_MAX, "%s" ZONE_DOOR_PATH,
7197             zonecfg_get_root(), zone_name) < PATH_MAX);
7198 }
7199 
7200 /*
7201  * system daemons are not audited.  For the global zone, this occurs
7202  * "naturally" since init is started with the default audit
7203  * characteristics.  Since zoneadmd is a system daemon and it starts
7204  * init for a zone, it is necessary to clear out the audit
7205  * characteristics inherited from whomever started zoneadmd.  This is
7206  * indicated by the audit id, which is set from the ruid parameter of
7207  * adt_set_user(), below.
7208  */
7209 
7210 static void
7211 prepare_audit_context(const char *zone_name)
7212 {
7213         adt_session_data_t      *ah;
7214         char                    *failure = gettext("audit failure: %s");
7215 
7216         if (adt_start_session(&ah, NULL, 0)) {
7217                 zerror(zone_name, failure, strerror(errno));
7218                 return;
7219         }
7220         if (adt_set_user(ah, ADT_NO_AUDIT, ADT_NO_AUDIT,
7221             ADT_NO_AUDIT, ADT_NO_AUDIT, NULL, ADT_NEW)) {
7222                 zerror(zone_name, failure, strerror(errno));
7223                 (void) adt_end_session(ah);
7224                 return;
7225         }
7226         if (adt_set_proc(ah))
7227                 zerror(zone_name, failure, strerror(errno));
7228 
7229         (void) adt_end_session(ah);
7230 }
7231 
7232 static int
7233 start_zoneadmd(const char *zone_name, boolean_t lock)
7234 {
7235         char doorpath[PATH_MAX];
7236         pid_t child_pid;
7237         int error = -1;
7238         int doorfd, lockfd;
7239         struct door_info info;
7240 
7241         if (!get_doorname(zone_name, doorpath))
7242                 return (-1);
7243 
7244         if (lock)
7245                 if (zonecfg_grab_lock_file(zone_name, &lockfd) != Z_OK)
7246                         return (-1);
7247 
7248         /*
7249          * Now that we have the lock, re-confirm that the daemon is
7250          * *not* up and working fine.  If it is still down, we have a green
7251          * light to start it.
7252          */
7253         if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
7254                 if (errno != ENOENT) {
7255                         zperror(doorpath);
7256                         goto out;
7257                 }
7258         } else {
7259                 if (door_info(doorfd, &info) == 0 &&
7260                     ((info.di_attributes & DOOR_REVOKED) == 0)) {
7261                         error = Z_OK;
7262                         (void) close(doorfd);
7263                         goto out;
7264                 }
7265                 (void) close(doorfd);
7266         }
7267 
7268         if ((child_pid = fork()) == -1) {
7269                 zperror(gettext("could not fork"));
7270                 goto out;
7271         }
7272 
7273         if (child_pid == 0) {
7274                 const char *argv[6], **ap;
7275 
7276                 /* child process */
7277                 prepare_audit_context(zone_name);
7278 
7279                 ap = argv;
7280                 *ap++ = "zoneadmd";
7281                 *ap++ = "-z";
7282                 *ap++ = zone_name;
7283                 if (zonecfg_in_alt_root()) {
7284                         *ap++ = "-R";
7285                         *ap++ = zonecfg_get_root();
7286                 }
7287                 *ap = NULL;
7288 
7289                 (void) execv("/usr/lib/zones/zoneadmd", (char * const *)argv);
7290                 /*
7291                  * TRANSLATION_NOTE
7292                  * zoneadmd is a literal that should not be translated.
7293                  */
7294                 zperror(gettext("could not exec zoneadmd"));
7295                 _exit(1);
7296         } else {
7297                 /* parent process */
7298                 pid_t retval;
7299                 int pstatus = 0;
7300 
7301                 do {
7302                         retval = waitpid(child_pid, &pstatus, 0);
7303                 } while (retval != child_pid);
7304                 if (WIFSIGNALED(pstatus) || (WIFEXITED(pstatus) &&
7305                     WEXITSTATUS(pstatus) != 0)) {
7306                         zerror(zone_name, gettext("could not start %s"),
7307                             "zoneadmd");
7308                         goto out;
7309                 }
7310         }
7311         error = Z_OK;
7312 out:
7313         if (lock)
7314                 zonecfg_release_lock_file(zone_name, lockfd);
7315         return (error);
7316 }
7317 
7318 int
7319 zonecfg_ping_zoneadmd(const char *zone_name)
7320 {
7321         char doorpath[PATH_MAX];
7322         int doorfd;
7323         struct door_info info;
7324 
7325         if (!get_doorname(zone_name, doorpath))
7326                 return (-1);
7327 
7328         if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
7329                 return (-1);
7330         }
7331         if (door_info(doorfd, &info) == 0 &&
7332             ((info.di_attributes & DOOR_REVOKED) == 0)) {
7333                 (void) close(doorfd);
7334                 return (Z_OK);
7335         }
7336         (void) close(doorfd);
7337         return (-1);
7338 }
7339 
7340 int
7341 zonecfg_call_zoneadmd(const char *zone_name, zone_cmd_arg_t *arg, char *locale,
7342     boolean_t lock)
7343 {
7344         char doorpath[PATH_MAX];
7345         int doorfd, result;
7346         door_arg_t darg;
7347 
7348         zoneid_t zoneid;
7349         uint64_t uniqid = 0;
7350 
7351         zone_cmd_rval_t *rvalp;
7352         size_t rlen;
7353         char *cp, *errbuf;
7354 
7355         rlen = getpagesize();
7356         if ((rvalp = malloc(rlen)) == NULL) {
7357                 zerror(zone_name, gettext("failed to allocate %lu bytes: %s"),
7358                     rlen, strerror(errno));
7359                 return (-1);
7360         }
7361 
7362         if ((zoneid = getzoneidbyname(zone_name)) != ZONE_ID_UNDEFINED) {
7363                 (void) zone_getattr(zoneid, ZONE_ATTR_UNIQID, &uniqid,
7364                     sizeof (uniqid));
7365         }
7366         arg->uniqid = uniqid;
7367         (void) strlcpy(arg->locale, locale, sizeof (arg->locale));
7368         if (!get_doorname(zone_name, doorpath)) {
7369                 zerror(zone_name, gettext("alternate root path is too long"));
7370                 free(rvalp);
7371                 return (-1);
7372         }
7373 
7374         /*
7375          * Loop trying to start zoneadmd; if something goes seriously
7376          * wrong we break out and fail.
7377          */
7378         for (;;) {
7379                 if (start_zoneadmd(zone_name, lock) != Z_OK)
7380                         break;
7381 
7382                 if ((doorfd = open(doorpath, O_RDONLY)) < 0) {
7383                         zperror(gettext("failed to open zone door"));
7384                         break;
7385                 }
7386 
7387                 darg.data_ptr = (char *)arg;
7388                 darg.data_size = sizeof (*arg);
7389                 darg.desc_ptr = NULL;
7390                 darg.desc_num = 0;
7391                 darg.rbuf = (char *)rvalp;
7392                 darg.rsize = rlen;
7393                 if (door_call(doorfd, &darg) != 0) {
7394                         (void) close(doorfd);
7395                         /*
7396                          * We'll get EBADF if the door has been revoked.
7397                          */
7398                         if (errno != EBADF) {
7399                                 zperror(gettext("door_call failed"));
7400                                 break;
7401                         }
7402                         continue;       /* take another lap */
7403                 }
7404                 (void) close(doorfd);
7405 
7406                 if (darg.data_size == 0) {
7407                         /* Door server is going away; kick it again. */
7408                         continue;
7409                 }
7410 
7411                 errbuf = rvalp->errbuf;
7412                 while (*errbuf != '\0') {
7413                         /*
7414                          * Remove any newlines since zerror()
7415                          * will append one automatically.
7416                          */
7417                         cp = strchr(errbuf, '\n');
7418                         if (cp != NULL)
7419                                 *cp = '\0';
7420                         zerror(zone_name, "%s", errbuf);
7421                         if (cp == NULL)
7422                                 break;
7423                         errbuf = cp + 1;
7424                 }
7425                 result = rvalp->rval == 0 ? 0 : -1;
7426                 free(rvalp);
7427                 return (result);
7428         }
7429 
7430         free(rvalp);
7431         return (-1);
7432 }
7433 
7434 boolean_t
7435 zonecfg_valid_auths(const char *auths, const char *zonename)
7436 {
7437         char *right;
7438         char *tmpauths;
7439         char *lasts;
7440         char authname[MAXAUTHS];
7441         boolean_t status = B_TRUE;
7442 
7443         tmpauths = strdup(auths);
7444         if (tmpauths == NULL) {
7445                 zerror(zonename, gettext("Out of memory"));
7446                 return (B_FALSE);
7447         }
7448         right = strtok_r(tmpauths, ",", &lasts);
7449         while (right != NULL) {
7450                 (void) snprintf(authname, MAXAUTHS, "%s%s",
7451                     ZONE_AUTH_PREFIX, right);
7452                 if (getauthnam(authname) == NULL) {
7453                         status = B_FALSE;
7454                         zerror(zonename,
7455                             gettext("'%s' is not a valid authorization"),
7456                             right);
7457                 }
7458                 right = strtok_r(NULL, ",", &lasts);
7459         }
7460         free(tmpauths);
7461         return (status);
7462 }
7463 
7464 int
7465 zonecfg_delete_admins(zone_dochandle_t handle, char *zonename)
7466 {
7467         int err;
7468         struct zone_admintab admintab;
7469         boolean_t changed = B_FALSE;
7470 
7471         if ((err = zonecfg_setadminent(handle)) != Z_OK) {
7472                 return (err);
7473         }
7474         while (zonecfg_getadminent(handle, &admintab) == Z_OK) {
7475                 err = zonecfg_delete_admin(handle, &admintab,
7476                     zonename);
7477                 if (err != Z_OK) {
7478                         (void) zonecfg_endadminent(handle);
7479                         return (err);
7480                 } else {
7481                         changed = B_TRUE;
7482                 }
7483                 if ((err = zonecfg_setadminent(handle)) != Z_OK) {
7484                         return (err);
7485                 }
7486         }
7487         (void) zonecfg_endadminent(handle);
7488         return (changed? Z_OK:Z_NO_ENTRY);
7489 }
7490 
7491 /*
7492  * Checks if a long authorization applies to this zone.
7493  * If so, it returns true, after destructively stripping
7494  * the authorization of its prefix and zone suffix.
7495  */
7496 static boolean_t
7497 is_zone_auth(char **auth, char *zonename, char *oldzonename)
7498 {
7499         char *suffix;
7500         size_t offset;
7501 
7502         offset = strlen(ZONE_AUTH_PREFIX);
7503         if ((strncmp(*auth, ZONE_AUTH_PREFIX, offset) == 0) &&
7504             ((suffix = strchr(*auth, '/')) != NULL)) {
7505                 if (strcmp(suffix + 1, zonename) == 0) {
7506                         *auth += offset;
7507                         suffix[0] = '\0';
7508                         return (B_TRUE);
7509                 } else if ((oldzonename != NULL) &&
7510                     (strcmp(suffix + 1, oldzonename) == 0)) {
7511                         *auth += offset;
7512                         suffix[0] = '\0';
7513                         return (B_TRUE);
7514                 }
7515         }
7516         return (B_FALSE);
7517 }
7518 
7519 /*
7520  * This function determines whether the zone-specific authorization
7521  * assignments in /etc/user_attr have been changed more recently
7522  * than the equivalent data stored in the zone's configuration file.
7523  * This should only happen if the zone-specific authorizations in
7524  * the user_attr file were modified using a tool other than zonecfg.
7525  * If the configuration file is out-of-date with respect to these
7526  * authorization assignments, it is updated to match those specified
7527  * in /etc/user_attr.
7528  */
7529 
7530 int
7531 zonecfg_update_userauths(zone_dochandle_t handle, char *zonename)
7532 {
7533         userattr_t *ua_ptr;
7534         char *authlist;
7535         char *lasts;
7536         FILE  *uaf;
7537         struct zone_admintab admintab;
7538         struct stat config_st, ua_st;
7539         char config_file[MAXPATHLEN];
7540         boolean_t changed = B_FALSE;
7541         int err;
7542 
7543         if ((uaf = fopen(USERATTR_FILENAME, "r")) == NULL) {
7544                 zerror(zonename, gettext("could not open file %s: %s"),
7545                     USERATTR_FILENAME, strerror(errno));
7546                 if (errno == EACCES)
7547                         return (Z_ACCES);
7548                 if (errno == ENOENT)
7549                         return (Z_NO_ZONE);
7550                 return (Z_MISC_FS);
7551         }
7552         if ((err = fstat(fileno(uaf), &ua_st)) != 0) {
7553                 zerror(zonename, gettext("could not stat file %s: %s"),
7554                     USERATTR_FILENAME, strerror(errno));
7555                 (void) fclose(uaf);
7556                 return (Z_MISC_FS);
7557         }
7558         if (!config_file_path(zonename, config_file, sizeof (config_file))) {
7559                 (void) fclose(uaf);
7560                 return (Z_MISC_FS);
7561         }
7562 
7563         if ((err = stat(config_file, &config_st)) != 0) {
7564                 zerror(zonename, gettext("could not stat file %s: %s"),
7565                     config_file, strerror(errno));
7566                 (void) fclose(uaf);
7567                 return (Z_MISC_FS);
7568         }
7569         if (config_st.st_mtime >= ua_st.st_mtime) {
7570                 (void) fclose(uaf);
7571                 return (Z_NO_ENTRY);
7572         }
7573         if ((err = zonecfg_delete_admins(handle, zonename)) == Z_OK) {
7574                 changed = B_TRUE;
7575         } else if (err != Z_NO_ENTRY) {
7576                 (void) fclose(uaf);
7577                 return (err);
7578         }
7579         while ((ua_ptr = fgetuserattr(uaf)) != NULL) {
7580                 if (ua_ptr->name[0] == '#') {
7581                         continue;
7582                 }
7583                 authlist = kva_match(ua_ptr->attr, USERATTR_AUTHS_KW);
7584                 if (authlist != NULL) {
7585                         char *cur_auth;
7586                         boolean_t first;
7587 
7588                         first = B_TRUE;
7589                         bzero(&admintab.zone_admin_auths, MAXAUTHS);
7590                         cur_auth = strtok_r(authlist, ",", &lasts);
7591                         while (cur_auth != NULL) {
7592                                 if (is_zone_auth(&cur_auth, zonename,
7593                                     NULL)) {
7594                                         /*
7595                                          * Add auths for this zone
7596                                          */
7597                                         if (first) {
7598                                                 first = B_FALSE;
7599                                         } else {
7600                                                 (void) strlcat(
7601                                                     admintab.zone_admin_auths,
7602                                                     ",", MAXAUTHS);
7603                                         }
7604                                         (void) strlcat(
7605                                             admintab.zone_admin_auths,
7606                                             cur_auth, MAXAUTHS);
7607                                 }
7608                                 cur_auth = strtok_r(NULL, ",", &lasts);
7609                         }
7610                         if (!first) {
7611                                 /*
7612                                  * Add this right to config file
7613                                  */
7614                                 (void) strlcpy(admintab.zone_admin_user,
7615                                     ua_ptr->name,
7616                                     sizeof (admintab.zone_admin_user));
7617                                 err = zonecfg_add_admin(handle,
7618                                     &admintab, zonename);
7619                                 if (err != Z_OK) {
7620                                         (void) fclose(uaf);
7621                                         return (err);
7622                                 } else {
7623                                         changed = B_TRUE;
7624                                 }
7625                         }
7626                 }
7627         } /* end-of-while-loop */
7628         (void) fclose(uaf);
7629         return (changed? Z_OK: Z_NO_ENTRY);
7630 }
7631 
7632 static void
7633 update_profiles(char *rbac_profs, boolean_t add)
7634 {
7635         char new_profs[MAXPROFS];
7636         char *cur_prof;
7637         boolean_t first = B_TRUE;
7638         boolean_t found = B_FALSE;
7639         char *lasts;
7640 
7641         cur_prof = strtok_r(rbac_profs, ",", &lasts);
7642         while (cur_prof != NULL) {
7643                 if (strcmp(cur_prof, ZONE_MGMT_PROF) == 0) {
7644                         found = B_TRUE;
7645                         if (!add) {
7646                                 cur_prof = strtok_r(NULL, ",", &lasts);
7647                                 continue;
7648                         }
7649                 }
7650                 if (first) {
7651                         first = B_FALSE;
7652                 } else {
7653                         (void) strlcat(new_profs, ",",
7654                             MAXPROFS);
7655                 }
7656                 (void) strlcat(new_profs, cur_prof,
7657                     MAXPROFS);
7658                 cur_prof = strtok_r(NULL, ",", &lasts);
7659         }
7660         /*
7661          * Now prepend the Zone Management profile at the beginning
7662          * of the list if it is needed, and append the rest.
7663          * Return the updated list in the original buffer.
7664          */
7665         if (add && !found) {
7666                 first = B_FALSE;
7667                 (void) strlcpy(rbac_profs, ZONE_MGMT_PROF, MAXPROFS);
7668         } else {
7669                 first = B_TRUE;
7670                 rbac_profs[0] = '\0';
7671         }
7672         if (strlen(new_profs) > 0) {
7673                 if (!first)
7674                         (void) strlcat(rbac_profs, ",", MAXPROFS);
7675                 (void) strlcat(rbac_profs, new_profs, MAXPROFS);
7676         }
7677 }
7678 
7679 #define MAX_CMD_LEN     1024
7680 
7681 static int
7682 do_subproc(char *zonename, char *cmdbuf)
7683 {
7684         char inbuf[MAX_CMD_LEN];
7685         FILE *file;
7686         int status;
7687 
7688         file = popen(cmdbuf, "r");
7689         if (file == NULL) {
7690                 zerror(zonename, gettext("Could not launch: %s"), cmdbuf);
7691                 return (-1);
7692         }
7693 
7694         while (fgets(inbuf, sizeof (inbuf), file) != NULL)
7695                 (void) fprintf(stderr, "%s", inbuf);
7696         status = pclose(file);
7697 
7698         if (WIFSIGNALED(status)) {
7699                 zerror(zonename, gettext("%s unexpectedly terminated "
7700                     "due to signal %d"),
7701                     cmdbuf, WTERMSIG(status));
7702                 return (-1);
7703         }
7704         assert(WIFEXITED(status));
7705         return (WEXITSTATUS(status));
7706 }
7707 
7708 /*
7709  * This function updates the local /etc/user_attr file to
7710  * correspond to the admin settings that are currently being
7711  * committed. The updates are done via usermod and/or rolemod
7712  * depending on the type of the specified user. It is also
7713  * invoked to remove entries from user_attr corresponding to
7714  * removed admin assignments, using an empty auths string.
7715  *
7716  * Because the removed entries are no longer included in the
7717  * cofiguration that is being committed, a linked list of
7718  * removed admin entries is maintained to keep track of such
7719  * transactions. The head of the list is stored in the zone_dh_userauths
7720  * element of the handle strcture.
7721  */
7722 static int
7723 zonecfg_authorize_user_impl(zone_dochandle_t handle, char *user,
7724     char *auths, char *zonename)
7725 {
7726         char *right;
7727         char old_auths[MAXAUTHS];
7728         char new_auths[MAXAUTHS];
7729         char rbac_profs[MAXPROFS];
7730         char *lasts;
7731         userattr_t *u;
7732         boolean_t first = B_TRUE;
7733         boolean_t is_zone_admin = B_FALSE;
7734         char user_cmd[] = "/usr/sbin/usermod";
7735         char role_cmd[] = "/usr/sbin/rolemod";
7736         char *auths_cmd = user_cmd;     /* either usermod or rolemod */
7737         char *new_auth_start;           /* string containing the new auths */
7738         int new_auth_cnt = 0;           /* delta of changed authorizations */
7739 
7740         /*
7741          * First get the existing authorizations for this user
7742          */
7743 
7744         bzero(&old_auths, sizeof (old_auths));
7745         bzero(&new_auths, sizeof (new_auths));
7746         bzero(&rbac_profs, sizeof (rbac_profs));
7747         if ((u = getusernam(user)) != NULL) {
7748                 char *current_auths;
7749                 char *current_profs;
7750                 char *type;
7751 
7752                 type = kva_match(u->attr, USERATTR_TYPE_KW);
7753                 if (type != NULL) {
7754                         if (strcmp(type, USERATTR_TYPE_NONADMIN_KW) == 0)
7755                                 auths_cmd = role_cmd;
7756                 }
7757 
7758                 current_auths = kva_match(u->attr, USERATTR_AUTHS_KW);
7759                 if (current_auths != NULL) {
7760                         char *cur_auth;
7761                         char *delete_name;
7762                         size_t offset;
7763 
7764                         offset = strlen(ZONE_AUTH_PREFIX);
7765 
7766                         (void) strlcpy(old_auths, current_auths, MAXAUTHS);
7767                         cur_auth = strtok_r(current_auths, ",", &lasts);
7768 
7769                         /*
7770                          * Next, remove any existing authorizations
7771                          * for this zone, and determine if the
7772                          * user still needs the Zone Management Profile.
7773                          */
7774                         if (is_renaming(handle))
7775                                 delete_name = handle->zone_dh_delete_name;
7776                         else
7777                                 delete_name = NULL;
7778                         while (cur_auth != NULL) {
7779                                 if (!is_zone_auth(&cur_auth, zonename,
7780                                     delete_name)) {
7781                                         if (first) {
7782                                                 first = B_FALSE;
7783                                         } else {
7784                                                 (void) strlcat(new_auths, ",",
7785                                                     MAXAUTHS);
7786                                         }
7787                                         (void) strlcat(new_auths, cur_auth,
7788                                             MAXAUTHS);
7789                                         /*
7790                                          * If the user has authorizations
7791                                          * for other zones, then set a
7792                                          * flag indicate that the Zone
7793                                          * Management profile should be
7794                                          * preserved in user_attr.
7795                                          */
7796                                         if (strncmp(cur_auth,
7797                                             ZONE_AUTH_PREFIX, offset) == 0)
7798                                                 is_zone_admin = B_TRUE;
7799                                 } else {
7800                                         new_auth_cnt++;
7801                                 }
7802                                 cur_auth = strtok_r(NULL, ",", &lasts);
7803                         }
7804                 }
7805                 current_profs = kva_match(u->attr, USERATTR_PROFILES_KW);
7806                 if (current_profs != NULL) {
7807                         (void) strlcpy(rbac_profs, current_profs, MAXPROFS);
7808                 }
7809                 free_userattr(u);
7810         }
7811         /*
7812          * The following is done to avoid revisiting the
7813          * user_attr entry for this user
7814          */
7815         (void) zonecfg_remove_userauths(handle, user, "", B_FALSE);
7816 
7817         /*
7818          * Convert each right into a properly formatted authorization
7819          */
7820         new_auth_start = new_auths + strlen(new_auths);
7821         if (!first)
7822                 new_auth_start++;
7823         right = strtok_r(auths, ",", &lasts);
7824         while (right != NULL) {
7825                 char auth[MAXAUTHS];
7826 
7827                 (void) snprintf(auth, MAXAUTHS, "%s%s/%s",
7828                     ZONE_AUTH_PREFIX, right, zonename);
7829                 if (first) {
7830                         first = B_FALSE;
7831                 } else {
7832                         (void) strlcat(new_auths, ",", MAXAUTHS);
7833                 }
7834                 (void) strlcat(new_auths, auth, MAXAUTHS);
7835                 is_zone_admin = B_TRUE;
7836                 new_auth_cnt--;
7837                 right = strtok_r(NULL, ",", &lasts);
7838         }
7839 
7840         /*
7841          * Need to update the authorizations in user_attr unless
7842          * the number of old and new authorizations is unchanged
7843          * and the new auths are a substrings of the old auths.
7844          *
7845          * If the user's previous authorizations have changed
7846          * execute the usermod progam to update them in user_attr.
7847          */
7848         if ((new_auth_cnt != 0) ||
7849             (strstr(old_auths, new_auth_start) == NULL)) {
7850                 char    *cmdbuf;
7851                 size_t  cmd_len;
7852 
7853                 update_profiles(rbac_profs, is_zone_admin);
7854                 cmd_len = snprintf(NULL, 0, "%s -A \"%s\" -P \"%s\" %s",
7855                     auths_cmd, new_auths, rbac_profs, user) + 1;
7856                 if ((cmdbuf = malloc(cmd_len)) == NULL) {
7857                         return (Z_NOMEM);
7858                 }
7859                 (void) snprintf(cmdbuf, cmd_len, "%s -A \"%s\" -P \"%s\" %s",
7860                     auths_cmd, new_auths, rbac_profs, user);
7861                 if (do_subproc(zonename, cmdbuf) != 0) {
7862                         free(cmdbuf);
7863                         return (Z_SYSTEM);
7864                 }
7865                 free(cmdbuf);
7866         }
7867 
7868         return (Z_OK);
7869 }
7870 
7871 int
7872 zonecfg_authorize_users(zone_dochandle_t handle, char *zonename)
7873 {
7874         xmlNodePtr cur;
7875         int err;
7876         char user[MAXUSERNAME];
7877         char auths[MAXAUTHS];
7878 
7879         if ((err = operation_prep(handle)) != Z_OK)
7880                 return (err);
7881 
7882         cur = handle->zone_dh_cur;
7883         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
7884                 if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
7885                         continue;
7886                 if (fetchprop(cur, DTD_ATTR_USER, user,
7887                     sizeof (user)) != Z_OK)
7888                         continue;
7889                 if (fetchprop(cur, DTD_ATTR_AUTHS, auths,
7890                     sizeof (auths)) != Z_OK)
7891                         continue;
7892                 if (zonecfg_authorize_user_impl(handle, user, auths, zonename)
7893                     != Z_OK)
7894                         return (Z_SYSTEM);
7895         }
7896         (void) zonecfg_remove_userauths(handle, "", "", B_TRUE);
7897 
7898         return (Z_OK);
7899 }
7900 
7901 int
7902 zonecfg_deauthorize_user(zone_dochandle_t handle, char *user, char *zonename)
7903 {
7904         return (zonecfg_authorize_user_impl(handle, user, "", zonename));
7905 }
7906 
7907 int
7908 zonecfg_deauthorize_users(zone_dochandle_t handle, char *zonename)
7909 {
7910         xmlNodePtr cur;
7911         int err;
7912         char user[MAXUSERNAME];
7913 
7914         if ((err = operation_prep(handle)) != Z_OK)
7915                 return (err);
7916 
7917         cur = handle->zone_dh_cur;
7918         for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
7919                 if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
7920                         continue;
7921                 if (fetchprop(cur, DTD_ATTR_USER, user,
7922                     sizeof (user)) != Z_OK)
7923                         continue;
7924                 if ((err = zonecfg_deauthorize_user(handle, user,
7925                     zonename)) != Z_OK)
7926                         return (err);
7927         }
7928         return (Z_OK);
7929 }
7930 
7931 int
7932 zonecfg_insert_userauths(zone_dochandle_t handle, char *user, char *zonename)
7933 {
7934         zone_userauths_t *new, **prev, *next;
7935 
7936         prev = &handle->zone_dh_userauths;
7937         next = *prev;
7938         while (next) {
7939                 if ((strncmp(next->user, user, MAXUSERNAME) == 0) &&
7940                     (strncmp(next->zonename, zonename,
7941                     ZONENAME_MAX) == 0)) {
7942                         /*
7943                          * user is already in list
7944                          * which isn't supposed to happen!
7945                          */
7946                         return (Z_OK);
7947                 }
7948                 prev = &next->next;
7949                 next = *prev;
7950         }
7951         new = (zone_userauths_t *)malloc(sizeof (zone_userauths_t));
7952         if (new == NULL)
7953                 return (Z_NOMEM);
7954 
7955         (void) strlcpy(new->user, user, sizeof (new->user));
7956         (void) strlcpy(new->zonename, zonename, sizeof (new->zonename));
7957         new->next = NULL;
7958         *prev = new;
7959         return (Z_OK);
7960 }
7961 
7962 int
7963 zonecfg_remove_userauths(zone_dochandle_t handle, char *user, char *zonename,
7964         boolean_t deauthorize)
7965 {
7966         zone_userauths_t *new, **prev, *next;
7967 
7968         prev = &handle->zone_dh_userauths;
7969         next = *prev;
7970 
7971         while (next) {
7972                 if ((strlen(user) == 0 ||
7973                     strncmp(next->user, user, MAXUSERNAME) == 0) &&
7974                     (strlen(zonename) == 0 ||
7975                     (strncmp(next->zonename, zonename, ZONENAME_MAX) == 0))) {
7976                         new = next;
7977                         *prev = next->next;
7978                         next =  *prev;
7979                         if (deauthorize)
7980                                 (void) zonecfg_deauthorize_user(handle,
7981                                     new->user, new->zonename);
7982                         free(new);
7983                         continue;
7984                 }
7985                 prev = &next->next;
7986                 next = *prev;
7987         }
7988         return (Z_OK);
7989 }