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