client.go 14 KB

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