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