github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/p2p/netutil/net.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum 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 go-ethereum 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 go-ethereum 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 // UnmarshalTOML implements toml.UnmarshalerRec. 100 func (l *Netlist) UnmarshalTOML(fn func(interface{}) error) error { 101 var masks []string 102 if err := fn(&masks); err != nil { 103 return err 104 } 105 for _, mask := range masks { 106 _, n, err := net.ParseCIDR(mask) 107 if err != nil { 108 return err 109 } 110 *l = append(*l, *n) 111 } 112 return nil 113 } 114 115 // Add parses a CIDR mask and appends it to the list. It panics for invalid masks and is 116 // intended to be used for setting up static lists. 117 func (l *Netlist) Add(cidr string) { 118 _, n, err := net.ParseCIDR(cidr) 119 if err != nil { 120 panic(err) 121 } 122 *l = append(*l, *n) 123 } 124 125 // Contains reports whether the given IP is contained in the list. 126 func (l *Netlist) Contains(ip net.IP) bool { 127 if l == nil { 128 return false 129 } 130 for _, net := range *l { 131 if net.Contains(ip) { 132 return true 133 } 134 } 135 return false 136 } 137 138 // IsLAN reports whether an IP is a local network address. 139 func IsLAN(ip net.IP) bool { 140 if ip.IsLoopback() { 141 return true 142 } 143 if v4 := ip.To4(); v4 != nil { 144 return lan4.Contains(v4) 145 } 146 return lan6.Contains(ip) 147 } 148 149 // IsSpecialNetwork reports whether an IP is located in a special-use network range 150 // This includes broadcast, multicast and documentation addresses. 151 func IsSpecialNetwork(ip net.IP) bool { 152 if ip.IsMulticast() { 153 return true 154 } 155 if v4 := ip.To4(); v4 != nil { 156 return special4.Contains(v4) 157 } 158 return special6.Contains(ip) 159 } 160 161 var ( 162 errInvalid = errors.New("invalid IP") 163 errUnspecified = errors.New("zero address") 164 errSpecial = errors.New("special network") 165 errLoopback = errors.New("loopback address from non-loopback host") 166 errLAN = errors.New("LAN address from WAN host") 167 ) 168 169 // CheckRelayIP reports whether an IP relayed from the given sender IP 170 // is a valid connection target. 171 // 172 // There are four rules: 173 // - Special network addresses are never valid. 174 // - Loopback addresses are OK if relayed by a loopback host. 175 // - LAN addresses are OK if relayed by a LAN host. 176 // - All other addresses are always acceptable. 177 func CheckRelayIP(sender, addr net.IP) error { 178 if len(addr) != net.IPv4len && len(addr) != net.IPv6len { 179 return errInvalid 180 } 181 if addr.IsUnspecified() { 182 return errUnspecified 183 } 184 if IsSpecialNetwork(addr) { 185 return errSpecial 186 } 187 if addr.IsLoopback() && !sender.IsLoopback() { 188 return errLoopback 189 } 190 if IsLAN(addr) && !IsLAN(sender) { 191 return errLAN 192 } 193 return nil 194 } 195 196 // SameNet reports whether two IP addresses have an equal prefix of the given bit length. 197 func SameNet(bits uint, ip, other net.IP) bool { 198 ip4, other4 := ip.To4(), other.To4() 199 switch { 200 case (ip4 == nil) != (other4 == nil): 201 return false 202 case ip4 != nil: 203 return sameNet(bits, ip4, other4) 204 default: 205 return sameNet(bits, ip.To16(), other.To16()) 206 } 207 } 208 209 func sameNet(bits uint, ip, other net.IP) bool { 210 nb := int(bits / 8) 211 mask := ^byte(0xFF >> (bits % 8)) 212 if mask != 0 && nb < len(ip) && ip[nb]&mask != other[nb]&mask { 213 return false 214 } 215 return nb <= len(ip) && ip[:nb].Equal(other[:nb]) 216 } 217 218 // DistinctNetSet tracks IPs, ensuring that at most N of them 219 // fall into the same network range. 220 type DistinctNetSet struct { 221 Subnet uint // number of common prefix bits 222 Limit uint // maximum number of IPs in each subnet 223 224 members map[string]uint 225 buf net.IP 226 } 227 228 // Add adds an IP address to the set. It returns false (and doesn't add the IP) if the 229 // number of existing IPs in the defined range exceeds the limit. 230 func (s *DistinctNetSet) Add(ip net.IP) bool { 231 key := s.key(ip) 232 n := s.members[string(key)] 233 if n < s.Limit { 234 s.members[string(key)] = n + 1 235 return true 236 } 237 return false 238 } 239 240 // Remove removes an IP from the set. 241 func (s *DistinctNetSet) Remove(ip net.IP) { 242 key := s.key(ip) 243 if n, ok := s.members[string(key)]; ok { 244 if n == 1 { 245 delete(s.members, string(key)) 246 } else { 247 s.members[string(key)] = n - 1 248 } 249 } 250 } 251 252 // Contains whether the given IP is contained in the set. 253 func (s DistinctNetSet) Contains(ip net.IP) bool { 254 key := s.key(ip) 255 _, ok := s.members[string(key)] 256 return ok 257 } 258 259 // Len returns the number of tracked IPs. 260 func (s DistinctNetSet) Len() int { 261 n := uint(0) 262 for _, i := range s.members { 263 n += i 264 } 265 return int(n) 266 } 267 268 // key encodes the map key for an address into a temporary buffer. 269 // 270 // The first byte of key is '4' or '6' to distinguish IPv4/IPv6 address types. 271 // The remainder of the key is the IP, truncated to the number of bits. 272 func (s *DistinctNetSet) key(ip net.IP) net.IP { 273 // Lazily initialize storage. 274 if s.members == nil { 275 s.members = make(map[string]uint) 276 s.buf = make(net.IP, 17) 277 } 278 // Canonicalize ip and bits. 279 typ := byte('6') 280 if ip4 := ip.To4(); ip4 != nil { 281 typ, ip = '4', ip4 282 } 283 bits := s.Subnet 284 if bits > uint(len(ip)*8) { 285 bits = uint(len(ip) * 8) 286 } 287 // Encode the prefix into s.buf. 288 nb := int(bits / 8) 289 mask := ^byte(0xFF >> (bits % 8)) 290 s.buf[0] = typ 291 buf := append(s.buf[:1], ip[:nb]...) 292 if nb < len(ip) && mask != 0 { 293 buf = append(buf, ip[nb]&mask) 294 } 295 return buf 296 } 297 298 // String implements fmt.Stringer 299 func (s DistinctNetSet) String() string { 300 var buf bytes.Buffer 301 buf.WriteString("{") 302 keys := make([]string, 0, len(s.members)) 303 for k := range s.members { 304 keys = append(keys, k) 305 } 306 sort.Strings(keys) 307 for i, k := range keys { 308 var ip net.IP 309 if k[0] == '4' { 310 ip = make(net.IP, 4) 311 } else { 312 ip = make(net.IP, 16) 313 } 314 copy(ip, k[1:]) 315 fmt.Fprintf(&buf, "%vĂ—%d", ip, s.members[k]) 316 if i != len(keys)-1 { 317 buf.WriteString(" ") 318 } 319 } 320 buf.WriteString("}") 321 return buf.String() 322 }