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