time_helper.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /* time_helper.c
  2. *
  3. * Copyright (C) 2006-2024 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. /* See https://tf.nist.gov/tf-cgi/servers.cgi */
  22. /* common Espressif time_helper v5.6.6.001 */
  23. #include "sdkconfig.h"
  24. #include "time_helper.h"
  25. #include <esp_log.h>
  26. #include <esp_idf_version.h>
  27. #if defined(ESP_IDF_VERSION_MAJOR) && defined(ESP_IDF_VERSION_MINOR)
  28. #if (ESP_IDF_VERSION_MAJOR == 5) && (ESP_IDF_VERSION_MINOR >= 1)
  29. #define HAS_ESP_NETIF_SNTP 1
  30. #include <lwip/apps/sntp.h>
  31. #include <esp_netif_sntp.h>
  32. #else
  33. #include <string.h>
  34. #include <esp_sntp.h>
  35. #endif
  36. #else
  37. /* TODO Consider non ESP-IDF environments */
  38. #endif
  39. /* ESP-IDF uses a 64-bit signed integer to represent time_t starting from
  40. * release v5.0. See: Espressif api-reference/system/system_time */
  41. /* see https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html */
  42. #ifndef TIME_ZONE
  43. /*
  44. * PST represents Pacific Standard Time.
  45. * +8 specifies the offset from UTC (Coordinated Universal Time), indicating
  46. * that Pacific Time is UTC-8 during standard time.
  47. * PDT represents Pacific Daylight Time.
  48. * M3.2.0 indicates that Daylight Saving Time (DST) starts on the
  49. * second (2) Sunday (0) of March (3).
  50. * M11.1.0 indicates that DST ends on the first (1) Sunday (0) of November (11)
  51. */
  52. #define TIME_ZONE "PST+8PDT,M3.2.0,M11.1.0"
  53. #endif /* not defined: TIME_ZONE, so we are setting our own */
  54. #define NTP_RETRY_COUNT 10
  55. /* NELEMS(x) number of elements
  56. * To determine the number of elements in the array, we can divide the total
  57. * size of the array by the size of the array element.
  58. * See https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c
  59. **/
  60. #define NELEMS(x) ( (int)(sizeof(x) / sizeof((x)[0])) )
  61. /* See also CONFIG_LWIP_SNTP_MAX_SERVERS in sdkconfig */
  62. #define NTP_SERVER_LIST ( (char*[]) { \
  63. "pool.ntp.org", \
  64. "time.nist.gov", \
  65. "utcnist.colorado.edu" \
  66. } \
  67. )
  68. /* #define NTP_SERVER_COUNT using NELEMS:
  69. *
  70. * (int)(sizeof(NTP_SERVER_LIST) / sizeof(NTP_SERVER_LIST[0]))
  71. */
  72. #define NTP_SERVER_COUNT NELEMS(NTP_SERVER_LIST)
  73. #ifndef CONFIG_LWIP_SNTP_MAX_SERVERS
  74. /* We should find max value in sdkconfig, if not set it to our count:*/
  75. #define CONFIG_LWIP_SNTP_MAX_SERVERS NTP_SERVER_COUNT
  76. #endif
  77. char* ntpServerList[NTP_SERVER_COUNT] = NTP_SERVER_LIST;
  78. const static char* TAG = "time_helper";
  79. /* our NTP server list is global info */
  80. extern char* ntpServerList[NTP_SERVER_COUNT];
  81. /* Show the current date and time */
  82. int esp_show_current_datetime(void)
  83. {
  84. time_t now;
  85. char strftime_buf[64];
  86. struct tm timeinfo;
  87. time(&now);
  88. setenv("TZ", TIME_ZONE, 1);
  89. tzset();
  90. localtime_r(&now, &timeinfo);
  91. strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
  92. ESP_LOGI(TAG, "The current date/time is: %s", strftime_buf);
  93. return ESP_OK;
  94. }
  95. /* the worst-case scenario is a hard-coded date/time */
  96. int set_fixed_default_time(void)
  97. {
  98. /* ideally, we'd like to set time from network,
  99. * but let's set a default time, just in case */
  100. struct tm timeinfo = {
  101. .tm_year = 2024 - 1900,
  102. .tm_mon = 10,
  103. .tm_mday = 11,
  104. .tm_hour = 13,
  105. .tm_min = 01,
  106. .tm_sec = 05
  107. };
  108. struct timeval now;
  109. time_t interim_time;
  110. int ret = -1;
  111. /* set interim static time */
  112. interim_time = mktime(&timeinfo);
  113. ESP_LOGI(TAG, "Adjusting time from fixed value");
  114. now = (struct timeval){ .tv_sec = interim_time };
  115. ret = settimeofday(&now, NULL);
  116. ESP_LOGI(TAG, "settimeofday result = %d", ret);
  117. return ret;
  118. }
  119. /* probably_valid_time_string(s)
  120. *
  121. * some sanity checks on time string before calling sscanf()
  122. *
  123. * returns 0 == ESP_OK == Success if str is likely a valid time.
  124. * -1 == ESP_FAIL otherwise
  125. */
  126. int probably_valid_time_string(const char* str)
  127. {
  128. int ret = ESP_OK;
  129. size_t length = 0;
  130. size_t spaces = 0;
  131. size_t colons = 0;
  132. while (str[length] != '\0') {
  133. if (str[length] == ' ') {
  134. spaces++;
  135. }
  136. if (str[length] == ':') {
  137. colons++;
  138. }
  139. length++;
  140. }
  141. if ((length > 32) || (spaces < 4) || (spaces > 5) || (colons > 2)) {
  142. ret = ESP_FAIL;
  143. ESP_LOGE(TAG, "ERROR, failed time sanity check: %s", str);
  144. }
  145. return ret;
  146. }
  147. /* set_time_from_string(s)
  148. *
  149. * returns 0 = success if able to set the time from the provided string
  150. * error for any other value, typically -1 */
  151. int set_time_from_string(const char* time_buffer)
  152. {
  153. /* expecting github default formatting: 'Thu Aug 31 12:41:45 2023 -0700' */
  154. char offset[28]; /* large arrays, just in case there's still bad data */
  155. char day_str[28];
  156. char month_str[28];
  157. const char *format = "%3s %3s %d %d:%d:%d %d %s";
  158. struct tm this_timeinfo;
  159. struct timeval now;
  160. time_t interim_time;
  161. int day, year, hour, minute, second;
  162. int quote_offset = 0;
  163. int ret = 0;
  164. /* perform some basic sanity checks */
  165. ret = probably_valid_time_string(time_buffer);
  166. if (ret == ESP_OK) {
  167. /* we are expecting the string to be encapsulated in single quotes */
  168. if (*time_buffer == 0x27) {
  169. quote_offset = 1;
  170. }
  171. ret = sscanf(time_buffer + quote_offset,
  172. format,
  173. day_str, month_str,
  174. &day, &hour, &minute, &second, &year, &offset);
  175. if (ret == 8) {
  176. /* we found a match for all components */
  177. const char *months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  178. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  179. };
  180. for (int i = 0; i < 12; i++) {
  181. if (strcmp(month_str, months[i]) == 0) {
  182. this_timeinfo.tm_mon = i;
  183. break;
  184. }
  185. }
  186. this_timeinfo.tm_mday = day;
  187. this_timeinfo.tm_hour = hour;
  188. this_timeinfo.tm_min = minute;
  189. this_timeinfo.tm_sec = second;
  190. this_timeinfo.tm_year = year - 1900; /* Years since 1900 */
  191. interim_time = mktime(&this_timeinfo);
  192. now = (struct timeval){ .tv_sec = interim_time };
  193. ret = settimeofday(&now, NULL);
  194. ESP_LOGI(TAG, "Time updated to %s", time_buffer);
  195. }
  196. else {
  197. ESP_LOGE(TAG, "Failed to convert \"%s\" to a tm date.",
  198. time_buffer);
  199. ESP_LOGI(TAG, "Trying fixed date that was hard-coded....");
  200. set_fixed_default_time();
  201. ret = ESP_FAIL;
  202. }
  203. }
  204. return ret;
  205. }
  206. /* set time; returns 0 if succecssfully configured with NTP */
  207. int set_time(void)
  208. {
  209. #ifndef NTP_SERVER_COUNT
  210. ESP_LOGW(TAG, "Warning: no sntp server names defined. "
  211. "Setting to empty list");
  212. #define NTP_SERVER_COUNT 0
  213. #warning "NTP not properly configured"
  214. #endif /* not defined: NTP_SERVER_COUNT */
  215. #ifdef HAS_ESP_NETIF_SNTP
  216. #if CONFIG_LWIP_SNTP_MAX_SERVERS > 1
  217. esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(
  218. NTP_SERVER_COUNT,
  219. ESP_SNTP_SERVER_LIST(ntpServerList[0])
  220. );
  221. #else
  222. esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(ntpServerList[0]);
  223. #endif /* CONFIG_LWIP_SNTP_MAX_SERVERS > 1 */
  224. #endif /* HAS_ESP_NETIF_SNTP */
  225. int ret = 0;
  226. int i = 0; /* counter for time servers */
  227. ESP_LOGI(TAG, "Setting the time. Startup time:");
  228. esp_show_current_datetime();
  229. #ifdef LIBWOLFSSL_VERSION_GIT_HASH_DATE
  230. /* initially set a default approximate time from recent git commit */
  231. ESP_LOGI(TAG, "Found git hash date, attempting to set system date: %s",
  232. LIBWOLFSSL_VERSION_GIT_HASH_DATE);
  233. set_time_from_string(LIBWOLFSSL_VERSION_GIT_HASH_DATE"\0");
  234. esp_show_current_datetime();
  235. ret = -4;
  236. #else
  237. /* otherwise set a fixed time that was hard coded */
  238. set_fixed_default_time();
  239. esp_show_current_datetime();
  240. ret = -3;
  241. #endif
  242. #ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH
  243. config.smooth_sync = true;
  244. #endif
  245. if (NTP_SERVER_COUNT) {
  246. /* next, let's setup NTP time servers
  247. *
  248. * see Espressifapi-reference/system/system_time.html#sntp-time-synchronization
  249. *
  250. * WARNING: do not set operating mode while SNTP client is running!
  251. */
  252. /* TODO Consider esp_sntp_setoperatingmode(SNTP_OPMODE_POLL); */
  253. sntp_setoperatingmode(SNTP_OPMODE_POLL);
  254. if (NTP_SERVER_COUNT > CONFIG_LWIP_SNTP_MAX_SERVERS) {
  255. ESP_LOGW(TAG, "WARNING: %d NTP Servers defined, but "
  256. "CONFIG_LWIP_SNTP_MAX_SERVERS = %d",
  257. NTP_SERVER_COUNT,CONFIG_LWIP_SNTP_MAX_SERVERS);
  258. }
  259. ESP_LOGI(TAG, "sntp_setservername:");
  260. for (i = 0; i < CONFIG_LWIP_SNTP_MAX_SERVERS; i++) {
  261. const char* thisServer = ntpServerList[i];
  262. if (strncmp(thisServer, "\x00", 1) == 0) {
  263. /* just in case we run out of NTP servers */
  264. break;
  265. }
  266. ESP_LOGI(TAG, "%s", thisServer);
  267. sntp_setservername(i, thisServer);
  268. ret = ESP_OK;
  269. }
  270. #ifdef HAS_ESP_NETIF_SNTP
  271. ret = esp_netif_sntp_init(&config);
  272. #else
  273. ESP_LOGW(TAG,"Warning: Consider upgrading ESP-IDF to take advantage "
  274. "of updated SNTP libraries");
  275. #endif
  276. if (ret == ESP_OK) {
  277. ESP_LOGV(TAG, "Successfully called esp_netif_sntp_init");
  278. }
  279. else {
  280. ESP_LOGE(TAG, "ERROR: esp_netif_sntp_init return = %d", ret);
  281. }
  282. sntp_init();
  283. switch (ret) {
  284. case ESP_ERR_INVALID_STATE:
  285. break;
  286. default:
  287. break;
  288. }
  289. ESP_LOGI(TAG, "sntp_init done.");
  290. }
  291. else {
  292. ESP_LOGW(TAG, "No sntp time servers found.");
  293. ret = -1;
  294. }
  295. esp_show_current_datetime();
  296. ESP_LOGI(TAG, "time helper existing with result = %d", ret);
  297. return ret;
  298. }
  299. /* wait for NTP to actually set the time */
  300. int set_time_wait_for_ntp(void)
  301. {
  302. int ret = 0;
  303. #ifdef HAS_ESP_NETIF_SNTP
  304. int ntp_retry = 0;
  305. const int ntp_retry_count = NTP_RETRY_COUNT;
  306. ret = esp_netif_sntp_start();
  307. ret = esp_netif_sntp_sync_wait(500 / portTICK_PERIOD_MS);
  308. #else
  309. ESP_LOGW(TAG, "HAS_ESP_NETIF_SNTP not defined");
  310. #endif /* HAS_ESP_NETIF_SNTP */
  311. esp_show_current_datetime();
  312. #ifdef HAS_ESP_NETIF_SNTP
  313. while (ret == ESP_ERR_TIMEOUT && (ntp_retry++ < ntp_retry_count)) {
  314. ret = esp_netif_sntp_sync_wait(1000 / portTICK_PERIOD_MS);
  315. ESP_LOGI(TAG, "Waiting for NTP to sync time... (%d/%d)",
  316. ntp_retry,
  317. ntp_retry_count);
  318. esp_show_current_datetime();
  319. }
  320. #endif /* HAS_ESP_NETIF_SNTP */
  321. #ifdef TIME_ZONE
  322. setenv("TZ", TIME_ZONE, 1);
  323. tzset();
  324. #endif
  325. if (ret == ESP_OK) {
  326. ESP_LOGI(TAG, "Successfully set time via NTP servers.");
  327. }
  328. else {
  329. ESP_LOGW(TAG, "Warning: Failed to set time with NTP: "
  330. "result = 0x%0x: %s",
  331. ret, esp_err_to_name(ret));
  332. }
  333. return ret;
  334. }