xref: /freebsd/bin/ls/print.c (revision 74985094ef1904f3bb16254005b0704f0c82d515)
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 #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 
70 static int	printaname __P((FTSENT *, u_long, u_long));
71 static void	printlink __P((FTSENT *));
72 static void	printtime __P((time_t));
73 static 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> */
79 typedef 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 
94 char *defcolors = "4x5x2x3x1x464301060203";
95 
96 static int colors[C_NUMCOLORS][2];
97 #endif
98 
99 void
100 printscol(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 
113 void
114 printlong(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 
178 void
179 printcol(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  */
266 static int
267 printaname(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 
296 static void
297 printtime(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 
326 static int
327 printtype(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
355 static char tcapbuf[512];
356 void
357 printcolor(c)
358        Colors c;
359 {
360 	char *bp = tcapbuf;
361 	char *ansiseq;
362 
363 	if (colors[c][0] != -1) {
364 		ansiseq = tparm(tgetstr("AF", &bp), colors[c][0]);
365 		if (ansiseq)
366 			putp(ansiseq);
367 	}
368 
369 	if (colors[c][1] != -1) {
370 		ansiseq = tparm(tgetstr("AB", &bp), colors[c][1]);
371 		if (ansiseq)
372 			putp(ansiseq);
373 	}
374 }
375 
376 void
377 endcolor()
378 {
379 	char *bp = tcapbuf;
380 	char *ansiseq;
381 	ansiseq = tgetstr("se", &bp);
382 	if (ansiseq)
383 		putp(ansiseq);
384 }
385 
386 int
387 colortype(mode)
388        mode_t mode;
389 {
390 	switch(mode & S_IFMT) {
391 	      case S_IFDIR:
392 		if (mode & S_IWOTH)
393 		    if (mode & S_ISTXT)
394 			printcolor(C_WSDIR);
395 		    else
396 			printcolor(C_WDIR);
397 		else
398 		    printcolor(C_DIR);
399 		return(1);
400 	      case S_IFLNK:
401 		printcolor(C_LNK);
402 		return(1);
403 	      case S_IFSOCK:
404 		printcolor(C_SOCK);
405 		return(1);
406 	      case S_IFIFO:
407 		printcolor(C_FIFO);
408 		return(1);
409 	      case S_IFBLK:
410 		printcolor(C_BLK);
411 		return(1);
412 	      case S_IFCHR:
413 		printcolor(C_CHR);
414 		return(1);
415 	}
416 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
417 		if (mode & S_ISUID)
418 		    printcolor(C_SUID);
419 		else if (mode & S_ISGID)
420 		    printcolor(C_SGID);
421 		else
422 		    printcolor(C_EXEC);
423 		return(1);
424 	}
425 	return(0);
426 }
427 
428 void
429 parsecolors(cs)
430 char *cs;
431 {
432 	int i, j, len;
433 	char c[2];
434 	if (cs == NULL)    cs = ""; /* LSCOLORS not set */
435 	len = strlen(cs);
436 	for (i = 0 ; i < C_NUMCOLORS ; i++) {
437 		if (len <= 2*i) {
438 			c[0] = defcolors[2*i];
439 			c[1] = defcolors[2*i+1];
440 		}
441 		else {
442 			c[0] = cs[2*i];
443 			c[1] = cs[2*i+1];
444 		}
445 		for (j = 0 ; j < 2 ; j++) {
446 			if ((c[j] < '0' || c[j] > '7') &&
447 			    tolower(c[j]) != 'x') {
448 				fprintf(stderr,
449 					"error: invalid character '%c' in LSCOLORS env var\n",
450 					c[j]);
451 				c[j] = defcolors[2*i+j];
452 			}
453 			if (c[j] == 'x')
454 			    colors[i][j] = -1;
455 			else
456 			    colors[i][j] = c[j]-'0';
457 		}
458 	}
459 }
460 #endif /*COLORLS*/
461 
462 static void
463 printlink(p)
464 	FTSENT *p;
465 {
466 	int lnklen;
467 	char name[MAXPATHLEN + 1], path[MAXPATHLEN + 1];
468 
469 	if (p->fts_level == FTS_ROOTLEVEL)
470 		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
471 	else
472 		(void)snprintf(name, sizeof(name),
473 		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
474 	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
475 		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
476 		return;
477 	}
478 	path[lnklen] = '\0';
479 	if (f_octal || f_octal_escape) {
480 	        (void)printf(" -> ");
481 	        (void)prn_octal(path);
482 	}
483 	else (void)printf(" -> %s", path);
484 }
485