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/matchers.go | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) (limited to 'modules/caddyhttp/matchers.go') diff --git a/modules/caddyhttp/matchers.go b/modules/caddyhttp/matchers.go index d6bbe7e..5056c9a 100644 --- a/modules/caddyhttp/matchers.go +++ b/modules/caddyhttp/matchers.go @@ -20,6 +20,7 @@ import ( "fmt" "net" "net/http" + "net/netip" "net/textproto" "net/url" "path" @@ -171,7 +172,7 @@ type ( // cidrs and zones vars should aligned always in the same // length and indexes for matching later - cidrs []*net.IPNet + cidrs []*netip.Prefix zones []string logger *zap.Logger } @@ -1311,27 +1312,24 @@ func (m *MatchRemoteIP) Provision(ctx caddy.Context) error { m.zones = append(m.zones, "") } if strings.Contains(str, "/") { - _, ipNet, err := net.ParseCIDR(str) + ipNet, err := netip.ParsePrefix(str) if err != nil { return fmt.Errorf("parsing CIDR expression '%s': %v", str, err) } - m.cidrs = append(m.cidrs, ipNet) + m.cidrs = append(m.cidrs, &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) } - mask := len(ip) * 8 - m.cidrs = append(m.cidrs, &net.IPNet{ - IP: ip, - Mask: net.CIDRMask(mask, mask), - }) + ipNew := netip.PrefixFrom(ipAddr, ipAddr.BitLen()) + m.cidrs = append(m.cidrs, &ipNew) } } return nil } -func (m MatchRemoteIP) getClientIP(r *http.Request) (net.IP, string, error) { +func (m MatchRemoteIP) getClientIP(r *http.Request) (netip.Addr, string, error) { remote := r.RemoteAddr zoneID := "" if m.Forwarded { @@ -1350,11 +1348,11 @@ func (m MatchRemoteIP) getClientIP(r *http.Request) (net.IP, string, error) { ipStr = split[0] zoneID = split[1] } - ip := net.ParseIP(ipStr) - if ip == nil { - return nil, zoneID, fmt.Errorf("invalid client IP address: %s", ipStr) + ipAddr, err := netip.ParseAddr(ipStr) + if err != nil { + return netip.IPv4Unspecified(), "", err } - return ip, zoneID, nil + return ipAddr, zoneID, nil } // Match returns true if r matches m. -- cgit v1.2.3