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