xref: /original-bsd/bin/ls/ls.c (revision 94e7bb75)
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 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.66 (Berkeley) 06/02/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 passes the list along
308  * with any other necessary information to the print function (printfcn()).
309  * P 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 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 	maxuser = maxgroup = maxflags = 0;
340 	maxsize = 0;
341 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
342 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
343 			err(0, "%s: %s",
344 			    cur->fts_name, strerror(cur->fts_errno));
345 			cur->fts_number = NO_PRINT;
346 			continue;
347 		}
348 
349 		/*
350 		 * P is NULL if list is the argv list, to which different rules
351 		 * apply.
352 		 */
353 		if (p == NULL) {
354 			/* Directories will be displayed later. */
355 			if (cur->fts_info == FTS_D && !f_listdir) {
356 				cur->fts_number = NO_PRINT;
357 				continue;
358 			}
359 		} else {
360 			/* Only display dot file if -a/-A set. */
361 			if (cur->fts_name[0] == '.' && !f_listdot) {
362 				cur->fts_number = NO_PRINT;
363 				continue;
364 			}
365 		}
366 		if (f_nonprint)
367 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
368 		if (cur->fts_namelen > maxlen)
369 			maxlen = cur->fts_namelen;
370 		if (needstats) {
371 			sp = cur->fts_statp;
372 			if (sp->st_blocks > maxblock)
373 				maxblock = sp->st_blocks;
374 			if (sp->st_ino > maxinode)
375 				maxinode = sp->st_ino;
376 			if (sp->st_nlink > maxnlink)
377 				maxnlink = sp->st_nlink;
378 			if (sp->st_size > maxsize)
379 				maxsize = sp->st_size;
380 
381 			btotal += sp->st_blocks;
382 			if (f_longform) {
383 				user = user_from_uid(sp->st_uid, 0);
384 				if ((ulen = strlen(user)) > maxuser)
385 					maxuser = ulen;
386 				group = group_from_gid(sp->st_gid, 0);
387 				if ((glen = strlen(group)) > maxgroup)
388 					maxgroup = glen;
389 				if (f_flags) {
390 					flags = flags_from_fid(sp->st_flags);
391 					if ((flen = strlen(flags)) > maxflags)
392 						maxflags = flen;
393 				} else
394 					flen = 0;
395 
396 				if ((np = malloc(sizeof(NAMES) +
397 				    ulen + glen + flen + 3)) == NULL)
398 					err(1, "%s", strerror(errno));
399 
400 				np->user = &np->data[0];
401 				(void)strcpy(np->user, user);
402 				np->group = &np->data[ulen + 1];
403 				(void)strcpy(np->group, group);
404 
405 				if (f_flags) {
406 					np->flags = &np->data[ulen + glen + 2];
407 				  	(void)strcpy(np->flags, flags);
408 				}
409 				cur->fts_pointer = np;
410 			}
411 		}
412 		++entries;
413 	}
414 
415 	if (!entries)
416 		return;
417 
418 	d.list = list;
419 	d.entries = entries;
420 	d.maxlen = maxlen;
421 	if (needstats) {
422 		d.btotal = btotal;
423 		d.s_block = snprintf(buf, sizeof(buf), "%lu", maxblock);
424 		d.s_flags = maxflags;
425 		d.s_group = maxgroup;
426 		d.s_inode = snprintf(buf, sizeof(buf), "%lu", maxinode);
427 		d.s_nlink = snprintf(buf, sizeof(buf), "%lu", maxnlink);
428 		d.s_size = snprintf(buf, sizeof(buf), "%qu", maxsize);
429 		d.s_user = maxuser;
430 	}
431 
432 	printfcn(&d);
433 	output = 1;
434 
435 	if (f_longform)
436 		for (cur = list; cur; cur = cur->fts_link)
437 			free(cur->fts_pointer);
438 }
439 
440 /*
441  * Ordering for mastercmp:
442  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
443  * as larger than directories.  Within either group, use the sort function.
444  * All other levels use the sort function.  Error entries remain unsorted.
445  */
446 static int
447 mastercmp(a, b)
448 	const FTSENT **a, **b;
449 {
450 	register int a_info, b_info;
451 
452 	a_info = (*a)->fts_info;
453 	if (a_info == FTS_ERR)
454 		return (0);
455 	b_info = (*b)->fts_info;
456 	if (b_info == FTS_ERR)
457 		return (0);
458 
459 	if (a_info == FTS_NS || b_info == FTS_NS)
460 		return (namecmp(*a, *b));
461 
462 	if (a_info == b_info)
463 		return (sortfcn(*a, *b));
464 
465 	if ((*a)->fts_level == FTS_ROOTLEVEL)
466 		if (a_info == FTS_D)
467 			return (1);
468 		else if (b_info == FTS_D)
469 			return (-1);
470 		else
471 			return (sortfcn(*a, *b));
472 	else
473 		return (sortfcn(*a, *b));
474 }
475 
476 static char *
477 flags_from_fid(flags)
478 	u_long flags;
479 {
480 	static char buf[20];
481 	register int comma;
482 	register char *p;
483 
484 	p = buf;
485 	if (flags & ARCHIVED) {
486 		(void)strcpy(p, "arch");
487 		p += sizeof("arch") - 1;
488 		comma = 1;
489 	} else
490 		comma = 0;
491 	if (flags & NODUMP) {
492 		if (comma++)
493 			*p++ = ',';
494 		(void)strcpy(p, "nodump");
495 		p += sizeof("nodump") - 1;
496 	}
497 	if (flags & IMMUTABLE) {
498 		if (comma++)
499 			*p++ = ',';
500 		(void)strcpy(p, "nochg");
501 		p += sizeof("nochg") - 1;
502 	}
503 	if (!comma)
504 		(void)strcpy(p, "-");
505 	return (buf);
506 }
507