dns.go 5.6 KB

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