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