From c7772588bd44ceffcc0ba4817e4d43c826675379 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wilczy=C5=84skiT?= <102859171+WilczynskiT@users.noreply.github.com> Date: Thu, 18 Aug 2022 00:10:57 +0200 Subject: core: Change net.IP to netip.Addr; use netip.Prefix (#4966) Co-authored-by: Matt Holt --- modules/caddyhttp/reverseproxy/reverseproxy.go | 31 +++++++++++--------------- 1 file changed, 13 insertions(+), 18 deletions(-) (limited to 'modules/caddyhttp/reverseproxy') diff --git a/modules/caddyhttp/reverseproxy/reverseproxy.go b/modules/caddyhttp/reverseproxy/reverseproxy.go index cc6b530..0890306 100644 --- a/modules/caddyhttp/reverseproxy/reverseproxy.go +++ b/modules/caddyhttp/reverseproxy/reverseproxy.go @@ -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) - } - if ipv4 := ip.To4(); ipv4 != nil { - ip = ipv4 + ipAddr, err := netip.ParseAddr(str) + if err != nil { + return fmt.Errorf("invalid IP address: '%s': %v", str, err) } - 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 } -- cgit v1.2.3