time_fmt.c 15 KB

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