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