xref: /freebsd/bin/ls/print.c (revision 82dd3eab133ed08413c78c43e4bf586e508762b7)
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 <signal.h>
63 #endif
64 
65 #include "ls.h"
66 #include "extern.h"
67 
68 static int	printaname __P((FTSENT *, u_long, u_long));
69 static void	printlink __P((FTSENT *));
70 static void	printtime __P((time_t));
71 static int	printtype __P((u_int));
72 #ifdef COLORLS
73 static void     endcolor __P((int));
74 static 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> */
81 typedef 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 
96 char *defcolors = "4x5x2x3x1x464301060203";
97 
98 static int colors[C_NUMCOLORS][2];
99 #endif
100 
101 void
102 printscol(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 
115 void
116 printlong(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 
183 void
184 printcol(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 			while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
245 			    <= endcol){
246 				(void)putchar(f_notabs ? ' ' : '\t');
247 				chcnt = cnt;
248 			}
249 			endcol += colwidth;
250 		}
251 		(void)putchar('\n');
252 	}
253 }
254 
255 /*
256  * print [inode] [size] name
257  * return # of characters printed, no trailing characters.
258  */
259 static int
260 printaname(p, inodefield, sizefield)
261 	FTSENT *p;
262 	u_long sizefield, inodefield;
263 {
264 	struct stat *sp;
265 	int chcnt;
266 #ifdef COLORLS
267 	int color_printed = 0;
268 #endif
269 
270 	sp = p->fts_statp;
271 	chcnt = 0;
272 	if (f_inode)
273 		chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
274 	if (f_size)
275 		chcnt += printf("%*qd ",
276 		    (int)sizefield, howmany(sp->st_blocks, blocksize));
277 #ifdef COLORLS
278 	if (f_color)
279 		color_printed = colortype(sp->st_mode);
280 #endif
281 	chcnt += (f_octal || f_octal_escape) ? prn_octal(p->fts_name)
282 	                                     : printf("%s", p->fts_name);
283 #ifdef COLORLS
284 	if (f_color && color_printed)
285 		endcolor(0);
286 #endif
287 	if (f_type)
288 		chcnt += printtype(sp->st_mode);
289 	return (chcnt);
290 }
291 
292 static void
293 printtime(ftime)
294 	time_t ftime;
295 {
296 	int i;
297 	char longstring[80];
298 	static time_t now;
299 
300 	if (now == 0)
301 		now = time(NULL);
302 
303 	strftime(longstring, sizeof(longstring), "%c", localtime(&ftime));
304 	for (i = 4; i < 11; ++i)
305 		(void)putchar(longstring[i]);
306 
307 #define	SIXMONTHS	((365 / 2) * 86400)
308 	if (f_sectime)
309 		for (i = 11; i < 24; i++)
310 			(void)putchar(longstring[i]);
311 	else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
312 		for (i = 11; i < 16; ++i)
313 			(void)putchar(longstring[i]);
314 	else {
315 		(void)putchar(' ');
316 		for (i = 20; i < 24; ++i)
317 			(void)putchar(longstring[i]);
318 	}
319 	(void)putchar(' ');
320 }
321 
322 static int
323 printtype(mode)
324 	u_int mode;
325 {
326 	switch (mode & S_IFMT) {
327 	case S_IFDIR:
328 		(void)putchar('/');
329 		return (1);
330 	case S_IFIFO:
331 		(void)putchar('|');
332 		return (1);
333 	case S_IFLNK:
334 		(void)putchar('@');
335 		return (1);
336 	case S_IFSOCK:
337 		(void)putchar('=');
338 		return (1);
339 	case S_IFWHT:
340 		(void)putchar('%');
341 		return (1);
342 	}
343 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
344 		(void)putchar('*');
345 		return (1);
346 	}
347 	return (0);
348 }
349 
350 #ifdef COLORLS
351 static int
352 putch(c)
353 	int c;
354 {
355 	(void) putchar(c);
356 	return 0;
357 }
358 
359 static int
360 writech(c)
361 	int c;
362 {
363 	char tmp = c;
364 
365 	(void) write(STDOUT_FILENO, &tmp, 1);
366 	return 0;
367 }
368 
369 static void
370 printcolor(c)
371        Colors c;
372 {
373 	char *ansiseq;
374 
375 	if (colors[c][0] != -1) {
376 		ansiseq = tgoto(ansi_fgcol, 0, colors[c][0]);
377 		if (ansiseq)
378 			tputs(ansiseq, 1, putch);
379 	}
380 
381 	if (colors[c][1] != -1) {
382 		ansiseq = tgoto(ansi_bgcol, 0, colors[c][1]);
383 		if (ansiseq)
384 			tputs(ansiseq, 1, putch);
385 	}
386 }
387 
388 static void
389 endcolor(sig)
390 	int sig;
391 {
392 	tputs(ansi_coloff, 1, sig ? writech : putch);
393 }
394 
395 static int
396 colortype(mode)
397        mode_t mode;
398 {
399 	switch(mode & S_IFMT) {
400 	      case S_IFDIR:
401 		if (mode & S_IWOTH)
402 		    if (mode & S_ISTXT)
403 			printcolor(C_WSDIR);
404 		    else
405 			printcolor(C_WDIR);
406 		else
407 		    printcolor(C_DIR);
408 		return(1);
409 	      case S_IFLNK:
410 		printcolor(C_LNK);
411 		return(1);
412 	      case S_IFSOCK:
413 		printcolor(C_SOCK);
414 		return(1);
415 	      case S_IFIFO:
416 		printcolor(C_FIFO);
417 		return(1);
418 	      case S_IFBLK:
419 		printcolor(C_BLK);
420 		return(1);
421 	      case S_IFCHR:
422 		printcolor(C_CHR);
423 		return(1);
424 	}
425 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
426 		if (mode & S_ISUID)
427 		    printcolor(C_SUID);
428 		else if (mode & S_ISGID)
429 		    printcolor(C_SGID);
430 		else
431 		    printcolor(C_EXEC);
432 		return(1);
433 	}
434 	return(0);
435 }
436 
437 void
438 parsecolors(cs)
439 char *cs;
440 {
441 	int i, j, len;
442 	char c[2];
443 
444 	if (cs == NULL)    cs = ""; /* LSCOLORS not set */
445 	len = strlen(cs);
446 	for (i = 0 ; i < C_NUMCOLORS ; i++) {
447 		if (len <= 2*i) {
448 			c[0] = defcolors[2*i];
449 			c[1] = defcolors[2*i+1];
450 		}
451 		else {
452 			c[0] = cs[2*i];
453 			c[1] = cs[2*i+1];
454 		}
455 		for (j = 0 ; j < 2 ; j++) {
456 			if ((c[j] < '0' || c[j] > '7') &&
457 			    tolower((unsigned char)c[j]) != 'x') {
458 				fprintf(stderr,
459 					"error: invalid character '%c' in LSCOLORS env var\n",
460 					c[j]);
461 				c[j] = defcolors[2*i+j];
462 			}
463 			if (tolower((unsigned char)c[j]) == 'x')
464 			    colors[i][j] = -1;
465 			else
466 			    colors[i][j] = c[j]-'0';
467 		}
468 	}
469 }
470 
471 void
472 colorquit(sig)
473 	int sig;
474 {
475 	endcolor(sig);
476 
477 	(void) signal(sig, SIG_DFL);
478 	(void) kill(getpid(), sig);
479 }
480 #endif /*COLORLS*/
481 
482 static void
483 printlink(p)
484 	FTSENT *p;
485 {
486 	int lnklen;
487 	char name[MAXPATHLEN + 1], path[MAXPATHLEN + 1];
488 
489 	if (p->fts_level == FTS_ROOTLEVEL)
490 		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
491 	else
492 		(void)snprintf(name, sizeof(name),
493 		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
494 	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
495 		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
496 		return;
497 	}
498 	path[lnklen] = '\0';
499 	if (f_octal || f_octal_escape) {
500 	        (void)printf(" -> ");
501 	        (void)prn_octal(path);
502 	}
503 	else (void)printf(" -> %s", path);
504 }
505