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