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