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