xref: /openbsd-src/bin/ls/ls.c (revision d13be5d47e4149db2549a9828e244d59dbc43f15)
1 /*	$OpenBSD: ls.c,v 1.37 2011/03/04 21:03:19 okan 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 'a':
190 			fts_options |= FTS_SEEDOT;
191 			/* FALLTHROUGH */
192 		case 'A':
193 			f_listdot = 1;
194 			break;
195 		/* The -d option turns off the -R option. */
196 		case 'd':
197 			f_listdir = 1;
198 			f_recursive = 0;
199 			break;
200 		case 'f':
201 			f_nosort = 1;
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 btotal, maxblock, maxinode, maxlen, maxnlink;
416 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
417 	int entries, needstats;
418 	char *user, *group, buf[21];	/* 64 bits == 20 digits */
419 	char nuser[12], ngroup[12];
420 	char *flags = NULL;
421 
422 	/*
423 	 * If list is NULL there are two possibilities: that the parent
424 	 * directory p has no children, or that fts_children() returned an
425 	 * error.  We ignore the error case since it will be replicated
426 	 * on the next call to fts_read() on the post-order visit to the
427 	 * directory p, and will be signalled in traverse().
428 	 */
429 	if (list == NULL)
430 		return;
431 
432 	needstats = f_inode || f_longform || f_size;
433 	flen = 0;
434 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
435 	bcfile = 0;
436 	maxuser = maxgroup = maxflags = 0;
437 	maxsize = 0;
438 	for (cur = list, entries = 0; cur != NULL; cur = cur->fts_link) {
439 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
440 			warnx("%s: %s",
441 			    cur->fts_name, strerror(cur->fts_errno));
442 			cur->fts_number = NO_PRINT;
443 			rval = 1;
444 			continue;
445 		}
446 
447 		/*
448 		 * P is NULL if list is the argv list, to which different rules
449 		 * apply.
450 		 */
451 		if (p == NULL) {
452 			/* Directories will be displayed later. */
453 			if (cur->fts_info == FTS_D && !f_listdir) {
454 				cur->fts_number = NO_PRINT;
455 				continue;
456 			}
457 		} else {
458 			/* Only display dot file if -a/-A set. */
459 			if (cur->fts_name[0] == '.' && !f_listdot) {
460 				cur->fts_number = NO_PRINT;
461 				continue;
462 			}
463 		}
464 		if (cur->fts_namelen > maxlen)
465 			maxlen = cur->fts_namelen;
466 		if (needstats) {
467 			sp = cur->fts_statp;
468 			if (sp->st_blocks > maxblock)
469 				maxblock = sp->st_blocks;
470 			if (sp->st_ino > maxinode)
471 				maxinode = sp->st_ino;
472 			if (sp->st_nlink > maxnlink)
473 				maxnlink = sp->st_nlink;
474 			if (sp->st_size > maxsize)
475 				maxsize = sp->st_size;
476 
477 			btotal += sp->st_blocks;
478 			if (f_longform) {
479 				if (f_numericonly) {
480 					snprintf(nuser, 12, "%u", sp->st_uid);
481 					snprintf(ngroup, 12, "%u", sp->st_gid);
482 					user = nuser;
483 					group = ngroup;
484 				} else {
485 					user = user_from_uid(sp->st_uid, 0);
486 					group = group_from_gid(sp->st_gid, 0);
487 				}
488 				if ((ulen = strlen(user)) > maxuser)
489 					maxuser = ulen;
490 				if ((glen = strlen(group)) > maxgroup)
491 					maxgroup = glen;
492 				if (f_flags) {
493 					flags = fflagstostr(sp->st_flags);
494 					if (*flags == '\0')
495 						flags = "-";
496 					if ((flen = strlen(flags)) > maxflags)
497 						maxflags = flen;
498 				} else
499 					flen = 0;
500 
501 				if ((np = malloc(sizeof(NAMES) +
502 				    ulen + 1 + glen + 1 + flen + 1)) == NULL)
503 					err(1, NULL);
504 
505 				np->user = &np->data[0];
506 				(void)strlcpy(np->user, user, ulen + 1);
507 				np->group = &np->data[ulen + 1];
508 				(void)strlcpy(np->group, group, glen + 1);
509 
510 				if (S_ISCHR(sp->st_mode) ||
511 				    S_ISBLK(sp->st_mode))
512 					bcfile = 1;
513 
514 				if (f_flags) {
515 					np->flags = &np->data[ulen + 1 + glen + 1];
516 				  	(void)strlcpy(np->flags, flags, flen + 1);
517 					if (*flags != '-')
518 						free(flags);
519 				}
520 				cur->fts_pointer = np;
521 			}
522 		}
523 		++entries;
524 	}
525 
526 	if (!entries)
527 		return;
528 
529 	d.list = list;
530 	d.entries = entries;
531 	d.maxlen = maxlen;
532 	if (needstats) {
533 		d.bcfile = bcfile;
534 		d.btotal = btotal;
535 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
536 		d.s_block = strlen(buf);
537 		d.s_flags = maxflags;
538 		d.s_group = maxgroup;
539 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
540 		d.s_inode = strlen(buf);
541 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
542 		d.s_nlink = strlen(buf);
543 		if (!f_humanval) {
544 			(void)snprintf(buf, sizeof(buf), "%lld",
545 				(long long) maxsize);
546 			d.s_size = strlen(buf);
547 		} else
548 			d.s_size = FMT_SCALED_STRSIZE-2; /* no - or '\0' */
549 		d.s_user = maxuser;
550 	}
551 
552 	printfcn(&d);
553 	output = 1;
554 
555 	if (f_longform)
556 		for (cur = list; cur != NULL; cur = cur->fts_link)
557 			free(cur->fts_pointer);
558 }
559 
560 /*
561  * Ordering for mastercmp:
562  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
563  * as larger than directories.  Within either group, use the sort function.
564  * All other levels use the sort function.  Error entries remain unsorted.
565  */
566 static int
567 mastercmp(const FTSENT **a, const FTSENT **b)
568 {
569 	int a_info, b_info;
570 
571 	a_info = (*a)->fts_info;
572 	if (a_info == FTS_ERR)
573 		return (0);
574 	b_info = (*b)->fts_info;
575 	if (b_info == FTS_ERR)
576 		return (0);
577 
578 	if (a_info == FTS_NS || b_info == FTS_NS) {
579 		if (b_info != FTS_NS)
580 			return (1);
581 		else if (a_info != FTS_NS)
582 			return (-1);
583 		else
584 			return (namecmp(*a, *b));
585 	}
586 
587 	if (a_info != b_info &&
588 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
589 		if (a_info == FTS_D)
590 			return (1);
591 		if (b_info == FTS_D)
592 			return (-1);
593 	}
594 	return (sortfcn(*a, *b));
595 }
596