xref: /titanic_41/usr/src/cmd/ls/ls.c (revision 2c2d21e98a95cba5687ec6574c974a5c6c4a6adb)
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 /*
23  * Copyright (c) 1988, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
25  */
26 
27 /*
28  * Copyright 2009 Jason King.  All rights reserved.
29  * Use is subject to license terms.
30  */
31 
32 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
33 /*	  All Rights Reserved  	*/
34 
35 /*	Copyright (c) 1987, 1988 Microsoft Corporation	*/
36 /*	  All Rights Reserved	*/
37 
38 /*
39  * List files or directories
40  */
41 
42 #include <sys/param.h>
43 #include <sys/types.h>
44 #include <sys/mkdev.h>
45 #include <sys/stat.h>
46 #include <sys/acl.h>
47 
48 #include <wchar.h>
49 #include <stdio.h>
50 #include <ctype.h>
51 #include <dirent.h>
52 #include <string.h>
53 #include <locale.h>
54 #include <curses.h>
55 #include <term.h>
56 #include <termios.h>
57 #include <stdlib.h>
58 #include <widec.h>
59 #include <locale.h>
60 #include <wctype.h>
61 #include <pwd.h>
62 #include <grp.h>
63 #include <limits.h>
64 #include <fcntl.h>
65 #include <unistd.h>
66 #include <libgen.h>
67 #include <errno.h>
68 #include <aclutils.h>
69 #include <libnvpair.h>
70 #include <libcmdutils.h>
71 #include <attr.h>
72 #include <getopt.h>
73 #include <inttypes.h>
74 
75 #ifndef STANDALONE
76 #define	TERMINFO
77 #endif
78 
79 /*
80  * -DNOTERMINFO can be defined on the cc command line to prevent
81  * the use of terminfo.  This should be done on systems not having
82  * the terminfo feature(pre 6.0 systems ?).
83  * As a result, columnar listings assume 80 columns for output,
84  * unless told otherwise via the COLUMNS environment variable.
85  */
86 #ifdef NOTERMINFO
87 #undef TERMINFO
88 #endif
89 
90 #include <term.h>
91 
92 #define	BFSIZE	16
93 /* this bit equals 1 in lflags of structure lbuf if *namep is to be used */
94 #define	ISARG	0100000
95 
96 /*
97  * this flag has been added to manipulate the display of S instead of 'l' when
98  * the file is not a regular file and when group execution bit is off
99  */
100 #define	LS_NOTREG	010000
101 
102 
103 /*
104  * Date and time formats
105  *
106  * b --- abbreviated month name
107  * e --- day number
108  * Y --- year in the form ccyy
109  * H --- hour(24-hour version)
110  * M --- minute
111  * F --- yyyy-mm-dd
112  * T --- hh:mm:ss
113  * z --- time zone as hours displacement from UTC
114  * note that %F and %z are from the ISO C99 standard and are
115  * not present in older C libraries
116  */
117 #define	FORMAT_OLD	" %b %e  %Y "
118 #define	FORMAT_NEW	" %b %e %H:%M "
119 #define	FORMAT_LONG	" %b %e %T %Y "
120 #define	FORMAT_ISO_FULL	" %%F %%T.%.09ld %%z "
121 #define	FORMAT_ISO_LONG	" %F %R "
122 #define	FORMAT_ISO_NEW	" %m-%d %H:%M "
123 #define	FORMAT_ISO_OLD	" %F "
124 
125 #undef BUFSIZ
126 #define	BUFSIZ 4096
127 #define	NUMBER_WIDTH 40
128 #define	FMTSIZE 50
129 
130 struct ditem {
131 	dev_t	dev;			/* directory items device number */
132 	ino_t	ino;			/* directory items inode number */
133 	struct ditem *parent;		/* dir items ptr to its parent's info */
134 };
135 /* Holds boolean extended system attributes */
136 struct attrb {
137 	char		*name;
138 };
139 /* Holds timestamp extended system attributes */
140 struct attrtm {
141 	char		*name;
142 	uint64_t	stm;
143 	uint64_t	nstm;
144 };
145 
146 #define	LSA_NONE	(0)
147 #define	LSA_BOLD	(1L << 0)
148 #define	LSA_UNDERSCORE	(1L << 1)
149 #define	LSA_BLINK	(1L << 2)
150 #define	LSA_REVERSE	(1L << 3)
151 #define	LSA_CONCEALED	(1L << 4)
152 
153 /* these should be ordered most general to most specific */
154 typedef enum LS_CFTYPE {
155 	LS_NORMAL,
156 	LS_FILE,
157 	LS_EXEC,
158 	LS_DIR,
159 	LS_LINK,
160 	LS_FIFO,
161 	LS_SOCK,
162 	LS_DOOR,
163 	LS_BLK,
164 	LS_CHR,
165 	LS_PORT,
166 	LS_STICKY,
167 	LS_ORPHAN,
168 	LS_SETGID,
169 	LS_SETUID,
170 	LS_OTHER_WRITABLE,
171 	LS_STICKY_OTHER_WRITABLE,
172 	LS_PAT
173 } ls_cftype_t;
174 
175 typedef struct {
176 	char		*sfx;
177 	ls_cftype_t	ftype;
178 	int		attr;
179 	int		fg;
180 	int		bg;
181 } ls_color_t;
182 
183 struct	lbuf	{
184 	union	{
185 		char	lname[MAXNAMLEN]; /* used for filename in a directory */
186 		char	*namep;		/* for name in ls-command; */
187 	} ln;
188 	char	ltype;		/* filetype */
189 	ino_t	lnum;		/* inode number of file */
190 	mode_t	lflags; 	/* 0777 bits used as r,w,x permissions */
191 	nlink_t	lnl;		/* number of links to file */
192 	uid_t	luid;
193 	gid_t	lgid;
194 	off_t	lsize;		/* filesize or major/minor dev numbers */
195 	blkcnt_t	lblocks;	/* number of file blocks */
196 	timestruc_t	lmtime;
197 	timestruc_t	lat;
198 	timestruc_t	lct;
199 	timestruc_t	lmt;
200 	char	*flinkto;	/* symbolic link contents */
201 	char 	acl;		/* indicate there are additional acl entries */
202 	int	cycle;		/* cycle detected flag */
203 	struct ditem *ancinfo;	/* maintains ancestor info */
204 	acl_t *aclp;		/* ACL if present */
205 	struct attrb *exttr;	/* boolean extended system attributes */
206 	struct attrtm *extm;	/* timestamp extended system attributes */
207 	ls_color_t	*color;	/* color for entry */
208 	ls_color_t	*link_color;	/* color for symlink */
209 };
210 
211 struct dchain {
212 	char *dc_name;		/* path name */
213 	int cycle_detected;	/* cycle detected visiting this directory */
214 	struct ditem *myancinfo;	/* this directory's ancestry info */
215 	struct dchain *dc_next;	/* next directory in the chain */
216 };
217 
218 /*
219  * A numbuf_t is used when converting a number to a string representation
220  */
221 typedef char numbuf_t[NUMBER_WIDTH];
222 
223 static struct dchain *dfirst;	/* start of the dir chain */
224 static struct dchain *cdfirst;	/* start of the current dir chain */
225 static struct dchain *dtemp;	/* temporary - used for linking */
226 static char *curdir;		/* the current directory */
227 
228 static int	first = 1;	/* true if first line is not yet printed */
229 static int	nfiles = 0;	/* number of flist entries in current use */
230 static int	nargs = 0;	/* number of flist entries used for arguments */
231 static int	maxfils = 0;	/* number of flist/lbuf entries allocated */
232 static int	maxn = 0;	/* number of flist entries with lbufs asigned */
233 static int	quantn = 64;	/* allocation growth quantum */
234 
235 static struct lbuf	*nxtlbf;	/* ptr to next lbuf to be assigned */
236 static struct lbuf	**flist;	/* ptr to list of lbuf pointers */
237 static struct lbuf	*gstat(char *, int, struct ditem *);
238 static char		*getname(uid_t);
239 static char		*getgroup(gid_t);
240 static char		*makename(char *, char *);
241 static void		pentry(struct lbuf *);
242 static void		column(void);
243 static void		pmode(mode_t aflag);
244 static void		selection(int *);
245 static void		new_line(void);
246 static void		rddir(char *, struct ditem *);
247 static int		strcol(unsigned char *);
248 static void		pem(struct lbuf **, struct lbuf **, int);
249 static void		pdirectory(char *, int, int, int, struct ditem *);
250 static struct cachenode *findincache(struct cachenode **, long);
251 static void		csi_pprintf(unsigned char *);
252 static void		pprintf(char *, char *);
253 static int		compar(struct lbuf **pp1, struct lbuf **pp2);
254 static char 		*number_to_scaled_string(numbuf_t buf,
255 			    unsigned long long number,
256 			    long scale);
257 static void		record_ancestry(char *, struct stat *, struct lbuf *,
258 			    int, struct ditem *);
259 static void		ls_color_init(void);
260 static ls_color_t	*ls_color_find(const char *, mode_t);
261 static void		ls_start_color(ls_color_t *);
262 static void		ls_end_color(void);
263 
264 static int		aflg;
265 static int		atflg;
266 static int		bflg;
267 static int		cflg;
268 static int		dflg;
269 static int		eflg;
270 static int		fflg;
271 static int		gflg;
272 static int		hflg;
273 static int		iflg;
274 static int		lflg;
275 static int		mflg;
276 static int		nflg;
277 static int		oflg;
278 static int		pflg;
279 static int		qflg;
280 static int		rflg = 1; /* init to 1 for special use in compar */
281 static int		sflg;
282 static int		tflg;
283 static int		uflg;
284 static int		Uflg;
285 static int		wflg;
286 static int		xflg;
287 static int		Aflg;
288 static int		Bflg;
289 static int		Cflg;
290 static int		Eflg;
291 static int		Fflg;
292 static int		Hflg;
293 static int		Lflg;
294 static int		Rflg;
295 static int		Sflg;
296 static int		vflg;
297 static int		Vflg;
298 static int		saflg;		/* boolean extended system attr. */
299 static int		sacnt;		/* number of extended system attr. */
300 static int		copt;
301 static int		vopt;
302 static int		tmflg;		/* create time ext. system attr. */
303 static int		ctm;
304 static int		atm;
305 static int		mtm;
306 static int		crtm;
307 static int		alltm;
308 static long		hscale;
309 static mode_t		flags;
310 static int		err = 0;	/* Contains return code */
311 static int		colorflg;
312 static int		file_typeflg;
313 static int		noflist = 0;
314 
315 static uid_t		lastuid	= (uid_t)-1;
316 static gid_t		lastgid = (gid_t)-1;
317 static char		*lastuname = NULL;
318 static char		*lastgname = NULL;
319 
320 /* statreq > 0 if any of sflg, (n)lflg, tflg, Sflg, colorflg are on */
321 static int		statreq;
322 
323 static uint64_t		block_size = 1;
324 static char		*dotp = ".";
325 
326 static u_longlong_t 	tblocks; /* number of blocks of files in a directory */
327 static time_t		year, now;
328 
329 static int		num_cols = 80;
330 static int		colwidth;
331 static int		filewidth;
332 static int		fixedwidth;
333 static int		nomocore;
334 static int		curcol;
335 
336 static struct	winsize	win;
337 
338 /* if time_fmt_new is left NULL, time_fmt_old is used for all times */
339 static const char	*time_fmt_old = FORMAT_OLD;	/* non-recent files */
340 static const char	*time_fmt_new = FORMAT_NEW;	/* recent files */
341 static int		time_custom;	/* != 0 if a custom format */
342 static char	time_buf[FMTSIZE];	/* array to hold day and time */
343 
344 static int		lsc_debug;
345 static ls_color_t	*lsc_match;
346 static ls_color_t	*lsc_colors;
347 static size_t		lsc_ncolors;
348 static char		*lsc_bold;
349 static char		*lsc_underline;
350 static char		*lsc_blink;
351 static char		*lsc_reverse;
352 static char		*lsc_concealed;
353 static char		*lsc_none;
354 static char		*lsc_setfg;
355 static char		*lsc_setbg;
356 static ls_color_t	*lsc_orphan;
357 
358 #define	NOTWORKINGDIR(d, l)	(((l) < 2) || \
359 				    (strcmp((d) + (l) - 2, "/.") != 0))
360 
361 #define	NOTPARENTDIR(d, l)	(((l) < 3) || \
362 				    (strcmp((d) + (l) - 3, "/..") != 0))
363 /* Extended system attributes support */
364 static int get_sysxattr(char *, struct lbuf *);
365 static void set_sysattrb_display(char *, boolean_t, struct lbuf *);
366 static void set_sysattrtm_display(char *, struct lbuf *);
367 static void format_time(time_t, time_t);
368 static void print_time(struct lbuf *);
369 static void format_attrtime(struct lbuf *);
370 static void *xmalloc(size_t, struct lbuf *);
371 static void free_sysattr(struct lbuf *);
372 static nvpair_t *pair;
373 static nvlist_t	*response;
374 static int acl_err;
375 
376 const struct option long_options[] = {
377 	{ "all", no_argument, NULL, 'a' },
378 	{ "almost-all", no_argument, NULL, 'A' },
379 	{ "escape", no_argument, NULL, 'b' },
380 	{ "classify", no_argument, NULL, 'F' },
381 	{ "human-readable", no_argument, NULL, 'h' },
382 	{ "dereference", no_argument, NULL, 'L' },
383 	{ "dereference-command-line", no_argument, NULL, 'H' },
384 	{ "ignore-backups", no_argument, NULL, 'B' },
385 	{ "inode", no_argument, NULL, 'i' },
386 	{ "numeric-uid-gid", no_argument, NULL, 'n' },
387 	{ "no-group", no_argument, NULL, 'o' },
388 	{ "hide-control-chars", no_argument, NULL, 'q' },
389 	{ "reverse", no_argument, NULL, 'r' },
390 	{ "recursive", no_argument, NULL, 'R' },
391 	{ "size", no_argument, NULL, 's' },
392 	{ "width", required_argument, NULL, 'w' },
393 
394 	/* no short options for these */
395 	{ "block-size", required_argument, NULL, 0 },
396 	{ "full-time", no_argument, NULL, 0 },
397 	{ "si", no_argument, NULL, 0 },
398 	{ "color", optional_argument, NULL, 0 },
399 	{ "colour", optional_argument, NULL, 0},
400 	{ "file-type", no_argument, NULL, 0 },
401 	{ "time-style", required_argument, NULL, 0 },
402 
403 	{0, 0, 0, 0}
404 };
405 
406 int
407 main(int argc, char *argv[])
408 {
409 	int		c;
410 	int		i;
411 	int		width;
412 	int		amino = 0;
413 	int		opterr = 0;
414 	int		option_index = 0;
415 	struct lbuf	*ep;
416 	struct lbuf	lb;
417 	struct ditem	*myinfo;
418 
419 	(void) setlocale(LC_ALL, "");
420 #if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
421 #define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
422 #endif
423 	(void) textdomain(TEXT_DOMAIN);
424 #ifdef STANDALONE
425 	if (argv[0][0] == '\0')
426 		argc = getargv("ls", &argv, 0);
427 #endif
428 
429 	lb.lmtime.tv_sec = time(NULL);
430 	lb.lmtime.tv_nsec = 0;
431 	year = lb.lmtime.tv_sec - 6L*30L*24L*60L*60L; /* 6 months ago */
432 	now = lb.lmtime.tv_sec + 60;
433 	if (isatty(1)) {
434 		Cflg = 1;
435 		mflg = 0;
436 	}
437 
438 	while ((c = getopt_long(argc, argv,
439 	    "+aAbBcCdeEfFghHiklLmnopqrRsStuUw:x1@vV/:%:", long_options,
440 	    &option_index)) != -1)
441 		switch (c) {
442 		case 0:
443 			/* non-short options */
444 			if (strcmp(long_options[option_index].name,
445 			    "color") == 0 ||
446 			    strcmp(long_options[option_index].name,
447 			    "colour") == 0) {
448 				if (optarg == NULL ||
449 				    strcmp(optarg, "always") == 0 ||
450 				    strcmp(optarg, "yes") == 0 ||
451 				    strcmp(optarg, "force") == 0) {
452 					colorflg++;
453 					statreq++;
454 					continue;
455 				}
456 
457 				if (strcmp(optarg, "auto") == 0 ||
458 				    strcmp(optarg, "tty") == 0 ||
459 				    strcmp(optarg, "if-tty") == 0) {
460 					if (isatty(1) == 1) {
461 						colorflg++;
462 						statreq++;
463 					}
464 					continue;
465 				}
466 
467 				if (strcmp(optarg, "never") == 0 ||
468 				    strcmp(optarg, "no") == 0 ||
469 				    strcmp(optarg, "none") == 0) {
470 					colorflg = 0;
471 					continue;
472 				}
473 				(void) fprintf(stderr,
474 				    gettext("Invalid argument '%s' for "
475 				    "--color\n"), optarg);
476 				++opterr;
477 				continue;
478 			}
479 
480 			if (strcmp(long_options[option_index].name,
481 			    "si") == 0) {
482 				hflg++;
483 				hscale = 1000;
484 				continue;
485 			}
486 
487 			if (strcmp(long_options[option_index].name,
488 			    "block-size") == 0) {
489 				size_t scale_len = strlen(optarg);
490 				uint64_t scale = 1;
491 				uint64_t kilo = 1024;
492 				char scale_c;
493 
494 				if (scale_len == 0) {
495 					(void) fprintf(stderr, gettext(
496 					    "Invalid block size \'%s\'\n"),
497 					    optarg);
498 					exit(1);
499 				}
500 
501 				scale_c = optarg[scale_len - 1];
502 				if (scale_c == 'B') {
503 					/* need at least digit, scale, B */
504 					if (scale_len < 3) {
505 						(void) fprintf(stderr, gettext(
506 						    "Invalid block size "
507 						    "\'%s\'\n"), optarg);
508 						exit(1);
509 					}
510 					kilo = 1000;
511 					scale_c = optarg[scale_len - 2];
512 					if (isdigit(scale_c)) {
513 						(void) fprintf(stderr,
514 						    gettext("Invalid block size"
515 						    " \'%s\'\n"), optarg);
516 						exit(1);
517 					}
518 					/*
519 					 * make optarg[scale_len - 1] point to
520 					 * the scale factor
521 					 */
522 					--scale_len;
523 				}
524 
525 				switch (scale_c) {
526 				case 'y':
527 				case 'Y':
528 					scale *= kilo;
529 					/*FALLTHROUGH*/
530 				case 'Z':
531 				case 'z':
532 					scale *= kilo;
533 					/*FALLTHROUGH*/
534 				case 'E':
535 				case 'e':
536 					scale *= kilo;
537 					/*FALLTHROUGH*/
538 				case 'P':
539 				case 'p':
540 					scale *= kilo;
541 					/*FALLTHROUGH*/
542 				case 'T':
543 				case 't':
544 					scale *= kilo;
545 					/*FALLTHROUGH*/
546 				case 'G':
547 				case 'g':
548 					scale *= kilo;
549 					/*FALLTHROUGH*/
550 				case 'M':
551 				case 'm':
552 					scale *= kilo;
553 					/*FALLTHROUGH*/
554 				case 'K':
555 				case 'k':
556 					scale *= kilo;
557 					break;
558 				default:
559 					if (!isdigit(scale_c)) {
560 						(void) fprintf(stderr,
561 						    gettext("Invalid character "
562 						    "following block size in "
563 						    "\'%s\'\n"), optarg);
564 						exit(1);
565 					}
566 				}
567 
568 				/* NULL out scale constant if present */
569 				if (scale > 1 && !isdigit(scale_c))
570 					optarg[scale_len - 1] = '\0';
571 
572 				/* Based on testing, this is what GNU ls does */
573 				block_size = strtoll(optarg, NULL, 0) * scale;
574 				if (block_size < 1) {
575 					(void) fprintf(stderr,
576 					    gettext("Invalid block size "
577 					    "\'%s\'\n"), optarg);
578 					exit(1);
579 				}
580 				continue;
581 			}
582 
583 			if (strcmp(long_options[option_index].name,
584 			    "file-type") == 0) {
585 				file_typeflg++;
586 				Fflg++;
587 				statreq++;
588 				continue;
589 			}
590 
591 
592 			if (strcmp(long_options[option_index].name,
593 			    "full-time") == 0) {
594 				Eflg++;
595 				statreq++;
596 				eflg = 0;
597 				time_fmt_old = FORMAT_ISO_FULL;
598 				time_fmt_new = FORMAT_ISO_FULL;
599 				continue;
600 			}
601 
602 			if (strcmp(long_options[option_index].name,
603 			    "time-style") == 0) {
604 				/* like -E, but doesn't imply -l */
605 				if (strcmp(optarg, "full-iso") == 0) {
606 					Eflg++;
607 					statreq++;
608 					eflg = 0;
609 					time_fmt_old = FORMAT_ISO_FULL;
610 					time_fmt_new = FORMAT_ISO_FULL;
611 					continue;
612 				}
613 				if (strcmp(optarg, "long-iso") == 0) {
614 					statreq++;
615 					Eflg = 0;
616 					eflg = 0;
617 					time_fmt_old = FORMAT_ISO_LONG;
618 					time_fmt_new = FORMAT_ISO_LONG;
619 					continue;
620 				}
621 				if (strcmp(optarg, "iso") == 0) {
622 					statreq++;
623 					Eflg = 0;
624 					eflg = 0;
625 					time_fmt_old = FORMAT_ISO_OLD;
626 					time_fmt_new = FORMAT_ISO_NEW;
627 					continue;
628 				}
629 				/* should be the default */
630 				if (strcmp(optarg, "locale") == 0) {
631 					time_fmt_old = FORMAT_OLD;
632 					time_fmt_new = FORMAT_NEW;
633 					continue;
634 				}
635 				if (optarg[0] == '+') {
636 					char	*told, *tnew;
637 					char	*p;
638 					size_t	timelen = strlen(optarg);
639 
640 					p = strchr(optarg, '\n');
641 					if (p != NULL)
642 						*p++ = '\0';
643 
644 					/*
645 					 * Time format requires a leading and
646 					 * trailing space
647 					 * Add room for 3 spaces + 2 nulls
648 					 * The + in optarg is replaced with
649 					 * a space.
650 					 */
651 					timelen += 2 + 3;
652 					told = malloc(timelen);
653 					if (told == NULL) {
654 						perror("ls");
655 						exit(2);
656 					}
657 
658 					(void) memset(told, 0, timelen);
659 					told[0] = ' ';
660 					(void) strlcat(told, &optarg[1],
661 					    timelen);
662 					(void) strlcat(told, " ", timelen);
663 
664 					if (p != NULL) {
665 						size_t tnew_len;
666 
667 						tnew = told + strlen(told) + 1;
668 						tnew_len = timelen -
669 						    strlen(told) - 1;
670 
671 						tnew[0] = ' ';
672 						(void) strlcat(tnew, p,
673 						    tnew_len);
674 						(void) strlcat(tnew, " ",
675 						    tnew_len);
676 						time_fmt_new =
677 						    (const char *)tnew;
678 					} else {
679 						time_fmt_new =
680 						    (const char *)told;
681 					}
682 
683 					time_fmt_old = (const char *)told;
684 					time_custom = 1;
685 					continue;
686 				}
687 				continue;
688 			}
689 
690 			continue;
691 
692 		case 'a':
693 			aflg++;
694 			continue;
695 		case 'A':
696 			Aflg++;
697 			continue;
698 		case 'b':
699 			bflg = 1;
700 			qflg = 0;
701 			continue;
702 		case 'B':
703 			Bflg = 1;
704 			continue;
705 		case 'c':
706 			uflg = 0;
707 			atm = 0;
708 			ctm = 0;
709 			mtm = 0;
710 			crtm = 0;
711 			cflg++;
712 			continue;
713 		case 'C':
714 			Cflg = 1;
715 			mflg = 0;
716 #ifdef XPG4
717 			lflg = 0;
718 #endif
719 			continue;
720 		case 'd':
721 			dflg++;
722 			continue;
723 		case 'e':
724 			eflg++;
725 			lflg++;
726 			statreq++;
727 			Eflg = 0;
728 			time_fmt_old = FORMAT_LONG;
729 			time_fmt_new = FORMAT_LONG;
730 			continue;
731 		case 'E':
732 			Eflg++;
733 			lflg++;
734 			statreq++;
735 			eflg = 0;
736 			time_fmt_old = FORMAT_ISO_FULL;
737 			time_fmt_new = FORMAT_ISO_FULL;
738 			continue;
739 		case 'f':
740 			fflg++;
741 			continue;
742 		case 'F':
743 			Fflg++;
744 			statreq++;
745 			continue;
746 		case 'g':
747 			gflg++;
748 			lflg++;
749 			statreq++;
750 			continue;
751 		case 'h':
752 			hflg++;
753 			hscale = 1024;
754 			continue;
755 		case 'H':
756 			Hflg++;
757 			/* -H and -L are mutually exclusive */
758 			Lflg = 0;
759 			continue;
760 		case 'i':
761 			iflg++;
762 			continue;
763 		case 'k':
764 			block_size = 1024;
765 			continue;
766 		case 'l':
767 			lflg++;
768 			statreq++;
769 			Cflg = 0;
770 			xflg = 0;
771 			mflg = 0;
772 			atflg = 0;
773 			continue;
774 		case 'L':
775 			Lflg++;
776 			/* -H and -L are mutually exclusive */
777 			Hflg = 0;
778 			continue;
779 		case 'm':
780 			Cflg = 0;
781 			mflg = 1;
782 #ifdef XPG4
783 			lflg = 0;
784 #endif
785 			continue;
786 		case 'n':
787 			nflg++;
788 			lflg++;
789 			statreq++;
790 			Cflg = 0;
791 			xflg = 0;
792 			mflg = 0;
793 			atflg = 0;
794 			continue;
795 		case 'o':
796 			oflg++;
797 			lflg++;
798 			statreq++;
799 			continue;
800 		case 'p':
801 			pflg++;
802 			statreq++;
803 			continue;
804 		case 'q':
805 			qflg = 1;
806 			bflg = 0;
807 			continue;
808 		case 'r':
809 			rflg = -1;
810 			continue;
811 		case 'R':
812 			Rflg++;
813 			statreq++;
814 			continue;
815 		case 's':
816 			sflg++;
817 			statreq++;
818 			continue;
819 		case 'S':
820 			tflg = 0;
821 			Uflg = 0;
822 			Sflg++;
823 			statreq++;
824 			continue;
825 		case 't':
826 			Sflg = 0;
827 			Uflg = 0;
828 			tflg++;
829 			statreq++;
830 			continue;
831 		case 'U':
832 			Sflg = 0;
833 			tflg = 0;
834 			Uflg++;
835 			continue;
836 		case 'u':
837 			cflg = 0;
838 			atm = 0;
839 			ctm = 0;
840 			mtm = 0;
841 			crtm = 0;
842 			uflg++;
843 			continue;
844 		case 'V':
845 			Vflg++;
846 			/*FALLTHROUGH*/
847 		case 'v':
848 			vflg++;
849 #if !defined(XPG4)
850 			if (lflg)
851 				continue;
852 #endif
853 			lflg++;
854 			statreq++;
855 			Cflg = 0;
856 			xflg = 0;
857 			mflg = 0;
858 			continue;
859 		case 'w':
860 			wflg++;
861 			num_cols = atoi(optarg);
862 			continue;
863 		case 'x':
864 			xflg = 1;
865 			Cflg = 1;
866 			mflg = 0;
867 #ifdef XPG4
868 			lflg = 0;
869 #endif
870 			continue;
871 		case '1':
872 			Cflg = 0;
873 			continue;
874 		case '@':
875 #if !defined(XPG4)
876 			/*
877 			 * -l has precedence over -@
878 			 */
879 			if (lflg)
880 				continue;
881 #endif
882 			atflg++;
883 			lflg++;
884 			statreq++;
885 			Cflg = 0;
886 			xflg = 0;
887 			mflg = 0;
888 			continue;
889 		case '/':
890 			saflg++;
891 			if (optarg != NULL) {
892 				if (strcmp(optarg, "c") == 0) {
893 					copt++;
894 					vopt = 0;
895 				} else if (strcmp(optarg, "v") == 0) {
896 					vopt++;
897 					copt = 0;
898 				} else
899 					opterr++;
900 			} else
901 				opterr++;
902 			lflg++;
903 			statreq++;
904 			Cflg = 0;
905 			xflg = 0;
906 			mflg = 0;
907 			continue;
908 		case '%':
909 			tmflg++;
910 			if (optarg != NULL) {
911 				if (strcmp(optarg, "ctime") == 0) {
912 					ctm++;
913 					atm = 0;
914 					mtm = 0;
915 					crtm = 0;
916 				} else if (strcmp(optarg, "atime") == 0) {
917 					atm++;
918 					ctm = 0;
919 					mtm = 0;
920 					crtm = 0;
921 					uflg = 0;
922 					cflg = 0;
923 				} else if (strcmp(optarg, "mtime") == 0) {
924 					mtm++;
925 					atm = 0;
926 					ctm = 0;
927 					crtm = 0;
928 					uflg = 0;
929 					cflg = 0;
930 				} else if (strcmp(optarg, "crtime") == 0) {
931 					crtm++;
932 					atm = 0;
933 					ctm = 0;
934 					mtm = 0;
935 					uflg = 0;
936 					cflg = 0;
937 				} else if (strcmp(optarg, "all") == 0) {
938 					alltm++;
939 					atm = 0;
940 					ctm = 0;
941 					mtm = 0;
942 					crtm = 0;
943 				} else
944 					opterr++;
945 			} else
946 				opterr++;
947 
948 			Sflg = 0;
949 			statreq++;
950 			mflg = 0;
951 			continue;
952 		case '?':
953 			opterr++;
954 			continue;
955 		}
956 
957 	if (opterr) {
958 		(void) fprintf(stderr, gettext(
959 		    "usage: ls -aAbBcCdeEfFghHiklLmnopqrRsStuUwxvV1@/%[c | v]"
960 		    "%%[atime | crtime | ctime | mtime | all]"
961 		    " [files]\n"));
962 		exit(2);
963 	}
964 
965 	if (fflg) {
966 		aflg++;
967 		lflg = 0;
968 		sflg = 0;
969 		tflg = 0;
970 		Sflg = 0;
971 		statreq = 0;
972 	}
973 
974 	fixedwidth = 2;
975 	if (pflg || Fflg)
976 		fixedwidth++;
977 	if (iflg)
978 		fixedwidth += 11;
979 	if (sflg)
980 		fixedwidth += 5;
981 
982 	if (lflg) {
983 		if (!gflg && !oflg)
984 			gflg = oflg = 1;
985 		else
986 		if (gflg && oflg)
987 			gflg = oflg = 0;
988 		Cflg = mflg = 0;
989 	}
990 
991 	if (!wflg && (Cflg || mflg)) {
992 		char *clptr;
993 		if ((clptr = getenv("COLUMNS")) != NULL)
994 			num_cols = atoi(clptr);
995 #ifdef TERMINFO
996 		else {
997 			if (ioctl(1, TIOCGWINSZ, &win) != -1)
998 				num_cols = (win.ws_col == 0 ? 80 : win.ws_col);
999 		}
1000 #endif
1001 	}
1002 
1003 	/*
1004 	 * When certain options (-f, or -U and -1, and not -l, etc.) are
1005 	 * specified, don't cache each dirent as it's read.  This 'noflist'
1006 	 * option is set when there's no need to cache those dirents; instead,
1007 	 * print them out as they're read.
1008 	 */
1009 	if ((Uflg || fflg) && !Cflg && !lflg && !iflg && statreq == 0)
1010 		noflist = 1;
1011 
1012 	if (num_cols < 20 || num_cols > 1000)
1013 		/* assume it is an error */
1014 		num_cols = 80;
1015 
1016 	/* allocate space for flist and the associated	*/
1017 	/* data structures (lbufs)			*/
1018 	maxfils = quantn;
1019 	if (((flist = malloc(maxfils * sizeof (struct lbuf *))) == NULL) ||
1020 	    ((nxtlbf = malloc(quantn * sizeof (struct lbuf))) == NULL)) {
1021 		perror("ls");
1022 		exit(2);
1023 	}
1024 	if ((amino = (argc-optind)) == 0) {
1025 					/*
1026 					 * case when no names are given
1027 					 * in ls-command and current
1028 					 * directory is to be used
1029 					 */
1030 		argv[optind] = dotp;
1031 	}
1032 
1033 	for (i = 0; i < (amino ? amino : 1); i++) {
1034 
1035 		/*
1036 		 * If we are recursing, we need to make sure we don't
1037 		 * get into an endless loop.  To keep track of the inodes
1038 		 * (actually, just the directories) visited, we
1039 		 * maintain a directory ancestry list for a file
1040 		 * hierarchy.  As we go deeper into the hierarchy,
1041 		 * a parent directory passes its directory list
1042 		 * info (device id, inode number, and a pointer to
1043 		 * its parent) to each of its children.  As we
1044 		 * process a child that is a directory, we save
1045 		 * its own personal directory list info.  We then
1046 		 * check to see if the child has already been
1047 		 * processed by comparing its device id and inode
1048 		 * number from its own personal directory list info
1049 		 * to that of each of its ancestors.  If there is a
1050 		 * match, then we know we've detected a cycle.
1051 		 */
1052 		if (Rflg) {
1053 			/*
1054 			 * This is the first parent in this lineage
1055 			 * (first in a directory hierarchy), so
1056 			 * this parent's parent doesn't exist.  We
1057 			 * only initialize myinfo when we are
1058 			 * recursing, otherwise it's not used.
1059 			 */
1060 			if ((myinfo = (struct ditem *)malloc(
1061 			    sizeof (struct ditem))) == NULL) {
1062 				perror("ls");
1063 				exit(2);
1064 			} else {
1065 				myinfo->dev = 0;
1066 				myinfo->ino = 0;
1067 				myinfo->parent = NULL;
1068 			}
1069 		}
1070 
1071 		if (Cflg || mflg) {
1072 			width = strcol((unsigned char *)argv[optind]);
1073 			if (width > filewidth)
1074 				filewidth = width;
1075 		}
1076 		if ((ep = gstat((*argv[optind] ? argv[optind] : dotp),
1077 		    1, myinfo)) == NULL) {
1078 			if (nomocore)
1079 				exit(2);
1080 			err = 2;
1081 			optind++;
1082 			continue;
1083 		}
1084 		ep->ln.namep = (*argv[optind] ? argv[optind] : dotp);
1085 		ep->lflags |= ISARG;
1086 		optind++;
1087 		nargs++;	/* count good arguments stored in flist */
1088 		if (acl_err)
1089 			err = 2;
1090 	}
1091 	colwidth = fixedwidth + filewidth;
1092 	if (!Uflg)
1093 		qsort(flist, (unsigned)nargs, sizeof (struct lbuf *),
1094 		    (int (*)(const void *, const void *))compar);
1095 	for (i = 0; i < nargs; i++) {
1096 		if (flist[i]->ltype == 'd' && dflg == 0 || fflg)
1097 			break;
1098 	}
1099 
1100 	if (colorflg)
1101 		ls_color_init();
1102 
1103 	pem(&flist[0], &flist[i], 0);
1104 	for (; i < nargs; i++) {
1105 		pdirectory(flist[i]->ln.namep, Rflg ||
1106 		    (amino > 1), nargs, 0, flist[i]->ancinfo);
1107 		if (nomocore)
1108 			exit(2);
1109 		/* -R: print subdirectories found */
1110 		while (dfirst || cdfirst) {
1111 			/* Place direct subdirs on front in right order */
1112 			while (cdfirst) {
1113 				/* reverse cdfirst onto front of dfirst */
1114 				dtemp = cdfirst;
1115 				cdfirst = cdfirst -> dc_next;
1116 				dtemp -> dc_next = dfirst;
1117 				dfirst = dtemp;
1118 			}
1119 			/* take off first dir on dfirst & print it */
1120 			dtemp = dfirst;
1121 			dfirst = dfirst->dc_next;
1122 			pdirectory(dtemp->dc_name, 1, nargs,
1123 			    dtemp->cycle_detected, dtemp->myancinfo);
1124 			if (nomocore)
1125 				exit(2);
1126 			free(dtemp->dc_name);
1127 			free(dtemp);
1128 		}
1129 	}
1130 
1131 	return (err);
1132 }
1133 
1134 /*
1135  * pdirectory: print the directory name, labelling it if title is
1136  * nonzero, using lp as the place to start reading in the dir.
1137  */
1138 static void
1139 pdirectory(char *name, int title, int lp, int cdetect, struct ditem *myinfo)
1140 {
1141 	struct dchain *dp;
1142 	struct lbuf *ap;
1143 	char *pname;
1144 	int j;
1145 
1146 	filewidth = 0;
1147 	curdir = name;
1148 	if (title) {
1149 		if (!first)
1150 			(void) putc('\n', stdout);
1151 		pprintf(name, ":");
1152 		new_line();
1153 	}
1154 	/*
1155 	 * If there was a cycle detected, then notify and don't report
1156 	 * further.
1157 	 */
1158 	if (cdetect) {
1159 		if (lflg || sflg) {
1160 			curcol += printf(gettext("total %d"), 0);
1161 			new_line();
1162 		}
1163 		(void) fprintf(stderr, gettext(
1164 		    "ls: cycle detected for %s\n"), name);
1165 		return;
1166 	}
1167 
1168 	nfiles = lp;
1169 	rddir(name, myinfo);
1170 	if (nomocore || noflist)
1171 		return;
1172 	if (fflg == 0 && Uflg == 0)
1173 		qsort(&flist[lp], (unsigned)(nfiles - lp),
1174 		    sizeof (struct lbuf *),
1175 		    (int (*)(const void *, const void *))compar);
1176 	if (Rflg) {
1177 		for (j = nfiles - 1; j >= lp; j--) {
1178 			ap = flist[j];
1179 			if (ap->ltype == 'd' && strcmp(ap->ln.lname, ".") &&
1180 			    strcmp(ap->ln.lname, "..")) {
1181 				dp = malloc(sizeof (struct dchain));
1182 				if (dp == NULL) {
1183 					perror("ls");
1184 					exit(2);
1185 				}
1186 				pname = makename(curdir, ap->ln.lname);
1187 				if ((dp->dc_name = strdup(pname)) == NULL) {
1188 					perror("ls");
1189 					exit(2);
1190 				}
1191 				dp->cycle_detected = ap->cycle;
1192 				dp->myancinfo = ap->ancinfo;
1193 				dp->dc_next = dfirst;
1194 				dfirst = dp;
1195 			}
1196 		}
1197 	}
1198 	if (lflg || sflg) {
1199 		curcol += printf(gettext("total %llu"), tblocks);
1200 		new_line();
1201 	}
1202 	pem(&flist[lp], &flist[nfiles], lflg||sflg);
1203 }
1204 
1205 /*
1206  * pem: print 'em. Print a list of files (e.g. a directory) bounded
1207  * by slp and lp.
1208  */
1209 static void
1210 pem(struct lbuf **slp, struct lbuf **lp, int tot_flag)
1211 {
1212 	long row, nrows, i;
1213 	int col, ncols;
1214 	struct lbuf **ep;
1215 
1216 	if (Cflg || mflg) {
1217 		if (colwidth > num_cols) {
1218 			ncols = 1;
1219 		} else {
1220 			ncols = num_cols / colwidth;
1221 		}
1222 	}
1223 
1224 	if (ncols == 1 || mflg || xflg || !Cflg) {
1225 		for (ep = slp; ep < lp; ep++)
1226 			pentry(*ep);
1227 		new_line();
1228 		return;
1229 	}
1230 	/* otherwise print -C columns */
1231 	if (tot_flag) {
1232 		slp--;
1233 		row = 1;
1234 	}
1235 	else
1236 		row = 0;
1237 
1238 	nrows = (lp - slp - 1) / ncols + 1;
1239 	for (i = 0; i < nrows; i++, row++) {
1240 		for (col = 0; col < ncols; col++) {
1241 			ep = slp + (nrows * col) + row;
1242 			if (ep < lp)
1243 				pentry(*ep);
1244 		}
1245 		new_line();
1246 	}
1247 }
1248 
1249 /*
1250  * print one output entry;
1251  * if uid/gid is not found in the appropriate
1252  * file(passwd/group), then print uid/gid instead of
1253  * user/group name;
1254  */
1255 static void
1256 pentry(struct lbuf *ap)
1257 {
1258 	struct lbuf *p;
1259 	numbuf_t hbuf;
1260 	char *dmark = "";	/* Used if -p or -F option active */
1261 	char *cp;
1262 	char *str;
1263 
1264 	if (noflist) {
1265 		(void) printf("%s\n", ap->ln.lname);
1266 		return;
1267 	}
1268 
1269 	p = ap;
1270 	column();
1271 	if (iflg)
1272 		if (mflg && !lflg)
1273 			curcol += printf("%llu ", (long long)p->lnum);
1274 		else
1275 			curcol += printf("%10llu ", (long long)p->lnum);
1276 	if (sflg)
1277 		curcol += printf((mflg && !lflg) ? "%lld " :
1278 		    (p->lblocks < 10000) ? "%4lld " : "%lld ",
1279 		    (p->ltype != 'b' && p->ltype != 'c') ?
1280 		    p->lblocks : 0LL);
1281 	if (lflg) {
1282 		(void) putchar(p->ltype);
1283 		curcol++;
1284 		pmode(p->lflags);
1285 
1286 		/* ACL: additional access mode flag */
1287 		(void) putchar(p->acl);
1288 		curcol++;
1289 
1290 		curcol += printf("%3lu ", (ulong_t)p->lnl);
1291 		if (oflg)
1292 			if (!nflg) {
1293 				cp = getname(p->luid);
1294 				curcol += printf("%-8s ", cp);
1295 			} else
1296 				curcol += printf("%-8lu ", (ulong_t)p->luid);
1297 		if (gflg)
1298 			if (!nflg) {
1299 				cp = getgroup(p->lgid);
1300 				curcol += printf("%-8s ", cp);
1301 			} else
1302 				curcol += printf("%-8lu ", (ulong_t)p->lgid);
1303 		if (p->ltype == 'b' || p->ltype == 'c') {
1304 			curcol += printf("%3u, %2u",
1305 			    (uint_t)major((dev_t)p->lsize),
1306 			    (uint_t)minor((dev_t)p->lsize));
1307 		} else if (hflg && (p->lsize >= hscale)) {
1308 			curcol += printf("%7s",
1309 			    number_to_scaled_string(hbuf, p->lsize, hscale));
1310 		} else {
1311 			uint64_t bsize = p->lsize / block_size;
1312 
1313 			/*
1314 			 * Round up only when using blocks > 1 byte, otherwise
1315 			 * 'normal' sizes display 1 byte too large.
1316 			 */
1317 			if (p->lsize % block_size != 0)
1318 				bsize++;
1319 
1320 			curcol += printf("%7" PRIu64, bsize);
1321 		}
1322 		format_time(p->lmtime.tv_sec, p->lmtime.tv_nsec);
1323 		/* format extended system attribute time */
1324 		if (tmflg && crtm)
1325 			format_attrtime(p);
1326 
1327 		curcol += printf("%s", time_buf);
1328 
1329 	}
1330 	/*
1331 	 * prevent both "->" and trailing marks
1332 	 * from appearing
1333 	 */
1334 
1335 	if (pflg && p->ltype == 'd')
1336 		dmark = "/";
1337 
1338 	if (Fflg && !(lflg && p->flinkto)) {
1339 		if (p->ltype == 'd')
1340 			dmark = "/";
1341 		else if (p->ltype == 'D')
1342 			dmark = ">";
1343 		else if (p->ltype == 'p')
1344 			dmark = "|";
1345 		else if (p->ltype == 'l')
1346 			dmark = "@";
1347 		else if (p->ltype == 's')
1348 			dmark = "=";
1349 		else if (!file_typeflg &&
1350 		    (p->lflags & (S_IXUSR|S_IXGRP|S_IXOTH)))
1351 			dmark = "*";
1352 		else
1353 			dmark = "";
1354 	}
1355 
1356 	if (colorflg)
1357 		ls_start_color(p->color);
1358 
1359 	if (p->lflags & ISARG)
1360 		str = p->ln.namep;
1361 	else
1362 		str = p->ln.lname;
1363 
1364 	if (qflg || bflg) {
1365 		csi_pprintf((unsigned char *)str);
1366 
1367 		if (lflg && p->flinkto) {
1368 			if (colorflg)
1369 				ls_end_color();
1370 			csi_pprintf((unsigned char *)" -> ");
1371 			if (colorflg)
1372 				ls_start_color(p->link_color);
1373 			csi_pprintf((unsigned char *)p->flinkto);
1374 		} else {
1375 			csi_pprintf((unsigned char *)dmark);
1376 		}
1377 	} else {
1378 		(void) printf("%s", str);
1379 		curcol += strcol((unsigned char *)str);
1380 
1381 		if (lflg && p->flinkto) {
1382 			if (colorflg)
1383 				ls_end_color();
1384 			str = " -> ";
1385 			(void) printf("%s", str);
1386 			curcol += strcol((unsigned char *)str);
1387 			if (colorflg)
1388 				ls_start_color(p->link_color);
1389 			(void) printf("%s", p->flinkto);
1390 			curcol += strcol((unsigned char *)p->flinkto);
1391 		} else {
1392 			(void) printf("%s", dmark);
1393 			curcol += strcol((unsigned char *)dmark);
1394 		}
1395 	}
1396 
1397 	if (colorflg)
1398 		ls_end_color();
1399 
1400 	/* Display extended system attributes */
1401 	if (saflg) {
1402 		int i;
1403 
1404 		new_line();
1405 		(void) printf("	\t{");
1406 		if (p->exttr != NULL) {
1407 			int k = 0;
1408 			for (i = 0; i < sacnt; i++) {
1409 				if (p->exttr[i].name != NULL)
1410 					k++;
1411 			}
1412 			for (i = 0; i < sacnt; i++) {
1413 				if (p->exttr[i].name != NULL) {
1414 					(void) printf("%s", p->exttr[i].name);
1415 					k--;
1416 					if (vopt && (k != 0))
1417 						(void) printf(",");
1418 				}
1419 			}
1420 		}
1421 		(void) printf("}\n");
1422 	}
1423 	/* Display file timestamps and extended system attribute timestamps */
1424 	if (tmflg && alltm) {
1425 		new_line();
1426 		print_time(p);
1427 		new_line();
1428 	}
1429 	if (vflg) {
1430 		new_line();
1431 		if (p->aclp) {
1432 			acl_printacl(p->aclp, num_cols, Vflg);
1433 		}
1434 	}
1435 	/* Free extended system attribute lists */
1436 	if (saflg || tmflg)
1437 		free_sysattr(p);
1438 }
1439 
1440 /* print various r,w,x permissions */
1441 static void
1442 pmode(mode_t aflag)
1443 {
1444 	/* these arrays are declared static to allow initializations */
1445 	static int	m0[] = { 1, S_IRUSR, 'r', '-' };
1446 	static int	m1[] = { 1, S_IWUSR, 'w', '-' };
1447 	static int	m2[] = { 3, S_ISUID|S_IXUSR, 's', S_IXUSR,
1448 	    'x', S_ISUID, 'S', '-' };
1449 	static int	m3[] = { 1, S_IRGRP, 'r', '-' };
1450 	static int	m4[] = { 1, S_IWGRP, 'w', '-' };
1451 	static int	m5[] = { 4, S_ISGID|S_IXGRP, 's', S_IXGRP,
1452 				'x', S_ISGID|LS_NOTREG, 'S',
1453 #ifdef XPG4
1454 		S_ISGID, 'L', '-'};
1455 #else
1456 		S_ISGID, 'l', '-'};
1457 #endif
1458 	static int	m6[] = { 1, S_IROTH, 'r', '-' };
1459 	static int	m7[] = { 1, S_IWOTH, 'w', '-' };
1460 	static int	m8[] = { 3, S_ISVTX|S_IXOTH, 't', S_IXOTH,
1461 	    'x', S_ISVTX, 'T', '-'};
1462 
1463 	static int *m[] = { m0, m1, m2, m3, m4, m5, m6, m7, m8};
1464 
1465 	int **mp;
1466 
1467 	flags = aflag;
1468 	for (mp = &m[0]; mp < &m[sizeof (m) / sizeof (m[0])]; mp++)
1469 		selection(*mp);
1470 }
1471 
1472 static void
1473 selection(int *pairp)
1474 {
1475 	int n;
1476 
1477 	n = *pairp++;
1478 	while (n-->0) {
1479 		if ((flags & *pairp) == *pairp) {
1480 			pairp++;
1481 			break;
1482 		} else {
1483 			pairp += 2;
1484 		}
1485 	}
1486 	(void) putchar(*pairp);
1487 	curcol++;
1488 }
1489 
1490 /*
1491  * column: get to the beginning of the next column.
1492  */
1493 static void
1494 column(void)
1495 {
1496 	if (curcol == 0)
1497 		return;
1498 	if (mflg) {
1499 		(void) putc(',', stdout);
1500 		curcol++;
1501 		if (curcol + colwidth + 2 > num_cols) {
1502 			(void) putc('\n', stdout);
1503 			curcol = 0;
1504 			return;
1505 		}
1506 		(void) putc(' ', stdout);
1507 		curcol++;
1508 		return;
1509 	}
1510 	if (Cflg == 0) {
1511 		(void) putc('\n', stdout);
1512 		curcol = 0;
1513 		return;
1514 	}
1515 	if ((curcol / colwidth + 2) * colwidth > num_cols) {
1516 		(void) putc('\n', stdout);
1517 		curcol = 0;
1518 		return;
1519 	}
1520 	do {
1521 		(void) putc(' ', stdout);
1522 		curcol++;
1523 	} while (curcol % colwidth);
1524 }
1525 
1526 static void
1527 new_line(void)
1528 {
1529 	if (curcol) {
1530 		first = 0;
1531 		(void) putc('\n', stdout);
1532 		curcol = 0;
1533 	}
1534 }
1535 
1536 /*
1537  * read each filename in directory dir and store its
1538  * status in flist[nfiles]
1539  * use makename() to form pathname dir/filename;
1540  */
1541 static void
1542 rddir(char *dir, struct ditem *myinfo)
1543 {
1544 	struct dirent *dentry;
1545 	DIR *dirf;
1546 	int j;
1547 	struct lbuf *ep;
1548 	int width;
1549 
1550 	if ((dirf = opendir(dir)) == NULL) {
1551 		(void) fflush(stdout);
1552 		perror(dir);
1553 		err = 2;
1554 		return;
1555 	} else {
1556 		tblocks = 0;
1557 		for (;;) {
1558 			errno = 0;
1559 			if ((dentry = readdir(dirf)) == NULL)
1560 				break;
1561 			if (aflg == 0 && dentry->d_name[0] == '.' &&
1562 			    (Aflg == 0 ||
1563 			    dentry->d_name[1] == '\0' ||
1564 			    dentry->d_name[1] == '.' &&
1565 			    dentry->d_name[2] == '\0'))
1566 				/*
1567 				 * check for directory items '.', '..',
1568 				 *  and items without valid inode-number;
1569 				 */
1570 				continue;
1571 
1572 			/* skip entries ending in ~ if -B was given */
1573 			if (Bflg &&
1574 			    dentry->d_name[strlen(dentry->d_name) - 1] == '~')
1575 				continue;
1576 			if (Cflg || mflg) {
1577 				width = strcol((unsigned char *)dentry->d_name);
1578 				if (width > filewidth)
1579 					filewidth = width;
1580 			}
1581 			ep = gstat(makename(dir, dentry->d_name), 0, myinfo);
1582 			if (ep == NULL) {
1583 				if (nomocore)
1584 					exit(2);
1585 				continue;
1586 			} else {
1587 				ep->lnum = dentry->d_ino;
1588 				for (j = 0; dentry->d_name[j] != '\0'; j++)
1589 					ep->ln.lname[j] = dentry->d_name[j];
1590 				ep->ln.lname[j] = '\0';
1591 
1592 				/*
1593 				 * Since this entry doesn't need to be sorted
1594 				 * or further processed, print it right away.
1595 				 */
1596 				if (noflist) {
1597 					pem(&ep, &ep + 1, 0);
1598 					nfiles--;
1599 				}
1600 			}
1601 		}
1602 		if (errno) {
1603 			int sav_errno = errno;
1604 
1605 			(void) fprintf(stderr,
1606 			    gettext("ls: error reading directory %s: %s\n"),
1607 			    dir, strerror(sav_errno));
1608 		}
1609 		(void) closedir(dirf);
1610 		colwidth = fixedwidth + filewidth;
1611 	}
1612 }
1613 
1614 /*
1615  * Attaching a link to an inode's ancestors.  Search
1616  * through the ancestors to check for cycles (an inode which
1617  * we have already tracked in this inodes ancestry).  If a cycle
1618  * is detected, set the exit code and record the fact so that
1619  * it is reported at the right time when printing the directory.
1620  * In addition, set the exit code.  Note:  If the -a flag was
1621  * specified, we don't want to check for cycles for directories
1622  * ending in '/.' or '/..' unless they were specified on the
1623  * command line.
1624  */
1625 static void
1626 record_ancestry(char *file, struct stat *pstatb, struct lbuf *rep,
1627     int argfl, struct ditem *myparent)
1628 {
1629 	size_t		file_len;
1630 	struct ditem	*myinfo;
1631 	struct ditem	*tptr;
1632 
1633 	file_len = strlen(file);
1634 	if (!aflg || argfl || (NOTWORKINGDIR(file, file_len) &&
1635 	    NOTPARENTDIR(file, file_len))) {
1636 		/*
1637 		 * Add this inode's ancestry
1638 		 * info and insert it into the
1639 		 * ancestry list by pointing
1640 		 * back to its parent.  We save
1641 		 * it (in rep) with the other info
1642 		 * we're gathering for this inode.
1643 		 */
1644 		if ((myinfo = malloc(
1645 		    sizeof (struct ditem))) == NULL) {
1646 			perror("ls");
1647 			exit(2);
1648 		}
1649 		myinfo->dev = pstatb->st_dev;
1650 		myinfo->ino = pstatb->st_ino;
1651 		myinfo->parent = myparent;
1652 		rep->ancinfo = myinfo;
1653 
1654 		/*
1655 		 * If this node has the same device id and
1656 		 * inode number of one of its ancestors,
1657 		 * then we've detected a cycle.
1658 		 */
1659 		if (myparent != NULL) {
1660 			for (tptr = myparent; tptr->parent != NULL;
1661 			    tptr = tptr->parent) {
1662 				if ((tptr->dev == pstatb->st_dev) &&
1663 				    (tptr->ino == pstatb->st_ino)) {
1664 					/*
1665 					 * Cycle detected for this
1666 					 * directory.  Record the fact
1667 					 * it is a cycle so we don't
1668 					 * try to process this
1669 					 * directory as we are
1670 					 * walking through the
1671 					 * list of directories.
1672 					 */
1673 					rep->cycle = 1;
1674 					err = 2;
1675 					break;
1676 				}
1677 			}
1678 		}
1679 	}
1680 }
1681 
1682 /*
1683  * Do re-calculate the mode for group for ACE_T type of acls.
1684  * This is because, if the server's FS happens to be UFS, supporting
1685  * POSIX ACL's, then it does a special calculation of group mode
1686  * to be the bitwise OR of CLASS_OBJ and GROUP_OBJ (see PSARC/2001/717.)
1687  *
1688  * This algorithm is from the NFSv4 ACL Draft. Here a part of that
1689  * algorithm is used for the group mode calculation only.
1690  * What is modified here from the algorithm is that only the
1691  * entries with flags ACE_GROUP are considered. For each entry
1692  * with ACE_GROUP flag, the first occurance of a specific access
1693  * is checked if it is allowed.
1694  * We are not interested in perms for user and other, as they
1695  * were taken from st_mode value.
1696  * We are not interested in a_who field of ACE, as we need just
1697  * unix mode bits for the group.
1698  */
1699 
1700 #define	OWNED_GROUP	(ACE_GROUP | ACE_IDENTIFIER_GROUP)
1701 #define	IS_TYPE_ALLOWED(type)	((type) == ACE_ACCESS_ALLOWED_ACE_TYPE)
1702 
1703 int
1704 grp_mask_to_mode(struct lbuf *p)
1705 {
1706 	int mode = 0, seen = 0;
1707 	int acecnt;
1708 	int flags;
1709 	ace_t *ap;
1710 	acl_t *acep = p->aclp;
1711 
1712 	acecnt = acl_cnt(acep);
1713 	for (ap = (ace_t *)acl_data(acep); acecnt--; ap++) {
1714 
1715 		if (ap->a_type != ACE_ACCESS_ALLOWED_ACE_TYPE &&
1716 		    ap->a_type != ACE_ACCESS_DENIED_ACE_TYPE)
1717 			continue;
1718 
1719 		if (ap->a_flags & ACE_INHERIT_ONLY_ACE)
1720 			continue;
1721 
1722 		/*
1723 		 * if it is first group@ or first everyone@
1724 		 * for each of read, write and execute, then
1725 		 * that will be the group mode bit.
1726 		 */
1727 		flags = ap->a_flags & ACE_TYPE_FLAGS;
1728 		if (flags == OWNED_GROUP || (flags == ACE_IDENTIFIER_GROUP &&
1729 		    ap->a_who == p->lgid) || flags == ACE_EVERYONE) {
1730 			if (ap->a_access_mask & ACE_READ_DATA) {
1731 				if (!(seen & S_IRGRP)) {
1732 					seen |= S_IRGRP;
1733 					if (IS_TYPE_ALLOWED(ap->a_type))
1734 						mode |= S_IRGRP;
1735 				}
1736 			}
1737 			if (ap->a_access_mask & ACE_WRITE_DATA) {
1738 				if (!(seen & S_IWGRP)) {
1739 					seen |= S_IWGRP;
1740 					if (IS_TYPE_ALLOWED(ap->a_type))
1741 						mode |= S_IWGRP;
1742 				}
1743 			}
1744 			if (ap->a_access_mask & ACE_EXECUTE) {
1745 				if (!(seen & S_IXGRP)) {
1746 					seen |= S_IXGRP;
1747 					if (IS_TYPE_ALLOWED(ap->a_type))
1748 						mode |= S_IXGRP;
1749 				}
1750 			}
1751 		}
1752 	}
1753 	return (mode);
1754 }
1755 
1756 /*
1757  * get status of file and recomputes tblocks;
1758  * argfl = 1 if file is a name in ls-command and = 0
1759  * for filename in a directory whose name is an
1760  * argument in the command;
1761  * stores a pointer in flist[nfiles] and
1762  * returns that pointer;
1763  * returns NULL if failed;
1764  */
1765 static struct lbuf *
1766 gstat(char *file, int argfl, struct ditem *myparent)
1767 {
1768 	struct stat statb, statb1;
1769 	struct lbuf *rep;
1770 	char buf[BUFSIZ];
1771 	ssize_t cc;
1772 	int (*statf)() = ((Lflg) || (Hflg && argfl)) ? stat : lstat;
1773 	int aclcnt;
1774 	int error;
1775 	aclent_t *tp;
1776 	o_mode_t groupperm, mask;
1777 	int grouppermfound, maskfound;
1778 
1779 	if (nomocore)
1780 		return (NULL);
1781 
1782 	if (nfiles >= maxfils) {
1783 		/*
1784 		 * all flist/lbuf pair assigned files, time to get some
1785 		 * more space
1786 		 */
1787 		maxfils += quantn;
1788 		if (((flist = realloc(flist,
1789 		    maxfils * sizeof (struct lbuf *))) == NULL) ||
1790 		    ((nxtlbf = malloc(quantn *
1791 		    sizeof (struct lbuf))) == NULL)) {
1792 			perror("ls");
1793 			nomocore = 1;
1794 			return (NULL);
1795 		}
1796 	}
1797 
1798 	/*
1799 	 * nfiles is reset to nargs for each directory
1800 	 * that is given as an argument maxn is checked
1801 	 * to prevent the assignment of an lbuf to a flist entry
1802 	 * that already has one assigned.
1803 	 */
1804 	if (nfiles >= maxn) {
1805 		rep = nxtlbf++;
1806 		flist[nfiles++] = rep;
1807 		maxn = nfiles;
1808 	} else {
1809 		rep = flist[nfiles++];
1810 	}
1811 
1812 	/*
1813 	 * When noflist is set, none of the extra information about the dirent
1814 	 * will be printed, so omit initialization of this lbuf as well as the
1815 	 * stat(2) call.
1816 	 */
1817 	if (!argfl && noflist)
1818 		return (rep);
1819 
1820 	/* Initialize */
1821 
1822 	rep->lflags = (mode_t)0;
1823 	rep->flinkto = NULL;
1824 	rep->cycle = 0;
1825 	rep->lat.tv_sec = time(NULL);
1826 	rep->lat.tv_nsec = 0;
1827 	rep->lct.tv_sec = time(NULL);
1828 	rep->lct.tv_nsec = 0;
1829 	rep->lmt.tv_sec = time(NULL);
1830 	rep->lmt.tv_nsec = 0;
1831 	rep->aclp = NULL;
1832 	rep->exttr = NULL;
1833 	rep->extm = NULL;
1834 	rep->color = NULL;
1835 	rep->link_color = NULL;
1836 
1837 	if (argfl || statreq) {
1838 		int doacl;
1839 
1840 		if (lflg)
1841 			doacl = 1;
1842 		else
1843 			doacl = 0;
1844 
1845 		if ((*statf)(file, &statb) < 0) {
1846 			if (argfl || errno != ENOENT ||
1847 			    (Lflg && lstat(file, &statb) == 0)) {
1848 				/*
1849 				 * Avoid race between readdir and lstat.
1850 				 * Print error message in case of dangling link.
1851 				 */
1852 				perror(file);
1853 				err = 2;
1854 			}
1855 			nfiles--;
1856 			return (NULL);
1857 		}
1858 
1859 		/*
1860 		 * If -H was specified, and the file linked to was
1861 		 * not a directory, then we need to get the info
1862 		 * for the symlink itself.
1863 		 */
1864 		if ((Hflg) && (argfl) &&
1865 		    ((statb.st_mode & S_IFMT) != S_IFDIR)) {
1866 			if (lstat(file, &statb) < 0) {
1867 				perror(file);
1868 				err = 2;
1869 			}
1870 		}
1871 
1872 		rep->lnum = statb.st_ino;
1873 		rep->lsize = statb.st_size;
1874 		rep->lblocks = statb.st_blocks;
1875 		if (colorflg)
1876 			rep->color = ls_color_find(file, statb.st_mode);
1877 
1878 		switch (statb.st_mode & S_IFMT) {
1879 		case S_IFDIR:
1880 			rep->ltype = 'd';
1881 			if (Rflg) {
1882 				record_ancestry(file, &statb, rep,
1883 				    argfl, myparent);
1884 			}
1885 			break;
1886 		case S_IFBLK:
1887 			rep->ltype = 'b';
1888 			rep->lsize = (off_t)statb.st_rdev;
1889 			break;
1890 		case S_IFCHR:
1891 			rep->ltype = 'c';
1892 			rep->lsize = (off_t)statb.st_rdev;
1893 			break;
1894 		case S_IFIFO:
1895 			rep->ltype = 'p';
1896 			break;
1897 		case S_IFSOCK:
1898 			rep->ltype = 's';
1899 			rep->lsize = 0;
1900 			break;
1901 		case S_IFLNK:
1902 			/* symbolic links may not have ACLs, so elide acl() */
1903 			if ((Lflg == 0) || (Hflg == 0) ||
1904 			    ((Hflg) && (!argfl))) {
1905 				doacl = 0;
1906 			}
1907 			rep->ltype = 'l';
1908 			if (lflg || colorflg) {
1909 				cc = readlink(file, buf, BUFSIZ);
1910 				if (cc < 0)
1911 					break;
1912 
1913 				/*
1914 				 * follow the symbolic link
1915 				 * to generate the appropriate
1916 				 * Fflg marker for the object
1917 				 * eg, /bin -> /sym/bin/
1918 				 */
1919 				error = 0;
1920 				if (Fflg || pflg || colorflg)
1921 					error = stat(file, &statb1);
1922 
1923 				if (colorflg) {
1924 					if (error >= 0)
1925 						rep->link_color =
1926 						    ls_color_find(file,
1927 						    statb1.st_mode);
1928 					else
1929 						rep->link_color =
1930 						    lsc_orphan;
1931 				}
1932 
1933 				if ((Fflg || pflg) && error >= 0) {
1934 					switch (statb1.st_mode & S_IFMT) {
1935 					case S_IFDIR:
1936 						buf[cc++] = '/';
1937 						break;
1938 					case S_IFSOCK:
1939 						buf[cc++] = '=';
1940 						break;
1941 					case S_IFDOOR:
1942 						buf[cc++] = '>';
1943 						break;
1944 					case S_IFIFO:
1945 						buf[cc++] = '|';
1946 						break;
1947 					default:
1948 						if ((statb1.st_mode & ~S_IFMT) &
1949 						    (S_IXUSR|S_IXGRP| S_IXOTH))
1950 							buf[cc++] = '*';
1951 						break;
1952 					}
1953 				}
1954 				buf[cc] = '\0';
1955 				rep->flinkto = strdup(buf);
1956 				if (rep->flinkto == NULL) {
1957 					perror("ls");
1958 					nomocore = 1;
1959 					return (NULL);
1960 				}
1961 				break;
1962 			}
1963 
1964 			/*
1965 			 * ls /sym behaves differently from ls /sym/
1966 			 * when /sym is a symbolic link. This is fixed
1967 			 * when explicit arguments are specified.
1968 			 */
1969 
1970 #ifdef XPG6
1971 			/* Do not follow a symlink when -F is specified */
1972 			if ((!argfl) || (argfl && Fflg) ||
1973 			    (stat(file, &statb1) < 0))
1974 #else
1975 			/* Follow a symlink when -F is specified */
1976 			if (!argfl || stat(file, &statb1) < 0)
1977 #endif /* XPG6 */
1978 				break;
1979 			if ((statb1.st_mode & S_IFMT) == S_IFDIR) {
1980 				statb = statb1;
1981 				rep->ltype = 'd';
1982 				rep->lsize = statb1.st_size;
1983 				if (Rflg) {
1984 					record_ancestry(file, &statb, rep,
1985 					    argfl, myparent);
1986 				}
1987 			}
1988 			break;
1989 		case S_IFDOOR:
1990 			rep->ltype = 'D';
1991 			break;
1992 		case S_IFREG:
1993 			rep->ltype = '-';
1994 			break;
1995 		case S_IFPORT:
1996 			rep->ltype = 'P';
1997 			break;
1998 		default:
1999 			rep->ltype = '?';
2000 			break;
2001 		}
2002 		rep->lflags = statb.st_mode & ~S_IFMT;
2003 
2004 		if (!S_ISREG(statb.st_mode))
2005 			rep->lflags |= LS_NOTREG;
2006 
2007 		rep->luid = statb.st_uid;
2008 		rep->lgid = statb.st_gid;
2009 		rep->lnl = statb.st_nlink;
2010 		if (uflg || (tmflg && atm))
2011 			rep->lmtime = statb.st_atim;
2012 		else if (cflg || (tmflg && ctm))
2013 			rep->lmtime = statb.st_ctim;
2014 		else
2015 			rep->lmtime = statb.st_mtim;
2016 		rep->lat = statb.st_atim;
2017 		rep->lct = statb.st_ctim;
2018 		rep->lmt = statb.st_mtim;
2019 
2020 		/* ACL: check acl entries count */
2021 		if (doacl) {
2022 
2023 			error = acl_get(file, 0, &rep->aclp);
2024 			if (error) {
2025 				(void) fprintf(stderr,
2026 				    gettext("ls: can't read ACL on %s: %s\n"),
2027 				    file, acl_strerror(error));
2028 				rep->acl = ' ';
2029 				acl_err++;
2030 				return (rep);
2031 			}
2032 
2033 			rep->acl = ' ';
2034 
2035 			if (rep->aclp &&
2036 			    ((acl_flags(rep->aclp) & ACL_IS_TRIVIAL) == 0)) {
2037 				rep->acl = '+';
2038 				/*
2039 				 * Special handling for ufs aka aclent_t ACL's
2040 				 */
2041 				if (acl_type(rep->aclp) == ACLENT_T) {
2042 					/*
2043 					 * For files with non-trivial acls, the
2044 					 * effective group permissions are the
2045 					 * intersection of the GROUP_OBJ value
2046 					 * and the CLASS_OBJ (acl mask) value.
2047 					 * Determine both the GROUP_OBJ and
2048 					 * CLASS_OBJ for this file and insert
2049 					 * the logical AND of those two values
2050 					 * in the group permissions field
2051 					 * of the lflags value for this file.
2052 					 */
2053 
2054 					/*
2055 					 * Until found in acl list, assume
2056 					 * maximum permissions for both group
2057 					 * a nd mask.  (Just in case the acl
2058 					 * lacks either value for some reason.)
2059 					 */
2060 					groupperm = 07;
2061 					mask = 07;
2062 					grouppermfound = 0;
2063 					maskfound = 0;
2064 					aclcnt = acl_cnt(rep->aclp);
2065 					for (tp =
2066 					    (aclent_t *)acl_data(rep->aclp);
2067 					    aclcnt--; tp++) {
2068 						if (tp->a_type == GROUP_OBJ) {
2069 							groupperm = tp->a_perm;
2070 							grouppermfound = 1;
2071 							continue;
2072 						}
2073 						if (tp->a_type == CLASS_OBJ) {
2074 							mask = tp->a_perm;
2075 							maskfound = 1;
2076 						}
2077 						if (grouppermfound && maskfound)
2078 							break;
2079 					}
2080 
2081 
2082 					/* reset all the group bits */
2083 					rep->lflags &= ~S_IRWXG;
2084 
2085 					/*
2086 					 * Now set them to the logical AND of
2087 					 * the GROUP_OBJ permissions and the
2088 					 * acl mask.
2089 					 */
2090 
2091 					rep->lflags |= (groupperm & mask) << 3;
2092 
2093 				} else if (acl_type(rep->aclp) == ACE_T) {
2094 					int mode;
2095 					mode = grp_mask_to_mode(rep);
2096 					rep->lflags &= ~S_IRWXG;
2097 					rep->lflags |= mode;
2098 				}
2099 			}
2100 
2101 			if (!vflg && !Vflg && rep->aclp) {
2102 				acl_free(rep->aclp);
2103 				rep->aclp = NULL;
2104 			}
2105 
2106 			if (atflg && pathconf(file, _PC_XATTR_EXISTS) == 1)
2107 				rep->acl = '@';
2108 
2109 		} else
2110 			rep->acl = ' ';
2111 
2112 		/* mask ISARG and other file-type bits */
2113 
2114 		if (rep->ltype != 'b' && rep->ltype != 'c')
2115 			tblocks += rep->lblocks;
2116 
2117 		/* Get extended system attributes */
2118 
2119 		if ((saflg || (tmflg && crtm) || (tmflg && alltm)) &&
2120 		    (sysattr_support(file, _PC_SATTR_EXISTS) == 1)) {
2121 			int i;
2122 
2123 			sacnt = attr_count();
2124 			/*
2125 			 * Allocate 'sacnt' size array to hold extended
2126 			 * system attribute name (verbose) or respective
2127 			 * symbol represenation (compact).
2128 			 */
2129 			rep->exttr = xmalloc(sacnt * sizeof (struct attrb),
2130 			    rep);
2131 
2132 			/* initialize boolean attribute list */
2133 			for (i = 0; i < sacnt; i++)
2134 				rep->exttr[i].name = NULL;
2135 			if (get_sysxattr(file, rep) != 0) {
2136 				(void) fprintf(stderr,
2137 				    gettext("ls:Failed to retrieve "
2138 				    "extended system attribute from "
2139 				    "%s\n"), file);
2140 				rep->exttr[0].name = xmalloc(2, rep);
2141 				(void) strlcpy(rep->exttr[0].name, "?", 2);
2142 			}
2143 		}
2144 	}
2145 	return (rep);
2146 }
2147 
2148 /*
2149  * returns pathname of the form dir/file;
2150  * dir and file are null-terminated strings.
2151  */
2152 static char *
2153 makename(char *dir, char *file)
2154 {
2155 	/*
2156 	 * PATH_MAX is the maximum length of a path name.
2157 	 * MAXNAMLEN is the maximum length of any path name component.
2158 	 * Allocate space for both, plus the '/' in the middle
2159 	 * and the null character at the end.
2160 	 * dfile is static as this is returned by makename().
2161 	 */
2162 	static char dfile[PATH_MAX + 1 + MAXNAMLEN + 1];
2163 	char *dp, *fp;
2164 
2165 	dp = dfile;
2166 	fp = dir;
2167 	while (*fp)
2168 		*dp++ = *fp++;
2169 	if (dp > dfile && *(dp - 1) != '/')
2170 		*dp++ = '/';
2171 	fp = file;
2172 	while (*fp)
2173 		*dp++ = *fp++;
2174 	*dp = '\0';
2175 	return (dfile);
2176 }
2177 
2178 
2179 #include <pwd.h>
2180 #include <grp.h>
2181 #include <utmpx.h>
2182 
2183 struct	utmpx utmp;
2184 
2185 #define	NMAX	(sizeof (utmp.ut_name))
2186 #define	SCPYN(a, b)	(void) strncpy(a, b, NMAX)
2187 
2188 
2189 struct cachenode {		/* this struct must be zeroed before using */
2190 	struct cachenode *lesschild;	/* subtree whose entries < val */
2191 	struct cachenode *grtrchild;	/* subtree whose entries > val */
2192 	long val;			/* the uid or gid of this entry */
2193 	int initted;			/* name has been filled in */
2194 	char name[NMAX+1];		/* the string that val maps to */
2195 };
2196 static struct cachenode *names, *groups;
2197 
2198 static struct cachenode *
2199 findincache(struct cachenode **head, long val)
2200 {
2201 	struct cachenode **parent = head;
2202 	struct cachenode *c = *parent;
2203 
2204 	while (c != NULL) {
2205 		if (val == c->val) {
2206 			/* found it */
2207 			return (c);
2208 		} else if (val < c->val) {
2209 			parent = &c->lesschild;
2210 			c = c->lesschild;
2211 		} else {
2212 			parent = &c->grtrchild;
2213 			c = c->grtrchild;
2214 		}
2215 	}
2216 
2217 	/* not in the cache, make a new entry for it */
2218 	c = calloc(1, sizeof (struct cachenode));
2219 	if (c == NULL) {
2220 		perror("ls");
2221 		exit(2);
2222 	}
2223 	*parent = c;
2224 	c->val = val;
2225 	return (c);
2226 }
2227 
2228 /*
2229  * get name from cache, or passwd file for a given uid;
2230  * lastuid is set to uid.
2231  */
2232 static char *
2233 getname(uid_t uid)
2234 {
2235 	struct passwd *pwent;
2236 	struct cachenode *c;
2237 
2238 	if ((uid == lastuid) && lastuname)
2239 		return (lastuname);
2240 
2241 	c = findincache(&names, uid);
2242 	if (c->initted == 0) {
2243 		if ((pwent = getpwuid(uid)) != NULL) {
2244 			SCPYN(&c->name[0], pwent->pw_name);
2245 		} else {
2246 			(void) sprintf(&c->name[0], "%-8u", (int)uid);
2247 		}
2248 		c->initted = 1;
2249 	}
2250 	lastuid = uid;
2251 	lastuname = &c->name[0];
2252 	return (lastuname);
2253 }
2254 
2255 /*
2256  * get name from cache, or group file for a given gid;
2257  * lastgid is set to gid.
2258  */
2259 static char *
2260 getgroup(gid_t gid)
2261 {
2262 	struct group *grent;
2263 	struct cachenode *c;
2264 
2265 	if ((gid == lastgid) && lastgname)
2266 		return (lastgname);
2267 
2268 	c = findincache(&groups, gid);
2269 	if (c->initted == 0) {
2270 		if ((grent = getgrgid(gid)) != NULL) {
2271 			SCPYN(&c->name[0], grent->gr_name);
2272 		} else {
2273 			(void) sprintf(&c->name[0], "%-8u", (int)gid);
2274 		}
2275 		c->initted = 1;
2276 	}
2277 	lastgid = gid;
2278 	lastgname = &c->name[0];
2279 	return (lastgname);
2280 }
2281 
2282 /* return >0 if item pointed by pp2 should appear first */
2283 static int
2284 compar(struct lbuf **pp1, struct lbuf **pp2)
2285 {
2286 	struct lbuf *p1, *p2;
2287 
2288 	p1 = *pp1;
2289 	p2 = *pp2;
2290 	if (dflg == 0) {
2291 /*
2292  * compare two names in ls-command one of which is file
2293  * and the other is a directory;
2294  * this portion is not used for comparing files within
2295  * a directory name of ls-command;
2296  */
2297 		if (p1->lflags&ISARG && p1->ltype == 'd') {
2298 			if (!(p2->lflags&ISARG && p2->ltype == 'd'))
2299 				return (1);
2300 		} else {
2301 			if (p2->lflags&ISARG && p2->ltype == 'd')
2302 				return (-1);
2303 		}
2304 	}
2305 	if (tflg) {
2306 		if (p2->lmtime.tv_sec > p1->lmtime.tv_sec)
2307 			return (rflg);
2308 		else if (p2->lmtime.tv_sec < p1->lmtime.tv_sec)
2309 			return (-rflg);
2310 		/* times are equal to the sec, check nsec */
2311 		if (p2->lmtime.tv_nsec > p1->lmtime.tv_nsec)
2312 			return (rflg);
2313 		else if (p2->lmtime.tv_nsec < p1->lmtime.tv_nsec)
2314 			return (-rflg);
2315 		/* if times are equal, fall through and sort by name */
2316 	} else if (Sflg) {
2317 		/*
2318 		 * The size stored in lsize can be either the
2319 		 * size or the major minor number (in the case of
2320 		 * block and character special devices).  If it's
2321 		 * a major minor number, then the size is considered
2322 		 * to be zero and we want to fall through and sort
2323 		 * by name.  In addition, if the size of p2 is equal
2324 		 * to the size of p1 we want to fall through and
2325 		 * sort by name.
2326 		 */
2327 		off_t	p1size = (p1->ltype == 'b') ||
2328 		    (p1->ltype == 'c') ? 0 : p1->lsize;
2329 		off_t	p2size = (p2->ltype == 'b') ||
2330 		    (p2->ltype == 'c') ? 0 : p2->lsize;
2331 		if (p2size > p1size) {
2332 			return (rflg);
2333 		} else if (p2size < p1size) {
2334 			return (-rflg);
2335 		}
2336 		/* Sizes are equal, fall through and sort by name. */
2337 	}
2338 	return (rflg * strcoll(
2339 	    p1->lflags & ISARG ? p1->ln.namep : p1->ln.lname,
2340 	    p2->lflags&ISARG ? p2->ln.namep : p2->ln.lname));
2341 }
2342 
2343 static void
2344 pprintf(char *s1, char *s2)
2345 {
2346 	csi_pprintf((unsigned char *)s1);
2347 	csi_pprintf((unsigned char *)s2);
2348 }
2349 
2350 static void
2351 csi_pprintf(unsigned char *s)
2352 {
2353 	unsigned char *cp;
2354 	char	c;
2355 	int	i;
2356 	int	c_len;
2357 	int	p_col;
2358 	wchar_t	pcode;
2359 
2360 	if (!qflg && !bflg) {
2361 		for (cp = s; *cp != '\0'; cp++) {
2362 			(void) putchar(*cp);
2363 			curcol++;
2364 		}
2365 		return;
2366 	}
2367 
2368 	for (cp = s; *cp; ) {
2369 		if (isascii(c = *cp)) {
2370 			if (!isprint(c)) {
2371 				if (qflg) {
2372 					c = '?';
2373 				} else {
2374 					curcol += 3;
2375 					(void) putc('\\', stdout);
2376 					c = '0' + ((*cp >> 6) & 07);
2377 					(void) putc(c, stdout);
2378 					c = '0' + ((*cp >> 3) & 07);
2379 					(void) putc(c, stdout);
2380 					c = '0' + (*cp & 07);
2381 				}
2382 			}
2383 			curcol++;
2384 			cp++;
2385 			(void) putc(c, stdout);
2386 			continue;
2387 		}
2388 
2389 		if ((c_len = mbtowc(&pcode, (char *)cp, MB_LEN_MAX)) <= 0) {
2390 			c_len = 1;
2391 			goto not_print;
2392 		}
2393 
2394 		if ((p_col = wcwidth(pcode)) > 0) {
2395 			(void) putwchar(pcode);
2396 			cp += c_len;
2397 			curcol += p_col;
2398 			continue;
2399 		}
2400 
2401 not_print:
2402 		for (i = 0; i < c_len; i++) {
2403 			if (qflg) {
2404 				c = '?';
2405 			} else {
2406 				curcol += 3;
2407 				(void) putc('\\', stdout);
2408 				c = '0' + ((*cp >> 6) & 07);
2409 				(void) putc(c, stdout);
2410 				c = '0' + ((*cp >> 3) & 07);
2411 				(void) putc(c, stdout);
2412 				c = '0' + (*cp & 07);
2413 			}
2414 			curcol++;
2415 			(void) putc(c, stdout);
2416 			cp++;
2417 		}
2418 	}
2419 }
2420 
2421 static int
2422 strcol(unsigned char *s1)
2423 {
2424 	int	w;
2425 	int	w_col;
2426 	int	len;
2427 	wchar_t	wc;
2428 
2429 	w = 0;
2430 	while (*s1) {
2431 		if (isascii(*s1)) {
2432 			w++;
2433 			s1++;
2434 			continue;
2435 		}
2436 
2437 		if ((len = mbtowc(&wc, (char *)s1, MB_LEN_MAX)) <= 0) {
2438 			w++;
2439 			s1++;
2440 			continue;
2441 		}
2442 
2443 		if ((w_col = wcwidth(wc)) < 0)
2444 			w_col = len;
2445 		s1 += len;
2446 		w += w_col;
2447 	}
2448 	return (w);
2449 }
2450 
2451 /*
2452  * Convert an unsigned long long to a string representation and place the
2453  * result in the caller-supplied buffer.
2454  *
2455  * The number provided is a size in bytes.  The number is first
2456  * converted to an integral multiple of 'scale' bytes.  This new
2457  * number is then scaled down until it is small enough to be in a good
2458  * human readable format, i.e.  in the range 0 thru scale-1.  If the
2459  * number used to derive the final number is not a multiple of scale, and
2460  * the final number has only a single significant digit, we compute
2461  * tenths of units to provide a second significant digit.
2462  *
2463  * The value "(unsigned long long)-1" is a special case and is always
2464  * converted to "-1".
2465  *
2466  * A pointer to the caller-supplied buffer is returned.
2467  */
2468 static char *
2469 number_to_scaled_string(
2470 			numbuf_t buf,		/* put the result here */
2471 			unsigned long long number, /* convert this number */
2472 			long scale)
2473 {
2474 	unsigned long long save;
2475 	/* Measurement: kilo, mega, giga, tera, peta, exa */
2476 	char *uom = "KMGTPE";
2477 
2478 	if ((long long)number == (long long)-1) {
2479 		(void) strlcpy(buf, "-1", sizeof (numbuf_t));
2480 		return (buf);
2481 	}
2482 
2483 	save = number;
2484 	number = number / scale;
2485 
2486 	/*
2487 	 * Now we have number as a count of scale units.
2488 	 * If no further scaling is necessary, we round up as appropriate.
2489 	 *
2490 	 * The largest value number could have had entering the routine is
2491 	 * 16 Exabytes, so running off the end of the uom array should
2492 	 * never happen.  We check for that, though, as a guard against
2493 	 * a breakdown elsewhere in the algorithm.
2494 	 */
2495 	if (number < (unsigned long long)scale) {
2496 		if ((save % scale) >= (unsigned long long)(scale / 2)) {
2497 			if (++number == (unsigned long long)scale) {
2498 				uom++;
2499 				number = 1;
2500 			}
2501 		}
2502 	} else {
2503 		while ((number >= (unsigned long long)scale) && (*uom != 'E')) {
2504 			uom++; /* next unit of measurement */
2505 			save = number;
2506 			/*
2507 			 * If we're over half way to the next unit of
2508 			 * 'scale' bytes (which means we should round
2509 			 * up), then adding half of 'scale' prior to
2510 			 * the division will push us into that next
2511 			 * unit of scale when we perform the division
2512 			 */
2513 			number = (number + (scale / 2)) / scale;
2514 		}
2515 	}
2516 
2517 	/* check if we should output a decimal place after the point */
2518 	if ((save / scale) < 10) {
2519 		/* snprintf() will round for us */
2520 		float fnum = (float)save / scale;
2521 		(void) snprintf(buf, sizeof (numbuf_t), "%2.1f%c",
2522 		    fnum, *uom);
2523 	} else {
2524 		(void) snprintf(buf, sizeof (numbuf_t), "%4llu%c",
2525 		    number, *uom);
2526 	}
2527 	return (buf);
2528 }
2529 
2530 /* Get extended system attributes and set the display */
2531 
2532 int
2533 get_sysxattr(char *fname, struct lbuf *rep)
2534 {
2535 	boolean_t	value;
2536 	data_type_t	type;
2537 	int		error;
2538 	char		*name;
2539 	int		i;
2540 
2541 	if ((error = getattrat(AT_FDCWD, XATTR_VIEW_READWRITE, fname,
2542 	    &response)) != 0) {
2543 		perror("ls:getattrat");
2544 		return (error);
2545 	}
2546 
2547 	/*
2548 	 * Allocate 'sacnt' size array to hold extended timestamp
2549 	 * system attributes and initialize the array.
2550 	 */
2551 	rep->extm = xmalloc(sacnt * sizeof (struct attrtm), rep);
2552 	for (i = 0; i < sacnt; i++) {
2553 		rep->extm[i].stm = 0;
2554 		rep->extm[i].nstm = 0;
2555 		rep->extm[i].name = NULL;
2556 	}
2557 	while ((pair = nvlist_next_nvpair(response, pair)) != NULL) {
2558 		name = nvpair_name(pair);
2559 		type = nvpair_type(pair);
2560 		if (type == DATA_TYPE_BOOLEAN_VALUE) {
2561 			error = nvpair_value_boolean_value(pair, &value);
2562 			if (error) {
2563 				(void) fprintf(stderr,
2564 				    gettext("nvpair_value_boolean_value "
2565 				    "failed: error = %d\n"), error);
2566 				continue;
2567 			}
2568 			if (name != NULL)
2569 				set_sysattrb_display(name, value, rep);
2570 			continue;
2571 		} else if (type == DATA_TYPE_UINT64_ARRAY) {
2572 			if (name != NULL)
2573 				set_sysattrtm_display(name, rep);
2574 			continue;
2575 		}
2576 	}
2577 	nvlist_free(response);
2578 	return (0);
2579 }
2580 
2581 /* Set extended system attribute boolean display */
2582 
2583 void
2584 set_sysattrb_display(char *name, boolean_t val, struct lbuf *rep)
2585 {
2586 	f_attr_t	fattr;
2587 	const char	*opt;
2588 	size_t		len;
2589 
2590 	fattr = name_to_attr(name);
2591 	if (fattr != F_ATTR_INVAL && fattr < sacnt) {
2592 		if (vopt) {
2593 			len = strlen(name);
2594 			if (val) {
2595 				rep->exttr[fattr].name = xmalloc(len + 1, rep);
2596 				(void) strlcpy(rep->exttr[fattr].name, name,
2597 				    len + 1);
2598 			} else {
2599 				rep->exttr[fattr].name = xmalloc(len + 3, rep);
2600 				(void) snprintf(rep->exttr[fattr].name, len + 3,
2601 				    "no%s", name);
2602 			}
2603 		} else {
2604 			opt = attr_to_option(fattr);
2605 			if (opt != NULL) {
2606 				len = strlen(opt);
2607 				rep->exttr[fattr].name = xmalloc(len + 1, rep);
2608 				if (val)
2609 					(void) strlcpy(rep->exttr[fattr].name,
2610 					    opt, len + 1);
2611 				else
2612 					(void) strlcpy(rep->exttr[fattr].name,
2613 					    "-", len + 1);
2614 			}
2615 		}
2616 	}
2617 }
2618 
2619 /* Set extended system attribute timestamp display */
2620 
2621 void
2622 set_sysattrtm_display(char *name, struct lbuf *rep)
2623 {
2624 	uint_t		nelem;
2625 	uint64_t	*value;
2626 	int		i;
2627 	size_t		len;
2628 
2629 	if (nvpair_value_uint64_array(pair, &value, &nelem) == 0) {
2630 		if (*value != NULL) {
2631 			len = strlen(name);
2632 			i = 0;
2633 			while (rep->extm[i].stm != 0 && i < sacnt)
2634 				i++;
2635 			rep->extm[i].stm = value[0];
2636 			rep->extm[i].nstm = value[1];
2637 			rep->extm[i].name = xmalloc(len + 1, rep);
2638 			(void) strlcpy(rep->extm[i].name, name, len + 1);
2639 		}
2640 	}
2641 }
2642 
2643 void
2644 format_time(time_t sec, time_t nsec)
2645 {
2646 	const char *fstr = time_fmt_new;
2647 	char fmt_buf[FMTSIZE];
2648 
2649 	if (Eflg) {
2650 		(void) snprintf(fmt_buf, FMTSIZE, fstr, nsec);
2651 		(void) strftime(time_buf, sizeof (time_buf), fmt_buf,
2652 		    localtime(&sec));
2653 		return;
2654 	}
2655 
2656 	if (sec < year || sec > now)
2657 		fstr = time_fmt_old;
2658 
2659 	/* if a custom time was specified, shouldn't be localized */
2660 	(void) strftime(time_buf, sizeof (time_buf),
2661 	    (time_custom == 0) ? dcgettext(NULL, fstr, LC_TIME) : fstr,
2662 	    localtime(&sec));
2663 }
2664 
2665 void
2666 format_attrtime(struct lbuf *p)
2667 {
2668 	int tmattr = 0;
2669 	int i;
2670 
2671 	if (p->extm != NULL) {
2672 		for (i = 0; i < sacnt; i++) {
2673 			if (p->extm[i].name != NULL) {
2674 				tmattr = 1;
2675 				break;
2676 			}
2677 		}
2678 	}
2679 
2680 	if (tmattr) {
2681 		const char *old_save = time_fmt_old;
2682 		const char *new_save = time_fmt_new;
2683 
2684 		/* Eflg always sets format to FORMAT_ISO_FULL */
2685 		if (!Eflg && !time_custom) {
2686 			time_fmt_old = FORMAT_OLD;
2687 			time_fmt_new = FORMAT_NEW;
2688 		}
2689 
2690 		format_time((time_t)p->extm[i].stm, (time_t)p->extm[i].nstm);
2691 
2692 		time_fmt_old = old_save;
2693 		time_fmt_new = new_save;
2694 	}
2695 }
2696 
2697 void
2698 print_time(struct lbuf *p)
2699 {
2700 	const char *old_save = time_fmt_old;
2701 	const char *new_save = time_fmt_new;
2702 
2703 	int i = 0;
2704 
2705 	if (!Eflg) {
2706 		time_fmt_old = FORMAT_LONG;
2707 		time_fmt_new = FORMAT_LONG;
2708 	}
2709 
2710 	new_line();
2711 	format_time(p->lat.tv_sec, p->lat.tv_nsec);
2712 	(void) printf("         timestamp: atime        %s\n", time_buf);
2713 	format_time(p->lct.tv_sec, p->lct.tv_nsec);
2714 	(void) printf("         timestamp: ctime        %s\n", time_buf);
2715 	format_time(p->lmt.tv_sec, p->lmt.tv_nsec);
2716 	(void) printf("         timestamp: mtime        %s\n", time_buf);
2717 	if (p->extm != NULL) {
2718 		while (p->extm[i].nstm != 0 && i < sacnt) {
2719 			format_time(p->extm[i].stm, p->extm[i].nstm);
2720 			if (p->extm[i].name != NULL) {
2721 				(void) printf("         timestamp:"
2722 				    " %s        %s\n",
2723 				    p->extm[i].name, time_buf);
2724 			}
2725 			i++;
2726 		}
2727 	}
2728 
2729 	time_fmt_old = old_save;
2730 	time_fmt_new = new_save;
2731 }
2732 
2733 /*
2734  * Check if color definition applies to entry, returns 1 if yes, 0 if no
2735  */
2736 static int
2737 color_match(const char *fname, mode_t mode, ls_color_t *color)
2738 {
2739 	switch (color->ftype) {
2740 	case LS_PAT:
2741 	{
2742 		size_t	fname_len, sfx_len;
2743 
2744 		fname_len = strlen(fname);
2745 		sfx_len = strlen(color->sfx);
2746 		if (sfx_len > fname_len)
2747 			return (0);
2748 
2749 		if (strcmp(color->sfx, fname + fname_len - sfx_len) == 0)
2750 			return (1);
2751 		else
2752 			return (0);
2753 	}
2754 
2755 	case LS_NORMAL:
2756 		return (1);
2757 
2758 	case LS_FILE:
2759 		return (S_ISREG(mode));
2760 
2761 	case LS_DIR:
2762 		return (S_ISDIR(mode));
2763 
2764 	case LS_LINK:
2765 		return (S_ISLNK(mode));
2766 
2767 	case LS_FIFO:
2768 		return (S_ISFIFO(mode));
2769 
2770 	case LS_SOCK:
2771 		return (S_ISSOCK(mode));
2772 
2773 	case LS_DOOR:
2774 		return (S_ISDOOR(mode));
2775 
2776 	case LS_BLK:
2777 		return (S_ISBLK(mode));
2778 
2779 	case LS_CHR:
2780 		return (S_ISCHR(mode));
2781 
2782 	case LS_PORT:
2783 		return (S_ISPORT(mode));
2784 
2785 	case LS_ORPHAN:
2786 		/* this is tested for by gstat */
2787 		return (0);
2788 
2789 	case LS_SETUID:
2790 		return (!S_ISLNK(mode) && (mode & S_ISUID));
2791 
2792 	case LS_SETGID:
2793 		return (!S_ISLNK(mode) && (mode & S_ISGID));
2794 
2795 	case LS_STICKY_OTHER_WRITABLE:
2796 		return (!S_ISLNK(mode) && (mode & (S_IWOTH|S_ISVTX)));
2797 
2798 	case LS_OTHER_WRITABLE:
2799 		return (!S_ISLNK(mode) && (mode & S_IWOTH));
2800 
2801 	case LS_STICKY:
2802 		return (!S_ISLNK(mode) && (mode & S_ISVTX));
2803 
2804 	case LS_EXEC:
2805 		return (!S_ISLNK(mode) && (mode & (S_IXUSR|S_IXGRP|S_IXOTH)));
2806 	}
2807 
2808 	return (0);
2809 }
2810 
2811 static void
2812 dump_color(ls_color_t *c)
2813 {
2814 	if (c == NULL)
2815 		return;
2816 
2817 	(void) printf("\n\ttype: ");
2818 	switch (c->ftype) {
2819 	case LS_NORMAL:
2820 		(void) printf("LS_NORMAL");
2821 		break;
2822 	case LS_FILE:
2823 		(void) printf("LS_FILE");
2824 		break;
2825 	case LS_EXEC:
2826 		(void) printf("LS_EXEC");
2827 		break;
2828 	case LS_DIR:
2829 		(void) printf("LS_DIR");
2830 		break;
2831 	case LS_LINK:
2832 		(void) printf("LS_LINK");
2833 		break;
2834 
2835 	case LS_FIFO:
2836 		(void) printf("LS_FIFO");
2837 		break;
2838 
2839 	case LS_SOCK:
2840 		(void) printf("LS_SOCK");
2841 		break;
2842 
2843 	case LS_DOOR:
2844 		(void) printf("LS_DOOR");
2845 		break;
2846 
2847 	case LS_BLK:
2848 		(void) printf("LS_BLK");
2849 		break;
2850 
2851 	case LS_CHR:
2852 		(void) printf("LS_CHR");
2853 		break;
2854 
2855 	case LS_PORT:
2856 		(void) printf("LS_PORT");
2857 		break;
2858 
2859 	case LS_STICKY:
2860 		(void) printf("LS_STICKY");
2861 		break;
2862 
2863 	case LS_ORPHAN:
2864 		(void) printf("LS_ORPHAN");
2865 		break;
2866 
2867 	case LS_SETGID:
2868 		(void) printf("LS_SETGID");
2869 		break;
2870 
2871 	case LS_SETUID:
2872 		(void) printf("LS_SETUID");
2873 		break;
2874 
2875 	case LS_OTHER_WRITABLE:
2876 		(void) printf("LS_OTHER_WRITABLE");
2877 		break;
2878 
2879 	case LS_STICKY_OTHER_WRITABLE:
2880 		(void) printf("LS_STICKY_OTHER_WRITABLE");
2881 		break;
2882 
2883 	case LS_PAT:
2884 		(void) printf("LS_PAT\n");
2885 		(void) printf("\tpattern: %s", c->sfx);
2886 		break;
2887 	}
2888 	(void) printf("\n");
2889 	(void) printf("\tattr: %d\n", c->attr);
2890 	(void) printf("\tfg: %d\n", c->fg);
2891 	(void) printf("\tbg: %d\n", c->bg);
2892 	(void) printf("\t");
2893 }
2894 
2895 static ls_color_t *
2896 ls_color_find(const char *fname, mode_t mode)
2897 {
2898 	int i;
2899 
2900 	/*
2901 	 * Colors are sorted from most general lsc_colors[0] to most specific
2902 	 * lsc_colors[lsc_ncolors - 1] by ls_color_init().  Start search with
2903 	 * most specific color rule and work towards most general.
2904 	 */
2905 	for (i = lsc_ncolors - 1; i >= 0; --i)
2906 		if (color_match(fname, mode, &lsc_colors[i]))
2907 			return (&lsc_colors[i]);
2908 
2909 	return (NULL);
2910 }
2911 
2912 static void
2913 ls_tprint(char *str, long int p1, long int p2, long int p3, long int p4,
2914     long int p5, long int p6, long int p7, long int p8, long int p9)
2915 {
2916 	char *s;
2917 
2918 	if (str == NULL)
2919 		return;
2920 
2921 	s = tparm(str, p1, p2, p3, p4, p5, p6, p7, p8, p9);
2922 
2923 	if (s != NULL)
2924 		(void) putp(s);
2925 }
2926 
2927 static void
2928 ls_start_color(ls_color_t *c)
2929 {
2930 	if (c == NULL)
2931 		return;
2932 
2933 	if (lsc_debug)
2934 		lsc_match = c;
2935 
2936 	if (c->attr & LSA_BOLD)
2937 		ls_tprint(lsc_bold, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2938 	if (c->attr & LSA_UNDERSCORE)
2939 		ls_tprint(lsc_underline, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2940 	if (c->attr & LSA_BLINK)
2941 		ls_tprint(lsc_blink, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2942 	if (c->attr & LSA_REVERSE)
2943 		ls_tprint(lsc_reverse, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2944 	if (c->attr & LSA_CONCEALED)
2945 		ls_tprint(lsc_concealed, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2946 	if (c->attr == LSA_NONE)
2947 		ls_tprint(lsc_none, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2948 
2949 	if (c->fg != -1)
2950 		ls_tprint(lsc_setfg, c->fg, 0, 0, 0, 0, 0, 0, 0, 0);
2951 	if (c->bg != -1)
2952 		ls_tprint(lsc_setbg, c->bg, 0, 0, 0, 0, 0, 0, 0, 0);
2953 }
2954 
2955 static void
2956 ls_end_color()
2957 {
2958 	ls_tprint(lsc_none, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2959 	if (lsc_debug)
2960 		dump_color(lsc_match);
2961 }
2962 
2963 static void
2964 new_color_entry(char *colorstr)
2965 {
2966 	static const struct {
2967 		const char	*s;
2968 		ls_cftype_t	stype;
2969 	} type_map[] = {
2970 		{ "no", LS_NORMAL },
2971 		{ "fi", LS_FILE },
2972 		{ "di", LS_DIR },
2973 		{ "ln", LS_LINK },
2974 		{ "pi", LS_FIFO },
2975 		{ "so", LS_SOCK },
2976 		{ "do", LS_DOOR },
2977 		{ "bd", LS_BLK },
2978 		{ "cd", LS_CHR },
2979 		{ "or", LS_ORPHAN },
2980 		{ "su", LS_SETUID },
2981 		{ "sg", LS_SETGID },
2982 		{ "tw", LS_STICKY_OTHER_WRITABLE },
2983 		{ "ow", LS_OTHER_WRITABLE },
2984 		{ "st", LS_STICKY },
2985 		{ "ex", LS_EXEC },
2986 		{ "po", LS_PORT },
2987 		{ NULL, LS_NORMAL }
2988 	};
2989 
2990 	char		*p, *lasts;
2991 	int		i;
2992 	int		color, attr;
2993 
2994 	p = strtok_r(colorstr, "=", &lasts);
2995 	if (p == NULL) {
2996 		colorflg = 0;
2997 		return;
2998 	}
2999 
3000 	if (p[0] == '*') {
3001 		lsc_colors[lsc_ncolors].ftype = LS_PAT;
3002 		/* don't include the * in the suffix */
3003 		if ((lsc_colors[lsc_ncolors].sfx = strdup(p + 1)) == NULL) {
3004 			colorflg = 0;
3005 			return;
3006 		}
3007 	} else {
3008 		lsc_colors[lsc_ncolors].sfx = NULL;
3009 
3010 		for (i = 0; type_map[i].s != NULL; ++i) {
3011 			if (strncmp(type_map[i].s, p, 2) == 0)
3012 				break;
3013 		}
3014 
3015 		/* ignore unknown file types */
3016 		if (type_map[i].s == NULL)
3017 			return;
3018 
3019 		lsc_colors[lsc_ncolors].ftype = type_map[i].stype;
3020 	}
3021 
3022 	attr = LSA_NONE;
3023 	lsc_colors[lsc_ncolors].fg = -1;
3024 	lsc_colors[lsc_ncolors].bg = -1;
3025 	for (p = strtok_r(NULL, ";", &lasts); p != NULL;
3026 	    p = strtok_r(NULL, ";", &lasts)) {
3027 		color = strtol(p, NULL, 10);
3028 
3029 		if (color < 10) {
3030 			switch (color) {
3031 			case 0:
3032 				attr = LSA_NONE;
3033 				continue;
3034 			case 1:
3035 				attr |= LSA_BOLD;
3036 				continue;
3037 			case 4:
3038 				attr |= LSA_UNDERSCORE;
3039 				continue;
3040 			case 5:
3041 				attr |= LSA_BLINK;
3042 				continue;
3043 			case 7:
3044 				attr |= LSA_REVERSE;
3045 				continue;
3046 			case 8:
3047 				attr |= LSA_CONCEALED;
3048 				continue;
3049 			default:
3050 				continue;
3051 			}
3052 		}
3053 
3054 		if (color < 40)
3055 			lsc_colors[lsc_ncolors].fg = color - 30;
3056 		else
3057 			lsc_colors[lsc_ncolors].bg = color - 40;
3058 	}
3059 
3060 	lsc_colors[lsc_ncolors].attr = attr;
3061 	++lsc_ncolors;
3062 }
3063 
3064 static int
3065 ls_color_compare(const void *p1, const void *p2)
3066 {
3067 	const ls_color_t *c1 = (const ls_color_t *)p1;
3068 	const ls_color_t *c2 = (const ls_color_t *)p2;
3069 
3070 	int ret = c1->ftype - c2->ftype;
3071 
3072 	if (ret != 0)
3073 		return (ret);
3074 
3075 	if (c1->ftype != LS_PAT)
3076 		return (ret);
3077 
3078 	return (strcmp(c1->sfx, c2->sfx));
3079 }
3080 
3081 static void
3082 ls_color_init()
3083 {
3084 	static char *default_colorstr = "no=00:fi=00:di=01;34:ln=01;36:po=01;35"
3085 	    ":pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01"
3086 	    ":su=37;41:sg=30;43:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31"
3087 	    ":*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31"
3088 	    ":*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31"
3089 	    ":*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35"
3090 	    ":*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35"
3091 	    ":*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35"
3092 	    ":*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35"
3093 	    ":*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.flac=01;35"
3094 	    ":*.mp3=01;35:*.mpc=01;35:*.ogg=01;35:*.wav=01;35";
3095 
3096 	char    *colorstr;
3097 	char    *p, *lasts;
3098 	size_t  color_sz;
3099 	int	termret;
3100 	int	i;
3101 
3102 	(void) setupterm(NULL, 1, &termret);
3103 	if (termret != 1)
3104 		return;
3105 
3106 	if ((p = getenv("LS_COLORS")) == NULL)
3107 		p = default_colorstr;
3108 	colorstr = strdup(p);
3109 	if (colorstr == NULL)
3110 		return;
3111 
3112 	/*
3113 	 * Determine the size of lsc_colors.  color_sz can be > lsc_ncolors
3114 	 * if there are invalid entries passed in the string (they are ignored)
3115 	 */
3116 	color_sz = 1;
3117 	for (p = strchr(colorstr, ':'); p != NULL && *p != '\0';
3118 	    p = strchr(++p, ':'))
3119 		++color_sz;
3120 
3121 	lsc_colors = calloc(color_sz, sizeof (ls_color_t));
3122 	if (lsc_colors == NULL) {
3123 		free(colorstr);
3124 		return;
3125 	}
3126 
3127 	for (p = strtok_r(colorstr, ":", &lasts);
3128 	    p != NULL && lsc_ncolors < color_sz;
3129 	    p = strtok_r(NULL, ":", &lasts))
3130 		new_color_entry(p);
3131 
3132 	qsort((void *)lsc_colors, lsc_ncolors, sizeof (ls_color_t),
3133 	    ls_color_compare);
3134 
3135 	for (i = 0; i < lsc_ncolors; ++i)
3136 		if (lsc_colors[i].ftype == LS_ORPHAN) {
3137 			lsc_orphan = &lsc_colors[i];
3138 			break;
3139 		}
3140 
3141 	if ((lsc_bold = tigetstr("bold")) == (char *)-1)
3142 		lsc_bold = NULL;
3143 
3144 	if ((lsc_underline = tigetstr("smul")) == (char *)-1)
3145 		lsc_underline = NULL;
3146 
3147 	if ((lsc_blink = tigetstr("blink")) == (char *)-1)
3148 		lsc_blink = NULL;
3149 
3150 	if ((lsc_reverse = tigetstr("rev")) == (char *)-1)
3151 		lsc_reverse = NULL;
3152 
3153 	if ((lsc_concealed = tigetstr("prot")) == (char *)-1)
3154 		lsc_concealed = NULL;
3155 
3156 	if ((lsc_none = tigetstr("sgr0")) == (char *)-1)
3157 		lsc_none = NULL;
3158 
3159 	if ((lsc_setfg = tigetstr("setaf")) == (char *)-1)
3160 		lsc_setfg = NULL;
3161 
3162 	if ((lsc_setbg = tigetstr("setab")) == (char *)-1)
3163 		lsc_setbg = NULL;
3164 
3165 	if (getenv("_LS_COLOR_DEBUG") != NULL) {
3166 		int i;
3167 
3168 		lsc_debug = 1;
3169 		for (i = 0; i < lsc_ncolors; ++i)
3170 			dump_color(&lsc_colors[i]);
3171 	}
3172 
3173 	free(colorstr);
3174 }
3175 
3176 /* Free extended system attribute lists */
3177 
3178 void
3179 free_sysattr(struct lbuf *p)
3180 {
3181 	int i;
3182 
3183 	if (p->exttr != NULL) {
3184 		for (i = 0; i < sacnt; i++) {
3185 			if (p->exttr[i].name != NULL)
3186 				free(p->exttr[i].name);
3187 		}
3188 		free(p->exttr);
3189 	}
3190 	if (p->extm != NULL) {
3191 		for (i = 0; i < sacnt; i++) {
3192 			if (p->extm[i].name != NULL)
3193 				free(p->extm[i].name);
3194 		}
3195 		free(p->extm);
3196 	}
3197 }
3198 
3199 /* Allocate extended system attribute list */
3200 
3201 void *
3202 xmalloc(size_t size, struct lbuf *p)
3203 {
3204 	if ((p = malloc(size)) == NULL) {
3205 		perror("ls");
3206 		free_sysattr(p);
3207 		nvlist_free(response);
3208 		exit(2);
3209 	}
3210 	return (p);
3211 }
3212