tests: skip the misc/stdbuf test if stdbuf was not built
[coreutils.git] / src / stat.c
blob63c5911c42f40319a4d08dbb92142259a083b501
1 /* stat.c -- display file or file system status
2 Copyright (C) 2001-2009 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 Written by Michael Meskes. */
19 #include <config.h>
21 /* Keep this conditional in sync with the similar conditional in
22 ../m4/stat-prog.m4. */
23 #if (STAT_STATVFS \
24 && (HAVE_STRUCT_STATVFS_F_BASETYPE || HAVE_STRUCT_STATVFS_F_FSTYPENAME \
25 || (! HAVE_STRUCT_STATFS_F_FSTYPENAME && HAVE_STRUCT_STATVFS_F_TYPE)))
26 # define USE_STATVFS 1
27 #else
28 # define USE_STATVFS 0
29 #endif
31 #include <stddef.h>
32 #include <stdio.h>
33 #include <sys/types.h>
34 #include <pwd.h>
35 #include <grp.h>
36 #if USE_STATVFS
37 # include <sys/statvfs.h>
38 #elif HAVE_SYS_VFS_H
39 # include <sys/vfs.h>
40 #elif HAVE_SYS_MOUNT_H && HAVE_SYS_PARAM_H
41 /* NOTE: freebsd5.0 needs sys/param.h and sys/mount.h for statfs.
42 It does have statvfs.h, but shouldn't use it, since it doesn't
43 HAVE_STRUCT_STATVFS_F_BASETYPE. So find a clean way to fix it. */
44 /* NetBSD 1.5.2 needs these, for the declaration of struct statfs. */
45 # include <sys/param.h>
46 # include <sys/mount.h>
47 # if HAVE_NETINET_IN_H && HAVE_NFS_NFS_CLNT_H && HAVE_NFS_VFS_H
48 /* Ultrix 4.4 needs these for the declaration of struct statfs. */
49 # include <netinet/in.h>
50 # include <nfs/nfs_clnt.h>
51 # include <nfs/vfs.h>
52 # endif
53 #elif HAVE_OS_H /* BeOS */
54 # include <fs_info.h>
55 #endif
56 #include <selinux/selinux.h>
58 #include "system.h"
60 #include "error.h"
61 #include "filemode.h"
62 #include "file-type.h"
63 #include "fs.h"
64 #include "getopt.h"
65 #include "quote.h"
66 #include "quotearg.h"
67 #include "stat-time.h"
68 #include "strftime.h"
69 #include "areadlink.h"
71 #define alignof(type) offsetof (struct { char c; type x; }, x)
73 #if USE_STATVFS
74 # define STRUCT_STATVFS struct statvfs
75 # define STRUCT_STATXFS_F_FSID_IS_INTEGER STRUCT_STATVFS_F_FSID_IS_INTEGER
76 # define HAVE_STRUCT_STATXFS_F_TYPE HAVE_STRUCT_STATVFS_F_TYPE
77 # if HAVE_STRUCT_STATVFS_F_NAMEMAX
78 # define SB_F_NAMEMAX(S) ((S)->f_namemax)
79 # endif
80 # define STATFS statvfs
81 # define STATFS_FRSIZE(S) ((S)->f_frsize)
82 #else
83 # define HAVE_STRUCT_STATXFS_F_TYPE HAVE_STRUCT_STATFS_F_TYPE
84 # if HAVE_STRUCT_STATFS_F_NAMELEN
85 # define SB_F_NAMEMAX(S) ((S)->f_namelen)
86 # endif
87 # define STATFS statfs
88 # if HAVE_OS_H /* BeOS */
89 /* BeOS has a statvfs function, but it does not return sensible values
90 for f_files, f_ffree and f_favail, and lacks f_type, f_basetype and
91 f_fstypename. Use 'struct fs_info' instead. */
92 static int
93 statfs (char const *filename, struct fs_info *buf)
95 dev_t device = dev_for_path (filename);
96 if (device < 0)
98 errno = (device == B_ENTRY_NOT_FOUND ? ENOENT
99 : device == B_BAD_VALUE ? EINVAL
100 : device == B_NAME_TOO_LONG ? ENAMETOOLONG
101 : device == B_NO_MEMORY ? ENOMEM
102 : device == B_FILE_ERROR ? EIO
103 : 0);
104 return -1;
106 /* If successful, buf->dev will be == device. */
107 return fs_stat_dev (device, buf);
109 # define f_fsid dev
110 # define f_blocks total_blocks
111 # define f_bfree free_blocks
112 # define f_bavail free_blocks
113 # define f_bsize io_size
114 # define f_files total_nodes
115 # define f_ffree free_nodes
116 # define STRUCT_STATVFS struct fs_info
117 # define STRUCT_STATXFS_F_FSID_IS_INTEGER true
118 # define STATFS_FRSIZE(S) ((S)->block_size)
119 # else
120 # define STRUCT_STATVFS struct statfs
121 # define STRUCT_STATXFS_F_FSID_IS_INTEGER STRUCT_STATFS_F_FSID_IS_INTEGER
122 # define STATFS_FRSIZE(S) 0
123 # endif
124 #endif
126 #ifdef SB_F_NAMEMAX
127 # define OUT_NAMEMAX out_uint
128 #else
129 /* NetBSD 1.5.2 has neither f_namemax nor f_namelen. */
130 # define SB_F_NAMEMAX(S) "*"
131 # define OUT_NAMEMAX out_string
132 #endif
134 #if HAVE_STRUCT_STATVFS_F_BASETYPE
135 # define STATXFS_FILE_SYSTEM_TYPE_MEMBER_NAME f_basetype
136 #else
137 # if HAVE_STRUCT_STATVFS_F_FSTYPENAME || HAVE_STRUCT_STATFS_F_FSTYPENAME
138 # define STATXFS_FILE_SYSTEM_TYPE_MEMBER_NAME f_fstypename
139 # elif HAVE_OS_H /* BeOS */
140 # define STATXFS_FILE_SYSTEM_TYPE_MEMBER_NAME fsh_name
141 # endif
142 #endif
144 /* FIXME: these are used by printf.c, too */
145 #define isodigit(c) ('0' <= (c) && (c) <= '7')
146 #define octtobin(c) ((c) - '0')
147 #define hextobin(c) ((c) >= 'a' && (c) <= 'f' ? (c) - 'a' + 10 : \
148 (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : (c) - '0')
150 #define PROGRAM_NAME "stat"
152 #define AUTHORS proper_name ("Michael Meskes")
154 enum
156 PRINTF_OPTION = CHAR_MAX + 1
159 static struct option const long_options[] =
161 {"context", no_argument, 0, 'Z'},
162 {"dereference", no_argument, NULL, 'L'},
163 {"file-system", no_argument, NULL, 'f'},
164 {"format", required_argument, NULL, 'c'},
165 {"printf", required_argument, NULL, PRINTF_OPTION},
166 {"terse", no_argument, NULL, 't'},
167 {GETOPT_HELP_OPTION_DECL},
168 {GETOPT_VERSION_OPTION_DECL},
169 {NULL, 0, NULL, 0}
172 /* Whether to follow symbolic links; True for --dereference (-L). */
173 static bool follow_links;
175 /* Whether to interpret backslash-escape sequences.
176 True for --printf=FMT, not for --format=FMT (-c). */
177 static bool interpret_backslash_escapes;
179 /* The trailing delimiter string:
180 "" for --printf=FMT, "\n" for --format=FMT (-c). */
181 static char const *trailing_delim = "";
183 /* Return the type of the specified file system.
184 Some systems have statfvs.f_basetype[FSTYPSZ] (AIX, HP-UX, and Solaris).
185 Others have statvfs.f_fstypename[_VFS_NAMELEN] (NetBSD 3.0).
186 Others have statfs.f_fstypename[MFSNAMELEN] (NetBSD 1.5.2).
187 Still others have neither and have to get by with f_type (GNU/Linux).
188 But f_type may only exist in statfs (Cygwin). */
189 static char const *
190 human_fstype (STRUCT_STATVFS const *statfsbuf)
192 #ifdef STATXFS_FILE_SYSTEM_TYPE_MEMBER_NAME
193 return statfsbuf->STATXFS_FILE_SYSTEM_TYPE_MEMBER_NAME;
194 #else
195 switch (statfsbuf->f_type)
197 # if defined __linux__
199 /* Compare with what's in libc:
200 f=/a/libc/sysdeps/unix/sysv/linux/linux_fsinfo.h
201 sed -n '/ADFS_SUPER_MAGIC/,/SYSFS_MAGIC/p' $f \
202 | perl -n -e '/#define (.*?)_(?:SUPER_)MAGIC\s+0x(\S+)/' \
203 -e 'and print "case S_MAGIC_$1: /\* 0x" . uc($2) . " *\/\n"' \
204 | sort > sym_libc
205 perl -ne '/^\s+(case S_MAGIC_.*?): \/\* 0x(\S+) \*\//' \
206 -e 'and do { $v=uc$2; print "$1: /\* 0x$v *\/\n"}' stat.c \
207 | sort > sym_stat
208 diff -u sym_stat sym_libc
211 /* Also sync from the list in "man 2 statfs". */
213 /* IMPORTANT NOTE: Each of the following `case S_MAGIC_...:'
214 statements must be followed by a hexadecimal constant in
215 a comment. The S_MAGIC_... name and constant are automatically
216 combined to produce the #define directives in fs.h. */
218 case S_MAGIC_ADFS: /* 0xADF5 */
219 return "adfs";
220 case S_MAGIC_AFFS: /* 0xADFF */
221 return "affs";
222 case S_MAGIC_AUTOFS: /* 0x187 */
223 return "autofs";
224 case S_MAGIC_BEFS: /* 0x42465331 */
225 return "befs";
226 case S_MAGIC_BFS: /* 0x1BADFACE */
227 return "bfs";
228 case S_MAGIC_BINFMT_MISC: /* 0x42494e4d */
229 return "binfmt_misc";
230 case S_MAGIC_CODA: /* 0x73757245 */
231 return "coda";
232 case S_MAGIC_COH: /* 0x012FF7B7 */
233 return "coh";
234 case S_MAGIC_CRAMFS: /* 0x28CD3D45 */
235 return "cramfs";
236 case S_MAGIC_DEVFS: /* 0x1373 */
237 return "devfs";
238 case S_MAGIC_DEVPTS: /* 0x1CD1 */
239 return "devpts";
240 case S_MAGIC_EFS: /* 0x414A53 */
241 return "efs";
242 case S_MAGIC_EXT: /* 0x137D */
243 return "ext";
244 case S_MAGIC_EXT2: /* 0xEF53 */
245 return "ext2/ext3";
246 case S_MAGIC_EXT2_OLD: /* 0xEF51 */
247 return "ext2";
248 case S_MAGIC_FAT: /* 0x4006 */
249 return "fat";
250 case S_MAGIC_FUSECTL: /* 0x65735543 */
251 return "fusectl";
252 case S_MAGIC_HPFS: /* 0xF995E849 */
253 return "hpfs";
254 case S_MAGIC_HUGETLBFS: /* 0x958458f6 */
255 return "hugetlbfs";
256 case S_MAGIC_ISOFS: /* 0x9660 */
257 return "isofs";
258 case S_MAGIC_ISOFS_R_WIN: /* 0x4004 */
259 return "isofs";
260 case S_MAGIC_ISOFS_WIN: /* 0x4000 */
261 return "isofs";
262 case S_MAGIC_JFFS2: /* 0x72B6 */
263 return "jffs2";
264 case S_MAGIC_JFFS: /* 0x07C0 */
265 return "jffs";
266 case S_MAGIC_JFS: /* 0x3153464A */
267 return "jfs";
268 case S_MAGIC_LUSTRE: /* 0x0BD00BD0 */
269 return "lustre";
270 case S_MAGIC_MINIX: /* 0x137F */
271 return "minix";
272 case S_MAGIC_MINIX_30: /* 0x138F */
273 return "minix (30 char.)";
274 case S_MAGIC_MINIX_V2: /* 0x2468 */
275 return "minix v2";
276 case S_MAGIC_MINIX_V2_30: /* 0x2478 */
277 return "minix v2 (30 char.)";
278 case S_MAGIC_MSDOS: /* 0x4D44 */
279 return "msdos";
280 case S_MAGIC_NCP: /* 0x564C */
281 return "novell";
282 case S_MAGIC_NFS: /* 0x6969 */
283 return "nfs";
284 case S_MAGIC_NFSD: /* 0x6E667364 */
285 return "nfsd";
286 case S_MAGIC_NTFS: /* 0x5346544E */
287 return "ntfs";
288 case S_MAGIC_OPENPROM: /* 0x9fa1 */
289 return "openprom";
290 case S_MAGIC_PROC: /* 0x9FA0 */
291 return "proc";
292 case S_MAGIC_QNX4: /* 0x002F */
293 return "qnx4";
294 case S_MAGIC_RAMFS: /* 0x858458F6 */
295 return "ramfs";
296 case S_MAGIC_REISERFS: /* 0x52654973 */
297 return "reiserfs";
298 case S_MAGIC_ROMFS: /* 0x7275 */
299 return "romfs";
300 case S_MAGIC_SMB: /* 0x517B */
301 return "smb";
302 case S_MAGIC_SQUASHFS: /* 0x73717368 */
303 return "squashfs";
304 case S_MAGIC_SYSFS: /* 0x62656572 */
305 return "sysfs";
306 case S_MAGIC_SYSV2: /* 0x012FF7B6 */
307 return "sysv2";
308 case S_MAGIC_SYSV4: /* 0x012FF7B5 */
309 return "sysv4";
310 case S_MAGIC_TMPFS: /* 0x1021994 */
311 return "tmpfs";
312 case S_MAGIC_UDF: /* 0x15013346 */
313 return "udf";
314 case S_MAGIC_UFS: /* 0x00011954 */
315 return "ufs";
316 case S_MAGIC_UFS_BYTESWAPPED: /* 0x54190100 */
317 return "ufs";
318 case S_MAGIC_USBDEVFS: /* 0x9FA2 */
319 return "usbdevfs";
320 case S_MAGIC_VXFS: /* 0xA501FCF5 */
321 return "vxfs";
322 case S_MAGIC_XENIX: /* 0x012FF7B4 */
323 return "xenix";
324 case S_MAGIC_XFS: /* 0x58465342 */
325 return "xfs";
326 case S_MAGIC_XIAFS: /* 0x012FD16D */
327 return "xia";
329 # elif __GNU__
330 case FSTYPE_UFS:
331 return "ufs";
332 case FSTYPE_NFS:
333 return "nfs";
334 case FSTYPE_GFS:
335 return "gfs";
336 case FSTYPE_LFS:
337 return "lfs";
338 case FSTYPE_SYSV:
339 return "sysv";
340 case FSTYPE_FTP:
341 return "ftp";
342 case FSTYPE_TAR:
343 return "tar";
344 case FSTYPE_AR:
345 return "ar";
346 case FSTYPE_CPIO:
347 return "cpio";
348 case FSTYPE_MSLOSS:
349 return "msloss";
350 case FSTYPE_CPM:
351 return "cpm";
352 case FSTYPE_HFS:
353 return "hfs";
354 case FSTYPE_DTFS:
355 return "dtfs";
356 case FSTYPE_GRFS:
357 return "grfs";
358 case FSTYPE_TERM:
359 return "term";
360 case FSTYPE_DEV:
361 return "dev";
362 case FSTYPE_PROC:
363 return "proc";
364 case FSTYPE_IFSOCK:
365 return "ifsock";
366 case FSTYPE_AFS:
367 return "afs";
368 case FSTYPE_DFS:
369 return "dfs";
370 case FSTYPE_PROC9:
371 return "proc9";
372 case FSTYPE_SOCKET:
373 return "socket";
374 case FSTYPE_MISC:
375 return "misc";
376 case FSTYPE_EXT2FS:
377 return "ext2/ext3";
378 case FSTYPE_HTTP:
379 return "http";
380 case FSTYPE_MEMFS:
381 return "memfs";
382 case FSTYPE_ISO9660:
383 return "iso9660";
384 # endif
385 default:
387 unsigned long int type = statfsbuf->f_type;
388 static char buf[sizeof "UNKNOWN (0x%lx)" - 3
389 + (sizeof type * CHAR_BIT + 3) / 4];
390 sprintf (buf, "UNKNOWN (0x%lx)", type);
391 return buf;
394 #endif
397 static char *
398 human_access (struct stat const *statbuf)
400 static char modebuf[12];
401 filemodestring (statbuf, modebuf);
402 modebuf[10] = 0;
403 return modebuf;
406 static char *
407 human_time (struct timespec t)
409 static char str[MAX (INT_BUFSIZE_BOUND (intmax_t),
410 (INT_STRLEN_BOUND (int) /* YYYY */
411 + 1 /* because YYYY might equal INT_MAX + 1900 */
412 + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +ZZZZ"))];
413 struct tm const *tm = localtime (&t.tv_sec);
414 if (tm == NULL)
415 return timetostr (t.tv_sec, str);
416 nstrftime (str, sizeof str, "%Y-%m-%d %H:%M:%S.%N %z", tm, 0, t.tv_nsec);
417 return str;
420 static void
421 out_string (char *pformat, size_t prefix_len, char const *arg)
423 strcpy (pformat + prefix_len, "s");
424 printf (pformat, arg);
426 static void
427 out_int (char *pformat, size_t prefix_len, intmax_t arg)
429 strcpy (pformat + prefix_len, PRIdMAX);
430 printf (pformat, arg);
432 static void
433 out_uint (char *pformat, size_t prefix_len, uintmax_t arg)
435 strcpy (pformat + prefix_len, PRIuMAX);
436 printf (pformat, arg);
438 static void
439 out_uint_o (char *pformat, size_t prefix_len, uintmax_t arg)
441 strcpy (pformat + prefix_len, PRIoMAX);
442 printf (pformat, arg);
444 static void
445 out_uint_x (char *pformat, size_t prefix_len, uintmax_t arg)
447 strcpy (pformat + prefix_len, PRIxMAX);
448 printf (pformat, arg);
451 /* Very specialized function (modifies FORMAT), just so as to avoid
452 duplicating this code between both print_statfs and print_stat. */
453 static void
454 out_file_context (char const *filename, char *pformat, size_t prefix_len)
456 char *scontext;
457 if ((follow_links
458 ? getfilecon (filename, &scontext)
459 : lgetfilecon (filename, &scontext)) < 0)
461 error (0, errno, _("failed to get security context of %s"),
462 quote (filename));
463 scontext = NULL;
465 strcpy (pformat + prefix_len, "s");
466 printf (pformat, (scontext ? scontext : "?"));
467 if (scontext)
468 freecon (scontext);
471 /* print statfs info */
472 static void
473 print_statfs (char *pformat, size_t prefix_len, char m, char const *filename,
474 void const *data)
476 STRUCT_STATVFS const *statfsbuf = data;
478 switch (m)
480 case 'n':
481 out_string (pformat, prefix_len, filename);
482 break;
484 case 'i':
486 #if STRUCT_STATXFS_F_FSID_IS_INTEGER
487 uintmax_t fsid = statfsbuf->f_fsid;
488 #else
489 typedef unsigned int fsid_word;
490 verify (alignof (STRUCT_STATVFS) % alignof (fsid_word) == 0);
491 verify (offsetof (STRUCT_STATVFS, f_fsid) % alignof (fsid_word) == 0);
492 verify (sizeof statfsbuf->f_fsid % alignof (fsid_word) == 0);
493 fsid_word const *p = (fsid_word *) &statfsbuf->f_fsid;
495 /* Assume a little-endian word order, as that is compatible
496 with glibc's statvfs implementation. */
497 uintmax_t fsid = 0;
498 int words = sizeof statfsbuf->f_fsid / sizeof *p;
499 int i;
500 for (i = 0; i < words && i * sizeof *p < sizeof fsid; i++)
502 uintmax_t u = p[words - 1 - i];
503 fsid |= u << (i * CHAR_BIT * sizeof *p);
505 #endif
506 out_uint_x (pformat, prefix_len, fsid);
508 break;
510 case 'l':
511 OUT_NAMEMAX (pformat, prefix_len, SB_F_NAMEMAX (statfsbuf));
512 break;
513 case 't':
514 #if HAVE_STRUCT_STATXFS_F_TYPE
515 out_uint_x (pformat, prefix_len, statfsbuf->f_type);
516 #else
517 fputc ('?', stdout);
518 #endif
519 break;
520 case 'T':
521 out_string (pformat, prefix_len, human_fstype (statfsbuf));
522 break;
523 case 'b':
524 out_int (pformat, prefix_len, statfsbuf->f_blocks);
525 break;
526 case 'f':
527 out_int (pformat, prefix_len, statfsbuf->f_bfree);
528 break;
529 case 'a':
530 out_int (pformat, prefix_len, statfsbuf->f_bavail);
531 break;
532 case 's':
533 out_uint (pformat, prefix_len, statfsbuf->f_bsize);
534 break;
535 case 'S':
537 uintmax_t frsize = STATFS_FRSIZE (statfsbuf);
538 if (! frsize)
539 frsize = statfsbuf->f_bsize;
540 out_uint (pformat, prefix_len, frsize);
542 break;
543 case 'c':
544 out_uint (pformat, prefix_len, statfsbuf->f_files);
545 break;
546 case 'd':
547 out_int (pformat, prefix_len, statfsbuf->f_ffree);
548 break;
549 case 'C':
550 out_file_context (filename, pformat, prefix_len);
551 break;
552 default:
553 fputc ('?', stdout);
554 break;
558 /* print stat info */
559 static void
560 print_stat (char *pformat, size_t prefix_len, char m,
561 char const *filename, void const *data)
563 struct stat *statbuf = (struct stat *) data;
564 struct passwd *pw_ent;
565 struct group *gw_ent;
567 switch (m)
569 case 'n':
570 out_string (pformat, prefix_len, filename);
571 break;
572 case 'N':
573 out_string (pformat, prefix_len, quote (filename));
574 if (S_ISLNK (statbuf->st_mode))
576 char *linkname = areadlink_with_size (filename, statbuf->st_size);
577 if (linkname == NULL)
579 error (0, errno, _("cannot read symbolic link %s"),
580 quote (filename));
581 return;
583 printf (" -> ");
584 out_string (pformat, prefix_len, quote (linkname));
586 break;
587 case 'd':
588 out_uint (pformat, prefix_len, statbuf->st_dev);
589 break;
590 case 'D':
591 out_uint_x (pformat, prefix_len, statbuf->st_dev);
592 break;
593 case 'i':
594 out_uint (pformat, prefix_len, statbuf->st_ino);
595 break;
596 case 'a':
597 out_uint_o (pformat, prefix_len, statbuf->st_mode & CHMOD_MODE_BITS);
598 break;
599 case 'A':
600 out_string (pformat, prefix_len, human_access (statbuf));
601 break;
602 case 'f':
603 out_uint_x (pformat, prefix_len, statbuf->st_mode);
604 break;
605 case 'F':
606 out_string (pformat, prefix_len, file_type (statbuf));
607 break;
608 case 'h':
609 out_uint (pformat, prefix_len, statbuf->st_nlink);
610 break;
611 case 'u':
612 out_uint (pformat, prefix_len, statbuf->st_uid);
613 break;
614 case 'U':
615 setpwent ();
616 pw_ent = getpwuid (statbuf->st_uid);
617 out_string (pformat, prefix_len,
618 pw_ent ? pw_ent->pw_name : "UNKNOWN");
619 break;
620 case 'g':
621 out_uint (pformat, prefix_len, statbuf->st_gid);
622 break;
623 case 'G':
624 setgrent ();
625 gw_ent = getgrgid (statbuf->st_gid);
626 out_string (pformat, prefix_len,
627 gw_ent ? gw_ent->gr_name : "UNKNOWN");
628 break;
629 case 't':
630 out_uint_x (pformat, prefix_len, major (statbuf->st_rdev));
631 break;
632 case 'T':
633 out_uint_x (pformat, prefix_len, minor (statbuf->st_rdev));
634 break;
635 case 's':
636 out_uint (pformat, prefix_len, statbuf->st_size);
637 break;
638 case 'B':
639 out_uint (pformat, prefix_len, ST_NBLOCKSIZE);
640 break;
641 case 'b':
642 out_uint (pformat, prefix_len, ST_NBLOCKS (*statbuf));
643 break;
644 case 'o':
645 out_uint (pformat, prefix_len, statbuf->st_blksize);
646 break;
647 case 'x':
648 out_string (pformat, prefix_len, human_time (get_stat_atime (statbuf)));
649 break;
650 case 'X':
651 if (TYPE_SIGNED (time_t))
652 out_int (pformat, prefix_len, statbuf->st_atime);
653 else
654 out_uint (pformat, prefix_len, statbuf->st_atime);
655 break;
656 case 'y':
657 out_string (pformat, prefix_len, human_time (get_stat_mtime (statbuf)));
658 break;
659 case 'Y':
660 if (TYPE_SIGNED (time_t))
661 out_int (pformat, prefix_len, statbuf->st_mtime);
662 else
663 out_uint (pformat, prefix_len, statbuf->st_mtime);
664 break;
665 case 'z':
666 out_string (pformat, prefix_len, human_time (get_stat_ctime (statbuf)));
667 break;
668 case 'Z':
669 if (TYPE_SIGNED (time_t))
670 out_int (pformat, prefix_len, statbuf->st_ctime);
671 else
672 out_uint (pformat, prefix_len, statbuf->st_ctime);
673 break;
674 case 'C':
675 out_file_context (filename, pformat, prefix_len);
676 break;
677 default:
678 fputc ('?', stdout);
679 break;
683 /* Output a single-character \ escape. */
685 static void
686 print_esc_char (char c)
688 switch (c)
690 case 'a': /* Alert. */
691 c ='\a';
692 break;
693 case 'b': /* Backspace. */
694 c ='\b';
695 break;
696 case 'f': /* Form feed. */
697 c ='\f';
698 break;
699 case 'n': /* New line. */
700 c ='\n';
701 break;
702 case 'r': /* Carriage return. */
703 c ='\r';
704 break;
705 case 't': /* Horizontal tab. */
706 c ='\t';
707 break;
708 case 'v': /* Vertical tab. */
709 c ='\v';
710 break;
711 case '"':
712 case '\\':
713 break;
714 default:
715 error (0, 0, _("warning: unrecognized escape `\\%c'"), c);
716 break;
718 putchar (c);
721 static void
722 print_it (char const *format, char const *filename,
723 void (*print_func) (char *, size_t, char, char const *, void const *),
724 void const *data)
726 /* Add 2 to accommodate our conversion of the stat `%s' format string
727 to the longer printf `%llu' one. */
728 enum
730 MAX_ADDITIONAL_BYTES =
731 (MAX (sizeof PRIdMAX,
732 MAX (sizeof PRIoMAX, MAX (sizeof PRIuMAX, sizeof PRIxMAX)))
733 - 1)
735 size_t n_alloc = strlen (format) + MAX_ADDITIONAL_BYTES + 1;
736 char *dest = xmalloc (n_alloc);
737 char const *b;
738 for (b = format; *b; b++)
740 switch (*b)
742 case '%':
744 size_t len = strspn (b + 1, "#-+.I 0123456789");
745 char const *fmt_char = b + len + 1;
746 memcpy (dest, b, len + 1);
748 b = fmt_char;
749 switch (*fmt_char)
751 case '\0':
752 --b;
753 /* fall through */
754 case '%':
755 if (0 < len)
757 dest[len + 1] = *fmt_char;
758 dest[len + 2] = '\0';
759 error (EXIT_FAILURE, 0, _("%s: invalid directive"),
760 quotearg_colon (dest));
762 putchar ('%');
763 break;
764 default:
765 print_func (dest, len + 1, *fmt_char, filename, data);
766 break;
768 break;
771 case '\\':
772 if ( ! interpret_backslash_escapes)
774 putchar ('\\');
775 break;
777 ++b;
778 if (isodigit (*b))
780 int esc_value = octtobin (*b);
781 int esc_length = 1; /* number of octal digits */
782 for (++b; esc_length < 3 && isodigit (*b);
783 ++esc_length, ++b)
785 esc_value = esc_value * 8 + octtobin (*b);
787 putchar (esc_value);
788 --b;
790 else if (*b == 'x' && isxdigit (to_uchar (b[1])))
792 int esc_value = hextobin (b[1]); /* Value of \xhh escape. */
793 /* A hexadecimal \xhh escape sequence must have
794 1 or 2 hex. digits. */
795 ++b;
796 if (isxdigit (to_uchar (b[1])))
798 ++b;
799 esc_value = esc_value * 16 + hextobin (*b);
801 putchar (esc_value);
803 else if (*b == '\0')
805 error (0, 0, _("warning: backslash at end of format"));
806 putchar ('\\');
807 /* Arrange to exit the loop. */
808 --b;
810 else
812 print_esc_char (*b);
814 break;
816 default:
817 putchar (*b);
818 break;
821 free (dest);
823 fputs (trailing_delim, stdout);
826 /* Stat the file system and print what we find. */
827 static bool
828 do_statfs (char const *filename, bool terse, char const *format)
830 STRUCT_STATVFS statfsbuf;
832 if (STATFS (filename, &statfsbuf) != 0)
834 error (0, errno, _("cannot read file system information for %s"),
835 quote (filename));
836 return false;
839 if (format == NULL)
841 format = (terse
842 ? "%n %i %l %t %s %S %b %f %a %c %d\n"
843 : " File: \"%n\"\n"
844 " ID: %-8i Namelen: %-7l Type: %T\n"
845 "Block size: %-10s Fundamental block size: %S\n"
846 "Blocks: Total: %-10b Free: %-10f Available: %a\n"
847 "Inodes: Total: %-10c Free: %d\n");
850 print_it (format, filename, print_statfs, &statfsbuf);
851 return true;
854 /* stat the file and print what we find */
855 static bool
856 do_stat (char const *filename, bool terse, char const *format)
858 struct stat statbuf;
860 if ((follow_links ? stat : lstat) (filename, &statbuf) != 0)
862 error (0, errno, _("cannot stat %s"), quote (filename));
863 return false;
866 if (format == NULL)
868 if (terse)
870 format = "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %o\n";
872 else
874 /* Temporary hack to match original output until conditional
875 implemented. */
876 if (S_ISBLK (statbuf.st_mode) || S_ISCHR (statbuf.st_mode))
878 format =
879 " File: %N\n"
880 " Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
881 "Device: %Dh/%dd\tInode: %-10i Links: %-5h"
882 " Device type: %t,%T\n"
883 "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n"
884 "Access: %x\n" "Modify: %y\n" "Change: %z\n";
886 else
888 format =
889 " File: %N\n"
890 " Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
891 "Device: %Dh/%dd\tInode: %-10i Links: %h\n"
892 "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n"
893 "Access: %x\n" "Modify: %y\n" "Change: %z\n";
897 print_it (format, filename, print_stat, &statbuf);
898 return true;
901 void
902 usage (int status)
904 if (status != EXIT_SUCCESS)
905 fprintf (stderr, _("Try `%s --help' for more information.\n"),
906 program_name);
907 else
909 printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
910 fputs (_("\
911 Display file or file system status.\n\
913 -L, --dereference follow links\n\
914 -f, --file-system display file system status instead of file status\n\
915 "), stdout);
916 fputs (_("\
917 -c --format=FORMAT use the specified FORMAT instead of the default;\n\
918 output a newline after each use of FORMAT\n\
919 --printf=FORMAT like --format, but interpret backslash escapes,\n\
920 and do not output a mandatory trailing newline.\n\
921 If you want a newline, include \\n in FORMAT.\n\
922 -t, --terse print the information in terse form\n\
923 "), stdout);
924 fputs (HELP_OPTION_DESCRIPTION, stdout);
925 fputs (VERSION_OPTION_DESCRIPTION, stdout);
927 fputs (_("\n\
928 The valid format sequences for files (without --file-system):\n\
930 %a Access rights in octal\n\
931 %A Access rights in human readable form\n\
932 %b Number of blocks allocated (see %B)\n\
933 %B The size in bytes of each block reported by %b\n\
934 %C SELinux security context string\n\
935 "), stdout);
936 fputs (_("\
937 %d Device number in decimal\n\
938 %D Device number in hex\n\
939 %f Raw mode in hex\n\
940 %F File type\n\
941 %g Group ID of owner\n\
942 %G Group name of owner\n\
943 "), stdout);
944 fputs (_("\
945 %h Number of hard links\n\
946 %i Inode number\n\
947 %n File name\n\
948 %N Quoted file name with dereference if symbolic link\n\
949 %o I/O block size\n\
950 %s Total size, in bytes\n\
951 %t Major device type in hex\n\
952 %T Minor device type in hex\n\
953 "), stdout);
954 fputs (_("\
955 %u User ID of owner\n\
956 %U User name of owner\n\
957 %x Time of last access\n\
958 %X Time of last access as seconds since Epoch\n\
959 %y Time of last modification\n\
960 %Y Time of last modification as seconds since Epoch\n\
961 %z Time of last change\n\
962 %Z Time of last change as seconds since Epoch\n\
964 "), stdout);
966 fputs (_("\
967 Valid format sequences for file systems:\n\
969 %a Free blocks available to non-superuser\n\
970 %b Total data blocks in file system\n\
971 %c Total file nodes in file system\n\
972 %d Free file nodes in file system\n\
973 %f Free blocks in file system\n\
974 %C SELinux security context string\n\
975 "), stdout);
976 fputs (_("\
977 %i File System ID in hex\n\
978 %l Maximum length of filenames\n\
979 %n File name\n\
980 %s Block size (for faster transfers)\n\
981 %S Fundamental block size (for block counts)\n\
982 %t Type in hex\n\
983 %T Type in human readable form\n\
984 "), stdout);
985 printf (USAGE_BUILTIN_WARNING, PROGRAM_NAME);
986 emit_bug_reporting_address ();
988 exit (status);
992 main (int argc, char *argv[])
994 int c;
995 int i;
996 bool fs = false;
997 bool terse = false;
998 char *format = NULL;
999 bool ok = true;
1001 initialize_main (&argc, &argv);
1002 set_program_name (argv[0]);
1003 setlocale (LC_ALL, "");
1004 bindtextdomain (PACKAGE, LOCALEDIR);
1005 textdomain (PACKAGE);
1007 atexit (close_stdout);
1009 while ((c = getopt_long (argc, argv, "c:fLtZ", long_options, NULL)) != -1)
1011 switch (c)
1013 case PRINTF_OPTION:
1014 format = optarg;
1015 interpret_backslash_escapes = true;
1016 trailing_delim = "";
1017 break;
1019 case 'c':
1020 format = optarg;
1021 interpret_backslash_escapes = false;
1022 trailing_delim = "\n";
1023 break;
1025 case 'L':
1026 follow_links = true;
1027 break;
1029 case 'f':
1030 fs = true;
1031 break;
1033 case 't':
1034 terse = true;
1035 break;
1037 case 'Z': /* FIXME: remove in 2010 */
1038 /* Ignore, for compatibility with distributions
1039 that implemented this before upstream.
1040 But warn of impending removal. */
1041 error (0, 0,
1042 _("the --context (-Z) option is obsolete and will be removed\n"
1043 "in a future release"));
1044 break;
1046 case_GETOPT_HELP_CHAR;
1048 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1050 default:
1051 usage (EXIT_FAILURE);
1055 if (argc == optind)
1057 error (0, 0, _("missing operand"));
1058 usage (EXIT_FAILURE);
1061 for (i = optind; i < argc; i++)
1062 ok &= (fs
1063 ? do_statfs (argv[i], terse, format)
1064 : do_stat (argv[i], terse, format));
1066 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);