78df9c94840fe4ab2e0004205a8eb68972775e58
[oweals/busybox.git] / coreutils / stat.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * stat -- display file or file system status
4  *
5  * Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation.
6  * Copyright (C) 2005 by Erik Andersen <andersen@codepoet.org>
7  * Copyright (C) 2005 by Mike Frysinger <vapier@gentoo.org>
8  * Copyright (C) 2006 by Yoshinori Sato <ysato@users.sourceforge.jp>
9  *
10  * Written by Michael Meskes
11  * Taken from coreutils and turned into a busybox applet by Mike Frysinger
12  *
13  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14  */
15 //config:config STAT
16 //config:       bool "stat"
17 //config:       default y
18 //config:       help
19 //config:         display file or filesystem status.
20 //config:
21 //config:config FEATURE_STAT_FORMAT
22 //config:       bool "Enable custom formats (-c)"
23 //config:       default y
24 //config:       depends on STAT
25 //config:       help
26 //config:         Without this, stat will not support the '-c format' option where
27 //config:         users can pass a custom format string for output. This adds about
28 //config:         7k to a nonstatic build on amd64.
29 //config:
30 //config:config FEATURE_STAT_FILESYSTEM
31 //config:       bool "Enable display of filesystem status (-f)"
32 //config:       default y
33 //config:       depends on STAT
34 //config:       select PLATFORM_LINUX # statfs()
35 //config:       help
36 //config:         Without this, stat will not support the '-f' option to display
37 //config:         information about filesystem status.
38
39
40 //usage:#define stat_trivial_usage
41 //usage:       "[OPTIONS] FILE..."
42 //usage:#define stat_full_usage "\n\n"
43 //usage:       "Display file"
44 //usage:            IF_FEATURE_STAT_FILESYSTEM(" (default) or filesystem")
45 //usage:            " status\n"
46 //usage:        IF_FEATURE_STAT_FORMAT(
47 //usage:     "\n        -c FMT  Use the specified format"
48 //usage:        )
49 //usage:        IF_FEATURE_STAT_FILESYSTEM(
50 //usage:     "\n        -f      Display filesystem status"
51 //usage:        )
52 //usage:     "\n        -L      Follow links"
53 //usage:     "\n        -t      Terse display"
54 //usage:        IF_SELINUX(
55 //usage:     "\n        -Z      Print security context"
56 //usage:        )
57 //usage:        IF_FEATURE_STAT_FORMAT(
58 //usage:       "\n\nFMT sequences"IF_FEATURE_STAT_FILESYSTEM(" for files")":\n"
59 //usage:       " %a     Access rights in octal\n"
60 //usage:       " %A     Access rights in human readable form\n"
61 //usage:       " %b     Number of blocks allocated (see %B)\n"
62 //usage:       " %B     Size in bytes of each block reported by %b\n"
63 //usage:       " %d     Device number in decimal\n"
64 //usage:       " %D     Device number in hex\n"
65 //usage:       " %f     Raw mode in hex\n"
66 //usage:       " %F     File type\n"
67 //usage:       " %g     Group ID\n"
68 //usage:       " %G     Group name\n"
69 //usage:       " %h     Number of hard links\n"
70 //usage:       " %i     Inode number\n"
71 //usage:       " %n     File name\n"
72 //usage:       " %N     File name, with -> TARGET if symlink\n"
73 //usage:       " %o     I/O block size\n"
74 //usage:       " %s     Total size in bytes\n"
75 //usage:       " %t     Major device type in hex\n"
76 //usage:       " %T     Minor device type in hex\n"
77 //usage:       " %u     User ID\n"
78 //usage:       " %U     User name\n"
79 //usage:       " %x     Time of last access\n"
80 //usage:       " %X     Time of last access as seconds since Epoch\n"
81 //usage:       " %y     Time of last modification\n"
82 //usage:       " %Y     Time of last modification as seconds since Epoch\n"
83 //usage:       " %z     Time of last change\n"
84 //usage:       " %Z     Time of last change as seconds since Epoch\n"
85 //usage:        IF_FEATURE_STAT_FILESYSTEM(
86 //usage:       "\nFMT sequences for file systems:\n"
87 //usage:       " %a     Free blocks available to non-superuser\n"
88 //usage:       " %b     Total data blocks\n"
89 //usage:       " %c     Total file nodes\n"
90 //usage:       " %d     Free file nodes\n"
91 //usage:       " %f     Free blocks\n"
92 //usage:        IF_SELINUX(
93 //usage:       " %C     Security context in selinux\n"
94 //usage:        )
95 //usage:       " %i     File System ID in hex\n"
96 //usage:       " %l     Maximum length of filenames\n"
97 //usage:       " %n     File name\n"
98 //usage:       " %s     Block size (for faster transfer)\n"
99 //usage:       " %S     Fundamental block size (for block counts)\n"
100 //usage:       " %t     Type in hex\n"
101 //usage:       " %T     Type in human readable form"
102 //usage:        )
103 //usage:        )
104
105 #include "libbb.h"
106 #include "common_bufsiz.h"
107
108 enum {
109         OPT_TERSE       = (1 << 0),
110         OPT_DEREFERENCE = (1 << 1),
111         OPT_FILESYS     = (1 << 2) * ENABLE_FEATURE_STAT_FILESYSTEM,
112         OPT_SELINUX     = (1 << (2+ENABLE_FEATURE_STAT_FILESYSTEM)) * ENABLE_SELINUX,
113 };
114
115 #if ENABLE_FEATURE_STAT_FORMAT
116 typedef bool (*statfunc_ptr)(const char *, const char *);
117 #else
118 typedef bool (*statfunc_ptr)(const char *);
119 #endif
120
121 static const char *file_type(const struct stat *st)
122 {
123         /* See POSIX 1003.1-2001 XCU Table 4-8 lines 17093-17107
124          * for some of these formats.
125          * To keep diagnostics grammatical in English, the
126          * returned string must start with a consonant.
127          */
128         if (S_ISREG(st->st_mode))  return st->st_size == 0 ? "regular empty file" : "regular file";
129         if (S_ISDIR(st->st_mode))  return "directory";
130         if (S_ISBLK(st->st_mode))  return "block special file";
131         if (S_ISCHR(st->st_mode))  return "character special file";
132         if (S_ISFIFO(st->st_mode)) return "fifo";
133         if (S_ISLNK(st->st_mode))  return "symbolic link";
134         if (S_ISSOCK(st->st_mode)) return "socket";
135 #ifdef S_TYPEISMQ
136         if (S_TYPEISMQ(st))        return "message queue";
137 #endif
138 #ifdef S_TYPEISSEM
139         if (S_TYPEISSEM(st))       return "semaphore";
140 #endif
141 #ifdef S_TYPEISSHM
142         if (S_TYPEISSHM(st))       return "shared memory object";
143 #endif
144 #ifdef S_TYPEISTMO
145         if (S_TYPEISTMO(st))       return "typed memory object";
146 #endif
147         return "weird file";
148 }
149
150 static const char *human_time(time_t t)
151 {
152         /* Old
153         static char *str;
154         str = ctime(&t);
155         str[strlen(str)-1] = '\0';
156         return str;
157         */
158         /* coreutils 6.3 compat: */
159
160         /*static char buf[sizeof("YYYY-MM-DD HH:MM:SS.000000000")] ALIGN1;*/
161 #define        buf bb_common_bufsiz1
162 #define sizeof_buf COMMON_BUFSIZE
163
164         strcpy(strftime_YYYYMMDDHHMMSS(buf, sizeof_buf, &t), ".000000000");
165         return buf;
166 #undef buf
167 }
168
169 #if ENABLE_FEATURE_STAT_FILESYSTEM
170 /* Return the type of the specified file system.
171  * Some systems have statfvs.f_basetype[FSTYPSZ]. (AIX, HP-UX, and Solaris)
172  * Others have statfs.f_fstypename[MFSNAMELEN]. (NetBSD 1.5.2)
173  * Still others have neither and have to get by with f_type (Linux).
174  */
175 static const char *human_fstype(uint32_t f_type)
176 {
177         static const struct types {
178                 uint32_t type;
179                 const char *const fs;
180         } humantypes[] = {
181                 { 0xADFF,     "affs" },
182                 { 0x1Cd1,     "devpts" },
183                 { 0x137D,     "ext" },
184                 { 0xEF51,     "ext2" },
185                 { 0xEF53,     "ext2/ext3" },
186                 { 0x3153464a, "jfs" },
187                 { 0x58465342, "xfs" },
188                 { 0xF995E849, "hpfs" },
189                 { 0x9660,     "isofs" },
190                 { 0x4000,     "isofs" },
191                 { 0x4004,     "isofs" },
192                 { 0x137F,     "minix" },
193                 { 0x138F,     "minix (30 char.)" },
194                 { 0x2468,     "minix v2" },
195                 { 0x2478,     "minix v2 (30 char.)" },
196                 { 0x4d44,     "msdos" },
197                 { 0x4006,     "fat" },
198                 { 0x564c,     "novell" },
199                 { 0x6969,     "nfs" },
200                 { 0x9fa0,     "proc" },
201                 { 0x517B,     "smb" },
202                 { 0x012FF7B4, "xenix" },
203                 { 0x012FF7B5, "sysv4" },
204                 { 0x012FF7B6, "sysv2" },
205                 { 0x012FF7B7, "coh" },
206                 { 0x00011954, "ufs" },
207                 { 0x012FD16D, "xia" },
208                 { 0x5346544e, "ntfs" },
209                 { 0x1021994,  "tmpfs" },
210                 { 0x52654973, "reiserfs" },
211                 { 0x28cd3d45, "cramfs" },
212                 { 0x7275,     "romfs" },
213                 { 0x858458f6, "romfs" },
214                 { 0x73717368, "squashfs" },
215                 { 0x62656572, "sysfs" },
216                 { 0, "UNKNOWN" }
217         };
218
219         int i;
220
221         for (i = 0; humantypes[i].type; ++i)
222                 if (humantypes[i].type == f_type)
223                         break;
224         return humantypes[i].fs;
225 }
226
227 /* "man statfs" says that statfsbuf->f_fsid is a mess */
228 /* coreutils treats it as an array of ints, most significant first */
229 static unsigned long long get_f_fsid(const struct statfs *statfsbuf)
230 {
231         const unsigned *p = (const void*) &statfsbuf->f_fsid;
232         unsigned sz = sizeof(statfsbuf->f_fsid) / sizeof(unsigned);
233         unsigned long long r = 0;
234
235         do
236                 r = (r << (sizeof(unsigned)*8)) | *p++;
237         while (--sz > 0);
238         return r;
239 }
240 #endif  /* FEATURE_STAT_FILESYSTEM */
241
242 #if ENABLE_FEATURE_STAT_FORMAT
243 static void strcatc(char *str, char c)
244 {
245         int len = strlen(str);
246         str[len++] = c;
247         str[len] = '\0';
248 }
249
250 static void printfs(char *pformat, const char *msg)
251 {
252         strcatc(pformat, 's');
253         printf(pformat, msg);
254 }
255
256 #if ENABLE_FEATURE_STAT_FILESYSTEM
257 /* print statfs info */
258 static void FAST_FUNC print_statfs(char *pformat, const char m,
259                 const char *const filename, const void *data
260                 IF_SELINUX(, security_context_t scontext))
261 {
262         const struct statfs *statfsbuf = data;
263         if (m == 'n') {
264                 printfs(pformat, filename);
265         } else if (m == 'i') {
266                 strcat(pformat, "llx");
267                 printf(pformat, get_f_fsid(statfsbuf));
268         } else if (m == 'l') {
269                 strcat(pformat, "lu");
270                 printf(pformat, (unsigned long) statfsbuf->f_namelen);
271         } else if (m == 't') {
272                 strcat(pformat, "lx");
273                 printf(pformat, (unsigned long) statfsbuf->f_type); /* no equiv */
274         } else if (m == 'T') {
275                 printfs(pformat, human_fstype(statfsbuf->f_type));
276         } else if (m == 'b') {
277                 strcat(pformat, "llu");
278                 printf(pformat, (unsigned long long) statfsbuf->f_blocks);
279         } else if (m == 'f') {
280                 strcat(pformat, "llu");
281                 printf(pformat, (unsigned long long) statfsbuf->f_bfree);
282         } else if (m == 'a') {
283                 strcat(pformat, "llu");
284                 printf(pformat, (unsigned long long) statfsbuf->f_bavail);
285         } else if (m == 's' || m == 'S') {
286                 strcat(pformat, "lu");
287                 printf(pformat, (unsigned long) statfsbuf->f_bsize);
288         } else if (m == 'c') {
289                 strcat(pformat, "llu");
290                 printf(pformat, (unsigned long long) statfsbuf->f_files);
291         } else if (m == 'd') {
292                 strcat(pformat, "llu");
293                 printf(pformat, (unsigned long long) statfsbuf->f_ffree);
294 # if ENABLE_SELINUX
295         } else if (m == 'C' && (option_mask32 & OPT_SELINUX)) {
296                 printfs(pformat, scontext);
297 # endif
298         } else {
299                 strcatc(pformat, 'c');
300                 printf(pformat, m);
301         }
302 }
303 #endif
304
305 /* print stat info */
306 static void FAST_FUNC print_stat(char *pformat, const char m,
307                 const char *const filename, const void *data
308                 IF_SELINUX(, security_context_t scontext))
309 {
310 #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
311         struct stat *statbuf = (struct stat *) data;
312         struct passwd *pw_ent;
313         struct group *gw_ent;
314
315         if (m == 'n') {
316                 printfs(pformat, filename);
317         } else if (m == 'N') {
318                 strcatc(pformat, 's');
319                 if (S_ISLNK(statbuf->st_mode)) {
320                         char *linkname = xmalloc_readlink_or_warn(filename);
321                         if (linkname == NULL)
322                                 return;
323                         printf("'%s' -> '%s'", filename, linkname);
324                         free(linkname);
325                 } else {
326                         printf(pformat, filename);
327                 }
328         } else if (m == 'd') {
329                 strcat(pformat, "llu");
330                 printf(pformat, (unsigned long long) statbuf->st_dev);
331         } else if (m == 'D') {
332                 strcat(pformat, "llx");
333                 printf(pformat, (unsigned long long) statbuf->st_dev);
334         } else if (m == 'i') {
335                 strcat(pformat, "llu");
336                 printf(pformat, (unsigned long long) statbuf->st_ino);
337         } else if (m == 'a') {
338                 strcat(pformat, "lo");
339                 printf(pformat, (unsigned long) (statbuf->st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)));
340         } else if (m == 'A') {
341                 printfs(pformat, bb_mode_string(statbuf->st_mode));
342         } else if (m == 'f') {
343                 strcat(pformat, "lx");
344                 printf(pformat, (unsigned long) statbuf->st_mode);
345         } else if (m == 'F') {
346                 printfs(pformat, file_type(statbuf));
347         } else if (m == 'h') {
348                 strcat(pformat, "lu");
349                 printf(pformat, (unsigned long) statbuf->st_nlink);
350         } else if (m == 'u') {
351                 strcat(pformat, "lu");
352                 printf(pformat, (unsigned long) statbuf->st_uid);
353         } else if (m == 'U') {
354                 pw_ent = getpwuid(statbuf->st_uid);
355                 printfs(pformat, (pw_ent != NULL) ? pw_ent->pw_name : "UNKNOWN");
356         } else if (m == 'g') {
357                 strcat(pformat, "lu");
358                 printf(pformat, (unsigned long) statbuf->st_gid);
359         } else if (m == 'G') {
360                 gw_ent = getgrgid(statbuf->st_gid);
361                 printfs(pformat, (gw_ent != NULL) ? gw_ent->gr_name : "UNKNOWN");
362         } else if (m == 't') {
363                 strcat(pformat, "lx");
364                 printf(pformat, (unsigned long) major(statbuf->st_rdev));
365         } else if (m == 'T') {
366                 strcat(pformat, "lx");
367                 printf(pformat, (unsigned long) minor(statbuf->st_rdev));
368         } else if (m == 's') {
369                 strcat(pformat, "llu");
370                 printf(pformat, (unsigned long long) statbuf->st_size);
371         } else if (m == 'B') {
372                 strcat(pformat, "lu");
373                 printf(pformat, (unsigned long) 512); //ST_NBLOCKSIZE
374         } else if (m == 'b') {
375                 strcat(pformat, "llu");
376                 printf(pformat, (unsigned long long) statbuf->st_blocks);
377         } else if (m == 'o') {
378                 strcat(pformat, "lu");
379                 printf(pformat, (unsigned long) statbuf->st_blksize);
380         } else if (m == 'x') {
381                 printfs(pformat, human_time(statbuf->st_atime));
382         } else if (m == 'X') {
383                 strcat(pformat, TYPE_SIGNED(time_t) ? "ld" : "lu");
384                 /* note: (unsigned long) would be wrong:
385                  * imagine (unsigned long64)int32 */
386                 printf(pformat, (long) statbuf->st_atime);
387         } else if (m == 'y') {
388                 printfs(pformat, human_time(statbuf->st_mtime));
389         } else if (m == 'Y') {
390                 strcat(pformat, TYPE_SIGNED(time_t) ? "ld" : "lu");
391                 printf(pformat, (long) statbuf->st_mtime);
392         } else if (m == 'z') {
393                 printfs(pformat, human_time(statbuf->st_ctime));
394         } else if (m == 'Z') {
395                 strcat(pformat, TYPE_SIGNED(time_t) ? "ld" : "lu");
396                 printf(pformat, (long) statbuf->st_ctime);
397 # if ENABLE_SELINUX
398         } else if (m == 'C' && (option_mask32 & OPT_SELINUX)) {
399                 printfs(pformat, scontext);
400 # endif
401         } else {
402                 strcatc(pformat, 'c');
403                 printf(pformat, m);
404         }
405 }
406
407 static void print_it(const char *masterformat,
408                 const char *filename,
409                 void FAST_FUNC (*print_func)(char*, char, const char*, const void* IF_SELINUX(, security_context_t scontext)),
410                 const void *data
411                 IF_SELINUX(, security_context_t scontext))
412 {
413         /* Create a working copy of the format string */
414         char *format = xstrdup(masterformat);
415         /* Add 2 to accommodate our conversion of the stat '%s' format string
416          * to the printf '%llu' one.  */
417         char *dest = xmalloc(strlen(format) + 2 + 1);
418         char *b;
419
420         b = format;
421         while (b) {
422                 /* Each iteration finds next %spec,
423                  * prints preceding string and handles found %spec
424                  */
425                 size_t len;
426                 char *p = strchr(b, '%');
427                 if (!p) {
428                         /* coreutils 6.3 always prints newline at the end */
429                         /*fputs(b, stdout);*/
430                         puts(b);
431                         break;
432                 }
433
434                 /* dest = "%<modifiers>" */
435                 len = 1 + strspn(p + 1, "#-+.I 0123456789");
436                 memcpy(dest, p, len);
437                 dest[len] = '\0';
438
439                 /* print preceding string */
440                 *p = '\0';
441                 fputs(b, stdout);
442
443                 p += len;
444                 b = p + 1;
445                 switch (*p) {
446                 case '\0':
447                         b = NULL;
448                         /* fall through */
449                 case '%':
450                         bb_putchar('%');
451                         break;
452                 default:
453                         /* Completes "%<modifiers>" with specifier and printfs */
454                         print_func(dest, *p, filename, data IF_SELINUX(,scontext));
455                         break;
456                 }
457         }
458
459         free(format);
460         free(dest);
461 }
462 #endif  /* FEATURE_STAT_FORMAT */
463
464 #if ENABLE_FEATURE_STAT_FILESYSTEM
465 /* Stat the file system and print what we find.  */
466 #if !ENABLE_FEATURE_STAT_FORMAT
467 #define do_statfs(filename, format) do_statfs(filename)
468 #endif
469 static bool do_statfs(const char *filename, const char *format)
470 {
471         struct statfs statfsbuf;
472 #if !ENABLE_FEATURE_STAT_FORMAT
473         const char *format;
474 #endif
475 #if ENABLE_SELINUX
476         security_context_t scontext = NULL;
477
478         if (option_mask32 & OPT_SELINUX) {
479                 if ((option_mask32 & OPT_DEREFERENCE
480                      ? lgetfilecon(filename, &scontext)
481                      : getfilecon(filename, &scontext)
482                     ) < 0
483                 ) {
484                         bb_simple_perror_msg(filename);
485                         return 0;
486                 }
487         }
488 #endif
489         if (statfs(filename, &statfsbuf) != 0) {
490                 bb_perror_msg("can't read file system information for '%s'", filename);
491                 return 0;
492         }
493
494 #if ENABLE_FEATURE_STAT_FORMAT
495         if (format == NULL) {
496 # if !ENABLE_SELINUX
497                 format = (option_mask32 & OPT_TERSE
498                         ? "%n %i %l %t %s %b %f %a %c %d\n"
499                         : "  File: \"%n\"\n"
500                           "    ID: %-8i Namelen: %-7l Type: %T\n"
501                           "Block size: %-10s\n"
502                           "Blocks: Total: %-10b Free: %-10f Available: %a\n"
503                           "Inodes: Total: %-10c Free: %d");
504 # else
505                 format = (option_mask32 & OPT_TERSE
506                         ? (option_mask32 & OPT_SELINUX ? "%n %i %l %t %s %b %f %a %c %d %C\n":
507                         "%n %i %l %t %s %b %f %a %c %d\n")
508                         : (option_mask32 & OPT_SELINUX ?
509                         "  File: \"%n\"\n"
510                         "    ID: %-8i Namelen: %-7l Type: %T\n"
511                         "Block size: %-10s\n"
512                         "Blocks: Total: %-10b Free: %-10f Available: %a\n"
513                         "Inodes: Total: %-10c Free: %d"
514                         "  S_context: %C\n":
515                         "  File: \"%n\"\n"
516                         "    ID: %-8i Namelen: %-7l Type: %T\n"
517                         "Block size: %-10s\n"
518                         "Blocks: Total: %-10b Free: %-10f Available: %a\n"
519                         "Inodes: Total: %-10c Free: %d\n")
520                         );
521 # endif /* SELINUX */
522         }
523         print_it(format, filename, print_statfs, &statfsbuf IF_SELINUX(, scontext));
524 #else /* FEATURE_STAT_FORMAT */
525         format = (option_mask32 & OPT_TERSE
526                 ? "%s %llx %lu "
527                 : "  File: \"%s\"\n"
528                   "    ID: %-8llx Namelen: %-7lu ");
529         printf(format,
530                filename,
531                get_f_fsid(&statfsbuf),
532                statfsbuf.f_namelen);
533
534         if (option_mask32 & OPT_TERSE)
535                 printf("%lx ", (unsigned long) statfsbuf.f_type);
536         else
537                 printf("Type: %s\n", human_fstype(statfsbuf.f_type));
538
539 # if !ENABLE_SELINUX
540         format = (option_mask32 & OPT_TERSE
541                 ? "%lu %llu %llu %llu %llu %llu\n"
542                 : "Block size: %-10lu\n"
543                   "Blocks: Total: %-10llu Free: %-10llu Available: %llu\n"
544                   "Inodes: Total: %-10llu Free: %llu\n");
545         printf(format,
546                (unsigned long) statfsbuf.f_bsize,
547                (unsigned long long) statfsbuf.f_blocks,
548                (unsigned long long) statfsbuf.f_bfree,
549                (unsigned long long) statfsbuf.f_bavail,
550                (unsigned long long) statfsbuf.f_files,
551                (unsigned long long) statfsbuf.f_ffree);
552 # else
553         format = (option_mask32 & OPT_TERSE
554                 ? (option_mask32 & OPT_SELINUX ? "%lu %llu %llu %llu %llu %llu %C\n" : "%lu %llu %llu %llu %llu %llu\n")
555                 : (option_mask32 & OPT_SELINUX
556                         ?       "Block size: %-10lu\n"
557                                 "Blocks: Total: %-10llu Free: %-10llu Available: %llu\n"
558                                 "Inodes: Total: %-10llu Free: %llu"
559                                 "S_context: %C\n"
560                         :       "Block size: %-10lu\n"
561                                 "Blocks: Total: %-10llu Free: %-10llu Available: %llu\n"
562                                 "Inodes: Total: %-10llu Free: %llu\n"
563                         )
564                 );
565         printf(format,
566                 (unsigned long) statfsbuf.f_bsize,
567                 (unsigned long long) statfsbuf.f_blocks,
568                 (unsigned long long) statfsbuf.f_bfree,
569                 (unsigned long long) statfsbuf.f_bavail,
570                 (unsigned long long) statfsbuf.f_files,
571                 (unsigned long long) statfsbuf.f_ffree,
572                 scontext);
573
574         if (scontext)
575                 freecon(scontext);
576 # endif
577 #endif  /* FEATURE_STAT_FORMAT */
578         return 1;
579 }
580 #endif  /* FEATURE_STAT_FILESYSTEM */
581
582 /* stat the file and print what we find */
583 #if !ENABLE_FEATURE_STAT_FORMAT
584 #define do_stat(filename, format) do_stat(filename)
585 #endif
586 static bool do_stat(const char *filename, const char *format)
587 {
588         struct stat statbuf;
589 #if ENABLE_SELINUX
590         security_context_t scontext = NULL;
591
592         if (option_mask32 & OPT_SELINUX) {
593                 if ((option_mask32 & OPT_DEREFERENCE
594                      ? lgetfilecon(filename, &scontext)
595                      : getfilecon(filename, &scontext)
596                     ) < 0
597                 ) {
598                         bb_simple_perror_msg(filename);
599                         return 0;
600                 }
601         }
602 #endif
603         if ((option_mask32 & OPT_DEREFERENCE ? stat : lstat) (filename, &statbuf) != 0) {
604                 bb_perror_msg("can't stat '%s'", filename);
605                 return 0;
606         }
607
608 #if ENABLE_FEATURE_STAT_FORMAT
609         if (format == NULL) {
610 # if !ENABLE_SELINUX
611                 if (option_mask32 & OPT_TERSE) {
612                         format = "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %o";
613                 } else {
614                         if (S_ISBLK(statbuf.st_mode) || S_ISCHR(statbuf.st_mode)) {
615                                 format =
616                                         "  File: %N\n"
617                                         "  Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
618                                         "Device: %Dh/%dd\tInode: %-10i  Links: %-5h"
619                                         " Device type: %t,%T\n"
620                                         "Access: (%04a/%10.10A)  Uid: (%5u/%8U)   Gid: (%5g/%8G)\n"
621                                         "Access: %x\n" "Modify: %y\n" "Change: %z\n";
622                         } else {
623                                 format =
624                                         "  File: %N\n"
625                                         "  Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
626                                         "Device: %Dh/%dd\tInode: %-10i  Links: %h\n"
627                                         "Access: (%04a/%10.10A)  Uid: (%5u/%8U)   Gid: (%5g/%8G)\n"
628                                         "Access: %x\n" "Modify: %y\n" "Change: %z\n";
629                         }
630                 }
631 # else
632                 if (option_mask32 & OPT_TERSE) {
633                         format = (option_mask32 & OPT_SELINUX ?
634                                 "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %o %C\n"
635                                 :
636                                 "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %o\n"
637                                 );
638                 } else {
639                         if (S_ISBLK(statbuf.st_mode) || S_ISCHR(statbuf.st_mode)) {
640                                 format = (option_mask32 & OPT_SELINUX ?
641                                         "  File: %N\n"
642                                         "  Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
643                                         "Device: %Dh/%dd\tInode: %-10i  Links: %-5h"
644                                         " Device type: %t,%T\n"
645                                         "Access: (%04a/%10.10A)  Uid: (%5u/%8U)   Gid: (%5g/%8G)\n"
646                                         "   S_Context: %C\n"
647                                         "Access: %x\n" "Modify: %y\n" "Change: %z\n"
648                                         :
649                                         "  File: %N\n"
650                                         "  Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
651                                         "Device: %Dh/%dd\tInode: %-10i  Links: %-5h"
652                                         " Device type: %t,%T\n"
653                                         "Access: (%04a/%10.10A)  Uid: (%5u/%8U)   Gid: (%5g/%8G)\n"
654                                         "Access: %x\n" "Modify: %y\n" "Change: %z\n"
655                                         );
656                         } else {
657                                 format = (option_mask32 & OPT_SELINUX ?
658                                         "  File: %N\n"
659                                         "  Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
660                                         "Device: %Dh/%dd\tInode: %-10i  Links: %h\n"
661                                         "Access: (%04a/%10.10A)  Uid: (%5u/%8U)   Gid: (%5g/%8G)\n"
662                                         "S_Context: %C\n"
663                                         "Access: %x\n" "Modify: %y\n" "Change: %z\n"
664                                         :
665                                         "  File: %N\n"
666                                         "  Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n"
667                                         "Device: %Dh/%dd\tInode: %-10i  Links: %h\n"
668                                         "Access: (%04a/%10.10A)  Uid: (%5u/%8U)   Gid: (%5g/%8G)\n"
669                                         "Access: %x\n" "Modify: %y\n" "Change: %z\n"
670                                         );
671                         }
672                 }
673 # endif
674         }
675         print_it(format, filename, print_stat, &statbuf IF_SELINUX(, scontext));
676 #else   /* FEATURE_STAT_FORMAT */
677         if (option_mask32 & OPT_TERSE) {
678                 printf("%s %llu %llu %lx %lu %lu %llx %llu %lu %lx %lx %lu %lu %lu %lu"
679                        IF_NOT_SELINUX("\n"),
680                        filename,
681                        (unsigned long long) statbuf.st_size,
682                        (unsigned long long) statbuf.st_blocks,
683                        (unsigned long) statbuf.st_mode,
684                        (unsigned long) statbuf.st_uid,
685                        (unsigned long) statbuf.st_gid,
686                        (unsigned long long) statbuf.st_dev,
687                        (unsigned long long) statbuf.st_ino,
688                        (unsigned long) statbuf.st_nlink,
689                        (unsigned long) major(statbuf.st_rdev),
690                        (unsigned long) minor(statbuf.st_rdev),
691                        (unsigned long) statbuf.st_atime,
692                        (unsigned long) statbuf.st_mtime,
693                        (unsigned long) statbuf.st_ctime,
694                        (unsigned long) statbuf.st_blksize
695                 );
696 # if ENABLE_SELINUX
697                 if (option_mask32 & OPT_SELINUX)
698                         printf(" %s\n", scontext);
699                 else
700                         bb_putchar('\n');
701 # endif
702         } else {
703                 char *linkname = NULL;
704                 struct passwd *pw_ent;
705                 struct group *gw_ent;
706
707                 gw_ent = getgrgid(statbuf.st_gid);
708                 pw_ent = getpwuid(statbuf.st_uid);
709
710                 if (S_ISLNK(statbuf.st_mode))
711                         linkname = xmalloc_readlink_or_warn(filename);
712                 if (linkname) {
713                         printf("  File: '%s' -> '%s'\n", filename, linkname);
714                         free(linkname);
715                 } else {
716                         printf("  File: '%s'\n", filename);
717                 }
718
719                 printf("  Size: %-10llu\tBlocks: %-10llu IO Block: %-6lu %s\n"
720                        "Device: %llxh/%llud\tInode: %-10llu  Links: %-5lu",
721                        (unsigned long long) statbuf.st_size,
722                        (unsigned long long) statbuf.st_blocks,
723                        (unsigned long) statbuf.st_blksize,
724                        file_type(&statbuf),
725                        (unsigned long long) statbuf.st_dev,
726                        (unsigned long long) statbuf.st_dev,
727                        (unsigned long long) statbuf.st_ino,
728                        (unsigned long) statbuf.st_nlink);
729                 if (S_ISBLK(statbuf.st_mode) || S_ISCHR(statbuf.st_mode))
730                         printf(" Device type: %lx,%lx\n",
731                                (unsigned long) major(statbuf.st_rdev),
732                                (unsigned long) minor(statbuf.st_rdev));
733                 else
734                         bb_putchar('\n');
735                 printf("Access: (%04lo/%10.10s)  Uid: (%5lu/%8s)   Gid: (%5lu/%8s)\n",
736                        (unsigned long) (statbuf.st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)),
737                        bb_mode_string(statbuf.st_mode),
738                        (unsigned long) statbuf.st_uid,
739                        (pw_ent != NULL) ? pw_ent->pw_name : "UNKNOWN",
740                        (unsigned long) statbuf.st_gid,
741                        (gw_ent != NULL) ? gw_ent->gr_name : "UNKNOWN");
742 # if ENABLE_SELINUX
743                 if (option_mask32 & OPT_SELINUX)
744                         printf("   S_Context: %s\n", scontext);
745 # endif
746                 printf("Access: %s\n", human_time(statbuf.st_atime));
747                 printf("Modify: %s\n", human_time(statbuf.st_mtime));
748                 printf("Change: %s\n", human_time(statbuf.st_ctime));
749         }
750 #endif  /* FEATURE_STAT_FORMAT */
751         return 1;
752 }
753
754 int stat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
755 int stat_main(int argc UNUSED_PARAM, char **argv)
756 {
757         IF_FEATURE_STAT_FORMAT(char *format = NULL;)
758         int i;
759         int ok;
760         unsigned opts;
761         statfunc_ptr statfunc = do_stat;
762
763         opt_complementary = "-1"; /* min one arg */
764         opts = getopt32(argv, "tL"
765                 IF_FEATURE_STAT_FILESYSTEM("f")
766                 IF_SELINUX("Z")
767                 IF_FEATURE_STAT_FORMAT("c:", &format)
768         );
769 #if ENABLE_FEATURE_STAT_FILESYSTEM
770         if (opts & OPT_FILESYS) /* -f */
771                 statfunc = do_statfs;
772 #endif
773 #if ENABLE_SELINUX
774         if (opts & OPT_SELINUX) {
775                 selinux_or_die();
776         }
777 #endif
778         ok = 1;
779         argv += optind;
780         for (i = 0; argv[i]; ++i)
781                 ok &= statfunc(argv[i] IF_FEATURE_STAT_FORMAT(, format));
782
783         return (ok ? EXIT_SUCCESS : EXIT_FAILURE);
784 }