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