nameserver_doh.go 9.4 KB

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