xref: /freebsd/bin/ls/print.c (revision 68e7a217f8019b955f87547f218e95ab237597af)
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 #include <sys/cdefs.h>
38 
39 __FBSDID("$FreeBSD$");
40 
41 #if 0
42 #ifndef lint
43 static char sccsid[] = "@(#)print.c	8.4 (Berkeley) 4/17/94";
44 #endif /* not lint */
45 #endif
46 
47 #include <sys/param.h>
48 #include <sys/stat.h>
49 
50 #include <err.h>
51 #include <errno.h>
52 #include <fts.h>
53 #include <math.h>
54 #include <langinfo.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <time.h>
59 #include <unistd.h>
60 #ifdef COLORLS
61 #include <ctype.h>
62 #include <termcap.h>
63 #include <signal.h>
64 #endif
65 
66 #include "ls.h"
67 #include "extern.h"
68 
69 static int	printaname(FTSENT *, u_long, u_long);
70 static void	printlink(FTSENT *);
71 static void	printtime(time_t);
72 static int	printtype(u_int);
73 static void	printsize(size_t, off_t);
74 #ifdef COLORLS
75 static void	endcolor(int);
76 static int	colortype(mode_t);
77 #endif
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(off_t *);
99 
100 static int 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 static 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 
168 	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
169 		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
170 
171 	for (p = dp->list; p; p = p->fts_link) {
172 		if (IS_NOPRINT(p))
173 			continue;
174 		sp = p->fts_statp;
175 		if (f_inode)
176 			(void)printf("%*lu ", dp->s_inode, (u_long)sp->st_ino);
177 		if (f_size)
178 			(void)printf("%*lld ",
179 			    dp->s_block, howmany(sp->st_blocks, blocksize));
180 		strmode(sp->st_mode, buf);
181 		np = p->fts_pointer;
182 		(void)printf("%s %*u %-*s  %-*s  ", buf, dp->s_nlink,
183 		    sp->st_nlink, dp->s_user, np->user, dp->s_group,
184 		    np->group);
185 		if (f_flags)
186 			(void)printf("%-*s ", dp->s_flags, np->flags);
187 		if (f_lomac)
188 			(void)printf("%-*s ", dp->s_lattr, np->lattr);
189 		if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
190 			if (minor(sp->st_rdev) > 255 || minor(sp->st_rdev) < 0)
191 				(void)printf("%3d, 0x%08x ",
192 				    major(sp->st_rdev),
193 				    (u_int)minor(sp->st_rdev));
194 			else
195 				(void)printf("%3d, %3d ",
196 				    major(sp->st_rdev), minor(sp->st_rdev));
197 		else if (dp->bcfile)
198 			(void)printf("%*s%*lld ",
199 			    8 - dp->s_size, "", dp->s_size, sp->st_size);
200 		else
201 			printsize(dp->s_size, sp->st_size);
202 		if (f_accesstime)
203 			printtime(sp->st_atime);
204 		else if (f_statustime)
205 			printtime(sp->st_ctime);
206 		else
207 			printtime(sp->st_mtime);
208 #ifdef COLORLS
209 		if (f_color)
210 			color_printed = colortype(sp->st_mode);
211 #endif
212 		(void)printname(p->fts_name);
213 #ifdef COLORLS
214 		if (f_color && color_printed)
215 			endcolor(0);
216 #endif
217 		if (f_type)
218 			(void)printtype(sp->st_mode);
219 		if (S_ISLNK(sp->st_mode))
220 			printlink(p);
221 		(void)putchar('\n');
222 	}
223 }
224 
225 void
226 printstream(DISPLAY *dp)
227 {
228 	FTSENT *p;
229 	extern int termwidth;
230 	int chcnt;
231 
232 	for (p = dp->list, chcnt = 0; p; p = p->fts_link) {
233 		if (p->fts_number == NO_PRINT)
234 			continue;
235 		if (strlen(p->fts_name) + chcnt +
236 		    (p->fts_link ? 2 : 0) >= (unsigned)termwidth) {
237 			putchar('\n');
238 			chcnt = 0;
239 		}
240 		chcnt += printaname(p, dp->s_inode, dp->s_block);
241 		if (p->fts_link) {
242 			printf(", ");
243 			chcnt += 2;
244 		}
245 	}
246 	if (chcnt)
247 		putchar('\n');
248 }
249 
250 void
251 printcol(DISPLAY *dp)
252 {
253 	extern int termwidth;
254 	static FTSENT **array;
255 	static int lastentries = -1;
256 	FTSENT *p;
257 	int base;
258 	int chcnt;
259 	int cnt;
260 	int col;
261 	int colwidth;
262 	int endcol;
263 	int num;
264 	int numcols;
265 	int numrows;
266 	int row;
267 	int tabwidth;
268 
269 	if (f_notabs)
270 		tabwidth = 1;
271 	else
272 		tabwidth = 8;
273 
274 	/*
275 	 * Have to do random access in the linked list -- build a table
276 	 * of pointers.
277 	 */
278 	if (dp->entries > lastentries) {
279 		lastentries = dp->entries;
280 		if ((array =
281 		    realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
282 			warn(NULL);
283 			printscol(dp);
284 		}
285 	}
286 	for (p = dp->list, num = 0; p; p = p->fts_link)
287 		if (p->fts_number != NO_PRINT)
288 			array[num++] = p;
289 
290 	colwidth = dp->maxlen;
291 	if (f_inode)
292 		colwidth += dp->s_inode + 1;
293 	if (f_size)
294 		colwidth += dp->s_block + 1;
295 	if (f_type)
296 		colwidth += 1;
297 
298 	colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
299 	if (termwidth < 2 * colwidth) {
300 		printscol(dp);
301 		return;
302 	}
303 	numcols = termwidth / colwidth;
304 	numrows = num / numcols;
305 	if (num % numcols)
306 		++numrows;
307 
308 	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
309 		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
310 
311 	if (f_sortacross)
312 		base = 0;
313 	for (row = 0; row < numrows; ++row) {
314 		endcol = colwidth;
315 		if (!f_sortacross)
316 			base = row;
317 		for (col = 0, chcnt = 0; col < numcols; ++col) {
318 			chcnt += printaname(array[base], dp->s_inode,
319 			    dp->s_block);
320 			if (f_sortacross)
321 				base++;
322 			else
323 				base += numrows;
324 			if (base >= num)
325 				break;
326 			while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
327 			    <= endcol) {
328 				if (f_sortacross && col + 1 >= numcols)
329 					break;
330 				(void)putchar(f_notabs ? ' ' : '\t');
331 				chcnt = cnt;
332 			}
333 			endcol += colwidth;
334 		}
335 		(void)putchar('\n');
336 	}
337 }
338 
339 /*
340  * print [inode] [size] name
341  * return # of characters printed, no trailing characters.
342  */
343 static int
344 printaname(FTSENT *p, u_long inodefield, u_long sizefield)
345 {
346 	struct stat *sp;
347 	int chcnt;
348 #ifdef COLORLS
349 	int color_printed = 0;
350 #endif
351 
352 	sp = p->fts_statp;
353 	chcnt = 0;
354 	if (f_inode)
355 		chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
356 	if (f_size)
357 		chcnt += printf("%*lld ",
358 		    (int)sizefield, howmany(sp->st_blocks, blocksize));
359 #ifdef COLORLS
360 	if (f_color)
361 		color_printed = colortype(sp->st_mode);
362 #endif
363 	chcnt += printname(p->fts_name);
364 #ifdef COLORLS
365 	if (f_color && color_printed)
366 		endcolor(0);
367 #endif
368 	if (f_type)
369 		chcnt += printtype(sp->st_mode);
370 	return (chcnt);
371 }
372 
373 static void
374 printtime(time_t ftime)
375 {
376 	char longstring[80];
377 	static time_t now;
378 	const char *format;
379 	static int d_first = -1;
380 
381 	if (d_first < 0)
382 		d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
383 	if (now == 0)
384 		now = time(NULL);
385 
386 #define	SIXMONTHS	((365 / 2) * 86400)
387 	if (f_sectime)
388 		/* mmm dd hh:mm:ss yyyy || dd mmm hh:mm:ss yyyy */
389 		format = d_first ? "%e %b %T %Y " : "%b %e %T %Y ";
390 	else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
391 		/* mmm dd hh:mm || dd mmm hh:mm */
392 		format = d_first ? "%e %b %R " : "%b %e %R ";
393 	else
394 		/* mmm dd  yyyy || dd mmm  yyyy */
395 		format = d_first ? "%e %b  %Y " : "%b %e  %Y ";
396 	strftime(longstring, sizeof(longstring), format, localtime(&ftime));
397 	fputs(longstring, stdout);
398 }
399 
400 static int
401 printtype(u_int mode)
402 {
403 
404 	if (f_slash) {
405 		if ((mode & S_IFMT) == S_IFDIR) {
406 			(void)putchar('/');
407 			return (1);
408 		}
409 		return (0);
410 	}
411 
412 	switch (mode & S_IFMT) {
413 	case S_IFDIR:
414 		(void)putchar('/');
415 		return (1);
416 	case S_IFIFO:
417 		(void)putchar('|');
418 		return (1);
419 	case S_IFLNK:
420 		(void)putchar('@');
421 		return (1);
422 	case S_IFSOCK:
423 		(void)putchar('=');
424 		return (1);
425 	case S_IFWHT:
426 		(void)putchar('%');
427 		return (1);
428 	default:
429 		break;
430 	}
431 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
432 		(void)putchar('*');
433 		return (1);
434 	}
435 	return (0);
436 }
437 
438 #ifdef COLORLS
439 static int
440 putch(int c)
441 {
442 	(void)putchar(c);
443 	return 0;
444 }
445 
446 static int
447 writech(int c)
448 {
449 	char tmp = c;
450 
451 	(void)write(STDOUT_FILENO, &tmp, 1);
452 	return 0;
453 }
454 
455 static void
456 printcolor(Colors c)
457 {
458 	char *ansiseq;
459 
460 	if (colors[c].bold)
461 		tputs(enter_bold, 1, putch);
462 
463 	if (colors[c].num[0] != -1) {
464 		ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
465 		if (ansiseq)
466 			tputs(ansiseq, 1, putch);
467 	}
468 	if (colors[c].num[1] != -1) {
469 		ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
470 		if (ansiseq)
471 			tputs(ansiseq, 1, putch);
472 	}
473 }
474 
475 static void
476 endcolor(int sig)
477 {
478 	tputs(ansi_coloff, 1, sig ? writech : putch);
479 	tputs(attrs_off, 1, sig ? writech : putch);
480 }
481 
482 static int
483 colortype(mode_t mode)
484 {
485 	switch (mode & S_IFMT) {
486 	case S_IFDIR:
487 		if (mode & S_IWOTH)
488 			if (mode & S_ISTXT)
489 				printcolor(C_WSDIR);
490 			else
491 				printcolor(C_WDIR);
492 		else
493 			printcolor(C_DIR);
494 		return (1);
495 	case S_IFLNK:
496 		printcolor(C_LNK);
497 		return (1);
498 	case S_IFSOCK:
499 		printcolor(C_SOCK);
500 		return (1);
501 	case S_IFIFO:
502 		printcolor(C_FIFO);
503 		return (1);
504 	case S_IFBLK:
505 		printcolor(C_BLK);
506 		return (1);
507 	case S_IFCHR:
508 		printcolor(C_CHR);
509 		return (1);
510 	}
511 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
512 		if (mode & S_ISUID)
513 			printcolor(C_SUID);
514 		else if (mode & S_ISGID)
515 			printcolor(C_SGID);
516 		else
517 			printcolor(C_EXEC);
518 		return (1);
519 	}
520 	return (0);
521 }
522 
523 void
524 parsecolors(const char *cs)
525 {
526 	int i;
527 	int j;
528 	int len;
529 	char c[2];
530 	short legacy_warn = 0;
531 
532 	if (cs == NULL)
533 		cs = "";	/* LSCOLORS not set */
534 	len = strlen(cs);
535 	for (i = 0; i < C_NUMCOLORS; i++) {
536 		colors[i].bold = 0;
537 
538 		if (len <= 2 * i) {
539 			c[0] = defcolors[2 * i];
540 			c[1] = defcolors[2 * i + 1];
541 		} else {
542 			c[0] = cs[2 * i];
543 			c[1] = cs[2 * i + 1];
544 		}
545 		for (j = 0; j < 2; j++) {
546 			/* Legacy colours used 0-7 */
547 			if (c[j] >= '0' && c[j] <= '7') {
548 				colors[i].num[j] = c[j] - '0';
549 				if (!legacy_warn) {
550 					fprintf(stderr,
551 					    "warn: LSCOLORS should use "
552 					    "characters a-h instead of 0-9 ("
553 					    "see the manual page)\n");
554 				}
555 				legacy_warn = 1;
556 			} else if (c[j] >= 'a' && c[j] <= 'h')
557 				colors[i].num[j] = c[j] - 'a';
558 			else if (c[j] >= 'A' && c[j] <= 'H') {
559 				colors[i].num[j] = c[j] - 'A';
560 				colors[i].bold = 1;
561 			} else if (tolower((unsigned char)c[j] == 'x'))
562 				colors[i].num[j] = -1;
563 			else {
564 				fprintf(stderr,
565 				    "error: invalid character '%c' in LSCOLORS"
566 				    " env var\n", c[j]);
567 				colors[i].num[j] = -1;
568 			}
569 		}
570 	}
571 }
572 
573 void
574 colorquit(int sig)
575 {
576 	endcolor(sig);
577 
578 	(void)signal(sig, SIG_DFL);
579 	(void)kill(getpid(), sig);
580 }
581 
582 #endif /* COLORLS */
583 
584 static void
585 printlink(FTSENT *p)
586 {
587 	int lnklen;
588 	char name[MAXPATHLEN + 1];
589 	char path[MAXPATHLEN + 1];
590 
591 	if (p->fts_level == FTS_ROOTLEVEL)
592 		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
593 	else
594 		(void)snprintf(name, sizeof(name),
595 		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
596 	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
597 		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
598 		return;
599 	}
600 	path[lnklen] = '\0';
601 	(void)printf(" -> ");
602 	(void)printname(path);
603 }
604 
605 static void
606 printsize(size_t width, off_t bytes)
607 {
608 	unit_t unit;
609 
610 	if (f_humanval) {
611 		unit = unit_adjust(&bytes);
612 
613 		if (bytes == 0)
614 			(void)printf("%*s ", width, "0B");
615 		else
616 			(void)printf("%*lld%c ", width - 1, bytes,
617 			    "BKMGTPE"[unit]);
618 	} else
619 		(void)printf("%*lld ", width, bytes);
620 }
621 
622 /*
623  * Output in "human-readable" format.  Uses 3 digits max and puts
624  * unit suffixes at the end.  Makes output compact and easy to read,
625  * especially on huge disks.
626  *
627  */
628 unit_t
629 unit_adjust(off_t *val)
630 {
631 	double abval;
632 	unit_t unit;
633 	unsigned int unit_sz;
634 
635 	abval = fabs((double)*val);
636 
637 	unit_sz = abval ? ilogb(abval) / 10 : 0;
638 
639 	if (unit_sz >= UNIT_MAX) {
640 		unit = NONE;
641 	} else {
642 		unit = unitp[unit_sz];
643 		*val /= (double)vals_base2[unit_sz];
644 	}
645 
646 	return (unit);
647 }
648