time_fmt.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /* Copyright (c) 2001, Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file time_fmt.c
  8. *
  9. * \brief Encode and decode time in various formats.
  10. *
  11. * This module is higher-level than the conversion functions in "wallclock",
  12. * and handles a larger variety of types. It converts between different time
  13. * formats, and encodes and decodes them from strings.
  14. **/
  15. #include "lib/encoding/time_fmt.h"
  16. #include "lib/log/log.h"
  17. #include "lib/log/escape.h"
  18. #include "lib/log/util_bug.h"
  19. #include "lib/malloc/malloc.h"
  20. #include "lib/string/printf.h"
  21. #include "lib/string/scanf.h"
  22. #include "lib/wallclock/time_to_tm.h"
  23. #include <string.h>
  24. #include <time.h>
  25. #ifdef HAVE_SYS_TIME_H
  26. #include <sys/time.h>
  27. #endif
  28. #ifdef _WIN32
  29. /* For struct timeval */
  30. #include <winsock2.h>
  31. #endif
  32. /** As localtime_r, but defined for platforms that don't have it:
  33. *
  34. * Convert *<b>timep</b> to a struct tm in local time, and store the value in
  35. * *<b>result</b>. Return the result on success, or NULL on failure.
  36. */
  37. struct tm *
  38. tor_localtime_r(const time_t *timep, struct tm *result)
  39. {
  40. char *err = NULL;
  41. struct tm *r = tor_localtime_r_msg(timep, result, &err);
  42. if (err) {
  43. log_warn(LD_BUG, "%s", err);
  44. tor_free(err);
  45. }
  46. return r;
  47. }
  48. /** As gmtime_r, but defined for platforms that don't have it:
  49. *
  50. * Convert *<b>timep</b> to a struct tm in UTC, and store the value in
  51. * *<b>result</b>. Return the result on success, or NULL on failure.
  52. */
  53. struct tm *
  54. tor_gmtime_r(const time_t *timep, struct tm *result)
  55. {
  56. char *err = NULL;
  57. struct tm *r = tor_gmtime_r_msg(timep, result, &err);
  58. if (err) {
  59. log_warn(LD_BUG, "%s", err);
  60. tor_free(err);
  61. }
  62. return r;
  63. }
  64. /** Yield true iff <b>y</b> is a leap-year. */
  65. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  66. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  67. static int
  68. n_leapdays(int year1, int year2)
  69. {
  70. --year1;
  71. --year2;
  72. return (year2/4 - year1/4) - (year2/100 - year1/100)
  73. + (year2/400 - year1/400);
  74. }
  75. /** Number of days per month in non-leap year; used by tor_timegm and
  76. * parse_rfc1123_time. */
  77. static const int days_per_month[] =
  78. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  79. /** Compute a time_t given a struct tm. The result is given in UTC, and
  80. * does not account for leap seconds. Return 0 on success, -1 on failure.
  81. */
  82. int
  83. tor_timegm(const struct tm *tm, time_t *time_out)
  84. {
  85. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  86. * It's way more brute-force than fiddling with tzset().
  87. *
  88. * We use int64_t rather than time_t to avoid overflow on multiplication on
  89. * platforms with 32-bit time_t. Since year is clipped to INT32_MAX, and
  90. * since 365 * 24 * 60 * 60 is approximately 31 million, it's not possible
  91. * for INT32_MAX years to overflow int64_t when converted to seconds. */
  92. int64_t year, days, hours, minutes, seconds;
  93. int i, invalid_year, dpm;
  94. /* Initialize time_out to 0 for now, to avoid bad usage in case this function
  95. fails and the caller ignores the return value. */
  96. tor_assert(time_out);
  97. *time_out = 0;
  98. /* avoid int overflow on addition */
  99. if (tm->tm_year < INT32_MAX-1900) {
  100. year = tm->tm_year + 1900;
  101. } else {
  102. /* clamp year */
  103. year = INT32_MAX;
  104. }
  105. invalid_year = (year < 1970 || tm->tm_year >= INT32_MAX-1900);
  106. if (tm->tm_mon >= 0 && tm->tm_mon <= 11) {
  107. dpm = days_per_month[tm->tm_mon];
  108. if (tm->tm_mon == 1 && !invalid_year && IS_LEAPYEAR(tm->tm_year)) {
  109. dpm = 29;
  110. }
  111. } else {
  112. /* invalid month - default to 0 days per month */
  113. dpm = 0;
  114. }
  115. if (invalid_year ||
  116. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  117. tm->tm_mday < 1 || tm->tm_mday > dpm ||
  118. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  119. tm->tm_min < 0 || tm->tm_min > 59 ||
  120. tm->tm_sec < 0 || tm->tm_sec > 60) {
  121. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  122. return -1;
  123. }
  124. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  125. for (i = 0; i < tm->tm_mon; ++i)
  126. days += days_per_month[i];
  127. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  128. ++days;
  129. days += tm->tm_mday - 1;
  130. hours = days*24 + tm->tm_hour;
  131. minutes = hours*60 + tm->tm_min;
  132. seconds = minutes*60 + tm->tm_sec;
  133. /* Check that "seconds" will fit in a time_t. On platforms where time_t is
  134. * 32-bit, this check will fail for dates in and after 2038.
  135. *
  136. * We already know that "seconds" can't be negative because "year" >= 1970 */
  137. #if SIZEOF_TIME_T < 8
  138. if (seconds < TIME_MIN || seconds > TIME_MAX) {
  139. log_warn(LD_BUG, "Result does not fit in tor_timegm");
  140. return -1;
  141. }
  142. #endif /* SIZEOF_TIME_T < 8 */
  143. *time_out = (time_t)seconds;
  144. return 0;
  145. }
  146. /* strftime is locale-specific, so we need to replace those parts */
  147. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  148. static const char *WEEKDAY_NAMES[] =
  149. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  150. /** A c-locale array of 3-letter names of months, starting with Jan. */
  151. static const char *MONTH_NAMES[] =
  152. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  153. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  154. /** Set <b>buf</b> to the RFC1123 encoding of the UTC value of <b>t</b>.
  155. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  156. *
  157. * (RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT"
  158. * rather than "UTC".)
  159. */
  160. void
  161. format_rfc1123_time(char *buf, time_t t)
  162. {
  163. struct tm tm;
  164. tor_gmtime_r(&t, &tm);
  165. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  166. tor_assert(tm.tm_wday >= 0);
  167. tor_assert(tm.tm_wday <= 6);
  168. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  169. tor_assert(tm.tm_mon >= 0);
  170. tor_assert(tm.tm_mon <= 11);
  171. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  172. }
  173. /** Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from
  174. * <b>buf</b>, and store the result in *<b>t</b>.
  175. *
  176. * Note that we only accept the subset generated by format_rfc1123_time above,
  177. * not the full range of formats suggested by RFC 1123.
  178. *
  179. * Return 0 on success, -1 on failure.
  180. */
  181. int
  182. parse_rfc1123_time(const char *buf, time_t *t)
  183. {
  184. struct tm tm;
  185. char month[4];
  186. char weekday[4];
  187. int i, m, invalid_year;
  188. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  189. unsigned dpm;
  190. if (strlen(buf) != RFC1123_TIME_LEN)
  191. return -1;
  192. memset(&tm, 0, sizeof(tm));
  193. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  194. &tm_mday, month, &tm_year, &tm_hour,
  195. &tm_min, &tm_sec) < 7) {
  196. char *esc = esc_for_log(buf);
  197. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  198. tor_free(esc);
  199. return -1;
  200. }
  201. m = -1;
  202. for (i = 0; i < 12; ++i) {
  203. if (!strcmp(month, MONTH_NAMES[i])) {
  204. m = i;
  205. break;
  206. }
  207. }
  208. if (m<0) {
  209. char *esc = esc_for_log(buf);
  210. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  211. tor_free(esc);
  212. return -1;
  213. }
  214. tm.tm_mon = m;
  215. invalid_year = (tm_year >= INT32_MAX || tm_year < 1970);
  216. tor_assert(m >= 0 && m <= 11);
  217. dpm = days_per_month[m];
  218. if (m == 1 && !invalid_year && IS_LEAPYEAR(tm_year)) {
  219. dpm = 29;
  220. }
  221. if (invalid_year || tm_mday < 1 || tm_mday > dpm ||
  222. tm_hour > 23 || tm_min > 59 || tm_sec > 60) {
  223. char *esc = esc_for_log(buf);
  224. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  225. tor_free(esc);
  226. return -1;
  227. }
  228. tm.tm_mday = (int)tm_mday;
  229. tm.tm_year = (int)tm_year;
  230. tm.tm_hour = (int)tm_hour;
  231. tm.tm_min = (int)tm_min;
  232. tm.tm_sec = (int)tm_sec;
  233. if (tm.tm_year < 1970) {
  234. /* LCOV_EXCL_START
  235. * XXXX I think this is dead code; we already checked for
  236. * invalid_year above. */
  237. tor_assert_nonfatal_unreached();
  238. char *esc = esc_for_log(buf);
  239. log_warn(LD_GENERAL,
  240. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  241. tor_free(esc);
  242. return -1;
  243. /* LCOV_EXCL_STOP */
  244. }
  245. tm.tm_year -= 1900;
  246. return tor_timegm(&tm, t);
  247. }
  248. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  249. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  250. *
  251. * (ISO8601 format is 2006-10-29 10:57:20)
  252. */
  253. void
  254. format_local_iso_time(char *buf, time_t t)
  255. {
  256. struct tm tm;
  257. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  258. }
  259. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  260. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  261. */
  262. void
  263. format_iso_time(char *buf, time_t t)
  264. {
  265. struct tm tm;
  266. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  267. }
  268. /** As format_local_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  269. * embedding an internal space. */
  270. void
  271. format_local_iso_time_nospace(char *buf, time_t t)
  272. {
  273. format_local_iso_time(buf, t);
  274. buf[10] = 'T';
  275. }
  276. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  277. * embedding an internal space. */
  278. void
  279. format_iso_time_nospace(char *buf, time_t t)
  280. {
  281. format_iso_time(buf, t);
  282. buf[10] = 'T';
  283. }
  284. /** As format_iso_time_nospace, but include microseconds in decimal
  285. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  286. * bytes long. */
  287. void
  288. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  289. {
  290. tor_assert(tv);
  291. format_iso_time_nospace(buf, (time_t)tv->tv_sec);
  292. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  293. }
  294. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  295. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  296. * failure. Ignore extraneous stuff in <b>cp</b> after the end of the time
  297. * string, unless <b>strict</b> is set. If <b>nospace</b> is set,
  298. * expect the YYYY-MM-DDTHH:MM:SS format. */
  299. int
  300. parse_iso_time_(const char *cp, time_t *t, int strict, int nospace)
  301. {
  302. struct tm st_tm;
  303. unsigned int year=0, month=0, day=0, hour=0, minute=0, second=0;
  304. int n_fields;
  305. char extra_char, separator_char;
  306. n_fields = tor_sscanf(cp, "%u-%2u-%2u%c%2u:%2u:%2u%c",
  307. &year, &month, &day,
  308. &separator_char,
  309. &hour, &minute, &second, &extra_char);
  310. if (strict ? (n_fields != 7) : (n_fields < 7)) {
  311. char *esc = esc_for_log(cp);
  312. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  313. tor_free(esc);
  314. return -1;
  315. }
  316. if (separator_char != (nospace ? 'T' : ' ')) {
  317. char *esc = esc_for_log(cp);
  318. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  319. tor_free(esc);
  320. return -1;
  321. }
  322. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  323. hour > 23 || minute > 59 || second > 60 || year >= INT32_MAX) {
  324. char *esc = esc_for_log(cp);
  325. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  326. tor_free(esc);
  327. return -1;
  328. }
  329. st_tm.tm_year = (int)year-1900;
  330. st_tm.tm_mon = month-1;
  331. st_tm.tm_mday = day;
  332. st_tm.tm_hour = hour;
  333. st_tm.tm_min = minute;
  334. st_tm.tm_sec = second;
  335. st_tm.tm_wday = 0; /* Should be ignored. */
  336. if (st_tm.tm_year < 70) {
  337. /* LCOV_EXCL_START
  338. * XXXX I think this is dead code; we already checked for
  339. * year < 1970 above. */
  340. tor_assert_nonfatal_unreached();
  341. char *esc = esc_for_log(cp);
  342. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  343. tor_free(esc);
  344. return -1;
  345. /* LCOV_EXCL_STOP */
  346. }
  347. return tor_timegm(&st_tm, t);
  348. }
  349. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  350. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  351. * failure. Reject the string if any characters are present after the time.
  352. */
  353. int
  354. parse_iso_time(const char *cp, time_t *t)
  355. {
  356. return parse_iso_time_(cp, t, 1, 0);
  357. }
  358. /**
  359. * As parse_iso_time, but parses a time encoded by format_iso_time_nospace().
  360. */
  361. int
  362. parse_iso_time_nospace(const char *cp, time_t *t)
  363. {
  364. return parse_iso_time_(cp, t, 1, 1);
  365. }
  366. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  367. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  368. int
  369. parse_http_time(const char *date, struct tm *tm)
  370. {
  371. const char *cp;
  372. char month[4];
  373. char wkday[4];
  374. int i;
  375. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  376. tor_assert(tm);
  377. memset(tm, 0, sizeof(*tm));
  378. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  379. if ((cp = strchr(date, ','))) {
  380. ++cp;
  381. if (*cp != ' ')
  382. return -1;
  383. ++cp;
  384. if (tor_sscanf(cp, "%2u %3s %4u %2u:%2u:%2u GMT",
  385. &tm_mday, month, &tm_year,
  386. &tm_hour, &tm_min, &tm_sec) == 6) {
  387. /* rfc1123-date */
  388. tm_year -= 1900;
  389. } else if (tor_sscanf(cp, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  390. &tm_mday, month, &tm_year,
  391. &tm_hour, &tm_min, &tm_sec) == 6) {
  392. /* rfc850-date */
  393. } else {
  394. return -1;
  395. }
  396. } else {
  397. /* No comma; possibly asctime() format. */
  398. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  399. wkday, month, &tm_mday,
  400. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  401. tm_year -= 1900;
  402. } else {
  403. return -1;
  404. }
  405. }
  406. tm->tm_mday = (int)tm_mday;
  407. tm->tm_year = (int)tm_year;
  408. tm->tm_hour = (int)tm_hour;
  409. tm->tm_min = (int)tm_min;
  410. tm->tm_sec = (int)tm_sec;
  411. tm->tm_wday = 0; /* Leave this unset. */
  412. month[3] = '\0';
  413. /* Okay, now decode the month. */
  414. /* set tm->tm_mon to dummy value so the check below fails. */
  415. tm->tm_mon = -1;
  416. for (i = 0; i < 12; ++i) {
  417. if (!strcasecmp(MONTH_NAMES[i], month)) {
  418. tm->tm_mon = i;
  419. }
  420. }
  421. if (tm->tm_year < 0 ||
  422. tm->tm_mon < 0 || tm->tm_mon > 11 ||
  423. tm->tm_mday < 1 || tm->tm_mday > 31 ||
  424. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  425. tm->tm_min < 0 || tm->tm_min > 59 ||
  426. tm->tm_sec < 0 || tm->tm_sec > 60)
  427. return -1; /* Out of range, or bad month. */
  428. return 0;
  429. }
  430. /** Given an <b>interval</b> in seconds, try to write it to the
  431. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  432. * Returns a non-negative integer on success, -1 on failure.
  433. */
  434. int
  435. format_time_interval(char *out, size_t out_len, long interval)
  436. {
  437. /* We only report seconds if there's no hours. */
  438. long sec = 0, min = 0, hour = 0, day = 0;
  439. /* -LONG_MIN is LONG_MAX + 1, which causes signed overflow */
  440. if (interval < -LONG_MAX)
  441. interval = LONG_MAX;
  442. else if (interval < 0)
  443. interval = -interval;
  444. if (interval >= 86400) {
  445. day = interval / 86400;
  446. interval %= 86400;
  447. }
  448. if (interval >= 3600) {
  449. hour = interval / 3600;
  450. interval %= 3600;
  451. }
  452. if (interval >= 60) {
  453. min = interval / 60;
  454. interval %= 60;
  455. }
  456. sec = interval;
  457. if (day) {
  458. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  459. day, hour, min);
  460. } else if (hour) {
  461. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  462. } else if (min) {
  463. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  464. } else {
  465. return tor_snprintf(out, out_len, "%ld seconds", sec);
  466. }
  467. }