xref: /titanic_51/usr/src/cmd/svc/svccfg/svccfg_libscf.c (revision 8c1d5be330d8ad770aaaa74b0da6cac9139842af)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, Joyent, Inc. All rights reserved.
25  * Copyright 2012 Milan Jurik. All rights reserved.
26  */
27 
28 
29 #include <alloca.h>
30 #include <assert.h>
31 #include <ctype.h>
32 #include <door.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <fnmatch.h>
36 #include <inttypes.h>
37 #include <libintl.h>
38 #include <libnvpair.h>
39 #include <libscf.h>
40 #include <libscf_priv.h>
41 #include <libtecla.h>
42 #include <libuutil.h>
43 #include <limits.h>
44 #include <locale.h>
45 #include <stdarg.h>
46 #include <string.h>
47 #include <strings.h>
48 #include <time.h>
49 #include <unistd.h>
50 #include <wait.h>
51 #include <poll.h>
52 
53 #include <libxml/tree.h>
54 
55 #include <sys/param.h>
56 
57 #include <sys/stat.h>
58 #include <sys/mman.h>
59 
60 #include "svccfg.h"
61 #include "notify_params.h"
62 #include "manifest_hash.h"
63 #include "manifest_find.h"
64 
65 /* The colon namespaces in each entity (each followed by a newline). */
66 #define	COLON_NAMESPACES	":properties\n"
67 
68 #define	TEMP_FILE_PATTERN	"/tmp/svccfg-XXXXXX"
69 
70 /* These are characters which the lexer requires to be in double-quotes. */
71 #define	CHARS_TO_QUOTE		" \t\n\\>=\"()"
72 
73 #define	HASH_SIZE		16
74 #define	HASH_PG_TYPE		"framework"
75 #define	HASH_PG_FLAGS		0
76 #define	HASH_PROP		"md5sum"
77 
78 /*
79  * Indentation used in the output of the describe subcommand.
80  */
81 #define	TMPL_VALUE_INDENT	"  "
82 #define	TMPL_INDENT		"    "
83 #define	TMPL_INDENT_2X		"        "
84 #define	TMPL_CHOICE_INDENT	"      "
85 
86 /*
87  * Directory locations for manifests
88  */
89 #define	VARSVC_DIR		"/var/svc/manifest"
90 #define	LIBSVC_DIR		"/lib/svc/manifest"
91 #define	VARSVC_PR		"var_svc_manifest"
92 #define	LIBSVC_PR		"lib_svc_manifest"
93 #define	MFSTFILEPR		"manifestfile"
94 
95 #define	SUPPORTPROP		"support"
96 
97 #define	MFSTHISTFILE		"/lib/svc/share/mfsthistory"
98 
99 #define	MFSTFILE_MAX		16
100 
101 /*
102  * These are the classes of elements which may appear as children of service
103  * or instance elements in XML manifests.
104  */
105 struct entity_elts {
106 	xmlNodePtr	create_default_instance;
107 	xmlNodePtr	single_instance;
108 	xmlNodePtr	restarter;
109 	xmlNodePtr	dependencies;
110 	xmlNodePtr	dependents;
111 	xmlNodePtr	method_context;
112 	xmlNodePtr	exec_methods;
113 	xmlNodePtr	notify_params;
114 	xmlNodePtr	property_groups;
115 	xmlNodePtr	instances;
116 	xmlNodePtr	stability;
117 	xmlNodePtr	template;
118 };
119 
120 /*
121  * Likewise for property_group elements.
122  */
123 struct pg_elts {
124 	xmlNodePtr	stability;
125 	xmlNodePtr	propvals;
126 	xmlNodePtr	properties;
127 };
128 
129 /*
130  * Likewise for template elements.
131  */
132 struct template_elts {
133 	xmlNodePtr	common_name;
134 	xmlNodePtr	description;
135 	xmlNodePtr	documentation;
136 };
137 
138 /*
139  * Likewise for type (for notification parameters) elements.
140  */
141 struct params_elts {
142 	xmlNodePtr	paramval;
143 	xmlNodePtr	parameter;
144 };
145 
146 /*
147  * This structure is for snaplevel lists.  They are convenient because libscf
148  * only allows traversing snaplevels in one direction.
149  */
150 struct snaplevel {
151 	uu_list_node_t	list_node;
152 	scf_snaplevel_t	*sl;
153 };
154 
155 /*
156  * This is used for communication between lscf_service_export and
157  * export_callback.
158  */
159 struct export_args {
160 	const char	*filename;
161 	int 		flags;
162 };
163 
164 /*
165  * The service_manifest structure is used by the upgrade process
166  * to create a list of service to manifest linkages from the manifests
167  * in a set of given directories.
168  */
169 typedef struct service_manifest {
170 	const char 	*servicename;
171 	uu_list_t	*mfstlist;
172 	size_t	mfstlist_sz;
173 
174 	uu_avl_node_t	svcmfst_node;
175 } service_manifest_t;
176 
177 /*
178  * Structure to track the manifest file property group
179  * and the manifest file associated with that property
180  * group.  Also, a flag to keep the access once it has
181  * been checked.
182  */
183 struct mpg_mfile {
184 	char	*mpg;
185 	char	*mfile;
186 	int	access;
187 };
188 
189 const char * const scf_pg_general = SCF_PG_GENERAL;
190 const char * const scf_group_framework = SCF_GROUP_FRAMEWORK;
191 const char * const scf_property_enabled = SCF_PROPERTY_ENABLED;
192 const char * const scf_property_external = "external";
193 
194 const char * const snap_initial = "initial";
195 const char * const snap_lastimport = "last-import";
196 const char * const snap_previous = "previous";
197 const char * const snap_running = "running";
198 
199 scf_handle_t *g_hndl = NULL;	/* only valid after lscf_prep_hndl() */
200 
201 ssize_t max_scf_fmri_len;
202 ssize_t max_scf_name_len;
203 ssize_t max_scf_pg_type_len;
204 ssize_t max_scf_value_len;
205 static size_t max_scf_len;
206 
207 static scf_scope_t *cur_scope;
208 static scf_service_t *cur_svc = NULL;
209 static scf_instance_t *cur_inst = NULL;
210 static scf_snapshot_t *cur_snap = NULL;
211 static scf_snaplevel_t *cur_level = NULL;
212 
213 static uu_list_pool_t *snaplevel_pool;
214 /* cur_levels is the snaplevels of cur_snap, from least specific to most. */
215 static uu_list_t *cur_levels;
216 static struct snaplevel *cur_elt;		/* cur_elt->sl == cur_level */
217 
218 static FILE *tempfile = NULL;
219 static char tempfilename[sizeof (TEMP_FILE_PATTERN)] = "";
220 
221 static const char *emsg_entity_not_selected;
222 static const char *emsg_permission_denied;
223 static const char *emsg_create_xml;
224 static const char *emsg_cant_modify_snapshots;
225 static const char *emsg_invalid_for_snapshot;
226 static const char *emsg_read_only;
227 static const char *emsg_deleted;
228 static const char *emsg_invalid_pg_name;
229 static const char *emsg_invalid_prop_name;
230 static const char *emsg_no_such_pg;
231 static const char *emsg_fmri_invalid_pg_name;
232 static const char *emsg_fmri_invalid_pg_name_type;
233 static const char *emsg_pg_added;
234 static const char *emsg_pg_changed;
235 static const char *emsg_pg_deleted;
236 static const char *emsg_pg_mod_perm;
237 static const char *emsg_pg_add_perm;
238 static const char *emsg_pg_del_perm;
239 static const char *emsg_snap_perm;
240 static const char *emsg_dpt_dangling;
241 static const char *emsg_dpt_no_dep;
242 
243 static int li_only = 0;
244 static int no_refresh = 0;
245 
246 /* how long in ns we should wait between checks for a pg */
247 static uint64_t pg_timeout = 100 * (NANOSEC / MILLISEC);
248 
249 /* import globals, to minimize allocations */
250 static scf_scope_t *imp_scope = NULL;
251 static scf_service_t *imp_svc = NULL, *imp_tsvc = NULL;
252 static scf_instance_t *imp_inst = NULL, *imp_tinst = NULL;
253 static scf_snapshot_t *imp_snap = NULL, *imp_lisnap = NULL, *imp_tlisnap = NULL;
254 static scf_snapshot_t *imp_rsnap = NULL;
255 static scf_snaplevel_t *imp_snpl = NULL, *imp_rsnpl = NULL;
256 static scf_propertygroup_t *imp_pg = NULL, *imp_pg2 = NULL;
257 static scf_property_t *imp_prop = NULL;
258 static scf_iter_t *imp_iter = NULL;
259 static scf_iter_t *imp_rpg_iter = NULL;
260 static scf_iter_t *imp_up_iter = NULL;
261 static scf_transaction_t *imp_tx = NULL;	/* always reset this */
262 static char *imp_str = NULL;
263 static size_t imp_str_sz;
264 static char *imp_tsname = NULL;
265 static char *imp_fe1 = NULL;		/* for fmri_equal() */
266 static char *imp_fe2 = NULL;
267 static uu_list_t *imp_deleted_dpts = NULL;	/* pgroup_t's to refresh */
268 
269 /* upgrade_dependents() globals */
270 static scf_instance_t *ud_inst = NULL;
271 static scf_snaplevel_t *ud_snpl = NULL;
272 static scf_propertygroup_t *ud_pg = NULL;
273 static scf_propertygroup_t *ud_cur_depts_pg = NULL;
274 static scf_propertygroup_t *ud_run_dpts_pg = NULL;
275 static int ud_run_dpts_pg_set = 0;
276 static scf_property_t *ud_prop = NULL;
277 static scf_property_t *ud_dpt_prop = NULL;
278 static scf_value_t *ud_val = NULL;
279 static scf_iter_t *ud_iter = NULL, *ud_iter2 = NULL;
280 static scf_transaction_t *ud_tx = NULL;
281 static char *ud_ctarg = NULL;
282 static char *ud_oldtarg = NULL;
283 static char *ud_name = NULL;
284 
285 /* export globals */
286 static scf_instance_t *exp_inst;
287 static scf_propertygroup_t *exp_pg;
288 static scf_property_t *exp_prop;
289 static scf_value_t *exp_val;
290 static scf_iter_t *exp_inst_iter, *exp_pg_iter, *exp_prop_iter, *exp_val_iter;
291 static char *exp_str;
292 static size_t exp_str_sz;
293 
294 /* cleanup globals */
295 static uu_avl_pool_t *service_manifest_pool = NULL;
296 static uu_avl_t *service_manifest_tree = NULL;
297 
298 static void scfdie_lineno(int lineno) __NORETURN;
299 
300 static char *start_method_names[] = {
301 	"start",
302 	"inetd_start",
303 	NULL
304 };
305 
306 static struct uri_scheme {
307 	const char *scheme;
308 	const char *protocol;
309 } uri_scheme[] = {
310 	{ "mailto", "smtp" },
311 	{ "snmp", "snmp" },
312 	{ "syslog", "syslog" },
313 	{ NULL, NULL }
314 };
315 #define	URI_SCHEME_NUM ((sizeof (uri_scheme) / \
316     sizeof (struct uri_scheme)) - 1)
317 
318 static int
319 check_uri_scheme(const char *scheme)
320 {
321 	int i;
322 
323 	for (i = 0; uri_scheme[i].scheme != NULL; ++i) {
324 		if (strcmp(scheme, uri_scheme[i].scheme) == 0)
325 			return (i);
326 	}
327 
328 	return (-1);
329 }
330 
331 static int
332 check_uri_protocol(const char *p)
333 {
334 	int i;
335 
336 	for (i = 0; uri_scheme[i].protocol != NULL; ++i) {
337 		if (strcmp(p, uri_scheme[i].protocol) == 0)
338 			return (i);
339 	}
340 
341 	return (-1);
342 }
343 
344 /*
345  * For unexpected libscf errors.
346  */
347 #ifdef NDEBUG
348 
349 static void scfdie(void) __NORETURN;
350 
351 static void
352 scfdie(void)
353 {
354 	scf_error_t err = scf_error();
355 
356 	if (err == SCF_ERROR_CONNECTION_BROKEN)
357 		uu_die(gettext("Repository connection broken.  Exiting.\n"));
358 
359 	uu_die(gettext("Unexpected fatal libscf error: %s.  Exiting.\n"),
360 	    scf_strerror(err));
361 }
362 
363 #else
364 
365 #define	scfdie()	scfdie_lineno(__LINE__)
366 
367 static void
368 scfdie_lineno(int lineno)
369 {
370 	scf_error_t err = scf_error();
371 
372 	if (err == SCF_ERROR_CONNECTION_BROKEN)
373 		uu_die(gettext("Repository connection broken.  Exiting.\n"));
374 
375 	uu_die(gettext("Unexpected libscf error on line %d of " __FILE__
376 	    ": %s.\n"), lineno, scf_strerror(err));
377 }
378 
379 #endif
380 
381 static void
382 scfwarn(void)
383 {
384 	warn(gettext("Unexpected libscf error: %s.\n"),
385 	    scf_strerror(scf_error()));
386 }
387 
388 /*
389  * Clear a field of a structure.
390  */
391 static int
392 clear_int(void *a, void *b)
393 {
394 	/* LINTED */
395 	*(int *)((char *)a + (size_t)b) = 0;
396 
397 	return (UU_WALK_NEXT);
398 }
399 
400 static int
401 scferror2errno(scf_error_t err)
402 {
403 	switch (err) {
404 	case SCF_ERROR_BACKEND_ACCESS:
405 		return (EACCES);
406 
407 	case SCF_ERROR_BACKEND_READONLY:
408 		return (EROFS);
409 
410 	case SCF_ERROR_CONNECTION_BROKEN:
411 		return (ECONNABORTED);
412 
413 	case SCF_ERROR_CONSTRAINT_VIOLATED:
414 	case SCF_ERROR_INVALID_ARGUMENT:
415 		return (EINVAL);
416 
417 	case SCF_ERROR_DELETED:
418 		return (ECANCELED);
419 
420 	case SCF_ERROR_EXISTS:
421 		return (EEXIST);
422 
423 	case SCF_ERROR_NO_MEMORY:
424 		return (ENOMEM);
425 
426 	case SCF_ERROR_NO_RESOURCES:
427 		return (ENOSPC);
428 
429 	case SCF_ERROR_NOT_FOUND:
430 		return (ENOENT);
431 
432 	case SCF_ERROR_PERMISSION_DENIED:
433 		return (EPERM);
434 
435 	default:
436 #ifndef NDEBUG
437 		(void) fprintf(stderr, "%s:%d: Unknown libscf error %d.\n",
438 		    __FILE__, __LINE__, err);
439 #else
440 		(void) fprintf(stderr, "Unknown libscf error %d.\n", err);
441 #endif
442 		abort();
443 		/* NOTREACHED */
444 	}
445 }
446 
447 static int
448 entity_get_pg(void *ent, int issvc, const char *name,
449     scf_propertygroup_t *pg)
450 {
451 	if (issvc)
452 		return (scf_service_get_pg(ent, name, pg));
453 	else
454 		return (scf_instance_get_pg(ent, name, pg));
455 }
456 
457 static void
458 entity_destroy(void *ent, int issvc)
459 {
460 	if (issvc)
461 		scf_service_destroy(ent);
462 	else
463 		scf_instance_destroy(ent);
464 }
465 
466 static int
467 get_pg(const char *pg_name, scf_propertygroup_t *pg)
468 {
469 	int ret;
470 
471 	if (cur_level != NULL)
472 		ret = scf_snaplevel_get_pg(cur_level, pg_name, pg);
473 	else if (cur_inst != NULL)
474 		ret = scf_instance_get_pg(cur_inst, pg_name, pg);
475 	else
476 		ret = scf_service_get_pg(cur_svc, pg_name, pg);
477 
478 	return (ret);
479 }
480 
481 /*
482  * Find a snaplevel in a snapshot.  If get_svc is true, find the service
483  * snaplevel.  Otherwise find the instance snaplevel.
484  *
485  * Returns
486  *   0 - success
487  *   ECONNABORTED - repository connection broken
488  *   ECANCELED - instance containing snap was deleted
489  *   ENOENT - snap has no snaplevels
490  *	    - requested snaplevel not found
491  */
492 static int
493 get_snaplevel(scf_snapshot_t *snap, int get_svc, scf_snaplevel_t *snpl)
494 {
495 	if (scf_snapshot_get_base_snaplevel(snap, snpl) != 0) {
496 		switch (scf_error()) {
497 		case SCF_ERROR_CONNECTION_BROKEN:
498 		case SCF_ERROR_DELETED:
499 		case SCF_ERROR_NOT_FOUND:
500 			return (scferror2errno(scf_error()));
501 
502 		case SCF_ERROR_HANDLE_MISMATCH:
503 		case SCF_ERROR_NOT_BOUND:
504 		case SCF_ERROR_NOT_SET:
505 		default:
506 			bad_error("scf_snapshot_get_base_snaplevel",
507 			    scf_error());
508 		}
509 	}
510 
511 	for (;;) {
512 		ssize_t ssz;
513 
514 		ssz = scf_snaplevel_get_instance_name(snpl, NULL, 0);
515 		if (ssz >= 0) {
516 			if (!get_svc)
517 				return (0);
518 		} else {
519 			switch (scf_error()) {
520 			case SCF_ERROR_CONSTRAINT_VIOLATED:
521 				if (get_svc)
522 					return (0);
523 				break;
524 
525 			case SCF_ERROR_DELETED:
526 			case SCF_ERROR_CONNECTION_BROKEN:
527 				return (scferror2errno(scf_error()));
528 
529 			case SCF_ERROR_NOT_SET:
530 			case SCF_ERROR_NOT_BOUND:
531 			default:
532 				bad_error("scf_snaplevel_get_instance_name",
533 				    scf_error());
534 			}
535 		}
536 
537 		if (scf_snaplevel_get_next_snaplevel(snpl, snpl) != 0) {
538 			switch (scf_error()) {
539 			case SCF_ERROR_NOT_FOUND:
540 			case SCF_ERROR_CONNECTION_BROKEN:
541 			case SCF_ERROR_DELETED:
542 				return (scferror2errno(scf_error()));
543 
544 			case SCF_ERROR_HANDLE_MISMATCH:
545 			case SCF_ERROR_NOT_BOUND:
546 			case SCF_ERROR_NOT_SET:
547 			case SCF_ERROR_INVALID_ARGUMENT:
548 			default:
549 				bad_error("scf_snaplevel_get_next_snaplevel",
550 				    scf_error());
551 			}
552 		}
553 	}
554 }
555 
556 /*
557  * If issvc is 0, take ent to be a pointer to an scf_instance_t.  If it has
558  * a running snapshot, and that snapshot has an instance snaplevel, set pg to
559  * the property group named name in it.  If it doesn't have a running
560  * snapshot, set pg to the instance's current property group named name.
561  *
562  * If issvc is nonzero, take ent to be a pointer to an scf_service_t, and walk
563  * its instances.  If one has a running snapshot with a service snaplevel, set
564  * pg to the property group named name in it.  If no such snaplevel could be
565  * found, set pg to the service's current property group named name.
566  *
567  * iter, inst, snap, and snpl are required scratch objects.
568  *
569  * Returns
570  *   0 - success
571  *   ECONNABORTED - repository connection broken
572  *   ECANCELED - ent was deleted
573  *   ENOENT - no such property group
574  *   EINVAL - name is an invalid property group name
575  *   EBADF - found running snapshot is missing a snaplevel
576  */
577 static int
578 entity_get_running_pg(void *ent, int issvc, const char *name,
579     scf_propertygroup_t *pg, scf_iter_t *iter, scf_instance_t *inst,
580     scf_snapshot_t *snap, scf_snaplevel_t *snpl)
581 {
582 	int r;
583 
584 	if (issvc) {
585 		/* Search for an instance with a running snapshot. */
586 		if (scf_iter_service_instances(iter, ent) != 0) {
587 			switch (scf_error()) {
588 			case SCF_ERROR_DELETED:
589 			case SCF_ERROR_CONNECTION_BROKEN:
590 				return (scferror2errno(scf_error()));
591 
592 			case SCF_ERROR_NOT_SET:
593 			case SCF_ERROR_NOT_BOUND:
594 			case SCF_ERROR_HANDLE_MISMATCH:
595 			default:
596 				bad_error("scf_iter_service_instances",
597 				    scf_error());
598 			}
599 		}
600 
601 		for (;;) {
602 			r = scf_iter_next_instance(iter, inst);
603 			if (r == 0) {
604 				if (scf_service_get_pg(ent, name, pg) == 0)
605 					return (0);
606 
607 				switch (scf_error()) {
608 				case SCF_ERROR_DELETED:
609 				case SCF_ERROR_NOT_FOUND:
610 				case SCF_ERROR_INVALID_ARGUMENT:
611 				case SCF_ERROR_CONNECTION_BROKEN:
612 					return (scferror2errno(scf_error()));
613 
614 				case SCF_ERROR_NOT_BOUND:
615 				case SCF_ERROR_HANDLE_MISMATCH:
616 				case SCF_ERROR_NOT_SET:
617 				default:
618 					bad_error("scf_service_get_pg",
619 					    scf_error());
620 				}
621 			}
622 			if (r != 1) {
623 				switch (scf_error()) {
624 				case SCF_ERROR_DELETED:
625 				case SCF_ERROR_CONNECTION_BROKEN:
626 					return (scferror2errno(scf_error()));
627 
628 				case SCF_ERROR_INVALID_ARGUMENT:
629 				case SCF_ERROR_NOT_SET:
630 				case SCF_ERROR_NOT_BOUND:
631 				case SCF_ERROR_HANDLE_MISMATCH:
632 				default:
633 					bad_error("scf_iter_next_instance",
634 					    scf_error());
635 				}
636 			}
637 
638 			if (scf_instance_get_snapshot(inst, snap_running,
639 			    snap) == 0)
640 				break;
641 
642 			switch (scf_error()) {
643 			case SCF_ERROR_NOT_FOUND:
644 			case SCF_ERROR_DELETED:
645 				continue;
646 
647 			case SCF_ERROR_CONNECTION_BROKEN:
648 				return (ECONNABORTED);
649 
650 			case SCF_ERROR_HANDLE_MISMATCH:
651 			case SCF_ERROR_INVALID_ARGUMENT:
652 			case SCF_ERROR_NOT_SET:
653 			case SCF_ERROR_NOT_BOUND:
654 			default:
655 				bad_error("scf_instance_get_snapshot",
656 				    scf_error());
657 			}
658 		}
659 	} else {
660 		if (scf_instance_get_snapshot(ent, snap_running, snap) != 0) {
661 			switch (scf_error()) {
662 			case SCF_ERROR_NOT_FOUND:
663 				break;
664 
665 			case SCF_ERROR_DELETED:
666 			case SCF_ERROR_CONNECTION_BROKEN:
667 				return (scferror2errno(scf_error()));
668 
669 			case SCF_ERROR_NOT_BOUND:
670 			case SCF_ERROR_HANDLE_MISMATCH:
671 			case SCF_ERROR_INVALID_ARGUMENT:
672 			case SCF_ERROR_NOT_SET:
673 			default:
674 				bad_error("scf_instance_get_snapshot",
675 				    scf_error());
676 			}
677 
678 			if (scf_instance_get_pg(ent, name, pg) == 0)
679 				return (0);
680 
681 			switch (scf_error()) {
682 			case SCF_ERROR_DELETED:
683 			case SCF_ERROR_NOT_FOUND:
684 			case SCF_ERROR_INVALID_ARGUMENT:
685 			case SCF_ERROR_CONNECTION_BROKEN:
686 				return (scferror2errno(scf_error()));
687 
688 			case SCF_ERROR_NOT_BOUND:
689 			case SCF_ERROR_HANDLE_MISMATCH:
690 			case SCF_ERROR_NOT_SET:
691 			default:
692 				bad_error("scf_instance_get_pg", scf_error());
693 			}
694 		}
695 	}
696 
697 	r = get_snaplevel(snap, issvc, snpl);
698 	switch (r) {
699 	case 0:
700 		break;
701 
702 	case ECONNABORTED:
703 	case ECANCELED:
704 		return (r);
705 
706 	case ENOENT:
707 		return (EBADF);
708 
709 	default:
710 		bad_error("get_snaplevel", r);
711 	}
712 
713 	if (scf_snaplevel_get_pg(snpl, name, pg) == 0)
714 		return (0);
715 
716 	switch (scf_error()) {
717 	case SCF_ERROR_DELETED:
718 	case SCF_ERROR_INVALID_ARGUMENT:
719 	case SCF_ERROR_CONNECTION_BROKEN:
720 	case SCF_ERROR_NOT_FOUND:
721 		return (scferror2errno(scf_error()));
722 
723 	case SCF_ERROR_NOT_BOUND:
724 	case SCF_ERROR_HANDLE_MISMATCH:
725 	case SCF_ERROR_NOT_SET:
726 	default:
727 		bad_error("scf_snaplevel_get_pg", scf_error());
728 		/* NOTREACHED */
729 	}
730 }
731 
732 /*
733  * To be registered with atexit().
734  */
735 static void
736 remove_tempfile(void)
737 {
738 	int ret;
739 
740 	if (tempfile != NULL) {
741 		if (fclose(tempfile) == EOF)
742 			(void) warn(gettext("Could not close temporary file"));
743 		tempfile = NULL;
744 	}
745 
746 	if (tempfilename[0] != '\0') {
747 		do {
748 			ret = remove(tempfilename);
749 		} while (ret == -1 && errno == EINTR);
750 		if (ret == -1)
751 			warn(gettext("Could not remove temporary file"));
752 		tempfilename[0] = '\0';
753 	}
754 }
755 
756 /*
757  * Launch private svc.configd(1M) for manipulating alternate repositories.
758  */
759 static void
760 start_private_repository(engine_state_t *est)
761 {
762 	int fd, stat;
763 	struct door_info info;
764 	pid_t pid;
765 
766 	/*
767 	 * 1.  Create a temporary file for the door.
768 	 */
769 	if (est->sc_repo_doorname != NULL)
770 		free((void *)est->sc_repo_doorname);
771 
772 	est->sc_repo_doorname = tempnam(est->sc_repo_doordir, "scfdr");
773 	if (est->sc_repo_doorname == NULL)
774 		uu_die(gettext("Could not acquire temporary filename"));
775 
776 	fd = open(est->sc_repo_doorname, O_CREAT | O_EXCL | O_RDWR, 0600);
777 	if (fd < 0)
778 		uu_die(gettext("Could not create temporary file for "
779 		    "repository server"));
780 
781 	(void) close(fd);
782 
783 	/*
784 	 * 2.  Launch a configd with that door, using the specified
785 	 * repository.
786 	 */
787 	if ((est->sc_repo_pid = fork()) == 0) {
788 		(void) execlp(est->sc_repo_server, est->sc_repo_server, "-p",
789 		    "-d", est->sc_repo_doorname, "-r", est->sc_repo_filename,
790 		    NULL);
791 		uu_die(gettext("Could not execute %s"), est->sc_repo_server);
792 	} else if (est->sc_repo_pid == -1)
793 		uu_die(gettext("Attempt to fork failed"));
794 
795 	do {
796 		pid = waitpid(est->sc_repo_pid, &stat, 0);
797 	} while (pid == -1 && errno == EINTR);
798 
799 	if (pid == -1)
800 		uu_die(gettext("Could not waitpid() for repository server"));
801 
802 	if (!WIFEXITED(stat)) {
803 		uu_die(gettext("Repository server failed (status %d).\n"),
804 		    stat);
805 	} else if (WEXITSTATUS(stat) != 0) {
806 		uu_die(gettext("Repository server failed (exit %d).\n"),
807 		    WEXITSTATUS(stat));
808 	}
809 
810 	/*
811 	 * See if it was successful by checking if the door is a door.
812 	 */
813 
814 	fd = open(est->sc_repo_doorname, O_RDWR);
815 	if (fd < 0)
816 		uu_die(gettext("Could not open door \"%s\""),
817 		    est->sc_repo_doorname);
818 
819 	if (door_info(fd, &info) < 0)
820 		uu_die(gettext("Unexpected door_info() error"));
821 
822 	if (close(fd) == -1)
823 		warn(gettext("Could not close repository door"),
824 		    strerror(errno));
825 
826 	est->sc_repo_pid = info.di_target;
827 }
828 
829 void
830 lscf_cleanup(void)
831 {
832 	/*
833 	 * In the case where we've launched a private svc.configd(1M)
834 	 * instance, we must terminate our child and remove the temporary
835 	 * rendezvous point.
836 	 */
837 	if (est->sc_repo_pid > 0) {
838 		(void) kill(est->sc_repo_pid, SIGTERM);
839 		(void) waitpid(est->sc_repo_pid, NULL, 0);
840 		(void) unlink(est->sc_repo_doorname);
841 
842 		est->sc_repo_pid = 0;
843 	}
844 }
845 
846 void
847 unselect_cursnap(void)
848 {
849 	void *cookie;
850 
851 	cur_level = NULL;
852 
853 	cookie = NULL;
854 	while ((cur_elt = uu_list_teardown(cur_levels, &cookie)) != NULL) {
855 		scf_snaplevel_destroy(cur_elt->sl);
856 		free(cur_elt);
857 	}
858 
859 	scf_snapshot_destroy(cur_snap);
860 	cur_snap = NULL;
861 }
862 
863 void
864 lscf_prep_hndl(void)
865 {
866 	if (g_hndl != NULL)
867 		return;
868 
869 	g_hndl = scf_handle_create(SCF_VERSION);
870 	if (g_hndl == NULL)
871 		scfdie();
872 
873 	if (est->sc_repo_filename != NULL)
874 		start_private_repository(est);
875 
876 	if (est->sc_repo_doorname != NULL) {
877 		scf_value_t *repo_value;
878 		int ret;
879 
880 		repo_value = scf_value_create(g_hndl);
881 		if (repo_value == NULL)
882 			scfdie();
883 
884 		ret = scf_value_set_astring(repo_value, est->sc_repo_doorname);
885 		assert(ret == SCF_SUCCESS);
886 
887 		if (scf_handle_decorate(g_hndl, "door_path", repo_value) !=
888 		    SCF_SUCCESS)
889 			scfdie();
890 
891 		scf_value_destroy(repo_value);
892 	}
893 
894 	if (scf_handle_bind(g_hndl) != 0)
895 		uu_die(gettext("Could not connect to repository server: %s.\n"),
896 		    scf_strerror(scf_error()));
897 
898 	cur_scope = scf_scope_create(g_hndl);
899 	if (cur_scope == NULL)
900 		scfdie();
901 
902 	if (scf_handle_get_local_scope(g_hndl, cur_scope) != 0)
903 		scfdie();
904 }
905 
906 static void
907 repository_teardown(void)
908 {
909 	if (g_hndl != NULL) {
910 		if (cur_snap != NULL)
911 			unselect_cursnap();
912 		scf_instance_destroy(cur_inst);
913 		scf_service_destroy(cur_svc);
914 		scf_scope_destroy(cur_scope);
915 		scf_handle_destroy(g_hndl);
916 		cur_inst = NULL;
917 		cur_svc = NULL;
918 		cur_scope = NULL;
919 		g_hndl = NULL;
920 		lscf_cleanup();
921 	}
922 }
923 
924 void
925 lscf_set_repository(const char *repfile, int force)
926 {
927 	repository_teardown();
928 
929 	if (est->sc_repo_filename != NULL) {
930 		free((void *)est->sc_repo_filename);
931 		est->sc_repo_filename = NULL;
932 	}
933 
934 	if ((force == 0) && (access(repfile, R_OK) != 0)) {
935 		/*
936 		 * Repository file does not exist
937 		 * or has no read permission.
938 		 */
939 		warn(gettext("Cannot access \"%s\": %s\n"),
940 		    repfile, strerror(errno));
941 	} else {
942 		est->sc_repo_filename = safe_strdup(repfile);
943 	}
944 
945 	lscf_prep_hndl();
946 }
947 
948 void
949 lscf_init()
950 {
951 	if ((max_scf_fmri_len = scf_limit(SCF_LIMIT_MAX_FMRI_LENGTH)) < 0 ||
952 	    (max_scf_name_len = scf_limit(SCF_LIMIT_MAX_NAME_LENGTH)) < 0 ||
953 	    (max_scf_pg_type_len = scf_limit(SCF_LIMIT_MAX_PG_TYPE_LENGTH)) <
954 	    0 ||
955 	    (max_scf_value_len = scf_limit(SCF_LIMIT_MAX_VALUE_LENGTH)) < 0)
956 		scfdie();
957 
958 	max_scf_len = max_scf_fmri_len;
959 	if (max_scf_name_len > max_scf_len)
960 		max_scf_len = max_scf_name_len;
961 	if (max_scf_pg_type_len > max_scf_len)
962 		max_scf_len = max_scf_pg_type_len;
963 	/*
964 	 * When a value of type opaque is represented as a string, the
965 	 * string contains 2 characters for every byte of data.  That is
966 	 * because the string contains the hex representation of the opaque
967 	 * value.
968 	 */
969 	if (2 * max_scf_value_len > max_scf_len)
970 		max_scf_len = 2 * max_scf_value_len;
971 
972 	if (atexit(remove_tempfile) != 0)
973 		uu_die(gettext("Could not register atexit() function"));
974 
975 	emsg_entity_not_selected = gettext("An entity is not selected.\n");
976 	emsg_permission_denied = gettext("Permission denied.\n");
977 	emsg_create_xml = gettext("Could not create XML node.\n");
978 	emsg_cant_modify_snapshots = gettext("Cannot modify snapshots.\n");
979 	emsg_invalid_for_snapshot =
980 	    gettext("Invalid operation on a snapshot.\n");
981 	emsg_read_only = gettext("Backend read-only.\n");
982 	emsg_deleted = gettext("Current selection has been deleted.\n");
983 	emsg_invalid_pg_name =
984 	    gettext("Invalid property group name \"%s\".\n");
985 	emsg_invalid_prop_name = gettext("Invalid property name \"%s\".\n");
986 	emsg_no_such_pg = gettext("No such property group \"%s\".\n");
987 	emsg_fmri_invalid_pg_name = gettext("Service %s has property group "
988 	    "with invalid name \"%s\".\n");
989 	emsg_fmri_invalid_pg_name_type = gettext("Service %s has property "
990 	    "group with invalid name \"%s\" or type \"%s\".\n");
991 	emsg_pg_added = gettext("%s changed unexpectedly "
992 	    "(property group \"%s\" added).\n");
993 	emsg_pg_changed = gettext("%s changed unexpectedly "
994 	    "(property group \"%s\" changed).\n");
995 	emsg_pg_deleted = gettext("%s changed unexpectedly "
996 	    "(property group \"%s\" or an ancestor was deleted).\n");
997 	emsg_pg_mod_perm = gettext("Could not modify property group \"%s\" "
998 	    "in %s (permission denied).\n");
999 	emsg_pg_add_perm = gettext("Could not create property group \"%s\" "
1000 	    "in %s (permission denied).\n");
1001 	emsg_pg_del_perm = gettext("Could not delete property group \"%s\" "
1002 	    "in %s (permission denied).\n");
1003 	emsg_snap_perm = gettext("Could not take \"%s\" snapshot of %s "
1004 	    "(permission denied).\n");
1005 	emsg_dpt_dangling = gettext("Conflict upgrading %s (not importing "
1006 	    "new dependent \"%s\" because it already exists).  Warning: The "
1007 	    "current dependent's target (%s) does not exist.\n");
1008 	emsg_dpt_no_dep = gettext("Conflict upgrading %s (not importing new "
1009 	    "dependent \"%s\" because it already exists).  Warning: The "
1010 	    "current dependent's target (%s) does not have a dependency named "
1011 	    "\"%s\" as expected.\n");
1012 
1013 	string_pool = uu_list_pool_create("strings", sizeof (string_list_t),
1014 	    offsetof(string_list_t, node), NULL, 0);
1015 	snaplevel_pool = uu_list_pool_create("snaplevels",
1016 	    sizeof (struct snaplevel), offsetof(struct snaplevel, list_node),
1017 	    NULL, 0);
1018 }
1019 
1020 
1021 static const char *
1022 prop_to_typestr(const scf_property_t *prop)
1023 {
1024 	scf_type_t ty;
1025 
1026 	if (scf_property_type(prop, &ty) != SCF_SUCCESS)
1027 		scfdie();
1028 
1029 	return (scf_type_to_string(ty));
1030 }
1031 
1032 static scf_type_t
1033 string_to_type(const char *type)
1034 {
1035 	size_t len = strlen(type);
1036 	char *buf;
1037 
1038 	if (len == 0 || type[len - 1] != ':')
1039 		return (SCF_TYPE_INVALID);
1040 
1041 	buf = (char *)alloca(len + 1);
1042 	(void) strlcpy(buf, type, len + 1);
1043 	buf[len - 1] = 0;
1044 
1045 	return (scf_string_to_type(buf));
1046 }
1047 
1048 static scf_value_t *
1049 string_to_value(const char *str, scf_type_t ty, boolean_t require_quotes)
1050 {
1051 	scf_value_t *v;
1052 	char *dup, *nstr;
1053 	size_t len;
1054 
1055 	v = scf_value_create(g_hndl);
1056 	if (v == NULL)
1057 		scfdie();
1058 
1059 	len = strlen(str);
1060 	if (require_quotes &&
1061 	    (len < 2 || str[0] != '\"' || str[len - 1] != '\"')) {
1062 		semerr(gettext("Multiple string values or string values "
1063 		    "with spaces must be quoted with '\"'.\n"));
1064 		scf_value_destroy(v);
1065 		return (NULL);
1066 	}
1067 
1068 	nstr = dup = safe_strdup(str);
1069 	if (dup[0] == '\"') {
1070 		/*
1071 		 * Strip out the first and the last quote.
1072 		 */
1073 		dup[len - 1] = '\0';
1074 		nstr = dup + 1;
1075 	}
1076 
1077 	if (scf_value_set_from_string(v, ty, (const char *)nstr) != 0) {
1078 		assert(scf_error() == SCF_ERROR_INVALID_ARGUMENT);
1079 		semerr(gettext("Invalid \"%s\" value \"%s\".\n"),
1080 		    scf_type_to_string(ty), nstr);
1081 		scf_value_destroy(v);
1082 		v = NULL;
1083 	}
1084 	free(dup);
1085 	return (v);
1086 }
1087 
1088 /*
1089  * Print str to strm, quoting double-quotes and backslashes with backslashes.
1090  * Optionally append a comment prefix ('#') to newlines ('\n').
1091  */
1092 static int
1093 quote_and_print(const char *str, FILE *strm, int commentnl)
1094 {
1095 	const char *cp;
1096 
1097 	for (cp = str; *cp != '\0'; ++cp) {
1098 		if (*cp == '"' || *cp == '\\')
1099 			(void) putc('\\', strm);
1100 
1101 		(void) putc(*cp, strm);
1102 
1103 		if (commentnl && *cp == '\n') {
1104 			(void) putc('#', strm);
1105 		}
1106 	}
1107 
1108 	return (ferror(strm));
1109 }
1110 
1111 /*
1112  * These wrappers around lowlevel functions provide consistent error checking
1113  * and warnings.
1114  */
1115 static int
1116 pg_get_prop(scf_propertygroup_t *pg, const char *propname, scf_property_t *prop)
1117 {
1118 	if (scf_pg_get_property(pg, propname, prop) == SCF_SUCCESS)
1119 		return (0);
1120 
1121 	if (scf_error() != SCF_ERROR_NOT_FOUND)
1122 		scfdie();
1123 
1124 	if (g_verbose) {
1125 		ssize_t len;
1126 		char *fmri;
1127 
1128 		len = scf_pg_to_fmri(pg, NULL, 0);
1129 		if (len < 0)
1130 			scfdie();
1131 
1132 		fmri = safe_malloc(len + 1);
1133 
1134 		if (scf_pg_to_fmri(pg, fmri, len + 1) < 0)
1135 			scfdie();
1136 
1137 		warn(gettext("Expected property %s of property group %s is "
1138 		    "missing.\n"), propname, fmri);
1139 
1140 		free(fmri);
1141 	}
1142 
1143 	return (-1);
1144 }
1145 
1146 static int
1147 prop_check_type(scf_property_t *prop, scf_type_t ty)
1148 {
1149 	scf_type_t pty;
1150 
1151 	if (scf_property_type(prop, &pty) != SCF_SUCCESS)
1152 		scfdie();
1153 
1154 	if (ty == pty)
1155 		return (0);
1156 
1157 	if (g_verbose) {
1158 		ssize_t len;
1159 		char *fmri;
1160 		const char *tystr;
1161 
1162 		len = scf_property_to_fmri(prop, NULL, 0);
1163 		if (len < 0)
1164 			scfdie();
1165 
1166 		fmri = safe_malloc(len + 1);
1167 
1168 		if (scf_property_to_fmri(prop, fmri, len + 1) < 0)
1169 			scfdie();
1170 
1171 		tystr = scf_type_to_string(ty);
1172 		if (tystr == NULL)
1173 			tystr = "?";
1174 
1175 		warn(gettext("Property %s is not of expected type %s.\n"),
1176 		    fmri, tystr);
1177 
1178 		free(fmri);
1179 	}
1180 
1181 	return (-1);
1182 }
1183 
1184 static int
1185 prop_get_val(scf_property_t *prop, scf_value_t *val)
1186 {
1187 	scf_error_t err;
1188 
1189 	if (scf_property_get_value(prop, val) == SCF_SUCCESS)
1190 		return (0);
1191 
1192 	err = scf_error();
1193 
1194 	if (err != SCF_ERROR_NOT_FOUND &&
1195 	    err != SCF_ERROR_CONSTRAINT_VIOLATED &&
1196 	    err != SCF_ERROR_PERMISSION_DENIED)
1197 		scfdie();
1198 
1199 	if (g_verbose) {
1200 		ssize_t len;
1201 		char *fmri, *emsg;
1202 
1203 		len = scf_property_to_fmri(prop, NULL, 0);
1204 		if (len < 0)
1205 			scfdie();
1206 
1207 		fmri = safe_malloc(len + 1);
1208 
1209 		if (scf_property_to_fmri(prop, fmri, len + 1) < 0)
1210 			scfdie();
1211 
1212 		if (err == SCF_ERROR_NOT_FOUND)
1213 			emsg = gettext("Property %s has no values; expected "
1214 			    "one.\n");
1215 		else if (err == SCF_ERROR_CONSTRAINT_VIOLATED)
1216 			emsg = gettext("Property %s has multiple values; "
1217 			    "expected one.\n");
1218 		else
1219 			emsg = gettext("No permission to read property %s.\n");
1220 
1221 		warn(emsg, fmri);
1222 
1223 		free(fmri);
1224 	}
1225 
1226 	return (-1);
1227 }
1228 
1229 
1230 static boolean_t
1231 snaplevel_is_instance(const scf_snaplevel_t *level)
1232 {
1233 	if (scf_snaplevel_get_instance_name(level, NULL, 0) < 0) {
1234 		if (scf_error() != SCF_ERROR_CONSTRAINT_VIOLATED)
1235 			scfdie();
1236 		return (0);
1237 	} else {
1238 		return (1);
1239 	}
1240 }
1241 
1242 /*
1243  * Decode FMRI into a service or instance, and put the result in *ep.  If
1244  * memory cannot be allocated, return SCF_ERROR_NO_MEMORY.  If the FMRI is
1245  * invalid, return SCF_ERROR_INVALID_ARGUMENT.  If the FMRI does not specify
1246  * an entity, return SCF_ERROR_CONSTRAINT_VIOLATED.  If the entity cannot be
1247  * found, return SCF_ERROR_NOT_FOUND.  Otherwise return SCF_ERROR_NONE, point
1248  * *ep to a valid scf_service_t or scf_instance_t, and set *isservice to
1249  * whether *ep is a service.
1250  */
1251 static scf_error_t
1252 fmri_to_entity(scf_handle_t *h, const char *fmri, void **ep, int *isservice)
1253 {
1254 	char *fmri_copy;
1255 	const char *sstr, *istr, *pgstr;
1256 	scf_service_t *svc;
1257 	scf_instance_t *inst;
1258 
1259 	fmri_copy = strdup(fmri);
1260 	if (fmri_copy == NULL)
1261 		return (SCF_ERROR_NO_MEMORY);
1262 
1263 	if (scf_parse_svc_fmri(fmri_copy, NULL, &sstr, &istr, &pgstr, NULL) !=
1264 	    SCF_SUCCESS) {
1265 		free(fmri_copy);
1266 		return (SCF_ERROR_INVALID_ARGUMENT);
1267 	}
1268 
1269 	free(fmri_copy);
1270 
1271 	if (sstr == NULL || pgstr != NULL)
1272 		return (SCF_ERROR_CONSTRAINT_VIOLATED);
1273 
1274 	if (istr == NULL) {
1275 		svc = scf_service_create(h);
1276 		if (svc == NULL)
1277 			return (SCF_ERROR_NO_MEMORY);
1278 
1279 		if (scf_handle_decode_fmri(h, fmri, NULL, svc, NULL, NULL, NULL,
1280 		    SCF_DECODE_FMRI_EXACT) != SCF_SUCCESS) {
1281 			if (scf_error() != SCF_ERROR_NOT_FOUND)
1282 				scfdie();
1283 
1284 			return (SCF_ERROR_NOT_FOUND);
1285 		}
1286 
1287 		*ep = svc;
1288 		*isservice = 1;
1289 	} else {
1290 		inst = scf_instance_create(h);
1291 		if (inst == NULL)
1292 			return (SCF_ERROR_NO_MEMORY);
1293 
1294 		if (scf_handle_decode_fmri(h, fmri, NULL, NULL, inst, NULL,
1295 		    NULL, SCF_DECODE_FMRI_EXACT) != SCF_SUCCESS) {
1296 			if (scf_error() != SCF_ERROR_NOT_FOUND)
1297 				scfdie();
1298 
1299 			return (SCF_ERROR_NOT_FOUND);
1300 		}
1301 
1302 		*ep = inst;
1303 		*isservice = 0;
1304 	}
1305 
1306 	return (SCF_ERROR_NONE);
1307 }
1308 
1309 /*
1310  * Create the entity named by fmri.  Place a pointer to its libscf handle in
1311  * *ep, and set or clear *isservicep if it is a service or an instance.
1312  * Returns
1313  *   SCF_ERROR_NONE - success
1314  *   SCF_ERROR_NO_MEMORY - scf_*_create() failed
1315  *   SCF_ERROR_INVALID_ARGUMENT - fmri is invalid
1316  *   SCF_ERROR_CONSTRAINT_VIOLATED - fmri is not a service or instance
1317  *   SCF_ERROR_NOT_FOUND - no such scope
1318  *   SCF_ERROR_PERMISSION_DENIED
1319  *   SCF_ERROR_BACKEND_READONLY
1320  *   SCF_ERROR_BACKEND_ACCESS
1321  */
1322 static scf_error_t
1323 create_entity(scf_handle_t *h, const char *fmri, void **ep, int *isservicep)
1324 {
1325 	char *fmri_copy;
1326 	const char *scstr, *sstr, *istr, *pgstr;
1327 	scf_scope_t *scope = NULL;
1328 	scf_service_t *svc = NULL;
1329 	scf_instance_t *inst = NULL;
1330 	scf_error_t scfe;
1331 
1332 	fmri_copy = safe_strdup(fmri);
1333 
1334 	if (scf_parse_svc_fmri(fmri_copy, &scstr, &sstr, &istr, &pgstr, NULL) !=
1335 	    0) {
1336 		free(fmri_copy);
1337 		return (SCF_ERROR_INVALID_ARGUMENT);
1338 	}
1339 
1340 	if (scstr == NULL || sstr == NULL || pgstr != NULL) {
1341 		free(fmri_copy);
1342 		return (SCF_ERROR_CONSTRAINT_VIOLATED);
1343 	}
1344 
1345 	*ep = NULL;
1346 
1347 	if ((scope = scf_scope_create(h)) == NULL ||
1348 	    (svc = scf_service_create(h)) == NULL ||
1349 	    (inst = scf_instance_create(h)) == NULL) {
1350 		scfe = SCF_ERROR_NO_MEMORY;
1351 		goto out;
1352 	}
1353 
1354 get_scope:
1355 	if (scf_handle_get_scope(h, scstr, scope) != 0) {
1356 		switch (scf_error()) {
1357 		case SCF_ERROR_CONNECTION_BROKEN:
1358 			scfdie();
1359 			/* NOTREACHED */
1360 
1361 		case SCF_ERROR_NOT_FOUND:
1362 			scfe = SCF_ERROR_NOT_FOUND;
1363 			goto out;
1364 
1365 		case SCF_ERROR_HANDLE_MISMATCH:
1366 		case SCF_ERROR_NOT_BOUND:
1367 		case SCF_ERROR_INVALID_ARGUMENT:
1368 		default:
1369 			bad_error("scf_handle_get_scope", scf_error());
1370 		}
1371 	}
1372 
1373 get_svc:
1374 	if (scf_scope_get_service(scope, sstr, svc) != 0) {
1375 		switch (scf_error()) {
1376 		case SCF_ERROR_CONNECTION_BROKEN:
1377 			scfdie();
1378 			/* NOTREACHED */
1379 
1380 		case SCF_ERROR_DELETED:
1381 			goto get_scope;
1382 
1383 		case SCF_ERROR_NOT_FOUND:
1384 			break;
1385 
1386 		case SCF_ERROR_HANDLE_MISMATCH:
1387 		case SCF_ERROR_INVALID_ARGUMENT:
1388 		case SCF_ERROR_NOT_BOUND:
1389 		case SCF_ERROR_NOT_SET:
1390 		default:
1391 			bad_error("scf_scope_get_service", scf_error());
1392 		}
1393 
1394 		if (scf_scope_add_service(scope, sstr, svc) != 0) {
1395 			switch (scf_error()) {
1396 			case SCF_ERROR_CONNECTION_BROKEN:
1397 				scfdie();
1398 				/* NOTREACHED */
1399 
1400 			case SCF_ERROR_DELETED:
1401 				goto get_scope;
1402 
1403 			case SCF_ERROR_PERMISSION_DENIED:
1404 			case SCF_ERROR_BACKEND_READONLY:
1405 			case SCF_ERROR_BACKEND_ACCESS:
1406 				scfe = scf_error();
1407 				goto out;
1408 
1409 			case SCF_ERROR_HANDLE_MISMATCH:
1410 			case SCF_ERROR_INVALID_ARGUMENT:
1411 			case SCF_ERROR_NOT_BOUND:
1412 			case SCF_ERROR_NOT_SET:
1413 			default:
1414 				bad_error("scf_scope_get_service", scf_error());
1415 			}
1416 		}
1417 	}
1418 
1419 	if (istr == NULL) {
1420 		scfe = SCF_ERROR_NONE;
1421 		*ep = svc;
1422 		*isservicep = 1;
1423 		goto out;
1424 	}
1425 
1426 get_inst:
1427 	if (scf_service_get_instance(svc, istr, inst) != 0) {
1428 		switch (scf_error()) {
1429 		case SCF_ERROR_CONNECTION_BROKEN:
1430 			scfdie();
1431 			/* NOTREACHED */
1432 
1433 		case SCF_ERROR_DELETED:
1434 			goto get_svc;
1435 
1436 		case SCF_ERROR_NOT_FOUND:
1437 			break;
1438 
1439 		case SCF_ERROR_HANDLE_MISMATCH:
1440 		case SCF_ERROR_INVALID_ARGUMENT:
1441 		case SCF_ERROR_NOT_BOUND:
1442 		case SCF_ERROR_NOT_SET:
1443 		default:
1444 			bad_error("scf_service_get_instance", scf_error());
1445 		}
1446 
1447 		if (scf_service_add_instance(svc, istr, inst) != 0) {
1448 			switch (scf_error()) {
1449 			case SCF_ERROR_CONNECTION_BROKEN:
1450 				scfdie();
1451 				/* NOTREACHED */
1452 
1453 			case SCF_ERROR_DELETED:
1454 				goto get_svc;
1455 
1456 			case SCF_ERROR_PERMISSION_DENIED:
1457 			case SCF_ERROR_BACKEND_READONLY:
1458 			case SCF_ERROR_BACKEND_ACCESS:
1459 				scfe = scf_error();
1460 				goto out;
1461 
1462 			case SCF_ERROR_HANDLE_MISMATCH:
1463 			case SCF_ERROR_INVALID_ARGUMENT:
1464 			case SCF_ERROR_NOT_BOUND:
1465 			case SCF_ERROR_NOT_SET:
1466 			default:
1467 				bad_error("scf_service_add_instance",
1468 				    scf_error());
1469 			}
1470 		}
1471 	}
1472 
1473 	scfe = SCF_ERROR_NONE;
1474 	*ep = inst;
1475 	*isservicep = 0;
1476 
1477 out:
1478 	if (*ep != inst)
1479 		scf_instance_destroy(inst);
1480 	if (*ep != svc)
1481 		scf_service_destroy(svc);
1482 	scf_scope_destroy(scope);
1483 	free(fmri_copy);
1484 	return (scfe);
1485 }
1486 
1487 /*
1488  * Create or update a snapshot of inst.  snap is a required scratch object.
1489  *
1490  * Returns
1491  *   0 - success
1492  *   ECONNABORTED - repository connection broken
1493  *   EPERM - permission denied
1494  *   ENOSPC - configd is out of resources
1495  *   ECANCELED - inst was deleted
1496  *   -1 - unknown libscf error (message printed)
1497  */
1498 static int
1499 take_snap(scf_instance_t *inst, const char *name, scf_snapshot_t *snap)
1500 {
1501 again:
1502 	if (scf_instance_get_snapshot(inst, name, snap) == 0) {
1503 		if (_scf_snapshot_take_attach(inst, snap) != 0) {
1504 			switch (scf_error()) {
1505 			case SCF_ERROR_CONNECTION_BROKEN:
1506 			case SCF_ERROR_PERMISSION_DENIED:
1507 			case SCF_ERROR_NO_RESOURCES:
1508 				return (scferror2errno(scf_error()));
1509 
1510 			case SCF_ERROR_NOT_SET:
1511 			case SCF_ERROR_INVALID_ARGUMENT:
1512 			default:
1513 				bad_error("_scf_snapshot_take_attach",
1514 				    scf_error());
1515 			}
1516 		}
1517 	} else {
1518 		switch (scf_error()) {
1519 		case SCF_ERROR_NOT_FOUND:
1520 			break;
1521 
1522 		case SCF_ERROR_DELETED:
1523 		case SCF_ERROR_CONNECTION_BROKEN:
1524 			return (scferror2errno(scf_error()));
1525 
1526 		case SCF_ERROR_HANDLE_MISMATCH:
1527 		case SCF_ERROR_NOT_BOUND:
1528 		case SCF_ERROR_INVALID_ARGUMENT:
1529 		case SCF_ERROR_NOT_SET:
1530 		default:
1531 			bad_error("scf_instance_get_snapshot", scf_error());
1532 		}
1533 
1534 		if (_scf_snapshot_take_new(inst, name, snap) != 0) {
1535 			switch (scf_error()) {
1536 			case SCF_ERROR_EXISTS:
1537 				goto again;
1538 
1539 			case SCF_ERROR_CONNECTION_BROKEN:
1540 			case SCF_ERROR_NO_RESOURCES:
1541 			case SCF_ERROR_PERMISSION_DENIED:
1542 				return (scferror2errno(scf_error()));
1543 
1544 			default:
1545 				scfwarn();
1546 				return (-1);
1547 
1548 			case SCF_ERROR_NOT_SET:
1549 			case SCF_ERROR_INTERNAL:
1550 			case SCF_ERROR_INVALID_ARGUMENT:
1551 			case SCF_ERROR_HANDLE_MISMATCH:
1552 				bad_error("_scf_snapshot_take_new",
1553 				    scf_error());
1554 			}
1555 		}
1556 	}
1557 
1558 	return (0);
1559 }
1560 
1561 static int
1562 refresh_running_snapshot(void *entity)
1563 {
1564 	scf_snapshot_t *snap;
1565 	int r;
1566 
1567 	if ((snap = scf_snapshot_create(g_hndl)) == NULL)
1568 		scfdie();
1569 	r = take_snap(entity, snap_running, snap);
1570 	scf_snapshot_destroy(snap);
1571 
1572 	return (r);
1573 }
1574 
1575 /*
1576  * Refresh entity.  If isservice is zero, take entity to be an scf_instance_t *.
1577  * Otherwise take entity to be an scf_service_t * and refresh all of its child
1578  * instances.  fmri is used for messages.  inst, iter, and name_buf are used
1579  * for scratch space.  Returns
1580  *   0 - success
1581  *   ECONNABORTED - repository connection broken
1582  *   ECANCELED - entity was deleted
1583  *   EACCES - backend denied access
1584  *   EPERM - permission denied
1585  *   ENOSPC - repository server out of resources
1586  *   -1 - _smf_refresh_instance_i() failed.  scf_error() should be set.
1587  */
1588 static int
1589 refresh_entity(int isservice, void *entity, const char *fmri,
1590     scf_instance_t *inst, scf_iter_t *iter, char *name_buf)
1591 {
1592 	scf_error_t scfe;
1593 	int r;
1594 
1595 	if (!isservice) {
1596 		/*
1597 		 * Let restarter handles refreshing and making new running
1598 		 * snapshot only if operating on a live repository and not
1599 		 * running in early import.
1600 		 */
1601 		if (est->sc_repo_filename == NULL &&
1602 		    est->sc_repo_doorname == NULL &&
1603 		    est->sc_in_emi == 0) {
1604 			if (_smf_refresh_instance_i(entity) == 0) {
1605 				if (g_verbose)
1606 					warn(gettext("Refreshed %s.\n"), fmri);
1607 				return (0);
1608 			}
1609 
1610 			switch (scf_error()) {
1611 			case SCF_ERROR_BACKEND_ACCESS:
1612 				return (EACCES);
1613 
1614 			case SCF_ERROR_PERMISSION_DENIED:
1615 				return (EPERM);
1616 
1617 			default:
1618 				return (-1);
1619 			}
1620 		} else {
1621 			r = refresh_running_snapshot(entity);
1622 			switch (r) {
1623 			case 0:
1624 				break;
1625 
1626 			case ECONNABORTED:
1627 			case ECANCELED:
1628 			case EPERM:
1629 			case ENOSPC:
1630 				break;
1631 
1632 			default:
1633 				bad_error("refresh_running_snapshot",
1634 				    scf_error());
1635 			}
1636 
1637 			return (r);
1638 		}
1639 	}
1640 
1641 	if (scf_iter_service_instances(iter, entity) != 0) {
1642 		switch (scf_error()) {
1643 		case SCF_ERROR_CONNECTION_BROKEN:
1644 			return (ECONNABORTED);
1645 
1646 		case SCF_ERROR_DELETED:
1647 			return (ECANCELED);
1648 
1649 		case SCF_ERROR_HANDLE_MISMATCH:
1650 		case SCF_ERROR_NOT_BOUND:
1651 		case SCF_ERROR_NOT_SET:
1652 		default:
1653 			bad_error("scf_iter_service_instances", scf_error());
1654 		}
1655 	}
1656 
1657 	for (;;) {
1658 		r = scf_iter_next_instance(iter, inst);
1659 		if (r == 0)
1660 			break;
1661 		if (r != 1) {
1662 			switch (scf_error()) {
1663 			case SCF_ERROR_CONNECTION_BROKEN:
1664 				return (ECONNABORTED);
1665 
1666 			case SCF_ERROR_DELETED:
1667 				return (ECANCELED);
1668 
1669 			case SCF_ERROR_HANDLE_MISMATCH:
1670 			case SCF_ERROR_NOT_BOUND:
1671 			case SCF_ERROR_NOT_SET:
1672 			case SCF_ERROR_INVALID_ARGUMENT:
1673 			default:
1674 				bad_error("scf_iter_next_instance",
1675 				    scf_error());
1676 			}
1677 		}
1678 
1679 		/*
1680 		 * Similarly, just take a new running snapshot if operating on
1681 		 * a non-live repository or running during early import.
1682 		 */
1683 		if (est->sc_repo_filename != NULL ||
1684 		    est->sc_repo_doorname != NULL ||
1685 		    est->sc_in_emi == 1) {
1686 			r = refresh_running_snapshot(inst);
1687 			switch (r) {
1688 			case 0:
1689 				continue;
1690 
1691 			case ECONNABORTED:
1692 			case ECANCELED:
1693 			case EPERM:
1694 			case ENOSPC:
1695 				break;
1696 			default:
1697 				bad_error("refresh_running_snapshot",
1698 				    scf_error());
1699 			}
1700 
1701 			return (r);
1702 
1703 		}
1704 
1705 		if (_smf_refresh_instance_i(inst) == 0) {
1706 			if (g_verbose) {
1707 				if (scf_instance_get_name(inst, name_buf,
1708 				    max_scf_name_len + 1) < 0)
1709 					(void) strcpy(name_buf, "?");
1710 
1711 				warn(gettext("Refreshed %s:%s.\n"),
1712 				    fmri, name_buf);
1713 			}
1714 		} else {
1715 			if (scf_error() != SCF_ERROR_BACKEND_ACCESS ||
1716 			    g_verbose) {
1717 				scfe = scf_error();
1718 
1719 				if (scf_instance_to_fmri(inst, name_buf,
1720 				    max_scf_name_len + 1) < 0)
1721 					(void) strcpy(name_buf, "?");
1722 
1723 				warn(gettext(
1724 				    "Refresh of %s:%s failed: %s.\n"), fmri,
1725 				    name_buf, scf_strerror(scfe));
1726 			}
1727 		}
1728 	}
1729 
1730 	return (0);
1731 }
1732 
1733 static void
1734 private_refresh(void)
1735 {
1736 	scf_instance_t *pinst = NULL;
1737 	scf_iter_t *piter = NULL;
1738 	ssize_t fmrilen;
1739 	size_t bufsz;
1740 	char *fmribuf;
1741 	void *ent;
1742 	int issvc;
1743 	int r;
1744 
1745 	if (est->sc_repo_filename == NULL && est->sc_repo_doorname == NULL)
1746 		return;
1747 
1748 	assert(cur_svc != NULL);
1749 
1750 	bufsz = max_scf_fmri_len + 1;
1751 	fmribuf = safe_malloc(bufsz);
1752 	if (cur_inst) {
1753 		issvc = 0;
1754 		ent = cur_inst;
1755 		fmrilen = scf_instance_to_fmri(ent, fmribuf, bufsz);
1756 	} else {
1757 		issvc = 1;
1758 		ent = cur_svc;
1759 		fmrilen = scf_service_to_fmri(ent, fmribuf, bufsz);
1760 		if ((pinst = scf_instance_create(g_hndl)) == NULL)
1761 			scfdie();
1762 
1763 		if ((piter = scf_iter_create(g_hndl)) == NULL)
1764 			scfdie();
1765 	}
1766 	if (fmrilen < 0) {
1767 		free(fmribuf);
1768 		if (scf_error() != SCF_ERROR_DELETED)
1769 			scfdie();
1770 
1771 		warn(emsg_deleted);
1772 		return;
1773 	}
1774 	assert(fmrilen < bufsz);
1775 
1776 	r = refresh_entity(issvc, ent, fmribuf, pinst, piter, NULL);
1777 	switch (r) {
1778 	case 0:
1779 		break;
1780 
1781 	case ECONNABORTED:
1782 		warn(gettext("Could not refresh %s "
1783 		    "(repository connection broken).\n"), fmribuf);
1784 		break;
1785 
1786 	case ECANCELED:
1787 		warn(emsg_deleted);
1788 		break;
1789 
1790 	case EPERM:
1791 		warn(gettext("Could not refresh %s "
1792 		    "(permission denied).\n"), fmribuf);
1793 		break;
1794 
1795 	case ENOSPC:
1796 		warn(gettext("Could not refresh %s "
1797 		    "(repository server out of resources).\n"),
1798 		    fmribuf);
1799 		break;
1800 
1801 	case EACCES:
1802 	default:
1803 		bad_error("refresh_entity", scf_error());
1804 	}
1805 
1806 	if (issvc) {
1807 		scf_instance_destroy(pinst);
1808 		scf_iter_destroy(piter);
1809 	}
1810 
1811 	free(fmribuf);
1812 }
1813 
1814 
1815 static int
1816 stash_scferror_err(scf_callback_t *cbp, scf_error_t err)
1817 {
1818 	cbp->sc_err = scferror2errno(err);
1819 	return (UU_WALK_ERROR);
1820 }
1821 
1822 static int
1823 stash_scferror(scf_callback_t *cbp)
1824 {
1825 	return (stash_scferror_err(cbp, scf_error()));
1826 }
1827 
1828 static int select_inst(const char *);
1829 static int select_svc(const char *);
1830 
1831 /*
1832  * Take a property that does not have a type and check to see if a type
1833  * exists or can be gleened from the current data.  Set the type.
1834  *
1835  * Check the current level (instance) and then check the higher level
1836  * (service).  This could be the case for adding a new property to
1837  * the instance that's going to "override" a service level property.
1838  *
1839  * For a property :
1840  * 1. Take the type from an existing property
1841  * 2. Take the type from a template entry
1842  *
1843  * If the type can not be found, then leave the type as is, and let the import
1844  * report the problem of the missing type.
1845  */
1846 static int
1847 find_current_prop_type(void *p, void *g)
1848 {
1849 	property_t *prop = p;
1850 	scf_callback_t *lcb = g;
1851 	pgroup_t *pg = NULL;
1852 
1853 	const char *fmri = NULL;
1854 	char *lfmri = NULL;
1855 	char *cur_selection = NULL;
1856 
1857 	scf_propertygroup_t *sc_pg = NULL;
1858 	scf_property_t *sc_prop = NULL;
1859 	scf_pg_tmpl_t *t_pg = NULL;
1860 	scf_prop_tmpl_t *t_prop = NULL;
1861 	scf_type_t prop_type;
1862 
1863 	value_t *vp;
1864 	int issvc = lcb->sc_service;
1865 	int r = UU_WALK_ERROR;
1866 
1867 	if (prop->sc_value_type != SCF_TYPE_INVALID)
1868 		return (UU_WALK_NEXT);
1869 
1870 	t_prop = scf_tmpl_prop_create(g_hndl);
1871 	sc_prop = scf_property_create(g_hndl);
1872 	if (sc_prop == NULL || t_prop == NULL) {
1873 		warn(gettext("Unable to create the property to attempt and "
1874 		    "find a missing type.\n"));
1875 
1876 		scf_property_destroy(sc_prop);
1877 		scf_tmpl_prop_destroy(t_prop);
1878 
1879 		return (UU_WALK_ERROR);
1880 	}
1881 
1882 	if (lcb->sc_flags == 1) {
1883 		pg = lcb->sc_parent;
1884 		issvc = (pg->sc_parent->sc_etype == SVCCFG_SERVICE_OBJECT);
1885 		fmri = pg->sc_parent->sc_fmri;
1886 retry_pg:
1887 		if (cur_svc && cur_selection == NULL) {
1888 			cur_selection = safe_malloc(max_scf_fmri_len + 1);
1889 			lscf_get_selection_str(cur_selection,
1890 			    max_scf_fmri_len + 1);
1891 
1892 			if (strcmp(cur_selection, fmri) != 0) {
1893 				lscf_select(fmri);
1894 			} else {
1895 				free(cur_selection);
1896 				cur_selection = NULL;
1897 			}
1898 		} else {
1899 			lscf_select(fmri);
1900 		}
1901 
1902 		if (sc_pg == NULL && (sc_pg = scf_pg_create(g_hndl)) == NULL) {
1903 			warn(gettext("Unable to create property group to "
1904 			    "find a missing property type.\n"));
1905 
1906 			goto out;
1907 		}
1908 
1909 		if (get_pg(pg->sc_pgroup_name, sc_pg) != SCF_SUCCESS) {
1910 			/*
1911 			 * If this is the sc_pg from the parent
1912 			 * let the caller clean up the sc_pg,
1913 			 * and just throw it away in this case.
1914 			 */
1915 			if (sc_pg != lcb->sc_parent)
1916 				scf_pg_destroy(sc_pg);
1917 
1918 			sc_pg = NULL;
1919 			if ((t_pg = scf_tmpl_pg_create(g_hndl)) == NULL) {
1920 				warn(gettext("Unable to create template "
1921 				    "property group to find a property "
1922 				    "type.\n"));
1923 
1924 				goto out;
1925 			}
1926 
1927 			if (scf_tmpl_get_by_pg_name(fmri, NULL,
1928 			    pg->sc_pgroup_name, NULL, t_pg,
1929 			    SCF_PG_TMPL_FLAG_EXACT) != SCF_SUCCESS) {
1930 				/*
1931 				 * if instance get service and jump back
1932 				 */
1933 				scf_tmpl_pg_destroy(t_pg);
1934 				t_pg = NULL;
1935 				if (issvc == 0) {
1936 					entity_t *e = pg->sc_parent->sc_parent;
1937 
1938 					fmri = e->sc_fmri;
1939 					issvc = 1;
1940 					goto retry_pg;
1941 				} else {
1942 					goto out;
1943 				}
1944 			}
1945 		}
1946 	} else {
1947 		sc_pg = lcb->sc_parent;
1948 	}
1949 
1950 	/*
1951 	 * Attempt to get the type from an existing property.  If the property
1952 	 * cannot be found then attempt to get the type from a template entry
1953 	 * for the property.
1954 	 *
1955 	 * Finally, if at the instance level look at the service level.
1956 	 */
1957 	if (sc_pg != NULL &&
1958 	    pg_get_prop(sc_pg, prop->sc_property_name,
1959 	    sc_prop) == SCF_SUCCESS &&
1960 	    scf_property_type(sc_prop, &prop_type) == SCF_SUCCESS) {
1961 		prop->sc_value_type = prop_type;
1962 
1963 		/*
1964 		 * Found a type, update the value types and validate
1965 		 * the actual value against this type.
1966 		 */
1967 		for (vp = uu_list_first(prop->sc_property_values);
1968 		    vp != NULL;
1969 		    vp = uu_list_next(prop->sc_property_values, vp)) {
1970 			vp->sc_type = prop->sc_value_type;
1971 			lxml_store_value(vp, 0, NULL);
1972 		}
1973 
1974 		r = UU_WALK_NEXT;
1975 		goto out;
1976 	}
1977 
1978 	/*
1979 	 * If we get here with t_pg set to NULL then we had to have
1980 	 * gotten an sc_pg but that sc_pg did not have the property
1981 	 * we are looking for.   So if the t_pg is not null look up
1982 	 * the template entry for the property.
1983 	 *
1984 	 * If the t_pg is null then need to attempt to get a matching
1985 	 * template entry for the sc_pg, and see if there is a property
1986 	 * entry for that template entry.
1987 	 */
1988 do_tmpl :
1989 	if (t_pg != NULL &&
1990 	    scf_tmpl_get_by_prop(t_pg, prop->sc_property_name,
1991 	    t_prop, 0) == SCF_SUCCESS) {
1992 		if (scf_tmpl_prop_type(t_prop, &prop_type) == SCF_SUCCESS) {
1993 			prop->sc_value_type = prop_type;
1994 
1995 			/*
1996 			 * Found a type, update the value types and validate
1997 			 * the actual value against this type.
1998 			 */
1999 			for (vp = uu_list_first(prop->sc_property_values);
2000 			    vp != NULL;
2001 			    vp = uu_list_next(prop->sc_property_values, vp)) {
2002 				vp->sc_type = prop->sc_value_type;
2003 				lxml_store_value(vp, 0, NULL);
2004 			}
2005 
2006 			r = UU_WALK_NEXT;
2007 			goto out;
2008 		}
2009 	} else {
2010 		if (t_pg == NULL && sc_pg) {
2011 			if ((t_pg = scf_tmpl_pg_create(g_hndl)) == NULL) {
2012 				warn(gettext("Unable to create template "
2013 				    "property group to find a property "
2014 				    "type.\n"));
2015 
2016 				goto out;
2017 			}
2018 
2019 			if (scf_tmpl_get_by_pg(sc_pg, t_pg, 0) != SCF_SUCCESS) {
2020 				scf_tmpl_pg_destroy(t_pg);
2021 				t_pg = NULL;
2022 			} else {
2023 				goto do_tmpl;
2024 			}
2025 		}
2026 	}
2027 
2028 	if (issvc == 0) {
2029 		scf_instance_t *i;
2030 		scf_service_t *s;
2031 
2032 		issvc = 1;
2033 		if (lcb->sc_flags == 1) {
2034 			entity_t *e = pg->sc_parent->sc_parent;
2035 
2036 			fmri = e->sc_fmri;
2037 			goto retry_pg;
2038 		}
2039 
2040 		/*
2041 		 * because lcb->sc_flags was not set then this means
2042 		 * the pg was not used and can be used here.
2043 		 */
2044 		if ((pg = internal_pgroup_new()) == NULL) {
2045 			warn(gettext("Could not create internal property group "
2046 			    "to find a missing type."));
2047 
2048 			goto out;
2049 		}
2050 
2051 		pg->sc_pgroup_name = safe_malloc(max_scf_name_len + 1);
2052 		if (scf_pg_get_name(sc_pg, (char *)pg->sc_pgroup_name,
2053 		    max_scf_name_len + 1) < 0)
2054 				goto out;
2055 
2056 		i = scf_instance_create(g_hndl);
2057 		s = scf_service_create(g_hndl);
2058 		if (i == NULL || s == NULL ||
2059 		    scf_pg_get_parent_instance(sc_pg, i) != SCF_SUCCESS) {
2060 			warn(gettext("Could not get a service for the instance "
2061 			    "to find a missing type."));
2062 
2063 			goto out;
2064 		}
2065 
2066 		/*
2067 		 * Check to see truly at the instance level.
2068 		 */
2069 		lfmri = safe_malloc(max_scf_fmri_len + 1);
2070 		if (scf_instance_get_parent(i, s) == SCF_SUCCESS &&
2071 		    scf_service_to_fmri(s, lfmri, max_scf_fmri_len + 1) < 0)
2072 			goto out;
2073 		else
2074 			fmri = (const char *)lfmri;
2075 
2076 		goto retry_pg;
2077 	}
2078 
2079 out :
2080 	if (sc_pg != lcb->sc_parent) {
2081 		scf_pg_destroy(sc_pg);
2082 	}
2083 
2084 	/*
2085 	 * If this is true then the pg was allocated
2086 	 * here, and the name was set so need to free
2087 	 * the name and the pg.
2088 	 */
2089 	if (pg != NULL && pg != lcb->sc_parent) {
2090 		free((char *)pg->sc_pgroup_name);
2091 		internal_pgroup_free(pg);
2092 	}
2093 
2094 	if (cur_selection) {
2095 		lscf_select(cur_selection);
2096 		free(cur_selection);
2097 	}
2098 
2099 	scf_tmpl_pg_destroy(t_pg);
2100 	scf_tmpl_prop_destroy(t_prop);
2101 	scf_property_destroy(sc_prop);
2102 
2103 	if (r != UU_WALK_NEXT)
2104 		warn(gettext("Could not find property type for \"%s\" "
2105 		    "from \"%s\"\n"), prop->sc_property_name,
2106 		    fmri != NULL ? fmri : lcb->sc_source_fmri);
2107 
2108 	free(lfmri);
2109 
2110 	return (r);
2111 }
2112 
2113 /*
2114  * Take a property group that does not have a type and check to see if a type
2115  * exists or can be gleened from the current data.  Set the type.
2116  *
2117  * Check the current level (instance) and then check the higher level
2118  * (service).  This could be the case for adding a new property to
2119  * the instance that's going to "override" a service level property.
2120  *
2121  * For a property group
2122  * 1. Take the type from an existing property group
2123  * 2. Take the type from a template entry
2124  *
2125  * If the type can not be found, then leave the type as is, and let the import
2126  * report the problem of the missing type.
2127  */
2128 static int
2129 find_current_pg_type(void *p, void *sori)
2130 {
2131 	entity_t *si = sori;
2132 	pgroup_t *pg = p;
2133 
2134 	const char *ofmri, *fmri;
2135 	char *cur_selection = NULL;
2136 	char *pg_type = NULL;
2137 
2138 	scf_propertygroup_t *sc_pg = NULL;
2139 	scf_pg_tmpl_t *t_pg = NULL;
2140 
2141 	int issvc = (si->sc_etype == SVCCFG_SERVICE_OBJECT);
2142 	int r = UU_WALK_ERROR;
2143 
2144 	ofmri = fmri = si->sc_fmri;
2145 	if (pg->sc_pgroup_type != NULL) {
2146 		r = UU_WALK_NEXT;
2147 
2148 		goto out;
2149 	}
2150 
2151 	sc_pg = scf_pg_create(g_hndl);
2152 	if (sc_pg == NULL) {
2153 		warn(gettext("Unable to create property group to attempt "
2154 		    "and find a missing type.\n"));
2155 
2156 		return (UU_WALK_ERROR);
2157 	}
2158 
2159 	/*
2160 	 * Using get_pg() requires that the cur_svc/cur_inst be
2161 	 * via lscf_select.  Need to preserve the current selection
2162 	 * if going to use lscf_select() to set up the cur_svc/cur_inst
2163 	 */
2164 	if (cur_svc) {
2165 		cur_selection = safe_malloc(max_scf_fmri_len + 1);
2166 		lscf_get_selection_str(cur_selection, max_scf_fmri_len + 1);
2167 	}
2168 
2169 	/*
2170 	 * If the property group exists get the type, and set
2171 	 * the pgroup_t type of that type.
2172 	 *
2173 	 * If not the check for a template pg_pattern entry
2174 	 * and take the type from that.
2175 	 */
2176 retry_svc:
2177 	lscf_select(fmri);
2178 
2179 	if (get_pg(pg->sc_pgroup_name, sc_pg) == SCF_SUCCESS) {
2180 		pg_type = safe_malloc(max_scf_pg_type_len + 1);
2181 		if (pg_type != NULL && scf_pg_get_type(sc_pg, pg_type,
2182 		    max_scf_pg_type_len + 1) != -1) {
2183 			pg->sc_pgroup_type = pg_type;
2184 
2185 			r = UU_WALK_NEXT;
2186 			goto out;
2187 		} else {
2188 			free(pg_type);
2189 		}
2190 	} else {
2191 		if ((t_pg == NULL) &&
2192 		    (t_pg = scf_tmpl_pg_create(g_hndl)) == NULL)
2193 			goto out;
2194 
2195 		if (scf_tmpl_get_by_pg_name(fmri, NULL, pg->sc_pgroup_name,
2196 		    NULL, t_pg, SCF_PG_TMPL_FLAG_EXACT) == SCF_SUCCESS &&
2197 		    scf_tmpl_pg_type(t_pg, &pg_type) != -1) {
2198 			pg->sc_pgroup_type = pg_type;
2199 
2200 			r = UU_WALK_NEXT;
2201 			goto out;
2202 		}
2203 	}
2204 
2205 	/*
2206 	 * If type is not found at the instance level then attempt to
2207 	 * find the type at the service level.
2208 	 */
2209 	if (!issvc) {
2210 		si = si->sc_parent;
2211 		fmri = si->sc_fmri;
2212 		issvc = (si->sc_etype == SVCCFG_SERVICE_OBJECT);
2213 		goto retry_svc;
2214 	}
2215 
2216 out :
2217 	if (cur_selection) {
2218 		lscf_select(cur_selection);
2219 		free(cur_selection);
2220 	}
2221 
2222 	/*
2223 	 * Now walk the properties of the property group to make sure that
2224 	 * all properties have the correct type and values are valid for
2225 	 * those types.
2226 	 */
2227 	if (r == UU_WALK_NEXT) {
2228 		scf_callback_t cb;
2229 
2230 		cb.sc_service = issvc;
2231 		cb.sc_source_fmri = ofmri;
2232 		if (sc_pg != NULL) {
2233 			cb.sc_parent = sc_pg;
2234 			cb.sc_flags = 0;
2235 		} else {
2236 			cb.sc_parent = pg;
2237 			cb.sc_flags = 1;
2238 		}
2239 
2240 		if (uu_list_walk(pg->sc_pgroup_props, find_current_prop_type,
2241 		    &cb, UU_DEFAULT) != 0) {
2242 			if (uu_error() != UU_ERROR_CALLBACK_FAILED)
2243 				bad_error("uu_list_walk", uu_error());
2244 
2245 			r = UU_WALK_ERROR;
2246 		}
2247 	} else {
2248 		warn(gettext("Could not find property group type for "
2249 		    "\"%s\" from \"%s\"\n"), pg->sc_pgroup_name, fmri);
2250 	}
2251 
2252 	scf_tmpl_pg_destroy(t_pg);
2253 	scf_pg_destroy(sc_pg);
2254 
2255 	return (r);
2256 }
2257 
2258 /*
2259  * Import.  These functions import a bundle into the repository.
2260  */
2261 
2262 /*
2263  * Add a transaction entry to lcbdata->sc_trans for this property_t.  Uses
2264  * sc_handle, sc_trans, and sc_flags (SCI_NOENABLED) in lcbdata.  On success,
2265  * returns UU_WALK_NEXT.  On error returns UU_WALK_ERROR and sets
2266  * lcbdata->sc_err to
2267  *   ENOMEM - out of memory
2268  *   ECONNABORTED - repository connection broken
2269  *   ECANCELED - sc_trans's property group was deleted
2270  *   EINVAL - p's name is invalid (error printed)
2271  *	    - p has an invalid value (error printed)
2272  */
2273 static int
2274 lscf_property_import(void *v, void *pvt)
2275 {
2276 	property_t *p = v;
2277 	scf_callback_t *lcbdata = pvt;
2278 	value_t *vp;
2279 	scf_transaction_t *trans = lcbdata->sc_trans;
2280 	scf_transaction_entry_t *entr;
2281 	scf_value_t *val;
2282 	scf_type_t tp;
2283 
2284 	if ((lcbdata->sc_flags & SCI_NOENABLED ||
2285 	    lcbdata->sc_flags & SCI_DELAYENABLE) &&
2286 	    strcmp(p->sc_property_name, SCF_PROPERTY_ENABLED) == 0) {
2287 		lcbdata->sc_enable = p;
2288 		return (UU_WALK_NEXT);
2289 	}
2290 
2291 	entr = scf_entry_create(lcbdata->sc_handle);
2292 	if (entr == NULL) {
2293 		switch (scf_error()) {
2294 		case SCF_ERROR_NO_MEMORY:
2295 			return (stash_scferror(lcbdata));
2296 
2297 		case SCF_ERROR_INVALID_ARGUMENT:
2298 		default:
2299 			bad_error("scf_entry_create", scf_error());
2300 		}
2301 	}
2302 
2303 	tp = p->sc_value_type;
2304 
2305 	if (scf_transaction_property_new(trans, entr,
2306 	    p->sc_property_name, tp) != 0) {
2307 		switch (scf_error()) {
2308 		case SCF_ERROR_INVALID_ARGUMENT:
2309 			semerr(emsg_invalid_prop_name, p->sc_property_name);
2310 			scf_entry_destroy(entr);
2311 			return (stash_scferror(lcbdata));
2312 
2313 		case SCF_ERROR_EXISTS:
2314 			break;
2315 
2316 		case SCF_ERROR_DELETED:
2317 		case SCF_ERROR_CONNECTION_BROKEN:
2318 			scf_entry_destroy(entr);
2319 			return (stash_scferror(lcbdata));
2320 
2321 		case SCF_ERROR_NOT_BOUND:
2322 		case SCF_ERROR_HANDLE_MISMATCH:
2323 		case SCF_ERROR_NOT_SET:
2324 		default:
2325 			bad_error("scf_transaction_property_new", scf_error());
2326 		}
2327 
2328 		if (scf_transaction_property_change_type(trans, entr,
2329 		    p->sc_property_name, tp) != 0) {
2330 			switch (scf_error()) {
2331 			case SCF_ERROR_DELETED:
2332 			case SCF_ERROR_CONNECTION_BROKEN:
2333 				scf_entry_destroy(entr);
2334 				return (stash_scferror(lcbdata));
2335 
2336 			case SCF_ERROR_INVALID_ARGUMENT:
2337 				semerr(emsg_invalid_prop_name,
2338 				    p->sc_property_name);
2339 				scf_entry_destroy(entr);
2340 				return (stash_scferror(lcbdata));
2341 
2342 			case SCF_ERROR_NOT_FOUND:
2343 			case SCF_ERROR_NOT_SET:
2344 			case SCF_ERROR_HANDLE_MISMATCH:
2345 			case SCF_ERROR_NOT_BOUND:
2346 			default:
2347 				bad_error(
2348 				    "scf_transaction_property_change_type",
2349 				    scf_error());
2350 			}
2351 		}
2352 	}
2353 
2354 	for (vp = uu_list_first(p->sc_property_values);
2355 	    vp != NULL;
2356 	    vp = uu_list_next(p->sc_property_values, vp)) {
2357 		val = scf_value_create(g_hndl);
2358 		if (val == NULL) {
2359 			switch (scf_error()) {
2360 			case SCF_ERROR_NO_MEMORY:
2361 				return (stash_scferror(lcbdata));
2362 
2363 			case SCF_ERROR_INVALID_ARGUMENT:
2364 			default:
2365 				bad_error("scf_value_create", scf_error());
2366 			}
2367 		}
2368 
2369 		switch (tp) {
2370 		case SCF_TYPE_BOOLEAN:
2371 			scf_value_set_boolean(val, vp->sc_u.sc_count);
2372 			break;
2373 		case SCF_TYPE_COUNT:
2374 			scf_value_set_count(val, vp->sc_u.sc_count);
2375 			break;
2376 		case SCF_TYPE_INTEGER:
2377 			scf_value_set_integer(val, vp->sc_u.sc_integer);
2378 			break;
2379 		default:
2380 			assert(vp->sc_u.sc_string != NULL);
2381 			if (scf_value_set_from_string(val, tp,
2382 			    vp->sc_u.sc_string) != 0) {
2383 				if (scf_error() != SCF_ERROR_INVALID_ARGUMENT)
2384 					bad_error("scf_value_set_from_string",
2385 					    scf_error());
2386 
2387 				warn(gettext("Value \"%s\" is not a valid "
2388 				    "%s.\n"), vp->sc_u.sc_string,
2389 				    scf_type_to_string(tp));
2390 				scf_value_destroy(val);
2391 				return (stash_scferror(lcbdata));
2392 			}
2393 			break;
2394 		}
2395 
2396 		if (scf_entry_add_value(entr, val) != 0)
2397 			bad_error("scf_entry_add_value", scf_error());
2398 	}
2399 
2400 	return (UU_WALK_NEXT);
2401 }
2402 
2403 /*
2404  * Import a pgroup_t into the repository.  Uses sc_handle, sc_parent,
2405  * sc_service, sc_flags (SCI_GENERALLAST, SCI_FORCE, & SCI_KEEP),
2406  * sc_source_fmri, and sc_target_fmri in lcbdata, and uses imp_pg and imp_tx.
2407  * On success, returns UU_WALK_NEXT.  On error returns UU_WALK_ERROR and sets
2408  * lcbdata->sc_err to
2409  *   ECONNABORTED - repository connection broken
2410  *   ENOMEM - out of memory
2411  *   ENOSPC - svc.configd is out of resources
2412  *   ECANCELED - sc_parent was deleted
2413  *   EPERM - could not create property group (permission denied) (error printed)
2414  *	   - could not modify property group (permission denied) (error printed)
2415  *	   - could not delete property group (permission denied) (error	printed)
2416  *   EROFS - could not create property group (repository is read-only)
2417  *	   - could not delete property group (repository is read-only)
2418  *   EACCES - could not create property group (backend access denied)
2419  *	    - could not delete property group (backend access denied)
2420  *   EEXIST - could not create property group (already exists)
2421  *   EINVAL - invalid property group name (error printed)
2422  *	    - invalid property name (error printed)
2423  *	    - invalid value (error printed)
2424  *   EBUSY - new property group deleted (error printed)
2425  *	   - new property group changed (error printed)
2426  *	   - property group added (error printed)
2427  *	   - property group deleted (error printed)
2428  */
2429 static int
2430 entity_pgroup_import(void *v, void *pvt)
2431 {
2432 	pgroup_t *p = v;
2433 	scf_callback_t cbdata;
2434 	scf_callback_t *lcbdata = pvt;
2435 	void *ent = lcbdata->sc_parent;
2436 	int issvc = lcbdata->sc_service;
2437 	int r;
2438 
2439 	const char * const pg_changed = gettext("%s changed unexpectedly "
2440 	    "(new property group \"%s\" changed).\n");
2441 
2442 	/* Never import deleted property groups. */
2443 	if (p->sc_pgroup_delete) {
2444 		if ((lcbdata->sc_flags & SCI_OP_APPLY) == SCI_OP_APPLY &&
2445 		    entity_get_pg(ent, issvc, p->sc_pgroup_name, imp_pg) == 0) {
2446 			goto delete_pg;
2447 		}
2448 		return (UU_WALK_NEXT);
2449 	}
2450 
2451 	if (!issvc && (lcbdata->sc_flags & SCI_GENERALLAST) &&
2452 	    strcmp(p->sc_pgroup_name, SCF_PG_GENERAL) == 0) {
2453 		lcbdata->sc_general = p;
2454 		return (UU_WALK_NEXT);
2455 	}
2456 
2457 add_pg:
2458 	if (issvc)
2459 		r = scf_service_add_pg(ent, p->sc_pgroup_name,
2460 		    p->sc_pgroup_type, p->sc_pgroup_flags, imp_pg);
2461 	else
2462 		r = scf_instance_add_pg(ent, p->sc_pgroup_name,
2463 		    p->sc_pgroup_type, p->sc_pgroup_flags, imp_pg);
2464 	if (r != 0) {
2465 		switch (scf_error()) {
2466 		case SCF_ERROR_DELETED:
2467 		case SCF_ERROR_CONNECTION_BROKEN:
2468 		case SCF_ERROR_BACKEND_READONLY:
2469 		case SCF_ERROR_BACKEND_ACCESS:
2470 		case SCF_ERROR_NO_RESOURCES:
2471 			return (stash_scferror(lcbdata));
2472 
2473 		case SCF_ERROR_EXISTS:
2474 			if (lcbdata->sc_flags & SCI_FORCE)
2475 				break;
2476 			return (stash_scferror(lcbdata));
2477 
2478 		case SCF_ERROR_INVALID_ARGUMENT:
2479 			warn(emsg_fmri_invalid_pg_name_type,
2480 			    lcbdata->sc_source_fmri,
2481 			    p->sc_pgroup_name, p->sc_pgroup_type);
2482 			return (stash_scferror(lcbdata));
2483 
2484 		case SCF_ERROR_PERMISSION_DENIED:
2485 			warn(emsg_pg_add_perm, p->sc_pgroup_name,
2486 			    lcbdata->sc_target_fmri);
2487 			return (stash_scferror(lcbdata));
2488 
2489 		case SCF_ERROR_NOT_BOUND:
2490 		case SCF_ERROR_HANDLE_MISMATCH:
2491 		case SCF_ERROR_NOT_SET:
2492 		default:
2493 			bad_error("scf_service_add_pg", scf_error());
2494 		}
2495 
2496 		if (entity_get_pg(ent, issvc, p->sc_pgroup_name, imp_pg) != 0) {
2497 			switch (scf_error()) {
2498 			case SCF_ERROR_CONNECTION_BROKEN:
2499 			case SCF_ERROR_DELETED:
2500 				return (stash_scferror(lcbdata));
2501 
2502 			case SCF_ERROR_INVALID_ARGUMENT:
2503 				warn(emsg_fmri_invalid_pg_name,
2504 				    lcbdata->sc_source_fmri,
2505 				    p->sc_pgroup_name);
2506 				return (stash_scferror(lcbdata));
2507 
2508 			case SCF_ERROR_NOT_FOUND:
2509 				warn(emsg_pg_deleted, lcbdata->sc_target_fmri,
2510 				    p->sc_pgroup_name);
2511 				lcbdata->sc_err = EBUSY;
2512 				return (UU_WALK_ERROR);
2513 
2514 			case SCF_ERROR_NOT_BOUND:
2515 			case SCF_ERROR_HANDLE_MISMATCH:
2516 			case SCF_ERROR_NOT_SET:
2517 			default:
2518 				bad_error("entity_get_pg", scf_error());
2519 			}
2520 		}
2521 
2522 		if (lcbdata->sc_flags & SCI_KEEP)
2523 			goto props;
2524 
2525 delete_pg:
2526 		if (scf_pg_delete(imp_pg) != 0) {
2527 			switch (scf_error()) {
2528 			case SCF_ERROR_DELETED:
2529 				warn(emsg_pg_deleted, lcbdata->sc_target_fmri,
2530 				    p->sc_pgroup_name);
2531 				lcbdata->sc_err = EBUSY;
2532 				return (UU_WALK_ERROR);
2533 
2534 			case SCF_ERROR_PERMISSION_DENIED:
2535 				warn(emsg_pg_del_perm, p->sc_pgroup_name,
2536 				    lcbdata->sc_target_fmri);
2537 				return (stash_scferror(lcbdata));
2538 
2539 			case SCF_ERROR_BACKEND_READONLY:
2540 			case SCF_ERROR_BACKEND_ACCESS:
2541 			case SCF_ERROR_CONNECTION_BROKEN:
2542 				return (stash_scferror(lcbdata));
2543 
2544 			case SCF_ERROR_NOT_SET:
2545 			default:
2546 				bad_error("scf_pg_delete", scf_error());
2547 			}
2548 		}
2549 
2550 		if (p->sc_pgroup_delete)
2551 			return (UU_WALK_NEXT);
2552 
2553 		goto add_pg;
2554 	}
2555 
2556 props:
2557 
2558 	/*
2559 	 * Add properties to property group, if any.
2560 	 */
2561 	cbdata.sc_handle = lcbdata->sc_handle;
2562 	cbdata.sc_parent = imp_pg;
2563 	cbdata.sc_flags = lcbdata->sc_flags;
2564 	cbdata.sc_trans = imp_tx;
2565 	cbdata.sc_enable = NULL;
2566 
2567 	if (scf_transaction_start(imp_tx, imp_pg) != 0) {
2568 		switch (scf_error()) {
2569 		case SCF_ERROR_BACKEND_ACCESS:
2570 		case SCF_ERROR_BACKEND_READONLY:
2571 		case SCF_ERROR_CONNECTION_BROKEN:
2572 			return (stash_scferror(lcbdata));
2573 
2574 		case SCF_ERROR_DELETED:
2575 			warn(pg_changed, lcbdata->sc_target_fmri,
2576 			    p->sc_pgroup_name);
2577 			lcbdata->sc_err = EBUSY;
2578 			return (UU_WALK_ERROR);
2579 
2580 		case SCF_ERROR_PERMISSION_DENIED:
2581 			warn(emsg_pg_mod_perm, p->sc_pgroup_name,
2582 			    lcbdata->sc_target_fmri);
2583 			return (stash_scferror(lcbdata));
2584 
2585 		case SCF_ERROR_NOT_BOUND:
2586 		case SCF_ERROR_NOT_SET:
2587 		case SCF_ERROR_IN_USE:
2588 		case SCF_ERROR_HANDLE_MISMATCH:
2589 		default:
2590 			bad_error("scf_transaction_start", scf_error());
2591 		}
2592 	}
2593 
2594 	if (uu_list_walk(p->sc_pgroup_props, lscf_property_import, &cbdata,
2595 	    UU_DEFAULT) != 0) {
2596 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
2597 			bad_error("uu_list_walk", uu_error());
2598 		scf_transaction_reset(imp_tx);
2599 
2600 		lcbdata->sc_err = cbdata.sc_err;
2601 		if (cbdata.sc_err == ECANCELED) {
2602 			warn(pg_changed, lcbdata->sc_target_fmri,
2603 			    p->sc_pgroup_name);
2604 			lcbdata->sc_err = EBUSY;
2605 		}
2606 		return (UU_WALK_ERROR);
2607 	}
2608 
2609 	if ((lcbdata->sc_flags & SCI_DELAYENABLE) && cbdata.sc_enable) {
2610 		cbdata.sc_flags = cbdata.sc_flags & (~SCI_DELAYENABLE);
2611 
2612 		/*
2613 		 * take the snapshot running snapshot then
2614 		 * import the stored general/enable property
2615 		 */
2616 		r = take_snap(ent, snap_running, imp_rsnap);
2617 		switch (r) {
2618 		case 0:
2619 			break;
2620 
2621 		case ECONNABORTED:
2622 			warn(gettext("Could not take %s snapshot on import "
2623 			    "(repository connection broken).\n"),
2624 			    snap_running);
2625 			lcbdata->sc_err = r;
2626 			return (UU_WALK_ERROR);
2627 		case ECANCELED:
2628 			warn(emsg_deleted);
2629 			lcbdata->sc_err = r;
2630 			return (UU_WALK_ERROR);
2631 
2632 		case EPERM:
2633 			warn(gettext("Could not take %s snapshot "
2634 			    "(permission denied).\n"), snap_running);
2635 			lcbdata->sc_err = r;
2636 			return (UU_WALK_ERROR);
2637 
2638 		case ENOSPC:
2639 			warn(gettext("Could not take %s snapshot"
2640 			    "(repository server out of resources).\n"),
2641 			    snap_running);
2642 			lcbdata->sc_err = r;
2643 			return (UU_WALK_ERROR);
2644 
2645 		default:
2646 			bad_error("take_snap", r);
2647 		}
2648 
2649 		r = lscf_property_import(cbdata.sc_enable, &cbdata);
2650 		if (r != UU_WALK_NEXT) {
2651 			if (r != UU_WALK_ERROR)
2652 				bad_error("lscf_property_import", r);
2653 			return (EINVAL);
2654 		}
2655 	}
2656 
2657 	r = scf_transaction_commit(imp_tx);
2658 	switch (r) {
2659 	case 1:
2660 		r = UU_WALK_NEXT;
2661 		break;
2662 
2663 	case 0:
2664 		warn(pg_changed, lcbdata->sc_target_fmri, p->sc_pgroup_name);
2665 		lcbdata->sc_err = EBUSY;
2666 		r = UU_WALK_ERROR;
2667 		break;
2668 
2669 	case -1:
2670 		switch (scf_error()) {
2671 		case SCF_ERROR_BACKEND_READONLY:
2672 		case SCF_ERROR_BACKEND_ACCESS:
2673 		case SCF_ERROR_CONNECTION_BROKEN:
2674 		case SCF_ERROR_NO_RESOURCES:
2675 			r = stash_scferror(lcbdata);
2676 			break;
2677 
2678 		case SCF_ERROR_DELETED:
2679 			warn(emsg_pg_deleted, lcbdata->sc_target_fmri,
2680 			    p->sc_pgroup_name);
2681 			lcbdata->sc_err = EBUSY;
2682 			r = UU_WALK_ERROR;
2683 			break;
2684 
2685 		case SCF_ERROR_PERMISSION_DENIED:
2686 			warn(emsg_pg_mod_perm, p->sc_pgroup_name,
2687 			    lcbdata->sc_target_fmri);
2688 			r = stash_scferror(lcbdata);
2689 			break;
2690 
2691 		case SCF_ERROR_NOT_SET:
2692 		case SCF_ERROR_INVALID_ARGUMENT:
2693 		case SCF_ERROR_NOT_BOUND:
2694 		default:
2695 			bad_error("scf_transaction_commit", scf_error());
2696 		}
2697 		break;
2698 
2699 	default:
2700 		bad_error("scf_transaction_commit", r);
2701 	}
2702 
2703 	scf_transaction_destroy_children(imp_tx);
2704 
2705 	return (r);
2706 }
2707 
2708 /*
2709  * Returns
2710  *   0 - success
2711  *   ECONNABORTED - repository connection broken
2712  *   ENOMEM - out of memory
2713  *   ENOSPC - svc.configd is out of resources
2714  *   ECANCELED - inst was deleted
2715  *   EPERM - could not create property group (permission denied) (error printed)
2716  *	   - could not modify property group (permission denied) (error printed)
2717  *   EROFS - could not create property group (repository is read-only)
2718  *   EACCES - could not create property group (backend access denied)
2719  *   EEXIST - could not create property group (already exists)
2720  *   EINVAL - invalid property group name (error printed)
2721  *	    - invalid property name (error printed)
2722  *	    - invalid value (error printed)
2723  *   EBUSY - new property group changed (error printed)
2724  */
2725 static int
2726 lscf_import_service_pgs(scf_service_t *svc, const char *target_fmri,
2727     const entity_t *isvc, int flags)
2728 {
2729 	scf_callback_t cbdata;
2730 
2731 	cbdata.sc_handle = scf_service_handle(svc);
2732 	cbdata.sc_parent = svc;
2733 	cbdata.sc_service = 1;
2734 	cbdata.sc_general = 0;
2735 	cbdata.sc_enable = 0;
2736 	cbdata.sc_flags = flags;
2737 	cbdata.sc_source_fmri = isvc->sc_fmri;
2738 	cbdata.sc_target_fmri = target_fmri;
2739 
2740 	/*
2741 	 * If the op is set, then add the flag to the callback
2742 	 * flags for later use.
2743 	 */
2744 	if (isvc->sc_op != SVCCFG_OP_NONE) {
2745 		switch (isvc->sc_op) {
2746 		case SVCCFG_OP_IMPORT :
2747 			cbdata.sc_flags |= SCI_OP_IMPORT;
2748 			break;
2749 		case SVCCFG_OP_APPLY :
2750 			cbdata.sc_flags |= SCI_OP_APPLY;
2751 			break;
2752 		case SVCCFG_OP_RESTORE :
2753 			cbdata.sc_flags |= SCI_OP_RESTORE;
2754 			break;
2755 		default :
2756 			uu_die(gettext("lscf_import_service_pgs : "
2757 			    "Unknown op stored in the service entity\n"));
2758 
2759 		}
2760 	}
2761 
2762 	if (uu_list_walk(isvc->sc_pgroups, entity_pgroup_import, &cbdata,
2763 	    UU_DEFAULT) != 0) {
2764 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
2765 			bad_error("uu_list_walk", uu_error());
2766 
2767 		return (cbdata.sc_err);
2768 	}
2769 
2770 	return (0);
2771 }
2772 
2773 /*
2774  * Returns
2775  *   0 - success
2776  *   ECONNABORTED - repository connection broken
2777  *   ENOMEM - out of memory
2778  *   ENOSPC - svc.configd is out of resources
2779  *   ECANCELED - inst was deleted
2780  *   EPERM - could not create property group (permission denied) (error printed)
2781  *	   - could not modify property group (permission denied) (error printed)
2782  *   EROFS - could not create property group (repository is read-only)
2783  *   EACCES - could not create property group (backend access denied)
2784  *   EEXIST - could not create property group (already exists)
2785  *   EINVAL - invalid property group name (error printed)
2786  *	    - invalid property name (error printed)
2787  *	    - invalid value (error printed)
2788  *   EBUSY - new property group changed (error printed)
2789  */
2790 static int
2791 lscf_import_instance_pgs(scf_instance_t *inst, const char *target_fmri,
2792     const entity_t *iinst, int flags)
2793 {
2794 	scf_callback_t cbdata;
2795 
2796 	cbdata.sc_handle = scf_instance_handle(inst);
2797 	cbdata.sc_parent = inst;
2798 	cbdata.sc_service = 0;
2799 	cbdata.sc_general = NULL;
2800 	cbdata.sc_enable = NULL;
2801 	cbdata.sc_flags = flags;
2802 	cbdata.sc_source_fmri = iinst->sc_fmri;
2803 	cbdata.sc_target_fmri = target_fmri;
2804 
2805 	/*
2806 	 * If the op is set, then add the flag to the callback
2807 	 * flags for later use.
2808 	 */
2809 	if (iinst->sc_op != SVCCFG_OP_NONE) {
2810 		switch (iinst->sc_op) {
2811 		case SVCCFG_OP_IMPORT :
2812 			cbdata.sc_flags |= SCI_OP_IMPORT;
2813 			break;
2814 		case SVCCFG_OP_APPLY :
2815 			cbdata.sc_flags |= SCI_OP_APPLY;
2816 			break;
2817 		case SVCCFG_OP_RESTORE :
2818 			cbdata.sc_flags |= SCI_OP_RESTORE;
2819 			break;
2820 		default :
2821 			uu_die(gettext("lscf_import_instance_pgs : "
2822 			    "Unknown op stored in the instance entity\n"));
2823 		}
2824 	}
2825 
2826 	if (uu_list_walk(iinst->sc_pgroups, entity_pgroup_import, &cbdata,
2827 	    UU_DEFAULT) != 0) {
2828 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
2829 			bad_error("uu_list_walk", uu_error());
2830 
2831 		return (cbdata.sc_err);
2832 	}
2833 
2834 	if ((flags & SCI_GENERALLAST) && cbdata.sc_general) {
2835 		cbdata.sc_flags = flags & (~SCI_GENERALLAST);
2836 		/*
2837 		 * If importing with the SCI_NOENABLED flag then
2838 		 * skip the delay, but if not then add the delay
2839 		 * of the enable property.
2840 		 */
2841 		if (!(cbdata.sc_flags & SCI_NOENABLED)) {
2842 			cbdata.sc_flags |= SCI_DELAYENABLE;
2843 		}
2844 
2845 		if (entity_pgroup_import(cbdata.sc_general, &cbdata)
2846 		    != UU_WALK_NEXT)
2847 			return (cbdata.sc_err);
2848 	}
2849 
2850 	return (0);
2851 }
2852 
2853 /*
2854  * Report the reasons why we can't upgrade pg2 to pg1.
2855  */
2856 static void
2857 report_pg_diffs(const pgroup_t *pg1, const pgroup_t *pg2, const char *fmri,
2858     int new)
2859 {
2860 	property_t *p1, *p2;
2861 
2862 	assert(strcmp(pg1->sc_pgroup_name, pg2->sc_pgroup_name) == 0);
2863 
2864 	if (!pg_attrs_equal(pg1, pg2, fmri, new))
2865 		return;
2866 
2867 	for (p1 = uu_list_first(pg1->sc_pgroup_props);
2868 	    p1 != NULL;
2869 	    p1 = uu_list_next(pg1->sc_pgroup_props, p1)) {
2870 		p2 = uu_list_find(pg2->sc_pgroup_props, p1, NULL, NULL);
2871 		if (p2 != NULL) {
2872 			(void) prop_equal(p1, p2, fmri, pg1->sc_pgroup_name,
2873 			    new);
2874 			continue;
2875 		}
2876 
2877 		if (new)
2878 			warn(gettext("Conflict upgrading %s (new property "
2879 			    "group \"%s\" is missing property \"%s\").\n"),
2880 			    fmri, pg1->sc_pgroup_name, p1->sc_property_name);
2881 		else
2882 			warn(gettext("Conflict upgrading %s (property "
2883 			    "\"%s/%s\" is missing).\n"), fmri,
2884 			    pg1->sc_pgroup_name, p1->sc_property_name);
2885 	}
2886 
2887 	/*
2888 	 * Since pg1 should be from the manifest, any properties in pg2 which
2889 	 * aren't in pg1 shouldn't be reported as conflicts.
2890 	 */
2891 }
2892 
2893 /*
2894  * Add transaction entries to tx which will upgrade cur's pg according to old
2895  * & new.
2896  *
2897  * Returns
2898  *   0 - success
2899  *   EINVAL - new has a property with an invalid name or value (message emitted)
2900  *   ENOMEM - out of memory
2901  */
2902 static int
2903 add_upgrade_entries(scf_transaction_t *tx, pgroup_t *old, pgroup_t *new,
2904     pgroup_t *cur, int speak, const char *fmri)
2905 {
2906 	property_t *p, *new_p, *cur_p;
2907 	scf_transaction_entry_t *e;
2908 	int r;
2909 	int is_general;
2910 	int is_protected;
2911 
2912 	if (uu_list_walk(new->sc_pgroup_props, clear_int,
2913 	    (void *)offsetof(property_t, sc_seen), UU_DEFAULT) != 0)
2914 		bad_error("uu_list_walk", uu_error());
2915 
2916 	is_general = strcmp(old->sc_pgroup_name, SCF_PG_GENERAL) == 0;
2917 
2918 	for (p = uu_list_first(old->sc_pgroup_props);
2919 	    p != NULL;
2920 	    p = uu_list_next(old->sc_pgroup_props, p)) {
2921 		/* p is a property in the old property group. */
2922 
2923 		/* Protect live properties. */
2924 		is_protected = 0;
2925 		if (is_general) {
2926 			if (strcmp(p->sc_property_name, SCF_PROPERTY_ENABLED) ==
2927 			    0 ||
2928 			    strcmp(p->sc_property_name,
2929 			    SCF_PROPERTY_RESTARTER) == 0)
2930 				is_protected = 1;
2931 		}
2932 
2933 		/* Look for the same property in the new properties. */
2934 		new_p = uu_list_find(new->sc_pgroup_props, p, NULL, NULL);
2935 		if (new_p != NULL) {
2936 			new_p->sc_seen = 1;
2937 
2938 			/*
2939 			 * If the new property is the same as the old, don't do
2940 			 * anything (leave any user customizations).
2941 			 */
2942 			if (prop_equal(p, new_p, NULL, NULL, 0))
2943 				continue;
2944 
2945 			if (new_p->sc_property_override)
2946 				goto upgrade;
2947 		}
2948 
2949 		cur_p = uu_list_find(cur->sc_pgroup_props, p, NULL, NULL);
2950 		if (cur_p == NULL) {
2951 			/*
2952 			 * p has been deleted from the repository.  If we were
2953 			 * going to delete it anyway, do nothing.  Otherwise
2954 			 * report a conflict.
2955 			 */
2956 			if (new_p == NULL)
2957 				continue;
2958 
2959 			if (is_protected)
2960 				continue;
2961 
2962 			warn(gettext("Conflict upgrading %s "
2963 			    "(property \"%s/%s\" is missing).\n"), fmri,
2964 			    old->sc_pgroup_name, p->sc_property_name);
2965 			continue;
2966 		}
2967 
2968 		if (!prop_equal(p, cur_p, NULL, NULL, 0)) {
2969 			/*
2970 			 * Conflict.  Don't warn if the property is already the
2971 			 * way we want it, though.
2972 			 */
2973 			if (is_protected)
2974 				continue;
2975 
2976 			if (new_p == NULL)
2977 				(void) prop_equal(p, cur_p, fmri,
2978 				    old->sc_pgroup_name, 0);
2979 			else
2980 				(void) prop_equal(cur_p, new_p, fmri,
2981 				    old->sc_pgroup_name, 0);
2982 			continue;
2983 		}
2984 
2985 		if (is_protected) {
2986 			if (speak)
2987 				warn(gettext("%s: Refusing to upgrade "
2988 				    "\"%s/%s\" (live property).\n"), fmri,
2989 				    old->sc_pgroup_name, p->sc_property_name);
2990 			continue;
2991 		}
2992 
2993 upgrade:
2994 		/* p hasn't been customized in the repository.  Upgrade it. */
2995 		if (new_p == NULL) {
2996 			/* p was deleted.  Delete from cur if unchanged. */
2997 			if (speak)
2998 				warn(gettext(
2999 				    "%s: Deleting property \"%s/%s\".\n"),
3000 				    fmri, old->sc_pgroup_name,
3001 				    p->sc_property_name);
3002 
3003 			e = scf_entry_create(g_hndl);
3004 			if (e == NULL)
3005 				return (ENOMEM);
3006 
3007 			if (scf_transaction_property_delete(tx, e,
3008 			    p->sc_property_name) != 0) {
3009 				switch (scf_error()) {
3010 				case SCF_ERROR_DELETED:
3011 					scf_entry_destroy(e);
3012 					return (ECANCELED);
3013 
3014 				case SCF_ERROR_CONNECTION_BROKEN:
3015 					scf_entry_destroy(e);
3016 					return (ECONNABORTED);
3017 
3018 				case SCF_ERROR_NOT_FOUND:
3019 					/*
3020 					 * This can happen if cur is from the
3021 					 * running snapshot (and it differs
3022 					 * from the live properties).
3023 					 */
3024 					scf_entry_destroy(e);
3025 					break;
3026 
3027 				case SCF_ERROR_HANDLE_MISMATCH:
3028 				case SCF_ERROR_NOT_BOUND:
3029 				case SCF_ERROR_NOT_SET:
3030 				case SCF_ERROR_INVALID_ARGUMENT:
3031 				default:
3032 					bad_error(
3033 					    "scf_transaction_property_delete",
3034 					    scf_error());
3035 				}
3036 			}
3037 		} else {
3038 			scf_callback_t ctx;
3039 
3040 			if (speak)
3041 				warn(gettext(
3042 				    "%s: Upgrading property \"%s/%s\".\n"),
3043 				    fmri, old->sc_pgroup_name,
3044 				    p->sc_property_name);
3045 
3046 			ctx.sc_handle = g_hndl;
3047 			ctx.sc_trans = tx;
3048 			ctx.sc_flags = 0;
3049 
3050 			r = lscf_property_import(new_p, &ctx);
3051 			if (r != UU_WALK_NEXT) {
3052 				if (r != UU_WALK_ERROR)
3053 					bad_error("lscf_property_import", r);
3054 				return (EINVAL);
3055 			}
3056 		}
3057 	}
3058 
3059 	/* Go over the properties which were added. */
3060 	for (new_p = uu_list_first(new->sc_pgroup_props);
3061 	    new_p != NULL;
3062 	    new_p = uu_list_next(new->sc_pgroup_props, new_p)) {
3063 		if (new_p->sc_seen)
3064 			continue;
3065 
3066 		/* This is a new property. */
3067 		cur_p = uu_list_find(cur->sc_pgroup_props, new_p, NULL, NULL);
3068 		if (cur_p == NULL) {
3069 			scf_callback_t ctx;
3070 
3071 			ctx.sc_handle = g_hndl;
3072 			ctx.sc_trans = tx;
3073 			ctx.sc_flags = 0;
3074 
3075 			r = lscf_property_import(new_p, &ctx);
3076 			if (r != UU_WALK_NEXT) {
3077 				if (r != UU_WALK_ERROR)
3078 					bad_error("lscf_property_import", r);
3079 				return (EINVAL);
3080 			}
3081 			continue;
3082 		}
3083 
3084 		/*
3085 		 * Report a conflict if the new property differs from the
3086 		 * current one.  Unless it's general/enabled, since that's
3087 		 * never in the last-import snapshot.
3088 		 */
3089 		if (strcmp(new_p->sc_property_name, SCF_PROPERTY_ENABLED) ==
3090 		    0 &&
3091 		    strcmp(cur->sc_pgroup_name, SCF_PG_GENERAL) == 0)
3092 			continue;
3093 
3094 		(void) prop_equal(cur_p, new_p, fmri, old->sc_pgroup_name, 1);
3095 	}
3096 
3097 	return (0);
3098 }
3099 
3100 /*
3101  * Upgrade pg according to old & new.
3102  *
3103  * Returns
3104  *   0 - success
3105  *   ECONNABORTED - repository connection broken
3106  *   ENOMEM - out of memory
3107  *   ENOSPC - svc.configd is out of resources
3108  *   ECANCELED - pg was deleted
3109  *   EPERM - couldn't modify pg (permission denied)
3110  *   EROFS - couldn't modify pg (backend read-only)
3111  *   EACCES - couldn't modify pg (backend access denied)
3112  *   EINVAL - new has a property with invalid name or value (error printed)
3113  *   EBUSY - pg changed unexpectedly
3114  */
3115 static int
3116 upgrade_pg(scf_propertygroup_t *pg, pgroup_t *cur, pgroup_t *old,
3117     pgroup_t *new, int speak, const char *fmri)
3118 {
3119 	int r;
3120 
3121 	if (scf_transaction_start(imp_tx, pg) != 0) {
3122 		switch (scf_error()) {
3123 		case SCF_ERROR_CONNECTION_BROKEN:
3124 		case SCF_ERROR_DELETED:
3125 		case SCF_ERROR_PERMISSION_DENIED:
3126 		case SCF_ERROR_BACKEND_READONLY:
3127 		case SCF_ERROR_BACKEND_ACCESS:
3128 			return (scferror2errno(scf_error()));
3129 
3130 		case SCF_ERROR_HANDLE_MISMATCH:
3131 		case SCF_ERROR_IN_USE:
3132 		case SCF_ERROR_NOT_BOUND:
3133 		case SCF_ERROR_NOT_SET:
3134 		default:
3135 			bad_error("scf_transaction_start", scf_error());
3136 		}
3137 	}
3138 
3139 	r = add_upgrade_entries(imp_tx, old, new, cur, speak, fmri);
3140 	switch (r) {
3141 	case 0:
3142 		break;
3143 
3144 	case EINVAL:
3145 	case ENOMEM:
3146 		scf_transaction_destroy_children(imp_tx);
3147 		return (r);
3148 
3149 	default:
3150 		bad_error("add_upgrade_entries", r);
3151 	}
3152 
3153 	r = scf_transaction_commit(imp_tx);
3154 
3155 	scf_transaction_destroy_children(imp_tx);
3156 
3157 	switch (r) {
3158 	case 1:
3159 		break;
3160 
3161 	case 0:
3162 		return (EBUSY);
3163 
3164 	case -1:
3165 		switch (scf_error()) {
3166 		case SCF_ERROR_CONNECTION_BROKEN:
3167 		case SCF_ERROR_NO_RESOURCES:
3168 		case SCF_ERROR_PERMISSION_DENIED:
3169 		case SCF_ERROR_BACKEND_READONLY:
3170 		case SCF_ERROR_BACKEND_ACCESS:
3171 		case SCF_ERROR_DELETED:
3172 			return (scferror2errno(scf_error()));
3173 
3174 		case SCF_ERROR_NOT_BOUND:
3175 		case SCF_ERROR_INVALID_ARGUMENT:
3176 		case SCF_ERROR_NOT_SET:
3177 		default:
3178 			bad_error("scf_transaction_commit", scf_error());
3179 		}
3180 
3181 	default:
3182 		bad_error("scf_transaction_commit", r);
3183 	}
3184 
3185 	return (0);
3186 }
3187 
3188 /*
3189  * Compares two entity FMRIs.  Returns
3190  *
3191  *   1 - equal
3192  *   0 - not equal
3193  *   -1 - f1 is invalid or not an entity
3194  *   -2 - f2 is invalid or not an entity
3195  */
3196 static int
3197 fmri_equal(const char *f1, const char *f2)
3198 {
3199 	int r;
3200 	const char *s1, *i1, *pg1;
3201 	const char *s2, *i2, *pg2;
3202 
3203 	if (strlcpy(imp_fe1, f1, max_scf_fmri_len + 1) >= max_scf_fmri_len + 1)
3204 		return (-1);
3205 	if (scf_parse_svc_fmri(imp_fe1, NULL, &s1, &i1, &pg1, NULL) != 0)
3206 		return (-1);
3207 
3208 	if (s1 == NULL || pg1 != NULL)
3209 		return (-1);
3210 
3211 	if (strlcpy(imp_fe2, f2, max_scf_fmri_len + 1) >= max_scf_fmri_len + 1)
3212 		return (-2);
3213 	if (scf_parse_svc_fmri(imp_fe2, NULL, &s2, &i2, &pg2, NULL) != 0)
3214 		return (-2);
3215 
3216 	if (s2 == NULL || pg2 != NULL)
3217 		return (-2);
3218 
3219 	r = strcmp(s1, s2);
3220 	if (r != 0)
3221 		return (0);
3222 
3223 	if (i1 == NULL && i2 == NULL)
3224 		return (1);
3225 
3226 	if (i1 == NULL || i2 == NULL)
3227 		return (0);
3228 
3229 	return (strcmp(i1, i2) == 0);
3230 }
3231 
3232 /*
3233  * Import a dependent by creating a dependency property group in the dependent
3234  * entity.  If lcbdata->sc_trans is set, assume it's been started on the
3235  * dependents pg, and add an entry to create a new property for this
3236  * dependent.  Uses sc_handle, sc_trans, and sc_fmri in lcbdata.
3237  *
3238  * On success, returns UU_WALK_NEXT.  On error, returns UU_WALK_ERROR and sets
3239  * lcbdata->sc_err to
3240  *   ECONNABORTED - repository connection broken
3241  *   ENOMEM - out of memory
3242  *   ENOSPC - configd is out of resources
3243  *   EINVAL - target is invalid (error printed)
3244  *	    - target is not an entity (error printed)
3245  *	    - dependent has invalid name (error printed)
3246  *	    - invalid property name (error printed)
3247  *	    - invalid value (error printed)
3248  *	    - scope of target does not exist (error printed)
3249  *   EPERM - couldn't create target (permission denied) (error printed)
3250  *	   - couldn't create dependency pg (permission denied) (error printed)
3251  *	   - couldn't modify dependency pg (permission denied) (error printed)
3252  *   EROFS - couldn't create target (repository read-only)
3253  *	   - couldn't create dependency pg (repository read-only)
3254  *   EACCES - couldn't create target (backend access denied)
3255  *	    - couldn't create dependency pg (backend access denied)
3256  *   ECANCELED - sc_trans's pg was deleted
3257  *   EALREADY - property for dependent already exists in sc_trans's pg
3258  *   EEXIST - dependency pg already exists in target (error printed)
3259  *   EBUSY - target deleted (error printed)
3260  *         - property group changed during import (error printed)
3261  */
3262 static int
3263 lscf_dependent_import(void *a1, void *pvt)
3264 {
3265 	pgroup_t *pgrp = a1;
3266 	scf_callback_t *lcbdata = pvt;
3267 
3268 	int isservice;
3269 	int ret;
3270 	scf_transaction_entry_t *e;
3271 	scf_value_t *val;
3272 	scf_callback_t dependent_cbdata;
3273 	scf_error_t scfe;
3274 
3275 	/*
3276 	 * Decode the FMRI into dependent_cbdata->sc_parent.  Do it here so if
3277 	 * it's invalid, we fail before modifying the repository.
3278 	 */
3279 	scfe = fmri_to_entity(lcbdata->sc_handle, pgrp->sc_pgroup_fmri,
3280 	    &dependent_cbdata.sc_parent, &isservice);
3281 	switch (scfe) {
3282 	case SCF_ERROR_NONE:
3283 		break;
3284 
3285 	case SCF_ERROR_NO_MEMORY:
3286 		return (stash_scferror_err(lcbdata, scfe));
3287 
3288 	case SCF_ERROR_INVALID_ARGUMENT:
3289 		semerr(gettext("The FMRI for the \"%s\" dependent is "
3290 		    "invalid.\n"), pgrp->sc_pgroup_name);
3291 		return (stash_scferror_err(lcbdata, scfe));
3292 
3293 	case SCF_ERROR_CONSTRAINT_VIOLATED:
3294 		semerr(gettext("The FMRI \"%s\" for the \"%s\" dependent "
3295 		    "specifies neither a service nor an instance.\n"),
3296 		    pgrp->sc_pgroup_fmri, pgrp->sc_pgroup_name);
3297 		return (stash_scferror_err(lcbdata, scfe));
3298 
3299 	case SCF_ERROR_NOT_FOUND:
3300 		scfe = create_entity(lcbdata->sc_handle, pgrp->sc_pgroup_fmri,
3301 		    &dependent_cbdata.sc_parent, &isservice);
3302 		switch (scfe) {
3303 		case SCF_ERROR_NONE:
3304 			break;
3305 
3306 		case SCF_ERROR_NO_MEMORY:
3307 		case SCF_ERROR_BACKEND_READONLY:
3308 		case SCF_ERROR_BACKEND_ACCESS:
3309 			return (stash_scferror_err(lcbdata, scfe));
3310 
3311 		case SCF_ERROR_NOT_FOUND:
3312 			semerr(gettext("The scope in FMRI \"%s\" for the "
3313 			    "\"%s\" dependent does not exist.\n"),
3314 			    pgrp->sc_pgroup_fmri, pgrp->sc_pgroup_name);
3315 			lcbdata->sc_err = EINVAL;
3316 			return (UU_WALK_ERROR);
3317 
3318 		case SCF_ERROR_PERMISSION_DENIED:
3319 			warn(gettext(
3320 			    "Could not create %s (permission denied).\n"),
3321 			    pgrp->sc_pgroup_fmri);
3322 			return (stash_scferror_err(lcbdata, scfe));
3323 
3324 		case SCF_ERROR_INVALID_ARGUMENT:
3325 		case SCF_ERROR_CONSTRAINT_VIOLATED:
3326 		default:
3327 			bad_error("create_entity", scfe);
3328 		}
3329 		break;
3330 
3331 	default:
3332 		bad_error("fmri_to_entity", scfe);
3333 	}
3334 
3335 	if (lcbdata->sc_trans != NULL) {
3336 		e = scf_entry_create(lcbdata->sc_handle);
3337 		if (e == NULL) {
3338 			if (scf_error() != SCF_ERROR_NO_MEMORY)
3339 				bad_error("scf_entry_create", scf_error());
3340 
3341 			entity_destroy(dependent_cbdata.sc_parent, isservice);
3342 			return (stash_scferror(lcbdata));
3343 		}
3344 
3345 		if (scf_transaction_property_new(lcbdata->sc_trans, e,
3346 		    pgrp->sc_pgroup_name, SCF_TYPE_FMRI) != 0) {
3347 			switch (scf_error()) {
3348 			case SCF_ERROR_INVALID_ARGUMENT:
3349 				warn(gettext("Dependent of %s has invalid name "
3350 				    "\"%s\".\n"), pgrp->sc_parent->sc_fmri,
3351 				    pgrp->sc_pgroup_name);
3352 				/* FALLTHROUGH */
3353 
3354 			case SCF_ERROR_DELETED:
3355 			case SCF_ERROR_CONNECTION_BROKEN:
3356 				scf_entry_destroy(e);
3357 				entity_destroy(dependent_cbdata.sc_parent,
3358 				    isservice);
3359 				return (stash_scferror(lcbdata));
3360 
3361 			case SCF_ERROR_EXISTS:
3362 				scf_entry_destroy(e);
3363 				entity_destroy(dependent_cbdata.sc_parent,
3364 				    isservice);
3365 				lcbdata->sc_err = EALREADY;
3366 				return (UU_WALK_ERROR);
3367 
3368 			case SCF_ERROR_NOT_BOUND:
3369 			case SCF_ERROR_HANDLE_MISMATCH:
3370 			case SCF_ERROR_NOT_SET:
3371 			default:
3372 				bad_error("scf_transaction_property_new",
3373 				    scf_error());
3374 			}
3375 		}
3376 
3377 		val = scf_value_create(lcbdata->sc_handle);
3378 		if (val == NULL) {
3379 			if (scf_error() != SCF_ERROR_NO_MEMORY)
3380 				bad_error("scf_value_create", scf_error());
3381 
3382 			entity_destroy(dependent_cbdata.sc_parent, isservice);
3383 			return (stash_scferror(lcbdata));
3384 		}
3385 
3386 		if (scf_value_set_from_string(val, SCF_TYPE_FMRI,
3387 		    pgrp->sc_pgroup_fmri) != 0)
3388 			/* invalid should have been caught above */
3389 			bad_error("scf_value_set_from_string", scf_error());
3390 
3391 		if (scf_entry_add_value(e, val) != 0)
3392 			bad_error("scf_entry_add_value", scf_error());
3393 	}
3394 
3395 	/* Add the property group to the target entity. */
3396 
3397 	dependent_cbdata.sc_handle = lcbdata->sc_handle;
3398 	dependent_cbdata.sc_flags = lcbdata->sc_flags;
3399 	dependent_cbdata.sc_source_fmri = lcbdata->sc_source_fmri;
3400 	dependent_cbdata.sc_target_fmri = pgrp->sc_pgroup_fmri;
3401 
3402 	ret = entity_pgroup_import(pgrp, &dependent_cbdata);
3403 
3404 	entity_destroy(dependent_cbdata.sc_parent, isservice);
3405 
3406 	if (ret == UU_WALK_NEXT)
3407 		return (ret);
3408 
3409 	if (ret != UU_WALK_ERROR)
3410 		bad_error("entity_pgroup_import", ret);
3411 
3412 	switch (dependent_cbdata.sc_err) {
3413 	case ECANCELED:
3414 		warn(gettext("%s deleted unexpectedly.\n"),
3415 		    pgrp->sc_pgroup_fmri);
3416 		lcbdata->sc_err = EBUSY;
3417 		break;
3418 
3419 	case EEXIST:
3420 		warn(gettext("Could not create \"%s\" dependency in %s "
3421 		    "(already exists).\n"), pgrp->sc_pgroup_name,
3422 		    pgrp->sc_pgroup_fmri);
3423 		/* FALLTHROUGH */
3424 
3425 	default:
3426 		lcbdata->sc_err = dependent_cbdata.sc_err;
3427 	}
3428 
3429 	return (UU_WALK_ERROR);
3430 }
3431 
3432 static int upgrade_dependent(const scf_property_t *, const entity_t *,
3433     const scf_snaplevel_t *, scf_transaction_t *);
3434 static int handle_dependent_conflict(const entity_t *, const scf_property_t *,
3435     const pgroup_t *);
3436 
3437 /*
3438  * Upgrade uncustomized dependents of ent to those specified in ient.  Read
3439  * the current dependent targets from running (the snaplevel of a running
3440  * snapshot which corresponds to ient) if not NULL (ent, an scf_service_t * or
3441  * scf_instance_t * according to ient, otherwise).  Draw the ancestral
3442  * dependent targets and dependency properties from li_dpts_pg (the
3443  * "dependents" property group in snpl) and snpl (the snaplevel which
3444  * corresponds to ent in a last-import snapshot).  If li_dpts_pg is NULL, then
3445  * snpl doesn't have a "dependents" property group, and any dependents in ient
3446  * are new.
3447  *
3448  * Returns
3449  *   0 - success
3450  *   ECONNABORTED - repository connection broken
3451  *   ENOMEM - out of memory
3452  *   ENOSPC - configd is out of resources
3453  *   ECANCELED - ent was deleted
3454  *   ENODEV - the entity containing li_dpts_pg was deleted
3455  *   EPERM - could not modify dependents pg (permission denied) (error printed)
3456  *	   - couldn't upgrade dependent (permission denied) (error printed)
3457  *	   - couldn't create dependent (permission denied) (error printed)
3458  *   EROFS - could not modify dependents pg (repository read-only)
3459  *	   - couldn't upgrade dependent (repository read-only)
3460  *	   - couldn't create dependent (repository read-only)
3461  *   EACCES - could not modify dependents pg (backend access denied)
3462  *	    - could not upgrade dependent (backend access denied)
3463  *	    - could not create dependent (backend access denied)
3464  *   EBUSY - "dependents" pg of ent added, changed, or deleted (error printed)
3465  *	   - dependent target deleted (error printed)
3466  *	   - dependent pg changed (error printed)
3467  *   EINVAL - new dependent is invalid (error printed)
3468  *   EBADF - snpl is corrupt (error printed)
3469  *	   - snpl has corrupt pg (error printed)
3470  *	   - dependency pg in target is corrupt (error printed)
3471  *	   - target has corrupt snapshot (error printed)
3472  *   EEXIST - dependency pg already existed in target service (error printed)
3473  */
3474 static int
3475 upgrade_dependents(const scf_propertygroup_t *li_dpts_pg,
3476     const scf_snaplevel_t *snpl, const entity_t *ient,
3477     const scf_snaplevel_t *running, void *ent)
3478 {
3479 	pgroup_t *new_dpt_pgroup;
3480 	scf_callback_t cbdata;
3481 	int r, unseen, tx_started = 0;
3482 	int have_cur_depts;
3483 
3484 	const char * const dependents = "dependents";
3485 
3486 	const int issvc = (ient->sc_etype == SVCCFG_SERVICE_OBJECT);
3487 
3488 	if (li_dpts_pg == NULL && uu_list_numnodes(ient->sc_dependents) == 0)
3489 		/* Nothing to do. */
3490 		return (0);
3491 
3492 	/* Fetch the current version of the "dependents" property group. */
3493 	have_cur_depts = 1;
3494 	if (entity_get_pg(ent, issvc, dependents, ud_cur_depts_pg) != 0) {
3495 		switch (scf_error()) {
3496 		case SCF_ERROR_NOT_FOUND:
3497 			break;
3498 
3499 		case SCF_ERROR_DELETED:
3500 		case SCF_ERROR_CONNECTION_BROKEN:
3501 			return (scferror2errno(scf_error()));
3502 
3503 		case SCF_ERROR_NOT_SET:
3504 		case SCF_ERROR_INVALID_ARGUMENT:
3505 		case SCF_ERROR_HANDLE_MISMATCH:
3506 		case SCF_ERROR_NOT_BOUND:
3507 		default:
3508 			bad_error("entity_get_pg", scf_error());
3509 		}
3510 
3511 		have_cur_depts = 0;
3512 	}
3513 
3514 	/* Fetch the running version of the "dependents" property group. */
3515 	ud_run_dpts_pg_set = 0;
3516 	if (running != NULL)
3517 		r = scf_snaplevel_get_pg(running, dependents, ud_run_dpts_pg);
3518 	else
3519 		r = entity_get_pg(ent, issvc, dependents, ud_run_dpts_pg);
3520 	if (r == 0) {
3521 		ud_run_dpts_pg_set = 1;
3522 	} else {
3523 		switch (scf_error()) {
3524 		case SCF_ERROR_NOT_FOUND:
3525 			break;
3526 
3527 		case SCF_ERROR_DELETED:
3528 		case SCF_ERROR_CONNECTION_BROKEN:
3529 			return (scferror2errno(scf_error()));
3530 
3531 		case SCF_ERROR_NOT_SET:
3532 		case SCF_ERROR_INVALID_ARGUMENT:
3533 		case SCF_ERROR_HANDLE_MISMATCH:
3534 		case SCF_ERROR_NOT_BOUND:
3535 		default:
3536 			bad_error(running ? "scf_snaplevel_get_pg" :
3537 			    "entity_get_pg", scf_error());
3538 		}
3539 	}
3540 
3541 	/*
3542 	 * Clear the seen fields of the dependents, so we can tell which ones
3543 	 * are new.
3544 	 */
3545 	if (uu_list_walk(ient->sc_dependents, clear_int,
3546 	    (void *)offsetof(pgroup_t, sc_pgroup_seen), UU_DEFAULT) != 0)
3547 		bad_error("uu_list_walk", uu_error());
3548 
3549 	if (li_dpts_pg != NULL) {
3550 		/*
3551 		 * Each property in li_dpts_pg represents a dependent tag in
3552 		 * the old manifest.  For each, call upgrade_dependent(),
3553 		 * which will change ud_cur_depts_pg or dependencies in other
3554 		 * services as appropriate.  Note (a) that changes to
3555 		 * ud_cur_depts_pg are accumulated in ud_tx so they can all be
3556 		 * made en masse, and (b) it's ok if the entity doesn't have
3557 		 * a current version of the "dependents" property group,
3558 		 * because we'll just consider all dependents as customized
3559 		 * (by being deleted).
3560 		 */
3561 
3562 		if (scf_iter_pg_properties(ud_iter, li_dpts_pg) != 0) {
3563 			switch (scf_error()) {
3564 			case SCF_ERROR_DELETED:
3565 				return (ENODEV);
3566 
3567 			case SCF_ERROR_CONNECTION_BROKEN:
3568 				return (ECONNABORTED);
3569 
3570 			case SCF_ERROR_HANDLE_MISMATCH:
3571 			case SCF_ERROR_NOT_BOUND:
3572 			case SCF_ERROR_NOT_SET:
3573 			default:
3574 				bad_error("scf_iter_pg_properties",
3575 				    scf_error());
3576 			}
3577 		}
3578 
3579 		if (have_cur_depts &&
3580 		    scf_transaction_start(ud_tx, ud_cur_depts_pg) != 0) {
3581 			switch (scf_error()) {
3582 			case SCF_ERROR_BACKEND_ACCESS:
3583 			case SCF_ERROR_BACKEND_READONLY:
3584 			case SCF_ERROR_CONNECTION_BROKEN:
3585 				return (scferror2errno(scf_error()));
3586 
3587 			case SCF_ERROR_DELETED:
3588 				warn(emsg_pg_deleted, ient->sc_fmri,
3589 				    dependents);
3590 				return (EBUSY);
3591 
3592 			case SCF_ERROR_PERMISSION_DENIED:
3593 				warn(emsg_pg_mod_perm, dependents,
3594 				    ient->sc_fmri);
3595 				return (scferror2errno(scf_error()));
3596 
3597 			case SCF_ERROR_HANDLE_MISMATCH:
3598 			case SCF_ERROR_IN_USE:
3599 			case SCF_ERROR_NOT_BOUND:
3600 			case SCF_ERROR_NOT_SET:
3601 			default:
3602 				bad_error("scf_transaction_start", scf_error());
3603 			}
3604 		}
3605 		tx_started = have_cur_depts;
3606 
3607 		for (;;) {
3608 			r = scf_iter_next_property(ud_iter, ud_dpt_prop);
3609 			if (r == 0)
3610 				break;
3611 			if (r == 1) {
3612 				r = upgrade_dependent(ud_dpt_prop, ient, snpl,
3613 				    tx_started ? ud_tx : NULL);
3614 				switch (r) {
3615 				case 0:
3616 					continue;
3617 
3618 				case ECONNABORTED:
3619 				case ENOMEM:
3620 				case ENOSPC:
3621 				case EBADF:
3622 				case EBUSY:
3623 				case EINVAL:
3624 				case EPERM:
3625 				case EROFS:
3626 				case EACCES:
3627 				case EEXIST:
3628 					break;
3629 
3630 				case ECANCELED:
3631 					r = ENODEV;
3632 					break;
3633 
3634 				default:
3635 					bad_error("upgrade_dependent", r);
3636 				}
3637 
3638 				if (tx_started)
3639 					scf_transaction_destroy_children(ud_tx);
3640 				return (r);
3641 			}
3642 			if (r != -1)
3643 				bad_error("scf_iter_next_property", r);
3644 
3645 			switch (scf_error()) {
3646 			case SCF_ERROR_DELETED:
3647 				r = ENODEV;
3648 				break;
3649 
3650 			case SCF_ERROR_CONNECTION_BROKEN:
3651 				r = ECONNABORTED;
3652 				break;
3653 
3654 			case SCF_ERROR_NOT_SET:
3655 			case SCF_ERROR_INVALID_ARGUMENT:
3656 			case SCF_ERROR_NOT_BOUND:
3657 			case SCF_ERROR_HANDLE_MISMATCH:
3658 			default:
3659 				bad_error("scf_iter_next_property",
3660 				    scf_error());
3661 			}
3662 
3663 			if (tx_started)
3664 				scf_transaction_destroy_children(ud_tx);
3665 			return (r);
3666 		}
3667 	}
3668 
3669 	/* import unseen dependents */
3670 	unseen = 0;
3671 	for (new_dpt_pgroup = uu_list_first(ient->sc_dependents);
3672 	    new_dpt_pgroup != NULL;
3673 	    new_dpt_pgroup = uu_list_next(ient->sc_dependents,
3674 	    new_dpt_pgroup)) {
3675 		if (!new_dpt_pgroup->sc_pgroup_seen) {
3676 			unseen = 1;
3677 			break;
3678 		}
3679 	}
3680 
3681 	/* If there are none, exit early. */
3682 	if (unseen == 0)
3683 		goto commit;
3684 
3685 	/* Set up for lscf_dependent_import() */
3686 	cbdata.sc_handle = g_hndl;
3687 	cbdata.sc_parent = ent;
3688 	cbdata.sc_service = issvc;
3689 	cbdata.sc_flags = 0;
3690 
3691 	if (!have_cur_depts) {
3692 		/*
3693 		 * We have new dependents to import, so we need a "dependents"
3694 		 * property group.
3695 		 */
3696 		if (issvc)
3697 			r = scf_service_add_pg(ent, dependents,
3698 			    SCF_GROUP_FRAMEWORK, 0, ud_cur_depts_pg);
3699 		else
3700 			r = scf_instance_add_pg(ent, dependents,
3701 			    SCF_GROUP_FRAMEWORK, 0, ud_cur_depts_pg);
3702 		if (r != 0) {
3703 			switch (scf_error()) {
3704 			case SCF_ERROR_DELETED:
3705 			case SCF_ERROR_CONNECTION_BROKEN:
3706 			case SCF_ERROR_BACKEND_READONLY:
3707 			case SCF_ERROR_BACKEND_ACCESS:
3708 			case SCF_ERROR_NO_RESOURCES:
3709 				return (scferror2errno(scf_error()));
3710 
3711 			case SCF_ERROR_EXISTS:
3712 				warn(emsg_pg_added, ient->sc_fmri, dependents);
3713 				return (EBUSY);
3714 
3715 			case SCF_ERROR_PERMISSION_DENIED:
3716 				warn(emsg_pg_add_perm, dependents,
3717 				    ient->sc_fmri);
3718 				return (scferror2errno(scf_error()));
3719 
3720 			case SCF_ERROR_NOT_BOUND:
3721 			case SCF_ERROR_HANDLE_MISMATCH:
3722 			case SCF_ERROR_INVALID_ARGUMENT:
3723 			case SCF_ERROR_NOT_SET:
3724 			default:
3725 				bad_error("scf_service_add_pg", scf_error());
3726 			}
3727 		}
3728 	}
3729 
3730 	cbdata.sc_trans = ud_tx;
3731 
3732 	if (!tx_started && scf_transaction_start(ud_tx, ud_cur_depts_pg) != 0) {
3733 		switch (scf_error()) {
3734 		case SCF_ERROR_CONNECTION_BROKEN:
3735 		case SCF_ERROR_BACKEND_ACCESS:
3736 		case SCF_ERROR_BACKEND_READONLY:
3737 			return (scferror2errno(scf_error()));
3738 
3739 		case SCF_ERROR_DELETED:
3740 			warn(emsg_pg_deleted, ient->sc_fmri, dependents);
3741 			return (EBUSY);
3742 
3743 		case SCF_ERROR_PERMISSION_DENIED:
3744 			warn(emsg_pg_mod_perm, dependents, ient->sc_fmri);
3745 			return (scferror2errno(scf_error()));
3746 
3747 		case SCF_ERROR_HANDLE_MISMATCH:
3748 		case SCF_ERROR_IN_USE:
3749 		case SCF_ERROR_NOT_BOUND:
3750 		case SCF_ERROR_NOT_SET:
3751 		default:
3752 			bad_error("scf_transaction_start", scf_error());
3753 		}
3754 	}
3755 	tx_started = 1;
3756 
3757 	for (new_dpt_pgroup = uu_list_first(ient->sc_dependents);
3758 	    new_dpt_pgroup != NULL;
3759 	    new_dpt_pgroup = uu_list_next(ient->sc_dependents,
3760 	    new_dpt_pgroup)) {
3761 		if (new_dpt_pgroup->sc_pgroup_seen)
3762 			continue;
3763 
3764 		if (ud_run_dpts_pg_set) {
3765 			/*
3766 			 * If the dependent is already there, then we have
3767 			 * a conflict.
3768 			 */
3769 			if (scf_pg_get_property(ud_run_dpts_pg,
3770 			    new_dpt_pgroup->sc_pgroup_name, ud_prop) == 0) {
3771 				r = handle_dependent_conflict(ient, ud_prop,
3772 				    new_dpt_pgroup);
3773 				switch (r) {
3774 				case 0:
3775 					continue;
3776 
3777 				case ECONNABORTED:
3778 				case ENOMEM:
3779 				case EBUSY:
3780 				case EBADF:
3781 				case EINVAL:
3782 					scf_transaction_destroy_children(ud_tx);
3783 					return (r);
3784 
3785 				default:
3786 					bad_error("handle_dependent_conflict",
3787 					    r);
3788 				}
3789 			} else {
3790 				switch (scf_error()) {
3791 				case SCF_ERROR_NOT_FOUND:
3792 					break;
3793 
3794 				case SCF_ERROR_INVALID_ARGUMENT:
3795 					warn(emsg_fmri_invalid_pg_name,
3796 					    ient->sc_fmri,
3797 					    new_dpt_pgroup->sc_pgroup_name);
3798 					scf_transaction_destroy_children(ud_tx);
3799 					return (EINVAL);
3800 
3801 				case SCF_ERROR_DELETED:
3802 					warn(emsg_pg_deleted, ient->sc_fmri,
3803 					    new_dpt_pgroup->sc_pgroup_name);
3804 					scf_transaction_destroy_children(ud_tx);
3805 					return (EBUSY);
3806 
3807 				case SCF_ERROR_CONNECTION_BROKEN:
3808 					scf_transaction_destroy_children(ud_tx);
3809 					return (ECONNABORTED);
3810 
3811 				case SCF_ERROR_NOT_BOUND:
3812 				case SCF_ERROR_HANDLE_MISMATCH:
3813 				case SCF_ERROR_NOT_SET:
3814 				default:
3815 					bad_error("scf_pg_get_property",
3816 					    scf_error());
3817 				}
3818 			}
3819 		}
3820 
3821 		r = lscf_dependent_import(new_dpt_pgroup, &cbdata);
3822 		if (r != UU_WALK_NEXT) {
3823 			if (r != UU_WALK_ERROR)
3824 				bad_error("lscf_dependent_import", r);
3825 
3826 			if (cbdata.sc_err == EALREADY) {
3827 				/* Collisions were handled preemptively. */
3828 				bad_error("lscf_dependent_import",
3829 				    cbdata.sc_err);
3830 			}
3831 
3832 			scf_transaction_destroy_children(ud_tx);
3833 			return (cbdata.sc_err);
3834 		}
3835 	}
3836 
3837 commit:
3838 	if (!tx_started)
3839 		return (0);
3840 
3841 	r = scf_transaction_commit(ud_tx);
3842 
3843 	scf_transaction_destroy_children(ud_tx);
3844 
3845 	switch (r) {
3846 	case 1:
3847 		return (0);
3848 
3849 	case 0:
3850 		warn(emsg_pg_changed, ient->sc_fmri, dependents);
3851 		return (EBUSY);
3852 
3853 	case -1:
3854 		break;
3855 
3856 	default:
3857 		bad_error("scf_transaction_commit", r);
3858 	}
3859 
3860 	switch (scf_error()) {
3861 	case SCF_ERROR_CONNECTION_BROKEN:
3862 	case SCF_ERROR_BACKEND_READONLY:
3863 	case SCF_ERROR_BACKEND_ACCESS:
3864 	case SCF_ERROR_NO_RESOURCES:
3865 		return (scferror2errno(scf_error()));
3866 
3867 	case SCF_ERROR_DELETED:
3868 		warn(emsg_pg_deleted, ient->sc_fmri, dependents);
3869 		return (EBUSY);
3870 
3871 	case SCF_ERROR_PERMISSION_DENIED:
3872 		warn(emsg_pg_mod_perm, dependents, ient->sc_fmri);
3873 		return (scferror2errno(scf_error()));
3874 
3875 	case SCF_ERROR_NOT_BOUND:
3876 	case SCF_ERROR_INVALID_ARGUMENT:
3877 	case SCF_ERROR_NOT_SET:
3878 	default:
3879 		bad_error("scf_transaction_destroy", scf_error());
3880 		/* NOTREACHED */
3881 	}
3882 }
3883 
3884 /*
3885  * Used to add the manifests to the list of currently supported manifests.
3886  * We can modify the existing manifest list removing entries if the files
3887  * don't exist.
3888  *
3889  * Get the old list and the new file name
3890  * If the new file name is in the list return
3891  * If not then add the file to the list.
3892  * As we process the list check to see if the files in the old list exist
3893  * 	if not then remove the file from the list.
3894  * Commit the list of manifest file names.
3895  *
3896  */
3897 static int
3898 upgrade_manifestfiles(pgroup_t *pg, const entity_t *ient,
3899     const scf_snaplevel_t *running, void *ent)
3900 {
3901 	scf_propertygroup_t *ud_mfsts_pg = NULL;
3902 	scf_property_t *ud_prop = NULL;
3903 	scf_iter_t *ud_prop_iter;
3904 	scf_value_t *fname_value;
3905 	scf_callback_t cbdata;
3906 	pgroup_t *mfst_pgroup;
3907 	property_t *mfst_prop;
3908 	property_t *old_prop;
3909 	char *pname;
3910 	char *fval;
3911 	char *old_pname;
3912 	char *old_fval;
3913 	int no_upgrade_pg;
3914 	int mfst_seen;
3915 	int r;
3916 
3917 	const int issvc = (ient->sc_etype == SVCCFG_SERVICE_OBJECT);
3918 
3919 	/*
3920 	 * This should always be the service base on the code
3921 	 * path, and the fact that the manifests pg is a service
3922 	 * level property group only.
3923 	 */
3924 	ud_mfsts_pg = scf_pg_create(g_hndl);
3925 	ud_prop = scf_property_create(g_hndl);
3926 	ud_prop_iter = scf_iter_create(g_hndl);
3927 	fname_value = scf_value_create(g_hndl);
3928 
3929 	/* Fetch the "manifests" property group */
3930 	no_upgrade_pg = 0;
3931 	r = entity_get_pg(ent, issvc, SCF_PG_MANIFESTFILES,
3932 	    ud_mfsts_pg);
3933 	if (r != 0) {
3934 		switch (scf_error()) {
3935 		case SCF_ERROR_NOT_FOUND:
3936 			no_upgrade_pg = 1;
3937 			break;
3938 
3939 		case SCF_ERROR_DELETED:
3940 		case SCF_ERROR_CONNECTION_BROKEN:
3941 			return (scferror2errno(scf_error()));
3942 
3943 		case SCF_ERROR_NOT_SET:
3944 		case SCF_ERROR_INVALID_ARGUMENT:
3945 		case SCF_ERROR_HANDLE_MISMATCH:
3946 		case SCF_ERROR_NOT_BOUND:
3947 		default:
3948 			bad_error(running ? "scf_snaplevel_get_pg" :
3949 			    "entity_get_pg", scf_error());
3950 		}
3951 	}
3952 
3953 	if (no_upgrade_pg) {
3954 		cbdata.sc_handle = g_hndl;
3955 		cbdata.sc_parent = ent;
3956 		cbdata.sc_service = issvc;
3957 		cbdata.sc_flags = SCI_FORCE;
3958 		cbdata.sc_source_fmri = ient->sc_fmri;
3959 		cbdata.sc_target_fmri = ient->sc_fmri;
3960 
3961 		if (entity_pgroup_import(pg, &cbdata) != UU_WALK_NEXT)
3962 			return (cbdata.sc_err);
3963 
3964 		return (0);
3965 	}
3966 
3967 	/* Fetch the new manifests property group */
3968 	for (mfst_pgroup = uu_list_first(ient->sc_pgroups);
3969 	    mfst_pgroup != NULL;
3970 	    mfst_pgroup = uu_list_next(ient->sc_pgroups, mfst_pgroup)) {
3971 		if (strcmp(mfst_pgroup->sc_pgroup_name,
3972 		    SCF_PG_MANIFESTFILES) == 0)
3973 			break;
3974 	}
3975 
3976 	if ((r = scf_iter_pg_properties(ud_prop_iter, ud_mfsts_pg)) !=
3977 	    SCF_SUCCESS)
3978 		return (-1);
3979 
3980 	if ((pname = malloc(MAXPATHLEN)) == NULL)
3981 		return (ENOMEM);
3982 	if ((fval = malloc(MAXPATHLEN)) == NULL) {
3983 		free(pname);
3984 		return (ENOMEM);
3985 	}
3986 
3987 	while ((r = scf_iter_next_property(ud_prop_iter, ud_prop)) == 1) {
3988 		mfst_seen = 0;
3989 		if (scf_property_get_name(ud_prop, pname, MAXPATHLEN) < 0)
3990 			continue;
3991 
3992 		for (mfst_prop = uu_list_first(mfst_pgroup->sc_pgroup_props);
3993 		    mfst_prop != NULL;
3994 		    mfst_prop = uu_list_next(mfst_pgroup->sc_pgroup_props,
3995 		    mfst_prop)) {
3996 			if (strcmp(mfst_prop->sc_property_name, pname) == 0) {
3997 				mfst_seen = 1;
3998 			}
3999 		}
4000 
4001 		/*
4002 		 * If the manifest is not seen then add it to the new mfst
4003 		 * property list to get proccessed into the repo.
4004 		 */
4005 		if (mfst_seen == 0) {
4006 			/*
4007 			 * If we cannot get the value then there is no
4008 			 * reason to attempt to attach the value to
4009 			 * the property group
4010 			 */
4011 			if (prop_get_val(ud_prop, fname_value) == 0 &&
4012 			    scf_value_get_astring(fname_value, fval,
4013 			    MAXPATHLEN) != -1)  {
4014 				old_pname = safe_strdup(pname);
4015 				old_fval = safe_strdup(fval);
4016 				old_prop = internal_property_create(old_pname,
4017 				    SCF_TYPE_ASTRING, 1, old_fval);
4018 
4019 				/*
4020 				 * Already checked to see if the property exists
4021 				 * in the group, and it does not.
4022 				 */
4023 				(void) internal_attach_property(mfst_pgroup,
4024 				    old_prop);
4025 			}
4026 		}
4027 	}
4028 	free(pname);
4029 	free(fval);
4030 
4031 	cbdata.sc_handle = g_hndl;
4032 	cbdata.sc_parent = ent;
4033 	cbdata.sc_service = issvc;
4034 	cbdata.sc_flags = SCI_FORCE;
4035 	cbdata.sc_source_fmri = ient->sc_fmri;
4036 	cbdata.sc_target_fmri = ient->sc_fmri;
4037 
4038 	if (entity_pgroup_import(mfst_pgroup, &cbdata) != UU_WALK_NEXT)
4039 		return (cbdata.sc_err);
4040 
4041 	return (r);
4042 }
4043 
4044 /*
4045  * prop is taken to be a property in the "dependents" property group of snpl,
4046  * which is taken to be the snaplevel of a last-import snapshot corresponding
4047  * to ient.  If prop is a valid dependents property, upgrade the dependent it
4048  * represents according to the repository & ient.  If ud_run_dpts_pg_set is
4049  * true, then ud_run_dpts_pg is taken to be the "dependents" property group
4050  * of the entity ient represents (possibly in the running snapshot).  If it
4051  * needs to be changed, an entry will be added to tx, if not NULL.
4052  *
4053  * Returns
4054  *   0 - success
4055  *   ECONNABORTED - repository connection broken
4056  *   ENOMEM - out of memory
4057  *   ENOSPC - configd was out of resources
4058  *   ECANCELED - snpl's entity was deleted
4059  *   EINVAL - dependent target is invalid (error printed)
4060  *	    - dependent is invalid (error printed)
4061  *   EBADF - snpl is corrupt (error printed)
4062  *	   - snpl has corrupt pg (error printed)
4063  *	   - dependency pg in target is corrupt (error printed)
4064  *	   - running snapshot in dependent is missing snaplevel (error printed)
4065  *   EPERM - couldn't delete dependency pg (permission denied) (error printed)
4066  *	   - couldn't create dependent (permission denied) (error printed)
4067  *	   - couldn't modify dependent pg (permission denied) (error printed)
4068  *   EROFS - couldn't delete dependency pg (repository read-only)
4069  *	   - couldn't create dependent (repository read-only)
4070  *   EACCES - couldn't delete dependency pg (backend access denied)
4071  *	    - couldn't create dependent (backend access denied)
4072  *   EBUSY - ud_run_dpts_pg was deleted (error printed)
4073  *	   - tx's pg was deleted (error printed)
4074  *	   - dependent pg was changed or deleted (error printed)
4075  *   EEXIST - dependency pg already exists in new target (error printed)
4076  */
4077 static int
4078 upgrade_dependent(const scf_property_t *prop, const entity_t *ient,
4079     const scf_snaplevel_t *snpl, scf_transaction_t *tx)
4080 {
4081 	pgroup_t pgrp;
4082 	scf_type_t ty;
4083 	pgroup_t *new_dpt_pgroup;
4084 	pgroup_t *old_dpt_pgroup = NULL;
4085 	pgroup_t *current_pg;
4086 	pgroup_t *dpt;
4087 	scf_callback_t cbdata;
4088 	int tissvc;
4089 	void *target_ent;
4090 	scf_error_t serr;
4091 	int r;
4092 	scf_transaction_entry_t *ent;
4093 
4094 	const char * const cf_inval = gettext("Conflict upgrading %s "
4095 	    "(dependent \"%s\" has invalid dependents property).\n");
4096 	const char * const cf_missing = gettext("Conflict upgrading %s "
4097 	    "(dependent \"%s\" is missing).\n");
4098 	const char * const cf_newdpg = gettext("Conflict upgrading %s "
4099 	    "(dependent \"%s\" has new dependency property group).\n");
4100 	const char * const cf_newtarg = gettext("Conflict upgrading %s "
4101 	    "(dependent \"%s\" has new target).\n");
4102 	const char * const li_corrupt =
4103 	    gettext("%s: \"last-import\" snapshot is corrupt.\n");
4104 	const char * const upgrading =
4105 	    gettext("%s: Upgrading dependent \"%s\".\n");
4106 	const char * const r_no_lvl = gettext("%s: \"running\" snapshot is "
4107 	    "corrupt (missing snaplevel).\n");
4108 
4109 	if (scf_property_type(prop, &ty) != 0) {
4110 		switch (scf_error()) {
4111 		case SCF_ERROR_DELETED:
4112 		case SCF_ERROR_CONNECTION_BROKEN:
4113 			return (scferror2errno(scf_error()));
4114 
4115 		case SCF_ERROR_NOT_BOUND:
4116 		case SCF_ERROR_NOT_SET:
4117 		default:
4118 			bad_error("scf_property_type", scf_error());
4119 		}
4120 	}
4121 
4122 	if (!(ty == SCF_TYPE_FMRI || ty == SCF_TYPE_ASTRING)) {
4123 		warn(li_corrupt, ient->sc_fmri);
4124 		return (EBADF);
4125 	}
4126 
4127 	/*
4128 	 * prop represents a dependent in the old manifest.  It is named after
4129 	 * the dependent.
4130 	 */
4131 	if (scf_property_get_name(prop, ud_name, max_scf_name_len + 1) < 0) {
4132 		switch (scf_error()) {
4133 		case SCF_ERROR_DELETED:
4134 		case SCF_ERROR_CONNECTION_BROKEN:
4135 			return (scferror2errno(scf_error()));
4136 
4137 		case SCF_ERROR_NOT_BOUND:
4138 		case SCF_ERROR_NOT_SET:
4139 		default:
4140 			bad_error("scf_property_get_name", scf_error());
4141 		}
4142 	}
4143 
4144 	/* See if it's in the new manifest. */
4145 	pgrp.sc_pgroup_name = ud_name;
4146 	new_dpt_pgroup =
4147 	    uu_list_find(ient->sc_dependents, &pgrp, NULL, UU_DEFAULT);
4148 
4149 	/* If it's not, delete it... if it hasn't been customized. */
4150 	if (new_dpt_pgroup == NULL) {
4151 		if (!ud_run_dpts_pg_set)
4152 			return (0);
4153 
4154 		if (scf_property_get_value(prop, ud_val) != 0) {
4155 			switch (scf_error()) {
4156 			case SCF_ERROR_NOT_FOUND:
4157 			case SCF_ERROR_CONSTRAINT_VIOLATED:
4158 				warn(li_corrupt, ient->sc_fmri);
4159 				return (EBADF);
4160 
4161 			case SCF_ERROR_DELETED:
4162 			case SCF_ERROR_CONNECTION_BROKEN:
4163 				return (scferror2errno(scf_error()));
4164 
4165 			case SCF_ERROR_HANDLE_MISMATCH:
4166 			case SCF_ERROR_NOT_BOUND:
4167 			case SCF_ERROR_NOT_SET:
4168 			case SCF_ERROR_PERMISSION_DENIED:
4169 			default:
4170 				bad_error("scf_property_get_value",
4171 				    scf_error());
4172 			}
4173 		}
4174 
4175 		if (scf_value_get_as_string(ud_val, ud_oldtarg,
4176 		    max_scf_value_len + 1) < 0)
4177 			bad_error("scf_value_get_as_string", scf_error());
4178 
4179 		if (scf_pg_get_property(ud_run_dpts_pg, ud_name, ud_prop) !=
4180 		    0) {
4181 			switch (scf_error()) {
4182 			case SCF_ERROR_NOT_FOUND:
4183 				return (0);
4184 
4185 			case SCF_ERROR_CONNECTION_BROKEN:
4186 				return (scferror2errno(scf_error()));
4187 
4188 			case SCF_ERROR_DELETED:
4189 				warn(emsg_pg_deleted, ient->sc_fmri,
4190 				    "dependents");
4191 				return (EBUSY);
4192 
4193 			case SCF_ERROR_INVALID_ARGUMENT:
4194 			case SCF_ERROR_NOT_BOUND:
4195 			case SCF_ERROR_HANDLE_MISMATCH:
4196 			case SCF_ERROR_NOT_SET:
4197 			default:
4198 				bad_error("scf_pg_get_property", scf_error());
4199 			}
4200 		}
4201 		if (scf_property_get_value(ud_prop, ud_val) != 0) {
4202 			switch (scf_error()) {
4203 			case SCF_ERROR_NOT_FOUND:
4204 			case SCF_ERROR_CONSTRAINT_VIOLATED:
4205 				warn(cf_inval, ient->sc_fmri, ud_name);
4206 				return (0);
4207 
4208 			case SCF_ERROR_DELETED:
4209 			case SCF_ERROR_CONNECTION_BROKEN:
4210 				return (scferror2errno(scf_error()));
4211 
4212 			case SCF_ERROR_HANDLE_MISMATCH:
4213 			case SCF_ERROR_NOT_BOUND:
4214 			case SCF_ERROR_NOT_SET:
4215 			case SCF_ERROR_PERMISSION_DENIED:
4216 			default:
4217 				bad_error("scf_property_get_value",
4218 				    scf_error());
4219 			}
4220 		}
4221 
4222 		ty = scf_value_type(ud_val);
4223 		assert(ty != SCF_TYPE_INVALID);
4224 		if (!(ty == SCF_TYPE_FMRI || ty == SCF_TYPE_ASTRING)) {
4225 			warn(cf_inval, ient->sc_fmri, ud_name);
4226 			return (0);
4227 		}
4228 
4229 		if (scf_value_get_as_string(ud_val, ud_ctarg,
4230 		    max_scf_value_len + 1) < 0)
4231 			bad_error("scf_value_get_as_string", scf_error());
4232 
4233 		r = fmri_equal(ud_ctarg, ud_oldtarg);
4234 		switch (r) {
4235 		case 1:
4236 			break;
4237 
4238 		case 0:
4239 		case -1:	/* warn? */
4240 			warn(cf_newtarg, ient->sc_fmri, ud_name);
4241 			return (0);
4242 
4243 		case -2:
4244 			warn(li_corrupt, ient->sc_fmri);
4245 			return (EBADF);
4246 
4247 		default:
4248 			bad_error("fmri_equal", r);
4249 		}
4250 
4251 		if (scf_snaplevel_get_pg(snpl, ud_name, ud_pg) != 0) {
4252 			switch (scf_error()) {
4253 			case SCF_ERROR_NOT_FOUND:
4254 				warn(li_corrupt, ient->sc_fmri);
4255 				return (EBADF);
4256 
4257 			case SCF_ERROR_DELETED:
4258 			case SCF_ERROR_CONNECTION_BROKEN:
4259 				return (scferror2errno(scf_error()));
4260 
4261 			case SCF_ERROR_NOT_BOUND:
4262 			case SCF_ERROR_HANDLE_MISMATCH:
4263 			case SCF_ERROR_INVALID_ARGUMENT:
4264 			case SCF_ERROR_NOT_SET:
4265 			default:
4266 				bad_error("scf_snaplevel_get_pg", scf_error());
4267 			}
4268 		}
4269 
4270 		r = load_pg(ud_pg, &old_dpt_pgroup, ient->sc_fmri,
4271 		    snap_lastimport);
4272 		switch (r) {
4273 		case 0:
4274 			break;
4275 
4276 		case ECANCELED:
4277 		case ECONNABORTED:
4278 		case ENOMEM:
4279 		case EBADF:
4280 			return (r);
4281 
4282 		case EACCES:
4283 		default:
4284 			bad_error("load_pg", r);
4285 		}
4286 
4287 		serr = fmri_to_entity(g_hndl, ud_ctarg, &target_ent, &tissvc);
4288 		switch (serr) {
4289 		case SCF_ERROR_NONE:
4290 			break;
4291 
4292 		case SCF_ERROR_NO_MEMORY:
4293 			internal_pgroup_free(old_dpt_pgroup);
4294 			return (ENOMEM);
4295 
4296 		case SCF_ERROR_NOT_FOUND:
4297 			internal_pgroup_free(old_dpt_pgroup);
4298 			goto delprop;
4299 
4300 		case SCF_ERROR_CONSTRAINT_VIOLATED:	/* caught above */
4301 		case SCF_ERROR_INVALID_ARGUMENT:	/* caught above */
4302 		default:
4303 			bad_error("fmri_to_entity", serr);
4304 		}
4305 
4306 		r = entity_get_running_pg(target_ent, tissvc, ud_name,
4307 		    ud_pg, ud_iter2, ud_inst, imp_snap, ud_snpl);
4308 		switch (r) {
4309 		case 0:
4310 			break;
4311 
4312 		case ECONNABORTED:
4313 			internal_pgroup_free(old_dpt_pgroup);
4314 			return (r);
4315 
4316 		case ECANCELED:
4317 		case ENOENT:
4318 			internal_pgroup_free(old_dpt_pgroup);
4319 			goto delprop;
4320 
4321 		case EBADF:
4322 			warn(r_no_lvl, ud_ctarg);
4323 			internal_pgroup_free(old_dpt_pgroup);
4324 			return (r);
4325 
4326 		case EINVAL:
4327 		default:
4328 			bad_error("entity_get_running_pg", r);
4329 		}
4330 
4331 		/* load it */
4332 		r = load_pg(ud_pg, &current_pg, ud_ctarg, NULL);
4333 		switch (r) {
4334 		case 0:
4335 			break;
4336 
4337 		case ECANCELED:
4338 			internal_pgroup_free(old_dpt_pgroup);
4339 			goto delprop;
4340 
4341 		case ECONNABORTED:
4342 		case ENOMEM:
4343 		case EBADF:
4344 			internal_pgroup_free(old_dpt_pgroup);
4345 			return (r);
4346 
4347 		case EACCES:
4348 		default:
4349 			bad_error("load_pg", r);
4350 		}
4351 
4352 		/* compare property groups */
4353 		if (!pg_equal(old_dpt_pgroup, current_pg)) {
4354 			warn(cf_newdpg, ient->sc_fmri, ud_name);
4355 			internal_pgroup_free(old_dpt_pgroup);
4356 			internal_pgroup_free(current_pg);
4357 			return (0);
4358 		}
4359 
4360 		internal_pgroup_free(old_dpt_pgroup);
4361 		internal_pgroup_free(current_pg);
4362 
4363 		if (g_verbose)
4364 			warn(gettext("%s: Deleting dependent \"%s\".\n"),
4365 			    ient->sc_fmri, ud_name);
4366 
4367 		if (entity_get_pg(target_ent, tissvc, ud_name, ud_pg) != 0) {
4368 			switch (scf_error()) {
4369 			case SCF_ERROR_NOT_FOUND:
4370 			case SCF_ERROR_DELETED:
4371 				internal_pgroup_free(old_dpt_pgroup);
4372 				goto delprop;
4373 
4374 			case SCF_ERROR_CONNECTION_BROKEN:
4375 				internal_pgroup_free(old_dpt_pgroup);
4376 				return (ECONNABORTED);
4377 
4378 			case SCF_ERROR_NOT_SET:
4379 			case SCF_ERROR_INVALID_ARGUMENT:
4380 			case SCF_ERROR_HANDLE_MISMATCH:
4381 			case SCF_ERROR_NOT_BOUND:
4382 			default:
4383 				bad_error("entity_get_pg", scf_error());
4384 			}
4385 		}
4386 
4387 		if (scf_pg_delete(ud_pg) != 0) {
4388 			switch (scf_error()) {
4389 			case SCF_ERROR_DELETED:
4390 				break;
4391 
4392 			case SCF_ERROR_CONNECTION_BROKEN:
4393 			case SCF_ERROR_BACKEND_READONLY:
4394 			case SCF_ERROR_BACKEND_ACCESS:
4395 				return (scferror2errno(scf_error()));
4396 
4397 			case SCF_ERROR_PERMISSION_DENIED:
4398 				warn(emsg_pg_del_perm, ud_name, ient->sc_fmri);
4399 				return (scferror2errno(scf_error()));
4400 
4401 			case SCF_ERROR_NOT_SET:
4402 			default:
4403 				bad_error("scf_pg_delete", scf_error());
4404 			}
4405 		}
4406 
4407 		/*
4408 		 * This service was changed, so it must be refreshed.  But
4409 		 * since it's not mentioned in the new manifest, we have to
4410 		 * record its FMRI here for use later.  We record the name
4411 		 * & the entity (via sc_parent) in case we need to print error
4412 		 * messages during the refresh.
4413 		 */
4414 		dpt = internal_pgroup_new();
4415 		if (dpt == NULL)
4416 			return (ENOMEM);
4417 		dpt->sc_pgroup_name = strdup(ud_name);
4418 		dpt->sc_pgroup_fmri = strdup(ud_ctarg);
4419 		if (dpt->sc_pgroup_name == NULL || dpt->sc_pgroup_fmri == NULL)
4420 			return (ENOMEM);
4421 		dpt->sc_parent = (entity_t *)ient;
4422 		if (uu_list_insert_after(imp_deleted_dpts, NULL, dpt) != 0)
4423 			uu_die(gettext("libuutil error: %s\n"),
4424 			    uu_strerror(uu_error()));
4425 
4426 delprop:
4427 		if (tx == NULL)
4428 			return (0);
4429 
4430 		ent = scf_entry_create(g_hndl);
4431 		if (ent == NULL)
4432 			return (ENOMEM);
4433 
4434 		if (scf_transaction_property_delete(tx, ent, ud_name) != 0) {
4435 			scf_entry_destroy(ent);
4436 			switch (scf_error()) {
4437 			case SCF_ERROR_DELETED:
4438 				warn(emsg_pg_deleted, ient->sc_fmri,
4439 				    "dependents");
4440 				return (EBUSY);
4441 
4442 			case SCF_ERROR_CONNECTION_BROKEN:
4443 				return (scferror2errno(scf_error()));
4444 
4445 			case SCF_ERROR_NOT_FOUND:
4446 				break;
4447 
4448 			case SCF_ERROR_HANDLE_MISMATCH:
4449 			case SCF_ERROR_NOT_BOUND:
4450 			case SCF_ERROR_INVALID_ARGUMENT:
4451 			case SCF_ERROR_NOT_SET:
4452 			default:
4453 				bad_error("scf_transaction_property_delete",
4454 				    scf_error());
4455 			}
4456 		}
4457 
4458 		return (0);
4459 	}
4460 
4461 	new_dpt_pgroup->sc_pgroup_seen = 1;
4462 
4463 	/*
4464 	 * Decide whether the dependent has changed in the manifest.
4465 	 */
4466 	/* Compare the target. */
4467 	if (scf_property_get_value(prop, ud_val) != 0) {
4468 		switch (scf_error()) {
4469 		case SCF_ERROR_NOT_FOUND:
4470 		case SCF_ERROR_CONSTRAINT_VIOLATED:
4471 			warn(li_corrupt, ient->sc_fmri);
4472 			return (EBADF);
4473 
4474 		case SCF_ERROR_DELETED:
4475 		case SCF_ERROR_CONNECTION_BROKEN:
4476 			return (scferror2errno(scf_error()));
4477 
4478 		case SCF_ERROR_HANDLE_MISMATCH:
4479 		case SCF_ERROR_NOT_BOUND:
4480 		case SCF_ERROR_NOT_SET:
4481 		case SCF_ERROR_PERMISSION_DENIED:
4482 		default:
4483 			bad_error("scf_property_get_value", scf_error());
4484 		}
4485 	}
4486 
4487 	if (scf_value_get_as_string(ud_val, ud_oldtarg, max_scf_value_len + 1) <
4488 	    0)
4489 		bad_error("scf_value_get_as_string", scf_error());
4490 
4491 	/*
4492 	 * If the fmri's are not equal then the old fmri will need to
4493 	 * be refreshed to ensure that the changes are properly updated
4494 	 * in that service.
4495 	 */
4496 	r = fmri_equal(ud_oldtarg, new_dpt_pgroup->sc_pgroup_fmri);
4497 	switch (r) {
4498 	case 0:
4499 		dpt = internal_pgroup_new();
4500 		if (dpt == NULL)
4501 			return (ENOMEM);
4502 		dpt->sc_pgroup_name = strdup(ud_name);
4503 		dpt->sc_pgroup_fmri = strdup(ud_oldtarg);
4504 		if (dpt->sc_pgroup_name == NULL || dpt->sc_pgroup_fmri == NULL)
4505 			return (ENOMEM);
4506 		dpt->sc_parent = (entity_t *)ient;
4507 		if (uu_list_insert_after(imp_deleted_dpts, NULL, dpt) != 0)
4508 			uu_die(gettext("libuutil error: %s\n"),
4509 			    uu_strerror(uu_error()));
4510 		break;
4511 
4512 	case 1:
4513 		/* Compare the dependency pgs. */
4514 		if (scf_snaplevel_get_pg(snpl, ud_name, ud_pg) != 0) {
4515 			switch (scf_error()) {
4516 			case SCF_ERROR_NOT_FOUND:
4517 				warn(li_corrupt, ient->sc_fmri);
4518 				return (EBADF);
4519 
4520 			case SCF_ERROR_DELETED:
4521 			case SCF_ERROR_CONNECTION_BROKEN:
4522 				return (scferror2errno(scf_error()));
4523 
4524 			case SCF_ERROR_NOT_BOUND:
4525 			case SCF_ERROR_HANDLE_MISMATCH:
4526 			case SCF_ERROR_INVALID_ARGUMENT:
4527 			case SCF_ERROR_NOT_SET:
4528 			default:
4529 				bad_error("scf_snaplevel_get_pg", scf_error());
4530 			}
4531 		}
4532 
4533 		r = load_pg(ud_pg, &old_dpt_pgroup, ient->sc_fmri,
4534 		    snap_lastimport);
4535 		switch (r) {
4536 		case 0:
4537 			break;
4538 
4539 		case ECANCELED:
4540 		case ECONNABORTED:
4541 		case ENOMEM:
4542 		case EBADF:
4543 			return (r);
4544 
4545 		case EACCES:
4546 		default:
4547 			bad_error("load_pg", r);
4548 		}
4549 
4550 		if (pg_equal(old_dpt_pgroup, new_dpt_pgroup)) {
4551 			/* no change, leave customizations */
4552 			internal_pgroup_free(old_dpt_pgroup);
4553 			return (0);
4554 		}
4555 		break;
4556 
4557 	case -1:
4558 		warn(li_corrupt, ient->sc_fmri);
4559 		return (EBADF);
4560 
4561 	case -2:
4562 		warn(gettext("Dependent \"%s\" has invalid target \"%s\".\n"),
4563 		    ud_name, new_dpt_pgroup->sc_pgroup_fmri);
4564 		return (EINVAL);
4565 
4566 	default:
4567 		bad_error("fmri_equal", r);
4568 	}
4569 
4570 	/*
4571 	 * The dependent has changed in the manifest.  Upgrade the current
4572 	 * properties if they haven't been customized.
4573 	 */
4574 
4575 	/*
4576 	 * If new_dpt_pgroup->sc_override, then act as though the property
4577 	 * group hasn't been customized.
4578 	 */
4579 	if (new_dpt_pgroup->sc_pgroup_override) {
4580 		(void) strcpy(ud_ctarg, ud_oldtarg);
4581 		goto nocust;
4582 	}
4583 
4584 	if (!ud_run_dpts_pg_set) {
4585 		warn(cf_missing, ient->sc_fmri, ud_name);
4586 		r = 0;
4587 		goto out;
4588 	} else if (scf_pg_get_property(ud_run_dpts_pg, ud_name, ud_prop) != 0) {
4589 		switch (scf_error()) {
4590 		case SCF_ERROR_NOT_FOUND:
4591 			warn(cf_missing, ient->sc_fmri, ud_name);
4592 			r = 0;
4593 			goto out;
4594 
4595 		case SCF_ERROR_CONNECTION_BROKEN:
4596 			r = scferror2errno(scf_error());
4597 			goto out;
4598 
4599 		case SCF_ERROR_DELETED:
4600 			warn(emsg_pg_deleted, ient->sc_fmri, "dependents");
4601 			r = EBUSY;
4602 			goto out;
4603 
4604 		case SCF_ERROR_INVALID_ARGUMENT:
4605 		case SCF_ERROR_NOT_BOUND:
4606 		case SCF_ERROR_HANDLE_MISMATCH:
4607 		case SCF_ERROR_NOT_SET:
4608 		default:
4609 			bad_error("scf_pg_get_property", scf_error());
4610 		}
4611 	}
4612 
4613 	if (scf_property_get_value(ud_prop, ud_val) != 0) {
4614 		switch (scf_error()) {
4615 		case SCF_ERROR_NOT_FOUND:
4616 		case SCF_ERROR_CONSTRAINT_VIOLATED:
4617 			warn(cf_inval, ient->sc_fmri, ud_name);
4618 			r = 0;
4619 			goto out;
4620 
4621 		case SCF_ERROR_DELETED:
4622 		case SCF_ERROR_CONNECTION_BROKEN:
4623 			r = scferror2errno(scf_error());
4624 			goto out;
4625 
4626 		case SCF_ERROR_HANDLE_MISMATCH:
4627 		case SCF_ERROR_NOT_BOUND:
4628 		case SCF_ERROR_NOT_SET:
4629 		case SCF_ERROR_PERMISSION_DENIED:
4630 		default:
4631 			bad_error("scf_property_get_value", scf_error());
4632 		}
4633 	}
4634 
4635 	ty = scf_value_type(ud_val);
4636 	assert(ty != SCF_TYPE_INVALID);
4637 	if (!(ty == SCF_TYPE_FMRI || ty == SCF_TYPE_ASTRING)) {
4638 		warn(cf_inval, ient->sc_fmri, ud_name);
4639 		r = 0;
4640 		goto out;
4641 	}
4642 	if (scf_value_get_as_string(ud_val, ud_ctarg, max_scf_value_len + 1) <
4643 	    0)
4644 		bad_error("scf_value_get_as_string", scf_error());
4645 
4646 	r = fmri_equal(ud_ctarg, ud_oldtarg);
4647 	if (r == -1) {
4648 		warn(cf_inval, ient->sc_fmri, ud_name);
4649 		r = 0;
4650 		goto out;
4651 	} else if (r == -2) {
4652 		warn(li_corrupt, ient->sc_fmri);
4653 		r = EBADF;
4654 		goto out;
4655 	} else if (r == 0) {
4656 		/*
4657 		 * Target has been changed.  Only abort now if it's been
4658 		 * changed to something other than what's in the manifest.
4659 		 */
4660 		r = fmri_equal(ud_ctarg, new_dpt_pgroup->sc_pgroup_fmri);
4661 		if (r == -1) {
4662 			warn(cf_inval, ient->sc_fmri, ud_name);
4663 			r = 0;
4664 			goto out;
4665 		} else if (r == 0) {
4666 			warn(cf_newtarg, ient->sc_fmri, ud_name);
4667 			r = 0;
4668 			goto out;
4669 		} else if (r != 1) {
4670 			/* invalid sc_pgroup_fmri caught above */
4671 			bad_error("fmri_equal", r);
4672 		}
4673 
4674 		/*
4675 		 * Fetch the current dependency pg.  If it's what the manifest
4676 		 * says, then no problem.
4677 		 */
4678 		serr = fmri_to_entity(g_hndl, ud_ctarg, &target_ent, &tissvc);
4679 		switch (serr) {
4680 		case SCF_ERROR_NONE:
4681 			break;
4682 
4683 		case SCF_ERROR_NOT_FOUND:
4684 			warn(cf_missing, ient->sc_fmri, ud_name);
4685 			r = 0;
4686 			goto out;
4687 
4688 		case SCF_ERROR_NO_MEMORY:
4689 			r = ENOMEM;
4690 			goto out;
4691 
4692 		case SCF_ERROR_CONSTRAINT_VIOLATED:
4693 		case SCF_ERROR_INVALID_ARGUMENT:
4694 		default:
4695 			bad_error("fmri_to_entity", serr);
4696 		}
4697 
4698 		r = entity_get_running_pg(target_ent, tissvc, ud_name,
4699 		    ud_pg, ud_iter2, ud_inst, imp_snap, ud_snpl);
4700 		switch (r) {
4701 		case 0:
4702 			break;
4703 
4704 		case ECONNABORTED:
4705 			goto out;
4706 
4707 		case ECANCELED:
4708 		case ENOENT:
4709 			warn(cf_missing, ient->sc_fmri, ud_name);
4710 			r = 0;
4711 			goto out;
4712 
4713 		case EBADF:
4714 			warn(r_no_lvl, ud_ctarg);
4715 			goto out;
4716 
4717 		case EINVAL:
4718 		default:
4719 			bad_error("entity_get_running_pg", r);
4720 		}
4721 
4722 		r = load_pg(ud_pg, &current_pg, ud_ctarg, NULL);
4723 		switch (r) {
4724 		case 0:
4725 			break;
4726 
4727 		case ECANCELED:
4728 			warn(cf_missing, ient->sc_fmri, ud_name);
4729 			r = 0;
4730 			goto out;
4731 
4732 		case ECONNABORTED:
4733 		case ENOMEM:
4734 		case EBADF:
4735 			goto out;
4736 
4737 		case EACCES:
4738 		default:
4739 			bad_error("load_pg", r);
4740 		}
4741 
4742 		if (!pg_equal(current_pg, new_dpt_pgroup))
4743 			warn(cf_newdpg, ient->sc_fmri, ud_name);
4744 		internal_pgroup_free(current_pg);
4745 		r = 0;
4746 		goto out;
4747 	} else if (r != 1) {
4748 		bad_error("fmri_equal", r);
4749 	}
4750 
4751 nocust:
4752 	/*
4753 	 * Target has not been customized.  Check the dependency property
4754 	 * group.
4755 	 */
4756 
4757 	if (old_dpt_pgroup == NULL) {
4758 		if (scf_snaplevel_get_pg(snpl, new_dpt_pgroup->sc_pgroup_name,
4759 		    ud_pg) != 0) {
4760 			switch (scf_error()) {
4761 			case SCF_ERROR_NOT_FOUND:
4762 				warn(li_corrupt, ient->sc_fmri);
4763 				return (EBADF);
4764 
4765 			case SCF_ERROR_DELETED:
4766 			case SCF_ERROR_CONNECTION_BROKEN:
4767 				return (scferror2errno(scf_error()));
4768 
4769 			case SCF_ERROR_NOT_BOUND:
4770 			case SCF_ERROR_HANDLE_MISMATCH:
4771 			case SCF_ERROR_INVALID_ARGUMENT:
4772 			case SCF_ERROR_NOT_SET:
4773 			default:
4774 				bad_error("scf_snaplevel_get_pg", scf_error());
4775 			}
4776 		}
4777 
4778 		r = load_pg(ud_pg, &old_dpt_pgroup, ient->sc_fmri,
4779 		    snap_lastimport);
4780 		switch (r) {
4781 		case 0:
4782 			break;
4783 
4784 		case ECANCELED:
4785 		case ECONNABORTED:
4786 		case ENOMEM:
4787 		case EBADF:
4788 			return (r);
4789 
4790 		case EACCES:
4791 		default:
4792 			bad_error("load_pg", r);
4793 		}
4794 	}
4795 	serr = fmri_to_entity(g_hndl, ud_ctarg, &target_ent, &tissvc);
4796 	switch (serr) {
4797 	case SCF_ERROR_NONE:
4798 		break;
4799 
4800 	case SCF_ERROR_NOT_FOUND:
4801 		warn(cf_missing, ient->sc_fmri, ud_name);
4802 		r = 0;
4803 		goto out;
4804 
4805 	case SCF_ERROR_NO_MEMORY:
4806 		r = ENOMEM;
4807 		goto out;
4808 
4809 	case SCF_ERROR_CONSTRAINT_VIOLATED:
4810 	case SCF_ERROR_INVALID_ARGUMENT:
4811 	default:
4812 		bad_error("fmri_to_entity", serr);
4813 	}
4814 
4815 	r = entity_get_running_pg(target_ent, tissvc, ud_name, ud_pg,
4816 	    ud_iter2, ud_inst, imp_snap, ud_snpl);
4817 	switch (r) {
4818 	case 0:
4819 		break;
4820 
4821 	case ECONNABORTED:
4822 		goto out;
4823 
4824 	case ECANCELED:
4825 	case ENOENT:
4826 		warn(cf_missing, ient->sc_fmri, ud_name);
4827 		r = 0;
4828 		goto out;
4829 
4830 	case EBADF:
4831 		warn(r_no_lvl, ud_ctarg);
4832 		goto out;
4833 
4834 	case EINVAL:
4835 	default:
4836 		bad_error("entity_get_running_pg", r);
4837 	}
4838 
4839 	r = load_pg(ud_pg, &current_pg, ud_ctarg, NULL);
4840 	switch (r) {
4841 	case 0:
4842 		break;
4843 
4844 	case ECANCELED:
4845 		warn(cf_missing, ient->sc_fmri, ud_name);
4846 		goto out;
4847 
4848 	case ECONNABORTED:
4849 	case ENOMEM:
4850 	case EBADF:
4851 		goto out;
4852 
4853 	case EACCES:
4854 	default:
4855 		bad_error("load_pg", r);
4856 	}
4857 
4858 	if (!pg_equal(current_pg, old_dpt_pgroup)) {
4859 		if (!pg_equal(current_pg, new_dpt_pgroup))
4860 			warn(cf_newdpg, ient->sc_fmri, ud_name);
4861 		internal_pgroup_free(current_pg);
4862 		r = 0;
4863 		goto out;
4864 	}
4865 
4866 	/* Uncustomized.  Upgrade. */
4867 
4868 	r = fmri_equal(new_dpt_pgroup->sc_pgroup_fmri, ud_oldtarg);
4869 	switch (r) {
4870 	case 1:
4871 		if (pg_equal(current_pg, new_dpt_pgroup)) {
4872 			/* Already upgraded. */
4873 			internal_pgroup_free(current_pg);
4874 			r = 0;
4875 			goto out;
4876 		}
4877 
4878 		internal_pgroup_free(current_pg);
4879 
4880 		/* upgrade current_pg */
4881 		if (entity_get_pg(target_ent, tissvc, ud_name, ud_pg) != 0) {
4882 			switch (scf_error()) {
4883 			case SCF_ERROR_CONNECTION_BROKEN:
4884 				r = scferror2errno(scf_error());
4885 				goto out;
4886 
4887 			case SCF_ERROR_DELETED:
4888 				warn(cf_missing, ient->sc_fmri, ud_name);
4889 				r = 0;
4890 				goto out;
4891 
4892 			case SCF_ERROR_NOT_FOUND:
4893 				break;
4894 
4895 			case SCF_ERROR_INVALID_ARGUMENT:
4896 			case SCF_ERROR_NOT_BOUND:
4897 			case SCF_ERROR_NOT_SET:
4898 			case SCF_ERROR_HANDLE_MISMATCH:
4899 			default:
4900 				bad_error("entity_get_pg", scf_error());
4901 			}
4902 
4903 			if (tissvc)
4904 				r = scf_service_add_pg(target_ent, ud_name,
4905 				    SCF_GROUP_DEPENDENCY, 0, ud_pg);
4906 			else
4907 				r = scf_instance_add_pg(target_ent, ud_name,
4908 				    SCF_GROUP_DEPENDENCY, 0, ud_pg);
4909 			if (r != 0) {
4910 				switch (scf_error()) {
4911 				case SCF_ERROR_CONNECTION_BROKEN:
4912 				case SCF_ERROR_NO_RESOURCES:
4913 				case SCF_ERROR_BACKEND_READONLY:
4914 				case SCF_ERROR_BACKEND_ACCESS:
4915 					r = scferror2errno(scf_error());
4916 					goto out;
4917 
4918 				case SCF_ERROR_DELETED:
4919 					warn(cf_missing, ient->sc_fmri,
4920 					    ud_name);
4921 					r = 0;
4922 					goto out;
4923 
4924 				case SCF_ERROR_PERMISSION_DENIED:
4925 					warn(emsg_pg_deleted, ud_ctarg,
4926 					    ud_name);
4927 					r = EPERM;
4928 					goto out;
4929 
4930 				case SCF_ERROR_EXISTS:
4931 					warn(emsg_pg_added, ud_ctarg, ud_name);
4932 					r = EBUSY;
4933 					goto out;
4934 
4935 				case SCF_ERROR_NOT_BOUND:
4936 				case SCF_ERROR_HANDLE_MISMATCH:
4937 				case SCF_ERROR_INVALID_ARGUMENT:
4938 				case SCF_ERROR_NOT_SET:
4939 				default:
4940 					bad_error("entity_add_pg", scf_error());
4941 				}
4942 			}
4943 		}
4944 
4945 		r = load_pg(ud_pg, &current_pg, ud_ctarg, NULL);
4946 		switch (r) {
4947 		case 0:
4948 			break;
4949 
4950 		case ECANCELED:
4951 			warn(cf_missing, ient->sc_fmri, ud_name);
4952 			goto out;
4953 
4954 		case ECONNABORTED:
4955 		case ENOMEM:
4956 		case EBADF:
4957 			goto out;
4958 
4959 		case EACCES:
4960 		default:
4961 			bad_error("load_pg", r);
4962 		}
4963 
4964 		if (g_verbose)
4965 			warn(upgrading, ient->sc_fmri, ud_name);
4966 
4967 		r = upgrade_pg(ud_pg, current_pg, old_dpt_pgroup,
4968 		    new_dpt_pgroup, 0, ient->sc_fmri);
4969 		switch (r) {
4970 		case 0:
4971 			break;
4972 
4973 		case ECANCELED:
4974 			warn(emsg_pg_deleted, ud_ctarg, ud_name);
4975 			r = EBUSY;
4976 			goto out;
4977 
4978 		case EPERM:
4979 			warn(emsg_pg_mod_perm, ud_name, ud_ctarg);
4980 			goto out;
4981 
4982 		case EBUSY:
4983 			warn(emsg_pg_changed, ud_ctarg, ud_name);
4984 			goto out;
4985 
4986 		case ECONNABORTED:
4987 		case ENOMEM:
4988 		case ENOSPC:
4989 		case EROFS:
4990 		case EACCES:
4991 		case EINVAL:
4992 			goto out;
4993 
4994 		default:
4995 			bad_error("upgrade_pg", r);
4996 		}
4997 		break;
4998 
4999 	case 0: {
5000 		scf_transaction_entry_t *ent;
5001 		scf_value_t *val;
5002 
5003 		internal_pgroup_free(current_pg);
5004 
5005 		/* delete old pg */
5006 		if (g_verbose)
5007 			warn(upgrading, ient->sc_fmri, ud_name);
5008 
5009 		if (entity_get_pg(target_ent, tissvc, ud_name, ud_pg) != 0) {
5010 			switch (scf_error()) {
5011 			case SCF_ERROR_CONNECTION_BROKEN:
5012 				r = scferror2errno(scf_error());
5013 				goto out;
5014 
5015 			case SCF_ERROR_DELETED:
5016 				warn(cf_missing, ient->sc_fmri, ud_name);
5017 				r = 0;
5018 				goto out;
5019 
5020 			case SCF_ERROR_NOT_FOUND:
5021 				break;
5022 
5023 			case SCF_ERROR_INVALID_ARGUMENT:
5024 			case SCF_ERROR_NOT_BOUND:
5025 			case SCF_ERROR_NOT_SET:
5026 			case SCF_ERROR_HANDLE_MISMATCH:
5027 			default:
5028 				bad_error("entity_get_pg", scf_error());
5029 			}
5030 		} else if (scf_pg_delete(ud_pg) != 0) {
5031 			switch (scf_error()) {
5032 			case SCF_ERROR_DELETED:
5033 				break;
5034 
5035 			case SCF_ERROR_CONNECTION_BROKEN:
5036 			case SCF_ERROR_BACKEND_READONLY:
5037 			case SCF_ERROR_BACKEND_ACCESS:
5038 				r = scferror2errno(scf_error());
5039 				goto out;
5040 
5041 			case SCF_ERROR_PERMISSION_DENIED:
5042 				warn(emsg_pg_del_perm, ud_name, ient->sc_fmri);
5043 				r = scferror2errno(scf_error());
5044 				goto out;
5045 
5046 			case SCF_ERROR_NOT_SET:
5047 			default:
5048 				bad_error("scf_pg_delete", scf_error());
5049 			}
5050 		}
5051 
5052 		/* import new one */
5053 		cbdata.sc_handle = g_hndl;
5054 		cbdata.sc_trans = NULL;		/* handled below */
5055 		cbdata.sc_flags = 0;
5056 
5057 		r = lscf_dependent_import(new_dpt_pgroup, &cbdata);
5058 		if (r != UU_WALK_NEXT) {
5059 			if (r != UU_WALK_ERROR)
5060 				bad_error("lscf_dependent_import", r);
5061 
5062 			r = cbdata.sc_err;
5063 			goto out;
5064 		}
5065 
5066 		if (tx == NULL)
5067 			break;
5068 
5069 		if ((ent = scf_entry_create(g_hndl)) == NULL ||
5070 		    (val = scf_value_create(g_hndl)) == NULL) {
5071 			if (scf_error() == SCF_ERROR_NO_MEMORY)
5072 				return (ENOMEM);
5073 
5074 			bad_error("scf_entry_create", scf_error());
5075 		}
5076 
5077 		if (scf_transaction_property_change_type(tx, ent, ud_name,
5078 		    SCF_TYPE_FMRI) != 0) {
5079 			switch (scf_error()) {
5080 			case SCF_ERROR_CONNECTION_BROKEN:
5081 				r = scferror2errno(scf_error());
5082 				goto out;
5083 
5084 			case SCF_ERROR_DELETED:
5085 				warn(emsg_pg_deleted, ient->sc_fmri,
5086 				    "dependents");
5087 				r = EBUSY;
5088 				goto out;
5089 
5090 			case SCF_ERROR_NOT_FOUND:
5091 				break;
5092 
5093 			case SCF_ERROR_NOT_BOUND:
5094 			case SCF_ERROR_HANDLE_MISMATCH:
5095 			case SCF_ERROR_INVALID_ARGUMENT:
5096 			case SCF_ERROR_NOT_SET:
5097 			default:
5098 				bad_error("scf_transaction_property_"
5099 				    "change_type", scf_error());
5100 			}
5101 
5102 			if (scf_transaction_property_new(tx, ent, ud_name,
5103 			    SCF_TYPE_FMRI) != 0) {
5104 				switch (scf_error()) {
5105 				case SCF_ERROR_CONNECTION_BROKEN:
5106 					r = scferror2errno(scf_error());
5107 					goto out;
5108 
5109 				case SCF_ERROR_DELETED:
5110 					warn(emsg_pg_deleted, ient->sc_fmri,
5111 					    "dependents");
5112 					r = EBUSY;
5113 					goto out;
5114 
5115 				case SCF_ERROR_EXISTS:
5116 					warn(emsg_pg_changed, ient->sc_fmri,
5117 					    "dependents");
5118 					r = EBUSY;
5119 					goto out;
5120 
5121 				case SCF_ERROR_INVALID_ARGUMENT:
5122 				case SCF_ERROR_HANDLE_MISMATCH:
5123 				case SCF_ERROR_NOT_BOUND:
5124 				case SCF_ERROR_NOT_SET:
5125 				default:
5126 					bad_error("scf_transaction_property_"
5127 					    "new", scf_error());
5128 				}
5129 			}
5130 		}
5131 
5132 		if (scf_value_set_from_string(val, SCF_TYPE_FMRI,
5133 		    new_dpt_pgroup->sc_pgroup_fmri) != 0)
5134 			/* invalid sc_pgroup_fmri caught above */
5135 			bad_error("scf_value_set_from_string",
5136 			    scf_error());
5137 
5138 		if (scf_entry_add_value(ent, val) != 0)
5139 			bad_error("scf_entry_add_value", scf_error());
5140 		break;
5141 	}
5142 
5143 	case -2:
5144 		warn(li_corrupt, ient->sc_fmri);
5145 		internal_pgroup_free(current_pg);
5146 		r = EBADF;
5147 		goto out;
5148 
5149 	case -1:
5150 	default:
5151 		/* invalid sc_pgroup_fmri caught above */
5152 		bad_error("fmri_equal", r);
5153 	}
5154 
5155 	r = 0;
5156 
5157 out:
5158 	if (old_dpt_pgroup != NULL)
5159 		internal_pgroup_free(old_dpt_pgroup);
5160 
5161 	return (r);
5162 }
5163 
5164 /*
5165  * new_dpt_pgroup was in the manifest but not the last-import snapshot, so we
5166  * would import it, except it seems to exist in the service anyway.  Compare
5167  * the existent dependent with the one we would import, and report any
5168  * differences (if there are none, be silent).  prop is the property which
5169  * represents the existent dependent (in the dependents property group) in the
5170  * entity corresponding to ient.
5171  *
5172  * Returns
5173  *   0 - success (Sort of.  At least, we can continue importing.)
5174  *   ECONNABORTED - repository connection broken
5175  *   EBUSY - ancestor of prop was deleted (error printed)
5176  *   ENOMEM - out of memory
5177  *   EBADF - corrupt property group (error printed)
5178  *   EINVAL - new_dpt_pgroup has invalid target (error printed)
5179  */
5180 static int
5181 handle_dependent_conflict(const entity_t * const ient,
5182     const scf_property_t * const prop, const pgroup_t * const new_dpt_pgroup)
5183 {
5184 	int r;
5185 	scf_type_t ty;
5186 	scf_error_t scfe;
5187 	void *tptr;
5188 	int tissvc;
5189 	pgroup_t *pgroup;
5190 
5191 	if (scf_property_get_value(prop, ud_val) != 0) {
5192 		switch (scf_error()) {
5193 		case SCF_ERROR_CONNECTION_BROKEN:
5194 			return (scferror2errno(scf_error()));
5195 
5196 		case SCF_ERROR_DELETED:
5197 			warn(emsg_pg_deleted, ient->sc_fmri,
5198 			    new_dpt_pgroup->sc_pgroup_name);
5199 			return (EBUSY);
5200 
5201 		case SCF_ERROR_CONSTRAINT_VIOLATED:
5202 		case SCF_ERROR_NOT_FOUND:
5203 			warn(gettext("Conflict upgrading %s (not importing "
5204 			    "dependent \"%s\" because it already exists.)  "
5205 			    "Warning: The \"%s/%2$s\" property has more or "
5206 			    "fewer than one value)).\n"), ient->sc_fmri,
5207 			    new_dpt_pgroup->sc_pgroup_name, "dependents");
5208 			return (0);
5209 
5210 		case SCF_ERROR_HANDLE_MISMATCH:
5211 		case SCF_ERROR_NOT_BOUND:
5212 		case SCF_ERROR_NOT_SET:
5213 		case SCF_ERROR_PERMISSION_DENIED:
5214 		default:
5215 			bad_error("scf_property_get_value",
5216 			    scf_error());
5217 		}
5218 	}
5219 
5220 	ty = scf_value_type(ud_val);
5221 	assert(ty != SCF_TYPE_INVALID);
5222 	if (!(ty == SCF_TYPE_FMRI || ty == SCF_TYPE_ASTRING)) {
5223 		warn(gettext("Conflict upgrading %s (not importing dependent "
5224 		    "\"%s\" because it already exists).  Warning: The "
5225 		    "\"%s/%s\" property has unexpected type \"%s\")).\n"),
5226 		    ient->sc_fmri, new_dpt_pgroup->sc_pgroup_name,
5227 		    scf_type_to_string(ty), "dependents");
5228 		return (0);
5229 	}
5230 
5231 	if (scf_value_get_as_string(ud_val, ud_ctarg, max_scf_value_len + 1) <
5232 	    0)
5233 		bad_error("scf_value_get_as_string", scf_error());
5234 
5235 	r = fmri_equal(ud_ctarg, new_dpt_pgroup->sc_pgroup_fmri);
5236 	switch (r) {
5237 	case 0:
5238 		warn(gettext("Conflict upgrading %s (not importing dependent "
5239 		    "\"%s\" (target \"%s\") because it already exists with "
5240 		    "target \"%s\").\n"), ient->sc_fmri,
5241 		    new_dpt_pgroup->sc_pgroup_name,
5242 		    new_dpt_pgroup->sc_pgroup_fmri, ud_ctarg);
5243 		return (0);
5244 
5245 	case 1:
5246 		break;
5247 
5248 	case -1:
5249 		warn(gettext("Conflict upgrading %s (not importing dependent "
5250 		    "\"%s\" because it already exists).  Warning: The current "
5251 		    "dependent's target (%s) is invalid.\n"), ient->sc_fmri,
5252 		    new_dpt_pgroup->sc_pgroup_name, ud_ctarg);
5253 		return (0);
5254 
5255 	case -2:
5256 		warn(gettext("Dependent \"%s\" of %s has invalid target "
5257 		    "\"%s\".\n"), new_dpt_pgroup->sc_pgroup_name, ient->sc_fmri,
5258 		    new_dpt_pgroup->sc_pgroup_fmri);
5259 		return (EINVAL);
5260 
5261 	default:
5262 		bad_error("fmri_equal", r);
5263 	}
5264 
5265 	/* compare dependency pgs in target */
5266 	scfe = fmri_to_entity(g_hndl, ud_ctarg, &tptr, &tissvc);
5267 	switch (scfe) {
5268 	case SCF_ERROR_NONE:
5269 		break;
5270 
5271 	case SCF_ERROR_NO_MEMORY:
5272 		return (ENOMEM);
5273 
5274 	case SCF_ERROR_NOT_FOUND:
5275 		warn(emsg_dpt_dangling, ient->sc_fmri,
5276 		    new_dpt_pgroup->sc_pgroup_name, ud_ctarg);
5277 		return (0);
5278 
5279 	case SCF_ERROR_CONSTRAINT_VIOLATED:
5280 	case SCF_ERROR_INVALID_ARGUMENT:
5281 	default:
5282 		bad_error("fmri_to_entity", scfe);
5283 	}
5284 
5285 	r = entity_get_running_pg(tptr, tissvc, new_dpt_pgroup->sc_pgroup_name,
5286 	    ud_pg, ud_iter, ud_inst, imp_snap, ud_snpl);
5287 	switch (r) {
5288 	case 0:
5289 		break;
5290 
5291 	case ECONNABORTED:
5292 		return (r);
5293 
5294 	case ECANCELED:
5295 		warn(emsg_dpt_dangling, ient->sc_fmri,
5296 		    new_dpt_pgroup->sc_pgroup_name, ud_ctarg);
5297 		return (0);
5298 
5299 	case EBADF:
5300 		if (tissvc)
5301 			warn(gettext("%s has an instance with a \"%s\" "
5302 			    "snapshot which is missing a snaplevel.\n"),
5303 			    ud_ctarg, "running");
5304 		else
5305 			warn(gettext("%s has a \"%s\" snapshot which is "
5306 			    "missing a snaplevel.\n"), ud_ctarg, "running");
5307 		/* FALLTHROUGH */
5308 
5309 	case ENOENT:
5310 		warn(emsg_dpt_no_dep, ient->sc_fmri,
5311 		    new_dpt_pgroup->sc_pgroup_name, ud_ctarg,
5312 		    new_dpt_pgroup->sc_pgroup_name);
5313 		return (0);
5314 
5315 	case EINVAL:
5316 	default:
5317 		bad_error("entity_get_running_pg", r);
5318 	}
5319 
5320 	pgroup = internal_pgroup_new();
5321 	if (pgroup == NULL)
5322 		return (ENOMEM);
5323 
5324 	r = load_pg(ud_pg, &pgroup, ud_ctarg, NULL);
5325 	switch (r) {
5326 	case 0:
5327 		break;
5328 
5329 	case ECONNABORTED:
5330 	case EBADF:
5331 	case ENOMEM:
5332 		internal_pgroup_free(pgroup);
5333 		return (r);
5334 
5335 	case ECANCELED:
5336 		warn(emsg_dpt_no_dep, ient->sc_fmri,
5337 		    new_dpt_pgroup->sc_pgroup_name, ud_ctarg,
5338 		    new_dpt_pgroup->sc_pgroup_name);
5339 		internal_pgroup_free(pgroup);
5340 		return (0);
5341 
5342 	case EACCES:
5343 	default:
5344 		bad_error("load_pg", r);
5345 	}
5346 
5347 	/* report differences */
5348 	report_pg_diffs(new_dpt_pgroup, pgroup, ud_ctarg, 1);
5349 	internal_pgroup_free(pgroup);
5350 	return (0);
5351 }
5352 
5353 /*
5354  * lipg is a property group in the last-import snapshot of ent, which is an
5355  * scf_service_t or an scf_instance_t (according to ient).  If lipg is not in
5356  * ient's pgroups, delete it from ent if it hasn't been customized.  If it is
5357  * in ents's property groups, compare and upgrade ent appropriately.
5358  *
5359  * Returns
5360  *   0 - success
5361  *   ECONNABORTED - repository connection broken
5362  *   ENOMEM - out of memory
5363  *   ENOSPC - configd is out of resources
5364  *   EINVAL - ient has invalid dependent (error printed)
5365  *	    - ient has invalid pgroup_t (error printed)
5366  *   ECANCELED - ent has been deleted
5367  *   ENODEV - entity containing lipg has been deleted
5368  *	    - entity containing running has been deleted
5369  *   EPERM - could not delete pg (permission denied) (error printed)
5370  *	   - couldn't upgrade dependents (permission denied) (error printed)
5371  *	   - couldn't import pg (permission denied) (error printed)
5372  *	   - couldn't upgrade pg (permission denied) (error printed)
5373  *   EROFS - could not delete pg (repository read-only)
5374  *	   - couldn't upgrade dependents (repository read-only)
5375  *	   - couldn't import pg (repository read-only)
5376  *	   - couldn't upgrade pg (repository read-only)
5377  *   EACCES - could not delete pg (backend access denied)
5378  *	    - couldn't upgrade dependents (backend access denied)
5379  *	    - couldn't import pg (backend access denied)
5380  *	    - couldn't upgrade pg (backend access denied)
5381  *	    - couldn't read property (backend access denied)
5382  *   EBUSY - property group was added (error printed)
5383  *	   - property group was deleted (error printed)
5384  *	   - property group changed (error printed)
5385  *	   - "dependents" pg was added, changed, or deleted (error printed)
5386  *	   - dependent target deleted (error printed)
5387  *	   - dependent pg changed (error printed)
5388  *   EBADF - imp_snpl is corrupt (error printed)
5389  *	   - ent has bad pg (error printed)
5390  *   EEXIST - dependent collision in target service (error printed)
5391  */
5392 static int
5393 process_old_pg(const scf_propertygroup_t *lipg, entity_t *ient, void *ent,
5394     const scf_snaplevel_t *running)
5395 {
5396 	int r;
5397 	pgroup_t *mpg, *lipg_i, *curpg_i, pgrp;
5398 	scf_callback_t cbdata;
5399 
5400 	const char * const cf_pg_missing =
5401 	    gettext("Conflict upgrading %s (property group %s is missing)\n");
5402 	const char * const deleting =
5403 	    gettext("%s: Deleting property group \"%s\".\n");
5404 
5405 	const int issvc = (ient->sc_etype == SVCCFG_SERVICE_OBJECT);
5406 
5407 	/* Skip dependent property groups. */
5408 	if (scf_pg_get_type(lipg, imp_str, imp_str_sz) < 0) {
5409 		switch (scf_error()) {
5410 		case SCF_ERROR_DELETED:
5411 			return (ENODEV);
5412 
5413 		case SCF_ERROR_CONNECTION_BROKEN:
5414 			return (ECONNABORTED);
5415 
5416 		case SCF_ERROR_NOT_SET:
5417 		case SCF_ERROR_NOT_BOUND:
5418 		default:
5419 			bad_error("scf_pg_get_type", scf_error());
5420 		}
5421 	}
5422 
5423 	if (strcmp(imp_str, SCF_GROUP_DEPENDENCY) == 0) {
5424 		if (scf_pg_get_property(lipg, "external", NULL) == 0)
5425 			return (0);
5426 
5427 		switch (scf_error()) {
5428 		case SCF_ERROR_NOT_FOUND:
5429 			break;
5430 
5431 		case SCF_ERROR_CONNECTION_BROKEN:
5432 			return (ECONNABORTED);
5433 
5434 		case SCF_ERROR_DELETED:
5435 			return (ENODEV);
5436 
5437 		case SCF_ERROR_INVALID_ARGUMENT:
5438 		case SCF_ERROR_NOT_BOUND:
5439 		case SCF_ERROR_HANDLE_MISMATCH:
5440 		case SCF_ERROR_NOT_SET:
5441 		default:
5442 			bad_error("scf_pg_get_property", scf_error());
5443 		}
5444 	}
5445 
5446 	/* lookup pg in new properties */
5447 	if (scf_pg_get_name(lipg, imp_str, imp_str_sz) < 0) {
5448 		switch (scf_error()) {
5449 		case SCF_ERROR_DELETED:
5450 			return (ENODEV);
5451 
5452 		case SCF_ERROR_CONNECTION_BROKEN:
5453 			return (ECONNABORTED);
5454 
5455 		case SCF_ERROR_NOT_SET:
5456 		case SCF_ERROR_NOT_BOUND:
5457 		default:
5458 			bad_error("scf_pg_get_name", scf_error());
5459 		}
5460 	}
5461 
5462 	pgrp.sc_pgroup_name = imp_str;
5463 	mpg = uu_list_find(ient->sc_pgroups, &pgrp, NULL, NULL);
5464 
5465 	if (mpg != NULL)
5466 		mpg->sc_pgroup_seen = 1;
5467 
5468 	/* Special handling for dependents */
5469 	if (strcmp(imp_str, "dependents") == 0)
5470 		return (upgrade_dependents(lipg, imp_snpl, ient, running, ent));
5471 
5472 	if (strcmp(imp_str, SCF_PG_MANIFESTFILES) == 0)
5473 		return (upgrade_manifestfiles(NULL, ient, running, ent));
5474 
5475 	if (mpg == NULL || mpg->sc_pgroup_delete) {
5476 		/* property group was deleted from manifest */
5477 		if (entity_get_pg(ent, issvc, imp_str, imp_pg2) != 0) {
5478 			switch (scf_error()) {
5479 			case SCF_ERROR_NOT_FOUND:
5480 				return (0);
5481 
5482 			case SCF_ERROR_DELETED:
5483 			case SCF_ERROR_CONNECTION_BROKEN:
5484 				return (scferror2errno(scf_error()));
5485 
5486 			case SCF_ERROR_INVALID_ARGUMENT:
5487 			case SCF_ERROR_HANDLE_MISMATCH:
5488 			case SCF_ERROR_NOT_BOUND:
5489 			case SCF_ERROR_NOT_SET:
5490 			default:
5491 				bad_error("entity_get_pg", scf_error());
5492 			}
5493 		}
5494 
5495 		if (mpg != NULL && mpg->sc_pgroup_delete) {
5496 			if (g_verbose)
5497 				warn(deleting, ient->sc_fmri, imp_str);
5498 			if (scf_pg_delete(imp_pg2) == 0)
5499 				return (0);
5500 
5501 			switch (scf_error()) {
5502 			case SCF_ERROR_DELETED:
5503 				return (0);
5504 
5505 			case SCF_ERROR_CONNECTION_BROKEN:
5506 			case SCF_ERROR_BACKEND_READONLY:
5507 			case SCF_ERROR_BACKEND_ACCESS:
5508 				return (scferror2errno(scf_error()));
5509 
5510 			case SCF_ERROR_PERMISSION_DENIED:
5511 				warn(emsg_pg_del_perm, imp_str, ient->sc_fmri);
5512 				return (scferror2errno(scf_error()));
5513 
5514 			case SCF_ERROR_NOT_SET:
5515 			default:
5516 				bad_error("scf_pg_delete", scf_error());
5517 			}
5518 		}
5519 
5520 		r = load_pg(lipg, &lipg_i, ient->sc_fmri, snap_lastimport);
5521 		switch (r) {
5522 		case 0:
5523 			break;
5524 
5525 		case ECANCELED:
5526 			return (ENODEV);
5527 
5528 		case ECONNABORTED:
5529 		case ENOMEM:
5530 		case EBADF:
5531 		case EACCES:
5532 			return (r);
5533 
5534 		default:
5535 			bad_error("load_pg", r);
5536 		}
5537 
5538 		r = load_pg(imp_pg2, &curpg_i, ient->sc_fmri, NULL);
5539 		switch (r) {
5540 		case 0:
5541 			break;
5542 
5543 		case ECANCELED:
5544 		case ECONNABORTED:
5545 		case ENOMEM:
5546 		case EBADF:
5547 		case EACCES:
5548 			internal_pgroup_free(lipg_i);
5549 			return (r);
5550 
5551 		default:
5552 			bad_error("load_pg", r);
5553 		}
5554 
5555 		if (pg_equal(lipg_i, curpg_i)) {
5556 			if (g_verbose)
5557 				warn(deleting, ient->sc_fmri, imp_str);
5558 			if (scf_pg_delete(imp_pg2) != 0) {
5559 				switch (scf_error()) {
5560 				case SCF_ERROR_DELETED:
5561 					break;
5562 
5563 				case SCF_ERROR_CONNECTION_BROKEN:
5564 					internal_pgroup_free(lipg_i);
5565 					internal_pgroup_free(curpg_i);
5566 					return (ECONNABORTED);
5567 
5568 				case SCF_ERROR_NOT_SET:
5569 				case SCF_ERROR_NOT_BOUND:
5570 				default:
5571 					bad_error("scf_pg_delete", scf_error());
5572 				}
5573 			}
5574 		} else {
5575 			report_pg_diffs(lipg_i, curpg_i, ient->sc_fmri, 0);
5576 		}
5577 
5578 		internal_pgroup_free(lipg_i);
5579 		internal_pgroup_free(curpg_i);
5580 
5581 		return (0);
5582 	}
5583 
5584 	/*
5585 	 * Only dependent pgs can have override set, and we skipped those
5586 	 * above.
5587 	 */
5588 	assert(!mpg->sc_pgroup_override);
5589 
5590 	/* compare */
5591 	r = load_pg(lipg, &lipg_i, ient->sc_fmri, snap_lastimport);
5592 	switch (r) {
5593 	case 0:
5594 		break;
5595 
5596 	case ECANCELED:
5597 		return (ENODEV);
5598 
5599 	case ECONNABORTED:
5600 	case EBADF:
5601 	case ENOMEM:
5602 	case EACCES:
5603 		return (r);
5604 
5605 	default:
5606 		bad_error("load_pg", r);
5607 	}
5608 
5609 	if (pg_equal(mpg, lipg_i)) {
5610 		/* The manifest pg has not changed.  Move on. */
5611 		r = 0;
5612 		goto out;
5613 	}
5614 
5615 	/* upgrade current properties according to lipg & mpg */
5616 	if (running != NULL)
5617 		r = scf_snaplevel_get_pg(running, imp_str, imp_pg2);
5618 	else
5619 		r = entity_get_pg(ent, issvc, imp_str, imp_pg2);
5620 	if (r != 0) {
5621 		switch (scf_error()) {
5622 		case SCF_ERROR_CONNECTION_BROKEN:
5623 			r = scferror2errno(scf_error());
5624 			goto out;
5625 
5626 		case SCF_ERROR_DELETED:
5627 			if (running != NULL)
5628 				r = ENODEV;
5629 			else
5630 				r = ECANCELED;
5631 			goto out;
5632 
5633 		case SCF_ERROR_NOT_FOUND:
5634 			break;
5635 
5636 		case SCF_ERROR_INVALID_ARGUMENT:
5637 		case SCF_ERROR_HANDLE_MISMATCH:
5638 		case SCF_ERROR_NOT_BOUND:
5639 		case SCF_ERROR_NOT_SET:
5640 		default:
5641 			bad_error("entity_get_pg", scf_error());
5642 		}
5643 
5644 		warn(cf_pg_missing, ient->sc_fmri, imp_str);
5645 
5646 		r = 0;
5647 		goto out;
5648 	}
5649 
5650 	r = load_pg_attrs(imp_pg2, &curpg_i);
5651 	switch (r) {
5652 	case 0:
5653 		break;
5654 
5655 	case ECANCELED:
5656 		warn(cf_pg_missing, ient->sc_fmri, imp_str);
5657 		r = 0;
5658 		goto out;
5659 
5660 	case ECONNABORTED:
5661 	case ENOMEM:
5662 		goto out;
5663 
5664 	default:
5665 		bad_error("load_pg_attrs", r);
5666 	}
5667 
5668 	if (!pg_attrs_equal(lipg_i, curpg_i, NULL, 0)) {
5669 		(void) pg_attrs_equal(curpg_i, mpg, ient->sc_fmri, 0);
5670 		internal_pgroup_free(curpg_i);
5671 		r = 0;
5672 		goto out;
5673 	}
5674 
5675 	internal_pgroup_free(curpg_i);
5676 
5677 	r = load_pg(imp_pg2, &curpg_i, ient->sc_fmri, NULL);
5678 	switch (r) {
5679 	case 0:
5680 		break;
5681 
5682 	case ECANCELED:
5683 		warn(cf_pg_missing, ient->sc_fmri, imp_str);
5684 		r = 0;
5685 		goto out;
5686 
5687 	case ECONNABORTED:
5688 	case EBADF:
5689 	case ENOMEM:
5690 	case EACCES:
5691 		goto out;
5692 
5693 	default:
5694 		bad_error("load_pg", r);
5695 	}
5696 
5697 	if (pg_equal(lipg_i, curpg_i) &&
5698 	    !pg_attrs_equal(lipg_i, mpg, NULL, 0)) {
5699 		int do_delete = 1;
5700 
5701 		if (g_verbose)
5702 			warn(gettext("%s: Upgrading property group \"%s\".\n"),
5703 			    ient->sc_fmri, mpg->sc_pgroup_name);
5704 
5705 		internal_pgroup_free(curpg_i);
5706 
5707 		if (running != NULL &&
5708 		    entity_get_pg(ent, issvc, imp_str, imp_pg2) != 0) {
5709 			switch (scf_error()) {
5710 			case SCF_ERROR_DELETED:
5711 				r = ECANCELED;
5712 				goto out;
5713 
5714 			case SCF_ERROR_NOT_FOUND:
5715 				do_delete = 0;
5716 				break;
5717 
5718 			case SCF_ERROR_CONNECTION_BROKEN:
5719 				r = scferror2errno(scf_error());
5720 				goto out;
5721 
5722 			case SCF_ERROR_HANDLE_MISMATCH:
5723 			case SCF_ERROR_INVALID_ARGUMENT:
5724 			case SCF_ERROR_NOT_SET:
5725 			case SCF_ERROR_NOT_BOUND:
5726 			default:
5727 				bad_error("entity_get_pg", scf_error());
5728 			}
5729 		}
5730 
5731 		if (do_delete && scf_pg_delete(imp_pg2) != 0) {
5732 			switch (scf_error()) {
5733 			case SCF_ERROR_DELETED:
5734 				break;
5735 
5736 			case SCF_ERROR_CONNECTION_BROKEN:
5737 			case SCF_ERROR_BACKEND_READONLY:
5738 			case SCF_ERROR_BACKEND_ACCESS:
5739 				r = scferror2errno(scf_error());
5740 				goto out;
5741 
5742 			case SCF_ERROR_PERMISSION_DENIED:
5743 				warn(emsg_pg_del_perm, mpg->sc_pgroup_name,
5744 				    ient->sc_fmri);
5745 				r = scferror2errno(scf_error());
5746 				goto out;
5747 
5748 			case SCF_ERROR_NOT_SET:
5749 			case SCF_ERROR_NOT_BOUND:
5750 			default:
5751 				bad_error("scf_pg_delete", scf_error());
5752 			}
5753 		}
5754 
5755 		cbdata.sc_handle = g_hndl;
5756 		cbdata.sc_parent = ent;
5757 		cbdata.sc_service = issvc;
5758 		cbdata.sc_flags = 0;
5759 		cbdata.sc_source_fmri = ient->sc_fmri;
5760 		cbdata.sc_target_fmri = ient->sc_fmri;
5761 
5762 		r = entity_pgroup_import(mpg, &cbdata);
5763 		switch (r) {
5764 		case UU_WALK_NEXT:
5765 			r = 0;
5766 			goto out;
5767 
5768 		case UU_WALK_ERROR:
5769 			if (cbdata.sc_err == EEXIST) {
5770 				warn(emsg_pg_added, ient->sc_fmri,
5771 				    mpg->sc_pgroup_name);
5772 				r = EBUSY;
5773 			} else {
5774 				r = cbdata.sc_err;
5775 			}
5776 			goto out;
5777 
5778 		default:
5779 			bad_error("entity_pgroup_import", r);
5780 		}
5781 	}
5782 
5783 	if (running != NULL &&
5784 	    entity_get_pg(ent, issvc, imp_str, imp_pg2) != 0) {
5785 		switch (scf_error()) {
5786 		case SCF_ERROR_CONNECTION_BROKEN:
5787 		case SCF_ERROR_DELETED:
5788 			r = scferror2errno(scf_error());
5789 			goto out;
5790 
5791 		case SCF_ERROR_NOT_FOUND:
5792 			break;
5793 
5794 		case SCF_ERROR_HANDLE_MISMATCH:
5795 		case SCF_ERROR_INVALID_ARGUMENT:
5796 		case SCF_ERROR_NOT_SET:
5797 		case SCF_ERROR_NOT_BOUND:
5798 		default:
5799 			bad_error("entity_get_pg", scf_error());
5800 		}
5801 
5802 		cbdata.sc_handle = g_hndl;
5803 		cbdata.sc_parent = ent;
5804 		cbdata.sc_service = issvc;
5805 		cbdata.sc_flags = SCI_FORCE;
5806 		cbdata.sc_source_fmri = ient->sc_fmri;
5807 		cbdata.sc_target_fmri = ient->sc_fmri;
5808 
5809 		r = entity_pgroup_import(mpg, &cbdata);
5810 		switch (r) {
5811 		case UU_WALK_NEXT:
5812 			r = 0;
5813 			goto out;
5814 
5815 		case UU_WALK_ERROR:
5816 			if (cbdata.sc_err == EEXIST) {
5817 				warn(emsg_pg_added, ient->sc_fmri,
5818 				    mpg->sc_pgroup_name);
5819 				r = EBUSY;
5820 			} else {
5821 				r = cbdata.sc_err;
5822 			}
5823 			goto out;
5824 
5825 		default:
5826 			bad_error("entity_pgroup_import", r);
5827 		}
5828 	}
5829 
5830 	r = upgrade_pg(imp_pg2, curpg_i, lipg_i, mpg, g_verbose, ient->sc_fmri);
5831 	internal_pgroup_free(curpg_i);
5832 	switch (r) {
5833 	case 0:
5834 		ient->sc_import_state = IMPORT_PROP_BEGUN;
5835 		break;
5836 
5837 	case ECANCELED:
5838 		warn(emsg_pg_deleted, ient->sc_fmri, mpg->sc_pgroup_name);
5839 		r = EBUSY;
5840 		break;
5841 
5842 	case EPERM:
5843 		warn(emsg_pg_mod_perm, mpg->sc_pgroup_name, ient->sc_fmri);
5844 		break;
5845 
5846 	case EBUSY:
5847 		warn(emsg_pg_changed, ient->sc_fmri, mpg->sc_pgroup_name);
5848 		break;
5849 
5850 	case ECONNABORTED:
5851 	case ENOMEM:
5852 	case ENOSPC:
5853 	case EROFS:
5854 	case EACCES:
5855 	case EINVAL:
5856 		break;
5857 
5858 	default:
5859 		bad_error("upgrade_pg", r);
5860 	}
5861 
5862 out:
5863 	internal_pgroup_free(lipg_i);
5864 	return (r);
5865 }
5866 
5867 /*
5868  * Upgrade the properties of ent according to snpl & ient.
5869  *
5870  * Returns
5871  *   0 - success
5872  *   ECONNABORTED - repository connection broken
5873  *   ENOMEM - out of memory
5874  *   ENOSPC - configd is out of resources
5875  *   ECANCELED - ent was deleted
5876  *   ENODEV - entity containing snpl was deleted
5877  *	    - entity containing running was deleted
5878  *   EBADF - imp_snpl is corrupt (error printed)
5879  *	   - ent has corrupt pg (error printed)
5880  *	   - dependent has corrupt pg (error printed)
5881  *	   - dependent target has a corrupt snapshot (error printed)
5882  *   EBUSY - pg was added, changed, or deleted (error printed)
5883  *	   - dependent target was deleted (error printed)
5884  *	   - dependent pg changed (error printed)
5885  *   EINVAL - invalid property group name (error printed)
5886  *	    - invalid property name (error printed)
5887  *	    - invalid value (error printed)
5888  *	    - ient has invalid pgroup or dependent (error printed)
5889  *   EPERM - could not create property group (permission denied) (error printed)
5890  *	   - could not modify property group (permission denied) (error printed)
5891  *	   - couldn't delete, upgrade, or import pg or dependent (error printed)
5892  *   EROFS - could not create property group (repository read-only)
5893  *	   - couldn't delete, upgrade, or import pg or dependent
5894  *   EACCES - could not create property group (backend access denied)
5895  *	    - couldn't delete, upgrade, or import pg or dependent
5896  *   EEXIST - dependent collision in target service (error printed)
5897  */
5898 static int
5899 upgrade_props(void *ent, scf_snaplevel_t *running, scf_snaplevel_t *snpl,
5900     entity_t *ient)
5901 {
5902 	pgroup_t *pg, *rpg;
5903 	int r;
5904 	uu_list_t *pgs = ient->sc_pgroups;
5905 
5906 	const int issvc = (ient->sc_etype == SVCCFG_SERVICE_OBJECT);
5907 
5908 	/* clear sc_sceen for pgs */
5909 	if (uu_list_walk(pgs, clear_int,
5910 	    (void *)offsetof(pgroup_t, sc_pgroup_seen), UU_DEFAULT) != 0)
5911 		bad_error("uu_list_walk", uu_error());
5912 
5913 	if (scf_iter_snaplevel_pgs(imp_up_iter, snpl) != 0) {
5914 		switch (scf_error()) {
5915 		case SCF_ERROR_DELETED:
5916 			return (ENODEV);
5917 
5918 		case SCF_ERROR_CONNECTION_BROKEN:
5919 			return (ECONNABORTED);
5920 
5921 		case SCF_ERROR_NOT_SET:
5922 		case SCF_ERROR_NOT_BOUND:
5923 		case SCF_ERROR_HANDLE_MISMATCH:
5924 		default:
5925 			bad_error("scf_iter_snaplevel_pgs", scf_error());
5926 		}
5927 	}
5928 
5929 	for (;;) {
5930 		r = scf_iter_next_pg(imp_up_iter, imp_pg);
5931 		if (r == 0)
5932 			break;
5933 		if (r == 1) {
5934 			r = process_old_pg(imp_pg, ient, ent, running);
5935 			switch (r) {
5936 			case 0:
5937 				break;
5938 
5939 			case ECONNABORTED:
5940 			case ENOMEM:
5941 			case ENOSPC:
5942 			case ECANCELED:
5943 			case ENODEV:
5944 			case EPERM:
5945 			case EROFS:
5946 			case EACCES:
5947 			case EBADF:
5948 			case EBUSY:
5949 			case EINVAL:
5950 			case EEXIST:
5951 				return (r);
5952 
5953 			default:
5954 				bad_error("process_old_pg", r);
5955 			}
5956 			continue;
5957 		}
5958 		if (r != -1)
5959 			bad_error("scf_iter_next_pg", r);
5960 
5961 		switch (scf_error()) {
5962 		case SCF_ERROR_DELETED:
5963 			return (ENODEV);
5964 
5965 		case SCF_ERROR_CONNECTION_BROKEN:
5966 			return (ECONNABORTED);
5967 
5968 		case SCF_ERROR_HANDLE_MISMATCH:
5969 		case SCF_ERROR_NOT_BOUND:
5970 		case SCF_ERROR_NOT_SET:
5971 		case SCF_ERROR_INVALID_ARGUMENT:
5972 		default:
5973 			bad_error("scf_iter_next_pg", scf_error());
5974 		}
5975 	}
5976 
5977 	for (pg = uu_list_first(pgs); pg != NULL; pg = uu_list_next(pgs, pg)) {
5978 		if (pg->sc_pgroup_seen)
5979 			continue;
5980 
5981 		/* pg is new */
5982 
5983 		if (strcmp(pg->sc_pgroup_name, "dependents") == 0) {
5984 			r = upgrade_dependents(NULL, imp_snpl, ient, running,
5985 			    ent);
5986 			switch (r) {
5987 			case 0:
5988 				break;
5989 
5990 			case ECONNABORTED:
5991 			case ENOMEM:
5992 			case ENOSPC:
5993 			case ECANCELED:
5994 			case ENODEV:
5995 			case EBADF:
5996 			case EBUSY:
5997 			case EINVAL:
5998 			case EPERM:
5999 			case EROFS:
6000 			case EACCES:
6001 			case EEXIST:
6002 				return (r);
6003 
6004 			default:
6005 				bad_error("upgrade_dependents", r);
6006 			}
6007 			continue;
6008 		}
6009 
6010 		if (strcmp(pg->sc_pgroup_name, SCF_PG_MANIFESTFILES) == 0) {
6011 			r = upgrade_manifestfiles(pg, ient, running, ent);
6012 			switch (r) {
6013 			case 0:
6014 				break;
6015 
6016 			case ECONNABORTED:
6017 			case ENOMEM:
6018 			case ENOSPC:
6019 			case ECANCELED:
6020 			case ENODEV:
6021 			case EBADF:
6022 			case EBUSY:
6023 			case EINVAL:
6024 			case EPERM:
6025 			case EROFS:
6026 			case EACCES:
6027 			case EEXIST:
6028 				return (r);
6029 
6030 			default:
6031 				bad_error("upgrade_manifestfiles", r);
6032 			}
6033 			continue;
6034 		}
6035 
6036 		if (running != NULL) {
6037 			r = scf_snaplevel_get_pg(running, pg->sc_pgroup_name,
6038 			    imp_pg);
6039 		} else {
6040 			r = entity_get_pg(ent, issvc, pg->sc_pgroup_name,
6041 			    imp_pg);
6042 		}
6043 		if (r != 0) {
6044 			scf_callback_t cbdata;
6045 
6046 			switch (scf_error()) {
6047 			case SCF_ERROR_NOT_FOUND:
6048 				break;
6049 
6050 			case SCF_ERROR_CONNECTION_BROKEN:
6051 				return (scferror2errno(scf_error()));
6052 
6053 			case SCF_ERROR_DELETED:
6054 				if (running != NULL)
6055 					return (ENODEV);
6056 				else
6057 					return (scferror2errno(scf_error()));
6058 
6059 			case SCF_ERROR_INVALID_ARGUMENT:
6060 				warn(emsg_fmri_invalid_pg_name, ient->sc_fmri,
6061 				    pg->sc_pgroup_name);
6062 				return (EINVAL);
6063 
6064 			case SCF_ERROR_NOT_SET:
6065 			case SCF_ERROR_HANDLE_MISMATCH:
6066 			case SCF_ERROR_NOT_BOUND:
6067 			default:
6068 				bad_error("entity_get_pg", scf_error());
6069 			}
6070 
6071 			/* User doesn't have pg, so import it. */
6072 
6073 			cbdata.sc_handle = g_hndl;
6074 			cbdata.sc_parent = ent;
6075 			cbdata.sc_service = issvc;
6076 			cbdata.sc_flags = SCI_FORCE;
6077 			cbdata.sc_source_fmri = ient->sc_fmri;
6078 			cbdata.sc_target_fmri = ient->sc_fmri;
6079 
6080 			r = entity_pgroup_import(pg, &cbdata);
6081 			switch (r) {
6082 			case UU_WALK_NEXT:
6083 				ient->sc_import_state = IMPORT_PROP_BEGUN;
6084 				continue;
6085 
6086 			case UU_WALK_ERROR:
6087 				if (cbdata.sc_err == EEXIST) {
6088 					warn(emsg_pg_added, ient->sc_fmri,
6089 					    pg->sc_pgroup_name);
6090 					return (EBUSY);
6091 				}
6092 				return (cbdata.sc_err);
6093 
6094 			default:
6095 				bad_error("entity_pgroup_import", r);
6096 			}
6097 		}
6098 
6099 		/* report differences between pg & current */
6100 		r = load_pg(imp_pg, &rpg, ient->sc_fmri, NULL);
6101 		switch (r) {
6102 		case 0:
6103 			break;
6104 
6105 		case ECANCELED:
6106 			warn(emsg_pg_deleted, ient->sc_fmri,
6107 			    pg->sc_pgroup_name);
6108 			return (EBUSY);
6109 
6110 		case ECONNABORTED:
6111 		case EBADF:
6112 		case ENOMEM:
6113 		case EACCES:
6114 			return (r);
6115 
6116 		default:
6117 			bad_error("load_pg", r);
6118 		}
6119 		report_pg_diffs(pg, rpg, ient->sc_fmri, 1);
6120 		internal_pgroup_free(rpg);
6121 		rpg = NULL;
6122 	}
6123 
6124 	return (0);
6125 }
6126 
6127 /*
6128  * Import an instance.  If it doesn't exist, create it.  If it has
6129  * a last-import snapshot, upgrade its properties.  Finish by updating its
6130  * last-import snapshot.  If it doesn't have a last-import snapshot then it
6131  * could have been created for a dependent tag in another manifest.  Import the
6132  * new properties.  If there's a conflict, don't override, like now?
6133  *
6134  * On success, returns UU_WALK_NEXT.  On error returns UU_WALK_ERROR and sets
6135  * lcbdata->sc_err to
6136  *   ECONNABORTED - repository connection broken
6137  *   ENOMEM - out of memory
6138  *   ENOSPC - svc.configd is out of resources
6139  *   EEXIST - dependency collision in dependent service (error printed)
6140  *   EPERM - couldn't create temporary instance (permission denied)
6141  *	   - couldn't import into temporary instance (permission denied)
6142  *	   - couldn't take snapshot (permission denied)
6143  *	   - couldn't upgrade properties (permission denied)
6144  *	   - couldn't import properties (permission denied)
6145  *	   - couldn't import dependents (permission denied)
6146  *   EROFS - couldn't create temporary instance (repository read-only)
6147  *	   - couldn't import into temporary instance (repository read-only)
6148  *	   - couldn't upgrade properties (repository read-only)
6149  *	   - couldn't import properties (repository read-only)
6150  *	   - couldn't import dependents (repository read-only)
6151  *   EACCES - couldn't create temporary instance (backend access denied)
6152  *	    - couldn't import into temporary instance (backend access denied)
6153  *	    - couldn't upgrade properties (backend access denied)
6154  *	    - couldn't import properties (backend access denied)
6155  *	    - couldn't import dependents (backend access denied)
6156  *   EINVAL - invalid instance name (error printed)
6157  *	    - invalid pgroup_t's (error printed)
6158  *	    - invalid dependents (error printed)
6159  *   EBUSY - temporary service deleted (error printed)
6160  *	   - temporary instance deleted (error printed)
6161  *	   - temporary instance changed (error printed)
6162  *	   - temporary instance already exists (error printed)
6163  *	   - instance deleted (error printed)
6164  *   EBADF - instance has corrupt last-import snapshot (error printed)
6165  *	   - instance is corrupt (error printed)
6166  *	   - dependent has corrupt pg (error printed)
6167  *	   - dependent target has a corrupt snapshot (error printed)
6168  *   -1 - unknown libscf error (error printed)
6169  */
6170 static int
6171 lscf_instance_import(void *v, void *pvt)
6172 {
6173 	entity_t *inst = v;
6174 	scf_callback_t ctx;
6175 	scf_callback_t *lcbdata = pvt;
6176 	scf_service_t *rsvc = lcbdata->sc_parent;
6177 	int r;
6178 	scf_snaplevel_t *running;
6179 	int flags = lcbdata->sc_flags;
6180 
6181 	const char * const emsg_tdel =
6182 	    gettext("Temporary instance svc:/%s:%s was deleted.\n");
6183 	const char * const emsg_tchg = gettext("Temporary instance svc:/%s:%s "
6184 	    "changed unexpectedly.\n");
6185 	const char * const emsg_del = gettext("%s changed unexpectedly "
6186 	    "(instance \"%s\" was deleted.)\n");
6187 	const char * const emsg_badsnap = gettext(
6188 	    "\"%s\" snapshot of %s is corrupt (missing a snaplevel).\n");
6189 
6190 	/*
6191 	 * prepare last-import snapshot:
6192 	 * create temporary instance (service was precreated)
6193 	 * populate with properties from bundle
6194 	 * take snapshot
6195 	 */
6196 	if (scf_service_add_instance(imp_tsvc, inst->sc_name, imp_tinst) != 0) {
6197 		switch (scf_error()) {
6198 		case SCF_ERROR_CONNECTION_BROKEN:
6199 		case SCF_ERROR_NO_RESOURCES:
6200 		case SCF_ERROR_BACKEND_READONLY:
6201 		case SCF_ERROR_BACKEND_ACCESS:
6202 			return (stash_scferror(lcbdata));
6203 
6204 		case SCF_ERROR_EXISTS:
6205 			warn(gettext("Temporary service svc:/%s "
6206 			    "changed unexpectedly (instance \"%s\" added).\n"),
6207 			    imp_tsname, inst->sc_name);
6208 			lcbdata->sc_err = EBUSY;
6209 			return (UU_WALK_ERROR);
6210 
6211 		case SCF_ERROR_DELETED:
6212 			warn(gettext("Temporary service svc:/%s "
6213 			    "was deleted unexpectedly.\n"), imp_tsname);
6214 			lcbdata->sc_err = EBUSY;
6215 			return (UU_WALK_ERROR);
6216 
6217 		case SCF_ERROR_INVALID_ARGUMENT:
6218 			warn(gettext("Invalid instance name \"%s\".\n"),
6219 			    inst->sc_name);
6220 			return (stash_scferror(lcbdata));
6221 
6222 		case SCF_ERROR_PERMISSION_DENIED:
6223 			warn(gettext("Could not create temporary instance "
6224 			    "\"%s\" in svc:/%s (permission denied).\n"),
6225 			    inst->sc_name, imp_tsname);
6226 			return (stash_scferror(lcbdata));
6227 
6228 		case SCF_ERROR_HANDLE_MISMATCH:
6229 		case SCF_ERROR_NOT_BOUND:
6230 		case SCF_ERROR_NOT_SET:
6231 		default:
6232 			bad_error("scf_service_add_instance", scf_error());
6233 		}
6234 	}
6235 
6236 	r = snprintf(imp_str, imp_str_sz, "svc:/%s:%s", imp_tsname,
6237 	    inst->sc_name);
6238 	if (r < 0)
6239 		bad_error("snprintf", errno);
6240 
6241 	r = lscf_import_instance_pgs(imp_tinst, imp_str, inst,
6242 	    lcbdata->sc_flags | SCI_NOENABLED);
6243 	switch (r) {
6244 	case 0:
6245 		break;
6246 
6247 	case ECANCELED:
6248 		warn(emsg_tdel, imp_tsname, inst->sc_name);
6249 		lcbdata->sc_err = EBUSY;
6250 		r = UU_WALK_ERROR;
6251 		goto deltemp;
6252 
6253 	case EEXIST:
6254 		warn(emsg_tchg, imp_tsname, inst->sc_name);
6255 		lcbdata->sc_err = EBUSY;
6256 		r = UU_WALK_ERROR;
6257 		goto deltemp;
6258 
6259 	case ECONNABORTED:
6260 		goto connaborted;
6261 
6262 	case ENOMEM:
6263 	case ENOSPC:
6264 	case EPERM:
6265 	case EROFS:
6266 	case EACCES:
6267 	case EINVAL:
6268 	case EBUSY:
6269 		lcbdata->sc_err = r;
6270 		r = UU_WALK_ERROR;
6271 		goto deltemp;
6272 
6273 	default:
6274 		bad_error("lscf_import_instance_pgs", r);
6275 	}
6276 
6277 	r = snprintf(imp_str, imp_str_sz, "svc:/%s:%s", imp_tsname,
6278 	    inst->sc_name);
6279 	if (r < 0)
6280 		bad_error("snprintf", errno);
6281 
6282 	ctx.sc_handle = lcbdata->sc_handle;
6283 	ctx.sc_parent = imp_tinst;
6284 	ctx.sc_service = 0;
6285 	ctx.sc_source_fmri = inst->sc_fmri;
6286 	ctx.sc_target_fmri = imp_str;
6287 	if (uu_list_walk(inst->sc_dependents, entity_pgroup_import, &ctx,
6288 	    UU_DEFAULT) != 0) {
6289 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
6290 			bad_error("uu_list_walk", uu_error());
6291 
6292 		switch (ctx.sc_err) {
6293 		case ECONNABORTED:
6294 			goto connaborted;
6295 
6296 		case ECANCELED:
6297 			warn(emsg_tdel, imp_tsname, inst->sc_name);
6298 			lcbdata->sc_err = EBUSY;
6299 			break;
6300 
6301 		case EEXIST:
6302 			warn(emsg_tchg, imp_tsname, inst->sc_name);
6303 			lcbdata->sc_err = EBUSY;
6304 			break;
6305 
6306 		default:
6307 			lcbdata->sc_err = ctx.sc_err;
6308 		}
6309 		r = UU_WALK_ERROR;
6310 		goto deltemp;
6311 	}
6312 
6313 	if (_scf_snapshot_take_new_named(imp_tinst, inst->sc_parent->sc_name,
6314 	    inst->sc_name, snap_lastimport, imp_tlisnap) != 0) {
6315 		switch (scf_error()) {
6316 		case SCF_ERROR_CONNECTION_BROKEN:
6317 			goto connaborted;
6318 
6319 		case SCF_ERROR_NO_RESOURCES:
6320 			r = stash_scferror(lcbdata);
6321 			goto deltemp;
6322 
6323 		case SCF_ERROR_EXISTS:
6324 			warn(emsg_tchg, imp_tsname, inst->sc_name);
6325 			lcbdata->sc_err = EBUSY;
6326 			r = UU_WALK_ERROR;
6327 			goto deltemp;
6328 
6329 		case SCF_ERROR_PERMISSION_DENIED:
6330 			warn(gettext("Could not take \"%s\" snapshot of %s "
6331 			    "(permission denied).\n"), snap_lastimport,
6332 			    imp_str);
6333 			r = stash_scferror(lcbdata);
6334 			goto deltemp;
6335 
6336 		default:
6337 			scfwarn();
6338 			lcbdata->sc_err = -1;
6339 			r = UU_WALK_ERROR;
6340 			goto deltemp;
6341 
6342 		case SCF_ERROR_HANDLE_MISMATCH:
6343 		case SCF_ERROR_INVALID_ARGUMENT:
6344 		case SCF_ERROR_NOT_SET:
6345 			bad_error("_scf_snapshot_take_new_named", scf_error());
6346 		}
6347 	}
6348 
6349 	if (lcbdata->sc_flags & SCI_FRESH)
6350 		goto fresh;
6351 
6352 	if (scf_service_get_instance(rsvc, inst->sc_name, imp_inst) == 0) {
6353 		if (scf_instance_get_snapshot(imp_inst, snap_lastimport,
6354 		    imp_lisnap) != 0) {
6355 			switch (scf_error()) {
6356 			case SCF_ERROR_DELETED:
6357 				warn(emsg_del, inst->sc_parent->sc_fmri,
6358 				    inst->sc_name);
6359 				lcbdata->sc_err = EBUSY;
6360 				r = UU_WALK_ERROR;
6361 				goto deltemp;
6362 
6363 			case SCF_ERROR_NOT_FOUND:
6364 				flags |= SCI_FORCE;
6365 				goto nosnap;
6366 
6367 			case SCF_ERROR_CONNECTION_BROKEN:
6368 				goto connaborted;
6369 
6370 			case SCF_ERROR_INVALID_ARGUMENT:
6371 			case SCF_ERROR_HANDLE_MISMATCH:
6372 			case SCF_ERROR_NOT_BOUND:
6373 			case SCF_ERROR_NOT_SET:
6374 			default:
6375 				bad_error("scf_instance_get_snapshot",
6376 				    scf_error());
6377 			}
6378 		}
6379 
6380 		/* upgrade */
6381 
6382 		/*
6383 		 * compare new properties with last-import properties
6384 		 * upgrade current properties
6385 		 */
6386 		/* clear sc_sceen for pgs */
6387 		if (uu_list_walk(inst->sc_pgroups, clear_int,
6388 		    (void *)offsetof(pgroup_t, sc_pgroup_seen), UU_DEFAULT) !=
6389 		    0)
6390 			bad_error("uu_list_walk", uu_error());
6391 
6392 		r = get_snaplevel(imp_lisnap, 0, imp_snpl);
6393 		switch (r) {
6394 		case 0:
6395 			break;
6396 
6397 		case ECONNABORTED:
6398 			goto connaborted;
6399 
6400 		case ECANCELED:
6401 			warn(emsg_del, inst->sc_parent->sc_fmri, inst->sc_name);
6402 			lcbdata->sc_err = EBUSY;
6403 			r = UU_WALK_ERROR;
6404 			goto deltemp;
6405 
6406 		case ENOENT:
6407 			warn(emsg_badsnap, snap_lastimport, inst->sc_fmri);
6408 			lcbdata->sc_err = EBADF;
6409 			r = UU_WALK_ERROR;
6410 			goto deltemp;
6411 
6412 		default:
6413 			bad_error("get_snaplevel", r);
6414 		}
6415 
6416 		if (scf_instance_get_snapshot(imp_inst, snap_running,
6417 		    imp_rsnap) != 0) {
6418 			switch (scf_error()) {
6419 			case SCF_ERROR_DELETED:
6420 				warn(emsg_del, inst->sc_parent->sc_fmri,
6421 				    inst->sc_name);
6422 				lcbdata->sc_err = EBUSY;
6423 				r = UU_WALK_ERROR;
6424 				goto deltemp;
6425 
6426 			case SCF_ERROR_NOT_FOUND:
6427 				break;
6428 
6429 			case SCF_ERROR_CONNECTION_BROKEN:
6430 				goto connaborted;
6431 
6432 			case SCF_ERROR_INVALID_ARGUMENT:
6433 			case SCF_ERROR_HANDLE_MISMATCH:
6434 			case SCF_ERROR_NOT_BOUND:
6435 			case SCF_ERROR_NOT_SET:
6436 			default:
6437 				bad_error("scf_instance_get_snapshot",
6438 				    scf_error());
6439 			}
6440 
6441 			running = NULL;
6442 		} else {
6443 			r = get_snaplevel(imp_rsnap, 0, imp_rsnpl);
6444 			switch (r) {
6445 			case 0:
6446 				running = imp_rsnpl;
6447 				break;
6448 
6449 			case ECONNABORTED:
6450 				goto connaborted;
6451 
6452 			case ECANCELED:
6453 				warn(emsg_del, inst->sc_parent->sc_fmri,
6454 				    inst->sc_name);
6455 				lcbdata->sc_err = EBUSY;
6456 				r = UU_WALK_ERROR;
6457 				goto deltemp;
6458 
6459 			case ENOENT:
6460 				warn(emsg_badsnap, snap_running, inst->sc_fmri);
6461 				lcbdata->sc_err = EBADF;
6462 				r = UU_WALK_ERROR;
6463 				goto deltemp;
6464 
6465 			default:
6466 				bad_error("get_snaplevel", r);
6467 			}
6468 		}
6469 
6470 		r = upgrade_props(imp_inst, running, imp_snpl, inst);
6471 		switch (r) {
6472 		case 0:
6473 			break;
6474 
6475 		case ECANCELED:
6476 		case ENODEV:
6477 			warn(emsg_del, inst->sc_parent->sc_fmri, inst->sc_name);
6478 			lcbdata->sc_err = EBUSY;
6479 			r = UU_WALK_ERROR;
6480 			goto deltemp;
6481 
6482 		case ECONNABORTED:
6483 			goto connaborted;
6484 
6485 		case ENOMEM:
6486 		case ENOSPC:
6487 		case EBADF:
6488 		case EBUSY:
6489 		case EINVAL:
6490 		case EPERM:
6491 		case EROFS:
6492 		case EACCES:
6493 		case EEXIST:
6494 			lcbdata->sc_err = r;
6495 			r = UU_WALK_ERROR;
6496 			goto deltemp;
6497 
6498 		default:
6499 			bad_error("upgrade_props", r);
6500 		}
6501 
6502 		inst->sc_import_state = IMPORT_PROP_DONE;
6503 	} else {
6504 		switch (scf_error()) {
6505 		case SCF_ERROR_CONNECTION_BROKEN:
6506 			goto connaborted;
6507 
6508 		case SCF_ERROR_NOT_FOUND:
6509 			break;
6510 
6511 		case SCF_ERROR_INVALID_ARGUMENT:	/* caught above */
6512 		case SCF_ERROR_HANDLE_MISMATCH:
6513 		case SCF_ERROR_NOT_BOUND:
6514 		case SCF_ERROR_NOT_SET:
6515 		default:
6516 			bad_error("scf_service_get_instance", scf_error());
6517 		}
6518 
6519 fresh:
6520 		/* create instance */
6521 		if (scf_service_add_instance(rsvc, inst->sc_name,
6522 		    imp_inst) != 0) {
6523 			switch (scf_error()) {
6524 			case SCF_ERROR_CONNECTION_BROKEN:
6525 				goto connaborted;
6526 
6527 			case SCF_ERROR_NO_RESOURCES:
6528 			case SCF_ERROR_BACKEND_READONLY:
6529 			case SCF_ERROR_BACKEND_ACCESS:
6530 				r = stash_scferror(lcbdata);
6531 				goto deltemp;
6532 
6533 			case SCF_ERROR_EXISTS:
6534 				warn(gettext("%s changed unexpectedly "
6535 				    "(instance \"%s\" added).\n"),
6536 				    inst->sc_parent->sc_fmri, inst->sc_name);
6537 				lcbdata->sc_err = EBUSY;
6538 				r = UU_WALK_ERROR;
6539 				goto deltemp;
6540 
6541 			case SCF_ERROR_PERMISSION_DENIED:
6542 				warn(gettext("Could not create \"%s\" instance "
6543 				    "in %s (permission denied).\n"),
6544 				    inst->sc_name, inst->sc_parent->sc_fmri);
6545 				r = stash_scferror(lcbdata);
6546 				goto deltemp;
6547 
6548 			case SCF_ERROR_INVALID_ARGUMENT:  /* caught above */
6549 			case SCF_ERROR_HANDLE_MISMATCH:
6550 			case SCF_ERROR_NOT_BOUND:
6551 			case SCF_ERROR_NOT_SET:
6552 			default:
6553 				bad_error("scf_service_add_instance",
6554 				    scf_error());
6555 			}
6556 		}
6557 
6558 nosnap:
6559 		/*
6560 		 * Create a last-import snapshot to serve as an attachment
6561 		 * point for the real one from the temporary instance.  Since
6562 		 * the contents is irrelevant, take it now, while the instance
6563 		 * is empty, to minimize svc.configd's work.
6564 		 */
6565 		if (_scf_snapshot_take_new(imp_inst, snap_lastimport,
6566 		    imp_lisnap) != 0) {
6567 			switch (scf_error()) {
6568 			case SCF_ERROR_CONNECTION_BROKEN:
6569 				goto connaborted;
6570 
6571 			case SCF_ERROR_NO_RESOURCES:
6572 				r = stash_scferror(lcbdata);
6573 				goto deltemp;
6574 
6575 			case SCF_ERROR_EXISTS:
6576 				warn(gettext("%s changed unexpectedly "
6577 				    "(snapshot \"%s\" added).\n"),
6578 				    inst->sc_fmri, snap_lastimport);
6579 				lcbdata->sc_err = EBUSY;
6580 				r = UU_WALK_ERROR;
6581 				goto deltemp;
6582 
6583 			case SCF_ERROR_PERMISSION_DENIED:
6584 				warn(gettext("Could not take \"%s\" snapshot "
6585 				    "of %s (permission denied).\n"),
6586 				    snap_lastimport, inst->sc_fmri);
6587 				r = stash_scferror(lcbdata);
6588 				goto deltemp;
6589 
6590 			default:
6591 				scfwarn();
6592 				lcbdata->sc_err = -1;
6593 				r = UU_WALK_ERROR;
6594 				goto deltemp;
6595 
6596 			case SCF_ERROR_NOT_SET:
6597 			case SCF_ERROR_INTERNAL:
6598 			case SCF_ERROR_INVALID_ARGUMENT:
6599 			case SCF_ERROR_HANDLE_MISMATCH:
6600 				bad_error("_scf_snapshot_take_new",
6601 				    scf_error());
6602 			}
6603 		}
6604 
6605 		if (li_only)
6606 			goto lionly;
6607 
6608 		inst->sc_import_state = IMPORT_PROP_BEGUN;
6609 
6610 		r = lscf_import_instance_pgs(imp_inst, inst->sc_fmri, inst,
6611 		    flags);
6612 		switch (r) {
6613 		case 0:
6614 			break;
6615 
6616 		case ECONNABORTED:
6617 			goto connaborted;
6618 
6619 		case ECANCELED:
6620 			warn(gettext("%s changed unexpectedly "
6621 			    "(instance \"%s\" deleted).\n"),
6622 			    inst->sc_parent->sc_fmri, inst->sc_name);
6623 			lcbdata->sc_err = EBUSY;
6624 			r = UU_WALK_ERROR;
6625 			goto deltemp;
6626 
6627 		case EEXIST:
6628 			warn(gettext("%s changed unexpectedly "
6629 			    "(property group added).\n"), inst->sc_fmri);
6630 			lcbdata->sc_err = EBUSY;
6631 			r = UU_WALK_ERROR;
6632 			goto deltemp;
6633 
6634 		default:
6635 			lcbdata->sc_err = r;
6636 			r = UU_WALK_ERROR;
6637 			goto deltemp;
6638 
6639 		case EINVAL:	/* caught above */
6640 			bad_error("lscf_import_instance_pgs", r);
6641 		}
6642 
6643 		ctx.sc_parent = imp_inst;
6644 		ctx.sc_service = 0;
6645 		ctx.sc_trans = NULL;
6646 		ctx.sc_flags = 0;
6647 		if (uu_list_walk(inst->sc_dependents, lscf_dependent_import,
6648 		    &ctx, UU_DEFAULT) != 0) {
6649 			if (uu_error() != UU_ERROR_CALLBACK_FAILED)
6650 				bad_error("uu_list_walk", uu_error());
6651 
6652 			if (ctx.sc_err == ECONNABORTED)
6653 				goto connaborted;
6654 			lcbdata->sc_err = ctx.sc_err;
6655 			r = UU_WALK_ERROR;
6656 			goto deltemp;
6657 		}
6658 
6659 		inst->sc_import_state = IMPORT_PROP_DONE;
6660 
6661 		if (g_verbose)
6662 			warn(gettext("Taking \"%s\" snapshot for %s.\n"),
6663 			    snap_initial, inst->sc_fmri);
6664 		r = take_snap(imp_inst, snap_initial, imp_snap);
6665 		switch (r) {
6666 		case 0:
6667 			break;
6668 
6669 		case ECONNABORTED:
6670 			goto connaborted;
6671 
6672 		case ENOSPC:
6673 		case -1:
6674 			lcbdata->sc_err = r;
6675 			r = UU_WALK_ERROR;
6676 			goto deltemp;
6677 
6678 		case ECANCELED:
6679 			warn(gettext("%s changed unexpectedly "
6680 			    "(instance %s deleted).\n"),
6681 			    inst->sc_parent->sc_fmri, inst->sc_name);
6682 			lcbdata->sc_err = r;
6683 			r = UU_WALK_ERROR;
6684 			goto deltemp;
6685 
6686 		case EPERM:
6687 			warn(emsg_snap_perm, snap_initial, inst->sc_fmri);
6688 			lcbdata->sc_err = r;
6689 			r = UU_WALK_ERROR;
6690 			goto deltemp;
6691 
6692 		default:
6693 			bad_error("take_snap", r);
6694 		}
6695 	}
6696 
6697 lionly:
6698 	if (lcbdata->sc_flags & SCI_NOSNAP)
6699 		goto deltemp;
6700 
6701 	/* transfer snapshot from temporary instance */
6702 	if (g_verbose)
6703 		warn(gettext("Taking \"%s\" snapshot for %s.\n"),
6704 		    snap_lastimport, inst->sc_fmri);
6705 	if (_scf_snapshot_attach(imp_tlisnap, imp_lisnap) != 0) {
6706 		switch (scf_error()) {
6707 		case SCF_ERROR_CONNECTION_BROKEN:
6708 			goto connaborted;
6709 
6710 		case SCF_ERROR_NO_RESOURCES:
6711 			r = stash_scferror(lcbdata);
6712 			goto deltemp;
6713 
6714 		case SCF_ERROR_PERMISSION_DENIED:
6715 			warn(gettext("Could not take \"%s\" snapshot for %s "
6716 			    "(permission denied).\n"), snap_lastimport,
6717 			    inst->sc_fmri);
6718 			r = stash_scferror(lcbdata);
6719 			goto deltemp;
6720 
6721 		case SCF_ERROR_NOT_SET:
6722 		case SCF_ERROR_HANDLE_MISMATCH:
6723 		default:
6724 			bad_error("_scf_snapshot_attach", scf_error());
6725 		}
6726 	}
6727 
6728 	inst->sc_import_state = IMPORT_COMPLETE;
6729 
6730 	r = UU_WALK_NEXT;
6731 
6732 deltemp:
6733 	/* delete temporary instance */
6734 	if (scf_instance_delete(imp_tinst) != 0) {
6735 		switch (scf_error()) {
6736 		case SCF_ERROR_DELETED:
6737 			break;
6738 
6739 		case SCF_ERROR_CONNECTION_BROKEN:
6740 			goto connaborted;
6741 
6742 		case SCF_ERROR_NOT_SET:
6743 		case SCF_ERROR_NOT_BOUND:
6744 		default:
6745 			bad_error("scf_instance_delete", scf_error());
6746 		}
6747 	}
6748 
6749 	return (r);
6750 
6751 connaborted:
6752 	warn(gettext("Could not delete svc:/%s:%s "
6753 	    "(repository connection broken).\n"), imp_tsname, inst->sc_name);
6754 	lcbdata->sc_err = ECONNABORTED;
6755 	return (UU_WALK_ERROR);
6756 }
6757 
6758 /*
6759  * When an instance is imported we end up telling configd about it. Once we tell
6760  * configd about these changes, startd eventually notices. If this is a new
6761  * instance, the manifest may not specify the SCF_PG_RESTARTER (restarter)
6762  * property group. However, many of the other tools expect that this property
6763  * group exists and has certain values.
6764  *
6765  * These values are added asynchronously by startd. We should not return from
6766  * this routine until we can verify that the property group we need is there.
6767  *
6768  * Before we go ahead and verify this, we have to ask ourselves an important
6769  * question: Is the early manifest service currently running?  Because if it is
6770  * running and it has invoked us, then the service will never get a restarter
6771  * property because svc.startd is blocked on EMI finishing before it lets itself
6772  * fully connect to svc.configd. Of course, this means that this race condition
6773  * is in fact impossible to 100% eliminate.
6774  *
6775  * svc.startd makes sure that EMI only runs once and has succeeded by checking
6776  * the state of the EMI instance. If it is online it bails out and makes sure
6777  * that it doesn't run again. In this case, we're going to do something similar,
6778  * only if the state is online, then we're going to actually verify. EMI always
6779  * has to be present, but it can be explicitly disabled to reduce the amount of
6780  * damage it can cause. If EMI has been disabled then we no longer have to worry
6781  * about the implicit race condition and can go ahead and check things. If EMI
6782  * is in some state that isn't online or disabled and isn't runinng, then we
6783  * assume that things are rather bad and we're not going to get in your way,
6784  * even if the rest of SMF does.
6785  *
6786  * Returns 0 on success or returns an errno.
6787  */
6788 #ifndef NATIVE_BUILD
6789 static int
6790 lscf_instance_verify(scf_scope_t *scope, entity_t *svc, entity_t *inst)
6791 {
6792 	int ret, err;
6793 	struct timespec ts;
6794 	char *emi_state;
6795 
6796 	/*
6797 	 * smf_get_state does not distinguish between its different failure
6798 	 * modes: memory allocation failures and SMF internal failures.
6799 	 */
6800 	if ((emi_state = smf_get_state(SCF_INSTANCE_EMI)) == NULL)
6801 		return (EAGAIN);
6802 
6803 	/*
6804 	 * As per the block comment for this function check the state of EMI
6805 	 */
6806 	if (strcmp(emi_state, SCF_STATE_STRING_ONLINE) != 0 &&
6807 	    strcmp(emi_state, SCF_STATE_STRING_DISABLED) != 0) {
6808 		warn(gettext("Not validating instance %s:%s because EMI's "
6809 		    "state is %s\n"), svc->sc_name, inst->sc_name, emi_state);
6810 		free(emi_state);
6811 		return (0);
6812 	}
6813 
6814 	free(emi_state);
6815 
6816 	/*
6817 	 * First we have to get the property.
6818 	 */
6819 	if ((ret = scf_scope_get_service(scope, svc->sc_name, imp_svc)) != 0) {
6820 		ret = scf_error();
6821 		warn(gettext("Failed to look up service: %s\n"), svc->sc_name);
6822 		return (ret);
6823 	}
6824 
6825 	/*
6826 	 * We should always be able to get the instance. It should already
6827 	 * exist because we just created it or got it. There probably is a
6828 	 * slim chance that someone may have come in and deleted it though from
6829 	 * under us.
6830 	 */
6831 	if ((ret = scf_service_get_instance(imp_svc, inst->sc_name, imp_inst))
6832 	    != 0) {
6833 		ret = scf_error();
6834 		warn(gettext("Failed to verify instance: %s\n"), inst->sc_name);
6835 		switch (ret) {
6836 		case SCF_ERROR_DELETED:
6837 			err = ENODEV;
6838 			break;
6839 		case SCF_ERROR_CONNECTION_BROKEN:
6840 			warn(gettext("Lost repository connection\n"));
6841 			err = ECONNABORTED;
6842 			break;
6843 		case SCF_ERROR_NOT_FOUND:
6844 			warn(gettext("Instance \"%s\" disappeared out from "
6845 			    "under us.\n"), inst->sc_name);
6846 			err = ENOENT;
6847 			break;
6848 		default:
6849 			bad_error("scf_service_get_instance", ret);
6850 		}
6851 
6852 		return (err);
6853 	}
6854 
6855 	/*
6856 	 * An astute observer may want to use _scf_wait_pg which would notify us
6857 	 * of a property group change, unfortunately that does not work if the
6858 	 * property group in question does not exist. So instead we have to
6859 	 * manually poll and ask smf the best way to get to it.
6860 	 */
6861 	while ((ret = scf_instance_get_pg(imp_inst, SCF_PG_RESTARTER, imp_pg))
6862 	    != SCF_SUCCESS) {
6863 		ret = scf_error();
6864 		if (ret != SCF_ERROR_NOT_FOUND) {
6865 			warn(gettext("Failed to get restarter property "
6866 			    "group for instance: %s\n"), inst->sc_name);
6867 			switch (ret) {
6868 			case SCF_ERROR_DELETED:
6869 				err = ENODEV;
6870 				break;
6871 			case SCF_ERROR_CONNECTION_BROKEN:
6872 				warn(gettext("Lost repository connection\n"));
6873 				err = ECONNABORTED;
6874 				break;
6875 			default:
6876 				bad_error("scf_service_get_instance", ret);
6877 			}
6878 
6879 			return (err);
6880 		}
6881 
6882 		ts.tv_sec = pg_timeout / NANOSEC;
6883 		ts.tv_nsec = pg_timeout % NANOSEC;
6884 
6885 		(void) nanosleep(&ts, NULL);
6886 	}
6887 
6888 	/*
6889 	 * svcadm also expects that the SCF_PROPERTY_STATE property is present.
6890 	 * So in addition to the property group being present, we need to wait
6891 	 * for the property to be there in some form.
6892 	 *
6893 	 * Note that a property group is a frozen snapshot in time. To properly
6894 	 * get beyond this, you have to refresh the property group each time.
6895 	 */
6896 	while ((ret = scf_pg_get_property(imp_pg, SCF_PROPERTY_STATE,
6897 	    imp_prop)) != 0) {
6898 
6899 		ret = scf_error();
6900 		if (ret != SCF_ERROR_NOT_FOUND) {
6901 			warn(gettext("Failed to get property %s from the "
6902 			    "restarter property group of instance %s\n"),
6903 			    SCF_PROPERTY_STATE, inst->sc_name);
6904 			switch (ret) {
6905 			case SCF_ERROR_CONNECTION_BROKEN:
6906 				warn(gettext("Lost repository connection\n"));
6907 				err = ECONNABORTED;
6908 				break;
6909 			case SCF_ERROR_DELETED:
6910 				err = ENODEV;
6911 				break;
6912 			default:
6913 				bad_error("scf_pg_get_property", ret);
6914 			}
6915 
6916 			return (err);
6917 		}
6918 
6919 		ts.tv_sec = pg_timeout / NANOSEC;
6920 		ts.tv_nsec = pg_timeout % NANOSEC;
6921 
6922 		(void) nanosleep(&ts, NULL);
6923 
6924 		ret = scf_instance_get_pg(imp_inst, SCF_PG_RESTARTER, imp_pg);
6925 		if (ret != SCF_SUCCESS) {
6926 			warn(gettext("Failed to get restarter property "
6927 			    "group for instance: %s\n"), inst->sc_name);
6928 			switch (ret) {
6929 			case SCF_ERROR_DELETED:
6930 				err = ENODEV;
6931 				break;
6932 			case SCF_ERROR_CONNECTION_BROKEN:
6933 				warn(gettext("Lost repository connection\n"));
6934 				err = ECONNABORTED;
6935 				break;
6936 			default:
6937 				bad_error("scf_service_get_instance", ret);
6938 			}
6939 
6940 			return (err);
6941 		}
6942 	}
6943 
6944 	/*
6945 	 * We don't have to free the property groups or other values that we got
6946 	 * because we stored them in global variables that are allocated and
6947 	 * freed by the routines that call into these functions. Unless of
6948 	 * course the rest of the code here that we are basing this on is
6949 	 * mistaken.
6950 	 */
6951 	return (0);
6952 }
6953 #endif
6954 
6955 /*
6956  * If the service is missing, create it, import its properties, and import the
6957  * instances.  Since the service is brand new, it should be empty, and if we
6958  * run into any existing entities (SCF_ERROR_EXISTS), abort.
6959  *
6960  * If the service exists, we want to upgrade its properties and import the
6961  * instances.  Upgrade requires a last-import snapshot, though, which are
6962  * children of instances, so first we'll have to go through the instances
6963  * looking for a last-import snapshot.  If we don't find one then we'll just
6964  * override-import the service properties (but don't delete existing
6965  * properties: another service might have declared us as a dependent).  Before
6966  * we change anything, though, we want to take the previous snapshots.  We
6967  * also give lscf_instance_import() a leg up on taking last-import snapshots
6968  * by importing the manifest's service properties into a temporary service.
6969  *
6970  * On success, returns UU_WALK_NEXT.  On failure, returns UU_WALK_ERROR and
6971  * sets lcbdata->sc_err to
6972  *   ECONNABORTED - repository connection broken
6973  *   ENOMEM - out of memory
6974  *   ENOSPC - svc.configd is out of resources
6975  *   EPERM - couldn't create temporary service (error printed)
6976  *	   - couldn't import into temp service (error printed)
6977  *	   - couldn't create service (error printed)
6978  *	   - couldn't import dependent (error printed)
6979  *	   - couldn't take snapshot (error printed)
6980  *	   - couldn't create instance (error printed)
6981  *	   - couldn't create, modify, or delete pg (error printed)
6982  *	   - couldn't create, modify, or delete dependent (error printed)
6983  *	   - couldn't import instance (error printed)
6984  *   EROFS - couldn't create temporary service (repository read-only)
6985  *	   - couldn't import into temporary service (repository read-only)
6986  *	   - couldn't create service (repository read-only)
6987  *	   - couldn't import dependent (repository read-only)
6988  *	   - couldn't create instance (repository read-only)
6989  *	   - couldn't create, modify, or delete pg or dependent
6990  *	   - couldn't import instance (repository read-only)
6991  *   EACCES - couldn't create temporary service (backend access denied)
6992  *	    - couldn't import into temporary service (backend access denied)
6993  *	    - couldn't create service (backend access denied)
6994  *	    - couldn't import dependent (backend access denied)
6995  *	    - couldn't create instance (backend access denied)
6996  *	    - couldn't create, modify, or delete pg or dependent
6997  *	    - couldn't import instance (backend access denied)
6998  *   EINVAL - service name is invalid (error printed)
6999  *	    - service name is too long (error printed)
7000  *	    - s has invalid pgroup (error printed)
7001  *	    - s has invalid dependent (error printed)
7002  *	    - instance name is invalid (error printed)
7003  *	    - instance entity_t is invalid (error printed)
7004  *   EEXIST - couldn't create temporary service (already exists) (error printed)
7005  *	    - couldn't import dependent (dependency pg already exists) (printed)
7006  *	    - dependency collision in dependent service (error printed)
7007  *   EBUSY - temporary service deleted (error printed)
7008  *	   - property group added to temporary service (error printed)
7009  *	   - new property group changed or was deleted (error printed)
7010  *	   - service was added unexpectedly (error printed)
7011  *	   - service was deleted unexpectedly (error printed)
7012  *	   - property group added to new service (error printed)
7013  *	   - instance added unexpectedly (error printed)
7014  *	   - instance deleted unexpectedly (error printed)
7015  *	   - dependent service deleted unexpectedly (error printed)
7016  *	   - pg was added, changed, or deleted (error printed)
7017  *	   - dependent pg changed (error printed)
7018  *	   - temporary instance added, changed, or deleted (error printed)
7019  *   EBADF - a last-import snapshot is corrupt (error printed)
7020  *	   - the service is corrupt (error printed)
7021  *	   - a dependent is corrupt (error printed)
7022  *	   - an instance is corrupt (error printed)
7023  *	   - an instance has a corrupt last-import snapshot (error printed)
7024  *	   - dependent target has a corrupt snapshot (error printed)
7025  *   -1 - unknown libscf error (error printed)
7026  */
7027 static int
7028 lscf_service_import(void *v, void *pvt)
7029 {
7030 	entity_t *s = v;
7031 	scf_callback_t cbdata;
7032 	scf_callback_t *lcbdata = pvt;
7033 	scf_scope_t *scope = lcbdata->sc_parent;
7034 	entity_t *inst, linst;
7035 	int r;
7036 	int fresh = 0;
7037 	scf_snaplevel_t *running;
7038 	int have_ge = 0;
7039 
7040 	const char * const ts_deleted = gettext("Temporary service svc:/%s "
7041 	    "was deleted unexpectedly.\n");
7042 	const char * const ts_pg_added = gettext("Temporary service svc:/%s "
7043 	    "changed unexpectedly (property group added).\n");
7044 	const char * const s_deleted =
7045 	    gettext("%s was deleted unexpectedly.\n");
7046 	const char * const i_deleted =
7047 	    gettext("%s changed unexpectedly (instance \"%s\" deleted).\n");
7048 	const char * const badsnap = gettext("\"%s\" snapshot of svc:/%s:%s "
7049 	    "is corrupt (missing service snaplevel).\n");
7050 	const char * const s_mfile_upd =
7051 	    gettext("Unable to update the manifest file connection "
7052 	    "for %s\n");
7053 
7054 	li_only = 0;
7055 	/* Validate the service name */
7056 	if (scf_scope_get_service(scope, s->sc_name, imp_svc) != 0) {
7057 		switch (scf_error()) {
7058 		case SCF_ERROR_CONNECTION_BROKEN:
7059 			return (stash_scferror(lcbdata));
7060 
7061 		case SCF_ERROR_INVALID_ARGUMENT:
7062 			warn(gettext("\"%s\" is an invalid service name.  "
7063 			    "Cannot import.\n"), s->sc_name);
7064 			return (stash_scferror(lcbdata));
7065 
7066 		case SCF_ERROR_NOT_FOUND:
7067 			break;
7068 
7069 		case SCF_ERROR_HANDLE_MISMATCH:
7070 		case SCF_ERROR_NOT_BOUND:
7071 		case SCF_ERROR_NOT_SET:
7072 		default:
7073 			bad_error("scf_scope_get_service", scf_error());
7074 		}
7075 	}
7076 
7077 	/* create temporary service */
7078 	/*
7079 	 * the size of the buffer was reduced to max_scf_name_len to prevent
7080 	 * hitting bug 6681151.  After the bug fix, the size of the buffer
7081 	 * should be restored to its original value (max_scf_name_len +1)
7082 	 */
7083 	r = snprintf(imp_tsname, max_scf_name_len, "TEMP/%s", s->sc_name);
7084 	if (r < 0)
7085 		bad_error("snprintf", errno);
7086 	if (r > max_scf_name_len) {
7087 		warn(gettext(
7088 		    "Service name \"%s\" is too long.  Cannot import.\n"),
7089 		    s->sc_name);
7090 		lcbdata->sc_err = EINVAL;
7091 		return (UU_WALK_ERROR);
7092 	}
7093 
7094 	if (scf_scope_add_service(imp_scope, imp_tsname, imp_tsvc) != 0) {
7095 		switch (scf_error()) {
7096 		case SCF_ERROR_CONNECTION_BROKEN:
7097 		case SCF_ERROR_NO_RESOURCES:
7098 		case SCF_ERROR_BACKEND_READONLY:
7099 		case SCF_ERROR_BACKEND_ACCESS:
7100 			return (stash_scferror(lcbdata));
7101 
7102 		case SCF_ERROR_EXISTS:
7103 			warn(gettext(
7104 			    "Temporary service \"%s\" must be deleted before "
7105 			    "this manifest can be imported.\n"), imp_tsname);
7106 			return (stash_scferror(lcbdata));
7107 
7108 		case SCF_ERROR_PERMISSION_DENIED:
7109 			warn(gettext("Could not create temporary service "
7110 			    "\"%s\" (permission denied).\n"), imp_tsname);
7111 			return (stash_scferror(lcbdata));
7112 
7113 		case SCF_ERROR_INVALID_ARGUMENT:
7114 		case SCF_ERROR_HANDLE_MISMATCH:
7115 		case SCF_ERROR_NOT_BOUND:
7116 		case SCF_ERROR_NOT_SET:
7117 		default:
7118 			bad_error("scf_scope_add_service", scf_error());
7119 		}
7120 	}
7121 
7122 	r = snprintf(imp_str, imp_str_sz, "svc:/%s", imp_tsname);
7123 	if (r < 0)
7124 		bad_error("snprintf", errno);
7125 
7126 	cbdata.sc_handle = lcbdata->sc_handle;
7127 	cbdata.sc_parent = imp_tsvc;
7128 	cbdata.sc_service = 1;
7129 	cbdata.sc_source_fmri = s->sc_fmri;
7130 	cbdata.sc_target_fmri = imp_str;
7131 	cbdata.sc_flags = 0;
7132 
7133 	if (uu_list_walk(s->sc_pgroups, entity_pgroup_import, &cbdata,
7134 	    UU_DEFAULT) != 0) {
7135 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7136 			bad_error("uu_list_walk", uu_error());
7137 
7138 		lcbdata->sc_err = cbdata.sc_err;
7139 		switch (cbdata.sc_err) {
7140 		case ECONNABORTED:
7141 			goto connaborted;
7142 
7143 		case ECANCELED:
7144 			warn(ts_deleted, imp_tsname);
7145 			lcbdata->sc_err = EBUSY;
7146 			return (UU_WALK_ERROR);
7147 
7148 		case EEXIST:
7149 			warn(ts_pg_added, imp_tsname);
7150 			lcbdata->sc_err = EBUSY;
7151 			return (UU_WALK_ERROR);
7152 		}
7153 
7154 		r = UU_WALK_ERROR;
7155 		goto deltemp;
7156 	}
7157 
7158 	if (uu_list_walk(s->sc_dependents, entity_pgroup_import, &cbdata,
7159 	    UU_DEFAULT) != 0) {
7160 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7161 			bad_error("uu_list_walk", uu_error());
7162 
7163 		lcbdata->sc_err = cbdata.sc_err;
7164 		switch (cbdata.sc_err) {
7165 		case ECONNABORTED:
7166 			goto connaborted;
7167 
7168 		case ECANCELED:
7169 			warn(ts_deleted, imp_tsname);
7170 			lcbdata->sc_err = EBUSY;
7171 			return (UU_WALK_ERROR);
7172 
7173 		case EEXIST:
7174 			warn(ts_pg_added, imp_tsname);
7175 			lcbdata->sc_err = EBUSY;
7176 			return (UU_WALK_ERROR);
7177 		}
7178 
7179 		r = UU_WALK_ERROR;
7180 		goto deltemp;
7181 	}
7182 
7183 	if (scf_scope_get_service(scope, s->sc_name, imp_svc) != 0) {
7184 		switch (scf_error()) {
7185 		case SCF_ERROR_NOT_FOUND:
7186 			break;
7187 
7188 		case SCF_ERROR_CONNECTION_BROKEN:
7189 			goto connaborted;
7190 
7191 		case SCF_ERROR_INVALID_ARGUMENT:
7192 		case SCF_ERROR_HANDLE_MISMATCH:
7193 		case SCF_ERROR_NOT_BOUND:
7194 		case SCF_ERROR_NOT_SET:
7195 		default:
7196 			bad_error("scf_scope_get_service", scf_error());
7197 		}
7198 
7199 		if (scf_scope_add_service(scope, s->sc_name, imp_svc) != 0) {
7200 			switch (scf_error()) {
7201 			case SCF_ERROR_CONNECTION_BROKEN:
7202 				goto connaborted;
7203 
7204 			case SCF_ERROR_NO_RESOURCES:
7205 			case SCF_ERROR_BACKEND_READONLY:
7206 			case SCF_ERROR_BACKEND_ACCESS:
7207 				r = stash_scferror(lcbdata);
7208 				goto deltemp;
7209 
7210 			case SCF_ERROR_EXISTS:
7211 				warn(gettext("Scope \"%s\" changed unexpectedly"
7212 				    " (service \"%s\" added).\n"),
7213 				    SCF_SCOPE_LOCAL, s->sc_name);
7214 				lcbdata->sc_err = EBUSY;
7215 				goto deltemp;
7216 
7217 			case SCF_ERROR_PERMISSION_DENIED:
7218 				warn(gettext("Could not create service \"%s\" "
7219 				    "(permission denied).\n"), s->sc_name);
7220 				goto deltemp;
7221 
7222 			case SCF_ERROR_INVALID_ARGUMENT:
7223 			case SCF_ERROR_HANDLE_MISMATCH:
7224 			case SCF_ERROR_NOT_BOUND:
7225 			case SCF_ERROR_NOT_SET:
7226 			default:
7227 				bad_error("scf_scope_add_service", scf_error());
7228 			}
7229 		}
7230 
7231 		s->sc_import_state = IMPORT_PROP_BEGUN;
7232 
7233 		/* import service properties */
7234 		cbdata.sc_handle = lcbdata->sc_handle;
7235 		cbdata.sc_parent = imp_svc;
7236 		cbdata.sc_service = 1;
7237 		cbdata.sc_flags = lcbdata->sc_flags;
7238 		cbdata.sc_source_fmri = s->sc_fmri;
7239 		cbdata.sc_target_fmri = s->sc_fmri;
7240 
7241 		if (uu_list_walk(s->sc_pgroups, entity_pgroup_import,
7242 		    &cbdata, UU_DEFAULT) != 0) {
7243 			if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7244 				bad_error("uu_list_walk", uu_error());
7245 
7246 			lcbdata->sc_err = cbdata.sc_err;
7247 			switch (cbdata.sc_err) {
7248 			case ECONNABORTED:
7249 				goto connaborted;
7250 
7251 			case ECANCELED:
7252 				warn(s_deleted, s->sc_fmri);
7253 				lcbdata->sc_err = EBUSY;
7254 				return (UU_WALK_ERROR);
7255 
7256 			case EEXIST:
7257 				warn(gettext("%s changed unexpectedly "
7258 				    "(property group added).\n"), s->sc_fmri);
7259 				lcbdata->sc_err = EBUSY;
7260 				return (UU_WALK_ERROR);
7261 
7262 			case EINVAL:
7263 				/* caught above */
7264 				bad_error("entity_pgroup_import",
7265 				    cbdata.sc_err);
7266 			}
7267 
7268 			r = UU_WALK_ERROR;
7269 			goto deltemp;
7270 		}
7271 
7272 		cbdata.sc_trans = NULL;
7273 		cbdata.sc_flags = 0;
7274 		if (uu_list_walk(s->sc_dependents, lscf_dependent_import,
7275 		    &cbdata, UU_DEFAULT) != 0) {
7276 			if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7277 				bad_error("uu_list_walk", uu_error());
7278 
7279 			lcbdata->sc_err = cbdata.sc_err;
7280 			if (cbdata.sc_err == ECONNABORTED)
7281 				goto connaborted;
7282 			r = UU_WALK_ERROR;
7283 			goto deltemp;
7284 		}
7285 
7286 		s->sc_import_state = IMPORT_PROP_DONE;
7287 
7288 		/*
7289 		 * This is a new service, so we can't take previous snapshots
7290 		 * or upgrade service properties.
7291 		 */
7292 		fresh = 1;
7293 		goto instances;
7294 	}
7295 
7296 	/* Clear sc_seen for the instances. */
7297 	if (uu_list_walk(s->sc_u.sc_service.sc_service_instances, clear_int,
7298 	    (void *)offsetof(entity_t, sc_seen), UU_DEFAULT) != 0)
7299 		bad_error("uu_list_walk", uu_error());
7300 
7301 	/*
7302 	 * Take previous snapshots for all instances.  Even for ones not
7303 	 * mentioned in the bundle, since we might change their service
7304 	 * properties.
7305 	 */
7306 	if (scf_iter_service_instances(imp_iter, imp_svc) != 0) {
7307 		switch (scf_error()) {
7308 		case SCF_ERROR_CONNECTION_BROKEN:
7309 			goto connaborted;
7310 
7311 		case SCF_ERROR_DELETED:
7312 			warn(s_deleted, s->sc_fmri);
7313 			lcbdata->sc_err = EBUSY;
7314 			r = UU_WALK_ERROR;
7315 			goto deltemp;
7316 
7317 		case SCF_ERROR_HANDLE_MISMATCH:
7318 		case SCF_ERROR_NOT_BOUND:
7319 		case SCF_ERROR_NOT_SET:
7320 		default:
7321 			bad_error("scf_iter_service_instances", scf_error());
7322 		}
7323 	}
7324 
7325 	for (;;) {
7326 		r = scf_iter_next_instance(imp_iter, imp_inst);
7327 		if (r == 0)
7328 			break;
7329 		if (r != 1) {
7330 			switch (scf_error()) {
7331 			case SCF_ERROR_DELETED:
7332 				warn(s_deleted, s->sc_fmri);
7333 				lcbdata->sc_err = EBUSY;
7334 				r = UU_WALK_ERROR;
7335 				goto deltemp;
7336 
7337 			case SCF_ERROR_CONNECTION_BROKEN:
7338 				goto connaborted;
7339 
7340 			case SCF_ERROR_NOT_BOUND:
7341 			case SCF_ERROR_HANDLE_MISMATCH:
7342 			case SCF_ERROR_INVALID_ARGUMENT:
7343 			case SCF_ERROR_NOT_SET:
7344 			default:
7345 				bad_error("scf_iter_next_instance",
7346 				    scf_error());
7347 			}
7348 		}
7349 
7350 		if (scf_instance_get_name(imp_inst, imp_str, imp_str_sz) < 0) {
7351 			switch (scf_error()) {
7352 			case SCF_ERROR_DELETED:
7353 				continue;
7354 
7355 			case SCF_ERROR_CONNECTION_BROKEN:
7356 				goto connaborted;
7357 
7358 			case SCF_ERROR_NOT_SET:
7359 			case SCF_ERROR_NOT_BOUND:
7360 			default:
7361 				bad_error("scf_instance_get_name", scf_error());
7362 			}
7363 		}
7364 
7365 		if (g_verbose)
7366 			warn(gettext(
7367 			    "Taking \"%s\" snapshot for svc:/%s:%s.\n"),
7368 			    snap_previous, s->sc_name, imp_str);
7369 
7370 		r = take_snap(imp_inst, snap_previous, imp_snap);
7371 		switch (r) {
7372 		case 0:
7373 			break;
7374 
7375 		case ECANCELED:
7376 			continue;
7377 
7378 		case ECONNABORTED:
7379 			goto connaborted;
7380 
7381 		case EPERM:
7382 			warn(gettext("Could not take \"%s\" snapshot of "
7383 			    "svc:/%s:%s (permission denied).\n"),
7384 			    snap_previous, s->sc_name, imp_str);
7385 			lcbdata->sc_err = r;
7386 			return (UU_WALK_ERROR);
7387 
7388 		case ENOSPC:
7389 		case -1:
7390 			lcbdata->sc_err = r;
7391 			r = UU_WALK_ERROR;
7392 			goto deltemp;
7393 
7394 		default:
7395 			bad_error("take_snap", r);
7396 		}
7397 
7398 		linst.sc_name = imp_str;
7399 		inst = uu_list_find(s->sc_u.sc_service.sc_service_instances,
7400 		    &linst, NULL, NULL);
7401 		if (inst != NULL) {
7402 			inst->sc_import_state = IMPORT_PREVIOUS;
7403 			inst->sc_seen = 1;
7404 		}
7405 	}
7406 
7407 	/*
7408 	 * Create the new instances and take previous snapshots of
7409 	 * them.  This is not necessary, but it maximizes data preservation.
7410 	 */
7411 	for (inst = uu_list_first(s->sc_u.sc_service.sc_service_instances);
7412 	    inst != NULL;
7413 	    inst = uu_list_next(s->sc_u.sc_service.sc_service_instances,
7414 	    inst)) {
7415 		if (inst->sc_seen)
7416 			continue;
7417 
7418 		if (scf_service_add_instance(imp_svc, inst->sc_name,
7419 		    imp_inst) != 0) {
7420 			switch (scf_error()) {
7421 			case SCF_ERROR_CONNECTION_BROKEN:
7422 				goto connaborted;
7423 
7424 			case SCF_ERROR_BACKEND_READONLY:
7425 			case SCF_ERROR_BACKEND_ACCESS:
7426 			case SCF_ERROR_NO_RESOURCES:
7427 				r = stash_scferror(lcbdata);
7428 				goto deltemp;
7429 
7430 			case SCF_ERROR_EXISTS:
7431 				warn(gettext("%s changed unexpectedly "
7432 				    "(instance \"%s\" added).\n"), s->sc_fmri,
7433 				    inst->sc_name);
7434 				lcbdata->sc_err = EBUSY;
7435 				r = UU_WALK_ERROR;
7436 				goto deltemp;
7437 
7438 			case SCF_ERROR_INVALID_ARGUMENT:
7439 				warn(gettext("Service \"%s\" has instance with "
7440 				    "invalid name \"%s\".\n"), s->sc_name,
7441 				    inst->sc_name);
7442 				r = stash_scferror(lcbdata);
7443 				goto deltemp;
7444 
7445 			case SCF_ERROR_PERMISSION_DENIED:
7446 				warn(gettext("Could not create instance \"%s\" "
7447 				    "in %s (permission denied).\n"),
7448 				    inst->sc_name, s->sc_fmri);
7449 				r = stash_scferror(lcbdata);
7450 				goto deltemp;
7451 
7452 			case SCF_ERROR_HANDLE_MISMATCH:
7453 			case SCF_ERROR_NOT_BOUND:
7454 			case SCF_ERROR_NOT_SET:
7455 			default:
7456 				bad_error("scf_service_add_instance",
7457 				    scf_error());
7458 			}
7459 		}
7460 
7461 		if (g_verbose)
7462 			warn(gettext("Taking \"%s\" snapshot for "
7463 			    "new service %s.\n"), snap_previous, inst->sc_fmri);
7464 		r = take_snap(imp_inst, snap_previous, imp_snap);
7465 		switch (r) {
7466 		case 0:
7467 			break;
7468 
7469 		case ECANCELED:
7470 			warn(i_deleted, s->sc_fmri, inst->sc_name);
7471 			lcbdata->sc_err = EBUSY;
7472 			r = UU_WALK_ERROR;
7473 			goto deltemp;
7474 
7475 		case ECONNABORTED:
7476 			goto connaborted;
7477 
7478 		case EPERM:
7479 			warn(emsg_snap_perm, snap_previous, inst->sc_fmri);
7480 			lcbdata->sc_err = r;
7481 			r = UU_WALK_ERROR;
7482 			goto deltemp;
7483 
7484 		case ENOSPC:
7485 		case -1:
7486 			r = UU_WALK_ERROR;
7487 			goto deltemp;
7488 
7489 		default:
7490 			bad_error("take_snap", r);
7491 		}
7492 	}
7493 
7494 	s->sc_import_state = IMPORT_PREVIOUS;
7495 
7496 	/*
7497 	 * Upgrade service properties, if we can find a last-import snapshot.
7498 	 * Any will do because we don't support different service properties
7499 	 * in different manifests, so all snaplevels of the service in all of
7500 	 * the last-import snapshots of the instances should be the same.
7501 	 */
7502 	if (scf_iter_service_instances(imp_iter, imp_svc) != 0) {
7503 		switch (scf_error()) {
7504 		case SCF_ERROR_CONNECTION_BROKEN:
7505 			goto connaborted;
7506 
7507 		case SCF_ERROR_DELETED:
7508 			warn(s_deleted, s->sc_fmri);
7509 			lcbdata->sc_err = EBUSY;
7510 			r = UU_WALK_ERROR;
7511 			goto deltemp;
7512 
7513 		case SCF_ERROR_HANDLE_MISMATCH:
7514 		case SCF_ERROR_NOT_BOUND:
7515 		case SCF_ERROR_NOT_SET:
7516 		default:
7517 			bad_error("scf_iter_service_instances", scf_error());
7518 		}
7519 	}
7520 
7521 	for (;;) {
7522 		r = scf_iter_next_instance(imp_iter, imp_inst);
7523 		if (r == -1) {
7524 			switch (scf_error()) {
7525 			case SCF_ERROR_DELETED:
7526 				warn(s_deleted, s->sc_fmri);
7527 				lcbdata->sc_err = EBUSY;
7528 				r = UU_WALK_ERROR;
7529 				goto deltemp;
7530 
7531 			case SCF_ERROR_CONNECTION_BROKEN:
7532 				goto connaborted;
7533 
7534 			case SCF_ERROR_NOT_BOUND:
7535 			case SCF_ERROR_HANDLE_MISMATCH:
7536 			case SCF_ERROR_INVALID_ARGUMENT:
7537 			case SCF_ERROR_NOT_SET:
7538 			default:
7539 				bad_error("scf_iter_next_instance",
7540 				    scf_error());
7541 			}
7542 		}
7543 
7544 		if (r == 0) {
7545 			/*
7546 			 * Didn't find any last-import snapshots.  Override-
7547 			 * import the properties.  Unless one of the instances
7548 			 * has a general/enabled property, in which case we're
7549 			 * probably running a last-import-capable svccfg for
7550 			 * the first time, and we should only take the
7551 			 * last-import snapshot.
7552 			 */
7553 			if (have_ge) {
7554 				pgroup_t *mfpg;
7555 				scf_callback_t mfcbdata;
7556 
7557 				li_only = 1;
7558 				no_refresh = 1;
7559 				/*
7560 				 * Need to go ahead and import the manifestfiles
7561 				 * pg if it exists. If the last-import snapshot
7562 				 * upgrade code is ever removed this code can
7563 				 * be removed as well.
7564 				 */
7565 				mfpg = internal_pgroup_find(s,
7566 				    SCF_PG_MANIFESTFILES, SCF_GROUP_FRAMEWORK);
7567 
7568 				if (mfpg) {
7569 					mfcbdata.sc_handle = g_hndl;
7570 					mfcbdata.sc_parent = imp_svc;
7571 					mfcbdata.sc_service = 1;
7572 					mfcbdata.sc_flags = SCI_FORCE;
7573 					mfcbdata.sc_source_fmri = s->sc_fmri;
7574 					mfcbdata.sc_target_fmri = s->sc_fmri;
7575 					if (entity_pgroup_import(mfpg,
7576 					    &mfcbdata) != UU_WALK_NEXT) {
7577 						warn(s_mfile_upd, s->sc_fmri);
7578 						r = UU_WALK_ERROR;
7579 						goto deltemp;
7580 					}
7581 				}
7582 				break;
7583 			}
7584 
7585 			s->sc_import_state = IMPORT_PROP_BEGUN;
7586 
7587 			cbdata.sc_handle = g_hndl;
7588 			cbdata.sc_parent = imp_svc;
7589 			cbdata.sc_service = 1;
7590 			cbdata.sc_flags = SCI_FORCE;
7591 			cbdata.sc_source_fmri = s->sc_fmri;
7592 			cbdata.sc_target_fmri = s->sc_fmri;
7593 			if (uu_list_walk(s->sc_pgroups, entity_pgroup_import,
7594 			    &cbdata, UU_DEFAULT) != 0) {
7595 				if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7596 					bad_error("uu_list_walk", uu_error());
7597 				lcbdata->sc_err = cbdata.sc_err;
7598 				switch (cbdata.sc_err) {
7599 				case ECONNABORTED:
7600 					goto connaborted;
7601 
7602 				case ECANCELED:
7603 					warn(s_deleted, s->sc_fmri);
7604 					lcbdata->sc_err = EBUSY;
7605 					break;
7606 
7607 				case EINVAL:	/* caught above */
7608 				case EEXIST:
7609 					bad_error("entity_pgroup_import",
7610 					    cbdata.sc_err);
7611 				}
7612 
7613 				r = UU_WALK_ERROR;
7614 				goto deltemp;
7615 			}
7616 
7617 			cbdata.sc_trans = NULL;
7618 			cbdata.sc_flags = 0;
7619 			if (uu_list_walk(s->sc_dependents,
7620 			    lscf_dependent_import, &cbdata, UU_DEFAULT) != 0) {
7621 				if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7622 					bad_error("uu_list_walk", uu_error());
7623 				lcbdata->sc_err = cbdata.sc_err;
7624 				if (cbdata.sc_err == ECONNABORTED)
7625 					goto connaborted;
7626 				r = UU_WALK_ERROR;
7627 				goto deltemp;
7628 			}
7629 			break;
7630 		}
7631 
7632 		if (scf_instance_get_snapshot(imp_inst, snap_lastimport,
7633 		    imp_snap) != 0) {
7634 			switch (scf_error()) {
7635 			case SCF_ERROR_DELETED:
7636 				continue;
7637 
7638 			case SCF_ERROR_NOT_FOUND:
7639 				break;
7640 
7641 			case SCF_ERROR_CONNECTION_BROKEN:
7642 				goto connaborted;
7643 
7644 			case SCF_ERROR_HANDLE_MISMATCH:
7645 			case SCF_ERROR_NOT_BOUND:
7646 			case SCF_ERROR_INVALID_ARGUMENT:
7647 			case SCF_ERROR_NOT_SET:
7648 			default:
7649 				bad_error("scf_instance_get_snapshot",
7650 				    scf_error());
7651 			}
7652 
7653 			if (have_ge)
7654 				continue;
7655 
7656 			/*
7657 			 * Check for a general/enabled property.  This is how
7658 			 * we tell whether to import if there turn out to be
7659 			 * no last-import snapshots.
7660 			 */
7661 			if (scf_instance_get_pg(imp_inst, SCF_PG_GENERAL,
7662 			    imp_pg) == 0) {
7663 				if (scf_pg_get_property(imp_pg,
7664 				    SCF_PROPERTY_ENABLED, imp_prop) == 0) {
7665 					have_ge = 1;
7666 				} else {
7667 					switch (scf_error()) {
7668 					case SCF_ERROR_DELETED:
7669 					case SCF_ERROR_NOT_FOUND:
7670 						continue;
7671 
7672 					case SCF_ERROR_INVALID_ARGUMENT:
7673 					case SCF_ERROR_HANDLE_MISMATCH:
7674 					case SCF_ERROR_CONNECTION_BROKEN:
7675 					case SCF_ERROR_NOT_BOUND:
7676 					case SCF_ERROR_NOT_SET:
7677 					default:
7678 						bad_error("scf_pg_get_property",
7679 						    scf_error());
7680 					}
7681 				}
7682 			} else {
7683 				switch (scf_error()) {
7684 				case SCF_ERROR_DELETED:
7685 				case SCF_ERROR_NOT_FOUND:
7686 					continue;
7687 
7688 				case SCF_ERROR_CONNECTION_BROKEN:
7689 					goto connaborted;
7690 
7691 				case SCF_ERROR_NOT_BOUND:
7692 				case SCF_ERROR_NOT_SET:
7693 				case SCF_ERROR_INVALID_ARGUMENT:
7694 				case SCF_ERROR_HANDLE_MISMATCH:
7695 				default:
7696 					bad_error("scf_instance_get_pg",
7697 					    scf_error());
7698 				}
7699 			}
7700 			continue;
7701 		}
7702 
7703 		/* find service snaplevel */
7704 		r = get_snaplevel(imp_snap, 1, imp_snpl);
7705 		switch (r) {
7706 		case 0:
7707 			break;
7708 
7709 		case ECONNABORTED:
7710 			goto connaborted;
7711 
7712 		case ECANCELED:
7713 			continue;
7714 
7715 		case ENOENT:
7716 			if (scf_instance_get_name(imp_inst, imp_str,
7717 			    imp_str_sz) < 0)
7718 				(void) strcpy(imp_str, "?");
7719 			warn(badsnap, snap_lastimport, s->sc_name, imp_str);
7720 			lcbdata->sc_err = EBADF;
7721 			r = UU_WALK_ERROR;
7722 			goto deltemp;
7723 
7724 		default:
7725 			bad_error("get_snaplevel", r);
7726 		}
7727 
7728 		if (scf_instance_get_snapshot(imp_inst, snap_running,
7729 		    imp_rsnap) != 0) {
7730 			switch (scf_error()) {
7731 			case SCF_ERROR_DELETED:
7732 				continue;
7733 
7734 			case SCF_ERROR_NOT_FOUND:
7735 				break;
7736 
7737 			case SCF_ERROR_CONNECTION_BROKEN:
7738 				goto connaborted;
7739 
7740 			case SCF_ERROR_INVALID_ARGUMENT:
7741 			case SCF_ERROR_HANDLE_MISMATCH:
7742 			case SCF_ERROR_NOT_BOUND:
7743 			case SCF_ERROR_NOT_SET:
7744 			default:
7745 				bad_error("scf_instance_get_snapshot",
7746 				    scf_error());
7747 			}
7748 			running = NULL;
7749 		} else {
7750 			r = get_snaplevel(imp_rsnap, 1, imp_rsnpl);
7751 			switch (r) {
7752 			case 0:
7753 				running = imp_rsnpl;
7754 				break;
7755 
7756 			case ECONNABORTED:
7757 				goto connaborted;
7758 
7759 			case ECANCELED:
7760 				continue;
7761 
7762 			case ENOENT:
7763 				if (scf_instance_get_name(imp_inst, imp_str,
7764 				    imp_str_sz) < 0)
7765 					(void) strcpy(imp_str, "?");
7766 				warn(badsnap, snap_running, s->sc_name,
7767 				    imp_str);
7768 				lcbdata->sc_err = EBADF;
7769 				r = UU_WALK_ERROR;
7770 				goto deltemp;
7771 
7772 			default:
7773 				bad_error("get_snaplevel", r);
7774 			}
7775 		}
7776 
7777 		if (g_verbose) {
7778 			if (scf_instance_get_name(imp_inst, imp_str,
7779 			    imp_str_sz) < 0)
7780 				(void) strcpy(imp_str, "?");
7781 			warn(gettext("Upgrading properties of %s according to "
7782 			    "instance \"%s\".\n"), s->sc_fmri, imp_str);
7783 		}
7784 
7785 		/* upgrade service properties */
7786 		r = upgrade_props(imp_svc, running, imp_snpl, s);
7787 		if (r == 0)
7788 			break;
7789 
7790 		switch (r) {
7791 		case ECONNABORTED:
7792 			goto connaborted;
7793 
7794 		case ECANCELED:
7795 			warn(s_deleted, s->sc_fmri);
7796 			lcbdata->sc_err = EBUSY;
7797 			break;
7798 
7799 		case ENODEV:
7800 			if (scf_instance_get_name(imp_inst, imp_str,
7801 			    imp_str_sz) < 0)
7802 				(void) strcpy(imp_str, "?");
7803 			warn(i_deleted, s->sc_fmri, imp_str);
7804 			lcbdata->sc_err = EBUSY;
7805 			break;
7806 
7807 		default:
7808 			lcbdata->sc_err = r;
7809 		}
7810 
7811 		r = UU_WALK_ERROR;
7812 		goto deltemp;
7813 	}
7814 
7815 	s->sc_import_state = IMPORT_PROP_DONE;
7816 
7817 instances:
7818 	/* import instances */
7819 	cbdata.sc_handle = lcbdata->sc_handle;
7820 	cbdata.sc_parent = imp_svc;
7821 	cbdata.sc_service = 1;
7822 	cbdata.sc_flags = lcbdata->sc_flags | (fresh ? SCI_FRESH : 0);
7823 	cbdata.sc_general = NULL;
7824 
7825 	if (uu_list_walk(s->sc_u.sc_service.sc_service_instances,
7826 	    lscf_instance_import, &cbdata, UU_DEFAULT) != 0) {
7827 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7828 			bad_error("uu_list_walk", uu_error());
7829 
7830 		lcbdata->sc_err = cbdata.sc_err;
7831 		if (cbdata.sc_err == ECONNABORTED)
7832 			goto connaborted;
7833 		r = UU_WALK_ERROR;
7834 		goto deltemp;
7835 	}
7836 
7837 	s->sc_import_state = IMPORT_COMPLETE;
7838 	r = UU_WALK_NEXT;
7839 
7840 deltemp:
7841 	/* delete temporary service */
7842 	if (scf_service_delete(imp_tsvc) != 0) {
7843 		switch (scf_error()) {
7844 		case SCF_ERROR_DELETED:
7845 			break;
7846 
7847 		case SCF_ERROR_CONNECTION_BROKEN:
7848 			goto connaborted;
7849 
7850 		case SCF_ERROR_EXISTS:
7851 			warn(gettext(
7852 			    "Could not delete svc:/%s (instances exist).\n"),
7853 			    imp_tsname);
7854 			break;
7855 
7856 		case SCF_ERROR_NOT_SET:
7857 		case SCF_ERROR_NOT_BOUND:
7858 		default:
7859 			bad_error("scf_service_delete", scf_error());
7860 		}
7861 	}
7862 
7863 	return (r);
7864 
7865 connaborted:
7866 	warn(gettext("Could not delete svc:/%s "
7867 	    "(repository connection broken).\n"), imp_tsname);
7868 	lcbdata->sc_err = ECONNABORTED;
7869 	return (UU_WALK_ERROR);
7870 }
7871 
7872 static const char *
7873 import_progress(int st)
7874 {
7875 	switch (st) {
7876 	case 0:
7877 		return (gettext("not reached."));
7878 
7879 	case IMPORT_PREVIOUS:
7880 		return (gettext("previous snapshot taken."));
7881 
7882 	case IMPORT_PROP_BEGUN:
7883 		return (gettext("some properties imported."));
7884 
7885 	case IMPORT_PROP_DONE:
7886 		return (gettext("properties imported."));
7887 
7888 	case IMPORT_COMPLETE:
7889 		return (gettext("imported."));
7890 
7891 	case IMPORT_REFRESHED:
7892 		return (gettext("refresh requested."));
7893 
7894 	default:
7895 #ifndef NDEBUG
7896 		(void) fprintf(stderr, "%s:%d: Unknown entity state %d.\n",
7897 		    __FILE__, __LINE__, st);
7898 #endif
7899 		abort();
7900 		/* NOTREACHED */
7901 	}
7902 }
7903 
7904 /*
7905  * Returns
7906  *   0 - success
7907  *     - fmri wasn't found (error printed)
7908  *     - entity was deleted (error printed)
7909  *     - backend denied access (error printed)
7910  *   ENOMEM - out of memory (error printed)
7911  *   ECONNABORTED - repository connection broken (error printed)
7912  *   EPERM - permission denied (error printed)
7913  *   -1 - unknown libscf error (error printed)
7914  */
7915 static int
7916 imp_refresh_fmri(const char *fmri, const char *name, const char *d_fmri)
7917 {
7918 	scf_error_t serr;
7919 	void *ent;
7920 	int issvc;
7921 	int r;
7922 
7923 	const char *deleted = gettext("Could not refresh %s (deleted).\n");
7924 	const char *dpt_deleted = gettext("Could not refresh %s "
7925 	    "(dependent \"%s\" of %s) (deleted).\n");
7926 
7927 	serr = fmri_to_entity(g_hndl, fmri, &ent, &issvc);
7928 	switch (serr) {
7929 	case SCF_ERROR_NONE:
7930 		break;
7931 
7932 	case SCF_ERROR_NO_MEMORY:
7933 		if (name == NULL)
7934 			warn(gettext("Could not refresh %s (out of memory).\n"),
7935 			    fmri);
7936 		else
7937 			warn(gettext("Could not refresh %s "
7938 			    "(dependent \"%s\" of %s) (out of memory).\n"),
7939 			    fmri, name, d_fmri);
7940 		return (ENOMEM);
7941 
7942 	case SCF_ERROR_NOT_FOUND:
7943 		if (name == NULL)
7944 			warn(deleted, fmri);
7945 		else
7946 			warn(dpt_deleted, fmri, name, d_fmri);
7947 		return (0);
7948 
7949 	case SCF_ERROR_INVALID_ARGUMENT:
7950 	case SCF_ERROR_CONSTRAINT_VIOLATED:
7951 	default:
7952 		bad_error("fmri_to_entity", serr);
7953 	}
7954 
7955 	r = refresh_entity(issvc, ent, fmri, imp_inst, imp_iter, imp_str);
7956 	switch (r) {
7957 	case 0:
7958 		break;
7959 
7960 	case ECONNABORTED:
7961 		if (name != NULL)
7962 			warn(gettext("Could not refresh %s "
7963 			    "(dependent \"%s\" of %s) "
7964 			    "(repository connection broken).\n"), fmri, name,
7965 			    d_fmri);
7966 		return (r);
7967 
7968 	case ECANCELED:
7969 		if (name == NULL)
7970 			warn(deleted, fmri);
7971 		else
7972 			warn(dpt_deleted, fmri, name, d_fmri);
7973 		return (0);
7974 
7975 	case EACCES:
7976 		if (!g_verbose)
7977 			return (0);
7978 		if (name == NULL)
7979 			warn(gettext("Could not refresh %s "
7980 			    "(backend access denied).\n"), fmri);
7981 		else
7982 			warn(gettext("Could not refresh %s "
7983 			    "(dependent \"%s\" of %s) "
7984 			    "(backend access denied).\n"), fmri, name, d_fmri);
7985 		return (0);
7986 
7987 	case EPERM:
7988 		if (name == NULL)
7989 			warn(gettext("Could not refresh %s "
7990 			    "(permission denied).\n"), fmri);
7991 		else
7992 			warn(gettext("Could not refresh %s "
7993 			    "(dependent \"%s\" of %s) "
7994 			    "(permission denied).\n"), fmri, name, d_fmri);
7995 		return (r);
7996 
7997 	case ENOSPC:
7998 		if (name == NULL)
7999 			warn(gettext("Could not refresh %s "
8000 			    "(repository server out of resources).\n"),
8001 			    fmri);
8002 		else
8003 			warn(gettext("Could not refresh %s "
8004 			    "(dependent \"%s\" of %s) "
8005 			    "(repository server out of resources).\n"),
8006 			    fmri, name, d_fmri);
8007 		return (r);
8008 
8009 	case -1:
8010 		scfwarn();
8011 		return (r);
8012 
8013 	default:
8014 		bad_error("refresh_entity", r);
8015 	}
8016 
8017 	if (issvc)
8018 		scf_service_destroy(ent);
8019 	else
8020 		scf_instance_destroy(ent);
8021 
8022 	return (0);
8023 }
8024 
8025 static int
8026 alloc_imp_globals()
8027 {
8028 	int r;
8029 
8030 	const char * const emsg_nomem = gettext("Out of memory.\n");
8031 	const char * const emsg_nores =
8032 	    gettext("svc.configd is out of resources.\n");
8033 
8034 	imp_str_sz = ((max_scf_name_len > max_scf_fmri_len) ?
8035 	    max_scf_name_len : max_scf_fmri_len) + 1;
8036 
8037 	if ((imp_scope = scf_scope_create(g_hndl)) == NULL ||
8038 	    (imp_svc = scf_service_create(g_hndl)) == NULL ||
8039 	    (imp_tsvc = scf_service_create(g_hndl)) == NULL ||
8040 	    (imp_inst = scf_instance_create(g_hndl)) == NULL ||
8041 	    (imp_tinst = scf_instance_create(g_hndl)) == NULL ||
8042 	    (imp_snap = scf_snapshot_create(g_hndl)) == NULL ||
8043 	    (imp_lisnap = scf_snapshot_create(g_hndl)) == NULL ||
8044 	    (imp_tlisnap = scf_snapshot_create(g_hndl)) == NULL ||
8045 	    (imp_rsnap = scf_snapshot_create(g_hndl)) == NULL ||
8046 	    (imp_snpl = scf_snaplevel_create(g_hndl)) == NULL ||
8047 	    (imp_rsnpl = scf_snaplevel_create(g_hndl)) == NULL ||
8048 	    (imp_pg = scf_pg_create(g_hndl)) == NULL ||
8049 	    (imp_pg2 = scf_pg_create(g_hndl)) == NULL ||
8050 	    (imp_prop = scf_property_create(g_hndl)) == NULL ||
8051 	    (imp_iter = scf_iter_create(g_hndl)) == NULL ||
8052 	    (imp_rpg_iter = scf_iter_create(g_hndl)) == NULL ||
8053 	    (imp_up_iter = scf_iter_create(g_hndl)) == NULL ||
8054 	    (imp_tx = scf_transaction_create(g_hndl)) == NULL ||
8055 	    (imp_str = malloc(imp_str_sz)) == NULL ||
8056 	    (imp_tsname = malloc(max_scf_name_len + 1)) == NULL ||
8057 	    (imp_fe1 = malloc(max_scf_fmri_len + 1)) == NULL ||
8058 	    (imp_fe2 = malloc(max_scf_fmri_len + 1)) == NULL ||
8059 	    (imp_deleted_dpts = uu_list_create(string_pool, NULL, 0)) == NULL ||
8060 	    (ud_inst = scf_instance_create(g_hndl)) == NULL ||
8061 	    (ud_snpl = scf_snaplevel_create(g_hndl)) == NULL ||
8062 	    (ud_pg = scf_pg_create(g_hndl)) == NULL ||
8063 	    (ud_cur_depts_pg = scf_pg_create(g_hndl)) == NULL ||
8064 	    (ud_run_dpts_pg = scf_pg_create(g_hndl)) == NULL ||
8065 	    (ud_prop = scf_property_create(g_hndl)) == NULL ||
8066 	    (ud_dpt_prop = scf_property_create(g_hndl)) == NULL ||
8067 	    (ud_val = scf_value_create(g_hndl)) == NULL ||
8068 	    (ud_iter = scf_iter_create(g_hndl)) == NULL ||
8069 	    (ud_iter2 = scf_iter_create(g_hndl)) == NULL ||
8070 	    (ud_tx = scf_transaction_create(g_hndl)) == NULL ||
8071 	    (ud_ctarg = malloc(max_scf_value_len + 1)) == NULL ||
8072 	    (ud_oldtarg = malloc(max_scf_value_len + 1)) == NULL ||
8073 	    (ud_name = malloc(max_scf_name_len + 1)) == NULL) {
8074 		if (scf_error() == SCF_ERROR_NO_RESOURCES)
8075 			warn(emsg_nores);
8076 		else
8077 			warn(emsg_nomem);
8078 
8079 		return (-1);
8080 	}
8081 
8082 	r = load_init();
8083 	switch (r) {
8084 	case 0:
8085 		break;
8086 
8087 	case ENOMEM:
8088 		warn(emsg_nomem);
8089 		return (-1);
8090 
8091 	default:
8092 		bad_error("load_init", r);
8093 	}
8094 
8095 	return (0);
8096 }
8097 
8098 static void
8099 free_imp_globals()
8100 {
8101 	pgroup_t *old_dpt;
8102 	void *cookie;
8103 
8104 	load_fini();
8105 
8106 	free(ud_ctarg);
8107 	free(ud_oldtarg);
8108 	free(ud_name);
8109 	ud_ctarg = ud_oldtarg = ud_name = NULL;
8110 
8111 	scf_transaction_destroy(ud_tx);
8112 	ud_tx = NULL;
8113 	scf_iter_destroy(ud_iter);
8114 	scf_iter_destroy(ud_iter2);
8115 	ud_iter = ud_iter2 = NULL;
8116 	scf_value_destroy(ud_val);
8117 	ud_val = NULL;
8118 	scf_property_destroy(ud_prop);
8119 	scf_property_destroy(ud_dpt_prop);
8120 	ud_prop = ud_dpt_prop = NULL;
8121 	scf_pg_destroy(ud_pg);
8122 	scf_pg_destroy(ud_cur_depts_pg);
8123 	scf_pg_destroy(ud_run_dpts_pg);
8124 	ud_pg = ud_cur_depts_pg = ud_run_dpts_pg = NULL;
8125 	scf_snaplevel_destroy(ud_snpl);
8126 	ud_snpl = NULL;
8127 	scf_instance_destroy(ud_inst);
8128 	ud_inst = NULL;
8129 
8130 	free(imp_str);
8131 	free(imp_tsname);
8132 	free(imp_fe1);
8133 	free(imp_fe2);
8134 	imp_str = imp_tsname = imp_fe1 = imp_fe2 = NULL;
8135 
8136 	cookie = NULL;
8137 	while ((old_dpt = uu_list_teardown(imp_deleted_dpts, &cookie)) !=
8138 	    NULL) {
8139 		free((char *)old_dpt->sc_pgroup_name);
8140 		free((char *)old_dpt->sc_pgroup_fmri);
8141 		internal_pgroup_free(old_dpt);
8142 	}
8143 	uu_list_destroy(imp_deleted_dpts);
8144 
8145 	scf_transaction_destroy(imp_tx);
8146 	imp_tx = NULL;
8147 	scf_iter_destroy(imp_iter);
8148 	scf_iter_destroy(imp_rpg_iter);
8149 	scf_iter_destroy(imp_up_iter);
8150 	imp_iter = imp_rpg_iter = imp_up_iter = NULL;
8151 	scf_property_destroy(imp_prop);
8152 	imp_prop = NULL;
8153 	scf_pg_destroy(imp_pg);
8154 	scf_pg_destroy(imp_pg2);
8155 	imp_pg = imp_pg2 = NULL;
8156 	scf_snaplevel_destroy(imp_snpl);
8157 	scf_snaplevel_destroy(imp_rsnpl);
8158 	imp_snpl = imp_rsnpl = NULL;
8159 	scf_snapshot_destroy(imp_snap);
8160 	scf_snapshot_destroy(imp_lisnap);
8161 	scf_snapshot_destroy(imp_tlisnap);
8162 	scf_snapshot_destroy(imp_rsnap);
8163 	imp_snap = imp_lisnap = imp_tlisnap = imp_rsnap = NULL;
8164 	scf_instance_destroy(imp_inst);
8165 	scf_instance_destroy(imp_tinst);
8166 	imp_inst = imp_tinst = NULL;
8167 	scf_service_destroy(imp_svc);
8168 	scf_service_destroy(imp_tsvc);
8169 	imp_svc = imp_tsvc = NULL;
8170 	scf_scope_destroy(imp_scope);
8171 	imp_scope = NULL;
8172 
8173 	load_fini();
8174 }
8175 
8176 int
8177 lscf_bundle_import(bundle_t *bndl, const char *filename, uint_t flags)
8178 {
8179 	scf_callback_t cbdata;
8180 	int result = 0;
8181 	entity_t *svc, *inst;
8182 	uu_list_t *insts;
8183 	int r;
8184 	pgroup_t *old_dpt;
8185 	int annotation_set = 0;
8186 
8187 	const char * const emsg_nomem = gettext("Out of memory.\n");
8188 	const char * const emsg_nores =
8189 	    gettext("svc.configd is out of resources.\n");
8190 
8191 	lscf_prep_hndl();
8192 
8193 	if (alloc_imp_globals())
8194 		goto out;
8195 
8196 	if (scf_handle_get_scope(g_hndl, SCF_SCOPE_LOCAL, imp_scope) != 0) {
8197 		switch (scf_error()) {
8198 		case SCF_ERROR_CONNECTION_BROKEN:
8199 			warn(gettext("Repository connection broken.\n"));
8200 			repository_teardown();
8201 			result = -1;
8202 			goto out;
8203 
8204 		case SCF_ERROR_NOT_FOUND:
8205 		case SCF_ERROR_INVALID_ARGUMENT:
8206 		case SCF_ERROR_NOT_BOUND:
8207 		case SCF_ERROR_HANDLE_MISMATCH:
8208 		default:
8209 			bad_error("scf_handle_get_scope", scf_error());
8210 		}
8211 	}
8212 
8213 	/* Set up the auditing annotation. */
8214 	if (_scf_set_annotation(g_hndl, "svccfg import", filename) == 0) {
8215 		annotation_set = 1;
8216 	} else {
8217 		switch (scf_error()) {
8218 		case SCF_ERROR_CONNECTION_BROKEN:
8219 			warn(gettext("Repository connection broken.\n"));
8220 			repository_teardown();
8221 			result = -1;
8222 			goto out;
8223 
8224 		case SCF_ERROR_INVALID_ARGUMENT:
8225 		case SCF_ERROR_NOT_BOUND:
8226 		case SCF_ERROR_NO_RESOURCES:
8227 		case SCF_ERROR_INTERNAL:
8228 			bad_error("_scf_set_annotation", scf_error());
8229 			/* NOTREACHED */
8230 
8231 		default:
8232 			/*
8233 			 * Do not terminate import because of inability to
8234 			 * generate annotation audit event.
8235 			 */
8236 			warn(gettext("_scf_set_annotation() unexpectedly "
8237 			    "failed with return code of %d\n"), scf_error());
8238 			break;
8239 		}
8240 	}
8241 
8242 	/*
8243 	 * Clear the sc_import_state's of all services & instances so we can
8244 	 * report how far we got if we fail.
8245 	 */
8246 	for (svc = uu_list_first(bndl->sc_bundle_services);
8247 	    svc != NULL;
8248 	    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8249 		svc->sc_import_state = 0;
8250 
8251 		if (uu_list_walk(svc->sc_u.sc_service.sc_service_instances,
8252 		    clear_int, (void *)offsetof(entity_t, sc_import_state),
8253 		    UU_DEFAULT) != 0)
8254 			bad_error("uu_list_walk", uu_error());
8255 	}
8256 
8257 	cbdata.sc_handle = g_hndl;
8258 	cbdata.sc_parent = imp_scope;
8259 	cbdata.sc_flags = flags;
8260 	cbdata.sc_general = NULL;
8261 
8262 	if (uu_list_walk(bndl->sc_bundle_services, lscf_service_import,
8263 	    &cbdata, UU_DEFAULT) == 0) {
8264 		/* Success.  Refresh everything. */
8265 
8266 		if (flags & SCI_NOREFRESH || no_refresh) {
8267 			no_refresh = 0;
8268 			result = 0;
8269 			goto out;
8270 		}
8271 
8272 		for (svc = uu_list_first(bndl->sc_bundle_services);
8273 		    svc != NULL;
8274 		    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8275 			pgroup_t *dpt;
8276 
8277 			insts = svc->sc_u.sc_service.sc_service_instances;
8278 
8279 			for (inst = uu_list_first(insts);
8280 			    inst != NULL;
8281 			    inst = uu_list_next(insts, inst)) {
8282 				r = imp_refresh_fmri(inst->sc_fmri, NULL, NULL);
8283 				switch (r) {
8284 				case 0:
8285 					break;
8286 
8287 				case ENOMEM:
8288 				case ECONNABORTED:
8289 				case EPERM:
8290 				case -1:
8291 					goto progress;
8292 
8293 				default:
8294 					bad_error("imp_refresh_fmri", r);
8295 				}
8296 
8297 				inst->sc_import_state = IMPORT_REFRESHED;
8298 
8299 				for (dpt = uu_list_first(inst->sc_dependents);
8300 				    dpt != NULL;
8301 				    dpt = uu_list_next(inst->sc_dependents,
8302 				    dpt))
8303 					if (imp_refresh_fmri(
8304 					    dpt->sc_pgroup_fmri,
8305 					    dpt->sc_pgroup_name,
8306 					    inst->sc_fmri) != 0)
8307 						goto progress;
8308 			}
8309 
8310 			for (dpt = uu_list_first(svc->sc_dependents);
8311 			    dpt != NULL;
8312 			    dpt = uu_list_next(svc->sc_dependents, dpt))
8313 				if (imp_refresh_fmri(dpt->sc_pgroup_fmri,
8314 				    dpt->sc_pgroup_name, svc->sc_fmri) != 0)
8315 					goto progress;
8316 		}
8317 
8318 		for (old_dpt = uu_list_first(imp_deleted_dpts);
8319 		    old_dpt != NULL;
8320 		    old_dpt = uu_list_next(imp_deleted_dpts, old_dpt))
8321 			if (imp_refresh_fmri(old_dpt->sc_pgroup_fmri,
8322 			    old_dpt->sc_pgroup_name,
8323 			    old_dpt->sc_parent->sc_fmri) != 0)
8324 				goto progress;
8325 
8326 		result = 0;
8327 
8328 		/*
8329 		 * This snippet of code assumes that we are running svccfg as we
8330 		 * normally do -- witih svc.startd running. Of course, that is
8331 		 * not actually the case all the time because we also use a
8332 		 * varient of svc.configd and svccfg which are only meant to
8333 		 * run during the build process. During this time we have no
8334 		 * svc.startd, so this check would hang the build process.
8335 		 */
8336 #ifndef NATIVE_BUILD
8337 		/*
8338 		 * Verify that the restarter group is preset
8339 		 */
8340 		for (svc = uu_list_first(bndl->sc_bundle_services);
8341 		    svc != NULL;
8342 		    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8343 
8344 			insts = svc->sc_u.sc_service.sc_service_instances;
8345 
8346 			for (inst = uu_list_first(insts);
8347 			    inst != NULL;
8348 			    inst = uu_list_next(insts, inst)) {
8349 				if (lscf_instance_verify(imp_scope, svc,
8350 				    inst) != 0)
8351 					goto progress;
8352 			}
8353 		}
8354 #endif
8355 		goto out;
8356 
8357 	}
8358 
8359 	if (uu_error() != UU_ERROR_CALLBACK_FAILED)
8360 		bad_error("uu_list_walk", uu_error());
8361 
8362 printerr:
8363 	/* If the error hasn't been printed yet, do so here. */
8364 	switch (cbdata.sc_err) {
8365 	case ECONNABORTED:
8366 		warn(gettext("Repository connection broken.\n"));
8367 		break;
8368 
8369 	case ENOMEM:
8370 		warn(emsg_nomem);
8371 		break;
8372 
8373 	case ENOSPC:
8374 		warn(emsg_nores);
8375 		break;
8376 
8377 	case EROFS:
8378 		warn(gettext("Repository is read-only.\n"));
8379 		break;
8380 
8381 	case EACCES:
8382 		warn(gettext("Repository backend denied access.\n"));
8383 		break;
8384 
8385 	case EPERM:
8386 	case EINVAL:
8387 	case EEXIST:
8388 	case EBUSY:
8389 	case EBADF:
8390 	case -1:
8391 		break;
8392 
8393 	default:
8394 		bad_error("lscf_service_import", cbdata.sc_err);
8395 	}
8396 
8397 progress:
8398 	warn(gettext("Import of %s failed.  Progress:\n"), filename);
8399 
8400 	for (svc = uu_list_first(bndl->sc_bundle_services);
8401 	    svc != NULL;
8402 	    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8403 		insts = svc->sc_u.sc_service.sc_service_instances;
8404 
8405 		warn(gettext("  Service \"%s\": %s\n"), svc->sc_name,
8406 		    import_progress(svc->sc_import_state));
8407 
8408 		for (inst = uu_list_first(insts);
8409 		    inst != NULL;
8410 		    inst = uu_list_next(insts, inst))
8411 			warn(gettext("    Instance \"%s\": %s\n"),
8412 			    inst->sc_name,
8413 			    import_progress(inst->sc_import_state));
8414 	}
8415 
8416 	if (cbdata.sc_err == ECONNABORTED)
8417 		repository_teardown();
8418 
8419 
8420 	result = -1;
8421 
8422 out:
8423 	if (annotation_set != 0) {
8424 		/* Turn off annotation.  It is no longer needed. */
8425 		(void) _scf_set_annotation(g_hndl, NULL, NULL);
8426 	}
8427 
8428 	free_imp_globals();
8429 
8430 	return (result);
8431 }
8432 
8433 /*
8434  * _lscf_import_err() summarize the error handling returned by
8435  * lscf_import_{instance | service}_pgs
8436  * Return values are:
8437  * IMPORT_NEXT
8438  * IMPORT_OUT
8439  * IMPORT_BAD
8440  */
8441 
8442 #define	IMPORT_BAD	-1
8443 #define	IMPORT_NEXT	0
8444 #define	IMPORT_OUT	1
8445 
8446 static int
8447 _lscf_import_err(int err, const char *fmri)
8448 {
8449 	switch (err) {
8450 	case 0:
8451 		if (g_verbose)
8452 			warn(gettext("%s updated.\n"), fmri);
8453 		return (IMPORT_NEXT);
8454 
8455 	case ECONNABORTED:
8456 		warn(gettext("Could not update %s "
8457 		    "(repository connection broken).\n"), fmri);
8458 		return (IMPORT_OUT);
8459 
8460 	case ENOMEM:
8461 		warn(gettext("Could not update %s (out of memory).\n"), fmri);
8462 		return (IMPORT_OUT);
8463 
8464 	case ENOSPC:
8465 		warn(gettext("Could not update %s "
8466 		    "(repository server out of resources).\n"), fmri);
8467 		return (IMPORT_OUT);
8468 
8469 	case ECANCELED:
8470 		warn(gettext(
8471 		    "Could not update %s (deleted).\n"), fmri);
8472 		return (IMPORT_NEXT);
8473 
8474 	case EPERM:
8475 	case EINVAL:
8476 	case EBUSY:
8477 		return (IMPORT_NEXT);
8478 
8479 	case EROFS:
8480 		warn(gettext("Could not update %s (repository read-only).\n"),
8481 		    fmri);
8482 		return (IMPORT_OUT);
8483 
8484 	case EACCES:
8485 		warn(gettext("Could not update %s "
8486 		    "(backend access denied).\n"), fmri);
8487 		return (IMPORT_NEXT);
8488 
8489 	case EEXIST:
8490 	default:
8491 		return (IMPORT_BAD);
8492 	}
8493 
8494 	/*NOTREACHED*/
8495 }
8496 
8497 /*
8498  * The global imp_svc and imp_inst should be set by the caller in the
8499  * check to make sure the service and instance exist that the apply is
8500  * working on.
8501  */
8502 static int
8503 lscf_dependent_apply(void *dpg, void *e)
8504 {
8505 	scf_callback_t cb;
8506 	pgroup_t *dpt_pgroup = dpg;
8507 	pgroup_t *deldpt;
8508 	entity_t *ent = e;
8509 	int tissvc;
8510 	void *sc_ent, *tent;
8511 	scf_error_t serr;
8512 	int r;
8513 
8514 	const char * const dependents = "dependents";
8515 	const int issvc = (ent->sc_etype == SVCCFG_SERVICE_OBJECT);
8516 
8517 	if (issvc)
8518 		sc_ent = imp_svc;
8519 	else
8520 		sc_ent = imp_inst;
8521 
8522 	if (entity_get_running_pg(sc_ent, issvc, dependents, imp_pg,
8523 	    imp_iter, imp_tinst, imp_snap, imp_snpl) != 0 ||
8524 	    scf_pg_get_property(imp_pg, dpt_pgroup->sc_pgroup_name,
8525 	    imp_prop) != 0) {
8526 		switch (scf_error()) {
8527 		case SCF_ERROR_NOT_FOUND:
8528 		case SCF_ERROR_DELETED:
8529 			break;
8530 
8531 		case SCF_ERROR_CONNECTION_BROKEN:
8532 		case SCF_ERROR_NOT_SET:
8533 		case SCF_ERROR_INVALID_ARGUMENT:
8534 		case SCF_ERROR_HANDLE_MISMATCH:
8535 		case SCF_ERROR_NOT_BOUND:
8536 		default:
8537 			bad_error("entity_get_pg", scf_error());
8538 		}
8539 	} else {
8540 		/*
8541 		 * Found the dependents/<wip dep> so check to
8542 		 * see if the service is different.  If so
8543 		 * store the service for later refresh, and
8544 		 * delete the wip dependency from the service
8545 		 */
8546 		if (scf_property_get_value(imp_prop, ud_val) != 0) {
8547 			switch (scf_error()) {
8548 				case SCF_ERROR_DELETED:
8549 					break;
8550 
8551 				case SCF_ERROR_CONNECTION_BROKEN:
8552 				case SCF_ERROR_NOT_SET:
8553 				case SCF_ERROR_INVALID_ARGUMENT:
8554 				case SCF_ERROR_HANDLE_MISMATCH:
8555 				case SCF_ERROR_NOT_BOUND:
8556 				default:
8557 					bad_error("scf_property_get_value",
8558 					    scf_error());
8559 			}
8560 		}
8561 
8562 		if (scf_value_get_as_string(ud_val, ud_oldtarg,
8563 		    max_scf_value_len + 1) < 0)
8564 			bad_error("scf_value_get_as_string", scf_error());
8565 
8566 		r = fmri_equal(dpt_pgroup->sc_pgroup_fmri, ud_oldtarg);
8567 		switch (r) {
8568 		case 1:
8569 			break;
8570 		case 0:
8571 			if ((serr = fmri_to_entity(g_hndl, ud_oldtarg, &tent,
8572 			    &tissvc)) != SCF_ERROR_NONE) {
8573 				if (serr == SCF_ERROR_NOT_FOUND) {
8574 					break;
8575 				} else {
8576 					bad_error("fmri_to_entity", serr);
8577 				}
8578 			}
8579 
8580 			if (entity_get_pg(tent, tissvc,
8581 			    dpt_pgroup->sc_pgroup_name, imp_pg) != 0) {
8582 				serr = scf_error();
8583 				if (serr == SCF_ERROR_NOT_FOUND ||
8584 				    serr == SCF_ERROR_DELETED) {
8585 					break;
8586 				} else {
8587 					bad_error("entity_get_pg", scf_error());
8588 				}
8589 			}
8590 
8591 			if (scf_pg_delete(imp_pg) != 0) {
8592 				serr = scf_error();
8593 				if (serr == SCF_ERROR_NOT_FOUND ||
8594 				    serr == SCF_ERROR_DELETED) {
8595 					break;
8596 				} else {
8597 					bad_error("scf_pg_delete", scf_error());
8598 				}
8599 			}
8600 
8601 			deldpt = internal_pgroup_new();
8602 			if (deldpt == NULL)
8603 				return (ENOMEM);
8604 			deldpt->sc_pgroup_name =
8605 			    strdup(dpt_pgroup->sc_pgroup_name);
8606 			deldpt->sc_pgroup_fmri = strdup(ud_oldtarg);
8607 			if (deldpt->sc_pgroup_name == NULL ||
8608 			    deldpt->sc_pgroup_fmri == NULL)
8609 				return (ENOMEM);
8610 			deldpt->sc_parent = (entity_t *)ent;
8611 			if (uu_list_insert_after(imp_deleted_dpts, NULL,
8612 			    deldpt) != 0)
8613 				uu_die(gettext("libuutil error: %s\n"),
8614 				    uu_strerror(uu_error()));
8615 
8616 			break;
8617 		default:
8618 			bad_error("fmri_equal", r);
8619 		}
8620 	}
8621 
8622 	cb.sc_handle = g_hndl;
8623 	cb.sc_parent = ent;
8624 	cb.sc_service = ent->sc_etype == SVCCFG_SERVICE_OBJECT;
8625 	cb.sc_source_fmri = ent->sc_fmri;
8626 	cb.sc_target_fmri = ent->sc_fmri;
8627 	cb.sc_trans = NULL;
8628 	cb.sc_flags = SCI_FORCE;
8629 
8630 	if (lscf_dependent_import(dpt_pgroup, &cb) != UU_WALK_NEXT)
8631 		return (UU_WALK_ERROR);
8632 
8633 	r = imp_refresh_fmri(dpt_pgroup->sc_pgroup_fmri, NULL, NULL);
8634 	switch (r) {
8635 	case 0:
8636 		break;
8637 
8638 	case ENOMEM:
8639 	case ECONNABORTED:
8640 	case EPERM:
8641 	case -1:
8642 		warn(gettext("Unable to refresh \"%s\"\n"),
8643 		    dpt_pgroup->sc_pgroup_fmri);
8644 		return (UU_WALK_ERROR);
8645 
8646 	default:
8647 		bad_error("imp_refresh_fmri", r);
8648 	}
8649 
8650 	return (UU_WALK_NEXT);
8651 }
8652 
8653 /*
8654  * Returns
8655  *   0 - success
8656  *   -1 - lscf_import_instance_pgs() failed.
8657  */
8658 int
8659 lscf_bundle_apply(bundle_t *bndl, const char *file)
8660 {
8661 	pgroup_t *old_dpt;
8662 	entity_t *svc, *inst;
8663 	int annotation_set = 0;
8664 	int ret = 0;
8665 	int r = 0;
8666 
8667 	lscf_prep_hndl();
8668 
8669 	if ((ret = alloc_imp_globals()))
8670 		goto out;
8671 
8672 	if (scf_handle_get_scope(g_hndl, SCF_SCOPE_LOCAL, imp_scope) != 0)
8673 		scfdie();
8674 
8675 	/*
8676 	 * Set the strings to be used for the security audit annotation
8677 	 * event.
8678 	 */
8679 	if (_scf_set_annotation(g_hndl, "svccfg apply", file) == 0) {
8680 		annotation_set = 1;
8681 	} else {
8682 		switch (scf_error()) {
8683 		case SCF_ERROR_CONNECTION_BROKEN:
8684 			warn(gettext("Repository connection broken.\n"));
8685 			goto out;
8686 
8687 		case SCF_ERROR_INVALID_ARGUMENT:
8688 		case SCF_ERROR_NOT_BOUND:
8689 		case SCF_ERROR_NO_RESOURCES:
8690 		case SCF_ERROR_INTERNAL:
8691 			bad_error("_scf_set_annotation", scf_error());
8692 			/* NOTREACHED */
8693 
8694 		default:
8695 			/*
8696 			 * Do not abort apply operation because of
8697 			 * inability to create annotation audit event.
8698 			 */
8699 			warn(gettext("_scf_set_annotation() unexpectedly "
8700 			    "failed with return code of %d\n"), scf_error());
8701 			break;
8702 		}
8703 	}
8704 
8705 	for (svc = uu_list_first(bndl->sc_bundle_services);
8706 	    svc != NULL;
8707 	    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8708 		int refresh = 0;
8709 
8710 		if (scf_scope_get_service(imp_scope, svc->sc_name,
8711 		    imp_svc) != 0) {
8712 			switch (scf_error()) {
8713 			case SCF_ERROR_NOT_FOUND:
8714 				if (g_verbose)
8715 					warn(gettext("Ignoring nonexistent "
8716 					    "service %s.\n"), svc->sc_name);
8717 				continue;
8718 
8719 			default:
8720 				scfdie();
8721 			}
8722 		}
8723 
8724 		/*
8725 		 * If there were missing types in the profile, then need to
8726 		 * attempt to find the types.
8727 		 */
8728 		if (svc->sc_miss_type) {
8729 			if (uu_list_numnodes(svc->sc_pgroups) &&
8730 			    uu_list_walk(svc->sc_pgroups, find_current_pg_type,
8731 			    svc, UU_DEFAULT) != 0) {
8732 				if (uu_error() != UU_ERROR_CALLBACK_FAILED)
8733 					bad_error("uu_list_walk", uu_error());
8734 
8735 				ret = -1;
8736 				continue;
8737 			}
8738 
8739 			for (inst = uu_list_first(
8740 			    svc->sc_u.sc_service.sc_service_instances);
8741 			    inst != NULL;
8742 			    inst = uu_list_next(
8743 			    svc->sc_u.sc_service.sc_service_instances, inst)) {
8744 				/*
8745 				 * If the instance doesn't exist just
8746 				 * skip to the next instance and let the
8747 				 * import note the missing instance.
8748 				 */
8749 				if (scf_service_get_instance(imp_svc,
8750 				    inst->sc_name, imp_inst) != 0)
8751 					continue;
8752 
8753 				if (uu_list_walk(inst->sc_pgroups,
8754 				    find_current_pg_type, inst,
8755 				    UU_DEFAULT) != 0) {
8756 					if (uu_error() !=
8757 					    UU_ERROR_CALLBACK_FAILED)
8758 						bad_error("uu_list_walk",
8759 						    uu_error());
8760 
8761 					ret = -1;
8762 					inst->sc_miss_type = B_TRUE;
8763 				}
8764 			}
8765 		}
8766 
8767 		/*
8768 		 * if we have pgs in the profile, we need to refresh ALL
8769 		 * instances of the service
8770 		 */
8771 		if (uu_list_numnodes(svc->sc_pgroups) != 0) {
8772 			refresh = 1;
8773 			r = lscf_import_service_pgs(imp_svc, svc->sc_fmri, svc,
8774 			    SCI_FORCE | SCI_KEEP);
8775 			switch (_lscf_import_err(r, svc->sc_fmri)) {
8776 			case IMPORT_NEXT:
8777 				break;
8778 
8779 			case IMPORT_OUT:
8780 				goto out;
8781 
8782 			case IMPORT_BAD:
8783 			default:
8784 				bad_error("lscf_import_service_pgs", r);
8785 			}
8786 		}
8787 
8788 		if (uu_list_numnodes(svc->sc_dependents) != 0) {
8789 			uu_list_walk(svc->sc_dependents,
8790 			    lscf_dependent_apply, svc, UU_DEFAULT);
8791 		}
8792 
8793 		for (inst = uu_list_first(
8794 		    svc->sc_u.sc_service.sc_service_instances);
8795 		    inst != NULL;
8796 		    inst = uu_list_next(
8797 		    svc->sc_u.sc_service.sc_service_instances, inst)) {
8798 			/*
8799 			 * This instance still has missing types
8800 			 * so skip it.
8801 			 */
8802 			if (inst->sc_miss_type) {
8803 				if (g_verbose)
8804 					warn(gettext("Ignoring instance "
8805 					    "%s:%s with missing types\n"),
8806 					    inst->sc_parent->sc_name,
8807 					    inst->sc_name);
8808 
8809 				continue;
8810 			}
8811 
8812 			if (scf_service_get_instance(imp_svc, inst->sc_name,
8813 			    imp_inst) != 0) {
8814 				switch (scf_error()) {
8815 				case SCF_ERROR_NOT_FOUND:
8816 					if (g_verbose)
8817 						warn(gettext("Ignoring "
8818 						    "nonexistant instance "
8819 						    "%s:%s.\n"),
8820 						    inst->sc_parent->sc_name,
8821 						    inst->sc_name);
8822 					continue;
8823 
8824 				default:
8825 					scfdie();
8826 				}
8827 			}
8828 
8829 			/*
8830 			 * If the instance does not have a general/enabled
8831 			 * property and no last-import snapshot then the
8832 			 * instance is not a fully installed instance and
8833 			 * should not have a profile applied to it.
8834 			 *
8835 			 * This could happen if a service/instance declares
8836 			 * a dependent on behalf of another service/instance.
8837 			 *
8838 			 */
8839 			if (scf_instance_get_snapshot(imp_inst, snap_lastimport,
8840 			    imp_snap) != 0) {
8841 				if (scf_instance_get_pg(imp_inst,
8842 				    SCF_PG_GENERAL, imp_pg) != 0 ||
8843 				    scf_pg_get_property(imp_pg,
8844 				    SCF_PROPERTY_ENABLED, imp_prop) != 0) {
8845 					if (g_verbose)
8846 						warn(gettext("Ignoreing "
8847 						    "partial instance "
8848 						    "%s:%s.\n"),
8849 						    inst->sc_parent->sc_name,
8850 						    inst->sc_name);
8851 					continue;
8852 				}
8853 			}
8854 
8855 			r = lscf_import_instance_pgs(imp_inst, inst->sc_fmri,
8856 			    inst, SCI_FORCE | SCI_KEEP);
8857 			switch (_lscf_import_err(r, inst->sc_fmri)) {
8858 			case IMPORT_NEXT:
8859 				break;
8860 
8861 			case IMPORT_OUT:
8862 				goto out;
8863 
8864 			case IMPORT_BAD:
8865 			default:
8866 				bad_error("lscf_import_instance_pgs", r);
8867 			}
8868 
8869 			if (uu_list_numnodes(inst->sc_dependents) != 0) {
8870 				uu_list_walk(inst->sc_dependents,
8871 				    lscf_dependent_apply, inst, UU_DEFAULT);
8872 			}
8873 
8874 			/* refresh only if there is no pgs in the service */
8875 			if (refresh == 0)
8876 				(void) refresh_entity(0, imp_inst,
8877 				    inst->sc_fmri, NULL, NULL, NULL);
8878 		}
8879 
8880 		if (refresh == 1) {
8881 			char *name_buf = safe_malloc(max_scf_name_len + 1);
8882 
8883 			(void) refresh_entity(1, imp_svc, svc->sc_name,
8884 			    imp_inst, imp_iter, name_buf);
8885 			free(name_buf);
8886 		}
8887 
8888 		for (old_dpt = uu_list_first(imp_deleted_dpts);
8889 		    old_dpt != NULL;
8890 		    old_dpt = uu_list_next(imp_deleted_dpts, old_dpt)) {
8891 			if (imp_refresh_fmri(old_dpt->sc_pgroup_fmri,
8892 			    old_dpt->sc_pgroup_name,
8893 			    old_dpt->sc_parent->sc_fmri) != 0) {
8894 				warn(gettext("Unable to refresh \"%s\"\n"),
8895 				    old_dpt->sc_pgroup_fmri);
8896 			}
8897 		}
8898 	}
8899 
8900 out:
8901 	if (annotation_set) {
8902 		/* Remove security audit annotation strings. */
8903 		(void) _scf_set_annotation(g_hndl, NULL, NULL);
8904 	}
8905 
8906 	free_imp_globals();
8907 	return (ret);
8908 }
8909 
8910 
8911 /*
8912  * Export.  These functions create and output an XML tree of a service
8913  * description from the repository.  This is largely the inverse of
8914  * lxml_get_bundle() in svccfg_xml.c, but with some kickers:
8915  *
8916  * - We must include any properties which are not represented specifically by
8917  *   a service manifest, e.g., properties created by an admin post-import.  To
8918  *   do so we'll iterate through all properties and deal with each
8919  *   apropriately.
8920  *
8921  * - Children of services and instances must must be in the order set by the
8922  *   DTD, but we iterate over the properties in undefined order.  The elements
8923  *   are not easily (or efficiently) sortable by name.  Since there's a fixed
8924  *   number of classes of them, however, we'll keep the classes separate and
8925  *   assemble them in order.
8926  */
8927 
8928 /*
8929  * Convenience function to handle xmlSetProp errors (and type casting).
8930  */
8931 static void
8932 safe_setprop(xmlNodePtr n, const char *name, const char *val)
8933 {
8934 	if (xmlSetProp(n, (const xmlChar *)name, (const xmlChar *)val) == NULL)
8935 		uu_die(gettext("Could not set XML property.\n"));
8936 }
8937 
8938 /*
8939  * Convenience function to set an XML attribute to the single value of an
8940  * astring property.  If the value happens to be the default, don't set the
8941  * attribute.  "dval" should be the default value supplied by the DTD, or
8942  * NULL for no default.
8943  */
8944 static int
8945 set_attr_from_prop_default(scf_property_t *prop, xmlNodePtr n,
8946     const char *name, const char *dval)
8947 {
8948 	scf_value_t *val;
8949 	ssize_t len;
8950 	char *str;
8951 
8952 	val = scf_value_create(g_hndl);
8953 	if (val == NULL)
8954 		scfdie();
8955 
8956 	if (prop_get_val(prop, val) != 0) {
8957 		scf_value_destroy(val);
8958 		return (-1);
8959 	}
8960 
8961 	len = scf_value_get_as_string(val, NULL, 0);
8962 	if (len < 0)
8963 		scfdie();
8964 
8965 	str = safe_malloc(len + 1);
8966 
8967 	if (scf_value_get_as_string(val, str, len + 1) < 0)
8968 		scfdie();
8969 
8970 	scf_value_destroy(val);
8971 
8972 	if (dval == NULL || strcmp(str, dval) != 0)
8973 		safe_setprop(n, name, str);
8974 
8975 	free(str);
8976 
8977 	return (0);
8978 }
8979 
8980 /*
8981  * As above, but the attribute is always set.
8982  */
8983 static int
8984 set_attr_from_prop(scf_property_t *prop, xmlNodePtr n, const char *name)
8985 {
8986 	return (set_attr_from_prop_default(prop, n, name, NULL));
8987 }
8988 
8989 /*
8990  * Dump the given document onto f, with "'s replaced by ''s.
8991  */
8992 static int
8993 write_service_bundle(xmlDocPtr doc, FILE *f)
8994 {
8995 	xmlChar *mem;
8996 	int sz, i;
8997 
8998 	mem = NULL;
8999 	xmlDocDumpFormatMemory(doc, &mem, &sz, 1);
9000 
9001 	if (mem == NULL) {
9002 		semerr(gettext("Could not dump XML tree.\n"));
9003 		return (-1);
9004 	}
9005 
9006 	/*
9007 	 * Fortunately libxml produces &quot; instead of ", so we can blindly
9008 	 * replace all " with '.  Cursed libxml2!  Why must you #ifdef out the
9009 	 * &apos; code?!
9010 	 */
9011 	for (i = 0; i < sz; ++i) {
9012 		char c = (char)mem[i];
9013 
9014 		if (c == '"')
9015 			(void) fputc('\'', f);
9016 		else if (c == '\'')
9017 			(void) fwrite("&apos;", sizeof ("&apos;") - 1, 1, f);
9018 		else
9019 			(void) fputc(c, f);
9020 	}
9021 
9022 	return (0);
9023 }
9024 
9025 /*
9026  * Create the DOM elements in elts necessary to (generically) represent prop
9027  * (i.e., a property or propval element).  If the name of the property is
9028  * known, it should be passed as name_arg.  Otherwise, pass NULL.
9029  */
9030 static void
9031 export_property(scf_property_t *prop, const char *name_arg,
9032     struct pg_elts *elts, int flags)
9033 {
9034 	const char *type;
9035 	scf_error_t err = 0;
9036 	xmlNodePtr pnode, lnode;
9037 	char *lnname;
9038 	int ret;
9039 
9040 	/* name */
9041 	if (name_arg != NULL) {
9042 		(void) strcpy(exp_str, name_arg);
9043 	} else {
9044 		if (scf_property_get_name(prop, exp_str, exp_str_sz) < 0)
9045 			scfdie();
9046 	}
9047 
9048 	/* type */
9049 	type = prop_to_typestr(prop);
9050 	if (type == NULL)
9051 		uu_die(gettext("Can't export property %s: unknown type.\n"),
9052 		    exp_str);
9053 
9054 	/* If we're exporting values, and there's just one, export it here. */
9055 	if (!(flags & SCE_ALL_VALUES))
9056 		goto empty;
9057 
9058 	if (scf_property_get_value(prop, exp_val) == SCF_SUCCESS) {
9059 		xmlNodePtr n;
9060 
9061 		/* Single value, so use propval */
9062 		n = xmlNewNode(NULL, (xmlChar *)"propval");
9063 		if (n == NULL)
9064 			uu_die(emsg_create_xml);
9065 
9066 		safe_setprop(n, name_attr, exp_str);
9067 		safe_setprop(n, type_attr, type);
9068 
9069 		if (scf_value_get_as_string(exp_val, exp_str, exp_str_sz) < 0)
9070 			scfdie();
9071 		safe_setprop(n, value_attr, exp_str);
9072 
9073 		if (elts->propvals == NULL)
9074 			elts->propvals = n;
9075 		else
9076 			(void) xmlAddSibling(elts->propvals, n);
9077 
9078 		return;
9079 	}
9080 
9081 	err = scf_error();
9082 
9083 	if (err == SCF_ERROR_PERMISSION_DENIED) {
9084 		semerr(emsg_permission_denied);
9085 		return;
9086 	}
9087 
9088 	if (err != SCF_ERROR_CONSTRAINT_VIOLATED &&
9089 	    err != SCF_ERROR_NOT_FOUND &&
9090 	    err != SCF_ERROR_PERMISSION_DENIED)
9091 		scfdie();
9092 
9093 empty:
9094 	/* Multiple (or no) values, so use property */
9095 	pnode = xmlNewNode(NULL, (xmlChar *)"property");
9096 	if (pnode == NULL)
9097 		uu_die(emsg_create_xml);
9098 
9099 	safe_setprop(pnode, name_attr, exp_str);
9100 	safe_setprop(pnode, type_attr, type);
9101 
9102 	if (err == SCF_ERROR_CONSTRAINT_VIOLATED) {
9103 		lnname = uu_msprintf("%s_list", type);
9104 		if (lnname == NULL)
9105 			uu_die(gettext("Could not create string"));
9106 
9107 		lnode = xmlNewChild(pnode, NULL, (xmlChar *)lnname, NULL);
9108 		if (lnode == NULL)
9109 			uu_die(emsg_create_xml);
9110 
9111 		uu_free(lnname);
9112 
9113 		if (scf_iter_property_values(exp_val_iter, prop) != SCF_SUCCESS)
9114 			scfdie();
9115 
9116 		while ((ret = scf_iter_next_value(exp_val_iter, exp_val)) ==
9117 		    1) {
9118 			xmlNodePtr vn;
9119 
9120 			vn = xmlNewChild(lnode, NULL, (xmlChar *)"value_node",
9121 			    NULL);
9122 			if (vn == NULL)
9123 				uu_die(emsg_create_xml);
9124 
9125 			if (scf_value_get_as_string(exp_val, exp_str,
9126 			    exp_str_sz) < 0)
9127 				scfdie();
9128 			safe_setprop(vn, value_attr, exp_str);
9129 		}
9130 		if (ret != 0)
9131 			scfdie();
9132 	}
9133 
9134 	if (elts->properties == NULL)
9135 		elts->properties = pnode;
9136 	else
9137 		(void) xmlAddSibling(elts->properties, pnode);
9138 }
9139 
9140 /*
9141  * Add a property_group element for this property group to elts.
9142  */
9143 static void
9144 export_pg(scf_propertygroup_t *pg, struct entity_elts *eelts, int flags)
9145 {
9146 	xmlNodePtr n;
9147 	struct pg_elts elts;
9148 	int ret;
9149 	boolean_t read_protected;
9150 
9151 	n = xmlNewNode(NULL, (xmlChar *)"property_group");
9152 
9153 	/* name */
9154 	if (scf_pg_get_name(pg, exp_str, max_scf_name_len + 1) < 0)
9155 		scfdie();
9156 	safe_setprop(n, name_attr, exp_str);
9157 
9158 	/* type */
9159 	if (scf_pg_get_type(pg, exp_str, exp_str_sz) < 0)
9160 		scfdie();
9161 	safe_setprop(n, type_attr, exp_str);
9162 
9163 	/* properties */
9164 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9165 		scfdie();
9166 
9167 	(void) memset(&elts, 0, sizeof (elts));
9168 
9169 	/*
9170 	 * If this property group is not read protected, we always want to
9171 	 * output all the values.  Otherwise, we only output the values if the
9172 	 * caller set SCE_ALL_VALUES (i.e., the user gave us export/archive -a).
9173 	 */
9174 	if (_scf_pg_is_read_protected(pg, &read_protected) != SCF_SUCCESS)
9175 		scfdie();
9176 
9177 	if (!read_protected)
9178 		flags |= SCE_ALL_VALUES;
9179 
9180 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9181 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9182 			scfdie();
9183 
9184 		if (strcmp(exp_str, SCF_PROPERTY_STABILITY) == 0) {
9185 			xmlNodePtr m;
9186 
9187 			m = xmlNewNode(NULL, (xmlChar *)"stability");
9188 			if (m == NULL)
9189 				uu_die(emsg_create_xml);
9190 
9191 			if (set_attr_from_prop(exp_prop, m, value_attr) == 0) {
9192 				elts.stability = m;
9193 				continue;
9194 			}
9195 
9196 			xmlFreeNode(m);
9197 		}
9198 
9199 		export_property(exp_prop, NULL, &elts, flags);
9200 	}
9201 	if (ret == -1)
9202 		scfdie();
9203 
9204 	(void) xmlAddChild(n, elts.stability);
9205 	(void) xmlAddChildList(n, elts.propvals);
9206 	(void) xmlAddChildList(n, elts.properties);
9207 
9208 	if (eelts->property_groups == NULL)
9209 		eelts->property_groups = n;
9210 	else
9211 		(void) xmlAddSibling(eelts->property_groups, n);
9212 }
9213 
9214 /*
9215  * Create an XML node representing the dependency described by the given
9216  * property group and put it in eelts.  Unless the dependency is not valid, in
9217  * which case create a generic property_group element which represents it and
9218  * put it in eelts.
9219  */
9220 static void
9221 export_dependency(scf_propertygroup_t *pg, struct entity_elts *eelts)
9222 {
9223 	xmlNodePtr n;
9224 	int err = 0, ret;
9225 	struct pg_elts elts;
9226 
9227 	n = xmlNewNode(NULL, (xmlChar *)"dependency");
9228 	if (n == NULL)
9229 		uu_die(emsg_create_xml);
9230 
9231 	/*
9232 	 * If the external flag is present, skip this dependency because it
9233 	 * should have been created by another manifest.
9234 	 */
9235 	if (scf_pg_get_property(pg, scf_property_external, exp_prop) == 0) {
9236 		if (prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
9237 		    prop_get_val(exp_prop, exp_val) == 0) {
9238 			uint8_t b;
9239 
9240 			if (scf_value_get_boolean(exp_val, &b) != SCF_SUCCESS)
9241 				scfdie();
9242 
9243 			if (b)
9244 				return;
9245 		}
9246 	} else if (scf_error() != SCF_ERROR_NOT_FOUND)
9247 		scfdie();
9248 
9249 	/* Get the required attributes. */
9250 
9251 	/* name */
9252 	if (scf_pg_get_name(pg, exp_str, max_scf_name_len + 1) < 0)
9253 		scfdie();
9254 	safe_setprop(n, name_attr, exp_str);
9255 
9256 	/* grouping */
9257 	if (pg_get_prop(pg, SCF_PROPERTY_GROUPING, exp_prop) != 0 ||
9258 	    set_attr_from_prop(exp_prop, n, "grouping") != 0)
9259 		err = 1;
9260 
9261 	/* restart_on */
9262 	if (pg_get_prop(pg, SCF_PROPERTY_RESTART_ON, exp_prop) != 0 ||
9263 	    set_attr_from_prop(exp_prop, n, "restart_on") != 0)
9264 		err = 1;
9265 
9266 	/* type */
9267 	if (pg_get_prop(pg, SCF_PROPERTY_TYPE, exp_prop) != 0 ||
9268 	    set_attr_from_prop(exp_prop, n, type_attr) != 0)
9269 		err = 1;
9270 
9271 	/*
9272 	 * entities: Not required, but if we create no children, it will be
9273 	 * created as empty on import, so fail if it's missing.
9274 	 */
9275 	if (pg_get_prop(pg, SCF_PROPERTY_ENTITIES, exp_prop) == 0 &&
9276 	    prop_check_type(exp_prop, SCF_TYPE_FMRI) == 0) {
9277 		scf_iter_t *eiter;
9278 		int ret2;
9279 
9280 		eiter = scf_iter_create(g_hndl);
9281 		if (eiter == NULL)
9282 			scfdie();
9283 
9284 		if (scf_iter_property_values(eiter, exp_prop) != SCF_SUCCESS)
9285 			scfdie();
9286 
9287 		while ((ret2 = scf_iter_next_value(eiter, exp_val)) == 1) {
9288 			xmlNodePtr ch;
9289 
9290 			if (scf_value_get_astring(exp_val, exp_str,
9291 			    exp_str_sz) < 0)
9292 				scfdie();
9293 
9294 			/*
9295 			 * service_fmri's must be first, so we can add them
9296 			 * here.
9297 			 */
9298 			ch = xmlNewChild(n, NULL, (xmlChar *)"service_fmri",
9299 			    NULL);
9300 			if (ch == NULL)
9301 				uu_die(emsg_create_xml);
9302 
9303 			safe_setprop(ch, value_attr, exp_str);
9304 		}
9305 		if (ret2 == -1)
9306 			scfdie();
9307 
9308 		scf_iter_destroy(eiter);
9309 	} else
9310 		err = 1;
9311 
9312 	if (err) {
9313 		xmlFreeNode(n);
9314 
9315 		export_pg(pg, eelts, SCE_ALL_VALUES);
9316 
9317 		return;
9318 	}
9319 
9320 	/* Iterate through the properties & handle each. */
9321 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9322 		scfdie();
9323 
9324 	(void) memset(&elts, 0, sizeof (elts));
9325 
9326 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9327 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9328 			scfdie();
9329 
9330 		if (strcmp(exp_str, SCF_PROPERTY_GROUPING) == 0 ||
9331 		    strcmp(exp_str, SCF_PROPERTY_RESTART_ON) == 0 ||
9332 		    strcmp(exp_str, SCF_PROPERTY_TYPE) == 0 ||
9333 		    strcmp(exp_str, SCF_PROPERTY_ENTITIES) == 0) {
9334 			continue;
9335 		} else if (strcmp(exp_str, SCF_PROPERTY_STABILITY) == 0) {
9336 			xmlNodePtr m;
9337 
9338 			m = xmlNewNode(NULL, (xmlChar *)"stability");
9339 			if (m == NULL)
9340 				uu_die(emsg_create_xml);
9341 
9342 			if (set_attr_from_prop(exp_prop, m, value_attr) == 0) {
9343 				elts.stability = m;
9344 				continue;
9345 			}
9346 
9347 			xmlFreeNode(m);
9348 		}
9349 
9350 		export_property(exp_prop, exp_str, &elts, SCE_ALL_VALUES);
9351 	}
9352 	if (ret == -1)
9353 		scfdie();
9354 
9355 	(void) xmlAddChild(n, elts.stability);
9356 	(void) xmlAddChildList(n, elts.propvals);
9357 	(void) xmlAddChildList(n, elts.properties);
9358 
9359 	if (eelts->dependencies == NULL)
9360 		eelts->dependencies = n;
9361 	else
9362 		(void) xmlAddSibling(eelts->dependencies, n);
9363 }
9364 
9365 static xmlNodePtr
9366 export_method_environment(scf_propertygroup_t *pg)
9367 {
9368 	xmlNodePtr env;
9369 	int ret;
9370 	int children = 0;
9371 
9372 	if (scf_pg_get_property(pg, SCF_PROPERTY_ENVIRONMENT, NULL) != 0)
9373 		return (NULL);
9374 
9375 	env = xmlNewNode(NULL, (xmlChar *)"method_environment");
9376 	if (env == NULL)
9377 		uu_die(emsg_create_xml);
9378 
9379 	if (pg_get_prop(pg, SCF_PROPERTY_ENVIRONMENT, exp_prop) != 0)
9380 		scfdie();
9381 
9382 	if (scf_iter_property_values(exp_val_iter, exp_prop) != SCF_SUCCESS)
9383 		scfdie();
9384 
9385 	while ((ret = scf_iter_next_value(exp_val_iter, exp_val)) == 1) {
9386 		xmlNodePtr ev;
9387 		char *cp;
9388 
9389 		if (scf_value_get_as_string(exp_val, exp_str, exp_str_sz) < 0)
9390 			scfdie();
9391 
9392 		if ((cp = strchr(exp_str, '=')) == NULL || cp == exp_str) {
9393 			warn(gettext("Invalid environment variable \"%s\".\n"),
9394 			    exp_str);
9395 			continue;
9396 		} else if (strncmp(exp_str, "SMF_", 4) == 0) {
9397 			warn(gettext("Invalid environment variable \"%s\"; "
9398 			    "\"SMF_\" prefix is reserved.\n"), exp_str);
9399 			continue;
9400 		}
9401 
9402 		*cp = '\0';
9403 		cp++;
9404 
9405 		ev = xmlNewChild(env, NULL, (xmlChar *)"envvar", NULL);
9406 		if (ev == NULL)
9407 			uu_die(emsg_create_xml);
9408 
9409 		safe_setprop(ev, name_attr, exp_str);
9410 		safe_setprop(ev, value_attr, cp);
9411 		children++;
9412 	}
9413 
9414 	if (ret != 0)
9415 		scfdie();
9416 
9417 	if (children == 0) {
9418 		xmlFreeNode(env);
9419 		return (NULL);
9420 	}
9421 
9422 	return (env);
9423 }
9424 
9425 /*
9426  * As above, but for a method property group.
9427  */
9428 static void
9429 export_method(scf_propertygroup_t *pg, struct entity_elts *eelts)
9430 {
9431 	xmlNodePtr n, env;
9432 	char *str;
9433 	int err = 0, nonenv, ret;
9434 	uint8_t use_profile;
9435 	struct pg_elts elts;
9436 	xmlNodePtr ctxt = NULL;
9437 
9438 	n = xmlNewNode(NULL, (xmlChar *)"exec_method");
9439 
9440 	/* Get the required attributes. */
9441 
9442 	/* name */
9443 	if (scf_pg_get_name(pg, exp_str, max_scf_name_len + 1) < 0)
9444 		scfdie();
9445 	safe_setprop(n, name_attr, exp_str);
9446 
9447 	/* type */
9448 	if (pg_get_prop(pg, SCF_PROPERTY_TYPE, exp_prop) != 0 ||
9449 	    set_attr_from_prop(exp_prop, n, type_attr) != 0)
9450 		err = 1;
9451 
9452 	/* exec */
9453 	if (pg_get_prop(pg, SCF_PROPERTY_EXEC, exp_prop) != 0 ||
9454 	    set_attr_from_prop(exp_prop, n, "exec") != 0)
9455 		err = 1;
9456 
9457 	/* timeout */
9458 	if (pg_get_prop(pg, SCF_PROPERTY_TIMEOUT, exp_prop) == 0 &&
9459 	    prop_check_type(exp_prop, SCF_TYPE_COUNT) == 0 &&
9460 	    prop_get_val(exp_prop, exp_val) == 0) {
9461 		uint64_t c;
9462 
9463 		if (scf_value_get_count(exp_val, &c) != SCF_SUCCESS)
9464 			scfdie();
9465 
9466 		str = uu_msprintf("%llu", c);
9467 		if (str == NULL)
9468 			uu_die(gettext("Could not create string"));
9469 
9470 		safe_setprop(n, "timeout_seconds", str);
9471 		free(str);
9472 	} else
9473 		err = 1;
9474 
9475 	if (err) {
9476 		xmlFreeNode(n);
9477 
9478 		export_pg(pg, eelts, SCE_ALL_VALUES);
9479 
9480 		return;
9481 	}
9482 
9483 
9484 	/*
9485 	 * If we're going to have a method_context child, we need to know
9486 	 * before we iterate through the properties.  Since method_context's
9487 	 * are optional, we don't want to complain about any properties
9488 	 * missing if none of them are there.  Thus we can't use the
9489 	 * convenience functions.
9490 	 */
9491 	nonenv =
9492 	    scf_pg_get_property(pg, SCF_PROPERTY_WORKING_DIRECTORY, NULL) ==
9493 	    SCF_SUCCESS ||
9494 	    scf_pg_get_property(pg, SCF_PROPERTY_PROJECT, NULL) ==
9495 	    SCF_SUCCESS ||
9496 	    scf_pg_get_property(pg, SCF_PROPERTY_RESOURCE_POOL, NULL) ==
9497 	    SCF_SUCCESS ||
9498 	    scf_pg_get_property(pg, SCF_PROPERTY_USE_PROFILE, NULL) ==
9499 	    SCF_SUCCESS;
9500 
9501 	if (nonenv) {
9502 		ctxt = xmlNewNode(NULL, (xmlChar *)"method_context");
9503 		if (ctxt == NULL)
9504 			uu_die(emsg_create_xml);
9505 
9506 		if (pg_get_prop(pg, SCF_PROPERTY_WORKING_DIRECTORY, exp_prop) ==
9507 		    0 &&
9508 		    set_attr_from_prop_default(exp_prop, ctxt,
9509 		    "working_directory", ":default") != 0)
9510 			err = 1;
9511 
9512 		if (pg_get_prop(pg, SCF_PROPERTY_PROJECT, exp_prop) == 0 &&
9513 		    set_attr_from_prop_default(exp_prop, ctxt, "project",
9514 		    ":default") != 0)
9515 			err = 1;
9516 
9517 		if (pg_get_prop(pg, SCF_PROPERTY_RESOURCE_POOL, exp_prop) ==
9518 		    0 &&
9519 		    set_attr_from_prop_default(exp_prop, ctxt,
9520 		    "resource_pool", ":default") != 0)
9521 			err = 1;
9522 		/*
9523 		 * We only want to complain about profile or credential
9524 		 * properties if we will use them.  To determine that we must
9525 		 * examine USE_PROFILE.
9526 		 */
9527 		if (pg_get_prop(pg, SCF_PROPERTY_USE_PROFILE, exp_prop) == 0 &&
9528 		    prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
9529 		    prop_get_val(exp_prop, exp_val) == 0) {
9530 			if (scf_value_get_boolean(exp_val, &use_profile) !=
9531 			    SCF_SUCCESS) {
9532 				scfdie();
9533 			}
9534 
9535 			if (use_profile) {
9536 				xmlNodePtr prof;
9537 
9538 				prof = xmlNewChild(ctxt, NULL,
9539 				    (xmlChar *)"method_profile", NULL);
9540 				if (prof == NULL)
9541 					uu_die(emsg_create_xml);
9542 
9543 				if (pg_get_prop(pg, SCF_PROPERTY_PROFILE,
9544 				    exp_prop) != 0 ||
9545 				    set_attr_from_prop(exp_prop, prof,
9546 				    name_attr) != 0)
9547 					err = 1;
9548 			} else {
9549 				xmlNodePtr cred;
9550 
9551 				cred = xmlNewChild(ctxt, NULL,
9552 				    (xmlChar *)"method_credential", NULL);
9553 				if (cred == NULL)
9554 					uu_die(emsg_create_xml);
9555 
9556 				if (pg_get_prop(pg, SCF_PROPERTY_USER,
9557 				    exp_prop) != 0 ||
9558 				    set_attr_from_prop(exp_prop, cred,
9559 				    "user") != 0) {
9560 					err = 1;
9561 				}
9562 
9563 				if (pg_get_prop(pg, SCF_PROPERTY_GROUP,
9564 				    exp_prop) == 0 &&
9565 				    set_attr_from_prop_default(exp_prop, cred,
9566 				    "group", ":default") != 0)
9567 					err = 1;
9568 
9569 				if (pg_get_prop(pg, SCF_PROPERTY_SUPP_GROUPS,
9570 				    exp_prop) == 0 &&
9571 				    set_attr_from_prop_default(exp_prop, cred,
9572 				    "supp_groups", ":default") != 0)
9573 					err = 1;
9574 
9575 				if (pg_get_prop(pg, SCF_PROPERTY_PRIVILEGES,
9576 				    exp_prop) == 0 &&
9577 				    set_attr_from_prop_default(exp_prop, cred,
9578 				    "privileges", ":default") != 0)
9579 					err = 1;
9580 
9581 				if (pg_get_prop(pg,
9582 				    SCF_PROPERTY_LIMIT_PRIVILEGES,
9583 				    exp_prop) == 0 &&
9584 				    set_attr_from_prop_default(exp_prop, cred,
9585 				    "limit_privileges", ":default") != 0)
9586 					err = 1;
9587 			}
9588 		}
9589 	}
9590 
9591 	if ((env = export_method_environment(pg)) != NULL) {
9592 		if (ctxt == NULL) {
9593 			ctxt = xmlNewNode(NULL, (xmlChar *)"method_context");
9594 			if (ctxt == NULL)
9595 				uu_die(emsg_create_xml);
9596 		}
9597 		(void) xmlAddChild(ctxt, env);
9598 	}
9599 
9600 	if (env != NULL || (nonenv && err == 0))
9601 		(void) xmlAddChild(n, ctxt);
9602 	else
9603 		xmlFreeNode(ctxt);
9604 
9605 	nonenv = (err == 0);
9606 
9607 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9608 		scfdie();
9609 
9610 	(void) memset(&elts, 0, sizeof (elts));
9611 
9612 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9613 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9614 			scfdie();
9615 
9616 		if (strcmp(exp_str, SCF_PROPERTY_TYPE) == 0 ||
9617 		    strcmp(exp_str, SCF_PROPERTY_EXEC) == 0 ||
9618 		    strcmp(exp_str, SCF_PROPERTY_TIMEOUT) == 0) {
9619 			continue;
9620 		} else if (strcmp(exp_str, SCF_PROPERTY_STABILITY) == 0) {
9621 			xmlNodePtr m;
9622 
9623 			m = xmlNewNode(NULL, (xmlChar *)"stability");
9624 			if (m == NULL)
9625 				uu_die(emsg_create_xml);
9626 
9627 			if (set_attr_from_prop(exp_prop, m, value_attr) == 0) {
9628 				elts.stability = m;
9629 				continue;
9630 			}
9631 
9632 			xmlFreeNode(m);
9633 		} else if (strcmp(exp_str, SCF_PROPERTY_WORKING_DIRECTORY) ==
9634 		    0 ||
9635 		    strcmp(exp_str, SCF_PROPERTY_PROJECT) == 0 ||
9636 		    strcmp(exp_str, SCF_PROPERTY_RESOURCE_POOL) == 0 ||
9637 		    strcmp(exp_str, SCF_PROPERTY_USE_PROFILE) == 0) {
9638 			if (nonenv)
9639 				continue;
9640 		} else if (strcmp(exp_str, SCF_PROPERTY_USER) == 0 ||
9641 		    strcmp(exp_str, SCF_PROPERTY_GROUP) == 0 ||
9642 		    strcmp(exp_str, SCF_PROPERTY_SUPP_GROUPS) == 0 ||
9643 		    strcmp(exp_str, SCF_PROPERTY_PRIVILEGES) == 0 ||
9644 		    strcmp(exp_str, SCF_PROPERTY_LIMIT_PRIVILEGES) == 0) {
9645 			if (nonenv && !use_profile)
9646 				continue;
9647 		} else if (strcmp(exp_str, SCF_PROPERTY_PROFILE) == 0) {
9648 			if (nonenv && use_profile)
9649 				continue;
9650 		} else if (strcmp(exp_str, SCF_PROPERTY_ENVIRONMENT) == 0) {
9651 			if (env != NULL)
9652 				continue;
9653 		}
9654 
9655 		export_property(exp_prop, exp_str, &elts, SCE_ALL_VALUES);
9656 	}
9657 	if (ret == -1)
9658 		scfdie();
9659 
9660 	(void) xmlAddChild(n, elts.stability);
9661 	(void) xmlAddChildList(n, elts.propvals);
9662 	(void) xmlAddChildList(n, elts.properties);
9663 
9664 	if (eelts->exec_methods == NULL)
9665 		eelts->exec_methods = n;
9666 	else
9667 		(void) xmlAddSibling(eelts->exec_methods, n);
9668 }
9669 
9670 static void
9671 export_pg_elts(struct pg_elts *elts, const char *name, const char *type,
9672     struct entity_elts *eelts)
9673 {
9674 	xmlNodePtr pgnode;
9675 
9676 	pgnode = xmlNewNode(NULL, (xmlChar *)"property_group");
9677 	if (pgnode == NULL)
9678 		uu_die(emsg_create_xml);
9679 
9680 	safe_setprop(pgnode, name_attr, name);
9681 	safe_setprop(pgnode, type_attr, type);
9682 
9683 	(void) xmlAddChildList(pgnode, elts->propvals);
9684 	(void) xmlAddChildList(pgnode, elts->properties);
9685 
9686 	if (eelts->property_groups == NULL)
9687 		eelts->property_groups = pgnode;
9688 	else
9689 		(void) xmlAddSibling(eelts->property_groups, pgnode);
9690 }
9691 
9692 /*
9693  * Process the general property group for a service.  This is the one with the
9694  * goodies.
9695  */
9696 static void
9697 export_svc_general(scf_propertygroup_t *pg, struct entity_elts *selts)
9698 {
9699 	struct pg_elts elts;
9700 	int ret;
9701 
9702 	/*
9703 	 * In case there are properties which don't correspond to child
9704 	 * entities of the service entity, we'll set up a pg_elts structure to
9705 	 * put them in.
9706 	 */
9707 	(void) memset(&elts, 0, sizeof (elts));
9708 
9709 	/* Walk the properties, looking for special ones. */
9710 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9711 		scfdie();
9712 
9713 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9714 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9715 			scfdie();
9716 
9717 		if (strcmp(exp_str, SCF_PROPERTY_SINGLE_INSTANCE) == 0) {
9718 			if (prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
9719 			    prop_get_val(exp_prop, exp_val) == 0) {
9720 				uint8_t b;
9721 
9722 				if (scf_value_get_boolean(exp_val, &b) !=
9723 				    SCF_SUCCESS)
9724 					scfdie();
9725 
9726 				if (b) {
9727 					selts->single_instance =
9728 					    xmlNewNode(NULL,
9729 					    (xmlChar *)"single_instance");
9730 					if (selts->single_instance == NULL)
9731 						uu_die(emsg_create_xml);
9732 				}
9733 
9734 				continue;
9735 			}
9736 		} else if (strcmp(exp_str, SCF_PROPERTY_RESTARTER) == 0) {
9737 			xmlNodePtr rnode, sfnode;
9738 
9739 			rnode = xmlNewNode(NULL, (xmlChar *)"restarter");
9740 			if (rnode == NULL)
9741 				uu_die(emsg_create_xml);
9742 
9743 			sfnode = xmlNewChild(rnode, NULL,
9744 			    (xmlChar *)"service_fmri", NULL);
9745 			if (sfnode == NULL)
9746 				uu_die(emsg_create_xml);
9747 
9748 			if (set_attr_from_prop(exp_prop, sfnode,
9749 			    value_attr) == 0) {
9750 				selts->restarter = rnode;
9751 				continue;
9752 			}
9753 
9754 			xmlFreeNode(rnode);
9755 		} else if (strcmp(exp_str, SCF_PROPERTY_ENTITY_STABILITY) ==
9756 		    0) {
9757 			xmlNodePtr s;
9758 
9759 			s = xmlNewNode(NULL, (xmlChar *)"stability");
9760 			if (s == NULL)
9761 				uu_die(emsg_create_xml);
9762 
9763 			if (set_attr_from_prop(exp_prop, s, value_attr) == 0) {
9764 				selts->stability = s;
9765 				continue;
9766 			}
9767 
9768 			xmlFreeNode(s);
9769 		}
9770 
9771 		export_property(exp_prop, exp_str, &elts, SCE_ALL_VALUES);
9772 	}
9773 	if (ret == -1)
9774 		scfdie();
9775 
9776 	if (elts.propvals != NULL || elts.properties != NULL)
9777 		export_pg_elts(&elts, scf_pg_general, scf_group_framework,
9778 		    selts);
9779 }
9780 
9781 static void
9782 export_method_context(scf_propertygroup_t *pg, struct entity_elts *elts)
9783 {
9784 	xmlNodePtr n, prof, cred, env;
9785 	uint8_t use_profile;
9786 	int ret, err = 0;
9787 
9788 	n = xmlNewNode(NULL, (xmlChar *)"method_context");
9789 
9790 	env = export_method_environment(pg);
9791 
9792 	/* Need to know whether we'll use a profile or not. */
9793 	if (pg_get_prop(pg, SCF_PROPERTY_USE_PROFILE, exp_prop) == 0 &&
9794 	    prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
9795 	    prop_get_val(exp_prop, exp_val) == 0) {
9796 		if (scf_value_get_boolean(exp_val, &use_profile) != SCF_SUCCESS)
9797 			scfdie();
9798 
9799 		if (use_profile)
9800 			prof =
9801 			    xmlNewChild(n, NULL, (xmlChar *)"method_profile",
9802 			    NULL);
9803 		else
9804 			cred =
9805 			    xmlNewChild(n, NULL, (xmlChar *)"method_credential",
9806 			    NULL);
9807 	}
9808 
9809 	if (env != NULL)
9810 		(void) xmlAddChild(n, env);
9811 
9812 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9813 		scfdie();
9814 
9815 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9816 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9817 			scfdie();
9818 
9819 		if (strcmp(exp_str, SCF_PROPERTY_WORKING_DIRECTORY) == 0) {
9820 			if (set_attr_from_prop(exp_prop, n,
9821 			    "working_directory") != 0)
9822 				err = 1;
9823 		} else if (strcmp(exp_str, SCF_PROPERTY_PROJECT) == 0) {
9824 			if (set_attr_from_prop(exp_prop, n, "project") != 0)
9825 				err = 1;
9826 		} else if (strcmp(exp_str, SCF_PROPERTY_RESOURCE_POOL) == 0) {
9827 			if (set_attr_from_prop(exp_prop, n,
9828 			    "resource_pool") != 0)
9829 				err = 1;
9830 		} else if (strcmp(exp_str, SCF_PROPERTY_USE_PROFILE) == 0) {
9831 			/* EMPTY */
9832 		} else if (strcmp(exp_str, SCF_PROPERTY_USER) == 0) {
9833 			if (use_profile ||
9834 			    set_attr_from_prop(exp_prop, cred, "user") != 0)
9835 				err = 1;
9836 		} else if (strcmp(exp_str, SCF_PROPERTY_GROUP) == 0) {
9837 			if (use_profile ||
9838 			    set_attr_from_prop(exp_prop, cred, "group") != 0)
9839 				err = 1;
9840 		} else if (strcmp(exp_str, SCF_PROPERTY_SUPP_GROUPS) == 0) {
9841 			if (use_profile || set_attr_from_prop(exp_prop, cred,
9842 			    "supp_groups") != 0)
9843 				err = 1;
9844 		} else if (strcmp(exp_str, SCF_PROPERTY_PRIVILEGES) == 0) {
9845 			if (use_profile || set_attr_from_prop(exp_prop, cred,
9846 			    "privileges") != 0)
9847 				err = 1;
9848 		} else if (strcmp(exp_str, SCF_PROPERTY_LIMIT_PRIVILEGES) ==
9849 		    0) {
9850 			if (use_profile || set_attr_from_prop(exp_prop, cred,
9851 			    "limit_privileges") != 0)
9852 				err = 1;
9853 		} else if (strcmp(exp_str, SCF_PROPERTY_PROFILE) == 0) {
9854 			if (!use_profile || set_attr_from_prop(exp_prop,
9855 			    prof, name_attr) != 0)
9856 				err = 1;
9857 		} else {
9858 			/* Can't have generic properties in method_context's */
9859 			err = 1;
9860 		}
9861 	}
9862 	if (ret == -1)
9863 		scfdie();
9864 
9865 	if (err && env == NULL) {
9866 		xmlFreeNode(n);
9867 		export_pg(pg, elts, SCE_ALL_VALUES);
9868 		return;
9869 	}
9870 
9871 	elts->method_context = n;
9872 }
9873 
9874 /*
9875  * Given a dependency property group in the tfmri entity (target fmri), return
9876  * a dependent element which represents it.
9877  */
9878 static xmlNodePtr
9879 export_dependent(scf_propertygroup_t *pg, const char *name, const char *tfmri)
9880 {
9881 	uint8_t b;
9882 	xmlNodePtr n, sf;
9883 	int err = 0, ret;
9884 	struct pg_elts pgelts;
9885 
9886 	/*
9887 	 * If external isn't set to true then exporting the service will
9888 	 * export this as a normal dependency, so we should stop to avoid
9889 	 * duplication.
9890 	 */
9891 	if (scf_pg_get_property(pg, scf_property_external, exp_prop) != 0 ||
9892 	    scf_property_get_value(exp_prop, exp_val) != 0 ||
9893 	    scf_value_get_boolean(exp_val, &b) != 0 || !b) {
9894 		if (g_verbose) {
9895 			warn(gettext("Dependent \"%s\" cannot be exported "
9896 			    "properly because the \"%s\" property of the "
9897 			    "\"%s\" dependency of %s is not set to true.\n"),
9898 			    name, scf_property_external, name, tfmri);
9899 		}
9900 
9901 		return (NULL);
9902 	}
9903 
9904 	n = xmlNewNode(NULL, (xmlChar *)"dependent");
9905 	if (n == NULL)
9906 		uu_die(emsg_create_xml);
9907 
9908 	safe_setprop(n, name_attr, name);
9909 
9910 	/* Get the required attributes */
9911 	if (pg_get_prop(pg, SCF_PROPERTY_RESTART_ON, exp_prop) != 0 ||
9912 	    set_attr_from_prop(exp_prop, n, "restart_on") != 0)
9913 		err = 1;
9914 
9915 	if (pg_get_prop(pg, SCF_PROPERTY_GROUPING, exp_prop) != 0 ||
9916 	    set_attr_from_prop(exp_prop, n, "grouping") != 0)
9917 		err = 1;
9918 
9919 	if (pg_get_prop(pg, SCF_PROPERTY_ENTITIES, exp_prop) == 0 &&
9920 	    prop_check_type(exp_prop, SCF_TYPE_FMRI) == 0 &&
9921 	    prop_get_val(exp_prop, exp_val) == 0) {
9922 		/* EMPTY */
9923 	} else
9924 		err = 1;
9925 
9926 	if (err) {
9927 		xmlFreeNode(n);
9928 		return (NULL);
9929 	}
9930 
9931 	sf = xmlNewChild(n, NULL, (xmlChar *)"service_fmri", NULL);
9932 	if (sf == NULL)
9933 		uu_die(emsg_create_xml);
9934 
9935 	safe_setprop(sf, value_attr, tfmri);
9936 
9937 	/*
9938 	 * Now add elements for the other properties.
9939 	 */
9940 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9941 		scfdie();
9942 
9943 	(void) memset(&pgelts, 0, sizeof (pgelts));
9944 
9945 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9946 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9947 			scfdie();
9948 
9949 		if (strcmp(exp_str, scf_property_external) == 0 ||
9950 		    strcmp(exp_str, SCF_PROPERTY_RESTART_ON) == 0 ||
9951 		    strcmp(exp_str, SCF_PROPERTY_GROUPING) == 0 ||
9952 		    strcmp(exp_str, SCF_PROPERTY_ENTITIES) == 0) {
9953 			continue;
9954 		} else if (strcmp(exp_str, SCF_PROPERTY_TYPE) == 0) {
9955 			if (prop_check_type(exp_prop, SCF_TYPE_ASTRING) == 0 &&
9956 			    prop_get_val(exp_prop, exp_val) == 0) {
9957 				char type[sizeof ("service") + 1];
9958 
9959 				if (scf_value_get_astring(exp_val, type,
9960 				    sizeof (type)) < 0)
9961 					scfdie();
9962 
9963 				if (strcmp(type, "service") == 0)
9964 					continue;
9965 			}
9966 		} else if (strcmp(exp_str, SCF_PROPERTY_STABILITY) == 0) {
9967 			xmlNodePtr s;
9968 
9969 			s = xmlNewNode(NULL, (xmlChar *)"stability");
9970 			if (s == NULL)
9971 				uu_die(emsg_create_xml);
9972 
9973 			if (set_attr_from_prop(exp_prop, s, value_attr) == 0) {
9974 				pgelts.stability = s;
9975 				continue;
9976 			}
9977 
9978 			xmlFreeNode(s);
9979 		}
9980 
9981 		export_property(exp_prop, exp_str, &pgelts, SCE_ALL_VALUES);
9982 	}
9983 	if (ret == -1)
9984 		scfdie();
9985 
9986 	(void) xmlAddChild(n, pgelts.stability);
9987 	(void) xmlAddChildList(n, pgelts.propvals);
9988 	(void) xmlAddChildList(n, pgelts.properties);
9989 
9990 	return (n);
9991 }
9992 
9993 static void
9994 export_dependents(scf_propertygroup_t *pg, struct entity_elts *eelts)
9995 {
9996 	scf_propertygroup_t *opg;
9997 	scf_iter_t *iter;
9998 	char *type, *fmri;
9999 	int ret;
10000 	struct pg_elts pgelts;
10001 	xmlNodePtr n;
10002 	scf_error_t serr;
10003 
10004 	if ((opg = scf_pg_create(g_hndl)) == NULL ||
10005 	    (iter = scf_iter_create(g_hndl)) == NULL)
10006 		scfdie();
10007 
10008 	/* Can't use exp_prop_iter due to export_dependent(). */
10009 	if (scf_iter_pg_properties(iter, pg) != SCF_SUCCESS)
10010 		scfdie();
10011 
10012 	type = safe_malloc(max_scf_pg_type_len + 1);
10013 
10014 	/* Get an extra byte so we can tell if values are too long. */
10015 	fmri = safe_malloc(max_scf_fmri_len + 2);
10016 
10017 	(void) memset(&pgelts, 0, sizeof (pgelts));
10018 
10019 	while ((ret = scf_iter_next_property(iter, exp_prop)) == 1) {
10020 		void *entity;
10021 		int isservice;
10022 		scf_type_t ty;
10023 
10024 		if (scf_property_type(exp_prop, &ty) != SCF_SUCCESS)
10025 			scfdie();
10026 
10027 		if ((ty != SCF_TYPE_ASTRING &&
10028 		    prop_check_type(exp_prop, SCF_TYPE_FMRI) != 0) ||
10029 		    prop_get_val(exp_prop, exp_val) != 0) {
10030 			export_property(exp_prop, NULL, &pgelts,
10031 			    SCE_ALL_VALUES);
10032 			continue;
10033 		}
10034 
10035 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
10036 			scfdie();
10037 
10038 		if (scf_value_get_astring(exp_val, fmri,
10039 		    max_scf_fmri_len + 2) < 0)
10040 			scfdie();
10041 
10042 		/* Look for a dependency group in the target fmri. */
10043 		serr = fmri_to_entity(g_hndl, fmri, &entity, &isservice);
10044 		switch (serr) {
10045 		case SCF_ERROR_NONE:
10046 			break;
10047 
10048 		case SCF_ERROR_NO_MEMORY:
10049 			uu_die(gettext("Out of memory.\n"));
10050 			/* NOTREACHED */
10051 
10052 		case SCF_ERROR_INVALID_ARGUMENT:
10053 			if (g_verbose) {
10054 				if (scf_property_to_fmri(exp_prop, fmri,
10055 				    max_scf_fmri_len + 2) < 0)
10056 					scfdie();
10057 
10058 				warn(gettext("The value of %s is not a valid "
10059 				    "FMRI.\n"), fmri);
10060 			}
10061 
10062 			export_property(exp_prop, exp_str, &pgelts,
10063 			    SCE_ALL_VALUES);
10064 			continue;
10065 
10066 		case SCF_ERROR_CONSTRAINT_VIOLATED:
10067 			if (g_verbose) {
10068 				if (scf_property_to_fmri(exp_prop, fmri,
10069 				    max_scf_fmri_len + 2) < 0)
10070 					scfdie();
10071 
10072 				warn(gettext("The value of %s does not specify "
10073 				    "a service or an instance.\n"), fmri);
10074 			}
10075 
10076 			export_property(exp_prop, exp_str, &pgelts,
10077 			    SCE_ALL_VALUES);
10078 			continue;
10079 
10080 		case SCF_ERROR_NOT_FOUND:
10081 			if (g_verbose) {
10082 				if (scf_property_to_fmri(exp_prop, fmri,
10083 				    max_scf_fmri_len + 2) < 0)
10084 					scfdie();
10085 
10086 				warn(gettext("The entity specified by %s does "
10087 				    "not exist.\n"), fmri);
10088 			}
10089 
10090 			export_property(exp_prop, exp_str, &pgelts,
10091 			    SCE_ALL_VALUES);
10092 			continue;
10093 
10094 		default:
10095 #ifndef NDEBUG
10096 			(void) fprintf(stderr, "%s:%d: %s() failed with "
10097 			    "unexpected error %d.\n", __FILE__, __LINE__,
10098 			    "fmri_to_entity", serr);
10099 #endif
10100 			abort();
10101 		}
10102 
10103 		if (entity_get_pg(entity, isservice, exp_str, opg) != 0) {
10104 			if (scf_error() != SCF_ERROR_NOT_FOUND)
10105 				scfdie();
10106 
10107 			warn(gettext("Entity %s is missing dependency property "
10108 			    "group %s.\n"), fmri, exp_str);
10109 
10110 			export_property(exp_prop, NULL, &pgelts,
10111 			    SCE_ALL_VALUES);
10112 			continue;
10113 		}
10114 
10115 		if (scf_pg_get_type(opg, type, max_scf_pg_type_len + 1) < 0)
10116 			scfdie();
10117 
10118 		if (strcmp(type, SCF_GROUP_DEPENDENCY) != 0) {
10119 			if (scf_pg_to_fmri(opg, fmri, max_scf_fmri_len + 2) < 0)
10120 				scfdie();
10121 
10122 			warn(gettext("Property group %s is not of "
10123 			    "expected type %s.\n"), fmri, SCF_GROUP_DEPENDENCY);
10124 
10125 			export_property(exp_prop, NULL, &pgelts,
10126 			    SCE_ALL_VALUES);
10127 			continue;
10128 		}
10129 
10130 		n = export_dependent(opg, exp_str, fmri);
10131 		if (n == NULL) {
10132 			export_property(exp_prop, exp_str, &pgelts,
10133 			    SCE_ALL_VALUES);
10134 		} else {
10135 			if (eelts->dependents == NULL)
10136 				eelts->dependents = n;
10137 			else
10138 				(void) xmlAddSibling(eelts->dependents,
10139 				    n);
10140 		}
10141 	}
10142 	if (ret == -1)
10143 		scfdie();
10144 
10145 	free(fmri);
10146 	free(type);
10147 
10148 	scf_iter_destroy(iter);
10149 	scf_pg_destroy(opg);
10150 
10151 	if (pgelts.propvals != NULL || pgelts.properties != NULL)
10152 		export_pg_elts(&pgelts, SCF_PG_DEPENDENTS, scf_group_framework,
10153 		    eelts);
10154 }
10155 
10156 static void
10157 make_node(xmlNodePtr *nodep, const char *name)
10158 {
10159 	if (*nodep == NULL) {
10160 		*nodep = xmlNewNode(NULL, (xmlChar *)name);
10161 		if (*nodep == NULL)
10162 			uu_die(emsg_create_xml);
10163 	}
10164 }
10165 
10166 static xmlNodePtr
10167 export_tm_loctext(scf_propertygroup_t *pg, const char *parname)
10168 {
10169 	int ret;
10170 	xmlNodePtr parent = NULL;
10171 	xmlNodePtr loctext = NULL;
10172 
10173 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
10174 		scfdie();
10175 
10176 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
10177 		if (prop_check_type(exp_prop, SCF_TYPE_USTRING) != 0 ||
10178 		    prop_get_val(exp_prop, exp_val) != 0)
10179 			continue;
10180 
10181 		if (scf_value_get_ustring(exp_val, exp_str, exp_str_sz) < 0)
10182 			scfdie();
10183 
10184 		make_node(&parent, parname);
10185 		loctext = xmlNewTextChild(parent, NULL, (xmlChar *)"loctext",
10186 		    (xmlChar *)exp_str);
10187 		if (loctext == NULL)
10188 			uu_die(emsg_create_xml);
10189 
10190 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
10191 			scfdie();
10192 
10193 		safe_setprop(loctext, "xml:lang", exp_str);
10194 	}
10195 
10196 	if (ret == -1)
10197 		scfdie();
10198 
10199 	return (parent);
10200 }
10201 
10202 static xmlNodePtr
10203 export_tm_manpage(scf_propertygroup_t *pg)
10204 {
10205 	xmlNodePtr manpage = xmlNewNode(NULL, (xmlChar *)"manpage");
10206 	if (manpage == NULL)
10207 		uu_die(emsg_create_xml);
10208 
10209 	if (pg_get_prop(pg, SCF_PROPERTY_TM_TITLE, exp_prop) != 0 ||
10210 	    set_attr_from_prop(exp_prop, manpage, "title") != 0 ||
10211 	    pg_get_prop(pg, SCF_PROPERTY_TM_SECTION, exp_prop) != 0 ||
10212 	    set_attr_from_prop(exp_prop, manpage, "section") != 0) {
10213 		xmlFreeNode(manpage);
10214 		return (NULL);
10215 	}
10216 
10217 	if (pg_get_prop(pg, SCF_PROPERTY_TM_MANPATH, exp_prop) == 0)
10218 		(void) set_attr_from_prop_default(exp_prop,
10219 		    manpage, "manpath", ":default");
10220 
10221 	return (manpage);
10222 }
10223 
10224 static xmlNodePtr
10225 export_tm_doc_link(scf_propertygroup_t *pg)
10226 {
10227 	xmlNodePtr doc_link = xmlNewNode(NULL, (xmlChar *)"doc_link");
10228 	if (doc_link == NULL)
10229 		uu_die(emsg_create_xml);
10230 
10231 	if (pg_get_prop(pg, SCF_PROPERTY_TM_NAME, exp_prop) != 0 ||
10232 	    set_attr_from_prop(exp_prop, doc_link, "name") != 0 ||
10233 	    pg_get_prop(pg, SCF_PROPERTY_TM_URI, exp_prop) != 0 ||
10234 	    set_attr_from_prop(exp_prop, doc_link, "uri") != 0) {
10235 		xmlFreeNode(doc_link);
10236 		return (NULL);
10237 	}
10238 	return (doc_link);
10239 }
10240 
10241 /*
10242  * Process template information for a service or instances.
10243  */
10244 static void
10245 export_template(scf_propertygroup_t *pg, struct entity_elts *elts,
10246     struct template_elts *telts)
10247 {
10248 	size_t mansz = strlen(SCF_PG_TM_MAN_PREFIX);
10249 	size_t docsz = strlen(SCF_PG_TM_DOC_PREFIX);
10250 	xmlNodePtr child = NULL;
10251 
10252 	if (scf_pg_get_name(pg, exp_str, exp_str_sz) < 0)
10253 		scfdie();
10254 
10255 	if (strcmp(exp_str, SCF_PG_TM_COMMON_NAME) == 0) {
10256 		telts->common_name = export_tm_loctext(pg, "common_name");
10257 		if (telts->common_name == NULL)
10258 			export_pg(pg, elts, SCE_ALL_VALUES);
10259 		return;
10260 	} else if (strcmp(exp_str, SCF_PG_TM_DESCRIPTION) == 0) {
10261 		telts->description = export_tm_loctext(pg, "description");
10262 		if (telts->description == NULL)
10263 			export_pg(pg, elts, SCE_ALL_VALUES);
10264 		return;
10265 	}
10266 
10267 	if (strncmp(exp_str, SCF_PG_TM_MAN_PREFIX, mansz) == 0) {
10268 		child = export_tm_manpage(pg);
10269 	} else if (strncmp(exp_str, SCF_PG_TM_DOC_PREFIX, docsz) == 0) {
10270 		child = export_tm_doc_link(pg);
10271 	}
10272 
10273 	if (child != NULL) {
10274 		make_node(&telts->documentation, "documentation");
10275 		(void) xmlAddChild(telts->documentation, child);
10276 	} else {
10277 		export_pg(pg, elts, SCE_ALL_VALUES);
10278 	}
10279 }
10280 
10281 /*
10282  * Process parameter and paramval elements
10283  */
10284 static void
10285 export_parameter(scf_property_t *prop, const char *name,
10286     struct params_elts *elts)
10287 {
10288 	xmlNodePtr param;
10289 	scf_error_t err = 0;
10290 	int ret;
10291 
10292 	if (scf_property_get_value(prop, exp_val) == SCF_SUCCESS) {
10293 		if ((param = xmlNewNode(NULL, (xmlChar *)"paramval")) == NULL)
10294 			uu_die(emsg_create_xml);
10295 
10296 		safe_setprop(param, name_attr, name);
10297 
10298 		if (scf_value_get_as_string(exp_val, exp_str, exp_str_sz) < 0)
10299 			scfdie();
10300 		safe_setprop(param, value_attr, exp_str);
10301 
10302 		if (elts->paramval == NULL)
10303 			elts->paramval = param;
10304 		else
10305 			(void) xmlAddSibling(elts->paramval, param);
10306 
10307 		return;
10308 	}
10309 
10310 	err = scf_error();
10311 
10312 	if (err != SCF_ERROR_CONSTRAINT_VIOLATED &&
10313 	    err != SCF_ERROR_NOT_FOUND)
10314 		scfdie();
10315 
10316 	if ((param = xmlNewNode(NULL, (xmlChar *)"parameter")) == NULL)
10317 		uu_die(emsg_create_xml);
10318 
10319 	safe_setprop(param, name_attr, name);
10320 
10321 	if (err == SCF_ERROR_CONSTRAINT_VIOLATED) {
10322 		if (scf_iter_property_values(exp_val_iter, prop) != SCF_SUCCESS)
10323 			scfdie();
10324 
10325 		while ((ret = scf_iter_next_value(exp_val_iter, exp_val)) ==
10326 		    1) {
10327 			xmlNodePtr vn;
10328 
10329 			if ((vn = xmlNewChild(param, NULL,
10330 			    (xmlChar *)"value_node", NULL)) == NULL)
10331 				uu_die(emsg_create_xml);
10332 
10333 			if (scf_value_get_as_string(exp_val, exp_str,
10334 			    exp_str_sz) < 0)
10335 				scfdie();
10336 
10337 			safe_setprop(vn, value_attr, exp_str);
10338 		}
10339 		if (ret != 0)
10340 			scfdie();
10341 	}
10342 
10343 	if (elts->parameter == NULL)
10344 		elts->parameter = param;
10345 	else
10346 		(void) xmlAddSibling(elts->parameter, param);
10347 }
10348 
10349 /*
10350  * Process notification parameters for a service or instance
10351  */
10352 static void
10353 export_notify_params(scf_propertygroup_t *pg, struct entity_elts *elts)
10354 {
10355 	xmlNodePtr n, event, *type;
10356 	struct params_elts *eelts;
10357 	int ret, err, i;
10358 
10359 	n = xmlNewNode(NULL, (xmlChar *)"notification_parameters");
10360 	event = xmlNewNode(NULL, (xmlChar *)"event");
10361 	if (n == NULL || event == NULL)
10362 		uu_die(emsg_create_xml);
10363 
10364 	/* event value */
10365 	if (scf_pg_get_name(pg, exp_str, max_scf_name_len + 1) < 0)
10366 		scfdie();
10367 	safe_setprop(event, value_attr, exp_str);
10368 
10369 	(void) xmlAddChild(n, event);
10370 
10371 	if ((type = calloc(URI_SCHEME_NUM, sizeof (xmlNodePtr))) == NULL ||
10372 	    (eelts = calloc(URI_SCHEME_NUM,
10373 	    sizeof (struct params_elts))) == NULL)
10374 		uu_die(gettext("Out of memory.\n"));
10375 
10376 	err = 0;
10377 
10378 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
10379 		scfdie();
10380 
10381 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
10382 		char *t, *p;
10383 
10384 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
10385 			scfdie();
10386 
10387 		if ((t = strtok_r(exp_str, ",", &p)) == NULL || p == NULL) {
10388 			/*
10389 			 * this is not a well formed notification parameters
10390 			 * element, we should export as regular pg
10391 			 */
10392 			err = 1;
10393 			break;
10394 		}
10395 
10396 		if ((i = check_uri_protocol(t)) < 0) {
10397 			err = 1;
10398 			break;
10399 		}
10400 
10401 		if (type[i] == NULL) {
10402 			if ((type[i] = xmlNewNode(NULL, (xmlChar *)"type")) ==
10403 			    NULL)
10404 				uu_die(emsg_create_xml);
10405 
10406 			safe_setprop(type[i], name_attr, t);
10407 		}
10408 		if (strcmp(p, active_attr) == 0) {
10409 			if (set_attr_from_prop(exp_prop, type[i],
10410 			    active_attr) != 0) {
10411 				err = 1;
10412 				break;
10413 			}
10414 			continue;
10415 		}
10416 		/*
10417 		 * We export the parameter
10418 		 */
10419 		export_parameter(exp_prop, p, &eelts[i]);
10420 	}
10421 
10422 	if (ret == -1)
10423 		scfdie();
10424 
10425 	if (err == 1) {
10426 		for (i = 0; i < URI_SCHEME_NUM; ++i)
10427 			xmlFree(type[i]);
10428 		free(type);
10429 
10430 		export_pg(pg, elts, SCE_ALL_VALUES);
10431 
10432 		return;
10433 	} else {
10434 		for (i = 0; i < URI_SCHEME_NUM; ++i)
10435 			if (type[i] != NULL) {
10436 				(void) xmlAddChildList(type[i],
10437 				    eelts[i].paramval);
10438 				(void) xmlAddChildList(type[i],
10439 				    eelts[i].parameter);
10440 				(void) xmlAddSibling(event, type[i]);
10441 			}
10442 	}
10443 	free(type);
10444 
10445 	if (elts->notify_params == NULL)
10446 		elts->notify_params = n;
10447 	else
10448 		(void) xmlAddSibling(elts->notify_params, n);
10449 }
10450 
10451 /*
10452  * Process the general property group for an instance.
10453  */
10454 static void
10455 export_inst_general(scf_propertygroup_t *pg, xmlNodePtr inode,
10456     struct entity_elts *elts)
10457 {
10458 	uint8_t enabled;
10459 	struct pg_elts pgelts;
10460 	int ret;
10461 
10462 	/* enabled */
10463 	if (pg_get_prop(pg, scf_property_enabled, exp_prop) == 0 &&
10464 	    prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
10465 	    prop_get_val(exp_prop, exp_val) == 0) {
10466 		if (scf_value_get_boolean(exp_val, &enabled) != SCF_SUCCESS)
10467 			scfdie();
10468 	} else {
10469 		enabled = 0;
10470 	}
10471 
10472 	safe_setprop(inode, enabled_attr, enabled ? true : false);
10473 
10474 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
10475 		scfdie();
10476 
10477 	(void) memset(&pgelts, 0, sizeof (pgelts));
10478 
10479 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
10480 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
10481 			scfdie();
10482 
10483 		if (strcmp(exp_str, scf_property_enabled) == 0) {
10484 			continue;
10485 		} else if (strcmp(exp_str, SCF_PROPERTY_RESTARTER) == 0) {
10486 			xmlNodePtr rnode, sfnode;
10487 
10488 			rnode = xmlNewNode(NULL, (xmlChar *)"restarter");
10489 			if (rnode == NULL)
10490 				uu_die(emsg_create_xml);
10491 
10492 			sfnode = xmlNewChild(rnode, NULL,
10493 			    (xmlChar *)"service_fmri", NULL);
10494 			if (sfnode == NULL)
10495 				uu_die(emsg_create_xml);
10496 
10497 			if (set_attr_from_prop(exp_prop, sfnode,
10498 			    value_attr) == 0) {
10499 				elts->restarter = rnode;
10500 				continue;
10501 			}
10502 
10503 			xmlFreeNode(rnode);
10504 		}
10505 
10506 		export_property(exp_prop, exp_str, &pgelts, SCE_ALL_VALUES);
10507 	}
10508 	if (ret == -1)
10509 		scfdie();
10510 
10511 	if (pgelts.propvals != NULL || pgelts.properties != NULL)
10512 		export_pg_elts(&pgelts, scf_pg_general, scf_group_framework,
10513 		    elts);
10514 }
10515 
10516 /*
10517  * Put an instance element for the given instance into selts.
10518  */
10519 static void
10520 export_instance(scf_instance_t *inst, struct entity_elts *selts, int flags)
10521 {
10522 	xmlNodePtr n;
10523 	boolean_t isdefault;
10524 	struct entity_elts elts;
10525 	struct template_elts template_elts;
10526 	int ret;
10527 
10528 	n = xmlNewNode(NULL, (xmlChar *)"instance");
10529 	if (n == NULL)
10530 		uu_die(emsg_create_xml);
10531 
10532 	/* name */
10533 	if (scf_instance_get_name(inst, exp_str, exp_str_sz) < 0)
10534 		scfdie();
10535 	safe_setprop(n, name_attr, exp_str);
10536 	isdefault = strcmp(exp_str, "default") == 0;
10537 
10538 	/* check existance of general pg (since general/enabled is required) */
10539 	if (scf_instance_get_pg(inst, scf_pg_general, exp_pg) != SCF_SUCCESS) {
10540 		if (scf_error() != SCF_ERROR_NOT_FOUND)
10541 			scfdie();
10542 
10543 		if (g_verbose) {
10544 			if (scf_instance_to_fmri(inst, exp_str, exp_str_sz) < 0)
10545 				scfdie();
10546 
10547 			warn(gettext("Instance %s has no general property "
10548 			    "group; it will be marked disabled.\n"), exp_str);
10549 		}
10550 
10551 		safe_setprop(n, enabled_attr, false);
10552 	} else if (scf_pg_get_type(exp_pg, exp_str, exp_str_sz) < 0 ||
10553 	    strcmp(exp_str, scf_group_framework) != 0) {
10554 		if (g_verbose) {
10555 			if (scf_pg_to_fmri(exp_pg, exp_str, exp_str_sz) < 0)
10556 				scfdie();
10557 
10558 			warn(gettext("Property group %s is not of type "
10559 			    "framework; the instance will be marked "
10560 			    "disabled.\n"), exp_str);
10561 		}
10562 
10563 		safe_setprop(n, enabled_attr, false);
10564 	}
10565 
10566 	/* property groups */
10567 	if (scf_iter_instance_pgs(exp_pg_iter, inst) < 0)
10568 		scfdie();
10569 
10570 	(void) memset(&elts, 0, sizeof (elts));
10571 	(void) memset(&template_elts, 0, sizeof (template_elts));
10572 
10573 	while ((ret = scf_iter_next_pg(exp_pg_iter, exp_pg)) == 1) {
10574 		uint32_t pgflags;
10575 
10576 		if (scf_pg_get_flags(exp_pg, &pgflags) != 0)
10577 			scfdie();
10578 
10579 		if (pgflags & SCF_PG_FLAG_NONPERSISTENT)
10580 			continue;
10581 
10582 		if (scf_pg_get_type(exp_pg, exp_str, exp_str_sz) < 0)
10583 			scfdie();
10584 
10585 		if (strcmp(exp_str, SCF_GROUP_DEPENDENCY) == 0) {
10586 			export_dependency(exp_pg, &elts);
10587 			continue;
10588 		} else if (strcmp(exp_str, SCF_GROUP_METHOD) == 0) {
10589 			export_method(exp_pg, &elts);
10590 			continue;
10591 		} else if (strcmp(exp_str, scf_group_framework) == 0) {
10592 			if (scf_pg_get_name(exp_pg, exp_str,
10593 			    max_scf_name_len + 1) < 0)
10594 				scfdie();
10595 
10596 			if (strcmp(exp_str, scf_pg_general) == 0) {
10597 				export_inst_general(exp_pg, n, &elts);
10598 				continue;
10599 			} else if (strcmp(exp_str, SCF_PG_METHOD_CONTEXT) ==
10600 			    0) {
10601 				export_method_context(exp_pg, &elts);
10602 				continue;
10603 			} else if (strcmp(exp_str, SCF_PG_DEPENDENTS) == 0) {
10604 				export_dependents(exp_pg, &elts);
10605 				continue;
10606 			}
10607 		} else if (strcmp(exp_str, SCF_GROUP_TEMPLATE) == 0) {
10608 			export_template(exp_pg, &elts, &template_elts);
10609 			continue;
10610 		} else if (strcmp(exp_str, SCF_NOTIFY_PARAMS_PG_TYPE) == 0) {
10611 			export_notify_params(exp_pg, &elts);
10612 			continue;
10613 		}
10614 
10615 		/* Ordinary pg. */
10616 		export_pg(exp_pg, &elts, flags);
10617 	}
10618 	if (ret == -1)
10619 		scfdie();
10620 
10621 	if (template_elts.common_name != NULL) {
10622 		elts.template = xmlNewNode(NULL, (xmlChar *)"template");
10623 		(void) xmlAddChild(elts.template, template_elts.common_name);
10624 		(void) xmlAddChild(elts.template, template_elts.description);
10625 		(void) xmlAddChild(elts.template, template_elts.documentation);
10626 	} else {
10627 		xmlFreeNode(template_elts.description);
10628 		xmlFreeNode(template_elts.documentation);
10629 	}
10630 
10631 	if (isdefault && elts.restarter == NULL &&
10632 	    elts.dependencies == NULL && elts.method_context == NULL &&
10633 	    elts.exec_methods == NULL && elts.notify_params == NULL &&
10634 	    elts.property_groups == NULL && elts.template == NULL) {
10635 		xmlChar *eval;
10636 
10637 		/* This is a default instance */
10638 		eval = xmlGetProp(n, (xmlChar *)enabled_attr);
10639 
10640 		xmlFreeNode(n);
10641 
10642 		n = xmlNewNode(NULL, (xmlChar *)"create_default_instance");
10643 		if (n == NULL)
10644 			uu_die(emsg_create_xml);
10645 
10646 		safe_setprop(n, enabled_attr, (char *)eval);
10647 		xmlFree(eval);
10648 
10649 		selts->create_default_instance = n;
10650 	} else {
10651 		/* Assemble the children in order. */
10652 		(void) xmlAddChild(n, elts.restarter);
10653 		(void) xmlAddChildList(n, elts.dependencies);
10654 		(void) xmlAddChildList(n, elts.dependents);
10655 		(void) xmlAddChild(n, elts.method_context);
10656 		(void) xmlAddChildList(n, elts.exec_methods);
10657 		(void) xmlAddChildList(n, elts.notify_params);
10658 		(void) xmlAddChildList(n, elts.property_groups);
10659 		(void) xmlAddChild(n, elts.template);
10660 
10661 		if (selts->instances == NULL)
10662 			selts->instances = n;
10663 		else
10664 			(void) xmlAddSibling(selts->instances, n);
10665 	}
10666 }
10667 
10668 /*
10669  * Return a service element for the given service.
10670  */
10671 static xmlNodePtr
10672 export_service(scf_service_t *svc, int flags)
10673 {
10674 	xmlNodePtr snode;
10675 	struct entity_elts elts;
10676 	struct template_elts template_elts;
10677 	int ret;
10678 
10679 	snode = xmlNewNode(NULL, (xmlChar *)"service");
10680 	if (snode == NULL)
10681 		uu_die(emsg_create_xml);
10682 
10683 	/* Get & set name attribute */
10684 	if (scf_service_get_name(svc, exp_str, max_scf_name_len + 1) < 0)
10685 		scfdie();
10686 	safe_setprop(snode, name_attr, exp_str);
10687 
10688 	safe_setprop(snode, type_attr, "service");
10689 	safe_setprop(snode, "version", "0");
10690 
10691 	/* Acquire child elements. */
10692 	if (scf_iter_service_pgs(exp_pg_iter, svc) != SCF_SUCCESS)
10693 		scfdie();
10694 
10695 	(void) memset(&elts, 0, sizeof (elts));
10696 	(void) memset(&template_elts, 0, sizeof (template_elts));
10697 
10698 	while ((ret = scf_iter_next_pg(exp_pg_iter, exp_pg)) == 1) {
10699 		uint32_t pgflags;
10700 
10701 		if (scf_pg_get_flags(exp_pg, &pgflags) != 0)
10702 			scfdie();
10703 
10704 		if (pgflags & SCF_PG_FLAG_NONPERSISTENT)
10705 			continue;
10706 
10707 		if (scf_pg_get_type(exp_pg, exp_str, exp_str_sz) < 0)
10708 			scfdie();
10709 
10710 		if (strcmp(exp_str, SCF_GROUP_DEPENDENCY) == 0) {
10711 			export_dependency(exp_pg, &elts);
10712 			continue;
10713 		} else if (strcmp(exp_str, SCF_GROUP_METHOD) == 0) {
10714 			export_method(exp_pg, &elts);
10715 			continue;
10716 		} else if (strcmp(exp_str, scf_group_framework) == 0) {
10717 			if (scf_pg_get_name(exp_pg, exp_str,
10718 			    max_scf_name_len + 1) < 0)
10719 				scfdie();
10720 
10721 			if (strcmp(exp_str, scf_pg_general) == 0) {
10722 				export_svc_general(exp_pg, &elts);
10723 				continue;
10724 			} else if (strcmp(exp_str, SCF_PG_METHOD_CONTEXT) ==
10725 			    0) {
10726 				export_method_context(exp_pg, &elts);
10727 				continue;
10728 			} else if (strcmp(exp_str, SCF_PG_DEPENDENTS) == 0) {
10729 				export_dependents(exp_pg, &elts);
10730 				continue;
10731 			} else if (strcmp(exp_str, SCF_PG_MANIFESTFILES) == 0) {
10732 				continue;
10733 			}
10734 		} else if (strcmp(exp_str, SCF_GROUP_TEMPLATE) == 0) {
10735 			export_template(exp_pg, &elts, &template_elts);
10736 			continue;
10737 		} else if (strcmp(exp_str, SCF_NOTIFY_PARAMS_PG_TYPE) == 0) {
10738 			export_notify_params(exp_pg, &elts);
10739 			continue;
10740 		}
10741 
10742 		export_pg(exp_pg, &elts, flags);
10743 	}
10744 	if (ret == -1)
10745 		scfdie();
10746 
10747 	if (template_elts.common_name != NULL) {
10748 		elts.template = xmlNewNode(NULL, (xmlChar *)"template");
10749 		(void) xmlAddChild(elts.template, template_elts.common_name);
10750 		(void) xmlAddChild(elts.template, template_elts.description);
10751 		(void) xmlAddChild(elts.template, template_elts.documentation);
10752 	} else {
10753 		xmlFreeNode(template_elts.description);
10754 		xmlFreeNode(template_elts.documentation);
10755 	}
10756 
10757 	/* Iterate instances */
10758 	if (scf_iter_service_instances(exp_inst_iter, svc) != SCF_SUCCESS)
10759 		scfdie();
10760 
10761 	while ((ret = scf_iter_next_instance(exp_inst_iter, exp_inst)) == 1)
10762 		export_instance(exp_inst, &elts, flags);
10763 	if (ret == -1)
10764 		scfdie();
10765 
10766 	/* Now add all of the accumulated elements in order. */
10767 	(void) xmlAddChild(snode, elts.create_default_instance);
10768 	(void) xmlAddChild(snode, elts.single_instance);
10769 	(void) xmlAddChild(snode, elts.restarter);
10770 	(void) xmlAddChildList(snode, elts.dependencies);
10771 	(void) xmlAddChildList(snode, elts.dependents);
10772 	(void) xmlAddChild(snode, elts.method_context);
10773 	(void) xmlAddChildList(snode, elts.exec_methods);
10774 	(void) xmlAddChildList(snode, elts.notify_params);
10775 	(void) xmlAddChildList(snode, elts.property_groups);
10776 	(void) xmlAddChildList(snode, elts.instances);
10777 	(void) xmlAddChild(snode, elts.stability);
10778 	(void) xmlAddChild(snode, elts.template);
10779 
10780 	return (snode);
10781 }
10782 
10783 static int
10784 export_callback(void *data, scf_walkinfo_t *wip)
10785 {
10786 	FILE *f;
10787 	xmlDocPtr doc;
10788 	xmlNodePtr sb;
10789 	int result;
10790 	struct export_args *argsp = (struct export_args *)data;
10791 
10792 	if ((exp_inst = scf_instance_create(g_hndl)) == NULL ||
10793 	    (exp_pg = scf_pg_create(g_hndl)) == NULL ||
10794 	    (exp_prop = scf_property_create(g_hndl)) == NULL ||
10795 	    (exp_val = scf_value_create(g_hndl)) == NULL ||
10796 	    (exp_inst_iter = scf_iter_create(g_hndl)) == NULL ||
10797 	    (exp_pg_iter = scf_iter_create(g_hndl)) == NULL ||
10798 	    (exp_prop_iter = scf_iter_create(g_hndl)) == NULL ||
10799 	    (exp_val_iter = scf_iter_create(g_hndl)) == NULL)
10800 		scfdie();
10801 
10802 	exp_str_sz = max_scf_len + 1;
10803 	exp_str = safe_malloc(exp_str_sz);
10804 
10805 	if (argsp->filename != NULL) {
10806 		errno = 0;
10807 		f = fopen(argsp->filename, "wb");
10808 		if (f == NULL) {
10809 			if (errno == 0)
10810 				uu_die(gettext("Could not open \"%s\": no free "
10811 				    "stdio streams.\n"), argsp->filename);
10812 			else
10813 				uu_die(gettext("Could not open \"%s\""),
10814 				    argsp->filename);
10815 		}
10816 	} else
10817 		f = stdout;
10818 
10819 	doc = xmlNewDoc((xmlChar *)"1.0");
10820 	if (doc == NULL)
10821 		uu_die(gettext("Could not create XML document.\n"));
10822 
10823 	if (xmlCreateIntSubset(doc, (xmlChar *)"service_bundle", NULL,
10824 	    (xmlChar *)MANIFEST_DTD_PATH) == NULL)
10825 		uu_die(emsg_create_xml);
10826 
10827 	sb = xmlNewNode(NULL, (xmlChar *)"service_bundle");
10828 	if (sb == NULL)
10829 		uu_die(emsg_create_xml);
10830 	safe_setprop(sb, type_attr, "manifest");
10831 	safe_setprop(sb, name_attr, "export");
10832 	(void) xmlAddSibling(doc->children, sb);
10833 
10834 	(void) xmlAddChild(sb, export_service(wip->svc, argsp->flags));
10835 
10836 	result = write_service_bundle(doc, f);
10837 
10838 	free(exp_str);
10839 	scf_iter_destroy(exp_val_iter);
10840 	scf_iter_destroy(exp_prop_iter);
10841 	scf_iter_destroy(exp_pg_iter);
10842 	scf_iter_destroy(exp_inst_iter);
10843 	scf_value_destroy(exp_val);
10844 	scf_property_destroy(exp_prop);
10845 	scf_pg_destroy(exp_pg);
10846 	scf_instance_destroy(exp_inst);
10847 
10848 	xmlFreeDoc(doc);
10849 
10850 	if (f != stdout)
10851 		(void) fclose(f);
10852 
10853 	return (result);
10854 }
10855 
10856 /*
10857  * Get the service named by fmri, build an XML tree which represents it, and
10858  * dump it into filename (or stdout if filename is NULL).
10859  */
10860 int
10861 lscf_service_export(char *fmri, const char *filename, int flags)
10862 {
10863 	struct export_args args;
10864 	char *fmridup;
10865 	const char *scope, *svc, *inst;
10866 	size_t cblen = 3 * max_scf_name_len;
10867 	char *canonbuf = alloca(cblen);
10868 	int ret, err;
10869 
10870 	lscf_prep_hndl();
10871 
10872 	bzero(&args, sizeof (args));
10873 	args.filename = filename;
10874 	args.flags = flags;
10875 
10876 	/*
10877 	 * If some poor user has passed an exact instance FMRI, of the sort
10878 	 * one might cut and paste from svcs(1) or an error message, warn
10879 	 * and chop off the instance instead of failing.
10880 	 */
10881 	fmridup = alloca(strlen(fmri) + 1);
10882 	(void) strcpy(fmridup, fmri);
10883 	if (strncmp(fmridup, SCF_FMRI_SVC_PREFIX,
10884 	    sizeof (SCF_FMRI_SVC_PREFIX) -1) == 0 &&
10885 	    scf_parse_svc_fmri(fmridup, &scope, &svc, &inst, NULL, NULL) == 0 &&
10886 	    inst != NULL) {
10887 		(void) strlcpy(canonbuf, "svc:/", cblen);
10888 		if (strcmp(scope, SCF_FMRI_LOCAL_SCOPE) != 0) {
10889 			(void) strlcat(canonbuf, "/", cblen);
10890 			(void) strlcat(canonbuf, scope, cblen);
10891 		}
10892 		(void) strlcat(canonbuf, svc, cblen);
10893 		fmri = canonbuf;
10894 
10895 		warn(gettext("Only services may be exported; ignoring "
10896 		    "instance portion of argument.\n"));
10897 	}
10898 
10899 	err = 0;
10900 	if ((ret = scf_walk_fmri(g_hndl, 1, (char **)&fmri,
10901 	    SCF_WALK_SERVICE | SCF_WALK_NOINSTANCE, export_callback,
10902 	    &args, &err, semerr)) != 0) {
10903 		if (ret != -1)
10904 			semerr(gettext("Failed to walk instances: %s\n"),
10905 			    scf_strerror(ret));
10906 		return (-1);
10907 	}
10908 
10909 	/*
10910 	 * Error message has already been printed.
10911 	 */
10912 	if (err != 0)
10913 		return (-1);
10914 
10915 	return (0);
10916 }
10917 
10918 
10919 /*
10920  * Archive
10921  */
10922 
10923 static xmlNodePtr
10924 make_archive(int flags)
10925 {
10926 	xmlNodePtr sb;
10927 	scf_scope_t *scope;
10928 	scf_service_t *svc;
10929 	scf_iter_t *iter;
10930 	int r;
10931 
10932 	if ((scope = scf_scope_create(g_hndl)) == NULL ||
10933 	    (svc = scf_service_create(g_hndl)) == NULL ||
10934 	    (iter = scf_iter_create(g_hndl)) == NULL ||
10935 	    (exp_inst = scf_instance_create(g_hndl)) == NULL ||
10936 	    (exp_pg = scf_pg_create(g_hndl)) == NULL ||
10937 	    (exp_prop = scf_property_create(g_hndl)) == NULL ||
10938 	    (exp_val = scf_value_create(g_hndl)) == NULL ||
10939 	    (exp_inst_iter = scf_iter_create(g_hndl)) == NULL ||
10940 	    (exp_pg_iter = scf_iter_create(g_hndl)) == NULL ||
10941 	    (exp_prop_iter = scf_iter_create(g_hndl)) == NULL ||
10942 	    (exp_val_iter = scf_iter_create(g_hndl)) == NULL)
10943 		scfdie();
10944 
10945 	exp_str_sz = max_scf_len + 1;
10946 	exp_str = safe_malloc(exp_str_sz);
10947 
10948 	sb = xmlNewNode(NULL, (xmlChar *)"service_bundle");
10949 	if (sb == NULL)
10950 		uu_die(emsg_create_xml);
10951 	safe_setprop(sb, type_attr, "archive");
10952 	safe_setprop(sb, name_attr, "none");
10953 
10954 	if (scf_handle_get_scope(g_hndl, SCF_SCOPE_LOCAL, scope) != 0)
10955 		scfdie();
10956 	if (scf_iter_scope_services(iter, scope) != 0)
10957 		scfdie();
10958 
10959 	for (;;) {
10960 		r = scf_iter_next_service(iter, svc);
10961 		if (r == 0)
10962 			break;
10963 		if (r != 1)
10964 			scfdie();
10965 
10966 		if (scf_service_get_name(svc, exp_str,
10967 		    max_scf_name_len + 1) < 0)
10968 			scfdie();
10969 
10970 		if (strcmp(exp_str, SCF_LEGACY_SERVICE) == 0)
10971 			continue;
10972 
10973 		(void) xmlAddChild(sb, export_service(svc, flags));
10974 	}
10975 
10976 	free(exp_str);
10977 
10978 	scf_iter_destroy(exp_val_iter);
10979 	scf_iter_destroy(exp_prop_iter);
10980 	scf_iter_destroy(exp_pg_iter);
10981 	scf_iter_destroy(exp_inst_iter);
10982 	scf_value_destroy(exp_val);
10983 	scf_property_destroy(exp_prop);
10984 	scf_pg_destroy(exp_pg);
10985 	scf_instance_destroy(exp_inst);
10986 	scf_iter_destroy(iter);
10987 	scf_service_destroy(svc);
10988 	scf_scope_destroy(scope);
10989 
10990 	return (sb);
10991 }
10992 
10993 int
10994 lscf_archive(const char *filename, int flags)
10995 {
10996 	FILE *f;
10997 	xmlDocPtr doc;
10998 	int result;
10999 
11000 	lscf_prep_hndl();
11001 
11002 	if (filename != NULL) {
11003 		errno = 0;
11004 		f = fopen(filename, "wb");
11005 		if (f == NULL) {
11006 			if (errno == 0)
11007 				uu_die(gettext("Could not open \"%s\": no free "
11008 				    "stdio streams.\n"), filename);
11009 			else
11010 				uu_die(gettext("Could not open \"%s\""),
11011 				    filename);
11012 		}
11013 	} else
11014 		f = stdout;
11015 
11016 	doc = xmlNewDoc((xmlChar *)"1.0");
11017 	if (doc == NULL)
11018 		uu_die(gettext("Could not create XML document.\n"));
11019 
11020 	if (xmlCreateIntSubset(doc, (xmlChar *)"service_bundle", NULL,
11021 	    (xmlChar *)MANIFEST_DTD_PATH) == NULL)
11022 		uu_die(emsg_create_xml);
11023 
11024 	(void) xmlAddSibling(doc->children, make_archive(flags));
11025 
11026 	result = write_service_bundle(doc, f);
11027 
11028 	xmlFreeDoc(doc);
11029 
11030 	if (f != stdout)
11031 		(void) fclose(f);
11032 
11033 	return (result);
11034 }
11035 
11036 
11037 /*
11038  * "Extract" a profile.
11039  */
11040 int
11041 lscf_profile_extract(const char *filename)
11042 {
11043 	FILE *f;
11044 	xmlDocPtr doc;
11045 	xmlNodePtr sb, snode, inode;
11046 	scf_scope_t *scope;
11047 	scf_service_t *svc;
11048 	scf_instance_t *inst;
11049 	scf_propertygroup_t *pg;
11050 	scf_property_t *prop;
11051 	scf_value_t *val;
11052 	scf_iter_t *siter, *iiter;
11053 	int r, s;
11054 	char *namebuf;
11055 	uint8_t b;
11056 	int result;
11057 
11058 	lscf_prep_hndl();
11059 
11060 	if (filename != NULL) {
11061 		errno = 0;
11062 		f = fopen(filename, "wb");
11063 		if (f == NULL) {
11064 			if (errno == 0)
11065 				uu_die(gettext("Could not open \"%s\": no "
11066 				    "free stdio streams.\n"), filename);
11067 			else
11068 				uu_die(gettext("Could not open \"%s\""),
11069 				    filename);
11070 		}
11071 	} else
11072 		f = stdout;
11073 
11074 	doc = xmlNewDoc((xmlChar *)"1.0");
11075 	if (doc == NULL)
11076 		uu_die(gettext("Could not create XML document.\n"));
11077 
11078 	if (xmlCreateIntSubset(doc, (xmlChar *)"service_bundle", NULL,
11079 	    (xmlChar *)MANIFEST_DTD_PATH) == NULL)
11080 		uu_die(emsg_create_xml);
11081 
11082 	sb = xmlNewNode(NULL, (xmlChar *)"service_bundle");
11083 	if (sb == NULL)
11084 		uu_die(emsg_create_xml);
11085 	safe_setprop(sb, type_attr, "profile");
11086 	safe_setprop(sb, name_attr, "extract");
11087 	(void) xmlAddSibling(doc->children, sb);
11088 
11089 	if ((scope = scf_scope_create(g_hndl)) == NULL ||
11090 	    (svc = scf_service_create(g_hndl)) == NULL ||
11091 	    (inst = scf_instance_create(g_hndl)) == NULL ||
11092 	    (pg = scf_pg_create(g_hndl)) == NULL ||
11093 	    (prop = scf_property_create(g_hndl)) == NULL ||
11094 	    (val = scf_value_create(g_hndl)) == NULL ||
11095 	    (siter = scf_iter_create(g_hndl)) == NULL ||
11096 	    (iiter = scf_iter_create(g_hndl)) == NULL)
11097 		scfdie();
11098 
11099 	if (scf_handle_get_local_scope(g_hndl, scope) != SCF_SUCCESS)
11100 		scfdie();
11101 
11102 	if (scf_iter_scope_services(siter, scope) != SCF_SUCCESS)
11103 		scfdie();
11104 
11105 	namebuf = safe_malloc(max_scf_name_len + 1);
11106 
11107 	while ((r = scf_iter_next_service(siter, svc)) == 1) {
11108 		if (scf_iter_service_instances(iiter, svc) != SCF_SUCCESS)
11109 			scfdie();
11110 
11111 		snode = xmlNewNode(NULL, (xmlChar *)"service");
11112 		if (snode == NULL)
11113 			uu_die(emsg_create_xml);
11114 
11115 		if (scf_service_get_name(svc, namebuf, max_scf_name_len + 1) <
11116 		    0)
11117 			scfdie();
11118 
11119 		safe_setprop(snode, name_attr, namebuf);
11120 
11121 		safe_setprop(snode, type_attr, "service");
11122 		safe_setprop(snode, "version", "0");
11123 
11124 		while ((s = scf_iter_next_instance(iiter, inst)) == 1) {
11125 			if (scf_instance_get_pg(inst, scf_pg_general, pg) !=
11126 			    SCF_SUCCESS) {
11127 				if (scf_error() != SCF_ERROR_NOT_FOUND)
11128 					scfdie();
11129 
11130 				if (g_verbose) {
11131 					ssize_t len;
11132 					char *fmri;
11133 
11134 					len =
11135 					    scf_instance_to_fmri(inst, NULL, 0);
11136 					if (len < 0)
11137 						scfdie();
11138 
11139 					fmri = safe_malloc(len + 1);
11140 
11141 					if (scf_instance_to_fmri(inst, fmri,
11142 					    len + 1) < 0)
11143 						scfdie();
11144 
11145 					warn("Instance %s has no \"%s\" "
11146 					    "property group.\n", fmri,
11147 					    scf_pg_general);
11148 
11149 					free(fmri);
11150 				}
11151 
11152 				continue;
11153 			}
11154 
11155 			if (pg_get_prop(pg, scf_property_enabled, prop) != 0 ||
11156 			    prop_check_type(prop, SCF_TYPE_BOOLEAN) != 0 ||
11157 			    prop_get_val(prop, val) != 0)
11158 				continue;
11159 
11160 			inode = xmlNewChild(snode, NULL, (xmlChar *)"instance",
11161 			    NULL);
11162 			if (inode == NULL)
11163 				uu_die(emsg_create_xml);
11164 
11165 			if (scf_instance_get_name(inst, namebuf,
11166 			    max_scf_name_len + 1) < 0)
11167 				scfdie();
11168 
11169 			safe_setprop(inode, name_attr, namebuf);
11170 
11171 			if (scf_value_get_boolean(val, &b) != SCF_SUCCESS)
11172 				scfdie();
11173 
11174 			safe_setprop(inode, enabled_attr, b ? true : false);
11175 		}
11176 		if (s < 0)
11177 			scfdie();
11178 
11179 		if (snode->children != NULL)
11180 			(void) xmlAddChild(sb, snode);
11181 		else
11182 			xmlFreeNode(snode);
11183 	}
11184 	if (r < 0)
11185 		scfdie();
11186 
11187 	free(namebuf);
11188 
11189 	result = write_service_bundle(doc, f);
11190 
11191 	xmlFreeDoc(doc);
11192 
11193 	if (f != stdout)
11194 		(void) fclose(f);
11195 
11196 	return (result);
11197 }
11198 
11199 
11200 /*
11201  * Entity manipulation commands
11202  */
11203 
11204 /*
11205  * Entity selection.  If no entity is selected, then the current scope is in
11206  * cur_scope, and cur_svc and cur_inst are NULL.  When a service is selected,
11207  * only cur_inst is NULL, and when an instance is selected, none are NULL.
11208  * When the snaplevel of a snapshot is selected, cur_level, cur_snap, and
11209  * cur_inst will be non-NULL.
11210  */
11211 
11212 /* Returns 1 if maybe absolute fmri, 0 on success (dies on failure) */
11213 static int
11214 select_inst(const char *name)
11215 {
11216 	scf_instance_t *inst;
11217 	scf_error_t err;
11218 
11219 	assert(cur_svc != NULL);
11220 
11221 	inst = scf_instance_create(g_hndl);
11222 	if (inst == NULL)
11223 		scfdie();
11224 
11225 	if (scf_service_get_instance(cur_svc, name, inst) == SCF_SUCCESS) {
11226 		cur_inst = inst;
11227 		return (0);
11228 	}
11229 
11230 	err = scf_error();
11231 	if (err != SCF_ERROR_NOT_FOUND && err != SCF_ERROR_INVALID_ARGUMENT)
11232 		scfdie();
11233 
11234 	scf_instance_destroy(inst);
11235 	return (1);
11236 }
11237 
11238 /* Returns as above. */
11239 static int
11240 select_svc(const char *name)
11241 {
11242 	scf_service_t *svc;
11243 	scf_error_t err;
11244 
11245 	assert(cur_scope != NULL);
11246 
11247 	svc = scf_service_create(g_hndl);
11248 	if (svc == NULL)
11249 		scfdie();
11250 
11251 	if (scf_scope_get_service(cur_scope, name, svc) == SCF_SUCCESS) {
11252 		cur_svc = svc;
11253 		return (0);
11254 	}
11255 
11256 	err = scf_error();
11257 	if (err != SCF_ERROR_NOT_FOUND && err != SCF_ERROR_INVALID_ARGUMENT)
11258 		scfdie();
11259 
11260 	scf_service_destroy(svc);
11261 	return (1);
11262 }
11263 
11264 /* ARGSUSED */
11265 static int
11266 select_callback(void *unused, scf_walkinfo_t *wip)
11267 {
11268 	scf_instance_t *inst;
11269 	scf_service_t *svc;
11270 	scf_scope_t *scope;
11271 
11272 	if (wip->inst != NULL) {
11273 		if ((scope = scf_scope_create(g_hndl)) == NULL ||
11274 		    (svc = scf_service_create(g_hndl)) == NULL ||
11275 		    (inst = scf_instance_create(g_hndl)) == NULL)
11276 			scfdie();
11277 
11278 		if (scf_handle_decode_fmri(g_hndl, wip->fmri, scope, svc,
11279 		    inst, NULL, NULL, SCF_DECODE_FMRI_EXACT) != SCF_SUCCESS)
11280 			scfdie();
11281 	} else {
11282 		assert(wip->svc != NULL);
11283 
11284 		if ((scope = scf_scope_create(g_hndl)) == NULL ||
11285 		    (svc = scf_service_create(g_hndl)) == NULL)
11286 			scfdie();
11287 
11288 		if (scf_handle_decode_fmri(g_hndl, wip->fmri, scope, svc,
11289 		    NULL, NULL, NULL, SCF_DECODE_FMRI_EXACT) != SCF_SUCCESS)
11290 			scfdie();
11291 
11292 		inst = NULL;
11293 	}
11294 
11295 	/* Clear out the current selection */
11296 	assert(cur_scope != NULL);
11297 	scf_scope_destroy(cur_scope);
11298 	scf_service_destroy(cur_svc);
11299 	scf_instance_destroy(cur_inst);
11300 
11301 	cur_scope = scope;
11302 	cur_svc = svc;
11303 	cur_inst = inst;
11304 
11305 	return (0);
11306 }
11307 
11308 static int
11309 validate_callback(void *fmri_p, scf_walkinfo_t *wip)
11310 {
11311 	char **fmri = fmri_p;
11312 
11313 	*fmri = strdup(wip->fmri);
11314 	if (*fmri == NULL)
11315 		uu_die(gettext("Out of memory.\n"));
11316 
11317 	return (0);
11318 }
11319 
11320 /*
11321  * validate [fmri]
11322  * Perform the validation of an FMRI instance.
11323  */
11324 void
11325 lscf_validate_fmri(const char *fmri)
11326 {
11327 	int ret = 0;
11328 	size_t inst_sz;
11329 	char *inst_fmri = NULL;
11330 	scf_tmpl_errors_t *errs = NULL;
11331 	char *snapbuf = NULL;
11332 
11333 	lscf_prep_hndl();
11334 
11335 	if (fmri == NULL) {
11336 		inst_sz = max_scf_fmri_len + 1;
11337 		inst_fmri = safe_malloc(inst_sz);
11338 
11339 		if (cur_snap != NULL) {
11340 			snapbuf = safe_malloc(max_scf_name_len + 1);
11341 			if (scf_snapshot_get_name(cur_snap, snapbuf,
11342 			    max_scf_name_len + 1) < 0)
11343 				scfdie();
11344 		}
11345 		if (cur_inst == NULL) {
11346 			semerr(gettext("No instance selected\n"));
11347 			goto cleanup;
11348 		} else if (scf_instance_to_fmri(cur_inst, inst_fmri,
11349 		    inst_sz) >= inst_sz) {
11350 			/* sanity check. Should never get here */
11351 			uu_die(gettext("Unexpected error! file %s, line %d\n"),
11352 			    __FILE__, __LINE__);
11353 		}
11354 	} else {
11355 		scf_error_t scf_err;
11356 		int err = 0;
11357 
11358 		if ((scf_err = scf_walk_fmri(g_hndl, 1, (char **)&fmri, 0,
11359 		    validate_callback, &inst_fmri, &err, semerr)) != 0) {
11360 			uu_warn("Failed to walk instances: %s\n",
11361 			    scf_strerror(scf_err));
11362 			goto cleanup;
11363 		}
11364 		if (err != 0) {
11365 			/* error message displayed by scf_walk_fmri */
11366 			goto cleanup;
11367 		}
11368 	}
11369 
11370 	ret = scf_tmpl_validate_fmri(g_hndl, inst_fmri, snapbuf, &errs,
11371 	    SCF_TMPL_VALIDATE_FLAG_CURRENT);
11372 	if (ret == -1) {
11373 		if (scf_error() == SCF_ERROR_TEMPLATE_INVALID) {
11374 			warn(gettext("Template data for %s is invalid. "
11375 			    "Consider reverting to a previous snapshot or "
11376 			    "restoring original configuration.\n"), inst_fmri);
11377 		} else {
11378 			uu_warn("%s: %s\n",
11379 			    gettext("Error validating the instance"),
11380 			    scf_strerror(scf_error()));
11381 		}
11382 	} else if (ret == 1 && errs != NULL) {
11383 		scf_tmpl_error_t *err = NULL;
11384 		char *msg;
11385 		size_t len = 256;	/* initial error buffer size */
11386 		int flag = (est->sc_cmd_flags & SC_CMD_IACTIVE) ?
11387 		    SCF_TMPL_STRERROR_HUMAN : 0;
11388 
11389 		msg = safe_malloc(len);
11390 
11391 		while ((err = scf_tmpl_next_error(errs)) != NULL) {
11392 			int ret;
11393 
11394 			if ((ret = scf_tmpl_strerror(err, msg, len,
11395 			    flag)) >= len) {
11396 				len = ret + 1;
11397 				msg = realloc(msg, len);
11398 				if (msg == NULL)
11399 					uu_die(gettext(
11400 					    "Out of memory.\n"));
11401 				(void) scf_tmpl_strerror(err, msg, len,
11402 				    flag);
11403 			}
11404 			(void) fprintf(stderr, "%s\n", msg);
11405 		}
11406 		if (msg != NULL)
11407 			free(msg);
11408 	}
11409 	if (errs != NULL)
11410 		scf_tmpl_errors_destroy(errs);
11411 
11412 cleanup:
11413 	free(inst_fmri);
11414 	free(snapbuf);
11415 }
11416 
11417 static void
11418 lscf_validate_file(const char *filename)
11419 {
11420 	tmpl_errors_t *errs;
11421 
11422 	bundle_t *b = internal_bundle_new();
11423 	if (lxml_get_bundle_file(b, filename, SVCCFG_OP_IMPORT) == 0) {
11424 		if (tmpl_validate_bundle(b, &errs) != TVS_SUCCESS) {
11425 			tmpl_errors_print(stderr, errs, "");
11426 			semerr(gettext("Validation failed.\n"));
11427 		}
11428 		tmpl_errors_destroy(errs);
11429 	}
11430 	(void) internal_bundle_free(b);
11431 }
11432 
11433 /*
11434  * validate [fmri|file]
11435  */
11436 void
11437 lscf_validate(const char *arg)
11438 {
11439 	const char *str;
11440 
11441 	if (strncmp(arg, SCF_FMRI_FILE_PREFIX,
11442 	    sizeof (SCF_FMRI_FILE_PREFIX) - 1) == 0) {
11443 		str = arg + sizeof (SCF_FMRI_FILE_PREFIX) - 1;
11444 		lscf_validate_file(str);
11445 	} else if (strncmp(arg, SCF_FMRI_SVC_PREFIX,
11446 	    sizeof (SCF_FMRI_SVC_PREFIX) - 1) == 0) {
11447 		str = arg + sizeof (SCF_FMRI_SVC_PREFIX) - 1;
11448 		lscf_validate_fmri(str);
11449 	} else if (access(arg, R_OK | F_OK) == 0) {
11450 		lscf_validate_file(arg);
11451 	} else {
11452 		lscf_validate_fmri(arg);
11453 	}
11454 }
11455 
11456 void
11457 lscf_select(const char *fmri)
11458 {
11459 	int ret, err;
11460 
11461 	lscf_prep_hndl();
11462 
11463 	if (cur_snap != NULL) {
11464 		struct snaplevel *elt;
11465 		char *buf;
11466 
11467 		/* Error unless name is that of the next level. */
11468 		elt = uu_list_next(cur_levels, cur_elt);
11469 		if (elt == NULL) {
11470 			semerr(gettext("No children.\n"));
11471 			return;
11472 		}
11473 
11474 		buf = safe_malloc(max_scf_name_len + 1);
11475 
11476 		if (scf_snaplevel_get_instance_name(elt->sl, buf,
11477 		    max_scf_name_len + 1) < 0)
11478 			scfdie();
11479 
11480 		if (strcmp(buf, fmri) != 0) {
11481 			semerr(gettext("No such child.\n"));
11482 			free(buf);
11483 			return;
11484 		}
11485 
11486 		free(buf);
11487 
11488 		cur_elt = elt;
11489 		cur_level = elt->sl;
11490 		return;
11491 	}
11492 
11493 	/*
11494 	 * Special case for 'svc:', which takes the user to the scope level.
11495 	 */
11496 	if (strcmp(fmri, "svc:") == 0) {
11497 		scf_instance_destroy(cur_inst);
11498 		scf_service_destroy(cur_svc);
11499 		cur_inst = NULL;
11500 		cur_svc = NULL;
11501 		return;
11502 	}
11503 
11504 	/*
11505 	 * Special case for ':properties'.  This appears as part of 'list' but
11506 	 * can't be selected.  Give a more helpful error message in this case.
11507 	 */
11508 	if (strcmp(fmri, ":properties") == 0) {
11509 		semerr(gettext(":properties is not an entity.  Try 'listprop' "
11510 		    "to list properties.\n"));
11511 		return;
11512 	}
11513 
11514 	/*
11515 	 * First try the argument as relative to the current selection.
11516 	 */
11517 	if (cur_inst != NULL) {
11518 		/* EMPTY */;
11519 	} else if (cur_svc != NULL) {
11520 		if (select_inst(fmri) != 1)
11521 			return;
11522 	} else {
11523 		if (select_svc(fmri) != 1)
11524 			return;
11525 	}
11526 
11527 	err = 0;
11528 	if ((ret = scf_walk_fmri(g_hndl, 1, (char **)&fmri, SCF_WALK_SERVICE,
11529 	    select_callback, NULL, &err, semerr)) != 0) {
11530 		semerr(gettext("Failed to walk instances: %s\n"),
11531 		    scf_strerror(ret));
11532 	}
11533 }
11534 
11535 void
11536 lscf_unselect(void)
11537 {
11538 	lscf_prep_hndl();
11539 
11540 	if (cur_snap != NULL) {
11541 		struct snaplevel *elt;
11542 
11543 		elt = uu_list_prev(cur_levels, cur_elt);
11544 		if (elt == NULL) {
11545 			semerr(gettext("No parent levels.\n"));
11546 		} else {
11547 			cur_elt = elt;
11548 			cur_level = elt->sl;
11549 		}
11550 	} else if (cur_inst != NULL) {
11551 		scf_instance_destroy(cur_inst);
11552 		cur_inst = NULL;
11553 	} else if (cur_svc != NULL) {
11554 		scf_service_destroy(cur_svc);
11555 		cur_svc = NULL;
11556 	} else {
11557 		semerr(gettext("Cannot unselect at scope level.\n"));
11558 	}
11559 }
11560 
11561 /*
11562  * Return the FMRI of the current selection, for the prompt.
11563  */
11564 void
11565 lscf_get_selection_str(char *buf, size_t bufsz)
11566 {
11567 	char *cp;
11568 	ssize_t fmrilen, szret;
11569 	boolean_t deleted = B_FALSE;
11570 
11571 	if (g_hndl == NULL) {
11572 		(void) strlcpy(buf, "svc:", bufsz);
11573 		return;
11574 	}
11575 
11576 	if (cur_level != NULL) {
11577 		assert(cur_snap != NULL);
11578 
11579 		/* [ snapshot ] FMRI [: instance ] */
11580 		assert(bufsz >= 1 + max_scf_name_len + 1 + max_scf_fmri_len
11581 		    + 2 + max_scf_name_len + 1 + 1);
11582 
11583 		buf[0] = '[';
11584 
11585 		szret = scf_snapshot_get_name(cur_snap, buf + 1,
11586 		    max_scf_name_len + 1);
11587 		if (szret < 0) {
11588 			if (scf_error() != SCF_ERROR_DELETED)
11589 				scfdie();
11590 
11591 			goto snap_deleted;
11592 		}
11593 
11594 		(void) strcat(buf, "]svc:/");
11595 
11596 		cp = strchr(buf, '\0');
11597 
11598 		szret = scf_snaplevel_get_service_name(cur_level, cp,
11599 		    max_scf_name_len + 1);
11600 		if (szret < 0) {
11601 			if (scf_error() != SCF_ERROR_DELETED)
11602 				scfdie();
11603 
11604 			goto snap_deleted;
11605 		}
11606 
11607 		cp = strchr(cp, '\0');
11608 
11609 		if (snaplevel_is_instance(cur_level)) {
11610 			*cp++ = ':';
11611 
11612 			if (scf_snaplevel_get_instance_name(cur_level, cp,
11613 			    max_scf_name_len + 1) < 0) {
11614 				if (scf_error() != SCF_ERROR_DELETED)
11615 					scfdie();
11616 
11617 				goto snap_deleted;
11618 			}
11619 		} else {
11620 			*cp++ = '[';
11621 			*cp++ = ':';
11622 
11623 			if (scf_instance_get_name(cur_inst, cp,
11624 			    max_scf_name_len + 1) < 0) {
11625 				if (scf_error() != SCF_ERROR_DELETED)
11626 					scfdie();
11627 
11628 				goto snap_deleted;
11629 			}
11630 
11631 			(void) strcat(buf, "]");
11632 		}
11633 
11634 		return;
11635 
11636 snap_deleted:
11637 		deleted = B_TRUE;
11638 		free(buf);
11639 		unselect_cursnap();
11640 	}
11641 
11642 	assert(cur_snap == NULL);
11643 
11644 	if (cur_inst != NULL) {
11645 		assert(cur_svc != NULL);
11646 		assert(cur_scope != NULL);
11647 
11648 		fmrilen = scf_instance_to_fmri(cur_inst, buf, bufsz);
11649 		if (fmrilen >= 0) {
11650 			assert(fmrilen < bufsz);
11651 			if (deleted)
11652 				warn(emsg_deleted);
11653 			return;
11654 		}
11655 
11656 		if (scf_error() != SCF_ERROR_DELETED)
11657 			scfdie();
11658 
11659 		deleted = B_TRUE;
11660 
11661 		scf_instance_destroy(cur_inst);
11662 		cur_inst = NULL;
11663 	}
11664 
11665 	if (cur_svc != NULL) {
11666 		assert(cur_scope != NULL);
11667 
11668 		szret = scf_service_to_fmri(cur_svc, buf, bufsz);
11669 		if (szret >= 0) {
11670 			assert(szret < bufsz);
11671 			if (deleted)
11672 				warn(emsg_deleted);
11673 			return;
11674 		}
11675 
11676 		if (scf_error() != SCF_ERROR_DELETED)
11677 			scfdie();
11678 
11679 		deleted = B_TRUE;
11680 		scf_service_destroy(cur_svc);
11681 		cur_svc = NULL;
11682 	}
11683 
11684 	assert(cur_scope != NULL);
11685 	fmrilen = scf_scope_to_fmri(cur_scope, buf, bufsz);
11686 
11687 	if (fmrilen < 0)
11688 		scfdie();
11689 
11690 	assert(fmrilen < bufsz);
11691 	if (deleted)
11692 		warn(emsg_deleted);
11693 }
11694 
11695 /*
11696  * Entity listing.  Entities and colon namespaces (e.g., :properties and
11697  * :statistics) are listed for the current selection.
11698  */
11699 void
11700 lscf_list(const char *pattern)
11701 {
11702 	scf_iter_t *iter;
11703 	char *buf;
11704 	int ret;
11705 
11706 	lscf_prep_hndl();
11707 
11708 	if (cur_level != NULL) {
11709 		struct snaplevel *elt;
11710 
11711 		(void) fputs(COLON_NAMESPACES, stdout);
11712 
11713 		elt = uu_list_next(cur_levels, cur_elt);
11714 		if (elt == NULL)
11715 			return;
11716 
11717 		/*
11718 		 * For now, we know that the next level is an instance.  But
11719 		 * if we ever have multiple scopes, this could be complicated.
11720 		 */
11721 		buf = safe_malloc(max_scf_name_len + 1);
11722 		if (scf_snaplevel_get_instance_name(elt->sl, buf,
11723 		    max_scf_name_len + 1) >= 0) {
11724 			(void) puts(buf);
11725 		} else {
11726 			if (scf_error() != SCF_ERROR_DELETED)
11727 				scfdie();
11728 		}
11729 
11730 		free(buf);
11731 
11732 		return;
11733 	}
11734 
11735 	if (cur_inst != NULL) {
11736 		(void) fputs(COLON_NAMESPACES, stdout);
11737 		return;
11738 	}
11739 
11740 	iter = scf_iter_create(g_hndl);
11741 	if (iter == NULL)
11742 		scfdie();
11743 
11744 	buf = safe_malloc(max_scf_name_len + 1);
11745 
11746 	if (cur_svc != NULL) {
11747 		/* List the instances in this service. */
11748 		scf_instance_t *inst;
11749 
11750 		inst = scf_instance_create(g_hndl);
11751 		if (inst == NULL)
11752 			scfdie();
11753 
11754 		if (scf_iter_service_instances(iter, cur_svc) == 0) {
11755 			safe_printf(COLON_NAMESPACES);
11756 
11757 			for (;;) {
11758 				ret = scf_iter_next_instance(iter, inst);
11759 				if (ret == 0)
11760 					break;
11761 				if (ret != 1) {
11762 					if (scf_error() != SCF_ERROR_DELETED)
11763 						scfdie();
11764 
11765 					break;
11766 				}
11767 
11768 				if (scf_instance_get_name(inst, buf,
11769 				    max_scf_name_len + 1) >= 0) {
11770 					if (pattern == NULL ||
11771 					    fnmatch(pattern, buf, 0) == 0)
11772 						(void) puts(buf);
11773 				} else {
11774 					if (scf_error() != SCF_ERROR_DELETED)
11775 						scfdie();
11776 				}
11777 			}
11778 		} else {
11779 			if (scf_error() != SCF_ERROR_DELETED)
11780 				scfdie();
11781 		}
11782 
11783 		scf_instance_destroy(inst);
11784 	} else {
11785 		/* List the services in this scope. */
11786 		scf_service_t *svc;
11787 
11788 		assert(cur_scope != NULL);
11789 
11790 		svc = scf_service_create(g_hndl);
11791 		if (svc == NULL)
11792 			scfdie();
11793 
11794 		if (scf_iter_scope_services(iter, cur_scope) != SCF_SUCCESS)
11795 			scfdie();
11796 
11797 		for (;;) {
11798 			ret = scf_iter_next_service(iter, svc);
11799 			if (ret == 0)
11800 				break;
11801 			if (ret != 1)
11802 				scfdie();
11803 
11804 			if (scf_service_get_name(svc, buf,
11805 			    max_scf_name_len + 1) >= 0) {
11806 				if (pattern == NULL ||
11807 				    fnmatch(pattern, buf, 0) == 0)
11808 					safe_printf("%s\n", buf);
11809 			} else {
11810 				if (scf_error() != SCF_ERROR_DELETED)
11811 					scfdie();
11812 			}
11813 		}
11814 
11815 		scf_service_destroy(svc);
11816 	}
11817 
11818 	free(buf);
11819 	scf_iter_destroy(iter);
11820 }
11821 
11822 /*
11823  * Entity addition.  Creates an empty entity in the current selection.
11824  */
11825 void
11826 lscf_add(const char *name)
11827 {
11828 	lscf_prep_hndl();
11829 
11830 	if (cur_snap != NULL) {
11831 		semerr(emsg_cant_modify_snapshots);
11832 	} else if (cur_inst != NULL) {
11833 		semerr(gettext("Cannot add entities to an instance.\n"));
11834 	} else if (cur_svc != NULL) {
11835 
11836 		if (scf_service_add_instance(cur_svc, name, NULL) !=
11837 		    SCF_SUCCESS) {
11838 			switch (scf_error()) {
11839 			case SCF_ERROR_INVALID_ARGUMENT:
11840 				semerr(gettext("Invalid name.\n"));
11841 				break;
11842 
11843 			case SCF_ERROR_EXISTS:
11844 				semerr(gettext("Instance already exists.\n"));
11845 				break;
11846 
11847 			case SCF_ERROR_PERMISSION_DENIED:
11848 				semerr(emsg_permission_denied);
11849 				break;
11850 
11851 			default:
11852 				scfdie();
11853 			}
11854 		}
11855 	} else {
11856 		assert(cur_scope != NULL);
11857 
11858 		if (scf_scope_add_service(cur_scope, name, NULL) !=
11859 		    SCF_SUCCESS) {
11860 			switch (scf_error()) {
11861 			case SCF_ERROR_INVALID_ARGUMENT:
11862 				semerr(gettext("Invalid name.\n"));
11863 				break;
11864 
11865 			case SCF_ERROR_EXISTS:
11866 				semerr(gettext("Service already exists.\n"));
11867 				break;
11868 
11869 			case SCF_ERROR_PERMISSION_DENIED:
11870 				semerr(emsg_permission_denied);
11871 				break;
11872 
11873 			case SCF_ERROR_BACKEND_READONLY:
11874 				semerr(emsg_read_only);
11875 				break;
11876 
11877 			default:
11878 				scfdie();
11879 			}
11880 		}
11881 	}
11882 }
11883 
11884 /* return 1 if the entity has no persistent pgs, else return 0 */
11885 static int
11886 entity_has_no_pgs(void *ent, int isservice)
11887 {
11888 	scf_iter_t *iter = NULL;
11889 	scf_propertygroup_t *pg = NULL;
11890 	uint32_t flags;
11891 	int err;
11892 	int ret = 1;
11893 
11894 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
11895 	    (pg = scf_pg_create(g_hndl)) == NULL)
11896 		scfdie();
11897 
11898 	if (isservice) {
11899 		if (scf_iter_service_pgs(iter, (scf_service_t *)ent) < 0)
11900 			scfdie();
11901 	} else {
11902 		if (scf_iter_instance_pgs(iter, (scf_instance_t *)ent) < 0)
11903 			scfdie();
11904 	}
11905 
11906 	while ((err = scf_iter_next_pg(iter, pg)) == 1) {
11907 		if (scf_pg_get_flags(pg, &flags) != 0)
11908 			scfdie();
11909 
11910 		/* skip nonpersistent pgs */
11911 		if (flags & SCF_PG_FLAG_NONPERSISTENT)
11912 			continue;
11913 
11914 		ret = 0;
11915 		break;
11916 	}
11917 
11918 	if (err == -1)
11919 		scfdie();
11920 
11921 	scf_pg_destroy(pg);
11922 	scf_iter_destroy(iter);
11923 
11924 	return (ret);
11925 }
11926 
11927 /* return 1 if the service has no instances, else return 0 */
11928 static int
11929 svc_has_no_insts(scf_service_t *svc)
11930 {
11931 	scf_instance_t *inst;
11932 	scf_iter_t *iter;
11933 	int r;
11934 	int ret = 1;
11935 
11936 	if ((inst = scf_instance_create(g_hndl)) == NULL ||
11937 	    (iter = scf_iter_create(g_hndl)) == NULL)
11938 		scfdie();
11939 
11940 	if (scf_iter_service_instances(iter, svc) != 0)
11941 		scfdie();
11942 
11943 	r = scf_iter_next_instance(iter, inst);
11944 	if (r == 1) {
11945 		ret = 0;
11946 	} else if (r == 0) {
11947 		ret = 1;
11948 	} else if (r == -1) {
11949 		scfdie();
11950 	} else {
11951 		bad_error("scf_iter_next_instance", r);
11952 	}
11953 
11954 	scf_iter_destroy(iter);
11955 	scf_instance_destroy(inst);
11956 
11957 	return (ret);
11958 }
11959 
11960 /*
11961  * Entity deletion.
11962  */
11963 
11964 /*
11965  * Delete the property group <fmri>/:properties/<name>.  Returns
11966  * SCF_ERROR_NONE on success (or if the entity is not found),
11967  * SCF_ERROR_INVALID_ARGUMENT if the fmri is bad, SCF_ERROR_TYPE_MISMATCH if
11968  * the pg is the wrong type, or SCF_ERROR_PERMISSION_DENIED if permission was
11969  * denied.
11970  */
11971 static scf_error_t
11972 delete_dependency_pg(const char *fmri, const char *name)
11973 {
11974 	void *entity = NULL;
11975 	int isservice;
11976 	scf_propertygroup_t *pg = NULL;
11977 	scf_error_t result;
11978 	char *pgty;
11979 	scf_service_t *svc = NULL;
11980 	scf_instance_t *inst = NULL;
11981 	scf_iter_t *iter = NULL;
11982 	char *name_buf = NULL;
11983 
11984 	result = fmri_to_entity(g_hndl, fmri, &entity, &isservice);
11985 	switch (result) {
11986 	case SCF_ERROR_NONE:
11987 		break;
11988 
11989 	case SCF_ERROR_NO_MEMORY:
11990 		uu_die(gettext("Out of memory.\n"));
11991 		/* NOTREACHED */
11992 
11993 	case SCF_ERROR_INVALID_ARGUMENT:
11994 	case SCF_ERROR_CONSTRAINT_VIOLATED:
11995 		return (SCF_ERROR_INVALID_ARGUMENT);
11996 
11997 	case SCF_ERROR_NOT_FOUND:
11998 		result = SCF_ERROR_NONE;
11999 		goto out;
12000 
12001 	default:
12002 		bad_error("fmri_to_entity", result);
12003 	}
12004 
12005 	pg = scf_pg_create(g_hndl);
12006 	if (pg == NULL)
12007 		scfdie();
12008 
12009 	if (entity_get_pg(entity, isservice, name, pg) != 0) {
12010 		if (scf_error() != SCF_ERROR_NOT_FOUND)
12011 			scfdie();
12012 
12013 		result = SCF_ERROR_NONE;
12014 		goto out;
12015 	}
12016 
12017 	pgty = safe_malloc(max_scf_pg_type_len + 1);
12018 
12019 	if (scf_pg_get_type(pg, pgty, max_scf_pg_type_len + 1) < 0)
12020 		scfdie();
12021 
12022 	if (strcmp(pgty, SCF_GROUP_DEPENDENCY) != 0) {
12023 		result = SCF_ERROR_TYPE_MISMATCH;
12024 		free(pgty);
12025 		goto out;
12026 	}
12027 
12028 	free(pgty);
12029 
12030 	if (scf_pg_delete(pg) != 0) {
12031 		result = scf_error();
12032 		if (result != SCF_ERROR_PERMISSION_DENIED)
12033 			scfdie();
12034 		goto out;
12035 	}
12036 
12037 	/*
12038 	 * We have to handle the case where we've just deleted the last
12039 	 * property group of a "dummy" entity (instance or service).
12040 	 * A "dummy" entity is an entity only present to hold an
12041 	 * external dependency.
12042 	 * So, in the case we deleted the last property group then we
12043 	 * can also delete the entity. If the entity is an instance then
12044 	 * we must verify if this was the last instance for the service
12045 	 * and if it is, we can also delete the service if it doesn't
12046 	 * have any property group either.
12047 	 */
12048 
12049 	result = SCF_ERROR_NONE;
12050 
12051 	if (isservice) {
12052 		svc = (scf_service_t *)entity;
12053 
12054 		if ((inst = scf_instance_create(g_hndl)) == NULL ||
12055 		    (iter = scf_iter_create(g_hndl)) == NULL)
12056 			scfdie();
12057 
12058 		name_buf = safe_malloc(max_scf_name_len + 1);
12059 	} else {
12060 		inst = (scf_instance_t *)entity;
12061 	}
12062 
12063 	/*
12064 	 * If the entity is an instance and we've just deleted its last
12065 	 * property group then we should delete it.
12066 	 */
12067 	if (!isservice && entity_has_no_pgs(entity, isservice)) {
12068 		/* find the service before deleting the inst. - needed later */
12069 		if ((svc = scf_service_create(g_hndl)) == NULL)
12070 			scfdie();
12071 
12072 		if (scf_instance_get_parent(inst, svc) != 0)
12073 			scfdie();
12074 
12075 		/* delete the instance */
12076 		if (scf_instance_delete(inst) != 0) {
12077 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12078 				scfdie();
12079 
12080 			result = SCF_ERROR_PERMISSION_DENIED;
12081 			goto out;
12082 		}
12083 		/* no need to refresh the instance */
12084 		inst = NULL;
12085 	}
12086 
12087 	/*
12088 	 * If the service has no more instances and pgs or we just deleted the
12089 	 * last instance and the service doesn't have anymore propery groups
12090 	 * then the service should be deleted.
12091 	 */
12092 	if (svc != NULL &&
12093 	    svc_has_no_insts(svc) &&
12094 	    entity_has_no_pgs((void *)svc, 1)) {
12095 		if (scf_service_delete(svc) == 0) {
12096 			if (isservice) {
12097 				/* no need to refresh the service */
12098 				svc = NULL;
12099 			}
12100 
12101 			goto out;
12102 		}
12103 
12104 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12105 			scfdie();
12106 
12107 		result = SCF_ERROR_PERMISSION_DENIED;
12108 	}
12109 
12110 	/* if the entity has not been deleted, refresh it */
12111 	if ((isservice && svc != NULL) || (!isservice && inst != NULL)) {
12112 		(void) refresh_entity(isservice, entity, fmri, inst, iter,
12113 		    name_buf);
12114 	}
12115 
12116 out:
12117 	if (isservice && (inst != NULL && iter != NULL)) {
12118 		free(name_buf);
12119 		scf_iter_destroy(iter);
12120 		scf_instance_destroy(inst);
12121 	}
12122 
12123 	if (!isservice && svc != NULL) {
12124 		scf_service_destroy(svc);
12125 	}
12126 
12127 	scf_pg_destroy(pg);
12128 	if (entity != NULL)
12129 		entity_destroy(entity, isservice);
12130 
12131 	return (result);
12132 }
12133 
12134 static int
12135 delete_dependents(scf_propertygroup_t *pg)
12136 {
12137 	char *pgty, *name, *fmri;
12138 	scf_property_t *prop;
12139 	scf_value_t *val;
12140 	scf_iter_t *iter;
12141 	int r;
12142 	scf_error_t err;
12143 
12144 	/* Verify that the pg has the correct type. */
12145 	pgty = safe_malloc(max_scf_pg_type_len + 1);
12146 	if (scf_pg_get_type(pg, pgty, max_scf_pg_type_len + 1) < 0)
12147 		scfdie();
12148 
12149 	if (strcmp(pgty, scf_group_framework) != 0) {
12150 		if (g_verbose) {
12151 			fmri = safe_malloc(max_scf_fmri_len + 1);
12152 			if (scf_pg_to_fmri(pg, fmri, max_scf_fmri_len + 1) < 0)
12153 				scfdie();
12154 
12155 			warn(gettext("Property group %s is not of expected "
12156 			    "type %s.\n"), fmri, scf_group_framework);
12157 
12158 			free(fmri);
12159 		}
12160 
12161 		free(pgty);
12162 		return (-1);
12163 	}
12164 
12165 	free(pgty);
12166 
12167 	/* map delete_dependency_pg onto the properties. */
12168 	if ((prop = scf_property_create(g_hndl)) == NULL ||
12169 	    (val = scf_value_create(g_hndl)) == NULL ||
12170 	    (iter = scf_iter_create(g_hndl)) == NULL)
12171 		scfdie();
12172 
12173 	if (scf_iter_pg_properties(iter, pg) != SCF_SUCCESS)
12174 		scfdie();
12175 
12176 	name = safe_malloc(max_scf_name_len + 1);
12177 	fmri = safe_malloc(max_scf_fmri_len + 2);
12178 
12179 	while ((r = scf_iter_next_property(iter, prop)) == 1) {
12180 		scf_type_t ty;
12181 
12182 		if (scf_property_get_name(prop, name, max_scf_name_len + 1) < 0)
12183 			scfdie();
12184 
12185 		if (scf_property_type(prop, &ty) != SCF_SUCCESS)
12186 			scfdie();
12187 
12188 		if ((ty != SCF_TYPE_ASTRING &&
12189 		    prop_check_type(prop, SCF_TYPE_FMRI) != 0) ||
12190 		    prop_get_val(prop, val) != 0)
12191 			continue;
12192 
12193 		if (scf_value_get_astring(val, fmri, max_scf_fmri_len + 2) < 0)
12194 			scfdie();
12195 
12196 		err = delete_dependency_pg(fmri, name);
12197 		if (err == SCF_ERROR_INVALID_ARGUMENT && g_verbose) {
12198 			if (scf_property_to_fmri(prop, fmri,
12199 			    max_scf_fmri_len + 2) < 0)
12200 				scfdie();
12201 
12202 			warn(gettext("Value of %s is not a valid FMRI.\n"),
12203 			    fmri);
12204 		} else if (err == SCF_ERROR_TYPE_MISMATCH && g_verbose) {
12205 			warn(gettext("Property group \"%s\" of entity \"%s\" "
12206 			    "does not have dependency type.\n"), name, fmri);
12207 		} else if (err == SCF_ERROR_PERMISSION_DENIED && g_verbose) {
12208 			warn(gettext("Could not delete property group \"%s\" "
12209 			    "of entity \"%s\" (permission denied).\n"), name,
12210 			    fmri);
12211 		}
12212 	}
12213 	if (r == -1)
12214 		scfdie();
12215 
12216 	scf_value_destroy(val);
12217 	scf_property_destroy(prop);
12218 
12219 	return (0);
12220 }
12221 
12222 /*
12223  * Returns 1 if the instance may be running, and 0 otherwise.
12224  */
12225 static int
12226 inst_is_running(scf_instance_t *inst)
12227 {
12228 	scf_propertygroup_t *pg;
12229 	scf_property_t *prop;
12230 	scf_value_t *val;
12231 	char buf[MAX_SCF_STATE_STRING_SZ];
12232 	int ret = 0;
12233 	ssize_t szret;
12234 
12235 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
12236 	    (prop = scf_property_create(g_hndl)) == NULL ||
12237 	    (val = scf_value_create(g_hndl)) == NULL)
12238 		scfdie();
12239 
12240 	if (scf_instance_get_pg(inst, SCF_PG_RESTARTER, pg) != SCF_SUCCESS) {
12241 		if (scf_error() != SCF_ERROR_NOT_FOUND)
12242 			scfdie();
12243 		goto out;
12244 	}
12245 
12246 	if (pg_get_prop(pg, SCF_PROPERTY_STATE, prop) != 0 ||
12247 	    prop_check_type(prop, SCF_TYPE_ASTRING) != 0 ||
12248 	    prop_get_val(prop, val) != 0)
12249 		goto out;
12250 
12251 	szret = scf_value_get_astring(val, buf, sizeof (buf));
12252 	assert(szret >= 0);
12253 
12254 	ret = (strcmp(buf, SCF_STATE_STRING_ONLINE) == 0 ||
12255 	    strcmp(buf, SCF_STATE_STRING_DEGRADED) == 0) ? 1 : 0;
12256 
12257 out:
12258 	scf_value_destroy(val);
12259 	scf_property_destroy(prop);
12260 	scf_pg_destroy(pg);
12261 	return (ret);
12262 }
12263 
12264 static uint8_t
12265 pg_is_external_dependency(scf_propertygroup_t *pg)
12266 {
12267 	char *type;
12268 	scf_value_t *val;
12269 	scf_property_t *prop;
12270 	uint8_t b = B_FALSE;
12271 
12272 	type = safe_malloc(max_scf_pg_type_len + 1);
12273 
12274 	if (scf_pg_get_type(pg, type, max_scf_pg_type_len + 1) < 0)
12275 		scfdie();
12276 
12277 	if ((prop = scf_property_create(g_hndl)) == NULL ||
12278 	    (val = scf_value_create(g_hndl)) == NULL)
12279 		scfdie();
12280 
12281 	if (strcmp(type, SCF_GROUP_DEPENDENCY) == 0) {
12282 		if (pg_get_prop(pg, scf_property_external, prop) == 0) {
12283 			if (scf_property_get_value(prop, val) != 0)
12284 				scfdie();
12285 			if (scf_value_get_boolean(val, &b) != 0)
12286 				scfdie();
12287 		}
12288 	}
12289 
12290 	free(type);
12291 	(void) scf_value_destroy(val);
12292 	(void) scf_property_destroy(prop);
12293 
12294 	return (b);
12295 }
12296 
12297 #define	DELETE_FAILURE			-1
12298 #define	DELETE_SUCCESS_NOEXTDEPS	0
12299 #define	DELETE_SUCCESS_EXTDEPS		1
12300 
12301 /*
12302  * lscf_instance_delete() deletes an instance.  Before calling
12303  * scf_instance_delete(), though, we make sure the instance isn't
12304  * running and delete dependencies in other entities which the instance
12305  * declared as "dependents".  If there are dependencies which were
12306  * created for other entities, then instead of deleting the instance we
12307  * make it "empty" by deleting all other property groups and all
12308  * snapshots.
12309  *
12310  * lscf_instance_delete() verifies that there is no external dependency pgs
12311  * before suppressing the instance. If there is, then we must not remove them
12312  * now in case the instance is re-created otherwise the dependencies would be
12313  * lost. The external dependency pgs will be removed if the dependencies are
12314  * removed.
12315  *
12316  * Returns:
12317  *  DELETE_FAILURE		on failure
12318  *  DELETE_SUCCESS_NOEXTDEPS	on success - no external dependencies
12319  *  DELETE_SUCCESS_EXTDEPS	on success - external dependencies
12320  */
12321 static int
12322 lscf_instance_delete(scf_instance_t *inst, int force)
12323 {
12324 	scf_propertygroup_t *pg;
12325 	scf_snapshot_t *snap;
12326 	scf_iter_t *iter;
12327 	int err;
12328 	int external = 0;
12329 
12330 	/* If we're not forcing and the instance is running, refuse. */
12331 	if (!force && inst_is_running(inst)) {
12332 		char *fmri;
12333 
12334 		fmri = safe_malloc(max_scf_fmri_len + 1);
12335 
12336 		if (scf_instance_to_fmri(inst, fmri, max_scf_fmri_len + 1) < 0)
12337 			scfdie();
12338 
12339 		semerr(gettext("Instance %s may be running.  "
12340 		    "Use delete -f if it is not.\n"), fmri);
12341 
12342 		free(fmri);
12343 		return (DELETE_FAILURE);
12344 	}
12345 
12346 	pg = scf_pg_create(g_hndl);
12347 	if (pg == NULL)
12348 		scfdie();
12349 
12350 	if (scf_instance_get_pg(inst, SCF_PG_DEPENDENTS, pg) == 0)
12351 		(void) delete_dependents(pg);
12352 	else if (scf_error() != SCF_ERROR_NOT_FOUND)
12353 		scfdie();
12354 
12355 	scf_pg_destroy(pg);
12356 
12357 	/*
12358 	 * If the instance has some external dependencies then we must
12359 	 * keep them in case the instance is reimported otherwise the
12360 	 * dependencies would be lost on reimport.
12361 	 */
12362 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
12363 	    (pg = scf_pg_create(g_hndl)) == NULL)
12364 		scfdie();
12365 
12366 	if (scf_iter_instance_pgs(iter, inst) < 0)
12367 		scfdie();
12368 
12369 	while ((err = scf_iter_next_pg(iter, pg)) == 1) {
12370 		if (pg_is_external_dependency(pg)) {
12371 			external = 1;
12372 			continue;
12373 		}
12374 
12375 		if (scf_pg_delete(pg) != 0) {
12376 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12377 				scfdie();
12378 			else {
12379 				semerr(emsg_permission_denied);
12380 
12381 				(void) scf_iter_destroy(iter);
12382 				(void) scf_pg_destroy(pg);
12383 				return (DELETE_FAILURE);
12384 			}
12385 		}
12386 	}
12387 
12388 	if (err == -1)
12389 		scfdie();
12390 
12391 	(void) scf_iter_destroy(iter);
12392 	(void) scf_pg_destroy(pg);
12393 
12394 	if (external) {
12395 		/*
12396 		 * All the pgs have been deleted for the instance except
12397 		 * the ones holding the external dependencies.
12398 		 * For the job to be complete, we must also delete the
12399 		 * snapshots associated with the instance.
12400 		 */
12401 		if ((snap = scf_snapshot_create((scf_handle_t *)g_hndl)) ==
12402 		    NULL)
12403 			scfdie();
12404 		if ((iter = scf_iter_create((scf_handle_t *)g_hndl)) == NULL)
12405 			scfdie();
12406 
12407 		if (scf_iter_instance_snapshots(iter, inst) == -1)
12408 			scfdie();
12409 
12410 		while ((err = scf_iter_next_snapshot(iter, snap)) == 1) {
12411 			if (_scf_snapshot_delete(snap) != 0) {
12412 				if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12413 					scfdie();
12414 
12415 				semerr(emsg_permission_denied);
12416 
12417 				(void) scf_iter_destroy(iter);
12418 				(void) scf_snapshot_destroy(snap);
12419 				return (DELETE_FAILURE);
12420 			}
12421 		}
12422 
12423 		if (err == -1)
12424 			scfdie();
12425 
12426 		(void) scf_iter_destroy(iter);
12427 		(void) scf_snapshot_destroy(snap);
12428 		return (DELETE_SUCCESS_EXTDEPS);
12429 	}
12430 
12431 	if (scf_instance_delete(inst) != 0) {
12432 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12433 			scfdie();
12434 
12435 		semerr(emsg_permission_denied);
12436 
12437 		return (DELETE_FAILURE);
12438 	}
12439 
12440 	return (DELETE_SUCCESS_NOEXTDEPS);
12441 }
12442 
12443 /*
12444  * lscf_service_delete() deletes a service.  Before calling
12445  * scf_service_delete(), though, we call lscf_instance_delete() for
12446  * each of the instances and delete dependencies in other entities
12447  * which were created as "dependents" of this service.  If there are
12448  * dependencies which were created for other entities, then we delete
12449  * all other property groups in the service and leave it as "empty".
12450  *
12451  * lscf_service_delete() verifies that there is no external dependency
12452  * pgs at the instance & service level before suppressing the service.
12453  * If there is, then we must not remove them now in case the service
12454  * is re-imported otherwise the dependencies would be lost. The external
12455  * dependency pgs will be removed if the dependencies are removed.
12456  *
12457  * Returns:
12458  *   DELETE_FAILURE		on failure
12459  *   DELETE_SUCCESS_NOEXTDEPS	on success - no external dependencies
12460  *   DELETE_SUCCESS_EXTDEPS	on success - external dependencies
12461  */
12462 static int
12463 lscf_service_delete(scf_service_t *svc, int force)
12464 {
12465 	int r;
12466 	scf_instance_t *inst;
12467 	scf_propertygroup_t *pg;
12468 	scf_iter_t *iter;
12469 	int ret;
12470 	int external = 0;
12471 
12472 	if ((inst = scf_instance_create(g_hndl)) == NULL ||
12473 	    (pg = scf_pg_create(g_hndl)) == NULL ||
12474 	    (iter = scf_iter_create(g_hndl)) == NULL)
12475 		scfdie();
12476 
12477 	if (scf_iter_service_instances(iter, svc) != 0)
12478 		scfdie();
12479 
12480 	for (r = scf_iter_next_instance(iter, inst);
12481 	    r == 1;
12482 	    r = scf_iter_next_instance(iter, inst)) {
12483 
12484 		ret = lscf_instance_delete(inst, force);
12485 		if (ret == DELETE_FAILURE) {
12486 			scf_iter_destroy(iter);
12487 			scf_pg_destroy(pg);
12488 			scf_instance_destroy(inst);
12489 			return (DELETE_FAILURE);
12490 		}
12491 
12492 		/*
12493 		 * Record the fact that there is some external dependencies
12494 		 * at the instance level.
12495 		 */
12496 		if (ret == DELETE_SUCCESS_EXTDEPS)
12497 			external |= 1;
12498 	}
12499 
12500 	if (r != 0)
12501 		scfdie();
12502 
12503 	/* Delete dependency property groups in dependent services. */
12504 	if (scf_service_get_pg(svc, SCF_PG_DEPENDENTS, pg) == 0)
12505 		(void) delete_dependents(pg);
12506 	else if (scf_error() != SCF_ERROR_NOT_FOUND)
12507 		scfdie();
12508 
12509 	scf_iter_destroy(iter);
12510 	scf_pg_destroy(pg);
12511 	scf_instance_destroy(inst);
12512 
12513 	/*
12514 	 * If the service has some external dependencies then we don't
12515 	 * want to remove them in case the service is re-imported.
12516 	 */
12517 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
12518 	    (iter = scf_iter_create(g_hndl)) == NULL)
12519 		scfdie();
12520 
12521 	if (scf_iter_service_pgs(iter, svc) < 0)
12522 		scfdie();
12523 
12524 	while ((r = scf_iter_next_pg(iter, pg)) == 1) {
12525 		if (pg_is_external_dependency(pg)) {
12526 			external |= 2;
12527 			continue;
12528 		}
12529 
12530 		if (scf_pg_delete(pg) != 0) {
12531 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12532 				scfdie();
12533 			else {
12534 				semerr(emsg_permission_denied);
12535 
12536 				(void) scf_iter_destroy(iter);
12537 				(void) scf_pg_destroy(pg);
12538 				return (DELETE_FAILURE);
12539 			}
12540 		}
12541 	}
12542 
12543 	if (r == -1)
12544 		scfdie();
12545 
12546 	(void) scf_iter_destroy(iter);
12547 	(void) scf_pg_destroy(pg);
12548 
12549 	if (external != 0)
12550 		return (DELETE_SUCCESS_EXTDEPS);
12551 
12552 	if (scf_service_delete(svc) == 0)
12553 		return (DELETE_SUCCESS_NOEXTDEPS);
12554 
12555 	if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12556 		scfdie();
12557 
12558 	semerr(emsg_permission_denied);
12559 	return (DELETE_FAILURE);
12560 }
12561 
12562 static int
12563 delete_callback(void *data, scf_walkinfo_t *wip)
12564 {
12565 	int force = (int)data;
12566 
12567 	if (wip->inst != NULL)
12568 		(void) lscf_instance_delete(wip->inst, force);
12569 	else
12570 		(void) lscf_service_delete(wip->svc, force);
12571 
12572 	return (0);
12573 }
12574 
12575 void
12576 lscf_delete(const char *fmri, int force)
12577 {
12578 	scf_service_t *svc;
12579 	scf_instance_t *inst;
12580 	int ret;
12581 
12582 	lscf_prep_hndl();
12583 
12584 	if (cur_snap != NULL) {
12585 		if (!snaplevel_is_instance(cur_level)) {
12586 			char *buf;
12587 
12588 			buf = safe_malloc(max_scf_name_len + 1);
12589 			if (scf_instance_get_name(cur_inst, buf,
12590 			    max_scf_name_len + 1) >= 0) {
12591 				if (strcmp(buf, fmri) == 0) {
12592 					semerr(emsg_cant_modify_snapshots);
12593 					free(buf);
12594 					return;
12595 				}
12596 			} else if (scf_error() != SCF_ERROR_DELETED) {
12597 				scfdie();
12598 			}
12599 			free(buf);
12600 		}
12601 	} else if (cur_inst != NULL) {
12602 		/* EMPTY */;
12603 	} else if (cur_svc != NULL) {
12604 		inst = scf_instance_create(g_hndl);
12605 		if (inst == NULL)
12606 			scfdie();
12607 
12608 		if (scf_service_get_instance(cur_svc, fmri, inst) ==
12609 		    SCF_SUCCESS) {
12610 			(void) lscf_instance_delete(inst, force);
12611 			scf_instance_destroy(inst);
12612 			return;
12613 		}
12614 
12615 		if (scf_error() != SCF_ERROR_NOT_FOUND &&
12616 		    scf_error() != SCF_ERROR_INVALID_ARGUMENT)
12617 			scfdie();
12618 
12619 		scf_instance_destroy(inst);
12620 	} else {
12621 		assert(cur_scope != NULL);
12622 
12623 		svc = scf_service_create(g_hndl);
12624 		if (svc == NULL)
12625 			scfdie();
12626 
12627 		if (scf_scope_get_service(cur_scope, fmri, svc) ==
12628 		    SCF_SUCCESS) {
12629 			(void) lscf_service_delete(svc, force);
12630 			scf_service_destroy(svc);
12631 			return;
12632 		}
12633 
12634 		if (scf_error() != SCF_ERROR_NOT_FOUND &&
12635 		    scf_error() != SCF_ERROR_INVALID_ARGUMENT)
12636 			scfdie();
12637 
12638 		scf_service_destroy(svc);
12639 	}
12640 
12641 	/*
12642 	 * Match FMRI to entity.
12643 	 */
12644 	if ((ret = scf_walk_fmri(g_hndl, 1, (char **)&fmri, SCF_WALK_SERVICE,
12645 	    delete_callback, (void *)force, NULL, semerr)) != 0) {
12646 		semerr(gettext("Failed to walk instances: %s\n"),
12647 		    scf_strerror(ret));
12648 	}
12649 }
12650 
12651 
12652 
12653 /*
12654  * :properties commands.  These all end with "pg" or "prop" and generally
12655  * operate on the currently selected entity.
12656  */
12657 
12658 /*
12659  * Property listing.  List the property groups, properties, their types and
12660  * their values for the currently selected entity.
12661  */
12662 static void
12663 list_pg_info(const scf_propertygroup_t *pg, const char *name, size_t namewidth)
12664 {
12665 	char *buf;
12666 	uint32_t flags;
12667 
12668 	buf = safe_malloc(max_scf_pg_type_len + 1);
12669 
12670 	if (scf_pg_get_type(pg, buf, max_scf_pg_type_len + 1) < 0)
12671 		scfdie();
12672 
12673 	if (scf_pg_get_flags(pg, &flags) != SCF_SUCCESS)
12674 		scfdie();
12675 
12676 	safe_printf("%-*s  %s", namewidth, name, buf);
12677 
12678 	if (flags & SCF_PG_FLAG_NONPERSISTENT)
12679 		safe_printf("\tNONPERSISTENT");
12680 
12681 	safe_printf("\n");
12682 
12683 	free(buf);
12684 }
12685 
12686 static boolean_t
12687 prop_has_multiple_values(const scf_property_t *prop, scf_value_t *val)
12688 {
12689 	if (scf_property_get_value(prop, val) == 0) {
12690 		return (B_FALSE);
12691 	} else {
12692 		switch (scf_error()) {
12693 		case SCF_ERROR_NOT_FOUND:
12694 			return (B_FALSE);
12695 		case SCF_ERROR_PERMISSION_DENIED:
12696 		case SCF_ERROR_CONSTRAINT_VIOLATED:
12697 			return (B_TRUE);
12698 		default:
12699 			scfdie();
12700 			/*NOTREACHED*/
12701 		}
12702 	}
12703 }
12704 
12705 static void
12706 list_prop_info(const scf_property_t *prop, const char *name, size_t len)
12707 {
12708 	scf_iter_t *iter;
12709 	scf_value_t *val;
12710 	const char *type;
12711 	int multiple_strings = 0;
12712 	int ret;
12713 
12714 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
12715 	    (val = scf_value_create(g_hndl)) == NULL)
12716 		scfdie();
12717 
12718 	type = prop_to_typestr(prop);
12719 	assert(type != NULL);
12720 
12721 	safe_printf("%-*s  %-7s ", len, name, type);
12722 
12723 	if (prop_has_multiple_values(prop, val) &&
12724 	    (scf_value_type(val) == SCF_TYPE_ASTRING ||
12725 	    scf_value_type(val) == SCF_TYPE_USTRING))
12726 		multiple_strings = 1;
12727 
12728 	if (scf_iter_property_values(iter, prop) != SCF_SUCCESS)
12729 		scfdie();
12730 
12731 	while ((ret = scf_iter_next_value(iter, val)) == 1) {
12732 		char *buf;
12733 		ssize_t vlen, szret;
12734 
12735 		vlen = scf_value_get_as_string(val, NULL, 0);
12736 		if (vlen < 0)
12737 			scfdie();
12738 
12739 		buf = safe_malloc(vlen + 1);
12740 
12741 		szret = scf_value_get_as_string(val, buf, vlen + 1);
12742 		if (szret < 0)
12743 			scfdie();
12744 		assert(szret <= vlen);
12745 
12746 		/* This is to be human-readable, so don't use CHARS_TO_QUOTE */
12747 		if (multiple_strings || strpbrk(buf, " \t\n\"()") != NULL) {
12748 			safe_printf(" \"");
12749 			(void) quote_and_print(buf, stdout, 0);
12750 			(void) putchar('"');
12751 			if (ferror(stdout)) {
12752 				(void) putchar('\n');
12753 				uu_die(gettext("Error writing to stdout.\n"));
12754 			}
12755 		} else {
12756 			safe_printf(" %s", buf);
12757 		}
12758 
12759 		free(buf);
12760 	}
12761 	if (ret != 0 && scf_error() != SCF_ERROR_PERMISSION_DENIED)
12762 		scfdie();
12763 
12764 	if (putchar('\n') != '\n')
12765 		uu_die(gettext("Could not output newline"));
12766 }
12767 
12768 /*
12769  * Outputs template property group info for the describe subcommand.
12770  * If 'templates' == 2, verbose output is printed in the format expected
12771  * for describe -v, which includes all templates fields.  If pg is
12772  * not NULL, we're describing the template data, not an existing property
12773  * group, and formatting should be appropriate for describe -t.
12774  */
12775 static void
12776 list_pg_tmpl(scf_pg_tmpl_t *pgt, scf_propertygroup_t *pg, int templates)
12777 {
12778 	char *buf;
12779 	uint8_t required;
12780 	scf_property_t *stability_prop;
12781 	scf_value_t *stability_val;
12782 
12783 	if (templates == 0)
12784 		return;
12785 
12786 	if ((stability_prop = scf_property_create(g_hndl)) == NULL ||
12787 	    (stability_val = scf_value_create(g_hndl)) == NULL)
12788 		scfdie();
12789 
12790 	if (templates == 2 && pg != NULL) {
12791 		if (scf_pg_get_property(pg, SCF_PROPERTY_STABILITY,
12792 		    stability_prop) == 0) {
12793 			if (prop_check_type(stability_prop,
12794 			    SCF_TYPE_ASTRING) == 0 &&
12795 			    prop_get_val(stability_prop, stability_val) == 0) {
12796 				char *stability;
12797 
12798 				stability = safe_malloc(max_scf_value_len + 1);
12799 
12800 				if (scf_value_get_astring(stability_val,
12801 				    stability, max_scf_value_len + 1) == -1 &&
12802 				    scf_error() != SCF_ERROR_NOT_FOUND)
12803 					scfdie();
12804 
12805 				safe_printf("%s%s: %s\n", TMPL_INDENT,
12806 				    gettext("stability"), stability);
12807 
12808 				free(stability);
12809 			}
12810 		} else if (scf_error() != SCF_ERROR_NOT_FOUND)
12811 			scfdie();
12812 	}
12813 
12814 	scf_property_destroy(stability_prop);
12815 	scf_value_destroy(stability_val);
12816 
12817 	if (pgt == NULL)
12818 		return;
12819 
12820 	if (pg == NULL || templates == 2) {
12821 		/* print type info only if scf_tmpl_pg_name succeeds */
12822 		if (scf_tmpl_pg_name(pgt, &buf) != -1) {
12823 			if (pg != NULL)
12824 				safe_printf("%s", TMPL_INDENT);
12825 			safe_printf("%s: ", gettext("name"));
12826 			safe_printf("%s\n", buf);
12827 			free(buf);
12828 		}
12829 
12830 		/* print type info only if scf_tmpl_pg_type succeeds */
12831 		if (scf_tmpl_pg_type(pgt, &buf) != -1) {
12832 			if (pg != NULL)
12833 				safe_printf("%s", TMPL_INDENT);
12834 			safe_printf("%s: ", gettext("type"));
12835 			safe_printf("%s\n", buf);
12836 			free(buf);
12837 		}
12838 	}
12839 
12840 	if (templates == 2 && scf_tmpl_pg_required(pgt, &required) == 0)
12841 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("required"),
12842 		    required ? "true" : "false");
12843 
12844 	if (templates == 2 && scf_tmpl_pg_target(pgt, &buf) > 0) {
12845 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("target"),
12846 		    buf);
12847 		free(buf);
12848 	}
12849 
12850 	if (templates == 2 && scf_tmpl_pg_common_name(pgt, NULL, &buf) > 0) {
12851 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("common name"),
12852 		    buf);
12853 		free(buf);
12854 	}
12855 
12856 	if (scf_tmpl_pg_description(pgt, NULL, &buf) > 0) {
12857 		if (templates == 2)
12858 			safe_printf("%s%s: %s\n", TMPL_INDENT,
12859 			    gettext("description"), buf);
12860 		else
12861 			safe_printf("%s%s\n", TMPL_INDENT, buf);
12862 		free(buf);
12863 	}
12864 
12865 }
12866 
12867 /*
12868  * With as_value set to true, indent as appropriate for the value level.
12869  * If false, indent to appropriate level for inclusion in constraint
12870  * or choice printout.
12871  */
12872 static void
12873 print_template_value_details(scf_prop_tmpl_t *prt, const char *val_buf,
12874     int as_value)
12875 {
12876 	char *buf;
12877 
12878 	if (scf_tmpl_value_common_name(prt, NULL, val_buf, &buf) > 0) {
12879 		if (as_value == 0)
12880 			safe_printf("%s", TMPL_CHOICE_INDENT);
12881 		else
12882 			safe_printf("%s", TMPL_INDENT);
12883 		safe_printf("%s: %s\n", gettext("value common name"), buf);
12884 		free(buf);
12885 	}
12886 
12887 	if (scf_tmpl_value_description(prt, NULL, val_buf, &buf) > 0) {
12888 		if (as_value == 0)
12889 			safe_printf("%s", TMPL_CHOICE_INDENT);
12890 		else
12891 			safe_printf("%s", TMPL_INDENT);
12892 		safe_printf("%s: %s\n", gettext("value description"), buf);
12893 		free(buf);
12894 	}
12895 }
12896 
12897 static void
12898 print_template_value(scf_prop_tmpl_t *prt, const char *val_buf)
12899 {
12900 	safe_printf("%s%s: ", TMPL_VALUE_INDENT, gettext("value"));
12901 	/* This is to be human-readable, so don't use CHARS_TO_QUOTE */
12902 	safe_printf("%s\n", val_buf);
12903 
12904 	print_template_value_details(prt, val_buf, 1);
12905 }
12906 
12907 static void
12908 print_template_constraints(scf_prop_tmpl_t *prt, int verbose)
12909 {
12910 	int i, printed = 0;
12911 	scf_values_t values;
12912 	scf_count_ranges_t c_ranges;
12913 	scf_int_ranges_t i_ranges;
12914 
12915 	printed = 0;
12916 	i = 0;
12917 	if (scf_tmpl_value_name_constraints(prt, &values) == 0) {
12918 		safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12919 		    gettext("value constraints"));
12920 		printed++;
12921 		for (i = 0; i < values.value_count; ++i) {
12922 			safe_printf("%s%s: %s\n", TMPL_INDENT,
12923 			    gettext("value name"), values.values_as_strings[i]);
12924 			if (verbose == 1)
12925 				print_template_value_details(prt,
12926 				    values.values_as_strings[i], 0);
12927 		}
12928 
12929 		scf_values_destroy(&values);
12930 	}
12931 
12932 	if (scf_tmpl_value_count_range_constraints(prt, &c_ranges) == 0) {
12933 		if (printed++ == 0)
12934 			safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12935 			    gettext("value constraints"));
12936 		for (i = 0; i < c_ranges.scr_num_ranges; ++i) {
12937 			safe_printf("%s%s: %llu to %llu\n", TMPL_INDENT,
12938 			    gettext("range"), c_ranges.scr_min[i],
12939 			    c_ranges.scr_max[i]);
12940 		}
12941 		scf_count_ranges_destroy(&c_ranges);
12942 	} else if (scf_error() == SCF_ERROR_CONSTRAINT_VIOLATED &&
12943 	    scf_tmpl_value_int_range_constraints(prt, &i_ranges) == 0) {
12944 		if (printed++ == 0)
12945 			safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12946 			    gettext("value constraints"));
12947 		for (i = 0; i < i_ranges.sir_num_ranges; ++i) {
12948 			safe_printf("%s%s: %lld to %lld\n", TMPL_INDENT,
12949 			    gettext("range"), i_ranges.sir_min[i],
12950 			    i_ranges.sir_max[i]);
12951 		}
12952 		scf_int_ranges_destroy(&i_ranges);
12953 	}
12954 }
12955 
12956 static void
12957 print_template_choices(scf_prop_tmpl_t *prt, int verbose)
12958 {
12959 	int i = 0, printed = 0;
12960 	scf_values_t values;
12961 	scf_count_ranges_t c_ranges;
12962 	scf_int_ranges_t i_ranges;
12963 
12964 	printed = 0;
12965 	if (scf_tmpl_value_name_choices(prt, &values) == 0) {
12966 		safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12967 		    gettext("value constraints"));
12968 		printed++;
12969 		for (i = 0; i < values.value_count; i++) {
12970 			safe_printf("%s%s: %s\n", TMPL_INDENT,
12971 			    gettext("value name"), values.values_as_strings[i]);
12972 			if (verbose == 1)
12973 				print_template_value_details(prt,
12974 				    values.values_as_strings[i], 0);
12975 		}
12976 
12977 		scf_values_destroy(&values);
12978 	}
12979 
12980 	if (scf_tmpl_value_count_range_choices(prt, &c_ranges) == 0) {
12981 		for (i = 0; i < c_ranges.scr_num_ranges; ++i) {
12982 			if (printed++ == 0)
12983 				safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12984 				    gettext("value choices"));
12985 			safe_printf("%s%s: %llu to %llu\n", TMPL_INDENT,
12986 			    gettext("range"), c_ranges.scr_min[i],
12987 			    c_ranges.scr_max[i]);
12988 		}
12989 		scf_count_ranges_destroy(&c_ranges);
12990 	} else if (scf_error() == SCF_ERROR_CONSTRAINT_VIOLATED &&
12991 	    scf_tmpl_value_int_range_choices(prt, &i_ranges) == 0) {
12992 		for (i = 0; i < i_ranges.sir_num_ranges; ++i) {
12993 			if (printed++ == 0)
12994 				safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12995 				    gettext("value choices"));
12996 			safe_printf("%s%s: %lld to %lld\n", TMPL_INDENT,
12997 			    gettext("range"), i_ranges.sir_min[i],
12998 			    i_ranges.sir_max[i]);
12999 		}
13000 		scf_int_ranges_destroy(&i_ranges);
13001 	}
13002 }
13003 
13004 static void
13005 list_values_by_template(scf_prop_tmpl_t *prt)
13006 {
13007 	print_template_constraints(prt, 1);
13008 	print_template_choices(prt, 1);
13009 }
13010 
13011 static void
13012 list_values_tmpl(scf_prop_tmpl_t *prt, scf_property_t *prop)
13013 {
13014 	char *val_buf;
13015 	scf_iter_t *iter;
13016 	scf_value_t *val;
13017 	int ret;
13018 
13019 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
13020 	    (val = scf_value_create(g_hndl)) == NULL)
13021 		scfdie();
13022 
13023 	if (scf_iter_property_values(iter, prop) != SCF_SUCCESS)
13024 		scfdie();
13025 
13026 	val_buf = safe_malloc(max_scf_value_len + 1);
13027 
13028 	while ((ret = scf_iter_next_value(iter, val)) == 1) {
13029 		if (scf_value_get_as_string(val, val_buf,
13030 		    max_scf_value_len + 1) < 0)
13031 			scfdie();
13032 
13033 		print_template_value(prt, val_buf);
13034 	}
13035 	if (ret != 0 && scf_error() != SCF_ERROR_PERMISSION_DENIED)
13036 		scfdie();
13037 	free(val_buf);
13038 
13039 	print_template_constraints(prt, 0);
13040 	print_template_choices(prt, 0);
13041 
13042 }
13043 
13044 /*
13045  * Outputs property info for the describe subcommand
13046  * Verbose output if templates == 2, -v option of svccfg describe
13047  * Displays template data if prop is not NULL, -t option of svccfg describe
13048  */
13049 static void
13050 list_prop_tmpl(scf_prop_tmpl_t *prt, scf_property_t *prop, int templates)
13051 {
13052 	char *buf;
13053 	uint8_t u_buf;
13054 	int i;
13055 	uint64_t min, max;
13056 	scf_values_t values;
13057 
13058 	if (prt == NULL || templates == 0)
13059 		return;
13060 
13061 	if (prop == NULL) {
13062 		safe_printf("%s%s: ", TMPL_VALUE_INDENT, gettext("name"));
13063 		if (scf_tmpl_prop_name(prt, &buf) > 0) {
13064 			safe_printf("%s\n", buf);
13065 			free(buf);
13066 		} else
13067 			safe_printf("(%s)\n", gettext("any"));
13068 	}
13069 
13070 	if (prop == NULL || templates == 2) {
13071 		if (prop != NULL)
13072 			safe_printf("%s", TMPL_INDENT);
13073 		else
13074 			safe_printf("%s", TMPL_VALUE_INDENT);
13075 		safe_printf("%s: ", gettext("type"));
13076 		if ((buf = _scf_read_tmpl_prop_type_as_string(prt)) != NULL) {
13077 			safe_printf("%s\n", buf);
13078 			free(buf);
13079 		} else
13080 			safe_printf("(%s)\n", gettext("any"));
13081 	}
13082 
13083 	if (templates == 2 && scf_tmpl_prop_required(prt, &u_buf) == 0)
13084 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("required"),
13085 		    u_buf ? "true" : "false");
13086 
13087 	if (templates == 2 && scf_tmpl_prop_common_name(prt, NULL, &buf) > 0) {
13088 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("common name"),
13089 		    buf);
13090 		free(buf);
13091 	}
13092 
13093 	if (templates == 2 && scf_tmpl_prop_units(prt, NULL, &buf) > 0) {
13094 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("units"),
13095 		    buf);
13096 		free(buf);
13097 	}
13098 
13099 	if (scf_tmpl_prop_description(prt, NULL, &buf) > 0) {
13100 		safe_printf("%s%s\n", TMPL_INDENT, buf);
13101 		free(buf);
13102 	}
13103 
13104 	if (templates == 2 && scf_tmpl_prop_visibility(prt, &u_buf) == 0)
13105 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("visibility"),
13106 		    scf_tmpl_visibility_to_string(u_buf));
13107 
13108 	if (templates == 2 && scf_tmpl_prop_cardinality(prt, &min, &max) == 0) {
13109 		safe_printf("%s%s: %" PRIu64 "\n", TMPL_INDENT,
13110 		    gettext("minimum number of values"), min);
13111 		if (max == ULLONG_MAX) {
13112 			safe_printf("%s%s: %s\n", TMPL_INDENT,
13113 			    gettext("maximum number of values"),
13114 			    gettext("unlimited"));
13115 		} else {
13116 			safe_printf("%s%s: %" PRIu64 "\n", TMPL_INDENT,
13117 			    gettext("maximum number of values"), max);
13118 		}
13119 	}
13120 
13121 	if (templates == 2 && scf_tmpl_prop_internal_seps(prt, &values) == 0) {
13122 		for (i = 0; i < values.value_count; i++) {
13123 			if (i == 0) {
13124 				safe_printf("%s%s:", TMPL_INDENT,
13125 				    gettext("internal separators"));
13126 			}
13127 			safe_printf(" \"%s\"", values.values_as_strings[i]);
13128 		}
13129 		safe_printf("\n");
13130 	}
13131 
13132 	if (templates != 2)
13133 		return;
13134 
13135 	if (prop != NULL)
13136 		list_values_tmpl(prt, prop);
13137 	else
13138 		list_values_by_template(prt);
13139 }
13140 
13141 static char *
13142 read_astring(scf_propertygroup_t *pg, const char *prop_name)
13143 {
13144 	char *rv;
13145 
13146 	rv = _scf_read_single_astring_from_pg(pg, prop_name);
13147 	if (rv == NULL) {
13148 		switch (scf_error()) {
13149 		case SCF_ERROR_NOT_FOUND:
13150 			break;
13151 		default:
13152 			scfdie();
13153 		}
13154 	}
13155 	return (rv);
13156 }
13157 
13158 static void
13159 display_documentation(scf_iter_t *iter, scf_propertygroup_t *pg)
13160 {
13161 	size_t doc_len;
13162 	size_t man_len;
13163 	char *pg_name;
13164 	char *text = NULL;
13165 	int rv;
13166 
13167 	doc_len = strlen(SCF_PG_TM_DOC_PREFIX);
13168 	man_len = strlen(SCF_PG_TM_MAN_PREFIX);
13169 	pg_name = safe_malloc(max_scf_name_len + 1);
13170 	while ((rv = scf_iter_next_pg(iter, pg)) == 1) {
13171 		if (scf_pg_get_name(pg, pg_name, max_scf_name_len + 1) == -1) {
13172 			scfdie();
13173 		}
13174 		if (strncmp(pg_name, SCF_PG_TM_DOC_PREFIX, doc_len) == 0) {
13175 			/* Display doc_link and and uri */
13176 			safe_printf("%s%s:\n", TMPL_INDENT,
13177 			    gettext("doc_link"));
13178 			text = read_astring(pg, SCF_PROPERTY_TM_NAME);
13179 			if (text != NULL) {
13180 				safe_printf("%s%s%s: %s\n", TMPL_INDENT,
13181 				    TMPL_INDENT, gettext("name"), text);
13182 				uu_free(text);
13183 			}
13184 			text = read_astring(pg, SCF_PROPERTY_TM_URI);
13185 			if (text != NULL) {
13186 				safe_printf("%s%s: %s\n", TMPL_INDENT_2X,
13187 				    gettext("uri"), text);
13188 				uu_free(text);
13189 			}
13190 		} else if (strncmp(pg_name, SCF_PG_TM_MAN_PREFIX,
13191 		    man_len) == 0) {
13192 			/* Display manpage title, section and path */
13193 			safe_printf("%s%s:\n", TMPL_INDENT,
13194 			    gettext("manpage"));
13195 			text = read_astring(pg, SCF_PROPERTY_TM_TITLE);
13196 			if (text != NULL) {
13197 				safe_printf("%s%s%s: %s\n", TMPL_INDENT,
13198 				    TMPL_INDENT, gettext("title"), text);
13199 				uu_free(text);
13200 			}
13201 			text = read_astring(pg, SCF_PROPERTY_TM_SECTION);
13202 			if (text != NULL) {
13203 				safe_printf("%s%s%s: %s\n", TMPL_INDENT,
13204 				    TMPL_INDENT, gettext("section"), text);
13205 				uu_free(text);
13206 			}
13207 			text = read_astring(pg, SCF_PROPERTY_TM_MANPATH);
13208 			if (text != NULL) {
13209 				safe_printf("%s%s%s: %s\n", TMPL_INDENT,
13210 				    TMPL_INDENT, gettext("manpath"), text);
13211 				uu_free(text);
13212 			}
13213 		}
13214 	}
13215 	if (rv == -1)
13216 		scfdie();
13217 
13218 done:
13219 	free(pg_name);
13220 }
13221 
13222 static void
13223 list_entity_tmpl(int templates)
13224 {
13225 	char *common_name = NULL;
13226 	char *description = NULL;
13227 	char *locale = NULL;
13228 	scf_iter_t *iter;
13229 	scf_propertygroup_t *pg;
13230 	scf_property_t *prop;
13231 	int r;
13232 	scf_value_t *val;
13233 
13234 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
13235 	    (prop = scf_property_create(g_hndl)) == NULL ||
13236 	    (val = scf_value_create(g_hndl)) == NULL ||
13237 	    (iter = scf_iter_create(g_hndl)) == NULL)
13238 		scfdie();
13239 
13240 	locale = setlocale(LC_MESSAGES, NULL);
13241 
13242 	if (get_pg(SCF_PG_TM_COMMON_NAME, pg) == 0) {
13243 		common_name = safe_malloc(max_scf_value_len + 1);
13244 
13245 		/* Try both the current locale and the "C" locale. */
13246 		if (scf_pg_get_property(pg, locale, prop) == 0 ||
13247 		    (scf_error() == SCF_ERROR_NOT_FOUND &&
13248 		    scf_pg_get_property(pg, "C", prop) == 0)) {
13249 			if (prop_get_val(prop, val) == 0 &&
13250 			    scf_value_get_ustring(val, common_name,
13251 			    max_scf_value_len + 1) != -1) {
13252 				safe_printf("%s%s: %s\n", TMPL_INDENT,
13253 				    gettext("common name"), common_name);
13254 			}
13255 		}
13256 	}
13257 
13258 	/*
13259 	 * Do description, manpages, and doc links if templates == 2.
13260 	 */
13261 	if (templates == 2) {
13262 		/* Get the description. */
13263 		if (get_pg(SCF_PG_TM_DESCRIPTION, pg) == 0) {
13264 			description = safe_malloc(max_scf_value_len + 1);
13265 
13266 			/* Try both the current locale and the "C" locale. */
13267 			if (scf_pg_get_property(pg, locale, prop) == 0 ||
13268 			    (scf_error() == SCF_ERROR_NOT_FOUND &&
13269 			    scf_pg_get_property(pg, "C", prop) == 0)) {
13270 				if (prop_get_val(prop, val) == 0 &&
13271 				    scf_value_get_ustring(val, description,
13272 				    max_scf_value_len + 1) != -1) {
13273 					safe_printf("%s%s: %s\n", TMPL_INDENT,
13274 					    gettext("description"),
13275 					    description);
13276 				}
13277 			}
13278 		}
13279 
13280 		/* Process doc_link & manpage elements. */
13281 		if (cur_level != NULL) {
13282 			r = scf_iter_snaplevel_pgs_typed(iter, cur_level,
13283 			    SCF_GROUP_TEMPLATE);
13284 		} else if (cur_inst != NULL) {
13285 			r = scf_iter_instance_pgs_typed(iter, cur_inst,
13286 			    SCF_GROUP_TEMPLATE);
13287 		} else {
13288 			r = scf_iter_service_pgs_typed(iter, cur_svc,
13289 			    SCF_GROUP_TEMPLATE);
13290 		}
13291 		if (r == 0) {
13292 			display_documentation(iter, pg);
13293 		}
13294 	}
13295 
13296 	free(common_name);
13297 	free(description);
13298 	scf_pg_destroy(pg);
13299 	scf_property_destroy(prop);
13300 	scf_value_destroy(val);
13301 	scf_iter_destroy(iter);
13302 }
13303 
13304 static void
13305 listtmpl(const char *pattern, int templates)
13306 {
13307 	scf_pg_tmpl_t *pgt;
13308 	scf_prop_tmpl_t *prt;
13309 	char *snapbuf = NULL;
13310 	char *fmribuf;
13311 	char *pg_name = NULL, *prop_name = NULL;
13312 	ssize_t prop_name_size;
13313 	char *qual_prop_name;
13314 	char *search_name;
13315 	int listed = 0;
13316 
13317 	if ((pgt = scf_tmpl_pg_create(g_hndl)) == NULL ||
13318 	    (prt = scf_tmpl_prop_create(g_hndl)) == NULL)
13319 		scfdie();
13320 
13321 	fmribuf = safe_malloc(max_scf_name_len + 1);
13322 	qual_prop_name = safe_malloc(max_scf_name_len + 1);
13323 
13324 	if (cur_snap != NULL) {
13325 		snapbuf = safe_malloc(max_scf_name_len + 1);
13326 		if (scf_snapshot_get_name(cur_snap, snapbuf,
13327 		    max_scf_name_len + 1) < 0)
13328 			scfdie();
13329 	}
13330 
13331 	if (cur_inst != NULL) {
13332 		if (scf_instance_to_fmri(cur_inst, fmribuf,
13333 		    max_scf_name_len + 1) < 0)
13334 			scfdie();
13335 	} else if (cur_svc != NULL) {
13336 		if (scf_service_to_fmri(cur_svc, fmribuf,
13337 		    max_scf_name_len + 1) < 0)
13338 			scfdie();
13339 	} else
13340 		abort();
13341 
13342 	/* If pattern is specified, we want to list only those items. */
13343 	while (scf_tmpl_iter_pgs(pgt, fmribuf, snapbuf, NULL, 0) == 1) {
13344 		listed = 0;
13345 		if (pattern == NULL || (scf_tmpl_pg_name(pgt, &pg_name) > 0 &&
13346 		    fnmatch(pattern, pg_name, 0) == 0)) {
13347 			list_pg_tmpl(pgt, NULL, templates);
13348 			listed++;
13349 		}
13350 
13351 		scf_tmpl_prop_reset(prt);
13352 
13353 		while (scf_tmpl_iter_props(pgt, prt, 0) == 0) {
13354 			search_name = NULL;
13355 			prop_name_size = scf_tmpl_prop_name(prt, &prop_name);
13356 			if ((prop_name_size > 0) && (pg_name != NULL)) {
13357 				if (snprintf(qual_prop_name,
13358 				    max_scf_name_len + 1, "%s/%s",
13359 				    pg_name, prop_name) >=
13360 				    max_scf_name_len + 1) {
13361 					prop_name_size = -1;
13362 				} else {
13363 					search_name = qual_prop_name;
13364 				}
13365 			}
13366 			if (listed > 0 || pattern == NULL ||
13367 			    (prop_name_size > 0 &&
13368 			    fnmatch(pattern, search_name,
13369 			    FNM_PATHNAME) == 0))
13370 				list_prop_tmpl(prt, NULL, templates);
13371 			if (prop_name != NULL) {
13372 				free(prop_name);
13373 				prop_name = NULL;
13374 			}
13375 		}
13376 		if (pg_name != NULL) {
13377 			free(pg_name);
13378 			pg_name = NULL;
13379 		}
13380 	}
13381 
13382 	scf_tmpl_prop_destroy(prt);
13383 	scf_tmpl_pg_destroy(pgt);
13384 	free(snapbuf);
13385 	free(fmribuf);
13386 	free(qual_prop_name);
13387 }
13388 
13389 static void
13390 listprop(const char *pattern, int only_pgs, int templates)
13391 {
13392 	scf_propertygroup_t *pg;
13393 	scf_property_t *prop;
13394 	scf_iter_t *iter, *piter;
13395 	char *pgnbuf, *prnbuf, *ppnbuf;
13396 	scf_pg_tmpl_t *pgt, *pgtp;
13397 	scf_prop_tmpl_t *prt;
13398 
13399 	void **objects;
13400 	char **names;
13401 	void **tmpls;
13402 	int allocd, i;
13403 
13404 	int ret;
13405 	ssize_t pgnlen, prnlen, szret;
13406 	size_t max_len = 0;
13407 
13408 	if (cur_svc == NULL && cur_inst == NULL) {
13409 		semerr(emsg_entity_not_selected);
13410 		return;
13411 	}
13412 
13413 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
13414 	    (prop = scf_property_create(g_hndl)) == NULL ||
13415 	    (iter = scf_iter_create(g_hndl)) == NULL ||
13416 	    (piter = scf_iter_create(g_hndl)) == NULL ||
13417 	    (prt = scf_tmpl_prop_create(g_hndl)) == NULL ||
13418 	    (pgt = scf_tmpl_pg_create(g_hndl)) == NULL)
13419 		scfdie();
13420 
13421 	prnbuf = safe_malloc(max_scf_name_len + 1);
13422 
13423 	if (cur_level != NULL)
13424 		ret = scf_iter_snaplevel_pgs(iter, cur_level);
13425 	else if (cur_inst != NULL)
13426 		ret = scf_iter_instance_pgs(iter, cur_inst);
13427 	else
13428 		ret = scf_iter_service_pgs(iter, cur_svc);
13429 	if (ret != 0) {
13430 		return;
13431 	}
13432 
13433 	/*
13434 	 * We want to only list items which match pattern, and we want the
13435 	 * second column to line up, so during the first pass we'll save
13436 	 * matching items, their names, and their templates in objects,
13437 	 * names, and tmpls, computing the maximum name length as we go,
13438 	 * and then we'll print them out.
13439 	 *
13440 	 * Note: We always keep an extra slot available so the array can be
13441 	 * NULL-terminated.
13442 	 */
13443 	i = 0;
13444 	allocd = 1;
13445 	objects = safe_malloc(sizeof (*objects));
13446 	names = safe_malloc(sizeof (*names));
13447 	tmpls = safe_malloc(sizeof (*tmpls));
13448 
13449 	while ((ret = scf_iter_next_pg(iter, pg)) == 1) {
13450 		int new_pg = 0;
13451 		int print_props = 0;
13452 		pgtp = NULL;
13453 
13454 		pgnlen = scf_pg_get_name(pg, NULL, 0);
13455 		if (pgnlen < 0)
13456 			scfdie();
13457 
13458 		pgnbuf = safe_malloc(pgnlen + 1);
13459 
13460 		szret = scf_pg_get_name(pg, pgnbuf, pgnlen + 1);
13461 		if (szret < 0)
13462 			scfdie();
13463 		assert(szret <= pgnlen);
13464 
13465 		if (scf_tmpl_get_by_pg(pg, pgt, 0) == -1) {
13466 			if (scf_error() != SCF_ERROR_NOT_FOUND)
13467 				scfdie();
13468 			pgtp = NULL;
13469 		} else {
13470 			pgtp = pgt;
13471 		}
13472 
13473 		if (pattern == NULL ||
13474 		    fnmatch(pattern, pgnbuf, 0) == 0) {
13475 			if (i+1 >= allocd) {
13476 				allocd *= 2;
13477 				objects = realloc(objects,
13478 				    sizeof (*objects) * allocd);
13479 				names =
13480 				    realloc(names, sizeof (*names) * allocd);
13481 				tmpls = realloc(tmpls,
13482 				    sizeof (*tmpls) * allocd);
13483 				if (objects == NULL || names == NULL ||
13484 				    tmpls == NULL)
13485 					uu_die(gettext("Out of memory"));
13486 			}
13487 			objects[i] = pg;
13488 			names[i] = pgnbuf;
13489 
13490 			if (pgtp == NULL)
13491 				tmpls[i] = NULL;
13492 			else
13493 				tmpls[i] = pgt;
13494 
13495 			++i;
13496 
13497 			if (pgnlen > max_len)
13498 				max_len = pgnlen;
13499 
13500 			new_pg = 1;
13501 			print_props = 1;
13502 		}
13503 
13504 		if (only_pgs) {
13505 			if (new_pg) {
13506 				pg = scf_pg_create(g_hndl);
13507 				if (pg == NULL)
13508 					scfdie();
13509 				pgt = scf_tmpl_pg_create(g_hndl);
13510 				if (pgt == NULL)
13511 					scfdie();
13512 			} else
13513 				free(pgnbuf);
13514 
13515 			continue;
13516 		}
13517 
13518 		if (scf_iter_pg_properties(piter, pg) != SCF_SUCCESS)
13519 			scfdie();
13520 
13521 		while ((ret = scf_iter_next_property(piter, prop)) == 1) {
13522 			prnlen = scf_property_get_name(prop, prnbuf,
13523 			    max_scf_name_len + 1);
13524 			if (prnlen < 0)
13525 				scfdie();
13526 
13527 			/* Will prepend the property group name and a slash. */
13528 			prnlen += pgnlen + 1;
13529 
13530 			ppnbuf = safe_malloc(prnlen + 1);
13531 
13532 			if (snprintf(ppnbuf, prnlen + 1, "%s/%s", pgnbuf,
13533 			    prnbuf) < 0)
13534 				uu_die("snprintf");
13535 
13536 			if (pattern == NULL || print_props == 1 ||
13537 			    fnmatch(pattern, ppnbuf, 0) == 0) {
13538 				if (i+1 >= allocd) {
13539 					allocd *= 2;
13540 					objects = realloc(objects,
13541 					    sizeof (*objects) * allocd);
13542 					names = realloc(names,
13543 					    sizeof (*names) * allocd);
13544 					tmpls = realloc(tmpls,
13545 					    sizeof (*tmpls) * allocd);
13546 					if (objects == NULL || names == NULL ||
13547 					    tmpls == NULL)
13548 						uu_die(gettext(
13549 						    "Out of memory"));
13550 				}
13551 
13552 				objects[i] = prop;
13553 				names[i] = ppnbuf;
13554 
13555 				if (pgtp != NULL) {
13556 					if (scf_tmpl_get_by_prop(pgt, prnbuf,
13557 					    prt, 0) < 0) {
13558 						if (scf_error() !=
13559 						    SCF_ERROR_NOT_FOUND)
13560 							scfdie();
13561 						tmpls[i] = NULL;
13562 					} else {
13563 						tmpls[i] = prt;
13564 					}
13565 				} else {
13566 					tmpls[i] = NULL;
13567 				}
13568 
13569 				++i;
13570 
13571 				if (prnlen > max_len)
13572 					max_len = prnlen;
13573 
13574 				prop = scf_property_create(g_hndl);
13575 				prt = scf_tmpl_prop_create(g_hndl);
13576 			} else {
13577 				free(ppnbuf);
13578 			}
13579 		}
13580 
13581 		if (new_pg) {
13582 			pg = scf_pg_create(g_hndl);
13583 			if (pg == NULL)
13584 				scfdie();
13585 			pgt = scf_tmpl_pg_create(g_hndl);
13586 			if (pgt == NULL)
13587 				scfdie();
13588 		} else
13589 			free(pgnbuf);
13590 	}
13591 	if (ret != 0)
13592 		scfdie();
13593 
13594 	objects[i] = NULL;
13595 
13596 	scf_pg_destroy(pg);
13597 	scf_tmpl_pg_destroy(pgt);
13598 	scf_property_destroy(prop);
13599 	scf_tmpl_prop_destroy(prt);
13600 
13601 	for (i = 0; objects[i] != NULL; ++i) {
13602 		if (strchr(names[i], '/') == NULL) {
13603 			/* property group */
13604 			pg = (scf_propertygroup_t *)objects[i];
13605 			pgt = (scf_pg_tmpl_t *)tmpls[i];
13606 			list_pg_info(pg, names[i], max_len);
13607 			list_pg_tmpl(pgt, pg, templates);
13608 			free(names[i]);
13609 			scf_pg_destroy(pg);
13610 			if (pgt != NULL)
13611 				scf_tmpl_pg_destroy(pgt);
13612 		} else {
13613 			/* property */
13614 			prop = (scf_property_t *)objects[i];
13615 			prt = (scf_prop_tmpl_t *)tmpls[i];
13616 			list_prop_info(prop, names[i], max_len);
13617 			list_prop_tmpl(prt, prop, templates);
13618 			free(names[i]);
13619 			scf_property_destroy(prop);
13620 			if (prt != NULL)
13621 				scf_tmpl_prop_destroy(prt);
13622 		}
13623 	}
13624 
13625 	free(names);
13626 	free(objects);
13627 	free(tmpls);
13628 }
13629 
13630 void
13631 lscf_listpg(const char *pattern)
13632 {
13633 	lscf_prep_hndl();
13634 
13635 	listprop(pattern, 1, 0);
13636 }
13637 
13638 /*
13639  * Property group and property creation, setting, and deletion.  setprop (and
13640  * its alias, addprop) can either create a property group of a given type, or
13641  * it can create or set a property to a given type and list of values.
13642  */
13643 void
13644 lscf_addpg(const char *name, const char *type, const char *flags)
13645 {
13646 	scf_propertygroup_t *pg;
13647 	int ret;
13648 	uint32_t flgs = 0;
13649 	const char *cp;
13650 
13651 
13652 	lscf_prep_hndl();
13653 
13654 	if (cur_snap != NULL) {
13655 		semerr(emsg_cant_modify_snapshots);
13656 		return;
13657 	}
13658 
13659 	if (cur_inst == NULL && cur_svc == NULL) {
13660 		semerr(emsg_entity_not_selected);
13661 		return;
13662 	}
13663 
13664 	if (flags != NULL) {
13665 		for (cp = flags; *cp != '\0'; ++cp) {
13666 			switch (*cp) {
13667 			case 'P':
13668 				flgs |= SCF_PG_FLAG_NONPERSISTENT;
13669 				break;
13670 
13671 			case 'p':
13672 				flgs &= ~SCF_PG_FLAG_NONPERSISTENT;
13673 				break;
13674 
13675 			default:
13676 				semerr(gettext("Invalid property group flag "
13677 				    "%c."), *cp);
13678 				return;
13679 			}
13680 		}
13681 	}
13682 
13683 	pg = scf_pg_create(g_hndl);
13684 	if (pg == NULL)
13685 		scfdie();
13686 
13687 	if (cur_inst != NULL)
13688 		ret = scf_instance_add_pg(cur_inst, name, type, flgs, pg);
13689 	else
13690 		ret = scf_service_add_pg(cur_svc, name, type, flgs, pg);
13691 
13692 	if (ret != SCF_SUCCESS) {
13693 		switch (scf_error()) {
13694 		case SCF_ERROR_INVALID_ARGUMENT:
13695 			semerr(gettext("Name, type, or flags are invalid.\n"));
13696 			break;
13697 
13698 		case SCF_ERROR_EXISTS:
13699 			semerr(gettext("Property group already exists.\n"));
13700 			break;
13701 
13702 		case SCF_ERROR_PERMISSION_DENIED:
13703 			semerr(emsg_permission_denied);
13704 			break;
13705 
13706 		case SCF_ERROR_BACKEND_ACCESS:
13707 			semerr(gettext("Backend refused access.\n"));
13708 			break;
13709 
13710 		default:
13711 			scfdie();
13712 		}
13713 	}
13714 
13715 	scf_pg_destroy(pg);
13716 
13717 	private_refresh();
13718 }
13719 
13720 void
13721 lscf_delpg(char *name)
13722 {
13723 	lscf_prep_hndl();
13724 
13725 	if (cur_snap != NULL) {
13726 		semerr(emsg_cant_modify_snapshots);
13727 		return;
13728 	}
13729 
13730 	if (cur_inst == NULL && cur_svc == NULL) {
13731 		semerr(emsg_entity_not_selected);
13732 		return;
13733 	}
13734 
13735 	if (strchr(name, '/') != NULL) {
13736 		semerr(emsg_invalid_pg_name, name);
13737 		return;
13738 	}
13739 
13740 	lscf_delprop(name);
13741 }
13742 
13743 /*
13744  * scf_delhash() is used to remove the property group related to the
13745  * hash entry for a specific manifest in the repository. pgname will be
13746  * constructed from the location of the manifest file. If deathrow isn't 0,
13747  * manifest file doesn't need to exist (manifest string will be used as
13748  * an absolute path).
13749  */
13750 void
13751 lscf_delhash(char *manifest, int deathrow)
13752 {
13753 	char *pgname;
13754 
13755 	if (cur_snap != NULL ||
13756 	    cur_inst != NULL || cur_svc != NULL) {
13757 		warn(gettext("error, an entity is selected\n"));
13758 		return;
13759 	}
13760 
13761 	/* select smf/manifest */
13762 	lscf_select(HASH_SVC);
13763 	/*
13764 	 * Translate the manifest file name to property name. In the deathrow
13765 	 * case, the manifest file does not need to exist.
13766 	 */
13767 	pgname = mhash_filename_to_propname(manifest,
13768 	    deathrow ? B_TRUE : B_FALSE);
13769 	if (pgname == NULL) {
13770 		warn(gettext("cannot resolve pathname for %s\n"), manifest);
13771 		return;
13772 	}
13773 	/* delete the hash property name */
13774 	lscf_delpg(pgname);
13775 }
13776 
13777 void
13778 lscf_listprop(const char *pattern)
13779 {
13780 	lscf_prep_hndl();
13781 
13782 	listprop(pattern, 0, 0);
13783 }
13784 
13785 int
13786 lscf_setprop(const char *pgname, const char *type, const char *value,
13787     const uu_list_t *values)
13788 {
13789 	scf_type_t ty, current_ty;
13790 	scf_service_t *svc;
13791 	scf_propertygroup_t *pg, *parent_pg;
13792 	scf_property_t *prop, *parent_prop;
13793 	scf_pg_tmpl_t *pgt;
13794 	scf_prop_tmpl_t *prt;
13795 	int ret, result = 0;
13796 	scf_transaction_t *tx;
13797 	scf_transaction_entry_t *e;
13798 	scf_value_t *v;
13799 	uu_list_walk_t *walk;
13800 	string_list_t *sp;
13801 	char *propname;
13802 	int req_quotes = 0;
13803 
13804 	lscf_prep_hndl();
13805 
13806 	if ((e = scf_entry_create(g_hndl)) == NULL ||
13807 	    (svc = scf_service_create(g_hndl)) == NULL ||
13808 	    (parent_pg = scf_pg_create(g_hndl)) == NULL ||
13809 	    (pg = scf_pg_create(g_hndl)) == NULL ||
13810 	    (parent_prop = scf_property_create(g_hndl)) == NULL ||
13811 	    (prop = scf_property_create(g_hndl)) == NULL ||
13812 	    (pgt = scf_tmpl_pg_create(g_hndl)) == NULL ||
13813 	    (prt = scf_tmpl_prop_create(g_hndl)) == NULL ||
13814 	    (tx = scf_transaction_create(g_hndl)) == NULL)
13815 		scfdie();
13816 
13817 	if (cur_snap != NULL) {
13818 		semerr(emsg_cant_modify_snapshots);
13819 		goto fail;
13820 	}
13821 
13822 	if (cur_inst == NULL && cur_svc == NULL) {
13823 		semerr(emsg_entity_not_selected);
13824 		goto fail;
13825 	}
13826 
13827 	propname = strchr(pgname, '/');
13828 	if (propname == NULL) {
13829 		semerr(gettext("Property names must contain a `/'.\n"));
13830 		goto fail;
13831 	}
13832 
13833 	*propname = '\0';
13834 	++propname;
13835 
13836 	if (type != NULL) {
13837 		ty = string_to_type(type);
13838 		if (ty == SCF_TYPE_INVALID) {
13839 			semerr(gettext("Unknown type \"%s\".\n"), type);
13840 			goto fail;
13841 		}
13842 	}
13843 
13844 	if (cur_inst != NULL)
13845 		ret = scf_instance_get_pg(cur_inst, pgname, pg);
13846 	else
13847 		ret = scf_service_get_pg(cur_svc, pgname, pg);
13848 	if (ret != SCF_SUCCESS) {
13849 		switch (scf_error()) {
13850 		case SCF_ERROR_NOT_FOUND:
13851 			semerr(emsg_no_such_pg, pgname);
13852 			goto fail;
13853 
13854 		case SCF_ERROR_INVALID_ARGUMENT:
13855 			semerr(emsg_invalid_pg_name, pgname);
13856 			goto fail;
13857 
13858 		default:
13859 			scfdie();
13860 			break;
13861 		}
13862 	}
13863 
13864 	do {
13865 		if (scf_pg_update(pg) == -1)
13866 			scfdie();
13867 		if (scf_transaction_start(tx, pg) != SCF_SUCCESS) {
13868 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
13869 				scfdie();
13870 
13871 			semerr(emsg_permission_denied);
13872 			goto fail;
13873 		}
13874 
13875 		ret = scf_pg_get_property(pg, propname, prop);
13876 		if (ret == SCF_SUCCESS) {
13877 			if (scf_property_type(prop, &current_ty) != SCF_SUCCESS)
13878 				scfdie();
13879 
13880 			if (type == NULL)
13881 				ty = current_ty;
13882 			if (scf_transaction_property_change_type(tx, e,
13883 			    propname, ty) == -1)
13884 				scfdie();
13885 
13886 		} else if (scf_error() == SCF_ERROR_NOT_FOUND) {
13887 			/* Infer the type, if possible. */
13888 			if (type == NULL) {
13889 				/*
13890 				 * First check if we're an instance and the
13891 				 * property is set on the service.
13892 				 */
13893 				if (cur_inst != NULL &&
13894 				    scf_instance_get_parent(cur_inst,
13895 				    svc) == 0 &&
13896 				    scf_service_get_pg(cur_svc, pgname,
13897 				    parent_pg) == 0 &&
13898 				    scf_pg_get_property(parent_pg, propname,
13899 				    parent_prop) == 0 &&
13900 				    scf_property_type(parent_prop,
13901 				    &current_ty) == 0) {
13902 					ty = current_ty;
13903 
13904 				/* Then check for a type set in a template. */
13905 				} else if (scf_tmpl_get_by_pg(pg, pgt,
13906 				    0) == 0 &&
13907 				    scf_tmpl_get_by_prop(pgt, propname, prt,
13908 				    0) == 0 &&
13909 				    scf_tmpl_prop_type(prt, &current_ty) == 0) {
13910 					ty = current_ty;
13911 
13912 				/* If type can't be inferred, fail. */
13913 				} else {
13914 					semerr(gettext("Type required for new "
13915 					    "properties.\n"));
13916 					goto fail;
13917 				}
13918 			}
13919 			if (scf_transaction_property_new(tx, e, propname,
13920 			    ty) == -1)
13921 				scfdie();
13922 		} else if (scf_error() == SCF_ERROR_INVALID_ARGUMENT) {
13923 			semerr(emsg_invalid_prop_name, propname);
13924 			goto fail;
13925 		} else {
13926 			scfdie();
13927 		}
13928 
13929 		if (ty == SCF_TYPE_ASTRING || ty == SCF_TYPE_USTRING)
13930 			req_quotes = 1;
13931 
13932 		if (value != NULL) {
13933 			v = string_to_value(value, ty, 0);
13934 
13935 			if (v == NULL)
13936 				goto fail;
13937 
13938 			ret = scf_entry_add_value(e, v);
13939 			assert(ret == SCF_SUCCESS);
13940 		} else {
13941 			assert(values != NULL);
13942 
13943 			walk = uu_list_walk_start((uu_list_t *)values,
13944 			    UU_DEFAULT);
13945 			if (walk == NULL)
13946 				uu_die(gettext("Could not walk list"));
13947 
13948 			for (sp = uu_list_walk_next(walk); sp != NULL;
13949 			    sp = uu_list_walk_next(walk)) {
13950 				v = string_to_value(sp->str, ty, req_quotes);
13951 
13952 				if (v == NULL) {
13953 					scf_entry_destroy_children(e);
13954 					goto fail;
13955 				}
13956 
13957 				ret = scf_entry_add_value(e, v);
13958 				assert(ret == SCF_SUCCESS);
13959 			}
13960 			uu_list_walk_end(walk);
13961 		}
13962 		result = scf_transaction_commit(tx);
13963 
13964 		scf_transaction_reset(tx);
13965 		scf_entry_destroy_children(e);
13966 	} while (result == 0);
13967 
13968 	if (result < 0) {
13969 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
13970 			scfdie();
13971 
13972 		semerr(emsg_permission_denied);
13973 		goto fail;
13974 	}
13975 
13976 	ret = 0;
13977 
13978 	private_refresh();
13979 
13980 	goto cleanup;
13981 
13982 fail:
13983 	ret = -1;
13984 
13985 cleanup:
13986 	scf_transaction_destroy(tx);
13987 	scf_entry_destroy(e);
13988 	scf_service_destroy(svc);
13989 	scf_pg_destroy(parent_pg);
13990 	scf_pg_destroy(pg);
13991 	scf_property_destroy(parent_prop);
13992 	scf_property_destroy(prop);
13993 	scf_tmpl_pg_destroy(pgt);
13994 	scf_tmpl_prop_destroy(prt);
13995 
13996 	return (ret);
13997 }
13998 
13999 void
14000 lscf_delprop(char *pgn)
14001 {
14002 	char *slash, *pn;
14003 	scf_propertygroup_t *pg;
14004 	scf_transaction_t *tx;
14005 	scf_transaction_entry_t *e;
14006 	int ret;
14007 
14008 
14009 	lscf_prep_hndl();
14010 
14011 	if (cur_snap != NULL) {
14012 		semerr(emsg_cant_modify_snapshots);
14013 		return;
14014 	}
14015 
14016 	if (cur_inst == NULL && cur_svc == NULL) {
14017 		semerr(emsg_entity_not_selected);
14018 		return;
14019 	}
14020 
14021 	pg = scf_pg_create(g_hndl);
14022 	if (pg == NULL)
14023 		scfdie();
14024 
14025 	slash = strchr(pgn, '/');
14026 	if (slash == NULL) {
14027 		pn = NULL;
14028 	} else {
14029 		*slash = '\0';
14030 		pn = slash + 1;
14031 	}
14032 
14033 	if (cur_inst != NULL)
14034 		ret = scf_instance_get_pg(cur_inst, pgn, pg);
14035 	else
14036 		ret = scf_service_get_pg(cur_svc, pgn, pg);
14037 	if (ret != SCF_SUCCESS) {
14038 		switch (scf_error()) {
14039 		case SCF_ERROR_NOT_FOUND:
14040 			semerr(emsg_no_such_pg, pgn);
14041 			break;
14042 
14043 		case SCF_ERROR_INVALID_ARGUMENT:
14044 			semerr(emsg_invalid_pg_name, pgn);
14045 			break;
14046 
14047 		default:
14048 			scfdie();
14049 		}
14050 
14051 		scf_pg_destroy(pg);
14052 
14053 		return;
14054 	}
14055 
14056 	if (pn == NULL) {
14057 		/* Try to delete the property group. */
14058 		if (scf_pg_delete(pg) != SCF_SUCCESS) {
14059 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14060 				scfdie();
14061 
14062 			semerr(emsg_permission_denied);
14063 		} else {
14064 			private_refresh();
14065 		}
14066 
14067 		scf_pg_destroy(pg);
14068 		return;
14069 	}
14070 
14071 	e = scf_entry_create(g_hndl);
14072 	tx = scf_transaction_create(g_hndl);
14073 
14074 	do {
14075 		if (scf_pg_update(pg) == -1)
14076 			scfdie();
14077 		if (scf_transaction_start(tx, pg) != SCF_SUCCESS) {
14078 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14079 				scfdie();
14080 
14081 			semerr(emsg_permission_denied);
14082 			break;
14083 		}
14084 
14085 		if (scf_transaction_property_delete(tx, e, pn) != SCF_SUCCESS) {
14086 			if (scf_error() == SCF_ERROR_NOT_FOUND) {
14087 				semerr(gettext("No such property %s/%s.\n"),
14088 				    pgn, pn);
14089 				break;
14090 			} else if (scf_error() == SCF_ERROR_INVALID_ARGUMENT) {
14091 				semerr(emsg_invalid_prop_name, pn);
14092 				break;
14093 			} else {
14094 				scfdie();
14095 			}
14096 		}
14097 
14098 		ret = scf_transaction_commit(tx);
14099 
14100 		if (ret == 0)
14101 			scf_transaction_reset(tx);
14102 	} while (ret == 0);
14103 
14104 	if (ret < 0) {
14105 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14106 			scfdie();
14107 
14108 		semerr(emsg_permission_denied);
14109 	} else {
14110 		private_refresh();
14111 	}
14112 
14113 	scf_transaction_destroy(tx);
14114 	scf_entry_destroy(e);
14115 	scf_pg_destroy(pg);
14116 }
14117 
14118 /*
14119  * Property editing.
14120  */
14121 
14122 static int
14123 write_edit_script(FILE *strm)
14124 {
14125 	char *fmribuf;
14126 	ssize_t fmrilen;
14127 
14128 	scf_propertygroup_t *pg;
14129 	scf_property_t *prop;
14130 	scf_value_t *val;
14131 	scf_type_t ty;
14132 	int ret, result = 0;
14133 	scf_iter_t *iter, *piter, *viter;
14134 	char *buf, *tybuf, *pname;
14135 	const char *emsg_write_error;
14136 
14137 
14138 	emsg_write_error = gettext("Error writing temoprary file: %s.\n");
14139 
14140 
14141 	/* select fmri */
14142 	if (cur_inst != NULL) {
14143 		fmrilen = scf_instance_to_fmri(cur_inst, NULL, 0);
14144 		if (fmrilen < 0)
14145 			scfdie();
14146 		fmribuf = safe_malloc(fmrilen + 1);
14147 		if (scf_instance_to_fmri(cur_inst, fmribuf, fmrilen + 1) < 0)
14148 			scfdie();
14149 	} else {
14150 		assert(cur_svc != NULL);
14151 		fmrilen = scf_service_to_fmri(cur_svc, NULL, 0);
14152 		if (fmrilen < 0)
14153 			scfdie();
14154 		fmribuf = safe_malloc(fmrilen + 1);
14155 		if (scf_service_to_fmri(cur_svc, fmribuf, fmrilen + 1) < 0)
14156 			scfdie();
14157 	}
14158 
14159 	if (fprintf(strm, "select %s\n\n", fmribuf) < 0) {
14160 		warn(emsg_write_error, strerror(errno));
14161 		free(fmribuf);
14162 		return (-1);
14163 	}
14164 
14165 	free(fmribuf);
14166 
14167 
14168 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
14169 	    (prop = scf_property_create(g_hndl)) == NULL ||
14170 	    (val = scf_value_create(g_hndl)) == NULL ||
14171 	    (iter = scf_iter_create(g_hndl)) == NULL ||
14172 	    (piter = scf_iter_create(g_hndl)) == NULL ||
14173 	    (viter = scf_iter_create(g_hndl)) == NULL)
14174 		scfdie();
14175 
14176 	buf = safe_malloc(max_scf_name_len + 1);
14177 	tybuf = safe_malloc(max_scf_pg_type_len + 1);
14178 	pname = safe_malloc(max_scf_name_len + 1);
14179 
14180 	if (cur_inst != NULL)
14181 		ret = scf_iter_instance_pgs(iter, cur_inst);
14182 	else
14183 		ret = scf_iter_service_pgs(iter, cur_svc);
14184 	if (ret != SCF_SUCCESS)
14185 		scfdie();
14186 
14187 	while ((ret = scf_iter_next_pg(iter, pg)) == 1) {
14188 		int ret2;
14189 
14190 		/*
14191 		 * # delprop pg
14192 		 * # addpg pg type
14193 		 */
14194 		if (scf_pg_get_name(pg, buf, max_scf_name_len + 1) < 0)
14195 			scfdie();
14196 
14197 		if (scf_pg_get_type(pg, tybuf, max_scf_pg_type_len + 1) < 0)
14198 			scfdie();
14199 
14200 		if (fprintf(strm, "# Property group \"%s\"\n"
14201 		    "# delprop %s\n"
14202 		    "# addpg %s %s\n", buf, buf, buf, tybuf) < 0) {
14203 			warn(emsg_write_error, strerror(errno));
14204 			result = -1;
14205 			goto out;
14206 		}
14207 
14208 		/* # setprop pg/prop = (values) */
14209 
14210 		if (scf_iter_pg_properties(piter, pg) != SCF_SUCCESS)
14211 			scfdie();
14212 
14213 		while ((ret2 = scf_iter_next_property(piter, prop)) == 1) {
14214 			int first = 1;
14215 			int ret3;
14216 			int multiple;
14217 			int is_str;
14218 			scf_type_t bty;
14219 
14220 			if (scf_property_get_name(prop, pname,
14221 			    max_scf_name_len + 1) < 0)
14222 				scfdie();
14223 
14224 			if (scf_property_type(prop, &ty) != 0)
14225 				scfdie();
14226 
14227 			multiple = prop_has_multiple_values(prop, val);
14228 
14229 			if (fprintf(strm, "# setprop %s/%s = %s: %s", buf,
14230 			    pname, scf_type_to_string(ty), multiple ? "(" : "")
14231 			    < 0) {
14232 				warn(emsg_write_error, strerror(errno));
14233 				result = -1;
14234 				goto out;
14235 			}
14236 
14237 			(void) scf_type_base_type(ty, &bty);
14238 			is_str = (bty == SCF_TYPE_ASTRING);
14239 
14240 			if (scf_iter_property_values(viter, prop) !=
14241 			    SCF_SUCCESS)
14242 				scfdie();
14243 
14244 			while ((ret3 = scf_iter_next_value(viter, val)) == 1) {
14245 				char *buf;
14246 				ssize_t buflen;
14247 
14248 				buflen = scf_value_get_as_string(val, NULL, 0);
14249 				if (buflen < 0)
14250 					scfdie();
14251 
14252 				buf = safe_malloc(buflen + 1);
14253 
14254 				if (scf_value_get_as_string(val, buf,
14255 				    buflen + 1) < 0)
14256 					scfdie();
14257 
14258 				if (first)
14259 					first = 0;
14260 				else {
14261 					if (putc(' ', strm) != ' ') {
14262 						warn(emsg_write_error,
14263 						    strerror(errno));
14264 						result = -1;
14265 						goto out;
14266 					}
14267 				}
14268 
14269 				if ((is_str && multiple) ||
14270 				    strpbrk(buf, CHARS_TO_QUOTE) != NULL) {
14271 					(void) putc('"', strm);
14272 					(void) quote_and_print(buf, strm, 1);
14273 					(void) putc('"', strm);
14274 
14275 					if (ferror(strm)) {
14276 						warn(emsg_write_error,
14277 						    strerror(errno));
14278 						result = -1;
14279 						goto out;
14280 					}
14281 				} else {
14282 					if (fprintf(strm, "%s", buf) < 0) {
14283 						warn(emsg_write_error,
14284 						    strerror(errno));
14285 						result = -1;
14286 						goto out;
14287 					}
14288 				}
14289 
14290 				free(buf);
14291 			}
14292 			if (ret3 < 0 &&
14293 			    scf_error() != SCF_ERROR_PERMISSION_DENIED)
14294 				scfdie();
14295 
14296 			/* Write closing paren if mult-value property */
14297 			if ((multiple && putc(')', strm) == EOF) ||
14298 
14299 			    /* Write final newline */
14300 			    fputc('\n', strm) == EOF) {
14301 				warn(emsg_write_error, strerror(errno));
14302 				result = -1;
14303 				goto out;
14304 			}
14305 		}
14306 		if (ret2 < 0)
14307 			scfdie();
14308 
14309 		if (fputc('\n', strm) == EOF) {
14310 			warn(emsg_write_error, strerror(errno));
14311 			result = -1;
14312 			goto out;
14313 		}
14314 	}
14315 	if (ret < 0)
14316 		scfdie();
14317 
14318 out:
14319 	free(pname);
14320 	free(tybuf);
14321 	free(buf);
14322 	scf_iter_destroy(viter);
14323 	scf_iter_destroy(piter);
14324 	scf_iter_destroy(iter);
14325 	scf_value_destroy(val);
14326 	scf_property_destroy(prop);
14327 	scf_pg_destroy(pg);
14328 
14329 	if (result == 0) {
14330 		if (fflush(strm) != 0) {
14331 			warn(emsg_write_error, strerror(errno));
14332 			return (-1);
14333 		}
14334 	}
14335 
14336 	return (result);
14337 }
14338 
14339 int
14340 lscf_editprop()
14341 {
14342 	char *buf, *editor;
14343 	size_t bufsz;
14344 	int tmpfd;
14345 	char tempname[] = TEMP_FILE_PATTERN;
14346 
14347 	lscf_prep_hndl();
14348 
14349 	if (cur_snap != NULL) {
14350 		semerr(emsg_cant_modify_snapshots);
14351 		return (-1);
14352 	}
14353 
14354 	if (cur_svc == NULL && cur_inst == NULL) {
14355 		semerr(emsg_entity_not_selected);
14356 		return (-1);
14357 	}
14358 
14359 	tmpfd = mkstemp(tempname);
14360 	if (tmpfd == -1) {
14361 		semerr(gettext("Could not create temporary file.\n"));
14362 		return (-1);
14363 	}
14364 
14365 	(void) strcpy(tempfilename, tempname);
14366 
14367 	tempfile = fdopen(tmpfd, "r+");
14368 	if (tempfile == NULL) {
14369 		warn(gettext("Could not create temporary file.\n"));
14370 		if (close(tmpfd) == -1)
14371 			warn(gettext("Could not close temporary file: %s.\n"),
14372 			    strerror(errno));
14373 
14374 		remove_tempfile();
14375 
14376 		return (-1);
14377 	}
14378 
14379 	if (write_edit_script(tempfile) == -1) {
14380 		remove_tempfile();
14381 		return (-1);
14382 	}
14383 
14384 	editor = getenv("EDITOR");
14385 	if (editor == NULL)
14386 		editor = "vi";
14387 
14388 	bufsz = strlen(editor) + 1 + strlen(tempname) + 1;
14389 	buf = safe_malloc(bufsz);
14390 
14391 	if (snprintf(buf, bufsz, "%s %s", editor, tempname) < 0)
14392 		uu_die(gettext("Error creating editor command"));
14393 
14394 	if (system(buf) == -1) {
14395 		semerr(gettext("Could not launch editor %s: %s\n"), editor,
14396 		    strerror(errno));
14397 		free(buf);
14398 		remove_tempfile();
14399 		return (-1);
14400 	}
14401 
14402 	free(buf);
14403 
14404 	(void) engine_source(tempname, est->sc_cmd_flags & SC_CMD_IACTIVE);
14405 
14406 	remove_tempfile();
14407 
14408 	return (0);
14409 }
14410 
14411 static void
14412 add_string(uu_list_t *strlist, const char *str)
14413 {
14414 	string_list_t *elem;
14415 	elem = safe_malloc(sizeof (*elem));
14416 	uu_list_node_init(elem, &elem->node, string_pool);
14417 	elem->str = safe_strdup(str);
14418 	if (uu_list_append(strlist, elem) != 0)
14419 		uu_die(gettext("libuutil error: %s\n"),
14420 		    uu_strerror(uu_error()));
14421 }
14422 
14423 static int
14424 remove_string(uu_list_t *strlist, const char *str)
14425 {
14426 	uu_list_walk_t	*elems;
14427 	string_list_t	*sp;
14428 
14429 	/*
14430 	 * Find the element that needs to be removed.
14431 	 */
14432 	elems = uu_list_walk_start(strlist, UU_DEFAULT);
14433 	while ((sp = uu_list_walk_next(elems)) != NULL) {
14434 		if (strcmp(sp->str, str) == 0)
14435 			break;
14436 	}
14437 	uu_list_walk_end(elems);
14438 
14439 	/*
14440 	 * Returning 1 here as the value was not found, this
14441 	 * might not be an error.  Leave it to the caller to
14442 	 * decide.
14443 	 */
14444 	if (sp == NULL) {
14445 		return (1);
14446 	}
14447 
14448 	uu_list_remove(strlist, sp);
14449 
14450 	free(sp->str);
14451 	free(sp);
14452 
14453 	return (0);
14454 }
14455 
14456 /*
14457  * Get all property values that don't match the given glob pattern,
14458  * if a pattern is specified.
14459  */
14460 static void
14461 get_prop_values(scf_property_t *prop, uu_list_t *values,
14462     const char *pattern)
14463 {
14464 	scf_iter_t *iter;
14465 	scf_value_t *val;
14466 	int ret;
14467 
14468 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
14469 	    (val = scf_value_create(g_hndl)) == NULL)
14470 		scfdie();
14471 
14472 	if (scf_iter_property_values(iter, prop) != 0)
14473 		scfdie();
14474 
14475 	while ((ret = scf_iter_next_value(iter, val)) == 1) {
14476 		char *buf;
14477 		ssize_t vlen, szret;
14478 
14479 		vlen = scf_value_get_as_string(val, NULL, 0);
14480 		if (vlen < 0)
14481 			scfdie();
14482 
14483 		buf = safe_malloc(vlen + 1);
14484 
14485 		szret = scf_value_get_as_string(val, buf, vlen + 1);
14486 		if (szret < 0)
14487 			scfdie();
14488 		assert(szret <= vlen);
14489 
14490 		if (pattern == NULL || fnmatch(pattern, buf, 0) != 0)
14491 			add_string(values, buf);
14492 
14493 		free(buf);
14494 	}
14495 
14496 	if (ret == -1)
14497 		scfdie();
14498 
14499 	scf_value_destroy(val);
14500 	scf_iter_destroy(iter);
14501 }
14502 
14503 static int
14504 lscf_setpropvalue(const char *pgname, const char *type,
14505     const char *arg, int isadd, int isnotfoundok)
14506 {
14507 	scf_type_t ty;
14508 	scf_propertygroup_t *pg;
14509 	scf_property_t *prop;
14510 	int ret, result = 0;
14511 	scf_transaction_t *tx;
14512 	scf_transaction_entry_t *e;
14513 	scf_value_t *v;
14514 	string_list_t *sp;
14515 	char *propname;
14516 	uu_list_t *values;
14517 	uu_list_walk_t *walk;
14518 	void *cookie = NULL;
14519 	char *pattern = NULL;
14520 
14521 	lscf_prep_hndl();
14522 
14523 	if ((values = uu_list_create(string_pool, NULL, 0)) == NULL)
14524 		uu_die(gettext("Could not create property list: %s\n"),
14525 		    uu_strerror(uu_error()));
14526 
14527 	if (!isadd)
14528 		pattern = safe_strdup(arg);
14529 
14530 	if ((e = scf_entry_create(g_hndl)) == NULL ||
14531 	    (pg = scf_pg_create(g_hndl)) == NULL ||
14532 	    (prop = scf_property_create(g_hndl)) == NULL ||
14533 	    (tx = scf_transaction_create(g_hndl)) == NULL)
14534 		scfdie();
14535 
14536 	if (cur_snap != NULL) {
14537 		semerr(emsg_cant_modify_snapshots);
14538 		goto fail;
14539 	}
14540 
14541 	if (cur_inst == NULL && cur_svc == NULL) {
14542 		semerr(emsg_entity_not_selected);
14543 		goto fail;
14544 	}
14545 
14546 	propname = strchr(pgname, '/');
14547 	if (propname == NULL) {
14548 		semerr(gettext("Property names must contain a `/'.\n"));
14549 		goto fail;
14550 	}
14551 
14552 	*propname = '\0';
14553 	++propname;
14554 
14555 	if (type != NULL) {
14556 		ty = string_to_type(type);
14557 		if (ty == SCF_TYPE_INVALID) {
14558 			semerr(gettext("Unknown type \"%s\".\n"), type);
14559 			goto fail;
14560 		}
14561 	}
14562 
14563 	if (cur_inst != NULL)
14564 		ret = scf_instance_get_pg(cur_inst, pgname, pg);
14565 	else
14566 		ret = scf_service_get_pg(cur_svc, pgname, pg);
14567 	if (ret != 0) {
14568 		switch (scf_error()) {
14569 		case SCF_ERROR_NOT_FOUND:
14570 			if (isnotfoundok) {
14571 				result = 0;
14572 			} else {
14573 				semerr(emsg_no_such_pg, pgname);
14574 				result = -1;
14575 			}
14576 			goto out;
14577 
14578 		case SCF_ERROR_INVALID_ARGUMENT:
14579 			semerr(emsg_invalid_pg_name, pgname);
14580 			goto fail;
14581 
14582 		default:
14583 			scfdie();
14584 		}
14585 	}
14586 
14587 	do {
14588 		if (scf_pg_update(pg) == -1)
14589 			scfdie();
14590 		if (scf_transaction_start(tx, pg) != 0) {
14591 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14592 				scfdie();
14593 
14594 			semerr(emsg_permission_denied);
14595 			goto fail;
14596 		}
14597 
14598 		ret = scf_pg_get_property(pg, propname, prop);
14599 		if (ret == 0) {
14600 			scf_type_t ptype;
14601 			char *pat = pattern;
14602 
14603 			if (scf_property_type(prop, &ptype) != 0)
14604 				scfdie();
14605 
14606 			if (isadd) {
14607 				if (type != NULL && ptype != ty) {
14608 					semerr(gettext("Property \"%s\" is not "
14609 					    "of type \"%s\".\n"), propname,
14610 					    type);
14611 					goto fail;
14612 				}
14613 
14614 				pat = NULL;
14615 			} else {
14616 				size_t len = strlen(pat);
14617 				if (len > 0 && pat[len - 1] == '\"')
14618 					pat[len - 1] = '\0';
14619 				if (len > 0 && pat[0] == '\"')
14620 					pat++;
14621 			}
14622 
14623 			ty = ptype;
14624 
14625 			get_prop_values(prop, values, pat);
14626 
14627 			if (isadd)
14628 				add_string(values, arg);
14629 
14630 			if (scf_transaction_property_change(tx, e,
14631 			    propname, ty) == -1)
14632 				scfdie();
14633 		} else if (scf_error() == SCF_ERROR_NOT_FOUND) {
14634 			if (isadd) {
14635 				if (type == NULL) {
14636 					semerr(gettext("Type required "
14637 					    "for new properties.\n"));
14638 					goto fail;
14639 				}
14640 
14641 				add_string(values, arg);
14642 
14643 				if (scf_transaction_property_new(tx, e,
14644 				    propname, ty) == -1)
14645 					scfdie();
14646 			} else if (isnotfoundok) {
14647 				result = 0;
14648 				goto out;
14649 			} else {
14650 				semerr(gettext("No such property %s/%s.\n"),
14651 				    pgname, propname);
14652 				result = -1;
14653 				goto out;
14654 			}
14655 		} else if (scf_error() == SCF_ERROR_INVALID_ARGUMENT) {
14656 			semerr(emsg_invalid_prop_name, propname);
14657 			goto fail;
14658 		} else {
14659 			scfdie();
14660 		}
14661 
14662 		walk = uu_list_walk_start(values, UU_DEFAULT);
14663 		if (walk == NULL)
14664 			uu_die(gettext("Could not walk property list.\n"));
14665 
14666 		for (sp = uu_list_walk_next(walk); sp != NULL;
14667 		    sp = uu_list_walk_next(walk)) {
14668 			v = string_to_value(sp->str, ty, 0);
14669 
14670 			if (v == NULL) {
14671 				scf_entry_destroy_children(e);
14672 				goto fail;
14673 			}
14674 			ret = scf_entry_add_value(e, v);
14675 			assert(ret == 0);
14676 		}
14677 		uu_list_walk_end(walk);
14678 
14679 		result = scf_transaction_commit(tx);
14680 
14681 		scf_transaction_reset(tx);
14682 		scf_entry_destroy_children(e);
14683 	} while (result == 0);
14684 
14685 	if (result < 0) {
14686 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14687 			scfdie();
14688 
14689 		semerr(emsg_permission_denied);
14690 		goto fail;
14691 	}
14692 
14693 	result = 0;
14694 
14695 	private_refresh();
14696 
14697 out:
14698 	scf_transaction_destroy(tx);
14699 	scf_entry_destroy(e);
14700 	scf_pg_destroy(pg);
14701 	scf_property_destroy(prop);
14702 	free(pattern);
14703 
14704 	while ((sp = uu_list_teardown(values, &cookie)) != NULL) {
14705 		free(sp->str);
14706 		free(sp);
14707 	}
14708 
14709 	uu_list_destroy(values);
14710 
14711 	return (result);
14712 
14713 fail:
14714 	result = -1;
14715 	goto out;
14716 }
14717 
14718 int
14719 lscf_addpropvalue(const char *pgname, const char *type, const char *value)
14720 {
14721 	return (lscf_setpropvalue(pgname, type, value, 1, 0));
14722 }
14723 
14724 int
14725 lscf_delpropvalue(const char *pgname, const char *pattern, int isnotfoundok)
14726 {
14727 	return (lscf_setpropvalue(pgname, NULL, pattern, 0, isnotfoundok));
14728 }
14729 
14730 /*
14731  * Look for a standard start method, first in the instance (if any),
14732  * then the service.
14733  */
14734 static const char *
14735 start_method_name(int *in_instance)
14736 {
14737 	scf_propertygroup_t *pg;
14738 	char **p;
14739 	int ret;
14740 	scf_instance_t *inst = cur_inst;
14741 
14742 	if ((pg = scf_pg_create(g_hndl)) == NULL)
14743 		scfdie();
14744 
14745 again:
14746 	for (p = start_method_names; *p != NULL; p++) {
14747 		if (inst != NULL)
14748 			ret = scf_instance_get_pg(inst, *p, pg);
14749 		else
14750 			ret = scf_service_get_pg(cur_svc, *p, pg);
14751 
14752 		if (ret == 0) {
14753 			size_t bufsz = strlen(SCF_GROUP_METHOD) + 1;
14754 			char *buf = safe_malloc(bufsz);
14755 
14756 			if ((ret = scf_pg_get_type(pg, buf, bufsz)) < 0) {
14757 				free(buf);
14758 				continue;
14759 			}
14760 			if (strcmp(buf, SCF_GROUP_METHOD) != 0) {
14761 				free(buf);
14762 				continue;
14763 			}
14764 
14765 			free(buf);
14766 			*in_instance = (inst != NULL);
14767 			scf_pg_destroy(pg);
14768 			return (*p);
14769 		}
14770 
14771 		if (scf_error() == SCF_ERROR_NOT_FOUND)
14772 			continue;
14773 
14774 		scfdie();
14775 	}
14776 
14777 	if (inst != NULL) {
14778 		inst = NULL;
14779 		goto again;
14780 	}
14781 
14782 	scf_pg_destroy(pg);
14783 	return (NULL);
14784 }
14785 
14786 static int
14787 addpg(const char *name, const char *type)
14788 {
14789 	scf_propertygroup_t *pg;
14790 	int ret;
14791 
14792 	pg = scf_pg_create(g_hndl);
14793 	if (pg == NULL)
14794 		scfdie();
14795 
14796 	if (cur_inst != NULL)
14797 		ret = scf_instance_add_pg(cur_inst, name, type, 0, pg);
14798 	else
14799 		ret = scf_service_add_pg(cur_svc, name, type, 0, pg);
14800 
14801 	if (ret != 0) {
14802 		switch (scf_error()) {
14803 		case SCF_ERROR_EXISTS:
14804 			ret = 0;
14805 			break;
14806 
14807 		case SCF_ERROR_PERMISSION_DENIED:
14808 			semerr(emsg_permission_denied);
14809 			break;
14810 
14811 		default:
14812 			scfdie();
14813 		}
14814 	}
14815 
14816 	scf_pg_destroy(pg);
14817 	return (ret);
14818 }
14819 
14820 int
14821 lscf_setenv(uu_list_t *args, int isunset)
14822 {
14823 	int ret = 0;
14824 	size_t i;
14825 	int argc;
14826 	char **argv = NULL;
14827 	string_list_t *slp;
14828 	char *pattern;
14829 	char *prop;
14830 	int do_service = 0;
14831 	int do_instance = 0;
14832 	const char *method = NULL;
14833 	const char *name = NULL;
14834 	const char *value = NULL;
14835 	scf_instance_t *saved_cur_inst = cur_inst;
14836 
14837 	lscf_prep_hndl();
14838 
14839 	argc = uu_list_numnodes(args);
14840 	if (argc < 1)
14841 		goto usage;
14842 
14843 	argv = calloc(argc + 1, sizeof (char *));
14844 	if (argv == NULL)
14845 		uu_die(gettext("Out of memory.\n"));
14846 
14847 	for (slp = uu_list_first(args), i = 0;
14848 	    slp != NULL;
14849 	    slp = uu_list_next(args, slp), ++i)
14850 		argv[i] = slp->str;
14851 
14852 	argv[i] = NULL;
14853 
14854 	opterr = 0;
14855 	optind = 0;
14856 	for (;;) {
14857 		ret = getopt(argc, argv, "sim:");
14858 		if (ret == -1)
14859 			break;
14860 
14861 		switch (ret) {
14862 		case 's':
14863 			do_service = 1;
14864 			cur_inst = NULL;
14865 			break;
14866 
14867 		case 'i':
14868 			do_instance = 1;
14869 			break;
14870 
14871 		case 'm':
14872 			method = optarg;
14873 			break;
14874 
14875 		case '?':
14876 			goto usage;
14877 
14878 		default:
14879 			bad_error("getopt", ret);
14880 		}
14881 	}
14882 
14883 	argc -= optind;
14884 	if ((do_service && do_instance) ||
14885 	    (isunset && argc != 1) ||
14886 	    (!isunset && argc != 2))
14887 		goto usage;
14888 
14889 	name = argv[optind];
14890 	if (!isunset)
14891 		value = argv[optind + 1];
14892 
14893 	if (cur_snap != NULL) {
14894 		semerr(emsg_cant_modify_snapshots);
14895 		ret = -1;
14896 		goto out;
14897 	}
14898 
14899 	if (cur_inst == NULL && cur_svc == NULL) {
14900 		semerr(emsg_entity_not_selected);
14901 		ret = -1;
14902 		goto out;
14903 	}
14904 
14905 	if (do_instance && cur_inst == NULL) {
14906 		semerr(gettext("No instance is selected.\n"));
14907 		ret = -1;
14908 		goto out;
14909 	}
14910 
14911 	if (do_service && cur_svc == NULL) {
14912 		semerr(gettext("No service is selected.\n"));
14913 		ret = -1;
14914 		goto out;
14915 	}
14916 
14917 	if (method == NULL) {
14918 		if (do_instance || do_service) {
14919 			method = "method_context";
14920 			if (!isunset) {
14921 				ret = addpg("method_context",
14922 				    SCF_GROUP_FRAMEWORK);
14923 				if (ret != 0)
14924 					goto out;
14925 			}
14926 		} else {
14927 			int in_instance;
14928 			method = start_method_name(&in_instance);
14929 			if (method == NULL) {
14930 				semerr(gettext(
14931 				    "Couldn't find start method; please "
14932 				    "specify a method with '-m'.\n"));
14933 				ret = -1;
14934 				goto out;
14935 			}
14936 			if (!in_instance)
14937 				cur_inst = NULL;
14938 		}
14939 	} else {
14940 		scf_propertygroup_t *pg;
14941 		size_t bufsz;
14942 		char *buf;
14943 		int ret;
14944 
14945 		if ((pg = scf_pg_create(g_hndl)) == NULL)
14946 			scfdie();
14947 
14948 		if (cur_inst != NULL)
14949 			ret = scf_instance_get_pg(cur_inst, method, pg);
14950 		else
14951 			ret = scf_service_get_pg(cur_svc, method, pg);
14952 
14953 		if (ret != 0) {
14954 			scf_pg_destroy(pg);
14955 			switch (scf_error()) {
14956 			case SCF_ERROR_NOT_FOUND:
14957 				semerr(gettext("Couldn't find the method "
14958 				    "\"%s\".\n"), method);
14959 				goto out;
14960 
14961 			case SCF_ERROR_INVALID_ARGUMENT:
14962 				semerr(gettext("Invalid method name \"%s\".\n"),
14963 				    method);
14964 				goto out;
14965 
14966 			default:
14967 				scfdie();
14968 			}
14969 		}
14970 
14971 		bufsz = strlen(SCF_GROUP_METHOD) + 1;
14972 		buf = safe_malloc(bufsz);
14973 
14974 		if (scf_pg_get_type(pg, buf, bufsz) < 0 ||
14975 		    strcmp(buf, SCF_GROUP_METHOD) != 0) {
14976 			semerr(gettext("Property group \"%s\" is not of type "
14977 			    "\"method\".\n"), method);
14978 			ret = -1;
14979 			free(buf);
14980 			scf_pg_destroy(pg);
14981 			goto out;
14982 		}
14983 
14984 		free(buf);
14985 		scf_pg_destroy(pg);
14986 	}
14987 
14988 	prop = uu_msprintf("%s/environment", method);
14989 	pattern = uu_msprintf("%s=*", name);
14990 
14991 	if (prop == NULL || pattern == NULL)
14992 		uu_die(gettext("Out of memory.\n"));
14993 
14994 	ret = lscf_delpropvalue(prop, pattern, !isunset);
14995 
14996 	if (ret == 0 && !isunset) {
14997 		uu_free(pattern);
14998 		uu_free(prop);
14999 		prop = uu_msprintf("%s/environment", method);
15000 		pattern = uu_msprintf("%s=%s", name, value);
15001 		if (prop == NULL || pattern == NULL)
15002 			uu_die(gettext("Out of memory.\n"));
15003 		ret = lscf_addpropvalue(prop, "astring:", pattern);
15004 	}
15005 	uu_free(pattern);
15006 	uu_free(prop);
15007 
15008 out:
15009 	cur_inst = saved_cur_inst;
15010 
15011 	free(argv);
15012 	return (ret);
15013 usage:
15014 	ret = -2;
15015 	goto out;
15016 }
15017 
15018 /*
15019  * Snapshot commands
15020  */
15021 
15022 void
15023 lscf_listsnap()
15024 {
15025 	scf_snapshot_t *snap;
15026 	scf_iter_t *iter;
15027 	char *nb;
15028 	int r;
15029 
15030 	lscf_prep_hndl();
15031 
15032 	if (cur_inst == NULL) {
15033 		semerr(gettext("Instance not selected.\n"));
15034 		return;
15035 	}
15036 
15037 	if ((snap = scf_snapshot_create(g_hndl)) == NULL ||
15038 	    (iter = scf_iter_create(g_hndl)) == NULL)
15039 		scfdie();
15040 
15041 	if (scf_iter_instance_snapshots(iter, cur_inst) != SCF_SUCCESS)
15042 		scfdie();
15043 
15044 	nb = safe_malloc(max_scf_name_len + 1);
15045 
15046 	while ((r = scf_iter_next_snapshot(iter, snap)) == 1) {
15047 		if (scf_snapshot_get_name(snap, nb, max_scf_name_len + 1) < 0)
15048 			scfdie();
15049 
15050 		(void) puts(nb);
15051 	}
15052 	if (r < 0)
15053 		scfdie();
15054 
15055 	free(nb);
15056 	scf_iter_destroy(iter);
15057 	scf_snapshot_destroy(snap);
15058 }
15059 
15060 void
15061 lscf_selectsnap(const char *name)
15062 {
15063 	scf_snapshot_t *snap;
15064 	scf_snaplevel_t *level;
15065 
15066 	lscf_prep_hndl();
15067 
15068 	if (cur_inst == NULL) {
15069 		semerr(gettext("Instance not selected.\n"));
15070 		return;
15071 	}
15072 
15073 	if (cur_snap != NULL) {
15074 		if (name != NULL) {
15075 			char *cur_snap_name;
15076 			boolean_t nochange;
15077 
15078 			cur_snap_name = safe_malloc(max_scf_name_len + 1);
15079 
15080 			if (scf_snapshot_get_name(cur_snap, cur_snap_name,
15081 			    max_scf_name_len + 1) < 0)
15082 				scfdie();
15083 
15084 			nochange = strcmp(name, cur_snap_name) == 0;
15085 
15086 			free(cur_snap_name);
15087 
15088 			if (nochange)
15089 				return;
15090 		}
15091 
15092 		unselect_cursnap();
15093 	}
15094 
15095 	if (name == NULL)
15096 		return;
15097 
15098 	if ((snap = scf_snapshot_create(g_hndl)) == NULL ||
15099 	    (level = scf_snaplevel_create(g_hndl)) == NULL)
15100 		scfdie();
15101 
15102 	if (scf_instance_get_snapshot(cur_inst, name, snap) !=
15103 	    SCF_SUCCESS) {
15104 		switch (scf_error()) {
15105 		case SCF_ERROR_INVALID_ARGUMENT:
15106 			semerr(gettext("Invalid name \"%s\".\n"), name);
15107 			break;
15108 
15109 		case SCF_ERROR_NOT_FOUND:
15110 			semerr(gettext("No such snapshot \"%s\".\n"), name);
15111 			break;
15112 
15113 		default:
15114 			scfdie();
15115 		}
15116 
15117 		scf_snaplevel_destroy(level);
15118 		scf_snapshot_destroy(snap);
15119 		return;
15120 	}
15121 
15122 	/* Load the snaplevels into our list. */
15123 	cur_levels = uu_list_create(snaplevel_pool, NULL, 0);
15124 	if (cur_levels == NULL)
15125 		uu_die(gettext("Could not create list: %s\n"),
15126 		    uu_strerror(uu_error()));
15127 
15128 	if (scf_snapshot_get_base_snaplevel(snap, level) != SCF_SUCCESS) {
15129 		if (scf_error() != SCF_ERROR_NOT_FOUND)
15130 			scfdie();
15131 
15132 		semerr(gettext("Snapshot has no snaplevels.\n"));
15133 
15134 		scf_snaplevel_destroy(level);
15135 		scf_snapshot_destroy(snap);
15136 		return;
15137 	}
15138 
15139 	cur_snap = snap;
15140 
15141 	for (;;) {
15142 		cur_elt = safe_malloc(sizeof (*cur_elt));
15143 		uu_list_node_init(cur_elt, &cur_elt->list_node,
15144 		    snaplevel_pool);
15145 		cur_elt->sl = level;
15146 		if (uu_list_insert_after(cur_levels, NULL, cur_elt) != 0)
15147 			uu_die(gettext("libuutil error: %s\n"),
15148 			    uu_strerror(uu_error()));
15149 
15150 		level = scf_snaplevel_create(g_hndl);
15151 		if (level == NULL)
15152 			scfdie();
15153 
15154 		if (scf_snaplevel_get_next_snaplevel(cur_elt->sl,
15155 		    level) != SCF_SUCCESS) {
15156 			if (scf_error() != SCF_ERROR_NOT_FOUND)
15157 				scfdie();
15158 
15159 			scf_snaplevel_destroy(level);
15160 			break;
15161 		}
15162 	}
15163 
15164 	cur_elt = uu_list_last(cur_levels);
15165 	cur_level = cur_elt->sl;
15166 }
15167 
15168 /*
15169  * Copies the properties & values in src to dst.  Assumes src won't change.
15170  * Returns -1 if permission is denied, -2 if another transaction interrupts,
15171  * and 0 on success.
15172  *
15173  * If enabled is 0 or 1, its value is used for the SCF_PROPERTY_ENABLED
15174  * property, if it is copied and has type boolean.  (See comment in
15175  * lscf_revert()).
15176  */
15177 static int
15178 pg_copy(const scf_propertygroup_t *src, scf_propertygroup_t *dst,
15179     uint8_t enabled)
15180 {
15181 	scf_transaction_t *tx;
15182 	scf_iter_t *iter, *viter;
15183 	scf_property_t *prop;
15184 	scf_value_t *v;
15185 	char *nbuf;
15186 	int r;
15187 
15188 	tx = scf_transaction_create(g_hndl);
15189 	if (tx == NULL)
15190 		scfdie();
15191 
15192 	if (scf_transaction_start(tx, dst) != SCF_SUCCESS) {
15193 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
15194 			scfdie();
15195 
15196 		scf_transaction_destroy(tx);
15197 
15198 		return (-1);
15199 	}
15200 
15201 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
15202 	    (prop = scf_property_create(g_hndl)) == NULL ||
15203 	    (viter = scf_iter_create(g_hndl)) == NULL)
15204 		scfdie();
15205 
15206 	nbuf = safe_malloc(max_scf_name_len + 1);
15207 
15208 	if (scf_iter_pg_properties(iter, src) != SCF_SUCCESS)
15209 		scfdie();
15210 
15211 	for (;;) {
15212 		scf_transaction_entry_t *e;
15213 		scf_type_t ty;
15214 
15215 		r = scf_iter_next_property(iter, prop);
15216 		if (r == -1)
15217 			scfdie();
15218 		if (r == 0)
15219 			break;
15220 
15221 		e = scf_entry_create(g_hndl);
15222 		if (e == NULL)
15223 			scfdie();
15224 
15225 		if (scf_property_type(prop, &ty) != SCF_SUCCESS)
15226 			scfdie();
15227 
15228 		if (scf_property_get_name(prop, nbuf, max_scf_name_len + 1) < 0)
15229 			scfdie();
15230 
15231 		if (scf_transaction_property_new(tx, e, nbuf,
15232 		    ty) != SCF_SUCCESS)
15233 			scfdie();
15234 
15235 		if ((enabled == 0 || enabled == 1) &&
15236 		    strcmp(nbuf, scf_property_enabled) == 0 &&
15237 		    ty == SCF_TYPE_BOOLEAN) {
15238 			v = scf_value_create(g_hndl);
15239 			if (v == NULL)
15240 				scfdie();
15241 
15242 			scf_value_set_boolean(v, enabled);
15243 
15244 			if (scf_entry_add_value(e, v) != 0)
15245 				scfdie();
15246 		} else {
15247 			if (scf_iter_property_values(viter, prop) != 0)
15248 				scfdie();
15249 
15250 			for (;;) {
15251 				v = scf_value_create(g_hndl);
15252 				if (v == NULL)
15253 					scfdie();
15254 
15255 				r = scf_iter_next_value(viter, v);
15256 				if (r == -1)
15257 					scfdie();
15258 				if (r == 0) {
15259 					scf_value_destroy(v);
15260 					break;
15261 				}
15262 
15263 				if (scf_entry_add_value(e, v) != SCF_SUCCESS)
15264 					scfdie();
15265 			}
15266 		}
15267 	}
15268 
15269 	free(nbuf);
15270 	scf_iter_destroy(viter);
15271 	scf_property_destroy(prop);
15272 	scf_iter_destroy(iter);
15273 
15274 	r = scf_transaction_commit(tx);
15275 	if (r == -1 && scf_error() != SCF_ERROR_PERMISSION_DENIED)
15276 		scfdie();
15277 
15278 	scf_transaction_destroy_children(tx);
15279 	scf_transaction_destroy(tx);
15280 
15281 	switch (r) {
15282 	case 1:		return (0);
15283 	case 0:		return (-2);
15284 	case -1:	return (-1);
15285 
15286 	default:
15287 		abort();
15288 	}
15289 
15290 	/* NOTREACHED */
15291 }
15292 
15293 void
15294 lscf_revert(const char *snapname)
15295 {
15296 	scf_snapshot_t *snap, *prev;
15297 	scf_snaplevel_t *level, *nlevel;
15298 	scf_iter_t *iter;
15299 	scf_propertygroup_t *pg, *npg;
15300 	scf_property_t *prop;
15301 	scf_value_t *val;
15302 	char *nbuf, *tbuf;
15303 	uint8_t enabled;
15304 
15305 	lscf_prep_hndl();
15306 
15307 	if (cur_inst == NULL) {
15308 		semerr(gettext("Instance not selected.\n"));
15309 		return;
15310 	}
15311 
15312 	if (snapname != NULL) {
15313 		snap = scf_snapshot_create(g_hndl);
15314 		if (snap == NULL)
15315 			scfdie();
15316 
15317 		if (scf_instance_get_snapshot(cur_inst, snapname, snap) !=
15318 		    SCF_SUCCESS) {
15319 			switch (scf_error()) {
15320 			case SCF_ERROR_INVALID_ARGUMENT:
15321 				semerr(gettext("Invalid snapshot name "
15322 				    "\"%s\".\n"), snapname);
15323 				break;
15324 
15325 			case SCF_ERROR_NOT_FOUND:
15326 				semerr(gettext("No such snapshot.\n"));
15327 				break;
15328 
15329 			default:
15330 				scfdie();
15331 			}
15332 
15333 			scf_snapshot_destroy(snap);
15334 			return;
15335 		}
15336 	} else {
15337 		if (cur_snap != NULL) {
15338 			snap = cur_snap;
15339 		} else {
15340 			semerr(gettext("No snapshot selected.\n"));
15341 			return;
15342 		}
15343 	}
15344 
15345 	if ((prev = scf_snapshot_create(g_hndl)) == NULL ||
15346 	    (level = scf_snaplevel_create(g_hndl)) == NULL ||
15347 	    (iter = scf_iter_create(g_hndl)) == NULL ||
15348 	    (pg = scf_pg_create(g_hndl)) == NULL ||
15349 	    (npg = scf_pg_create(g_hndl)) == NULL ||
15350 	    (prop = scf_property_create(g_hndl)) == NULL ||
15351 	    (val = scf_value_create(g_hndl)) == NULL)
15352 		scfdie();
15353 
15354 	nbuf = safe_malloc(max_scf_name_len + 1);
15355 	tbuf = safe_malloc(max_scf_pg_type_len + 1);
15356 
15357 	/* Take the "previous" snapshot before we blow away the properties. */
15358 	if (scf_instance_get_snapshot(cur_inst, snap_previous, prev) == 0) {
15359 		if (_scf_snapshot_take_attach(cur_inst, prev) != 0)
15360 			scfdie();
15361 	} else {
15362 		if (scf_error() != SCF_ERROR_NOT_FOUND)
15363 			scfdie();
15364 
15365 		if (_scf_snapshot_take_new(cur_inst, snap_previous, prev) != 0)
15366 			scfdie();
15367 	}
15368 
15369 	/* Save general/enabled, since we're probably going to replace it. */
15370 	enabled = 2;
15371 	if (scf_instance_get_pg(cur_inst, scf_pg_general, pg) == 0 &&
15372 	    scf_pg_get_property(pg, scf_property_enabled, prop) == 0 &&
15373 	    scf_property_get_value(prop, val) == 0)
15374 		(void) scf_value_get_boolean(val, &enabled);
15375 
15376 	if (scf_snapshot_get_base_snaplevel(snap, level) != SCF_SUCCESS) {
15377 		if (scf_error() != SCF_ERROR_NOT_FOUND)
15378 			scfdie();
15379 
15380 		goto out;
15381 	}
15382 
15383 	for (;;) {
15384 		boolean_t isinst;
15385 		uint32_t flags;
15386 		int r;
15387 
15388 		/* Clear the properties from the corresponding entity. */
15389 		isinst = snaplevel_is_instance(level);
15390 
15391 		if (!isinst)
15392 			r = scf_iter_service_pgs(iter, cur_svc);
15393 		else
15394 			r = scf_iter_instance_pgs(iter, cur_inst);
15395 		if (r != SCF_SUCCESS)
15396 			scfdie();
15397 
15398 		while ((r = scf_iter_next_pg(iter, pg)) == 1) {
15399 			if (scf_pg_get_flags(pg, &flags) != SCF_SUCCESS)
15400 				scfdie();
15401 
15402 			/* Skip nonpersistent pgs. */
15403 			if (flags & SCF_PG_FLAG_NONPERSISTENT)
15404 				continue;
15405 
15406 			if (scf_pg_delete(pg) != SCF_SUCCESS) {
15407 				if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
15408 					scfdie();
15409 
15410 				semerr(emsg_permission_denied);
15411 				goto out;
15412 			}
15413 		}
15414 		if (r == -1)
15415 			scfdie();
15416 
15417 		/* Copy the properties to the corresponding entity. */
15418 		if (scf_iter_snaplevel_pgs(iter, level) != SCF_SUCCESS)
15419 			scfdie();
15420 
15421 		while ((r = scf_iter_next_pg(iter, pg)) == 1) {
15422 			if (scf_pg_get_name(pg, nbuf, max_scf_name_len + 1) < 0)
15423 				scfdie();
15424 
15425 			if (scf_pg_get_type(pg, tbuf, max_scf_pg_type_len + 1) <
15426 			    0)
15427 				scfdie();
15428 
15429 			if (scf_pg_get_flags(pg, &flags) != SCF_SUCCESS)
15430 				scfdie();
15431 
15432 			if (!isinst)
15433 				r = scf_service_add_pg(cur_svc, nbuf, tbuf,
15434 				    flags, npg);
15435 			else
15436 				r = scf_instance_add_pg(cur_inst, nbuf, tbuf,
15437 				    flags, npg);
15438 			if (r != SCF_SUCCESS) {
15439 				if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
15440 					scfdie();
15441 
15442 				semerr(emsg_permission_denied);
15443 				goto out;
15444 			}
15445 
15446 			if ((enabled == 0 || enabled == 1) &&
15447 			    strcmp(nbuf, scf_pg_general) == 0)
15448 				r = pg_copy(pg, npg, enabled);
15449 			else
15450 				r = pg_copy(pg, npg, 2);
15451 
15452 			switch (r) {
15453 			case 0:
15454 				break;
15455 
15456 			case -1:
15457 				semerr(emsg_permission_denied);
15458 				goto out;
15459 
15460 			case -2:
15461 				semerr(gettext(
15462 				    "Interrupted by another change.\n"));
15463 				goto out;
15464 
15465 			default:
15466 				abort();
15467 			}
15468 		}
15469 		if (r == -1)
15470 			scfdie();
15471 
15472 		/* Get next level. */
15473 		nlevel = scf_snaplevel_create(g_hndl);
15474 		if (nlevel == NULL)
15475 			scfdie();
15476 
15477 		if (scf_snaplevel_get_next_snaplevel(level, nlevel) !=
15478 		    SCF_SUCCESS) {
15479 			if (scf_error() != SCF_ERROR_NOT_FOUND)
15480 				scfdie();
15481 
15482 			scf_snaplevel_destroy(nlevel);
15483 			break;
15484 		}
15485 
15486 		scf_snaplevel_destroy(level);
15487 		level = nlevel;
15488 	}
15489 
15490 	if (snapname == NULL) {
15491 		lscf_selectsnap(NULL);
15492 		snap = NULL;		/* cur_snap has been destroyed */
15493 	}
15494 
15495 out:
15496 	free(tbuf);
15497 	free(nbuf);
15498 	scf_value_destroy(val);
15499 	scf_property_destroy(prop);
15500 	scf_pg_destroy(npg);
15501 	scf_pg_destroy(pg);
15502 	scf_iter_destroy(iter);
15503 	scf_snaplevel_destroy(level);
15504 	scf_snapshot_destroy(prev);
15505 	if (snap != cur_snap)
15506 		scf_snapshot_destroy(snap);
15507 }
15508 
15509 void
15510 lscf_refresh(void)
15511 {
15512 	ssize_t fmrilen;
15513 	size_t bufsz;
15514 	char *fmribuf;
15515 	int r;
15516 
15517 	lscf_prep_hndl();
15518 
15519 	if (cur_inst == NULL) {
15520 		semerr(gettext("Instance not selected.\n"));
15521 		return;
15522 	}
15523 
15524 	bufsz = max_scf_fmri_len + 1;
15525 	fmribuf = safe_malloc(bufsz);
15526 	fmrilen = scf_instance_to_fmri(cur_inst, fmribuf, bufsz);
15527 	if (fmrilen < 0) {
15528 		free(fmribuf);
15529 		if (scf_error() != SCF_ERROR_DELETED)
15530 			scfdie();
15531 		scf_instance_destroy(cur_inst);
15532 		cur_inst = NULL;
15533 		warn(emsg_deleted);
15534 		return;
15535 	}
15536 	assert(fmrilen < bufsz);
15537 
15538 	r = refresh_entity(0, cur_inst, fmribuf, NULL, NULL, NULL);
15539 	switch (r) {
15540 	case 0:
15541 		break;
15542 
15543 	case ECONNABORTED:
15544 		warn(gettext("Could not refresh %s "
15545 		    "(repository connection broken).\n"), fmribuf);
15546 		break;
15547 
15548 	case ECANCELED:
15549 		warn(emsg_deleted);
15550 		break;
15551 
15552 	case EPERM:
15553 		warn(gettext("Could not refresh %s "
15554 		    "(permission denied).\n"), fmribuf);
15555 		break;
15556 
15557 	case ENOSPC:
15558 		warn(gettext("Could not refresh %s "
15559 		    "(repository server out of resources).\n"),
15560 		    fmribuf);
15561 		break;
15562 
15563 	case EACCES:
15564 	default:
15565 		bad_error("refresh_entity", scf_error());
15566 	}
15567 
15568 	free(fmribuf);
15569 }
15570 
15571 /*
15572  * describe [-v] [-t] [pg/prop]
15573  */
15574 int
15575 lscf_describe(uu_list_t *args, int hasargs)
15576 {
15577 	int ret = 0;
15578 	size_t i;
15579 	int argc;
15580 	char **argv = NULL;
15581 	string_list_t *slp;
15582 	int do_verbose = 0;
15583 	int do_templates = 0;
15584 	char *pattern = NULL;
15585 
15586 	lscf_prep_hndl();
15587 
15588 	if (hasargs != 0)  {
15589 		argc = uu_list_numnodes(args);
15590 		if (argc < 1)
15591 			goto usage;
15592 
15593 		argv = calloc(argc + 1, sizeof (char *));
15594 		if (argv == NULL)
15595 			uu_die(gettext("Out of memory.\n"));
15596 
15597 		for (slp = uu_list_first(args), i = 0;
15598 		    slp != NULL;
15599 		    slp = uu_list_next(args, slp), ++i)
15600 			argv[i] = slp->str;
15601 
15602 		argv[i] = NULL;
15603 
15604 		/*
15605 		 * We start optind = 0 because our list of arguments
15606 		 * starts at argv[0]
15607 		 */
15608 		optind = 0;
15609 		opterr = 0;
15610 		for (;;) {
15611 			ret = getopt(argc, argv, "vt");
15612 			if (ret == -1)
15613 				break;
15614 
15615 			switch (ret) {
15616 			case 'v':
15617 				do_verbose = 1;
15618 				break;
15619 
15620 			case 't':
15621 				do_templates = 1;
15622 				break;
15623 
15624 			case '?':
15625 				goto usage;
15626 
15627 			default:
15628 				bad_error("getopt", ret);
15629 			}
15630 		}
15631 
15632 		pattern = argv[optind];
15633 	}
15634 
15635 	if (cur_inst == NULL && cur_svc == NULL) {
15636 		semerr(emsg_entity_not_selected);
15637 		ret = -1;
15638 		goto out;
15639 	}
15640 
15641 	/*
15642 	 * list_entity_tmpl(), listprop() and listtmpl() produce verbose
15643 	 * output if their last parameter is set to 2.  Less information is
15644 	 * produced if the parameter is set to 1.
15645 	 */
15646 	if (pattern == NULL) {
15647 		if (do_verbose == 1)
15648 			list_entity_tmpl(2);
15649 		else
15650 			list_entity_tmpl(1);
15651 	}
15652 
15653 	if (do_templates == 0) {
15654 		if (do_verbose == 1)
15655 			listprop(pattern, 0, 2);
15656 		else
15657 			listprop(pattern, 0, 1);
15658 	} else {
15659 		if (do_verbose == 1)
15660 			listtmpl(pattern, 2);
15661 		else
15662 			listtmpl(pattern, 1);
15663 	}
15664 
15665 	ret = 0;
15666 out:
15667 	if (argv != NULL)
15668 		free(argv);
15669 	return (ret);
15670 usage:
15671 	ret = -2;
15672 	goto out;
15673 }
15674 
15675 #define	PARAM_ACTIVE	((const char *) "active")
15676 #define	PARAM_INACTIVE	((const char *) "inactive")
15677 #define	PARAM_SMTP_TO	((const char *) "to")
15678 
15679 /*
15680  * tokenize()
15681  * Breaks down the string according to the tokens passed.
15682  * Caller is responsible for freeing array of pointers returned.
15683  * Returns NULL on failure
15684  */
15685 char **
15686 tokenize(char *str, const char *sep)
15687 {
15688 	char *token, *lasts;
15689 	char **buf;
15690 	int n = 0;	/* number of elements */
15691 	int size = 8;	/* size of the array (initial) */
15692 
15693 	buf = safe_malloc(size * sizeof (char *));
15694 
15695 	for (token = strtok_r(str, sep, &lasts); token != NULL;
15696 	    token = strtok_r(NULL, sep, &lasts), ++n) {
15697 		if (n + 1 >= size) {
15698 			size *= 2;
15699 			if ((buf = realloc(buf, size * sizeof (char *))) ==
15700 			    NULL) {
15701 				uu_die(gettext("Out of memory"));
15702 			}
15703 		}
15704 		buf[n] = token;
15705 	}
15706 	/* NULL terminate the pointer array */
15707 	buf[n] = NULL;
15708 
15709 	return (buf);
15710 }
15711 
15712 int32_t
15713 check_tokens(char **p)
15714 {
15715 	int32_t smf = 0;
15716 	int32_t fma = 0;
15717 
15718 	while (*p) {
15719 		int32_t t = string_to_tset(*p);
15720 
15721 		if (t == 0) {
15722 			if (is_fma_token(*p) == 0)
15723 				return (INVALID_TOKENS);
15724 			fma = 1; /* this token is an fma event */
15725 		} else {
15726 			smf |= t;
15727 		}
15728 
15729 		if (smf != 0 && fma == 1)
15730 			return (MIXED_TOKENS);
15731 		++p;
15732 	}
15733 
15734 	if (smf > 0)
15735 		return (smf);
15736 	else if (fma == 1)
15737 		return (FMA_TOKENS);
15738 
15739 	return (INVALID_TOKENS);
15740 }
15741 
15742 static int
15743 get_selection_str(char *fmri, size_t sz)
15744 {
15745 	if (g_hndl == NULL) {
15746 		semerr(emsg_entity_not_selected);
15747 		return (-1);
15748 	} else if (cur_level != NULL) {
15749 		semerr(emsg_invalid_for_snapshot);
15750 		return (-1);
15751 	} else {
15752 		lscf_get_selection_str(fmri, sz);
15753 	}
15754 
15755 	return (0);
15756 }
15757 
15758 void
15759 lscf_delnotify(const char *set, int global)
15760 {
15761 	char *str = strdup(set);
15762 	char **pgs;
15763 	char **p;
15764 	int32_t tset;
15765 	char *fmri = NULL;
15766 
15767 	if (str == NULL)
15768 		uu_die(gettext("Out of memory.\n"));
15769 
15770 	pgs = tokenize(str, ",");
15771 
15772 	if ((tset = check_tokens(pgs)) > 0) {
15773 		size_t sz = max_scf_fmri_len + 1;
15774 
15775 		fmri = safe_malloc(sz);
15776 		if (global) {
15777 			(void) strlcpy(fmri, SCF_INSTANCE_GLOBAL, sz);
15778 		} else if (get_selection_str(fmri, sz) != 0) {
15779 			goto out;
15780 		}
15781 
15782 		if (smf_notify_del_params(SCF_SVC_TRANSITION_CLASS, fmri,
15783 		    tset) != SCF_SUCCESS) {
15784 			uu_warn(gettext("Failed smf_notify_del_params: %s\n"),
15785 			    scf_strerror(scf_error()));
15786 		}
15787 	} else if (tset == FMA_TOKENS) {
15788 		if (global) {
15789 			semerr(gettext("Can't use option '-g' with FMA event "
15790 			    "definitions\n"));
15791 			goto out;
15792 		}
15793 
15794 		for (p = pgs; *p; ++p) {
15795 			if (smf_notify_del_params(de_tag(*p), NULL, 0) !=
15796 			    SCF_SUCCESS) {
15797 				uu_warn(gettext("Failed for \"%s\": %s\n"), *p,
15798 				    scf_strerror(scf_error()));
15799 				goto out;
15800 			}
15801 		}
15802 	} else if (tset == MIXED_TOKENS) {
15803 		semerr(gettext("Can't mix SMF and FMA event definitions\n"));
15804 		goto out;
15805 	} else {
15806 		uu_die(gettext("Invalid input.\n"));
15807 	}
15808 
15809 out:
15810 	free(fmri);
15811 	free(pgs);
15812 	free(str);
15813 }
15814 
15815 void
15816 lscf_listnotify(const char *set, int global)
15817 {
15818 	char *str = safe_strdup(set);
15819 	char **pgs;
15820 	char **p;
15821 	int32_t tset;
15822 	nvlist_t *nvl;
15823 	char *fmri = NULL;
15824 
15825 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
15826 		uu_die(gettext("Out of memory.\n"));
15827 
15828 	pgs = tokenize(str, ",");
15829 
15830 	if ((tset = check_tokens(pgs)) > 0) {
15831 		size_t sz = max_scf_fmri_len + 1;
15832 
15833 		fmri = safe_malloc(sz);
15834 		if (global) {
15835 			(void) strlcpy(fmri, SCF_INSTANCE_GLOBAL, sz);
15836 		} else if (get_selection_str(fmri, sz) != 0) {
15837 			goto out;
15838 		}
15839 
15840 		if (_scf_get_svc_notify_params(fmri, nvl, tset, 1, 1) !=
15841 		    SCF_SUCCESS) {
15842 			if (scf_error() != SCF_ERROR_NOT_FOUND &&
15843 			    scf_error() != SCF_ERROR_DELETED)
15844 				uu_warn(gettext(
15845 				    "Failed listnotify: %s\n"),
15846 				    scf_strerror(scf_error()));
15847 			goto out;
15848 		}
15849 
15850 		listnotify_print(nvl, NULL);
15851 	} else if (tset == FMA_TOKENS) {
15852 		if (global) {
15853 			semerr(gettext("Can't use option '-g' with FMA event "
15854 			    "definitions\n"));
15855 			goto out;
15856 		}
15857 
15858 		for (p = pgs; *p; ++p) {
15859 			if (_scf_get_fma_notify_params(de_tag(*p), nvl, 1) !=
15860 			    SCF_SUCCESS) {
15861 				/*
15862 				 * if the preferences have just been deleted
15863 				 * or does not exist, just skip.
15864 				 */
15865 				if (scf_error() == SCF_ERROR_NOT_FOUND ||
15866 				    scf_error() == SCF_ERROR_DELETED)
15867 					continue;
15868 				uu_warn(gettext(
15869 				    "Failed listnotify: %s\n"),
15870 				    scf_strerror(scf_error()));
15871 				goto out;
15872 			}
15873 			listnotify_print(nvl, re_tag(*p));
15874 		}
15875 	} else if (tset == MIXED_TOKENS) {
15876 		semerr(gettext("Can't mix SMF and FMA event definitions\n"));
15877 		goto out;
15878 	} else {
15879 		semerr(gettext("Invalid input.\n"));
15880 	}
15881 
15882 out:
15883 	nvlist_free(nvl);
15884 	free(fmri);
15885 	free(pgs);
15886 	free(str);
15887 }
15888 
15889 static char *
15890 strip_quotes_and_blanks(char *s)
15891 {
15892 	char *start = s;
15893 	char *end = strrchr(s, '\"');
15894 
15895 	if (s[0] == '\"' && end != NULL && *(end + 1) == '\0') {
15896 		start = s + 1;
15897 		while (isblank(*start))
15898 			start++;
15899 		while (isblank(*(end - 1)) && end > start) {
15900 			end--;
15901 		}
15902 		*end = '\0';
15903 	}
15904 
15905 	return (start);
15906 }
15907 
15908 static int
15909 set_active(nvlist_t *mech, const char *hier_part)
15910 {
15911 	boolean_t b;
15912 
15913 	if (*hier_part == '\0' || strcmp(hier_part, PARAM_ACTIVE) == 0) {
15914 		b = B_TRUE;
15915 	} else if (strcmp(hier_part, PARAM_INACTIVE) == 0) {
15916 		b = B_FALSE;
15917 	} else {
15918 		return (-1);
15919 	}
15920 
15921 	if (nvlist_add_boolean_value(mech, PARAM_ACTIVE, b) != 0)
15922 		uu_die(gettext("Out of memory.\n"));
15923 
15924 	return (0);
15925 }
15926 
15927 static int
15928 add_snmp_params(nvlist_t *mech, char *hier_part)
15929 {
15930 	return (set_active(mech, hier_part));
15931 }
15932 
15933 static int
15934 add_syslog_params(nvlist_t *mech, char *hier_part)
15935 {
15936 	return (set_active(mech, hier_part));
15937 }
15938 
15939 /*
15940  * add_mailto_paramas()
15941  * parse the hier_part of mailto URI
15942  * mailto:<addr>[?<header1>=<value1>[&<header2>=<value2>]]
15943  * or mailto:{[active]|inactive}
15944  */
15945 static int
15946 add_mailto_params(nvlist_t *mech, char *hier_part)
15947 {
15948 	const char *tok = "?&";
15949 	char *p;
15950 	char *lasts;
15951 	char *param;
15952 	char *val;
15953 
15954 	/*
15955 	 * If the notification parametes are in the form of
15956 	 *
15957 	 *   malito:{[active]|inactive}
15958 	 *
15959 	 * we set the property accordingly and return.
15960 	 * Otherwise, we make the notification type active and
15961 	 * process the hier_part.
15962 	 */
15963 	if (set_active(mech, hier_part) == 0)
15964 		return (0);
15965 	else if (set_active(mech, PARAM_ACTIVE) != 0)
15966 		return (-1);
15967 
15968 	if ((p = strtok_r(hier_part, tok, &lasts)) == NULL) {
15969 		/*
15970 		 * sanity check: we only get here if hier_part = "", but
15971 		 * that's handled by set_active
15972 		 */
15973 		uu_die("strtok_r");
15974 	}
15975 
15976 	if (nvlist_add_string(mech, PARAM_SMTP_TO, p) != 0)
15977 		uu_die(gettext("Out of memory.\n"));
15978 
15979 	while ((p = strtok_r(NULL, tok, &lasts)) != NULL)
15980 		if ((param = strtok_r(p, "=", &val)) != NULL)
15981 			if (nvlist_add_string(mech, param, val) != 0)
15982 				uu_die(gettext("Out of memory.\n"));
15983 
15984 	return (0);
15985 }
15986 
15987 static int
15988 uri_split(char *uri, char **scheme, char **hier_part)
15989 {
15990 	int r = -1;
15991 
15992 	if ((*scheme = strtok_r(uri, ":", hier_part)) == NULL ||
15993 	    *hier_part == NULL) {
15994 		semerr(gettext("'%s' is not an URI\n"), uri);
15995 		return (r);
15996 	}
15997 
15998 	if ((r = check_uri_scheme(*scheme)) < 0) {
15999 		semerr(gettext("Unkown URI scheme: %s\n"), *scheme);
16000 		return (r);
16001 	}
16002 
16003 	return (r);
16004 }
16005 
16006 static int
16007 process_uri(nvlist_t *params, char *uri)
16008 {
16009 	char *scheme;
16010 	char *hier_part;
16011 	nvlist_t *mech;
16012 	int index;
16013 	int r;
16014 
16015 	if ((index = uri_split(uri, &scheme, &hier_part)) < 0)
16016 		return (-1);
16017 
16018 	if (nvlist_alloc(&mech, NV_UNIQUE_NAME, 0) != 0)
16019 		uu_die(gettext("Out of memory.\n"));
16020 
16021 	switch (index) {
16022 	case 0:
16023 		/* error messages displayed by called function */
16024 		r = add_mailto_params(mech, hier_part);
16025 		break;
16026 
16027 	case 1:
16028 		if ((r = add_snmp_params(mech, hier_part)) != 0)
16029 			semerr(gettext("Not valid parameters: '%s'\n"),
16030 			    hier_part);
16031 		break;
16032 
16033 	case 2:
16034 		if ((r = add_syslog_params(mech, hier_part)) != 0)
16035 			semerr(gettext("Not valid parameters: '%s'\n"),
16036 			    hier_part);
16037 		break;
16038 
16039 	default:
16040 		r = -1;
16041 	}
16042 
16043 	if (r == 0 && nvlist_add_nvlist(params, uri_scheme[index].protocol,
16044 	    mech) != 0)
16045 		uu_die(gettext("Out of memory.\n"));
16046 
16047 	nvlist_free(mech);
16048 	return (r);
16049 }
16050 
16051 static int
16052 set_params(nvlist_t *params, char **p)
16053 {
16054 	char *uri;
16055 
16056 	if (p == NULL)
16057 		/* sanity check */
16058 		uu_die("set_params");
16059 
16060 	while (*p) {
16061 		uri = strip_quotes_and_blanks(*p);
16062 		if (process_uri(params, uri) != 0)
16063 			return (-1);
16064 
16065 		++p;
16066 	}
16067 
16068 	return (0);
16069 }
16070 
16071 static int
16072 setnotify(const char *e, char **p, int global)
16073 {
16074 	char *str = safe_strdup(e);
16075 	char **events;
16076 	int32_t tset;
16077 	int r = -1;
16078 	nvlist_t *nvl, *params;
16079 	char *fmri = NULL;
16080 
16081 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
16082 	    nvlist_alloc(&params, NV_UNIQUE_NAME, 0) != 0 ||
16083 	    nvlist_add_uint32(nvl, SCF_NOTIFY_NAME_VERSION,
16084 	    SCF_NOTIFY_PARAMS_VERSION) != 0)
16085 		uu_die(gettext("Out of memory.\n"));
16086 
16087 	events = tokenize(str, ",");
16088 
16089 	if ((tset = check_tokens(events)) > 0) {
16090 		/* SMF state transitions parameters */
16091 		size_t sz = max_scf_fmri_len + 1;
16092 
16093 		fmri = safe_malloc(sz);
16094 		if (global) {
16095 			(void) strlcpy(fmri, SCF_INSTANCE_GLOBAL, sz);
16096 		} else if (get_selection_str(fmri, sz) != 0) {
16097 			goto out;
16098 		}
16099 
16100 		if (nvlist_add_string(nvl, SCF_NOTIFY_NAME_FMRI, fmri) != 0 ||
16101 		    nvlist_add_int32(nvl, SCF_NOTIFY_NAME_TSET, tset) != 0)
16102 			uu_die(gettext("Out of memory.\n"));
16103 
16104 		if ((r = set_params(params, p)) == 0) {
16105 			if (nvlist_add_nvlist(nvl, SCF_NOTIFY_PARAMS,
16106 			    params) != 0)
16107 				uu_die(gettext("Out of memory.\n"));
16108 
16109 			if (smf_notify_set_params(SCF_SVC_TRANSITION_CLASS,
16110 			    nvl) != SCF_SUCCESS) {
16111 				r = -1;
16112 				uu_warn(gettext(
16113 				    "Failed smf_notify_set_params(3SCF): %s\n"),
16114 				    scf_strerror(scf_error()));
16115 			}
16116 		}
16117 	} else if (tset == FMA_TOKENS) {
16118 		/* FMA event parameters */
16119 		if (global) {
16120 			semerr(gettext("Can't use option '-g' with FMA event "
16121 			    "definitions\n"));
16122 			goto out;
16123 		}
16124 
16125 		if ((r = set_params(params, p)) != 0)
16126 			goto out;
16127 
16128 		if (nvlist_add_nvlist(nvl, SCF_NOTIFY_PARAMS, params) != 0)
16129 			uu_die(gettext("Out of memory.\n"));
16130 
16131 		while (*events) {
16132 			if (smf_notify_set_params(de_tag(*events), nvl) !=
16133 			    SCF_SUCCESS)
16134 				uu_warn(gettext(
16135 				    "Failed smf_notify_set_params(3SCF) for "
16136 				    "event %s: %s\n"), *events,
16137 				    scf_strerror(scf_error()));
16138 			events++;
16139 		}
16140 	} else if (tset == MIXED_TOKENS) {
16141 		semerr(gettext("Can't mix SMF and FMA event definitions\n"));
16142 	} else {
16143 		/* Sanity check */
16144 		uu_die(gettext("Invalid input.\n"));
16145 	}
16146 
16147 out:
16148 	nvlist_free(nvl);
16149 	nvlist_free(params);
16150 	free(fmri);
16151 	free(str);
16152 
16153 	return (r);
16154 }
16155 
16156 int
16157 lscf_setnotify(uu_list_t *args)
16158 {
16159 	int argc;
16160 	char **argv = NULL;
16161 	string_list_t *slp;
16162 	int global;
16163 	char *events;
16164 	char **p;
16165 	int i;
16166 	int ret;
16167 
16168 	if ((argc = uu_list_numnodes(args)) < 2)
16169 		goto usage;
16170 
16171 	argv = calloc(argc + 1, sizeof (char *));
16172 	if (argv == NULL)
16173 		uu_die(gettext("Out of memory.\n"));
16174 
16175 	for (slp = uu_list_first(args), i = 0;
16176 	    slp != NULL;
16177 	    slp = uu_list_next(args, slp), ++i)
16178 		argv[i] = slp->str;
16179 
16180 	argv[i] = NULL;
16181 
16182 	if (strcmp(argv[0], "-g") == 0) {
16183 		global = 1;
16184 		events = argv[1];
16185 		p = argv + 2;
16186 	} else {
16187 		global = 0;
16188 		events = argv[0];
16189 		p = argv + 1;
16190 	}
16191 
16192 	ret = setnotify(events, p, global);
16193 
16194 out:
16195 	free(argv);
16196 	return (ret);
16197 
16198 usage:
16199 	ret = -2;
16200 	goto out;
16201 }
16202 
16203 /*
16204  * Creates a list of instance name strings associated with a service. If
16205  * wohandcrafted flag is set, get only instances that have a last-import
16206  * snapshot, instances that were imported via svccfg.
16207  */
16208 static uu_list_t *
16209 create_instance_list(scf_service_t *svc, int wohandcrafted)
16210 {
16211 	scf_snapshot_t  *snap = NULL;
16212 	scf_instance_t  *inst;
16213 	scf_iter_t	*inst_iter;
16214 	uu_list_t	*instances;
16215 	char		*instname;
16216 	int		r;
16217 
16218 	inst_iter = scf_iter_create(g_hndl);
16219 	inst = scf_instance_create(g_hndl);
16220 	if (inst_iter == NULL || inst == NULL) {
16221 		uu_warn(gettext("Could not create instance or iterator\n"));
16222 		scfdie();
16223 	}
16224 
16225 	if ((instances = uu_list_create(string_pool, NULL, 0)) == NULL)
16226 		return (instances);
16227 
16228 	if (scf_iter_service_instances(inst_iter, svc) != 0) {
16229 		switch (scf_error()) {
16230 		case SCF_ERROR_CONNECTION_BROKEN:
16231 		case SCF_ERROR_DELETED:
16232 			uu_list_destroy(instances);
16233 			instances = NULL;
16234 			goto out;
16235 
16236 		case SCF_ERROR_HANDLE_MISMATCH:
16237 		case SCF_ERROR_NOT_BOUND:
16238 		case SCF_ERROR_NOT_SET:
16239 		default:
16240 			bad_error("scf_iter_service_instances", scf_error());
16241 		}
16242 	}
16243 
16244 	instname = safe_malloc(max_scf_name_len + 1);
16245 	while ((r = scf_iter_next_instance(inst_iter, inst)) != 0) {
16246 		if (r == -1) {
16247 			(void) uu_warn(gettext("Unable to iterate through "
16248 			    "instances to create instance list : %s\n"),
16249 			    scf_strerror(scf_error()));
16250 
16251 			uu_list_destroy(instances);
16252 			instances = NULL;
16253 			goto out;
16254 		}
16255 
16256 		/*
16257 		 * If the instance does not have a last-import snapshot
16258 		 * then do not add it to the list as it is a hand-crafted
16259 		 * instance that should not be managed.
16260 		 */
16261 		if (wohandcrafted) {
16262 			if (snap == NULL &&
16263 			    (snap = scf_snapshot_create(g_hndl)) == NULL) {
16264 				uu_warn(gettext("Unable to create snapshot "
16265 				    "entity\n"));
16266 				scfdie();
16267 			}
16268 
16269 			if (scf_instance_get_snapshot(inst,
16270 			    snap_lastimport, snap) != 0) {
16271 				switch (scf_error()) {
16272 				case SCF_ERROR_NOT_FOUND :
16273 				case SCF_ERROR_DELETED:
16274 					continue;
16275 
16276 				case SCF_ERROR_CONNECTION_BROKEN:
16277 					uu_list_destroy(instances);
16278 					instances = NULL;
16279 					goto out;
16280 
16281 				case SCF_ERROR_HANDLE_MISMATCH:
16282 				case SCF_ERROR_NOT_BOUND:
16283 				case SCF_ERROR_NOT_SET:
16284 				default:
16285 					bad_error("scf_iter_service_instances",
16286 					    scf_error());
16287 				}
16288 			}
16289 		}
16290 
16291 		if (scf_instance_get_name(inst, instname,
16292 		    max_scf_name_len + 1) < 0) {
16293 			switch (scf_error()) {
16294 			case SCF_ERROR_NOT_FOUND :
16295 				continue;
16296 
16297 			case SCF_ERROR_CONNECTION_BROKEN:
16298 			case SCF_ERROR_DELETED:
16299 				uu_list_destroy(instances);
16300 				instances = NULL;
16301 				goto out;
16302 
16303 			case SCF_ERROR_HANDLE_MISMATCH:
16304 			case SCF_ERROR_NOT_BOUND:
16305 			case SCF_ERROR_NOT_SET:
16306 			default:
16307 				bad_error("scf_iter_service_instances",
16308 				    scf_error());
16309 			}
16310 		}
16311 
16312 		add_string(instances, instname);
16313 	}
16314 
16315 out:
16316 	if (snap)
16317 		scf_snapshot_destroy(snap);
16318 
16319 	scf_instance_destroy(inst);
16320 	scf_iter_destroy(inst_iter);
16321 	free(instname);
16322 	return (instances);
16323 }
16324 
16325 /*
16326  * disable an instance but wait for the instance to
16327  * move out of the running state.
16328  *
16329  * Returns 0 : if the instance did not disable
16330  * Returns non-zero : if the instance disabled.
16331  *
16332  */
16333 static int
16334 disable_instance(scf_instance_t *instance)
16335 {
16336 	char	*fmribuf;
16337 	int	enabled = 10000;
16338 
16339 	if (inst_is_running(instance)) {
16340 		fmribuf = safe_malloc(max_scf_name_len + 1);
16341 		if (scf_instance_to_fmri(instance, fmribuf,
16342 		    max_scf_name_len + 1) < 0) {
16343 			free(fmribuf);
16344 			return (0);
16345 		}
16346 
16347 		/*
16348 		 * If the instance cannot be disabled then return
16349 		 * failure to disable and let the caller decide
16350 		 * if that is of importance.
16351 		 */
16352 		if (smf_disable_instance(fmribuf, 0) != 0) {
16353 			free(fmribuf);
16354 			return (0);
16355 		}
16356 
16357 		while (enabled) {
16358 			if (!inst_is_running(instance))
16359 				break;
16360 
16361 			(void) poll(NULL, 0, 5);
16362 			enabled = enabled - 5;
16363 		}
16364 
16365 		free(fmribuf);
16366 	}
16367 
16368 	return (enabled);
16369 }
16370 
16371 /*
16372  * Function to compare two service_manifest structures.
16373  */
16374 /* ARGSUSED2 */
16375 static int
16376 service_manifest_compare(const void *left, const void *right, void *unused)
16377 {
16378 	service_manifest_t *l = (service_manifest_t *)left;
16379 	service_manifest_t *r = (service_manifest_t *)right;
16380 	int rc;
16381 
16382 	rc = strcmp(l->servicename, r->servicename);
16383 
16384 	return (rc);
16385 }
16386 
16387 /*
16388  * Look for the provided service in the service to manifest
16389  * tree.  If the service exists, and a manifest was provided
16390  * then add the manifest to that service.  If the service
16391  * does not exist, then add the service and manifest to the
16392  * list.
16393  *
16394  * If the manifest is NULL, return the element if found.  If
16395  * the service is not found return NULL.
16396  */
16397 service_manifest_t *
16398 find_add_svc_mfst(const char *svnbuf, const char *mfst)
16399 {
16400 	service_manifest_t	elem;
16401 	service_manifest_t	*fnelem;
16402 	uu_avl_index_t		marker;
16403 
16404 	elem.servicename = svnbuf;
16405 	fnelem = uu_avl_find(service_manifest_tree, &elem, NULL, &marker);
16406 
16407 	if (mfst) {
16408 		if (fnelem) {
16409 			add_string(fnelem->mfstlist, strdup(mfst));
16410 		} else {
16411 			fnelem = safe_malloc(sizeof (*fnelem));
16412 			fnelem->servicename = safe_strdup(svnbuf);
16413 			if ((fnelem->mfstlist =
16414 			    uu_list_create(string_pool, NULL, 0)) == NULL)
16415 				uu_die(gettext("Could not create property "
16416 				    "list: %s\n"), uu_strerror(uu_error()));
16417 
16418 			add_string(fnelem->mfstlist, safe_strdup(mfst));
16419 
16420 			uu_avl_insert(service_manifest_tree, fnelem, marker);
16421 		}
16422 	}
16423 
16424 	return (fnelem);
16425 }
16426 
16427 /*
16428  * Create the service to manifest avl tree.
16429  *
16430  * Walk each of the manifests currently installed in the supported
16431  * directories, /lib/svc/manifests and /var/svc/manifests.  For
16432  * each of the manifests, inventory the services and add them to
16433  * the tree.
16434  *
16435  * Code that calls this function should make sure fileystem/minimal is online,
16436  * /var is available, since this function walks the /var/svc/manifest directory.
16437  */
16438 static void
16439 create_manifest_tree(void)
16440 {
16441 	manifest_info_t **entry;
16442 	manifest_info_t **manifests;
16443 	uu_list_walk_t	*svcs;
16444 	bundle_t	*b;
16445 	entity_t	*mfsvc;
16446 	char		*dirs[] = {LIBSVC_DIR, VARSVC_DIR, NULL};
16447 	int		c, status;
16448 
16449 	if (service_manifest_pool)
16450 		return;
16451 
16452 	/*
16453 	 * Create the list pool for the service manifest list
16454 	 */
16455 	service_manifest_pool = uu_avl_pool_create("service_manifest",
16456 	    sizeof (service_manifest_t),
16457 	    offsetof(service_manifest_t, svcmfst_node),
16458 	    service_manifest_compare, UU_DEFAULT);
16459 	if (service_manifest_pool == NULL)
16460 		uu_die(gettext("service_manifest pool creation failed: %s\n"),
16461 		    uu_strerror(uu_error()));
16462 
16463 	/*
16464 	 * Create the list
16465 	 */
16466 	service_manifest_tree = uu_avl_create(service_manifest_pool, NULL,
16467 	    UU_DEFAULT);
16468 	if (service_manifest_tree == NULL)
16469 		uu_die(gettext("service_manifest tree creation failed: %s\n"),
16470 		    uu_strerror(uu_error()));
16471 
16472 	/*
16473 	 * Walk the manifests adding the service(s) from each manifest.
16474 	 *
16475 	 * If a service already exists add the manifest to the manifest
16476 	 * list for that service.  This covers the case of a service that
16477 	 * is supported by multiple manifest files.
16478 	 */
16479 	for (c = 0; dirs[c]; c++) {
16480 		status = find_manifests(g_hndl, dirs[c], &manifests, CHECKEXT);
16481 		if (status < 0) {
16482 			uu_warn(gettext("file tree walk of %s encountered "
16483 			    "error %s\n"), dirs[c], strerror(errno));
16484 
16485 			uu_avl_destroy(service_manifest_tree);
16486 			service_manifest_tree = NULL;
16487 			return;
16488 		}
16489 
16490 		/*
16491 		 * If a manifest that was in the list is not found
16492 		 * then skip and go to the next manifest file.
16493 		 */
16494 		if (manifests != NULL) {
16495 			for (entry = manifests; *entry != NULL; entry++) {
16496 				b = internal_bundle_new();
16497 				if (lxml_get_bundle_file(b, (*entry)->mi_path,
16498 				    SVCCFG_OP_IMPORT) != 0) {
16499 					internal_bundle_free(b);
16500 					continue;
16501 				}
16502 
16503 				svcs = uu_list_walk_start(b->sc_bundle_services,
16504 				    0);
16505 				if (svcs == NULL) {
16506 					internal_bundle_free(b);
16507 					continue;
16508 				}
16509 
16510 				while ((mfsvc = uu_list_walk_next(svcs)) !=
16511 				    NULL) {
16512 					/* Add manifest to service */
16513 					(void) find_add_svc_mfst(mfsvc->sc_name,
16514 					    (*entry)->mi_path);
16515 				}
16516 
16517 				uu_list_walk_end(svcs);
16518 				internal_bundle_free(b);
16519 			}
16520 
16521 			free_manifest_array(manifests);
16522 		}
16523 	}
16524 }
16525 
16526 /*
16527  * Check the manifest history file to see
16528  * if the service was ever installed from
16529  * one of the supported directories.
16530  *
16531  * Return Values :
16532  * 	-1 - if there's error reading manifest history file
16533  *	 1 - if the service is not found
16534  *	 0 - if the service is found
16535  */
16536 static int
16537 check_mfst_history(const char *svcname)
16538 {
16539 	struct stat	st;
16540 	caddr_t		mfsthist_start;
16541 	char		*svnbuf;
16542 	int		fd;
16543 	int		r = 1;
16544 
16545 	fd = open(MFSTHISTFILE, O_RDONLY);
16546 	if (fd == -1) {
16547 		uu_warn(gettext("Unable to open the history file\n"));
16548 		return (-1);
16549 	}
16550 
16551 	if (fstat(fd, &st) == -1) {
16552 		uu_warn(gettext("Unable to stat the history file\n"));
16553 		return (-1);
16554 	}
16555 
16556 	mfsthist_start = mmap(0, st.st_size, PROT_READ,
16557 	    MAP_PRIVATE, fd, 0);
16558 
16559 	(void) close(fd);
16560 	if (mfsthist_start == MAP_FAILED ||
16561 	    *(mfsthist_start + st.st_size) != '\0') {
16562 		(void) munmap(mfsthist_start, st.st_size);
16563 		return (-1);
16564 	}
16565 
16566 	/*
16567 	 * The manifest history file is a space delimited list
16568 	 * of service and instance to manifest linkage.  Adding
16569 	 * a space to the end of the service name so to get only
16570 	 * the service that is being searched for.
16571 	 */
16572 	svnbuf = uu_msprintf("%s ", svcname);
16573 	if (svnbuf == NULL)
16574 		uu_die(gettext("Out of memory"));
16575 
16576 	if (strstr(mfsthist_start, svnbuf) != NULL)
16577 		r = 0;
16578 
16579 	(void) munmap(mfsthist_start, st.st_size);
16580 	uu_free(svnbuf);
16581 	return (r);
16582 }
16583 
16584 /*
16585  * Take down each of the instances in the service
16586  * and remove them, then delete the service.
16587  */
16588 static void
16589 teardown_service(scf_service_t *svc, const char *svnbuf)
16590 {
16591 	scf_instance_t	*instance;
16592 	scf_iter_t	*iter;
16593 	int		r;
16594 
16595 	safe_printf(gettext("Delete service %s as there are no "
16596 	    "supporting manifests\n"), svnbuf);
16597 
16598 	instance = scf_instance_create(g_hndl);
16599 	iter = scf_iter_create(g_hndl);
16600 	if (iter == NULL || instance == NULL) {
16601 		uu_warn(gettext("Unable to create supporting entities to "
16602 		    "teardown the service\n"));
16603 		uu_warn(gettext("scf error is : %s\n"),
16604 		    scf_strerror(scf_error()));
16605 		scfdie();
16606 	}
16607 
16608 	if (scf_iter_service_instances(iter, svc) != 0) {
16609 		switch (scf_error()) {
16610 		case SCF_ERROR_CONNECTION_BROKEN:
16611 		case SCF_ERROR_DELETED:
16612 			goto out;
16613 
16614 		case SCF_ERROR_HANDLE_MISMATCH:
16615 		case SCF_ERROR_NOT_BOUND:
16616 		case SCF_ERROR_NOT_SET:
16617 		default:
16618 			bad_error("scf_iter_service_instances",
16619 			    scf_error());
16620 		}
16621 	}
16622 
16623 	while ((r = scf_iter_next_instance(iter, instance)) != 0) {
16624 		if (r == -1) {
16625 			uu_warn(gettext("Error - %s\n"),
16626 			    scf_strerror(scf_error()));
16627 			goto out;
16628 		}
16629 
16630 		(void) disable_instance(instance);
16631 	}
16632 
16633 	/*
16634 	 * Delete the service... forcing the deletion in case
16635 	 * any of the instances did not disable.
16636 	 */
16637 	(void) lscf_service_delete(svc, 1);
16638 out:
16639 	scf_instance_destroy(instance);
16640 	scf_iter_destroy(iter);
16641 }
16642 
16643 /*
16644  * Get the list of instances supported by the manifest
16645  * file.
16646  *
16647  * Return 0 if there are no instances.
16648  *
16649  * Return -1 if there are errors attempting to collect instances.
16650  *
16651  * Return the count of instances found if there are no errors.
16652  *
16653  */
16654 static int
16655 check_instance_support(char *mfstfile, const char *svcname,
16656     uu_list_t *instances)
16657 {
16658 	uu_list_walk_t	*svcs, *insts;
16659 	uu_list_t	*ilist;
16660 	bundle_t	*b;
16661 	entity_t	*mfsvc, *mfinst;
16662 	const char	*svcn;
16663 	int		rminstcnt = 0;
16664 
16665 
16666 	b = internal_bundle_new();
16667 
16668 	if (lxml_get_bundle_file(b, mfstfile, SVCCFG_OP_IMPORT) != 0) {
16669 		/*
16670 		 * Unable to process the manifest file for
16671 		 * instance support, so just return as
16672 		 * don't want to remove instances that could
16673 		 * not be accounted for that might exist here.
16674 		 */
16675 		internal_bundle_free(b);
16676 		return (0);
16677 	}
16678 
16679 	svcs = uu_list_walk_start(b->sc_bundle_services, 0);
16680 	if (svcs == NULL) {
16681 		internal_bundle_free(b);
16682 		return (0);
16683 	}
16684 
16685 	svcn = svcname + (sizeof (SCF_FMRI_SVC_PREFIX) - 1) +
16686 	    (sizeof (SCF_FMRI_SERVICE_PREFIX) - 1);
16687 
16688 	while ((mfsvc = uu_list_walk_next(svcs)) != NULL) {
16689 		if (strcmp(mfsvc->sc_name, svcn) == 0)
16690 			break;
16691 	}
16692 	uu_list_walk_end(svcs);
16693 
16694 	if (mfsvc == NULL) {
16695 		internal_bundle_free(b);
16696 		return (-1);
16697 	}
16698 
16699 	ilist = mfsvc->sc_u.sc_service.sc_service_instances;
16700 	if ((insts = uu_list_walk_start(ilist, 0)) == NULL) {
16701 		internal_bundle_free(b);
16702 		return (0);
16703 	}
16704 
16705 	while ((mfinst = uu_list_walk_next(insts)) != NULL) {
16706 		/*
16707 		 * Remove the instance from the instances list.
16708 		 * The unaccounted for instances will be removed
16709 		 * from the service once all manifests are
16710 		 * processed.
16711 		 */
16712 		(void) remove_string(instances,
16713 		    mfinst->sc_name);
16714 		rminstcnt++;
16715 	}
16716 
16717 	uu_list_walk_end(insts);
16718 	internal_bundle_free(b);
16719 
16720 	return (rminstcnt);
16721 }
16722 
16723 /*
16724  * For the given service, set its SCF_PG_MANIFESTFILES/SUPPORT property to
16725  * 'false' to indicate there's no manifest file(s) found for the service.
16726  */
16727 static void
16728 svc_add_no_support(scf_service_t *svc)
16729 {
16730 	char	*pname;
16731 
16732 	/* Add no support */
16733 	cur_svc = svc;
16734 	if (addpg(SCF_PG_MANIFESTFILES, SCF_GROUP_FRAMEWORK))
16735 		return;
16736 
16737 	pname = uu_msprintf("%s/%s", SCF_PG_MANIFESTFILES, SUPPORTPROP);
16738 	if (pname == NULL)
16739 		uu_die(gettext("Out of memory.\n"));
16740 
16741 	(void) lscf_addpropvalue(pname, "boolean:", "0");
16742 
16743 	uu_free(pname);
16744 	cur_svc = NULL;
16745 }
16746 
16747 /*
16748  * This function handles all upgrade scenarios for a service that doesn't have
16749  * SCF_PG_MANIFESTFILES pg. The function creates and populates
16750  * SCF_PG_MANIFESTFILES pg for the given service to keep track of service to
16751  * manifest(s) mapping. Manifests under supported directories are inventoried
16752  * and a property is added for each file that delivers configuration to the
16753  * service.  A service that has no corresponding manifest files (deleted) are
16754  * removed from repository.
16755  *
16756  * Unsupported services:
16757  *
16758  * A service is considered unsupported if there is no corresponding manifest
16759  * in the supported directories for that service and the service isn't in the
16760  * history file list.  The history file, MFSTHISTFILE, contains a list of all
16761  * services and instances that were delivered by Solaris before the introduction
16762  * of the SCF_PG_MANIFESTFILES property group.  The history file also contains
16763  * the path to the manifest file that defined the service or instance.
16764  *
16765  * Another type of unsupported services is 'handcrafted' services,
16766  * programmatically created services or services created by dependent entries
16767  * in other manifests. A handcrafted service is identified by its lack of any
16768  * instance containing last-import snapshot which is created during svccfg
16769  * import.
16770  *
16771  * This function sets a flag for unsupported services by setting services'
16772  * SCF_PG_MANIFESTFILES/support property to false.
16773  */
16774 static void
16775 upgrade_svc_mfst_connection(scf_service_t *svc, const char *svcname)
16776 {
16777 	service_manifest_t	*elem;
16778 	uu_list_walk_t		*mfwalk;
16779 	string_list_t		*mfile;
16780 	uu_list_t		*instances;
16781 	const char		*sname;
16782 	char			*pname;
16783 	int			r;
16784 
16785 	/*
16786 	 * Since there's no guarantee manifests under /var are available during
16787 	 * early import, don't perform any upgrade during early import.
16788 	 */
16789 	if (IGNORE_VAR)
16790 		return;
16791 
16792 	if (service_manifest_tree == NULL) {
16793 		create_manifest_tree();
16794 	}
16795 
16796 	/*
16797 	 * Find service's supporting manifest(s) after
16798 	 * stripping off the svc:/ prefix that is part
16799 	 * of the fmri that is not used in the service
16800 	 * manifest bundle list.
16801 	 */
16802 	sname = svcname + strlen(SCF_FMRI_SVC_PREFIX) +
16803 	    strlen(SCF_FMRI_SERVICE_PREFIX);
16804 	elem = find_add_svc_mfst(sname, NULL);
16805 	if (elem == NULL) {
16806 
16807 		/*
16808 		 * A handcrafted service, one that has no instance containing
16809 		 * last-import snapshot, should get unsupported flag.
16810 		 */
16811 		instances = create_instance_list(svc, 1);
16812 		if (instances == NULL) {
16813 			uu_warn(gettext("Unable to create instance list %s\n"),
16814 			    svcname);
16815 			return;
16816 		}
16817 
16818 		if (uu_list_numnodes(instances) == 0) {
16819 			svc_add_no_support(svc);
16820 			return;
16821 		}
16822 
16823 		/*
16824 		 * If the service is in the history file, and its supporting
16825 		 * manifests are not found, we can safely delete the service
16826 		 * because its manifests are removed from the system.
16827 		 *
16828 		 * Services not found in the history file are not delivered by
16829 		 * Solaris and/or delivered outside supported directories, set
16830 		 * unsupported flag for these services.
16831 		 */
16832 		r = check_mfst_history(svcname);
16833 		if (r == -1)
16834 			return;
16835 
16836 		if (r) {
16837 			/* Set unsupported flag for service  */
16838 			svc_add_no_support(svc);
16839 		} else {
16840 			/* Delete the service */
16841 			teardown_service(svc, svcname);
16842 		}
16843 
16844 		return;
16845 	}
16846 
16847 	/*
16848 	 * Walk through the list of manifests and add them
16849 	 * to the service.
16850 	 *
16851 	 * Create a manifestfiles pg and add the property.
16852 	 */
16853 	mfwalk = uu_list_walk_start(elem->mfstlist, 0);
16854 	if (mfwalk == NULL)
16855 		return;
16856 
16857 	cur_svc = svc;
16858 	r = addpg(SCF_PG_MANIFESTFILES, SCF_GROUP_FRAMEWORK);
16859 	if (r != 0) {
16860 		cur_svc = NULL;
16861 		return;
16862 	}
16863 
16864 	while ((mfile = uu_list_walk_next(mfwalk)) != NULL) {
16865 		pname = uu_msprintf("%s/%s", SCF_PG_MANIFESTFILES,
16866 		    mhash_filename_to_propname(mfile->str, 0));
16867 		if (pname == NULL)
16868 			uu_die(gettext("Out of memory.\n"));
16869 
16870 		(void) lscf_addpropvalue(pname, "astring:", mfile->str);
16871 		uu_free(pname);
16872 	}
16873 	uu_list_walk_end(mfwalk);
16874 
16875 	cur_svc = NULL;
16876 }
16877 
16878 /*
16879  * Take a service and process the manifest file entires to see if
16880  * there is continued support for the service and instances.  If
16881  * not cleanup as appropriate.
16882  *
16883  * If a service does not have a manifest files entry flag it for
16884  * upgrade and return.
16885  *
16886  * For each manifestfiles property check if the manifest file is
16887  * under the supported /lib/svc/manifest or /var/svc/manifest path
16888  * and if not then return immediately as this service is not supported
16889  * by the cleanup mechanism and should be ignored.
16890  *
16891  * For each manifest file that is supported, check to see if the
16892  * file exists.  If not then remove the manifest file property
16893  * from the service and the smf/manifest hash table.  If the manifest
16894  * file exists then verify that it supports the instances that are
16895  * part of the service.
16896  *
16897  * Once all manifest files have been accounted for remove any instances
16898  * that are no longer supported in the service.
16899  *
16900  * Return values :
16901  * 0 - Successfully processed the service
16902  * non-zero - failed to process the service
16903  *
16904  * On most errors, will just return to wait and get the next service,
16905  * unless in case of unable to create the needed structures which is
16906  * most likely a fatal error that is not going to be recoverable.
16907  */
16908 int
16909 lscf_service_cleanup(void *act, scf_walkinfo_t *wip)
16910 {
16911 	struct mpg_mfile	*mpntov;
16912 	struct mpg_mfile	**mpvarry = NULL;
16913 	scf_service_t		*svc;
16914 	scf_propertygroup_t	*mpg;
16915 	scf_property_t		*mp;
16916 	scf_value_t		*mv;
16917 	scf_iter_t		*mi;
16918 	scf_instance_t		*instance;
16919 	uu_list_walk_t		*insts;
16920 	uu_list_t		*instances = NULL;
16921 	boolean_t		activity = (boolean_t)act;
16922 	char			*mpnbuf;
16923 	char			*mpvbuf;
16924 	char			*pgpropbuf;
16925 	int			mfstcnt, rminstct, instct, mfstmax;
16926 	int			index;
16927 	int			r = 0;
16928 
16929 	assert(g_hndl != NULL);
16930 	assert(wip->svc != NULL);
16931 	assert(wip->fmri != NULL);
16932 
16933 	svc = wip->svc;
16934 
16935 	mpg = scf_pg_create(g_hndl);
16936 	mp = scf_property_create(g_hndl);
16937 	mi = scf_iter_create(g_hndl);
16938 	mv = scf_value_create(g_hndl);
16939 	instance = scf_instance_create(g_hndl);
16940 
16941 	if (mpg == NULL || mp == NULL || mi == NULL || mv == NULL ||
16942 	    instance == NULL) {
16943 		uu_warn(gettext("Unable to create the supporting entities\n"));
16944 		uu_warn(gettext("scf error is : %s\n"),
16945 		    scf_strerror(scf_error()));
16946 		scfdie();
16947 	}
16948 
16949 	/*
16950 	 * Get the manifestfiles property group to be parsed for
16951 	 * files existence.
16952 	 */
16953 	if (scf_service_get_pg(svc, SCF_PG_MANIFESTFILES, mpg) != SCF_SUCCESS) {
16954 		switch (scf_error()) {
16955 		case SCF_ERROR_NOT_FOUND:
16956 			upgrade_svc_mfst_connection(svc, wip->fmri);
16957 			break;
16958 		case SCF_ERROR_DELETED:
16959 		case SCF_ERROR_CONNECTION_BROKEN:
16960 			goto out;
16961 
16962 		case SCF_ERROR_HANDLE_MISMATCH:
16963 		case SCF_ERROR_NOT_BOUND:
16964 		case SCF_ERROR_NOT_SET:
16965 		default:
16966 			bad_error("scf_iter_pg_properties",
16967 			    scf_error());
16968 		}
16969 
16970 		goto out;
16971 	}
16972 
16973 	/*
16974 	 * Iterate through each of the manifestfiles properties
16975 	 * to determine what manifestfiles are available.
16976 	 *
16977 	 * If a manifest file is supported then increment the
16978 	 * count and therefore the service is safe.
16979 	 */
16980 	if (scf_iter_pg_properties(mi, mpg) != 0) {
16981 		switch (scf_error()) {
16982 		case SCF_ERROR_DELETED:
16983 		case SCF_ERROR_CONNECTION_BROKEN:
16984 			goto out;
16985 
16986 		case SCF_ERROR_HANDLE_MISMATCH:
16987 		case SCF_ERROR_NOT_BOUND:
16988 		case SCF_ERROR_NOT_SET:
16989 		default:
16990 			bad_error("scf_iter_pg_properties",
16991 			    scf_error());
16992 		}
16993 	}
16994 
16995 	mfstcnt = 0;
16996 	mfstmax = MFSTFILE_MAX;
16997 	mpvarry = safe_malloc(sizeof (struct mpg_file *) * MFSTFILE_MAX);
16998 	while ((r = scf_iter_next_property(mi, mp)) != 0) {
16999 		if (r == -1)
17000 			bad_error(gettext("Unable to iterate through "
17001 			    "manifestfiles properties : %s"),
17002 			    scf_error());
17003 
17004 		mpntov = safe_malloc(sizeof (struct mpg_mfile));
17005 		mpnbuf = safe_malloc(max_scf_name_len + 1);
17006 		mpvbuf = safe_malloc(max_scf_value_len + 1);
17007 		mpntov->mpg = mpnbuf;
17008 		mpntov->mfile = mpvbuf;
17009 		mpntov->access = 1;
17010 		if (scf_property_get_name(mp, mpnbuf,
17011 		    max_scf_name_len + 1) < 0) {
17012 			uu_warn(gettext("Unable to get manifest file "
17013 			    "property : %s\n"),
17014 			    scf_strerror(scf_error()));
17015 
17016 			switch (scf_error()) {
17017 			case SCF_ERROR_DELETED:
17018 			case SCF_ERROR_CONNECTION_BROKEN:
17019 				r = scferror2errno(scf_error());
17020 				goto out_free;
17021 
17022 			case SCF_ERROR_HANDLE_MISMATCH:
17023 			case SCF_ERROR_NOT_BOUND:
17024 			case SCF_ERROR_NOT_SET:
17025 			default:
17026 				bad_error("scf_iter_pg_properties",
17027 				    scf_error());
17028 			}
17029 		}
17030 
17031 		/*
17032 		 * The support property is a boolean value that indicates
17033 		 * if the service is supported for manifest file deletion.
17034 		 * Currently at this time there is no code that sets this
17035 		 * value to true.  So while we could just let this be caught
17036 		 * by the support check below, in the future this by be set
17037 		 * to true and require processing.  So for that, go ahead
17038 		 * and check here, and just return if false.  Otherwise,
17039 		 * fall through expecting that other support checks will
17040 		 * handle the entries.
17041 		 */
17042 		if (strcmp(mpnbuf, SUPPORTPROP) == 0) {
17043 			uint8_t	support;
17044 
17045 			if (scf_property_get_value(mp, mv) != 0 ||
17046 			    scf_value_get_boolean(mv, &support) != 0) {
17047 				uu_warn(gettext("Unable to get the manifest "
17048 				    "support value: %s\n"),
17049 				    scf_strerror(scf_error()));
17050 
17051 				switch (scf_error()) {
17052 				case SCF_ERROR_DELETED:
17053 				case SCF_ERROR_CONNECTION_BROKEN:
17054 					r = scferror2errno(scf_error());
17055 					goto out_free;
17056 
17057 				case SCF_ERROR_HANDLE_MISMATCH:
17058 				case SCF_ERROR_NOT_BOUND:
17059 				case SCF_ERROR_NOT_SET:
17060 				default:
17061 					bad_error("scf_iter_pg_properties",
17062 					    scf_error());
17063 				}
17064 			}
17065 
17066 			if (support == B_FALSE)
17067 				goto out_free;
17068 		}
17069 
17070 		/*
17071 		 * Anything with a manifest outside of the supported
17072 		 * directories, immediately bail out because that makes
17073 		 * this service non-supported.  We don't even want
17074 		 * to do instance processing in this case because the
17075 		 * instances could be part of the non-supported manifest.
17076 		 */
17077 		if (strncmp(mpnbuf, LIBSVC_PR, strlen(LIBSVC_PR)) != 0) {
17078 			/*
17079 			 * Manifest is not in /lib/svc, so we need to
17080 			 * consider the /var/svc case.
17081 			 */
17082 			if (strncmp(mpnbuf, VARSVC_PR,
17083 			    strlen(VARSVC_PR)) != 0 || IGNORE_VAR) {
17084 				/*
17085 				 * Either the manifest is not in /var/svc or
17086 				 * /var is not yet mounted.  We ignore the
17087 				 * manifest either because it is not in a
17088 				 * standard location or because we cannot
17089 				 * currently access the manifest.
17090 				 */
17091 				goto out_free;
17092 			}
17093 		}
17094 
17095 		/*
17096 		 * Get the value to of the manifest file for this entry
17097 		 * for access verification and instance support
17098 		 * verification if it still exists.
17099 		 *
17100 		 * During Early Manifest Import if the manifest is in
17101 		 * /var/svc then it may not yet be available for checking
17102 		 * so we must determine if /var/svc is available.  If not
17103 		 * then defer until Late Manifest Import to cleanup.
17104 		 */
17105 		if (scf_property_get_value(mp, mv) != 0) {
17106 			uu_warn(gettext("Unable to get the manifest file "
17107 			    "value: %s\n"),
17108 			    scf_strerror(scf_error()));
17109 
17110 			switch (scf_error()) {
17111 			case SCF_ERROR_DELETED:
17112 			case SCF_ERROR_CONNECTION_BROKEN:
17113 				r = scferror2errno(scf_error());
17114 				goto out_free;
17115 
17116 			case SCF_ERROR_HANDLE_MISMATCH:
17117 			case SCF_ERROR_NOT_BOUND:
17118 			case SCF_ERROR_NOT_SET:
17119 			default:
17120 				bad_error("scf_property_get_value",
17121 				    scf_error());
17122 			}
17123 		}
17124 
17125 		if (scf_value_get_astring(mv, mpvbuf,
17126 		    max_scf_value_len + 1) < 0) {
17127 			uu_warn(gettext("Unable to get the manifest "
17128 			    "file : %s\n"),
17129 			    scf_strerror(scf_error()));
17130 
17131 			switch (scf_error()) {
17132 			case SCF_ERROR_DELETED:
17133 			case SCF_ERROR_CONNECTION_BROKEN:
17134 				r = scferror2errno(scf_error());
17135 				goto out_free;
17136 
17137 			case SCF_ERROR_HANDLE_MISMATCH:
17138 			case SCF_ERROR_NOT_BOUND:
17139 			case SCF_ERROR_NOT_SET:
17140 			default:
17141 				bad_error("scf_value_get_astring",
17142 				    scf_error());
17143 			}
17144 		}
17145 
17146 		mpvarry[mfstcnt] = mpntov;
17147 		mfstcnt++;
17148 
17149 		/*
17150 		 * Check for the need to reallocate array
17151 		 */
17152 		if (mfstcnt >= (mfstmax - 1)) {
17153 			struct mpg_mfile **newmpvarry;
17154 
17155 			mfstmax = mfstmax * 2;
17156 			newmpvarry = realloc(mpvarry,
17157 			    sizeof (struct mpg_mfile *) * mfstmax);
17158 
17159 			if (newmpvarry == NULL)
17160 				goto out_free;
17161 
17162 			mpvarry = newmpvarry;
17163 		}
17164 
17165 		mpvarry[mfstcnt] = NULL;
17166 	}
17167 
17168 	for (index = 0; mpvarry[index]; index++) {
17169 		mpntov = mpvarry[index];
17170 
17171 		/*
17172 		 * Check to see if the manifestfile is accessable, if so hand
17173 		 * this service and manifestfile off to be processed for
17174 		 * instance support.
17175 		 */
17176 		mpnbuf = mpntov->mpg;
17177 		mpvbuf = mpntov->mfile;
17178 		if (access(mpvbuf, F_OK) != 0) {
17179 			mpntov->access = 0;
17180 			activity++;
17181 			mfstcnt--;
17182 			/* Remove the entry from the service */
17183 			cur_svc = svc;
17184 			pgpropbuf = uu_msprintf("%s/%s", SCF_PG_MANIFESTFILES,
17185 			    mpnbuf);
17186 			if (pgpropbuf == NULL)
17187 				uu_die(gettext("Out of memory.\n"));
17188 
17189 			lscf_delprop(pgpropbuf);
17190 			cur_svc = NULL;
17191 
17192 			uu_free(pgpropbuf);
17193 		}
17194 	}
17195 
17196 	/*
17197 	 * If mfstcnt is 0, none of the manifests that supported the service
17198 	 * existed so remove the service.
17199 	 */
17200 	if (mfstcnt == 0) {
17201 		teardown_service(svc, wip->fmri);
17202 
17203 		goto out_free;
17204 	}
17205 
17206 	if (activity) {
17207 		int	nosvcsupport = 0;
17208 
17209 		/*
17210 		 * If the list of service instances is NULL then
17211 		 * create the list.
17212 		 */
17213 		instances = create_instance_list(svc, 1);
17214 		if (instances == NULL) {
17215 			uu_warn(gettext("Unable to create instance list %s\n"),
17216 			    wip->fmri);
17217 			goto out_free;
17218 		}
17219 
17220 		rminstct = uu_list_numnodes(instances);
17221 		instct = rminstct;
17222 
17223 		for (index = 0; mpvarry[index]; index++) {
17224 			mpntov = mpvarry[index];
17225 			if (mpntov->access == 0)
17226 				continue;
17227 
17228 			mpnbuf = mpntov->mpg;
17229 			mpvbuf = mpntov->mfile;
17230 			r = check_instance_support(mpvbuf, wip->fmri,
17231 			    instances);
17232 			if (r == -1) {
17233 				nosvcsupport++;
17234 			} else {
17235 				rminstct -= r;
17236 			}
17237 		}
17238 
17239 		if (instct && instct == rminstct && nosvcsupport == mfstcnt) {
17240 			teardown_service(svc, wip->fmri);
17241 
17242 			goto out_free;
17243 		}
17244 	}
17245 
17246 	/*
17247 	 * If there are instances left on the instance list, then
17248 	 * we must remove them.
17249 	 */
17250 	if (instances != NULL && uu_list_numnodes(instances)) {
17251 		string_list_t *sp;
17252 
17253 		insts = uu_list_walk_start(instances, 0);
17254 		while ((sp = uu_list_walk_next(insts)) != NULL) {
17255 			/*
17256 			 * Remove the instance from the instances list.
17257 			 */
17258 			safe_printf(gettext("Delete instance %s from "
17259 			    "service %s\n"), sp->str, wip->fmri);
17260 			if (scf_service_get_instance(svc, sp->str,
17261 			    instance) != SCF_SUCCESS) {
17262 				(void) uu_warn("scf_error - %s\n",
17263 				    scf_strerror(scf_error()));
17264 
17265 				continue;
17266 			}
17267 
17268 			(void) disable_instance(instance);
17269 
17270 			(void) lscf_instance_delete(instance, 1);
17271 		}
17272 		scf_instance_destroy(instance);
17273 		uu_list_walk_end(insts);
17274 	}
17275 
17276 out_free:
17277 	if (mpvarry) {
17278 		struct mpg_mfile *fmpntov;
17279 
17280 		for (index = 0; mpvarry[index]; index++) {
17281 			fmpntov  = mpvarry[index];
17282 			if (fmpntov->mpg == mpnbuf)
17283 				mpnbuf = NULL;
17284 			free(fmpntov->mpg);
17285 
17286 			if (fmpntov->mfile == mpvbuf)
17287 				mpvbuf = NULL;
17288 			free(fmpntov->mfile);
17289 
17290 			if (fmpntov == mpntov)
17291 				mpntov = NULL;
17292 			free(fmpntov);
17293 		}
17294 		if (mpnbuf)
17295 			free(mpnbuf);
17296 		if (mpvbuf)
17297 			free(mpvbuf);
17298 		if (mpntov)
17299 			free(mpntov);
17300 
17301 		free(mpvarry);
17302 	}
17303 out:
17304 	scf_pg_destroy(mpg);
17305 	scf_property_destroy(mp);
17306 	scf_iter_destroy(mi);
17307 	scf_value_destroy(mv);
17308 
17309 	return (0);
17310 }
17311 
17312 /*
17313  * Take the service and search for the manifestfiles property
17314  * in each of the property groups.  If the manifest file
17315  * associated with the property does not exist then remove
17316  * the property group.
17317  */
17318 int
17319 lscf_hash_cleanup()
17320 {
17321 	scf_service_t		*svc;
17322 	scf_scope_t		*scope;
17323 	scf_propertygroup_t	*pg;
17324 	scf_property_t		*prop;
17325 	scf_value_t		*val;
17326 	scf_iter_t		*iter;
17327 	char			*pgname = NULL;
17328 	char			*mfile = NULL;
17329 	int			r;
17330 
17331 	svc = scf_service_create(g_hndl);
17332 	scope = scf_scope_create(g_hndl);
17333 	pg = scf_pg_create(g_hndl);
17334 	prop = scf_property_create(g_hndl);
17335 	val = scf_value_create(g_hndl);
17336 	iter = scf_iter_create(g_hndl);
17337 	if (pg == NULL || prop == NULL || val == NULL || iter == NULL ||
17338 	    svc == NULL || scope == NULL) {
17339 		uu_warn(gettext("Unable to create a property group, or "
17340 		    "property\n"));
17341 		uu_warn("%s\n", pg == NULL ? "pg is NULL" :
17342 		    "pg is not NULL");
17343 		uu_warn("%s\n", prop == NULL ? "prop is NULL" :
17344 		    "prop is not NULL");
17345 		uu_warn("%s\n", val == NULL ? "val is NULL" :
17346 		    "val is not NULL");
17347 		uu_warn("%s\n", iter == NULL ? "iter is NULL" :
17348 		    "iter is not NULL");
17349 		uu_warn("%s\n", svc == NULL ? "svc is NULL" :
17350 		    "svc is not NULL");
17351 		uu_warn("%s\n", scope == NULL ? "scope is NULL" :
17352 		    "scope is not NULL");
17353 		uu_warn(gettext("scf error is : %s\n"),
17354 		    scf_strerror(scf_error()));
17355 		scfdie();
17356 	}
17357 
17358 	if (scf_handle_get_scope(g_hndl, SCF_SCOPE_LOCAL, scope) != 0) {
17359 		switch (scf_error()) {
17360 		case SCF_ERROR_CONNECTION_BROKEN:
17361 		case SCF_ERROR_NOT_FOUND:
17362 			goto out;
17363 
17364 		case SCF_ERROR_HANDLE_MISMATCH:
17365 		case SCF_ERROR_NOT_BOUND:
17366 		case SCF_ERROR_INVALID_ARGUMENT:
17367 		default:
17368 			bad_error("scf_handle_get_scope", scf_error());
17369 		}
17370 	}
17371 
17372 	if (scf_scope_get_service(scope, HASH_SVC, svc) != 0) {
17373 		uu_warn(gettext("Unable to process the hash service, %s\n"),
17374 		    HASH_SVC);
17375 		goto out;
17376 	}
17377 
17378 	pgname = safe_malloc(max_scf_name_len + 1);
17379 	mfile = safe_malloc(max_scf_value_len + 1);
17380 
17381 	if (scf_iter_service_pgs(iter, svc) != SCF_SUCCESS) {
17382 		uu_warn(gettext("Unable to cleanup smf hash table : %s\n"),
17383 		    scf_strerror(scf_error()));
17384 		goto out;
17385 	}
17386 
17387 	while ((r = scf_iter_next_pg(iter, pg)) != 0) {
17388 		if (r == -1)
17389 			goto out;
17390 
17391 		if (scf_pg_get_name(pg, pgname, max_scf_name_len + 1) < 0) {
17392 			switch (scf_error()) {
17393 			case SCF_ERROR_DELETED:
17394 				return (ENODEV);
17395 
17396 			case SCF_ERROR_CONNECTION_BROKEN:
17397 				return (ECONNABORTED);
17398 
17399 			case SCF_ERROR_NOT_SET:
17400 			case SCF_ERROR_NOT_BOUND:
17401 			default:
17402 				bad_error("scf_pg_get_name", scf_error());
17403 			}
17404 		}
17405 		if (IGNORE_VAR) {
17406 			if (strncmp(pgname, VARSVC_PR, strlen(VARSVC_PR)) == 0)
17407 				continue;
17408 		}
17409 
17410 		/*
17411 		 * If unable to get the property continue as this is an
17412 		 * entry that has no location to check against.
17413 		 */
17414 		if (scf_pg_get_property(pg, MFSTFILEPR, prop) != SCF_SUCCESS) {
17415 			continue;
17416 		}
17417 
17418 		if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
17419 			uu_warn(gettext("Unable to get value from %s\n"),
17420 			    pgname);
17421 
17422 			switch (scf_error()) {
17423 			case SCF_ERROR_DELETED:
17424 			case SCF_ERROR_CONSTRAINT_VIOLATED:
17425 			case SCF_ERROR_NOT_FOUND:
17426 			case SCF_ERROR_NOT_SET:
17427 				continue;
17428 
17429 			case SCF_ERROR_CONNECTION_BROKEN:
17430 				r = scferror2errno(scf_error());
17431 				goto out;
17432 
17433 			case SCF_ERROR_HANDLE_MISMATCH:
17434 			case SCF_ERROR_NOT_BOUND:
17435 			default:
17436 				bad_error("scf_property_get_value",
17437 				    scf_error());
17438 			}
17439 		}
17440 
17441 		if (scf_value_get_astring(val, mfile, max_scf_value_len + 1)
17442 		    == -1) {
17443 			uu_warn(gettext("Unable to get astring from %s : %s\n"),
17444 			    pgname, scf_strerror(scf_error()));
17445 
17446 			switch (scf_error()) {
17447 			case SCF_ERROR_NOT_SET:
17448 			case SCF_ERROR_TYPE_MISMATCH:
17449 				continue;
17450 
17451 			default:
17452 				bad_error("scf_value_get_astring", scf_error());
17453 			}
17454 		}
17455 
17456 		if (access(mfile, F_OK) == 0)
17457 			continue;
17458 
17459 		(void) scf_pg_delete(pg);
17460 	}
17461 
17462 out:
17463 	scf_scope_destroy(scope);
17464 	scf_service_destroy(svc);
17465 	scf_pg_destroy(pg);
17466 	scf_property_destroy(prop);
17467 	scf_value_destroy(val);
17468 	scf_iter_destroy(iter);
17469 	free(pgname);
17470 	free(mfile);
17471 
17472 	return (0);
17473 }
17474 
17475 #ifndef NATIVE_BUILD
17476 /* ARGSUSED */
17477 CPL_MATCH_FN(complete_select)
17478 {
17479 	const char *arg0, *arg1, *arg1end;
17480 	int word_start, err = 0, r;
17481 	size_t len;
17482 	char *buf;
17483 
17484 	lscf_prep_hndl();
17485 
17486 	arg0 = line + strspn(line, " \t");
17487 	assert(strncmp(arg0, "select", sizeof ("select") - 1) == 0);
17488 
17489 	arg1 = arg0 + sizeof ("select") - 1;
17490 	arg1 += strspn(arg1, " \t");
17491 	word_start = arg1 - line;
17492 
17493 	arg1end = arg1 + strcspn(arg1, " \t");
17494 	if (arg1end < line + word_end)
17495 		return (0);
17496 
17497 	len = line + word_end - arg1;
17498 
17499 	buf = safe_malloc(max_scf_name_len + 1);
17500 
17501 	if (cur_snap != NULL) {
17502 		return (0);
17503 	} else if (cur_inst != NULL) {
17504 		return (0);
17505 	} else if (cur_svc != NULL) {
17506 		scf_instance_t *inst;
17507 		scf_iter_t *iter;
17508 
17509 		if ((inst = scf_instance_create(g_hndl)) == NULL ||
17510 		    (iter = scf_iter_create(g_hndl)) == NULL)
17511 			scfdie();
17512 
17513 		if (scf_iter_service_instances(iter, cur_svc) != 0)
17514 			scfdie();
17515 
17516 		for (;;) {
17517 			r = scf_iter_next_instance(iter, inst);
17518 			if (r == 0)
17519 				break;
17520 			if (r != 1)
17521 				scfdie();
17522 
17523 			if (scf_instance_get_name(inst, buf,
17524 			    max_scf_name_len + 1) < 0)
17525 				scfdie();
17526 
17527 			if (strncmp(buf, arg1, len) == 0) {
17528 				err = cpl_add_completion(cpl, line, word_start,
17529 				    word_end, buf + len, "", " ");
17530 				if (err != 0)
17531 					break;
17532 			}
17533 		}
17534 
17535 		scf_iter_destroy(iter);
17536 		scf_instance_destroy(inst);
17537 
17538 		return (err);
17539 	} else {
17540 		scf_service_t *svc;
17541 		scf_iter_t *iter;
17542 
17543 		assert(cur_scope != NULL);
17544 
17545 		if ((svc = scf_service_create(g_hndl)) == NULL ||
17546 		    (iter = scf_iter_create(g_hndl)) == NULL)
17547 			scfdie();
17548 
17549 		if (scf_iter_scope_services(iter, cur_scope) != 0)
17550 			scfdie();
17551 
17552 		for (;;) {
17553 			r = scf_iter_next_service(iter, svc);
17554 			if (r == 0)
17555 				break;
17556 			if (r != 1)
17557 				scfdie();
17558 
17559 			if (scf_service_get_name(svc, buf,
17560 			    max_scf_name_len + 1) < 0)
17561 				scfdie();
17562 
17563 			if (strncmp(buf, arg1, len) == 0) {
17564 				err = cpl_add_completion(cpl, line, word_start,
17565 				    word_end, buf + len, "", " ");
17566 				if (err != 0)
17567 					break;
17568 			}
17569 		}
17570 
17571 		scf_iter_destroy(iter);
17572 		scf_service_destroy(svc);
17573 
17574 		return (err);
17575 	}
17576 }
17577 
17578 /* ARGSUSED */
17579 CPL_MATCH_FN(complete_command)
17580 {
17581 	uint32_t scope = 0;
17582 
17583 	if (cur_snap != NULL)
17584 		scope = CS_SNAP;
17585 	else if (cur_inst != NULL)
17586 		scope = CS_INST;
17587 	else if (cur_svc != NULL)
17588 		scope = CS_SVC;
17589 	else
17590 		scope = CS_SCOPE;
17591 
17592 	return (scope ? add_cmd_matches(cpl, line, word_end, scope) : 0);
17593 }
17594 #endif	/* NATIVE_BUILD */
17595