xref: /freebsd/bin/ls/print.c (revision 3193579b66fd7067f898dbc54bdea81a0e6f9bd0)
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(const 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 *, const 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(const 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(const 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("%*jd ",
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%*jd ",
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(const DISPLAY *dp)
239 {
240 	FTSENT *p;
241 	int chcnt;
242 
243 	for (p = dp->list, chcnt = 0; p; p = p->fts_link) {
244 		if (p->fts_number == NO_PRINT)
245 			continue;
246 		if (strlen(p->fts_name) + chcnt +
247 		    (p->fts_link ? 2 : 0) >= (unsigned)termwidth) {
248 			putchar('\n');
249 			chcnt = 0;
250 		}
251 		chcnt += printaname(p, dp->s_inode, dp->s_block);
252 		if (p->fts_link) {
253 			printf(", ");
254 			chcnt += 2;
255 		}
256 	}
257 	if (chcnt)
258 		putchar('\n');
259 }
260 
261 void
262 printcol(const DISPLAY *dp)
263 {
264 	static FTSENT **array;
265 	static int lastentries = -1;
266 	FTSENT *p;
267 	FTSENT **narray;
268 	int base;
269 	int chcnt;
270 	int cnt;
271 	int col;
272 	int colwidth;
273 	int endcol;
274 	int num;
275 	int numcols;
276 	int numrows;
277 	int row;
278 	int tabwidth;
279 
280 	if (f_notabs)
281 		tabwidth = 1;
282 	else
283 		tabwidth = 8;
284 
285 	/*
286 	 * Have to do random access in the linked list -- build a table
287 	 * of pointers.
288 	 */
289 	if (dp->entries > lastentries) {
290 		if ((narray =
291 		    realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
292 			warn(NULL);
293 			printscol(dp);
294 			return;
295 		}
296 		lastentries = dp->entries;
297 		array = narray;
298 	}
299 	for (p = dp->list, num = 0; p; p = p->fts_link)
300 		if (p->fts_number != NO_PRINT)
301 			array[num++] = p;
302 
303 	colwidth = dp->maxlen;
304 	if (f_inode)
305 		colwidth += dp->s_inode + 1;
306 	if (f_size)
307 		colwidth += dp->s_block + 1;
308 	if (f_type)
309 		colwidth += 1;
310 
311 	colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
312 	if (termwidth < 2 * colwidth) {
313 		printscol(dp);
314 		return;
315 	}
316 	numcols = termwidth / colwidth;
317 	numrows = num / numcols;
318 	if (num % numcols)
319 		++numrows;
320 
321 	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
322 		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
323 
324 	base = 0;
325 	for (row = 0; row < numrows; ++row) {
326 		endcol = colwidth;
327 		if (!f_sortacross)
328 			base = row;
329 		for (col = 0, chcnt = 0; col < numcols; ++col) {
330 			chcnt += printaname(array[base], dp->s_inode,
331 			    dp->s_block);
332 			if (f_sortacross)
333 				base++;
334 			else
335 				base += numrows;
336 			if (base >= num)
337 				break;
338 			while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
339 			    <= endcol) {
340 				if (f_sortacross && col + 1 >= numcols)
341 					break;
342 				(void)putchar(f_notabs ? ' ' : '\t');
343 				chcnt = cnt;
344 			}
345 			endcol += colwidth;
346 		}
347 		(void)putchar('\n');
348 	}
349 }
350 
351 /*
352  * print [inode] [size] name
353  * return # of characters printed, no trailing characters.
354  */
355 static int
356 printaname(const FTSENT *p, u_long inodefield, u_long sizefield)
357 {
358 	struct stat *sp;
359 	int chcnt;
360 #ifdef COLORLS
361 	int color_printed = 0;
362 #endif
363 
364 	sp = p->fts_statp;
365 	chcnt = 0;
366 	if (f_inode)
367 		chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
368 	if (f_size)
369 		chcnt += printf("%*jd ",
370 		    (int)sizefield, howmany(sp->st_blocks, blocksize));
371 #ifdef COLORLS
372 	if (f_color)
373 		color_printed = colortype(sp->st_mode);
374 #endif
375 	chcnt += printname(p->fts_name);
376 #ifdef COLORLS
377 	if (f_color && color_printed)
378 		endcolor(0);
379 #endif
380 	if (f_type)
381 		chcnt += printtype(sp->st_mode);
382 	return (chcnt);
383 }
384 
385 static void
386 printtime(time_t ftime)
387 {
388 	char longstring[80];
389 	static time_t now = 0;
390 	const char *format;
391 	static int d_first = -1;
392 
393 	if (d_first < 0)
394 		d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
395 	if (now == 0)
396 		now = time(NULL);
397 
398 #define	SIXMONTHS	((365 / 2) * 86400)
399 	if (f_sectime)
400 		/* mmm dd hh:mm:ss yyyy || dd mmm hh:mm:ss yyyy */
401 		format = d_first ? "%e %b %T %Y " : "%b %e %T %Y ";
402 	else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
403 		/* mmm dd hh:mm || dd mmm hh:mm */
404 		format = d_first ? "%e %b %R " : "%b %e %R ";
405 	else
406 		/* mmm dd  yyyy || dd mmm  yyyy */
407 		format = d_first ? "%e %b  %Y " : "%b %e  %Y ";
408 	strftime(longstring, sizeof(longstring), format, localtime(&ftime));
409 	fputs(longstring, stdout);
410 }
411 
412 static int
413 printtype(u_int mode)
414 {
415 
416 	if (f_slash) {
417 		if ((mode & S_IFMT) == S_IFDIR) {
418 			(void)putchar('/');
419 			return (1);
420 		}
421 		return (0);
422 	}
423 
424 	switch (mode & S_IFMT) {
425 	case S_IFDIR:
426 		(void)putchar('/');
427 		return (1);
428 	case S_IFIFO:
429 		(void)putchar('|');
430 		return (1);
431 	case S_IFLNK:
432 		(void)putchar('@');
433 		return (1);
434 	case S_IFSOCK:
435 		(void)putchar('=');
436 		return (1);
437 	case S_IFWHT:
438 		(void)putchar('%');
439 		return (1);
440 	default:
441 		break;
442 	}
443 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
444 		(void)putchar('*');
445 		return (1);
446 	}
447 	return (0);
448 }
449 
450 #ifdef COLORLS
451 static int
452 putch(int c)
453 {
454 	(void)putchar(c);
455 	return 0;
456 }
457 
458 static int
459 writech(int c)
460 {
461 	char tmp = (char)c;
462 
463 	(void)write(STDOUT_FILENO, &tmp, 1);
464 	return 0;
465 }
466 
467 static void
468 printcolor(Colors c)
469 {
470 	char *ansiseq;
471 
472 	if (colors[c].bold)
473 		tputs(enter_bold, 1, putch);
474 
475 	if (colors[c].num[0] != -1) {
476 		ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
477 		if (ansiseq)
478 			tputs(ansiseq, 1, putch);
479 	}
480 	if (colors[c].num[1] != -1) {
481 		ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
482 		if (ansiseq)
483 			tputs(ansiseq, 1, putch);
484 	}
485 }
486 
487 static void
488 endcolor(int sig)
489 {
490 	tputs(ansi_coloff, 1, sig ? writech : putch);
491 	tputs(attrs_off, 1, sig ? writech : putch);
492 }
493 
494 static int
495 colortype(mode_t mode)
496 {
497 	switch (mode & S_IFMT) {
498 	case S_IFDIR:
499 		if (mode & S_IWOTH)
500 			if (mode & S_ISTXT)
501 				printcolor(C_WSDIR);
502 			else
503 				printcolor(C_WDIR);
504 		else
505 			printcolor(C_DIR);
506 		return (1);
507 	case S_IFLNK:
508 		printcolor(C_LNK);
509 		return (1);
510 	case S_IFSOCK:
511 		printcolor(C_SOCK);
512 		return (1);
513 	case S_IFIFO:
514 		printcolor(C_FIFO);
515 		return (1);
516 	case S_IFBLK:
517 		printcolor(C_BLK);
518 		return (1);
519 	case S_IFCHR:
520 		printcolor(C_CHR);
521 		return (1);
522 	default:;
523 	}
524 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
525 		if (mode & S_ISUID)
526 			printcolor(C_SUID);
527 		else if (mode & S_ISGID)
528 			printcolor(C_SGID);
529 		else
530 			printcolor(C_EXEC);
531 		return (1);
532 	}
533 	return (0);
534 }
535 
536 void
537 parsecolors(const char *cs)
538 {
539 	int i;
540 	int j;
541 	size_t len;
542 	char c[2];
543 	short legacy_warn = 0;
544 
545 	if (cs == NULL)
546 		cs = "";	/* LSCOLORS not set */
547 	len = strlen(cs);
548 	for (i = 0; i < (int)C_NUMCOLORS; i++) {
549 		colors[i].bold = 0;
550 
551 		if (len <= 2 * (size_t)i) {
552 			c[0] = defcolors[2 * i];
553 			c[1] = defcolors[2 * i + 1];
554 		} else {
555 			c[0] = cs[2 * i];
556 			c[1] = cs[2 * i + 1];
557 		}
558 		for (j = 0; j < 2; j++) {
559 			/* Legacy colours used 0-7 */
560 			if (c[j] >= '0' && c[j] <= '7') {
561 				colors[i].num[j] = c[j] - '0';
562 				if (!legacy_warn) {
563 					warnx("LSCOLORS should use "
564 					    "characters a-h instead of 0-9 ("
565 					    "see the manual page)");
566 				}
567 				legacy_warn = 1;
568 			} else if (c[j] >= 'a' && c[j] <= 'h')
569 				colors[i].num[j] = c[j] - 'a';
570 			else if (c[j] >= 'A' && c[j] <= 'H') {
571 				colors[i].num[j] = c[j] - 'A';
572 				colors[i].bold = 1;
573 			} else if (tolower((unsigned char)c[j]) == 'x')
574 				colors[i].num[j] = -1;
575 			else {
576 				warnx("invalid character '%c' in LSCOLORS"
577 				    " env var", c[j]);
578 				colors[i].num[j] = -1;
579 			}
580 		}
581 	}
582 }
583 
584 void
585 colorquit(int sig)
586 {
587 	endcolor(sig);
588 
589 	(void)signal(sig, SIG_DFL);
590 	(void)kill(getpid(), sig);
591 }
592 
593 #endif /* COLORLS */
594 
595 static void
596 printlink(const FTSENT *p)
597 {
598 	int lnklen;
599 	char name[MAXPATHLEN + 1];
600 	char path[MAXPATHLEN + 1];
601 
602 	if (p->fts_level == FTS_ROOTLEVEL)
603 		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
604 	else
605 		(void)snprintf(name, sizeof(name),
606 		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
607 	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
608 		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
609 		return;
610 	}
611 	path[lnklen] = '\0';
612 	(void)printf(" -> ");
613 	(void)printname(path);
614 }
615 
616 static void
617 printsize(size_t width, off_t bytes)
618 {
619 	double dbytes;
620 	unit_t unit;
621 
622 	if (f_humanval) {
623 		dbytes = bytes;
624 		unit = unit_adjust(&dbytes);
625 
626 		if (dbytes == 0)
627 			(void)printf("%*s ", (u_int)width, "0B");
628 		else
629 			(void)printf("%*.*f%c ", (u_int)width - 1,
630 			    dbytes > 10 ? 0 : 1, dbytes, "BKMGTPE"[unit]);
631 	} else
632 		(void)printf("%*jd ", (u_int)width, bytes);
633 }
634 
635 /*
636  * Output in "human-readable" format.  Uses 3 digits max and puts
637  * unit suffixes at the end.  Makes output compact and easy to read,
638  * especially on huge disks.
639  *
640  */
641 static unit_t
642 unit_adjust(double *val)
643 {
644 	double abval;
645 	unit_t unit;
646 	u_int unit_sz;
647 
648 	abval = fabs(*val);
649 
650 	unit_sz = abval ? (u_int)ilogb(abval) / 10 : 0;
651 
652 	if (unit_sz >= (u_int)UNIT_MAX) {
653 		unit = NONE;
654 	} else {
655 		unit = unitp[unit_sz];
656 		*val /= (double)vals_base2[unit_sz];
657 	}
658 
659 	return (unit);
660 }
661 
662 static void
663 aclmode(char *buf, const FTSENT *p, int *haveacls)
664 {
665 	char name[MAXPATHLEN + 1];
666 	int entries, ret;
667 	acl_t facl;
668 	acl_entry_t ae;
669 
670 	/*
671 	 * Add a + after the standard rwxrwxrwx mode if the file has an
672 	 * extended ACL. strmode() reserves space at the end of the string.
673 	 */
674 	if (p->fts_level == FTS_ROOTLEVEL)
675 		snprintf(name, sizeof(name), "%s", p->fts_name);
676 	else
677 		snprintf(name, sizeof(name), "%s/%s",
678 		    p->fts_parent->fts_accpath, p->fts_name);
679 	/*
680 	 * We have no way to tell whether a symbolic link has an ACL since
681 	 * pathconf() and acl_get_file() both follow them.
682 	 */
683 	if (S_ISLNK(p->fts_statp->st_mode)) {
684 		*haveacls = 1;
685 		return;
686 	}
687 	if ((ret = pathconf(name, _PC_ACL_EXTENDED)) <= 0) {
688 		if (ret < 0 && errno != EINVAL)
689 			warn("%s", name);
690 		else
691 			*haveacls = 0;
692 		return;
693 	}
694 	*haveacls = 1;
695 	if ((facl = acl_get_file(name, ACL_TYPE_ACCESS)) != NULL) {
696 		if (acl_get_entry(facl, ACL_FIRST_ENTRY, &ae) == 1) {
697 			entries = 0;
698 			do
699 				entries++;
700 			while (acl_get_entry(facl, ACL_NEXT_ENTRY, &ae) == 1);
701 			if (entries != 3)
702 				buf[10] = '+';
703 		}
704 		acl_free(facl);
705 	} else
706 		warn("%s", name);
707 }
708