client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. // create a new dialer with the appropriate timeout
  76. var d net.Dialer
  77. if c.Dialer == nil {
  78. d = net.Dialer{Timeout: c.getTimeoutForRequest(c.dialTimeout())}
  79. } else {
  80. d = *c.Dialer
  81. }
  82. network := c.Net
  83. if network == "" {
  84. network = "udp"
  85. }
  86. useTLS := strings.HasPrefix(network, "tcp") && strings.HasSuffix(network, "-tls")
  87. conn = new(Conn)
  88. if useTLS {
  89. network = strings.TrimSuffix(network, "-tls")
  90. conn.Conn, err = tls.DialWithDialer(&d, network, address, c.TLSConfig)
  91. } else {
  92. conn.Conn, err = d.Dial(network, address)
  93. }
  94. if err != nil {
  95. return nil, err
  96. }
  97. conn.UDPSize = c.UDPSize
  98. return conn, nil
  99. }
  100. // Exchange performs a synchronous query. It sends the message m to the address
  101. // contained in a and waits for a reply. Basic use pattern with a *dns.Client:
  102. //
  103. // c := new(dns.Client)
  104. // in, rtt, err := c.Exchange(message, "127.0.0.1:53")
  105. //
  106. // Exchange does not retry a failed query, nor will it fall back to TCP in
  107. // case of truncation.
  108. // It is up to the caller to create a message that allows for larger responses to be
  109. // returned. Specifically this means adding an EDNS0 OPT RR that will advertise a larger
  110. // buffer, see SetEdns0. Messages without an OPT RR will fallback to the historic limit
  111. // of 512 bytes
  112. // To specify a local address or a timeout, the caller has to set the `Client.Dialer`
  113. // attribute appropriately
  114. func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error) {
  115. co, err := c.Dial(address)
  116. if err != nil {
  117. return nil, 0, err
  118. }
  119. defer co.Close()
  120. return c.ExchangeWithConn(m, co)
  121. }
  122. // ExchangeWithConn has the same behavior as Exchange, just with a predetermined connection
  123. // that will be used instead of creating a new one.
  124. // Usage pattern with a *dns.Client:
  125. // c := new(dns.Client)
  126. // // connection management logic goes here
  127. //
  128. // conn := c.Dial(address)
  129. // in, rtt, err := c.ExchangeWithConn(message, conn)
  130. //
  131. // This allows users of the library to implement their own connection management,
  132. // as opposed to Exchange, which will always use new connections and incur the added overhead
  133. // that entails when using "tcp" and especially "tcp-tls" clients.
  134. func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) {
  135. if !c.SingleInflight {
  136. return c.exchange(m, conn)
  137. }
  138. q := m.Question[0]
  139. key := fmt.Sprintf("%s:%d:%d", q.Name, q.Qtype, q.Qclass)
  140. r, rtt, err, shared := c.group.Do(key, func() (*Msg, time.Duration, error) {
  141. return c.exchange(m, conn)
  142. })
  143. if r != nil && shared {
  144. r = r.Copy()
  145. }
  146. return r, rtt, err
  147. }
  148. func (c *Client) exchange(m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) {
  149. opt := m.IsEdns0()
  150. // If EDNS0 is used use that for size.
  151. if opt != nil && opt.UDPSize() >= MinMsgSize {
  152. co.UDPSize = opt.UDPSize()
  153. }
  154. // Otherwise use the client's configured UDP size.
  155. if opt == nil && c.UDPSize >= MinMsgSize {
  156. co.UDPSize = c.UDPSize
  157. }
  158. co.TsigSecret, co.TsigProvider = c.TsigSecret, c.TsigProvider
  159. t := time.Now()
  160. // write with the appropriate write timeout
  161. co.SetWriteDeadline(t.Add(c.getTimeoutForRequest(c.writeTimeout())))
  162. if err = co.WriteMsg(m); err != nil {
  163. return nil, 0, err
  164. }
  165. co.SetReadDeadline(time.Now().Add(c.getTimeoutForRequest(c.readTimeout())))
  166. if _, ok := co.Conn.(net.PacketConn); ok {
  167. for {
  168. r, err = co.ReadMsg()
  169. // Ignore replies with mismatched IDs because they might be
  170. // responses to earlier queries that timed out.
  171. if err != nil || r.Id == m.Id {
  172. break
  173. }
  174. }
  175. } else {
  176. r, err = co.ReadMsg()
  177. if err == nil && r.Id != m.Id {
  178. err = ErrId
  179. }
  180. }
  181. rtt = time.Since(t)
  182. return r, rtt, err
  183. }
  184. // ReadMsg reads a message from the connection co.
  185. // If the received message contains a TSIG record the transaction signature
  186. // is verified. This method always tries to return the message, however if an
  187. // error is returned there are no guarantees that the returned message is a
  188. // valid representation of the packet read.
  189. func (co *Conn) ReadMsg() (*Msg, error) {
  190. p, err := co.ReadMsgHeader(nil)
  191. if err != nil {
  192. return nil, err
  193. }
  194. m := new(Msg)
  195. if err := m.Unpack(p); err != nil {
  196. // If an error was returned, we still want to allow the user to use
  197. // the message, but naively they can just check err if they don't want
  198. // to use an erroneous message
  199. return m, err
  200. }
  201. if t := m.IsTsig(); t != nil {
  202. if co.TsigProvider != nil {
  203. err = tsigVerifyProvider(p, co.TsigProvider, co.tsigRequestMAC, false)
  204. } else {
  205. if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
  206. return m, ErrSecret
  207. }
  208. // Need to work on the original message p, as that was used to calculate the tsig.
  209. err = TsigVerify(p, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
  210. }
  211. }
  212. return m, err
  213. }
  214. // ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil).
  215. // Returns message as a byte slice to be parsed with Msg.Unpack later on.
  216. // Note that error handling on the message body is not possible as only the header is parsed.
  217. func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
  218. var (
  219. p []byte
  220. n int
  221. err error
  222. )
  223. if _, ok := co.Conn.(net.PacketConn); ok {
  224. if co.UDPSize > MinMsgSize {
  225. p = make([]byte, co.UDPSize)
  226. } else {
  227. p = make([]byte, MinMsgSize)
  228. }
  229. n, err = co.Read(p)
  230. } else {
  231. var length uint16
  232. if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
  233. return nil, err
  234. }
  235. p = make([]byte, length)
  236. n, err = io.ReadFull(co.Conn, p)
  237. }
  238. if err != nil {
  239. return nil, err
  240. } else if n < headerSize {
  241. return nil, ErrShortRead
  242. }
  243. p = p[:n]
  244. if hdr != nil {
  245. dh, _, err := unpackMsgHdr(p, 0)
  246. if err != nil {
  247. return nil, err
  248. }
  249. *hdr = dh
  250. }
  251. return p, err
  252. }
  253. // Read implements the net.Conn read method.
  254. func (co *Conn) Read(p []byte) (n int, err error) {
  255. if co.Conn == nil {
  256. return 0, ErrConnEmpty
  257. }
  258. if _, ok := co.Conn.(net.PacketConn); ok {
  259. // UDP connection
  260. return co.Conn.Read(p)
  261. }
  262. var length uint16
  263. if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
  264. return 0, err
  265. }
  266. if int(length) > len(p) {
  267. return 0, io.ErrShortBuffer
  268. }
  269. return io.ReadFull(co.Conn, p[:length])
  270. }
  271. // WriteMsg sends a message through the connection co.
  272. // If the message m contains a TSIG record the transaction
  273. // signature is calculated.
  274. func (co *Conn) WriteMsg(m *Msg) (err error) {
  275. var out []byte
  276. if t := m.IsTsig(); t != nil {
  277. mac := ""
  278. if co.TsigProvider != nil {
  279. out, mac, err = tsigGenerateProvider(m, co.TsigProvider, co.tsigRequestMAC, false)
  280. } else {
  281. if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
  282. return ErrSecret
  283. }
  284. out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
  285. }
  286. // Set for the next read, although only used in zone transfers
  287. co.tsigRequestMAC = mac
  288. } else {
  289. out, err = m.Pack()
  290. }
  291. if err != nil {
  292. return err
  293. }
  294. _, err = co.Write(out)
  295. return err
  296. }
  297. // Write implements the net.Conn Write method.
  298. func (co *Conn) Write(p []byte) (int, error) {
  299. if len(p) > MaxMsgSize {
  300. return 0, &Error{err: "message too large"}
  301. }
  302. if _, ok := co.Conn.(net.PacketConn); ok {
  303. return co.Conn.Write(p)
  304. }
  305. msg := make([]byte, 2+len(p))
  306. binary.BigEndian.PutUint16(msg, uint16(len(p)))
  307. copy(msg[2:], p)
  308. return co.Conn.Write(msg)
  309. }
  310. // Return the appropriate timeout for a specific request
  311. func (c *Client) getTimeoutForRequest(timeout time.Duration) time.Duration {
  312. var requestTimeout time.Duration
  313. if c.Timeout != 0 {
  314. requestTimeout = c.Timeout
  315. } else {
  316. requestTimeout = timeout
  317. }
  318. // net.Dialer.Timeout has priority if smaller than the timeouts computed so
  319. // far
  320. if c.Dialer != nil && c.Dialer.Timeout != 0 {
  321. if c.Dialer.Timeout < requestTimeout {
  322. requestTimeout = c.Dialer.Timeout
  323. }
  324. }
  325. return requestTimeout
  326. }
  327. // Dial connects to the address on the named network.
  328. func Dial(network, address string) (conn *Conn, err error) {
  329. conn = new(Conn)
  330. conn.Conn, err = net.Dial(network, address)
  331. if err != nil {
  332. return nil, err
  333. }
  334. return conn, nil
  335. }
  336. // ExchangeContext performs a synchronous UDP query, like Exchange. It
  337. // additionally obeys deadlines from the passed Context.
  338. func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error) {
  339. client := Client{Net: "udp"}
  340. r, _, err = client.ExchangeContext(ctx, m, a)
  341. // ignoring rtt to leave the original ExchangeContext API unchanged, but
  342. // this function will go away
  343. return r, err
  344. }
  345. // ExchangeConn performs a synchronous query. It sends the message m via the connection
  346. // c and waits for a reply. The connection c is not closed by ExchangeConn.
  347. // Deprecated: This function is going away, but can easily be mimicked:
  348. //
  349. // co := &dns.Conn{Conn: c} // c is your net.Conn
  350. // co.WriteMsg(m)
  351. // in, _ := co.ReadMsg()
  352. // co.Close()
  353. //
  354. func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
  355. println("dns: ExchangeConn: this function is deprecated")
  356. co := new(Conn)
  357. co.Conn = c
  358. if err = co.WriteMsg(m); err != nil {
  359. return nil, err
  360. }
  361. r, err = co.ReadMsg()
  362. if err == nil && r.Id != m.Id {
  363. err = ErrId
  364. }
  365. return r, err
  366. }
  367. // DialTimeout acts like Dial but takes a timeout.
  368. func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) {
  369. client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}}
  370. return client.Dial(address)
  371. }
  372. // DialWithTLS connects to the address on the named network with TLS.
  373. func DialWithTLS(network, address string, tlsConfig *tls.Config) (conn *Conn, err error) {
  374. if !strings.HasSuffix(network, "-tls") {
  375. network += "-tls"
  376. }
  377. client := Client{Net: network, TLSConfig: tlsConfig}
  378. return client.Dial(address)
  379. }
  380. // DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.
  381. func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error) {
  382. if !strings.HasSuffix(network, "-tls") {
  383. network += "-tls"
  384. }
  385. client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}, TLSConfig: tlsConfig}
  386. return client.Dial(address)
  387. }
  388. // ExchangeContext acts like Exchange, but honors the deadline on the provided
  389. // context, if present. If there is both a context deadline and a configured
  390. // timeout on the client, the earliest of the two takes effect.
  391. func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
  392. var timeout time.Duration
  393. if deadline, ok := ctx.Deadline(); !ok {
  394. timeout = 0
  395. } else {
  396. timeout = time.Until(deadline)
  397. }
  398. // not passing the context to the underlying calls, as the API does not support
  399. // context. For timeouts you should set up Client.Dialer and call Client.Exchange.
  400. // TODO(tmthrgd,miekg): this is a race condition.
  401. c.Dialer = &net.Dialer{Timeout: timeout}
  402. return c.Exchange(m, a)
  403. }