nameserver_doh.go 9.4 KB

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