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