xref: /netbsd/usr.bin/xinstall/xinstall.c (revision 8d5e7ecc)
1 /*	$NetBSD: xinstall.c,v 1.127 2023/07/20 16:21:23 lukem Exp $	*/
2 
3 /*
4  * Copyright (c) 1987, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*-
33  * Copyright (c) 2015 The NetBSD Foundation, Inc.
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to The NetBSD Foundation
37  * by Christos Zoulas.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
49  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
50  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
51  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
52  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
53  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
54  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
55  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
56  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
57  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
58  * POSSIBILITY OF SUCH DAMAGE.
59  */
60 
61 #define __MKTEMP_OK__	/* All uses of mktemp have been checked */
62 
63 #if HAVE_NBTOOL_CONFIG_H
64 #include "nbtool_config.h"
65 #else
66 #define HAVE_FUTIMES 1
67 #define HAVE_POSIX_SPAWN 1
68 #define HAVE_STRUCT_STAT_ST_FLAGS 1
69 #endif
70 
71 #include <sys/cdefs.h>
72 #if defined(__COPYRIGHT) && !defined(lint)
73 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\
74  The Regents of the University of California.  All rights reserved.");
75 #endif /* not lint */
76 
77 #if defined(__RCSID) && !defined(lint)
78 #if 0
79 static char sccsid[] = "@(#)xinstall.c	8.1 (Berkeley) 7/21/93";
80 #else
81 __RCSID("$NetBSD: xinstall.c,v 1.127 2023/07/20 16:21:23 lukem Exp $");
82 #endif
83 #endif /* not lint */
84 
85 #include <sys/param.h>
86 #include <sys/mman.h>
87 #include <sys/stat.h>
88 #include <sys/wait.h>
89 #include <sys/time.h>
90 
91 #include <ctype.h>
92 #include <err.h>
93 #include <errno.h>
94 #include <fcntl.h>
95 #include <grp.h>
96 #include <libgen.h>
97 #include <paths.h>
98 #include <pwd.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <unistd.h>
103 #include <util.h>
104 #include <vis.h>
105 
106 #ifdef HAVE_POSIX_SPAWN
107 #include <spawn.h>
108 #endif
109 
110 #include <md5.h>
111 #include <rmd160.h>
112 #include <sha1.h>
113 #include <sha2.h>
114 
115 #include "pathnames.h"
116 #include "mtree.h"
117 
118 #define BACKUP_SUFFIX ".old"
119 
120 static int	dobackup, dodir, dostrip, dolink, dopreserve, dorename, dounpriv;
121 static int	haveopt_f, haveopt_g, haveopt_m, haveopt_o;
122 static int	numberedbackup;
123 static int	mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
124 static char	pathbuf[MAXPATHLEN];
125 static uid_t	uid = -1;
126 static gid_t	gid = -1;
127 static char	*group, *owner, *fflags, *tags;
128 static FILE	*metafp;
129 static char	*metafile;
130 static u_long	fileflags;
131 static char	*stripArgs;
132 static char	*afterinstallcmd;
133 static const char *suffix = BACKUP_SUFFIX;
134 static char	*destdir;
135 
136 enum {
137 	DIGEST_NONE = 0,
138 	DIGEST_MD5,
139 	DIGEST_RMD160,
140 	DIGEST_SHA1,
141 	DIGEST_SHA256,
142 	DIGEST_SHA384,
143 	DIGEST_SHA512,
144 } digesttype = DIGEST_NONE;
145 
146 static char	*digest;
147 
148 #define LN_ABSOLUTE	0x01
149 #define LN_RELATIVE	0x02
150 #define LN_HARD		0x04
151 #define LN_SYMBOLIC	0x08
152 #define LN_MIXED	0x10
153 
154 #define	DIRECTORY	0x01		/* Tell install it's a directory. */
155 #define	SETFLAGS	0x02		/* Tell install to set flags. */
156 #define	HASUID		0x04		/* Tell install the uid was given */
157 #define	HASGID		0x08		/* Tell install the gid was given */
158 
159 static void	afterinstall(const char *, const char *, int);
160 static void	backup(const char *);
161 static char   *copy(int, char *, int, char *, off_t);
162 static int	do_link(char *, char *);
163 static void	do_symlink(char *, char *);
164 static void	install(char *, char *, u_int);
165 static void	install_dir(char *, u_int);
166 static void	makelink(char *, char *);
167 static void	metadata_log(const char *, const char *, struct timeval *,
168 	    const char *, const char *, off_t);
169 static int	parseid(char *, id_t *);
170 static void 	run(const char *, const char *, const char *, int);
171 static void	strip(const char *);
172 __dead static void	usage(void);
173 static char   *xbasename(char *);
174 static char   *xdirname(char *);
175 static int	needshell(const char *, int);
176 
177 int
main(int argc,char * argv[])178 main(int argc, char *argv[])
179 {
180 	struct stat	from_sb, to_sb;
181 	void		*set;
182 	u_int		iflags;
183 	int		ch, no_target;
184 	char		*p, *to_name;
185 
186 	setprogname(argv[0]);
187 
188 	iflags = 0;
189 	while ((ch = getopt(argc, argv, "a:cbB:dD:f:g:h:l:m:M:N:o:prsS:T:U"))
190 	    != -1)
191 		switch((char)ch) {
192 		case 'a':
193 			afterinstallcmd = strdup(optarg);
194 			if (afterinstallcmd == NULL)
195 				err(EXIT_FAILURE,
196 				    "Can't allocate after command");
197 			break;
198 		case 'B':
199 			suffix = optarg;
200 			numberedbackup = 0;
201 			{
202 				/* Check if given suffix really generates
203 				   different suffixes - catch e.g. ".%" */
204 				char suffix_expanded0[FILENAME_MAX],
205 				     suffix_expanded1[FILENAME_MAX];
206 				(void)snprintf(suffix_expanded0, FILENAME_MAX,
207 					       suffix, 0);
208 				(void)snprintf(suffix_expanded1, FILENAME_MAX,
209 					       suffix, 1);
210 				if (strcmp(suffix_expanded0, suffix_expanded1)
211 				    != 0)
212 					numberedbackup = 1;
213 			}
214 			/* fall through; -B implies -b */
215 			/*FALLTHROUGH*/
216 		case 'b':
217 			dobackup = 1;
218 			break;
219 		case 'c':
220 			/* ignored; was "docopy" which is now the default. */
221 			break;
222 		case 'd':
223 			dodir = 1;
224 			break;
225 		case 'D':
226 			destdir = optarg;
227 			break;
228 #if ! HAVE_NBTOOL_CONFIG_H
229 		case 'f':
230 			haveopt_f = 1;
231 			fflags = optarg;
232 			break;
233 #endif
234 		case 'g':
235 			haveopt_g = 1;
236 			group = optarg;
237 			break;
238 		case 'h':
239 			digest = optarg;
240 			break;
241 		case 'l':
242 			for (p = optarg; *p; p++)
243 				switch (*p) {
244 				case 's':
245 					dolink &= ~(LN_HARD|LN_MIXED);
246 					dolink |= LN_SYMBOLIC;
247 					break;
248 				case 'h':
249 					dolink &= ~(LN_SYMBOLIC|LN_MIXED);
250 					dolink |= LN_HARD;
251 					break;
252 				case 'm':
253 					dolink &= ~(LN_SYMBOLIC|LN_HARD);
254 					dolink |= LN_MIXED;
255 					break;
256 				case 'a':
257 					dolink &= ~LN_RELATIVE;
258 					dolink |= LN_ABSOLUTE;
259 					break;
260 				case 'r':
261 					dolink &= ~LN_ABSOLUTE;
262 					dolink |= LN_RELATIVE;
263 					break;
264 				default:
265 					errx(EXIT_FAILURE, "%c: invalid link type", *p);
266 					/* NOTREACHED */
267 				}
268 			break;
269 		case 'm':
270 			haveopt_m = 1;
271 			if (!(set = setmode(optarg)))
272 				err(EXIT_FAILURE, "Cannot set file mode `%s'", optarg);
273 			mode = getmode(set, 0);
274 			free(set);
275 			break;
276 		case 'M':
277 			metafile = optarg;
278 			break;
279 		case 'N':
280 			if (! setup_getid(optarg))
281 				errx(EXIT_FAILURE,
282 			    "Unable to use user and group databases in `%s'",
283 				    optarg);
284 			break;
285 		case 'o':
286 			haveopt_o = 1;
287 			owner = optarg;
288 			break;
289 		case 'p':
290 			dopreserve = 1;
291 			break;
292 		case 'r':
293 			dorename = 1;
294 			break;
295 		case 'S':
296 			stripArgs = strdup(optarg);
297 			if (stripArgs == NULL)
298 				err(EXIT_FAILURE, "Can't allocate options");
299 			/* fall through; -S implies -s */
300 			/*FALLTHROUGH*/
301 		case 's':
302 			dostrip = 1;
303 			break;
304 		case 'T':
305 			tags = optarg;
306 			break;
307 		case 'U':
308 			dounpriv = 1;
309 			break;
310 		case '?':
311 		default:
312 			usage();
313 		}
314 	argc -= optind;
315 	argv += optind;
316 
317 	/* strip and link options make no sense when creating directories */
318 	if ((dostrip || dolink) && dodir)
319 		usage();
320 
321 	/* strip and flags make no sense with links */
322 	if ((dostrip || fflags) && dolink)
323 		usage();
324 
325 	/* must have at least two arguments, except when creating directories */
326 	if (argc < 2 && !dodir)
327 		usage();
328 
329 	if (digest) {
330 		if (0) {
331 		} else if (strcmp(digest, "none") == 0) {
332 			digesttype = DIGEST_NONE;
333 		} else if (strcmp(digest, "md5") == 0) {
334 			digesttype = DIGEST_MD5;
335 		} else if (strcmp(digest, "rmd160") == 0) {
336 			digesttype = DIGEST_RMD160;
337 		} else if (strcmp(digest, "sha1") == 0) {
338 			digesttype = DIGEST_SHA1;
339 		} else if (strcmp(digest, "sha256") == 0) {
340 			digesttype = DIGEST_SHA256;
341 		} else if (strcmp(digest, "sha384") == 0) {
342 			digesttype = DIGEST_SHA384;
343 		} else if (strcmp(digest, "sha512") == 0) {
344 			digesttype = DIGEST_SHA512;
345 		} else {
346 			warnx("unknown digest `%s'", digest);
347 			usage();
348 		}
349 	}
350 
351 	/* get group and owner id's */
352 	if (group && !dounpriv) {
353 		if (gid_from_group(group, &gid) == -1) {
354 			id_t id;
355 			if (!parseid(group, &id))
356 				errx(EXIT_FAILURE, "unknown group %s", group);
357 			gid = id;
358 		}
359 		iflags |= HASGID;
360 	}
361 	if (owner && !dounpriv) {
362 		if (uid_from_user(owner, &uid) == -1) {
363 			id_t id;
364 			if (!parseid(owner, &id))
365 				errx(EXIT_FAILURE, "unknown user %s", owner);
366 			uid = id;
367 		}
368 		iflags |= HASUID;
369 	}
370 
371 #if ! HAVE_NBTOOL_CONFIG_H
372 	if (fflags && !dounpriv) {
373 		if (string_to_flags(&fflags, &fileflags, NULL))
374 			errx(EXIT_FAILURE, "%s: invalid flag", fflags);
375 		/* restore fflags since string_to_flags() changed it */
376 		fflags = flags_to_string(fileflags, "-");
377 		iflags |= SETFLAGS;
378 	}
379 #endif
380 
381 	if (metafile) {
382 		if ((metafp = fopen(metafile, "a")) == NULL)
383 			warn("open %s", metafile);
384 	} else
385 		digesttype = DIGEST_NONE;
386 
387 	if (dodir) {
388 		for (; *argv != NULL; ++argv)
389 			install_dir(*argv, iflags);
390 		exit (0);
391 	}
392 
393 	no_target = stat(to_name = argv[argc - 1], &to_sb);
394 	if (!no_target && S_ISDIR(to_sb.st_mode)) {
395 		for (; *argv != to_name; ++argv)
396 			install(*argv, to_name, iflags | DIRECTORY);
397 		exit(0);
398 	}
399 
400 	/* can't do file1 file2 directory/file */
401 	if (argc != 2) {
402 		errx(EXIT_FAILURE, "the last argument (%s) "
403 		    "must name an existing directory", argv[argc - 1]);
404 		/* NOTREACHED */
405 	}
406 
407 	if (!no_target) {
408 		/* makelink() handles checks for links */
409 		if (!dolink) {
410 			if (stat(*argv, &from_sb))
411 				err(EXIT_FAILURE, "%s: stat", *argv);
412 			if (!S_ISREG(to_sb.st_mode))
413 				errx(EXIT_FAILURE, "%s: not a regular file", to_name);
414 			if (to_sb.st_dev == from_sb.st_dev &&
415 			    to_sb.st_ino == from_sb.st_ino)
416 				errx(EXIT_FAILURE, "%s and %s are the same file", *argv,
417 				    to_name);
418 		}
419 		/*
420 		 * Unlink now... avoid ETXTBSY errors later.  Try and turn
421 		 * off the append/immutable bits -- if we fail, go ahead,
422 		 * it might work.
423 		 */
424 #if ! HAVE_NBTOOL_CONFIG_H
425 #define	NOCHANGEBITS	(UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
426 		if (to_sb.st_flags & NOCHANGEBITS)
427 			(void)chflags(to_name,
428 			    to_sb.st_flags & ~(NOCHANGEBITS));
429 #endif
430 		if (dobackup)
431 			backup(to_name);
432 		else if (!dorename)
433 			(void)unlink(to_name);
434 	}
435 	install(*argv, to_name, iflags);
436 	exit(0);
437 }
438 
439 /*
440  * parseid --
441  *	parse uid or gid from arg into id, returning non-zero if successful
442  */
443 static int
parseid(char * name,id_t * id)444 parseid(char *name, id_t *id)
445 {
446 	char	*ep;
447 
448 	errno = 0;
449 	*id = (id_t)strtoul(name, &ep, 10);
450 	if (errno || *ep != '\0')
451 		return (0);
452 	return (1);
453 }
454 
455 /*
456  * do_link --
457  *	make a hard link, obeying dorename if set
458  *	return -1 on failure
459  */
460 static int
do_link(char * from_name,char * to_name)461 do_link(char *from_name, char *to_name)
462 {
463 	char tmpl[MAXPATHLEN];
464 	int ret;
465 
466 	if (dorename) {
467 		(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
468 		/* This usage is safe. */
469 		if (mktemp(tmpl) == NULL)
470 			err(EXIT_FAILURE, "%s: mktemp", tmpl);
471 		ret = link(from_name, tmpl);
472 		if (ret == 0) {
473 			ret = rename(tmpl, to_name);
474 			/* If rename has posix semantics, then the temporary
475 			 * file may still exist when from_name and to_name point
476 			 * to the same file, so unlink it unconditionally.
477 			 */
478 			(void)unlink(tmpl);
479 		}
480 		return (ret);
481 	} else
482 		return (link(from_name, to_name));
483 }
484 
485 /*
486  * do_symlink --
487  *	make a symbolic link, obeying dorename if set
488  *	exit on failure
489  */
490 static void
do_symlink(char * from_name,char * to_name)491 do_symlink(char *from_name, char *to_name)
492 {
493 	char tmpl[MAXPATHLEN];
494 
495 	if (dorename) {
496 		(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
497 		/* This usage is safe. */
498 		if (mktemp(tmpl) == NULL)
499 			err(EXIT_FAILURE, "%s: mktemp", tmpl);
500 
501 		if (symlink(from_name, tmpl) == -1)
502 			err(EXIT_FAILURE, "symlink %s -> %s", from_name, tmpl);
503 		if (rename(tmpl, to_name) == -1) {
504 			/* remove temporary link before exiting */
505 			(void)unlink(tmpl);
506 			err(EXIT_FAILURE, "%s: rename", to_name);
507 		}
508 	} else {
509 		if (symlink(from_name, to_name) == -1)
510 			err(EXIT_FAILURE, "symlink %s -> %s", from_name, to_name);
511 	}
512 }
513 
514 /*
515  * makelink --
516  *	make a link from source to destination
517  */
518 static void
makelink(char * from_name,char * to_name)519 makelink(char *from_name, char *to_name)
520 {
521 	char	src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
522 	struct stat	to_sb;
523 
524 	/* Try hard links first */
525 	if (dolink & (LN_HARD|LN_MIXED)) {
526 		if (do_link(from_name, to_name) == -1) {
527 			if ((dolink & LN_HARD) || errno != EXDEV)
528 				err(EXIT_FAILURE, "link %s -> %s", from_name, to_name);
529 		} else {
530 			if (stat(to_name, &to_sb))
531 				err(EXIT_FAILURE, "%s: stat", to_name);
532 			if (S_ISREG(to_sb.st_mode)) {
533 					/* XXX: hard links to anything
534 					 * other than plain files are not
535 					 * metalogged
536 					 */
537 				int omode;
538 				char *oowner, *ogroup, *offlags;
539 				char *dres;
540 
541 					/* XXX: use underlying perms,
542 					 * unless overridden on command line.
543 					 */
544 				omode = mode;
545 				if (!haveopt_m)
546 					mode = (to_sb.st_mode & 0777);
547 				oowner = owner;
548 				if (!haveopt_o)
549 					owner = NULL;
550 				ogroup = group;
551 				if (!haveopt_g)
552 					group = NULL;
553 				offlags = fflags;
554 				if (!haveopt_f)
555 					fflags = NULL;
556 				switch (digesttype) {
557 				case DIGEST_MD5:
558 					dres = MD5File(from_name, NULL);
559 					break;
560 				case DIGEST_RMD160:
561 					dres = RMD160File(from_name, NULL);
562 					break;
563 				case DIGEST_SHA1:
564 					dres = SHA1File(from_name, NULL);
565 					break;
566 				case DIGEST_SHA256:
567 					dres = SHA256_File(from_name, NULL);
568 					break;
569 				case DIGEST_SHA384:
570 					dres = SHA384_File(from_name, NULL);
571 					break;
572 				case DIGEST_SHA512:
573 					dres = SHA512_File(from_name, NULL);
574 					break;
575 				default:
576 					dres = NULL;
577 				}
578 				metadata_log(to_name, "file", NULL, NULL,
579 				    dres, to_sb.st_size);
580 				free(dres);
581 				mode = omode;
582 				owner = oowner;
583 				group = ogroup;
584 				fflags = offlags;
585 			}
586 			return;
587 		}
588 	}
589 
590 	/* Symbolic links */
591 	if (dolink & LN_ABSOLUTE) {
592 		/* Convert source path to absolute */
593 		if (realpath(from_name, src) == NULL)
594 			err(EXIT_FAILURE, "%s: realpath", from_name);
595 		do_symlink(src, to_name);
596 			/* XXX: src may point outside of destdir */
597 		metadata_log(to_name, "link", NULL, src, NULL, 0);
598 		return;
599 	}
600 
601 	if (dolink & LN_RELATIVE) {
602 		char *cp, *d, *s;
603 
604 		/* Resolve pathnames */
605 		if (realpath(from_name, src) == NULL)
606 			err(EXIT_FAILURE, "%s: realpath", from_name);
607 
608 		/*
609 		 * The last component of to_name may be a symlink,
610 		 * so use realpath to resolve only the directory.
611 		 */
612 		cp = xdirname(to_name);
613 		if (realpath(cp, dst) == NULL)
614 			err(EXIT_FAILURE, "%s: realpath", cp);
615 		/* .. and add the last component */
616 		if (strcmp(dst, "/") != 0) {
617 			if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
618 				errx(EXIT_FAILURE, "resolved pathname too long");
619 		}
620 		cp = xbasename(to_name);
621 		if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
622 			errx(EXIT_FAILURE, "resolved pathname too long");
623 
624 		/* trim common path components */
625 		for (s = src, d = dst; *s == *d; s++, d++)
626 			continue;
627 		while (*s != '/')
628 			s--, d--;
629 
630 		/* count the number of directories we need to backtrack */
631 		for (++d, lnk[0] = '\0'; *d; d++)
632 			if (*d == '/')
633 				(void)strlcat(lnk, "../", sizeof(lnk));
634 
635 		(void)strlcat(lnk, ++s, sizeof(lnk));
636 
637 		do_symlink(lnk, to_name);
638 			/* XXX: lnk may point outside of destdir */
639 		metadata_log(to_name, "link", NULL, lnk, NULL, 0);
640 		return;
641 	}
642 
643 	/*
644 	 * If absolute or relative was not specified,
645 	 * try the names the user provided
646 	 */
647 	do_symlink(from_name, to_name);
648 		/* XXX: from_name may point outside of destdir */
649 	metadata_log(to_name, "link", NULL, from_name, NULL, 0);
650 }
651 
652 /*
653  * install --
654  *	build a path name and install the file
655  */
656 static void
install(char * from_name,char * to_name,u_int flags)657 install(char *from_name, char *to_name, u_int flags)
658 {
659 	struct stat	from_sb;
660 	struct stat	to_sb;
661 	struct timeval	tv[2];
662 	off_t		size;
663 	int		devnull, from_fd, to_fd, serrno, tmpmode;
664 	char		*p, tmpl[MAXPATHLEN], *oto_name, *digestresult;
665 
666 	size = -1;
667 	if (!dolink) {
668 			/* ensure that from_sb & tv are sane if !dolink */
669 		if (stat(from_name, &from_sb))
670 			err(EXIT_FAILURE, "%s: stat", from_name);
671 		size = from_sb.st_size;
672 #if BSD4_4 && !HAVE_NBTOOL_CONFIG_H
673 		TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
674 		TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
675 #else
676 		tv[0].tv_sec = from_sb.st_atime;
677 		tv[0].tv_usec = 0;
678 		tv[1].tv_sec = from_sb.st_mtime;
679 		tv[1].tv_usec = 0;
680 #endif
681 	}
682 
683 	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL) != 0) {
684 		devnull = 0;
685 		if (!dolink) {
686 			if (!S_ISREG(from_sb.st_mode))
687 				errx(EXIT_FAILURE, "%s: not a regular file", from_name);
688 		}
689 		/* Build the target path. */
690 		if (flags & DIRECTORY) {
691 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
692 			    to_name,
693 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
694 			to_name = pathbuf;
695 		}
696 	} else {
697 		devnull = 1;
698 		size = 0;
699 #if HAVE_STRUCT_STAT_ST_FLAGS
700 		from_sb.st_flags = 0;	/* XXX */
701 #endif
702 	}
703 
704 	/*
705 	 * Unlink now... avoid ETXTBSY errors later.  Try and turn
706 	 * off the append/immutable bits -- if we fail, go ahead,
707 	 * it might work.
708 	 */
709 #if ! HAVE_NBTOOL_CONFIG_H
710 	if (stat(to_name, &to_sb) == 0 &&
711 	    to_sb.st_flags & (NOCHANGEBITS))
712 		(void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
713 #endif
714 	if (dorename) {
715 		(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
716 		oto_name = to_name;
717 		to_name = tmpl;
718 	} else {
719 		oto_name = NULL;	/* pacify gcc */
720 		if (dobackup)
721 			backup(to_name);
722 		else
723 			(void)unlink(to_name);
724 	}
725 
726 	if (dolink) {
727 		makelink(from_name, dorename ? oto_name : to_name);
728 		return;
729 	}
730 
731 	/* Create target. */
732 	if (dorename) {
733 		if ((to_fd = mkstemp(to_name)) == -1)
734 			err(EXIT_FAILURE, "%s: mkstemp", to_name);
735 	} else {
736 		if ((to_fd = open(to_name,
737 		    O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
738 			err(EXIT_FAILURE, "%s: open", to_name);
739 	}
740 	digestresult = NULL;
741 	if (!devnull) {
742 		if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
743 			(void)unlink(to_name);
744 			err(EXIT_FAILURE, "%s: open", from_name);
745 		}
746 		digestresult =
747 		    copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
748 		(void)close(from_fd);
749 	}
750 
751 	if (dostrip) {
752 		strip(to_name);
753 
754 		/*
755 		 * Re-open our fd on the target, in case we used a strip
756 		 *  that does not work in-place -- like gnu binutils strip.
757 		 */
758 		close(to_fd);
759 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
760 			err(EXIT_FAILURE, "stripping %s", to_name);
761 
762 		/*
763 		 * Recalculate size and digestresult after stripping.
764 		 */
765 		if (fstat(to_fd, &to_sb) != 0)
766 			err(EXIT_FAILURE, "%s: fstat", to_name);
767 		size = to_sb.st_size;
768 		digestresult =
769 		    copy(to_fd, to_name, -1, NULL, size);
770 
771 	}
772 
773 	if (afterinstallcmd != NULL) {
774 		afterinstall(afterinstallcmd, to_name, 1);
775 
776 		/*
777 		 * Re-open our fd on the target, in case we used an
778 		 * after-install command that does not work in-place
779 		 */
780 		close(to_fd);
781 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
782 			err(EXIT_FAILURE, "running after install command on %s", to_name);
783 	}
784 
785 	/*
786 	 * Set owner, group, mode for target; do the chown first,
787 	 * chown may lose the setuid bits.
788 	 */
789 	if (!dounpriv &&
790 	    (flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
791 		serrno = errno;
792 		(void)unlink(to_name);
793 		errc(EXIT_FAILURE, serrno, "%s: chown/chgrp", to_name);
794 	}
795 	tmpmode = mode;
796 	if (dounpriv)
797 		tmpmode &= S_IRWXU|S_IRWXG|S_IRWXO;
798 	if (fchmod(to_fd, tmpmode) == -1) {
799 		serrno = errno;
800 		(void)unlink(to_name);
801 		errc(EXIT_FAILURE, serrno, "%s: chmod", to_name);
802 	}
803 
804 	/*
805 	 * Preserve the date of the source file.
806 	 */
807 	if (dopreserve) {
808 #if HAVE_FUTIMES
809 		if (futimes(to_fd, tv) == -1)
810 			warn("%s: futimes", to_name);
811 #else
812 		if (utimes(to_name, tv) == -1)
813 			warn("%s: utimes", to_name);
814 #endif
815 	}
816 
817 	(void)close(to_fd);
818 
819 	if (dorename) {
820 		if (rename(to_name, oto_name) == -1)
821 			err(EXIT_FAILURE, "%s: rename", to_name);
822 		to_name = oto_name;
823 	}
824 
825 	/*
826 	 * If provided a set of flags, set them, otherwise, preserve the
827 	 * flags, except for the dump flag.
828 	 */
829 #if ! HAVE_NBTOOL_CONFIG_H
830 	if (!dounpriv && chflags(to_name,
831 	    flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
832 	{
833 		if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
834 			warn("%s: chflags", to_name);
835 	}
836 #endif
837 
838 	metadata_log(to_name, "file", tv, NULL, digestresult, size);
839 	free(digestresult);
840 }
841 
842 /*
843  * copy --
844  *	copy from one file to another, returning a digest.
845  *
846  *	If to_fd < 0, just calculate a digest, don't copy.
847  */
848 static char *
copy(int from_fd,char * from_name,int to_fd,char * to_name,off_t size)849 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
850 {
851 	ssize_t	nr, nw;
852 	int	serrno;
853 	u_char	*p;
854 	u_char	buf[MAXBSIZE];
855 	MD5_CTX		ctxMD5;
856 	RMD160_CTX	ctxRMD160;
857 	SHA1_CTX	ctxSHA1;
858 	SHA256_CTX	ctxSHA256;
859 	SHA384_CTX	ctxSHA384;
860 	SHA512_CTX	ctxSHA512;
861 
862 	switch (digesttype) {
863 	case DIGEST_MD5:
864 		MD5Init(&ctxMD5);
865 		break;
866 	case DIGEST_RMD160:
867 		RMD160Init(&ctxRMD160);
868 		break;
869 	case DIGEST_SHA1:
870 		SHA1Init(&ctxSHA1);
871 		break;
872 	case DIGEST_SHA256:
873 		SHA256_Init(&ctxSHA256);
874 		break;
875 	case DIGEST_SHA384:
876 		SHA384_Init(&ctxSHA384);
877 		break;
878 	case DIGEST_SHA512:
879 		SHA512_Init(&ctxSHA512);
880 		break;
881 	case DIGEST_NONE:
882 		if (to_fd < 0)
883 			return NULL; /* no need to do anything */
884 	default:
885 		break;
886 	}
887 	/*
888 	 * There's no reason to do anything other than close the file
889 	 * now if it's empty, so let's not bother.
890 	 */
891 	if (size > 0) {
892 
893 		/*
894 		 * Mmap and write if less than 8M (the limit is so we
895 		 * don't totally trash memory on big files).  This is
896 		 * really a minor hack, but it wins some CPU back.
897 		 */
898 
899 		if (size <= 8 * 1048576) {
900 			if ((p = mmap(NULL, (size_t)size, PROT_READ,
901 			    MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
902 			    == MAP_FAILED) {
903 				goto mmap_failed;
904 			}
905 #if defined(MADV_SEQUENTIAL) && !defined(__APPLE__)
906 			if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
907 			    && errno != EOPNOTSUPP)
908 				warn("madvise");
909 #endif
910 
911 			if (to_fd >= 0 && write(to_fd, p, size) != size) {
912 				serrno = errno;
913 				(void)unlink(to_name);
914 				errc(EXIT_FAILURE, serrno, "%s: write",
915 				    to_name);
916 			}
917 			switch (digesttype) {
918 			case DIGEST_MD5:
919 				MD5Update(&ctxMD5, p, size);
920 				break;
921 			case DIGEST_RMD160:
922 				RMD160Update(&ctxRMD160, p, size);
923 				break;
924 			case DIGEST_SHA1:
925 				SHA1Update(&ctxSHA1, p, size);
926 				break;
927 			case DIGEST_SHA256:
928 				SHA256_Update(&ctxSHA256, p, size);
929 				break;
930 			case DIGEST_SHA384:
931 				SHA384_Update(&ctxSHA384, p, size);
932 				break;
933 			case DIGEST_SHA512:
934 				SHA512_Update(&ctxSHA512, p, size);
935 				break;
936 			default:
937 				break;
938 			}
939 			(void)munmap(p, size);
940 		} else {
941  mmap_failed:
942 			while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
943 				if (to_fd >= 0 &&
944 				    (nw = write(to_fd, buf, nr)) != nr) {
945 					serrno = errno;
946 					(void)unlink(to_name);
947 					errc(EXIT_FAILURE,
948 					    nw > 0 ? EIO : serrno,
949 					    "%s: write", to_name);
950 				}
951 				switch (digesttype) {
952 				case DIGEST_MD5:
953 					MD5Update(&ctxMD5, buf, nr);
954 					break;
955 				case DIGEST_RMD160:
956 					RMD160Update(&ctxRMD160, buf, nr);
957 					break;
958 				case DIGEST_SHA1:
959 					SHA1Update(&ctxSHA1, buf, nr);
960 					break;
961 				case DIGEST_SHA256:
962 					SHA256_Update(&ctxSHA256, buf, nr);
963 					break;
964 				case DIGEST_SHA384:
965 					SHA384_Update(&ctxSHA384, buf, nr);
966 					break;
967 				case DIGEST_SHA512:
968 					SHA512_Update(&ctxSHA512, buf, nr);
969 					break;
970 				default:
971 					break;
972 				}
973 			}
974 			if (nr != 0) {
975 				serrno = errno;
976 				(void)unlink(to_name);
977 				errc(EXIT_FAILURE, serrno, "%s: read",
978 				    from_name);
979 			}
980 		}
981 	}
982 	switch (digesttype) {
983 	case DIGEST_MD5:
984 		return MD5End(&ctxMD5, NULL);
985 	case DIGEST_RMD160:
986 		return RMD160End(&ctxRMD160, NULL);
987 	case DIGEST_SHA1:
988 		return SHA1End(&ctxSHA1, NULL);
989 	case DIGEST_SHA256:
990 		return SHA256_End(&ctxSHA256, NULL);
991 	case DIGEST_SHA384:
992 		return SHA384_End(&ctxSHA384, NULL);
993 	case DIGEST_SHA512:
994 		return SHA512_End(&ctxSHA512, NULL);
995 	default:
996 		return NULL;
997 	}
998 }
999 
1000 static void
run(const char * command,const char * flags,const char * to_name,int errunlink)1001 run(const char *command, const char *flags, const char *to_name, int errunlink)
1002 {
1003 	char	*args[4];
1004 	char	*cmd;
1005 	int	status;
1006 	int	rv;
1007 	size_t	i;
1008 
1009 	i = 1;
1010 	status = 0;
1011 
1012 	if (needshell(command, 1)) {
1013 		rv = asprintf(&cmd, "%s %s%s%s", command, flags ? flags : "",
1014 		    flags ? " " : "", to_name);
1015 		if (rv < 0) {
1016 			warn("Cannot execute %s", command);
1017 			goto out;
1018 		}
1019 		command = _PATH_BSHELL;
1020 		flags = "-c";
1021 	} else
1022 		cmd = __UNCONST(to_name);
1023 
1024 	args[0] = __UNCONST(command);
1025 	if (flags)
1026 		args[i++] = __UNCONST(flags);
1027 	args[i++] = cmd;
1028 	args[i] = NULL;
1029 
1030 #ifdef HAVE_POSIX_SPAWN
1031 	if (*command == '/')
1032 		rv = posix_spawn(NULL, command, NULL, NULL, args, NULL);
1033 	else
1034 		rv = posix_spawnp(NULL, command, NULL, NULL, args, NULL);
1035 	if (rv != 0)
1036 		warnc(rv, "Cannot execute %s", command);
1037 	/*
1038 	 * the wait below will fail if we did not create a child it will
1039 	 * make rv negative.
1040 	 */
1041 #else
1042 	switch (vfork()) {
1043 	case -1:
1044 		rv = errno;
1045 		if (errunlink)
1046 			(void)unlink(to_name);
1047 		errc(EXIT_FAILURE, rv, "vfork");
1048 		/*NOTREACHED*/
1049 	case 0:
1050 		if (*command == '/')
1051 			execv(command, args);
1052 		else
1053 			execvp(command, args);
1054 		rv = errno;
1055 		const char *arr[] = {
1056 			getprogname(),
1057 			": exec failed for ",
1058 			command,
1059 			" (",
1060 			strerror(rv),
1061 			")\n",
1062 		};
1063 		for (i = 0; i < __arraycount(arr); i++)
1064 			write(STDERR_FILENO, arr[i], strlen(arr[i]));
1065 		_exit(1);
1066 		/*NOTREACHED*/
1067 	default:
1068 		break;
1069 	}
1070 #endif
1071 	rv = wait(&status);
1072 	if (cmd != to_name)
1073 		free(cmd);
1074 out:
1075 	if ((rv < 0 || status) && errunlink)
1076 		(void)unlink(to_name);
1077 }
1078 
1079 /*
1080  * strip --
1081  *	use strip(1) to strip the target file
1082  */
1083 static void
strip(const char * to_name)1084 strip(const char *to_name)
1085 {
1086 	const char *stripprog;
1087 
1088 	if ((stripprog = getenv("STRIP")) == NULL || *stripprog == '\0') {
1089 #ifdef TARGET_STRIP
1090 		stripprog = TARGET_STRIP;
1091 #else
1092 		stripprog = _PATH_STRIP;
1093 #endif
1094 	}
1095 	run(stripprog, stripArgs, to_name, 1);
1096 }
1097 
1098 /*
1099  * afterinstall --
1100  *	run provided command on the target file or directory after it's been
1101  *	installed and stripped, but before permissions are set or it's renamed
1102  */
1103 static void
afterinstall(const char * command,const char * to_name,int errunlink)1104 afterinstall(const char *command, const char *to_name, int errunlink)
1105 {
1106 	run(command, NULL, to_name, errunlink);
1107 }
1108 
1109 /*
1110  * backup --
1111  *	backup file "to_name" to to_name.suffix
1112  *	if suffix contains a "%", it's taken as a printf(3) pattern
1113  *	used for a numbered backup.
1114  */
1115 static void
backup(const char * to_name)1116 backup(const char *to_name)
1117 {
1118 	char	bname[FILENAME_MAX];
1119 
1120 	if (numberedbackup) {
1121 		/* Do numbered backup */
1122 		int cnt;
1123 		char suffix_expanded[FILENAME_MAX];
1124 
1125 		cnt=0;
1126 		do {
1127 			(void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
1128 			    cnt);
1129 			(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name,
1130 			    suffix_expanded);
1131 			cnt++;
1132 		} while (access(bname, F_OK) == 0);
1133 	} else {
1134 		/* Do simple backup */
1135 		(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name, suffix);
1136 	}
1137 
1138 	(void)rename(to_name, bname);
1139 }
1140 
1141 /*
1142  * install_dir --
1143  *	build directory hierarchy
1144  */
1145 static void
install_dir(char * path,u_int flags)1146 install_dir(char *path, u_int flags)
1147 {
1148 	char		*p;
1149 	struct stat	sb;
1150 	int		ch;
1151 
1152 	for (p = path;; ++p)
1153 		if (!*p || (p != path && *p  == '/')) {
1154 			ch = *p;
1155 			*p = '\0';
1156 			if (mkdir(path, 0777) < 0) {
1157 				/*
1158 				 * Can't create; path exists or no perms.
1159 				 * stat() path to determine what's there now.
1160 				 */
1161 				int sverrno;
1162 				sverrno = errno;
1163 				if (stat(path, &sb) < 0) {
1164 					/* Not there; use mkdir()s error */
1165 					errno = sverrno;
1166 					err(EXIT_FAILURE, "%s: mkdir", path);
1167 				}
1168 				if (!S_ISDIR(sb.st_mode)) {
1169 					errx(EXIT_FAILURE,
1170 					    "%s exists but is not a directory",
1171 					    path);
1172 				}
1173 			}
1174 			if (!(*p = ch))
1175 				break;
1176 		}
1177 
1178 	if (afterinstallcmd != NULL)
1179 		afterinstall(afterinstallcmd, path, 0);
1180 
1181 	if (!dounpriv && (
1182 	    ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
1183 	    || chmod(path, mode) == -1 )) {
1184 		warn("%s: chown/chmod", path);
1185 	}
1186 	metadata_log(path, "dir", NULL, NULL, NULL, 0);
1187 }
1188 
1189 /*
1190  * metadata_log --
1191  *	if metafp is not NULL, output mtree(8) full path name and settings to
1192  *	metafp, to allow permissions to be set correctly by other tools,
1193  *	or to allow integrity checks to be performed.
1194  */
1195 static void
metadata_log(const char * path,const char * type,struct timeval * tv,const char * slink,const char * digestresult,off_t size)1196 metadata_log(const char *path, const char *type, struct timeval *tv,
1197 	const char *slink, const char *digestresult, off_t size)
1198 {
1199 	static const char	extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
1200 	const char	*p;
1201 	char		*buf;
1202 	size_t		destlen;
1203 	struct flock	metalog_lock;
1204 
1205 	if (!metafp)
1206 		return;
1207 	buf = malloc(4 * strlen(path) + 1);	/* buf for strsvis(3) */
1208 	if (buf == NULL) {
1209 		warn("Can't allocate metadata");
1210 		return;
1211 	}
1212 							/* lock log file */
1213 	metalog_lock.l_start = 0;
1214 	metalog_lock.l_len = 0;
1215 	metalog_lock.l_whence = SEEK_SET;
1216 	metalog_lock.l_type = F_WRLCK;
1217 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
1218 		warn("can't lock %s", metafile);
1219 		free(buf);
1220 		return;
1221 	}
1222 
1223 	p = path;					/* remove destdir */
1224 	if (destdir) {
1225 		destlen = strlen(destdir);
1226 		if (strncmp(p, destdir, destlen) == 0 &&
1227 		    (p[destlen] == '/' || p[destlen] == '\0'))
1228 			p += destlen;
1229 	}
1230 	while (*p && *p == '/')				/* remove leading /s */
1231 		p++;
1232 	strsvis(buf, p, VIS_CSTYLE, extra);		/* encode name */
1233 	p = buf;
1234 							/* print details */
1235 	fprintf(metafp, ".%s%s type=%s", *p ? "/" : "", p, type);
1236 	if (owner)
1237 		fprintf(metafp, " uname=%s", owner);
1238 	if (group)
1239 		fprintf(metafp, " gname=%s", group);
1240 	fprintf(metafp, " mode=%#o", mode);
1241 	if (slink) {
1242 		strsvis(buf, slink, VIS_CSTYLE, extra);	/* encode link */
1243 		fprintf(metafp, " link=%s", buf);
1244 	}
1245 	if (*type == 'f') /* type=file */
1246 		fprintf(metafp, " size=%lld", (long long)size);
1247 	if (tv != NULL && dopreserve)
1248 		fprintf(metafp, " time=%lld.%0*lld",
1249 			(long long)tv[1].tv_sec,
1250 			(tv[1].tv_usec == 0 ? 1 : 9),
1251 			(long long)tv[1].tv_usec * 1000);
1252 	if (digestresult && digest)
1253 		fprintf(metafp, " %s=%s", digest, digestresult);
1254 	if (fflags)
1255 		fprintf(metafp, " flags=%s", fflags);
1256 	if (tags)
1257 		fprintf(metafp, " tags=%s", tags);
1258 	fputc('\n', metafp);
1259 	fflush(metafp);					/* flush output */
1260 							/* unlock log file */
1261 	metalog_lock.l_type = F_UNLCK;
1262 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
1263 		warn("can't unlock %s", metafile);
1264 	}
1265 	free(buf);
1266 }
1267 
1268 /*
1269  * xbasename --
1270  *	libc basename(3) that returns a pointer to a static buffer
1271  *	instead of overwriting that passed-in string.
1272  */
1273 static char *
xbasename(char * path)1274 xbasename(char *path)
1275 {
1276 	static char tmp[MAXPATHLEN];
1277 
1278 	(void)strlcpy(tmp, path, sizeof(tmp));
1279 	return (basename(tmp));
1280 }
1281 
1282 /*
1283  * xdirname --
1284  *	libc dirname(3) that returns a pointer to a static buffer
1285  *	instead of overwriting that passed-in string.
1286  */
1287 static char *
xdirname(char * path)1288 xdirname(char *path)
1289 {
1290 	static char tmp[MAXPATHLEN];
1291 
1292 	(void)strlcpy(tmp, path, sizeof(tmp));
1293 	return (dirname(tmp));
1294 }
1295 
1296 /*
1297  * usage --
1298  *	print a usage message and die
1299  */
1300 static void
usage(void)1301 usage(void)
1302 {
1303 	const char *prog;
1304 
1305 	prog = getprogname();
1306 
1307 	(void)fprintf(stderr,
1308 "usage: %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
1309 "           [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group] \n"
1310 "           [-l linkflags] [-h hash] [-S stripflags] file1 file2\n"
1311 "       %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
1312 "           [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group]\n"
1313 "           [-l linkflags] [-h hash] [-S stripflags] file1 ... fileN directory\n"
1314 "       %s -d [-Up] [-M log] [-D dest] [-T tags] [-a aftercmd] [-m mode]\n"
1315 "           [-N dbdir] [-o owner] [-g group] directory ...\n",
1316 	    prog, prog, prog);
1317 	exit(1);
1318 }
1319 
1320 /*
1321  * The following array is used to make a fast determination of which
1322  * characters are interpreted specially by the shell.  If a command
1323  * contains any of these characters, it is executed by the shell, not
1324  * directly by us.
1325  */
1326 static unsigned char _metachar[128] = {
1327 /*    nul   soh   stx   etx   eot   enq   ack   bel */
1328 	1,    0,    0,    0,    0,    0,    0,    0,
1329 /*     bs    ht    nl    vt    np    cr    so    si */
1330 	0,    0,    1,    0,	0,    0,    0,    0,
1331 /*    dle   dc1   dc2   dc3   dc4   nak   syn   etb */
1332 	0,    0,    0,    0,    0,    0,    0,    0,
1333 /*    can    em   sub   esc    fs    gs    rs    us */
1334 	0,    0,    0,    0,    0,    0,    0,    0,
1335 /*     sp     !     "     #     $     %     &     ' */
1336 	0,    1,    1,    1,    1,    0,    1,    1,
1337 /*      (     )     *     +     ,     -     .     / */
1338 	1,    1,    1,    0,    0,    0,    0,    0,
1339 /*      0     1     2     3     4     5     6     7 */
1340 	0,    0,    0,    0,    0,    0,    0,    0,
1341 /*      8     9     :     ;     <     =     >     ? */
1342 	0,    0,    0,    1,    1,    0,    1,    1,
1343 /*      @     A     B     C     D     E     F     G */
1344 	0,    0,    0,    0,    0,    0,    0,    0,
1345 /*      H     I     J     K     L     M     N     O */
1346 	0,    0,    0,    0,    0,    0,    0,    0,
1347 /*      P     Q     R     S     T     U     V     W */
1348 	0,    0,    0,    0,    0,    0,    0,    0,
1349 /*      X     Y     Z     [     \     ]     ^     _ */
1350 	0,    0,    0,    1,    1,    1,    1,    0,
1351 /*      `     a     b     c     d     e     f     g */
1352 	1,    0,    0,    0,    0,    0,    0,    0,
1353 /*      h     i     j     k     l     m     n     o */
1354 	0,    0,    0,    0,    0,    0,    0,    0,
1355 /*      p     q     r     s     t     u     v     w */
1356 	0,    0,    0,    0,    0,    0,    0,    0,
1357 /*      x     y     z     {     |     }     ~   del */
1358 	0,    0,    0,    1,    1,    1,    1,    0,
1359 };
1360 
1361 #define ismeta(c)	_metachar[(c) & 0x7f]
1362 
1363 static int
needshell(const char * cmd,int white)1364 needshell(const char *cmd, int white)
1365 {
1366 	while (!ismeta(*cmd) && *cmd != ':' && *cmd != '=') {
1367 		if (white && isspace((unsigned char)*cmd))
1368 			break;
1369 		cmd++;
1370 	}
1371 
1372 	return *cmd != '\0';
1373 }
1374