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