https_request_example_main.c 9.5 KB

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