xref: /freebsd/bin/ls/ls.c (revision 17ee9d00bc1ae1e598c38f25826f861e4bc6c3ce)
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.3 1994/09/24 02:55:54 davidg 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 		(void)getbsize(&notused, &blocksize);
231 		    blocksize /= 512;
232 		if (f_kblocks)
233 		    blocksize *= 2;
234 	}
235 
236 	/* Select a sort function. */
237 	if (f_reversesort) {
238 		if (!f_timesort)
239 			sortfcn = revnamecmp;
240 		else if (f_accesstime)
241 			sortfcn = revacccmp;
242 		else if (f_statustime)
243 			sortfcn = revstatcmp;
244 		else /* Use modification time. */
245 			sortfcn = revmodcmp;
246 	} else {
247 		if (!f_timesort)
248 			sortfcn = namecmp;
249 		else if (f_accesstime)
250 			sortfcn = acccmp;
251 		else if (f_statustime)
252 			sortfcn = statcmp;
253 		else /* Use modification time. */
254 			sortfcn = modcmp;
255 	}
256 
257 	/* Select a print function. */
258 	if (f_singlecol)
259 		printfcn = printscol;
260 	else if (f_longform)
261 		printfcn = printlong;
262 	else
263 		printfcn = printcol;
264 
265 	if (argc)
266 		traverse(argc, argv, fts_options);
267 	else
268 		traverse(1, dotav, fts_options);
269 	exit(0);
270 }
271 
272 static int output;			/* If anything output. */
273 
274 /*
275  * Traverse() walks the logical directory structure specified by the argv list
276  * in the order specified by the mastercmp() comparison function.  During the
277  * traversal it passes linked lists of structures to display() which represent
278  * a superset (may be exact set) of the files to be displayed.
279  */
280 static void
281 traverse(argc, argv, options)
282 	int argc, options;
283 	char *argv[];
284 {
285 	FTS *ftsp;
286 	FTSENT *p, *chp;
287 	int ch_options;
288 
289 	if ((ftsp =
290 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
291 		err(1, NULL);
292 
293 	display(NULL, fts_children(ftsp, 0));
294 	if (f_listdir)
295 		return;
296 
297 	/*
298 	 * If not recursing down this tree and don't need stat info, just get
299 	 * the names.
300 	 */
301 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
302 
303 	while ((p = fts_read(ftsp)) != NULL)
304 		switch (p->fts_info) {
305 		case FTS_DC:
306 			warnx("%s: directory causes a cycle", p->fts_name);
307 			break;
308 		case FTS_DNR:
309 		case FTS_ERR:
310 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
311 			break;
312 		case FTS_D:
313 			if (p->fts_level != FTS_ROOTLEVEL &&
314 			    p->fts_name[0] == '.' && !f_listdot)
315 				break;
316 
317 			/*
318 			 * If already output something, put out a newline as
319 			 * a separator.  If multiple arguments, precede each
320 			 * directory with its name.
321 			 */
322 			if (output)
323 				(void)printf("\n%s:\n", p->fts_path);
324 			else if (argc > 1) {
325 				(void)printf("%s:\n", p->fts_path);
326 				output = 1;
327 			}
328 
329 			chp = fts_children(ftsp, ch_options);
330 			display(p, chp);
331 
332 			if (!f_recursive && chp != NULL)
333 				(void)fts_set(ftsp, p, FTS_SKIP);
334 			break;
335 		}
336 	if (errno)
337 		err(1, "fts_read");
338 }
339 
340 /*
341  * Display() takes a linked list of FTSENT structures and passes the list
342  * along with any other necessary information to the print function.  P
343  * points to the parent directory of the display list.
344  */
345 static void
346 display(p, list)
347 	FTSENT *p, *list;
348 {
349 	struct stat *sp;
350 	DISPLAY d;
351 	FTSENT *cur;
352 	NAMES *np;
353 	u_quad_t maxsize;
354 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
355 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
356 	int entries, needstats;
357 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
358 
359 	/*
360 	 * If list is NULL there are two possibilities: that the parent
361 	 * directory p has no children, or that fts_children() returned an
362 	 * error.  We ignore the error case since it will be replicated
363 	 * on the next call to fts_read() on the post-order visit to the
364 	 * directory p, and will be signalled in traverse().
365 	 */
366 	if (list == NULL)
367 		return;
368 
369 	needstats = f_inode || f_longform || f_size;
370 	flen = 0;
371 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
372 	bcfile = 0;
373 	maxuser = maxgroup = maxflags = 0;
374 	maxsize = 0;
375 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
376 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
377 			warnx("%s: %s",
378 			    cur->fts_name, strerror(cur->fts_errno));
379 			cur->fts_number = NO_PRINT;
380 			continue;
381 		}
382 
383 		/*
384 		 * P is NULL if list is the argv list, to which different rules
385 		 * apply.
386 		 */
387 		if (p == NULL) {
388 			/* Directories will be displayed later. */
389 			if (cur->fts_info == FTS_D && !f_listdir) {
390 				cur->fts_number = NO_PRINT;
391 				continue;
392 			}
393 		} else {
394 			/* Only display dot file if -a/-A set. */
395 			if (cur->fts_name[0] == '.' && !f_listdot) {
396 				cur->fts_number = NO_PRINT;
397 				continue;
398 			}
399 		}
400 		if (f_nonprint)
401 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
402 		if (cur->fts_namelen > maxlen)
403 			maxlen = cur->fts_namelen;
404 		if (needstats) {
405 			sp = cur->fts_statp;
406 			if (sp->st_blocks > maxblock)
407 				maxblock = sp->st_blocks;
408 			if (sp->st_ino > maxinode)
409 				maxinode = sp->st_ino;
410 			if (sp->st_nlink > maxnlink)
411 				maxnlink = sp->st_nlink;
412 			if (sp->st_size > maxsize)
413 				maxsize = sp->st_size;
414 
415 			btotal += sp->st_blocks;
416 			if (f_longform) {
417 				user = user_from_uid(sp->st_uid, 0);
418 				if ((ulen = strlen(user)) > maxuser)
419 					maxuser = ulen;
420 				group = group_from_gid(sp->st_gid, 0);
421 				if ((glen = strlen(group)) > maxgroup)
422 					maxgroup = glen;
423 				if (f_flags) {
424 					flags =
425 					    flags_to_string(sp->st_flags, "-");
426 					if ((flen = strlen(flags)) > maxflags)
427 						maxflags = flen;
428 				} else
429 					flen = 0;
430 
431 				if ((np = malloc(sizeof(NAMES) +
432 				    ulen + glen + flen + 3)) == NULL)
433 					err(1, NULL);
434 
435 				np->user = &np->data[0];
436 				(void)strcpy(np->user, user);
437 				np->group = &np->data[ulen + 1];
438 				(void)strcpy(np->group, group);
439 
440 				if (S_ISCHR(sp->st_mode) ||
441 				    S_ISBLK(sp->st_mode))
442 					bcfile = 1;
443 
444 				if (f_flags) {
445 					np->flags = &np->data[ulen + glen + 2];
446 				  	(void)strcpy(np->flags, flags);
447 				}
448 				cur->fts_pointer = np;
449 			}
450 		}
451 		++entries;
452 	}
453 
454 	if (!entries)
455 		return;
456 
457 	d.list = list;
458 	d.entries = entries;
459 	d.maxlen = maxlen;
460 	if (needstats) {
461 		d.bcfile = bcfile;
462 		d.btotal = btotal;
463 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
464 		d.s_block = strlen(buf);
465 		d.s_flags = maxflags;
466 		d.s_group = maxgroup;
467 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
468 		d.s_inode = strlen(buf);
469 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
470 		d.s_nlink = strlen(buf);
471 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
472 		d.s_size = strlen(buf);
473 		d.s_user = maxuser;
474 	}
475 
476 	printfcn(&d);
477 	output = 1;
478 
479 	if (f_longform)
480 		for (cur = list; cur; cur = cur->fts_link)
481 			free(cur->fts_pointer);
482 }
483 
484 /*
485  * Ordering for mastercmp:
486  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
487  * as larger than directories.  Within either group, use the sort function.
488  * All other levels use the sort function.  Error entries remain unsorted.
489  */
490 static int
491 mastercmp(a, b)
492 	const FTSENT **a, **b;
493 {
494 	int a_info, b_info;
495 
496 	a_info = (*a)->fts_info;
497 	if (a_info == FTS_ERR)
498 		return (0);
499 	b_info = (*b)->fts_info;
500 	if (b_info == FTS_ERR)
501 		return (0);
502 
503 	if (a_info == FTS_NS || b_info == FTS_NS)
504 		return (namecmp(*a, *b));
505 
506 	if (a_info == b_info)
507 		return (sortfcn(*a, *b));
508 
509 	if ((*a)->fts_level == FTS_ROOTLEVEL)
510 		if (a_info == FTS_D)
511 			return (1);
512 		else if (b_info == FTS_D)
513 			return (-1);
514 		else
515 			return (sortfcn(*a, *b));
516 	else
517 		return (sortfcn(*a, *b));
518 }
519