From ced065f07a03ff0f6fdef6ee954ea4a71f9104ae Mon Sep 17 00:00:00 2001 From: seteiro <276597748+cms19859230182-lang@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:31:30 +0800 Subject: [PATCH] [net][dhcpd] recycle expired DHCP client leases Fix #11878 Store and renew node->lease_end in sys_now() milliseconds, align DHCP_DEFAULT_LIVE_TIME with option 51 (86400 seconds), and reclaim expired leases via dhcp_client_remove_expired() before allocating a new IP. - Validate MAC ownership before reusing nodes in the requested-IP paths of dhcp_client_find() and dhcp_client_alloc() to prevent giving one client's active lease to another MAC. The full-MAC scan already covered the list, so the leftover requested-IP lookup could only ever reject: drop that dead code. - Register a periodic lwIP sys_timeout timer to clean up expired client leases even during long idle periods where no incoming DHCP packets arrive, preventing expired leases from persisting across 2^32 ms counter wraparounds. - Move the periodic recycle callback to file scope so LWIP_USING_DHCPD configurations compile, and make it visible to dhcpd_stop(). - Reserve one MEMP_NUM_SYS_TIMEOUT slot for the permanent DHCPD timer across the supported lwIP versions. - Run server start/stop on the lwIP tcpip thread through tcpip_callback() plus a completion semaphore, and detect calls that already run on that thread. lwIP 2.0.3 (the RT-Thread default) walks the timeout list outside LOCK_TCPIP_CORE(); with LWIP_TCPIP_CORE_LOCKING == 0 that lock is an empty macro. Registering or cancelling the timeout from another thread therefore raced with the tcpip thread even with the lock, and a plain sys_timeout() does not wake a sleeping tcpip thread. The lease list and the server are now only touched from the tcpip thread, together with the timeout. - Only accept Ethernet clients: the receive path drops frames whose hardware address length is not 6, and the lease lookup/ownership/release comparisons use the full six-byte address. A shorter hardware address used to match any node that shared its prefix, and a prefix match could hand one client's lease to another. - Move the host regression test to test/ so */*.c globs in downstream builds no longer pick it up, replace the empty timer mocks with a model of the tcpip thread, and cover the periodic recycle, a full 2^32 ms idle period, a full pool and the start/stop timer lifecycle. Add test/Makefile, test/README.md and .github/workflows/dhcpd_host_test.yml. --- .github/workflows/dhcpd_host_test.yml | 34 + components/net/lwip-dhcpd/dhcp_server_raw.c | 445 +++++++++-- components/net/lwip-dhcpd/test/.gitignore | 2 + components/net/lwip-dhcpd/test/Makefile | 19 + components/net/lwip-dhcpd/test/README.md | 47 ++ .../net/lwip-dhcpd/test/mock/lwip/dhcp.h | 2 + .../lwip-dhcpd/test/mock/lwip/inet_chksum.h | 2 + .../net/lwip-dhcpd/test/mock/lwip/init.h | 2 + components/net/lwip-dhcpd/test/mock/lwip/ip.h | 2 + .../net/lwip-dhcpd/test/mock/lwip/opt.h | 2 + .../net/lwip-dhcpd/test/mock/lwip/prot/dhcp.h | 2 + .../net/lwip-dhcpd/test/mock/lwip/sockets.h | 2 + .../net/lwip-dhcpd/test/mock/lwip/sys.h | 2 + .../net/lwip-dhcpd/test/mock/lwip/tcpip.h | 2 + .../net/lwip-dhcpd/test/mock/lwip/timeouts.h | 2 + .../net/lwip-dhcpd/test/mock/mock_lwip.h | 649 ++++++++++++++++ .../net/lwip-dhcpd/test/mock/netif/etharp.h | 2 + .../lwip-dhcpd/test/mock/netif/ethernetif.h | 2 + .../net/lwip-dhcpd/test/mock/rtthread.h | 2 + .../net/lwip-dhcpd/test/test_dhcpd_lease.c | 713 ++++++++++++++++++ components/net/lwip/port/lwipopts.h | 25 +- 21 files changed, 1885 insertions(+), 75 deletions(-) create mode 100644 .github/workflows/dhcpd_host_test.yml create mode 100644 components/net/lwip-dhcpd/test/.gitignore create mode 100644 components/net/lwip-dhcpd/test/Makefile create mode 100644 components/net/lwip-dhcpd/test/README.md create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/dhcp.h create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/inet_chksum.h create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/init.h create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/ip.h create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/opt.h create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/prot/dhcp.h create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/sockets.h create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/sys.h create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/tcpip.h create mode 100644 components/net/lwip-dhcpd/test/mock/lwip/timeouts.h create mode 100644 components/net/lwip-dhcpd/test/mock/mock_lwip.h create mode 100644 components/net/lwip-dhcpd/test/mock/netif/etharp.h create mode 100644 components/net/lwip-dhcpd/test/mock/netif/ethernetif.h create mode 100644 components/net/lwip-dhcpd/test/mock/rtthread.h create mode 100644 components/net/lwip-dhcpd/test/test_dhcpd_lease.c diff --git a/.github/workflows/dhcpd_host_test.yml b/.github/workflows/dhcpd_host_test.yml new file mode 100644 index 00000000000..2fc15087ca9 --- /dev/null +++ b/.github/workflows/dhcpd_host_test.yml @@ -0,0 +1,34 @@ +# Host-side regression test for the DHCPD lease bookkeeping. +# It compiles components/net/lwip-dhcpd/dhcp_server_raw.c against the lwIP / +# RT-Thread stubs in components/net/lwip-dhcpd/test/mock. + +name: dhcpd_host_test + +on: + push: + paths: + - 'components/net/lwip-dhcpd/**' + - '.github/workflows/dhcpd_host_test.yml' + pull_request: + paths: + - 'components/net/lwip-dhcpd/**' + - '.github/workflows/dhcpd_host_test.yml' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + lease-test: + runs-on: ubuntu-22.04 + name: DHCPD lease host test + if: github.repository_owner == 'RT-Thread' + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Build and run the DHCPD lease host test + working-directory: components/net/lwip-dhcpd/test + run: make run \ No newline at end of file diff --git a/components/net/lwip-dhcpd/dhcp_server_raw.c b/components/net/lwip-dhcpd/dhcp_server_raw.c index f0d7b4aaedc..c2c8b7cf1a8 100644 --- a/components/net/lwip-dhcpd/dhcp_server_raw.c +++ b/components/net/lwip-dhcpd/dhcp_server_raw.c @@ -46,6 +46,9 @@ #include #include #include +#include +#include +#include #if (LWIP_VERSION) < 0x02000000U // cppcheck-suppress preprocessorErrorDirective @@ -53,51 +56,57 @@ #endif #if !LWIP_IPV4 - #error "must enable IPV4" +#error "must enable IPV4" #endif #if (LWIP_VERSION) >= 0x02000000U - #include +#include #endif /* DHCP server option */ /* allocated client ip range */ #ifndef DHCPD_CLIENT_IP_MIN - #define DHCPD_CLIENT_IP_MIN 2 +#define DHCPD_CLIENT_IP_MIN 2 #endif #ifndef DHCPD_CLIENT_IP_MAX - #define DHCPD_CLIENT_IP_MAX 254 +#define DHCPD_CLIENT_IP_MAX 254 #endif /* the DHCP server address */ #ifndef DHCPD_SERVER_IP - #define DHCPD_SERVER_IP "192.168.169.1" +#define DHCPD_SERVER_IP "192.168.169.1" #endif #define DHCP_DEBUG_PRINTF -#ifdef DHCP_DEBUG_PRINTF - #define DEBUG_PRINTF rt_kprintf("[DHCP] "); rt_kprintf +#ifdef DHCP_DEBUG_PRINTF +#define DEBUG_PRINTF \ + rt_kprintf("[DHCP] "); \ + rt_kprintf #else - #define DEBUG_PRINTF(...) +#define DEBUG_PRINTF(...) #endif /* DHCP_DEBUG_PRINTF */ /* we need some routines in the DHCP of lwIP */ -#undef LWIP_DHCP -#define LWIP_DHCP 1 +#undef LWIP_DHCP +#define LWIP_DHCP 1 #include /** Mac address length */ -#define DHCP_MAX_HLEN 6 -/** dhcp default live time */ -#define DHCP_DEFAULT_LIVE_TIME 0x80510100 +#define DHCP_MAX_HLEN 6 +/** dhcp default lease time in seconds */ +#define DHCP_DEFAULT_LIVE_TIME 86400 +/** dhcp default lease time in milliseconds */ +#define DHCP_DEFAULT_LEASE_TIME_MS (DHCP_DEFAULT_LIVE_TIME * 1000U) /** Minimum length for request before packet is parsed */ -#define DHCP_MIN_REQUEST_LEN 44 +#define DHCP_MIN_REQUEST_LEN 44 -#define LWIP_NETIF_LOCK(...) -#define LWIP_NETIF_UNLOCK(...) +/* How often the TCP/IP thread scans all servers for expired leases. */ +#ifndef DHCPD_RECYCLE_INTERVAL_MS +#define DHCPD_RECYCLE_INTERVAL_MS 60000 +#endif #ifndef DHCP_SERVER_PORT #define DHCP_SERVER_PORT 67 @@ -111,7 +120,7 @@ struct dhcp_client_node struct dhcp_client_node *next; u8_t chaddr[DHCP_MAX_HLEN]; ip4_addr_t ipaddr; - u32_t lease_end; + u32_t lease_end; /* lease expiry in sys_now() milliseconds */ }; /** @@ -148,9 +157,19 @@ dhcp_client_find_by_mac(struct dhcp_server *dhcpserver, const u8_t *chaddr, u8_t { struct dhcp_client_node *node; + /* + * Leases are stored as full Ethernet addresses. Comparing only hlen bytes + * would let a client with a shorter (e.g. one byte) hardware address claim + * the lease of any node that shares that prefix. + */ + if (hlen != DHCP_MAX_HLEN) + { + return NULL; + } + for (node = dhcpserver->node_list; node != NULL; node = node->next) { - if (memcmp(node->chaddr, chaddr, hlen) == 0) + if (memcmp(node->chaddr, chaddr, DHCP_MAX_HLEN) == 0) { return node; } @@ -182,6 +201,96 @@ dhcp_client_find_by_ip(struct dhcp_server *dhcpserver, const ip4_addr_t *ip) return NULL; } +/** +* Check whether a dhcp client lease has expired. +* +* @param node The dhcp client node +* @return 1 if expired, 0 otherwise +*/ +static rt_bool_t dhcp_client_lease_expired(const struct dhcp_client_node *node) +{ + u32_t lease_start = node->lease_end - DHCP_DEFAULT_LEASE_TIME_MS; + + /* Unsigned elapsed check avoids the ~24.8-day signed half-range false negative. */ + return (u32_t)(sys_now() - lease_start) >= DHCP_DEFAULT_LEASE_TIME_MS; +} + +/** +* Renew the lease of a dhcp client node. +* +* @param node The dhcp client node +*/ +static void dhcp_client_lease_renew(struct dhcp_client_node *node) +{ + node->lease_end = sys_now() + DHCP_DEFAULT_LEASE_TIME_MS; +} + +/** +* Remove expired dhcp client nodes from the list. +* +* @param dhcpserver The dhcp server +*/ +static void dhcp_client_remove_expired(struct dhcp_server *dhcpserver) +{ + struct dhcp_client_node *node = dhcpserver->node_list; + struct dhcp_client_node *prev = NULL; + struct dhcp_client_node *next; + + while (node != NULL) + { + next = node->next; + + if (dhcp_client_lease_expired(node)) + { + if (prev == NULL) + { + dhcpserver->node_list = next; + } + else + { + prev->next = next; + } + mem_free(node); + } + else + { + prev = node; + } + node = next; + } +} + +/** +* Tell whether a received frame is a DHCP request this server can serve. +* +* The server only serves Ethernet clients. A hardware address length other +* than 6 cannot be matched against the stored leases, so such a request is +* dropped at the entry instead of being compared byte by byte. +* +* @param msg The dhcp message +* @return 1 if the message may be handled, 0 otherwise +*/ +static rt_bool_t dhcp_msg_usable(const struct dhcp_msg *msg) +{ + return msg->op == DHCP_BOOTREQUEST && + msg->cookie == PP_HTONL(DHCP_MAGIC_COOKIE) && + msg->hlen == DHCP_MAX_HLEN; +} + +/** +* Tell whether a lease node belongs to the client of the dhcp message. +* +* @param node The dhcp client node +* @param msg The dhcp message +* @return 1 if the stored lease belongs to that client, 0 otherwise +*/ +static rt_bool_t dhcp_chaddr_equal(const struct dhcp_client_node *node, + const struct dhcp_msg *msg) +{ + return msg->hlen == DHCP_MAX_HLEN && + memcmp(node->chaddr, msg->chaddr, DHCP_MAX_HLEN) == 0; +} + /** * Find a dhcp client node by dhcp message * @@ -195,26 +304,27 @@ static struct dhcp_client_node * dhcp_client_find(struct dhcp_server *dhcpserver, struct dhcp_msg *msg, u8_t *opt_buf, u16_t len) { - u8_t *opt; - //u32_t ipaddr; struct dhcp_client_node *node; - node = dhcp_client_find_by_mac(dhcpserver, msg->chaddr, msg->hlen); - if (node != NULL) + LWIP_UNUSED_ARG(opt_buf); + LWIP_UNUSED_ARG(len); + + if (!dhcp_msg_usable(msg)) { - return node; + return NULL; } - opt = dhcp_server_option_find(opt_buf, len, DHCP_OPTION_REQUESTED_IP); - if (opt != NULL && opt[1] >= 4) + node = dhcp_client_find_by_mac(dhcpserver, msg->chaddr, msg->hlen); + if (node != NULL) { - node = dhcp_client_find_by_ip(dhcpserver, (ip4_addr_t *)(&opt[2])); - if (node != NULL) - { - return node; - } + return node; } + /* + * A REQUESTED_IP lookup cannot grant anything here: the MAC scan above + * covered the whole list, so a node at the requested IP belongs to a + * different client. + */ return NULL; } @@ -231,26 +341,34 @@ static struct dhcp_client_node * dhcp_client_alloc(struct dhcp_server *dhcpserver, struct dhcp_msg *msg, u8_t *opt_buf, u16_t len) { - u8_t *opt; u32_t ipaddr; u32_t first_candidate; struct dhcp_client_node *node; + LWIP_UNUSED_ARG(opt_buf); + LWIP_UNUSED_ARG(len); + + if (!dhcp_msg_usable(msg)) + { + return NULL; + } + node = dhcp_client_find_by_mac(dhcpserver, msg->chaddr, msg->hlen); if (node != NULL) { + dhcp_client_lease_renew(node); return node; } - opt = dhcp_server_option_find(opt_buf, len, DHCP_OPTION_REQUESTED_IP); - if (opt != NULL && opt[1] >= 4) - { - node = dhcp_client_find_by_ip(dhcpserver, (ip4_addr_t *)(&opt[2])); - if (node != NULL) - { - return node; - } - } + /* keep the current client's node, reclaim expired nodes of other clients */ + dhcp_client_remove_expired(dhcpserver); + + /* + * The requested IP was already looked up by MAC above. If it is in use, + * the ownership check there rejected it; the pool walk below only skips + * addresses that are still leased, so a foreign REQUESTED_IP can never be + * handed to the requester. + */ /* Check each pool address at most once. */ first_candidate = dhcpserver->current.addr; @@ -280,8 +398,10 @@ dhcp_client_alloc(struct dhcp_server *dhcpserver, struct dhcp_msg *msg, { return NULL; } - SMEMCPY(node->chaddr, msg->chaddr, (msg->hlen > sizeof(node->chaddr)) ? sizeof(node->chaddr) : msg->hlen); + memset(node->chaddr, 0, sizeof(node->chaddr)); + SMEMCPY(node->chaddr, msg->chaddr, DHCP_MAX_HLEN); node->ipaddr = dhcpserver->current; + dhcp_client_lease_renew(node); node->next = dhcpserver->node_list; dhcpserver->node_list = node; @@ -379,20 +499,11 @@ dhcp_server_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t pbuf_free(p); msg = (struct dhcp_msg *)q->payload; - if (msg->op != DHCP_BOOTREQUEST) - { - LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("not a DHCP request message, but type %"U16_F"\n", (u16_t)msg->op)); - goto free_pbuf_and_return; - } - - if (msg->cookie != PP_HTONL(DHCP_MAGIC_COOKIE)) - { - LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("bad DHCP_MAGIC_COOKIE!\n")); - goto free_pbuf_and_return; - } - - if (msg->hlen > DHCP_MAX_HLEN) + if (!dhcp_msg_usable(msg)) { + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, + ("drop DHCP frame: op %" U16_F " cookie 0x%08" X32_F " hlen %" U16_F "\n", + (u16_t)msg->op, msg->cookie, (u16_t)msg->hlen)); goto free_pbuf_and_return; } @@ -408,7 +519,6 @@ dhcp_server_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t { goto free_pbuf_and_return; } - node->lease_end = DHCP_DEFAULT_LIVE_TIME; /* create dhcp offer and send */ msg->op = DHCP_BOOTREPLY; msg->hops = 0; @@ -485,7 +595,7 @@ dhcp_server_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t if (node != NULL) { /* Send ack */ - node->lease_end = DHCP_DEFAULT_LIVE_TIME; + dhcp_client_lease_renew(node); /* create dhcp offer and send */ msg->op = DHCP_BOOTREPLY; msg->hops = 0; @@ -595,7 +705,7 @@ dhcp_server_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t for (node = dhcp_server->node_list; node != NULL; node = node->next) { - if (memcmp(node->chaddr, msg->chaddr, msg->hlen) == 0) + if (dhcp_chaddr_equal(node, msg)) { if (node == dhcp_server->node_list) { @@ -615,7 +725,7 @@ dhcp_server_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t mem_free(node); } } - else if (msg_type == DHCP_DECLINE) + else if (msg_type == DHCP_DECLINE) { ; } @@ -625,12 +735,132 @@ dhcp_server_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t } } } + /* Reclaim expired leases on incoming packets too, shortening gaps between checks. */ + dhcp_client_remove_expired(dhcp_server); } free_pbuf_and_return: pbuf_free(q); } +/* + * The DHCP server lifecycle must run on the lwIP TCP/IP thread. + * + * sys_timeout() / sys_untimeout() are not safe from any other thread: + * - lwIP 2.0.3 (the RT-Thread default) runs sys_timeouts_mbox_fetch() and + * sys_check_timeouts() outside LOCK_TCPIP_CORE(), so posting or cancelling + * a timeout from another thread races with the tcpip thread on the + * next_timeout list - even when LWIP_TCPIP_CORE_LOCKING == 1; + * - when LWIP_TCPIP_CORE_LOCKING == 0, LOCK_TCPIP_CORE() is an empty macro + * and protects nothing at all; + * - a timeout posted from outside does not wake a blocked tcpip thread, so + * the periodic recycle would be delayed until unrelated traffic arrives. + * + * dhcp_server_recv() and dhcp_server_periodic_recycle() already run on that + * thread, so the start/stop entry points are marshalled there with + * tcpip_callback(). The server, its lease list and its timeout then live in + * one context on every supported lwIP (2.0.3 / 2.1.2 / 2.2.1) and with either + * setting of LWIP_TCPIP_CORE_LOCKING. + */ +typedef void (*dhcpd_tcpip_fn)(void *arg); + +struct dhcpd_tcpip_call +{ + dhcpd_tcpip_fn fn; + void *arg; + sys_sem_t done; +}; + +/* + * Tell whether the caller already runs on the lwIP TCP/IP thread: posting a + * callback from that thread and waiting for it would deadlock. The tcpip + * thread is created by the lwIP port with TCPIP_THREAD_NAME, the same way + * components/net/lwip/port/ethernetif.c identifies it. + */ +static rt_bool_t dhcpd_in_tcpip_thread(void) +{ + rt_thread_t self = rt_thread_self(); + + if (self == RT_NULL) + { + return RT_FALSE; + } + + return self == rt_thread_find(TCPIP_THREAD_NAME); +} + +static void dhcpd_tcpip_call_entry(void *arg) +{ + struct dhcpd_tcpip_call *call = (struct dhcpd_tcpip_call *)arg; + + call->fn(call->arg); + sys_sem_signal(&call->done); +} + +/* + * Run fn on the tcpip thread and wait for its completion. + * + * The callback message is handled with the core lock held by lwIP (2.0.3, + * 2.1.2 and 2.2.1 alike), so fn must not take LOCK_TCPIP_CORE() again. + * + * @return ERR_OK when fn ran, or the tcpip_callback()/sys_sem_new() error + */ +static err_t dhcpd_run_in_tcpip(dhcpd_tcpip_fn fn, void *arg) +{ + struct dhcpd_tcpip_call call; + err_t err; + + if (dhcpd_in_tcpip_thread()) + { + fn(arg); + return ERR_OK; + } + + err = sys_sem_new(&call.done, 0); + if (err != ERR_OK) + { + return err; + } + + call.fn = fn; + call.arg = arg; + + err = tcpip_callback(dhcpd_tcpip_call_entry, &call); + if (err != ERR_OK) + { + sys_sem_free(&call.done); + return err; + } + + sys_sem_wait(&call.done); + sys_sem_free(&call.done); + + return ERR_OK; +} + +/** +* Periodically reclaim expired leases from every registered server. +* +* Registered and unregistered from the tcpip thread only, and itself executed +* by the lwIP timeout path on that same thread, so no lock is needed to walk +* the server list or the lease lists. +*/ +static void dhcp_server_periodic_recycle(void *arg) +{ + struct dhcp_server *server; + LWIP_UNUSED_ARG(arg); + + for (server = lw_dhcp_server; server != NULL; server = server->next) + { + dhcp_client_remove_expired(server); + } + + if (lw_dhcp_server != NULL) + { + sys_timeout(DHCPD_RECYCLE_INTERVAL_MS, dhcp_server_periodic_recycle, NULL); + } +} + /** * start dhcp server for a netif * @@ -640,9 +870,10 @@ dhcp_server_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t * @return lwIP error code * - ERR_OK - No error * - ERR_MEM - Out of memory +* +* Must run on the lwIP tcpip thread, see dhcpd_run_in_tcpip(). */ -err_t -dhcp_server_start(struct netif *netif, ip4_addr_t *start, ip4_addr_t *end) +static err_t dhcp_server_start_core(struct netif *netif, ip4_addr_t *start, ip4_addr_t *end) { struct dhcp_server *dhcp_server; err_t err; @@ -681,7 +912,7 @@ dhcp_server_start(struct netif *netif, ip4_addr_t *start, ip4_addr_t *end) dhcp_server->pcb = udp_new(); if (dhcp_server->pcb == NULL) { - LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_server_start(): could not obtain pcb\n")); + LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_server_start(): could not obtain pcb\n")); mem_free(dhcp_server); return ERR_MEM; } @@ -697,10 +928,15 @@ dhcp_server_start(struct netif *netif, ip4_addr_t *start, ip4_addr_t *end) return err; } //udp_connect(dhcp_server->pcb, IP_ADDR_ANY, DHCP_CLIENT_PORT); + /* set up the recv callback and argument */ udp_recv(dhcp_server->pcb, dhcp_server_recv, dhcp_server); /* Publish the server only after all resources are ready. */ + if (lw_dhcp_server == NULL) + { + sys_timeout(DHCPD_RECYCLE_INTERVAL_MS, dhcp_server_periodic_recycle, NULL); + } dhcp_server->next = lw_dhcp_server; lw_dhcp_server = dhcp_server; LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp_server_start(): starting DHCP server\n")); @@ -708,16 +944,46 @@ dhcp_server_start(struct netif *netif, ip4_addr_t *start, ip4_addr_t *end) return ERR_OK; } +struct dhcp_server_start_args +{ + struct netif *netif; + ip4_addr_t start; + ip4_addr_t end; + err_t err; +}; + +static void dhcp_server_start_entry(void *arg) +{ + struct dhcp_server_start_args *args = (struct dhcp_server_start_args *)arg; + + args->err = dhcp_server_start_core(args->netif, &args->start, &args->end); +} + +err_t dhcp_server_start(struct netif *netif, ip4_addr_t *start, ip4_addr_t *end) +{ + struct dhcp_server_start_args args; + err_t err; + + args.netif = netif; + args.start = *start; + args.end = *end; + args.err = ERR_MEM; /* reported when the callback never runs */ + + err = dhcpd_run_in_tcpip(dhcp_server_start_entry, &args); + + return (err == ERR_OK) ? args.err : err; +} + extern void set_if(const char *netif_name, const char *ip_addr, const char *gw_addr, const char *nm_addr); -void dhcpd_start(const char *netif_name) +static void dhcpd_start_core(const char *netif_name) { - struct netif *netif = netif_list; + struct netif *netif; err_t res; DEBUG_PRINTF("%s: %s\r\n", __FUNCTION__, netif_name); - LWIP_NETIF_LOCK(); + netif = netif_list; if (strlen(netif_name) > sizeof(netif->name)) { DEBUG_PRINTF("network interface name too long!\r\n"); @@ -727,7 +993,9 @@ void dhcpd_start(const char *netif_name) while (netif != RT_NULL) { if (strncmp(netif_name, netif->name, sizeof(netif->name)) == 0) + { break; + } netif = netif->next; if (netif == RT_NULL) @@ -779,7 +1047,7 @@ void dhcpd_start(const char *netif_name) ip4addr_aton(str_tmp, &ip_end); DEBUG_PRINTF("ip_end: [%s]\r\n", str_tmp); - res = dhcp_server_start(netif, &ip_start, &ip_end); + res = dhcp_server_start_core(netif, &ip_start, &ip_end); if (res != 0) { DEBUG_PRINTF("dhcp_server_start res: %d.\r\n", (int)res); @@ -787,19 +1055,34 @@ void dhcpd_start(const char *netif_name) } _exit: - LWIP_NETIF_UNLOCK(); return; } -void dhcpd_stop(const char *netif_name) +static void dhcpd_start_entry(void *arg) +{ + dhcpd_start_core((const char *)arg); +} + +void dhcpd_start(const char *netif_name) +{ + err_t err = dhcpd_run_in_tcpip(dhcpd_start_entry, (void *)netif_name); + + if (err != ERR_OK) + { + DEBUG_PRINTF("%s: failed to run on the tcpip thread, err=%d\r\n", + __FUNCTION__, (int)err); + } +} + +static void dhcpd_stop_core(const char *netif_name) { struct dhcp_server *dhcp_server, *server_node; - struct netif *netif = netif_list; + struct netif *netif; struct dhcp_client_node *node, *next; DEBUG_PRINTF("%s: %s\r\n", __FUNCTION__, netif_name); - LWIP_NETIF_LOCK(); + netif = netif_list; if (strlen(netif_name) > sizeof(netif->name)) { DEBUG_PRINTF("network interface name too long!\r\n"); @@ -809,7 +1092,9 @@ void dhcpd_stop(const char *netif_name) while (netif != RT_NULL) { if (strncmp(netif_name, netif->name, sizeof(netif->name)) == 0) + { break; + } netif = netif->next; if (netif == RT_NULL) @@ -866,8 +1151,28 @@ void dhcpd_stop(const char *netif_name) } mem_free(dhcp_server); + if (lw_dhcp_server == NULL) + { + sys_untimeout(dhcp_server_periodic_recycle, NULL); + } set_if(netif_name, "0.0.0.0", "0.0.0.0", "0.0.0.0"); _exit: - LWIP_NETIF_UNLOCK(); + return; +} + +static void dhcpd_stop_entry(void *arg) +{ + dhcpd_stop_core((const char *)arg); +} + +void dhcpd_stop(const char *netif_name) +{ + err_t err = dhcpd_run_in_tcpip(dhcpd_stop_entry, (void *)netif_name); + + if (err != ERR_OK) + { + DEBUG_PRINTF("%s: failed to run on the tcpip thread, err=%d\r\n", + __FUNCTION__, (int)err); + } } diff --git a/components/net/lwip-dhcpd/test/.gitignore b/components/net/lwip-dhcpd/test/.gitignore new file mode 100644 index 00000000000..4ffdb869e3d --- /dev/null +++ b/components/net/lwip-dhcpd/test/.gitignore @@ -0,0 +1,2 @@ +/dhcpd_lease_test +/dhcpd_lease_test.dSYM/ diff --git a/components/net/lwip-dhcpd/test/Makefile b/components/net/lwip-dhcpd/test/Makefile new file mode 100644 index 00000000000..cdc5325dd44 --- /dev/null +++ b/components/net/lwip-dhcpd/test/Makefile @@ -0,0 +1,19 @@ +CC ?= cc +CFLAGS ?= -std=c99 -O1 -g -Wall -Wextra \ + -Wno-unused-function -Wno-unused-parameter -Wno-pointer-to-int-cast +CPPFLAGS += -I mock + +BIN := dhcpd_lease_test + +.PHONY: all run clean + +all: run + +$(BIN): test_dhcpd_lease.c ../dhcp_server_raw.c mock/mock_lwip.h + $(CC) $(CFLAGS) $(CPPFLAGS) test_dhcpd_lease.c -o $(BIN) + +run: $(BIN) + ./$(BIN) + +clean: + rm -f $(BIN) \ No newline at end of file diff --git a/components/net/lwip-dhcpd/test/README.md b/components/net/lwip-dhcpd/test/README.md new file mode 100644 index 00000000000..e8821c38c27 --- /dev/null +++ b/components/net/lwip-dhcpd/test/README.md @@ -0,0 +1,47 @@ +# DHCPD lease host test + +Host-side regression test for `../dhcp_server_raw.c`. It compiles the +production source against the lwIP / RT-Thread stubs in `mock/`, so the lease +lookup, allocation, expiry and lifecycle paths under test are the real ones. + +Run it with: + +```sh +make run +``` + +or directly: + +```sh +cc -std=c99 -Wall -Wextra -Wno-unused-function -Wno-unused-parameter \ + -I mock test_dhcpd_lease.c -o /tmp/dhcpd_lease_test +/tmp/dhcpd_lease_test +``` + +No board, QEMU or RT-Thread build is needed: the whole lwIP surface used by +this component is stubbed in `mock/mock_lwip.h`. The test exits non-zero when +a check fails, so it can run in CI (see +`.github/workflows/dhcpd_host_test.yml`). + +## What it covers + +- `REQUESTED_IP` ownership: a lease is only returned to its own MAC. +- Expired-lease reclaim in `dhcp_client_remove_expired()` / allocation. +- `sys_now()` wrap-around handling of the lease expiry arithmetic. +- The Ethernet-only entry gate (`hlen == 6`) and short hardware addresses. +- Start/stop register and cancel exactly one periodic recycle timeout, a + repeated start does not stack a second one, and stop leaves no timer behind. +- Calls made from the tcpip thread itself run in place instead of deadlocking + on `tcpip_callback()`. +- Full pool: allocation fails while all addresses are leased, and succeeds + after the periodic timer reclaims them without any incoming packet. +- A lease that crosses the 32-bit millisecond wrap stays valid, and more than + a whole `2^32 ms` idle period with the recycle timer running keeps the pool + usable. + +## What it does not cover + +The mock models the lwIP tcpip thread (timeouts and callbacks), but it is +single-threaded: it cannot reproduce the real race in lwIP 2.0.3's +`sys_check_timeouts()` and it does not exercise a board or QEMU. A firmware +cross build is still required for that. \ No newline at end of file diff --git a/components/net/lwip-dhcpd/test/mock/lwip/dhcp.h b/components/net/lwip-dhcpd/test/mock/lwip/dhcp.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/dhcp.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/lwip/inet_chksum.h b/components/net/lwip-dhcpd/test/mock/lwip/inet_chksum.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/inet_chksum.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/lwip/init.h b/components/net/lwip-dhcpd/test/mock/lwip/init.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/init.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/lwip/ip.h b/components/net/lwip-dhcpd/test/mock/lwip/ip.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/ip.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/lwip/opt.h b/components/net/lwip-dhcpd/test/mock/lwip/opt.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/opt.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/lwip/prot/dhcp.h b/components/net/lwip-dhcpd/test/mock/lwip/prot/dhcp.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/prot/dhcp.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/lwip/sockets.h b/components/net/lwip-dhcpd/test/mock/lwip/sockets.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/sockets.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/lwip/sys.h b/components/net/lwip-dhcpd/test/mock/lwip/sys.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/sys.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/lwip/tcpip.h b/components/net/lwip-dhcpd/test/mock/lwip/tcpip.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/tcpip.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/lwip/timeouts.h b/components/net/lwip-dhcpd/test/mock/lwip/timeouts.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/lwip/timeouts.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/mock_lwip.h b/components/net/lwip-dhcpd/test/mock/mock_lwip.h new file mode 100644 index 00000000000..34105d91360 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/mock_lwip.h @@ -0,0 +1,649 @@ +/* + * Minimal lwIP / RT-Thread stubs for the host-side DHCPD lease test. + * + * Only the declarations that dhcp_server_raw.c references are provided. The + * packet path is a no-op; the test drives the lease bookkeeping + * (dhcp_client_find / dhcp_client_alloc / dhcp_client_remove_expired) and the + * lifecycle entry points directly. + * + * The timeout and tcpip_callback stubs are not empty: they model the lwIP + * tcpip thread closely enough to verify that start/stop register and cancel + * the periodic recycle timer, and that the recycle handler runs from that + * thread. See the "tcpip thread" section below. + * + * This header is used by test/test_dhcpd_lease.c only; firmware builds keep + * using the real lwIP headers. + */ + +#ifndef DHCPD_TEST_MOCK_LWIP_H +#define DHCPD_TEST_MOCK_LWIP_H + +#include +#include +#include +#include +#include +#include + +/* ---------------------------------------------------------------- types */ + +typedef uint8_t u8_t; +typedef uint16_t u16_t; +typedef uint32_t u32_t; +typedef int32_t s32_t; +typedef int8_t err_t; +typedef int rt_bool_t; +typedef unsigned long rt_ubase_t; + +#define RT_NULL ((void *)0) +#define RT_FALSE 0 +#define RT_TRUE 1 +#define SMEMCPY(dst, src, len) memcpy((dst), (src), (len)) + +#define ERR_OK 0 +#define ERR_MEM (-1) + +/* version gates evaluated by dhcp_server_raw.c (override with -DLWIP_VERSION) */ +#ifndef LWIP_VERSION +#define LWIP_VERSION 0x02010000U +#endif +#ifndef LWIP_IPV4 +#define LWIP_IPV4 1 +#endif +#ifndef LWIP_DHCP +#define LWIP_DHCP 0 +#endif + +/* ---------------------------------------------------------------- debug */ + +#define LWIP_DBG_ON 0x80U +#define DHCP_DEBUG LWIP_DBG_ON +#define LWIP_DBG_TRACE 0x40U +#define LWIP_DBG_LEVEL_WARNING 0x01U +#define U16_F "u" +#define X32_F "x" + +#define LWIP_DEBUGF(debug, message) \ + do \ + { \ + (void)(debug); \ + } while (0) +#define LWIP_UNUSED_ARG(x) ((void)(x)) + +static inline int mock_printf(const char *fmt, ...) +{ + va_list ap; + int printed; + + va_start(ap, fmt); + printed = vprintf(fmt, ap); + va_end(ap); + + return printed; +} + +#define rt_kprintf mock_printf + +/* ---------------------------------------------------------- fake runtime */ + +static u32_t mock_now_ms; +static size_t mock_mem_live; + +static inline void mock_reset_clock(u32_t now_ms) +{ + mock_now_ms = now_ms; +} +static inline size_t mock_mem_live_count(void) +{ + return mock_mem_live; +} + +static inline u32_t sys_now(void) +{ + return mock_now_ms; +} + +static inline void *mem_malloc(size_t size) +{ + void *ptr = malloc(size); + + if (ptr != NULL) + { + mock_mem_live++; + } + + return ptr; +} + +static inline void mem_free(void *ptr) +{ + if (ptr != NULL) + { + mock_mem_live--; + free(ptr); + } +} + +/* --------------------------------------------------------- fake threads */ + +#ifndef RT_NAME_MAX +#define RT_NAME_MAX 8 +#endif + +/* lwIP port value, see components/net/lwip/port/lwipopts.h */ +#define TCPIP_THREAD_NAME "tcpip" + +struct rt_thread +{ + char name[RT_NAME_MAX]; +}; + +typedef struct rt_thread *rt_thread_t; + +static struct rt_thread mock_caller_thread = { "main" }; + +static inline rt_thread_t rt_thread_self(void) +{ + return &mock_caller_thread; +} + +static inline void mock_set_caller_name(const char *name) +{ + memset(mock_caller_thread.name, 0, sizeof(mock_caller_thread.name)); + strncpy(mock_caller_thread.name, name, sizeof(mock_caller_thread.name) - 1); +} + +/* only one fake thread exists; it is the tcpip thread when named so */ +static inline rt_thread_t rt_thread_find(char *name) +{ + return (strcmp(mock_caller_thread.name, name) == 0) ? &mock_caller_thread : RT_NULL; +} + +/* ---------------------------------------------------------------- timers */ + +typedef void (*sys_timeout_handler)(void *arg); +typedef void (*tcpip_callback_fn)(void *ctx); + +struct mock_timer +{ + struct mock_timer *next; + sys_timeout_handler handler; + void *arg; + u32_t due_ms; +}; + +static struct mock_timer *mock_timers; +static size_t mock_timer_live; +static unsigned long mock_timer_fires; + +static inline size_t mock_timer_count(void) +{ + return mock_timer_live; +} + +static inline int mock_timer_registered(sys_timeout_handler handler) +{ + struct mock_timer *timer; + + for (timer = mock_timers; timer != NULL; timer = timer->next) + { + if (timer->handler == handler) + { + return 1; + } + } + + return 0; +} + +/* like lwIP sys_timeout(): one new entry, due at now + msecs */ +static inline void sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg) +{ + struct mock_timer *timer = (struct mock_timer *)calloc(1, sizeof(*timer)); + + if (timer == NULL) + { + printf("mock sys_timeout: out of memory\n"); + exit(1); + } + + timer->handler = handler; + timer->arg = arg; + timer->due_ms = mock_now_ms + msecs; + timer->next = mock_timers; + mock_timers = timer; + mock_timer_live++; +} + +/* like lwIP sys_untimeout(): drop every entry with this handler/arg pair */ +static inline void sys_untimeout(sys_timeout_handler handler, void *arg) +{ + struct mock_timer **link = &mock_timers; + + while (*link != NULL) + { + struct mock_timer *timer = *link; + + if (timer->handler == handler && timer->arg == arg) + { + *link = timer->next; + free(timer); + mock_timer_live--; + } + else + { + link = &timer->next; + } + } +} + +/* Run every expired timeout, the way the tcpip thread does. */ +static inline void mock_run_timeouts(void) +{ + for (;;) + { + struct mock_timer **link = &mock_timers; + struct mock_timer *timer = NULL; + sys_timeout_handler handler; + void *arg; + + while (*link != NULL) + { + /* TIME_LESS_THAN(): wrap-safe "now >= due" */ + if ((s32_t)(mock_now_ms - (*link)->due_ms) >= 0) + { + timer = *link; + break; + } + link = &(*link)->next; + } + + if (timer == NULL) + { + return; + } + + /* lwIP frees the entry before invoking the handler, and the handler + * may register the next period from inside the call. */ + *link = timer->next; + handler = timer->handler; + arg = timer->arg; + free(timer); + mock_timer_live--; + + mock_timer_fires++; + handler(arg); + } +} + +/* Advance the mock clock and run the timeouts that became due. */ +static inline void mock_advance_clock(u32_t elapsed_ms) +{ + mock_now_ms += elapsed_ms; + mock_run_timeouts(); +} + +/* ------------------------------------------------ tcpip thread marshalling */ + +#define MOCK_TCPIP_QUEUE_DEPTH 4 + +struct mock_tcpip_msg +{ + tcpip_callback_fn fn; + void *ctx; +}; + +static struct mock_tcpip_msg mock_tcpip_queue[MOCK_TCPIP_QUEUE_DEPTH]; +static size_t mock_tcpip_queued; +static unsigned long mock_tcpip_callbacks; + +static inline unsigned long mock_tcpip_callback_count(void) +{ + return mock_tcpip_callbacks; +} + +/* like lwIP tcpip_callback(): queue the function for the tcpip thread */ +static inline err_t tcpip_callback(tcpip_callback_fn fn, void *ctx) +{ + if (mock_tcpip_queued == MOCK_TCPIP_QUEUE_DEPTH) + { + return ERR_MEM; + } + + mock_tcpip_queue[mock_tcpip_queued].fn = fn; + mock_tcpip_queue[mock_tcpip_queued].ctx = ctx; + mock_tcpip_queued++; + mock_tcpip_callbacks++; + + return ERR_OK; +} + +/* Run queued tcpip callbacks in order, as the tcpip thread would. */ +static inline void mock_tcpip_run(void) +{ + while (mock_tcpip_queued > 0) + { + struct mock_tcpip_msg msg = mock_tcpip_queue[0]; + size_t i; + + for (i = 1; i < mock_tcpip_queued; i++) + { + mock_tcpip_queue[i - 1] = mock_tcpip_queue[i]; + } + mock_tcpip_queued--; + + msg.fn(msg.ctx); + } +} + +/* -------------------------------------------------------------- semaphores */ + +typedef struct +{ + int count; +} sys_sem_t; + +static inline err_t sys_sem_new(sys_sem_t *sem, u8_t count) +{ + sem->count = count; + return ERR_OK; +} + +/* + * A thread that waits for a tcpip callback lets the "tcpip thread" run the + * queued message. If nothing signals it, the production code would sleep + * forever, so fail loudly instead of hanging the test. + */ +static inline u32_t sys_sem_wait(sys_sem_t *sem) +{ + mock_tcpip_run(); + + if (sem->count == 0) + { + printf("mock sys_sem_wait: callback never signaled (deadlock)\n"); + exit(1); + } + + sem->count--; + return 0; +} + +static inline void sys_sem_signal(sys_sem_t *sem) +{ + sem->count++; +} + +static inline void sys_sem_free(sys_sem_t *sem) +{ + (void)sem; +} + +/* ----------------------------------------------------------- core locking */ + +/* + * The production code never takes the core lock itself: every lifecycle call + * is marshalled to the tcpip thread. Keep the macros around so a future + * regression that reintroduces LOCK_TCPIP_CORE() still compiles. + */ +#define LOCK_TCPIP_CORE() \ + do \ + { \ + } while (0) +#define UNLOCK_TCPIP_CORE() \ + do \ + { \ + } while (0) + +/* ------------------------------------------------------------- addresses */ + +typedef struct +{ + u32_t addr; +} ip4_addr_t; + +typedef struct +{ + ip4_addr_t ip4; +} ip_addr_t; + +static inline u32_t mock_bswap32(u32_t value) +{ +#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) + return value; +#else + return ((value & 0x000000ffU) << 24) | ((value & 0x0000ff00U) << 8) | + ((value & 0x00ff0000U) >> 8) | ((value & 0xff000000U) >> 24); +#endif +} + +#undef htonl +#undef ntohl +#define htonl(value) mock_bswap32((u32_t)(value)) +#define ntohl(value) mock_bswap32((u32_t)(value)) +#define PP_HTONL(value) htonl(value) + +#define INADDR_BROADCAST 0xffffffffUL +#define IP_ADDR_ANY ((const ip_addr_t *)0) + +#define ip_2_ip4(ipaddr) (&(ipaddr)->ip4) + +static inline int ip4_addr_cmp(const ip4_addr_t *left, const ip4_addr_t *right) +{ + return left->addr == right->addr; +} + +static inline int ip4addr_aton(const char *cp, ip4_addr_t *addr) +{ + unsigned int part[4]; + + if (sscanf(cp, "%u.%u.%u.%u", &part[0], &part[1], &part[2], &part[3]) != 4) + { + return 0; + } + + addr->addr = htonl((part[0] << 24) | (part[1] << 16) | (part[2] << 8) | part[3]); + + return 1; +} + +/* ---------------------------------------------------------------- netif */ + +struct netif +{ + char name[2]; + ip_addr_t ip_addr; + ip_addr_t netmask; + struct netif *next; +}; + +static struct netif *netif_list; + +static inline void netif_set_up(struct netif *netif) +{ + (void)netif; +} + +static inline void dhcp_stop(struct netif *netif) +{ + (void)netif; +} + +/* + * Matches the extern declaration inside dhcp_server_raw.c (defined by + * components/net/lwip/port/ethernetif.c in a firmware build). Do not make it + * static: the test translation unit includes the production source file. + */ +void set_if(const char *netif_name, const char *ip_addr, + const char *gw_addr, const char *nm_addr) +{ + (void)netif_name; + (void)ip_addr; + (void)gw_addr; + (void)nm_addr; +} + +/* ------------------------------------------------------------ udp / pbuf */ + +struct udp_pcb; +struct pbuf; + +typedef void (*mock_udp_recv_fn)(void *arg, struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *addr, u16_t port); + +struct udp_pcb +{ + int unused; +}; + +struct pbuf +{ + void *payload; + u16_t len; + u16_t tot_len; +}; + +#define SOF_BROADCAST 0x0020U + +#define PBUF_TRANSPORT 0 +#define PBUF_RAM 0 + +#define ip_set_option(pcb, option) \ + do \ + { \ + (void)(pcb); \ + (void)(option); \ + } while (0) + +#define MOCK_UDP_PCB_POOL 4 +static struct udp_pcb mock_udp_pcbs[MOCK_UDP_PCB_POOL]; +static size_t mock_udp_used; + +static inline struct udp_pcb *udp_new(void) +{ + if (mock_udp_used == MOCK_UDP_PCB_POOL) + { + return NULL; + } + + return &mock_udp_pcbs[mock_udp_used++]; +} + +static inline err_t udp_bind(struct udp_pcb *pcb, const ip_addr_t *local_ip, + u16_t local_port) +{ + (void)pcb; + (void)local_ip; + (void)local_port; + + return ERR_OK; +} + +static inline void udp_remove(struct udp_pcb *pcb) +{ + (void)pcb; +} + +static inline void udp_disconnect(struct udp_pcb *pcb) +{ + (void)pcb; +} + +static inline void udp_recv(struct udp_pcb *pcb, mock_udp_recv_fn recv, void *recv_arg) +{ + (void)pcb; + (void)recv; + (void)recv_arg; +} + +static inline err_t udp_sendto_if(struct udp_pcb *pcb, struct pbuf *p, + const ip_addr_t *dst_ip, u16_t dst_port, + struct netif *netif) +{ + (void)pcb; + (void)p; + (void)dst_ip; + (void)dst_port; + (void)netif; + + return ERR_OK; +} + +static inline struct pbuf *pbuf_alloc(int layer, u16_t length, int type) +{ + (void)layer; + (void)length; + (void)type; + + return NULL; +} + +static inline void pbuf_free(struct pbuf *p) +{ + (void)p; +} + +static inline u16_t pbuf_copy(struct pbuf *dst, const struct pbuf *src) +{ + (void)dst; + (void)src; + + return 0; +} + +static inline void pbuf_realloc(struct pbuf *p, u16_t size) +{ + (void)p; + (void)size; +} + +/* ------------------------------------------------------------ DHCP wire */ + +#define DHCP_BOOTREQUEST 1 +#define DHCP_BOOTREPLY 2 + +#define DHCP_OPTION_PAD 0 +#define DHCP_OPTION_SUBNET_MASK 1 +#define DHCP_OPTION_ROUTER 3 +#define DHCP_OPTION_DNS_SERVER 6 +#define DHCP_OPTION_REQUESTED_IP 50 +#define DHCP_OPTION_LEASE_TIME 51 +#define DHCP_OPTION_MESSAGE_TYPE 53 +#define DHCP_OPTION_SERVER_ID 54 +#define DHCP_OPTION_END 255 + +#define DHCP_DISCOVER 1 +#define DHCP_OFFER 2 +#define DHCP_REQUEST 3 +#define DHCP_DECLINE 4 +#define DHCP_ACK 5 +#define DHCP_NAK 6 +#define DHCP_RELEASE 7 +#define DHCP_INFORM 8 + +#define DHCP_MAGIC_COOKIE 0x63825363UL + +struct __attribute__((packed)) dhcp_msg +{ + u8_t op; + u8_t htype; + u8_t hlen; + u8_t hops; + u32_t xid; + u16_t secs; + u16_t flags; + u8_t ciaddr[4]; + u8_t yiaddr[4]; + u8_t siaddr[4]; + u8_t giaddr[4]; + u8_t chaddr[16]; + u8_t sname[64]; + u8_t file[128]; + u32_t cookie; +}; + +/* matches the lwIP DHCP wire layout used by dhcp_server_raw.c */ +#define DHCP_OPTIONS_OFS 240 + +typedef char dhcp_msg_layout_check[(sizeof(struct dhcp_msg) == DHCP_OPTIONS_OFS) ? 1 : -1]; + +#endif /* DHCPD_TEST_MOCK_LWIP_H */ diff --git a/components/net/lwip-dhcpd/test/mock/netif/etharp.h b/components/net/lwip-dhcpd/test/mock/netif/etharp.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/netif/etharp.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/netif/ethernetif.h b/components/net/lwip-dhcpd/test/mock/netif/ethernetif.h new file mode 100644 index 00000000000..f686058c308 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/netif/ethernetif.h @@ -0,0 +1,2 @@ +/* Host-test stub: real declaration lives in mock_lwip.h. */ +#include diff --git a/components/net/lwip-dhcpd/test/mock/rtthread.h b/components/net/lwip-dhcpd/test/mock/rtthread.h new file mode 100644 index 00000000000..eb32aa681f4 --- /dev/null +++ b/components/net/lwip-dhcpd/test/mock/rtthread.h @@ -0,0 +1,2 @@ +/* Host-test stub for RT-Thread APIs used by dhcp_server_raw.c. */ +#include diff --git a/components/net/lwip-dhcpd/test/test_dhcpd_lease.c b/components/net/lwip-dhcpd/test/test_dhcpd_lease.c new file mode 100644 index 00000000000..6b06ab8ca26 --- /dev/null +++ b/components/net/lwip-dhcpd/test/test_dhcpd_lease.c @@ -0,0 +1,713 @@ +/* + * Regression test for the DHCP server lease and lifecycle paths. + * + * The test compiles the production implementation (../dhcp_server_raw.c) + * against the lwIP / RT-Thread stubs in ./mock, so every assertion below runs + * through the real dhcp_client_find(), dhcp_client_alloc(), + * dhcp_client_remove_expired(), dhcp_server_periodic_recycle() and the + * dhcpd_start()/dhcpd_stop() marshalling. Nothing here re-implements the + * matching, the expiry rule or the timer bookkeeping. + * + * The mock runs sys_timeout()/sys_untimeout() and tcpip_callback() like the + * lwIP tcpip thread does, so the cases below also fail if start/stop stop + * registering, cancel or re-arm the periodic recycle timer correctly. + * + * Build and run (host, no board required): + * + * cd components/net/lwip-dhcpd/test + * make run + * + * or directly: + * + * cc -std=c99 -Wall -Wextra -Wno-unused-function -Wno-unused-parameter \ + * -I mock test_dhcpd_lease.c -o /tmp/dhcpd_lease_test + * /tmp/dhcpd_lease_test + */ + +#include "../dhcp_server_raw.c" + +#define LEASE_MS DHCP_DEFAULT_LEASE_TIME_MS + +/* build an address in lwIP's network byte order */ +#define IP4(a, b, c, d) \ + ((u32_t)htonl((((u32_t)(a)) << 24) | (((u32_t)(b)) << 16) | \ + (((u32_t)(c)) << 8) | ((u32_t)(d)))) + +static int test_failures; + +#define CHECK(expr) \ + do \ + { \ + if (!(expr)) \ + { \ + printf(" FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); \ + test_failures++; \ + } \ + } while (0) + +static const u8_t mac_owner[6] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55 }; +static const u8_t mac_other[6] = { 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; +static const u8_t mac_third[6] = { 0x02, 0x00, 0x00, 0x00, 0x00, 0x01 }; + +/* ------------------------------------------------------------ fixtures */ + +/* forget every timer, including entries a failed case left behind */ +static void mock_clear_timers(void) +{ + struct mock_timer *timer = mock_timers; + struct mock_timer *next; + + while (timer != NULL) + { + next = timer->next; + free(timer); + timer = next; + } + + mock_timers = NULL; + mock_timer_live = 0; +} + +/* + * Reset the fake world: no server, no timer, no callback, an empty "tcpip" + * mailbox and a caller thread that is not the tcpip thread. + */ +static void mock_world_reset(u32_t now_ms) +{ + mock_reset_clock(now_ms); + mock_set_caller_name("main"); + mock_udp_used = 0; + mock_tcpip_queued = 0; + mock_tcpip_callbacks = 0; + mock_timer_fires = 0; + netif_list = NULL; + mock_clear_timers(); +} + +static void netif_fixture_init(struct netif *netif, const char *name) +{ + memset(netif, 0, sizeof(*netif)); + netif->name[0] = name[0]; + netif->name[1] = name[1]; + netif->next = NULL; +} + +static void lease_server_init(struct dhcp_server *server) +{ + memset(server, 0, sizeof(*server)); +} + +/* fixture only: put a lease node in the list, as dhcp_client_alloc() would */ +static struct dhcp_client_node *lease_add(struct dhcp_server *server, + const u8_t *chaddr, u32_t ipaddr, + u32_t lease_end) +{ + struct dhcp_client_node *node; + + node = mem_malloc(sizeof(*node)); + if (node == NULL) + { + printf("out of memory while building the test fixture\n"); + exit(1); + } + + memset(node, 0, sizeof(*node)); + SMEMCPY(node->chaddr, chaddr, DHCP_MAX_HLEN); + node->ipaddr.addr = ipaddr; + node->lease_end = lease_end; + + node->next = server->node_list; + server->node_list = node; + + return node; +} + +static void lease_list_free(struct dhcp_server *server) +{ + struct dhcp_client_node *node = server->node_list; + struct dhcp_client_node *next; + + while (node != NULL) + { + next = node->next; + mem_free(node); + node = next; + } + + server->node_list = NULL; +} + +static int lease_count(struct dhcp_server *server) +{ + struct dhcp_client_node *node; + int count = 0; + + for (node = server->node_list; node != NULL; node = node->next) + { + count++; + } + + return count; +} + +/* build a DHCP request the production code has to judge */ +static void lease_msg_build(struct dhcp_msg *msg, u8_t *opt, u16_t *len, + const u8_t *chaddr, u32_t requested_ip, u8_t hlen) +{ + memset(msg, 0, sizeof(*msg)); + msg->op = DHCP_BOOTREQUEST; + msg->htype = 1; + msg->cookie = PP_HTONL(DHCP_MAGIC_COOKIE); + msg->hlen = hlen; + SMEMCPY(msg->chaddr, chaddr, DHCP_MAX_HLEN); + + *len = 0; + if (requested_ip != 0) + { + opt[0] = DHCP_OPTION_REQUESTED_IP; + opt[1] = 4; + SMEMCPY(&opt[2], &requested_ip, 4); + *len = 6; + } +} + +/* let the production dhcp_client_find() answer a request of the given hlen */ +static struct dhcp_client_node *lease_find_hlen(struct dhcp_server *server, + const u8_t *chaddr, + u32_t requested_ip, u8_t hlen) +{ + struct dhcp_msg msg; + u8_t opt[6] = { 0 }; + u16_t len; + + lease_msg_build(&msg, opt, &len, chaddr, requested_ip, hlen); + + return dhcp_client_find(server, &msg, opt, len); +} + +/* let the production dhcp_client_alloc() answer a request of the given hlen */ +static struct dhcp_client_node *lease_alloc_hlen(struct dhcp_server *server, + const u8_t *chaddr, + u32_t requested_ip, u8_t hlen) +{ + struct dhcp_msg msg; + u8_t opt[6] = { 0 }; + u16_t len; + + lease_msg_build(&msg, opt, &len, chaddr, requested_ip, hlen); + + return dhcp_client_alloc(server, &msg, opt, len); +} + +/* build a DHCP message and let the production dhcp_client_find() answer it */ +static struct dhcp_client_node *lease_find(struct dhcp_server *server, + const u8_t *chaddr, + u32_t requested_ip) +{ + return lease_find_hlen(server, chaddr, requested_ip, DHCP_MAX_HLEN); +} + +/* build a DHCP message and let the production dhcp_client_alloc() answer it */ +static struct dhcp_client_node *lease_alloc(struct dhcp_server *server, + const u8_t *chaddr, + u32_t requested_ip) +{ + return lease_alloc_hlen(server, chaddr, requested_ip, DHCP_MAX_HLEN); +} + +/* ------------------------------------------------------- lease behaviour */ + +/* + * REQUESTED_IP ownership: dhcp_client_find() may only hand a lease back to the + * client that owns it. + */ +static void test_requested_ip_ownership(void) +{ + struct dhcp_server server; + struct dhcp_client_node *owner; + u32_t owner_ip = IP4(192, 168, 169, 10); + + printf("[case] requested-ip ownership via dhcp_client_find()\n"); + + mock_world_reset(1000); + lease_server_init(&server); + owner = lease_add(&server, mac_owner, owner_ip, sys_now() + LEASE_MS); + + /* the owner gets its lease back, by MAC and via REQUESTED_IP */ + CHECK(lease_find(&server, mac_owner, 0) == owner); + CHECK(lease_find(&server, mac_owner, owner_ip) == owner); + + /* another client must not inherit a lease that belongs to someone else */ + CHECK(lease_find(&server, mac_other, owner_ip) == NULL); + CHECK(lease_find(&server, mac_other, 0) == NULL); + + /* the rejected requests left the owner's lease in place */ + CHECK(lease_count(&server) == 1); + CHECK(lease_find(&server, mac_owner, owner_ip) == owner); + CHECK(owner->ipaddr.addr == owner_ip); + + lease_list_free(&server); +} + +/* + * A foreign REQUESTED_IP must not be handed out through the allocation path + * either: the requester gets a free pool address and the owner keeps its node. + */ +static void test_alloc_rejects_foreign_requested_ip(void) +{ + struct dhcp_server server; + struct dhcp_client_node *owner; + struct dhcp_client_node *other; + u32_t pool_first = IP4(192, 168, 169, 2); + u32_t pool_last = IP4(192, 168, 169, 3); + + printf("[case] allocation rejects a foreign REQUESTED_IP\n"); + + mock_world_reset(2000); + lease_server_init(&server); + server.start.addr = pool_first; + server.end.addr = pool_last; + server.current.addr = pool_first; + + owner = lease_add(&server, mac_owner, pool_first, sys_now() + LEASE_MS); + + /* mac_other asks for the address the owner already holds */ + other = lease_alloc(&server, mac_other, pool_first); + + CHECK(other != NULL); + CHECK(other != owner); + CHECK(other != NULL && other->ipaddr.addr != owner->ipaddr.addr); + CHECK(other != NULL && other->ipaddr.addr == pool_last); + CHECK(lease_count(&server) == 2); + + /* both leases stay reachable through the production lookup */ + CHECK(lease_find(&server, mac_owner, pool_first) == owner); + CHECK(lease_find(&server, mac_other, 0) == other); + + lease_list_free(&server); +} + +/* + * Expired-lease reclaim: dhcp_client_remove_expired() must unlink and free the + * expired nodes, keep the live ones, and be idempotent. + */ +static void test_remove_expired(void) +{ + struct dhcp_server server; + struct dhcp_client_node *live; + u32_t live_ip = IP4(192, 168, 169, 21); + + printf("[case] expired leases are recycled by dhcp_client_remove_expired()\n"); + + mock_world_reset(100000); + lease_server_init(&server); + + /* list order, newest first: expired tail -> live -> expired head */ + lease_add(&server, mac_owner, IP4(192, 168, 169, 20), sys_now() - 1); + live = lease_add(&server, mac_other, live_ip, sys_now() + LEASE_MS); + lease_add(&server, mac_third, IP4(192, 168, 169, 22), sys_now() - LEASE_MS - 1); + + CHECK(lease_count(&server) == 3); + CHECK(mock_mem_live_count() == 3); + + dhcp_client_remove_expired(&server); + + /* both expired nodes are gone (head and tail), the live one is kept */ + CHECK(lease_count(&server) == 1); + CHECK(server.node_list == live); + CHECK(mock_mem_live_count() == 1); + CHECK(lease_find(&server, mac_owner, 0) == NULL); + CHECK(lease_find(&server, mac_third, 0) == NULL); + CHECK(lease_find(&server, mac_other, live_ip) == live); + + /* nothing left to reclaim */ + dhcp_client_remove_expired(&server); + CHECK(lease_count(&server) == 1); + CHECK(server.node_list == live); + + lease_list_free(&server); +} + +/* + * The allocation path must reclaim an expired lease before handing out pool + * addresses: with a single-address pool an un-reclaimed expired node would + * make the next allocation fail. + */ +static void test_alloc_reclaims_expired(void) +{ + struct dhcp_server server; + struct dhcp_client_node *node; + u32_t pool_ip = IP4(192, 168, 169, 2); + + printf("[case] allocation reclaims an expired lease first\n"); + + mock_world_reset(300000); + lease_server_init(&server); + server.start.addr = pool_ip; + server.end.addr = pool_ip; + server.current.addr = pool_ip; + + lease_add(&server, mac_owner, pool_ip, sys_now() - 1); + + node = lease_alloc(&server, mac_other, pool_ip); + + CHECK(node != NULL); + CHECK(node != NULL && node->ipaddr.addr == pool_ip); + CHECK(lease_count(&server) == 1); + CHECK(mock_mem_live_count() == 1); + CHECK(lease_find(&server, mac_other, pool_ip) == node); + CHECK(lease_find(&server, mac_owner, 0) == NULL); + + lease_list_free(&server); +} + +/* + * Expiry arithmetic: sys_now() wraps every ~49.7 days, the check must stay + * correct across the wrap instead of reporting a live lease as expired. + */ +static void test_lease_expiry_across_wrap(void) +{ + struct dhcp_client_node node; + + printf("[case] lease expiry survives the sys_now() wrap\n"); + + memset(&node, 0, sizeof(node)); + + mock_reset_clock(0xfffff000U); + node.lease_end = sys_now() + LEASE_MS; /* lease_end wraps past 0 */ + + CHECK(node.lease_end < 0xfffff000U); + CHECK(!dhcp_client_lease_expired(&node)); + + mock_reset_clock(0xfffff000U + LEASE_MS - 1); + CHECK(!dhcp_client_lease_expired(&node)); + + mock_reset_clock(0xfffff000U + LEASE_MS); + CHECK(dhcp_client_lease_expired(&node)); + + /* + * A lease that was never renewed is expired even when the elapsed time + * passed 2^31 ms (~24.8 days): the check must not fall back to a signed + * comparison, which would report it as still valid. + */ + node.lease_end = LEASE_MS; /* lease_start == 0 */ + mock_reset_clock(0x80000000U + LEASE_MS); + CHECK(dhcp_client_lease_expired(&node)); +} + +/* + * The server only serves Ethernet clients: the entry gate must drop a frame + * whose hardware address length is not 6 instead of comparing it by prefix. + */ +static void test_entry_requires_ethernet_hlen(void) +{ + struct dhcp_msg msg; + u8_t opt[6] = { 0 }; + u16_t len; + static const u8_t hlen_cases[] = { 0, 1, 5, 6, 16, 255 }; + size_t i; + + printf("[case] the DHCP entry only accepts Ethernet hardware addresses\n"); + + CHECK(DHCP_MAX_HLEN == 6); + + for (i = 0; i < sizeof(hlen_cases); i++) + { + lease_msg_build(&msg, opt, &len, mac_owner, 0, hlen_cases[i]); + CHECK(dhcp_msg_usable(&msg) == (hlen_cases[i] == DHCP_MAX_HLEN)); + } + + lease_msg_build(&msg, opt, &len, mac_owner, 0, DHCP_MAX_HLEN); + msg.op = DHCP_BOOTREPLY; + CHECK(!dhcp_msg_usable(&msg)); + + lease_msg_build(&msg, opt, &len, mac_owner, 0, DHCP_MAX_HLEN); + msg.cookie = 0; + CHECK(!dhcp_msg_usable(&msg)); +} + +/* + * A hardware address shorter than an Ethernet address must not hit a stored + * lease, and must not create one either: both paths run through the production + * lookup/allocation code. + */ +static void test_short_hlen_never_matches(void) +{ + struct dhcp_server server; + struct dhcp_client_node *owner; + u32_t owner_ip = IP4(192, 168, 169, 30); + u32_t pool_ip = IP4(192, 168, 169, 31); + u8_t prefix_only[DHCP_MAX_HLEN] = { 0 }; + u8_t hlen; + + printf("[case] a short hardware address never owns a lease\n"); + + mock_world_reset(400000); + lease_server_init(&server); + server.start.addr = pool_ip; + server.end.addr = pool_ip; + server.current.addr = pool_ip; + owner = lease_add(&server, mac_owner, owner_ip, sys_now() + LEASE_MS); + + /* only the first bytes of the owner's address are present */ + SMEMCPY(prefix_only, mac_owner, sizeof(prefix_only)); + + for (hlen = 0; hlen < DHCP_MAX_HLEN; hlen++) + { + CHECK(lease_find_hlen(&server, prefix_only, 0, hlen) == NULL); + CHECK(lease_find_hlen(&server, prefix_only, owner_ip, hlen) == NULL); + CHECK(lease_alloc_hlen(&server, prefix_only, owner_ip, hlen) == NULL); + CHECK(lease_count(&server) == 1); + CHECK(server.node_list == owner); + } + + /* with the full addresses the same calls do match again */ + CHECK(lease_find(&server, mac_owner, 0) == owner); + CHECK(lease_find(&server, mac_owner, owner_ip) == owner); + + lease_list_free(&server); +} + +/* ------------------------------------------------------- timer lifecycle */ + +/* + * start must register exactly one periodic recycle timeout, a repeated start + * must not stack a second one, and stop must cancel it again. + */ +static void test_start_stop_timer_lifecycle(void) +{ + struct netif netif; + + printf("[case] start/stop register and cancel exactly one recycle timer\n"); + + mock_world_reset(1000); + netif_fixture_init(&netif, "e0"); + netif_list = &netif; + + dhcpd_start("e0"); + CHECK(mock_tcpip_callback_count() == 1); /* marshalled to the tcpip thread */ + CHECK(lw_dhcp_server != NULL); + CHECK(lw_dhcp_server != NULL && lw_dhcp_server->netif == &netif); + CHECK(mock_timer_count() == 1); + CHECK(mock_timer_registered(dhcp_server_periodic_recycle)); + + /* the same netif: only the pool is updated, no second timeout */ + dhcpd_start("e0"); + CHECK(mock_tcpip_callback_count() == 2); + CHECK(mock_timer_count() == 1); + + dhcpd_stop("e0"); + CHECK(mock_tcpip_callback_count() == 3); + CHECK(lw_dhcp_server == NULL); + CHECK(mock_timer_count() == 0); + CHECK(!mock_timer_registered(dhcp_server_periodic_recycle)); + CHECK(mock_mem_live_count() == 0); + + /* stopping again must not crash or double-cancel */ + dhcpd_stop("e0"); + CHECK(mock_tcpip_callback_count() == 4); + CHECK(mock_timer_count() == 0); + + /* and the server can come back with exactly one timer */ + dhcpd_start("e0"); + CHECK(mock_timer_count() == 1); + dhcpd_stop("e0"); + CHECK(mock_timer_count() == 0); + CHECK(!mock_timer_registered(dhcp_server_periodic_recycle)); + CHECK(mock_mem_live_count() == 0); +} + +/* + * The lifecycle entry points may also be reached from the tcpip thread itself + * (a recv callback, a timeout handler). Marshalling must detect that and run + * in place instead of posting a callback that only this thread could run. + */ +static void test_lifecycle_from_tcpip_thread_is_direct(void) +{ + struct netif netif; + ip4_addr_t pool_start; + ip4_addr_t pool_end; + err_t err; + + printf("[case] lifecycle calls on the tcpip thread run in place\n"); + + mock_world_reset(500); + netif_fixture_init(&netif, "e1"); + netif_list = &netif; + + mock_set_caller_name(TCPIP_THREAD_NAME); + + dhcpd_start("e1"); + CHECK(mock_tcpip_callback_count() == 0); + CHECK(lw_dhcp_server != NULL); + CHECK(mock_timer_count() == 1); + + dhcpd_stop("e1"); + CHECK(mock_tcpip_callback_count() == 0); + CHECK(mock_timer_count() == 0); + CHECK(mock_mem_live_count() == 0); + + /* dhcp_server_start() is a public entry point of its own */ + ip4addr_aton("192.168.169.2", &pool_start); + ip4addr_aton("192.168.169.10", &pool_end); + err = dhcp_server_start(&netif, &pool_start, &pool_end); + CHECK(err == ERR_OK); + CHECK(mock_tcpip_callback_count() == 0); + CHECK(mock_timer_count() == 1); + + dhcpd_stop("e1"); + CHECK(mock_timer_count() == 0); + + mock_set_caller_name("main"); +} + +/* + * With every pool address held by a live lease, allocation fails (the #11878 + * symptom). Once the leases expire the periodic timer reclaims them without + * any incoming packet, and allocation succeeds again. + */ +static void test_pool_exhausted_then_recycled(void) +{ + struct netif netif; + struct dhcp_server *server; + struct dhcp_client_node *node; + u32_t pool_first = IP4(192, 168, 169, 2); + u32_t pool_last = IP4(192, 168, 169, 3); + + printf("[case] a full pool rejects allocation until leases expire\n"); + + mock_world_reset(1000); + netif_fixture_init(&netif, "e0"); + netif_list = &netif; + + dhcpd_start("e0"); + server = lw_dhcp_server; + CHECK(server != NULL); + if (server == NULL) + { + return; + } + + server->start.addr = pool_first; + server->end.addr = pool_last; + server->current.addr = pool_first; + + lease_add(server, mac_owner, pool_first, sys_now() + LEASE_MS / 2); + lease_add(server, mac_other, pool_last, sys_now() + LEASE_MS / 2); + + CHECK(lease_alloc(server, mac_third, 0) == NULL); + CHECK(lease_count(server) == 2); + + /* time passes, no DHCP packet arrives, only the recycle timer runs */ + mock_advance_clock(LEASE_MS / 2 + DHCPD_RECYCLE_INTERVAL_MS); + CHECK(lease_count(server) == 0); + CHECK(mock_timer_count() == 1); /* the handler re-armed exactly once */ + + node = lease_alloc(server, mac_third, 0); + CHECK(node != NULL); + CHECK(node != NULL && node->ipaddr.addr == pool_first); + CHECK(lease_count(server) == 1); + + dhcpd_stop("e0"); + CHECK(mock_timer_count() == 0); + CHECK(mock_mem_live_count() == 0); +} + +/* + * The reported field failure: a client leases an address, disappears, and no + * DHCP packet arrives for longer than the whole 32-bit millisecond period. + * The periodic recycle timer alone must keep the pool usable; the unsigned + * expiry check must also keep a lease valid while the clock wraps. + */ +static void test_periodic_recycle_across_full_clock_wrap(void) +{ + struct netif netif; + struct dhcp_server *server; + struct dhcp_client_node *node; + u32_t pool_ip = IP4(192, 168, 169, 9); + unsigned long long idle_ms = 0; + unsigned long fires_before; + + printf("[case] periodic recycle survives a full 2^32 ms idle period\n"); + + /* start one tick before the clock wraps so the next lease crosses it */ + mock_world_reset(0xffff0000U - DHCPD_RECYCLE_INTERVAL_MS); + netif_fixture_init(&netif, "e0"); + netif_list = &netif; + + dhcpd_start("e0"); + server = lw_dhcp_server; + CHECK(server != NULL); + if (server == NULL) + { + return; + } + + server->start.addr = pool_ip; + server->end.addr = pool_ip; + server->current.addr = pool_ip; + + /* a lease that expired before the server even got a packet again */ + lease_add(server, mac_owner, pool_ip, sys_now() - LEASE_MS - 1); + CHECK(lease_count(server) == 1); + + mock_advance_clock(DHCPD_RECYCLE_INTERVAL_MS); + CHECK(lease_count(server) == 0); /* reclaimed by the timer alone */ + CHECK(mock_timer_count() == 1); + + /* a lease issued just before the wrap ends after it: it must stay valid */ + node = lease_add(server, mac_third, pool_ip, sys_now() + LEASE_MS); + CHECK(node->lease_end < sys_now()); + mock_advance_clock(2 * DHCPD_RECYCLE_INTERVAL_MS); + CHECK(lease_count(server) == 1); + CHECK(lease_find(server, mac_third, 0) == node); + + /* now stay idle for more than one whole 32-bit millisecond period */ + fires_before = mock_timer_fires; + while (idle_ms <= 0x100000000ULL) + { + mock_advance_clock(DHCPD_RECYCLE_INTERVAL_MS); + idle_ms += DHCPD_RECYCLE_INTERVAL_MS; + } + + CHECK(mock_timer_fires > fires_before); + CHECK(mock_timer_count() == 1); /* still one registration, no pile-up */ + CHECK(lease_count(server) == 0); /* the long-idle lease was reclaimed */ + + /* the reclaimed address is allocatable again, with no packet ever seen */ + node = lease_alloc(server, mac_other, 0); + CHECK(node != NULL); + CHECK(node != NULL && node->ipaddr.addr == pool_ip); + + dhcpd_stop("e0"); + CHECK(mock_timer_count() == 0); + CHECK(mock_mem_live_count() == 0); +} + +int main(void) +{ + test_requested_ip_ownership(); + test_alloc_rejects_foreign_requested_ip(); + test_remove_expired(); + test_alloc_reclaims_expired(); + test_lease_expiry_across_wrap(); + test_entry_requires_ethernet_hlen(); + test_short_hlen_never_matches(); + test_start_stop_timer_lifecycle(); + test_lifecycle_from_tcpip_thread_is_direct(); + test_pool_exhausted_then_recycled(); + test_periodic_recycle_across_full_clock_wrap(); + + CHECK(mock_mem_live_count() == 0); + CHECK(mock_timer_count() == 0); + + if (test_failures != 0) + { + printf("%d check(s) failed\n", test_failures); + return 1; + } + + printf("All dhcpd lease regression tests passed!\n"); + + return 0; +} diff --git a/components/net/lwip/port/lwipopts.h b/components/net/lwip/port/lwipopts.h index 52be6900cf2..d004ac433a3 100644 --- a/components/net/lwip/port/lwipopts.h +++ b/components/net/lwip/port/lwipopts.h @@ -654,17 +654,32 @@ #define LWIP_NETIF_API 1 #endif +/* DHCPD keeps one permanent sys_timeout for periodic lease recycling. + * Reserve it explicitly: with MEMP_MEM_MALLOC=0 the pool otherwise only + * covers lwIP's own protocol timers, so DHCPD would either hit an empty + * pool or steal a slot reserved for TCP and the other protocols. */ +#ifdef LWIP_USING_DHCPD +#define DHCPD_SYS_TIMEOUT_COUNT 1 +#else +#define DHCPD_SYS_TIMEOUT_COUNT 0 +#endif + /* MEMP_NUM_SYS_TIMEOUT: the number of simultaneously active timeouts. */ #if RT_USING_LWIP_VER_NUM >= 0x20200 /* lwIP 2.2.x changed the pool formula (LWIP_ACD, LWIP_IPV6_DHCP6, - * PPP_NUM_TIMEOUTS_PER_PCB). Do not derive it here; fall back to the - * upstream opt.h default (MEMP_NUM_SYS_TIMEOUT == LWIP_NUM_SYS_TIMEOUT_INTERNAL, - * opt.h:527 in 2.2.1) which always matches its own code. */ + * PPP_NUM_TIMEOUTS_PER_PCB). Do not derive it here; use the upstream + * LWIP_NUM_SYS_TIMEOUT_INTERNAL value (opt.h:519 in 2.2.1) and only add + * the DHCPD reservation when DHCPD is enabled. */ +#ifdef LWIP_USING_DHCPD +/* opt.h defines LWIP_NUM_SYS_TIMEOUT_INTERNAL after including lwipopts.h; + * this expression is expanded later, when MEMP_NUM_SYS_TIMEOUT is used. */ +#define MEMP_NUM_SYS_TIMEOUT (LWIP_NUM_SYS_TIMEOUT_INTERNAL + DHCPD_SYS_TIMEOUT_COUNT) +#endif #else #if RT_USING_LWIP_VER_NUM == 0x20102 -#define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + PPP_NUM_TIMEOUTS + (LWIP_IPV6 * (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD))) +#define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + PPP_NUM_TIMEOUTS + (LWIP_IPV6 * (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD)) + DHCPD_SYS_TIMEOUT_COUNT) #else -#define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + PPP_SUPPORT + (LWIP_IPV6 ? (1 + (2*LWIP_IPV6)) : 0)) +#define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + PPP_SUPPORT + (LWIP_IPV6 ? (1 + (2*LWIP_IPV6)) : 0) + DHCPD_SYS_TIMEOUT_COUNT) #endif #endif