dohdns.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. dns_feature "v2ray.com/core/features/dns"
  15. "golang.org/x/net/dns/dnsmessage"
  16. "v2ray.com/core/common"
  17. "v2ray.com/core/common/net"
  18. "v2ray.com/core/common/protocol/dns"
  19. "v2ray.com/core/common/session"
  20. "v2ray.com/core/common/signal/pubsub"
  21. "v2ray.com/core/common/task"
  22. "v2ray.com/core/features/routing"
  23. "v2ray.com/core/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. clientIP net.IP
  35. httpClient *http.Client
  36. dohURL string
  37. name string
  38. }
  39. // NewDoHNameServer creates DOH client object for remote resolving
  40. func NewDoHNameServer(url *url.URL, dispatcher routing.Dispatcher, clientIP net.IP) (*DoHNameServer, error) {
  41. newError("DNS: created Remote DOH client for ", url.String()).AtInfo().WriteToLog()
  42. s := baseDOHNameServer(url, "DOH", clientIP)
  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, clientIP net.IP) *DoHNameServer {
  78. url.Scheme = "https"
  79. s := baseDOHNameServer(url, "DOHL", clientIP)
  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, clientIP net.IP) *DoHNameServer {
  103. s := &DoHNameServer{
  104. ips: make(map[string]record),
  105. clientIP: clientIP,
  106. pub: pubsub.NewService(),
  107. name: prefix + "//" + url.Host,
  108. dohURL: url.String(),
  109. }
  110. s.cleanup = &task.Periodic{
  111. Interval: time.Minute,
  112. Execute: s.Cleanup,
  113. }
  114. return s
  115. }
  116. // Name returns client name
  117. func (s *DoHNameServer) Name() string {
  118. return s.name
  119. }
  120. // Cleanup clears expired items from cache
  121. func (s *DoHNameServer) Cleanup() error {
  122. now := time.Now()
  123. s.Lock()
  124. defer s.Unlock()
  125. if len(s.ips) == 0 {
  126. return newError("nothing to do. stopping...")
  127. }
  128. for domain, record := range s.ips {
  129. if record.A != nil && record.A.Expire.Before(now) {
  130. record.A = nil
  131. }
  132. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  133. record.AAAA = nil
  134. }
  135. if record.A == nil && record.AAAA == nil {
  136. newError(s.name, " cleanup ", domain).AtDebug().WriteToLog()
  137. delete(s.ips, domain)
  138. } else {
  139. s.ips[domain] = record
  140. }
  141. }
  142. if len(s.ips) == 0 {
  143. s.ips = make(map[string]record)
  144. }
  145. return nil
  146. }
  147. func (s *DoHNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  148. elapsed := time.Since(req.start)
  149. s.Lock()
  150. rec := s.ips[req.domain]
  151. updated := false
  152. switch req.reqType {
  153. case dnsmessage.TypeA:
  154. if isNewer(rec.A, ipRec) {
  155. rec.A = ipRec
  156. updated = true
  157. }
  158. case dnsmessage.TypeAAAA:
  159. addr := make([]net.Address, 0)
  160. for _, ip := range ipRec.IP {
  161. if len(ip.IP()) == net.IPv6len {
  162. addr = append(addr, ip)
  163. }
  164. }
  165. ipRec.IP = addr
  166. if isNewer(rec.AAAA, ipRec) {
  167. rec.AAAA = ipRec
  168. updated = true
  169. }
  170. }
  171. newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  172. if updated {
  173. s.ips[req.domain] = rec
  174. }
  175. switch req.reqType {
  176. case dnsmessage.TypeA:
  177. s.pub.Publish(req.domain+"4", nil)
  178. case dnsmessage.TypeAAAA:
  179. s.pub.Publish(req.domain+"6", nil)
  180. }
  181. s.Unlock()
  182. common.Must(s.cleanup.Start())
  183. }
  184. func (s *DoHNameServer) newReqID() uint16 {
  185. return uint16(atomic.AddUint32(&s.reqID, 1))
  186. }
  187. func (s *DoHNameServer) sendQuery(ctx context.Context, domain string, option IPOption) {
  188. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  189. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(s.clientIP))
  190. var deadline time.Time
  191. if d, ok := ctx.Deadline(); ok {
  192. deadline = d
  193. } else {
  194. deadline = time.Now().Add(time.Second * 8)
  195. }
  196. for _, req := range reqs {
  197. go func(r *dnsRequest) {
  198. // generate new context for each req, using same context
  199. // may cause reqs all aborted if any one encounter an error
  200. dnsCtx := context.Background()
  201. // reserve internal dns server requested Inbound
  202. if inbound := session.InboundFromContext(ctx); inbound != nil {
  203. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  204. }
  205. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  206. Protocol: "https",
  207. SkipRoutePick: true,
  208. })
  209. // forced to use mux for DOH
  210. dnsCtx = session.ContextWithMuxPrefered(dnsCtx, true)
  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 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), nil
  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 is called from dns.Server->queryIPTimeout
  286. func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
  287. fqdn := Fqdn(domain)
  288. ips, err := s.findIPsForDomain(fqdn, option)
  289. if err != errRecordNotFound {
  290. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  291. return ips, err
  292. }
  293. // ipv4 and ipv6 belong to different subscription groups
  294. var sub4, sub6 *pubsub.Subscriber
  295. if option.IPv4Enable {
  296. sub4 = s.pub.Subscribe(fqdn + "4")
  297. defer sub4.Close()
  298. }
  299. if option.IPv6Enable {
  300. sub6 = s.pub.Subscribe(fqdn + "6")
  301. defer sub6.Close()
  302. }
  303. done := make(chan interface{})
  304. go func() {
  305. if sub4 != nil {
  306. select {
  307. case <-sub4.Wait():
  308. case <-ctx.Done():
  309. }
  310. }
  311. if sub6 != nil {
  312. select {
  313. case <-sub6.Wait():
  314. case <-ctx.Done():
  315. }
  316. }
  317. close(done)
  318. }()
  319. s.sendQuery(ctx, fqdn, option)
  320. for {
  321. ips, err := s.findIPsForDomain(fqdn, option)
  322. if err != errRecordNotFound {
  323. return ips, err
  324. }
  325. select {
  326. case <-ctx.Done():
  327. return nil, ctx.Err()
  328. case <-done:
  329. }
  330. }
  331. }