nameserver_doh.go 9.2 KB

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