date.c 12 KB

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