xref: /original-bsd/bin/ls/ls.c (revision 4ba124f7)
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Michael Fischbein.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #ifndef lint
12 static char copyright[] =
13 "@(#) Copyright (c) 1989, 1993, 1994\n\
14 	The Regents of the University of California.  All rights reserved.\n";
15 #endif /* not lint */
16 
17 #ifndef lint
18 static char sccsid[] = "@(#)ls.c	8.6 (Berkeley) 07/28/94";
19 #endif /* not lint */
20 
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/ioctl.h>
24 
25 #include <dirent.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <fts.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 
34 #include "ls.h"
35 #include "extern.h"
36 
37 static void	 display __P((FTSENT *, FTSENT *));
38 static int	 mastercmp __P((const FTSENT **, const FTSENT **));
39 static void	 traverse __P((int, char **, int));
40 
41 static void (*printfcn) __P((DISPLAY *));
42 static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
43 
44 long blocksize;			/* block size units */
45 int termwidth = 80;		/* default terminal width */
46 
47 /* flags */
48 int f_accesstime;		/* use time of last access */
49 int f_column;			/* columnated format */
50 int f_flags;			/* show flags associated with a file */
51 int f_inode;			/* print inode */
52 int f_listdir;			/* list actual directory, not contents */
53 int f_listdot;			/* list files beginning with . */
54 int f_longform;			/* long listing format */
55 int f_newline;			/* if precede with newline */
56 int f_nonprint;			/* show unprintables as ? */
57 int f_nosort;			/* don't sort output */
58 int f_recursive;		/* ls subdirectories also */
59 int f_reversesort;		/* reverse whatever sort is used */
60 int f_sectime;			/* print the real time for all files */
61 int f_singlecol;		/* use single column output */
62 int f_size;			/* list size in short listing */
63 int f_statustime;		/* use time of last mode change */
64 int f_dirname;			/* if precede with directory name */
65 int f_timesort;			/* sort by time vice name */
66 int f_type;			/* add type character for non-regular files */
67 int f_whiteout;			/* show whiteout entries */
68 
69 int
70 main(argc, argv)
71 	int argc;
72 	char *argv[];
73 {
74 	static char dot[] = ".", *dotav[] = { dot, NULL };
75 	struct winsize win;
76 	int ch, fts_options, notused;
77 	char *p;
78 
79 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
80 	if (isatty(STDOUT_FILENO)) {
81 		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
82 		    !win.ws_col) {
83 			if ((p = getenv("COLUMNS")) != NULL)
84 				termwidth = atoi(p);
85 		}
86 		else
87 			termwidth = win.ws_col;
88 		f_column = f_nonprint = 1;
89 	} else
90 		f_singlecol = 1;
91 
92 	/* Root is -A automatically. */
93 	if (!getuid())
94 		f_listdot = 1;
95 
96 	fts_options = FTS_PHYSICAL;
97 	while ((ch = getopt(argc, argv, "1ACFLRTWacdfgiloqrstu")) != EOF) {
98 		switch (ch) {
99 		/*
100 		 * The -1, -C and -l options all override each other so shell
101 		 * aliasing works right.
102 		 */
103 		case '1':
104 			f_singlecol = 1;
105 			f_column = f_longform = 0;
106 			break;
107 		case 'C':
108 			f_column = 1;
109 			f_longform = f_singlecol = 0;
110 			break;
111 		case 'l':
112 			f_longform = 1;
113 			f_column = f_singlecol = 0;
114 			break;
115 		/* The -c and -u options override each other. */
116 		case 'c':
117 			f_statustime = 1;
118 			f_accesstime = 0;
119 			break;
120 		case 'u':
121 			f_accesstime = 1;
122 			f_statustime = 0;
123 			break;
124 		case 'F':
125 			f_type = 1;
126 			break;
127 		case 'L':
128 			fts_options &= ~FTS_PHYSICAL;
129 			fts_options |= FTS_LOGICAL;
130 			break;
131 		case 'R':
132 			f_recursive = 1;
133 			break;
134 		case 'a':
135 			fts_options |= FTS_SEEDOT;
136 			/* FALLTHROUGH */
137 		case 'A':
138 			f_listdot = 1;
139 			break;
140 		/* The -d option turns off the -R option. */
141 		case 'd':
142 			f_listdir = 1;
143 			f_recursive = 0;
144 			break;
145 		case 'f':
146 			f_nosort = 1;
147 			break;
148 		case 'g':		/* Compatibility with 4.3BSD. */
149 			break;
150 		case 'i':
151 			f_inode = 1;
152 			break;
153 		case 'o':
154 			f_flags = 1;
155 			break;
156 		case 'q':
157 			f_nonprint = 1;
158 			break;
159 		case 'r':
160 			f_reversesort = 1;
161 			break;
162 		case 's':
163 			f_size = 1;
164 			break;
165 		case 'T':
166 			f_sectime = 1;
167 			break;
168 		case 't':
169 			f_timesort = 1;
170 			break;
171 		case 'W':
172 			f_whiteout = 1;
173 			break;
174 		default:
175 		case '?':
176 			usage();
177 		}
178 	}
179 	argc -= optind;
180 	argv += optind;
181 
182 	/*
183 	 * If not -F, -i, -l, -s or -t options, don't require stat
184 	 * information.
185 	 */
186 	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
187 		fts_options |= FTS_NOSTAT;
188 
189 	/*
190 	 * If not -F, -d or -l options, follow any symbolic links listed on
191 	 * the command line.
192 	 */
193 	if (!f_longform && !f_listdir && !f_type)
194 		fts_options |= FTS_COMFOLLOW;
195 
196 	/*
197 	 * If -W, show whiteout entries
198 	 */
199 	if (f_whiteout)
200 		fts_options |= FTS_WHITEOUT;
201 
202 	/* If -l or -s, figure out block size. */
203 	if (f_longform || f_size) {
204 		(void)getbsize(&notused, &blocksize);
205 		blocksize /= 512;
206 	}
207 
208 	/* Select a sort function. */
209 	if (f_reversesort) {
210 		if (!f_timesort)
211 			sortfcn = revnamecmp;
212 		else if (f_accesstime)
213 			sortfcn = revacccmp;
214 		else if (f_statustime)
215 			sortfcn = revstatcmp;
216 		else /* Use modification time. */
217 			sortfcn = revmodcmp;
218 	} else {
219 		if (!f_timesort)
220 			sortfcn = namecmp;
221 		else if (f_accesstime)
222 			sortfcn = acccmp;
223 		else if (f_statustime)
224 			sortfcn = statcmp;
225 		else /* Use modification time. */
226 			sortfcn = modcmp;
227 	}
228 
229 	/* Select a print function. */
230 	if (f_singlecol)
231 		printfcn = printscol;
232 	else if (f_longform)
233 		printfcn = printlong;
234 	else
235 		printfcn = printcol;
236 
237 	if (argc)
238 		traverse(argc, argv, fts_options);
239 	else
240 		traverse(1, dotav, fts_options);
241 	exit(0);
242 }
243 
244 static int output;			/* If anything output. */
245 
246 /*
247  * Traverse() walks the logical directory structure specified by the argv list
248  * in the order specified by the mastercmp() comparison function.  During the
249  * traversal it passes linked lists of structures to display() which represent
250  * a superset (may be exact set) of the files to be displayed.
251  */
252 static void
253 traverse(argc, argv, options)
254 	int argc, options;
255 	char *argv[];
256 {
257 	FTS *ftsp;
258 	FTSENT *p, *chp;
259 	int ch_options;
260 
261 	if ((ftsp =
262 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
263 		err(1, NULL);
264 
265 	display(NULL, fts_children(ftsp, 0));
266 	if (f_listdir)
267 		return;
268 
269 	/*
270 	 * If not recursing down this tree and don't need stat info, just get
271 	 * the names.
272 	 */
273 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
274 
275 	while ((p = fts_read(ftsp)) != NULL)
276 		switch (p->fts_info) {
277 		case FTS_DC:
278 			warnx("%s: directory causes a cycle", p->fts_name);
279 			break;
280 		case FTS_DNR:
281 		case FTS_ERR:
282 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
283 			break;
284 		case FTS_D:
285 			if (p->fts_level != FTS_ROOTLEVEL &&
286 			    p->fts_name[0] == '.' && !f_listdot)
287 				break;
288 
289 			/*
290 			 * If already output something, put out a newline as
291 			 * a separator.  If multiple arguments, precede each
292 			 * directory with its name.
293 			 */
294 			if (output)
295 				(void)printf("\n%s:\n", p->fts_path);
296 			else if (argc > 1) {
297 				(void)printf("%s:\n", p->fts_path);
298 				output = 1;
299 			}
300 
301 			chp = fts_children(ftsp, ch_options);
302 			display(p, chp);
303 
304 			if (!f_recursive && chp != NULL)
305 				(void)fts_set(ftsp, p, FTS_SKIP);
306 			break;
307 		}
308 	if (errno)
309 		err(1, "fts_read");
310 }
311 
312 /*
313  * Display() takes a linked list of FTSENT structures and passes the list
314  * along with any other necessary information to the print function.  P
315  * points to the parent directory of the display list.
316  */
317 static void
318 display(p, list)
319 	FTSENT *p, *list;
320 {
321 	struct stat *sp;
322 	DISPLAY d;
323 	FTSENT *cur;
324 	NAMES *np;
325 	u_quad_t maxsize;
326 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
327 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
328 	int entries, needstats;
329 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
330 
331 	/*
332 	 * If list is NULL there are two possibilities: that the parent
333 	 * directory p has no children, or that fts_children() returned an
334 	 * error.  We ignore the error case since it will be replicated
335 	 * on the next call to fts_read() on the post-order visit to the
336 	 * directory p, and will be signalled in traverse().
337 	 */
338 	if (list == NULL)
339 		return;
340 
341 	needstats = f_inode || f_longform || f_size;
342 	flen = 0;
343 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
344 	bcfile = 0;
345 	maxuser = maxgroup = maxflags = 0;
346 	maxsize = 0;
347 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
348 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
349 			warnx("%s: %s",
350 			    cur->fts_name, strerror(cur->fts_errno));
351 			cur->fts_number = NO_PRINT;
352 			continue;
353 		}
354 
355 		/*
356 		 * P is NULL if list is the argv list, to which different rules
357 		 * apply.
358 		 */
359 		if (p == NULL) {
360 			/* Directories will be displayed later. */
361 			if (cur->fts_info == FTS_D && !f_listdir) {
362 				cur->fts_number = NO_PRINT;
363 				continue;
364 			}
365 		} else {
366 			/* Only display dot file if -a/-A set. */
367 			if (cur->fts_name[0] == '.' && !f_listdot) {
368 				cur->fts_number = NO_PRINT;
369 				continue;
370 			}
371 		}
372 		if (f_nonprint)
373 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
374 		if (cur->fts_namelen > maxlen)
375 			maxlen = cur->fts_namelen;
376 		if (needstats) {
377 			sp = cur->fts_statp;
378 			if (sp->st_blocks > maxblock)
379 				maxblock = sp->st_blocks;
380 			if (sp->st_ino > maxinode)
381 				maxinode = sp->st_ino;
382 			if (sp->st_nlink > maxnlink)
383 				maxnlink = sp->st_nlink;
384 			if (sp->st_size > maxsize)
385 				maxsize = sp->st_size;
386 
387 			btotal += sp->st_blocks;
388 			if (f_longform) {
389 				user = user_from_uid(sp->st_uid, 0);
390 				if ((ulen = strlen(user)) > maxuser)
391 					maxuser = ulen;
392 				group = group_from_gid(sp->st_gid, 0);
393 				if ((glen = strlen(group)) > maxgroup)
394 					maxgroup = glen;
395 				if (f_flags) {
396 					flags =
397 					    flags_to_string(sp->st_flags, "-");
398 					if ((flen = strlen(flags)) > maxflags)
399 						maxflags = flen;
400 				} else
401 					flen = 0;
402 
403 				if ((np = malloc(sizeof(NAMES) +
404 				    ulen + glen + flen + 3)) == NULL)
405 					err(1, NULL);
406 
407 				np->user = &np->data[0];
408 				(void)strcpy(np->user, user);
409 				np->group = &np->data[ulen + 1];
410 				(void)strcpy(np->group, group);
411 
412 				if (S_ISCHR(sp->st_mode) ||
413 				    S_ISBLK(sp->st_mode))
414 					bcfile = 1;
415 
416 				if (f_flags) {
417 					np->flags = &np->data[ulen + glen + 2];
418 				  	(void)strcpy(np->flags, flags);
419 				}
420 				cur->fts_pointer = np;
421 			}
422 		}
423 		++entries;
424 	}
425 
426 	if (!entries)
427 		return;
428 
429 	d.list = list;
430 	d.entries = entries;
431 	d.maxlen = maxlen;
432 	if (needstats) {
433 		d.bcfile = bcfile;
434 		d.btotal = btotal;
435 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
436 		d.s_block = strlen(buf);
437 		d.s_flags = maxflags;
438 		d.s_group = maxgroup;
439 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
440 		d.s_inode = strlen(buf);
441 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
442 		d.s_nlink = strlen(buf);
443 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
444 		d.s_size = strlen(buf);
445 		d.s_user = maxuser;
446 	}
447 
448 	printfcn(&d);
449 	output = 1;
450 
451 	if (f_longform)
452 		for (cur = list; cur; cur = cur->fts_link)
453 			free(cur->fts_pointer);
454 }
455 
456 /*
457  * Ordering for mastercmp:
458  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
459  * as larger than directories.  Within either group, use the sort function.
460  * All other levels use the sort function.  Error entries remain unsorted.
461  */
462 static int
463 mastercmp(a, b)
464 	const FTSENT **a, **b;
465 {
466 	int a_info, b_info;
467 
468 	a_info = (*a)->fts_info;
469 	if (a_info == FTS_ERR)
470 		return (0);
471 	b_info = (*b)->fts_info;
472 	if (b_info == FTS_ERR)
473 		return (0);
474 
475 	if (a_info == FTS_NS || b_info == FTS_NS)
476 		return (namecmp(*a, *b));
477 
478 	if (a_info == b_info)
479 		return (sortfcn(*a, *b));
480 
481 	if ((*a)->fts_level == FTS_ROOTLEVEL)
482 		if (a_info == FTS_D)
483 			return (1);
484 		else if (b_info == FTS_D)
485 			return (-1);
486 		else
487 			return (sortfcn(*a, *b));
488 	else
489 		return (sortfcn(*a, *b));
490 }
491