date.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. //applet:IF_DATE(APPLET(date, BB_DIR_BIN, BB_SUID_DROP))
  20. //kbuild:lib-$(CONFIG_DATE) += date.o
  21. //config:config DATE
  22. //config: bool "date"
  23. //config: default y
  24. //config: help
  25. //config: date is used to set the system date or display the
  26. //config: current time in the given format.
  27. //config:
  28. //config:config FEATURE_DATE_ISOFMT
  29. //config: bool "Enable ISO date format output (-I)"
  30. //config: default y
  31. //config: depends on DATE
  32. //config: help
  33. //config: Enable option (-I) to output an ISO-8601 compliant
  34. //config: date/time string.
  35. //config:
  36. //config:# defaults to "no": stat's nanosecond field is a bit non-portable
  37. //config:config FEATURE_DATE_NANO
  38. //config: bool "Support %[num]N nanosecond format specifier"
  39. //config: default n
  40. //config: depends on DATE # syscall(__NR_clock_gettime)
  41. //config: select PLATFORM_LINUX
  42. //config: help
  43. //config: Support %[num]N format specifier. Adds ~250 bytes of code.
  44. //config:
  45. //config:config FEATURE_DATE_COMPAT
  46. //config: bool "Support weird 'date MMDDhhmm[[YY]YY][.ss]' format"
  47. //config: default y
  48. //config: depends on DATE
  49. //config: help
  50. //config: System time can be set by 'date -s DATE' and simply 'date DATE',
  51. //config: but formats of DATE string are different. 'date DATE' accepts
  52. //config: a rather weird MMDDhhmm[[YY]YY][.ss] format with completely
  53. //config: unnatural placement of year between minutes and seconds.
  54. //config: date -s (and other commands like touch -d) use more sensible
  55. //config: formats (for one, ISO format YYYY-MM-DD hh:mm:ss.ssssss).
  56. //config:
  57. //config: With this option off, 'date DATE' is 'date -s DATE' support
  58. //config: the same format. With it on, 'date DATE' additionally supports
  59. //config: MMDDhhmm[[YY]YY][.ss] format.
  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. #if ENABLE_FEATURE_DATE_NANO
  134. # include <sys/syscall.h>
  135. #endif
  136. enum {
  137. OPT_RFC2822 = (1 << 0), /* R */
  138. OPT_SET = (1 << 1), /* s */
  139. OPT_UTC = (1 << 2), /* u */
  140. OPT_DATE = (1 << 3), /* d */
  141. OPT_REFERENCE = (1 << 4), /* r */
  142. OPT_TIMESPEC = (1 << 5) * ENABLE_FEATURE_DATE_ISOFMT, /* I */
  143. OPT_HINT = (1 << 6) * ENABLE_FEATURE_DATE_ISOFMT, /* D */
  144. };
  145. static void maybe_set_utc(int opt)
  146. {
  147. if (opt & OPT_UTC)
  148. putenv((char*)"TZ=UTC0");
  149. }
  150. #if ENABLE_LONG_OPTS
  151. static const char date_longopts[] ALIGN1 =
  152. "rfc-822\0" No_argument "R"
  153. "rfc-2822\0" No_argument "R"
  154. "set\0" Required_argument "s"
  155. "utc\0" No_argument "u"
  156. /* "universal\0" No_argument "u" */
  157. "date\0" Required_argument "d"
  158. "reference\0" Required_argument "r"
  159. ;
  160. #endif
  161. int date_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  162. int date_main(int argc UNUSED_PARAM, char **argv)
  163. {
  164. struct timespec ts;
  165. struct tm tm_time;
  166. char buf_fmt_dt2str[64];
  167. unsigned opt;
  168. int ifmt = -1;
  169. char *date_str;
  170. char *fmt_dt2str;
  171. char *fmt_str2dt;
  172. char *filename;
  173. char *isofmt_arg = NULL;
  174. opt_complementary = "d--s:s--d"
  175. IF_FEATURE_DATE_ISOFMT(":R--I:I--R");
  176. IF_LONG_OPTS(applet_long_options = date_longopts;)
  177. opt = getopt32(argv, "Rs:ud:r:"
  178. IF_FEATURE_DATE_ISOFMT("I::D:"),
  179. &date_str, &date_str, &filename
  180. IF_FEATURE_DATE_ISOFMT(, &isofmt_arg, &fmt_str2dt));
  181. argv += optind;
  182. maybe_set_utc(opt);
  183. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_TIMESPEC)) {
  184. ifmt = 0; /* default is date */
  185. if (isofmt_arg) {
  186. static const char isoformats[] ALIGN1 =
  187. "date\0""hours\0""minutes\0""seconds\0"; /* ns? */
  188. ifmt = index_in_substrings(isoformats, isofmt_arg);
  189. if (ifmt < 0)
  190. bb_show_usage();
  191. }
  192. }
  193. fmt_dt2str = NULL;
  194. if (argv[0] && argv[0][0] == '+') {
  195. fmt_dt2str = &argv[0][1]; /* skip over the '+' */
  196. argv++;
  197. }
  198. if (!(opt & (OPT_SET | OPT_DATE))) {
  199. opt |= OPT_SET;
  200. date_str = argv[0]; /* can be NULL */
  201. if (date_str) {
  202. #if ENABLE_FEATURE_DATE_COMPAT
  203. int len = strspn(date_str, "0123456789");
  204. if (date_str[len] == '\0'
  205. || (date_str[len] == '.'
  206. && isdigit(date_str[len+1])
  207. && isdigit(date_str[len+2])
  208. && date_str[len+3] == '\0'
  209. )
  210. ) {
  211. /* Dreaded MMDDhhmm[[CC]YY][.ss] format!
  212. * It does not match -d or -s format.
  213. * Some users actually do use it.
  214. */
  215. len -= 8;
  216. if (len < 0 || len > 4 || (len & 1))
  217. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  218. if (len != 0) { /* move YY or CCYY to front */
  219. char buf[4];
  220. memcpy(buf, date_str + 8, len);
  221. memmove(date_str + len, date_str, 8);
  222. memcpy(date_str, buf, len);
  223. }
  224. }
  225. #endif
  226. argv++;
  227. }
  228. }
  229. if (*argv)
  230. bb_show_usage();
  231. /* Now we have parsed all the information except the date format
  232. * which depends on whether the clock is being set or read */
  233. if (opt & OPT_REFERENCE) {
  234. struct stat statbuf;
  235. xstat(filename, &statbuf);
  236. ts.tv_sec = statbuf.st_mtime;
  237. #if ENABLE_FEATURE_DATE_NANO
  238. ts.tv_nsec = statbuf.st_mtim.tv_nsec;
  239. /* Some toolchains use .st_mtimensec instead of st_mtim.tv_nsec.
  240. * If you need #define _SVID_SOURCE 1 to enable st_mtim.tv_nsec,
  241. * drop a mail to project mailing list please
  242. */
  243. #endif
  244. } else {
  245. #if ENABLE_FEATURE_DATE_NANO
  246. /* libc has incredibly messy way of doing this,
  247. * typically requiring -lrt. We just skip all this mess */
  248. syscall(__NR_clock_gettime, CLOCK_REALTIME, &ts);
  249. #else
  250. time(&ts.tv_sec);
  251. #endif
  252. }
  253. localtime_r(&ts.tv_sec, &tm_time);
  254. /* If date string is given, update tm_time, and maybe set date */
  255. if (date_str != NULL) {
  256. /* Zero out fields - take her back to midnight! */
  257. tm_time.tm_sec = 0;
  258. tm_time.tm_min = 0;
  259. tm_time.tm_hour = 0;
  260. /* Process any date input to UNIX time since 1 Jan 1970 */
  261. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_HINT)) {
  262. if (strptime(date_str, fmt_str2dt, &tm_time) == NULL)
  263. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  264. } else {
  265. parse_datestr(date_str, &tm_time);
  266. }
  267. /* Correct any day of week and day of year etc. fields */
  268. /* Be sure to recheck dst (but not if date is time_t format) */
  269. if (date_str[0] != '@')
  270. tm_time.tm_isdst = -1;
  271. ts.tv_sec = validate_tm_time(date_str, &tm_time);
  272. maybe_set_utc(opt);
  273. /* if setting time, set it */
  274. if ((opt & OPT_SET) && stime(&ts.tv_sec) < 0) {
  275. bb_perror_msg("can't set date");
  276. }
  277. }
  278. /* Display output */
  279. /* Deal with format string */
  280. if (fmt_dt2str == NULL) {
  281. int i;
  282. fmt_dt2str = buf_fmt_dt2str;
  283. if (ENABLE_FEATURE_DATE_ISOFMT && ifmt >= 0) {
  284. /* -I[SPEC]: 0:date 1:hours 2:minutes 3:seconds */
  285. strcpy(fmt_dt2str, "%Y-%m-%dT%H:%M:%S");
  286. i = 8 + 3 * ifmt;
  287. if (ifmt != 0) {
  288. /* TODO: if (ifmt==4) i += sprintf(&fmt_dt2str[i], ",%09u", nanoseconds); */
  289. format_utc:
  290. fmt_dt2str[i++] = '%';
  291. fmt_dt2str[i++] = (opt & OPT_UTC) ? 'Z' : 'z';
  292. }
  293. fmt_dt2str[i] = '\0';
  294. } else if (opt & OPT_RFC2822) {
  295. /* -R. undo busybox.c setlocale */
  296. if (ENABLE_LOCALE_SUPPORT)
  297. setlocale(LC_TIME, "C");
  298. strcpy(fmt_dt2str, "%a, %d %b %Y %H:%M:%S ");
  299. i = sizeof("%a, %d %b %Y %H:%M:%S ")-1;
  300. goto format_utc;
  301. } else { /* default case */
  302. fmt_dt2str = (char*)"%a %b %e %H:%M:%S %Z %Y";
  303. }
  304. }
  305. #if ENABLE_FEATURE_DATE_NANO
  306. else {
  307. /* User-specified fmt_dt2str */
  308. /* Search for and process "%N" */
  309. char *p = fmt_dt2str;
  310. while ((p = strchr(p, '%')) != NULL) {
  311. int n, m;
  312. unsigned pres, scale;
  313. p++;
  314. if (*p == '%') {
  315. p++;
  316. continue;
  317. }
  318. n = strspn(p, "0123456789");
  319. if (p[n] != 'N') {
  320. p += n;
  321. continue;
  322. }
  323. /* We have "%[nnn]N" */
  324. p[-1] = '\0';
  325. p[n] = '\0';
  326. scale = 1;
  327. pres = 9;
  328. if (n) {
  329. pres = xatoi_positive(p);
  330. if (pres == 0)
  331. pres = 9;
  332. m = 9 - pres;
  333. while (--m >= 0)
  334. scale *= 10;
  335. }
  336. m = p - fmt_dt2str;
  337. p += n + 1;
  338. fmt_dt2str = xasprintf("%s%0*u%s", fmt_dt2str, pres, (unsigned)ts.tv_nsec / scale, p);
  339. p = fmt_dt2str + m;
  340. }
  341. }
  342. #endif
  343. #define date_buf bb_common_bufsiz1
  344. if (*fmt_dt2str == '\0') {
  345. /* With no format string, just print a blank line */
  346. date_buf[0] = '\0';
  347. } else {
  348. /* Handle special conversions */
  349. if (is_prefixed_with(fmt_dt2str, "%f")) {
  350. fmt_dt2str = (char*)"%Y.%m.%d-%H:%M:%S";
  351. }
  352. /* Generate output string */
  353. strftime(date_buf, sizeof(date_buf), fmt_dt2str, &tm_time);
  354. }
  355. puts(date_buf);
  356. return EXIT_SUCCESS;
  357. }