xref: /original-bsd/bin/ls/ls.c (revision 5b6bcd2a)
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.68 (Berkeley) 09/16/92";
19 #endif /* not lint */
20 
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/ioctl.h>
24 #include <dirent.h>
25 #include <unistd.h>
26 #include <fts.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <stdio.h>
31 #include "ls.h"
32 #include "extern.h"
33 
34 char	*getbsize __P((char *, int *, long *));
35 char	*group_from_gid __P((u_int, int));
36 char	*user_from_uid __P((u_int, int));
37 
38 static void	 display __P((FTSENT *, FTSENT *));
39 static char	*flags_from_fid __P((u_long));
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, "1ACFLRTacdfgikloqrstu")) != 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 'k':		/* Delete before 4.4BSD. */
155 			(void)fprintf(stderr, "ls: -k no longer supported\n");
156 			break;
157 		case 'o':
158 			f_flags = 1;
159 			break;
160 		case 'q':
161 			f_nonprint = 1;
162 			break;
163 		case 'r':
164 			f_reversesort = 1;
165 			break;
166 		case 's':
167 			f_size = 1;
168 			break;
169 		case 'T':
170 			f_sectime = 1;
171 			break;
172 		case 't':
173 			f_timesort = 1;
174 			break;
175 		default:
176 		case '?':
177 			usage();
178 		}
179 	}
180 	argc -= optind;
181 	argv += optind;
182 
183 	/*
184 	 * If not -F, -i, -l, -s or -t options, don't require stat
185 	 * information.
186 	 */
187 	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
188 		fts_options |= FTS_NOSTAT;
189 
190 	/*
191 	 * If not -F, -d or -l options, follow any symbolic links listed on
192 	 * the command line.
193 	 */
194 	if (!f_longform && !f_listdir && !f_type)
195 		fts_options |= FTS_COMFOLLOW;
196 
197 	/* If -l or -s, figure out block size. */
198 	if (f_longform || f_size) {
199 		(void)getbsize("ls", &notused, &blocksize);
200 		blocksize /= 512;
201 	}
202 
203 	/* Select a sort function. */
204 	if (f_reversesort) {
205 		if (!f_timesort)
206 			sortfcn = revnamecmp;
207 		else if (f_accesstime)
208 			sortfcn = revacccmp;
209 		else if (f_statustime)
210 			sortfcn = revstatcmp;
211 		else /* Use modification time. */
212 			sortfcn = revmodcmp;
213 	} else {
214 		if (!f_timesort)
215 			sortfcn = namecmp;
216 		else if (f_accesstime)
217 			sortfcn = acccmp;
218 		else if (f_statustime)
219 			sortfcn = statcmp;
220 		else /* Use modification time. */
221 			sortfcn = modcmp;
222 	}
223 
224 	/* Select a print function. */
225 	if (f_singlecol)
226 		printfcn = printscol;
227 	else if (f_longform)
228 		printfcn = printlong;
229 	else
230 		printfcn = printcol;
231 
232 	if (argc)
233 		traverse(argc, argv, fts_options);
234 	else
235 		traverse(1, dotav, fts_options);
236 	exit(0);
237 }
238 
239 static int output;			/* If anything output. */
240 
241 /*
242  * Traverse() walks the logical directory structure specified by the argv list
243  * in the order specified by the mastercmp() comparison function.  During the
244  * traversal it passes linked lists of structures to display() which represent
245  * a superset (may be exact set) of the files to be displayed.
246  */
247 static void
248 traverse(argc, argv, options)
249 	int argc, options;
250 	char *argv[];
251 {
252 	register FTS *ftsp;
253 	register FTSENT *p;
254 	int ch_options;
255 
256 	if ((ftsp =
257 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
258 		err(1, "%s", strerror(errno));
259 
260 	display(NULL, fts_children(ftsp, 0));
261 	if (f_listdir)
262 		return;
263 
264 	/*
265 	 * If not recursing down this tree and don't need stat info, just get
266 	 * the names.
267 	 */
268 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
269 
270 	while (p = fts_read(ftsp))
271 		switch(p->fts_info) {
272 		case FTS_DC:
273 			err(0, "%s: directory causes a cycle", p->fts_name);
274 			break;
275 		case FTS_DNR:
276 		case FTS_ERR:
277 			err(0, "%s: %s",
278 			    p->fts_name, strerror(p->fts_errno));
279 			break;
280 		case FTS_D:
281 			if (p->fts_level != FTS_ROOTLEVEL &&
282 			    p->fts_name[0] == '.' && !f_listdot)
283 				break;
284 
285 			/*
286 			 * If already output something, put out a newline as
287 			 * a separator.  If multiple arguments, precede each
288 			 * directory with its name.
289 			 */
290 			if (output)
291 				(void)printf("\n%s:\n", p->fts_path);
292 			else if (argc > 1) {
293 				(void)printf("%s:\n", p->fts_path);
294 				output = 1;
295 			}
296 
297 			display(p, fts_children(ftsp, ch_options));
298 
299 			if (!f_recursive)
300 				(void)fts_set(ftsp, p, FTS_SKIP);
301 			break;
302 		}
303 	(void)fts_close(ftsp);
304 }
305 
306 /*
307  * Display() takes a linked list of FTSENT structures and passes the list
308  * along with any other necessary information to the print function.  P
309  * points to the parent directory of the display list.
310  */
311 static void
312 display(p, list)
313 	register FTSENT *p;
314 	FTSENT *list;
315 {
316 	register FTSENT *cur;
317 	struct stat *sp;
318 	DISPLAY d;
319 	NAMES *np;
320 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
321 	u_quad_t maxsize;
322 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
323 	int entries, needstats;
324 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
325 
326 	/*
327 	 * If list is NULL there are two possibilities: that the parent
328 	 * directory p has no children, or that fts_children() returned an
329 	 * error.  We ignore the error case since it will be replicated
330 	 * on the next call to fts_read() on the post-order visit to the
331 	 * directory p, and will be signalled in traverse().
332 	 */
333 	if (list == NULL)
334 		return;
335 
336 	needstats = f_inode || f_longform || f_size;
337 	flen = 0;
338 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
339 	bcfile = 0;
340 	maxuser = maxgroup = maxflags = 0;
341 	maxsize = 0;
342 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
343 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
344 			err(0, "%s: %s",
345 			    cur->fts_name, strerror(cur->fts_errno));
346 			cur->fts_number = NO_PRINT;
347 			continue;
348 		}
349 
350 		/*
351 		 * P is NULL if list is the argv list, to which different rules
352 		 * apply.
353 		 */
354 		if (p == NULL) {
355 			/* Directories will be displayed later. */
356 			if (cur->fts_info == FTS_D && !f_listdir) {
357 				cur->fts_number = NO_PRINT;
358 				continue;
359 			}
360 		} else {
361 			/* Only display dot file if -a/-A set. */
362 			if (cur->fts_name[0] == '.' && !f_listdot) {
363 				cur->fts_number = NO_PRINT;
364 				continue;
365 			}
366 		}
367 		if (f_nonprint)
368 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
369 		if (cur->fts_namelen > maxlen)
370 			maxlen = cur->fts_namelen;
371 		if (needstats) {
372 			sp = cur->fts_statp;
373 			if (sp->st_blocks > maxblock)
374 				maxblock = sp->st_blocks;
375 			if (sp->st_ino > maxinode)
376 				maxinode = sp->st_ino;
377 			if (sp->st_nlink > maxnlink)
378 				maxnlink = sp->st_nlink;
379 			if (sp->st_size > maxsize)
380 				maxsize = sp->st_size;
381 
382 			btotal += sp->st_blocks;
383 			if (f_longform) {
384 				user = user_from_uid(sp->st_uid, 0);
385 				if ((ulen = strlen(user)) > maxuser)
386 					maxuser = ulen;
387 				group = group_from_gid(sp->st_gid, 0);
388 				if ((glen = strlen(group)) > maxgroup)
389 					maxgroup = glen;
390 				if (f_flags) {
391 					flags = flags_from_fid(sp->st_flags);
392 					if ((flen = strlen(flags)) > maxflags)
393 						maxflags = flen;
394 				} else
395 					flen = 0;
396 
397 				if ((np = malloc(sizeof(NAMES) +
398 				    ulen + glen + flen + 3)) == NULL)
399 					err(1, "%s", strerror(errno));
400 
401 				np->user = &np->data[0];
402 				(void)strcpy(np->user, user);
403 				np->group = &np->data[ulen + 1];
404 				(void)strcpy(np->group, group);
405 
406 				if (S_ISCHR(sp->st_mode) ||
407 				    S_ISBLK(sp->st_mode))
408 					bcfile = 1;
409 
410 				if (f_flags) {
411 					np->flags = &np->data[ulen + glen + 2];
412 				  	(void)strcpy(np->flags, flags);
413 				}
414 				cur->fts_pointer = np;
415 			}
416 		}
417 		++entries;
418 	}
419 
420 	if (!entries)
421 		return;
422 
423 	d.list = list;
424 	d.entries = entries;
425 	d.maxlen = maxlen;
426 	if (needstats) {
427 		d.bcfile = bcfile;
428 		d.btotal = btotal;
429 		d.s_block = snprintf(buf, sizeof(buf), "%lu", maxblock);
430 		d.s_flags = maxflags;
431 		d.s_group = maxgroup;
432 		d.s_inode = snprintf(buf, sizeof(buf), "%lu", maxinode);
433 		d.s_nlink = snprintf(buf, sizeof(buf), "%lu", maxnlink);
434 		d.s_size = snprintf(buf, sizeof(buf), "%qu", maxsize);
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 	register 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 
482 static char *
483 flags_from_fid(flags)
484 	u_long flags;
485 {
486 	static char buf[20];
487 	register int comma;
488 	register char *p;
489 
490 	p = buf;
491 	if (flags & ARCHIVED) {
492 		(void)strcpy(p, "arch");
493 		p += sizeof("arch") - 1;
494 		comma = 1;
495 	} else
496 		comma = 0;
497 	if (flags & NODUMP) {
498 		if (comma++)
499 			*p++ = ',';
500 		(void)strcpy(p, "nodump");
501 		p += sizeof("nodump") - 1;
502 	}
503 	if (flags & IMMUTABLE) {
504 		if (comma++)
505 			*p++ = ',';
506 		(void)strcpy(p, "nochg");
507 		p += sizeof("nochg") - 1;
508 	}
509 	if (!comma)
510 		(void)strcpy(p, "-");
511 	return (buf);
512 }
513