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