diff --git a/components/esp_dns/CMakeLists.txt b/components/esp_dns/CMakeLists.txt new file mode 100644 index 0000000000..e85ab3e653 --- /dev/null +++ b/components/esp_dns/CMakeLists.txt @@ -0,0 +1,15 @@ +idf_component_register(SRCS + "esp_dns_udp.c" + "esp_dns_tcp.c" + "esp_dns_dot.c" + "esp_dns_doh.c" + "esp_dns.c" + "esp_dns_lwip.c" + "esp_dns_utils.c" + INCLUDE_DIRS "include" + PRIV_INCLUDE_DIRS "." + PRIV_REQUIRES nvs_flash lwip esp_event esp-tls esp_http_client esp-tls tcp_transport) + +if(CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM) + target_link_libraries(${COMPONENT_LIB} "-u lwip_hook_netconn_external_resolve") +endif() diff --git a/components/esp_dns/LICENSE b/components/esp_dns/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/components/esp_dns/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/components/esp_dns/README.md b/components/esp_dns/README.md new file mode 100644 index 0000000000..d53e4fa08d --- /dev/null +++ b/components/esp_dns/README.md @@ -0,0 +1,223 @@ +# ESP DNS Component + +This component provides a flexible DNS resolution system for ESP32 devices with support for multiple DNS protocols. It allows applications to securely resolve domain names using various transport methods, including standard UDP/TCP DNS, DNS over TLS (DoT), and DNS over HTTPS (DoH). + +## Table of Contents +- [Features](#features) +- [Requirements](#requirements) +- [How to Use](#how-to-use) +- [Configuration](#configuration) +- [Certificate Options](#certificate-options) +- [Limitations](#limitations) +- [Performance Considerations](#performance-considerations) +- [How It Works](#how-it-works) +- [Troubleshooting](#troubleshooting) + +## Features + +- **Multiple Protocol Support** Choose from various DNS protocols: + - Standard UDP DNS (Port 53) + - TCP DNS (Port 53) + - DNS over TLS (DoT) (Port 853) + - DNS over HTTPS (DoH) (Port 443) + +- **Secure DNS Resolution**: Supports encrypted DNS queries using TLS and HTTPS to protect privacy and prevent DNS spoofing. + +- **Flexible Configuration**: Easily configure DNS servers, ports, timeouts, and protocol-specific options. + +- **LWIP Integration**: Seamlessly integrates with the ESP-IDF networking stack through LWIP hooks. + +- **Standard getaddrinfo() Interface**: Use the standard `getaddrinfo()` function to resolve domain names. + + +## Requirements + +- ESP-IDF v5.0 or newer +- Network connectivity (Wi-Fi or Ethernet) +- For DoT/DoH: Sufficient RAM for TLS operations + + +## How to Use + +### 1. Enable custom DNS resolution + +To enable custom DNS resolution, configure the `CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM` setting either through menuconfig or by adding `CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM=y` to your `sdkconfig.defaults` file to pre-set the configuration during the build process. + +### 2. Configure DNS Settings + +Initialize the DNS component with your preferred configuration: +```C +#include "esp_dns.h" + +/* Configure DNS over HTTPS */ +esp_dns_config_t dns_config = { + .dns_server = "dns.google", /* DNS server hostname or IP address */ + .port = ESP_DNS_DEFAULT_DOH_PORT, /* Optional: Server port (443 is default for HTTPS) */ + .timeout_ms = ESP_DNS_DEFAULT_TIMEOUT_MS, /* Optional: Request timeout in milliseconds (10000ms default) */ + .tls_config = { + /* Optional: Use ESP-IDF certificate bundle for validating popular DNS providers */ + .crt_bundle_attach = esp_crt_bundle_attach, + + /* Or provide a custom certificate in PEM format (string) for your DNS server */ + /* Note: Only PEM format is supported; DER format certificates are not supported yet */ + .cert_pem = server_root_cert_pem_start, + + /* Note: If both crt_bundle_attach and cert_pem are provided, + crt_bundle_attach is preferred over cert_pem */ + }, + .protocol_config.doh_config = { + .url_path = "/dns-query", /* Optional: DoH endpoint path on the server ("/dns-query" default) */ + } +}; + +/* Initialize DNS component based on protocol */ +esp_dns_handle_t dns_handle = NULL; + +/* Call esp_dns_init_doh() to use DNS over HTTPS */ +dns_handle = esp_dns_init_doh(&dns_config); + +/* or Call esp_dns_init_dot() to use DNS over TLS */ +dns_handle = esp_dns_init_dot(&dns_config); + +/* or Call esp_dns_init_tcp() to use DNS over TCP */ +dns_handle = esp_dns_init_tcp(&dns_config); + +/* or Call esp_dns_init_udp() to use DNS over UDP */ +dns_handle = esp_dns_init_udp(&dns_config); + +if (dns_handle == NULL) { + ESP_LOGE(TAG, "Failed to initialize DNS"); + return; +} +``` + + +### 3. Resolve Domain Names + +Once initialized, the component automatically handles DNS resolution through the standard `getaddrinfo()` function: + +```C +struct addrinfo hints = { + .ai_family = AF_UNSPEC, + .ai_socktype = SOCK_STREAM, +}; +struct addrinfo res; +int err = getaddrinfo("www.example.com", "80", &hints, &res); +if (err != 0) { + ESP_LOGE(TAG, "DNS lookup failed: %d", err); + return; +} +/* Use the resolved addresses */ +/* ... */ + +/* Free the address info when done */ +freeaddrinfo(res); +``` + +### 4. Cleanup + +When you're done using the DNS component, clean up resources based on the protocol used: + +```C +int ret = 0; +/* Call esp_dns_cleanup_doh() to cleanup DNS over HTTPS */ +ret = esp_dns_cleanup_doh(dns_handle); + +/* or Call esp_dns_cleanup_dot() to cleanup DNS over TLS */ +ret = esp_dns_cleanup_dot(dns_handle); + +/* or Call esp_dns_cleanup_tcp() to cleanup DNS over TCP */ +ret = esp_dns_cleanup_tcp(dns_handle); + +/* or Call esp_dns_cleanup_udp() to cleanup DNS over UDP */ +ret = esp_dns_cleanup_udp(dns_handle); + +if (ret != 0) { + ESP_LOGE(TAG, "Failed to cleanup DNS"); +} +``` + + +## Configuration + +### Setting Up the ESP DNS Component + +1. Navigate to your project directory. +2. Execute `idf.py menuconfig`. +3. Locate the **Component config -> LWIP -> Hooks -> Netconn external resolve Hook** section. +4. Change the setting to `Custom implementation`. + +### Common Settings + +| Parameter | Description | Default Value | +|-----------|-------------|---------------| +| `dns_server` | IP address or hostname of DNS server | `"8.8.8.8"` (Google DNS) | +| `port` | Server port number | Protocol-dependent (53, 853, or 443) | +| `timeout_ms` | Query timeout in milliseconds | `10000` (10 seconds) | + +### TLS Configuration (for DoT and DoH) + +| Parameter | Description | +|-----------|-------------| +| `crt_bundle_attach` | Function pointer to attach certificate bundle | +| `server_cert` | SSL server certificate in PEM format | +| `alpn_protos` | ALPN protocols for DoH (typically `"h2"`) | + +### Protocol-Specific Options + +#### DoH Options +- **URL Path**: URL path for DoH service (e.g., "/dns-query") + + +## Certificate Options + +When using secure DNS protocols (DoT and DoH), you have two certificate options: + +1. **Certificate Bundle**: Use ESP-IDF's certificate bundle for validating connections to popular DNS providers. +2. **Custom Certificate**: Provide your own certificate in PEM format for custom DNS servers. + + +## Limitations + +- The UDP DNS protocol implementation relies on the native LWIP DNS resolver. +- Transport protocol selection must be configured through `esp_dns_init_xxx()` rather than `getaddrinfo()` parameters due to LWIP resolver hook limitations. +- Maximum response size is limited by the buffer size (default: 512 bytes) for DNS over TLS (DOT) and TCP protocols. +- Only one DNS protocol can be active at a time. + +- **Resolution Speed**: + - UDP DNS is fastest but least secure + - DoH typically has the highest latency but offers the best security + + +## Performance Considerations + +- **Memory Usage**: DoH and DoT require more memory due to TLS overhead: + +TBD: Fill in the memory usage for each protocol + + +## How It Works +This component utilizes the `CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM` hook to override the core DNS functionality of LWIP and implement custom DNS over HTTPS resolution. To enable this, ensure that the configuration option `Component config → LWIP → Hooks → Netconn external resolve Hook` is set to `Custom implementation`. + +Once you add this component to your project, it will replace the default LWIP DNS resolution automatically. + +**⚠️ Warning:** This component cannot work alongside other components that use the CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM hook, such as the OpenThread component. + + +## Troubleshooting + +- **Connection Issues**: + - Ensure network connectivity and correct DNS server configuration + - Verify that your network allows the required ports (53, 853, or 443) + +- **Certificate Errors**: + - Verify that the correct certificate is provided for secure protocols + - For public DNS servers, use the certificate bundle approach + +- **Timeout Errors**: + - Increase the timeout value for slow network connections + - Try a different DNS server that might be geographically closer + +- **Memory Issues**: + - If you encounter memory errors, consider increasing the task stack size + - For memory-constrained devices, prefer UDP DNS. diff --git a/components/esp_dns/esp_dns.c b/components/esp_dns/esp_dns.c new file mode 100644 index 0000000000..8c83434c13 --- /dev/null +++ b/components/esp_dns/esp_dns.c @@ -0,0 +1,160 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file esp_dns.c + * @brief Custom DNS module for ESP32 with multiple protocol support + * + * This module provides DNS resolution capabilities with support for various protocols: + * - Standard UDP/TCP DNS (Port 53) + * - DNS over TLS (DoT) (Port 853) + * - DNS over HTTPS (DoH) (Port 443) + */ + +#include +#include +#include +#include +#include + +#include "freertos/FreeRTOS.h" +#include "esp_log.h" + +#include "esp_dns_priv.h" +#include "esp_dns.h" + +#define TAG "ESP_DNS" + +/* Global DNS handle instance */ +esp_dns_handle_t g_dns_handle = NULL; + +/* Mutex for protecting global handle access */ +static SemaphoreHandle_t s_dns_global_mutex = NULL; + +/** + * @brief Creates or returns a singleton DNS handle instance + * + * This function implements a singleton pattern for the DNS handle. It creates + * a static instance of the dns_handle structure on first call and initializes + * it to zeros. On subsequent calls, it returns a pointer to the same instance. + * + * The function ensures that only one DNS handle exists throughout the application + * lifecycle, which helps manage resources efficiently. + * + * @return Pointer to the singleton DNS handle instance + */ +static esp_dns_handle_t esp_dns_create_handle(void) +{ + static struct esp_dns_handle instance; + static bool initialized = false; + + if (!initialized) { + memset(&instance, 0, sizeof(instance)); + initialized = true; + } + + return &instance; +} + +/** + * @brief Initialize the DNS module with provided configuration + * + * @param config DNS configuration parameters + * + * @return On success, returns a handle to the initialized DNS module + * On failure, returns NULL + */ +esp_dns_handle_t esp_dns_init(const esp_dns_config_t *config) +{ + /* Create global mutex if it doesn't exist */ + if (s_dns_global_mutex == NULL) { + s_dns_global_mutex = xSemaphoreCreateMutex(); + if (s_dns_global_mutex == NULL) { + ESP_LOGE(TAG, "Failed to create global mutex"); + return NULL; + } + } + + /* Take the global mutex */ + if (xSemaphoreTake(s_dns_global_mutex, portMAX_DELAY) != pdTRUE) { + ESP_LOGE(TAG, "Failed to take global mutex"); + return NULL; + } + + /* Check if we need to clean up an existing handle */ + if (g_dns_handle != NULL) { + ESP_LOGE(TAG, "DNS handle already initialized. Call esp_dns_cleanup() before reinitializing"); + xSemaphoreGive(s_dns_global_mutex); + return NULL; + } + + /* Allocate memory for the new handle */ + esp_dns_handle_t handle = esp_dns_create_handle(); + if (handle == NULL) { + ESP_LOGE(TAG, "Failed to allocate memory for DNS handle"); + xSemaphoreGive(s_dns_global_mutex); + return NULL; + } + + /* Copy configuration */ + memcpy(&handle->config, config, sizeof(esp_dns_config_t)); + + /* Create mutex for this handle */ + handle->lock = xSemaphoreCreateMutex(); + if (handle->lock == NULL) { + ESP_LOGE(TAG, "Failed to create handle mutex"); + free(handle); + xSemaphoreGive(s_dns_global_mutex); + return NULL; + } + + /* Set global handle */ + g_dns_handle = handle; + handle->initialized = true; + + /* Release global mutex */ + xSemaphoreGive(s_dns_global_mutex); + + return handle; +} + +/** + * @brief Cleanup and release resources associated with a DNS module handle + * + * @param handle DNS module handle previously obtained from esp_dns_init() + * + * @return 0 on success, non-zero error code on failure + */ +int esp_dns_cleanup(esp_dns_handle_t handle) +{ + /* Take the handle mutex */ + if (xSemaphoreTake(handle->lock, portMAX_DELAY) != pdTRUE) { + ESP_LOGE(TAG, "Failed to take handle mutex during cleanup"); + return -1; + } + + /* Release and delete mutex */ + xSemaphoreGive(handle->lock); + vSemaphoreDelete(handle->lock); + + /* Take global mutex before modifying global handle */ + if (s_dns_global_mutex != NULL && xSemaphoreTake(s_dns_global_mutex, portMAX_DELAY) == pdTRUE) { + /* Clear global handle if it matches this one */ + if (g_dns_handle == handle) { + g_dns_handle = NULL; + } + + xSemaphoreGive(s_dns_global_mutex); + } + + /* Mark as uninitialized */ + handle->initialized = false; + + /* Empty the handle */ + memset(handle, 0, sizeof(handle)); + + return 0; +} diff --git a/components/esp_dns/esp_dns_doh.c b/components/esp_dns/esp_dns_doh.c new file mode 100644 index 0000000000..829433f2f1 --- /dev/null +++ b/components/esp_dns/esp_dns_doh.c @@ -0,0 +1,306 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include "esp_event.h" +#include "esp_log.h" +#include "sdkconfig.h" +#include "esp_http_client.h" +#include "esp_dns_utils.h" +#include "esp_dns_priv.h" +#include "esp_dns.h" + +#define TAG "ESP_DNS_DOH" + +#define SERVER_URL_MAX_SZ 256 + +/** + * @brief Initializes the DNS over HTTPS (DoH) module + * + * Sets up the DoH service using the provided configuration. Validates the parameters, + * sets the protocol, and initializes the DNS module. Returns a handle for further use. + * + * @param config Pointer to the DNS configuration structure, which must be initialized + * + * @return On success, returns a handle to the initialized DoH module; returns NULL on failure + */ +esp_dns_handle_t esp_dns_init_doh(esp_dns_config_t *config) +{ + ESP_LOGD(TAG, "Initializing DNS over HTTPS"); + + /* Validate parameters */ + if (config == NULL) { + ESP_LOGE(TAG, "Invalid configuration (NULL)"); + return NULL; + } + + config->protocol = ESP_DNS_PROTOCOL_DOH; + + esp_dns_handle_t handle = esp_dns_init(config); + if (handle == NULL) { + ESP_LOGE(TAG, "Failed to initialize DNS"); + return NULL; + } + + ESP_LOGD(TAG, "DNS module initialized successfully with protocol DNS Over HTTPS(%d)", config->protocol); + return handle; +} + +/** + * @brief Cleans up the DNS over HTTPS (DoH) module + * + * Releases resources allocated for the DoH service. Validates the parameters, + * checks the protocol, and cleans up the DNS module. + * + * @param handle Pointer to the DNS handle to be cleaned up + * + * @return 0 on success, or -1 on failure + */ +int esp_dns_cleanup_doh(esp_dns_handle_t handle) +{ + ESP_LOGD(TAG, "Cleaning up DNS over HTTPS"); + + /* Validate parameters */ + if (handle == NULL) { + ESP_LOGE(TAG, "Invalid handle (NULL)"); + return -1; + } + + if (handle->config.protocol != ESP_DNS_PROTOCOL_DOH) { + ESP_LOGW(TAG, "Unknown protocol during cleanup: %d", handle->config.protocol); + return -1; + } + + int ret = esp_dns_cleanup(handle); + if (ret != 0) { + ESP_LOGE(TAG, "Failed to cleanup DNS"); + return ret; + } + + ESP_LOGD(TAG, "DNS module cleaned up DNS Over HTTPS successfully"); + return 0; +} + +/** + * @brief HTTP event handler for DNS over HTTPS requests + * + * Handles HTTP events during DNS over HTTPS communication, including data reception, + * connection status, and error conditions. + * + * @param evt Pointer to the HTTP client event structure + * + * @return ESP_OK on success, or an error code on failure + */ +esp_err_t _http_event_handler(esp_http_client_event_t *evt) +{ + char *temp_buff = NULL; + size_t temp_buff_len = 0; + esp_dns_handle_t handle = (esp_dns_handle_t)evt->user_data; + + switch (evt->event_id) { + case HTTP_EVENT_ERROR: + ESP_LOGD(TAG, "HTTP_EVENT_ERROR"); + break; + case HTTP_EVENT_ON_CONNECTED: + ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED"); + break; + case HTTP_EVENT_HEADER_SENT: + ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT"); + break; + case HTTP_EVENT_ON_HEADER: + ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value); + break; + case HTTP_EVENT_ON_DATA: + ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len); + /* Check if buffer is null, if yes, initialize it */ + if (handle->response_buffer.buffer == NULL) { + if (evt->data_len == 0) { + ESP_LOGW(TAG, "Received empty HTTP data"); + return ESP_ERR_INVALID_ARG; + } + temp_buff = malloc(evt->data_len); + if (temp_buff) { + handle->response_buffer.buffer = temp_buff; + handle->response_buffer.length = evt->data_len; + memcpy(handle->response_buffer.buffer, evt->data, evt->data_len); + } else { + ESP_LOGE(TAG, "Buffer allocation error"); + return ESP_ERR_NO_MEM; + } + } else { + /* Reallocate buffer to hold the new data chunk */ + int new_len = handle->response_buffer.length + evt->data_len; + if (new_len == 0) { + ESP_LOGW(TAG, "New data length is zero after receiving HTTP data"); + return ESP_ERR_INVALID_ARG; + } + temp_buff = realloc(handle->response_buffer.buffer, new_len); + if (temp_buff) { + handle->response_buffer.buffer = temp_buff; + memcpy(handle->response_buffer.buffer + handle->response_buffer.length, evt->data, evt->data_len); + handle->response_buffer.length = new_len; + } else { + ESP_LOGE(TAG, "Buffer allocation error"); + return ESP_ERR_NO_MEM; + } + } + break; + case HTTP_EVENT_ON_FINISH: + ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH"); + /* Entire response received, process it here */ + ESP_LOGD(TAG, "Received full response, length: %d", handle->response_buffer.length); + + /* Check if the buffer indicates an HTTP error response */ + if (HttpStatus_Ok == esp_http_client_get_status_code(evt->client)) { + /* Parse the DNS response */ + esp_dns_parse_response((uint8_t *)handle->response_buffer.buffer, + handle->response_buffer.length, + &handle->response_buffer.dns_response); + } else { + ESP_LOGE(TAG, "HTTP Error: %d", esp_http_client_get_status_code(evt->client)); + temp_buff_len = handle->response_buffer.length > ESP_DNS_BUFFER_SIZE ? ESP_DNS_BUFFER_SIZE : handle->response_buffer.length; + ESP_LOG_BUFFER_HEXDUMP(TAG, handle->response_buffer.buffer, temp_buff_len, ESP_LOG_ERROR); + handle->response_buffer.dns_response.status_code = ERR_VAL; /* TBD: Not handled properly yet */ + } + + free(handle->response_buffer.buffer); + handle->response_buffer.buffer = NULL; + handle->response_buffer.length = 0; + break; + case HTTP_EVENT_DISCONNECTED: + ESP_LOGD(TAG, "HTTP_EVENT_DISCONNECTED"); + break; + case HTTP_EVENT_REDIRECT: + ESP_LOGE(TAG, "HTTP_EVENT_REDIRECT: Not supported(%d)", esp_http_client_get_status_code(evt->client)); + break; + } + return ESP_OK; +} + +/** + * @brief Resolves a hostname using DNS over HTTPS + * + * This function generates a DNS request, sends it via HTTPS, and processes + * the response to extract IP addresses. + * + * @param handle Pointer to the DNS handle + * @param name The hostname to resolve + * @param addr Pointer to store the resolved IP addresses + * @param rrtype The address RR type (A or AAAA) + * + * @return ERR_OK on success, or an error code on failure + */ +err_t dns_resolve_doh(const esp_dns_handle_t handle, const char *name, ip_addr_t *addr, u8_t rrtype) +{ + uint8_t buffer_qry[ESP_DNS_BUFFER_SIZE]; + + /* Initialize error status */ + err_t err = ERR_OK; + const char *prefix = "https://"; + + /* Set default values for DoH configuration if not specified */ + const char *url_path = handle->config.protocol_config.doh_config.url_path ? + handle->config.protocol_config.doh_config.url_path : "dns-query"; + int port = handle->config.port ? + handle->config.port : ESP_DNS_DEFAULT_DOH_PORT; + + /* Calculate required URL length: https:// + server + / + path + null terminator */ + size_t url_len = strlen(prefix) + \ + strlen(handle->config.dns_server) + 1 + \ + strlen(url_path) + 1; /* 1 for '/' and 1 for '\0' */ + + /* Allocate memory for the full server URL */ + char *dns_server_url = malloc(url_len); + if (dns_server_url == NULL) { + ESP_LOGE(TAG, "Memory allocation failed"); + return ERR_MEM; + } + + /* Construct the complete server URL by combining prefix, server and path */ + snprintf(dns_server_url, url_len, "%s%s/%s", prefix, + handle->config.dns_server, + url_path); + + /* Configure the HTTP client with base settings */ + esp_http_client_config_t config = { + .url = dns_server_url, + .event_handler = _http_event_handler, + .method = HTTP_METHOD_POST, + .user_data = handle, + .port = port, + }; + + /* Configure TLS certificate settings - either using bundle or PEM cert */ + if (handle->config.tls_config.crt_bundle_attach) { + config.crt_bundle_attach = handle->config.tls_config.crt_bundle_attach; + } else { + config.cert_pem = handle->config.tls_config.cert_pem; /* Use the root certificate for dns.google if needed */ + } + + /* Clear the response buffer to ensure no residual data remains */ + memset(&handle->response_buffer, 0, sizeof(response_buffer_t)); + + /* Create DNS query in wire format */ + size_t query_size = esp_dns_create_query(buffer_qry, sizeof(buffer_qry), name, rrtype, &handle->response_buffer.dns_response.id); + if (query_size == -1) { + ESP_LOGE(TAG, "Error: Hostname too big"); + err = ERR_MEM; + goto cleanup; + } + + /* Initialize HTTP client with the configuration */ + esp_http_client_handle_t client = esp_http_client_init(&config); + if (client == NULL) { + ESP_LOGE(TAG, "Error initializing HTTP client"); + err = ERR_VAL; + goto cleanup; + } + + /* Set Content-Type header for DNS-over-HTTPS */ + esp_err_t ret = esp_http_client_set_header(client, "Content-Type", "application/dns-message"); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "Error setting HTTP header: %s", esp_err_to_name(ret)); + err = ERR_VAL; + goto client_cleanup; + } + + /* Set the DNS query as POST data */ + ret = esp_http_client_set_post_field(client, (const char *)buffer_qry, query_size); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "Error setting POST field: %s", esp_err_to_name(ret)); + err = ERR_VAL; + goto client_cleanup; + } + + /* Execute the HTTP request */ + ret = esp_http_client_perform(client); + if (ret == ESP_OK) { + ESP_LOGD(TAG, "HTTP POST Status = %d, content_length = %lld", + esp_http_client_get_status_code(client), + esp_http_client_get_content_length(client)); + + /* Verify HTTP status code and DNS response status */ + if ((HttpStatus_Ok != esp_http_client_get_status_code(client)) || + (handle->response_buffer.dns_response.status_code != ERR_OK)) { + err = ERR_ARG; + goto client_cleanup; + } + + /* Extract IP addresses from DNS response */ + err = esp_dns_extract_ip_addresses_from_response(&handle->response_buffer.dns_response, addr); + } else { + ESP_LOGE(TAG, "HTTP POST request failed: %s", esp_err_to_name(ret)); + err = ERR_VAL; + } + + /* Clean up HTTP client */ +client_cleanup: + esp_http_client_cleanup(client); + + /* Free allocated memory */ +cleanup: + free(dns_server_url); + + return err; +} diff --git a/components/esp_dns/esp_dns_dot.c b/components/esp_dns/esp_dns_dot.c new file mode 100644 index 0000000000..f4bace1f84 --- /dev/null +++ b/components/esp_dns/esp_dns_dot.c @@ -0,0 +1,202 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include "esp_transport.h" +#include "esp_transport_ssl.h" +#include "esp_dns_priv.h" +#include "esp_dns.h" + + +#define TAG "ESP_DNS_DOT" + + +/** + * @brief Initializes the DNS over TLS (DoT) module + * + * Sets up the DoT service using the provided configuration. Validates the parameters, + * sets the protocol, and initializes the DNS module. Returns a handle for further use. + * + * @param config Pointer to the DNS configuration structure, which must be initialized + * + * @return On success, returns a handle to the initialized DoT module; returns NULL on failure + */ +esp_dns_handle_t esp_dns_init_dot(esp_dns_config_t *config) +{ + ESP_LOGD(TAG, "Initializing DNS over TLS"); + + /* Validate parameters */ + if (config == NULL) { + ESP_LOGE(TAG, "Invalid configuration (NULL)"); + return NULL; + } + + config->protocol = ESP_DNS_PROTOCOL_DOT; + + esp_dns_handle_t handle = esp_dns_init(config); + if (handle == NULL) { + ESP_LOGE(TAG, "Failed to initialize DNS"); + return NULL; + } + + ESP_LOGD(TAG, "DNS module initialized successfully with protocol DNS Over TLS(%d)", config->protocol); + return handle; +} + + +/** + * @brief Cleans up the DNS over TLS (DoT) module + * + * Releases resources allocated for the DoT service. Validates the parameters, + * checks the protocol, and cleans up the DNS module. + * + * @param handle Pointer to the DNS handle to be cleaned up + * + * @return 0 on success, or -1 on failure + */ +int esp_dns_cleanup_dot(esp_dns_handle_t handle) +{ + ESP_LOGD(TAG, "Cleaning up DNS over TLS"); + + /* Validate parameters */ + if (handle == NULL) { + ESP_LOGE(TAG, "Invalid handle (NULL)"); + return -1; + } + + if (handle->config.protocol != ESP_DNS_PROTOCOL_DOT) { + ESP_LOGW(TAG, "Unknown protocol during cleanup: %d", handle->config.protocol); + return -1; + } + + int ret = esp_dns_cleanup(handle); + if (ret != 0) { + ESP_LOGE(TAG, "Failed to cleanup DNS"); + return ret; + } + + ESP_LOGD(TAG, "DNS module cleaned up DNS Over TLS successfully"); + return 0; +} + +/** + * @brief Resolves a hostname using DNS over TLS (DoT) + * + * Performs DNS resolution over a TLS-encrypted connection. Creates a DNS query, + * establishes a TLS connection, sends the query, and processes the response. + * + * @param handle Pointer to the DNS handle + * @param name Hostname to resolve + * @param addr Pointer to store the resolved IP address + * @param rrtype DNS record type to query + * + * @return ERR_OK on success, or an error code on failure + */ +err_t dns_resolve_dot(const esp_dns_handle_t handle, const char *name, ip_addr_t *addr, u8_t rrtype) +{ + int err = ERR_OK; + esp_transport_handle_t transport = NULL; + int len = 0; + char dot_buffer[ESP_DNS_BUFFER_SIZE]; + size_t query_size; + int timeout_ms; + int dot_port; + + if (addr == NULL) { + return ERR_ARG; + } + + /* Set timeout and port values, using defaults if not specified in config */ + timeout_ms = handle->config.timeout_ms ? : ESP_DNS_DEFAULT_TIMEOUT_MS; + dot_port = handle->config.port ? : ESP_DNS_DEFAULT_DOT_PORT; + + /* Clear the response buffer to ensure no residual data remains */ + memset(&handle->response_buffer, 0, sizeof(response_buffer_t)); + + /* Create DNS query in wire format, leaving 2 bytes at start for length prefix as required by RFC 7858 */ + memset(dot_buffer, 0, ESP_DNS_BUFFER_SIZE); + query_size = esp_dns_create_query((uint8_t *)(dot_buffer + 2), sizeof(dot_buffer) - 2, + name, rrtype, &handle->response_buffer.dns_response.id); + if (query_size == -1) { + ESP_LOGE(TAG, "Error: Hostname too big"); + return ERR_MEM; + } + + /* Prepends the 2-byte length field to DNS messages as required by RFC 7858 */ + dot_buffer[0] = (query_size >> 8) & 0xFF; + dot_buffer[1] = query_size & 0xFF; + + transport = esp_transport_ssl_init(); + if (!transport) { + ESP_LOGE(TAG, "Failed to initialize transport"); + return ERR_MEM; + } + + /* Configure TLS certificate settings - either using bundle or PEM cert */ + if (handle->config.tls_config.crt_bundle_attach) { + esp_transport_ssl_crt_bundle_attach(transport, handle->config.tls_config.crt_bundle_attach); + } else { + if (handle->config.tls_config.cert_pem == NULL) { + ESP_LOGE(TAG, "Certificate PEM data is null"); + err = ERR_VAL; + goto cleanup; + } + esp_transport_ssl_set_cert_data(transport, + handle->config.tls_config.cert_pem, + strlen(handle->config.tls_config.cert_pem)); + } + + if (esp_transport_connect(transport, handle->config.dns_server, dot_port, timeout_ms) < 0) { + ESP_LOGE(TAG, "TLS connection failed"); + err = ERR_CONN; + goto cleanup; + } + + /* Send DNS query */ + len = esp_transport_write(transport, + dot_buffer, + query_size + 2, + timeout_ms); + if (len < 0) { + ESP_LOGE(TAG, "Failed to send DNS query"); + err = ERR_ABRT; + goto cleanup; + } + + /* Read response */ + memset(dot_buffer, 0, ESP_DNS_BUFFER_SIZE); + len = esp_transport_read(transport, + dot_buffer, + sizeof(dot_buffer), + timeout_ms); + if (len > 0) { + /* Skip the 2-byte length field that prepends DNS messages as required by RFC 7858 */ + handle->response_buffer.buffer = dot_buffer + 2; + handle->response_buffer.length = len - 2; + + /* Parse the DNS response */ + esp_dns_parse_response((uint8_t *)handle->response_buffer.buffer, + handle->response_buffer.length, + &handle->response_buffer.dns_response); + + /* Extract IP addresses from DNS response */ + err = esp_dns_extract_ip_addresses_from_response(&handle->response_buffer.dns_response, addr); + if (err != ERR_OK) { + ESP_LOGE(TAG, "Failed to extract IP address from DNS response"); + goto cleanup; + } + } else { + ESP_LOGE(TAG, "Failed to receive response"); + err = ERR_ABRT; + goto cleanup; + } + +cleanup: + if (transport) { + esp_transport_close(transport); + esp_transport_destroy(transport); + } + + return err; +} diff --git a/components/esp_dns/esp_dns_lwip.c b/components/esp_dns/esp_dns_lwip.c new file mode 100644 index 0000000000..f46ec8674d --- /dev/null +++ b/components/esp_dns/esp_dns_lwip.c @@ -0,0 +1,111 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file esp_dns_lwip.c + * @brief Custom DNS module for ESP32 with multiple protocol support + * + * Provides DNS resolution capabilities with support for various protocols: + * - Standard UDP/TCP DNS (Port 53) + * - DNS over TLS (DoT) (Port 853) + * - DNS over HTTPS (DoH) (Port 443) + */ + +#include +#include +#include +#include +#include + +#include "freertos/FreeRTOS.h" +#include "esp_log.h" + +#include "esp_dns.h" +#include "esp_dns_priv.h" + +#define TAG "ESP_DNS_LWIP" + +/* Global DNS handle instance */ +extern esp_dns_handle_t g_dns_handle; + +/* ========================= LWIP HOOK FUNCTIONS ========================= */ + +#if defined(CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM) +/** + * @brief Custom DNS resolution hook for lwIP network connections + * + * @param name Hostname to resolve + * @param addr Pointer to store resolved IP address + * @param addrtype Type of address to resolve (IPv4/IPv6) + * @param err Pointer to store error code + * + * @return int 0 if resolution should be handled by lwIP, 1 if handled by this module + */ +int lwip_hook_netconn_external_resolve(const char *name, ip_addr_t *addr, u8_t addrtype, err_t *err) +{ + if (g_dns_handle == NULL) { + ESP_LOGD(TAG, "ESP_DNS module not initialized, resolving through native DNS"); + *err = ERR_OK; + return 0; + } + + if (name == NULL || addr == NULL || err == NULL) { + if (err) { + *err = ERR_ARG; + } + return 1; + } + + /* Check if name is already an IP address */ + if (ipaddr_aton(name, addr)) { + *err = ERR_OK; + return 0; + } + + /* Check if DNS server name matches or if it's localhost */ + if ((strcmp(name, g_dns_handle->config.dns_server) == 0) || +#if LWIP_HAVE_LOOPIF + (strcmp(name, "localhost") == 0) || +#endif + ipaddr_aton(name, addr)) { + return 0; + } + + u8_t rrtype; + if ((addrtype == NETCONN_DNS_IPV4) || (addrtype == NETCONN_DNS_IPV4_IPV6)) { + rrtype = DNS_RRTYPE_A; + } else if ((addrtype == NETCONN_DNS_IPV6) || (addrtype == NETCONN_DNS_IPV6_IPV4)) { + rrtype = DNS_RRTYPE_AAAA; + } else { + ESP_LOGE(TAG, "Invalid address type"); + *err = ERR_VAL; + return 1; + } + + /* Resolve based on configured transport type */ + switch (g_dns_handle->config.protocol) { + case ESP_DNS_PROTOCOL_UDP: + /* Return zero as lwIP DNS can handle UDP DNS */ + return 0; + case ESP_DNS_PROTOCOL_TCP: + *err = dns_resolve_tcp(g_dns_handle, name, addr, rrtype); + break; + case ESP_DNS_PROTOCOL_DOT: + *err = dns_resolve_dot(g_dns_handle, name, addr, rrtype); + break; + case ESP_DNS_PROTOCOL_DOH: + *err = dns_resolve_doh(g_dns_handle, name, addr, rrtype); + break; + default: + ESP_LOGE(TAG, "Invalid transport type"); + *err = ERR_VAL; + } + + return 1; +} +#else +#error "CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not defined. Please enable it in your menuconfig" +#endif /* CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM */ diff --git a/components/esp_dns/esp_dns_priv.h b/components/esp_dns/esp_dns_priv.h new file mode 100644 index 0000000000..c16d32abcd --- /dev/null +++ b/components/esp_dns/esp_dns_priv.h @@ -0,0 +1,116 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +/** + * @file esp_dns_priv.h + * @brief Private header for ESP DNS module + * + * This module provides DNS resolution capabilities with support for various protocols: + * - Standard UDP/TCP DNS (Port 53) + * - DNS over TLS (DoT) + * - DNS over HTTPS (DoH) + */ + +#include +#include +#include +#include +#include + +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/task.h" +#include "lwip/prot/dns.h" +#include "lwip/ip_addr.h" +#include "lwip/err.h" +#include "esp_log.h" + +#include "esp_dns.h" +#include "esp_dns_utils.h" + +/** + * @brief Opaque handle type for DNS module instances + */ +struct esp_dns_handle { + /* Configuration */ + esp_dns_config_t config; /* Copy of user configuration */ + + /* Connection state */ + bool initialized; /* Flag indicating successful initialization */ + + response_buffer_t response_buffer; /* Buffer for storing DNS response data during processing */ + + /* Thread safety */ + SemaphoreHandle_t lock; /* Mutex for synchronization */ +}; + + +/** + * @brief Initialize DNS module with configuration + * + * @param config DNS configuration parameters + * + * @return esp_dns_handle_t Handle to DNS module instance + */ +esp_dns_handle_t esp_dns_init(const esp_dns_config_t *config); + +/** + * @brief Clean up DNS module resources + * + * @param handle DNS module handle + * + * @return int 0 on success, negative error code on failure + */ +int esp_dns_cleanup(esp_dns_handle_t handle); + +/** + * @brief Resolve hostname using DNS over HTTPS + * + * @param handle DNS module handle + * @param name Hostname to resolve + * @param addr Pointer to store resolved IP address + * @param rrtype Record type (A or AAAA) + * + * @return err_t Error code + */ +err_t dns_resolve_doh(const esp_dns_handle_t handle, const char *name, ip_addr_t *addr, u8_t rrtype); + +/** + * @brief Resolve hostname using DNS over TLS + * + * @param handle DNS module handle + * @param name Hostname to resolve + * @param addr Pointer to store resolved IP address + * @param rrtype Record type (A or AAAA) + * + * @return err_t Error code + */ +err_t dns_resolve_dot(const esp_dns_handle_t handle, const char *name, ip_addr_t *addr, u8_t rrtype); + +/** + * @brief Resolve hostname using TCP DNS + * + * @param handle DNS module handle + * @param name Hostname to resolve + * @param addr Pointer to store resolved IP address + * @param rrtype Record type (A or AAAA) + * + * @return err_t Error code + */ +err_t dns_resolve_tcp(const esp_dns_handle_t handle, const char *name, ip_addr_t *addr, u8_t rrtype); + +/** + * @brief Resolve hostname using UDP DNS + * + * @param handle DNS module handle + * @param name Hostname to resolve + * @param addr Pointer to store resolved IP address + * @param rrtype Record type (A or AAAA) + * + * @return err_t Error code + */ +err_t dns_resolve_udp(const esp_dns_handle_t handle, const char *name, ip_addr_t *addr, u8_t rrtype); diff --git a/components/esp_dns/esp_dns_tcp.c b/components/esp_dns/esp_dns_tcp.c new file mode 100644 index 0000000000..0c52093f0a --- /dev/null +++ b/components/esp_dns/esp_dns_tcp.c @@ -0,0 +1,185 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include "esp_transport.h" +#include "esp_transport_tcp.h" +#include "esp_dns_priv.h" +#include "esp_dns.h" + +#define TAG "ESP_DNS_TCP" + +/** + * @brief Initializes the TCP DNS module + * + * Sets up the TCP DNS service using the provided configuration. Validates the parameters, + * sets the protocol, and initializes the DNS module. + * + * @param config Pointer to the DNS configuration structure + * + * @return Handle to the initialized TCP module on success, NULL on failure + */ +esp_dns_handle_t esp_dns_init_tcp(esp_dns_config_t *config) +{ + ESP_LOGD(TAG, "Initializing TCP DNS"); + + /* Validate parameters */ + if (config == NULL) { + ESP_LOGE(TAG, "Invalid configuration (NULL)"); + return NULL; + } + + config->protocol = ESP_DNS_PROTOCOL_TCP; + + esp_dns_handle_t handle = esp_dns_init(config); + if (handle == NULL) { + ESP_LOGE(TAG, "Failed to initialize DNS"); + return NULL; + } + + ESP_LOGD(TAG, "DNS module initialized successfully with protocol DNS Over TCP(%d)", config->protocol); + return handle; +} + +/** + * @brief Cleans up the TCP DNS module + * + * Releases resources allocated for the TCP DNS service. Validates the parameters, + * checks the protocol, and cleans up the DNS module. + * + * @param handle Pointer to the DNS handle to be cleaned up + * + * @return 0 on success, -1 on failure + */ +int esp_dns_cleanup_tcp(esp_dns_handle_t handle) +{ + ESP_LOGD(TAG, "Cleaning up TCP DNS"); + + /* Validate parameters */ + if (handle == NULL) { + ESP_LOGE(TAG, "Invalid handle (NULL)"); + return -1; + } + + if (handle->config.protocol != ESP_DNS_PROTOCOL_TCP) { + ESP_LOGW(TAG, "Unknown protocol during cleanup: %d", handle->config.protocol); + return -1; + } + + int ret = esp_dns_cleanup(handle); + if (ret != 0) { + ESP_LOGE(TAG, "Failed to cleanup DNS"); + return ret; + } + + ESP_LOGD(TAG, "DNS module cleaned up DNS Over TCP successfully"); + return 0; +} + +/** + * @brief Resolves a hostname using TCP DNS + * + * Performs DNS resolution over TCP for the given hostname. Creates a TCP connection, + * sends the DNS query, and processes the response. + * + * @param handle DNS handle + * @param name Hostname to resolve + * @param addr Pointer to store the resolved IP address + * @param rrtype DNS record type + * + * @return ERR_OK on success, error code on failure + */ +err_t dns_resolve_tcp(const esp_dns_handle_t handle, const char *name, ip_addr_t *addr, u8_t rrtype) +{ + int err = ERR_OK; + esp_transport_handle_t transport = NULL; + int len = 0; + char tcp_buffer[ESP_DNS_BUFFER_SIZE]; + size_t query_size; + int timeout_ms; + int tcp_port; + + if (addr == NULL) { + return ERR_ARG; + } + + /* Set timeout and port values, using defaults if not specified in config */ + timeout_ms = handle->config.timeout_ms ? : ESP_DNS_DEFAULT_TIMEOUT_MS; + tcp_port = handle->config.port ? : ESP_DNS_DEFAULT_TCP_PORT; + + /* Clear the response buffer to ensure no residual data remains */ + memset(&handle->response_buffer, 0, sizeof(response_buffer_t)); + + /* Create DNS query in wire format, leaving 2 bytes at start for length prefix as required by RFC 7858 */ + memset(tcp_buffer, 0, ESP_DNS_BUFFER_SIZE); + query_size = esp_dns_create_query((uint8_t *)(tcp_buffer + 2), sizeof(tcp_buffer) - 2, + name, rrtype, &handle->response_buffer.dns_response.id); + if (query_size == -1) { + ESP_LOGE(TAG, "Error: Hostname too big"); + return ERR_MEM; + } + + /* Prepends the 2-byte length field to DNS messages as required by RFC 7858 */ + tcp_buffer[0] = (query_size >> 8) & 0xFF; + tcp_buffer[1] = query_size & 0xFF; + + transport = esp_transport_tcp_init(); + if (!transport) { + ESP_LOGE(TAG, "Failed to initialize transport"); + return ERR_MEM; + } + + if (esp_transport_connect(transport, handle->config.dns_server, tcp_port, timeout_ms) < 0) { + ESP_LOGE(TAG, "TCP connection failed"); + err = ERR_CONN; + goto cleanup; + } + + /* Send DNS query */ + len = esp_transport_write(transport, + tcp_buffer, + query_size + 2, + timeout_ms); + if (len < 0) { + ESP_LOGE(TAG, "Failed to send DNS query"); + err = ERR_ABRT; + goto cleanup; + } + + /* Read response */ + memset(tcp_buffer, 0, ESP_DNS_BUFFER_SIZE); + len = esp_transport_read(transport, + tcp_buffer, + sizeof(tcp_buffer), + timeout_ms); + if (len > 0) { + /* Skip the 2-byte length field that prepends DNS messages as required by RFC 7858 */ + handle->response_buffer.buffer = tcp_buffer + 2; + handle->response_buffer.length = len - 2; + + /* Parse the DNS response */ + esp_dns_parse_response((uint8_t *)handle->response_buffer.buffer, + handle->response_buffer.length, + &handle->response_buffer.dns_response); + + /* Extract IP addresses from DNS response */ + err = esp_dns_extract_ip_addresses_from_response(&handle->response_buffer.dns_response, addr); + if (err != ERR_OK) { + ESP_LOGE(TAG, "Failed to extract IP address from DNS response"); + goto cleanup; + } + } else { + ESP_LOGE(TAG, "Failed to receive response"); + err = ERR_ABRT; + goto cleanup; + } + +cleanup: + if (transport) { + esp_transport_close(transport); + esp_transport_destroy(transport); + } + + return err; +} diff --git a/components/esp_dns/esp_dns_udp.c b/components/esp_dns/esp_dns_udp.c new file mode 100644 index 0000000000..fd0e5506e0 --- /dev/null +++ b/components/esp_dns/esp_dns_udp.c @@ -0,0 +1,103 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include "esp_dns_priv.h" +#include "esp_dns.h" + + +#define TAG "ESP_DNS_UDP" + + +/** + * @brief Initializes the UDP DNS module + * + * Sets up the UDP DNS service using the provided configuration. Validates the parameters, + * sets the protocol, and initializes the DNS module. + * + * @param config Pointer to the DNS configuration structure + * + * @return Handle to the initialized UDP module on success, NULL on failure + */ +esp_dns_handle_t esp_dns_init_udp(esp_dns_config_t *config) +{ + ESP_LOGD(TAG, "Initializing UDP DNS"); + + /* Validate parameters */ + if (config == NULL) { + ESP_LOGE(TAG, "Invalid configuration (NULL)"); + return NULL; + } + + config->protocol = ESP_DNS_PROTOCOL_UDP; + + esp_dns_handle_t handle = esp_dns_init(config); + if (handle == NULL) { + ESP_LOGE(TAG, "Failed to initialize DNS"); + return NULL; + } + + ESP_LOGD(TAG, "DNS module initialized successfully with protocol DNS Over UDP(%d)", config->protocol); + return handle; +} + + +/** + * @brief Cleans up the UDP DNS module + * + * Releases resources allocated for the UDP DNS service. Validates the parameters, + * checks the protocol, and cleans up the DNS module. + * + * @param handle Pointer to the DNS handle to be cleaned up + * + * @return 0 on success, -1 on failure + */ +int esp_dns_cleanup_udp(esp_dns_handle_t handle) +{ + ESP_LOGD(TAG, "Cleaning up UDP DNS"); + + /* Validate parameters */ + if (handle == NULL) { + ESP_LOGE(TAG, "Invalid handle (NULL)"); + return -1; + } + + if (handle->config.protocol != ESP_DNS_PROTOCOL_UDP) { + ESP_LOGW(TAG, "Unknown protocol during cleanup: %d", handle->config.protocol); + return -1; + } + + int ret = esp_dns_cleanup(handle); + if (ret != 0) { + ESP_LOGE(TAG, "Failed to cleanup DNS"); + return ret; + } + + ESP_LOGD(TAG, "DNS module cleaned up DNS Over UDP successfully"); + return 0; +} + + +/** + * @brief Resolves a hostname using UDP DNS + * + * Performs DNS resolution over UDP for the given hostname. Creates a UDP connection, + * sends the DNS query, and processes the response. + * + * @param handle DNS handle + * @param name Hostname to resolve + * @param addr Pointer to store the resolved IP address + * @param rrtype DNS record type + * + * @return ERR_OK on success, error code on failure + */ +err_t dns_resolve_udp(const esp_dns_handle_t handle, const char *name, ip_addr_t *addr, u8_t rrtype) +{ + // TBD: Implement UDP DNS resolution + if (addr == NULL) { + return ERR_ARG; + } + + return ERR_OK; +} diff --git a/components/esp_dns/esp_dns_utils.c b/components/esp_dns/esp_dns_utils.c new file mode 100644 index 0000000000..37a987c6d5 --- /dev/null +++ b/components/esp_dns/esp_dns_utils.c @@ -0,0 +1,242 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include "esp_random.h" +#include "esp_dns_utils.h" + +/** + * @brief Creates a DNS query packet in the provided buffer + * + * @param buffer Buffer to store the DNS query + * @param buffer_size Size of the buffer + * @param hostname Domain name to query + * @param addrtype Type of address to query (A or AAAA) + * @param id_o Pointer to store the generated query ID + * + * @return size_t Size of the created query packet, or -1 on error + */ +size_t esp_dns_create_query(uint8_t *buffer, size_t buffer_size, const char *hostname, int addrtype, uint16_t *id_o) +{ + /* + * Sample DNS Query for example.com (Type A) + * 0x00, 0x00, // Transaction ID + * 0x01, 0x00, // Flags: Standard query + * 0x00, 0x01, // Questions: 1 + * 0x00, 0x00, // Answer RRs: 0 + * 0x00, 0x00, // Authority RRs: 0 + * 0x00, 0x00, // Additional RRs: 0 + * 0x07, 'e', 'x', 'a', 'm', 'p', 'l', 'e', // QNAME: example.com + * 0x03, 'c', 'o', 'm', + * 0x00, // End of QNAME + * 0x00, 0x01, // QTYPE: A (host address) + * 0x00, 0x01 // QCLASS: IN (internet) + */ + + dns_header_t *header = (dns_header_t *)buffer; + memset(buffer, 0, buffer_size); + + /* Set header fields */ + *id_o = (uint16_t)(esp_random() & 0xFFFF); /* Return the id for response validation */ + header->id = htons(*id_o); /* Random transaction ID */ + header->flags = htons(0x0100); /* Standard query with recursion */ + header->qdcount = htons(1); /* One question */ + + /* Add the question name */ + uint8_t *qname = buffer + sizeof(dns_header_t); + const char *dot = hostname; + while (*dot) { + const char *next_dot = strchr(dot, '.'); + if (!next_dot) { + next_dot = dot + strlen(dot); + } + uint8_t len = next_dot - dot; + *qname++ = len; + /* Check for buffer overflow */ + if ((qname - buffer) > buffer_size) { + return -1; + } + memcpy(qname, dot, len); + qname += len; + dot = (*next_dot) ? next_dot + 1 : next_dot; + } + *qname++ = 0; /* Null-terminate the question name */ + + /* Set question fields */ + dns_question_t *question = (dns_question_t *)qname; + question->qtype = htons(addrtype); + question->qclass = htons(DNS_RRCLASS_IN); + + /* Return the total query size */ + return (qname + sizeof(dns_question_t)) - buffer; +} + +/** + * @brief Skips over a DNS name in a DNS reply message and returns the offset to the end of the name. + * + * This function handles both uncompressed labels and compression pointers according to RFC 1035. + * Reference: RFC 1035, sections 3.1 (Name Space Definitions) and 4.1.4 (Message Compression). + * + * @param ptr Pointer to the start of the DNS name in the DNS message + * @param remaining_bytes Number of bytes remaining in the buffer + * + * @return uint8_t* Pointer to the end of the DNS name, or NULL on error + */ +static uint8_t *skip_dns_name(uint8_t *ptr, size_t remaining_bytes) +{ + uint8_t offset = 0; + + /* Loop through each part of the name, handling labels and compression pointers */ + while (ptr[offset] != 0) { + if (offset >= remaining_bytes) { + return NULL; + } + /* Check if this part is a compression pointer, indicated by the two high bits set to 1 (0xC0) */ + /* RFC 1035, Section 4.1.4: Compression pointers */ + if ((ptr[offset] & 0xC0) == 0xC0) { + /* Compression pointer is 2 bytes; move offset by 2 and stop */ + offset += 2; + return ptr + offset; /* End of name processing due to pointer */ + } else { + /* Otherwise, it's a label + RFC 1035, Section 3.1: Labels + - The first byte is the length of this label + - Followed by 'length' bytes of label content */ + offset += ptr[offset] + 1; /* Move past this label (1 byte for length + label content) */ + } + } + + /* RFC 1035, Section 3.1: End of a name is indicated by a zero-length byte (0x00) */ + offset += 1; /* Move past the terminating zero byte */ + return ptr + offset; +} + +/** + * @brief Parses a DNS response message + * + * @param buffer Buffer containing the DNS response + * @param response_size Size of the response buffer + * + * @param dns_response Structure to store parsed response + */ +void esp_dns_parse_response(uint8_t *buffer, size_t response_size, dns_response_t *dns_response) +{ + /* Validate input buffer */ + assert(buffer != NULL); + + dns_header_t *header = (dns_header_t *)buffer; + + dns_response->status_code = ERR_OK; /* Initialize DNS response code */ + + /* Check if there are answers and Transaction id matches */ + int answer_count = ntohs(header->ancount); + if ((ntohs(header->id) != dns_response->id) || (answer_count == 0)) { + dns_response->status_code = ERR_VAL; /* DNS response code */ + return; + } + + /* Ensure only MAX_ANSWERS are processed */ + dns_response->num_answers = (answer_count < MAX_ANSWERS ? answer_count : MAX_ANSWERS); + + /* Skip the header and question section */ + uint8_t *ptr = buffer + sizeof(dns_header_t); + + /* Skip the question name */ + ptr = skip_dns_name(ptr, response_size - (ptr - buffer)); + if (ptr == NULL) { + dns_response->status_code = ERR_VAL; + return; + } + + /* Skip the question type and class */ + ptr += sizeof(dns_question_t); + + /* Parse each answer record */ + for (int i = 0; i < dns_response->num_answers; i++) { + + /* Answer fields */ + ptr = skip_dns_name(ptr, response_size - (ptr - buffer)); + if (ptr == NULL) { + dns_response->status_code = ERR_VAL; + return; + } + + dns_answer_t *answer = (dns_answer_t *)ptr; + uint16_t type = ntohs(answer->type); + uint16_t class = ntohs(answer->class); + uint32_t ttl = ntohl(answer->ttl); + uint16_t data_len = ntohs(answer->data_len); + + /* Skip fixed parts of answer (type, class, ttl, data_len) */ + ptr += SIZEOF_DNS_ANSWER; + + /* Validate RR class and ttl */ + if ((class != DNS_RRCLASS_IN) || (ttl > DNS_MAX_TTL)) { + dns_response->answers[i].status = ERR_VAL; + goto next_answer; + } + + /* Initialize status for this answer */ + dns_response->answers[i].status = ERR_OK; + + /* Check the type of answer */ + if (type == DNS_RRTYPE_A && data_len == 4) { + /* IPv4 Address (A record) */ + memcpy(&dns_response->answers[i].ip, ptr, sizeof(struct in_addr)); + IP_SET_TYPE(&dns_response->answers[i].ip, IPADDR_TYPE_V4); + } else if (type == DNS_RRTYPE_AAAA && data_len == 16) { + /* IPv6 Address (AAAA record) */ + memcpy(&dns_response->answers[i].ip, ptr, sizeof(struct in6_addr)); + IP_SET_TYPE(&dns_response->answers[i].ip, IPADDR_TYPE_V6); + } else { + dns_response->answers[i].status = ERR_VAL; + } + +next_answer: + /* Move pointer to next answer */ + ptr += data_len; + } +} + +/** + * @brief Converts a dns_response_t to an array of IP addresses. + * + * This function iterates over the DNS response and extracts valid + * IPv4 and IPv6 addresses, storing them in the provided array. + * + * @param response The DNS response to process + * @param ipaddr Array to store the extracted IP addresses + * + * @return err_t Status of DNS response parsing + */ +err_t esp_dns_extract_ip_addresses_from_response(const dns_response_t *response, ip_addr_t ipaddr[]) +{ + int count = 0; + memset(ipaddr, 0, DNS_MAX_HOST_IP * sizeof(ip_addr_t)); + + if (response->status_code != ERR_OK) { + return response->status_code; + } + + /* Iterate over the DNS answers */ + for (int i = 0; i < response->num_answers && count < DNS_MAX_HOST_IP; i++) { + const dns_answer_storage_t *answer = &response->answers[i]; + + /* Check if the answer is valid */ + if (answer->status != ERR_OK) { + continue; + } + + ipaddr[count] = answer->ip; + count++; + } + + if (count == 0) { + return ERR_VAL; + } + + /* Store the number of valid IP addresses */ + return ERR_OK; +} diff --git a/components/esp_dns/esp_dns_utils.h b/components/esp_dns/esp_dns_utils.h new file mode 100644 index 0000000000..11c94891c8 --- /dev/null +++ b/components/esp_dns/esp_dns_utils.h @@ -0,0 +1,134 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "freertos/FreeRTOS.h" +#include "esp_event.h" +#include "esp_log.h" +#include "nvs_flash.h" +#include "esp_tls.h" +#include "sdkconfig.h" +#include "lwip/prot/dns.h" +#include "lwip/api.h" +#include "lwip/opt.h" +#include "lwip/dns.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_DNS_BUFFER_SIZE 512 + +/** + * @brief DNS header structure + * + * Contains the basic fields of a DNS message header as defined in RFC 1035 + */ +typedef struct { + uint16_t id; /* Identification - unique identifier for the query */ + uint16_t flags; /* Flags - control bits for the DNS message */ + uint16_t qdcount; /* Number of questions in the question section */ + uint16_t ancount; /* Number of answers in the answer section */ + uint16_t nscount; /* Number of authority records in the authority section */ + uint16_t arcount; /* Number of additional records in the additional section */ +} dns_header_t; + +/** + * @brief DNS question structure + * + * Represents a single question in the question section of a DNS message + */ +typedef struct { + uint16_t qtype; /* Question type (e.g., A, AAAA, MX) */ + uint16_t qclass; /* Question class (e.g., IN for internet) */ +} dns_question_t; + +/** + * @brief DNS answer message structure + * + * Represents a single resource record in the answer section of a DNS message + * No packing needed as it's only used locally on the stack + */ +typedef struct { + uint16_t type; /* Resource record type (e.g., A, AAAA, MX) */ + uint16_t class; /* Resource record class (e.g., IN for internet) */ + uint32_t ttl; /* Time-to-live in seconds */ + uint16_t data_len; /* Length of the resource data */ +} dns_answer_t; + +#define SIZEOF_DNS_ANSWER 10 /* Size of dns_answer_t structure in bytes */ + +/** Maximum TTL value for DNS resource records (one week) */ +#define DNS_MAX_TTL 604800 + +/** Maximum number of answers that can be stored */ +#define MAX_ANSWERS (CONFIG_LWIP_DNS_MAX_HOST_IP) + +/** + * @brief Structure to store a single DNS answer + */ +typedef struct { + err_t status; /* Status of the answer */ + ip_addr_t ip; /* IP address from the answer */ +} dns_answer_storage_t; + +/** + * @brief Structure to store a complete DNS response + */ +typedef struct { + err_t status_code; /* Overall status of the DNS response */ + uint16_t id; /* Transaction ID */ + int num_answers; /* Number of valid answers */ + dns_answer_storage_t answers[MAX_ANSWERS]; /* Array of answers */ +} dns_response_t; + +/** + * @brief Buffer structure for DNS response processing + */ +typedef struct { + char *buffer; /* Pointer to response data buffer */ + int length; /* Current length of data in buffer */ + dns_response_t dns_response; /* Parsed DNS response information */ +} response_buffer_t; + +/** + * @brief Creates a DNS query for A and AAAA records + * + * @param buffer Buffer to store the query + * @param buffer_size Size of the buffer + * @param hostname Hostname to query + * @param addrtype Address type (A or AAAA) + * @param id_o Pointer to store the generated query ID + * + * @return size_t Size of the created query, or -1 on error + */ +size_t esp_dns_create_query(uint8_t *buffer, size_t buffer_size, const char *hostname, int addrtype, uint16_t *id_o); + +/** + * @brief Parses a DNS response message + * + * @param buffer Buffer containing the DNS response + * @param response_size Size of the response + * @param dns_response Structure to store parsed response + */ +void esp_dns_parse_response(uint8_t *buffer, size_t response_size, dns_response_t *dns_response); + +/** + * @brief Converts a dns_response_t to an array of IP addresses. + * + * This function iterates over the DNS response and extracts valid + * IPv4 and IPv6 addresses, storing them in the provided array. + * + * @param response The DNS response to process. + * @param ipaddr An array to store the extracted IP addresses. + * + * @return err Status of dns response parsing + */ +err_t esp_dns_extract_ip_addresses_from_response(const dns_response_t *response, ip_addr_t ipaddr[]); + +#ifdef __cplusplus +} +#endif diff --git a/components/esp_dns/examples/esp_dns_basic/CMakeLists.txt b/components/esp_dns/examples/esp_dns_basic/CMakeLists.txt new file mode 100644 index 0000000000..3339e6318e --- /dev/null +++ b/components/esp_dns/examples/esp_dns_basic/CMakeLists.txt @@ -0,0 +1,8 @@ +# For more information about build system see +# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(esp_dns_example) diff --git a/components/esp_dns/examples/esp_dns_basic/README.md b/components/esp_dns/examples/esp_dns_basic/README.md new file mode 100644 index 0000000000..2df7397819 --- /dev/null +++ b/components/esp_dns/examples/esp_dns_basic/README.md @@ -0,0 +1,193 @@ +| Supported Targets | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | +| ----------------- | ----- | -------- | -------- | -------- | -------- | --------- | -------- | -------- | -------- | -------- | + +# ESP DNS Example + +This example demonstrates how to use the ESP DNS component in an ESP32 application. The example resolves domain names using various DNS protocols including standard UDP, TCP, DNS over TLS (DoT), and DNS over HTTPS (DoH). + +## Features + +- **Standard UDP DNS**: Traditional DNS resolution over UDP +- **DNS over TCP**: DNS resolution using TCP transport +- **DNS over TLS (DoT)**: Secure DNS resolution using TLS encryption +- **DNS over HTTPS (DoH)**: Secure DNS resolution using HTTPS + +## Certificate Options + +This example provides two certificate options for secure DNS protocols (DoT and DoH): + +1. **Certificate Bundle (Default)**: Uses the ESP-IDF certificate bundle, making it easy to get started with popular DNS providers like Google. +2. **Custom Certificate**: Uses a specific certificate for the DNS server. The example includes a Google DNS certificate. + +## How It Works + +1. **Network Initialization**: The application initializes the network interfaces (Wi-Fi or Ethernet) and establishes a connection. +2. **DNS Resolution Tests**: The example performs DNS resolution using different protocols: + - Native UDP DNS (system default) + - ESP DNS with UDP protocol + - ESP DNS with TCP protocol + - ESP DNS with DoT protocol (using server certificate) + - ESP DNS with DoT protocol (using certificate bundle) + - ESP DNS with DoH protocol (using server certificate) + - ESP DNS with DoH protocol (using certificate bundle) +3. **Domain Resolution**: For each protocol, the application resolves several domain names including: + - yahoo.com + - www.google.com + - IP addresses (0.0.0.0 and IPv6 address) + +## How to use example + +Before project configuration and build, be sure to set the correct chip target using `idf.py set-target `. + +### Hardware Required + +* A development board with ESP32/ESP32-S2/ESP32-C3 SoC (e.g., ESP32-DevKitC, ESP-WROVER-KIT, etc.) +* A USB cable for power supply and programming + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output: + +idf.py -p PORT flash monitor + + +(Replace PORT with the name of the serial port to use.) + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Troubleshooting Tips + +* **Connectivity**: + Ensure that the network connection details are accurate. For example, verify the Wi-Fi SSID and password or check that the Ethernet connection is secure and not faulty. + +* **Memory Issues**: + If you encounter memory-related errors, check the system information output which displays free heap and stack high water mark. You may need to increase task stack sizes for more complex DNS operations. + +* **Certificate Issues**: + For DoT and DoH protocols, ensure that the certificates are valid for the DNS server you're using. The example includes Google DNS certificates, but these may need to be updated if they expire. + +## Example Output + +``` +I (3188) wifi:new:<12,0>, old:<1,0>, ap:<255,255>, sta:<12,0>, prof:1, snd_ch_cfg:0x0 +I (3188) wifi:state: init -> auth (0xb0) +I (3218) wifi:state: auth -> assoc (0x0) +I (3238) wifi:state: assoc -> run (0x10) +I (3368) wifi:connected with Avrow, aid = 19, channel 12, BW20, bssid = a0:36:bc:0e:c4:f0 +I (3368) wifi:security: WPA2-PSK, phy: bgn, rssi: -52 +I (3368) wifi:pm start, type: 1 + +I (3368) wifi:dp: 1, bi: 102400, li: 3, scale listen interval from 307200 us to 307200 us +I (3408) wifi:idx:0 (ifx:0, a0:36:bc:0e:c4:f0), tid:6, ssn:2, winSize:64 +I (3418) wifi:AP's beacon interval = 102400 us, DTIM period = 1 +I (4398) esp_netif_handlers: example_netif_sta ip: 192.168.50.47, mask: 255.255.255.0, gw: 192.168.50.1 +I (4398) example_connect: Got IPv4 event: Interface "example_netif_sta" address: 192.168.50.47 +I (4558) example_connect: Got IPv6 event: Interface "example_netif_sta" address: fe80:0000:0000:0000:26d7:ebff:febb:f218, type: ESP_IP6_ADDR_IS_LINK_LOCAL +I (4558) example_common: Connected to example_netif_sta +I (4568) example_common: - IPv4 address: 192.168.50.47, +I (4568) example_common: - IPv6 address: fe80:0000:0000:0000:26d7:ebff:febb:f218, type: ESP_IP6_ADDR_IS_LINK_LOCAL + +I (4578) example_esp_dns: Executing DNS without initializing ESP_DNS module +I (4598) wifi:idx:1 (ifx:0, a0:36:bc:0e:c4:f0), tid:7, ssn:3, winSize:64 +I (4598) example_esp_dns: Hostname: yahoo.com: 98.137.11.164(IPv4) +I (4598) example_esp_dns: Hostname: yahoo.com: 74.6.143.25(IPv4) +I (4598) wifi:idx:0, tid:6 +I (4608) example_esp_dns: Hostname: yahoo.com: 74.6.231.21(IPv4) +I (4608) wifi:idx:0 (ifx:0, a0:36:bc:0e:c4:f0), tid:0, ssn:1, winSize:64 +I (4618) example_esp_dns: Hostname: yahoo.com: 74.6.231.20(IPv4) +I (4628) example_esp_dns: Hostname: www.google.com: 2404:6800:4015:803::2004(IPv6) +I (4638) example_esp_dns: Hostname: 0.0.0.0: 0.0.0.0(IPv4) +I (4638) example_esp_dns: Hostname: fe80:0000:0000:0000:5abf:25ff:fee0:4100: FE80::5ABF:25FF:FEE0:4100(IPv6) +I (4648) example_esp_dns: Free Heap: 220608 bytes, Min Free Heap: 210320 bytes, Stack High Water Mark: 1048 bytes + +I (4658) example_esp_dns: Executing UDP DNS +I (4658) ESP_DNS_UDP: Initializing UDP DNS +I (4668) ESP_DNS: DNS module initialized successfully with protocol 0 +I (4668) example_esp_dns: Hostname: yahoo.com: 98.137.11.164(IPv4) +I (4678) example_esp_dns: Hostname: yahoo.com: 74.6.143.25(IPv4) +I (4688) example_esp_dns: Hostname: yahoo.com: 74.6.231.21(IPv4) +I (4688) example_esp_dns: Hostname: yahoo.com: 74.6.231.20(IPv4) +I (4698) example_esp_dns: Hostname: www.google.com: 2404:6800:4015:803::2004(IPv6) +I (4698) example_esp_dns: Hostname: 0.0.0.0: 0.0.0.0(IPv4) +I (4708) example_esp_dns: Hostname: fe80:0000:0000:0000:5abf:25ff:fee0:4100: FE80::5ABF:25FF:FEE0:4100(IPv6) +I (4718) example_esp_dns: Free Heap: 220296 bytes, Min Free Heap: 210320 bytes, Stack High Water Mark: 1048 bytes +I (4728) ESP_DNS_UDP: Cleaning up UDP DNS +I (4728) ESP_DNS: DNS module cleaned up successfully + +I (4738) example_esp_dns: Executing DNS over TCP with server cert +I (4738) ESP_DNS_TCP: Initializing TCP DNS +I (4748) ESP_DNS: DNS module initialized successfully with protocol 1 +I (4778) example_esp_dns: Hostname: yahoo.com: 74.6.231.21(IPv4) +I (4778) example_esp_dns: Hostname: yahoo.com: 74.6.143.26(IPv4) +I (4778) example_esp_dns: Hostname: yahoo.com: 98.137.11.163(IPv4) +I (4788) example_esp_dns: Hostname: yahoo.com: 98.137.11.164(IPv4) +I (4818) example_esp_dns: Hostname: www.google.com: 2404:6800:4015:803::2004(IPv6) +I (4818) example_esp_dns: Hostname: 0.0.0.0: 0.0.0.0(IPv4) +I (4818) example_esp_dns: Hostname: fe80:0000:0000:0000:5abf:25ff:fee0:4100: FE80::5ABF:25FF:FEE0:4100(IPv6) +I (4828) example_esp_dns: Free Heap: 219848 bytes, Min Free Heap: 210320 bytes, Stack High Water Mark: 1048 bytes +I (4838) ESP_DNS_TCP: Cleaning up TCP DNS +I (4838) ESP_DNS: DNS module cleaned up successfully + +I (4848) example_esp_dns: Executing DNS over TLS with server cert +I (4848) ESP_DNS_DOT: Initializing DNS over TLS +I (4858) ESP_DNS: DNS module initialized successfully with protocol 2 +I (5878) example_esp_dns: Hostname: yahoo.com: 74.6.143.26(IPv4) +I (5878) example_esp_dns: Hostname: yahoo.com: 98.137.11.163(IPv4) +I (5878) example_esp_dns: Hostname: yahoo.com: 98.137.11.164(IPv4) +I (5888) example_esp_dns: Hostname: yahoo.com: 74.6.231.20(IPv4) +I (6978) example_esp_dns: Hostname: www.google.com: 2404:6800:4015:803::2004(IPv6) +I (6978) example_esp_dns: Hostname: 0.0.0.0: 0.0.0.0(IPv4) +I (6978) example_esp_dns: Hostname: fe80:0000:0000:0000:5abf:25ff:fee0:4100: FE80::5ABF:25FF:FEE0:4100(IPv6) +I (6988) example_esp_dns: Free Heap: 218948 bytes, Min Free Heap: 173612 bytes, Stack High Water Mark: 1048 bytes +I (6998) ESP_DNS_DOT: Cleaning up DNS over TLS +I (6998) ESP_DNS: DNS module cleaned up successfully + +I (7008) example_esp_dns: Executing DNS over TLS with cert bundle +I (7008) ESP_DNS_DOT: Initializing DNS over TLS +I (7018) ESP_DNS: DNS module initialized successfully with protocol 2 +I (7358) esp-x509-crt-bundle: Certificate validated +I (8158) example_esp_dns: Hostname: yahoo.com: 98.137.11.163(IPv4) +I (8158) example_esp_dns: Hostname: yahoo.com: 98.137.11.164(IPv4) +I (8158) example_esp_dns: Hostname: yahoo.com: 74.6.143.26(IPv4) +I (8158) example_esp_dns: Hostname: yahoo.com: 74.6.231.20(IPv4) +I (8478) esp-x509-crt-bundle: Certificate validated +I (9278) example_esp_dns: Hostname: www.google.com: 2404:6800:4015:803::2004(IPv6) +I (9278) example_esp_dns: Hostname: 0.0.0.0: 0.0.0.0(IPv4) +I (9278) example_esp_dns: Hostname: fe80:0000:0000:0000:5abf:25ff:fee0:4100: FE80::5ABF:25FF:FEE0:4100(IPv6) +I (9288) example_esp_dns: Free Heap: 218504 bytes, Min Free Heap: 173612 bytes, Stack High Water Mark: 1048 bytes +I (9298) ESP_DNS_DOT: Cleaning up DNS over TLS +I (9308) ESP_DNS: DNS module cleaned up successfully + +I (9308) example_esp_dns: Executing DNS over HTTPS with server cert +I (9318) ESP_DNS_DOH: Initializing DNS over HTTPS +I (9318) ESP_DNS: DNS module initialized successfully with protocol 3 +I (10368) example_esp_dns: Hostname: yahoo.com: 74.6.231.21(IPv4) +I (10368) example_esp_dns: Hostname: yahoo.com: 74.6.143.26(IPv4) +I (10368) example_esp_dns: Hostname: yahoo.com: 74.6.143.25(IPv4) +I (10378) example_esp_dns: Hostname: yahoo.com: 74.6.231.20(IPv4) +I (11508) example_esp_dns: Hostname: www.google.com: 2404:6800:4015:803::2004(IPv6) +I (11508) example_esp_dns: Hostname: 0.0.0.0: 0.0.0.0(IPv4) +I (11508) example_esp_dns: Hostname: fe80:0000:0000:0000:5abf:25ff:fee0:4100: FE80::5ABF:25FF:FEE0:4100(IPv6) +I (11518) example_esp_dns: Free Heap: 218068 bytes, Min Free Heap: 170516 bytes, Stack High Water Mark: 1048 bytes +I (11528) ESP_DNS_DOH: Cleaning up DNS over HTTPS +I (11528) ESP_DNS: DNS module cleaned up successfully + +I (11538) example_esp_dns: Executing DNS over HTTPS with cert bundle +I (11548) ESP_DNS_DOH: Initializing DNS over HTTPS +I (11548) ESP_DNS: DNS module initialized successfully with protocol 3 +I (11858) esp-x509-crt-bundle: Certificate validated +I (12668) example_esp_dns: Hostname: yahoo.com: 74.6.231.21(IPv4) +I (12678) example_esp_dns: Hostname: yahoo.com: 98.137.11.164(IPv4) +I (12678) example_esp_dns: Hostname: yahoo.com: 98.137.11.163(IPv4) +I (12678) example_esp_dns: Hostname: yahoo.com: 74.6.143.26(IPv4) +I (12948) esp-x509-crt-bundle: Certificate validated +I (13748) example_esp_dns: Hostname: www.google.com: 2404:6800:4015:803::2004(IPv6) +I (13748) example_esp_dns: Hostname: 0.0.0.0: 0.0.0.0(IPv4) +I (13748) example_esp_dns: Hostname: fe80:0000:0000:0000:5abf:25ff:fee0:4100: FE80::5ABF:25FF:FEE0:4100(IPv6) +I (13758) example_esp_dns: Free Heap: 217620 bytes, Min Free Heap: 170516 bytes, Stack High Water Mark: 1048 bytes +I (13768) ESP_DNS_DOH: Cleaning up DNS over HTTPS +I (13778) ESP_DNS: DNS module cleaned up successfully +I (13778) main_task: Returned from app_main() +``` diff --git a/components/esp_dns/examples/esp_dns_basic/main/CMakeLists.txt b/components/esp_dns/examples/esp_dns_basic/main/CMakeLists.txt new file mode 100644 index 0000000000..1271d39016 --- /dev/null +++ b/components/esp_dns/examples/esp_dns_basic/main/CMakeLists.txt @@ -0,0 +1,3 @@ +idf_component_register(SRCS "esp_dns_example.c" + INCLUDE_DIRS "." + EMBED_TXTFILES "cert_google_root.pem") diff --git a/components/esp_dns/examples/esp_dns_basic/main/cert_google_root.pem b/components/esp_dns/examples/esp_dns_basic/main/cert_google_root.pem new file mode 100644 index 0000000000..a13aa05641 --- /dev/null +++ b/components/esp_dns/examples/esp_dns_basic/main/cert_google_root.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw +CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU +MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw +MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp +Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo +27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w +Cl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw +TcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl +qAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH +szVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8 +Y/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk +MiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92 +wO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p +aDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN +VjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID +AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E +FgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb +C5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe +QkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy +h6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4 +7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J +ZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef +MgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/ +Z6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT +6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ +0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm +2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb +bP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c +-----END CERTIFICATE----- diff --git a/components/esp_dns/examples/esp_dns_basic/main/esp_dns_example.c b/components/esp_dns/examples/esp_dns_basic/main/esp_dns_example.c new file mode 100644 index 0000000000..83c9894952 --- /dev/null +++ b/components/esp_dns/examples/esp_dns_basic/main/esp_dns_example.c @@ -0,0 +1,324 @@ +/* + * SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#include +#include +#include +#include +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include +#include "esp_log.h" +#include "esp_system.h" +#include "nvs_flash.h" +#include "esp_event.h" +#include "esp_timer.h" +#include "lwip/opt.h" +#include "protocol_examples_common.h" +#include "esp_dns.h" +#if defined(CONFIG_MBEDTLS_CERTIFICATE_BUNDLE) +#include "esp_crt_bundle.h" +#endif + + +#ifndef INET6_ADDRSTRLEN +#define INET6_ADDRSTRLEN INET_ADDRSTRLEN +#endif + +#define TAG "example_esp_dns" + +extern const char server_root_cert_pem_start[] asm("_binary_cert_google_root_pem_start"); +extern const char server_root_cert_pem_end[] asm("_binary_cert_google_root_pem_end"); + + +/** + * @brief Performs DNS lookup for a given hostname and address family + * @param hostname The hostname to resolve + * @param family The address family (AF_INET, AF_INET6, or AF_UNSPEC) + */ +static void do_getaddrinfo(char *hostname, int family) +{ + struct addrinfo hints, *res, *p; + int status; + char ipstr[INET6_ADDRSTRLEN]; + void *addr = NULL; + char *ipver = NULL; + + /* Initialize the hints structure */ + memset(&hints, 0, sizeof hints); + hints.ai_family = family; + hints.ai_socktype = SOCK_DGRAM; /* UDP datagram sockets */ + + /* Get address information */ + if ((status = getaddrinfo(hostname, NULL, &hints, &res)) != 0) { + ESP_LOGE(TAG, "getaddrinfo error: %d", status); + goto cleanup; + } + + /* Loop through all the results */ + for (p = res; p != NULL; p = p->ai_next) { + + /* Get pointer to the address itself */ +#if defined(CONFIG_LWIP_IPV4) + if (p->ai_family == AF_INET) { /* IPv4 */ + struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr; + addr = &(ipv4->sin_addr); + ipver = "IPv4"; + + /* Convert the IP to a string and print it */ + inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr); + ESP_LOGI(TAG, "Hostname: %s: %s(%s)", hostname, ipstr, ipver); + } +#endif +#if defined(CONFIG_LWIP_IPV6) + if (p->ai_family == AF_INET6) { /* IPv6 */ + struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr; + addr = &(ipv6->sin6_addr); + ipver = "IPv6"; + + /* Convert the IP to a string and print it */ + inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr); + ESP_LOGI(TAG, "Hostname: %s: %s(%s)", hostname, ipstr, ipver); + } +#endif + } + +cleanup: + freeaddrinfo(res); /* Free the linked list */ +} + + +/** + * @brief Task that performs DNS lookups for various hostnames + * @param pvParameters Parent task handle for notification + */ +static void addr_info_task(void *pvParameters) +{ + TaskHandle_t parent_handle = (TaskHandle_t)pvParameters; + + do_getaddrinfo("yahoo.com", AF_UNSPEC); + do_getaddrinfo("www.google.com", AF_INET6); + do_getaddrinfo("0.0.0.0", AF_UNSPEC); + do_getaddrinfo("fe80:0000:0000:0000:5abf:25ff:fee0:4100", AF_UNSPEC); + + /* Notify parent task before deleting */ + if (parent_handle) { + xTaskNotifyGive(parent_handle); + } + vTaskDelete(NULL); +} + + +/** + * @brief Prints system information including heap and stack usage + */ +void print_system_info(void) +{ + /* Get the free heap size */ + uint32_t free_heap = esp_get_free_heap_size(); + uint32_t min_free_heap = esp_get_minimum_free_heap_size(); + + /* Get the stack high water mark for the current task */ + UBaseType_t stack_high_water_mark = uxTaskGetStackHighWaterMark(NULL); + + ESP_LOGI(TAG, "Free Heap: %d bytes, Min Free Heap: %d bytes, Stack High Water Mark: %d bytes\n", + free_heap, min_free_heap, stack_high_water_mark); +} + + +/** + * @brief Creates and runs the DNS query task + */ +static void run_dns_query_task(void) +{ + TaskHandle_t task_handle = NULL; + TaskHandle_t parent_handle = xTaskGetCurrentTaskHandle(); + xTaskCreate(addr_info_task, "AddressInfo", 4 * 1024, parent_handle, 5, &task_handle); + + /* Wait for task to complete */ + if (task_handle != NULL) { + xTaskNotifyWait(0, 0, NULL, portMAX_DELAY); + } + + print_system_info(); +} + + +/** + * @brief Performs DNS queries using UDP protocol + */ +void perform_esp_dns_udp_query(void) +{ + esp_dns_handle_t dns_handle; + + ESP_LOGI(TAG, "Executing UDP DNS"); + + /* Initialize with UDP DNS configuration */ + esp_dns_config_t udp_config = { + .dns_server = "dns.google", /* Google DNS */ + }; + + /* Initialize UDP DNS module */ + dns_handle = esp_dns_init_udp(&udp_config); + if (!dns_handle) { + ESP_LOGE(TAG, "Failed to initialize UDP DNS module"); + return; + } + + run_dns_query_task(); + + /* Cleanup */ + esp_dns_cleanup_udp(dns_handle); +} + + +/** + * @brief Performs DNS queries using TCP protocol + */ +void perform_esp_dns_tcp_query(void) +{ + esp_dns_handle_t dns_handle; + + ESP_LOGI(TAG, "Executing TCP DNS"); + + /* Initialize with TCP DNS configuration */ + esp_dns_config_t tcp_config = { + .dns_server = "dns.google", + .port = ESP_DNS_DEFAULT_TCP_PORT, + .timeout_ms = ESP_DNS_DEFAULT_TIMEOUT_MS, + }; + + /* Initialize TCP DNS module */ + dns_handle = esp_dns_init_tcp(&tcp_config); + if (!dns_handle) { + ESP_LOGE(TAG, "Failed to initialize TCP DNS module"); + return; + } + + run_dns_query_task(); + + /* Cleanup */ + esp_dns_cleanup_tcp(dns_handle); +} + + +/** + * @brief Performs DNS queries using DNS over TLS protocol + * @param val_type Type of certificate validation ("cert" or "bndl") + */ +void perform_esp_dns_dot_query(char *val_type) +{ + esp_dns_handle_t dns_handle; + + ESP_LOGI(TAG, "Executing DNS over TLS"); + + /* Initialize with DNS over TLS configuration */ + esp_dns_config_t dot_config = { + .dns_server = "dns.google", + .port = ESP_DNS_DEFAULT_DOT_PORT, + .timeout_ms = ESP_DNS_DEFAULT_TIMEOUT_MS, + }; + + if (strcmp(val_type, "cert") == 0) { + dot_config.tls_config.cert_pem = server_root_cert_pem_start; + } else if (strcmp(val_type, "bndl") == 0) { + dot_config.tls_config.crt_bundle_attach = esp_crt_bundle_attach; + } + + /* Initialize DoT DNS module */ + dns_handle = esp_dns_init_dot(&dot_config); + if (!dns_handle) { + ESP_LOGE(TAG, "Failed to initialize DoT DNS module"); + return; + } + + run_dns_query_task(); + + /* Cleanup */ + esp_dns_cleanup_dot(dns_handle); +} + + +/** + * @brief Performs DNS queries using DNS over HTTPS protocol + * @param val_type Type of certificate validation ("cert" or "bndl") + */ +void perform_esp_dns_doh_query(char *val_type) +{ + esp_dns_handle_t dns_handle; + + ESP_LOGI(TAG, "Executing DNS over HTTPS"); + + /* Initialize with DNS over HTTPS configuration */ + esp_dns_config_t doh_config = { + .dns_server = "dns.google", + .port = ESP_DNS_DEFAULT_DOH_PORT, + + .protocol_config.doh_config = { + .url_path = "/dns-query", + }, + }; + + if (strcmp(val_type, "cert") == 0) { + doh_config.tls_config.cert_pem = server_root_cert_pem_start; + } else if (strcmp(val_type, "bndl") == 0) { + doh_config.tls_config.crt_bundle_attach = esp_crt_bundle_attach; + } + + /* Initialize DoH DNS module */ + dns_handle = esp_dns_init_doh(&doh_config); + if (!dns_handle) { + ESP_LOGE(TAG, "Failed to initialize DoH DNS module"); + return; + } + + run_dns_query_task(); + + /* Cleanup */ + esp_dns_cleanup_doh(dns_handle); +} + + +void app_main(void) +{ + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + esp_err_t ret = nvs_flash_init(); /* Initialize NVS */ + if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { + ESP_ERROR_CHECK(nvs_flash_erase()); + ret = nvs_flash_init(); + } + ESP_ERROR_CHECK(ret); + + /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. + * Read "Establishing Wi-Fi or Ethernet Connection" section in + * examples/protocols/README.md for more information about this function. + */ + ESP_ERROR_CHECK(example_connect()); + + /* Test Without ESP_DNS module */ + ESP_LOGI(TAG, "Executing DNS without initializing ESP_DNS module"); + run_dns_query_task(); + + /* DNS over UDP Test */ + perform_esp_dns_udp_query(); + + /* DNS over TCP Test */ + perform_esp_dns_tcp_query(); + + /* DNS over TLS Test with cert */ + perform_esp_dns_dot_query("cert"); + + /* DNS over TLS Test with cert bundle */ + perform_esp_dns_dot_query("bndl"); + + /* DNS over HTTPS Test with cert */ + perform_esp_dns_doh_query("cert"); + + /* DNS over HTTPS Test with cert bundle */ + perform_esp_dns_doh_query("bndl"); +} diff --git a/components/esp_dns/examples/esp_dns_basic/main/idf_component.yml b/components/esp_dns/examples/esp_dns_basic/main/idf_component.yml new file mode 100644 index 0000000000..0f902b6b01 --- /dev/null +++ b/components/esp_dns/examples/esp_dns_basic/main/idf_component.yml @@ -0,0 +1,8 @@ +dependencies: + idf: + version: ">=5.1" + protocol_examples_common: + path: ${IDF_PATH}/examples/common_components/protocol_examples_common + esp_dns: + version: "*" + override_path: '../../../' diff --git a/components/esp_dns/examples/esp_dns_basic/pytest_esp_dns.py b/components/esp_dns/examples/esp_dns_basic/pytest_esp_dns.py new file mode 100644 index 0000000000..89276e6176 --- /dev/null +++ b/components/esp_dns/examples/esp_dns_basic/pytest_esp_dns.py @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Unlicense OR CC0-1.0 + +# -*- coding: utf-8 -*- + +import pytest + + +@pytest.mark.esp32 +def test_examples_getaddrinfo(dut): + dut.expect('esp>', timeout=30) + dut.write('getaddrinfo www.google.com') + dut.expect(r'getaddrinfo', timeout=30) + dut.expect(r'getaddrinfo', timeout=30) + dut.expect(r'getaddrinfo', timeout=30) + dut.expect(r'getaddrinfo', timeout=30) + dut.expect(r'getaddrinfo', timeout=30) diff --git a/components/esp_dns/examples/esp_dns_basic/sdkconfig.defaults b/components/esp_dns/examples/esp_dns_basic/sdkconfig.defaults new file mode 100644 index 0000000000..7684c687c3 --- /dev/null +++ b/components/esp_dns/examples/esp_dns_basic/sdkconfig.defaults @@ -0,0 +1,7 @@ +# This file was generated using idf.py save-defconfig. It can be edited manually. +# Espressif IoT Development Framework (ESP-IDF) 5.5.0 Project Minimal Configuration +# +CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE=y +CONFIG_LWIP_DNS_MAX_HOST_IP=4 +CONFIG_LWIP_USE_ESP_GETADDRINFO=y +CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM=y diff --git a/components/esp_dns/idf_component.yml b/components/esp_dns/idf_component.yml new file mode 100644 index 0000000000..55fb5cdb86 --- /dev/null +++ b/components/esp_dns/idf_component.yml @@ -0,0 +1,5 @@ +## IDF Component Manager Manifest File +version: 0.1.0 +dependencies: + idf: + version: ">=5.1" diff --git a/components/esp_dns/include/esp_dns.h b/components/esp_dns/include/esp_dns.h new file mode 100644 index 0000000000..93ea4fbfe6 --- /dev/null +++ b/components/esp_dns/include/esp_dns.h @@ -0,0 +1,155 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "sdkconfig.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_DNS_DEFAULT_TCP_PORT 53 /* Default TCP port for DNS */ +#define ESP_DNS_DEFAULT_DOT_PORT 853 /* Default TLS port for DNS over TLS */ +#define ESP_DNS_DEFAULT_DOH_PORT 443 /* Default HTTPS port for DNS over HTTPS */ + +#define ESP_DNS_DEFAULT_TIMEOUT_MS 10000 /* Default timeout for DNS queries in milliseconds */ + +typedef enum { + ESP_DNS_PROTOCOL_UDP, /* Traditional UDP DNS (Port 53) */ + ESP_DNS_PROTOCOL_TCP, /* TCP DNS (Port 53) */ + ESP_DNS_PROTOCOL_DOT, /* DNS over TLS (Port 853) */ + ESP_DNS_PROTOCOL_DOH, /* DNS over HTTPS (Port 443) */ +} esp_dns_protocol_type_t; + +/** + * @brief DNS configuration structure + */ +typedef struct { + /* Basic protocol selection */ + esp_dns_protocol_type_t protocol; /* DNS protocol type */ + + /* Common settings */ + const char *dns_server; /* DNS server IP address or hostname */ + uint16_t port; /* Custom port number (if not using default) */ + uint32_t timeout_ms; /* Query timeout in milliseconds */ + + /* Secure protocol options */ + struct { + const char *cert_pem; /* SSL server certification in PEM format as string */ + esp_err_t (*crt_bundle_attach)(void *conf); /* Function pointer to attach cert bundle */ + } tls_config; /* Used for DoT, DoH, DoH3, DNSCrypt, DoQ */ + + /* Protocol-specific options */ + union { + /* DoH options */ + struct { + const char *url_path; /* URL path for DoH service (e.g., "/dns-query") */ + } doh_config; /* DNS over HTTPS configuration */ + } protocol_config; /* Protocol-specific configuration */ +} esp_dns_config_t; + +typedef struct esp_dns_handle* esp_dns_handle_t; + +/** + * @brief Initialize DNS over HTTPS (DoH) module + * + * Sets up the DoH service using the provided configuration. Validates the parameters, + * sets the protocol, and initializes the DNS module. + * + * @param config Pointer to the DNS configuration structure + * + * @return Handle to the initialized DoH module on success, NULL on failure + */ +esp_dns_handle_t esp_dns_init_doh(esp_dns_config_t *config); + +/** + * @brief Initialize DNS over TLS (DoT) module + * + * Sets up the DoT service using the provided configuration. Validates the parameters, + * sets the protocol, and initializes the DNS module. + * + * @param config Pointer to the DNS configuration structure + * + * @return Handle to the initialized DoT module on success, NULL on failure + */ +esp_dns_handle_t esp_dns_init_dot(esp_dns_config_t *config); + +/** + * @brief Initialize TCP DNS module + * + * Sets up the TCP DNS service using the provided configuration. Validates the parameters, + * sets the protocol, and initializes the DNS module. + * + * @param config Pointer to the DNS configuration structure + * + * @return Handle to the initialized TCP module on success, NULL on failure + */ +esp_dns_handle_t esp_dns_init_tcp(esp_dns_config_t *config); + +/** + * @brief Initialize UDP DNS module + * + * Sets up the UDP DNS service using the provided configuration. Validates the parameters, + * sets the protocol, and initializes the DNS module. + * + * @param config Pointer to the DNS configuration structure + * + * @return Handle to the initialized UDP module on success, NULL on failure + */ +esp_dns_handle_t esp_dns_init_udp(esp_dns_config_t *config); + +/** + * @brief Clean up DNS over HTTPS (DoH) module + * + * Releases resources allocated for the DoH service. Validates the parameters, + * checks the protocol, and cleans up the DNS module. + * + * @param handle Pointer to the DNS handle to be cleaned up + * + * @return 0 on success, -1 on failure + */ +int esp_dns_cleanup_doh(esp_dns_handle_t handle); + +/** + * @brief Clean up DNS over TLS (DoT) module + * + * Releases resources allocated for the DoT service. Validates the parameters, + * checks the protocol, and cleans up the DNS module. + * + * @param handle Pointer to the DNS handle to be cleaned up + * + * @return 0 on success, -1 on failure + */ +int esp_dns_cleanup_dot(esp_dns_handle_t handle); + +/** + * @brief Clean up TCP DNS module + * + * Releases resources allocated for the TCP DNS service. Validates the parameters, + * checks the protocol, and cleans up the DNS module. + * + * @param handle Pointer to the DNS handle to be cleaned up + * + * @return 0 on success, -1 on failure + */ +int esp_dns_cleanup_tcp(esp_dns_handle_t handle); + +/** + * @brief Clean up UDP DNS module + * + * Releases resources allocated for the UDP DNS service. Validates the parameters, + * checks the protocol, and cleans up the DNS module. + * + * @param handle Pointer to the DNS handle to be cleaned up + * + * @return 0 on success, -1 on failure + */ +int esp_dns_cleanup_udp(esp_dns_handle_t handle); + +#ifdef __cplusplus +} +#endif