dns.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. "math/rand"
  24. "net"
  25. "strings"
  26. "sync/atomic"
  27. "time"
  28. "github.com/Psiphon-Labs/goarista/monotime"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  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. true,
  74. func(fileContent []byte, _ time.Time) error {
  75. resolvers, err := parseResolveConf(fileContent)
  76. if err != nil {
  77. // On error, state remains the same
  78. return errors.Trace(err)
  79. }
  80. dns.resolvers = resolvers
  81. log.WithTraceFields(
  82. LogFields{
  83. "resolvers": resolvers,
  84. }).Debug("loaded system DNS resolvers")
  85. return nil
  86. })
  87. _, err := dns.Reload()
  88. if err != nil {
  89. if defaultResolver == "" {
  90. return nil, errors.Trace(err)
  91. }
  92. log.WithTraceFields(
  93. LogFields{"err": err}).Info(
  94. "failed to load system DNS resolver; using default")
  95. resolver, err := parseResolver(defaultResolver)
  96. if err != nil {
  97. return nil, errors.Trace(err)
  98. }
  99. dns.resolvers = []net.IP{resolver}
  100. }
  101. return dns, nil
  102. }
  103. // Get returns one of the cached resolvers, selected at random,
  104. // after first updating the cached values if they're stale. If
  105. // reloading fails, the previous values are used.
  106. //
  107. // Randomly selecting any one of the configured resolvers is
  108. // expected to be more resiliant to failure; e.g., if one of
  109. // the resolvers becomes unavailable.
  110. func (dns *DNSResolver) Get() net.IP {
  111. dns.reloadWhenStale()
  112. dns.ReloadableFile.RLock()
  113. defer dns.ReloadableFile.RUnlock()
  114. return dns.resolvers[rand.Intn(len(dns.resolvers))]
  115. }
  116. func (dns *DNSResolver) reloadWhenStale() {
  117. // Every UDP DNS port forward frequently calls Get(), so this code
  118. // is intended to minimize blocking. Most callers will hit just the
  119. // atomic.LoadInt64 reload time check and the RLock (an atomic.AddInt32
  120. // when no write lock is pending). An atomic.CompareAndSwapInt32 is
  121. // used to ensure only one goroutine enters Reload() and blocks on
  122. // its write lock. Finally, since since ReloadableFile.Reload
  123. // checks whether the underlying file has changed _before_ acquiring a
  124. // write lock, we only incur write lock blocking when "/etc/resolv.conf"
  125. // has actually changed.
  126. lastReloadTime := monotime.Time(atomic.LoadInt64(&dns.lastReloadTime))
  127. stale := monotime.Now().After(lastReloadTime.Add(DNS_SYSTEM_CONFIG_RELOAD_PERIOD))
  128. if stale {
  129. isReloader := atomic.CompareAndSwapInt32(&dns.isReloading, 0, 1)
  130. if isReloader {
  131. // Unconditionally set last reload time. Even on failure only
  132. // want to retry after another DNS_SYSTEM_CONFIG_RELOAD_PERIOD.
  133. atomic.StoreInt64(&dns.lastReloadTime, int64(monotime.Now()))
  134. _, err := dns.Reload()
  135. if err != nil {
  136. log.WithTraceFields(
  137. LogFields{"err": err}).Info(
  138. "failed to reload system DNS resolver")
  139. }
  140. atomic.StoreInt32(&dns.isReloading, 0)
  141. }
  142. }
  143. }
  144. // GetAllIPv4 returns a list of all IPv4 DNS resolver addresses.
  145. // Cached values are updated if they're stale. If reloading fails,
  146. // the previous values are used.
  147. func (dns *DNSResolver) GetAllIPv4() []net.IP {
  148. return dns.getAll(false)
  149. }
  150. // GetAllIPv6 returns a list of all IPv6 DNS resolver addresses.
  151. // Cached values are updated if they're stale. If reloading fails,
  152. // the previous values are used.
  153. func (dns *DNSResolver) GetAllIPv6() []net.IP {
  154. return dns.getAll(true)
  155. }
  156. func (dns *DNSResolver) getAll(wantIPv6 bool) []net.IP {
  157. dns.reloadWhenStale()
  158. dns.ReloadableFile.RLock()
  159. defer dns.ReloadableFile.RUnlock()
  160. resolvers := make([]net.IP, 0)
  161. for _, resolver := range dns.resolvers {
  162. if (resolver.To4() == nil) == wantIPv6 {
  163. resolvers = append(resolvers, resolver)
  164. }
  165. }
  166. return resolvers
  167. }
  168. func parseResolveConf(fileContent []byte) ([]net.IP, error) {
  169. scanner := bufio.NewScanner(bytes.NewReader(fileContent))
  170. var resolvers []net.IP
  171. for scanner.Scan() {
  172. line := scanner.Text()
  173. if strings.HasPrefix(line, ";") || strings.HasPrefix(line, "#") {
  174. continue
  175. }
  176. fields := strings.Fields(line)
  177. if len(fields) == 2 && fields[0] == "nameserver" {
  178. resolver, err := parseResolver(fields[1])
  179. if err == nil {
  180. resolvers = append(resolvers, resolver)
  181. }
  182. }
  183. }
  184. if err := scanner.Err(); err != nil {
  185. return nil, errors.Trace(err)
  186. }
  187. if len(resolvers) == 0 {
  188. return nil, errors.TraceNew("no nameservers found")
  189. }
  190. return resolvers, nil
  191. }
  192. func parseResolver(resolver string) (net.IP, error) {
  193. ipAddress := net.ParseIP(resolver)
  194. if ipAddress == nil {
  195. return nil, errors.TraceNew("invalid IP address")
  196. }
  197. return ipAddress, nil
  198. }