xref: /titanic_52/usr/src/cmd/svc/svccfg/svccfg_libscf.c (revision b819cea2f73f98c5662230cc9affc8cc84f77fcf)
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) 2012, 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 	boolean_t retried = B_FALSE;
7040 
7041 	const char * const ts_deleted = gettext("Temporary service svc:/%s "
7042 	    "was deleted unexpectedly.\n");
7043 	const char * const ts_pg_added = gettext("Temporary service svc:/%s "
7044 	    "changed unexpectedly (property group added).\n");
7045 	const char * const s_deleted =
7046 	    gettext("%s was deleted unexpectedly.\n");
7047 	const char * const i_deleted =
7048 	    gettext("%s changed unexpectedly (instance \"%s\" deleted).\n");
7049 	const char * const badsnap = gettext("\"%s\" snapshot of svc:/%s:%s "
7050 	    "is corrupt (missing service snaplevel).\n");
7051 	const char * const s_mfile_upd =
7052 	    gettext("Unable to update the manifest file connection "
7053 	    "for %s\n");
7054 
7055 	li_only = 0;
7056 	/* Validate the service name */
7057 	if (scf_scope_get_service(scope, s->sc_name, imp_svc) != 0) {
7058 		switch (scf_error()) {
7059 		case SCF_ERROR_CONNECTION_BROKEN:
7060 			return (stash_scferror(lcbdata));
7061 
7062 		case SCF_ERROR_INVALID_ARGUMENT:
7063 			warn(gettext("\"%s\" is an invalid service name.  "
7064 			    "Cannot import.\n"), s->sc_name);
7065 			return (stash_scferror(lcbdata));
7066 
7067 		case SCF_ERROR_NOT_FOUND:
7068 			break;
7069 
7070 		case SCF_ERROR_HANDLE_MISMATCH:
7071 		case SCF_ERROR_NOT_BOUND:
7072 		case SCF_ERROR_NOT_SET:
7073 		default:
7074 			bad_error("scf_scope_get_service", scf_error());
7075 		}
7076 	}
7077 
7078 	/* create temporary service */
7079 	/*
7080 	 * the size of the buffer was reduced to max_scf_name_len to prevent
7081 	 * hitting bug 6681151.  After the bug fix, the size of the buffer
7082 	 * should be restored to its original value (max_scf_name_len +1)
7083 	 */
7084 	r = snprintf(imp_tsname, max_scf_name_len, "TEMP/%s", s->sc_name);
7085 	if (r < 0)
7086 		bad_error("snprintf", errno);
7087 	if (r > max_scf_name_len) {
7088 		warn(gettext(
7089 		    "Service name \"%s\" is too long.  Cannot import.\n"),
7090 		    s->sc_name);
7091 		lcbdata->sc_err = EINVAL;
7092 		return (UU_WALK_ERROR);
7093 	}
7094 
7095 retry:
7096 	if (scf_scope_add_service(imp_scope, imp_tsname, imp_tsvc) != 0) {
7097 		switch (scf_error()) {
7098 		case SCF_ERROR_CONNECTION_BROKEN:
7099 		case SCF_ERROR_NO_RESOURCES:
7100 		case SCF_ERROR_BACKEND_READONLY:
7101 		case SCF_ERROR_BACKEND_ACCESS:
7102 			return (stash_scferror(lcbdata));
7103 
7104 		case SCF_ERROR_EXISTS:
7105 			if (!retried) {
7106 				lscf_delete(imp_tsname, 0);
7107 				retried = B_TRUE;
7108 				goto retry;
7109 			}
7110 			warn(gettext(
7111 			    "Temporary service \"%s\" must be deleted before "
7112 			    "this manifest can be imported.\n"), imp_tsname);
7113 			return (stash_scferror(lcbdata));
7114 
7115 		case SCF_ERROR_PERMISSION_DENIED:
7116 			warn(gettext("Could not create temporary service "
7117 			    "\"%s\" (permission denied).\n"), imp_tsname);
7118 			return (stash_scferror(lcbdata));
7119 
7120 		case SCF_ERROR_INVALID_ARGUMENT:
7121 		case SCF_ERROR_HANDLE_MISMATCH:
7122 		case SCF_ERROR_NOT_BOUND:
7123 		case SCF_ERROR_NOT_SET:
7124 		default:
7125 			bad_error("scf_scope_add_service", scf_error());
7126 		}
7127 	}
7128 
7129 	r = snprintf(imp_str, imp_str_sz, "svc:/%s", imp_tsname);
7130 	if (r < 0)
7131 		bad_error("snprintf", errno);
7132 
7133 	cbdata.sc_handle = lcbdata->sc_handle;
7134 	cbdata.sc_parent = imp_tsvc;
7135 	cbdata.sc_service = 1;
7136 	cbdata.sc_source_fmri = s->sc_fmri;
7137 	cbdata.sc_target_fmri = imp_str;
7138 	cbdata.sc_flags = 0;
7139 
7140 	if (uu_list_walk(s->sc_pgroups, entity_pgroup_import, &cbdata,
7141 	    UU_DEFAULT) != 0) {
7142 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7143 			bad_error("uu_list_walk", uu_error());
7144 
7145 		lcbdata->sc_err = cbdata.sc_err;
7146 		switch (cbdata.sc_err) {
7147 		case ECONNABORTED:
7148 			goto connaborted;
7149 
7150 		case ECANCELED:
7151 			warn(ts_deleted, imp_tsname);
7152 			lcbdata->sc_err = EBUSY;
7153 			return (UU_WALK_ERROR);
7154 
7155 		case EEXIST:
7156 			warn(ts_pg_added, imp_tsname);
7157 			lcbdata->sc_err = EBUSY;
7158 			return (UU_WALK_ERROR);
7159 		}
7160 
7161 		r = UU_WALK_ERROR;
7162 		goto deltemp;
7163 	}
7164 
7165 	if (uu_list_walk(s->sc_dependents, entity_pgroup_import, &cbdata,
7166 	    UU_DEFAULT) != 0) {
7167 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7168 			bad_error("uu_list_walk", uu_error());
7169 
7170 		lcbdata->sc_err = cbdata.sc_err;
7171 		switch (cbdata.sc_err) {
7172 		case ECONNABORTED:
7173 			goto connaborted;
7174 
7175 		case ECANCELED:
7176 			warn(ts_deleted, imp_tsname);
7177 			lcbdata->sc_err = EBUSY;
7178 			return (UU_WALK_ERROR);
7179 
7180 		case EEXIST:
7181 			warn(ts_pg_added, imp_tsname);
7182 			lcbdata->sc_err = EBUSY;
7183 			return (UU_WALK_ERROR);
7184 		}
7185 
7186 		r = UU_WALK_ERROR;
7187 		goto deltemp;
7188 	}
7189 
7190 	if (scf_scope_get_service(scope, s->sc_name, imp_svc) != 0) {
7191 		switch (scf_error()) {
7192 		case SCF_ERROR_NOT_FOUND:
7193 			break;
7194 
7195 		case SCF_ERROR_CONNECTION_BROKEN:
7196 			goto connaborted;
7197 
7198 		case SCF_ERROR_INVALID_ARGUMENT:
7199 		case SCF_ERROR_HANDLE_MISMATCH:
7200 		case SCF_ERROR_NOT_BOUND:
7201 		case SCF_ERROR_NOT_SET:
7202 		default:
7203 			bad_error("scf_scope_get_service", scf_error());
7204 		}
7205 
7206 		if (scf_scope_add_service(scope, s->sc_name, imp_svc) != 0) {
7207 			switch (scf_error()) {
7208 			case SCF_ERROR_CONNECTION_BROKEN:
7209 				goto connaborted;
7210 
7211 			case SCF_ERROR_NO_RESOURCES:
7212 			case SCF_ERROR_BACKEND_READONLY:
7213 			case SCF_ERROR_BACKEND_ACCESS:
7214 				r = stash_scferror(lcbdata);
7215 				goto deltemp;
7216 
7217 			case SCF_ERROR_EXISTS:
7218 				warn(gettext("Scope \"%s\" changed unexpectedly"
7219 				    " (service \"%s\" added).\n"),
7220 				    SCF_SCOPE_LOCAL, s->sc_name);
7221 				lcbdata->sc_err = EBUSY;
7222 				goto deltemp;
7223 
7224 			case SCF_ERROR_PERMISSION_DENIED:
7225 				warn(gettext("Could not create service \"%s\" "
7226 				    "(permission denied).\n"), s->sc_name);
7227 				goto deltemp;
7228 
7229 			case SCF_ERROR_INVALID_ARGUMENT:
7230 			case SCF_ERROR_HANDLE_MISMATCH:
7231 			case SCF_ERROR_NOT_BOUND:
7232 			case SCF_ERROR_NOT_SET:
7233 			default:
7234 				bad_error("scf_scope_add_service", scf_error());
7235 			}
7236 		}
7237 
7238 		s->sc_import_state = IMPORT_PROP_BEGUN;
7239 
7240 		/* import service properties */
7241 		cbdata.sc_handle = lcbdata->sc_handle;
7242 		cbdata.sc_parent = imp_svc;
7243 		cbdata.sc_service = 1;
7244 		cbdata.sc_flags = lcbdata->sc_flags;
7245 		cbdata.sc_source_fmri = s->sc_fmri;
7246 		cbdata.sc_target_fmri = s->sc_fmri;
7247 
7248 		if (uu_list_walk(s->sc_pgroups, entity_pgroup_import,
7249 		    &cbdata, UU_DEFAULT) != 0) {
7250 			if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7251 				bad_error("uu_list_walk", uu_error());
7252 
7253 			lcbdata->sc_err = cbdata.sc_err;
7254 			switch (cbdata.sc_err) {
7255 			case ECONNABORTED:
7256 				goto connaborted;
7257 
7258 			case ECANCELED:
7259 				warn(s_deleted, s->sc_fmri);
7260 				lcbdata->sc_err = EBUSY;
7261 				return (UU_WALK_ERROR);
7262 
7263 			case EEXIST:
7264 				warn(gettext("%s changed unexpectedly "
7265 				    "(property group added).\n"), s->sc_fmri);
7266 				lcbdata->sc_err = EBUSY;
7267 				return (UU_WALK_ERROR);
7268 
7269 			case EINVAL:
7270 				/* caught above */
7271 				bad_error("entity_pgroup_import",
7272 				    cbdata.sc_err);
7273 			}
7274 
7275 			r = UU_WALK_ERROR;
7276 			goto deltemp;
7277 		}
7278 
7279 		cbdata.sc_trans = NULL;
7280 		cbdata.sc_flags = 0;
7281 		if (uu_list_walk(s->sc_dependents, lscf_dependent_import,
7282 		    &cbdata, UU_DEFAULT) != 0) {
7283 			if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7284 				bad_error("uu_list_walk", uu_error());
7285 
7286 			lcbdata->sc_err = cbdata.sc_err;
7287 			if (cbdata.sc_err == ECONNABORTED)
7288 				goto connaborted;
7289 			r = UU_WALK_ERROR;
7290 			goto deltemp;
7291 		}
7292 
7293 		s->sc_import_state = IMPORT_PROP_DONE;
7294 
7295 		/*
7296 		 * This is a new service, so we can't take previous snapshots
7297 		 * or upgrade service properties.
7298 		 */
7299 		fresh = 1;
7300 		goto instances;
7301 	}
7302 
7303 	/* Clear sc_seen for the instances. */
7304 	if (uu_list_walk(s->sc_u.sc_service.sc_service_instances, clear_int,
7305 	    (void *)offsetof(entity_t, sc_seen), UU_DEFAULT) != 0)
7306 		bad_error("uu_list_walk", uu_error());
7307 
7308 	/*
7309 	 * Take previous snapshots for all instances.  Even for ones not
7310 	 * mentioned in the bundle, since we might change their service
7311 	 * properties.
7312 	 */
7313 	if (scf_iter_service_instances(imp_iter, imp_svc) != 0) {
7314 		switch (scf_error()) {
7315 		case SCF_ERROR_CONNECTION_BROKEN:
7316 			goto connaborted;
7317 
7318 		case SCF_ERROR_DELETED:
7319 			warn(s_deleted, s->sc_fmri);
7320 			lcbdata->sc_err = EBUSY;
7321 			r = UU_WALK_ERROR;
7322 			goto deltemp;
7323 
7324 		case SCF_ERROR_HANDLE_MISMATCH:
7325 		case SCF_ERROR_NOT_BOUND:
7326 		case SCF_ERROR_NOT_SET:
7327 		default:
7328 			bad_error("scf_iter_service_instances", scf_error());
7329 		}
7330 	}
7331 
7332 	for (;;) {
7333 		r = scf_iter_next_instance(imp_iter, imp_inst);
7334 		if (r == 0)
7335 			break;
7336 		if (r != 1) {
7337 			switch (scf_error()) {
7338 			case SCF_ERROR_DELETED:
7339 				warn(s_deleted, s->sc_fmri);
7340 				lcbdata->sc_err = EBUSY;
7341 				r = UU_WALK_ERROR;
7342 				goto deltemp;
7343 
7344 			case SCF_ERROR_CONNECTION_BROKEN:
7345 				goto connaborted;
7346 
7347 			case SCF_ERROR_NOT_BOUND:
7348 			case SCF_ERROR_HANDLE_MISMATCH:
7349 			case SCF_ERROR_INVALID_ARGUMENT:
7350 			case SCF_ERROR_NOT_SET:
7351 			default:
7352 				bad_error("scf_iter_next_instance",
7353 				    scf_error());
7354 			}
7355 		}
7356 
7357 		if (scf_instance_get_name(imp_inst, imp_str, imp_str_sz) < 0) {
7358 			switch (scf_error()) {
7359 			case SCF_ERROR_DELETED:
7360 				continue;
7361 
7362 			case SCF_ERROR_CONNECTION_BROKEN:
7363 				goto connaborted;
7364 
7365 			case SCF_ERROR_NOT_SET:
7366 			case SCF_ERROR_NOT_BOUND:
7367 			default:
7368 				bad_error("scf_instance_get_name", scf_error());
7369 			}
7370 		}
7371 
7372 		if (g_verbose)
7373 			warn(gettext(
7374 			    "Taking \"%s\" snapshot for svc:/%s:%s.\n"),
7375 			    snap_previous, s->sc_name, imp_str);
7376 
7377 		r = take_snap(imp_inst, snap_previous, imp_snap);
7378 		switch (r) {
7379 		case 0:
7380 			break;
7381 
7382 		case ECANCELED:
7383 			continue;
7384 
7385 		case ECONNABORTED:
7386 			goto connaborted;
7387 
7388 		case EPERM:
7389 			warn(gettext("Could not take \"%s\" snapshot of "
7390 			    "svc:/%s:%s (permission denied).\n"),
7391 			    snap_previous, s->sc_name, imp_str);
7392 			lcbdata->sc_err = r;
7393 			return (UU_WALK_ERROR);
7394 
7395 		case ENOSPC:
7396 		case -1:
7397 			lcbdata->sc_err = r;
7398 			r = UU_WALK_ERROR;
7399 			goto deltemp;
7400 
7401 		default:
7402 			bad_error("take_snap", r);
7403 		}
7404 
7405 		linst.sc_name = imp_str;
7406 		inst = uu_list_find(s->sc_u.sc_service.sc_service_instances,
7407 		    &linst, NULL, NULL);
7408 		if (inst != NULL) {
7409 			inst->sc_import_state = IMPORT_PREVIOUS;
7410 			inst->sc_seen = 1;
7411 		}
7412 	}
7413 
7414 	/*
7415 	 * Create the new instances and take previous snapshots of
7416 	 * them.  This is not necessary, but it maximizes data preservation.
7417 	 */
7418 	for (inst = uu_list_first(s->sc_u.sc_service.sc_service_instances);
7419 	    inst != NULL;
7420 	    inst = uu_list_next(s->sc_u.sc_service.sc_service_instances,
7421 	    inst)) {
7422 		if (inst->sc_seen)
7423 			continue;
7424 
7425 		if (scf_service_add_instance(imp_svc, inst->sc_name,
7426 		    imp_inst) != 0) {
7427 			switch (scf_error()) {
7428 			case SCF_ERROR_CONNECTION_BROKEN:
7429 				goto connaborted;
7430 
7431 			case SCF_ERROR_BACKEND_READONLY:
7432 			case SCF_ERROR_BACKEND_ACCESS:
7433 			case SCF_ERROR_NO_RESOURCES:
7434 				r = stash_scferror(lcbdata);
7435 				goto deltemp;
7436 
7437 			case SCF_ERROR_EXISTS:
7438 				warn(gettext("%s changed unexpectedly "
7439 				    "(instance \"%s\" added).\n"), s->sc_fmri,
7440 				    inst->sc_name);
7441 				lcbdata->sc_err = EBUSY;
7442 				r = UU_WALK_ERROR;
7443 				goto deltemp;
7444 
7445 			case SCF_ERROR_INVALID_ARGUMENT:
7446 				warn(gettext("Service \"%s\" has instance with "
7447 				    "invalid name \"%s\".\n"), s->sc_name,
7448 				    inst->sc_name);
7449 				r = stash_scferror(lcbdata);
7450 				goto deltemp;
7451 
7452 			case SCF_ERROR_PERMISSION_DENIED:
7453 				warn(gettext("Could not create instance \"%s\" "
7454 				    "in %s (permission denied).\n"),
7455 				    inst->sc_name, s->sc_fmri);
7456 				r = stash_scferror(lcbdata);
7457 				goto deltemp;
7458 
7459 			case SCF_ERROR_HANDLE_MISMATCH:
7460 			case SCF_ERROR_NOT_BOUND:
7461 			case SCF_ERROR_NOT_SET:
7462 			default:
7463 				bad_error("scf_service_add_instance",
7464 				    scf_error());
7465 			}
7466 		}
7467 
7468 		if (g_verbose)
7469 			warn(gettext("Taking \"%s\" snapshot for "
7470 			    "new service %s.\n"), snap_previous, inst->sc_fmri);
7471 		r = take_snap(imp_inst, snap_previous, imp_snap);
7472 		switch (r) {
7473 		case 0:
7474 			break;
7475 
7476 		case ECANCELED:
7477 			warn(i_deleted, s->sc_fmri, inst->sc_name);
7478 			lcbdata->sc_err = EBUSY;
7479 			r = UU_WALK_ERROR;
7480 			goto deltemp;
7481 
7482 		case ECONNABORTED:
7483 			goto connaborted;
7484 
7485 		case EPERM:
7486 			warn(emsg_snap_perm, snap_previous, inst->sc_fmri);
7487 			lcbdata->sc_err = r;
7488 			r = UU_WALK_ERROR;
7489 			goto deltemp;
7490 
7491 		case ENOSPC:
7492 		case -1:
7493 			r = UU_WALK_ERROR;
7494 			goto deltemp;
7495 
7496 		default:
7497 			bad_error("take_snap", r);
7498 		}
7499 	}
7500 
7501 	s->sc_import_state = IMPORT_PREVIOUS;
7502 
7503 	/*
7504 	 * Upgrade service properties, if we can find a last-import snapshot.
7505 	 * Any will do because we don't support different service properties
7506 	 * in different manifests, so all snaplevels of the service in all of
7507 	 * the last-import snapshots of the instances should be the same.
7508 	 */
7509 	if (scf_iter_service_instances(imp_iter, imp_svc) != 0) {
7510 		switch (scf_error()) {
7511 		case SCF_ERROR_CONNECTION_BROKEN:
7512 			goto connaborted;
7513 
7514 		case SCF_ERROR_DELETED:
7515 			warn(s_deleted, s->sc_fmri);
7516 			lcbdata->sc_err = EBUSY;
7517 			r = UU_WALK_ERROR;
7518 			goto deltemp;
7519 
7520 		case SCF_ERROR_HANDLE_MISMATCH:
7521 		case SCF_ERROR_NOT_BOUND:
7522 		case SCF_ERROR_NOT_SET:
7523 		default:
7524 			bad_error("scf_iter_service_instances", scf_error());
7525 		}
7526 	}
7527 
7528 	for (;;) {
7529 		r = scf_iter_next_instance(imp_iter, imp_inst);
7530 		if (r == -1) {
7531 			switch (scf_error()) {
7532 			case SCF_ERROR_DELETED:
7533 				warn(s_deleted, s->sc_fmri);
7534 				lcbdata->sc_err = EBUSY;
7535 				r = UU_WALK_ERROR;
7536 				goto deltemp;
7537 
7538 			case SCF_ERROR_CONNECTION_BROKEN:
7539 				goto connaborted;
7540 
7541 			case SCF_ERROR_NOT_BOUND:
7542 			case SCF_ERROR_HANDLE_MISMATCH:
7543 			case SCF_ERROR_INVALID_ARGUMENT:
7544 			case SCF_ERROR_NOT_SET:
7545 			default:
7546 				bad_error("scf_iter_next_instance",
7547 				    scf_error());
7548 			}
7549 		}
7550 
7551 		if (r == 0) {
7552 			/*
7553 			 * Didn't find any last-import snapshots.  Override-
7554 			 * import the properties.  Unless one of the instances
7555 			 * has a general/enabled property, in which case we're
7556 			 * probably running a last-import-capable svccfg for
7557 			 * the first time, and we should only take the
7558 			 * last-import snapshot.
7559 			 */
7560 			if (have_ge) {
7561 				pgroup_t *mfpg;
7562 				scf_callback_t mfcbdata;
7563 
7564 				li_only = 1;
7565 				no_refresh = 1;
7566 				/*
7567 				 * Need to go ahead and import the manifestfiles
7568 				 * pg if it exists. If the last-import snapshot
7569 				 * upgrade code is ever removed this code can
7570 				 * be removed as well.
7571 				 */
7572 				mfpg = internal_pgroup_find(s,
7573 				    SCF_PG_MANIFESTFILES, SCF_GROUP_FRAMEWORK);
7574 
7575 				if (mfpg) {
7576 					mfcbdata.sc_handle = g_hndl;
7577 					mfcbdata.sc_parent = imp_svc;
7578 					mfcbdata.sc_service = 1;
7579 					mfcbdata.sc_flags = SCI_FORCE;
7580 					mfcbdata.sc_source_fmri = s->sc_fmri;
7581 					mfcbdata.sc_target_fmri = s->sc_fmri;
7582 					if (entity_pgroup_import(mfpg,
7583 					    &mfcbdata) != UU_WALK_NEXT) {
7584 						warn(s_mfile_upd, s->sc_fmri);
7585 						r = UU_WALK_ERROR;
7586 						goto deltemp;
7587 					}
7588 				}
7589 				break;
7590 			}
7591 
7592 			s->sc_import_state = IMPORT_PROP_BEGUN;
7593 
7594 			cbdata.sc_handle = g_hndl;
7595 			cbdata.sc_parent = imp_svc;
7596 			cbdata.sc_service = 1;
7597 			cbdata.sc_flags = SCI_FORCE;
7598 			cbdata.sc_source_fmri = s->sc_fmri;
7599 			cbdata.sc_target_fmri = s->sc_fmri;
7600 			if (uu_list_walk(s->sc_pgroups, entity_pgroup_import,
7601 			    &cbdata, UU_DEFAULT) != 0) {
7602 				if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7603 					bad_error("uu_list_walk", uu_error());
7604 				lcbdata->sc_err = cbdata.sc_err;
7605 				switch (cbdata.sc_err) {
7606 				case ECONNABORTED:
7607 					goto connaborted;
7608 
7609 				case ECANCELED:
7610 					warn(s_deleted, s->sc_fmri);
7611 					lcbdata->sc_err = EBUSY;
7612 					break;
7613 
7614 				case EINVAL:	/* caught above */
7615 				case EEXIST:
7616 					bad_error("entity_pgroup_import",
7617 					    cbdata.sc_err);
7618 				}
7619 
7620 				r = UU_WALK_ERROR;
7621 				goto deltemp;
7622 			}
7623 
7624 			cbdata.sc_trans = NULL;
7625 			cbdata.sc_flags = 0;
7626 			if (uu_list_walk(s->sc_dependents,
7627 			    lscf_dependent_import, &cbdata, UU_DEFAULT) != 0) {
7628 				if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7629 					bad_error("uu_list_walk", uu_error());
7630 				lcbdata->sc_err = cbdata.sc_err;
7631 				if (cbdata.sc_err == ECONNABORTED)
7632 					goto connaborted;
7633 				r = UU_WALK_ERROR;
7634 				goto deltemp;
7635 			}
7636 			break;
7637 		}
7638 
7639 		if (scf_instance_get_snapshot(imp_inst, snap_lastimport,
7640 		    imp_snap) != 0) {
7641 			switch (scf_error()) {
7642 			case SCF_ERROR_DELETED:
7643 				continue;
7644 
7645 			case SCF_ERROR_NOT_FOUND:
7646 				break;
7647 
7648 			case SCF_ERROR_CONNECTION_BROKEN:
7649 				goto connaborted;
7650 
7651 			case SCF_ERROR_HANDLE_MISMATCH:
7652 			case SCF_ERROR_NOT_BOUND:
7653 			case SCF_ERROR_INVALID_ARGUMENT:
7654 			case SCF_ERROR_NOT_SET:
7655 			default:
7656 				bad_error("scf_instance_get_snapshot",
7657 				    scf_error());
7658 			}
7659 
7660 			if (have_ge)
7661 				continue;
7662 
7663 			/*
7664 			 * Check for a general/enabled property.  This is how
7665 			 * we tell whether to import if there turn out to be
7666 			 * no last-import snapshots.
7667 			 */
7668 			if (scf_instance_get_pg(imp_inst, SCF_PG_GENERAL,
7669 			    imp_pg) == 0) {
7670 				if (scf_pg_get_property(imp_pg,
7671 				    SCF_PROPERTY_ENABLED, imp_prop) == 0) {
7672 					have_ge = 1;
7673 				} else {
7674 					switch (scf_error()) {
7675 					case SCF_ERROR_DELETED:
7676 					case SCF_ERROR_NOT_FOUND:
7677 						continue;
7678 
7679 					case SCF_ERROR_INVALID_ARGUMENT:
7680 					case SCF_ERROR_HANDLE_MISMATCH:
7681 					case SCF_ERROR_CONNECTION_BROKEN:
7682 					case SCF_ERROR_NOT_BOUND:
7683 					case SCF_ERROR_NOT_SET:
7684 					default:
7685 						bad_error("scf_pg_get_property",
7686 						    scf_error());
7687 					}
7688 				}
7689 			} else {
7690 				switch (scf_error()) {
7691 				case SCF_ERROR_DELETED:
7692 				case SCF_ERROR_NOT_FOUND:
7693 					continue;
7694 
7695 				case SCF_ERROR_CONNECTION_BROKEN:
7696 					goto connaborted;
7697 
7698 				case SCF_ERROR_NOT_BOUND:
7699 				case SCF_ERROR_NOT_SET:
7700 				case SCF_ERROR_INVALID_ARGUMENT:
7701 				case SCF_ERROR_HANDLE_MISMATCH:
7702 				default:
7703 					bad_error("scf_instance_get_pg",
7704 					    scf_error());
7705 				}
7706 			}
7707 			continue;
7708 		}
7709 
7710 		/* find service snaplevel */
7711 		r = get_snaplevel(imp_snap, 1, imp_snpl);
7712 		switch (r) {
7713 		case 0:
7714 			break;
7715 
7716 		case ECONNABORTED:
7717 			goto connaborted;
7718 
7719 		case ECANCELED:
7720 			continue;
7721 
7722 		case ENOENT:
7723 			if (scf_instance_get_name(imp_inst, imp_str,
7724 			    imp_str_sz) < 0)
7725 				(void) strcpy(imp_str, "?");
7726 			warn(badsnap, snap_lastimport, s->sc_name, imp_str);
7727 			lcbdata->sc_err = EBADF;
7728 			r = UU_WALK_ERROR;
7729 			goto deltemp;
7730 
7731 		default:
7732 			bad_error("get_snaplevel", r);
7733 		}
7734 
7735 		if (scf_instance_get_snapshot(imp_inst, snap_running,
7736 		    imp_rsnap) != 0) {
7737 			switch (scf_error()) {
7738 			case SCF_ERROR_DELETED:
7739 				continue;
7740 
7741 			case SCF_ERROR_NOT_FOUND:
7742 				break;
7743 
7744 			case SCF_ERROR_CONNECTION_BROKEN:
7745 				goto connaborted;
7746 
7747 			case SCF_ERROR_INVALID_ARGUMENT:
7748 			case SCF_ERROR_HANDLE_MISMATCH:
7749 			case SCF_ERROR_NOT_BOUND:
7750 			case SCF_ERROR_NOT_SET:
7751 			default:
7752 				bad_error("scf_instance_get_snapshot",
7753 				    scf_error());
7754 			}
7755 			running = NULL;
7756 		} else {
7757 			r = get_snaplevel(imp_rsnap, 1, imp_rsnpl);
7758 			switch (r) {
7759 			case 0:
7760 				running = imp_rsnpl;
7761 				break;
7762 
7763 			case ECONNABORTED:
7764 				goto connaborted;
7765 
7766 			case ECANCELED:
7767 				continue;
7768 
7769 			case ENOENT:
7770 				if (scf_instance_get_name(imp_inst, imp_str,
7771 				    imp_str_sz) < 0)
7772 					(void) strcpy(imp_str, "?");
7773 				warn(badsnap, snap_running, s->sc_name,
7774 				    imp_str);
7775 				lcbdata->sc_err = EBADF;
7776 				r = UU_WALK_ERROR;
7777 				goto deltemp;
7778 
7779 			default:
7780 				bad_error("get_snaplevel", r);
7781 			}
7782 		}
7783 
7784 		if (g_verbose) {
7785 			if (scf_instance_get_name(imp_inst, imp_str,
7786 			    imp_str_sz) < 0)
7787 				(void) strcpy(imp_str, "?");
7788 			warn(gettext("Upgrading properties of %s according to "
7789 			    "instance \"%s\".\n"), s->sc_fmri, imp_str);
7790 		}
7791 
7792 		/* upgrade service properties */
7793 		r = upgrade_props(imp_svc, running, imp_snpl, s);
7794 		if (r == 0)
7795 			break;
7796 
7797 		switch (r) {
7798 		case ECONNABORTED:
7799 			goto connaborted;
7800 
7801 		case ECANCELED:
7802 			warn(s_deleted, s->sc_fmri);
7803 			lcbdata->sc_err = EBUSY;
7804 			break;
7805 
7806 		case ENODEV:
7807 			if (scf_instance_get_name(imp_inst, imp_str,
7808 			    imp_str_sz) < 0)
7809 				(void) strcpy(imp_str, "?");
7810 			warn(i_deleted, s->sc_fmri, imp_str);
7811 			lcbdata->sc_err = EBUSY;
7812 			break;
7813 
7814 		default:
7815 			lcbdata->sc_err = r;
7816 		}
7817 
7818 		r = UU_WALK_ERROR;
7819 		goto deltemp;
7820 	}
7821 
7822 	s->sc_import_state = IMPORT_PROP_DONE;
7823 
7824 instances:
7825 	/* import instances */
7826 	cbdata.sc_handle = lcbdata->sc_handle;
7827 	cbdata.sc_parent = imp_svc;
7828 	cbdata.sc_service = 1;
7829 	cbdata.sc_flags = lcbdata->sc_flags | (fresh ? SCI_FRESH : 0);
7830 	cbdata.sc_general = NULL;
7831 
7832 	if (uu_list_walk(s->sc_u.sc_service.sc_service_instances,
7833 	    lscf_instance_import, &cbdata, UU_DEFAULT) != 0) {
7834 		if (uu_error() != UU_ERROR_CALLBACK_FAILED)
7835 			bad_error("uu_list_walk", uu_error());
7836 
7837 		lcbdata->sc_err = cbdata.sc_err;
7838 		if (cbdata.sc_err == ECONNABORTED)
7839 			goto connaborted;
7840 		r = UU_WALK_ERROR;
7841 		goto deltemp;
7842 	}
7843 
7844 	s->sc_import_state = IMPORT_COMPLETE;
7845 	r = UU_WALK_NEXT;
7846 
7847 deltemp:
7848 	/* delete temporary service */
7849 	if (scf_service_delete(imp_tsvc) != 0) {
7850 		switch (scf_error()) {
7851 		case SCF_ERROR_DELETED:
7852 			break;
7853 
7854 		case SCF_ERROR_CONNECTION_BROKEN:
7855 			goto connaborted;
7856 
7857 		case SCF_ERROR_EXISTS:
7858 			warn(gettext(
7859 			    "Could not delete svc:/%s (instances exist).\n"),
7860 			    imp_tsname);
7861 			break;
7862 
7863 		case SCF_ERROR_NOT_SET:
7864 		case SCF_ERROR_NOT_BOUND:
7865 		default:
7866 			bad_error("scf_service_delete", scf_error());
7867 		}
7868 	}
7869 
7870 	return (r);
7871 
7872 connaborted:
7873 	warn(gettext("Could not delete svc:/%s "
7874 	    "(repository connection broken).\n"), imp_tsname);
7875 	lcbdata->sc_err = ECONNABORTED;
7876 	return (UU_WALK_ERROR);
7877 }
7878 
7879 static const char *
7880 import_progress(int st)
7881 {
7882 	switch (st) {
7883 	case 0:
7884 		return (gettext("not reached."));
7885 
7886 	case IMPORT_PREVIOUS:
7887 		return (gettext("previous snapshot taken."));
7888 
7889 	case IMPORT_PROP_BEGUN:
7890 		return (gettext("some properties imported."));
7891 
7892 	case IMPORT_PROP_DONE:
7893 		return (gettext("properties imported."));
7894 
7895 	case IMPORT_COMPLETE:
7896 		return (gettext("imported."));
7897 
7898 	case IMPORT_REFRESHED:
7899 		return (gettext("refresh requested."));
7900 
7901 	default:
7902 #ifndef NDEBUG
7903 		(void) fprintf(stderr, "%s:%d: Unknown entity state %d.\n",
7904 		    __FILE__, __LINE__, st);
7905 #endif
7906 		abort();
7907 		/* NOTREACHED */
7908 	}
7909 }
7910 
7911 /*
7912  * Returns
7913  *   0 - success
7914  *     - fmri wasn't found (error printed)
7915  *     - entity was deleted (error printed)
7916  *     - backend denied access (error printed)
7917  *   ENOMEM - out of memory (error printed)
7918  *   ECONNABORTED - repository connection broken (error printed)
7919  *   EPERM - permission denied (error printed)
7920  *   -1 - unknown libscf error (error printed)
7921  */
7922 static int
7923 imp_refresh_fmri(const char *fmri, const char *name, const char *d_fmri)
7924 {
7925 	scf_error_t serr;
7926 	void *ent;
7927 	int issvc;
7928 	int r;
7929 
7930 	const char *deleted = gettext("Could not refresh %s (deleted).\n");
7931 	const char *dpt_deleted = gettext("Could not refresh %s "
7932 	    "(dependent \"%s\" of %s) (deleted).\n");
7933 
7934 	serr = fmri_to_entity(g_hndl, fmri, &ent, &issvc);
7935 	switch (serr) {
7936 	case SCF_ERROR_NONE:
7937 		break;
7938 
7939 	case SCF_ERROR_NO_MEMORY:
7940 		if (name == NULL)
7941 			warn(gettext("Could not refresh %s (out of memory).\n"),
7942 			    fmri);
7943 		else
7944 			warn(gettext("Could not refresh %s "
7945 			    "(dependent \"%s\" of %s) (out of memory).\n"),
7946 			    fmri, name, d_fmri);
7947 		return (ENOMEM);
7948 
7949 	case SCF_ERROR_NOT_FOUND:
7950 		if (name == NULL)
7951 			warn(deleted, fmri);
7952 		else
7953 			warn(dpt_deleted, fmri, name, d_fmri);
7954 		return (0);
7955 
7956 	case SCF_ERROR_INVALID_ARGUMENT:
7957 	case SCF_ERROR_CONSTRAINT_VIOLATED:
7958 	default:
7959 		bad_error("fmri_to_entity", serr);
7960 	}
7961 
7962 	r = refresh_entity(issvc, ent, fmri, imp_inst, imp_iter, imp_str);
7963 	switch (r) {
7964 	case 0:
7965 		break;
7966 
7967 	case ECONNABORTED:
7968 		if (name != NULL)
7969 			warn(gettext("Could not refresh %s "
7970 			    "(dependent \"%s\" of %s) "
7971 			    "(repository connection broken).\n"), fmri, name,
7972 			    d_fmri);
7973 		return (r);
7974 
7975 	case ECANCELED:
7976 		if (name == NULL)
7977 			warn(deleted, fmri);
7978 		else
7979 			warn(dpt_deleted, fmri, name, d_fmri);
7980 		return (0);
7981 
7982 	case EACCES:
7983 		if (!g_verbose)
7984 			return (0);
7985 		if (name == NULL)
7986 			warn(gettext("Could not refresh %s "
7987 			    "(backend access denied).\n"), fmri);
7988 		else
7989 			warn(gettext("Could not refresh %s "
7990 			    "(dependent \"%s\" of %s) "
7991 			    "(backend access denied).\n"), fmri, name, d_fmri);
7992 		return (0);
7993 
7994 	case EPERM:
7995 		if (name == NULL)
7996 			warn(gettext("Could not refresh %s "
7997 			    "(permission denied).\n"), fmri);
7998 		else
7999 			warn(gettext("Could not refresh %s "
8000 			    "(dependent \"%s\" of %s) "
8001 			    "(permission denied).\n"), fmri, name, d_fmri);
8002 		return (r);
8003 
8004 	case ENOSPC:
8005 		if (name == NULL)
8006 			warn(gettext("Could not refresh %s "
8007 			    "(repository server out of resources).\n"),
8008 			    fmri);
8009 		else
8010 			warn(gettext("Could not refresh %s "
8011 			    "(dependent \"%s\" of %s) "
8012 			    "(repository server out of resources).\n"),
8013 			    fmri, name, d_fmri);
8014 		return (r);
8015 
8016 	case -1:
8017 		scfwarn();
8018 		return (r);
8019 
8020 	default:
8021 		bad_error("refresh_entity", r);
8022 	}
8023 
8024 	if (issvc)
8025 		scf_service_destroy(ent);
8026 	else
8027 		scf_instance_destroy(ent);
8028 
8029 	return (0);
8030 }
8031 
8032 static int
8033 alloc_imp_globals()
8034 {
8035 	int r;
8036 
8037 	const char * const emsg_nomem = gettext("Out of memory.\n");
8038 	const char * const emsg_nores =
8039 	    gettext("svc.configd is out of resources.\n");
8040 
8041 	imp_str_sz = ((max_scf_name_len > max_scf_fmri_len) ?
8042 	    max_scf_name_len : max_scf_fmri_len) + 1;
8043 
8044 	if ((imp_scope = scf_scope_create(g_hndl)) == NULL ||
8045 	    (imp_svc = scf_service_create(g_hndl)) == NULL ||
8046 	    (imp_tsvc = scf_service_create(g_hndl)) == NULL ||
8047 	    (imp_inst = scf_instance_create(g_hndl)) == NULL ||
8048 	    (imp_tinst = scf_instance_create(g_hndl)) == NULL ||
8049 	    (imp_snap = scf_snapshot_create(g_hndl)) == NULL ||
8050 	    (imp_lisnap = scf_snapshot_create(g_hndl)) == NULL ||
8051 	    (imp_tlisnap = scf_snapshot_create(g_hndl)) == NULL ||
8052 	    (imp_rsnap = scf_snapshot_create(g_hndl)) == NULL ||
8053 	    (imp_snpl = scf_snaplevel_create(g_hndl)) == NULL ||
8054 	    (imp_rsnpl = scf_snaplevel_create(g_hndl)) == NULL ||
8055 	    (imp_pg = scf_pg_create(g_hndl)) == NULL ||
8056 	    (imp_pg2 = scf_pg_create(g_hndl)) == NULL ||
8057 	    (imp_prop = scf_property_create(g_hndl)) == NULL ||
8058 	    (imp_iter = scf_iter_create(g_hndl)) == NULL ||
8059 	    (imp_rpg_iter = scf_iter_create(g_hndl)) == NULL ||
8060 	    (imp_up_iter = scf_iter_create(g_hndl)) == NULL ||
8061 	    (imp_tx = scf_transaction_create(g_hndl)) == NULL ||
8062 	    (imp_str = malloc(imp_str_sz)) == NULL ||
8063 	    (imp_tsname = malloc(max_scf_name_len + 1)) == NULL ||
8064 	    (imp_fe1 = malloc(max_scf_fmri_len + 1)) == NULL ||
8065 	    (imp_fe2 = malloc(max_scf_fmri_len + 1)) == NULL ||
8066 	    (imp_deleted_dpts = uu_list_create(string_pool, NULL, 0)) == NULL ||
8067 	    (ud_inst = scf_instance_create(g_hndl)) == NULL ||
8068 	    (ud_snpl = scf_snaplevel_create(g_hndl)) == NULL ||
8069 	    (ud_pg = scf_pg_create(g_hndl)) == NULL ||
8070 	    (ud_cur_depts_pg = scf_pg_create(g_hndl)) == NULL ||
8071 	    (ud_run_dpts_pg = scf_pg_create(g_hndl)) == NULL ||
8072 	    (ud_prop = scf_property_create(g_hndl)) == NULL ||
8073 	    (ud_dpt_prop = scf_property_create(g_hndl)) == NULL ||
8074 	    (ud_val = scf_value_create(g_hndl)) == NULL ||
8075 	    (ud_iter = scf_iter_create(g_hndl)) == NULL ||
8076 	    (ud_iter2 = scf_iter_create(g_hndl)) == NULL ||
8077 	    (ud_tx = scf_transaction_create(g_hndl)) == NULL ||
8078 	    (ud_ctarg = malloc(max_scf_value_len + 1)) == NULL ||
8079 	    (ud_oldtarg = malloc(max_scf_value_len + 1)) == NULL ||
8080 	    (ud_name = malloc(max_scf_name_len + 1)) == NULL) {
8081 		if (scf_error() == SCF_ERROR_NO_RESOURCES)
8082 			warn(emsg_nores);
8083 		else
8084 			warn(emsg_nomem);
8085 
8086 		return (-1);
8087 	}
8088 
8089 	r = load_init();
8090 	switch (r) {
8091 	case 0:
8092 		break;
8093 
8094 	case ENOMEM:
8095 		warn(emsg_nomem);
8096 		return (-1);
8097 
8098 	default:
8099 		bad_error("load_init", r);
8100 	}
8101 
8102 	return (0);
8103 }
8104 
8105 static void
8106 free_imp_globals()
8107 {
8108 	pgroup_t *old_dpt;
8109 	void *cookie;
8110 
8111 	load_fini();
8112 
8113 	free(ud_ctarg);
8114 	free(ud_oldtarg);
8115 	free(ud_name);
8116 	ud_ctarg = ud_oldtarg = ud_name = NULL;
8117 
8118 	scf_transaction_destroy(ud_tx);
8119 	ud_tx = NULL;
8120 	scf_iter_destroy(ud_iter);
8121 	scf_iter_destroy(ud_iter2);
8122 	ud_iter = ud_iter2 = NULL;
8123 	scf_value_destroy(ud_val);
8124 	ud_val = NULL;
8125 	scf_property_destroy(ud_prop);
8126 	scf_property_destroy(ud_dpt_prop);
8127 	ud_prop = ud_dpt_prop = NULL;
8128 	scf_pg_destroy(ud_pg);
8129 	scf_pg_destroy(ud_cur_depts_pg);
8130 	scf_pg_destroy(ud_run_dpts_pg);
8131 	ud_pg = ud_cur_depts_pg = ud_run_dpts_pg = NULL;
8132 	scf_snaplevel_destroy(ud_snpl);
8133 	ud_snpl = NULL;
8134 	scf_instance_destroy(ud_inst);
8135 	ud_inst = NULL;
8136 
8137 	free(imp_str);
8138 	free(imp_tsname);
8139 	free(imp_fe1);
8140 	free(imp_fe2);
8141 	imp_str = imp_tsname = imp_fe1 = imp_fe2 = NULL;
8142 
8143 	cookie = NULL;
8144 	while ((old_dpt = uu_list_teardown(imp_deleted_dpts, &cookie)) !=
8145 	    NULL) {
8146 		free((char *)old_dpt->sc_pgroup_name);
8147 		free((char *)old_dpt->sc_pgroup_fmri);
8148 		internal_pgroup_free(old_dpt);
8149 	}
8150 	uu_list_destroy(imp_deleted_dpts);
8151 
8152 	scf_transaction_destroy(imp_tx);
8153 	imp_tx = NULL;
8154 	scf_iter_destroy(imp_iter);
8155 	scf_iter_destroy(imp_rpg_iter);
8156 	scf_iter_destroy(imp_up_iter);
8157 	imp_iter = imp_rpg_iter = imp_up_iter = NULL;
8158 	scf_property_destroy(imp_prop);
8159 	imp_prop = NULL;
8160 	scf_pg_destroy(imp_pg);
8161 	scf_pg_destroy(imp_pg2);
8162 	imp_pg = imp_pg2 = NULL;
8163 	scf_snaplevel_destroy(imp_snpl);
8164 	scf_snaplevel_destroy(imp_rsnpl);
8165 	imp_snpl = imp_rsnpl = NULL;
8166 	scf_snapshot_destroy(imp_snap);
8167 	scf_snapshot_destroy(imp_lisnap);
8168 	scf_snapshot_destroy(imp_tlisnap);
8169 	scf_snapshot_destroy(imp_rsnap);
8170 	imp_snap = imp_lisnap = imp_tlisnap = imp_rsnap = NULL;
8171 	scf_instance_destroy(imp_inst);
8172 	scf_instance_destroy(imp_tinst);
8173 	imp_inst = imp_tinst = NULL;
8174 	scf_service_destroy(imp_svc);
8175 	scf_service_destroy(imp_tsvc);
8176 	imp_svc = imp_tsvc = NULL;
8177 	scf_scope_destroy(imp_scope);
8178 	imp_scope = NULL;
8179 
8180 	load_fini();
8181 }
8182 
8183 int
8184 lscf_bundle_import(bundle_t *bndl, const char *filename, uint_t flags)
8185 {
8186 	scf_callback_t cbdata;
8187 	int result = 0;
8188 	entity_t *svc, *inst;
8189 	uu_list_t *insts;
8190 	int r;
8191 	pgroup_t *old_dpt;
8192 	int annotation_set = 0;
8193 
8194 	const char * const emsg_nomem = gettext("Out of memory.\n");
8195 	const char * const emsg_nores =
8196 	    gettext("svc.configd is out of resources.\n");
8197 
8198 	lscf_prep_hndl();
8199 
8200 	if (alloc_imp_globals())
8201 		goto out;
8202 
8203 	if (scf_handle_get_scope(g_hndl, SCF_SCOPE_LOCAL, imp_scope) != 0) {
8204 		switch (scf_error()) {
8205 		case SCF_ERROR_CONNECTION_BROKEN:
8206 			warn(gettext("Repository connection broken.\n"));
8207 			repository_teardown();
8208 			result = -1;
8209 			goto out;
8210 
8211 		case SCF_ERROR_NOT_FOUND:
8212 		case SCF_ERROR_INVALID_ARGUMENT:
8213 		case SCF_ERROR_NOT_BOUND:
8214 		case SCF_ERROR_HANDLE_MISMATCH:
8215 		default:
8216 			bad_error("scf_handle_get_scope", scf_error());
8217 		}
8218 	}
8219 
8220 	/* Set up the auditing annotation. */
8221 	if (_scf_set_annotation(g_hndl, "svccfg import", filename) == 0) {
8222 		annotation_set = 1;
8223 	} else {
8224 		switch (scf_error()) {
8225 		case SCF_ERROR_CONNECTION_BROKEN:
8226 			warn(gettext("Repository connection broken.\n"));
8227 			repository_teardown();
8228 			result = -1;
8229 			goto out;
8230 
8231 		case SCF_ERROR_INVALID_ARGUMENT:
8232 		case SCF_ERROR_NOT_BOUND:
8233 		case SCF_ERROR_NO_RESOURCES:
8234 		case SCF_ERROR_INTERNAL:
8235 			bad_error("_scf_set_annotation", scf_error());
8236 			/* NOTREACHED */
8237 
8238 		default:
8239 			/*
8240 			 * Do not terminate import because of inability to
8241 			 * generate annotation audit event.
8242 			 */
8243 			warn(gettext("_scf_set_annotation() unexpectedly "
8244 			    "failed with return code of %d\n"), scf_error());
8245 			break;
8246 		}
8247 	}
8248 
8249 	/*
8250 	 * Clear the sc_import_state's of all services & instances so we can
8251 	 * report how far we got if we fail.
8252 	 */
8253 	for (svc = uu_list_first(bndl->sc_bundle_services);
8254 	    svc != NULL;
8255 	    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8256 		svc->sc_import_state = 0;
8257 
8258 		if (uu_list_walk(svc->sc_u.sc_service.sc_service_instances,
8259 		    clear_int, (void *)offsetof(entity_t, sc_import_state),
8260 		    UU_DEFAULT) != 0)
8261 			bad_error("uu_list_walk", uu_error());
8262 	}
8263 
8264 	cbdata.sc_handle = g_hndl;
8265 	cbdata.sc_parent = imp_scope;
8266 	cbdata.sc_flags = flags;
8267 	cbdata.sc_general = NULL;
8268 
8269 	if (uu_list_walk(bndl->sc_bundle_services, lscf_service_import,
8270 	    &cbdata, UU_DEFAULT) == 0) {
8271 		char *eptr;
8272 		/* Success.  Refresh everything. */
8273 
8274 		if (flags & SCI_NOREFRESH || no_refresh) {
8275 			no_refresh = 0;
8276 			result = 0;
8277 			goto out;
8278 		}
8279 
8280 		for (svc = uu_list_first(bndl->sc_bundle_services);
8281 		    svc != NULL;
8282 		    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8283 			pgroup_t *dpt;
8284 
8285 			insts = svc->sc_u.sc_service.sc_service_instances;
8286 
8287 			for (inst = uu_list_first(insts);
8288 			    inst != NULL;
8289 			    inst = uu_list_next(insts, inst)) {
8290 				r = imp_refresh_fmri(inst->sc_fmri, NULL, NULL);
8291 				switch (r) {
8292 				case 0:
8293 					break;
8294 
8295 				case ENOMEM:
8296 				case ECONNABORTED:
8297 				case EPERM:
8298 				case -1:
8299 					goto progress;
8300 
8301 				default:
8302 					bad_error("imp_refresh_fmri", r);
8303 				}
8304 
8305 				inst->sc_import_state = IMPORT_REFRESHED;
8306 
8307 				for (dpt = uu_list_first(inst->sc_dependents);
8308 				    dpt != NULL;
8309 				    dpt = uu_list_next(inst->sc_dependents,
8310 				    dpt))
8311 					if (imp_refresh_fmri(
8312 					    dpt->sc_pgroup_fmri,
8313 					    dpt->sc_pgroup_name,
8314 					    inst->sc_fmri) != 0)
8315 						goto progress;
8316 			}
8317 
8318 			for (dpt = uu_list_first(svc->sc_dependents);
8319 			    dpt != NULL;
8320 			    dpt = uu_list_next(svc->sc_dependents, dpt))
8321 				if (imp_refresh_fmri(dpt->sc_pgroup_fmri,
8322 				    dpt->sc_pgroup_name, svc->sc_fmri) != 0)
8323 					goto progress;
8324 		}
8325 
8326 		for (old_dpt = uu_list_first(imp_deleted_dpts);
8327 		    old_dpt != NULL;
8328 		    old_dpt = uu_list_next(imp_deleted_dpts, old_dpt))
8329 			if (imp_refresh_fmri(old_dpt->sc_pgroup_fmri,
8330 			    old_dpt->sc_pgroup_name,
8331 			    old_dpt->sc_parent->sc_fmri) != 0)
8332 				goto progress;
8333 
8334 		result = 0;
8335 
8336 		/*
8337 		 * This snippet of code assumes that we are running svccfg as we
8338 		 * normally do -- witih svc.startd running. Of course, that is
8339 		 * not actually the case all the time because we also use a
8340 		 * varient of svc.configd and svccfg which are only meant to
8341 		 * run during the build process. During this time we have no
8342 		 * svc.startd, so this check would hang the build process.
8343 		 *
8344 		 * However, we've also given other consolidations, a bit of a
8345 		 * means to tie themselves into a knot. They're not properly
8346 		 * using the native build equivalents, but they've been getting
8347 		 * away with it anyways. Therefore, if we've found that
8348 		 * SVCCFG_REPOSITORY is set indicating that a separate configd
8349 		 * should be spun up, then we have to assume it's not using a
8350 		 * startd and we should not do this check.
8351 		 */
8352 #ifndef NATIVE_BUILD
8353 		/*
8354 		 * Verify that the restarter group is preset
8355 		 */
8356 		eptr = getenv("SVCCFG_REPOSITORY");
8357 		for (svc = uu_list_first(bndl->sc_bundle_services);
8358 		    svc != NULL && eptr == NULL;
8359 		    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8360 
8361 			insts = svc->sc_u.sc_service.sc_service_instances;
8362 
8363 			for (inst = uu_list_first(insts);
8364 			    inst != NULL;
8365 			    inst = uu_list_next(insts, inst)) {
8366 				if (lscf_instance_verify(imp_scope, svc,
8367 				    inst) != 0)
8368 					goto progress;
8369 			}
8370 		}
8371 #endif
8372 		goto out;
8373 
8374 	}
8375 
8376 	if (uu_error() != UU_ERROR_CALLBACK_FAILED)
8377 		bad_error("uu_list_walk", uu_error());
8378 
8379 printerr:
8380 	/* If the error hasn't been printed yet, do so here. */
8381 	switch (cbdata.sc_err) {
8382 	case ECONNABORTED:
8383 		warn(gettext("Repository connection broken.\n"));
8384 		break;
8385 
8386 	case ENOMEM:
8387 		warn(emsg_nomem);
8388 		break;
8389 
8390 	case ENOSPC:
8391 		warn(emsg_nores);
8392 		break;
8393 
8394 	case EROFS:
8395 		warn(gettext("Repository is read-only.\n"));
8396 		break;
8397 
8398 	case EACCES:
8399 		warn(gettext("Repository backend denied access.\n"));
8400 		break;
8401 
8402 	case EPERM:
8403 	case EINVAL:
8404 	case EEXIST:
8405 	case EBUSY:
8406 	case EBADF:
8407 	case -1:
8408 		break;
8409 
8410 	default:
8411 		bad_error("lscf_service_import", cbdata.sc_err);
8412 	}
8413 
8414 progress:
8415 	warn(gettext("Import of %s failed.  Progress:\n"), filename);
8416 
8417 	for (svc = uu_list_first(bndl->sc_bundle_services);
8418 	    svc != NULL;
8419 	    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8420 		insts = svc->sc_u.sc_service.sc_service_instances;
8421 
8422 		warn(gettext("  Service \"%s\": %s\n"), svc->sc_name,
8423 		    import_progress(svc->sc_import_state));
8424 
8425 		for (inst = uu_list_first(insts);
8426 		    inst != NULL;
8427 		    inst = uu_list_next(insts, inst))
8428 			warn(gettext("    Instance \"%s\": %s\n"),
8429 			    inst->sc_name,
8430 			    import_progress(inst->sc_import_state));
8431 	}
8432 
8433 	if (cbdata.sc_err == ECONNABORTED)
8434 		repository_teardown();
8435 
8436 
8437 	result = -1;
8438 
8439 out:
8440 	if (annotation_set != 0) {
8441 		/* Turn off annotation.  It is no longer needed. */
8442 		(void) _scf_set_annotation(g_hndl, NULL, NULL);
8443 	}
8444 
8445 	free_imp_globals();
8446 
8447 	return (result);
8448 }
8449 
8450 /*
8451  * _lscf_import_err() summarize the error handling returned by
8452  * lscf_import_{instance | service}_pgs
8453  * Return values are:
8454  * IMPORT_NEXT
8455  * IMPORT_OUT
8456  * IMPORT_BAD
8457  */
8458 
8459 #define	IMPORT_BAD	-1
8460 #define	IMPORT_NEXT	0
8461 #define	IMPORT_OUT	1
8462 
8463 static int
8464 _lscf_import_err(int err, const char *fmri)
8465 {
8466 	switch (err) {
8467 	case 0:
8468 		if (g_verbose)
8469 			warn(gettext("%s updated.\n"), fmri);
8470 		return (IMPORT_NEXT);
8471 
8472 	case ECONNABORTED:
8473 		warn(gettext("Could not update %s "
8474 		    "(repository connection broken).\n"), fmri);
8475 		return (IMPORT_OUT);
8476 
8477 	case ENOMEM:
8478 		warn(gettext("Could not update %s (out of memory).\n"), fmri);
8479 		return (IMPORT_OUT);
8480 
8481 	case ENOSPC:
8482 		warn(gettext("Could not update %s "
8483 		    "(repository server out of resources).\n"), fmri);
8484 		return (IMPORT_OUT);
8485 
8486 	case ECANCELED:
8487 		warn(gettext(
8488 		    "Could not update %s (deleted).\n"), fmri);
8489 		return (IMPORT_NEXT);
8490 
8491 	case EPERM:
8492 	case EINVAL:
8493 	case EBUSY:
8494 		return (IMPORT_NEXT);
8495 
8496 	case EROFS:
8497 		warn(gettext("Could not update %s (repository read-only).\n"),
8498 		    fmri);
8499 		return (IMPORT_OUT);
8500 
8501 	case EACCES:
8502 		warn(gettext("Could not update %s "
8503 		    "(backend access denied).\n"), fmri);
8504 		return (IMPORT_NEXT);
8505 
8506 	case EEXIST:
8507 	default:
8508 		return (IMPORT_BAD);
8509 	}
8510 
8511 	/*NOTREACHED*/
8512 }
8513 
8514 /*
8515  * The global imp_svc and imp_inst should be set by the caller in the
8516  * check to make sure the service and instance exist that the apply is
8517  * working on.
8518  */
8519 static int
8520 lscf_dependent_apply(void *dpg, void *e)
8521 {
8522 	scf_callback_t cb;
8523 	pgroup_t *dpt_pgroup = dpg;
8524 	pgroup_t *deldpt;
8525 	entity_t *ent = e;
8526 	int tissvc;
8527 	void *sc_ent, *tent;
8528 	scf_error_t serr;
8529 	int r;
8530 
8531 	const char * const dependents = "dependents";
8532 	const int issvc = (ent->sc_etype == SVCCFG_SERVICE_OBJECT);
8533 
8534 	if (issvc)
8535 		sc_ent = imp_svc;
8536 	else
8537 		sc_ent = imp_inst;
8538 
8539 	if (entity_get_running_pg(sc_ent, issvc, dependents, imp_pg,
8540 	    imp_iter, imp_tinst, imp_snap, imp_snpl) != 0 ||
8541 	    scf_pg_get_property(imp_pg, dpt_pgroup->sc_pgroup_name,
8542 	    imp_prop) != 0) {
8543 		switch (scf_error()) {
8544 		case SCF_ERROR_NOT_FOUND:
8545 		case SCF_ERROR_DELETED:
8546 			break;
8547 
8548 		case SCF_ERROR_CONNECTION_BROKEN:
8549 		case SCF_ERROR_NOT_SET:
8550 		case SCF_ERROR_INVALID_ARGUMENT:
8551 		case SCF_ERROR_HANDLE_MISMATCH:
8552 		case SCF_ERROR_NOT_BOUND:
8553 		default:
8554 			bad_error("entity_get_pg", scf_error());
8555 		}
8556 	} else {
8557 		/*
8558 		 * Found the dependents/<wip dep> so check to
8559 		 * see if the service is different.  If so
8560 		 * store the service for later refresh, and
8561 		 * delete the wip dependency from the service
8562 		 */
8563 		if (scf_property_get_value(imp_prop, ud_val) != 0) {
8564 			switch (scf_error()) {
8565 				case SCF_ERROR_DELETED:
8566 					break;
8567 
8568 				case SCF_ERROR_CONNECTION_BROKEN:
8569 				case SCF_ERROR_NOT_SET:
8570 				case SCF_ERROR_INVALID_ARGUMENT:
8571 				case SCF_ERROR_HANDLE_MISMATCH:
8572 				case SCF_ERROR_NOT_BOUND:
8573 				default:
8574 					bad_error("scf_property_get_value",
8575 					    scf_error());
8576 			}
8577 		}
8578 
8579 		if (scf_value_get_as_string(ud_val, ud_oldtarg,
8580 		    max_scf_value_len + 1) < 0)
8581 			bad_error("scf_value_get_as_string", scf_error());
8582 
8583 		r = fmri_equal(dpt_pgroup->sc_pgroup_fmri, ud_oldtarg);
8584 		switch (r) {
8585 		case 1:
8586 			break;
8587 		case 0:
8588 			if ((serr = fmri_to_entity(g_hndl, ud_oldtarg, &tent,
8589 			    &tissvc)) != SCF_ERROR_NONE) {
8590 				if (serr == SCF_ERROR_NOT_FOUND) {
8591 					break;
8592 				} else {
8593 					bad_error("fmri_to_entity", serr);
8594 				}
8595 			}
8596 
8597 			if (entity_get_pg(tent, tissvc,
8598 			    dpt_pgroup->sc_pgroup_name, imp_pg) != 0) {
8599 				serr = scf_error();
8600 				if (serr == SCF_ERROR_NOT_FOUND ||
8601 				    serr == SCF_ERROR_DELETED) {
8602 					break;
8603 				} else {
8604 					bad_error("entity_get_pg", scf_error());
8605 				}
8606 			}
8607 
8608 			if (scf_pg_delete(imp_pg) != 0) {
8609 				serr = scf_error();
8610 				if (serr == SCF_ERROR_NOT_FOUND ||
8611 				    serr == SCF_ERROR_DELETED) {
8612 					break;
8613 				} else {
8614 					bad_error("scf_pg_delete", scf_error());
8615 				}
8616 			}
8617 
8618 			deldpt = internal_pgroup_new();
8619 			if (deldpt == NULL)
8620 				return (ENOMEM);
8621 			deldpt->sc_pgroup_name =
8622 			    strdup(dpt_pgroup->sc_pgroup_name);
8623 			deldpt->sc_pgroup_fmri = strdup(ud_oldtarg);
8624 			if (deldpt->sc_pgroup_name == NULL ||
8625 			    deldpt->sc_pgroup_fmri == NULL)
8626 				return (ENOMEM);
8627 			deldpt->sc_parent = (entity_t *)ent;
8628 			if (uu_list_insert_after(imp_deleted_dpts, NULL,
8629 			    deldpt) != 0)
8630 				uu_die(gettext("libuutil error: %s\n"),
8631 				    uu_strerror(uu_error()));
8632 
8633 			break;
8634 		default:
8635 			bad_error("fmri_equal", r);
8636 		}
8637 	}
8638 
8639 	cb.sc_handle = g_hndl;
8640 	cb.sc_parent = ent;
8641 	cb.sc_service = ent->sc_etype == SVCCFG_SERVICE_OBJECT;
8642 	cb.sc_source_fmri = ent->sc_fmri;
8643 	cb.sc_target_fmri = ent->sc_fmri;
8644 	cb.sc_trans = NULL;
8645 	cb.sc_flags = SCI_FORCE;
8646 
8647 	if (lscf_dependent_import(dpt_pgroup, &cb) != UU_WALK_NEXT)
8648 		return (UU_WALK_ERROR);
8649 
8650 	r = imp_refresh_fmri(dpt_pgroup->sc_pgroup_fmri, NULL, NULL);
8651 	switch (r) {
8652 	case 0:
8653 		break;
8654 
8655 	case ENOMEM:
8656 	case ECONNABORTED:
8657 	case EPERM:
8658 	case -1:
8659 		warn(gettext("Unable to refresh \"%s\"\n"),
8660 		    dpt_pgroup->sc_pgroup_fmri);
8661 		return (UU_WALK_ERROR);
8662 
8663 	default:
8664 		bad_error("imp_refresh_fmri", r);
8665 	}
8666 
8667 	return (UU_WALK_NEXT);
8668 }
8669 
8670 /*
8671  * Returns
8672  *   0 - success
8673  *   -1 - lscf_import_instance_pgs() failed.
8674  */
8675 int
8676 lscf_bundle_apply(bundle_t *bndl, const char *file)
8677 {
8678 	pgroup_t *old_dpt;
8679 	entity_t *svc, *inst;
8680 	int annotation_set = 0;
8681 	int ret = 0;
8682 	int r = 0;
8683 
8684 	lscf_prep_hndl();
8685 
8686 	if ((ret = alloc_imp_globals()))
8687 		goto out;
8688 
8689 	if (scf_handle_get_scope(g_hndl, SCF_SCOPE_LOCAL, imp_scope) != 0)
8690 		scfdie();
8691 
8692 	/*
8693 	 * Set the strings to be used for the security audit annotation
8694 	 * event.
8695 	 */
8696 	if (_scf_set_annotation(g_hndl, "svccfg apply", file) == 0) {
8697 		annotation_set = 1;
8698 	} else {
8699 		switch (scf_error()) {
8700 		case SCF_ERROR_CONNECTION_BROKEN:
8701 			warn(gettext("Repository connection broken.\n"));
8702 			goto out;
8703 
8704 		case SCF_ERROR_INVALID_ARGUMENT:
8705 		case SCF_ERROR_NOT_BOUND:
8706 		case SCF_ERROR_NO_RESOURCES:
8707 		case SCF_ERROR_INTERNAL:
8708 			bad_error("_scf_set_annotation", scf_error());
8709 			/* NOTREACHED */
8710 
8711 		default:
8712 			/*
8713 			 * Do not abort apply operation because of
8714 			 * inability to create annotation audit event.
8715 			 */
8716 			warn(gettext("_scf_set_annotation() unexpectedly "
8717 			    "failed with return code of %d\n"), scf_error());
8718 			break;
8719 		}
8720 	}
8721 
8722 	for (svc = uu_list_first(bndl->sc_bundle_services);
8723 	    svc != NULL;
8724 	    svc = uu_list_next(bndl->sc_bundle_services, svc)) {
8725 		int refresh = 0;
8726 
8727 		if (scf_scope_get_service(imp_scope, svc->sc_name,
8728 		    imp_svc) != 0) {
8729 			switch (scf_error()) {
8730 			case SCF_ERROR_NOT_FOUND:
8731 				if (g_verbose)
8732 					warn(gettext("Ignoring nonexistent "
8733 					    "service %s.\n"), svc->sc_name);
8734 				continue;
8735 
8736 			default:
8737 				scfdie();
8738 			}
8739 		}
8740 
8741 		/*
8742 		 * If there were missing types in the profile, then need to
8743 		 * attempt to find the types.
8744 		 */
8745 		if (svc->sc_miss_type) {
8746 			if (uu_list_numnodes(svc->sc_pgroups) &&
8747 			    uu_list_walk(svc->sc_pgroups, find_current_pg_type,
8748 			    svc, UU_DEFAULT) != 0) {
8749 				if (uu_error() != UU_ERROR_CALLBACK_FAILED)
8750 					bad_error("uu_list_walk", uu_error());
8751 
8752 				ret = -1;
8753 				continue;
8754 			}
8755 
8756 			for (inst = uu_list_first(
8757 			    svc->sc_u.sc_service.sc_service_instances);
8758 			    inst != NULL;
8759 			    inst = uu_list_next(
8760 			    svc->sc_u.sc_service.sc_service_instances, inst)) {
8761 				/*
8762 				 * If the instance doesn't exist just
8763 				 * skip to the next instance and let the
8764 				 * import note the missing instance.
8765 				 */
8766 				if (scf_service_get_instance(imp_svc,
8767 				    inst->sc_name, imp_inst) != 0)
8768 					continue;
8769 
8770 				if (uu_list_walk(inst->sc_pgroups,
8771 				    find_current_pg_type, inst,
8772 				    UU_DEFAULT) != 0) {
8773 					if (uu_error() !=
8774 					    UU_ERROR_CALLBACK_FAILED)
8775 						bad_error("uu_list_walk",
8776 						    uu_error());
8777 
8778 					ret = -1;
8779 					inst->sc_miss_type = B_TRUE;
8780 				}
8781 			}
8782 		}
8783 
8784 		/*
8785 		 * if we have pgs in the profile, we need to refresh ALL
8786 		 * instances of the service
8787 		 */
8788 		if (uu_list_numnodes(svc->sc_pgroups) != 0) {
8789 			refresh = 1;
8790 			r = lscf_import_service_pgs(imp_svc, svc->sc_fmri, svc,
8791 			    SCI_FORCE | SCI_KEEP);
8792 			switch (_lscf_import_err(r, svc->sc_fmri)) {
8793 			case IMPORT_NEXT:
8794 				break;
8795 
8796 			case IMPORT_OUT:
8797 				goto out;
8798 
8799 			case IMPORT_BAD:
8800 			default:
8801 				bad_error("lscf_import_service_pgs", r);
8802 			}
8803 		}
8804 
8805 		if (uu_list_numnodes(svc->sc_dependents) != 0) {
8806 			uu_list_walk(svc->sc_dependents,
8807 			    lscf_dependent_apply, svc, UU_DEFAULT);
8808 		}
8809 
8810 		for (inst = uu_list_first(
8811 		    svc->sc_u.sc_service.sc_service_instances);
8812 		    inst != NULL;
8813 		    inst = uu_list_next(
8814 		    svc->sc_u.sc_service.sc_service_instances, inst)) {
8815 			/*
8816 			 * This instance still has missing types
8817 			 * so skip it.
8818 			 */
8819 			if (inst->sc_miss_type) {
8820 				if (g_verbose)
8821 					warn(gettext("Ignoring instance "
8822 					    "%s:%s with missing types\n"),
8823 					    inst->sc_parent->sc_name,
8824 					    inst->sc_name);
8825 
8826 				continue;
8827 			}
8828 
8829 			if (scf_service_get_instance(imp_svc, inst->sc_name,
8830 			    imp_inst) != 0) {
8831 				switch (scf_error()) {
8832 				case SCF_ERROR_NOT_FOUND:
8833 					if (g_verbose)
8834 						warn(gettext("Ignoring "
8835 						    "nonexistant instance "
8836 						    "%s:%s.\n"),
8837 						    inst->sc_parent->sc_name,
8838 						    inst->sc_name);
8839 					continue;
8840 
8841 				default:
8842 					scfdie();
8843 				}
8844 			}
8845 
8846 			/*
8847 			 * If the instance does not have a general/enabled
8848 			 * property and no last-import snapshot then the
8849 			 * instance is not a fully installed instance and
8850 			 * should not have a profile applied to it.
8851 			 *
8852 			 * This could happen if a service/instance declares
8853 			 * a dependent on behalf of another service/instance.
8854 			 *
8855 			 */
8856 			if (scf_instance_get_snapshot(imp_inst, snap_lastimport,
8857 			    imp_snap) != 0) {
8858 				if (scf_instance_get_pg(imp_inst,
8859 				    SCF_PG_GENERAL, imp_pg) != 0 ||
8860 				    scf_pg_get_property(imp_pg,
8861 				    SCF_PROPERTY_ENABLED, imp_prop) != 0) {
8862 					if (g_verbose)
8863 						warn(gettext("Ignoreing "
8864 						    "partial instance "
8865 						    "%s:%s.\n"),
8866 						    inst->sc_parent->sc_name,
8867 						    inst->sc_name);
8868 					continue;
8869 				}
8870 			}
8871 
8872 			r = lscf_import_instance_pgs(imp_inst, inst->sc_fmri,
8873 			    inst, SCI_FORCE | SCI_KEEP);
8874 			switch (_lscf_import_err(r, inst->sc_fmri)) {
8875 			case IMPORT_NEXT:
8876 				break;
8877 
8878 			case IMPORT_OUT:
8879 				goto out;
8880 
8881 			case IMPORT_BAD:
8882 			default:
8883 				bad_error("lscf_import_instance_pgs", r);
8884 			}
8885 
8886 			if (uu_list_numnodes(inst->sc_dependents) != 0) {
8887 				uu_list_walk(inst->sc_dependents,
8888 				    lscf_dependent_apply, inst, UU_DEFAULT);
8889 			}
8890 
8891 			/* refresh only if there is no pgs in the service */
8892 			if (refresh == 0)
8893 				(void) refresh_entity(0, imp_inst,
8894 				    inst->sc_fmri, NULL, NULL, NULL);
8895 		}
8896 
8897 		if (refresh == 1) {
8898 			char *name_buf = safe_malloc(max_scf_name_len + 1);
8899 
8900 			(void) refresh_entity(1, imp_svc, svc->sc_name,
8901 			    imp_inst, imp_iter, name_buf);
8902 			free(name_buf);
8903 		}
8904 
8905 		for (old_dpt = uu_list_first(imp_deleted_dpts);
8906 		    old_dpt != NULL;
8907 		    old_dpt = uu_list_next(imp_deleted_dpts, old_dpt)) {
8908 			if (imp_refresh_fmri(old_dpt->sc_pgroup_fmri,
8909 			    old_dpt->sc_pgroup_name,
8910 			    old_dpt->sc_parent->sc_fmri) != 0) {
8911 				warn(gettext("Unable to refresh \"%s\"\n"),
8912 				    old_dpt->sc_pgroup_fmri);
8913 			}
8914 		}
8915 	}
8916 
8917 out:
8918 	if (annotation_set) {
8919 		/* Remove security audit annotation strings. */
8920 		(void) _scf_set_annotation(g_hndl, NULL, NULL);
8921 	}
8922 
8923 	free_imp_globals();
8924 	return (ret);
8925 }
8926 
8927 
8928 /*
8929  * Export.  These functions create and output an XML tree of a service
8930  * description from the repository.  This is largely the inverse of
8931  * lxml_get_bundle() in svccfg_xml.c, but with some kickers:
8932  *
8933  * - We must include any properties which are not represented specifically by
8934  *   a service manifest, e.g., properties created by an admin post-import.  To
8935  *   do so we'll iterate through all properties and deal with each
8936  *   apropriately.
8937  *
8938  * - Children of services and instances must must be in the order set by the
8939  *   DTD, but we iterate over the properties in undefined order.  The elements
8940  *   are not easily (or efficiently) sortable by name.  Since there's a fixed
8941  *   number of classes of them, however, we'll keep the classes separate and
8942  *   assemble them in order.
8943  */
8944 
8945 /*
8946  * Convenience function to handle xmlSetProp errors (and type casting).
8947  */
8948 static void
8949 safe_setprop(xmlNodePtr n, const char *name, const char *val)
8950 {
8951 	if (xmlSetProp(n, (const xmlChar *)name, (const xmlChar *)val) == NULL)
8952 		uu_die(gettext("Could not set XML property.\n"));
8953 }
8954 
8955 /*
8956  * Convenience function to set an XML attribute to the single value of an
8957  * astring property.  If the value happens to be the default, don't set the
8958  * attribute.  "dval" should be the default value supplied by the DTD, or
8959  * NULL for no default.
8960  */
8961 static int
8962 set_attr_from_prop_default(scf_property_t *prop, xmlNodePtr n,
8963     const char *name, const char *dval)
8964 {
8965 	scf_value_t *val;
8966 	ssize_t len;
8967 	char *str;
8968 
8969 	val = scf_value_create(g_hndl);
8970 	if (val == NULL)
8971 		scfdie();
8972 
8973 	if (prop_get_val(prop, val) != 0) {
8974 		scf_value_destroy(val);
8975 		return (-1);
8976 	}
8977 
8978 	len = scf_value_get_as_string(val, NULL, 0);
8979 	if (len < 0)
8980 		scfdie();
8981 
8982 	str = safe_malloc(len + 1);
8983 
8984 	if (scf_value_get_as_string(val, str, len + 1) < 0)
8985 		scfdie();
8986 
8987 	scf_value_destroy(val);
8988 
8989 	if (dval == NULL || strcmp(str, dval) != 0)
8990 		safe_setprop(n, name, str);
8991 
8992 	free(str);
8993 
8994 	return (0);
8995 }
8996 
8997 /*
8998  * As above, but the attribute is always set.
8999  */
9000 static int
9001 set_attr_from_prop(scf_property_t *prop, xmlNodePtr n, const char *name)
9002 {
9003 	return (set_attr_from_prop_default(prop, n, name, NULL));
9004 }
9005 
9006 /*
9007  * Dump the given document onto f, with "'s replaced by ''s.
9008  */
9009 static int
9010 write_service_bundle(xmlDocPtr doc, FILE *f)
9011 {
9012 	xmlChar *mem;
9013 	int sz, i;
9014 
9015 	mem = NULL;
9016 	xmlDocDumpFormatMemory(doc, &mem, &sz, 1);
9017 
9018 	if (mem == NULL) {
9019 		semerr(gettext("Could not dump XML tree.\n"));
9020 		return (-1);
9021 	}
9022 
9023 	/*
9024 	 * Fortunately libxml produces &quot; instead of ", so we can blindly
9025 	 * replace all " with '.  Cursed libxml2!  Why must you #ifdef out the
9026 	 * &apos; code?!
9027 	 */
9028 	for (i = 0; i < sz; ++i) {
9029 		char c = (char)mem[i];
9030 
9031 		if (c == '"')
9032 			(void) fputc('\'', f);
9033 		else if (c == '\'')
9034 			(void) fwrite("&apos;", sizeof ("&apos;") - 1, 1, f);
9035 		else
9036 			(void) fputc(c, f);
9037 	}
9038 
9039 	return (0);
9040 }
9041 
9042 /*
9043  * Create the DOM elements in elts necessary to (generically) represent prop
9044  * (i.e., a property or propval element).  If the name of the property is
9045  * known, it should be passed as name_arg.  Otherwise, pass NULL.
9046  */
9047 static void
9048 export_property(scf_property_t *prop, const char *name_arg,
9049     struct pg_elts *elts, int flags)
9050 {
9051 	const char *type;
9052 	scf_error_t err = 0;
9053 	xmlNodePtr pnode, lnode;
9054 	char *lnname;
9055 	int ret;
9056 
9057 	/* name */
9058 	if (name_arg != NULL) {
9059 		(void) strcpy(exp_str, name_arg);
9060 	} else {
9061 		if (scf_property_get_name(prop, exp_str, exp_str_sz) < 0)
9062 			scfdie();
9063 	}
9064 
9065 	/* type */
9066 	type = prop_to_typestr(prop);
9067 	if (type == NULL)
9068 		uu_die(gettext("Can't export property %s: unknown type.\n"),
9069 		    exp_str);
9070 
9071 	/* If we're exporting values, and there's just one, export it here. */
9072 	if (!(flags & SCE_ALL_VALUES))
9073 		goto empty;
9074 
9075 	if (scf_property_get_value(prop, exp_val) == SCF_SUCCESS) {
9076 		xmlNodePtr n;
9077 
9078 		/* Single value, so use propval */
9079 		n = xmlNewNode(NULL, (xmlChar *)"propval");
9080 		if (n == NULL)
9081 			uu_die(emsg_create_xml);
9082 
9083 		safe_setprop(n, name_attr, exp_str);
9084 		safe_setprop(n, type_attr, type);
9085 
9086 		if (scf_value_get_as_string(exp_val, exp_str, exp_str_sz) < 0)
9087 			scfdie();
9088 		safe_setprop(n, value_attr, exp_str);
9089 
9090 		if (elts->propvals == NULL)
9091 			elts->propvals = n;
9092 		else
9093 			(void) xmlAddSibling(elts->propvals, n);
9094 
9095 		return;
9096 	}
9097 
9098 	err = scf_error();
9099 
9100 	if (err == SCF_ERROR_PERMISSION_DENIED) {
9101 		semerr(emsg_permission_denied);
9102 		return;
9103 	}
9104 
9105 	if (err != SCF_ERROR_CONSTRAINT_VIOLATED &&
9106 	    err != SCF_ERROR_NOT_FOUND &&
9107 	    err != SCF_ERROR_PERMISSION_DENIED)
9108 		scfdie();
9109 
9110 empty:
9111 	/* Multiple (or no) values, so use property */
9112 	pnode = xmlNewNode(NULL, (xmlChar *)"property");
9113 	if (pnode == NULL)
9114 		uu_die(emsg_create_xml);
9115 
9116 	safe_setprop(pnode, name_attr, exp_str);
9117 	safe_setprop(pnode, type_attr, type);
9118 
9119 	if (err == SCF_ERROR_CONSTRAINT_VIOLATED) {
9120 		lnname = uu_msprintf("%s_list", type);
9121 		if (lnname == NULL)
9122 			uu_die(gettext("Could not create string"));
9123 
9124 		lnode = xmlNewChild(pnode, NULL, (xmlChar *)lnname, NULL);
9125 		if (lnode == NULL)
9126 			uu_die(emsg_create_xml);
9127 
9128 		uu_free(lnname);
9129 
9130 		if (scf_iter_property_values(exp_val_iter, prop) != SCF_SUCCESS)
9131 			scfdie();
9132 
9133 		while ((ret = scf_iter_next_value(exp_val_iter, exp_val)) ==
9134 		    1) {
9135 			xmlNodePtr vn;
9136 
9137 			vn = xmlNewChild(lnode, NULL, (xmlChar *)"value_node",
9138 			    NULL);
9139 			if (vn == NULL)
9140 				uu_die(emsg_create_xml);
9141 
9142 			if (scf_value_get_as_string(exp_val, exp_str,
9143 			    exp_str_sz) < 0)
9144 				scfdie();
9145 			safe_setprop(vn, value_attr, exp_str);
9146 		}
9147 		if (ret != 0)
9148 			scfdie();
9149 	}
9150 
9151 	if (elts->properties == NULL)
9152 		elts->properties = pnode;
9153 	else
9154 		(void) xmlAddSibling(elts->properties, pnode);
9155 }
9156 
9157 /*
9158  * Add a property_group element for this property group to elts.
9159  */
9160 static void
9161 export_pg(scf_propertygroup_t *pg, struct entity_elts *eelts, int flags)
9162 {
9163 	xmlNodePtr n;
9164 	struct pg_elts elts;
9165 	int ret;
9166 	boolean_t read_protected;
9167 
9168 	n = xmlNewNode(NULL, (xmlChar *)"property_group");
9169 
9170 	/* name */
9171 	if (scf_pg_get_name(pg, exp_str, max_scf_name_len + 1) < 0)
9172 		scfdie();
9173 	safe_setprop(n, name_attr, exp_str);
9174 
9175 	/* type */
9176 	if (scf_pg_get_type(pg, exp_str, exp_str_sz) < 0)
9177 		scfdie();
9178 	safe_setprop(n, type_attr, exp_str);
9179 
9180 	/* properties */
9181 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9182 		scfdie();
9183 
9184 	(void) memset(&elts, 0, sizeof (elts));
9185 
9186 	/*
9187 	 * If this property group is not read protected, we always want to
9188 	 * output all the values.  Otherwise, we only output the values if the
9189 	 * caller set SCE_ALL_VALUES (i.e., the user gave us export/archive -a).
9190 	 */
9191 	if (_scf_pg_is_read_protected(pg, &read_protected) != SCF_SUCCESS)
9192 		scfdie();
9193 
9194 	if (!read_protected)
9195 		flags |= SCE_ALL_VALUES;
9196 
9197 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9198 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9199 			scfdie();
9200 
9201 		if (strcmp(exp_str, SCF_PROPERTY_STABILITY) == 0) {
9202 			xmlNodePtr m;
9203 
9204 			m = xmlNewNode(NULL, (xmlChar *)"stability");
9205 			if (m == NULL)
9206 				uu_die(emsg_create_xml);
9207 
9208 			if (set_attr_from_prop(exp_prop, m, value_attr) == 0) {
9209 				elts.stability = m;
9210 				continue;
9211 			}
9212 
9213 			xmlFreeNode(m);
9214 		}
9215 
9216 		export_property(exp_prop, NULL, &elts, flags);
9217 	}
9218 	if (ret == -1)
9219 		scfdie();
9220 
9221 	(void) xmlAddChild(n, elts.stability);
9222 	(void) xmlAddChildList(n, elts.propvals);
9223 	(void) xmlAddChildList(n, elts.properties);
9224 
9225 	if (eelts->property_groups == NULL)
9226 		eelts->property_groups = n;
9227 	else
9228 		(void) xmlAddSibling(eelts->property_groups, n);
9229 }
9230 
9231 /*
9232  * Create an XML node representing the dependency described by the given
9233  * property group and put it in eelts.  Unless the dependency is not valid, in
9234  * which case create a generic property_group element which represents it and
9235  * put it in eelts.
9236  */
9237 static void
9238 export_dependency(scf_propertygroup_t *pg, struct entity_elts *eelts)
9239 {
9240 	xmlNodePtr n;
9241 	int err = 0, ret;
9242 	struct pg_elts elts;
9243 
9244 	n = xmlNewNode(NULL, (xmlChar *)"dependency");
9245 	if (n == NULL)
9246 		uu_die(emsg_create_xml);
9247 
9248 	/*
9249 	 * If the external flag is present, skip this dependency because it
9250 	 * should have been created by another manifest.
9251 	 */
9252 	if (scf_pg_get_property(pg, scf_property_external, exp_prop) == 0) {
9253 		if (prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
9254 		    prop_get_val(exp_prop, exp_val) == 0) {
9255 			uint8_t b;
9256 
9257 			if (scf_value_get_boolean(exp_val, &b) != SCF_SUCCESS)
9258 				scfdie();
9259 
9260 			if (b)
9261 				return;
9262 		}
9263 	} else if (scf_error() != SCF_ERROR_NOT_FOUND)
9264 		scfdie();
9265 
9266 	/* Get the required attributes. */
9267 
9268 	/* name */
9269 	if (scf_pg_get_name(pg, exp_str, max_scf_name_len + 1) < 0)
9270 		scfdie();
9271 	safe_setprop(n, name_attr, exp_str);
9272 
9273 	/* grouping */
9274 	if (pg_get_prop(pg, SCF_PROPERTY_GROUPING, exp_prop) != 0 ||
9275 	    set_attr_from_prop(exp_prop, n, "grouping") != 0)
9276 		err = 1;
9277 
9278 	/* restart_on */
9279 	if (pg_get_prop(pg, SCF_PROPERTY_RESTART_ON, exp_prop) != 0 ||
9280 	    set_attr_from_prop(exp_prop, n, "restart_on") != 0)
9281 		err = 1;
9282 
9283 	/* type */
9284 	if (pg_get_prop(pg, SCF_PROPERTY_TYPE, exp_prop) != 0 ||
9285 	    set_attr_from_prop(exp_prop, n, type_attr) != 0)
9286 		err = 1;
9287 
9288 	/*
9289 	 * entities: Not required, but if we create no children, it will be
9290 	 * created as empty on import, so fail if it's missing.
9291 	 */
9292 	if (pg_get_prop(pg, SCF_PROPERTY_ENTITIES, exp_prop) == 0 &&
9293 	    prop_check_type(exp_prop, SCF_TYPE_FMRI) == 0) {
9294 		scf_iter_t *eiter;
9295 		int ret2;
9296 
9297 		eiter = scf_iter_create(g_hndl);
9298 		if (eiter == NULL)
9299 			scfdie();
9300 
9301 		if (scf_iter_property_values(eiter, exp_prop) != SCF_SUCCESS)
9302 			scfdie();
9303 
9304 		while ((ret2 = scf_iter_next_value(eiter, exp_val)) == 1) {
9305 			xmlNodePtr ch;
9306 
9307 			if (scf_value_get_astring(exp_val, exp_str,
9308 			    exp_str_sz) < 0)
9309 				scfdie();
9310 
9311 			/*
9312 			 * service_fmri's must be first, so we can add them
9313 			 * here.
9314 			 */
9315 			ch = xmlNewChild(n, NULL, (xmlChar *)"service_fmri",
9316 			    NULL);
9317 			if (ch == NULL)
9318 				uu_die(emsg_create_xml);
9319 
9320 			safe_setprop(ch, value_attr, exp_str);
9321 		}
9322 		if (ret2 == -1)
9323 			scfdie();
9324 
9325 		scf_iter_destroy(eiter);
9326 	} else
9327 		err = 1;
9328 
9329 	if (err) {
9330 		xmlFreeNode(n);
9331 
9332 		export_pg(pg, eelts, SCE_ALL_VALUES);
9333 
9334 		return;
9335 	}
9336 
9337 	/* Iterate through the properties & handle each. */
9338 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9339 		scfdie();
9340 
9341 	(void) memset(&elts, 0, sizeof (elts));
9342 
9343 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9344 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9345 			scfdie();
9346 
9347 		if (strcmp(exp_str, SCF_PROPERTY_GROUPING) == 0 ||
9348 		    strcmp(exp_str, SCF_PROPERTY_RESTART_ON) == 0 ||
9349 		    strcmp(exp_str, SCF_PROPERTY_TYPE) == 0 ||
9350 		    strcmp(exp_str, SCF_PROPERTY_ENTITIES) == 0) {
9351 			continue;
9352 		} else if (strcmp(exp_str, SCF_PROPERTY_STABILITY) == 0) {
9353 			xmlNodePtr m;
9354 
9355 			m = xmlNewNode(NULL, (xmlChar *)"stability");
9356 			if (m == NULL)
9357 				uu_die(emsg_create_xml);
9358 
9359 			if (set_attr_from_prop(exp_prop, m, value_attr) == 0) {
9360 				elts.stability = m;
9361 				continue;
9362 			}
9363 
9364 			xmlFreeNode(m);
9365 		}
9366 
9367 		export_property(exp_prop, exp_str, &elts, SCE_ALL_VALUES);
9368 	}
9369 	if (ret == -1)
9370 		scfdie();
9371 
9372 	(void) xmlAddChild(n, elts.stability);
9373 	(void) xmlAddChildList(n, elts.propvals);
9374 	(void) xmlAddChildList(n, elts.properties);
9375 
9376 	if (eelts->dependencies == NULL)
9377 		eelts->dependencies = n;
9378 	else
9379 		(void) xmlAddSibling(eelts->dependencies, n);
9380 }
9381 
9382 static xmlNodePtr
9383 export_method_environment(scf_propertygroup_t *pg)
9384 {
9385 	xmlNodePtr env;
9386 	int ret;
9387 	int children = 0;
9388 
9389 	if (scf_pg_get_property(pg, SCF_PROPERTY_ENVIRONMENT, NULL) != 0)
9390 		return (NULL);
9391 
9392 	env = xmlNewNode(NULL, (xmlChar *)"method_environment");
9393 	if (env == NULL)
9394 		uu_die(emsg_create_xml);
9395 
9396 	if (pg_get_prop(pg, SCF_PROPERTY_ENVIRONMENT, exp_prop) != 0)
9397 		scfdie();
9398 
9399 	if (scf_iter_property_values(exp_val_iter, exp_prop) != SCF_SUCCESS)
9400 		scfdie();
9401 
9402 	while ((ret = scf_iter_next_value(exp_val_iter, exp_val)) == 1) {
9403 		xmlNodePtr ev;
9404 		char *cp;
9405 
9406 		if (scf_value_get_as_string(exp_val, exp_str, exp_str_sz) < 0)
9407 			scfdie();
9408 
9409 		if ((cp = strchr(exp_str, '=')) == NULL || cp == exp_str) {
9410 			warn(gettext("Invalid environment variable \"%s\".\n"),
9411 			    exp_str);
9412 			continue;
9413 		} else if (strncmp(exp_str, "SMF_", 4) == 0) {
9414 			warn(gettext("Invalid environment variable \"%s\"; "
9415 			    "\"SMF_\" prefix is reserved.\n"), exp_str);
9416 			continue;
9417 		}
9418 
9419 		*cp = '\0';
9420 		cp++;
9421 
9422 		ev = xmlNewChild(env, NULL, (xmlChar *)"envvar", NULL);
9423 		if (ev == NULL)
9424 			uu_die(emsg_create_xml);
9425 
9426 		safe_setprop(ev, name_attr, exp_str);
9427 		safe_setprop(ev, value_attr, cp);
9428 		children++;
9429 	}
9430 
9431 	if (ret != 0)
9432 		scfdie();
9433 
9434 	if (children == 0) {
9435 		xmlFreeNode(env);
9436 		return (NULL);
9437 	}
9438 
9439 	return (env);
9440 }
9441 
9442 /*
9443  * As above, but for a method property group.
9444  */
9445 static void
9446 export_method(scf_propertygroup_t *pg, struct entity_elts *eelts)
9447 {
9448 	xmlNodePtr n, env;
9449 	char *str;
9450 	int err = 0, nonenv, ret;
9451 	uint8_t use_profile;
9452 	struct pg_elts elts;
9453 	xmlNodePtr ctxt = NULL;
9454 
9455 	n = xmlNewNode(NULL, (xmlChar *)"exec_method");
9456 
9457 	/* Get the required attributes. */
9458 
9459 	/* name */
9460 	if (scf_pg_get_name(pg, exp_str, max_scf_name_len + 1) < 0)
9461 		scfdie();
9462 	safe_setprop(n, name_attr, exp_str);
9463 
9464 	/* type */
9465 	if (pg_get_prop(pg, SCF_PROPERTY_TYPE, exp_prop) != 0 ||
9466 	    set_attr_from_prop(exp_prop, n, type_attr) != 0)
9467 		err = 1;
9468 
9469 	/* exec */
9470 	if (pg_get_prop(pg, SCF_PROPERTY_EXEC, exp_prop) != 0 ||
9471 	    set_attr_from_prop(exp_prop, n, "exec") != 0)
9472 		err = 1;
9473 
9474 	/* timeout */
9475 	if (pg_get_prop(pg, SCF_PROPERTY_TIMEOUT, exp_prop) == 0 &&
9476 	    prop_check_type(exp_prop, SCF_TYPE_COUNT) == 0 &&
9477 	    prop_get_val(exp_prop, exp_val) == 0) {
9478 		uint64_t c;
9479 
9480 		if (scf_value_get_count(exp_val, &c) != SCF_SUCCESS)
9481 			scfdie();
9482 
9483 		str = uu_msprintf("%llu", c);
9484 		if (str == NULL)
9485 			uu_die(gettext("Could not create string"));
9486 
9487 		safe_setprop(n, "timeout_seconds", str);
9488 		free(str);
9489 	} else
9490 		err = 1;
9491 
9492 	if (err) {
9493 		xmlFreeNode(n);
9494 
9495 		export_pg(pg, eelts, SCE_ALL_VALUES);
9496 
9497 		return;
9498 	}
9499 
9500 
9501 	/*
9502 	 * If we're going to have a method_context child, we need to know
9503 	 * before we iterate through the properties.  Since method_context's
9504 	 * are optional, we don't want to complain about any properties
9505 	 * missing if none of them are there.  Thus we can't use the
9506 	 * convenience functions.
9507 	 */
9508 	nonenv =
9509 	    scf_pg_get_property(pg, SCF_PROPERTY_WORKING_DIRECTORY, NULL) ==
9510 	    SCF_SUCCESS ||
9511 	    scf_pg_get_property(pg, SCF_PROPERTY_PROJECT, NULL) ==
9512 	    SCF_SUCCESS ||
9513 	    scf_pg_get_property(pg, SCF_PROPERTY_RESOURCE_POOL, NULL) ==
9514 	    SCF_SUCCESS ||
9515 	    scf_pg_get_property(pg, SCF_PROPERTY_USE_PROFILE, NULL) ==
9516 	    SCF_SUCCESS;
9517 
9518 	if (nonenv) {
9519 		ctxt = xmlNewNode(NULL, (xmlChar *)"method_context");
9520 		if (ctxt == NULL)
9521 			uu_die(emsg_create_xml);
9522 
9523 		if (pg_get_prop(pg, SCF_PROPERTY_WORKING_DIRECTORY, exp_prop) ==
9524 		    0 &&
9525 		    set_attr_from_prop_default(exp_prop, ctxt,
9526 		    "working_directory", ":default") != 0)
9527 			err = 1;
9528 
9529 		if (pg_get_prop(pg, SCF_PROPERTY_PROJECT, exp_prop) == 0 &&
9530 		    set_attr_from_prop_default(exp_prop, ctxt, "project",
9531 		    ":default") != 0)
9532 			err = 1;
9533 
9534 		if (pg_get_prop(pg, SCF_PROPERTY_RESOURCE_POOL, exp_prop) ==
9535 		    0 &&
9536 		    set_attr_from_prop_default(exp_prop, ctxt,
9537 		    "resource_pool", ":default") != 0)
9538 			err = 1;
9539 		/*
9540 		 * We only want to complain about profile or credential
9541 		 * properties if we will use them.  To determine that we must
9542 		 * examine USE_PROFILE.
9543 		 */
9544 		if (pg_get_prop(pg, SCF_PROPERTY_USE_PROFILE, exp_prop) == 0 &&
9545 		    prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
9546 		    prop_get_val(exp_prop, exp_val) == 0) {
9547 			if (scf_value_get_boolean(exp_val, &use_profile) !=
9548 			    SCF_SUCCESS) {
9549 				scfdie();
9550 			}
9551 
9552 			if (use_profile) {
9553 				xmlNodePtr prof;
9554 
9555 				prof = xmlNewChild(ctxt, NULL,
9556 				    (xmlChar *)"method_profile", NULL);
9557 				if (prof == NULL)
9558 					uu_die(emsg_create_xml);
9559 
9560 				if (pg_get_prop(pg, SCF_PROPERTY_PROFILE,
9561 				    exp_prop) != 0 ||
9562 				    set_attr_from_prop(exp_prop, prof,
9563 				    name_attr) != 0)
9564 					err = 1;
9565 			} else {
9566 				xmlNodePtr cred;
9567 
9568 				cred = xmlNewChild(ctxt, NULL,
9569 				    (xmlChar *)"method_credential", NULL);
9570 				if (cred == NULL)
9571 					uu_die(emsg_create_xml);
9572 
9573 				if (pg_get_prop(pg, SCF_PROPERTY_USER,
9574 				    exp_prop) != 0 ||
9575 				    set_attr_from_prop(exp_prop, cred,
9576 				    "user") != 0) {
9577 					err = 1;
9578 				}
9579 
9580 				if (pg_get_prop(pg, SCF_PROPERTY_GROUP,
9581 				    exp_prop) == 0 &&
9582 				    set_attr_from_prop_default(exp_prop, cred,
9583 				    "group", ":default") != 0)
9584 					err = 1;
9585 
9586 				if (pg_get_prop(pg, SCF_PROPERTY_SUPP_GROUPS,
9587 				    exp_prop) == 0 &&
9588 				    set_attr_from_prop_default(exp_prop, cred,
9589 				    "supp_groups", ":default") != 0)
9590 					err = 1;
9591 
9592 				if (pg_get_prop(pg, SCF_PROPERTY_PRIVILEGES,
9593 				    exp_prop) == 0 &&
9594 				    set_attr_from_prop_default(exp_prop, cred,
9595 				    "privileges", ":default") != 0)
9596 					err = 1;
9597 
9598 				if (pg_get_prop(pg,
9599 				    SCF_PROPERTY_LIMIT_PRIVILEGES,
9600 				    exp_prop) == 0 &&
9601 				    set_attr_from_prop_default(exp_prop, cred,
9602 				    "limit_privileges", ":default") != 0)
9603 					err = 1;
9604 			}
9605 		}
9606 	}
9607 
9608 	if ((env = export_method_environment(pg)) != NULL) {
9609 		if (ctxt == NULL) {
9610 			ctxt = xmlNewNode(NULL, (xmlChar *)"method_context");
9611 			if (ctxt == NULL)
9612 				uu_die(emsg_create_xml);
9613 		}
9614 		(void) xmlAddChild(ctxt, env);
9615 	}
9616 
9617 	if (env != NULL || (nonenv && err == 0))
9618 		(void) xmlAddChild(n, ctxt);
9619 	else
9620 		xmlFreeNode(ctxt);
9621 
9622 	nonenv = (err == 0);
9623 
9624 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9625 		scfdie();
9626 
9627 	(void) memset(&elts, 0, sizeof (elts));
9628 
9629 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9630 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9631 			scfdie();
9632 
9633 		if (strcmp(exp_str, SCF_PROPERTY_TYPE) == 0 ||
9634 		    strcmp(exp_str, SCF_PROPERTY_EXEC) == 0 ||
9635 		    strcmp(exp_str, SCF_PROPERTY_TIMEOUT) == 0) {
9636 			continue;
9637 		} else if (strcmp(exp_str, SCF_PROPERTY_STABILITY) == 0) {
9638 			xmlNodePtr m;
9639 
9640 			m = xmlNewNode(NULL, (xmlChar *)"stability");
9641 			if (m == NULL)
9642 				uu_die(emsg_create_xml);
9643 
9644 			if (set_attr_from_prop(exp_prop, m, value_attr) == 0) {
9645 				elts.stability = m;
9646 				continue;
9647 			}
9648 
9649 			xmlFreeNode(m);
9650 		} else if (strcmp(exp_str, SCF_PROPERTY_WORKING_DIRECTORY) ==
9651 		    0 ||
9652 		    strcmp(exp_str, SCF_PROPERTY_PROJECT) == 0 ||
9653 		    strcmp(exp_str, SCF_PROPERTY_RESOURCE_POOL) == 0 ||
9654 		    strcmp(exp_str, SCF_PROPERTY_USE_PROFILE) == 0) {
9655 			if (nonenv)
9656 				continue;
9657 		} else if (strcmp(exp_str, SCF_PROPERTY_USER) == 0 ||
9658 		    strcmp(exp_str, SCF_PROPERTY_GROUP) == 0 ||
9659 		    strcmp(exp_str, SCF_PROPERTY_SUPP_GROUPS) == 0 ||
9660 		    strcmp(exp_str, SCF_PROPERTY_PRIVILEGES) == 0 ||
9661 		    strcmp(exp_str, SCF_PROPERTY_LIMIT_PRIVILEGES) == 0) {
9662 			if (nonenv && !use_profile)
9663 				continue;
9664 		} else if (strcmp(exp_str, SCF_PROPERTY_PROFILE) == 0) {
9665 			if (nonenv && use_profile)
9666 				continue;
9667 		} else if (strcmp(exp_str, SCF_PROPERTY_ENVIRONMENT) == 0) {
9668 			if (env != NULL)
9669 				continue;
9670 		}
9671 
9672 		export_property(exp_prop, exp_str, &elts, SCE_ALL_VALUES);
9673 	}
9674 	if (ret == -1)
9675 		scfdie();
9676 
9677 	(void) xmlAddChild(n, elts.stability);
9678 	(void) xmlAddChildList(n, elts.propvals);
9679 	(void) xmlAddChildList(n, elts.properties);
9680 
9681 	if (eelts->exec_methods == NULL)
9682 		eelts->exec_methods = n;
9683 	else
9684 		(void) xmlAddSibling(eelts->exec_methods, n);
9685 }
9686 
9687 static void
9688 export_pg_elts(struct pg_elts *elts, const char *name, const char *type,
9689     struct entity_elts *eelts)
9690 {
9691 	xmlNodePtr pgnode;
9692 
9693 	pgnode = xmlNewNode(NULL, (xmlChar *)"property_group");
9694 	if (pgnode == NULL)
9695 		uu_die(emsg_create_xml);
9696 
9697 	safe_setprop(pgnode, name_attr, name);
9698 	safe_setprop(pgnode, type_attr, type);
9699 
9700 	(void) xmlAddChildList(pgnode, elts->propvals);
9701 	(void) xmlAddChildList(pgnode, elts->properties);
9702 
9703 	if (eelts->property_groups == NULL)
9704 		eelts->property_groups = pgnode;
9705 	else
9706 		(void) xmlAddSibling(eelts->property_groups, pgnode);
9707 }
9708 
9709 /*
9710  * Process the general property group for a service.  This is the one with the
9711  * goodies.
9712  */
9713 static void
9714 export_svc_general(scf_propertygroup_t *pg, struct entity_elts *selts)
9715 {
9716 	struct pg_elts elts;
9717 	int ret;
9718 
9719 	/*
9720 	 * In case there are properties which don't correspond to child
9721 	 * entities of the service entity, we'll set up a pg_elts structure to
9722 	 * put them in.
9723 	 */
9724 	(void) memset(&elts, 0, sizeof (elts));
9725 
9726 	/* Walk the properties, looking for special ones. */
9727 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9728 		scfdie();
9729 
9730 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9731 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9732 			scfdie();
9733 
9734 		if (strcmp(exp_str, SCF_PROPERTY_SINGLE_INSTANCE) == 0) {
9735 			if (prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
9736 			    prop_get_val(exp_prop, exp_val) == 0) {
9737 				uint8_t b;
9738 
9739 				if (scf_value_get_boolean(exp_val, &b) !=
9740 				    SCF_SUCCESS)
9741 					scfdie();
9742 
9743 				if (b) {
9744 					selts->single_instance =
9745 					    xmlNewNode(NULL,
9746 					    (xmlChar *)"single_instance");
9747 					if (selts->single_instance == NULL)
9748 						uu_die(emsg_create_xml);
9749 				}
9750 
9751 				continue;
9752 			}
9753 		} else if (strcmp(exp_str, SCF_PROPERTY_RESTARTER) == 0) {
9754 			xmlNodePtr rnode, sfnode;
9755 
9756 			rnode = xmlNewNode(NULL, (xmlChar *)"restarter");
9757 			if (rnode == NULL)
9758 				uu_die(emsg_create_xml);
9759 
9760 			sfnode = xmlNewChild(rnode, NULL,
9761 			    (xmlChar *)"service_fmri", NULL);
9762 			if (sfnode == NULL)
9763 				uu_die(emsg_create_xml);
9764 
9765 			if (set_attr_from_prop(exp_prop, sfnode,
9766 			    value_attr) == 0) {
9767 				selts->restarter = rnode;
9768 				continue;
9769 			}
9770 
9771 			xmlFreeNode(rnode);
9772 		} else if (strcmp(exp_str, SCF_PROPERTY_ENTITY_STABILITY) ==
9773 		    0) {
9774 			xmlNodePtr s;
9775 
9776 			s = xmlNewNode(NULL, (xmlChar *)"stability");
9777 			if (s == NULL)
9778 				uu_die(emsg_create_xml);
9779 
9780 			if (set_attr_from_prop(exp_prop, s, value_attr) == 0) {
9781 				selts->stability = s;
9782 				continue;
9783 			}
9784 
9785 			xmlFreeNode(s);
9786 		}
9787 
9788 		export_property(exp_prop, exp_str, &elts, SCE_ALL_VALUES);
9789 	}
9790 	if (ret == -1)
9791 		scfdie();
9792 
9793 	if (elts.propvals != NULL || elts.properties != NULL)
9794 		export_pg_elts(&elts, scf_pg_general, scf_group_framework,
9795 		    selts);
9796 }
9797 
9798 static void
9799 export_method_context(scf_propertygroup_t *pg, struct entity_elts *elts)
9800 {
9801 	xmlNodePtr n, prof, cred, env;
9802 	uint8_t use_profile;
9803 	int ret, err = 0;
9804 
9805 	n = xmlNewNode(NULL, (xmlChar *)"method_context");
9806 
9807 	env = export_method_environment(pg);
9808 
9809 	/* Need to know whether we'll use a profile or not. */
9810 	if (pg_get_prop(pg, SCF_PROPERTY_USE_PROFILE, exp_prop) == 0 &&
9811 	    prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
9812 	    prop_get_val(exp_prop, exp_val) == 0) {
9813 		if (scf_value_get_boolean(exp_val, &use_profile) != SCF_SUCCESS)
9814 			scfdie();
9815 
9816 		if (use_profile)
9817 			prof =
9818 			    xmlNewChild(n, NULL, (xmlChar *)"method_profile",
9819 			    NULL);
9820 		else
9821 			cred =
9822 			    xmlNewChild(n, NULL, (xmlChar *)"method_credential",
9823 			    NULL);
9824 	}
9825 
9826 	if (env != NULL)
9827 		(void) xmlAddChild(n, env);
9828 
9829 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9830 		scfdie();
9831 
9832 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9833 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9834 			scfdie();
9835 
9836 		if (strcmp(exp_str, SCF_PROPERTY_WORKING_DIRECTORY) == 0) {
9837 			if (set_attr_from_prop(exp_prop, n,
9838 			    "working_directory") != 0)
9839 				err = 1;
9840 		} else if (strcmp(exp_str, SCF_PROPERTY_PROJECT) == 0) {
9841 			if (set_attr_from_prop(exp_prop, n, "project") != 0)
9842 				err = 1;
9843 		} else if (strcmp(exp_str, SCF_PROPERTY_RESOURCE_POOL) == 0) {
9844 			if (set_attr_from_prop(exp_prop, n,
9845 			    "resource_pool") != 0)
9846 				err = 1;
9847 		} else if (strcmp(exp_str, SCF_PROPERTY_USE_PROFILE) == 0) {
9848 			/* EMPTY */
9849 		} else if (strcmp(exp_str, SCF_PROPERTY_USER) == 0) {
9850 			if (use_profile ||
9851 			    set_attr_from_prop(exp_prop, cred, "user") != 0)
9852 				err = 1;
9853 		} else if (strcmp(exp_str, SCF_PROPERTY_GROUP) == 0) {
9854 			if (use_profile ||
9855 			    set_attr_from_prop(exp_prop, cred, "group") != 0)
9856 				err = 1;
9857 		} else if (strcmp(exp_str, SCF_PROPERTY_SUPP_GROUPS) == 0) {
9858 			if (use_profile || set_attr_from_prop(exp_prop, cred,
9859 			    "supp_groups") != 0)
9860 				err = 1;
9861 		} else if (strcmp(exp_str, SCF_PROPERTY_PRIVILEGES) == 0) {
9862 			if (use_profile || set_attr_from_prop(exp_prop, cred,
9863 			    "privileges") != 0)
9864 				err = 1;
9865 		} else if (strcmp(exp_str, SCF_PROPERTY_LIMIT_PRIVILEGES) ==
9866 		    0) {
9867 			if (use_profile || set_attr_from_prop(exp_prop, cred,
9868 			    "limit_privileges") != 0)
9869 				err = 1;
9870 		} else if (strcmp(exp_str, SCF_PROPERTY_PROFILE) == 0) {
9871 			if (!use_profile || set_attr_from_prop(exp_prop,
9872 			    prof, name_attr) != 0)
9873 				err = 1;
9874 		} else {
9875 			/* Can't have generic properties in method_context's */
9876 			err = 1;
9877 		}
9878 	}
9879 	if (ret == -1)
9880 		scfdie();
9881 
9882 	if (err && env == NULL) {
9883 		xmlFreeNode(n);
9884 		export_pg(pg, elts, SCE_ALL_VALUES);
9885 		return;
9886 	}
9887 
9888 	elts->method_context = n;
9889 }
9890 
9891 /*
9892  * Given a dependency property group in the tfmri entity (target fmri), return
9893  * a dependent element which represents it.
9894  */
9895 static xmlNodePtr
9896 export_dependent(scf_propertygroup_t *pg, const char *name, const char *tfmri)
9897 {
9898 	uint8_t b;
9899 	xmlNodePtr n, sf;
9900 	int err = 0, ret;
9901 	struct pg_elts pgelts;
9902 
9903 	/*
9904 	 * If external isn't set to true then exporting the service will
9905 	 * export this as a normal dependency, so we should stop to avoid
9906 	 * duplication.
9907 	 */
9908 	if (scf_pg_get_property(pg, scf_property_external, exp_prop) != 0 ||
9909 	    scf_property_get_value(exp_prop, exp_val) != 0 ||
9910 	    scf_value_get_boolean(exp_val, &b) != 0 || !b) {
9911 		if (g_verbose) {
9912 			warn(gettext("Dependent \"%s\" cannot be exported "
9913 			    "properly because the \"%s\" property of the "
9914 			    "\"%s\" dependency of %s is not set to true.\n"),
9915 			    name, scf_property_external, name, tfmri);
9916 		}
9917 
9918 		return (NULL);
9919 	}
9920 
9921 	n = xmlNewNode(NULL, (xmlChar *)"dependent");
9922 	if (n == NULL)
9923 		uu_die(emsg_create_xml);
9924 
9925 	safe_setprop(n, name_attr, name);
9926 
9927 	/* Get the required attributes */
9928 	if (pg_get_prop(pg, SCF_PROPERTY_RESTART_ON, exp_prop) != 0 ||
9929 	    set_attr_from_prop(exp_prop, n, "restart_on") != 0)
9930 		err = 1;
9931 
9932 	if (pg_get_prop(pg, SCF_PROPERTY_GROUPING, exp_prop) != 0 ||
9933 	    set_attr_from_prop(exp_prop, n, "grouping") != 0)
9934 		err = 1;
9935 
9936 	if (pg_get_prop(pg, SCF_PROPERTY_ENTITIES, exp_prop) == 0 &&
9937 	    prop_check_type(exp_prop, SCF_TYPE_FMRI) == 0 &&
9938 	    prop_get_val(exp_prop, exp_val) == 0) {
9939 		/* EMPTY */
9940 	} else
9941 		err = 1;
9942 
9943 	if (err) {
9944 		xmlFreeNode(n);
9945 		return (NULL);
9946 	}
9947 
9948 	sf = xmlNewChild(n, NULL, (xmlChar *)"service_fmri", NULL);
9949 	if (sf == NULL)
9950 		uu_die(emsg_create_xml);
9951 
9952 	safe_setprop(sf, value_attr, tfmri);
9953 
9954 	/*
9955 	 * Now add elements for the other properties.
9956 	 */
9957 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
9958 		scfdie();
9959 
9960 	(void) memset(&pgelts, 0, sizeof (pgelts));
9961 
9962 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
9963 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
9964 			scfdie();
9965 
9966 		if (strcmp(exp_str, scf_property_external) == 0 ||
9967 		    strcmp(exp_str, SCF_PROPERTY_RESTART_ON) == 0 ||
9968 		    strcmp(exp_str, SCF_PROPERTY_GROUPING) == 0 ||
9969 		    strcmp(exp_str, SCF_PROPERTY_ENTITIES) == 0) {
9970 			continue;
9971 		} else if (strcmp(exp_str, SCF_PROPERTY_TYPE) == 0) {
9972 			if (prop_check_type(exp_prop, SCF_TYPE_ASTRING) == 0 &&
9973 			    prop_get_val(exp_prop, exp_val) == 0) {
9974 				char type[sizeof ("service") + 1];
9975 
9976 				if (scf_value_get_astring(exp_val, type,
9977 				    sizeof (type)) < 0)
9978 					scfdie();
9979 
9980 				if (strcmp(type, "service") == 0)
9981 					continue;
9982 			}
9983 		} else if (strcmp(exp_str, SCF_PROPERTY_STABILITY) == 0) {
9984 			xmlNodePtr s;
9985 
9986 			s = xmlNewNode(NULL, (xmlChar *)"stability");
9987 			if (s == NULL)
9988 				uu_die(emsg_create_xml);
9989 
9990 			if (set_attr_from_prop(exp_prop, s, value_attr) == 0) {
9991 				pgelts.stability = s;
9992 				continue;
9993 			}
9994 
9995 			xmlFreeNode(s);
9996 		}
9997 
9998 		export_property(exp_prop, exp_str, &pgelts, SCE_ALL_VALUES);
9999 	}
10000 	if (ret == -1)
10001 		scfdie();
10002 
10003 	(void) xmlAddChild(n, pgelts.stability);
10004 	(void) xmlAddChildList(n, pgelts.propvals);
10005 	(void) xmlAddChildList(n, pgelts.properties);
10006 
10007 	return (n);
10008 }
10009 
10010 static void
10011 export_dependents(scf_propertygroup_t *pg, struct entity_elts *eelts)
10012 {
10013 	scf_propertygroup_t *opg;
10014 	scf_iter_t *iter;
10015 	char *type, *fmri;
10016 	int ret;
10017 	struct pg_elts pgelts;
10018 	xmlNodePtr n;
10019 	scf_error_t serr;
10020 
10021 	if ((opg = scf_pg_create(g_hndl)) == NULL ||
10022 	    (iter = scf_iter_create(g_hndl)) == NULL)
10023 		scfdie();
10024 
10025 	/* Can't use exp_prop_iter due to export_dependent(). */
10026 	if (scf_iter_pg_properties(iter, pg) != SCF_SUCCESS)
10027 		scfdie();
10028 
10029 	type = safe_malloc(max_scf_pg_type_len + 1);
10030 
10031 	/* Get an extra byte so we can tell if values are too long. */
10032 	fmri = safe_malloc(max_scf_fmri_len + 2);
10033 
10034 	(void) memset(&pgelts, 0, sizeof (pgelts));
10035 
10036 	while ((ret = scf_iter_next_property(iter, exp_prop)) == 1) {
10037 		void *entity;
10038 		int isservice;
10039 		scf_type_t ty;
10040 
10041 		if (scf_property_type(exp_prop, &ty) != SCF_SUCCESS)
10042 			scfdie();
10043 
10044 		if ((ty != SCF_TYPE_ASTRING &&
10045 		    prop_check_type(exp_prop, SCF_TYPE_FMRI) != 0) ||
10046 		    prop_get_val(exp_prop, exp_val) != 0) {
10047 			export_property(exp_prop, NULL, &pgelts,
10048 			    SCE_ALL_VALUES);
10049 			continue;
10050 		}
10051 
10052 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
10053 			scfdie();
10054 
10055 		if (scf_value_get_astring(exp_val, fmri,
10056 		    max_scf_fmri_len + 2) < 0)
10057 			scfdie();
10058 
10059 		/* Look for a dependency group in the target fmri. */
10060 		serr = fmri_to_entity(g_hndl, fmri, &entity, &isservice);
10061 		switch (serr) {
10062 		case SCF_ERROR_NONE:
10063 			break;
10064 
10065 		case SCF_ERROR_NO_MEMORY:
10066 			uu_die(gettext("Out of memory.\n"));
10067 			/* NOTREACHED */
10068 
10069 		case SCF_ERROR_INVALID_ARGUMENT:
10070 			if (g_verbose) {
10071 				if (scf_property_to_fmri(exp_prop, fmri,
10072 				    max_scf_fmri_len + 2) < 0)
10073 					scfdie();
10074 
10075 				warn(gettext("The value of %s is not a valid "
10076 				    "FMRI.\n"), fmri);
10077 			}
10078 
10079 			export_property(exp_prop, exp_str, &pgelts,
10080 			    SCE_ALL_VALUES);
10081 			continue;
10082 
10083 		case SCF_ERROR_CONSTRAINT_VIOLATED:
10084 			if (g_verbose) {
10085 				if (scf_property_to_fmri(exp_prop, fmri,
10086 				    max_scf_fmri_len + 2) < 0)
10087 					scfdie();
10088 
10089 				warn(gettext("The value of %s does not specify "
10090 				    "a service or an instance.\n"), fmri);
10091 			}
10092 
10093 			export_property(exp_prop, exp_str, &pgelts,
10094 			    SCE_ALL_VALUES);
10095 			continue;
10096 
10097 		case SCF_ERROR_NOT_FOUND:
10098 			if (g_verbose) {
10099 				if (scf_property_to_fmri(exp_prop, fmri,
10100 				    max_scf_fmri_len + 2) < 0)
10101 					scfdie();
10102 
10103 				warn(gettext("The entity specified by %s does "
10104 				    "not exist.\n"), fmri);
10105 			}
10106 
10107 			export_property(exp_prop, exp_str, &pgelts,
10108 			    SCE_ALL_VALUES);
10109 			continue;
10110 
10111 		default:
10112 #ifndef NDEBUG
10113 			(void) fprintf(stderr, "%s:%d: %s() failed with "
10114 			    "unexpected error %d.\n", __FILE__, __LINE__,
10115 			    "fmri_to_entity", serr);
10116 #endif
10117 			abort();
10118 		}
10119 
10120 		if (entity_get_pg(entity, isservice, exp_str, opg) != 0) {
10121 			if (scf_error() != SCF_ERROR_NOT_FOUND)
10122 				scfdie();
10123 
10124 			warn(gettext("Entity %s is missing dependency property "
10125 			    "group %s.\n"), fmri, exp_str);
10126 
10127 			export_property(exp_prop, NULL, &pgelts,
10128 			    SCE_ALL_VALUES);
10129 			continue;
10130 		}
10131 
10132 		if (scf_pg_get_type(opg, type, max_scf_pg_type_len + 1) < 0)
10133 			scfdie();
10134 
10135 		if (strcmp(type, SCF_GROUP_DEPENDENCY) != 0) {
10136 			if (scf_pg_to_fmri(opg, fmri, max_scf_fmri_len + 2) < 0)
10137 				scfdie();
10138 
10139 			warn(gettext("Property group %s is not of "
10140 			    "expected type %s.\n"), fmri, SCF_GROUP_DEPENDENCY);
10141 
10142 			export_property(exp_prop, NULL, &pgelts,
10143 			    SCE_ALL_VALUES);
10144 			continue;
10145 		}
10146 
10147 		n = export_dependent(opg, exp_str, fmri);
10148 		if (n == NULL) {
10149 			export_property(exp_prop, exp_str, &pgelts,
10150 			    SCE_ALL_VALUES);
10151 		} else {
10152 			if (eelts->dependents == NULL)
10153 				eelts->dependents = n;
10154 			else
10155 				(void) xmlAddSibling(eelts->dependents,
10156 				    n);
10157 		}
10158 	}
10159 	if (ret == -1)
10160 		scfdie();
10161 
10162 	free(fmri);
10163 	free(type);
10164 
10165 	scf_iter_destroy(iter);
10166 	scf_pg_destroy(opg);
10167 
10168 	if (pgelts.propvals != NULL || pgelts.properties != NULL)
10169 		export_pg_elts(&pgelts, SCF_PG_DEPENDENTS, scf_group_framework,
10170 		    eelts);
10171 }
10172 
10173 static void
10174 make_node(xmlNodePtr *nodep, const char *name)
10175 {
10176 	if (*nodep == NULL) {
10177 		*nodep = xmlNewNode(NULL, (xmlChar *)name);
10178 		if (*nodep == NULL)
10179 			uu_die(emsg_create_xml);
10180 	}
10181 }
10182 
10183 static xmlNodePtr
10184 export_tm_loctext(scf_propertygroup_t *pg, const char *parname)
10185 {
10186 	int ret;
10187 	xmlNodePtr parent = NULL;
10188 	xmlNodePtr loctext = NULL;
10189 
10190 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
10191 		scfdie();
10192 
10193 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
10194 		if (prop_check_type(exp_prop, SCF_TYPE_USTRING) != 0 ||
10195 		    prop_get_val(exp_prop, exp_val) != 0)
10196 			continue;
10197 
10198 		if (scf_value_get_ustring(exp_val, exp_str, exp_str_sz) < 0)
10199 			scfdie();
10200 
10201 		make_node(&parent, parname);
10202 		loctext = xmlNewTextChild(parent, NULL, (xmlChar *)"loctext",
10203 		    (xmlChar *)exp_str);
10204 		if (loctext == NULL)
10205 			uu_die(emsg_create_xml);
10206 
10207 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
10208 			scfdie();
10209 
10210 		safe_setprop(loctext, "xml:lang", exp_str);
10211 	}
10212 
10213 	if (ret == -1)
10214 		scfdie();
10215 
10216 	return (parent);
10217 }
10218 
10219 static xmlNodePtr
10220 export_tm_manpage(scf_propertygroup_t *pg)
10221 {
10222 	xmlNodePtr manpage = xmlNewNode(NULL, (xmlChar *)"manpage");
10223 	if (manpage == NULL)
10224 		uu_die(emsg_create_xml);
10225 
10226 	if (pg_get_prop(pg, SCF_PROPERTY_TM_TITLE, exp_prop) != 0 ||
10227 	    set_attr_from_prop(exp_prop, manpage, "title") != 0 ||
10228 	    pg_get_prop(pg, SCF_PROPERTY_TM_SECTION, exp_prop) != 0 ||
10229 	    set_attr_from_prop(exp_prop, manpage, "section") != 0) {
10230 		xmlFreeNode(manpage);
10231 		return (NULL);
10232 	}
10233 
10234 	if (pg_get_prop(pg, SCF_PROPERTY_TM_MANPATH, exp_prop) == 0)
10235 		(void) set_attr_from_prop_default(exp_prop,
10236 		    manpage, "manpath", ":default");
10237 
10238 	return (manpage);
10239 }
10240 
10241 static xmlNodePtr
10242 export_tm_doc_link(scf_propertygroup_t *pg)
10243 {
10244 	xmlNodePtr doc_link = xmlNewNode(NULL, (xmlChar *)"doc_link");
10245 	if (doc_link == NULL)
10246 		uu_die(emsg_create_xml);
10247 
10248 	if (pg_get_prop(pg, SCF_PROPERTY_TM_NAME, exp_prop) != 0 ||
10249 	    set_attr_from_prop(exp_prop, doc_link, "name") != 0 ||
10250 	    pg_get_prop(pg, SCF_PROPERTY_TM_URI, exp_prop) != 0 ||
10251 	    set_attr_from_prop(exp_prop, doc_link, "uri") != 0) {
10252 		xmlFreeNode(doc_link);
10253 		return (NULL);
10254 	}
10255 	return (doc_link);
10256 }
10257 
10258 /*
10259  * Process template information for a service or instances.
10260  */
10261 static void
10262 export_template(scf_propertygroup_t *pg, struct entity_elts *elts,
10263     struct template_elts *telts)
10264 {
10265 	size_t mansz = strlen(SCF_PG_TM_MAN_PREFIX);
10266 	size_t docsz = strlen(SCF_PG_TM_DOC_PREFIX);
10267 	xmlNodePtr child = NULL;
10268 
10269 	if (scf_pg_get_name(pg, exp_str, exp_str_sz) < 0)
10270 		scfdie();
10271 
10272 	if (strcmp(exp_str, SCF_PG_TM_COMMON_NAME) == 0) {
10273 		telts->common_name = export_tm_loctext(pg, "common_name");
10274 		if (telts->common_name == NULL)
10275 			export_pg(pg, elts, SCE_ALL_VALUES);
10276 		return;
10277 	} else if (strcmp(exp_str, SCF_PG_TM_DESCRIPTION) == 0) {
10278 		telts->description = export_tm_loctext(pg, "description");
10279 		if (telts->description == NULL)
10280 			export_pg(pg, elts, SCE_ALL_VALUES);
10281 		return;
10282 	}
10283 
10284 	if (strncmp(exp_str, SCF_PG_TM_MAN_PREFIX, mansz) == 0) {
10285 		child = export_tm_manpage(pg);
10286 	} else if (strncmp(exp_str, SCF_PG_TM_DOC_PREFIX, docsz) == 0) {
10287 		child = export_tm_doc_link(pg);
10288 	}
10289 
10290 	if (child != NULL) {
10291 		make_node(&telts->documentation, "documentation");
10292 		(void) xmlAddChild(telts->documentation, child);
10293 	} else {
10294 		export_pg(pg, elts, SCE_ALL_VALUES);
10295 	}
10296 }
10297 
10298 /*
10299  * Process parameter and paramval elements
10300  */
10301 static void
10302 export_parameter(scf_property_t *prop, const char *name,
10303     struct params_elts *elts)
10304 {
10305 	xmlNodePtr param;
10306 	scf_error_t err = 0;
10307 	int ret;
10308 
10309 	if (scf_property_get_value(prop, exp_val) == SCF_SUCCESS) {
10310 		if ((param = xmlNewNode(NULL, (xmlChar *)"paramval")) == NULL)
10311 			uu_die(emsg_create_xml);
10312 
10313 		safe_setprop(param, name_attr, name);
10314 
10315 		if (scf_value_get_as_string(exp_val, exp_str, exp_str_sz) < 0)
10316 			scfdie();
10317 		safe_setprop(param, value_attr, exp_str);
10318 
10319 		if (elts->paramval == NULL)
10320 			elts->paramval = param;
10321 		else
10322 			(void) xmlAddSibling(elts->paramval, param);
10323 
10324 		return;
10325 	}
10326 
10327 	err = scf_error();
10328 
10329 	if (err != SCF_ERROR_CONSTRAINT_VIOLATED &&
10330 	    err != SCF_ERROR_NOT_FOUND)
10331 		scfdie();
10332 
10333 	if ((param = xmlNewNode(NULL, (xmlChar *)"parameter")) == NULL)
10334 		uu_die(emsg_create_xml);
10335 
10336 	safe_setprop(param, name_attr, name);
10337 
10338 	if (err == SCF_ERROR_CONSTRAINT_VIOLATED) {
10339 		if (scf_iter_property_values(exp_val_iter, prop) != SCF_SUCCESS)
10340 			scfdie();
10341 
10342 		while ((ret = scf_iter_next_value(exp_val_iter, exp_val)) ==
10343 		    1) {
10344 			xmlNodePtr vn;
10345 
10346 			if ((vn = xmlNewChild(param, NULL,
10347 			    (xmlChar *)"value_node", NULL)) == NULL)
10348 				uu_die(emsg_create_xml);
10349 
10350 			if (scf_value_get_as_string(exp_val, exp_str,
10351 			    exp_str_sz) < 0)
10352 				scfdie();
10353 
10354 			safe_setprop(vn, value_attr, exp_str);
10355 		}
10356 		if (ret != 0)
10357 			scfdie();
10358 	}
10359 
10360 	if (elts->parameter == NULL)
10361 		elts->parameter = param;
10362 	else
10363 		(void) xmlAddSibling(elts->parameter, param);
10364 }
10365 
10366 /*
10367  * Process notification parameters for a service or instance
10368  */
10369 static void
10370 export_notify_params(scf_propertygroup_t *pg, struct entity_elts *elts)
10371 {
10372 	xmlNodePtr n, event, *type;
10373 	struct params_elts *eelts;
10374 	int ret, err, i;
10375 
10376 	n = xmlNewNode(NULL, (xmlChar *)"notification_parameters");
10377 	event = xmlNewNode(NULL, (xmlChar *)"event");
10378 	if (n == NULL || event == NULL)
10379 		uu_die(emsg_create_xml);
10380 
10381 	/* event value */
10382 	if (scf_pg_get_name(pg, exp_str, max_scf_name_len + 1) < 0)
10383 		scfdie();
10384 	safe_setprop(event, value_attr, exp_str);
10385 
10386 	(void) xmlAddChild(n, event);
10387 
10388 	if ((type = calloc(URI_SCHEME_NUM, sizeof (xmlNodePtr))) == NULL ||
10389 	    (eelts = calloc(URI_SCHEME_NUM,
10390 	    sizeof (struct params_elts))) == NULL)
10391 		uu_die(gettext("Out of memory.\n"));
10392 
10393 	err = 0;
10394 
10395 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
10396 		scfdie();
10397 
10398 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
10399 		char *t, *p;
10400 
10401 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
10402 			scfdie();
10403 
10404 		if ((t = strtok_r(exp_str, ",", &p)) == NULL || p == NULL) {
10405 			/*
10406 			 * this is not a well formed notification parameters
10407 			 * element, we should export as regular pg
10408 			 */
10409 			err = 1;
10410 			break;
10411 		}
10412 
10413 		if ((i = check_uri_protocol(t)) < 0) {
10414 			err = 1;
10415 			break;
10416 		}
10417 
10418 		if (type[i] == NULL) {
10419 			if ((type[i] = xmlNewNode(NULL, (xmlChar *)"type")) ==
10420 			    NULL)
10421 				uu_die(emsg_create_xml);
10422 
10423 			safe_setprop(type[i], name_attr, t);
10424 		}
10425 		if (strcmp(p, active_attr) == 0) {
10426 			if (set_attr_from_prop(exp_prop, type[i],
10427 			    active_attr) != 0) {
10428 				err = 1;
10429 				break;
10430 			}
10431 			continue;
10432 		}
10433 		/*
10434 		 * We export the parameter
10435 		 */
10436 		export_parameter(exp_prop, p, &eelts[i]);
10437 	}
10438 
10439 	if (ret == -1)
10440 		scfdie();
10441 
10442 	if (err == 1) {
10443 		for (i = 0; i < URI_SCHEME_NUM; ++i)
10444 			xmlFree(type[i]);
10445 		free(type);
10446 
10447 		export_pg(pg, elts, SCE_ALL_VALUES);
10448 
10449 		return;
10450 	} else {
10451 		for (i = 0; i < URI_SCHEME_NUM; ++i)
10452 			if (type[i] != NULL) {
10453 				(void) xmlAddChildList(type[i],
10454 				    eelts[i].paramval);
10455 				(void) xmlAddChildList(type[i],
10456 				    eelts[i].parameter);
10457 				(void) xmlAddSibling(event, type[i]);
10458 			}
10459 	}
10460 	free(type);
10461 
10462 	if (elts->notify_params == NULL)
10463 		elts->notify_params = n;
10464 	else
10465 		(void) xmlAddSibling(elts->notify_params, n);
10466 }
10467 
10468 /*
10469  * Process the general property group for an instance.
10470  */
10471 static void
10472 export_inst_general(scf_propertygroup_t *pg, xmlNodePtr inode,
10473     struct entity_elts *elts)
10474 {
10475 	uint8_t enabled;
10476 	struct pg_elts pgelts;
10477 	int ret;
10478 
10479 	/* enabled */
10480 	if (pg_get_prop(pg, scf_property_enabled, exp_prop) == 0 &&
10481 	    prop_check_type(exp_prop, SCF_TYPE_BOOLEAN) == 0 &&
10482 	    prop_get_val(exp_prop, exp_val) == 0) {
10483 		if (scf_value_get_boolean(exp_val, &enabled) != SCF_SUCCESS)
10484 			scfdie();
10485 	} else {
10486 		enabled = 0;
10487 	}
10488 
10489 	safe_setprop(inode, enabled_attr, enabled ? true : false);
10490 
10491 	if (scf_iter_pg_properties(exp_prop_iter, pg) != SCF_SUCCESS)
10492 		scfdie();
10493 
10494 	(void) memset(&pgelts, 0, sizeof (pgelts));
10495 
10496 	while ((ret = scf_iter_next_property(exp_prop_iter, exp_prop)) == 1) {
10497 		if (scf_property_get_name(exp_prop, exp_str, exp_str_sz) < 0)
10498 			scfdie();
10499 
10500 		if (strcmp(exp_str, scf_property_enabled) == 0) {
10501 			continue;
10502 		} else if (strcmp(exp_str, SCF_PROPERTY_RESTARTER) == 0) {
10503 			xmlNodePtr rnode, sfnode;
10504 
10505 			rnode = xmlNewNode(NULL, (xmlChar *)"restarter");
10506 			if (rnode == NULL)
10507 				uu_die(emsg_create_xml);
10508 
10509 			sfnode = xmlNewChild(rnode, NULL,
10510 			    (xmlChar *)"service_fmri", NULL);
10511 			if (sfnode == NULL)
10512 				uu_die(emsg_create_xml);
10513 
10514 			if (set_attr_from_prop(exp_prop, sfnode,
10515 			    value_attr) == 0) {
10516 				elts->restarter = rnode;
10517 				continue;
10518 			}
10519 
10520 			xmlFreeNode(rnode);
10521 		}
10522 
10523 		export_property(exp_prop, exp_str, &pgelts, SCE_ALL_VALUES);
10524 	}
10525 	if (ret == -1)
10526 		scfdie();
10527 
10528 	if (pgelts.propvals != NULL || pgelts.properties != NULL)
10529 		export_pg_elts(&pgelts, scf_pg_general, scf_group_framework,
10530 		    elts);
10531 }
10532 
10533 /*
10534  * Put an instance element for the given instance into selts.
10535  */
10536 static void
10537 export_instance(scf_instance_t *inst, struct entity_elts *selts, int flags)
10538 {
10539 	xmlNodePtr n;
10540 	boolean_t isdefault;
10541 	struct entity_elts elts;
10542 	struct template_elts template_elts;
10543 	int ret;
10544 
10545 	n = xmlNewNode(NULL, (xmlChar *)"instance");
10546 	if (n == NULL)
10547 		uu_die(emsg_create_xml);
10548 
10549 	/* name */
10550 	if (scf_instance_get_name(inst, exp_str, exp_str_sz) < 0)
10551 		scfdie();
10552 	safe_setprop(n, name_attr, exp_str);
10553 	isdefault = strcmp(exp_str, "default") == 0;
10554 
10555 	/* check existance of general pg (since general/enabled is required) */
10556 	if (scf_instance_get_pg(inst, scf_pg_general, exp_pg) != SCF_SUCCESS) {
10557 		if (scf_error() != SCF_ERROR_NOT_FOUND)
10558 			scfdie();
10559 
10560 		if (g_verbose) {
10561 			if (scf_instance_to_fmri(inst, exp_str, exp_str_sz) < 0)
10562 				scfdie();
10563 
10564 			warn(gettext("Instance %s has no general property "
10565 			    "group; it will be marked disabled.\n"), exp_str);
10566 		}
10567 
10568 		safe_setprop(n, enabled_attr, false);
10569 	} else if (scf_pg_get_type(exp_pg, exp_str, exp_str_sz) < 0 ||
10570 	    strcmp(exp_str, scf_group_framework) != 0) {
10571 		if (g_verbose) {
10572 			if (scf_pg_to_fmri(exp_pg, exp_str, exp_str_sz) < 0)
10573 				scfdie();
10574 
10575 			warn(gettext("Property group %s is not of type "
10576 			    "framework; the instance will be marked "
10577 			    "disabled.\n"), exp_str);
10578 		}
10579 
10580 		safe_setprop(n, enabled_attr, false);
10581 	}
10582 
10583 	/* property groups */
10584 	if (scf_iter_instance_pgs(exp_pg_iter, inst) < 0)
10585 		scfdie();
10586 
10587 	(void) memset(&elts, 0, sizeof (elts));
10588 	(void) memset(&template_elts, 0, sizeof (template_elts));
10589 
10590 	while ((ret = scf_iter_next_pg(exp_pg_iter, exp_pg)) == 1) {
10591 		uint32_t pgflags;
10592 
10593 		if (scf_pg_get_flags(exp_pg, &pgflags) != 0)
10594 			scfdie();
10595 
10596 		if (pgflags & SCF_PG_FLAG_NONPERSISTENT)
10597 			continue;
10598 
10599 		if (scf_pg_get_type(exp_pg, exp_str, exp_str_sz) < 0)
10600 			scfdie();
10601 
10602 		if (strcmp(exp_str, SCF_GROUP_DEPENDENCY) == 0) {
10603 			export_dependency(exp_pg, &elts);
10604 			continue;
10605 		} else if (strcmp(exp_str, SCF_GROUP_METHOD) == 0) {
10606 			export_method(exp_pg, &elts);
10607 			continue;
10608 		} else if (strcmp(exp_str, scf_group_framework) == 0) {
10609 			if (scf_pg_get_name(exp_pg, exp_str,
10610 			    max_scf_name_len + 1) < 0)
10611 				scfdie();
10612 
10613 			if (strcmp(exp_str, scf_pg_general) == 0) {
10614 				export_inst_general(exp_pg, n, &elts);
10615 				continue;
10616 			} else if (strcmp(exp_str, SCF_PG_METHOD_CONTEXT) ==
10617 			    0) {
10618 				export_method_context(exp_pg, &elts);
10619 				continue;
10620 			} else if (strcmp(exp_str, SCF_PG_DEPENDENTS) == 0) {
10621 				export_dependents(exp_pg, &elts);
10622 				continue;
10623 			}
10624 		} else if (strcmp(exp_str, SCF_GROUP_TEMPLATE) == 0) {
10625 			export_template(exp_pg, &elts, &template_elts);
10626 			continue;
10627 		} else if (strcmp(exp_str, SCF_NOTIFY_PARAMS_PG_TYPE) == 0) {
10628 			export_notify_params(exp_pg, &elts);
10629 			continue;
10630 		}
10631 
10632 		/* Ordinary pg. */
10633 		export_pg(exp_pg, &elts, flags);
10634 	}
10635 	if (ret == -1)
10636 		scfdie();
10637 
10638 	if (template_elts.common_name != NULL) {
10639 		elts.template = xmlNewNode(NULL, (xmlChar *)"template");
10640 		(void) xmlAddChild(elts.template, template_elts.common_name);
10641 		(void) xmlAddChild(elts.template, template_elts.description);
10642 		(void) xmlAddChild(elts.template, template_elts.documentation);
10643 	} else {
10644 		xmlFreeNode(template_elts.description);
10645 		xmlFreeNode(template_elts.documentation);
10646 	}
10647 
10648 	if (isdefault && elts.restarter == NULL &&
10649 	    elts.dependencies == NULL && elts.method_context == NULL &&
10650 	    elts.exec_methods == NULL && elts.notify_params == NULL &&
10651 	    elts.property_groups == NULL && elts.template == NULL) {
10652 		xmlChar *eval;
10653 
10654 		/* This is a default instance */
10655 		eval = xmlGetProp(n, (xmlChar *)enabled_attr);
10656 
10657 		xmlFreeNode(n);
10658 
10659 		n = xmlNewNode(NULL, (xmlChar *)"create_default_instance");
10660 		if (n == NULL)
10661 			uu_die(emsg_create_xml);
10662 
10663 		safe_setprop(n, enabled_attr, (char *)eval);
10664 		xmlFree(eval);
10665 
10666 		selts->create_default_instance = n;
10667 	} else {
10668 		/* Assemble the children in order. */
10669 		(void) xmlAddChild(n, elts.restarter);
10670 		(void) xmlAddChildList(n, elts.dependencies);
10671 		(void) xmlAddChildList(n, elts.dependents);
10672 		(void) xmlAddChild(n, elts.method_context);
10673 		(void) xmlAddChildList(n, elts.exec_methods);
10674 		(void) xmlAddChildList(n, elts.notify_params);
10675 		(void) xmlAddChildList(n, elts.property_groups);
10676 		(void) xmlAddChild(n, elts.template);
10677 
10678 		if (selts->instances == NULL)
10679 			selts->instances = n;
10680 		else
10681 			(void) xmlAddSibling(selts->instances, n);
10682 	}
10683 }
10684 
10685 /*
10686  * Return a service element for the given service.
10687  */
10688 static xmlNodePtr
10689 export_service(scf_service_t *svc, int flags)
10690 {
10691 	xmlNodePtr snode;
10692 	struct entity_elts elts;
10693 	struct template_elts template_elts;
10694 	int ret;
10695 
10696 	snode = xmlNewNode(NULL, (xmlChar *)"service");
10697 	if (snode == NULL)
10698 		uu_die(emsg_create_xml);
10699 
10700 	/* Get & set name attribute */
10701 	if (scf_service_get_name(svc, exp_str, max_scf_name_len + 1) < 0)
10702 		scfdie();
10703 	safe_setprop(snode, name_attr, exp_str);
10704 
10705 	safe_setprop(snode, type_attr, "service");
10706 	safe_setprop(snode, "version", "0");
10707 
10708 	/* Acquire child elements. */
10709 	if (scf_iter_service_pgs(exp_pg_iter, svc) != SCF_SUCCESS)
10710 		scfdie();
10711 
10712 	(void) memset(&elts, 0, sizeof (elts));
10713 	(void) memset(&template_elts, 0, sizeof (template_elts));
10714 
10715 	while ((ret = scf_iter_next_pg(exp_pg_iter, exp_pg)) == 1) {
10716 		uint32_t pgflags;
10717 
10718 		if (scf_pg_get_flags(exp_pg, &pgflags) != 0)
10719 			scfdie();
10720 
10721 		if (pgflags & SCF_PG_FLAG_NONPERSISTENT)
10722 			continue;
10723 
10724 		if (scf_pg_get_type(exp_pg, exp_str, exp_str_sz) < 0)
10725 			scfdie();
10726 
10727 		if (strcmp(exp_str, SCF_GROUP_DEPENDENCY) == 0) {
10728 			export_dependency(exp_pg, &elts);
10729 			continue;
10730 		} else if (strcmp(exp_str, SCF_GROUP_METHOD) == 0) {
10731 			export_method(exp_pg, &elts);
10732 			continue;
10733 		} else if (strcmp(exp_str, scf_group_framework) == 0) {
10734 			if (scf_pg_get_name(exp_pg, exp_str,
10735 			    max_scf_name_len + 1) < 0)
10736 				scfdie();
10737 
10738 			if (strcmp(exp_str, scf_pg_general) == 0) {
10739 				export_svc_general(exp_pg, &elts);
10740 				continue;
10741 			} else if (strcmp(exp_str, SCF_PG_METHOD_CONTEXT) ==
10742 			    0) {
10743 				export_method_context(exp_pg, &elts);
10744 				continue;
10745 			} else if (strcmp(exp_str, SCF_PG_DEPENDENTS) == 0) {
10746 				export_dependents(exp_pg, &elts);
10747 				continue;
10748 			} else if (strcmp(exp_str, SCF_PG_MANIFESTFILES) == 0) {
10749 				continue;
10750 			}
10751 		} else if (strcmp(exp_str, SCF_GROUP_TEMPLATE) == 0) {
10752 			export_template(exp_pg, &elts, &template_elts);
10753 			continue;
10754 		} else if (strcmp(exp_str, SCF_NOTIFY_PARAMS_PG_TYPE) == 0) {
10755 			export_notify_params(exp_pg, &elts);
10756 			continue;
10757 		}
10758 
10759 		export_pg(exp_pg, &elts, flags);
10760 	}
10761 	if (ret == -1)
10762 		scfdie();
10763 
10764 	if (template_elts.common_name != NULL) {
10765 		elts.template = xmlNewNode(NULL, (xmlChar *)"template");
10766 		(void) xmlAddChild(elts.template, template_elts.common_name);
10767 		(void) xmlAddChild(elts.template, template_elts.description);
10768 		(void) xmlAddChild(elts.template, template_elts.documentation);
10769 	} else {
10770 		xmlFreeNode(template_elts.description);
10771 		xmlFreeNode(template_elts.documentation);
10772 	}
10773 
10774 	/* Iterate instances */
10775 	if (scf_iter_service_instances(exp_inst_iter, svc) != SCF_SUCCESS)
10776 		scfdie();
10777 
10778 	while ((ret = scf_iter_next_instance(exp_inst_iter, exp_inst)) == 1)
10779 		export_instance(exp_inst, &elts, flags);
10780 	if (ret == -1)
10781 		scfdie();
10782 
10783 	/* Now add all of the accumulated elements in order. */
10784 	(void) xmlAddChild(snode, elts.create_default_instance);
10785 	(void) xmlAddChild(snode, elts.single_instance);
10786 	(void) xmlAddChild(snode, elts.restarter);
10787 	(void) xmlAddChildList(snode, elts.dependencies);
10788 	(void) xmlAddChildList(snode, elts.dependents);
10789 	(void) xmlAddChild(snode, elts.method_context);
10790 	(void) xmlAddChildList(snode, elts.exec_methods);
10791 	(void) xmlAddChildList(snode, elts.notify_params);
10792 	(void) xmlAddChildList(snode, elts.property_groups);
10793 	(void) xmlAddChildList(snode, elts.instances);
10794 	(void) xmlAddChild(snode, elts.stability);
10795 	(void) xmlAddChild(snode, elts.template);
10796 
10797 	return (snode);
10798 }
10799 
10800 static int
10801 export_callback(void *data, scf_walkinfo_t *wip)
10802 {
10803 	FILE *f;
10804 	xmlDocPtr doc;
10805 	xmlNodePtr sb;
10806 	int result;
10807 	struct export_args *argsp = (struct export_args *)data;
10808 
10809 	if ((exp_inst = scf_instance_create(g_hndl)) == NULL ||
10810 	    (exp_pg = scf_pg_create(g_hndl)) == NULL ||
10811 	    (exp_prop = scf_property_create(g_hndl)) == NULL ||
10812 	    (exp_val = scf_value_create(g_hndl)) == NULL ||
10813 	    (exp_inst_iter = scf_iter_create(g_hndl)) == NULL ||
10814 	    (exp_pg_iter = scf_iter_create(g_hndl)) == NULL ||
10815 	    (exp_prop_iter = scf_iter_create(g_hndl)) == NULL ||
10816 	    (exp_val_iter = scf_iter_create(g_hndl)) == NULL)
10817 		scfdie();
10818 
10819 	exp_str_sz = max_scf_len + 1;
10820 	exp_str = safe_malloc(exp_str_sz);
10821 
10822 	if (argsp->filename != NULL) {
10823 		errno = 0;
10824 		f = fopen(argsp->filename, "wb");
10825 		if (f == NULL) {
10826 			if (errno == 0)
10827 				uu_die(gettext("Could not open \"%s\": no free "
10828 				    "stdio streams.\n"), argsp->filename);
10829 			else
10830 				uu_die(gettext("Could not open \"%s\""),
10831 				    argsp->filename);
10832 		}
10833 	} else
10834 		f = stdout;
10835 
10836 	doc = xmlNewDoc((xmlChar *)"1.0");
10837 	if (doc == NULL)
10838 		uu_die(gettext("Could not create XML document.\n"));
10839 
10840 	if (xmlCreateIntSubset(doc, (xmlChar *)"service_bundle", NULL,
10841 	    (xmlChar *)MANIFEST_DTD_PATH) == NULL)
10842 		uu_die(emsg_create_xml);
10843 
10844 	sb = xmlNewNode(NULL, (xmlChar *)"service_bundle");
10845 	if (sb == NULL)
10846 		uu_die(emsg_create_xml);
10847 	safe_setprop(sb, type_attr, "manifest");
10848 	safe_setprop(sb, name_attr, "export");
10849 	(void) xmlAddSibling(doc->children, sb);
10850 
10851 	(void) xmlAddChild(sb, export_service(wip->svc, argsp->flags));
10852 
10853 	result = write_service_bundle(doc, f);
10854 
10855 	free(exp_str);
10856 	scf_iter_destroy(exp_val_iter);
10857 	scf_iter_destroy(exp_prop_iter);
10858 	scf_iter_destroy(exp_pg_iter);
10859 	scf_iter_destroy(exp_inst_iter);
10860 	scf_value_destroy(exp_val);
10861 	scf_property_destroy(exp_prop);
10862 	scf_pg_destroy(exp_pg);
10863 	scf_instance_destroy(exp_inst);
10864 
10865 	xmlFreeDoc(doc);
10866 
10867 	if (f != stdout)
10868 		(void) fclose(f);
10869 
10870 	return (result);
10871 }
10872 
10873 /*
10874  * Get the service named by fmri, build an XML tree which represents it, and
10875  * dump it into filename (or stdout if filename is NULL).
10876  */
10877 int
10878 lscf_service_export(char *fmri, const char *filename, int flags)
10879 {
10880 	struct export_args args;
10881 	char *fmridup;
10882 	const char *scope, *svc, *inst;
10883 	size_t cblen = 3 * max_scf_name_len;
10884 	char *canonbuf = alloca(cblen);
10885 	int ret, err;
10886 
10887 	lscf_prep_hndl();
10888 
10889 	bzero(&args, sizeof (args));
10890 	args.filename = filename;
10891 	args.flags = flags;
10892 
10893 	/*
10894 	 * If some poor user has passed an exact instance FMRI, of the sort
10895 	 * one might cut and paste from svcs(1) or an error message, warn
10896 	 * and chop off the instance instead of failing.
10897 	 */
10898 	fmridup = alloca(strlen(fmri) + 1);
10899 	(void) strcpy(fmridup, fmri);
10900 	if (strncmp(fmridup, SCF_FMRI_SVC_PREFIX,
10901 	    sizeof (SCF_FMRI_SVC_PREFIX) -1) == 0 &&
10902 	    scf_parse_svc_fmri(fmridup, &scope, &svc, &inst, NULL, NULL) == 0 &&
10903 	    inst != NULL) {
10904 		(void) strlcpy(canonbuf, "svc:/", cblen);
10905 		if (strcmp(scope, SCF_FMRI_LOCAL_SCOPE) != 0) {
10906 			(void) strlcat(canonbuf, "/", cblen);
10907 			(void) strlcat(canonbuf, scope, cblen);
10908 		}
10909 		(void) strlcat(canonbuf, svc, cblen);
10910 		fmri = canonbuf;
10911 
10912 		warn(gettext("Only services may be exported; ignoring "
10913 		    "instance portion of argument.\n"));
10914 	}
10915 
10916 	err = 0;
10917 	if ((ret = scf_walk_fmri(g_hndl, 1, (char **)&fmri,
10918 	    SCF_WALK_SERVICE | SCF_WALK_NOINSTANCE, export_callback,
10919 	    &args, &err, semerr)) != 0) {
10920 		if (ret != -1)
10921 			semerr(gettext("Failed to walk instances: %s\n"),
10922 			    scf_strerror(ret));
10923 		return (-1);
10924 	}
10925 
10926 	/*
10927 	 * Error message has already been printed.
10928 	 */
10929 	if (err != 0)
10930 		return (-1);
10931 
10932 	return (0);
10933 }
10934 
10935 
10936 /*
10937  * Archive
10938  */
10939 
10940 static xmlNodePtr
10941 make_archive(int flags)
10942 {
10943 	xmlNodePtr sb;
10944 	scf_scope_t *scope;
10945 	scf_service_t *svc;
10946 	scf_iter_t *iter;
10947 	int r;
10948 
10949 	if ((scope = scf_scope_create(g_hndl)) == NULL ||
10950 	    (svc = scf_service_create(g_hndl)) == NULL ||
10951 	    (iter = scf_iter_create(g_hndl)) == NULL ||
10952 	    (exp_inst = scf_instance_create(g_hndl)) == NULL ||
10953 	    (exp_pg = scf_pg_create(g_hndl)) == NULL ||
10954 	    (exp_prop = scf_property_create(g_hndl)) == NULL ||
10955 	    (exp_val = scf_value_create(g_hndl)) == NULL ||
10956 	    (exp_inst_iter = scf_iter_create(g_hndl)) == NULL ||
10957 	    (exp_pg_iter = scf_iter_create(g_hndl)) == NULL ||
10958 	    (exp_prop_iter = scf_iter_create(g_hndl)) == NULL ||
10959 	    (exp_val_iter = scf_iter_create(g_hndl)) == NULL)
10960 		scfdie();
10961 
10962 	exp_str_sz = max_scf_len + 1;
10963 	exp_str = safe_malloc(exp_str_sz);
10964 
10965 	sb = xmlNewNode(NULL, (xmlChar *)"service_bundle");
10966 	if (sb == NULL)
10967 		uu_die(emsg_create_xml);
10968 	safe_setprop(sb, type_attr, "archive");
10969 	safe_setprop(sb, name_attr, "none");
10970 
10971 	if (scf_handle_get_scope(g_hndl, SCF_SCOPE_LOCAL, scope) != 0)
10972 		scfdie();
10973 	if (scf_iter_scope_services(iter, scope) != 0)
10974 		scfdie();
10975 
10976 	for (;;) {
10977 		r = scf_iter_next_service(iter, svc);
10978 		if (r == 0)
10979 			break;
10980 		if (r != 1)
10981 			scfdie();
10982 
10983 		if (scf_service_get_name(svc, exp_str,
10984 		    max_scf_name_len + 1) < 0)
10985 			scfdie();
10986 
10987 		if (strcmp(exp_str, SCF_LEGACY_SERVICE) == 0)
10988 			continue;
10989 
10990 		(void) xmlAddChild(sb, export_service(svc, flags));
10991 	}
10992 
10993 	free(exp_str);
10994 
10995 	scf_iter_destroy(exp_val_iter);
10996 	scf_iter_destroy(exp_prop_iter);
10997 	scf_iter_destroy(exp_pg_iter);
10998 	scf_iter_destroy(exp_inst_iter);
10999 	scf_value_destroy(exp_val);
11000 	scf_property_destroy(exp_prop);
11001 	scf_pg_destroy(exp_pg);
11002 	scf_instance_destroy(exp_inst);
11003 	scf_iter_destroy(iter);
11004 	scf_service_destroy(svc);
11005 	scf_scope_destroy(scope);
11006 
11007 	return (sb);
11008 }
11009 
11010 int
11011 lscf_archive(const char *filename, int flags)
11012 {
11013 	FILE *f;
11014 	xmlDocPtr doc;
11015 	int result;
11016 
11017 	lscf_prep_hndl();
11018 
11019 	if (filename != NULL) {
11020 		errno = 0;
11021 		f = fopen(filename, "wb");
11022 		if (f == NULL) {
11023 			if (errno == 0)
11024 				uu_die(gettext("Could not open \"%s\": no free "
11025 				    "stdio streams.\n"), filename);
11026 			else
11027 				uu_die(gettext("Could not open \"%s\""),
11028 				    filename);
11029 		}
11030 	} else
11031 		f = stdout;
11032 
11033 	doc = xmlNewDoc((xmlChar *)"1.0");
11034 	if (doc == NULL)
11035 		uu_die(gettext("Could not create XML document.\n"));
11036 
11037 	if (xmlCreateIntSubset(doc, (xmlChar *)"service_bundle", NULL,
11038 	    (xmlChar *)MANIFEST_DTD_PATH) == NULL)
11039 		uu_die(emsg_create_xml);
11040 
11041 	(void) xmlAddSibling(doc->children, make_archive(flags));
11042 
11043 	result = write_service_bundle(doc, f);
11044 
11045 	xmlFreeDoc(doc);
11046 
11047 	if (f != stdout)
11048 		(void) fclose(f);
11049 
11050 	return (result);
11051 }
11052 
11053 
11054 /*
11055  * "Extract" a profile.
11056  */
11057 int
11058 lscf_profile_extract(const char *filename)
11059 {
11060 	FILE *f;
11061 	xmlDocPtr doc;
11062 	xmlNodePtr sb, snode, inode;
11063 	scf_scope_t *scope;
11064 	scf_service_t *svc;
11065 	scf_instance_t *inst;
11066 	scf_propertygroup_t *pg;
11067 	scf_property_t *prop;
11068 	scf_value_t *val;
11069 	scf_iter_t *siter, *iiter;
11070 	int r, s;
11071 	char *namebuf;
11072 	uint8_t b;
11073 	int result;
11074 
11075 	lscf_prep_hndl();
11076 
11077 	if (filename != NULL) {
11078 		errno = 0;
11079 		f = fopen(filename, "wb");
11080 		if (f == NULL) {
11081 			if (errno == 0)
11082 				uu_die(gettext("Could not open \"%s\": no "
11083 				    "free stdio streams.\n"), filename);
11084 			else
11085 				uu_die(gettext("Could not open \"%s\""),
11086 				    filename);
11087 		}
11088 	} else
11089 		f = stdout;
11090 
11091 	doc = xmlNewDoc((xmlChar *)"1.0");
11092 	if (doc == NULL)
11093 		uu_die(gettext("Could not create XML document.\n"));
11094 
11095 	if (xmlCreateIntSubset(doc, (xmlChar *)"service_bundle", NULL,
11096 	    (xmlChar *)MANIFEST_DTD_PATH) == NULL)
11097 		uu_die(emsg_create_xml);
11098 
11099 	sb = xmlNewNode(NULL, (xmlChar *)"service_bundle");
11100 	if (sb == NULL)
11101 		uu_die(emsg_create_xml);
11102 	safe_setprop(sb, type_attr, "profile");
11103 	safe_setprop(sb, name_attr, "extract");
11104 	(void) xmlAddSibling(doc->children, sb);
11105 
11106 	if ((scope = scf_scope_create(g_hndl)) == NULL ||
11107 	    (svc = scf_service_create(g_hndl)) == NULL ||
11108 	    (inst = scf_instance_create(g_hndl)) == NULL ||
11109 	    (pg = scf_pg_create(g_hndl)) == NULL ||
11110 	    (prop = scf_property_create(g_hndl)) == NULL ||
11111 	    (val = scf_value_create(g_hndl)) == NULL ||
11112 	    (siter = scf_iter_create(g_hndl)) == NULL ||
11113 	    (iiter = scf_iter_create(g_hndl)) == NULL)
11114 		scfdie();
11115 
11116 	if (scf_handle_get_local_scope(g_hndl, scope) != SCF_SUCCESS)
11117 		scfdie();
11118 
11119 	if (scf_iter_scope_services(siter, scope) != SCF_SUCCESS)
11120 		scfdie();
11121 
11122 	namebuf = safe_malloc(max_scf_name_len + 1);
11123 
11124 	while ((r = scf_iter_next_service(siter, svc)) == 1) {
11125 		if (scf_iter_service_instances(iiter, svc) != SCF_SUCCESS)
11126 			scfdie();
11127 
11128 		snode = xmlNewNode(NULL, (xmlChar *)"service");
11129 		if (snode == NULL)
11130 			uu_die(emsg_create_xml);
11131 
11132 		if (scf_service_get_name(svc, namebuf, max_scf_name_len + 1) <
11133 		    0)
11134 			scfdie();
11135 
11136 		safe_setprop(snode, name_attr, namebuf);
11137 
11138 		safe_setprop(snode, type_attr, "service");
11139 		safe_setprop(snode, "version", "0");
11140 
11141 		while ((s = scf_iter_next_instance(iiter, inst)) == 1) {
11142 			if (scf_instance_get_pg(inst, scf_pg_general, pg) !=
11143 			    SCF_SUCCESS) {
11144 				if (scf_error() != SCF_ERROR_NOT_FOUND)
11145 					scfdie();
11146 
11147 				if (g_verbose) {
11148 					ssize_t len;
11149 					char *fmri;
11150 
11151 					len =
11152 					    scf_instance_to_fmri(inst, NULL, 0);
11153 					if (len < 0)
11154 						scfdie();
11155 
11156 					fmri = safe_malloc(len + 1);
11157 
11158 					if (scf_instance_to_fmri(inst, fmri,
11159 					    len + 1) < 0)
11160 						scfdie();
11161 
11162 					warn("Instance %s has no \"%s\" "
11163 					    "property group.\n", fmri,
11164 					    scf_pg_general);
11165 
11166 					free(fmri);
11167 				}
11168 
11169 				continue;
11170 			}
11171 
11172 			if (pg_get_prop(pg, scf_property_enabled, prop) != 0 ||
11173 			    prop_check_type(prop, SCF_TYPE_BOOLEAN) != 0 ||
11174 			    prop_get_val(prop, val) != 0)
11175 				continue;
11176 
11177 			inode = xmlNewChild(snode, NULL, (xmlChar *)"instance",
11178 			    NULL);
11179 			if (inode == NULL)
11180 				uu_die(emsg_create_xml);
11181 
11182 			if (scf_instance_get_name(inst, namebuf,
11183 			    max_scf_name_len + 1) < 0)
11184 				scfdie();
11185 
11186 			safe_setprop(inode, name_attr, namebuf);
11187 
11188 			if (scf_value_get_boolean(val, &b) != SCF_SUCCESS)
11189 				scfdie();
11190 
11191 			safe_setprop(inode, enabled_attr, b ? true : false);
11192 		}
11193 		if (s < 0)
11194 			scfdie();
11195 
11196 		if (snode->children != NULL)
11197 			(void) xmlAddChild(sb, snode);
11198 		else
11199 			xmlFreeNode(snode);
11200 	}
11201 	if (r < 0)
11202 		scfdie();
11203 
11204 	free(namebuf);
11205 
11206 	result = write_service_bundle(doc, f);
11207 
11208 	xmlFreeDoc(doc);
11209 
11210 	if (f != stdout)
11211 		(void) fclose(f);
11212 
11213 	return (result);
11214 }
11215 
11216 
11217 /*
11218  * Entity manipulation commands
11219  */
11220 
11221 /*
11222  * Entity selection.  If no entity is selected, then the current scope is in
11223  * cur_scope, and cur_svc and cur_inst are NULL.  When a service is selected,
11224  * only cur_inst is NULL, and when an instance is selected, none are NULL.
11225  * When the snaplevel of a snapshot is selected, cur_level, cur_snap, and
11226  * cur_inst will be non-NULL.
11227  */
11228 
11229 /* Returns 1 if maybe absolute fmri, 0 on success (dies on failure) */
11230 static int
11231 select_inst(const char *name)
11232 {
11233 	scf_instance_t *inst;
11234 	scf_error_t err;
11235 
11236 	assert(cur_svc != NULL);
11237 
11238 	inst = scf_instance_create(g_hndl);
11239 	if (inst == NULL)
11240 		scfdie();
11241 
11242 	if (scf_service_get_instance(cur_svc, name, inst) == SCF_SUCCESS) {
11243 		cur_inst = inst;
11244 		return (0);
11245 	}
11246 
11247 	err = scf_error();
11248 	if (err != SCF_ERROR_NOT_FOUND && err != SCF_ERROR_INVALID_ARGUMENT)
11249 		scfdie();
11250 
11251 	scf_instance_destroy(inst);
11252 	return (1);
11253 }
11254 
11255 /* Returns as above. */
11256 static int
11257 select_svc(const char *name)
11258 {
11259 	scf_service_t *svc;
11260 	scf_error_t err;
11261 
11262 	assert(cur_scope != NULL);
11263 
11264 	svc = scf_service_create(g_hndl);
11265 	if (svc == NULL)
11266 		scfdie();
11267 
11268 	if (scf_scope_get_service(cur_scope, name, svc) == SCF_SUCCESS) {
11269 		cur_svc = svc;
11270 		return (0);
11271 	}
11272 
11273 	err = scf_error();
11274 	if (err != SCF_ERROR_NOT_FOUND && err != SCF_ERROR_INVALID_ARGUMENT)
11275 		scfdie();
11276 
11277 	scf_service_destroy(svc);
11278 	return (1);
11279 }
11280 
11281 /* ARGSUSED */
11282 static int
11283 select_callback(void *unused, scf_walkinfo_t *wip)
11284 {
11285 	scf_instance_t *inst;
11286 	scf_service_t *svc;
11287 	scf_scope_t *scope;
11288 
11289 	if (wip->inst != NULL) {
11290 		if ((scope = scf_scope_create(g_hndl)) == NULL ||
11291 		    (svc = scf_service_create(g_hndl)) == NULL ||
11292 		    (inst = scf_instance_create(g_hndl)) == NULL)
11293 			scfdie();
11294 
11295 		if (scf_handle_decode_fmri(g_hndl, wip->fmri, scope, svc,
11296 		    inst, NULL, NULL, SCF_DECODE_FMRI_EXACT) != SCF_SUCCESS)
11297 			scfdie();
11298 	} else {
11299 		assert(wip->svc != NULL);
11300 
11301 		if ((scope = scf_scope_create(g_hndl)) == NULL ||
11302 		    (svc = scf_service_create(g_hndl)) == NULL)
11303 			scfdie();
11304 
11305 		if (scf_handle_decode_fmri(g_hndl, wip->fmri, scope, svc,
11306 		    NULL, NULL, NULL, SCF_DECODE_FMRI_EXACT) != SCF_SUCCESS)
11307 			scfdie();
11308 
11309 		inst = NULL;
11310 	}
11311 
11312 	/* Clear out the current selection */
11313 	assert(cur_scope != NULL);
11314 	scf_scope_destroy(cur_scope);
11315 	scf_service_destroy(cur_svc);
11316 	scf_instance_destroy(cur_inst);
11317 
11318 	cur_scope = scope;
11319 	cur_svc = svc;
11320 	cur_inst = inst;
11321 
11322 	return (0);
11323 }
11324 
11325 static int
11326 validate_callback(void *fmri_p, scf_walkinfo_t *wip)
11327 {
11328 	char **fmri = fmri_p;
11329 
11330 	*fmri = strdup(wip->fmri);
11331 	if (*fmri == NULL)
11332 		uu_die(gettext("Out of memory.\n"));
11333 
11334 	return (0);
11335 }
11336 
11337 /*
11338  * validate [fmri]
11339  * Perform the validation of an FMRI instance.
11340  */
11341 void
11342 lscf_validate_fmri(const char *fmri)
11343 {
11344 	int ret = 0;
11345 	size_t inst_sz;
11346 	char *inst_fmri = NULL;
11347 	scf_tmpl_errors_t *errs = NULL;
11348 	char *snapbuf = NULL;
11349 
11350 	lscf_prep_hndl();
11351 
11352 	if (fmri == NULL) {
11353 		inst_sz = max_scf_fmri_len + 1;
11354 		inst_fmri = safe_malloc(inst_sz);
11355 
11356 		if (cur_snap != NULL) {
11357 			snapbuf = safe_malloc(max_scf_name_len + 1);
11358 			if (scf_snapshot_get_name(cur_snap, snapbuf,
11359 			    max_scf_name_len + 1) < 0)
11360 				scfdie();
11361 		}
11362 		if (cur_inst == NULL) {
11363 			semerr(gettext("No instance selected\n"));
11364 			goto cleanup;
11365 		} else if (scf_instance_to_fmri(cur_inst, inst_fmri,
11366 		    inst_sz) >= inst_sz) {
11367 			/* sanity check. Should never get here */
11368 			uu_die(gettext("Unexpected error! file %s, line %d\n"),
11369 			    __FILE__, __LINE__);
11370 		}
11371 	} else {
11372 		scf_error_t scf_err;
11373 		int err = 0;
11374 
11375 		if ((scf_err = scf_walk_fmri(g_hndl, 1, (char **)&fmri, 0,
11376 		    validate_callback, &inst_fmri, &err, semerr)) != 0) {
11377 			uu_warn("Failed to walk instances: %s\n",
11378 			    scf_strerror(scf_err));
11379 			goto cleanup;
11380 		}
11381 		if (err != 0) {
11382 			/* error message displayed by scf_walk_fmri */
11383 			goto cleanup;
11384 		}
11385 	}
11386 
11387 	ret = scf_tmpl_validate_fmri(g_hndl, inst_fmri, snapbuf, &errs,
11388 	    SCF_TMPL_VALIDATE_FLAG_CURRENT);
11389 	if (ret == -1) {
11390 		if (scf_error() == SCF_ERROR_TEMPLATE_INVALID) {
11391 			warn(gettext("Template data for %s is invalid. "
11392 			    "Consider reverting to a previous snapshot or "
11393 			    "restoring original configuration.\n"), inst_fmri);
11394 		} else {
11395 			uu_warn("%s: %s\n",
11396 			    gettext("Error validating the instance"),
11397 			    scf_strerror(scf_error()));
11398 		}
11399 	} else if (ret == 1 && errs != NULL) {
11400 		scf_tmpl_error_t *err = NULL;
11401 		char *msg;
11402 		size_t len = 256;	/* initial error buffer size */
11403 		int flag = (est->sc_cmd_flags & SC_CMD_IACTIVE) ?
11404 		    SCF_TMPL_STRERROR_HUMAN : 0;
11405 
11406 		msg = safe_malloc(len);
11407 
11408 		while ((err = scf_tmpl_next_error(errs)) != NULL) {
11409 			int ret;
11410 
11411 			if ((ret = scf_tmpl_strerror(err, msg, len,
11412 			    flag)) >= len) {
11413 				len = ret + 1;
11414 				msg = realloc(msg, len);
11415 				if (msg == NULL)
11416 					uu_die(gettext(
11417 					    "Out of memory.\n"));
11418 				(void) scf_tmpl_strerror(err, msg, len,
11419 				    flag);
11420 			}
11421 			(void) fprintf(stderr, "%s\n", msg);
11422 		}
11423 		if (msg != NULL)
11424 			free(msg);
11425 	}
11426 	if (errs != NULL)
11427 		scf_tmpl_errors_destroy(errs);
11428 
11429 cleanup:
11430 	free(inst_fmri);
11431 	free(snapbuf);
11432 }
11433 
11434 static void
11435 lscf_validate_file(const char *filename)
11436 {
11437 	tmpl_errors_t *errs;
11438 
11439 	bundle_t *b = internal_bundle_new();
11440 	if (lxml_get_bundle_file(b, filename, SVCCFG_OP_IMPORT) == 0) {
11441 		if (tmpl_validate_bundle(b, &errs) != TVS_SUCCESS) {
11442 			tmpl_errors_print(stderr, errs, "");
11443 			semerr(gettext("Validation failed.\n"));
11444 		}
11445 		tmpl_errors_destroy(errs);
11446 	}
11447 	(void) internal_bundle_free(b);
11448 }
11449 
11450 /*
11451  * validate [fmri|file]
11452  */
11453 void
11454 lscf_validate(const char *arg)
11455 {
11456 	const char *str;
11457 
11458 	if (strncmp(arg, SCF_FMRI_FILE_PREFIX,
11459 	    sizeof (SCF_FMRI_FILE_PREFIX) - 1) == 0) {
11460 		str = arg + sizeof (SCF_FMRI_FILE_PREFIX) - 1;
11461 		lscf_validate_file(str);
11462 	} else if (strncmp(arg, SCF_FMRI_SVC_PREFIX,
11463 	    sizeof (SCF_FMRI_SVC_PREFIX) - 1) == 0) {
11464 		str = arg + sizeof (SCF_FMRI_SVC_PREFIX) - 1;
11465 		lscf_validate_fmri(str);
11466 	} else if (access(arg, R_OK | F_OK) == 0) {
11467 		lscf_validate_file(arg);
11468 	} else {
11469 		lscf_validate_fmri(arg);
11470 	}
11471 }
11472 
11473 void
11474 lscf_select(const char *fmri)
11475 {
11476 	int ret, err;
11477 
11478 	lscf_prep_hndl();
11479 
11480 	if (cur_snap != NULL) {
11481 		struct snaplevel *elt;
11482 		char *buf;
11483 
11484 		/* Error unless name is that of the next level. */
11485 		elt = uu_list_next(cur_levels, cur_elt);
11486 		if (elt == NULL) {
11487 			semerr(gettext("No children.\n"));
11488 			return;
11489 		}
11490 
11491 		buf = safe_malloc(max_scf_name_len + 1);
11492 
11493 		if (scf_snaplevel_get_instance_name(elt->sl, buf,
11494 		    max_scf_name_len + 1) < 0)
11495 			scfdie();
11496 
11497 		if (strcmp(buf, fmri) != 0) {
11498 			semerr(gettext("No such child.\n"));
11499 			free(buf);
11500 			return;
11501 		}
11502 
11503 		free(buf);
11504 
11505 		cur_elt = elt;
11506 		cur_level = elt->sl;
11507 		return;
11508 	}
11509 
11510 	/*
11511 	 * Special case for 'svc:', which takes the user to the scope level.
11512 	 */
11513 	if (strcmp(fmri, "svc:") == 0) {
11514 		scf_instance_destroy(cur_inst);
11515 		scf_service_destroy(cur_svc);
11516 		cur_inst = NULL;
11517 		cur_svc = NULL;
11518 		return;
11519 	}
11520 
11521 	/*
11522 	 * Special case for ':properties'.  This appears as part of 'list' but
11523 	 * can't be selected.  Give a more helpful error message in this case.
11524 	 */
11525 	if (strcmp(fmri, ":properties") == 0) {
11526 		semerr(gettext(":properties is not an entity.  Try 'listprop' "
11527 		    "to list properties.\n"));
11528 		return;
11529 	}
11530 
11531 	/*
11532 	 * First try the argument as relative to the current selection.
11533 	 */
11534 	if (cur_inst != NULL) {
11535 		/* EMPTY */;
11536 	} else if (cur_svc != NULL) {
11537 		if (select_inst(fmri) != 1)
11538 			return;
11539 	} else {
11540 		if (select_svc(fmri) != 1)
11541 			return;
11542 	}
11543 
11544 	err = 0;
11545 	if ((ret = scf_walk_fmri(g_hndl, 1, (char **)&fmri, SCF_WALK_SERVICE,
11546 	    select_callback, NULL, &err, semerr)) != 0) {
11547 		semerr(gettext("Failed to walk instances: %s\n"),
11548 		    scf_strerror(ret));
11549 	}
11550 }
11551 
11552 void
11553 lscf_unselect(void)
11554 {
11555 	lscf_prep_hndl();
11556 
11557 	if (cur_snap != NULL) {
11558 		struct snaplevel *elt;
11559 
11560 		elt = uu_list_prev(cur_levels, cur_elt);
11561 		if (elt == NULL) {
11562 			semerr(gettext("No parent levels.\n"));
11563 		} else {
11564 			cur_elt = elt;
11565 			cur_level = elt->sl;
11566 		}
11567 	} else if (cur_inst != NULL) {
11568 		scf_instance_destroy(cur_inst);
11569 		cur_inst = NULL;
11570 	} else if (cur_svc != NULL) {
11571 		scf_service_destroy(cur_svc);
11572 		cur_svc = NULL;
11573 	} else {
11574 		semerr(gettext("Cannot unselect at scope level.\n"));
11575 	}
11576 }
11577 
11578 /*
11579  * Return the FMRI of the current selection, for the prompt.
11580  */
11581 void
11582 lscf_get_selection_str(char *buf, size_t bufsz)
11583 {
11584 	char *cp;
11585 	ssize_t fmrilen, szret;
11586 	boolean_t deleted = B_FALSE;
11587 
11588 	if (g_hndl == NULL) {
11589 		(void) strlcpy(buf, "svc:", bufsz);
11590 		return;
11591 	}
11592 
11593 	if (cur_level != NULL) {
11594 		assert(cur_snap != NULL);
11595 
11596 		/* [ snapshot ] FMRI [: instance ] */
11597 		assert(bufsz >= 1 + max_scf_name_len + 1 + max_scf_fmri_len
11598 		    + 2 + max_scf_name_len + 1 + 1);
11599 
11600 		buf[0] = '[';
11601 
11602 		szret = scf_snapshot_get_name(cur_snap, buf + 1,
11603 		    max_scf_name_len + 1);
11604 		if (szret < 0) {
11605 			if (scf_error() != SCF_ERROR_DELETED)
11606 				scfdie();
11607 
11608 			goto snap_deleted;
11609 		}
11610 
11611 		(void) strcat(buf, "]svc:/");
11612 
11613 		cp = strchr(buf, '\0');
11614 
11615 		szret = scf_snaplevel_get_service_name(cur_level, cp,
11616 		    max_scf_name_len + 1);
11617 		if (szret < 0) {
11618 			if (scf_error() != SCF_ERROR_DELETED)
11619 				scfdie();
11620 
11621 			goto snap_deleted;
11622 		}
11623 
11624 		cp = strchr(cp, '\0');
11625 
11626 		if (snaplevel_is_instance(cur_level)) {
11627 			*cp++ = ':';
11628 
11629 			if (scf_snaplevel_get_instance_name(cur_level, cp,
11630 			    max_scf_name_len + 1) < 0) {
11631 				if (scf_error() != SCF_ERROR_DELETED)
11632 					scfdie();
11633 
11634 				goto snap_deleted;
11635 			}
11636 		} else {
11637 			*cp++ = '[';
11638 			*cp++ = ':';
11639 
11640 			if (scf_instance_get_name(cur_inst, cp,
11641 			    max_scf_name_len + 1) < 0) {
11642 				if (scf_error() != SCF_ERROR_DELETED)
11643 					scfdie();
11644 
11645 				goto snap_deleted;
11646 			}
11647 
11648 			(void) strcat(buf, "]");
11649 		}
11650 
11651 		return;
11652 
11653 snap_deleted:
11654 		deleted = B_TRUE;
11655 		free(buf);
11656 		unselect_cursnap();
11657 	}
11658 
11659 	assert(cur_snap == NULL);
11660 
11661 	if (cur_inst != NULL) {
11662 		assert(cur_svc != NULL);
11663 		assert(cur_scope != NULL);
11664 
11665 		fmrilen = scf_instance_to_fmri(cur_inst, buf, bufsz);
11666 		if (fmrilen >= 0) {
11667 			assert(fmrilen < bufsz);
11668 			if (deleted)
11669 				warn(emsg_deleted);
11670 			return;
11671 		}
11672 
11673 		if (scf_error() != SCF_ERROR_DELETED)
11674 			scfdie();
11675 
11676 		deleted = B_TRUE;
11677 
11678 		scf_instance_destroy(cur_inst);
11679 		cur_inst = NULL;
11680 	}
11681 
11682 	if (cur_svc != NULL) {
11683 		assert(cur_scope != NULL);
11684 
11685 		szret = scf_service_to_fmri(cur_svc, buf, bufsz);
11686 		if (szret >= 0) {
11687 			assert(szret < bufsz);
11688 			if (deleted)
11689 				warn(emsg_deleted);
11690 			return;
11691 		}
11692 
11693 		if (scf_error() != SCF_ERROR_DELETED)
11694 			scfdie();
11695 
11696 		deleted = B_TRUE;
11697 		scf_service_destroy(cur_svc);
11698 		cur_svc = NULL;
11699 	}
11700 
11701 	assert(cur_scope != NULL);
11702 	fmrilen = scf_scope_to_fmri(cur_scope, buf, bufsz);
11703 
11704 	if (fmrilen < 0)
11705 		scfdie();
11706 
11707 	assert(fmrilen < bufsz);
11708 	if (deleted)
11709 		warn(emsg_deleted);
11710 }
11711 
11712 /*
11713  * Entity listing.  Entities and colon namespaces (e.g., :properties and
11714  * :statistics) are listed for the current selection.
11715  */
11716 void
11717 lscf_list(const char *pattern)
11718 {
11719 	scf_iter_t *iter;
11720 	char *buf;
11721 	int ret;
11722 
11723 	lscf_prep_hndl();
11724 
11725 	if (cur_level != NULL) {
11726 		struct snaplevel *elt;
11727 
11728 		(void) fputs(COLON_NAMESPACES, stdout);
11729 
11730 		elt = uu_list_next(cur_levels, cur_elt);
11731 		if (elt == NULL)
11732 			return;
11733 
11734 		/*
11735 		 * For now, we know that the next level is an instance.  But
11736 		 * if we ever have multiple scopes, this could be complicated.
11737 		 */
11738 		buf = safe_malloc(max_scf_name_len + 1);
11739 		if (scf_snaplevel_get_instance_name(elt->sl, buf,
11740 		    max_scf_name_len + 1) >= 0) {
11741 			(void) puts(buf);
11742 		} else {
11743 			if (scf_error() != SCF_ERROR_DELETED)
11744 				scfdie();
11745 		}
11746 
11747 		free(buf);
11748 
11749 		return;
11750 	}
11751 
11752 	if (cur_inst != NULL) {
11753 		(void) fputs(COLON_NAMESPACES, stdout);
11754 		return;
11755 	}
11756 
11757 	iter = scf_iter_create(g_hndl);
11758 	if (iter == NULL)
11759 		scfdie();
11760 
11761 	buf = safe_malloc(max_scf_name_len + 1);
11762 
11763 	if (cur_svc != NULL) {
11764 		/* List the instances in this service. */
11765 		scf_instance_t *inst;
11766 
11767 		inst = scf_instance_create(g_hndl);
11768 		if (inst == NULL)
11769 			scfdie();
11770 
11771 		if (scf_iter_service_instances(iter, cur_svc) == 0) {
11772 			safe_printf(COLON_NAMESPACES);
11773 
11774 			for (;;) {
11775 				ret = scf_iter_next_instance(iter, inst);
11776 				if (ret == 0)
11777 					break;
11778 				if (ret != 1) {
11779 					if (scf_error() != SCF_ERROR_DELETED)
11780 						scfdie();
11781 
11782 					break;
11783 				}
11784 
11785 				if (scf_instance_get_name(inst, buf,
11786 				    max_scf_name_len + 1) >= 0) {
11787 					if (pattern == NULL ||
11788 					    fnmatch(pattern, buf, 0) == 0)
11789 						(void) puts(buf);
11790 				} else {
11791 					if (scf_error() != SCF_ERROR_DELETED)
11792 						scfdie();
11793 				}
11794 			}
11795 		} else {
11796 			if (scf_error() != SCF_ERROR_DELETED)
11797 				scfdie();
11798 		}
11799 
11800 		scf_instance_destroy(inst);
11801 	} else {
11802 		/* List the services in this scope. */
11803 		scf_service_t *svc;
11804 
11805 		assert(cur_scope != NULL);
11806 
11807 		svc = scf_service_create(g_hndl);
11808 		if (svc == NULL)
11809 			scfdie();
11810 
11811 		if (scf_iter_scope_services(iter, cur_scope) != SCF_SUCCESS)
11812 			scfdie();
11813 
11814 		for (;;) {
11815 			ret = scf_iter_next_service(iter, svc);
11816 			if (ret == 0)
11817 				break;
11818 			if (ret != 1)
11819 				scfdie();
11820 
11821 			if (scf_service_get_name(svc, buf,
11822 			    max_scf_name_len + 1) >= 0) {
11823 				if (pattern == NULL ||
11824 				    fnmatch(pattern, buf, 0) == 0)
11825 					safe_printf("%s\n", buf);
11826 			} else {
11827 				if (scf_error() != SCF_ERROR_DELETED)
11828 					scfdie();
11829 			}
11830 		}
11831 
11832 		scf_service_destroy(svc);
11833 	}
11834 
11835 	free(buf);
11836 	scf_iter_destroy(iter);
11837 }
11838 
11839 /*
11840  * Entity addition.  Creates an empty entity in the current selection.
11841  */
11842 void
11843 lscf_add(const char *name)
11844 {
11845 	lscf_prep_hndl();
11846 
11847 	if (cur_snap != NULL) {
11848 		semerr(emsg_cant_modify_snapshots);
11849 	} else if (cur_inst != NULL) {
11850 		semerr(gettext("Cannot add entities to an instance.\n"));
11851 	} else if (cur_svc != NULL) {
11852 
11853 		if (scf_service_add_instance(cur_svc, name, NULL) !=
11854 		    SCF_SUCCESS) {
11855 			switch (scf_error()) {
11856 			case SCF_ERROR_INVALID_ARGUMENT:
11857 				semerr(gettext("Invalid name.\n"));
11858 				break;
11859 
11860 			case SCF_ERROR_EXISTS:
11861 				semerr(gettext("Instance already exists.\n"));
11862 				break;
11863 
11864 			case SCF_ERROR_PERMISSION_DENIED:
11865 				semerr(emsg_permission_denied);
11866 				break;
11867 
11868 			default:
11869 				scfdie();
11870 			}
11871 		}
11872 	} else {
11873 		assert(cur_scope != NULL);
11874 
11875 		if (scf_scope_add_service(cur_scope, name, NULL) !=
11876 		    SCF_SUCCESS) {
11877 			switch (scf_error()) {
11878 			case SCF_ERROR_INVALID_ARGUMENT:
11879 				semerr(gettext("Invalid name.\n"));
11880 				break;
11881 
11882 			case SCF_ERROR_EXISTS:
11883 				semerr(gettext("Service already exists.\n"));
11884 				break;
11885 
11886 			case SCF_ERROR_PERMISSION_DENIED:
11887 				semerr(emsg_permission_denied);
11888 				break;
11889 
11890 			case SCF_ERROR_BACKEND_READONLY:
11891 				semerr(emsg_read_only);
11892 				break;
11893 
11894 			default:
11895 				scfdie();
11896 			}
11897 		}
11898 	}
11899 }
11900 
11901 /* return 1 if the entity has no persistent pgs, else return 0 */
11902 static int
11903 entity_has_no_pgs(void *ent, int isservice)
11904 {
11905 	scf_iter_t *iter = NULL;
11906 	scf_propertygroup_t *pg = NULL;
11907 	uint32_t flags;
11908 	int err;
11909 	int ret = 1;
11910 
11911 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
11912 	    (pg = scf_pg_create(g_hndl)) == NULL)
11913 		scfdie();
11914 
11915 	if (isservice) {
11916 		if (scf_iter_service_pgs(iter, (scf_service_t *)ent) < 0)
11917 			scfdie();
11918 	} else {
11919 		if (scf_iter_instance_pgs(iter, (scf_instance_t *)ent) < 0)
11920 			scfdie();
11921 	}
11922 
11923 	while ((err = scf_iter_next_pg(iter, pg)) == 1) {
11924 		if (scf_pg_get_flags(pg, &flags) != 0)
11925 			scfdie();
11926 
11927 		/* skip nonpersistent pgs */
11928 		if (flags & SCF_PG_FLAG_NONPERSISTENT)
11929 			continue;
11930 
11931 		ret = 0;
11932 		break;
11933 	}
11934 
11935 	if (err == -1)
11936 		scfdie();
11937 
11938 	scf_pg_destroy(pg);
11939 	scf_iter_destroy(iter);
11940 
11941 	return (ret);
11942 }
11943 
11944 /* return 1 if the service has no instances, else return 0 */
11945 static int
11946 svc_has_no_insts(scf_service_t *svc)
11947 {
11948 	scf_instance_t *inst;
11949 	scf_iter_t *iter;
11950 	int r;
11951 	int ret = 1;
11952 
11953 	if ((inst = scf_instance_create(g_hndl)) == NULL ||
11954 	    (iter = scf_iter_create(g_hndl)) == NULL)
11955 		scfdie();
11956 
11957 	if (scf_iter_service_instances(iter, svc) != 0)
11958 		scfdie();
11959 
11960 	r = scf_iter_next_instance(iter, inst);
11961 	if (r == 1) {
11962 		ret = 0;
11963 	} else if (r == 0) {
11964 		ret = 1;
11965 	} else if (r == -1) {
11966 		scfdie();
11967 	} else {
11968 		bad_error("scf_iter_next_instance", r);
11969 	}
11970 
11971 	scf_iter_destroy(iter);
11972 	scf_instance_destroy(inst);
11973 
11974 	return (ret);
11975 }
11976 
11977 /*
11978  * Entity deletion.
11979  */
11980 
11981 /*
11982  * Delete the property group <fmri>/:properties/<name>.  Returns
11983  * SCF_ERROR_NONE on success (or if the entity is not found),
11984  * SCF_ERROR_INVALID_ARGUMENT if the fmri is bad, SCF_ERROR_TYPE_MISMATCH if
11985  * the pg is the wrong type, or SCF_ERROR_PERMISSION_DENIED if permission was
11986  * denied.
11987  */
11988 static scf_error_t
11989 delete_dependency_pg(const char *fmri, const char *name)
11990 {
11991 	void *entity = NULL;
11992 	int isservice;
11993 	scf_propertygroup_t *pg = NULL;
11994 	scf_error_t result;
11995 	char *pgty;
11996 	scf_service_t *svc = NULL;
11997 	scf_instance_t *inst = NULL;
11998 	scf_iter_t *iter = NULL;
11999 	char *name_buf = NULL;
12000 
12001 	result = fmri_to_entity(g_hndl, fmri, &entity, &isservice);
12002 	switch (result) {
12003 	case SCF_ERROR_NONE:
12004 		break;
12005 
12006 	case SCF_ERROR_NO_MEMORY:
12007 		uu_die(gettext("Out of memory.\n"));
12008 		/* NOTREACHED */
12009 
12010 	case SCF_ERROR_INVALID_ARGUMENT:
12011 	case SCF_ERROR_CONSTRAINT_VIOLATED:
12012 		return (SCF_ERROR_INVALID_ARGUMENT);
12013 
12014 	case SCF_ERROR_NOT_FOUND:
12015 		result = SCF_ERROR_NONE;
12016 		goto out;
12017 
12018 	default:
12019 		bad_error("fmri_to_entity", result);
12020 	}
12021 
12022 	pg = scf_pg_create(g_hndl);
12023 	if (pg == NULL)
12024 		scfdie();
12025 
12026 	if (entity_get_pg(entity, isservice, name, pg) != 0) {
12027 		if (scf_error() != SCF_ERROR_NOT_FOUND)
12028 			scfdie();
12029 
12030 		result = SCF_ERROR_NONE;
12031 		goto out;
12032 	}
12033 
12034 	pgty = safe_malloc(max_scf_pg_type_len + 1);
12035 
12036 	if (scf_pg_get_type(pg, pgty, max_scf_pg_type_len + 1) < 0)
12037 		scfdie();
12038 
12039 	if (strcmp(pgty, SCF_GROUP_DEPENDENCY) != 0) {
12040 		result = SCF_ERROR_TYPE_MISMATCH;
12041 		free(pgty);
12042 		goto out;
12043 	}
12044 
12045 	free(pgty);
12046 
12047 	if (scf_pg_delete(pg) != 0) {
12048 		result = scf_error();
12049 		if (result != SCF_ERROR_PERMISSION_DENIED)
12050 			scfdie();
12051 		goto out;
12052 	}
12053 
12054 	/*
12055 	 * We have to handle the case where we've just deleted the last
12056 	 * property group of a "dummy" entity (instance or service).
12057 	 * A "dummy" entity is an entity only present to hold an
12058 	 * external dependency.
12059 	 * So, in the case we deleted the last property group then we
12060 	 * can also delete the entity. If the entity is an instance then
12061 	 * we must verify if this was the last instance for the service
12062 	 * and if it is, we can also delete the service if it doesn't
12063 	 * have any property group either.
12064 	 */
12065 
12066 	result = SCF_ERROR_NONE;
12067 
12068 	if (isservice) {
12069 		svc = (scf_service_t *)entity;
12070 
12071 		if ((inst = scf_instance_create(g_hndl)) == NULL ||
12072 		    (iter = scf_iter_create(g_hndl)) == NULL)
12073 			scfdie();
12074 
12075 		name_buf = safe_malloc(max_scf_name_len + 1);
12076 	} else {
12077 		inst = (scf_instance_t *)entity;
12078 	}
12079 
12080 	/*
12081 	 * If the entity is an instance and we've just deleted its last
12082 	 * property group then we should delete it.
12083 	 */
12084 	if (!isservice && entity_has_no_pgs(entity, isservice)) {
12085 		/* find the service before deleting the inst. - needed later */
12086 		if ((svc = scf_service_create(g_hndl)) == NULL)
12087 			scfdie();
12088 
12089 		if (scf_instance_get_parent(inst, svc) != 0)
12090 			scfdie();
12091 
12092 		/* delete the instance */
12093 		if (scf_instance_delete(inst) != 0) {
12094 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12095 				scfdie();
12096 
12097 			result = SCF_ERROR_PERMISSION_DENIED;
12098 			goto out;
12099 		}
12100 		/* no need to refresh the instance */
12101 		inst = NULL;
12102 	}
12103 
12104 	/*
12105 	 * If the service has no more instances and pgs or we just deleted the
12106 	 * last instance and the service doesn't have anymore propery groups
12107 	 * then the service should be deleted.
12108 	 */
12109 	if (svc != NULL &&
12110 	    svc_has_no_insts(svc) &&
12111 	    entity_has_no_pgs((void *)svc, 1)) {
12112 		if (scf_service_delete(svc) == 0) {
12113 			if (isservice) {
12114 				/* no need to refresh the service */
12115 				svc = NULL;
12116 			}
12117 
12118 			goto out;
12119 		}
12120 
12121 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12122 			scfdie();
12123 
12124 		result = SCF_ERROR_PERMISSION_DENIED;
12125 	}
12126 
12127 	/* if the entity has not been deleted, refresh it */
12128 	if ((isservice && svc != NULL) || (!isservice && inst != NULL)) {
12129 		(void) refresh_entity(isservice, entity, fmri, inst, iter,
12130 		    name_buf);
12131 	}
12132 
12133 out:
12134 	if (isservice && (inst != NULL && iter != NULL)) {
12135 		free(name_buf);
12136 		scf_iter_destroy(iter);
12137 		scf_instance_destroy(inst);
12138 	}
12139 
12140 	if (!isservice && svc != NULL) {
12141 		scf_service_destroy(svc);
12142 	}
12143 
12144 	scf_pg_destroy(pg);
12145 	if (entity != NULL)
12146 		entity_destroy(entity, isservice);
12147 
12148 	return (result);
12149 }
12150 
12151 static int
12152 delete_dependents(scf_propertygroup_t *pg)
12153 {
12154 	char *pgty, *name, *fmri;
12155 	scf_property_t *prop;
12156 	scf_value_t *val;
12157 	scf_iter_t *iter;
12158 	int r;
12159 	scf_error_t err;
12160 
12161 	/* Verify that the pg has the correct type. */
12162 	pgty = safe_malloc(max_scf_pg_type_len + 1);
12163 	if (scf_pg_get_type(pg, pgty, max_scf_pg_type_len + 1) < 0)
12164 		scfdie();
12165 
12166 	if (strcmp(pgty, scf_group_framework) != 0) {
12167 		if (g_verbose) {
12168 			fmri = safe_malloc(max_scf_fmri_len + 1);
12169 			if (scf_pg_to_fmri(pg, fmri, max_scf_fmri_len + 1) < 0)
12170 				scfdie();
12171 
12172 			warn(gettext("Property group %s is not of expected "
12173 			    "type %s.\n"), fmri, scf_group_framework);
12174 
12175 			free(fmri);
12176 		}
12177 
12178 		free(pgty);
12179 		return (-1);
12180 	}
12181 
12182 	free(pgty);
12183 
12184 	/* map delete_dependency_pg onto the properties. */
12185 	if ((prop = scf_property_create(g_hndl)) == NULL ||
12186 	    (val = scf_value_create(g_hndl)) == NULL ||
12187 	    (iter = scf_iter_create(g_hndl)) == NULL)
12188 		scfdie();
12189 
12190 	if (scf_iter_pg_properties(iter, pg) != SCF_SUCCESS)
12191 		scfdie();
12192 
12193 	name = safe_malloc(max_scf_name_len + 1);
12194 	fmri = safe_malloc(max_scf_fmri_len + 2);
12195 
12196 	while ((r = scf_iter_next_property(iter, prop)) == 1) {
12197 		scf_type_t ty;
12198 
12199 		if (scf_property_get_name(prop, name, max_scf_name_len + 1) < 0)
12200 			scfdie();
12201 
12202 		if (scf_property_type(prop, &ty) != SCF_SUCCESS)
12203 			scfdie();
12204 
12205 		if ((ty != SCF_TYPE_ASTRING &&
12206 		    prop_check_type(prop, SCF_TYPE_FMRI) != 0) ||
12207 		    prop_get_val(prop, val) != 0)
12208 			continue;
12209 
12210 		if (scf_value_get_astring(val, fmri, max_scf_fmri_len + 2) < 0)
12211 			scfdie();
12212 
12213 		err = delete_dependency_pg(fmri, name);
12214 		if (err == SCF_ERROR_INVALID_ARGUMENT && g_verbose) {
12215 			if (scf_property_to_fmri(prop, fmri,
12216 			    max_scf_fmri_len + 2) < 0)
12217 				scfdie();
12218 
12219 			warn(gettext("Value of %s is not a valid FMRI.\n"),
12220 			    fmri);
12221 		} else if (err == SCF_ERROR_TYPE_MISMATCH && g_verbose) {
12222 			warn(gettext("Property group \"%s\" of entity \"%s\" "
12223 			    "does not have dependency type.\n"), name, fmri);
12224 		} else if (err == SCF_ERROR_PERMISSION_DENIED && g_verbose) {
12225 			warn(gettext("Could not delete property group \"%s\" "
12226 			    "of entity \"%s\" (permission denied).\n"), name,
12227 			    fmri);
12228 		}
12229 	}
12230 	if (r == -1)
12231 		scfdie();
12232 
12233 	scf_value_destroy(val);
12234 	scf_property_destroy(prop);
12235 
12236 	return (0);
12237 }
12238 
12239 /*
12240  * Returns 1 if the instance may be running, and 0 otherwise.
12241  */
12242 static int
12243 inst_is_running(scf_instance_t *inst)
12244 {
12245 	scf_propertygroup_t *pg;
12246 	scf_property_t *prop;
12247 	scf_value_t *val;
12248 	char buf[MAX_SCF_STATE_STRING_SZ];
12249 	int ret = 0;
12250 	ssize_t szret;
12251 
12252 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
12253 	    (prop = scf_property_create(g_hndl)) == NULL ||
12254 	    (val = scf_value_create(g_hndl)) == NULL)
12255 		scfdie();
12256 
12257 	if (scf_instance_get_pg(inst, SCF_PG_RESTARTER, pg) != SCF_SUCCESS) {
12258 		if (scf_error() != SCF_ERROR_NOT_FOUND)
12259 			scfdie();
12260 		goto out;
12261 	}
12262 
12263 	if (pg_get_prop(pg, SCF_PROPERTY_STATE, prop) != 0 ||
12264 	    prop_check_type(prop, SCF_TYPE_ASTRING) != 0 ||
12265 	    prop_get_val(prop, val) != 0)
12266 		goto out;
12267 
12268 	szret = scf_value_get_astring(val, buf, sizeof (buf));
12269 	assert(szret >= 0);
12270 
12271 	ret = (strcmp(buf, SCF_STATE_STRING_ONLINE) == 0 ||
12272 	    strcmp(buf, SCF_STATE_STRING_DEGRADED) == 0) ? 1 : 0;
12273 
12274 out:
12275 	scf_value_destroy(val);
12276 	scf_property_destroy(prop);
12277 	scf_pg_destroy(pg);
12278 	return (ret);
12279 }
12280 
12281 static uint8_t
12282 pg_is_external_dependency(scf_propertygroup_t *pg)
12283 {
12284 	char *type;
12285 	scf_value_t *val;
12286 	scf_property_t *prop;
12287 	uint8_t b = B_FALSE;
12288 
12289 	type = safe_malloc(max_scf_pg_type_len + 1);
12290 
12291 	if (scf_pg_get_type(pg, type, max_scf_pg_type_len + 1) < 0)
12292 		scfdie();
12293 
12294 	if ((prop = scf_property_create(g_hndl)) == NULL ||
12295 	    (val = scf_value_create(g_hndl)) == NULL)
12296 		scfdie();
12297 
12298 	if (strcmp(type, SCF_GROUP_DEPENDENCY) == 0) {
12299 		if (pg_get_prop(pg, scf_property_external, prop) == 0) {
12300 			if (scf_property_get_value(prop, val) != 0)
12301 				scfdie();
12302 			if (scf_value_get_boolean(val, &b) != 0)
12303 				scfdie();
12304 		}
12305 	}
12306 
12307 	free(type);
12308 	(void) scf_value_destroy(val);
12309 	(void) scf_property_destroy(prop);
12310 
12311 	return (b);
12312 }
12313 
12314 #define	DELETE_FAILURE			-1
12315 #define	DELETE_SUCCESS_NOEXTDEPS	0
12316 #define	DELETE_SUCCESS_EXTDEPS		1
12317 
12318 /*
12319  * lscf_instance_delete() deletes an instance.  Before calling
12320  * scf_instance_delete(), though, we make sure the instance isn't
12321  * running and delete dependencies in other entities which the instance
12322  * declared as "dependents".  If there are dependencies which were
12323  * created for other entities, then instead of deleting the instance we
12324  * make it "empty" by deleting all other property groups and all
12325  * snapshots.
12326  *
12327  * lscf_instance_delete() verifies that there is no external dependency pgs
12328  * before suppressing the instance. If there is, then we must not remove them
12329  * now in case the instance is re-created otherwise the dependencies would be
12330  * lost. The external dependency pgs will be removed if the dependencies are
12331  * removed.
12332  *
12333  * Returns:
12334  *  DELETE_FAILURE		on failure
12335  *  DELETE_SUCCESS_NOEXTDEPS	on success - no external dependencies
12336  *  DELETE_SUCCESS_EXTDEPS	on success - external dependencies
12337  */
12338 static int
12339 lscf_instance_delete(scf_instance_t *inst, int force)
12340 {
12341 	scf_propertygroup_t *pg;
12342 	scf_snapshot_t *snap;
12343 	scf_iter_t *iter;
12344 	int err;
12345 	int external = 0;
12346 
12347 	/* If we're not forcing and the instance is running, refuse. */
12348 	if (!force && inst_is_running(inst)) {
12349 		char *fmri;
12350 
12351 		fmri = safe_malloc(max_scf_fmri_len + 1);
12352 
12353 		if (scf_instance_to_fmri(inst, fmri, max_scf_fmri_len + 1) < 0)
12354 			scfdie();
12355 
12356 		semerr(gettext("Instance %s may be running.  "
12357 		    "Use delete -f if it is not.\n"), fmri);
12358 
12359 		free(fmri);
12360 		return (DELETE_FAILURE);
12361 	}
12362 
12363 	pg = scf_pg_create(g_hndl);
12364 	if (pg == NULL)
12365 		scfdie();
12366 
12367 	if (scf_instance_get_pg(inst, SCF_PG_DEPENDENTS, pg) == 0)
12368 		(void) delete_dependents(pg);
12369 	else if (scf_error() != SCF_ERROR_NOT_FOUND)
12370 		scfdie();
12371 
12372 	scf_pg_destroy(pg);
12373 
12374 	/*
12375 	 * If the instance has some external dependencies then we must
12376 	 * keep them in case the instance is reimported otherwise the
12377 	 * dependencies would be lost on reimport.
12378 	 */
12379 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
12380 	    (pg = scf_pg_create(g_hndl)) == NULL)
12381 		scfdie();
12382 
12383 	if (scf_iter_instance_pgs(iter, inst) < 0)
12384 		scfdie();
12385 
12386 	while ((err = scf_iter_next_pg(iter, pg)) == 1) {
12387 		if (pg_is_external_dependency(pg)) {
12388 			external = 1;
12389 			continue;
12390 		}
12391 
12392 		if (scf_pg_delete(pg) != 0) {
12393 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12394 				scfdie();
12395 			else {
12396 				semerr(emsg_permission_denied);
12397 
12398 				(void) scf_iter_destroy(iter);
12399 				(void) scf_pg_destroy(pg);
12400 				return (DELETE_FAILURE);
12401 			}
12402 		}
12403 	}
12404 
12405 	if (err == -1)
12406 		scfdie();
12407 
12408 	(void) scf_iter_destroy(iter);
12409 	(void) scf_pg_destroy(pg);
12410 
12411 	if (external) {
12412 		/*
12413 		 * All the pgs have been deleted for the instance except
12414 		 * the ones holding the external dependencies.
12415 		 * For the job to be complete, we must also delete the
12416 		 * snapshots associated with the instance.
12417 		 */
12418 		if ((snap = scf_snapshot_create((scf_handle_t *)g_hndl)) ==
12419 		    NULL)
12420 			scfdie();
12421 		if ((iter = scf_iter_create((scf_handle_t *)g_hndl)) == NULL)
12422 			scfdie();
12423 
12424 		if (scf_iter_instance_snapshots(iter, inst) == -1)
12425 			scfdie();
12426 
12427 		while ((err = scf_iter_next_snapshot(iter, snap)) == 1) {
12428 			if (_scf_snapshot_delete(snap) != 0) {
12429 				if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12430 					scfdie();
12431 
12432 				semerr(emsg_permission_denied);
12433 
12434 				(void) scf_iter_destroy(iter);
12435 				(void) scf_snapshot_destroy(snap);
12436 				return (DELETE_FAILURE);
12437 			}
12438 		}
12439 
12440 		if (err == -1)
12441 			scfdie();
12442 
12443 		(void) scf_iter_destroy(iter);
12444 		(void) scf_snapshot_destroy(snap);
12445 		return (DELETE_SUCCESS_EXTDEPS);
12446 	}
12447 
12448 	if (scf_instance_delete(inst) != 0) {
12449 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12450 			scfdie();
12451 
12452 		semerr(emsg_permission_denied);
12453 
12454 		return (DELETE_FAILURE);
12455 	}
12456 
12457 	return (DELETE_SUCCESS_NOEXTDEPS);
12458 }
12459 
12460 /*
12461  * lscf_service_delete() deletes a service.  Before calling
12462  * scf_service_delete(), though, we call lscf_instance_delete() for
12463  * each of the instances and delete dependencies in other entities
12464  * which were created as "dependents" of this service.  If there are
12465  * dependencies which were created for other entities, then we delete
12466  * all other property groups in the service and leave it as "empty".
12467  *
12468  * lscf_service_delete() verifies that there is no external dependency
12469  * pgs at the instance & service level before suppressing the service.
12470  * If there is, then we must not remove them now in case the service
12471  * is re-imported otherwise the dependencies would be lost. The external
12472  * dependency pgs will be removed if the dependencies are removed.
12473  *
12474  * Returns:
12475  *   DELETE_FAILURE		on failure
12476  *   DELETE_SUCCESS_NOEXTDEPS	on success - no external dependencies
12477  *   DELETE_SUCCESS_EXTDEPS	on success - external dependencies
12478  */
12479 static int
12480 lscf_service_delete(scf_service_t *svc, int force)
12481 {
12482 	int r;
12483 	scf_instance_t *inst;
12484 	scf_propertygroup_t *pg;
12485 	scf_iter_t *iter;
12486 	int ret;
12487 	int external = 0;
12488 
12489 	if ((inst = scf_instance_create(g_hndl)) == NULL ||
12490 	    (pg = scf_pg_create(g_hndl)) == NULL ||
12491 	    (iter = scf_iter_create(g_hndl)) == NULL)
12492 		scfdie();
12493 
12494 	if (scf_iter_service_instances(iter, svc) != 0)
12495 		scfdie();
12496 
12497 	for (r = scf_iter_next_instance(iter, inst);
12498 	    r == 1;
12499 	    r = scf_iter_next_instance(iter, inst)) {
12500 
12501 		ret = lscf_instance_delete(inst, force);
12502 		if (ret == DELETE_FAILURE) {
12503 			scf_iter_destroy(iter);
12504 			scf_pg_destroy(pg);
12505 			scf_instance_destroy(inst);
12506 			return (DELETE_FAILURE);
12507 		}
12508 
12509 		/*
12510 		 * Record the fact that there is some external dependencies
12511 		 * at the instance level.
12512 		 */
12513 		if (ret == DELETE_SUCCESS_EXTDEPS)
12514 			external |= 1;
12515 	}
12516 
12517 	if (r != 0)
12518 		scfdie();
12519 
12520 	/* Delete dependency property groups in dependent services. */
12521 	if (scf_service_get_pg(svc, SCF_PG_DEPENDENTS, pg) == 0)
12522 		(void) delete_dependents(pg);
12523 	else if (scf_error() != SCF_ERROR_NOT_FOUND)
12524 		scfdie();
12525 
12526 	scf_iter_destroy(iter);
12527 	scf_pg_destroy(pg);
12528 	scf_instance_destroy(inst);
12529 
12530 	/*
12531 	 * If the service has some external dependencies then we don't
12532 	 * want to remove them in case the service is re-imported.
12533 	 */
12534 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
12535 	    (iter = scf_iter_create(g_hndl)) == NULL)
12536 		scfdie();
12537 
12538 	if (scf_iter_service_pgs(iter, svc) < 0)
12539 		scfdie();
12540 
12541 	while ((r = scf_iter_next_pg(iter, pg)) == 1) {
12542 		if (pg_is_external_dependency(pg)) {
12543 			external |= 2;
12544 			continue;
12545 		}
12546 
12547 		if (scf_pg_delete(pg) != 0) {
12548 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12549 				scfdie();
12550 			else {
12551 				semerr(emsg_permission_denied);
12552 
12553 				(void) scf_iter_destroy(iter);
12554 				(void) scf_pg_destroy(pg);
12555 				return (DELETE_FAILURE);
12556 			}
12557 		}
12558 	}
12559 
12560 	if (r == -1)
12561 		scfdie();
12562 
12563 	(void) scf_iter_destroy(iter);
12564 	(void) scf_pg_destroy(pg);
12565 
12566 	if (external != 0)
12567 		return (DELETE_SUCCESS_EXTDEPS);
12568 
12569 	if (scf_service_delete(svc) == 0)
12570 		return (DELETE_SUCCESS_NOEXTDEPS);
12571 
12572 	if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
12573 		scfdie();
12574 
12575 	semerr(emsg_permission_denied);
12576 	return (DELETE_FAILURE);
12577 }
12578 
12579 static int
12580 delete_callback(void *data, scf_walkinfo_t *wip)
12581 {
12582 	int force = (int)data;
12583 
12584 	if (wip->inst != NULL)
12585 		(void) lscf_instance_delete(wip->inst, force);
12586 	else
12587 		(void) lscf_service_delete(wip->svc, force);
12588 
12589 	return (0);
12590 }
12591 
12592 void
12593 lscf_delete(const char *fmri, int force)
12594 {
12595 	scf_service_t *svc;
12596 	scf_instance_t *inst;
12597 	int ret;
12598 
12599 	lscf_prep_hndl();
12600 
12601 	if (cur_snap != NULL) {
12602 		if (!snaplevel_is_instance(cur_level)) {
12603 			char *buf;
12604 
12605 			buf = safe_malloc(max_scf_name_len + 1);
12606 			if (scf_instance_get_name(cur_inst, buf,
12607 			    max_scf_name_len + 1) >= 0) {
12608 				if (strcmp(buf, fmri) == 0) {
12609 					semerr(emsg_cant_modify_snapshots);
12610 					free(buf);
12611 					return;
12612 				}
12613 			} else if (scf_error() != SCF_ERROR_DELETED) {
12614 				scfdie();
12615 			}
12616 			free(buf);
12617 		}
12618 	} else if (cur_inst != NULL) {
12619 		/* EMPTY */;
12620 	} else if (cur_svc != NULL) {
12621 		inst = scf_instance_create(g_hndl);
12622 		if (inst == NULL)
12623 			scfdie();
12624 
12625 		if (scf_service_get_instance(cur_svc, fmri, inst) ==
12626 		    SCF_SUCCESS) {
12627 			(void) lscf_instance_delete(inst, force);
12628 			scf_instance_destroy(inst);
12629 			return;
12630 		}
12631 
12632 		if (scf_error() != SCF_ERROR_NOT_FOUND &&
12633 		    scf_error() != SCF_ERROR_INVALID_ARGUMENT)
12634 			scfdie();
12635 
12636 		scf_instance_destroy(inst);
12637 	} else {
12638 		assert(cur_scope != NULL);
12639 
12640 		svc = scf_service_create(g_hndl);
12641 		if (svc == NULL)
12642 			scfdie();
12643 
12644 		if (scf_scope_get_service(cur_scope, fmri, svc) ==
12645 		    SCF_SUCCESS) {
12646 			(void) lscf_service_delete(svc, force);
12647 			scf_service_destroy(svc);
12648 			return;
12649 		}
12650 
12651 		if (scf_error() != SCF_ERROR_NOT_FOUND &&
12652 		    scf_error() != SCF_ERROR_INVALID_ARGUMENT)
12653 			scfdie();
12654 
12655 		scf_service_destroy(svc);
12656 	}
12657 
12658 	/*
12659 	 * Match FMRI to entity.
12660 	 */
12661 	if ((ret = scf_walk_fmri(g_hndl, 1, (char **)&fmri, SCF_WALK_SERVICE,
12662 	    delete_callback, (void *)force, NULL, semerr)) != 0) {
12663 		semerr(gettext("Failed to walk instances: %s\n"),
12664 		    scf_strerror(ret));
12665 	}
12666 }
12667 
12668 
12669 
12670 /*
12671  * :properties commands.  These all end with "pg" or "prop" and generally
12672  * operate on the currently selected entity.
12673  */
12674 
12675 /*
12676  * Property listing.  List the property groups, properties, their types and
12677  * their values for the currently selected entity.
12678  */
12679 static void
12680 list_pg_info(const scf_propertygroup_t *pg, const char *name, size_t namewidth)
12681 {
12682 	char *buf;
12683 	uint32_t flags;
12684 
12685 	buf = safe_malloc(max_scf_pg_type_len + 1);
12686 
12687 	if (scf_pg_get_type(pg, buf, max_scf_pg_type_len + 1) < 0)
12688 		scfdie();
12689 
12690 	if (scf_pg_get_flags(pg, &flags) != SCF_SUCCESS)
12691 		scfdie();
12692 
12693 	safe_printf("%-*s  %s", namewidth, name, buf);
12694 
12695 	if (flags & SCF_PG_FLAG_NONPERSISTENT)
12696 		safe_printf("\tNONPERSISTENT");
12697 
12698 	safe_printf("\n");
12699 
12700 	free(buf);
12701 }
12702 
12703 static boolean_t
12704 prop_has_multiple_values(const scf_property_t *prop, scf_value_t *val)
12705 {
12706 	if (scf_property_get_value(prop, val) == 0) {
12707 		return (B_FALSE);
12708 	} else {
12709 		switch (scf_error()) {
12710 		case SCF_ERROR_NOT_FOUND:
12711 			return (B_FALSE);
12712 		case SCF_ERROR_PERMISSION_DENIED:
12713 		case SCF_ERROR_CONSTRAINT_VIOLATED:
12714 			return (B_TRUE);
12715 		default:
12716 			scfdie();
12717 			/*NOTREACHED*/
12718 		}
12719 	}
12720 }
12721 
12722 static void
12723 list_prop_info(const scf_property_t *prop, const char *name, size_t len)
12724 {
12725 	scf_iter_t *iter;
12726 	scf_value_t *val;
12727 	const char *type;
12728 	int multiple_strings = 0;
12729 	int ret;
12730 
12731 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
12732 	    (val = scf_value_create(g_hndl)) == NULL)
12733 		scfdie();
12734 
12735 	type = prop_to_typestr(prop);
12736 	assert(type != NULL);
12737 
12738 	safe_printf("%-*s  %-7s ", len, name, type);
12739 
12740 	if (prop_has_multiple_values(prop, val) &&
12741 	    (scf_value_type(val) == SCF_TYPE_ASTRING ||
12742 	    scf_value_type(val) == SCF_TYPE_USTRING))
12743 		multiple_strings = 1;
12744 
12745 	if (scf_iter_property_values(iter, prop) != SCF_SUCCESS)
12746 		scfdie();
12747 
12748 	while ((ret = scf_iter_next_value(iter, val)) == 1) {
12749 		char *buf;
12750 		ssize_t vlen, szret;
12751 
12752 		vlen = scf_value_get_as_string(val, NULL, 0);
12753 		if (vlen < 0)
12754 			scfdie();
12755 
12756 		buf = safe_malloc(vlen + 1);
12757 
12758 		szret = scf_value_get_as_string(val, buf, vlen + 1);
12759 		if (szret < 0)
12760 			scfdie();
12761 		assert(szret <= vlen);
12762 
12763 		/* This is to be human-readable, so don't use CHARS_TO_QUOTE */
12764 		if (multiple_strings || strpbrk(buf, " \t\n\"()") != NULL) {
12765 			safe_printf(" \"");
12766 			(void) quote_and_print(buf, stdout, 0);
12767 			(void) putchar('"');
12768 			if (ferror(stdout)) {
12769 				(void) putchar('\n');
12770 				uu_die(gettext("Error writing to stdout.\n"));
12771 			}
12772 		} else {
12773 			safe_printf(" %s", buf);
12774 		}
12775 
12776 		free(buf);
12777 	}
12778 	if (ret != 0 && scf_error() != SCF_ERROR_PERMISSION_DENIED)
12779 		scfdie();
12780 
12781 	if (putchar('\n') != '\n')
12782 		uu_die(gettext("Could not output newline"));
12783 }
12784 
12785 /*
12786  * Outputs template property group info for the describe subcommand.
12787  * If 'templates' == 2, verbose output is printed in the format expected
12788  * for describe -v, which includes all templates fields.  If pg is
12789  * not NULL, we're describing the template data, not an existing property
12790  * group, and formatting should be appropriate for describe -t.
12791  */
12792 static void
12793 list_pg_tmpl(scf_pg_tmpl_t *pgt, scf_propertygroup_t *pg, int templates)
12794 {
12795 	char *buf;
12796 	uint8_t required;
12797 	scf_property_t *stability_prop;
12798 	scf_value_t *stability_val;
12799 
12800 	if (templates == 0)
12801 		return;
12802 
12803 	if ((stability_prop = scf_property_create(g_hndl)) == NULL ||
12804 	    (stability_val = scf_value_create(g_hndl)) == NULL)
12805 		scfdie();
12806 
12807 	if (templates == 2 && pg != NULL) {
12808 		if (scf_pg_get_property(pg, SCF_PROPERTY_STABILITY,
12809 		    stability_prop) == 0) {
12810 			if (prop_check_type(stability_prop,
12811 			    SCF_TYPE_ASTRING) == 0 &&
12812 			    prop_get_val(stability_prop, stability_val) == 0) {
12813 				char *stability;
12814 
12815 				stability = safe_malloc(max_scf_value_len + 1);
12816 
12817 				if (scf_value_get_astring(stability_val,
12818 				    stability, max_scf_value_len + 1) == -1 &&
12819 				    scf_error() != SCF_ERROR_NOT_FOUND)
12820 					scfdie();
12821 
12822 				safe_printf("%s%s: %s\n", TMPL_INDENT,
12823 				    gettext("stability"), stability);
12824 
12825 				free(stability);
12826 			}
12827 		} else if (scf_error() != SCF_ERROR_NOT_FOUND)
12828 			scfdie();
12829 	}
12830 
12831 	scf_property_destroy(stability_prop);
12832 	scf_value_destroy(stability_val);
12833 
12834 	if (pgt == NULL)
12835 		return;
12836 
12837 	if (pg == NULL || templates == 2) {
12838 		/* print type info only if scf_tmpl_pg_name succeeds */
12839 		if (scf_tmpl_pg_name(pgt, &buf) != -1) {
12840 			if (pg != NULL)
12841 				safe_printf("%s", TMPL_INDENT);
12842 			safe_printf("%s: ", gettext("name"));
12843 			safe_printf("%s\n", buf);
12844 			free(buf);
12845 		}
12846 
12847 		/* print type info only if scf_tmpl_pg_type succeeds */
12848 		if (scf_tmpl_pg_type(pgt, &buf) != -1) {
12849 			if (pg != NULL)
12850 				safe_printf("%s", TMPL_INDENT);
12851 			safe_printf("%s: ", gettext("type"));
12852 			safe_printf("%s\n", buf);
12853 			free(buf);
12854 		}
12855 	}
12856 
12857 	if (templates == 2 && scf_tmpl_pg_required(pgt, &required) == 0)
12858 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("required"),
12859 		    required ? "true" : "false");
12860 
12861 	if (templates == 2 && scf_tmpl_pg_target(pgt, &buf) > 0) {
12862 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("target"),
12863 		    buf);
12864 		free(buf);
12865 	}
12866 
12867 	if (templates == 2 && scf_tmpl_pg_common_name(pgt, NULL, &buf) > 0) {
12868 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("common name"),
12869 		    buf);
12870 		free(buf);
12871 	}
12872 
12873 	if (scf_tmpl_pg_description(pgt, NULL, &buf) > 0) {
12874 		if (templates == 2)
12875 			safe_printf("%s%s: %s\n", TMPL_INDENT,
12876 			    gettext("description"), buf);
12877 		else
12878 			safe_printf("%s%s\n", TMPL_INDENT, buf);
12879 		free(buf);
12880 	}
12881 
12882 }
12883 
12884 /*
12885  * With as_value set to true, indent as appropriate for the value level.
12886  * If false, indent to appropriate level for inclusion in constraint
12887  * or choice printout.
12888  */
12889 static void
12890 print_template_value_details(scf_prop_tmpl_t *prt, const char *val_buf,
12891     int as_value)
12892 {
12893 	char *buf;
12894 
12895 	if (scf_tmpl_value_common_name(prt, NULL, val_buf, &buf) > 0) {
12896 		if (as_value == 0)
12897 			safe_printf("%s", TMPL_CHOICE_INDENT);
12898 		else
12899 			safe_printf("%s", TMPL_INDENT);
12900 		safe_printf("%s: %s\n", gettext("value common name"), buf);
12901 		free(buf);
12902 	}
12903 
12904 	if (scf_tmpl_value_description(prt, NULL, val_buf, &buf) > 0) {
12905 		if (as_value == 0)
12906 			safe_printf("%s", TMPL_CHOICE_INDENT);
12907 		else
12908 			safe_printf("%s", TMPL_INDENT);
12909 		safe_printf("%s: %s\n", gettext("value description"), buf);
12910 		free(buf);
12911 	}
12912 }
12913 
12914 static void
12915 print_template_value(scf_prop_tmpl_t *prt, const char *val_buf)
12916 {
12917 	safe_printf("%s%s: ", TMPL_VALUE_INDENT, gettext("value"));
12918 	/* This is to be human-readable, so don't use CHARS_TO_QUOTE */
12919 	safe_printf("%s\n", val_buf);
12920 
12921 	print_template_value_details(prt, val_buf, 1);
12922 }
12923 
12924 static void
12925 print_template_constraints(scf_prop_tmpl_t *prt, int verbose)
12926 {
12927 	int i, printed = 0;
12928 	scf_values_t values;
12929 	scf_count_ranges_t c_ranges;
12930 	scf_int_ranges_t i_ranges;
12931 
12932 	printed = 0;
12933 	i = 0;
12934 	if (scf_tmpl_value_name_constraints(prt, &values) == 0) {
12935 		safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12936 		    gettext("value constraints"));
12937 		printed++;
12938 		for (i = 0; i < values.value_count; ++i) {
12939 			safe_printf("%s%s: %s\n", TMPL_INDENT,
12940 			    gettext("value name"), values.values_as_strings[i]);
12941 			if (verbose == 1)
12942 				print_template_value_details(prt,
12943 				    values.values_as_strings[i], 0);
12944 		}
12945 
12946 		scf_values_destroy(&values);
12947 	}
12948 
12949 	if (scf_tmpl_value_count_range_constraints(prt, &c_ranges) == 0) {
12950 		if (printed++ == 0)
12951 			safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12952 			    gettext("value constraints"));
12953 		for (i = 0; i < c_ranges.scr_num_ranges; ++i) {
12954 			safe_printf("%s%s: %llu to %llu\n", TMPL_INDENT,
12955 			    gettext("range"), c_ranges.scr_min[i],
12956 			    c_ranges.scr_max[i]);
12957 		}
12958 		scf_count_ranges_destroy(&c_ranges);
12959 	} else if (scf_error() == SCF_ERROR_CONSTRAINT_VIOLATED &&
12960 	    scf_tmpl_value_int_range_constraints(prt, &i_ranges) == 0) {
12961 		if (printed++ == 0)
12962 			safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12963 			    gettext("value constraints"));
12964 		for (i = 0; i < i_ranges.sir_num_ranges; ++i) {
12965 			safe_printf("%s%s: %lld to %lld\n", TMPL_INDENT,
12966 			    gettext("range"), i_ranges.sir_min[i],
12967 			    i_ranges.sir_max[i]);
12968 		}
12969 		scf_int_ranges_destroy(&i_ranges);
12970 	}
12971 }
12972 
12973 static void
12974 print_template_choices(scf_prop_tmpl_t *prt, int verbose)
12975 {
12976 	int i = 0, printed = 0;
12977 	scf_values_t values;
12978 	scf_count_ranges_t c_ranges;
12979 	scf_int_ranges_t i_ranges;
12980 
12981 	printed = 0;
12982 	if (scf_tmpl_value_name_choices(prt, &values) == 0) {
12983 		safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
12984 		    gettext("value constraints"));
12985 		printed++;
12986 		for (i = 0; i < values.value_count; i++) {
12987 			safe_printf("%s%s: %s\n", TMPL_INDENT,
12988 			    gettext("value name"), values.values_as_strings[i]);
12989 			if (verbose == 1)
12990 				print_template_value_details(prt,
12991 				    values.values_as_strings[i], 0);
12992 		}
12993 
12994 		scf_values_destroy(&values);
12995 	}
12996 
12997 	if (scf_tmpl_value_count_range_choices(prt, &c_ranges) == 0) {
12998 		for (i = 0; i < c_ranges.scr_num_ranges; ++i) {
12999 			if (printed++ == 0)
13000 				safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
13001 				    gettext("value choices"));
13002 			safe_printf("%s%s: %llu to %llu\n", TMPL_INDENT,
13003 			    gettext("range"), c_ranges.scr_min[i],
13004 			    c_ranges.scr_max[i]);
13005 		}
13006 		scf_count_ranges_destroy(&c_ranges);
13007 	} else if (scf_error() == SCF_ERROR_CONSTRAINT_VIOLATED &&
13008 	    scf_tmpl_value_int_range_choices(prt, &i_ranges) == 0) {
13009 		for (i = 0; i < i_ranges.sir_num_ranges; ++i) {
13010 			if (printed++ == 0)
13011 				safe_printf("%s%s:\n", TMPL_VALUE_INDENT,
13012 				    gettext("value choices"));
13013 			safe_printf("%s%s: %lld to %lld\n", TMPL_INDENT,
13014 			    gettext("range"), i_ranges.sir_min[i],
13015 			    i_ranges.sir_max[i]);
13016 		}
13017 		scf_int_ranges_destroy(&i_ranges);
13018 	}
13019 }
13020 
13021 static void
13022 list_values_by_template(scf_prop_tmpl_t *prt)
13023 {
13024 	print_template_constraints(prt, 1);
13025 	print_template_choices(prt, 1);
13026 }
13027 
13028 static void
13029 list_values_tmpl(scf_prop_tmpl_t *prt, scf_property_t *prop)
13030 {
13031 	char *val_buf;
13032 	scf_iter_t *iter;
13033 	scf_value_t *val;
13034 	int ret;
13035 
13036 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
13037 	    (val = scf_value_create(g_hndl)) == NULL)
13038 		scfdie();
13039 
13040 	if (scf_iter_property_values(iter, prop) != SCF_SUCCESS)
13041 		scfdie();
13042 
13043 	val_buf = safe_malloc(max_scf_value_len + 1);
13044 
13045 	while ((ret = scf_iter_next_value(iter, val)) == 1) {
13046 		if (scf_value_get_as_string(val, val_buf,
13047 		    max_scf_value_len + 1) < 0)
13048 			scfdie();
13049 
13050 		print_template_value(prt, val_buf);
13051 	}
13052 	if (ret != 0 && scf_error() != SCF_ERROR_PERMISSION_DENIED)
13053 		scfdie();
13054 	free(val_buf);
13055 
13056 	print_template_constraints(prt, 0);
13057 	print_template_choices(prt, 0);
13058 
13059 }
13060 
13061 /*
13062  * Outputs property info for the describe subcommand
13063  * Verbose output if templates == 2, -v option of svccfg describe
13064  * Displays template data if prop is not NULL, -t option of svccfg describe
13065  */
13066 static void
13067 list_prop_tmpl(scf_prop_tmpl_t *prt, scf_property_t *prop, int templates)
13068 {
13069 	char *buf;
13070 	uint8_t u_buf;
13071 	int i;
13072 	uint64_t min, max;
13073 	scf_values_t values;
13074 
13075 	if (prt == NULL || templates == 0)
13076 		return;
13077 
13078 	if (prop == NULL) {
13079 		safe_printf("%s%s: ", TMPL_VALUE_INDENT, gettext("name"));
13080 		if (scf_tmpl_prop_name(prt, &buf) > 0) {
13081 			safe_printf("%s\n", buf);
13082 			free(buf);
13083 		} else
13084 			safe_printf("(%s)\n", gettext("any"));
13085 	}
13086 
13087 	if (prop == NULL || templates == 2) {
13088 		if (prop != NULL)
13089 			safe_printf("%s", TMPL_INDENT);
13090 		else
13091 			safe_printf("%s", TMPL_VALUE_INDENT);
13092 		safe_printf("%s: ", gettext("type"));
13093 		if ((buf = _scf_read_tmpl_prop_type_as_string(prt)) != NULL) {
13094 			safe_printf("%s\n", buf);
13095 			free(buf);
13096 		} else
13097 			safe_printf("(%s)\n", gettext("any"));
13098 	}
13099 
13100 	if (templates == 2 && scf_tmpl_prop_required(prt, &u_buf) == 0)
13101 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("required"),
13102 		    u_buf ? "true" : "false");
13103 
13104 	if (templates == 2 && scf_tmpl_prop_common_name(prt, NULL, &buf) > 0) {
13105 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("common name"),
13106 		    buf);
13107 		free(buf);
13108 	}
13109 
13110 	if (templates == 2 && scf_tmpl_prop_units(prt, NULL, &buf) > 0) {
13111 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("units"),
13112 		    buf);
13113 		free(buf);
13114 	}
13115 
13116 	if (scf_tmpl_prop_description(prt, NULL, &buf) > 0) {
13117 		safe_printf("%s%s\n", TMPL_INDENT, buf);
13118 		free(buf);
13119 	}
13120 
13121 	if (templates == 2 && scf_tmpl_prop_visibility(prt, &u_buf) == 0)
13122 		safe_printf("%s%s: %s\n", TMPL_INDENT, gettext("visibility"),
13123 		    scf_tmpl_visibility_to_string(u_buf));
13124 
13125 	if (templates == 2 && scf_tmpl_prop_cardinality(prt, &min, &max) == 0) {
13126 		safe_printf("%s%s: %" PRIu64 "\n", TMPL_INDENT,
13127 		    gettext("minimum number of values"), min);
13128 		if (max == ULLONG_MAX) {
13129 			safe_printf("%s%s: %s\n", TMPL_INDENT,
13130 			    gettext("maximum number of values"),
13131 			    gettext("unlimited"));
13132 		} else {
13133 			safe_printf("%s%s: %" PRIu64 "\n", TMPL_INDENT,
13134 			    gettext("maximum number of values"), max);
13135 		}
13136 	}
13137 
13138 	if (templates == 2 && scf_tmpl_prop_internal_seps(prt, &values) == 0) {
13139 		for (i = 0; i < values.value_count; i++) {
13140 			if (i == 0) {
13141 				safe_printf("%s%s:", TMPL_INDENT,
13142 				    gettext("internal separators"));
13143 			}
13144 			safe_printf(" \"%s\"", values.values_as_strings[i]);
13145 		}
13146 		safe_printf("\n");
13147 	}
13148 
13149 	if (templates != 2)
13150 		return;
13151 
13152 	if (prop != NULL)
13153 		list_values_tmpl(prt, prop);
13154 	else
13155 		list_values_by_template(prt);
13156 }
13157 
13158 static char *
13159 read_astring(scf_propertygroup_t *pg, const char *prop_name)
13160 {
13161 	char *rv;
13162 
13163 	rv = _scf_read_single_astring_from_pg(pg, prop_name);
13164 	if (rv == NULL) {
13165 		switch (scf_error()) {
13166 		case SCF_ERROR_NOT_FOUND:
13167 			break;
13168 		default:
13169 			scfdie();
13170 		}
13171 	}
13172 	return (rv);
13173 }
13174 
13175 static void
13176 display_documentation(scf_iter_t *iter, scf_propertygroup_t *pg)
13177 {
13178 	size_t doc_len;
13179 	size_t man_len;
13180 	char *pg_name;
13181 	char *text = NULL;
13182 	int rv;
13183 
13184 	doc_len = strlen(SCF_PG_TM_DOC_PREFIX);
13185 	man_len = strlen(SCF_PG_TM_MAN_PREFIX);
13186 	pg_name = safe_malloc(max_scf_name_len + 1);
13187 	while ((rv = scf_iter_next_pg(iter, pg)) == 1) {
13188 		if (scf_pg_get_name(pg, pg_name, max_scf_name_len + 1) == -1) {
13189 			scfdie();
13190 		}
13191 		if (strncmp(pg_name, SCF_PG_TM_DOC_PREFIX, doc_len) == 0) {
13192 			/* Display doc_link and and uri */
13193 			safe_printf("%s%s:\n", TMPL_INDENT,
13194 			    gettext("doc_link"));
13195 			text = read_astring(pg, SCF_PROPERTY_TM_NAME);
13196 			if (text != NULL) {
13197 				safe_printf("%s%s%s: %s\n", TMPL_INDENT,
13198 				    TMPL_INDENT, gettext("name"), text);
13199 				uu_free(text);
13200 			}
13201 			text = read_astring(pg, SCF_PROPERTY_TM_URI);
13202 			if (text != NULL) {
13203 				safe_printf("%s%s: %s\n", TMPL_INDENT_2X,
13204 				    gettext("uri"), text);
13205 				uu_free(text);
13206 			}
13207 		} else if (strncmp(pg_name, SCF_PG_TM_MAN_PREFIX,
13208 		    man_len) == 0) {
13209 			/* Display manpage title, section and path */
13210 			safe_printf("%s%s:\n", TMPL_INDENT,
13211 			    gettext("manpage"));
13212 			text = read_astring(pg, SCF_PROPERTY_TM_TITLE);
13213 			if (text != NULL) {
13214 				safe_printf("%s%s%s: %s\n", TMPL_INDENT,
13215 				    TMPL_INDENT, gettext("title"), text);
13216 				uu_free(text);
13217 			}
13218 			text = read_astring(pg, SCF_PROPERTY_TM_SECTION);
13219 			if (text != NULL) {
13220 				safe_printf("%s%s%s: %s\n", TMPL_INDENT,
13221 				    TMPL_INDENT, gettext("section"), text);
13222 				uu_free(text);
13223 			}
13224 			text = read_astring(pg, SCF_PROPERTY_TM_MANPATH);
13225 			if (text != NULL) {
13226 				safe_printf("%s%s%s: %s\n", TMPL_INDENT,
13227 				    TMPL_INDENT, gettext("manpath"), text);
13228 				uu_free(text);
13229 			}
13230 		}
13231 	}
13232 	if (rv == -1)
13233 		scfdie();
13234 
13235 done:
13236 	free(pg_name);
13237 }
13238 
13239 static void
13240 list_entity_tmpl(int templates)
13241 {
13242 	char *common_name = NULL;
13243 	char *description = NULL;
13244 	char *locale = NULL;
13245 	scf_iter_t *iter;
13246 	scf_propertygroup_t *pg;
13247 	scf_property_t *prop;
13248 	int r;
13249 	scf_value_t *val;
13250 
13251 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
13252 	    (prop = scf_property_create(g_hndl)) == NULL ||
13253 	    (val = scf_value_create(g_hndl)) == NULL ||
13254 	    (iter = scf_iter_create(g_hndl)) == NULL)
13255 		scfdie();
13256 
13257 	locale = setlocale(LC_MESSAGES, NULL);
13258 
13259 	if (get_pg(SCF_PG_TM_COMMON_NAME, pg) == 0) {
13260 		common_name = safe_malloc(max_scf_value_len + 1);
13261 
13262 		/* Try both the current locale and the "C" locale. */
13263 		if (scf_pg_get_property(pg, locale, prop) == 0 ||
13264 		    (scf_error() == SCF_ERROR_NOT_FOUND &&
13265 		    scf_pg_get_property(pg, "C", prop) == 0)) {
13266 			if (prop_get_val(prop, val) == 0 &&
13267 			    scf_value_get_ustring(val, common_name,
13268 			    max_scf_value_len + 1) != -1) {
13269 				safe_printf("%s%s: %s\n", TMPL_INDENT,
13270 				    gettext("common name"), common_name);
13271 			}
13272 		}
13273 	}
13274 
13275 	/*
13276 	 * Do description, manpages, and doc links if templates == 2.
13277 	 */
13278 	if (templates == 2) {
13279 		/* Get the description. */
13280 		if (get_pg(SCF_PG_TM_DESCRIPTION, pg) == 0) {
13281 			description = safe_malloc(max_scf_value_len + 1);
13282 
13283 			/* Try both the current locale and the "C" locale. */
13284 			if (scf_pg_get_property(pg, locale, prop) == 0 ||
13285 			    (scf_error() == SCF_ERROR_NOT_FOUND &&
13286 			    scf_pg_get_property(pg, "C", prop) == 0)) {
13287 				if (prop_get_val(prop, val) == 0 &&
13288 				    scf_value_get_ustring(val, description,
13289 				    max_scf_value_len + 1) != -1) {
13290 					safe_printf("%s%s: %s\n", TMPL_INDENT,
13291 					    gettext("description"),
13292 					    description);
13293 				}
13294 			}
13295 		}
13296 
13297 		/* Process doc_link & manpage elements. */
13298 		if (cur_level != NULL) {
13299 			r = scf_iter_snaplevel_pgs_typed(iter, cur_level,
13300 			    SCF_GROUP_TEMPLATE);
13301 		} else if (cur_inst != NULL) {
13302 			r = scf_iter_instance_pgs_typed(iter, cur_inst,
13303 			    SCF_GROUP_TEMPLATE);
13304 		} else {
13305 			r = scf_iter_service_pgs_typed(iter, cur_svc,
13306 			    SCF_GROUP_TEMPLATE);
13307 		}
13308 		if (r == 0) {
13309 			display_documentation(iter, pg);
13310 		}
13311 	}
13312 
13313 	free(common_name);
13314 	free(description);
13315 	scf_pg_destroy(pg);
13316 	scf_property_destroy(prop);
13317 	scf_value_destroy(val);
13318 	scf_iter_destroy(iter);
13319 }
13320 
13321 static void
13322 listtmpl(const char *pattern, int templates)
13323 {
13324 	scf_pg_tmpl_t *pgt;
13325 	scf_prop_tmpl_t *prt;
13326 	char *snapbuf = NULL;
13327 	char *fmribuf;
13328 	char *pg_name = NULL, *prop_name = NULL;
13329 	ssize_t prop_name_size;
13330 	char *qual_prop_name;
13331 	char *search_name;
13332 	int listed = 0;
13333 
13334 	if ((pgt = scf_tmpl_pg_create(g_hndl)) == NULL ||
13335 	    (prt = scf_tmpl_prop_create(g_hndl)) == NULL)
13336 		scfdie();
13337 
13338 	fmribuf = safe_malloc(max_scf_name_len + 1);
13339 	qual_prop_name = safe_malloc(max_scf_name_len + 1);
13340 
13341 	if (cur_snap != NULL) {
13342 		snapbuf = safe_malloc(max_scf_name_len + 1);
13343 		if (scf_snapshot_get_name(cur_snap, snapbuf,
13344 		    max_scf_name_len + 1) < 0)
13345 			scfdie();
13346 	}
13347 
13348 	if (cur_inst != NULL) {
13349 		if (scf_instance_to_fmri(cur_inst, fmribuf,
13350 		    max_scf_name_len + 1) < 0)
13351 			scfdie();
13352 	} else if (cur_svc != NULL) {
13353 		if (scf_service_to_fmri(cur_svc, fmribuf,
13354 		    max_scf_name_len + 1) < 0)
13355 			scfdie();
13356 	} else
13357 		abort();
13358 
13359 	/* If pattern is specified, we want to list only those items. */
13360 	while (scf_tmpl_iter_pgs(pgt, fmribuf, snapbuf, NULL, 0) == 1) {
13361 		listed = 0;
13362 		if (pattern == NULL || (scf_tmpl_pg_name(pgt, &pg_name) > 0 &&
13363 		    fnmatch(pattern, pg_name, 0) == 0)) {
13364 			list_pg_tmpl(pgt, NULL, templates);
13365 			listed++;
13366 		}
13367 
13368 		scf_tmpl_prop_reset(prt);
13369 
13370 		while (scf_tmpl_iter_props(pgt, prt, 0) == 0) {
13371 			search_name = NULL;
13372 			prop_name_size = scf_tmpl_prop_name(prt, &prop_name);
13373 			if ((prop_name_size > 0) && (pg_name != NULL)) {
13374 				if (snprintf(qual_prop_name,
13375 				    max_scf_name_len + 1, "%s/%s",
13376 				    pg_name, prop_name) >=
13377 				    max_scf_name_len + 1) {
13378 					prop_name_size = -1;
13379 				} else {
13380 					search_name = qual_prop_name;
13381 				}
13382 			}
13383 			if (listed > 0 || pattern == NULL ||
13384 			    (prop_name_size > 0 &&
13385 			    fnmatch(pattern, search_name,
13386 			    FNM_PATHNAME) == 0))
13387 				list_prop_tmpl(prt, NULL, templates);
13388 			if (prop_name != NULL) {
13389 				free(prop_name);
13390 				prop_name = NULL;
13391 			}
13392 		}
13393 		if (pg_name != NULL) {
13394 			free(pg_name);
13395 			pg_name = NULL;
13396 		}
13397 	}
13398 
13399 	scf_tmpl_prop_destroy(prt);
13400 	scf_tmpl_pg_destroy(pgt);
13401 	free(snapbuf);
13402 	free(fmribuf);
13403 	free(qual_prop_name);
13404 }
13405 
13406 static void
13407 listprop(const char *pattern, int only_pgs, int templates)
13408 {
13409 	scf_propertygroup_t *pg;
13410 	scf_property_t *prop;
13411 	scf_iter_t *iter, *piter;
13412 	char *pgnbuf, *prnbuf, *ppnbuf;
13413 	scf_pg_tmpl_t *pgt, *pgtp;
13414 	scf_prop_tmpl_t *prt;
13415 
13416 	void **objects;
13417 	char **names;
13418 	void **tmpls;
13419 	int allocd, i;
13420 
13421 	int ret;
13422 	ssize_t pgnlen, prnlen, szret;
13423 	size_t max_len = 0;
13424 
13425 	if (cur_svc == NULL && cur_inst == NULL) {
13426 		semerr(emsg_entity_not_selected);
13427 		return;
13428 	}
13429 
13430 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
13431 	    (prop = scf_property_create(g_hndl)) == NULL ||
13432 	    (iter = scf_iter_create(g_hndl)) == NULL ||
13433 	    (piter = scf_iter_create(g_hndl)) == NULL ||
13434 	    (prt = scf_tmpl_prop_create(g_hndl)) == NULL ||
13435 	    (pgt = scf_tmpl_pg_create(g_hndl)) == NULL)
13436 		scfdie();
13437 
13438 	prnbuf = safe_malloc(max_scf_name_len + 1);
13439 
13440 	if (cur_level != NULL)
13441 		ret = scf_iter_snaplevel_pgs(iter, cur_level);
13442 	else if (cur_inst != NULL)
13443 		ret = scf_iter_instance_pgs(iter, cur_inst);
13444 	else
13445 		ret = scf_iter_service_pgs(iter, cur_svc);
13446 	if (ret != 0) {
13447 		return;
13448 	}
13449 
13450 	/*
13451 	 * We want to only list items which match pattern, and we want the
13452 	 * second column to line up, so during the first pass we'll save
13453 	 * matching items, their names, and their templates in objects,
13454 	 * names, and tmpls, computing the maximum name length as we go,
13455 	 * and then we'll print them out.
13456 	 *
13457 	 * Note: We always keep an extra slot available so the array can be
13458 	 * NULL-terminated.
13459 	 */
13460 	i = 0;
13461 	allocd = 1;
13462 	objects = safe_malloc(sizeof (*objects));
13463 	names = safe_malloc(sizeof (*names));
13464 	tmpls = safe_malloc(sizeof (*tmpls));
13465 
13466 	while ((ret = scf_iter_next_pg(iter, pg)) == 1) {
13467 		int new_pg = 0;
13468 		int print_props = 0;
13469 		pgtp = NULL;
13470 
13471 		pgnlen = scf_pg_get_name(pg, NULL, 0);
13472 		if (pgnlen < 0)
13473 			scfdie();
13474 
13475 		pgnbuf = safe_malloc(pgnlen + 1);
13476 
13477 		szret = scf_pg_get_name(pg, pgnbuf, pgnlen + 1);
13478 		if (szret < 0)
13479 			scfdie();
13480 		assert(szret <= pgnlen);
13481 
13482 		if (scf_tmpl_get_by_pg(pg, pgt, 0) == -1) {
13483 			if (scf_error() != SCF_ERROR_NOT_FOUND)
13484 				scfdie();
13485 			pgtp = NULL;
13486 		} else {
13487 			pgtp = pgt;
13488 		}
13489 
13490 		if (pattern == NULL ||
13491 		    fnmatch(pattern, pgnbuf, 0) == 0) {
13492 			if (i+1 >= allocd) {
13493 				allocd *= 2;
13494 				objects = realloc(objects,
13495 				    sizeof (*objects) * allocd);
13496 				names =
13497 				    realloc(names, sizeof (*names) * allocd);
13498 				tmpls = realloc(tmpls,
13499 				    sizeof (*tmpls) * allocd);
13500 				if (objects == NULL || names == NULL ||
13501 				    tmpls == NULL)
13502 					uu_die(gettext("Out of memory"));
13503 			}
13504 			objects[i] = pg;
13505 			names[i] = pgnbuf;
13506 
13507 			if (pgtp == NULL)
13508 				tmpls[i] = NULL;
13509 			else
13510 				tmpls[i] = pgt;
13511 
13512 			++i;
13513 
13514 			if (pgnlen > max_len)
13515 				max_len = pgnlen;
13516 
13517 			new_pg = 1;
13518 			print_props = 1;
13519 		}
13520 
13521 		if (only_pgs) {
13522 			if (new_pg) {
13523 				pg = scf_pg_create(g_hndl);
13524 				if (pg == NULL)
13525 					scfdie();
13526 				pgt = scf_tmpl_pg_create(g_hndl);
13527 				if (pgt == NULL)
13528 					scfdie();
13529 			} else
13530 				free(pgnbuf);
13531 
13532 			continue;
13533 		}
13534 
13535 		if (scf_iter_pg_properties(piter, pg) != SCF_SUCCESS)
13536 			scfdie();
13537 
13538 		while ((ret = scf_iter_next_property(piter, prop)) == 1) {
13539 			prnlen = scf_property_get_name(prop, prnbuf,
13540 			    max_scf_name_len + 1);
13541 			if (prnlen < 0)
13542 				scfdie();
13543 
13544 			/* Will prepend the property group name and a slash. */
13545 			prnlen += pgnlen + 1;
13546 
13547 			ppnbuf = safe_malloc(prnlen + 1);
13548 
13549 			if (snprintf(ppnbuf, prnlen + 1, "%s/%s", pgnbuf,
13550 			    prnbuf) < 0)
13551 				uu_die("snprintf");
13552 
13553 			if (pattern == NULL || print_props == 1 ||
13554 			    fnmatch(pattern, ppnbuf, 0) == 0) {
13555 				if (i+1 >= allocd) {
13556 					allocd *= 2;
13557 					objects = realloc(objects,
13558 					    sizeof (*objects) * allocd);
13559 					names = realloc(names,
13560 					    sizeof (*names) * allocd);
13561 					tmpls = realloc(tmpls,
13562 					    sizeof (*tmpls) * allocd);
13563 					if (objects == NULL || names == NULL ||
13564 					    tmpls == NULL)
13565 						uu_die(gettext(
13566 						    "Out of memory"));
13567 				}
13568 
13569 				objects[i] = prop;
13570 				names[i] = ppnbuf;
13571 
13572 				if (pgtp != NULL) {
13573 					if (scf_tmpl_get_by_prop(pgt, prnbuf,
13574 					    prt, 0) < 0) {
13575 						if (scf_error() !=
13576 						    SCF_ERROR_NOT_FOUND)
13577 							scfdie();
13578 						tmpls[i] = NULL;
13579 					} else {
13580 						tmpls[i] = prt;
13581 					}
13582 				} else {
13583 					tmpls[i] = NULL;
13584 				}
13585 
13586 				++i;
13587 
13588 				if (prnlen > max_len)
13589 					max_len = prnlen;
13590 
13591 				prop = scf_property_create(g_hndl);
13592 				prt = scf_tmpl_prop_create(g_hndl);
13593 			} else {
13594 				free(ppnbuf);
13595 			}
13596 		}
13597 
13598 		if (new_pg) {
13599 			pg = scf_pg_create(g_hndl);
13600 			if (pg == NULL)
13601 				scfdie();
13602 			pgt = scf_tmpl_pg_create(g_hndl);
13603 			if (pgt == NULL)
13604 				scfdie();
13605 		} else
13606 			free(pgnbuf);
13607 	}
13608 	if (ret != 0)
13609 		scfdie();
13610 
13611 	objects[i] = NULL;
13612 
13613 	scf_pg_destroy(pg);
13614 	scf_tmpl_pg_destroy(pgt);
13615 	scf_property_destroy(prop);
13616 	scf_tmpl_prop_destroy(prt);
13617 
13618 	for (i = 0; objects[i] != NULL; ++i) {
13619 		if (strchr(names[i], '/') == NULL) {
13620 			/* property group */
13621 			pg = (scf_propertygroup_t *)objects[i];
13622 			pgt = (scf_pg_tmpl_t *)tmpls[i];
13623 			list_pg_info(pg, names[i], max_len);
13624 			list_pg_tmpl(pgt, pg, templates);
13625 			free(names[i]);
13626 			scf_pg_destroy(pg);
13627 			if (pgt != NULL)
13628 				scf_tmpl_pg_destroy(pgt);
13629 		} else {
13630 			/* property */
13631 			prop = (scf_property_t *)objects[i];
13632 			prt = (scf_prop_tmpl_t *)tmpls[i];
13633 			list_prop_info(prop, names[i], max_len);
13634 			list_prop_tmpl(prt, prop, templates);
13635 			free(names[i]);
13636 			scf_property_destroy(prop);
13637 			if (prt != NULL)
13638 				scf_tmpl_prop_destroy(prt);
13639 		}
13640 	}
13641 
13642 	free(names);
13643 	free(objects);
13644 	free(tmpls);
13645 }
13646 
13647 void
13648 lscf_listpg(const char *pattern)
13649 {
13650 	lscf_prep_hndl();
13651 
13652 	listprop(pattern, 1, 0);
13653 }
13654 
13655 /*
13656  * Property group and property creation, setting, and deletion.  setprop (and
13657  * its alias, addprop) can either create a property group of a given type, or
13658  * it can create or set a property to a given type and list of values.
13659  */
13660 void
13661 lscf_addpg(const char *name, const char *type, const char *flags)
13662 {
13663 	scf_propertygroup_t *pg;
13664 	int ret;
13665 	uint32_t flgs = 0;
13666 	const char *cp;
13667 
13668 
13669 	lscf_prep_hndl();
13670 
13671 	if (cur_snap != NULL) {
13672 		semerr(emsg_cant_modify_snapshots);
13673 		return;
13674 	}
13675 
13676 	if (cur_inst == NULL && cur_svc == NULL) {
13677 		semerr(emsg_entity_not_selected);
13678 		return;
13679 	}
13680 
13681 	if (flags != NULL) {
13682 		for (cp = flags; *cp != '\0'; ++cp) {
13683 			switch (*cp) {
13684 			case 'P':
13685 				flgs |= SCF_PG_FLAG_NONPERSISTENT;
13686 				break;
13687 
13688 			case 'p':
13689 				flgs &= ~SCF_PG_FLAG_NONPERSISTENT;
13690 				break;
13691 
13692 			default:
13693 				semerr(gettext("Invalid property group flag "
13694 				    "%c."), *cp);
13695 				return;
13696 			}
13697 		}
13698 	}
13699 
13700 	pg = scf_pg_create(g_hndl);
13701 	if (pg == NULL)
13702 		scfdie();
13703 
13704 	if (cur_inst != NULL)
13705 		ret = scf_instance_add_pg(cur_inst, name, type, flgs, pg);
13706 	else
13707 		ret = scf_service_add_pg(cur_svc, name, type, flgs, pg);
13708 
13709 	if (ret != SCF_SUCCESS) {
13710 		switch (scf_error()) {
13711 		case SCF_ERROR_INVALID_ARGUMENT:
13712 			semerr(gettext("Name, type, or flags are invalid.\n"));
13713 			break;
13714 
13715 		case SCF_ERROR_EXISTS:
13716 			semerr(gettext("Property group already exists.\n"));
13717 			break;
13718 
13719 		case SCF_ERROR_PERMISSION_DENIED:
13720 			semerr(emsg_permission_denied);
13721 			break;
13722 
13723 		case SCF_ERROR_BACKEND_ACCESS:
13724 			semerr(gettext("Backend refused access.\n"));
13725 			break;
13726 
13727 		default:
13728 			scfdie();
13729 		}
13730 	}
13731 
13732 	scf_pg_destroy(pg);
13733 
13734 	private_refresh();
13735 }
13736 
13737 void
13738 lscf_delpg(char *name)
13739 {
13740 	lscf_prep_hndl();
13741 
13742 	if (cur_snap != NULL) {
13743 		semerr(emsg_cant_modify_snapshots);
13744 		return;
13745 	}
13746 
13747 	if (cur_inst == NULL && cur_svc == NULL) {
13748 		semerr(emsg_entity_not_selected);
13749 		return;
13750 	}
13751 
13752 	if (strchr(name, '/') != NULL) {
13753 		semerr(emsg_invalid_pg_name, name);
13754 		return;
13755 	}
13756 
13757 	lscf_delprop(name);
13758 }
13759 
13760 /*
13761  * scf_delhash() is used to remove the property group related to the
13762  * hash entry for a specific manifest in the repository. pgname will be
13763  * constructed from the location of the manifest file. If deathrow isn't 0,
13764  * manifest file doesn't need to exist (manifest string will be used as
13765  * an absolute path).
13766  */
13767 void
13768 lscf_delhash(char *manifest, int deathrow)
13769 {
13770 	char *pgname;
13771 
13772 	if (cur_snap != NULL ||
13773 	    cur_inst != NULL || cur_svc != NULL) {
13774 		warn(gettext("error, an entity is selected\n"));
13775 		return;
13776 	}
13777 
13778 	/* select smf/manifest */
13779 	lscf_select(HASH_SVC);
13780 	/*
13781 	 * Translate the manifest file name to property name. In the deathrow
13782 	 * case, the manifest file does not need to exist.
13783 	 */
13784 	pgname = mhash_filename_to_propname(manifest,
13785 	    deathrow ? B_TRUE : B_FALSE);
13786 	if (pgname == NULL) {
13787 		warn(gettext("cannot resolve pathname for %s\n"), manifest);
13788 		return;
13789 	}
13790 	/* delete the hash property name */
13791 	lscf_delpg(pgname);
13792 }
13793 
13794 void
13795 lscf_listprop(const char *pattern)
13796 {
13797 	lscf_prep_hndl();
13798 
13799 	listprop(pattern, 0, 0);
13800 }
13801 
13802 int
13803 lscf_setprop(const char *pgname, const char *type, const char *value,
13804     const uu_list_t *values)
13805 {
13806 	scf_type_t ty, current_ty;
13807 	scf_service_t *svc;
13808 	scf_propertygroup_t *pg, *parent_pg;
13809 	scf_property_t *prop, *parent_prop;
13810 	scf_pg_tmpl_t *pgt;
13811 	scf_prop_tmpl_t *prt;
13812 	int ret, result = 0;
13813 	scf_transaction_t *tx;
13814 	scf_transaction_entry_t *e;
13815 	scf_value_t *v;
13816 	uu_list_walk_t *walk;
13817 	string_list_t *sp;
13818 	char *propname;
13819 	int req_quotes = 0;
13820 
13821 	lscf_prep_hndl();
13822 
13823 	if ((e = scf_entry_create(g_hndl)) == NULL ||
13824 	    (svc = scf_service_create(g_hndl)) == NULL ||
13825 	    (parent_pg = scf_pg_create(g_hndl)) == NULL ||
13826 	    (pg = scf_pg_create(g_hndl)) == NULL ||
13827 	    (parent_prop = scf_property_create(g_hndl)) == NULL ||
13828 	    (prop = scf_property_create(g_hndl)) == NULL ||
13829 	    (pgt = scf_tmpl_pg_create(g_hndl)) == NULL ||
13830 	    (prt = scf_tmpl_prop_create(g_hndl)) == NULL ||
13831 	    (tx = scf_transaction_create(g_hndl)) == NULL)
13832 		scfdie();
13833 
13834 	if (cur_snap != NULL) {
13835 		semerr(emsg_cant_modify_snapshots);
13836 		goto fail;
13837 	}
13838 
13839 	if (cur_inst == NULL && cur_svc == NULL) {
13840 		semerr(emsg_entity_not_selected);
13841 		goto fail;
13842 	}
13843 
13844 	propname = strchr(pgname, '/');
13845 	if (propname == NULL) {
13846 		semerr(gettext("Property names must contain a `/'.\n"));
13847 		goto fail;
13848 	}
13849 
13850 	*propname = '\0';
13851 	++propname;
13852 
13853 	if (type != NULL) {
13854 		ty = string_to_type(type);
13855 		if (ty == SCF_TYPE_INVALID) {
13856 			semerr(gettext("Unknown type \"%s\".\n"), type);
13857 			goto fail;
13858 		}
13859 	}
13860 
13861 	if (cur_inst != NULL)
13862 		ret = scf_instance_get_pg(cur_inst, pgname, pg);
13863 	else
13864 		ret = scf_service_get_pg(cur_svc, pgname, pg);
13865 	if (ret != SCF_SUCCESS) {
13866 		switch (scf_error()) {
13867 		case SCF_ERROR_NOT_FOUND:
13868 			semerr(emsg_no_such_pg, pgname);
13869 			goto fail;
13870 
13871 		case SCF_ERROR_INVALID_ARGUMENT:
13872 			semerr(emsg_invalid_pg_name, pgname);
13873 			goto fail;
13874 
13875 		default:
13876 			scfdie();
13877 			break;
13878 		}
13879 	}
13880 
13881 	do {
13882 		if (scf_pg_update(pg) == -1)
13883 			scfdie();
13884 		if (scf_transaction_start(tx, pg) != SCF_SUCCESS) {
13885 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
13886 				scfdie();
13887 
13888 			semerr(emsg_permission_denied);
13889 			goto fail;
13890 		}
13891 
13892 		ret = scf_pg_get_property(pg, propname, prop);
13893 		if (ret == SCF_SUCCESS) {
13894 			if (scf_property_type(prop, &current_ty) != SCF_SUCCESS)
13895 				scfdie();
13896 
13897 			if (type == NULL)
13898 				ty = current_ty;
13899 			if (scf_transaction_property_change_type(tx, e,
13900 			    propname, ty) == -1)
13901 				scfdie();
13902 
13903 		} else if (scf_error() == SCF_ERROR_NOT_FOUND) {
13904 			/* Infer the type, if possible. */
13905 			if (type == NULL) {
13906 				/*
13907 				 * First check if we're an instance and the
13908 				 * property is set on the service.
13909 				 */
13910 				if (cur_inst != NULL &&
13911 				    scf_instance_get_parent(cur_inst,
13912 				    svc) == 0 &&
13913 				    scf_service_get_pg(cur_svc, pgname,
13914 				    parent_pg) == 0 &&
13915 				    scf_pg_get_property(parent_pg, propname,
13916 				    parent_prop) == 0 &&
13917 				    scf_property_type(parent_prop,
13918 				    &current_ty) == 0) {
13919 					ty = current_ty;
13920 
13921 				/* Then check for a type set in a template. */
13922 				} else if (scf_tmpl_get_by_pg(pg, pgt,
13923 				    0) == 0 &&
13924 				    scf_tmpl_get_by_prop(pgt, propname, prt,
13925 				    0) == 0 &&
13926 				    scf_tmpl_prop_type(prt, &current_ty) == 0) {
13927 					ty = current_ty;
13928 
13929 				/* If type can't be inferred, fail. */
13930 				} else {
13931 					semerr(gettext("Type required for new "
13932 					    "properties.\n"));
13933 					goto fail;
13934 				}
13935 			}
13936 			if (scf_transaction_property_new(tx, e, propname,
13937 			    ty) == -1)
13938 				scfdie();
13939 		} else if (scf_error() == SCF_ERROR_INVALID_ARGUMENT) {
13940 			semerr(emsg_invalid_prop_name, propname);
13941 			goto fail;
13942 		} else {
13943 			scfdie();
13944 		}
13945 
13946 		if (ty == SCF_TYPE_ASTRING || ty == SCF_TYPE_USTRING)
13947 			req_quotes = 1;
13948 
13949 		if (value != NULL) {
13950 			v = string_to_value(value, ty, 0);
13951 
13952 			if (v == NULL)
13953 				goto fail;
13954 
13955 			ret = scf_entry_add_value(e, v);
13956 			assert(ret == SCF_SUCCESS);
13957 		} else {
13958 			assert(values != NULL);
13959 
13960 			walk = uu_list_walk_start((uu_list_t *)values,
13961 			    UU_DEFAULT);
13962 			if (walk == NULL)
13963 				uu_die(gettext("Could not walk list"));
13964 
13965 			for (sp = uu_list_walk_next(walk); sp != NULL;
13966 			    sp = uu_list_walk_next(walk)) {
13967 				v = string_to_value(sp->str, ty, req_quotes);
13968 
13969 				if (v == NULL) {
13970 					scf_entry_destroy_children(e);
13971 					goto fail;
13972 				}
13973 
13974 				ret = scf_entry_add_value(e, v);
13975 				assert(ret == SCF_SUCCESS);
13976 			}
13977 			uu_list_walk_end(walk);
13978 		}
13979 		result = scf_transaction_commit(tx);
13980 
13981 		scf_transaction_reset(tx);
13982 		scf_entry_destroy_children(e);
13983 	} while (result == 0);
13984 
13985 	if (result < 0) {
13986 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
13987 			scfdie();
13988 
13989 		semerr(emsg_permission_denied);
13990 		goto fail;
13991 	}
13992 
13993 	ret = 0;
13994 
13995 	private_refresh();
13996 
13997 	goto cleanup;
13998 
13999 fail:
14000 	ret = -1;
14001 
14002 cleanup:
14003 	scf_transaction_destroy(tx);
14004 	scf_entry_destroy(e);
14005 	scf_service_destroy(svc);
14006 	scf_pg_destroy(parent_pg);
14007 	scf_pg_destroy(pg);
14008 	scf_property_destroy(parent_prop);
14009 	scf_property_destroy(prop);
14010 	scf_tmpl_pg_destroy(pgt);
14011 	scf_tmpl_prop_destroy(prt);
14012 
14013 	return (ret);
14014 }
14015 
14016 void
14017 lscf_delprop(char *pgn)
14018 {
14019 	char *slash, *pn;
14020 	scf_propertygroup_t *pg;
14021 	scf_transaction_t *tx;
14022 	scf_transaction_entry_t *e;
14023 	int ret;
14024 
14025 
14026 	lscf_prep_hndl();
14027 
14028 	if (cur_snap != NULL) {
14029 		semerr(emsg_cant_modify_snapshots);
14030 		return;
14031 	}
14032 
14033 	if (cur_inst == NULL && cur_svc == NULL) {
14034 		semerr(emsg_entity_not_selected);
14035 		return;
14036 	}
14037 
14038 	pg = scf_pg_create(g_hndl);
14039 	if (pg == NULL)
14040 		scfdie();
14041 
14042 	slash = strchr(pgn, '/');
14043 	if (slash == NULL) {
14044 		pn = NULL;
14045 	} else {
14046 		*slash = '\0';
14047 		pn = slash + 1;
14048 	}
14049 
14050 	if (cur_inst != NULL)
14051 		ret = scf_instance_get_pg(cur_inst, pgn, pg);
14052 	else
14053 		ret = scf_service_get_pg(cur_svc, pgn, pg);
14054 	if (ret != SCF_SUCCESS) {
14055 		switch (scf_error()) {
14056 		case SCF_ERROR_NOT_FOUND:
14057 			semerr(emsg_no_such_pg, pgn);
14058 			break;
14059 
14060 		case SCF_ERROR_INVALID_ARGUMENT:
14061 			semerr(emsg_invalid_pg_name, pgn);
14062 			break;
14063 
14064 		default:
14065 			scfdie();
14066 		}
14067 
14068 		scf_pg_destroy(pg);
14069 
14070 		return;
14071 	}
14072 
14073 	if (pn == NULL) {
14074 		/* Try to delete the property group. */
14075 		if (scf_pg_delete(pg) != SCF_SUCCESS) {
14076 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14077 				scfdie();
14078 
14079 			semerr(emsg_permission_denied);
14080 		} else {
14081 			private_refresh();
14082 		}
14083 
14084 		scf_pg_destroy(pg);
14085 		return;
14086 	}
14087 
14088 	e = scf_entry_create(g_hndl);
14089 	tx = scf_transaction_create(g_hndl);
14090 
14091 	do {
14092 		if (scf_pg_update(pg) == -1)
14093 			scfdie();
14094 		if (scf_transaction_start(tx, pg) != SCF_SUCCESS) {
14095 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14096 				scfdie();
14097 
14098 			semerr(emsg_permission_denied);
14099 			break;
14100 		}
14101 
14102 		if (scf_transaction_property_delete(tx, e, pn) != SCF_SUCCESS) {
14103 			if (scf_error() == SCF_ERROR_NOT_FOUND) {
14104 				semerr(gettext("No such property %s/%s.\n"),
14105 				    pgn, pn);
14106 				break;
14107 			} else if (scf_error() == SCF_ERROR_INVALID_ARGUMENT) {
14108 				semerr(emsg_invalid_prop_name, pn);
14109 				break;
14110 			} else {
14111 				scfdie();
14112 			}
14113 		}
14114 
14115 		ret = scf_transaction_commit(tx);
14116 
14117 		if (ret == 0)
14118 			scf_transaction_reset(tx);
14119 	} while (ret == 0);
14120 
14121 	if (ret < 0) {
14122 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14123 			scfdie();
14124 
14125 		semerr(emsg_permission_denied);
14126 	} else {
14127 		private_refresh();
14128 	}
14129 
14130 	scf_transaction_destroy(tx);
14131 	scf_entry_destroy(e);
14132 	scf_pg_destroy(pg);
14133 }
14134 
14135 /*
14136  * Property editing.
14137  */
14138 
14139 static int
14140 write_edit_script(FILE *strm)
14141 {
14142 	char *fmribuf;
14143 	ssize_t fmrilen;
14144 
14145 	scf_propertygroup_t *pg;
14146 	scf_property_t *prop;
14147 	scf_value_t *val;
14148 	scf_type_t ty;
14149 	int ret, result = 0;
14150 	scf_iter_t *iter, *piter, *viter;
14151 	char *buf, *tybuf, *pname;
14152 	const char *emsg_write_error;
14153 
14154 
14155 	emsg_write_error = gettext("Error writing temoprary file: %s.\n");
14156 
14157 
14158 	/* select fmri */
14159 	if (cur_inst != NULL) {
14160 		fmrilen = scf_instance_to_fmri(cur_inst, NULL, 0);
14161 		if (fmrilen < 0)
14162 			scfdie();
14163 		fmribuf = safe_malloc(fmrilen + 1);
14164 		if (scf_instance_to_fmri(cur_inst, fmribuf, fmrilen + 1) < 0)
14165 			scfdie();
14166 	} else {
14167 		assert(cur_svc != NULL);
14168 		fmrilen = scf_service_to_fmri(cur_svc, NULL, 0);
14169 		if (fmrilen < 0)
14170 			scfdie();
14171 		fmribuf = safe_malloc(fmrilen + 1);
14172 		if (scf_service_to_fmri(cur_svc, fmribuf, fmrilen + 1) < 0)
14173 			scfdie();
14174 	}
14175 
14176 	if (fprintf(strm, "select %s\n\n", fmribuf) < 0) {
14177 		warn(emsg_write_error, strerror(errno));
14178 		free(fmribuf);
14179 		return (-1);
14180 	}
14181 
14182 	free(fmribuf);
14183 
14184 
14185 	if ((pg = scf_pg_create(g_hndl)) == NULL ||
14186 	    (prop = scf_property_create(g_hndl)) == NULL ||
14187 	    (val = scf_value_create(g_hndl)) == NULL ||
14188 	    (iter = scf_iter_create(g_hndl)) == NULL ||
14189 	    (piter = scf_iter_create(g_hndl)) == NULL ||
14190 	    (viter = scf_iter_create(g_hndl)) == NULL)
14191 		scfdie();
14192 
14193 	buf = safe_malloc(max_scf_name_len + 1);
14194 	tybuf = safe_malloc(max_scf_pg_type_len + 1);
14195 	pname = safe_malloc(max_scf_name_len + 1);
14196 
14197 	if (cur_inst != NULL)
14198 		ret = scf_iter_instance_pgs(iter, cur_inst);
14199 	else
14200 		ret = scf_iter_service_pgs(iter, cur_svc);
14201 	if (ret != SCF_SUCCESS)
14202 		scfdie();
14203 
14204 	while ((ret = scf_iter_next_pg(iter, pg)) == 1) {
14205 		int ret2;
14206 
14207 		/*
14208 		 * # delprop pg
14209 		 * # addpg pg type
14210 		 */
14211 		if (scf_pg_get_name(pg, buf, max_scf_name_len + 1) < 0)
14212 			scfdie();
14213 
14214 		if (scf_pg_get_type(pg, tybuf, max_scf_pg_type_len + 1) < 0)
14215 			scfdie();
14216 
14217 		if (fprintf(strm, "# Property group \"%s\"\n"
14218 		    "# delprop %s\n"
14219 		    "# addpg %s %s\n", buf, buf, buf, tybuf) < 0) {
14220 			warn(emsg_write_error, strerror(errno));
14221 			result = -1;
14222 			goto out;
14223 		}
14224 
14225 		/* # setprop pg/prop = (values) */
14226 
14227 		if (scf_iter_pg_properties(piter, pg) != SCF_SUCCESS)
14228 			scfdie();
14229 
14230 		while ((ret2 = scf_iter_next_property(piter, prop)) == 1) {
14231 			int first = 1;
14232 			int ret3;
14233 			int multiple;
14234 			int is_str;
14235 			scf_type_t bty;
14236 
14237 			if (scf_property_get_name(prop, pname,
14238 			    max_scf_name_len + 1) < 0)
14239 				scfdie();
14240 
14241 			if (scf_property_type(prop, &ty) != 0)
14242 				scfdie();
14243 
14244 			multiple = prop_has_multiple_values(prop, val);
14245 
14246 			if (fprintf(strm, "# setprop %s/%s = %s: %s", buf,
14247 			    pname, scf_type_to_string(ty), multiple ? "(" : "")
14248 			    < 0) {
14249 				warn(emsg_write_error, strerror(errno));
14250 				result = -1;
14251 				goto out;
14252 			}
14253 
14254 			(void) scf_type_base_type(ty, &bty);
14255 			is_str = (bty == SCF_TYPE_ASTRING);
14256 
14257 			if (scf_iter_property_values(viter, prop) !=
14258 			    SCF_SUCCESS)
14259 				scfdie();
14260 
14261 			while ((ret3 = scf_iter_next_value(viter, val)) == 1) {
14262 				char *buf;
14263 				ssize_t buflen;
14264 
14265 				buflen = scf_value_get_as_string(val, NULL, 0);
14266 				if (buflen < 0)
14267 					scfdie();
14268 
14269 				buf = safe_malloc(buflen + 1);
14270 
14271 				if (scf_value_get_as_string(val, buf,
14272 				    buflen + 1) < 0)
14273 					scfdie();
14274 
14275 				if (first)
14276 					first = 0;
14277 				else {
14278 					if (putc(' ', strm) != ' ') {
14279 						warn(emsg_write_error,
14280 						    strerror(errno));
14281 						result = -1;
14282 						goto out;
14283 					}
14284 				}
14285 
14286 				if ((is_str && multiple) ||
14287 				    strpbrk(buf, CHARS_TO_QUOTE) != NULL) {
14288 					(void) putc('"', strm);
14289 					(void) quote_and_print(buf, strm, 1);
14290 					(void) putc('"', strm);
14291 
14292 					if (ferror(strm)) {
14293 						warn(emsg_write_error,
14294 						    strerror(errno));
14295 						result = -1;
14296 						goto out;
14297 					}
14298 				} else {
14299 					if (fprintf(strm, "%s", buf) < 0) {
14300 						warn(emsg_write_error,
14301 						    strerror(errno));
14302 						result = -1;
14303 						goto out;
14304 					}
14305 				}
14306 
14307 				free(buf);
14308 			}
14309 			if (ret3 < 0 &&
14310 			    scf_error() != SCF_ERROR_PERMISSION_DENIED)
14311 				scfdie();
14312 
14313 			/* Write closing paren if mult-value property */
14314 			if ((multiple && putc(')', strm) == EOF) ||
14315 
14316 			    /* Write final newline */
14317 			    fputc('\n', strm) == EOF) {
14318 				warn(emsg_write_error, strerror(errno));
14319 				result = -1;
14320 				goto out;
14321 			}
14322 		}
14323 		if (ret2 < 0)
14324 			scfdie();
14325 
14326 		if (fputc('\n', strm) == EOF) {
14327 			warn(emsg_write_error, strerror(errno));
14328 			result = -1;
14329 			goto out;
14330 		}
14331 	}
14332 	if (ret < 0)
14333 		scfdie();
14334 
14335 out:
14336 	free(pname);
14337 	free(tybuf);
14338 	free(buf);
14339 	scf_iter_destroy(viter);
14340 	scf_iter_destroy(piter);
14341 	scf_iter_destroy(iter);
14342 	scf_value_destroy(val);
14343 	scf_property_destroy(prop);
14344 	scf_pg_destroy(pg);
14345 
14346 	if (result == 0) {
14347 		if (fflush(strm) != 0) {
14348 			warn(emsg_write_error, strerror(errno));
14349 			return (-1);
14350 		}
14351 	}
14352 
14353 	return (result);
14354 }
14355 
14356 int
14357 lscf_editprop()
14358 {
14359 	char *buf, *editor;
14360 	size_t bufsz;
14361 	int tmpfd;
14362 	char tempname[] = TEMP_FILE_PATTERN;
14363 
14364 	lscf_prep_hndl();
14365 
14366 	if (cur_snap != NULL) {
14367 		semerr(emsg_cant_modify_snapshots);
14368 		return (-1);
14369 	}
14370 
14371 	if (cur_svc == NULL && cur_inst == NULL) {
14372 		semerr(emsg_entity_not_selected);
14373 		return (-1);
14374 	}
14375 
14376 	tmpfd = mkstemp(tempname);
14377 	if (tmpfd == -1) {
14378 		semerr(gettext("Could not create temporary file.\n"));
14379 		return (-1);
14380 	}
14381 
14382 	(void) strcpy(tempfilename, tempname);
14383 
14384 	tempfile = fdopen(tmpfd, "r+");
14385 	if (tempfile == NULL) {
14386 		warn(gettext("Could not create temporary file.\n"));
14387 		if (close(tmpfd) == -1)
14388 			warn(gettext("Could not close temporary file: %s.\n"),
14389 			    strerror(errno));
14390 
14391 		remove_tempfile();
14392 
14393 		return (-1);
14394 	}
14395 
14396 	if (write_edit_script(tempfile) == -1) {
14397 		remove_tempfile();
14398 		return (-1);
14399 	}
14400 
14401 	editor = getenv("EDITOR");
14402 	if (editor == NULL)
14403 		editor = "vi";
14404 
14405 	bufsz = strlen(editor) + 1 + strlen(tempname) + 1;
14406 	buf = safe_malloc(bufsz);
14407 
14408 	if (snprintf(buf, bufsz, "%s %s", editor, tempname) < 0)
14409 		uu_die(gettext("Error creating editor command"));
14410 
14411 	if (system(buf) == -1) {
14412 		semerr(gettext("Could not launch editor %s: %s\n"), editor,
14413 		    strerror(errno));
14414 		free(buf);
14415 		remove_tempfile();
14416 		return (-1);
14417 	}
14418 
14419 	free(buf);
14420 
14421 	(void) engine_source(tempname, est->sc_cmd_flags & SC_CMD_IACTIVE);
14422 
14423 	remove_tempfile();
14424 
14425 	return (0);
14426 }
14427 
14428 static void
14429 add_string(uu_list_t *strlist, const char *str)
14430 {
14431 	string_list_t *elem;
14432 	elem = safe_malloc(sizeof (*elem));
14433 	uu_list_node_init(elem, &elem->node, string_pool);
14434 	elem->str = safe_strdup(str);
14435 	if (uu_list_append(strlist, elem) != 0)
14436 		uu_die(gettext("libuutil error: %s\n"),
14437 		    uu_strerror(uu_error()));
14438 }
14439 
14440 static int
14441 remove_string(uu_list_t *strlist, const char *str)
14442 {
14443 	uu_list_walk_t	*elems;
14444 	string_list_t	*sp;
14445 
14446 	/*
14447 	 * Find the element that needs to be removed.
14448 	 */
14449 	elems = uu_list_walk_start(strlist, UU_DEFAULT);
14450 	while ((sp = uu_list_walk_next(elems)) != NULL) {
14451 		if (strcmp(sp->str, str) == 0)
14452 			break;
14453 	}
14454 	uu_list_walk_end(elems);
14455 
14456 	/*
14457 	 * Returning 1 here as the value was not found, this
14458 	 * might not be an error.  Leave it to the caller to
14459 	 * decide.
14460 	 */
14461 	if (sp == NULL) {
14462 		return (1);
14463 	}
14464 
14465 	uu_list_remove(strlist, sp);
14466 
14467 	free(sp->str);
14468 	free(sp);
14469 
14470 	return (0);
14471 }
14472 
14473 /*
14474  * Get all property values that don't match the given glob pattern,
14475  * if a pattern is specified.
14476  */
14477 static void
14478 get_prop_values(scf_property_t *prop, uu_list_t *values,
14479     const char *pattern)
14480 {
14481 	scf_iter_t *iter;
14482 	scf_value_t *val;
14483 	int ret;
14484 
14485 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
14486 	    (val = scf_value_create(g_hndl)) == NULL)
14487 		scfdie();
14488 
14489 	if (scf_iter_property_values(iter, prop) != 0)
14490 		scfdie();
14491 
14492 	while ((ret = scf_iter_next_value(iter, val)) == 1) {
14493 		char *buf;
14494 		ssize_t vlen, szret;
14495 
14496 		vlen = scf_value_get_as_string(val, NULL, 0);
14497 		if (vlen < 0)
14498 			scfdie();
14499 
14500 		buf = safe_malloc(vlen + 1);
14501 
14502 		szret = scf_value_get_as_string(val, buf, vlen + 1);
14503 		if (szret < 0)
14504 			scfdie();
14505 		assert(szret <= vlen);
14506 
14507 		if (pattern == NULL || fnmatch(pattern, buf, 0) != 0)
14508 			add_string(values, buf);
14509 
14510 		free(buf);
14511 	}
14512 
14513 	if (ret == -1)
14514 		scfdie();
14515 
14516 	scf_value_destroy(val);
14517 	scf_iter_destroy(iter);
14518 }
14519 
14520 static int
14521 lscf_setpropvalue(const char *pgname, const char *type,
14522     const char *arg, int isadd, int isnotfoundok)
14523 {
14524 	scf_type_t ty;
14525 	scf_propertygroup_t *pg;
14526 	scf_property_t *prop;
14527 	int ret, result = 0;
14528 	scf_transaction_t *tx;
14529 	scf_transaction_entry_t *e;
14530 	scf_value_t *v;
14531 	string_list_t *sp;
14532 	char *propname;
14533 	uu_list_t *values;
14534 	uu_list_walk_t *walk;
14535 	void *cookie = NULL;
14536 	char *pattern = NULL;
14537 
14538 	lscf_prep_hndl();
14539 
14540 	if ((values = uu_list_create(string_pool, NULL, 0)) == NULL)
14541 		uu_die(gettext("Could not create property list: %s\n"),
14542 		    uu_strerror(uu_error()));
14543 
14544 	if (!isadd)
14545 		pattern = safe_strdup(arg);
14546 
14547 	if ((e = scf_entry_create(g_hndl)) == NULL ||
14548 	    (pg = scf_pg_create(g_hndl)) == NULL ||
14549 	    (prop = scf_property_create(g_hndl)) == NULL ||
14550 	    (tx = scf_transaction_create(g_hndl)) == NULL)
14551 		scfdie();
14552 
14553 	if (cur_snap != NULL) {
14554 		semerr(emsg_cant_modify_snapshots);
14555 		goto fail;
14556 	}
14557 
14558 	if (cur_inst == NULL && cur_svc == NULL) {
14559 		semerr(emsg_entity_not_selected);
14560 		goto fail;
14561 	}
14562 
14563 	propname = strchr(pgname, '/');
14564 	if (propname == NULL) {
14565 		semerr(gettext("Property names must contain a `/'.\n"));
14566 		goto fail;
14567 	}
14568 
14569 	*propname = '\0';
14570 	++propname;
14571 
14572 	if (type != NULL) {
14573 		ty = string_to_type(type);
14574 		if (ty == SCF_TYPE_INVALID) {
14575 			semerr(gettext("Unknown type \"%s\".\n"), type);
14576 			goto fail;
14577 		}
14578 	}
14579 
14580 	if (cur_inst != NULL)
14581 		ret = scf_instance_get_pg(cur_inst, pgname, pg);
14582 	else
14583 		ret = scf_service_get_pg(cur_svc, pgname, pg);
14584 	if (ret != 0) {
14585 		switch (scf_error()) {
14586 		case SCF_ERROR_NOT_FOUND:
14587 			if (isnotfoundok) {
14588 				result = 0;
14589 			} else {
14590 				semerr(emsg_no_such_pg, pgname);
14591 				result = -1;
14592 			}
14593 			goto out;
14594 
14595 		case SCF_ERROR_INVALID_ARGUMENT:
14596 			semerr(emsg_invalid_pg_name, pgname);
14597 			goto fail;
14598 
14599 		default:
14600 			scfdie();
14601 		}
14602 	}
14603 
14604 	do {
14605 		if (scf_pg_update(pg) == -1)
14606 			scfdie();
14607 		if (scf_transaction_start(tx, pg) != 0) {
14608 			if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14609 				scfdie();
14610 
14611 			semerr(emsg_permission_denied);
14612 			goto fail;
14613 		}
14614 
14615 		ret = scf_pg_get_property(pg, propname, prop);
14616 		if (ret == 0) {
14617 			scf_type_t ptype;
14618 			char *pat = pattern;
14619 
14620 			if (scf_property_type(prop, &ptype) != 0)
14621 				scfdie();
14622 
14623 			if (isadd) {
14624 				if (type != NULL && ptype != ty) {
14625 					semerr(gettext("Property \"%s\" is not "
14626 					    "of type \"%s\".\n"), propname,
14627 					    type);
14628 					goto fail;
14629 				}
14630 
14631 				pat = NULL;
14632 			} else {
14633 				size_t len = strlen(pat);
14634 				if (len > 0 && pat[len - 1] == '\"')
14635 					pat[len - 1] = '\0';
14636 				if (len > 0 && pat[0] == '\"')
14637 					pat++;
14638 			}
14639 
14640 			ty = ptype;
14641 
14642 			get_prop_values(prop, values, pat);
14643 
14644 			if (isadd)
14645 				add_string(values, arg);
14646 
14647 			if (scf_transaction_property_change(tx, e,
14648 			    propname, ty) == -1)
14649 				scfdie();
14650 		} else if (scf_error() == SCF_ERROR_NOT_FOUND) {
14651 			if (isadd) {
14652 				if (type == NULL) {
14653 					semerr(gettext("Type required "
14654 					    "for new properties.\n"));
14655 					goto fail;
14656 				}
14657 
14658 				add_string(values, arg);
14659 
14660 				if (scf_transaction_property_new(tx, e,
14661 				    propname, ty) == -1)
14662 					scfdie();
14663 			} else if (isnotfoundok) {
14664 				result = 0;
14665 				goto out;
14666 			} else {
14667 				semerr(gettext("No such property %s/%s.\n"),
14668 				    pgname, propname);
14669 				result = -1;
14670 				goto out;
14671 			}
14672 		} else if (scf_error() == SCF_ERROR_INVALID_ARGUMENT) {
14673 			semerr(emsg_invalid_prop_name, propname);
14674 			goto fail;
14675 		} else {
14676 			scfdie();
14677 		}
14678 
14679 		walk = uu_list_walk_start(values, UU_DEFAULT);
14680 		if (walk == NULL)
14681 			uu_die(gettext("Could not walk property list.\n"));
14682 
14683 		for (sp = uu_list_walk_next(walk); sp != NULL;
14684 		    sp = uu_list_walk_next(walk)) {
14685 			v = string_to_value(sp->str, ty, 0);
14686 
14687 			if (v == NULL) {
14688 				scf_entry_destroy_children(e);
14689 				goto fail;
14690 			}
14691 			ret = scf_entry_add_value(e, v);
14692 			assert(ret == 0);
14693 		}
14694 		uu_list_walk_end(walk);
14695 
14696 		result = scf_transaction_commit(tx);
14697 
14698 		scf_transaction_reset(tx);
14699 		scf_entry_destroy_children(e);
14700 	} while (result == 0);
14701 
14702 	if (result < 0) {
14703 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
14704 			scfdie();
14705 
14706 		semerr(emsg_permission_denied);
14707 		goto fail;
14708 	}
14709 
14710 	result = 0;
14711 
14712 	private_refresh();
14713 
14714 out:
14715 	scf_transaction_destroy(tx);
14716 	scf_entry_destroy(e);
14717 	scf_pg_destroy(pg);
14718 	scf_property_destroy(prop);
14719 	free(pattern);
14720 
14721 	while ((sp = uu_list_teardown(values, &cookie)) != NULL) {
14722 		free(sp->str);
14723 		free(sp);
14724 	}
14725 
14726 	uu_list_destroy(values);
14727 
14728 	return (result);
14729 
14730 fail:
14731 	result = -1;
14732 	goto out;
14733 }
14734 
14735 int
14736 lscf_addpropvalue(const char *pgname, const char *type, const char *value)
14737 {
14738 	return (lscf_setpropvalue(pgname, type, value, 1, 0));
14739 }
14740 
14741 int
14742 lscf_delpropvalue(const char *pgname, const char *pattern, int isnotfoundok)
14743 {
14744 	return (lscf_setpropvalue(pgname, NULL, pattern, 0, isnotfoundok));
14745 }
14746 
14747 /*
14748  * Look for a standard start method, first in the instance (if any),
14749  * then the service.
14750  */
14751 static const char *
14752 start_method_name(int *in_instance)
14753 {
14754 	scf_propertygroup_t *pg;
14755 	char **p;
14756 	int ret;
14757 	scf_instance_t *inst = cur_inst;
14758 
14759 	if ((pg = scf_pg_create(g_hndl)) == NULL)
14760 		scfdie();
14761 
14762 again:
14763 	for (p = start_method_names; *p != NULL; p++) {
14764 		if (inst != NULL)
14765 			ret = scf_instance_get_pg(inst, *p, pg);
14766 		else
14767 			ret = scf_service_get_pg(cur_svc, *p, pg);
14768 
14769 		if (ret == 0) {
14770 			size_t bufsz = strlen(SCF_GROUP_METHOD) + 1;
14771 			char *buf = safe_malloc(bufsz);
14772 
14773 			if ((ret = scf_pg_get_type(pg, buf, bufsz)) < 0) {
14774 				free(buf);
14775 				continue;
14776 			}
14777 			if (strcmp(buf, SCF_GROUP_METHOD) != 0) {
14778 				free(buf);
14779 				continue;
14780 			}
14781 
14782 			free(buf);
14783 			*in_instance = (inst != NULL);
14784 			scf_pg_destroy(pg);
14785 			return (*p);
14786 		}
14787 
14788 		if (scf_error() == SCF_ERROR_NOT_FOUND)
14789 			continue;
14790 
14791 		scfdie();
14792 	}
14793 
14794 	if (inst != NULL) {
14795 		inst = NULL;
14796 		goto again;
14797 	}
14798 
14799 	scf_pg_destroy(pg);
14800 	return (NULL);
14801 }
14802 
14803 static int
14804 addpg(const char *name, const char *type)
14805 {
14806 	scf_propertygroup_t *pg;
14807 	int ret;
14808 
14809 	pg = scf_pg_create(g_hndl);
14810 	if (pg == NULL)
14811 		scfdie();
14812 
14813 	if (cur_inst != NULL)
14814 		ret = scf_instance_add_pg(cur_inst, name, type, 0, pg);
14815 	else
14816 		ret = scf_service_add_pg(cur_svc, name, type, 0, pg);
14817 
14818 	if (ret != 0) {
14819 		switch (scf_error()) {
14820 		case SCF_ERROR_EXISTS:
14821 			ret = 0;
14822 			break;
14823 
14824 		case SCF_ERROR_PERMISSION_DENIED:
14825 			semerr(emsg_permission_denied);
14826 			break;
14827 
14828 		default:
14829 			scfdie();
14830 		}
14831 	}
14832 
14833 	scf_pg_destroy(pg);
14834 	return (ret);
14835 }
14836 
14837 int
14838 lscf_setenv(uu_list_t *args, int isunset)
14839 {
14840 	int ret = 0;
14841 	size_t i;
14842 	int argc;
14843 	char **argv = NULL;
14844 	string_list_t *slp;
14845 	char *pattern;
14846 	char *prop;
14847 	int do_service = 0;
14848 	int do_instance = 0;
14849 	const char *method = NULL;
14850 	const char *name = NULL;
14851 	const char *value = NULL;
14852 	scf_instance_t *saved_cur_inst = cur_inst;
14853 
14854 	lscf_prep_hndl();
14855 
14856 	argc = uu_list_numnodes(args);
14857 	if (argc < 1)
14858 		goto usage;
14859 
14860 	argv = calloc(argc + 1, sizeof (char *));
14861 	if (argv == NULL)
14862 		uu_die(gettext("Out of memory.\n"));
14863 
14864 	for (slp = uu_list_first(args), i = 0;
14865 	    slp != NULL;
14866 	    slp = uu_list_next(args, slp), ++i)
14867 		argv[i] = slp->str;
14868 
14869 	argv[i] = NULL;
14870 
14871 	opterr = 0;
14872 	optind = 0;
14873 	for (;;) {
14874 		ret = getopt(argc, argv, "sim:");
14875 		if (ret == -1)
14876 			break;
14877 
14878 		switch (ret) {
14879 		case 's':
14880 			do_service = 1;
14881 			cur_inst = NULL;
14882 			break;
14883 
14884 		case 'i':
14885 			do_instance = 1;
14886 			break;
14887 
14888 		case 'm':
14889 			method = optarg;
14890 			break;
14891 
14892 		case '?':
14893 			goto usage;
14894 
14895 		default:
14896 			bad_error("getopt", ret);
14897 		}
14898 	}
14899 
14900 	argc -= optind;
14901 	if ((do_service && do_instance) ||
14902 	    (isunset && argc != 1) ||
14903 	    (!isunset && argc != 2))
14904 		goto usage;
14905 
14906 	name = argv[optind];
14907 	if (!isunset)
14908 		value = argv[optind + 1];
14909 
14910 	if (cur_snap != NULL) {
14911 		semerr(emsg_cant_modify_snapshots);
14912 		ret = -1;
14913 		goto out;
14914 	}
14915 
14916 	if (cur_inst == NULL && cur_svc == NULL) {
14917 		semerr(emsg_entity_not_selected);
14918 		ret = -1;
14919 		goto out;
14920 	}
14921 
14922 	if (do_instance && cur_inst == NULL) {
14923 		semerr(gettext("No instance is selected.\n"));
14924 		ret = -1;
14925 		goto out;
14926 	}
14927 
14928 	if (do_service && cur_svc == NULL) {
14929 		semerr(gettext("No service is selected.\n"));
14930 		ret = -1;
14931 		goto out;
14932 	}
14933 
14934 	if (method == NULL) {
14935 		if (do_instance || do_service) {
14936 			method = "method_context";
14937 			if (!isunset) {
14938 				ret = addpg("method_context",
14939 				    SCF_GROUP_FRAMEWORK);
14940 				if (ret != 0)
14941 					goto out;
14942 			}
14943 		} else {
14944 			int in_instance;
14945 			method = start_method_name(&in_instance);
14946 			if (method == NULL) {
14947 				semerr(gettext(
14948 				    "Couldn't find start method; please "
14949 				    "specify a method with '-m'.\n"));
14950 				ret = -1;
14951 				goto out;
14952 			}
14953 			if (!in_instance)
14954 				cur_inst = NULL;
14955 		}
14956 	} else {
14957 		scf_propertygroup_t *pg;
14958 		size_t bufsz;
14959 		char *buf;
14960 		int ret;
14961 
14962 		if ((pg = scf_pg_create(g_hndl)) == NULL)
14963 			scfdie();
14964 
14965 		if (cur_inst != NULL)
14966 			ret = scf_instance_get_pg(cur_inst, method, pg);
14967 		else
14968 			ret = scf_service_get_pg(cur_svc, method, pg);
14969 
14970 		if (ret != 0) {
14971 			scf_pg_destroy(pg);
14972 			switch (scf_error()) {
14973 			case SCF_ERROR_NOT_FOUND:
14974 				semerr(gettext("Couldn't find the method "
14975 				    "\"%s\".\n"), method);
14976 				goto out;
14977 
14978 			case SCF_ERROR_INVALID_ARGUMENT:
14979 				semerr(gettext("Invalid method name \"%s\".\n"),
14980 				    method);
14981 				goto out;
14982 
14983 			default:
14984 				scfdie();
14985 			}
14986 		}
14987 
14988 		bufsz = strlen(SCF_GROUP_METHOD) + 1;
14989 		buf = safe_malloc(bufsz);
14990 
14991 		if (scf_pg_get_type(pg, buf, bufsz) < 0 ||
14992 		    strcmp(buf, SCF_GROUP_METHOD) != 0) {
14993 			semerr(gettext("Property group \"%s\" is not of type "
14994 			    "\"method\".\n"), method);
14995 			ret = -1;
14996 			free(buf);
14997 			scf_pg_destroy(pg);
14998 			goto out;
14999 		}
15000 
15001 		free(buf);
15002 		scf_pg_destroy(pg);
15003 	}
15004 
15005 	prop = uu_msprintf("%s/environment", method);
15006 	pattern = uu_msprintf("%s=*", name);
15007 
15008 	if (prop == NULL || pattern == NULL)
15009 		uu_die(gettext("Out of memory.\n"));
15010 
15011 	ret = lscf_delpropvalue(prop, pattern, !isunset);
15012 
15013 	if (ret == 0 && !isunset) {
15014 		uu_free(pattern);
15015 		uu_free(prop);
15016 		prop = uu_msprintf("%s/environment", method);
15017 		pattern = uu_msprintf("%s=%s", name, value);
15018 		if (prop == NULL || pattern == NULL)
15019 			uu_die(gettext("Out of memory.\n"));
15020 		ret = lscf_addpropvalue(prop, "astring:", pattern);
15021 	}
15022 	uu_free(pattern);
15023 	uu_free(prop);
15024 
15025 out:
15026 	cur_inst = saved_cur_inst;
15027 
15028 	free(argv);
15029 	return (ret);
15030 usage:
15031 	ret = -2;
15032 	goto out;
15033 }
15034 
15035 /*
15036  * Snapshot commands
15037  */
15038 
15039 void
15040 lscf_listsnap()
15041 {
15042 	scf_snapshot_t *snap;
15043 	scf_iter_t *iter;
15044 	char *nb;
15045 	int r;
15046 
15047 	lscf_prep_hndl();
15048 
15049 	if (cur_inst == NULL) {
15050 		semerr(gettext("Instance not selected.\n"));
15051 		return;
15052 	}
15053 
15054 	if ((snap = scf_snapshot_create(g_hndl)) == NULL ||
15055 	    (iter = scf_iter_create(g_hndl)) == NULL)
15056 		scfdie();
15057 
15058 	if (scf_iter_instance_snapshots(iter, cur_inst) != SCF_SUCCESS)
15059 		scfdie();
15060 
15061 	nb = safe_malloc(max_scf_name_len + 1);
15062 
15063 	while ((r = scf_iter_next_snapshot(iter, snap)) == 1) {
15064 		if (scf_snapshot_get_name(snap, nb, max_scf_name_len + 1) < 0)
15065 			scfdie();
15066 
15067 		(void) puts(nb);
15068 	}
15069 	if (r < 0)
15070 		scfdie();
15071 
15072 	free(nb);
15073 	scf_iter_destroy(iter);
15074 	scf_snapshot_destroy(snap);
15075 }
15076 
15077 void
15078 lscf_selectsnap(const char *name)
15079 {
15080 	scf_snapshot_t *snap;
15081 	scf_snaplevel_t *level;
15082 
15083 	lscf_prep_hndl();
15084 
15085 	if (cur_inst == NULL) {
15086 		semerr(gettext("Instance not selected.\n"));
15087 		return;
15088 	}
15089 
15090 	if (cur_snap != NULL) {
15091 		if (name != NULL) {
15092 			char *cur_snap_name;
15093 			boolean_t nochange;
15094 
15095 			cur_snap_name = safe_malloc(max_scf_name_len + 1);
15096 
15097 			if (scf_snapshot_get_name(cur_snap, cur_snap_name,
15098 			    max_scf_name_len + 1) < 0)
15099 				scfdie();
15100 
15101 			nochange = strcmp(name, cur_snap_name) == 0;
15102 
15103 			free(cur_snap_name);
15104 
15105 			if (nochange)
15106 				return;
15107 		}
15108 
15109 		unselect_cursnap();
15110 	}
15111 
15112 	if (name == NULL)
15113 		return;
15114 
15115 	if ((snap = scf_snapshot_create(g_hndl)) == NULL ||
15116 	    (level = scf_snaplevel_create(g_hndl)) == NULL)
15117 		scfdie();
15118 
15119 	if (scf_instance_get_snapshot(cur_inst, name, snap) !=
15120 	    SCF_SUCCESS) {
15121 		switch (scf_error()) {
15122 		case SCF_ERROR_INVALID_ARGUMENT:
15123 			semerr(gettext("Invalid name \"%s\".\n"), name);
15124 			break;
15125 
15126 		case SCF_ERROR_NOT_FOUND:
15127 			semerr(gettext("No such snapshot \"%s\".\n"), name);
15128 			break;
15129 
15130 		default:
15131 			scfdie();
15132 		}
15133 
15134 		scf_snaplevel_destroy(level);
15135 		scf_snapshot_destroy(snap);
15136 		return;
15137 	}
15138 
15139 	/* Load the snaplevels into our list. */
15140 	cur_levels = uu_list_create(snaplevel_pool, NULL, 0);
15141 	if (cur_levels == NULL)
15142 		uu_die(gettext("Could not create list: %s\n"),
15143 		    uu_strerror(uu_error()));
15144 
15145 	if (scf_snapshot_get_base_snaplevel(snap, level) != SCF_SUCCESS) {
15146 		if (scf_error() != SCF_ERROR_NOT_FOUND)
15147 			scfdie();
15148 
15149 		semerr(gettext("Snapshot has no snaplevels.\n"));
15150 
15151 		scf_snaplevel_destroy(level);
15152 		scf_snapshot_destroy(snap);
15153 		return;
15154 	}
15155 
15156 	cur_snap = snap;
15157 
15158 	for (;;) {
15159 		cur_elt = safe_malloc(sizeof (*cur_elt));
15160 		uu_list_node_init(cur_elt, &cur_elt->list_node,
15161 		    snaplevel_pool);
15162 		cur_elt->sl = level;
15163 		if (uu_list_insert_after(cur_levels, NULL, cur_elt) != 0)
15164 			uu_die(gettext("libuutil error: %s\n"),
15165 			    uu_strerror(uu_error()));
15166 
15167 		level = scf_snaplevel_create(g_hndl);
15168 		if (level == NULL)
15169 			scfdie();
15170 
15171 		if (scf_snaplevel_get_next_snaplevel(cur_elt->sl,
15172 		    level) != SCF_SUCCESS) {
15173 			if (scf_error() != SCF_ERROR_NOT_FOUND)
15174 				scfdie();
15175 
15176 			scf_snaplevel_destroy(level);
15177 			break;
15178 		}
15179 	}
15180 
15181 	cur_elt = uu_list_last(cur_levels);
15182 	cur_level = cur_elt->sl;
15183 }
15184 
15185 /*
15186  * Copies the properties & values in src to dst.  Assumes src won't change.
15187  * Returns -1 if permission is denied, -2 if another transaction interrupts,
15188  * and 0 on success.
15189  *
15190  * If enabled is 0 or 1, its value is used for the SCF_PROPERTY_ENABLED
15191  * property, if it is copied and has type boolean.  (See comment in
15192  * lscf_revert()).
15193  */
15194 static int
15195 pg_copy(const scf_propertygroup_t *src, scf_propertygroup_t *dst,
15196     uint8_t enabled)
15197 {
15198 	scf_transaction_t *tx;
15199 	scf_iter_t *iter, *viter;
15200 	scf_property_t *prop;
15201 	scf_value_t *v;
15202 	char *nbuf;
15203 	int r;
15204 
15205 	tx = scf_transaction_create(g_hndl);
15206 	if (tx == NULL)
15207 		scfdie();
15208 
15209 	if (scf_transaction_start(tx, dst) != SCF_SUCCESS) {
15210 		if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
15211 			scfdie();
15212 
15213 		scf_transaction_destroy(tx);
15214 
15215 		return (-1);
15216 	}
15217 
15218 	if ((iter = scf_iter_create(g_hndl)) == NULL ||
15219 	    (prop = scf_property_create(g_hndl)) == NULL ||
15220 	    (viter = scf_iter_create(g_hndl)) == NULL)
15221 		scfdie();
15222 
15223 	nbuf = safe_malloc(max_scf_name_len + 1);
15224 
15225 	if (scf_iter_pg_properties(iter, src) != SCF_SUCCESS)
15226 		scfdie();
15227 
15228 	for (;;) {
15229 		scf_transaction_entry_t *e;
15230 		scf_type_t ty;
15231 
15232 		r = scf_iter_next_property(iter, prop);
15233 		if (r == -1)
15234 			scfdie();
15235 		if (r == 0)
15236 			break;
15237 
15238 		e = scf_entry_create(g_hndl);
15239 		if (e == NULL)
15240 			scfdie();
15241 
15242 		if (scf_property_type(prop, &ty) != SCF_SUCCESS)
15243 			scfdie();
15244 
15245 		if (scf_property_get_name(prop, nbuf, max_scf_name_len + 1) < 0)
15246 			scfdie();
15247 
15248 		if (scf_transaction_property_new(tx, e, nbuf,
15249 		    ty) != SCF_SUCCESS)
15250 			scfdie();
15251 
15252 		if ((enabled == 0 || enabled == 1) &&
15253 		    strcmp(nbuf, scf_property_enabled) == 0 &&
15254 		    ty == SCF_TYPE_BOOLEAN) {
15255 			v = scf_value_create(g_hndl);
15256 			if (v == NULL)
15257 				scfdie();
15258 
15259 			scf_value_set_boolean(v, enabled);
15260 
15261 			if (scf_entry_add_value(e, v) != 0)
15262 				scfdie();
15263 		} else {
15264 			if (scf_iter_property_values(viter, prop) != 0)
15265 				scfdie();
15266 
15267 			for (;;) {
15268 				v = scf_value_create(g_hndl);
15269 				if (v == NULL)
15270 					scfdie();
15271 
15272 				r = scf_iter_next_value(viter, v);
15273 				if (r == -1)
15274 					scfdie();
15275 				if (r == 0) {
15276 					scf_value_destroy(v);
15277 					break;
15278 				}
15279 
15280 				if (scf_entry_add_value(e, v) != SCF_SUCCESS)
15281 					scfdie();
15282 			}
15283 		}
15284 	}
15285 
15286 	free(nbuf);
15287 	scf_iter_destroy(viter);
15288 	scf_property_destroy(prop);
15289 	scf_iter_destroy(iter);
15290 
15291 	r = scf_transaction_commit(tx);
15292 	if (r == -1 && scf_error() != SCF_ERROR_PERMISSION_DENIED)
15293 		scfdie();
15294 
15295 	scf_transaction_destroy_children(tx);
15296 	scf_transaction_destroy(tx);
15297 
15298 	switch (r) {
15299 	case 1:		return (0);
15300 	case 0:		return (-2);
15301 	case -1:	return (-1);
15302 
15303 	default:
15304 		abort();
15305 	}
15306 
15307 	/* NOTREACHED */
15308 }
15309 
15310 void
15311 lscf_revert(const char *snapname)
15312 {
15313 	scf_snapshot_t *snap, *prev;
15314 	scf_snaplevel_t *level, *nlevel;
15315 	scf_iter_t *iter;
15316 	scf_propertygroup_t *pg, *npg;
15317 	scf_property_t *prop;
15318 	scf_value_t *val;
15319 	char *nbuf, *tbuf;
15320 	uint8_t enabled;
15321 
15322 	lscf_prep_hndl();
15323 
15324 	if (cur_inst == NULL) {
15325 		semerr(gettext("Instance not selected.\n"));
15326 		return;
15327 	}
15328 
15329 	if (snapname != NULL) {
15330 		snap = scf_snapshot_create(g_hndl);
15331 		if (snap == NULL)
15332 			scfdie();
15333 
15334 		if (scf_instance_get_snapshot(cur_inst, snapname, snap) !=
15335 		    SCF_SUCCESS) {
15336 			switch (scf_error()) {
15337 			case SCF_ERROR_INVALID_ARGUMENT:
15338 				semerr(gettext("Invalid snapshot name "
15339 				    "\"%s\".\n"), snapname);
15340 				break;
15341 
15342 			case SCF_ERROR_NOT_FOUND:
15343 				semerr(gettext("No such snapshot.\n"));
15344 				break;
15345 
15346 			default:
15347 				scfdie();
15348 			}
15349 
15350 			scf_snapshot_destroy(snap);
15351 			return;
15352 		}
15353 	} else {
15354 		if (cur_snap != NULL) {
15355 			snap = cur_snap;
15356 		} else {
15357 			semerr(gettext("No snapshot selected.\n"));
15358 			return;
15359 		}
15360 	}
15361 
15362 	if ((prev = scf_snapshot_create(g_hndl)) == NULL ||
15363 	    (level = scf_snaplevel_create(g_hndl)) == NULL ||
15364 	    (iter = scf_iter_create(g_hndl)) == NULL ||
15365 	    (pg = scf_pg_create(g_hndl)) == NULL ||
15366 	    (npg = scf_pg_create(g_hndl)) == NULL ||
15367 	    (prop = scf_property_create(g_hndl)) == NULL ||
15368 	    (val = scf_value_create(g_hndl)) == NULL)
15369 		scfdie();
15370 
15371 	nbuf = safe_malloc(max_scf_name_len + 1);
15372 	tbuf = safe_malloc(max_scf_pg_type_len + 1);
15373 
15374 	/* Take the "previous" snapshot before we blow away the properties. */
15375 	if (scf_instance_get_snapshot(cur_inst, snap_previous, prev) == 0) {
15376 		if (_scf_snapshot_take_attach(cur_inst, prev) != 0)
15377 			scfdie();
15378 	} else {
15379 		if (scf_error() != SCF_ERROR_NOT_FOUND)
15380 			scfdie();
15381 
15382 		if (_scf_snapshot_take_new(cur_inst, snap_previous, prev) != 0)
15383 			scfdie();
15384 	}
15385 
15386 	/* Save general/enabled, since we're probably going to replace it. */
15387 	enabled = 2;
15388 	if (scf_instance_get_pg(cur_inst, scf_pg_general, pg) == 0 &&
15389 	    scf_pg_get_property(pg, scf_property_enabled, prop) == 0 &&
15390 	    scf_property_get_value(prop, val) == 0)
15391 		(void) scf_value_get_boolean(val, &enabled);
15392 
15393 	if (scf_snapshot_get_base_snaplevel(snap, level) != SCF_SUCCESS) {
15394 		if (scf_error() != SCF_ERROR_NOT_FOUND)
15395 			scfdie();
15396 
15397 		goto out;
15398 	}
15399 
15400 	for (;;) {
15401 		boolean_t isinst;
15402 		uint32_t flags;
15403 		int r;
15404 
15405 		/* Clear the properties from the corresponding entity. */
15406 		isinst = snaplevel_is_instance(level);
15407 
15408 		if (!isinst)
15409 			r = scf_iter_service_pgs(iter, cur_svc);
15410 		else
15411 			r = scf_iter_instance_pgs(iter, cur_inst);
15412 		if (r != SCF_SUCCESS)
15413 			scfdie();
15414 
15415 		while ((r = scf_iter_next_pg(iter, pg)) == 1) {
15416 			if (scf_pg_get_flags(pg, &flags) != SCF_SUCCESS)
15417 				scfdie();
15418 
15419 			/* Skip nonpersistent pgs. */
15420 			if (flags & SCF_PG_FLAG_NONPERSISTENT)
15421 				continue;
15422 
15423 			if (scf_pg_delete(pg) != SCF_SUCCESS) {
15424 				if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
15425 					scfdie();
15426 
15427 				semerr(emsg_permission_denied);
15428 				goto out;
15429 			}
15430 		}
15431 		if (r == -1)
15432 			scfdie();
15433 
15434 		/* Copy the properties to the corresponding entity. */
15435 		if (scf_iter_snaplevel_pgs(iter, level) != SCF_SUCCESS)
15436 			scfdie();
15437 
15438 		while ((r = scf_iter_next_pg(iter, pg)) == 1) {
15439 			if (scf_pg_get_name(pg, nbuf, max_scf_name_len + 1) < 0)
15440 				scfdie();
15441 
15442 			if (scf_pg_get_type(pg, tbuf, max_scf_pg_type_len + 1) <
15443 			    0)
15444 				scfdie();
15445 
15446 			if (scf_pg_get_flags(pg, &flags) != SCF_SUCCESS)
15447 				scfdie();
15448 
15449 			if (!isinst)
15450 				r = scf_service_add_pg(cur_svc, nbuf, tbuf,
15451 				    flags, npg);
15452 			else
15453 				r = scf_instance_add_pg(cur_inst, nbuf, tbuf,
15454 				    flags, npg);
15455 			if (r != SCF_SUCCESS) {
15456 				if (scf_error() != SCF_ERROR_PERMISSION_DENIED)
15457 					scfdie();
15458 
15459 				semerr(emsg_permission_denied);
15460 				goto out;
15461 			}
15462 
15463 			if ((enabled == 0 || enabled == 1) &&
15464 			    strcmp(nbuf, scf_pg_general) == 0)
15465 				r = pg_copy(pg, npg, enabled);
15466 			else
15467 				r = pg_copy(pg, npg, 2);
15468 
15469 			switch (r) {
15470 			case 0:
15471 				break;
15472 
15473 			case -1:
15474 				semerr(emsg_permission_denied);
15475 				goto out;
15476 
15477 			case -2:
15478 				semerr(gettext(
15479 				    "Interrupted by another change.\n"));
15480 				goto out;
15481 
15482 			default:
15483 				abort();
15484 			}
15485 		}
15486 		if (r == -1)
15487 			scfdie();
15488 
15489 		/* Get next level. */
15490 		nlevel = scf_snaplevel_create(g_hndl);
15491 		if (nlevel == NULL)
15492 			scfdie();
15493 
15494 		if (scf_snaplevel_get_next_snaplevel(level, nlevel) !=
15495 		    SCF_SUCCESS) {
15496 			if (scf_error() != SCF_ERROR_NOT_FOUND)
15497 				scfdie();
15498 
15499 			scf_snaplevel_destroy(nlevel);
15500 			break;
15501 		}
15502 
15503 		scf_snaplevel_destroy(level);
15504 		level = nlevel;
15505 	}
15506 
15507 	if (snapname == NULL) {
15508 		lscf_selectsnap(NULL);
15509 		snap = NULL;		/* cur_snap has been destroyed */
15510 	}
15511 
15512 out:
15513 	free(tbuf);
15514 	free(nbuf);
15515 	scf_value_destroy(val);
15516 	scf_property_destroy(prop);
15517 	scf_pg_destroy(npg);
15518 	scf_pg_destroy(pg);
15519 	scf_iter_destroy(iter);
15520 	scf_snaplevel_destroy(level);
15521 	scf_snapshot_destroy(prev);
15522 	if (snap != cur_snap)
15523 		scf_snapshot_destroy(snap);
15524 }
15525 
15526 void
15527 lscf_refresh(void)
15528 {
15529 	ssize_t fmrilen;
15530 	size_t bufsz;
15531 	char *fmribuf;
15532 	int r;
15533 
15534 	lscf_prep_hndl();
15535 
15536 	if (cur_inst == NULL) {
15537 		semerr(gettext("Instance not selected.\n"));
15538 		return;
15539 	}
15540 
15541 	bufsz = max_scf_fmri_len + 1;
15542 	fmribuf = safe_malloc(bufsz);
15543 	fmrilen = scf_instance_to_fmri(cur_inst, fmribuf, bufsz);
15544 	if (fmrilen < 0) {
15545 		free(fmribuf);
15546 		if (scf_error() != SCF_ERROR_DELETED)
15547 			scfdie();
15548 		scf_instance_destroy(cur_inst);
15549 		cur_inst = NULL;
15550 		warn(emsg_deleted);
15551 		return;
15552 	}
15553 	assert(fmrilen < bufsz);
15554 
15555 	r = refresh_entity(0, cur_inst, fmribuf, NULL, NULL, NULL);
15556 	switch (r) {
15557 	case 0:
15558 		break;
15559 
15560 	case ECONNABORTED:
15561 		warn(gettext("Could not refresh %s "
15562 		    "(repository connection broken).\n"), fmribuf);
15563 		break;
15564 
15565 	case ECANCELED:
15566 		warn(emsg_deleted);
15567 		break;
15568 
15569 	case EPERM:
15570 		warn(gettext("Could not refresh %s "
15571 		    "(permission denied).\n"), fmribuf);
15572 		break;
15573 
15574 	case ENOSPC:
15575 		warn(gettext("Could not refresh %s "
15576 		    "(repository server out of resources).\n"),
15577 		    fmribuf);
15578 		break;
15579 
15580 	case EACCES:
15581 	default:
15582 		bad_error("refresh_entity", scf_error());
15583 	}
15584 
15585 	free(fmribuf);
15586 }
15587 
15588 /*
15589  * describe [-v] [-t] [pg/prop]
15590  */
15591 int
15592 lscf_describe(uu_list_t *args, int hasargs)
15593 {
15594 	int ret = 0;
15595 	size_t i;
15596 	int argc;
15597 	char **argv = NULL;
15598 	string_list_t *slp;
15599 	int do_verbose = 0;
15600 	int do_templates = 0;
15601 	char *pattern = NULL;
15602 
15603 	lscf_prep_hndl();
15604 
15605 	if (hasargs != 0)  {
15606 		argc = uu_list_numnodes(args);
15607 		if (argc < 1)
15608 			goto usage;
15609 
15610 		argv = calloc(argc + 1, sizeof (char *));
15611 		if (argv == NULL)
15612 			uu_die(gettext("Out of memory.\n"));
15613 
15614 		for (slp = uu_list_first(args), i = 0;
15615 		    slp != NULL;
15616 		    slp = uu_list_next(args, slp), ++i)
15617 			argv[i] = slp->str;
15618 
15619 		argv[i] = NULL;
15620 
15621 		/*
15622 		 * We start optind = 0 because our list of arguments
15623 		 * starts at argv[0]
15624 		 */
15625 		optind = 0;
15626 		opterr = 0;
15627 		for (;;) {
15628 			ret = getopt(argc, argv, "vt");
15629 			if (ret == -1)
15630 				break;
15631 
15632 			switch (ret) {
15633 			case 'v':
15634 				do_verbose = 1;
15635 				break;
15636 
15637 			case 't':
15638 				do_templates = 1;
15639 				break;
15640 
15641 			case '?':
15642 				goto usage;
15643 
15644 			default:
15645 				bad_error("getopt", ret);
15646 			}
15647 		}
15648 
15649 		pattern = argv[optind];
15650 	}
15651 
15652 	if (cur_inst == NULL && cur_svc == NULL) {
15653 		semerr(emsg_entity_not_selected);
15654 		ret = -1;
15655 		goto out;
15656 	}
15657 
15658 	/*
15659 	 * list_entity_tmpl(), listprop() and listtmpl() produce verbose
15660 	 * output if their last parameter is set to 2.  Less information is
15661 	 * produced if the parameter is set to 1.
15662 	 */
15663 	if (pattern == NULL) {
15664 		if (do_verbose == 1)
15665 			list_entity_tmpl(2);
15666 		else
15667 			list_entity_tmpl(1);
15668 	}
15669 
15670 	if (do_templates == 0) {
15671 		if (do_verbose == 1)
15672 			listprop(pattern, 0, 2);
15673 		else
15674 			listprop(pattern, 0, 1);
15675 	} else {
15676 		if (do_verbose == 1)
15677 			listtmpl(pattern, 2);
15678 		else
15679 			listtmpl(pattern, 1);
15680 	}
15681 
15682 	ret = 0;
15683 out:
15684 	if (argv != NULL)
15685 		free(argv);
15686 	return (ret);
15687 usage:
15688 	ret = -2;
15689 	goto out;
15690 }
15691 
15692 #define	PARAM_ACTIVE	((const char *) "active")
15693 #define	PARAM_INACTIVE	((const char *) "inactive")
15694 #define	PARAM_SMTP_TO	((const char *) "to")
15695 
15696 /*
15697  * tokenize()
15698  * Breaks down the string according to the tokens passed.
15699  * Caller is responsible for freeing array of pointers returned.
15700  * Returns NULL on failure
15701  */
15702 char **
15703 tokenize(char *str, const char *sep)
15704 {
15705 	char *token, *lasts;
15706 	char **buf;
15707 	int n = 0;	/* number of elements */
15708 	int size = 8;	/* size of the array (initial) */
15709 
15710 	buf = safe_malloc(size * sizeof (char *));
15711 
15712 	for (token = strtok_r(str, sep, &lasts); token != NULL;
15713 	    token = strtok_r(NULL, sep, &lasts), ++n) {
15714 		if (n + 1 >= size) {
15715 			size *= 2;
15716 			if ((buf = realloc(buf, size * sizeof (char *))) ==
15717 			    NULL) {
15718 				uu_die(gettext("Out of memory"));
15719 			}
15720 		}
15721 		buf[n] = token;
15722 	}
15723 	/* NULL terminate the pointer array */
15724 	buf[n] = NULL;
15725 
15726 	return (buf);
15727 }
15728 
15729 int32_t
15730 check_tokens(char **p)
15731 {
15732 	int32_t smf = 0;
15733 	int32_t fma = 0;
15734 
15735 	while (*p) {
15736 		int32_t t = string_to_tset(*p);
15737 
15738 		if (t == 0) {
15739 			if (is_fma_token(*p) == 0)
15740 				return (INVALID_TOKENS);
15741 			fma = 1; /* this token is an fma event */
15742 		} else {
15743 			smf |= t;
15744 		}
15745 
15746 		if (smf != 0 && fma == 1)
15747 			return (MIXED_TOKENS);
15748 		++p;
15749 	}
15750 
15751 	if (smf > 0)
15752 		return (smf);
15753 	else if (fma == 1)
15754 		return (FMA_TOKENS);
15755 
15756 	return (INVALID_TOKENS);
15757 }
15758 
15759 static int
15760 get_selection_str(char *fmri, size_t sz)
15761 {
15762 	if (g_hndl == NULL) {
15763 		semerr(emsg_entity_not_selected);
15764 		return (-1);
15765 	} else if (cur_level != NULL) {
15766 		semerr(emsg_invalid_for_snapshot);
15767 		return (-1);
15768 	} else {
15769 		lscf_get_selection_str(fmri, sz);
15770 	}
15771 
15772 	return (0);
15773 }
15774 
15775 void
15776 lscf_delnotify(const char *set, int global)
15777 {
15778 	char *str = strdup(set);
15779 	char **pgs;
15780 	char **p;
15781 	int32_t tset;
15782 	char *fmri = NULL;
15783 
15784 	if (str == NULL)
15785 		uu_die(gettext("Out of memory.\n"));
15786 
15787 	pgs = tokenize(str, ",");
15788 
15789 	if ((tset = check_tokens(pgs)) > 0) {
15790 		size_t sz = max_scf_fmri_len + 1;
15791 
15792 		fmri = safe_malloc(sz);
15793 		if (global) {
15794 			(void) strlcpy(fmri, SCF_INSTANCE_GLOBAL, sz);
15795 		} else if (get_selection_str(fmri, sz) != 0) {
15796 			goto out;
15797 		}
15798 
15799 		if (smf_notify_del_params(SCF_SVC_TRANSITION_CLASS, fmri,
15800 		    tset) != SCF_SUCCESS) {
15801 			uu_warn(gettext("Failed smf_notify_del_params: %s\n"),
15802 			    scf_strerror(scf_error()));
15803 		}
15804 	} else if (tset == FMA_TOKENS) {
15805 		if (global) {
15806 			semerr(gettext("Can't use option '-g' with FMA event "
15807 			    "definitions\n"));
15808 			goto out;
15809 		}
15810 
15811 		for (p = pgs; *p; ++p) {
15812 			if (smf_notify_del_params(de_tag(*p), NULL, 0) !=
15813 			    SCF_SUCCESS) {
15814 				uu_warn(gettext("Failed for \"%s\": %s\n"), *p,
15815 				    scf_strerror(scf_error()));
15816 				goto out;
15817 			}
15818 		}
15819 	} else if (tset == MIXED_TOKENS) {
15820 		semerr(gettext("Can't mix SMF and FMA event definitions\n"));
15821 		goto out;
15822 	} else {
15823 		uu_die(gettext("Invalid input.\n"));
15824 	}
15825 
15826 out:
15827 	free(fmri);
15828 	free(pgs);
15829 	free(str);
15830 }
15831 
15832 void
15833 lscf_listnotify(const char *set, int global)
15834 {
15835 	char *str = safe_strdup(set);
15836 	char **pgs;
15837 	char **p;
15838 	int32_t tset;
15839 	nvlist_t *nvl;
15840 	char *fmri = NULL;
15841 
15842 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
15843 		uu_die(gettext("Out of memory.\n"));
15844 
15845 	pgs = tokenize(str, ",");
15846 
15847 	if ((tset = check_tokens(pgs)) > 0) {
15848 		size_t sz = max_scf_fmri_len + 1;
15849 
15850 		fmri = safe_malloc(sz);
15851 		if (global) {
15852 			(void) strlcpy(fmri, SCF_INSTANCE_GLOBAL, sz);
15853 		} else if (get_selection_str(fmri, sz) != 0) {
15854 			goto out;
15855 		}
15856 
15857 		if (_scf_get_svc_notify_params(fmri, nvl, tset, 1, 1) !=
15858 		    SCF_SUCCESS) {
15859 			if (scf_error() != SCF_ERROR_NOT_FOUND &&
15860 			    scf_error() != SCF_ERROR_DELETED)
15861 				uu_warn(gettext(
15862 				    "Failed listnotify: %s\n"),
15863 				    scf_strerror(scf_error()));
15864 			goto out;
15865 		}
15866 
15867 		listnotify_print(nvl, NULL);
15868 	} else if (tset == FMA_TOKENS) {
15869 		if (global) {
15870 			semerr(gettext("Can't use option '-g' with FMA event "
15871 			    "definitions\n"));
15872 			goto out;
15873 		}
15874 
15875 		for (p = pgs; *p; ++p) {
15876 			if (_scf_get_fma_notify_params(de_tag(*p), nvl, 1) !=
15877 			    SCF_SUCCESS) {
15878 				/*
15879 				 * if the preferences have just been deleted
15880 				 * or does not exist, just skip.
15881 				 */
15882 				if (scf_error() == SCF_ERROR_NOT_FOUND ||
15883 				    scf_error() == SCF_ERROR_DELETED)
15884 					continue;
15885 				uu_warn(gettext(
15886 				    "Failed listnotify: %s\n"),
15887 				    scf_strerror(scf_error()));
15888 				goto out;
15889 			}
15890 			listnotify_print(nvl, re_tag(*p));
15891 		}
15892 	} else if (tset == MIXED_TOKENS) {
15893 		semerr(gettext("Can't mix SMF and FMA event definitions\n"));
15894 		goto out;
15895 	} else {
15896 		semerr(gettext("Invalid input.\n"));
15897 	}
15898 
15899 out:
15900 	nvlist_free(nvl);
15901 	free(fmri);
15902 	free(pgs);
15903 	free(str);
15904 }
15905 
15906 static char *
15907 strip_quotes_and_blanks(char *s)
15908 {
15909 	char *start = s;
15910 	char *end = strrchr(s, '\"');
15911 
15912 	if (s[0] == '\"' && end != NULL && *(end + 1) == '\0') {
15913 		start = s + 1;
15914 		while (isblank(*start))
15915 			start++;
15916 		while (isblank(*(end - 1)) && end > start) {
15917 			end--;
15918 		}
15919 		*end = '\0';
15920 	}
15921 
15922 	return (start);
15923 }
15924 
15925 static int
15926 set_active(nvlist_t *mech, const char *hier_part)
15927 {
15928 	boolean_t b;
15929 
15930 	if (*hier_part == '\0' || strcmp(hier_part, PARAM_ACTIVE) == 0) {
15931 		b = B_TRUE;
15932 	} else if (strcmp(hier_part, PARAM_INACTIVE) == 0) {
15933 		b = B_FALSE;
15934 	} else {
15935 		return (-1);
15936 	}
15937 
15938 	if (nvlist_add_boolean_value(mech, PARAM_ACTIVE, b) != 0)
15939 		uu_die(gettext("Out of memory.\n"));
15940 
15941 	return (0);
15942 }
15943 
15944 static int
15945 add_snmp_params(nvlist_t *mech, char *hier_part)
15946 {
15947 	return (set_active(mech, hier_part));
15948 }
15949 
15950 static int
15951 add_syslog_params(nvlist_t *mech, char *hier_part)
15952 {
15953 	return (set_active(mech, hier_part));
15954 }
15955 
15956 /*
15957  * add_mailto_paramas()
15958  * parse the hier_part of mailto URI
15959  * mailto:<addr>[?<header1>=<value1>[&<header2>=<value2>]]
15960  * or mailto:{[active]|inactive}
15961  */
15962 static int
15963 add_mailto_params(nvlist_t *mech, char *hier_part)
15964 {
15965 	const char *tok = "?&";
15966 	char *p;
15967 	char *lasts;
15968 	char *param;
15969 	char *val;
15970 
15971 	/*
15972 	 * If the notification parametes are in the form of
15973 	 *
15974 	 *   malito:{[active]|inactive}
15975 	 *
15976 	 * we set the property accordingly and return.
15977 	 * Otherwise, we make the notification type active and
15978 	 * process the hier_part.
15979 	 */
15980 	if (set_active(mech, hier_part) == 0)
15981 		return (0);
15982 	else if (set_active(mech, PARAM_ACTIVE) != 0)
15983 		return (-1);
15984 
15985 	if ((p = strtok_r(hier_part, tok, &lasts)) == NULL) {
15986 		/*
15987 		 * sanity check: we only get here if hier_part = "", but
15988 		 * that's handled by set_active
15989 		 */
15990 		uu_die("strtok_r");
15991 	}
15992 
15993 	if (nvlist_add_string(mech, PARAM_SMTP_TO, p) != 0)
15994 		uu_die(gettext("Out of memory.\n"));
15995 
15996 	while ((p = strtok_r(NULL, tok, &lasts)) != NULL)
15997 		if ((param = strtok_r(p, "=", &val)) != NULL)
15998 			if (nvlist_add_string(mech, param, val) != 0)
15999 				uu_die(gettext("Out of memory.\n"));
16000 
16001 	return (0);
16002 }
16003 
16004 static int
16005 uri_split(char *uri, char **scheme, char **hier_part)
16006 {
16007 	int r = -1;
16008 
16009 	if ((*scheme = strtok_r(uri, ":", hier_part)) == NULL ||
16010 	    *hier_part == NULL) {
16011 		semerr(gettext("'%s' is not an URI\n"), uri);
16012 		return (r);
16013 	}
16014 
16015 	if ((r = check_uri_scheme(*scheme)) < 0) {
16016 		semerr(gettext("Unkown URI scheme: %s\n"), *scheme);
16017 		return (r);
16018 	}
16019 
16020 	return (r);
16021 }
16022 
16023 static int
16024 process_uri(nvlist_t *params, char *uri)
16025 {
16026 	char *scheme;
16027 	char *hier_part;
16028 	nvlist_t *mech;
16029 	int index;
16030 	int r;
16031 
16032 	if ((index = uri_split(uri, &scheme, &hier_part)) < 0)
16033 		return (-1);
16034 
16035 	if (nvlist_alloc(&mech, NV_UNIQUE_NAME, 0) != 0)
16036 		uu_die(gettext("Out of memory.\n"));
16037 
16038 	switch (index) {
16039 	case 0:
16040 		/* error messages displayed by called function */
16041 		r = add_mailto_params(mech, hier_part);
16042 		break;
16043 
16044 	case 1:
16045 		if ((r = add_snmp_params(mech, hier_part)) != 0)
16046 			semerr(gettext("Not valid parameters: '%s'\n"),
16047 			    hier_part);
16048 		break;
16049 
16050 	case 2:
16051 		if ((r = add_syslog_params(mech, hier_part)) != 0)
16052 			semerr(gettext("Not valid parameters: '%s'\n"),
16053 			    hier_part);
16054 		break;
16055 
16056 	default:
16057 		r = -1;
16058 	}
16059 
16060 	if (r == 0 && nvlist_add_nvlist(params, uri_scheme[index].protocol,
16061 	    mech) != 0)
16062 		uu_die(gettext("Out of memory.\n"));
16063 
16064 	nvlist_free(mech);
16065 	return (r);
16066 }
16067 
16068 static int
16069 set_params(nvlist_t *params, char **p)
16070 {
16071 	char *uri;
16072 
16073 	if (p == NULL)
16074 		/* sanity check */
16075 		uu_die("set_params");
16076 
16077 	while (*p) {
16078 		uri = strip_quotes_and_blanks(*p);
16079 		if (process_uri(params, uri) != 0)
16080 			return (-1);
16081 
16082 		++p;
16083 	}
16084 
16085 	return (0);
16086 }
16087 
16088 static int
16089 setnotify(const char *e, char **p, int global)
16090 {
16091 	char *str = safe_strdup(e);
16092 	char **events;
16093 	int32_t tset;
16094 	int r = -1;
16095 	nvlist_t *nvl, *params;
16096 	char *fmri = NULL;
16097 
16098 	if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
16099 	    nvlist_alloc(&params, NV_UNIQUE_NAME, 0) != 0 ||
16100 	    nvlist_add_uint32(nvl, SCF_NOTIFY_NAME_VERSION,
16101 	    SCF_NOTIFY_PARAMS_VERSION) != 0)
16102 		uu_die(gettext("Out of memory.\n"));
16103 
16104 	events = tokenize(str, ",");
16105 
16106 	if ((tset = check_tokens(events)) > 0) {
16107 		/* SMF state transitions parameters */
16108 		size_t sz = max_scf_fmri_len + 1;
16109 
16110 		fmri = safe_malloc(sz);
16111 		if (global) {
16112 			(void) strlcpy(fmri, SCF_INSTANCE_GLOBAL, sz);
16113 		} else if (get_selection_str(fmri, sz) != 0) {
16114 			goto out;
16115 		}
16116 
16117 		if (nvlist_add_string(nvl, SCF_NOTIFY_NAME_FMRI, fmri) != 0 ||
16118 		    nvlist_add_int32(nvl, SCF_NOTIFY_NAME_TSET, tset) != 0)
16119 			uu_die(gettext("Out of memory.\n"));
16120 
16121 		if ((r = set_params(params, p)) == 0) {
16122 			if (nvlist_add_nvlist(nvl, SCF_NOTIFY_PARAMS,
16123 			    params) != 0)
16124 				uu_die(gettext("Out of memory.\n"));
16125 
16126 			if (smf_notify_set_params(SCF_SVC_TRANSITION_CLASS,
16127 			    nvl) != SCF_SUCCESS) {
16128 				r = -1;
16129 				uu_warn(gettext(
16130 				    "Failed smf_notify_set_params(3SCF): %s\n"),
16131 				    scf_strerror(scf_error()));
16132 			}
16133 		}
16134 	} else if (tset == FMA_TOKENS) {
16135 		/* FMA event parameters */
16136 		if (global) {
16137 			semerr(gettext("Can't use option '-g' with FMA event "
16138 			    "definitions\n"));
16139 			goto out;
16140 		}
16141 
16142 		if ((r = set_params(params, p)) != 0)
16143 			goto out;
16144 
16145 		if (nvlist_add_nvlist(nvl, SCF_NOTIFY_PARAMS, params) != 0)
16146 			uu_die(gettext("Out of memory.\n"));
16147 
16148 		while (*events) {
16149 			if (smf_notify_set_params(de_tag(*events), nvl) !=
16150 			    SCF_SUCCESS)
16151 				uu_warn(gettext(
16152 				    "Failed smf_notify_set_params(3SCF) for "
16153 				    "event %s: %s\n"), *events,
16154 				    scf_strerror(scf_error()));
16155 			events++;
16156 		}
16157 	} else if (tset == MIXED_TOKENS) {
16158 		semerr(gettext("Can't mix SMF and FMA event definitions\n"));
16159 	} else {
16160 		/* Sanity check */
16161 		uu_die(gettext("Invalid input.\n"));
16162 	}
16163 
16164 out:
16165 	nvlist_free(nvl);
16166 	nvlist_free(params);
16167 	free(fmri);
16168 	free(str);
16169 
16170 	return (r);
16171 }
16172 
16173 int
16174 lscf_setnotify(uu_list_t *args)
16175 {
16176 	int argc;
16177 	char **argv = NULL;
16178 	string_list_t *slp;
16179 	int global;
16180 	char *events;
16181 	char **p;
16182 	int i;
16183 	int ret;
16184 
16185 	if ((argc = uu_list_numnodes(args)) < 2)
16186 		goto usage;
16187 
16188 	argv = calloc(argc + 1, sizeof (char *));
16189 	if (argv == NULL)
16190 		uu_die(gettext("Out of memory.\n"));
16191 
16192 	for (slp = uu_list_first(args), i = 0;
16193 	    slp != NULL;
16194 	    slp = uu_list_next(args, slp), ++i)
16195 		argv[i] = slp->str;
16196 
16197 	argv[i] = NULL;
16198 
16199 	if (strcmp(argv[0], "-g") == 0) {
16200 		global = 1;
16201 		events = argv[1];
16202 		p = argv + 2;
16203 	} else {
16204 		global = 0;
16205 		events = argv[0];
16206 		p = argv + 1;
16207 	}
16208 
16209 	ret = setnotify(events, p, global);
16210 
16211 out:
16212 	free(argv);
16213 	return (ret);
16214 
16215 usage:
16216 	ret = -2;
16217 	goto out;
16218 }
16219 
16220 /*
16221  * Creates a list of instance name strings associated with a service. If
16222  * wohandcrafted flag is set, get only instances that have a last-import
16223  * snapshot, instances that were imported via svccfg.
16224  */
16225 static uu_list_t *
16226 create_instance_list(scf_service_t *svc, int wohandcrafted)
16227 {
16228 	scf_snapshot_t  *snap = NULL;
16229 	scf_instance_t  *inst;
16230 	scf_iter_t	*inst_iter;
16231 	uu_list_t	*instances;
16232 	char		*instname;
16233 	int		r;
16234 
16235 	inst_iter = scf_iter_create(g_hndl);
16236 	inst = scf_instance_create(g_hndl);
16237 	if (inst_iter == NULL || inst == NULL) {
16238 		uu_warn(gettext("Could not create instance or iterator\n"));
16239 		scfdie();
16240 	}
16241 
16242 	if ((instances = uu_list_create(string_pool, NULL, 0)) == NULL)
16243 		return (instances);
16244 
16245 	if (scf_iter_service_instances(inst_iter, svc) != 0) {
16246 		switch (scf_error()) {
16247 		case SCF_ERROR_CONNECTION_BROKEN:
16248 		case SCF_ERROR_DELETED:
16249 			uu_list_destroy(instances);
16250 			instances = NULL;
16251 			goto out;
16252 
16253 		case SCF_ERROR_HANDLE_MISMATCH:
16254 		case SCF_ERROR_NOT_BOUND:
16255 		case SCF_ERROR_NOT_SET:
16256 		default:
16257 			bad_error("scf_iter_service_instances", scf_error());
16258 		}
16259 	}
16260 
16261 	instname = safe_malloc(max_scf_name_len + 1);
16262 	while ((r = scf_iter_next_instance(inst_iter, inst)) != 0) {
16263 		if (r == -1) {
16264 			(void) uu_warn(gettext("Unable to iterate through "
16265 			    "instances to create instance list : %s\n"),
16266 			    scf_strerror(scf_error()));
16267 
16268 			uu_list_destroy(instances);
16269 			instances = NULL;
16270 			goto out;
16271 		}
16272 
16273 		/*
16274 		 * If the instance does not have a last-import snapshot
16275 		 * then do not add it to the list as it is a hand-crafted
16276 		 * instance that should not be managed.
16277 		 */
16278 		if (wohandcrafted) {
16279 			if (snap == NULL &&
16280 			    (snap = scf_snapshot_create(g_hndl)) == NULL) {
16281 				uu_warn(gettext("Unable to create snapshot "
16282 				    "entity\n"));
16283 				scfdie();
16284 			}
16285 
16286 			if (scf_instance_get_snapshot(inst,
16287 			    snap_lastimport, snap) != 0) {
16288 				switch (scf_error()) {
16289 				case SCF_ERROR_NOT_FOUND :
16290 				case SCF_ERROR_DELETED:
16291 					continue;
16292 
16293 				case SCF_ERROR_CONNECTION_BROKEN:
16294 					uu_list_destroy(instances);
16295 					instances = NULL;
16296 					goto out;
16297 
16298 				case SCF_ERROR_HANDLE_MISMATCH:
16299 				case SCF_ERROR_NOT_BOUND:
16300 				case SCF_ERROR_NOT_SET:
16301 				default:
16302 					bad_error("scf_iter_service_instances",
16303 					    scf_error());
16304 				}
16305 			}
16306 		}
16307 
16308 		if (scf_instance_get_name(inst, instname,
16309 		    max_scf_name_len + 1) < 0) {
16310 			switch (scf_error()) {
16311 			case SCF_ERROR_NOT_FOUND :
16312 				continue;
16313 
16314 			case SCF_ERROR_CONNECTION_BROKEN:
16315 			case SCF_ERROR_DELETED:
16316 				uu_list_destroy(instances);
16317 				instances = NULL;
16318 				goto out;
16319 
16320 			case SCF_ERROR_HANDLE_MISMATCH:
16321 			case SCF_ERROR_NOT_BOUND:
16322 			case SCF_ERROR_NOT_SET:
16323 			default:
16324 				bad_error("scf_iter_service_instances",
16325 				    scf_error());
16326 			}
16327 		}
16328 
16329 		add_string(instances, instname);
16330 	}
16331 
16332 out:
16333 	if (snap)
16334 		scf_snapshot_destroy(snap);
16335 
16336 	scf_instance_destroy(inst);
16337 	scf_iter_destroy(inst_iter);
16338 	free(instname);
16339 	return (instances);
16340 }
16341 
16342 /*
16343  * disable an instance but wait for the instance to
16344  * move out of the running state.
16345  *
16346  * Returns 0 : if the instance did not disable
16347  * Returns non-zero : if the instance disabled.
16348  *
16349  */
16350 static int
16351 disable_instance(scf_instance_t *instance)
16352 {
16353 	char	*fmribuf;
16354 	int	enabled = 10000;
16355 
16356 	if (inst_is_running(instance)) {
16357 		fmribuf = safe_malloc(max_scf_name_len + 1);
16358 		if (scf_instance_to_fmri(instance, fmribuf,
16359 		    max_scf_name_len + 1) < 0) {
16360 			free(fmribuf);
16361 			return (0);
16362 		}
16363 
16364 		/*
16365 		 * If the instance cannot be disabled then return
16366 		 * failure to disable and let the caller decide
16367 		 * if that is of importance.
16368 		 */
16369 		if (smf_disable_instance(fmribuf, 0) != 0) {
16370 			free(fmribuf);
16371 			return (0);
16372 		}
16373 
16374 		while (enabled) {
16375 			if (!inst_is_running(instance))
16376 				break;
16377 
16378 			(void) poll(NULL, 0, 5);
16379 			enabled = enabled - 5;
16380 		}
16381 
16382 		free(fmribuf);
16383 	}
16384 
16385 	return (enabled);
16386 }
16387 
16388 /*
16389  * Function to compare two service_manifest structures.
16390  */
16391 /* ARGSUSED2 */
16392 static int
16393 service_manifest_compare(const void *left, const void *right, void *unused)
16394 {
16395 	service_manifest_t *l = (service_manifest_t *)left;
16396 	service_manifest_t *r = (service_manifest_t *)right;
16397 	int rc;
16398 
16399 	rc = strcmp(l->servicename, r->servicename);
16400 
16401 	return (rc);
16402 }
16403 
16404 /*
16405  * Look for the provided service in the service to manifest
16406  * tree.  If the service exists, and a manifest was provided
16407  * then add the manifest to that service.  If the service
16408  * does not exist, then add the service and manifest to the
16409  * list.
16410  *
16411  * If the manifest is NULL, return the element if found.  If
16412  * the service is not found return NULL.
16413  */
16414 service_manifest_t *
16415 find_add_svc_mfst(const char *svnbuf, const char *mfst)
16416 {
16417 	service_manifest_t	elem;
16418 	service_manifest_t	*fnelem;
16419 	uu_avl_index_t		marker;
16420 
16421 	elem.servicename = svnbuf;
16422 	fnelem = uu_avl_find(service_manifest_tree, &elem, NULL, &marker);
16423 
16424 	if (mfst) {
16425 		if (fnelem) {
16426 			add_string(fnelem->mfstlist, strdup(mfst));
16427 		} else {
16428 			fnelem = safe_malloc(sizeof (*fnelem));
16429 			fnelem->servicename = safe_strdup(svnbuf);
16430 			if ((fnelem->mfstlist =
16431 			    uu_list_create(string_pool, NULL, 0)) == NULL)
16432 				uu_die(gettext("Could not create property "
16433 				    "list: %s\n"), uu_strerror(uu_error()));
16434 
16435 			add_string(fnelem->mfstlist, safe_strdup(mfst));
16436 
16437 			uu_avl_insert(service_manifest_tree, fnelem, marker);
16438 		}
16439 	}
16440 
16441 	return (fnelem);
16442 }
16443 
16444 /*
16445  * Create the service to manifest avl tree.
16446  *
16447  * Walk each of the manifests currently installed in the supported
16448  * directories, /lib/svc/manifests and /var/svc/manifests.  For
16449  * each of the manifests, inventory the services and add them to
16450  * the tree.
16451  *
16452  * Code that calls this function should make sure fileystem/minimal is online,
16453  * /var is available, since this function walks the /var/svc/manifest directory.
16454  */
16455 static void
16456 create_manifest_tree(void)
16457 {
16458 	manifest_info_t **entry;
16459 	manifest_info_t **manifests;
16460 	uu_list_walk_t	*svcs;
16461 	bundle_t	*b;
16462 	entity_t	*mfsvc;
16463 	char		*dirs[] = {LIBSVC_DIR, VARSVC_DIR, NULL};
16464 	int		c, status;
16465 
16466 	if (service_manifest_pool)
16467 		return;
16468 
16469 	/*
16470 	 * Create the list pool for the service manifest list
16471 	 */
16472 	service_manifest_pool = uu_avl_pool_create("service_manifest",
16473 	    sizeof (service_manifest_t),
16474 	    offsetof(service_manifest_t, svcmfst_node),
16475 	    service_manifest_compare, UU_DEFAULT);
16476 	if (service_manifest_pool == NULL)
16477 		uu_die(gettext("service_manifest pool creation failed: %s\n"),
16478 		    uu_strerror(uu_error()));
16479 
16480 	/*
16481 	 * Create the list
16482 	 */
16483 	service_manifest_tree = uu_avl_create(service_manifest_pool, NULL,
16484 	    UU_DEFAULT);
16485 	if (service_manifest_tree == NULL)
16486 		uu_die(gettext("service_manifest tree creation failed: %s\n"),
16487 		    uu_strerror(uu_error()));
16488 
16489 	/*
16490 	 * Walk the manifests adding the service(s) from each manifest.
16491 	 *
16492 	 * If a service already exists add the manifest to the manifest
16493 	 * list for that service.  This covers the case of a service that
16494 	 * is supported by multiple manifest files.
16495 	 */
16496 	for (c = 0; dirs[c]; c++) {
16497 		status = find_manifests(g_hndl, dirs[c], &manifests, CHECKEXT);
16498 		if (status < 0) {
16499 			uu_warn(gettext("file tree walk of %s encountered "
16500 			    "error %s\n"), dirs[c], strerror(errno));
16501 
16502 			uu_avl_destroy(service_manifest_tree);
16503 			service_manifest_tree = NULL;
16504 			return;
16505 		}
16506 
16507 		/*
16508 		 * If a manifest that was in the list is not found
16509 		 * then skip and go to the next manifest file.
16510 		 */
16511 		if (manifests != NULL) {
16512 			for (entry = manifests; *entry != NULL; entry++) {
16513 				b = internal_bundle_new();
16514 				if (lxml_get_bundle_file(b, (*entry)->mi_path,
16515 				    SVCCFG_OP_IMPORT) != 0) {
16516 					internal_bundle_free(b);
16517 					continue;
16518 				}
16519 
16520 				svcs = uu_list_walk_start(b->sc_bundle_services,
16521 				    0);
16522 				if (svcs == NULL) {
16523 					internal_bundle_free(b);
16524 					continue;
16525 				}
16526 
16527 				while ((mfsvc = uu_list_walk_next(svcs)) !=
16528 				    NULL) {
16529 					/* Add manifest to service */
16530 					(void) find_add_svc_mfst(mfsvc->sc_name,
16531 					    (*entry)->mi_path);
16532 				}
16533 
16534 				uu_list_walk_end(svcs);
16535 				internal_bundle_free(b);
16536 			}
16537 
16538 			free_manifest_array(manifests);
16539 		}
16540 	}
16541 }
16542 
16543 /*
16544  * Check the manifest history file to see
16545  * if the service was ever installed from
16546  * one of the supported directories.
16547  *
16548  * Return Values :
16549  * 	-1 - if there's error reading manifest history file
16550  *	 1 - if the service is not found
16551  *	 0 - if the service is found
16552  */
16553 static int
16554 check_mfst_history(const char *svcname)
16555 {
16556 	struct stat	st;
16557 	caddr_t		mfsthist_start;
16558 	char		*svnbuf;
16559 	int		fd;
16560 	int		r = 1;
16561 
16562 	fd = open(MFSTHISTFILE, O_RDONLY);
16563 	if (fd == -1) {
16564 		uu_warn(gettext("Unable to open the history file\n"));
16565 		return (-1);
16566 	}
16567 
16568 	if (fstat(fd, &st) == -1) {
16569 		uu_warn(gettext("Unable to stat the history file\n"));
16570 		return (-1);
16571 	}
16572 
16573 	mfsthist_start = mmap(0, st.st_size, PROT_READ,
16574 	    MAP_PRIVATE, fd, 0);
16575 
16576 	(void) close(fd);
16577 	if (mfsthist_start == MAP_FAILED ||
16578 	    *(mfsthist_start + st.st_size) != '\0') {
16579 		(void) munmap(mfsthist_start, st.st_size);
16580 		return (-1);
16581 	}
16582 
16583 	/*
16584 	 * The manifest history file is a space delimited list
16585 	 * of service and instance to manifest linkage.  Adding
16586 	 * a space to the end of the service name so to get only
16587 	 * the service that is being searched for.
16588 	 */
16589 	svnbuf = uu_msprintf("%s ", svcname);
16590 	if (svnbuf == NULL)
16591 		uu_die(gettext("Out of memory"));
16592 
16593 	if (strstr(mfsthist_start, svnbuf) != NULL)
16594 		r = 0;
16595 
16596 	(void) munmap(mfsthist_start, st.st_size);
16597 	uu_free(svnbuf);
16598 	return (r);
16599 }
16600 
16601 /*
16602  * Take down each of the instances in the service
16603  * and remove them, then delete the service.
16604  */
16605 static void
16606 teardown_service(scf_service_t *svc, const char *svnbuf)
16607 {
16608 	scf_instance_t	*instance;
16609 	scf_iter_t	*iter;
16610 	int		r;
16611 
16612 	safe_printf(gettext("Delete service %s as there are no "
16613 	    "supporting manifests\n"), svnbuf);
16614 
16615 	instance = scf_instance_create(g_hndl);
16616 	iter = scf_iter_create(g_hndl);
16617 	if (iter == NULL || instance == NULL) {
16618 		uu_warn(gettext("Unable to create supporting entities to "
16619 		    "teardown the service\n"));
16620 		uu_warn(gettext("scf error is : %s\n"),
16621 		    scf_strerror(scf_error()));
16622 		scfdie();
16623 	}
16624 
16625 	if (scf_iter_service_instances(iter, svc) != 0) {
16626 		switch (scf_error()) {
16627 		case SCF_ERROR_CONNECTION_BROKEN:
16628 		case SCF_ERROR_DELETED:
16629 			goto out;
16630 
16631 		case SCF_ERROR_HANDLE_MISMATCH:
16632 		case SCF_ERROR_NOT_BOUND:
16633 		case SCF_ERROR_NOT_SET:
16634 		default:
16635 			bad_error("scf_iter_service_instances",
16636 			    scf_error());
16637 		}
16638 	}
16639 
16640 	while ((r = scf_iter_next_instance(iter, instance)) != 0) {
16641 		if (r == -1) {
16642 			uu_warn(gettext("Error - %s\n"),
16643 			    scf_strerror(scf_error()));
16644 			goto out;
16645 		}
16646 
16647 		(void) disable_instance(instance);
16648 	}
16649 
16650 	/*
16651 	 * Delete the service... forcing the deletion in case
16652 	 * any of the instances did not disable.
16653 	 */
16654 	(void) lscf_service_delete(svc, 1);
16655 out:
16656 	scf_instance_destroy(instance);
16657 	scf_iter_destroy(iter);
16658 }
16659 
16660 /*
16661  * Get the list of instances supported by the manifest
16662  * file.
16663  *
16664  * Return 0 if there are no instances.
16665  *
16666  * Return -1 if there are errors attempting to collect instances.
16667  *
16668  * Return the count of instances found if there are no errors.
16669  *
16670  */
16671 static int
16672 check_instance_support(char *mfstfile, const char *svcname,
16673     uu_list_t *instances)
16674 {
16675 	uu_list_walk_t	*svcs, *insts;
16676 	uu_list_t	*ilist;
16677 	bundle_t	*b;
16678 	entity_t	*mfsvc, *mfinst;
16679 	const char	*svcn;
16680 	int		rminstcnt = 0;
16681 
16682 
16683 	b = internal_bundle_new();
16684 
16685 	if (lxml_get_bundle_file(b, mfstfile, SVCCFG_OP_IMPORT) != 0) {
16686 		/*
16687 		 * Unable to process the manifest file for
16688 		 * instance support, so just return as
16689 		 * don't want to remove instances that could
16690 		 * not be accounted for that might exist here.
16691 		 */
16692 		internal_bundle_free(b);
16693 		return (0);
16694 	}
16695 
16696 	svcs = uu_list_walk_start(b->sc_bundle_services, 0);
16697 	if (svcs == NULL) {
16698 		internal_bundle_free(b);
16699 		return (0);
16700 	}
16701 
16702 	svcn = svcname + (sizeof (SCF_FMRI_SVC_PREFIX) - 1) +
16703 	    (sizeof (SCF_FMRI_SERVICE_PREFIX) - 1);
16704 
16705 	while ((mfsvc = uu_list_walk_next(svcs)) != NULL) {
16706 		if (strcmp(mfsvc->sc_name, svcn) == 0)
16707 			break;
16708 	}
16709 	uu_list_walk_end(svcs);
16710 
16711 	if (mfsvc == NULL) {
16712 		internal_bundle_free(b);
16713 		return (-1);
16714 	}
16715 
16716 	ilist = mfsvc->sc_u.sc_service.sc_service_instances;
16717 	if ((insts = uu_list_walk_start(ilist, 0)) == NULL) {
16718 		internal_bundle_free(b);
16719 		return (0);
16720 	}
16721 
16722 	while ((mfinst = uu_list_walk_next(insts)) != NULL) {
16723 		/*
16724 		 * Remove the instance from the instances list.
16725 		 * The unaccounted for instances will be removed
16726 		 * from the service once all manifests are
16727 		 * processed.
16728 		 */
16729 		(void) remove_string(instances,
16730 		    mfinst->sc_name);
16731 		rminstcnt++;
16732 	}
16733 
16734 	uu_list_walk_end(insts);
16735 	internal_bundle_free(b);
16736 
16737 	return (rminstcnt);
16738 }
16739 
16740 /*
16741  * For the given service, set its SCF_PG_MANIFESTFILES/SUPPORT property to
16742  * 'false' to indicate there's no manifest file(s) found for the service.
16743  */
16744 static void
16745 svc_add_no_support(scf_service_t *svc)
16746 {
16747 	char	*pname;
16748 
16749 	/* Add no support */
16750 	cur_svc = svc;
16751 	if (addpg(SCF_PG_MANIFESTFILES, SCF_GROUP_FRAMEWORK))
16752 		return;
16753 
16754 	pname = uu_msprintf("%s/%s", SCF_PG_MANIFESTFILES, SUPPORTPROP);
16755 	if (pname == NULL)
16756 		uu_die(gettext("Out of memory.\n"));
16757 
16758 	(void) lscf_addpropvalue(pname, "boolean:", "0");
16759 
16760 	uu_free(pname);
16761 	cur_svc = NULL;
16762 }
16763 
16764 /*
16765  * This function handles all upgrade scenarios for a service that doesn't have
16766  * SCF_PG_MANIFESTFILES pg. The function creates and populates
16767  * SCF_PG_MANIFESTFILES pg for the given service to keep track of service to
16768  * manifest(s) mapping. Manifests under supported directories are inventoried
16769  * and a property is added for each file that delivers configuration to the
16770  * service.  A service that has no corresponding manifest files (deleted) are
16771  * removed from repository.
16772  *
16773  * Unsupported services:
16774  *
16775  * A service is considered unsupported if there is no corresponding manifest
16776  * in the supported directories for that service and the service isn't in the
16777  * history file list.  The history file, MFSTHISTFILE, contains a list of all
16778  * services and instances that were delivered by Solaris before the introduction
16779  * of the SCF_PG_MANIFESTFILES property group.  The history file also contains
16780  * the path to the manifest file that defined the service or instance.
16781  *
16782  * Another type of unsupported services is 'handcrafted' services,
16783  * programmatically created services or services created by dependent entries
16784  * in other manifests. A handcrafted service is identified by its lack of any
16785  * instance containing last-import snapshot which is created during svccfg
16786  * import.
16787  *
16788  * This function sets a flag for unsupported services by setting services'
16789  * SCF_PG_MANIFESTFILES/support property to false.
16790  */
16791 static void
16792 upgrade_svc_mfst_connection(scf_service_t *svc, const char *svcname)
16793 {
16794 	service_manifest_t	*elem;
16795 	uu_list_walk_t		*mfwalk;
16796 	string_list_t		*mfile;
16797 	uu_list_t		*instances;
16798 	const char		*sname;
16799 	char			*pname;
16800 	int			r;
16801 
16802 	/*
16803 	 * Since there's no guarantee manifests under /var are available during
16804 	 * early import, don't perform any upgrade during early import.
16805 	 */
16806 	if (IGNORE_VAR)
16807 		return;
16808 
16809 	if (service_manifest_tree == NULL) {
16810 		create_manifest_tree();
16811 	}
16812 
16813 	/*
16814 	 * Find service's supporting manifest(s) after
16815 	 * stripping off the svc:/ prefix that is part
16816 	 * of the fmri that is not used in the service
16817 	 * manifest bundle list.
16818 	 */
16819 	sname = svcname + strlen(SCF_FMRI_SVC_PREFIX) +
16820 	    strlen(SCF_FMRI_SERVICE_PREFIX);
16821 	elem = find_add_svc_mfst(sname, NULL);
16822 	if (elem == NULL) {
16823 
16824 		/*
16825 		 * A handcrafted service, one that has no instance containing
16826 		 * last-import snapshot, should get unsupported flag.
16827 		 */
16828 		instances = create_instance_list(svc, 1);
16829 		if (instances == NULL) {
16830 			uu_warn(gettext("Unable to create instance list %s\n"),
16831 			    svcname);
16832 			return;
16833 		}
16834 
16835 		if (uu_list_numnodes(instances) == 0) {
16836 			svc_add_no_support(svc);
16837 			return;
16838 		}
16839 
16840 		/*
16841 		 * If the service is in the history file, and its supporting
16842 		 * manifests are not found, we can safely delete the service
16843 		 * because its manifests are removed from the system.
16844 		 *
16845 		 * Services not found in the history file are not delivered by
16846 		 * Solaris and/or delivered outside supported directories, set
16847 		 * unsupported flag for these services.
16848 		 */
16849 		r = check_mfst_history(svcname);
16850 		if (r == -1)
16851 			return;
16852 
16853 		if (r) {
16854 			/* Set unsupported flag for service  */
16855 			svc_add_no_support(svc);
16856 		} else {
16857 			/* Delete the service */
16858 			teardown_service(svc, svcname);
16859 		}
16860 
16861 		return;
16862 	}
16863 
16864 	/*
16865 	 * Walk through the list of manifests and add them
16866 	 * to the service.
16867 	 *
16868 	 * Create a manifestfiles pg and add the property.
16869 	 */
16870 	mfwalk = uu_list_walk_start(elem->mfstlist, 0);
16871 	if (mfwalk == NULL)
16872 		return;
16873 
16874 	cur_svc = svc;
16875 	r = addpg(SCF_PG_MANIFESTFILES, SCF_GROUP_FRAMEWORK);
16876 	if (r != 0) {
16877 		cur_svc = NULL;
16878 		return;
16879 	}
16880 
16881 	while ((mfile = uu_list_walk_next(mfwalk)) != NULL) {
16882 		pname = uu_msprintf("%s/%s", SCF_PG_MANIFESTFILES,
16883 		    mhash_filename_to_propname(mfile->str, 0));
16884 		if (pname == NULL)
16885 			uu_die(gettext("Out of memory.\n"));
16886 
16887 		(void) lscf_addpropvalue(pname, "astring:", mfile->str);
16888 		uu_free(pname);
16889 	}
16890 	uu_list_walk_end(mfwalk);
16891 
16892 	cur_svc = NULL;
16893 }
16894 
16895 /*
16896  * Take a service and process the manifest file entires to see if
16897  * there is continued support for the service and instances.  If
16898  * not cleanup as appropriate.
16899  *
16900  * If a service does not have a manifest files entry flag it for
16901  * upgrade and return.
16902  *
16903  * For each manifestfiles property check if the manifest file is
16904  * under the supported /lib/svc/manifest or /var/svc/manifest path
16905  * and if not then return immediately as this service is not supported
16906  * by the cleanup mechanism and should be ignored.
16907  *
16908  * For each manifest file that is supported, check to see if the
16909  * file exists.  If not then remove the manifest file property
16910  * from the service and the smf/manifest hash table.  If the manifest
16911  * file exists then verify that it supports the instances that are
16912  * part of the service.
16913  *
16914  * Once all manifest files have been accounted for remove any instances
16915  * that are no longer supported in the service.
16916  *
16917  * Return values :
16918  * 0 - Successfully processed the service
16919  * non-zero - failed to process the service
16920  *
16921  * On most errors, will just return to wait and get the next service,
16922  * unless in case of unable to create the needed structures which is
16923  * most likely a fatal error that is not going to be recoverable.
16924  */
16925 int
16926 lscf_service_cleanup(void *act, scf_walkinfo_t *wip)
16927 {
16928 	struct mpg_mfile	*mpntov;
16929 	struct mpg_mfile	**mpvarry = NULL;
16930 	scf_service_t		*svc;
16931 	scf_propertygroup_t	*mpg;
16932 	scf_property_t		*mp;
16933 	scf_value_t		*mv;
16934 	scf_iter_t		*mi;
16935 	scf_instance_t		*instance;
16936 	uu_list_walk_t		*insts;
16937 	uu_list_t		*instances = NULL;
16938 	boolean_t		activity = (boolean_t)act;
16939 	char			*mpnbuf;
16940 	char			*mpvbuf;
16941 	char			*pgpropbuf;
16942 	int			mfstcnt, rminstct, instct, mfstmax;
16943 	int			index;
16944 	int			r = 0;
16945 
16946 	assert(g_hndl != NULL);
16947 	assert(wip->svc != NULL);
16948 	assert(wip->fmri != NULL);
16949 
16950 	svc = wip->svc;
16951 
16952 	mpg = scf_pg_create(g_hndl);
16953 	mp = scf_property_create(g_hndl);
16954 	mi = scf_iter_create(g_hndl);
16955 	mv = scf_value_create(g_hndl);
16956 	instance = scf_instance_create(g_hndl);
16957 
16958 	if (mpg == NULL || mp == NULL || mi == NULL || mv == NULL ||
16959 	    instance == NULL) {
16960 		uu_warn(gettext("Unable to create the supporting entities\n"));
16961 		uu_warn(gettext("scf error is : %s\n"),
16962 		    scf_strerror(scf_error()));
16963 		scfdie();
16964 	}
16965 
16966 	/*
16967 	 * Get the manifestfiles property group to be parsed for
16968 	 * files existence.
16969 	 */
16970 	if (scf_service_get_pg(svc, SCF_PG_MANIFESTFILES, mpg) != SCF_SUCCESS) {
16971 		switch (scf_error()) {
16972 		case SCF_ERROR_NOT_FOUND:
16973 			upgrade_svc_mfst_connection(svc, wip->fmri);
16974 			break;
16975 		case SCF_ERROR_DELETED:
16976 		case SCF_ERROR_CONNECTION_BROKEN:
16977 			goto out;
16978 
16979 		case SCF_ERROR_HANDLE_MISMATCH:
16980 		case SCF_ERROR_NOT_BOUND:
16981 		case SCF_ERROR_NOT_SET:
16982 		default:
16983 			bad_error("scf_iter_pg_properties",
16984 			    scf_error());
16985 		}
16986 
16987 		goto out;
16988 	}
16989 
16990 	/*
16991 	 * Iterate through each of the manifestfiles properties
16992 	 * to determine what manifestfiles are available.
16993 	 *
16994 	 * If a manifest file is supported then increment the
16995 	 * count and therefore the service is safe.
16996 	 */
16997 	if (scf_iter_pg_properties(mi, mpg) != 0) {
16998 		switch (scf_error()) {
16999 		case SCF_ERROR_DELETED:
17000 		case SCF_ERROR_CONNECTION_BROKEN:
17001 			goto out;
17002 
17003 		case SCF_ERROR_HANDLE_MISMATCH:
17004 		case SCF_ERROR_NOT_BOUND:
17005 		case SCF_ERROR_NOT_SET:
17006 		default:
17007 			bad_error("scf_iter_pg_properties",
17008 			    scf_error());
17009 		}
17010 	}
17011 
17012 	mfstcnt = 0;
17013 	mfstmax = MFSTFILE_MAX;
17014 	mpvarry = safe_malloc(sizeof (struct mpg_file *) * MFSTFILE_MAX);
17015 	while ((r = scf_iter_next_property(mi, mp)) != 0) {
17016 		if (r == -1)
17017 			bad_error(gettext("Unable to iterate through "
17018 			    "manifestfiles properties : %s"),
17019 			    scf_error());
17020 
17021 		mpntov = safe_malloc(sizeof (struct mpg_mfile));
17022 		mpnbuf = safe_malloc(max_scf_name_len + 1);
17023 		mpvbuf = safe_malloc(max_scf_value_len + 1);
17024 		mpntov->mpg = mpnbuf;
17025 		mpntov->mfile = mpvbuf;
17026 		mpntov->access = 1;
17027 		if (scf_property_get_name(mp, mpnbuf,
17028 		    max_scf_name_len + 1) < 0) {
17029 			uu_warn(gettext("Unable to get manifest file "
17030 			    "property : %s\n"),
17031 			    scf_strerror(scf_error()));
17032 
17033 			switch (scf_error()) {
17034 			case SCF_ERROR_DELETED:
17035 			case SCF_ERROR_CONNECTION_BROKEN:
17036 				r = scferror2errno(scf_error());
17037 				goto out_free;
17038 
17039 			case SCF_ERROR_HANDLE_MISMATCH:
17040 			case SCF_ERROR_NOT_BOUND:
17041 			case SCF_ERROR_NOT_SET:
17042 			default:
17043 				bad_error("scf_iter_pg_properties",
17044 				    scf_error());
17045 			}
17046 		}
17047 
17048 		/*
17049 		 * The support property is a boolean value that indicates
17050 		 * if the service is supported for manifest file deletion.
17051 		 * Currently at this time there is no code that sets this
17052 		 * value to true.  So while we could just let this be caught
17053 		 * by the support check below, in the future this by be set
17054 		 * to true and require processing.  So for that, go ahead
17055 		 * and check here, and just return if false.  Otherwise,
17056 		 * fall through expecting that other support checks will
17057 		 * handle the entries.
17058 		 */
17059 		if (strcmp(mpnbuf, SUPPORTPROP) == 0) {
17060 			uint8_t	support;
17061 
17062 			if (scf_property_get_value(mp, mv) != 0 ||
17063 			    scf_value_get_boolean(mv, &support) != 0) {
17064 				uu_warn(gettext("Unable to get the manifest "
17065 				    "support value: %s\n"),
17066 				    scf_strerror(scf_error()));
17067 
17068 				switch (scf_error()) {
17069 				case SCF_ERROR_DELETED:
17070 				case SCF_ERROR_CONNECTION_BROKEN:
17071 					r = scferror2errno(scf_error());
17072 					goto out_free;
17073 
17074 				case SCF_ERROR_HANDLE_MISMATCH:
17075 				case SCF_ERROR_NOT_BOUND:
17076 				case SCF_ERROR_NOT_SET:
17077 				default:
17078 					bad_error("scf_iter_pg_properties",
17079 					    scf_error());
17080 				}
17081 			}
17082 
17083 			if (support == B_FALSE)
17084 				goto out_free;
17085 		}
17086 
17087 		/*
17088 		 * Anything with a manifest outside of the supported
17089 		 * directories, immediately bail out because that makes
17090 		 * this service non-supported.  We don't even want
17091 		 * to do instance processing in this case because the
17092 		 * instances could be part of the non-supported manifest.
17093 		 */
17094 		if (strncmp(mpnbuf, LIBSVC_PR, strlen(LIBSVC_PR)) != 0) {
17095 			/*
17096 			 * Manifest is not in /lib/svc, so we need to
17097 			 * consider the /var/svc case.
17098 			 */
17099 			if (strncmp(mpnbuf, VARSVC_PR,
17100 			    strlen(VARSVC_PR)) != 0 || IGNORE_VAR) {
17101 				/*
17102 				 * Either the manifest is not in /var/svc or
17103 				 * /var is not yet mounted.  We ignore the
17104 				 * manifest either because it is not in a
17105 				 * standard location or because we cannot
17106 				 * currently access the manifest.
17107 				 */
17108 				goto out_free;
17109 			}
17110 		}
17111 
17112 		/*
17113 		 * Get the value to of the manifest file for this entry
17114 		 * for access verification and instance support
17115 		 * verification if it still exists.
17116 		 *
17117 		 * During Early Manifest Import if the manifest is in
17118 		 * /var/svc then it may not yet be available for checking
17119 		 * so we must determine if /var/svc is available.  If not
17120 		 * then defer until Late Manifest Import to cleanup.
17121 		 */
17122 		if (scf_property_get_value(mp, mv) != 0) {
17123 			uu_warn(gettext("Unable to get the manifest file "
17124 			    "value: %s\n"),
17125 			    scf_strerror(scf_error()));
17126 
17127 			switch (scf_error()) {
17128 			case SCF_ERROR_DELETED:
17129 			case SCF_ERROR_CONNECTION_BROKEN:
17130 				r = scferror2errno(scf_error());
17131 				goto out_free;
17132 
17133 			case SCF_ERROR_HANDLE_MISMATCH:
17134 			case SCF_ERROR_NOT_BOUND:
17135 			case SCF_ERROR_NOT_SET:
17136 			default:
17137 				bad_error("scf_property_get_value",
17138 				    scf_error());
17139 			}
17140 		}
17141 
17142 		if (scf_value_get_astring(mv, mpvbuf,
17143 		    max_scf_value_len + 1) < 0) {
17144 			uu_warn(gettext("Unable to get the manifest "
17145 			    "file : %s\n"),
17146 			    scf_strerror(scf_error()));
17147 
17148 			switch (scf_error()) {
17149 			case SCF_ERROR_DELETED:
17150 			case SCF_ERROR_CONNECTION_BROKEN:
17151 				r = scferror2errno(scf_error());
17152 				goto out_free;
17153 
17154 			case SCF_ERROR_HANDLE_MISMATCH:
17155 			case SCF_ERROR_NOT_BOUND:
17156 			case SCF_ERROR_NOT_SET:
17157 			default:
17158 				bad_error("scf_value_get_astring",
17159 				    scf_error());
17160 			}
17161 		}
17162 
17163 		mpvarry[mfstcnt] = mpntov;
17164 		mfstcnt++;
17165 
17166 		/*
17167 		 * Check for the need to reallocate array
17168 		 */
17169 		if (mfstcnt >= (mfstmax - 1)) {
17170 			struct mpg_mfile **newmpvarry;
17171 
17172 			mfstmax = mfstmax * 2;
17173 			newmpvarry = realloc(mpvarry,
17174 			    sizeof (struct mpg_mfile *) * mfstmax);
17175 
17176 			if (newmpvarry == NULL)
17177 				goto out_free;
17178 
17179 			mpvarry = newmpvarry;
17180 		}
17181 
17182 		mpvarry[mfstcnt] = NULL;
17183 	}
17184 
17185 	for (index = 0; mpvarry[index]; index++) {
17186 		mpntov = mpvarry[index];
17187 
17188 		/*
17189 		 * Check to see if the manifestfile is accessable, if so hand
17190 		 * this service and manifestfile off to be processed for
17191 		 * instance support.
17192 		 */
17193 		mpnbuf = mpntov->mpg;
17194 		mpvbuf = mpntov->mfile;
17195 		if (access(mpvbuf, F_OK) != 0) {
17196 			mpntov->access = 0;
17197 			activity++;
17198 			mfstcnt--;
17199 			/* Remove the entry from the service */
17200 			cur_svc = svc;
17201 			pgpropbuf = uu_msprintf("%s/%s", SCF_PG_MANIFESTFILES,
17202 			    mpnbuf);
17203 			if (pgpropbuf == NULL)
17204 				uu_die(gettext("Out of memory.\n"));
17205 
17206 			lscf_delprop(pgpropbuf);
17207 			cur_svc = NULL;
17208 
17209 			uu_free(pgpropbuf);
17210 		}
17211 	}
17212 
17213 	/*
17214 	 * If mfstcnt is 0, none of the manifests that supported the service
17215 	 * existed so remove the service.
17216 	 */
17217 	if (mfstcnt == 0) {
17218 		teardown_service(svc, wip->fmri);
17219 
17220 		goto out_free;
17221 	}
17222 
17223 	if (activity) {
17224 		int	nosvcsupport = 0;
17225 
17226 		/*
17227 		 * If the list of service instances is NULL then
17228 		 * create the list.
17229 		 */
17230 		instances = create_instance_list(svc, 1);
17231 		if (instances == NULL) {
17232 			uu_warn(gettext("Unable to create instance list %s\n"),
17233 			    wip->fmri);
17234 			goto out_free;
17235 		}
17236 
17237 		rminstct = uu_list_numnodes(instances);
17238 		instct = rminstct;
17239 
17240 		for (index = 0; mpvarry[index]; index++) {
17241 			mpntov = mpvarry[index];
17242 			if (mpntov->access == 0)
17243 				continue;
17244 
17245 			mpnbuf = mpntov->mpg;
17246 			mpvbuf = mpntov->mfile;
17247 			r = check_instance_support(mpvbuf, wip->fmri,
17248 			    instances);
17249 			if (r == -1) {
17250 				nosvcsupport++;
17251 			} else {
17252 				rminstct -= r;
17253 			}
17254 		}
17255 
17256 		if (instct && instct == rminstct && nosvcsupport == mfstcnt) {
17257 			teardown_service(svc, wip->fmri);
17258 
17259 			goto out_free;
17260 		}
17261 	}
17262 
17263 	/*
17264 	 * If there are instances left on the instance list, then
17265 	 * we must remove them.
17266 	 */
17267 	if (instances != NULL && uu_list_numnodes(instances)) {
17268 		string_list_t *sp;
17269 
17270 		insts = uu_list_walk_start(instances, 0);
17271 		while ((sp = uu_list_walk_next(insts)) != NULL) {
17272 			/*
17273 			 * Remove the instance from the instances list.
17274 			 */
17275 			safe_printf(gettext("Delete instance %s from "
17276 			    "service %s\n"), sp->str, wip->fmri);
17277 			if (scf_service_get_instance(svc, sp->str,
17278 			    instance) != SCF_SUCCESS) {
17279 				(void) uu_warn("scf_error - %s\n",
17280 				    scf_strerror(scf_error()));
17281 
17282 				continue;
17283 			}
17284 
17285 			(void) disable_instance(instance);
17286 
17287 			(void) lscf_instance_delete(instance, 1);
17288 		}
17289 		scf_instance_destroy(instance);
17290 		uu_list_walk_end(insts);
17291 	}
17292 
17293 out_free:
17294 	if (mpvarry) {
17295 		struct mpg_mfile *fmpntov;
17296 
17297 		for (index = 0; mpvarry[index]; index++) {
17298 			fmpntov  = mpvarry[index];
17299 			if (fmpntov->mpg == mpnbuf)
17300 				mpnbuf = NULL;
17301 			free(fmpntov->mpg);
17302 
17303 			if (fmpntov->mfile == mpvbuf)
17304 				mpvbuf = NULL;
17305 			free(fmpntov->mfile);
17306 
17307 			if (fmpntov == mpntov)
17308 				mpntov = NULL;
17309 			free(fmpntov);
17310 		}
17311 		if (mpnbuf)
17312 			free(mpnbuf);
17313 		if (mpvbuf)
17314 			free(mpvbuf);
17315 		if (mpntov)
17316 			free(mpntov);
17317 
17318 		free(mpvarry);
17319 	}
17320 out:
17321 	scf_pg_destroy(mpg);
17322 	scf_property_destroy(mp);
17323 	scf_iter_destroy(mi);
17324 	scf_value_destroy(mv);
17325 
17326 	return (0);
17327 }
17328 
17329 /*
17330  * Take the service and search for the manifestfiles property
17331  * in each of the property groups.  If the manifest file
17332  * associated with the property does not exist then remove
17333  * the property group.
17334  */
17335 int
17336 lscf_hash_cleanup()
17337 {
17338 	scf_service_t		*svc;
17339 	scf_scope_t		*scope;
17340 	scf_propertygroup_t	*pg;
17341 	scf_property_t		*prop;
17342 	scf_value_t		*val;
17343 	scf_iter_t		*iter;
17344 	char			*pgname = NULL;
17345 	char			*mfile = NULL;
17346 	int			r;
17347 
17348 	svc = scf_service_create(g_hndl);
17349 	scope = scf_scope_create(g_hndl);
17350 	pg = scf_pg_create(g_hndl);
17351 	prop = scf_property_create(g_hndl);
17352 	val = scf_value_create(g_hndl);
17353 	iter = scf_iter_create(g_hndl);
17354 	if (pg == NULL || prop == NULL || val == NULL || iter == NULL ||
17355 	    svc == NULL || scope == NULL) {
17356 		uu_warn(gettext("Unable to create a property group, or "
17357 		    "property\n"));
17358 		uu_warn("%s\n", pg == NULL ? "pg is NULL" :
17359 		    "pg is not NULL");
17360 		uu_warn("%s\n", prop == NULL ? "prop is NULL" :
17361 		    "prop is not NULL");
17362 		uu_warn("%s\n", val == NULL ? "val is NULL" :
17363 		    "val is not NULL");
17364 		uu_warn("%s\n", iter == NULL ? "iter is NULL" :
17365 		    "iter is not NULL");
17366 		uu_warn("%s\n", svc == NULL ? "svc is NULL" :
17367 		    "svc is not NULL");
17368 		uu_warn("%s\n", scope == NULL ? "scope is NULL" :
17369 		    "scope is not NULL");
17370 		uu_warn(gettext("scf error is : %s\n"),
17371 		    scf_strerror(scf_error()));
17372 		scfdie();
17373 	}
17374 
17375 	if (scf_handle_get_scope(g_hndl, SCF_SCOPE_LOCAL, scope) != 0) {
17376 		switch (scf_error()) {
17377 		case SCF_ERROR_CONNECTION_BROKEN:
17378 		case SCF_ERROR_NOT_FOUND:
17379 			goto out;
17380 
17381 		case SCF_ERROR_HANDLE_MISMATCH:
17382 		case SCF_ERROR_NOT_BOUND:
17383 		case SCF_ERROR_INVALID_ARGUMENT:
17384 		default:
17385 			bad_error("scf_handle_get_scope", scf_error());
17386 		}
17387 	}
17388 
17389 	if (scf_scope_get_service(scope, HASH_SVC, svc) != 0) {
17390 		uu_warn(gettext("Unable to process the hash service, %s\n"),
17391 		    HASH_SVC);
17392 		goto out;
17393 	}
17394 
17395 	pgname = safe_malloc(max_scf_name_len + 1);
17396 	mfile = safe_malloc(max_scf_value_len + 1);
17397 
17398 	if (scf_iter_service_pgs(iter, svc) != SCF_SUCCESS) {
17399 		uu_warn(gettext("Unable to cleanup smf hash table : %s\n"),
17400 		    scf_strerror(scf_error()));
17401 		goto out;
17402 	}
17403 
17404 	while ((r = scf_iter_next_pg(iter, pg)) != 0) {
17405 		if (r == -1)
17406 			goto out;
17407 
17408 		if (scf_pg_get_name(pg, pgname, max_scf_name_len + 1) < 0) {
17409 			switch (scf_error()) {
17410 			case SCF_ERROR_DELETED:
17411 				return (ENODEV);
17412 
17413 			case SCF_ERROR_CONNECTION_BROKEN:
17414 				return (ECONNABORTED);
17415 
17416 			case SCF_ERROR_NOT_SET:
17417 			case SCF_ERROR_NOT_BOUND:
17418 			default:
17419 				bad_error("scf_pg_get_name", scf_error());
17420 			}
17421 		}
17422 		if (IGNORE_VAR) {
17423 			if (strncmp(pgname, VARSVC_PR, strlen(VARSVC_PR)) == 0)
17424 				continue;
17425 		}
17426 
17427 		/*
17428 		 * If unable to get the property continue as this is an
17429 		 * entry that has no location to check against.
17430 		 */
17431 		if (scf_pg_get_property(pg, MFSTFILEPR, prop) != SCF_SUCCESS) {
17432 			continue;
17433 		}
17434 
17435 		if (scf_property_get_value(prop, val) != SCF_SUCCESS) {
17436 			uu_warn(gettext("Unable to get value from %s\n"),
17437 			    pgname);
17438 
17439 			switch (scf_error()) {
17440 			case SCF_ERROR_DELETED:
17441 			case SCF_ERROR_CONSTRAINT_VIOLATED:
17442 			case SCF_ERROR_NOT_FOUND:
17443 			case SCF_ERROR_NOT_SET:
17444 				continue;
17445 
17446 			case SCF_ERROR_CONNECTION_BROKEN:
17447 				r = scferror2errno(scf_error());
17448 				goto out;
17449 
17450 			case SCF_ERROR_HANDLE_MISMATCH:
17451 			case SCF_ERROR_NOT_BOUND:
17452 			default:
17453 				bad_error("scf_property_get_value",
17454 				    scf_error());
17455 			}
17456 		}
17457 
17458 		if (scf_value_get_astring(val, mfile, max_scf_value_len + 1)
17459 		    == -1) {
17460 			uu_warn(gettext("Unable to get astring from %s : %s\n"),
17461 			    pgname, scf_strerror(scf_error()));
17462 
17463 			switch (scf_error()) {
17464 			case SCF_ERROR_NOT_SET:
17465 			case SCF_ERROR_TYPE_MISMATCH:
17466 				continue;
17467 
17468 			default:
17469 				bad_error("scf_value_get_astring", scf_error());
17470 			}
17471 		}
17472 
17473 		if (access(mfile, F_OK) == 0)
17474 			continue;
17475 
17476 		(void) scf_pg_delete(pg);
17477 	}
17478 
17479 out:
17480 	scf_scope_destroy(scope);
17481 	scf_service_destroy(svc);
17482 	scf_pg_destroy(pg);
17483 	scf_property_destroy(prop);
17484 	scf_value_destroy(val);
17485 	scf_iter_destroy(iter);
17486 	free(pgname);
17487 	free(mfile);
17488 
17489 	return (0);
17490 }
17491 
17492 #ifndef NATIVE_BUILD
17493 /* ARGSUSED */
17494 CPL_MATCH_FN(complete_select)
17495 {
17496 	const char *arg0, *arg1, *arg1end;
17497 	int word_start, err = 0, r;
17498 	size_t len;
17499 	char *buf;
17500 
17501 	lscf_prep_hndl();
17502 
17503 	arg0 = line + strspn(line, " \t");
17504 	assert(strncmp(arg0, "select", sizeof ("select") - 1) == 0);
17505 
17506 	arg1 = arg0 + sizeof ("select") - 1;
17507 	arg1 += strspn(arg1, " \t");
17508 	word_start = arg1 - line;
17509 
17510 	arg1end = arg1 + strcspn(arg1, " \t");
17511 	if (arg1end < line + word_end)
17512 		return (0);
17513 
17514 	len = line + word_end - arg1;
17515 
17516 	buf = safe_malloc(max_scf_name_len + 1);
17517 
17518 	if (cur_snap != NULL) {
17519 		return (0);
17520 	} else if (cur_inst != NULL) {
17521 		return (0);
17522 	} else if (cur_svc != NULL) {
17523 		scf_instance_t *inst;
17524 		scf_iter_t *iter;
17525 
17526 		if ((inst = scf_instance_create(g_hndl)) == NULL ||
17527 		    (iter = scf_iter_create(g_hndl)) == NULL)
17528 			scfdie();
17529 
17530 		if (scf_iter_service_instances(iter, cur_svc) != 0)
17531 			scfdie();
17532 
17533 		for (;;) {
17534 			r = scf_iter_next_instance(iter, inst);
17535 			if (r == 0)
17536 				break;
17537 			if (r != 1)
17538 				scfdie();
17539 
17540 			if (scf_instance_get_name(inst, buf,
17541 			    max_scf_name_len + 1) < 0)
17542 				scfdie();
17543 
17544 			if (strncmp(buf, arg1, len) == 0) {
17545 				err = cpl_add_completion(cpl, line, word_start,
17546 				    word_end, buf + len, "", " ");
17547 				if (err != 0)
17548 					break;
17549 			}
17550 		}
17551 
17552 		scf_iter_destroy(iter);
17553 		scf_instance_destroy(inst);
17554 
17555 		return (err);
17556 	} else {
17557 		scf_service_t *svc;
17558 		scf_iter_t *iter;
17559 
17560 		assert(cur_scope != NULL);
17561 
17562 		if ((svc = scf_service_create(g_hndl)) == NULL ||
17563 		    (iter = scf_iter_create(g_hndl)) == NULL)
17564 			scfdie();
17565 
17566 		if (scf_iter_scope_services(iter, cur_scope) != 0)
17567 			scfdie();
17568 
17569 		for (;;) {
17570 			r = scf_iter_next_service(iter, svc);
17571 			if (r == 0)
17572 				break;
17573 			if (r != 1)
17574 				scfdie();
17575 
17576 			if (scf_service_get_name(svc, buf,
17577 			    max_scf_name_len + 1) < 0)
17578 				scfdie();
17579 
17580 			if (strncmp(buf, arg1, len) == 0) {
17581 				err = cpl_add_completion(cpl, line, word_start,
17582 				    word_end, buf + len, "", " ");
17583 				if (err != 0)
17584 					break;
17585 			}
17586 		}
17587 
17588 		scf_iter_destroy(iter);
17589 		scf_service_destroy(svc);
17590 
17591 		return (err);
17592 	}
17593 }
17594 
17595 /* ARGSUSED */
17596 CPL_MATCH_FN(complete_command)
17597 {
17598 	uint32_t scope = 0;
17599 
17600 	if (cur_snap != NULL)
17601 		scope = CS_SNAP;
17602 	else if (cur_inst != NULL)
17603 		scope = CS_INST;
17604 	else if (cur_svc != NULL)
17605 		scope = CS_SVC;
17606 	else
17607 		scope = CS_SCOPE;
17608 
17609 	return (scope ? add_cmd_matches(cpl, line, word_end, scope) : 0);
17610 }
17611 #endif	/* NATIVE_BUILD */
17612