xref: /illumos-gate/usr/src/cmd/svc/svccfg/svccfg_engine.c (revision adfc3118ca8c6b541b6a93d4bc24583eb4ebd73d)
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  */
25 
26 
27 /*
28  * svccfg(1) interpreter and command execution engine.
29  */
30 
31 #include <sys/mman.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34 #include <assert.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <libintl.h>
38 #include <libtecla.h>
39 #include <md5.h>
40 #include <string.h>
41 #include <stdlib.h>
42 #include <unistd.h>
43 
44 #include "manifest_find.h"
45 #include "manifest_hash.h"
46 #include "svccfg.h"
47 
48 #define	MS_PER_US		1000
49 
50 engine_state_t *est;
51 
52 /*
53  * Replacement lex(1) character retrieval routines.
54  */
55 int
56 engine_cmd_getc(engine_state_t *E)
57 {
58 	if (E->sc_cmd_file != NULL)
59 		return (getc(E->sc_cmd_file));
60 
61 	if (E->sc_cmd_flags & SC_CMD_EOF)
62 		return (EOF);
63 
64 	if (E->sc_cmd_bufoff < E->sc_cmd_bufsz)
65 		return (*(E->sc_cmd_buf + E->sc_cmd_bufoff++));
66 
67 	if (!(E->sc_cmd_flags & SC_CMD_IACTIVE)) {
68 		E->sc_cmd_flags |= SC_CMD_EOF;
69 
70 		return (EOF);
71 	} else {
72 #ifdef NATIVE_BUILD
73 		return (EOF);
74 #else
75 		extern int parens;
76 
77 		if (parens <= 0) {
78 			E->sc_cmd_flags |= SC_CMD_EOF;
79 			return (EOF);
80 		}
81 
82 		for (;;) {
83 			E->sc_cmd_buf = gl_get_line(E->sc_gl, "> ", NULL, -1);
84 			if (E->sc_cmd_buf != NULL)
85 				break;
86 
87 			switch (gl_return_status(E->sc_gl)) {
88 			case GLR_SIGNAL:
89 				gl_abandon_line(E->sc_gl);
90 				continue;
91 
92 			case GLR_EOF:
93 				E->sc_cmd_flags |= SC_CMD_EOF;
94 				return (EOF);
95 
96 			case GLR_ERROR:
97 				uu_die(gettext("Error reading terminal: %s.\n"),
98 				    gl_error_message(E->sc_gl, NULL, 0));
99 				/* NOTREACHED */
100 
101 			default:
102 #ifndef NDEBUG
103 				(void) fprintf(stderr, "%s:%d: gl_get_line() "
104 				    "returned unexpected value %d.\n", __FILE__,
105 				    __LINE__, gl_return_status(E->sc_gl));
106 #endif
107 				abort();
108 			}
109 		}
110 
111 		E->sc_cmd_bufsz = strlen(E->sc_cmd_buf);
112 		E->sc_cmd_bufoff = 1;
113 
114 		return (E->sc_cmd_buf[0]);
115 #endif	/* NATIVE_BUILD */
116 	}
117 }
118 
119 int
120 engine_cmd_ungetc(engine_state_t *E, char c)
121 {
122 	if (E->sc_cmd_file != NULL)
123 		return (ungetc(c, E->sc_cmd_file));
124 
125 	if (E->sc_cmd_buf != NULL)
126 		*(E->sc_cmd_buf + --E->sc_cmd_bufoff) = c;
127 
128 	return (c);
129 }
130 
131 /*ARGSUSED*/
132 void
133 engine_cmd_nputs(engine_state_t *E, char *c, size_t n)
134 {
135 	/* our lexer shouldn't need this state */
136 	exit(11);
137 }
138 
139 int
140 engine_exec(char *cmd)
141 {
142 	est->sc_cmd_buf = cmd;
143 	est->sc_cmd_bufsz = strlen(cmd) + 1;
144 	est->sc_cmd_bufoff = 0;
145 
146 	(void) yyparse();
147 
148 	return (0);
149 }
150 
151 #ifndef NATIVE_BUILD
152 /* ARGSUSED */
153 static
154 CPL_CHECK_FN(check_xml)
155 {
156 	const char *ext;
157 
158 	if (strlen(pathname) < 4)
159 		return (0);
160 
161 	ext = pathname + strlen(pathname) - 4;
162 
163 	return (strcmp(ext, ".xml") == 0 ? 1 : 0);
164 }
165 
166 static const char * const whitespace = " \t";
167 
168 static
169 CPL_MATCH_FN(complete_single_xml_file_arg)
170 {
171 	const char *arg1 = data;
172 	int arg1end_i, ret;
173 	CplFileConf *cfc;
174 
175 	arg1end_i = arg1 + strcspn(arg1, whitespace) - line;
176 	if (arg1end_i < word_end)
177 		return (0);
178 
179 	cfc = new_CplFileConf();
180 	if (cfc == NULL) {
181 		cpl_record_error(cpl, "Out of memory.");
182 		return (1);
183 	}
184 
185 	cfc_set_check_fn(cfc, check_xml, NULL);
186 
187 	ret = cpl_file_completions(cpl, cfc, line, word_end);
188 
189 	(void) del_CplFileConf(cfc);
190 	return (ret);
191 }
192 
193 static struct cmd_info {
194 	const char	*name;
195 	uint32_t	flags;
196 	CplMatchFn	*complete_args_f;
197 } cmds[] = {
198 	{ "validate", CS_GLOBAL, complete_single_xml_file_arg },
199 	{ "import", CS_GLOBAL, complete_single_xml_file_arg },
200 	{ "cleanup", CS_GLOBAL, NULL},
201 	{ "export", CS_GLOBAL, NULL },
202 	{ "archive", CS_GLOBAL, NULL },
203 	{ "apply", CS_GLOBAL, complete_single_xml_file_arg },
204 	{ "extract", CS_GLOBAL, NULL },
205 	{ "repository", CS_GLOBAL, NULL },
206 	{ "inventory", CS_GLOBAL, complete_single_xml_file_arg },
207 	{ "set", CS_GLOBAL, NULL },
208 	{ "end", CS_GLOBAL, NULL },
209 	{ "exit", CS_GLOBAL, NULL },
210 	{ "quit", CS_GLOBAL, NULL },
211 	{ "help", CS_GLOBAL, NULL },
212 	{ "delete", CS_GLOBAL, NULL },
213 	{ "select", CS_GLOBAL, complete_select },
214 	{ "unselect", CS_SVC | CS_INST | CS_SNAP, NULL },
215 	{ "list", CS_SCOPE | CS_SVC | CS_SNAP, NULL },
216 	{ "add", CS_SCOPE | CS_SVC, NULL },
217 	{ "listpg", CS_SVC | CS_INST | CS_SNAP, NULL },
218 	{ "addpg", CS_SVC | CS_INST, NULL },
219 	{ "delpg", CS_SVC | CS_INST, NULL },
220 	{ "delhash", CS_GLOBAL, complete_single_xml_file_arg },
221 	{ "listprop", CS_SVC | CS_INST | CS_SNAP, NULL },
222 	{ "setprop", CS_SVC | CS_INST, NULL },
223 	{ "delprop", CS_SVC | CS_INST, NULL },
224 	{ "editprop", CS_SVC | CS_INST, NULL },
225 	{ "describe", CS_SVC | CS_INST | CS_SNAP, NULL },
226 	{ "listsnap", CS_INST | CS_SNAP, NULL },
227 	{ "selectsnap", CS_INST | CS_SNAP, NULL },
228 	{ "revert", CS_INST | CS_SNAP, NULL },
229 	{ "refresh", CS_INST, NULL },
230 	{ NULL }
231 };
232 
233 int
234 add_cmd_matches(WordCompletion *cpl, const char *line, int word_end,
235     uint32_t scope)
236 {
237 	int word_start, err;
238 	size_t len;
239 	const char *bol;
240 	struct cmd_info *cip;
241 
242 	word_start = strspn(line, whitespace);
243 	len = word_end - word_start;
244 	bol = line + word_end - len;
245 
246 	for (cip = cmds; cip->name != NULL; ++cip) {
247 		if ((cip->flags & scope) == 0)
248 			continue;
249 
250 		if (strncmp(cip->name, bol, len) == 0) {
251 			err = cpl_add_completion(cpl, line, word_start,
252 			    word_end, cip->name + len, "", " ");
253 			if (err != 0)
254 				return (err);
255 		}
256 	}
257 
258 	return (0);
259 }
260 
261 /*
262  * Suggest completions.  We must first determine if the cursor is in command
263  * position or in argument position.  If the former, complete_command() finds
264  * matching commands.  If the latter, we tail-call the command-specific
265  * argument-completion routine in the cmds table.
266  */
267 /* ARGSUSED */
268 static
269 CPL_MATCH_FN(complete)
270 {
271 	const char *arg0, *arg1;
272 	size_t arg0len;
273 	struct cmd_info *cip;
274 
275 	arg0 = line + strspn(line, whitespace);
276 	arg0len = strcspn(arg0, whitespace);
277 	if ((arg0 + arg0len) - line >= word_end ||
278 	    (arg0[arg0len] != ' ' && arg0[arg0len] != '\t'))
279 		return (complete_command(cpl, (void *)arg0, line, word_end));
280 
281 	arg1 = arg0 + arg0len;
282 	arg1 += strspn(arg1, whitespace);
283 
284 	for (cip = cmds; cip->name != NULL; ++cip) {
285 		if (strlen(cip->name) != arg0len)
286 			continue;
287 
288 		if (strncmp(cip->name, arg0, arg0len) != 0)
289 			continue;
290 
291 		if (cip->complete_args_f == NULL)
292 			break;
293 
294 		return (cip->complete_args_f(cpl, (void *)arg1, line,
295 		    word_end));
296 	}
297 
298 	return (0);
299 }
300 #endif	/* NATIVE_BUILD */
301 
302 int
303 engine_interp()
304 {
305 #ifdef NATIVE_BUILD
306 	uu_die("native build does not support interactive mode.");
307 #else
308 	char *selfmri;
309 	size_t sfsz;
310 	int r;
311 
312 	extern int parens;
313 
314 	(void) sigset(SIGINT, SIG_IGN);
315 
316 	est->sc_gl = new_GetLine(512, 8000);
317 	if (est->sc_gl == NULL)
318 		uu_die(gettext("Out of memory.\n"));
319 
320 	/* The longest string is "[snapname]fmri[:instname]> ". */
321 	sfsz = 1 + max_scf_name_len + 1 + max_scf_fmri_len + 2 +
322 	    max_scf_name_len + 1 + 2 + 1;
323 	selfmri = safe_malloc(sfsz);
324 
325 	r = gl_customize_completion(est->sc_gl, NULL, complete);
326 	assert(r == 0);
327 
328 	for (;;) {
329 		lscf_get_selection_str(selfmri, sfsz - 2);
330 		(void) strcat(selfmri, "> ");
331 		est->sc_cmd_buf = gl_get_line(est->sc_gl, selfmri, NULL, -1);
332 
333 		if (est->sc_cmd_buf == NULL) {
334 			switch (gl_return_status(est->sc_gl)) {
335 			case GLR_SIGNAL:
336 				gl_abandon_line(est->sc_gl);
337 				continue;
338 
339 			case GLR_EOF:
340 				break;
341 
342 			case GLR_ERROR:
343 				uu_die(gettext("Error reading terminal: %s.\n"),
344 				    gl_error_message(est->sc_gl, NULL, 0));
345 				/* NOTREACHED */
346 
347 			default:
348 #ifndef NDEBUG
349 				(void) fprintf(stderr, "%s:%d: gl_get_line() "
350 				    "returned unexpected value %d.\n", __FILE__,
351 				    __LINE__, gl_return_status(est->sc_gl));
352 #endif
353 				abort();
354 			}
355 
356 			break;
357 		}
358 
359 		parens = 0;
360 		est->sc_cmd_bufsz = strlen(est->sc_cmd_buf);
361 		est->sc_cmd_bufoff = 0;
362 		est->sc_cmd_flags = SC_CMD_IACTIVE;
363 
364 		(void) yyparse();
365 	}
366 
367 	free(selfmri);
368 	est->sc_gl = del_GetLine(est->sc_gl);	/* returns NULL */
369 
370 #endif	/* NATIVE_BUILD */
371 	return (0);
372 }
373 
374 int
375 engine_source(const char *name, boolean_t dont_exit)
376 {
377 	engine_state_t *old = est;
378 	struct stat st;
379 	int ret;
380 
381 	est = uu_zalloc(sizeof (engine_state_t));
382 
383 	/* first, copy the stuff set up in engine_init */
384 	est->sc_repo_pid = old->sc_repo_pid;
385 	if (old->sc_repo_filename != NULL)
386 		est->sc_repo_filename = safe_strdup(old->sc_repo_filename);
387 	if (old->sc_repo_doordir != NULL)
388 		est->sc_repo_doordir = safe_strdup(old->sc_repo_doordir);
389 	if (old->sc_repo_doorname != NULL)
390 		est->sc_repo_doorname = safe_strdup(old->sc_repo_doorname);
391 	if (old->sc_repo_server != NULL)
392 		est->sc_repo_server = safe_strdup(old->sc_repo_server);
393 
394 	/* set up the new guy */
395 	est->sc_cmd_lineno = 1;
396 
397 	if (dont_exit)
398 		est->sc_cmd_flags |= SC_CMD_DONT_EXIT;
399 
400 	if (strcmp(name, "-") == 0) {
401 		est->sc_cmd_file = stdin;
402 		est->sc_cmd_filename = "<stdin>";
403 	} else {
404 		errno = 0;
405 		est->sc_cmd_filename = name;
406 		est->sc_cmd_file = fopen(name, "r");
407 		if (est->sc_cmd_file == NULL) {
408 			if (errno == 0)
409 				semerr(gettext("No free stdio streams.\n"));
410 			else
411 				semerr(gettext("Could not open %s"), name);
412 
413 			ret = -1;
414 			goto fail;
415 		}
416 
417 		do {
418 			ret = fstat(fileno(est->sc_cmd_file), &st);
419 		} while (ret != 0 && errno == EINTR);
420 		if (ret != 0) {
421 			(void) fclose(est->sc_cmd_file);
422 			est->sc_cmd_file = NULL;	/* for semerr() */
423 
424 			semerr(gettext("Could not stat %s"), name);
425 
426 			ret = -1;
427 			goto fail;
428 		}
429 
430 		if (!S_ISREG(st.st_mode)) {
431 			(void) fclose(est->sc_cmd_file);
432 			est->sc_cmd_file = NULL;	/* for semerr() */
433 
434 			semerr(gettext("%s is not a regular file.\n"), name);
435 
436 			ret = -1;
437 			goto fail;
438 		}
439 	}
440 
441 	(void) yyparse();
442 
443 	if (est->sc_cmd_file != stdin)
444 		(void) fclose(est->sc_cmd_file);
445 
446 	ret = 0;
447 
448 fail:
449 	if (est->sc_repo_pid != old->sc_repo_pid)
450 		lscf_cleanup();		/* clean up any new repository */
451 
452 	if (est->sc_repo_filename != NULL)
453 		free((void *)est->sc_repo_filename);
454 	if (est->sc_repo_doordir != NULL)
455 		free((void *)est->sc_repo_doordir);
456 	if (est->sc_repo_doorname != NULL)
457 		free((void *)est->sc_repo_doorname);
458 	if (est->sc_repo_server != NULL)
459 		free((void *)est->sc_repo_server);
460 	free(est);
461 
462 	est = old;
463 
464 	return (ret);
465 }
466 
467 /*
468  * Initialize svccfg state.  We recognize four environment variables:
469  *
470  * SVCCFG_REPOSITORY	Create a private instance of svc.configd(1M) to answer
471  *			requests for the specified repository file.
472  * SVCCFG_DOOR_PATH	Directory for door creation.
473  *
474  * SVCCFG_DOOR		Rendezvous via an alternative repository door.
475  *
476  * SVCCFG_CONFIGD_PATH	Resolvable path to alternative svc.configd(1M) binary.
477  */
478 void
479 engine_init()
480 {
481 	const char *cp;
482 
483 	est = uu_zalloc(sizeof (engine_state_t));
484 
485 	est->sc_cmd_lineno = 1;
486 	est->sc_repo_pid = -1;
487 
488 	cp = getenv("SVCCFG_REPOSITORY");
489 	est->sc_repo_filename = cp ? safe_strdup(cp) : NULL;
490 
491 	cp = getenv("SVCCFG_DOOR_PATH");
492 	est->sc_repo_doordir = cp ? cp : "/var/run";
493 
494 	cp = getenv("SVCCFG_DOOR");
495 	if (cp != NULL) {
496 		if (est->sc_repo_filename != NULL) {
497 			uu_warn(gettext("SVCCFG_DOOR unused when "
498 			    "SVCCFG_REPOSITORY specified\n"));
499 		} else {
500 			est->sc_repo_doorname = safe_strdup(cp);
501 		}
502 	}
503 
504 	cp = getenv("SVCCFG_CONFIGD_PATH");
505 	est->sc_repo_server = cp ? cp : "/lib/svc/bin/svc.configd";
506 
507 	est->sc_in_emi = 0;
508 	cp = getenv("SMF_FMRI");
509 	if ((cp != NULL) && (strcmp(cp, SCF_INSTANCE_EMI) == 0))
510 		est->sc_in_emi = 1;
511 
512 	cp = smf_get_state(SCF_INSTANCE_FS_MINIMAL);
513 	if (cp && (strcmp(cp, SCF_STATE_STRING_ONLINE) == 0))
514 		est->sc_fs_minimal = B_TRUE;
515 	free((void *) cp);
516 }
517 
518 static int
519 import_manifest_file(manifest_info_t *info, boolean_t validate, FILE *pout,
520     uint_t flags)
521 {
522 	bundle_t *b;
523 	tmpl_errors_t *errs;
524 	const char *file;
525 	tmpl_validate_status_t vr;
526 
527 	file = info->mi_path;
528 
529 	/* Load the manifest */
530 	b = internal_bundle_new();
531 
532 	if (lxml_get_bundle_file(b, file, SVCCFG_OP_IMPORT) != 0) {
533 		internal_bundle_free(b);
534 		return (-1);
535 	}
536 
537 	/* Validate */
538 	if ((vr = tmpl_validate_bundle(b, &errs)) != TVS_SUCCESS) {
539 		char *prefix;
540 
541 		if ((validate == 0) || (vr == TVS_WARN)) {
542 			prefix = gettext("Warning: ");
543 		} else {
544 			prefix = "";
545 		}
546 		tmpl_errors_print(stderr, errs, prefix);
547 		if (validate && (vr != TVS_WARN)) {
548 			tmpl_errors_destroy(errs);
549 			semerr(gettext("Import of %s failed.\n"),
550 			    info->mi_path);
551 			if (pout != NULL) {
552 				(void) fprintf(pout, gettext("WARNING: svccfg "
553 				    "import of %s failed.\n"), info->mi_path);
554 			}
555 
556 			return (-1);
557 		}
558 	}
559 	tmpl_errors_destroy(errs);
560 
561 	/* Import */
562 	if (lscf_bundle_import(b, file, flags) != 0) {
563 		internal_bundle_free(b);
564 		semerr(gettext("Import of %s failed.\n"), info->mi_path);
565 		if (pout != NULL) {
566 			(void) fprintf(pout, gettext("WARNING: svccfg import "
567 			    "of %s failed.\n"), info->mi_path);
568 		}
569 		return (-1);
570 	}
571 
572 	internal_bundle_free(b);
573 
574 	if (info->mi_prop) {
575 		char *errstr;
576 
577 		if (mhash_store_entry(g_hndl, info->mi_prop, file,
578 		    info->mi_hash, APPLY_NONE, &errstr)) {
579 			if (errstr)
580 				semerr(gettext("Could not store hash for %s. "
581 				    "%s\n"), info->mi_path, errstr);
582 			else
583 				semerr(gettext("Unknown error from "
584 				    "mhash_store_entry() for %s\n"),
585 				    info->mi_path);
586 		}
587 
588 	}
589 
590 	return (0);
591 }
592 
593 /*
594  * Return values:
595  *	1	No manifests need to be imported.
596  *	0	Success
597  *	-1	Error
598  *	-2	Syntax error
599  */
600 int
601 engine_import(uu_list_t *args)
602 {
603 	int argc, i, o;
604 	int dont_exit;
605 	int failed_manifests;
606 	int total_manifests;
607 	char *file;
608 	char **argv = NULL;
609 	string_list_t *slp;
610 	boolean_t validate = B_FALSE;
611 	uint_t flags = SCI_GENERALLAST;
612 	int dirarg = 0;
613 	int isdir;
614 	int rc = -1;
615 	struct stat sb;
616 	char **paths;
617 	manifest_info_t ***manifest_sets = NULL;
618 	manifest_info_t **manifests;
619 	char *progress_file = NULL;
620 	FILE *progress_out = NULL;
621 	int progress_count;
622 	int back_count;
623 	int count;
624 	int fm_flags;
625 
626 	argc = uu_list_numnodes(args);
627 	if (argc < 1)
628 		return (-2);
629 
630 	argv = calloc(argc + 1, sizeof (char *));
631 	if (argv == NULL)
632 		uu_die(gettext("Out of memory.\n"));
633 
634 	for (slp = uu_list_first(args), i = 0;
635 	    slp != NULL;
636 	    slp = uu_list_next(args, slp), ++i)
637 		argv[i] = slp->str;
638 
639 	argv[i] = NULL;
640 
641 	opterr = 0;
642 	optind = 0;				/* Remember, no argv[0]. */
643 	for (;;) {
644 		o = getopt(argc, argv, "np:V");
645 		if (o == -1)
646 			break;
647 
648 		switch (o) {
649 		case 'n':
650 			flags |= SCI_NOREFRESH;
651 			break;
652 
653 		case 'p':
654 			progress_file = optarg;
655 			break;
656 
657 		case 'V':
658 			validate = B_TRUE;
659 			break;
660 
661 		case '?':
662 			free(argv);
663 			return (-2);
664 
665 		default:
666 			bad_error("getopt", o);
667 		}
668 	}
669 
670 	argc -= optind;
671 	if (argc < 1) {
672 		free(argv);
673 		return (-2);
674 	}
675 
676 	/* Open device for progress messages */
677 	if (progress_file != NULL) {
678 		if (strcmp(progress_file, "-") == 0) {
679 			progress_out = stdout;
680 		} else {
681 			progress_out = fopen(progress_file, "w");
682 			if (progress_out == NULL) {
683 				semerr(gettext("Unable to open %s for "
684 				    "progress reporting.  %s\n"),
685 				    progress_file, strerror(errno));
686 				goto out;
687 			}
688 			setbuf(progress_out, NULL);
689 		}
690 	}
691 
692 	paths = argv+optind;
693 	manifest_sets = safe_malloc(argc * sizeof (*manifest_sets));
694 
695 	/* If we're in interactive mode, force strict validation. */
696 	if (est->sc_cmd_flags & SC_CMD_IACTIVE)
697 		validate = B_TRUE;
698 
699 	lscf_prep_hndl();
700 
701 	/* Determine which manifests must be imported. */
702 
703 	total_manifests = 0;
704 	for (i = 0; i < argc; i++) {
705 		file = *(paths + i);
706 		fm_flags = CHECKHASH;
707 
708 		/* Determine if argument is a directory or file. */
709 		if (stat(file, &sb) == -1) {
710 			semerr(gettext("Unable to stat file %s.  %s\n"), file,
711 			    strerror(errno));
712 			goto out;
713 		}
714 		if (sb.st_mode & S_IFDIR) {
715 			fm_flags |= CHECKEXT;
716 			dirarg = 1;
717 			isdir = 1;
718 		} else if (sb.st_mode & S_IFREG) {
719 			isdir = 0;
720 		} else {
721 			semerr(gettext("%s is not a directory or regular "
722 			    "file\n"), file);
723 			goto out;
724 		}
725 
726 		/* Get list of manifests that we should import for this path. */
727 		if ((count = find_manifests(file, &manifests, fm_flags)) < 0) {
728 			if (isdir) {
729 				semerr(gettext("Could not hash directory %s\n"),
730 				    file);
731 			} else {
732 				semerr(gettext("Could not hash file %s\n"),
733 				    file);
734 			}
735 			free_manifest_array(manifests);
736 			goto out;
737 		}
738 		total_manifests += count;
739 		manifest_sets[i] = manifests;
740 	}
741 
742 	if (total_manifests == 0) {
743 		/* No manifests to process. */
744 		if (g_verbose) {
745 			warn(gettext("No changes were necessary\n"));
746 		}
747 		rc = 1;
748 		goto out;
749 	}
750 
751 	/*
752 	 * If we're processing more than one file, we don't want to exit if
753 	 * we encounter an error.  We should go ahead and process all of
754 	 * the manifests.
755 	 */
756 	dont_exit = est->sc_cmd_flags & SC_CMD_DONT_EXIT;
757 	if (total_manifests > 1)
758 		est->sc_cmd_flags |= SC_CMD_DONT_EXIT;
759 
760 	if (progress_out != NULL)
761 		(void) fprintf(progress_out,
762 		    "Loading smf(5) service descriptions: ");
763 
764 	failed_manifests = 0;
765 	progress_count = 0;
766 	for (i = 0; i < argc; i++) {
767 		manifests = manifest_sets[i];
768 		if (manifests == NULL)
769 			continue;
770 		for (; *manifests != NULL; manifests++) {
771 			progress_count++;
772 			if (progress_out != NULL) {
773 				back_count = fprintf(progress_out, "%d/%d",
774 				    progress_count, total_manifests);
775 				while (back_count-- > 0) {
776 					(void) fputc('\b', progress_out);
777 				}
778 			}
779 			if (import_manifest_file(*manifests, validate,
780 			    progress_out, flags) != 0) {
781 				failed_manifests++;
782 			}
783 		}
784 	}
785 	if (progress_out != NULL)
786 		(void) fputc('\n', progress_out);
787 
788 	if ((total_manifests > 1) && (dont_exit == 0))
789 		est->sc_cmd_flags &= ~SC_CMD_DONT_EXIT;
790 
791 	if (dirarg && total_manifests > 0) {
792 		char *msg;
793 
794 		msg = "Loaded %d smf(5) service descriptions\n";
795 		warn(gettext(msg), progress_count);
796 
797 		if (failed_manifests) {
798 			msg = "%d smf(5) service descriptions failed to load\n";
799 			warn(gettext(msg), failed_manifests);
800 		}
801 	}
802 
803 	if (failed_manifests > 0)
804 		goto out;
805 
806 	if (g_verbose)
807 		warn(gettext("Successful import.\n"));
808 	rc = 0;
809 
810 out:
811 	if ((progress_out != NULL) && (progress_out != stdout))
812 		(void) fclose(progress_out);
813 	free(argv);
814 	if (manifest_sets != NULL) {
815 		for (i = 0; i < argc; i++) {
816 			free_manifest_array(manifest_sets[i]);
817 		}
818 		free(manifest_sets);
819 	}
820 	return (rc);
821 }
822 
823 /*
824  * Walk each service and get its manifest file.
825  *
826  * If the file exists check instance support, and cleanup any
827  * stale instances.
828  *
829  * If the file doesn't exist tear down the service and/or instances
830  * that are no longer supported by files.
831  */
832 int
833 engine_cleanup(int flags)
834 {
835 	boolean_t		activity = B_TRUE;
836 	int			r = -1;
837 
838 	lscf_prep_hndl();
839 
840 	if (flags == 1) {
841 		activity = B_FALSE;
842 	}
843 
844 	if (scf_walk_fmri(g_hndl, 0, NULL, SCF_WALK_SERVICE|SCF_WALK_NOINSTANCE,
845 	    lscf_service_cleanup, (void *)activity, NULL,
846 	    uu_warn) == SCF_SUCCESS)
847 		r = 0;
848 
849 	(void) lscf_hash_cleanup();
850 
851 	return (r);
852 }
853 
854 static int
855 apply_profile(manifest_info_t *info, int apply_changes)
856 {
857 	bundle_t *b = internal_bundle_new();
858 
859 	if (lxml_get_bundle_file(b, info->mi_path, SVCCFG_OP_APPLY) != 0) {
860 		internal_bundle_free(b);
861 		return (-1);
862 	}
863 
864 	if (!apply_changes) {	/* we don't want to apply, just test */
865 		internal_bundle_free(b);
866 		return (0);
867 	}
868 
869 	if (lscf_bundle_apply(b, info->mi_path) != 0) {
870 		internal_bundle_free(b);
871 		return (-1);
872 	}
873 
874 	internal_bundle_free(b);
875 
876 	if (info->mi_prop) {
877 		apply_action_t apply;
878 		char *errstr;
879 
880 		apply = (est->sc_in_emi == 1) ? APPLY_LATE : APPLY_NONE;
881 		if (mhash_store_entry(g_hndl, info->mi_prop, info->mi_path,
882 		    info->mi_hash, apply, &errstr)) {
883 			semerr(errstr);
884 		}
885 	}
886 
887 	return (0);
888 }
889 
890 int
891 engine_apply(const char *file, int apply_changes)
892 {
893 	int rc = 0;
894 	int isdir;
895 	int dont_exit;
896 	int profile_count;
897 	int fm_flags;
898 	struct stat sb;
899 	manifest_info_t **profiles = NULL;
900 	manifest_info_t **entry;
901 	manifest_info_t *pfile;
902 
903 	lscf_prep_hndl();
904 
905 	/* Determine which profile(s) must be applied. */
906 
907 	profile_count = 0;
908 	fm_flags = BUNDLE_PROF | CHECKHASH;
909 
910 	/* Determine if argument is a directory or file. */
911 	if (stat(file, &sb) == -1) {
912 		semerr(gettext("Unable to stat file %s.  %s\n"), file,
913 		    strerror(errno));
914 		rc = -1;
915 		goto out;
916 	}
917 
918 	if (sb.st_mode & S_IFDIR) {
919 		fm_flags |= CHECKEXT;
920 		isdir = 1;
921 	} else if (sb.st_mode & S_IFREG) {
922 		isdir = 0;
923 	} else {
924 		semerr(gettext("%s is not a directory or regular "
925 		    "file\n"), file);
926 		rc = -1;
927 		goto out;
928 	}
929 
930 	/* Get list of profiles to be applied. */
931 	if ((profile_count = find_manifests(file, &profiles, fm_flags)) < 0) {
932 		if (isdir) {
933 			semerr(gettext("Could not hash directory %s\n"), file);
934 		} else {
935 			semerr(gettext("Could not hash file %s\n"), file);
936 		}
937 		rc = -1;
938 		goto out;
939 	}
940 
941 	if (profile_count == 0) {
942 		/* No profiles to process. */
943 		if (g_verbose) {
944 			warn(gettext("No changes were necessary\n"));
945 		}
946 		goto out;
947 	}
948 
949 	/*
950 	 * We don't want to exit if we encounter an error.  We should go ahead
951 	 * and process all of the profiles.
952 	 */
953 	dont_exit = est->sc_cmd_flags & SC_CMD_DONT_EXIT;
954 	est->sc_cmd_flags |= SC_CMD_DONT_EXIT;
955 
956 	for (entry = profiles; *entry != NULL; entry++) {
957 		pfile = *entry;
958 
959 		if (apply_profile(pfile, apply_changes) == 0) {
960 			if (g_verbose) {
961 				warn(gettext("Successfully applied: %s\n"),
962 				    pfile->mi_path);
963 			}
964 		} else {
965 			warn(gettext("WARNING: Failed to apply %s\n"),
966 			    pfile->mi_path);
967 			rc = -1;
968 		}
969 	}
970 
971 	if (dont_exit == 0)
972 		est->sc_cmd_flags &= ~SC_CMD_DONT_EXIT;
973 
974 	/* exit(1) appropriately if any profile failed to be applied. */
975 	if ((rc == -1) &&
976 	    (est->sc_cmd_flags & (SC_CMD_IACTIVE | SC_CMD_DONT_EXIT)) == 0) {
977 		free_manifest_array(profiles);
978 		exit(1);
979 	}
980 
981 out:
982 	free_manifest_array(profiles);
983 	return (rc);
984 }
985 
986 int
987 engine_restore(const char *file)
988 {
989 	bundle_t *b;
990 
991 	lscf_prep_hndl();
992 
993 	b = internal_bundle_new();
994 
995 	if (lxml_get_bundle_file(b, file, SVCCFG_OP_RESTORE) != 0) {
996 		internal_bundle_free(b);
997 		return (-1);
998 	}
999 
1000 	if (lscf_bundle_import(b, file, SCI_NOSNAP) != 0) {
1001 		internal_bundle_free(b);
1002 		return (-1);
1003 	}
1004 
1005 	internal_bundle_free(b);
1006 
1007 	return (0);
1008 }
1009 
1010 int
1011 engine_set(uu_list_t *args)
1012 {
1013 	uu_list_walk_t *walk;
1014 	string_list_t *slp;
1015 
1016 	if (uu_list_first(args) == NULL) {
1017 		/* Display current options. */
1018 		if (!g_verbose)
1019 			(void) fputs("no", stdout);
1020 		(void) puts("verbose");
1021 
1022 		return (0);
1023 	}
1024 
1025 	walk = uu_list_walk_start(args, UU_DEFAULT);
1026 	if (walk == NULL)
1027 		uu_die(gettext("Couldn't read arguments"));
1028 
1029 	/* Use getopt? */
1030 	for (slp = uu_list_walk_next(walk);
1031 	    slp != NULL;
1032 	    slp = uu_list_walk_next(walk)) {
1033 		if (slp->str[0] == '-') {
1034 			char *op;
1035 
1036 			for (op = &slp->str[1]; *op != '\0'; ++op) {
1037 				switch (*op) {
1038 				case 'v':
1039 					g_verbose = 1;
1040 					break;
1041 
1042 				case 'V':
1043 					g_verbose = 0;
1044 					break;
1045 
1046 				default:
1047 					warn(gettext("Unknown option -%c.\n"),
1048 					    *op);
1049 				}
1050 			}
1051 		} else {
1052 			warn(gettext("No non-flag arguments defined.\n"));
1053 		}
1054 	}
1055 
1056 	return (0);
1057 }
1058 
1059 void
1060 help(int com)
1061 {
1062 	int i;
1063 
1064 	if (com == 0) {
1065 		warn(gettext("General commands:	 help set repository end\n"
1066 		    "Manifest commands:	 inventory validate import export "
1067 		    "archive\n"
1068 		    "Profile commands:	 apply extract\n"
1069 		    "Entity commands:	 list select unselect add delete "
1070 		    "describe\n"
1071 		    "Snapshot commands:	 listsnap selectsnap revert\n"
1072 		    "Instance commands:	 refresh\n"
1073 		    "Property group commands: listpg addpg delpg\n"
1074 		    "Property commands:	 listprop setprop delprop editprop\n"
1075 		    "Property value commands: addpropvalue delpropvalue "
1076 		    "setenv unsetenv\n"));
1077 		return;
1078 	}
1079 
1080 	for (i = 0; help_messages[i].message != NULL; ++i) {
1081 		if (help_messages[i].token == com) {
1082 			warn(gettext("Usage: %s\n"),
1083 			    gettext(help_messages[i].message));
1084 			return;
1085 		}
1086 	}
1087 
1088 	warn(gettext("Unknown command.\n"));
1089 }
1090