https_request_example_main.c 9.4 KB

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