dns/client.go

497 lines
14 KiB
Go
Raw Normal View History

2011-04-12 19:44:56 +00:00
package dns
2013-01-28 19:41:17 +00:00
// A client implementation.
2011-04-12 19:44:56 +00:00
import (
"bytes"
"context"
"crypto/tls"
"encoding/binary"
2011-04-15 21:55:27 +00:00
"io"
"net"
"strings"
2012-01-20 11:13:47 +00:00
"time"
2011-04-12 19:44:56 +00:00
)
const (
dnsTimeout time.Duration = 2 * time.Second
tcpIdleTimeout time.Duration = 8 * time.Second
)
2013-10-11 21:34:04 +00:00
// A Conn represents a connection to a DNS server.
2013-09-28 19:31:29 +00:00
type Conn struct {
2013-10-11 16:18:37 +00:00
net.Conn // a net.Conn holding the connection
2014-07-31 08:48:26 +00:00
UDPSize uint16 // minimum receive buffer for UDP messages
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)
2013-10-11 16:18:37 +00:00
tsigRequestMAC string
}
// A Client defines parameters for a DNS client.
2011-04-12 19:44:56 +00:00
type Client struct {
Net string // if "tcp" or "tcp-tls" (DNS over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
UDPSize uint16 // minimum receive buffer for UDP messages
TLSConfig *tls.Config // TLS connection configuration
Dialer *net.Dialer // a net.Dialer used to set local address, timeouts and more
// Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout,
// WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and
// Client.Dialer) or context.Context.Deadline (see the deprecated ExchangeContext)
Timeout time.Duration
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
ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
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)
2013-09-06 09:49:07 +00:00
SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass
group singleflight
}
// Exchange performs a synchronous UDP query. It sends the message m to the address
2016-10-03 14:10:00 +00:00
// contained in a and waits for a reply. Exchange does not retry a failed query, nor
2013-12-30 16:46:53 +00:00
// will it fall back to TCP in case of truncation.
// See client.Exchange for more information on setting larger buffer sizes.
func Exchange(m *Msg, a string) (r *Msg, err error) {
client := Client{Net: "udp"}
r, _, err = client.Exchange(m, a)
return r, err
}
func (c *Client) dialTimeout() time.Duration {
if c.Timeout != 0 {
return c.Timeout
}
if c.DialTimeout != 0 {
return c.DialTimeout
}
return dnsTimeout
}
func (c *Client) readTimeout() time.Duration {
if c.ReadTimeout != 0 {
return c.ReadTimeout
}
return dnsTimeout
2013-09-28 19:31:29 +00:00
}
func (c *Client) writeTimeout() time.Duration {
if c.WriteTimeout != 0 {
return c.WriteTimeout
}
return dnsTimeout
}
// Dial connects to the address on the named network.
func (c *Client) Dial(address string) (conn *Conn, err error) {
// create a new dialer with the appropriate timeout
var d net.Dialer
if c.Dialer == nil {
d = net.Dialer{Timeout: c.getTimeoutForRequest(c.dialTimeout())}
} else {
d = *c.Dialer
}
network := c.Net
if network == "" {
network = "udp"
}
useTLS := strings.HasPrefix(network, "tcp") && strings.HasSuffix(network, "-tls")
conn = new(Conn)
if useTLS {
network = strings.TrimSuffix(network, "-tls")
conn.Conn, err = tls.DialWithDialer(&d, network, address, c.TLSConfig)
} else {
conn.Conn, err = d.Dial(network, address)
2013-10-12 11:35:09 +00:00
}
if err != nil {
return nil, err
}
return conn, nil
2013-10-12 11:35:09 +00:00
}
2016-10-03 14:10:00 +00:00
// Exchange performs a synchronous query. It sends the message m to the address
// contained in a and waits for a reply. Basic use pattern with a *dns.Client:
//
// c := new(dns.Client)
// in, rtt, err := c.Exchange(message, "127.0.0.1:53")
//
// Exchange does not retry a failed query, nor will it fall back to TCP in
// case of truncation.
// It is up to the caller to create a message that allows for larger responses to be
// returned. Specifically this means adding an EDNS0 OPT RR that will advertise a larger
2017-03-19 15:10:46 +00:00
// buffer, see SetEdns0. Messages without an OPT RR will fallback to the historic limit
// of 512 bytes
// To specify a local address or a timeout, the caller has to set the `Client.Dialer`
// attribute appropriately
func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error) {
2013-09-06 09:49:07 +00:00
if !c.SingleInflight {
return c.exchange(m, address)
}
t := "nop"
if t1, ok := TypeToString[m.Question[0].Qtype]; ok {
t = t1
}
cl := "nop"
if cl1, ok := ClassToString[m.Question[0].Qclass]; ok {
cl = cl1
}
r, rtt, err, shared := c.group.Do(m.Question[0].Name+t+cl, func() (*Msg, time.Duration, error) {
return c.exchange(m, address)
})
if r != nil && shared {
r = r.Copy()
}
return r, rtt, err
}
func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
var co *Conn
co, err = c.Dial(a)
if err != nil {
2013-01-28 19:30:13 +00:00
return nil, 0, err
}
defer co.Close()
opt := m.IsEdns0()
2014-07-31 08:48:26 +00:00
// If EDNS0 is used use that for size.
if opt != nil && opt.UDPSize() >= MinMsgSize {
co.UDPSize = opt.UDPSize()
}
2014-07-31 08:48:26 +00:00
// Otherwise use the client's configured UDP size.
if opt == nil && c.UDPSize >= MinMsgSize {
co.UDPSize = c.UDPSize
}
co.TsigSecret = c.TsigSecret
t := time.Now()
// write with the appropriate write timeout
co.SetWriteDeadline(t.Add(c.getTimeoutForRequest(c.writeTimeout())))
if err = co.WriteMsg(m); err != nil {
2013-01-28 19:30:13 +00:00
return nil, 0, err
}
co.SetReadDeadline(time.Now().Add(c.getTimeoutForRequest(c.readTimeout())))
r, err = co.ReadMsg()
if err == nil && r.Id != m.Id {
err = ErrId
}
rtt = time.Since(t)
return r, rtt, err
2011-08-08 11:10:35 +00:00
}
// ReadMsg reads a message from the connection co.
// If the received message contains a TSIG record the transaction signature
// is verified. This method always tries to return the message, however if an
// error is returned there are no guarantees that the returned message is a
// valid representation of the packet read.
func (co *Conn) ReadMsg() (*Msg, error) {
p, err := co.ReadMsgHeader(nil)
if err != nil {
2011-04-18 20:08:12 +00:00
return nil, err
}
m := new(Msg)
if err := m.Unpack(p); err != nil {
// If an error was returned, we still want to allow the user to use
// the message, but naively they can just check err if they don't want
// to use an erroneous message
return m, err
2011-04-18 20:08:12 +00:00
}
if t := m.IsTsig(); t != nil {
if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
2012-10-16 07:42:38 +00:00
return m, ErrSecret
2011-04-22 14:37:26 +00:00
}
2012-02-25 20:42:08 +00:00
// Need to work on the original message p, as that was used to calculate the tsig.
2013-10-11 16:18:37 +00:00
err = TsigVerify(p, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
2011-04-22 14:37:26 +00:00
}
return m, err
}
2011-04-15 21:55:27 +00:00
// ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil).
// Returns message as a byte slice to be parsed with Msg.Unpack later on.
// Note that error handling on the message body is not possible as only the header is parsed.
func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
2015-06-29 12:06:49 +00:00
var (
p []byte
n int
err error
)
switch t := co.Conn.(type) {
case *net.TCPConn, *tls.Conn:
r := t.(io.Reader)
// First two bytes specify the length of the entire message.
l, err := tcpMsgLen(r)
2015-06-29 12:06:49 +00:00
if err != nil {
return nil, err
}
p = make([]byte, l)
n, err = tcpRead(r, p)
default:
if co.UDPSize > MinMsgSize {
p = make([]byte, co.UDPSize)
} else {
p = make([]byte, MinMsgSize)
}
2015-06-29 12:06:49 +00:00
n, err = co.Read(p)
}
if err != nil {
return nil, err
} else if n < headerSize {
return nil, ErrShortRead
}
p = p[:n]
if hdr != nil {
dh, _, err := unpackMsgHdr(p, 0)
if err != nil {
return nil, err
}
*hdr = dh
}
return p, err
}
// tcpMsgLen is a helper func to read first two bytes of stream as uint16 packet length.
func tcpMsgLen(t io.Reader) (int, error) {
p := []byte{0, 0}
n, err := t.Read(p)
2015-06-29 12:06:49 +00:00
if err != nil {
return 0, err
}
// As seen with my local router/switch, returns 1 byte on the above read,
// resulting a a ShortRead. Just write it out (instead of loop) and read the
// other byte.
if n == 1 {
n1, err := t.Read(p[1:])
if err != nil {
return 0, err
}
n += n1
}
if n != 2 {
2015-06-29 12:06:49 +00:00
return 0, ErrShortRead
}
l := binary.BigEndian.Uint16(p)
2015-06-29 12:06:49 +00:00
if l == 0 {
return 0, ErrShortRead
}
return int(l), nil
}
// tcpRead calls TCPConn.Read enough times to fill allocated buffer.
func tcpRead(t io.Reader, p []byte) (int, error) {
2015-06-29 12:06:49 +00:00
n, err := t.Read(p)
if err != nil {
return n, err
}
for n < len(p) {
j, err := t.Read(p[n:])
if err != nil {
return n, err
}
n += j
}
return n, err
}
// Read implements the net.Conn read method.
func (co *Conn) Read(p []byte) (n int, err error) {
if co.Conn == nil {
2011-11-02 22:06:54 +00:00
return 0, ErrConnEmpty
}
if len(p) < 2 {
2012-05-26 08:24:47 +00:00
return 0, io.ErrShortBuffer
}
switch t := co.Conn.(type) {
case *net.TCPConn, *tls.Conn:
r := t.(io.Reader)
l, err := tcpMsgLen(r)
if err != nil {
2015-06-29 12:06:49 +00:00
return 0, err
}
2015-06-29 12:06:49 +00:00
if l > len(p) {
return int(l), io.ErrShortBuffer
2011-04-18 20:08:12 +00:00
}
return tcpRead(r, p[:l])
2013-10-12 17:32:53 +00:00
}
2014-02-14 22:47:53 +00:00
// UDP connection
2013-10-12 17:47:11 +00:00
n, err = co.Conn.Read(p)
2013-10-12 17:32:53 +00:00
if err != nil {
return n, err
2011-04-17 08:54:34 +00:00
}
return n, err
2011-04-15 21:55:27 +00:00
}
2016-01-19 22:24:18 +00:00
// WriteMsg sends a message through the connection co.
2011-04-18 20:08:12 +00:00
// If the message m contains a TSIG record the transaction
// signature is calculated.
func (co *Conn) WriteMsg(m *Msg) (err error) {
2012-03-02 20:19:37 +00:00
var out []byte
if t := m.IsTsig(); t != nil {
2012-03-02 20:19:37 +00:00
mac := ""
if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
return ErrSecret
2011-04-22 14:37:26 +00:00
}
2013-10-11 16:18:37 +00:00
out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
2016-01-19 22:23:11 +00:00
// Set for the next read, although only used in zone transfers
2013-10-11 16:18:37 +00:00
co.tsigRequestMAC = mac
2012-03-02 20:19:37 +00:00
} else {
out, err = m.Pack()
}
if err != nil {
return err
2011-04-15 21:55:27 +00:00
}
if _, err = co.Write(out); err != nil {
2012-03-02 20:19:37 +00:00
return err
}
2011-04-15 21:55:27 +00:00
return nil
}
// Write implements the net.Conn Write method.
func (co *Conn) Write(p []byte) (n int, err error) {
switch t := co.Conn.(type) {
case *net.TCPConn, *tls.Conn:
w := t.(io.Writer)
lp := len(p)
if lp < 2 {
2011-04-15 21:55:27 +00:00
return 0, io.ErrShortBuffer
}
if lp > MaxMsgSize {
return 0, &Error{err: "message too large"}
2011-04-15 21:55:27 +00:00
}
l := make([]byte, 2, lp+2)
binary.BigEndian.PutUint16(l, uint16(lp))
p = append(l, p...)
n, err := io.Copy(w, bytes.NewReader(p))
return int(n), err
2011-04-15 21:55:27 +00:00
}
n, err = co.Conn.Write(p)
return n, err
2011-04-15 21:55:27 +00:00
}
2012-05-04 21:18:29 +00:00
// Return the appropriate timeout for a specific request
func (c *Client) getTimeoutForRequest(timeout time.Duration) time.Duration {
var requestTimeout time.Duration
if c.Timeout != 0 {
requestTimeout = c.Timeout
} else {
requestTimeout = timeout
}
// net.Dialer.Timeout has priority if smaller than the timeouts computed so
// far
if c.Dialer != nil && c.Dialer.Timeout != 0 {
if c.Dialer.Timeout < requestTimeout {
requestTimeout = c.Dialer.Timeout
}
}
return requestTimeout
}
// Dial connects to the address on the named network.
func Dial(network, address string) (conn *Conn, err error) {
2013-11-01 09:50:55 +00:00
conn = new(Conn)
conn.Conn, err = net.Dial(network, address)
if err != nil {
return nil, err
}
return conn, nil
}
// ExchangeContext performs a synchronous UDP query, like Exchange. It
// additionally obeys deadlines from the passed Context.
func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error) {
client := Client{Net: "udp"}
r, _, err = client.ExchangeContext(ctx, m, a)
// ignorint rtt to leave the original ExchangeContext API unchanged, but
// this function will go away
return r, err
}
// ExchangeConn performs a synchronous query. It sends the message m via the connection
// c and waits for a reply. The connection c is not closed by ExchangeConn.
// This function is going away, but can easily be mimicked:
//
// co := &dns.Conn{Conn: c} // c is your net.Conn
// co.WriteMsg(m)
// in, _ := co.ReadMsg()
// co.Close()
//
func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
println("dns: ExchangeConn: this function is deprecated")
co := new(Conn)
co.Conn = c
if err = co.WriteMsg(m); err != nil {
return nil, err
}
r, err = co.ReadMsg()
if err == nil && r.Id != m.Id {
err = ErrId
}
return r, err
}
// DialTimeout acts like Dial but takes a timeout.
func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) {
client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}}
conn, err = client.Dial(address)
if err != nil {
return nil, err
}
return conn, nil
}
// DialWithTLS connects to the address on the named network with TLS.
func DialWithTLS(network, address string, tlsConfig *tls.Config) (conn *Conn, err error) {
if !strings.HasSuffix(network, "-tls") {
network += "-tls"
}
client := Client{Net: network, TLSConfig: tlsConfig}
conn, err = client.Dial(address)
if err != nil {
return nil, err
}
return conn, nil
}
// DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.
func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error) {
if !strings.HasSuffix(network, "-tls") {
network += "-tls"
}
client := Client{Net: network, Dialer: &net.Dialer{Timeout: timeout}, TLSConfig: tlsConfig}
conn, err = client.Dial(address)
if err != nil {
return nil, err
}
return conn, nil
}
// ExchangeContext acts like Exchange, but honors the deadline on the provided
// context, if present. If there is both a context deadline and a configured
// timeout on the client, the earliest of the two takes effect.
func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
var timeout time.Duration
if deadline, ok := ctx.Deadline(); !ok {
timeout = 0
} else {
Fix dominikh/go-tools nits (#758) * Remove unused functions and consts * Address gosimple nits * Address staticcheck nits This excludes several that were intentional or weren't actual errors. * Reduce size of lex struct This reduces the size of the lex struct by 8 bytes from: lex.token string: 0-16 (size 16, align 8) lex.tokenUpper string: 16-32 (size 16, align 8) lex.length int: 32-40 (size 8, align 8) lex.err bool: 40-41 (size 1, align 1) lex.value uint8: 41-42 (size 1, align 1) padding: 42-48 (size 6, align 0) lex.line int: 48-56 (size 8, align 8) lex.column int: 56-64 (size 8, align 8) lex.torc uint16: 64-66 (size 2, align 2) padding: 66-72 (size 6, align 0) lex.comment string: 72-88 (size 16, align 8) to: lex.token string: 0-16 (size 16, align 8) lex.tokenUpper string: 16-32 (size 16, align 8) lex.length int: 32-40 (size 8, align 8) lex.err bool: 40-41 (size 1, align 1) lex.value uint8: 41-42 (size 1, align 1) lex.torc uint16: 42-44 (size 2, align 2) padding: 44-48 (size 4, align 0) lex.line int: 48-56 (size 8, align 8) lex.column int: 56-64 (size 8, align 8) lex.comment string: 64-80 (size 16, align 8) * Reduce size of response struct This reduces the size of the response struct by 8 bytes from: response.msg []byte: 0-24 (size 24, align 8) response.hijacked bool: 24-25 (size 1, align 1) padding: 25-32 (size 7, align 0) response.tsigStatus error: 32-48 (size 16, align 8) response.tsigTimersOnly bool: 48-49 (size 1, align 1) padding: 49-56 (size 7, align 0) response.tsigRequestMAC string: 56-72 (size 16, align 8) response.tsigSecret map[string]string: 72-80 (size 8, align 8) response.udp *net.UDPConn: 80-88 (size 8, align 8) response.tcp net.Conn: 88-104 (size 16, align 8) response.udpSession *github.com/tmthrgd/dns.SessionUDP: 104-112 (size 8, align 8) response.writer github.com/tmthrgd/dns.Writer: 112-128 (size 16, align 8) response.wg *sync.WaitGroup: 128-136 (size 8, align 8) to: response.msg []byte: 0-24 (size 24, align 8) response.hijacked bool: 24-25 (size 1, align 1) response.tsigTimersOnly bool: 25-26 (size 1, align 1) padding: 26-32 (size 6, align 0) response.tsigStatus error: 32-48 (size 16, align 8) response.tsigRequestMAC string: 48-64 (size 16, align 8) response.tsigSecret map[string]string: 64-72 (size 8, align 8) response.udp *net.UDPConn: 72-80 (size 8, align 8) response.tcp net.Conn: 80-96 (size 16, align 8) response.udpSession *github.com/tmthrgd/dns.SessionUDP: 96-104 (size 8, align 8) response.writer github.com/tmthrgd/dns.Writer: 104-120 (size 16, align 8) response.wg *sync.WaitGroup: 120-128 (size 8, align 8)
2018-09-26 18:32:05 +00:00
timeout = time.Until(deadline)
}
// not passing the context to the underlying calls, as the API does not support
// context. For timeouts you should set up Client.Dialer and call Client.Exchange.
// TODO(tmthrgd,miekg): this is a race condition.
c.Dialer = &net.Dialer{Timeout: timeout}
return c.Exchange(m, a)
}