rehostsfile.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. package rehosts
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "io"
  7. "net"
  8. "os"
  9. "regexp"
  10. "strings"
  11. "sync"
  12. "time"
  13. "unicode"
  14. "golang.org/x/net/idna"
  15. )
  16. type Matcher interface {
  17. Match(*string) bool
  18. }
  19. // Single hosts file record that maps regex matcher to IP (v4 or v6)
  20. type RehostsFileRecord struct {
  21. Match func(str string) bool
  22. AddrV4 []net.IP
  23. AddrV6 []net.IP
  24. }
  25. type options struct {
  26. // Auto reload period
  27. reload time.Duration
  28. // TTL of DNS record
  29. ttl uint32
  30. }
  31. func newOptions() *options {
  32. return &options{
  33. ttl: 3600,
  34. reload: 5 * time.Second,
  35. }
  36. }
  37. type RehostsFile struct {
  38. // DNS Regex records
  39. records []*RehostsFileRecord
  40. // List pf authoritative origins
  41. Origins []string
  42. // File attrubutes for relaod check
  43. mtime time.Time
  44. fsize int64
  45. // Update lock
  46. sync.RWMutex
  47. // Path to file
  48. path string
  49. // Options from Caddyfile
  50. options *options
  51. }
  52. func (r *RehostsFile) readRehosts() {
  53. file, err := os.Open(r.path)
  54. if err != nil {
  55. return
  56. }
  57. defer file.Close()
  58. // Check if file has changed
  59. stat, err := file.Stat()
  60. if err != nil {
  61. return
  62. }
  63. r.RLock()
  64. fsize := r.fsize
  65. mtime := r.mtime
  66. r.RUnlock()
  67. if mtime.Equal(stat.ModTime()) && fsize == stat.Size() {
  68. return
  69. }
  70. newRecords := r.parse(file)
  71. log.Debugf("Parsed rehosts file into %d entries", len(newRecords))
  72. r.Lock()
  73. r.records = newRecords
  74. r.mtime = stat.ModTime()
  75. r.fsize = stat.Size()
  76. r.Unlock()
  77. }
  78. func parseIP(addr string) net.IP {
  79. addr = strings.TrimSpace(addr)
  80. // discard IPv6 zone (lol?)
  81. if pos := strings.Index(addr, "%"); pos >= 0 {
  82. addr = addr[0:pos]
  83. }
  84. return net.ParseIP(addr)
  85. }
  86. func verifyWildcard(s string) bool {
  87. for _, c := range s {
  88. if unicode.IsLetter(c) {
  89. continue
  90. }
  91. if unicode.IsDigit(c) {
  92. continue
  93. }
  94. if (c == '*') || (c == '.') || (c == '-') || (c == '_') {
  95. continue
  96. }
  97. return false
  98. }
  99. return true
  100. }
  101. // Parse reads the hostsfile and populates the byName and addr maps.
  102. func (h *RehostsFile) parse(r io.Reader) []*RehostsFileRecord {
  103. records := make([]*RehostsFileRecord, 0)
  104. wildcardReplacer := strings.NewReplacer(".", "\\.", "*", ".*")
  105. scanner := bufio.NewScanner(r)
  106. for scanner.Scan() {
  107. line := scanner.Bytes()
  108. // Remove all comments
  109. if commentPos := bytes.Index(line, []byte{'#'}); commentPos >= 0 {
  110. line = line[0:commentPos]
  111. }
  112. line = bytes.TrimSpace(line)
  113. if len(line) == 0 {
  114. continue
  115. }
  116. // Regex mode
  117. if atPos := bytes.Index(line, []byte{'@'}); atPos >= 0 {
  118. // Try parse IP
  119. ipStr := string(line[0:atPos])
  120. ip := parseIP(ipStr)
  121. if ip == nil {
  122. log.Warningf("Invalid ip %q", ipStr)
  123. continue
  124. }
  125. // Try parse regexp
  126. regexpStr := string(bytes.TrimSpace(line[atPos+1:]))
  127. regexp, err := regexp.Compile(regexpStr)
  128. if err != nil {
  129. log.Warningf("Invalid regexp %q: %v", regexp, err)
  130. continue
  131. }
  132. // TODO: Check for authoritative zones?
  133. // Combine together
  134. var record RehostsFileRecord
  135. record.Match = func(str string) bool {
  136. return regexp.MatchString(str)
  137. }
  138. if ip.To4() != nil {
  139. record.AddrV4 = append(record.AddrV4, ip)
  140. } else {
  141. record.AddrV6 = append(record.AddrV6, ip)
  142. }
  143. records = append(records, &record)
  144. } else {
  145. fields := bytes.Fields(line)
  146. // Try parse IP
  147. ipStr := string(fields[0])
  148. ip := parseIP(ipStr)
  149. if ip == nil {
  150. log.Warningf("Invalid ip %q", ipStr)
  151. continue
  152. }
  153. for fieldIndex := 1; fieldIndex < len(fields); fieldIndex++ {
  154. fieldStr := string(fields[fieldIndex])
  155. // Single record per each domain in line
  156. var record RehostsFileRecord
  157. if ip.To4() != nil {
  158. record.AddrV4 = append(record.AddrV4, ip)
  159. } else {
  160. record.AddrV6 = append(record.AddrV6, ip)
  161. }
  162. // Check if addr is some kind of wildcard
  163. if wcPos := strings.Index(fieldStr, "*"); wcPos >= 0 {
  164. // Normalize
  165. if !verifyWildcard(fieldStr) {
  166. log.Warningf("Invalid wildcard %q", fieldStr)
  167. continue
  168. }
  169. regexpStr := wildcardReplacer.Replace(fieldStr)
  170. regexpStr = strings.ToLower(regexpStr)
  171. // Try parse regexp
  172. regexp, err := regexp.Compile(regexpStr)
  173. if err != nil {
  174. log.Warningf("Invalid regexp %q: %v", regexp, err)
  175. continue
  176. }
  177. // TODO: Check for authoritative zones?
  178. record.Match = func(str string) bool {
  179. return regexp.MatchString(str)
  180. }
  181. } else {
  182. // Normalize
  183. hostName := strings.ToLower(fieldStr)
  184. record.Match = func(str string) bool {
  185. return hostName == str
  186. }
  187. }
  188. records = append(records, &record)
  189. }
  190. }
  191. }
  192. return records
  193. }
  194. func DeFQDNnIDNA(host string) (string, error) {
  195. if !(len(host) > 0 && host[len(host)-1] == '.') {
  196. return "", errors.New("not FQDN")
  197. }
  198. host = host[:len(host)-1]
  199. host = strings.ToLower(host)
  200. unicodeHost, err := idna.ToUnicode(host)
  201. if err != nil {
  202. return "", err
  203. }
  204. return unicodeHost, nil
  205. }
  206. // Lookup host IPv4 records
  207. func (r *RehostsFile) LookupStaticHostV4(host string) []net.IP {
  208. r.RLock()
  209. defer r.RUnlock()
  210. if r.records == nil {
  211. return nil
  212. }
  213. for _, record := range r.records {
  214. unicodeHost, err := DeFQDNnIDNA(host)
  215. if err != nil {
  216. log.Debugf("Invalid IDNA %q: %v", host, err)
  217. return nil
  218. }
  219. if record.Match(unicodeHost) && len(record.AddrV4) != 0 {
  220. addr4Copy := make([]net.IP, len(record.AddrV4))
  221. copy(addr4Copy, record.AddrV4)
  222. return addr4Copy
  223. }
  224. }
  225. return nil
  226. }
  227. // Lookup host IPv6 records
  228. func (r *RehostsFile) LookupStaticHostV6(host string) []net.IP {
  229. r.RLock()
  230. defer r.RUnlock()
  231. if r.records == nil {
  232. return nil
  233. }
  234. for _, record := range r.records {
  235. unicodeHost, err := DeFQDNnIDNA(host)
  236. if err != nil {
  237. log.Debugf("Invalid IDNA %q: %v", host, err)
  238. return nil
  239. }
  240. if record.Match(unicodeHost) && len(record.AddrV6) != 0 {
  241. addr6Copy := make([]net.IP, len(record.AddrV6))
  242. copy(addr6Copy, record.AddrV6)
  243. return addr6Copy
  244. }
  245. }
  246. return nil
  247. }