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