dohdns.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // +build !confonly
  2. package dns
  3. import (
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "golang.org/x/net/dns/dnsmessage"
  13. "v2ray.com/core/common"
  14. "v2ray.com/core/common/dice"
  15. "v2ray.com/core/common/net"
  16. "v2ray.com/core/common/protocol/dns"
  17. "v2ray.com/core/common/session"
  18. "v2ray.com/core/common/signal/pubsub"
  19. "v2ray.com/core/common/task"
  20. "v2ray.com/core/features/routing"
  21. )
  22. // DoHNameServer implimented DNS over HTTPS (RFC8484) Wire Format,
  23. // which is compatiable with traditional dns over udp(RFC1035),
  24. // thus most of the DOH implimentation is copied from udpns.go
  25. type DoHNameServer struct {
  26. sync.RWMutex
  27. dispatcher routing.Dispatcher
  28. dohDests []net.Destination
  29. ips map[string]record
  30. pub *pubsub.Service
  31. cleanup *task.Periodic
  32. reqID uint32
  33. clientIP net.IP
  34. httpClient *http.Client
  35. dohURL string
  36. name string
  37. }
  38. func NewDoHNameServer(dests []net.Destination, dohHost string, dispatcher routing.Dispatcher, clientIP net.IP) *DoHNameServer {
  39. s := NewDoHLocalNameServer(dohHost, clientIP)
  40. s.name = "DOH:" + dohHost
  41. s.dispatcher = dispatcher
  42. s.dohDests = dests
  43. // Dispatched connection will be closed (interupted) after each request
  44. // This makes DOH inefficient without a keeped-alive connection
  45. // See: core/app/proxyman/outbound/handler.go:113
  46. // Using mux (https request wrapped in a stream layer) improves the situation.
  47. // Recommand to use NewDoHLocalNameServer (DOHL:) if v2ray instance is running on
  48. // a normal network eg. the server side of v2ray
  49. tr := &http.Transport{
  50. MaxIdleConns: 10,
  51. IdleConnTimeout: 90 * time.Second,
  52. TLSHandshakeTimeout: 10 * time.Second,
  53. DialContext: s.DialContext,
  54. }
  55. dispatchedClient := &http.Client{
  56. Transport: tr,
  57. Timeout: 16 * time.Second,
  58. }
  59. s.httpClient = dispatchedClient
  60. return s
  61. }
  62. func NewDoHLocalNameServer(dohHost string, clientIP net.IP) *DoHNameServer {
  63. s := &DoHNameServer{
  64. httpClient: http.DefaultClient,
  65. ips: make(map[string]record),
  66. clientIP: clientIP,
  67. pub: pubsub.NewService(),
  68. name: "DOHL:" + dohHost,
  69. dohURL: fmt.Sprintf("https://%s/dns-query", dohHost),
  70. }
  71. s.cleanup = &task.Periodic{
  72. Interval: time.Minute,
  73. Execute: s.Cleanup,
  74. }
  75. return s
  76. }
  77. func (s *DoHNameServer) Name() string {
  78. return s.name
  79. }
  80. func (s *DoHNameServer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
  81. dest := s.dohDests[dice.Roll(len(s.dohDests))]
  82. link, err := s.dispatcher.Dispatch(ctx, dest)
  83. if err != nil {
  84. return nil, err
  85. }
  86. return net.NewConnection(
  87. net.ConnectionInputMulti(link.Writer),
  88. net.ConnectionOutputMulti(link.Reader),
  89. ), nil
  90. }
  91. func (s *DoHNameServer) Cleanup() error {
  92. now := time.Now()
  93. s.Lock()
  94. defer s.Unlock()
  95. if len(s.ips) == 0 {
  96. return newError("nothing to do. stopping...")
  97. }
  98. for domain, record := range s.ips {
  99. if record.A != nil && record.A.Expire.Before(now) {
  100. record.A = nil
  101. }
  102. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  103. record.AAAA = nil
  104. }
  105. if record.A == nil && record.AAAA == nil {
  106. newError(s.name, " cleanup ", domain).AtDebug().WriteToLog()
  107. delete(s.ips, domain)
  108. } else {
  109. s.ips[domain] = record
  110. }
  111. }
  112. if len(s.ips) == 0 {
  113. s.ips = make(map[string]record)
  114. }
  115. return nil
  116. }
  117. func (s *DoHNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  118. elapsed := time.Since(req.start)
  119. newError(s.name, " got answere: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  120. s.Lock()
  121. rec := s.ips[req.domain]
  122. updated := false
  123. switch req.reqType {
  124. case dnsmessage.TypeA:
  125. if isNewer(rec.A, ipRec) {
  126. rec.A = ipRec
  127. updated = true
  128. }
  129. case dnsmessage.TypeAAAA:
  130. if isNewer(rec.AAAA, ipRec) {
  131. rec.AAAA = ipRec
  132. updated = true
  133. }
  134. }
  135. if updated {
  136. s.ips[req.domain] = rec
  137. s.pub.Publish(req.domain, nil)
  138. }
  139. s.Unlock()
  140. common.Must(s.cleanup.Start())
  141. }
  142. func (s *DoHNameServer) newReqID() uint16 {
  143. return uint16(atomic.AddUint32(&s.reqID, 1))
  144. }
  145. func (s *DoHNameServer) sendQuery(ctx context.Context, domain string, option IPOption) {
  146. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  147. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(s.clientIP))
  148. var deadline time.Time
  149. if d, ok := ctx.Deadline(); ok {
  150. deadline = d
  151. } else {
  152. deadline = time.Now().Add(time.Second * 8)
  153. }
  154. for _, req := range reqs {
  155. go func(r *dnsRequest) {
  156. // generate new context for each req, using same context
  157. // may cause reqs all aborted if any one encounter an error
  158. dnsCtx := context.Background()
  159. // reserve internal dns server requested Inbound
  160. if inbound := session.InboundFromContext(ctx); inbound != nil {
  161. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  162. }
  163. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  164. Protocol: "https",
  165. })
  166. // forced to use mux for DOH
  167. dnsCtx = session.ContextWithMuxPrefered(dnsCtx, true)
  168. dnsCtx, cancel := context.WithDeadline(dnsCtx, deadline)
  169. defer cancel()
  170. b, _ := dns.PackMessage(r.msg)
  171. resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes())
  172. if err != nil {
  173. newError("failed to retrive response").Base(err).AtError().WriteToLog()
  174. return
  175. }
  176. rec, err := parseResponse(resp)
  177. if err != nil {
  178. newError("failed to handle DOH response").Base(err).AtError().WriteToLog()
  179. return
  180. }
  181. s.updateIP(r, rec)
  182. }(req)
  183. }
  184. }
  185. func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte, error) {
  186. body := bytes.NewBuffer(b)
  187. req, err := http.NewRequest("POST", s.dohURL, body)
  188. if err != nil {
  189. return nil, err
  190. }
  191. req.Header.Add("Accept", "application/dns-message")
  192. req.Header.Add("Content-Type", "application/dns-message")
  193. resp, err := s.httpClient.Do(req.WithContext(ctx))
  194. if err != nil {
  195. return nil, err
  196. }
  197. defer resp.Body.Close()
  198. if resp.StatusCode != http.StatusOK {
  199. err = fmt.Errorf("DOH HTTPS server returned with non-OK code %d", resp.StatusCode)
  200. return nil, err
  201. }
  202. return ioutil.ReadAll(resp.Body)
  203. }
  204. func (s *DoHNameServer) findIPsForDomain(domain string, option IPOption) ([]net.IP, error) {
  205. s.RLock()
  206. record, found := s.ips[domain]
  207. s.RUnlock()
  208. if !found {
  209. return nil, errRecordNotFound
  210. }
  211. var ips []net.Address
  212. var lastErr error
  213. if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
  214. aaaa, err := record.AAAA.getIPs()
  215. if err != nil {
  216. lastErr = err
  217. }
  218. ips = append(ips, aaaa...)
  219. }
  220. if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
  221. a, err := record.A.getIPs()
  222. if err != nil {
  223. lastErr = err
  224. }
  225. ips = append(ips, a...)
  226. }
  227. if len(ips) > 0 {
  228. return toNetIP(ips), nil
  229. }
  230. if lastErr != nil {
  231. return nil, lastErr
  232. }
  233. return nil, errRecordNotFound
  234. }
  235. // QueryIP is called from dns.Server->queryIPTimeout
  236. func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
  237. fqdn := Fqdn(domain)
  238. ips, err := s.findIPsForDomain(fqdn, option)
  239. if err != errRecordNotFound {
  240. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  241. return ips, err
  242. }
  243. sub := s.pub.Subscribe(fqdn)
  244. defer sub.Close()
  245. s.sendQuery(ctx, fqdn, option)
  246. for {
  247. ips, err := s.findIPsForDomain(fqdn, option)
  248. if err != errRecordNotFound {
  249. return ips, err
  250. }
  251. select {
  252. case <-ctx.Done():
  253. return nil, ctx.Err()
  254. case <-sub.Wait():
  255. }
  256. }
  257. }