xref: /openbsd/bin/ls/print.c (revision 8529ddd3)
1 /*	$OpenBSD: print.c,v 1.34 2015/03/15 00:41:27 millert Exp $	*/
2 /*	$NetBSD: print.c,v 1.15 1996/12/11 03:25:39 thorpej Exp $	*/
3 
4 /*
5  * Copyright (c) 1989, 1993, 1994
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Michael Fischbein.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 
39 #include <err.h>
40 #include <errno.h>
41 #include <fts.h>
42 #include <grp.h>
43 #include <pwd.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <time.h>
48 #include <unistd.h>
49 #include <limits.h>
50 #include <util.h>
51 
52 #include "ls.h"
53 #include "extern.h"
54 
55 static int	printaname(FTSENT *, u_long, u_long);
56 static void	printlink(FTSENT *);
57 static void	printsize(size_t, off_t);
58 static void	printtime(time_t);
59 static int	printtype(u_int);
60 static int	compute_columns(DISPLAY *, int *);
61 
62 #define	IS_NOPRINT(p)	((p)->fts_number == NO_PRINT)
63 
64 #define	DATELEN		64
65 
66 #define	SECSPERDAY	(24 * 60 * 60)
67 #define	SIXMONTHS	(SECSPERDAY * 365 / 2)
68 
69 void
70 printscol(DISPLAY *dp)
71 {
72 	FTSENT *p;
73 
74 	for (p = dp->list; p; p = p->fts_link) {
75 		if (IS_NOPRINT(p))
76 			continue;
77 		(void)printaname(p, dp->s_inode, dp->s_block);
78 		(void)putchar('\n');
79 	}
80 }
81 
82 void
83 printlong(DISPLAY *dp)
84 {
85 	struct stat *sp;
86 	FTSENT *p;
87 	NAMES *np;
88 	char buf[20];
89 
90 	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
91 		(void)printf("total %llu\n", howmany(dp->btotal, blocksize));
92 
93 	for (p = dp->list; p; p = p->fts_link) {
94 		if (IS_NOPRINT(p))
95 			continue;
96 		sp = p->fts_statp;
97 		if (f_inode)
98 			(void)printf("%*llu ", dp->s_inode,
99 			    (unsigned long long)sp->st_ino);
100 		if (f_size)
101 			(void)printf("%*qd ",
102 			    dp->s_block, howmany(sp->st_blocks, blocksize));
103 		(void)strmode(sp->st_mode, buf);
104 		np = p->fts_pointer;
105 		(void)printf("%s %*u ", buf, dp->s_nlink, sp->st_nlink);
106 		if (!f_grouponly)
107 			(void)printf("%-*s  ", dp->s_user, np->user);
108 		(void)printf("%-*s  ", dp->s_group, np->group);
109 		if (f_flags)
110 			(void)printf("%-*s ", dp->s_flags, np->flags);
111 		if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
112 			(void)printf("%3d, %3d ",
113 			    major(sp->st_rdev), minor(sp->st_rdev));
114 		else if (dp->bcfile)
115 			(void)printf("%*s%*qd ",
116 			    8 - dp->s_size, "", dp->s_size, sp->st_size);
117 		else
118 			printsize(dp->s_size, sp->st_size);
119 		if (f_accesstime)
120 			printtime(sp->st_atime);
121 		else if (f_statustime)
122 			printtime(sp->st_ctime);
123 		else
124 			printtime(sp->st_mtime);
125 		(void)putname(p->fts_name);
126 		if (f_type || (f_typedir && S_ISDIR(sp->st_mode)))
127 			(void)printtype(sp->st_mode);
128 		if (S_ISLNK(sp->st_mode))
129 			printlink(p);
130 		(void)putchar('\n');
131 	}
132 }
133 
134 static int
135 compute_columns(DISPLAY *dp, int *pnum)
136 {
137 	int colwidth;
138 	extern int termwidth;
139 	int mywidth;
140 
141 	colwidth = dp->maxlen;
142 	if (f_inode)
143 		colwidth += dp->s_inode + 1;
144 	if (f_size)
145 		colwidth += dp->s_block + 1;
146 	if (f_type || f_typedir)
147 		colwidth += 1;
148 
149 	colwidth += 1;
150 	mywidth = termwidth + 1;	/* no extra space for last column */
151 
152 	if (mywidth < 2 * colwidth) {
153 		printscol(dp);
154 		return (0);
155 	}
156 
157 	*pnum = mywidth / colwidth;
158 	return (mywidth / *pnum);		/* spread out if possible */
159 }
160 
161 void
162 printcol(DISPLAY *dp)
163 {
164 	static FTSENT **array;
165 	static int lastentries = -1;
166 	FTSENT *p;
167 	int base, chcnt, col, colwidth, num;
168 	int numcols, numrows, row;
169 
170 	if ((colwidth = compute_columns(dp, &numcols)) == 0)
171 		return;
172 	/*
173 	 * Have to do random access in the linked list -- build a table
174 	 * of pointers.
175 	 */
176 	if (dp->entries > lastentries) {
177 		FTSENT **a;
178 
179 		if ((a = reallocarray(array, dp->entries, sizeof(FTSENT *))) ==
180 		    NULL) {
181 			free(array);
182 			array = NULL;
183 			dp->entries = 0;
184 			lastentries = -1;
185 			warn(NULL);
186 			printscol(dp);
187 			return;
188 		}
189 		lastentries = dp->entries;
190 		array = a;
191 	}
192 	for (p = dp->list, num = 0; p; p = p->fts_link)
193 		if (p->fts_number != NO_PRINT)
194 			array[num++] = p;
195 
196 	numrows = num / numcols;
197 	if (num % numcols)
198 		++numrows;
199 
200 	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
201 		(void)printf("total %llu\n", howmany(dp->btotal, blocksize));
202 	for (row = 0; row < numrows; ++row) {
203 		for (base = row, col = 0;;) {
204 			chcnt = printaname(array[base], dp->s_inode, dp->s_block);
205 			if ((base += numrows) >= num)
206 				break;
207 			if (++col == numcols)
208 				break;
209 			while (chcnt++ < colwidth)
210 				putchar(' ');
211 		}
212 		(void)putchar('\n');
213 	}
214 }
215 
216 /*
217  * print [inode] [size] name
218  * return # of characters printed, no trailing characters.
219  */
220 static int
221 printaname(FTSENT *p, u_long inodefield, u_long sizefield)
222 {
223 	struct stat *sp;
224 	int chcnt;
225 
226 	sp = p->fts_statp;
227 	chcnt = 0;
228 	if (f_inode)
229 		chcnt += printf("%*llu ", (int)inodefield,
230 		    (unsigned long long)sp->st_ino);
231 	if (f_size)
232 		chcnt += printf("%*qd ",
233 		    (int)sizefield, howmany(sp->st_blocks, blocksize));
234 	chcnt += putname(p->fts_name);
235 	if (f_type || (f_typedir && S_ISDIR(sp->st_mode)))
236 		chcnt += printtype(sp->st_mode);
237 	return (chcnt);
238 }
239 
240 static void
241 printtime(time_t ftime)
242 {
243 	char f_date[DATELEN];
244 	static time_t now;
245 	static int now_set = 0;
246 
247 	if (! now_set) {
248 		now = time(NULL);
249 		now_set = 1;
250 	}
251 
252 	/*
253 	 * convert time to string, and print
254 	 */
255 	if (strftime(f_date, sizeof(f_date), f_sectime ? "%b %e %H:%M:%S %Y" :
256 	    (ftime <= now - SIXMONTHS || ftime > now) ? "%b %e  %Y" :
257 	    "%b %e %H:%M", localtime(&ftime)) == 0)
258 		f_date[0] = '\0';
259 
260 	printf("%s ", f_date);
261 }
262 
263 void
264 printacol(DISPLAY *dp)
265 {
266 	FTSENT *p;
267 	int chcnt, col, colwidth;
268 	int numcols;
269 
270 	if ( (colwidth = compute_columns(dp, &numcols)) == 0)
271 		return;
272 
273 	if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
274 		(void)printf("total %llu\n", howmany(dp->btotal, blocksize));
275 	col = 0;
276 	for (p = dp->list; p; p = p->fts_link) {
277 		if (IS_NOPRINT(p))
278 			continue;
279 		if (col >= numcols) {
280 			col = 0;
281 			(void)putchar('\n');
282 		}
283 		chcnt = printaname(p, dp->s_inode, dp->s_block);
284 		col++;
285 		if (col < numcols)
286 			while (chcnt++ < colwidth)
287 				(void)putchar(' ');
288 	}
289 	(void)putchar('\n');
290 }
291 
292 void
293 printstream(DISPLAY *dp)
294 {
295 	extern int termwidth;
296 	FTSENT *p;
297 	int col;
298 	int extwidth;
299 
300 	extwidth = 0;
301 	if (f_inode)
302 		extwidth += dp->s_inode + 1;
303 	if (f_size)
304 		extwidth += dp->s_block + 1;
305 	if (f_type)
306 		extwidth += 1;
307 
308 	for (col = 0, p = dp->list; p != NULL; p = p->fts_link) {
309 		if (IS_NOPRINT(p))
310 			continue;
311 		if (col > 0) {
312 			(void)putchar(','), col++;
313 			if (col + 1 + extwidth + p->fts_namelen >= termwidth)
314 				(void)putchar('\n'), col = 0;
315 			else
316 				(void)putchar(' '), col++;
317 		}
318 		col += printaname(p, dp->s_inode, dp->s_block);
319 	}
320 	(void)putchar('\n');
321 }
322 
323 static int
324 printtype(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 	}
340 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
341 		(void)putchar('*');
342 		return (1);
343 	}
344 	return (0);
345 }
346 
347 static void
348 printlink(FTSENT *p)
349 {
350 	int lnklen;
351 	char name[PATH_MAX], path[PATH_MAX];
352 
353 	if (p->fts_level == FTS_ROOTLEVEL)
354 		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
355 	else
356 		(void)snprintf(name, sizeof(name),
357 		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
358 	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
359 		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
360 		return;
361 	}
362 	path[lnklen] = '\0';
363 	(void)printf(" -> ");
364 	(void)putname(path);
365 }
366 
367 static void
368 printsize(size_t width, off_t bytes)
369 {
370 	char ret[FMT_SCALED_STRSIZE];
371 
372 	if ((f_humanval) && (fmt_scaled(bytes, ret) != -1)) {
373 		(void)printf("%*s ", (u_int)width, ret);
374 		return;
375 	}
376 	(void)printf("%*qd ", (u_int)width, bytes);
377 }
378