date.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini date implementation for busybox
  4. *
  5. * by Matthew Grant <grantma@anathoth.gen.nz>
  6. *
  7. * iso-format handling added by Robert Griebl <griebl@gmx.de>
  8. * bugfixes and cleanup by Bernhard Reutner-Fischer
  9. *
  10. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  11. */
  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
  16. mail commands */
  17. /* Input parsing code is always bulky - used heavy duty libc stuff as
  18. much as possible, missed out a lot of bounds checking */
  19. //config:config DATE
  20. //config: bool "date"
  21. //config: default y
  22. //config: help
  23. //config: date is used to set the system date or display the
  24. //config: current time in the given format.
  25. //config:
  26. //config:config FEATURE_DATE_ISOFMT
  27. //config: bool "Enable ISO date format output (-I)"
  28. //config: default y
  29. //config: depends on DATE
  30. //config: help
  31. //config: Enable option (-I) to output an ISO-8601 compliant
  32. //config: date/time string.
  33. //config:
  34. //config:# defaults to "no": stat's nanosecond field is a bit non-portable
  35. //config:config FEATURE_DATE_NANO
  36. //config: bool "Support %[num]N nanosecond format specifier"
  37. //config: default n
  38. //config: depends on DATE # syscall(__NR_clock_gettime)
  39. //config: select PLATFORM_LINUX
  40. //config: help
  41. //config: Support %[num]N format specifier. Adds ~250 bytes of code.
  42. //config:
  43. //config:config FEATURE_DATE_COMPAT
  44. //config: bool "Support weird 'date MMDDhhmm[[YY]YY][.ss]' format"
  45. //config: default y
  46. //config: depends on DATE
  47. //config: help
  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).
  54. //config:
  55. //config: With this option off, 'date DATE' is 'date -s DATE' support
  56. //config: the same format. With it on, 'date DATE' additionally supports
  57. //config: MMDDhhmm[[YY]YY][.ss] format.
  58. //applet:IF_DATE(APPLET(date, BB_DIR_BIN, BB_SUID_DROP))
  59. //kbuild:lib-$(CONFIG_DATE) += date.o
  60. /* GNU coreutils 6.9 man page:
  61. * date [OPTION]... [+FORMAT]
  62. * date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
  63. * -d, --date=STRING
  64. * display time described by STRING, not `now'
  65. * -f, --file=DATEFILE
  66. * like --date once for each line of DATEFILE
  67. * -r, --reference=FILE
  68. * display the last modification time of FILE
  69. * -R, --rfc-2822
  70. * output date and time in RFC 2822 format.
  71. * Example: Mon, 07 Aug 2006 12:34:56 -0600
  72. * --rfc-3339=TIMESPEC
  73. * output date and time in RFC 3339 format.
  74. * TIMESPEC='date', 'seconds', or 'ns'
  75. * Date and time components are separated by a single space:
  76. * 2006-08-07 12:34:56-06:00
  77. * -s, --set=STRING
  78. * set time described by STRING
  79. * -u, --utc, --universal
  80. * print or set Coordinated Universal Time
  81. *
  82. * Busybox:
  83. * long options are not supported
  84. * -f is not supported
  85. * -I seems to roughly match --rfc-3339, but -I has _optional_ param
  86. * (thus "-I seconds" doesn't work, only "-Iseconds"),
  87. * and does not support -Ins
  88. * -D FMT is a bbox extension for _input_ conversion of -d DATE
  89. */
  90. //usage:#define date_trivial_usage
  91. //usage: "[OPTIONS] [+FMT] [TIME]"
  92. //usage:#define date_full_usage "\n\n"
  93. //usage: "Display time (using +FMT), or set time\n"
  94. //usage: IF_NOT_LONG_OPTS(
  95. //usage: "\n [-s] TIME Set time to TIME"
  96. //usage: "\n -u Work in UTC (don't convert to local time)"
  97. //usage: "\n -R Output RFC-2822 compliant date string"
  98. //usage: ) IF_LONG_OPTS(
  99. //usage: "\n [-s,--set] TIME Set time to TIME"
  100. //usage: "\n -u,--utc Work in UTC (don't convert to local time)"
  101. //usage: "\n -R,--rfc-2822 Output RFC-2822 compliant date string"
  102. //usage: )
  103. //usage: IF_FEATURE_DATE_ISOFMT(
  104. //usage: "\n -I[SPEC] Output ISO-8601 compliant date string"
  105. //usage: "\n SPEC='date' (default) for date only,"
  106. //usage: "\n 'hours', 'minutes', or 'seconds' for date and"
  107. //usage: "\n time to the indicated precision"
  108. //usage: )
  109. //usage: IF_NOT_LONG_OPTS(
  110. //usage: "\n -r FILE Display last modification time of FILE"
  111. //usage: "\n -d TIME Display TIME, not 'now'"
  112. //usage: ) IF_LONG_OPTS(
  113. //usage: "\n -r,--reference FILE Display last modification time of FILE"
  114. //usage: "\n -d,--date TIME Display TIME, not 'now'"
  115. //usage: )
  116. //usage: IF_FEATURE_DATE_ISOFMT(
  117. //usage: "\n -D FMT Use FMT for -d TIME conversion"
  118. //usage: )
  119. //usage: "\n"
  120. //usage: "\nRecognized TIME formats:"
  121. //usage: "\n hh:mm[:ss]"
  122. //usage: "\n [YYYY.]MM.DD-hh:mm[:ss]"
  123. //usage: "\n YYYY-MM-DD hh:mm[:ss]"
  124. //usage: "\n [[[[[YY]YY]MM]DD]hh]mm[.ss]"
  125. //usage: IF_FEATURE_DATE_COMPAT(
  126. //usage: "\n 'date TIME' form accepts MMDDhhmm[[YY]YY][.ss] instead"
  127. //usage: )
  128. //usage:
  129. //usage:#define date_example_usage
  130. //usage: "$ date\n"
  131. //usage: "Wed Apr 12 18:52:41 MDT 2000\n"
  132. #include "libbb.h"
  133. #include "common_bufsiz.h"
  134. #if ENABLE_FEATURE_DATE_NANO
  135. # include <sys/syscall.h>
  136. #endif
  137. enum {
  138. OPT_RFC2822 = (1 << 0), /* R */
  139. OPT_SET = (1 << 1), /* s */
  140. OPT_UTC = (1 << 2), /* u */
  141. OPT_DATE = (1 << 3), /* d */
  142. OPT_REFERENCE = (1 << 4), /* r */
  143. OPT_TIMESPEC = (1 << 5) * ENABLE_FEATURE_DATE_ISOFMT, /* I */
  144. OPT_HINT = (1 << 6) * ENABLE_FEATURE_DATE_ISOFMT, /* D */
  145. };
  146. static void maybe_set_utc(int opt)
  147. {
  148. if (opt & OPT_UTC)
  149. putenv((char*)"TZ=UTC0");
  150. }
  151. #if ENABLE_LONG_OPTS
  152. static const char date_longopts[] ALIGN1 =
  153. "rfc-822\0" No_argument "R"
  154. "rfc-2822\0" No_argument "R"
  155. "set\0" Required_argument "s"
  156. "utc\0" No_argument "u"
  157. /* "universal\0" No_argument "u" */
  158. "date\0" Required_argument "d"
  159. "reference\0" Required_argument "r"
  160. ;
  161. #endif
  162. int date_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  163. int date_main(int argc UNUSED_PARAM, char **argv)
  164. {
  165. struct timespec ts;
  166. struct tm tm_time;
  167. char buf_fmt_dt2str[64];
  168. unsigned opt;
  169. int ifmt = -1;
  170. char *date_str;
  171. char *fmt_dt2str;
  172. char *fmt_str2dt;
  173. char *filename;
  174. char *isofmt_arg = NULL;
  175. opt_complementary = "d--s:s--d"
  176. IF_FEATURE_DATE_ISOFMT(":R--I:I--R");
  177. IF_LONG_OPTS(applet_long_options = date_longopts;)
  178. opt = getopt32(argv, "Rs:ud:r:"
  179. IF_FEATURE_DATE_ISOFMT("I::D:"),
  180. &date_str, &date_str, &filename
  181. IF_FEATURE_DATE_ISOFMT(, &isofmt_arg, &fmt_str2dt));
  182. argv += optind;
  183. maybe_set_utc(opt);
  184. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_TIMESPEC)) {
  185. ifmt = 0; /* default is date */
  186. if (isofmt_arg) {
  187. static const char isoformats[] ALIGN1 =
  188. "date\0""hours\0""minutes\0""seconds\0"; /* ns? */
  189. ifmt = index_in_substrings(isoformats, isofmt_arg);
  190. if (ifmt < 0)
  191. bb_show_usage();
  192. }
  193. }
  194. fmt_dt2str = NULL;
  195. if (argv[0] && argv[0][0] == '+') {
  196. fmt_dt2str = &argv[0][1]; /* skip over the '+' */
  197. argv++;
  198. }
  199. if (!(opt & (OPT_SET | OPT_DATE))) {
  200. opt |= OPT_SET;
  201. date_str = argv[0]; /* can be NULL */
  202. if (date_str) {
  203. #if ENABLE_FEATURE_DATE_COMPAT
  204. int len = strspn(date_str, "0123456789");
  205. if (date_str[len] == '\0'
  206. || (date_str[len] == '.'
  207. && isdigit(date_str[len+1])
  208. && isdigit(date_str[len+2])
  209. && date_str[len+3] == '\0'
  210. )
  211. ) {
  212. /* Dreaded MMDDhhmm[[CC]YY][.ss] format!
  213. * It does not match -d or -s format.
  214. * Some users actually do use it.
  215. */
  216. len -= 8;
  217. if (len < 0 || len > 4 || (len & 1))
  218. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  219. if (len != 0) { /* move YY or CCYY to front */
  220. char buf[4];
  221. memcpy(buf, date_str + 8, len);
  222. memmove(date_str + len, date_str, 8);
  223. memcpy(date_str, buf, len);
  224. }
  225. }
  226. #endif
  227. argv++;
  228. }
  229. }
  230. if (*argv)
  231. bb_show_usage();
  232. /* Now we have parsed all the information except the date format
  233. * which depends on whether the clock is being set or read */
  234. if (opt & OPT_REFERENCE) {
  235. struct stat statbuf;
  236. xstat(filename, &statbuf);
  237. ts.tv_sec = statbuf.st_mtime;
  238. #if ENABLE_FEATURE_DATE_NANO
  239. ts.tv_nsec = statbuf.st_mtim.tv_nsec;
  240. /* Some toolchains use .st_mtimensec instead of st_mtim.tv_nsec.
  241. * If you need #define _SVID_SOURCE 1 to enable st_mtim.tv_nsec,
  242. * drop a mail to project mailing list please
  243. */
  244. #endif
  245. } else {
  246. #if ENABLE_FEATURE_DATE_NANO
  247. /* libc has incredibly messy way of doing this,
  248. * typically requiring -lrt. We just skip all this mess */
  249. syscall(__NR_clock_gettime, CLOCK_REALTIME, &ts);
  250. #else
  251. time(&ts.tv_sec);
  252. #endif
  253. }
  254. localtime_r(&ts.tv_sec, &tm_time);
  255. /* If date string is given, update tm_time, and maybe set date */
  256. if (date_str != NULL) {
  257. /* Zero out fields - take her back to midnight! */
  258. tm_time.tm_sec = 0;
  259. tm_time.tm_min = 0;
  260. tm_time.tm_hour = 0;
  261. /* Process any date input to UNIX time since 1 Jan 1970 */
  262. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_HINT)) {
  263. if (strptime(date_str, fmt_str2dt, &tm_time) == NULL)
  264. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  265. } else {
  266. parse_datestr(date_str, &tm_time);
  267. }
  268. /* Correct any day of week and day of year etc. fields */
  269. /* Be sure to recheck dst (but not if date is time_t format) */
  270. if (date_str[0] != '@')
  271. tm_time.tm_isdst = -1;
  272. ts.tv_sec = validate_tm_time(date_str, &tm_time);
  273. maybe_set_utc(opt);
  274. /* if setting time, set it */
  275. if ((opt & OPT_SET) && stime(&ts.tv_sec) < 0) {
  276. bb_perror_msg("can't set date");
  277. }
  278. }
  279. /* Display output */
  280. /* Deal with format string */
  281. if (fmt_dt2str == NULL) {
  282. int i;
  283. fmt_dt2str = buf_fmt_dt2str;
  284. if (ENABLE_FEATURE_DATE_ISOFMT && ifmt >= 0) {
  285. /* -I[SPEC]: 0:date 1:hours 2:minutes 3:seconds */
  286. strcpy(fmt_dt2str, "%Y-%m-%dT%H:%M:%S");
  287. i = 8 + 3 * ifmt;
  288. if (ifmt != 0) {
  289. /* TODO: if (ifmt==4) i += sprintf(&fmt_dt2str[i], ",%09u", nanoseconds); */
  290. format_utc:
  291. fmt_dt2str[i++] = '%';
  292. fmt_dt2str[i++] = (opt & OPT_UTC) ? 'Z' : 'z';
  293. }
  294. fmt_dt2str[i] = '\0';
  295. } else if (opt & OPT_RFC2822) {
  296. /* -R. undo busybox.c setlocale */
  297. if (ENABLE_LOCALE_SUPPORT)
  298. setlocale(LC_TIME, "C");
  299. strcpy(fmt_dt2str, "%a, %d %b %Y %H:%M:%S ");
  300. i = sizeof("%a, %d %b %Y %H:%M:%S ")-1;
  301. goto format_utc;
  302. } else { /* default case */
  303. fmt_dt2str = (char*)"%a %b %e %H:%M:%S %Z %Y";
  304. }
  305. }
  306. #if ENABLE_FEATURE_DATE_NANO
  307. else {
  308. /* User-specified fmt_dt2str */
  309. /* Search for and process "%N" */
  310. char *p = fmt_dt2str;
  311. while ((p = strchr(p, '%')) != NULL) {
  312. int n, m;
  313. unsigned pres, scale;
  314. p++;
  315. if (*p == '%') {
  316. p++;
  317. continue;
  318. }
  319. n = strspn(p, "0123456789");
  320. if (p[n] != 'N') {
  321. p += n;
  322. continue;
  323. }
  324. /* We have "%[nnn]N" */
  325. p[-1] = '\0';
  326. p[n] = '\0';
  327. scale = 1;
  328. pres = 9;
  329. if (n) {
  330. pres = xatoi_positive(p);
  331. if (pres == 0)
  332. pres = 9;
  333. m = 9 - pres;
  334. while (--m >= 0)
  335. scale *= 10;
  336. }
  337. m = p - fmt_dt2str;
  338. p += n + 1;
  339. fmt_dt2str = xasprintf("%s%0*u%s", fmt_dt2str, pres, (unsigned)ts.tv_nsec / scale, p);
  340. p = fmt_dt2str + m;
  341. }
  342. }
  343. #endif
  344. #define date_buf bb_common_bufsiz1
  345. setup_common_bufsiz();
  346. if (*fmt_dt2str == '\0') {
  347. /* With no format string, just print a blank line */
  348. date_buf[0] = '\0';
  349. } else {
  350. /* Handle special conversions */
  351. if (is_prefixed_with(fmt_dt2str, "%f")) {
  352. fmt_dt2str = (char*)"%Y.%m.%d-%H:%M:%S";
  353. }
  354. /* Generate output string */
  355. strftime(date_buf, COMMON_BUFSIZE, fmt_dt2str, &tm_time);
  356. }
  357. puts(date_buf);
  358. return EXIT_SUCCESS;
  359. }