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