date.c 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 tarball for details.
  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. /* Default input handling to save surprising some people */
  20. /* GNU coreutils 6.9 man page:
  21. * date [OPTION]... [+FORMAT]
  22. * date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
  23. * -d, --date=STRING
  24. * display time described by STRING, not `now'
  25. * -f, --file=DATEFILE
  26. * like --date once for each line of DATEFILE
  27. * -r, --reference=FILE
  28. * display the last modification time of FILE
  29. * -R, --rfc-2822
  30. * output date and time in RFC 2822 format.
  31. * Example: Mon, 07 Aug 2006 12:34:56 -0600
  32. * --rfc-3339=TIMESPEC
  33. * output date and time in RFC 3339 format.
  34. * TIMESPEC='date', 'seconds', or 'ns'
  35. * Date and time components are separated by a single space:
  36. * 2006-08-07 12:34:56-06:00
  37. * -s, --set=STRING
  38. * set time described by STRING
  39. * -u, --utc, --universal
  40. * print or set Coordinated Universal Time
  41. *
  42. * Busybox:
  43. * long options are not supported
  44. * -f is not supported
  45. * -I seems to roughly match --rfc-3339, but -I has _optional_ param
  46. * (thus "-I seconds" doesn't work, only "-Iseconds"),
  47. * and does not support -Ins
  48. * -D FMT is a bbox extension for _input_ conversion of -d DATE
  49. */
  50. //kbuild:lib-$(CONFIG_DATE) += date.o
  51. //config:config DATE
  52. //config: bool "date"
  53. //config: default y
  54. //config: help
  55. //config: date is used to set the system date or display the
  56. //config: current time in the given format.
  57. //config:
  58. //config:config FEATURE_DATE_ISOFMT
  59. //config: bool "Enable ISO date format output (-I)"
  60. //config: default y
  61. //config: depends on DATE
  62. //config: help
  63. //config: Enable option (-I) to output an ISO-8601 compliant
  64. //config: date/time string.
  65. //config:
  66. //config:config FEATURE_DATE_NANO
  67. //config: bool "Support %[num]N nanosecond format specifier"
  68. //config: default n
  69. //config: depends on DATE && PLATFORM_LINUX # syscall(__NR_clock_gettime)
  70. //config: help
  71. //config: Support %[num]N format specifier. Adds ~250 bytes of code.
  72. //config:
  73. //config:config FEATURE_DATE_COMPAT
  74. //config: bool "Support weird 'date MMDDhhmm[[YY]YY][.ss]' format"
  75. //config: default y
  76. //config: depends on DATE
  77. //config: help
  78. //config: System time can be set by 'date -s DATE' and simply 'date DATE',
  79. //config: but formats of DATE string are different. 'date DATE' accepts
  80. //config: a rather weird MMDDhhmm[[YY]YY][.ss] format with completely
  81. //config: unnatural placement of year between minutes and seconds.
  82. //config: date -s (and other commands like touch -d) use more sensible
  83. //config: formats (for one, ISO format YYYY-MM-DD hh:mm:ss.ssssss).
  84. //config:
  85. //config: With this option off, 'date DATE' is 'date -s DATE' support
  86. //config: the same format. With it on, 'date DATE' additionally supports
  87. //config: MMDDhhmm[[YY]YY][.ss] format.
  88. #include "libbb.h"
  89. #if ENABLE_FEATURE_DATE_NANO
  90. # include <sys/syscall.h>
  91. #endif
  92. enum {
  93. OPT_RFC2822 = (1 << 0), /* R */
  94. OPT_SET = (1 << 1), /* s */
  95. OPT_UTC = (1 << 2), /* u */
  96. OPT_DATE = (1 << 3), /* d */
  97. OPT_REFERENCE = (1 << 4), /* r */
  98. OPT_TIMESPEC = (1 << 5) * ENABLE_FEATURE_DATE_ISOFMT, /* I */
  99. OPT_HINT = (1 << 6) * ENABLE_FEATURE_DATE_ISOFMT, /* D */
  100. };
  101. static void maybe_set_utc(int opt)
  102. {
  103. if (opt & OPT_UTC)
  104. putenv((char*)"TZ=UTC0");
  105. }
  106. #if ENABLE_LONG_OPTS
  107. static const char date_longopts[] ALIGN1 =
  108. "rfc-822\0" No_argument "R"
  109. "rfc-2822\0" No_argument "R"
  110. "set\0" Required_argument "s"
  111. "utc\0" No_argument "u"
  112. /* "universal\0" No_argument "u" */
  113. "date\0" Required_argument "d"
  114. "reference\0" Required_argument "r"
  115. ;
  116. #endif
  117. int date_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  118. int date_main(int argc UNUSED_PARAM, char **argv)
  119. {
  120. struct timespec ts;
  121. struct tm tm_time;
  122. char buf_fmt_dt2str[64];
  123. unsigned opt;
  124. int ifmt = -1;
  125. char *date_str;
  126. char *fmt_dt2str;
  127. char *fmt_str2dt;
  128. char *filename;
  129. char *isofmt_arg = NULL;
  130. opt_complementary = "d--s:s--d"
  131. IF_FEATURE_DATE_ISOFMT(":R--I:I--R");
  132. IF_LONG_OPTS(applet_long_options = date_longopts;)
  133. opt = getopt32(argv, "Rs:ud:r:"
  134. IF_FEATURE_DATE_ISOFMT("I::D:"),
  135. &date_str, &date_str, &filename
  136. IF_FEATURE_DATE_ISOFMT(, &isofmt_arg, &fmt_str2dt));
  137. argv += optind;
  138. maybe_set_utc(opt);
  139. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_TIMESPEC)) {
  140. ifmt = 0; /* default is date */
  141. if (isofmt_arg) {
  142. static const char isoformats[] ALIGN1 =
  143. "date\0""hours\0""minutes\0""seconds\0"; /* ns? */
  144. ifmt = index_in_substrings(isoformats, isofmt_arg);
  145. if (ifmt < 0)
  146. bb_show_usage();
  147. }
  148. }
  149. fmt_dt2str = NULL;
  150. if (argv[0] && argv[0][0] == '+') {
  151. fmt_dt2str = &argv[0][1]; /* skip over the '+' */
  152. argv++;
  153. }
  154. if (!(opt & (OPT_SET | OPT_DATE))) {
  155. opt |= OPT_SET;
  156. date_str = argv[0]; /* can be NULL */
  157. if (date_str) {
  158. #if ENABLE_FEATURE_DATE_COMPAT
  159. int len = strspn(date_str, "0123456789");
  160. if (date_str[len] == '\0'
  161. || (date_str[len] == '.'
  162. && isdigit(date_str[len+1])
  163. && isdigit(date_str[len+2])
  164. && date_str[len+3] == '\0'
  165. )
  166. ) {
  167. /* Dreaded MMDDhhmm[[CC]YY][.ss] format!
  168. * It does not match -d or -s format.
  169. * Some users actually do use it.
  170. */
  171. len -= 8;
  172. if (len < 0 || len > 4 || (len & 1))
  173. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  174. if (len != 0) { /* move YY or CCYY to front */
  175. char buf[4];
  176. memcpy(buf, date_str + 8, len);
  177. memmove(date_str + len, date_str, 8);
  178. memcpy(date_str, buf, len);
  179. }
  180. }
  181. #endif
  182. argv++;
  183. }
  184. }
  185. if (*argv)
  186. bb_show_usage();
  187. /* Now we have parsed all the information except the date format
  188. * which depends on whether the clock is being set or read */
  189. if (opt & OPT_REFERENCE) {
  190. struct stat statbuf;
  191. xstat(filename, &statbuf);
  192. ts.tv_sec = statbuf.st_mtime;
  193. #if ENABLE_FEATURE_DATE_NANO
  194. ts.tv_nsec = statbuf.st_mtim.tv_nsec;
  195. #endif
  196. } else {
  197. #if ENABLE_FEATURE_DATE_NANO
  198. /* libc has incredibly messy way of doing this,
  199. * typically requiring -lrt. We just skip all this mess */
  200. syscall(__NR_clock_gettime, CLOCK_REALTIME, &ts);
  201. #else
  202. time(&ts.tv_sec);
  203. #endif
  204. }
  205. localtime_r(&ts.tv_sec, &tm_time);
  206. /* If date string is given, update tm_time, and maybe set date */
  207. if (date_str != NULL) {
  208. /* Zero out fields - take her back to midnight! */
  209. tm_time.tm_sec = 0;
  210. tm_time.tm_min = 0;
  211. tm_time.tm_hour = 0;
  212. /* Process any date input to UNIX time since 1 Jan 1970 */
  213. if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_HINT)) {
  214. if (strptime(date_str, fmt_str2dt, &tm_time) == NULL)
  215. bb_error_msg_and_die(bb_msg_invalid_date, date_str);
  216. } else {
  217. parse_datestr(date_str, &tm_time);
  218. }
  219. /* Correct any day of week and day of year etc. fields */
  220. tm_time.tm_isdst = -1; /* Be sure to recheck dst */
  221. ts.tv_sec = validate_tm_time(date_str, &tm_time);
  222. maybe_set_utc(opt);
  223. /* if setting time, set it */
  224. if ((opt & OPT_SET) && stime(&ts.tv_sec) < 0) {
  225. bb_perror_msg("can't set date");
  226. }
  227. }
  228. /* Display output */
  229. /* Deal with format string */
  230. if (fmt_dt2str == NULL) {
  231. int i;
  232. fmt_dt2str = buf_fmt_dt2str;
  233. if (ENABLE_FEATURE_DATE_ISOFMT && ifmt >= 0) {
  234. /* -I[SPEC]: 0:date 1:hours 2:minutes 3:seconds */
  235. strcpy(fmt_dt2str, "%Y-%m-%dT%H:%M:%S");
  236. i = 8 + 3 * ifmt;
  237. if (ifmt != 0) {
  238. /* TODO: if (ifmt==4) i += sprintf(&fmt_dt2str[i], ",%09u", nanoseconds); */
  239. format_utc:
  240. fmt_dt2str[i++] = '%';
  241. fmt_dt2str[i++] = (opt & OPT_UTC) ? 'Z' : 'z';
  242. }
  243. fmt_dt2str[i] = '\0';
  244. } else if (opt & OPT_RFC2822) {
  245. /* -R. undo busybox.c setlocale */
  246. if (ENABLE_LOCALE_SUPPORT)
  247. setlocale(LC_TIME, "C");
  248. strcpy(fmt_dt2str, "%a, %d %b %Y %H:%M:%S ");
  249. i = sizeof("%a, %d %b %Y %H:%M:%S ")-1;
  250. goto format_utc;
  251. } else { /* default case */
  252. fmt_dt2str = (char*)"%a %b %e %H:%M:%S %Z %Y";
  253. }
  254. }
  255. #if ENABLE_FEATURE_DATE_NANO
  256. else {
  257. /* User-specified fmt_dt2str */
  258. /* Search for and process "%N" */
  259. char *p = fmt_dt2str;
  260. while ((p = strchr(p, '%')) != NULL) {
  261. int n, m;
  262. unsigned pres, scale;
  263. p++;
  264. if (*p == '%') {
  265. p++;
  266. continue;
  267. }
  268. n = strspn(p, "0123456789");
  269. if (p[n] != 'N') {
  270. p += n;
  271. continue;
  272. }
  273. /* We have "%[nnn]N" */
  274. p[-1] = '\0';
  275. p[n] = '\0';
  276. scale = 1;
  277. pres = 9;
  278. if (n) {
  279. pres = xatoi_u(p);
  280. if (pres == 0)
  281. pres = 9;
  282. m = 9 - pres;
  283. while (--m >= 0)
  284. scale *= 10;
  285. }
  286. m = p - fmt_dt2str;
  287. p += n + 1;
  288. fmt_dt2str = xasprintf("%s%0*u%s", fmt_dt2str, pres, (unsigned)ts.tv_nsec / scale, p);
  289. p = fmt_dt2str + m;
  290. }
  291. }
  292. #endif
  293. #define date_buf bb_common_bufsiz1
  294. if (*fmt_dt2str == '\0') {
  295. /* With no format string, just print a blank line */
  296. date_buf[0] = '\0';
  297. } else {
  298. /* Handle special conversions */
  299. if (strncmp(fmt_dt2str, "%f", 2) == 0) {
  300. fmt_dt2str = (char*)"%Y.%m.%d-%H:%M:%S";
  301. }
  302. /* Generate output string */
  303. strftime(date_buf, sizeof(date_buf), fmt_dt2str, &tm_time);
  304. }
  305. puts(date_buf);
  306. return EXIT_SUCCESS;
  307. }