print.c revision 157098
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
35static char sccsid[] = "@(#)print.c	8.4 (Berkeley) 4/17/94";
36#endif /* not lint */
37#endif
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: head/bin/ls/print.c 157098 2006-03-24 16:38:02Z jhb $");
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
64static int	printaname(const FTSENT *, u_long, u_long);
65static void	printlink(const FTSENT *);
66static void	printtime(time_t);
67static int	printtype(u_int);
68static void	printsize(size_t, off_t);
69#ifdef COLORLS
70static void	endcolor(int);
71static int	colortype(mode_t);
72#endif
73static 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> */
79typedef 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
96static const char *defcolors = "exfxcxdxbxegedabagacad";
97
98/* colors for file types */
99static struct {
100	int	num[2];
101	int	bold;
102} colors[C_NUMCOLORS];
103#endif
104
105void
106printscol(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 */
121int
122printname(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
132void
133printlong(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
216void
217printstream(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
241void
242printcol(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 */
337static int
338printaname(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
367static void
368printtime(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_sectime)
382		/* mmm dd hh:mm:ss yyyy || dd mmm hh:mm:ss yyyy */
383		format = d_first ? "%e %b %T %Y " : "%b %e %T %Y ";
384	else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
385		/* mmm dd hh:mm || dd mmm hh:mm */
386		format = d_first ? "%e %b %R " : "%b %e %R ";
387	else
388		/* mmm dd  yyyy || dd mmm  yyyy */
389		format = d_first ? "%e %b  %Y " : "%b %e  %Y ";
390	strftime(longstring, sizeof(longstring), format, localtime(&ftime));
391	fputs(longstring, stdout);
392}
393
394static int
395printtype(u_int mode)
396{
397
398	if (f_slash) {
399		if ((mode & S_IFMT) == S_IFDIR) {
400			(void)putchar('/');
401			return (1);
402		}
403		return (0);
404	}
405
406	switch (mode & S_IFMT) {
407	case S_IFDIR:
408		(void)putchar('/');
409		return (1);
410	case S_IFIFO:
411		(void)putchar('|');
412		return (1);
413	case S_IFLNK:
414		(void)putchar('@');
415		return (1);
416	case S_IFSOCK:
417		(void)putchar('=');
418		return (1);
419	case S_IFWHT:
420		(void)putchar('%');
421		return (1);
422	default:
423		break;
424	}
425	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
426		(void)putchar('*');
427		return (1);
428	}
429	return (0);
430}
431
432#ifdef COLORLS
433static int
434putch(int c)
435{
436	(void)putchar(c);
437	return 0;
438}
439
440static int
441writech(int c)
442{
443	char tmp = (char)c;
444
445	(void)write(STDOUT_FILENO, &tmp, 1);
446	return 0;
447}
448
449static void
450printcolor(Colors c)
451{
452	char *ansiseq;
453
454	if (colors[c].bold)
455		tputs(enter_bold, 1, putch);
456
457	if (colors[c].num[0] != -1) {
458		ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
459		if (ansiseq)
460			tputs(ansiseq, 1, putch);
461	}
462	if (colors[c].num[1] != -1) {
463		ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
464		if (ansiseq)
465			tputs(ansiseq, 1, putch);
466	}
467}
468
469static void
470endcolor(int sig)
471{
472	tputs(ansi_coloff, 1, sig ? writech : putch);
473	tputs(attrs_off, 1, sig ? writech : putch);
474}
475
476static int
477colortype(mode_t mode)
478{
479	switch (mode & S_IFMT) {
480	case S_IFDIR:
481		if (mode & S_IWOTH)
482			if (mode & S_ISTXT)
483				printcolor(C_WSDIR);
484			else
485				printcolor(C_WDIR);
486		else
487			printcolor(C_DIR);
488		return (1);
489	case S_IFLNK:
490		printcolor(C_LNK);
491		return (1);
492	case S_IFSOCK:
493		printcolor(C_SOCK);
494		return (1);
495	case S_IFIFO:
496		printcolor(C_FIFO);
497		return (1);
498	case S_IFBLK:
499		printcolor(C_BLK);
500		return (1);
501	case S_IFCHR:
502		printcolor(C_CHR);
503		return (1);
504	default:;
505	}
506	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
507		if (mode & S_ISUID)
508			printcolor(C_SUID);
509		else if (mode & S_ISGID)
510			printcolor(C_SGID);
511		else
512			printcolor(C_EXEC);
513		return (1);
514	}
515	return (0);
516}
517
518void
519parsecolors(const char *cs)
520{
521	int i;
522	int j;
523	size_t len;
524	char c[2];
525	short legacy_warn = 0;
526
527	if (cs == NULL)
528		cs = "";	/* LSCOLORS not set */
529	len = strlen(cs);
530	for (i = 0; i < (int)C_NUMCOLORS; i++) {
531		colors[i].bold = 0;
532
533		if (len <= 2 * (size_t)i) {
534			c[0] = defcolors[2 * i];
535			c[1] = defcolors[2 * i + 1];
536		} else {
537			c[0] = cs[2 * i];
538			c[1] = cs[2 * i + 1];
539		}
540		for (j = 0; j < 2; j++) {
541			/* Legacy colours used 0-7 */
542			if (c[j] >= '0' && c[j] <= '7') {
543				colors[i].num[j] = c[j] - '0';
544				if (!legacy_warn) {
545					warnx("LSCOLORS should use "
546					    "characters a-h instead of 0-9 ("
547					    "see the manual page)");
548				}
549				legacy_warn = 1;
550			} else if (c[j] >= 'a' && c[j] <= 'h')
551				colors[i].num[j] = c[j] - 'a';
552			else if (c[j] >= 'A' && c[j] <= 'H') {
553				colors[i].num[j] = c[j] - 'A';
554				colors[i].bold = 1;
555			} else if (tolower((unsigned char)c[j]) == 'x')
556				colors[i].num[j] = -1;
557			else {
558				warnx("invalid character '%c' in LSCOLORS"
559				    " env var", c[j]);
560				colors[i].num[j] = -1;
561			}
562		}
563	}
564}
565
566void
567colorquit(int sig)
568{
569	endcolor(sig);
570
571	(void)signal(sig, SIG_DFL);
572	(void)kill(getpid(), sig);
573}
574
575#endif /* COLORLS */
576
577static void
578printlink(const FTSENT *p)
579{
580	int lnklen;
581	char name[MAXPATHLEN + 1];
582	char path[MAXPATHLEN + 1];
583
584	if (p->fts_level == FTS_ROOTLEVEL)
585		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
586	else
587		(void)snprintf(name, sizeof(name),
588		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
589	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
590		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
591		return;
592	}
593	path[lnklen] = '\0';
594	(void)printf(" -> ");
595	(void)printname(path);
596}
597
598static void
599printsize(size_t width, off_t bytes)
600{
601
602	if (f_humanval) {
603		char buf[5];
604
605		humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
606		    HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
607		(void)printf("%5s ", buf);
608	} else
609		(void)printf("%*jd ", (u_int)width, bytes);
610}
611
612static void
613aclmode(char *buf, const FTSENT *p, int *haveacls)
614{
615	char name[MAXPATHLEN + 1];
616	int entries, ret;
617	acl_t facl;
618	acl_entry_t ae;
619
620	/*
621	 * Add a + after the standard rwxrwxrwx mode if the file has an
622	 * extended ACL. strmode() reserves space at the end of the string.
623	 */
624	if (p->fts_level == FTS_ROOTLEVEL)
625		snprintf(name, sizeof(name), "%s", p->fts_name);
626	else
627		snprintf(name, sizeof(name), "%s/%s",
628		    p->fts_parent->fts_accpath, p->fts_name);
629	/*
630	 * We have no way to tell whether a symbolic link has an ACL since
631	 * pathconf() and acl_get_file() both follow them.
632	 */
633	if (S_ISLNK(p->fts_statp->st_mode)) {
634		*haveacls = 1;
635		return;
636	}
637	if ((ret = pathconf(name, _PC_ACL_EXTENDED)) <= 0) {
638		if (ret < 0 && errno != EINVAL)
639			warn("%s", name);
640		else
641			*haveacls = 0;
642		return;
643	}
644	*haveacls = 1;
645	if ((facl = acl_get_file(name, ACL_TYPE_ACCESS)) != NULL) {
646		if (acl_get_entry(facl, ACL_FIRST_ENTRY, &ae) == 1) {
647			entries = 1;
648			while (acl_get_entry(facl, ACL_NEXT_ENTRY, &ae) == 1)
649				if (++entries > 3)
650					break;
651			/*
652			 * POSIX.1e requires that ACLs of type ACL_TYPE_ACCESS
653			 * must have at least three entries (owner, group,
654			 * and other). So anything with more than 3 ACLs looks
655			 * interesting to us.
656			 */
657			if (entries > 3)
658				buf[10] = '+';
659		}
660		acl_free(facl);
661	} else
662		warn("%s", name);
663}
664