xref: /freebsd/bin/ls/print.c (revision 9fd69f37d28cfd7438cac3eeb45fe9dd46b4d7dd)
1 /*-
2  * Copyright (c) 1989, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Michael Fischbein.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #if 0
34 #ifndef lint
35 static char sccsid[] = "@(#)print.c	8.4 (Berkeley) 4/17/94";
36 #endif /* not lint */
37 #endif
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include <sys/param.h>
42 #include <sys/stat.h>
43 #include <sys/acl.h>
44 
45 #include <err.h>
46 #include <errno.h>
47 #include <fts.h>
48 #include <langinfo.h>
49 #include <libutil.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <time.h>
54 #include <unistd.h>
55 #ifdef COLORLS
56 #include <ctype.h>
57 #include <termcap.h>
58 #include <signal.h>
59 #endif
60 
61 #include "ls.h"
62 #include "extern.h"
63 
64 static int	printaname(const FTSENT *, u_long, u_long);
65 static void	printdev(size_t, dev_t);
66 static void	printlink(const FTSENT *);
67 static void	printtime(time_t);
68 static int	printtype(u_int);
69 static void	printsize(size_t, off_t);
70 #ifdef COLORLS
71 static void	endcolor(int);
72 static int	colortype(mode_t);
73 #endif
74 static void	aclmode(char *, const FTSENT *);
75 
76 #define	IS_NOPRINT(p)	((p)->fts_number == NO_PRINT)
77 
78 #ifdef COLORLS
79 /* Most of these are taken from <sys/stat.h> */
80 typedef enum Colors {
81 	C_DIR,			/* directory */
82 	C_LNK,			/* symbolic link */
83 	C_SOCK,			/* socket */
84 	C_FIFO,			/* pipe */
85 	C_EXEC,			/* executable */
86 	C_BLK,			/* block special */
87 	C_CHR,			/* character special */
88 	C_SUID,			/* setuid executable */
89 	C_SGID,			/* setgid executable */
90 	C_WSDIR,		/* directory writeble to others, with sticky
91 				 * bit */
92 	C_WDIR,			/* directory writeble to others, without
93 				 * sticky bit */
94 	C_NUMCOLORS		/* just a place-holder */
95 } Colors;
96 
97 static const char *defcolors = "exfxcxdxbxegedabagacad";
98 
99 /* colors for file types */
100 static struct {
101 	int	num[2];
102 	int	bold;
103 } colors[C_NUMCOLORS];
104 #endif
105 
106 void
107 printscol(const DISPLAY *dp)
108 {
109 	FTSENT *p;
110 
111 	for (p = dp->list; p; p = p->fts_link) {
112 		if (IS_NOPRINT(p))
113 			continue;
114 		(void)printaname(p, dp->s_inode, dp->s_block);
115 		(void)putchar('\n');
116 	}
117 }
118 
119 /*
120  * print name in current style
121  */
122 int
123 printname(const char *name)
124 {
125 	if (f_octal || f_octal_escape)
126 		return prn_octal(name);
127 	else if (f_nonprint)
128 		return prn_printable(name);
129 	else
130 		return prn_normal(name);
131 }
132 
133 void
134 printlong(const DISPLAY *dp)
135 {
136 	struct stat *sp;
137 	FTSENT *p;
138 	NAMES *np;
139 	char buf[20];
140 #ifdef COLORLS
141 	int color_printed = 0;
142 #endif
143 
144 	if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
145 	    (f_longform || f_size)) {
146 		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
147 	}
148 
149 	for (p = dp->list; p; p = p->fts_link) {
150 		if (IS_NOPRINT(p))
151 			continue;
152 		sp = p->fts_statp;
153 		if (f_inode)
154 			(void)printf("%*lu ", dp->s_inode, (u_long)sp->st_ino);
155 		if (f_size)
156 			(void)printf("%*jd ",
157 			    dp->s_block, howmany(sp->st_blocks, blocksize));
158 		strmode(sp->st_mode, buf);
159 		aclmode(buf, p);
160 		np = p->fts_pointer;
161 		(void)printf("%s %*u %-*s  %-*s  ", buf, dp->s_nlink,
162 		    sp->st_nlink, dp->s_user, np->user, dp->s_group,
163 		    np->group);
164 		if (f_flags)
165 			(void)printf("%-*s ", dp->s_flags, np->flags);
166 		if (f_label)
167 			(void)printf("%-*s ", dp->s_label, np->label);
168 		if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
169 			printdev(dp->s_size, sp->st_rdev);
170 		else
171 			printsize(dp->s_size, sp->st_size);
172 		if (f_accesstime)
173 			printtime(sp->st_atime);
174 		else if (f_birthtime)
175 			printtime(sp->st_birthtime);
176 		else if (f_statustime)
177 			printtime(sp->st_ctime);
178 		else
179 			printtime(sp->st_mtime);
180 #ifdef COLORLS
181 		if (f_color)
182 			color_printed = colortype(sp->st_mode);
183 #endif
184 		(void)printname(p->fts_name);
185 #ifdef COLORLS
186 		if (f_color && color_printed)
187 			endcolor(0);
188 #endif
189 		if (f_type)
190 			(void)printtype(sp->st_mode);
191 		if (S_ISLNK(sp->st_mode))
192 			printlink(p);
193 		(void)putchar('\n');
194 	}
195 }
196 
197 void
198 printstream(const DISPLAY *dp)
199 {
200 	FTSENT *p;
201 	int chcnt;
202 
203 	for (p = dp->list, chcnt = 0; p; p = p->fts_link) {
204 		if (p->fts_number == NO_PRINT)
205 			continue;
206 		/* XXX strlen does not take octal escapes into account. */
207 		if (strlen(p->fts_name) + chcnt +
208 		    (p->fts_link ? 2 : 0) >= (unsigned)termwidth) {
209 			putchar('\n');
210 			chcnt = 0;
211 		}
212 		chcnt += printaname(p, dp->s_inode, dp->s_block);
213 		if (p->fts_link) {
214 			printf(", ");
215 			chcnt += 2;
216 		}
217 	}
218 	if (chcnt)
219 		putchar('\n');
220 }
221 
222 void
223 printcol(const DISPLAY *dp)
224 {
225 	static FTSENT **array;
226 	static int lastentries = -1;
227 	FTSENT *p;
228 	FTSENT **narray;
229 	int base;
230 	int chcnt;
231 	int cnt;
232 	int col;
233 	int colwidth;
234 	int endcol;
235 	int num;
236 	int numcols;
237 	int numrows;
238 	int row;
239 	int tabwidth;
240 
241 	if (f_notabs)
242 		tabwidth = 1;
243 	else
244 		tabwidth = 8;
245 
246 	/*
247 	 * Have to do random access in the linked list -- build a table
248 	 * of pointers.
249 	 */
250 	if (dp->entries > lastentries) {
251 		if ((narray =
252 		    realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
253 			warn(NULL);
254 			printscol(dp);
255 			return;
256 		}
257 		lastentries = dp->entries;
258 		array = narray;
259 	}
260 	for (p = dp->list, num = 0; p; p = p->fts_link)
261 		if (p->fts_number != NO_PRINT)
262 			array[num++] = p;
263 
264 	colwidth = dp->maxlen;
265 	if (f_inode)
266 		colwidth += dp->s_inode + 1;
267 	if (f_size)
268 		colwidth += dp->s_block + 1;
269 	if (f_type)
270 		colwidth += 1;
271 
272 	colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
273 	if (termwidth < 2 * colwidth) {
274 		printscol(dp);
275 		return;
276 	}
277 	numcols = termwidth / colwidth;
278 	numrows = num / numcols;
279 	if (num % numcols)
280 		++numrows;
281 
282 	if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
283 	    (f_longform || f_size)) {
284 		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
285 	}
286 
287 	base = 0;
288 	for (row = 0; row < numrows; ++row) {
289 		endcol = colwidth;
290 		if (!f_sortacross)
291 			base = row;
292 		for (col = 0, chcnt = 0; col < numcols; ++col) {
293 			chcnt += printaname(array[base], dp->s_inode,
294 			    dp->s_block);
295 			if (f_sortacross)
296 				base++;
297 			else
298 				base += numrows;
299 			if (base >= num)
300 				break;
301 			while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
302 			    <= endcol) {
303 				if (f_sortacross && col + 1 >= numcols)
304 					break;
305 				(void)putchar(f_notabs ? ' ' : '\t');
306 				chcnt = cnt;
307 			}
308 			endcol += colwidth;
309 		}
310 		(void)putchar('\n');
311 	}
312 }
313 
314 /*
315  * print [inode] [size] name
316  * return # of characters printed, no trailing characters.
317  */
318 static int
319 printaname(const FTSENT *p, u_long inodefield, u_long sizefield)
320 {
321 	struct stat *sp;
322 	int chcnt;
323 #ifdef COLORLS
324 	int color_printed = 0;
325 #endif
326 
327 	sp = p->fts_statp;
328 	chcnt = 0;
329 	if (f_inode)
330 		chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
331 	if (f_size)
332 		chcnt += printf("%*jd ",
333 		    (int)sizefield, howmany(sp->st_blocks, blocksize));
334 #ifdef COLORLS
335 	if (f_color)
336 		color_printed = colortype(sp->st_mode);
337 #endif
338 	chcnt += printname(p->fts_name);
339 #ifdef COLORLS
340 	if (f_color && color_printed)
341 		endcolor(0);
342 #endif
343 	if (f_type)
344 		chcnt += printtype(sp->st_mode);
345 	return (chcnt);
346 }
347 
348 /*
349  * Print device special file major and minor numbers.
350  */
351 static void
352 printdev(size_t width, dev_t dev)
353 {
354 	char buf[DEVSTR_HEX_LEN + 1];
355 
356 	if (minor(dev) > 255 || minor(dev) < 0)
357 		(void)snprintf(buf, sizeof(buf), "%3d, 0x%08x",
358 		    major(dev), (u_int)minor(dev));
359 	else
360 		(void)snprintf(buf, sizeof(buf), "%3d, %3d",
361 		    major(dev), minor(dev));
362 
363 	(void)printf("%*s ", (u_int)width, buf);
364 }
365 
366 static void
367 printtime(time_t ftime)
368 {
369 	char longstring[80];
370 	static time_t now = 0;
371 	const char *format;
372 	static int d_first = -1;
373 
374 	if (d_first < 0)
375 		d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
376 	if (now == 0)
377 		now = time(NULL);
378 
379 #define	SIXMONTHS	((365 / 2) * 86400)
380 	if (f_timeformat)  /* user specified format */
381 		format = f_timeformat;
382 	else if (f_sectime)
383 		/* mmm dd hh:mm:ss yyyy || dd mmm hh:mm:ss yyyy */
384 		format = d_first ? "%e %b %T %Y" : "%b %e %T %Y";
385 	else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
386 		/* mmm dd hh:mm || dd mmm hh:mm */
387 		format = d_first ? "%e %b %R" : "%b %e %R";
388 	else
389 		/* mmm dd  yyyy || dd mmm  yyyy */
390 		format = d_first ? "%e %b  %Y" : "%b %e  %Y";
391 	strftime(longstring, sizeof(longstring), format, localtime(&ftime));
392 	fputs(longstring, stdout);
393 	fputc(' ', stdout);
394 }
395 
396 static int
397 printtype(u_int mode)
398 {
399 
400 	if (f_slash) {
401 		if ((mode & S_IFMT) == S_IFDIR) {
402 			(void)putchar('/');
403 			return (1);
404 		}
405 		return (0);
406 	}
407 
408 	switch (mode & S_IFMT) {
409 	case S_IFDIR:
410 		(void)putchar('/');
411 		return (1);
412 	case S_IFIFO:
413 		(void)putchar('|');
414 		return (1);
415 	case S_IFLNK:
416 		(void)putchar('@');
417 		return (1);
418 	case S_IFSOCK:
419 		(void)putchar('=');
420 		return (1);
421 	case S_IFWHT:
422 		(void)putchar('%');
423 		return (1);
424 	default:
425 		break;
426 	}
427 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
428 		(void)putchar('*');
429 		return (1);
430 	}
431 	return (0);
432 }
433 
434 #ifdef COLORLS
435 static int
436 putch(int c)
437 {
438 	(void)putchar(c);
439 	return 0;
440 }
441 
442 static int
443 writech(int c)
444 {
445 	char tmp = (char)c;
446 
447 	(void)write(STDOUT_FILENO, &tmp, 1);
448 	return 0;
449 }
450 
451 static void
452 printcolor(Colors c)
453 {
454 	char *ansiseq;
455 
456 	if (colors[c].bold)
457 		tputs(enter_bold, 1, putch);
458 
459 	if (colors[c].num[0] != -1) {
460 		ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
461 		if (ansiseq)
462 			tputs(ansiseq, 1, putch);
463 	}
464 	if (colors[c].num[1] != -1) {
465 		ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
466 		if (ansiseq)
467 			tputs(ansiseq, 1, putch);
468 	}
469 }
470 
471 static void
472 endcolor(int sig)
473 {
474 	tputs(ansi_coloff, 1, sig ? writech : putch);
475 	tputs(attrs_off, 1, sig ? writech : putch);
476 }
477 
478 static int
479 colortype(mode_t mode)
480 {
481 	switch (mode & S_IFMT) {
482 	case S_IFDIR:
483 		if (mode & S_IWOTH)
484 			if (mode & S_ISTXT)
485 				printcolor(C_WSDIR);
486 			else
487 				printcolor(C_WDIR);
488 		else
489 			printcolor(C_DIR);
490 		return (1);
491 	case S_IFLNK:
492 		printcolor(C_LNK);
493 		return (1);
494 	case S_IFSOCK:
495 		printcolor(C_SOCK);
496 		return (1);
497 	case S_IFIFO:
498 		printcolor(C_FIFO);
499 		return (1);
500 	case S_IFBLK:
501 		printcolor(C_BLK);
502 		return (1);
503 	case S_IFCHR:
504 		printcolor(C_CHR);
505 		return (1);
506 	default:;
507 	}
508 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
509 		if (mode & S_ISUID)
510 			printcolor(C_SUID);
511 		else if (mode & S_ISGID)
512 			printcolor(C_SGID);
513 		else
514 			printcolor(C_EXEC);
515 		return (1);
516 	}
517 	return (0);
518 }
519 
520 void
521 parsecolors(const char *cs)
522 {
523 	int i;
524 	int j;
525 	size_t len;
526 	char c[2];
527 	short legacy_warn = 0;
528 
529 	if (cs == NULL)
530 		cs = "";	/* LSCOLORS not set */
531 	len = strlen(cs);
532 	for (i = 0; i < (int)C_NUMCOLORS; i++) {
533 		colors[i].bold = 0;
534 
535 		if (len <= 2 * (size_t)i) {
536 			c[0] = defcolors[2 * i];
537 			c[1] = defcolors[2 * i + 1];
538 		} else {
539 			c[0] = cs[2 * i];
540 			c[1] = cs[2 * i + 1];
541 		}
542 		for (j = 0; j < 2; j++) {
543 			/* Legacy colours used 0-7 */
544 			if (c[j] >= '0' && c[j] <= '7') {
545 				colors[i].num[j] = c[j] - '0';
546 				if (!legacy_warn) {
547 					warnx("LSCOLORS should use "
548 					    "characters a-h instead of 0-9 ("
549 					    "see the manual page)");
550 				}
551 				legacy_warn = 1;
552 			} else if (c[j] >= 'a' && c[j] <= 'h')
553 				colors[i].num[j] = c[j] - 'a';
554 			else if (c[j] >= 'A' && c[j] <= 'H') {
555 				colors[i].num[j] = c[j] - 'A';
556 				colors[i].bold = 1;
557 			} else if (tolower((unsigned char)c[j]) == 'x')
558 				colors[i].num[j] = -1;
559 			else {
560 				warnx("invalid character '%c' in LSCOLORS"
561 				    " env var", c[j]);
562 				colors[i].num[j] = -1;
563 			}
564 		}
565 	}
566 }
567 
568 void
569 colorquit(int sig)
570 {
571 	endcolor(sig);
572 
573 	(void)signal(sig, SIG_DFL);
574 	(void)kill(getpid(), sig);
575 }
576 
577 #endif /* COLORLS */
578 
579 static void
580 printlink(const FTSENT *p)
581 {
582 	int lnklen;
583 	char name[MAXPATHLEN + 1];
584 	char path[MAXPATHLEN + 1];
585 
586 	if (p->fts_level == FTS_ROOTLEVEL)
587 		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
588 	else
589 		(void)snprintf(name, sizeof(name),
590 		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
591 	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
592 		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
593 		return;
594 	}
595 	path[lnklen] = '\0';
596 	(void)printf(" -> ");
597 	(void)printname(path);
598 }
599 
600 static void
601 printsize(size_t width, off_t bytes)
602 {
603 
604 	if (f_humanval) {
605 		/*
606 		 * Reserve one space before the size and allocate room for
607 		 * the trailing '\0'.
608 		 */
609 		char buf[HUMANVALSTR_LEN - 1 + 1];
610 
611 		humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
612 		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
613 		(void)printf("%*s ", (u_int)width, buf);
614 	} else
615 		(void)printf("%*jd ", (u_int)width, bytes);
616 }
617 
618 /*
619  * Add a + after the standard rwxrwxrwx mode if the file has an
620  * ACL. strmode() reserves space at the end of the string.
621  */
622 static void
623 aclmode(char *buf, const FTSENT *p)
624 {
625 	char name[MAXPATHLEN + 1];
626 	int ret, trivial;
627 	static dev_t previous_dev = NODEV;
628 	static int supports_acls = -1;
629 	static int type = ACL_TYPE_ACCESS;
630 	acl_t facl;
631 
632 	/*
633 	 * XXX: ACLs are not supported on whiteouts and device files
634 	 * residing on UFS.
635 	 */
636 	if (S_ISCHR(p->fts_statp->st_mode) || S_ISBLK(p->fts_statp->st_mode) ||
637 	    S_ISWHT(p->fts_statp->st_mode))
638 		return;
639 
640 	if (previous_dev == p->fts_statp->st_dev && supports_acls == 0)
641 		return;
642 
643 	if (p->fts_level == FTS_ROOTLEVEL)
644 		snprintf(name, sizeof(name), "%s", p->fts_name);
645 	else
646 		snprintf(name, sizeof(name), "%s/%s",
647 		    p->fts_parent->fts_accpath, p->fts_name);
648 
649 	if (previous_dev != p->fts_statp->st_dev) {
650 		previous_dev = p->fts_statp->st_dev;
651 		supports_acls = 0;
652 
653 		ret = lpathconf(name, _PC_ACL_NFS4);
654 		if (ret > 0) {
655 			type = ACL_TYPE_NFS4;
656 			supports_acls = 1;
657 		} else if (ret < 0 && errno != EINVAL) {
658 			warn("%s", name);
659 			return;
660 		}
661 		if (supports_acls == 0) {
662 			ret = lpathconf(name, _PC_ACL_EXTENDED);
663 			if (ret > 0) {
664 				type = ACL_TYPE_ACCESS;
665 				supports_acls = 1;
666 			} else if (ret < 0 && errno != EINVAL) {
667 				warn("%s", name);
668 				return;
669 			}
670 		}
671 	}
672 	if (supports_acls == 0)
673 		return;
674 	facl = acl_get_link_np(name, type);
675 	if (facl == NULL) {
676 		warn("%s", name);
677 		return;
678 	}
679 	if (acl_is_trivial_np(facl, &trivial)) {
680 		acl_free(facl);
681 		warn("%s", name);
682 		return;
683 	}
684 	if (!trivial)
685 		buf[10] = '+';
686 	acl_free(facl);
687 }
688