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