dohdns.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 implimented DNS over HTTPS (RFC8484) Wire Format,
  26. // which is compatiable with traditional dns over udp(RFC1035),
  27. // thus most of the DOH implimentation 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 (interupted) after each request
  44. // This makes DOH inefficient without a keeped-alive connection
  45. // See: core/app/proxyman/outbound/handler.go:113
  46. // Using mux (https request wrapped in a stream layer) improves the situation.
  47. // Recommand 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. 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, clientIP net.IP) *DoHNameServer {
  77. url.Scheme = "https"
  78. s := baseDOHNameServer(url, "DOHL", clientIP)
  79. tr := &http.Transport{
  80. IdleConnTimeout: 90 * time.Second,
  81. DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
  82. dest, err := net.ParseDestination(network + ":" + addr)
  83. if err != nil {
  84. return nil, err
  85. }
  86. conn, err := internet.DialSystem(ctx, dest, nil)
  87. if err != nil {
  88. return nil, err
  89. }
  90. return conn, nil
  91. },
  92. }
  93. s.httpClient = &http.Client{
  94. Timeout: time.Second * 180,
  95. Transport: tr,
  96. }
  97. newError("DNS: created Local DOH client for ", url.String()).AtInfo().WriteToLog()
  98. return s
  99. }
  100. func baseDOHNameServer(url *url.URL, prefix string, clientIP net.IP) *DoHNameServer {
  101. s := &DoHNameServer{
  102. ips: make(map[string]record),
  103. clientIP: clientIP,
  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 returns client name
  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 answere: ", 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, option IPOption) {
  186. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  187. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(s.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 * 8)
  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. SkipRoutePick: true,
  206. })
  207. // forced to use mux for DOH
  208. dnsCtx = session.ContextWithMuxPrefered(dnsCtx, true)
  209. dnsCtx, cancel := context.WithDeadline(dnsCtx, deadline)
  210. defer cancel()
  211. b, _ := dns.PackMessage(r.msg)
  212. resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes())
  213. if err != nil {
  214. newError("failed to retrive response").Base(err).AtError().WriteToLog()
  215. return
  216. }
  217. rec, err := parseResponse(resp)
  218. if err != nil {
  219. newError("failed to handle DOH response").Base(err).AtError().WriteToLog()
  220. return
  221. }
  222. s.updateIP(r, rec)
  223. }(req)
  224. }
  225. }
  226. func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte, error) {
  227. body := bytes.NewBuffer(b)
  228. req, err := http.NewRequest("POST", s.dohURL, body)
  229. if err != nil {
  230. return nil, err
  231. }
  232. req.Header.Add("Accept", "application/dns-message")
  233. req.Header.Add("Content-Type", "application/dns-message")
  234. resp, err := s.httpClient.Do(req.WithContext(ctx))
  235. if err != nil {
  236. return nil, err
  237. }
  238. defer resp.Body.Close()
  239. if resp.StatusCode != http.StatusOK {
  240. io.Copy(ioutil.Discard, resp.Body) // flush resp.Body so that the conn is reusable
  241. return nil, fmt.Errorf("DOH server returned code %d", resp.StatusCode)
  242. }
  243. return ioutil.ReadAll(resp.Body)
  244. }
  245. func (s *DoHNameServer) findIPsForDomain(domain string, option IPOption) ([]net.IP, error) {
  246. s.RLock()
  247. record, found := s.ips[domain]
  248. s.RUnlock()
  249. if !found {
  250. return nil, errRecordNotFound
  251. }
  252. var ips []net.Address
  253. var lastErr error
  254. if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
  255. aaaa, err := record.AAAA.getIPs()
  256. if err != nil {
  257. lastErr = err
  258. }
  259. ips = append(ips, aaaa...)
  260. }
  261. if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
  262. a, err := record.A.getIPs()
  263. if err != nil {
  264. lastErr = err
  265. }
  266. ips = append(ips, a...)
  267. }
  268. if len(ips) > 0 {
  269. return toNetIP(ips), nil
  270. }
  271. if lastErr != nil {
  272. return nil, lastErr
  273. }
  274. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  275. return nil, dns_feature.ErrEmptyResponse
  276. }
  277. return nil, errRecordNotFound
  278. }
  279. // QueryIP is called from dns.Server->queryIPTimeout
  280. func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
  281. fqdn := Fqdn(domain)
  282. ips, err := s.findIPsForDomain(fqdn, option)
  283. if err != errRecordNotFound {
  284. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  285. return ips, err
  286. }
  287. // ipv4 and ipv6 belong to different subscription groups
  288. var sub4, sub6 *pubsub.Subscriber
  289. if option.IPv4Enable {
  290. sub4 = s.pub.Subscribe(fqdn + "4")
  291. defer sub4.Close()
  292. }
  293. if option.IPv6Enable {
  294. sub6 = s.pub.Subscribe(fqdn + "6")
  295. defer sub6.Close()
  296. }
  297. done := make(chan interface{})
  298. go func() {
  299. if sub4 != nil {
  300. select {
  301. case <-sub4.Wait():
  302. case <-ctx.Done():
  303. }
  304. }
  305. if sub6 != nil {
  306. select {
  307. case <-sub6.Wait():
  308. case <-ctx.Done():
  309. }
  310. }
  311. close(done)
  312. }()
  313. s.sendQuery(ctx, fqdn, option)
  314. for {
  315. ips, err := s.findIPsForDomain(fqdn, option)
  316. if err != errRecordNotFound {
  317. return ips, err
  318. }
  319. select {
  320. case <-ctx.Done():
  321. return nil, ctx.Err()
  322. case <-done:
  323. }
  324. }
  325. }