dohdns.go 8.5 KB

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