add DHCP lease renewal at T/2

- Add Renew() to dhcp.Client: sends REQUEST with ciaddr (RENEWING state)
- Start renewal goroutine in session at lease_time/2
- On IP change: flush TAP, reconfigure address/routes/DNS/policy routes
- On renewal failure: retry at T/4 (min 60s)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Git Sagar 2026-06-06 22:05:34 +05:30
parent d5878a170f
commit a62ed3287f
3 changed files with 105 additions and 0 deletions

View file

@ -61,6 +61,13 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n
if opts.PolicyRouteTable > 0 && lease.Gateway != nil {
defer netcfg.ConfigurePolicyRoute(dev.Name, lease, opts.PolicyRouteTable)()
}
// Start DHCP renewal at T/2
if lease.LeaseTime > 0 {
stopRenew := make(chan struct{})
defer close(stopRenew)
go renewLoop(dhcpClient, tunnel, dev.Name, lease, opts, stopRenew)
}
}
select {
@ -71,6 +78,50 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n
}
}
func renewLoop(dc *dhcp.Client, tunnel *client.Tunnel, ifname string, lease *dhcp.Lease, opts netcfg.Options, stop chan struct{}) {
currentIP := lease.ClientIP
renewAt := lease.LeaseTime / 2
for {
select {
case <-stop:
return
case <-time.After(renewAt):
}
log.Printf("dhcp: renewing lease for %s...", currentIP)
newLease, err := dc.Renew(currentIP, func(frame []byte) error {
return tunnel.WriteFrames([][]byte{frame})
}, 10*time.Second)
if err != nil {
log.Printf("dhcp: renewal failed: %v", err)
// Try again at T/4 of remaining time, or 60s minimum
renewAt = lease.LeaseTime / 4
if renewAt < 60*time.Second {
renewAt = 60 * time.Second
}
continue
}
ones, _ := newLease.SubnetMask.Size()
log.Printf("dhcp: renewed lease: ip=%s/%d gw=%s ttl=%v",
newLease.ClientIP, ones, newLease.Gateway, newLease.LeaseTime)
if !newLease.ClientIP.Equal(currentIP) {
log.Printf("dhcp: IP changed %s → %s, reconfiguring", currentIP, newLease.ClientIP)
netcfg.ReconfigureTAP(ifname, newLease, opts.AcceptDefaultGW, opts.AcceptStaticRoutes, opts.AcceptDNS)
if opts.PolicyRouteTable > 0 && newLease.Gateway != nil {
netcfg.ConfigurePolicyRoute(ifname, newLease, opts.PolicyRouteTable)
}
currentIP = newLease.ClientIP
}
if newLease.LeaseTime > 0 {
renewAt = newLease.LeaseTime / 2
}
}
}
func runDHCP(dc *dhcp.Client, tunnel *client.Tunnel) (*dhcp.Lease, error) {
log.Println("starting DHCP exchange...")