From 6e25b747817d98ee943e7127038ac0ed0721298c Mon Sep 17 00:00:00 2001 From: bert hubert Date: Sat, 20 Aug 2016 22:04:35 +0200 Subject: [PATCH] Make DNS engine RFC 5452 compliant (#1324) The original code did not deal with UDP binding failures, this new code does one random port attempt and then sets port to 0 to get 'OS default' behaviour, and ASSERTs that that has to work. Patch also moves the local UDP port range definition to udp.h from udp.c. --- app/include/lwip/udp.h | 5 +++++ app/lwip/core/dns.c | 10 ++++++++-- app/lwip/core/udp.c | 4 ---- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/app/include/lwip/udp.h b/app/include/lwip/udp.h index cb53d33e..760b24cf 100644 --- a/app/include/lwip/udp.h +++ b/app/include/lwip/udp.h @@ -156,6 +156,11 @@ void udp_input (struct pbuf *p, struct netif *inp)ICACHE_FLASH_ #define udp_init() /* Compatibility define, not init needed. */ +#ifndef UDP_LOCAL_PORT_RANGE_START +#define UDP_LOCAL_PORT_RANGE_START 4096 +#define UDP_LOCAL_PORT_RANGE_END 0x7fff +#endif + #if UDP_DEBUG void udp_debug_print(struct udp_hdr *udphdr)ICACHE_FLASH_ATTR; #else diff --git a/app/lwip/core/dns.c b/app/lwip/core/dns.c index c0d616f2..72a31995 100644 --- a/app/lwip/core/dns.c +++ b/app/lwip/core/dns.c @@ -254,8 +254,14 @@ dns_init() LWIP_ASSERT("For implicit initialization to work, DNS_STATE_UNUSED needs to be 0", DNS_STATE_UNUSED == 0); - /* initialize DNS client */ - udp_bind(dns_pcb, IP_ADDR_ANY, 0); + /* initialize DNS client, try to get RFC 5452 random source port */ + u16_t port = UDP_LOCAL_PORT_RANGE_START + (os_random() % (UDP_LOCAL_PORT_RANGE_END - UDP_LOCAL_PORT_RANGE_START)); + for(;;) { + if(udp_bind(dns_pcb, IP_ADDR_ANY, port) == ERR_OK) + break; + LWIP_ASSERT("Unable to get a PCB for DNS", port != 0); + port=0; // try again with random source + } udp_recv(dns_pcb, dns_recv, NULL); /* initialize default DNS primary server */ diff --git a/app/lwip/core/udp.c b/app/lwip/core/udp.c index e44d7f38..2d794818 100644 --- a/app/lwip/core/udp.c +++ b/app/lwip/core/udp.c @@ -758,10 +758,6 @@ udp_bind(struct udp_pcb *pcb, ip_addr_t *ipaddr, u16_t port) /* no port specified? */ if (port == 0) { -#ifndef UDP_LOCAL_PORT_RANGE_START -#define UDP_LOCAL_PORT_RANGE_START 4096 -#define UDP_LOCAL_PORT_RANGE_END 0x7fff -#endif port = UDP_LOCAL_PORT_RANGE_START; ipcb = udp_pcbs; while ((ipcb != NULL) && (port != UDP_LOCAL_PORT_RANGE_END)) {