xref: /original-bsd/bin/ls/ls.c (revision a043e977)
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.70 (Berkeley) 01/15/93";
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, *chp;
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 			chp = fts_children(ftsp, ch_options);
298 			display(p, chp);
299 
300 			if (!f_recursive && chp != NULL)
301 				(void)fts_set(ftsp, p, FTS_SKIP);
302 			break;
303 		}
304 	(void)fts_close(ftsp);
305 }
306 
307 /*
308  * Display() takes a linked list of FTSENT structures and passes the list
309  * along with any other necessary information to the print function.  P
310  * points to the parent directory of the display list.
311  */
312 static void
313 display(p, list)
314 	register FTSENT *p;
315 	FTSENT *list;
316 {
317 	register FTSENT *cur;
318 	struct stat *sp;
319 	DISPLAY d;
320 	NAMES *np;
321 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
322 	u_quad_t maxsize;
323 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
324 	int entries, needstats;
325 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
326 
327 	/*
328 	 * If list is NULL there are two possibilities: that the parent
329 	 * directory p has no children, or that fts_children() returned an
330 	 * error.  We ignore the error case since it will be replicated
331 	 * on the next call to fts_read() on the post-order visit to the
332 	 * directory p, and will be signalled in traverse().
333 	 */
334 	if (list == NULL)
335 		return;
336 
337 	needstats = f_inode || f_longform || f_size;
338 	flen = 0;
339 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
340 	bcfile = 0;
341 	maxuser = maxgroup = maxflags = 0;
342 	maxsize = 0;
343 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
344 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
345 			err(0, "%s: %s",
346 			    cur->fts_name, strerror(cur->fts_errno));
347 			cur->fts_number = NO_PRINT;
348 			continue;
349 		}
350 
351 		/*
352 		 * P is NULL if list is the argv list, to which different rules
353 		 * apply.
354 		 */
355 		if (p == NULL) {
356 			/* Directories will be displayed later. */
357 			if (cur->fts_info == FTS_D && !f_listdir) {
358 				cur->fts_number = NO_PRINT;
359 				continue;
360 			}
361 		} else {
362 			/* Only display dot file if -a/-A set. */
363 			if (cur->fts_name[0] == '.' && !f_listdot) {
364 				cur->fts_number = NO_PRINT;
365 				continue;
366 			}
367 		}
368 		if (f_nonprint)
369 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
370 		if (cur->fts_namelen > maxlen)
371 			maxlen = cur->fts_namelen;
372 		if (needstats) {
373 			sp = cur->fts_statp;
374 			if (sp->st_blocks > maxblock)
375 				maxblock = sp->st_blocks;
376 			if (sp->st_ino > maxinode)
377 				maxinode = sp->st_ino;
378 			if (sp->st_nlink > maxnlink)
379 				maxnlink = sp->st_nlink;
380 			if (sp->st_size > maxsize)
381 				maxsize = sp->st_size;
382 
383 			btotal += sp->st_blocks;
384 			if (f_longform) {
385 				user = user_from_uid(sp->st_uid, 0);
386 				if ((ulen = strlen(user)) > maxuser)
387 					maxuser = ulen;
388 				group = group_from_gid(sp->st_gid, 0);
389 				if ((glen = strlen(group)) > maxgroup)
390 					maxgroup = glen;
391 				if (f_flags) {
392 					flags = flags_from_fid(sp->st_flags);
393 					if ((flen = strlen(flags)) > maxflags)
394 						maxflags = flen;
395 				} else
396 					flen = 0;
397 
398 				if ((np = malloc(sizeof(NAMES) +
399 				    ulen + glen + flen + 3)) == NULL)
400 					err(1, "%s", strerror(errno));
401 
402 				np->user = &np->data[0];
403 				(void)strcpy(np->user, user);
404 				np->group = &np->data[ulen + 1];
405 				(void)strcpy(np->group, group);
406 
407 				if (S_ISCHR(sp->st_mode) ||
408 				    S_ISBLK(sp->st_mode))
409 					bcfile = 1;
410 
411 				if (f_flags) {
412 					np->flags = &np->data[ulen + glen + 2];
413 				  	(void)strcpy(np->flags, flags);
414 				}
415 				cur->fts_pointer = np;
416 			}
417 		}
418 		++entries;
419 	}
420 
421 	if (!entries)
422 		return;
423 
424 	d.list = list;
425 	d.entries = entries;
426 	d.maxlen = maxlen;
427 	if (needstats) {
428 		d.bcfile = bcfile;
429 		d.btotal = btotal;
430 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
431 		d.s_block = strlen(buf);
432 		d.s_flags = maxflags;
433 		d.s_group = maxgroup;
434 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
435 		d.s_inode = strlen(buf);
436 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
437 		d.s_nlink = strlen(buf);
438 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
439 		d.s_size = strlen(buf);
440 		d.s_user = maxuser;
441 	}
442 
443 	printfcn(&d);
444 	output = 1;
445 
446 	if (f_longform)
447 		for (cur = list; cur; cur = cur->fts_link)
448 			free(cur->fts_pointer);
449 }
450 
451 /*
452  * Ordering for mastercmp:
453  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
454  * as larger than directories.  Within either group, use the sort function.
455  * All other levels use the sort function.  Error entries remain unsorted.
456  */
457 static int
458 mastercmp(a, b)
459 	const FTSENT **a, **b;
460 {
461 	register int a_info, b_info;
462 
463 	a_info = (*a)->fts_info;
464 	if (a_info == FTS_ERR)
465 		return (0);
466 	b_info = (*b)->fts_info;
467 	if (b_info == FTS_ERR)
468 		return (0);
469 
470 	if (a_info == FTS_NS || b_info == FTS_NS)
471 		return (namecmp(*a, *b));
472 
473 	if (a_info == b_info)
474 		return (sortfcn(*a, *b));
475 
476 	if ((*a)->fts_level == FTS_ROOTLEVEL)
477 		if (a_info == FTS_D)
478 			return (1);
479 		else if (b_info == FTS_D)
480 			return (-1);
481 		else
482 			return (sortfcn(*a, *b));
483 	else
484 		return (sortfcn(*a, *b));
485 }
486 
487 static char *
488 flags_from_fid(flags)
489 	u_long flags;
490 {
491 	static char buf[20];
492 	register int comma;
493 	register char *p;
494 
495 	p = buf;
496 	if (flags & ARCHIVED) {
497 		(void)strcpy(p, "arch");
498 		p += sizeof("arch") - 1;
499 		comma = 1;
500 	} else
501 		comma = 0;
502 	if (flags & NODUMP) {
503 		if (comma++)
504 			*p++ = ',';
505 		(void)strcpy(p, "nodump");
506 		p += sizeof("nodump") - 1;
507 	}
508 	if (flags & IMMUTABLE) {
509 		if (comma++)
510 			*p++ = ',';
511 		(void)strcpy(p, "nochg");
512 		p += sizeof("nochg") - 1;
513 	}
514 	if (!comma)
515 		(void)strcpy(p, "-");
516 	return (buf);
517 }
518