dohdns.go 9.5 KB

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