dns.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "bufio"
  22. "bytes"
  23. "errors"
  24. "math/rand"
  25. "net"
  26. "strings"
  27. "sync/atomic"
  28. "time"
  29. "github.com/Psiphon-Labs/goarista/monotime"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  31. )
  32. const (
  33. DNS_SYSTEM_CONFIG_FILENAME = "/etc/resolv.conf"
  34. DNS_SYSTEM_CONFIG_RELOAD_PERIOD = 5 * time.Second
  35. DNS_RESOLVER_PORT = 53
  36. )
  37. // DNSResolver maintains fresh DNS resolver values, monitoring
  38. // "/etc/resolv.conf" on platforms where it is available; and
  39. // otherwise using a default value.
  40. type DNSResolver struct {
  41. // Note: 64-bit ints used with atomic operations are placed
  42. // at the start of struct to ensure 64-bit alignment.
  43. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  44. lastReloadTime int64
  45. common.ReloadableFile
  46. isReloading int32
  47. resolvers []net.IP
  48. }
  49. // NewDNSResolver initializes a new DNSResolver, loading it with
  50. // fresh resolver values. The load must succeed, so either
  51. // "/etc/resolv.conf" must contain valid "nameserver" lines with
  52. // a DNS server IP address, or a valid "defaultResolver" default
  53. // value must be provided.
  54. // On systems without "/etc/resolv.conf", "defaultResolver" is
  55. // required.
  56. //
  57. // The resolver is considered stale and reloaded if last checked
  58. // more than 5 seconds before the last Get(), which is similar to
  59. // frequencies in other implementations:
  60. //
  61. // - https://golang.org/src/net/dnsclient_unix.go,
  62. // resolverConfig.tryUpdate: 5 seconds
  63. //
  64. // - https://github.com/ambrop72/badvpn/blob/master/udpgw/udpgw.c,
  65. // maybe_update_dns: 2 seconds
  66. //
  67. func NewDNSResolver(defaultResolver string) (*DNSResolver, error) {
  68. dns := &DNSResolver{
  69. lastReloadTime: int64(monotime.Now()),
  70. }
  71. dns.ReloadableFile = common.NewReloadableFile(
  72. DNS_SYSTEM_CONFIG_FILENAME,
  73. func(fileContent []byte) error {
  74. resolvers, err := parseResolveConf(fileContent)
  75. if err != nil {
  76. // On error, state remains the same
  77. return common.ContextError(err)
  78. }
  79. dns.resolvers = resolvers
  80. log.WithContextFields(
  81. LogFields{
  82. "resolvers": resolvers,
  83. }).Debug("loaded system DNS resolvers")
  84. return nil
  85. })
  86. _, err := dns.Reload()
  87. if err != nil {
  88. if defaultResolver == "" {
  89. return nil, common.ContextError(err)
  90. }
  91. log.WithContextFields(
  92. LogFields{"err": err}).Info(
  93. "failed to load system DNS resolver; using default")
  94. resolver, err := parseResolver(defaultResolver)
  95. if err != nil {
  96. return nil, common.ContextError(err)
  97. }
  98. dns.resolvers = []net.IP{resolver}
  99. }
  100. return dns, nil
  101. }
  102. // Get returns one of the cached resolvers, selected at random,
  103. // after first updating the cached values if they're stale. If
  104. // reloading fails, the previous values are used.
  105. //
  106. // Randomly selecting any one of the configured resolvers is
  107. // expected to be more resiliant to failure; e.g., if one of
  108. // the resolvers becomes unavailable.
  109. func (dns *DNSResolver) Get() net.IP {
  110. dns.reloadWhenStale()
  111. dns.ReloadableFile.RLock()
  112. defer dns.ReloadableFile.RUnlock()
  113. return dns.resolvers[rand.Intn(len(dns.resolvers))]
  114. }
  115. func (dns *DNSResolver) reloadWhenStale() {
  116. // Every UDP DNS port forward frequently calls Get(), so this code
  117. // is intended to minimize blocking. Most callers will hit just the
  118. // atomic.LoadInt64 reload time check and the RLock (an atomic.AddInt32
  119. // when no write lock is pending). An atomic.CompareAndSwapInt32 is
  120. // used to ensure only one goroutine enters Reload() and blocks on
  121. // its write lock. Finally, since since ReloadableFile.Reload
  122. // checks whether the underlying file has changed _before_ acquiring a
  123. // write lock, we only incur write lock blocking when "/etc/resolv.conf"
  124. // has actually changed.
  125. lastReloadTime := monotime.Time(atomic.LoadInt64(&dns.lastReloadTime))
  126. stale := monotime.Now().After(lastReloadTime.Add(DNS_SYSTEM_CONFIG_RELOAD_PERIOD))
  127. if stale {
  128. isReloader := atomic.CompareAndSwapInt32(&dns.isReloading, 0, 1)
  129. if isReloader {
  130. // Unconditionally set last reload time. Even on failure only
  131. // want to retry after another DNS_SYSTEM_CONFIG_RELOAD_PERIOD.
  132. atomic.StoreInt64(&dns.lastReloadTime, time.Now().Unix())
  133. _, err := dns.Reload()
  134. if err != nil {
  135. log.WithContextFields(
  136. LogFields{"err": err}).Info(
  137. "failed to reload system DNS resolver")
  138. }
  139. atomic.StoreInt32(&dns.isReloading, 0)
  140. }
  141. }
  142. }
  143. // GetAllIPv4 returns a list of all IPv4 DNS resolver addresses.
  144. // Cached values are updated if they're stale. If reloading fails,
  145. // the previous values are used.
  146. func (dns *DNSResolver) GetAllIPv4() []net.IP {
  147. return dns.getAll(false)
  148. }
  149. // GetAllIPv6 returns a list of all IPv6 DNS resolver addresses.
  150. // Cached values are updated if they're stale. If reloading fails,
  151. // the previous values are used.
  152. func (dns *DNSResolver) GetAllIPv6() []net.IP {
  153. return dns.getAll(true)
  154. }
  155. func (dns *DNSResolver) getAll(wantIPv6 bool) []net.IP {
  156. dns.reloadWhenStale()
  157. dns.ReloadableFile.RLock()
  158. defer dns.ReloadableFile.RUnlock()
  159. resolvers := make([]net.IP, 0)
  160. for _, resolver := range dns.resolvers {
  161. if (resolver.To4() == nil) == wantIPv6 {
  162. resolvers = append(resolvers, resolver)
  163. }
  164. }
  165. return resolvers
  166. }
  167. func parseResolveConf(fileContent []byte) ([]net.IP, error) {
  168. scanner := bufio.NewScanner(bytes.NewReader(fileContent))
  169. var resolvers []net.IP
  170. for scanner.Scan() {
  171. line := scanner.Text()
  172. if strings.HasPrefix(line, ";") || strings.HasPrefix(line, "#") {
  173. continue
  174. }
  175. fields := strings.Fields(line)
  176. if len(fields) == 2 && fields[0] == "nameserver" {
  177. resolver, err := parseResolver(fields[1])
  178. if err == nil {
  179. resolvers = append(resolvers, resolver)
  180. }
  181. }
  182. }
  183. if err := scanner.Err(); err != nil {
  184. return nil, common.ContextError(err)
  185. }
  186. if len(resolvers) == 0 {
  187. return nil, common.ContextError(errors.New("no nameservers found"))
  188. }
  189. return resolvers, nil
  190. }
  191. func parseResolver(resolver string) (net.IP, error) {
  192. ipAddress := net.ParseIP(resolver)
  193. if ipAddress == nil {
  194. return nil, common.ContextError(errors.New("invalid IP address"))
  195. }
  196. return ipAddress, nil
  197. }