Skip to content

[net][dhcpd] 回收过期 DHCP 租约 - #12024

Open
cms19859230182-lang wants to merge 1 commit into
RT-Thread:masterfrom
cms19859230182-lang:fix/dhcpd-lease-expiry-recycle
Open

cms19859230182-lang wants to merge 1 commit into
RT-Thread:masterfrom
cms19859230182-lang:fix/dhcpd-lease-expiry-recycle

Conversation

@cms19859230182-lang

@cms19859230182-lang cms19859230182-lang commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

修了关于过期租约的一大堆问题

@github-actions

Copy link
Copy Markdown

👋 感谢您对 RT-Thread 的贡献!Thank you for your contribution to RT-Thread!

为确保代码符合 RT-Thread 的编码规范,请在你的仓库中执行以下步骤运行代码格式化工作流(如果格式化CI运行失败)。
To ensure your code complies with RT-Thread's coding style, please run the code formatting workflow by following the steps below (If the formatting of CI fails to run).


🛠 操作步骤 | Steps

  1. 前往 Actions 页面 | Go to the Actions page
    点击进入工作流 → | Click to open workflow →

  2. 点击 Run workflow | Click Run workflow

  • Use workflow from 保持默认分支(通常为 master)
    Keep the default branch (usually master) in Use workflow from
  • 在 branch 输入框填写 PR 分支 fix/dhcpd-lease-expiry-recycle
    Enter PR branch fix/dhcpd-lease-expiry-recycle in the branch field
  • 设置需排除的文件/目录(目录请以"/"结尾)
    Set files/directories to exclude (directories should end with "/")
  1. 等待工作流完成 | Wait for the workflow to complete
    格式化后的代码将作为独立提交推送至你的分支。
    The formatting changes will be pushed to your branch as a separate commit.

完成后,提交将自动更新至 fix/dhcpd-lease-expiry-recycle 分支,关联的 Pull Request 也会同步更新。
Once completed, commits will be pushed to the fix/dhcpd-lease-expiry-recycle branch automatically, and the related Pull Request will be updated.

如有问题欢迎联系我们,再次感谢您的贡献!💐
If you have any questions, feel free to reach out. Thanks again for your contribution!

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

📌 Code Review Assignment

🏷️ Tag: components

Reviewers: @Maihuanyi

Changed Files (Click to expand)
  • components/net/lwip-dhcpd/dhcp_server_raw.c
  • components/net/lwip-dhcpd/test/mock/lwip/dhcp.h
  • components/net/lwip-dhcpd/test/mock/lwip/inet_chksum.h
  • components/net/lwip-dhcpd/test/mock/lwip/init.h
  • components/net/lwip-dhcpd/test/mock/lwip/ip.h
  • components/net/lwip-dhcpd/test/mock/lwip/opt.h
  • components/net/lwip-dhcpd/test/mock/lwip/prot/dhcp.h
  • components/net/lwip-dhcpd/test/mock/lwip/sockets.h
  • components/net/lwip-dhcpd/test/mock/lwip/sys.h
  • components/net/lwip-dhcpd/test/mock/lwip/tcpip.h
  • components/net/lwip-dhcpd/test/mock/lwip/timeouts.h
  • components/net/lwip-dhcpd/test/mock/mock_lwip.h
  • components/net/lwip-dhcpd/test/mock/netif/etharp.h
  • components/net/lwip-dhcpd/test/mock/netif/ethernetif.h
  • components/net/lwip-dhcpd/test/mock/rtthread.h
  • components/net/lwip-dhcpd/test_dhcpd_lease.c
  • components/net/lwip/port/lwipopts.h

📊 Current Review Status (Last Updated: 2026-11-25 03:59 CST)


📝 Review Instructions

  1. 维护者可以通过单击此处来刷新审查状态: 🔄 刷新状态
    Maintainers can refresh the review status by clicking here: 🔄 Refresh Status

  2. 确认审核通过后评论 LGTM/lgtm
    Comment LGTM/lgtm after confirming approval

  3. PR合并前需至少一位维护者确认
    PR must be confirmed by at least one maintainer before merging

ℹ️ 刷新CI状态操作需要具备仓库写入权限。
ℹ️ Refresh CI status operation requires repository Write permission.

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

@BernardXiong BernardXiong left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

结论:方向正确,未发现阻塞问题。

已验证:

  • lease_end 现在由 dhcp_client_lease_renew() 写入,并在 dhcp_client_alloc() 扫描地址池前回收过期节点;命中 MAC、命中 REQUESTED_IP、新建节点和 ACK 路径都会续租。
  • DHCP_DEFAULT_LIVE_TIME 改为 86400 秒后,PP_HTONL() 写出的 option 51 仍为 86400 秒(原 0x80510100 是预交换值),与服务器实际租期一致。
  • mem_malloc / mem_free 配对,链表操作粒度与既有 RELEASE / stop 路径一致。
  • CI:107 pass / 3 skipping。

非阻塞建议:

  1. dhcp_client_lease_expired()(dhcp_server_raw.c#L194)使用 (s32_t)(sys_now() - lease_end) >= 0,仅当距 lease_end 小于 2^31 ms(约 24.8 天)时判断成立。若节点过期后超过 24.8 天才再次检查,差值为负会被判为“未过期”,池满时仍无法回收。可在收包路径周期性回收,避免检查间隔超过该窗口。
  2. 本 PR 只做了 -fsyntax-only 验证,建议补充一次手工或 QEMU 下的租约过期回收验证说明。

@cms19859230182-lang
cms19859230182-lang force-pushed the fix/dhcpd-lease-expiry-recycle branch from a4f748d to 1d59beb Compare November 11, 2026 15:21
@cms19859230182-lang

Copy link
Copy Markdown
Contributor Author

@BernardXiong 已按非阻塞建议更新至 1d59beb6:

  • dhcp_client_lease_expired() 改为无符号已租用时比较:lease_start = node->lease_end - DHCP_DEFAULT_LEASE_TIME_MS,再用 (u32_t)(sys_now() - lease_start) >= DHCP_DEFAULT_LEASE_TIME_MS,覆盖「过期超过 ~24.8 天(可达 ~49.7 天)才再检查」的窗口。
  • dhcp_server_recv() 处理完合法 DHCP 报文后也会调用 dhcp_client_remove_expired(),使收包路径同样触发回收,未引入额外定时器框架。
  • 验证说明已写进 PR 正文:静态与枚举边界核对(未跑板),并说明长时间过期后判断仍为过期。

@BernardXiong BernardXiong left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

批准。 复核 head 1d59beb6:租约改用 sys_now() 毫秒时间戳,无符号差值判断可正确处理 49.7 天回绕;分配与 DHCPREQUEST 路径一致续租,过期节点在分配和收包路径回收,未见阻塞问题。CI 中 ESP32C6 的失败在 Upload output as artifact 步骤,属 Actions artifact 基础设施故障,不是代码失败。

Approved. Lease expiry now uses sys_now() milliseconds with an unsigned elapsed check, renew paths are consistent, and expired nodes are reclaimed on allocate and receive. The ESP32C6 failure is an Actions artifact upload infrastructure error, not a code failure.

@Rbb666 Rbb666 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

请求修改 / Request changes

复核提交 1d59beb6,两个问题已在主机模拟中复现:过期地址重新分配后,旧客户端仍能收到该地址的 ACK;长时间无 DHCP 报文、超过一个完整的 32 位毫秒计时周期后,过期节点仍会阻塞地址分配。请修复下面两条行内意见,并补充对应回归测试。

Reviewed commit 1d59beb6. Host-side reproduction confirms two issues: a returning client can receive an ACK for an address reassigned to another client, and expired leases can block allocation after a full 32-bit millisecond clock cycle without DHCP traffic. Please address the two inline comments and add regression coverage.

验证 / Validation: 直接编译基线和 PR 中的租约分配、查找及收包函数,以模拟时钟和报文验证。普通到期回收、续租、链表删除、RELEASE 和有效租约跨计时零点的用例通过;未进行板级或 QEMU 验证。 The host harness compiles the allocation, lookup and receive functions from the base and PR sources with mocked time and packets. Normal expiry, renewal, list removal, RELEASE and live leases crossing the clock zero point pass. No board or QEMU validation was performed.

}

/* keep the current client's node, reclaim expired nodes of other clients */
dhcp_client_remove_expired(dhcpserver);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 校验租约归属后再复用地址 / Validate lease ownership before reusing an address

中文:这里启用过期回收后,现有仅按 requested IP 匹配节点的逻辑会在正常重连流程中确认其他客户端的有效租约。已用两个地址的池复现:A 获得 192.168.169.2;24 小时后 B 的 DISCOVER 回收 A 的节点,B 获得 .2 并收到 ACK;随后 A 在 INIT-REBOOT 状态发送携带旧地址 .2 的 DHCPREQUEST,dhcp_client_find() 按 MAC 找不到 A,转而按 IP 命中 B 的节点,收包路径续租该节点并向 A 返回 ACK。服务端因此把同一 IP 确认给两个客户端,可能造成地址冲突或无法入网;同一流程在基线上分别分配 .2 和 .3,不会产生重复 ACK。请在 dhcp_client_find() 和 dhcp_client_alloc() 的 requested-IP 分支中校验绑定所属客户端,不能仅因 IP 相同就返回另一个客户端仍有效的节点。

English: Recycling makes the existing requested-IP-only lookup acknowledge another client's active binding during a normal reconnect. Reproduced with a two-address pool: A receives 192.168.169.2; after 24 hours B's DISCOVER removes A's expired node, and B is offered and ACKed .2. A then sends an INIT-REBOOT DHCPREQUEST for its cached .2. With no MAC match, dhcp_client_find() falls back to the IP lookup, returns B's node, and the receive path renews it and ACKs .2 to A as well. The same flow on the base assigns .2 and .3 separately. Validate ownership in the requested-IP branches of both lookup and allocation; an active node belonging to another client must not be returned merely because its IP matches.

Comment on lines +196 to +199
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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 完整计时回绕后仍会把过期租约判为有效 / Expired leases become valid again after a full clock cycle

中文:无符号差值可以处理有效租约跨零点,但不能识别自租约开始已超过完整 2^32 ms 周期的情况。例如租约在 sys_now() == 0 时建立,之后没有 DHCP 报文,经过 2^32 + 1000 ms(约 49.7 天)才再次分配时,这里的已用时间仅为 1000 ms,小于 86400000,已过期的节点被保留。已复现地址池的两个节点都保留,新 MAC 的 DISCOVER 收不到 OFFER。新增的收包回收也只在有报文时执行,不能保证在一个完整周期内检查。建议在 lwIP 线程中周期回收,或使用能够可靠记录完整回绕次数的时间源,并覆盖该长时间空闲场景。

English: Unsigned subtraction handles a live lease crossing zero, but loses elapsed time once a full 2^32 ms cycle has passed. For a lease created at sys_now() == 0, the first allocation after 2^32 + 1000 ms without DHCP traffic computes only 1000 ms elapsed, so the expired node is retained. With a full two-address pool, both stale nodes remain and a new client's DISCOVER receives no OFFER. Receive-driven cleanup does not bound the check interval when there is no traffic. Add periodic reclamation in the lwIP thread or a time source that reliably tracks full wraps, and test this idle-period case.

@cms19859230182-lang
cms19859230182-lang marked this pull request as draft November 14, 2026 09:22
@cms19859230182-lang
cms19859230182-lang force-pushed the fix/dhcpd-lease-expiry-recycle branch from f118afa to 271b210 Compare November 14, 2026 09:59
@cms19859230182-lang

Copy link
Copy Markdown
Contributor Author

@Rbb666 按 IP 找租约会核对 MAC;空闲跨整圈也会周期清过期节点。tip 已推到最新,麻烦再看。

@cms19859230182-lang
cms19859230182-lang marked this pull request as ready for review November 14, 2026 10:00

@Rbb666 Rbb666 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复核当前 head 271b210e:周期回收的接入还有以下三处需要修正。编译问题已由 w60x CI 确认;固定定时器池耗尽已通过抽取 lwIP 实现的主机模拟复现;启停与回收的并发问题经调用链核验。本轮未运行板级或 QEMU 测试。

#define DHCPD_RECYCLE_INTERVAL_MS 60000
#endif

static void dhcp_server_periodic_recycle(void *arg)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 将周期回调移到文件作用域

这里仍在 dhcp_server_start() 的函数体内,不能定义这个 static 函数;外部的 dhcpd_stop() 也无法引用该局部名字。当前 w60x CI 已分别在第 783 行报 invalid storage class for function、第 978 行报回调 undeclared,因此启用该 DHCPD 实现的配置无法编译。请将完整回调定义移到文件作用域,并保证 start/stop 调用前有可见声明,然后重跑启用 LWIP_USING_DHCPD 的构建。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

纳尼,还有这种问题的,我咋没扫出来,我来看看

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

纳尼,还有这种问题的,我咋没扫出来,我来看看

/* 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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 为新增回收定时器增加固定池容量

这里增加一个常驻 timeout,但 lwipopts.h 仍设置 MEMP_MEM_MALLOC=0,MEMP_NUM_SYS_TIMEOUT 只覆盖 lwIP 内部协议定时器,没有为 DHCPD 预留槽位。以 IPv4、TCP、IP 重组、ARP、DHCP、DNS 开启且 PPP/IPv6 关闭的 lwIP 2.1.2 配置为例,内部初始化占 5/6 项,活动 TCP 占满第 6 项,此处再注册会触发 pool MEMP_SYS_TIMEOUT is empty 断言;关闭断言时则直接注册失败。反过来先启动 DHCPD,会占掉 TCP 预留项,后续 TCP timer 无法注册。该容量耗尽已通过真实 timeout 注册代码配合模拟固定池复现。请按 LWIP_USING_DHCPD 为这个全局回收定时器增加一个槽位,并覆盖支持的各 lwIP 版本。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

嘶,你的方案貌似会更好,我来改改

Comment on lines +788 to +790
for (server = lw_dhcp_server; server != NULL; server = server->next)
{
dhcp_client_remove_expired(server);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 将周期回收与服务启停串行化

新增回调在 TCP/IP 线程遍历服务器和租约,但启用 RT_WLAN_WORK_THREAD_ENABLE 时,dev_wlan_lwip.c:273 会把 AP 状态处理投递到 WLAN 工作线程,再由第 190/212 行直接调用 dhcpd_start()/dhcpd_stop();这些调用没有持有 core lock,本文件的 LWIP_NETIF_LOCK/UNLOCK 也是空宏。因此回调持有的 server/node 可能被停止路径第 968–975 行同时释放,造成释放后访问或重复释放。第 978 行在释放之后调用的 sys_untimeout() 只取消尚未触发的条目,不会等待正在执行的回调;新增 timeout 注册/注销本身也在无锁修改 lwIP 的超时链表。请将服务启停、对象释放及定时器操作统一串行化到 TCP/IP 线程,或完整使用 core lock 保护相关生命周期。仅移动回调定义不能消除该风险。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

看上去会空转???

我研究一下

@cms19859230182-lang

Copy link
Copy Markdown
Contributor Author

都改完了,首先是周期回到文件作用域了

然后我多给 SYS-timeline 留了一个槽

最后启停和周期回收串起来了,避免空转

@cms19859230182-lang cms19859230182-lang changed the title [net][dhcpd] recycle expired DHCP client leases [net][dhcpd] 回收过期 DHCP 租约 Nov 16, 2026
node.ipaddr = 0x0101a8c0; /* 192.168.1.1 */

/* Same MAC: ownership valid */
assert(memcmp(node.chaddr, mac_owner, 6) == 0);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里比较的是测试自己填的两组 MAC,没有走 DHCP 服务的租约匹配。到期用例也在测试里复制了实现,生产代码改坏后仍会通过。请让用例直接覆盖实际的租约匹配与回收路径。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

@cms19859230182-lang
cms19859230182-lang force-pushed the fix/dhcpd-lease-expiry-recycle branch 2 times, most recently from f673e3a to adea637 Compare November 23, 2026 07:49
if (node != NULL)
{
return node;
if (memcmp(node->chaddr, msg->chaddr, msg->hlen) == 0)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

入口允许小于 6 的 hlen。这里按报文长度比较,只要地址前缀相同就可能匹配到其他客户端的租约。请在入口校验以太网地址长度为 6,并用短地址验证不会命中已有租约。

@cms19859230182-lang

Copy link
Copy Markdown
Contributor Author

同意 hlen 与单测这两条。入口强制 hlen==6,并补短地址/真实匹配回收用例;改完贴 tip。

Fix RT-Thread#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 requested-IP paths of
  dhcp_client_find() and dhcp_client_alloc() to prevent giving one client's
  active lease to another MAC.
- 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 start/stop, server/node teardown and sys_timeout/sys_untimeout under the
  lwIP core lock, serializing them with the recycle callback.
- 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.
- Drive the regression test through the production lease code: it builds
  dhcp_server_raw.c against lwIP/RT-Thread stubs and checks dhcp_msg_usable(),
  dhcp_client_find(), dhcp_client_alloc() and dhcp_client_remove_expired(),
  instead of comparing two hand-filled MACs and keeping a private copy of the
  expiry rule. The new cases cover the entry gate and short hardware addresses.
@cms19859230182-lang
cms19859230182-lang force-pushed the fix/dhcpd-lease-expiry-recycle branch from adea637 to c7e5bbd Compare November 24, 2026 19:59

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants