nameserver_doh.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. // +build !confonly
  2. package dns
  3. import (
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  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 := s.ips[req.domain]
  149. updated := false
  150. switch req.reqType {
  151. case dnsmessage.TypeA:
  152. if isNewer(rec.A, ipRec) {
  153. rec.A = ipRec
  154. updated = true
  155. }
  156. case dnsmessage.TypeAAAA:
  157. addr := make([]net.Address, 0)
  158. for _, ip := range ipRec.IP {
  159. if len(ip.IP()) == net.IPv6len {
  160. addr = append(addr, ip)
  161. }
  162. }
  163. ipRec.IP = addr
  164. if isNewer(rec.AAAA, ipRec) {
  165. rec.AAAA = ipRec
  166. updated = true
  167. }
  168. }
  169. newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  170. if updated {
  171. s.ips[req.domain] = rec
  172. }
  173. switch req.reqType {
  174. case dnsmessage.TypeA:
  175. s.pub.Publish(req.domain+"4", nil)
  176. case dnsmessage.TypeAAAA:
  177. s.pub.Publish(req.domain+"6", nil)
  178. }
  179. s.Unlock()
  180. common.Must(s.cleanup.Start())
  181. }
  182. func (s *DoHNameServer) newReqID() uint16 {
  183. return uint16(atomic.AddUint32(&s.reqID, 1))
  184. }
  185. func (s *DoHNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
  186. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  187. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
  188. var deadline time.Time
  189. if d, ok := ctx.Deadline(); ok {
  190. deadline = d
  191. } else {
  192. deadline = time.Now().Add(time.Second * 5)
  193. }
  194. for _, req := range reqs {
  195. go func(r *dnsRequest) {
  196. // generate new context for each req, using same context
  197. // may cause reqs all aborted if any one encounter an error
  198. dnsCtx := context.Background()
  199. // reserve internal dns server requested Inbound
  200. if inbound := session.InboundFromContext(ctx); inbound != nil {
  201. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  202. }
  203. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  204. Protocol: "https",
  205. SkipDNSResolve: true,
  206. })
  207. // forced to use mux for DOH
  208. dnsCtx = session.ContextWithMuxPrefered(dnsCtx, true)
  209. var cancel context.CancelFunc
  210. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  211. defer cancel()
  212. b, err := dns.PackMessage(r.msg)
  213. if err != nil {
  214. newError("failed to pack dns query").Base(err).AtError().WriteToLog()
  215. return
  216. }
  217. resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes())
  218. if err != nil {
  219. newError("failed to retrieve response").Base(err).AtError().WriteToLog()
  220. return
  221. }
  222. rec, err := parseResponse(resp)
  223. if err != nil {
  224. newError("failed to handle DOH response").Base(err).AtError().WriteToLog()
  225. return
  226. }
  227. s.updateIP(r, rec)
  228. }(req)
  229. }
  230. }
  231. func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte, error) {
  232. body := bytes.NewBuffer(b)
  233. req, err := http.NewRequest("POST", s.dohURL, body)
  234. if err != nil {
  235. return nil, err
  236. }
  237. req.Header.Add("Accept", "application/dns-message")
  238. req.Header.Add("Content-Type", "application/dns-message")
  239. resp, err := s.httpClient.Do(req.WithContext(ctx))
  240. if err != nil {
  241. return nil, err
  242. }
  243. defer resp.Body.Close()
  244. if resp.StatusCode != http.StatusOK {
  245. io.Copy(ioutil.Discard, resp.Body) // flush resp.Body so that the conn is reusable
  246. return nil, fmt.Errorf("DOH server returned code %d", resp.StatusCode)
  247. }
  248. return ioutil.ReadAll(resp.Body)
  249. }
  250. func (s *DoHNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
  251. s.RLock()
  252. record, found := s.ips[domain]
  253. s.RUnlock()
  254. if !found {
  255. return nil, errRecordNotFound
  256. }
  257. var ips []net.Address
  258. var lastErr error
  259. if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
  260. aaaa, err := record.AAAA.getIPs()
  261. if err != nil {
  262. lastErr = err
  263. }
  264. ips = append(ips, aaaa...)
  265. }
  266. if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
  267. a, err := record.A.getIPs()
  268. if err != nil {
  269. lastErr = err
  270. }
  271. ips = append(ips, a...)
  272. }
  273. if len(ips) > 0 {
  274. return toNetIP(ips)
  275. }
  276. if lastErr != nil {
  277. return nil, lastErr
  278. }
  279. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  280. return nil, dns_feature.ErrEmptyResponse
  281. }
  282. return nil, errRecordNotFound
  283. }
  284. // QueryIP implements Server.
  285. func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { // nolint: dupl
  286. fqdn := Fqdn(domain)
  287. if disableCache {
  288. newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog()
  289. } else {
  290. ips, err := s.findIPsForDomain(fqdn, option)
  291. if err != errRecordNotFound {
  292. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  293. return ips, err
  294. }
  295. }
  296. // ipv4 and ipv6 belong to different subscription groups
  297. var sub4, sub6 *pubsub.Subscriber
  298. if option.IPv4Enable {
  299. sub4 = s.pub.Subscribe(fqdn + "4")
  300. defer sub4.Close()
  301. }
  302. if option.IPv6Enable {
  303. sub6 = s.pub.Subscribe(fqdn + "6")
  304. defer sub6.Close()
  305. }
  306. done := make(chan interface{})
  307. go func() {
  308. if sub4 != nil {
  309. select {
  310. case <-sub4.Wait():
  311. case <-ctx.Done():
  312. }
  313. }
  314. if sub6 != nil {
  315. select {
  316. case <-sub6.Wait():
  317. case <-ctx.Done():
  318. }
  319. }
  320. close(done)
  321. }()
  322. s.sendQuery(ctx, fqdn, clientIP, option)
  323. for {
  324. ips, err := s.findIPsForDomain(fqdn, option)
  325. if err != errRecordNotFound {
  326. return ips, err
  327. }
  328. select {
  329. case <-ctx.Done():
  330. return nil, ctx.Err()
  331. case <-done:
  332. }
  333. }
  334. }