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