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