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