hosts.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. package hosts
  2. // this file copy and modify from golang's std net/hosts.go
  3. import (
  4. "errors"
  5. "io"
  6. "io/fs"
  7. "net/netip"
  8. "os"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var hostsFilePath = "/etc/hosts"
  14. const cacheMaxAge = 5 * time.Second
  15. func parseLiteralIP(addr string) string {
  16. ip, err := netip.ParseAddr(addr)
  17. if err != nil {
  18. return ""
  19. }
  20. return ip.String()
  21. }
  22. type byName struct {
  23. addrs []string
  24. canonicalName string
  25. }
  26. // hosts contains known host entries.
  27. var hosts struct {
  28. sync.Mutex
  29. // Key for the list of literal IP addresses must be a host
  30. // name. It would be part of DNS labels, a FQDN or an absolute
  31. // FQDN.
  32. // For now the key is converted to lower case for convenience.
  33. byName map[string]byName
  34. // Key for the list of host names must be a literal IP address
  35. // including IPv6 address with zone identifier.
  36. // We don't support old-classful IP address notation.
  37. byAddr map[string][]string
  38. expire time.Time
  39. path string
  40. mtime time.Time
  41. size int64
  42. }
  43. func readHosts() {
  44. now := time.Now()
  45. hp := hostsFilePath
  46. if now.Before(hosts.expire) && hosts.path == hp && len(hosts.byName) > 0 {
  47. return
  48. }
  49. mtime, size, err := stat(hp)
  50. if err == nil && hosts.path == hp && hosts.mtime.Equal(mtime) && hosts.size == size {
  51. hosts.expire = now.Add(cacheMaxAge)
  52. return
  53. }
  54. hs := make(map[string]byName)
  55. is := make(map[string][]string)
  56. file, err := open(hp)
  57. if err != nil {
  58. if !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, fs.ErrPermission) {
  59. return
  60. }
  61. }
  62. if file != nil {
  63. defer file.close()
  64. for line, ok := file.readLine(); ok; line, ok = file.readLine() {
  65. if i := strings.IndexByte(line, '#'); i >= 0 {
  66. // Discard comments.
  67. line = line[0:i]
  68. }
  69. f := getFields(line)
  70. if len(f) < 2 {
  71. continue
  72. }
  73. addr := parseLiteralIP(f[0])
  74. if addr == "" {
  75. continue
  76. }
  77. var canonical string
  78. for i := 1; i < len(f); i++ {
  79. name := absDomainName(f[i])
  80. h := []byte(f[i])
  81. lowerASCIIBytes(h)
  82. key := absDomainName(string(h))
  83. if i == 1 {
  84. canonical = key
  85. }
  86. is[addr] = append(is[addr], name)
  87. if v, ok := hs[key]; ok {
  88. hs[key] = byName{
  89. addrs: append(v.addrs, addr),
  90. canonicalName: v.canonicalName,
  91. }
  92. continue
  93. }
  94. hs[key] = byName{
  95. addrs: []string{addr},
  96. canonicalName: canonical,
  97. }
  98. }
  99. }
  100. }
  101. // Update the data cache.
  102. hosts.expire = now.Add(cacheMaxAge)
  103. hosts.path = hp
  104. hosts.byName = hs
  105. hosts.byAddr = is
  106. hosts.mtime = mtime
  107. hosts.size = size
  108. }
  109. // LookupStaticHost looks up the addresses and the canonical name for the given host from /etc/hosts.
  110. func LookupStaticHost(host string) ([]string, string) {
  111. hosts.Lock()
  112. defer hosts.Unlock()
  113. readHosts()
  114. if len(hosts.byName) != 0 {
  115. if hasUpperCase(host) {
  116. lowerHost := []byte(host)
  117. lowerASCIIBytes(lowerHost)
  118. host = string(lowerHost)
  119. }
  120. if byName, ok := hosts.byName[absDomainName(host)]; ok {
  121. ipsCp := make([]string, len(byName.addrs))
  122. copy(ipsCp, byName.addrs)
  123. return ipsCp, byName.canonicalName
  124. }
  125. }
  126. return nil, ""
  127. }
  128. // LookupStaticAddr looks up the hosts for the given address from /etc/hosts.
  129. func LookupStaticAddr(addr string) []string {
  130. hosts.Lock()
  131. defer hosts.Unlock()
  132. readHosts()
  133. addr = parseLiteralIP(addr)
  134. if addr == "" {
  135. return nil
  136. }
  137. if len(hosts.byAddr) != 0 {
  138. if hosts, ok := hosts.byAddr[addr]; ok {
  139. hostsCp := make([]string, len(hosts))
  140. copy(hostsCp, hosts)
  141. return hostsCp
  142. }
  143. }
  144. return nil
  145. }
  146. func stat(name string) (mtime time.Time, size int64, err error) {
  147. st, err := os.Stat(name)
  148. if err != nil {
  149. return time.Time{}, 0, err
  150. }
  151. return st.ModTime(), st.Size(), nil
  152. }
  153. type file struct {
  154. file *os.File
  155. data []byte
  156. atEOF bool
  157. }
  158. func (f *file) close() { f.file.Close() }
  159. func (f *file) getLineFromData() (s string, ok bool) {
  160. data := f.data
  161. i := 0
  162. for i = 0; i < len(data); i++ {
  163. if data[i] == '\n' {
  164. s = string(data[0:i])
  165. ok = true
  166. // move data
  167. i++
  168. n := len(data) - i
  169. copy(data[0:], data[i:])
  170. f.data = data[0:n]
  171. return
  172. }
  173. }
  174. if f.atEOF && len(f.data) > 0 {
  175. // EOF, return all we have
  176. s = string(data)
  177. f.data = f.data[0:0]
  178. ok = true
  179. }
  180. return
  181. }
  182. func (f *file) readLine() (s string, ok bool) {
  183. if s, ok = f.getLineFromData(); ok {
  184. return
  185. }
  186. if len(f.data) < cap(f.data) {
  187. ln := len(f.data)
  188. n, err := io.ReadFull(f.file, f.data[ln:cap(f.data)])
  189. if n >= 0 {
  190. f.data = f.data[0 : ln+n]
  191. }
  192. if err == io.EOF || err == io.ErrUnexpectedEOF {
  193. f.atEOF = true
  194. }
  195. }
  196. s, ok = f.getLineFromData()
  197. return
  198. }
  199. func (f *file) stat() (mtime time.Time, size int64, err error) {
  200. st, err := f.file.Stat()
  201. if err != nil {
  202. return time.Time{}, 0, err
  203. }
  204. return st.ModTime(), st.Size(), nil
  205. }
  206. func open(name string) (*file, error) {
  207. fd, err := os.Open(name)
  208. if err != nil {
  209. return nil, err
  210. }
  211. return &file{fd, make([]byte, 0, 64*1024), false}, nil
  212. }
  213. func getFields(s string) []string { return splitAtBytes(s, " \r\t\n") }
  214. // Count occurrences in s of any bytes in t.
  215. func countAnyByte(s string, t string) int {
  216. n := 0
  217. for i := 0; i < len(s); i++ {
  218. if strings.IndexByte(t, s[i]) >= 0 {
  219. n++
  220. }
  221. }
  222. return n
  223. }
  224. // Split s at any bytes in t.
  225. func splitAtBytes(s string, t string) []string {
  226. a := make([]string, 1+countAnyByte(s, t))
  227. n := 0
  228. last := 0
  229. for i := 0; i < len(s); i++ {
  230. if strings.IndexByte(t, s[i]) >= 0 {
  231. if last < i {
  232. a[n] = s[last:i]
  233. n++
  234. }
  235. last = i + 1
  236. }
  237. }
  238. if last < len(s) {
  239. a[n] = s[last:]
  240. n++
  241. }
  242. return a[0:n]
  243. }
  244. // lowerASCIIBytes makes x ASCII lowercase in-place.
  245. func lowerASCIIBytes(x []byte) {
  246. for i, b := range x {
  247. if 'A' <= b && b <= 'Z' {
  248. x[i] += 'a' - 'A'
  249. }
  250. }
  251. }
  252. // hasUpperCase tells whether the given string contains at least one upper-case.
  253. func hasUpperCase(s string) bool {
  254. for i := range s {
  255. if 'A' <= s[i] && s[i] <= 'Z' {
  256. return true
  257. }
  258. }
  259. return false
  260. }
  261. // absDomainName returns an absolute domain name which ends with a
  262. // trailing dot to match pure Go reverse resolver and all other lookup
  263. // routines.
  264. // See golang.org/issue/12189.
  265. // But we don't want to add dots for local names from /etc/hosts.
  266. // It's hard to tell so we settle on the heuristic that names without dots
  267. // (like "localhost" or "myhost") do not get trailing dots, but any other
  268. // names do.
  269. func absDomainName(s string) string {
  270. if strings.IndexByte(s, '.') != -1 && s[len(s)-1] != '.' {
  271. s += "."
  272. }
  273. return s
  274. }