client.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. func isPacketConn(c net.Conn) bool {
  18. if _, ok := c.(net.PacketConn); !ok {
  19. return false
  20. }
  21. if ua, ok := c.LocalAddr().(*net.UnixAddr); ok {
  22. return ua.Net == "unixgram" || ua.Net == "unixpacket"
  23. }
  24. return true
  25. }
  26. // A Conn represents a connection to a DNS server.
  27. type Conn struct {
  28. net.Conn // a net.Conn holding the connection
  29. UDPSize uint16 // minimum receive buffer for UDP messages
  30. 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)
  31. TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
  32. tsigRequestMAC string
  33. }
  34. func (co *Conn) tsigProvider() TsigProvider {
  35. if co.TsigProvider != nil {
  36. return co.TsigProvider
  37. }
  38. // tsigSecretProvider will return ErrSecret if co.TsigSecret is nil.
  39. return tsigSecretProvider(co.TsigSecret)
  40. }
  41. // A Client defines parameters for a DNS client.
  42. type Client struct {
  43. Net string // if "tcp" or "tcp-tls" (DNS over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
  44. UDPSize uint16 // minimum receive buffer for UDP messages
  45. TLSConfig *tls.Config // TLS connection configuration
  46. Dialer *net.Dialer // a net.Dialer used to set local address, timeouts and more
  47. // Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout,
  48. // WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and
  49. // Client.Dialer) or context.Context.Deadline (see ExchangeContext)
  50. Timeout time.Duration
  51. 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
  52. ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
  53. WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
  54. 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)
  55. TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
  56. SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass
  57. group singleflight
  58. }
  59. // Exchange performs a synchronous UDP query. It sends the message m to the address
  60. // contained in a and waits for a reply. Exchange does not retry a failed query, nor
  61. // will it fall back to TCP in case of truncation.
  62. // See client.Exchange for more information on setting larger buffer sizes.
  63. func Exchange(m *Msg, a string) (r *Msg, err error) {
  64. client := Client{Net: "udp"}
  65. r, _, err = client.Exchange(m, a)
  66. return r, err
  67. }
  68. func (c *Client) dialTimeout() time.Duration {
  69. if c.Timeout != 0 {
  70. return c.Timeout
  71. }
  72. if c.DialTimeout != 0 {
  73. return c.DialTimeout
  74. }
  75. return dnsTimeout
  76. }
  77. func (c *Client) readTimeout() time.Duration {
  78. if c.ReadTimeout != 0 {
  79. return c.ReadTimeout
  80. }
  81. return dnsTimeout
  82. }
  83. func (c *Client) writeTimeout() time.Duration {
  84. if c.WriteTimeout != 0 {
  85. return c.WriteTimeout
  86. }
  87. return dnsTimeout
  88. }
  89. // Dial connects to the address on the named network.
  90. func (c *Client) Dial(address string) (conn *Conn, err error) {
  91. return c.DialContext(context.Background(), address)
  92. }
  93. // DialContext connects to the address on the named network, with a context.Context.
  94. // For TLS over TCP (DoT) the context isn't used yet. This will be enabled when Go 1.18 is released.
  95. func (c *Client) DialContext(ctx context.Context, address string) (conn *Conn, err error) {
  96. // create a new dialer with the appropriate timeout
  97. var d net.Dialer
  98. if c.Dialer == nil {
  99. d = net.Dialer{Timeout: c.getTimeoutForRequest(c.dialTimeout())}
  100. } else {
  101. d = *c.Dialer
  102. }
  103. network := c.Net
  104. if network == "" {
  105. network = "udp"
  106. }
  107. useTLS := strings.HasPrefix(network, "tcp") && strings.HasSuffix(network, "-tls")
  108. conn = new(Conn)
  109. if useTLS {
  110. network = strings.TrimSuffix(network, "-tls")
  111. // TODO(miekg): Enable after Go 1.18 is released, to be able to support two prev. releases.
  112. /*
  113. tlsDialer := tls.Dialer{
  114. NetDialer: &d,
  115. Config: c.TLSConfig,
  116. }
  117. conn.Conn, err = tlsDialer.DialContext(ctx, network, address)
  118. */
  119. conn.Conn, err = tls.DialWithDialer(&d, network, address, c.TLSConfig)
  120. } else {
  121. conn.Conn, err = d.DialContext(ctx, network, address)
  122. }
  123. if err != nil {
  124. return nil, err
  125. }
  126. conn.UDPSize = c.UDPSize
  127. return conn, nil
  128. }
  129. // Exchange performs a synchronous query. It sends the message m to the address
  130. // contained in a and waits for a reply. Basic use pattern with a *dns.Client:
  131. //
  132. // c := new(dns.Client)
  133. // in, rtt, err := c.Exchange(message, "127.0.0.1:53")
  134. //
  135. // Exchange does not retry a failed query, nor will it fall back to TCP in
  136. // case of truncation.
  137. // It is up to the caller to create a message that allows for larger responses to be
  138. // returned. Specifically this means adding an EDNS0 OPT RR that will advertise a larger
  139. // buffer, see SetEdns0. Messages without an OPT RR will fallback to the historic limit
  140. // of 512 bytes
  141. // To specify a local address or a timeout, the caller has to set the `Client.Dialer`
  142. // attribute appropriately
  143. func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error) {
  144. co, err := c.Dial(address)
  145. if err != nil {
  146. return nil, 0, err
  147. }
  148. defer co.Close()
  149. return c.ExchangeWithConn(m, co)
  150. }
  151. // ExchangeWithConn has the same behavior as Exchange, just with a predetermined connection
  152. // that will be used instead of creating a new one.
  153. // Usage pattern with a *dns.Client:
  154. //
  155. // c := new(dns.Client)
  156. // // connection management logic goes here
  157. //
  158. // conn := c.Dial(address)
  159. // in, rtt, err := c.ExchangeWithConn(message, conn)
  160. //
  161. // This allows users of the library to implement their own connection management,
  162. // as opposed to Exchange, which will always use new connections and incur the added overhead
  163. // that entails when using "tcp" and especially "tcp-tls" clients.
  164. //
  165. // When the singleflight is set for this client the context is _not_ forwarded to the (shared) exchange, to
  166. // prevent one cancelation from canceling all outstanding requests.
  167. func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) {
  168. return c.exchangeWithConnContext(context.Background(), m, conn)
  169. }
  170. func (c *Client) exchangeWithConnContext(ctx context.Context, m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) {
  171. if !c.SingleInflight {
  172. return c.exchangeContext(ctx, m, conn)
  173. }
  174. q := m.Question[0]
  175. key := fmt.Sprintf("%s:%d:%d", q.Name, q.Qtype, q.Qclass)
  176. r, rtt, err, shared := c.group.Do(key, func() (*Msg, time.Duration, error) {
  177. // When we're doing singleflight we don't want one context cancelation, cancel _all_ outstanding queries.
  178. // Hence we ignore the context and use Background().
  179. return c.exchangeContext(context.Background(), m, conn)
  180. })
  181. if r != nil && shared {
  182. r = r.Copy()
  183. }
  184. return r, rtt, err
  185. }
  186. func (c *Client) exchangeContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) {
  187. opt := m.IsEdns0()
  188. // If EDNS0 is used use that for size.
  189. if opt != nil && opt.UDPSize() >= MinMsgSize {
  190. co.UDPSize = opt.UDPSize()
  191. }
  192. // Otherwise use the client's configured UDP size.
  193. if opt == nil && c.UDPSize >= MinMsgSize {
  194. co.UDPSize = c.UDPSize
  195. }
  196. // write with the appropriate write timeout
  197. t := time.Now()
  198. writeDeadline := t.Add(c.getTimeoutForRequest(c.writeTimeout()))
  199. readDeadline := t.Add(c.getTimeoutForRequest(c.readTimeout()))
  200. if deadline, ok := ctx.Deadline(); ok {
  201. if deadline.Before(writeDeadline) {
  202. writeDeadline = deadline
  203. }
  204. if deadline.Before(readDeadline) {
  205. readDeadline = deadline
  206. }
  207. }
  208. co.SetWriteDeadline(writeDeadline)
  209. co.SetReadDeadline(readDeadline)
  210. co.TsigSecret, co.TsigProvider = c.TsigSecret, c.TsigProvider
  211. if err = co.WriteMsg(m); err != nil {
  212. return nil, 0, err
  213. }
  214. if isPacketConn(co.Conn) {
  215. for {
  216. r, err = co.ReadMsg()
  217. // Ignore replies with mismatched IDs because they might be
  218. // responses to earlier queries that timed out.
  219. if err != nil || r.Id == m.Id {
  220. break
  221. }
  222. }
  223. } else {
  224. r, err = co.ReadMsg()
  225. if err == nil && r.Id != m.Id {
  226. err = ErrId
  227. }
  228. }
  229. rtt = time.Since(t)
  230. return r, rtt, err
  231. }
  232. // ReadMsg reads a message from the connection co.
  233. // If the received message contains a TSIG record the transaction signature
  234. // is verified. This method always tries to return the message, however if an
  235. // error is returned there are no guarantees that the returned message is a
  236. // valid representation of the packet read.
  237. func (co *Conn) ReadMsg() (*Msg, error) {
  238. p, err := co.ReadMsgHeader(nil)
  239. if err != nil {
  240. return nil, err
  241. }
  242. m := new(Msg)
  243. if err := m.Unpack(p); err != nil {
  244. // If an error was returned, we still want to allow the user to use
  245. // the message, but naively they can just check err if they don't want
  246. // to use an erroneous message
  247. return m, err
  248. }
  249. if t := m.IsTsig(); t != nil {
  250. // Need to work on the original message p, as that was used to calculate the tsig.
  251. err = TsigVerifyWithProvider(p, co.tsigProvider(), co.tsigRequestMAC, false)
  252. }
  253. return m, err
  254. }
  255. // ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil).
  256. // Returns message as a byte slice to be parsed with Msg.Unpack later on.
  257. // Note that error handling on the message body is not possible as only the header is parsed.
  258. func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
  259. var (
  260. p []byte
  261. n int
  262. err error
  263. )
  264. if isPacketConn(co.Conn) {
  265. if co.UDPSize > MinMsgSize {
  266. p = make([]byte, co.UDPSize)
  267. } else {
  268. p = make([]byte, MinMsgSize)
  269. }
  270. n, err = co.Read(p)
  271. } else {
  272. var length uint16
  273. if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
  274. return nil, err
  275. }
  276. p = make([]byte, length)
  277. n, err = io.ReadFull(co.Conn, p)
  278. }
  279. if err != nil {
  280. return nil, err
  281. } else if n < headerSize {
  282. return nil, ErrShortRead
  283. }
  284. p = p[:n]
  285. if hdr != nil {
  286. dh, _, err := unpackMsgHdr(p, 0)
  287. if err != nil {
  288. return nil, err
  289. }
  290. *hdr = dh
  291. }
  292. return p, err
  293. }
  294. // Read implements the net.Conn read method.
  295. func (co *Conn) Read(p []byte) (n int, err error) {
  296. if co.Conn == nil {
  297. return 0, ErrConnEmpty
  298. }
  299. if isPacketConn(co.Conn) {
  300. // UDP connection
  301. return co.Conn.Read(p)
  302. }
  303. var length uint16
  304. if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
  305. return 0, err
  306. }
  307. if int(length) > len(p) {
  308. return 0, io.ErrShortBuffer
  309. }
  310. return io.ReadFull(co.Conn, p[:length])
  311. }
  312. // WriteMsg sends a message through the connection co.
  313. // If the message m contains a TSIG record the transaction
  314. // signature is calculated.
  315. func (co *Conn) WriteMsg(m *Msg) (err error) {
  316. var out []byte
  317. if t := m.IsTsig(); t != nil {
  318. // Set tsigRequestMAC for the next read, although only used in zone transfers.
  319. out, co.tsigRequestMAC, err = TsigGenerateWithProvider(m, co.tsigProvider(), co.tsigRequestMAC, false)
  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 isPacketConn(co.Conn) {
  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. }