Whamcloud - gitweb
LU-12511 utils: Move utilies specific values out of Lustre UAPI headers
[fs/lustre-release.git] / lustre / tests / statx.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * All rights reserved. This program and the accompanying materials
7  * are made available under the terms of the GNU Lesser General Public License
8  * (LGPL) version 2.1 or (at your discretion) any later version.
9  * (LGPL) version 2.1 accompanies this distribution, and is available at
10  * http://www.gnu.org/licenses/lgpl-2.1.html
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * LGPL HEADER END
18  */
19 /*
20  * Copyright (c) 2019, DDN Storage Corporation.
21  */
22 /*
23  * This file is part of Lustre, http://www.lustre.org/
24  */
25 /*
26  *
27  * Test for Lustre statx().
28  * It uses some code in coreutils ('ls.c' and 'stat.c') for reference.
29  *
30  * Author: Qian Yingjin <qian@ddn.com>
31  */
32 #define _ATFILE_SOURCE
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <getopt.h>
37 #include <limits.h>
38 #include <unistd.h>
39 #include <ctype.h>
40 #include <errno.h>
41 #include <time.h>
42 #include <sys/time.h>
43 #include <pwd.h>
44 #include <grp.h>
45 #include <dirent.h>
46 #include <sys/syscall.h>
47 #include <sys/types.h>
48 #include <sys/param.h>
49 #include <sys/sysmacros.h>
50 #include <inttypes.h>
51 #include <fcntl.h>
52 #include <locale.h>
53 #include <libiberty.h>
54 #include <linux/lustre/lustre_user.h>
55
56 #ifdef HAVE_SELINUX
57 #include <selinux/selinux.h>
58 #endif
59
60 /* Factor out some of the common --help and --version processing code. */
61
62 /* These enum values cannot possibly conflict with the option values
63  * ordinarily used by commands, including CHAR_MAX + 1, etc.  Avoid
64  * CHAR_MIN - 1, as it may equal -1, the getopt end-of-options value.
65  */
66 enum {
67         PRINTF_OPTION = (CHAR_MAX + 1),
68         GETOPT_HELP_CHAR = (CHAR_MIN - 2),
69         GETOPT_VERSION_CHAR = (CHAR_MIN - 3)
70 };
71
72 static bool o_quiet;
73
74 #ifdef __NR_statx
75 #ifndef HAVE_STATX
76
77 #define AT_STATX_SYNC_TYPE      0x6000
78 #define AT_STATX_FORCE_SYNC     0x2000
79 #define AT_STATX_DONT_SYNC      0x4000
80
81 static __attribute__((unused))
82 ssize_t statx(int dfd, const char *filename, int flags,
83               unsigned int mask, struct statx *buffer)
84 {
85         return syscall(__NR_statx, dfd, filename, flags, mask, buffer);
86 }
87 #endif /* HAVE_STATX */
88
89 /* coreutils/lib/intprops.h */
90 #define _GL_SIGNED_TYPE_OR_EXPR(t) TYPE_SIGNED(__typeof__(t))
91
92 /* Bound on length of the string representing an unsigned integer
93  * value representable in B bits.  log10 (2.0) < 146/485.  The
94  * smallest value of B where this bound is not tight is 2621.
95  */
96 #define INT_BITS_STRLEN_BOUND(b) (((b) * 146 + 484) / 485)
97
98 /* The width in bits of the integer type or expression T.
99  * Do not evaluate T.
100  * Padding bits are not supported; this is checked at compile-time below.
101  */
102 #define TYPE_WIDTH(t) (sizeof(t) * CHAR_BIT)
103
104 /* Bound on length of the string representing an integer type or expression T.
105  * Subtract 1 for the sign bit if T is signed, and then add 1 more for
106  * a minus sign if needed.
107  *
108  * Because _GL_SIGNED_TYPE_OR_EXPR sometimes returns 1 when its argument is
109  * unsigned, this macro may overestimate the true bound by one byte when
110  * applied to unsigned types of size 2, 4, 16, ... bytes.
111  */
112 #define INT_STRLEN_BOUND(t)                                     \
113         (INT_BITS_STRLEN_BOUND(TYPE_WIDTH(t) - _GL_SIGNED_TYPE_OR_EXPR(t)) \
114         + _GL_SIGNED_TYPE_OR_EXPR(t))
115
116 /* Bound on buffer size needed to represent an integer type or expression T,
117  * including the terminating null.
118  */
119 #define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND(t) + 1)
120
121 /* The maximum and minimum values for the integer type T.  */
122 #define TYPE_MINIMUM(t) ((t)~TYPE_MAXIMUM(t))
123 #define TYPE_MAXIMUM(t)                                         \
124         ((t) (!TYPE_SIGNED(t)                                   \
125         ? (t)-1                                         \
126         : ((((t)1 << (TYPE_WIDTH(t) - 2)) - 1) * 2 + 1)))
127
128 static bool o_dir_list;
129 static bool long_format; /* use a long listing format */
130
131 /* Current time in seconds and nanoseconds since 1970, updated as
132  * needed when deciding whether a file is recent.
133  */
134 static struct timespec current_time;
135
136 /* FIXME: these are used by printf.c, too */
137 #define isodigit(c) ('0' <= (c) && (c) <= '7')
138 #define octtobin(c) ((c) - '0')
139 #define hextobin(c) ((c) >= 'a' && (c) <= 'f' ? (c) - 'a' + 10 : \
140                      (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : (c) - '0')
141
142 #define ISDIGIT(c) ((unsigned int)(c) - '0' <= 9)
143
144 /* True if the real type T is signed.  */
145 #define TYPE_SIGNED(t) (!((t)0 < (t)-1))
146
147 static char const digits[] = "0123456789";
148
149 /* Flags that are portable for use in printf, for at least one
150  * conversion specifier; make_format removes unportable flags as
151  * needed for particular specifiers.  The glibc 2.2 extension "I" is
152  * listed here; it is removed by make_format because it has undefined
153  * behavior elsewhere and because it is incompatible with
154  * out_epoch_sec.
155  */
156 static char const printf_flags[] = "'-+ #0I";
157
158 /* Formats for the --terse option. */
159 static char const fmt_terse_fs[] = "%n %i %l %t %s %S %b %f %a %c %d\n";
160 static char const fmt_terse_regular[] = "%n %s %b %f %u %g %D %i %h %t %T"
161                                         " %X %Y %Z %W %o\n";
162 static char const fmt_terse_selinux[] = "%n %s %b %f %u %g %D %i %h %t %T"
163                                         " %X %Y %Z %W %o %C\n";
164
165 static char *format;
166
167 /* Whether to follow symbolic links;  True for --dereference (-L).  */
168 static bool follow_links;
169
170 /* Whether to interpret backslash-escape sequences.
171  * True for --printf=FMT, not for --format=FMT (-c).
172  */
173 static bool interpret_backslash_escapes;
174
175 /* The trailing delimiter string:
176  * "" for --printf=FMT, "\n" for --format=FMT (-c).
177  */
178 static char const *trailing_delim = "";
179
180 /* The representation of the decimal point in the current locale.  */
181 static char const *decimal_point;
182 static size_t decimal_point_len;
183
184 /* Convert a possibly-signed character to an unsigned character.  This is
185  * a bit safer than casting to unsigned char, since it catches some type
186  * errors that the cast doesn't.
187  */
188 static inline unsigned char to_uchar(char ch)
189 {
190         return ch;
191 }
192
193 void usage(char *prog)
194 {
195         printf("Usage: %s [options] <FILE>...\n", prog);
196         printf("Display file status via statx() syscall.\n"
197                "List information about the FILE "
198                "(the current diretory by default) via statx() syscall.\n"
199                "options:\n"
200                "\t-L --dereference   follow links\n"
201                "\t--cached=MODE      specify how to use cached attributes;\n"
202                "\t                     See MODE below\n"
203                "\t-c --format=FORMAT use the specified FORMAT instead of the "
204                "default;\n"
205                "\t                     output a newline after each use of "
206                "FORMAT\n"
207                "\t-t, --terse        print the information in terse form\n"
208                "\t-D --dir           list information about the FILE (ls)\n"
209                "\t-l                 use a long listing format\n"
210                "\t-q --quiet         do not display results, test only\n\n"
211                "The --cached MODE argument can be; always, never, or default.\n"
212                "`always` will use cached attributes if available, while\n"
213                "`never` will try to synchronize with the latest attributes,\n"
214                "and `default` will leave it up to the underlying file system.\n"
215                "\n"
216                "The valid format sequences for files (without --file-system):\n"
217                "\n"
218                "\t%%a  access rights in octal (note '#' and '0' printf flags)\n"
219                "\t%%A   access rights in human readable form\n"
220                "\t%%b   number of blocks allocated (see %%B)\n"
221                "\t%%B   the size in bytes of each block reported by %%b\n"
222                "\t%%C   SELinux security context string\n"
223                "\t%%d   device number in decimal\n"
224                "\t%%D   device number in hex\n"
225                "\t%%f   raw mode in hex\n"
226                "\t%%F   file type\n"
227                "\t%%g   group ID of owner\n"
228                "\t%%G   group name of owner\n"
229                "\t%%h   number of hard links\n"
230                "\t%%i   inode number\n"
231                "\t%%m   mount point\n"
232                "\t%%n   file name\n"
233                "\t%%N   quoted file name with dereference if symbolic link\n"
234                "\t%%o   optimal I/O transfer size hint\n"
235                "\t%%q   Mask to show what's supported in stx_attributes\n"
236                "\t%%r   Flags conveying information about the file: "
237                "stx_attributes\n"
238                "\t%%s   total size, in bytes\n"
239                "\t%%t   major device type in hex, for character/block device "
240                "special files\n"
241                "\t%%T   minor device type in hex, for character/block device "
242                "special files\n"
243                "\t%%u   user ID of owner\n"
244                "\t%%U   user name of owner\n"
245                "\t%%w   time of file birth, human-readable; - if unknown\n"
246                "\t%%W   time of file birth, seconds since Epoch; 0 if unknown\n"
247                "\t%%x   time of last access, human-readable\n"
248                "\t%%X   time of last access, seconds since Epoch\n"
249                "\t%%y   time of last data modification, human-readable\n"
250                "\t%%Y   time of last data modification, seconds since Epoch\n"
251                "\t%%z   time of last status change, human-readable\n"
252                "\t%%Z   time of last status change, seconds since Epoch\n");
253         exit(0);
254 }
255
256 /* gnulib/lib/filemode.c */
257 /* Return a character indicating the type of file described by
258  * file mode BITS:
259  * '-' regular file
260  * 'b' block special file
261  * 'c' character special file
262  * 'C' high performance ("contiguous data") file
263  * 'd' directory
264  * 'D' door
265  * 'l' symbolic link
266  * 'm' multiplexed file (7th edition Unix; obsolete)
267  * 'n' network special file (HP-UX)
268  * 'p' fifo (named pipe)
269  * 'P' port
270  * 's' socket
271  * 'w' whiteout (4.4BSD)
272  * '?' some other file type
273  */
274 static char ftypelet(mode_t bits)
275 {
276         /* These are the most common, so test for them first.*/
277         if (S_ISREG(bits))
278                 return '-';
279         if (S_ISDIR(bits))
280                 return 'd';
281
282         /* Other letters standardized by POSIX 1003.1-2004.*/
283         if (S_ISBLK(bits))
284                 return 'b';
285         if (S_ISCHR(bits))
286                 return 'c';
287         if (S_ISLNK(bits))
288                 return 'l';
289         if (S_ISFIFO(bits))
290                 return 'p';
291
292         /* Other file types (though not letters) standardized by POSIX.*/
293         if (S_ISSOCK(bits))
294                 return 's';
295
296         return '?';
297 }
298
299 /* Like filemodestring, but rely only on MODE.*/
300 static void strmode(mode_t mode, char *str)
301 {
302         str[0] = ftypelet(mode);
303         str[1] = mode & S_IRUSR ? 'r' : '-';
304         str[2] = mode & S_IWUSR ? 'w' : '-';
305         str[3] = (mode & S_ISUID
306                         ? (mode & S_IXUSR ? 's' : 'S')
307                         : (mode & S_IXUSR ? 'x' : '-'));
308         str[4] = mode & S_IRGRP ? 'r' : '-';
309         str[5] = mode & S_IWGRP ? 'w' : '-';
310         str[6] = (mode & S_ISGID
311                         ? (mode & S_IXGRP ? 's' : 'S')
312                         : (mode & S_IXGRP ? 'x' : '-'));
313         str[7] = mode & S_IROTH ? 'r' : '-';
314         str[8] = mode & S_IWOTH ? 'w' : '-';
315         str[9] = (mode & S_ISVTX
316                         ? (mode & S_IXOTH ? 't' : 'T')
317                         : (mode & S_IXOTH ? 'x' : '-'));
318         str[10] = ' ';
319         str[11] = '\0';
320 }
321
322 /* filemodestring - fill in string STR with an ls-style ASCII
323  * representation of the st_mode field of file stats block STATP.
324  * 12 characters are stored in STR.
325  * The characters stored in STR are:
326  *
327  * 0    File type, as in ftypelet above, except that other letters are used
328  *      for files whose type cannot be determined solely from st_mode:
329  *
330  *          'F' semaphore
331  *          'M' migrated file (Cray DMF)
332  *          'Q' message queue
333  *          'S' shared memory object
334  *          'T' typed memory object
335  *
336  * 1    'r' if the owner may read, '-' otherwise.
337  *
338  * 2    'w' if the owner may write, '-' otherwise.
339  *
340  * 3    'x' if the owner may execute, 's' if the file is
341  *      set-user-id, '-' otherwise.
342  *      'S' if the file is set-user-id, but the execute
343  *      bit isn't set.
344  *
345  * 4    'r' if group members may read, '-' otherwise.
346  *
347  * 5    'w' if group members may write, '-' otherwise.
348  *
349  * 6    'x' if group members may execute, 's' if the file is
350  *      set-group-id, '-' otherwise.
351  *      'S' if it is set-group-id but not executable.
352  *
353  * 7    'r' if any user may read, '-' otherwise.
354  *
355  * 8    'w' if any user may write, '-' otherwise.
356  *
357  * 9    'x' if any user may execute, 't' if the file is "sticky"
358  *      (will be retained in swap space after execution), '-'
359  *      otherwise.
360  *      'T' if the file is sticky but not executable.
361  *
362  * 10   ' ' for compatibility with 4.4BSD strmode,
363  *      since this interface does not support ACLs.
364  *
365  * 11   '\0'.
366  */
367 static void filemodestring(struct statx const *stxp, char *str)
368 {
369         strmode(stxp->stx_mode, str);
370
371 /*
372         if (S_TYPEISSEM(statp))
373                 str[0] = 'F';
374         else if (IS_MIGRATED_FILE (statp))
375                 str[0] = 'M';
376         else if (S_TYPEISMQ (statp))
377                 str[0] = 'Q';
378         else if (S_TYPEISSHM (statp))
379                 str[0] = 'S';
380         else if (S_TYPEISTMO (statp))
381                 str[0] = 'T';
382  */
383 }
384
385 /* gnulib/lib/file-type.c */
386 static char const *file_type(struct statx const *stx)
387 {
388         /* See POSIX 1003.1-2001 XCU Table 4-8 lines 17093-17107 for some of
389          * these formats.
390          *
391          * To keep diagnostics grammatical in English, the returned string
392          * must start with a consonant.
393          */
394         /* Do these three first, as they're the most common.  */
395         if (S_ISREG(stx->stx_mode))
396                 return stx->stx_size == 0 ? "regular empty file" :
397                                             "regular file";
398
399         if (S_ISDIR(stx->stx_mode))
400                 return "directory";
401
402         if (S_ISLNK(stx->stx_mode))
403                 return "symbolic link";
404
405         /* The remaining are in alphabetical order.  */
406         if (S_ISBLK(stx->stx_mode))
407                 return "block special file";
408
409         if (S_ISCHR(stx->stx_mode))
410                 return "character special file";
411
412         if (S_ISFIFO(stx->stx_mode))
413                 return "fifo";
414
415         if (S_ISSOCK(stx->stx_mode))
416                 return "socket";
417
418         return "weird file";
419 }
420
421 /* gnulib/lib/areadlink-with-size.c */
422 /* SYMLINK_MAX is used only for an initial memory-allocation sanity
423  * check, so it's OK to guess too small on hosts where there is no
424  * arbitrary limit to symbolic link length.
425  */
426 #ifndef SYMLINK_MAX
427 #define SYMLINK_MAX 1024
428 #endif
429
430 #define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX)
431
432 /* Call readlink to get the symbolic link value of FILE.
433  * SIZE is a hint as to how long the link is expected to be;
434  * typically it is taken from st_size.  It need not be correct.
435  * Return a pointer to that NUL-terminated string in malloc'd storage.
436  * If readlink fails, malloc fails, or if the link value is longer
437  * than SSIZE_MAX, return NULL (caller may use errno to diagnose).
438  */
439 static char *areadlink_with_size(char const *file, size_t size)
440 {
441         /* Some buggy file systems report garbage in st_size.  Defend
442          * against them by ignoring outlandish st_size values in the initial
443          * memory allocation.
444          */
445         size_t symlink_max = SYMLINK_MAX;
446         size_t INITIAL_LIMIT_BOUND = 8 * 1024;
447         size_t initial_limit = (symlink_max < INITIAL_LIMIT_BOUND ?
448                                 symlink_max + 1 : INITIAL_LIMIT_BOUND);
449         enum { stackbuf_size = 128 };
450         /* The initial buffer size for the link value. */
451         size_t buf_size = (size == 0 ? stackbuf_size : size < initial_limit ?
452                            size + 1 : initial_limit);
453
454         while (1) {
455                 ssize_t r;
456                 size_t link_length;
457                 char stackbuf[stackbuf_size];
458                 char *buf = stackbuf;
459                 char *buffer = NULL;
460
461                 if (!(size == 0 && buf_size == stackbuf_size)) {
462                         buf = buffer = malloc(buf_size);
463                         if (!buffer)
464                                 return NULL;
465                 }
466
467                 r = readlink(file, buf, buf_size);
468                 link_length = r;
469
470                 /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
471                  * with errno == ERANGE if the buffer is too small.
472                  */
473                 if (r < 0 && errno != ERANGE) {
474                         int saved_errno = errno;
475
476                         free(buffer);
477                         errno = saved_errno;
478                         return NULL;
479                 }
480
481                 if (link_length < buf_size) {
482                         buf[link_length] = 0;
483                         if (!buffer) {
484                                 buffer = malloc(link_length + 1);
485                                 if (buffer)
486                                         return memcpy(buffer, buf,
487                                                       link_length + 1);
488                         } else if (link_length + 1 < buf_size) {
489                                 /* Shrink BUFFER before returning it. */
490                                 char *shrinked_buffer;
491
492                                 shrinked_buffer = realloc(buffer,
493                                                           link_length + 1);
494                                 if (shrinked_buffer != NULL)
495                                         buffer = shrinked_buffer;
496                         }
497                         return buffer;
498                 }
499
500                 free(buffer);
501                 if (buf_size <= MAXSIZE / 2) {
502                         buf_size *= 2;
503                 } else if (buf_size < MAXSIZE) {
504                         buf_size = MAXSIZE;
505                 } else {
506                         errno = ENOMEM;
507                         return NULL;
508                 }
509         }
510 }
511
512 /* coreutils/src/stat.c */
513 /* Output a single-character \ escape.  */
514 static void print_esc_char(char c)
515 {
516         switch (c) {
517         case 'a':                       /* Alert. */
518                 c = '\a';
519                 break;
520         case 'b':                       /* Backspace. */
521                 c = '\b';
522                 break;
523         case 'e':                       /* Escape. */
524                 c = '\x1B';
525                 break;
526         case 'f':                       /* Form feed. */
527                 c = '\f';
528                 break;
529         case 'n':                       /* New line. */
530                 c = '\n';
531                 break;
532         case 'r':                       /* Carriage return. */
533                 c = '\r';
534                 break;
535         case 't':                       /* Horizontal tab. */
536                 c = '\t';
537                 break;
538         case 'v':                       /* Vertical tab. */
539                 c = '\v';
540                 break;
541         case '"':
542         case '\\':
543                 break;
544         default:
545                 printf("warning: unrecognized escape '\\%c'", c);
546                 break;
547         }
548         putchar (c);
549 }
550
551 static size_t format_code_offset(char const *directive)
552 {
553         size_t len = strspn(directive + 1, printf_flags);
554         char const *fmt_char = directive + len + 1;
555
556         fmt_char += strspn(fmt_char, digits);
557         if (*fmt_char == '.')
558                 fmt_char += 1 + strspn(fmt_char + 1, digits);
559
560         return fmt_char - directive;
561 }
562
563 static unsigned int fmt_to_mask(char fmt)
564 {
565         switch (fmt) {
566         case 'N':
567                 return STATX_MODE;
568         case 'd':
569         case 'D':
570                 return STATX_MODE;
571         case 'i':
572                 return STATX_INO;
573         case 'a':
574         case 'A':
575                 return STATX_MODE;
576         case 'f':
577                 return STATX_MODE|STATX_TYPE;
578         case 'F':
579                 return STATX_TYPE;
580         case 'h':
581                 return STATX_NLINK;
582         case 'u':
583         case 'U':
584                 return STATX_UID;
585         case 'g':
586         case 'G':
587                 return STATX_GID;
588         case 'm':
589                 return STATX_MODE|STATX_INO;
590         case 's':
591                 return STATX_SIZE;
592         case 't':
593         case 'T':
594                 return STATX_MODE;
595         case 'b':
596                 return STATX_BLOCKS;
597         case 'w':
598         case 'W':
599                 return STATX_BTIME;
600         case 'x':
601         case 'X':
602                 return STATX_ATIME;
603         case 'y':
604         case 'Y':
605                 return STATX_MTIME;
606         case 'z':
607         case 'Z':
608                 return STATX_CTIME;
609         }
610         return 0;
611 }
612
613 static unsigned int format_to_mask(char const *format)
614 {
615         unsigned int mask = 0;
616         char const *b;
617
618         for (b = format; *b; b++) {
619                 if (*b != '%')
620                         continue;
621
622                 b += format_code_offset(b);
623                 if (*b == '\0')
624                         break;
625                 mask |= fmt_to_mask(*b);
626         }
627
628         return mask;
629 }
630
631 static char *human_access(struct statx const *stxbuf)
632 {
633         static char modebuf[12];
634
635         filemodestring(stxbuf, modebuf);
636         modebuf[10] = 0;
637         return modebuf;
638 }
639
640 static inline struct timespec
641 statx_timestamp_to_timespec(struct statx_timestamp tsx)
642 {
643         struct timespec ts;
644
645         ts.tv_sec = tsx.tv_sec;
646         ts.tv_nsec = tsx.tv_nsec;
647
648         return ts;
649 }
650
651 static int timespec_cmp(struct timespec a, struct timespec b)
652 {
653         if (a.tv_sec < b.tv_sec)
654                 return -1;
655         if (a.tv_sec > b.tv_sec)
656                 return 1;
657
658         return a.tv_nsec - b.tv_nsec;
659 }
660
661 static char *human_time(const struct statx_timestamp *ts)
662 {
663         /* STR must be at least INT_BUFSIZE_BOUND (intmax_t) big, either
664          * because localtime_rz fails, or because the time zone is truly
665          * outlandish so that %z expands to a long string.
666          */
667         static char str[INT_BUFSIZE_BOUND(intmax_t)
668                 + INT_STRLEN_BOUND(int) /* YYYY */
669                 + 1 /* because YYYY might equal INT_MAX + 1900 */
670                 + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +"];
671         struct tm tm;
672         time_t tim;
673         int len;
674         int len2;
675
676         tim = ts->tv_sec;
677         if (!localtime_r(&tim, &tm)) {
678                 perror("localtime_r");
679                 exit(EXIT_FAILURE);
680         }
681
682         if (o_dir_list && long_format) {
683                 struct timespec when_timespec;
684                 struct timespec six_months_ago;
685                 bool recent;
686
687                 when_timespec = statx_timestamp_to_timespec(*ts);
688                 /* If the file appears to be in the future, update the current
689                  * time, in case the file happens to have been modified since
690                  * the last time we checked the clock.
691                  */
692                 if (timespec_cmp(current_time, when_timespec) < 0) {
693                         struct timeval tv;
694
695                         gettimeofday(&tv, NULL);
696                         current_time.tv_sec = tv.tv_sec;
697                         current_time.tv_nsec = tv.tv_usec * 1000;
698                 }
699
700                 /* Consider a time to be recent if it is within the past six
701                  * months.
702                  * A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952
703                  * seconds on the average.  Write this value as an integer
704                  * constant to avoid floating point hassles.
705                  */
706                 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
707                 six_months_ago.tv_nsec = current_time.tv_nsec;
708
709                 recent = (timespec_cmp(six_months_ago, when_timespec) < 0 &&
710                           (timespec_cmp(when_timespec, current_time) < 0));
711
712                 /* We assume here that all time zones are offset from UTC by a
713                  * whole number of seconds.
714                  */
715                 len = strftime(str, sizeof(str),
716                                recent ? "%b %e %H:%M" : "%b %e %Y", &tm);
717                 if (len == 0) {
718                         perror("strftime");
719                         exit(EXIT_FAILURE);
720                 }
721
722                 return str;
723         }
724
725         len = strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &tm);
726         if (len == 0) {
727                 perror("strftime");
728                 exit(EXIT_FAILURE);
729         }
730
731         len2 = snprintf(str + len, sizeof(str) - len, ".%09u ", ts->tv_nsec);
732         len = strftime(str + len + len2, sizeof(str) - len - len2, "%z", &tm);
733         if (len == 0) {
734                 perror("strftime2");
735                 exit(1);
736         }
737
738         return str;
739 }
740
741 /* PFORMAT points to a '%' followed by a prefix of a format, all of
742  * size PREFIX_LEN.  The flags allowed for this format are
743  * ALLOWED_FLAGS; remove other printf flags from the prefix, then
744  * append SUFFIX.
745  */
746 static void make_format(char *pformat, size_t prefix_len,
747                         char const *allowed_flags, char const *suffix)
748 {
749         char *dst = pformat + 1;
750         char const *src;
751         char const *srclim = pformat + prefix_len;
752
753         for (src = dst; src < srclim && strchr(printf_flags, *src); src++)
754                 if (strchr(allowed_flags, *src))
755                         *dst++ = *src;
756         while (src < srclim)
757                 *dst++ = *src++;
758         strcpy(dst, suffix);
759 }
760
761 static void out_string(char *pformat, size_t prefix_len, char const *arg)
762 {
763         make_format(pformat, prefix_len, "-", "s");
764         printf(pformat, arg);
765 }
766
767 static int out_int(char *pformat, size_t prefix_len, intmax_t arg)
768 {
769         make_format(pformat, prefix_len, "'-+ 0", PRIdMAX);
770         return printf(pformat, arg);
771 }
772
773 static int out_uint(char *pformat, size_t prefix_len, uintmax_t arg)
774 {
775         make_format(pformat, prefix_len, "'-0", PRIuMAX);
776         return printf(pformat, arg);
777 }
778
779 static void out_uint_o(char *pformat, size_t prefix_len, uintmax_t arg)
780 {
781         make_format(pformat, prefix_len, "-#0", PRIoMAX);
782         printf(pformat, arg);
783 }
784
785 static void out_uint_x(char *pformat, size_t prefix_len, uintmax_t arg)
786 {
787         make_format(pformat, prefix_len, "-#0", PRIxMAX);
788         printf(pformat, arg);
789 }
790
791 static int out_minus_zero(char *pformat, size_t prefix_len)
792 {
793         make_format(pformat, prefix_len, "'-+ 0", ".0f");
794         return printf(pformat, -0.25);
795 }
796
797 /* Output the number of seconds since the Epoch, using a format that
798  * acts like printf's %f format.
799  */
800 static void out_epoch_sec(char *pformat, size_t prefix_len,
801                           struct timespec arg)
802 {
803         char *dot = memchr(pformat, '.', prefix_len);
804         size_t sec_prefix_len = prefix_len;
805         int width = 0;
806         int precision = 0;
807         bool frac_left_adjust = false;
808
809         if (dot) {
810                 sec_prefix_len = dot - pformat;
811                 pformat[prefix_len] = '\0';
812
813                 if (ISDIGIT(dot[1])) {
814                         long int lprec = strtol(dot + 1, NULL, 10);
815
816                         precision = (lprec <= INT_MAX ? lprec : INT_MAX);
817                 } else {
818                         precision = 9;
819                 }
820
821                 if (precision && ISDIGIT(dot[-1])) {
822                         /* If a nontrivial width is given, subtract the width
823                          * of the decimal point and PRECISION digits that will
824                          * be output later.
825                          */
826                         char *p = dot;
827
828                         *dot = '\0';
829
830                         do
831                                 --p;
832                         while (ISDIGIT(p[-1]));
833
834                         long int lwidth = strtol(p, NULL, 10);
835
836                         width = (lwidth <= INT_MAX ? lwidth : INT_MAX);
837                         if (width > 1) {
838                                 p += (*p == '0');
839                                 sec_prefix_len = p - pformat;
840
841                                 int w_d = (decimal_point_len < width ?
842                                            width - decimal_point_len : 0);
843
844                                 if (w_d > 1) {
845                                         int w = w_d - precision;
846
847                                         if (w > 1) {
848                                                 char *dst = pformat;
849                                                 char const *src = dst;
850                                                 for (; src < p; src++) {
851                                                         if (*src == '-')
852                                                                 frac_left_adjust = true;
853                                                         else
854                                                                 *dst++ = *src;
855                                                 }
856                                                 sec_prefix_len =
857                                                         (dst - pformat
858                         + (frac_left_adjust ? 0 : sprintf(dst, "%d", w)));
859                                         }
860                                 }
861                         }
862                 }
863         }
864
865         int divisor = 1;
866         int i;
867
868         for (i = precision; i < 9; i++)
869                 divisor *= 10;
870
871         int frac_sec = arg.tv_nsec / divisor;
872         int int_len;
873
874
875         if (TYPE_SIGNED(time_t)) {
876                 bool minus_zero = false;
877
878                 if (arg.tv_sec < 0 && arg.tv_nsec != 0) {
879                         int frac_sec_modulus = 1000000000 / divisor;
880
881                         frac_sec = (frac_sec_modulus - frac_sec
882                                     - (arg.tv_nsec % divisor != 0));
883                         arg.tv_sec += (frac_sec != 0);
884                         minus_zero = (arg.tv_sec == 0);
885                 }
886                 int_len = (minus_zero ?
887                            out_minus_zero(pformat, sec_prefix_len) :
888                            out_int(pformat, sec_prefix_len, arg.tv_sec));
889         } else {
890                 int_len = out_uint(pformat, sec_prefix_len, arg.tv_sec);
891         }
892
893         if (precision) {
894                 int prec = (precision < 9 ? precision : 9);
895                 int trailing_prec = precision - prec;
896                 int ilen = (int_len < 0 ? 0 : int_len);
897                 int trailing_width = (ilen < width &&
898                                       decimal_point_len < width - ilen ?
899                                       width - ilen - decimal_point_len - prec :
900                                       0);
901
902                 printf("%s%.*d%-*.*d", decimal_point, prec, frac_sec,
903                         trailing_width, trailing_prec, 0);
904         }
905 }
906
907 /* Print the context information of FILENAME, and return true iff the
908  * context could not be obtained.
909  */
910 static int out_file_context(char *pformat, size_t prefix_len,
911                             char const *filename)
912 {
913         char *scontext = NULL;
914         int rc = 0;
915
916 #ifdef HAVE_SELINUX
917         if ((follow_links ? getfilecon(filename, &scontext) :
918                             lgetfilecon(filename, &scontext)) < 0) {
919                 printf("failed to get security context of %s: %s\n",
920                        filename, strerror(errno));
921                 scontext = NULL;
922                 rc  = -errno;
923         }
924 #endif
925
926         strcpy(pformat + prefix_len, "s");
927         printf(pformat, (scontext ? scontext : "?"));
928         if (scontext)
929                 freecon(scontext);
930         return rc;
931 }
932
933 /* Map a TS with negative TS.tv_nsec to {0,0}.  */
934 static inline struct timespec neg_to_zero(struct timespec ts)
935 {
936         if (ts.tv_nsec >= 0) {
937                 return ts;
938         } else {
939                 struct timespec z = {0, 0};
940
941                 return z;
942         }
943 }
944
945 /* All the mode bits that can be affected by chmod.  */
946 #define CHMOD_MODE_BITS \
947         (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
948
949 /* Print statx info.  Return zero upon success, nonzero upon failure.  */
950 static int print_statx(char *pformat, size_t prefix_len, unsigned int m,
951                        int fd, char const *filename, struct statx const *stx)
952 {
953         struct passwd *pw_ent;
954         struct group *gw_ent;
955         int rc = 0;
956         int ret;
957
958         switch (m) {
959         case 'n':
960                 out_string(pformat, prefix_len,
961                            o_dir_list ? strrchr(filename, '/') + 1 : filename);
962                 break;
963         case 'N':
964                 out_string(pformat, prefix_len,
965                            o_dir_list ? strrchr(filename, '/')  + 1 : filename);
966                 if (S_ISLNK(stx->stx_mode)) {
967                         char *linkname;
968
969                         linkname = areadlink_with_size(filename, stx->stx_size);
970                         if (linkname == NULL) {
971                                 printf("cannot read symbolic link %s: %s",
972                                        filename, strerror(errno));
973                                 return -errno;
974                         }
975                         printf(" -> ");
976                         out_string(pformat, prefix_len, linkname);
977                         free(linkname);
978                 }
979                 break;
980         case 'd':
981                 out_uint(pformat, prefix_len, makedev(stx->stx_dev_major,
982                                                       stx->stx_dev_minor));
983                 break;
984         case 'D':
985                 out_uint_x(pformat, prefix_len, makedev(stx->stx_dev_major,
986                                                         stx->stx_dev_minor));
987                 break;
988         case 'i':
989                 out_uint(pformat, prefix_len, stx->stx_ino);
990                 break;
991         case 'a':
992                 out_uint_o(pformat, prefix_len,
993                            stx->stx_mode & CHMOD_MODE_BITS);
994                 break;
995         case 'A':
996                 out_string(pformat, prefix_len, human_access(stx));
997                 break;
998         case 'f':
999                 out_uint_x(pformat, prefix_len, stx->stx_mode);
1000                 break;
1001         case 'F':
1002                 out_string(pformat, prefix_len, file_type(stx));
1003                 break;
1004         case 'h':
1005                 out_uint(pformat, prefix_len, stx->stx_nlink);
1006                 break;
1007         case 'u':
1008                 out_uint(pformat, prefix_len, stx->stx_uid);
1009                 break;
1010         case 'U':
1011                 pw_ent = getpwuid(stx->stx_uid);
1012                 out_string(pformat, prefix_len,
1013                            pw_ent ? pw_ent->pw_name : "UNKNOWN");
1014                 break;
1015         case 'g':
1016                 out_uint(pformat, prefix_len, stx->stx_gid);
1017                 break;
1018         case 'G':
1019                 gw_ent = getgrgid(stx->stx_gid);
1020                 out_string(pformat, prefix_len,
1021                            gw_ent ? gw_ent->gr_name : "UNKNOWN");
1022                 break;
1023         case 'm':
1024                 /*
1025                  * fail |= out_mount_point(filename, pformat, prefix_len,
1026                  *                         statbuf);
1027                  */
1028                 if (!rc)
1029                         rc = -ENOTSUP;
1030                 break;
1031         case 's':
1032                 out_int(pformat, prefix_len, stx->stx_size);
1033                 break;
1034         case 't':
1035                 out_uint_x(pformat, prefix_len,
1036                            major(makedev(stx->stx_rdev_major,
1037                                          stx->stx_rdev_minor)));
1038                 break;
1039         case 'T':
1040                 out_uint_x(pformat, prefix_len,
1041                            minor(makedev(stx->stx_rdev_major,
1042                                          stx->stx_rdev_minor)));
1043                 break;
1044         case 'B':
1045                 out_uint(pformat, prefix_len, S_BLKSIZE);
1046                 break;
1047         case 'b':
1048                 out_uint(pformat, prefix_len, stx->stx_blocks);
1049                 break;
1050         case 'o':
1051                 out_uint(pformat, prefix_len, stx->stx_blksize);
1052                 break;
1053         case 'p':
1054                 out_uint_x(pformat, prefix_len, stx->stx_attributes_mask);
1055                 break;
1056         case 'r':
1057                 out_uint_x(pformat, prefix_len, stx->stx_attributes);
1058                 break;
1059         case 'w':
1060                 if (stx->stx_btime.tv_nsec < 0)
1061                         out_string(pformat, prefix_len, "-");
1062                 else
1063                         out_string(pformat, prefix_len,
1064                                    human_time(&stx->stx_btime));
1065                 break;
1066         case 'W':
1067                 out_epoch_sec(pformat, prefix_len,
1068                               neg_to_zero(statx_timestamp_to_timespec(
1069                                               stx->stx_btime)));
1070                 break;
1071         case 'x':
1072                 out_string(pformat, prefix_len,
1073                            human_time(&stx->stx_atime));
1074                 break;
1075         case 'X':
1076                 out_epoch_sec(pformat, prefix_len,
1077                               neg_to_zero(statx_timestamp_to_timespec(
1078                                               stx->stx_atime)));
1079                 break;
1080         case 'y':
1081                 out_string(pformat, prefix_len,
1082                            human_time(&stx->stx_mtime));
1083                 break;
1084         case 'Y':
1085                 out_epoch_sec(pformat, prefix_len,
1086                               neg_to_zero(statx_timestamp_to_timespec(
1087                                               stx->stx_mtime)));
1088                 break;
1089         case 'z':
1090                 out_string(pformat, prefix_len,
1091                            human_time(&stx->stx_ctime));
1092                 break;
1093         case 'Z':
1094                 out_epoch_sec(pformat, prefix_len,
1095                               neg_to_zero(statx_timestamp_to_timespec(
1096                                               stx->stx_ctime)));
1097                 break;
1098         case 'C':
1099                 ret = out_file_context(pformat, prefix_len, filename);
1100                 if (!rc && ret)
1101                         rc = ret;
1102                 break;
1103         default:
1104                 fputc('?', stdout);
1105                 break;
1106         }
1107
1108         return rc;
1109 }
1110
1111 static int print_it(int fd, char const *filename,
1112                     int (*print_func)(char *, size_t, unsigned int,
1113                                       int, char const *, struct statx const *),
1114                     void const *data)
1115 {
1116         /* Add 2 to accommodate our conversion of the stat '%s' format string
1117          * to the longer printf '%llu' one.
1118          */
1119         enum {
1120                 MAX_ADDITIONAL_BYTES = (MAX(sizeof(PRIdMAX),
1121                                         MAX(sizeof(PRIoMAX),
1122                                             MAX(sizeof(PRIuMAX),
1123                                                 sizeof(PRIxMAX)))) - 1)
1124         };
1125         size_t n_alloc;
1126         char *dest;
1127         char const *b;
1128         int rc = 0;
1129
1130         if (o_quiet)
1131                 return 0;
1132
1133         n_alloc = strlen(format) + MAX_ADDITIONAL_BYTES + 1;
1134         dest = malloc(n_alloc);
1135         if (dest == NULL)
1136                 return -ENOMEM;
1137
1138         for (b = format; *b; b++) {
1139                 switch (*b) {
1140                 case '%': {
1141                         size_t len = format_code_offset(b);
1142                         char const *fmt_char = b + len;
1143                         int ret;
1144
1145                         memcpy(dest, b, len);
1146                         b += len;
1147
1148                         switch (*fmt_char) {
1149                         case '\0':
1150                                 --b;
1151                         case '%':
1152                                 if (len > 1) {
1153                                         dest[len] = *fmt_char;
1154                                         dest[len + 1] = '\0';
1155                                         printf("%s: invalid directive", dest);
1156                                         return -EINVAL;
1157                                 }
1158                                 putchar('%');
1159                                 break;
1160                         default:
1161                                 ret = print_func(dest, len, to_uchar(*fmt_char),
1162                                                  fd, filename, data);
1163                                 if (rc == 0 && ret)
1164                                         rc = ret;
1165                                 break;
1166                         }
1167                         break;
1168                 }
1169                 case '\\':
1170                         if (!interpret_backslash_escapes) {
1171                                 putchar ('\\');
1172                                 break;
1173                         }
1174                         ++b;
1175                         if (isodigit(*b)) {
1176                                 int esc_value = octtobin(*b);
1177                                 int esc_length = 1; /* number of octal digits */
1178
1179                                 for (++b; esc_length < 3 && isodigit(*b);
1180                                      ++esc_length, ++b) {
1181                                         esc_value = esc_value * 8 +
1182                                                     octtobin(*b);
1183                                 }
1184                                 putchar(esc_value);
1185                                 --b;
1186                         } else if (*b == 'x' && isxdigit(to_uchar(b[1]))) {
1187                                 /* Value of \xhh escape. */
1188                                 int esc_value = hextobin(b[1]);
1189                                 /* A hexadecimal \xhh escape sequence must have
1190                                  * 1 or 2 hex. digits.
1191                                  */
1192
1193                                 ++b;
1194                                 if (isxdigit(to_uchar(b[1]))) {
1195                                         ++b;
1196                                         esc_value = esc_value * 16 +
1197                                                     hextobin(*b);
1198                                 }
1199                                 putchar(esc_value);
1200                         } else if (*b == '\0') {
1201                                 printf("warning: backslash at end of format");
1202                                 putchar('\\');
1203                                 /* Arrange to exit the loop.  */
1204                                 --b;
1205                         } else {
1206                                 print_esc_char(*b);
1207                         }
1208                         break;
1209
1210                 default:
1211                         putchar(*b);
1212                         break;
1213                 }
1214         }
1215         free(dest);
1216
1217         fputs(trailing_delim, stdout);
1218
1219         return rc;
1220 }
1221
1222 /* Return an allocated format string in static storage that
1223  * corresponds to whether FS and TERSE options were declared.
1224  */
1225 static char *default_format(bool fs, bool terse, bool device)
1226 {
1227         char *format;
1228
1229         if (fs) {
1230                 if (terse) {
1231                         format = xstrdup(fmt_terse_fs);
1232                 } else {
1233                         /* TRANSLATORS: This string uses format specifiers from
1234                          * 'stat --help' with --file-system, and NOT from
1235                          * printf.
1236                          */
1237                         format = xstrdup(
1238                         "  File: \"%n\"\n"
1239                         "    ID: %-8i Namelen: %-7l Type: %T\n"
1240                         "Block size: %-10s Fundamental block size: %S\n"
1241                         "Blocks: Total: %-10b Free: %-10f Available: %a\n"
1242                         "Inodes: Total: %-10c Free: %d\n");
1243                 }
1244         } else /* ! fs */ {
1245                 if (terse) {
1246 #ifdef HAVE_SELINUX
1247                         if (is_selinux_enabled() > 0)
1248                                 format = xstrdup(fmt_terse_selinux);
1249                         else
1250 #endif
1251                                 format = xstrdup(fmt_terse_regular);
1252                 } else {
1253                         char *temp;
1254
1255                         /* TRANSLATORS: This string uses format specifiers from
1256                          * 'stat --help' without --file-system, and NOT from
1257                          * printf.
1258                          */
1259                         format = xstrdup("\
1260   File: %N\n\
1261   Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n\
1262 ");
1263
1264                         temp = format;
1265                         if (device) {
1266                                 /* TRANSLATORS: This string uses format
1267                                  * specifiers from 'stat --help' without
1268                                  * --file-system, and NOT from printf.
1269                                  */
1270                                 format = xasprintf("%s%s", format, "\
1271 " "Device: %Dh/%dd\tInode: %-10i  Links: %-5h Device type: %t,%T\n\
1272 ");
1273                         } else {
1274                                 /* TRANSLATORS: This string uses format
1275                                  * specifiers from 'stat --help' without
1276                                  * --file-system, and NOT from printf.
1277                                  */
1278                                 format = xasprintf("%s%s", format, "\
1279 " "Device: %Dh/%dd\tInode: %-10i  Links: %h\n\
1280 ");
1281                         }
1282                         free(temp);
1283
1284                         temp = format;
1285                         /* TRANSLATORS: This string uses format specifiers from
1286                          * 'stat --help' without --file-system, and NOT from
1287                          * printf.
1288                          */
1289                         format = xasprintf("%s%s", format, "\
1290 " "Access: (%04a/%10.10A)  Uid: (%5u/%8U)   Gid: (%5g/%8G)\n\
1291 ");
1292                         free(temp);
1293
1294                         if (is_selinux_enabled() > 0) {
1295                                 temp = format;
1296                                 /* TRANSLATORS: This string uses format
1297                                  * specifiers from 'stat --help' without
1298                                  * --file-system, and NOT from printf.
1299                                  */
1300                                 format = xasprintf("%s%s", format,
1301                                                    "Context: %C\n");
1302                                 free(temp);
1303                         }
1304
1305                         temp = format;
1306                         /* TRANSLATORS: This string uses format specifiers from
1307                          * 'stat --help' without --file-system, and NOT from
1308                          * printf.
1309                          */
1310                         format = xasprintf("%s%s", format,
1311                                            "Access: %x\n"
1312                                            "Modify: %y\n"
1313                                            "Change: %z\n"
1314                                            " Birth: %w\n");
1315                         free(temp);
1316                 }
1317         }
1318         return format;
1319 }
1320
1321 static char *list_long_format(void)
1322 {
1323         char *format;
1324
1325         format = xstrdup("\
1326 " "%10.10A %h %8U %8G %-10s %y %N\
1327 ");
1328
1329         return format;
1330 }
1331
1332 static int do_statx(char const *filename, unsigned int request_mask, int flags)
1333 {
1334         const char *pathname = filename;
1335         struct statx stx = { 0, };
1336         int fd;
1337
1338         if (strcmp(filename, "-") == 0)
1339                 fd = 0;
1340         else
1341                 fd = AT_FDCWD;
1342
1343         if (fd != AT_FDCWD) {
1344                 pathname = "";
1345                 flags |= AT_EMPTY_PATH;
1346         }
1347
1348         fd = statx(fd, pathname, flags, request_mask, &stx);
1349         if (fd < 0) {
1350                 if (flags & AT_EMPTY_PATH)
1351                         printf("cannot stat standard input\n");
1352                 else
1353                         printf("cannot statx %s: %s\n",
1354                                filename, strerror(errno));
1355
1356                 return -errno;
1357         }
1358
1359         return print_it(fd, filename, print_statx, &stx);
1360 }
1361
1362 /* Return true if FILE should be ignored. */
1363 static bool file_ignored(char const *name)
1364 {
1365         return name[0] == '.';
1366 }
1367
1368 static int do_dir_list(char const *dirname, unsigned int request_mask,
1369                        int flags)
1370 {
1371         DIR *dir;
1372         struct dirent *ent;
1373         char fullname[PATH_MAX];
1374         int rc = 0;
1375
1376         dir = opendir(dirname);
1377         if (!dir) {
1378                 rc = -errno;
1379                 printf("lsx: cannot open directory '%s': %s\n",
1380                        dirname, strerror(errno));
1381                 return rc;
1382         }
1383
1384         while ((ent = readdir(dir)) != NULL) {
1385                 int ret;
1386
1387                 /* skip "." and ".." */
1388                 if (file_ignored(ent->d_name))
1389                         continue;
1390
1391                 /* ls -1 */
1392                 if (!format) {
1393                         if (o_quiet)
1394                                 continue;
1395
1396                         printf("%s", ent->d_name);
1397                         putchar('\n');
1398                 } else {
1399                         if (strlen(ent->d_name) + strlen(dirname) + 1 >=
1400                             sizeof(fullname)) {
1401                                 errno = ENAMETOOLONG;
1402                                 fprintf(stderr,
1403                                         "lsx: ignored too long path: %s/%s\n",
1404                                         dirname, ent->d_name);
1405                                 if (!rc)
1406                                         rc = -ENAMETOOLONG;
1407                                 continue;
1408                         }
1409                         snprintf(fullname, PATH_MAX, "%s/%s",
1410                                  dirname, ent->d_name);
1411                         ret = do_statx(fullname, request_mask, flags);
1412                         if (!ret)
1413                                 putchar('\n');
1414                         else if (rc == 0)
1415                                 rc = ret;
1416                 }
1417         }
1418
1419         closedir(dir);
1420         return rc;
1421 }
1422
1423 int main(int argc, char **argv)
1424 {
1425         static struct option options[] = {
1426                 {"dereference", no_argument, NULL, 'L'},
1427                 {"format", required_argument, NULL, 'c'},
1428                 {"printf", required_argument, NULL, PRINTF_OPTION},
1429                 {"terse", no_argument, NULL, 't'},
1430                 {"cached", required_argument, NULL, 0},
1431                 {"dir", no_argument, NULL, 'D'},
1432                 {"long-format", no_argument, NULL, 'l'},
1433                 {"quiet", no_argument, NULL, 'q'},
1434                 {"help", no_argument, NULL, GETOPT_HELP_CHAR},
1435                 {"version", no_argument, NULL, GETOPT_VERSION_CHAR},
1436                 {NULL, 0, NULL, 0}
1437         };
1438         bool terse = false;
1439         unsigned int request_mask;
1440         int flags = AT_SYMLINK_NOFOLLOW;
1441         struct lconv const *locale = localeconv();
1442         int c;
1443         int rc = 0;
1444         int i = 0;
1445
1446         decimal_point = locale->decimal_point[0] ? locale->decimal_point : ".";
1447         decimal_point_len = strlen(decimal_point);
1448         current_time.tv_sec = TYPE_MINIMUM(time_t);
1449         current_time.tv_nsec = -1;
1450
1451         while ((c = getopt_long(argc, argv, "c:DqLlt", options, NULL)) != EOF) {
1452                 switch (c) {
1453                 case 'L':
1454                         flags &= ~AT_SYMLINK_NOFOLLOW;
1455                         follow_links = true;
1456                         break;
1457                 case PRINTF_OPTION:
1458                         format = optarg;
1459                         interpret_backslash_escapes = true;
1460                         trailing_delim = "";
1461                         break;
1462                 case 'c':
1463                         format = optarg;
1464                         interpret_backslash_escapes = false;
1465                         trailing_delim = "\n";
1466                         break;
1467                 case 'q':
1468                         o_quiet = true;
1469                         break;
1470                 case 'l':
1471                         o_dir_list = true;
1472                         long_format = true;
1473                         break;
1474                 case 'D':
1475                         o_dir_list = true;
1476                         break;
1477                 case 't':
1478                         terse = true;
1479                         break;
1480                 case 0:
1481                         if (strcmp(optarg, "never") == 0) {
1482                                 flags &= ~AT_STATX_SYNC_TYPE;
1483                                 flags |= AT_STATX_FORCE_SYNC;
1484                         } else if (strcmp(optarg, "always") == 0) {
1485                                 flags &= ~AT_STATX_SYNC_TYPE;
1486                                 flags |= AT_STATX_DONT_SYNC;
1487                         } else if (strcmp(optarg, "default") == 0) {
1488                                 flags &= ~AT_STATX_SYNC_TYPE;
1489                                 flags |= AT_SYMLINK_NOFOLLOW;
1490                         } else {
1491                                 printf("%s: invalid cached mode: %s\n",
1492                                        argv[0], optarg);
1493                                 return -EINVAL;
1494                         }
1495                         break;
1496                 case GETOPT_HELP_CHAR:
1497                         usage(argv[0]);
1498                 case GETOPT_VERSION_CHAR:
1499                         if (!o_quiet)
1500                                 printf("Lustre statx: version 0.1\n");
1501                         return 0;
1502                 default:
1503                         printf("%s: unknown option '-%c'\n",
1504                                argv[0], optopt);
1505                         return -EINVAL;
1506                 }
1507         }
1508
1509         if (format) {
1510                 request_mask = format_to_mask(format);
1511         } else {
1512                 request_mask = STATX_ALL;
1513                 if (o_dir_list)
1514                         format = long_format ? list_long_format() : NULL;
1515                 else
1516                         format = default_format(false, terse, false);
1517         }
1518
1519         if (optind == argc) {
1520                 if (o_dir_list)
1521                         return do_dir_list(".", request_mask, flags);
1522
1523                 printf("statx: missing operand\n"
1524                        "Try 'stat --help' for more information.\n");
1525                 return 0;
1526         }
1527
1528         for (i = optind; i < argc; i++) {
1529                 int ret;
1530
1531                 if (o_dir_list)
1532                         ret = do_dir_list(argv[i], request_mask, flags);
1533                 else
1534                         ret = do_statx(argv[i], request_mask, flags);
1535
1536                 if (rc == 0 && ret)
1537                         rc = ret;
1538         }
1539
1540         return rc;
1541 }
1542 #else
1543 int main(int argc, char **argv)
1544 {
1545         static struct option options[] = {
1546                 {"version", no_argument, NULL, GETOPT_VERSION_CHAR},
1547                 {"quiet", no_argument, NULL, 'q'},
1548                 {NULL, 0, NULL, 0}
1549         };
1550         int c;
1551
1552         while ((c = getopt_long(argc, argv, "q", options, NULL)) != EOF) {
1553                 switch (c) {
1554                 case 'q':
1555                         o_quiet = true;
1556                         break;
1557                 case GETOPT_VERSION_CHAR:
1558                         if (!o_quiet)
1559                                 printf("statx: Not support statx() syscall\n");
1560                         return -ENOTSUP;
1561                 }
1562         }
1563         printf("Skip: system does not support statx syscall.\n");
1564         return 0;
1565 }
1566 #endif /* __NR_statx */