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