Home | History | Annotate | Line # | Download | only in ls
ls.c revision 1.10
      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.10 1994/04/04 19:29:42 chopps 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 	off_t maxsize;
    375 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
    376 	int entries, needstats;
    377 	char *user, *group, *flags, buf[20];	/* 32 bits == 10 digits */
    378 
    379 	/*
    380 	 * If list is NULL there are two possibilities: that the parent
    381 	 * directory p has no children, or that fts_children() returned an
    382 	 * error.  We ignore the error case since it will be replicated
    383 	 * on the next call to fts_read() on the post-order visit to the
    384 	 * directory p, and will be signalled in traverse().
    385 	 */
    386 	if (list == NULL)
    387 		return;
    388 
    389 	needstats = f_inode || f_longform || f_size;
    390 	flen = 0;
    391 	btotal = maxblock = maxinode = maxlen = maxnlink = 0;
    392 	bcfile = 0;
    393 	maxuser = maxgroup = maxflags = 0;
    394 	maxsize = 0;
    395 	for (cur = list, entries = 0; cur; cur = cur->fts_link) {
    396 		if (cur->fts_info == FTS_ERR || cur->fts_info == FTS_NS) {
    397 			warnx("%s: %s", cur->fts_name,
    398 			    strerror(cur->fts_errno));
    399 			cur->fts_number = NO_PRINT;
    400 			continue;
    401 		}
    402 
    403 		/*
    404 		 * P is NULL if list is the argv list, to which different rules
    405 		 * apply.
    406 		 */
    407 		if (p == NULL) {
    408 			/* Directories will be displayed later. */
    409 			if (cur->fts_info == FTS_D && !f_listdir) {
    410 				cur->fts_number = NO_PRINT;
    411 				continue;
    412 			}
    413 		} else {
    414 			/* Only display dot file if -a/-A set. */
    415 			if (cur->fts_name[0] == '.' && !f_listdot) {
    416 				cur->fts_number = NO_PRINT;
    417 				continue;
    418 			}
    419 		}
    420 		if (f_nonprint)
    421 			prcopy(cur->fts_name, cur->fts_name, cur->fts_namelen);
    422 		if (cur->fts_namelen > maxlen)
    423 			maxlen = cur->fts_namelen;
    424 		if (needstats) {
    425 			sp = cur->fts_statp;
    426 			if (sp->st_blocks > maxblock)
    427 				maxblock = sp->st_blocks;
    428 			if (sp->st_ino > maxinode)
    429 				maxinode = sp->st_ino;
    430 			if (sp->st_nlink > maxnlink)
    431 				maxnlink = sp->st_nlink;
    432 			if (sp->st_size > maxsize)
    433 				maxsize = sp->st_size;
    434 
    435 			btotal += sp->st_blocks;
    436 			if (f_longform) {
    437 				user = user_from_uid(sp->st_uid, 0);
    438 				if ((ulen = strlen(user)) > maxuser)
    439 					maxuser = ulen;
    440 				group = group_from_gid(sp->st_gid, 0);
    441 				if ((glen = strlen(group)) > maxgroup)
    442 					maxgroup = glen;
    443 				if (f_flags) {
    444 					flags = flags_from_fid(sp->st_flags);
    445 					if ((flen = strlen(flags)) > maxflags)
    446 						maxflags = flen;
    447 				} else
    448 					flen = 0;
    449 
    450 				if ((np = malloc(sizeof(NAMES) +
    451 				    ulen + glen + flen + 3)) == NULL)
    452 					err(1, NULL);
    453 
    454 				np->user = &np->data[0];
    455 				(void)strcpy(np->user, user);
    456 				np->group = &np->data[ulen + 1];
    457 				(void)strcpy(np->group, group);
    458 
    459 				if (S_ISCHR(sp->st_mode) ||
    460 				    S_ISBLK(sp->st_mode))
    461 					bcfile = 1;
    462 
    463 				if (f_flags) {
    464 					np->flags = &np->data[ulen + glen + 2];
    465 				  	(void)strcpy(np->flags, flags);
    466 				}
    467 				cur->fts_pointer = np;
    468 			}
    469 		}
    470 		++entries;
    471 	}
    472 
    473 	if (!entries)
    474 		return;
    475 
    476 	d.list = list;
    477 	d.entries = entries;
    478 	d.maxlen = maxlen;
    479 	if (needstats) {
    480 		d.bcfile = bcfile;
    481 		d.btotal = btotal;
    482 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
    483 		d.s_block = strlen(buf);
    484 		d.s_flags = maxflags;
    485 		d.s_group = maxgroup;
    486 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
    487 		d.s_inode = strlen(buf);
    488 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
    489 		d.s_nlink = strlen(buf);
    490 		(void)snprintf(buf, sizeof(buf), "%qu", maxsize);
    491 		d.s_size = strlen(buf);
    492 		d.s_user = maxuser;
    493 	}
    494 
    495 	printfcn(&d);
    496 	output = 1;
    497 
    498 	if (f_longform)
    499 		for (cur = list; cur; cur = cur->fts_link)
    500 			free(cur->fts_pointer);
    501 }
    502 
    503 /*
    504  * Ordering for mastercmp:
    505  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
    506  * as larger than directories.  Within either group, use the sort function.
    507  * All other levels use the sort function.  Error entries remain unsorted.
    508  */
    509 static int
    510 mastercmp(a, b)
    511 	const FTSENT **a, **b;
    512 {
    513 	register int a_info, b_info;
    514 
    515 	a_info = (*a)->fts_info;
    516 	if (a_info == FTS_ERR)
    517 		return (0);
    518 	b_info = (*b)->fts_info;
    519 	if (b_info == FTS_ERR)
    520 		return (0);
    521 
    522 	if (a_info == FTS_NS || b_info == FTS_NS)
    523 		return (namecmp(*a, *b));
    524 
    525 	if (a_info == b_info)
    526 		return (sortfcn(*a, *b));
    527 
    528 	if ((*a)->fts_level == FTS_ROOTLEVEL)
    529 		if (a_info == FTS_D)
    530 			return (1);
    531 		else if (b_info == FTS_D)
    532 			return (-1);
    533 		else
    534 			return (sortfcn(*a, *b));
    535 	else
    536 		return (sortfcn(*a, *b));
    537 }
    538 
    539 static char *
    540 flags_from_fid(flags)
    541 	u_long flags;
    542 {
    543 	static char buf[20];
    544 	register int comma;
    545 	register char *p;
    546 
    547 	p = buf;
    548 #ifdef notyet
    549 	if (flags & ARCHIVED) {
    550 		(void)strcpy(p, "arch");
    551 		p += sizeof("arch") - 1;
    552 		comma = 1;
    553 	} else
    554 		comma = 0;
    555 	if (flags & NODUMP) {
    556 		if (comma++)
    557 			*p++ = ',';
    558 		(void)strcpy(p, "nodump");
    559 		p += sizeof("nodump") - 1;
    560 	}
    561 	if (flags & IMMUTABLE) {
    562 		if (comma++)
    563 			*p++ = ',';
    564 		(void)strcpy(p, "nochg");
    565 		p += sizeof("nochg") - 1;
    566 	}
    567 	if (!comma)
    568 #endif
    569 		(void)strcpy(p, "-");
    570 	return (buf);
    571 }
    572