dns_server.c 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /* Captive Portal Example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <sys/param.h>
  8. #include "esp_log.h"
  9. #include "esp_system.h"
  10. #include "esp_netif.h"
  11. #include "lwip/err.h"
  12. #include "lwip/sockets.h"
  13. #include "lwip/sys.h"
  14. #include "lwip/netdb.h"
  15. #define DNS_PORT (53)
  16. #define DNS_MAX_LEN (256)
  17. #define OPCODE_MASK (0x7800)
  18. #define QR_FLAG (1 << 7)
  19. #define QD_TYPE_A (0x0001)
  20. #define ANS_TTL_SEC (300)
  21. static const char *TAG = "example_dns_redirect_server";
  22. // DNS Header Packet
  23. typedef struct __attribute__((__packed__))
  24. {
  25. uint16_t id;
  26. uint16_t flags;
  27. uint16_t qd_count;
  28. uint16_t an_count;
  29. uint16_t ns_count;
  30. uint16_t ar_count;
  31. } dns_header_t;
  32. // DNS Question Packet
  33. typedef struct {
  34. uint16_t type;
  35. uint16_t class;
  36. } dns_question_t;
  37. // DNS Answer Packet
  38. typedef struct __attribute__((__packed__))
  39. {
  40. uint16_t ptr_offset;
  41. uint16_t type;
  42. uint16_t class;
  43. uint32_t ttl;
  44. uint16_t addr_len;
  45. uint32_t ip_addr;
  46. } dns_answer_t;
  47. /*
  48. Parse the name from the packet from the DNS name format to a regular .-seperated name
  49. returns the pointer to the next part of the packet
  50. */
  51. static char *parse_dns_name(char *raw_name, char *parsed_name, size_t parsed_name_max_len)
  52. {
  53. char *label = raw_name;
  54. char *name_itr = parsed_name;
  55. int name_len = 0;
  56. do {
  57. int sub_name_len = *label;
  58. // (len + 1) since we are adding a '.'
  59. name_len += (sub_name_len + 1);
  60. if (name_len > parsed_name_max_len) {
  61. return NULL;
  62. }
  63. // Copy the sub name that follows the the label
  64. memcpy(name_itr, label + 1, sub_name_len);
  65. name_itr[sub_name_len] = '.';
  66. name_itr += (sub_name_len + 1);
  67. label += sub_name_len + 1;
  68. } while (*label != 0);
  69. // Terminate the final string, replacing the last '.'
  70. parsed_name[name_len - 1] = '\0';
  71. // Return pointer to first char after the name
  72. return label + 1;
  73. }
  74. // Parses the DNS request and prepares a DNS response with the IP of the softAP
  75. static int parse_dns_request(char *req, size_t req_len, char *dns_reply, size_t dns_reply_max_len)
  76. {
  77. if (req_len > dns_reply_max_len) {
  78. return -1;
  79. }
  80. // Prepare the reply
  81. memset(dns_reply, 0, dns_reply_max_len);
  82. memcpy(dns_reply, req, req_len);
  83. // Endianess of NW packet different from chip
  84. dns_header_t *header = (dns_header_t *)dns_reply;
  85. ESP_LOGD(TAG, "DNS query with header id: 0x%X, flags: 0x%X, qd_count: %d",
  86. ntohs(header->id), ntohs(header->flags), ntohs(header->qd_count));
  87. // Not a standard query
  88. if ((header->flags & OPCODE_MASK) != 0) {
  89. return 0;
  90. }
  91. // Set question response flag
  92. header->flags |= QR_FLAG;
  93. uint16_t qd_count = ntohs(header->qd_count);
  94. header->an_count = htons(qd_count);
  95. int reply_len = qd_count * sizeof(dns_answer_t) + req_len;
  96. if (reply_len > dns_reply_max_len) {
  97. return -1;
  98. }
  99. // Pointer to current answer and question
  100. char *cur_ans_ptr = dns_reply + req_len;
  101. char *cur_qd_ptr = dns_reply + sizeof(dns_header_t);
  102. char name[128];
  103. // Respond to all questions with the ESP32's IP address
  104. for (int i = 0; i < qd_count; i++) {
  105. char *name_end_ptr = parse_dns_name(cur_qd_ptr, name, sizeof(name));
  106. if (name_end_ptr == NULL) {
  107. ESP_LOGE(TAG, "Failed to parse DNS question: %s", cur_qd_ptr);
  108. return -1;
  109. }
  110. dns_question_t *question = (dns_question_t *)(name_end_ptr);
  111. uint16_t qd_type = ntohs(question->type);
  112. uint16_t qd_class = ntohs(question->class);
  113. ESP_LOGD(TAG, "Received type: %d | Class: %d | Question for: %s", qd_type, qd_class, name);
  114. if (qd_type == QD_TYPE_A) {
  115. dns_answer_t *answer = (dns_answer_t *)cur_ans_ptr;
  116. answer->ptr_offset = htons(0xC000 | (cur_qd_ptr - dns_reply));
  117. answer->type = htons(qd_type);
  118. answer->class = htons(qd_class);
  119. answer->ttl = htonl(ANS_TTL_SEC);
  120. esp_netif_ip_info_t ip_info;
  121. esp_netif_get_ip_info(esp_netif_get_handle_from_ifkey("WIFI_AP_DEF"), &ip_info);
  122. ESP_LOGD(TAG, "Answer with PTR offset: 0x%X and IP 0x%X", ntohs(answer->ptr_offset), ip_info.ip.addr);
  123. answer->addr_len = htons(sizeof(ip_info.ip.addr));
  124. answer->ip_addr = ip_info.ip.addr;
  125. }
  126. }
  127. return reply_len;
  128. }
  129. /*
  130. Sets up a socket and listen for DNS queries,
  131. replies to all type A queries with the IP of the softAP
  132. */
  133. void dns_server_task(void *pvParameters)
  134. {
  135. char rx_buffer[128];
  136. char addr_str[128];
  137. int addr_family;
  138. int ip_protocol;
  139. while (1) {
  140. struct sockaddr_in dest_addr;
  141. dest_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  142. dest_addr.sin_family = AF_INET;
  143. dest_addr.sin_port = htons(DNS_PORT);
  144. addr_family = AF_INET;
  145. ip_protocol = IPPROTO_IP;
  146. inet_ntoa_r(dest_addr.sin_addr, addr_str, sizeof(addr_str) - 1);
  147. int sock = socket(addr_family, SOCK_DGRAM, ip_protocol);
  148. if (sock < 0) {
  149. ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
  150. break;
  151. }
  152. ESP_LOGI(TAG, "Socket created");
  153. int err = bind(sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
  154. if (err < 0) {
  155. ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno);
  156. }
  157. ESP_LOGI(TAG, "Socket bound, port %d", DNS_PORT);
  158. while (1) {
  159. ESP_LOGI(TAG, "Waiting for data");
  160. struct sockaddr_in6 source_addr; // Large enough for both IPv4 or IPv6
  161. socklen_t socklen = sizeof(source_addr);
  162. int len = recvfrom(sock, rx_buffer, sizeof(rx_buffer) - 1, 0, (struct sockaddr *)&source_addr, &socklen);
  163. // Error occurred during receiving
  164. if (len < 0) {
  165. ESP_LOGE(TAG, "recvfrom failed: errno %d", errno);
  166. close(sock);
  167. break;
  168. }
  169. // Data received
  170. else {
  171. // Get the sender's ip address as string
  172. if (source_addr.sin6_family == PF_INET) {
  173. inet_ntoa_r(((struct sockaddr_in *)&source_addr)->sin_addr.s_addr, addr_str, sizeof(addr_str) - 1);
  174. } else if (source_addr.sin6_family == PF_INET6) {
  175. inet6_ntoa_r(source_addr.sin6_addr, addr_str, sizeof(addr_str) - 1);
  176. }
  177. // Null-terminate whatever we received and treat like a string...
  178. rx_buffer[len] = 0;
  179. char reply[DNS_MAX_LEN];
  180. int reply_len = parse_dns_request(rx_buffer, len, reply, DNS_MAX_LEN);
  181. ESP_LOGI(TAG, "Received %d bytes from %s | DNS reply with len: %d", len, addr_str, reply_len);
  182. if (reply_len <= 0) {
  183. ESP_LOGE(TAG, "Failed to prepare a DNS reply");
  184. } else {
  185. int err = sendto(sock, reply, reply_len, 0, (struct sockaddr *)&source_addr, sizeof(source_addr));
  186. if (err < 0) {
  187. ESP_LOGE(TAG, "Error occurred during sending: errno %d", errno);
  188. break;
  189. }
  190. }
  191. }
  192. }
  193. if (sock != -1) {
  194. ESP_LOGE(TAG, "Shutting down socket");
  195. shutdown(sock, 0);
  196. close(sock);
  197. }
  198. }
  199. vTaskDelete(NULL);
  200. }
  201. void start_dns_server(void)
  202. {
  203. xTaskCreate(dns_server_task, "dns_server", 4096, NULL, 5, NULL);
  204. }