client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. tsigRequestMAC string
  23. }
  24. // A Client defines parameters for a DNS client.
  25. type Client struct {
  26. Net string // if "tcp" or "tcp-tls" (DNS over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
  27. UDPSize uint16 // minimum receive buffer for UDP messages
  28. TLSConfig *tls.Config // TLS connection configuration
  29. Dialer *net.Dialer // a net.Dialer used to set local address, timeouts and more
  30. // Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout,
  31. // WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and
  32. // Client.Dialer) or context.Context.Deadline (see the deprecated ExchangeContext)
  33. Timeout time.Duration
  34. 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
  35. ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
  36. WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
  37. 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)
  38. SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass
  39. group singleflight
  40. }
  41. // Exchange performs a synchronous UDP query. It sends the message m to the address
  42. // contained in a and waits for a reply. Exchange does not retry a failed query, nor
  43. // will it fall back to TCP in case of truncation.
  44. // See client.Exchange for more information on setting larger buffer sizes.
  45. func Exchange(m *Msg, a string) (r *Msg, err error) {
  46. client := Client{Net: "udp"}
  47. r, _, err = client.Exchange(m, a)
  48. return r, err
  49. }
  50. func (c *Client) dialTimeout() time.Duration {
  51. if c.Timeout != 0 {
  52. return c.Timeout
  53. }
  54. if c.DialTimeout != 0 {
  55. return c.DialTimeout
  56. }
  57. return dnsTimeout
  58. }
  59. func (c *Client) readTimeout() time.Duration {
  60. if c.ReadTimeout != 0 {
  61. return c.ReadTimeout
  62. }
  63. return dnsTimeout
  64. }
  65. func (c *Client) writeTimeout() time.Duration {
  66. if c.WriteTimeout != 0 {
  67. return c.WriteTimeout
  68. }
  69. return dnsTimeout
  70. }
  71. // Dial connects to the address on the named network.
  72. func (c *Client) Dial(address string) (conn *Conn, err error) {
  73. // create a new dialer with the appropriate timeout
  74. var d net.Dialer
  75. if c.Dialer == nil {
  76. d = net.Dialer{Timeout: c.getTimeoutForRequest(c.dialTimeout())}
  77. } else {
  78. d = *c.Dialer
  79. }
  80. network := c.Net
  81. if network == "" {
  82. network = "udp"
  83. }
  84. useTLS := strings.HasPrefix(network, "tcp") && strings.HasSuffix(network, "-tls")
  85. conn = new(Conn)
  86. if useTLS {
  87. network = strings.TrimSuffix(network, "-tls")
  88. conn.Conn, err = tls.DialWithDialer(&d, network, address, c.TLSConfig)
  89. } else {
  90. conn.Conn, err = d.Dial(network, address)
  91. }
  92. if err != nil {
  93. return nil, err
  94. }
  95. return conn, nil
  96. }
  97. // Exchange performs a synchronous query. It sends the message m to the address
  98. // contained in a and waits for a reply. Basic use pattern with a *dns.Client:
  99. //
  100. // c := new(dns.Client)
  101. // in, rtt, err := c.Exchange(message, "127.0.0.1:53")
  102. //
  103. // Exchange does not retry a failed query, nor will it fall back to TCP in
  104. // case of truncation.
  105. // It is up to the caller to create a message that allows for larger responses to be
  106. // returned. Specifically this means adding an EDNS0 OPT RR that will advertise a larger
  107. // buffer, see SetEdns0. Messages without an OPT RR will fallback to the historic limit
  108. // of 512 bytes
  109. // To specify a local address or a timeout, the caller has to set the `Client.Dialer`
  110. // attribute appropriately
  111. func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error) {
  112. if !c.SingleInflight {
  113. return c.exchange(m, address)
  114. }
  115. q := m.Question[0]
  116. key := fmt.Sprintf("%s:%d:%d", q.Name, q.Qtype, q.Qclass)
  117. r, rtt, err, shared := c.group.Do(key, func() (*Msg, time.Duration, error) {
  118. return c.exchange(m, address)
  119. })
  120. if r != nil && shared {
  121. r = r.Copy()
  122. }
  123. return r, rtt, err
  124. }
  125. func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
  126. var co *Conn
  127. co, err = c.Dial(a)
  128. if err != nil {
  129. return nil, 0, err
  130. }
  131. defer co.Close()
  132. opt := m.IsEdns0()
  133. // If EDNS0 is used use that for size.
  134. if opt != nil && opt.UDPSize() >= MinMsgSize {
  135. co.UDPSize = opt.UDPSize()
  136. }
  137. // Otherwise use the client's configured UDP size.
  138. if opt == nil && c.UDPSize >= MinMsgSize {
  139. co.UDPSize = c.UDPSize
  140. }
  141. co.TsigSecret = c.TsigSecret
  142. t := time.Now()
  143. // write with the appropriate write timeout
  144. co.SetWriteDeadline(t.Add(c.getTimeoutForRequest(c.writeTimeout())))
  145. if err = co.WriteMsg(m); err != nil {
  146. return nil, 0, err
  147. }
  148. co.SetReadDeadline(time.Now().Add(c.getTimeoutForRequest(c.readTimeout())))
  149. r, err = co.ReadMsg()
  150. if err == nil && r.Id != m.Id {
  151. err = ErrId
  152. }
  153. rtt = time.Since(t)
  154. return r, rtt, err
  155. }
  156. // ReadMsg reads a message from the connection co.
  157. // If the received message contains a TSIG record the transaction signature
  158. // is verified. This method always tries to return the message, however if an
  159. // error is returned there are no guarantees that the returned message is a
  160. // valid representation of the packet read.
  161. func (co *Conn) ReadMsg() (*Msg, error) {
  162. p, err := co.ReadMsgHeader(nil)
  163. if err != nil {
  164. return nil, err
  165. }
  166. m := new(Msg)
  167. if err := m.Unpack(p); err != nil {
  168. // If an error was returned, we still want to allow the user to use
  169. // the message, but naively they can just check err if they don't want
  170. // to use an erroneous message
  171. return m, err
  172. }
  173. if t := m.IsTsig(); t != nil {
  174. if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
  175. return m, ErrSecret
  176. }
  177. // Need to work on the original message p, as that was used to calculate the tsig.
  178. err = TsigVerify(p, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
  179. }
  180. return m, err
  181. }
  182. // ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil).
  183. // Returns message as a byte slice to be parsed with Msg.Unpack later on.
  184. // Note that error handling on the message body is not possible as only the header is parsed.
  185. func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
  186. var (
  187. p []byte
  188. n int
  189. err error
  190. )
  191. if _, ok := co.Conn.(net.PacketConn); ok {
  192. if co.UDPSize > MinMsgSize {
  193. p = make([]byte, co.UDPSize)
  194. } else {
  195. p = make([]byte, MinMsgSize)
  196. }
  197. n, err = co.Read(p)
  198. } else {
  199. var length uint16
  200. if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
  201. return nil, err
  202. }
  203. p = make([]byte, length)
  204. n, err = io.ReadFull(co.Conn, p)
  205. }
  206. if err != nil {
  207. return nil, err
  208. } else if n < headerSize {
  209. return nil, ErrShortRead
  210. }
  211. p = p[:n]
  212. if hdr != nil {
  213. dh, _, err := unpackMsgHdr(p, 0)
  214. if err != nil {
  215. return nil, err
  216. }
  217. *hdr = dh
  218. }
  219. return p, err
  220. }
  221. // Read implements the net.Conn read method.
  222. func (co *Conn) Read(p []byte) (n int, err error) {
  223. if co.Conn == nil {
  224. return 0, ErrConnEmpty
  225. }
  226. if _, ok := co.Conn.(net.PacketConn); ok {
  227. // UDP connection
  228. return co.Conn.Read(p)
  229. }
  230. var length uint16
  231. if err := binary.Read(co.Conn, binary.BigEndian, &length); err != nil {
  232. return 0, err
  233. }
  234. if int(length) > len(p) {
  235. return 0, io.ErrShortBuffer
  236. }
  237. return io.ReadFull(co.Conn, p[:length])
  238. }
  239. // WriteMsg sends a message through the connection co.
  240. // If the message m contains a TSIG record the transaction
  241. // signature is calculated.
  242. func (co *Conn) WriteMsg(m *Msg) (err error) {
  243. var out []byte
  244. if t := m.IsTsig(); t != nil {
  245. mac := ""
  246. if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
  247. return ErrSecret
  248. }
  249. out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
  250. // Set for the next read, although only used in zone transfers
  251. co.tsigRequestMAC = mac
  252. } else {
  253. out, err = m.Pack()
  254. }
  255. if err != nil {
  256. return err
  257. }
  258. _, err = co.Write(out)
  259. return err
  260. }
  261. // Write implements the net.Conn Write method.
  262. func (co *Conn) Write(p []byte) (int, error) {
  263. if len(p) > MaxMsgSize {
  264. return 0, &Error{err: "message too large"}
  265. }
  266. if _, ok := co.Conn.(net.PacketConn); ok {
  267. return co.Conn.Write(p)
  268. }
  269. l := make([]byte, 2)
  270. binary.BigEndian.PutUint16(l, uint16(len(p)))
  271. n, err := (&net.Buffers{l, p}).WriteTo(co.Conn)
  272. return int(n), err
  273. }
  274. // Return the appropriate timeout for a specific request
  275. func (c *Client) getTimeoutForRequest(timeout time.Duration) time.Duration {
  276. var requestTimeout time.Duration
  277. if c.Timeout != 0 {
  278. requestTimeout = c.Timeout
  279. } else {
  280. requestTimeout = timeout
  281. }
  282. // net.Dialer.Timeout has priority if smaller than the timeouts computed so
  283. // far
  284. if c.Dialer != nil && c.Dialer.Timeout != 0 {
  285. if c.Dialer.Timeout < requestTimeout {
  286. requestTimeout = c.Dialer.Timeout
  287. }
  288. }
  289. return requestTimeout
  290. }
  291. // Dial connects to the address on the named network.
  292. func Dial(network, address string) (conn *Conn, err error) {
  293. conn = new(Conn)
  294. conn.Conn, err = net.Dial(network, address)
  295. if err != nil {
  296. return nil, err
  297. }
  298. return conn, nil
  299. }
  300. // ExchangeContext performs a synchronous UDP query, like Exchange. It
  301. // additionally obeys deadlines from the passed Context.
  302. func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error) {
  303. client := Client{Net: "udp"}
  304. r, _, err = client.ExchangeContext(ctx, m, a)
  305. // ignorint rtt to leave the original ExchangeContext API unchanged, but
  306. // this function will go away
  307. return r, err
  308. }
  309. // ExchangeConn performs a synchronous query. It sends the message m via the connection
  310. // c and waits for a reply. The connection c is not closed by ExchangeConn.
  311. // Deprecated: This function is going away, but can easily be mimicked:
  312. //
  313. // co := &dns.Conn{Conn: c} // c is your net.Conn
  314. // co.WriteMsg(m)
  315. // in, _ := co.ReadMsg()
  316. // co.Close()
  317. //
  318. func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
  319. println("dns: ExchangeConn: this function is deprecated")
  320. co := new(Conn)
  321. co.Conn = c
  322. if err = co.WriteMsg(m); err != nil {
  323. return nil, err
  324. }
  325. r, err = co.ReadMsg()
  326. if err == nil && r.Id != m.Id {
  327. err = ErrId
  328. }
  329. return r, err
  330. }
  331. // DialTimeout acts like Dial but takes a timeout.
  332. func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) {
  333. client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}}
  334. return client.Dial(address)
  335. }
  336. // DialWithTLS connects to the address on the named network with TLS.
  337. func DialWithTLS(network, address string, tlsConfig *tls.Config) (conn *Conn, err error) {
  338. if !strings.HasSuffix(network, "-tls") {
  339. network += "-tls"
  340. }
  341. client := Client{Net: network, TLSConfig: tlsConfig}
  342. return client.Dial(address)
  343. }
  344. // DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.
  345. func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error) {
  346. if !strings.HasSuffix(network, "-tls") {
  347. network += "-tls"
  348. }
  349. client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}, TLSConfig: tlsConfig}
  350. return client.Dial(address)
  351. }
  352. // ExchangeContext acts like Exchange, but honors the deadline on the provided
  353. // context, if present. If there is both a context deadline and a configured
  354. // timeout on the client, the earliest of the two takes effect.
  355. func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
  356. var timeout time.Duration
  357. if deadline, ok := ctx.Deadline(); !ok {
  358. timeout = 0
  359. } else {
  360. timeout = time.Until(deadline)
  361. }
  362. // not passing the context to the underlying calls, as the API does not support
  363. // context. For timeouts you should set up Client.Dialer and call Client.Exchange.
  364. // TODO(tmthrgd,miekg): this is a race condition.
  365. c.Dialer = &net.Dialer{Timeout: timeout}
  366. return c.Exchange(m, a)
  367. }