print.c revision 61334
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 61334 2000-06-06 12:10:07Z ache $";
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#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
68static int	printaname __P((FTSENT *, u_long, u_long));
69static void	printlink __P((FTSENT *));
70static void	printtime __P((time_t));
71static int	printtype __P((u_int));
72#ifdef COLORLS
73static void     endcolor __P((int));
74static int      colortype __P((mode_t));
75#endif
76
77#define	IS_NOPRINT(p)	((p)->fts_number == NO_PRINT)
78
79#ifdef COLORLS
80/* Most of these are taken from <sys/stat.h> */
81typedef enum Colors {
82    C_DIR,     /* directory */
83    C_LNK,     /* symbolic link */
84    C_SOCK,    /* socket */
85    C_FIFO,    /* pipe */
86    C_EXEC,    /* executable */
87    C_BLK,     /* block special */
88    C_CHR,     /* character special */
89    C_SUID,    /* setuid executable */
90    C_SGID,    /* setgid executable */
91    C_WSDIR,   /* directory writeble to others, with sticky bit */
92    C_WDIR,    /* directory writeble to others, without sticky bit */
93    C_NUMCOLORS        /* just a place-holder */
94} Colors ;
95
96char *defcolors = "4x5x2x3x1x464301060203";
97
98static int colors[C_NUMCOLORS][2];
99#endif
100
101void
102printscol(dp)
103	DISPLAY *dp;
104{
105	FTSENT *p;
106
107	for (p = dp->list; p; p = p->fts_link) {
108		if (IS_NOPRINT(p))
109			continue;
110		(void)printaname(p, dp->s_inode, dp->s_block);
111		(void)putchar('\n');
112	}
113}
114
115void
116printlong(dp)
117	DISPLAY *dp;
118{
119	struct stat *sp;
120	FTSENT *p;
121	NAMES *np;
122	char buf[20];
123#ifdef COLORLS
124	int color_printed = 0;
125#endif
126
127	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
128		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
129
130	for (p = dp->list; p; p = p->fts_link) {
131		if (IS_NOPRINT(p))
132			continue;
133		sp = p->fts_statp;
134		if (f_inode)
135			(void)printf("%*lu ", dp->s_inode, (u_long)sp->st_ino);
136		if (f_size)
137			(void)printf("%*qd ",
138			    dp->s_block, howmany(sp->st_blocks, blocksize));
139		(void)strmode(sp->st_mode, buf);
140		np = p->fts_pointer;
141		(void)printf("%s %*u %-*s  %-*s  ", buf, dp->s_nlink,
142		    sp->st_nlink, dp->s_user, np->user, dp->s_group,
143		    np->group);
144		if (f_flags)
145			(void)printf("%-*s ", dp->s_flags, np->flags);
146		if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
147			if (minor(sp->st_rdev) > 255 || minor(sp->st_rdev) < 0)
148				(void)printf("%3d, 0x%08x ",
149				    major(sp->st_rdev),
150				    (u_int)minor(sp->st_rdev));
151			else
152				(void)printf("%3d, %3d ",
153				    major(sp->st_rdev), minor(sp->st_rdev));
154		else if (dp->bcfile)
155			(void)printf("%*s%*qd ",
156			    8 - dp->s_size, "", dp->s_size, sp->st_size);
157		else
158			(void)printf("%*qd ", dp->s_size, sp->st_size);
159		if (f_accesstime)
160			printtime(sp->st_atime);
161		else if (f_statustime)
162			printtime(sp->st_ctime);
163		else
164			printtime(sp->st_mtime);
165#ifdef COLORLS
166		if (f_color)
167			color_printed = colortype(sp->st_mode);
168#endif
169		if (f_octal || f_octal_escape) (void)prn_octal(p->fts_name);
170		else (void)printf("%s", p->fts_name);
171#ifdef COLORLS
172		if (f_color && color_printed)
173			endcolor(0);
174#endif
175		if (f_type)
176			(void)printtype(sp->st_mode);
177		if (S_ISLNK(sp->st_mode))
178			printlink(p);
179		(void)putchar('\n');
180	}
181}
182
183void
184printcol(dp)
185	DISPLAY *dp;
186{
187	extern int termwidth;
188	static FTSENT **array;
189	static int lastentries = -1;
190	FTSENT *p;
191	int base, chcnt, cnt, col, colwidth, num;
192	int endcol, numcols, numrows, row;
193	int tabwidth;
194
195	if (f_notabs)
196		tabwidth = 1;
197	else
198		tabwidth = 8;
199
200	/*
201	 * Have to do random access in the linked list -- build a table
202	 * of pointers.
203	 */
204	if (dp->entries > lastentries) {
205		lastentries = dp->entries;
206		if ((array =
207		    realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
208			warn(NULL);
209			printscol(dp);
210		}
211	}
212	for (p = dp->list, num = 0; p; p = p->fts_link)
213		if (p->fts_number != NO_PRINT)
214			array[num++] = p;
215
216	colwidth = dp->maxlen;
217	if (f_inode)
218		colwidth += dp->s_inode + 1;
219	if (f_size)
220		colwidth += dp->s_block + 1;
221	if (f_type)
222		colwidth += 1;
223
224	colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
225	if (termwidth < 2 * colwidth) {
226		printscol(dp);
227		return;
228	}
229
230	numcols = termwidth / colwidth;
231	numrows = num / numcols;
232	if (num % numcols)
233		++numrows;
234
235	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
236		(void)printf("total %lu\n", howmany(dp->btotal, blocksize));
237	for (row = 0; row < numrows; ++row) {
238		endcol = colwidth;
239		for (base = row, chcnt = col = 0; col < numcols; ++col) {
240			chcnt += printaname(array[base], dp->s_inode,
241			    dp->s_block);
242			if ((base += numrows) >= num)
243				break;
244#ifdef COLORLS
245			/*
246			 * We can't put tabs and color sequences together:
247			 * column number will be incremented incorrectly
248			 * for "stty oxtabs" mode.
249			 */
250			if (f_color)
251				while ((cnt = (chcnt + 1)) <= endcol) {
252					(void)putchar(' ');
253					chcnt = cnt;
254				}
255			else
256#endif
257			while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
258			    <= endcol){
259				(void)putchar(f_notabs ? ' ' : '\t');
260				chcnt = cnt;
261			}
262			endcol += colwidth;
263		}
264		(void)putchar('\n');
265	}
266}
267
268/*
269 * print [inode] [size] name
270 * return # of characters printed, no trailing characters.
271 */
272static int
273printaname(p, inodefield, sizefield)
274	FTSENT *p;
275	u_long sizefield, inodefield;
276{
277	struct stat *sp;
278	int chcnt;
279#ifdef COLORLS
280	int color_printed = 0;
281#endif
282
283	sp = p->fts_statp;
284	chcnt = 0;
285	if (f_inode)
286		chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
287	if (f_size)
288		chcnt += printf("%*qd ",
289		    (int)sizefield, howmany(sp->st_blocks, blocksize));
290#ifdef COLORLS
291	if (f_color)
292		color_printed = colortype(sp->st_mode);
293#endif
294	chcnt += (f_octal || f_octal_escape) ? prn_octal(p->fts_name)
295	                                     : printf("%s", p->fts_name);
296#ifdef COLORLS
297	if (f_color && color_printed)
298		endcolor(0);
299#endif
300	if (f_type)
301		chcnt += printtype(sp->st_mode);
302	return (chcnt);
303}
304
305static void
306printtime(ftime)
307	time_t ftime;
308{
309	int i;
310	char longstring[80];
311	static time_t now;
312
313	if (now == 0)
314		now = time(NULL);
315
316	strftime(longstring, sizeof(longstring), "%c", localtime(&ftime));
317	for (i = 4; i < 11; ++i)
318		(void)putchar(longstring[i]);
319
320#define	SIXMONTHS	((365 / 2) * 86400)
321	if (f_sectime)
322		for (i = 11; i < 24; i++)
323			(void)putchar(longstring[i]);
324	else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
325		for (i = 11; i < 16; ++i)
326			(void)putchar(longstring[i]);
327	else {
328		(void)putchar(' ');
329		for (i = 20; i < 24; ++i)
330			(void)putchar(longstring[i]);
331	}
332	(void)putchar(' ');
333}
334
335static int
336printtype(mode)
337	u_int mode;
338{
339	switch (mode & S_IFMT) {
340	case S_IFDIR:
341		(void)putchar('/');
342		return (1);
343	case S_IFIFO:
344		(void)putchar('|');
345		return (1);
346	case S_IFLNK:
347		(void)putchar('@');
348		return (1);
349	case S_IFSOCK:
350		(void)putchar('=');
351		return (1);
352	case S_IFWHT:
353		(void)putchar('%');
354		return (1);
355	}
356	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
357		(void)putchar('*');
358		return (1);
359	}
360	return (0);
361}
362
363#ifdef COLORLS
364static int
365putch(c)
366	int c;
367{
368	(void) putchar(c);
369	return 0;
370}
371
372static int
373writech(c)
374	int c;
375{
376	char tmp = c;
377
378	(void) write(STDOUT_FILENO, &tmp, 1);
379	return 0;
380}
381
382static void
383printcolor(c)
384       Colors c;
385{
386	char *ansiseq;
387
388	if (colors[c][0] != -1) {
389		ansiseq = tgoto(ansi_fgcol, 0, colors[c][0]);
390		if (ansiseq)
391			tputs(ansiseq, 1, putch);
392	}
393
394	if (colors[c][1] != -1) {
395		ansiseq = tgoto(ansi_bgcol, 0, colors[c][1]);
396		if (ansiseq)
397			tputs(ansiseq, 1, putch);
398	}
399}
400
401static void
402endcolor(sig)
403	int sig;
404{
405	tputs(ansi_coloff, 1, sig ? writech : putch);
406}
407
408static int
409colortype(mode)
410       mode_t mode;
411{
412	switch(mode & S_IFMT) {
413	      case S_IFDIR:
414		if (mode & S_IWOTH)
415		    if (mode & S_ISTXT)
416			printcolor(C_WSDIR);
417		    else
418			printcolor(C_WDIR);
419		else
420		    printcolor(C_DIR);
421		return(1);
422	      case S_IFLNK:
423		printcolor(C_LNK);
424		return(1);
425	      case S_IFSOCK:
426		printcolor(C_SOCK);
427		return(1);
428	      case S_IFIFO:
429		printcolor(C_FIFO);
430		return(1);
431	      case S_IFBLK:
432		printcolor(C_BLK);
433		return(1);
434	      case S_IFCHR:
435		printcolor(C_CHR);
436		return(1);
437	}
438	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
439		if (mode & S_ISUID)
440		    printcolor(C_SUID);
441		else if (mode & S_ISGID)
442		    printcolor(C_SGID);
443		else
444		    printcolor(C_EXEC);
445		return(1);
446	}
447	return(0);
448}
449
450void
451parsecolors(cs)
452char *cs;
453{
454	int i, j, len;
455	char c[2];
456
457	if (cs == NULL)    cs = ""; /* LSCOLORS not set */
458	len = strlen(cs);
459	for (i = 0 ; i < C_NUMCOLORS ; i++) {
460		if (len <= 2*i) {
461			c[0] = defcolors[2*i];
462			c[1] = defcolors[2*i+1];
463		}
464		else {
465			c[0] = cs[2*i];
466			c[1] = cs[2*i+1];
467		}
468		for (j = 0 ; j < 2 ; j++) {
469			if ((c[j] < '0' || c[j] > '7') &&
470			    tolower((unsigned char)c[j]) != 'x') {
471				fprintf(stderr,
472					"error: invalid character '%c' in LSCOLORS env var\n",
473					c[j]);
474				c[j] = defcolors[2*i+j];
475			}
476			if (tolower((unsigned char)c[j]) == 'x')
477			    colors[i][j] = -1;
478			else
479			    colors[i][j] = c[j]-'0';
480		}
481	}
482}
483
484void
485colorquit(sig)
486	int sig;
487{
488	endcolor(sig);
489
490	(void) signal(sig, SIG_DFL);
491	(void) kill(getpid(), sig);
492}
493#endif /*COLORLS*/
494
495static void
496printlink(p)
497	FTSENT *p;
498{
499	int lnklen;
500	char name[MAXPATHLEN + 1], path[MAXPATHLEN + 1];
501
502	if (p->fts_level == FTS_ROOTLEVEL)
503		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
504	else
505		(void)snprintf(name, sizeof(name),
506		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
507	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
508		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
509		return;
510	}
511	path[lnklen] = '\0';
512	if (f_octal || f_octal_escape) {
513	        (void)printf(" -> ");
514	        (void)prn_octal(path);
515	}
516	else (void)printf(" -> %s", path);
517}
518