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