xref: /freebsd/bin/ls/print.c (revision 2be1a816b9ff69588e55be0a84cbe2a31efc0f2f)
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	printlink(const FTSENT *);
66 static void	printtime(time_t);
67 static int	printtype(u_int);
68 static void	printsize(size_t, off_t);
69 #ifdef COLORLS
70 static void	endcolor(int);
71 static int	colortype(mode_t);
72 #endif
73 static void	aclmode(char *, const FTSENT *, int *);
74 
75 #define	IS_NOPRINT(p)	((p)->fts_number == NO_PRINT)
76 
77 #ifdef COLORLS
78 /* Most of these are taken from <sys/stat.h> */
79 typedef enum Colors {
80 	C_DIR,			/* directory */
81 	C_LNK,			/* symbolic link */
82 	C_SOCK,			/* socket */
83 	C_FIFO,			/* pipe */
84 	C_EXEC,			/* executable */
85 	C_BLK,			/* block special */
86 	C_CHR,			/* character special */
87 	C_SUID,			/* setuid executable */
88 	C_SGID,			/* setgid executable */
89 	C_WSDIR,		/* directory writeble to others, with sticky
90 				 * bit */
91 	C_WDIR,			/* directory writeble to others, without
92 				 * sticky bit */
93 	C_NUMCOLORS		/* just a place-holder */
94 } Colors;
95 
96 static const char *defcolors = "exfxcxdxbxegedabagacad";
97 
98 /* colors for file types */
99 static struct {
100 	int	num[2];
101 	int	bold;
102 } colors[C_NUMCOLORS];
103 #endif
104 
105 void
106 printscol(const DISPLAY *dp)
107 {
108 	FTSENT *p;
109 
110 	for (p = dp->list; p; p = p->fts_link) {
111 		if (IS_NOPRINT(p))
112 			continue;
113 		(void)printaname(p, dp->s_inode, dp->s_block);
114 		(void)putchar('\n');
115 	}
116 }
117 
118 /*
119  * print name in current style
120  */
121 int
122 printname(const char *name)
123 {
124 	if (f_octal || f_octal_escape)
125 		return prn_octal(name);
126 	else if (f_nonprint)
127 		return prn_printable(name);
128 	else
129 		return prn_normal(name);
130 }
131 
132 void
133 printlong(const DISPLAY *dp)
134 {
135 	struct stat *sp;
136 	FTSENT *p;
137 	NAMES *np;
138 	char buf[20];
139 #ifdef COLORLS
140 	int color_printed = 0;
141 #endif
142 	int haveacls;
143 	dev_t prevdev;
144 
145 	if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
146 	    (f_longform || f_size)) {
147 		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
148 	}
149 
150 	haveacls = 1;
151 	prevdev = (dev_t)-1;
152 	for (p = dp->list; p; p = p->fts_link) {
153 		if (IS_NOPRINT(p))
154 			continue;
155 		sp = p->fts_statp;
156 		if (f_inode)
157 			(void)printf("%*lu ", dp->s_inode, (u_long)sp->st_ino);
158 		if (f_size)
159 			(void)printf("%*jd ",
160 			    dp->s_block, howmany(sp->st_blocks, blocksize));
161 		strmode(sp->st_mode, buf);
162 		/*
163 		 * Cache whether or not the filesystem supports ACL's to
164 		 * avoid expensive syscalls. Try again when we change devices.
165 		 */
166 		if (haveacls || sp->st_dev != prevdev) {
167 			aclmode(buf, p, &haveacls);
168 			prevdev = sp->st_dev;
169 		}
170 		np = p->fts_pointer;
171 		(void)printf("%s %*u %-*s  %-*s  ", buf, dp->s_nlink,
172 		    sp->st_nlink, dp->s_user, np->user, dp->s_group,
173 		    np->group);
174 		if (f_flags)
175 			(void)printf("%-*s ", dp->s_flags, np->flags);
176 		if (f_label)
177 			(void)printf("%-*s ", dp->s_label, np->label);
178 		if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
179 			if (minor(sp->st_rdev) > 255 || minor(sp->st_rdev) < 0)
180 				(void)printf("%3d, 0x%08x ",
181 				    major(sp->st_rdev),
182 				    (u_int)minor(sp->st_rdev));
183 			else
184 				(void)printf("%3d, %3d ",
185 				    major(sp->st_rdev), minor(sp->st_rdev));
186 		else if (dp->bcfile)
187 			(void)printf("%*s%*jd ",
188 			    8 - dp->s_size, "", dp->s_size, sp->st_size);
189 		else
190 			printsize(dp->s_size, sp->st_size);
191 		if (f_accesstime)
192 			printtime(sp->st_atime);
193 		else if (f_birthtime)
194 			printtime(sp->st_birthtime);
195 		else if (f_statustime)
196 			printtime(sp->st_ctime);
197 		else
198 			printtime(sp->st_mtime);
199 #ifdef COLORLS
200 		if (f_color)
201 			color_printed = colortype(sp->st_mode);
202 #endif
203 		(void)printname(p->fts_name);
204 #ifdef COLORLS
205 		if (f_color && color_printed)
206 			endcolor(0);
207 #endif
208 		if (f_type)
209 			(void)printtype(sp->st_mode);
210 		if (S_ISLNK(sp->st_mode))
211 			printlink(p);
212 		(void)putchar('\n');
213 	}
214 }
215 
216 void
217 printstream(const DISPLAY *dp)
218 {
219 	FTSENT *p;
220 	int chcnt;
221 
222 	for (p = dp->list, chcnt = 0; p; p = p->fts_link) {
223 		if (p->fts_number == NO_PRINT)
224 			continue;
225 		/* XXX strlen does not take octal escapes into account. */
226 		if (strlen(p->fts_name) + chcnt +
227 		    (p->fts_link ? 2 : 0) >= (unsigned)termwidth) {
228 			putchar('\n');
229 			chcnt = 0;
230 		}
231 		chcnt += printaname(p, dp->s_inode, dp->s_block);
232 		if (p->fts_link) {
233 			printf(", ");
234 			chcnt += 2;
235 		}
236 	}
237 	if (chcnt)
238 		putchar('\n');
239 }
240 
241 void
242 printcol(const DISPLAY *dp)
243 {
244 	static FTSENT **array;
245 	static int lastentries = -1;
246 	FTSENT *p;
247 	FTSENT **narray;
248 	int base;
249 	int chcnt;
250 	int cnt;
251 	int col;
252 	int colwidth;
253 	int endcol;
254 	int num;
255 	int numcols;
256 	int numrows;
257 	int row;
258 	int tabwidth;
259 
260 	if (f_notabs)
261 		tabwidth = 1;
262 	else
263 		tabwidth = 8;
264 
265 	/*
266 	 * Have to do random access in the linked list -- build a table
267 	 * of pointers.
268 	 */
269 	if (dp->entries > lastentries) {
270 		if ((narray =
271 		    realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
272 			warn(NULL);
273 			printscol(dp);
274 			return;
275 		}
276 		lastentries = dp->entries;
277 		array = narray;
278 	}
279 	for (p = dp->list, num = 0; p; p = p->fts_link)
280 		if (p->fts_number != NO_PRINT)
281 			array[num++] = p;
282 
283 	colwidth = dp->maxlen;
284 	if (f_inode)
285 		colwidth += dp->s_inode + 1;
286 	if (f_size)
287 		colwidth += dp->s_block + 1;
288 	if (f_type)
289 		colwidth += 1;
290 
291 	colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
292 	if (termwidth < 2 * colwidth) {
293 		printscol(dp);
294 		return;
295 	}
296 	numcols = termwidth / colwidth;
297 	numrows = num / numcols;
298 	if (num % numcols)
299 		++numrows;
300 
301 	if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
302 	    (f_longform || f_size)) {
303 		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
304 	}
305 
306 	base = 0;
307 	for (row = 0; row < numrows; ++row) {
308 		endcol = colwidth;
309 		if (!f_sortacross)
310 			base = row;
311 		for (col = 0, chcnt = 0; col < numcols; ++col) {
312 			chcnt += printaname(array[base], dp->s_inode,
313 			    dp->s_block);
314 			if (f_sortacross)
315 				base++;
316 			else
317 				base += numrows;
318 			if (base >= num)
319 				break;
320 			while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
321 			    <= endcol) {
322 				if (f_sortacross && col + 1 >= numcols)
323 					break;
324 				(void)putchar(f_notabs ? ' ' : '\t');
325 				chcnt = cnt;
326 			}
327 			endcol += colwidth;
328 		}
329 		(void)putchar('\n');
330 	}
331 }
332 
333 /*
334  * print [inode] [size] name
335  * return # of characters printed, no trailing characters.
336  */
337 static int
338 printaname(const FTSENT *p, u_long inodefield, u_long sizefield)
339 {
340 	struct stat *sp;
341 	int chcnt;
342 #ifdef COLORLS
343 	int color_printed = 0;
344 #endif
345 
346 	sp = p->fts_statp;
347 	chcnt = 0;
348 	if (f_inode)
349 		chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
350 	if (f_size)
351 		chcnt += printf("%*jd ",
352 		    (int)sizefield, howmany(sp->st_blocks, blocksize));
353 #ifdef COLORLS
354 	if (f_color)
355 		color_printed = colortype(sp->st_mode);
356 #endif
357 	chcnt += printname(p->fts_name);
358 #ifdef COLORLS
359 	if (f_color && color_printed)
360 		endcolor(0);
361 #endif
362 	if (f_type)
363 		chcnt += printtype(sp->st_mode);
364 	return (chcnt);
365 }
366 
367 static void
368 printtime(time_t ftime)
369 {
370 	char longstring[80];
371 	static time_t now = 0;
372 	const char *format;
373 	static int d_first = -1;
374 
375 	if (d_first < 0)
376 		d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
377 	if (now == 0)
378 		now = time(NULL);
379 
380 #define	SIXMONTHS	((365 / 2) * 86400)
381 	if (f_timeformat)  /* user specified format */
382 		format = f_timeformat;
383 	else if (f_sectime)
384 		/* mmm dd hh:mm:ss yyyy || dd mmm hh:mm:ss yyyy */
385 		format = d_first ? "%e %b %T %Y" : "%b %e %T %Y";
386 	else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
387 		/* mmm dd hh:mm || dd mmm hh:mm */
388 		format = d_first ? "%e %b %R" : "%b %e %R";
389 	else
390 		/* mmm dd  yyyy || dd mmm  yyyy */
391 		format = d_first ? "%e %b  %Y" : "%b %e  %Y";
392 	strftime(longstring, sizeof(longstring), format, localtime(&ftime));
393 	fputs(longstring, stdout);
394 	fputc(' ', stdout);
395 }
396 
397 static int
398 printtype(u_int mode)
399 {
400 
401 	if (f_slash) {
402 		if ((mode & S_IFMT) == S_IFDIR) {
403 			(void)putchar('/');
404 			return (1);
405 		}
406 		return (0);
407 	}
408 
409 	switch (mode & S_IFMT) {
410 	case S_IFDIR:
411 		(void)putchar('/');
412 		return (1);
413 	case S_IFIFO:
414 		(void)putchar('|');
415 		return (1);
416 	case S_IFLNK:
417 		(void)putchar('@');
418 		return (1);
419 	case S_IFSOCK:
420 		(void)putchar('=');
421 		return (1);
422 	case S_IFWHT:
423 		(void)putchar('%');
424 		return (1);
425 	default:
426 		break;
427 	}
428 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
429 		(void)putchar('*');
430 		return (1);
431 	}
432 	return (0);
433 }
434 
435 #ifdef COLORLS
436 static int
437 putch(int c)
438 {
439 	(void)putchar(c);
440 	return 0;
441 }
442 
443 static int
444 writech(int c)
445 {
446 	char tmp = (char)c;
447 
448 	(void)write(STDOUT_FILENO, &tmp, 1);
449 	return 0;
450 }
451 
452 static void
453 printcolor(Colors c)
454 {
455 	char *ansiseq;
456 
457 	if (colors[c].bold)
458 		tputs(enter_bold, 1, putch);
459 
460 	if (colors[c].num[0] != -1) {
461 		ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
462 		if (ansiseq)
463 			tputs(ansiseq, 1, putch);
464 	}
465 	if (colors[c].num[1] != -1) {
466 		ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
467 		if (ansiseq)
468 			tputs(ansiseq, 1, putch);
469 	}
470 }
471 
472 static void
473 endcolor(int sig)
474 {
475 	tputs(ansi_coloff, 1, sig ? writech : putch);
476 	tputs(attrs_off, 1, sig ? writech : putch);
477 }
478 
479 static int
480 colortype(mode_t mode)
481 {
482 	switch (mode & S_IFMT) {
483 	case S_IFDIR:
484 		if (mode & S_IWOTH)
485 			if (mode & S_ISTXT)
486 				printcolor(C_WSDIR);
487 			else
488 				printcolor(C_WDIR);
489 		else
490 			printcolor(C_DIR);
491 		return (1);
492 	case S_IFLNK:
493 		printcolor(C_LNK);
494 		return (1);
495 	case S_IFSOCK:
496 		printcolor(C_SOCK);
497 		return (1);
498 	case S_IFIFO:
499 		printcolor(C_FIFO);
500 		return (1);
501 	case S_IFBLK:
502 		printcolor(C_BLK);
503 		return (1);
504 	case S_IFCHR:
505 		printcolor(C_CHR);
506 		return (1);
507 	default:;
508 	}
509 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
510 		if (mode & S_ISUID)
511 			printcolor(C_SUID);
512 		else if (mode & S_ISGID)
513 			printcolor(C_SGID);
514 		else
515 			printcolor(C_EXEC);
516 		return (1);
517 	}
518 	return (0);
519 }
520 
521 void
522 parsecolors(const char *cs)
523 {
524 	int i;
525 	int j;
526 	size_t len;
527 	char c[2];
528 	short legacy_warn = 0;
529 
530 	if (cs == NULL)
531 		cs = "";	/* LSCOLORS not set */
532 	len = strlen(cs);
533 	for (i = 0; i < (int)C_NUMCOLORS; i++) {
534 		colors[i].bold = 0;
535 
536 		if (len <= 2 * (size_t)i) {
537 			c[0] = defcolors[2 * i];
538 			c[1] = defcolors[2 * i + 1];
539 		} else {
540 			c[0] = cs[2 * i];
541 			c[1] = cs[2 * i + 1];
542 		}
543 		for (j = 0; j < 2; j++) {
544 			/* Legacy colours used 0-7 */
545 			if (c[j] >= '0' && c[j] <= '7') {
546 				colors[i].num[j] = c[j] - '0';
547 				if (!legacy_warn) {
548 					warnx("LSCOLORS should use "
549 					    "characters a-h instead of 0-9 ("
550 					    "see the manual page)");
551 				}
552 				legacy_warn = 1;
553 			} else if (c[j] >= 'a' && c[j] <= 'h')
554 				colors[i].num[j] = c[j] - 'a';
555 			else if (c[j] >= 'A' && c[j] <= 'H') {
556 				colors[i].num[j] = c[j] - 'A';
557 				colors[i].bold = 1;
558 			} else if (tolower((unsigned char)c[j]) == 'x')
559 				colors[i].num[j] = -1;
560 			else {
561 				warnx("invalid character '%c' in LSCOLORS"
562 				    " env var", c[j]);
563 				colors[i].num[j] = -1;
564 			}
565 		}
566 	}
567 }
568 
569 void
570 colorquit(int sig)
571 {
572 	endcolor(sig);
573 
574 	(void)signal(sig, SIG_DFL);
575 	(void)kill(getpid(), sig);
576 }
577 
578 #endif /* COLORLS */
579 
580 static void
581 printlink(const FTSENT *p)
582 {
583 	int lnklen;
584 	char name[MAXPATHLEN + 1];
585 	char path[MAXPATHLEN + 1];
586 
587 	if (p->fts_level == FTS_ROOTLEVEL)
588 		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
589 	else
590 		(void)snprintf(name, sizeof(name),
591 		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
592 	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
593 		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
594 		return;
595 	}
596 	path[lnklen] = '\0';
597 	(void)printf(" -> ");
598 	(void)printname(path);
599 }
600 
601 static void
602 printsize(size_t width, off_t bytes)
603 {
604 
605 	if (f_humanval) {
606 		char buf[5];
607 
608 		humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
609 		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
610 		(void)printf("%5s ", buf);
611 	} else
612 		(void)printf("%*jd ", (u_int)width, bytes);
613 }
614 
615 static void
616 aclmode(char *buf, const FTSENT *p, int *haveacls)
617 {
618 	char name[MAXPATHLEN + 1];
619 	int entries, ret;
620 	acl_t facl;
621 	acl_entry_t ae;
622 
623 	/*
624 	 * Add a + after the standard rwxrwxrwx mode if the file has an
625 	 * extended ACL. strmode() reserves space at the end of the string.
626 	 */
627 	if (p->fts_level == FTS_ROOTLEVEL)
628 		snprintf(name, sizeof(name), "%s", p->fts_name);
629 	else
630 		snprintf(name, sizeof(name), "%s/%s",
631 		    p->fts_parent->fts_accpath, p->fts_name);
632 	/*
633 	 * We have no way to tell whether a symbolic link has an ACL since
634 	 * pathconf() and acl_get_file() both follow them.  They also don't
635 	 * support whiteouts.
636 	 */
637 	if (S_ISLNK(p->fts_statp->st_mode) || S_ISWHT(p->fts_statp->st_mode)) {
638 		*haveacls = 1;
639 		return;
640 	}
641 	if ((ret = pathconf(name, _PC_ACL_EXTENDED)) <= 0) {
642 		if (ret < 0 && errno != EINVAL)
643 			warn("%s", name);
644 		else
645 			*haveacls = 0;
646 		return;
647 	}
648 	*haveacls = 1;
649 	if ((facl = acl_get_file(name, ACL_TYPE_ACCESS)) != NULL) {
650 		if (acl_get_entry(facl, ACL_FIRST_ENTRY, &ae) == 1) {
651 			entries = 1;
652 			while (acl_get_entry(facl, ACL_NEXT_ENTRY, &ae) == 1)
653 				if (++entries > 3)
654 					break;
655 			/*
656 			 * POSIX.1e requires that ACLs of type ACL_TYPE_ACCESS
657 			 * must have at least three entries (owner, group,
658 			 * and other). So anything with more than 3 ACLs looks
659 			 * interesting to us.
660 			 */
661 			if (entries > 3)
662 				buf[10] = '+';
663 		}
664 		acl_free(facl);
665 	} else
666 		warn("%s", name);
667 }
668