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