Source file src/vendor/golang.org/x/net/dns/dnsmessage/message.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package dnsmessage provides a mostly RFC 1035 compliant implementation of
     6  // DNS message packing and unpacking.
     7  //
     8  // The package also supports messages with Extension Mechanisms for DNS
     9  // (EDNS(0)) as defined in RFC 6891.
    10  //
    11  // This implementation is designed to minimize heap allocations and avoid
    12  // unnecessary packing and unpacking as much as possible.
    13  package dnsmessage
    14  
    15  import (
    16  	"errors"
    17  )
    18  
    19  // Message formats
    20  //
    21  // To add a new Resource Record type:
    22  // 1. Create Resource Record types
    23  //   1.1. Add a Type constant named "Type<name>"
    24  //   1.2. Add the corresponding entry to the typeNames map
    25  //   1.3. Add a [ResourceBody] implementation named "<name>Resource"
    26  // 2. Implement packing
    27  //   2.1. Implement Builder.<name>Resource()
    28  // 3. Implement unpacking
    29  //   3.1. Add the unpacking code to unpackResourceBody()
    30  //   3.2. Implement Parser.<name>Resource()
    31  
    32  // A Type is the type of a DNS Resource Record, as defined in the [IANA registry].
    33  //
    34  // [IANA registry]: https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
    35  type Type uint16
    36  
    37  const (
    38  	// ResourceHeader.Type and Question.Type
    39  	TypeA     Type = 1
    40  	TypeNS    Type = 2
    41  	TypeCNAME Type = 5
    42  	TypeSOA   Type = 6
    43  	TypePTR   Type = 12
    44  	TypeMX    Type = 15
    45  	TypeTXT   Type = 16
    46  	TypeAAAA  Type = 28
    47  	TypeSRV   Type = 33
    48  	TypeOPT   Type = 41
    49  	TypeSVCB  Type = 64
    50  	TypeHTTPS Type = 65
    51  
    52  	// Question.Type
    53  	TypeWKS   Type = 11
    54  	TypeHINFO Type = 13
    55  	TypeMINFO Type = 14
    56  	TypeAXFR  Type = 252
    57  	TypeALL   Type = 255
    58  )
    59  
    60  var typeNames = map[Type]string{
    61  	TypeA:     "TypeA",
    62  	TypeNS:    "TypeNS",
    63  	TypeCNAME: "TypeCNAME",
    64  	TypeSOA:   "TypeSOA",
    65  	TypePTR:   "TypePTR",
    66  	TypeMX:    "TypeMX",
    67  	TypeTXT:   "TypeTXT",
    68  	TypeAAAA:  "TypeAAAA",
    69  	TypeSRV:   "TypeSRV",
    70  	TypeOPT:   "TypeOPT",
    71  	TypeSVCB:  "TypeSVCB",
    72  	TypeHTTPS: "TypeHTTPS",
    73  	TypeWKS:   "TypeWKS",
    74  	TypeHINFO: "TypeHINFO",
    75  	TypeMINFO: "TypeMINFO",
    76  	TypeAXFR:  "TypeAXFR",
    77  	TypeALL:   "TypeALL",
    78  }
    79  
    80  // String implements fmt.Stringer.String.
    81  func (t Type) String() string {
    82  	if n, ok := typeNames[t]; ok {
    83  		return n
    84  	}
    85  	return printUint16(uint16(t))
    86  }
    87  
    88  // GoString implements fmt.GoStringer.GoString.
    89  func (t Type) GoString() string {
    90  	if n, ok := typeNames[t]; ok {
    91  		return "dnsmessage." + n
    92  	}
    93  	return printUint16(uint16(t))
    94  }
    95  
    96  // A Class is a type of network.
    97  type Class uint16
    98  
    99  const (
   100  	// ResourceHeader.Class and Question.Class
   101  	ClassINET   Class = 1
   102  	ClassCSNET  Class = 2
   103  	ClassCHAOS  Class = 3
   104  	ClassHESIOD Class = 4
   105  
   106  	// Question.Class
   107  	ClassANY Class = 255
   108  )
   109  
   110  var classNames = map[Class]string{
   111  	ClassINET:   "ClassINET",
   112  	ClassCSNET:  "ClassCSNET",
   113  	ClassCHAOS:  "ClassCHAOS",
   114  	ClassHESIOD: "ClassHESIOD",
   115  	ClassANY:    "ClassANY",
   116  }
   117  
   118  // String implements fmt.Stringer.String.
   119  func (c Class) String() string {
   120  	if n, ok := classNames[c]; ok {
   121  		return n
   122  	}
   123  	return printUint16(uint16(c))
   124  }
   125  
   126  // GoString implements fmt.GoStringer.GoString.
   127  func (c Class) GoString() string {
   128  	if n, ok := classNames[c]; ok {
   129  		return "dnsmessage." + n
   130  	}
   131  	return printUint16(uint16(c))
   132  }
   133  
   134  // An OpCode is a DNS operation code.
   135  type OpCode uint16
   136  
   137  // GoString implements fmt.GoStringer.GoString.
   138  func (o OpCode) GoString() string {
   139  	return printUint16(uint16(o))
   140  }
   141  
   142  // An RCode is a DNS response status code.
   143  type RCode uint16
   144  
   145  // Header.RCode values.
   146  const (
   147  	RCodeSuccess        RCode = 0 // NoError
   148  	RCodeFormatError    RCode = 1 // FormErr
   149  	RCodeServerFailure  RCode = 2 // ServFail
   150  	RCodeNameError      RCode = 3 // NXDomain
   151  	RCodeNotImplemented RCode = 4 // NotImp
   152  	RCodeRefused        RCode = 5 // Refused
   153  )
   154  
   155  var rCodeNames = map[RCode]string{
   156  	RCodeSuccess:        "RCodeSuccess",
   157  	RCodeFormatError:    "RCodeFormatError",
   158  	RCodeServerFailure:  "RCodeServerFailure",
   159  	RCodeNameError:      "RCodeNameError",
   160  	RCodeNotImplemented: "RCodeNotImplemented",
   161  	RCodeRefused:        "RCodeRefused",
   162  }
   163  
   164  // String implements fmt.Stringer.String.
   165  func (r RCode) String() string {
   166  	if n, ok := rCodeNames[r]; ok {
   167  		return n
   168  	}
   169  	return printUint16(uint16(r))
   170  }
   171  
   172  // GoString implements fmt.GoStringer.GoString.
   173  func (r RCode) GoString() string {
   174  	if n, ok := rCodeNames[r]; ok {
   175  		return "dnsmessage." + n
   176  	}
   177  	return printUint16(uint16(r))
   178  }
   179  
   180  func printPaddedUint8(i uint8) string {
   181  	b := byte(i)
   182  	return string([]byte{
   183  		b/100 + '0',
   184  		b/10%10 + '0',
   185  		b%10 + '0',
   186  	})
   187  }
   188  
   189  func printUint8Bytes(buf []byte, i uint8) []byte {
   190  	b := byte(i)
   191  	if i >= 100 {
   192  		buf = append(buf, b/100+'0')
   193  	}
   194  	if i >= 10 {
   195  		buf = append(buf, b/10%10+'0')
   196  	}
   197  	return append(buf, b%10+'0')
   198  }
   199  
   200  func printByteSlice(b []byte) string {
   201  	if len(b) == 0 {
   202  		return ""
   203  	}
   204  	buf := make([]byte, 0, 5*len(b))
   205  	buf = printUint8Bytes(buf, uint8(b[0]))
   206  	for _, n := range b[1:] {
   207  		buf = append(buf, ',', ' ')
   208  		buf = printUint8Bytes(buf, uint8(n))
   209  	}
   210  	return string(buf)
   211  }
   212  
   213  const hexDigits = "0123456789abcdef"
   214  
   215  func printString(str []byte) string {
   216  	buf := make([]byte, 0, len(str))
   217  	for i := 0; i < len(str); i++ {
   218  		c := str[i]
   219  		if c == '.' || c == '-' || c == ' ' ||
   220  			'A' <= c && c <= 'Z' ||
   221  			'a' <= c && c <= 'z' ||
   222  			'0' <= c && c <= '9' {
   223  			buf = append(buf, c)
   224  			continue
   225  		}
   226  
   227  		upper := c >> 4
   228  		lower := (c << 4) >> 4
   229  		buf = append(
   230  			buf,
   231  			'\\',
   232  			'x',
   233  			hexDigits[upper],
   234  			hexDigits[lower],
   235  		)
   236  	}
   237  	return string(buf)
   238  }
   239  
   240  func printUint16(i uint16) string {
   241  	return printUint32(uint32(i))
   242  }
   243  
   244  func printUint32(i uint32) string {
   245  	// Max value is 4294967295.
   246  	buf := make([]byte, 10)
   247  	for b, d := buf, uint32(1000000000); d > 0; d /= 10 {
   248  		b[0] = byte(i/d%10 + '0')
   249  		if b[0] == '0' && len(b) == len(buf) && len(buf) > 1 {
   250  			buf = buf[1:]
   251  		}
   252  		b = b[1:]
   253  		i %= d
   254  	}
   255  	return string(buf)
   256  }
   257  
   258  func printBool(b bool) string {
   259  	if b {
   260  		return "true"
   261  	}
   262  	return "false"
   263  }
   264  
   265  var (
   266  	// ErrNotStarted indicates that the prerequisite information isn't
   267  	// available yet because the previous records haven't been appropriately
   268  	// parsed, skipped or finished.
   269  	ErrNotStarted = errors.New("parsing/packing of this type isn't available yet")
   270  
   271  	// ErrSectionDone indicated that all records in the section have been
   272  	// parsed or finished.
   273  	ErrSectionDone = errors.New("parsing/packing of this section has completed")
   274  
   275  	errBaseLen            = errors.New("insufficient data for base length type")
   276  	errCalcLen            = errors.New("insufficient data for calculated length type")
   277  	errReserved           = errors.New("segment prefix is reserved")
   278  	errTooManyPtr         = errors.New("too many pointers (>10)")
   279  	errInvalidPtr         = errors.New("invalid pointer")
   280  	errInvalidName        = errors.New("invalid dns name")
   281  	errNilResouceBody     = errors.New("nil resource body")
   282  	errResourceLen        = errors.New("insufficient data for resource body length")
   283  	errSegTooLong         = errors.New("segment length too long")
   284  	errNameTooLong        = errors.New("name too long")
   285  	errZeroSegLen         = errors.New("zero length segment")
   286  	errResTooLong         = errors.New("resource length too long")
   287  	errTooManyQuestions   = errors.New("too many Questions to pack (>65535)")
   288  	errTooManyAnswers     = errors.New("too many Answers to pack (>65535)")
   289  	errTooManyAuthorities = errors.New("too many Authorities to pack (>65535)")
   290  	errTooManyAdditionals = errors.New("too many Additionals to pack (>65535)")
   291  	errNonCanonicalName   = errors.New("name is not in canonical format (it must end with a .)")
   292  	errStringTooLong      = errors.New("character string exceeds maximum length (255)")
   293  	errParamOutOfOrder    = errors.New("parameter out of order")
   294  	errTooLongSVCBValue   = errors.New("value too long (>65535 bytes)")
   295  )
   296  
   297  // Internal constants.
   298  const (
   299  	// packStartingCap is the default initial buffer size allocated during
   300  	// packing.
   301  	//
   302  	// The starting capacity doesn't matter too much, but most DNS responses
   303  	// Will be <= 512 bytes as it is the limit for DNS over UDP.
   304  	packStartingCap = 512
   305  
   306  	// uint16Len is the length (in bytes) of a uint16.
   307  	uint16Len = 2
   308  
   309  	// uint32Len is the length (in bytes) of a uint32.
   310  	uint32Len = 4
   311  
   312  	// headerLen is the length (in bytes) of a DNS header.
   313  	//
   314  	// A header is comprised of 6 uint16s and no padding.
   315  	headerLen = 6 * uint16Len
   316  )
   317  
   318  type nestedError struct {
   319  	// s is the current level's error message.
   320  	s string
   321  
   322  	// err is the nested error.
   323  	err error
   324  }
   325  
   326  // nestedError implements error.Error.
   327  func (e *nestedError) Error() string {
   328  	return e.s + ": " + e.err.Error()
   329  }
   330  
   331  // Header is a representation of a DNS message header.
   332  type Header struct {
   333  	ID                 uint16
   334  	Response           bool
   335  	OpCode             OpCode
   336  	Authoritative      bool
   337  	Truncated          bool
   338  	RecursionDesired   bool
   339  	RecursionAvailable bool
   340  	AuthenticData      bool
   341  	CheckingDisabled   bool
   342  	RCode              RCode
   343  }
   344  
   345  func (m *Header) pack() (id uint16, bits uint16) {
   346  	id = m.ID
   347  	bits = uint16(m.OpCode)<<11 | uint16(m.RCode)
   348  	if m.RecursionAvailable {
   349  		bits |= headerBitRA
   350  	}
   351  	if m.RecursionDesired {
   352  		bits |= headerBitRD
   353  	}
   354  	if m.Truncated {
   355  		bits |= headerBitTC
   356  	}
   357  	if m.Authoritative {
   358  		bits |= headerBitAA
   359  	}
   360  	if m.Response {
   361  		bits |= headerBitQR
   362  	}
   363  	if m.AuthenticData {
   364  		bits |= headerBitAD
   365  	}
   366  	if m.CheckingDisabled {
   367  		bits |= headerBitCD
   368  	}
   369  	return
   370  }
   371  
   372  // GoString implements fmt.GoStringer.GoString.
   373  func (m *Header) GoString() string {
   374  	return "dnsmessage.Header{" +
   375  		"ID: " + printUint16(m.ID) + ", " +
   376  		"Response: " + printBool(m.Response) + ", " +
   377  		"OpCode: " + m.OpCode.GoString() + ", " +
   378  		"Authoritative: " + printBool(m.Authoritative) + ", " +
   379  		"Truncated: " + printBool(m.Truncated) + ", " +
   380  		"RecursionDesired: " + printBool(m.RecursionDesired) + ", " +
   381  		"RecursionAvailable: " + printBool(m.RecursionAvailable) + ", " +
   382  		"AuthenticData: " + printBool(m.AuthenticData) + ", " +
   383  		"CheckingDisabled: " + printBool(m.CheckingDisabled) + ", " +
   384  		"RCode: " + m.RCode.GoString() + "}"
   385  }
   386  
   387  // Message is a representation of a DNS message.
   388  type Message struct {
   389  	Header
   390  	Questions   []Question
   391  	Answers     []Resource
   392  	Authorities []Resource
   393  	Additionals []Resource
   394  }
   395  
   396  type section uint8
   397  
   398  const (
   399  	sectionNotStarted section = iota
   400  	sectionHeader
   401  	sectionQuestions
   402  	sectionAnswers
   403  	sectionAuthorities
   404  	sectionAdditionals
   405  	sectionDone
   406  
   407  	headerBitQR = 1 << 15 // query/response (response=1)
   408  	headerBitAA = 1 << 10 // authoritative
   409  	headerBitTC = 1 << 9  // truncated
   410  	headerBitRD = 1 << 8  // recursion desired
   411  	headerBitRA = 1 << 7  // recursion available
   412  	headerBitAD = 1 << 5  // authentic data
   413  	headerBitCD = 1 << 4  // checking disabled
   414  )
   415  
   416  var sectionNames = map[section]string{
   417  	sectionHeader:      "header",
   418  	sectionQuestions:   "Question",
   419  	sectionAnswers:     "Answer",
   420  	sectionAuthorities: "Authority",
   421  	sectionAdditionals: "Additional",
   422  }
   423  
   424  // header is the wire format for a DNS message header.
   425  type header struct {
   426  	id          uint16
   427  	bits        uint16
   428  	questions   uint16
   429  	answers     uint16
   430  	authorities uint16
   431  	additionals uint16
   432  }
   433  
   434  func (h *header) count(sec section) uint16 {
   435  	switch sec {
   436  	case sectionQuestions:
   437  		return h.questions
   438  	case sectionAnswers:
   439  		return h.answers
   440  	case sectionAuthorities:
   441  		return h.authorities
   442  	case sectionAdditionals:
   443  		return h.additionals
   444  	}
   445  	return 0
   446  }
   447  
   448  // pack appends the wire format of the header to msg.
   449  func (h *header) pack(msg []byte) []byte {
   450  	msg = packUint16(msg, h.id)
   451  	msg = packUint16(msg, h.bits)
   452  	msg = packUint16(msg, h.questions)
   453  	msg = packUint16(msg, h.answers)
   454  	msg = packUint16(msg, h.authorities)
   455  	return packUint16(msg, h.additionals)
   456  }
   457  
   458  func (h *header) unpack(msg []byte, off int) (int, error) {
   459  	newOff := off
   460  	var err error
   461  	if h.id, newOff, err = unpackUint16(msg, newOff); err != nil {
   462  		return off, &nestedError{"id", err}
   463  	}
   464  	if h.bits, newOff, err = unpackUint16(msg, newOff); err != nil {
   465  		return off, &nestedError{"bits", err}
   466  	}
   467  	if h.questions, newOff, err = unpackUint16(msg, newOff); err != nil {
   468  		return off, &nestedError{"questions", err}
   469  	}
   470  	if h.answers, newOff, err = unpackUint16(msg, newOff); err != nil {
   471  		return off, &nestedError{"answers", err}
   472  	}
   473  	if h.authorities, newOff, err = unpackUint16(msg, newOff); err != nil {
   474  		return off, &nestedError{"authorities", err}
   475  	}
   476  	if h.additionals, newOff, err = unpackUint16(msg, newOff); err != nil {
   477  		return off, &nestedError{"additionals", err}
   478  	}
   479  	return newOff, nil
   480  }
   481  
   482  func (h *header) header() Header {
   483  	return Header{
   484  		ID:                 h.id,
   485  		Response:           (h.bits & headerBitQR) != 0,
   486  		OpCode:             OpCode(h.bits>>11) & 0xF,
   487  		Authoritative:      (h.bits & headerBitAA) != 0,
   488  		Truncated:          (h.bits & headerBitTC) != 0,
   489  		RecursionDesired:   (h.bits & headerBitRD) != 0,
   490  		RecursionAvailable: (h.bits & headerBitRA) != 0,
   491  		AuthenticData:      (h.bits & headerBitAD) != 0,
   492  		CheckingDisabled:   (h.bits & headerBitCD) != 0,
   493  		RCode:              RCode(h.bits & 0xF),
   494  	}
   495  }
   496  
   497  // A Resource is a DNS resource record.
   498  type Resource struct {
   499  	Header ResourceHeader
   500  	Body   ResourceBody
   501  }
   502  
   503  func (r *Resource) GoString() string {
   504  	return "dnsmessage.Resource{" +
   505  		"Header: " + r.Header.GoString() +
   506  		", Body: &" + r.Body.GoString() +
   507  		"}"
   508  }
   509  
   510  // A ResourceBody is a DNS resource record minus the header.
   511  type ResourceBody interface {
   512  	// pack packs a Resource except for its header.
   513  	pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error)
   514  
   515  	// realType returns the actual type of the Resource. This is used to
   516  	// fill in the header Type field.
   517  	realType() Type
   518  
   519  	// GoString implements fmt.GoStringer.GoString.
   520  	GoString() string
   521  }
   522  
   523  // pack appends the wire format of the Resource to msg.
   524  func (r *Resource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
   525  	if r.Body == nil {
   526  		return msg, errNilResouceBody
   527  	}
   528  	oldMsg := msg
   529  	r.Header.Type = r.Body.realType()
   530  	msg, lenOff, err := r.Header.pack(msg, compression, compressionOff)
   531  	if err != nil {
   532  		return msg, &nestedError{"ResourceHeader", err}
   533  	}
   534  	preLen := len(msg)
   535  	msg, err = r.Body.pack(msg, compression, compressionOff)
   536  	if err != nil {
   537  		return msg, &nestedError{"content", err}
   538  	}
   539  	if err := r.Header.fixLen(msg, lenOff, preLen); err != nil {
   540  		return oldMsg, err
   541  	}
   542  	return msg, nil
   543  }
   544  
   545  // A Parser allows incrementally parsing a DNS message.
   546  //
   547  // When parsing is started, the Header is parsed. Next, each Question can be
   548  // either parsed or skipped. Alternatively, all Questions can be skipped at
   549  // once. When all Questions have been parsed, attempting to parse Questions
   550  // will return the [ErrSectionDone] error.
   551  // After all Questions have been either parsed or skipped, all
   552  // Answers, Authorities and Additionals can be either parsed or skipped in the
   553  // same way, and each type of Resource must be fully parsed or skipped before
   554  // proceeding to the next type of Resource.
   555  //
   556  // Parser is safe to copy to preserve the parsing state.
   557  //
   558  // Note that there is no requirement to fully skip or parse the message.
   559  type Parser struct {
   560  	msg    []byte
   561  	header header
   562  
   563  	section         section
   564  	off             int
   565  	index           int
   566  	resHeaderValid  bool
   567  	resHeaderOffset int
   568  	resHeaderType   Type
   569  	resHeaderLength uint16
   570  }
   571  
   572  // Start parses the header and enables the parsing of Questions.
   573  func (p *Parser) Start(msg []byte) (Header, error) {
   574  	if p.msg != nil {
   575  		*p = Parser{}
   576  	}
   577  	p.msg = msg
   578  	var err error
   579  	if p.off, err = p.header.unpack(msg, 0); err != nil {
   580  		return Header{}, &nestedError{"unpacking header", err}
   581  	}
   582  	p.section = sectionQuestions
   583  	return p.header.header(), nil
   584  }
   585  
   586  func (p *Parser) checkAdvance(sec section) error {
   587  	if p.section < sec {
   588  		return ErrNotStarted
   589  	}
   590  	if p.section > sec {
   591  		return ErrSectionDone
   592  	}
   593  	p.resHeaderValid = false
   594  	if p.index == int(p.header.count(sec)) {
   595  		p.index = 0
   596  		p.section++
   597  		return ErrSectionDone
   598  	}
   599  	return nil
   600  }
   601  
   602  func (p *Parser) resource(sec section) (Resource, error) {
   603  	var r Resource
   604  	var err error
   605  	r.Header, err = p.resourceHeader(sec)
   606  	if err != nil {
   607  		return r, err
   608  	}
   609  	p.resHeaderValid = false
   610  	r.Body, p.off, err = unpackResourceBody(p.msg, p.off, r.Header)
   611  	if err != nil {
   612  		return Resource{}, &nestedError{"unpacking " + sectionNames[sec], err}
   613  	}
   614  	p.index++
   615  	return r, nil
   616  }
   617  
   618  func (p *Parser) resourceHeader(sec section) (ResourceHeader, error) {
   619  	if p.resHeaderValid {
   620  		p.off = p.resHeaderOffset
   621  	}
   622  
   623  	if err := p.checkAdvance(sec); err != nil {
   624  		return ResourceHeader{}, err
   625  	}
   626  	var hdr ResourceHeader
   627  	off, err := hdr.unpack(p.msg, p.off)
   628  	if err != nil {
   629  		return ResourceHeader{}, err
   630  	}
   631  	p.resHeaderValid = true
   632  	p.resHeaderOffset = p.off
   633  	p.resHeaderType = hdr.Type
   634  	p.resHeaderLength = hdr.Length
   635  	p.off = off
   636  	return hdr, nil
   637  }
   638  
   639  func (p *Parser) skipResource(sec section) error {
   640  	if p.resHeaderValid && p.section == sec {
   641  		newOff := p.off + int(p.resHeaderLength)
   642  		if newOff > len(p.msg) {
   643  			return errResourceLen
   644  		}
   645  		p.off = newOff
   646  		p.resHeaderValid = false
   647  		p.index++
   648  		return nil
   649  	}
   650  	if err := p.checkAdvance(sec); err != nil {
   651  		return err
   652  	}
   653  	var err error
   654  	p.off, err = skipResource(p.msg, p.off)
   655  	if err != nil {
   656  		return &nestedError{"skipping: " + sectionNames[sec], err}
   657  	}
   658  	p.index++
   659  	return nil
   660  }
   661  
   662  // Question parses a single Question.
   663  func (p *Parser) Question() (Question, error) {
   664  	if err := p.checkAdvance(sectionQuestions); err != nil {
   665  		return Question{}, err
   666  	}
   667  	var name Name
   668  	off, err := name.unpack(p.msg, p.off)
   669  	if err != nil {
   670  		return Question{}, &nestedError{"unpacking Question.Name", err}
   671  	}
   672  	typ, off, err := unpackType(p.msg, off)
   673  	if err != nil {
   674  		return Question{}, &nestedError{"unpacking Question.Type", err}
   675  	}
   676  	class, off, err := unpackClass(p.msg, off)
   677  	if err != nil {
   678  		return Question{}, &nestedError{"unpacking Question.Class", err}
   679  	}
   680  	p.off = off
   681  	p.index++
   682  	return Question{name, typ, class}, nil
   683  }
   684  
   685  // AllQuestions parses all Questions.
   686  func (p *Parser) AllQuestions() ([]Question, error) {
   687  	// Multiple questions are valid according to the spec,
   688  	// but servers don't actually support them. There will
   689  	// be at most one question here.
   690  	//
   691  	// Do not pre-allocate based on info in p.header, since
   692  	// the data is untrusted.
   693  	qs := []Question{}
   694  	for {
   695  		q, err := p.Question()
   696  		if err == ErrSectionDone {
   697  			return qs, nil
   698  		}
   699  		if err != nil {
   700  			return nil, err
   701  		}
   702  		qs = append(qs, q)
   703  	}
   704  }
   705  
   706  // SkipQuestion skips a single Question.
   707  func (p *Parser) SkipQuestion() error {
   708  	if err := p.checkAdvance(sectionQuestions); err != nil {
   709  		return err
   710  	}
   711  	off, err := skipName(p.msg, p.off)
   712  	if err != nil {
   713  		return &nestedError{"skipping Question Name", err}
   714  	}
   715  	if off, err = skipType(p.msg, off); err != nil {
   716  		return &nestedError{"skipping Question Type", err}
   717  	}
   718  	if off, err = skipClass(p.msg, off); err != nil {
   719  		return &nestedError{"skipping Question Class", err}
   720  	}
   721  	p.off = off
   722  	p.index++
   723  	return nil
   724  }
   725  
   726  // SkipAllQuestions skips all Questions.
   727  func (p *Parser) SkipAllQuestions() error {
   728  	for {
   729  		if err := p.SkipQuestion(); err == ErrSectionDone {
   730  			return nil
   731  		} else if err != nil {
   732  			return err
   733  		}
   734  	}
   735  }
   736  
   737  // AnswerHeader parses a single Answer ResourceHeader.
   738  func (p *Parser) AnswerHeader() (ResourceHeader, error) {
   739  	return p.resourceHeader(sectionAnswers)
   740  }
   741  
   742  // Answer parses a single Answer Resource.
   743  func (p *Parser) Answer() (Resource, error) {
   744  	return p.resource(sectionAnswers)
   745  }
   746  
   747  // AllAnswers parses all Answer Resources.
   748  func (p *Parser) AllAnswers() ([]Resource, error) {
   749  	// The most common query is for A/AAAA, which usually returns
   750  	// a handful of IPs.
   751  	//
   752  	// Pre-allocate up to a certain limit, since p.header is
   753  	// untrusted data.
   754  	n := min(int(p.header.answers), 20)
   755  	as := make([]Resource, 0, n)
   756  	for {
   757  		a, err := p.Answer()
   758  		if err == ErrSectionDone {
   759  			return as, nil
   760  		}
   761  		if err != nil {
   762  			return nil, err
   763  		}
   764  		as = append(as, a)
   765  	}
   766  }
   767  
   768  // SkipAnswer skips a single Answer Resource.
   769  //
   770  // It does not perform a complete validation of the resource header, which means
   771  // it may return a nil error when the [AnswerHeader] would actually return an error.
   772  func (p *Parser) SkipAnswer() error {
   773  	return p.skipResource(sectionAnswers)
   774  }
   775  
   776  // SkipAllAnswers skips all Answer Resources.
   777  func (p *Parser) SkipAllAnswers() error {
   778  	for {
   779  		if err := p.SkipAnswer(); err == ErrSectionDone {
   780  			return nil
   781  		} else if err != nil {
   782  			return err
   783  		}
   784  	}
   785  }
   786  
   787  // AuthorityHeader parses a single Authority ResourceHeader.
   788  func (p *Parser) AuthorityHeader() (ResourceHeader, error) {
   789  	return p.resourceHeader(sectionAuthorities)
   790  }
   791  
   792  // Authority parses a single Authority Resource.
   793  func (p *Parser) Authority() (Resource, error) {
   794  	return p.resource(sectionAuthorities)
   795  }
   796  
   797  // AllAuthorities parses all Authority Resources.
   798  func (p *Parser) AllAuthorities() ([]Resource, error) {
   799  	// Authorities contains SOA in case of NXDOMAIN and friends,
   800  	// otherwise it is empty.
   801  	//
   802  	// Pre-allocate up to a certain limit, since p.header is
   803  	// untrusted data.
   804  	n := min(int(p.header.authorities), 10)
   805  	as := make([]Resource, 0, n)
   806  	for {
   807  		a, err := p.Authority()
   808  		if err == ErrSectionDone {
   809  			return as, nil
   810  		}
   811  		if err != nil {
   812  			return nil, err
   813  		}
   814  		as = append(as, a)
   815  	}
   816  }
   817  
   818  // SkipAuthority skips a single Authority Resource.
   819  //
   820  // It does not perform a complete validation of the resource header, which means
   821  // it may return a nil error when the [AuthorityHeader] would actually return an error.
   822  func (p *Parser) SkipAuthority() error {
   823  	return p.skipResource(sectionAuthorities)
   824  }
   825  
   826  // SkipAllAuthorities skips all Authority Resources.
   827  func (p *Parser) SkipAllAuthorities() error {
   828  	for {
   829  		if err := p.SkipAuthority(); err == ErrSectionDone {
   830  			return nil
   831  		} else if err != nil {
   832  			return err
   833  		}
   834  	}
   835  }
   836  
   837  // AdditionalHeader parses a single Additional ResourceHeader.
   838  func (p *Parser) AdditionalHeader() (ResourceHeader, error) {
   839  	return p.resourceHeader(sectionAdditionals)
   840  }
   841  
   842  // Additional parses a single Additional Resource.
   843  func (p *Parser) Additional() (Resource, error) {
   844  	return p.resource(sectionAdditionals)
   845  }
   846  
   847  // AllAdditionals parses all Additional Resources.
   848  func (p *Parser) AllAdditionals() ([]Resource, error) {
   849  	// Additionals usually contain OPT, and sometimes A/AAAA
   850  	// glue records.
   851  	//
   852  	// Pre-allocate up to a certain limit, since p.header is
   853  	// untrusted data.
   854  	n := min(int(p.header.additionals), 10)
   855  	as := make([]Resource, 0, n)
   856  	for {
   857  		a, err := p.Additional()
   858  		if err == ErrSectionDone {
   859  			return as, nil
   860  		}
   861  		if err != nil {
   862  			return nil, err
   863  		}
   864  		as = append(as, a)
   865  	}
   866  }
   867  
   868  // SkipAdditional skips a single Additional Resource.
   869  //
   870  // It does not perform a complete validation of the resource header, which means
   871  // it may return a nil error when the [AdditionalHeader] would actually return an error.
   872  func (p *Parser) SkipAdditional() error {
   873  	return p.skipResource(sectionAdditionals)
   874  }
   875  
   876  // SkipAllAdditionals skips all Additional Resources.
   877  func (p *Parser) SkipAllAdditionals() error {
   878  	for {
   879  		if err := p.SkipAdditional(); err == ErrSectionDone {
   880  			return nil
   881  		} else if err != nil {
   882  			return err
   883  		}
   884  	}
   885  }
   886  
   887  // CNAMEResource parses a single CNAMEResource.
   888  //
   889  // One of the XXXHeader methods must have been called before calling this
   890  // method.
   891  func (p *Parser) CNAMEResource() (CNAMEResource, error) {
   892  	if !p.resHeaderValid || p.resHeaderType != TypeCNAME {
   893  		return CNAMEResource{}, ErrNotStarted
   894  	}
   895  	r, err := unpackCNAMEResource(p.msg, p.off)
   896  	if err != nil {
   897  		return CNAMEResource{}, err
   898  	}
   899  	p.off += int(p.resHeaderLength)
   900  	p.resHeaderValid = false
   901  	p.index++
   902  	return r, nil
   903  }
   904  
   905  // MXResource parses a single MXResource.
   906  //
   907  // One of the XXXHeader methods must have been called before calling this
   908  // method.
   909  func (p *Parser) MXResource() (MXResource, error) {
   910  	if !p.resHeaderValid || p.resHeaderType != TypeMX {
   911  		return MXResource{}, ErrNotStarted
   912  	}
   913  	r, err := unpackMXResource(p.msg, p.off)
   914  	if err != nil {
   915  		return MXResource{}, err
   916  	}
   917  	p.off += int(p.resHeaderLength)
   918  	p.resHeaderValid = false
   919  	p.index++
   920  	return r, nil
   921  }
   922  
   923  // NSResource parses a single NSResource.
   924  //
   925  // One of the XXXHeader methods must have been called before calling this
   926  // method.
   927  func (p *Parser) NSResource() (NSResource, error) {
   928  	if !p.resHeaderValid || p.resHeaderType != TypeNS {
   929  		return NSResource{}, ErrNotStarted
   930  	}
   931  	r, err := unpackNSResource(p.msg, p.off)
   932  	if err != nil {
   933  		return NSResource{}, err
   934  	}
   935  	p.off += int(p.resHeaderLength)
   936  	p.resHeaderValid = false
   937  	p.index++
   938  	return r, nil
   939  }
   940  
   941  // PTRResource parses a single PTRResource.
   942  //
   943  // One of the XXXHeader methods must have been called before calling this
   944  // method.
   945  func (p *Parser) PTRResource() (PTRResource, error) {
   946  	if !p.resHeaderValid || p.resHeaderType != TypePTR {
   947  		return PTRResource{}, ErrNotStarted
   948  	}
   949  	r, err := unpackPTRResource(p.msg, p.off)
   950  	if err != nil {
   951  		return PTRResource{}, err
   952  	}
   953  	p.off += int(p.resHeaderLength)
   954  	p.resHeaderValid = false
   955  	p.index++
   956  	return r, nil
   957  }
   958  
   959  // SOAResource parses a single SOAResource.
   960  //
   961  // One of the XXXHeader methods must have been called before calling this
   962  // method.
   963  func (p *Parser) SOAResource() (SOAResource, error) {
   964  	if !p.resHeaderValid || p.resHeaderType != TypeSOA {
   965  		return SOAResource{}, ErrNotStarted
   966  	}
   967  	r, err := unpackSOAResource(p.msg, p.off)
   968  	if err != nil {
   969  		return SOAResource{}, err
   970  	}
   971  	p.off += int(p.resHeaderLength)
   972  	p.resHeaderValid = false
   973  	p.index++
   974  	return r, nil
   975  }
   976  
   977  // TXTResource parses a single TXTResource.
   978  //
   979  // One of the XXXHeader methods must have been called before calling this
   980  // method.
   981  func (p *Parser) TXTResource() (TXTResource, error) {
   982  	if !p.resHeaderValid || p.resHeaderType != TypeTXT {
   983  		return TXTResource{}, ErrNotStarted
   984  	}
   985  	r, err := unpackTXTResource(p.msg, p.off, p.resHeaderLength)
   986  	if err != nil {
   987  		return TXTResource{}, err
   988  	}
   989  	p.off += int(p.resHeaderLength)
   990  	p.resHeaderValid = false
   991  	p.index++
   992  	return r, nil
   993  }
   994  
   995  // SRVResource parses a single SRVResource.
   996  //
   997  // One of the XXXHeader methods must have been called before calling this
   998  // method.
   999  func (p *Parser) SRVResource() (SRVResource, error) {
  1000  	if !p.resHeaderValid || p.resHeaderType != TypeSRV {
  1001  		return SRVResource{}, ErrNotStarted
  1002  	}
  1003  	r, err := unpackSRVResource(p.msg, p.off)
  1004  	if err != nil {
  1005  		return SRVResource{}, err
  1006  	}
  1007  	p.off += int(p.resHeaderLength)
  1008  	p.resHeaderValid = false
  1009  	p.index++
  1010  	return r, nil
  1011  }
  1012  
  1013  // AResource parses a single AResource.
  1014  //
  1015  // One of the XXXHeader methods must have been called before calling this
  1016  // method.
  1017  func (p *Parser) AResource() (AResource, error) {
  1018  	if !p.resHeaderValid || p.resHeaderType != TypeA {
  1019  		return AResource{}, ErrNotStarted
  1020  	}
  1021  	r, err := unpackAResource(p.msg, p.off)
  1022  	if err != nil {
  1023  		return AResource{}, err
  1024  	}
  1025  	p.off += int(p.resHeaderLength)
  1026  	p.resHeaderValid = false
  1027  	p.index++
  1028  	return r, nil
  1029  }
  1030  
  1031  // AAAAResource parses a single AAAAResource.
  1032  //
  1033  // One of the XXXHeader methods must have been called before calling this
  1034  // method.
  1035  func (p *Parser) AAAAResource() (AAAAResource, error) {
  1036  	if !p.resHeaderValid || p.resHeaderType != TypeAAAA {
  1037  		return AAAAResource{}, ErrNotStarted
  1038  	}
  1039  	r, err := unpackAAAAResource(p.msg, p.off)
  1040  	if err != nil {
  1041  		return AAAAResource{}, err
  1042  	}
  1043  	p.off += int(p.resHeaderLength)
  1044  	p.resHeaderValid = false
  1045  	p.index++
  1046  	return r, nil
  1047  }
  1048  
  1049  // OPTResource parses a single OPTResource.
  1050  //
  1051  // One of the XXXHeader methods must have been called before calling this
  1052  // method.
  1053  func (p *Parser) OPTResource() (OPTResource, error) {
  1054  	if !p.resHeaderValid || p.resHeaderType != TypeOPT {
  1055  		return OPTResource{}, ErrNotStarted
  1056  	}
  1057  	r, err := unpackOPTResource(p.msg, p.off, p.resHeaderLength)
  1058  	if err != nil {
  1059  		return OPTResource{}, err
  1060  	}
  1061  	p.off += int(p.resHeaderLength)
  1062  	p.resHeaderValid = false
  1063  	p.index++
  1064  	return r, nil
  1065  }
  1066  
  1067  // UnknownResource parses a single UnknownResource.
  1068  //
  1069  // One of the XXXHeader methods must have been called before calling this
  1070  // method.
  1071  func (p *Parser) UnknownResource() (UnknownResource, error) {
  1072  	if !p.resHeaderValid {
  1073  		return UnknownResource{}, ErrNotStarted
  1074  	}
  1075  	r, err := unpackUnknownResource(p.resHeaderType, p.msg, p.off, p.resHeaderLength)
  1076  	if err != nil {
  1077  		return UnknownResource{}, err
  1078  	}
  1079  	p.off += int(p.resHeaderLength)
  1080  	p.resHeaderValid = false
  1081  	p.index++
  1082  	return r, nil
  1083  }
  1084  
  1085  // Unpack parses a full Message.
  1086  func (m *Message) Unpack(msg []byte) error {
  1087  	var p Parser
  1088  	var err error
  1089  	if m.Header, err = p.Start(msg); err != nil {
  1090  		return err
  1091  	}
  1092  	if m.Questions, err = p.AllQuestions(); err != nil {
  1093  		return err
  1094  	}
  1095  	if m.Answers, err = p.AllAnswers(); err != nil {
  1096  		return err
  1097  	}
  1098  	if m.Authorities, err = p.AllAuthorities(); err != nil {
  1099  		return err
  1100  	}
  1101  	if m.Additionals, err = p.AllAdditionals(); err != nil {
  1102  		return err
  1103  	}
  1104  	return nil
  1105  }
  1106  
  1107  // Pack packs a full Message.
  1108  func (m *Message) Pack() ([]byte, error) {
  1109  	return m.AppendPack(make([]byte, 0, packStartingCap))
  1110  }
  1111  
  1112  // AppendPack is like Pack but appends the full Message to b and returns the
  1113  // extended buffer.
  1114  func (m *Message) AppendPack(b []byte) ([]byte, error) {
  1115  	// Validate the lengths. It is very unlikely that anyone will try to
  1116  	// pack more than 65535 of any particular type, but it is possible and
  1117  	// we should fail gracefully.
  1118  	if len(m.Questions) > int(^uint16(0)) {
  1119  		return nil, errTooManyQuestions
  1120  	}
  1121  	if len(m.Answers) > int(^uint16(0)) {
  1122  		return nil, errTooManyAnswers
  1123  	}
  1124  	if len(m.Authorities) > int(^uint16(0)) {
  1125  		return nil, errTooManyAuthorities
  1126  	}
  1127  	if len(m.Additionals) > int(^uint16(0)) {
  1128  		return nil, errTooManyAdditionals
  1129  	}
  1130  
  1131  	var h header
  1132  	h.id, h.bits = m.Header.pack()
  1133  
  1134  	h.questions = uint16(len(m.Questions))
  1135  	h.answers = uint16(len(m.Answers))
  1136  	h.authorities = uint16(len(m.Authorities))
  1137  	h.additionals = uint16(len(m.Additionals))
  1138  
  1139  	compressionOff := len(b)
  1140  	msg := h.pack(b)
  1141  
  1142  	// RFC 1035 allows (but does not require) compression for packing. RFC
  1143  	// 1035 requires unpacking implementations to support compression, so
  1144  	// unconditionally enabling it is fine.
  1145  	//
  1146  	// DNS lookups are typically done over UDP, and RFC 1035 states that UDP
  1147  	// DNS messages can be a maximum of 512 bytes long. Without compression,
  1148  	// many DNS response messages are over this limit, so enabling
  1149  	// compression will help ensure compliance.
  1150  	compression := map[string]uint16{}
  1151  
  1152  	for i := range m.Questions {
  1153  		var err error
  1154  		if msg, err = m.Questions[i].pack(msg, compression, compressionOff); err != nil {
  1155  			return nil, &nestedError{"packing Question", err}
  1156  		}
  1157  	}
  1158  	for i := range m.Answers {
  1159  		var err error
  1160  		if msg, err = m.Answers[i].pack(msg, compression, compressionOff); err != nil {
  1161  			return nil, &nestedError{"packing Answer", err}
  1162  		}
  1163  	}
  1164  	for i := range m.Authorities {
  1165  		var err error
  1166  		if msg, err = m.Authorities[i].pack(msg, compression, compressionOff); err != nil {
  1167  			return nil, &nestedError{"packing Authority", err}
  1168  		}
  1169  	}
  1170  	for i := range m.Additionals {
  1171  		var err error
  1172  		if msg, err = m.Additionals[i].pack(msg, compression, compressionOff); err != nil {
  1173  			return nil, &nestedError{"packing Additional", err}
  1174  		}
  1175  	}
  1176  
  1177  	return msg, nil
  1178  }
  1179  
  1180  // GoString implements fmt.GoStringer.GoString.
  1181  func (m *Message) GoString() string {
  1182  	s := "dnsmessage.Message{Header: " + m.Header.GoString() + ", " +
  1183  		"Questions: []dnsmessage.Question{"
  1184  	if len(m.Questions) > 0 {
  1185  		s += m.Questions[0].GoString()
  1186  		for _, q := range m.Questions[1:] {
  1187  			s += ", " + q.GoString()
  1188  		}
  1189  	}
  1190  	s += "}, Answers: []dnsmessage.Resource{"
  1191  	if len(m.Answers) > 0 {
  1192  		s += m.Answers[0].GoString()
  1193  		for _, a := range m.Answers[1:] {
  1194  			s += ", " + a.GoString()
  1195  		}
  1196  	}
  1197  	s += "}, Authorities: []dnsmessage.Resource{"
  1198  	if len(m.Authorities) > 0 {
  1199  		s += m.Authorities[0].GoString()
  1200  		for _, a := range m.Authorities[1:] {
  1201  			s += ", " + a.GoString()
  1202  		}
  1203  	}
  1204  	s += "}, Additionals: []dnsmessage.Resource{"
  1205  	if len(m.Additionals) > 0 {
  1206  		s += m.Additionals[0].GoString()
  1207  		for _, a := range m.Additionals[1:] {
  1208  			s += ", " + a.GoString()
  1209  		}
  1210  	}
  1211  	return s + "}}"
  1212  }
  1213  
  1214  // A Builder allows incrementally packing a DNS message.
  1215  //
  1216  // Example usage:
  1217  //
  1218  //	buf := make([]byte, 2, 514)
  1219  //	b := NewBuilder(buf, Header{...})
  1220  //	b.EnableCompression()
  1221  //	// Optionally start a section and add things to that section.
  1222  //	// Repeat adding sections as necessary.
  1223  //	buf, err := b.Finish()
  1224  //	// If err is nil, buf[2:] will contain the built bytes.
  1225  type Builder struct {
  1226  	// msg is the storage for the message being built.
  1227  	msg []byte
  1228  
  1229  	// section keeps track of the current section being built.
  1230  	section section
  1231  
  1232  	// header keeps track of what should go in the header when Finish is
  1233  	// called.
  1234  	header header
  1235  
  1236  	// start is the starting index of the bytes allocated in msg for header.
  1237  	start int
  1238  
  1239  	// compression is a mapping from name suffixes to their starting index
  1240  	// in msg.
  1241  	compression map[string]uint16
  1242  }
  1243  
  1244  // NewBuilder creates a new builder with compression disabled.
  1245  //
  1246  // Note: Most users will want to immediately enable compression with the
  1247  // EnableCompression method. See that method's comment for why you may or may
  1248  // not want to enable compression.
  1249  //
  1250  // The DNS message is appended to the provided initial buffer buf (which may be
  1251  // nil) as it is built. The final message is returned by the (*Builder).Finish
  1252  // method, which includes buf[:len(buf)] and may return the same underlying
  1253  // array if there was sufficient capacity in the slice.
  1254  func NewBuilder(buf []byte, h Header) Builder {
  1255  	if buf == nil {
  1256  		buf = make([]byte, 0, packStartingCap)
  1257  	}
  1258  	b := Builder{msg: buf, start: len(buf)}
  1259  	b.header.id, b.header.bits = h.pack()
  1260  	var hb [headerLen]byte
  1261  	b.msg = append(b.msg, hb[:]...)
  1262  	b.section = sectionHeader
  1263  	return b
  1264  }
  1265  
  1266  // EnableCompression enables compression in the Builder.
  1267  //
  1268  // Leaving compression disabled avoids compression related allocations, but can
  1269  // result in larger message sizes. Be careful with this mode as it can cause
  1270  // messages to exceed the UDP size limit.
  1271  //
  1272  // According to RFC 1035, section 4.1.4, the use of compression is optional, but
  1273  // all implementations must accept both compressed and uncompressed DNS
  1274  // messages.
  1275  //
  1276  // Compression should be enabled before any sections are added for best results.
  1277  func (b *Builder) EnableCompression() {
  1278  	b.compression = map[string]uint16{}
  1279  }
  1280  
  1281  func (b *Builder) startCheck(s section) error {
  1282  	if b.section <= sectionNotStarted {
  1283  		return ErrNotStarted
  1284  	}
  1285  	if b.section > s {
  1286  		return ErrSectionDone
  1287  	}
  1288  	return nil
  1289  }
  1290  
  1291  // StartQuestions prepares the builder for packing Questions.
  1292  func (b *Builder) StartQuestions() error {
  1293  	if err := b.startCheck(sectionQuestions); err != nil {
  1294  		return err
  1295  	}
  1296  	b.section = sectionQuestions
  1297  	return nil
  1298  }
  1299  
  1300  // StartAnswers prepares the builder for packing Answers.
  1301  func (b *Builder) StartAnswers() error {
  1302  	if err := b.startCheck(sectionAnswers); err != nil {
  1303  		return err
  1304  	}
  1305  	b.section = sectionAnswers
  1306  	return nil
  1307  }
  1308  
  1309  // StartAuthorities prepares the builder for packing Authorities.
  1310  func (b *Builder) StartAuthorities() error {
  1311  	if err := b.startCheck(sectionAuthorities); err != nil {
  1312  		return err
  1313  	}
  1314  	b.section = sectionAuthorities
  1315  	return nil
  1316  }
  1317  
  1318  // StartAdditionals prepares the builder for packing Additionals.
  1319  func (b *Builder) StartAdditionals() error {
  1320  	if err := b.startCheck(sectionAdditionals); err != nil {
  1321  		return err
  1322  	}
  1323  	b.section = sectionAdditionals
  1324  	return nil
  1325  }
  1326  
  1327  func (b *Builder) incrementSectionCount() error {
  1328  	var count *uint16
  1329  	var err error
  1330  	switch b.section {
  1331  	case sectionQuestions:
  1332  		count = &b.header.questions
  1333  		err = errTooManyQuestions
  1334  	case sectionAnswers:
  1335  		count = &b.header.answers
  1336  		err = errTooManyAnswers
  1337  	case sectionAuthorities:
  1338  		count = &b.header.authorities
  1339  		err = errTooManyAuthorities
  1340  	case sectionAdditionals:
  1341  		count = &b.header.additionals
  1342  		err = errTooManyAdditionals
  1343  	}
  1344  	if *count == ^uint16(0) {
  1345  		return err
  1346  	}
  1347  	*count++
  1348  	return nil
  1349  }
  1350  
  1351  // Question adds a single Question.
  1352  func (b *Builder) Question(q Question) error {
  1353  	if b.section < sectionQuestions {
  1354  		return ErrNotStarted
  1355  	}
  1356  	if b.section > sectionQuestions {
  1357  		return ErrSectionDone
  1358  	}
  1359  	msg, err := q.pack(b.msg, b.compression, b.start)
  1360  	if err != nil {
  1361  		return err
  1362  	}
  1363  	if err := b.incrementSectionCount(); err != nil {
  1364  		return err
  1365  	}
  1366  	b.msg = msg
  1367  	return nil
  1368  }
  1369  
  1370  func (b *Builder) checkResourceSection() error {
  1371  	if b.section < sectionAnswers {
  1372  		return ErrNotStarted
  1373  	}
  1374  	if b.section > sectionAdditionals {
  1375  		return ErrSectionDone
  1376  	}
  1377  	return nil
  1378  }
  1379  
  1380  // CNAMEResource adds a single CNAMEResource.
  1381  func (b *Builder) CNAMEResource(h ResourceHeader, r CNAMEResource) error {
  1382  	if err := b.checkResourceSection(); err != nil {
  1383  		return err
  1384  	}
  1385  	h.Type = r.realType()
  1386  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1387  	if err != nil {
  1388  		return &nestedError{"ResourceHeader", err}
  1389  	}
  1390  	preLen := len(msg)
  1391  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1392  		return &nestedError{"CNAMEResource body", err}
  1393  	}
  1394  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1395  		return err
  1396  	}
  1397  	if err := b.incrementSectionCount(); err != nil {
  1398  		return err
  1399  	}
  1400  	b.msg = msg
  1401  	return nil
  1402  }
  1403  
  1404  // MXResource adds a single MXResource.
  1405  func (b *Builder) MXResource(h ResourceHeader, r MXResource) error {
  1406  	if err := b.checkResourceSection(); err != nil {
  1407  		return err
  1408  	}
  1409  	h.Type = r.realType()
  1410  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1411  	if err != nil {
  1412  		return &nestedError{"ResourceHeader", err}
  1413  	}
  1414  	preLen := len(msg)
  1415  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1416  		return &nestedError{"MXResource body", err}
  1417  	}
  1418  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1419  		return err
  1420  	}
  1421  	if err := b.incrementSectionCount(); err != nil {
  1422  		return err
  1423  	}
  1424  	b.msg = msg
  1425  	return nil
  1426  }
  1427  
  1428  // NSResource adds a single NSResource.
  1429  func (b *Builder) NSResource(h ResourceHeader, r NSResource) error {
  1430  	if err := b.checkResourceSection(); err != nil {
  1431  		return err
  1432  	}
  1433  	h.Type = r.realType()
  1434  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1435  	if err != nil {
  1436  		return &nestedError{"ResourceHeader", err}
  1437  	}
  1438  	preLen := len(msg)
  1439  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1440  		return &nestedError{"NSResource body", err}
  1441  	}
  1442  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1443  		return err
  1444  	}
  1445  	if err := b.incrementSectionCount(); err != nil {
  1446  		return err
  1447  	}
  1448  	b.msg = msg
  1449  	return nil
  1450  }
  1451  
  1452  // PTRResource adds a single PTRResource.
  1453  func (b *Builder) PTRResource(h ResourceHeader, r PTRResource) error {
  1454  	if err := b.checkResourceSection(); err != nil {
  1455  		return err
  1456  	}
  1457  	h.Type = r.realType()
  1458  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1459  	if err != nil {
  1460  		return &nestedError{"ResourceHeader", err}
  1461  	}
  1462  	preLen := len(msg)
  1463  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1464  		return &nestedError{"PTRResource body", err}
  1465  	}
  1466  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1467  		return err
  1468  	}
  1469  	if err := b.incrementSectionCount(); err != nil {
  1470  		return err
  1471  	}
  1472  	b.msg = msg
  1473  	return nil
  1474  }
  1475  
  1476  // SOAResource adds a single SOAResource.
  1477  func (b *Builder) SOAResource(h ResourceHeader, r SOAResource) error {
  1478  	if err := b.checkResourceSection(); err != nil {
  1479  		return err
  1480  	}
  1481  	h.Type = r.realType()
  1482  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1483  	if err != nil {
  1484  		return &nestedError{"ResourceHeader", err}
  1485  	}
  1486  	preLen := len(msg)
  1487  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1488  		return &nestedError{"SOAResource body", err}
  1489  	}
  1490  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1491  		return err
  1492  	}
  1493  	if err := b.incrementSectionCount(); err != nil {
  1494  		return err
  1495  	}
  1496  	b.msg = msg
  1497  	return nil
  1498  }
  1499  
  1500  // TXTResource adds a single TXTResource.
  1501  func (b *Builder) TXTResource(h ResourceHeader, r TXTResource) error {
  1502  	if err := b.checkResourceSection(); err != nil {
  1503  		return err
  1504  	}
  1505  	h.Type = r.realType()
  1506  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1507  	if err != nil {
  1508  		return &nestedError{"ResourceHeader", err}
  1509  	}
  1510  	preLen := len(msg)
  1511  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1512  		return &nestedError{"TXTResource body", err}
  1513  	}
  1514  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1515  		return err
  1516  	}
  1517  	if err := b.incrementSectionCount(); err != nil {
  1518  		return err
  1519  	}
  1520  	b.msg = msg
  1521  	return nil
  1522  }
  1523  
  1524  // SRVResource adds a single SRVResource.
  1525  func (b *Builder) SRVResource(h ResourceHeader, r SRVResource) error {
  1526  	if err := b.checkResourceSection(); err != nil {
  1527  		return err
  1528  	}
  1529  	h.Type = r.realType()
  1530  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1531  	if err != nil {
  1532  		return &nestedError{"ResourceHeader", err}
  1533  	}
  1534  	preLen := len(msg)
  1535  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1536  		return &nestedError{"SRVResource body", err}
  1537  	}
  1538  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1539  		return err
  1540  	}
  1541  	if err := b.incrementSectionCount(); err != nil {
  1542  		return err
  1543  	}
  1544  	b.msg = msg
  1545  	return nil
  1546  }
  1547  
  1548  // AResource adds a single AResource.
  1549  func (b *Builder) AResource(h ResourceHeader, r AResource) error {
  1550  	if err := b.checkResourceSection(); err != nil {
  1551  		return err
  1552  	}
  1553  	h.Type = r.realType()
  1554  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1555  	if err != nil {
  1556  		return &nestedError{"ResourceHeader", err}
  1557  	}
  1558  	preLen := len(msg)
  1559  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1560  		return &nestedError{"AResource body", err}
  1561  	}
  1562  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1563  		return err
  1564  	}
  1565  	if err := b.incrementSectionCount(); err != nil {
  1566  		return err
  1567  	}
  1568  	b.msg = msg
  1569  	return nil
  1570  }
  1571  
  1572  // AAAAResource adds a single AAAAResource.
  1573  func (b *Builder) AAAAResource(h ResourceHeader, r AAAAResource) error {
  1574  	if err := b.checkResourceSection(); err != nil {
  1575  		return err
  1576  	}
  1577  	h.Type = r.realType()
  1578  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1579  	if err != nil {
  1580  		return &nestedError{"ResourceHeader", err}
  1581  	}
  1582  	preLen := len(msg)
  1583  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1584  		return &nestedError{"AAAAResource body", err}
  1585  	}
  1586  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1587  		return err
  1588  	}
  1589  	if err := b.incrementSectionCount(); err != nil {
  1590  		return err
  1591  	}
  1592  	b.msg = msg
  1593  	return nil
  1594  }
  1595  
  1596  // OPTResource adds a single OPTResource.
  1597  func (b *Builder) OPTResource(h ResourceHeader, r OPTResource) error {
  1598  	if err := b.checkResourceSection(); err != nil {
  1599  		return err
  1600  	}
  1601  	h.Type = r.realType()
  1602  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1603  	if err != nil {
  1604  		return &nestedError{"ResourceHeader", err}
  1605  	}
  1606  	preLen := len(msg)
  1607  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1608  		return &nestedError{"OPTResource body", err}
  1609  	}
  1610  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1611  		return err
  1612  	}
  1613  	if err := b.incrementSectionCount(); err != nil {
  1614  		return err
  1615  	}
  1616  	b.msg = msg
  1617  	return nil
  1618  }
  1619  
  1620  // UnknownResource adds a single UnknownResource.
  1621  func (b *Builder) UnknownResource(h ResourceHeader, r UnknownResource) error {
  1622  	if err := b.checkResourceSection(); err != nil {
  1623  		return err
  1624  	}
  1625  	h.Type = r.realType()
  1626  	msg, lenOff, err := h.pack(b.msg, b.compression, b.start)
  1627  	if err != nil {
  1628  		return &nestedError{"ResourceHeader", err}
  1629  	}
  1630  	preLen := len(msg)
  1631  	if msg, err = r.pack(msg, b.compression, b.start); err != nil {
  1632  		return &nestedError{"UnknownResource body", err}
  1633  	}
  1634  	if err := h.fixLen(msg, lenOff, preLen); err != nil {
  1635  		return err
  1636  	}
  1637  	if err := b.incrementSectionCount(); err != nil {
  1638  		return err
  1639  	}
  1640  	b.msg = msg
  1641  	return nil
  1642  }
  1643  
  1644  // Finish ends message building and generates a binary message.
  1645  func (b *Builder) Finish() ([]byte, error) {
  1646  	if b.section < sectionHeader {
  1647  		return nil, ErrNotStarted
  1648  	}
  1649  	b.section = sectionDone
  1650  	// Space for the header was allocated in NewBuilder.
  1651  	b.header.pack(b.msg[b.start:b.start])
  1652  	return b.msg, nil
  1653  }
  1654  
  1655  // A ResourceHeader is the header of a DNS resource record. There are
  1656  // many types of DNS resource records, but they all share the same header.
  1657  type ResourceHeader struct {
  1658  	// Name is the domain name for which this resource record pertains.
  1659  	Name Name
  1660  
  1661  	// Type is the type of DNS resource record.
  1662  	//
  1663  	// This field will be set automatically during packing.
  1664  	Type Type
  1665  
  1666  	// Class is the class of network to which this DNS resource record
  1667  	// pertains.
  1668  	Class Class
  1669  
  1670  	// TTL is the length of time (measured in seconds) which this resource
  1671  	// record is valid for (time to live). All Resources in a set should
  1672  	// have the same TTL (RFC 2181 Section 5.2).
  1673  	TTL uint32
  1674  
  1675  	// Length is the length of data in the resource record after the header.
  1676  	//
  1677  	// This field will be set automatically during packing.
  1678  	Length uint16
  1679  }
  1680  
  1681  // GoString implements fmt.GoStringer.GoString.
  1682  func (h *ResourceHeader) GoString() string {
  1683  	return "dnsmessage.ResourceHeader{" +
  1684  		"Name: " + h.Name.GoString() + ", " +
  1685  		"Type: " + h.Type.GoString() + ", " +
  1686  		"Class: " + h.Class.GoString() + ", " +
  1687  		"TTL: " + printUint32(h.TTL) + ", " +
  1688  		"Length: " + printUint16(h.Length) + "}"
  1689  }
  1690  
  1691  // pack appends the wire format of the ResourceHeader to oldMsg.
  1692  //
  1693  // lenOff is the offset in msg where the Length field was packed.
  1694  func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]uint16, compressionOff int) (msg []byte, lenOff int, err error) {
  1695  	msg = oldMsg
  1696  	if msg, err = h.Name.pack(msg, compression, compressionOff); err != nil {
  1697  		return oldMsg, 0, &nestedError{"Name", err}
  1698  	}
  1699  	msg = packType(msg, h.Type)
  1700  	msg = packClass(msg, h.Class)
  1701  	msg = packUint32(msg, h.TTL)
  1702  	lenOff = len(msg)
  1703  	msg = packUint16(msg, h.Length)
  1704  	return msg, lenOff, nil
  1705  }
  1706  
  1707  func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) {
  1708  	newOff := off
  1709  	var err error
  1710  	if newOff, err = h.Name.unpack(msg, newOff); err != nil {
  1711  		return off, &nestedError{"Name", err}
  1712  	}
  1713  	if h.Type, newOff, err = unpackType(msg, newOff); err != nil {
  1714  		return off, &nestedError{"Type", err}
  1715  	}
  1716  	if h.Class, newOff, err = unpackClass(msg, newOff); err != nil {
  1717  		return off, &nestedError{"Class", err}
  1718  	}
  1719  	if h.TTL, newOff, err = unpackUint32(msg, newOff); err != nil {
  1720  		return off, &nestedError{"TTL", err}
  1721  	}
  1722  	if h.Length, newOff, err = unpackUint16(msg, newOff); err != nil {
  1723  		return off, &nestedError{"Length", err}
  1724  	}
  1725  	return newOff, nil
  1726  }
  1727  
  1728  // fixLen updates a packed ResourceHeader to include the length of the
  1729  // ResourceBody.
  1730  //
  1731  // lenOff is the offset of the ResourceHeader.Length field in msg.
  1732  //
  1733  // preLen is the length that msg was before the ResourceBody was packed.
  1734  func (h *ResourceHeader) fixLen(msg []byte, lenOff int, preLen int) error {
  1735  	conLen := len(msg) - preLen
  1736  	if conLen > int(^uint16(0)) {
  1737  		return errResTooLong
  1738  	}
  1739  
  1740  	// Fill in the length now that we know how long the content is.
  1741  	packUint16(msg[lenOff:lenOff], uint16(conLen))
  1742  	h.Length = uint16(conLen)
  1743  
  1744  	return nil
  1745  }
  1746  
  1747  // EDNS(0) wire constants.
  1748  const (
  1749  	edns0Version = 0
  1750  
  1751  	edns0DNSSECOK     = 0x00008000
  1752  	ednsVersionMask   = 0x00ff0000
  1753  	edns0DNSSECOKMask = 0x00ff8000
  1754  )
  1755  
  1756  // SetEDNS0 configures h for EDNS(0).
  1757  //
  1758  // The provided extRCode must be an extended RCode.
  1759  func (h *ResourceHeader) SetEDNS0(udpPayloadLen int, extRCode RCode, dnssecOK bool) error {
  1760  	h.Name = Name{Data: [255]byte{'.'}, Length: 1} // RFC 6891 section 6.1.2
  1761  	h.Type = TypeOPT
  1762  	h.Class = Class(udpPayloadLen)
  1763  	h.TTL = uint32(extRCode) >> 4 << 24
  1764  	if dnssecOK {
  1765  		h.TTL |= edns0DNSSECOK
  1766  	}
  1767  	return nil
  1768  }
  1769  
  1770  // DNSSECAllowed reports whether the DNSSEC OK bit is set.
  1771  func (h *ResourceHeader) DNSSECAllowed() bool {
  1772  	return h.TTL&edns0DNSSECOKMask == edns0DNSSECOK // RFC 6891 section 6.1.3
  1773  }
  1774  
  1775  // ExtendedRCode returns an extended RCode.
  1776  //
  1777  // The provided rcode must be the RCode in DNS message header.
  1778  func (h *ResourceHeader) ExtendedRCode(rcode RCode) RCode {
  1779  	if h.TTL&ednsVersionMask == edns0Version { // RFC 6891 section 6.1.3
  1780  		return RCode(h.TTL>>24<<4) | rcode
  1781  	}
  1782  	return rcode
  1783  }
  1784  
  1785  func skipResource(msg []byte, off int) (int, error) {
  1786  	newOff, err := skipName(msg, off)
  1787  	if err != nil {
  1788  		return off, &nestedError{"Name", err}
  1789  	}
  1790  	if newOff, err = skipType(msg, newOff); err != nil {
  1791  		return off, &nestedError{"Type", err}
  1792  	}
  1793  	if newOff, err = skipClass(msg, newOff); err != nil {
  1794  		return off, &nestedError{"Class", err}
  1795  	}
  1796  	if newOff, err = skipUint32(msg, newOff); err != nil {
  1797  		return off, &nestedError{"TTL", err}
  1798  	}
  1799  	length, newOff, err := unpackUint16(msg, newOff)
  1800  	if err != nil {
  1801  		return off, &nestedError{"Length", err}
  1802  	}
  1803  	if newOff += int(length); newOff > len(msg) {
  1804  		return off, errResourceLen
  1805  	}
  1806  	return newOff, nil
  1807  }
  1808  
  1809  // packUint16 appends the wire format of field to msg.
  1810  func packUint16(msg []byte, field uint16) []byte {
  1811  	return append(msg, byte(field>>8), byte(field))
  1812  }
  1813  
  1814  func unpackUint16(msg []byte, off int) (uint16, int, error) {
  1815  	if off+uint16Len > len(msg) {
  1816  		return 0, off, errBaseLen
  1817  	}
  1818  	return uint16(msg[off])<<8 | uint16(msg[off+1]), off + uint16Len, nil
  1819  }
  1820  
  1821  func skipUint16(msg []byte, off int) (int, error) {
  1822  	if off+uint16Len > len(msg) {
  1823  		return off, errBaseLen
  1824  	}
  1825  	return off + uint16Len, nil
  1826  }
  1827  
  1828  // packType appends the wire format of field to msg.
  1829  func packType(msg []byte, field Type) []byte {
  1830  	return packUint16(msg, uint16(field))
  1831  }
  1832  
  1833  func unpackType(msg []byte, off int) (Type, int, error) {
  1834  	t, o, err := unpackUint16(msg, off)
  1835  	return Type(t), o, err
  1836  }
  1837  
  1838  func skipType(msg []byte, off int) (int, error) {
  1839  	return skipUint16(msg, off)
  1840  }
  1841  
  1842  // packClass appends the wire format of field to msg.
  1843  func packClass(msg []byte, field Class) []byte {
  1844  	return packUint16(msg, uint16(field))
  1845  }
  1846  
  1847  func unpackClass(msg []byte, off int) (Class, int, error) {
  1848  	c, o, err := unpackUint16(msg, off)
  1849  	return Class(c), o, err
  1850  }
  1851  
  1852  func skipClass(msg []byte, off int) (int, error) {
  1853  	return skipUint16(msg, off)
  1854  }
  1855  
  1856  // packUint32 appends the wire format of field to msg.
  1857  func packUint32(msg []byte, field uint32) []byte {
  1858  	return append(
  1859  		msg,
  1860  		byte(field>>24),
  1861  		byte(field>>16),
  1862  		byte(field>>8),
  1863  		byte(field),
  1864  	)
  1865  }
  1866  
  1867  func unpackUint32(msg []byte, off int) (uint32, int, error) {
  1868  	if off+uint32Len > len(msg) {
  1869  		return 0, off, errBaseLen
  1870  	}
  1871  	v := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])
  1872  	return v, off + uint32Len, nil
  1873  }
  1874  
  1875  func skipUint32(msg []byte, off int) (int, error) {
  1876  	if off+uint32Len > len(msg) {
  1877  		return off, errBaseLen
  1878  	}
  1879  	return off + uint32Len, nil
  1880  }
  1881  
  1882  // packText appends the wire format of field to msg.
  1883  func packText(msg []byte, field string) ([]byte, error) {
  1884  	l := len(field)
  1885  	if l > 255 {
  1886  		return nil, errStringTooLong
  1887  	}
  1888  	msg = append(msg, byte(l))
  1889  	msg = append(msg, field...)
  1890  
  1891  	return msg, nil
  1892  }
  1893  
  1894  func unpackText(msg []byte, off int) (string, int, error) {
  1895  	if off >= len(msg) {
  1896  		return "", off, errBaseLen
  1897  	}
  1898  	beginOff := off + 1
  1899  	endOff := beginOff + int(msg[off])
  1900  	if endOff > len(msg) {
  1901  		return "", off, errCalcLen
  1902  	}
  1903  	return string(msg[beginOff:endOff]), endOff, nil
  1904  }
  1905  
  1906  // packBytes appends the wire format of field to msg.
  1907  func packBytes(msg []byte, field []byte) []byte {
  1908  	return append(msg, field...)
  1909  }
  1910  
  1911  func unpackBytes(msg []byte, off int, field []byte) (int, error) {
  1912  	newOff := off + len(field)
  1913  	if newOff > len(msg) {
  1914  		return off, errBaseLen
  1915  	}
  1916  	copy(field, msg[off:newOff])
  1917  	return newOff, nil
  1918  }
  1919  
  1920  const nonEncodedNameMax = 254
  1921  
  1922  // A Name is a non-encoded and non-escaped domain name. It is used instead of strings to avoid
  1923  // allocations.
  1924  type Name struct {
  1925  	Data   [255]byte
  1926  	Length uint8
  1927  }
  1928  
  1929  // NewName creates a new Name from a string.
  1930  func NewName(name string) (Name, error) {
  1931  	n := Name{Length: uint8(len(name))}
  1932  	if len(name) > len(n.Data) {
  1933  		return Name{}, errCalcLen
  1934  	}
  1935  	copy(n.Data[:], name)
  1936  	return n, nil
  1937  }
  1938  
  1939  // MustNewName creates a new Name from a string and panics on error.
  1940  func MustNewName(name string) Name {
  1941  	n, err := NewName(name)
  1942  	if err != nil {
  1943  		panic("creating name: " + err.Error())
  1944  	}
  1945  	return n
  1946  }
  1947  
  1948  // String implements fmt.Stringer.String.
  1949  //
  1950  // Note: characters inside the labels are not escaped in any way.
  1951  func (n Name) String() string {
  1952  	return string(n.Data[:n.Length])
  1953  }
  1954  
  1955  // GoString implements fmt.GoStringer.GoString.
  1956  func (n *Name) GoString() string {
  1957  	return `dnsmessage.MustNewName("` + printString(n.Data[:n.Length]) + `")`
  1958  }
  1959  
  1960  // pack appends the wire format of the Name to msg.
  1961  //
  1962  // Domain names are a sequence of counted strings split at the dots. They end
  1963  // with a zero-length string. Compression can be used to reuse domain suffixes.
  1964  //
  1965  // The compression map will be updated with new domain suffixes. If compression
  1966  // is nil, compression will not be used.
  1967  func (n *Name) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  1968  	oldMsg := msg
  1969  
  1970  	if n.Length > nonEncodedNameMax {
  1971  		return nil, errNameTooLong
  1972  	}
  1973  
  1974  	// Add a trailing dot to canonicalize name.
  1975  	if n.Length == 0 || n.Data[n.Length-1] != '.' {
  1976  		return oldMsg, errNonCanonicalName
  1977  	}
  1978  
  1979  	// Allow root domain.
  1980  	if n.Data[0] == '.' && n.Length == 1 {
  1981  		return append(msg, 0), nil
  1982  	}
  1983  
  1984  	var nameAsStr string
  1985  
  1986  	// Emit sequence of counted strings, chopping at dots.
  1987  	for i, begin := 0, 0; i < int(n.Length); i++ {
  1988  		// Check for the end of the segment.
  1989  		if n.Data[i] == '.' {
  1990  			// The two most significant bits have special meaning.
  1991  			// It isn't allowed for segments to be long enough to
  1992  			// need them.
  1993  			if i-begin >= 1<<6 {
  1994  				return oldMsg, errSegTooLong
  1995  			}
  1996  
  1997  			// Segments must have a non-zero length.
  1998  			if i-begin == 0 {
  1999  				return oldMsg, errZeroSegLen
  2000  			}
  2001  
  2002  			msg = append(msg, byte(i-begin))
  2003  
  2004  			for j := begin; j < i; j++ {
  2005  				msg = append(msg, n.Data[j])
  2006  			}
  2007  
  2008  			begin = i + 1
  2009  			continue
  2010  		}
  2011  
  2012  		// We can only compress domain suffixes starting with a new
  2013  		// segment. A pointer is two bytes with the two most significant
  2014  		// bits set to 1 to indicate that it is a pointer.
  2015  		if (i == 0 || n.Data[i-1] == '.') && compression != nil {
  2016  			if ptr, ok := compression[string(n.Data[i:n.Length])]; ok {
  2017  				// Hit. Emit a pointer instead of the rest of
  2018  				// the domain.
  2019  				return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil
  2020  			}
  2021  
  2022  			// Miss. Add the suffix to the compression table if the
  2023  			// offset can be stored in the available 14 bits.
  2024  			newPtr := len(msg) - compressionOff
  2025  			if newPtr <= int(^uint16(0)>>2) {
  2026  				if nameAsStr == "" {
  2027  					// allocate n.Data on the heap once, to avoid allocating it
  2028  					// multiple times (for next labels).
  2029  					nameAsStr = string(n.Data[:n.Length])
  2030  				}
  2031  				compression[nameAsStr[i:]] = uint16(newPtr)
  2032  			}
  2033  		}
  2034  	}
  2035  	return append(msg, 0), nil
  2036  }
  2037  
  2038  // unpack unpacks a domain name.
  2039  func (n *Name) unpack(msg []byte, off int) (int, error) {
  2040  	// currOff is the current working offset.
  2041  	currOff := off
  2042  
  2043  	// newOff is the offset where the next record will start. Pointers lead
  2044  	// to data that belongs to other names and thus doesn't count towards to
  2045  	// the usage of this name.
  2046  	newOff := off
  2047  
  2048  	// ptr is the number of pointers followed.
  2049  	var ptr int
  2050  
  2051  	// Name is a slice representation of the name data.
  2052  	name := n.Data[:0]
  2053  
  2054  Loop:
  2055  	for {
  2056  		if currOff >= len(msg) {
  2057  			return off, errBaseLen
  2058  		}
  2059  		c := int(msg[currOff])
  2060  		currOff++
  2061  		switch c & 0xC0 {
  2062  		case 0x00: // String segment
  2063  			if c == 0x00 {
  2064  				// A zero length signals the end of the name.
  2065  				break Loop
  2066  			}
  2067  			endOff := currOff + c
  2068  			if endOff > len(msg) {
  2069  				return off, errCalcLen
  2070  			}
  2071  
  2072  			// Reject names containing dots.
  2073  			// See issue golang/go#56246
  2074  			for _, v := range msg[currOff:endOff] {
  2075  				if v == '.' {
  2076  					return off, errInvalidName
  2077  				}
  2078  			}
  2079  			// Reject names that are too long while unpacking
  2080  			// See issue golang/go#77540
  2081  			if len(name)+(endOff-currOff) >= nonEncodedNameMax {
  2082  				return off, errNameTooLong
  2083  			}
  2084  			name = append(name, msg[currOff:endOff]...)
  2085  			name = append(name, '.')
  2086  			currOff = endOff
  2087  		case 0xC0: // Pointer
  2088  			if currOff >= len(msg) {
  2089  				return off, errInvalidPtr
  2090  			}
  2091  			c1 := msg[currOff]
  2092  			currOff++
  2093  			if ptr == 0 {
  2094  				newOff = currOff
  2095  			}
  2096  			// Don't follow too many pointers, maybe there's a loop.
  2097  			if ptr++; ptr > 10 {
  2098  				return off, errTooManyPtr
  2099  			}
  2100  			currOff = (c^0xC0)<<8 | int(c1)
  2101  		default:
  2102  			// Prefixes 0x80 and 0x40 are reserved.
  2103  			return off, errReserved
  2104  		}
  2105  	}
  2106  	if len(name) == 0 {
  2107  		name = append(name, '.')
  2108  	}
  2109  	n.Length = uint8(len(name))
  2110  	if ptr == 0 {
  2111  		newOff = currOff
  2112  	}
  2113  	return newOff, nil
  2114  }
  2115  
  2116  func skipName(msg []byte, off int) (int, error) {
  2117  	// newOff is the offset where the next record will start. Pointers lead
  2118  	// to data that belongs to other names and thus doesn't count towards to
  2119  	// the usage of this name.
  2120  	newOff := off
  2121  
  2122  Loop:
  2123  	for {
  2124  		if newOff >= len(msg) {
  2125  			return off, errBaseLen
  2126  		}
  2127  		c := int(msg[newOff])
  2128  		newOff++
  2129  		switch c & 0xC0 {
  2130  		case 0x00:
  2131  			if c == 0x00 {
  2132  				// A zero length signals the end of the name.
  2133  				break Loop
  2134  			}
  2135  			// literal string
  2136  			newOff += c
  2137  			if newOff > len(msg) {
  2138  				return off, errCalcLen
  2139  			}
  2140  		case 0xC0:
  2141  			// Pointer to somewhere else in msg.
  2142  
  2143  			// Pointers are two bytes.
  2144  			newOff++
  2145  
  2146  			// Don't follow the pointer as the data here has ended.
  2147  			break Loop
  2148  		default:
  2149  			// Prefixes 0x80 and 0x40 are reserved.
  2150  			return off, errReserved
  2151  		}
  2152  	}
  2153  
  2154  	return newOff, nil
  2155  }
  2156  
  2157  // A Question is a DNS query.
  2158  type Question struct {
  2159  	Name  Name
  2160  	Type  Type
  2161  	Class Class
  2162  }
  2163  
  2164  // pack appends the wire format of the Question to msg.
  2165  func (q *Question) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2166  	msg, err := q.Name.pack(msg, compression, compressionOff)
  2167  	if err != nil {
  2168  		return msg, &nestedError{"Name", err}
  2169  	}
  2170  	msg = packType(msg, q.Type)
  2171  	return packClass(msg, q.Class), nil
  2172  }
  2173  
  2174  // GoString implements fmt.GoStringer.GoString.
  2175  func (q *Question) GoString() string {
  2176  	return "dnsmessage.Question{" +
  2177  		"Name: " + q.Name.GoString() + ", " +
  2178  		"Type: " + q.Type.GoString() + ", " +
  2179  		"Class: " + q.Class.GoString() + "}"
  2180  }
  2181  
  2182  func unpackResourceBody(msg []byte, off int, hdr ResourceHeader) (ResourceBody, int, error) {
  2183  	var (
  2184  		r    ResourceBody
  2185  		err  error
  2186  		name string
  2187  	)
  2188  	switch hdr.Type {
  2189  	case TypeA:
  2190  		var rb AResource
  2191  		rb, err = unpackAResource(msg, off)
  2192  		r = &rb
  2193  		name = "A"
  2194  	case TypeNS:
  2195  		var rb NSResource
  2196  		rb, err = unpackNSResource(msg, off)
  2197  		r = &rb
  2198  		name = "NS"
  2199  	case TypeCNAME:
  2200  		var rb CNAMEResource
  2201  		rb, err = unpackCNAMEResource(msg, off)
  2202  		r = &rb
  2203  		name = "CNAME"
  2204  	case TypeSOA:
  2205  		var rb SOAResource
  2206  		rb, err = unpackSOAResource(msg, off)
  2207  		r = &rb
  2208  		name = "SOA"
  2209  	case TypePTR:
  2210  		var rb PTRResource
  2211  		rb, err = unpackPTRResource(msg, off)
  2212  		r = &rb
  2213  		name = "PTR"
  2214  	case TypeMX:
  2215  		var rb MXResource
  2216  		rb, err = unpackMXResource(msg, off)
  2217  		r = &rb
  2218  		name = "MX"
  2219  	case TypeTXT:
  2220  		var rb TXTResource
  2221  		rb, err = unpackTXTResource(msg, off, hdr.Length)
  2222  		r = &rb
  2223  		name = "TXT"
  2224  	case TypeAAAA:
  2225  		var rb AAAAResource
  2226  		rb, err = unpackAAAAResource(msg, off)
  2227  		r = &rb
  2228  		name = "AAAA"
  2229  	case TypeSRV:
  2230  		var rb SRVResource
  2231  		rb, err = unpackSRVResource(msg, off)
  2232  		r = &rb
  2233  		name = "SRV"
  2234  	case TypeSVCB:
  2235  		var rb SVCBResource
  2236  		rb, err = unpackSVCBResource(msg, off, hdr.Length)
  2237  		r = &rb
  2238  		name = "SVCB"
  2239  	case TypeHTTPS:
  2240  		var rb HTTPSResource
  2241  		rb.SVCBResource, err = unpackSVCBResource(msg, off, hdr.Length)
  2242  		r = &rb
  2243  		name = "HTTPS"
  2244  	case TypeOPT:
  2245  		var rb OPTResource
  2246  		rb, err = unpackOPTResource(msg, off, hdr.Length)
  2247  		r = &rb
  2248  		name = "OPT"
  2249  	default:
  2250  		var rb UnknownResource
  2251  		rb, err = unpackUnknownResource(hdr.Type, msg, off, hdr.Length)
  2252  		r = &rb
  2253  		name = "Unknown"
  2254  	}
  2255  	if err != nil {
  2256  		return nil, off, &nestedError{name + " record", err}
  2257  	}
  2258  	return r, off + int(hdr.Length), nil
  2259  }
  2260  
  2261  // A CNAMEResource is a CNAME Resource record.
  2262  type CNAMEResource struct {
  2263  	CNAME Name
  2264  }
  2265  
  2266  func (r *CNAMEResource) realType() Type {
  2267  	return TypeCNAME
  2268  }
  2269  
  2270  // pack appends the wire format of the CNAMEResource to msg.
  2271  func (r *CNAMEResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2272  	return r.CNAME.pack(msg, compression, compressionOff)
  2273  }
  2274  
  2275  // GoString implements fmt.GoStringer.GoString.
  2276  func (r *CNAMEResource) GoString() string {
  2277  	return "dnsmessage.CNAMEResource{CNAME: " + r.CNAME.GoString() + "}"
  2278  }
  2279  
  2280  func unpackCNAMEResource(msg []byte, off int) (CNAMEResource, error) {
  2281  	var cname Name
  2282  	if _, err := cname.unpack(msg, off); err != nil {
  2283  		return CNAMEResource{}, err
  2284  	}
  2285  	return CNAMEResource{cname}, nil
  2286  }
  2287  
  2288  // An MXResource is an MX Resource record.
  2289  type MXResource struct {
  2290  	Pref uint16
  2291  	MX   Name
  2292  }
  2293  
  2294  func (r *MXResource) realType() Type {
  2295  	return TypeMX
  2296  }
  2297  
  2298  // pack appends the wire format of the MXResource to msg.
  2299  func (r *MXResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2300  	oldMsg := msg
  2301  	msg = packUint16(msg, r.Pref)
  2302  	msg, err := r.MX.pack(msg, compression, compressionOff)
  2303  	if err != nil {
  2304  		return oldMsg, &nestedError{"MXResource.MX", err}
  2305  	}
  2306  	return msg, nil
  2307  }
  2308  
  2309  // GoString implements fmt.GoStringer.GoString.
  2310  func (r *MXResource) GoString() string {
  2311  	return "dnsmessage.MXResource{" +
  2312  		"Pref: " + printUint16(r.Pref) + ", " +
  2313  		"MX: " + r.MX.GoString() + "}"
  2314  }
  2315  
  2316  func unpackMXResource(msg []byte, off int) (MXResource, error) {
  2317  	pref, off, err := unpackUint16(msg, off)
  2318  	if err != nil {
  2319  		return MXResource{}, &nestedError{"Pref", err}
  2320  	}
  2321  	var mx Name
  2322  	if _, err := mx.unpack(msg, off); err != nil {
  2323  		return MXResource{}, &nestedError{"MX", err}
  2324  	}
  2325  	return MXResource{pref, mx}, nil
  2326  }
  2327  
  2328  // An NSResource is an NS Resource record.
  2329  type NSResource struct {
  2330  	NS Name
  2331  }
  2332  
  2333  func (r *NSResource) realType() Type {
  2334  	return TypeNS
  2335  }
  2336  
  2337  // pack appends the wire format of the NSResource to msg.
  2338  func (r *NSResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2339  	return r.NS.pack(msg, compression, compressionOff)
  2340  }
  2341  
  2342  // GoString implements fmt.GoStringer.GoString.
  2343  func (r *NSResource) GoString() string {
  2344  	return "dnsmessage.NSResource{NS: " + r.NS.GoString() + "}"
  2345  }
  2346  
  2347  func unpackNSResource(msg []byte, off int) (NSResource, error) {
  2348  	var ns Name
  2349  	if _, err := ns.unpack(msg, off); err != nil {
  2350  		return NSResource{}, err
  2351  	}
  2352  	return NSResource{ns}, nil
  2353  }
  2354  
  2355  // A PTRResource is a PTR Resource record.
  2356  type PTRResource struct {
  2357  	PTR Name
  2358  }
  2359  
  2360  func (r *PTRResource) realType() Type {
  2361  	return TypePTR
  2362  }
  2363  
  2364  // pack appends the wire format of the PTRResource to msg.
  2365  func (r *PTRResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2366  	return r.PTR.pack(msg, compression, compressionOff)
  2367  }
  2368  
  2369  // GoString implements fmt.GoStringer.GoString.
  2370  func (r *PTRResource) GoString() string {
  2371  	return "dnsmessage.PTRResource{PTR: " + r.PTR.GoString() + "}"
  2372  }
  2373  
  2374  func unpackPTRResource(msg []byte, off int) (PTRResource, error) {
  2375  	var ptr Name
  2376  	if _, err := ptr.unpack(msg, off); err != nil {
  2377  		return PTRResource{}, err
  2378  	}
  2379  	return PTRResource{ptr}, nil
  2380  }
  2381  
  2382  // An SOAResource is an SOA Resource record.
  2383  type SOAResource struct {
  2384  	NS      Name
  2385  	MBox    Name
  2386  	Serial  uint32
  2387  	Refresh uint32
  2388  	Retry   uint32
  2389  	Expire  uint32
  2390  
  2391  	// MinTTL the is the default TTL of Resources records which did not
  2392  	// contain a TTL value and the TTL of negative responses. (RFC 2308
  2393  	// Section 4)
  2394  	MinTTL uint32
  2395  }
  2396  
  2397  func (r *SOAResource) realType() Type {
  2398  	return TypeSOA
  2399  }
  2400  
  2401  // pack appends the wire format of the SOAResource to msg.
  2402  func (r *SOAResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2403  	oldMsg := msg
  2404  	msg, err := r.NS.pack(msg, compression, compressionOff)
  2405  	if err != nil {
  2406  		return oldMsg, &nestedError{"SOAResource.NS", err}
  2407  	}
  2408  	msg, err = r.MBox.pack(msg, compression, compressionOff)
  2409  	if err != nil {
  2410  		return oldMsg, &nestedError{"SOAResource.MBox", err}
  2411  	}
  2412  	msg = packUint32(msg, r.Serial)
  2413  	msg = packUint32(msg, r.Refresh)
  2414  	msg = packUint32(msg, r.Retry)
  2415  	msg = packUint32(msg, r.Expire)
  2416  	return packUint32(msg, r.MinTTL), nil
  2417  }
  2418  
  2419  // GoString implements fmt.GoStringer.GoString.
  2420  func (r *SOAResource) GoString() string {
  2421  	return "dnsmessage.SOAResource{" +
  2422  		"NS: " + r.NS.GoString() + ", " +
  2423  		"MBox: " + r.MBox.GoString() + ", " +
  2424  		"Serial: " + printUint32(r.Serial) + ", " +
  2425  		"Refresh: " + printUint32(r.Refresh) + ", " +
  2426  		"Retry: " + printUint32(r.Retry) + ", " +
  2427  		"Expire: " + printUint32(r.Expire) + ", " +
  2428  		"MinTTL: " + printUint32(r.MinTTL) + "}"
  2429  }
  2430  
  2431  func unpackSOAResource(msg []byte, off int) (SOAResource, error) {
  2432  	var ns Name
  2433  	off, err := ns.unpack(msg, off)
  2434  	if err != nil {
  2435  		return SOAResource{}, &nestedError{"NS", err}
  2436  	}
  2437  	var mbox Name
  2438  	if off, err = mbox.unpack(msg, off); err != nil {
  2439  		return SOAResource{}, &nestedError{"MBox", err}
  2440  	}
  2441  	serial, off, err := unpackUint32(msg, off)
  2442  	if err != nil {
  2443  		return SOAResource{}, &nestedError{"Serial", err}
  2444  	}
  2445  	refresh, off, err := unpackUint32(msg, off)
  2446  	if err != nil {
  2447  		return SOAResource{}, &nestedError{"Refresh", err}
  2448  	}
  2449  	retry, off, err := unpackUint32(msg, off)
  2450  	if err != nil {
  2451  		return SOAResource{}, &nestedError{"Retry", err}
  2452  	}
  2453  	expire, off, err := unpackUint32(msg, off)
  2454  	if err != nil {
  2455  		return SOAResource{}, &nestedError{"Expire", err}
  2456  	}
  2457  	minTTL, _, err := unpackUint32(msg, off)
  2458  	if err != nil {
  2459  		return SOAResource{}, &nestedError{"MinTTL", err}
  2460  	}
  2461  	return SOAResource{ns, mbox, serial, refresh, retry, expire, minTTL}, nil
  2462  }
  2463  
  2464  // A TXTResource is a TXT Resource record.
  2465  type TXTResource struct {
  2466  	TXT []string
  2467  }
  2468  
  2469  func (r *TXTResource) realType() Type {
  2470  	return TypeTXT
  2471  }
  2472  
  2473  // pack appends the wire format of the TXTResource to msg.
  2474  func (r *TXTResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2475  	oldMsg := msg
  2476  	for _, s := range r.TXT {
  2477  		var err error
  2478  		msg, err = packText(msg, s)
  2479  		if err != nil {
  2480  			return oldMsg, err
  2481  		}
  2482  	}
  2483  	return msg, nil
  2484  }
  2485  
  2486  // GoString implements fmt.GoStringer.GoString.
  2487  func (r *TXTResource) GoString() string {
  2488  	s := "dnsmessage.TXTResource{TXT: []string{"
  2489  	if len(r.TXT) == 0 {
  2490  		return s + "}}"
  2491  	}
  2492  	s += `"` + printString([]byte(r.TXT[0]))
  2493  	for _, t := range r.TXT[1:] {
  2494  		s += `", "` + printString([]byte(t))
  2495  	}
  2496  	return s + `"}}`
  2497  }
  2498  
  2499  func unpackTXTResource(msg []byte, off int, length uint16) (TXTResource, error) {
  2500  	txts := make([]string, 0, 1)
  2501  	for n := uint16(0); n < length; {
  2502  		var t string
  2503  		var err error
  2504  		if t, off, err = unpackText(msg, off); err != nil {
  2505  			return TXTResource{}, &nestedError{"text", err}
  2506  		}
  2507  		// Check if we got too many bytes.
  2508  		if length-n < uint16(len(t))+1 {
  2509  			return TXTResource{}, errCalcLen
  2510  		}
  2511  		n += uint16(len(t)) + 1
  2512  		txts = append(txts, t)
  2513  	}
  2514  	return TXTResource{txts}, nil
  2515  }
  2516  
  2517  // An SRVResource is an SRV Resource record.
  2518  type SRVResource struct {
  2519  	Priority uint16
  2520  	Weight   uint16
  2521  	Port     uint16
  2522  	Target   Name // Not compressed as per RFC 2782.
  2523  }
  2524  
  2525  func (r *SRVResource) realType() Type {
  2526  	return TypeSRV
  2527  }
  2528  
  2529  // pack appends the wire format of the SRVResource to msg.
  2530  func (r *SRVResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2531  	oldMsg := msg
  2532  	msg = packUint16(msg, r.Priority)
  2533  	msg = packUint16(msg, r.Weight)
  2534  	msg = packUint16(msg, r.Port)
  2535  	msg, err := r.Target.pack(msg, nil, compressionOff)
  2536  	if err != nil {
  2537  		return oldMsg, &nestedError{"SRVResource.Target", err}
  2538  	}
  2539  	return msg, nil
  2540  }
  2541  
  2542  // GoString implements fmt.GoStringer.GoString.
  2543  func (r *SRVResource) GoString() string {
  2544  	return "dnsmessage.SRVResource{" +
  2545  		"Priority: " + printUint16(r.Priority) + ", " +
  2546  		"Weight: " + printUint16(r.Weight) + ", " +
  2547  		"Port: " + printUint16(r.Port) + ", " +
  2548  		"Target: " + r.Target.GoString() + "}"
  2549  }
  2550  
  2551  func unpackSRVResource(msg []byte, off int) (SRVResource, error) {
  2552  	priority, off, err := unpackUint16(msg, off)
  2553  	if err != nil {
  2554  		return SRVResource{}, &nestedError{"Priority", err}
  2555  	}
  2556  	weight, off, err := unpackUint16(msg, off)
  2557  	if err != nil {
  2558  		return SRVResource{}, &nestedError{"Weight", err}
  2559  	}
  2560  	port, off, err := unpackUint16(msg, off)
  2561  	if err != nil {
  2562  		return SRVResource{}, &nestedError{"Port", err}
  2563  	}
  2564  	var target Name
  2565  	if _, err := target.unpack(msg, off); err != nil {
  2566  		return SRVResource{}, &nestedError{"Target", err}
  2567  	}
  2568  	return SRVResource{priority, weight, port, target}, nil
  2569  }
  2570  
  2571  // An AResource is an A Resource record.
  2572  type AResource struct {
  2573  	A [4]byte
  2574  }
  2575  
  2576  func (r *AResource) realType() Type {
  2577  	return TypeA
  2578  }
  2579  
  2580  // pack appends the wire format of the AResource to msg.
  2581  func (r *AResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2582  	return packBytes(msg, r.A[:]), nil
  2583  }
  2584  
  2585  // GoString implements fmt.GoStringer.GoString.
  2586  func (r *AResource) GoString() string {
  2587  	return "dnsmessage.AResource{" +
  2588  		"A: [4]byte{" + printByteSlice(r.A[:]) + "}}"
  2589  }
  2590  
  2591  func unpackAResource(msg []byte, off int) (AResource, error) {
  2592  	var a [4]byte
  2593  	if _, err := unpackBytes(msg, off, a[:]); err != nil {
  2594  		return AResource{}, err
  2595  	}
  2596  	return AResource{a}, nil
  2597  }
  2598  
  2599  // An AAAAResource is an AAAA Resource record.
  2600  type AAAAResource struct {
  2601  	AAAA [16]byte
  2602  }
  2603  
  2604  func (r *AAAAResource) realType() Type {
  2605  	return TypeAAAA
  2606  }
  2607  
  2608  // GoString implements fmt.GoStringer.GoString.
  2609  func (r *AAAAResource) GoString() string {
  2610  	return "dnsmessage.AAAAResource{" +
  2611  		"AAAA: [16]byte{" + printByteSlice(r.AAAA[:]) + "}}"
  2612  }
  2613  
  2614  // pack appends the wire format of the AAAAResource to msg.
  2615  func (r *AAAAResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2616  	return packBytes(msg, r.AAAA[:]), nil
  2617  }
  2618  
  2619  func unpackAAAAResource(msg []byte, off int) (AAAAResource, error) {
  2620  	var aaaa [16]byte
  2621  	if _, err := unpackBytes(msg, off, aaaa[:]); err != nil {
  2622  		return AAAAResource{}, err
  2623  	}
  2624  	return AAAAResource{aaaa}, nil
  2625  }
  2626  
  2627  // An OPTResource is an OPT pseudo Resource record.
  2628  //
  2629  // The pseudo resource record is part of the extension mechanisms for DNS
  2630  // as defined in RFC 6891.
  2631  type OPTResource struct {
  2632  	Options []Option
  2633  }
  2634  
  2635  // An Option represents a DNS message option within OPTResource.
  2636  //
  2637  // The message option is part of the extension mechanisms for DNS as
  2638  // defined in RFC 6891.
  2639  type Option struct {
  2640  	Code uint16 // option code
  2641  	Data []byte
  2642  }
  2643  
  2644  // GoString implements fmt.GoStringer.GoString.
  2645  func (o *Option) GoString() string {
  2646  	return "dnsmessage.Option{" +
  2647  		"Code: " + printUint16(o.Code) + ", " +
  2648  		"Data: []byte{" + printByteSlice(o.Data) + "}}"
  2649  }
  2650  
  2651  func (r *OPTResource) realType() Type {
  2652  	return TypeOPT
  2653  }
  2654  
  2655  func (r *OPTResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2656  	for _, opt := range r.Options {
  2657  		msg = packUint16(msg, opt.Code)
  2658  		l := uint16(len(opt.Data))
  2659  		msg = packUint16(msg, l)
  2660  		msg = packBytes(msg, opt.Data)
  2661  	}
  2662  	return msg, nil
  2663  }
  2664  
  2665  // GoString implements fmt.GoStringer.GoString.
  2666  func (r *OPTResource) GoString() string {
  2667  	s := "dnsmessage.OPTResource{Options: []dnsmessage.Option{"
  2668  	if len(r.Options) == 0 {
  2669  		return s + "}}"
  2670  	}
  2671  	s += r.Options[0].GoString()
  2672  	for _, o := range r.Options[1:] {
  2673  		s += ", " + o.GoString()
  2674  	}
  2675  	return s + "}}"
  2676  }
  2677  
  2678  func unpackOPTResource(msg []byte, off int, length uint16) (OPTResource, error) {
  2679  	var opts []Option
  2680  	for oldOff := off; off < oldOff+int(length); {
  2681  		var err error
  2682  		var o Option
  2683  		o.Code, off, err = unpackUint16(msg, off)
  2684  		if err != nil {
  2685  			return OPTResource{}, &nestedError{"Code", err}
  2686  		}
  2687  		var l uint16
  2688  		l, off, err = unpackUint16(msg, off)
  2689  		if err != nil {
  2690  			return OPTResource{}, &nestedError{"Data", err}
  2691  		}
  2692  		o.Data = make([]byte, l)
  2693  		if copy(o.Data, msg[off:]) != int(l) {
  2694  			return OPTResource{}, &nestedError{"Data", errCalcLen}
  2695  		}
  2696  		off += int(l)
  2697  		opts = append(opts, o)
  2698  	}
  2699  	return OPTResource{opts}, nil
  2700  }
  2701  
  2702  // An UnknownResource is a catch-all container for unknown record types.
  2703  type UnknownResource struct {
  2704  	Type Type
  2705  	Data []byte
  2706  }
  2707  
  2708  func (r *UnknownResource) realType() Type {
  2709  	return r.Type
  2710  }
  2711  
  2712  // pack appends the wire format of the UnknownResource to msg.
  2713  func (r *UnknownResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) {
  2714  	return packBytes(msg, r.Data[:]), nil
  2715  }
  2716  
  2717  // GoString implements fmt.GoStringer.GoString.
  2718  func (r *UnknownResource) GoString() string {
  2719  	return "dnsmessage.UnknownResource{" +
  2720  		"Type: " + r.Type.GoString() + ", " +
  2721  		"Data: []byte{" + printByteSlice(r.Data) + "}}"
  2722  }
  2723  
  2724  func unpackUnknownResource(recordType Type, msg []byte, off int, length uint16) (UnknownResource, error) {
  2725  	parsed := UnknownResource{
  2726  		Type: recordType,
  2727  		Data: make([]byte, length),
  2728  	}
  2729  	if _, err := unpackBytes(msg, off, parsed.Data); err != nil {
  2730  		return UnknownResource{}, err
  2731  	}
  2732  	return parsed, nil
  2733  }
  2734  

View as plain text