dohdns.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. package dns
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "github.com/xtls/xray-core/common"
  14. "github.com/xtls/xray-core/common/log"
  15. "github.com/xtls/xray-core/common/net"
  16. "github.com/xtls/xray-core/common/net/cnc"
  17. "github.com/xtls/xray-core/common/protocol/dns"
  18. "github.com/xtls/xray-core/common/session"
  19. "github.com/xtls/xray-core/common/signal/pubsub"
  20. "github.com/xtls/xray-core/common/task"
  21. dns_feature "github.com/xtls/xray-core/features/dns"
  22. "github.com/xtls/xray-core/features/routing"
  23. "github.com/xtls/xray-core/transport/internet"
  24. "golang.org/x/net/dns/dnsmessage"
  25. )
  26. // DoHNameServer implemented DNS over HTTPS (RFC8484) Wire Format,
  27. // which is compatible with traditional dns over udp(RFC1035),
  28. // thus most of the DOH implementation is copied from udpns.go
  29. type DoHNameServer struct {
  30. dispatcher routing.Dispatcher
  31. sync.RWMutex
  32. ips map[string]record
  33. pub *pubsub.Service
  34. cleanup *task.Periodic
  35. reqID uint32
  36. clientIP net.IP
  37. httpClient *http.Client
  38. dohURL string
  39. name string
  40. }
  41. // NewDoHNameServer creates DOH client object for remote resolving
  42. func NewDoHNameServer(url *url.URL, dispatcher routing.Dispatcher, clientIP net.IP) (*DoHNameServer, error) {
  43. newError("DNS: created Remote DOH client for ", url.String()).AtInfo().WriteToLog()
  44. s := baseDOHNameServer(url, "DOH", clientIP)
  45. s.dispatcher = dispatcher
  46. tr := &http.Transport{
  47. MaxIdleConns: 30,
  48. IdleConnTimeout: 90 * time.Second,
  49. TLSHandshakeTimeout: 30 * time.Second,
  50. ForceAttemptHTTP2: true,
  51. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  52. dispatcherCtx := context.Background()
  53. if inbound := session.InboundFromContext(ctx); inbound != nil {
  54. dispatcherCtx = session.ContextWithInbound(dispatcherCtx, inbound)
  55. }
  56. if content := session.ContentFromContext(ctx); content != nil {
  57. dispatcherCtx = session.ContextWithContent(dispatcherCtx, content)
  58. }
  59. dispatcherCtx = internet.ContextWithLookupDomain(dispatcherCtx, internet.LookupDomainFromContext(ctx))
  60. dest, err := net.ParseDestination(network + ":" + addr)
  61. if err != nil {
  62. return nil, err
  63. }
  64. dispatcherCtx = log.ContextWithAccessMessage(dispatcherCtx, &log.AccessMessage{
  65. From: "DoH",
  66. To: s.dohURL,
  67. Status: log.AccessAccepted,
  68. Reason: "",
  69. })
  70. link, err := s.dispatcher.Dispatch(dispatcherCtx, dest)
  71. if err != nil {
  72. return nil, err
  73. }
  74. cc := common.ChainedClosable{}
  75. if cw, ok := link.Writer.(common.Closable); ok {
  76. cc = append(cc, cw)
  77. }
  78. if cr, ok := link.Reader.(common.Closable); ok {
  79. cc = append(cc, cr)
  80. }
  81. return cnc.NewConnection(
  82. cnc.ConnectionInputMulti(link.Writer),
  83. cnc.ConnectionOutputMulti(link.Reader),
  84. cnc.ConnectionOnClose(cc),
  85. ), nil
  86. },
  87. }
  88. s.httpClient = &http.Client{
  89. Timeout: time.Second * 180,
  90. Transport: tr,
  91. }
  92. return s, nil
  93. }
  94. // NewDoHLocalNameServer creates DOH client object for local resolving
  95. func NewDoHLocalNameServer(url *url.URL, clientIP net.IP) *DoHNameServer {
  96. url.Scheme = "https"
  97. s := baseDOHNameServer(url, "DOHL", clientIP)
  98. tr := &http.Transport{
  99. IdleConnTimeout: 90 * time.Second,
  100. ForceAttemptHTTP2: true,
  101. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  102. dest, err := net.ParseDestination(network + ":" + addr)
  103. if err != nil {
  104. return nil, err
  105. }
  106. conn, err := internet.DialSystem(ctx, dest, nil)
  107. log.Record(&log.AccessMessage{
  108. From: "DoH",
  109. To: s.dohURL,
  110. Status: log.AccessAccepted,
  111. Detour: "local",
  112. })
  113. if err != nil {
  114. return nil, err
  115. }
  116. return conn, nil
  117. },
  118. }
  119. s.httpClient = &http.Client{
  120. Timeout: time.Second * 180,
  121. Transport: tr,
  122. }
  123. newError("DNS: created Local DOH client for ", url.String()).AtInfo().WriteToLog()
  124. return s
  125. }
  126. func baseDOHNameServer(url *url.URL, prefix string, clientIP net.IP) *DoHNameServer {
  127. s := &DoHNameServer{
  128. ips: make(map[string]record),
  129. clientIP: clientIP,
  130. pub: pubsub.NewService(),
  131. name: prefix + "//" + url.Host,
  132. dohURL: url.String(),
  133. }
  134. s.cleanup = &task.Periodic{
  135. Interval: time.Minute,
  136. Execute: s.Cleanup,
  137. }
  138. return s
  139. }
  140. // Name returns client name
  141. func (s *DoHNameServer) Name() string {
  142. return s.name
  143. }
  144. // Cleanup clears expired items from cache
  145. func (s *DoHNameServer) Cleanup() error {
  146. now := time.Now()
  147. s.Lock()
  148. defer s.Unlock()
  149. if len(s.ips) == 0 {
  150. return newError("nothing to do. stopping...")
  151. }
  152. for domain, record := range s.ips {
  153. if record.A != nil && record.A.Expire.Before(now) {
  154. record.A = nil
  155. }
  156. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  157. record.AAAA = nil
  158. }
  159. if record.A == nil && record.AAAA == nil {
  160. newError(s.name, " cleanup ", domain).AtDebug().WriteToLog()
  161. delete(s.ips, domain)
  162. } else {
  163. s.ips[domain] = record
  164. }
  165. }
  166. if len(s.ips) == 0 {
  167. s.ips = make(map[string]record)
  168. }
  169. return nil
  170. }
  171. func (s *DoHNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  172. elapsed := time.Since(req.start)
  173. s.Lock()
  174. rec := s.ips[req.domain]
  175. updated := false
  176. switch req.reqType {
  177. case dnsmessage.TypeA:
  178. if isNewer(rec.A, ipRec) {
  179. rec.A = ipRec
  180. updated = true
  181. }
  182. case dnsmessage.TypeAAAA:
  183. addr := make([]net.Address, 0)
  184. for _, ip := range ipRec.IP {
  185. if len(ip.IP()) == net.IPv6len {
  186. addr = append(addr, ip)
  187. }
  188. }
  189. ipRec.IP = addr
  190. if isNewer(rec.AAAA, ipRec) {
  191. rec.AAAA = ipRec
  192. updated = true
  193. }
  194. }
  195. newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  196. if updated {
  197. s.ips[req.domain] = rec
  198. }
  199. switch req.reqType {
  200. case dnsmessage.TypeA:
  201. s.pub.Publish(req.domain+"4", nil)
  202. case dnsmessage.TypeAAAA:
  203. s.pub.Publish(req.domain+"6", nil)
  204. }
  205. s.Unlock()
  206. common.Must(s.cleanup.Start())
  207. }
  208. func (s *DoHNameServer) newReqID() uint16 {
  209. return uint16(atomic.AddUint32(&s.reqID, 1))
  210. }
  211. func (s *DoHNameServer) sendQuery(ctx context.Context, domain string, option dns_feature.IPOption) {
  212. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  213. if s.name+"." == "DOH//"+domain {
  214. newError(s.name, " tries to resolve itself! Use IP or set \"hosts\" instead.").AtError().WriteToLog(session.ExportIDToError(ctx))
  215. return
  216. }
  217. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(s.clientIP))
  218. var deadline time.Time
  219. if d, ok := ctx.Deadline(); ok {
  220. deadline = d
  221. } else {
  222. deadline = time.Now().Add(time.Second * 5)
  223. }
  224. for _, req := range reqs {
  225. go func(r *dnsRequest) {
  226. // generate new context for each req, using same context
  227. // may cause reqs all aborted if any one encounter an error
  228. dnsCtx := context.Background()
  229. // reserve internal dns server requested Inbound
  230. if inbound := session.InboundFromContext(ctx); inbound != nil {
  231. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  232. }
  233. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  234. Protocol: "https",
  235. //SkipRoutePick: true,
  236. })
  237. // forced to use mux for DOH
  238. // dnsCtx = session.ContextWithMuxPrefered(dnsCtx, true)
  239. var cancel context.CancelFunc
  240. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  241. defer cancel()
  242. b, err := dns.PackMessage(r.msg)
  243. if err != nil {
  244. newError("failed to pack dns query for ", domain).Base(err).AtError().WriteToLog()
  245. return
  246. }
  247. resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes())
  248. if err != nil {
  249. newError("failed to retrieve response for ", domain).Base(err).AtError().WriteToLog()
  250. return
  251. }
  252. rec, err := parseResponse(resp)
  253. if err != nil {
  254. newError("failed to handle DOH response for ", domain).Base(err).AtError().WriteToLog()
  255. return
  256. }
  257. s.updateIP(r, rec)
  258. }(req)
  259. }
  260. }
  261. func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte, error) {
  262. body := bytes.NewBuffer(b)
  263. req, err := http.NewRequest("POST", s.dohURL, body)
  264. if err != nil {
  265. return nil, err
  266. }
  267. req.Header.Add("Accept", "application/dns-message")
  268. req.Header.Add("Content-Type", "application/dns-message")
  269. hc := s.httpClient
  270. resp, err := hc.Do(req.WithContext(ctx))
  271. if err != nil {
  272. return nil, err
  273. }
  274. defer resp.Body.Close()
  275. if resp.StatusCode != http.StatusOK {
  276. io.Copy(ioutil.Discard, resp.Body) // flush resp.Body so that the conn is reusable
  277. return nil, fmt.Errorf("DOH server returned code %d", resp.StatusCode)
  278. }
  279. return ioutil.ReadAll(resp.Body)
  280. }
  281. func (s *DoHNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
  282. s.RLock()
  283. record, found := s.ips[domain]
  284. s.RUnlock()
  285. if !found {
  286. return nil, errRecordNotFound
  287. }
  288. var ips []net.Address
  289. var lastErr error
  290. if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
  291. aaaa, err := record.AAAA.getIPs()
  292. if err != nil {
  293. lastErr = err
  294. }
  295. ips = append(ips, aaaa...)
  296. }
  297. if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
  298. a, err := record.A.getIPs()
  299. if err != nil {
  300. lastErr = err
  301. }
  302. ips = append(ips, a...)
  303. }
  304. if len(ips) > 0 {
  305. return toNetIP(ips), nil
  306. }
  307. if lastErr != nil {
  308. return nil, lastErr
  309. }
  310. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  311. return nil, dns_feature.ErrEmptyResponse
  312. }
  313. return nil, errRecordNotFound
  314. }
  315. // QueryIP is called from dns.Server->queryIPTimeout
  316. func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, option dns_feature.IPOption) ([]net.IP, error) { // nolint: dupl
  317. fqdn := Fqdn(domain)
  318. ips, err := s.findIPsForDomain(fqdn, option)
  319. if err != errRecordNotFound {
  320. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  321. log.Record(&log.DNSLog{s.name, domain, ips, log.DNSCacheHit, 0, err})
  322. return ips, err
  323. }
  324. // ipv4 and ipv6 belong to different subscription groups
  325. var sub4, sub6 *pubsub.Subscriber
  326. if option.IPv4Enable {
  327. sub4 = s.pub.Subscribe(fqdn + "4")
  328. defer sub4.Close()
  329. }
  330. if option.IPv6Enable {
  331. sub6 = s.pub.Subscribe(fqdn + "6")
  332. defer sub6.Close()
  333. }
  334. done := make(chan interface{})
  335. go func() {
  336. if sub4 != nil {
  337. select {
  338. case <-sub4.Wait():
  339. case <-ctx.Done():
  340. }
  341. }
  342. if sub6 != nil {
  343. select {
  344. case <-sub6.Wait():
  345. case <-ctx.Done():
  346. }
  347. }
  348. close(done)
  349. }()
  350. s.sendQuery(ctx, fqdn, option)
  351. start := time.Now()
  352. for {
  353. ips, err := s.findIPsForDomain(fqdn, option)
  354. if err != errRecordNotFound {
  355. log.Record(&log.DNSLog{s.name, domain, ips, log.DNSQueried, time.Since(start), err})
  356. return ips, err
  357. }
  358. select {
  359. case <-ctx.Done():
  360. return nil, ctx.Err()
  361. case <-done:
  362. }
  363. }
  364. }