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