lobase

Linux port of OpenBSDs userland.

ls.c (15530B)


      1 /*	$OpenBSD: ls.c,v 1.48 2016/08/16 16:13:32 krw Exp $	*/
      2 /*	$NetBSD: ls.c,v 1.18 1996/07/09 09:16:29 mycroft Exp $	*/
      3 
      4 /*
      5  * Copyright (c) 1989, 1993, 1994
      6  *	The Regents of the University of California.  All rights reserved.
      7  *
      8  * This code is derived from software contributed to Berkeley by
      9  * Michael Fischbein.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/types.h>
     37 #include <sys/stat.h>
     38 #include <sys/ioctl.h>
     39 
     40 #include <dirent.h>
     41 #include <err.h>
     42 #include <errno.h>
     43 #include <fts.h>
     44 #include <grp.h>
     45 #include <pwd.h>
     46 #include <stdio.h>
     47 #include <stdlib.h>
     48 #include <string.h>
     49 #include <unistd.h>
     50 #include <limits.h>
     51 #include <locale.h>
     52 #include <util.h>
     53 
     54 #include "ls.h"
     55 #include "extern.h"
     56 
     57 static void	 display(FTSENT *, FTSENT *);
     58 static int	 mastercmp(const FTSENT **, const FTSENT **);
     59 static void	 traverse(int, char **, int);
     60 
     61 static void (*printfcn)(DISPLAY *);
     62 static int (*sortfcn)(const FTSENT *, const FTSENT *);
     63 
     64 #define	BY_NAME 0
     65 #define	BY_SIZE 1
     66 #define	BY_TIME	2
     67 
     68 long blocksize;			/* block size units */
     69 int termwidth;			/* default terminal width */
     70 int sortkey = BY_NAME;
     71 
     72 /* flags */
     73 int f_accesstime;		/* use time of last access */
     74 int f_column;			/* columnated format */
     75 int f_columnacross;		/* columnated format, sorted across */
     76 #if 0
     77 int f_flags;			/* show flags associated with a file */
     78 #endif
     79 int f_grouponly;		/* long listing format without owner */
     80 int f_humanval;			/* show human-readable file sizes */
     81 int f_inode;			/* print inode */
     82 int f_listdir;			/* list actual directory, not contents */
     83 int f_listdot;			/* list files beginning with . */
     84 int f_longform;			/* long listing format */
     85 int f_nonprint;			/* show unprintables as ? */
     86 int f_nosort;			/* don't sort output */
     87 int f_numericonly;		/* don't expand uid to symbolic name */
     88 int f_recursive;		/* ls subdirectories also */
     89 int f_reversesort;		/* reverse whatever sort is used */
     90 int f_sectime;			/* print the real time for all files */
     91 int f_singlecol;		/* use single column output */
     92 int f_size;			/* list size in short listing */
     93 int f_statustime;		/* use time of last mode change */
     94 int f_stream;			/* stream format */
     95 int f_type;			/* add type character for non-regular files */
     96 int f_typedir;			/* add type character for directories */
     97 
     98 int rval;
     99 
    100 int
    101 ls_main(int argc, char *argv[])
    102 {
    103 	static char dot[] = ".", *dotav[] = { dot, NULL };
    104 	struct winsize win;
    105 	int ch, fts_options, notused;
    106 	int kflag = 0;
    107 	char *p;
    108 
    109 #ifndef SMALL
    110 	setlocale(LC_CTYPE, "");
    111 #endif
    112 
    113 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
    114 	if (isatty(STDOUT_FILENO)) {
    115 		f_column = f_nonprint = 1;
    116 	} else {
    117 		f_singlecol = 1;
    118 	}
    119 
    120 	termwidth = 0;
    121 	if ((p = getenv("COLUMNS")) != NULL)
    122 		termwidth = strtonum(p, 1, INT_MAX, NULL);
    123 	if (termwidth == 0 && ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
    124 	    win.ws_col > 0)
    125 		termwidth = win.ws_col;
    126 	if (termwidth == 0)
    127 		termwidth = 80;
    128 
    129 	if (pledge("stdio rpath getpw", NULL) == -1)
    130 		err(1, "pledge");
    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, "1ACFHLRSTacdfghiklmnopqrstux")) != -1) {
    138 		switch (ch) {
    139 		/*
    140 		 * The -1, -C and -l, -m, -n and -x options all override each
    141 		 * other so shell aliasing works right.
    142 		 */
    143 		case '1':
    144 			f_singlecol = 1;
    145 			f_column = f_columnacross = f_longform = 0;
    146 			f_numericonly = f_stream = 0;
    147 			break;
    148 		case 'C':
    149 			f_column = 1;
    150 			f_columnacross = f_longform = f_numericonly = 0;
    151 			f_singlecol = f_stream = 0;
    152 			break;
    153 		case 'g':
    154 			f_longform = 1;
    155 			if (f_grouponly != -1)
    156 				f_grouponly = 1;
    157 			f_column = f_columnacross = f_singlecol = f_stream = 0;
    158 			break;
    159 		case 'l':
    160 			f_longform = 1;
    161 			f_grouponly = -1;	/* -l always overrides -g */
    162 			f_column = f_columnacross = f_singlecol = f_stream = 0;
    163 			break;
    164 		case 'm':
    165 			f_stream = 1;
    166 			f_column = f_columnacross = f_longform = 0;
    167 			f_numericonly = f_singlecol = 0;
    168 			break;
    169 		case 'x':
    170 			f_columnacross = 1;
    171 			f_column = f_longform = f_numericonly = 0;
    172 			f_singlecol = f_stream = 0;
    173 			break;
    174 		case 'n':
    175 			f_longform = 1;
    176 			f_numericonly = 1;
    177 			f_column = f_columnacross = f_singlecol = f_stream = 0;
    178 			break;
    179 		/* The -c and -u options override each other. */
    180 		case 'c':
    181 			f_statustime = 1;
    182 			f_accesstime = 0;
    183 			break;
    184 		case 'u':
    185 			f_accesstime = 1;
    186 			f_statustime = 0;
    187 			break;
    188 		case 'F':
    189 			f_type = 1;
    190 			break;
    191 		case 'H':
    192 			fts_options |= FTS_COMFOLLOW;
    193 			break;
    194 		case 'L':
    195 			fts_options &= ~FTS_PHYSICAL;
    196 			fts_options |= FTS_LOGICAL;
    197 			break;
    198 		case 'R':
    199 			f_recursive = 1;
    200 			break;
    201 		case 'f':
    202 			f_nosort = 1;
    203 			/* FALLTHROUGH */
    204 		case 'a':
    205 			fts_options |= FTS_SEEDOT;
    206 			/* FALLTHROUGH */
    207 		case 'A':
    208 			f_listdot = 1;
    209 			break;
    210 		/* The -d option turns off the -R option. */
    211 		case 'd':
    212 			f_listdir = 1;
    213 			f_recursive = 0;
    214 			break;
    215 		case 'h':
    216 			f_humanval = 1;
    217 			break;
    218 		case 'i':
    219 			f_inode = 1;
    220 			break;
    221 		case 'k':
    222 			blocksize = 1024;
    223 			kflag = 1;
    224 			break;
    225 #if 0
    226 		case 'o':
    227 			f_flags = 1;
    228 			break;
    229 #endif
    230 		case 'p':
    231 			f_typedir = 1;
    232 			break;
    233 		case 'q':
    234 			f_nonprint = 1;
    235 			break;
    236 		case 'r':
    237 			f_reversesort = 1;
    238 			break;
    239 		case 'S':
    240 			sortkey = BY_SIZE;
    241 			break;
    242 		case 's':
    243 			f_size = 1;
    244 			break;
    245 		case 'T':
    246 			f_sectime = 1;
    247 			break;
    248 		case 't':
    249 			sortkey = BY_TIME;
    250 			break;
    251 		default:
    252 			usage();
    253 		}
    254 	}
    255 	argc -= optind;
    256 	argv += optind;
    257 
    258 	/*
    259 	 * If both -g and -l options, let -l take precedence.
    260 	 * This preserves compatibility with the historic BSD ls -lg.
    261 	 */
    262 	if (f_grouponly == -1)
    263 		f_grouponly = 0;
    264 
    265 	/*
    266 	 * If not -F, -i, -l, -p, -S, -s or -t options, don't require stat
    267 	 * information.
    268 	 */
    269 	if (!f_longform && !f_inode && !f_size && !f_type && !f_typedir &&
    270 	    sortkey == BY_NAME)
    271 		fts_options |= FTS_NOSTAT;
    272 
    273 	/*
    274 	 * If not -F, -d or -l options, follow any symbolic links listed on
    275 	 * the command line.
    276 	 */
    277 	if (!f_longform && !f_listdir && !f_type)
    278 		fts_options |= FTS_COMFOLLOW;
    279 
    280 	/* If -l or -s, figure out block size. */
    281 	if (f_longform || f_size) {
    282 		if (!kflag)
    283 			(void)getbsize(&notused, &blocksize);
    284 		blocksize /= 512;
    285 	}
    286 
    287 	/* Select a sort function. */
    288 	if (f_reversesort) {
    289 		switch (sortkey) {
    290 		case BY_NAME:
    291 			sortfcn = revnamecmp;
    292 			break;
    293 		case BY_SIZE:
    294 			sortfcn = revsizecmp;
    295 			break;
    296 		case BY_TIME:
    297 			if (f_accesstime)
    298 				sortfcn = revacccmp;
    299 			else if (f_statustime)
    300 				sortfcn = revstatcmp;
    301 			else /* Use modification time. */
    302 				sortfcn = revmodcmp;
    303 			break;
    304 		}
    305 	} else {
    306 		switch (sortkey) {
    307 		case BY_NAME:
    308 			sortfcn = namecmp;
    309 			break;
    310 		case BY_SIZE:
    311 			sortfcn = sizecmp;
    312 			break;
    313 		case BY_TIME:
    314 			if (f_accesstime)
    315 				sortfcn = acccmp;
    316 			else if (f_statustime)
    317 				sortfcn = statcmp;
    318 			else /* Use modification time. */
    319 				sortfcn = modcmp;
    320 			break;
    321 		}
    322 	}
    323 
    324 	/* Select a print function. */
    325 	if (f_singlecol)
    326 		printfcn = printscol;
    327 	else if (f_columnacross)
    328 		printfcn = printacol;
    329 	else if (f_longform)
    330 		printfcn = printlong;
    331 	else if (f_stream)
    332 		printfcn = printstream;
    333 	else
    334 		printfcn = printcol;
    335 
    336 	if (argc)
    337 		traverse(argc, argv, fts_options);
    338 	else
    339 		traverse(1, dotav, fts_options);
    340 	return (rval);
    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, saved_errno;
    357 
    358 	if ((ftsp =
    359 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
    360 		err(1, 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_D:
    375 			if (p->fts_name[0] == '.' &&
    376 			    p->fts_level != FTS_ROOTLEVEL && !f_listdot)
    377 				break;
    378 
    379 			/*
    380 			 * If already output something, put out a newline as
    381 			 * a separator.  If multiple arguments, precede each
    382 			 * directory with its name.
    383 			 */
    384 			if (output)
    385 				(void)printf("\n%s:\n", p->fts_path);
    386 			else if (argc > 1) {
    387 				(void)printf("%s:\n", p->fts_path);
    388 				output = 1;
    389 			}
    390 
    391 			chp = fts_children(ftsp, ch_options);
    392 			saved_errno = errno;
    393 			display(p, chp);
    394 
    395 			/*
    396 			 * On fts_children() returning error do recurse to see
    397 			 * the error.
    398 			 */
    399 			if (!f_recursive && !(chp == NULL && saved_errno != 0))
    400 				(void)fts_set(ftsp, p, FTS_SKIP);
    401 			break;
    402 		case FTS_DC:
    403 			warnx("%s: directory causes a cycle", p->fts_name);
    404 			break;
    405 		case FTS_DNR:
    406 		case FTS_ERR:
    407 			warnx("%s: %s", p->fts_name[0] == '\0' ? p->fts_path :
    408 			    p->fts_name, strerror(p->fts_errno));
    409 			rval = 1;
    410 			break;
    411 		}
    412 	if (errno)
    413 		err(1, "fts_read");
    414 
    415 	fts_close(ftsp);
    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 	off_t maxsize;
    431 	nlink_t maxnlink;
    432 	unsigned long long btotal;
    433 	blkcnt_t maxblock;
    434 	ino_t maxinode;
    435 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser, maxlen;
    436 	int entries, needstats;
    437 	int width;
    438 	char *user, *group, buf[21];	/* 64 bits == 20 digits */
    439 	char nuser[12], ngroup[12];
    440 #if 0
    441 	char *flags = NULL;
    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 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
    457 	bcfile = 0;
    458 	maxuser = maxgroup = maxflags = 0;
    459 	maxsize = 0;
    460 	for (cur = list, entries = 0; cur != NULL; cur = cur->fts_link) {
    461 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
    462 			warnx("%s: %s",
    463 			    cur->fts_name, strerror(cur->fts_errno));
    464 			cur->fts_number = NO_PRINT;
    465 			rval = 1;
    466 			continue;
    467 		}
    468 
    469 		/*
    470 		 * P is NULL if list is the argv list, to which different rules
    471 		 * apply.
    472 		 */
    473 		if (p == NULL) {
    474 			/* Directories will be displayed later. */
    475 			if (cur->fts_info == FTS_D && !f_listdir) {
    476 				cur->fts_number = NO_PRINT;
    477 				continue;
    478 			}
    479 		} else {
    480 			/* Only display dot file if -a/-A set. */
    481 			if (cur->fts_name[0] == '.' && !f_listdot) {
    482 				cur->fts_number = NO_PRINT;
    483 				continue;
    484 			}
    485 		}
    486 		if ((width = mbsprint(cur->fts_name, 0)) > maxlen)
    487 			maxlen = width;
    488 		if (needstats) {
    489 			sp = cur->fts_statp;
    490 			if (sp->st_blocks > maxblock)
    491 				maxblock = sp->st_blocks;
    492 			if (sp->st_ino > maxinode)
    493 				maxinode = sp->st_ino;
    494 			if (sp->st_nlink > maxnlink)
    495 				maxnlink = sp->st_nlink;
    496 			if (sp->st_size > maxsize)
    497 				maxsize = sp->st_size;
    498 
    499 			btotal += sp->st_blocks;
    500 			if (f_longform) {
    501 				if (f_numericonly) {
    502 					snprintf(nuser, 12, "%u", sp->st_uid);
    503 					snprintf(ngroup, 12, "%u", sp->st_gid);
    504 					user = nuser;
    505 					group = ngroup;
    506 				} else {
    507 					user = user_from_uid(sp->st_uid, 0);
    508 					group = group_from_gid(sp->st_gid, 0);
    509 				}
    510 				if ((ulen = strlen(user)) > maxuser)
    511 					maxuser = ulen;
    512 				if ((glen = strlen(group)) > maxgroup)
    513 					maxgroup = glen;
    514 #if 0
    515 				if (f_flags) {
    516 					flags = fflagstostr(sp->st_flags);
    517 					if (*flags == '\0')
    518 						flags = "-";
    519 					if ((flen = strlen(flags)) > maxflags)
    520 						maxflags = flen;
    521 				} else
    522 					flen = 0;
    523 #else
    524 				flen = 0;
    525 #endif
    526 
    527 				if ((np = malloc(sizeof(NAMES) +
    528 				    ulen + 1 + glen + 1 + flen + 1)) == NULL)
    529 					err(1, NULL);
    530 
    531 				np->user = &np->data[0];
    532 				(void)strlcpy(np->user, user, ulen + 1);
    533 				np->group = &np->data[ulen + 1];
    534 				(void)strlcpy(np->group, group, glen + 1);
    535 
    536 				if (S_ISCHR(sp->st_mode) ||
    537 				    S_ISBLK(sp->st_mode))
    538 					bcfile = 1;
    539 
    540 #if 0
    541 				if (f_flags) {
    542 					np->flags = &np->data[ulen + 1 + glen + 1];
    543 					(void)strlcpy(np->flags, flags, flen + 1);
    544 					if (*flags != '-')
    545 						free(flags);
    546 				}
    547 #endif
    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.bcfile = bcfile;
    562 		d.btotal = btotal;
    563 		(void)snprintf(buf, sizeof(buf), "%llu",
    564 		   (unsigned long long)maxblock);
    565 		d.s_block = strlen(buf);
    566 		d.s_flags = maxflags;
    567 		d.s_group = maxgroup;
    568 		(void)snprintf(buf, sizeof(buf), "%llu",
    569 		    (unsigned long long)maxinode);
    570 		d.s_inode = strlen(buf);
    571 		(void)snprintf(buf, sizeof(buf), "%lu",
    572 		    (unsigned long)maxnlink);
    573 		d.s_nlink = strlen(buf);
    574 		if (!f_humanval) {
    575 			(void)snprintf(buf, sizeof(buf), "%lld",
    576 				(long long) maxsize);
    577 			d.s_size = strlen(buf);
    578 		} else
    579 			d.s_size = FMT_SCALED_STRSIZE-2; /* no - or '\0' */
    580 		d.s_user = maxuser;
    581 	}
    582 
    583 	printfcn(&d);
    584 	output = 1;
    585 
    586 	if (f_longform)
    587 		for (cur = list; cur != NULL; cur = cur->fts_link)
    588 			free(cur->fts_pointer);
    589 }
    590 
    591 /*
    592  * Ordering for mastercmp:
    593  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
    594  * as larger than directories.  Within either group, use the sort function.
    595  * All other levels use the sort function.  Error entries remain unsorted.
    596  */
    597 static int
    598 mastercmp(const FTSENT **a, const FTSENT **b)
    599 {
    600 	int a_info, b_info;
    601 
    602 	a_info = (*a)->fts_info;
    603 	if (a_info == FTS_ERR)
    604 		return (0);
    605 	b_info = (*b)->fts_info;
    606 	if (b_info == FTS_ERR)
    607 		return (0);
    608 
    609 	if (a_info == FTS_NS || b_info == FTS_NS) {
    610 		if (b_info != FTS_NS)
    611 			return (1);
    612 		else if (a_info != FTS_NS)
    613 			return (-1);
    614 		else
    615 			return (namecmp(*a, *b));
    616 	}
    617 
    618 	if (a_info != b_info &&
    619 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
    620 		if (a_info == FTS_D)
    621 			return (1);
    622 		if (b_info == FTS_D)
    623 			return (-1);
    624 	}
    625 	return (sortfcn(*a, *b));
    626 }