client.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. package dns
  2. // A client implementation.
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "encoding/binary"
  7. "fmt"
  8. "io"
  9. "net"
  10. "strings"
  11. "time"
  12. )
  13. const (
  14. dnsTimeout time.Duration = 2 * time.Second
  15. tcpIdleTimeout time.Duration = 8 * time.Second
  16. )
  17. // A Conn represents a connection to a DNS server.
  18. type Conn struct {
  19. net.Conn // a net.Conn holding the connection
  20. UDPSize uint16 // minimum receive buffer for UDP messages
  21. TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2)
  22. TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
  23. tsigRequestMAC string
  24. }
  25. // A Client defines parameters for a DNS client.
  26. type Client struct {
  27. Net string // if "tcp" or "tcp-tls" (DNS over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
  28. UDPSize uint16 // minimum receive buffer for UDP messages
  29. TLSConfig *tls.Config // TLS connection configuration
  30. Dialer *net.Dialer // a net.Dialer used to set local address, timeouts and more
  31. // Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout,
  32. // WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and
  33. // Client.Dialer) or context.Context.Deadline (see ExchangeContext)
  34. Timeout time.Duration
  35. DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds, or net.Dialer.Timeout if expiring earlier - overridden by Timeout when that value is non-zero
  36. ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
  37. WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
  38. TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2)
  39. TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
  40. SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass
  41. group singleflight
  42. }
  43. // Exchange performs a synchronous UDP query. It sends the message m to the address
  44. // contained in a and waits for a reply. Exchange does not retry a failed query, nor
  45. // will it fall back to TCP in case of truncation.
  46. // See client.Exchange for more information on setting larger buffer sizes.
  47. func Exchange(m *Msg, a string) (r *Msg, err error) {
  48. client := Client{Net: "udp"}
  49. r, _, err = client.Exchange(m, a)
  50. return r, err
  51. }
  52. func (c *Client) dialTimeout() time.Duration {
  53. if c.Timeout != 0 {
  54. return c.Timeout
  55. }
  56. if c.DialTimeout != 0 {
  57. return c.DialTimeout
  58. }
  59. return dnsTimeout
  60. }
  61. func (c *Client) readTimeout() time.Duration {
  62. if c.ReadTimeout != 0 {
  63. return c.ReadTimeout
  64. }
  65. return dnsTimeout
  66. }
  67. func (c *Client) writeTimeout() time.Duration {
  68. if c.WriteTimeout != 0 {
  69. return c.WriteTimeout
  70. }
  71. return dnsTimeout
  72. }
  73. // Dial connects to the address on the named network.
  74. func (c *Client) Dial(address string) (conn *Conn, err error) {
  75. return c.DialContext(context.Background(), address)
  76. }
  77. // DialContext connects to the address on the named network, with a context.Context.
  78. // For TLS over TCP (DoT) the context isn't used yet. This will be enabled when Go 1.18 is released.
  79. func (c *Client) DialContext(ctx context.Context, address string) (conn *Conn, err error) {
  80. // create a new dialer with the appropriate timeout
  81. var d net.Dialer
  82. if c.Dialer == nil {
  83. d = net.Dialer{Timeout: c.getTimeoutForRequest(c.dialTimeout())}
  84. } else {
  85. d = *c.Dialer
  86. }
  87. network := c.Net
  88. if network == "" {
  89. network = "udp"
  90. }
  91. useTLS := strings.HasPrefix(network, "tcp") && strings.HasSuffix(network, "-tls")
  92. conn = new(Conn)
  93. if useTLS {
  94. network = strings.TrimSuffix(network, "-tls")
  95. // TODO(miekg): Enable after Go 1.18 is released, to be able to support two prev. releases.
  96. /*
  97. tlsDialer := tls.Dialer{
  98. NetDialer: &d,
  99. Config: c.TLSConfig,
  100. }
  101. conn.Conn, err = tlsDialer.DialContext(ctx, network, address)
  102. */
  103. conn.Conn, err = tls.DialWithDialer(&d, network, address, c.TLSConfig)
  104. } else {
  105. conn.Conn, err = d.DialContext(ctx, network, address)
  106. }
  107. if err != nil {
  108. return nil, err
  109. }
  110. conn.UDPSize = c.UDPSize
  111. return conn, nil
  112. }
  113. // Exchange performs a synchronous query. It sends the message m to the address
  114. // contained in a and waits for a reply. Basic use pattern with a *dns.Client:
  115. //
  116. // c := new(dns.Client)
  117. // in, rtt, err := c.Exchange(message, "127.0.0.1:53")
  118. //
  119. // Exchange does not retry a failed query, nor will it fall back to TCP in
  120. // case of truncation.
  121. // It is up to the caller to create a message that allows for larger responses to be
  122. // returned. Specifically this means adding an EDNS0 OPT RR that will advertise a larger
  123. // buffer, see SetEdns0. Messages without an OPT RR will fallback to the historic limit
  124. // of 512 bytes
  125. // To specify a local address or a timeout, the caller has to set the `Client.Dialer`
  126. // attribute appropriately
  127. func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error) {
  128. co, err := c.Dial(address)
  129. if err != nil {
  130. return nil, 0, err
  131. }
  132. defer co.Close()
  133. return c.ExchangeWithConn(m, co)
  134. }
  135. // ExchangeWithConn has the same behavior as Exchange, just with a predetermined connection
  136. // that will be used instead of creating a new one.
  137. // Usage pattern with a *dns.Client:
  138. //
  139. // c := new(dns.Client)
  140. // // connection management logic goes here
  141. //
  142. // conn := c.Dial(address)
  143. // in, rtt, err := c.ExchangeWithConn(message, conn)
  144. //
  145. // This allows users of the library to implement their own connection management,
  146. // as opposed to Exchange, which will always use new connections and incur the added overhead
  147. // that entails when using "tcp" and especially "tcp-tls" clients.
  148. //
  149. // When the singleflight is set for this client the context is _not_ forwarded to the (shared) exchange, to
  150. // prevent one cancelation from canceling all outstanding requests.
  151. func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) {
  152. return c.exchangeWithConnContext(context.Background(), m, conn)
  153. }
  154. func (c *Client) exchangeWithConnContext(ctx context.Context, m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) {
  155. if !c.SingleInflight {
  156. return c.exchangeContext(ctx, m, conn)
  157. }
  158. q := m.Question[0]
  159. key := fmt.Sprintf("%s:%d:%d", q.Name, q.Qtype, q.Qclass)
  160. r, rtt, err, shared := c.group.Do(key, func() (*Msg, time.Duration, error) {
  161. // When we're doing singleflight we don't want one context cancelation, cancel _all_ outstanding queries.
  162. // Hence we ignore the context and use Background().
  163. return c.exchangeContext(context.Background(), m, conn)
  164. })
  165. if r != nil && shared {
  166. r = r.Copy()
  167. }
  168. return r, rtt, err
  169. }
  170. func (c *Client) exchangeContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) {
  171. opt := m.IsEdns0()
  172. // If EDNS0 is used use that for size.
  173. if opt != nil && opt.UDPSize() >= MinMsgSize {
  174. co.UDPSize = opt.UDPSize()
  175. }
  176. // Otherwise use the client's configured UDP size.
  177. if opt == nil && c.UDPSize >= MinMsgSize {
  178. co.UDPSize = c.UDPSize
  179. }
  180. // write with the appropriate write timeout
  181. t := time.Now()
  182. writeDeadline := t.Add(c.getTimeoutForRequest(c.writeTimeout()))
  183. readDeadline := t.Add(c.getTimeoutForRequest(c.readTimeout()))
  184. if deadline, ok := ctx.Deadline(); ok {
  185. if deadline.Before(writeDeadline) {
  186. writeDeadline = deadline
  187. }
  188. if deadline.Before(readDeadline) {
  189. readDeadline = deadline
  190. }
  191. }
  192. co.SetWriteDeadline(writeDeadline)
  193. co.SetReadDeadline(readDeadline)
  194. co.TsigSecret, co.TsigProvider = c.TsigSecret, c.TsigProvider
  195. if err = co.WriteMsg(m); err != nil {
  196. return nil, 0, err
  197. }
  198. if _, ok := co.Conn.(net.PacketConn); ok {
  199. for {
  200. r, err = co.ReadMsg()
  201. // Ignore replies with mismatched IDs because they might be
  202. // responses to earlier queries that timed out.
  203. if err != nil || r.Id == m.Id {
  204. break
  205. }
  206. }
  207. } else {
  208. r, err = co.ReadMsg()
  209. if err == nil && r.Id != m.Id {
  210. err = ErrId
  211. }
  212. }
  213. rtt = time.Since(t)
  214. return r, rtt, err
  215. }
  216. // ReadMsg reads a message from the connection co.
  217. // If the received message contains a TSIG record the transaction signature
  218. // is verified. This method always tries to return the message, however if an
  219. // error is returned there are no guarantees that the returned message is a
  220. // valid representation of the packet read.
  221. func (co *Conn) ReadMsg() (*Msg, error) {
  222. p, err := co.ReadMsgHeader(nil)
  223. if err != nil {
  224. return nil, err
  225. }
  226. m := new(Msg)
  227. if err := m.Unpack(p); err != nil {
  228. // If an error was returned, we still want to allow the user to use
  229. // the message, but naively they can just check err if they don't want
  230. // to use an erroneous message
  231. return m, err
  232. }
  233. if t := m.IsTsig(); t != nil {
  234. if co.TsigProvider != nil {
  235. err = tsigVerifyProvider(p, co.TsigProvider, co.tsigRequestMAC, false)
  236. } else {
  237. if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
  238. return m, ErrSecret
  239. }
  240. // Need to work on the original message p, as that was used to calculate the tsig.
  241. err = TsigVerify(p, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
  242. }
  243. }
  244. return m, err
  245. }
  246. // ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil).
  247. // Returns message as a byte slice to be parsed with Msg.Unpack later on.
  248. // Note that error handling on the message body is not possible as only the header is parsed.
  249. func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
  250. var (
  251. p []byte
  252. n int
  253. err error
  254. )
  255. if _, ok := co.Conn.(net.PacketConn); ok {
  256. if co.UDPSize > MinMsgSize {
  257. p = make([]byte, co.UDPSize)
  258. } else {
  259. p = make([]byte, MinMsgSize)
  260. }
  261. n, err = co.Read(p)
  262. } else {
  263. var length uint16
  264. if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
  265. return nil, err
  266. }
  267. p = make([]byte, length)
  268. n, err = io.ReadFull(co.Conn, p)
  269. }
  270. if err != nil {
  271. return nil, err
  272. } else if n < headerSize {
  273. return nil, ErrShortRead
  274. }
  275. p = p[:n]
  276. if hdr != nil {
  277. dh, _, err := unpackMsgHdr(p, 0)
  278. if err != nil {
  279. return nil, err
  280. }
  281. *hdr = dh
  282. }
  283. return p, err
  284. }
  285. // Read implements the net.Conn read method.
  286. func (co *Conn) Read(p []byte) (n int, err error) {
  287. if co.Conn == nil {
  288. return 0, ErrConnEmpty
  289. }
  290. if _, ok := co.Conn.(net.PacketConn); ok {
  291. // UDP connection
  292. return co.Conn.Read(p)
  293. }
  294. var length uint16
  295. if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
  296. return 0, err
  297. }
  298. if int(length) > len(p) {
  299. return 0, io.ErrShortBuffer
  300. }
  301. return io.ReadFull(co.Conn, p[:length])
  302. }
  303. // WriteMsg sends a message through the connection co.
  304. // If the message m contains a TSIG record the transaction
  305. // signature is calculated.
  306. func (co *Conn) WriteMsg(m *Msg) (err error) {
  307. var out []byte
  308. if t := m.IsTsig(); t != nil {
  309. mac := ""
  310. if co.TsigProvider != nil {
  311. out, mac, err = tsigGenerateProvider(m, co.TsigProvider, co.tsigRequestMAC, false)
  312. } else {
  313. if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
  314. return ErrSecret
  315. }
  316. out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
  317. }
  318. // Set for the next read, although only used in zone transfers
  319. co.tsigRequestMAC = mac
  320. } else {
  321. out, err = m.Pack()
  322. }
  323. if err != nil {
  324. return err
  325. }
  326. _, err = co.Write(out)
  327. return err
  328. }
  329. // Write implements the net.Conn Write method.
  330. func (co *Conn) Write(p []byte) (int, error) {
  331. if len(p) > MaxMsgSize {
  332. return 0, &Error{err: "message too large"}
  333. }
  334. if _, ok := co.Conn.(net.PacketConn); ok {
  335. return co.Conn.Write(p)
  336. }
  337. msg := make([]byte, 2+len(p))
  338. binary.BigEndian.PutUint16(msg, uint16(len(p)))
  339. copy(msg[2:], p)
  340. return co.Conn.Write(msg)
  341. }
  342. // Return the appropriate timeout for a specific request
  343. func (c *Client) getTimeoutForRequest(timeout time.Duration) time.Duration {
  344. var requestTimeout time.Duration
  345. if c.Timeout != 0 {
  346. requestTimeout = c.Timeout
  347. } else {
  348. requestTimeout = timeout
  349. }
  350. // net.Dialer.Timeout has priority if smaller than the timeouts computed so
  351. // far
  352. if c.Dialer != nil && c.Dialer.Timeout != 0 {
  353. if c.Dialer.Timeout < requestTimeout {
  354. requestTimeout = c.Dialer.Timeout
  355. }
  356. }
  357. return requestTimeout
  358. }
  359. // Dial connects to the address on the named network.
  360. func Dial(network, address string) (conn *Conn, err error) {
  361. conn = new(Conn)
  362. conn.Conn, err = net.Dial(network, address)
  363. if err != nil {
  364. return nil, err
  365. }
  366. return conn, nil
  367. }
  368. // ExchangeContext performs a synchronous UDP query, like Exchange. It
  369. // additionally obeys deadlines from the passed Context.
  370. func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error) {
  371. client := Client{Net: "udp"}
  372. r, _, err = client.ExchangeContext(ctx, m, a)
  373. // ignoring rtt to leave the original ExchangeContext API unchanged, but
  374. // this function will go away
  375. return r, err
  376. }
  377. // ExchangeConn performs a synchronous query. It sends the message m via the connection
  378. // c and waits for a reply. The connection c is not closed by ExchangeConn.
  379. // Deprecated: This function is going away, but can easily be mimicked:
  380. //
  381. // co := &dns.Conn{Conn: c} // c is your net.Conn
  382. // co.WriteMsg(m)
  383. // in, _ := co.ReadMsg()
  384. // co.Close()
  385. //
  386. func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
  387. println("dns: ExchangeConn: this function is deprecated")
  388. co := new(Conn)
  389. co.Conn = c
  390. if err = co.WriteMsg(m); err != nil {
  391. return nil, err
  392. }
  393. r, err = co.ReadMsg()
  394. if err == nil && r.Id != m.Id {
  395. err = ErrId
  396. }
  397. return r, err
  398. }
  399. // DialTimeout acts like Dial but takes a timeout.
  400. func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) {
  401. client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}}
  402. return client.Dial(address)
  403. }
  404. // DialWithTLS connects to the address on the named network with TLS.
  405. func DialWithTLS(network, address string, tlsConfig *tls.Config) (conn *Conn, err error) {
  406. if !strings.HasSuffix(network, "-tls") {
  407. network += "-tls"
  408. }
  409. client := Client{Net: network, TLSConfig: tlsConfig}
  410. return client.Dial(address)
  411. }
  412. // DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.
  413. func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error) {
  414. if !strings.HasSuffix(network, "-tls") {
  415. network += "-tls"
  416. }
  417. client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}, TLSConfig: tlsConfig}
  418. return client.Dial(address)
  419. }
  420. // ExchangeContext acts like Exchange, but honors the deadline on the provided
  421. // context, if present. If there is both a context deadline and a configured
  422. // timeout on the client, the earliest of the two takes effect.
  423. func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
  424. conn, err := c.DialContext(ctx, a)
  425. if err != nil {
  426. return nil, 0, err
  427. }
  428. defer conn.Close()
  429. return c.exchangeWithConnContext(ctx, m, conn)
  430. }