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