xref: /illumos-gate/usr/src/cmd/find/find.c (revision 9ab6dc39bc9739a3452a740eda8b9aaa4a5ba4b0)
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  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
29 /*	  All Rights Reserved  	*/
30 
31 
32 /*	Parts of this product may be derived from		*/
33 /*	Mortice Kern Systems Inc. and Berkeley 4.3 BSD systems.	*/
34 /*	licensed from  Mortice Kern Systems Inc. and 		*/
35 /*	the University of California.				*/
36 
37 /*
38  * Copyright 1985, 1990 by Mortice Kern Systems Inc.  All rights reserved.
39  */
40 
41 #include <stdio.h>
42 #include <errno.h>
43 #include <pwd.h>
44 #include <grp.h>
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <sys/param.h>
48 #include <sys/acl.h>
49 #include <limits.h>
50 #include <unistd.h>
51 #include <stdlib.h>
52 #include <locale.h>
53 #include <string.h>
54 #include <strings.h>
55 #include <ctype.h>
56 #include <wait.h>
57 #include <fnmatch.h>
58 #include <langinfo.h>
59 #include <ftw.h>
60 #include <libgen.h>
61 #include "getresponse.h"
62 
63 #define	A_DAY		(long)(60*60*24)	/* a day full of seconds */
64 #define	A_MIN		(long)(60)
65 #define	BLKSIZ		512
66 #define	round(x, s)	(((x)+(s)-1)&~((s)-1))
67 #ifndef FTW_SLN
68 #define	FTW_SLN		7
69 #endif
70 #define	LINEBUF_SIZE		LINE_MAX	/* input or output lines */
71 #define	REMOTE_FS		"/etc/dfs/fstypes"
72 #define	N_FSTYPES		20
73 #define	SHELL_MAXARGS		253	/* see doexec() for description */
74 
75 /*
76  * This is the list of operations
77  * F_USER and F_GROUP are named to avoid conflict with USER and GROUP defined
78  * in sys/acl.h
79  */
80 
81 enum Command
82 {
83 	PRINT, DEPTH, LOCAL, MOUNT, ATIME, MTIME, CTIME, NEWER,
84 	NAME, F_USER, F_GROUP, INUM, SIZE, LINKS, PERM, EXEC, OK, CPIO, NCPIO,
85 	TYPE, AND, OR, NOT, LPAREN, RPAREN, CSIZE, VARARGS, FOLLOW,
86 	PRUNE, NOUSER, NOGRP, FSTYPE, LS, XATTR, ACL, MMIN, AMIN, CMIN
87 };
88 
89 enum Type
90 {
91 	Unary, Id, Num, Str, Exec, Cpio, Op
92 };
93 
94 struct Args
95 {
96 	char		name[10];
97 	enum Command	action;
98 	enum Type	type;
99 };
100 
101 /*
102  * Except for pathnames, these are the only legal arguments
103  */
104 static struct Args commands[] =
105 {
106 	"!",		NOT,	Op,
107 	"(",		LPAREN,	Unary,
108 	")",		RPAREN,	Unary,
109 	"-a",		AND,	Op,
110 	"-amin",	AMIN,	Num,
111 	"-atime",	ATIME,	Num,
112 	"-cpio",	CPIO,	Cpio,
113 	"-cmin",	CMIN,	Num,
114 	"-ctime",	CTIME,	Num,
115 	"-depth",	DEPTH,	Unary,
116 	"-exec",	EXEC,	Exec,
117 	"-follow",	FOLLOW, Unary,
118 	"-group",	F_GROUP,	Num,
119 	"-inum",	INUM,	Num,
120 	"-links",	LINKS,	Num,
121 	"-local",	LOCAL,	Unary,
122 	"-mount",	MOUNT,	Unary,
123 	"-mmin",	MMIN,	Num,
124 	"-mtime",	MTIME,	Num,
125 	"-name",	NAME,	Str,
126 	"-ncpio",	NCPIO,  Cpio,
127 	"-newer",	NEWER,	Str,
128 	"-o",		OR,	Op,
129 	"-ok",		OK,	Exec,
130 	"-perm",	PERM,	Num,
131 	"-print",	PRINT,	Unary,
132 	"-size",	SIZE,	Num,
133 	"-type",	TYPE,	Num,
134 	"-xdev",	MOUNT,	Unary,
135 	"-user",	F_USER,	Num,
136 	"-prune",	PRUNE,	Unary,
137 	"-nouser",	NOUSER,	Unary,
138 	"-nogroup",	NOGRP,	Unary,
139 	"-fstype",	FSTYPE,	Str,
140 	"-ls",		LS,	Unary,
141 	"-xattr",	XATTR,	Unary,
142 	"-acl",		ACL,	Unary,
143 	NULL,		0,	0
144 };
145 
146 union Item
147 {
148 	struct Node	*np;
149 	struct Arglist	*vp;
150 	time_t		t;
151 	char		*cp;
152 	char		**ap;
153 	long		l;
154 	int		i;
155 	long long	ll;
156 };
157 
158 struct Node
159 {
160 	struct Node	*next;
161 	enum Command	action;
162 	enum Type	type;
163 	union Item	first;
164 	union Item	second;
165 };
166 
167 /* if no -print, -exec or -ok replace "expression" with "(expression) -print" */
168 static	struct	Node PRINT_NODE = { 0, PRINT, 0, 0};
169 static	struct	Node LPAREN_NODE = { 0, LPAREN, 0, 0};
170 
171 
172 /*
173  * Prototype variable size arglist buffer
174  */
175 
176 struct Arglist
177 {
178 	struct Arglist	*next;
179 	char		*end;
180 	char		*nextstr;
181 	char		**firstvar;
182 	char		**nextvar;
183 	char		*arglist[1];
184 };
185 
186 
187 static int		compile();
188 static int		execute();
189 static int		doexec(char *, char **, int *);
190 static struct Args	*lookup();
191 static int		ok();
192 static void		usage(void)	__NORETURN;
193 static struct Arglist	*varargs();
194 static int		list();
195 static char		*getgroup();
196 static FILE		*cmdopen();
197 static int		cmdclose();
198 static char		*getshell();
199 static void 		init_remote_fs();
200 static char		*getname();
201 static int		readmode();
202 static mode_t		getmode();
203 static char		*gettail();
204 
205 
206 static int walkflags = FTW_CHDIR|FTW_PHYS|FTW_ANYERR|FTW_NOLOOP;
207 static struct Node	*topnode;
208 static struct Node	*freenode;	/* next free node we may use later */
209 static char		*cpio[] = { "cpio", "-o", 0 };
210 static char		*ncpio[] = { "cpio", "-oc", 0 };
211 static char		*cpiol[] = { "cpio", "-oL", 0 };
212 static char		*ncpiol[] = { "cpio", "-ocL", 0 };
213 static time_t		now;
214 static FILE		*output;
215 static char		*dummyarg = (char *)-1;
216 static int		lastval;
217 static int		varsize;
218 static struct Arglist	*lastlist;
219 static char		*cmdname;
220 static char		*remote_fstypes[N_FSTYPES+1];
221 static int		fstype_index = 0;
222 static int		action_expression = 0;	/* -print, -exec, or -ok */
223 static int		error = 0;
224 static int		paren_cnt = 0;	/* keeps track of parentheses */
225 static int		hflag = 0;
226 static int		lflag = 0;
227 /* set when doexec()-invoked utility returns non-zero */
228 static int		exec_exitcode = 0;
229 extern char		**environ;
230 
231 int
232 main(int argc, char **argv)
233 {
234 	char *cp;
235 	int c;
236 	int paths;
237 	char *cwdpath;
238 
239 	(void) setlocale(LC_ALL, "");
240 #if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
241 #define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
242 #endif
243 	(void) textdomain(TEXT_DOMAIN);
244 
245 	cmdname = argv[0];
246 	if (time(&now) == (time_t)(-1)) {
247 		(void) fprintf(stderr, gettext("%s: time() %s\n"),
248 		    cmdname, strerror(errno));
249 		exit(1);
250 	}
251 	while ((c = getopt(argc, argv, "HL")) != -1) {
252 		switch (c) {
253 		case 'H':
254 			hflag = 1;
255 			lflag = 0;
256 			break;
257 		case 'L':
258 			hflag = 0;
259 			lflag = 1;
260 			break;
261 		case '?':
262 			usage();
263 			break;
264 		}
265 	}
266 
267 	argc -= optind;
268 	argv += optind;
269 
270 	if (argc < 1) {
271 		(void) fprintf(stderr,
272 		    gettext("%s: insufficient number of arguments\n"), cmdname);
273 		usage();
274 	}
275 
276 	for (paths = 0; (cp = argv[paths]) != 0; ++paths) {
277 		if (*cp == '-')
278 			break;
279 		else if ((*cp == '!' || *cp == '(') && *(cp+1) == 0)
280 			break;
281 	}
282 
283 	if (paths == 0) /* no path-list */
284 		usage();
285 
286 	output = stdout;
287 
288 	/* lflag is the same as -follow */
289 	if (lflag)
290 		walkflags &= ~FTW_PHYS;
291 
292 	/* allocate enough space for the compiler */
293 	topnode = malloc((argc + 1) * sizeof (struct Node));
294 	(void) memset(topnode, 0, (argc + 1) * sizeof (struct Node));
295 
296 	if (compile(argv + paths, topnode, &action_expression) == 0) {
297 		/* no expression, default to -print */
298 		(void) memcpy(topnode, &PRINT_NODE, sizeof (struct Node));
299 	} else if (!action_expression) {
300 		/*
301 		 * if no action expression, insert an LPAREN node above topnode,
302 		 * with a PRINT node as its next node
303 		 */
304 		struct Node *savenode;
305 
306 		if (freenode == NULL) {
307 			(void) fprintf(stderr, gettext("%s: can't append -print"
308 			    " implicitly; try explicit -print option\n"),
309 			    cmdname);
310 			exit(1);
311 		}
312 		savenode = topnode;
313 		topnode = freenode++;
314 		(void) memcpy(topnode, &LPAREN_NODE, sizeof (struct Node));
315 		topnode->next = freenode;
316 		topnode->first.np = savenode;
317 		(void) memcpy(topnode->next, &PRINT_NODE, sizeof (struct Node));
318 	}
319 
320 	while (paths--) {
321 		char *curpath;
322 		struct stat sb;
323 
324 		curpath = *(argv++);
325 
326 		/*
327 		 * If -H is specified, it means we walk the first
328 		 * level (pathname on command line) logically, following
329 		 * symlinks, but lower levels are walked physically.
330 		 * We use our own secret interface to nftw() to change
331 		 * the from stat to lstat after the top level is walked.
332 		 */
333 		if (hflag) {
334 			if (stat(curpath, &sb) < 0 && errno == ENOENT)
335 				walkflags &= ~FTW_HOPTION;
336 			else
337 				walkflags |= FTW_HOPTION;
338 		}
339 
340 		/*
341 		 * We need this check as nftw needs a CWD and we have no
342 		 * way of returning back from that code with a meaningful
343 		 * error related to this
344 		 */
345 		if ((cwdpath = getcwd(NULL, PATH_MAX)) == NULL) {
346 			(void) fprintf(stderr,
347 			    gettext("%s : cannot get the current working "
348 			    "directory\n"), cmdname);
349 			exit(1);
350 		} else
351 			free(cwdpath);
352 
353 
354 		if (nftw(curpath, execute, 1000, walkflags)) {
355 			(void) fprintf(stderr,
356 			    gettext("%s: cannot open %s: %s\n"),
357 			    cmdname, curpath, strerror(errno));
358 			error = 1;
359 		}
360 
361 	}
362 
363 	/* execute any remaining variable length lists */
364 	while (lastlist) {
365 		if (lastlist->end != lastlist->nextstr) {
366 			*lastlist->nextvar = 0;
367 			(void) doexec((char *)0, lastlist->arglist,
368 			    &exec_exitcode);
369 		}
370 		lastlist = lastlist->next;
371 	}
372 	if (output != stdout)
373 		return (cmdclose(output));
374 	return ((exec_exitcode != 0) ? exec_exitcode : error);
375 }
376 
377 /*
378  * compile the arguments
379  */
380 
381 static int
382 compile(argv, np, actionp)
383 char **argv;
384 struct Node *np;
385 int *actionp;
386 {
387 	char *b;
388 	char **av;
389 	struct Node *oldnp = topnode;
390 	struct Args *argp;
391 	char **com;
392 	int i;
393 	enum Command wasop = PRINT;
394 
395 	if (init_yes() < 0) {
396 		(void) fprintf(stderr, gettext(ERR_MSG_INIT_YES),
397 		    strerror(errno));
398 		exit(1);
399 	}
400 
401 	for (av = argv; *av && (argp = lookup(*av)); av++) {
402 		np->next = 0;
403 		np->action = argp->action;
404 		np->type = argp->type;
405 		np->second.i = 0;
406 		if (argp->type == Op) {
407 			if (wasop == NOT || (wasop && np->action != NOT)) {
408 				(void) fprintf(stderr,
409 				gettext("%s: operand follows operand\n"),
410 						cmdname);
411 				exit(1);
412 			}
413 			if (np->action != NOT && oldnp == 0)
414 				goto err;
415 			wasop = argp->action;
416 		} else {
417 			wasop = PRINT;
418 			if (argp->type != Unary) {
419 				if (!(b = *++av)) {
420 					(void) fprintf(stderr,
421 					gettext("%s: incomplete statement\n"),
422 							cmdname);
423 					exit(1);
424 				}
425 				if (argp->type == Num) {
426 					if ((argp->action != PERM) ||
427 					    (*b != '+')) {
428 						if (*b == '+' || *b == '-') {
429 							np->second.i = *b;
430 							b++;
431 						}
432 					}
433 				}
434 			}
435 		}
436 		switch (argp->action) {
437 		case AND:
438 			break;
439 		case NOT:
440 			break;
441 		case OR:
442 			np->first.np = topnode;
443 			topnode = np;
444 			oldnp->next = 0;
445 			break;
446 
447 		case LPAREN: {
448 			struct Node *save = topnode;
449 			topnode = np+1;
450 			paren_cnt++;
451 			i = compile(++av, topnode, actionp);
452 			np->first.np = topnode;
453 			topnode = save;
454 			av += i;
455 			oldnp = np;
456 			np += i + 1;
457 			oldnp->next = np;
458 			continue;
459 		}
460 
461 		case RPAREN:
462 			if (paren_cnt <= 0) {
463 				(void) fprintf(stderr,
464 				    gettext("%s: unmatched ')'\n"),
465 				    cmdname);
466 				exit(1);
467 			}
468 			paren_cnt--;
469 			if (oldnp == 0)
470 				goto err;
471 			if (oldnp->type == Op) {
472 				(void) fprintf(stderr,
473 				    gettext("%s: cannot immediately"
474 				    " follow an operand with ')'\n"),
475 				    cmdname);
476 				exit(1);
477 			}
478 			oldnp->next = 0;
479 			return (av-argv);
480 
481 		case FOLLOW:
482 			walkflags &= ~FTW_PHYS;
483 			break;
484 		case MOUNT:
485 			walkflags |= FTW_MOUNT;
486 			break;
487 		case DEPTH:
488 			walkflags |= FTW_DEPTH;
489 			break;
490 
491 		case LOCAL:
492 			np->first.l = 0L;
493 			np->first.ll = 0LL;
494 			np->second.i = '+';
495 			/*
496 			 * Make it compatible to df -l for
497 			 * future enhancement. So, anything
498 			 * that is not remote, then it is
499 			 * local.
500 			 */
501 			init_remote_fs();
502 			break;
503 
504 		case SIZE:
505 			if (b[strlen(b)-1] == 'c')
506 				np->action = CSIZE;
507 			/*FALLTHROUGH*/
508 		case INUM:
509 			np->first.ll = atoll(b);
510 			break;
511 
512 		case CMIN:
513 		case CTIME:
514 		case MMIN:
515 		case MTIME:
516 		case AMIN:
517 		case ATIME:
518 		case LINKS:
519 			np->first.l = atol(b);
520 			break;
521 
522 		case F_USER:
523 		case F_GROUP: {
524 			struct	passwd	*pw;
525 			struct	group *gr;
526 			i = -1;
527 			if (argp->action == F_USER) {
528 				if ((pw = getpwnam(b)) != 0)
529 					i = (int)pw->pw_uid;
530 			} else {
531 				if ((gr = getgrnam(b)) != 0)
532 					i = (int)gr->gr_gid;
533 			}
534 			if (i == -1) {
535 				if (fnmatch("[0-9][0-9][0-9]*", b, 0) &&
536 						fnmatch("[0-9][0-9]", b, 0) &&
537 						fnmatch("[0-9]", b, 0)) {
538 					(void) fprintf(stderr, gettext(
539 					    "%s: cannot find %s name\n"),
540 						cmdname, *av);
541 					exit(1);
542 				}
543 				i = atoi(b);
544 			}
545 			np->first.l = i;
546 			break;
547 		}
548 
549 		case EXEC:
550 		case OK:
551 			walkflags &= ~FTW_CHDIR;
552 			np->first.ap = av;
553 			(*actionp)++;
554 			for (;;) {
555 				if ((b = *av) == 0) {
556 					(void) fprintf(stderr,
557 					gettext("%s: incomplete statement\n"),
558 						cmdname);
559 					exit(1);
560 				}
561 				if (strcmp(b, ";") == 0) {
562 					*av = 0;
563 					break;
564 				} else if (strcmp(b, "{}") == 0)
565 					*av = dummyarg;
566 				else if (strcmp(b, "+") == 0 &&
567 					av[-1] == dummyarg &&
568 					np->action == EXEC) {
569 					av[-1] = 0;
570 					np->first.vp = varargs(np->first.ap);
571 					np->action = VARARGS;
572 					break;
573 				}
574 				av++;
575 			}
576 			break;
577 
578 		case NAME:
579 			np->first.cp = b;
580 			break;
581 		case PERM:
582 			if (*b == '-')
583 				++b;
584 
585 			if (readmode(b) != NULL) {
586 				(void) fprintf(stderr, gettext(
587 				    "find: -perm: Bad permission string\n"));
588 				usage();
589 			}
590 			np->first.l = (long)getmode((mode_t)0);
591 			break;
592 		case TYPE:
593 			i = *b;
594 			np->first.l =
595 			    i == 'd' ? S_IFDIR :
596 			    i == 'b' ? S_IFBLK :
597 			    i == 'c' ? S_IFCHR :
598 #ifdef S_IFIFO
599 			    i == 'p' ? S_IFIFO :
600 #endif
601 			    i == 'f' ? S_IFREG :
602 #ifdef S_IFLNK
603 			    i == 'l' ? S_IFLNK :
604 #endif
605 #ifdef S_IFSOCK
606 			    i == 's' ? S_IFSOCK :
607 #endif
608 #ifdef S_IFDOOR
609 			    i == 'D' ? S_IFDOOR :
610 #endif
611 			    0;
612 			break;
613 
614 		case CPIO:
615 			if (walkflags & FTW_PHYS)
616 				com = cpio;
617 			else
618 				com = cpiol;
619 			goto common;
620 
621 		case NCPIO: {
622 			FILE *fd;
623 
624 			if (walkflags & FTW_PHYS)
625 				com = ncpio;
626 			else
627 				com = ncpiol;
628 		common:
629 			/* set up cpio */
630 			if ((fd = fopen(b, "w")) == NULL) {
631 				(void) fprintf(stderr,
632 					gettext("%s: cannot create %s\n"),
633 					cmdname, b);
634 				exit(1);
635 			}
636 
637 			np->first.l = (long)cmdopen("cpio", com, "w", fd);
638 			(void) fclose(fd);
639 			walkflags |= FTW_DEPTH;
640 			np->action = CPIO;
641 		}
642 			/*FALLTHROUGH*/
643 		case PRINT:
644 			(*actionp)++;
645 			break;
646 
647 		case NEWER: {
648 			struct stat statb;
649 			if (stat(b, &statb) < 0) {
650 				(void) fprintf(stderr,
651 					gettext("%s: cannot access %s\n"),
652 					cmdname, b);
653 				exit(1);
654 			}
655 			np->first.l = statb.st_mtime;
656 			np->second.i = '+';
657 			break;
658 		}
659 
660 		case PRUNE:
661 		case NOUSER:
662 		case NOGRP:
663 			break;
664 		case FSTYPE:
665 			np->first.cp = b;
666 			break;
667 		case LS:
668 			(*actionp)++;
669 			break;
670 		case XATTR:
671 			break;
672 		case ACL:
673 			break;
674 		}
675 
676 		oldnp = np++;
677 		oldnp->next = np;
678 	}
679 
680 	if ((*av) || (wasop))
681 		goto err;
682 
683 	if (paren_cnt != 0) {
684 		(void) fprintf(stderr, gettext("%s: unmatched '('\n"),
685 		cmdname);
686 		exit(1);
687 	}
688 
689 	/* just before returning, save next free node from the list */
690 	freenode = oldnp->next;
691 	oldnp->next = 0;
692 	return (av-argv);
693 err:
694 	if (*av)
695 		(void) fprintf(stderr,
696 		    gettext("%s: bad option %s\n"), cmdname, *av);
697 	else
698 		(void) fprintf(stderr, gettext("%s: bad option\n"), cmdname);
699 	usage();
700 	/*NOTREACHED*/
701 }
702 
703 /*
704  * print out a usage message
705  */
706 
707 static void
708 usage(void)
709 {
710 	(void) fprintf(stderr,
711 	    gettext("%s: [-H | -L] path-list predicate-list\n"), cmdname);
712 	exit(1);
713 }
714 
715 /*
716  * This is the function that gets executed at each node
717  */
718 
719 static int
720 execute(name, statb, type, state)
721 char *name;
722 struct stat *statb;
723 int type;
724 struct FTW *state;
725 {
726 	struct Node *np = topnode;
727 	int val;
728 	time_t t;
729 	long l;
730 	long long ll;
731 	int not = 1;
732 	char *filename;
733 
734 	if (type == FTW_NS) {
735 		(void) fprintf(stderr, gettext("%s: stat() error %s: %s\n"),
736 			cmdname, name, strerror(errno));
737 		error = 1;
738 		return (0);
739 	} else if (type == FTW_DNR) {
740 		(void) fprintf(stderr, gettext("%s: cannot read dir %s: %s\n"),
741 			cmdname, name, strerror(errno));
742 		error = 1;
743 		return (0);
744 	} else if (type == FTW_SLN && lflag == 0) {
745 		(void) fprintf(stderr,
746 			gettext("%s: cannot follow symbolic link %s: %s\n"),
747 			cmdname, name, strerror(errno));
748 		error = 1;
749 		return (0);
750 	} else if (type == FTW_DL) {
751 		(void) fprintf(stderr, gettext("%s: cycle detected for %s\n"),
752 			cmdname, name);
753 		error = 1;
754 		return (0);
755 	}
756 
757 	while (np) {
758 		switch (np->action) {
759 		case NOT:
760 			not = !not;
761 			np = np->next;
762 			continue;
763 
764 		case AND:
765 			np = np->next;
766 			continue;
767 
768 		case OR:
769 			if (np->first.np == np) {
770 				/*
771 				 * handle naked OR (no term on left hand side)
772 				 */
773 				(void) fprintf(stderr,
774 				    gettext("%s: invalid -o construction\n"),
775 				    cmdname);
776 				exit(2);
777 			}
778 			/* FALLTHROUGH */
779 		case LPAREN: {
780 			struct Node *save = topnode;
781 			topnode = np->first.np;
782 			(void) execute(name, statb, type, state);
783 			val = lastval;
784 			topnode = save;
785 			if (np->action == OR) {
786 				if (val)
787 					return (0);
788 				val = 1;
789 			}
790 			break;
791 		}
792 
793 		case LOCAL: {
794 			int	nremfs;
795 			val = 1;
796 			/*
797 			 * If file system type matches the remote
798 			 * file system type, then it is not local.
799 			 */
800 			for (nremfs = 0; nremfs < fstype_index; nremfs++) {
801 				if (strcmp(remote_fstypes[nremfs],
802 						statb->st_fstype) == 0) {
803 					val = 0;
804 					break;
805 				}
806 			}
807 			break;
808 		}
809 
810 		case TYPE:
811 			l = (long)statb->st_mode&S_IFMT;
812 			goto num;
813 
814 		case PERM:
815 			l = (long)statb->st_mode&07777;
816 			if (np->second.i == '-')
817 				val = ((l&np->first.l) == np->first.l);
818 			else
819 				val = (l == np->first.l);
820 			break;
821 
822 		case INUM:
823 			ll = (long long)statb->st_ino;
824 			goto llnum;
825 		case NEWER:
826 			l = statb->st_mtime;
827 			goto num;
828 		case ATIME:
829 			t = statb->st_atime;
830 			goto days;
831 		case CTIME:
832 			t = statb->st_ctime;
833 			goto days;
834 		case MTIME:
835 			t = statb->st_mtime;
836 		days:
837 			l = (now-t)/A_DAY;
838 			goto num;
839 		case MMIN:
840 			t = statb->st_mtime;
841 			goto mins;
842 		case AMIN:
843 			t = statb->st_atime;
844 			goto mins;
845 		case CMIN:
846 			t = statb->st_ctime;
847 			goto mins;
848 		mins:
849 			l = (now-t)/A_MIN;
850 			goto num;
851 		case CSIZE:
852 			ll = (long long)statb->st_size;
853 			goto llnum;
854 		case SIZE:
855 			ll = (long long)round(statb->st_size, BLKSIZ)/BLKSIZ;
856 			goto llnum;
857 		case F_USER:
858 			l = (long)statb->st_uid;
859 			goto num;
860 		case F_GROUP:
861 			l = (long)statb->st_gid;
862 			goto num;
863 		case LINKS:
864 			l = (long)statb->st_nlink;
865 			goto num;
866 		llnum:
867 			if (np->second.i == '+')
868 				val = (ll > np->first.ll);
869 			else if (np->second.i == '-')
870 				val = (ll < np->first.ll);
871 			else
872 				val = (ll == np->first.ll);
873 			break;
874 		num:
875 			if (np->second.i == '+')
876 				val = (l > np->first.l);
877 			else if (np->second.i == '-')
878 				val = (l < np->first.l);
879 			else
880 				val = (l == np->first.l);
881 			break;
882 		case OK:
883 			val = ok(name, np->first.ap);
884 			break;
885 		case EXEC:
886 			val = doexec(name, np->first.ap, NULL);
887 			break;
888 
889 		case VARARGS: {
890 			struct Arglist *ap = np->first.vp;
891 			char *cp;
892 			cp = ap->nextstr - (strlen(name)+1);
893 			if (cp >= (char *)(ap->nextvar+3)) {
894 				/* there is room just copy the name */
895 				val = 1;
896 				(void) strcpy(cp, name);
897 				*ap->nextvar++ = cp;
898 				ap->nextstr = cp;
899 			} else {
900 				/* no more room, exec command */
901 				*ap->nextvar++ = name;
902 				*ap->nextvar = 0;
903 				val = 1;
904 				(void) doexec((char *)0, ap->arglist,
905 				    &exec_exitcode);
906 				ap->nextstr = ap->end;
907 				ap->nextvar = ap->firstvar;
908 			}
909 			break;
910 		}
911 
912 		case DEPTH:
913 		case MOUNT:
914 		case FOLLOW:
915 			val = 1;
916 			break;
917 
918 		case NAME: {
919 			char *name1;
920 
921 			/*
922 			 * basename(3c) may modify name, so
923 			 * we need to pass another string
924 			 */
925 			if ((name1 = strdup(name)) == NULL) {
926 				(void) fprintf(stderr,
927 				    gettext("%s: cannot strdup() %s: %s\n"),
928 				    name, strerror(errno));
929 				exit(2);
930 			}
931 			/*
932 			 * XPG4 find should not treat a leading '.' in a
933 			 * filename specially for pattern matching.
934 			 * /usr/bin/find  will not pattern match a leading
935 			 * '.' in a filename, unless '.' is explicitly
936 			 * specified.
937 			 */
938 #ifdef XPG4
939 			val = !fnmatch(np->first.cp,
940 			    basename(name1), 0);
941 #else
942 			val = !fnmatch(np->first.cp,
943 			    basename(name1), FNM_PERIOD);
944 #endif
945 			break;
946 		}
947 
948 		case PRUNE:
949 			if (type == FTW_D)
950 				state->quit = FTW_PRUNE;
951 			val = 1;
952 			break;
953 		case NOUSER:
954 			val = ((getpwuid(statb->st_uid)) == 0);
955 			break;
956 		case NOGRP:
957 			val = ((getgrgid(statb->st_gid)) == 0);
958 			break;
959 		case FSTYPE:
960 			val = (strcmp(np->first.cp, statb->st_fstype) == 0);
961 			break;
962 		case CPIO:
963 			output = (FILE *)np->first.l;
964 			(void) fprintf(output, "%s\n", name);
965 			val = 1;
966 			break;
967 		case PRINT:
968 			(void) fprintf(stdout, "%s\n", name);
969 			val = 1;
970 			break;
971 		case LS:
972 			(void) list(name, statb);
973 			val = 1;
974 			break;
975 		case XATTR:
976 			filename = gettail(name);
977 			val = (pathconf(filename, _PC_XATTR_EXISTS) == 1);
978 			break;
979 		case ACL:
980 			/*
981 			 * Need to get the tail of the file name, since we have
982 			 * already chdir()ed into the directory (performed in
983 			 * nftw()) of the file
984 			 */
985 			filename = gettail(name);
986 			val = acl_trivial(name);
987 			break;
988 		}
989 		/*
990 		 * evaluate 'val' and 'not' (exclusive-or)
991 		 * if no inversion (not == 1), return only when val == 0
992 		 * (primary not true). Otherwise, invert the primary
993 		 * and return when the primary is true.
994 		 * 'Lastval' saves the last result (fail or pass) when
995 		 * returning back to the calling routine.
996 		 */
997 		if (val^not) {
998 			lastval = 0;
999 			return (0);
1000 		}
1001 		lastval = 1;
1002 		not = 1;
1003 		np = np->next;
1004 	}
1005 	return (0);
1006 }
1007 
1008 /*
1009  * code for the -ok option
1010  */
1011 
1012 static int
1013 ok(name, argv)
1014 char *name;
1015 char *argv[];
1016 {
1017 	int  c;
1018 	int i = 0;
1019 	char resp[LINE_MAX + 1];
1020 
1021 	(void) fflush(stdout); 	/* to flush possible `-print' */
1022 
1023 	if ((*argv != dummyarg) && (strcmp(*argv, name)))
1024 		(void) fprintf(stderr, "< %s ... %s >?   ", *argv, name);
1025 	else
1026 		(void) fprintf(stderr, "< {} ... %s >?   ", name);
1027 
1028 	(void) fflush(stderr);
1029 
1030 	while ((c = getchar()) != '\n') {
1031 		if (c == EOF)
1032 			exit(2);
1033 		if (i < LINE_MAX)
1034 			resp[i++] = c;
1035 	}
1036 	resp[i] = '\0';
1037 
1038 	if (yes_check(resp))
1039 		return (doexec(name, argv, NULL));
1040 	else
1041 		return (0);
1042 }
1043 
1044 /*
1045  * execute argv with {} replaced by name
1046  *
1047  * Per XPG6, find must exit non-zero if an invocation through
1048  * -exec, punctuated by a plus sign, exits non-zero, so set
1049  * exitcode if we see a non-zero exit.
1050  * exitcode should be NULL when -exec or -ok is not punctuated
1051  * by a plus sign.
1052  */
1053 
1054 static int
1055 doexec(char *name, char *argv[], int *exitcode)
1056 {
1057 	char *cp;
1058 	char **av = argv;
1059 	char *newargs[1 + SHELL_MAXARGS + 1];
1060 	int dummyseen = 0;
1061 	int i, j, status, rc, r = 0;
1062 	int exit_status = 0;
1063 	pid_t pid, pid1;
1064 
1065 	(void) fflush(stdout);	  /* to flush possible `-print' */
1066 	if (name) {
1067 		while (cp = *av++) {
1068 			if (cp == dummyarg) {
1069 				dummyseen = 1;
1070 				av[-1] = name;
1071 			}
1072 
1073 		}
1074 	}
1075 	if (argv[0] == NULL)    /* null command line */
1076 		return (r);
1077 
1078 	if ((pid = fork()) == -1) {
1079 		/* fork failed */
1080 		if (exitcode != NULL)
1081 			*exitcode = 1;
1082 		return (0);
1083 	}
1084 	if (pid != 0) {
1085 		/* parent */
1086 		do {
1087 			/* wait for child to exit */
1088 			if ((rc = wait(&r)) == -1 && errno != EINTR) {
1089 				(void) fprintf(stderr,
1090 				    gettext("wait failed %s"), strerror(errno));
1091 
1092 				if (exitcode != NULL)
1093 					*exitcode = 1;
1094 				return (0);
1095 			}
1096 		} while (rc != pid);
1097 	} else {
1098 		/* child */
1099 		(void) execvp(argv[0], argv);
1100 		if (errno != E2BIG)
1101 			exit(1);
1102 
1103 		/*
1104 		 * We are in a situation where argv[0] points to a
1105 		 * script without the interpreter line, e.g. #!/bin/sh.
1106 		 * execvp() will execute either /usr/bin/sh or
1107 		 * /usr/xpg4/bin/sh against the script, and you will be
1108 		 * limited to SHELL_MAXARGS arguments. If you try to
1109 		 * pass more than SHELL_MAXARGS arguments, execvp()
1110 		 * fails with E2BIG.
1111 		 * See usr/src/lib/libc/port/gen/execvp.c.
1112 		 *
1113 		 * In this situation, process the argument list by
1114 		 * packets of SHELL_MAXARGS arguments with respect of
1115 		 * the following rules:
1116 		 * 1. the invocations have to complete before find exits
1117 		 * 2. only one invocation can be running at a time
1118 		 */
1119 
1120 		i = 1;
1121 		newargs[0] = argv[0];
1122 
1123 		while (argv[i]) {
1124 			j = 1;
1125 			while (j <= SHELL_MAXARGS && argv[i]) {
1126 				newargs[j++] = argv[i++];
1127 			}
1128 			newargs[j] = NULL;
1129 
1130 			if ((pid1 = fork()) == -1) {
1131 				/* fork failed */
1132 				exit(1);
1133 			}
1134 			if (pid1 == 0) {
1135 				/* child */
1136 				(void) execvp(newargs[0], newargs);
1137 				exit(1);
1138 			}
1139 
1140 			status = 0;
1141 
1142 			do {
1143 				/* wait for the child to exit */
1144 				if ((rc = wait(&status)) == -1 &&
1145 				    errno != EINTR) {
1146 					(void) fprintf(stderr,
1147 					    gettext("wait failed %s"),
1148 					    strerror(errno));
1149 					exit(1);
1150 				}
1151 			} while (rc != pid1);
1152 
1153 			if (status)
1154 				exit_status = 1;
1155 		}
1156 		/* all the invocations have completed */
1157 		exit(exit_status);
1158 	}
1159 
1160 	if (name && dummyseen) {
1161 		for (av = argv; cp = *av++; ) {
1162 			if (cp == name)
1163 				av[-1] = dummyarg;
1164 		}
1165 	}
1166 
1167 	if (r && exitcode != NULL)
1168 		*exitcode = 3; /* use to indicate error in cmd invocation */
1169 
1170 	return (!r);
1171 }
1172 
1173 
1174 /*
1175  *  Table lookup routine
1176  */
1177 static struct Args *
1178 lookup(word)
1179 char *word;
1180 {
1181 	struct Args *argp = commands;
1182 	int second;
1183 	if (word == 0 || *word == 0)
1184 		return (0);
1185 	second = word[1];
1186 	while (*argp->name) {
1187 		if (second == argp->name[1] && strcmp(word, argp->name) == 0)
1188 			return (argp);
1189 		argp++;
1190 	}
1191 	return (0);
1192 }
1193 
1194 
1195 /*
1196  * Get space for variable length argument list
1197  */
1198 
1199 static struct Arglist *
1200 varargs(com)
1201 char **com;
1202 {
1203 	struct Arglist *ap;
1204 	int n;
1205 	char **ep;
1206 	if (varsize == 0) {
1207 		n = 2*sizeof (char **);
1208 		for (ep = environ; *ep; ep++)
1209 			n += (strlen(*ep)+sizeof (ep) + 1);
1210 		varsize = sizeof (struct Arglist)+ARG_MAX-PATH_MAX-n-1;
1211 	}
1212 	ap = (struct Arglist *)malloc(varsize+1);
1213 	ap->end = (char *)ap + varsize;
1214 	ap->nextstr = ap->end;
1215 	ap->nextvar = ap->arglist;
1216 	while (*ap->nextvar++ = *com++);
1217 	ap->nextvar--;
1218 	ap->firstvar = ap->nextvar;
1219 	ap->next = lastlist;
1220 	lastlist = ap;
1221 	return (ap);
1222 }
1223 
1224 /*
1225  * filter command support
1226  * fork and exec cmd(argv) according to mode:
1227  *
1228  *	"r"	with fp as stdin of cmd (default stdin), cmd stdout returned
1229  *	"w"	with fp as stdout of cmd (default stdout), cmd stdin returned
1230  */
1231 
1232 #define	CMDERR	((1<<8)-1)	/* command error exit code		*/
1233 #define	MAXCMDS	8		/* max # simultaneous cmdopen()'s	*/
1234 
1235 static struct			/* info for each cmdopen()		*/
1236 {
1237 	FILE	*fp;		/* returned by cmdopen()		*/
1238 	pid_t	pid;		/* pid used by cmdopen()		*/
1239 } cmdproc[MAXCMDS];
1240 
1241 static FILE *
1242 cmdopen(cmd, argv, mode, fp)
1243 char	*cmd;
1244 char	**argv;
1245 char	*mode;
1246 FILE	*fp;
1247 {
1248 	int	proc;
1249 	int	cmdfd;
1250 	int	usrfd;
1251 	int		pio[2];
1252 
1253 	switch (*mode) {
1254 	case 'r':
1255 		cmdfd = 1;
1256 		usrfd = 0;
1257 		break;
1258 	case 'w':
1259 		cmdfd = 0;
1260 		usrfd = 1;
1261 		break;
1262 	default:
1263 		return (0);
1264 	}
1265 
1266 	for (proc = 0; proc < MAXCMDS; proc++)
1267 		if (!cmdproc[proc].fp)
1268 			break;
1269 	if (proc >= MAXCMDS)
1270 		return (0);
1271 
1272 	if (pipe(pio))
1273 		return (0);
1274 
1275 	switch (cmdproc[proc].pid = fork()) {
1276 	case -1:
1277 		return (0);
1278 	case 0:
1279 		if (fp && fileno(fp) != usrfd) {
1280 			(void) close(usrfd);
1281 			if (dup2(fileno(fp), usrfd) != usrfd)
1282 				_exit(CMDERR);
1283 			(void) close(fileno(fp));
1284 		}
1285 		(void) close(cmdfd);
1286 		if (dup2(pio[cmdfd], cmdfd) != cmdfd)
1287 			_exit(CMDERR);
1288 		(void) close(pio[cmdfd]);
1289 		(void) close(pio[usrfd]);
1290 		(void) execvp(cmd, argv);
1291 		if (errno == ENOEXEC) {
1292 			char	**p;
1293 			char		**v;
1294 
1295 			/*
1296 			 * assume cmd is a shell script
1297 			 */
1298 
1299 			p = argv;
1300 			while (*p++);
1301 			if (v = (char **)malloc((p - argv + 1) *
1302 					sizeof (char **))) {
1303 				p = v;
1304 				*p++ = cmd;
1305 				if (*argv) argv++;
1306 				while (*p++ = *argv++);
1307 				(void) execv(getshell(), v);
1308 			}
1309 		}
1310 		_exit(CMDERR);
1311 		/*NOTREACHED*/
1312 	default:
1313 		(void) close(pio[cmdfd]);
1314 		return (cmdproc[proc].fp = fdopen(pio[usrfd], mode));
1315 	}
1316 }
1317 
1318 /*
1319  * close a stream opened by cmdopen()
1320  * -1 returned if cmdopen() had a problem
1321  * otherwise exit() status of command is returned
1322  */
1323 
1324 static int
1325 cmdclose(fp)
1326 FILE	*fp;
1327 {
1328 	int	i;
1329 	pid_t	p, pid;
1330 	int		status;
1331 
1332 	for (i = 0; i < MAXCMDS; i++)
1333 		if (fp == cmdproc[i].fp) break;
1334 	if (i >= MAXCMDS)
1335 		return (-1);
1336 	(void) fclose(fp);
1337 	cmdproc[i].fp = 0;
1338 	pid = cmdproc[i].pid;
1339 	while ((p = wait(&status)) != pid && p != (pid_t)-1);
1340 	if (p == pid) {
1341 		status = (status >> 8) & CMDERR;
1342 		if (status == CMDERR)
1343 			status = -1;
1344 	}
1345 	else
1346 		status = -1;
1347 	return (status);
1348 }
1349 
1350 /*
1351  * return pointer to the full path name of the shell
1352  *
1353  * SHELL is read from the environment and must start with /
1354  *
1355  * if set-uid or set-gid then the executable and its containing
1356  * directory must not be writable by the real user
1357  *
1358  * /usr/bin/sh is returned by default
1359  */
1360 
1361 char *
1362 getshell()
1363 {
1364 	char	*s;
1365 	char	*sh;
1366 	uid_t	u;
1367 	int	j;
1368 
1369 	if (((sh = getenv("SHELL")) != 0) && *sh == '/') {
1370 		if (u = getuid()) {
1371 			if ((u != geteuid() || getgid() != getegid()) &&
1372 			    access(sh, 2) == 0)
1373 				goto defshell;
1374 			s = strrchr(sh, '/');
1375 			*s = 0;
1376 			j = access(sh, 2);
1377 			*s = '/';
1378 			if (!j) goto defshell;
1379 		}
1380 		return (sh);
1381 	}
1382 defshell:
1383 	return ("/usr/bin/sh");
1384 }
1385 
1386 /*
1387  * the following functions implement the added "-ls" option
1388  */
1389 
1390 #include <utmpx.h>
1391 #include <sys/mkdev.h>
1392 
1393 struct		utmpx utmpx;
1394 #define	NMAX	(sizeof (utmpx.ut_name))
1395 #define	SCPYN(a, b)	(void) strncpy(a, b, NMAX)
1396 
1397 #define	NUID	64
1398 #define	NGID	64
1399 
1400 static struct ncache {
1401 	int	id;
1402 	char	name[NMAX+1];
1403 } nc[NUID], gc[NGID];
1404 
1405 /*
1406  * This function assumes that the password file is hashed
1407  * (or some such) to allow fast access based on a name key.
1408  */
1409 static char *
1410 getname(uid_t uid)
1411 {
1412 	struct passwd *pw;
1413 	int cp;
1414 
1415 #if	(((NUID) & ((NUID) - 1)) != 0)
1416 	cp = uid % (NUID);
1417 #else
1418 	cp = uid & ((NUID) - 1);
1419 #endif
1420 	if (nc[cp].id == uid && nc[cp].name[0])
1421 		return (nc[cp].name);
1422 	pw = getpwuid(uid);
1423 	if (!pw)
1424 		return (0);
1425 	nc[cp].id = uid;
1426 	SCPYN(nc[cp].name, pw->pw_name);
1427 	return (nc[cp].name);
1428 }
1429 
1430 /*
1431  * This function assumes that the group file is hashed
1432  * (or some such) to allow fast access based on a name key.
1433  */
1434 static char *
1435 getgroup(gid_t gid)
1436 {
1437 	struct group *gr;
1438 	int cp;
1439 
1440 #if	(((NGID) & ((NGID) - 1)) != 0)
1441 	cp = gid % (NGID);
1442 #else
1443 	cp = gid & ((NGID) - 1);
1444 #endif
1445 	if (gc[cp].id == gid && gc[cp].name[0])
1446 		return (gc[cp].name);
1447 	gr = getgrgid(gid);
1448 	if (!gr)
1449 		return (0);
1450 	gc[cp].id = gid;
1451 	SCPYN(gc[cp].name, gr->gr_name);
1452 	return (gc[cp].name);
1453 }
1454 
1455 #define	permoffset(who)		((who) * 3)
1456 #define	permission(who, type)	((type) >> permoffset(who))
1457 #define	kbytes(bytes)		(((bytes) + 1023) / 1024)
1458 
1459 static int
1460 list(file, stp)
1461 	char *file;
1462 	struct stat *stp;
1463 {
1464 	char pmode[32], uname[32], gname[32], fsize[32], ftime[32];
1465 	int trivial;
1466 
1467 /*
1468  * Each line below contains the relevant permission (column 1) and character
1469  * shown when  the corresponding execute bit is either clear (column 2)
1470  * or set (column 3)
1471  * These permissions are as shown by ls(1b)
1472  */
1473 	static long special[] = {	S_ISUID, 'S', 's',
1474 					S_ISGID, 'S', 's',
1475 					S_ISVTX, 'T', 't' };
1476 
1477 	static time_t sixmonthsago = -1;
1478 #ifdef	S_IFLNK
1479 	char flink[MAXPATHLEN + 1];
1480 #endif
1481 	int who;
1482 	char *cp;
1483 	char *tailname;
1484 	time_t now;
1485 	long long ksize;
1486 
1487 	if (file == NULL || stp == NULL)
1488 		return (-1);
1489 
1490 	(void) time(&now);
1491 	if (sixmonthsago == -1)
1492 		sixmonthsago = now - 6L*30L*24L*60L*60L;
1493 
1494 	switch (stp->st_mode & S_IFMT) {
1495 #ifdef	S_IFDIR
1496 	case S_IFDIR:	/* directory */
1497 		pmode[0] = 'd';
1498 		break;
1499 #endif
1500 #ifdef	S_IFCHR
1501 	case S_IFCHR:	/* character special */
1502 		pmode[0] = 'c';
1503 		break;
1504 #endif
1505 #ifdef	S_IFBLK
1506 	case S_IFBLK:	/* block special */
1507 		pmode[0] = 'b';
1508 		break;
1509 #endif
1510 #ifdef	S_IFIFO
1511 	case S_IFIFO:	/* fifo special */
1512 		pmode[0] = 'p';
1513 		break;
1514 #endif
1515 #ifdef	S_IFLNK
1516 	case S_IFLNK:	/* symbolic link */
1517 		pmode[0] = 'l';
1518 		break;
1519 #endif
1520 #ifdef	S_IFSOCK
1521 	case S_IFSOCK:	/* socket */
1522 		pmode[0] = 's';
1523 		break;
1524 #endif
1525 #ifdef	S_IFDOOR
1526 	case S_IFDOOR:	/* door */
1527 		pmode[0] = 'D';
1528 		break;
1529 #endif
1530 #ifdef	S_IFREG
1531 	case S_IFREG:	/* regular */
1532 		pmode[0] = '-';
1533 		break;
1534 #endif
1535 	default:
1536 		pmode[0] = '?';
1537 		break;
1538 	}
1539 
1540 	for (who = 0; who < 3; who++) {
1541 		int is_exec =  stp->st_mode & permission(who, S_IEXEC)? 1 : 0;
1542 
1543 		if (stp->st_mode & permission(who, S_IREAD))
1544 			pmode[permoffset(who) + 1] = 'r';
1545 		else
1546 			pmode[permoffset(who) + 1] = '-';
1547 
1548 		if (stp->st_mode & permission(who, S_IWRITE))
1549 			pmode[permoffset(who) + 2] = 'w';
1550 		else
1551 			pmode[permoffset(who) + 2] = '-';
1552 
1553 		if (stp->st_mode & special[who * 3])
1554 			pmode[permoffset(who) + 3] =
1555 				special[who * 3 + 1 + is_exec];
1556 		else if (is_exec)
1557 			pmode[permoffset(who) + 3] = 'x';
1558 		else
1559 			pmode[permoffset(who) + 3] = '-';
1560 	}
1561 
1562 	/*
1563 	 * Need to get the tail of the file name, since we have
1564 	 * already chdir()ed into the directory of the file
1565 	 */
1566 
1567 	tailname = gettail(file);
1568 
1569 	trivial = acl_trivial(tailname);
1570 	if (trivial == -1)
1571 		trivial =  0;
1572 
1573 	if (trivial == 1)
1574 		pmode[permoffset(who) + 1] = '+';
1575 	else
1576 		pmode[permoffset(who) + 1] = ' ';
1577 
1578 	pmode[permoffset(who) + 2] = '\0';
1579 
1580 	/*
1581 	 * Prepare uname and gname.  Always add a space afterwards
1582 	 * to keep columns from running together.
1583 	 */
1584 	cp = getname(stp->st_uid);
1585 	if (cp != NULL)
1586 		(void) sprintf(uname, "%-8s ", cp);
1587 	else
1588 		(void) sprintf(uname, "%-8u ", stp->st_uid);
1589 
1590 	cp = getgroup(stp->st_gid);
1591 	if (cp != NULL)
1592 		(void) sprintf(gname, "%-8s ", cp);
1593 	else
1594 		(void) sprintf(gname, "%-8u ", stp->st_gid);
1595 
1596 	if (pmode[0] == 'b' || pmode[0] == 'c')
1597 		(void) sprintf(fsize, "%3ld,%4ld",
1598 			major(stp->st_rdev), minor(stp->st_rdev));
1599 	else {
1600 		(void) sprintf(fsize, (stp->st_size < 100000000) ?
1601 			"%8lld" : "%lld", stp->st_size);
1602 #ifdef	S_IFLNK
1603 		if (pmode[0] == 'l') {
1604 
1605 
1606 			who = readlink(tailname, flink, sizeof (flink) - 1);
1607 
1608 			if (who >= 0)
1609 				flink[who] = '\0';
1610 			else
1611 				flink[0] = '\0';
1612 		}
1613 #endif
1614 	}
1615 
1616 	cp = ctime(&stp->st_mtime);
1617 	if (stp->st_mtime < sixmonthsago || stp->st_mtime > now)
1618 		(void) sprintf(ftime, "%-7.7s %-4.4s", cp + 4, cp + 20);
1619 	else
1620 		(void) sprintf(ftime, "%-12.12s", cp + 4);
1621 
1622 	(void) printf((stp->st_ino < 100000) ? "%5llu " :
1623 		"%llu ", stp->st_ino);  /* inode #	*/
1624 #ifdef	S_IFSOCK
1625 	ksize = (long long) kbytes(ldbtob(stp->st_blocks)); /* kbytes */
1626 #else
1627 	ksize = (long long) kbytes(stp->st_size); /* kbytes */
1628 #endif
1629 	(void) printf((ksize < 10000) ? "%4lld " : "%lld ", ksize);
1630 	(void) printf("%s %2ld %s%s%s %s %s%s%s\n",
1631 		pmode,					/* protection	*/
1632 		stp->st_nlink,				/* # of links	*/
1633 		uname,					/* owner	*/
1634 		gname,					/* group	*/
1635 		fsize,					/* # of bytes	*/
1636 		ftime,					/* modify time	*/
1637 		file,					/* name		*/
1638 #ifdef	S_IFLNK
1639 		(pmode[0] == 'l') ? " -> " : "",
1640 		(pmode[0] == 'l') ? flink  : ""		/* symlink	*/
1641 #else
1642 		"",
1643 		""
1644 #endif
1645 );
1646 
1647 	return (0);
1648 }
1649 
1650 static char *
1651 new_string(char *s)
1652 {
1653 	char *p = strdup(s);
1654 
1655 	if (p)
1656 		return (p);
1657 	(void) fprintf(stderr, gettext("%s: out of memory\n"), cmdname);
1658 	exit(1);
1659 	/*NOTREACHED*/
1660 }
1661 
1662 /*
1663  * Read remote file system types from REMOTE_FS into the
1664  * remote_fstypes array.
1665  */
1666 static void
1667 init_remote_fs()
1668 {
1669 	FILE    *fp;
1670 	char    line_buf[LINEBUF_SIZE];
1671 
1672 	if ((fp = fopen(REMOTE_FS, "r")) == NULL) {
1673 		(void) fprintf(stderr,
1674 		    gettext("%s: Warning: can't open %s, ignored\n"),
1675 		    REMOTE_FS, cmdname);
1676 		/* Use default string name for NFS */
1677 		remote_fstypes[fstype_index++] = "nfs";
1678 		return;
1679 	}
1680 
1681 	while (fgets(line_buf, sizeof (line_buf), fp) != NULL) {
1682 		char buf[LINEBUF_SIZE];
1683 
1684 		/* LINTED - unbounded string specifier */
1685 		(void) sscanf(line_buf, "%s", buf);
1686 		remote_fstypes[fstype_index++] = new_string(buf);
1687 
1688 		if (fstype_index == N_FSTYPES)
1689 			break;
1690 	}
1691 	(void) fclose(fp);
1692 }
1693 
1694 #define	NPERM	30			/* Largest machine */
1695 
1696 /*
1697  * The PERM struct is the machine that builds permissions.  The p_special
1698  * field contains what permissions need to be checked at run-time in
1699  * getmode().  This is one of 'X', 'u', 'g', or 'o'.  It contains '\0' to
1700  * indicate normal processing.
1701  */
1702 typedef	struct	PERMST	{
1703 	ushort_t	p_who;		/* Range of permission (e.g. ugo) */
1704 	ushort_t	p_perm;		/* Bits to turn on, off, assign */
1705 	uchar_t		p_op;		/* Operation: + - = */
1706 	uchar_t		p_special;	/* Special handling? */
1707 }	PERMST;
1708 
1709 #ifndef	S_ISVTX
1710 #define	S_ISVTX	0			/* Not .1 */
1711 #endif
1712 
1713 /* Mask values */
1714 #define	P_A	(S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO) /* allbits */
1715 #define	P_U	(S_ISUID|S_ISVTX|S_IRWXU)		/* user */
1716 #define	P_G	(S_ISGID|S_ISVTX|S_IRWXG)		/* group */
1717 #define	P_O	(S_ISVTX|S_IRWXO)			/* other */
1718 
1719 static	int	iswho(int c);
1720 static	int	isop(int c);
1721 static	int	isperm(PERMST *pp, int c);
1722 
1723 static	PERMST	machine[NPERM];		/* Permission construction machine */
1724 static	PERMST	*endp;			/* Last used PERM structure */
1725 
1726 static	uint_t	nowho;			/* No who for this mode (DOS kludge) */
1727 
1728 /*
1729  * Read an ASCII string containing the symbolic/octal mode and
1730  * compile an automaton that recognizes it.  The return value
1731  * is NULL if everything is OK, otherwise it is -1.
1732  */
1733 static int
1734 readmode(ascmode)
1735 const char *ascmode;
1736 {
1737 	const char *amode = ascmode;
1738 	PERMST *pp;
1739 	int seen_X;
1740 
1741 	nowho = 0;
1742 	seen_X = 0;
1743 	pp = &machine[0];
1744 	if (*amode >= '0' && *amode <= '7') {
1745 		int mode;
1746 
1747 		mode = 0;
1748 		while (*amode >= '0' && *amode <= '7')
1749 			mode = (mode<<3) + *amode++ - '0';
1750 		if (*amode != '\0')
1751 			return (-1);
1752 #if	S_ISUID != 04000 || S_ISGID != 02000 || \
1753 	S_IRUSR != 0400 || S_IWUSR != 0200 || S_IXUSR != 0100 || \
1754 	S_IRGRP != 0040 || S_IWGRP != 0020 || S_IXGRP != 0010 || \
1755 	S_IROTH != 0004 || S_IWOTH != 0002 || S_IXOTH != 0001
1756 		/*
1757 		 * There is no requirement of the octal mode bits being
1758 		 * the same as the S_ macros.
1759 		 */
1760 	{
1761 		mode_t mapping[] = {
1762 			S_IXOTH, S_IWOTH, S_IROTH,
1763 			S_IXGRP, S_IWGRP, S_IRGRP,
1764 			S_IXUSR, S_IWUSR, S_IRUSR,
1765 			S_ISGID, S_ISUID,
1766 			0
1767 		};
1768 		int i, newmode = 0;
1769 
1770 		for (i = 0; mapping[i] != 0; i++)
1771 			if (mode & (1<<i))
1772 				newmode |= mapping[i];
1773 		mode = newmode;
1774 	}
1775 #endif
1776 		pp->p_who = P_A;
1777 		pp->p_perm = mode;
1778 		pp->p_op = '=';
1779 	} else	for (;;) {
1780 		int t;
1781 		int who = 0;
1782 
1783 		while ((t = iswho(*amode)) != 0) {
1784 			++amode;
1785 			who |= t;
1786 		}
1787 		if (who == 0) {
1788 			mode_t currmask;
1789 			(void) umask(currmask = umask((mode_t)0));
1790 
1791 			/*
1792 			 * If no who specified, must use contents of
1793 			 * umask to determine which bits to flip.  This
1794 			 * is POSIX/V7/BSD behaviour, but not SVID.
1795 			 */
1796 			who = (~currmask)&P_A;
1797 			++nowho;
1798 		} else
1799 			nowho = 0;
1800 	samewho:
1801 		if (!isop(pp->p_op = *amode++))
1802 			return (-1);
1803 		pp->p_perm = 0;
1804 		pp->p_special = 0;
1805 		while ((t = isperm(pp, *amode)) != 0) {
1806 			if (pp->p_special == 'X') {
1807 				seen_X = 1;
1808 
1809 				if (pp->p_perm != 0) {
1810 					ushort_t op;
1811 
1812 					/*
1813 					 * Remember the 'who' for the previous
1814 					 * transformation.
1815 					 */
1816 					pp->p_who = who;
1817 					pp->p_special = 0;
1818 
1819 					op = pp->p_op;
1820 
1821 					/* Keep 'X' separate */
1822 					++pp;
1823 					pp->p_special = 'X';
1824 					pp->p_op = op;
1825 				}
1826 			} else if (seen_X) {
1827 				ushort_t op;
1828 
1829 				/* Remember the 'who' for the X */
1830 				pp->p_who = who;
1831 
1832 				op = pp->p_op;
1833 
1834 				/* Keep 'X' separate */
1835 				++pp;
1836 				pp->p_perm = 0;
1837 				pp->p_special = 0;
1838 				pp->p_op = op;
1839 			}
1840 			++amode;
1841 			pp->p_perm |= t;
1842 		}
1843 
1844 		/*
1845 		 * These returned 0, but were actually parsed, so
1846 		 * don't look at them again.
1847 		 */
1848 		switch (pp->p_special) {
1849 		case 'u':
1850 		case 'g':
1851 		case 'o':
1852 			++amode;
1853 			break;
1854 		}
1855 		pp->p_who = who;
1856 		switch (*amode) {
1857 		case '\0':
1858 			break;
1859 
1860 		case ',':
1861 			++amode;
1862 			++pp;
1863 			continue;
1864 
1865 		default:
1866 			++pp;
1867 			goto samewho;
1868 		}
1869 		break;
1870 	}
1871 	endp = pp;
1872 	return (NULL);
1873 }
1874 
1875 /*
1876  * Given a character from the mode, return the associated
1877  * value as who (user designation) mask or 0 if this isn't valid.
1878  */
1879 static int
1880 iswho(c)
1881 int c;
1882 {
1883 	switch (c) {
1884 	case 'a':
1885 		return (P_A);
1886 
1887 	case 'u':
1888 		return (P_U);
1889 
1890 	case 'g':
1891 		return (P_G);
1892 
1893 	case 'o':
1894 		return (P_O);
1895 
1896 	default:
1897 		return (0);
1898 	}
1899 	/* NOTREACHED */
1900 }
1901 
1902 /*
1903  * Return non-zero if this is a valid op code
1904  * in a symbolic mode.
1905  */
1906 static int
1907 isop(c)
1908 int c;
1909 {
1910 	switch (c) {
1911 	case '+':
1912 	case '-':
1913 	case '=':
1914 		return (1);
1915 
1916 	default:
1917 		return (0);
1918 	}
1919 	/* NOTREACHED */
1920 }
1921 
1922 /*
1923  * Return the permission bits implied by this character or 0
1924  * if it isn't valid.  Also returns 0 when the pseudo-permissions 'u', 'g', or
1925  * 'o' are used, and sets pp->p_special to the one used.
1926  */
1927 static int
1928 isperm(pp, c)
1929 PERMST *pp;
1930 int c;
1931 {
1932 	switch (c) {
1933 	case 'u':
1934 	case 'g':
1935 	case 'o':
1936 		pp->p_special = c;
1937 		return (0);
1938 
1939 	case 'r':
1940 		return (S_IRUSR|S_IRGRP|S_IROTH);
1941 
1942 	case 'w':
1943 		return (S_IWUSR|S_IWGRP|S_IWOTH);
1944 
1945 	case 'x':
1946 		return (S_IXUSR|S_IXGRP|S_IXOTH);
1947 
1948 #if S_ISVTX != 0
1949 	case 't':
1950 		return (S_ISVTX);
1951 #endif
1952 
1953 	case 'X':
1954 		pp->p_special = 'X';
1955 		return (S_IXUSR|S_IXGRP|S_IXOTH);
1956 
1957 #if S_ISVTX != 0
1958 	case 'a':
1959 		return (S_ISVTX);
1960 #endif
1961 
1962 	case 'h':
1963 		return (S_ISUID);
1964 
1965 	/*
1966 	 * This change makes:
1967 	 *	chmod +s file
1968 	 * set the system bit on dos but means that
1969 	 *	chmod u+s file
1970 	 *	chmod g+s file
1971 	 *	chmod a+s file
1972 	 * are all like UNIX.
1973 	 */
1974 	case 's':
1975 		return (nowho ? S_ISGID : S_ISGID|S_ISUID);
1976 
1977 	default:
1978 		return (0);
1979 	}
1980 	/* NOTREACHED */
1981 }
1982 
1983 /*
1984  * Execute the automaton that is created by readmode()
1985  * to generate the final mode that will be used.  This
1986  * code is passed a starting mode that is usually the original
1987  * mode of the file being changed (or 0).  Note that this mode must contain
1988  * the file-type bits as well, so that S_ISDIR will succeed on directories.
1989  */
1990 static mode_t
1991 getmode(mode_t startmode)
1992 {
1993 	PERMST *pp;
1994 	mode_t temp;
1995 	mode_t perm;
1996 
1997 	for (pp = &machine[0]; pp <= endp; ++pp) {
1998 		perm = (mode_t)0;
1999 		/*
2000 		 * For the special modes 'u', 'g' and 'o', the named portion
2001 		 * of the mode refers to after the previous clause has been
2002 		 * processed, while the 'X' mode refers to the contents of the
2003 		 * mode before any clauses have been processed.
2004 		 *
2005 		 * References: P1003.2/D11.2, Section 4.7.7,
2006 		 *  lines 2568-2570, 2578-2583
2007 		 */
2008 		switch (pp->p_special) {
2009 		case 'u':
2010 			temp = startmode & S_IRWXU;
2011 			if (temp & (S_IRUSR|S_IRGRP|S_IROTH))
2012 				perm |= ((S_IRUSR|S_IRGRP|S_IROTH) &
2013 				    pp->p_who);
2014 			if (temp & (S_IWUSR|S_IWGRP|S_IWOTH))
2015 				perm |= ((S_IWUSR|S_IWGRP|S_IWOTH) & pp->p_who);
2016 			if (temp & (S_IXUSR|S_IXGRP|S_IXOTH))
2017 				perm |= ((S_IXUSR|S_IXGRP|S_IXOTH) & pp->p_who);
2018 			break;
2019 
2020 		case 'g':
2021 			temp = startmode & S_IRWXG;
2022 			if (temp & (S_IRUSR|S_IRGRP|S_IROTH))
2023 				perm |= ((S_IRUSR|S_IRGRP|S_IROTH) & pp->p_who);
2024 			if (temp & (S_IWUSR|S_IWGRP|S_IWOTH))
2025 				perm |= ((S_IWUSR|S_IWGRP|S_IWOTH) & pp->p_who);
2026 			if (temp & (S_IXUSR|S_IXGRP|S_IXOTH))
2027 				perm |= ((S_IXUSR|S_IXGRP|S_IXOTH) & pp->p_who);
2028 			break;
2029 
2030 		case 'o':
2031 			temp = startmode & S_IRWXO;
2032 			if (temp & (S_IRUSR|S_IRGRP|S_IROTH))
2033 				perm |= ((S_IRUSR|S_IRGRP|S_IROTH) & pp->p_who);
2034 			if (temp & (S_IWUSR|S_IWGRP|S_IWOTH))
2035 				perm |= ((S_IWUSR|S_IWGRP|S_IWOTH) & pp->p_who);
2036 			if (temp & (S_IXUSR|S_IXGRP|S_IXOTH))
2037 				perm |= ((S_IXUSR|S_IXGRP|S_IXOTH) & pp->p_who);
2038 			break;
2039 
2040 		case 'X':
2041 			perm = pp->p_perm;
2042 			break;
2043 
2044 		default:
2045 			perm = pp->p_perm;
2046 			break;
2047 		}
2048 		switch (pp->p_op) {
2049 		case '-':
2050 			startmode &= ~(perm & pp->p_who);
2051 			break;
2052 
2053 		case '=':
2054 			startmode &= ~pp->p_who;
2055 			/* FALLTHROUGH */
2056 		case '+':
2057 			startmode |= (perm & pp->p_who);
2058 			break;
2059 		}
2060 	}
2061 	return (startmode);
2062 }
2063 
2064 /*
2065  * Returns the last component of a path name, unless it is
2066  * an absolute path, in which case it returns the whole path
2067  */
2068 static char
2069 *gettail(char *fname)
2070 {
2071 	char	*base = fname;
2072 
2073 	if (*fname != '/') {
2074 		if ((base = strrchr(fname, '/')) != NULL)
2075 			base++;
2076 		else
2077 			base = fname;
2078 	}
2079 	return (base);
2080 }
2081