time_fmt.c 14 KB

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