date.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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] [[-s] 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 FMT (strptime format) for -s/-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), hours, minutes, seconds or ns"
  105. //usage: )
  106. //usage: "\n"
  107. //usage: "\nRecognized TIME formats:"
  108. //usage: "\n @seconds_since_1970"
  109. //usage: "\n hh:mm[:ss]"
  110. //usage: "\n [YYYY.]MM.DD-hh:mm[:ss]"
  111. //usage: "\n YYYY-MM-DD hh:mm[:ss]"
  112. //usage: "\n [[[[[YY]YY]MM]DD]hh]mm[.ss]"
  113. //usage: IF_FEATURE_DATE_COMPAT(
  114. //usage: "\n 'date TIME' form accepts MMDDhhmm[[YY]YY][.ss] instead"
  115. //usage: )
  116. //usage:
  117. //usage:#define date_example_usage
  118. //usage: "$ date\n"
  119. //usage: "Wed Apr 12 18:52:41 MDT 2000\n"
  120. #include "libbb.h"
  121. #include "common_bufsiz.h"
  122. #if ENABLE_FEATURE_DATE_NANO
  123. # include <sys/syscall.h>
  124. #endif
  125. enum {
  126. OPT_RFC2822 = (1 << 0), /* R */
  127. OPT_SET = (1 << 1), /* s */
  128. OPT_UTC = (1 << 2), /* u */
  129. OPT_DATE = (1 << 3), /* d */
  130. OPT_REFERENCE = (1 << 4), /* r */
  131. OPT_ISO8601 = (1 << 5) * ENABLE_FEATURE_DATE_ISOFMT, /* I */
  132. OPT_STR2DT = (1 << 6) * ENABLE_FEATURE_DATE_ISOFMT, /* D */
  133. };
  134. #if ENABLE_LONG_OPTS
  135. static const char date_longopts[] ALIGN1 =
  136. "rfc-822\0" No_argument "R"
  137. "rfc-2822\0" No_argument "R"
  138. "set\0" Required_argument "s"
  139. "utc\0" No_argument "u"
  140. /* "universal\0" No_argument "u" */
  141. "date\0" Required_argument "d"
  142. "reference\0" Required_argument "r"
  143. ;
  144. #endif
  145. /* We are a NOEXEC applet.
  146. * Obstacles to NOFORK:
  147. * - we change env
  148. * - xasprintf result not freed
  149. * - after xasprintf we use other xfuncs
  150. */
  151. int date_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  152. int date_main(int argc UNUSED_PARAM, char **argv)
  153. {
  154. struct timespec ts;
  155. struct tm tm_time;
  156. char buf_fmt_dt2str[64];
  157. unsigned opt;
  158. int isofmt = -1;
  159. char *date_str;
  160. char *fmt_dt2str;
  161. char *fmt_str2dt;
  162. char *filename;
  163. char *isofmt_arg = NULL;
  164. opt = getopt32long(argv, "^"
  165. "Rs:ud:r:"
  166. IF_FEATURE_DATE_ISOFMT("I::D:")
  167. "\0"
  168. "d--s:s--d"
  169. IF_FEATURE_DATE_ISOFMT(":R--I:I--R"),
  170. date_longopts,
  171. &date_str, &date_str, &filename
  172. IF_FEATURE_DATE_ISOFMT(, &isofmt_arg, &fmt_str2dt)
  173. );
  174. argv += optind;
  175. if (opt & OPT_UTC)
  176. putenv((char*)"TZ=UTC0");
  177. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_ISO8601)) {
  178. isofmt = 0; /* default is date */
  179. if (isofmt_arg) {
  180. static const char isoformats[] ALIGN1 =
  181. "date\0""hours\0""minutes\0""seconds\0ns\0";
  182. isofmt = index_in_substrings(isoformats, isofmt_arg);
  183. if (isofmt < 0)
  184. bb_show_usage();
  185. }
  186. }
  187. fmt_dt2str = NULL;
  188. if (argv[0] && argv[0][0] == '+') {
  189. fmt_dt2str = &argv[0][1]; /* skip over the '+' */
  190. argv++;
  191. }
  192. if (!(opt & (OPT_SET | OPT_DATE))) { /* neither -s TIME nor -d TIME? */
  193. opt |= OPT_SET;
  194. date_str = argv[0]; /* can be NULL */
  195. if (date_str) {
  196. #if ENABLE_FEATURE_DATE_COMPAT
  197. int len = strspn(date_str, "0123456789");
  198. if (date_str[len] == '\0'
  199. || (date_str[len] == '.'
  200. && isdigit(date_str[len+1])
  201. && isdigit(date_str[len+2])
  202. && date_str[len+3] == '\0'
  203. )
  204. ) {
  205. /* Dreaded MMDDhhmm[[CC]YY][.ss] format!
  206. * It does not match -d or -s format.
  207. * Some users actually do use it.
  208. */
  209. len -= 8;
  210. if (len < 0 || len > 4 || (len & 1))
  211. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  212. if (len != 0) { /* move YY or CCYY to front */
  213. char buf[4];
  214. memcpy(buf, date_str + 8, len);
  215. memmove(date_str + len, date_str, 8);
  216. memcpy(date_str, buf, len);
  217. }
  218. }
  219. #endif
  220. argv++;
  221. }
  222. }
  223. if (*argv)
  224. bb_show_usage();
  225. /* Now we have parsed all the information except the date format
  226. * which depends on whether the clock is being set or read */
  227. if (opt & OPT_REFERENCE) {
  228. struct stat statbuf;
  229. xstat(filename, &statbuf);
  230. ts.tv_sec = statbuf.st_mtime;
  231. #if ENABLE_FEATURE_DATE_NANO
  232. ts.tv_nsec = statbuf.st_mtim.tv_nsec;
  233. /* Some toolchains use .st_mtimensec instead of st_mtim.tv_nsec.
  234. * If you need #define _SVID_SOURCE 1 to enable st_mtim.tv_nsec,
  235. * drop a mail to project mailing list please
  236. */
  237. #endif
  238. } else {
  239. #if ENABLE_FEATURE_DATE_NANO
  240. clock_gettime(CLOCK_REALTIME, &ts);
  241. #else
  242. time(&ts.tv_sec);
  243. #endif
  244. }
  245. #if !ENABLE_FEATURE_DATE_NANO
  246. ts.tv_nsec = 0;
  247. #endif
  248. localtime_r(&ts.tv_sec, &tm_time);
  249. /* If date string is given, update tm_time, and maybe set date */
  250. if (date_str != NULL) {
  251. int check_dst = 1;
  252. /* Zero out fields - take her back to midnight! */
  253. tm_time.tm_sec = 0;
  254. tm_time.tm_min = 0;
  255. tm_time.tm_hour = 0;
  256. /* Process any date input to UNIX time since 1 Jan 1970 */
  257. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_STR2DT)) {
  258. if (strptime(date_str, fmt_str2dt, &tm_time) == NULL)
  259. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  260. } else {
  261. check_dst = parse_datestr(date_str, &tm_time);
  262. }
  263. /* Correct any day of week and day of year etc. fields */
  264. /* Be sure to recheck dst (but not if date is UTC) */
  265. if (check_dst)
  266. tm_time.tm_isdst = -1;
  267. ts.tv_sec = validate_tm_time(date_str, &tm_time);
  268. ts.tv_nsec = 0;
  269. /* if setting time, set it */
  270. if ((opt & OPT_SET) && clock_settime(CLOCK_REALTIME, &ts) < 0) {
  271. bb_simple_perror_msg("can't set date");
  272. }
  273. }
  274. /* Display output */
  275. /* Deal with format string */
  276. if (fmt_dt2str == NULL) {
  277. int i;
  278. fmt_dt2str = buf_fmt_dt2str;
  279. if (ENABLE_FEATURE_DATE_ISOFMT && isofmt >= 0) {
  280. /* -I[SPEC]: 0:date 1:hours 2:minutes 3:seconds 4:ns*/
  281. strcpy(fmt_dt2str, "%Y-%m-%dT%H:%M:%S");
  282. i = 8 + 3 * isofmt;
  283. if (isofmt != 0) {
  284. int n;
  285. if (isofmt == 4) {
  286. i -= 3;
  287. i += sprintf(&fmt_dt2str[i], ",%09u", (unsigned)ts.tv_nsec);
  288. }
  289. /* %z prints "+hhmm" timezone, but coreutils-8.30 prints "+hh:mm"! */
  290. /* ...therefore this atrocity: */
  291. n = strftime(&fmt_dt2str[i], 8, "%z", &tm_time);
  292. i += n;
  293. if (n == 5 && (fmt_dt2str[i-5] == '+' || fmt_dt2str[i-5] == '-')) {
  294. /* "mm" -> ":mm" */
  295. fmt_dt2str[i ] = fmt_dt2str[i - 1];
  296. fmt_dt2str[i - 1] = fmt_dt2str[i - 2];
  297. fmt_dt2str[i - 2] = ':';
  298. i++;
  299. }
  300. }
  301. fmt_dt2str[i] = '\0';
  302. } else if (opt & OPT_RFC2822) {
  303. /* -R. undo busybox.c setlocale */
  304. if (ENABLE_LOCALE_SUPPORT)
  305. setlocale(LC_TIME, "C");
  306. fmt_dt2str = (char*)"%a, %d %b %Y %H:%M:%S %z";
  307. } else { /* default case */
  308. fmt_dt2str = (char*)"%a %b %e %H:%M:%S %Z %Y";
  309. }
  310. }
  311. #if ENABLE_FEATURE_DATE_NANO
  312. else {
  313. /* User-specified fmt_dt2str */
  314. /* Search for and process "%N" */
  315. char *p = fmt_dt2str;
  316. while ((p = strchr(p, '%')) != NULL) {
  317. int n, m;
  318. unsigned pres, scale;
  319. p++;
  320. if (*p == '%') {
  321. p++;
  322. continue;
  323. }
  324. n = strspn(p, "0123456789");
  325. if (p[n] != 'N') {
  326. p += n;
  327. continue;
  328. }
  329. /* We have "%[nnn]N" */
  330. p[-1] = '\0';
  331. p[n] = '\0';
  332. scale = 1;
  333. pres = 9;
  334. if (n) {
  335. pres = xatoi_positive(p);
  336. if (pres == 0)
  337. pres = 9;
  338. m = 9 - pres;
  339. while (--m >= 0)
  340. scale *= 10;
  341. }
  342. m = p - fmt_dt2str;
  343. p += n + 1;
  344. fmt_dt2str = xasprintf("%s%0*u%s", fmt_dt2str, pres, (unsigned)ts.tv_nsec / scale, p);
  345. p = fmt_dt2str + m;
  346. }
  347. }
  348. #endif
  349. #define date_buf bb_common_bufsiz1
  350. setup_common_bufsiz();
  351. if (*fmt_dt2str == '\0') {
  352. /* With no format string, just print a blank line */
  353. date_buf[0] = '\0';
  354. } else {
  355. /* Generate output string */
  356. strftime(date_buf, COMMON_BUFSIZE, fmt_dt2str, &tm_time);
  357. }
  358. puts(date_buf);
  359. return EXIT_SUCCESS;
  360. }