Source file
src/net/hosts.go
1
2
3
4
5 package net
6
7 import (
8 "internal/bytealg"
9 "sync"
10 "time"
11 )
12
13 const cacheMaxAge = 5 * time.Second
14
15 func parseLiteralIP(addr string) string {
16 var ip IP
17 var zone string
18 ip = parseIPv4(addr)
19 if ip == nil {
20 ip, zone = parseIPv6Zone(addr)
21 }
22 if ip == nil {
23 return ""
24 }
25 if zone == "" {
26 return ip.String()
27 }
28 return ip.String() + "%" + zone
29 }
30
31
32 var hosts struct {
33 sync.Mutex
34
35
36
37
38
39 byName map[string][]string
40
41
42
43
44 byAddr map[string][]string
45
46 expire time.Time
47 path string
48 mtime time.Time
49 size int64
50 }
51
52 func readHosts() {
53 now := time.Now()
54 hp := testHookHostsPath
55
56 if now.Before(hosts.expire) && hosts.path == hp && len(hosts.byName) > 0 {
57 return
58 }
59 mtime, size, err := stat(hp)
60 if err == nil && hosts.path == hp && hosts.mtime.Equal(mtime) && hosts.size == size {
61 hosts.expire = now.Add(cacheMaxAge)
62 return
63 }
64
65 hs := make(map[string][]string)
66 is := make(map[string][]string)
67 var file *file
68 if file, _ = open(hp); file == nil {
69 return
70 }
71 for line, ok := file.readLine(); ok; line, ok = file.readLine() {
72 if i := bytealg.IndexByteString(line, '#'); i >= 0 {
73
74 line = line[0:i]
75 }
76 f := getFields(line)
77 if len(f) < 2 {
78 continue
79 }
80 addr := parseLiteralIP(f[0])
81 if addr == "" {
82 continue
83 }
84 for i := 1; i < len(f); i++ {
85 name := absDomainName(f[i])
86 h := []byte(f[i])
87 lowerASCIIBytes(h)
88 key := absDomainName(string(h))
89 hs[key] = append(hs[key], addr)
90 is[addr] = append(is[addr], name)
91 }
92 }
93
94 hosts.expire = now.Add(cacheMaxAge)
95 hosts.path = hp
96 hosts.byName = hs
97 hosts.byAddr = is
98 hosts.mtime = mtime
99 hosts.size = size
100 file.close()
101 }
102
103
104 func lookupStaticHost(host string) []string {
105 hosts.Lock()
106 defer hosts.Unlock()
107 readHosts()
108 if len(hosts.byName) != 0 {
109 if hasUpperCase(host) {
110 lowerHost := []byte(host)
111 lowerASCIIBytes(lowerHost)
112 host = string(lowerHost)
113 }
114 if ips, ok := hosts.byName[absDomainName(host)]; ok {
115 ipsCp := make([]string, len(ips))
116 copy(ipsCp, ips)
117 return ipsCp
118 }
119 }
120 return nil
121 }
122
123
124 func lookupStaticAddr(addr string) []string {
125 hosts.Lock()
126 defer hosts.Unlock()
127 readHosts()
128 addr = parseLiteralIP(addr)
129 if addr == "" {
130 return nil
131 }
132 if len(hosts.byAddr) != 0 {
133 if hosts, ok := hosts.byAddr[addr]; ok {
134 hostsCp := make([]string, len(hosts))
135 copy(hostsCp, hosts)
136 return hostsCp
137 }
138 }
139 return nil
140 }
141
View as plain text