xref: /original-bsd/bin/ls/ls.c (revision 6953413c)
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.4 (Berkeley) 04/01/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 
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")) != NULL)
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 	FTS *ftsp;
248 	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)) != NULL)
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 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
273 			break;
274 		case FTS_D:
275 			if (p->fts_level != FTS_ROOTLEVEL &&
276 			    p->fts_name[0] == '.' && !f_listdot)
277 				break;
278 
279 			/*
280 			 * If already output something, put out a newline as
281 			 * a separator.  If multiple arguments, precede each
282 			 * directory with its name.
283 			 */
284 			if (output)
285 				(void)printf("\n%s:\n", p->fts_path);
286 			else if (argc > 1) {
287 				(void)printf("%s:\n", p->fts_path);
288 				output = 1;
289 			}
290 
291 			chp = fts_children(ftsp, ch_options);
292 			display(p, chp);
293 
294 			if (!f_recursive && chp != NULL)
295 				(void)fts_set(ftsp, p, FTS_SKIP);
296 			break;
297 		}
298 	if (errno)
299 		err(1, "fts_read");
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 	FTSENT *p, *list;
310 {
311 	struct stat *sp;
312 	DISPLAY d;
313 	FTSENT *cur;
314 	NAMES *np;
315 	u_quad_t maxsize;
316 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
317 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
318 	int entries, needstats;
319 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
320 
321 	/*
322 	 * If list is NULL there are two possibilities: that the parent
323 	 * directory p has no children, or that fts_children() returned an
324 	 * error.  We ignore the error case since it will be replicated
325 	 * on the next call to fts_read() on the post-order visit to the
326 	 * directory p, and will be signalled in traverse().
327 	 */
328 	if (list == NULL)
329 		return;
330 
331 	needstats = f_inode || f_longform || f_size;
332 	flen = 0;
333 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
334 	bcfile = 0;
335 	maxuser = maxgroup = maxflags = 0;
336 	maxsize = 0;
337 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
338 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
339 			warnx("%s: %s",
340 			    cur->fts_name, strerror(cur->fts_errno));
341 			cur->fts_number = NO_PRINT;
342 			continue;
343 		}
344 
345 		/*
346 		 * P is NULL if list is the argv list, to which different rules
347 		 * apply.
348 		 */
349 		if (p == NULL) {
350 			/* Directories will be displayed later. */
351 			if (cur->fts_info == FTS_D && !f_listdir) {
352 				cur->fts_number = NO_PRINT;
353 				continue;
354 			}
355 		} else {
356 			/* Only display dot file if -a/-A set. */
357 			if (cur->fts_name[0] == '.' && !f_listdot) {
358 				cur->fts_number = NO_PRINT;
359 				continue;
360 			}
361 		}
362 		if (f_nonprint)
363 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
364 		if (cur->fts_namelen > maxlen)
365 			maxlen = cur->fts_namelen;
366 		if (needstats) {
367 			sp = cur->fts_statp;
368 			if (sp->st_blocks > maxblock)
369 				maxblock = sp->st_blocks;
370 			if (sp->st_ino > maxinode)
371 				maxinode = sp->st_ino;
372 			if (sp->st_nlink > maxnlink)
373 				maxnlink = sp->st_nlink;
374 			if (sp->st_size > maxsize)
375 				maxsize = sp->st_size;
376 
377 			btotal += sp->st_blocks;
378 			if (f_longform) {
379 				user = user_from_uid(sp->st_uid, 0);
380 				if ((ulen = strlen(user)) > maxuser)
381 					maxuser = ulen;
382 				group = group_from_gid(sp->st_gid, 0);
383 				if ((glen = strlen(group)) > maxgroup)
384 					maxgroup = glen;
385 				if (f_flags) {
386 					flags =
387 					    flags_to_string(sp->st_flags, "-");
388 					if ((flen = strlen(flags)) > maxflags)
389 						maxflags = flen;
390 				} else
391 					flen = 0;
392 
393 				if ((np = malloc(sizeof(NAMES) +
394 				    ulen + glen + flen + 3)) == NULL)
395 					err(1, NULL);
396 
397 				np->user = &np->data[0];
398 				(void)strcpy(np->user, user);
399 				np->group = &np->data[ulen + 1];
400 				(void)strcpy(np->group, group);
401 
402 				if (S_ISCHR(sp->st_mode) ||
403 				    S_ISBLK(sp->st_mode))
404 					bcfile = 1;
405 
406 				if (f_flags) {
407 					np->flags = &np->data[ulen + glen + 2];
408 				  	(void)strcpy(np->flags, flags);
409 				}
410 				cur->fts_pointer = np;
411 			}
412 		}
413 		++entries;
414 	}
415 
416 	if (!entries)
417 		return;
418 
419 	d.list = list;
420 	d.entries = entries;
421 	d.maxlen = maxlen;
422 	if (needstats) {
423 		d.bcfile = bcfile;
424 		d.btotal = btotal;
425 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
426 		d.s_block = strlen(buf);
427 		d.s_flags = maxflags;
428 		d.s_group = maxgroup;
429 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
430 		d.s_inode = strlen(buf);
431 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
432 		d.s_nlink = strlen(buf);
433 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
434 		d.s_size = strlen(buf);
435 		d.s_user = maxuser;
436 	}
437 
438 	printfcn(&d);
439 	output = 1;
440 
441 	if (f_longform)
442 		for (cur = list; cur; cur = cur->fts_link)
443 			free(cur->fts_pointer);
444 }
445 
446 /*
447  * Ordering for mastercmp:
448  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
449  * as larger than directories.  Within either group, use the sort function.
450  * All other levels use the sort function.  Error entries remain unsorted.
451  */
452 static int
453 mastercmp(a, b)
454 	const FTSENT **a, **b;
455 {
456 	int a_info, b_info;
457 
458 	a_info = (*a)->fts_info;
459 	if (a_info == FTS_ERR)
460 		return (0);
461 	b_info = (*b)->fts_info;
462 	if (b_info == FTS_ERR)
463 		return (0);
464 
465 	if (a_info == FTS_NS || b_info == FTS_NS)
466 		return (namecmp(*a, *b));
467 
468 	if (a_info == b_info)
469 		return (sortfcn(*a, *b));
470 
471 	if ((*a)->fts_level == FTS_ROOTLEVEL)
472 		if (a_info == FTS_D)
473 			return (1);
474 		else if (b_info == FTS_D)
475 			return (-1);
476 		else
477 			return (sortfcn(*a, *b));
478 	else
479 		return (sortfcn(*a, *b));
480 }
481