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