Home | History | Annotate | Line # | Download | only in ls
ls.c revision 1.1.1.3
      1 /*
      2  * Copyright (c) 1989, 1993, 1994
      3  *	The Regents of the University of California.  All rights reserved.
      4  *
      5  * This code is derived from software contributed to Berkeley by
      6  * Michael Fischbein.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. All advertising materials mentioning features or use of this software
     17  *    must display the following acknowledgement:
     18  *	This product includes software developed by the University of
     19  *	California, Berkeley and its contributors.
     20  * 4. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  */
     36 
     37 #ifndef lint
     38 static char copyright[] =
     39 "@(#) Copyright (c) 1989, 1993, 1994\n\
     40 	The Regents of the University of California.  All rights reserved.\n";
     41 #endif /* not lint */
     42 
     43 #ifndef lint
     44 static char sccsid[] = "@(#)ls.c	8.7 (Berkeley) 8/5/94";
     45 #endif /* not lint */
     46 
     47 #include <sys/types.h>
     48 #include <sys/stat.h>
     49 #include <sys/ioctl.h>
     50 
     51 #include <dirent.h>
     52 #include <err.h>
     53 #include <errno.h>
     54 #include <fts.h>
     55 #include <stdio.h>
     56 #include <stdlib.h>
     57 #include <string.h>
     58 #include <unistd.h>
     59 
     60 #include "ls.h"
     61 #include "extern.h"
     62 
     63 static void	 display __P((FTSENT *, FTSENT *));
     64 static int	 mastercmp __P((const FTSENT **, const FTSENT **));
     65 static void	 traverse __P((int, char **, int));
     66 
     67 static void (*printfcn) __P((DISPLAY *));
     68 static int (*sortfcn) __P((const FTSENT *, const FTSENT *));
     69 
     70 long blocksize;			/* block size units */
     71 int termwidth = 80;		/* default terminal width */
     72 
     73 /* flags */
     74 int f_accesstime;		/* use time of last access */
     75 int f_column;			/* columnated format */
     76 int f_flags;			/* show flags associated with a file */
     77 int f_inode;			/* print inode */
     78 int f_listdir;			/* list actual directory, not contents */
     79 int f_listdot;			/* list files beginning with . */
     80 int f_longform;			/* long listing format */
     81 int f_newline;			/* if precede with newline */
     82 int f_nonprint;			/* show unprintables as ? */
     83 int f_nosort;			/* don't sort output */
     84 int f_recursive;		/* ls subdirectories also */
     85 int f_reversesort;		/* reverse whatever sort is used */
     86 int f_sectime;			/* print the real time for all files */
     87 int f_singlecol;		/* use single column output */
     88 int f_size;			/* list size in short listing */
     89 int f_statustime;		/* use time of last mode change */
     90 int f_dirname;			/* if precede with directory name */
     91 int f_timesort;			/* sort by time vice name */
     92 int f_type;			/* add type character for non-regular files */
     93 int f_whiteout;			/* show whiteout entries */
     94 
     95 int
     96 main(argc, argv)
     97 	int argc;
     98 	char *argv[];
     99 {
    100 	static char dot[] = ".", *dotav[] = { dot, NULL };
    101 	struct winsize win;
    102 	int ch, fts_options, notused;
    103 	char *p;
    104 
    105 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
    106 	if (isatty(STDOUT_FILENO)) {
    107 		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == -1 ||
    108 		    !win.ws_col) {
    109 			if ((p = getenv("COLUMNS")) != NULL)
    110 				termwidth = atoi(p);
    111 		}
    112 		else
    113 			termwidth = win.ws_col;
    114 		f_column = f_nonprint = 1;
    115 	} else
    116 		f_singlecol = 1;
    117 
    118 	/* Root is -A automatically. */
    119 	if (!getuid())
    120 		f_listdot = 1;
    121 
    122 	fts_options = FTS_PHYSICAL;
    123 	while ((ch = getopt(argc, argv, "1ACFLRTWacdfgiloqrstu")) != EOF) {
    124 		switch (ch) {
    125 		/*
    126 		 * The -1, -C and -l options all override each other so shell
    127 		 * aliasing works right.
    128 		 */
    129 		case '1':
    130 			f_singlecol = 1;
    131 			f_column = f_longform = 0;
    132 			break;
    133 		case 'C':
    134 			f_column = 1;
    135 			f_longform = f_singlecol = 0;
    136 			break;
    137 		case 'l':
    138 			f_longform = 1;
    139 			f_column = f_singlecol = 0;
    140 			break;
    141 		/* The -c and -u options override each other. */
    142 		case 'c':
    143 			f_statustime = 1;
    144 			f_accesstime = 0;
    145 			break;
    146 		case 'u':
    147 			f_accesstime = 1;
    148 			f_statustime = 0;
    149 			break;
    150 		case 'F':
    151 			f_type = 1;
    152 			break;
    153 		case 'L':
    154 			fts_options &= ~FTS_PHYSICAL;
    155 			fts_options |= FTS_LOGICAL;
    156 			break;
    157 		case 'R':
    158 			f_recursive = 1;
    159 			break;
    160 		case 'a':
    161 			fts_options |= FTS_SEEDOT;
    162 			/* FALLTHROUGH */
    163 		case 'A':
    164 			f_listdot = 1;
    165 			break;
    166 		/* The -d option turns off the -R option. */
    167 		case 'd':
    168 			f_listdir = 1;
    169 			f_recursive = 0;
    170 			break;
    171 		case 'f':
    172 			f_nosort = 1;
    173 			break;
    174 		case 'g':		/* Compatibility with 4.3BSD. */
    175 			break;
    176 		case 'i':
    177 			f_inode = 1;
    178 			break;
    179 		case 'o':
    180 			f_flags = 1;
    181 			break;
    182 		case 'q':
    183 			f_nonprint = 1;
    184 			break;
    185 		case 'r':
    186 			f_reversesort = 1;
    187 			break;
    188 		case 's':
    189 			f_size = 1;
    190 			break;
    191 		case 'T':
    192 			f_sectime = 1;
    193 			break;
    194 		case 't':
    195 			f_timesort = 1;
    196 			break;
    197 		case 'W':
    198 			f_whiteout = 1;
    199 			break;
    200 		default:
    201 		case '?':
    202 			usage();
    203 		}
    204 	}
    205 	argc -= optind;
    206 	argv += optind;
    207 
    208 	/*
    209 	 * If not -F, -i, -l, -s or -t options, don't require stat
    210 	 * information.
    211 	 */
    212 	if (!f_inode && !f_longform && !f_size && !f_timesort && !f_type)
    213 		fts_options |= FTS_NOSTAT;
    214 
    215 	/*
    216 	 * If not -F, -d or -l options, follow any symbolic links listed on
    217 	 * the command line.
    218 	 */
    219 	if (!f_longform && !f_listdir && !f_type)
    220 		fts_options |= FTS_COMFOLLOW;
    221 
    222 	/*
    223 	 * If -W, show whiteout entries
    224 	 */
    225 #ifdef FTS_WHITEOUT
    226 	if (f_whiteout)
    227 		fts_options |= FTS_WHITEOUT;
    228 #endif
    229 
    230 	/* If -l or -s, figure out block size. */
    231 	if (f_longform || f_size) {
    232 		(void)getbsize(&notused, &blocksize);
    233 		blocksize /= 512;
    234 	}
    235 
    236 	/* Select a sort function. */
    237 	if (f_reversesort) {
    238 		if (!f_timesort)
    239 			sortfcn = revnamecmp;
    240 		else if (f_accesstime)
    241 			sortfcn = revacccmp;
    242 		else if (f_statustime)
    243 			sortfcn = revstatcmp;
    244 		else /* Use modification time. */
    245 			sortfcn = revmodcmp;
    246 	} else {
    247 		if (!f_timesort)
    248 			sortfcn = namecmp;
    249 		else if (f_accesstime)
    250 			sortfcn = acccmp;
    251 		else if (f_statustime)
    252 			sortfcn = statcmp;
    253 		else /* Use modification time. */
    254 			sortfcn = modcmp;
    255 	}
    256 
    257 	/* Select a print function. */
    258 	if (f_singlecol)
    259 		printfcn = printscol;
    260 	else if (f_longform)
    261 		printfcn = printlong;
    262 	else
    263 		printfcn = printcol;
    264 
    265 	if (argc)
    266 		traverse(argc, argv, fts_options);
    267 	else
    268 		traverse(1, dotav, fts_options);
    269 	exit(0);
    270 }
    271 
    272 static int output;			/* If anything output. */
    273 
    274 /*
    275  * Traverse() walks the logical directory structure specified by the argv list
    276  * in the order specified by the mastercmp() comparison function.  During the
    277  * traversal it passes linked lists of structures to display() which represent
    278  * a superset (may be exact set) of the files to be displayed.
    279  */
    280 static void
    281 traverse(argc, argv, options)
    282 	int argc, options;
    283 	char *argv[];
    284 {
    285 	FTS *ftsp;
    286 	FTSENT *p, *chp;
    287 	int ch_options;
    288 
    289 	if ((ftsp =
    290 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
    291 		err(1, NULL);
    292 
    293 	display(NULL, fts_children(ftsp, 0));
    294 	if (f_listdir)
    295 		return;
    296 
    297 	/*
    298 	 * If not recursing down this tree and don't need stat info, just get
    299 	 * the names.
    300 	 */
    301 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
    302 
    303 	while ((p = fts_read(ftsp)) != NULL)
    304 		switch (p->fts_info) {
    305 		case FTS_DC:
    306 			warnx("%s: directory causes a cycle", p->fts_name);
    307 			break;
    308 		case FTS_DNR:
    309 		case FTS_ERR:
    310 			warnx("%s: %s", p->fts_name, strerror(p->fts_errno));
    311 			break;
    312 		case FTS_D:
    313 			if (p->fts_level != FTS_ROOTLEVEL &&
    314 			    p->fts_name[0] == '.' && !f_listdot)
    315 				break;
    316 
    317 			/*
    318 			 * If already output something, put out a newline as
    319 			 * a separator.  If multiple arguments, precede each
    320 			 * directory with its name.
    321 			 */
    322 			if (output)
    323 				(void)printf("\n%s:\n", p->fts_path);
    324 			else if (argc > 1) {
    325 				(void)printf("%s:\n", p->fts_path);
    326 				output = 1;
    327 			}
    328 
    329 			chp = fts_children(ftsp, ch_options);
    330 			display(p, chp);
    331 
    332 			if (!f_recursive && chp != NULL)
    333 				(void)fts_set(ftsp, p, FTS_SKIP);
    334 			break;
    335 		}
    336 	if (errno)
    337 		err(1, "fts_read");
    338 }
    339 
    340 /*
    341  * Display() takes a linked list of FTSENT structures and passes the list
    342  * along with any other necessary information to the print function.  P
    343  * points to the parent directory of the display list.
    344  */
    345 static void
    346 display(p, list)
    347 	FTSENT *p, *list;
    348 {
    349 	struct stat *sp;
    350 	DISPLAY d;
    351 	FTSENT *cur;
    352 	NAMES *np;
    353 	u_quad_t maxsize;
    354 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
    355 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
    356 	int entries, needstats;
    357 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
    358 
    359 	/*
    360 	 * If list is NULL there are two possibilities: that the parent
    361 	 * directory p has no children, or that fts_children() returned an
    362 	 * error.  We ignore the error case since it will be replicated
    363 	 * on the next call to fts_read() on the post-order visit to the
    364 	 * directory p, and will be signalled in traverse().
    365 	 */
    366 	if (list == NULL)
    367 		return;
    368 
    369 	needstats = f_inode || f_longform || f_size;
    370 	flen = 0;
    371 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
    372 	bcfile = 0;
    373 	maxuser = maxgroup = maxflags = 0;
    374 	maxsize = 0;
    375 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
    376 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
    377 			warnx("%s: %s",
    378 			    cur->fts_name, strerror(cur->fts_errno));
    379 			cur->fts_number = NO_PRINT;
    380 			continue;
    381 		}
    382 
    383 		/*
    384 		 * P is NULL if list is the argv list, to which different rules
    385 		 * apply.
    386 		 */
    387 		if (p == NULL) {
    388 			/* Directories will be displayed later. */
    389 			if (cur->fts_info == FTS_D && !f_listdir) {
    390 				cur->fts_number = NO_PRINT;
    391 				continue;
    392 			}
    393 		} else {
    394 			/* Only display dot file if -a/-A set. */
    395 			if (cur->fts_name[0] == '.' && !f_listdot) {
    396 				cur->fts_number = NO_PRINT;
    397 				continue;
    398 			}
    399 		}
    400 		if (f_nonprint)
    401 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
    402 		if (cur->fts_namelen > maxlen)
    403 			maxlen = cur->fts_namelen;
    404 		if (needstats) {
    405 			sp = cur->fts_statp;
    406 			if (sp->st_blocks > maxblock)
    407 				maxblock = sp->st_blocks;
    408 			if (sp->st_ino > maxinode)
    409 				maxinode = sp->st_ino;
    410 			if (sp->st_nlink > maxnlink)
    411 				maxnlink = sp->st_nlink;
    412 			if (sp->st_size > maxsize)
    413 				maxsize = sp->st_size;
    414 
    415 			btotal += sp->st_blocks;
    416 			if (f_longform) {
    417 				user = user_from_uid(sp->st_uid, 0);
    418 				if ((ulen = strlen(user)) > maxuser)
    419 					maxuser = ulen;
    420 				group = group_from_gid(sp->st_gid, 0);
    421 				if ((glen = strlen(group)) > maxgroup)
    422 					maxgroup = glen;
    423 				if (f_flags) {
    424 					flags =
    425 					    flags_to_string(sp->st_flags, "-");
    426 					if ((flen = strlen(flags)) > maxflags)
    427 						maxflags = flen;
    428 				} else
    429 					flen = 0;
    430 
    431 				if ((np = malloc(sizeof(NAMES) +
    432 				    ulen + glen + flen + 3)) == NULL)
    433 					err(1, NULL);
    434 
    435 				np->user = &np->data[0];
    436 				(void)strcpy(np->user, user);
    437 				np->group = &np->data[ulen + 1];
    438 				(void)strcpy(np->group, group);
    439 
    440 				if (S_ISCHR(sp->st_mode) ||
    441 				    S_ISBLK(sp->st_mode))
    442 					bcfile = 1;
    443 
    444 				if (f_flags) {
    445 					np->flags = &np->data[ulen + glen + 2];
    446 				  	(void)strcpy(np->flags, flags);
    447 				}
    448 				cur->fts_pointer = np;
    449 			}
    450 		}
    451 		++entries;
    452 	}
    453 
    454 	if (!entries)
    455 		return;
    456 
    457 	d.list = list;
    458 	d.entries = entries;
    459 	d.maxlen = maxlen;
    460 	if (needstats) {
    461 		d.bcfile = bcfile;
    462 		d.btotal = btotal;
    463 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
    464 		d.s_block = strlen(buf);
    465 		d.s_flags = maxflags;
    466 		d.s_group = maxgroup;
    467 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
    468 		d.s_inode = strlen(buf);
    469 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
    470 		d.s_nlink = strlen(buf);
    471 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
    472 		d.s_size = strlen(buf);
    473 		d.s_user = maxuser;
    474 	}
    475 
    476 	printfcn(&d);
    477 	output = 1;
    478 
    479 	if (f_longform)
    480 		for (cur = list; cur; cur = cur->fts_link)
    481 			free(cur->fts_pointer);
    482 }
    483 
    484 /*
    485  * Ordering for mastercmp:
    486  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
    487  * as larger than directories.  Within either group, use the sort function.
    488  * All other levels use the sort function.  Error entries remain unsorted.
    489  */
    490 static int
    491 mastercmp(a, b)
    492 	const FTSENT **a, **b;
    493 {
    494 	int a_info, b_info;
    495 
    496 	a_info = (*a)->fts_info;
    497 	if (a_info == FTS_ERR)
    498 		return (0);
    499 	b_info = (*b)->fts_info;
    500 	if (b_info == FTS_ERR)
    501 		return (0);
    502 
    503 	if (a_info == FTS_NS || b_info == FTS_NS)
    504 		return (namecmp(*a, *b));
    505 
    506 	if (a_info == b_info)
    507 		return (sortfcn(*a, *b));
    508 
    509 	if ((*a)->fts_level == FTS_ROOTLEVEL)
    510 		if (a_info == FTS_D)
    511 			return (1);
    512 		else if (b_info == FTS_D)
    513 			return (-1);
    514 		else
    515 			return (sortfcn(*a, *b));
    516 	else
    517 		return (sortfcn(*a, *b));
    518 }
    519