xref: /freebsd/bin/ls/ls.c (revision 0de89efe5c443f213c7ea28773ef2dc6cf3af2ed)
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 static const char copyright[] =
39 "@(#) Copyright (c) 1989, 1993, 1994\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "@(#)ls.c	8.5 (Berkeley) 4/2/94";
46 #else
47 static const char rcsid[] =
48 	"$Id: ls.c,v 1.16 1997/08/07 22:28:23 steve Exp $";
49 #endif
50 #endif /* not lint */
51 
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <sys/ioctl.h>
55 
56 #include <dirent.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fts.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 #include <locale.h>
65 
66 #include "ls.h"
67 #include "extern.h"
68 
69 static void	 display __P((FTSENT *, FTSENT *));
70 static int	 mastercmp __P((const FTSENT **, const FTSENT **));
71 static void	 traverse __P((int, char **, int));
72 
73 static void (*printfcn) __P((DISPLAY *));
74 static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
75 
76 long blocksize;			/* block size units */
77 int termwidth = 80;		/* default terminal width */
78 
79 /* flags */
80 int f_accesstime;		/* use time of last access */
81 int f_column;			/* columnated format */
82 int f_flags;			/* show flags associated with a file */
83 int f_inode;			/* print inode */
84 int f_kblocks;			/* print size in kilobytes */
85 int f_listdir;			/* list actual directory, not contents */
86 int f_listdot;			/* list files beginning with . */
87 int f_longform;			/* long listing format */
88 int f_newline;			/* if precede with newline */
89 int f_nonprint;			/* show unprintables as ? */
90 int f_nosort;			/* don't sort output */
91 int f_recursive;		/* ls subdirectories also */
92 int f_reversesort;		/* reverse whatever sort is used */
93 int f_sectime;			/* print the real time for all files */
94 int f_singlecol;		/* use single column output */
95 int f_size;			/* list size in short listing */
96 int f_statustime;		/* use time of last mode change */
97 int f_dirname;			/* if precede with directory name */
98 int f_timesort;			/* sort by time vice name */
99 int f_type;			/* add type character for non-regular files */
100 int f_whiteout;			/* show whiteout entries */
101 
102 int rval;
103 
104 int
105 main(argc, argv)
106 	int argc;
107 	char *argv[];
108 {
109 	static char dot[] = ".", *dotav[] = { dot, NULL };
110 	struct winsize win;
111 	int ch, fts_options, notused;
112 	char *p;
113 
114 	(void) setlocale(LC_ALL, "");
115 
116 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
117 	if (isatty(STDOUT_FILENO)) {
118 		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
119 		    !win.ws_col) {
120 			if ((p = getenv("COLUMNS")) != NULL)
121 				termwidth = atoi(p);
122 		}
123 		else
124 			termwidth = win.ws_col;
125 		f_column = f_nonprint = 1;
126 	} else {
127 		f_singlecol = 1;
128 		/* retrieve environment variable, in case of explicit -C */
129 		if ((p = getenv("COLUMNS")))
130 			termwidth = atoi(p);
131 	}
132 
133 	/* Root is -A automatically. */
134 	if (!getuid())
135 		f_listdot = 1;
136 
137 	fts_options = FTS_PHYSICAL;
138 	while ((ch = getopt(argc, argv, "1ACFLRTWacdfgikloqrstu")) != -1) {
139 		switch (ch) {
140 		/*
141 		 * The -1, -C and -l options all override each other so shell
142 		 * aliasing works right.
143 		 */
144 		case '1':
145 			f_singlecol = 1;
146 			f_column = f_longform = 0;
147 			break;
148 		case 'C':
149 			f_column = 1;
150 			f_longform = f_singlecol = 0;
151 			break;
152 		case 'l':
153 			f_longform = 1;
154 			f_column = f_singlecol = 0;
155 			break;
156 		/* The -c and -u options override each other. */
157 		case 'c':
158 			f_statustime = 1;
159 			f_accesstime = 0;
160 			break;
161 		case 'u':
162 			f_accesstime = 1;
163 			f_statustime = 0;
164 			break;
165 		case 'F':
166 			f_type = 1;
167 			break;
168 		case 'L':
169 			fts_options &= ~FTS_PHYSICAL;
170 			fts_options |= FTS_LOGICAL;
171 			break;
172 		case 'R':
173 			f_recursive = 1;
174 			break;
175 		case 'a':
176 			fts_options |= FTS_SEEDOT;
177 			/* FALLTHROUGH */
178 		case 'A':
179 			f_listdot = 1;
180 			break;
181 		/* The -d option turns off the -R option. */
182 		case 'd':
183 			f_listdir = 1;
184 			f_recursive = 0;
185 			break;
186 		case 'f':
187 			f_nosort = 1;
188 			break;
189 		case 'g':		/* Compatibility with 4.3BSD. */
190 			break;
191 		case 'i':
192 			f_inode = 1;
193 			break;
194 		case 'k':
195 			f_kblocks = 1;
196 			break;
197 		case 'o':
198 			f_flags = 1;
199 			break;
200 		case 'q':
201 			f_nonprint = 1;
202 			break;
203 		case 'r':
204 			f_reversesort = 1;
205 			break;
206 		case 's':
207 			f_size = 1;
208 			break;
209 		case 'T':
210 			f_sectime = 1;
211 			break;
212 		case 't':
213 			f_timesort = 1;
214 			break;
215 		case 'W':
216 			f_whiteout = 1;
217 			break;
218 		default:
219 		case '?':
220 			usage();
221 		}
222 	}
223 	argc -= optind;
224 	argv += optind;
225 
226 	/*
227 	 * If not -F, -i, -l, -s or -t options, don't require stat
228 	 * information.
229 	 */
230 	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
231 		fts_options |= FTS_NOSTAT;
232 
233 	/*
234 	 * If not -F, -d or -l options, follow any symbolic links listed on
235 	 * the command line.
236 	 */
237 	if (!f_longform && !f_listdir && !f_type)
238 		fts_options |= FTS_COMFOLLOW;
239 
240 	/*
241 	 * If -W, show whiteout entries
242 	 */
243 #ifdef FTS_WHITEOUT
244 	if (f_whiteout)
245 		fts_options |= FTS_WHITEOUT;
246 #endif
247 
248 	/* If -l or -s, figure out block size. */
249 	if (f_longform || f_size) {
250 		if (f_kblocks)
251 			blocksize = 2;
252 		else {
253 			(void)getbsize(&notused, &blocksize);
254 			blocksize /= 512;
255 		}
256 	}
257 
258 	/* Select a sort function. */
259 	if (f_reversesort) {
260 		if (!f_timesort)
261 			sortfcn = revnamecmp;
262 		else if (f_accesstime)
263 			sortfcn = revacccmp;
264 		else if (f_statustime)
265 			sortfcn = revstatcmp;
266 		else /* Use modification time. */
267 			sortfcn = revmodcmp;
268 	} else {
269 		if (!f_timesort)
270 			sortfcn = namecmp;
271 		else if (f_accesstime)
272 			sortfcn = acccmp;
273 		else if (f_statustime)
274 			sortfcn = statcmp;
275 		else /* Use modification time. */
276 			sortfcn = modcmp;
277 	}
278 
279 	/* Select a print function. */
280 	if (f_singlecol)
281 		printfcn = printscol;
282 	else if (f_longform)
283 		printfcn = printlong;
284 	else
285 		printfcn = printcol;
286 
287 	if (argc)
288 		traverse(argc, argv, fts_options);
289 	else
290 		traverse(1, dotav, fts_options);
291 	exit(rval);
292 }
293 
294 static int output;			/* If anything output. */
295 
296 /*
297  * Traverse() walks the logical directory structure specified by the argv list
298  * in the order specified by the mastercmp() comparison function.  During the
299  * traversal it passes linked lists of structures to display() which represent
300  * a superset (may be exact set) of the files to be displayed.
301  */
302 static void
303 traverse(argc, argv, options)
304 	int argc, options;
305 	char *argv[];
306 {
307 	FTS *ftsp;
308 	FTSENT *p, *chp;
309 	int ch_options;
310 
311 	if ((ftsp =
312 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
313 		err(1, NULL);
314 
315 	display(NULL, fts_children(ftsp, 0));
316 	if (f_listdir)
317 		return;
318 
319 	/*
320 	 * If not recursing down this tree and don't need stat info, just get
321 	 * the names.
322 	 */
323 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
324 
325 	while ((p = fts_read(ftsp)) != NULL)
326 		switch (p->fts_info) {
327 		case FTS_DC:
328 			warnx("%s: directory causes a cycle", p->fts_name);
329 			break;
330 		case FTS_DNR:
331 		case FTS_ERR:
332 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
333 			rval = 1;
334 			break;
335 		case FTS_D:
336 			if (p->fts_level != FTS_ROOTLEVEL &&
337 			    p->fts_name[0] == '.' && !f_listdot)
338 				break;
339 
340 			/*
341 			 * If already output something, put out a newline as
342 			 * a separator.  If multiple arguments, precede each
343 			 * directory with its name.
344 			 */
345 			if (output)
346 				(void)printf("\n%s:\n", p->fts_path);
347 			else if (argc > 1) {
348 				(void)printf("%s:\n", p->fts_path);
349 				output = 1;
350 			}
351 
352 			chp = fts_children(ftsp, ch_options);
353 			display(p, chp);
354 
355 			if (!f_recursive && chp != NULL)
356 				(void)fts_set(ftsp, p, FTS_SKIP);
357 			break;
358 		}
359 	if (errno)
360 		err(1, "fts_read");
361 }
362 
363 /*
364  * Display() takes a linked list of FTSENT structures and passes the list
365  * along with any other necessary information to the print function.  P
366  * points to the parent directory of the display list.
367  */
368 static void
369 display(p, list)
370 	FTSENT *p, *list;
371 {
372 	struct stat *sp;
373 	DISPLAY d;
374 	FTSENT *cur;
375 	NAMES *np;
376 	u_quad_t maxsize;
377 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
378 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
379 	int entries, needstats;
380 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
381 
382 	/*
383 	 * If list is NULL there are two possibilities: that the parent
384 	 * directory p has no children, or that fts_children() returned an
385 	 * error.  We ignore the error case since it will be replicated
386 	 * on the next call to fts_read() on the post-order visit to the
387 	 * directory p, and will be signalled in traverse().
388 	 */
389 	if (list == NULL)
390 		return;
391 
392 	needstats = f_inode || f_longform || f_size;
393 	flen = 0;
394 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
395 	bcfile = 0;
396 	maxuser = maxgroup = maxflags = 0;
397 	flags = NULL;
398 	maxsize = 0;
399 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
400 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
401 			warnx("%s: %s",
402 			    cur->fts_name, strerror(cur->fts_errno));
403 			cur->fts_number = NO_PRINT;
404 			rval = 1;
405 			continue;
406 		}
407 
408 		/*
409 		 * P is NULL if list is the argv list, to which different rules
410 		 * apply.
411 		 */
412 		if (p == NULL) {
413 			/* Directories will be displayed later. */
414 			if (cur->fts_info == FTS_D && !f_listdir) {
415 				cur->fts_number = NO_PRINT;
416 				continue;
417 			}
418 		} else {
419 			/* Only display dot file if -a/-A set. */
420 			if (cur->fts_name[0] == '.' && !f_listdot) {
421 				cur->fts_number = NO_PRINT;
422 				continue;
423 			}
424 		}
425 		if (f_nonprint)
426 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
427 		if (cur->fts_namelen > maxlen)
428 			maxlen = cur->fts_namelen;
429 		if (needstats) {
430 			sp = cur->fts_statp;
431 			if (sp->st_blocks > maxblock)
432 				maxblock = sp->st_blocks;
433 			if (sp->st_ino > maxinode)
434 				maxinode = sp->st_ino;
435 			if (sp->st_nlink > maxnlink)
436 				maxnlink = sp->st_nlink;
437 			if (sp->st_size > maxsize)
438 				maxsize = sp->st_size;
439 
440 			btotal += sp->st_blocks;
441 			if (f_longform) {
442 				user = user_from_uid(sp->st_uid, 0);
443 				if ((ulen = strlen(user)) > maxuser)
444 					maxuser = ulen;
445 				group = group_from_gid(sp->st_gid, 0);
446 				if ((glen = strlen(group)) > maxgroup)
447 					maxgroup = glen;
448 				if (f_flags) {
449 					flags =
450 					    flags_to_string(sp->st_flags, "-");
451 					if ((flen = strlen(flags)) > maxflags)
452 						maxflags = flen;
453 				} else
454 					flen = 0;
455 
456 				if ((np = malloc(sizeof(NAMES) +
457 				    ulen + glen + flen + 3)) == NULL)
458 					err(1, NULL);
459 
460 				np->user = &np->data[0];
461 				(void)strcpy(np->user, user);
462 				np->group = &np->data[ulen + 1];
463 				(void)strcpy(np->group, group);
464 
465 				if (S_ISCHR(sp->st_mode) ||
466 				    S_ISBLK(sp->st_mode))
467 					bcfile = 1;
468 
469 				if (f_flags) {
470 					np->flags = &np->data[ulen + glen + 2];
471 				  	(void)strcpy(np->flags, flags);
472 				}
473 				cur->fts_pointer = np;
474 			}
475 		}
476 		++entries;
477 	}
478 
479 	if (!entries)
480 		return;
481 
482 	d.list = list;
483 	d.entries = entries;
484 	d.maxlen = maxlen;
485 	if (needstats) {
486 		d.bcfile = bcfile;
487 		d.btotal = btotal;
488 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
489 		d.s_block = strlen(buf);
490 		d.s_flags = maxflags;
491 		d.s_group = maxgroup;
492 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
493 		d.s_inode = strlen(buf);
494 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
495 		d.s_nlink = strlen(buf);
496 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
497 		d.s_size = strlen(buf);
498 		d.s_user = maxuser;
499 	}
500 
501 	printfcn(&d);
502 	output = 1;
503 
504 	if (f_longform)
505 		for (cur = list; cur; cur = cur->fts_link)
506 			free(cur->fts_pointer);
507 }
508 
509 /*
510  * Ordering for mastercmp:
511  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
512  * as larger than directories.  Within either group, use the sort function.
513  * All other levels use the sort function.  Error entries remain unsorted.
514  */
515 static int
516 mastercmp(a, b)
517 	const FTSENT **a, **b;
518 {
519 	int a_info, b_info;
520 
521 	a_info = (*a)->fts_info;
522 	if (a_info == FTS_ERR)
523 		return (0);
524 	b_info = (*b)->fts_info;
525 	if (b_info == FTS_ERR)
526 		return (0);
527 
528 	if (a_info == FTS_NS || b_info == FTS_NS)
529 		return (namecmp(*a, *b));
530 
531 	if (a_info != b_info &&
532 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
533 		if (a_info == FTS_D)
534 			return (1);
535 		if (b_info == FTS_D)
536 			return (-1);
537 	}
538 	return (sortfcn(*a, *b));
539 }
540