dns.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. "errors"
  23. "net"
  24. "os"
  25. "strings"
  26. "sync/atomic"
  27. "time"
  28. "github.com/Psiphon-Inc/goarista/monotime"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. )
  31. const (
  32. DNS_SYSTEM_CONFIG_FILENAME = "/etc/resolv.conf"
  33. DNS_SYSTEM_CONFIG_RELOAD_PERIOD = 5 * time.Second
  34. DNS_RESOLVER_PORT = 53
  35. )
  36. // DNSResolver maintains a fresh DNS resolver value, monitoring
  37. // "/etc/resolv.conf" on platforms where it is available; and
  38. // otherwise using a default value.
  39. type DNSResolver struct {
  40. // Note: 64-bit ints used with atomic operations are at placed
  41. // at the start of struct to ensure 64-bit alignment.
  42. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  43. lastReloadTime int64
  44. common.ReloadableFile
  45. isReloading int32
  46. resolver net.IP
  47. }
  48. // NewDNSResolver initializes a new DNSResolver, loading it with
  49. // a fresh resolver value. The load must succeed, so either
  50. // "/etc/resolv.conf" must contain a valid "nameserver" line with
  51. // a DNS server IP address, or a valid "defaultResolver" default
  52. // value must be provided.
  53. // On systems without "/etc/resolv.conf", "defaultResolver" is
  54. // required.
  55. //
  56. // The resolver is considered stale and reloaded if last checked
  57. // more than 5 seconds before the last Get(), which is similar to
  58. // frequencies in other implementations:
  59. //
  60. // - https://golang.org/src/net/dnsclient_unix.go,
  61. // resolverConfig.tryUpdate: 5 seconds
  62. //
  63. // - https://github.com/ambrop72/badvpn/blob/master/udpgw/udpgw.c,
  64. // maybe_update_dns: 2 seconds
  65. //
  66. func NewDNSResolver(defaultResolver string) (*DNSResolver, error) {
  67. dns := &DNSResolver{
  68. lastReloadTime: int64(monotime.Now()),
  69. }
  70. dns.ReloadableFile = common.NewReloadableFile(
  71. DNS_SYSTEM_CONFIG_FILENAME,
  72. func(filename string) error {
  73. resolver, err := parseResolveConf(filename)
  74. if err != nil {
  75. // On error, state remains the same
  76. return common.ContextError(err)
  77. }
  78. dns.resolver = resolver
  79. log.WithContextFields(
  80. LogFields{
  81. "resolver": resolver.String(),
  82. }).Debug("loaded system DNS resolver")
  83. return nil
  84. })
  85. _, err := dns.Reload()
  86. if err != nil {
  87. if defaultResolver == "" {
  88. return nil, common.ContextError(err)
  89. }
  90. log.WithContextFields(
  91. LogFields{"err": err}).Info(
  92. "failed to load system DNS resolver; using default")
  93. resolver, err := parseResolver(defaultResolver)
  94. if err != nil {
  95. return nil, common.ContextError(err)
  96. }
  97. dns.resolver = resolver
  98. }
  99. return dns, nil
  100. }
  101. // Get returns the cached resolver, first updating the cached
  102. // value if it's stale. If reloading fails, the previous value
  103. // is used.
  104. func (dns *DNSResolver) Get() net.IP {
  105. // Every UDP DNS port forward frequently calls Get(), so this code
  106. // is intended to minimize blocking. Most callers will hit just the
  107. // atomic.LoadInt64 reload time check and the RLock (an atomic.AddInt32
  108. // when no write lock is pending). An atomic.CompareAndSwapInt32 is
  109. // used to ensure only one goroutine enters Reload() and blocks on
  110. // its write lock. Finally, since since ReloadableFile.Reload
  111. // checks whether the underlying file has changed _before_ aquiring a
  112. // write lock, we only incur write lock blocking when "/etc/resolv.conf"
  113. // has actually changed.
  114. lastReloadTime := monotime.Time(atomic.LoadInt64(&dns.lastReloadTime))
  115. stale := monotime.Now().After(lastReloadTime.Add(DNS_SYSTEM_CONFIG_RELOAD_PERIOD))
  116. if stale {
  117. isReloader := atomic.CompareAndSwapInt32(&dns.isReloading, 0, 1)
  118. if isReloader {
  119. // Unconditionally set last reload time. Even on failure only
  120. // want to retry after another DNS_SYSTEM_CONFIG_RELOAD_PERIOD.
  121. atomic.StoreInt64(&dns.lastReloadTime, time.Now().Unix())
  122. _, err := dns.Reload()
  123. if err != nil {
  124. log.WithContextFields(
  125. LogFields{"err": err}).Info(
  126. "failed to reload system DNS resolver")
  127. }
  128. atomic.StoreInt32(&dns.isReloading, 0)
  129. }
  130. }
  131. dns.ReloadableFile.RLock()
  132. defer dns.ReloadableFile.RUnlock()
  133. return dns.resolver
  134. }
  135. func parseResolveConf(filename string) (net.IP, error) {
  136. file, err := os.Open(filename)
  137. if err != nil {
  138. return nil, common.ContextError(err)
  139. }
  140. defer file.Close()
  141. scanner := bufio.NewScanner(file)
  142. for scanner.Scan() {
  143. line := scanner.Text()
  144. if strings.HasPrefix(line, ";") || strings.HasPrefix(line, "#") {
  145. continue
  146. }
  147. fields := strings.Fields(line)
  148. if len(fields) == 2 && fields[0] == "nameserver" {
  149. // TODO: parseResolverAddress will fail when the nameserver
  150. // is not an IP address. It may be a domain name. To support
  151. // this case, should proceed to the next "nameserver" line.
  152. return parseResolver(fields[1])
  153. }
  154. }
  155. if err := scanner.Err(); err != nil {
  156. return nil, common.ContextError(err)
  157. }
  158. return nil, common.ContextError(errors.New("nameserver not found"))
  159. }
  160. func parseResolver(resolver string) (net.IP, error) {
  161. ipAddress := net.ParseIP(resolver)
  162. if ipAddress == nil {
  163. return nil, common.ContextError(errors.New("invalid IP address"))
  164. }
  165. return ipAddress, nil
  166. }