1 /**	$MirOS: src/bin/ls/ls.c,v 1.4 2007/02/18 03:16:45 tg Exp $ */
2 /*	$OpenBSD: ls.c,v 1.24 2005/06/15 17:47:17 millert Exp $	*/
3 /*	$NetBSD: ls.c,v 1.18 1996/07/09 09:16:29 mycroft Exp $	*/
4 
5 /*
6  * Copyright (c) 1989, 1993, 1994
7  *	The Regents of the University of California.  All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Michael Fischbein.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. 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 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <sys/ioctl.h>
40 
41 #include <dirent.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fts.h>
45 #include <grp.h>
46 #include <pwd.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 
52 #include "ls.h"
53 #include "extern.h"
54 
55 __SCCSID("@(#)ls.c	8.7 (Berkeley) 8/5/94");
56 __RCSID("$MirOS: src/bin/ls/ls.c,v 1.4 2007/02/18 03:16:45 tg Exp $");
57 
58 static void	 display(FTSENT *, FTSENT *);
59 static int	 mastercmp(const FTSENT **, const FTSENT **);
60 static void	 traverse(int, char **, int);
61 
62 static void (*printfcn)(DISPLAY *);
63 static int (*sortfcn)(const FTSENT *, const FTSENT *);
64 
65 #define	BY_NAME 0
66 #define	BY_SIZE 1
67 #define	BY_TIME	2
68 
69 long blocksize;			/* block size units */
70 int termwidth = 80;		/* default terminal width */
71 int sortkey = BY_NAME;
72 
73 /* flags */
74 int f_accesstime;		/* use time of last access */
75 int f_column;			/* columnated format */
76 int f_columnacross;		/* columnated format, sorted across */
77 int f_flags;			/* show flags associated with a file */
78 int f_inode;			/* print inode */
79 int f_listdir;			/* list actual directory, not contents */
80 int f_listdot;			/* list files beginning with . */
81 int f_longform;			/* long listing format */
82 int f_newline;			/* if precede with newline */
83 int f_nonprint;			/* show unprintables as ? */
84 int f_nosort;			/* don't sort output */
85 int f_numericonly;		/* don't expand uid to symbolic name */
86 int f_recursive;		/* ls subdirectories also */
87 int f_reversesort;		/* reverse whatever sort is used */
88 int f_sectime;			/* print the real time for all files */
89 int f_singlecol;		/* use single column output */
90 int f_size;			/* list size in short listing */
91 int f_statustime;		/* use time of last mode change */
92 int f_stream;			/* stream format */
93 int f_dirname;			/* if precede with directory name */
94 int f_type;			/* add type character for non-regular files */
95 int f_typedir;			/* add type character for directories */
96 
97 int rval;
98 
99 int
ls_main(int argc,char * argv[])100 ls_main(int argc, char *argv[])
101 {
102 	static char dot[] = ".", *dotav[] = { dot, NULL };
103 	struct winsize win;
104 	int ch, fts_options, notused;
105 	int kflag = 0;
106 	char *p;
107 
108 	/* Terminal defaults to -Cq, non-terminal defaults to -1. */
109 	if (isatty(STDOUT_FILENO)) {
110 		if ((p = getenv("COLUMNS")) != NULL)
111 			termwidth = atoi(p);
112 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
113 		    win.ws_col > 0)
114 			termwidth = win.ws_col;
115 		f_column = f_nonprint = 1;
116 	} else
117 		f_singlecol = 1;
118 
119 	/* Root is -A automatically. */
120 	if (!getuid())
121 		f_listdot = 1;
122 
123 	fts_options = FTS_PHYSICAL;
124 	while ((ch = getopt(argc, argv, "1ACFLRSTacdfgiklmnopqrstux")) != -1) {
125 		switch (ch) {
126 		/*
127 		 * The -1, -C and -l, -m and -x options all override each
128 		 * other so shell aliasing works right.
129 		 */
130 		case '1':
131 			f_singlecol = 1;
132 			f_column = f_columnacross = f_longform = f_stream = 0;
133 			break;
134 		case 'C':
135 			f_column = 1;
136 			f_longform = f_columnacross = f_singlecol = f_stream = 0;
137 			break;
138 		case 'l':
139 			f_longform = 1;
140 			f_numericonly = 0;
141 			f_column = f_columnacross = f_singlecol = f_stream = 0;
142 			break;
143 		case 'm':
144 			f_stream = 1;
145 			f_column = f_columnacross = f_singlecol = 0;
146 			f_singlecol = 0;
147 			break;
148 		case 'x':
149 			f_columnacross = 1;
150 			f_column = f_longform = f_singlecol = f_stream = 0;
151 			break;
152 		case 'n':
153 			f_longform = 1;
154 			f_numericonly = 1;
155 			f_column = f_singlecol = 0;
156 			break;
157 		/* The -c and -u options override each other. */
158 		case 'c':
159 			f_statustime = 1;
160 			f_accesstime = 0;
161 			break;
162 		case 'u':
163 			f_accesstime = 1;
164 			f_statustime = 0;
165 			break;
166 		case 'F':
167 			f_type = 1;
168 			break;
169 		case 'L':
170 			fts_options &= ~FTS_PHYSICAL;
171 			fts_options |= FTS_LOGICAL;
172 			break;
173 		case 'R':
174 			f_recursive = 1;
175 			break;
176 		case 'a':
177 			fts_options |= FTS_SEEDOT;
178 			/* FALLTHROUGH */
179 		case 'A':
180 			f_listdot = 1;
181 			break;
182 		/* The -d option turns off the -R option. */
183 		case 'd':
184 			f_listdir = 1;
185 			f_recursive = 0;
186 			break;
187 		case 'f':
188 			f_nosort = 1;
189 			break;
190 		case 'g':		/* Compatibility with 4.3BSD. */
191 			break;
192 		case 'i':
193 			f_inode = 1;
194 			break;
195 		case 'k':
196 			blocksize = 1024;
197 			kflag = 1;
198 			break;
199 		case 'o':
200 			f_flags = 1;
201 			break;
202 		case 'p':
203 			f_typedir = 1;
204 			break;
205 		case 'q':
206 			f_nonprint = 1;
207 			break;
208 		case 'r':
209 			f_reversesort = 1;
210 			break;
211 		case 'S':
212 			sortkey = BY_SIZE;
213 			break;
214 		case 's':
215 			f_size = 1;
216 			break;
217 		case 'T':
218 			f_sectime = 1;
219 			break;
220 		case 't':
221 			sortkey = BY_TIME;
222 			break;
223 		default:
224 			usage();
225 		}
226 	}
227 	argc -= optind;
228 	argv += optind;
229 
230 	/*
231 	 * If not -F, -i, -l, -p, -S, -s or -t options, don't require stat
232 	 * information.
233 	 */
234 	if (!f_longform && !f_inode && !f_size && !f_type && !f_typedir &&
235 	    sortkey == BY_NAME)
236 		fts_options |= FTS_NOSTAT;
237 
238 	/*
239 	 * If not -F, -d or -l options, follow any symbolic links listed on
240 	 * the command line.
241 	 */
242 	if (!f_longform && !f_listdir && !f_type)
243 		fts_options |= FTS_COMFOLLOW;
244 
245 	/* If -l or -s, figure out block size. */
246 	if (f_longform || f_size) {
247 		if (!kflag)
248 			(void)getbsize(&notused, &blocksize);
249 		blocksize /= 512;
250 	}
251 
252 	/* Select a sort function. */
253 	if (f_reversesort) {
254 		switch (sortkey) {
255 		case BY_NAME:
256 			sortfcn = revnamecmp;
257 			break;
258 		case BY_SIZE:
259 			sortfcn = revsizecmp;
260 			break;
261 		case BY_TIME:
262 			if (f_accesstime)
263 				sortfcn = revacccmp;
264 			else if (f_statustime)
265 				sortfcn = revstatcmp;
266 			else /* Use modification time. */
267 				sortfcn = revmodcmp;
268 			break;
269 		}
270 	} else {
271 		switch (sortkey) {
272 		case BY_NAME:
273 			sortfcn = namecmp;
274 			break;
275 		case BY_SIZE:
276 			sortfcn = sizecmp;
277 			break;
278 		case BY_TIME:
279 			if (f_accesstime)
280 				sortfcn = acccmp;
281 			else if (f_statustime)
282 				sortfcn = statcmp;
283 			else /* Use modification time. */
284 				sortfcn = modcmp;
285 			break;
286 		}
287 	}
288 
289 	/* Select a print function. */
290 	if (f_singlecol)
291 		printfcn = printscol;
292 	else if (f_columnacross)
293 		printfcn = printacol;
294 	else if (f_longform)
295 		printfcn = printlong;
296 	else if (f_stream)
297 		printfcn = printstream;
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(rval);
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
traverse(int argc,char * argv[],int options)317 traverse(int argc, char *argv[], int options)
318 {
319 	FTS *ftsp;
320 	FTSENT *p, *chp;
321 	int ch_options;
322 
323 	if ((ftsp =
324 	    fts_open(argv, options, f_nosort ? NULL : mastercmp)) == NULL)
325 		err(1, NULL);
326 
327 	display(NULL, fts_children(ftsp, 0));
328 	if (f_listdir)
329 		return;
330 
331 	/*
332 	 * If not recursing down this tree and don't need stat info, just get
333 	 * the names.
334 	 */
335 	ch_options = !f_recursive && options & FTS_NOSTAT ? FTS_NAMEONLY : 0;
336 
337 	while ((p = fts_read(ftsp)) != NULL)
338 		switch (p->fts_info) {
339 		case FTS_D:
340 			if (p->fts_name[0] == '.' &&
341 			    p->fts_level != FTS_ROOTLEVEL && !f_listdot)
342 				break;
343 
344 			/*
345 			 * If already output something, put out a newline as
346 			 * a separator.  If multiple arguments, precede each
347 			 * directory with its name.
348 			 */
349 			if (output)
350 				(void)printf("\n%s:\n", p->fts_path);
351 			else if (argc > 1) {
352 				(void)printf("%s:\n", p->fts_path);
353 				output = 1;
354 			}
355 
356 			chp = fts_children(ftsp, ch_options);
357 			display(p, chp);
358 
359 			if (!f_recursive && chp != NULL)
360 				(void)fts_set(ftsp, p, FTS_SKIP);
361 			break;
362 		case FTS_DC:
363 			warnx("%s: directory causes a cycle", p->fts_name);
364 			break;
365 		case FTS_DNR:
366 		case FTS_ERR:
367 			warnx("%s: %s", p->fts_name[0] == '\0' ? p->fts_path :
368 			    p->fts_name, strerror(p->fts_errno));
369 			rval = 1;
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
display(FTSENT * p,FTSENT * list)382 display(FTSENT *p, FTSENT *list)
383 {
384 	struct stat *sp;
385 	DISPLAY d;
386 	FTSENT *cur;
387 	NAMES *np;
388 	u_quad_t maxsize;
389 	u_long btotal, maxblock, maxinode, maxlen, maxnlink;
390 	int bcfile, flen, glen, ulen, maxflags, maxgroup, maxuser;
391 	int entries, needstats;
392 	char *user, *group, buf[21];	/* 64 bits == 20 digits */
393 	char nuser[12], ngroup[12];
394 	const char *flags = NULL;
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 != NULL; 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 			rval = 1;
418 			continue;
419 		}
420 
421 		/*
422 		 * P is NULL if list is the argv list, to which different rules
423 		 * apply.
424 		 */
425 		if (p == NULL) {
426 			/* Directories will be displayed later. */
427 			if (cur->fts_info == FTS_D && !f_listdir) {
428 				cur->fts_number = NO_PRINT;
429 				continue;
430 			}
431 		} else {
432 			/* Only display dot file if -a/-A set. */
433 			if (cur->fts_name[0] == '.' && !f_listdot) {
434 				cur->fts_number = NO_PRINT;
435 				continue;
436 			}
437 		}
438 		if (cur->fts_namelen > maxlen)
439 			maxlen = cur->fts_namelen;
440 		if (needstats) {
441 			sp = cur->fts_statp;
442 			if (sp->st_blocks > maxblock)
443 				maxblock = sp->st_blocks;
444 			if (sp->st_ino > maxinode)
445 				maxinode = sp->st_ino;
446 			if (sp->st_nlink > maxnlink)
447 				maxnlink = sp->st_nlink;
448 			if ((u_quad_t)sp->st_size > maxsize)
449 				maxsize = sp->st_size;
450 
451 			btotal += sp->st_blocks;
452 			if (f_longform) {
453 				if (f_numericonly) {
454 					snprintf(nuser, 12, "%u", sp->st_uid);
455 					snprintf(ngroup, 12, "%u", sp->st_gid);
456 					user = nuser;
457 					group = ngroup;
458 				} else {
459 					user = user_from_uid(sp->st_uid, 0);
460 					group = group_from_gid(sp->st_gid, 0);
461 				}
462 				if ((ulen = strlen(user)) > maxuser)
463 					maxuser = ulen;
464 				if ((glen = strlen(group)) > maxgroup)
465 					maxgroup = glen;
466 				if (f_flags) {
467 					flags = fflagstostr(sp->st_flags);
468 					if (*flags == '\0')
469 						flags = "-";
470 					if ((flen = strlen(flags)) > maxflags)
471 						maxflags = flen;
472 				} else
473 					flen = 0;
474 
475 				if ((np = malloc(sizeof(NAMES) +
476 				    ulen + 1 + glen + 1 + flen + 1)) == NULL)
477 					err(1, NULL);
478 
479 				np->user = &np->data[0];
480 				(void)strlcpy(np->user, user, ulen + 1);
481 				np->group = &np->data[ulen + 1];
482 				(void)strlcpy(np->group, group, glen + 1);
483 
484 				if (S_ISCHR(sp->st_mode) ||
485 				    S_ISBLK(sp->st_mode))
486 					bcfile = 1;
487 
488 				if (f_flags) {
489 					np->flags = &np->data[ulen + 1 + glen + 1];
490 				  	(void)strlcpy(np->flags, flags, flen + 1);
491 					if (*flags != '-') {
492 						union {
493 							const void *cvp;
494 							void *vp;
495 						} fnord;
496 						fnord.cvp = flags;
497 						free(fnord.vp);
498 					}
499 				}
500 				cur->fts_pointer = np;
501 			}
502 		}
503 		++entries;
504 	}
505 
506 	if (!entries)
507 		return;
508 
509 	d.list = list;
510 	d.entries = entries;
511 	d.maxlen = maxlen;
512 	if (needstats) {
513 		d.bcfile = bcfile;
514 		d.btotal = btotal;
515 		(void)snprintf(buf, sizeof(buf), "%lu", maxblock);
516 		d.s_block = strlen(buf);
517 		d.s_flags = maxflags;
518 		d.s_group = maxgroup;
519 		(void)snprintf(buf, sizeof(buf), "%lu", maxinode);
520 		d.s_inode = strlen(buf);
521 		(void)snprintf(buf, sizeof(buf), "%lu", maxnlink);
522 		d.s_nlink = strlen(buf);
523 		(void)snprintf(buf, sizeof(buf), "%llu", maxsize);
524 		d.s_size = strlen(buf);
525 		d.s_user = maxuser;
526 	}
527 
528 	printfcn(&d);
529 	output = 1;
530 
531 	if (f_longform)
532 		for (cur = list; cur != NULL; cur = cur->fts_link)
533 			free(cur->fts_pointer);
534 }
535 
536 /*
537  * Ordering for mastercmp:
538  * If ordering the argv (fts_level = FTS_ROOTLEVEL) return non-directories
539  * as larger than directories.  Within either group, use the sort function.
540  * All other levels use the sort function.  Error entries remain unsorted.
541  */
542 static int
mastercmp(const FTSENT ** a,const FTSENT ** b)543 mastercmp(const FTSENT **a, const FTSENT **b)
544 {
545 	int a_info, b_info;
546 
547 	a_info = (*a)->fts_info;
548 	if (a_info == FTS_ERR)
549 		return (0);
550 	b_info = (*b)->fts_info;
551 	if (b_info == FTS_ERR)
552 		return (0);
553 
554 	if (a_info == FTS_NS || b_info == FTS_NS) {
555 		if (b_info != FTS_NS)
556 			return (1);
557 		else if (a_info != FTS_NS)
558 			return (-1);
559 		else
560 			return (namecmp(*a, *b));
561 	}
562 
563 	if (a_info != b_info &&
564 	    (*a)->fts_level == FTS_ROOTLEVEL && !f_listdir) {
565 		if (a_info == FTS_D)
566 			return (1);
567 		if (b_info == FTS_D)
568 			return (-1);
569 	}
570 	return (sortfcn(*a, *b));
571 }
572