xref: /titanic_51/usr/src/cmd/find/find.c (revision 6e58529ce18ff7fbcb8bd13187103992c1edd122)
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 2007 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 <libgen.h>
56 #include <ctype.h>
57 #include <wait.h>
58 #include <fnmatch.h>
59 #include <langinfo.h>
60 #include <ftw.h>
61 
62 #define	A_DAY		(long)(60*60*24)	/* a day full of seconds */
63 #define	A_MIN		(long)(60)
64 #define	BLKSIZ		512
65 #define	round(x, s)	(((x)+(s)-1)&~((s)-1))
66 #ifndef FTW_SLN
67 #define	FTW_SLN		7
68 #endif
69 #define	LINEBUF_SIZE		LINE_MAX	/* input or output lines */
70 #define	REMOTE_FS		"/etc/dfs/fstypes"
71 #define	N_FSTYPES		20
72 #define	SHELL_MAXARGS		253	/* see doexec() for description */
73 
74 /*
75  * This is the list of operations
76  * F_USER and F_GROUP are named to avoid conflict with USER and GROUP defined
77  * in sys/acl.h
78  */
79 
80 enum Command
81 {
82 	PRINT, DEPTH, LOCAL, MOUNT, ATIME, MTIME, CTIME, NEWER,
83 	NAME, F_USER, F_GROUP, INUM, SIZE, LINKS, PERM, EXEC, OK, CPIO, NCPIO,
84 	TYPE, AND, OR, NOT, LPAREN, RPAREN, CSIZE, VARARGS, FOLLOW,
85 	PRUNE, NOUSER, NOGRP, FSTYPE, LS, XATTR, ACL, MMIN, AMIN, CMIN
86 };
87 
88 enum Type
89 {
90 	Unary, Id, Num, Str, Exec, Cpio, Op
91 };
92 
93 struct Args
94 {
95 	char		name[10];
96 	enum Command	action;
97 	enum Type	type;
98 };
99 
100 /*
101  * Except for pathnames, these are the only legal arguments
102  */
103 static struct Args commands[] =
104 {
105 	"!",		NOT,	Op,
106 	"(",		LPAREN,	Unary,
107 	")",		RPAREN,	Unary,
108 	"-a",		AND,	Op,
109 	"-amin",	AMIN,	Num,
110 	"-atime",	ATIME,	Num,
111 	"-cpio",	CPIO,	Cpio,
112 	"-cmin",	CMIN,	Num,
113 	"-ctime",	CTIME,	Num,
114 	"-depth",	DEPTH,	Unary,
115 	"-exec",	EXEC,	Exec,
116 	"-follow",	FOLLOW, Unary,
117 	"-group",	F_GROUP,	Num,
118 	"-inum",	INUM,	Num,
119 	"-links",	LINKS,	Num,
120 	"-local",	LOCAL,	Unary,
121 	"-mount",	MOUNT,	Unary,
122 	"-mmin",	MMIN,	Num,
123 	"-mtime",	MTIME,	Num,
124 	"-name",	NAME,	Str,
125 	"-ncpio",	NCPIO,  Cpio,
126 	"-newer",	NEWER,	Str,
127 	"-o",		OR,	Op,
128 	"-ok",		OK,	Exec,
129 	"-perm",	PERM,	Num,
130 	"-print",	PRINT,	Unary,
131 	"-size",	SIZE,	Num,
132 	"-type",	TYPE,	Num,
133 	"-xdev",	MOUNT,	Unary,
134 	"-user",	F_USER,	Num,
135 	"-prune",	PRUNE,	Unary,
136 	"-nouser",	NOUSER,	Unary,
137 	"-nogroup",	NOGRP,	Unary,
138 	"-fstype",	FSTYPE,	Str,
139 	"-ls",		LS,	Unary,
140 	"-xattr",	XATTR,	Unary,
141 	"-acl",		ACL,	Unary,
142 	NULL,		0,	0
143 };
144 
145 union Item
146 {
147 	struct Node	*np;
148 	struct Arglist	*vp;
149 	time_t		t;
150 	char		*cp;
151 	char		**ap;
152 	long		l;
153 	int		i;
154 	long long	ll;
155 };
156 
157 struct Node
158 {
159 	struct Node	*next;
160 	enum Command	action;
161 	enum Type	type;
162 	union Item	first;
163 	union Item	second;
164 };
165 
166 /* if no -print, -exec or -ok replace "expression" with "(expression) -print" */
167 static	struct	Node PRINT_NODE = { 0, PRINT, 0, 0};
168 static	struct	Node LPAREN_NODE = { 0, LPAREN, 0, 0};
169 
170 
171 /*
172  * Prototype variable size arglist buffer
173  */
174 
175 struct Arglist
176 {
177 	struct Arglist	*next;
178 	char		*end;
179 	char		*nextstr;
180 	char		**firstvar;
181 	char		**nextvar;
182 	char		*arglist[1];
183 };
184 
185 
186 static int		compile();
187 static int		execute();
188 static int		doexec(char *, char **, int *);
189 static struct Args	*lookup();
190 static int		ok();
191 static void		usage(void)	__NORETURN;
192 static struct Arglist	*varargs();
193 static int		list();
194 static char		*getgroup();
195 static FILE		*cmdopen();
196 static int		cmdclose();
197 static char		*getshell();
198 static void 		init_remote_fs();
199 static char		*getname();
200 static int		readmode();
201 static mode_t		getmode();
202 static char		*gettail();
203 
204 
205 static int walkflags = FTW_CHDIR|FTW_PHYS|FTW_ANYERR|FTW_NOLOOP;
206 static struct Node	*savetnode;
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 	savetnode = malloc((argc + 1) * sizeof (struct Node));
295 	(void) memset(topnode, 0, (argc + 1) * sizeof (struct Node));
296 	(void) memset(savetnode, 0, (argc + 1) * sizeof (struct Node));
297 
298 	if (compile(argv + paths, topnode, &action_expression) == 0) {
299 		/* no expression, default to -print */
300 		(void) memcpy(topnode, &PRINT_NODE, sizeof (struct Node));
301 	} else if (!action_expression) {
302 		/*
303 		 * if no action expression, insert an LPAREN node above topnode,
304 		 * with a PRINT node as its next node
305 		 */
306 		struct Node *savenode;
307 
308 		if (freenode == NULL) {
309 			(void) fprintf(stderr, gettext("%s: can't append -print"
310 				" implicitly; try explicit -print option\n"),
311 				cmdname);
312 			exit(1);
313 		}
314 		savenode = topnode;
315 		topnode = freenode++;
316 		(void) memcpy(topnode, &LPAREN_NODE, sizeof (struct Node));
317 		topnode->next = freenode;
318 		topnode->first.np = savenode;
319 		(void) memcpy(topnode->next, &PRINT_NODE, sizeof (struct Node));
320 	}
321 	(void) memcpy(savetnode, topnode, ((argc + 1) * sizeof (struct Node)));
322 
323 	while (paths--) {
324 		char *curpath;
325 		struct stat sb;
326 
327 		curpath = *(argv++);
328 
329 		/*
330 		 * If -H is specified, it means we walk the first
331 		 * level (pathname on command line) logically, following
332 		 * symlinks, but lower levels are walked physically.
333 		 * We use our own secret interface to nftw() to change
334 		 * the from stat to lstat after the top level is walked.
335 		 */
336 		if (hflag) {
337 			if (stat(curpath, &sb) < 0 && errno == ENOENT)
338 				walkflags &= ~FTW_HOPTION;
339 			else
340 				walkflags |= FTW_HOPTION;
341 		}
342 
343 		/*
344 		 * We need this check as nftw needs a CWD and we have no
345 		 * way of returning back from that code with a meaningful
346 		 * error related to this
347 		 */
348 		if ((cwdpath = getcwd(NULL, PATH_MAX)) == NULL) {
349 			(void) fprintf(stderr,
350 				gettext("%s : cannot get the current working "
351 					"directory\n"), cmdname);
352 			exit(1);
353 		} else
354 			free(cwdpath);
355 
356 
357 		if (nftw(curpath, execute, 1000, walkflags)) {
358 			(void) fprintf(stderr,
359 			    gettext("%s: cannot open %s: %s\n"),
360 			    cmdname, curpath, strerror(errno));
361 			error = 1;
362 		}
363 
364 		if (paths > 1)
365 			(void) memcpy(topnode, savetnode,
366 			    ((argc + 1) * sizeof (struct Node)));
367 	}
368 
369 	/* execute any remaining variable length lists */
370 	while (lastlist) {
371 		if (lastlist->end != lastlist->nextstr) {
372 			*lastlist->nextvar = 0;
373 			(void) doexec((char *)0, lastlist->arglist,
374 			    &exec_exitcode);
375 		}
376 		lastlist = lastlist->next;
377 	}
378 	if (output != stdout)
379 		return (cmdclose(output));
380 	return ((exec_exitcode != 0) ? exec_exitcode : error);
381 }
382 
383 /*
384  * compile the arguments
385  */
386 
387 static int
388 compile(argv, np, actionp)
389 char **argv;
390 struct Node *np;
391 int *actionp;
392 {
393 	char *b;
394 	char **av;
395 	struct Node *oldnp = topnode;
396 	struct Args *argp;
397 	char **com;
398 	int i;
399 	enum Command wasop = PRINT;
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 			/*
920 			 * XPG4 find should not treat a leading '.' in a
921 			 * filename specially for pattern matching.
922 			 * /usr/bin/find  will not pattern match a leading
923 			 * '.' in a filename, unless '.' is explicitly
924 			 * specified.
925 			 */
926 #ifdef XPG4
927 			val = !fnmatch(np->first.cp,
928 			    name+state->base, 0);
929 #else
930 			val = !fnmatch(np->first.cp,
931 			    name+state->base, FNM_PERIOD);
932 #endif
933 			break;
934 		}
935 
936 		case PRUNE:
937 			if (type == FTW_D)
938 				state->quit = FTW_PRUNE;
939 			val = 1;
940 			break;
941 		case NOUSER:
942 			val = ((getpwuid(statb->st_uid)) == 0);
943 			break;
944 		case NOGRP:
945 			val = ((getgrgid(statb->st_gid)) == 0);
946 			break;
947 		case FSTYPE:
948 			val = (strcmp(np->first.cp, statb->st_fstype) == 0);
949 			break;
950 		case CPIO:
951 			output = (FILE *)np->first.l;
952 			(void) fprintf(output, "%s\n", name);
953 			val = 1;
954 			break;
955 		case PRINT:
956 			(void) fprintf(stdout, "%s\n", name);
957 			val = 1;
958 			break;
959 		case LS:
960 			(void) list(name, statb);
961 			val = 1;
962 			break;
963 		case XATTR:
964 			filename = gettail(name);
965 			val = (pathconf(filename, _PC_XATTR_EXISTS) == 1);
966 			break;
967 		case ACL:
968 			/*
969 			 * Need to get the tail of the file name, since we have
970 			 * already chdir()ed into the directory (performed in
971 			 * nftw()) of the file
972 			 */
973 			filename = gettail(name);
974 			val = acl_trivial(name);
975 			break;
976 		}
977 		/*
978 		 * evaluate 'val' and 'not' (exclusive-or)
979 		 * if no inversion (not == 1), return only when val == 0
980 		 * (primary not true). Otherwise, invert the primary
981 		 * and return when the primary is true.
982 		 * 'Lastval' saves the last result (fail or pass) when
983 		 * returning back to the calling routine.
984 		 */
985 		if (val^not) {
986 			lastval = 0;
987 			return (0);
988 		}
989 		lastval = 1;
990 		not = 1;
991 		np = np->next;
992 	}
993 	return (0);
994 }
995 
996 /*
997  * code for the -ok option
998  */
999 
1000 static int
1001 ok(name, argv)
1002 char *name;
1003 char *argv[];
1004 {
1005 	int c, yes = 0;
1006 
1007 	(void) fflush(stdout); 	/* to flush possible `-print' */
1008 
1009 	if ((*argv != dummyarg) && (strcmp(*argv, name)))
1010 		(void) fprintf(stderr, "< %s ... %s >?   ", *argv, name);
1011 	else
1012 		(void) fprintf(stderr, "< {} ... %s >?   ", name);
1013 
1014 	(void) fflush(stderr);
1015 	if ((c = tolower(getchar())) == *nl_langinfo(YESSTR))
1016 		yes = 1;
1017 	while (c != '\n')
1018 		if (c == EOF)
1019 			exit(2);
1020 		else
1021 			c = getchar();
1022 	return (yes? doexec(name, argv, NULL): 0);
1023 }
1024 
1025 /*
1026  * execute argv with {} replaced by name
1027  *
1028  * Per XPG6, find must exit non-zero if an invocation through
1029  * -exec, punctuated by a plus sign, exits non-zero, so set
1030  * exitcode if we see a non-zero exit.
1031  * exitcode should be NULL when -exec or -ok is not punctuated
1032  * by a plus sign.
1033  */
1034 
1035 static int
1036 doexec(char *name, char *argv[], int *exitcode)
1037 {
1038 	char *cp;
1039 	char **av = argv;
1040 	char *newargs[1 + SHELL_MAXARGS + 1];
1041 	int dummyseen = 0;
1042 	int i, j, status, rc, r = 0;
1043 	int exit_status = 0;
1044 	pid_t pid, pid1;
1045 
1046 	(void) fflush(stdout);	  /* to flush possible `-print' */
1047 	if (name) {
1048 		while (cp = *av++) {
1049 			if (cp == dummyarg) {
1050 				dummyseen = 1;
1051 				av[-1] = name;
1052 			}
1053 
1054 		}
1055 	}
1056 	if (argv[0] == NULL)    /* null command line */
1057 		return (r);
1058 
1059 	if ((pid = fork()) == -1) {
1060 		/* fork failed */
1061 		if (exitcode != NULL)
1062 			*exitcode = 1;
1063 		return (0);
1064 	}
1065 	if (pid != 0) {
1066 		/* parent */
1067 		do {
1068 			/* wait for child to exit */
1069 			if ((rc = wait(&r)) == -1 && errno != EINTR) {
1070 				(void) fprintf(stderr,
1071 				    gettext("wait failed %s"), strerror(errno));
1072 
1073 				if (exitcode != NULL)
1074 					*exitcode = 1;
1075 				return (0);
1076 			}
1077 		} while (rc != pid);
1078 	} else {
1079 		/* child */
1080 		(void) execvp(argv[0], argv);
1081 		if (errno != E2BIG)
1082 			exit(1);
1083 
1084 		/*
1085 		 * We are in a situation where argv[0] points to a
1086 		 * script without the interpreter line, e.g. #!/bin/sh.
1087 		 * execvp() will execute either /usr/bin/sh or
1088 		 * /usr/xpg4/bin/sh against the script, and you will be
1089 		 * limited to SHELL_MAXARGS arguments. If you try to
1090 		 * pass more than SHELL_MAXARGS arguments, execvp()
1091 		 * fails with E2BIG.
1092 		 * See usr/src/lib/libc/port/gen/execvp.c.
1093 		 *
1094 		 * In this situation, process the argument list by
1095 		 * packets of SHELL_MAXARGS arguments with respect of
1096 		 * the following rules:
1097 		 * 1. the invocations have to complete before find exits
1098 		 * 2. only one invocation can be running at a time
1099 		 */
1100 
1101 		i = 1;
1102 		newargs[0] = argv[0];
1103 
1104 		while (argv[i]) {
1105 			j = 1;
1106 			while (j <= SHELL_MAXARGS && argv[i]) {
1107 				newargs[j++] = argv[i++];
1108 			}
1109 			newargs[j] = NULL;
1110 
1111 			if ((pid1 = fork()) == -1) {
1112 				/* fork failed */
1113 				exit(1);
1114 			}
1115 			if (pid1 == 0) {
1116 				/* child */
1117 				(void) execvp(newargs[0], newargs);
1118 				exit(1);
1119 			}
1120 
1121 			status = 0;
1122 
1123 			do {
1124 				/* wait for the child to exit */
1125 				if ((rc = wait(&status)) == -1 &&
1126 				    errno != EINTR) {
1127 					(void) fprintf(stderr,
1128 					    gettext("wait failed %s"),
1129 					    strerror(errno));
1130 					exit(1);
1131 				}
1132 			} while (rc != pid1);
1133 
1134 			if (status)
1135 				exit_status = 1;
1136 		}
1137 		/* all the invocations have completed */
1138 		exit(exit_status);
1139 	}
1140 
1141 	if (name && dummyseen) {
1142 		for (av = argv; cp = *av++; ) {
1143 			if (cp == name)
1144 				av[-1] = dummyarg;
1145 		}
1146 	}
1147 
1148 	if (r && exitcode != NULL)
1149 		*exitcode = 3; /* use to indicate error in cmd invocation */
1150 
1151 	return (!r);
1152 }
1153 
1154 
1155 /*
1156  *  Table lookup routine
1157  */
1158 static struct Args *
1159 lookup(word)
1160 char *word;
1161 {
1162 	struct Args *argp = commands;
1163 	int second;
1164 	if (word == 0 || *word == 0)
1165 		return (0);
1166 	second = word[1];
1167 	while (*argp->name) {
1168 		if (second == argp->name[1] && strcmp(word, argp->name) == 0)
1169 			return (argp);
1170 		argp++;
1171 	}
1172 	return (0);
1173 }
1174 
1175 
1176 /*
1177  * Get space for variable length argument list
1178  */
1179 
1180 static struct Arglist *
1181 varargs(com)
1182 char **com;
1183 {
1184 	struct Arglist *ap;
1185 	int n;
1186 	char **ep;
1187 	if (varsize == 0) {
1188 		n = 2*sizeof (char **);
1189 		for (ep = environ; *ep; ep++)
1190 			n += (strlen(*ep)+sizeof (ep) + 1);
1191 		varsize = sizeof (struct Arglist)+ARG_MAX-PATH_MAX-n-1;
1192 	}
1193 	ap = (struct Arglist *)malloc(varsize+1);
1194 	ap->end = (char *)ap + varsize;
1195 	ap->nextstr = ap->end;
1196 	ap->nextvar = ap->arglist;
1197 	while (*ap->nextvar++ = *com++);
1198 	ap->nextvar--;
1199 	ap->firstvar = ap->nextvar;
1200 	ap->next = lastlist;
1201 	lastlist = ap;
1202 	return (ap);
1203 }
1204 
1205 /*
1206  * filter command support
1207  * fork and exec cmd(argv) according to mode:
1208  *
1209  *	"r"	with fp as stdin of cmd (default stdin), cmd stdout returned
1210  *	"w"	with fp as stdout of cmd (default stdout), cmd stdin returned
1211  */
1212 
1213 #define	CMDERR	((1<<8)-1)	/* command error exit code		*/
1214 #define	MAXCMDS	8		/* max # simultaneous cmdopen()'s	*/
1215 
1216 static struct			/* info for each cmdopen()		*/
1217 {
1218 	FILE	*fp;		/* returned by cmdopen()		*/
1219 	pid_t	pid;		/* pid used by cmdopen()		*/
1220 } cmdproc[MAXCMDS];
1221 
1222 static FILE *
1223 cmdopen(cmd, argv, mode, fp)
1224 char	*cmd;
1225 char	**argv;
1226 char	*mode;
1227 FILE	*fp;
1228 {
1229 	int	proc;
1230 	int	cmdfd;
1231 	int	usrfd;
1232 	int		pio[2];
1233 
1234 	switch (*mode) {
1235 	case 'r':
1236 		cmdfd = 1;
1237 		usrfd = 0;
1238 		break;
1239 	case 'w':
1240 		cmdfd = 0;
1241 		usrfd = 1;
1242 		break;
1243 	default:
1244 		return (0);
1245 	}
1246 
1247 	for (proc = 0; proc < MAXCMDS; proc++)
1248 		if (!cmdproc[proc].fp)
1249 			break;
1250 	if (proc >= MAXCMDS)
1251 		return (0);
1252 
1253 	if (pipe(pio))
1254 		return (0);
1255 
1256 	switch (cmdproc[proc].pid = fork()) {
1257 	case -1:
1258 		return (0);
1259 	case 0:
1260 		if (fp && fileno(fp) != usrfd) {
1261 			(void) close(usrfd);
1262 			if (dup2(fileno(fp), usrfd) != usrfd)
1263 				_exit(CMDERR);
1264 			(void) close(fileno(fp));
1265 		}
1266 		(void) close(cmdfd);
1267 		if (dup2(pio[cmdfd], cmdfd) != cmdfd)
1268 			_exit(CMDERR);
1269 		(void) close(pio[cmdfd]);
1270 		(void) close(pio[usrfd]);
1271 		(void) execvp(cmd, argv);
1272 		if (errno == ENOEXEC) {
1273 			char	**p;
1274 			char		**v;
1275 
1276 			/*
1277 			 * assume cmd is a shell script
1278 			 */
1279 
1280 			p = argv;
1281 			while (*p++);
1282 			if (v = (char **)malloc((p - argv + 1) *
1283 					sizeof (char **))) {
1284 				p = v;
1285 				*p++ = cmd;
1286 				if (*argv) argv++;
1287 				while (*p++ = *argv++);
1288 				(void) execv(getshell(), v);
1289 			}
1290 		}
1291 		_exit(CMDERR);
1292 		/*NOTREACHED*/
1293 	default:
1294 		(void) close(pio[cmdfd]);
1295 		return (cmdproc[proc].fp = fdopen(pio[usrfd], mode));
1296 	}
1297 }
1298 
1299 /*
1300  * close a stream opened by cmdopen()
1301  * -1 returned if cmdopen() had a problem
1302  * otherwise exit() status of command is returned
1303  */
1304 
1305 static int
1306 cmdclose(fp)
1307 FILE	*fp;
1308 {
1309 	int	i;
1310 	pid_t	p, pid;
1311 	int		status;
1312 
1313 	for (i = 0; i < MAXCMDS; i++)
1314 		if (fp == cmdproc[i].fp) break;
1315 	if (i >= MAXCMDS)
1316 		return (-1);
1317 	(void) fclose(fp);
1318 	cmdproc[i].fp = 0;
1319 	pid = cmdproc[i].pid;
1320 	while ((p = wait(&status)) != pid && p != (pid_t)-1);
1321 	if (p == pid) {
1322 		status = (status >> 8) & CMDERR;
1323 		if (status == CMDERR)
1324 			status = -1;
1325 	}
1326 	else
1327 		status = -1;
1328 	return (status);
1329 }
1330 
1331 /*
1332  * return pointer to the full path name of the shell
1333  *
1334  * SHELL is read from the environment and must start with /
1335  *
1336  * if set-uid or set-gid then the executable and its containing
1337  * directory must not be writable by the real user
1338  *
1339  * /usr/bin/sh is returned by default
1340  */
1341 
1342 char *
1343 getshell()
1344 {
1345 	char	*s;
1346 	char	*sh;
1347 	uid_t	u;
1348 	int	j;
1349 
1350 	if (((sh = getenv("SHELL")) != 0) && *sh == '/') {
1351 		if (u = getuid()) {
1352 			if ((u != geteuid() || getgid() != getegid()) &&
1353 					!access(sh, 2))
1354 				goto defshell;
1355 			s = strrchr(sh, '/');
1356 			*s = 0;
1357 			j = access(sh, 2);
1358 			*s = '/';
1359 			if (!j) goto defshell;
1360 		}
1361 		return (sh);
1362 	}
1363 defshell:
1364 	return ("/usr/bin/sh");
1365 }
1366 
1367 /*
1368  * the following functions implement the added "-ls" option
1369  */
1370 
1371 #include <utmpx.h>
1372 #include <sys/mkdev.h>
1373 
1374 struct		utmpx utmpx;
1375 #define	NMAX	(sizeof (utmpx.ut_name))
1376 #define	SCPYN(a, b)	(void) strncpy(a, b, NMAX)
1377 
1378 #define	NUID	64
1379 #define	NGID	64
1380 
1381 static struct ncache {
1382 	int	id;
1383 	char	name[NMAX+1];
1384 } nc[NUID], gc[NGID];
1385 
1386 /*
1387  * This function assumes that the password file is hashed
1388  * (or some such) to allow fast access based on a name key.
1389  */
1390 static char *
1391 getname(uid_t uid)
1392 {
1393 	struct passwd *pw;
1394 	int cp;
1395 
1396 #if	(((NUID) & ((NUID) - 1)) != 0)
1397 	cp = uid % (NUID);
1398 #else
1399 	cp = uid & ((NUID) - 1);
1400 #endif
1401 	if (nc[cp].id == uid && nc[cp].name[0])
1402 		return (nc[cp].name);
1403 	pw = getpwuid(uid);
1404 	if (!pw)
1405 		return (0);
1406 	nc[cp].id = uid;
1407 	SCPYN(nc[cp].name, pw->pw_name);
1408 	return (nc[cp].name);
1409 }
1410 
1411 /*
1412  * This function assumes that the group file is hashed
1413  * (or some such) to allow fast access based on a name key.
1414  */
1415 static char *
1416 getgroup(gid_t gid)
1417 {
1418 	struct group *gr;
1419 	int cp;
1420 
1421 #if	(((NGID) & ((NGID) - 1)) != 0)
1422 	cp = gid % (NGID);
1423 #else
1424 	cp = gid & ((NGID) - 1);
1425 #endif
1426 	if (gc[cp].id == gid && gc[cp].name[0])
1427 		return (gc[cp].name);
1428 	gr = getgrgid(gid);
1429 	if (!gr)
1430 		return (0);
1431 	gc[cp].id = gid;
1432 	SCPYN(gc[cp].name, gr->gr_name);
1433 	return (gc[cp].name);
1434 }
1435 
1436 #define	permoffset(who)		((who) * 3)
1437 #define	permission(who, type)	((type) >> permoffset(who))
1438 #define	kbytes(bytes)		(((bytes) + 1023) / 1024)
1439 
1440 static int
1441 list(file, stp)
1442 	char *file;
1443 	struct stat *stp;
1444 {
1445 	char pmode[32], uname[32], gname[32], fsize[32], ftime[32];
1446 	int trivial;
1447 
1448 /*
1449  * Each line below contains the relevant permission (column 1) and character
1450  * shown when  the corresponding execute bit is either clear (column 2)
1451  * or set (column 3)
1452  * These permissions are as shown by ls(1b)
1453  */
1454 	static long special[] = {	S_ISUID, 'S', 's',
1455 					S_ISGID, 'S', 's',
1456 					S_ISVTX, 'T', 't' };
1457 
1458 	static time_t sixmonthsago = -1;
1459 #ifdef	S_IFLNK
1460 	char flink[MAXPATHLEN + 1];
1461 #endif
1462 	int who;
1463 	char *cp;
1464 	char *tailname;
1465 	time_t now;
1466 	long long ksize;
1467 
1468 	if (file == NULL || stp == NULL)
1469 		return (-1);
1470 
1471 	(void) time(&now);
1472 	if (sixmonthsago == -1)
1473 		sixmonthsago = now - 6L*30L*24L*60L*60L;
1474 
1475 	switch (stp->st_mode & S_IFMT) {
1476 #ifdef	S_IFDIR
1477 	case S_IFDIR:	/* directory */
1478 		pmode[0] = 'd';
1479 		break;
1480 #endif
1481 #ifdef	S_IFCHR
1482 	case S_IFCHR:	/* character special */
1483 		pmode[0] = 'c';
1484 		break;
1485 #endif
1486 #ifdef	S_IFBLK
1487 	case S_IFBLK:	/* block special */
1488 		pmode[0] = 'b';
1489 		break;
1490 #endif
1491 #ifdef	S_IFIFO
1492 	case S_IFIFO:	/* fifo special */
1493 		pmode[0] = 'p';
1494 		break;
1495 #endif
1496 #ifdef	S_IFLNK
1497 	case S_IFLNK:	/* symbolic link */
1498 		pmode[0] = 'l';
1499 		break;
1500 #endif
1501 #ifdef	S_IFSOCK
1502 	case S_IFSOCK:	/* socket */
1503 		pmode[0] = 's';
1504 		break;
1505 #endif
1506 #ifdef	S_IFDOOR
1507 	case S_IFDOOR:	/* door */
1508 		pmode[0] = 'D';
1509 		break;
1510 #endif
1511 #ifdef	S_IFREG
1512 	case S_IFREG:	/* regular */
1513 		pmode[0] = '-';
1514 		break;
1515 #endif
1516 	default:
1517 		pmode[0] = '?';
1518 		break;
1519 	}
1520 
1521 	for (who = 0; who < 3; who++) {
1522 		int is_exec =  stp->st_mode & permission(who, S_IEXEC)? 1 : 0;
1523 
1524 		if (stp->st_mode & permission(who, S_IREAD))
1525 			pmode[permoffset(who) + 1] = 'r';
1526 		else
1527 			pmode[permoffset(who) + 1] = '-';
1528 
1529 		if (stp->st_mode & permission(who, S_IWRITE))
1530 			pmode[permoffset(who) + 2] = 'w';
1531 		else
1532 			pmode[permoffset(who) + 2] = '-';
1533 
1534 		if (stp->st_mode & special[who * 3])
1535 			pmode[permoffset(who) + 3] =
1536 				special[who * 3 + 1 + is_exec];
1537 		else if (is_exec)
1538 			pmode[permoffset(who) + 3] = 'x';
1539 		else
1540 			pmode[permoffset(who) + 3] = '-';
1541 	}
1542 
1543 	/*
1544 	 * Need to get the tail of the file name, since we have
1545 	 * already chdir()ed into the directory of the file
1546 	 */
1547 
1548 	tailname = gettail(file);
1549 
1550 	trivial = acl_trivial(tailname);
1551 	if (trivial == -1)
1552 		trivial =  0;
1553 
1554 	if (trivial == 1)
1555 		pmode[permoffset(who) + 1] = '+';
1556 	else
1557 		pmode[permoffset(who) + 1] = ' ';
1558 
1559 	pmode[permoffset(who) + 2] = '\0';
1560 
1561 	/*
1562 	 * Prepare uname and gname.  Always add a space afterwards
1563 	 * to keep columns from running together.
1564 	 */
1565 	cp = getname(stp->st_uid);
1566 	if (cp != NULL)
1567 		(void) sprintf(uname, "%-8s ", cp);
1568 	else
1569 		(void) sprintf(uname, "%-8u ", stp->st_uid);
1570 
1571 	cp = getgroup(stp->st_gid);
1572 	if (cp != NULL)
1573 		(void) sprintf(gname, "%-8s ", cp);
1574 	else
1575 		(void) sprintf(gname, "%-8u ", stp->st_gid);
1576 
1577 	if (pmode[0] == 'b' || pmode[0] == 'c')
1578 		(void) sprintf(fsize, "%3ld,%4ld",
1579 			major(stp->st_rdev), minor(stp->st_rdev));
1580 	else {
1581 		(void) sprintf(fsize, (stp->st_size < 100000000) ?
1582 			"%8lld" : "%lld", stp->st_size);
1583 #ifdef	S_IFLNK
1584 		if (pmode[0] == 'l') {
1585 
1586 
1587 			who = readlink(tailname, flink, sizeof (flink) - 1);
1588 
1589 			if (who >= 0)
1590 				flink[who] = '\0';
1591 			else
1592 				flink[0] = '\0';
1593 		}
1594 #endif
1595 	}
1596 
1597 	cp = ctime(&stp->st_mtime);
1598 	if (stp->st_mtime < sixmonthsago || stp->st_mtime > now)
1599 		(void) sprintf(ftime, "%-7.7s %-4.4s", cp + 4, cp + 20);
1600 	else
1601 		(void) sprintf(ftime, "%-12.12s", cp + 4);
1602 
1603 	(void) printf((stp->st_ino < 100000) ? "%5llu " :
1604 		"%llu ", stp->st_ino);  /* inode #	*/
1605 #ifdef	S_IFSOCK
1606 	ksize = (long long) kbytes(ldbtob(stp->st_blocks)); /* kbytes */
1607 #else
1608 	ksize = (long long) kbytes(stp->st_size); /* kbytes */
1609 #endif
1610 	(void) printf((ksize < 10000) ? "%4lld " : "%lld ", ksize);
1611 	(void) printf("%s %2ld %s%s%s %s %s%s%s\n",
1612 		pmode,					/* protection	*/
1613 		stp->st_nlink,				/* # of links	*/
1614 		uname,					/* owner	*/
1615 		gname,					/* group	*/
1616 		fsize,					/* # of bytes	*/
1617 		ftime,					/* modify time	*/
1618 		file,					/* name		*/
1619 #ifdef	S_IFLNK
1620 		(pmode[0] == 'l') ? " -> " : "",
1621 		(pmode[0] == 'l') ? flink  : ""		/* symlink	*/
1622 #else
1623 		"",
1624 		""
1625 #endif
1626 );
1627 
1628 	return (0);
1629 }
1630 
1631 static char *
1632 new_string(char *s)
1633 {
1634 	char *p = strdup(s);
1635 
1636 	if (p)
1637 		return (p);
1638 	(void) fprintf(stderr, gettext("%s: out of memory\n"), cmdname);
1639 	exit(1);
1640 	/*NOTREACHED*/
1641 }
1642 
1643 /*
1644  * Read remote file system types from REMOTE_FS into the
1645  * remote_fstypes array.
1646  */
1647 static void
1648 init_remote_fs()
1649 {
1650 	FILE    *fp;
1651 	char    line_buf[LINEBUF_SIZE];
1652 
1653 	if ((fp = fopen(REMOTE_FS, "r")) == NULL) {
1654 		(void) fprintf(stderr,
1655 			gettext("%s: Warning: can't open %s, ignored\n"),
1656 				REMOTE_FS, cmdname);
1657 		/* Use default string name for NFS */
1658 		remote_fstypes[fstype_index++] = "nfs";
1659 		return;
1660 	}
1661 
1662 	while (fgets(line_buf, sizeof (line_buf), fp) != NULL) {
1663 		char buf[LINEBUF_SIZE];
1664 
1665 		/* LINTED - unbounded string specifier */
1666 		(void) sscanf(line_buf, "%s", buf);
1667 		remote_fstypes[fstype_index++] = new_string(buf);
1668 
1669 		if (fstype_index == N_FSTYPES)
1670 			break;
1671 	}
1672 	(void) fclose(fp);
1673 }
1674 
1675 #define	NPERM	30			/* Largest machine */
1676 
1677 /*
1678  * The PERM struct is the machine that builds permissions.  The p_special
1679  * field contains what permissions need to be checked at run-time in
1680  * getmode().  This is one of 'X', 'u', 'g', or 'o'.  It contains '\0' to
1681  * indicate normal processing.
1682  */
1683 typedef	struct	PERMST	{
1684 	ushort_t	p_who;		/* Range of permission (e.g. ugo) */
1685 	ushort_t	p_perm;		/* Bits to turn on, off, assign */
1686 	uchar_t		p_op;		/* Operation: + - = */
1687 	uchar_t		p_special;	/* Special handling? */
1688 }	PERMST;
1689 
1690 #ifndef	S_ISVTX
1691 #define	S_ISVTX	0			/* Not .1 */
1692 #endif
1693 
1694 /* Mask values */
1695 #define	P_A	(S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO) /* allbits */
1696 #define	P_U	(S_ISUID|S_ISVTX|S_IRWXU)		/* user */
1697 #define	P_G	(S_ISGID|S_ISVTX|S_IRWXG)		/* group */
1698 #define	P_O	(S_ISVTX|S_IRWXO)			/* other */
1699 
1700 static	int	iswho(int c);
1701 static	int	isop(int c);
1702 static	int	isperm(PERMST *pp, int c);
1703 
1704 static	PERMST	machine[NPERM];		/* Permission construction machine */
1705 static	PERMST	*endp;			/* Last used PERM structure */
1706 
1707 static	uint_t	nowho;			/* No who for this mode (DOS kludge) */
1708 
1709 /*
1710  * Read an ASCII string containing the symbolic/octal mode and
1711  * compile an automaton that recognizes it.  The return value
1712  * is NULL if everything is OK, otherwise it is -1.
1713  */
1714 static int
1715 readmode(ascmode)
1716 const char *ascmode;
1717 {
1718 	const char *amode = ascmode;
1719 	PERMST *pp;
1720 	int seen_X;
1721 
1722 	nowho = 0;
1723 	seen_X = 0;
1724 	pp = &machine[0];
1725 	if (*amode >= '0' && *amode <= '7') {
1726 		int mode;
1727 
1728 		mode = 0;
1729 		while (*amode >= '0' && *amode <= '7')
1730 			mode = (mode<<3) + *amode++ - '0';
1731 		if (*amode != '\0')
1732 			return (-1);
1733 #if	S_ISUID != 04000 || S_ISGID != 02000 || \
1734 	S_IRUSR != 0400 || S_IWUSR != 0200 || S_IXUSR != 0100 || \
1735 	S_IRGRP != 0040 || S_IWGRP != 0020 || S_IXGRP != 0010 || \
1736 	S_IROTH != 0004 || S_IWOTH != 0002 || S_IXOTH != 0001
1737 		/*
1738 		 * There is no requirement of the octal mode bits being
1739 		 * the same as the S_ macros.
1740 		 */
1741 	{
1742 		mode_t mapping[] = {
1743 			S_IXOTH, S_IWOTH, S_IROTH,
1744 			S_IXGRP, S_IWGRP, S_IRGRP,
1745 			S_IXUSR, S_IWUSR, S_IRUSR,
1746 			S_ISGID, S_ISUID,
1747 			0
1748 		};
1749 		int i, newmode = 0;
1750 
1751 		for (i = 0; mapping[i] != 0; i++)
1752 			if (mode & (1<<i))
1753 				newmode |= mapping[i];
1754 		mode = newmode;
1755 	}
1756 #endif
1757 		pp->p_who = P_A;
1758 		pp->p_perm = mode;
1759 		pp->p_op = '=';
1760 	} else	for (;;) {
1761 		int t;
1762 		int who = 0;
1763 
1764 		while ((t = iswho(*amode)) != 0) {
1765 			++amode;
1766 			who |= t;
1767 		}
1768 		if (who == 0) {
1769 			mode_t currmask;
1770 			(void) umask(currmask = umask((mode_t)0));
1771 
1772 			/*
1773 			 * If no who specified, must use contents of
1774 			 * umask to determine which bits to flip.  This
1775 			 * is POSIX/V7/BSD behaviour, but not SVID.
1776 			 */
1777 			who = (~currmask)&P_A;
1778 			++nowho;
1779 		} else
1780 			nowho = 0;
1781 	samewho:
1782 		if (!isop(pp->p_op = *amode++))
1783 			return (-1);
1784 		pp->p_perm = 0;
1785 		pp->p_special = 0;
1786 		while ((t = isperm(pp, *amode)) != 0) {
1787 			if (pp->p_special == 'X') {
1788 				seen_X = 1;
1789 
1790 				if (pp->p_perm != 0) {
1791 					ushort_t op;
1792 
1793 					/*
1794 					 * Remember the 'who' for the previous
1795 					 * transformation.
1796 					 */
1797 					pp->p_who = who;
1798 					pp->p_special = 0;
1799 
1800 					op = pp->p_op;
1801 
1802 					/* Keep 'X' separate */
1803 					++pp;
1804 					pp->p_special = 'X';
1805 					pp->p_op = op;
1806 				}
1807 			} else if (seen_X) {
1808 				ushort_t op;
1809 
1810 				/* Remember the 'who' for the X */
1811 				pp->p_who = who;
1812 
1813 				op = pp->p_op;
1814 
1815 				/* Keep 'X' separate */
1816 				++pp;
1817 				pp->p_perm = 0;
1818 				pp->p_special = 0;
1819 				pp->p_op = op;
1820 			}
1821 			++amode;
1822 			pp->p_perm |= t;
1823 		}
1824 
1825 		/*
1826 		 * These returned 0, but were actually parsed, so
1827 		 * don't look at them again.
1828 		 */
1829 		switch (pp->p_special) {
1830 		case 'u':
1831 		case 'g':
1832 		case 'o':
1833 			++amode;
1834 			break;
1835 		}
1836 		pp->p_who = who;
1837 		switch (*amode) {
1838 		case '\0':
1839 			break;
1840 
1841 		case ',':
1842 			++amode;
1843 			++pp;
1844 			continue;
1845 
1846 		default:
1847 			++pp;
1848 			goto samewho;
1849 		}
1850 		break;
1851 	}
1852 	endp = pp;
1853 	return (NULL);
1854 }
1855 
1856 /*
1857  * Given a character from the mode, return the associated
1858  * value as who (user designation) mask or 0 if this isn't valid.
1859  */
1860 static int
1861 iswho(c)
1862 int c;
1863 {
1864 	switch (c) {
1865 	case 'a':
1866 		return (P_A);
1867 
1868 	case 'u':
1869 		return (P_U);
1870 
1871 	case 'g':
1872 		return (P_G);
1873 
1874 	case 'o':
1875 		return (P_O);
1876 
1877 	default:
1878 		return (0);
1879 	}
1880 	/* NOTREACHED */
1881 }
1882 
1883 /*
1884  * Return non-zero if this is a valid op code
1885  * in a symbolic mode.
1886  */
1887 static int
1888 isop(c)
1889 int c;
1890 {
1891 	switch (c) {
1892 	case '+':
1893 	case '-':
1894 	case '=':
1895 		return (1);
1896 
1897 	default:
1898 		return (0);
1899 	}
1900 	/* NOTREACHED */
1901 }
1902 
1903 /*
1904  * Return the permission bits implied by this character or 0
1905  * if it isn't valid.  Also returns 0 when the pseudo-permissions 'u', 'g', or
1906  * 'o' are used, and sets pp->p_special to the one used.
1907  */
1908 static int
1909 isperm(pp, c)
1910 PERMST *pp;
1911 int c;
1912 {
1913 	switch (c) {
1914 	case 'u':
1915 	case 'g':
1916 	case 'o':
1917 		pp->p_special = c;
1918 		return (0);
1919 
1920 	case 'r':
1921 		return (S_IRUSR|S_IRGRP|S_IROTH);
1922 
1923 	case 'w':
1924 		return (S_IWUSR|S_IWGRP|S_IWOTH);
1925 
1926 	case 'x':
1927 		return (S_IXUSR|S_IXGRP|S_IXOTH);
1928 
1929 #if S_ISVTX != 0
1930 	case 't':
1931 		return (S_ISVTX);
1932 #endif
1933 
1934 	case 'X':
1935 		pp->p_special = 'X';
1936 		return (S_IXUSR|S_IXGRP|S_IXOTH);
1937 
1938 #if S_ISVTX != 0
1939 	case 'a':
1940 		return (S_ISVTX);
1941 #endif
1942 
1943 	case 'h':
1944 		return (S_ISUID);
1945 
1946 	/*
1947 	 * This change makes:
1948 	 *	chmod +s file
1949 	 * set the system bit on dos but means that
1950 	 *	chmod u+s file
1951 	 *	chmod g+s file
1952 	 *	chmod a+s file
1953 	 * are all like UNIX.
1954 	 */
1955 	case 's':
1956 		return (nowho ? S_ISGID : S_ISGID|S_ISUID);
1957 
1958 	default:
1959 		return (0);
1960 	}
1961 	/* NOTREACHED */
1962 }
1963 
1964 /*
1965  * Execute the automaton that is created by readmode()
1966  * to generate the final mode that will be used.  This
1967  * code is passed a starting mode that is usually the original
1968  * mode of the file being changed (or 0).  Note that this mode must contain
1969  * the file-type bits as well, so that S_ISDIR will succeed on directories.
1970  */
1971 static mode_t
1972 getmode(mode_t startmode)
1973 {
1974 	PERMST *pp;
1975 	mode_t temp;
1976 	mode_t perm;
1977 
1978 	for (pp = &machine[0]; pp <= endp; ++pp) {
1979 		perm = (mode_t)0;
1980 		/*
1981 		 * For the special modes 'u', 'g' and 'o', the named portion
1982 		 * of the mode refers to after the previous clause has been
1983 		 * processed, while the 'X' mode refers to the contents of the
1984 		 * mode before any clauses have been processed.
1985 		 *
1986 		 * References: P1003.2/D11.2, Section 4.7.7,
1987 		 *  lines 2568-2570, 2578-2583
1988 		 */
1989 		switch (pp->p_special) {
1990 		case 'u':
1991 			temp = startmode & S_IRWXU;
1992 			if (temp & (S_IRUSR|S_IRGRP|S_IROTH))
1993 				perm |= ((S_IRUSR|S_IRGRP|S_IROTH) &
1994 				    pp->p_who);
1995 			if (temp & (S_IWUSR|S_IWGRP|S_IWOTH))
1996 				perm |= ((S_IWUSR|S_IWGRP|S_IWOTH) & pp->p_who);
1997 			if (temp & (S_IXUSR|S_IXGRP|S_IXOTH))
1998 				perm |= ((S_IXUSR|S_IXGRP|S_IXOTH) & pp->p_who);
1999 			break;
2000 
2001 		case 'g':
2002 			temp = startmode & S_IRWXG;
2003 			if (temp & (S_IRUSR|S_IRGRP|S_IROTH))
2004 				perm |= ((S_IRUSR|S_IRGRP|S_IROTH) & pp->p_who);
2005 			if (temp & (S_IWUSR|S_IWGRP|S_IWOTH))
2006 				perm |= ((S_IWUSR|S_IWGRP|S_IWOTH) & pp->p_who);
2007 			if (temp & (S_IXUSR|S_IXGRP|S_IXOTH))
2008 				perm |= ((S_IXUSR|S_IXGRP|S_IXOTH) & pp->p_who);
2009 			break;
2010 
2011 		case 'o':
2012 			temp = startmode & S_IRWXO;
2013 			if (temp & (S_IRUSR|S_IRGRP|S_IROTH))
2014 				perm |= ((S_IRUSR|S_IRGRP|S_IROTH) & pp->p_who);
2015 			if (temp & (S_IWUSR|S_IWGRP|S_IWOTH))
2016 				perm |= ((S_IWUSR|S_IWGRP|S_IWOTH) & pp->p_who);
2017 			if (temp & (S_IXUSR|S_IXGRP|S_IXOTH))
2018 				perm |= ((S_IXUSR|S_IXGRP|S_IXOTH) & pp->p_who);
2019 			break;
2020 
2021 		case 'X':
2022 			perm = pp->p_perm;
2023 			break;
2024 
2025 		default:
2026 			perm = pp->p_perm;
2027 			break;
2028 		}
2029 		switch (pp->p_op) {
2030 		case '-':
2031 			startmode &= ~(perm & pp->p_who);
2032 			break;
2033 
2034 		case '=':
2035 			startmode &= ~pp->p_who;
2036 			/* FALLTHROUGH */
2037 		case '+':
2038 			startmode |= (perm & pp->p_who);
2039 			break;
2040 		}
2041 	}
2042 	return (startmode);
2043 }
2044 
2045 /*
2046  * Returns the last component of a path name, unless it is
2047  * an absolute path, in which case it returns the whole path
2048  */
2049 static char
2050 *gettail(char *fname)
2051 {
2052 	char	*base = fname;
2053 
2054 	if (*fname != '/') {
2055 		if ((base = strrchr(fname, '/')) != NULL)
2056 			base++;
2057 		else
2058 			base = fname;
2059 	}
2060 	return (base);
2061 }
2062