use the new multiaddr utilities in IsPublicAddr/IsPrivateAddr

This now means that addresses must *start* with the an IP address, we won't just
pull one out of the middle.
This commit is contained in:
Steven Allen 2018-10-18 13:56:20 +01:00
parent 7b43167897
commit 0425819f0e

View File

@ -67,36 +67,45 @@ func parseCIDR(cidrs []string) []*net.IPNet {
// IsPublicAddr retruns true if the IP part of the multiaddr is a publicly routable address // IsPublicAddr retruns true if the IP part of the multiaddr is a publicly routable address
func IsPublicAddr(a ma.Multiaddr) bool { func IsPublicAddr(a ma.Multiaddr) bool {
ip, err := a.ValueForProtocol(ma.P_IP4) isPublic := false
if err == nil { ma.ForEach(a, func(c ma.Component) bool {
return !inAddrRange(ip, Private4) && !inAddrRange(ip, Unroutable4) switch c.Protocol().Code {
} case ma.P_IP6ZONE:
return true
ip, err = a.ValueForProtocol(ma.P_IP6) default:
if err == nil { return false
return !inAddrRange(ip, Private6) && !inAddrRange(ip, Unroutable6) case ma.P_IP4:
} ip := net.IP(c.RawValue())
isPublic = !inAddrRange(ip, Private4) && !inAddrRange(ip, Unroutable4)
return false case ma.P_IP6:
ip := net.IP(c.RawValue())
isPublic = !inAddrRange(ip, Private6) && !inAddrRange(ip, Unroutable6)
}
return false
})
return isPublic
} }
// IsPrivateAddr returns true if the IP part of the mutiaddr is in a private network // IsPrivateAddr returns true if the IP part of the mutiaddr is in a private network
func IsPrivateAddr(a ma.Multiaddr) bool { func IsPrivateAddr(a ma.Multiaddr) bool {
ip, err := a.ValueForProtocol(ma.P_IP4) isPrivate := false
if err == nil { ma.ForEach(a, func(c ma.Component) bool {
return inAddrRange(ip, Private4) switch c.Protocol().Code {
} case ma.P_IP6ZONE:
return true
ip, err = a.ValueForProtocol(ma.P_IP6) default:
if err == nil { return false
return inAddrRange(ip, Private6) case ma.P_IP4:
} isPrivate = inAddrRange(net.IP(c.RawValue()), Private4)
case ma.P_IP6:
return false isPrivate = inAddrRange(net.IP(c.RawValue()), Private6)
}
return false
})
return isPrivate
} }
func inAddrRange(s string, ipnets []*net.IPNet) bool { func inAddrRange(ip net.IP, ipnets []*net.IPNet) bool {
ip := net.ParseIP(s)
for _, ipnet := range ipnets { for _, ipnet := range ipnets {
if ipnet.Contains(ip) { if ipnet.Contains(ip) {
return true return true