p2p/nat: fix err shadowing in UPnP addAnyPortMapping (#33355)
Some checks are pending
/ Linux Build (push) Waiting to run
/ Linux Build (arm) (push) Waiting to run
/ Keeper Build (push) Waiting to run
/ Windows Build (push) Waiting to run
/ Docker Image (push) Waiting to run

The random-port retry loop in addAnyPortMapping shadowed the err
variable, causing the function to return (0, nil) when all attempts
failed. This change removes the shadowing and preserves the last error
across both the fixed-port and random-port retries, ensuring failures
are reported to callers correctly.
This commit is contained in:
Snezhkko 2025-12-08 16:02:24 +02:00 committed by GitHub
parent dbca85869f
commit af47d9b472
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -107,30 +107,30 @@ func (n *upnp) addAnyPortMapping(protocol string, extport, intport int, ip net.I
}) })
} }
// For IGDv1 and v1 services we should first try to add with extport. // For IGDv1 and v1 services we should first try to add with extport.
var lastErr error
for i := 0; i < retryCount+1; i++ { for i := 0; i < retryCount+1; i++ {
err := n.withRateLimit(func() error { lastErr = n.withRateLimit(func() error {
return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS) return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
}) })
if err == nil { if lastErr == nil {
return uint16(extport), nil return uint16(extport), nil
} }
log.Debug("Failed to add port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", err) log.Debug("Failed to add port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", lastErr)
} }
// If above fails, we retry with a random port. // If above fails, we retry with a random port.
// We retry several times because of possible port conflicts. // We retry several times because of possible port conflicts.
var err error
for i := 0; i < randomCount; i++ { for i := 0; i < randomCount; i++ {
extport = n.randomPort() extport = n.randomPort()
err := n.withRateLimit(func() error { lastErr = n.withRateLimit(func() error {
return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS) return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
}) })
if err == nil { if lastErr == nil {
return uint16(extport), nil return uint16(extport), nil
} }
log.Debug("Failed to add random port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", err) log.Debug("Failed to add random port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", lastErr)
} }
return 0, err return 0, lastErr
} }
func (n *upnp) randomPort() int { func (n *upnp) randomPort() int {