1 /* vi: set sw=4 ts=4: */
3 * Mini date implementation for busybox
5 * by Matthew Grant <grantma@anathoth.gen.nz>
7 * iso-format handling added by Robert Griebl <griebl@gmx.de>
8 * bugfixes and cleanup by Bernhard Reutner-Fischer
10 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 /* This 'date' command supports only 2 time setting formats,
13 all the GNU strftime stuff (its in libc, lets use it),
14 setting time using UTC and displaying it, as well as
15 an RFC 2822 compliant date output for shell scripting
18 /* Input parsing code is always bulky - used heavy duty libc stuff as
19 much as possible, missed out a lot of bounds checking */
22 //config: bool "date (7.2 kb)"
25 //config: date is used to set the system date or display the
26 //config: current time in the given format.
28 //config:config FEATURE_DATE_ISOFMT
29 //config: bool "Enable ISO date format output (-I)"
31 //config: depends on DATE
33 //config: Enable option (-I) to output an ISO-8601 compliant
34 //config: date/time string.
36 //config:config FEATURE_DATE_NANO
37 //config: bool "Support %[num]N nanosecond format specifier"
38 //config: default n # stat's nanosecond field is a bit non-portable
39 //config: depends on DATE
41 //config: Support %[num]N format specifier. Adds ~250 bytes of code.
43 //config:config FEATURE_DATE_COMPAT
44 //config: bool "Support weird 'date MMDDhhmm[[YY]YY][.ss]' format"
46 //config: depends on DATE
48 //config: System time can be set by 'date -s DATE' and simply 'date DATE',
49 //config: but formats of DATE string are different. 'date DATE' accepts
50 //config: a rather weird MMDDhhmm[[YY]YY][.ss] format with completely
51 //config: unnatural placement of year between minutes and seconds.
52 //config: date -s (and other commands like touch -d) use more sensible
53 //config: formats (for one, ISO format YYYY-MM-DD hh:mm:ss.ssssss).
55 //config: With this option off, 'date DATE' and 'date -s DATE' support
56 //config: the same format. With it on, 'date DATE' additionally supports
57 //config: MMDDhhmm[[YY]YY][.ss] format.
59 //applet:IF_DATE(APPLET_NOEXEC(date, date, BB_DIR_BIN, BB_SUID_DROP, date))
60 /* bb_common_bufsiz1 usage here is safe wrt NOEXEC: not expecting it to be zeroed. */
62 //kbuild:lib-$(CONFIG_DATE) += date.o
64 /* GNU coreutils 6.9 man page:
65 * date [OPTION]... [+FORMAT]
66 * date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
68 * display time described by STRING, not 'now'
70 * like --date once for each line of DATEFILE
71 * -r, --reference=FILE
72 * display the last modification time of FILE
74 * output date and time in RFC 2822 format.
75 * Example: Mon, 07 Aug 2006 12:34:56 -0600
77 * output date and time in RFC 3339 format.
78 * TIMESPEC='date', 'seconds', or 'ns'
79 * Date and time components are separated by a single space:
80 * 2006-08-07 12:34:56-06:00
82 * set time described by STRING
83 * -u, --utc, --universal
84 * print or set Coordinated Universal Time
87 * long options are not supported
89 * -I seems to roughly match --rfc-3339, but -I has _optional_ param
90 * (thus "-I seconds" doesn't work, only "-Iseconds"),
91 * and does not support -Ins
92 * -D FMT is a bbox extension for _input_ conversion of -d DATE
95 //usage:#define date_trivial_usage
96 //usage: "[OPTIONS] [+FMT] [[-s] TIME]"
97 //usage:#define date_full_usage "\n\n"
98 //usage: "Display time (using +FMT), or set time\n"
99 //usage: "\n -u Work in UTC (don't convert to local time)"
100 //usage: "\n [-s] TIME Set time to TIME"
101 //usage: "\n -d TIME Display TIME, not 'now'"
102 //usage: IF_FEATURE_DATE_ISOFMT(
103 //usage: "\n -D FMT FMT (strptime format) for -s/-d TIME conversion"
104 ////////^^^^^^^^^^^^^^^^^^^^^^ busybox invention, not compat
106 //usage: "\n -r FILE Display last modification time of FILE"
107 //usage: "\n -R Output RFC-2822 date"
108 //usage: IF_FEATURE_DATE_ISOFMT(
109 //usage: "\n -I[SPEC] Output ISO-8601 date"
110 //usage: "\n SPEC=date (default), hours, minutes, seconds or ns"
113 //usage: "\nRecognized TIME formats:"
114 //usage: "\n @seconds_since_1970"
115 //usage: "\n hh:mm[:ss]"
116 //usage: "\n [YYYY.]MM.DD-hh:mm[:ss]"
117 //usage: "\n YYYY-MM-DD hh:mm[:ss]"
118 //usage: "\n [[[[[YY]YY]MM]DD]hh]mm[.ss]"
119 //usage: IF_FEATURE_DATE_COMPAT(
120 //usage: "\n 'date TIME' form accepts MMDDhhmm[[YY]YY][.ss] instead"
123 //usage:#define date_example_usage
125 //usage: "Wed Apr 12 18:52:41 MDT 2000\n"
128 #include "common_bufsiz.h"
129 #if ENABLE_FEATURE_DATE_NANO
130 # include <sys/syscall.h>
134 OPT_RFC2822
= (1 << 0), /* R */
135 OPT_SET
= (1 << 1), /* s */
136 OPT_UTC
= (1 << 2), /* u */
137 OPT_DATE
= (1 << 3), /* d */
138 OPT_REFERENCE
= (1 << 4), /* r */
139 OPT_ISO8601
= (1 << 5) * ENABLE_FEATURE_DATE_ISOFMT
, /* I */
140 OPT_STR2DT
= (1 << 6) * ENABLE_FEATURE_DATE_ISOFMT
, /* D */
144 static const char date_longopts
[] ALIGN1
=
145 "rfc-822\0" No_argument
"R"
146 "rfc-2822\0" No_argument
"R"
147 "set\0" Required_argument
"s"
148 "utc\0" No_argument
"u"
149 /* "universal\0" No_argument "u" */
150 "date\0" Required_argument
"d"
151 "reference\0" Required_argument
"r"
155 /* We are a NOEXEC applet.
156 * Obstacles to NOFORK:
158 * - xasprintf result not freed
159 * - after xasprintf we use other xfuncs
162 int date_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
163 int date_main(int argc UNUSED_PARAM
, char **argv
)
167 char buf_fmt_dt2str
[64];
174 char *isofmt_arg
= NULL
;
176 opt
= getopt32long(argv
, "^"
178 IF_FEATURE_DATE_ISOFMT("I::D:")
181 IF_FEATURE_DATE_ISOFMT(":R--I:I--R"),
183 &date_str
, &date_str
, &filename
184 IF_FEATURE_DATE_ISOFMT(, &isofmt_arg
, &fmt_str2dt
)
189 putenv((char*)"TZ=UTC0");
191 if (ENABLE_FEATURE_DATE_ISOFMT
&& (opt
& OPT_ISO8601
)) {
192 isofmt
= 0; /* default is date */
194 static const char isoformats
[] ALIGN1
=
195 "date\0""hours\0""minutes\0""seconds\0ns\0";
196 isofmt
= index_in_substrings(isoformats
, isofmt_arg
);
203 if (argv
[0] && argv
[0][0] == '+') {
204 fmt_dt2str
= &argv
[0][1]; /* skip over the '+' */
207 if (!(opt
& (OPT_SET
| OPT_DATE
))) { /* neither -s TIME nor -d TIME? */
209 date_str
= argv
[0]; /* can be NULL */
211 #if ENABLE_FEATURE_DATE_COMPAT
212 int len
= strspn(date_str
, "0123456789");
213 if (date_str
[len
] == '\0'
214 || (date_str
[len
] == '.'
215 && isdigit(date_str
[len
+1])
216 && isdigit(date_str
[len
+2])
217 && date_str
[len
+3] == '\0'
220 /* Dreaded MMDDhhmm[[CC]YY][.ss] format!
221 * It does not match -d or -s format.
222 * Some users actually do use it.
225 if (len
< 0 || len
> 4 || (len
& 1))
226 bb_error_msg_and_die(bb_msg_invalid_date
, date_str
);
227 if (len
!= 0) { /* move YY or CCYY to front */
229 memcpy(buf
, date_str
+ 8, len
);
230 memmove(date_str
+ len
, date_str
, 8);
231 memcpy(date_str
, buf
, len
);
241 /* Now we have parsed all the information except the date format
242 * which depends on whether the clock is being set or read */
244 if (opt
& OPT_REFERENCE
) {
246 xstat(filename
, &statbuf
);
247 ts
.tv_sec
= statbuf
.st_mtime
;
248 #if ENABLE_FEATURE_DATE_NANO
249 ts
.tv_nsec
= statbuf
.st_mtim
.tv_nsec
;
250 /* Some toolchains use .st_mtimensec instead of st_mtim.tv_nsec.
251 * If you need #define _SVID_SOURCE 1 to enable st_mtim.tv_nsec,
252 * drop a mail to project mailing list please
256 #if ENABLE_FEATURE_DATE_NANO
257 clock_gettime(CLOCK_REALTIME
, &ts
);
262 #if !ENABLE_FEATURE_DATE_NANO
265 localtime_r(&ts
.tv_sec
, &tm_time
);
267 /* If date string is given, update tm_time, and maybe set date */
268 if (date_str
!= NULL
) {
270 /* Zero out fields - take her back to midnight! */
275 /* Process any date input to UNIX time since 1 Jan 1970 */
276 if (ENABLE_FEATURE_DATE_ISOFMT
&& (opt
& OPT_STR2DT
)) {
277 if (strptime(date_str
, fmt_str2dt
, &tm_time
) == NULL
)
278 bb_error_msg_and_die(bb_msg_invalid_date
, date_str
);
280 check_dst
= parse_datestr(date_str
, &tm_time
);
283 /* Correct any day of week and day of year etc. fields */
284 /* Be sure to recheck dst (but not if date is UTC) */
286 tm_time
.tm_isdst
= -1;
287 ts
.tv_sec
= validate_tm_time(date_str
, &tm_time
);
290 /* if setting time, set it */
291 if ((opt
& OPT_SET
) && clock_settime(CLOCK_REALTIME
, &ts
) < 0) {
292 bb_simple_perror_msg("can't set date");
298 /* Deal with format string */
299 if (fmt_dt2str
== NULL
) {
301 fmt_dt2str
= buf_fmt_dt2str
;
302 if (ENABLE_FEATURE_DATE_ISOFMT
&& isofmt
>= 0) {
303 /* -I[SPEC]: 0:date 1:hours 2:minutes 3:seconds 4:ns*/
304 strcpy(fmt_dt2str
, "%Y-%m-%dT%H:%M:%S");
310 i
+= sprintf(&fmt_dt2str
[i
], ",%09u", (unsigned)ts
.tv_nsec
);
312 /* %z prints "+hhmm" timezone, but coreutils-8.30 prints "+hh:mm"! */
313 /* ...therefore this atrocity: */
314 n
= strftime(&fmt_dt2str
[i
], 8, "%z", &tm_time
);
316 if (n
== 5 && (fmt_dt2str
[i
-5] == '+' || fmt_dt2str
[i
-5] == '-')) {
318 fmt_dt2str
[i
] = fmt_dt2str
[i
- 1];
319 fmt_dt2str
[i
- 1] = fmt_dt2str
[i
- 2];
320 fmt_dt2str
[i
- 2] = ':';
324 fmt_dt2str
[i
] = '\0';
325 } else if (opt
& OPT_RFC2822
) {
326 /* -R. undo busybox.c setlocale */
327 if (ENABLE_LOCALE_SUPPORT
)
328 setlocale(LC_TIME
, "C");
329 fmt_dt2str
= (char*)"%a, %d %b %Y %H:%M:%S %z";
330 } else { /* default case */
331 fmt_dt2str
= (char*)"%a %b %e %H:%M:%S %Z %Y";
334 #if ENABLE_FEATURE_DATE_NANO
336 /* User-specified fmt_dt2str */
337 /* Search for and process "%N" */
338 char *p
= fmt_dt2str
;
339 while ((p
= strchr(p
, '%')) != NULL
) {
341 unsigned pres
, scale
;
348 n
= strspn(p
, "0123456789");
353 /* We have "%[nnn]N" */
359 pres
= xatoi_positive(p
);
369 fmt_dt2str
= xasprintf("%s%0*u%s", fmt_dt2str
, pres
, (unsigned)ts
.tv_nsec
/ scale
, p
);
375 #define date_buf bb_common_bufsiz1
376 setup_common_bufsiz();
377 if (*fmt_dt2str
== '\0') {
378 /* With no format string, just print a blank line */
381 /* Generate output string */
382 strftime(date_buf
, COMMON_BUFSIZE
, fmt_dt2str
, &tm_time
);