go-ethereum/p2p/nat/stun.go
cuiweixie 42c013f2af p2p/nat: return exactly n random STUN servers on every call
randomServers drew indices with rand.Intn into a dedup map, bounded by
len(serverList)*2 iterations. When n approaches the number of configured
servers, repeated random collisions can exhaust the iteration budget
before n unique servers are collected, so the function sometimes returns
fewer servers than requested even though enough exist.

For example, with 2 configured servers and requestLimit==3 (capped to 2),
the four allowed draws can collide and yield only a single server. If
that server is down, ExternalIP fails without ever trying the other.

Replace the sampling loop with rand.Perm, which produces a uniform
permutation of all indices in one pass. Slicing the first n entries
always yields exactly min(n, len(serverList)) distinct servers, with no
probabilistic shortfall.
2026-06-11 20:00:00 +08:00

138 lines
3.3 KiB
Go

// Copyright 2025 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package nat
import (
_ "embed"
"errors"
"fmt"
"math/rand"
"net"
"strings"
"time"
"github.com/ethereum/go-ethereum/log"
stunV3 "github.com/pion/stun/v3"
)
//go:embed stun-list.txt
var stunDefaultServers string
const requestLimit = 3
var errSTUNFailed = errors.New("STUN requests failed")
type stun struct {
serverList []string
}
func newSTUN(serverAddr string) (Interface, error) {
s := new(stun)
if serverAddr == "" {
s.serverList = strings.Split(stunDefaultServers, "\n")
} else {
_, err := net.ResolveUDPAddr("udp", serverAddr)
if err != nil {
return nil, err
}
s.serverList = []string{serverAddr}
}
return s, nil
}
func (s stun) String() string {
if len(s.serverList) == 1 {
return fmt.Sprintf("stun:%s", s.serverList[0])
}
return "stun"
}
func (s stun) MarshalText() ([]byte, error) {
return []byte(s.String()), nil
}
func (stun) SupportsMapping() bool {
return false
}
func (stun) AddMapping(protocol string, extport, intport int, name string, lifetime time.Duration) (uint16, error) {
return uint16(extport), nil
}
func (stun) DeleteMapping(string, int, int) error {
return nil
}
func (s *stun) ExternalIP() (net.IP, error) {
for _, server := range s.randomServers(requestLimit) {
ip, err := s.externalIP(server)
if err != nil {
log.Debug("STUN request failed", "server", server, "err", err)
continue
}
return ip, nil
}
return nil, errSTUNFailed
}
func (s *stun) randomServers(n int) []string {
n = min(n, len(s.serverList))
list := make([]string, 0, n)
for _, index := range rand.Perm(len(s.serverList))[:n] {
list = append(list, s.serverList[index])
}
return list
}
func (s *stun) externalIP(server string) (net.IP, error) {
_, _, err := net.SplitHostPort(server)
if err != nil {
server += fmt.Sprintf(":%d", stunV3.DefaultPort)
}
log.Trace("Attempting STUN binding request", "server", server)
conn, err := stunV3.Dial("udp", server)
if err != nil {
return nil, err
}
defer conn.Close()
message, err := stunV3.Build(stunV3.TransactionID, stunV3.BindingRequest)
if err != nil {
return nil, err
}
var responseError error
var mappedAddr stunV3.XORMappedAddress
err = conn.Do(message, func(event stunV3.Event) {
if event.Error != nil {
responseError = event.Error
return
}
if err := mappedAddr.GetFrom(event.Message); err != nil {
responseError = err
}
})
if err != nil {
return nil, err
}
if responseError != nil {
return nil, responseError
}
log.Trace("STUN returned IP", "server", server, "ip", mappedAddr.IP)
return mappedAddr.IP, nil
}