print.c revision 61178
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#ifndef lint
38#if 0
39static char sccsid[] = "@(#)print.c	8.4 (Berkeley) 4/17/94";
40#else
41static const char rcsid[] =
42  "$FreeBSD: head/bin/ls/print.c 61178 2000-06-02 14:53:42Z joe $";
43#endif
44#endif /* not lint */
45
46#include <sys/param.h>
47#include <sys/stat.h>
48
49#include <err.h>
50#include <errno.h>
51#include <fts.h>
52#include <grp.h>
53#include <pwd.h>
54#include <stdio.h>
55#include <stdlib.h>
56#include <string.h>
57#include <time.h>
58#include <unistd.h>
59#include <ctype.h>
60
61#include "ls.h"
62#include "extern.h"
63
64static int	printaname __P((FTSENT *, u_long, u_long));
65static void	printlink __P((FTSENT *));
66static void	printtime __P((time_t));
67static int	printtype __P((u_int));
68
69#define	IS_NOPRINT(p)	((p)->fts_number == NO_PRINT)
70
71/* Most of these are taken from <sys/stat.h> */
72typedef enum Colors {
73    C_DIR,     /* directory */
74    C_LNK,     /* symbolic link */
75    C_SOCK,    /* socket */
76    C_FIFO,    /* pipe */
77    C_EXEC,    /* executable */
78    C_BLK,     /* block special */
79    C_CHR,     /* character special */
80    C_SUID,    /* setuid executable */
81    C_SGID,    /* setgid executable */
82    C_WSDIR,   /* directory writeble to others, with sticky bit */
83    C_WDIR,    /* directory writeble to others, without sticky bit */
84    C_NUMCOLORS        /* just a place-holder */
85} Colors ;
86
87char *defcolors = "4x5x2x3x1x464301060203";
88
89static int colors[C_NUMCOLORS][2];
90
91void
92printscol(dp)
93	DISPLAY *dp;
94{
95	FTSENT *p;
96
97	for (p = dp->list; p; p = p->fts_link) {
98		if (IS_NOPRINT(p))
99			continue;
100		(void)printaname(p, dp->s_inode, dp->s_block);
101		(void)putchar('\n');
102	}
103}
104
105void
106printlong(dp)
107	DISPLAY *dp;
108{
109	struct stat *sp;
110	FTSENT *p;
111	NAMES *np;
112	char buf[20];
113
114	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
115		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
116
117	for (p = dp->list; p; p = p->fts_link) {
118		if (IS_NOPRINT(p))
119			continue;
120		sp = p->fts_statp;
121		if (f_inode)
122			(void)printf("%*lu ", dp->s_inode, (u_long)sp->st_ino);
123		if (f_size)
124			(void)printf("%*qd ",
125			    dp->s_block, howmany(sp->st_blocks, blocksize));
126		(void)strmode(sp->st_mode, buf);
127		np = p->fts_pointer;
128		(void)printf("%s %*u %-*s  %-*s  ", buf, dp->s_nlink,
129		    sp->st_nlink, dp->s_user, np->user, dp->s_group,
130		    np->group);
131		if (f_flags)
132			(void)printf("%-*s ", dp->s_flags, np->flags);
133		if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
134			if (minor(sp->st_rdev) > 255 || minor(sp->st_rdev) < 0)
135				(void)printf("%3d, 0x%08x ",
136				    major(sp->st_rdev),
137				    (u_int)minor(sp->st_rdev));
138			else
139				(void)printf("%3d, %3d ",
140				    major(sp->st_rdev), minor(sp->st_rdev));
141		else if (dp->bcfile)
142			(void)printf("%*s%*qd ",
143			    8 - dp->s_size, "", dp->s_size, sp->st_size);
144		else
145			(void)printf("%*qd ", dp->s_size, sp->st_size);
146		if (f_accesstime)
147			printtime(sp->st_atime);
148		else if (f_statustime)
149			printtime(sp->st_ctime);
150		else
151			printtime(sp->st_mtime);
152		if (f_color)
153			(void)colortype(sp->st_mode);
154		if (f_octal || f_octal_escape) (void)prn_octal(p->fts_name);
155		else (void)printf("%s", p->fts_name);
156		if (f_color)
157			(void)printf("\033[m");
158		if (f_type)
159			(void)printtype(sp->st_mode);
160		if (S_ISLNK(sp->st_mode))
161			printlink(p);
162		(void)putchar('\n');
163	}
164}
165
166void
167printcol(dp)
168	DISPLAY *dp;
169{
170	extern int termwidth;
171	static FTSENT **array;
172	static int lastentries = -1;
173	FTSENT *p;
174	int base, chcnt, cnt, col, colwidth, num;
175	int endcol, numcols, numrows, row;
176	int tabwidth;
177
178	if (f_notabs)
179		tabwidth = 1;
180	else
181		tabwidth = 8;
182
183	/*
184	 * Have to do random access in the linked list -- build a table
185	 * of pointers.
186	 */
187	if (dp->entries > lastentries) {
188		lastentries = dp->entries;
189		if ((array =
190		    realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
191			warn(NULL);
192			printscol(dp);
193		}
194	}
195	for (p = dp->list, num = 0; p; p = p->fts_link)
196		if (p->fts_number != NO_PRINT)
197			array[num++] = p;
198
199	colwidth = dp->maxlen;
200	if (f_inode)
201		colwidth += dp->s_inode + 1;
202	if (f_size)
203		colwidth += dp->s_block + 1;
204	if (f_type)
205		colwidth += 1;
206
207	colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
208	if (termwidth < 2 * colwidth) {
209		printscol(dp);
210		return;
211	}
212
213	numcols = termwidth / colwidth;
214	numrows = num / numcols;
215	if (num % numcols)
216		++numrows;
217
218	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
219		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
220	for (row = 0; row < numrows; ++row) {
221		endcol = colwidth;
222		for (base = row, chcnt = col = 0; col < numcols; ++col) {
223			chcnt += printaname(array[base], dp->s_inode,
224			    dp->s_block);
225			if ((base += numrows) >= num)
226				break;
227			/*
228			 * some terminals get confused if we mix tabs
229			 * with color sequences
230			 */
231			if (f_color)
232				while ((cnt = (chcnt + 1)) <= endcol) {
233					(void)putchar(' ');
234					chcnt = cnt;
235				}
236			else
237			while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
238			    <= endcol){
239				(void)putchar(f_notabs ? ' ' : '\t');
240				chcnt = cnt;
241			}
242			endcol += colwidth;
243		}
244		(void)putchar('\n');
245	}
246}
247
248/*
249 * print [inode] [size] name
250 * return # of characters printed, no trailing characters.
251 */
252static int
253printaname(p, inodefield, sizefield)
254	FTSENT *p;
255	u_long sizefield, inodefield;
256{
257	struct stat *sp;
258	int chcnt;
259
260	sp = p->fts_statp;
261	chcnt = 0;
262	if (f_inode)
263		chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
264	if (f_size)
265		chcnt += printf("%*qd ",
266		    (int)sizefield, howmany(sp->st_blocks, blocksize));
267	if (f_color)
268		(void)colortype(sp->st_mode);
269	chcnt += (f_octal || f_octal_escape) ? prn_octal(p->fts_name)
270	                                     : printf("%s", p->fts_name);
271	if (f_color)
272		printf("\033[m");
273	if (f_type)
274		chcnt += printtype(sp->st_mode);
275	return (chcnt);
276}
277
278static void
279printtime(ftime)
280	time_t ftime;
281{
282	int i;
283	char longstring[80];
284	static time_t now;
285
286	if (now == 0)
287		now = time(NULL);
288
289	strftime(longstring, sizeof(longstring), "%c", localtime(&ftime));
290	for (i = 4; i < 11; ++i)
291		(void)putchar(longstring[i]);
292
293#define	SIXMONTHS	((365 / 2) * 86400)
294	if (f_sectime)
295		for (i = 11; i < 24; i++)
296			(void)putchar(longstring[i]);
297	else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
298		for (i = 11; i < 16; ++i)
299			(void)putchar(longstring[i]);
300	else {
301		(void)putchar(' ');
302		for (i = 20; i < 24; ++i)
303			(void)putchar(longstring[i]);
304	}
305	(void)putchar(' ');
306}
307
308static int
309printtype(mode)
310	u_int mode;
311{
312	switch (mode & S_IFMT) {
313	case S_IFDIR:
314		(void)putchar('/');
315		return (1);
316	case S_IFIFO:
317		(void)putchar('|');
318		return (1);
319	case S_IFLNK:
320		(void)putchar('@');
321		return (1);
322	case S_IFSOCK:
323		(void)putchar('=');
324		return (1);
325	case S_IFWHT:
326		(void)putchar('%');
327		return (1);
328	}
329	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
330		(void)putchar('*');
331		return (1);
332	}
333	return (0);
334}
335
336void
337printcolor(c)
338       Colors c;
339{
340	printf("\033[");
341	if (colors[c][0] != -1) {
342		printf("3%d", colors[c][0]);
343		if (colors[c][1] != -1)
344		    printf(";");
345	}
346	if (colors[c][1] != -1)
347	    printf("4%d", colors[c][1]);
348	printf("m");
349}
350
351int
352colortype(mode)
353       mode_t mode;
354{
355	switch(mode & S_IFMT) {
356	      case S_IFDIR:
357		if (mode & S_IWOTH)
358		    if (mode & S_ISTXT)
359			printcolor(C_WSDIR);
360		    else
361			printcolor(C_WDIR);
362		else
363		    printcolor(C_DIR);
364		return(1);
365	      case S_IFLNK:
366		printcolor(C_LNK);
367		return(1);
368	      case S_IFSOCK:
369		printcolor(C_SOCK);
370		return(1);
371	      case S_IFIFO:
372		printcolor(C_FIFO);
373		return(1);
374	      case S_IFBLK:
375		printcolor(C_BLK);
376		return(1);
377	      case S_IFCHR:
378		printcolor(C_CHR);
379		return(1);
380	}
381	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
382		if (mode & S_ISUID)
383		    printcolor(C_SUID);
384		else if (mode & S_ISGID)
385		    printcolor(C_SGID);
386		else
387		    printcolor(C_EXEC);
388		return(1);
389	}
390	return(0);
391}
392
393void
394parsecolors(cs)
395char *cs;
396{
397	int i, j, len;
398	char c[2];
399	if (cs == NULL)    cs = ""; /* LSCOLORS not set */
400	len = strlen(cs);
401	for (i = 0 ; i < C_NUMCOLORS ; i++) {
402		if (len <= 2*i) {
403			c[0] = defcolors[2*i];
404			c[1] = defcolors[2*i+1];
405		}
406		else {
407			c[0] = cs[2*i];
408			c[1] = cs[2*i+1];
409		}
410		for (j = 0 ; j < 2 ; j++) {
411			if ((c[j] < '0' || c[j] > '7') &&
412			    tolower(c[j]) != 'x') {
413				fprintf(stderr,
414					"error: invalid character '%c' in LSCOLORS env var\n",
415					c[j]);
416				c[j] = defcolors[2*i+j];
417			}
418			if (c[j] == 'x')
419			    colors[i][j] = -1;
420			else
421			    colors[i][j] = c[j]-'0';
422		}
423	}
424}
425
426static void
427printlink(p)
428	FTSENT *p;
429{
430	int lnklen;
431	char name[MAXPATHLEN + 1], path[MAXPATHLEN + 1];
432
433	if (p->fts_level == FTS_ROOTLEVEL)
434		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
435	else
436		(void)snprintf(name, sizeof(name),
437		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
438	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
439		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
440		return;
441	}
442	path[lnklen] = '\0';
443	if (f_octal || f_octal_escape) {
444	        (void)printf(" -> ");
445	        (void)prn_octal(path);
446	}
447	else (void)printf(" -> %s", path);
448}
449