https_request_example_main.c 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. * HTTPS GET Example using plain Mbed TLS sockets
  3. *
  4. * Contacts the howsmyssl.com API via TLS v1.2 and reads a JSON
  5. * response.
  6. *
  7. * Adapted from the ssl_client1 example in Mbed TLS.
  8. *
  9. * SPDX-FileCopyrightText: The Mbed TLS Contributors
  10. *
  11. * SPDX-License-Identifier: Apache-2.0
  12. *
  13. * SPDX-FileContributor: 2015-2022 Espressif Systems (Shanghai) CO LTD
  14. */
  15. #include <string.h>
  16. #include <stdlib.h>
  17. #include <time.h>
  18. #include <sys/time.h>
  19. #include "freertos/FreeRTOS.h"
  20. #include "freertos/task.h"
  21. #include "freertos/event_groups.h"
  22. #include "esp_wifi.h"
  23. #include "esp_event.h"
  24. #include "esp_log.h"
  25. #include "esp_system.h"
  26. #include "esp_timer.h"
  27. #include "nvs_flash.h"
  28. #include "nvs.h"
  29. #include "protocol_examples_common.h"
  30. #include "esp_sntp.h"
  31. #include "esp_netif.h"
  32. #include "lwip/err.h"
  33. #include "lwip/sockets.h"
  34. #include "lwip/sys.h"
  35. #include "lwip/netdb.h"
  36. #include "lwip/dns.h"
  37. #include "esp_tls.h"
  38. #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
  39. #include "esp_crt_bundle.h"
  40. #endif
  41. #include "time_sync.h"
  42. /* Constants that aren't configurable in menuconfig */
  43. #define WEB_SERVER "www.howsmyssl.com"
  44. #define WEB_PORT "443"
  45. #define WEB_URL "https://www.howsmyssl.com/a/check"
  46. #define SERVER_URL_MAX_SZ 256
  47. static const char *TAG = "example";
  48. /* Timer interval once every day (24 Hours) */
  49. #define TIME_PERIOD (86400000000ULL)
  50. static const char HOWSMYSSL_REQUEST[] = "GET " WEB_URL " HTTP/1.1\r\n"
  51. "Host: "WEB_SERVER"\r\n"
  52. "User-Agent: esp-idf/1.0 esp32\r\n"
  53. "\r\n";
  54. #ifdef CONFIG_EXAMPLE_CLIENT_SESSION_TICKETS
  55. static const char LOCAL_SRV_REQUEST[] = "GET " CONFIG_EXAMPLE_LOCAL_SERVER_URL " HTTP/1.1\r\n"
  56. "Host: "WEB_SERVER"\r\n"
  57. "User-Agent: esp-idf/1.0 esp32\r\n"
  58. "\r\n";
  59. #endif
  60. /* Root cert for howsmyssl.com, taken from server_root_cert.pem
  61. The PEM file was extracted from the output of this command:
  62. openssl s_client -showcerts -connect www.howsmyssl.com:443 </dev/null
  63. The CA root cert is the last cert given in the chain of certs.
  64. To embed it in the app binary, the PEM file is named
  65. in the component.mk COMPONENT_EMBED_TXTFILES variable.
  66. */
  67. extern const uint8_t server_root_cert_pem_start[] asm("_binary_server_root_cert_pem_start");
  68. extern const uint8_t server_root_cert_pem_end[] asm("_binary_server_root_cert_pem_end");
  69. extern const uint8_t local_server_cert_pem_start[] asm("_binary_local_server_cert_pem_start");
  70. extern const uint8_t local_server_cert_pem_end[] asm("_binary_local_server_cert_pem_end");
  71. #ifdef CONFIG_EXAMPLE_CLIENT_SESSION_TICKETS
  72. esp_tls_client_session_t *tls_client_session = NULL;
  73. static bool save_client_session = false;
  74. #endif
  75. static void https_get_request(esp_tls_cfg_t cfg, const char *WEB_SERVER_URL, const char *REQUEST)
  76. {
  77. char buf[512];
  78. int ret, len;
  79. esp_tls_t *tls = esp_tls_init();
  80. if (!tls) {
  81. ESP_LOGE(TAG, "Failed to allocate esp_tls handle!");
  82. goto exit;
  83. }
  84. if (esp_tls_conn_http_new_sync(WEB_SERVER_URL, &cfg, tls) == 1) {
  85. ESP_LOGI(TAG, "Connection established...");
  86. } else {
  87. ESP_LOGE(TAG, "Connection failed...");
  88. goto cleanup;
  89. }
  90. #ifdef CONFIG_EXAMPLE_CLIENT_SESSION_TICKETS
  91. /* The TLS session is successfully established, now saving the session ctx for reuse */
  92. if (save_client_session) {
  93. free(tls_client_session);
  94. tls_client_session = esp_tls_get_client_session(tls);
  95. }
  96. #endif
  97. size_t written_bytes = 0;
  98. do {
  99. ret = esp_tls_conn_write(tls,
  100. REQUEST + written_bytes,
  101. strlen(REQUEST) - written_bytes);
  102. if (ret >= 0) {
  103. ESP_LOGI(TAG, "%d bytes written", ret);
  104. written_bytes += ret;
  105. } else if (ret != ESP_TLS_ERR_SSL_WANT_READ && ret != ESP_TLS_ERR_SSL_WANT_WRITE) {
  106. ESP_LOGE(TAG, "esp_tls_conn_write returned: [0x%02X](%s)", ret, esp_err_to_name(ret));
  107. goto cleanup;
  108. }
  109. } while (written_bytes < strlen(REQUEST));
  110. ESP_LOGI(TAG, "Reading HTTP response...");
  111. do {
  112. len = sizeof(buf) - 1;
  113. memset(buf, 0x00, sizeof(buf));
  114. ret = esp_tls_conn_read(tls, (char *)buf, len);
  115. if (ret == ESP_TLS_ERR_SSL_WANT_WRITE || ret == ESP_TLS_ERR_SSL_WANT_READ) {
  116. continue;
  117. } else if (ret < 0) {
  118. ESP_LOGE(TAG, "esp_tls_conn_read returned [-0x%02X](%s)", -ret, esp_err_to_name(ret));
  119. break;
  120. } else if (ret == 0) {
  121. ESP_LOGI(TAG, "connection closed");
  122. break;
  123. }
  124. len = ret;
  125. ESP_LOGD(TAG, "%d bytes read", len);
  126. /* Print response directly to stdout as it is read */
  127. for (int i = 0; i < len; i++) {
  128. putchar(buf[i]);
  129. }
  130. putchar('\n'); // JSON output doesn't have a newline at end
  131. } while (1);
  132. cleanup:
  133. esp_tls_conn_destroy(tls);
  134. exit:
  135. for (int countdown = 10; countdown >= 0; countdown--) {
  136. ESP_LOGI(TAG, "%d...", countdown);
  137. vTaskDelay(1000 / portTICK_PERIOD_MS);
  138. }
  139. }
  140. #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
  141. static void https_get_request_using_crt_bundle(void)
  142. {
  143. ESP_LOGI(TAG, "https_request using crt bundle");
  144. esp_tls_cfg_t cfg = {
  145. .crt_bundle_attach = esp_crt_bundle_attach,
  146. };
  147. https_get_request(cfg, WEB_URL, HOWSMYSSL_REQUEST);
  148. }
  149. #endif // CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
  150. static void https_get_request_using_cacert_buf(void)
  151. {
  152. ESP_LOGI(TAG, "https_request using cacert_buf");
  153. esp_tls_cfg_t cfg = {
  154. .cacert_buf = (const unsigned char *) server_root_cert_pem_start,
  155. .cacert_bytes = server_root_cert_pem_end - server_root_cert_pem_start,
  156. };
  157. https_get_request(cfg, WEB_URL, HOWSMYSSL_REQUEST);
  158. }
  159. static void https_get_request_using_global_ca_store(void)
  160. {
  161. esp_err_t esp_ret = ESP_FAIL;
  162. ESP_LOGI(TAG, "https_request using global ca_store");
  163. esp_ret = esp_tls_set_global_ca_store(server_root_cert_pem_start, server_root_cert_pem_end - server_root_cert_pem_start);
  164. if (esp_ret != ESP_OK) {
  165. ESP_LOGE(TAG, "Error in setting the global ca store: [%02X] (%s),could not complete the https_request using global_ca_store", esp_ret, esp_err_to_name(esp_ret));
  166. return;
  167. }
  168. esp_tls_cfg_t cfg = {
  169. .use_global_ca_store = true,
  170. };
  171. https_get_request(cfg, WEB_URL, HOWSMYSSL_REQUEST);
  172. esp_tls_free_global_ca_store();
  173. }
  174. #ifdef CONFIG_EXAMPLE_CLIENT_SESSION_TICKETS
  175. static void https_get_request_to_local_server(const char* url)
  176. {
  177. ESP_LOGI(TAG, "https_request to local server");
  178. esp_tls_cfg_t cfg = {
  179. .cacert_buf = (const unsigned char *) local_server_cert_pem_start,
  180. .cacert_bytes = local_server_cert_pem_end - local_server_cert_pem_start,
  181. .skip_common_name = true,
  182. };
  183. save_client_session = true;
  184. https_get_request(cfg, url, LOCAL_SRV_REQUEST);
  185. }
  186. static void https_get_request_using_already_saved_session(const char *url)
  187. {
  188. ESP_LOGI(TAG, "https_request using saved client session");
  189. esp_tls_cfg_t cfg = {
  190. .client_session = tls_client_session,
  191. };
  192. https_get_request(cfg, url, LOCAL_SRV_REQUEST);
  193. free(tls_client_session);
  194. save_client_session = false;
  195. tls_client_session = NULL;
  196. }
  197. #endif
  198. static void https_request_task(void *pvparameters)
  199. {
  200. ESP_LOGI(TAG, "Start https_request example");
  201. #ifdef CONFIG_EXAMPLE_CLIENT_SESSION_TICKETS
  202. char *server_url = NULL;
  203. #ifdef CONFIG_EXAMPLE_LOCAL_SERVER_URL_FROM_STDIN
  204. char url_buf[SERVER_URL_MAX_SZ];
  205. if (strcmp(CONFIG_EXAMPLE_LOCAL_SERVER_URL, "FROM_STDIN") == 0) {
  206. example_configure_stdin_stdout();
  207. fgets(url_buf, SERVER_URL_MAX_SZ, stdin);
  208. int len = strlen(url_buf);
  209. url_buf[len - 1] = '\0';
  210. server_url = url_buf;
  211. } else {
  212. ESP_LOGE(TAG, "Configuration mismatch: invalid url for local server");
  213. abort();
  214. }
  215. printf("\nServer URL obtained is %s\n", url_buf);
  216. #else
  217. server_url = CONFIG_EXAMPLE_LOCAL_SERVER_URL;
  218. #endif /* CONFIG_EXAMPLE_LOCAL_SERVER_URL_FROM_STDIN */
  219. https_get_request_to_local_server(server_url);
  220. https_get_request_using_already_saved_session(server_url);
  221. #endif
  222. #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
  223. https_get_request_using_crt_bundle();
  224. #endif
  225. ESP_LOGI(TAG, "Minimum free heap size: %d bytes", esp_get_minimum_free_heap_size());
  226. https_get_request_using_cacert_buf();
  227. https_get_request_using_global_ca_store();
  228. ESP_LOGI(TAG, "Finish https_request example");
  229. vTaskDelete(NULL);
  230. }
  231. void app_main(void)
  232. {
  233. ESP_ERROR_CHECK(nvs_flash_init());
  234. ESP_ERROR_CHECK(esp_netif_init());
  235. ESP_ERROR_CHECK(esp_event_loop_create_default());
  236. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  237. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  238. * examples/protocols/README.md for more information about this function.
  239. */
  240. ESP_ERROR_CHECK(example_connect());
  241. if (esp_reset_reason() == ESP_RST_POWERON) {
  242. ESP_LOGI(TAG, "Updating time from NVS");
  243. ESP_ERROR_CHECK(update_time_from_nvs());
  244. }
  245. const esp_timer_create_args_t nvs_update_timer_args = {
  246. .callback = &fetch_and_store_time_in_nvs,
  247. };
  248. esp_timer_handle_t nvs_update_timer;
  249. ESP_ERROR_CHECK(esp_timer_create(&nvs_update_timer_args, &nvs_update_timer));
  250. ESP_ERROR_CHECK(esp_timer_start_periodic(nvs_update_timer, TIME_PERIOD));
  251. xTaskCreate(&https_request_task, "https_get_task", 8192, NULL, 5, NULL);
  252. }