...

Package dns

import "github.com/miekg/dns"
Overview
Index
Examples
Subdirectories

Overview ▾

Package dns implements a full featured interface to the Domain Name System. Both server- and client-side programming is supported. The package allows complete control over what is sent out to the DNS. The API follows the less-is-more principle, by presenting a small, clean interface.

It supports (asynchronous) querying/replying, incoming/outgoing zone transfers, TSIG, EDNS0, dynamic updates, notifies and DNSSEC validation/signing.

Note that domain names MUST be fully qualified before sending them, unqualified names in a message will result in a packing failure.

Resource records are native types. They are not stored in wire format. Basic usage pattern for creating a new resource record:

r := new(dns.MX)
r.Hdr = dns.RR_Header{Name: "miek.nl.", Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: 3600}
r.Preference = 10
r.Mx = "mx.miek.nl."

Or directly from a string:

mx, err := dns.NewRR("miek.nl. 3600 IN MX 10 mx.miek.nl.")

Or when the default origin (.) and TTL (3600) and class (IN) suit you:

mx, err := dns.NewRR("miek.nl MX 10 mx.miek.nl")

Or even:

mx, err := dns.NewRR("$ORIGIN nl.\nmiek 1H IN MX 10 mx.miek")

In the DNS messages are exchanged, these messages contain resource records (sets). Use pattern for creating a message:

m := new(dns.Msg)
m.SetQuestion("miek.nl.", dns.TypeMX)

Or when not certain if the domain name is fully qualified:

m.SetQuestion(dns.Fqdn("miek.nl"), dns.TypeMX)

The message m is now a message with the question section set to ask the MX records for the miek.nl. zone.

The following is slightly more verbose, but more flexible:

m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{"miek.nl.", dns.TypeMX, dns.ClassINET}

After creating a message it can be sent. Basic use pattern for synchronous querying the DNS at a server configured on 127.0.0.1 and port 53:

c := new(dns.Client)
in, rtt, err := c.Exchange(m1, "127.0.0.1:53")

Suppressing multiple outstanding queries (with the same question, type and class) is as easy as setting:

c.SingleInflight = true

More advanced options are available using a net.Dialer and the corresponding API. For example it is possible to set a timeout, or to specify a source IP address and port to use for the connection:

c := new(dns.Client)
laddr := net.UDPAddr{
	IP: net.ParseIP("[::1]"),
	Port: 12345,
	Zone: "",
}
c.Dialer = &net.Dialer{
	Timeout: 200 * time.Millisecond,
	LocalAddr: &laddr,
}
in, rtt, err := c.Exchange(m1, "8.8.8.8:53")

If these "advanced" features are not needed, a simple UDP query can be sent, with:

in, err := dns.Exchange(m1, "127.0.0.1:53")

When this functions returns you will get DNS message. A DNS message consists out of four sections. The question section: in.Question, the answer section: in.Answer, the authority section: in.Ns and the additional section: in.Extra.

Each of these sections (except the Question section) contain a []RR. Basic use pattern for accessing the rdata of a TXT RR as the first RR in the Answer section:

if t, ok := in.Answer[0].(*dns.TXT); ok {
	// do something with t.Txt
}

Domain Name and TXT Character String Representations

Both domain names and TXT character strings are converted to presentation form both when unpacked and when converted to strings.

For TXT character strings, tabs, carriage returns and line feeds will be converted to \t, \r and \n respectively. Back slashes and quotations marks will be escaped. Bytes below 32 and above 127 will be converted to \DDD form.

For domain names, in addition to the above rules brackets, periods, spaces, semicolons and the at symbol are escaped.

DNSSEC

DNSSEC (DNS Security Extension) adds a layer of security to the DNS. It uses public key cryptography to sign resource records. The public keys are stored in DNSKEY records and the signatures in RRSIG records.

Requesting DNSSEC information for a zone is done by adding the DO (DNSSEC OK) bit to a request.

m := new(dns.Msg)
m.SetEdns0(4096, true)

Signature generation, signature verification and key generation are all supported.

DYNAMIC UPDATES

Dynamic updates reuses the DNS message format, but renames three of the sections. Question is Zone, Answer is Prerequisite, Authority is Update, only the Additional is not renamed. See RFC 2136 for the gory details.

You can set a rather complex set of rules for the existence of absence of certain resource records or names in a zone to specify if resource records should be added or removed. The table from RFC 2136 supplemented with the Go DNS function shows which functions exist to specify the prerequisites.

3.2.4 - Table Of Metavalues Used In Prerequisite Section

 CLASS    TYPE     RDATA    Meaning                    Function
 --------------------------------------------------------------
 ANY      ANY      empty    Name is in use             dns.NameUsed
 ANY      rrset    empty    RRset exists (value indep) dns.RRsetUsed
 NONE     ANY      empty    Name is not in use         dns.NameNotUsed
 NONE     rrset    empty    RRset does not exist       dns.RRsetNotUsed
 zone     rrset    rr       RRset exists (value dep)   dns.Used

The prerequisite section can also be left empty. If you have decided on the prerequisites you can tell what RRs should be added or deleted. The next table shows the options you have and what functions to call.

3.4.2.6 - Table Of Metavalues Used In Update Section

 CLASS    TYPE     RDATA    Meaning                     Function
 ---------------------------------------------------------------
 ANY      ANY      empty    Delete all RRsets from name dns.RemoveName
 ANY      rrset    empty    Delete an RRset             dns.RemoveRRset
 NONE     rrset    rr       Delete an RR from RRset     dns.Remove
 zone     rrset    rr       Add to an RRset             dns.Insert

TRANSACTION SIGNATURE

An TSIG or transaction signature adds a HMAC TSIG record to each message sent. The supported algorithms include: HmacSHA1, HmacSHA256 and HmacSHA512.

Basic use pattern when querying with a TSIG name "axfr." (note that these key names must be fully qualified - as they are domain names) and the base64 secret "so6ZGir4GPAqINNh9U5c3A==":

If an incoming message contains a TSIG record it MUST be the last record in the additional section (RFC2845 3.2). This means that you should make the call to SetTsig last, right before executing the query. If you make any changes to the RRset after calling SetTsig() the signature will be incorrect.

c := new(dns.Client)
c.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
m := new(dns.Msg)
m.SetQuestion("miek.nl.", dns.TypeMX)
m.SetTsig("axfr.", dns.HmacSHA256, 300, time.Now().Unix())
...
// When sending the TSIG RR is calculated and filled in before sending

When requesting an zone transfer (almost all TSIG usage is when requesting zone transfers), with TSIG, this is the basic use pattern. In this example we request an AXFR for miek.nl. with TSIG key named "axfr." and secret "so6ZGir4GPAqINNh9U5c3A==" and using the server 176.58.119.54:

t := new(dns.Transfer)
m := new(dns.Msg)
t.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
m.SetAxfr("miek.nl.")
m.SetTsig("axfr.", dns.HmacSHA256, 300, time.Now().Unix())
c, err := t.In(m, "176.58.119.54:53")
for r := range c { ... }

You can now read the records from the transfer as they come in. Each envelope is checked with TSIG. If something is not correct an error is returned.

A custom TSIG implementation can be used. This requires additional code to perform any session establishment and signature generation/verification. The client must be configured with an implementation of the TsigProvider interface:

type Provider struct{}

func (*Provider) Generate(msg []byte, tsig *dns.TSIG) ([]byte, error) {
	// Use tsig.Hdr.Name and tsig.Algorithm in your code to
	// generate the MAC using msg as the payload.
}

func (*Provider) Verify(msg []byte, tsig *dns.TSIG) error {
	// Use tsig.Hdr.Name and tsig.Algorithm in your code to verify
	// that msg matches the value in tsig.MAC.
}

c := new(dns.Client)
c.TsigProvider = new(Provider)
m := new(dns.Msg)
m.SetQuestion("miek.nl.", dns.TypeMX)
m.SetTsig(keyname, dns.HmacSHA256, 300, time.Now().Unix())
...
// TSIG RR is calculated by calling your Generate method

Basic use pattern validating and replying to a message that has TSIG set.

server := &dns.Server{Addr: ":53", Net: "udp"}
server.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
go server.ListenAndServe()
dns.HandleFunc(".", handleRequest)

func handleRequest(w dns.ResponseWriter, r *dns.Msg) {
	m := new(dns.Msg)
	m.SetReply(r)
	if r.IsTsig() != nil {
		if w.TsigStatus() == nil {
			// *Msg r has an TSIG record and it was validated
			m.SetTsig("axfr.", dns.HmacSHA256, 300, time.Now().Unix())
		} else {
			// *Msg r has an TSIG records and it was not validated
		}
	}
	w.WriteMsg(m)
}

PRIVATE RRS

RFC 6895 sets aside a range of type codes for private use. This range is 65,280 - 65,534 (0xFF00 - 0xFFFE). When experimenting with new Resource Records these can be used, before requesting an official type code from IANA.

See https://miek.nl/2014/september/21/idn-and-private-rr-in-go-dns/ for more information.

EDNS0

EDNS0 is an extension mechanism for the DNS defined in RFC 2671 and updated by RFC 6891. It defines a new RR type, the OPT RR, which is then completely abused.

Basic use pattern for creating an (empty) OPT RR:

o := new(dns.OPT)
o.Hdr.Name = "." // MUST be the root zone, per definition.
o.Hdr.Rrtype = dns.TypeOPT

The rdata of an OPT RR consists out of a slice of EDNS0 (RFC 6891) interfaces. Currently only a few have been standardized: EDNS0_NSID (RFC 5001) and EDNS0_SUBNET (RFC 7871). Note that these options may be combined in an OPT RR. Basic use pattern for a server to check if (and which) options are set:

// o is a dns.OPT
for _, s := range o.Option {
	switch e := s.(type) {
	case *dns.EDNS0_NSID:
		// do stuff with e.Nsid
	case *dns.EDNS0_SUBNET:
		// access e.Family, e.Address, etc.
	}
}

SIG(0)

From RFC 2931:

SIG(0) provides protection for DNS transactions and requests ....
... protection for glue records, DNS requests, protection for message headers
on requests and responses, and protection of the overall integrity of a response.

It works like TSIG, except that SIG(0) uses public key cryptography, instead of the shared secret approach in TSIG. Supported algorithms: ECDSAP256SHA256, ECDSAP384SHA384, RSASHA1, RSASHA256 and RSASHA512.

Signing subsequent messages in multi-message sessions is not implemented.

Index ▾

Constants
Variables
func ActivateAndServe(l net.Listener, p net.PacketConn, handler Handler) error
func CanonicalName(s string) string
func CertificateToDANE(selector, matchingType uint8, cert *x509.Certificate) (string, error)
func CompareDomainName(s1, s2 string) (n int)
func CountLabel(s string) (labels int)
func Field(r RR, i int) string
func Fqdn(s string) string
func Handle(pattern string, handler Handler)
func HandleFailed(w ResponseWriter, r *Msg)
func HandleFunc(pattern string, handler func(ResponseWriter, *Msg))
func HandleRemove(pattern string)
func HashName(label string, ha uint8, iter uint16, salt string) string
func IsDomainName(s string) (labels int, ok bool)
func IsDuplicate(r1, r2 RR) bool
func IsFqdn(s string) bool
func IsMsg(buf []byte) error
func IsRRset(rrset []RR) bool
func IsSubDomain(parent, child string) bool
func Len(r RR) int
func ListenAndServe(addr string, network string, handler Handler) error
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
func NextLabel(s string, offset int) (i int, end bool)
func NumField(r RR) int
func PackDomainName(s string, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error)
func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error)
func PrevLabel(s string, n int) (i int, start bool)
func PrivateHandle(rtypestr string, rtype uint16, generator func() PrivateRdata)
func PrivateHandleRemove(rtype uint16)
func ReverseAddr(addr string) (arpa string, err error)
func SMIMEAName(email, domain string) (string, error)
func Split(s string) []int
func SplitDomainName(s string) (labels []string)
func StringToTime(s string) (uint32, error)
func TLSAName(name, service, network string) (string, error)
func TimeToString(t uint32) string
func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, string, error)
func TsigGenerateWithProvider(m *Msg, provider TsigProvider, requestMAC string, timersOnly bool) ([]byte, string, error)
func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error
func TsigVerifyWithProvider(msg []byte, provider TsigProvider, requestMAC string, timersOnly bool) error
func UnpackDomainName(msg []byte, off int) (string, int, error)
func WriteToSessionUDP(conn *net.UDPConn, b []byte, session *SessionUDP) (int, error)
type A
    func (rr *A) Header() *RR_Header
    func (rr *A) String() string
type AAAA
    func (rr *AAAA) Header() *RR_Header
    func (rr *AAAA) String() string
type AFSDB
    func (rr *AFSDB) Header() *RR_Header
    func (rr *AFSDB) String() string
type AMTRELAY
    func (rr *AMTRELAY) Header() *RR_Header
    func (rr *AMTRELAY) String() string
type ANY
    func (rr *ANY) Header() *RR_Header
    func (rr *ANY) String() string
type APL
    func (rr *APL) Header() *RR_Header
    func (rr *APL) String() string
type APLPrefix
type AVC
    func (rr *AVC) Header() *RR_Header
    func (rr *AVC) String() string
type CAA
    func (rr *CAA) Header() *RR_Header
    func (rr *CAA) String() string
type CDNSKEY
    func (rr *CDNSKEY) Header() *RR_Header
type CDS
    func (rr *CDS) Header() *RR_Header
type CERT
    func (rr *CERT) Header() *RR_Header
    func (rr *CERT) String() string
type CNAME
    func (rr *CNAME) Header() *RR_Header
    func (rr *CNAME) String() string
type CSYNC
    func (rr *CSYNC) Header() *RR_Header
    func (rr *CSYNC) String() string
type Class
    func (c Class) String() string
type Client
    func (c *Client) Dial(address string) (conn *Conn, err error)
    func (c *Client) DialContext(ctx context.Context, address string) (conn *Conn, err error)
    func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error)
    func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error)
    func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error)
    func (c *Client) ExchangeWithConnContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error)
type ClientConfig
    func ClientConfigFromFile(resolvconf string) (*ClientConfig, error)
    func ClientConfigFromReader(resolvconf io.Reader) (*ClientConfig, error)
    func (c *ClientConfig) NameList(name string) []string
type Conn
    func Dial(network, address string) (conn *Conn, err error)
    func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error)
    func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error)
    func DialWithTLS(network, address string, tlsConfig *tls.Config) (conn *Conn, err error)
    func (co *Conn) Read(p []byte) (n int, err error)
    func (co *Conn) ReadMsg() (*Msg, error)
    func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error)
    func (co *Conn) Write(p []byte) (int, error)
    func (co *Conn) WriteMsg(m *Msg) (err error)
type ConnectionStater
type DHCID
    func (rr *DHCID) Header() *RR_Header
    func (rr *DHCID) String() string
type DLV
    func (rr *DLV) Header() *RR_Header
type DNAME
    func (rr *DNAME) Header() *RR_Header
    func (rr *DNAME) String() string
type DNSKEY
    func (k *DNSKEY) Generate(bits int) (crypto.PrivateKey, error)
    func (rr *DNSKEY) Header() *RR_Header
    func (k *DNSKEY) KeyTag() uint16
    func (k *DNSKEY) NewPrivateKey(s string) (crypto.PrivateKey, error)
    func (r *DNSKEY) PrivateKeyString(p crypto.PrivateKey) string
    func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, error)
    func (rr *DNSKEY) String() string
    func (k *DNSKEY) ToCDNSKEY() *CDNSKEY
    func (k *DNSKEY) ToDS(h uint8) *DS
type DS
    func (rr *DS) Header() *RR_Header
    func (rr *DS) String() string
    func (d *DS) ToCDS() *CDS
type DecorateReader
type DecorateWriter
type EDNS0
type EDNS0_COOKIE
    func (e *EDNS0_COOKIE) Option() uint16
    func (e *EDNS0_COOKIE) String() string
type EDNS0_DAU
    func (e *EDNS0_DAU) Option() uint16
    func (e *EDNS0_DAU) String() string
type EDNS0_DHU
    func (e *EDNS0_DHU) Option() uint16
    func (e *EDNS0_DHU) String() string
type EDNS0_EDE
    func (e *EDNS0_EDE) Option() uint16
    func (e *EDNS0_EDE) String() string
type EDNS0_ESU
    func (e *EDNS0_ESU) Option() uint16
    func (e *EDNS0_ESU) String() string
type EDNS0_EXPIRE
    func (e *EDNS0_EXPIRE) Option() uint16
    func (e *EDNS0_EXPIRE) String() (s string)
type EDNS0_LLQ
    func (e *EDNS0_LLQ) Option() uint16
    func (e *EDNS0_LLQ) String() string
type EDNS0_LOCAL
    func (e *EDNS0_LOCAL) Option() uint16
    func (e *EDNS0_LOCAL) String() string
type EDNS0_N3U
    func (e *EDNS0_N3U) Option() uint16
    func (e *EDNS0_N3U) String() string
type EDNS0_NSID
    func (e *EDNS0_NSID) Option() uint16
    func (e *EDNS0_NSID) String() string
type EDNS0_PADDING
    func (e *EDNS0_PADDING) Option() uint16
    func (e *EDNS0_PADDING) String() string
type EDNS0_SUBNET
    func (e *EDNS0_SUBNET) Option() uint16
    func (e *EDNS0_SUBNET) String() (s string)
type EDNS0_TCP_KEEPALIVE
    func (e *EDNS0_TCP_KEEPALIVE) Option() uint16
    func (e *EDNS0_TCP_KEEPALIVE) String() string
type EDNS0_UL
    func (e *EDNS0_UL) Option() uint16
    func (e *EDNS0_UL) String() string
type EID
    func (rr *EID) Header() *RR_Header
    func (rr *EID) String() string
type EUI48
    func (rr *EUI48) Header() *RR_Header
    func (rr *EUI48) String() string
type EUI64
    func (rr *EUI64) Header() *RR_Header
    func (rr *EUI64) String() string
type Envelope
type Error
    func (e *Error) Error() string
type GID
    func (rr *GID) Header() *RR_Header
    func (rr *GID) String() string
type GPOS
    func (rr *GPOS) Header() *RR_Header
    func (rr *GPOS) String() string
type HINFO
    func (rr *HINFO) Header() *RR_Header
    func (rr *HINFO) String() string
type HIP
    func (rr *HIP) Header() *RR_Header
    func (rr *HIP) String() string
type HTTPS
    func (rr *HTTPS) Header() *RR_Header
    func (rr *HTTPS) String() string
type Handler
type HandlerFunc
    func (f HandlerFunc) ServeDNS(w ResponseWriter, r *Msg)
type Header
type IPSECKEY
    func (rr *IPSECKEY) Header() *RR_Header
    func (rr *IPSECKEY) String() string
type KEY
    func (rr *KEY) Header() *RR_Header
type KX
    func (rr *KX) Header() *RR_Header
    func (rr *KX) String() string
type L32
    func (rr *L32) Header() *RR_Header
    func (rr *L32) String() string
type L64
    func (rr *L64) Header() *RR_Header
    func (rr *L64) String() string
type LOC
    func (rr *LOC) Header() *RR_Header
    func (rr *LOC) String() string
type LP
    func (rr *LP) Header() *RR_Header
    func (rr *LP) String() string
type MB
    func (rr *MB) Header() *RR_Header
    func (rr *MB) String() string
type MD
    func (rr *MD) Header() *RR_Header
    func (rr *MD) String() string
type MF
    func (rr *MF) Header() *RR_Header
    func (rr *MF) String() string
type MG
    func (rr *MG) Header() *RR_Header
    func (rr *MG) String() string
type MINFO
    func (rr *MINFO) Header() *RR_Header
    func (rr *MINFO) String() string
type MR
    func (rr *MR) Header() *RR_Header
    func (rr *MR) String() string
type MX
    func (rr *MX) Header() *RR_Header
    func (rr *MX) String() string
type Msg
    func Exchange(m *Msg, a string) (r *Msg, err error)
    func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error)
    func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error)
    func (dns *Msg) Copy() *Msg
    func (dns *Msg) CopyTo(r1 *Msg) *Msg
    func (u *Msg) Insert(rr []RR)
    func (dns *Msg) IsEdns0() *OPT
    func (dns *Msg) IsTsig() *TSIG
    func (dns *Msg) Len() int
    func (u *Msg) NameNotUsed(rr []RR)
    func (u *Msg) NameUsed(rr []RR)
    func (dns *Msg) Pack() (msg []byte, err error)
    func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error)
    func (u *Msg) RRsetNotUsed(rr []RR)
    func (u *Msg) RRsetUsed(rr []RR)
    func (u *Msg) Remove(rr []RR)
    func (u *Msg) RemoveName(rr []RR)
    func (u *Msg) RemoveRRset(rr []RR)
    func (dns *Msg) SetAxfr(z string) *Msg
    func (dns *Msg) SetEdns0(udpsize uint16, do bool) *Msg
    func (dns *Msg) SetIxfr(z string, serial uint32, ns, mbox string) *Msg
    func (dns *Msg) SetNotify(z string) *Msg
    func (dns *Msg) SetQuestion(z string, t uint16) *Msg
    func (dns *Msg) SetRcode(request *Msg, rcode int) *Msg
    func (dns *Msg) SetRcodeFormatError(request *Msg) *Msg
    func (dns *Msg) SetReply(request *Msg) *Msg
    func (dns *Msg) SetTsig(z, algo string, fudge uint16, timesigned int64) *Msg
    func (dns *Msg) SetUpdate(z string) *Msg
    func (dns *Msg) String() string
    func (dns *Msg) Truncate(size int)
    func (dns *Msg) Unpack(msg []byte) (err error)
    func (u *Msg) Used(rr []RR)
type MsgAcceptAction
type MsgAcceptFunc
type MsgHdr
    func (h *MsgHdr) String() string
type NAPTR
    func (rr *NAPTR) Header() *RR_Header
    func (rr *NAPTR) String() string
type NID
    func (rr *NID) Header() *RR_Header
    func (rr *NID) String() string
type NIMLOC
    func (rr *NIMLOC) Header() *RR_Header
    func (rr *NIMLOC) String() string
type NINFO
    func (rr *NINFO) Header() *RR_Header
    func (rr *NINFO) String() string
type NS
    func (rr *NS) Header() *RR_Header
    func (rr *NS) String() string
type NSAPPTR
    func (rr *NSAPPTR) Header() *RR_Header
    func (rr *NSAPPTR) String() string
type NSEC
    func (rr *NSEC) Header() *RR_Header
    func (rr *NSEC) String() string
type NSEC3
    func (rr *NSEC3) Cover(name string) bool
    func (rr *NSEC3) Header() *RR_Header
    func (rr *NSEC3) Match(name string) bool
    func (rr *NSEC3) String() string
type NSEC3PARAM
    func (rr *NSEC3PARAM) Header() *RR_Header
    func (rr *NSEC3PARAM) String() string
type NULL
    func (rr *NULL) Header() *RR_Header
    func (rr *NULL) String() string
type Name
    func (n Name) String() string
type OPENPGPKEY
    func (rr *OPENPGPKEY) Header() *RR_Header
    func (rr *OPENPGPKEY) String() string
type OPT
    func (rr *OPT) Do() bool
    func (rr *OPT) ExtendedRcode() int
    func (rr *OPT) Header() *RR_Header
    func (rr *OPT) SetDo(do ...bool)
    func (rr *OPT) SetExtendedRcode(v uint16)
    func (rr *OPT) SetUDPSize(size uint16)
    func (rr *OPT) SetVersion(v uint8)
    func (rr *OPT) SetZ(z uint16)
    func (rr *OPT) String() string
    func (rr *OPT) UDPSize() uint16
    func (rr *OPT) Version() uint8
    func (rr *OPT) Z() uint16
type PTR
    func (rr *PTR) Header() *RR_Header
    func (rr *PTR) String() string
type PX
    func (rr *PX) Header() *RR_Header
    func (rr *PX) String() string
type PacketConnReader
type ParseError
    func (e *ParseError) Error() (s string)
type PrivateRR
    func (r *PrivateRR) Header() *RR_Header
    func (r *PrivateRR) String() string
type PrivateRdata
type Question
    func (q *Question) String() (s string)
type RFC3597
    func (rr *RFC3597) Header() *RR_Header
    func (rr *RFC3597) String() string
    func (rr *RFC3597) ToRFC3597(r RR) error
type RKEY
    func (rr *RKEY) Header() *RR_Header
    func (rr *RKEY) String() string
type RP
    func (rr *RP) Header() *RR_Header
    func (rr *RP) String() string
type RR
    func Copy(r RR) RR
    func Dedup(rrs []RR, m map[string]RR) []RR
    func NewRR(s string) (RR, error)
    func ReadRR(r io.Reader, file string) (RR, error)
    func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error)
    func UnpackRRWithHeader(h RR_Header, msg []byte, off int) (rr RR, off1 int, err error)
type RRSIG
    func (rr *RRSIG) Header() *RR_Header
    func (rr *RRSIG) Sign(k crypto.Signer, rrset []RR) error
    func (rr *RRSIG) String() string
    func (rr *RRSIG) ValidityPeriod(t time.Time) bool
    func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error
type RR_Header
    func (h *RR_Header) Header() *RR_Header
    func (h *RR_Header) String() string
type RT
    func (rr *RT) Header() *RR_Header
    func (rr *RT) String() string
type Reader
type ResponseWriter
type SIG
    func (rr *SIG) Header() *RR_Header
    func (rr *SIG) Sign(k crypto.Signer, m *Msg) ([]byte, error)
    func (rr *SIG) Verify(k *KEY, buf []byte) error
type SMIMEA
    func (rr *SMIMEA) Header() *RR_Header
    func (r *SMIMEA) Sign(usage, selector, matchingType int, cert *x509.Certificate) (err error)
    func (rr *SMIMEA) String() string
    func (r *SMIMEA) Verify(cert *x509.Certificate) error
type SOA
    func (rr *SOA) Header() *RR_Header
    func (rr *SOA) String() string
type SPF
    func (rr *SPF) Header() *RR_Header
    func (rr *SPF) String() string
type SRV
    func (rr *SRV) Header() *RR_Header
    func (rr *SRV) String() string
type SSHFP
    func (rr *SSHFP) Header() *RR_Header
    func (rr *SSHFP) String() string
type SVCB
    func (rr *SVCB) Header() *RR_Header
    func (rr *SVCB) String() string
type SVCBAlpn
    func (*SVCBAlpn) Key() SVCBKey
    func (s *SVCBAlpn) String() string
type SVCBDoHPath
    func (*SVCBDoHPath) Key() SVCBKey
    func (s *SVCBDoHPath) String() string
type SVCBECHConfig
    func (*SVCBECHConfig) Key() SVCBKey
    func (s *SVCBECHConfig) String() string
type SVCBIPv4Hint
    func (*SVCBIPv4Hint) Key() SVCBKey
    func (s *SVCBIPv4Hint) String() string
type SVCBIPv6Hint
    func (*SVCBIPv6Hint) Key() SVCBKey
    func (s *SVCBIPv6Hint) String() string
type SVCBKey
    func (key SVCBKey) String() string
type SVCBKeyValue
type SVCBLocal
    func (s *SVCBLocal) Key() SVCBKey
    func (s *SVCBLocal) String() string
type SVCBMandatory
    func (*SVCBMandatory) Key() SVCBKey
    func (s *SVCBMandatory) String() string
type SVCBNoDefaultAlpn
    func (*SVCBNoDefaultAlpn) Key() SVCBKey
    func (*SVCBNoDefaultAlpn) String() string
type SVCBPort
    func (*SVCBPort) Key() SVCBKey
    func (s *SVCBPort) String() string
type ServeMux
    func NewServeMux() *ServeMux
    func (mux *ServeMux) Handle(pattern string, handler Handler)
    func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Msg))
    func (mux *ServeMux) HandleRemove(pattern string)
    func (mux *ServeMux) ServeDNS(w ResponseWriter, req *Msg)
type Server
    func (srv *Server) ActivateAndServe() error
    func (srv *Server) ListenAndServe() error
    func (srv *Server) Shutdown() error
    func (srv *Server) ShutdownContext(ctx context.Context) error
type SessionUDP
    func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error)
    func (s *SessionUDP) RemoteAddr() net.Addr
type TA
    func (rr *TA) Header() *RR_Header
    func (rr *TA) String() string
type TALINK
    func (rr *TALINK) Header() *RR_Header
    func (rr *TALINK) String() string
type TKEY
    func (rr *TKEY) Header() *RR_Header
    func (rr *TKEY) String() string
type TLSA
    func (rr *TLSA) Header() *RR_Header
    func (r *TLSA) Sign(usage, selector, matchingType int, cert *x509.Certificate) (err error)
    func (rr *TLSA) String() string
    func (r *TLSA) Verify(cert *x509.Certificate) error
type TSIG
    func (rr *TSIG) Header() *RR_Header
    func (rr *TSIG) String() string
type TXT
    func (rr *TXT) Header() *RR_Header
    func (rr *TXT) String() string
type Transfer
    func (t *Transfer) In(q *Msg, a string) (env chan *Envelope, err error)
    func (t *Transfer) Out(w ResponseWriter, q *Msg, ch chan *Envelope) error
    func (t *Transfer) ReadMsg() (*Msg, error)
    func (t *Transfer) WriteMsg(m *Msg) (err error)
type TsigProvider
type Type
    func (t Type) String() string
type UID
    func (rr *UID) Header() *RR_Header
    func (rr *UID) String() string
type UINFO
    func (rr *UINFO) Header() *RR_Header
    func (rr *UINFO) String() string
type URI
    func (rr *URI) Header() *RR_Header
    func (rr *URI) String() string
type Writer
type X25
    func (rr *X25) Header() *RR_Header
    func (rr *X25) String() string
type ZONEMD
    func (rr *ZONEMD) Header() *RR_Header
    func (rr *ZONEMD) String() string
type ZoneParser
    func NewZoneParser(r io.Reader, origin, file string) *ZoneParser
    func (zp *ZoneParser) Comment() string
    func (zp *ZoneParser) Err() error
    func (zp *ZoneParser) Next() (RR, bool)
    func (zp *ZoneParser) SetDefaultTTL(ttl uint32)
    func (zp *ZoneParser) SetIncludeAllowed(v bool)

Examples

DS
DecorateWriter
MX
PrivateHandle

Package files

acceptfunc.go client.go clientconfig.go dane.go defaults.go dns.go dnssec.go dnssec_keygen.go dnssec_keyscan.go dnssec_privkey.go doc.go duplicate.go edns.go format.go generate.go hash.go labels.go listen_reuseport.go msg.go msg_helpers.go msg_truncate.go nsecx.go privaterr.go reverse.go sanitize.go scan.go scan_rr.go serve_mux.go server.go sig0.go smimea.go svcb.go tlsa.go tsig.go types.go udp.go update.go version.go xfr.go zduplicate.go zmsg.go ztypes.go

Constants

const (

    // DefaultMsgSize is the standard default for messages larger than 512 bytes.
    DefaultMsgSize = 4096
    // MinMsgSize is the minimal size of a DNS packet.
    MinMsgSize = 512
    // MaxMsgSize is the largest possible DNS packet.
    MaxMsgSize = 65535
)

DNSSEC encryption algorithm codes.

const (
    RSAMD5 uint8
    DH
    DSA

    RSASHA1
    DSANSEC3SHA1
    RSASHA1NSEC3SHA1
    RSASHA256

    RSASHA512

    ECCGOST
    ECDSAP256SHA256
    ECDSAP384SHA384
    ED25519
    ED448
    INDIRECT   uint8 = 252
    PRIVATEDNS uint8 = 253 // Private (experimental keys)
    PRIVATEOID uint8 = 254
)

DNSSEC hashing algorithm codes.

const (
    SHA1   uint8 // RFC 4034
    SHA256       // RFC 4509
    GOST94       // RFC 5933
    SHA384       // Experimental
    SHA512       // Experimental
)

DNSKEY flag values.

const (
    SEP    = 1
    REVOKE = 1 << 7
    ZONE   = 1 << 8
)

EDNS0 Option codes.

const (
    EDNS0LLQ          = 0x1    // long lived queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01
    EDNS0UL           = 0x2    // update lease draft: http://files.dns-sd.org/draft-sekar-dns-ul.txt
    EDNS0NSID         = 0x3    // nsid (See RFC 5001)
    EDNS0ESU          = 0x4    // ENUM Source-URI draft: https://datatracker.ietf.org/doc/html/draft-kaplan-enum-source-uri-00
    EDNS0DAU          = 0x5    // DNSSEC Algorithm Understood
    EDNS0DHU          = 0x6    // DS Hash Understood
    EDNS0N3U          = 0x7    // NSEC3 Hash Understood
    EDNS0SUBNET       = 0x8    // client-subnet (See RFC 7871)
    EDNS0EXPIRE       = 0x9    // EDNS0 expire
    EDNS0COOKIE       = 0xa    // EDNS0 Cookie
    EDNS0TCPKEEPALIVE = 0xb    // EDNS0 tcp keep alive (See RFC 7828)
    EDNS0PADDING      = 0xc    // EDNS0 padding (See RFC 7830)
    EDNS0EDE          = 0xf    // EDNS0 extended DNS errors (See RFC 8914)
    EDNS0LOCALSTART   = 0xFDE9 // Beginning of range reserved for local/experimental use (See RFC 6891)
    EDNS0LOCALEND     = 0xFFFE // End of range reserved for local/experimental use (See RFC 6891)

)

Extended DNS Error Codes (RFC 8914).

const (
    ExtendedErrorCodeOther uint16 = iota
    ExtendedErrorCodeUnsupportedDNSKEYAlgorithm
    ExtendedErrorCodeUnsupportedDSDigestType
    ExtendedErrorCodeStaleAnswer
    ExtendedErrorCodeForgedAnswer
    ExtendedErrorCodeDNSSECIndeterminate
    ExtendedErrorCodeDNSBogus
    ExtendedErrorCodeSignatureExpired
    ExtendedErrorCodeSignatureNotYetValid
    ExtendedErrorCodeDNSKEYMissing
    ExtendedErrorCodeRRSIGsMissing
    ExtendedErrorCodeNoZoneKeyBitSet
    ExtendedErrorCodeNSECMissing
    ExtendedErrorCodeCachedError
    ExtendedErrorCodeNotReady
    ExtendedErrorCodeBlocked
    ExtendedErrorCodeCensored
    ExtendedErrorCodeFiltered
    ExtendedErrorCodeProhibited
    ExtendedErrorCodeStaleNXDOMAINAnswer
    ExtendedErrorCodeNotAuthoritative
    ExtendedErrorCodeNotSupported
    ExtendedErrorCodeNoReachableAuthority
    ExtendedErrorCodeNetworkError
    ExtendedErrorCodeInvalidData
)

HMAC hashing codes. These are transmitted as domain names.

const (
    HmacSHA1   = "hmac-sha1."
    HmacSHA224 = "hmac-sha224."
    HmacSHA256 = "hmac-sha256."
    HmacSHA384 = "hmac-sha384."
    HmacSHA512 = "hmac-sha512."

    HmacMD5 = "hmac-md5.sig-alg.reg.int." // Deprecated: HmacMD5 is no longer supported.
)

Wire constants and supported types.

const (
    TypeNone       uint16 = 0
    TypeA          uint16 = 1
    TypeNS         uint16 = 2
    TypeMD         uint16 = 3
    TypeMF         uint16 = 4
    TypeCNAME      uint16 = 5
    TypeSOA        uint16 = 6
    TypeMB         uint16 = 7
    TypeMG         uint16 = 8
    TypeMR         uint16 = 9
    TypeNULL       uint16 = 10
    TypePTR        uint16 = 12
    TypeHINFO      uint16 = 13
    TypeMINFO      uint16 = 14
    TypeMX         uint16 = 15
    TypeTXT        uint16 = 16
    TypeRP         uint16 = 17
    TypeAFSDB      uint16 = 18
    TypeX25        uint16 = 19
    TypeISDN       uint16 = 20
    TypeRT         uint16 = 21
    TypeNSAPPTR    uint16 = 23
    TypeSIG        uint16 = 24
    TypeKEY        uint16 = 25
    TypePX         uint16 = 26
    TypeGPOS       uint16 = 27
    TypeAAAA       uint16 = 28
    TypeLOC        uint16 = 29
    TypeNXT        uint16 = 30
    TypeEID        uint16 = 31
    TypeNIMLOC     uint16 = 32
    TypeSRV        uint16 = 33
    TypeATMA       uint16 = 34
    TypeNAPTR      uint16 = 35
    TypeKX         uint16 = 36
    TypeCERT       uint16 = 37
    TypeDNAME      uint16 = 39
    TypeOPT        uint16 = 41 // EDNS
    TypeAPL        uint16 = 42
    TypeDS         uint16 = 43
    TypeSSHFP      uint16 = 44
    TypeIPSECKEY   uint16 = 45
    TypeRRSIG      uint16 = 46
    TypeNSEC       uint16 = 47
    TypeDNSKEY     uint16 = 48
    TypeDHCID      uint16 = 49
    TypeNSEC3      uint16 = 50
    TypeNSEC3PARAM uint16 = 51
    TypeTLSA       uint16 = 52
    TypeSMIMEA     uint16 = 53
    TypeHIP        uint16 = 55
    TypeNINFO      uint16 = 56
    TypeRKEY       uint16 = 57
    TypeTALINK     uint16 = 58
    TypeCDS        uint16 = 59
    TypeCDNSKEY    uint16 = 60
    TypeOPENPGPKEY uint16 = 61
    TypeCSYNC      uint16 = 62
    TypeZONEMD     uint16 = 63
    TypeSVCB       uint16 = 64
    TypeHTTPS      uint16 = 65
    TypeSPF        uint16 = 99
    TypeUINFO      uint16 = 100
    TypeUID        uint16 = 101
    TypeGID        uint16 = 102
    TypeUNSPEC     uint16 = 103
    TypeNID        uint16 = 104
    TypeL32        uint16 = 105
    TypeL64        uint16 = 106
    TypeLP         uint16 = 107
    TypeEUI48      uint16 = 108
    TypeEUI64      uint16 = 109
    TypeURI        uint16 = 256
    TypeCAA        uint16 = 257
    TypeAVC        uint16 = 258
    TypeAMTRELAY   uint16 = 260

    TypeTKEY uint16 = 249
    TypeTSIG uint16 = 250

    // valid Question.Qtype only
    TypeIXFR  uint16 = 251
    TypeAXFR  uint16 = 252
    TypeMAILB uint16 = 253
    TypeMAILA uint16 = 254
    TypeANY   uint16 = 255

    TypeTA       uint16 = 32768
    TypeDLV      uint16 = 32769
    TypeReserved uint16 = 65535

    // valid Question.Qclass
    ClassINET   = 1
    ClassCSNET  = 2
    ClassCHAOS  = 3
    ClassHESIOD = 4
    ClassNONE   = 254
    ClassANY    = 255

    // Message Response Codes, see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml
    RcodeSuccess        = 0  // NoError   - No Error                          [DNS]
    RcodeFormatError    = 1  // FormErr   - Format Error                      [DNS]
    RcodeServerFailure  = 2  // ServFail  - Server Failure                    [DNS]
    RcodeNameError      = 3  // NXDomain  - Non-Existent Domain               [DNS]
    RcodeNotImplemented = 4  // NotImp    - Not Implemented                   [DNS]
    RcodeRefused        = 5  // Refused   - Query Refused                     [DNS]
    RcodeYXDomain       = 6  // YXDomain  - Name Exists when it should not    [DNS Update]
    RcodeYXRrset        = 7  // YXRRSet   - RR Set Exists when it should not  [DNS Update]
    RcodeNXRrset        = 8  // NXRRSet   - RR Set that should exist does not [DNS Update]
    RcodeNotAuth        = 9  // NotAuth   - Server Not Authoritative for zone [DNS Update]
    RcodeNotZone        = 10 // NotZone   - Name not contained in zone        [DNS Update/TSIG]
    RcodeBadSig         = 16 // BADSIG    - TSIG Signature Failure            [TSIG]
    RcodeBadVers        = 16 // BADVERS   - Bad OPT Version                   [EDNS0]
    RcodeBadKey         = 17 // BADKEY    - Key not recognized                [TSIG]
    RcodeBadTime        = 18 // BADTIME   - Signature out of time window      [TSIG]
    RcodeBadMode        = 19 // BADMODE   - Bad TKEY Mode                     [TKEY]
    RcodeBadName        = 20 // BADNAME   - Duplicate key name                [TKEY]
    RcodeBadAlg         = 21 // BADALG    - Algorithm not supported           [TKEY]
    RcodeBadTrunc       = 22 // BADTRUNC  - Bad Truncation                    [TSIG]
    RcodeBadCookie      = 23 // BADCOOKIE - Bad/missing Server Cookie         [DNS Cookies]

    // Message Opcodes. There is no 3.
    OpcodeQuery  = 0
    OpcodeIQuery = 1
    OpcodeStatus = 2
    OpcodeNotify = 4
    OpcodeUpdate = 5
)

Used in ZONEMD https://tools.ietf.org/html/rfc8976

const (
    ZoneMDSchemeSimple = 1

    ZoneMDHashAlgSHA384 = 1
    ZoneMDHashAlgSHA512 = 2
)

Used in IPSEC https://datatracker.ietf.org/doc/html/rfc4025#section-2.3

const (
    IPSECGatewayNone uint8 = iota
    IPSECGatewayIPv4
    IPSECGatewayIPv6
    IPSECGatewayHost
)

Used in AMTRELAY https://datatracker.ietf.org/doc/html/rfc8777#section-4.2.3

const (
    AMTRELAYNone = IPSECGatewayNone
    AMTRELAYIPv4 = IPSECGatewayIPv4
    AMTRELAYIPv6 = IPSECGatewayIPv6
    AMTRELAYHost = IPSECGatewayHost
)

Various constants used in the LOC RR. See RFC 1876.

const (
    LOC_EQUATOR       = 1 << 31 // RFC 1876, Section 2.
    LOC_PRIMEMERIDIAN = 1 << 31 // RFC 1876, Section 2.
    LOC_HOURS         = 60 * 1000
    LOC_DEGREES       = 60 * LOC_HOURS
    LOC_ALTITUDEBASE  = 100000
)

Different Certificate Types, see RFC 4398, Section 2.1

const (
    CertPKIX = 1 + iota
    CertSPKI
    CertPGP
    CertIPIX
    CertISPKI
    CertIPGP
    CertACPKIX
    CertIACPKIX
    CertURI = 253
    CertOID = 254
)

Variables

Errors defined in this package.

var (
    ErrAlg           error = &Error{err: "bad algorithm"}                  // ErrAlg indicates an error with the (DNSSEC) algorithm.
    ErrAuth          error = &Error{err: "bad authentication"}             // ErrAuth indicates an error in the TSIG authentication.
    ErrBuf           error = &Error{err: "buffer size too small"}          // ErrBuf indicates that the buffer used is too small for the message.
    ErrConnEmpty     error = &Error{err: "conn has no connection"}         // ErrConnEmpty indicates a connection is being used before it is initialized.
    ErrExtendedRcode error = &Error{err: "bad extended rcode"}             // ErrExtendedRcode ...
    ErrFqdn          error = &Error{err: "domain must be fully qualified"} // ErrFqdn indicates that a domain name does not have a closing dot.
    ErrId            error = &Error{err: "id mismatch"}                    // ErrId indicates there is a mismatch with the message's ID.
    ErrKeyAlg        error = &Error{err: "bad key algorithm"}              // ErrKeyAlg indicates that the algorithm in the key is not valid.
    ErrKey           error = &Error{err: "bad key"}
    ErrKeySize       error = &Error{err: "bad key size"}
    ErrLongDomain    error = &Error{err: fmt.Sprintf("domain name exceeded %d wire-format octets", maxDomainNameWireOctets)}
    ErrNoSig         error = &Error{err: "no signature found"}
    ErrPrivKey       error = &Error{err: "bad private key"}
    ErrRcode         error = &Error{err: "bad rcode"}
    ErrRdata         error = &Error{err: "bad rdata"}
    ErrRRset         error = &Error{err: "bad rrset"}
    ErrSecret        error = &Error{err: "no secrets defined"}
    ErrShortRead     error = &Error{err: "short read"}
    ErrSig           error = &Error{err: "bad signature"} // ErrSig indicates that a signature can not be cryptographically validated.
    ErrSoa           error = &Error{err: "no SOA"}        // ErrSOA indicates that no SOA RR was seen when doing zone transfers.
    ErrTime          error = &Error{err: "bad time"}      // ErrTime indicates a timing error in TSIG authentication.
)

AlgorithmToHash is a map of algorithm crypto hash IDs to crypto.Hash's. For newer algorithm that do their own hashing (i.e. ED25519) the returned value is 0, implying no (external) hashing should occur. The non-exported identityHash is then used.

var AlgorithmToHash = map[uint8]crypto.Hash{
    RSAMD5:           crypto.MD5,
    DSA:              crypto.SHA1,
    RSASHA1:          crypto.SHA1,
    RSASHA1NSEC3SHA1: crypto.SHA1,
    RSASHA256:        crypto.SHA256,
    ECDSAP256SHA256:  crypto.SHA256,
    ECDSAP384SHA384:  crypto.SHA384,
    RSASHA512:        crypto.SHA512,
    ED25519:          0,
}

AlgorithmToString is a map of algorithm IDs to algorithm names.

var AlgorithmToString = map[uint8]string{
    RSAMD5:           "RSAMD5",
    DH:               "DH",
    DSA:              "DSA",
    RSASHA1:          "RSASHA1",
    DSANSEC3SHA1:     "DSA-NSEC3-SHA1",
    RSASHA1NSEC3SHA1: "RSASHA1-NSEC3-SHA1",
    RSASHA256:        "RSASHA256",
    RSASHA512:        "RSASHA512",
    ECCGOST:          "ECC-GOST",
    ECDSAP256SHA256:  "ECDSAP256SHA256",
    ECDSAP384SHA384:  "ECDSAP384SHA384",
    ED25519:          "ED25519",
    ED448:            "ED448",
    INDIRECT:         "INDIRECT",
    PRIVATEDNS:       "PRIVATEDNS",
    PRIVATEOID:       "PRIVATEOID",
}

CertTypeToString converts the Cert Type to its string representation. See RFC 4398 and RFC 6944.

var CertTypeToString = map[uint16]string{
    CertPKIX:    "PKIX",
    CertSPKI:    "SPKI",
    CertPGP:     "PGP",
    CertIPIX:    "IPIX",
    CertISPKI:   "ISPKI",
    CertIPGP:    "IPGP",
    CertACPKIX:  "ACPKIX",
    CertIACPKIX: "IACPKIX",
    CertURI:     "URI",
    CertOID:     "OID",
}

ClassToString is a maps Classes to strings for each CLASS wire type.

var ClassToString = map[uint16]string{
    ClassINET:   "IN",
    ClassCSNET:  "CS",
    ClassCHAOS:  "CH",
    ClassHESIOD: "HS",
    ClassNONE:   "NONE",
    ClassANY:    "ANY",
}

DefaultServeMux is the default ServeMux used by Serve.

var DefaultServeMux = NewServeMux()

ExtendedErrorCodeToString maps extended error info codes to a human readable description.

var ExtendedErrorCodeToString = map[uint16]string{
    ExtendedErrorCodeOther:                      "Other",
    ExtendedErrorCodeUnsupportedDNSKEYAlgorithm: "Unsupported DNSKEY Algorithm",
    ExtendedErrorCodeUnsupportedDSDigestType:    "Unsupported DS Digest Type",
    ExtendedErrorCodeStaleAnswer:                "Stale Answer",
    ExtendedErrorCodeForgedAnswer:               "Forged Answer",
    ExtendedErrorCodeDNSSECIndeterminate:        "DNSSEC Indeterminate",
    ExtendedErrorCodeDNSBogus:                   "DNSSEC Bogus",
    ExtendedErrorCodeSignatureExpired:           "Signature Expired",
    ExtendedErrorCodeSignatureNotYetValid:       "Signature Not Yet Valid",
    ExtendedErrorCodeDNSKEYMissing:              "DNSKEY Missing",
    ExtendedErrorCodeRRSIGsMissing:              "RRSIGs Missing",
    ExtendedErrorCodeNoZoneKeyBitSet:            "No Zone Key Bit Set",
    ExtendedErrorCodeNSECMissing:                "NSEC Missing",
    ExtendedErrorCodeCachedError:                "Cached Error",
    ExtendedErrorCodeNotReady:                   "Not Ready",
    ExtendedErrorCodeBlocked:                    "Blocked",
    ExtendedErrorCodeCensored:                   "Censored",
    ExtendedErrorCodeFiltered:                   "Filtered",
    ExtendedErrorCodeProhibited:                 "Prohibited",
    ExtendedErrorCodeStaleNXDOMAINAnswer:        "Stale NXDOMAIN Answer",
    ExtendedErrorCodeNotAuthoritative:           "Not Authoritative",
    ExtendedErrorCodeNotSupported:               "Not Supported",
    ExtendedErrorCodeNoReachableAuthority:       "No Reachable Authority",
    ExtendedErrorCodeNetworkError:               "Network Error",
    ExtendedErrorCodeInvalidData:                "Invalid Data",
}

HashToString is a map of hash IDs to names.

var HashToString = map[uint8]string{
    SHA1:   "SHA1",
    SHA256: "SHA256",
    GOST94: "GOST94",
    SHA384: "SHA384",
    SHA512: "SHA512",
}

Id by default returns a 16-bit random number to be used as a message id. The number is drawn from a cryptographically secure random number generator. This being a variable the function can be reassigned to a custom function. For instance, to make it return a static value for testing:

dns.Id = func() uint16 { return 3 }
var Id = id

OpcodeToString maps Opcodes to strings.

var OpcodeToString = map[int]string{
    OpcodeQuery:  "QUERY",
    OpcodeIQuery: "IQUERY",
    OpcodeStatus: "STATUS",
    OpcodeNotify: "NOTIFY",
    OpcodeUpdate: "UPDATE",
}

RcodeToString maps Rcodes to strings.

var RcodeToString = map[int]string{
    RcodeSuccess:        "NOERROR",
    RcodeFormatError:    "FORMERR",
    RcodeServerFailure:  "SERVFAIL",
    RcodeNameError:      "NXDOMAIN",
    RcodeNotImplemented: "NOTIMP",
    RcodeRefused:        "REFUSED",
    RcodeYXDomain:       "YXDOMAIN",
    RcodeYXRrset:        "YXRRSET",
    RcodeNXRrset:        "NXRRSET",
    RcodeNotAuth:        "NOTAUTH",
    RcodeNotZone:        "NOTZONE",
    RcodeBadSig:         "BADSIG",

    RcodeBadKey:    "BADKEY",
    RcodeBadTime:   "BADTIME",
    RcodeBadMode:   "BADMODE",
    RcodeBadName:   "BADNAME",
    RcodeBadAlg:    "BADALG",
    RcodeBadTrunc:  "BADTRUNC",
    RcodeBadCookie: "BADCOOKIE",
}

StringToAlgorithm is the reverse of AlgorithmToString.

var StringToAlgorithm = reverseInt8(AlgorithmToString)

StringToCertType is the reverseof CertTypeToString.

var StringToCertType = reverseInt16(CertTypeToString)

StringToClass is the reverse of ClassToString, needed for string parsing.

var StringToClass = reverseInt16(ClassToString)

StringToExtendedErrorCode is a map from human readable descriptions to extended error info codes.

var StringToExtendedErrorCode = reverseInt16(ExtendedErrorCodeToString)

StringToHash is a map of names to hash IDs.

var StringToHash = reverseInt8(HashToString)

StringToOpcode is a map of opcodes to strings.

var StringToOpcode = reverseInt(OpcodeToString)

StringToRcode is a map of rcodes to strings.

var StringToRcode = reverseInt(RcodeToString)

StringToType is the reverse of TypeToString, needed for string parsing.

var StringToType = reverseInt16(TypeToString)

TypeToRR is a map of constructors for each RR type.

var TypeToRR = map[uint16]func() RR{
    TypeA:          func() RR { return new(A) },
    TypeAAAA:       func() RR { return new(AAAA) },
    TypeAFSDB:      func() RR { return new(AFSDB) },
    TypeAMTRELAY:   func() RR { return new(AMTRELAY) },
    TypeANY:        func() RR { return new(ANY) },
    TypeAPL:        func() RR { return new(APL) },
    TypeAVC:        func() RR { return new(AVC) },
    TypeCAA:        func() RR { return new(CAA) },
    TypeCDNSKEY:    func() RR { return new(CDNSKEY) },
    TypeCDS:        func() RR { return new(CDS) },
    TypeCERT:       func() RR { return new(CERT) },
    TypeCNAME:      func() RR { return new(CNAME) },
    TypeCSYNC:      func() RR { return new(CSYNC) },
    TypeDHCID:      func() RR { return new(DHCID) },
    TypeDLV:        func() RR { return new(DLV) },
    TypeDNAME:      func() RR { return new(DNAME) },
    TypeDNSKEY:     func() RR { return new(DNSKEY) },
    TypeDS:         func() RR { return new(DS) },
    TypeEID:        func() RR { return new(EID) },
    TypeEUI48:      func() RR { return new(EUI48) },
    TypeEUI64:      func() RR { return new(EUI64) },
    TypeGID:        func() RR { return new(GID) },
    TypeGPOS:       func() RR { return new(GPOS) },
    TypeHINFO:      func() RR { return new(HINFO) },
    TypeHIP:        func() RR { return new(HIP) },
    TypeHTTPS:      func() RR { return new(HTTPS) },
    TypeIPSECKEY:   func() RR { return new(IPSECKEY) },
    TypeKEY:        func() RR { return new(KEY) },
    TypeKX:         func() RR { return new(KX) },
    TypeL32:        func() RR { return new(L32) },
    TypeL64:        func() RR { return new(L64) },
    TypeLOC:        func() RR { return new(LOC) },
    TypeLP:         func() RR { return new(LP) },
    TypeMB:         func() RR { return new(MB) },
    TypeMD:         func() RR { return new(MD) },
    TypeMF:         func() RR { return new(MF) },
    TypeMG:         func() RR { return new(MG) },
    TypeMINFO:      func() RR { return new(MINFO) },
    TypeMR:         func() RR { return new(MR) },
    TypeMX:         func() RR { return new(MX) },
    TypeNAPTR:      func() RR { return new(NAPTR) },
    TypeNID:        func() RR { return new(NID) },
    TypeNIMLOC:     func() RR { return new(NIMLOC) },
    TypeNINFO:      func() RR { return new(NINFO) },
    TypeNS:         func() RR { return new(NS) },
    TypeNSAPPTR:    func() RR { return new(NSAPPTR) },
    TypeNSEC:       func() RR { return new(NSEC) },
    TypeNSEC3:      func() RR { return new(NSEC3) },
    TypeNSEC3PARAM: func() RR { return new(NSEC3PARAM) },
    TypeNULL:       func() RR { return new(NULL) },
    TypeOPENPGPKEY: func() RR { return new(OPENPGPKEY) },
    TypeOPT:        func() RR { return new(OPT) },
    TypePTR:        func() RR { return new(PTR) },
    TypePX:         func() RR { return new(PX) },
    TypeRKEY:       func() RR { return new(RKEY) },
    TypeRP:         func() RR { return new(RP) },
    TypeRRSIG:      func() RR { return new(RRSIG) },
    TypeRT:         func() RR { return new(RT) },
    TypeSIG:        func() RR { return new(SIG) },
    TypeSMIMEA:     func() RR { return new(SMIMEA) },
    TypeSOA:        func() RR { return new(SOA) },
    TypeSPF:        func() RR { return new(SPF) },
    TypeSRV:        func() RR { return new(SRV) },
    TypeSSHFP:      func() RR { return new(SSHFP) },
    TypeSVCB:       func() RR { return new(SVCB) },
    TypeTA:         func() RR { return new(TA) },
    TypeTALINK:     func() RR { return new(TALINK) },
    TypeTKEY:       func() RR { return new(TKEY) },
    TypeTLSA:       func() RR { return new(TLSA) },
    TypeTSIG:       func() RR { return new(TSIG) },
    TypeTXT:        func() RR { return new(TXT) },
    TypeUID:        func() RR { return new(UID) },
    TypeUINFO:      func() RR { return new(UINFO) },
    TypeURI:        func() RR { return new(URI) },
    TypeX25:        func() RR { return new(X25) },
    TypeZONEMD:     func() RR { return new(ZONEMD) },
}

TypeToString is a map of strings for each RR type.

var TypeToString = map[uint16]string{
    TypeA:          "A",
    TypeAAAA:       "AAAA",
    TypeAFSDB:      "AFSDB",
    TypeAMTRELAY:   "AMTRELAY",
    TypeANY:        "ANY",
    TypeAPL:        "APL",
    TypeATMA:       "ATMA",
    TypeAVC:        "AVC",
    TypeAXFR:       "AXFR",
    TypeCAA:        "CAA",
    TypeCDNSKEY:    "CDNSKEY",
    TypeCDS:        "CDS",
    TypeCERT:       "CERT",
    TypeCNAME:      "CNAME",
    TypeCSYNC:      "CSYNC",
    TypeDHCID:      "DHCID",
    TypeDLV:        "DLV",
    TypeDNAME:      "DNAME",
    TypeDNSKEY:     "DNSKEY",
    TypeDS:         "DS",
    TypeEID:        "EID",
    TypeEUI48:      "EUI48",
    TypeEUI64:      "EUI64",
    TypeGID:        "GID",
    TypeGPOS:       "GPOS",
    TypeHINFO:      "HINFO",
    TypeHIP:        "HIP",
    TypeHTTPS:      "HTTPS",
    TypeIPSECKEY:   "IPSECKEY",
    TypeISDN:       "ISDN",
    TypeIXFR:       "IXFR",
    TypeKEY:        "KEY",
    TypeKX:         "KX",
    TypeL32:        "L32",
    TypeL64:        "L64",
    TypeLOC:        "LOC",
    TypeLP:         "LP",
    TypeMAILA:      "MAILA",
    TypeMAILB:      "MAILB",
    TypeMB:         "MB",
    TypeMD:         "MD",
    TypeMF:         "MF",
    TypeMG:         "MG",
    TypeMINFO:      "MINFO",
    TypeMR:         "MR",
    TypeMX:         "MX",
    TypeNAPTR:      "NAPTR",
    TypeNID:        "NID",
    TypeNIMLOC:     "NIMLOC",
    TypeNINFO:      "NINFO",
    TypeNS:         "NS",
    TypeNSEC:       "NSEC",
    TypeNSEC3:      "NSEC3",
    TypeNSEC3PARAM: "NSEC3PARAM",
    TypeNULL:       "NULL",
    TypeNXT:        "NXT",
    TypeNone:       "None",
    TypeOPENPGPKEY: "OPENPGPKEY",
    TypeOPT:        "OPT",
    TypePTR:        "PTR",
    TypePX:         "PX",
    TypeRKEY:       "RKEY",
    TypeRP:         "RP",
    TypeRRSIG:      "RRSIG",
    TypeRT:         "RT",
    TypeReserved:   "Reserved",
    TypeSIG:        "SIG",
    TypeSMIMEA:     "SMIMEA",
    TypeSOA:        "SOA",
    TypeSPF:        "SPF",
    TypeSRV:        "SRV",
    TypeSSHFP:      "SSHFP",
    TypeSVCB:       "SVCB",
    TypeTA:         "TA",
    TypeTALINK:     "TALINK",
    TypeTKEY:       "TKEY",
    TypeTLSA:       "TLSA",
    TypeTSIG:       "TSIG",
    TypeTXT:        "TXT",
    TypeUID:        "UID",
    TypeUINFO:      "UINFO",
    TypeUNSPEC:     "UNSPEC",
    TypeURI:        "URI",
    TypeX25:        "X25",
    TypeZONEMD:     "ZONEMD",
    TypeNSAPPTR:    "NSAP-PTR",
}

Version is current version of this library.

var Version = v{1, 1, 57}

func ActivateAndServe

func ActivateAndServe(l net.Listener, p net.PacketConn, handler Handler) error

ActivateAndServe activates a server with a listener from systemd, l and p should not both be non-nil. If both l and p are not nil only p will be used. Invoke handler for incoming queries.

func CanonicalName

func CanonicalName(s string) string

CanonicalName returns the domain name in canonical form. A name in canonical form is lowercase and fully qualified. Only US-ASCII letters are affected. See Section 6.2 in RFC 4034.

func CertificateToDANE

func CertificateToDANE(selector, matchingType uint8, cert *x509.Certificate) (string, error)

CertificateToDANE converts a certificate to a hex string as used in the TLSA or SMIMEA records.

func CompareDomainName

func CompareDomainName(s1, s2 string) (n int)

CompareDomainName compares the names s1 and s2 and returns how many labels they have in common starting from the *right*. The comparison stops at the first inequality. The names are downcased before the comparison.

www.miek.nl. and miek.nl. have two labels in common: miek and nl www.miek.nl. and www.bla.nl. have one label in common: nl

s1 and s2 must be syntactically valid domain names.

func CountLabel

func CountLabel(s string) (labels int)

CountLabel counts the number of labels in the string s. s must be a syntactically valid domain name.

func Field

func Field(r RR, i int) string

Field returns the rdata field i as a string. Fields are indexed starting from 1. RR types that holds slice data, for instance the NSEC type bitmap will return a single string where the types are concatenated using a space. Accessing non existing fields will cause a panic.

func Fqdn

func Fqdn(s string) string

Fqdn return the fully qualified domain name from s. If s is already fully qualified, it behaves as the identity function.

func Handle

func Handle(pattern string, handler Handler)

Handle registers the handler with the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func HandleFailed

func HandleFailed(w ResponseWriter, r *Msg)

HandleFailed returns a HandlerFunc that returns SERVFAIL for every request it gets. Deprecated: This function is going away.

func HandleFunc

func HandleFunc(pattern string, handler func(ResponseWriter, *Msg))

HandleFunc registers the handler function with the given pattern in the DefaultServeMux.

func HandleRemove

func HandleRemove(pattern string)

HandleRemove deregisters the handle with the given pattern in the DefaultServeMux.

func HashName

func HashName(label string, ha uint8, iter uint16, salt string) string

HashName hashes a string (label) according to RFC 5155. It returns the hashed string in uppercase.

func IsDomainName

func IsDomainName(s string) (labels int, ok bool)

IsDomainName checks if s is a valid domain name, it returns the number of labels and true, when a domain name is valid. Note that non fully qualified domain name is considered valid, in this case the last label is counted in the number of labels. When false is returned the number of labels is not defined. Also note that this function is extremely liberal; almost any string is a valid domain name as the DNS is 8 bit protocol. It checks if each label fits in 63 characters and that the entire name will fit into the 255 octet wire format limit.

func IsDuplicate

func IsDuplicate(r1, r2 RR) bool

IsDuplicate checks of r1 and r2 are duplicates of each other, excluding the TTL. So this means the header data is equal *and* the RDATA is the same. Returns true if so, otherwise false. It's a protocol violation to have identical RRs in a message.

func IsFqdn

func IsFqdn(s string) bool

IsFqdn checks if a domain name is fully qualified.

func IsMsg

func IsMsg(buf []byte) error

IsMsg sanity checks buf and returns an error if it isn't a valid DNS packet. The checking is performed on the binary payload.

func IsRRset

func IsRRset(rrset []RR) bool

IsRRset reports whether a set of RRs is a valid RRset as defined by RFC 2181. This means the RRs need to have the same type, name, and class.

func IsSubDomain

func IsSubDomain(parent, child string) bool

IsSubDomain checks if child is indeed a child of the parent. If child and parent are the same domain true is returned as well.

func Len

func Len(r RR) int

Len returns the length (in octets) of the uncompressed RR in wire format.

func ListenAndServe

func ListenAndServe(addr string, network string, handler Handler) error

ListenAndServe Starts a server on address and network specified Invoke handler for incoming queries.

func ListenAndServeTLS

func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

ListenAndServeTLS acts like http.ListenAndServeTLS, more information in http://golang.org/pkg/net/http/#ListenAndServeTLS

func NextLabel

func NextLabel(s string, offset int) (i int, end bool)

NextLabel returns the index of the start of the next label in the string s starting at offset. A negative offset will cause a panic. The bool end is true when the end of the string has been reached. Also see PrevLabel.

func NumField

func NumField(r RR) int

NumField returns the number of rdata fields r has.

func PackDomainName

func PackDomainName(s string, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error)

PackDomainName packs a domain name s into msg[off:]. If compression is wanted compress must be true and the compression map needs to hold a mapping between domain names and offsets pointing into msg.

func PackRR

func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error)

PackRR packs a resource record rr into msg[off:]. See PackDomainName for documentation about the compression.

func PrevLabel

func PrevLabel(s string, n int) (i int, start bool)

PrevLabel returns the index of the label when starting from the right and jumping n labels to the left. The bool start is true when the start of the string has been overshot. Also see NextLabel.

func PrivateHandle

func PrivateHandle(rtypestr string, rtype uint16, generator func() PrivateRdata)

PrivateHandle registers a private resource record type. It requires string and numeric representation of private RR type and generator function as argument.

Example

Code:

dns.PrivateHandle("APAIR", TypeAPAIR, NewAPAIR)
defer dns.PrivateHandleRemove(TypeAPAIR)
var oldId = dns.Id
dns.Id = func() uint16 { return 3 }
defer func() { dns.Id = oldId }()

rr, err := dns.NewRR("miek.nl. APAIR (1.2.3.4    1.2.3.5)")
if err != nil {
    log.Fatal("could not parse APAIR record: ", err)
}
fmt.Println(rr) // see first line of Output below

m := new(dns.Msg)
m.SetQuestion("miek.nl.", TypeAPAIR)
m.Answer = append(m.Answer, rr)

fmt.Println(m)

Output:

miek.nl.	3600	IN	APAIR	1.2.3.4 1.2.3.5
;; opcode: QUERY, status: NOERROR, id: 3
;; flags: rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;miek.nl.	IN	 APAIR

;; ANSWER SECTION:
miek.nl.	3600	IN	APAIR	1.2.3.4 1.2.3.5

func PrivateHandleRemove

func PrivateHandleRemove(rtype uint16)

PrivateHandleRemove removes definitions required to support private RR type.

func ReverseAddr

func ReverseAddr(addr string) (arpa string, err error)

ReverseAddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP address suitable for reverse DNS (PTR) record lookups or an error if it fails to parse the IP address.

func SMIMEAName

func SMIMEAName(email, domain string) (string, error)

SMIMEAName returns the ownername of a SMIMEA resource record as per the format specified in RFC 'draft-ietf-dane-smime-12' Section 2 and 3

func Split

func Split(s string) []int

Split splits a name s into its label indexes. www.miek.nl. returns []int{0, 4, 9}, www.miek.nl also returns []int{0, 4, 9}. The root name (.) returns nil. Also see SplitDomainName. s must be a syntactically valid domain name.

func SplitDomainName

func SplitDomainName(s string) (labels []string)

SplitDomainName splits a name string into it's labels. www.miek.nl. returns []string{"www", "miek", "nl"} .www.miek.nl. returns []string{"", "www", "miek", "nl"}, The root label (.) returns nil. Note that using strings.Split(s) will work in most cases, but does not handle escaped dots (\.) for instance. s must be a syntactically valid domain name, see IsDomainName.

func StringToTime

func StringToTime(s string) (uint32, error)

StringToTime translates the RRSIG's incep. and expir. times from string values like "20110403154150" to an 32 bit integer. It takes serial arithmetic (RFC 1982) into account.

func TLSAName

func TLSAName(name, service, network string) (string, error)

TLSAName returns the ownername of a TLSA resource record as per the rules specified in RFC 6698, Section 3.

func TimeToString

func TimeToString(t uint32) string

TimeToString translates the RRSIG's incep. and expir. times to the string representation used when printing the record. It takes serial arithmetic (RFC 1982) into account.

func TsigGenerate

func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, string, error)

TsigGenerate fills out the TSIG record attached to the message. The message should contain a "stub" TSIG RR with the algorithm, key name (owner name of the RR), time fudge (defaults to 300 seconds) and the current time The TSIG MAC is saved in that Tsig RR. When TsigGenerate is called for the first time requestMAC should be set to the empty string and timersOnly to false.

func TsigGenerateWithProvider

func TsigGenerateWithProvider(m *Msg, provider TsigProvider, requestMAC string, timersOnly bool) ([]byte, string, error)

TsigGenerateWithProvider is similar to TsigGenerate, but allows for a custom TsigProvider.

func TsigVerify

func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error

TsigVerify verifies the TSIG on a message. If the signature does not validate the returned error contains the cause. If the signature is OK, the error is nil.

func TsigVerifyWithProvider

func TsigVerifyWithProvider(msg []byte, provider TsigProvider, requestMAC string, timersOnly bool) error

TsigVerifyWithProvider is similar to TsigVerify, but allows for a custom TsigProvider.

func UnpackDomainName

func UnpackDomainName(msg []byte, off int) (string, int, error)

UnpackDomainName unpacks a domain name into a string. It returns the name, the new offset into msg and any error that occurred.

When an error is encountered, the unpacked name will be discarded and len(msg) will be returned as the offset.

func WriteToSessionUDP

func WriteToSessionUDP(conn *net.UDPConn, b []byte, session *SessionUDP) (int, error)

WriteToSessionUDP acts just like net.UDPConn.WriteTo(), but uses a *SessionUDP instead of a net.Addr.

type A

A RR. See RFC 1035.

type A struct {
    Hdr RR_Header
    A   net.IP `dns:"a"`
}

func (*A) Header

func (rr *A) Header() *RR_Header

func (*A) String

func (rr *A) String() string

type AAAA

AAAA RR. See RFC 3596.

type AAAA struct {
    Hdr  RR_Header
    AAAA net.IP `dns:"aaaa"`
}

func (*AAAA) Header

func (rr *AAAA) Header() *RR_Header

func (*AAAA) String

func (rr *AAAA) String() string

type AFSDB

AFSDB RR. See RFC 1183.

type AFSDB struct {
    Hdr      RR_Header
    Subtype  uint16
    Hostname string `dns:"domain-name"`
}

func (*AFSDB) Header

func (rr *AFSDB) Header() *RR_Header

func (*AFSDB) String

func (rr *AFSDB) String() string

type AMTRELAY

AMTRELAY RR. See RFC 8777.

type AMTRELAY struct {
    Hdr         RR_Header
    Precedence  uint8
    GatewayType uint8  // discovery is packed in here at bit 0x80
    GatewayAddr net.IP `dns:"-"` // packing/unpacking/parsing/etc handled together with GatewayHost
    GatewayHost string `dns:"amtrelayhost"`
}

func (*AMTRELAY) Header

func (rr *AMTRELAY) Header() *RR_Header

func (*AMTRELAY) String

func (rr *AMTRELAY) String() string

type ANY

ANY is a wild card record. See RFC 1035, Section 3.2.3. ANY is named "*" there.

type ANY struct {
    Hdr RR_Header
}

func (*ANY) Header

func (rr *ANY) Header() *RR_Header

func (*ANY) String

func (rr *ANY) String() string

type APL

APL RR. See RFC 3123.

type APL struct {
    Hdr      RR_Header
    Prefixes []APLPrefix `dns:"apl"`
}

func (*APL) Header

func (rr *APL) Header() *RR_Header

func (*APL) String

func (rr *APL) String() string

String returns presentation form of the APL record.

type APLPrefix

APLPrefix is an address prefix hold by an APL record.

type APLPrefix struct {
    Negation bool
    Network  net.IPNet
}

type AVC

AVC RR. See https://www.iana.org/assignments/dns-parameters/AVC/avc-completed-template.

type AVC struct {
    Hdr RR_Header
    Txt []string `dns:"txt"`
}

func (*AVC) Header

func (rr *AVC) Header() *RR_Header

func (*AVC) String

func (rr *AVC) String() string

type CAA

CAA RR. See RFC 6844.

type CAA struct {
    Hdr   RR_Header
    Flag  uint8
    Tag   string
    Value string `dns:"octet"`
}

func (*CAA) Header

func (rr *CAA) Header() *RR_Header

func (*CAA) String

func (rr *CAA) String() string

rr.Value Is the character-string encoding of the value field as specified in RFC 1035, Section 5.1.

type CDNSKEY

CDNSKEY RR. See RFC 7344.

type CDNSKEY struct {
    DNSKEY
}

func (*CDNSKEY) Header

func (rr *CDNSKEY) Header() *RR_Header

type CDS

CDS RR. See RFC 7344.

type CDS struct{ DS }

func (*CDS) Header

func (rr *CDS) Header() *RR_Header

type CERT

CERT RR. See RFC 4398.

type CERT struct {
    Hdr         RR_Header
    Type        uint16
    KeyTag      uint16
    Algorithm   uint8
    Certificate string `dns:"base64"`
}

func (*CERT) Header

func (rr *CERT) Header() *RR_Header

func (*CERT) String

func (rr *CERT) String() string

type CNAME

CNAME RR. See RFC 1034.

type CNAME struct {
    Hdr    RR_Header
    Target string `dns:"cdomain-name"`
}

func (*CNAME) Header

func (rr *CNAME) Header() *RR_Header

func (*CNAME) String

func (rr *CNAME) String() string

type CSYNC

CSYNC RR. See RFC 7477.

type CSYNC struct {
    Hdr        RR_Header
    Serial     uint32
    Flags      uint16
    TypeBitMap []uint16 `dns:"nsec"`
}

func (*CSYNC) Header

func (rr *CSYNC) Header() *RR_Header

func (*CSYNC) String

func (rr *CSYNC) String() string

type Class

Class is a DNS class.

type Class uint16

func (Class) String

func (c Class) String() string

String returns the string representation for the class c.

type Client

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
}

func (*Client) Dial

func (c *Client) Dial(address string) (conn *Conn, err error)

Dial connects to the address on the named network.

func (*Client) DialContext

func (c *Client) DialContext(ctx context.Context, address string) (conn *Conn, err error)

DialContext connects to the address on the named network, with a context.Context.

func (*Client) Exchange

func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error)

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) ExchangeContext

func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error)

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) ExchangeWithConn

func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error)

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) ExchangeWithConnContext

func (c *Client) ExchangeWithConnContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error)

ExchangeWithConnContext has the same behaviour as ExchangeWithConn and additionally obeys deadlines from the passed Context.

type ClientConfig

ClientConfig wraps the contents of the /etc/resolv.conf file.

type ClientConfig struct {
    Servers  []string // servers to use
    Search   []string // suffixes to append to local name
    Port     string   // what port to use
    Ndots    int      // number of dots in name to trigger absolute lookup
    Timeout  int      // seconds before giving up on packet
    Attempts int      // lost packets before giving up on server, not used in the package dns
}

func ClientConfigFromFile

func ClientConfigFromFile(resolvconf string) (*ClientConfig, error)

ClientConfigFromFile parses a resolv.conf(5) like file and returns a *ClientConfig.

func ClientConfigFromReader

func ClientConfigFromReader(resolvconf io.Reader) (*ClientConfig, error)

ClientConfigFromReader works like ClientConfigFromFile but takes an io.Reader as argument

func (*ClientConfig) NameList

func (c *ClientConfig) NameList(name string) []string

NameList returns all of the names that should be queried based on the config. It is based off of go's net/dns name building, but it does not check the length of the resulting names.

type Conn

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.
    // contains filtered or unexported fields
}

func Dial

func Dial(network, address string) (conn *Conn, err error)

Dial connects to the address on the named network.

func DialTimeout

func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error)

DialTimeout acts like Dial but takes a timeout.

func DialTimeoutWithTLS

func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout time.Duration) (conn *Conn, err error)

DialTimeoutWithTLS acts like DialWithTLS but takes a timeout.

func DialWithTLS

func DialWithTLS(network, address string, tlsConfig *tls.Config) (conn *Conn, err error)

DialWithTLS connects to the address on the named network with TLS.

func (*Conn) Read

func (co *Conn) Read(p []byte) (n int, err error)

Read implements the net.Conn read method.

func (*Conn) ReadMsg

func (co *Conn) ReadMsg() (*Msg, error)

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) ReadMsgHeader

func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error)

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) Write

func (co *Conn) Write(p []byte) (int, error)

Write implements the net.Conn Write method.

func (*Conn) WriteMsg

func (co *Conn) WriteMsg(m *Msg) (err error)

WriteMsg sends a message through the connection co. If the message m contains a TSIG record the transaction signature is calculated.

type ConnectionStater

A ConnectionStater interface is used by a DNS Handler to access TLS connection state when available.

type ConnectionStater interface {
    ConnectionState() *tls.ConnectionState
}

type DHCID

DHCID RR. See RFC 4701.

type DHCID struct {
    Hdr    RR_Header
    Digest string `dns:"base64"`
}

func (*DHCID) Header

func (rr *DHCID) Header() *RR_Header

func (*DHCID) String

func (rr *DHCID) String() string

type DLV

DLV RR. See RFC 4431.

type DLV struct{ DS }

func (*DLV) Header

func (rr *DLV) Header() *RR_Header

type DNAME

DNAME RR. See RFC 2672.

type DNAME struct {
    Hdr    RR_Header
    Target string `dns:"domain-name"`
}

func (*DNAME) Header

func (rr *DNAME) Header() *RR_Header

func (*DNAME) String

func (rr *DNAME) String() string

type DNSKEY

DNSKEY RR. See RFC 4034 and RFC 3755.

type DNSKEY struct {
    Hdr       RR_Header
    Flags     uint16
    Protocol  uint8
    Algorithm uint8
    PublicKey string `dns:"base64"`
}

func (*DNSKEY) Generate

func (k *DNSKEY) Generate(bits int) (crypto.PrivateKey, error)

Generate generates a DNSKEY of the given bit size. The public part is put inside the DNSKEY record. The Algorithm in the key must be set as this will define what kind of DNSKEY will be generated. The ECDSA algorithms imply a fixed keysize, in that case bits should be set to the size of the algorithm.

func (*DNSKEY) Header

func (rr *DNSKEY) Header() *RR_Header

func (*DNSKEY) KeyTag

func (k *DNSKEY) KeyTag() uint16

KeyTag calculates the keytag (or key-id) of the DNSKEY.

func (*DNSKEY) NewPrivateKey

func (k *DNSKEY) NewPrivateKey(s string) (crypto.PrivateKey, error)

NewPrivateKey returns a PrivateKey by parsing the string s. s should be in the same form of the BIND private key files.

func (*DNSKEY) PrivateKeyString

func (r *DNSKEY) PrivateKeyString(p crypto.PrivateKey) string

PrivateKeyString converts a PrivateKey to a string. This string has the same format as the private-key-file of BIND9 (Private-key-format: v1.3). It needs some info from the key (the algorithm), so its a method of the DNSKEY. It supports *rsa.PrivateKey, *ecdsa.PrivateKey and ed25519.PrivateKey.

func (*DNSKEY) ReadPrivateKey

func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, error)

ReadPrivateKey reads a private key from the io.Reader q. The string file is only used in error reporting. The public key must be known, because some cryptographic algorithms embed the public inside the privatekey.

func (*DNSKEY) String

func (rr *DNSKEY) String() string

func (*DNSKEY) ToCDNSKEY

func (k *DNSKEY) ToCDNSKEY() *CDNSKEY

ToCDNSKEY converts a DNSKEY record to a CDNSKEY record.

func (*DNSKEY) ToDS

func (k *DNSKEY) ToDS(h uint8) *DS

ToDS converts a DNSKEY record to a DS record.

type DS

DS RR. See RFC 4034 and RFC 3658.

type DS struct {
    Hdr        RR_Header
    KeyTag     uint16
    Algorithm  uint8
    DigestType uint8
    Digest     string `dns:"hex"`
}

Example

Retrieve the DNSKEY records of a zone and convert them to DS records for SHA1, SHA256 and SHA384.

Code:

config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")
c := new(dns.Client)
m := new(dns.Msg)
zone := "miek.nl"
m.SetQuestion(dns.Fqdn(zone), dns.TypeDNSKEY)
m.SetEdns0(4096, true)
r, _, err := c.Exchange(m, net.JoinHostPort(config.Servers[0], config.Port))
if err != nil {
    return
}
if r.Rcode != dns.RcodeSuccess {
    return
}
for _, k := range r.Answer {
    if key, ok := k.(*dns.DNSKEY); ok {
        for _, alg := range []uint8{dns.SHA1, dns.SHA256, dns.SHA384} {
            fmt.Printf("%s; %d\n", key.ToDS(alg).String(), key.Flags)
        }
    }
}

func (*DS) Header

func (rr *DS) Header() *RR_Header

func (*DS) String

func (rr *DS) String() string

func (*DS) ToCDS

func (d *DS) ToCDS() *CDS

ToCDS converts a DS record to a CDS record.

type DecorateReader

DecorateReader is a decorator hook for extending or supplanting the functionality of a Reader. Implementations should never return a nil Reader. Readers should also implement the optional PacketConnReader interface. PacketConnReader is required to use a generic net.PacketConn.

type DecorateReader func(Reader) Reader

type DecorateWriter

DecorateWriter is a decorator hook for extending or supplanting the functionality of a Writer. Implementations should never return a nil Writer.

type DecorateWriter func(Writer) Writer

Example

Code:

// instrument raw DNS message writing
wf := DecorateWriter(func(w Writer) Writer {
    return &ExampleFrameLengthWriter{w}
})

// simple UDP server
pc, err := net.ListenPacket("udp", ":0")
if err != nil {
    fmt.Println(err.Error())
    return
}
server := &Server{
    PacketConn:     pc,
    DecorateWriter: wf,
    ReadTimeout:    time.Hour, WriteTimeout: time.Hour,
}

waitLock := sync.Mutex{}
waitLock.Lock()
server.NotifyStartedFunc = waitLock.Unlock
defer server.Shutdown()

go func() {
    server.ActivateAndServe()
    pc.Close()
}()

waitLock.Lock()

HandleFunc("miek.nl.", HelloServer)

c := new(Client)
m := new(Msg)
m.SetQuestion("miek.nl.", TypeTXT)
_, _, err = c.Exchange(m, pc.LocalAddr().String())
if err != nil {
    fmt.Println("failed to exchange", err.Error())
    return
}

Output:

writing raw DNS message of length 56

type EDNS0

EDNS0 defines an EDNS0 Option. An OPT RR can have multiple options appended to it.

type EDNS0 interface {
    // Option returns the option code for the option.
    Option() uint16

    // String returns the string representation of the option.
    String() string
    // contains filtered or unexported methods
}

The EDNS0_COOKIE option is used to add a DNS Cookie to a message.

o := new(dns.OPT)
o.Hdr.Name = "."
o.Hdr.Rrtype = dns.TypeOPT
e := new(dns.EDNS0_COOKIE)
e.Code = dns.EDNS0COOKIE
e.Cookie = "24a5ac.."
o.Option = append(o.Option, e)

The Cookie field consists out of a client cookie (RFC 7873 Section 4), that is always 8 bytes. It may then optionally be followed by the server cookie. The server cookie is of variable length, 8 to a maximum of 32 bytes. In other words:

cCookie := o.Cookie[:16]
sCookie := o.Cookie[16:]

There is no guarantee that the Cookie string has a specific length.

type EDNS0_COOKIE struct {
    Code   uint16 // Always EDNS0COOKIE
    Cookie string // Hex-encoded cookie data
}

func (*EDNS0_COOKIE) Option

func (e *EDNS0_COOKIE) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_COOKIE) String

func (e *EDNS0_COOKIE) String() string

type EDNS0_DAU

EDNS0_DAU implements the EDNS0 "DNSSEC Algorithm Understood" option. See RFC 6975.

type EDNS0_DAU struct {
    Code    uint16 // Always EDNS0DAU
    AlgCode []uint8
}

func (*EDNS0_DAU) Option

func (e *EDNS0_DAU) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_DAU) String

func (e *EDNS0_DAU) String() string

type EDNS0_DHU

EDNS0_DHU implements the EDNS0 "DS Hash Understood" option. See RFC 6975.

type EDNS0_DHU struct {
    Code    uint16 // Always EDNS0DHU
    AlgCode []uint8
}

func (*EDNS0_DHU) Option

func (e *EDNS0_DHU) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_DHU) String

func (e *EDNS0_DHU) String() string

type EDNS0_EDE

EDNS0_EDE option is used to return additional information about the cause of DNS errors.

type EDNS0_EDE struct {
    InfoCode  uint16
    ExtraText string
}

func (*EDNS0_EDE) Option

func (e *EDNS0_EDE) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_EDE) String

func (e *EDNS0_EDE) String() string

type EDNS0_ESU

The EDNS0_ESU option for ENUM Source-URI Extension

type EDNS0_ESU struct {
    Code uint16
    Uri  string
}

func (*EDNS0_ESU) Option

func (e *EDNS0_ESU) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_ESU) String

func (e *EDNS0_ESU) String() string

type EDNS0_EXPIRE

EDNS0_EXPIRE implements the EDNS0 option as described in RFC 7314.

type EDNS0_EXPIRE struct {
    Code   uint16 // Always EDNS0EXPIRE
    Expire uint32
    Empty  bool // Empty is used to signal an empty Expire option in a backwards compatible way, it's not used on the wire.
}

func (*EDNS0_EXPIRE) Option

func (e *EDNS0_EXPIRE) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_EXPIRE) String

func (e *EDNS0_EXPIRE) String() (s string)

type EDNS0_LLQ

EDNS0_LLQ stands for Long Lived Queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01 Implemented for completeness, as the EDNS0 type code is assigned.

type EDNS0_LLQ struct {
    Code      uint16 // Always EDNS0LLQ
    Version   uint16
    Opcode    uint16
    Error     uint16
    Id        uint64
    LeaseLife uint32
}

func (*EDNS0_LLQ) Option

func (e *EDNS0_LLQ) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_LLQ) String

func (e *EDNS0_LLQ) String() string

type EDNS0_LOCAL

The EDNS0_LOCAL option is used for local/experimental purposes. The option code is recommended to be within the range [EDNS0LOCALSTART, EDNS0LOCALEND] (RFC6891), although any unassigned code can actually be used. The content of the option is made available in Data, unaltered. Basic use pattern for creating a local option:

o := new(dns.OPT)
o.Hdr.Name = "."
o.Hdr.Rrtype = dns.TypeOPT
e := new(dns.EDNS0_LOCAL)
e.Code = dns.EDNS0LOCALSTART
e.Data = []byte{72, 82, 74}
o.Option = append(o.Option, e)
type EDNS0_LOCAL struct {
    Code uint16
    Data []byte
}

func (*EDNS0_LOCAL) Option

func (e *EDNS0_LOCAL) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_LOCAL) String

func (e *EDNS0_LOCAL) String() string

type EDNS0_N3U

EDNS0_N3U implements the EDNS0 "NSEC3 Hash Understood" option. See RFC 6975.

type EDNS0_N3U struct {
    Code    uint16 // Always EDNS0N3U
    AlgCode []uint8
}

func (*EDNS0_N3U) Option

func (e *EDNS0_N3U) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_N3U) String

func (e *EDNS0_N3U) String() string

type EDNS0_NSID

EDNS0_NSID option is used to retrieve a nameserver identifier. When sending a request Nsid must be set to the empty string The identifier is an opaque string encoded as hex. Basic use pattern for creating an nsid option:

o := new(dns.OPT)
o.Hdr.Name = "."
o.Hdr.Rrtype = dns.TypeOPT
e := new(dns.EDNS0_NSID)
e.Code = dns.EDNS0NSID
e.Nsid = "AA"
o.Option = append(o.Option, e)
type EDNS0_NSID struct {
    Code uint16 // Always EDNS0NSID
    Nsid string // This string needs to be hex encoded
}

func (*EDNS0_NSID) Option

func (e *EDNS0_NSID) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_NSID) String

func (e *EDNS0_NSID) String() string

type EDNS0_PADDING

EDNS0_PADDING option is used to add padding to a request/response. The default value of padding SHOULD be 0x0 but other values MAY be used, for instance if compression is applied before encryption which may break signatures.

type EDNS0_PADDING struct {
    Padding []byte
}

func (*EDNS0_PADDING) Option

func (e *EDNS0_PADDING) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_PADDING) String

func (e *EDNS0_PADDING) String() string

type EDNS0_SUBNET

EDNS0_SUBNET is the subnet option that is used to give the remote nameserver an idea of where the client lives. See RFC 7871. It can then give back a different answer depending on the location or network topology. Basic use pattern for creating an subnet option:

o := new(dns.OPT)
o.Hdr.Name = "."
o.Hdr.Rrtype = dns.TypeOPT
e := new(dns.EDNS0_SUBNET)
e.Code = dns.EDNS0SUBNET // by default this is filled in through unpacking OPT packets (unpackDataOpt)
e.Family = 1	// 1 for IPv4 source address, 2 for IPv6
e.SourceNetmask = 32	// 32 for IPV4, 128 for IPv6
e.SourceScope = 0
e.Address = net.ParseIP("127.0.0.1").To4()	// for IPv4
// e.Address = net.ParseIP("2001:7b8:32a::2")	// for IPV6
o.Option = append(o.Option, e)

This code will parse all the available bits when unpacking (up to optlen). When packing it will apply SourceNetmask. If you need more advanced logic, patches welcome and good luck.

type EDNS0_SUBNET struct {
    Code          uint16 // Always EDNS0SUBNET
    Family        uint16 // 1 for IP, 2 for IP6
    SourceNetmask uint8
    SourceScope   uint8
    Address       net.IP
}

func (*EDNS0_SUBNET) Option

func (e *EDNS0_SUBNET) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_SUBNET) String

func (e *EDNS0_SUBNET) String() (s string)

type EDNS0_TCP_KEEPALIVE

EDNS0_TCP_KEEPALIVE is an EDNS0 option that instructs the server to keep the TCP connection alive. See RFC 7828.

type EDNS0_TCP_KEEPALIVE struct {
    Code uint16 // Always EDNSTCPKEEPALIVE

    // Timeout is an idle timeout value for the TCP connection, specified in
    // units of 100 milliseconds, encoded in network byte order. If set to 0,
    // pack will return a nil slice.
    Timeout uint16

    // Length is the option's length.
    // Deprecated: this field is deprecated and is always equal to 0.
    Length uint16
}

func (*EDNS0_TCP_KEEPALIVE) Option

func (e *EDNS0_TCP_KEEPALIVE) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_TCP_KEEPALIVE) String

func (e *EDNS0_TCP_KEEPALIVE) String() string

type EDNS0_UL

The EDNS0_UL (Update Lease) (draft RFC) option is used to tell the server to set an expiration on an update RR. This is helpful for clients that cannot clean up after themselves. This is a draft RFC and more information can be found at https://tools.ietf.org/html/draft-sekar-dns-ul-02

o := new(dns.OPT)
o.Hdr.Name = "."
o.Hdr.Rrtype = dns.TypeOPT
e := new(dns.EDNS0_UL)
e.Code = dns.EDNS0UL
e.Lease = 120 // in seconds
o.Option = append(o.Option, e)
type EDNS0_UL struct {
    Code     uint16 // Always EDNS0UL
    Lease    uint32
    KeyLease uint32
}

func (*EDNS0_UL) Option

func (e *EDNS0_UL) Option() uint16

Option implements the EDNS0 interface.

func (*EDNS0_UL) String

func (e *EDNS0_UL) String() string

type EID

EID RR. See http://ana-3.lcs.mit.edu/~jnc/nimrod/dns.txt.

type EID struct {
    Hdr      RR_Header
    Endpoint string `dns:"hex"`
}

func (*EID) Header

func (rr *EID) Header() *RR_Header

func (*EID) String

func (rr *EID) String() string

type EUI48

EUI48 RR. See RFC 7043.

type EUI48 struct {
    Hdr     RR_Header
    Address uint64 `dns:"uint48"`
}

func (*EUI48) Header

func (rr *EUI48) Header() *RR_Header

func (*EUI48) String

func (rr *EUI48) String() string

type EUI64

EUI64 RR. See RFC 7043.

type EUI64 struct {
    Hdr     RR_Header
    Address uint64
}

func (*EUI64) Header

func (rr *EUI64) Header() *RR_Header

func (*EUI64) String

func (rr *EUI64) String() string

type Envelope

Envelope is used when doing a zone transfer with a remote server.

type Envelope struct {
    RR    []RR  // The set of RRs in the answer section of the xfr reply message.
    Error error // If something went wrong, this contains the error.
}

type Error

Error represents a DNS error.

type Error struct {
    // contains filtered or unexported fields
}

func (*Error) Error

func (e *Error) Error() string

type GID

GID RR. Deprecated, IANA-Reserved.

type GID struct {
    Hdr RR_Header
    Gid uint32
}

func (*GID) Header

func (rr *GID) Header() *RR_Header

func (*GID) String

func (rr *GID) String() string

type GPOS

GPOS RR. See RFC 1712.

type GPOS struct {
    Hdr       RR_Header
    Longitude string
    Latitude  string
    Altitude  string
}

func (*GPOS) Header

func (rr *GPOS) Header() *RR_Header

func (*GPOS) String

func (rr *GPOS) String() string

type HINFO

HINFO RR. See RFC 1034.

type HINFO struct {
    Hdr RR_Header
    Cpu string
    Os  string
}

func (*HINFO) Header

func (rr *HINFO) Header() *RR_Header

func (*HINFO) String

func (rr *HINFO) String() string

type HIP

HIP RR. See RFC 8005.

type HIP struct {
    Hdr                RR_Header
    HitLength          uint8
    PublicKeyAlgorithm uint8
    PublicKeyLength    uint16
    Hit                string   `dns:"size-hex:HitLength"`
    PublicKey          string   `dns:"size-base64:PublicKeyLength"`
    RendezvousServers  []string `dns:"domain-name"`
}

func (*HIP) Header

func (rr *HIP) Header() *RR_Header

func (*HIP) String

func (rr *HIP) String() string

type HTTPS

HTTPS RR. Everything valid for SVCB applies to HTTPS as well. Except that the HTTPS record is intended for use with the HTTP and HTTPS protocols.

NOTE: The HTTPS/SVCB RFCs are in the draft stage. The API, including constants and types related to SVCBKeyValues, may change in future versions in accordance with the latest drafts.

type HTTPS struct {
    SVCB
}

func (*HTTPS) Header

func (rr *HTTPS) Header() *RR_Header

func (*HTTPS) String

func (rr *HTTPS) String() string

type Handler

Handler is implemented by any value that implements ServeDNS.

type Handler interface {
    ServeDNS(w ResponseWriter, r *Msg)
}

type HandlerFunc

The HandlerFunc type is an adapter to allow the use of ordinary functions as DNS handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.

type HandlerFunc func(ResponseWriter, *Msg)

func (HandlerFunc) ServeDNS

func (f HandlerFunc) ServeDNS(w ResponseWriter, r *Msg)

ServeDNS calls f(w, r).

Header is the wire format for the DNS packet header.

type Header struct {
    Id                                 uint16
    Bits                               uint16
    Qdcount, Ancount, Nscount, Arcount uint16
}

type IPSECKEY

IPSECKEY RR. See RFC 4025.

type IPSECKEY struct {
    Hdr         RR_Header
    Precedence  uint8
    GatewayType uint8
    Algorithm   uint8
    GatewayAddr net.IP `dns:"-"` // packing/unpacking/parsing/etc handled together with GatewayHost
    GatewayHost string `dns:"ipsechost"`
    PublicKey   string `dns:"base64"`
}

func (*IPSECKEY) Header

func (rr *IPSECKEY) Header() *RR_Header

func (*IPSECKEY) String

func (rr *IPSECKEY) String() string

type KEY

KEY RR. See RFC RFC 2535.

type KEY struct {
    DNSKEY
}

func (*KEY) Header

func (rr *KEY) Header() *RR_Header

type KX

KX RR. See RFC 2230.

type KX struct {
    Hdr        RR_Header
    Preference uint16
    Exchanger  string `dns:"domain-name"`
}

func (*KX) Header

func (rr *KX) Header() *RR_Header

func (*KX) String

func (rr *KX) String() string

type L32

L32 RR, See RFC 6742.

type L32 struct {
    Hdr        RR_Header
    Preference uint16
    Locator32  net.IP `dns:"a"`
}

func (*L32) Header

func (rr *L32) Header() *RR_Header

func (*L32) String

func (rr *L32) String() string

type L64

L64 RR, See RFC 6742.

type L64 struct {
    Hdr        RR_Header
    Preference uint16
    Locator64  uint64
}

func (*L64) Header

func (rr *L64) Header() *RR_Header

func (*L64) String

func (rr *L64) String() string

type LOC

LOC RR. See RFC RFC 1876.

type LOC struct {
    Hdr       RR_Header
    Version   uint8
    Size      uint8
    HorizPre  uint8
    VertPre   uint8
    Latitude  uint32
    Longitude uint32
    Altitude  uint32
}

func (*LOC) Header

func (rr *LOC) Header() *RR_Header

func (*LOC) String

func (rr *LOC) String() string

type LP

LP RR. See RFC 6742.

type LP struct {
    Hdr        RR_Header
    Preference uint16
    Fqdn       string `dns:"domain-name"`
}

func (*LP) Header

func (rr *LP) Header() *RR_Header

func (*LP) String

func (rr *LP) String() string

type MB

MB RR. See RFC 1035.

type MB struct {
    Hdr RR_Header
    Mb  string `dns:"cdomain-name"`
}

func (*MB) Header

func (rr *MB) Header() *RR_Header

func (*MB) String

func (rr *MB) String() string

type MD

MD RR. See RFC 1035.

type MD struct {
    Hdr RR_Header
    Md  string `dns:"cdomain-name"`
}

func (*MD) Header

func (rr *MD) Header() *RR_Header

func (*MD) String

func (rr *MD) String() string

type MF

MF RR. See RFC 1035.

type MF struct {
    Hdr RR_Header
    Mf  string `dns:"cdomain-name"`
}

func (*MF) Header

func (rr *MF) Header() *RR_Header

func (*MF) String

func (rr *MF) String() string

type MG

MG RR. See RFC 1035.

type MG struct {
    Hdr RR_Header
    Mg  string `dns:"cdomain-name"`
}

func (*MG) Header

func (rr *MG) Header() *RR_Header

func (*MG) String

func (rr *MG) String() string

type MINFO

MINFO RR. See RFC 1035.

type MINFO struct {
    Hdr   RR_Header
    Rmail string `dns:"cdomain-name"`
    Email string `dns:"cdomain-name"`
}

func (*MINFO) Header

func (rr *MINFO) Header() *RR_Header

func (*MINFO) String

func (rr *MINFO) String() string

type MR

MR RR. See RFC 1035.

type MR struct {
    Hdr RR_Header
    Mr  string `dns:"cdomain-name"`
}

func (*MR) Header

func (rr *MR) Header() *RR_Header

func (*MR) String

func (rr *MR) String() string

type MX

MX RR. See RFC 1035.

type MX struct {
    Hdr        RR_Header
    Preference uint16
    Mx         string `dns:"cdomain-name"`
}

Example

Retrieve the MX records for miek.nl.

Code:

config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")
c := new(dns.Client)
m := new(dns.Msg)
m.SetQuestion("miek.nl.", dns.TypeMX)
m.RecursionDesired = true
r, _, err := c.Exchange(m, net.JoinHostPort(config.Servers[0], config.Port))
if err != nil {
    return
}
if r.Rcode != dns.RcodeSuccess {
    return
}
for _, a := range r.Answer {
    if mx, ok := a.(*dns.MX); ok {
        fmt.Printf("%s\n", mx.String())
    }
}

func (*MX) Header

func (rr *MX) Header() *RR_Header

func (*MX) String

func (rr *MX) String() string

type Msg

Msg contains the layout of a DNS message.

type Msg struct {
    MsgHdr
    Compress bool       `json:"-"` // If true, the message will be compressed when converted to wire format.
    Question []Question // Holds the RR(s) of the question section.
    Answer   []RR       // Holds the RR(s) of the answer section.
    Ns       []RR       // Holds the RR(s) of the authority section.
    Extra    []RR       // Holds the RR(s) of the additional section.
}

func Exchange

func Exchange(m *Msg, a string) (r *Msg, err error)

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 ExchangeConn

func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error)

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 ExchangeContext

func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error)

ExchangeContext performs a synchronous UDP query, like Exchange. It additionally obeys deadlines from the passed Context.

func (*Msg) Copy

func (dns *Msg) Copy() *Msg

Copy returns a new *Msg which is a deep-copy of dns.

func (*Msg) CopyTo

func (dns *Msg) CopyTo(r1 *Msg) *Msg

CopyTo copies the contents to the provided message using a deep-copy and returns the copy.

func (*Msg) Insert

func (u *Msg) Insert(rr []RR)

Insert creates a dynamic update packet that adds an complete RRset, see RFC 2136 section 2.5.1.

func (*Msg) IsEdns0

func (dns *Msg) IsEdns0() *OPT

IsEdns0 checks if the message has a EDNS0 (OPT) record, any EDNS0 record in the additional section will do. It returns the OPT record found or nil.

func (*Msg) IsTsig

func (dns *Msg) IsTsig() *TSIG

IsTsig checks if the message has a TSIG record as the last record in the additional section. It returns the TSIG record found or nil.

func (*Msg) Len

func (dns *Msg) Len() int

Len returns the message length when in (un)compressed wire format. If dns.Compress is true compression it is taken into account. Len() is provided to be a faster way to get the size of the resulting packet, than packing it, measuring the size and discarding the buffer.

func (*Msg) NameNotUsed

func (u *Msg) NameNotUsed(rr []RR)

NameNotUsed sets the RRs in the prereq section to "Name is in not use" RRs. RFC 2136 section 2.4.5.

func (*Msg) NameUsed

func (u *Msg) NameUsed(rr []RR)

NameUsed sets the RRs in the prereq section to "Name is in use" RRs. RFC 2136 section 2.4.4.

func (*Msg) Pack

func (dns *Msg) Pack() (msg []byte, err error)

Pack packs a Msg: it is converted to to wire format. If the dns.Compress is true the message will be in compressed wire format.

func (*Msg) PackBuffer

func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error)

PackBuffer packs a Msg, using the given buffer buf. If buf is too small a new buffer is allocated.

func (*Msg) RRsetNotUsed

func (u *Msg) RRsetNotUsed(rr []RR)

RRsetNotUsed sets the RRs in the prereq section to "RRset does not exist" RRs. RFC 2136 section 2.4.3.

func (*Msg) RRsetUsed

func (u *Msg) RRsetUsed(rr []RR)

RRsetUsed sets the RRs in the prereq section to "RRset exists (value independent -- no rdata)" RRs. RFC 2136 section 2.4.1.

func (*Msg) Remove

func (u *Msg) Remove(rr []RR)

Remove creates a dynamic update packet deletes RR from a RRSset, see RFC 2136 section 2.5.4

func (*Msg) RemoveName

func (u *Msg) RemoveName(rr []RR)

RemoveName creates a dynamic update packet that deletes all RRsets of a name, see RFC 2136 section 2.5.3

func (*Msg) RemoveRRset

func (u *Msg) RemoveRRset(rr []RR)

RemoveRRset creates a dynamic update packet that deletes an RRset, see RFC 2136 section 2.5.2.

func (*Msg) SetAxfr

func (dns *Msg) SetAxfr(z string) *Msg

SetAxfr creates message for requesting an AXFR.

func (*Msg) SetEdns0

func (dns *Msg) SetEdns0(udpsize uint16, do bool) *Msg

SetEdns0 appends a EDNS0 OPT RR to the message. TSIG should always the last RR in a message.

func (*Msg) SetIxfr

func (dns *Msg) SetIxfr(z string, serial uint32, ns, mbox string) *Msg

SetIxfr creates message for requesting an IXFR.

func (*Msg) SetNotify

func (dns *Msg) SetNotify(z string) *Msg

SetNotify creates a notify message, it sets the Question section, generates an Id and sets the Authoritative (AA) bit to true.

func (*Msg) SetQuestion

func (dns *Msg) SetQuestion(z string, t uint16) *Msg

SetQuestion creates a question message, it sets the Question section, generates an Id and sets the RecursionDesired (RD) bit to true.

func (*Msg) SetRcode

func (dns *Msg) SetRcode(request *Msg, rcode int) *Msg

SetRcode creates an error message suitable for the request.

func (*Msg) SetRcodeFormatError

func (dns *Msg) SetRcodeFormatError(request *Msg) *Msg

SetRcodeFormatError creates a message with FormError set.

func (*Msg) SetReply

func (dns *Msg) SetReply(request *Msg) *Msg

SetReply creates a reply message from a request message.

func (*Msg) SetTsig

func (dns *Msg) SetTsig(z, algo string, fudge uint16, timesigned int64) *Msg

SetTsig appends a TSIG RR to the message. This is only a skeleton TSIG RR that is added as the last RR in the additional section. The TSIG is calculated when the message is being send.

func (*Msg) SetUpdate

func (dns *Msg) SetUpdate(z string) *Msg

SetUpdate makes the message a dynamic update message. It sets the ZONE section to: z, TypeSOA, ClassINET.

func (*Msg) String

func (dns *Msg) String() string

Convert a complete message to a string with dig-like output.

func (*Msg) Truncate

func (dns *Msg) Truncate(size int)

Truncate ensures the reply message will fit into the requested buffer size by removing records that exceed the requested size.

It will first check if the reply fits without compression and then with compression. If it won't fit with compression, Truncate then walks the record adding as many records as possible without exceeding the requested buffer size.

If the message fits within the requested size without compression, Truncate will set the message's Compress attribute to false. It is the caller's responsibility to set it back to true if they wish to compress the payload regardless of size.

The TC bit will be set if any records were excluded from the message. If the TC bit is already set on the message it will be retained. TC indicates that the client should retry over TCP.

According to RFC 2181, the TC bit should only be set if not all of the "required" RRs can be included in the response. Unfortunately, we have no way of knowing which RRs are required so we set the TC bit if any RR had to be omitted from the response.

The appropriate buffer size can be retrieved from the requests OPT record, if present, and is transport specific otherwise. dns.MinMsgSize should be used for UDP requests without an OPT record, and dns.MaxMsgSize for TCP requests without an OPT record.

func (*Msg) Unpack

func (dns *Msg) Unpack(msg []byte) (err error)

Unpack unpacks a binary message to a Msg structure.

func (*Msg) Used

func (u *Msg) Used(rr []RR)

Used sets the RRs in the prereq section to "RRset exists (value dependent -- with rdata)" RRs. RFC 2136 section 2.4.2.

type MsgAcceptAction

MsgAcceptAction represents the action to be taken.

type MsgAcceptAction int

Allowed returned values from a MsgAcceptFunc.

const (
    MsgAccept               MsgAcceptAction = iota // Accept the message
    MsgReject                                      // Reject the message with a RcodeFormatError
    MsgIgnore                                      // Ignore the error and send nothing back.
    MsgRejectNotImplemented                        // Reject the message with a RcodeNotImplemented
)

type MsgAcceptFunc

MsgAcceptFunc is used early in the server code to accept or reject a message with RcodeFormatError. It returns a MsgAcceptAction to indicate what should happen with the message.

type MsgAcceptFunc func(dh Header) MsgAcceptAction

DefaultMsgAcceptFunc checks the request and will reject if:

* isn't a request (don't respond in that case)

* opcode isn't OpcodeQuery or OpcodeNotify

* does not have exactly 1 question in the question section

* has more than 1 RR in the Answer section

* has more than 0 RRs in the Authority section

* has more than 2 RRs in the Additional section

var DefaultMsgAcceptFunc MsgAcceptFunc = defaultMsgAcceptFunc

type MsgHdr

MsgHdr is a a manually-unpacked version of (id, bits).

type MsgHdr struct {
    Id                 uint16
    Response           bool
    Opcode             int
    Authoritative      bool
    Truncated          bool
    RecursionDesired   bool
    RecursionAvailable bool
    Zero               bool
    AuthenticatedData  bool
    CheckingDisabled   bool
    Rcode              int
}

func (*MsgHdr) String

func (h *MsgHdr) String() string

Convert a MsgHdr to a string, with dig-like headers:

;; opcode: QUERY, status: NOERROR, id: 48404

;; flags: qr aa rd ra;

type NAPTR

NAPTR RR. See RFC 2915.

type NAPTR struct {
    Hdr         RR_Header
    Order       uint16
    Preference  uint16
    Flags       string
    Service     string
    Regexp      string
    Replacement string `dns:"domain-name"`
}

func (*NAPTR) Header

func (rr *NAPTR) Header() *RR_Header

func (*NAPTR) String

func (rr *NAPTR) String() string

type NID

NID RR. See RFC RFC 6742.

type NID struct {
    Hdr        RR_Header
    Preference uint16
    NodeID     uint64
}

func (*NID) Header

func (rr *NID) Header() *RR_Header

func (*NID) String

func (rr *NID) String() string

type NIMLOC

NIMLOC RR. See http://ana-3.lcs.mit.edu/~jnc/nimrod/dns.txt.

type NIMLOC struct {
    Hdr     RR_Header
    Locator string `dns:"hex"`
}

func (*NIMLOC) Header

func (rr *NIMLOC) Header() *RR_Header

func (*NIMLOC) String

func (rr *NIMLOC) String() string

type NINFO

NINFO RR. See https://www.iana.org/assignments/dns-parameters/NINFO/ninfo-completed-template.

type NINFO struct {
    Hdr    RR_Header
    ZSData []string `dns:"txt"`
}

func (*NINFO) Header

func (rr *NINFO) Header() *RR_Header

func (*NINFO) String

func (rr *NINFO) String() string

type NS

NS RR. See RFC 1035.

type NS struct {
    Hdr RR_Header
    Ns  string `dns:"cdomain-name"`
}

func (*NS) Header

func (rr *NS) Header() *RR_Header

func (*NS) String

func (rr *NS) String() string

type NSAPPTR

NSAPPTR RR. See RFC 1348.

type NSAPPTR struct {
    Hdr RR_Header
    Ptr string `dns:"domain-name"`
}

func (*NSAPPTR) Header

func (rr *NSAPPTR) Header() *RR_Header

func (*NSAPPTR) String

func (rr *NSAPPTR) String() string

type NSEC

NSEC RR. See RFC 4034 and RFC 3755.

type NSEC struct {
    Hdr        RR_Header
    NextDomain string   `dns:"domain-name"`
    TypeBitMap []uint16 `dns:"nsec"`
}

func (*NSEC) Header

func (rr *NSEC) Header() *RR_Header

func (*NSEC) String

func (rr *NSEC) String() string

type NSEC3

NSEC3 RR. See RFC 5155.

type NSEC3 struct {
    Hdr        RR_Header
    Hash       uint8
    Flags      uint8
    Iterations uint16
    SaltLength uint8
    Salt       string `dns:"size-hex:SaltLength"`
    HashLength uint8
    NextDomain string   `dns:"size-base32:HashLength"`
    TypeBitMap []uint16 `dns:"nsec"`
}

func (*NSEC3) Cover

func (rr *NSEC3) Cover(name string) bool

Cover returns true if a name is covered by the NSEC3 record.

func (*NSEC3) Header

func (rr *NSEC3) Header() *RR_Header

func (*NSEC3) Match

func (rr *NSEC3) Match(name string) bool

Match returns true if a name matches the NSEC3 record

func (*NSEC3) String

func (rr *NSEC3) String() string

type NSEC3PARAM

NSEC3PARAM RR. See RFC 5155.

type NSEC3PARAM struct {
    Hdr        RR_Header
    Hash       uint8
    Flags      uint8
    Iterations uint16
    SaltLength uint8
    Salt       string `dns:"size-hex:SaltLength"`
}

func (*NSEC3PARAM) Header

func (rr *NSEC3PARAM) Header() *RR_Header

func (*NSEC3PARAM) String

func (rr *NSEC3PARAM) String() string

type NULL

NULL RR. See RFC 1035.

type NULL struct {
    Hdr  RR_Header
    Data string `dns:"any"`
}

func (*NULL) Header

func (rr *NULL) Header() *RR_Header

func (*NULL) String

func (rr *NULL) String() string

type Name

Name is a DNS domain name.

type Name string

func (Name) String

func (n Name) String() string

String returns the string representation for the name n.

type OPENPGPKEY

OPENPGPKEY RR. See RFC 7929.

type OPENPGPKEY struct {
    Hdr       RR_Header
    PublicKey string `dns:"base64"`
}

func (*OPENPGPKEY) Header

func (rr *OPENPGPKEY) Header() *RR_Header

func (*OPENPGPKEY) String

func (rr *OPENPGPKEY) String() string

type OPT

OPT is the EDNS0 RR appended to messages to convey extra (meta) information. See RFC 6891.

type OPT struct {
    Hdr    RR_Header
    Option []EDNS0 `dns:"opt"`
}

func (*OPT) Do

func (rr *OPT) Do() bool

Do returns the value of the DO (DNSSEC OK) bit.

func (*OPT) ExtendedRcode

func (rr *OPT) ExtendedRcode() int

ExtendedRcode returns the EDNS extended RCODE field (the upper 8 bits of the TTL).

func (*OPT) Header

func (rr *OPT) Header() *RR_Header

func (*OPT) SetDo

func (rr *OPT) SetDo(do ...bool)

SetDo sets the DO (DNSSEC OK) bit. If we pass an argument, set the DO bit to that value. It is possible to pass 2 or more arguments, but they will be ignored.

func (*OPT) SetExtendedRcode

func (rr *OPT) SetExtendedRcode(v uint16)

SetExtendedRcode sets the EDNS extended RCODE field.

If the RCODE is not an extended RCODE, will reset the extended RCODE field to 0.

func (*OPT) SetUDPSize

func (rr *OPT) SetUDPSize(size uint16)

SetUDPSize sets the UDP buffer size.

func (*OPT) SetVersion

func (rr *OPT) SetVersion(v uint8)

SetVersion sets the version of EDNS. This is usually zero.

func (*OPT) SetZ

func (rr *OPT) SetZ(z uint16)

SetZ sets the Z part of the OPT RR, note only the 15 least significant bits of z are used.

func (*OPT) String

func (rr *OPT) String() string

func (*OPT) UDPSize

func (rr *OPT) UDPSize() uint16

UDPSize returns the UDP buffer size.

func (*OPT) Version

func (rr *OPT) Version() uint8

Version returns the EDNS version used. Only zero is defined.

func (*OPT) Z

func (rr *OPT) Z() uint16

Z returns the Z part of the OPT RR as a uint16 with only the 15 least significant bits used.

type PTR

PTR RR. See RFC 1035.

type PTR struct {
    Hdr RR_Header
    Ptr string `dns:"cdomain-name"`
}

func (*PTR) Header

func (rr *PTR) Header() *RR_Header

func (*PTR) String

func (rr *PTR) String() string

type PX

PX RR. See RFC 2163.

type PX struct {
    Hdr        RR_Header
    Preference uint16
    Map822     string `dns:"domain-name"`
    Mapx400    string `dns:"domain-name"`
}

func (*PX) Header

func (rr *PX) Header() *RR_Header

func (*PX) String

func (rr *PX) String() string

type PacketConnReader

PacketConnReader is an optional interface that Readers can implement to support using generic net.PacketConns.

type PacketConnReader interface {
    Reader

    // ReadPacketConn reads a raw message from a generic net.PacketConn UDP connection. Implementations may
    // alter connection properties, for example the read-deadline.
    ReadPacketConn(conn net.PacketConn, timeout time.Duration) ([]byte, net.Addr, error)
}

type ParseError

ParseError is a parsing error. It contains the parse error and the location in the io.Reader where the error occurred.

type ParseError struct {
    // contains filtered or unexported fields
}

func (*ParseError) Error

func (e *ParseError) Error() (s string)

type PrivateRR

PrivateRR represents an RR that uses a PrivateRdata user-defined type. It mocks normal RRs and implements dns.RR interface.

type PrivateRR struct {
    Hdr  RR_Header
    Data PrivateRdata
    // contains filtered or unexported fields
}

func (*PrivateRR) Header

func (r *PrivateRR) Header() *RR_Header

Header return the RR header of r.

func (*PrivateRR) String

func (r *PrivateRR) String() string

type PrivateRdata

PrivateRdata is an interface used for implementing "Private Use" RR types, see RFC 6895. This allows one to experiment with new RR types, without requesting an official type code. Also see dns.PrivateHandle and dns.PrivateHandleRemove.

type PrivateRdata interface {
    // String returns the text presentation of the Rdata of the Private RR.
    String() string
    // Parse parses the Rdata of the private RR.
    Parse([]string) error
    // Pack is used when packing a private RR into a buffer.
    Pack([]byte) (int, error)
    // Unpack is used when unpacking a private RR from a buffer.
    Unpack([]byte) (int, error)
    // Copy copies the Rdata into the PrivateRdata argument.
    Copy(PrivateRdata) error
    // Len returns the length in octets of the Rdata.
    Len() int
}

type Question

Question holds a DNS question. Usually there is just one. While the original DNS RFCs allow multiple questions in the question section of a message, in practice it never works. Because most DNS servers see multiple questions as an error, it is recommended to only have one question per message.

type Question struct {
    Name   string `dns:"cdomain-name"` // "cdomain-name" specifies encoding (and may be compressed)
    Qtype  uint16
    Qclass uint16
}

func (*Question) String

func (q *Question) String() (s string)

type RFC3597

RFC3597 represents an unknown/generic RR. See RFC 3597.

type RFC3597 struct {
    Hdr   RR_Header
    Rdata string `dns:"hex"`
}

func (*RFC3597) Header

func (rr *RFC3597) Header() *RR_Header

func (*RFC3597) String

func (rr *RFC3597) String() string

func (*RFC3597) ToRFC3597

func (rr *RFC3597) ToRFC3597(r RR) error

ToRFC3597 converts a known RR to the unknown RR representation from RFC 3597.

type RKEY

RKEY RR. See https://www.iana.org/assignments/dns-parameters/RKEY/rkey-completed-template.

type RKEY struct {
    Hdr       RR_Header
    Flags     uint16
    Protocol  uint8
    Algorithm uint8
    PublicKey string `dns:"base64"`
}

func (*RKEY) Header

func (rr *RKEY) Header() *RR_Header

func (*RKEY) String

func (rr *RKEY) String() string

type RP

RP RR. See RFC 1138, Section 2.2.

type RP struct {
    Hdr  RR_Header
    Mbox string `dns:"domain-name"`
    Txt  string `dns:"domain-name"`
}

func (*RP) Header

func (rr *RP) Header() *RR_Header

func (*RP) String

func (rr *RP) String() string

type RR

An RR represents a resource record.

type RR interface {
    // Header returns the header of an resource record. The header contains
    // everything up to the rdata.
    Header() *RR_Header
    // String returns the text representation of the resource record.
    String() string
    // contains filtered or unexported methods
}

func Copy

func Copy(r RR) RR

Copy returns a new RR which is a deep-copy of r.

func Dedup

func Dedup(rrs []RR, m map[string]RR) []RR

Dedup removes identical RRs from rrs. It preserves the original ordering. The lowest TTL of any duplicates is used in the remaining one. Dedup modifies rrs. m is used to store the RRs temporary. If it is nil a new map will be allocated.

func NewRR

func NewRR(s string) (RR, error)

NewRR reads the RR contained in the string s. Only the first RR is returned. If s contains no records, NewRR will return nil with no error.

The class defaults to IN and TTL defaults to 3600. The full zone file syntax like $TTL, $ORIGIN, etc. is supported. All fields of the returned RR are set, except RR.Header().Rdlength which is set to 0.

func ReadRR

func ReadRR(r io.Reader, file string) (RR, error)

ReadRR reads the RR contained in r.

The string file is used in error reporting and to resolve relative $INCLUDE directives.

See NewRR for more documentation.

func UnpackRR

func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error)

UnpackRR unpacks msg[off:] into an RR.

func UnpackRRWithHeader

func UnpackRRWithHeader(h RR_Header, msg []byte, off int) (rr RR, off1 int, err error)

UnpackRRWithHeader unpacks the record type specific payload given an existing RR_Header.

type RRSIG

RRSIG RR. See RFC 4034 and RFC 3755.

type RRSIG struct {
    Hdr         RR_Header
    TypeCovered uint16
    Algorithm   uint8
    Labels      uint8
    OrigTtl     uint32
    Expiration  uint32
    Inception   uint32
    KeyTag      uint16
    SignerName  string `dns:"domain-name"`
    Signature   string `dns:"base64"`
}

func (*RRSIG) Header

func (rr *RRSIG) Header() *RR_Header

func (*RRSIG) Sign

func (rr *RRSIG) Sign(k crypto.Signer, rrset []RR) error

Sign signs an RRSet. The signature needs to be filled in with the values: Inception, Expiration, KeyTag, SignerName and Algorithm. The rest is copied from the RRset. Sign returns a non-nill error when the signing went OK. There is no check if RRSet is a proper (RFC 2181) RRSet. If OrigTTL is non zero, it is used as-is, otherwise the TTL of the RRset is used as the OrigTTL.

func (*RRSIG) String

func (rr *RRSIG) String() string

func (*RRSIG) ValidityPeriod

func (rr *RRSIG) ValidityPeriod(t time.Time) bool

ValidityPeriod uses RFC1982 serial arithmetic to calculate if a signature period is valid. If t is the zero time, the current time is taken other t is. Returns true if the signature is valid at the given time, otherwise returns false.

func (*RRSIG) Verify

func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error

Verify validates an RRSet with the signature and key. This is only the cryptographic test, the signature validity period must be checked separately. This function copies the rdata of some RRs (to lowercase domain names) for the validation to work. It also checks that the Zone Key bit (RFC 4034 2.1.1) is set on the DNSKEY and that the Protocol field is set to 3 (RFC 4034 2.1.2).

type RR_Header

RR_Header is the header all DNS resource records share.

type RR_Header struct {
    Name     string `dns:"cdomain-name"`
    Rrtype   uint16
    Class    uint16
    Ttl      uint32
    Rdlength uint16 // Length of data after header.
}

func (*RR_Header) Header

func (h *RR_Header) Header() *RR_Header

Header returns itself. This is here to make RR_Header implements the RR interface.

func (*RR_Header) String

func (h *RR_Header) String() string

type RT

RT RR. See RFC 1183, Section 3.3.

type RT struct {
    Hdr        RR_Header
    Preference uint16
    Host       string `dns:"domain-name"` // RFC 3597 prohibits compressing records not defined in RFC 1035.
}

func (*RT) Header

func (rr *RT) Header() *RR_Header

func (*RT) String

func (rr *RT) String() string

type Reader

Reader reads raw DNS messages; each call to ReadTCP or ReadUDP should return an entire message.

type Reader interface {
    // ReadTCP reads a raw message from a TCP connection. Implementations may alter
    // connection properties, for example the read-deadline.
    ReadTCP(conn net.Conn, timeout time.Duration) ([]byte, error)
    // ReadUDP reads a raw message from a UDP connection. Implementations may alter
    // connection properties, for example the read-deadline.
    ReadUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error)
}

type ResponseWriter

A ResponseWriter interface is used by an DNS handler to construct an DNS response.

type ResponseWriter interface {
    // LocalAddr returns the net.Addr of the server
    LocalAddr() net.Addr
    // RemoteAddr returns the net.Addr of the client that sent the current request.
    RemoteAddr() net.Addr
    // WriteMsg writes a reply back to the client.
    WriteMsg(*Msg) error
    // Write writes a raw buffer back to the client.
    Write([]byte) (int, error)
    // Close closes the connection.
    Close() error
    // TsigStatus returns the status of the Tsig.
    TsigStatus() error
    // TsigTimersOnly sets the tsig timers only boolean.
    TsigTimersOnly(bool)
    // Hijack lets the caller take over the connection.
    // After a call to Hijack(), the DNS package will not do anything with the connection.
    Hijack()
}

type SIG

SIG RR. See RFC 2535. The SIG RR is identical to RRSIG and nowadays only used for SIG(0), See RFC 2931.

type SIG struct {
    RRSIG
}

func (*SIG) Header

func (rr *SIG) Header() *RR_Header

func (*SIG) Sign

func (rr *SIG) Sign(k crypto.Signer, m *Msg) ([]byte, error)

Sign signs a dns.Msg. It fills the signature with the appropriate data. The SIG record should have the SignerName, KeyTag, Algorithm, Inception and Expiration set.

func (*SIG) Verify

func (rr *SIG) Verify(k *KEY, buf []byte) error

Verify validates the message buf using the key k. It's assumed that buf is a valid message from which rr was unpacked.

type SMIMEA

SMIMEA RR. See RFC 8162.

type SMIMEA struct {
    Hdr          RR_Header
    Usage        uint8
    Selector     uint8
    MatchingType uint8
    Certificate  string `dns:"hex"`
}

func (*SMIMEA) Header

func (rr *SMIMEA) Header() *RR_Header

func (*SMIMEA) Sign

func (r *SMIMEA) Sign(usage, selector, matchingType int, cert *x509.Certificate) (err error)

Sign creates a SMIMEA record from an SSL certificate.

func (*SMIMEA) String

func (rr *SMIMEA) String() string

func (*SMIMEA) Verify

func (r *SMIMEA) Verify(cert *x509.Certificate) error

Verify verifies a SMIMEA record against an SSL certificate. If it is OK a nil error is returned.

type SOA

SOA RR. See RFC 1035.

type SOA struct {
    Hdr     RR_Header
    Ns      string `dns:"cdomain-name"`
    Mbox    string `dns:"cdomain-name"`
    Serial  uint32
    Refresh uint32
    Retry   uint32
    Expire  uint32
    Minttl  uint32
}

func (*SOA) Header

func (rr *SOA) Header() *RR_Header

func (*SOA) String

func (rr *SOA) String() string

type SPF

SPF RR. See RFC 4408, Section 3.1.1.

type SPF struct {
    Hdr RR_Header
    Txt []string `dns:"txt"`
}

func (*SPF) Header

func (rr *SPF) Header() *RR_Header

func (*SPF) String

func (rr *SPF) String() string

type SRV

SRV RR. See RFC 2782.

type SRV struct {
    Hdr      RR_Header
    Priority uint16
    Weight   uint16
    Port     uint16
    Target   string `dns:"domain-name"`
}

func (*SRV) Header

func (rr *SRV) Header() *RR_Header

func (*SRV) String

func (rr *SRV) String() string

type SSHFP

SSHFP RR. See RFC RFC 4255.

type SSHFP struct {
    Hdr         RR_Header
    Algorithm   uint8
    Type        uint8
    FingerPrint string `dns:"hex"`
}

func (*SSHFP) Header

func (rr *SSHFP) Header() *RR_Header

func (*SSHFP) String

func (rr *SSHFP) String() string

type SVCB

SVCB RR. See RFC xxxx (https://tools.ietf.org/html/draft-ietf-dnsop-svcb-https-08).

NOTE: The HTTPS/SVCB RFCs are in the draft stage. The API, including constants and types related to SVCBKeyValues, may change in future versions in accordance with the latest drafts.

type SVCB struct {
    Hdr      RR_Header
    Priority uint16         // If zero, Value must be empty or discarded by the user of this library
    Target   string         `dns:"domain-name"`
    Value    []SVCBKeyValue `dns:"pairs"`
}

func (*SVCB) Header

func (rr *SVCB) Header() *RR_Header

func (*SVCB) String

func (rr *SVCB) String() string

type SVCBAlpn

SVCBAlpn pair is used to list supported connection protocols. The user of this library must ensure that at least one protocol is listed when alpn is present. Protocol IDs can be found at: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids Basic use pattern for creating an alpn option:

h := new(dns.HTTPS)
h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
e := new(dns.SVCBAlpn)
e.Alpn = []string{"h2", "http/1.1"}
h.Value = append(h.Value, e)
type SVCBAlpn struct {
    Alpn []string
}

func (*SVCBAlpn) Key

func (*SVCBAlpn) Key() SVCBKey

func (*SVCBAlpn) String

func (s *SVCBAlpn) String() string

type SVCBDoHPath

SVCBDoHPath pair is used to indicate the URI template that the clients may use to construct a DNS over HTTPS URI.

See RFC xxxx (https://datatracker.ietf.org/doc/html/draft-ietf-add-svcb-dns-02) and RFC yyyy (https://datatracker.ietf.org/doc/html/draft-ietf-add-ddr-06).

A basic example of using the dohpath option together with the alpn option to indicate support for DNS over HTTPS on a certain path:

s := new(dns.SVCB)
s.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeSVCB, Class: dns.ClassINET}
e := new(dns.SVCBAlpn)
e.Alpn = []string{"h2", "h3"}
p := new(dns.SVCBDoHPath)
p.Template = "/dns-query{?dns}"
s.Value = append(s.Value, e, p)

The parsing currently doesn't validate that Template is a valid RFC 6570 URI template.

type SVCBDoHPath struct {
    Template string
}

func (*SVCBDoHPath) Key

func (*SVCBDoHPath) Key() SVCBKey

func (*SVCBDoHPath) String

func (s *SVCBDoHPath) String() string

type SVCBECHConfig

SVCBECHConfig pair contains the ECHConfig structure defined in draft-ietf-tls-esni [RFC xxxx]. Basic use pattern for creating an ech option:

h := new(dns.HTTPS)
h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
e := new(dns.SVCBECHConfig)
e.ECH = []byte{0xfe, 0x08, ...}
h.Value = append(h.Value, e)
type SVCBECHConfig struct {
    ECH []byte // Specifically ECHConfigList including the redundant length prefix
}

func (*SVCBECHConfig) Key

func (*SVCBECHConfig) Key() SVCBKey

func (*SVCBECHConfig) String

func (s *SVCBECHConfig) String() string

type SVCBIPv4Hint

SVCBIPv4Hint pair suggests an IPv4 address which may be used to open connections if A and AAAA record responses for SVCB's Target domain haven't been received. In that case, optionally, A and AAAA requests can be made, after which the connection to the hinted IP address may be terminated and a new connection may be opened. Basic use pattern for creating an ipv4hint option:

	h := new(dns.HTTPS)
	h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
	e := new(dns.SVCBIPv4Hint)
	e.Hint = []net.IP{net.IPv4(1,1,1,1).To4()}

 Or

	e.Hint = []net.IP{net.ParseIP("1.1.1.1").To4()}
	h.Value = append(h.Value, e)
type SVCBIPv4Hint struct {
    Hint []net.IP
}

func (*SVCBIPv4Hint) Key

func (*SVCBIPv4Hint) Key() SVCBKey

func (*SVCBIPv4Hint) String

func (s *SVCBIPv4Hint) String() string

type SVCBIPv6Hint

SVCBIPv6Hint pair suggests an IPv6 address which may be used to open connections if A and AAAA record responses for SVCB's Target domain haven't been received. In that case, optionally, A and AAAA requests can be made, after which the connection to the hinted IP address may be terminated and a new connection may be opened. Basic use pattern for creating an ipv6hint option:

h := new(dns.HTTPS)
h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
e := new(dns.SVCBIPv6Hint)
e.Hint = []net.IP{net.ParseIP("2001:db8::1")}
h.Value = append(h.Value, e)
type SVCBIPv6Hint struct {
    Hint []net.IP
}

func (*SVCBIPv6Hint) Key

func (*SVCBIPv6Hint) Key() SVCBKey

func (*SVCBIPv6Hint) String

func (s *SVCBIPv6Hint) String() string

type SVCBKey

SVCBKey is the type of the keys used in the SVCB RR.

type SVCBKey uint16

Keys defined in draft-ietf-dnsop-svcb-https-08 Section 14.3.2.

const (
    SVCB_MANDATORY SVCBKey = iota
    SVCB_ALPN
    SVCB_NO_DEFAULT_ALPN
    SVCB_PORT
    SVCB_IPV4HINT
    SVCB_ECHCONFIG
    SVCB_IPV6HINT
    SVCB_DOHPATH // draft-ietf-add-svcb-dns-02 Section 9

)

func (SVCBKey) String

func (key SVCBKey) String() string

String takes the numerical code of an SVCB key and returns its name. Returns an empty string for reserved keys. Accepts unassigned keys as well as experimental/private keys.

type SVCBKeyValue

SVCBKeyValue defines a key=value pair for the SVCB RR type. An SVCB RR can have multiple SVCBKeyValues appended to it.

type SVCBKeyValue interface {
    Key() SVCBKey // Key returns the numerical key code.

    String() string // String returns the string representation of the value.
    // contains filtered or unexported methods
}

type SVCBLocal

SVCBLocal pair is intended for experimental/private use. The key is recommended to be in the range [SVCB_PRIVATE_LOWER, SVCB_PRIVATE_UPPER]. Basic use pattern for creating a keyNNNNN option:

h := new(dns.HTTPS)
h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
e := new(dns.SVCBLocal)
e.KeyCode = 65400
e.Data = []byte("abc")
h.Value = append(h.Value, e)
type SVCBLocal struct {
    KeyCode SVCBKey // Never 65535 or any assigned keys.
    Data    []byte  // All byte sequences are allowed.
}

func (*SVCBLocal) Key

func (s *SVCBLocal) Key() SVCBKey

func (*SVCBLocal) String

func (s *SVCBLocal) String() string

type SVCBMandatory

SVCBMandatory pair adds to required keys that must be interpreted for the RR to be functional. If ignored, the whole RRSet must be ignored. "port" and "no-default-alpn" are mandatory by default if present, so they shouldn't be included here.

It is incumbent upon the user of this library to reject the RRSet if or avoid constructing such an RRSet that: - "mandatory" is included as one of the keys of mandatory - no key is listed multiple times in mandatory - all keys listed in mandatory are present - escape sequences are not used in mandatory - mandatory, when present, lists at least one key

Basic use pattern for creating a mandatory option:

s := &dns.SVCB{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeSVCB, Class: dns.ClassINET}}
e := new(dns.SVCBMandatory)
e.Code = []uint16{dns.SVCB_ALPN}
s.Value = append(s.Value, e)
t := new(dns.SVCBAlpn)
t.Alpn = []string{"xmpp-client"}
s.Value = append(s.Value, t)
type SVCBMandatory struct {
    Code []SVCBKey
}

func (*SVCBMandatory) Key

func (*SVCBMandatory) Key() SVCBKey

func (*SVCBMandatory) String

func (s *SVCBMandatory) String() string

type SVCBNoDefaultAlpn

SVCBNoDefaultAlpn pair signifies no support for default connection protocols. Should be used in conjunction with alpn. Basic use pattern for creating a no-default-alpn option:

s := &dns.SVCB{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeSVCB, Class: dns.ClassINET}}
t := new(dns.SVCBAlpn)
t.Alpn = []string{"xmpp-client"}
s.Value = append(s.Value, t)
e := new(dns.SVCBNoDefaultAlpn)
s.Value = append(s.Value, e)
type SVCBNoDefaultAlpn struct{}

func (*SVCBNoDefaultAlpn) Key

func (*SVCBNoDefaultAlpn) Key() SVCBKey

func (*SVCBNoDefaultAlpn) String

func (*SVCBNoDefaultAlpn) String() string

type SVCBPort

SVCBPort pair defines the port for connection. Basic use pattern for creating a port option:

s := &dns.SVCB{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeSVCB, Class: dns.ClassINET}}
e := new(dns.SVCBPort)
e.Port = 80
s.Value = append(s.Value, e)
type SVCBPort struct {
    Port uint16
}

func (*SVCBPort) Key

func (*SVCBPort) Key() SVCBKey

func (*SVCBPort) String

func (s *SVCBPort) String() string

type ServeMux

ServeMux is an DNS request multiplexer. It matches the zone name of each incoming request against a list of registered patterns add calls the handler for the pattern that most closely matches the zone name.

ServeMux is DNSSEC aware, meaning that queries for the DS record are redirected to the parent zone (if that is also registered), otherwise the child gets the query.

ServeMux is also safe for concurrent access from multiple goroutines.

The zero ServeMux is empty and ready for use.

type ServeMux struct {
    // contains filtered or unexported fields
}

func NewServeMux

func NewServeMux() *ServeMux

NewServeMux allocates and returns a new ServeMux.

func (*ServeMux) Handle

func (mux *ServeMux) Handle(pattern string, handler Handler)

Handle adds a handler to the ServeMux for pattern.

func (*ServeMux) HandleFunc

func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Msg))

HandleFunc adds a handler function to the ServeMux for pattern.

func (*ServeMux) HandleRemove

func (mux *ServeMux) HandleRemove(pattern string)

HandleRemove deregisters the handler specific for pattern from the ServeMux.

func (*ServeMux) ServeDNS

func (mux *ServeMux) ServeDNS(w ResponseWriter, req *Msg)

ServeDNS dispatches the request to the handler whose pattern most closely matches the request message.

ServeDNS is DNSSEC aware, meaning that queries for the DS record are redirected to the parent zone (if that is also registered), otherwise the child gets the query.

If no handler is found, or there is no question, a standard REFUSED message is returned

type Server

A Server defines parameters for running an DNS server.

type Server struct {
    // Address to listen on, ":dns" if empty.
    Addr string
    // if "tcp" or "tcp-tls" (DNS over TLS) it will invoke a TCP listener, otherwise an UDP one
    Net string
    // TCP Listener to use, this is to aid in systemd's socket activation.
    Listener net.Listener
    // TLS connection configuration
    TLSConfig *tls.Config
    // UDP "Listener" to use, this is to aid in systemd's socket activation.
    PacketConn net.PacketConn
    // Handler to invoke, dns.DefaultServeMux if nil.
    Handler Handler
    // Default buffer size to use to read incoming UDP messages. If not set
    // it defaults to MinMsgSize (512 B).
    UDPSize int
    // The net.Conn.SetReadTimeout value for new connections, defaults to 2 * time.Second.
    ReadTimeout time.Duration
    // The net.Conn.SetWriteTimeout value for new connections, defaults to 2 * time.Second.
    WriteTimeout time.Duration
    // TCP idle timeout for multiple queries, if nil, defaults to 8 * time.Second (RFC 5966).
    IdleTimeout func() time.Duration
    // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
    TsigProvider TsigProvider
    // Secret(s) for Tsig map[<zonename>]<base64 secret>. The zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2).
    TsigSecret map[string]string
    // If NotifyStartedFunc is set it is called once the server has started listening.
    NotifyStartedFunc func()
    // DecorateReader is optional, allows customization of the process that reads raw DNS messages.
    DecorateReader DecorateReader
    // DecorateWriter is optional, allows customization of the process that writes raw DNS messages.
    DecorateWriter DecorateWriter
    // Maximum number of TCP queries before we close the socket. Default is maxTCPQueries (unlimited if -1).
    MaxTCPQueries int
    // Whether to set the SO_REUSEPORT socket option, allowing multiple listeners to be bound to a single address.
    // It is only supported on certain GOOSes and when using ListenAndServe.
    ReusePort bool
    // Whether to set the SO_REUSEADDR socket option, allowing multiple listeners to be bound to a single address.
    // Crucially this allows binding when an existing server is listening on `0.0.0.0` or `::`.
    // It is only supported on certain GOOSes and when using ListenAndServe.
    ReuseAddr bool
    // AcceptMsgFunc will check the incoming message and will reject it early in the process.
    // By default DefaultMsgAcceptFunc will be used.
    MsgAcceptFunc MsgAcceptFunc
    // contains filtered or unexported fields
}

func (*Server) ActivateAndServe

func (srv *Server) ActivateAndServe() error

ActivateAndServe starts a nameserver with the PacketConn or Listener configured in *Server. Its main use is to start a server from systemd.

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

ListenAndServe starts a nameserver on the configured address in *Server.

func (*Server) Shutdown

func (srv *Server) Shutdown() error

Shutdown shuts down a server. After a call to Shutdown, ListenAndServe and ActivateAndServe will return.

func (*Server) ShutdownContext

func (srv *Server) ShutdownContext(ctx context.Context) error

ShutdownContext shuts down a server. After a call to ShutdownContext, ListenAndServe and ActivateAndServe will return.

A context.Context may be passed to limit how long to wait for connections to terminate.

type SessionUDP

SessionUDP holds the remote address and the associated out-of-band data.

type SessionUDP struct {
    // contains filtered or unexported fields
}

func ReadFromSessionUDP

func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error)

ReadFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a net.UDPAddr.

func (*SessionUDP) RemoteAddr

func (s *SessionUDP) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

type TA

TA RR. See http://www.watson.org/~weiler/INI1999-19.pdf.

type TA struct {
    Hdr        RR_Header
    KeyTag     uint16
    Algorithm  uint8
    DigestType uint8
    Digest     string `dns:"hex"`
}

func (*TA) Header

func (rr *TA) Header() *RR_Header

func (*TA) String

func (rr *TA) String() string

TALINK RR. See https://www.iana.org/assignments/dns-parameters/TALINK/talink-completed-template.

type TALINK struct {
    Hdr          RR_Header
    PreviousName string `dns:"domain-name"`
    NextName     string `dns:"domain-name"`
}

func (*TALINK) Header

func (rr *TALINK) Header() *RR_Header

func (*TALINK) String

func (rr *TALINK) String() string

type TKEY

TKEY RR. See RFC 2930.

type TKEY struct {
    Hdr        RR_Header
    Algorithm  string `dns:"domain-name"`
    Inception  uint32
    Expiration uint32
    Mode       uint16
    Error      uint16
    KeySize    uint16
    Key        string `dns:"size-hex:KeySize"`
    OtherLen   uint16
    OtherData  string `dns:"size-hex:OtherLen"`
}

func (*TKEY) Header

func (rr *TKEY) Header() *RR_Header

func (*TKEY) String

func (rr *TKEY) String() string

TKEY has no official presentation format, but this will suffice.

type TLSA

TLSA RR. See RFC 6698.

type TLSA struct {
    Hdr          RR_Header
    Usage        uint8
    Selector     uint8
    MatchingType uint8
    Certificate  string `dns:"hex"`
}

func (*TLSA) Header

func (rr *TLSA) Header() *RR_Header

func (*TLSA) Sign

func (r *TLSA) Sign(usage, selector, matchingType int, cert *x509.Certificate) (err error)

Sign creates a TLSA record from an SSL certificate.

func (*TLSA) String

func (rr *TLSA) String() string

func (*TLSA) Verify

func (r *TLSA) Verify(cert *x509.Certificate) error

Verify verifies a TLSA record against an SSL certificate. If it is OK a nil error is returned.

type TSIG

TSIG is the RR the holds the transaction signature of a message. See RFC 2845 and RFC 4635.

type TSIG struct {
    Hdr        RR_Header
    Algorithm  string `dns:"domain-name"`
    TimeSigned uint64 `dns:"uint48"`
    Fudge      uint16
    MACSize    uint16
    MAC        string `dns:"size-hex:MACSize"`
    OrigId     uint16
    Error      uint16
    OtherLen   uint16
    OtherData  string `dns:"size-hex:OtherLen"`
}

func (*TSIG) Header

func (rr *TSIG) Header() *RR_Header

func (*TSIG) String

func (rr *TSIG) String() string

type TXT

TXT RR. See RFC 1035.

type TXT struct {
    Hdr RR_Header
    Txt []string `dns:"txt"`
}

func (*TXT) Header

func (rr *TXT) Header() *RR_Header

func (*TXT) String

func (rr *TXT) String() string

type Transfer

A Transfer defines parameters that are used during a zone transfer.

type Transfer struct {
    *Conn
    DialTimeout  time.Duration     // net.DialTimeout, defaults to 2 seconds
    ReadTimeout  time.Duration     // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds
    WriteTimeout time.Duration     // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds
    TsigProvider TsigProvider      // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
    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)
    // contains filtered or unexported fields
}

func (*Transfer) In

func (t *Transfer) In(q *Msg, a string) (env chan *Envelope, err error)

In performs an incoming transfer with the server in a. If you would like to set the source IP, or some other attribute of a Dialer for a Transfer, you can do so by specifying the attributes in the Transfer.Conn:

d := net.Dialer{LocalAddr: transfer_source}
con, err := d.Dial("tcp", master)
dnscon := &dns.Conn{Conn:con}
transfer = &dns.Transfer{Conn: dnscon}
channel, err := transfer.In(message, master)

func (*Transfer) Out

func (t *Transfer) Out(w ResponseWriter, q *Msg, ch chan *Envelope) error

Out performs an outgoing transfer with the client connecting in w. Basic use pattern:

ch := make(chan *dns.Envelope)
tr := new(dns.Transfer)
var wg sync.WaitGroup
go func() {
	tr.Out(w, r, ch)
	wg.Done()
}()
ch <- &dns.Envelope{RR: []dns.RR{soa, rr1, rr2, rr3, soa}}
close(ch)
wg.Wait() // wait until everything is written out
w.Close() // close connection

The server is responsible for sending the correct sequence of RRs through the channel ch.

func (*Transfer) ReadMsg

func (t *Transfer) ReadMsg() (*Msg, error)

ReadMsg reads a message from the transfer connection t.

func (*Transfer) WriteMsg

func (t *Transfer) WriteMsg(m *Msg) (err error)

WriteMsg writes a message through the transfer connection t.

type TsigProvider

TsigProvider provides the API to plug-in a custom TSIG implementation.

type TsigProvider interface {
    // Generate is passed the DNS message to be signed and the partial TSIG RR. It returns the signature and nil, otherwise an error.
    Generate(msg []byte, t *TSIG) ([]byte, error)
    // Verify is passed the DNS message to be verified and the TSIG RR. If the signature is valid it will return nil, otherwise an error.
    Verify(msg []byte, t *TSIG) error
}

type Type

Type is a DNS type.

type Type uint16

func (Type) String

func (t Type) String() string

String returns the string representation for the type t.

type UID

UID RR. Deprecated, IANA-Reserved.

type UID struct {
    Hdr RR_Header
    Uid uint32
}

func (*UID) Header

func (rr *UID) Header() *RR_Header

func (*UID) String

func (rr *UID) String() string

type UINFO

UINFO RR. Deprecated, IANA-Reserved.

type UINFO struct {
    Hdr   RR_Header
    Uinfo string
}

func (*UINFO) Header

func (rr *UINFO) Header() *RR_Header

func (*UINFO) String

func (rr *UINFO) String() string

type URI

URI RR. See RFC 7553.

type URI struct {
    Hdr      RR_Header
    Priority uint16
    Weight   uint16
    Target   string `dns:"octet"`
}

func (*URI) Header

func (rr *URI) Header() *RR_Header

func (*URI) String

func (rr *URI) String() string

rr.Target to be parsed as a sequence of character encoded octets according to RFC 3986

type Writer

Writer writes raw DNS messages; each call to Write should send an entire message.

type Writer interface {
    io.Writer
}

type X25

X25 RR. See RFC 1183, Section 3.1.

type X25 struct {
    Hdr         RR_Header
    PSDNAddress string
}

func (*X25) Header

func (rr *X25) Header() *RR_Header

func (*X25) String

func (rr *X25) String() string

type ZONEMD

ZONEMD RR, from draft-ietf-dnsop-dns-zone-digest

type ZONEMD struct {
    Hdr    RR_Header
    Serial uint32
    Scheme uint8
    Hash   uint8
    Digest string `dns:"hex"`
}

func (*ZONEMD) Header

func (rr *ZONEMD) Header() *RR_Header

func (*ZONEMD) String

func (rr *ZONEMD) String() string

type ZoneParser

ZoneParser is a parser for an RFC 1035 style zonefile.

Each parsed RR in the zone is returned sequentially from Next. An optional comment can be retrieved with Comment.

The directives $INCLUDE, $ORIGIN, $TTL and $GENERATE are all supported. Although $INCLUDE is disabled by default. Note that $GENERATE's range support up to a maximum of 65535 steps.

Basic usage pattern when reading from a string (z) containing the zone data:

zp := NewZoneParser(strings.NewReader(z), "", "")

for rr, ok := zp.Next(); ok; rr, ok = zp.Next() {
	// Do something with rr
}

if err := zp.Err(); err != nil {
	// log.Println(err)
}

Comments specified after an RR (and on the same line!) are returned too:

foo. IN A 10.0.0.1 ; this is a comment

The text "; this is comment" is returned from Comment. Comments inside the RR are returned concatenated along with the RR. Comments on a line by themselves are discarded.

Callers should not assume all returned data in an Resource Record is syntactically correct, e.g. illegal base64 in RRSIGs will be returned as-is.

type ZoneParser struct {
    // contains filtered or unexported fields
}

func NewZoneParser

func NewZoneParser(r io.Reader, origin, file string) *ZoneParser

NewZoneParser returns an RFC 1035 style zonefile parser that reads from r.

The string file is used in error reporting and to resolve relative $INCLUDE directives. The string origin is used as the initial origin, as if the file would start with an $ORIGIN directive.

func (*ZoneParser) Comment

func (zp *ZoneParser) Comment() string

Comment returns an optional text comment that occurred alongside the RR.

func (*ZoneParser) Err

func (zp *ZoneParser) Err() error

Err returns the first non-EOF error that was encountered by the ZoneParser.

func (*ZoneParser) Next

func (zp *ZoneParser) Next() (RR, bool)

Next advances the parser to the next RR in the zonefile and returns the (RR, true). It will return (nil, false) when the parsing stops, either by reaching the end of the input or an error. After Next returns (nil, false), the Err method will return any error that occurred during parsing.

func (*ZoneParser) SetDefaultTTL

func (zp *ZoneParser) SetDefaultTTL(ttl uint32)

SetDefaultTTL sets the parsers default TTL to ttl.

func (*ZoneParser) SetIncludeAllowed

func (zp *ZoneParser) SetIncludeAllowed(v bool)

SetIncludeAllowed controls whether $INCLUDE directives are allowed. $INCLUDE directives are not supported by default.

The $INCLUDE directive will open and read from a user controlled file on the system. Even if the file is not a valid zonefile, the contents of the file may be revealed in error messages, such as:

/etc/passwd: dns: not a TTL: "root:x:0:0:root:/root:/bin/bash" at line: 1:31
/etc/shadow: dns: not a TTL: "root:$6$<redacted>::0:99999:7:::" at line: 1:125

Subdirectories

Name Synopsis
..
dnsutil Package dnsutil contains higher-level methods useful with the dns package.