https_request_example_main.c 9.3 KB

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