3 // A client implementation.
17 dnsTimeout time.Duration = 2 * time.Second
18 tcpIdleTimeout time.Duration = 8 * time.Second
21 // A Conn represents a connection to a DNS server.
23 net.Conn // a net.Conn holding the connection
24 UDPSize uint16 // minimum receive buffer for UDP messages
25 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)
29 // A Client defines parameters for a DNS client.
31 Net string // if "tcp" or "tcp-tls" (DNS over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
32 UDPSize uint16 // minimum receive buffer for UDP messages
33 TLSConfig *tls.Config // TLS connection configuration
34 Dialer *net.Dialer // a net.Dialer used to set local address, timeouts and more
35 // Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout,
36 // WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and
37 // Client.Dialer) or context.Context.Deadline (see the deprecated ExchangeContext)
39 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
40 ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
41 WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
42 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)
43 SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass
47 // Exchange performs a synchronous UDP query. It sends the message m to the address
48 // contained in a and waits for a reply. Exchange does not retry a failed query, nor
49 // will it fall back to TCP in case of truncation.
50 // See client.Exchange for more information on setting larger buffer sizes.
51 func Exchange(m *Msg, a string) (r *Msg, err error) {
52 client := Client{Net: "udp"}
53 r, _, err = client.Exchange(m, a)
57 func (c *Client) dialTimeout() time.Duration {
61 if c.DialTimeout != 0 {
67 func (c *Client) readTimeout() time.Duration {
68 if c.ReadTimeout != 0 {
74 func (c *Client) writeTimeout() time.Duration {
75 if c.WriteTimeout != 0 {
81 // Dial connects to the address on the named network.
82 func (c *Client) Dial(address string) (conn *Conn, err error) {
83 // create a new dialer with the appropriate timeout
86 d = net.Dialer{Timeout: c.getTimeoutForRequest(c.dialTimeout())}
96 useTLS := strings.HasPrefix(network, "tcp") && strings.HasSuffix(network, "-tls")
100 network = strings.TrimSuffix(network, "-tls")
102 conn.Conn, err = tls.DialWithDialer(&d, network, address, c.TLSConfig)
104 conn.Conn, err = d.Dial(network, address)
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:
116 // c := new(dns.Client)
117 // in, rtt, err := c.Exchange(message, "127.0.0.1:53")
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
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 if !c.SingleInflight {
129 return c.exchange(m, address)
133 if t1, ok := TypeToString[m.Question[0].Qtype]; ok {
137 if cl1, ok := ClassToString[m.Question[0].Qclass]; ok {
140 r, rtt, err, shared := c.group.Do(m.Question[0].Name+t+cl, func() (*Msg, time.Duration, error) {
141 return c.exchange(m, address)
143 if r != nil && shared {
149 func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
160 // If EDNS0 is used use that for size.
161 if opt != nil && opt.UDPSize() >= MinMsgSize {
162 co.UDPSize = opt.UDPSize()
164 // Otherwise use the client's configured UDP size.
165 if opt == nil && c.UDPSize >= MinMsgSize {
166 co.UDPSize = c.UDPSize
169 co.TsigSecret = c.TsigSecret
171 // write with the appropriate write timeout
172 co.SetWriteDeadline(t.Add(c.getTimeoutForRequest(c.writeTimeout())))
173 if err = co.WriteMsg(m); err != nil {
177 co.SetReadDeadline(time.Now().Add(c.getTimeoutForRequest(c.readTimeout())))
178 r, err = co.ReadMsg()
179 if err == nil && r.Id != m.Id {
186 // ReadMsg reads a message from the connection co.
187 // If the received message contains a TSIG record the transaction signature
188 // is verified. This method always tries to return the message, however if an
189 // error is returned there are no guarantees that the returned message is a
190 // valid representation of the packet read.
191 func (co *Conn) ReadMsg() (*Msg, error) {
192 p, err := co.ReadMsgHeader(nil)
198 if err := m.Unpack(p); err != nil {
199 // If an error was returned, we still want to allow the user to use
200 // the message, but naively they can just check err if they don't want
201 // to use an erroneous message
204 if t := m.IsTsig(); t != nil {
205 if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
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)
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) {
224 switch t := co.Conn.(type) {
225 case *net.TCPConn, *tls.Conn:
228 // First two bytes specify the length of the entire message.
229 l, err := tcpMsgLen(r)
234 n, err = tcpRead(r, p)
236 if co.UDPSize > MinMsgSize {
237 p = make([]byte, co.UDPSize)
239 p = make([]byte, MinMsgSize)
246 } else if n < headerSize {
247 return nil, ErrShortRead
252 dh, _, err := unpackMsgHdr(p, 0)
261 // tcpMsgLen is a helper func to read first two bytes of stream as uint16 packet length.
262 func tcpMsgLen(t io.Reader) (int, error) {
269 // As seen with my local router/switch, returns 1 byte on the above read,
270 // resulting a a ShortRead. Just write it out (instead of loop) and read the
273 n1, err := t.Read(p[1:])
281 return 0, ErrShortRead
283 l := binary.BigEndian.Uint16(p)
285 return 0, ErrShortRead
290 // tcpRead calls TCPConn.Read enough times to fill allocated buffer.
291 func tcpRead(t io.Reader, p []byte) (int, error) {
297 j, err := t.Read(p[n:])
306 // Read implements the net.Conn read method.
307 func (co *Conn) Read(p []byte) (n int, err error) {
309 return 0, ErrConnEmpty
312 return 0, io.ErrShortBuffer
314 switch t := co.Conn.(type) {
315 case *net.TCPConn, *tls.Conn:
318 l, err := tcpMsgLen(r)
323 return l, io.ErrShortBuffer
325 return tcpRead(r, p[:l])
328 return co.Conn.Read(p)
331 // WriteMsg sends a message through the connection co.
332 // If the message m contains a TSIG record the transaction
333 // signature is calculated.
334 func (co *Conn) WriteMsg(m *Msg) (err error) {
336 if t := m.IsTsig(); t != nil {
338 if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
341 out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
342 // Set for the next read, although only used in zone transfers
343 co.tsigRequestMAC = mac
350 _, err = co.Write(out)
354 // Write implements the net.Conn Write method.
355 func (co *Conn) Write(p []byte) (n int, err error) {
356 switch t := co.Conn.(type) {
357 case *net.TCPConn, *tls.Conn:
362 return 0, io.ErrShortBuffer
365 return 0, &Error{err: "message too large"}
367 l := make([]byte, 2, lp+2)
368 binary.BigEndian.PutUint16(l, uint16(lp))
370 n, err := io.Copy(w, bytes.NewReader(p))
373 return co.Conn.Write(p)
376 // Return the appropriate timeout for a specific request
377 func (c *Client) getTimeoutForRequest(timeout time.Duration) time.Duration {
378 var requestTimeout time.Duration
380 requestTimeout = c.Timeout
382 requestTimeout = timeout
384 // net.Dialer.Timeout has priority if smaller than the timeouts computed so
386 if c.Dialer != nil && c.Dialer.Timeout != 0 {
387 if c.Dialer.Timeout < requestTimeout {
388 requestTimeout = c.Dialer.Timeout
391 return requestTimeout
394 // Dial connects to the address on the named network.
395 func Dial(network, address string) (conn *Conn, err error) {
397 conn.Conn, err = net.Dial(network, address)
404 // ExchangeContext performs a synchronous UDP query, like Exchange. It
405 // additionally obeys deadlines from the passed Context.
406 func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error) {
407 client := Client{Net: "udp"}
408 r, _, err = client.ExchangeContext(ctx, m, a)
409 // ignorint rtt to leave the original ExchangeContext API unchanged, but
410 // this function will go away
414 // ExchangeConn performs a synchronous query. It sends the message m via the connection
415 // c and waits for a reply. The connection c is not closed by ExchangeConn.
416 // Deprecated: This function is going away, but can easily be mimicked:
418 // co := &dns.Conn{Conn: c} // c is your net.Conn
420 // in, _ := co.ReadMsg()
423 func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
424 println("dns: ExchangeConn: this function is deprecated")
427 if err = co.WriteMsg(m); err != nil {
430 r, err = co.ReadMsg()
431 if err == nil && r.Id != m.Id {
437 // DialTimeout acts like Dial but takes a timeout.
438 func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) {
439 client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}}
440 return client.Dial(address)
443 // DialWithTLS connects to the address on the named network with TLS.
444 func DialWithTLS(network, address string, tlsConfig *tls.Config) (conn *Conn, err error) {
445 if !strings.HasSuffix(network, "-tls") {
448 client := Client{Net: network, TLSConfig: tlsConfig}
449 return client.Dial(address)
452 // DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.
453 func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error) {
454 if !strings.HasSuffix(network, "-tls") {
457 client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}, TLSConfig: tlsConfig}
458 return client.Dial(address)
461 // ExchangeContext acts like Exchange, but honors the deadline on the provided
462 // context, if present. If there is both a context deadline and a configured
463 // timeout on the client, the earliest of the two takes effect.
464 func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
465 var timeout time.Duration
466 if deadline, ok := ctx.Deadline(); !ok {
469 timeout = time.Until(deadline)
471 // not passing the context to the underlying calls, as the API does not support
472 // context. For timeouts you should set up Client.Dialer and call Client.Exchange.
473 // TODO(tmthrgd,miekg): this is a race condition.
474 c.Dialer = &net.Dialer{Timeout: timeout}
475 return c.Exchange(m, a)