date.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 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:config FEATURE_DATE_NANO
  35. //config: bool "Support %[num]N nanosecond format specifier"
  36. //config: default n # stat's nanosecond field is a bit non-portable
  37. //config: depends on DATE
  38. //config: select PLATFORM_LINUX
  39. //config: help
  40. //config: Support %[num]N format specifier. Adds ~250 bytes of code.
  41. //config:
  42. //config:config FEATURE_DATE_COMPAT
  43. //config: bool "Support weird 'date MMDDhhmm[[YY]YY][.ss]' format"
  44. //config: default y
  45. //config: depends on DATE
  46. //config: help
  47. //config: System time can be set by 'date -s DATE' and simply 'date DATE',
  48. //config: but formats of DATE string are different. 'date DATE' accepts
  49. //config: a rather weird MMDDhhmm[[YY]YY][.ss] format with completely
  50. //config: unnatural placement of year between minutes and seconds.
  51. //config: date -s (and other commands like touch -d) use more sensible
  52. //config: formats (for one, ISO format YYYY-MM-DD hh:mm:ss.ssssss).
  53. //config:
  54. //config: With this option off, 'date DATE' and 'date -s DATE' support
  55. //config: the same format. With it on, 'date DATE' additionally supports
  56. //config: MMDDhhmm[[YY]YY][.ss] format.
  57. //applet:IF_DATE(APPLET_NOEXEC(date, date, BB_DIR_BIN, BB_SUID_DROP, date))
  58. /* bb_common_bufsiz1 usage here is safe wrt NOEXEC: not expecting it to be zeroed. */
  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 (strptime format) 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. #if ENABLE_LONG_OPTS
  147. static const char date_longopts[] ALIGN1 =
  148. "rfc-822\0" No_argument "R"
  149. "rfc-2822\0" No_argument "R"
  150. "set\0" Required_argument "s"
  151. "utc\0" No_argument "u"
  152. /* "universal\0" No_argument "u" */
  153. "date\0" Required_argument "d"
  154. "reference\0" Required_argument "r"
  155. ;
  156. #endif
  157. /* We are a NOEXEC applet.
  158. * Obstacles to NOFORK:
  159. * - we change env
  160. * - xasprintf result not freed
  161. * - after xasprintf we use other xfuncs
  162. */
  163. static void maybe_set_utc(int opt)
  164. {
  165. if (opt & OPT_UTC)
  166. putenv((char*)"TZ=UTC0");
  167. }
  168. int date_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  169. int date_main(int argc UNUSED_PARAM, char **argv)
  170. {
  171. struct timespec ts;
  172. struct tm tm_time;
  173. char buf_fmt_dt2str[64];
  174. unsigned opt;
  175. int ifmt = -1;
  176. char *date_str;
  177. char *fmt_dt2str;
  178. char *fmt_str2dt;
  179. char *filename;
  180. char *isofmt_arg = NULL;
  181. opt = getopt32long(argv, "^"
  182. "Rs:ud:r:"
  183. IF_FEATURE_DATE_ISOFMT("I::D:")
  184. "\0"
  185. "d--s:s--d"
  186. IF_FEATURE_DATE_ISOFMT(":R--I:I--R"),
  187. date_longopts,
  188. &date_str, &date_str, &filename
  189. IF_FEATURE_DATE_ISOFMT(, &isofmt_arg, &fmt_str2dt)
  190. );
  191. argv += optind;
  192. maybe_set_utc(opt);
  193. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_TIMESPEC)) {
  194. ifmt = 0; /* default is date */
  195. if (isofmt_arg) {
  196. static const char isoformats[] ALIGN1 =
  197. "date\0""hours\0""minutes\0""seconds\0"; /* ns? */
  198. ifmt = index_in_substrings(isoformats, isofmt_arg);
  199. if (ifmt < 0)
  200. bb_show_usage();
  201. }
  202. }
  203. fmt_dt2str = NULL;
  204. if (argv[0] && argv[0][0] == '+') {
  205. fmt_dt2str = &argv[0][1]; /* skip over the '+' */
  206. argv++;
  207. }
  208. if (!(opt & (OPT_SET | OPT_DATE))) {
  209. opt |= OPT_SET;
  210. date_str = argv[0]; /* can be NULL */
  211. if (date_str) {
  212. #if ENABLE_FEATURE_DATE_COMPAT
  213. int len = strspn(date_str, "0123456789");
  214. if (date_str[len] == '\0'
  215. || (date_str[len] == '.'
  216. && isdigit(date_str[len+1])
  217. && isdigit(date_str[len+2])
  218. && date_str[len+3] == '\0'
  219. )
  220. ) {
  221. /* Dreaded MMDDhhmm[[CC]YY][.ss] format!
  222. * It does not match -d or -s format.
  223. * Some users actually do use it.
  224. */
  225. len -= 8;
  226. if (len < 0 || len > 4 || (len & 1))
  227. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  228. if (len != 0) { /* move YY or CCYY to front */
  229. char buf[4];
  230. memcpy(buf, date_str + 8, len);
  231. memmove(date_str + len, date_str, 8);
  232. memcpy(date_str, buf, len);
  233. }
  234. }
  235. #endif
  236. argv++;
  237. }
  238. }
  239. if (*argv)
  240. bb_show_usage();
  241. /* Now we have parsed all the information except the date format
  242. * which depends on whether the clock is being set or read */
  243. if (opt & OPT_REFERENCE) {
  244. struct stat statbuf;
  245. xstat(filename, &statbuf);
  246. ts.tv_sec = statbuf.st_mtime;
  247. #if ENABLE_FEATURE_DATE_NANO
  248. ts.tv_nsec = statbuf.st_mtim.tv_nsec;
  249. /* Some toolchains use .st_mtimensec instead of st_mtim.tv_nsec.
  250. * If you need #define _SVID_SOURCE 1 to enable st_mtim.tv_nsec,
  251. * drop a mail to project mailing list please
  252. */
  253. #endif
  254. } else {
  255. #if ENABLE_FEATURE_DATE_NANO
  256. clock_gettime(CLOCK_REALTIME, &ts);
  257. #else
  258. time(&ts.tv_sec);
  259. #endif
  260. }
  261. #if !ENABLE_FEATURE_DATE_NANO
  262. ts.tv_nsec = 0;
  263. #endif
  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. ts.tv_nsec = 0;
  284. /* if setting time, set it */
  285. if ((opt & OPT_SET) && clock_settime(CLOCK_REALTIME, &ts) < 0) {
  286. bb_simple_perror_msg("can't set date");
  287. }
  288. }
  289. /* Display output */
  290. /* Deal with format string */
  291. if (fmt_dt2str == NULL) {
  292. int i;
  293. fmt_dt2str = buf_fmt_dt2str;
  294. if (ENABLE_FEATURE_DATE_ISOFMT && ifmt >= 0) {
  295. /* -I[SPEC]: 0:date 1:hours 2:minutes 3:seconds */
  296. strcpy(fmt_dt2str, "%Y-%m-%dT%H:%M:%S");
  297. i = 8 + 3 * ifmt;
  298. if (ifmt != 0) {
  299. /* TODO: if (ifmt==4) i += sprintf(&fmt_dt2str[i], ",%09u", nanoseconds); */
  300. format_utc:
  301. fmt_dt2str[i++] = '%';
  302. fmt_dt2str[i++] = (opt & OPT_UTC) ? 'Z' : 'z';
  303. }
  304. fmt_dt2str[i] = '\0';
  305. } else if (opt & OPT_RFC2822) {
  306. /* -R. undo busybox.c setlocale */
  307. if (ENABLE_LOCALE_SUPPORT)
  308. setlocale(LC_TIME, "C");
  309. strcpy(fmt_dt2str, "%a, %d %b %Y %H:%M:%S ");
  310. i = sizeof("%a, %d %b %Y %H:%M:%S ")-1;
  311. goto format_utc;
  312. } else { /* default case */
  313. fmt_dt2str = (char*)"%a %b %e %H:%M:%S %Z %Y";
  314. }
  315. }
  316. #if ENABLE_FEATURE_DATE_NANO
  317. else {
  318. /* User-specified fmt_dt2str */
  319. /* Search for and process "%N" */
  320. char *p = fmt_dt2str;
  321. while ((p = strchr(p, '%')) != NULL) {
  322. int n, m;
  323. unsigned pres, scale;
  324. p++;
  325. if (*p == '%') {
  326. p++;
  327. continue;
  328. }
  329. n = strspn(p, "0123456789");
  330. if (p[n] != 'N') {
  331. p += n;
  332. continue;
  333. }
  334. /* We have "%[nnn]N" */
  335. p[-1] = '\0';
  336. p[n] = '\0';
  337. scale = 1;
  338. pres = 9;
  339. if (n) {
  340. pres = xatoi_positive(p);
  341. if (pres == 0)
  342. pres = 9;
  343. m = 9 - pres;
  344. while (--m >= 0)
  345. scale *= 10;
  346. }
  347. m = p - fmt_dt2str;
  348. p += n + 1;
  349. fmt_dt2str = xasprintf("%s%0*u%s", fmt_dt2str, pres, (unsigned)ts.tv_nsec / scale, p);
  350. p = fmt_dt2str + m;
  351. }
  352. }
  353. #endif
  354. #define date_buf bb_common_bufsiz1
  355. setup_common_bufsiz();
  356. if (*fmt_dt2str == '\0') {
  357. /* With no format string, just print a blank line */
  358. date_buf[0] = '\0';
  359. } else {
  360. /* Handle special conversions */
  361. if (is_prefixed_with(fmt_dt2str, "%f")) {
  362. fmt_dt2str = (char*)"%Y.%m.%d-%H:%M:%S";
  363. }
  364. /* Generate output string */
  365. strftime(date_buf, COMMON_BUFSIZE, fmt_dt2str, &tm_time);
  366. }
  367. puts(date_buf);
  368. return EXIT_SUCCESS;
  369. }