time_fmt.c 15 KB

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