mirror of
https://github.com/caddyserver/caddy.git
synced 2025-10-19 15:53:17 +00:00
core: Change net.IP to netip.Addr; use netip.Prefix (#4966)
Co-authored-by: Matt Holt <mholt@users.noreply.github.com>
This commit is contained in:
parent
a944de4ab7
commit
c7772588bd
5 changed files with 50 additions and 57 deletions
|
@ -24,6 +24,7 @@ import (
|
|||
"net"
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"net/netip"
|
||||
"net/textproto"
|
||||
"net/url"
|
||||
"regexp"
|
||||
|
@ -180,7 +181,7 @@ type Handler struct {
|
|||
DynamicUpstreams UpstreamSource `json:"-"`
|
||||
|
||||
// Holds the parsed CIDR ranges from TrustedProxies
|
||||
trustedProxies []*net.IPNet
|
||||
trustedProxies []netip.Prefix
|
||||
|
||||
// Holds the named response matchers from the Caddyfile while adapting
|
||||
responseMatchers map[string]caddyhttp.ResponseMatcher
|
||||
|
@ -251,24 +252,18 @@ func (h *Handler) Provision(ctx caddy.Context) error {
|
|||
// parse trusted proxy CIDRs ahead of time
|
||||
for _, str := range h.TrustedProxies {
|
||||
if strings.Contains(str, "/") {
|
||||
_, ipNet, err := net.ParseCIDR(str)
|
||||
ipNet, err := netip.ParsePrefix(str)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parsing CIDR expression: %v", err)
|
||||
return fmt.Errorf("parsing CIDR expression: '%s': %v", str, err)
|
||||
}
|
||||
h.trustedProxies = append(h.trustedProxies, ipNet)
|
||||
} else {
|
||||
ip := net.ParseIP(str)
|
||||
if ip == nil {
|
||||
return fmt.Errorf("invalid IP address: %s", str)
|
||||
ipAddr, err := netip.ParseAddr(str)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid IP address: '%s': %v", str, err)
|
||||
}
|
||||
if ipv4 := ip.To4(); ipv4 != nil {
|
||||
ip = ipv4
|
||||
}
|
||||
mask := len(ip) * 8
|
||||
h.trustedProxies = append(h.trustedProxies, &net.IPNet{
|
||||
IP: ip,
|
||||
Mask: net.CIDRMask(mask, mask),
|
||||
})
|
||||
ipNew := netip.PrefixFrom(ipAddr, ipAddr.BitLen())
|
||||
h.trustedProxies = append(h.trustedProxies, ipNew)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -672,15 +667,15 @@ func (h Handler) addForwardedHeaders(req *http.Request) error {
|
|||
if before, _, found := strings.Cut(clientIP, "%"); found {
|
||||
clientIP = before
|
||||
}
|
||||
ip := net.ParseIP(clientIP)
|
||||
if ip == nil {
|
||||
return fmt.Errorf("invalid client IP address: %s", clientIP)
|
||||
ipAddr, err := netip.ParseAddr(clientIP)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid IP address: '%s': %v", clientIP, err)
|
||||
}
|
||||
|
||||
// Check if the client is a trusted proxy
|
||||
trusted := false
|
||||
for _, ipRange := range h.trustedProxies {
|
||||
if ipRange.Contains(ip) {
|
||||
if ipRange.Contains(ipAddr) {
|
||||
trusted = true
|
||||
break
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue