feat: DDP frame sync over UDP broadcast, DDP acks, DDP enable setting
- Driver acks each completed DDP frame; the test waits for the acks before broadcasting the sync. - Sync listener on UDP 4049: a frame is held until the next sync, then shown. - DDP pixels are shown at full brightness, ignoring the device brightness settings. - "DDP and sync receive on" setting (NVS, network API, web UI); off ignores DDP and sync packets. - ddp_test.py: finds devices on the subnet, drives them in lockstep at a fixed rate, runs animations. - /api/ddp reports sync counters for diagnosis. - Includes in-progress WebSocket, multi-driver web UI and Wi-Fi work from the same tree. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
47f4eba0d6
commit
4cd3bc7973
294 files changed
+48954
-301
No files matched your search
@@ -0,0 +1,16 @@
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
if(${IDF_TARGET} STREQUAL "linux")
|
||||
set(EXTRA_COMPONENT_DIRS "../../../../common_components/linux_compat")
|
||||
set(COMPONENTS main)
|
||||
endif()
|
||||
|
||||
project(mdns_host)
|
||||
|
||||
# Enable sanitizers only without console (we'd see some leaks on argtable when console exits)
|
||||
if(NOT CONFIG_TEST_CONSOLE AND CONFIG_IDF_TARGET_LINUX)
|
||||
idf_component_get_property(mdns mdns COMPONENT_LIB)
|
||||
target_link_options(${mdns} INTERFACE -fsanitize=address -fsanitize=undefined)
|
||||
endif()
|
||||
@@ -0,0 +1,33 @@
|
||||
# Setup dummy network interfaces
|
||||
|
||||
Note: Set two addresses so we could use one as source and another as destination
|
||||
```
|
||||
sudo ip link add eth2 type dummy
|
||||
sudo ip addr add 192.168.1.200/24 dev eth2
|
||||
sudo ip addr add 192.168.1.201/24 dev eth2
|
||||
sudo ip link set eth2 up
|
||||
sudo ifconfig eth2 multicast
|
||||
```
|
||||
|
||||
# Dig on a specified interface
|
||||
|
||||
```
|
||||
dig +short -b 192.168.1.200 -p 5353 @224.0.0.251 myesp.local
|
||||
```
|
||||
|
||||
or a reverse query:
|
||||
```
|
||||
dig +short -b 192.168.2.200 -p 5353 @224.0.0.251 -x 192.168.1.200
|
||||
```
|
||||
|
||||
# Run avahi to browse services
|
||||
|
||||
Avahi needs the netif to have the "multicast" flag set
|
||||
|
||||
```bash
|
||||
david@david-comp:~/esp/idf (feature/mdns_networking_socket)$ avahi-browse -a -r -p
|
||||
+;eth2;IPv6;myesp-service2;Web Site;local
|
||||
+;eth2;IPv4;myesp-service2;Web Site;local
|
||||
=;eth2;IPv6;myesp-service2;Web Site;local;myesp.local;192.168.1.200;80;"board=esp32" "u=user" "p=password"
|
||||
=;eth2;IPv4;myesp-service2;Web Site;local;myesp.local;192.168.1.200;80;"board=esp32" "u=user" "p=password"
|
||||
```
|
||||
@@ -0,0 +1,314 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
|
||||
# SPDX-License-Identifier: Unlicense OR CC0-1.0
|
||||
"""Mock Bonjour-style mDNS responder for browse host tests.
|
||||
|
||||
Default response order mimics Bonjour browse answers:
|
||||
Answer: PTR
|
||||
Additional: A, AAAA, SRV, TXT
|
||||
|
||||
Use ``--goodbye-after N`` to answer the first N browse queries normally and then
|
||||
reply with a standalone PTR TTL=0 (Bonjour service removal).
|
||||
|
||||
Use ``--unsolicited-goodbye-after N`` to answer N browse queries normally and then
|
||||
multicast an unsolicited PTR TTL=0 announcement (keeps the active browse item).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
|
||||
import dns.flags
|
||||
import dns.message
|
||||
import dns.name
|
||||
import dns.rdataclass
|
||||
import dns.rdatatype
|
||||
import dns.rrset
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MDNS_ADDR = '224.0.0.251'
|
||||
MDNS_PORT = 5353
|
||||
|
||||
DEFAULTS = {
|
||||
'service': '_v301test',
|
||||
'proto': '_tcp',
|
||||
'instance': 'v301instance',
|
||||
'hostname': 'v301host',
|
||||
'port': 8080,
|
||||
'ipv4': '192.168.1.100',
|
||||
'ipv6': 'fe80::1234:5678:9abc:def0',
|
||||
'txt': 'vdv301=test',
|
||||
}
|
||||
|
||||
|
||||
def _fqdn(*labels: str) -> str:
|
||||
return '.'.join(labels) + '.local.'
|
||||
|
||||
|
||||
def build_goodbye_response(
|
||||
query: dns.message.Message,
|
||||
*,
|
||||
service: str,
|
||||
proto: str,
|
||||
instance: str,
|
||||
) -> dns.message.Message:
|
||||
service_name = _fqdn(service, proto)
|
||||
instance_name = _fqdn(instance, service, proto)
|
||||
|
||||
response = dns.message.make_response(query)
|
||||
response.flags |= dns.flags.AA
|
||||
response.answer.append(
|
||||
dns.rrset.from_text(service_name, 0, dns.rdataclass.IN, dns.rdatatype.PTR, instance_name)
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
def build_unsolicited_goodbye(
|
||||
*,
|
||||
service: str,
|
||||
proto: str,
|
||||
instance: str,
|
||||
) -> dns.message.Message:
|
||||
"""Build a multicast goodbye announcement (QR+AA, no question section)."""
|
||||
service_name = _fqdn(service, proto)
|
||||
instance_name = _fqdn(instance, service, proto)
|
||||
|
||||
msg = dns.message.Message(id=0)
|
||||
msg.flags = dns.flags.QR | dns.flags.AA
|
||||
msg.answer.append(
|
||||
dns.rrset.from_text(service_name, 0, dns.rdataclass.IN, dns.rdatatype.PTR, instance_name)
|
||||
)
|
||||
return msg
|
||||
|
||||
|
||||
def build_ptr_response(
|
||||
query: dns.message.Message,
|
||||
*,
|
||||
service: str,
|
||||
proto: str,
|
||||
instance: str,
|
||||
hostname: str,
|
||||
port: int,
|
||||
ipv4: str,
|
||||
ipv6: str,
|
||||
txt: str,
|
||||
srv_first: bool,
|
||||
) -> dns.message.Message:
|
||||
service_name = _fqdn(service, proto)
|
||||
instance_name = _fqdn(instance, service, proto)
|
||||
host_name = _fqdn(hostname)
|
||||
|
||||
response = dns.message.make_response(query)
|
||||
response.flags |= dns.flags.AA
|
||||
|
||||
response.answer.append(
|
||||
dns.rrset.from_text(service_name, 120, dns.rdataclass.IN, dns.rdatatype.PTR, instance_name)
|
||||
)
|
||||
|
||||
a_rr = dns.rrset.from_text(host_name, 120, dns.rdataclass.IN, dns.rdatatype.A, ipv4)
|
||||
aaaa_rr = dns.rrset.from_text(host_name, 120, dns.rdataclass.IN, dns.rdatatype.AAAA, ipv6)
|
||||
srv_rr = dns.rrset.from_text(
|
||||
instance_name,
|
||||
120,
|
||||
dns.rdataclass.IN,
|
||||
dns.rdatatype.SRV,
|
||||
f'0 0 {port} {host_name}',
|
||||
)
|
||||
txt_rr = dns.rrset.from_text(instance_name, 120, dns.rdataclass.IN, dns.rdatatype.TXT, txt)
|
||||
|
||||
if srv_first:
|
||||
response.additional = [srv_rr, txt_rr, a_rr, aaaa_rr]
|
||||
else:
|
||||
response.additional = [a_rr, aaaa_rr, srv_rr, txt_rr]
|
||||
|
||||
return response
|
||||
|
||||
|
||||
def create_socket(interface: str | None) -> socket.socket:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
try:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
|
||||
if interface:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface.encode() + b'\0')
|
||||
|
||||
sock.bind(('', MDNS_PORT))
|
||||
|
||||
membership = struct.pack(
|
||||
'=4s4s',
|
||||
socket.inet_aton(MDNS_ADDR),
|
||||
socket.inet_aton('0.0.0.0'),
|
||||
)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership)
|
||||
return sock
|
||||
|
||||
|
||||
def query_matches(query: dns.message.Message, service: str, proto: str) -> bool:
|
||||
target = dns.name.from_text(_fqdn(service, proto))
|
||||
for question in query.question:
|
||||
if question.rdtype != dns.rdatatype.PTR:
|
||||
continue
|
||||
if question.name == target:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def send_mdns_response(sock: socket.socket, payload: bytes, source: tuple[str, int]) -> None:
|
||||
if source[1] == MDNS_PORT:
|
||||
destination = (MDNS_ADDR, MDNS_PORT)
|
||||
else:
|
||||
destination = source
|
||||
sock.sendto(payload, destination)
|
||||
logger.info('Sent %d byte response to %s (query source %s:%d)', len(payload), destination, *source)
|
||||
|
||||
|
||||
def send_mdns_multicast(sock: socket.socket, payload: bytes) -> None:
|
||||
destination = (MDNS_ADDR, MDNS_PORT)
|
||||
sock.sendto(payload, destination)
|
||||
logger.info('Sent %d byte multicast announcement to %s', len(payload), destination)
|
||||
|
||||
|
||||
def maybe_send_unsolicited_goodbye(sock: socket.socket, args: argparse.Namespace, response_count: int) -> bool:
|
||||
"""After N normal answers, multicast one unsolicited PTR TTL=0. Returns True if sent."""
|
||||
if args.unsolicited_goodbye_after < 0 or response_count != args.unsolicited_goodbye_after:
|
||||
return False
|
||||
if args.unsolicited_goodbye_delay > 0:
|
||||
time.sleep(args.unsolicited_goodbye_delay)
|
||||
goodbye = build_unsolicited_goodbye(
|
||||
service=args.service,
|
||||
proto=args.proto,
|
||||
instance=args.instance,
|
||||
)
|
||||
send_mdns_multicast(sock, goodbye.to_wire())
|
||||
logger.info('Multicasted unsolicited PTR goodbye (TTL=0)')
|
||||
return True
|
||||
|
||||
|
||||
def serve(args: argparse.Namespace) -> None:
|
||||
sock = create_socket(args.interface)
|
||||
order = 'SRV, TXT, A, AAAA' if args.srv_first else 'A, AAAA, SRV, TXT'
|
||||
logger.info(
|
||||
'Listening on %s:%d (%s) for PTR %s.%s.local; additional order: %s; '
|
||||
'goodbye-after=%s; unsolicited-goodbye-after=%s',
|
||||
MDNS_ADDR,
|
||||
MDNS_PORT,
|
||||
args.interface or 'all interfaces',
|
||||
args.service,
|
||||
args.proto,
|
||||
order,
|
||||
args.goodbye_after,
|
||||
args.unsolicited_goodbye_after,
|
||||
)
|
||||
|
||||
response_count = 0
|
||||
unsolicited_goodbye_sent = False
|
||||
while True:
|
||||
try:
|
||||
data, source = sock.recvfrom(9000)
|
||||
except KeyboardInterrupt:
|
||||
logger.info('Stopping responder')
|
||||
break
|
||||
|
||||
try:
|
||||
query = dns.message.from_wire(data)
|
||||
except Exception as exc: # noqa: BLE001 - ignore malformed packets
|
||||
logger.debug('Ignoring non-DNS payload from %s:%d (%s)', source[0], source[1], exc)
|
||||
continue
|
||||
|
||||
if query.flags & dns.flags.QR:
|
||||
continue
|
||||
if not query_matches(query, args.service, args.proto):
|
||||
continue
|
||||
|
||||
if args.goodbye_after >= 0 and response_count >= args.goodbye_after:
|
||||
response = build_goodbye_response(
|
||||
query,
|
||||
service=args.service,
|
||||
proto=args.proto,
|
||||
instance=args.instance,
|
||||
)
|
||||
logger.info('Answered PTR goodbye (TTL=0) from %s:%d', source[0], source[1])
|
||||
else:
|
||||
response = build_ptr_response(
|
||||
query,
|
||||
service=args.service,
|
||||
proto=args.proto,
|
||||
instance=args.instance,
|
||||
hostname=args.hostname,
|
||||
port=args.port,
|
||||
ipv4=args.ipv4,
|
||||
ipv6=args.ipv6,
|
||||
txt=args.txt,
|
||||
srv_first=args.srv_first,
|
||||
)
|
||||
logger.info('Answered PTR browse from %s:%d', source[0], source[1])
|
||||
|
||||
send_mdns_response(sock, response.to_wire(), source)
|
||||
response_count += 1
|
||||
|
||||
if not unsolicited_goodbye_sent:
|
||||
unsolicited_goodbye_sent = maybe_send_unsolicited_goodbye(sock, args, response_count)
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--interface', default='eth0', help='Network interface for mDNS (default: eth0)')
|
||||
parser.add_argument('--service', default=DEFAULTS['service'], help='Service type without domain')
|
||||
parser.add_argument('--proto', default=DEFAULTS['proto'], help='Protocol (_tcp/_udp)')
|
||||
parser.add_argument('--instance', default=DEFAULTS['instance'], help='Service instance name')
|
||||
parser.add_argument('--hostname', default=DEFAULTS['hostname'], help='SRV target host label')
|
||||
parser.add_argument('--port', type=int, default=DEFAULTS['port'], help='SRV port')
|
||||
parser.add_argument('--ipv4', default=DEFAULTS['ipv4'], help='A record address')
|
||||
parser.add_argument('--ipv6', default=DEFAULTS['ipv6'], help='AAAA record address')
|
||||
parser.add_argument('--txt', default=DEFAULTS['txt'], help='TXT record payload')
|
||||
parser.add_argument(
|
||||
'--srv-first',
|
||||
action='store_true',
|
||||
help='Place SRV/TXT before A/AAAA (control case where browse gets addresses)',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--goodbye-after',
|
||||
type=int,
|
||||
default=-1,
|
||||
help='After N normal browse responses, reply with PTR TTL=0 only (-1 disables)',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--unsolicited-goodbye-after',
|
||||
type=int,
|
||||
default=-1,
|
||||
help='After N normal browse responses, multicast one unsolicited PTR TTL=0 (-1 disables)',
|
||||
)
|
||||
parser.add_argument(
|
||||
'--unsolicited-goodbye-delay',
|
||||
type=float,
|
||||
default=0.5,
|
||||
help='Seconds to wait after the Nth normal response before multicasting goodbye',
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_args(argv)
|
||||
try:
|
||||
serve(args)
|
||||
except PermissionError:
|
||||
logger.error('Binding to port %d requires root or CAP_NET_BIND_SERVICE', MDNS_PORT)
|
||||
return 1
|
||||
except OSError as exc:
|
||||
logger.error('Failed to start responder: %s', exc)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
idf_build_get_property(idf_target IDF_TARGET)
|
||||
if(${IDF_TARGET} STREQUAL "linux")
|
||||
idf_component_register(SRCS esp_netif_linux.c
|
||||
INCLUDE_DIRS include $ENV{IDF_PATH}/components/esp_netif/include
|
||||
REQUIRES esp_event)
|
||||
else()
|
||||
idf_component_register()
|
||||
endif()
|
||||
@@ -0,0 +1,15 @@
|
||||
menu "LWIP-MOCK-CONFIG"
|
||||
|
||||
config LWIP_IPV6
|
||||
bool "Enable IPv6"
|
||||
default y
|
||||
help
|
||||
Enable/disable IPv6
|
||||
|
||||
config LWIP_IPV4
|
||||
bool "Enable IPv4"
|
||||
default y
|
||||
help
|
||||
Enable/disable IPv4
|
||||
|
||||
endmenu
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include<stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "esp_netif.h"
|
||||
#include "esp_err.h"
|
||||
#include <string.h> //strlen
|
||||
#include <sys/socket.h>
|
||||
#include <arpa/inet.h> //inet_addr
|
||||
#include <sys/types.h>
|
||||
#include <ifaddrs.h>
|
||||
#include <net/if.h>
|
||||
#include "esp_netif_types.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
#define MAX_NETIFS 4
|
||||
|
||||
static const char *TAG = "esp_netif_linux";
|
||||
|
||||
static esp_netif_t *s_netif_list[MAX_NETIFS] = { 0 };
|
||||
|
||||
struct esp_netif_obj {
|
||||
const char *if_key;
|
||||
const char *if_desc;
|
||||
};
|
||||
|
||||
esp_netif_t *esp_netif_get_handle_from_ifkey(const char *if_key)
|
||||
{
|
||||
for (int i = 0; i < MAX_NETIFS; ++i) {
|
||||
if (s_netif_list[i] && strcmp(s_netif_list[i]->if_key, if_key) == 0) {
|
||||
return s_netif_list[i];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
esp_err_t esp_netif_get_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info)
|
||||
{
|
||||
if (esp_netif == NULL) {
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
struct ifaddrs *addrs, *tmp;
|
||||
getifaddrs(&addrs);
|
||||
tmp = addrs;
|
||||
|
||||
while (tmp) {
|
||||
if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) {
|
||||
char addr[20];
|
||||
struct sockaddr_in *pAddr = (struct sockaddr_in *) tmp->ifa_addr;
|
||||
inet_ntop(AF_INET, &pAddr->sin_addr, addr, sizeof(addr));
|
||||
if (strcmp(esp_netif->if_desc, tmp->ifa_name) == 0) {
|
||||
ESP_LOGD(TAG, "AF_INET4: %s: %s\n", tmp->ifa_name, addr);
|
||||
memcpy(&ip_info->ip.addr, &pAddr->sin_addr, 4);
|
||||
}
|
||||
}
|
||||
tmp = tmp->ifa_next;
|
||||
}
|
||||
freeifaddrs(addrs);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t esp_netif_dhcpc_get_status(esp_netif_t *esp_netif, esp_netif_dhcp_status_t *status)
|
||||
{
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
int esp_netif_get_all_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[])
|
||||
{
|
||||
if (esp_netif == NULL) {
|
||||
return 0;
|
||||
}
|
||||
struct ifaddrs *addrs, *tmp;
|
||||
int addr_count = 0;
|
||||
getifaddrs(&addrs);
|
||||
tmp = addrs;
|
||||
|
||||
while (tmp) {
|
||||
if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET6) {
|
||||
struct sockaddr_in6 *pAddr = (struct sockaddr_in6 *)tmp->ifa_addr;
|
||||
if (strcmp(esp_netif->if_desc, tmp->ifa_name) == 0) {
|
||||
memcpy(&if_ip6[addr_count++], &pAddr->sin6_addr, 4 * 4);
|
||||
}
|
||||
}
|
||||
tmp = tmp->ifa_next;
|
||||
}
|
||||
|
||||
freeifaddrs(addrs);
|
||||
return addr_count;
|
||||
}
|
||||
|
||||
esp_err_t esp_netif_get_ip6_linklocal(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip6)
|
||||
{
|
||||
if (esp_netif == NULL) {
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
struct ifaddrs *addrs, *tmp;
|
||||
getifaddrs(&addrs);
|
||||
tmp = addrs;
|
||||
|
||||
while (tmp) {
|
||||
if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET6) {
|
||||
char addr[64];
|
||||
struct sockaddr_in6 *pAddr = (struct sockaddr_in6 *)tmp->ifa_addr;
|
||||
inet_ntop(AF_INET6, &pAddr->sin6_addr, addr, sizeof(addr));
|
||||
if (strcmp(esp_netif->if_desc, tmp->ifa_name) == 0) {
|
||||
ESP_LOGD(TAG, "AF_INET6: %s: %s\n", tmp->ifa_name, addr);
|
||||
memcpy(if_ip6->addr, &pAddr->sin6_addr, 4 * 4);
|
||||
break;
|
||||
}
|
||||
}
|
||||
tmp = tmp->ifa_next;
|
||||
}
|
||||
|
||||
freeifaddrs(addrs);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
|
||||
int esp_netif_get_netif_impl_index(esp_netif_t *esp_netif)
|
||||
{
|
||||
if (esp_netif == NULL) {
|
||||
return -1;
|
||||
}
|
||||
uint32_t interfaceIndex = if_nametoindex(esp_netif->if_desc);
|
||||
return interfaceIndex;
|
||||
}
|
||||
|
||||
esp_err_t esp_netif_get_netif_impl_name(esp_netif_t *esp_netif, char *name)
|
||||
{
|
||||
if (esp_netif == NULL) {
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
strcpy(name, esp_netif->if_desc);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
const char *esp_netif_get_desc(esp_netif_t *esp_netif)
|
||||
{
|
||||
if (esp_netif == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
return esp_netif->if_desc;
|
||||
}
|
||||
|
||||
esp_netif_t *esp_netif_new(const esp_netif_config_t *config)
|
||||
{
|
||||
if (esp_netif_get_handle_from_ifkey(config->base->if_key)) {
|
||||
return NULL;
|
||||
}
|
||||
esp_netif_t *netif = calloc(1, sizeof(struct esp_netif_obj));
|
||||
if (netif) {
|
||||
netif->if_desc = config->base->if_desc;
|
||||
netif->if_key = config->base->if_key;
|
||||
}
|
||||
|
||||
for (int i = 0; i < MAX_NETIFS; ++i) {
|
||||
if (s_netif_list[i] == NULL) {
|
||||
s_netif_list[i] = netif;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return netif;
|
||||
}
|
||||
|
||||
void esp_netif_destroy(esp_netif_t *esp_netif)
|
||||
{
|
||||
for (int i = 0; i < MAX_NETIFS; ++i) {
|
||||
if (s_netif_list[i] == esp_netif) {
|
||||
s_netif_list[i] = NULL;
|
||||
break;
|
||||
}
|
||||
}
|
||||
free(esp_netif);
|
||||
}
|
||||
|
||||
const char *esp_netif_get_ifkey(esp_netif_t *esp_netif)
|
||||
{
|
||||
return esp_netif->if_key;
|
||||
}
|
||||
|
||||
esp_err_t esp_netif_str_to_ip4(const char *src, esp_ip4_addr_t *dst)
|
||||
{
|
||||
if (src == NULL || dst == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
struct in_addr addr;
|
||||
if (inet_pton(AF_INET, src, &addr) != 1) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
dst->addr = addr.s_addr;
|
||||
return ESP_OK;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
#include "esp_event.h"
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include_next "endian.h"
|
||||
@@ -0,0 +1,178 @@
|
||||
# SPDX-FileCopyrightText: 2024-2025 Espressif Systems (Shanghai) CO LTD
|
||||
# SPDX-License-Identifier: Unlicense OR CC0-1.0
|
||||
import logging
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
|
||||
import dns.message
|
||||
import dns.query
|
||||
import dns.rdataclass
|
||||
import dns.rdatatype
|
||||
import dns.resolver
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DnsPythonWrapper:
|
||||
def __init__(self, server='224.0.0.251', port=5353, retries=3):
|
||||
self.server = server
|
||||
self.port = port
|
||||
self.retries = retries
|
||||
|
||||
def send_and_receive_query(self, query, timeout=3):
|
||||
logger.info(f'Sending DNS query to {self.server}:{self.port}')
|
||||
try:
|
||||
# Create a UDP socket
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||
sock.settimeout(timeout)
|
||||
|
||||
# Send the DNS query
|
||||
query_data = query.to_wire()
|
||||
sock.sendto(query_data, (self.server, self.port))
|
||||
|
||||
# Receive the DNS response
|
||||
response_data, _ = sock.recvfrom(512) # 512 bytes is the typical size for a DNS response
|
||||
|
||||
# Parse the response
|
||||
response = dns.message.from_wire(response_data)
|
||||
|
||||
return response
|
||||
|
||||
except socket.timeout as e:
|
||||
logger.warning(f'DNS query timed out: {e}')
|
||||
return None
|
||||
except dns.exception.DNSException as e:
|
||||
logger.error(f'DNS query failed: {e}')
|
||||
return None
|
||||
|
||||
def run_query(self, name, query_type='PTR', timeout=3):
|
||||
logger.info(f'Running DNS query for {name} with type {query_type}')
|
||||
query = dns.message.make_query(name, dns.rdatatype.from_text(query_type), dns.rdataclass.IN)
|
||||
|
||||
# Print the DNS question section
|
||||
logger.info(f'DNS question section: {query.question}')
|
||||
|
||||
# Send and receive the DNS query
|
||||
response = None
|
||||
for attempt in range(1, self.retries + 1):
|
||||
logger.info(f'Attempt {attempt}/{self.retries}')
|
||||
response = self.send_and_receive_query(query, timeout)
|
||||
if response:
|
||||
break
|
||||
|
||||
if response:
|
||||
logger.info(f'DNS query response:\n{response}')
|
||||
else:
|
||||
logger.warning('No response received or response was invalid.')
|
||||
|
||||
return response
|
||||
|
||||
def parse_answer_section(self, response, query_type):
|
||||
answers = []
|
||||
if response:
|
||||
for answer in response.answer:
|
||||
if dns.rdatatype.to_text(answer.rdtype) == query_type:
|
||||
for item in answer.items:
|
||||
full_answer = (
|
||||
f'{answer.name} {answer.ttl} '
|
||||
f'{dns.rdataclass.to_text(answer.rdclass)} '
|
||||
f'{dns.rdatatype.to_text(answer.rdtype)} '
|
||||
f'{item.to_text()}'
|
||||
)
|
||||
answers.append(full_answer)
|
||||
return answers
|
||||
|
||||
def check_record(self, name, query_type, expected=True, expect=None):
|
||||
output = self.run_query(name, query_type=query_type)
|
||||
answers = self.parse_answer_section(output, query_type)
|
||||
logger.info(f'answers: {answers}')
|
||||
if expect is None:
|
||||
expect = name
|
||||
if expected:
|
||||
assert any(expect in answer for answer in answers), f"Expected record '{expect}' not in answer section"
|
||||
else:
|
||||
assert not any(expect in answer for answer in answers), f"Unexpected record '{expect}' found in answer section"
|
||||
|
||||
def parse_section(self, response, section: str, rdtype_text: str):
|
||||
"""Parse a specific response section (answer, authority, additional) for given rdtype.
|
||||
|
||||
Returns list of textual records for that rdtype.
|
||||
"""
|
||||
out = []
|
||||
if not response:
|
||||
return out
|
||||
rrsets = []
|
||||
if section == 'answer':
|
||||
rrsets = response.answer
|
||||
elif section == 'authority':
|
||||
rrsets = response.authority
|
||||
elif section == 'additional':
|
||||
rrsets = response.additional
|
||||
else:
|
||||
raise ValueError('invalid section')
|
||||
for rr in rrsets:
|
||||
if dns.rdatatype.to_text(rr.rdtype) != rdtype_text:
|
||||
continue
|
||||
for item in rr.items:
|
||||
full = (
|
||||
f'{rr.name} {rr.ttl} '
|
||||
f'{dns.rdataclass.to_text(rr.rdclass)} '
|
||||
f'{dns.rdatatype.to_text(rr.rdtype)} '
|
||||
f'{item.to_text()}'
|
||||
)
|
||||
out.append(full)
|
||||
return out
|
||||
|
||||
def check_additional(self, response, rdtype_text: str, owner_contains: str, expected: bool = True, expect_substr: str | None = None):
|
||||
"""Check Additional section for an RR of type rdtype_text whose owner includes owner_contains.
|
||||
|
||||
If expect_substr is provided, also require it to appear in the textual RR.
|
||||
"""
|
||||
records = self.parse_section(response, 'additional', rdtype_text)
|
||||
logger.info(f'additional({rdtype_text}): {records}')
|
||||
|
||||
def _matches(line: str) -> bool:
|
||||
in_owner = owner_contains in line
|
||||
has_val = (expect_substr in line) if expect_substr else True
|
||||
return in_owner and has_val
|
||||
found = any(_matches(r) for r in records)
|
||||
if expected:
|
||||
assert found, f"Expected {rdtype_text} for {owner_contains} in Additional not found"
|
||||
else:
|
||||
assert not found, f"Unexpected {rdtype_text} for {owner_contains} found in Additional"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) < 3:
|
||||
print('Usage: python dns_fixture.py <query_type> <name>')
|
||||
sys.exit(1)
|
||||
|
||||
query_type = sys.argv[1]
|
||||
name = sys.argv[2]
|
||||
ip_only = len(sys.argv) > 3 and sys.argv[3] == '--ip_only'
|
||||
if ip_only:
|
||||
logger.setLevel(logging.WARNING)
|
||||
|
||||
dns_wrapper = DnsPythonWrapper()
|
||||
if query_type == 'X' and '.' in name:
|
||||
# Sends an IPv4 reverse query
|
||||
reversed_ip = '.'.join(reversed(name.split('.')))
|
||||
name = f'{reversed_ip}.in-addr.arpa'
|
||||
query_type = 'PTR'
|
||||
response = dns_wrapper.run_query(name, query_type=query_type)
|
||||
answers = dns_wrapper.parse_answer_section(response, query_type)
|
||||
|
||||
if answers:
|
||||
for answer in answers:
|
||||
logger.info(f'DNS query response: {answer}')
|
||||
if ip_only:
|
||||
ipv4_pattern = re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b')
|
||||
ipv4_addresses = ipv4_pattern.findall(answer)
|
||||
if ipv4_addresses:
|
||||
print(f"{', '.join(ipv4_addresses)}")
|
||||
else:
|
||||
logger.info(f'No response for {name} with query type {query_type}')
|
||||
exit(9) # Same as dig timeout
|
||||
@@ -0,0 +1,4 @@
|
||||
idf_component_register(SRCS "main.c"
|
||||
INCLUDE_DIRS
|
||||
"."
|
||||
REQUIRES mdns console nvs_flash)
|
||||
@@ -0,0 +1,21 @@
|
||||
menu "Test Configuration"
|
||||
|
||||
config TEST_HOSTNAME
|
||||
string "mDNS Hostname"
|
||||
default "esp32-mdns"
|
||||
help
|
||||
mDNS Hostname for example to use
|
||||
|
||||
config TEST_NETIF_NAME
|
||||
string "Network interface name"
|
||||
default "eth2"
|
||||
help
|
||||
Name/ID if the network interface on which we run the mDNS host test
|
||||
|
||||
config TEST_CONSOLE
|
||||
bool "Start console"
|
||||
default n
|
||||
help
|
||||
Test uses esp_console for interactive testing.
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,7 @@
|
||||
dependencies:
|
||||
idf: ">=5.0"
|
||||
espressif/mdns:
|
||||
version: "^1.0.0"
|
||||
override_path: "../../.."
|
||||
protocol_examples_common:
|
||||
path: ${IDF_PATH}/examples/common_components/protocol_examples_common
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Unlicense OR CC0-1.0
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "esp_idf_version.h"
|
||||
#include "esp_log.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_console.h"
|
||||
#include "mdns.h"
|
||||
#include "mdns_console.h"
|
||||
|
||||
static const char *TAG = "mdns-test";
|
||||
|
||||
static void mdns_test_app(esp_netif_t *interface);
|
||||
|
||||
#ifdef CONFIG_TEST_CONSOLE
|
||||
static EventGroupHandle_t s_exit_signal = NULL;
|
||||
|
||||
static int exit_console(int argc, char **argv)
|
||||
{
|
||||
#ifdef CONFIG_IDF_TARGET_LINUX
|
||||
/* Host tests do not need graceful REPL teardown; exit hard so leftover
|
||||
* console_repl / linenoise threads cannot keep the process alive. */
|
||||
ESP_LOGI(TAG, "Exit");
|
||||
exit(0);
|
||||
#else
|
||||
xEventGroupSetBits(s_exit_signal, 1);
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
#else
|
||||
static void query_mdns_host(const char *host_name)
|
||||
{
|
||||
ESP_LOGI(TAG, "Query A: %s.local", host_name);
|
||||
|
||||
struct esp_ip4_addr addr;
|
||||
addr.addr = 0;
|
||||
|
||||
esp_err_t err = mdns_query_a(host_name, 2000, &addr);
|
||||
if (err) {
|
||||
if (err == ESP_ERR_NOT_FOUND) {
|
||||
ESP_LOGW(TAG, "%x: Host was not found!", (err));
|
||||
return;
|
||||
}
|
||||
ESP_LOGE(TAG, "Query Failed: %x", (err));
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Query A: %s.local resolved to: " IPSTR, host_name, IP2STR(&addr));
|
||||
}
|
||||
#endif // TEST_CONSOLE
|
||||
|
||||
#ifndef CONFIG_IDF_TARGET_LINUX
|
||||
#include "protocol_examples_common.h"
|
||||
#include "esp_event.h"
|
||||
#include "nvs_flash.h"
|
||||
|
||||
/**
|
||||
* @brief This is an entry point for the real target device,
|
||||
* need to init few components and connect to a network interface
|
||||
*/
|
||||
void app_main(void)
|
||||
{
|
||||
ESP_ERROR_CHECK(nvs_flash_init());
|
||||
ESP_ERROR_CHECK(esp_netif_init());
|
||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||
ESP_ERROR_CHECK(example_connect());
|
||||
|
||||
mdns_test_app(EXAMPLE_INTERFACE);
|
||||
|
||||
ESP_ERROR_CHECK(example_disconnect());
|
||||
}
|
||||
#else
|
||||
|
||||
/**
|
||||
* @brief This is an entry point for the linux target (simulator on host)
|
||||
* need to create a dummy WiFi station and use it as mdns network interface
|
||||
*/
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
const esp_netif_inherent_config_t base_cg = { .if_key = "WIFI_STA_DEF", .if_desc = CONFIG_TEST_NETIF_NAME };
|
||||
esp_netif_config_t cfg = { .base = &base_cg };
|
||||
esp_netif_t *sta = esp_netif_new(&cfg);
|
||||
|
||||
mdns_test_app(sta);
|
||||
|
||||
esp_netif_destroy(sta);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
static void mdns_test_app(esp_netif_t *interface)
|
||||
{
|
||||
ESP_ERROR_CHECK(mdns_init());
|
||||
ESP_ERROR_CHECK(mdns_hostname_set(CONFIG_TEST_HOSTNAME));
|
||||
ESP_LOGI(TAG, "mdns hostname set to: [%s]", CONFIG_TEST_HOSTNAME);
|
||||
ESP_ERROR_CHECK(mdns_register_netif(interface));
|
||||
ESP_ERROR_CHECK(mdns_netif_action(interface, MDNS_EVENT_ENABLE_IP4 /*| MDNS_EVENT_ENABLE_IP6 */ | MDNS_EVENT_IP4_REVERSE_LOOKUP | MDNS_EVENT_IP6_REVERSE_LOOKUP));
|
||||
// Query _services._dns-sd._udp to discover available service types
|
||||
mdns_result_t *results = NULL;
|
||||
esp_err_t err = mdns_query_ptr("_services._dns-sd", "_udp", 2000, 1, &results);
|
||||
if (err) {
|
||||
ESP_LOGE(TAG, "Query for _services._dns-sd._udp failed: 0x%x", err);
|
||||
}
|
||||
for (mdns_result_t *r = results; r; r = r->next) {
|
||||
ESP_LOGI(TAG, "Discovered service: %s.%s",
|
||||
r->service_type ? r->service_type : "?",
|
||||
r->proto ? r->proto : "?");
|
||||
}
|
||||
mdns_query_results_free(results);
|
||||
|
||||
#ifdef CONFIG_TEST_CONSOLE
|
||||
esp_console_repl_t *repl = NULL;
|
||||
esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
|
||||
s_exit_signal = xEventGroupCreate();
|
||||
|
||||
repl_config.prompt = "mdns>";
|
||||
// init console REPL environment
|
||||
#if CONFIG_IDF_TARGET_LINUX && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 1, 0)
|
||||
ESP_ERROR_CHECK(esp_console_new_repl_stdio(&repl_config, &repl));
|
||||
#else
|
||||
esp_console_dev_uart_config_t uart_config = ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_console_new_repl_uart(&uart_config, &repl_config, &repl));
|
||||
#endif
|
||||
|
||||
const esp_console_cmd_t cmd_exit = {
|
||||
.command = "exit",
|
||||
.help = "exit mDNS console application",
|
||||
.hint = NULL,
|
||||
.func = exit_console,
|
||||
.argtable = NULL
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd_exit));
|
||||
mdns_console_register();
|
||||
ESP_ERROR_CHECK(esp_console_start_repl(repl));
|
||||
xEventGroupWaitBits(s_exit_signal, 1, pdTRUE, pdFALSE, portMAX_DELAY);
|
||||
repl->del(repl);
|
||||
#else
|
||||
vTaskDelay(pdMS_TO_TICKS(10000));
|
||||
query_mdns_host("david-work");
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
#endif
|
||||
mdns_free();
|
||||
ESP_LOGI(TAG, "Exit");
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
# SPDX-FileCopyrightText: 2024-2026 Espressif Systems (Shanghai) CO LTD
|
||||
# SPDX-License-Identifier: Unlicense OR CC0-1.0
|
||||
import logging
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pexpect
|
||||
import pytest
|
||||
from bonjour_order_responder import DEFAULTS
|
||||
from dnsfixture import DnsPythonWrapper
|
||||
from querier_responder import DEFAULTS as QUERIER_DEFAULTS
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
ipv6_enabled = False
|
||||
|
||||
|
||||
def _console_line(label: str, value: str) -> str:
|
||||
"""Build a line as printed by mdns_print_results (avoids flake8 E203 on f'LABEL : {x}')."""
|
||||
return label + value
|
||||
|
||||
|
||||
class MdnsConsole:
|
||||
def __init__(self, command):
|
||||
self.process = pexpect.spawn(command, encoding='utf-8')
|
||||
self.process.logfile = open('mdns_interaction.log', 'w') # Log all interactions
|
||||
self.process.expect('mdns> ', timeout=10)
|
||||
|
||||
def send_input(self, input_data):
|
||||
logger.info(f'Sending to stdin: {input_data}')
|
||||
self.process.sendline(input_data)
|
||||
|
||||
def get_output(self, expected_data):
|
||||
logger.info(f'Expecting: {expected_data}')
|
||||
self.process.expect(expected_data, timeout=10)
|
||||
output = self.process.before.strip()
|
||||
logger.info(f'Received from stdout: {output}')
|
||||
return output
|
||||
|
||||
def wait_for_output(self, expected_data, timeout=10):
|
||||
logger.info(f'Waiting for: {expected_data}')
|
||||
self.process.expect(expected_data, timeout=timeout)
|
||||
output = (self.process.before or '') + (self.process.after or '')
|
||||
logger.info(f'Captured output while waiting: {output}')
|
||||
return output
|
||||
|
||||
def wait_for_browse_result(self, timeout=10):
|
||||
"""Wait until browse notifier printed the full result (A is last required field)."""
|
||||
return self.wait_for_output(_console_line('A : ', DEFAULTS['ipv4']), timeout=timeout)
|
||||
|
||||
def wait_for_browse_goodbye(self, timeout=10):
|
||||
"""Wait for Bonjour-style PTR TTL=0 removal notification (interface line then PTR)."""
|
||||
self.wait_for_output('TTL: 0', timeout=timeout)
|
||||
return self.wait_for_output(_console_line('PTR : ', DEFAULTS['instance']), timeout=timeout)
|
||||
|
||||
def terminate(self):
|
||||
self.send_input('exit')
|
||||
self.get_output('Exit')
|
||||
self.process.wait()
|
||||
self.process.close()
|
||||
assert self.process.exitstatus == 0
|
||||
|
||||
|
||||
def _bonjour_responder_cmd(
|
||||
srv_first: bool = False,
|
||||
goodbye_after: int = -1,
|
||||
unsolicited_goodbye_after: int = -1,
|
||||
) -> list[str]:
|
||||
cmd = [
|
||||
sys.executable,
|
||||
str(Path(__file__).with_name('bonjour_order_responder.py')),
|
||||
'--interface',
|
||||
'eth0',
|
||||
'--service',
|
||||
DEFAULTS['service'],
|
||||
'--proto',
|
||||
DEFAULTS['proto'],
|
||||
]
|
||||
if srv_first:
|
||||
cmd.append('--srv-first')
|
||||
if goodbye_after >= 0:
|
||||
cmd.extend(['--goodbye-after', str(goodbye_after)])
|
||||
if unsolicited_goodbye_after >= 0:
|
||||
cmd.extend(['--unsolicited-goodbye-after', str(unsolicited_goodbye_after)])
|
||||
return cmd
|
||||
|
||||
|
||||
def _run_bonjour_responder(
|
||||
*,
|
||||
srv_first: bool = False,
|
||||
goodbye_after: int = -1,
|
||||
unsolicited_goodbye_after: int = -1,
|
||||
label: str,
|
||||
):
|
||||
proc = subprocess.Popen(
|
||||
_bonjour_responder_cmd(
|
||||
srv_first=srv_first,
|
||||
goodbye_after=goodbye_after,
|
||||
unsolicited_goodbye_after=unsolicited_goodbye_after,
|
||||
),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
time.sleep(0.5)
|
||||
# poll() stays None while the responder is still running after startup.
|
||||
assert proc.poll() is None, f'{label} failed to start (need eth0 and port 5353?)'
|
||||
return proc
|
||||
|
||||
|
||||
def _stop_bonjour_responder(proc):
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait(timeout=3)
|
||||
|
||||
|
||||
def _run_querier_responder():
|
||||
proc = subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
str(Path(__file__).with_name('querier_responder.py')),
|
||||
'--interface',
|
||||
'eth0',
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
time.sleep(0.5)
|
||||
assert proc.poll() is None, 'Querier responder failed to start (need eth0 and port 5353?)'
|
||||
return proc
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def querier_responder():
|
||||
proc = _run_querier_responder()
|
||||
yield proc
|
||||
_stop_bonjour_responder(proc)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bonjour_responder():
|
||||
proc = _run_bonjour_responder(label='Bonjour-order responder')
|
||||
yield proc
|
||||
_stop_bonjour_responder(proc)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bonjour_responder_srv_first():
|
||||
proc = _run_bonjour_responder(srv_first=True, label='SRV-first responder')
|
||||
yield proc
|
||||
_stop_bonjour_responder(proc)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bonjour_responder_goodbye():
|
||||
proc = _run_bonjour_responder(
|
||||
unsolicited_goodbye_after=1,
|
||||
label='Unsolicited-goodbye responder',
|
||||
)
|
||||
yield proc
|
||||
_stop_bonjour_responder(proc)
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def mdns_console():
|
||||
app = MdnsConsole('./build_linux_console/mdns_host.elf')
|
||||
yield app
|
||||
app.terminate()
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def dig_app():
|
||||
return DnsPythonWrapper()
|
||||
|
||||
|
||||
def test_mdns_init(mdns_console, dig_app):
|
||||
mdns_console.send_input('mdns_init -h hostname')
|
||||
mdns_console.get_output('MDNS: Hostname: hostname')
|
||||
dig_app.check_record('hostname.local', query_type='A', expected=True)
|
||||
if ipv6_enabled:
|
||||
dig_app.check_record('hostname.local', query_type='AAAA', expected=True)
|
||||
|
||||
|
||||
def test_add_service(mdns_console, dig_app):
|
||||
mdns_console.send_input('mdns_service_add _http _tcp 80 -i test_service')
|
||||
mdns_console.get_output('MDNS: Service Instance: test_service')
|
||||
mdns_console.send_input('mdns_service_lookup _http _tcp')
|
||||
mdns_console.get_output('PTR : test_service')
|
||||
dig_app.check_record('_http._tcp.local', query_type='PTR', expected=True)
|
||||
|
||||
|
||||
def test_ptr_additional_records_for_service(dig_app):
|
||||
# Query PTR for the service type and ensure SRV/TXT are in Additional (RFC 6763 §12.1)
|
||||
resp = dig_app.run_query('_http._tcp.local', query_type='PTR')
|
||||
# Answer section should have at least one PTR to the instance
|
||||
answers = dig_app.parse_answer_section(resp, 'PTR')
|
||||
assert any('test_service._http._tcp.local' in a for a in answers)
|
||||
# Additional section should include SRV and TXT for the same instance
|
||||
dig_app.check_additional(resp, 'SRV', 'test_service._http._tcp.local', expected=True)
|
||||
dig_app.check_additional(resp, 'TXT', 'test_service._http._tcp.local', expected=True)
|
||||
|
||||
|
||||
def test_instance_any_answer_records(dig_app):
|
||||
"""Query ANY for the service instance and ensure SRV/TXT are in Answer (Q/A path)."""
|
||||
resp = dig_app.run_query('test_service._http._tcp.local', query_type='ANY')
|
||||
|
||||
# Answer section should contain SRV and TXT records for the instance
|
||||
srv_answers = dig_app.parse_section(resp, 'answer', 'SRV')
|
||||
txt_answers = dig_app.parse_section(resp, 'answer', 'TXT')
|
||||
assert any('test_service._http._tcp.local' in a for a in srv_answers)
|
||||
assert any('test_service._http._tcp.local' in a for a in txt_answers)
|
||||
|
||||
# We should not see a PTR for the generic service name in the Answer section
|
||||
ptr_answers = dig_app.parse_section(resp, 'answer', 'PTR')
|
||||
assert not any('_http._tcp.local' in a for a in ptr_answers)
|
||||
|
||||
|
||||
def test_remove_service(mdns_console, dig_app):
|
||||
mdns_console.send_input('mdns_service_remove _http _tcp')
|
||||
mdns_console.send_input('mdns_service_lookup _http _tcp')
|
||||
mdns_console.get_output('No results found!')
|
||||
dig_app.check_record('_http._tcp.local', query_type='PTR', expected=False)
|
||||
|
||||
|
||||
def test_delegate_host(mdns_console, dig_app):
|
||||
mdns_console.send_input('mdns_delegate_host delegated 1.2.3.4')
|
||||
dig_app.check_record('delegated.local', query_type='A', expected=True)
|
||||
|
||||
|
||||
def test_undelegate_host(mdns_console, dig_app):
|
||||
mdns_console.send_input('mdns_undelegate_host delegated')
|
||||
dig_app.check_record('delegated.local', query_type='A', expected=False)
|
||||
|
||||
|
||||
def test_add_delegated_service(mdns_console, dig_app):
|
||||
mdns_console.send_input('mdns_delegate_host delegated 1.2.3.4')
|
||||
dig_app.check_record('delegated.local', query_type='A', expected=True)
|
||||
mdns_console.send_input('mdns_service_add _test _tcp 80 -i local')
|
||||
mdns_console.get_output('MDNS: Service Instance: local')
|
||||
mdns_console.send_input('mdns_service_add _test2 _tcp 80 -i extern -h delegated')
|
||||
mdns_console.get_output('MDNS: Service Instance: extern')
|
||||
mdns_console.send_input('mdns_service_lookup _test _tcp')
|
||||
mdns_console.get_output('PTR : local')
|
||||
mdns_console.send_input('mdns_service_lookup _test2 _tcp -d')
|
||||
mdns_console.get_output('PTR : extern')
|
||||
dig_app.check_record('_test2._tcp.local', query_type='PTR', expected=True)
|
||||
dig_app.check_record('extern._test2._tcp.local', query_type='SRV', expected=True)
|
||||
|
||||
|
||||
def test_service_discovery_dns_sd(dig_app):
|
||||
"""Query _services._dns-sd._udp.local PTR to discover registered service types (RFC 6763 §9)."""
|
||||
resp = dig_app.run_query('_services._dns-sd._udp.local', query_type='PTR')
|
||||
answers = dig_app.parse_answer_section(resp, 'PTR')
|
||||
assert any('_test._tcp.local' in a for a in answers), \
|
||||
f'Expected _test._tcp.local in DNS-SD response, got: {answers}'
|
||||
assert any('_test2._tcp.local' in a for a in answers), \
|
||||
f'Expected _test2._tcp.local in DNS-SD response, got: {answers}'
|
||||
|
||||
|
||||
def test_service_discovery_query(mdns_console):
|
||||
"""Test querier-side: query _services._dns-sd._udp via mdns_query_ptr (exercises multi-label splitting)."""
|
||||
mdns_console.send_input('mdns_query_ptr _services._dns-sd _udp -t 2000 -m 10')
|
||||
mdns_console.get_output('Query PTR: _services._dns-sd._udp.local')
|
||||
mdns_console.get_output('mdns>')
|
||||
|
||||
|
||||
def test_remove_delegated_service(mdns_console, dig_app):
|
||||
mdns_console.send_input('mdns_service_remove _test2 _tcp -h delegated')
|
||||
mdns_console.send_input('mdns_service_lookup _test2 _tcp -d')
|
||||
mdns_console.get_output('No results found!')
|
||||
dig_app.check_record('_test2._tcp.local', query_type='PTR', expected=False)
|
||||
# add the delegated service again, would be used in the TXT test
|
||||
mdns_console.send_input('mdns_service_add _test2 _tcp 80 -i extern -h delegated')
|
||||
mdns_console.get_output('MDNS: Service Instance: extern')
|
||||
|
||||
|
||||
def check_txt_for_service(instance, service, proto, mdns_console, dig_app, host=None, with_inst=False):
|
||||
for_host_arg = f'-h {host}' if host is not None else ''
|
||||
for_inst_arg = f'-i {instance}' if with_inst else ''
|
||||
mdns_console.send_input(f'mdns_service_txt_set {service} {proto} {for_host_arg} {for_inst_arg} key1 value1')
|
||||
dig_app.check_record(f'{instance}.{service}.{proto}.local', query_type='SRV', expected=True)
|
||||
dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key1=value1')
|
||||
mdns_console.send_input(f'mdns_service_txt_set {service} {proto} {for_host_arg} {for_inst_arg} key2 value2')
|
||||
dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key2=value2')
|
||||
mdns_console.send_input(f'mdns_service_txt_remove {service} {proto} {for_host_arg} {for_inst_arg} key2')
|
||||
dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=False, expect='key2=value2')
|
||||
dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key1=value1')
|
||||
mdns_console.send_input(f'mdns_service_txt_replace {service} {proto} {for_host_arg} {for_inst_arg} key3=value3 key4=value4')
|
||||
dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=False, expect='key1=value1')
|
||||
dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key3=value3')
|
||||
dig_app.check_record(f'{service}.{proto}.local', query_type='TXT', expected=True, expect='key4=value4')
|
||||
|
||||
|
||||
def test_update_txt(mdns_console, dig_app):
|
||||
check_txt_for_service('local', '_test', '_tcp', mdns_console=mdns_console, dig_app=dig_app)
|
||||
check_txt_for_service('local', '_test', '_tcp', mdns_console=mdns_console, dig_app=dig_app, with_inst=True)
|
||||
|
||||
|
||||
def test_update_delegated_txt(mdns_console, dig_app):
|
||||
check_txt_for_service('extern', '_test2', '_tcp', mdns_console=mdns_console, dig_app=dig_app, host='delegated')
|
||||
check_txt_for_service('extern', '_test2', '_tcp', mdns_console=mdns_console, dig_app=dig_app, host='delegated', with_inst=True)
|
||||
|
||||
|
||||
def test_service_port_set(mdns_console, dig_app):
|
||||
dig_app.check_record('local._test._tcp.local', query_type='SRV', expected=True, expect='80')
|
||||
mdns_console.send_input('mdns_service_port_set _test _tcp 81')
|
||||
dig_app.check_record('local._test._tcp.local', query_type='SRV', expected=True, expect='81')
|
||||
mdns_console.send_input('mdns_service_port_set _test2 _tcp -h delegated 82')
|
||||
dig_app.check_record('extern._test2._tcp.local', query_type='SRV', expected=True, expect='82')
|
||||
mdns_console.send_input('mdns_service_port_set _test2 _tcp -h delegated -i extern 83')
|
||||
dig_app.check_record('extern._test2._tcp.local', query_type='SRV', expected=True, expect='83')
|
||||
mdns_console.send_input('mdns_service_port_set _test2 _tcp -h delegated -i invalid_inst 84')
|
||||
mdns_console.get_output('ESP_ERR_NOT_FOUND')
|
||||
dig_app.check_record('extern._test2._tcp.local', query_type='SRV', expected=True, expect='83')
|
||||
|
||||
|
||||
def test_service_subtype(mdns_console, dig_app):
|
||||
dig_app.check_record('local._test._tcp.local', query_type='SRV', expected=True)
|
||||
mdns_console.send_input('mdns_service_subtype _test _tcp _subtest -i local')
|
||||
dig_app.check_record('_subtest._sub._test._tcp.local', query_type='PTR', expected=True)
|
||||
mdns_console.send_input('mdns_service_subtype _test2 _tcp _subtest2 -i extern -h delegated')
|
||||
dig_app.check_record('_subtest2._sub._test2._tcp.local', query_type='PTR', expected=True)
|
||||
|
||||
|
||||
def test_service_set_instance(mdns_console, dig_app):
|
||||
dig_app.check_record('local._test._tcp.local', query_type='SRV', expected=True)
|
||||
mdns_console.send_input('mdns_service_instance_set _test _tcp local2')
|
||||
dig_app.check_record('local2._test._tcp.local', query_type='SRV', expected=True)
|
||||
mdns_console.send_input('mdns_service_instance_set _test2 _tcp extern2 -h delegated')
|
||||
mdns_console.send_input('mdns_service_lookup _test2 _tcp -d')
|
||||
mdns_console.get_output('PTR : extern2')
|
||||
dig_app.check_record('extern2._test2._tcp.local', query_type='SRV', expected=True)
|
||||
mdns_console.send_input('mdns_service_instance_set _test2 _tcp extern3 -h delegated -i extern')
|
||||
mdns_console.get_output('ESP_ERR_NOT_FOUND')
|
||||
|
||||
|
||||
def test_service_remove_all(mdns_console, dig_app):
|
||||
mdns_console.send_input('mdns_service_remove_all')
|
||||
mdns_console.send_input('mdns_service_lookup _test2 _tcp -d')
|
||||
mdns_console.get_output('No results found!')
|
||||
mdns_console.send_input('mdns_service_lookup _test _tcp')
|
||||
mdns_console.get_output('No results found!')
|
||||
dig_app.check_record('_test._tcp.local', query_type='PTR', expected=False)
|
||||
|
||||
|
||||
def _browse_v301test(mdns_console, *, reset_browse: bool = True):
|
||||
service = DEFAULTS['service']
|
||||
proto = DEFAULTS['proto']
|
||||
if reset_browse:
|
||||
mdns_console.send_input(f'mdns_browse_del {service} {proto}')
|
||||
mdns_console.get_output('mdns>')
|
||||
mdns_console.send_input(f'mdns_browse {service} {proto}')
|
||||
return mdns_console.wait_for_browse_result(timeout=10)
|
||||
|
||||
|
||||
def test_browse_bonjour_additional_order_includes_ip(mdns_console, bonjour_responder):
|
||||
"""Bonjour order (A/AAAA before SRV) must populate browse addresses on first response."""
|
||||
output = _browse_v301test(mdns_console)
|
||||
assert _console_line('PTR : ', DEFAULTS['instance']) in output
|
||||
assert _console_line('A : ', DEFAULTS['ipv4']) in output
|
||||
mdns_console.send_input(f"mdns_browse_del {DEFAULTS['service']} {DEFAULTS['proto']}")
|
||||
mdns_console.get_output('mdns>')
|
||||
|
||||
|
||||
def test_browse_srv_first_includes_ip(mdns_console, bonjour_responder_srv_first):
|
||||
"""Control case: SRV before A/AAAA should populate browse addresses."""
|
||||
output = _browse_v301test(mdns_console)
|
||||
assert _console_line('PTR : ', DEFAULTS['instance']) in output
|
||||
assert _console_line('A : ', DEFAULTS['ipv4']) in output
|
||||
mdns_console.send_input(f"mdns_browse_del {DEFAULTS['service']} {DEFAULTS['proto']}")
|
||||
mdns_console.get_output('mdns>')
|
||||
|
||||
|
||||
def test_browse_ptr_goodbye_notifies_removal(mdns_console, bonjour_responder_goodbye):
|
||||
"""Same live browse must see normal result then unsolicited PTR TTL=0 removal."""
|
||||
service = DEFAULTS['service']
|
||||
proto = DEFAULTS['proto']
|
||||
mdns_console.send_input(f'mdns_browse_del {service} {proto}')
|
||||
mdns_console.get_output('mdns>')
|
||||
mdns_console.send_input(f'mdns_browse {service} {proto}')
|
||||
mdns_console.wait_for_browse_result(timeout=10)
|
||||
output = mdns_console.wait_for_browse_goodbye(timeout=10)
|
||||
assert _console_line('PTR : ', DEFAULTS['instance']) in output
|
||||
mdns_console.send_input(f'mdns_browse_del {service} {proto}')
|
||||
mdns_console.get_output('mdns>')
|
||||
|
||||
|
||||
def test_browse_duplicate_rejected(mdns_console, bonjour_responder):
|
||||
"""Duplicate mdns_browse_new() for the same service/proto must fail and leave the original active."""
|
||||
service = DEFAULTS['service']
|
||||
proto = DEFAULTS['proto']
|
||||
mdns_console.send_input(f'mdns_browse_del {service} {proto}')
|
||||
mdns_console.get_output('mdns>')
|
||||
mdns_console.send_input(f'mdns_browse {service} {proto}')
|
||||
mdns_console.wait_for_browse_result(timeout=10)
|
||||
|
||||
mdns_console.send_input(f'mdns_browse {service} {proto}')
|
||||
mdns_console.get_output('Browse already exists')
|
||||
mdns_console.get_output('Command returned non-zero error code')
|
||||
mdns_console.get_output('mdns>')
|
||||
|
||||
# Original browse remains usable (delete must succeed).
|
||||
mdns_console.send_input(f'mdns_browse_del {service} {proto}')
|
||||
out = mdns_console.get_output('mdns>')
|
||||
assert 'Command returned non-zero' not in out
|
||||
|
||||
|
||||
def test_query_a_against_peer(mdns_console, querier_responder):
|
||||
"""DUT-side sync mdns_query_a against a controlled peer (replaces test_apps QUERY_HOST)."""
|
||||
host = QUERIER_DEFAULTS['hostname']
|
||||
ipv4 = QUERIER_DEFAULTS['ipv4']
|
||||
# Safe if suite already called mdns_init; required when this test runs alone.
|
||||
mdns_console.send_input('mdns_init -h hostname')
|
||||
mdns_console.get_output('mdns>')
|
||||
mdns_console.send_input(f'mdns_query_a {host} -t 2000')
|
||||
mdns_console.get_output(f'Query A: {host}.local')
|
||||
mdns_console.get_output(ipv4)
|
||||
mdns_console.get_output('mdns>')
|
||||
|
||||
|
||||
def test_query_a_async_against_peer(mdns_console, querier_responder):
|
||||
"""DUT-side async A query against a controlled peer (replaces test_apps QUERY_HOST_ASYNC)."""
|
||||
host = QUERIER_DEFAULTS['hostname']
|
||||
ipv4 = QUERIER_DEFAULTS['ipv4']
|
||||
mdns_console.send_input('mdns_init -h hostname')
|
||||
mdns_console.get_output('mdns>')
|
||||
mdns_console.send_input(f'mdns_query_a_async {host} -t 2000')
|
||||
mdns_console.get_output(f'Query A async: {host}.local')
|
||||
mdns_console.get_output(f'Async query resolved to A:{ipv4}')
|
||||
mdns_console.get_output('mdns>')
|
||||
|
||||
|
||||
def test_query_srv_against_peer(mdns_console, querier_responder):
|
||||
"""DUT-side mdns_query_srv against a controlled peer (replaces test_apps QUERY_SERVICE)."""
|
||||
instance = QUERIER_DEFAULTS['instance']
|
||||
service = QUERIER_DEFAULTS['service']
|
||||
proto = QUERIER_DEFAULTS['proto']
|
||||
hostname = QUERIER_DEFAULTS['hostname']
|
||||
port = QUERIER_DEFAULTS['port']
|
||||
mdns_console.send_input('mdns_init -h hostname')
|
||||
mdns_console.get_output('mdns>')
|
||||
mdns_console.send_input(f'mdns_query_srv {instance} {service} {proto} -t 2000')
|
||||
mdns_console.get_output(f'Query SRV: {instance}.{service}.{proto}.local')
|
||||
mdns_console.get_output(_console_line('SRV : ', f'{hostname}.local:{port}'))
|
||||
mdns_console.get_output('mdns>')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
pytest.main(['-s', 'test_mdns.py'])
|
||||
@@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
|
||||
# SPDX-License-Identifier: Unlicense OR CC0-1.0
|
||||
"""Controlled mDNS peer for host querier tests (A / SRV only).
|
||||
|
||||
Answers only the configured hostname A and instance SRV questions. Ignores all
|
||||
other traffic so system mDNS probes cannot create an answer storm.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import dns.flags
|
||||
import dns.message
|
||||
import dns.name
|
||||
import dns.rdataclass
|
||||
import dns.rdatatype
|
||||
import dns.rrset
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MDNS_ADDR = '224.0.0.251'
|
||||
MDNS_PORT = 5353
|
||||
|
||||
DEFAULTS = {
|
||||
'hostname': 'tinytester',
|
||||
'ipv4': '127.0.0.1',
|
||||
'instance': 'ESP32',
|
||||
'service': '_http',
|
||||
'proto': '_tcp',
|
||||
'port': 100,
|
||||
}
|
||||
|
||||
|
||||
def _fqdn(*labels: str) -> str:
|
||||
return '.'.join(labels) + '.local.'
|
||||
|
||||
|
||||
def create_socket(interface: str | None) -> socket.socket:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
try:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
|
||||
if interface:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface.encode() + b'\0')
|
||||
|
||||
sock.bind(('', MDNS_PORT))
|
||||
membership = struct.pack('=4s4s', socket.inet_aton(MDNS_ADDR), socket.inet_aton('0.0.0.0'))
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership)
|
||||
return sock
|
||||
|
||||
|
||||
def build_a_response(query: dns.message.Message, hostname: str, ipv4: str) -> dns.message.Message:
|
||||
host_name = _fqdn(hostname)
|
||||
# Exact QR|AA (0x8400). dnspython make_response also sets RD, which is fine for
|
||||
# answer parsing but keep mDNS-shaped packets consistent with bonjour fixtures.
|
||||
response = dns.message.Message(id=query.id)
|
||||
response.flags = dns.flags.QR | dns.flags.AA
|
||||
response.answer.append(
|
||||
dns.rrset.from_text(host_name, 120, dns.rdataclass.IN, dns.rdatatype.A, ipv4)
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
def build_srv_response(
|
||||
query: dns.message.Message,
|
||||
*,
|
||||
instance: str,
|
||||
service: str,
|
||||
proto: str,
|
||||
hostname: str,
|
||||
port: int,
|
||||
ipv4: str,
|
||||
) -> dns.message.Message:
|
||||
instance_name = _fqdn(instance, service, proto)
|
||||
host_name = _fqdn(hostname)
|
||||
response = dns.message.Message(id=query.id)
|
||||
response.flags = dns.flags.QR | dns.flags.AA
|
||||
response.answer.append(
|
||||
dns.rrset.from_text(
|
||||
instance_name,
|
||||
120,
|
||||
dns.rdataclass.IN,
|
||||
dns.rdatatype.SRV,
|
||||
f'0 0 {port} {host_name}',
|
||||
)
|
||||
)
|
||||
response.additional.append(
|
||||
dns.rrset.from_text(host_name, 120, dns.rdataclass.IN, dns.rdatatype.A, ipv4)
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
def match_question(query: dns.message.Message, args: argparse.Namespace):
|
||||
host_name = dns.name.from_text(_fqdn(args.hostname))
|
||||
instance_name = dns.name.from_text(_fqdn(args.instance, args.service, args.proto))
|
||||
for question in query.question:
|
||||
if question.rdtype == dns.rdatatype.A and question.name == host_name:
|
||||
return 'A'
|
||||
if question.rdtype == dns.rdatatype.SRV and question.name == instance_name:
|
||||
return 'SRV'
|
||||
return None
|
||||
|
||||
|
||||
def send_response(sock: socket.socket, payload: bytes, source: tuple[str, int]) -> None:
|
||||
# mDNS queries usually come from port 5353 → multicast reply; one-shot dig uses ephemeral ports.
|
||||
destination = (MDNS_ADDR, MDNS_PORT) if source[1] == MDNS_PORT else source
|
||||
sock.sendto(payload, destination)
|
||||
logger.info('Sent %d byte response to %s (from %s:%d)', len(payload), destination, *source)
|
||||
|
||||
|
||||
def serve(args: argparse.Namespace) -> None:
|
||||
sock = create_socket(args.interface)
|
||||
logger.info(
|
||||
'Querier responder on %s:%d (%s): A %s.local -> %s; SRV %s.%s.%s.local -> %s.local:%d',
|
||||
MDNS_ADDR,
|
||||
MDNS_PORT,
|
||||
args.interface or 'all interfaces',
|
||||
args.hostname,
|
||||
args.ipv4,
|
||||
args.instance,
|
||||
args.service,
|
||||
args.proto,
|
||||
args.hostname,
|
||||
args.port,
|
||||
)
|
||||
|
||||
while True:
|
||||
try:
|
||||
data, source = sock.recvfrom(9000)
|
||||
except KeyboardInterrupt:
|
||||
logger.info('Stopping querier responder')
|
||||
break
|
||||
|
||||
try:
|
||||
query = dns.message.from_wire(data)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug('Ignoring non-DNS payload from %s:%d (%s)', source[0], source[1], exc)
|
||||
continue
|
||||
|
||||
if query.flags & dns.flags.QR:
|
||||
continue
|
||||
|
||||
kind = match_question(query, args)
|
||||
if kind == 'A':
|
||||
response = build_a_response(query, args.hostname, args.ipv4)
|
||||
elif kind == 'SRV':
|
||||
response = build_srv_response(
|
||||
query,
|
||||
instance=args.instance,
|
||||
service=args.service,
|
||||
proto=args.proto,
|
||||
hostname=args.hostname,
|
||||
port=args.port,
|
||||
ipv4=args.ipv4,
|
||||
)
|
||||
else:
|
||||
continue
|
||||
|
||||
send_response(sock, response.to_wire(), source)
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--interface', default='eth0')
|
||||
parser.add_argument('--hostname', default=DEFAULTS['hostname'])
|
||||
parser.add_argument('--ipv4', default=DEFAULTS['ipv4'])
|
||||
parser.add_argument('--instance', default=DEFAULTS['instance'])
|
||||
parser.add_argument('--service', default=DEFAULTS['service'])
|
||||
parser.add_argument('--proto', default=DEFAULTS['proto'])
|
||||
parser.add_argument('--port', type=int, default=DEFAULTS['port'])
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_args(argv)
|
||||
serve(args)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,4 @@
|
||||
CONFIG_IDF_TARGET="linux"
|
||||
CONFIG_TEST_HOSTNAME="myesp"
|
||||
CONFIG_MDNS_ENABLE_DEBUG_PRINTS=y
|
||||
CONFIG_MDNS_RESPOND_REVERSE_QUERIES=y
|
||||
@@ -0,0 +1,4 @@
|
||||
CONFIG_IDF_TARGET="linux"
|
||||
CONFIG_ESP_EVENT_POST_FROM_ISR=n
|
||||
CONFIG_MDNS_ENABLE_CONSOLE_CLI=y
|
||||
CONFIG_TEST_CONSOLE=y
|
||||
@@ -0,0 +1 @@
|
||||
CONFIG_IDF_TARGET="esp32"
|
||||
@@ -0,0 +1,6 @@
|
||||
CONFIG_TEST_NETIF_NAME="eth0"
|
||||
CONFIG_ESP_EVENT_POST_FROM_ISR=n
|
||||
CONFIG_MDNS_NETWORKING_SOCKET=y
|
||||
CONFIG_MDNS_SKIP_SUPPRESSING_OWN_QUERIES=y
|
||||
CONFIG_MDNS_PREDEF_NETIF_STA=n
|
||||
CONFIG_MDNS_PREDEF_NETIF_AP=n
|
||||
Reference in new issue
Block a user