Home | History | Annotate | Line # | Download | only in ls
ls.c revision 1.29
      1 /*	$NetBSD: ls.c,v 1.29 1998/07/28 05:15:47 mycroft 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.29 1998/07/28 05:15:47 mycroft 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_nonprint;			/* show unprintables as ? */
     98 int f_nosort;			/* don't sort output */
     99 int f_numericonly;		/* don't convert uid/gid to name */
    100 int f_recursive;		/* ls subdirectories also */
    101 int f_reversesort;		/* reverse whatever sort is used */
    102 int f_sectime;			/* print the real time for all files */
    103 int f_singlecol;		/* use single column output */
    104 int f_size;			/* list size in short listing */
    105 int f_statustime;		/* use time of last mode change */
    106 int f_type;			/* add type character for non-regular files */
    107 int f_whiteout;			/* show whiteout entries */
    108 
    109 int
    110 main(argc, argv)
    111 	int argc;
    112 	char *argv[];
    113 {
    114 	static char dot[] = ".", *dotav[] = { dot, NULL };
    115 	struct winsize win;
    116 	int ch, fts_options, notused;
    117 	int kflag = 0;
    118 	const char *p;
    119 
    120 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
    121 	if (isatty(STDOUT_FILENO)) {
    122 		if ((p = getenv("COLUMNS")) != NULL)
    123 			termwidth = atoi(p);
    124 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
    125 		    win.ws_col > 0)
    126 			termwidth = win.ws_col;
    127 		f_column = f_nonprint = 1;
    128 	} else
    129 		f_singlecol = 1;
    130 
    131 	/* Root is -A automatically. */
    132 	if (!getuid())
    133 		f_listdot = 1;
    134 
    135 	fts_options = FTS_PHYSICAL;
    136 	while ((ch = getopt(argc, argv, "1ACFLRSTWacdfgiklnoqrstux")) != -1) {
    137 		switch (ch) {
    138 		/*
    139 		 * The -1, -C, -l and -x options all override each other so
    140 		 * shell aliasing works correctly.
    141 		 */
    142 		case '1':
    143 			f_singlecol = 1;
    144 			f_column = f_columnacross = f_longform = 0;
    145 			break;
    146 		case 'C':
    147 			f_column = 1;
    148 			f_columnacross = f_longform = f_singlecol = 0;
    149 			break;
    150 		case 'l':
    151 			f_longform = 1;
    152 			f_column = f_columnacross = f_singlecol = 0;
    153 			break;
    154 		case 'x':
    155 			f_columnacross = 1;
    156 			f_column = f_longform = f_singlecol = 0;
    157 			break;
    158 		/* The -c and -u options override each other. */
    159 		case 'c':
    160 			f_statustime = 1;
    161 			f_accesstime = 0;
    162 			break;
    163 		case 'u':
    164 			f_accesstime = 1;
    165 			f_statustime = 0;
    166 			break;
    167 		case 'F':
    168 			f_type = 1;
    169 			break;
    170 		case 'L':
    171 			fts_options &= ~FTS_PHYSICAL;
    172 			fts_options |= FTS_LOGICAL;
    173 			break;
    174 		case 'R':
    175 			f_recursive = 1;
    176 			break;
    177 		case 'a':
    178 			fts_options |= FTS_SEEDOT;
    179 			/* FALLTHROUGH */
    180 		case 'A':
    181 			f_listdot = 1;
    182 			break;
    183 		/* The -d option turns off the -R option. */
    184 		case 'd':
    185 			f_listdir = 1;
    186 			f_recursive = 0;
    187 			break;
    188 		case 'f':
    189 			f_nosort = 1;
    190 			break;
    191 		case 'g':		/* Compatibility with 4.3BSD. */
    192 			break;
    193 		case 'i':
    194 			f_inode = 1;
    195 			break;
    196 		case 'k':
    197 			blocksize = 1024;
    198 			kflag = 1;
    199 			break;
    200 		case 'n':
    201 			f_numericonly = 1;
    202 			break;
    203 		case 'o':
    204 			f_flags = 1;
    205 			break;
    206 		case 'q':
    207 			f_nonprint = 1;
    208 			break;
    209 		case 'r':
    210 			f_reversesort = 1;
    211 			break;
    212 		case 'S':
    213 			sortkey = BY_SIZE;
    214 			break;
    215 		case 's':
    216 			f_size = 1;
    217 			break;
    218 		case 'T':
    219 			f_sectime = 1;
    220 			break;
    221 		case 't':
    222 			sortkey = BY_TIME;
    223 			break;
    224 		case 'W':
    225 			f_whiteout = 1;
    226 			break;
    227 		default:
    228 		case '?':
    229 			usage();
    230 		}
    231 	}
    232 	argc -= optind;
    233 	argv += optind;
    234 
    235 	/*
    236 	 * If not -F, -i, -l, -S, -s or -t options, don't require stat
    237 	 * information.
    238 	 */
    239 	if (!f_inode && !f_longform && !f_size && !f_type &&
    240 	    sortkey == BY_NAME)
    241 		fts_options |= FTS_NOSTAT;
    242 
    243 	/*
    244 	 * If not -F, -d or -l options, follow any symbolic links listed on
    245 	 * the command line.
    246 	 */
    247 	if (!f_longform && !f_listdir && !f_type)
    248 		fts_options |= FTS_COMFOLLOW;
    249 
    250 	/*
    251 	 * If -W, show whiteout entries
    252 	 */
    253 #ifdef FTS_WHITEOUT
    254 	if (f_whiteout)
    255 		fts_options |= FTS_WHITEOUT;
    256 #endif
    257 
    258 	/* If -l or -s, figure out block size. */
    259 	if (f_longform || f_size) {
    260 		if (!kflag)
    261 			(void)getbsize(&notused, &blocksize);
    262 		blocksize /= 512;
    263 	}
    264 
    265 	/* Select a sort function. */
    266 	if (f_reversesort) {
    267 		switch (sortkey) {
    268 		case BY_NAME:
    269 			sortfcn = revnamecmp;
    270 			break;
    271 		case BY_SIZE:
    272 			sortfcn = revsizecmp;
    273 			break;
    274 		case BY_TIME:
    275 			if (f_accesstime)
    276 				sortfcn = revacccmp;
    277 			else if (f_statustime)
    278 				sortfcn = revstatcmp;
    279 			else /* Use modification time. */
    280 				sortfcn = revmodcmp;
    281 			break;
    282 		}
    283 	} else {
    284 		switch (sortkey) {
    285 		case BY_NAME:
    286 			sortfcn = namecmp;
    287 			break;
    288 		case BY_SIZE:
    289 			sortfcn = sizecmp;
    290 			break;
    291 		case BY_TIME:
    292 			if (f_accesstime)
    293 				sortfcn = acccmp;
    294 			else if (f_statustime)
    295 				sortfcn = statcmp;
    296 			else /* Use modification time. */
    297 				sortfcn = modcmp;
    298 			break;
    299 		}
    300 	}
    301 
    302 	/* Select a print function. */
    303 	if (f_singlecol)
    304 		printfcn = printscol;
    305 	else if (f_columnacross)
    306 		printfcn = printacol;
    307 	else if (f_longform)
    308 		printfcn = printlong;
    309 	else
    310 		printfcn = printcol;
    311 
    312 	if (argc)
    313 		traverse(argc, argv, fts_options);
    314 	else
    315 		traverse(1, dotav, fts_options);
    316 	exit(0);
    317 }
    318 
    319 static int output;			/* If anything output. */
    320 
    321 /*
    322  * Traverse() walks the logical directory structure specified by the argv list
    323  * in the order specified by the mastercmp() comparison function.  During the
    324  * traversal it passes linked lists of structures to display() which represent
    325  * a superset (may be exact set) of the files to be displayed.
    326  */
    327 static void
    328 traverse(argc, argv, options)
    329 	int argc, options;
    330 	char *argv[];
    331 {
    332 	FTS *ftsp;
    333 	FTSENT *p, *chp;
    334 	int ch_options;
    335 
    336 	if ((ftsp =
    337 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
    338 		err(1, "%s", "");
    339 
    340 	display(NULL, fts_children(ftsp, 0));
    341 	if (f_listdir)
    342 		return;
    343 
    344 	/*
    345 	 * If not recursing down this tree and don't need stat info, just get
    346 	 * the names.
    347 	 */
    348 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
    349 
    350 	while ((p = fts_read(ftsp)) != NULL)
    351 		switch (p->fts_info) {
    352 		case FTS_DC:
    353 			warnx("%s: directory causes a cycle", p->fts_name);
    354 			break;
    355 		case FTS_DNR:
    356 		case FTS_ERR:
    357 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
    358 			break;
    359 		case FTS_D:
    360 			if (p->fts_level != FTS_ROOTLEVEL &&
    361 			    p->fts_name[0] == '.' && !f_listdot)
    362 				break;
    363 
    364 			/*
    365 			 * If already output something, put out a newline as
    366 			 * a separator.  If multiple arguments, precede each
    367 			 * directory with its name.
    368 			 */
    369 			if (output)
    370 				(void)printf("\n%s:\n", p->fts_path);
    371 			else if (argc > 1) {
    372 				(void)printf("%s:\n", p->fts_path);
    373 				output = 1;
    374 			}
    375 
    376 			chp = fts_children(ftsp, ch_options);
    377 			display(p, chp);
    378 
    379 			if (!f_recursive && chp != NULL)
    380 				(void)fts_set(ftsp, p, FTS_SKIP);
    381 			break;
    382 		}
    383 	if (errno)
    384 		err(1, "fts_read");
    385 }
    386 
    387 /*
    388  * Display() takes a linked list of FTSENT structures and passes the list
    389  * along with any other necessary information to the print function.  P
    390  * points to the parent directory of the display list.
    391  */
    392 static void
    393 display(p, list)
    394 	FTSENT *p, *list;
    395 {
    396 	struct stat *sp;
    397 	DISPLAY d;
    398 	FTSENT *cur;
    399 	NAMES *np;
    400 	u_int64_t btotal, maxblock, maxsize;
    401 	int maxinode, maxnlink, maxmajor, maxminor;
    402 	int bcfile, entries, flen, glen, ulen, maxflags, maxgroup, maxlen;
    403 	int maxuser, needstats;
    404 	const char *user, *group;
    405 	char buf[21];			/* 64 bits == 20 digits, +1 for NUL */
    406 	char nuser[12], ngroup[12];
    407 	char *flags = NULL;
    408 
    409 #ifdef __GNUC__
    410 	/* This outrageous construct just to shut up a GCC warning. */
    411 	(void) &maxsize;
    412 #endif
    413 
    414 	/*
    415 	 * If list is NULL there are two possibilities: that the parent
    416 	 * directory p has no children, or that fts_children() returned an
    417 	 * error.  We ignore the error case since it will be replicated
    418 	 * on the next call to fts_read() on the post-order visit to the
    419 	 * directory p, and will be signalled in traverse().
    420 	 */
    421 	if (list == NULL)
    422 		return;
    423 
    424 	needstats = f_inode || f_longform || f_size;
    425 	flen = 0;
    426 	maxinode = maxnlink = 0;
    427 	bcfile = 0;
    428 	maxuser = maxgroup = maxflags = maxlen = 0;
    429 	btotal = maxblock = maxsize = 0;
    430 	maxmajor = maxminor = 0;
    431 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
    432 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
    433 			warnx("%s: %s",
    434 			    cur->fts_name, strerror(cur->fts_errno));
    435 			cur->fts_number = NO_PRINT;
    436 			continue;
    437 		}
    438 
    439 		/*
    440 		 * P is NULL if list is the argv list, to which different rules
    441 		 * apply.
    442 		 */
    443 		if (p == NULL) {
    444 			/* Directories will be displayed later. */
    445 			if (cur->fts_info == FTS_D && !f_listdir) {
    446 				cur->fts_number = NO_PRINT;
    447 				continue;
    448 			}
    449 		} else {
    450 			/* Only display dot file if -a/-A set. */
    451 			if (cur->fts_name[0] == '.' && !f_listdot) {
    452 				cur->fts_number = NO_PRINT;
    453 				continue;
    454 			}
    455 		}
    456 		if (f_nonprint)
    457 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
    458 		if (cur->fts_namelen > maxlen)
    459 			maxlen = cur->fts_namelen;
    460 		if (needstats) {
    461 			sp = cur->fts_statp;
    462 			if (sp->st_blocks > maxblock)
    463 				maxblock = sp->st_blocks;
    464 			if (sp->st_ino > maxinode)
    465 				maxinode = sp->st_ino;
    466 			if (sp->st_nlink > maxnlink)
    467 				maxnlink = sp->st_nlink;
    468 			if (sp->st_size > maxsize)
    469 				maxsize = sp->st_size;
    470 			if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode)) {
    471 				bcfile = 1;
    472 				if (major(sp->st_rdev) > maxmajor)
    473 					maxmajor = major(sp->st_rdev);
    474 				if (minor(sp->st_rdev) > maxminor)
    475 					maxminor = minor(sp->st_rdev);
    476 			}
    477 
    478 			btotal += sp->st_blocks;
    479 			if (f_longform) {
    480 				if (f_numericonly) {
    481 					(void)snprintf(nuser, sizeof(nuser),
    482 					    "%u", sp->st_uid);
    483 					(void)snprintf(ngroup, sizeof(ngroup),
    484 					    "%u", sp->st_gid);
    485 					user = nuser;
    486 					group = ngroup;
    487 				} else {
    488 					user = user_from_uid(sp->st_uid, 0);
    489 					group = group_from_gid(sp->st_gid, 0);
    490 				}
    491 				if ((ulen = strlen(user)) > maxuser)
    492 					maxuser = ulen;
    493 				if ((glen = strlen(group)) > maxgroup)
    494 					maxgroup = glen;
    495 				if (f_flags) {
    496 					flags =
    497 					    flags_to_string(sp->st_flags, "-");
    498 					if ((flen = strlen(flags)) > maxflags)
    499 						maxflags = flen;
    500 				} else
    501 					flen = 0;
    502 
    503 				if ((np = malloc(sizeof(NAMES) +
    504 				    ulen + glen + flen + 3)) == NULL)
    505 					err(1, "%s", "");
    506 
    507 				np->user = &np->data[0];
    508 				(void)strcpy(np->user, user);
    509 				np->group = &np->data[ulen + 1];
    510 				(void)strcpy(np->group, group);
    511 
    512 				if (f_flags) {
    513 					np->flags = &np->data[ulen + glen + 2];
    514 				  	(void)strcpy(np->flags, flags);
    515 				}
    516 				cur->fts_pointer = np;
    517 			}
    518 		}
    519 		++entries;
    520 	}
    521 
    522 	if (!entries)
    523 		return;
    524 
    525 	d.list = list;
    526 	d.entries = entries;
    527 	d.maxlen = maxlen;
    528 	if (needstats) {
    529 		d.btotal = btotal;
    530 		(void)snprintf(buf, sizeof(buf), "%qu", (long long)maxblock);
    531 		d.s_block = strlen(buf);
    532 		d.s_flags = maxflags;
    533 		d.s_group = maxgroup;
    534 		(void)snprintf(buf, sizeof(buf), "%u", maxinode);
    535 		d.s_inode = strlen(buf);
    536 		(void)snprintf(buf, sizeof(buf), "%u", maxnlink);
    537 		d.s_nlink = strlen(buf);
    538 		(void)snprintf(buf, sizeof(buf), "%qu", (long long)maxsize);
    539 		d.s_size = strlen(buf);
    540 		d.s_user = maxuser;
    541 		if (bcfile) {
    542 			(void)snprintf(buf, sizeof(buf), "%u", maxmajor);
    543 			d.s_major = strlen(buf);
    544 			(void)snprintf(buf, sizeof(buf), "%u", maxminor);
    545 			d.s_minor = strlen(buf);
    546 			if (d.s_major + d.s_minor + 2 > d.s_size)
    547 				d.s_size = d.s_major + d.s_minor + 2;
    548 			else if (d.s_size - d.s_minor - 2 > d.s_major)
    549 				d.s_major = d.s_size - d.s_minor - 2;
    550 		} else {
    551 			d.s_major = 0;
    552 			d.s_minor = 0;
    553 		}
    554 	}
    555 
    556 	printfcn(&d);
    557 	output = 1;
    558 
    559 	if (f_longform)
    560 		for (cur = list; cur; cur = cur->fts_link)
    561 			free(cur->fts_pointer);
    562 }
    563 
    564 /*
    565  * Ordering for mastercmp:
    566  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
    567  * as larger than directories.  Within either group, use the sort function.
    568  * All other levels use the sort function.  Error entries remain unsorted.
    569  */
    570 static int
    571 mastercmp(a, b)
    572 	const FTSENT **a, **b;
    573 {
    574 	int a_info, b_info;
    575 
    576 	a_info = (*a)->fts_info;
    577 	if (a_info == FTS_ERR)
    578 		return (0);
    579 	b_info = (*b)->fts_info;
    580 	if (b_info == FTS_ERR)
    581 		return (0);
    582 
    583 	if (a_info == FTS_NS || b_info == FTS_NS)
    584 		if (b_info != FTS_NS)
    585 			return (1);
    586 		else if (a_info != FTS_NS)
    587 			return (-1);
    588 		else
    589 			return (namecmp(*a, *b));
    590 
    591 	if (a_info != b_info && !f_listdir &&
    592 	    (*a)->fts_level == FTS_ROOTLEVEL) {
    593 		if (a_info == FTS_D)
    594 			return (1);
    595 		else if (b_info == FTS_D)
    596 			return (-1);
    597 	}
    598 	return (sortfcn(*a, *b));
    599 }
    600