xref: /netbsd-src/bin/ls/ls.c (revision ae9172d6cd9432a6a1a56760d86b32c57a66c39c)
1 /*
2  * Copyright (c) 1989, 1993, 1994
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  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 static char copyright[] =
39 "@(#) Copyright (c) 1989, 1993, 1994\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 /*static char sccsid[] = "from: @(#)ls.c	8.5 (Berkeley) 4/2/94";*/
45 static char *rcsid = "$Id: ls.c,v 1.12 1994/09/23 06:14:51 mycroft Exp $";
46 #endif /* not lint */
47 
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <sys/ioctl.h>
51 
52 #include <dirent.h>
53 #include <err.h>
54 #include <errno.h>
55 #include <fts.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 
61 #include "ls.h"
62 #include "extern.h"
63 
64 char	*group_from_gid __P((u_int, int));
65 char	*user_from_uid __P((u_int, int));
66 
67 static void	 display __P((FTSENT *, FTSENT *));
68 static int	 mastercmp __P((const FTSENT **, const FTSENT **));
69 static void	 traverse __P((int, char **, int));
70 
71 static void (*printfcn) __P((DISPLAY *));
72 static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
73 
74 #define	BY_NAME 0
75 #define	BY_SIZE 1
76 #define	BY_TIME	2
77 
78 long blocksize;			/* block size units */
79 int termwidth = 80;		/* default terminal width */
80 int sortkey = BY_NAME;
81 
82 /* flags */
83 int f_accesstime;		/* use time of last access */
84 int f_column;			/* columnated format */
85 int f_flags;			/* show flags associated with a file */
86 int f_inode;			/* print inode */
87 int f_listdir;			/* list actual directory, not contents */
88 int f_listdot;			/* list files beginning with . */
89 int f_longform;			/* long listing format */
90 int f_newline;			/* if precede with newline */
91 int f_nonprint;			/* show unprintables as ? */
92 int f_nosort;			/* don't sort output */
93 int f_recursive;		/* ls subdirectories also */
94 int f_reversesort;		/* reverse whatever sort is used */
95 int f_sectime;			/* print the real time for all files */
96 int f_singlecol;		/* use single column output */
97 int f_size;			/* list size in short listing */
98 int f_statustime;		/* use time of last mode change */
99 int f_dirname;			/* if precede with directory name */
100 int f_type;			/* add type character for non-regular files */
101 
102 int
103 main(argc, argv)
104 	int argc;
105 	char *argv[];
106 {
107 	static char dot[] = ".", *dotav[] = { dot, NULL };
108 	struct winsize win;
109 	int ch, fts_options, notused;
110 	int kflag = 0;
111 	char *p;
112 
113 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
114 	if (isatty(STDOUT_FILENO)) {
115 		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
116 		    !win.ws_col) {
117 			if ((p = getenv("COLUMNS")) != NULL)
118 				termwidth = atoi(p);
119 		}
120 		else
121 			termwidth = win.ws_col;
122 		f_column = f_nonprint = 1;
123 	} else
124 		f_singlecol = 1;
125 
126 	/* Root is -A automatically. */
127 	if (!getuid())
128 		f_listdot = 1;
129 
130 	fts_options = FTS_PHYSICAL;
131 	while ((ch = getopt(argc, argv, "1ACFLRSTacdfgikloqrstu")) != -1) {
132 		switch (ch) {
133 		/*
134 		 * The -1, -C and -l options all override each other so shell
135 		 * aliasing works right.
136 		 */
137 		case '1':
138 			f_singlecol = 1;
139 			f_column = f_longform = 0;
140 			break;
141 		case 'C':
142 			f_column = 1;
143 			f_longform = f_singlecol = 0;
144 			break;
145 		case 'l':
146 			f_longform = 1;
147 			f_column = f_singlecol = 0;
148 			break;
149 		/* The -c and -u options override each other. */
150 		case 'c':
151 			f_statustime = 1;
152 			f_accesstime = 0;
153 			break;
154 		case 'u':
155 			f_accesstime = 1;
156 			f_statustime = 0;
157 			break;
158 		case 'F':
159 			f_type = 1;
160 			break;
161 		case 'L':
162 			fts_options &= ~FTS_PHYSICAL;
163 			fts_options |= FTS_LOGICAL;
164 			break;
165 		case 'R':
166 			f_recursive = 1;
167 			break;
168 		case 'a':
169 			fts_options |= FTS_SEEDOT;
170 			/* FALLTHROUGH */
171 		case 'A':
172 			f_listdot = 1;
173 			break;
174 		/* The -d option turns off the -R option. */
175 		case 'd':
176 			f_listdir = 1;
177 			f_recursive = 0;
178 			break;
179 		case 'f':
180 			f_nosort = 1;
181 			break;
182 		case 'g':		/* Compatibility with 4.3BSD. */
183 			break;
184 		case 'i':
185 			f_inode = 1;
186 			break;
187 		case 'k':
188 			blocksize = 1024;
189 			kflag = 1;
190 			break;
191 		case 'o':
192 			f_flags = 1;
193 			break;
194 		case 'q':
195 			f_nonprint = 1;
196 			break;
197 		case 'r':
198 			f_reversesort = 1;
199 			break;
200 		case 'S':
201 			sortkey = BY_SIZE;
202 			break;
203 		case 's':
204 			f_size = 1;
205 			break;
206 		case 'T':
207 			f_sectime = 1;
208 			break;
209 		case 't':
210 			sortkey = BY_TIME;
211 			break;
212 		default:
213 		case '?':
214 			usage();
215 		}
216 	}
217 	argc -= optind;
218 	argv += optind;
219 
220 	/*
221 	 * If not -F, -i, -l, -S, -s or -t options, don't require stat
222 	 * information.
223 	 */
224 	if (!f_inode && !f_longform && !f_size && !f_type &&
225 	    sortkey == BY_NAME)
226 		fts_options |= FTS_NOSTAT;
227 
228 	/*
229 	 * If not -F, -d or -l options, follow any symbolic links listed on
230 	 * the command line.
231 	 */
232 	if (!f_longform && !f_listdir && !f_type)
233 		fts_options |= FTS_COMFOLLOW;
234 
235 	/* If -l or -s, figure out block size. */
236 	if (f_longform || f_size) {
237 		if (!kflag)
238 			(void)getbsize(&notused, &blocksize);
239 		blocksize /= 512;
240 	}
241 
242 	/* Select a sort function. */
243 	if (f_reversesort) {
244 		switch (sortkey) {
245 		case BY_NAME:
246 			sortfcn = revnamecmp;
247 			break;
248 		case BY_SIZE:
249 			sortfcn = revsizecmp;
250 			break;
251 		case BY_TIME:
252 			if (f_accesstime)
253 				sortfcn = revacccmp;
254 			else if (f_statustime)
255 				sortfcn = revstatcmp;
256 			else /* Use modification time. */
257 				sortfcn = revmodcmp;
258 			break;
259 		}
260 	} else {
261 		switch (sortkey) {
262 		case BY_NAME:
263 			sortfcn = namecmp;
264 			break;
265 		case BY_SIZE:
266 			sortfcn = sizecmp;
267 			break;
268 		case BY_TIME:
269 			if (f_accesstime)
270 				sortfcn = acccmp;
271 			else if (f_statustime)
272 				sortfcn = statcmp;
273 			else /* Use modification time. */
274 				sortfcn = modcmp;
275 			break;
276 		}
277 	}
278 
279 	/* Select a print function. */
280 	if (f_singlecol)
281 		printfcn = printscol;
282 	else if (f_longform)
283 		printfcn = printlong;
284 	else
285 		printfcn = printcol;
286 
287 	if (argc)
288 		traverse(argc, argv, fts_options);
289 	else
290 		traverse(1, dotav, fts_options);
291 	exit(0);
292 }
293 
294 static int output;			/* If anything output. */
295 
296 /*
297  * Traverse() walks the logical directory structure specified by the argv list
298  * in the order specified by the mastercmp() comparison function.  During the
299  * traversal it passes linked lists of structures to display() which represent
300  * a superset (may be exact set) of the files to be displayed.
301  */
302 static void
303 traverse(argc, argv, options)
304 	int argc, options;
305 	char *argv[];
306 {
307 	FTS *ftsp;
308 	FTSENT *p, *chp;
309 	int ch_options;
310 
311 	if ((ftsp =
312 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
313 		err(1, NULL);
314 
315 	display(NULL, fts_children(ftsp, 0));
316 	if (f_listdir)
317 		return;
318 
319 	/*
320 	 * If not recursing down this tree and don't need stat info, just get
321 	 * the names.
322 	 */
323 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
324 
325 	while ((p = fts_read(ftsp)) != NULL)
326 		switch (p->fts_info) {
327 		case FTS_DC:
328 			warnx("%s: directory causes a cycle", p->fts_name);
329 			break;
330 		case FTS_DNR:
331 		case FTS_ERR:
332 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
333 			break;
334 		case FTS_D:
335 			if (p->fts_level != FTS_ROOTLEVEL &&
336 			    p->fts_name[0] == '.' && !f_listdot)
337 				break;
338 
339 			/*
340 			 * If already output something, put out a newline as
341 			 * a separator.  If multiple arguments, precede each
342 			 * directory with its name.
343 			 */
344 			if (output)
345 				(void)printf("\n%s:\n", p->fts_path);
346 			else if (argc > 1) {
347 				(void)printf("%s:\n", p->fts_path);
348 				output = 1;
349 			}
350 
351 			chp = fts_children(ftsp, ch_options);
352 			display(p, chp);
353 
354 			if (!f_recursive && chp != NULL)
355 				(void)fts_set(ftsp, p, FTS_SKIP);
356 			break;
357 		}
358 	if (errno)
359 		err(1, "fts_read");
360 }
361 
362 /*
363  * Display() takes a linked list of FTSENT structures and passes the list
364  * along with any other necessary information to the print function.  P
365  * points to the parent directory of the display list.
366  */
367 static void
368 display(p, list)
369 	FTSENT *p, *list;
370 {
371 	struct stat *sp;
372 	DISPLAY d;
373 	FTSENT *cur;
374 	NAMES *np;
375 	u_quad_t maxsize;
376 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
377 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
378 	int entries, needstats;
379 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
380 
381 	/*
382 	 * If list is NULL there are two possibilities: that the parent
383 	 * directory p has no children, or that fts_children() returned an
384 	 * error.  We ignore the error case since it will be replicated
385 	 * on the next call to fts_read() on the post-order visit to the
386 	 * directory p, and will be signalled in traverse().
387 	 */
388 	if (list == NULL)
389 		return;
390 
391 	needstats = f_inode || f_longform || f_size;
392 	flen = 0;
393 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
394 	bcfile = 0;
395 	maxuser = maxgroup = maxflags = 0;
396 	maxsize = 0;
397 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
398 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
399 			warnx("%s: %s",
400 			    cur->fts_name, strerror(cur->fts_errno));
401 			cur->fts_number = NO_PRINT;
402 			continue;
403 		}
404 
405 		/*
406 		 * P is NULL if list is the argv list, to which different rules
407 		 * apply.
408 		 */
409 		if (p == NULL) {
410 			/* Directories will be displayed later. */
411 			if (cur->fts_info == FTS_D && !f_listdir) {
412 				cur->fts_number = NO_PRINT;
413 				continue;
414 			}
415 		} else {
416 			/* Only display dot file if -a/-A set. */
417 			if (cur->fts_name[0] == '.' && !f_listdot) {
418 				cur->fts_number = NO_PRINT;
419 				continue;
420 			}
421 		}
422 		if (f_nonprint)
423 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
424 		if (cur->fts_namelen > maxlen)
425 			maxlen = cur->fts_namelen;
426 		if (needstats) {
427 			sp = cur->fts_statp;
428 			if (sp->st_blocks > maxblock)
429 				maxblock = sp->st_blocks;
430 			if (sp->st_ino > maxinode)
431 				maxinode = sp->st_ino;
432 			if (sp->st_nlink > maxnlink)
433 				maxnlink = sp->st_nlink;
434 			if (sp->st_size > maxsize)
435 				maxsize = sp->st_size;
436 
437 			btotal += sp->st_blocks;
438 			if (f_longform) {
439 				user = user_from_uid(sp->st_uid, 0);
440 				if ((ulen = strlen(user)) > maxuser)
441 					maxuser = ulen;
442 				group = group_from_gid(sp->st_gid, 0);
443 				if ((glen = strlen(group)) > maxgroup)
444 					maxgroup = glen;
445 				if (f_flags) {
446 					flags =
447 					    flags_to_string(sp->st_flags, "-");
448 					if ((flen = strlen(flags)) > maxflags)
449 						maxflags = flen;
450 				} else
451 					flen = 0;
452 
453 				if ((np = malloc(sizeof(NAMES) +
454 				    ulen + glen + flen + 3)) == NULL)
455 					err(1, NULL);
456 
457 				np->user = &np->data[0];
458 				(void)strcpy(np->user, user);
459 				np->group = &np->data[ulen + 1];
460 				(void)strcpy(np->group, group);
461 
462 				if (S_ISCHR(sp->st_mode) ||
463 				    S_ISBLK(sp->st_mode))
464 					bcfile = 1;
465 
466 				if (f_flags) {
467 					np->flags = &np->data[ulen + glen + 2];
468 				  	(void)strcpy(np->flags, flags);
469 				}
470 				cur->fts_pointer = np;
471 			}
472 		}
473 		++entries;
474 	}
475 
476 	if (!entries)
477 		return;
478 
479 	d.list = list;
480 	d.entries = entries;
481 	d.maxlen = maxlen;
482 	if (needstats) {
483 		d.bcfile = bcfile;
484 		d.btotal = btotal;
485 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
486 		d.s_block = strlen(buf);
487 		d.s_flags = maxflags;
488 		d.s_group = maxgroup;
489 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
490 		d.s_inode = strlen(buf);
491 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
492 		d.s_nlink = strlen(buf);
493 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
494 		d.s_size = strlen(buf);
495 		d.s_user = maxuser;
496 	}
497 
498 	printfcn(&d);
499 	output = 1;
500 
501 	if (f_longform)
502 		for (cur = list; cur; cur = cur->fts_link)
503 			free(cur->fts_pointer);
504 }
505 
506 /*
507  * Ordering for mastercmp:
508  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
509  * as larger than directories.  Within either group, use the sort function.
510  * All other levels use the sort function.  Error entries remain unsorted.
511  */
512 static int
513 mastercmp(a, b)
514 	const FTSENT **a, **b;
515 {
516 	int a_info, b_info;
517 
518 	a_info = (*a)->fts_info;
519 	if (a_info == FTS_ERR)
520 		return (0);
521 	b_info = (*b)->fts_info;
522 	if (b_info == FTS_ERR)
523 		return (0);
524 
525 	if (a_info == FTS_NS || b_info == FTS_NS)
526 		return (namecmp(*a, *b));
527 
528 	if (a_info == b_info)
529 		return (sortfcn(*a, *b));
530 
531 	if ((*a)->fts_level == FTS_ROOTLEVEL)
532 		if (a_info == FTS_D)
533 			return (1);
534 		else if (b_info == FTS_D)
535 			return (-1);
536 		else
537 			return (sortfcn(*a, *b));
538 	else
539 		return (sortfcn(*a, *b));
540 }
541