dns.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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-Inc/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 at 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. // Every UDP DNS port forward frequently calls Get(), so this code
  111. // is intended to minimize blocking. Most callers will hit just the
  112. // atomic.LoadInt64 reload time check and the RLock (an atomic.AddInt32
  113. // when no write lock is pending). An atomic.CompareAndSwapInt32 is
  114. // used to ensure only one goroutine enters Reload() and blocks on
  115. // its write lock. Finally, since since ReloadableFile.Reload
  116. // checks whether the underlying file has changed _before_ aquiring a
  117. // write lock, we only incur write lock blocking when "/etc/resolv.conf"
  118. // has actually changed.
  119. lastReloadTime := monotime.Time(atomic.LoadInt64(&dns.lastReloadTime))
  120. stale := monotime.Now().After(lastReloadTime.Add(DNS_SYSTEM_CONFIG_RELOAD_PERIOD))
  121. if stale {
  122. isReloader := atomic.CompareAndSwapInt32(&dns.isReloading, 0, 1)
  123. if isReloader {
  124. // Unconditionally set last reload time. Even on failure only
  125. // want to retry after another DNS_SYSTEM_CONFIG_RELOAD_PERIOD.
  126. atomic.StoreInt64(&dns.lastReloadTime, time.Now().Unix())
  127. _, err := dns.Reload()
  128. if err != nil {
  129. log.WithContextFields(
  130. LogFields{"err": err}).Info(
  131. "failed to reload system DNS resolver")
  132. }
  133. atomic.StoreInt32(&dns.isReloading, 0)
  134. }
  135. }
  136. dns.ReloadableFile.RLock()
  137. defer dns.ReloadableFile.RUnlock()
  138. return dns.resolvers[rand.Intn(len(dns.resolvers))]
  139. }
  140. func parseResolveConf(fileContent []byte) ([]net.IP, error) {
  141. scanner := bufio.NewScanner(bytes.NewReader(fileContent))
  142. var resolvers []net.IP
  143. for scanner.Scan() {
  144. line := scanner.Text()
  145. if strings.HasPrefix(line, ";") || strings.HasPrefix(line, "#") {
  146. continue
  147. }
  148. fields := strings.Fields(line)
  149. if len(fields) == 2 && fields[0] == "nameserver" {
  150. resolver, err := parseResolver(fields[1])
  151. if err == nil {
  152. resolvers = append(resolvers, resolver)
  153. }
  154. }
  155. }
  156. if err := scanner.Err(); err != nil {
  157. return nil, common.ContextError(err)
  158. }
  159. if len(resolvers) == 0 {
  160. return nil, common.ContextError(errors.New("no nameservers found"))
  161. }
  162. return resolvers, nil
  163. }
  164. func parseResolver(resolver string) (net.IP, error) {
  165. ipAddress := net.ParseIP(resolver)
  166. if ipAddress == nil {
  167. return nil, common.ContextError(errors.New("invalid IP address"))
  168. }
  169. return ipAddress, nil
  170. }