nameserver_doh.go 9.5 KB

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