tests: ensure touch honors trailing slash
[coreutils/ericb.git] / src / stat.c
blobd3e16d70556fe417c3c5e8cba354810a0518fb8e
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_AFS: /* 0x5346414F */
223 return "afs";
224 case S_MAGIC_ANON_INODE_FS: /* 0x09041934 */
225 return "anon-inode FS";
226 case S_MAGIC_AUTOFS: /* 0x0187 */
227 return "autofs";
228 case S_MAGIC_BEFS: /* 0x42465331 */
229 return "befs";
230 case S_MAGIC_BFS: /* 0x1BADFACE */
231 return "bfs";
232 case S_MAGIC_BINFMT_MISC: /* 0x42494E4D */
233 return "binfmt_misc";
234 case S_MAGIC_BTRFS: /* 0x9123683E */
235 return "btrfs";
236 case S_MAGIC_CGROUP: /* 0x0027E0EB */
237 return "cgroupfs";
238 case S_MAGIC_CIFS: /* 0xFF534D42 */
239 return "cifs";
240 case S_MAGIC_CODA: /* 0x73757245 */
241 return "coda";
242 case S_MAGIC_COH: /* 0x012FF7B7 */
243 return "coh";
244 case S_MAGIC_CRAMFS: /* 0x28CD3D45 */
245 return "cramfs";
246 case S_MAGIC_CRAMFS_WEND: /* 0x453DCD28 */
247 return "cramfs-wend";
248 case S_MAGIC_DEBUGFS: /* 0x64626720 */
249 return "debugfs";
250 case S_MAGIC_DEVFS: /* 0x1373 */
251 return "devfs";
252 case S_MAGIC_DEVPTS: /* 0x1CD1 */
253 return "devpts";
254 case S_MAGIC_EFS: /* 0x00414A53 */
255 return "efs";
256 case S_MAGIC_EXT: /* 0x137D */
257 return "ext";
258 case S_MAGIC_EXT2: /* 0xEF53 */
259 return "ext2/ext3";
260 case S_MAGIC_EXT2_OLD: /* 0xEF51 */
261 return "ext2";
262 case S_MAGIC_FAT: /* 0x4006 */
263 return "fat";
264 case S_MAGIC_FUSECTL: /* 0x65735543 */
265 return "fusectl";
266 case S_MAGIC_FUTEXFS: /* 0x0BAD1DEA */
267 return "futexfs";
268 case S_MAGIC_HFS: /* 0x4244 */
269 return "hfs";
270 case S_MAGIC_HPFS: /* 0xF995E849 */
271 return "hpfs";
272 case S_MAGIC_HUGETLBFS: /* 0x958458F6 */
273 return "hugetlbfs";
274 case S_MAGIC_INOTIFYFS: /* 0x2BAD1DEA */
275 return "inotifyfs";
276 case S_MAGIC_ISOFS: /* 0x9660 */
277 return "isofs";
278 case S_MAGIC_ISOFS_R_WIN: /* 0x4004 */
279 return "isofs";
280 case S_MAGIC_ISOFS_WIN: /* 0x4000 */
281 return "isofs";
282 case S_MAGIC_JFFS: /* 0x07C0 */
283 return "jffs";
284 case S_MAGIC_JFFS2: /* 0x72B6 */
285 return "jffs2";
286 case S_MAGIC_JFS: /* 0x3153464A */
287 return "jfs";
288 case S_MAGIC_LUSTRE: /* 0x0BD00BD0 */
289 return "lustre";
290 case S_MAGIC_MINIX: /* 0x137F */
291 return "minix";
292 case S_MAGIC_MINIX_30: /* 0x138F */
293 return "minix (30 char.)";
294 case S_MAGIC_MINIX_V2: /* 0x2468 */
295 return "minix v2";
296 case S_MAGIC_MINIX_V2_30: /* 0x2478 */
297 return "minix v2 (30 char.)";
298 case S_MAGIC_MINIX_V3: /* 0x4D5A */
299 return "minux3";
300 case S_MAGIC_MSDOS: /* 0x4D44 */
301 return "msdos";
302 case S_MAGIC_NCP: /* 0x564C */
303 return "novell";
304 case S_MAGIC_NFS: /* 0x6969 */
305 return "nfs";
306 case S_MAGIC_NFSD: /* 0x6E667364 */
307 return "nfsd";
308 case S_MAGIC_NILFS: /* 0x3434 */
309 return "nilfs";
310 case S_MAGIC_NTFS: /* 0x5346544E */
311 return "ntfs";
312 case S_MAGIC_OPENPROM: /* 0x9FA1 */
313 return "openprom";
314 case S_MAGIC_PROC: /* 0x9FA0 */
315 return "proc";
316 case S_MAGIC_QNX4: /* 0x002F */
317 return "qnx4";
318 case S_MAGIC_RAMFS: /* 0x858458F6 */
319 return "ramfs";
320 case S_MAGIC_REISERFS: /* 0x52654973 */
321 return "reiserfs";
322 case S_MAGIC_ROMFS: /* 0x7275 */
323 return "romfs";
324 case S_MAGIC_SECURITYFS: /* 0x73636673 */
325 return "securityfs";
326 case S_MAGIC_SELINUX: /* 0xF97CFF8C */
327 return "selinux";
328 case S_MAGIC_SMB: /* 0x517B */
329 return "smb";
330 case S_MAGIC_SQUASHFS: /* 0x73717368 */
331 return "squashfs";
332 case S_MAGIC_SYSFS: /* 0x62656572 */
333 return "sysfs";
334 case S_MAGIC_SYSV2: /* 0x012FF7B6 */
335 return "sysv2";
336 case S_MAGIC_SYSV4: /* 0x012FF7B5 */
337 return "sysv4";
338 case S_MAGIC_TMPFS: /* 0x01021994 */
339 return "tmpfs";
340 case S_MAGIC_UDF: /* 0x15013346 */
341 return "udf";
342 case S_MAGIC_UFS: /* 0x00011954 */
343 return "ufs";
344 case S_MAGIC_UFS_BYTESWAPPED: /* 0x54190100 */
345 return "ufs";
346 case S_MAGIC_USBDEVFS: /* 0x9FA2 */
347 return "usbdevfs";
348 case S_MAGIC_VXFS: /* 0xA501FCF5 */
349 return "vxfs";
350 case S_MAGIC_XENFS: /* 0xABBA1974 */
351 return "xenfs";
352 case S_MAGIC_XENIX: /* 0x012FF7B4 */
353 return "xenix";
354 case S_MAGIC_XFS: /* 0x58465342 */
355 return "xfs";
356 case S_MAGIC_XIAFS: /* 0x012FD16D */
357 return "xia";
359 # elif __GNU__
360 case FSTYPE_UFS:
361 return "ufs";
362 case FSTYPE_NFS:
363 return "nfs";
364 case FSTYPE_GFS:
365 return "gfs";
366 case FSTYPE_LFS:
367 return "lfs";
368 case FSTYPE_SYSV:
369 return "sysv";
370 case FSTYPE_FTP:
371 return "ftp";
372 case FSTYPE_TAR:
373 return "tar";
374 case FSTYPE_AR:
375 return "ar";
376 case FSTYPE_CPIO:
377 return "cpio";
378 case FSTYPE_MSLOSS:
379 return "msloss";
380 case FSTYPE_CPM:
381 return "cpm";
382 case FSTYPE_HFS:
383 return "hfs";
384 case FSTYPE_DTFS:
385 return "dtfs";
386 case FSTYPE_GRFS:
387 return "grfs";
388 case FSTYPE_TERM:
389 return "term";
390 case FSTYPE_DEV:
391 return "dev";
392 case FSTYPE_PROC:
393 return "proc";
394 case FSTYPE_IFSOCK:
395 return "ifsock";
396 case FSTYPE_AFS:
397 return "afs";
398 case FSTYPE_DFS:
399 return "dfs";
400 case FSTYPE_PROC9:
401 return "proc9";
402 case FSTYPE_SOCKET:
403 return "socket";
404 case FSTYPE_MISC:
405 return "misc";
406 case FSTYPE_EXT2FS:
407 return "ext2/ext3";
408 case FSTYPE_HTTP:
409 return "http";
410 case FSTYPE_MEMFS:
411 return "memfs";
412 case FSTYPE_ISO9660:
413 return "iso9660";
414 # endif
415 default:
417 unsigned long int type = statfsbuf->f_type;
418 static char buf[sizeof "UNKNOWN (0x%lx)" - 3
419 + (sizeof type * CHAR_BIT + 3) / 4];
420 sprintf (buf, "UNKNOWN (0x%lx)", type);
421 return buf;
424 #endif
427 static char *
428 human_access (struct stat const *statbuf)
430 static char modebuf[12];
431 filemodestring (statbuf, modebuf);
432 modebuf[10] = 0;
433 return modebuf;
436 static char *
437 human_time (struct timespec t)
439 static char str[MAX (INT_BUFSIZE_BOUND (intmax_t),
440 (INT_STRLEN_BOUND (int) /* YYYY */
441 + 1 /* because YYYY might equal INT_MAX + 1900 */
442 + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +ZZZZ"))];
443 struct tm const *tm = localtime (&t.tv_sec);
444 if (tm == NULL)
445 return timetostr (t.tv_sec, str);
446 nstrftime (str, sizeof str, "%Y-%m-%d %H:%M:%S.%N %z", tm, 0, t.tv_nsec);
447 return str;
450 static void
451 out_string (char *pformat, size_t prefix_len, char const *arg)
453 strcpy (pformat + prefix_len, "s");
454 printf (pformat, arg);
456 static void
457 out_int (char *pformat, size_t prefix_len, intmax_t arg)
459 strcpy (pformat + prefix_len, PRIdMAX);
460 printf (pformat, arg);
462 static void
463 out_uint (char *pformat, size_t prefix_len, uintmax_t arg)
465 strcpy (pformat + prefix_len, PRIuMAX);
466 printf (pformat, arg);
468 static void
469 out_uint_o (char *pformat, size_t prefix_len, uintmax_t arg)
471 strcpy (pformat + prefix_len, PRIoMAX);
472 printf (pformat, arg);
474 static void
475 out_uint_x (char *pformat, size_t prefix_len, uintmax_t arg)
477 strcpy (pformat + prefix_len, PRIxMAX);
478 printf (pformat, arg);
481 /* Very specialized function (modifies FORMAT), just so as to avoid
482 duplicating this code between both print_statfs and print_stat. */
483 static void
484 out_file_context (char const *filename, char *pformat, size_t prefix_len)
486 char *scontext;
487 if ((follow_links
488 ? getfilecon (filename, &scontext)
489 : lgetfilecon (filename, &scontext)) < 0)
491 error (0, errno, _("failed to get security context of %s"),
492 quote (filename));
493 scontext = NULL;
495 strcpy (pformat + prefix_len, "s");
496 printf (pformat, (scontext ? scontext : "?"));
497 if (scontext)
498 freecon (scontext);
501 /* print statfs info */
502 static void
503 print_statfs (char *pformat, size_t prefix_len, char m, char const *filename,
504 void const *data)
506 STRUCT_STATVFS const *statfsbuf = data;
508 switch (m)
510 case 'n':
511 out_string (pformat, prefix_len, filename);
512 break;
514 case 'i':
516 #if STRUCT_STATXFS_F_FSID_IS_INTEGER
517 uintmax_t fsid = statfsbuf->f_fsid;
518 #else
519 typedef unsigned int fsid_word;
520 verify (alignof (STRUCT_STATVFS) % alignof (fsid_word) == 0);
521 verify (offsetof (STRUCT_STATVFS, f_fsid) % alignof (fsid_word) == 0);
522 verify (sizeof statfsbuf->f_fsid % alignof (fsid_word) == 0);
523 fsid_word const *p = (fsid_word *) &statfsbuf->f_fsid;
525 /* Assume a little-endian word order, as that is compatible
526 with glibc's statvfs implementation. */
527 uintmax_t fsid = 0;
528 int words = sizeof statfsbuf->f_fsid / sizeof *p;
529 int i;
530 for (i = 0; i < words && i * sizeof *p < sizeof fsid; i++)
532 uintmax_t u = p[words - 1 - i];
533 fsid |= u << (i * CHAR_BIT * sizeof *p);
535 #endif
536 out_uint_x (pformat, prefix_len, fsid);
538 break;
540 case 'l':
541 OUT_NAMEMAX (pformat, prefix_len, SB_F_NAMEMAX (statfsbuf));
542 break;
543 case 't':
544 #if HAVE_STRUCT_STATXFS_F_TYPE
545 out_uint_x (pformat, prefix_len, statfsbuf->f_type);
546 #else
547 fputc ('?', stdout);
548 #endif
549 break;
550 case 'T':
551 out_string (pformat, prefix_len, human_fstype (statfsbuf));
552 break;
553 case 'b':
554 out_int (pformat, prefix_len, statfsbuf->f_blocks);
555 break;
556 case 'f':
557 out_int (pformat, prefix_len, statfsbuf->f_bfree);
558 break;
559 case 'a':
560 out_int (pformat, prefix_len, statfsbuf->f_bavail);
561 break;
562 case 's':
563 out_uint (pformat, prefix_len, statfsbuf->f_bsize);
564 break;
565 case 'S':
567 uintmax_t frsize = STATFS_FRSIZE (statfsbuf);
568 if (! frsize)
569 frsize = statfsbuf->f_bsize;
570 out_uint (pformat, prefix_len, frsize);
572 break;
573 case 'c':
574 out_uint (pformat, prefix_len, statfsbuf->f_files);
575 break;
576 case 'd':
577 out_int (pformat, prefix_len, statfsbuf->f_ffree);
578 break;
579 case 'C':
580 out_file_context (filename, pformat, prefix_len);
581 break;
582 default:
583 fputc ('?', stdout);
584 break;
588 /* print stat info */
589 static void
590 print_stat (char *pformat, size_t prefix_len, char m,
591 char const *filename, void const *data)
593 struct stat *statbuf = (struct stat *) data;
594 struct passwd *pw_ent;
595 struct group *gw_ent;
597 switch (m)
599 case 'n':
600 out_string (pformat, prefix_len, filename);
601 break;
602 case 'N':
603 out_string (pformat, prefix_len, quote (filename));
604 if (S_ISLNK (statbuf->st_mode))
606 char *linkname = areadlink_with_size (filename, statbuf->st_size);
607 if (linkname == NULL)
609 error (0, errno, _("cannot read symbolic link %s"),
610 quote (filename));
611 return;
613 printf (" -> ");
614 out_string (pformat, prefix_len, quote (linkname));
616 break;
617 case 'd':
618 out_uint (pformat, prefix_len, statbuf->st_dev);
619 break;
620 case 'D':
621 out_uint_x (pformat, prefix_len, statbuf->st_dev);
622 break;
623 case 'i':
624 out_uint (pformat, prefix_len, statbuf->st_ino);
625 break;
626 case 'a':
627 out_uint_o (pformat, prefix_len, statbuf->st_mode & CHMOD_MODE_BITS);
628 break;
629 case 'A':
630 out_string (pformat, prefix_len, human_access (statbuf));
631 break;
632 case 'f':
633 out_uint_x (pformat, prefix_len, statbuf->st_mode);
634 break;
635 case 'F':
636 out_string (pformat, prefix_len, file_type (statbuf));
637 break;
638 case 'h':
639 out_uint (pformat, prefix_len, statbuf->st_nlink);
640 break;
641 case 'u':
642 out_uint (pformat, prefix_len, statbuf->st_uid);
643 break;
644 case 'U':
645 setpwent ();
646 pw_ent = getpwuid (statbuf->st_uid);
647 out_string (pformat, prefix_len,
648 pw_ent ? pw_ent->pw_name : "UNKNOWN");
649 break;
650 case 'g':
651 out_uint (pformat, prefix_len, statbuf->st_gid);
652 break;
653 case 'G':
654 setgrent ();
655 gw_ent = getgrgid (statbuf->st_gid);
656 out_string (pformat, prefix_len,
657 gw_ent ? gw_ent->gr_name : "UNKNOWN");
658 break;
659 case 't':
660 out_uint_x (pformat, prefix_len, major (statbuf->st_rdev));
661 break;
662 case 'T':
663 out_uint_x (pformat, prefix_len, minor (statbuf->st_rdev));
664 break;
665 case 's':
666 out_uint (pformat, prefix_len, statbuf->st_size);
667 break;
668 case 'B':
669 out_uint (pformat, prefix_len, ST_NBLOCKSIZE);
670 break;
671 case 'b':
672 out_uint (pformat, prefix_len, ST_NBLOCKS (*statbuf));
673 break;
674 case 'o':
675 out_uint (pformat, prefix_len, statbuf->st_blksize);
676 break;
677 case 'x':
678 out_string (pformat, prefix_len, human_time (get_stat_atime (statbuf)));
679 break;
680 case 'X':
681 if (TYPE_SIGNED (time_t))
682 out_int (pformat, prefix_len, statbuf->st_atime);
683 else
684 out_uint (pformat, prefix_len, statbuf->st_atime);
685 break;
686 case 'y':
687 out_string (pformat, prefix_len, human_time (get_stat_mtime (statbuf)));
688 break;
689 case 'Y':
690 if (TYPE_SIGNED (time_t))
691 out_int (pformat, prefix_len, statbuf->st_mtime);
692 else
693 out_uint (pformat, prefix_len, statbuf->st_mtime);
694 break;
695 case 'z':
696 out_string (pformat, prefix_len, human_time (get_stat_ctime (statbuf)));
697 break;
698 case 'Z':
699 if (TYPE_SIGNED (time_t))
700 out_int (pformat, prefix_len, statbuf->st_ctime);
701 else
702 out_uint (pformat, prefix_len, statbuf->st_ctime);
703 break;
704 case 'C':
705 out_file_context (filename, pformat, prefix_len);
706 break;
707 default:
708 fputc ('?', stdout);
709 break;
713 /* Output a single-character \ escape. */
715 static void
716 print_esc_char (char c)
718 switch (c)
720 case 'a': /* Alert. */
721 c ='\a';
722 break;
723 case 'b': /* Backspace. */
724 c ='\b';
725 break;
726 case 'f': /* Form feed. */
727 c ='\f';
728 break;
729 case 'n': /* New line. */
730 c ='\n';
731 break;
732 case 'r': /* Carriage return. */
733 c ='\r';
734 break;
735 case 't': /* Horizontal tab. */
736 c ='\t';
737 break;
738 case 'v': /* Vertical tab. */
739 c ='\v';
740 break;
741 case '"':
742 case '\\':
743 break;
744 default:
745 error (0, 0, _("warning: unrecognized escape `\\%c'"), c);
746 break;
748 putchar (c);
751 static void
752 print_it (char const *format, char const *filename,
753 void (*print_func) (char *, size_t, char, char const *, void const *),
754 void const *data)
756 /* Add 2 to accommodate our conversion of the stat `%s' format string
757 to the longer printf `%llu' one. */
758 enum
760 MAX_ADDITIONAL_BYTES =
761 (MAX (sizeof PRIdMAX,
762 MAX (sizeof PRIoMAX, MAX (sizeof PRIuMAX, sizeof PRIxMAX)))
763 - 1)
765 size_t n_alloc = strlen (format) + MAX_ADDITIONAL_BYTES + 1;
766 char *dest = xmalloc (n_alloc);
767 char const *b;
768 for (b = format; *b; b++)
770 switch (*b)
772 case '%':
774 size_t len = strspn (b + 1, "#-+.I 0123456789");
775 char const *fmt_char = b + len + 1;
776 memcpy (dest, b, len + 1);
778 b = fmt_char;
779 switch (*fmt_char)
781 case '\0':
782 --b;
783 /* fall through */
784 case '%':
785 if (0 < len)
787 dest[len + 1] = *fmt_char;
788 dest[len + 2] = '\0';
789 error (EXIT_FAILURE, 0, _("%s: invalid directive"),
790 quotearg_colon (dest));
792 putchar ('%');
793 break;
794 default:
795 print_func (dest, len + 1, *fmt_char, filename, data);
796 break;
798 break;
801 case '\\':
802 if ( ! interpret_backslash_escapes)
804 putchar ('\\');
805 break;
807 ++b;
808 if (isodigit (*b))
810 int esc_value = octtobin (*b);
811 int esc_length = 1; /* number of octal digits */
812 for (++b; esc_length < 3 && isodigit (*b);
813 ++esc_length, ++b)
815 esc_value = esc_value * 8 + octtobin (*b);
817 putchar (esc_value);
818 --b;
820 else if (*b == 'x' && isxdigit (to_uchar (b[1])))
822 int esc_value = hextobin (b[1]); /* Value of \xhh escape. */
823 /* A hexadecimal \xhh escape sequence must have
824 1 or 2 hex. digits. */
825 ++b;
826 if (isxdigit (to_uchar (b[1])))
828 ++b;
829 esc_value = esc_value * 16 + hextobin (*b);
831 putchar (esc_value);
833 else if (*b == '\0')
835 error (0, 0, _("warning: backslash at end of format"));
836 putchar ('\\');
837 /* Arrange to exit the loop. */
838 --b;
840 else
842 print_esc_char (*b);
844 break;
846 default:
847 putchar (*b);
848 break;
851 free (dest);
853 fputs (trailing_delim, stdout);
856 /* Stat the file system and print what we find. */
857 static bool
858 do_statfs (char const *filename, bool terse, char const *format)
860 STRUCT_STATVFS statfsbuf;
862 if (STREQ (filename, "-"))
864 error (0, 0, _("using %s to denote standard input does not work"
865 " in file system mode"), quote (filename));
866 return false;
869 if (STATFS (filename, &statfsbuf) != 0)
871 error (0, errno, _("cannot read file system information for %s"),
872 quote (filename));
873 return false;
876 if (format == NULL)
878 format = (terse
879 ? "%n %i %l %t %s %S %b %f %a %c %d\n"
880 : " File: \"%n\"\n"
881 " ID: %-8i Namelen: %-7l Type: %T\n"
882 "Block size: %-10s Fundamental block size: %S\n"
883 "Blocks: Total: %-10b Free: %-10f Available: %a\n"
884 "Inodes: Total: %-10c Free: %d\n");
887 print_it (format, filename, print_statfs, &statfsbuf);
888 return true;
891 /* stat the file and print what we find */
892 static bool
893 do_stat (char const *filename, bool terse, char const *format)
895 struct stat statbuf;
897 if (STREQ (filename, "-"))
899 if (fstat (STDIN_FILENO, &statbuf) != 0)
901 error (0, errno, _("cannot stat standard input"));
902 return false;
905 /* We can't use the shorter
906 (follow_links ? stat : lstat) (filename, &statbug)
907 since stat might be a function-like macro. */
908 else if ((follow_links
909 ? stat (filename, &statbuf)
910 : lstat (filename, &statbuf)) != 0)
912 error (0, errno, _("cannot stat %s"), quote (filename));
913 return false;
916 if (format == NULL)
918 if (terse)
920 format = "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %o\n";
922 else
924 /* Temporary hack to match original output until conditional
925 implemented. */
926 if (S_ISBLK (statbuf.st_mode) || S_ISCHR (statbuf.st_mode))
928 format =
929 " File: %N\n"
930 " Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
931 "Device: %Dh/%dd\tInode: %-10i Links: %-5h"
932 " Device type: %t,%T\n"
933 "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n"
934 "Access: %x\n" "Modify: %y\n" "Change: %z\n";
936 else
938 format =
939 " File: %N\n"
940 " Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
941 "Device: %Dh/%dd\tInode: %-10i Links: %h\n"
942 "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n"
943 "Access: %x\n" "Modify: %y\n" "Change: %z\n";
947 print_it (format, filename, print_stat, &statbuf);
948 return true;
951 void
952 usage (int status)
954 if (status != EXIT_SUCCESS)
955 fprintf (stderr, _("Try `%s --help' for more information.\n"),
956 program_name);
957 else
959 printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
960 fputs (_("\
961 Display file or file system status.\n\
963 -L, --dereference follow links\n\
964 -f, --file-system display file system status instead of file status\n\
965 "), stdout);
966 fputs (_("\
967 -c --format=FORMAT use the specified FORMAT instead of the default;\n\
968 output a newline after each use of FORMAT\n\
969 --printf=FORMAT like --format, but interpret backslash escapes,\n\
970 and do not output a mandatory trailing newline.\n\
971 If you want a newline, include \\n in FORMAT.\n\
972 -t, --terse print the information in terse form\n\
973 "), stdout);
974 fputs (HELP_OPTION_DESCRIPTION, stdout);
975 fputs (VERSION_OPTION_DESCRIPTION, stdout);
977 fputs (_("\n\
978 The valid format sequences for files (without --file-system):\n\
980 %a Access rights in octal\n\
981 %A Access rights in human readable form\n\
982 %b Number of blocks allocated (see %B)\n\
983 %B The size in bytes of each block reported by %b\n\
984 %C SELinux security context string\n\
985 "), stdout);
986 fputs (_("\
987 %d Device number in decimal\n\
988 %D Device number in hex\n\
989 %f Raw mode in hex\n\
990 %F File type\n\
991 %g Group ID of owner\n\
992 %G Group name of owner\n\
993 "), stdout);
994 fputs (_("\
995 %h Number of hard links\n\
996 %i Inode number\n\
997 %n File name\n\
998 %N Quoted file name with dereference if symbolic link\n\
999 %o I/O block size\n\
1000 %s Total size, in bytes\n\
1001 %t Major device type in hex\n\
1002 %T Minor device type in hex\n\
1003 "), stdout);
1004 fputs (_("\
1005 %u User ID of owner\n\
1006 %U User name of owner\n\
1007 %x Time of last access\n\
1008 %X Time of last access as seconds since Epoch\n\
1009 %y Time of last modification\n\
1010 %Y Time of last modification as seconds since Epoch\n\
1011 %z Time of last change\n\
1012 %Z Time of last change as seconds since Epoch\n\
1014 "), stdout);
1016 fputs (_("\
1017 Valid format sequences for file systems:\n\
1019 %a Free blocks available to non-superuser\n\
1020 %b Total data blocks in file system\n\
1021 %c Total file nodes in file system\n\
1022 %d Free file nodes in file system\n\
1023 %f Free blocks in file system\n\
1024 %C SELinux security context string\n\
1025 "), stdout);
1026 fputs (_("\
1027 %i File System ID in hex\n\
1028 %l Maximum length of filenames\n\
1029 %n File name\n\
1030 %s Block size (for faster transfers)\n\
1031 %S Fundamental block size (for block counts)\n\
1032 %t Type in hex\n\
1033 %T Type in human readable form\n\
1034 "), stdout);
1035 printf (USAGE_BUILTIN_WARNING, PROGRAM_NAME);
1036 emit_ancillary_info ();
1038 exit (status);
1042 main (int argc, char *argv[])
1044 int c;
1045 int i;
1046 bool fs = false;
1047 bool terse = false;
1048 char *format = NULL;
1049 bool ok = true;
1051 initialize_main (&argc, &argv);
1052 set_program_name (argv[0]);
1053 setlocale (LC_ALL, "");
1054 bindtextdomain (PACKAGE, LOCALEDIR);
1055 textdomain (PACKAGE);
1057 atexit (close_stdout);
1059 while ((c = getopt_long (argc, argv, "c:fLtZ", long_options, NULL)) != -1)
1061 switch (c)
1063 case PRINTF_OPTION:
1064 format = optarg;
1065 interpret_backslash_escapes = true;
1066 trailing_delim = "";
1067 break;
1069 case 'c':
1070 format = optarg;
1071 interpret_backslash_escapes = false;
1072 trailing_delim = "\n";
1073 break;
1075 case 'L':
1076 follow_links = true;
1077 break;
1079 case 'f':
1080 fs = true;
1081 break;
1083 case 't':
1084 terse = true;
1085 break;
1087 case 'Z': /* FIXME: remove in 2010 */
1088 /* Ignore, for compatibility with distributions
1089 that implemented this before upstream.
1090 But warn of impending removal. */
1091 error (0, 0,
1092 _("the --context (-Z) option is obsolete and will be removed\n"
1093 "in a future release"));
1094 break;
1096 case_GETOPT_HELP_CHAR;
1098 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1100 default:
1101 usage (EXIT_FAILURE);
1105 if (argc == optind)
1107 error (0, 0, _("missing operand"));
1108 usage (EXIT_FAILURE);
1111 for (i = optind; i < argc; i++)
1112 ok &= (fs
1113 ? do_statfs (argv[i], terse, format)
1114 : do_stat (argv[i], terse, format));
1116 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);