nameserver_doh.go 9.5 KB

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