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