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