ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
dns_server_esp32_idf.cpp
Go to the documentation of this file.
2#if defined(USE_ESP32) && (defined(USE_CAPTIVE_PORTAL) || defined(USE_WEBSERVER_CAPTIVE))
7#include <lwip/sockets.h>
8#include <lwip/inet.h>
9
11
12ESPHOME_LOG_TAG(TAG, "web_server_base.dns");
13
14// DNS constants
15static constexpr uint16_t DNS_PORT = 53;
16static constexpr uint16_t DNS_QR_FLAG = 1 << 15;
17static constexpr uint16_t DNS_AA_FLAG = 1 << 10;
18static constexpr uint16_t DNS_OPCODE_MASK = 0x7800;
19static constexpr uint16_t DNS_QTYPE_A = 0x0001;
20static constexpr uint16_t DNS_QCLASS_IN = 0x0001;
21// Same as the Arduino DNSServer, so clients drop the AP's address soon after the portal closes
22static constexpr uint16_t DNS_ANSWER_TTL = 60;
23
24// DNS Header structure
25struct DNSHeader {
26 uint16_t id;
27 uint16_t flags;
28 uint16_t qd_count;
29 uint16_t an_count;
30 uint16_t ns_count;
31 uint16_t ar_count;
32} __attribute__((packed));
33
34// DNS Question structure
35struct DNSQuestion {
36 uint16_t type;
37 uint16_t dns_class;
38} __attribute__((packed));
39
40// DNS Answer structure
41struct DNSAnswer {
42 uint16_t ptr_offset;
43 uint16_t type;
44 uint16_t dns_class;
45 uint32_t ttl;
46 uint16_t addr_len;
47 uint32_t ip_addr;
48} __attribute__((packed));
49
51 this->server_ip_ = ip;
52#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
53 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
54 ESP_LOGV(TAG, "Starting DNS server on %s", ip.str_to(ip_buf));
55#endif
56
57 // Create loop-monitored UDP socket
58 this->socket_ = socket::socket_ip_loop_monitored(SOCK_DGRAM, IPPROTO_UDP).release();
59 if (this->socket_ == nullptr) {
60 ESP_LOGE(TAG, "Socket create failed");
61 return false;
62 }
63
64 // Set socket options
65 int enable = 1;
66 this->socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
67
68 // Bind to port 53
69 struct sockaddr_storage server_addr = {};
70 socklen_t addr_len = socket::set_sockaddr_any((struct sockaddr *) &server_addr, sizeof(server_addr), DNS_PORT);
71
72 int err = this->socket_->bind((struct sockaddr *) &server_addr, addr_len);
73 if (err != 0) {
74 ESP_LOGE(TAG, "Bind failed: %d", errno);
75 this->destroy_socket_();
76 return false;
77 }
78 ESP_LOGV(TAG, "Bound to port %d", DNS_PORT);
79 return true;
80}
81
83 this->destroy_socket_();
84 ESP_LOGV(TAG, "Stopped");
85}
86
88 // Process one request if socket is valid and data is available
89 if (this->socket_ == nullptr || !this->socket_->ready()) {
90 return;
91 }
92 struct sockaddr_in client_addr;
93 socklen_t client_addr_len = sizeof(client_addr);
94
95 // Receive DNS request using raw fd for recvfrom
96 int fd = this->socket_->get_fd();
97 if (fd < 0) {
98 return;
99 }
100
101 ssize_t len = recvfrom(fd, this->buffer_, sizeof(this->buffer_), MSG_DONTWAIT, (struct sockaddr *) &client_addr,
102 &client_addr_len);
103
104 if (len < 0) {
105 const int err = errno;
106 if (err != EAGAIN && err != EWOULDBLOCK && err != EINTR) {
107 ESP_LOGE(TAG, "recvfrom failed: %d", err);
108 }
109 return;
110 }
111
112 ESP_LOGVV(TAG, "Received %d bytes from %s:%d", len, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
113
114 if (len < static_cast<ssize_t>(sizeof(DNSHeader) + 1)) {
115 ESP_LOGV(TAG, "Request too short: %d", len);
116 return;
117 }
118
119 // Parse DNS header
120 DNSHeader *header = (DNSHeader *) this->buffer_;
121 uint16_t flags = ntohs(header->flags);
122 uint16_t qd_count = ntohs(header->qd_count);
123
124 // Check if it's a standard query
125 if ((flags & DNS_QR_FLAG) || (flags & DNS_OPCODE_MASK) || qd_count != 1) {
126 ESP_LOGV(TAG, "Not a standard query: flags=0x%04X, qd_count=%d", flags, qd_count);
127 return; // Not a standard query
128 }
129
130 // Parse domain name (we don't actually care about it - redirect everything)
131 uint8_t *ptr = this->buffer_ + sizeof(DNSHeader);
132 uint8_t *end = this->buffer_ + len;
133
134 while (ptr < end && *ptr != 0) {
135 uint8_t label_len = *ptr;
136 if (label_len > 63) { // Check for invalid label length
137 return;
138 }
139 // Check if we have room for this label plus the length byte
140 if (ptr + label_len + 1 > end) {
141 return; // Would overflow
142 }
143 ptr += label_len + 1;
144 }
145
146 // Check if we reached a proper null terminator
147 if (ptr >= end || *ptr != 0) {
148 return; // Name not terminated or truncated
149 }
150 ptr++; // Skip the null terminator
151
152 // Check we have room for the question
153 if (ptr + sizeof(DNSQuestion) > end) {
154 return; // Request truncated
155 }
156
157 // Parse DNS question
158 DNSQuestion *question = (DNSQuestion *) ptr;
159 uint16_t qtype = ntohs(question->type);
160 uint16_t qclass = ntohs(question->dns_class);
161
162 // We only handle A queries
163 if (qtype != DNS_QTYPE_A || qclass != DNS_QCLASS_IN) {
164 ESP_LOGV(TAG, "Not an A query: type=0x%04X, class=0x%04X", qtype, qclass);
165 return; // Not an A query
166 }
167
168 // Build DNS response by modifying the request in-place
169 header->flags = htons(DNS_QR_FLAG | DNS_AA_FLAG); // Response + Authoritative
170 header->an_count = htons(1); // One answer
171
172 // Add answer section after the question
173 size_t question_len = (ptr + sizeof(DNSQuestion)) - this->buffer_ - sizeof(DNSHeader);
174 size_t answer_offset = sizeof(DNSHeader) + question_len;
175
176 // Check if we have room for the answer
177 if (answer_offset + sizeof(DNSAnswer) > sizeof(this->buffer_)) {
178 ESP_LOGW(TAG, "Response too large");
179 return;
180 }
181
182 DNSAnswer *answer = (DNSAnswer *) (this->buffer_ + answer_offset);
183
184 // Pointer to name in question (offset from start of packet)
185 answer->ptr_offset = htons(0xC000 | sizeof(DNSHeader));
186 answer->type = htons(DNS_QTYPE_A);
187 answer->dns_class = htons(DNS_QCLASS_IN);
188 answer->ttl = htonl(DNS_ANSWER_TTL);
189 answer->addr_len = htons(4);
190
191 // Get the raw IP address
192 ip4_addr_t addr = this->server_ip_;
193 answer->ip_addr = addr.addr;
194
195 size_t response_len = answer_offset + sizeof(DNSAnswer);
196
197 // Send response
198 ssize_t sent =
199 this->socket_->sendto(this->buffer_, response_len, 0, (struct sockaddr *) &client_addr, client_addr_len);
200 if (sent < 0) {
201 ESP_LOGV(TAG, "Send failed: %d", errno);
202 } else {
203 ESP_LOGV(TAG, "Sent %d bytes", sent);
204 }
205}
206
207} // namespace esphome::web_server_base
208
209#endif // USE_ESP32 && (USE_CAPTIVE_PORTAL || USE_WEBSERVER_CAPTIVE)
bool ready() const
Check if the socket has buffered data ready to read.
Definition socket.h:106
int bind(const struct sockaddr *addr, socklen_t addrlen)
ssize_t sendto(const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen)
int setsockopt(int level, int optname, const void *optval, socklen_t optlen)
bool start(const network::IPAddress &ip)
Returns false when the socket could not be created or bound.
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
uint16_t flags
uint16_t addr_len
uint16_t qd_count
uint32_t socklen_t
Definition headers.h:109
__int64 ssize_t
Definition httplib.h:178
struct in_addr ip4_addr_t
Definition ip_address.h:23
socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port)
Set a sockaddr to the any address and specified port for the IP version used by socket_ip().
std::unique_ptr< ListenSocket > socket_ip_loop_monitored(int type, int protocol)
Definition socket.h:175
ESPHOME_LOG_TAG(TAG, "web_server_base.dns")
const void size_t len
Definition hal.h:68
static void uint32_t
char * str_to(char *buf) const
Definition ip_address.h:152
struct in_addr sin_addr
Definition headers.h:77
in_port_t sin_port
Definition headers.h:76
uint8_t end[39]
Definition sun_gtil2.cpp:17