dohdns.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // +build !confonly
  2. package dns
  3. import (
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "golang.org/x/net/dns/dnsmessage"
  14. "v2ray.com/core/common"
  15. "v2ray.com/core/common/dice"
  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. "v2ray.com/core/features/routing"
  22. )
  23. // DoHNameServer implimented DNS over HTTPS (RFC8484) Wire Format,
  24. // which is compatiable with traditional dns over udp(RFC1035),
  25. // thus most of the DOH implimentation is copied from udpns.go
  26. type DoHNameServer struct {
  27. sync.RWMutex
  28. dispatcher routing.Dispatcher
  29. dohDests []net.Destination
  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. dohAddr := net.ParseAddress(url.Hostname())
  42. dohPort := "443"
  43. if url.Port() != "" {
  44. dohPort = url.Port()
  45. }
  46. parseIPDest := func(ip net.IP, port string) net.Destination {
  47. strIP := ip.String()
  48. if len(ip) == net.IPv6len {
  49. strIP = fmt.Sprintf("[%s]", strIP)
  50. }
  51. dest, err := net.ParseDestination(fmt.Sprintf("tcp:%s:%s", strIP, port))
  52. common.Must(err)
  53. return dest
  54. }
  55. var dests []net.Destination
  56. if dohAddr.Family().IsDomain() {
  57. // resolve DOH server in advance
  58. ips, err := net.LookupIP(dohAddr.Domain())
  59. if err != nil || len(ips) == 0 {
  60. return nil, err
  61. }
  62. for _, ip := range ips {
  63. dests = append(dests, parseIPDest(ip, dohPort))
  64. }
  65. } else {
  66. ip := dohAddr.IP()
  67. dests = append(dests, parseIPDest(ip, dohPort))
  68. }
  69. newError("DNS: created Remote DOH client for ", url.String(), ", preresolved Dests: ", dests).AtInfo().WriteToLog()
  70. s := baseDOHNameServer(url, "DOH", clientIP)
  71. s.dispatcher = dispatcher
  72. s.dohDests = dests
  73. // Dispatched connection will be closed (interupted) after each request
  74. // This makes DOH inefficient without a keeped-alive connection
  75. // See: core/app/proxyman/outbound/handler.go:113
  76. // Using mux (https request wrapped in a stream layer) improves the situation.
  77. // Recommand to use NewDoHLocalNameServer (DOHL:) if v2ray instance is running on
  78. // a normal network eg. the server side of v2ray
  79. tr := &http.Transport{
  80. MaxIdleConns: 10,
  81. IdleConnTimeout: 90 * time.Second,
  82. TLSHandshakeTimeout: 10 * time.Second,
  83. DialContext: s.DialContext,
  84. }
  85. dispatchedClient := &http.Client{
  86. Transport: tr,
  87. Timeout: 16 * time.Second,
  88. }
  89. s.httpClient = dispatchedClient
  90. return s, nil
  91. }
  92. // NewDoHLocalNameServer creates DOH client object for local resolving
  93. func NewDoHLocalNameServer(url *url.URL, clientIP net.IP) *DoHNameServer {
  94. url.Scheme = "https"
  95. s := baseDOHNameServer(url, "DOHL", clientIP)
  96. s.httpClient = &http.Client{
  97. Timeout: time.Second * 180,
  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: fmt.Sprintf("%s//%s", 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. // DialContext offer dispatched connection through core routing
  121. func (s *DoHNameServer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
  122. dest := s.dohDests[dice.Roll(len(s.dohDests))]
  123. link, err := s.dispatcher.Dispatch(ctx, dest)
  124. if err != nil {
  125. return nil, err
  126. }
  127. return net.NewConnection(
  128. net.ConnectionInputMulti(link.Writer),
  129. net.ConnectionOutputMulti(link.Reader),
  130. ), nil
  131. }
  132. // Cleanup clears expired items from cache
  133. func (s *DoHNameServer) Cleanup() error {
  134. now := time.Now()
  135. s.Lock()
  136. defer s.Unlock()
  137. if len(s.ips) == 0 {
  138. return newError("nothing to do. stopping...")
  139. }
  140. for domain, record := range s.ips {
  141. if record.A != nil && record.A.Expire.Before(now) {
  142. record.A = nil
  143. }
  144. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  145. record.AAAA = nil
  146. }
  147. if record.A == nil && record.AAAA == nil {
  148. newError(s.name, " cleanup ", domain).AtDebug().WriteToLog()
  149. delete(s.ips, domain)
  150. } else {
  151. s.ips[domain] = record
  152. }
  153. }
  154. if len(s.ips) == 0 {
  155. s.ips = make(map[string]record)
  156. }
  157. return nil
  158. }
  159. func (s *DoHNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  160. elapsed := time.Since(req.start)
  161. newError(s.name, " got answere: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  162. s.Lock()
  163. rec := s.ips[req.domain]
  164. updated := false
  165. switch req.reqType {
  166. case dnsmessage.TypeA:
  167. if isNewer(rec.A, ipRec) {
  168. rec.A = ipRec
  169. updated = true
  170. }
  171. case dnsmessage.TypeAAAA:
  172. if isNewer(rec.AAAA, ipRec) {
  173. rec.AAAA = ipRec
  174. updated = true
  175. }
  176. }
  177. if updated {
  178. s.ips[req.domain] = rec
  179. s.pub.Publish(req.domain, 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. })
  208. // forced to use mux for DOH
  209. dnsCtx = session.ContextWithMuxPrefered(dnsCtx, true)
  210. dnsCtx, cancel := context.WithDeadline(dnsCtx, deadline)
  211. defer cancel()
  212. b, _ := dns.PackMessage(r.msg)
  213. resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes())
  214. if err != nil {
  215. newError("failed to retrive response").Base(err).AtError().WriteToLog()
  216. return
  217. }
  218. rec, err := parseResponse(resp)
  219. if err != nil {
  220. newError("failed to handle DOH response").Base(err).AtError().WriteToLog()
  221. return
  222. }
  223. s.updateIP(r, rec)
  224. }(req)
  225. }
  226. }
  227. func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte, error) {
  228. body := bytes.NewBuffer(b)
  229. req, err := http.NewRequest("POST", s.dohURL, body)
  230. if err != nil {
  231. return nil, err
  232. }
  233. req.Header.Add("Accept", "application/dns-message")
  234. req.Header.Add("Content-Type", "application/dns-message")
  235. resp, err := s.httpClient.Do(req.WithContext(ctx))
  236. if err != nil {
  237. return nil, err
  238. }
  239. defer resp.Body.Close()
  240. if resp.StatusCode != http.StatusOK {
  241. err = fmt.Errorf("DOH HTTPS server returned with non-OK code %d", resp.StatusCode)
  242. return nil, err
  243. }
  244. return ioutil.ReadAll(resp.Body)
  245. }
  246. func (s *DoHNameServer) findIPsForDomain(domain string, option IPOption) ([]net.IP, error) {
  247. s.RLock()
  248. record, found := s.ips[domain]
  249. s.RUnlock()
  250. if !found {
  251. return nil, errRecordNotFound
  252. }
  253. var ips []net.Address
  254. var lastErr error
  255. if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
  256. aaaa, err := record.AAAA.getIPs()
  257. if err != nil {
  258. lastErr = err
  259. }
  260. ips = append(ips, aaaa...)
  261. }
  262. if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
  263. a, err := record.A.getIPs()
  264. if err != nil {
  265. lastErr = err
  266. }
  267. ips = append(ips, a...)
  268. }
  269. if len(ips) > 0 {
  270. return toNetIP(ips), nil
  271. }
  272. if lastErr != nil {
  273. return nil, lastErr
  274. }
  275. return nil, errRecordNotFound
  276. }
  277. // QueryIP is called from dns.Server->queryIPTimeout
  278. func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
  279. fqdn := Fqdn(domain)
  280. ips, err := s.findIPsForDomain(fqdn, option)
  281. if err != errRecordNotFound {
  282. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  283. return ips, err
  284. }
  285. sub := s.pub.Subscribe(fqdn)
  286. defer sub.Close()
  287. s.sendQuery(ctx, fqdn, option)
  288. for {
  289. ips, err := s.findIPsForDomain(fqdn, option)
  290. if err != errRecordNotFound {
  291. return ips, err
  292. }
  293. select {
  294. case <-ctx.Done():
  295. return nil, ctx.Err()
  296. case <-sub.Wait():
  297. }
  298. }
  299. }