xref: /netbsd-src/usr.bin/stat/stat.c (revision fd5cb0acea84d278e04e640d37ca2398f894991f)
1 /*	$NetBSD: stat.c,v 1.21 2005/01/13 00:53:14 jmc Exp $ */
2 
3 /*
4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Andrew Brown.
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 NetBSD
21  *      Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 #if HAVE_NBTOOL_CONFIG_H
40 #include "nbtool_config.h"
41 #endif
42 
43 #include <sys/cdefs.h>
44 #if !defined(lint)
45 __RCSID("$NetBSD: stat.c,v 1.21 2005/01/13 00:53:14 jmc Exp $");
46 #endif
47 
48 #if ! HAVE_NBTOOL_CONFIG_H
49 #define HAVE_STRUCT_STAT_ST_FLAGS 1
50 #define HAVE_STRUCT_STAT_ST_GEN 1
51 #define HAVE_STRUCT_STAT_ST_BIRTHTIME 1
52 #define HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC 1
53 #define HAVE_STRUCT_STAT_ST_MTIMENSEC 1
54 #define HAVE_DEVNAME 1
55 #endif /* HAVE_NBTOOL_CONFIG_H */
56 
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 
60 #include <ctype.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <grp.h>
64 #include <limits.h>
65 #include <pwd.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <time.h>
70 #include <unistd.h>
71 
72 #if HAVE_STRUCT_STAT_ST_FLAGS
73 #define DEF_F "%#Xf "
74 #define RAW_F "%f "
75 #define SHELL_F " st_flags=%f"
76 #else /* HAVE_STRUCT_STAT_ST_FLAGS */
77 #define DEF_F
78 #define RAW_F
79 #define SHELL_F
80 #endif /* HAVE_STRUCT_STAT_ST_FLAGS */
81 
82 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
83 #define DEF_B "\"%SB\" "
84 #define RAW_B "%B "
85 #define SHELL_B "st_birthtime=%B "
86 #else /* HAVE_STRUCT_STAT_ST_BIRTHTIME */
87 #define DEF_B
88 #define RAW_B
89 #define SHELL_B
90 #endif /* HAVE_STRUCT_STAT_ST_BIRTHTIME */
91 
92 #if HAVE_STRUCT_STAT_ST_ATIM
93 #define st_atimespec st_atim
94 #define st_ctimespec st_ctim
95 #define st_mtimespec st_mtim
96 #endif /* HAVE_STRUCT_STAT_ST_ATIM */
97 
98 #define DEF_FORMAT \
99 	"%d %i %Sp %l %Su %Sg %r %z \"%Sa\" \"%Sm\" \"%Sc\" " DEF_B \
100 	"%k %b " DEF_F "%N"
101 #define RAW_FORMAT	"%d %i %#p %l %u %g %r %z %a %m %c " RAW_B \
102 	"%k %b " RAW_F "%N"
103 #define LS_FORMAT	"%Sp %l %Su %Sg %Z %Sm %N%SY"
104 #define LSF_FORMAT	"%Sp %l %Su %Sg %Z %Sm %N%T%SY"
105 #define SHELL_FORMAT \
106 	"st_dev=%d st_ino=%i st_mode=%#p st_nlink=%l " \
107 	"st_uid=%u st_gid=%g st_rdev=%r st_size=%z " \
108 	"st_atime=%a st_mtime=%m st_ctime=%c " SHELL_B \
109 	"st_blksize=%k st_blocks=%b" SHELL_F
110 #define LINUX_FORMAT \
111 	"  File: \"%N\"%n" \
112 	"  Size: %-11z  FileType: %HT%n" \
113 	"  Mode: (%04OLp/%.10Sp)         Uid: (%5u/%8Su)  Gid: (%5g/%8Sg)%n" \
114 	"Device: %Hd,%Ld   Inode: %i    Links: %l%n" \
115 	"Access: %Sa%n" \
116 	"Modify: %Sm%n" \
117 	"Change: %Sc"
118 
119 #define TIME_FORMAT	"%b %e %T %Y"
120 
121 #define FLAG_POUND	0x01
122 #define FLAG_SPACE	0x02
123 #define FLAG_PLUS	0x04
124 #define FLAG_ZERO	0x08
125 #define FLAG_MINUS	0x10
126 
127 /*
128  * These format characters must all be unique, except the magic one.
129  */
130 #define FMT_MAGIC	'%'
131 #define FMT_DOT		'.'
132 
133 #define SIMPLE_NEWLINE	'n'
134 #define SIMPLE_TAB	't'
135 #define SIMPLE_PERCENT	'%'
136 #define SIMPLE_NUMBER	'@'
137 
138 #define FMT_POUND	'#'
139 #define FMT_SPACE	' '
140 #define FMT_PLUS	'+'
141 #define FMT_ZERO	'0'
142 #define FMT_MINUS	'-'
143 
144 #define FMT_DECIMAL 	'D'
145 #define FMT_OCTAL 	'O'
146 #define FMT_UNSIGNED 	'U'
147 #define FMT_HEX 	'X'
148 #define FMT_FLOAT 	'F'
149 #define FMT_STRING 	'S'
150 
151 #define FMTF_DECIMAL	0x01
152 #define FMTF_OCTAL	0x02
153 #define FMTF_UNSIGNED	0x04
154 #define FMTF_HEX	0x08
155 #define FMTF_FLOAT	0x10
156 #define FMTF_STRING	0x20
157 
158 #define HIGH_PIECE	'H'
159 #define MIDDLE_PIECE	'M'
160 #define LOW_PIECE	'L'
161 
162 #define SHOW_st_dev	'd'
163 #define SHOW_st_ino	'i'
164 #define SHOW_st_mode	'p'
165 #define SHOW_st_nlink	'l'
166 #define SHOW_st_uid	'u'
167 #define SHOW_st_gid	'g'
168 #define SHOW_st_rdev	'r'
169 #define SHOW_st_atime	'a'
170 #define SHOW_st_mtime	'm'
171 #define SHOW_st_ctime	'c'
172 #define SHOW_st_btime	'B'
173 #define SHOW_st_size	'z'
174 #define SHOW_st_blocks	'b'
175 #define SHOW_st_blksize	'k'
176 #define SHOW_st_flags	'f'
177 #define SHOW_st_gen	'v'
178 #define SHOW_symlink	'Y'
179 #define SHOW_filetype	'T'
180 #define SHOW_filename	'N'
181 #define SHOW_sizerdev	'Z'
182 
183 void	usage(const char *);
184 void	output(const struct stat *, const char *,
185 	    const char *, int, int, int);
186 int	format1(const struct stat *,	/* stat info */
187 	    const char *,		/* the file name */
188 	    const char *, int,		/* the format string itself */
189 	    char *, size_t,		/* a place to put the output */
190 	    int, int, int, int,		/* the parsed format */
191 	    int, int);
192 
193 char *timefmt;
194 int linkfail;
195 
196 #define addchar(s, c, nl) \
197 	do { \
198 		(void)fputc((c), (s)); \
199 		(*nl) = ((c) == '\n'); \
200 	} while (0/*CONSTCOND*/)
201 
202 int
203 main(int argc, char *argv[])
204 {
205 	struct stat st;
206 	int ch, rc, errs, am_readlink;
207 	int lsF, fmtchar, usestat, fn, nonl, quiet;
208 	char *statfmt, *options, *synopsis;
209 
210 	am_readlink = 0;
211 	lsF = 0;
212 	fmtchar = '\0';
213 	usestat = 0;
214 	nonl = 0;
215 	quiet = 0;
216 	linkfail = 0;
217 	statfmt = NULL;
218 	timefmt = NULL;
219 
220 	if (strcmp(getprogname(), "readlink") == 0) {
221 		am_readlink = 1;
222 		options = "n";
223 		synopsis = "[-n] [file ...]";
224 		statfmt = "%Y";
225 		fmtchar = 'f';
226 		quiet = 1;
227 	} else {
228 		options = "f:FlLnqrst:x";
229 		synopsis = "[-FlLnqrsx] [-f format] [-t timefmt] [file ...]";
230 	}
231 
232 	while ((ch = getopt(argc, argv, options)) != -1)
233 		switch (ch) {
234 		case 'F':
235 			lsF = 1;
236 			break;
237 		case 'L':
238 			usestat = 1;
239 			break;
240 		case 'n':
241 			nonl = 1;
242 			break;
243 		case 'q':
244 			quiet = 1;
245 			break;
246 		case 'f':
247 			statfmt = optarg;
248 			/* FALLTHROUGH */
249 		case 'l':
250 		case 'r':
251 		case 's':
252 		case 'x':
253 			if (fmtchar != 0)
254 				errx(1, "can't use format '%c' with '%c'",
255 				    fmtchar, ch);
256 			fmtchar = ch;
257 			break;
258 		case 't':
259 			timefmt = optarg;
260 			break;
261 		default:
262 			usage(synopsis);
263 		}
264 
265 	argc -= optind;
266 	argv += optind;
267 	fn = 1;
268 
269 	if (fmtchar == '\0') {
270 		if (lsF)
271 			fmtchar = 'l';
272 		else {
273 			fmtchar = 'f';
274 			statfmt = DEF_FORMAT;
275 		}
276 	}
277 
278 	if (lsF && fmtchar != 'l')
279 		errx(1, "can't use format '%c' with -F", fmtchar);
280 
281 	switch (fmtchar) {
282 	case 'f':
283 		/* statfmt already set */
284 		break;
285 	case 'l':
286 		statfmt = lsF ? LSF_FORMAT : LS_FORMAT;
287 		break;
288 	case 'r':
289 		statfmt = RAW_FORMAT;
290 		break;
291 	case 's':
292 		statfmt = SHELL_FORMAT;
293 		break;
294 	case 'x':
295 		statfmt = LINUX_FORMAT;
296 		if (timefmt == NULL)
297 			timefmt = "%c";
298 		break;
299 	default:
300 		usage(synopsis);
301 		/*NOTREACHED*/
302 	}
303 
304 	if (timefmt == NULL)
305 		timefmt = TIME_FORMAT;
306 
307 	errs = 0;
308 	do {
309 		if (argc == 0)
310 			rc = fstat(STDIN_FILENO, &st);
311 		else if (usestat) {
312 			/*
313 			 * Try stat() and if it fails, fall back to
314 			 * lstat() just in case we're examining a
315 			 * broken symlink.
316 			 */
317 			if ((rc = stat(argv[0], &st)) == -1 &&
318 			    errno == ENOENT &&
319 			    (rc = lstat(argv[0], &st)) == -1)
320 				errno = ENOENT;
321 		}
322 		else
323 			rc = lstat(argv[0], &st);
324 
325 		if (rc == -1) {
326 			errs = 1;
327 			linkfail = 1;
328 			if (!quiet)
329 				warn("%s: %s",
330 				    argc == 0 ? "(stdin)" : argv[0],
331 				    usestat ? "stat" : "lstat");
332 		}
333 		else
334 			output(&st, argv[0], statfmt, fn, nonl, quiet);
335 
336 		argv++;
337 		argc--;
338 		fn++;
339 	} while (argc > 0);
340 
341 	return (am_readlink ? linkfail : errs);
342 }
343 
344 void
345 usage(const char *synopsis)
346 {
347 
348 	(void)fprintf(stderr, "usage: %s %s\n", getprogname(), synopsis);
349 	exit(1);
350 }
351 
352 /*
353  * Parses a format string.
354  */
355 void
356 output(const struct stat *st, const char *file,
357     const char *statfmt, int fn, int nonl, int quiet)
358 {
359 	int flags, size, prec, ofmt, hilo, what;
360 	char buf[PATH_MAX];
361 	const char *subfmt;
362 	int nl, t, i;
363 
364 	nl = 1;
365 	while (*statfmt != '\0') {
366 
367 		/*
368 		 * Non-format characters go straight out.
369 		 */
370 		if (*statfmt != FMT_MAGIC) {
371 			addchar(stdout, *statfmt, &nl);
372 			statfmt++;
373 			continue;
374 		}
375 
376 		/*
377 		 * The current format "substring" starts here,
378 		 * and then we skip the magic.
379 		 */
380 		subfmt = statfmt;
381 		statfmt++;
382 
383 		/*
384 		 * Some simple one-character "formats".
385 		 */
386 		switch (*statfmt) {
387 		case SIMPLE_NEWLINE:
388 			addchar(stdout, '\n', &nl);
389 			statfmt++;
390 			continue;
391 		case SIMPLE_TAB:
392 			addchar(stdout, '\t', &nl);
393 			statfmt++;
394 			continue;
395 		case SIMPLE_PERCENT:
396 			addchar(stdout, '%', &nl);
397 			statfmt++;
398 			continue;
399 		case SIMPLE_NUMBER: {
400 			char num[12], *p;
401 
402 			snprintf(num, sizeof(num), "%d", fn);
403 			for (p = &num[0]; *p; p++)
404 				addchar(stdout, *p, &nl);
405 			statfmt++;
406 			continue;
407 		}
408 		}
409 
410 		/*
411 		 * This must be an actual format string.  Format strings are
412 		 * similar to printf(3) formats up to a point, and are of
413 		 * the form:
414 		 *
415 		 *	%	required start of format
416 		 *	[-# +0]	opt. format characters
417 		 *	size	opt. field width
418 		 *	.	opt. decimal separator, followed by
419 		 *	prec	opt. precision
420 		 *	fmt	opt. output specifier (string, numeric, etc.)
421 		 *	sub	opt. sub field specifier (high, middle, low)
422 		 *	datum	required field specifier (size, mode, etc)
423 		 *
424 		 * Only the % and the datum selector are required.  All data
425 		 * have reasonable default output forms.  The "sub" specifier
426 		 * only applies to certain data (mode, dev, rdev, filetype).
427 		 * The symlink output defaults to STRING, yet will only emit
428 		 * the leading " -> " if STRING is explicitly specified.  The
429 		 * sizerdev datum will generate rdev output for character or
430 		 * block devices, and size output for all others.
431 		 */
432 		flags = 0;
433 		do {
434 			if      (*statfmt == FMT_POUND)
435 				flags |= FLAG_POUND;
436 			else if (*statfmt == FMT_SPACE)
437 				flags |= FLAG_SPACE;
438 			else if (*statfmt == FMT_PLUS)
439 				flags |= FLAG_PLUS;
440 			else if (*statfmt == FMT_ZERO)
441 				flags |= FLAG_ZERO;
442 			else if (*statfmt == FMT_MINUS)
443 				flags |= FLAG_MINUS;
444 			else
445 				break;
446 			statfmt++;
447 		} while (1/*CONSTCOND*/);
448 
449 		size = -1;
450 		if (isdigit((unsigned)*statfmt)) {
451 			size = 0;
452 			while (isdigit((unsigned)*statfmt)) {
453 				size = (size * 10) + (*statfmt - '0');
454 				statfmt++;
455 				if (size < 0)
456 					goto badfmt;
457 			}
458 		}
459 
460 		prec = -1;
461 		if (*statfmt == FMT_DOT) {
462 			statfmt++;
463 
464 			prec = 0;
465 			while (isdigit((unsigned)*statfmt)) {
466 				prec = (prec * 10) + (*statfmt - '0');
467 				statfmt++;
468 				if (prec < 0)
469 					goto badfmt;
470 			}
471 		}
472 
473 #define fmtcase(x, y)		case (y): (x) = (y); statfmt++; break
474 #define fmtcasef(x, y, z)	case (y): (x) = (z); statfmt++; break
475 		switch (*statfmt) {
476 			fmtcasef(ofmt, FMT_DECIMAL,	FMTF_DECIMAL);
477 			fmtcasef(ofmt, FMT_OCTAL,	FMTF_OCTAL);
478 			fmtcasef(ofmt, FMT_UNSIGNED,	FMTF_UNSIGNED);
479 			fmtcasef(ofmt, FMT_HEX,		FMTF_HEX);
480 			fmtcasef(ofmt, FMT_FLOAT,	FMTF_FLOAT);
481 			fmtcasef(ofmt, FMT_STRING,	FMTF_STRING);
482 		default:
483 			ofmt = 0;
484 			break;
485 		}
486 
487 		switch (*statfmt) {
488 			fmtcase(hilo, HIGH_PIECE);
489 			fmtcase(hilo, MIDDLE_PIECE);
490 			fmtcase(hilo, LOW_PIECE);
491 		default:
492 			hilo = 0;
493 			break;
494 		}
495 
496 		switch (*statfmt) {
497 			fmtcase(what, SHOW_st_dev);
498 			fmtcase(what, SHOW_st_ino);
499 			fmtcase(what, SHOW_st_mode);
500 			fmtcase(what, SHOW_st_nlink);
501 			fmtcase(what, SHOW_st_uid);
502 			fmtcase(what, SHOW_st_gid);
503 			fmtcase(what, SHOW_st_rdev);
504 			fmtcase(what, SHOW_st_atime);
505 			fmtcase(what, SHOW_st_mtime);
506 			fmtcase(what, SHOW_st_ctime);
507 			fmtcase(what, SHOW_st_btime);
508 			fmtcase(what, SHOW_st_size);
509 			fmtcase(what, SHOW_st_blocks);
510 			fmtcase(what, SHOW_st_blksize);
511 			fmtcase(what, SHOW_st_flags);
512 			fmtcase(what, SHOW_st_gen);
513 			fmtcase(what, SHOW_symlink);
514 			fmtcase(what, SHOW_filetype);
515 			fmtcase(what, SHOW_filename);
516 			fmtcase(what, SHOW_sizerdev);
517 		default:
518 			goto badfmt;
519 		}
520 #undef fmtcasef
521 #undef fmtcase
522 
523 		t = format1(st,
524 		     file,
525 		     subfmt, statfmt - subfmt,
526 		     buf, sizeof(buf),
527 		     flags, size, prec, ofmt, hilo, what);
528 
529 		for (i = 0; i < t && i < sizeof(buf); i++)
530 			addchar(stdout, buf[i], &nl);
531 
532 		continue;
533 
534 	badfmt:
535 		errx(1, "%.*s: bad format",
536 		    (int)(statfmt - subfmt + 1), subfmt);
537 	}
538 
539 	if (!nl && !nonl)
540 		(void)fputc('\n', stdout);
541 	(void)fflush(stdout);
542 }
543 
544 /*
545  * Arranges output according to a single parsed format substring.
546  */
547 int
548 format1(const struct stat *st,
549     const char *file,
550     const char *fmt, int flen,
551     char *buf, size_t blen,
552     int flags, int size, int prec, int ofmt,
553     int hilo, int what)
554 {
555 	u_int64_t data;
556 	char *sdata, lfmt[24], tmp[20];
557 	char smode[12], sid[12], path[PATH_MAX + 4];
558 	struct passwd *pw;
559 	struct group *gr;
560 	struct tm *tm;
561 	time_t secs;
562 	long nsecs;
563 	int l, small, formats, gottime;
564 
565 	formats = 0;
566 	small = 0;
567 	gottime = 0;
568 	secs = 0;
569 	nsecs = 0;
570 
571 	/*
572 	 * First, pick out the data and tweak it based on hilo or
573 	 * specified output format (symlink output only).
574 	 */
575 	switch (what) {
576 	case SHOW_st_dev:
577 	case SHOW_st_rdev:
578 		small = (sizeof(st->st_dev) == 4);
579 		data = (what == SHOW_st_dev) ? st->st_dev : st->st_rdev;
580 #if HAVE_DEVNAME
581 		sdata = (what == SHOW_st_dev) ?
582 		    devname(st->st_dev, S_IFBLK) :
583 		    devname(st->st_rdev,
584 		    S_ISCHR(st->st_mode) ? S_IFCHR :
585 		    S_ISBLK(st->st_mode) ? S_IFBLK :
586 		    0U);
587 		if (sdata == NULL)
588 			sdata = "???";
589 #endif /* HAVE_DEVNAME */
590 		if (hilo == HIGH_PIECE) {
591 			data = major(data);
592 			hilo = 0;
593 		}
594 		else if (hilo == LOW_PIECE) {
595 			data = minor((unsigned)data);
596 			hilo = 0;
597 		}
598 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
599 #if HAVE_DEVNAME
600 		    FMTF_STRING;
601 #else /* HAVE_DEVNAME */
602 		    0;
603 #endif /* HAVE_DEVNAME */
604 		if (ofmt == 0)
605 			ofmt = FMTF_UNSIGNED;
606 		break;
607 	case SHOW_st_ino:
608 		small = (sizeof(st->st_ino) == 4);
609 		data = st->st_ino;
610 		sdata = NULL;
611 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
612 		if (ofmt == 0)
613 			ofmt = FMTF_UNSIGNED;
614 		break;
615 	case SHOW_st_mode:
616 		small = (sizeof(st->st_mode) == 4);
617 		data = st->st_mode;
618 		strmode(st->st_mode, smode);
619 		sdata = smode;
620 		l = strlen(sdata);
621 		if (sdata[l - 1] == ' ')
622 			sdata[--l] = '\0';
623 		if (hilo == HIGH_PIECE) {
624 			data >>= 12;
625 			sdata += 1;
626 			sdata[3] = '\0';
627 			hilo = 0;
628 		}
629 		else if (hilo == MIDDLE_PIECE) {
630 			data = (data >> 9) & 07;
631 			sdata += 4;
632 			sdata[3] = '\0';
633 			hilo = 0;
634 		}
635 		else if (hilo == LOW_PIECE) {
636 			data &= 0777;
637 			sdata += 7;
638 			sdata[3] = '\0';
639 			hilo = 0;
640 		}
641 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
642 		    FMTF_STRING;
643 		if (ofmt == 0)
644 			ofmt = FMTF_OCTAL;
645 		break;
646 	case SHOW_st_nlink:
647 		small = (sizeof(st->st_dev) == 4);
648 		data = st->st_nlink;
649 		sdata = NULL;
650 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
651 		if (ofmt == 0)
652 			ofmt = FMTF_UNSIGNED;
653 		break;
654 	case SHOW_st_uid:
655 		small = (sizeof(st->st_uid) == 4);
656 		data = st->st_uid;
657 		if ((pw = getpwuid(st->st_uid)) != NULL)
658 			sdata = pw->pw_name;
659 		else {
660 			snprintf(sid, sizeof(sid), "(%ld)", (long)st->st_uid);
661 			sdata = sid;
662 		}
663 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
664 		    FMTF_STRING;
665 		if (ofmt == 0)
666 			ofmt = FMTF_UNSIGNED;
667 		break;
668 	case SHOW_st_gid:
669 		small = (sizeof(st->st_gid) == 4);
670 		data = st->st_gid;
671 		if ((gr = getgrgid(st->st_gid)) != NULL)
672 			sdata = gr->gr_name;
673 		else {
674 			snprintf(sid, sizeof(sid), "(%ld)", (long)st->st_gid);
675 			sdata = sid;
676 		}
677 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
678 		    FMTF_STRING;
679 		if (ofmt == 0)
680 			ofmt = FMTF_UNSIGNED;
681 		break;
682 	case SHOW_st_atime:
683 		gottime = 1;
684 		secs = st->st_atime;
685 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
686 		nsecs = st->st_atimensec;
687 #endif
688 		/* FALLTHROUGH */
689 	case SHOW_st_mtime:
690 		if (!gottime) {
691 			gottime = 1;
692 			secs = st->st_mtime;
693 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
694 			nsecs = st->st_mtimensec;
695 #endif
696 		}
697 		/* FALLTHROUGH */
698 	case SHOW_st_ctime:
699 		if (!gottime) {
700 			gottime = 1;
701 			secs = st->st_ctime;
702 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
703 			nsecs = st->st_ctimensec;
704 #endif
705 		}
706 		/* FALLTHROUGH */
707 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
708 	case SHOW_st_btime:
709 		if (!gottime) {
710 			gottime = 1;
711 			secs = st->st_birthtime;
712 #if HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC
713 			nsecs = st->st_birthtimensec;
714 #endif /* HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC */
715 		}
716 #endif /* HAVE_STRUCT_STAT_ST_BIRTHTIME */
717 		small = (sizeof(secs) == 4);
718 		data = secs;
719 		small = 1;
720 		tm = localtime(&secs);
721 		(void)strftime(path, sizeof(path), timefmt, tm);
722 		sdata = path;
723 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX |
724 		    FMTF_FLOAT | FMTF_STRING;
725 		if (ofmt == 0)
726 			ofmt = FMTF_DECIMAL;
727 		break;
728 	case SHOW_st_size:
729 		small = (sizeof(st->st_size) == 4);
730 		data = st->st_size;
731 		sdata = NULL;
732 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
733 		if (ofmt == 0)
734 			ofmt = FMTF_UNSIGNED;
735 		break;
736 	case SHOW_st_blocks:
737 		small = (sizeof(st->st_blocks) == 4);
738 		data = st->st_blocks;
739 		sdata = NULL;
740 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
741 		if (ofmt == 0)
742 			ofmt = FMTF_UNSIGNED;
743 		break;
744 	case SHOW_st_blksize:
745 		small = (sizeof(st->st_blksize) == 4);
746 		data = st->st_blksize;
747 		sdata = NULL;
748 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
749 		if (ofmt == 0)
750 			ofmt = FMTF_UNSIGNED;
751 		break;
752 #if HAVE_STRUCT_STAT_ST_FLAGS
753 	case SHOW_st_flags:
754 		small = (sizeof(st->st_flags) == 4);
755 		data = st->st_flags;
756 		sdata = NULL;
757 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
758 		if (ofmt == 0)
759 			ofmt = FMTF_UNSIGNED;
760 		break;
761 #endif /* HAVE_STRUCT_STAT_ST_FLAGS */
762 #if HAVE_STRUCT_STAT_ST_GEN
763 	case SHOW_st_gen:
764 		small = (sizeof(st->st_gen) == 4);
765 		data = st->st_gen;
766 		sdata = NULL;
767 		formats = FMTF_DECIMAL | FMTF_OCTAL | FMTF_UNSIGNED | FMTF_HEX;
768 		if (ofmt == 0)
769 			ofmt = FMTF_UNSIGNED;
770 		break;
771 #endif /* HAVE_STRUCT_STAT_ST_GEN */
772 	case SHOW_symlink:
773 		small = 0;
774 		data = 0;
775 		if (S_ISLNK(st->st_mode)) {
776 			snprintf(path, sizeof(path), " -> ");
777 			l = readlink(file, path + 4, sizeof(path) - 4 - 1);
778 			if (l == -1) {
779 				linkfail = 1;
780 				l = 0;
781 				path[0] = '\0';
782 			}
783 			path[l + 4] = '\0';
784 			sdata = path + (ofmt == FMTF_STRING ? 0 : 4);
785 		}
786 		else {
787 			linkfail = 1;
788 			sdata = "";
789 		}
790 		formats = FMTF_STRING;
791 		if (ofmt == 0)
792 			ofmt = FMTF_STRING;
793 		break;
794 	case SHOW_filetype:
795 		small = 0;
796 		data = 0;
797 		sdata = smode;
798 		sdata[0] = '\0';
799 		if (hilo == 0 || hilo == LOW_PIECE) {
800 			switch (st->st_mode & S_IFMT) {
801 			case S_IFIFO:	(void)strcat(sdata, "|");	break;
802 			case S_IFDIR:	(void)strcat(sdata, "/");	break;
803 			case S_IFREG:
804 				if (st->st_mode &
805 				    (S_IXUSR | S_IXGRP | S_IXOTH))
806 					(void)strcat(sdata, "*");
807 				break;
808 			case S_IFLNK:	(void)strcat(sdata, "@");	break;
809 #ifdef S_IFSOCK
810 			case S_IFSOCK:	(void)strcat(sdata, "=");	break;
811 #endif
812 #ifdef S_IFWHT
813 			case S_IFWHT:	(void)strcat(sdata, "%");	break;
814 #endif /* S_IFWHT */
815 #ifdef S_IFDOOR
816 			case S_IFDOOR:	(void)strcat(sdata, ">");	break;
817 #endif /* S_IFDOOR */
818 			}
819 			hilo = 0;
820 		}
821 		else if (hilo == HIGH_PIECE) {
822 			switch (st->st_mode & S_IFMT) {
823 			case S_IFIFO:	sdata = "Fifo File";		break;
824 			case S_IFCHR:	sdata = "Character Device";	break;
825 			case S_IFDIR:	sdata = "Directory";		break;
826 			case S_IFBLK:	sdata = "Block Device";		break;
827 			case S_IFREG:	sdata = "Regular File";		break;
828 			case S_IFLNK:	sdata = "Symbolic Link";	break;
829 #ifdef S_IFSOCK
830 			case S_IFSOCK:	sdata = "Socket";		break;
831 #endif
832 #ifdef S_IFWHT
833 			case S_IFWHT:	sdata = "Whiteout File";	break;
834 #endif /* S_IFWHT */
835 #ifdef S_IFDOOR
836 			case S_IFDOOR:	sdata = "Door";			break;
837 #endif /* S_IFDOOR */
838 			default:	sdata = "???";			break;
839 			}
840 			hilo = 0;
841 		}
842 		formats = FMTF_STRING;
843 		if (ofmt == 0)
844 			ofmt = FMTF_STRING;
845 		break;
846 	case SHOW_filename:
847 		small = 0;
848 		data = 0;
849 		if (file == NULL) {
850 			(void)strncpy(path, "(stdin)", sizeof(path));
851 			if (hilo == HIGH_PIECE || hilo == LOW_PIECE)
852 				hilo = 0;
853 		}
854 		else if (hilo == 0)
855 			(void)strncpy(path, file, sizeof(path));
856 		else {
857 			char *s;
858 			(void)strncpy(path, file, sizeof(path));
859 			s = strrchr(path, '/');
860 			if (s != NULL) {
861 				/* trim off trailing /'s */
862 				while (s != path &&
863 				    s[0] == '/' && s[1] == '\0')
864 					*s-- = '\0';
865 				s = strrchr(path, '/');
866 			}
867 			if (hilo == HIGH_PIECE) {
868 				if (s == NULL)
869 					(void)strncpy(path, ".", sizeof(path));
870 				else {
871 					while (s != path && s[0] == '/')
872 						*s-- = '\0';
873 				}
874 				hilo = 0;
875 			}
876 			else if (hilo == LOW_PIECE) {
877 				if (s != NULL && s[1] != '\0')
878 					(void)strncpy(path, s + 1,
879 						      sizeof(path));
880 				hilo = 0;
881 			}
882 		}
883 		sdata = path;
884 		formats = FMTF_STRING;
885 		if (ofmt == 0)
886 			ofmt = FMTF_STRING;
887 		break;
888 	case SHOW_sizerdev:
889 		if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode)) {
890 			char majdev[20], mindev[20];
891 			int l1, l2;
892 
893 			l1 = format1(st,
894 			    file,
895 			    fmt, flen,
896 			    majdev, sizeof(majdev),
897 			    flags, size, prec,
898 			    ofmt, HIGH_PIECE, SHOW_st_rdev);
899 			l2 = format1(st,
900 			    file,
901 			    fmt, flen,
902 			    mindev, sizeof(mindev),
903 			    flags, size, prec,
904 			    ofmt, LOW_PIECE, SHOW_st_rdev);
905 			return (snprintf(buf, blen, "%.*s,%.*s",
906 			    l1, majdev, l2, mindev));
907 		}
908 		else {
909 			return (format1(st,
910 			    file,
911 			    fmt, flen,
912 			    buf, blen,
913 			    flags, size, prec,
914 			    ofmt, 0, SHOW_st_size));
915 		}
916 		/*NOTREACHED*/
917 	default:
918 		errx(1, "%.*s: bad format", (int)flen, fmt);
919 	}
920 
921 	/*
922 	 * If a subdatum was specified but not supported, or an output
923 	 * format was selected that is not supported, that's an error.
924 	 */
925 	if (hilo != 0 || (ofmt & formats) == 0)
926 		errx(1, "%.*s: bad format", (int)flen, fmt);
927 
928 	/*
929 	 * Assemble the format string for passing to printf(3).
930 	 */
931 	lfmt[0] = '\0';
932 	(void)strcat(lfmt, "%");
933 	if (flags & FLAG_POUND)
934 		(void)strcat(lfmt, "#");
935 	if (flags & FLAG_SPACE)
936 		(void)strcat(lfmt, " ");
937 	if (flags & FLAG_PLUS)
938 		(void)strcat(lfmt, "+");
939 	if (flags & FLAG_MINUS)
940 		(void)strcat(lfmt, "-");
941 	if (flags & FLAG_ZERO)
942 		(void)strcat(lfmt, "0");
943 
944 	/*
945 	 * Only the timespecs support the FLOAT output format, and that
946 	 * requires work that differs from the other formats.
947 	 */
948 	if (ofmt == FMTF_FLOAT) {
949 		/*
950 		 * Nothing after the decimal point, so just print seconds.
951 		 */
952 		if (prec == 0) {
953 			if (size != -1) {
954 				(void)snprintf(tmp, sizeof(tmp), "%d", size);
955 				(void)strcat(lfmt, tmp);
956 			}
957 			(void)strcat(lfmt, "d");
958 			return (snprintf(buf, blen, lfmt, secs));
959 		}
960 
961 		/*
962 		 * Unspecified precision gets all the precision we have:
963 		 * 9 digits.
964 		 */
965 		if (prec == -1)
966 			prec = 9;
967 
968 		/*
969 		 * Adjust the size for the decimal point and the digits
970 		 * that will follow.
971 		 */
972 		size -= prec + 1;
973 
974 		/*
975 		 * Any leftover size that's legitimate will be used.
976 		 */
977 		if (size > 0) {
978 			(void)snprintf(tmp, sizeof(tmp), "%d", size);
979 			(void)strcat(lfmt, tmp);
980 		}
981 		(void)strcat(lfmt, "d");
982 
983 		/*
984 		 * The stuff after the decimal point always needs zero
985 		 * filling.
986 		 */
987 		(void)strcat(lfmt, ".%0");
988 
989 		/*
990 		 * We can "print" at most nine digits of precision.  The
991 		 * rest we will pad on at the end.
992 		 */
993 		(void)snprintf(tmp, sizeof(tmp), "%dd", prec > 9 ? 9 : prec);
994 		(void)strcat(lfmt, tmp);
995 
996 		/*
997 		 * For precision of less that nine digits, trim off the
998 		 * less significant figures.
999 		 */
1000 		for (; prec < 9; prec++)
1001 			nsecs /= 10;
1002 
1003 		/*
1004 		 * Use the format, and then tack on any zeroes that
1005 		 * might be required to make up the requested precision.
1006 		 */
1007 		l = snprintf(buf, blen, lfmt, secs, nsecs);
1008 		for (; prec > 9 && l < blen; prec--, l++)
1009 			(void)strcat(buf, "0");
1010 		return (l);
1011 	}
1012 
1013 	/*
1014 	 * Add on size and precision, if specified, to the format.
1015 	 */
1016 	if (size != -1) {
1017 		(void)snprintf(tmp, sizeof(tmp), "%d", size);
1018 		(void)strcat(lfmt, tmp);
1019 	}
1020 	if (prec != -1) {
1021 		(void)snprintf(tmp, sizeof(tmp), ".%d", prec);
1022 		(void)strcat(lfmt, tmp);
1023 	}
1024 
1025 	/*
1026 	 * String output uses the temporary sdata.
1027 	 */
1028 	if (ofmt == FMTF_STRING) {
1029 		if (sdata == NULL)
1030 			errx(1, "%.*s: bad format", (int)flen, fmt);
1031 		(void)strcat(lfmt, "s");
1032 		return (snprintf(buf, blen, lfmt, sdata));
1033 	}
1034 
1035 	/*
1036 	 * Ensure that sign extension does not cause bad looking output
1037 	 * for some forms.
1038 	 */
1039 	if (small && ofmt != FMTF_DECIMAL)
1040 		data = (u_int32_t)data;
1041 
1042 	/*
1043 	 * The four "numeric" output forms.
1044 	 */
1045 	(void)strcat(lfmt, "ll");
1046 	switch (ofmt) {
1047 	case FMTF_DECIMAL:	(void)strcat(lfmt, "d");	break;
1048 	case FMTF_OCTAL:		(void)strcat(lfmt, "o");	break;
1049 	case FMTF_UNSIGNED:	(void)strcat(lfmt, "u");	break;
1050 	case FMTF_HEX:		(void)strcat(lfmt, "x");	break;
1051 	}
1052 
1053 	return (snprintf(buf, blen, lfmt, data));
1054 }
1055