package dns

// A client implementation.

import (
	
	
	
	
	
	
	
)

const (
	dnsTimeout     time.Duration = 2 * time.Second
	tcpIdleTimeout time.Duration = 8 * time.Second
)

func isPacketConn( net.Conn) bool {
	if ,  := .(net.PacketConn); ! {
		return false
	}

	if ,  := .LocalAddr().(*net.UnixAddr);  {
		return .Net == "unixgram" || .Net == "unixpacket"
	}

	return true
}

// A Conn represents a connection to a DNS server.
type Conn struct {
	net.Conn                         // a net.Conn holding the connection
	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)
	TsigProvider   TsigProvider      // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
	tsigRequestMAC string
}

func ( *Conn) () TsigProvider {
	if .TsigProvider != nil {
		return .TsigProvider
	}
	// tsigSecretProvider will return ErrSecret if co.TsigSecret is nil.
	return tsigSecretProvider(.TsigSecret)
}

// A Client defines parameters for a DNS client.
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 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)
	TsigProvider TsigProvider      // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.

	// SingleInflight previously serialised multiple concurrent queries for the
	// same Qname, Qtype and Qclass to ensure only one would be in flight at a
	// time.
	//
	// Deprecated: This is a no-op. Callers should implement their own in flight
	// query caching if needed. See github.com/miekg/dns/issues/1449.
	SingleInflight bool
}

// Exchange performs a synchronous UDP query. It sends the message m to the address
// contained in a and waits for a reply. Exchange does not retry a failed query, nor
// will it fall back to TCP in case of truncation.
// See client.Exchange for more information on setting larger buffer sizes.
func ( *Msg,  string) ( *Msg,  error) {
	 := Client{Net: "udp"}
	, _,  = .Exchange(, )
	return , 
}

func ( *Client) () time.Duration {
	if .Timeout != 0 {
		return .Timeout
	}
	if .DialTimeout != 0 {
		return .DialTimeout
	}
	return dnsTimeout
}

func ( *Client) () time.Duration {
	if .ReadTimeout != 0 {
		return .ReadTimeout
	}
	return dnsTimeout
}

func ( *Client) () time.Duration {
	if .WriteTimeout != 0 {
		return .WriteTimeout
	}
	return dnsTimeout
}

// Dial connects to the address on the named network.
func ( *Client) ( string) ( *Conn,  error) {
	return .DialContext(context.Background(), )
}

// DialContext connects to the address on the named network, with a context.Context.
func ( *Client) ( context.Context,  string) ( *Conn,  error) {
	// create a new dialer with the appropriate timeout
	var  net.Dialer
	if .Dialer == nil {
		 = net.Dialer{Timeout: .getTimeoutForRequest(.dialTimeout())}
	} else {
		 = *.Dialer
	}

	 := .Net
	if  == "" {
		 = "udp"
	}

	 := strings.HasPrefix(, "tcp") && strings.HasSuffix(, "-tls")

	 = new(Conn)
	if  {
		 = strings.TrimSuffix(, "-tls")

		 := tls.Dialer{
			NetDialer: &,
			Config:    .TLSConfig,
		}
		.Conn,  = .DialContext(, , )
	} else {
		.Conn,  = .DialContext(, , )
	}
	if  != nil {
		return nil, 
	}
	.UDPSize = .UDPSize
	return , nil
}

// 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
// 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 ( *Client) ( *Msg,  string) ( *Msg,  time.Duration,  error) {
	,  := .Dial()

	if  != nil {
		return nil, 0, 
	}
	defer .Close()
	return .ExchangeWithConn(, )
}

// ExchangeWithConn has the same behavior as Exchange, just with a predetermined connection
// that will be used instead of creating a new one.
// Usage pattern with a *dns.Client:
//
//	c := new(dns.Client)
//	// connection management logic goes here
//
//	conn := c.Dial(address)
//	in, rtt, err := c.ExchangeWithConn(message, conn)
//
// This allows users of the library to implement their own connection management,
// as opposed to Exchange, which will always use new connections and incur the added overhead
// that entails when using "tcp" and especially "tcp-tls" clients.
func ( *Client) ( *Msg,  *Conn) ( *Msg,  time.Duration,  error) {
	return .ExchangeWithConnContext(context.Background(), , )
}

// ExchangeWithConnContext has the same behaviour as ExchangeWithConn and
// additionally obeys deadlines from the passed Context.
func ( *Client) ( context.Context,  *Msg,  *Conn) ( *Msg,  time.Duration,  error) {
	 := .IsEdns0()
	// If EDNS0 is used use that for size.
	if  != nil && .UDPSize() >= MinMsgSize {
		.UDPSize = .UDPSize()
	}
	// Otherwise use the client's configured UDP size.
	if  == nil && .UDPSize >= MinMsgSize {
		.UDPSize = .UDPSize
	}

	// write with the appropriate write timeout
	 := time.Now()
	 := .Add(.getTimeoutForRequest(.writeTimeout()))
	 := .Add(.getTimeoutForRequest(.readTimeout()))
	if ,  := .Deadline();  {
		if .Before() {
			 = 
		}
		if .Before() {
			 = 
		}
	}
	.SetWriteDeadline()
	.SetReadDeadline()

	.TsigSecret, .TsigProvider = .TsigSecret, .TsigProvider

	if  = .WriteMsg();  != nil {
		return nil, 0, 
	}

	if isPacketConn(.Conn) {
		for {
			,  = .ReadMsg()
			// Ignore replies with mismatched IDs because they might be
			// responses to earlier queries that timed out.
			if  != nil || .Id == .Id {
				break
			}
		}
	} else {
		,  = .ReadMsg()
		if  == nil && .Id != .Id {
			 = ErrId
		}
	}
	 = time.Since()
	return , , 
}

// 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 ( *Conn) () (*Msg, error) {
	,  := .ReadMsgHeader(nil)
	if  != nil {
		return nil, 
	}

	 := new(Msg)
	if  := .Unpack();  != 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 , 
	}
	if  := .IsTsig();  != nil {
		// Need to work on the original message p, as that was used to calculate the tsig.
		 = TsigVerifyWithProvider(, .tsigProvider(), .tsigRequestMAC, false)
	}
	return , 
}

// 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 ( *Conn) ( *Header) ([]byte, error) {
	var (
		   []byte
		   int
		 error
	)

	if isPacketConn(.Conn) {
		if .UDPSize > MinMsgSize {
			 = make([]byte, .UDPSize)
		} else {
			 = make([]byte, MinMsgSize)
		}
		,  = .Read()
	} else {
		var  uint16
		if  := binary.Read(.Conn, binary.BigEndian, &);  != nil {
			return nil, 
		}

		 = make([]byte, )
		,  = io.ReadFull(.Conn, )
	}

	if  != nil {
		return nil, 
	} else if  < headerSize {
		return nil, ErrShortRead
	}

	 = [:]
	if  != nil {
		, ,  := unpackMsgHdr(, 0)
		if  != nil {
			return nil, 
		}
		* = 
	}
	return , 
}

// Read implements the net.Conn read method.
func ( *Conn) ( []byte) ( int,  error) {
	if .Conn == nil {
		return 0, ErrConnEmpty
	}

	if isPacketConn(.Conn) {
		// UDP connection
		return .Conn.Read()
	}

	var  uint16
	if  := binary.Read(.Conn, binary.BigEndian, &);  != nil {
		return 0, 
	}
	if int() > len() {
		return 0, io.ErrShortBuffer
	}

	return io.ReadFull(.Conn, [:])
}

// WriteMsg sends a message through the connection co.
// If the message m contains a TSIG record the transaction
// signature is calculated.
func ( *Conn) ( *Msg) ( error) {
	var  []byte
	if  := .IsTsig();  != nil {
		// Set tsigRequestMAC for the next read, although only used in zone transfers.
		, .tsigRequestMAC,  = TsigGenerateWithProvider(, .tsigProvider(), .tsigRequestMAC, false)
	} else {
		,  = .Pack()
	}
	if  != nil {
		return 
	}
	_,  = .Write()
	return 
}

// Write implements the net.Conn Write method.
func ( *Conn) ( []byte) (int, error) {
	if len() > MaxMsgSize {
		return 0, &Error{err: "message too large"}
	}

	if isPacketConn(.Conn) {
		return .Conn.Write()
	}

	 := make([]byte, 2+len())
	binary.BigEndian.PutUint16(, uint16(len()))
	copy([2:], )
	return .Conn.Write()
}

// Return the appropriate timeout for a specific request
func ( *Client) ( time.Duration) time.Duration {
	var  time.Duration
	if .Timeout != 0 {
		 = .Timeout
	} else {
		 = 
	}
	// net.Dialer.Timeout has priority if smaller than the timeouts computed so
	// far
	if .Dialer != nil && .Dialer.Timeout != 0 {
		if .Dialer.Timeout <  {
			 = .Dialer.Timeout
		}
	}
	return 
}

// Dial connects to the address on the named network.
func (,  string) ( *Conn,  error) {
	 = new(Conn)
	.Conn,  = net.Dial(, )
	if  != nil {
		return nil, 
	}
	return , nil
}

// ExchangeContext performs a synchronous UDP query, like Exchange. It
// additionally obeys deadlines from the passed Context.
func ( context.Context,  *Msg,  string) ( *Msg,  error) {
	 := Client{Net: "udp"}
	, _,  = .ExchangeContext(, , )
	// ignoring rtt to leave the original ExchangeContext API unchanged, but
	// this function will go away
	return , 
}

// 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.
// Deprecated: 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 ( net.Conn,  *Msg) ( *Msg,  error) {
	println("dns: ExchangeConn: this function is deprecated")
	 := new(Conn)
	.Conn = 
	if  = .WriteMsg();  != nil {
		return nil, 
	}
	,  = .ReadMsg()
	if  == nil && .Id != .Id {
		 = ErrId
	}
	return , 
}

// DialTimeout acts like Dial but takes a timeout.
func (,  string,  time.Duration) ( *Conn,  error) {
	 := Client{Net: , Dialer: &net.Dialer{Timeout: }}
	return .Dial()
}

// DialWithTLS connects to the address on the named network with TLS.
func (,  string,  *tls.Config) ( *Conn,  error) {
	if !strings.HasSuffix(, "-tls") {
		 += "-tls"
	}
	 := Client{Net: , TLSConfig: }
	return .Dial()
}

// DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.
func (,  string,  *tls.Config,  time.Duration) ( *Conn,  error) {
	if !strings.HasSuffix(, "-tls") {
		 += "-tls"
	}
	 := Client{Net: , Dialer: &net.Dialer{Timeout: }, TLSConfig: }
	return .Dial()
}

// 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 ( *Client) ( context.Context,  *Msg,  string) ( *Msg,  time.Duration,  error) {
	,  := .DialContext(, )
	if  != nil {
		return nil, 0, 
	}
	defer .Close()

	return .ExchangeWithConnContext(, , )
}