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