github.com/ethereum/go-ethereum@v1.16.1/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  	"maps"
    25  	"net"
    26  	"net/netip"
    27  	"slices"
    28  	"strings"
    29  )
    30  
    31  var special4, special6 Netlist
    32  
    33  func init() {
    34  	// Lists from RFC 5735, RFC 5156,
    35  	// https://www.iana.org/assignments/iana-ipv4-special-registry/
    36  	special4.Add("0.0.0.0/8")          // "This" network.
    37  	special4.Add("192.0.0.0/29")       // IPv4 Service Continuity
    38  	special4.Add("192.0.0.9/32")       // PCP Anycast
    39  	special4.Add("192.0.0.170/32")     // NAT64/DNS64 Discovery
    40  	special4.Add("192.0.0.171/32")     // NAT64/DNS64 Discovery
    41  	special4.Add("192.0.2.0/24")       // TEST-NET-1
    42  	special4.Add("192.31.196.0/24")    // AS112
    43  	special4.Add("192.52.193.0/24")    // AMT
    44  	special4.Add("192.88.99.0/24")     // 6to4 Relay Anycast
    45  	special4.Add("192.175.48.0/24")    // AS112
    46  	special4.Add("198.18.0.0/15")      // Device Benchmark Testing
    47  	special4.Add("198.51.100.0/24")    // TEST-NET-2
    48  	special4.Add("203.0.113.0/24")     // TEST-NET-3
    49  	special4.Add("255.255.255.255/32") // Limited Broadcast
    50  
    51  	// http://www.iana.org/assignments/iana-ipv6-special-registry/
    52  	special6.Add("100::/64")
    53  	special6.Add("2001::/32")
    54  	special6.Add("2001:1::1/128")
    55  	special6.Add("2001:2::/48")
    56  	special6.Add("2001:3::/32")
    57  	special6.Add("2001:4:112::/48")
    58  	special6.Add("2001:5::/32")
    59  	special6.Add("2001:10::/28")
    60  	special6.Add("2001:20::/28")
    61  	special6.Add("2001:db8::/32")
    62  	special6.Add("2002::/16")
    63  }
    64  
    65  // Netlist is a list of IP networks.
    66  type Netlist []netip.Prefix
    67  
    68  // ParseNetlist parses a comma-separated list of CIDR masks.
    69  // Whitespace and extra commas are ignored.
    70  func ParseNetlist(s string) (*Netlist, error) {
    71  	ws := strings.NewReplacer(" ", "", "\n", "", "\t", "")
    72  	masks := strings.Split(ws.Replace(s), ",")
    73  	l := make(Netlist, 0)
    74  	for _, mask := range masks {
    75  		if mask == "" {
    76  			continue
    77  		}
    78  		prefix, err := netip.ParsePrefix(mask)
    79  		if err != nil {
    80  			return nil, err
    81  		}
    82  		l = append(l, prefix)
    83  	}
    84  	return &l, nil
    85  }
    86  
    87  // MarshalTOML implements toml.MarshalerRec.
    88  func (l Netlist) MarshalTOML() interface{} {
    89  	list := make([]string, 0, len(l))
    90  	for _, net := range l {
    91  		list = append(list, net.String())
    92  	}
    93  	return list
    94  }
    95  
    96  // UnmarshalTOML implements toml.UnmarshalerRec.
    97  func (l *Netlist) UnmarshalTOML(fn func(interface{}) error) error {
    98  	var masks []string
    99  	if err := fn(&masks); err != nil {
   100  		return err
   101  	}
   102  	for _, mask := range masks {
   103  		prefix, err := netip.ParsePrefix(mask)
   104  		if err != nil {
   105  			return err
   106  		}
   107  		*l = append(*l, prefix)
   108  	}
   109  	return nil
   110  }
   111  
   112  // Add parses a CIDR mask and appends it to the list. It panics for invalid masks and is
   113  // intended to be used for setting up static lists.
   114  func (l *Netlist) Add(cidr string) {
   115  	prefix, err := netip.ParsePrefix(cidr)
   116  	if err != nil {
   117  		panic(err)
   118  	}
   119  	*l = append(*l, prefix)
   120  }
   121  
   122  // Contains reports whether the given IP is contained in the list.
   123  func (l *Netlist) Contains(ip net.IP) bool {
   124  	return l.ContainsAddr(IPToAddr(ip))
   125  }
   126  
   127  // ContainsAddr reports whether the given IP is contained in the list.
   128  func (l *Netlist) ContainsAddr(ip netip.Addr) bool {
   129  	if l == nil {
   130  		return false
   131  	}
   132  	for _, net := range *l {
   133  		if net.Contains(ip) {
   134  			return true
   135  		}
   136  	}
   137  	return false
   138  }
   139  
   140  // IsLAN reports whether an IP is a local network address.
   141  func IsLAN(ip net.IP) bool {
   142  	return AddrIsLAN(IPToAddr(ip))
   143  }
   144  
   145  // AddrIsLAN reports whether an IP is a local network address.
   146  func AddrIsLAN(ip netip.Addr) bool {
   147  	if ip.Is4In6() {
   148  		ip = netip.AddrFrom4(ip.As4())
   149  	}
   150  	if ip.IsLoopback() {
   151  		return true
   152  	}
   153  	return ip.IsPrivate() || ip.IsLinkLocalUnicast()
   154  }
   155  
   156  // IsSpecialNetwork reports whether an IP is located in a special-use network range
   157  // This includes broadcast, multicast and documentation addresses.
   158  func IsSpecialNetwork(ip net.IP) bool {
   159  	return AddrIsSpecialNetwork(IPToAddr(ip))
   160  }
   161  
   162  // AddrIsSpecialNetwork reports whether an IP is located in a special-use network range
   163  // This includes broadcast, multicast and documentation addresses.
   164  func AddrIsSpecialNetwork(ip netip.Addr) bool {
   165  	if ip.Is4In6() {
   166  		ip = netip.AddrFrom4(ip.As4())
   167  	}
   168  	if ip.IsMulticast() {
   169  		return true
   170  	}
   171  	if ip.Is4() {
   172  		return special4.ContainsAddr(ip)
   173  	}
   174  	return special6.ContainsAddr(ip)
   175  }
   176  
   177  var (
   178  	errInvalid     = errors.New("invalid IP")
   179  	errUnspecified = errors.New("zero address")
   180  	errSpecial     = errors.New("special network")
   181  	errLoopback    = errors.New("loopback address from non-loopback host")
   182  	errLAN         = errors.New("LAN address from WAN host")
   183  )
   184  
   185  // CheckRelayIP reports whether an IP relayed from the given sender IP
   186  // is a valid connection target.
   187  //
   188  // There are four rules:
   189  //   - Special network addresses are never valid.
   190  //   - Loopback addresses are OK if relayed by a loopback host.
   191  //   - LAN addresses are OK if relayed by a LAN host.
   192  //   - All other addresses are always acceptable.
   193  func CheckRelayIP(sender, addr net.IP) error {
   194  	return CheckRelayAddr(IPToAddr(sender), IPToAddr(addr))
   195  }
   196  
   197  // CheckRelayAddr reports whether an IP relayed from the given sender IP
   198  // is a valid connection target.
   199  //
   200  // There are four rules:
   201  //   - Special network addresses are never valid.
   202  //   - Loopback addresses are OK if relayed by a loopback host.
   203  //   - LAN addresses are OK if relayed by a LAN host.
   204  //   - All other addresses are always acceptable.
   205  func CheckRelayAddr(sender, addr netip.Addr) error {
   206  	if !addr.IsValid() {
   207  		return errInvalid
   208  	}
   209  	if addr.IsUnspecified() {
   210  		return errUnspecified
   211  	}
   212  	if AddrIsSpecialNetwork(addr) {
   213  		return errSpecial
   214  	}
   215  	if addr.IsLoopback() && !sender.IsLoopback() {
   216  		return errLoopback
   217  	}
   218  	if AddrIsLAN(addr) && !AddrIsLAN(sender) {
   219  		return errLAN
   220  	}
   221  	return nil
   222  }
   223  
   224  // SameNet reports whether two IP addresses have an equal prefix of the given bit length.
   225  func SameNet(bits uint, ip, other net.IP) bool {
   226  	ip4, other4 := ip.To4(), other.To4()
   227  	switch {
   228  	case (ip4 == nil) != (other4 == nil):
   229  		return false
   230  	case ip4 != nil:
   231  		return sameNet(bits, ip4, other4)
   232  	default:
   233  		return sameNet(bits, ip.To16(), other.To16())
   234  	}
   235  }
   236  
   237  func sameNet(bits uint, ip, other net.IP) bool {
   238  	nb := int(bits / 8)
   239  	mask := ^byte(0xFF >> (bits % 8))
   240  	if mask != 0 && nb < len(ip) && ip[nb]&mask != other[nb]&mask {
   241  		return false
   242  	}
   243  	return nb <= len(ip) && ip[:nb].Equal(other[:nb])
   244  }
   245  
   246  // DistinctNetSet tracks IPs, ensuring that at most N of them
   247  // fall into the same network range.
   248  type DistinctNetSet struct {
   249  	Subnet uint // number of common prefix bits
   250  	Limit  uint // maximum number of IPs in each subnet
   251  
   252  	members map[netip.Prefix]uint
   253  }
   254  
   255  // Add adds an IP address to the set. It returns false (and doesn't add the IP) if the
   256  // number of existing IPs in the defined range exceeds the limit.
   257  func (s *DistinctNetSet) Add(ip net.IP) bool {
   258  	return s.AddAddr(IPToAddr(ip))
   259  }
   260  
   261  // AddAddr adds an IP address to the set. It returns false (and doesn't add the IP) if the
   262  // number of existing IPs in the defined range exceeds the limit.
   263  func (s *DistinctNetSet) AddAddr(ip netip.Addr) bool {
   264  	key := s.key(ip)
   265  	n := s.members[key]
   266  	if n < s.Limit {
   267  		s.members[key] = n + 1
   268  		return true
   269  	}
   270  	return false
   271  }
   272  
   273  // Remove removes an IP from the set.
   274  func (s *DistinctNetSet) Remove(ip net.IP) {
   275  	s.RemoveAddr(IPToAddr(ip))
   276  }
   277  
   278  // RemoveAddr removes an IP from the set.
   279  func (s *DistinctNetSet) RemoveAddr(ip netip.Addr) {
   280  	key := s.key(ip)
   281  	if n, ok := s.members[key]; ok {
   282  		if n == 1 {
   283  			delete(s.members, key)
   284  		} else {
   285  			s.members[key] = n - 1
   286  		}
   287  	}
   288  }
   289  
   290  // Contains reports whether the given IP is contained in the set.
   291  func (s DistinctNetSet) Contains(ip net.IP) bool {
   292  	return s.ContainsAddr(IPToAddr(ip))
   293  }
   294  
   295  // ContainsAddr reports whether the given IP is contained in the set.
   296  func (s DistinctNetSet) ContainsAddr(ip netip.Addr) bool {
   297  	key := s.key(ip)
   298  	_, ok := s.members[key]
   299  	return ok
   300  }
   301  
   302  // Len returns the number of tracked IPs.
   303  func (s DistinctNetSet) Len() int {
   304  	n := uint(0)
   305  	for _, i := range s.members {
   306  		n += i
   307  	}
   308  	return int(n)
   309  }
   310  
   311  // key returns the map key for ip.
   312  func (s *DistinctNetSet) key(ip netip.Addr) netip.Prefix {
   313  	// Lazily initialize storage.
   314  	if s.members == nil {
   315  		s.members = make(map[netip.Prefix]uint)
   316  	}
   317  	p, err := ip.Prefix(int(s.Subnet))
   318  	if err != nil {
   319  		panic(err)
   320  	}
   321  	return p
   322  }
   323  
   324  // String implements fmt.Stringer
   325  func (s DistinctNetSet) String() string {
   326  	keys := slices.SortedFunc(maps.Keys(s.members), func(a, b netip.Prefix) int {
   327  		return strings.Compare(a.String(), b.String())
   328  	})
   329  
   330  	var buf bytes.Buffer
   331  	buf.WriteString("{")
   332  	for i, k := range keys {
   333  		fmt.Fprintf(&buf, "%vĂ—%d", k, s.members[k])
   334  		if i != len(keys)-1 {
   335  			buf.WriteString(" ")
   336  		}
   337  	}
   338  	buf.WriteString("}")
   339  	return buf.String()
   340  }