gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/p2p/netutil/net.go (about) 1 // Copyright 2018 The aquachain Authors 2 // This file is part of the aquachain library. 3 // 4 // The aquachain library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The aquachain library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the aquachain library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package netutil contains extensions to the net package. 18 package netutil 19 20 import ( 21 "bytes" 22 "errors" 23 "fmt" 24 "net" 25 "sort" 26 "strings" 27 ) 28 29 var lan4, lan6, special4, special6 Netlist 30 31 func init() { 32 // Lists from RFC 5735, RFC 5156, 33 // https://www.iana.org/assignments/iana-ipv4-special-registry/ 34 lan4.Add("0.0.0.0/8") // "This" network 35 lan4.Add("10.0.0.0/8") // Private Use 36 lan4.Add("172.16.0.0/12") // Private Use 37 lan4.Add("192.168.0.0/16") // Private Use 38 lan6.Add("fe80::/10") // Link-Local 39 lan6.Add("fc00::/7") // Unique-Local 40 special4.Add("192.0.0.0/29") // IPv4 Service Continuity 41 special4.Add("192.0.0.9/32") // PCP Anycast 42 special4.Add("192.0.0.170/32") // NAT64/DNS64 Discovery 43 special4.Add("192.0.0.171/32") // NAT64/DNS64 Discovery 44 special4.Add("192.0.2.0/24") // TEST-NET-1 45 special4.Add("192.31.196.0/24") // AS112 46 special4.Add("192.52.193.0/24") // AMT 47 special4.Add("192.88.99.0/24") // 6to4 Relay Anycast 48 special4.Add("192.175.48.0/24") // AS112 49 special4.Add("198.18.0.0/15") // Device Benchmark Testing 50 special4.Add("198.51.100.0/24") // TEST-NET-2 51 special4.Add("203.0.113.0/24") // TEST-NET-3 52 special4.Add("255.255.255.255/32") // Limited Broadcast 53 54 // http://www.iana.org/assignments/iana-ipv6-special-registry/ 55 special6.Add("100::/64") 56 special6.Add("2001::/32") 57 special6.Add("2001:1::1/128") 58 special6.Add("2001:2::/48") 59 special6.Add("2001:3::/32") 60 special6.Add("2001:4:112::/48") 61 special6.Add("2001:5::/32") 62 special6.Add("2001:10::/28") 63 special6.Add("2001:20::/28") 64 special6.Add("2001:db8::/32") 65 special6.Add("2002::/16") 66 } 67 68 // Netlist is a list of IP networks. 69 type Netlist []net.IPNet 70 71 // ParseNetlist parses a comma-separated list of CIDR masks. 72 // Whitespace and extra commas are ignored. 73 func ParseNetlist(s string) (*Netlist, error) { 74 ws := strings.NewReplacer(" ", "", "\n", "", "\t", "") 75 masks := strings.Split(ws.Replace(s), ",") 76 l := make(Netlist, 0) 77 for _, mask := range masks { 78 if mask == "" { 79 continue 80 } 81 _, n, err := net.ParseCIDR(mask) 82 if err != nil { 83 return nil, err 84 } 85 l = append(l, *n) 86 } 87 return &l, nil 88 } 89 90 // MarshalTOML implements toml.MarshalerRec. 91 func (l Netlist) MarshalTOML() interface{} { 92 list := make([]string, 0, len(l)) 93 for _, net := range l { 94 list = append(list, net.String()) 95 } 96 return list 97 } 98 99 func (l Netlist) String() string { 100 list := make([]string, 0, len(l)) 101 for _, net := range l { 102 list = append(list, net.String()) 103 } 104 return strings.Join(list, ",") 105 } 106 107 // UnmarshalTOML implements toml.UnmarshalerRec. 108 func (l *Netlist) UnmarshalTOML(fn func(interface{}) error) error { 109 var masks []string 110 if err := fn(&masks); err != nil { 111 return err 112 } 113 for _, mask := range masks { 114 _, n, err := net.ParseCIDR(mask) 115 if err != nil { 116 return err 117 } 118 *l = append(*l, *n) 119 } 120 return nil 121 } 122 123 // Add parses a CIDR mask and appends it to the list. It panics for invalid masks and is 124 // intended to be used for setting up static lists. 125 func (l *Netlist) Add(cidr string) { 126 _, n, err := net.ParseCIDR(cidr) 127 if err != nil { 128 panic(err) 129 } 130 *l = append(*l, *n) 131 } 132 133 // Contains reports whether the given IP is contained in the list. 134 func (l *Netlist) Contains(ip net.IP) bool { 135 if l == nil { 136 return false 137 } 138 for _, net := range *l { 139 if net.Contains(ip) { 140 return true 141 } 142 } 143 return false 144 } 145 146 // IsLAN reports whether an IP is a local network address. 147 func IsLAN(ip net.IP) bool { 148 if ip.IsLoopback() { 149 return true 150 } 151 if v4 := ip.To4(); v4 != nil { 152 return lan4.Contains(v4) 153 } 154 return lan6.Contains(ip) 155 } 156 157 // IsSpecialNetwork reports whether an IP is located in a special-use network range 158 // This includes broadcast, multicast and documentation addresses. 159 func IsSpecialNetwork(ip net.IP) bool { 160 if ip.IsMulticast() { 161 return true 162 } 163 if v4 := ip.To4(); v4 != nil { 164 return special4.Contains(v4) 165 } 166 return special6.Contains(ip) 167 } 168 169 var ( 170 errInvalid = errors.New("invalid IP") 171 errUnspecified = errors.New("zero address") 172 errSpecial = errors.New("special network") 173 errLoopback = errors.New("loopback address from non-loopback host") 174 errLAN = errors.New("LAN address from WAN host") 175 ) 176 177 // CheckRelayIP reports whether an IP relayed from the given sender IP 178 // is a valid connection target. 179 // 180 // There are four rules: 181 // - Special network addresses are never valid. 182 // - Loopback addresses are OK if relayed by a loopback host. 183 // - LAN addresses are OK if relayed by a LAN host. 184 // - All other addresses are always acceptable. 185 func CheckRelayIP(sender, addr net.IP) error { 186 if len(addr) != net.IPv4len && len(addr) != net.IPv6len { 187 return errInvalid 188 } 189 if addr.IsUnspecified() { 190 return errUnspecified 191 } 192 if IsSpecialNetwork(addr) { 193 return errSpecial 194 } 195 if addr.IsLoopback() && !sender.IsLoopback() { 196 return errLoopback 197 } 198 if IsLAN(addr) && !IsLAN(sender) { 199 return errLAN 200 } 201 return nil 202 } 203 204 // SameNet reports whether two IP addresses have an equal prefix of the given bit length. 205 func SameNet(bits uint, ip, other net.IP) bool { 206 ip4, other4 := ip.To4(), other.To4() 207 switch { 208 case (ip4 == nil) != (other4 == nil): 209 return false 210 case ip4 != nil: 211 return sameNet(bits, ip4, other4) 212 default: 213 return sameNet(bits, ip.To16(), other.To16()) 214 } 215 } 216 217 func sameNet(bits uint, ip, other net.IP) bool { 218 nb := int(bits / 8) 219 mask := ^byte(0xFF >> (bits % 8)) 220 if mask != 0 && nb < len(ip) && ip[nb]&mask != other[nb]&mask { 221 return false 222 } 223 return nb <= len(ip) && bytes.Equal(ip[:nb], other[:nb]) 224 } 225 226 // DistinctNetSet tracks IPs, ensuring that at most N of them 227 // fall into the same network range. 228 type DistinctNetSet struct { 229 Subnet uint // number of common prefix bits 230 Limit uint // maximum number of IPs in each subnet 231 232 members map[string]uint 233 buf net.IP 234 } 235 236 // Add adds an IP address to the set. It returns false (and doesn't add the IP) if the 237 // number of existing IPs in the defined range exceeds the limit. 238 func (s *DistinctNetSet) Add(ip net.IP) bool { 239 key := s.key(ip) 240 n := s.members[string(key)] 241 if n < s.Limit { 242 s.members[string(key)] = n + 1 243 return true 244 } 245 return false 246 } 247 248 // Remove removes an IP from the set. 249 func (s *DistinctNetSet) Remove(ip net.IP) { 250 key := s.key(ip) 251 if n, ok := s.members[string(key)]; ok { 252 if n == 1 { 253 delete(s.members, string(key)) 254 } else { 255 s.members[string(key)] = n - 1 256 } 257 } 258 } 259 260 // Contains whether the given IP is contained in the set. 261 func (s DistinctNetSet) Contains(ip net.IP) bool { 262 key := s.key(ip) 263 _, ok := s.members[string(key)] 264 return ok 265 } 266 267 // Len returns the number of tracked IPs. 268 func (s DistinctNetSet) Len() int { 269 n := uint(0) 270 for _, i := range s.members { 271 n += i 272 } 273 return int(n) 274 } 275 276 // key encodes the map key for an address into a temporary buffer. 277 // 278 // The first byte of key is '4' or '6' to distinguish IPv4/IPv6 address types. 279 // The remainder of the key is the IP, truncated to the number of bits. 280 func (s *DistinctNetSet) key(ip net.IP) net.IP { 281 // Lazily initialize storage. 282 if s.members == nil { 283 s.members = make(map[string]uint) 284 s.buf = make(net.IP, 17) 285 } 286 // Canonicalize ip and bits. 287 typ := byte('6') 288 if ip4 := ip.To4(); ip4 != nil { 289 typ, ip = '4', ip4 290 } 291 bits := s.Subnet 292 if bits > uint(len(ip)*8) { 293 bits = uint(len(ip) * 8) 294 } 295 // Encode the prefix into s.buf. 296 nb := int(bits / 8) 297 mask := ^byte(0xFF >> (bits % 8)) 298 s.buf[0] = typ 299 buf := append(s.buf[:1], ip[:nb]...) 300 if nb < len(ip) && mask != 0 { 301 buf = append(buf, ip[nb]&mask) 302 } 303 return buf 304 } 305 306 // String implements fmt.Stringer 307 func (s DistinctNetSet) String() string { 308 var buf bytes.Buffer 309 buf.WriteString("{") 310 keys := make([]string, 0, len(s.members)) 311 for k := range s.members { 312 keys = append(keys, k) 313 } 314 sort.Strings(keys) 315 for i, k := range keys { 316 var ip net.IP 317 if k[0] == '4' { 318 ip = make(net.IP, 4) 319 } else { 320 ip = make(net.IP, 16) 321 } 322 copy(ip, k[1:]) 323 fmt.Fprintf(&buf, "%vĂ—%d", ip, s.members[k]) 324 if i != len(keys)-1 { 325 buf.WriteString(" ") 326 } 327 } 328 buf.WriteString("}") 329 return buf.String() 330 }