xref: /original-bsd/bin/ls/ls.c (revision 87f36e71)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * 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 The Regents of the University of California.\n\
14  All rights reserved.\n";
15 #endif /* not lint */
16 
17 #ifndef lint
18 static char sccsid[] = "@(#)ls.c	5.75 (Berkeley) 04/29/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 char	*getbsize __P((int *, long *));
38 
39 static void	 display __P((FTSENT *, FTSENT *));
40 static int	 mastercmp __P((const FTSENT **, const FTSENT **));
41 static void	 traverse __P((int, char **, int));
42 
43 static void (*printfcn) __P((DISPLAY *));
44 static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
45 
46 long blocksize;			/* block size units */
47 int termwidth = 80;		/* default terminal width */
48 
49 /* flags */
50 int f_accesstime;		/* use time of last access */
51 int f_column;			/* columnated format */
52 int f_flags;			/* show flags associated with a file */
53 int f_inode;			/* print inode */
54 int f_listdir;			/* list actual directory, not contents */
55 int f_listdot;			/* list files beginning with . */
56 int f_longform;			/* long listing format */
57 int f_newline;			/* if precede with newline */
58 int f_nonprint;			/* show unprintables as ? */
59 int f_nosort;			/* don't sort output */
60 int f_recursive;		/* ls subdirectories also */
61 int f_reversesort;		/* reverse whatever sort is used */
62 int f_sectime;			/* print the real time for all files */
63 int f_singlecol;		/* use single column output */
64 int f_size;			/* list size in short listing */
65 int f_statustime;		/* use time of last mode change */
66 int f_dirname;			/* if precede with directory name */
67 int f_timesort;			/* sort by time vice name */
68 int f_type;			/* add type character for non-regular files */
69 
70 int
71 main(argc, argv)
72 	int argc;
73 	char *argv[];
74 {
75 	static char dot[] = ".", *dotav[] = { dot, NULL };
76 	struct winsize win;
77 	int ch, fts_options, notused;
78 	char *p;
79 
80 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
81 	if (isatty(STDOUT_FILENO)) {
82 		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
83 		    !win.ws_col) {
84 			if (p = getenv("COLUMNS"))
85 				termwidth = atoi(p);
86 		}
87 		else
88 			termwidth = win.ws_col;
89 		f_column = f_nonprint = 1;
90 	} else
91 		f_singlecol = 1;
92 
93 	/* Root is -A automatically. */
94 	if (!getuid())
95 		f_listdot = 1;
96 
97 	fts_options = FTS_PHYSICAL;
98 	while ((ch = getopt(argc, argv, "1ACFLRTacdfgiloqrstu")) != EOF) {
99 		switch (ch) {
100 		/*
101 		 * The -1, -C and -l options all override each other so shell
102 		 * aliasing works right.
103 		 */
104 		case '1':
105 			f_singlecol = 1;
106 			f_column = f_longform = 0;
107 			break;
108 		case 'C':
109 			f_column = 1;
110 			f_longform = f_singlecol = 0;
111 			break;
112 		case 'l':
113 			f_longform = 1;
114 			f_column = f_singlecol = 0;
115 			break;
116 		/* The -c and -u options override each other. */
117 		case 'c':
118 			f_statustime = 1;
119 			f_accesstime = 0;
120 			break;
121 		case 'u':
122 			f_accesstime = 1;
123 			f_statustime = 0;
124 			break;
125 		case 'F':
126 			f_type = 1;
127 			break;
128 		case 'L':
129 			fts_options &= ~FTS_PHYSICAL;
130 			fts_options |= FTS_LOGICAL;
131 			break;
132 		case 'R':
133 			f_recursive = 1;
134 			break;
135 		case 'a':
136 			fts_options |= FTS_SEEDOT;
137 			/* FALLTHROUGH */
138 		case 'A':
139 			f_listdot = 1;
140 			break;
141 		/* The -d option turns off the -R option. */
142 		case 'd':
143 			f_listdir = 1;
144 			f_recursive = 0;
145 			break;
146 		case 'f':
147 			f_nosort = 1;
148 			break;
149 		case 'g':		/* Compatibility with 4.3BSD. */
150 			break;
151 		case 'i':
152 			f_inode = 1;
153 			break;
154 		case 'o':
155 			f_flags = 1;
156 			break;
157 		case 'q':
158 			f_nonprint = 1;
159 			break;
160 		case 'r':
161 			f_reversesort = 1;
162 			break;
163 		case 's':
164 			f_size = 1;
165 			break;
166 		case 'T':
167 			f_sectime = 1;
168 			break;
169 		case 't':
170 			f_timesort = 1;
171 			break;
172 		default:
173 		case '?':
174 			usage();
175 		}
176 	}
177 	argc -= optind;
178 	argv += optind;
179 
180 	/*
181 	 * If not -F, -i, -l, -s or -t options, don't require stat
182 	 * information.
183 	 */
184 	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
185 		fts_options |= FTS_NOSTAT;
186 
187 	/*
188 	 * If not -F, -d or -l options, follow any symbolic links listed on
189 	 * the command line.
190 	 */
191 	if (!f_longform && !f_listdir && !f_type)
192 		fts_options |= FTS_COMFOLLOW;
193 
194 	/* If -l or -s, figure out block size. */
195 	if (f_longform || f_size) {
196 		(void)getbsize(&notused, &blocksize);
197 		blocksize /= 512;
198 	}
199 
200 	/* Select a sort function. */
201 	if (f_reversesort) {
202 		if (!f_timesort)
203 			sortfcn = revnamecmp;
204 		else if (f_accesstime)
205 			sortfcn = revacccmp;
206 		else if (f_statustime)
207 			sortfcn = revstatcmp;
208 		else /* Use modification time. */
209 			sortfcn = revmodcmp;
210 	} else {
211 		if (!f_timesort)
212 			sortfcn = namecmp;
213 		else if (f_accesstime)
214 			sortfcn = acccmp;
215 		else if (f_statustime)
216 			sortfcn = statcmp;
217 		else /* Use modification time. */
218 			sortfcn = modcmp;
219 	}
220 
221 	/* Select a print function. */
222 	if (f_singlecol)
223 		printfcn = printscol;
224 	else if (f_longform)
225 		printfcn = printlong;
226 	else
227 		printfcn = printcol;
228 
229 	if (argc)
230 		traverse(argc, argv, fts_options);
231 	else
232 		traverse(1, dotav, fts_options);
233 	exit(0);
234 }
235 
236 static int output;			/* If anything output. */
237 
238 /*
239  * Traverse() walks the logical directory structure specified by the argv list
240  * in the order specified by the mastercmp() comparison function.  During the
241  * traversal it passes linked lists of structures to display() which represent
242  * a superset (may be exact set) of the files to be displayed.
243  */
244 static void
245 traverse(argc, argv, options)
246 	int argc, options;
247 	char *argv[];
248 {
249 	register FTS *ftsp;
250 	register FTSENT *p, *chp;
251 	int ch_options;
252 
253 	if ((ftsp =
254 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
255 		err(1, NULL);
256 
257 	display(NULL, fts_children(ftsp, 0));
258 	if (f_listdir)
259 		return;
260 
261 	/*
262 	 * If not recursing down this tree and don't need stat info, just get
263 	 * the names.
264 	 */
265 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
266 
267 	while (p = fts_read(ftsp))
268 		switch(p->fts_info) {
269 		case FTS_DC:
270 			warnx("%s: directory causes a cycle", p->fts_name);
271 			break;
272 		case FTS_DNR:
273 		case FTS_ERR:
274 			warn("%s", p->fts_name);
275 			break;
276 		case FTS_D:
277 			if (p->fts_level != FTS_ROOTLEVEL &&
278 			    p->fts_name[0] == '.' && !f_listdot)
279 				break;
280 
281 			/*
282 			 * If already output something, put out a newline as
283 			 * a separator.  If multiple arguments, precede each
284 			 * directory with its name.
285 			 */
286 			if (output)
287 				(void)printf("\n%s:\n", p->fts_path);
288 			else if (argc > 1) {
289 				(void)printf("%s:\n", p->fts_path);
290 				output = 1;
291 			}
292 
293 			chp = fts_children(ftsp, ch_options);
294 			display(p, chp);
295 
296 			if (!f_recursive && chp != NULL)
297 				(void)fts_set(ftsp, p, FTS_SKIP);
298 			break;
299 		}
300 	(void)fts_close(ftsp);
301 }
302 
303 /*
304  * Display() takes a linked list of FTSENT structures and passes the list
305  * along with any other necessary information to the print function.  P
306  * points to the parent directory of the display list.
307  */
308 static void
309 display(p, list)
310 	register FTSENT *p;
311 	FTSENT *list;
312 {
313 	register FTSENT *cur;
314 	struct stat *sp;
315 	DISPLAY d;
316 	NAMES *np;
317 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
318 	u_quad_t maxsize;
319 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
320 	int entries, needstats;
321 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
322 
323 	/*
324 	 * If list is NULL there are two possibilities: that the parent
325 	 * directory p has no children, or that fts_children() returned an
326 	 * error.  We ignore the error case since it will be replicated
327 	 * on the next call to fts_read() on the post-order visit to the
328 	 * directory p, and will be signalled in traverse().
329 	 */
330 	if (list == NULL)
331 		return;
332 
333 	needstats = f_inode || f_longform || f_size;
334 	flen = 0;
335 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
336 	bcfile = 0;
337 	maxuser = maxgroup = maxflags = 0;
338 	maxsize = 0;
339 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
340 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
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