dohdns.go 8.8 KB

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