dohdns.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. "v2ray.com/core/common"
  16. "v2ray.com/core/common/net"
  17. "v2ray.com/core/common/protocol/dns"
  18. "v2ray.com/core/common/session"
  19. "v2ray.com/core/common/signal/pubsub"
  20. "v2ray.com/core/common/task"
  21. dns_feature "v2ray.com/core/features/dns"
  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. newError("DNS: Remote DOH client ", url.String(), " use clientip ", clientIP.String()).AtInfo().WriteToLog()
  43. s := baseDOHNameServer(url, "DOH", clientIP)
  44. // Dispatched connection will be closed (interrupted) after each request
  45. // This makes DOH inefficient without a keep-alived connection
  46. // See: core/app/proxyman/outbound/handler.go:113
  47. // Using mux (https request wrapped in a stream layer) improves the situation.
  48. // Recommend to use NewDoHLocalNameServer (DOHL:) if v2ray instance is running on
  49. // a normal network eg. the server side of v2ray
  50. tr := &http.Transport{
  51. MaxIdleConns: 30,
  52. IdleConnTimeout: 90 * time.Second,
  53. TLSHandshakeTimeout: 30 * time.Second,
  54. ForceAttemptHTTP2: true,
  55. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  56. dest, err := net.ParseDestination(network + ":" + addr)
  57. if err != nil {
  58. return nil, err
  59. }
  60. link, err := dispatcher.Dispatch(ctx, dest)
  61. if err != nil {
  62. return nil, err
  63. }
  64. return net.NewConnection(
  65. net.ConnectionInputMulti(link.Writer),
  66. net.ConnectionOutputMulti(link.Reader),
  67. ), nil
  68. },
  69. }
  70. dispatchedClient := &http.Client{
  71. Transport: tr,
  72. Timeout: 60 * time.Second,
  73. }
  74. s.httpClient = dispatchedClient
  75. return s, nil
  76. }
  77. // NewDoHLocalNameServer creates DOH client object for local resolving
  78. func NewDoHLocalNameServer(url *url.URL, clientIP net.IP) *DoHNameServer {
  79. url.Scheme = "https"
  80. s := baseDOHNameServer(url, "DOHL", clientIP)
  81. tr := &http.Transport{
  82. IdleConnTimeout: 90 * time.Second,
  83. ForceAttemptHTTP2: true,
  84. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  85. dest, err := net.ParseDestination(network + ":" + addr)
  86. if err != nil {
  87. return nil, err
  88. }
  89. conn, err := internet.DialSystem(ctx, dest, nil)
  90. if err != nil {
  91. return nil, err
  92. }
  93. return conn, nil
  94. },
  95. }
  96. s.httpClient = &http.Client{
  97. Timeout: time.Second * 180,
  98. Transport: tr,
  99. }
  100. newError("DNS: created Local DOH client for ", url.String()).AtInfo().WriteToLog()
  101. newError("DNS: Local DOH client ", url.String(), " use clientip ", clientIP.String()).AtInfo().WriteToLog()
  102. return s
  103. }
  104. func baseDOHNameServer(url *url.URL, prefix string, clientIP net.IP) *DoHNameServer {
  105. s := &DoHNameServer{
  106. ips: make(map[string]record),
  107. clientIP: clientIP,
  108. pub: pubsub.NewService(),
  109. name: prefix + "//" + url.Host,
  110. dohURL: url.String(),
  111. }
  112. s.cleanup = &task.Periodic{
  113. Interval: time.Minute,
  114. Execute: s.Cleanup,
  115. }
  116. return s
  117. }
  118. // Name returns client name
  119. func (s *DoHNameServer) Name() string {
  120. return s.name
  121. }
  122. // Cleanup clears expired items from cache
  123. func (s *DoHNameServer) Cleanup() error {
  124. now := time.Now()
  125. s.Lock()
  126. defer s.Unlock()
  127. if len(s.ips) == 0 {
  128. return newError("nothing to do. stopping...")
  129. }
  130. for domain, record := range s.ips {
  131. if record.A != nil && record.A.Expire.Before(now) {
  132. record.A = nil
  133. }
  134. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  135. record.AAAA = nil
  136. }
  137. if record.A == nil && record.AAAA == nil {
  138. newError(s.name, " cleanup ", domain).AtDebug().WriteToLog()
  139. delete(s.ips, domain)
  140. } else {
  141. s.ips[domain] = record
  142. }
  143. }
  144. if len(s.ips) == 0 {
  145. s.ips = make(map[string]record)
  146. }
  147. return nil
  148. }
  149. func (s *DoHNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  150. elapsed := time.Since(req.start)
  151. s.Lock()
  152. rec := s.ips[req.domain]
  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)
  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, option IPOption) {
  190. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  191. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(s.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 := context.Background()
  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. SkipRoutePick: 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 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 ips []net.Address
  262. var lastErr error
  263. if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
  264. aaaa, err := record.AAAA.getIPs()
  265. if err != nil {
  266. lastErr = err
  267. }
  268. ips = append(ips, aaaa...)
  269. }
  270. if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
  271. a, err := record.A.getIPs()
  272. if err != nil {
  273. lastErr = err
  274. }
  275. ips = append(ips, a...)
  276. }
  277. if len(ips) > 0 {
  278. return toNetIP(ips), nil
  279. }
  280. if lastErr != nil {
  281. return nil, lastErr
  282. }
  283. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  284. return nil, dns_feature.ErrEmptyResponse
  285. }
  286. return nil, errRecordNotFound
  287. }
  288. // QueryIP is called from dns.Server->queryIPTimeout
  289. func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
  290. fqdn := Fqdn(domain)
  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. // 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, 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. }