xref: /titanic_41/usr/src/cmd/find/find.c (revision 60405de4d8688d96dd05157c28db3ade5c9bc234)
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 2006 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;
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 	}
751 
752 	while (np) {
753 		switch (np->action) {
754 		case NOT:
755 			not = !not;
756 			np = np->next;
757 			continue;
758 
759 		case AND:
760 			np = np->next;
761 			continue;
762 
763 		case OR:
764 			if (np->first.np == np) {
765 				/*
766 				 * handle naked OR (no term on left hand side)
767 				 */
768 				(void) fprintf(stderr,
769 				    gettext("%s: invalid -o construction\n"),
770 				    cmdname);
771 				exit(2);
772 			}
773 			/* FALLTHROUGH */
774 		case LPAREN: {
775 			struct Node *save = topnode;
776 			topnode = np->first.np;
777 			(void) execute(name, statb, type, state);
778 			val = lastval;
779 			topnode = save;
780 			if (np->action == OR) {
781 				if (val)
782 					return (0);
783 				val = 1;
784 			}
785 			break;
786 		}
787 
788 		case LOCAL: {
789 			int	nremfs;
790 			val = 1;
791 			/*
792 			 * If file system type matches the remote
793 			 * file system type, then it is not local.
794 			 */
795 			for (nremfs = 0; nremfs < fstype_index; nremfs++) {
796 				if (strcmp(remote_fstypes[nremfs],
797 						statb->st_fstype) == 0) {
798 					val = 0;
799 					break;
800 				}
801 			}
802 			break;
803 		}
804 
805 		case TYPE:
806 			l = (long)statb->st_mode&S_IFMT;
807 			goto num;
808 
809 		case PERM:
810 			l = (long)statb->st_mode&07777;
811 			if (np->second.i == '-')
812 				val = ((l&np->first.l) == np->first.l);
813 			else
814 				val = (l == np->first.l);
815 			break;
816 
817 		case INUM:
818 			ll = (long long)statb->st_ino;
819 			goto llnum;
820 		case NEWER:
821 			l = statb->st_mtime;
822 			goto num;
823 		case ATIME:
824 			t = statb->st_atime;
825 			goto days;
826 		case CTIME:
827 			t = statb->st_ctime;
828 			goto days;
829 		case MTIME:
830 			t = statb->st_mtime;
831 		days:
832 			l = (now-t)/A_DAY;
833 			goto num;
834 		case MMIN:
835 			t = statb->st_mtime;
836 			goto mins;
837 		case AMIN:
838 			t = statb->st_atime;
839 			goto mins;
840 		case CMIN:
841 			t = statb->st_ctime;
842 			goto mins;
843 		mins:
844 			l = (now-t)/A_MIN;
845 			goto num;
846 		case CSIZE:
847 			ll = (long long)statb->st_size;
848 			goto llnum;
849 		case SIZE:
850 			ll = (long long)round(statb->st_size, BLKSIZ)/BLKSIZ;
851 			goto llnum;
852 		case F_USER:
853 			l = (long)statb->st_uid;
854 			goto num;
855 		case F_GROUP:
856 			l = (long)statb->st_gid;
857 			goto num;
858 		case LINKS:
859 			l = (long)statb->st_nlink;
860 			goto num;
861 		llnum:
862 			if (np->second.i == '+')
863 				val = (ll > np->first.ll);
864 			else if (np->second.i == '-')
865 				val = (ll < np->first.ll);
866 			else
867 				val = (ll == np->first.ll);
868 			break;
869 		num:
870 			if (np->second.i == '+')
871 				val = (l > np->first.l);
872 			else if (np->second.i == '-')
873 				val = (l < np->first.l);
874 			else
875 				val = (l == np->first.l);
876 			break;
877 		case OK:
878 			val = ok(name, np->first.ap);
879 			break;
880 		case EXEC:
881 			val = doexec(name, np->first.ap, NULL);
882 			break;
883 
884 		case VARARGS: {
885 			struct Arglist *ap = np->first.vp;
886 			char *cp;
887 			cp = ap->nextstr - (strlen(name)+1);
888 			if (cp >= (char *)(ap->nextvar+3)) {
889 				/* there is room just copy the name */
890 				val = 1;
891 				(void) strcpy(cp, name);
892 				*ap->nextvar++ = cp;
893 				ap->nextstr = cp;
894 			} else {
895 				/* no more room, exec command */
896 				*ap->nextvar++ = name;
897 				*ap->nextvar = 0;
898 				val = 1;
899 				(void) doexec((char *)0, ap->arglist,
900 				    &exec_exitcode);
901 				ap->nextstr = ap->end;
902 				ap->nextvar = ap->firstvar;
903 			}
904 			break;
905 		}
906 
907 		case DEPTH:
908 		case MOUNT:
909 		case FOLLOW:
910 			val = 1;
911 			break;
912 
913 		case NAME: {
914 			/*
915 			 * XPG4 find should not treat a leading '.' in a
916 			 * filename specially for pattern matching.
917 			 * /usr/bin/find  will not pattern match a leading
918 			 * '.' in a filename, unless '.' is explicitly
919 			 * specified.
920 			 */
921 #ifdef XPG4
922 			val = !fnmatch(np->first.cp,
923 			    name+state->base, 0);
924 #else
925 			val = !fnmatch(np->first.cp,
926 			    name+state->base, FNM_PERIOD);
927 #endif
928 			break;
929 		}
930 
931 		case PRUNE:
932 			if (type == FTW_D)
933 				state->quit = FTW_PRUNE;
934 			val = 1;
935 			break;
936 		case NOUSER:
937 			val = ((getpwuid(statb->st_uid)) == 0);
938 			break;
939 		case NOGRP:
940 			val = ((getgrgid(statb->st_gid)) == 0);
941 			break;
942 		case FSTYPE:
943 			val = (strcmp(np->first.cp, statb->st_fstype) == 0);
944 			break;
945 		case CPIO:
946 			output = (FILE *)np->first.l;
947 			(void) fprintf(output, "%s\n", name);
948 			val = 1;
949 			break;
950 		case PRINT:
951 			(void) fprintf(stdout, "%s\n", name);
952 			val = 1;
953 			break;
954 		case LS:
955 			(void) list(name, statb);
956 			val = 1;
957 			break;
958 		case XATTR:
959 			filename = gettail(name);
960 			val = (pathconf(filename, _PC_XATTR_EXISTS) == 1);
961 			break;
962 		case ACL:
963 			/*
964 			 * Need to get the tail of the file name, since we have
965 			 * already chdir()ed into the directory (performed in
966 			 * nftw()) of the file
967 			 */
968 			filename = gettail(name);
969 			val = acl_trivial(name);
970 			break;
971 		}
972 		/*
973 		 * evaluate 'val' and 'not' (exclusive-or)
974 		 * if no inversion (not == 1), return only when val == 0
975 		 * (primary not true). Otherwise, invert the primary
976 		 * and return when the primary is true.
977 		 * 'Lastval' saves the last result (fail or pass) when
978 		 * returning back to the calling routine.
979 		 */
980 		if (val^not) {
981 			lastval = 0;
982 			return (0);
983 		}
984 		lastval = 1;
985 		not = 1;
986 		np = np->next;
987 	}
988 	return (0);
989 }
990 
991 /*
992  * code for the -ok option
993  */
994 
995 static int
996 ok(name, argv)
997 char *name;
998 char *argv[];
999 {
1000 	int c, yes = 0;
1001 
1002 	(void) fflush(stdout); 	/* to flush possible `-print' */
1003 
1004 	if ((*argv != dummyarg) && (strcmp(*argv, name)))
1005 		(void) fprintf(stderr, "< %s ... %s >?   ", *argv, name);
1006 	else
1007 		(void) fprintf(stderr, "< {} ... %s >?   ", name);
1008 
1009 	(void) fflush(stderr);
1010 	if ((c = tolower(getchar())) == *nl_langinfo(YESSTR))
1011 		yes = 1;
1012 	while (c != '\n')
1013 		if (c == EOF)
1014 			exit(2);
1015 		else
1016 			c = getchar();
1017 	return (yes? doexec(name, argv, NULL): 0);
1018 }
1019 
1020 /*
1021  * execute argv with {} replaced by name
1022  *
1023  * Per XPG6, find must exit non-zero if an invocation through
1024  * -exec, punctuated by a plus sign, exits non-zero, so set
1025  * exitcode if we see a non-zero exit.
1026  * exitcode should be NULL when -exec or -ok is not punctuated
1027  * by a plus sign.
1028  */
1029 
1030 static int
1031 doexec(char *name, char *argv[], int *exitcode)
1032 {
1033 	char *cp;
1034 	char **av = argv;
1035 	char *newargs[1 + SHELL_MAXARGS + 1];
1036 	int dummyseen = 0;
1037 	int i, j, status, rc, r = 0;
1038 	int exit_status = 0;
1039 	pid_t pid, pid1;
1040 
1041 	(void) fflush(stdout);	  /* to flush possible `-print' */
1042 	if (name) {
1043 		while (cp = *av++) {
1044 			if (cp == dummyarg) {
1045 				dummyseen = 1;
1046 				av[-1] = name;
1047 			}
1048 
1049 		}
1050 	}
1051 	if (argv[0] == NULL)    /* null command line */
1052 		return (r);
1053 
1054 	if ((pid = fork()) == -1) {
1055 		/* fork failed */
1056 		if (exitcode != NULL)
1057 			*exitcode = 1;
1058 		return (0);
1059 	}
1060 	if (pid != 0) {
1061 		/* parent */
1062 		do {
1063 			/* wait for child to exit */
1064 			if ((rc = wait(&r)) == -1 && errno != EINTR) {
1065 				(void) fprintf(stderr,
1066 				    gettext("wait failed %s"), strerror(errno));
1067 
1068 				if (exitcode != NULL)
1069 					*exitcode = 1;
1070 				return (0);
1071 			}
1072 		} while (rc != pid);
1073 	} else {
1074 		/* child */
1075 		(void) execvp(argv[0], argv);
1076 		if (errno != E2BIG)
1077 			exit(1);
1078 
1079 		/*
1080 		 * We are in a situation where argv[0] points to a
1081 		 * script without the interpreter line, e.g. #!/bin/sh.
1082 		 * execvp() will execute either /usr/bin/sh or
1083 		 * /usr/xpg4/bin/sh against the script, and you will be
1084 		 * limited to SHELL_MAXARGS arguments. If you try to
1085 		 * pass more than SHELL_MAXARGS arguments, execvp()
1086 		 * fails with E2BIG.
1087 		 * See usr/src/lib/libc/port/gen/execvp.c.
1088 		 *
1089 		 * In this situation, process the argument list by
1090 		 * packets of SHELL_MAXARGS arguments with respect of
1091 		 * the following rules:
1092 		 * 1. the invocations have to complete before find exits
1093 		 * 2. only one invocation can be running at a time
1094 		 */
1095 
1096 		i = 1;
1097 		newargs[0] = argv[0];
1098 
1099 		while (argv[i]) {
1100 			j = 1;
1101 			while (j <= SHELL_MAXARGS && argv[i]) {
1102 				newargs[j++] = argv[i++];
1103 			}
1104 			newargs[j] = NULL;
1105 
1106 			if ((pid1 = fork()) == -1) {
1107 				/* fork failed */
1108 				exit(1);
1109 			}
1110 			if (pid1 == 0) {
1111 				/* child */
1112 				(void) execvp(newargs[0], newargs);
1113 				exit(1);
1114 			}
1115 
1116 			status = 0;
1117 
1118 			do {
1119 				/* wait for the child to exit */
1120 				if ((rc = wait(&status)) == -1 &&
1121 				    errno != EINTR) {
1122 					(void) fprintf(stderr,
1123 					    gettext("wait failed %s"),
1124 					    strerror(errno));
1125 					exit(1);
1126 				}
1127 			} while (rc != pid1);
1128 
1129 			if (status)
1130 				exit_status = 1;
1131 		}
1132 		/* all the invocations have completed */
1133 		exit(exit_status);
1134 	}
1135 
1136 	if (name && dummyseen) {
1137 		for (av = argv; cp = *av++; ) {
1138 			if (cp == name)
1139 				av[-1] = dummyarg;
1140 		}
1141 	}
1142 
1143 	if (r && exitcode != NULL)
1144 		*exitcode = 3; /* use to indicate error in cmd invocation */
1145 
1146 	return (!r);
1147 }
1148 
1149 
1150 /*
1151  *  Table lookup routine
1152  */
1153 static struct Args *
1154 lookup(word)
1155 char *word;
1156 {
1157 	struct Args *argp = commands;
1158 	int second;
1159 	if (word == 0 || *word == 0)
1160 		return (0);
1161 	second = word[1];
1162 	while (*argp->name) {
1163 		if (second == argp->name[1] && strcmp(word, argp->name) == 0)
1164 			return (argp);
1165 		argp++;
1166 	}
1167 	return (0);
1168 }
1169 
1170 
1171 /*
1172  * Get space for variable length argument list
1173  */
1174 
1175 static struct Arglist *
1176 varargs(com)
1177 char **com;
1178 {
1179 	struct Arglist *ap;
1180 	int n;
1181 	char **ep;
1182 	if (varsize == 0) {
1183 		n = 2*sizeof (char **);
1184 		for (ep = environ; *ep; ep++)
1185 			n += (strlen(*ep)+sizeof (ep) + 1);
1186 		varsize = sizeof (struct Arglist)+ARG_MAX-PATH_MAX-n-1;
1187 	}
1188 	ap = (struct Arglist *)malloc(varsize+1);
1189 	ap->end = (char *)ap + varsize;
1190 	ap->nextstr = ap->end;
1191 	ap->nextvar = ap->arglist;
1192 	while (*ap->nextvar++ = *com++);
1193 	ap->nextvar--;
1194 	ap->firstvar = ap->nextvar;
1195 	ap->next = lastlist;
1196 	lastlist = ap;
1197 	return (ap);
1198 }
1199 
1200 /*
1201  * filter command support
1202  * fork and exec cmd(argv) according to mode:
1203  *
1204  *	"r"	with fp as stdin of cmd (default stdin), cmd stdout returned
1205  *	"w"	with fp as stdout of cmd (default stdout), cmd stdin returned
1206  */
1207 
1208 #define	CMDERR	((1<<8)-1)	/* command error exit code		*/
1209 #define	MAXCMDS	8		/* max # simultaneous cmdopen()'s	*/
1210 
1211 static struct			/* info for each cmdopen()		*/
1212 {
1213 	FILE	*fp;		/* returned by cmdopen()		*/
1214 	pid_t	pid;		/* pid used by cmdopen()		*/
1215 } cmdproc[MAXCMDS];
1216 
1217 static FILE *
1218 cmdopen(cmd, argv, mode, fp)
1219 char	*cmd;
1220 char	**argv;
1221 char	*mode;
1222 FILE	*fp;
1223 {
1224 	int	proc;
1225 	int	cmdfd;
1226 	int	usrfd;
1227 	int		pio[2];
1228 
1229 	switch (*mode) {
1230 	case 'r':
1231 		cmdfd = 1;
1232 		usrfd = 0;
1233 		break;
1234 	case 'w':
1235 		cmdfd = 0;
1236 		usrfd = 1;
1237 		break;
1238 	default:
1239 		return (0);
1240 	}
1241 
1242 	for (proc = 0; proc < MAXCMDS; proc++)
1243 		if (!cmdproc[proc].fp)
1244 			break;
1245 	if (proc >= MAXCMDS)
1246 		return (0);
1247 
1248 	if (pipe(pio))
1249 		return (0);
1250 
1251 	switch (cmdproc[proc].pid = fork()) {
1252 	case -1:
1253 		return (0);
1254 	case 0:
1255 		if (fp && fileno(fp) != usrfd) {
1256 			(void) close(usrfd);
1257 			if (dup2(fileno(fp), usrfd) != usrfd)
1258 				_exit(CMDERR);
1259 			(void) close(fileno(fp));
1260 		}
1261 		(void) close(cmdfd);
1262 		if (dup2(pio[cmdfd], cmdfd) != cmdfd)
1263 			_exit(CMDERR);
1264 		(void) close(pio[cmdfd]);
1265 		(void) close(pio[usrfd]);
1266 		(void) execvp(cmd, argv);
1267 		if (errno == ENOEXEC) {
1268 			char	**p;
1269 			char		**v;
1270 
1271 			/*
1272 			 * assume cmd is a shell script
1273 			 */
1274 
1275 			p = argv;
1276 			while (*p++);
1277 			if (v = (char **)malloc((p - argv + 1) *
1278 					sizeof (char **))) {
1279 				p = v;
1280 				*p++ = cmd;
1281 				if (*argv) argv++;
1282 				while (*p++ = *argv++);
1283 				(void) execv(getshell(), v);
1284 			}
1285 		}
1286 		_exit(CMDERR);
1287 		/*NOTREACHED*/
1288 	default:
1289 		(void) close(pio[cmdfd]);
1290 		return (cmdproc[proc].fp = fdopen(pio[usrfd], mode));
1291 	}
1292 }
1293 
1294 /*
1295  * close a stream opened by cmdopen()
1296  * -1 returned if cmdopen() had a problem
1297  * otherwise exit() status of command is returned
1298  */
1299 
1300 static int
1301 cmdclose(fp)
1302 FILE	*fp;
1303 {
1304 	int	i;
1305 	pid_t	p, pid;
1306 	int		status;
1307 
1308 	for (i = 0; i < MAXCMDS; i++)
1309 		if (fp == cmdproc[i].fp) break;
1310 	if (i >= MAXCMDS)
1311 		return (-1);
1312 	(void) fclose(fp);
1313 	cmdproc[i].fp = 0;
1314 	pid = cmdproc[i].pid;
1315 	while ((p = wait(&status)) != pid && p != (pid_t)-1);
1316 	if (p == pid) {
1317 		status = (status >> 8) & CMDERR;
1318 		if (status == CMDERR)
1319 			status = -1;
1320 	}
1321 	else
1322 		status = -1;
1323 	return (status);
1324 }
1325 
1326 /*
1327  * return pointer to the full path name of the shell
1328  *
1329  * SHELL is read from the environment and must start with /
1330  *
1331  * if set-uid or set-gid then the executable and its containing
1332  * directory must not be writable by the real user
1333  *
1334  * /usr/bin/sh is returned by default
1335  */
1336 
1337 char *
1338 getshell()
1339 {
1340 	char	*s;
1341 	char	*sh;
1342 	uid_t	u;
1343 	int	j;
1344 
1345 	if (((sh = getenv("SHELL")) != 0) && *sh == '/') {
1346 		if (u = getuid()) {
1347 			if ((u != geteuid() || getgid() != getegid()) &&
1348 					!access(sh, 2))
1349 				goto defshell;
1350 			s = strrchr(sh, '/');
1351 			*s = 0;
1352 			j = access(sh, 2);
1353 			*s = '/';
1354 			if (!j) goto defshell;
1355 		}
1356 		return (sh);
1357 	}
1358 defshell:
1359 	return ("/usr/bin/sh");
1360 }
1361 
1362 /*
1363  * the following functions implement the added "-ls" option
1364  */
1365 
1366 #include <utmpx.h>
1367 #include <sys/mkdev.h>
1368 
1369 struct		utmpx utmpx;
1370 #define	NMAX	(sizeof (utmpx.ut_name))
1371 #define	SCPYN(a, b)	(void) strncpy(a, b, NMAX)
1372 
1373 #define	NUID	64
1374 #define	NGID	64
1375 
1376 static struct ncache {
1377 	int	id;
1378 	char	name[NMAX+1];
1379 } nc[NUID], gc[NGID];
1380 
1381 /*
1382  * This function assumes that the password file is hashed
1383  * (or some such) to allow fast access based on a name key.
1384  */
1385 static char *
1386 getname(uid_t uid)
1387 {
1388 	struct passwd *pw;
1389 	int cp;
1390 
1391 #if	(((NUID) & ((NUID) - 1)) != 0)
1392 	cp = uid % (NUID);
1393 #else
1394 	cp = uid & ((NUID) - 1);
1395 #endif
1396 	if (uid >= 0 && nc[cp].id == uid && nc[cp].name[0])
1397 		return (nc[cp].name);
1398 	pw = getpwuid(uid);
1399 	if (!pw)
1400 		return (0);
1401 	nc[cp].id = uid;
1402 	SCPYN(nc[cp].name, pw->pw_name);
1403 	return (nc[cp].name);
1404 }
1405 
1406 /*
1407  * This function assumes that the group file is hashed
1408  * (or some such) to allow fast access based on a name key.
1409  */
1410 static char *
1411 getgroup(gid_t gid)
1412 {
1413 	struct group *gr;
1414 	int cp;
1415 
1416 #if	(((NGID) & ((NGID) - 1)) != 0)
1417 	cp = gid % (NGID);
1418 #else
1419 	cp = gid & ((NGID) - 1);
1420 #endif
1421 	if (gid >= 0 && gc[cp].id == gid && gc[cp].name[0])
1422 		return (gc[cp].name);
1423 	gr = getgrgid(gid);
1424 	if (!gr)
1425 		return (0);
1426 	gc[cp].id = gid;
1427 	SCPYN(gc[cp].name, gr->gr_name);
1428 	return (gc[cp].name);
1429 }
1430 
1431 #define	permoffset(who)		((who) * 3)
1432 #define	permission(who, type)	((type) >> permoffset(who))
1433 #define	kbytes(bytes)		(((bytes) + 1023) / 1024)
1434 
1435 static int
1436 list(file, stp)
1437 	char *file;
1438 	struct stat *stp;
1439 {
1440 	char pmode[32], uname[32], gname[32], fsize[32], ftime[32];
1441 	int trivial;
1442 
1443 /*
1444  * Each line below contains the relevant permission (column 1) and character
1445  * shown when  the corresponding execute bit is either clear (column 2)
1446  * or set (column 3)
1447  * These permissions are as shown by ls(1b)
1448  */
1449 	static long special[] = {	S_ISUID, 'S', 's',
1450 					S_ISGID, 'S', 's',
1451 					S_ISVTX, 'T', 't' };
1452 
1453 	static time_t sixmonthsago = -1;
1454 #ifdef	S_IFLNK
1455 	char flink[MAXPATHLEN + 1];
1456 #endif
1457 	int who;
1458 	char *cp;
1459 	char *tailname;
1460 	time_t now;
1461 	long long ksize;
1462 
1463 	if (file == NULL || stp == NULL)
1464 		return (-1);
1465 
1466 	(void) time(&now);
1467 	if (sixmonthsago == -1)
1468 		sixmonthsago = now - 6L*30L*24L*60L*60L;
1469 
1470 	switch (stp->st_mode & S_IFMT) {
1471 #ifdef	S_IFDIR
1472 	case S_IFDIR:	/* directory */
1473 		pmode[0] = 'd';
1474 		break;
1475 #endif
1476 #ifdef	S_IFCHR
1477 	case S_IFCHR:	/* character special */
1478 		pmode[0] = 'c';
1479 		break;
1480 #endif
1481 #ifdef	S_IFBLK
1482 	case S_IFBLK:	/* block special */
1483 		pmode[0] = 'b';
1484 		break;
1485 #endif
1486 #ifdef	S_IFIFO
1487 	case S_IFIFO:	/* fifo special */
1488 		pmode[0] = 'p';
1489 		break;
1490 #endif
1491 #ifdef	S_IFLNK
1492 	case S_IFLNK:	/* symbolic link */
1493 		pmode[0] = 'l';
1494 		break;
1495 #endif
1496 #ifdef	S_IFSOCK
1497 	case S_IFSOCK:	/* socket */
1498 		pmode[0] = 's';
1499 		break;
1500 #endif
1501 #ifdef	S_IFDOOR
1502 	case S_IFDOOR:	/* door */
1503 		pmode[0] = 'D';
1504 		break;
1505 #endif
1506 #ifdef	S_IFREG
1507 	case S_IFREG:	/* regular */
1508 		pmode[0] = '-';
1509 		break;
1510 #endif
1511 	default:
1512 		pmode[0] = '?';
1513 		break;
1514 	}
1515 
1516 	for (who = 0; who < 3; who++) {
1517 		int is_exec =  stp->st_mode & permission(who, S_IEXEC)? 1 : 0;
1518 
1519 		if (stp->st_mode & permission(who, S_IREAD))
1520 			pmode[permoffset(who) + 1] = 'r';
1521 		else
1522 			pmode[permoffset(who) + 1] = '-';
1523 
1524 		if (stp->st_mode & permission(who, S_IWRITE))
1525 			pmode[permoffset(who) + 2] = 'w';
1526 		else
1527 			pmode[permoffset(who) + 2] = '-';
1528 
1529 		if (stp->st_mode & special[who * 3])
1530 			pmode[permoffset(who) + 3] =
1531 				special[who * 3 + 1 + is_exec];
1532 		else if (is_exec)
1533 			pmode[permoffset(who) + 3] = 'x';
1534 		else
1535 			pmode[permoffset(who) + 3] = '-';
1536 	}
1537 
1538 	/*
1539 	 * Need to get the tail of the file name, since we have
1540 	 * already chdir()ed into the directory of the file
1541 	 */
1542 
1543 	tailname = gettail(file);
1544 
1545 	trivial = acl_trivial(tailname);
1546 	if (trivial == -1)
1547 		trivial =  0;
1548 
1549 	if (trivial == 1)
1550 		pmode[permoffset(who) + 1] = '+';
1551 	else
1552 		pmode[permoffset(who) + 1] = ' ';
1553 
1554 	pmode[permoffset(who) + 2] = '\0';
1555 
1556 	/*
1557 	 * Prepare uname and gname.  Always add a space afterwards
1558 	 * to keep columns from running together.
1559 	 */
1560 	cp = getname(stp->st_uid);
1561 	if (cp != NULL)
1562 		(void) sprintf(uname, "%-8s ", cp);
1563 	else
1564 		(void) sprintf(uname, "%-8ld ", stp->st_uid);
1565 
1566 	cp = getgroup(stp->st_gid);
1567 	if (cp != NULL)
1568 		(void) sprintf(gname, "%-8s ", cp);
1569 	else
1570 		(void) sprintf(gname, "%-8ld ", stp->st_gid);
1571 
1572 	if (pmode[0] == 'b' || pmode[0] == 'c')
1573 		(void) sprintf(fsize, "%3ld,%4ld",
1574 			major(stp->st_rdev), minor(stp->st_rdev));
1575 	else {
1576 		(void) sprintf(fsize, (stp->st_size < 100000000) ?
1577 			"%8lld" : "%lld", stp->st_size);
1578 #ifdef	S_IFLNK
1579 		if (pmode[0] == 'l') {
1580 
1581 
1582 			who = readlink(tailname, flink, sizeof (flink) - 1);
1583 
1584 			if (who >= 0)
1585 				flink[who] = '\0';
1586 			else
1587 				flink[0] = '\0';
1588 		}
1589 #endif
1590 	}
1591 
1592 	cp = ctime(&stp->st_mtime);
1593 	if (stp->st_mtime < sixmonthsago || stp->st_mtime > now)
1594 		(void) sprintf(ftime, "%-7.7s %-4.4s", cp + 4, cp + 20);
1595 	else
1596 		(void) sprintf(ftime, "%-12.12s", cp + 4);
1597 
1598 	(void) printf((stp->st_ino < 100000) ? "%5llu " :
1599 		"%llu ", stp->st_ino);  /* inode #	*/
1600 #ifdef	S_IFSOCK
1601 	ksize = (long long) kbytes(ldbtob(stp->st_blocks)); /* kbytes */
1602 #else
1603 	ksize = (long long) kbytes(stp->st_size); /* kbytes */
1604 #endif
1605 	(void) printf((ksize < 10000) ? "%4lld " : "%lld ", ksize);
1606 	(void) printf("%s %2ld %s%s%s %s %s%s%s\n",
1607 		pmode,					/* protection	*/
1608 		stp->st_nlink,				/* # of links	*/
1609 		uname,					/* owner	*/
1610 		gname,					/* group	*/
1611 		fsize,					/* # of bytes	*/
1612 		ftime,					/* modify time	*/
1613 		file,					/* name		*/
1614 #ifdef	S_IFLNK
1615 		(pmode[0] == 'l') ? " -> " : "",
1616 		(pmode[0] == 'l') ? flink  : ""		/* symlink	*/
1617 #else
1618 		"",
1619 		""
1620 #endif
1621 );
1622 
1623 	return (0);
1624 }
1625 
1626 static char *
1627 new_string(char *s)
1628 {
1629 	char *p = strdup(s);
1630 
1631 	if (p)
1632 		return (p);
1633 	(void) fprintf(stderr, gettext("%s: out of memory\n"), cmdname);
1634 	exit(1);
1635 	/*NOTREACHED*/
1636 }
1637 
1638 /*
1639  * Read remote file system types from REMOTE_FS into the
1640  * remote_fstypes array.
1641  */
1642 static void
1643 init_remote_fs()
1644 {
1645 	FILE    *fp;
1646 	char    line_buf[LINEBUF_SIZE];
1647 
1648 	if ((fp = fopen(REMOTE_FS, "r")) == NULL) {
1649 		(void) fprintf(stderr,
1650 			gettext("%s: Warning: can't open %s, ignored\n"),
1651 				REMOTE_FS, cmdname);
1652 		/* Use default string name for NFS */
1653 		remote_fstypes[fstype_index++] = "nfs";
1654 		return;
1655 	}
1656 
1657 	while (fgets(line_buf, sizeof (line_buf), fp) != NULL) {
1658 		char buf[LINEBUF_SIZE];
1659 
1660 		/* LINTED - unbounded string specifier */
1661 		(void) sscanf(line_buf, "%s", buf);
1662 		remote_fstypes[fstype_index++] = new_string(buf);
1663 
1664 		if (fstype_index == N_FSTYPES)
1665 			break;
1666 	}
1667 	(void) fclose(fp);
1668 }
1669 
1670 #define	NPERM	30			/* Largest machine */
1671 
1672 /*
1673  * The PERM struct is the machine that builds permissions.  The p_special
1674  * field contains what permissions need to be checked at run-time in
1675  * getmode().  This is one of 'X', 'u', 'g', or 'o'.  It contains '\0' to
1676  * indicate normal processing.
1677  */
1678 typedef	struct	PERMST	{
1679 	ushort_t	p_who;		/* Range of permission (e.g. ugo) */
1680 	ushort_t	p_perm;		/* Bits to turn on, off, assign */
1681 	uchar_t		p_op;		/* Operation: + - = */
1682 	uchar_t		p_special;	/* Special handling? */
1683 }	PERMST;
1684 
1685 #ifndef	S_ISVTX
1686 #define	S_ISVTX	0			/* Not .1 */
1687 #endif
1688 
1689 /* Mask values */
1690 #define	P_A	(S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO) /* allbits */
1691 #define	P_U	(S_ISUID|S_ISVTX|S_IRWXU)		/* user */
1692 #define	P_G	(S_ISGID|S_ISVTX|S_IRWXG)		/* group */
1693 #define	P_O	(S_ISVTX|S_IRWXO)			/* other */
1694 
1695 static	int	iswho(int c);
1696 static	int	isop(int c);
1697 static	int	isperm(PERMST *pp, int c);
1698 
1699 static	PERMST	machine[NPERM];		/* Permission construction machine */
1700 static	PERMST	*endp;			/* Last used PERM structure */
1701 
1702 static	uint_t	nowho;			/* No who for this mode (DOS kludge) */
1703 
1704 /*
1705  * Read an ASCII string containing the symbolic/octal mode and
1706  * compile an automaton that recognizes it.  The return value
1707  * is NULL if everything is OK, otherwise it is -1.
1708  */
1709 static int
1710 readmode(ascmode)
1711 const char *ascmode;
1712 {
1713 	const char *amode = ascmode;
1714 	PERMST *pp;
1715 	int seen_X;
1716 
1717 	nowho = 0;
1718 	seen_X = 0;
1719 	pp = &machine[0];
1720 	if (*amode >= '0' && *amode <= '7') {
1721 		int mode;
1722 
1723 		mode = 0;
1724 		while (*amode >= '0' && *amode <= '7')
1725 			mode = (mode<<3) + *amode++ - '0';
1726 		if (*amode != '\0')
1727 			return (-1);
1728 #if	S_ISUID != 04000 || S_ISGID != 02000 || \
1729 	S_IRUSR != 0400 || S_IWUSR != 0200 || S_IXUSR != 0100 || \
1730 	S_IRGRP != 0040 || S_IWGRP != 0020 || S_IXGRP != 0010 || \
1731 	S_IROTH != 0004 || S_IWOTH != 0002 || S_IXOTH != 0001
1732 		/*
1733 		 * There is no requirement of the octal mode bits being
1734 		 * the same as the S_ macros.
1735 		 */
1736 	{
1737 		mode_t mapping[] = {
1738 			S_IXOTH, S_IWOTH, S_IROTH,
1739 			S_IXGRP, S_IWGRP, S_IRGRP,
1740 			S_IXUSR, S_IWUSR, S_IRUSR,
1741 			S_ISGID, S_ISUID,
1742 			0
1743 		};
1744 		int i, newmode = 0;
1745 
1746 		for (i = 0; mapping[i] != 0; i++)
1747 			if (mode & (1<<i))
1748 				newmode |= mapping[i];
1749 		mode = newmode;
1750 	}
1751 #endif
1752 		pp->p_who = P_A;
1753 		pp->p_perm = mode;
1754 		pp->p_op = '=';
1755 	} else	for (;;) {
1756 		int t;
1757 		int who = 0;
1758 
1759 		while ((t = iswho(*amode)) != 0) {
1760 			++amode;
1761 			who |= t;
1762 		}
1763 		if (who == 0) {
1764 			mode_t currmask;
1765 			(void) umask(currmask = umask((mode_t)0));
1766 
1767 			/*
1768 			 * If no who specified, must use contents of
1769 			 * umask to determine which bits to flip.  This
1770 			 * is POSIX/V7/BSD behaviour, but not SVID.
1771 			 */
1772 			who = (~currmask)&P_A;
1773 			++nowho;
1774 		} else
1775 			nowho = 0;
1776 	samewho:
1777 		if (!isop(pp->p_op = *amode++))
1778 			return (-1);
1779 		pp->p_perm = 0;
1780 		pp->p_special = 0;
1781 		while ((t = isperm(pp, *amode)) != 0) {
1782 			if (pp->p_special == 'X') {
1783 				seen_X = 1;
1784 
1785 				if (pp->p_perm != 0) {
1786 					ushort_t op;
1787 
1788 					/*
1789 					 * Remember the 'who' for the previous
1790 					 * transformation.
1791 					 */
1792 					pp->p_who = who;
1793 					pp->p_special = 0;
1794 
1795 					op = pp->p_op;
1796 
1797 					/* Keep 'X' separate */
1798 					++pp;
1799 					pp->p_special = 'X';
1800 					pp->p_op = op;
1801 				}
1802 			} else if (seen_X) {
1803 				ushort_t op;
1804 
1805 				/* Remember the 'who' for the X */
1806 				pp->p_who = who;
1807 
1808 				op = pp->p_op;
1809 
1810 				/* Keep 'X' separate */
1811 				++pp;
1812 				pp->p_perm = 0;
1813 				pp->p_special = 0;
1814 				pp->p_op = op;
1815 			}
1816 			++amode;
1817 			pp->p_perm |= t;
1818 		}
1819 
1820 		/*
1821 		 * These returned 0, but were actually parsed, so
1822 		 * don't look at them again.
1823 		 */
1824 		switch (pp->p_special) {
1825 		case 'u':
1826 		case 'g':
1827 		case 'o':
1828 			++amode;
1829 			break;
1830 		}
1831 		pp->p_who = who;
1832 		switch (*amode) {
1833 		case '\0':
1834 			break;
1835 
1836 		case ',':
1837 			++amode;
1838 			++pp;
1839 			continue;
1840 
1841 		default:
1842 			++pp;
1843 			goto samewho;
1844 		}
1845 		break;
1846 	}
1847 	endp = pp;
1848 	return (NULL);
1849 }
1850 
1851 /*
1852  * Given a character from the mode, return the associated
1853  * value as who (user designation) mask or 0 if this isn't valid.
1854  */
1855 static int
1856 iswho(c)
1857 int c;
1858 {
1859 	switch (c) {
1860 	case 'a':
1861 		return (P_A);
1862 
1863 	case 'u':
1864 		return (P_U);
1865 
1866 	case 'g':
1867 		return (P_G);
1868 
1869 	case 'o':
1870 		return (P_O);
1871 
1872 	default:
1873 		return (0);
1874 	}
1875 	/* NOTREACHED */
1876 }
1877 
1878 /*
1879  * Return non-zero if this is a valid op code
1880  * in a symbolic mode.
1881  */
1882 static int
1883 isop(c)
1884 int c;
1885 {
1886 	switch (c) {
1887 	case '+':
1888 	case '-':
1889 	case '=':
1890 		return (1);
1891 
1892 	default:
1893 		return (0);
1894 	}
1895 	/* NOTREACHED */
1896 }
1897 
1898 /*
1899  * Return the permission bits implied by this character or 0
1900  * if it isn't valid.  Also returns 0 when the pseudo-permissions 'u', 'g', or
1901  * 'o' are used, and sets pp->p_special to the one used.
1902  */
1903 static int
1904 isperm(pp, c)
1905 PERMST *pp;
1906 int c;
1907 {
1908 	switch (c) {
1909 	case 'u':
1910 	case 'g':
1911 	case 'o':
1912 		pp->p_special = c;
1913 		return (0);
1914 
1915 	case 'r':
1916 		return (S_IRUSR|S_IRGRP|S_IROTH);
1917 
1918 	case 'w':
1919 		return (S_IWUSR|S_IWGRP|S_IWOTH);
1920 
1921 	case 'x':
1922 		return (S_IXUSR|S_IXGRP|S_IXOTH);
1923 
1924 #if S_ISVTX != 0
1925 	case 't':
1926 		return (S_ISVTX);
1927 #endif
1928 
1929 	case 'X':
1930 		pp->p_special = 'X';
1931 		return (S_IXUSR|S_IXGRP|S_IXOTH);
1932 
1933 #if S_ISVTX != 0
1934 	case 'a':
1935 		return (S_ISVTX);
1936 #endif
1937 
1938 	case 'h':
1939 		return (S_ISUID);
1940 
1941 	/*
1942 	 * This change makes:
1943 	 *	chmod +s file
1944 	 * set the system bit on dos but means that
1945 	 *	chmod u+s file
1946 	 *	chmod g+s file
1947 	 *	chmod a+s file
1948 	 * are all like UNIX.
1949 	 */
1950 	case 's':
1951 		return (nowho ? S_ISGID : S_ISGID|S_ISUID);
1952 
1953 	default:
1954 		return (0);
1955 	}
1956 	/* NOTREACHED */
1957 }
1958 
1959 /*
1960  * Execute the automaton that is created by readmode()
1961  * to generate the final mode that will be used.  This
1962  * code is passed a starting mode that is usually the original
1963  * mode of the file being changed (or 0).  Note that this mode must contain
1964  * the file-type bits as well, so that S_ISDIR will succeed on directories.
1965  */
1966 static mode_t
1967 getmode(mode_t startmode)
1968 {
1969 	PERMST *pp;
1970 	mode_t temp;
1971 	mode_t perm;
1972 
1973 	for (pp = &machine[0]; pp <= endp; ++pp) {
1974 		perm = (mode_t)0;
1975 		/*
1976 		 * For the special modes 'u', 'g' and 'o', the named portion
1977 		 * of the mode refers to after the previous clause has been
1978 		 * processed, while the 'X' mode refers to the contents of the
1979 		 * mode before any clauses have been processed.
1980 		 *
1981 		 * References: P1003.2/D11.2, Section 4.7.7,
1982 		 *  lines 2568-2570, 2578-2583
1983 		 */
1984 		switch (pp->p_special) {
1985 		case 'u':
1986 			temp = startmode & S_IRWXU;
1987 			if (temp & (S_IRUSR|S_IRGRP|S_IROTH))
1988 				perm |= ((S_IRUSR|S_IRGRP|S_IROTH) &
1989 				    pp->p_who);
1990 			if (temp & (S_IWUSR|S_IWGRP|S_IWOTH))
1991 				perm |= ((S_IWUSR|S_IWGRP|S_IWOTH) & pp->p_who);
1992 			if (temp & (S_IXUSR|S_IXGRP|S_IXOTH))
1993 				perm |= ((S_IXUSR|S_IXGRP|S_IXOTH) & pp->p_who);
1994 			break;
1995 
1996 		case 'g':
1997 			temp = startmode & S_IRWXG;
1998 			if (temp & (S_IRUSR|S_IRGRP|S_IROTH))
1999 				perm |= ((S_IRUSR|S_IRGRP|S_IROTH) & pp->p_who);
2000 			if (temp & (S_IWUSR|S_IWGRP|S_IWOTH))
2001 				perm |= ((S_IWUSR|S_IWGRP|S_IWOTH) & pp->p_who);
2002 			if (temp & (S_IXUSR|S_IXGRP|S_IXOTH))
2003 				perm |= ((S_IXUSR|S_IXGRP|S_IXOTH) & pp->p_who);
2004 			break;
2005 
2006 		case 'o':
2007 			temp = startmode & S_IRWXO;
2008 			if (temp & (S_IRUSR|S_IRGRP|S_IROTH))
2009 				perm |= ((S_IRUSR|S_IRGRP|S_IROTH) & pp->p_who);
2010 			if (temp & (S_IWUSR|S_IWGRP|S_IWOTH))
2011 				perm |= ((S_IWUSR|S_IWGRP|S_IWOTH) & pp->p_who);
2012 			if (temp & (S_IXUSR|S_IXGRP|S_IXOTH))
2013 				perm |= ((S_IXUSR|S_IXGRP|S_IXOTH) & pp->p_who);
2014 			break;
2015 
2016 		case 'X':
2017 			perm = pp->p_perm;
2018 			break;
2019 
2020 		default:
2021 			perm = pp->p_perm;
2022 			break;
2023 		}
2024 		switch (pp->p_op) {
2025 		case '-':
2026 			startmode &= ~(perm & pp->p_who);
2027 			break;
2028 
2029 		case '=':
2030 			startmode &= ~pp->p_who;
2031 			/* FALLTHROUGH */
2032 		case '+':
2033 			startmode |= (perm & pp->p_who);
2034 			break;
2035 		}
2036 	}
2037 	return (startmode);
2038 }
2039 
2040 /*
2041  * Returns the last component of a path name, unless it is
2042  * an absolute path, in which case it returns the whole path
2043  */
2044 static char
2045 *gettail(char *fname)
2046 {
2047 	char	*base = fname;
2048 
2049 	if (*fname != '/') {
2050 		if ((base = strrchr(fname, '/')) != NULL)
2051 			base++;
2052 		else
2053 			base = fname;
2054 	}
2055 	return (base);
2056 }
2057