xref: /original-bsd/bin/ls/ls.c (revision 609590b9)
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.7 (Berkeley) 08/05/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
main(argc,argv)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 #ifdef FTS_WHITEOUT
200 	if (f_whiteout)
201 		fts_options |= FTS_WHITEOUT;
202 #endif
203 
204 	/* If -l or -s, figure out block size. */
205 	if (f_longform || f_size) {
206 		(void)getbsize(&notused, &blocksize);
207 		blocksize /= 512;
208 	}
209 
210 	/* Select a sort function. */
211 	if (f_reversesort) {
212 		if (!f_timesort)
213 			sortfcn = revnamecmp;
214 		else if (f_accesstime)
215 			sortfcn = revacccmp;
216 		else if (f_statustime)
217 			sortfcn = revstatcmp;
218 		else /* Use modification time. */
219 			sortfcn = revmodcmp;
220 	} else {
221 		if (!f_timesort)
222 			sortfcn = namecmp;
223 		else if (f_accesstime)
224 			sortfcn = acccmp;
225 		else if (f_statustime)
226 			sortfcn = statcmp;
227 		else /* Use modification time. */
228 			sortfcn = modcmp;
229 	}
230 
231 	/* Select a print function. */
232 	if (f_singlecol)
233 		printfcn = printscol;
234 	else if (f_longform)
235 		printfcn = printlong;
236 	else
237 		printfcn = printcol;
238 
239 	if (argc)
240 		traverse(argc, argv, fts_options);
241 	else
242 		traverse(1, dotav, fts_options);
243 	exit(0);
244 }
245 
246 static int output;			/* If anything output. */
247 
248 /*
249  * Traverse() walks the logical directory structure specified by the argv list
250  * in the order specified by the mastercmp() comparison function.  During the
251  * traversal it passes linked lists of structures to display() which represent
252  * a superset (may be exact set) of the files to be displayed.
253  */
254 static void
traverse(argc,argv,options)255 traverse(argc, argv, options)
256 	int argc, options;
257 	char *argv[];
258 {
259 	FTS *ftsp;
260 	FTSENT *p, *chp;
261 	int ch_options;
262 
263 	if ((ftsp =
264 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
265 		err(1, NULL);
266 
267 	display(NULL, fts_children(ftsp, 0));
268 	if (f_listdir)
269 		return;
270 
271 	/*
272 	 * If not recursing down this tree and don't need stat info, just get
273 	 * the names.
274 	 */
275 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
276 
277 	while ((p = fts_read(ftsp)) != NULL)
278 		switch (p->fts_info) {
279 		case FTS_DC:
280 			warnx("%s: directory causes a cycle", p->fts_name);
281 			break;
282 		case FTS_DNR:
283 		case FTS_ERR:
284 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
285 			break;
286 		case FTS_D:
287 			if (p->fts_level != FTS_ROOTLEVEL &&
288 			    p->fts_name[0] == '.' && !f_listdot)
289 				break;
290 
291 			/*
292 			 * If already output something, put out a newline as
293 			 * a separator.  If multiple arguments, precede each
294 			 * directory with its name.
295 			 */
296 			if (output)
297 				(void)printf("\n%s:\n", p->fts_path);
298 			else if (argc > 1) {
299 				(void)printf("%s:\n", p->fts_path);
300 				output = 1;
301 			}
302 
303 			chp = fts_children(ftsp, ch_options);
304 			display(p, chp);
305 
306 			if (!f_recursive && chp != NULL)
307 				(void)fts_set(ftsp, p, FTS_SKIP);
308 			break;
309 		}
310 	if (errno)
311 		err(1, "fts_read");
312 }
313 
314 /*
315  * Display() takes a linked list of FTSENT structures and passes the list
316  * along with any other necessary information to the print function.  P
317  * points to the parent directory of the display list.
318  */
319 static void
display(p,list)320 display(p, list)
321 	FTSENT *p, *list;
322 {
323 	struct stat *sp;
324 	DISPLAY d;
325 	FTSENT *cur;
326 	NAMES *np;
327 	u_quad_t maxsize;
328 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
329 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
330 	int entries, needstats;
331 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
332 
333 	/*
334 	 * If list is NULL there are two possibilities: that the parent
335 	 * directory p has no children, or that fts_children() returned an
336 	 * error.  We ignore the error case since it will be replicated
337 	 * on the next call to fts_read() on the post-order visit to the
338 	 * directory p, and will be signalled in traverse().
339 	 */
340 	if (list == NULL)
341 		return;
342 
343 	needstats = f_inode || f_longform || f_size;
344 	flen = 0;
345 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
346 	bcfile = 0;
347 	maxuser = maxgroup = maxflags = 0;
348 	maxsize = 0;
349 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
350 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
351 			warnx("%s: %s",
352 			    cur->fts_name, strerror(cur->fts_errno));
353 			cur->fts_number = NO_PRINT;
354 			continue;
355 		}
356 
357 		/*
358 		 * P is NULL if list is the argv list, to which different rules
359 		 * apply.
360 		 */
361 		if (p == NULL) {
362 			/* Directories will be displayed later. */
363 			if (cur->fts_info == FTS_D && !f_listdir) {
364 				cur->fts_number = NO_PRINT;
365 				continue;
366 			}
367 		} else {
368 			/* Only display dot file if -a/-A set. */
369 			if (cur->fts_name[0] == '.' && !f_listdot) {
370 				cur->fts_number = NO_PRINT;
371 				continue;
372 			}
373 		}
374 		if (f_nonprint)
375 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
376 		if (cur->fts_namelen > maxlen)
377 			maxlen = cur->fts_namelen;
378 		if (needstats) {
379 			sp = cur->fts_statp;
380 			if (sp->st_blocks > maxblock)
381 				maxblock = sp->st_blocks;
382 			if (sp->st_ino > maxinode)
383 				maxinode = sp->st_ino;
384 			if (sp->st_nlink > maxnlink)
385 				maxnlink = sp->st_nlink;
386 			if (sp->st_size > maxsize)
387 				maxsize = sp->st_size;
388 
389 			btotal += sp->st_blocks;
390 			if (f_longform) {
391 				user = user_from_uid(sp->st_uid, 0);
392 				if ((ulen = strlen(user)) > maxuser)
393 					maxuser = ulen;
394 				group = group_from_gid(sp->st_gid, 0);
395 				if ((glen = strlen(group)) > maxgroup)
396 					maxgroup = glen;
397 				if (f_flags) {
398 					flags =
399 					    flags_to_string(sp->st_flags, "-");
400 					if ((flen = strlen(flags)) > maxflags)
401 						maxflags = flen;
402 				} else
403 					flen = 0;
404 
405 				if ((np = malloc(sizeof(NAMES) +
406 				    ulen + glen + flen + 3)) == NULL)
407 					err(1, NULL);
408 
409 				np->user = &np->data[0];
410 				(void)strcpy(np->user, user);
411 				np->group = &np->data[ulen + 1];
412 				(void)strcpy(np->group, group);
413 
414 				if (S_ISCHR(sp->st_mode) ||
415 				    S_ISBLK(sp->st_mode))
416 					bcfile = 1;
417 
418 				if (f_flags) {
419 					np->flags = &np->data[ulen + glen + 2];
420 				  	(void)strcpy(np->flags, flags);
421 				}
422 				cur->fts_pointer = np;
423 			}
424 		}
425 		++entries;
426 	}
427 
428 	if (!entries)
429 		return;
430 
431 	d.list = list;
432 	d.entries = entries;
433 	d.maxlen = maxlen;
434 	if (needstats) {
435 		d.bcfile = bcfile;
436 		d.btotal = btotal;
437 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
438 		d.s_block = strlen(buf);
439 		d.s_flags = maxflags;
440 		d.s_group = maxgroup;
441 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
442 		d.s_inode = strlen(buf);
443 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
444 		d.s_nlink = strlen(buf);
445 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
446 		d.s_size = strlen(buf);
447 		d.s_user = maxuser;
448 	}
449 
450 	printfcn(&d);
451 	output = 1;
452 
453 	if (f_longform)
454 		for (cur = list; cur; cur = cur->fts_link)
455 			free(cur->fts_pointer);
456 }
457 
458 /*
459  * Ordering for mastercmp:
460  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
461  * as larger than directories.  Within either group, use the sort function.
462  * All other levels use the sort function.  Error entries remain unsorted.
463  */
464 static int
mastercmp(a,b)465 mastercmp(a, b)
466 	const FTSENT **a, **b;
467 {
468 	int a_info, b_info;
469 
470 	a_info = (*a)->fts_info;
471 	if (a_info == FTS_ERR)
472 		return (0);
473 	b_info = (*b)->fts_info;
474 	if (b_info == FTS_ERR)
475 		return (0);
476 
477 	if (a_info == FTS_NS || b_info == FTS_NS)
478 		return (namecmp(*a, *b));
479 
480 	if (a_info == b_info)
481 		return (sortfcn(*a, *b));
482 
483 	if ((*a)->fts_level == FTS_ROOTLEVEL)
484 		if (a_info == FTS_D)
485 			return (1);
486 		else if (b_info == FTS_D)
487 			return (-1);
488 		else
489 			return (sortfcn(*a, *b));
490 	else
491 		return (sortfcn(*a, *b));
492 }
493