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