dohdns.go 9.5 KB

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