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