date.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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: help
  39. //config: Support %[num]N format specifier. Adds ~250 bytes of code.
  40. //config:
  41. //config:config FEATURE_DATE_COMPAT
  42. //config: bool "Support weird 'date MMDDhhmm[[YY]YY][.ss]' format"
  43. //config: default y
  44. //config: depends on DATE
  45. //config: help
  46. //config: System time can be set by 'date -s DATE' and simply 'date DATE',
  47. //config: but formats of DATE string are different. 'date DATE' accepts
  48. //config: a rather weird MMDDhhmm[[YY]YY][.ss] format with completely
  49. //config: unnatural placement of year between minutes and seconds.
  50. //config: date -s (and other commands like touch -d) use more sensible
  51. //config: formats (for one, ISO format YYYY-MM-DD hh:mm:ss.ssssss).
  52. //config:
  53. //config: With this option off, 'date DATE' and 'date -s DATE' support
  54. //config: the same format. With it on, 'date DATE' additionally supports
  55. //config: MMDDhhmm[[YY]YY][.ss] format.
  56. //applet:IF_DATE(APPLET_NOEXEC(date, date, BB_DIR_BIN, BB_SUID_DROP, date))
  57. /* bb_common_bufsiz1 usage here is safe wrt NOEXEC: not expecting it to be zeroed. */
  58. //kbuild:lib-$(CONFIG_DATE) += date.o
  59. /* GNU coreutils 6.9 man page:
  60. * date [OPTION]... [+FORMAT]
  61. * date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
  62. * -d, --date=STRING
  63. * display time described by STRING, not 'now'
  64. * -f, --file=DATEFILE
  65. * like --date once for each line of DATEFILE
  66. * -r, --reference=FILE
  67. * display the last modification time of FILE
  68. * -R, --rfc-2822
  69. * output date and time in RFC 2822 format.
  70. * Example: Mon, 07 Aug 2006 12:34:56 -0600
  71. * --rfc-3339=TIMESPEC
  72. * output date and time in RFC 3339 format.
  73. * TIMESPEC='date', 'seconds', or 'ns'
  74. * Date and time components are separated by a single space:
  75. * 2006-08-07 12:34:56-06:00
  76. * -s, --set=STRING
  77. * set time described by STRING
  78. * -u, --utc, --universal
  79. * print or set Coordinated Universal Time
  80. *
  81. * Busybox:
  82. * long options are not supported
  83. * -f is not supported
  84. * -I seems to roughly match --rfc-3339, but -I has _optional_ param
  85. * (thus "-I seconds" doesn't work, only "-Iseconds"),
  86. * and does not support -Ins
  87. * -D FMT is a bbox extension for _input_ conversion of -d DATE
  88. */
  89. //usage:#define date_trivial_usage
  90. //usage: "[OPTIONS] [+FMT] [TIME]"
  91. //usage:#define date_full_usage "\n\n"
  92. //usage: "Display time (using +FMT), or set time\n"
  93. //usage: "\n -u Work in UTC (don't convert to local time)"
  94. //usage: "\n [-s] TIME Set time to TIME"
  95. //usage: "\n -d TIME Display TIME, not 'now'"
  96. //usage: IF_FEATURE_DATE_ISOFMT(
  97. //usage: "\n -D FMT Use FMT (strptime format) for -d TIME conversion"
  98. //////// ^^^^^^ busybox invention, not compat
  99. //usage: )
  100. //usage: "\n -r FILE Display last modification time of FILE"
  101. //usage: "\n -R Output RFC-2822 date"
  102. //usage: IF_FEATURE_DATE_ISOFMT(
  103. //usage: "\n -I[SPEC] Output ISO-8601 date"
  104. //usage: "\n SPEC='date' (default) for date only,"
  105. //usage: "\n 'hours', 'minutes', 'seconds' or 'ns'"
  106. //usage: "\n for date and time"
  107. //usage: )
  108. //usage: "\n"
  109. //usage: "\nRecognized TIME formats:"
  110. //usage: "\n hh:mm[:ss]"
  111. //usage: "\n [YYYY.]MM.DD-hh:mm[:ss]"
  112. //usage: "\n YYYY-MM-DD hh:mm[:ss]"
  113. //usage: "\n [[[[[YY]YY]MM]DD]hh]mm[.ss]"
  114. //usage: IF_FEATURE_DATE_COMPAT(
  115. //usage: "\n 'date TIME' form accepts MMDDhhmm[[YY]YY][.ss] instead"
  116. //usage: )
  117. //usage:
  118. //usage:#define date_example_usage
  119. //usage: "$ date\n"
  120. //usage: "Wed Apr 12 18:52:41 MDT 2000\n"
  121. #include "libbb.h"
  122. #include "common_bufsiz.h"
  123. #if ENABLE_FEATURE_DATE_NANO
  124. # include <sys/syscall.h>
  125. #endif
  126. enum {
  127. OPT_RFC2822 = (1 << 0), /* R */
  128. OPT_SET = (1 << 1), /* s */
  129. OPT_UTC = (1 << 2), /* u */
  130. OPT_DATE = (1 << 3), /* d */
  131. OPT_REFERENCE = (1 << 4), /* r */
  132. OPT_TIMESPEC = (1 << 5) * ENABLE_FEATURE_DATE_ISOFMT, /* I */
  133. OPT_HINT = (1 << 6) * ENABLE_FEATURE_DATE_ISOFMT, /* D */
  134. };
  135. #if ENABLE_LONG_OPTS
  136. static const char date_longopts[] ALIGN1 =
  137. "rfc-822\0" No_argument "R"
  138. "rfc-2822\0" No_argument "R"
  139. "set\0" Required_argument "s"
  140. "utc\0" No_argument "u"
  141. /* "universal\0" No_argument "u" */
  142. "date\0" Required_argument "d"
  143. "reference\0" Required_argument "r"
  144. ;
  145. #endif
  146. /* We are a NOEXEC applet.
  147. * Obstacles to NOFORK:
  148. * - we change env
  149. * - xasprintf result not freed
  150. * - after xasprintf we use other xfuncs
  151. */
  152. static void maybe_set_utc(int opt)
  153. {
  154. if (opt & OPT_UTC)
  155. putenv((char*)"TZ=UTC0");
  156. }
  157. int date_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  158. int date_main(int argc UNUSED_PARAM, char **argv)
  159. {
  160. struct timespec ts;
  161. struct tm tm_time;
  162. char buf_fmt_dt2str[64];
  163. unsigned opt;
  164. int ifmt = -1;
  165. char *date_str;
  166. char *fmt_dt2str;
  167. char *fmt_str2dt;
  168. char *filename;
  169. char *isofmt_arg = NULL;
  170. opt = getopt32long(argv, "^"
  171. "Rs:ud:r:"
  172. IF_FEATURE_DATE_ISOFMT("I::D:")
  173. "\0"
  174. "d--s:s--d"
  175. IF_FEATURE_DATE_ISOFMT(":R--I:I--R"),
  176. date_longopts,
  177. &date_str, &date_str, &filename
  178. IF_FEATURE_DATE_ISOFMT(, &isofmt_arg, &fmt_str2dt)
  179. );
  180. argv += optind;
  181. maybe_set_utc(opt);
  182. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_TIMESPEC)) {
  183. ifmt = 0; /* default is date */
  184. if (isofmt_arg) {
  185. static const char isoformats[] ALIGN1 =
  186. "date\0""hours\0""minutes\0""seconds\0ns\0";
  187. ifmt = index_in_substrings(isoformats, isofmt_arg);
  188. if (ifmt < 0)
  189. bb_show_usage();
  190. }
  191. }
  192. fmt_dt2str = NULL;
  193. if (argv[0] && argv[0][0] == '+') {
  194. fmt_dt2str = &argv[0][1]; /* skip over the '+' */
  195. argv++;
  196. }
  197. if (!(opt & (OPT_SET | OPT_DATE))) {
  198. opt |= OPT_SET;
  199. date_str = argv[0]; /* can be NULL */
  200. if (date_str) {
  201. #if ENABLE_FEATURE_DATE_COMPAT
  202. int len = strspn(date_str, "0123456789");
  203. if (date_str[len] == '\0'
  204. || (date_str[len] == '.'
  205. && isdigit(date_str[len+1])
  206. && isdigit(date_str[len+2])
  207. && date_str[len+3] == '\0'
  208. )
  209. ) {
  210. /* Dreaded MMDDhhmm[[CC]YY][.ss] format!
  211. * It does not match -d or -s format.
  212. * Some users actually do use it.
  213. */
  214. len -= 8;
  215. if (len < 0 || len > 4 || (len & 1))
  216. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  217. if (len != 0) { /* move YY or CCYY to front */
  218. char buf[4];
  219. memcpy(buf, date_str + 8, len);
  220. memmove(date_str + len, date_str, 8);
  221. memcpy(date_str, buf, len);
  222. }
  223. }
  224. #endif
  225. argv++;
  226. }
  227. }
  228. if (*argv)
  229. bb_show_usage();
  230. /* Now we have parsed all the information except the date format
  231. * which depends on whether the clock is being set or read */
  232. if (opt & OPT_REFERENCE) {
  233. struct stat statbuf;
  234. xstat(filename, &statbuf);
  235. ts.tv_sec = statbuf.st_mtime;
  236. #if ENABLE_FEATURE_DATE_NANO
  237. ts.tv_nsec = statbuf.st_mtim.tv_nsec;
  238. /* Some toolchains use .st_mtimensec instead of st_mtim.tv_nsec.
  239. * If you need #define _SVID_SOURCE 1 to enable st_mtim.tv_nsec,
  240. * drop a mail to project mailing list please
  241. */
  242. #endif
  243. } else {
  244. #if ENABLE_FEATURE_DATE_NANO
  245. clock_gettime(CLOCK_REALTIME, &ts);
  246. #else
  247. time(&ts.tv_sec);
  248. #endif
  249. }
  250. #if !ENABLE_FEATURE_DATE_NANO
  251. ts.tv_nsec = 0;
  252. #endif
  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. ts.tv_nsec = 0;
  273. /* if setting time, set it */
  274. if ((opt & OPT_SET) && clock_settime(CLOCK_REALTIME, &ts) < 0) {
  275. bb_simple_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 4:ns*/
  285. strcpy(fmt_dt2str, "%Y-%m-%dT%H:%M:%S");
  286. i = 8 + 3 * ifmt;
  287. if (ifmt != 0) {
  288. int n;
  289. if (ifmt == 4) {
  290. i -= 3;
  291. i += sprintf(&fmt_dt2str[i], ",%09u", (unsigned)ts.tv_nsec);
  292. }
  293. /* %z prints "+hhmm" timezone, but coreutils-8.30 prints "+hh:mm"! */
  294. /* ...therefore this atrocity: */
  295. n = strftime(&fmt_dt2str[i], 8, "%z", &tm_time);
  296. i += n;
  297. if (n == 5 && (fmt_dt2str[i-5] == '+' || fmt_dt2str[i-5] == '-')) {
  298. /* "mm" -> ":mm" */
  299. fmt_dt2str[i ] = fmt_dt2str[i - 1];
  300. fmt_dt2str[i - 1] = fmt_dt2str[i - 2];
  301. fmt_dt2str[i - 2] = ':';
  302. i++;
  303. }
  304. }
  305. fmt_dt2str[i] = '\0';
  306. } else if (opt & OPT_RFC2822) {
  307. /* -R. undo busybox.c setlocale */
  308. if (ENABLE_LOCALE_SUPPORT)
  309. setlocale(LC_TIME, "C");
  310. fmt_dt2str = (char*)"%a, %d %b %Y %H:%M:%S %z";
  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. /* Generate output string */
  360. strftime(date_buf, COMMON_BUFSIZE, fmt_dt2str, &tm_time);
  361. }
  362. puts(date_buf);
  363. return EXIT_SUCCESS;
  364. }