您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

net.go 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2016 Daniel Oaks <daniel@danieloaks.net>
  3. // released under the MIT license
  4. package utils
  5. import (
  6. "net"
  7. "regexp"
  8. "strings"
  9. )
  10. var (
  11. // subnet mask for an ipv6 /128:
  12. mask128 = net.CIDRMask(128, 128)
  13. IPv4LoopbackAddress = net.ParseIP("127.0.0.1").To16()
  14. validHostnameLabelRegexp = regexp.MustCompile(`^[0-9A-Za-z.\-]+$`)
  15. )
  16. // AddrToIP returns the IP address for a net.Addr; unix domain sockets are treated as IPv4 loopback
  17. func AddrToIP(addr net.Addr) net.IP {
  18. if tcpaddr, ok := addr.(*net.TCPAddr); ok {
  19. return tcpaddr.IP.To16()
  20. } else if AddrIsUnix(addr) {
  21. return IPv4LoopbackAddress
  22. } else {
  23. return nil
  24. }
  25. }
  26. // AddrIsUnix returns whether the address is a unix domain socket.
  27. func AddrIsUnix(addr net.Addr) bool {
  28. _, ok := addr.(*net.UnixAddr)
  29. return ok
  30. }
  31. // IPStringToHostname converts a string representation of an IP address to an IRC-ready hostname
  32. func IPStringToHostname(ipStr string) string {
  33. if 0 < len(ipStr) && ipStr[0] == ':' {
  34. // fix for IPv6 hostnames (so they don't start with a colon), same as all other IRCds
  35. ipStr = "0" + ipStr
  36. }
  37. return ipStr
  38. }
  39. // IsHostname returns whether we consider `name` a valid hostname.
  40. func IsHostname(name string) bool {
  41. name = strings.TrimSuffix(name, ".")
  42. if len(name) < 1 || len(name) > 253 {
  43. return false
  44. }
  45. // ensure each part of hostname is valid
  46. for _, part := range strings.Split(name, ".") {
  47. if len(part) < 1 || len(part) > 63 || strings.HasPrefix(part, "-") || strings.HasSuffix(part, "-") {
  48. return false
  49. }
  50. if !validHostnameLabelRegexp.MatchString(part) {
  51. return false
  52. }
  53. }
  54. return true
  55. }
  56. // IsServerName returns whether we consider `name` a valid IRC server name.
  57. func IsServerName(name string) bool {
  58. // IRC server names specifically require a period
  59. return IsHostname(name) && strings.IndexByte(name, '.') != -1
  60. }
  61. // Convenience to test whether `ip` is contained in any of `nets`.
  62. func IPInNets(ip net.IP, nets []net.IPNet) bool {
  63. for _, network := range nets {
  64. if network.Contains(ip) {
  65. return true
  66. }
  67. }
  68. return false
  69. }
  70. // NormalizeIPToNet represents an address (v4 or v6) as the v6 /128 CIDR
  71. // containing only it.
  72. func NormalizeIPToNet(addr net.IP) (network net.IPNet) {
  73. // represent ipv4 addresses as ipv6 addresses, using the 4-in-6 prefix
  74. // (actually this should be a no-op for any address returned by ParseIP)
  75. addr = addr.To16()
  76. // the network corresponding to this address is now an ipv6 /128:
  77. return net.IPNet{
  78. IP: addr,
  79. Mask: mask128,
  80. }
  81. }
  82. // NormalizeNet normalizes an IPNet to a v6 CIDR, using the 4-in-6 prefix.
  83. // (this is like IP.To16(), but for IPNet instead of IP)
  84. func NormalizeNet(network net.IPNet) (result net.IPNet) {
  85. if len(network.IP) == 16 {
  86. return network
  87. }
  88. ones, _ := network.Mask.Size()
  89. return net.IPNet{
  90. IP: network.IP.To16(),
  91. // include the 96 bits of the 4-in-6 prefix
  92. Mask: net.CIDRMask(96+ones, 128),
  93. }
  94. }
  95. // Given a network, produce a human-readable string
  96. // (i.e., CIDR if it's actually a network, IPv6 address if it's a v6 /128,
  97. // dotted quad if it's a v4 /32).
  98. func NetToNormalizedString(network net.IPNet) string {
  99. ones, bits := network.Mask.Size()
  100. if ones == bits && ones == len(network.IP)*8 {
  101. // either a /32 or a /128, output the address:
  102. return network.IP.String()
  103. }
  104. return network.String()
  105. }
  106. // Parse a human-readable description (an address or CIDR, either v4 or v6)
  107. // into a normalized v6 net.IPNet.
  108. func NormalizedNetFromString(str string) (result net.IPNet, err error) {
  109. _, network, err := net.ParseCIDR(str)
  110. if err == nil {
  111. return NormalizeNet(*network), nil
  112. }
  113. ip := net.ParseIP(str)
  114. if ip == nil {
  115. err = &net.AddrError{
  116. Err: "Couldn't interpret as either CIDR or address",
  117. Addr: str,
  118. }
  119. return
  120. }
  121. return NormalizeIPToNet(ip), nil
  122. }
  123. // Parse a list of IPs and nets as they would appear in one of our config
  124. // files, e.g., proxy-allowed-from or a throttling exemption list.
  125. func ParseNetList(netList []string) (nets []net.IPNet, err error) {
  126. var network net.IPNet
  127. for _, netStr := range netList {
  128. if netStr == "localhost" {
  129. ipv4Loopback, _ := NormalizedNetFromString("127.0.0.0/8")
  130. ipv6Loopback, _ := NormalizedNetFromString("::1/128")
  131. nets = append(nets, ipv4Loopback)
  132. nets = append(nets, ipv6Loopback)
  133. continue
  134. }
  135. network, err = NormalizedNetFromString(netStr)
  136. if err != nil {
  137. return
  138. } else {
  139. nets = append(nets, network)
  140. }
  141. }
  142. return
  143. }