Skip to content

Commit af47d9b

Browse files
authored
p2p/nat: fix err shadowing in UPnP addAnyPortMapping (#33355)
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.
1 parent dbca858 commit af47d9b

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

p2p/nat/natupnp.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -107,30 +107,30 @@ func (n *upnp) addAnyPortMapping(protocol string, extport, intport int, ip net.I
107107
})
108108
}
109109
// For IGDv1 and v1 services we should first try to add with extport.
110+
var lastErr error
110111
for i := 0; i < retryCount+1; i++ {
111-
err := n.withRateLimit(func() error {
112+
lastErr = n.withRateLimit(func() error {
112113
return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
113114
})
114-
if err == nil {
115+
if lastErr == nil {
115116
return uint16(extport), nil
116117
}
117-
log.Debug("Failed to add port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", err)
118+
log.Debug("Failed to add port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", lastErr)
118119
}
119120

120121
// If above fails, we retry with a random port.
121122
// We retry several times because of possible port conflicts.
122-
var err error
123123
for i := 0; i < randomCount; i++ {
124124
extport = n.randomPort()
125-
err := n.withRateLimit(func() error {
125+
lastErr = n.withRateLimit(func() error {
126126
return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
127127
})
128-
if err == nil {
128+
if lastErr == nil {
129129
return uint16(extport), nil
130130
}
131-
log.Debug("Failed to add random port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", err)
131+
log.Debug("Failed to add random port mapping", "protocol", protocol, "extport", extport, "intport", intport, "err", lastErr)
132132
}
133-
return 0, err
133+
return 0, lastErr
134134
}
135135

136136
func (n *upnp) randomPort() int {

0 commit comments

Comments
 (0)