xref: /openbsd-src/bin/ls/print.c (revision a0747c9f67a4ae71ccb71e62a28d1ea19e06a63c)
1 /*	$OpenBSD: print.c,v 1.39 2020/10/07 21:03:09 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 *, int, int);
56 static void	printlink(FTSENT *);
57 static void	printsize(int, off_t);
58 static void	printtime(time_t);
59 static int	printtype(mode_t);
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 == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
91 	    (f_longform || f_size))
92 		(void)printf("total %llu\n", howmany(dp->btotal, blocksize));
93 
94 	for (p = dp->list; p; p = p->fts_link) {
95 		if (IS_NOPRINT(p))
96 			continue;
97 		sp = p->fts_statp;
98 		if (f_inode)
99 			(void)printf("%*llu ", dp->s_inode,
100 			    (unsigned long long)sp->st_ino);
101 		if (f_size)
102 			(void)printf("%*lld ", dp->s_block,
103 			    howmany((long long)sp->st_blocks, blocksize));
104 		(void)strmode(sp->st_mode, buf);
105 		np = p->fts_pointer;
106 		(void)printf("%s %*u ", buf, dp->s_nlink, sp->st_nlink);
107 		if (!f_grouponly)
108 			(void)printf("%-*s  ", dp->s_user, np->user);
109 		(void)printf("%-*s  ", dp->s_group, np->group);
110 		if (f_flags)
111 			(void)printf("%-*s ", dp->s_flags, np->flags);
112 		if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
113 			(void)printf("%3u, %3u ",
114 			    major(sp->st_rdev), minor(sp->st_rdev));
115 		else if (dp->bcfile)
116 			(void)printf("%*s%*lld ",
117 			    8 - dp->s_size, "", dp->s_size,
118 			    (long long)sp->st_size);
119 		else
120 			printsize(dp->s_size, sp->st_size);
121 		if (f_accesstime)
122 			printtime(sp->st_atime);
123 		else if (f_statustime)
124 			printtime(sp->st_ctime);
125 		else
126 			printtime(sp->st_mtime);
127 		(void)mbsprint(p->fts_name, 1);
128 		if (f_type || (f_typedir && S_ISDIR(sp->st_mode)))
129 			(void)printtype(sp->st_mode);
130 		if (S_ISLNK(sp->st_mode))
131 			printlink(p);
132 		(void)putchar('\n');
133 	}
134 }
135 
136 static int
137 compute_columns(DISPLAY *dp, int *pnum)
138 {
139 	int colwidth;
140 	extern int termwidth;
141 	int mywidth;
142 
143 	colwidth = dp->maxlen;
144 	if (f_inode)
145 		colwidth += dp->s_inode + 1;
146 	if (f_size)
147 		colwidth += dp->s_block + 1;
148 	if (f_type || f_typedir)
149 		colwidth += 1;
150 
151 	colwidth += 1;
152 	mywidth = termwidth + 1;	/* no extra space for last column */
153 
154 	if (mywidth < 2 * colwidth) {
155 		printscol(dp);
156 		return (0);
157 	}
158 
159 	*pnum = mywidth / colwidth;
160 	return (mywidth / *pnum);		/* spread out if possible */
161 }
162 
163 void
164 printcol(DISPLAY *dp)
165 {
166 	static FTSENT **array;
167 	static int lastentries = -1;
168 	FTSENT *p;
169 	int base, chcnt, col, colwidth, num;
170 	int numcols, numrows, row;
171 
172 	if ((colwidth = compute_columns(dp, &numcols)) == 0)
173 		return;
174 	/*
175 	 * Have to do random access in the linked list -- build a table
176 	 * of pointers.
177 	 */
178 	if (dp->entries > lastentries) {
179 		FTSENT **a;
180 
181 		if ((a = reallocarray(array, dp->entries, sizeof(FTSENT *))) ==
182 		    NULL) {
183 			free(array);
184 			array = NULL;
185 			dp->entries = 0;
186 			lastentries = -1;
187 			warn(NULL);
188 			printscol(dp);
189 			return;
190 		}
191 		lastentries = dp->entries;
192 		array = a;
193 	}
194 	for (p = dp->list, num = 0; p; p = p->fts_link)
195 		if (p->fts_number != NO_PRINT)
196 			array[num++] = p;
197 
198 	numrows = num / numcols;
199 	if (num % numcols)
200 		++numrows;
201 
202 	if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
203 	    (f_longform || f_size))
204 		(void)printf("total %llu\n", howmany(dp->btotal, blocksize));
205 	for (row = 0; row < numrows; ++row) {
206 		for (base = row, col = 0;;) {
207 			chcnt = printaname(array[base], dp->s_inode, dp->s_block);
208 			if ((base += numrows) >= num)
209 				break;
210 			if (++col == numcols)
211 				break;
212 			while (chcnt++ < colwidth)
213 				putchar(' ');
214 		}
215 		(void)putchar('\n');
216 	}
217 }
218 
219 /*
220  * print [inode] [size] name
221  * return # of characters printed, no trailing characters.
222  */
223 static int
224 printaname(FTSENT *p, int inodefield, int sizefield)
225 {
226 	struct stat *sp;
227 	int chcnt;
228 
229 	sp = p->fts_statp;
230 	chcnt = 0;
231 	if (f_inode)
232 		chcnt += printf("%*llu ", inodefield,
233 		    (unsigned long long)sp->st_ino);
234 	if (f_size)
235 		chcnt += printf("%*lld ", sizefield,
236 		    howmany((long long)sp->st_blocks, blocksize));
237 	chcnt += mbsprint(p->fts_name, 1);
238 	if (f_type || (f_typedir && S_ISDIR(sp->st_mode)))
239 		chcnt += printtype(sp->st_mode);
240 	return (chcnt);
241 }
242 
243 static void
244 printtime(time_t ftime)
245 {
246 	char f_date[DATELEN];
247 	static time_t now;
248 	static int now_set = 0;
249 
250 	if (! now_set) {
251 		now = time(NULL);
252 		now_set = 1;
253 	}
254 
255 	/*
256 	 * convert time to string, and print
257 	 */
258 	if (strftime(f_date, sizeof(f_date), f_sectime ? "%b %e %H:%M:%S %Y" :
259 	    (ftime <= now - SIXMONTHS || ftime > now) ? "%b %e  %Y" :
260 	    "%b %e %H:%M", localtime(&ftime)) == 0)
261 		f_date[0] = '\0';
262 
263 	printf("%s ", f_date);
264 }
265 
266 void
267 printacol(DISPLAY *dp)
268 {
269 	FTSENT *p;
270 	int chcnt, col, colwidth;
271 	int numcols;
272 
273 	if ( (colwidth = compute_columns(dp, &numcols)) == 0)
274 		return;
275 
276 	if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
277 	    (f_longform || f_size))
278 		(void)printf("total %llu\n", howmany(dp->btotal, blocksize));
279 	col = 0;
280 	for (p = dp->list; p; p = p->fts_link) {
281 		if (IS_NOPRINT(p))
282 			continue;
283 		if (col >= numcols) {
284 			col = 0;
285 			(void)putchar('\n');
286 		}
287 		chcnt = printaname(p, dp->s_inode, dp->s_block);
288 		col++;
289 		if (col < numcols)
290 			while (chcnt++ < colwidth)
291 				(void)putchar(' ');
292 	}
293 	(void)putchar('\n');
294 }
295 
296 void
297 printstream(DISPLAY *dp)
298 {
299 	extern int termwidth;
300 	FTSENT *p;
301 	int col;
302 	int extwidth;
303 
304 	extwidth = 0;
305 	if (f_inode)
306 		extwidth += dp->s_inode + 1;
307 	if (f_size)
308 		extwidth += dp->s_block + 1;
309 	if (f_type)
310 		extwidth += 1;
311 
312 	for (col = 0, p = dp->list; p != NULL; p = p->fts_link) {
313 		if (IS_NOPRINT(p))
314 			continue;
315 		if (col > 0) {
316 			(void)putchar(','), col++;
317 			if (col + 1 + extwidth + mbsprint(p->fts_name, 0) >=
318 			    termwidth)
319 				(void)putchar('\n'), col = 0;
320 			else
321 				(void)putchar(' '), col++;
322 		}
323 		col += printaname(p, dp->s_inode, dp->s_block);
324 	}
325 	(void)putchar('\n');
326 }
327 
328 static int
329 printtype(mode_t mode)
330 {
331 	switch (mode & S_IFMT) {
332 	case S_IFDIR:
333 		(void)putchar('/');
334 		return (1);
335 	case S_IFIFO:
336 		(void)putchar('|');
337 		return (1);
338 	case S_IFLNK:
339 		(void)putchar('@');
340 		return (1);
341 	case S_IFSOCK:
342 		(void)putchar('=');
343 		return (1);
344 	}
345 	if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
346 		(void)putchar('*');
347 		return (1);
348 	}
349 	return (0);
350 }
351 
352 static void
353 printlink(FTSENT *p)
354 {
355 	int lnklen;
356 	char name[PATH_MAX], path[PATH_MAX];
357 
358 	if (p->fts_level == FTS_ROOTLEVEL)
359 		(void)snprintf(name, sizeof(name), "%s", p->fts_name);
360 	else
361 		(void)snprintf(name, sizeof(name),
362 		    "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
363 	if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
364 		(void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
365 		return;
366 	}
367 	path[lnklen] = '\0';
368 	(void)printf(" -> ");
369 	(void)mbsprint(path, 1);
370 }
371 
372 static void
373 printsize(int width, off_t bytes)
374 {
375 	char ret[FMT_SCALED_STRSIZE];
376 
377 	if ((f_humanval) && (fmt_scaled(bytes, ret) != -1)) {
378 		(void)printf("%*s ", width, ret);
379 		return;
380 	}
381 	(void)printf("%*lld ", width, (long long)bytes);
382 }
383