dns.go 5.4 KB

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