1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2014 Gary Mills
24  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2018, Joyent, Inc.
26  * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
27  */
28 
29 #include <libsysevent.h>
30 #include <pthread.h>
31 #include <stdlib.h>
32 #include <errno.h>
33 #include <fnmatch.h>
34 #include <strings.h>
35 #include <unistd.h>
36 #include <assert.h>
37 #include <libgen.h>
38 #include <libintl.h>
39 #include <alloca.h>
40 #include <ctype.h>
41 #include <sys/acl.h>
42 #include <sys/stat.h>
43 #include <sys/brand.h>
44 #include <sys/mntio.h>
45 #include <sys/mnttab.h>
46 #include <sys/nvpair.h>
47 #include <sys/types.h>
48 #include <sys/sockio.h>
49 #include <sys/systeminfo.h>
50 #include <ftw.h>
51 #include <pool.h>
52 #include <libscf.h>
53 #include <libproc.h>
54 #include <sys/priocntl.h>
55 #include <libuutil.h>
56 #include <wait.h>
57 #include <bsm/adt.h>
58 #include <auth_attr.h>
59 #include <auth_list.h>
60 #include <secdb.h>
61 #include <user_attr.h>
62 #include <prof_attr.h>
63 
64 #include <arpa/inet.h>
65 #include <netdb.h>
66 
67 #include <libxml/xmlmemory.h>
68 #include <libxml/parser.h>
69 
70 #include <libdevinfo.h>
71 #include <uuid/uuid.h>
72 #include <dirent.h>
73 #include <libbrand.h>
74 
75 #include <libzonecfg.h>
76 #include "zonecfg_impl.h"
77 
78 #define	_PATH_TMPFILE	"/zonecfg.XXXXXX"
79 #define	ZONE_CB_RETRY_COUNT		10
80 #define	ZONE_EVENT_PING_SUBCLASS	"ping"
81 #define	ZONE_EVENT_PING_PUBLISHER	"solaris"
82 
83 /* Hard-code the DTD element/attribute/entity names just once, here. */
84 #define	DTD_ELEM_ATTR		(const xmlChar *) "attr"
85 #define	DTD_ELEM_COMMENT	(const xmlChar *) "comment"
86 #define	DTD_ELEM_DEVICE		(const xmlChar *) "device"
87 #define	DTD_ELEM_FS		(const xmlChar *) "filesystem"
88 #define	DTD_ELEM_FSOPTION	(const xmlChar *) "fsoption"
89 #define	DTD_ELEM_NET		(const xmlChar *) "network"
90 #define	DTD_ELEM_RCTL		(const xmlChar *) "rctl"
91 #define	DTD_ELEM_RCTLVALUE	(const xmlChar *) "rctl-value"
92 #define	DTD_ELEM_ZONE		(const xmlChar *) "zone"
93 #define	DTD_ELEM_DATASET	(const xmlChar *) "dataset"
94 #define	DTD_ELEM_TMPPOOL	(const xmlChar *) "tmp_pool"
95 #define	DTD_ELEM_PSET		(const xmlChar *) "pset"
96 #define	DTD_ELEM_MCAP		(const xmlChar *) "mcap"
97 #define	DTD_ELEM_PACKAGE	(const xmlChar *) "package"
98 #define	DTD_ELEM_OBSOLETES	(const xmlChar *) "obsoletes"
99 #define	DTD_ELEM_DEV_PERM	(const xmlChar *) "dev-perm"
100 #define	DTD_ELEM_ADMIN		(const xmlChar *) "admin"
101 #define	DTD_ELEM_SECFLAGS	(const xmlChar *) "security-flags"
102 
103 #define	DTD_ATTR_ACTION		(const xmlChar *) "action"
104 #define	DTD_ATTR_ADDRESS	(const xmlChar *) "address"
105 #define	DTD_ATTR_ALLOWED_ADDRESS	(const xmlChar *) "allowed-address"
106 #define	DTD_ATTR_AUTOBOOT	(const xmlChar *) "autoboot"
107 #define	DTD_ATTR_IPTYPE		(const xmlChar *) "ip-type"
108 #define	DTD_ATTR_DEFROUTER	(const xmlChar *) "defrouter"
109 #define	DTD_ATTR_DIR		(const xmlChar *) "directory"
110 #define	DTD_ATTR_LIMIT		(const xmlChar *) "limit"
111 #define	DTD_ATTR_LIMITPRIV	(const xmlChar *) "limitpriv"
112 #define	DTD_ATTR_BOOTARGS	(const xmlChar *) "bootargs"
113 #define	DTD_ATTR_SCHED		(const xmlChar *) "scheduling-class"
114 #define	DTD_ATTR_MATCH		(const xmlChar *) "match"
115 #define	DTD_ATTR_NAME		(const xmlChar *) "name"
116 #define	DTD_ATTR_PHYSICAL	(const xmlChar *) "physical"
117 #define	DTD_ATTR_POOL		(const xmlChar *) "pool"
118 #define	DTD_ATTR_PRIV		(const xmlChar *) "priv"
119 #define	DTD_ATTR_RAW		(const xmlChar *) "raw"
120 #define	DTD_ATTR_SPECIAL	(const xmlChar *) "special"
121 #define	DTD_ATTR_TYPE		(const xmlChar *) "type"
122 #define	DTD_ATTR_VALUE		(const xmlChar *) "value"
123 #define	DTD_ATTR_ZONEPATH	(const xmlChar *) "zonepath"
124 #define	DTD_ATTR_NCPU_MIN	(const xmlChar *) "ncpu_min"
125 #define	DTD_ATTR_NCPU_MAX	(const xmlChar *) "ncpu_max"
126 #define	DTD_ATTR_IMPORTANCE	(const xmlChar *) "importance"
127 #define	DTD_ATTR_PHYSCAP	(const xmlChar *) "physcap"
128 #define	DTD_ATTR_VERSION	(const xmlChar *) "version"
129 #define	DTD_ATTR_ID		(const xmlChar *) "id"
130 #define	DTD_ATTR_UID		(const xmlChar *) "uid"
131 #define	DTD_ATTR_GID		(const xmlChar *) "gid"
132 #define	DTD_ATTR_MODE		(const xmlChar *) "mode"
133 #define	DTD_ATTR_ACL		(const xmlChar *) "acl"
134 #define	DTD_ATTR_BRAND		(const xmlChar *) "brand"
135 #define	DTD_ATTR_HOSTID		(const xmlChar *) "hostid"
136 #define	DTD_ATTR_USER		(const xmlChar *) "user"
137 #define	DTD_ATTR_AUTHS		(const xmlChar *) "auths"
138 #define	DTD_ATTR_FS_ALLOWED	(const xmlChar *) "fs-allowed"
139 #define	DTD_ATTR_DEFAULT	(const xmlChar *) "default"
140 #define	DTD_ATTR_LOWER		(const xmlChar *) "lower"
141 #define	DTD_ATTR_UPPER		(const xmlChar *) "upper"
142 
143 
144 #define	DTD_ENTITY_BOOLEAN	"boolean"
145 #define	DTD_ENTITY_DEVPATH	"devpath"
146 #define	DTD_ENTITY_DRIVER	"driver"
147 #define	DTD_ENTITY_DRVMIN	"drv_min"
148 #define	DTD_ENTITY_FALSE	"false"
149 #define	DTD_ENTITY_INT		"int"
150 #define	DTD_ENTITY_STRING	"string"
151 #define	DTD_ENTITY_TRUE		"true"
152 #define	DTD_ENTITY_UINT		"uint"
153 
154 #define	DTD_ENTITY_BOOL_LEN	6	/* "false" */
155 
156 #define	ATTACH_FORCED	"SUNWattached.xml"
157 
158 #define	TMP_POOL_NAME	"SUNWtmp_%s"
159 #define	MAX_TMP_POOL_NAME	(ZONENAME_MAX + 9)
160 #define	RCAP_SERVICE	"system/rcap:default"
161 #define	POOLD_SERVICE	"system/pools/dynamic:default"
162 
163 /*
164  * rctl alias definitions
165  *
166  * This holds the alias, the full rctl name, the default priv value, action
167  * and lower limit.  The functions that handle rctl aliases step through
168  * this table, matching on the alias, and using the full values for setting
169  * the rctl entry as well the limit for validation.
170  */
171 static struct alias {
172 	char *shortname;
173 	char *realname;
174 	char *priv;
175 	char *action;
176 	uint64_t low_limit;
177 } aliases[] = {
178 	{ALIAS_MAXLWPS, "zone.max-lwps", "privileged", "deny", 100},
179 	{ALIAS_MAXSHMMEM, "zone.max-shm-memory", "privileged", "deny", 0},
180 	{ALIAS_MAXSHMIDS, "zone.max-shm-ids", "privileged", "deny", 0},
181 	{ALIAS_MAXMSGIDS, "zone.max-msg-ids", "privileged", "deny", 0},
182 	{ALIAS_MAXSEMIDS, "zone.max-sem-ids", "privileged", "deny", 0},
183 	{ALIAS_MAXLOCKEDMEM, "zone.max-locked-memory", "privileged", "deny", 0},
184 	{ALIAS_MAXSWAP, "zone.max-swap", "privileged", "deny", 0},
185 	{ALIAS_SHARES, "zone.cpu-shares", "privileged", "none", 0},
186 	{ALIAS_CPUCAP, "zone.cpu-cap", "privileged", "deny", 0},
187 	{ALIAS_MAXPROCS, "zone.max-processes", "privileged", "deny", 100},
188 	{NULL, NULL, NULL, NULL, 0}
189 };
190 
191 /*
192  * Structure for applying rctls to a running zone.  It allows important
193  * process values to be passed together easily.
194  */
195 typedef struct pr_info_handle {
196 	struct ps_prochandle *pr;
197 	pid_t pid;
198 } pr_info_handle_t;
199 
200 struct zone_dochandle {
201 	char		*zone_dh_rootdir;
202 	xmlDocPtr	zone_dh_doc;
203 	xmlNodePtr	zone_dh_cur;
204 	xmlNodePtr	zone_dh_top;
205 	boolean_t	zone_dh_newzone;
206 	boolean_t	zone_dh_snapshot;
207 	boolean_t	zone_dh_sw_inv;
208 	zone_userauths_t	*zone_dh_userauths;
209 	char		zone_dh_delete_name[ZONENAME_MAX];
210 };
211 
212 struct znotify {
213 	void * zn_private;
214 	evchan_t *zn_eventchan;
215 	int (*zn_callback)(const  char *zonename, zoneid_t zid,
216 	    const char *newstate, const char *oldstate, hrtime_t when, void *p);
217 	pthread_mutex_t zn_mutex;
218 	pthread_cond_t zn_cond;
219 	pthread_mutex_t zn_bigmutex;
220 	volatile enum {ZN_UNLOCKED, ZN_LOCKED, ZN_PING_INFLIGHT,
221 	    ZN_PING_RECEIVED} zn_state;
222 	char zn_subscriber_id[MAX_SUBID_LEN];
223 	volatile boolean_t zn_failed;
224 	int zn_failure_count;
225 };
226 
227 /* used to track nested zone-lock operations */
228 static int zone_lock_cnt = 0;
229 
230 /* used to communicate lock status to children */
231 #define	LOCK_ENV_VAR	"_ZONEADM_LOCK_HELD"
232 static char zoneadm_lock_held[] = LOCK_ENV_VAR"=1";
233 static char zoneadm_lock_not_held[] = LOCK_ENV_VAR"=0";
234 
235 char *zonecfg_root = "";
236 
237 /*
238  * For functions which return int, which is most of the functions herein,
239  * the return values should be from the Z_foo set defined in <libzonecfg.h>.
240  * In some instances, we take pains mapping some libc errno values to Z_foo
241  * values from this set.
242  */
243 
244 /*
245  * Set the root (/) path for all zonecfg configuration files.  This is a
246  * private interface used by Live Upgrade extensions to access zone
247  * configuration inside mounted alternate boot environments.
248  * This interface is also used by zoneadm mount and unmount subcommands.
249  */
250 void
zonecfg_set_root(const char * rootpath)251 zonecfg_set_root(const char *rootpath)
252 {
253 	if (*zonecfg_root != '\0')
254 		free(zonecfg_root);
255 	if (rootpath == NULL || rootpath[0] == '\0' || rootpath[1] == '\0' ||
256 	    (zonecfg_root = strdup(rootpath)) == NULL)
257 		zonecfg_root = "";
258 }
259 
260 const char *
zonecfg_get_root(void)261 zonecfg_get_root(void)
262 {
263 	return (zonecfg_root);
264 }
265 
266 boolean_t
zonecfg_in_alt_root(void)267 zonecfg_in_alt_root(void)
268 {
269 	return (*zonecfg_root != '\0');
270 }
271 
272 /*
273  * Callers of the _file_path() functions are expected to have the second
274  * parameter be a (char foo[MAXPATHLEN]).
275  */
276 
277 static boolean_t
config_file_path(const char * zonename,char * answer)278 config_file_path(const char *zonename, char *answer)
279 {
280 	return (snprintf(answer, MAXPATHLEN, "%s%s/%s.xml", zonecfg_root,
281 	    ZONE_CONFIG_ROOT, zonename) < MAXPATHLEN);
282 }
283 
284 static boolean_t
snap_file_path(const char * zonename,char * answer)285 snap_file_path(const char *zonename, char *answer)
286 {
287 	return (snprintf(answer, MAXPATHLEN, "%s%s/%s.snapshot.xml",
288 	    zonecfg_root, ZONE_SNAPSHOT_ROOT, zonename) < MAXPATHLEN);
289 }
290 
291 /*ARGSUSED*/
292 static void
zonecfg_error_func(void * ctx,const char * msg,...)293 zonecfg_error_func(void *ctx, const char *msg, ...)
294 {
295 	/*
296 	 * This function does nothing by design.  Its purpose is to prevent
297 	 * libxml from dumping unwanted messages to stdout/stderr.
298 	 */
299 }
300 
301 zone_dochandle_t
zonecfg_init_handle(void)302 zonecfg_init_handle(void)
303 {
304 	zone_dochandle_t handle = calloc(1, sizeof (struct zone_dochandle));
305 	if (handle == NULL) {
306 		errno = Z_NOMEM;
307 		return (NULL);
308 	}
309 
310 	/* generic libxml initialization */
311 	(void) xmlLineNumbersDefault(1);
312 	xmlLoadExtDtdDefaultValue |= XML_DETECT_IDS;
313 	xmlDoValidityCheckingDefaultValue = 1;
314 	(void) xmlKeepBlanksDefault(0);
315 	xmlGetWarningsDefaultValue = 0;
316 	xmlSetGenericErrorFunc(NULL, zonecfg_error_func);
317 
318 	return (handle);
319 }
320 
321 int
zonecfg_check_handle(zone_dochandle_t handle)322 zonecfg_check_handle(zone_dochandle_t handle)
323 {
324 	if (handle == NULL || handle->zone_dh_doc == NULL)
325 		return (Z_BAD_HANDLE);
326 	return (Z_OK);
327 }
328 
329 void
zonecfg_fini_handle(zone_dochandle_t handle)330 zonecfg_fini_handle(zone_dochandle_t handle)
331 {
332 	if (zonecfg_check_handle(handle) == Z_OK)
333 		xmlFreeDoc(handle->zone_dh_doc);
334 	if (handle != NULL)
335 		free(handle);
336 }
337 
338 static int
zonecfg_destroy_impl(char * filename)339 zonecfg_destroy_impl(char *filename)
340 {
341 	if (unlink(filename) == -1) {
342 		if (errno == EACCES)
343 			return (Z_ACCES);
344 		if (errno == ENOENT)
345 			return (Z_NO_ZONE);
346 		return (Z_MISC_FS);
347 	}
348 	return (Z_OK);
349 }
350 
351 int
zonecfg_destroy(const char * zonename,boolean_t force)352 zonecfg_destroy(const char *zonename, boolean_t force)
353 {
354 	char path[MAXPATHLEN];
355 	struct zoneent ze;
356 	int err, state_err;
357 	zone_state_t state;
358 
359 	if (!config_file_path(zonename, path))
360 		return (Z_MISC_FS);
361 
362 	state_err = zone_get_state((char *)zonename, &state);
363 	err = access(path, W_OK);
364 
365 	/*
366 	 * If there is no file, and no index entry, reliably indicate that no
367 	 * such zone exists.
368 	 */
369 	if ((state_err == Z_NO_ZONE) && (err == -1) && (errno == ENOENT))
370 		return (Z_NO_ZONE);
371 
372 	/*
373 	 * Handle any other filesystem related errors (except if the XML
374 	 * file is missing, which we treat silently), unless we're forcing,
375 	 * in which case we plow on.
376 	 */
377 	if (err == -1 && errno != ENOENT) {
378 		if (errno == EACCES)
379 			return (Z_ACCES);
380 		else if (!force)
381 			return (Z_MISC_FS);
382 	}
383 
384 	if (state > ZONE_STATE_INSTALLED)
385 		return (Z_BAD_ZONE_STATE);
386 
387 	if (!force && state > ZONE_STATE_CONFIGURED)
388 		return (Z_BAD_ZONE_STATE);
389 
390 	/*
391 	 * Index deletion succeeds even if the entry doesn't exist.  So this
392 	 * will fail only if we've had some more severe problem.
393 	 */
394 	bzero(&ze, sizeof (ze));
395 	(void) strlcpy(ze.zone_name, zonename, sizeof (ze.zone_name));
396 	if ((err = putzoneent(&ze, PZE_REMOVE)) != Z_OK)
397 		if (!force)
398 			return (err);
399 
400 	err = zonecfg_destroy_impl(path);
401 
402 	/*
403 	 * Treat failure to find the XML file silently, since, well, it's
404 	 * gone, and with the index file cleaned up, we're done.
405 	 */
406 	if (err == Z_OK || err == Z_NO_ZONE)
407 		return (Z_OK);
408 	return (err);
409 }
410 
411 int
zonecfg_destroy_snapshot(const char * zonename)412 zonecfg_destroy_snapshot(const char *zonename)
413 {
414 	char path[MAXPATHLEN];
415 
416 	if (!snap_file_path(zonename, path))
417 		return (Z_MISC_FS);
418 	return (zonecfg_destroy_impl(path));
419 }
420 
421 static int
getroot(zone_dochandle_t handle,xmlNodePtr * root)422 getroot(zone_dochandle_t handle, xmlNodePtr *root)
423 {
424 	if (zonecfg_check_handle(handle) == Z_BAD_HANDLE)
425 		return (Z_BAD_HANDLE);
426 
427 	*root = xmlDocGetRootElement(handle->zone_dh_doc);
428 
429 	if (*root == NULL)
430 		return (Z_EMPTY_DOCUMENT);
431 
432 	if (xmlStrcmp((*root)->name, DTD_ELEM_ZONE))
433 		return (Z_WRONG_DOC_TYPE);
434 
435 	return (Z_OK);
436 }
437 
438 static int
operation_prep(zone_dochandle_t handle)439 operation_prep(zone_dochandle_t handle)
440 {
441 	xmlNodePtr root;
442 	int err;
443 
444 	if ((err = getroot(handle, &root)) != 0)
445 		return (err);
446 
447 	handle->zone_dh_cur = root;
448 	handle->zone_dh_top = root;
449 	return (Z_OK);
450 }
451 
452 static int
fetchprop(xmlNodePtr cur,const xmlChar * propname,char * dst,size_t dstsize)453 fetchprop(xmlNodePtr cur, const xmlChar *propname, char *dst, size_t dstsize)
454 {
455 	xmlChar *property;
456 	size_t srcsize;
457 
458 	if ((property = xmlGetProp(cur, propname)) == NULL)
459 		return (Z_BAD_PROPERTY);
460 	srcsize = strlcpy(dst, (char *)property, dstsize);
461 	xmlFree(property);
462 	if (srcsize >= dstsize)
463 		return (Z_TOO_BIG);
464 	return (Z_OK);
465 }
466 
467 static int
fetch_alloc_prop(xmlNodePtr cur,const xmlChar * propname,char ** dst)468 fetch_alloc_prop(xmlNodePtr cur, const xmlChar *propname, char **dst)
469 {
470 	xmlChar *property;
471 
472 	if ((property = xmlGetProp(cur, propname)) == NULL)
473 		return (Z_BAD_PROPERTY);
474 	if ((*dst = strdup((char *)property)) == NULL) {
475 		xmlFree(property);
476 		return (Z_NOMEM);
477 	}
478 	xmlFree(property);
479 	return (Z_OK);
480 }
481 
482 static int
getrootattr(zone_dochandle_t handle,const xmlChar * propname,char * propval,size_t propsize)483 getrootattr(zone_dochandle_t handle, const xmlChar *propname,
484     char *propval, size_t propsize)
485 {
486 	xmlNodePtr root;
487 	int err;
488 
489 	if ((err = getroot(handle, &root)) != 0)
490 		return (err);
491 
492 	return (fetchprop(root, propname, propval, propsize));
493 }
494 
495 static int
get_alloc_rootattr(zone_dochandle_t handle,const xmlChar * propname,char ** propval)496 get_alloc_rootattr(zone_dochandle_t handle, const xmlChar *propname,
497     char **propval)
498 {
499 	xmlNodePtr root;
500 	int err;
501 
502 	if ((err = getroot(handle, &root)) != 0)
503 		return (err);
504 
505 	return (fetch_alloc_prop(root, propname, propval));
506 }
507 
508 static int
setrootattr(zone_dochandle_t handle,const xmlChar * propname,const char * propval)509 setrootattr(zone_dochandle_t handle, const xmlChar *propname,
510     const char *propval)
511 {
512 	int err;
513 	xmlNodePtr root;
514 
515 	if ((err = getroot(handle, &root)) != Z_OK)
516 		return (err);
517 
518 	/*
519 	 * If we get a null propval remove the property (ignore return since it
520 	 * may not be set to begin with).
521 	 */
522 	if (propval == NULL) {
523 		(void) xmlUnsetProp(root, propname);
524 	} else {
525 		if (xmlSetProp(root, propname, (const xmlChar *) propval)
526 		    == NULL)
527 			return (Z_INVAL);
528 	}
529 	return (Z_OK);
530 }
531 
532 static void
addcomment(zone_dochandle_t handle,const char * comment)533 addcomment(zone_dochandle_t handle, const char *comment)
534 {
535 	xmlNodePtr node;
536 	node = xmlNewComment((xmlChar *) comment);
537 
538 	if (node != NULL)
539 		(void) xmlAddPrevSibling(handle->zone_dh_top, node);
540 }
541 
542 static void
stripcomments(zone_dochandle_t handle)543 stripcomments(zone_dochandle_t handle)
544 {
545 	xmlDocPtr top;
546 	xmlNodePtr child, next;
547 
548 	top = handle->zone_dh_doc;
549 	for (child = top->xmlChildrenNode; child != NULL; child = next) {
550 		next = child->next;
551 		if (child->name == NULL)
552 			continue;
553 		if (xmlStrcmp(child->name, DTD_ELEM_COMMENT) == 0) {
554 			next = child->next;
555 			xmlUnlinkNode(child);
556 			xmlFreeNode(child);
557 		}
558 	}
559 }
560 
561 static void
strip_sw_inv(zone_dochandle_t handle)562 strip_sw_inv(zone_dochandle_t handle)
563 {
564 	xmlNodePtr root, child, next;
565 
566 	root = xmlDocGetRootElement(handle->zone_dh_doc);
567 	for (child = root->xmlChildrenNode; child != NULL; child = next) {
568 		next = child->next;
569 		if (child->name == NULL)
570 			continue;
571 		if (xmlStrcmp(child->name, DTD_ELEM_PACKAGE) == 0) {
572 			next = child->next;
573 			xmlUnlinkNode(child);
574 			xmlFreeNode(child);
575 		}
576 	}
577 }
578 
579 static int
zonecfg_get_handle_impl(const char * zonename,const char * filename,zone_dochandle_t handle)580 zonecfg_get_handle_impl(const char *zonename, const char *filename,
581     zone_dochandle_t handle)
582 {
583 	xmlValidCtxtPtr cvp;
584 	struct stat statbuf;
585 	int valid;
586 
587 	if (zonename == NULL)
588 		return (Z_NO_ZONE);
589 
590 	if ((handle->zone_dh_doc = xmlParseFile(filename)) == NULL) {
591 		/* distinguish file not found vs. found but not parsed */
592 		if (stat(filename, &statbuf) == 0)
593 			return (Z_INVALID_DOCUMENT);
594 		return (Z_NO_ZONE);
595 	}
596 	if ((cvp = xmlNewValidCtxt()) == NULL)
597 		return (Z_NOMEM);
598 	cvp->error = zonecfg_error_func;
599 	cvp->warning = zonecfg_error_func;
600 	valid = xmlValidateDocument(cvp, handle->zone_dh_doc);
601 	xmlFreeValidCtxt(cvp);
602 	if (valid == 0)
603 		return (Z_INVALID_DOCUMENT);
604 
605 	/* delete any comments such as inherited Sun copyright / ident str */
606 	stripcomments(handle);
607 	return (Z_OK);
608 }
609 
610 int
zonecfg_get_handle(const char * zonename,zone_dochandle_t handle)611 zonecfg_get_handle(const char *zonename, zone_dochandle_t handle)
612 {
613 	char path[MAXPATHLEN];
614 
615 	if (!config_file_path(zonename, path))
616 		return (Z_MISC_FS);
617 	handle->zone_dh_newzone = B_FALSE;
618 
619 	return (zonecfg_get_handle_impl(zonename, path, handle));
620 }
621 
622 int
zonecfg_get_attach_handle(const char * path,const char * fname,const char * zonename,boolean_t preserve_sw,zone_dochandle_t handle)623 zonecfg_get_attach_handle(const char *path, const char *fname,
624     const char *zonename, boolean_t preserve_sw, zone_dochandle_t handle)
625 {
626 	char		migpath[MAXPATHLEN];
627 	int		err;
628 	struct stat	buf;
629 
630 	if (snprintf(migpath, sizeof (migpath), "%s/root", path) >=
631 	    sizeof (migpath))
632 		return (Z_NOMEM);
633 
634 	if (stat(migpath, &buf) == -1 || !S_ISDIR(buf.st_mode))
635 		return (Z_NO_ZONE);
636 
637 	if (snprintf(migpath, sizeof (migpath), "%s/%s", path, fname) >=
638 	    sizeof (migpath))
639 		return (Z_NOMEM);
640 
641 	if ((err = zonecfg_get_handle_impl(zonename, migpath, handle)) != Z_OK)
642 		return (err);
643 
644 	if (!preserve_sw)
645 		strip_sw_inv(handle);
646 
647 	handle->zone_dh_newzone = B_TRUE;
648 	if ((err = setrootattr(handle, DTD_ATTR_ZONEPATH, path)) != Z_OK)
649 		return (err);
650 
651 	return (setrootattr(handle, DTD_ATTR_NAME, zonename));
652 }
653 
654 int
zonecfg_get_snapshot_handle(const char * zonename,zone_dochandle_t handle)655 zonecfg_get_snapshot_handle(const char *zonename, zone_dochandle_t handle)
656 {
657 	char path[MAXPATHLEN];
658 
659 	if (!snap_file_path(zonename, path))
660 		return (Z_MISC_FS);
661 	handle->zone_dh_newzone = B_FALSE;
662 	return (zonecfg_get_handle_impl(zonename, path, handle));
663 }
664 
665 int
zonecfg_get_template_handle(const char * template,const char * zonename,zone_dochandle_t handle)666 zonecfg_get_template_handle(const char *template, const char *zonename,
667     zone_dochandle_t handle)
668 {
669 	char path[MAXPATHLEN];
670 	int err;
671 
672 	if (!config_file_path(template, path))
673 		return (Z_MISC_FS);
674 
675 	if ((err = zonecfg_get_handle_impl(template, path, handle)) != Z_OK)
676 		return (err);
677 	handle->zone_dh_newzone = B_TRUE;
678 	return (setrootattr(handle, DTD_ATTR_NAME, zonename));
679 }
680 
681 int
zonecfg_get_xml_handle(const char * path,zone_dochandle_t handle)682 zonecfg_get_xml_handle(const char *path, zone_dochandle_t handle)
683 {
684 	struct stat buf;
685 	int err;
686 
687 	if (stat(path, &buf) == -1)
688 		return (Z_MISC_FS);
689 
690 	if ((err = zonecfg_get_handle_impl("xml", path, handle)) != Z_OK)
691 		return (err);
692 	handle->zone_dh_newzone = B_TRUE;
693 	return (Z_OK);
694 }
695 
696 /*
697  * Initialize two handles from the manifest read on fd.  The rem_handle
698  * is initialized from the input file, including the sw inventory.  The
699  * local_handle is initialized with the same zone configuration but with
700  * no sw inventory.
701  */
702 int
zonecfg_attach_manifest(int fd,zone_dochandle_t local_handle,zone_dochandle_t rem_handle)703 zonecfg_attach_manifest(int fd, zone_dochandle_t local_handle,
704     zone_dochandle_t rem_handle)
705 {
706 	xmlValidCtxtPtr cvp;
707 	int valid;
708 
709 	/* load the manifest into the handle for the remote system */
710 	if ((rem_handle->zone_dh_doc = xmlReadFd(fd, NULL, NULL, 0)) == NULL) {
711 		return (Z_INVALID_DOCUMENT);
712 	}
713 	if ((cvp = xmlNewValidCtxt()) == NULL)
714 		return (Z_NOMEM);
715 	cvp->error = zonecfg_error_func;
716 	cvp->warning = zonecfg_error_func;
717 	valid = xmlValidateDocument(cvp, rem_handle->zone_dh_doc);
718 	xmlFreeValidCtxt(cvp);
719 	if (valid == 0)
720 		return (Z_INVALID_DOCUMENT);
721 
722 	/* delete any comments such as inherited Sun copyright / ident str */
723 	stripcomments(rem_handle);
724 
725 	rem_handle->zone_dh_newzone = B_TRUE;
726 	rem_handle->zone_dh_sw_inv = B_TRUE;
727 
728 	/*
729 	 * Now use the remote system handle to generate a local system handle
730 	 * with an identical zones configuration but no sw inventory.
731 	 */
732 	if ((local_handle->zone_dh_doc = xmlCopyDoc(rem_handle->zone_dh_doc,
733 	    1)) == NULL) {
734 		return (Z_INVALID_DOCUMENT);
735 	}
736 
737 	/*
738 	 * We need to re-run xmlValidateDocument on local_handle to properly
739 	 * update the in-core representation of the configuration.
740 	 */
741 	if ((cvp = xmlNewValidCtxt()) == NULL)
742 		return (Z_NOMEM);
743 	cvp->error = zonecfg_error_func;
744 	cvp->warning = zonecfg_error_func;
745 	valid = xmlValidateDocument(cvp, local_handle->zone_dh_doc);
746 	xmlFreeValidCtxt(cvp);
747 	if (valid == 0)
748 		return (Z_INVALID_DOCUMENT);
749 
750 	strip_sw_inv(local_handle);
751 
752 	local_handle->zone_dh_newzone = B_TRUE;
753 	local_handle->zone_dh_sw_inv = B_FALSE;
754 
755 	return (Z_OK);
756 }
757 
758 static boolean_t
is_renaming(zone_dochandle_t handle)759 is_renaming(zone_dochandle_t handle)
760 {
761 	if (handle->zone_dh_newzone)
762 		return (B_FALSE);
763 	if (strlen(handle->zone_dh_delete_name) > 0)
764 		return (B_TRUE);
765 	return (B_FALSE);
766 }
767 
768 static boolean_t
is_new(zone_dochandle_t handle)769 is_new(zone_dochandle_t handle)
770 {
771 	return (handle->zone_dh_newzone || handle->zone_dh_snapshot);
772 }
773 
774 static boolean_t
is_snapshot(zone_dochandle_t handle)775 is_snapshot(zone_dochandle_t handle)
776 {
777 	return (handle->zone_dh_snapshot);
778 }
779 
780 /*
781  * It would be great to be able to use libc's ctype(3c) macros, but we
782  * can't, as they are locale sensitive, and it would break our limited thread
783  * safety if this routine had to change the app locale on the fly.
784  */
785 int
zonecfg_validate_zonename(const char * zone)786 zonecfg_validate_zonename(const char *zone)
787 {
788 	int i;
789 
790 	if (strcmp(zone, GLOBAL_ZONENAME) == 0)
791 		return (Z_BOGUS_ZONE_NAME);
792 
793 	if (strlen(zone) >= ZONENAME_MAX)
794 		return (Z_BOGUS_ZONE_NAME);
795 
796 	if (!((zone[0] >= 'a' && zone[0] <= 'z') ||
797 	    (zone[0] >= 'A' && zone[0] <= 'Z') ||
798 	    (zone[0] >= '0' && zone[0] <= '9')))
799 		return (Z_BOGUS_ZONE_NAME);
800 
801 	for (i = 1; zone[i] != '\0'; i++) {
802 		if (!((zone[i] >= 'a' && zone[i] <= 'z') ||
803 		    (zone[i] >= 'A' && zone[i] <= 'Z') ||
804 		    (zone[i] >= '0' && zone[i] <= '9') ||
805 		    (zone[i] == '-') || (zone[i] == '_') || (zone[i] == '.')))
806 			return (Z_BOGUS_ZONE_NAME);
807 	}
808 
809 	return (Z_OK);
810 }
811 
812 /*
813  * Changing the zone name requires us to track both the old and new
814  * name of the zone until commit time.
815  */
816 int
zonecfg_get_name(zone_dochandle_t handle,char * name,size_t namesize)817 zonecfg_get_name(zone_dochandle_t handle, char *name, size_t namesize)
818 {
819 	return (getrootattr(handle, DTD_ATTR_NAME, name, namesize));
820 }
821 
822 static int
insert_admins(zone_dochandle_t handle,char * zonename)823 insert_admins(zone_dochandle_t handle, char *zonename)
824 {
825 	int err;
826 	struct zone_admintab admintab;
827 
828 	if ((err = zonecfg_setadminent(handle)) != Z_OK) {
829 		return (err);
830 	}
831 	while (zonecfg_getadminent(handle, &admintab) == Z_OK) {
832 		err = zonecfg_insert_userauths(handle,
833 		    admintab.zone_admin_user, zonename);
834 		if (err != Z_OK) {
835 			(void) zonecfg_endadminent(handle);
836 			return (err);
837 		}
838 	}
839 	(void) zonecfg_endadminent(handle);
840 	return (Z_OK);
841 }
842 
843 int
zonecfg_set_name(zone_dochandle_t handle,char * name)844 zonecfg_set_name(zone_dochandle_t handle, char *name)
845 {
846 	zone_state_t state;
847 	char curname[ZONENAME_MAX], old_delname[ZONENAME_MAX];
848 	int err;
849 
850 	if ((err = getrootattr(handle, DTD_ATTR_NAME, curname,
851 	    sizeof (curname))) != Z_OK)
852 		return (err);
853 
854 	if (strcmp(name, curname) == 0)
855 		return (Z_OK);
856 
857 	/*
858 	 * Switching zone names to one beginning with SUNW is not permitted.
859 	 */
860 	if (strncmp(name, "SUNW", 4) == 0)
861 		return (Z_BOGUS_ZONE_NAME);
862 
863 	if ((err = zonecfg_validate_zonename(name)) != Z_OK)
864 		return (err);
865 
866 	/*
867 	 * Setting the name back to the original name (effectively a revert of
868 	 * the name) is fine.  But if we carry on, we'll falsely identify the
869 	 * name as "in use," so special case here.
870 	 */
871 	if (strcmp(name, handle->zone_dh_delete_name) == 0) {
872 		err = setrootattr(handle, DTD_ATTR_NAME, name);
873 		handle->zone_dh_delete_name[0] = '\0';
874 		return (err);
875 	}
876 
877 	/* Check to see if new name chosen is already in use */
878 	if (zone_get_state(name, &state) != Z_NO_ZONE)
879 		return (Z_NAME_IN_USE);
880 
881 	/*
882 	 * If this isn't already "new" or in a renaming transition, then
883 	 * we're initiating a rename here; so stash the "delete name"
884 	 * (i.e. the name of the zone we'll be removing) for the rename.
885 	 */
886 	(void) strlcpy(old_delname, handle->zone_dh_delete_name,
887 	    sizeof (old_delname));
888 	if (!is_new(handle) && !is_renaming(handle)) {
889 		/*
890 		 * Name change is allowed only when the zone we're altering
891 		 * is not ready or running.
892 		 */
893 		err = zone_get_state(curname, &state);
894 		if (err == Z_OK) {
895 			if (state > ZONE_STATE_INSTALLED)
896 				return (Z_BAD_ZONE_STATE);
897 		} else if (err != Z_NO_ZONE) {
898 			return (err);
899 		}
900 
901 		(void) strlcpy(handle->zone_dh_delete_name, curname,
902 		    sizeof (handle->zone_dh_delete_name));
903 		assert(is_renaming(handle));
904 	} else if (is_renaming(handle)) {
905 		err = zone_get_state(handle->zone_dh_delete_name, &state);
906 		if (err == Z_OK) {
907 			if (state > ZONE_STATE_INSTALLED)
908 				return (Z_BAD_ZONE_STATE);
909 		} else if (err != Z_NO_ZONE) {
910 			return (err);
911 		}
912 	}
913 
914 	if ((err = setrootattr(handle, DTD_ATTR_NAME, name)) != Z_OK) {
915 		/*
916 		 * Restore the deletename to whatever it was at the
917 		 * top of the routine, since we've had a failure.
918 		 */
919 		(void) strlcpy(handle->zone_dh_delete_name, old_delname,
920 		    sizeof (handle->zone_dh_delete_name));
921 		return (err);
922 	}
923 
924 	/*
925 	 * Record the old admins from the old zonename
926 	 * so that they can be deleted when the operation is committed.
927 	 */
928 	if ((err = insert_admins(handle, curname)) != Z_OK)
929 		return (err);
930 	else
931 		return (Z_OK);
932 }
933 
934 int
zonecfg_get_zonepath(zone_dochandle_t handle,char * path,size_t pathsize)935 zonecfg_get_zonepath(zone_dochandle_t handle, char *path, size_t pathsize)
936 {
937 	size_t len;
938 
939 	if ((len = strlcpy(path, zonecfg_root, pathsize)) >= pathsize)
940 		return (Z_TOO_BIG);
941 	return (getrootattr(handle, DTD_ATTR_ZONEPATH, path + len,
942 	    pathsize - len));
943 }
944 
945 int
zonecfg_set_zonepath(zone_dochandle_t handle,char * zonepath)946 zonecfg_set_zonepath(zone_dochandle_t handle, char *zonepath)
947 {
948 	size_t len;
949 	char *modpath, *copy_mp, *curr_mp;	/* modified path ptrs */
950 	char last_copied;
951 	int ret;
952 
953 	/*
954 	 * Collapse multiple contiguous slashes and remove trailing slash.
955 	 */
956 	modpath = strdup(zonepath);
957 	if (modpath == NULL)
958 		return (Z_NOMEM);
959 	last_copied = '\0';
960 	for (copy_mp = curr_mp = modpath; *curr_mp != '\0'; curr_mp++) {
961 		if (*curr_mp != '/' || last_copied != '/') {
962 			last_copied = *copy_mp = *curr_mp;
963 			copy_mp++;
964 		}
965 	}
966 	if (last_copied == '/')
967 		copy_mp--;
968 	*copy_mp = '\0';
969 
970 	/*
971 	 * The user deals in absolute paths in the running global zone, but the
972 	 * internal configuration files deal with boot environment relative
973 	 * paths.  Strip out the alternate root when specified.
974 	 */
975 	len = strlen(zonecfg_root);
976 	if (strncmp(modpath, zonecfg_root, len) != 0 || modpath[len] != '/') {
977 		free(modpath);
978 		return (Z_BAD_PROPERTY);
979 	}
980 	curr_mp = modpath + len;
981 	ret = setrootattr(handle, DTD_ATTR_ZONEPATH, curr_mp);
982 	free(modpath);
983 	return (ret);
984 }
985 
986 static int
i_zonecfg_get_brand(zone_dochandle_t handle,char * brand,size_t brandsize,boolean_t default_query)987 i_zonecfg_get_brand(zone_dochandle_t handle, char *brand, size_t brandsize,
988     boolean_t default_query)
989 {
990 	int ret, sz;
991 
992 	ret = getrootattr(handle, DTD_ATTR_BRAND, brand, brandsize);
993 
994 	/*
995 	 * If the lookup failed, or succeeded in finding a non-null brand
996 	 * string then return.
997 	 */
998 	if (ret != Z_OK || brand[0] != '\0')
999 		return (ret);
1000 
1001 	if (!default_query) {
1002 		/* If the zone has no brand, it is the default brand. */
1003 		return (zonecfg_default_brand(brand, brandsize));
1004 	}
1005 
1006 	/* if SUNWdefault didn't specify a brand, fallback to "native" */
1007 	sz = strlcpy(brand, NATIVE_BRAND_NAME, brandsize);
1008 	if (sz >= brandsize)
1009 		return (Z_TOO_BIG);
1010 	return (Z_OK);
1011 }
1012 
1013 int
zonecfg_get_brand(zone_dochandle_t handle,char * brand,size_t brandsize)1014 zonecfg_get_brand(zone_dochandle_t handle, char *brand, size_t brandsize)
1015 {
1016 	return (i_zonecfg_get_brand(handle, brand, brandsize, B_FALSE));
1017 }
1018 
1019 int
zonecfg_set_brand(zone_dochandle_t handle,char * brand)1020 zonecfg_set_brand(zone_dochandle_t handle, char *brand)
1021 {
1022 	return (setrootattr(handle, DTD_ATTR_BRAND, brand));
1023 }
1024 
1025 int
zonecfg_get_autoboot(zone_dochandle_t handle,boolean_t * autoboot)1026 zonecfg_get_autoboot(zone_dochandle_t handle, boolean_t *autoboot)
1027 {
1028 	char autobootstr[DTD_ENTITY_BOOL_LEN];
1029 	int ret;
1030 
1031 	if ((ret = getrootattr(handle, DTD_ATTR_AUTOBOOT, autobootstr,
1032 	    sizeof (autobootstr))) != Z_OK)
1033 		return (ret);
1034 
1035 	if (strcmp(autobootstr, DTD_ENTITY_TRUE) == 0)
1036 		*autoboot = B_TRUE;
1037 	else if (strcmp(autobootstr, DTD_ENTITY_FALSE) == 0)
1038 		*autoboot = B_FALSE;
1039 	else
1040 		ret = Z_BAD_PROPERTY;
1041 	return (ret);
1042 }
1043 
1044 int
zonecfg_set_autoboot(zone_dochandle_t handle,boolean_t autoboot)1045 zonecfg_set_autoboot(zone_dochandle_t handle, boolean_t autoboot)
1046 {
1047 	return (setrootattr(handle, DTD_ATTR_AUTOBOOT,
1048 	    autoboot ? DTD_ENTITY_TRUE : DTD_ENTITY_FALSE));
1049 }
1050 
1051 int
zonecfg_get_pool(zone_dochandle_t handle,char * pool,size_t poolsize)1052 zonecfg_get_pool(zone_dochandle_t handle, char *pool, size_t poolsize)
1053 {
1054 	return (getrootattr(handle, DTD_ATTR_POOL, pool, poolsize));
1055 }
1056 
1057 int
zonecfg_set_pool(zone_dochandle_t handle,char * pool)1058 zonecfg_set_pool(zone_dochandle_t handle, char *pool)
1059 {
1060 	return (setrootattr(handle, DTD_ATTR_POOL, pool));
1061 }
1062 
1063 int
zonecfg_get_limitpriv(zone_dochandle_t handle,char ** limitpriv)1064 zonecfg_get_limitpriv(zone_dochandle_t handle, char **limitpriv)
1065 {
1066 	return (get_alloc_rootattr(handle, DTD_ATTR_LIMITPRIV, limitpriv));
1067 }
1068 
1069 int
zonecfg_set_limitpriv(zone_dochandle_t handle,char * limitpriv)1070 zonecfg_set_limitpriv(zone_dochandle_t handle, char *limitpriv)
1071 {
1072 	return (setrootattr(handle, DTD_ATTR_LIMITPRIV, limitpriv));
1073 }
1074 
1075 int
zonecfg_get_bootargs(zone_dochandle_t handle,char * bargs,size_t bargssize)1076 zonecfg_get_bootargs(zone_dochandle_t handle, char *bargs, size_t bargssize)
1077 {
1078 	return (getrootattr(handle, DTD_ATTR_BOOTARGS, bargs, bargssize));
1079 }
1080 
1081 int
zonecfg_set_bootargs(zone_dochandle_t handle,char * bargs)1082 zonecfg_set_bootargs(zone_dochandle_t handle, char *bargs)
1083 {
1084 	return (setrootattr(handle, DTD_ATTR_BOOTARGS, bargs));
1085 }
1086 
1087 int
zonecfg_get_sched_class(zone_dochandle_t handle,char * sched,size_t schedsize)1088 zonecfg_get_sched_class(zone_dochandle_t handle, char *sched, size_t schedsize)
1089 {
1090 	return (getrootattr(handle, DTD_ATTR_SCHED, sched, schedsize));
1091 }
1092 
1093 int
zonecfg_set_sched(zone_dochandle_t handle,char * sched)1094 zonecfg_set_sched(zone_dochandle_t handle, char *sched)
1095 {
1096 	return (setrootattr(handle, DTD_ATTR_SCHED, sched));
1097 }
1098 
1099 /*
1100  * /etc/zones/index caches a vital piece of information which is also
1101  * in the <zonename>.xml file: the path to the zone.  This is for performance,
1102  * since we need to walk all zonepath's in order to be able to detect conflicts
1103  * (see crosscheck_zonepaths() in the zoneadm command).
1104  *
1105  * An additional complexity is that when doing a rename, we'd like the entire
1106  * index update operation (rename, and potential state changes) to be atomic.
1107  * In general, the operation of this function should succeed or fail as
1108  * a unit.
1109  */
1110 int
zonecfg_refresh_index_file(zone_dochandle_t handle)1111 zonecfg_refresh_index_file(zone_dochandle_t handle)
1112 {
1113 	char name[ZONENAME_MAX], zonepath[MAXPATHLEN];
1114 	struct zoneent ze;
1115 	int err;
1116 	int opcode;
1117 	char *zn;
1118 
1119 	bzero(&ze, sizeof (ze));
1120 	ze.zone_state = -1;	/* Preserve existing state in index */
1121 
1122 	if ((err = zonecfg_get_name(handle, name, sizeof (name))) != Z_OK)
1123 		return (err);
1124 	(void) strlcpy(ze.zone_name, name, sizeof (ze.zone_name));
1125 
1126 	if ((err = zonecfg_get_zonepath(handle, zonepath,
1127 	    sizeof (zonepath))) != Z_OK)
1128 		return (err);
1129 	(void) strlcpy(ze.zone_path, zonepath + strlen(zonecfg_root),
1130 	    sizeof (ze.zone_path));
1131 
1132 	if (is_renaming(handle)) {
1133 		opcode = PZE_MODIFY;
1134 		(void) strlcpy(ze.zone_name, handle->zone_dh_delete_name,
1135 		    sizeof (ze.zone_name));
1136 		(void) strlcpy(ze.zone_newname, name, sizeof (ze.zone_newname));
1137 	} else if (is_new(handle)) {
1138 		FILE *cookie;
1139 		/*
1140 		 * Be tolerant of the zone already existing in the index file,
1141 		 * since we might be forcibly overwriting an existing
1142 		 * configuration with a new one (for example 'create -F'
1143 		 * in zonecfg).
1144 		 */
1145 		opcode = PZE_ADD;
1146 		cookie = setzoneent();
1147 		while ((zn = getzoneent(cookie)) != NULL) {
1148 			if (strcmp(zn, name) == 0) {
1149 				opcode = PZE_MODIFY;
1150 				free(zn);
1151 				break;
1152 			}
1153 			free(zn);
1154 		}
1155 		endzoneent(cookie);
1156 		ze.zone_state = ZONE_STATE_CONFIGURED;
1157 	} else {
1158 		opcode = PZE_MODIFY;
1159 	}
1160 
1161 	if ((err = putzoneent(&ze, opcode)) != Z_OK)
1162 		return (err);
1163 
1164 	return (Z_OK);
1165 }
1166 
1167 /*
1168  * The goal of this routine is to cause the index file update and the
1169  * document save to happen as an atomic operation.  We do the document
1170  * first, saving a backup copy using a hard link; if that succeeds, we go
1171  * on to the index.  If that fails, we roll the document back into place.
1172  *
1173  * Strategy:
1174  *
1175  * New zone 'foo' configuration:
1176  * 	Create tmpfile (zonecfg.xxxxxx)
1177  * 	Write XML to tmpfile
1178  * 	Rename tmpfile to xmlfile (zonecfg.xxxxxx -> foo.xml)
1179  * 	Add entry to index file
1180  * 	If it fails, delete foo.xml, leaving nothing behind.
1181  *
1182  * Save existing zone 'foo':
1183  * 	Make backup of foo.xml -> .backup
1184  * 	Create tmpfile (zonecfg.xxxxxx)
1185  * 	Write XML to tmpfile
1186  * 	Rename tmpfile to xmlfile (zonecfg.xxxxxx -> foo.xml)
1187  * 	Modify index file as needed
1188  * 	If it fails, recover from .backup -> foo.xml
1189  *
1190  * Rename 'foo' to 'bar':
1191  * 	Create tmpfile (zonecfg.xxxxxx)
1192  * 	Write XML to tmpfile
1193  * 	Rename tmpfile to xmlfile (zonecfg.xxxxxx -> bar.xml)
1194  * 	Add entry for 'bar' to index file, Remove entry for 'foo' (refresh)
1195  * 	If it fails, delete bar.xml; foo.xml is left behind.
1196  */
1197 static int
zonecfg_save_impl(zone_dochandle_t handle,char * filename)1198 zonecfg_save_impl(zone_dochandle_t handle, char *filename)
1199 {
1200 	char tmpfile[MAXPATHLEN];
1201 	char bakdir[MAXPATHLEN], bakbase[MAXPATHLEN], bakfile[MAXPATHLEN];
1202 	int tmpfd, err, valid;
1203 	xmlValidCtxt cvp = { NULL };
1204 	boolean_t backup;
1205 
1206 	(void) strlcpy(tmpfile, filename, sizeof (tmpfile));
1207 	(void) dirname(tmpfile);
1208 	(void) strlcat(tmpfile, _PATH_TMPFILE, sizeof (tmpfile));
1209 
1210 	tmpfd = mkstemp(tmpfile);
1211 	if (tmpfd == -1) {
1212 		(void) unlink(tmpfile);
1213 		return (Z_TEMP_FILE);
1214 	}
1215 	(void) close(tmpfd);
1216 
1217 	cvp.error = zonecfg_error_func;
1218 	cvp.warning = zonecfg_error_func;
1219 
1220 	/*
1221 	 * We do a final validation of the document.  Since the library has
1222 	 * malfunctioned if it fails to validate, we follow-up with an
1223 	 * assert() that the doc is valid.
1224 	 */
1225 	valid = xmlValidateDocument(&cvp, handle->zone_dh_doc);
1226 	assert(valid != 0);
1227 
1228 	if (xmlSaveFormatFile(tmpfile, handle->zone_dh_doc, 1) <= 0)
1229 		goto err;
1230 
1231 	(void) chmod(tmpfile, 0644);
1232 
1233 	/*
1234 	 * In the event we are doing a standard save, hard link a copy of the
1235 	 * original file in .backup.<pid>.filename so we can restore it if
1236 	 * something goes wrong.
1237 	 */
1238 	if (!is_new(handle) && !is_renaming(handle)) {
1239 		backup = B_TRUE;
1240 
1241 		(void) strlcpy(bakdir, filename, sizeof (bakdir));
1242 		(void) strlcpy(bakbase, filename, sizeof (bakbase));
1243 		(void) snprintf(bakfile, sizeof (bakfile), "%s/.backup.%d.%s",
1244 		    dirname(bakdir), getpid(), basename(bakbase));
1245 
1246 		if (link(filename, bakfile) == -1) {
1247 			err = errno;
1248 			(void) unlink(tmpfile);
1249 			if (errno == EACCES)
1250 				return (Z_ACCES);
1251 			return (Z_MISC_FS);
1252 		}
1253 	}
1254 
1255 	/*
1256 	 * Move the new document over top of the old.
1257 	 * i.e.:   zonecfg.XXXXXX  ->  myzone.xml
1258 	 */
1259 	if (rename(tmpfile, filename) == -1) {
1260 		err = errno;
1261 		(void) unlink(tmpfile);
1262 		if (backup)
1263 			(void) unlink(bakfile);
1264 		if (err == EACCES)
1265 			return (Z_ACCES);
1266 		return (Z_MISC_FS);
1267 	}
1268 
1269 	/*
1270 	 * If this is a snapshot, we're done-- don't add an index entry.
1271 	 */
1272 	if (is_snapshot(handle))
1273 		return (Z_OK);
1274 
1275 	/* now update the index file to reflect whatever we just did */
1276 	if ((err = zonecfg_refresh_index_file(handle)) != Z_OK) {
1277 		if (backup) {
1278 			/*
1279 			 * Try to restore from our backup.
1280 			 */
1281 			(void) unlink(filename);
1282 			(void) rename(bakfile, filename);
1283 		} else {
1284 			/*
1285 			 * Either the zone is new, in which case we can delete
1286 			 * new.xml, or we're doing a rename, so ditto.
1287 			 */
1288 			assert(is_new(handle) || is_renaming(handle));
1289 			(void) unlink(filename);
1290 		}
1291 		return (Z_UPDATING_INDEX);
1292 	}
1293 
1294 	if (backup)
1295 		(void) unlink(bakfile);
1296 
1297 	return (Z_OK);
1298 
1299 err:
1300 	(void) unlink(tmpfile);
1301 	return (Z_SAVING_FILE);
1302 }
1303 
1304 int
zonecfg_save(zone_dochandle_t handle)1305 zonecfg_save(zone_dochandle_t handle)
1306 {
1307 	char zname[ZONENAME_MAX], path[MAXPATHLEN];
1308 	char delpath[MAXPATHLEN];
1309 	int err = Z_SAVING_FILE;
1310 
1311 	if (zonecfg_check_handle(handle) != Z_OK)
1312 		return (Z_BAD_HANDLE);
1313 
1314 	/*
1315 	 * We don't support saving snapshots or a tree containing a sw
1316 	 * inventory at this time.
1317 	 */
1318 	if (handle->zone_dh_snapshot || handle->zone_dh_sw_inv)
1319 		return (Z_INVAL);
1320 
1321 	if ((err = zonecfg_get_name(handle, zname, sizeof (zname))) != Z_OK)
1322 		return (err);
1323 
1324 	if (!config_file_path(zname, path))
1325 		return (Z_MISC_FS);
1326 
1327 	addcomment(handle, "\n    DO NOT EDIT THIS "
1328 	    "FILE.  Use zonecfg(1M) instead.\n");
1329 
1330 	/*
1331 	 * Update user_attr first so that it will be older
1332 	 * than the config file.
1333 	 */
1334 	(void) zonecfg_authorize_users(handle, zname);
1335 	err = zonecfg_save_impl(handle, path);
1336 
1337 	stripcomments(handle);
1338 
1339 	if (err != Z_OK)
1340 		return (err);
1341 
1342 	handle->zone_dh_newzone = B_FALSE;
1343 
1344 	if (is_renaming(handle)) {
1345 		if (config_file_path(handle->zone_dh_delete_name, delpath))
1346 			(void) unlink(delpath);
1347 		handle->zone_dh_delete_name[0] = '\0';
1348 	}
1349 
1350 	return (Z_OK);
1351 }
1352 
1353 int
zonecfg_verify_save(zone_dochandle_t handle,char * filename)1354 zonecfg_verify_save(zone_dochandle_t handle, char *filename)
1355 {
1356 	int valid;
1357 
1358 	xmlValidCtxt cvp = { NULL };
1359 
1360 	if (zonecfg_check_handle(handle) != Z_OK)
1361 		return (Z_BAD_HANDLE);
1362 
1363 	cvp.error = zonecfg_error_func;
1364 	cvp.warning = zonecfg_error_func;
1365 
1366 	/*
1367 	 * We do a final validation of the document.  Since the library has
1368 	 * malfunctioned if it fails to validate, we follow-up with an
1369 	 * assert() that the doc is valid.
1370 	 */
1371 	valid = xmlValidateDocument(&cvp, handle->zone_dh_doc);
1372 	assert(valid != 0);
1373 
1374 	if (xmlSaveFormatFile(filename, handle->zone_dh_doc, 1) <= 0)
1375 		return (Z_SAVING_FILE);
1376 
1377 	return (Z_OK);
1378 }
1379 
1380 int
zonecfg_detach_save(zone_dochandle_t handle,uint_t flags)1381 zonecfg_detach_save(zone_dochandle_t handle, uint_t flags)
1382 {
1383 	char zname[ZONENAME_MAX];
1384 	char path[MAXPATHLEN];
1385 	char migpath[MAXPATHLEN];
1386 	xmlValidCtxt cvp = { NULL };
1387 	int err = Z_SAVING_FILE;
1388 	int valid;
1389 
1390 	if (zonecfg_check_handle(handle) != Z_OK)
1391 		return (Z_BAD_HANDLE);
1392 
1393 	if (flags & ZONE_DRY_RUN) {
1394 		(void) strlcpy(migpath, "-", sizeof (migpath));
1395 	} else {
1396 		if ((err = zonecfg_get_name(handle, zname, sizeof (zname)))
1397 		    != Z_OK)
1398 			return (err);
1399 
1400 		if ((err = zone_get_zonepath(zname, path, sizeof (path)))
1401 		    != Z_OK)
1402 			return (err);
1403 
1404 		if (snprintf(migpath, sizeof (migpath), "%s/%s", path,
1405 		    ZONE_DETACHED) >= sizeof (migpath))
1406 			return (Z_NOMEM);
1407 	}
1408 
1409 	if ((err = operation_prep(handle)) != Z_OK)
1410 		return (err);
1411 
1412 	addcomment(handle, "\n    DO NOT EDIT THIS FILE.  "
1413 	    "Use zonecfg(1M) and zoneadm(1M) attach.\n");
1414 
1415 	cvp.error = zonecfg_error_func;
1416 	cvp.warning = zonecfg_error_func;
1417 
1418 	/*
1419 	 * We do a final validation of the document.  Since the library has
1420 	 * malfunctioned if it fails to validate, we follow-up with an
1421 	 * assert() that the doc is valid.
1422 	 */
1423 	valid = xmlValidateDocument(&cvp, handle->zone_dh_doc);
1424 	assert(valid != 0);
1425 
1426 	if (xmlSaveFormatFile(migpath, handle->zone_dh_doc, 1) <= 0)
1427 		return (Z_SAVING_FILE);
1428 
1429 	if (!(flags & ZONE_DRY_RUN))
1430 		(void) chmod(migpath, 0644);
1431 
1432 	stripcomments(handle);
1433 
1434 	handle->zone_dh_newzone = B_FALSE;
1435 
1436 	return (Z_OK);
1437 }
1438 
1439 boolean_t
zonecfg_detached(const char * path)1440 zonecfg_detached(const char *path)
1441 {
1442 	char		migpath[MAXPATHLEN];
1443 	struct stat	buf;
1444 
1445 	if (snprintf(migpath, sizeof (migpath), "%s/%s", path, ZONE_DETACHED) >=
1446 	    sizeof (migpath))
1447 		return (B_FALSE);
1448 
1449 	if (stat(migpath, &buf) != -1)
1450 		return (B_TRUE);
1451 
1452 	return (B_FALSE);
1453 }
1454 
1455 void
zonecfg_rm_detached(zone_dochandle_t handle,boolean_t forced)1456 zonecfg_rm_detached(zone_dochandle_t handle, boolean_t forced)
1457 {
1458 	char zname[ZONENAME_MAX];
1459 	char path[MAXPATHLEN];
1460 	char detached[MAXPATHLEN];
1461 	char attached[MAXPATHLEN];
1462 
1463 	if (zonecfg_check_handle(handle) != Z_OK)
1464 		return;
1465 
1466 	if (zonecfg_get_name(handle, zname, sizeof (zname)) != Z_OK)
1467 		return;
1468 
1469 	if (zone_get_zonepath(zname, path, sizeof (path)) != Z_OK)
1470 		return;
1471 
1472 	(void) snprintf(detached, sizeof (detached), "%s/%s", path,
1473 	    ZONE_DETACHED);
1474 	(void) snprintf(attached, sizeof (attached), "%s/%s", path,
1475 	    ATTACH_FORCED);
1476 
1477 	if (forced) {
1478 		(void) rename(detached, attached);
1479 	} else {
1480 		(void) unlink(attached);
1481 		(void) unlink(detached);
1482 	}
1483 }
1484 
1485 /*
1486  * Special case: if access(2) fails with ENOENT, then try again using
1487  * ZONE_CONFIG_ROOT instead of config_file_path(zonename).  This is how we
1488  * work around the case of a config file which has not been created yet:
1489  * the user will need access to the directory so use that as a heuristic.
1490  */
1491 
1492 int
zonecfg_access(const char * zonename,int amode)1493 zonecfg_access(const char *zonename, int amode)
1494 {
1495 	char path[MAXPATHLEN];
1496 
1497 	if (!config_file_path(zonename, path))
1498 		return (Z_INVAL);
1499 	if (access(path, amode) == 0)
1500 		return (Z_OK);
1501 	if (errno == ENOENT) {
1502 		if (snprintf(path, sizeof (path), "%s%s", zonecfg_root,
1503 		    ZONE_CONFIG_ROOT) >= sizeof (path))
1504 			return (Z_INVAL);
1505 		if (access(path, amode) == 0)
1506 			return (Z_OK);
1507 	}
1508 	if (errno == EACCES)
1509 		return (Z_ACCES);
1510 	if (errno == EINVAL)
1511 		return (Z_INVAL);
1512 	return (Z_MISC_FS);
1513 }
1514 
1515 int
zonecfg_create_snapshot(const char * zonename)1516 zonecfg_create_snapshot(const char *zonename)
1517 {
1518 	zone_dochandle_t handle;
1519 	char path[MAXPATHLEN], zonepath[MAXPATHLEN], rpath[MAXPATHLEN];
1520 	int error = Z_OK, res;
1521 
1522 	if ((handle = zonecfg_init_handle()) == NULL) {
1523 		return (Z_NOMEM);
1524 	}
1525 
1526 	handle->zone_dh_newzone = B_TRUE;
1527 	handle->zone_dh_snapshot = B_TRUE;
1528 
1529 	if ((error = zonecfg_get_handle(zonename, handle)) != Z_OK)
1530 		goto out;
1531 	if ((error = operation_prep(handle)) != Z_OK)
1532 		goto out;
1533 	error = zonecfg_get_zonepath(handle, zonepath, sizeof (zonepath));
1534 	if (error != Z_OK)
1535 		goto out;
1536 	if ((res = resolvepath(zonepath, rpath, sizeof (rpath))) == -1) {
1537 		error = Z_RESOLVED_PATH;
1538 		goto out;
1539 	}
1540 	/*
1541 	 * If the resolved path is not the same as the original path, then
1542 	 * save the resolved path in the snapshot, thus preventing any
1543 	 * potential problems down the line when zoneadmd goes to unmount
1544 	 * file systems and depends on initial string matches with resolved
1545 	 * paths.
1546 	 */
1547 	rpath[res] = '\0';
1548 	if (strcmp(zonepath, rpath) != 0) {
1549 		if ((error = zonecfg_set_zonepath(handle, rpath)) != Z_OK)
1550 			goto out;
1551 	}
1552 	if (snprintf(path, sizeof (path), "%s%s", zonecfg_root,
1553 	    ZONE_SNAPSHOT_ROOT) >= sizeof (path)) {
1554 		error = Z_MISC_FS;
1555 		goto out;
1556 	}
1557 	if ((mkdir(path, S_IRWXU) == -1) && (errno != EEXIST)) {
1558 		error = Z_MISC_FS;
1559 		goto out;
1560 	}
1561 
1562 	if (!snap_file_path(zonename, path)) {
1563 		error = Z_MISC_FS;
1564 		goto out;
1565 	}
1566 
1567 	addcomment(handle, "\n    DO NOT EDIT THIS FILE.  "
1568 	    "It is a snapshot of running zone state.\n");
1569 
1570 	error = zonecfg_save_impl(handle, path);
1571 
1572 	stripcomments(handle);
1573 
1574 out:
1575 	zonecfg_fini_handle(handle);
1576 	return (error);
1577 }
1578 
1579 int
zonecfg_get_iptype(zone_dochandle_t handle,zone_iptype_t * iptypep)1580 zonecfg_get_iptype(zone_dochandle_t handle, zone_iptype_t *iptypep)
1581 {
1582 	char property[10]; /* 10 is big enough for "shared"/"exclusive" */
1583 	int err;
1584 
1585 	err = getrootattr(handle, DTD_ATTR_IPTYPE, property, sizeof (property));
1586 	if (err == Z_BAD_PROPERTY) {
1587 		/* Return default value */
1588 		*iptypep = ZS_SHARED;
1589 		return (Z_OK);
1590 	} else if (err != Z_OK) {
1591 		return (err);
1592 	}
1593 
1594 	if (strlen(property) == 0 ||
1595 	    strcmp(property, "shared") == 0)
1596 		*iptypep = ZS_SHARED;
1597 	else if (strcmp(property, "exclusive") == 0)
1598 		*iptypep = ZS_EXCLUSIVE;
1599 	else
1600 		return (Z_INVAL);
1601 
1602 	return (Z_OK);
1603 }
1604 
1605 int
zonecfg_set_iptype(zone_dochandle_t handle,zone_iptype_t iptype)1606 zonecfg_set_iptype(zone_dochandle_t handle, zone_iptype_t iptype)
1607 {
1608 	xmlNodePtr cur;
1609 
1610 	if (handle == NULL)
1611 		return (Z_INVAL);
1612 
1613 	cur = xmlDocGetRootElement(handle->zone_dh_doc);
1614 	if (cur == NULL) {
1615 		return (Z_EMPTY_DOCUMENT);
1616 	}
1617 
1618 	if (xmlStrcmp(cur->name, DTD_ELEM_ZONE) != 0) {
1619 		return (Z_WRONG_DOC_TYPE);
1620 	}
1621 	switch (iptype) {
1622 	case ZS_SHARED:
1623 		/*
1624 		 * Since "shared" is the default, we don't write it to the
1625 		 * configuration file, so that it's easier to migrate those
1626 		 * zones elsewhere, eg., to systems which are not IP-Instances
1627 		 * aware.
1628 		 * xmlUnsetProp only fails when the attribute doesn't exist,
1629 		 * which we don't care.
1630 		 */
1631 		(void) xmlUnsetProp(cur, DTD_ATTR_IPTYPE);
1632 		break;
1633 	case ZS_EXCLUSIVE:
1634 		if (xmlSetProp(cur, DTD_ATTR_IPTYPE,
1635 		    (const xmlChar *) "exclusive") == NULL)
1636 			return (Z_INVAL);
1637 		break;
1638 	}
1639 	return (Z_OK);
1640 }
1641 
1642 static int
newprop(xmlNodePtr node,const xmlChar * attrname,char * src)1643 newprop(xmlNodePtr node, const xmlChar *attrname, char *src)
1644 {
1645 	xmlAttrPtr newattr;
1646 
1647 	newattr = xmlNewProp(node, attrname, (xmlChar *)src);
1648 	if (newattr == NULL) {
1649 		xmlUnlinkNode(node);
1650 		xmlFreeNode(node);
1651 		return (Z_BAD_PROPERTY);
1652 	}
1653 	return (Z_OK);
1654 }
1655 
1656 static int
zonecfg_add_filesystem_core(zone_dochandle_t handle,struct zone_fstab * tabptr)1657 zonecfg_add_filesystem_core(zone_dochandle_t handle, struct zone_fstab *tabptr)
1658 {
1659 	xmlNodePtr newnode, cur = handle->zone_dh_cur, options_node;
1660 	zone_fsopt_t *ptr;
1661 	int err;
1662 
1663 	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_FS, NULL);
1664 	if ((err = newprop(newnode, DTD_ATTR_SPECIAL,
1665 	    tabptr->zone_fs_special)) != Z_OK)
1666 		return (err);
1667 	if (tabptr->zone_fs_raw[0] != '\0' &&
1668 	    (err = newprop(newnode, DTD_ATTR_RAW, tabptr->zone_fs_raw)) != Z_OK)
1669 		return (err);
1670 	if ((err = newprop(newnode, DTD_ATTR_DIR, tabptr->zone_fs_dir)) != Z_OK)
1671 		return (err);
1672 	if ((err = newprop(newnode, DTD_ATTR_TYPE,
1673 	    tabptr->zone_fs_type)) != Z_OK)
1674 		return (err);
1675 	if (tabptr->zone_fs_options != NULL) {
1676 		for (ptr = tabptr->zone_fs_options; ptr != NULL;
1677 		    ptr = ptr->zone_fsopt_next) {
1678 			options_node = xmlNewTextChild(newnode, NULL,
1679 			    DTD_ELEM_FSOPTION, NULL);
1680 			if ((err = newprop(options_node, DTD_ATTR_NAME,
1681 			    ptr->zone_fsopt_opt)) != Z_OK)
1682 				return (err);
1683 		}
1684 	}
1685 	return (Z_OK);
1686 }
1687 
1688 int
zonecfg_add_filesystem(zone_dochandle_t handle,struct zone_fstab * tabptr)1689 zonecfg_add_filesystem(zone_dochandle_t handle, struct zone_fstab *tabptr)
1690 {
1691 	int err;
1692 
1693 	if (tabptr == NULL)
1694 		return (Z_INVAL);
1695 
1696 	if ((err = operation_prep(handle)) != Z_OK)
1697 		return (err);
1698 
1699 	if ((err = zonecfg_add_filesystem_core(handle, tabptr)) != Z_OK)
1700 		return (err);
1701 
1702 	return (Z_OK);
1703 }
1704 
1705 int
zonecfg_add_fs_option(struct zone_fstab * tabptr,char * option)1706 zonecfg_add_fs_option(struct zone_fstab *tabptr, char *option)
1707 {
1708 	zone_fsopt_t *last, *old, *new;
1709 
1710 	last = tabptr->zone_fs_options;
1711 	for (old = last; old != NULL; old = old->zone_fsopt_next)
1712 		last = old;	/* walk to the end of the list */
1713 	new = (zone_fsopt_t *)malloc(sizeof (zone_fsopt_t));
1714 	if (new == NULL)
1715 		return (Z_NOMEM);
1716 	(void) strlcpy(new->zone_fsopt_opt, option,
1717 	    sizeof (new->zone_fsopt_opt));
1718 	new->zone_fsopt_next = NULL;
1719 	if (last == NULL)
1720 		tabptr->zone_fs_options = new;
1721 	else
1722 		last->zone_fsopt_next = new;
1723 	return (Z_OK);
1724 }
1725 
1726 int
zonecfg_remove_fs_option(struct zone_fstab * tabptr,char * option)1727 zonecfg_remove_fs_option(struct zone_fstab *tabptr, char *option)
1728 {
1729 	zone_fsopt_t *last, *this, *next;
1730 
1731 	last = tabptr->zone_fs_options;
1732 	for (this = last; this != NULL; this = this->zone_fsopt_next) {
1733 		if (strcmp(this->zone_fsopt_opt, option) == 0) {
1734 			next = this->zone_fsopt_next;
1735 			if (this == tabptr->zone_fs_options)
1736 				tabptr->zone_fs_options = next;
1737 			else
1738 				last->zone_fsopt_next = next;
1739 			free(this);
1740 			return (Z_OK);
1741 		} else
1742 			last = this;
1743 	}
1744 	return (Z_NO_PROPERTY_ID);
1745 }
1746 
1747 void
zonecfg_free_fs_option_list(zone_fsopt_t * list)1748 zonecfg_free_fs_option_list(zone_fsopt_t *list)
1749 {
1750 	zone_fsopt_t *this, *next;
1751 
1752 	for (this = list; this != NULL; this = next) {
1753 		next = this->zone_fsopt_next;
1754 		free(this);
1755 	}
1756 }
1757 
1758 void
zonecfg_free_rctl_value_list(struct zone_rctlvaltab * valtab)1759 zonecfg_free_rctl_value_list(struct zone_rctlvaltab *valtab)
1760 {
1761 	if (valtab == NULL)
1762 		return;
1763 	zonecfg_free_rctl_value_list(valtab->zone_rctlval_next);
1764 	free(valtab);
1765 }
1766 
1767 static boolean_t
match_prop(xmlNodePtr cur,const xmlChar * attr,char * user_prop)1768 match_prop(xmlNodePtr cur, const xmlChar *attr, char *user_prop)
1769 {
1770 	xmlChar *gotten_prop;
1771 	int prop_result;
1772 
1773 	gotten_prop = xmlGetProp(cur, attr);
1774 	if (gotten_prop == NULL)	/* shouldn't happen */
1775 		return (B_FALSE);
1776 	prop_result = xmlStrcmp(gotten_prop, (const xmlChar *) user_prop);
1777 	xmlFree(gotten_prop);
1778 	return ((prop_result == 0));	/* empty strings will match */
1779 }
1780 
1781 static int
zonecfg_delete_filesystem_core(zone_dochandle_t handle,struct zone_fstab * tabptr)1782 zonecfg_delete_filesystem_core(zone_dochandle_t handle,
1783     struct zone_fstab *tabptr)
1784 {
1785 	xmlNodePtr cur = handle->zone_dh_cur;
1786 	boolean_t dir_match, spec_match, raw_match, type_match;
1787 
1788 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
1789 		if (xmlStrcmp(cur->name, DTD_ELEM_FS))
1790 			continue;
1791 		dir_match = match_prop(cur, DTD_ATTR_DIR, tabptr->zone_fs_dir);
1792 		spec_match = match_prop(cur, DTD_ATTR_SPECIAL,
1793 		    tabptr->zone_fs_special);
1794 		raw_match = match_prop(cur, DTD_ATTR_RAW,
1795 		    tabptr->zone_fs_raw);
1796 		type_match = match_prop(cur, DTD_ATTR_TYPE,
1797 		    tabptr->zone_fs_type);
1798 		if (dir_match && spec_match && raw_match && type_match) {
1799 			xmlUnlinkNode(cur);
1800 			xmlFreeNode(cur);
1801 			return (Z_OK);
1802 		}
1803 	}
1804 	return (Z_NO_RESOURCE_ID);
1805 }
1806 
1807 int
zonecfg_delete_filesystem(zone_dochandle_t handle,struct zone_fstab * tabptr)1808 zonecfg_delete_filesystem(zone_dochandle_t handle, struct zone_fstab *tabptr)
1809 {
1810 	int err;
1811 
1812 	if (tabptr == NULL)
1813 		return (Z_INVAL);
1814 
1815 	if ((err = operation_prep(handle)) != Z_OK)
1816 		return (err);
1817 
1818 	if ((err = zonecfg_delete_filesystem_core(handle, tabptr)) != Z_OK)
1819 		return (err);
1820 
1821 	return (Z_OK);
1822 }
1823 
1824 int
zonecfg_modify_filesystem(zone_dochandle_t handle,struct zone_fstab * oldtabptr,struct zone_fstab * newtabptr)1825 zonecfg_modify_filesystem(
1826 	zone_dochandle_t handle,
1827 	struct zone_fstab *oldtabptr,
1828 	struct zone_fstab *newtabptr)
1829 {
1830 	int err;
1831 
1832 	if (oldtabptr == NULL || newtabptr == NULL)
1833 		return (Z_INVAL);
1834 
1835 	if ((err = operation_prep(handle)) != Z_OK)
1836 		return (err);
1837 
1838 	if ((err = zonecfg_delete_filesystem_core(handle, oldtabptr)) != Z_OK)
1839 		return (err);
1840 
1841 	if ((err = zonecfg_add_filesystem_core(handle, newtabptr)) != Z_OK)
1842 		return (err);
1843 
1844 	return (Z_OK);
1845 }
1846 
1847 int
zonecfg_lookup_filesystem(zone_dochandle_t handle,struct zone_fstab * tabptr)1848 zonecfg_lookup_filesystem(
1849 	zone_dochandle_t handle,
1850 	struct zone_fstab *tabptr)
1851 {
1852 	xmlNodePtr cur, options, firstmatch;
1853 	int err;
1854 	char dirname[MAXPATHLEN], special[MAXPATHLEN], raw[MAXPATHLEN];
1855 	char type[FSTYPSZ];
1856 	char options_str[MAX_MNTOPT_STR];
1857 
1858 	if (tabptr == NULL)
1859 		return (Z_INVAL);
1860 
1861 	if ((err = operation_prep(handle)) != Z_OK)
1862 		return (err);
1863 
1864 	/*
1865 	 * Walk the list of children looking for matches on any properties
1866 	 * specified in the fstab parameter.  If more than one resource
1867 	 * matches, we return Z_INSUFFICIENT_SPEC; if none match, we return
1868 	 * Z_NO_RESOURCE_ID.
1869 	 */
1870 	cur = handle->zone_dh_cur;
1871 	firstmatch = NULL;
1872 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
1873 		if (xmlStrcmp(cur->name, DTD_ELEM_FS))
1874 			continue;
1875 		if (strlen(tabptr->zone_fs_dir) > 0) {
1876 			if ((fetchprop(cur, DTD_ATTR_DIR, dirname,
1877 			    sizeof (dirname)) == Z_OK) &&
1878 			    (strcmp(tabptr->zone_fs_dir, dirname) == 0)) {
1879 				if (firstmatch == NULL)
1880 					firstmatch = cur;
1881 				else
1882 					return (Z_INSUFFICIENT_SPEC);
1883 			}
1884 		}
1885 		if (strlen(tabptr->zone_fs_special) > 0) {
1886 			if ((fetchprop(cur, DTD_ATTR_SPECIAL, special,
1887 			    sizeof (special)) == Z_OK)) {
1888 				if (strcmp(tabptr->zone_fs_special,
1889 				    special) == 0) {
1890 					if (firstmatch == NULL)
1891 						firstmatch = cur;
1892 					else if (firstmatch != cur)
1893 						return (Z_INSUFFICIENT_SPEC);
1894 				} else {
1895 					/*
1896 					 * If another property matched but this
1897 					 * one doesn't then reset firstmatch.
1898 					 */
1899 					if (firstmatch == cur)
1900 						firstmatch = NULL;
1901 				}
1902 			}
1903 		}
1904 		if (strlen(tabptr->zone_fs_raw) > 0) {
1905 			if ((fetchprop(cur, DTD_ATTR_RAW, raw,
1906 			    sizeof (raw)) == Z_OK)) {
1907 				if (strcmp(tabptr->zone_fs_raw, raw) == 0) {
1908 					if (firstmatch == NULL)
1909 						firstmatch = cur;
1910 					else if (firstmatch != cur)
1911 						return (Z_INSUFFICIENT_SPEC);
1912 				} else {
1913 					/*
1914 					 * If another property matched but this
1915 					 * one doesn't then reset firstmatch.
1916 					 */
1917 					if (firstmatch == cur)
1918 						firstmatch = NULL;
1919 				}
1920 			}
1921 		}
1922 		if (strlen(tabptr->zone_fs_type) > 0) {
1923 			if ((fetchprop(cur, DTD_ATTR_TYPE, type,
1924 			    sizeof (type)) == Z_OK)) {
1925 				if (strcmp(tabptr->zone_fs_type, type) == 0) {
1926 					if (firstmatch == NULL)
1927 						firstmatch = cur;
1928 					else if (firstmatch != cur)
1929 						return (Z_INSUFFICIENT_SPEC);
1930 				} else {
1931 					/*
1932 					 * If another property matched but this
1933 					 * one doesn't then reset firstmatch.
1934 					 */
1935 					if (firstmatch == cur)
1936 						firstmatch = NULL;
1937 				}
1938 			}
1939 		}
1940 	}
1941 
1942 	if (firstmatch == NULL)
1943 		return (Z_NO_RESOURCE_ID);
1944 
1945 	cur = firstmatch;
1946 
1947 	if ((err = fetchprop(cur, DTD_ATTR_DIR, tabptr->zone_fs_dir,
1948 	    sizeof (tabptr->zone_fs_dir))) != Z_OK)
1949 		return (err);
1950 
1951 	if ((err = fetchprop(cur, DTD_ATTR_SPECIAL, tabptr->zone_fs_special,
1952 	    sizeof (tabptr->zone_fs_special))) != Z_OK)
1953 		return (err);
1954 
1955 	if ((err = fetchprop(cur, DTD_ATTR_RAW, tabptr->zone_fs_raw,
1956 	    sizeof (tabptr->zone_fs_raw))) != Z_OK)
1957 		return (err);
1958 
1959 	if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_fs_type,
1960 	    sizeof (tabptr->zone_fs_type))) != Z_OK)
1961 		return (err);
1962 
1963 	/* options are optional */
1964 	tabptr->zone_fs_options = NULL;
1965 	for (options = cur->xmlChildrenNode; options != NULL;
1966 	    options = options->next) {
1967 		if ((fetchprop(options, DTD_ATTR_NAME, options_str,
1968 		    sizeof (options_str)) != Z_OK))
1969 			break;
1970 		if (zonecfg_add_fs_option(tabptr, options_str) != Z_OK)
1971 			break;
1972 	}
1973 	return (Z_OK);
1974 }
1975 
1976 /*
1977  * Compare two IP addresses in string form.  Allow for the possibility that
1978  * one might have "/<prefix-length>" at the end: allow a match on just the
1979  * IP address (or host name) part.
1980  */
1981 
1982 boolean_t
zonecfg_same_net_address(char * a1,char * a2)1983 zonecfg_same_net_address(char *a1, char *a2)
1984 {
1985 	char *slashp, *slashp1, *slashp2;
1986 	int result;
1987 
1988 	if (strcmp(a1, a2) == 0)
1989 		return (B_TRUE);
1990 
1991 	/*
1992 	 * If neither has a slash or both do, they need to match to be
1993 	 * considered the same, but they did not match above, so fail.
1994 	 */
1995 	slashp1 = strchr(a1, '/');
1996 	slashp2 = strchr(a2, '/');
1997 	if ((slashp1 == NULL && slashp2 == NULL) ||
1998 	    (slashp1 != NULL && slashp2 != NULL))
1999 		return (B_FALSE);
2000 
2001 	/*
2002 	 * Only one had a slash: pick that one, zero out the slash, compare
2003 	 * the "address only" strings, restore the slash, and return the
2004 	 * result of the comparison.
2005 	 */
2006 	slashp = (slashp1 == NULL) ? slashp2 : slashp1;
2007 	*slashp = '\0';
2008 	result = strcmp(a1, a2);
2009 	*slashp = '/';
2010 	return ((result == 0));
2011 }
2012 
2013 int
zonecfg_valid_net_address(char * address,struct lifreq * lifr)2014 zonecfg_valid_net_address(char *address, struct lifreq *lifr)
2015 {
2016 	struct sockaddr_in *sin4;
2017 	struct sockaddr_in6 *sin6;
2018 	struct addrinfo hints, *result;
2019 	char *slashp = strchr(address, '/');
2020 
2021 	bzero(lifr, sizeof (struct lifreq));
2022 	sin4 = (struct sockaddr_in *)&lifr->lifr_addr;
2023 	sin6 = (struct sockaddr_in6 *)&lifr->lifr_addr;
2024 	if (slashp != NULL)
2025 		*slashp = '\0';
2026 	if (inet_pton(AF_INET, address, &sin4->sin_addr) == 1) {
2027 		sin4->sin_family = AF_INET;
2028 	} else if (inet_pton(AF_INET6, address, &sin6->sin6_addr) == 1) {
2029 		if (slashp == NULL)
2030 			return (Z_IPV6_ADDR_PREFIX_LEN);
2031 		sin6->sin6_family = AF_INET6;
2032 	} else {
2033 		/* "address" may be a host name */
2034 		(void) memset(&hints, 0, sizeof (hints));
2035 		hints.ai_family = PF_INET;
2036 		if (getaddrinfo(address, NULL, &hints, &result) != 0)
2037 			return (Z_BOGUS_ADDRESS);
2038 		sin4->sin_family = result->ai_family;
2039 
2040 		(void) memcpy(&sin4->sin_addr,
2041 		    /* LINTED E_BAD_PTR_CAST_ALIGN */
2042 		    &((struct sockaddr_in *)result->ai_addr)->sin_addr,
2043 		    sizeof (struct in_addr));
2044 
2045 		freeaddrinfo(result);
2046 	}
2047 	return (Z_OK);
2048 }
2049 
2050 boolean_t
zonecfg_ifname_exists(sa_family_t af,char * ifname)2051 zonecfg_ifname_exists(sa_family_t af, char *ifname)
2052 {
2053 	struct lifreq lifr;
2054 	int so;
2055 	int save_errno;
2056 
2057 	(void) memset(&lifr, 0, sizeof (lifr));
2058 	(void) strlcpy(lifr.lifr_name, ifname, sizeof (lifr.lifr_name));
2059 	lifr.lifr_addr.ss_family = af;
2060 	if ((so = socket(af, SOCK_DGRAM, 0)) < 0) {
2061 		/* Odd - can't tell if the ifname exists */
2062 		return (B_FALSE);
2063 	}
2064 	if (ioctl(so, SIOCGLIFFLAGS, (caddr_t)&lifr) < 0) {
2065 		save_errno = errno;
2066 		(void) close(so);
2067 		errno = save_errno;
2068 		return (B_FALSE);
2069 	}
2070 	(void) close(so);
2071 	return (B_TRUE);
2072 }
2073 
2074 /*
2075  * Determines whether there is a net resource with the physical interface, IP
2076  * address, and default router specified by 'tabptr' in the zone configuration
2077  * to which 'handle' refers.  'tabptr' must have an interface, an address, a
2078  * default router, or a combination of the three.  This function returns Z_OK
2079  * iff there is exactly one net resource matching the query specified by
2080  * 'tabptr'.  The function returns Z_INSUFFICIENT_SPEC if there are multiple
2081  * matches or 'tabptr' does not specify a physical interface, address, or
2082  * default router.  The function returns Z_NO_RESOURCE_ID if are no matches.
2083  *
2084  * Errors might also be returned if the entry that exactly matches the
2085  * query lacks critical network resource information.
2086  *
2087  * If there is a single match, then the matching entry's physical interface, IP
2088  * address, and default router information are stored in 'tabptr'.
2089  */
2090 int
zonecfg_lookup_nwif(zone_dochandle_t handle,struct zone_nwiftab * tabptr)2091 zonecfg_lookup_nwif(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2092 {
2093 	xmlNodePtr cur;
2094 	xmlNodePtr firstmatch;
2095 	int err;
2096 	char address[INET6_ADDRSTRLEN];
2097 	char physical[LIFNAMSIZ];
2098 	size_t addrspec;		/* nonzero if tabptr has IP addr */
2099 	size_t physspec;		/* nonzero if tabptr has interface */
2100 	size_t defrouterspec;		/* nonzero if tabptr has def. router */
2101 	size_t allowed_addrspec;
2102 	zone_iptype_t iptype;
2103 
2104 	if (tabptr == NULL)
2105 		return (Z_INVAL);
2106 
2107 	/*
2108 	 * Determine the fields that will be searched.  There must be at least
2109 	 * one.
2110 	 *
2111 	 * zone_nwif_address, zone_nwif_physical, and zone_nwif_defrouter are
2112 	 * arrays, so no NULL checks are necessary.
2113 	 */
2114 	addrspec = strlen(tabptr->zone_nwif_address);
2115 	physspec = strlen(tabptr->zone_nwif_physical);
2116 	defrouterspec = strlen(tabptr->zone_nwif_defrouter);
2117 	allowed_addrspec = strlen(tabptr->zone_nwif_allowed_address);
2118 	if (addrspec != 0 && allowed_addrspec != 0)
2119 		return (Z_INVAL); /* can't specify both */
2120 	if (addrspec == 0 && physspec == 0 && defrouterspec == 0 &&
2121 	    allowed_addrspec == 0)
2122 		return (Z_INSUFFICIENT_SPEC);
2123 
2124 	if ((err = operation_prep(handle)) != Z_OK)
2125 		return (err);
2126 
2127 	if ((err = zonecfg_get_iptype(handle, &iptype)) != Z_OK)
2128 		return (err);
2129 	/*
2130 	 * Iterate over the configuration's elements and look for net elements
2131 	 * that match the query.
2132 	 */
2133 	firstmatch = NULL;
2134 	cur = handle->zone_dh_cur;
2135 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2136 		/* Skip non-net elements */
2137 		if (xmlStrcmp(cur->name, DTD_ELEM_NET))
2138 			continue;
2139 
2140 		/*
2141 		 * If any relevant fields don't match the query, then skip
2142 		 * the current net element.
2143 		 */
2144 		if (physspec != 0 && (fetchprop(cur, DTD_ATTR_PHYSICAL,
2145 		    physical, sizeof (physical)) != Z_OK ||
2146 		    strcmp(tabptr->zone_nwif_physical, physical) != 0))
2147 			continue;
2148 		if (iptype == ZS_SHARED && addrspec != 0 &&
2149 		    (fetchprop(cur, DTD_ATTR_ADDRESS, address,
2150 		    sizeof (address)) != Z_OK ||
2151 		    !zonecfg_same_net_address(tabptr->zone_nwif_address,
2152 		    address)))
2153 			continue;
2154 		if (iptype == ZS_EXCLUSIVE && allowed_addrspec != 0 &&
2155 		    (fetchprop(cur, DTD_ATTR_ALLOWED_ADDRESS, address,
2156 		    sizeof (address)) != Z_OK ||
2157 		    !zonecfg_same_net_address(tabptr->zone_nwif_allowed_address,
2158 		    address)))
2159 			continue;
2160 		if (defrouterspec != 0 && (fetchprop(cur, DTD_ATTR_DEFROUTER,
2161 		    address, sizeof (address)) != Z_OK ||
2162 		    !zonecfg_same_net_address(tabptr->zone_nwif_defrouter,
2163 		    address)))
2164 			continue;
2165 
2166 		/*
2167 		 * The current net element matches the query.  Select it if
2168 		 * it's the first match; otherwise, abort the search.
2169 		 */
2170 		if (firstmatch == NULL)
2171 			firstmatch = cur;
2172 		else
2173 			return (Z_INSUFFICIENT_SPEC);
2174 	}
2175 	if (firstmatch == NULL)
2176 		return (Z_NO_RESOURCE_ID);
2177 
2178 	cur = firstmatch;
2179 
2180 	if ((err = fetchprop(cur, DTD_ATTR_PHYSICAL, tabptr->zone_nwif_physical,
2181 	    sizeof (tabptr->zone_nwif_physical))) != Z_OK)
2182 		return (err);
2183 
2184 	if (iptype == ZS_SHARED &&
2185 	    (err = fetchprop(cur, DTD_ATTR_ADDRESS, tabptr->zone_nwif_address,
2186 	    sizeof (tabptr->zone_nwif_address))) != Z_OK)
2187 		return (err);
2188 
2189 	if (iptype == ZS_EXCLUSIVE &&
2190 	    (err = fetchprop(cur, DTD_ATTR_ALLOWED_ADDRESS,
2191 	    tabptr->zone_nwif_allowed_address,
2192 	    sizeof (tabptr->zone_nwif_allowed_address))) != Z_OK)
2193 		return (err);
2194 
2195 	if ((err = fetchprop(cur, DTD_ATTR_DEFROUTER,
2196 	    tabptr->zone_nwif_defrouter,
2197 	    sizeof (tabptr->zone_nwif_defrouter))) != Z_OK)
2198 		return (err);
2199 
2200 	return (Z_OK);
2201 }
2202 
2203 static int
zonecfg_add_nwif_core(zone_dochandle_t handle,struct zone_nwiftab * tabptr)2204 zonecfg_add_nwif_core(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2205 {
2206 	xmlNodePtr newnode, cur = handle->zone_dh_cur;
2207 	int err;
2208 
2209 	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_NET, NULL);
2210 	if (strlen(tabptr->zone_nwif_address) > 0 &&
2211 	    (err = newprop(newnode, DTD_ATTR_ADDRESS,
2212 	    tabptr->zone_nwif_address)) != Z_OK)
2213 		return (err);
2214 	if (strlen(tabptr->zone_nwif_allowed_address) > 0 &&
2215 	    (err = newprop(newnode, DTD_ATTR_ALLOWED_ADDRESS,
2216 	    tabptr->zone_nwif_allowed_address)) != Z_OK)
2217 		return (err);
2218 	if ((err = newprop(newnode, DTD_ATTR_PHYSICAL,
2219 	    tabptr->zone_nwif_physical)) != Z_OK)
2220 		return (err);
2221 	/*
2222 	 * Do not add this property when it is not set, for backwards
2223 	 * compatibility and because it is optional.
2224 	 */
2225 	if ((strlen(tabptr->zone_nwif_defrouter) > 0) &&
2226 	    ((err = newprop(newnode, DTD_ATTR_DEFROUTER,
2227 	    tabptr->zone_nwif_defrouter)) != Z_OK))
2228 		return (err);
2229 	return (Z_OK);
2230 }
2231 
2232 int
zonecfg_add_nwif(zone_dochandle_t handle,struct zone_nwiftab * tabptr)2233 zonecfg_add_nwif(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2234 {
2235 	int err;
2236 
2237 	if (tabptr == NULL)
2238 		return (Z_INVAL);
2239 
2240 	if ((err = operation_prep(handle)) != Z_OK)
2241 		return (err);
2242 
2243 	if ((err = zonecfg_add_nwif_core(handle, tabptr)) != Z_OK)
2244 		return (err);
2245 
2246 	return (Z_OK);
2247 }
2248 
2249 static int
zonecfg_delete_nwif_core(zone_dochandle_t handle,struct zone_nwiftab * tabptr)2250 zonecfg_delete_nwif_core(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2251 {
2252 	xmlNodePtr cur = handle->zone_dh_cur;
2253 	boolean_t addr_match, phys_match, allowed_addr_match;
2254 
2255 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2256 		if (xmlStrcmp(cur->name, DTD_ELEM_NET))
2257 			continue;
2258 
2259 		addr_match = match_prop(cur, DTD_ATTR_ADDRESS,
2260 		    tabptr->zone_nwif_address);
2261 		allowed_addr_match = match_prop(cur, DTD_ATTR_ALLOWED_ADDRESS,
2262 		    tabptr->zone_nwif_allowed_address);
2263 		phys_match = match_prop(cur, DTD_ATTR_PHYSICAL,
2264 		    tabptr->zone_nwif_physical);
2265 
2266 		if (addr_match && allowed_addr_match && phys_match) {
2267 			xmlUnlinkNode(cur);
2268 			xmlFreeNode(cur);
2269 			return (Z_OK);
2270 		}
2271 	}
2272 	return (Z_NO_RESOURCE_ID);
2273 }
2274 
2275 int
zonecfg_delete_nwif(zone_dochandle_t handle,struct zone_nwiftab * tabptr)2276 zonecfg_delete_nwif(zone_dochandle_t handle, struct zone_nwiftab *tabptr)
2277 {
2278 	int err;
2279 
2280 	if (tabptr == NULL)
2281 		return (Z_INVAL);
2282 
2283 	if ((err = operation_prep(handle)) != Z_OK)
2284 		return (err);
2285 
2286 	if ((err = zonecfg_delete_nwif_core(handle, tabptr)) != Z_OK)
2287 		return (err);
2288 
2289 	return (Z_OK);
2290 }
2291 
2292 int
zonecfg_modify_nwif(zone_dochandle_t handle,struct zone_nwiftab * oldtabptr,struct zone_nwiftab * newtabptr)2293 zonecfg_modify_nwif(
2294 	zone_dochandle_t handle,
2295 	struct zone_nwiftab *oldtabptr,
2296 	struct zone_nwiftab *newtabptr)
2297 {
2298 	int err;
2299 
2300 	if (oldtabptr == NULL || newtabptr == NULL)
2301 		return (Z_INVAL);
2302 
2303 	if ((err = operation_prep(handle)) != Z_OK)
2304 		return (err);
2305 
2306 	if ((err = zonecfg_delete_nwif_core(handle, oldtabptr)) != Z_OK)
2307 		return (err);
2308 
2309 	if ((err = zonecfg_add_nwif_core(handle, newtabptr)) != Z_OK)
2310 		return (err);
2311 
2312 	return (Z_OK);
2313 }
2314 
2315 /*
2316  * Must be a comma-separated list of alpha-numeric file system names.
2317  */
2318 static int
zonecfg_valid_fs_allowed(const char * fsallowedp)2319 zonecfg_valid_fs_allowed(const char *fsallowedp)
2320 {
2321 	char tmp[ZONE_FS_ALLOWED_MAX];
2322 	char *cp = tmp;
2323 	char *p;
2324 
2325 	if (strlen(fsallowedp) > ZONE_FS_ALLOWED_MAX)
2326 		return (Z_TOO_BIG);
2327 
2328 	(void) strlcpy(tmp, fsallowedp, sizeof (tmp));
2329 
2330 	while (*cp != '\0') {
2331 		p = cp;
2332 		while (*p != '\0' && *p != ',') {
2333 			if (!isalnum(*p) && *p != '-')
2334 				return (Z_INVALID_PROPERTY);
2335 			p++;
2336 		}
2337 
2338 		if (*p == ',') {
2339 			if (p == cp)
2340 				return (Z_INVALID_PROPERTY);
2341 
2342 			p++;
2343 
2344 			if (*p == '\0')
2345 				return (Z_INVALID_PROPERTY);
2346 		}
2347 
2348 		cp = p;
2349 	}
2350 
2351 	return (Z_OK);
2352 }
2353 
2354 int
zonecfg_get_fs_allowed(zone_dochandle_t handle,char * bufp,size_t buflen)2355 zonecfg_get_fs_allowed(zone_dochandle_t handle, char *bufp, size_t buflen)
2356 {
2357 	int err;
2358 
2359 	if ((err = getrootattr(handle, DTD_ATTR_FS_ALLOWED,
2360 	    bufp, buflen)) != Z_OK)
2361 		return (err);
2362 	if (bufp[0] == '\0')
2363 		return (Z_BAD_PROPERTY);
2364 	return (zonecfg_valid_fs_allowed(bufp));
2365 }
2366 
2367 int
zonecfg_set_fs_allowed(zone_dochandle_t handle,const char * bufp)2368 zonecfg_set_fs_allowed(zone_dochandle_t handle, const char *bufp)
2369 {
2370 	int err;
2371 
2372 	if (bufp == NULL || (err = zonecfg_valid_fs_allowed(bufp)) == Z_OK)
2373 		return (setrootattr(handle, DTD_ATTR_FS_ALLOWED, bufp));
2374 	return (err);
2375 }
2376 
2377 /*
2378  * Determines if the specified string is a valid hostid string.  This function
2379  * returns Z_OK if the string is a valid hostid string.  It returns Z_INVAL if
2380  * 'hostidp' is NULL, Z_TOO_BIG if 'hostidp' refers to a string buffer
2381  * containing a hex string with more than 8 digits, and Z_INVALID_PROPERTY if
2382  * the string has an invalid format.
2383  */
2384 static int
zonecfg_valid_hostid(const char * hostidp)2385 zonecfg_valid_hostid(const char *hostidp)
2386 {
2387 	char *currentp;
2388 	u_longlong_t hostidval;
2389 	size_t len;
2390 
2391 	if (hostidp == NULL)
2392 		return (Z_INVAL);
2393 
2394 	/* Empty strings and strings with whitespace are invalid. */
2395 	if (*hostidp == '\0')
2396 		return (Z_INVALID_PROPERTY);
2397 	for (currentp = (char *)hostidp; *currentp != '\0'; ++currentp) {
2398 		if (isspace(*currentp))
2399 			return (Z_INVALID_PROPERTY);
2400 	}
2401 	len = (size_t)(currentp - hostidp);
2402 
2403 	/*
2404 	 * The caller might pass a hostid that is larger than the maximum
2405 	 * unsigned 32-bit integral value.  Check for this!  Also, make sure
2406 	 * that the whole string is converted (this helps us find illegal
2407 	 * characters) and that the whole string fits within a buffer of size
2408 	 * HW_HOSTID_LEN.
2409 	 */
2410 	currentp = (char *)hostidp;
2411 	if (strncmp(hostidp, "0x", 2) == 0 || strncmp(hostidp, "0X", 2) == 0)
2412 		currentp += 2;
2413 	hostidval = strtoull(currentp, &currentp, 16);
2414 	if ((size_t)(currentp - hostidp) >= HW_HOSTID_LEN)
2415 		return (Z_TOO_BIG);
2416 	if (hostidval > UINT_MAX || hostidval == HW_INVALID_HOSTID ||
2417 	    currentp != hostidp + len)
2418 		return (Z_INVALID_PROPERTY);
2419 	return (Z_OK);
2420 }
2421 
2422 /*
2423  * Gets the zone hostid string stored in the specified zone configuration
2424  * document.  This function returns Z_OK on success.  Z_BAD_PROPERTY is returned
2425  * if the config file doesn't specify a hostid or if the hostid is blank.
2426  *
2427  * Note that buflen should be at least HW_HOSTID_LEN.
2428  */
2429 int
zonecfg_get_hostid(zone_dochandle_t handle,char * bufp,size_t buflen)2430 zonecfg_get_hostid(zone_dochandle_t handle, char *bufp, size_t buflen)
2431 {
2432 	int err;
2433 
2434 	if ((err = getrootattr(handle, DTD_ATTR_HOSTID, bufp, buflen)) != Z_OK)
2435 		return (err);
2436 	if (bufp[0] == '\0')
2437 		return (Z_BAD_PROPERTY);
2438 	return (zonecfg_valid_hostid(bufp));
2439 }
2440 
2441 /*
2442  * Sets the hostid string in the specified zone config document to the given
2443  * string value.  If 'hostidp' is NULL, then the config document's hostid
2444  * attribute is cleared.  Non-NULL hostids are validated.  This function returns
2445  * Z_OK on success.  Any other return value indicates failure.
2446  */
2447 int
zonecfg_set_hostid(zone_dochandle_t handle,const char * hostidp)2448 zonecfg_set_hostid(zone_dochandle_t handle, const char *hostidp)
2449 {
2450 	int err;
2451 
2452 	/*
2453 	 * A NULL hostid string is interpreted as a request to clear the
2454 	 * hostid.
2455 	 */
2456 	if (hostidp == NULL || (err = zonecfg_valid_hostid(hostidp)) == Z_OK)
2457 		return (setrootattr(handle, DTD_ATTR_HOSTID, hostidp));
2458 	return (err);
2459 }
2460 
2461 int
zonecfg_lookup_dev(zone_dochandle_t handle,struct zone_devtab * tabptr)2462 zonecfg_lookup_dev(zone_dochandle_t handle, struct zone_devtab *tabptr)
2463 {
2464 	xmlNodePtr cur, firstmatch;
2465 	int err;
2466 	char match[MAXPATHLEN];
2467 
2468 	if (tabptr == NULL)
2469 		return (Z_INVAL);
2470 
2471 	if ((err = operation_prep(handle)) != Z_OK)
2472 		return (err);
2473 
2474 	cur = handle->zone_dh_cur;
2475 	firstmatch = NULL;
2476 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2477 		if (xmlStrcmp(cur->name, DTD_ELEM_DEVICE))
2478 			continue;
2479 		if (strlen(tabptr->zone_dev_match) == 0)
2480 			continue;
2481 
2482 		if ((fetchprop(cur, DTD_ATTR_MATCH, match,
2483 		    sizeof (match)) == Z_OK)) {
2484 			if (strcmp(tabptr->zone_dev_match,
2485 			    match) == 0) {
2486 				if (firstmatch == NULL)
2487 					firstmatch = cur;
2488 				else if (firstmatch != cur)
2489 					return (Z_INSUFFICIENT_SPEC);
2490 			} else {
2491 				/*
2492 				 * If another property matched but this
2493 				 * one doesn't then reset firstmatch.
2494 				 */
2495 				if (firstmatch == cur)
2496 					firstmatch = NULL;
2497 			}
2498 		}
2499 	}
2500 	if (firstmatch == NULL)
2501 		return (Z_NO_RESOURCE_ID);
2502 
2503 	cur = firstmatch;
2504 
2505 	if ((err = fetchprop(cur, DTD_ATTR_MATCH, tabptr->zone_dev_match,
2506 	    sizeof (tabptr->zone_dev_match))) != Z_OK)
2507 		return (err);
2508 
2509 	return (Z_OK);
2510 }
2511 
2512 static int
zonecfg_add_dev_core(zone_dochandle_t handle,struct zone_devtab * tabptr)2513 zonecfg_add_dev_core(zone_dochandle_t handle, struct zone_devtab *tabptr)
2514 {
2515 	xmlNodePtr newnode, cur = handle->zone_dh_cur;
2516 	int err;
2517 
2518 	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_DEVICE, NULL);
2519 
2520 	if ((err = newprop(newnode, DTD_ATTR_MATCH,
2521 	    tabptr->zone_dev_match)) != Z_OK)
2522 		return (err);
2523 
2524 	return (Z_OK);
2525 }
2526 
2527 int
zonecfg_add_dev(zone_dochandle_t handle,struct zone_devtab * tabptr)2528 zonecfg_add_dev(zone_dochandle_t handle, struct zone_devtab *tabptr)
2529 {
2530 	int err;
2531 
2532 	if (tabptr == NULL)
2533 		return (Z_INVAL);
2534 
2535 	if ((err = operation_prep(handle)) != Z_OK)
2536 		return (err);
2537 
2538 	if ((err = zonecfg_add_dev_core(handle, tabptr)) != Z_OK)
2539 		return (err);
2540 
2541 	return (Z_OK);
2542 }
2543 
2544 static int
zonecfg_delete_dev_core(zone_dochandle_t handle,struct zone_devtab * tabptr)2545 zonecfg_delete_dev_core(zone_dochandle_t handle, struct zone_devtab *tabptr)
2546 {
2547 	xmlNodePtr cur = handle->zone_dh_cur;
2548 	int match_match;
2549 
2550 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2551 		if (xmlStrcmp(cur->name, DTD_ELEM_DEVICE))
2552 			continue;
2553 
2554 		match_match = match_prop(cur, DTD_ATTR_MATCH,
2555 		    tabptr->zone_dev_match);
2556 
2557 		if (match_match) {
2558 			xmlUnlinkNode(cur);
2559 			xmlFreeNode(cur);
2560 			return (Z_OK);
2561 		}
2562 	}
2563 	return (Z_NO_RESOURCE_ID);
2564 }
2565 
2566 int
zonecfg_delete_dev(zone_dochandle_t handle,struct zone_devtab * tabptr)2567 zonecfg_delete_dev(zone_dochandle_t handle, struct zone_devtab *tabptr)
2568 {
2569 	int err;
2570 
2571 	if (tabptr == NULL)
2572 		return (Z_INVAL);
2573 
2574 	if ((err = operation_prep(handle)) != Z_OK)
2575 		return (err);
2576 
2577 	if ((err = zonecfg_delete_dev_core(handle, tabptr)) != Z_OK)
2578 		return (err);
2579 
2580 	return (Z_OK);
2581 }
2582 
2583 int
zonecfg_modify_dev(zone_dochandle_t handle,struct zone_devtab * oldtabptr,struct zone_devtab * newtabptr)2584 zonecfg_modify_dev(
2585 	zone_dochandle_t handle,
2586 	struct zone_devtab *oldtabptr,
2587 	struct zone_devtab *newtabptr)
2588 {
2589 	int err;
2590 
2591 	if (oldtabptr == NULL || newtabptr == NULL)
2592 		return (Z_INVAL);
2593 
2594 	if ((err = operation_prep(handle)) != Z_OK)
2595 		return (err);
2596 
2597 	if ((err = zonecfg_delete_dev_core(handle, oldtabptr)) != Z_OK)
2598 		return (err);
2599 
2600 	if ((err = zonecfg_add_dev_core(handle, newtabptr)) != Z_OK)
2601 		return (err);
2602 
2603 	return (Z_OK);
2604 }
2605 
2606 static int
zonecfg_add_auth_core(zone_dochandle_t handle,struct zone_admintab * tabptr,char * zonename)2607 zonecfg_add_auth_core(zone_dochandle_t handle, struct zone_admintab *tabptr,
2608     char *zonename)
2609 {
2610 	xmlNodePtr newnode, cur = handle->zone_dh_cur;
2611 	int err;
2612 
2613 	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_ADMIN, NULL);
2614 	err = newprop(newnode, DTD_ATTR_USER, tabptr->zone_admin_user);
2615 	if (err != Z_OK)
2616 		return (err);
2617 	err = newprop(newnode, DTD_ATTR_AUTHS, tabptr->zone_admin_auths);
2618 	if (err != Z_OK)
2619 		return (err);
2620 	if ((err = zonecfg_remove_userauths(
2621 	    handle, tabptr->zone_admin_user, zonename, B_FALSE)) != Z_OK)
2622 		return (err);
2623 	return (Z_OK);
2624 }
2625 
2626 int
zonecfg_add_admin(zone_dochandle_t handle,struct zone_admintab * tabptr,char * zonename)2627 zonecfg_add_admin(zone_dochandle_t handle, struct zone_admintab *tabptr,
2628     char *zonename)
2629 {
2630 	int err;
2631 
2632 	if (tabptr == NULL)
2633 		return (Z_INVAL);
2634 
2635 	if ((err = operation_prep(handle)) != Z_OK)
2636 		return (err);
2637 
2638 	if ((err = zonecfg_add_auth_core(handle, tabptr,
2639 	    zonename)) != Z_OK)
2640 		return (err);
2641 
2642 	return (Z_OK);
2643 }
2644 
2645 static int
zonecfg_delete_auth_core(zone_dochandle_t handle,struct zone_admintab * tabptr,char * zonename)2646 zonecfg_delete_auth_core(zone_dochandle_t handle, struct zone_admintab *tabptr,
2647     char *zonename)
2648 {
2649 	xmlNodePtr cur = handle->zone_dh_cur;
2650 	boolean_t auth_match;
2651 	int err;
2652 
2653 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2654 		if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
2655 			continue;
2656 		auth_match = match_prop(cur, DTD_ATTR_USER,
2657 		    tabptr->zone_admin_user);
2658 		if (auth_match) {
2659 			if ((err = zonecfg_insert_userauths(
2660 			    handle, tabptr->zone_admin_user,
2661 			    zonename)) != Z_OK)
2662 				return (err);
2663 			xmlUnlinkNode(cur);
2664 			xmlFreeNode(cur);
2665 			return (Z_OK);
2666 		}
2667 	}
2668 	return (Z_NO_RESOURCE_ID);
2669 }
2670 
2671 int
zonecfg_delete_admin(zone_dochandle_t handle,struct zone_admintab * tabptr,char * zonename)2672 zonecfg_delete_admin(zone_dochandle_t handle, struct zone_admintab *tabptr,
2673     char *zonename)
2674 {
2675 	int err;
2676 
2677 	if (tabptr == NULL)
2678 		return (Z_INVAL);
2679 
2680 	if ((err = operation_prep(handle)) != Z_OK)
2681 		return (err);
2682 
2683 	if ((err = zonecfg_delete_auth_core(handle, tabptr, zonename)) != Z_OK)
2684 		return (err);
2685 
2686 	return (Z_OK);
2687 }
2688 
2689 int
zonecfg_modify_admin(zone_dochandle_t handle,struct zone_admintab * oldtabptr,struct zone_admintab * newtabptr,char * zonename)2690 zonecfg_modify_admin(zone_dochandle_t handle, struct zone_admintab *oldtabptr,
2691     struct zone_admintab *newtabptr, char *zonename)
2692 {
2693 	int err;
2694 
2695 	if (oldtabptr == NULL || newtabptr == NULL)
2696 		return (Z_INVAL);
2697 
2698 	if ((err = operation_prep(handle)) != Z_OK)
2699 		return (err);
2700 
2701 	if ((err = zonecfg_delete_auth_core(handle, oldtabptr, zonename))
2702 	    != Z_OK)
2703 		return (err);
2704 
2705 	if ((err = zonecfg_add_auth_core(handle, newtabptr,
2706 	    zonename)) != Z_OK)
2707 		return (err);
2708 
2709 	return (Z_OK);
2710 }
2711 
2712 int
zonecfg_lookup_admin(zone_dochandle_t handle,struct zone_admintab * tabptr)2713 zonecfg_lookup_admin(zone_dochandle_t handle, struct zone_admintab *tabptr)
2714 {
2715 	xmlNodePtr cur, firstmatch;
2716 	int err;
2717 	char user[MAXUSERNAME];
2718 
2719 	if (tabptr == NULL)
2720 		return (Z_INVAL);
2721 
2722 	if ((err = operation_prep(handle)) != Z_OK)
2723 		return (err);
2724 
2725 	cur = handle->zone_dh_cur;
2726 	firstmatch = NULL;
2727 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2728 		if (xmlStrcmp(cur->name, DTD_ELEM_ADMIN))
2729 			continue;
2730 		if (strlen(tabptr->zone_admin_user) > 0) {
2731 			if ((fetchprop(cur, DTD_ATTR_USER, user,
2732 			    sizeof (user)) == Z_OK) &&
2733 			    (strcmp(tabptr->zone_admin_user, user) == 0)) {
2734 				if (firstmatch == NULL)
2735 					firstmatch = cur;
2736 				else
2737 					return (Z_INSUFFICIENT_SPEC);
2738 			}
2739 		}
2740 	}
2741 	if (firstmatch == NULL)
2742 		return (Z_NO_RESOURCE_ID);
2743 
2744 	cur = firstmatch;
2745 
2746 	if ((err = fetchprop(cur, DTD_ATTR_USER, tabptr->zone_admin_user,
2747 	    sizeof (tabptr->zone_admin_user))) != Z_OK)
2748 		return (err);
2749 
2750 	if ((err = fetchprop(cur, DTD_ATTR_AUTHS, tabptr->zone_admin_auths,
2751 	    sizeof (tabptr->zone_admin_auths))) != Z_OK)
2752 		return (err);
2753 
2754 	return (Z_OK);
2755 }
2756 
2757 static int
zonecfg_add_secflags_core(zone_dochandle_t handle,struct zone_secflagstab * tabptr)2758 zonecfg_add_secflags_core(zone_dochandle_t handle,
2759     struct zone_secflagstab *tabptr)
2760 {
2761 	xmlNodePtr newnode, cur = handle->zone_dh_cur;
2762 	int err;
2763 
2764 	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_SECFLAGS, NULL);
2765 	err = newprop(newnode, DTD_ATTR_DEFAULT, tabptr->zone_secflags_default);
2766 	if (err != Z_OK)
2767 		return (err);
2768 	err = newprop(newnode, DTD_ATTR_LOWER, tabptr->zone_secflags_lower);
2769 	if (err != Z_OK)
2770 		return (err);
2771 	err = newprop(newnode, DTD_ATTR_UPPER, tabptr->zone_secflags_upper);
2772 	if (err != Z_OK)
2773 		return (err);
2774 
2775 	return (Z_OK);
2776 }
2777 
2778 int
zonecfg_add_secflags(zone_dochandle_t handle,struct zone_secflagstab * tabptr)2779 zonecfg_add_secflags(zone_dochandle_t handle, struct zone_secflagstab *tabptr)
2780 {
2781 	int err;
2782 
2783 
2784 	if (tabptr == NULL)
2785 		return (Z_INVAL);
2786 
2787 	if ((err = operation_prep(handle)) != Z_OK)
2788 		return (err);
2789 
2790 	if ((err = zonecfg_add_secflags_core(handle, tabptr)) != Z_OK)
2791 		return (err);
2792 
2793 	return (Z_OK);
2794 }
2795 
2796 static int
zonecfg_delete_secflags_core(zone_dochandle_t handle,struct zone_secflagstab * tabptr)2797 zonecfg_delete_secflags_core(zone_dochandle_t handle,
2798     struct zone_secflagstab *tabptr)
2799 {
2800 	xmlNodePtr cur = handle->zone_dh_cur;
2801 	boolean_t def_match, low_match, up_match;
2802 
2803 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2804 		if (xmlStrcmp(cur->name, DTD_ELEM_SECFLAGS) != 0)
2805 			continue;
2806 
2807 		def_match = match_prop(cur, DTD_ATTR_DEFAULT,
2808 		    tabptr->zone_secflags_default);
2809 		low_match = match_prop(cur, DTD_ATTR_LOWER,
2810 		    tabptr->zone_secflags_lower);
2811 		up_match = match_prop(cur, DTD_ATTR_UPPER,
2812 		    tabptr->zone_secflags_upper);
2813 
2814 		if (def_match && low_match && up_match) {
2815 			xmlUnlinkNode(cur);
2816 			xmlFreeNode(cur);
2817 			return (Z_OK);
2818 		}
2819 
2820 	}
2821 	return (Z_NO_RESOURCE_ID);
2822 }
2823 
2824 int
zonecfg_delete_secflags(zone_dochandle_t handle,struct zone_secflagstab * tabptr)2825 zonecfg_delete_secflags(zone_dochandle_t handle,
2826     struct zone_secflagstab *tabptr)
2827 {
2828 	int err;
2829 
2830 	if (tabptr == NULL)
2831 		return (Z_INVAL);
2832 
2833 	if ((err = operation_prep(handle)) != Z_OK)
2834 		return (err);
2835 
2836 	if ((err = zonecfg_delete_secflags_core(handle, tabptr)) != Z_OK)
2837 		return (err);
2838 
2839 	return (Z_OK);
2840 }
2841 
2842 int
zonecfg_modify_secflags(zone_dochandle_t handle,struct zone_secflagstab * oldtabptr,struct zone_secflagstab * newtabptr)2843 zonecfg_modify_secflags(zone_dochandle_t handle,
2844     struct zone_secflagstab *oldtabptr,
2845     struct zone_secflagstab *newtabptr)
2846 {
2847 	int err;
2848 
2849 	if (oldtabptr == NULL || newtabptr == NULL)
2850 		return (Z_INVAL);
2851 
2852 	if ((err = operation_prep(handle)) != Z_OK)
2853 		return (err);
2854 
2855 	if ((err = zonecfg_delete_secflags_core(handle, oldtabptr))
2856 	    != Z_OK)
2857 		return (err);
2858 
2859 	if ((err = zonecfg_add_secflags_core(handle, newtabptr)) != Z_OK)
2860 		return (err);
2861 
2862 	return (Z_OK);
2863 }
2864 
2865 int
zonecfg_lookup_secflags(zone_dochandle_t handle,struct zone_secflagstab * tabptr)2866 zonecfg_lookup_secflags(zone_dochandle_t handle,
2867     struct zone_secflagstab *tabptr)
2868 {
2869 	xmlNodePtr cur;
2870 	int err;
2871 
2872 	if (tabptr == NULL)
2873 		return (Z_INVAL);
2874 
2875 	if ((err = operation_prep(handle)) != Z_OK)
2876 		return (err);
2877 
2878 	cur = handle->zone_dh_cur;
2879 
2880 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
2881 		if (xmlStrcmp(cur->name, DTD_ELEM_SECFLAGS) != 0)
2882 			continue;
2883 
2884 		if ((err = fetchprop(cur, DTD_ATTR_DEFAULT,
2885 		    tabptr->zone_secflags_default,
2886 		    sizeof (tabptr->zone_secflags_default))) != Z_OK) {
2887 			handle->zone_dh_cur = handle->zone_dh_top;
2888 			return (err);
2889 		}
2890 
2891 		if ((err = fetchprop(cur, DTD_ATTR_LOWER,
2892 		    tabptr->zone_secflags_lower,
2893 		    sizeof (tabptr->zone_secflags_lower))) != Z_OK) {
2894 			handle->zone_dh_cur = handle->zone_dh_top;
2895 			return (err);
2896 		}
2897 
2898 		if ((err = fetchprop(cur, DTD_ATTR_UPPER,
2899 		    tabptr->zone_secflags_upper,
2900 		    sizeof (tabptr->zone_secflags_upper))) != Z_OK) {
2901 			handle->zone_dh_cur = handle->zone_dh_top;
2902 			return (err);
2903 		}
2904 
2905 		return (Z_OK);
2906 	}
2907 
2908 	return (Z_NO_ENTRY);
2909 }
2910 
2911 /* Lock to serialize all devwalks */
2912 static pthread_mutex_t zonecfg_devwalk_lock = PTHREAD_MUTEX_INITIALIZER;
2913 /*
2914  * Global variables used to pass data from zonecfg_dev_manifest to the nftw
2915  * call-back (zonecfg_devwalk_cb).  g_devwalk_data is really the void*
2916  * parameter and g_devwalk_cb is really the *cb parameter from
2917  * zonecfg_dev_manifest.
2918  */
2919 typedef struct __g_devwalk_data *g_devwalk_data_t;
2920 static g_devwalk_data_t g_devwalk_data;
2921 static int (*g_devwalk_cb)(const char *, uid_t, gid_t, mode_t, const char *,
2922     void *);
2923 static size_t g_devwalk_skip_prefix;
2924 
2925 /*
2926  * zonecfg_dev_manifest call-back function used during detach to generate the
2927  * dev info in the manifest.
2928  */
2929 static int
get_detach_dev_entry(const char * name,uid_t uid,gid_t gid,mode_t mode,const char * acl,void * hdl)2930 get_detach_dev_entry(const char *name, uid_t uid, gid_t gid, mode_t mode,
2931     const char *acl, void *hdl)
2932 {
2933 	zone_dochandle_t handle = (zone_dochandle_t)hdl;
2934 	xmlNodePtr newnode;
2935 	xmlNodePtr cur;
2936 	int err;
2937 	char buf[128];
2938 
2939 	if ((err = operation_prep(handle)) != Z_OK)
2940 		return (err);
2941 
2942 	cur = handle->zone_dh_cur;
2943 	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_DEV_PERM, NULL);
2944 	if ((err = newprop(newnode, DTD_ATTR_NAME, (char *)name)) != Z_OK)
2945 		return (err);
2946 	(void) snprintf(buf, sizeof (buf), "%lu", uid);
2947 	if ((err = newprop(newnode, DTD_ATTR_UID, buf)) != Z_OK)
2948 		return (err);
2949 	(void) snprintf(buf, sizeof (buf), "%lu", gid);
2950 	if ((err = newprop(newnode, DTD_ATTR_GID, buf)) != Z_OK)
2951 		return (err);
2952 	(void) snprintf(buf, sizeof (buf), "%o", mode);
2953 	if ((err = newprop(newnode, DTD_ATTR_MODE, buf)) != Z_OK)
2954 		return (err);
2955 	if ((err = newprop(newnode, DTD_ATTR_ACL, (char *)acl)) != Z_OK)
2956 		return (err);
2957 	return (Z_OK);
2958 }
2959 
2960 /*
2961  * This is the nftw call-back function used by zonecfg_dev_manifest.  It is
2962  * responsible for calling the actual call-back.
2963  */
2964 /* ARGSUSED2 */
2965 static int
zonecfg_devwalk_cb(const char * path,const struct stat * st,int f,struct FTW * ftw)2966 zonecfg_devwalk_cb(const char *path, const struct stat *st, int f,
2967     struct FTW *ftw)
2968 {
2969 	acl_t *acl;
2970 	char *acl_txt = NULL;
2971 
2972 	/* skip all but character and block devices */
2973 	if (!S_ISBLK(st->st_mode) && !S_ISCHR(st->st_mode))
2974 		return (0);
2975 
2976 	if ((acl_get(path, ACL_NO_TRIVIAL, &acl) == 0) &&
2977 	    acl != NULL) {
2978 		acl_txt = acl_totext(acl, ACL_NORESOLVE);
2979 		acl_free(acl);
2980 	}
2981 
2982 	if (strlen(path) <= g_devwalk_skip_prefix)
2983 		return (0);
2984 
2985 	(void) g_devwalk_cb(path + g_devwalk_skip_prefix, st->st_uid,
2986 	    st->st_gid, st->st_mode & S_IAMB, acl_txt != NULL ? acl_txt : "",
2987 	    g_devwalk_data);
2988 	free(acl_txt);
2989 	return (0);
2990 }
2991 
2992 /*
2993  * Walk the dev tree for the zone specified by hdl and call the
2994  * get_detach_dev_entry call-back function for each entry in the tree.  The
2995  * call-back will be passed the name, uid, gid, mode, acl string and the
2996  * handle input parameter for each dev entry.
2997  *
2998  * Data is passed to get_detach_dev_entry through the global variables
2999  * g_devwalk_data, *g_devwalk_cb, and g_devwalk_skip_prefix.  The
3000  * zonecfg_devwalk_cb function will actually call get_detach_dev_entry.
3001  */
3002 int
zonecfg_dev_manifest(zone_dochandle_t hdl)3003 zonecfg_dev_manifest(zone_dochandle_t hdl)
3004 {
3005 	char path[MAXPATHLEN];
3006 	int ret;
3007 
3008 	if ((ret = zonecfg_get_zonepath(hdl, path, sizeof (path))) != Z_OK)
3009 		return (ret);
3010 
3011 	if (strlcat(path, "/dev", sizeof (path)) >= sizeof (path))
3012 		return (Z_TOO_BIG);
3013 
3014 	/*
3015 	 * We have to serialize all devwalks in the same process
3016 	 * (which should be fine), since nftw() is so badly designed.
3017 	 */
3018 	(void) pthread_mutex_lock(&zonecfg_devwalk_lock);
3019 
3020 	g_devwalk_skip_prefix = strlen(path) + 1;
3021 	g_devwalk_data = (g_devwalk_data_t)hdl;
3022 	g_devwalk_cb = get_detach_dev_entry;
3023 	(void) nftw(path, zonecfg_devwalk_cb, 0, FTW_PHYS);
3024 
3025 	(void) pthread_mutex_unlock(&zonecfg_devwalk_lock);
3026 	return (Z_OK);
3027 }
3028 
3029 /*
3030  * Update the owner, group, mode and acl on the specified dev (inpath) for
3031  * the zone (hdl).  This function can be used to fix up the dev tree after
3032  * attaching a migrated zone.
3033  */
3034 int
zonecfg_devperms_apply(zone_dochandle_t hdl,const char * inpath,uid_t owner,gid_t group,mode_t mode,const char * acltxt)3035 zonecfg_devperms_apply(zone_dochandle_t hdl, const char *inpath, uid_t owner,
3036     gid_t group, mode_t mode, const char *acltxt)
3037 {
3038 	int ret;
3039 	char path[MAXPATHLEN];
3040 	struct stat st;
3041 	acl_t *aclp;
3042 
3043 	if ((ret = zonecfg_get_zonepath(hdl, path, sizeof (path))) != Z_OK)
3044 		return (ret);
3045 
3046 	if (strlcat(path, "/dev/", sizeof (path)) >= sizeof (path))
3047 		return (Z_TOO_BIG);
3048 	if (strlcat(path, inpath, sizeof (path)) >= sizeof (path))
3049 		return (Z_TOO_BIG);
3050 
3051 	if (stat(path, &st) == -1)
3052 		return (Z_INVAL);
3053 
3054 	/* make sure we're only touching device nodes */
3055 	if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode))
3056 		return (Z_INVAL);
3057 
3058 	if (chown(path, owner, group) == -1)
3059 		return (Z_SYSTEM);
3060 
3061 	if (chmod(path, mode) == -1)
3062 		return (Z_SYSTEM);
3063 
3064 	if ((acltxt == NULL) || (strcmp(acltxt, "") == 0))
3065 		return (Z_OK);
3066 
3067 	if (acl_fromtext(acltxt, &aclp) != 0) {
3068 		errno = EINVAL;
3069 		return (Z_SYSTEM);
3070 	}
3071 
3072 	errno = 0;
3073 	if (acl_set(path, aclp) == -1) {
3074 		free(aclp);
3075 		return (Z_SYSTEM);
3076 	}
3077 
3078 	free(aclp);
3079 	return (Z_OK);
3080 }
3081 
3082 /*
3083  * This function finds everything mounted under a zone's rootpath.
3084  * This returns the number of mounts under rootpath, or -1 on error.
3085  * callback is called once per mount found with the first argument
3086  * pointing to a mnttab structure containing the mount's information.
3087  *
3088  * If the callback function returns non-zero zonecfg_find_mounts
3089  * aborts with an error.
3090  */
3091 int
zonecfg_find_mounts(char * rootpath,int (* callback)(const struct mnttab *,void *),void * priv)3092 zonecfg_find_mounts(char *rootpath, int (*callback)(const struct mnttab *,
3093     void *), void *priv)
3094 {
3095 	FILE *mnttab;
3096 	struct mnttab m;
3097 	size_t l;
3098 	int zfsl;
3099 	int rv = 0;
3100 	char zfs_path[MAXPATHLEN];
3101 
3102 	assert(rootpath != NULL);
3103 
3104 	if ((zfsl = snprintf(zfs_path, sizeof (zfs_path), "%s/.zfs/", rootpath))
3105 	    >= sizeof (zfs_path))
3106 		return (-1);
3107 
3108 	l = strlen(rootpath);
3109 
3110 	mnttab = fopen("/etc/mnttab", "r");
3111 
3112 	if (mnttab == NULL)
3113 		return (-1);
3114 
3115 	if (ioctl(fileno(mnttab), MNTIOC_SHOWHIDDEN, NULL) < 0)  {
3116 		rv = -1;
3117 		goto out;
3118 	}
3119 
3120 	while (!getmntent(mnttab, &m)) {
3121 		if ((strncmp(rootpath, m.mnt_mountp, l) == 0) &&
3122 		    (m.mnt_mountp[l] == '/') &&
3123 		    (strncmp(zfs_path, m.mnt_mountp, zfsl) != 0)) {
3124 			rv++;
3125 			if (callback == NULL)
3126 				continue;
3127 			if (callback(&m, priv)) {
3128 				rv = -1;
3129 				goto out;
3130 
3131 			}
3132 		}
3133 	}
3134 
3135 out:
3136 	(void) fclose(mnttab);
3137 	return (rv);
3138 }
3139 
3140 int
zonecfg_lookup_attr(zone_dochandle_t handle,struct zone_attrtab * tabptr)3141 zonecfg_lookup_attr(zone_dochandle_t handle, struct zone_attrtab *tabptr)
3142 {
3143 	xmlNodePtr cur, firstmatch;
3144 	int err;
3145 	char name[MAXNAMELEN], type[MAXNAMELEN], value[MAXNAMELEN];
3146 
3147 	if (tabptr == NULL)
3148 		return (Z_INVAL);
3149 
3150 	if ((err = operation_prep(handle)) != Z_OK)
3151 		return (err);
3152 
3153 	cur = handle->zone_dh_cur;
3154 	firstmatch = NULL;
3155 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
3156 		if (xmlStrcmp(cur->name, DTD_ELEM_ATTR))
3157 			continue;
3158 		if (strlen(tabptr->zone_attr_name) > 0) {
3159 			if ((fetchprop(cur, DTD_ATTR_NAME, name,
3160 			    sizeof (name)) == Z_OK) &&
3161 			    (strcmp(tabptr->zone_attr_name, name) == 0)) {
3162 				if (firstmatch == NULL)
3163 					firstmatch = cur;
3164 				else
3165 					return (Z_INSUFFICIENT_SPEC);
3166 			}
3167 		}
3168 		if (strlen(tabptr->zone_attr_type) > 0) {
3169 			if ((fetchprop(cur, DTD_ATTR_TYPE, type,
3170 			    sizeof (type)) == Z_OK)) {
3171 				if (strcmp(tabptr->zone_attr_type, type) == 0) {
3172 					if (firstmatch == NULL)
3173 						firstmatch = cur;
3174 					else if (firstmatch != cur)
3175 						return (Z_INSUFFICIENT_SPEC);
3176 				} else {
3177 					/*
3178 					 * If another property matched but this
3179 					 * one doesn't then reset firstmatch.
3180 					 */
3181 					if (firstmatch == cur)
3182 						firstmatch = NULL;
3183 				}
3184 			}
3185 		}
3186 		if (strlen(tabptr->zone_attr_value) > 0) {
3187 			if ((fetchprop(cur, DTD_ATTR_VALUE, value,
3188 			    sizeof (value)) == Z_OK)) {
3189 				if (strcmp(tabptr->zone_attr_value, value) ==
3190 				    0) {
3191 					if (firstmatch == NULL)
3192 						firstmatch = cur;
3193 					else if (firstmatch != cur)
3194 						return (Z_INSUFFICIENT_SPEC);
3195 				} else {
3196 					/*
3197 					 * If another property matched but this
3198 					 * one doesn't then reset firstmatch.
3199 					 */
3200 					if (firstmatch == cur)
3201 						firstmatch = NULL;
3202 				}
3203 			}
3204 		}
3205 	}
3206 	if (firstmatch == NULL)
3207 		return (Z_NO_RESOURCE_ID);
3208 
3209 	cur = firstmatch;
3210 
3211 	if ((err = fetchprop(cur, DTD_ATTR_NAME, tabptr->zone_attr_name,
3212 	    sizeof (tabptr->zone_attr_name))) != Z_OK)
3213 		return (err);
3214 
3215 	if ((err = fetchprop(cur, DTD_ATTR_TYPE, tabptr->zone_attr_type,
3216 	    sizeof (tabptr->zone_attr_type))) != Z_OK)
3217 		return (err);
3218 
3219 	if ((err = fetchprop(cur, DTD_ATTR_VALUE, tabptr->zone_attr_value,
3220 	    sizeof (tabptr->zone_attr_value))) != Z_OK)
3221 		return (err);
3222 
3223 	return (Z_OK);
3224 }
3225 
3226 static int
zonecfg_add_attr_core(zone_dochandle_t handle,struct zone_attrtab * tabptr)3227 zonecfg_add_attr_core(zone_dochandle_t handle, struct zone_attrtab *tabptr)
3228 {
3229 	xmlNodePtr newnode, cur = handle->zone_dh_cur;
3230 	int err;
3231 
3232 	newnode = xmlNewTextChild(cur, NULL, DTD_ELEM_ATTR, NULL);
3233 	err = newprop(newnode, DTD_ATTR_NAME, tabptr->zone_attr_name);
3234 	if (err != Z_OK)
3235 		return (err);
3236 	err = newprop(newnode, DTD_ATTR_TYPE, tabptr->zone_attr_type);
3237 	if (err != Z_OK)
3238 		return (err);
3239 	err = newprop(newnode, DTD_ATTR_VALUE, tabptr->zone_attr_value);
3240 	if (err != Z_OK)
3241 		return (err);
3242 	return (Z_OK);
3243 }
3244 
3245 int
zonecfg_add_attr(zone_dochandle_t handle,struct zone_attrtab * tabptr)3246 zonecfg_add_attr(zone_dochandle_t handle, struct zone_attrtab *tabptr)
3247 {
3248 	int err;
3249 
3250 	if (tabptr == NULL)
3251 		return (Z_INVAL);
3252 
3253 	if ((err = operation_prep(handle)) != Z_OK)
3254 		return (err);
3255 
3256 	if ((err = zonecfg_add_attr_core(handle, tabptr)) != Z_OK)
3257 		return (err);
3258 
3259 	return (Z_OK);
3260 }
3261 
3262 static int
zonecfg_delete_attr_core(zone_dochandle_t handle,struct zone_attrtab * tabptr)3263 zonecfg_delete_attr_core(zone_dochandle_t handle, struct zone_attrtab *tabptr)
3264 {
3265 	xmlNodePtr cur = handle->zone_dh_cur;
3266 	int name_match, type_match, value_match;
3267 
3268 	for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
3269 		if (xmlStrcmp(cur->name, DTD_ELEM_ATTR))
3270 			continue;
3271 
3272 		name_match = match_prop(cur, DTD_ATTR_NAME,
3273 		    tabptr->zone_attr_name);
3274 		type_match = match_prop(cur, DTD_ATTR_TYPE,
3275 		    tabptr->zone_attr_type);
3276 		value_match = match_prop(cur, DTD_ATTR_VALUE,
3277 		    tabptr->zone_attr_value);
3278 
3279 		if (name_match && type_match && value_match) {
3280 			xmlUnlinkNode(cur);
3281 			xmlFreeNode(cur);
3282 			return (Z_OK);
3283 		}
3284 	}
3285 	return (Z_NO_RESOURCE_ID);
3286 }
3287 
3288 int
zonecfg_delete_attr(zone_dochandle_t handle,struct zone_attrtab * tabptr)3289 zonecfg_delete_attr(zone_dochandle_t handle, struct zone_attrtab *tabptr)
3290 {
3291 	int err;
3292 
3293 	if (tabptr == NULL)
3294 		return (Z_INVAL);
3295 
3296 	if ((err = operation_prep(handle)) != Z_OK)
3297 		return (err);
3298 
3299 	if ((err = zonecfg_delete_attr_core(handle, tabptr)) != Z_OK)
3300 		return (err);
3301 
3302 	return (Z_OK);
3303 }
3304 
3305 int
zonecfg_modify_attr(zone_dochandle_t handle,struct zone_attrtab * oldtabptr,struct zone_attrtab * newtabptr)3306 zonecfg_modify_attr(