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.
5 // Package dnsmessage provides a mostly RFC 1035 compliant implementation of
6 // DNS message packing and unpacking.
8 // This implementation is designed to minimize heap allocations and avoid
9 // unnecessary packing and unpacking as much as possible.
18 // A Type is a type of DNS request and response.
21 // A Class is a type of network.
24 // An OpCode is a DNS operation code.
27 // An RCode is a DNS response status code.
32 // ResourceHeader.Type and Question.Type
50 // ResourceHeader.Class and Question.Class
60 RCodeSuccess RCode = 0
61 RCodeFormatError RCode = 1
62 RCodeServerFailure RCode = 2
63 RCodeNameError RCode = 3
64 RCodeNotImplemented RCode = 4
65 RCodeRefused RCode = 5
69 // ErrNotStarted indicates that the prerequisite information isn't
70 // available yet because the previous records haven't been appropriately
71 // parsed, skipped or finished.
72 ErrNotStarted = errors.New("parsing/packing of this type isn't available yet")
74 // ErrSectionDone indicated that all records in the section have been
75 // parsed or finished.
76 ErrSectionDone = errors.New("parsing/packing of this section has completed")
78 errBaseLen = errors.New("insufficient data for base length type")
79 errCalcLen = errors.New("insufficient data for calculated length type")
80 errReserved = errors.New("segment prefix is reserved")
81 errTooManyPtr = errors.New("too many pointers (>10)")
82 errInvalidPtr = errors.New("invalid pointer")
83 errNilResouceBody = errors.New("nil resource body")
84 errResourceLen = errors.New("insufficient data for resource body length")
85 errSegTooLong = errors.New("segment length too long")
86 errZeroSegLen = errors.New("zero length segment")
87 errResTooLong = errors.New("resource length too long")
88 errTooManyQuestions = errors.New("too many Questions to pack (>65535)")
89 errTooManyAnswers = errors.New("too many Answers to pack (>65535)")
90 errTooManyAuthorities = errors.New("too many Authorities to pack (>65535)")
91 errTooManyAdditionals = errors.New("too many Additionals to pack (>65535)")
92 errNonCanonicalName = errors.New("name is not in canonical format (it must end with a .)")
95 // Internal constants.
97 // packStartingCap is the default initial buffer size allocated during
100 // The starting capacity doesn't matter too much, but most DNS responses
101 // Will be <= 512 bytes as it is the limit for DNS over UDP.
102 packStartingCap = 512
104 // uint16Len is the length (in bytes) of a uint16.
107 // uint32Len is the length (in bytes) of a uint32.
110 // headerLen is the length (in bytes) of a DNS header.
112 // A header is comprised of 6 uint16s and no padding.
113 headerLen = 6 * uint16Len
116 type nestedError struct {
117 // s is the current level's error message.
120 // err is the nested error.
124 // nestedError implements error.Error.
125 func (e *nestedError) Error() string {
126 return e.s + ": " + e.err.Error()
129 // Header is a representation of a DNS message header.
136 RecursionDesired bool
137 RecursionAvailable bool
141 func (m *Header) pack() (id uint16, bits uint16) {
143 bits = uint16(m.OpCode)<<11 | uint16(m.RCode)
144 if m.RecursionAvailable {
147 if m.RecursionDesired {
162 // Message is a representation of a DNS message.
163 type Message struct {
167 Authorities []Resource
168 Additionals []Resource
174 sectionNotStarted section = iota
182 headerBitQR = 1 << 15 // query/response (response=1)
183 headerBitAA = 1 << 10 // authoritative
184 headerBitTC = 1 << 9 // truncated
185 headerBitRD = 1 << 8 // recursion desired
186 headerBitRA = 1 << 7 // recursion available
189 var sectionNames = map[section]string{
190 sectionHeader: "header",
191 sectionQuestions: "Question",
192 sectionAnswers: "Answer",
193 sectionAuthorities: "Authority",
194 sectionAdditionals: "Additional",
197 // header is the wire format for a DNS message header.
207 func (h *header) count(sec section) uint16 {
209 case sectionQuestions:
213 case sectionAuthorities:
215 case sectionAdditionals:
221 func (h *header) pack(msg []byte) []byte {
222 msg = packUint16(msg, h.id)
223 msg = packUint16(msg, h.bits)
224 msg = packUint16(msg, h.questions)
225 msg = packUint16(msg, h.answers)
226 msg = packUint16(msg, h.authorities)
227 return packUint16(msg, h.additionals)
230 func (h *header) unpack(msg []byte, off int) (int, error) {
233 if h.id, newOff, err = unpackUint16(msg, newOff); err != nil {
234 return off, &nestedError{"id", err}
236 if h.bits, newOff, err = unpackUint16(msg, newOff); err != nil {
237 return off, &nestedError{"bits", err}
239 if h.questions, newOff, err = unpackUint16(msg, newOff); err != nil {
240 return off, &nestedError{"questions", err}
242 if h.answers, newOff, err = unpackUint16(msg, newOff); err != nil {
243 return off, &nestedError{"answers", err}
245 if h.authorities, newOff, err = unpackUint16(msg, newOff); err != nil {
246 return off, &nestedError{"authorities", err}
248 if h.additionals, newOff, err = unpackUint16(msg, newOff); err != nil {
249 return off, &nestedError{"additionals", err}
254 func (h *header) header() Header {
257 Response: (h.bits & headerBitQR) != 0,
258 OpCode: OpCode(h.bits>>11) & 0xF,
259 Authoritative: (h.bits & headerBitAA) != 0,
260 Truncated: (h.bits & headerBitTC) != 0,
261 RecursionDesired: (h.bits & headerBitRD) != 0,
262 RecursionAvailable: (h.bits & headerBitRA) != 0,
263 RCode: RCode(h.bits & 0xF),
267 // A Resource is a DNS resource record.
268 type Resource struct {
269 Header ResourceHeader
273 // A ResourceBody is a DNS resource record minus the header.
274 type ResourceBody interface {
275 // pack packs a Resource except for its header.
276 pack(msg []byte, compression map[string]int) ([]byte, error)
278 // realType returns the actual type of the Resource. This is used to
279 // fill in the header Type field.
283 func (r *Resource) pack(msg []byte, compression map[string]int) ([]byte, error) {
285 return msg, errNilResouceBody
288 r.Header.Type = r.Body.realType()
289 msg, length, err := r.Header.pack(msg, compression)
291 return msg, &nestedError{"ResourceHeader", err}
294 msg, err = r.Body.pack(msg, compression)
296 return msg, &nestedError{"content", err}
298 if err := r.Header.fixLen(msg, length, preLen); err != nil {
304 // A Parser allows incrementally parsing a DNS message.
306 // When parsing is started, the Header is parsed. Next, each Question can be
307 // either parsed or skipped. Alternatively, all Questions can be skipped at
308 // once. When all Questions have been parsed, attempting to parse Questions
309 // will return (nil, nil) and attempting to skip Questions will return
310 // (true, nil). After all Questions have been either parsed or skipped, all
311 // Answers, Authorities and Additionals can be either parsed or skipped in the
312 // same way, and each type of Resource must be fully parsed or skipped before
313 // proceeding to the next type of Resource.
315 // Note that there is no requirement to fully skip or parse the message.
324 resHeader ResourceHeader
327 // Start parses the header and enables the parsing of Questions.
328 func (p *Parser) Start(msg []byte) (Header, error) {
334 if p.off, err = p.header.unpack(msg, 0); err != nil {
335 return Header{}, &nestedError{"unpacking header", err}
337 p.section = sectionQuestions
338 return p.header.header(), nil
341 func (p *Parser) checkAdvance(sec section) error {
346 return ErrSectionDone
348 p.resHeaderValid = false
349 if p.index == int(p.header.count(sec)) {
352 return ErrSectionDone
357 func (p *Parser) resource(sec section) (Resource, error) {
360 r.Header, err = p.resourceHeader(sec)
364 p.resHeaderValid = false
365 r.Body, p.off, err = unpackResourceBody(p.msg, p.off, r.Header)
367 return Resource{}, &nestedError{"unpacking " + sectionNames[sec], err}
373 func (p *Parser) resourceHeader(sec section) (ResourceHeader, error) {
374 if p.resHeaderValid {
375 return p.resHeader, nil
377 if err := p.checkAdvance(sec); err != nil {
378 return ResourceHeader{}, err
380 var hdr ResourceHeader
381 off, err := hdr.unpack(p.msg, p.off)
383 return ResourceHeader{}, err
385 p.resHeaderValid = true
391 func (p *Parser) skipResource(sec section) error {
392 if p.resHeaderValid {
393 newOff := p.off + int(p.resHeader.Length)
394 if newOff > len(p.msg) {
395 return errResourceLen
398 p.resHeaderValid = false
402 if err := p.checkAdvance(sec); err != nil {
406 p.off, err = skipResource(p.msg, p.off)
408 return &nestedError{"skipping: " + sectionNames[sec], err}
414 // Question parses a single Question.
415 func (p *Parser) Question() (Question, error) {
416 if err := p.checkAdvance(sectionQuestions); err != nil {
417 return Question{}, err
420 off, err := name.unpack(p.msg, p.off)
422 return Question{}, &nestedError{"unpacking Question.Name", err}
424 typ, off, err := unpackType(p.msg, off)
426 return Question{}, &nestedError{"unpacking Question.Type", err}
428 class, off, err := unpackClass(p.msg, off)
430 return Question{}, &nestedError{"unpacking Question.Class", err}
434 return Question{name, typ, class}, nil
437 // AllQuestions parses all Questions.
438 func (p *Parser) AllQuestions() ([]Question, error) {
439 qs := make([]Question, 0, p.header.questions)
441 q, err := p.Question()
442 if err == ErrSectionDone {
452 // SkipQuestion skips a single Question.
453 func (p *Parser) SkipQuestion() error {
454 if err := p.checkAdvance(sectionQuestions); err != nil {
457 off, err := skipName(p.msg, p.off)
459 return &nestedError{"skipping Question Name", err}
461 if off, err = skipType(p.msg, off); err != nil {
462 return &nestedError{"skipping Question Type", err}
464 if off, err = skipClass(p.msg, off); err != nil {
465 return &nestedError{"skipping Question Class", err}
472 // SkipAllQuestions skips all Questions.
473 func (p *Parser) SkipAllQuestions() error {
475 if err := p.SkipQuestion(); err == ErrSectionDone {
477 } else if err != nil {
483 // AnswerHeader parses a single Answer ResourceHeader.
484 func (p *Parser) AnswerHeader() (ResourceHeader, error) {
485 return p.resourceHeader(sectionAnswers)
488 // Answer parses a single Answer Resource.
489 func (p *Parser) Answer() (Resource, error) {
490 return p.resource(sectionAnswers)
493 // AllAnswers parses all Answer Resources.
494 func (p *Parser) AllAnswers() ([]Resource, error) {
495 as := make([]Resource, 0, p.header.answers)
498 if err == ErrSectionDone {
508 // SkipAnswer skips a single Answer Resource.
509 func (p *Parser) SkipAnswer() error {
510 return p.skipResource(sectionAnswers)
513 // SkipAllAnswers skips all Answer Resources.
514 func (p *Parser) SkipAllAnswers() error {
516 if err := p.SkipAnswer(); err == ErrSectionDone {
518 } else if err != nil {
524 // AuthorityHeader parses a single Authority ResourceHeader.
525 func (p *Parser) AuthorityHeader() (ResourceHeader, error) {
526 return p.resourceHeader(sectionAuthorities)
529 // Authority parses a single Authority Resource.
530 func (p *Parser) Authority() (Resource, error) {
531 return p.resource(sectionAuthorities)
534 // AllAuthorities parses all Authority Resources.
535 func (p *Parser) AllAuthorities() ([]Resource, error) {
536 as := make([]Resource, 0, p.header.authorities)
538 a, err := p.Authority()
539 if err == ErrSectionDone {
549 // SkipAuthority skips a single Authority Resource.
550 func (p *Parser) SkipAuthority() error {
551 return p.skipResource(sectionAuthorities)
554 // SkipAllAuthorities skips all Authority Resources.
555 func (p *Parser) SkipAllAuthorities() error {
557 if err := p.SkipAuthority(); err == ErrSectionDone {
559 } else if err != nil {
565 // AdditionalHeader parses a single Additional ResourceHeader.
566 func (p *Parser) AdditionalHeader() (ResourceHeader, error) {
567 return p.resourceHeader(sectionAdditionals)
570 // Additional parses a single Additional Resource.
571 func (p *Parser) Additional() (Resource, error) {
572 return p.resource(sectionAdditionals)
575 // AllAdditionals parses all Additional Resources.
576 func (p *Parser) AllAdditionals() ([]Resource, error) {
577 as := make([]Resource, 0, p.header.additionals)
579 a, err := p.Additional()
580 if err == ErrSectionDone {
590 // SkipAdditional skips a single Additional Resource.
591 func (p *Parser) SkipAdditional() error {
592 return p.skipResource(sectionAdditionals)
595 // SkipAllAdditionals skips all Additional Resources.
596 func (p *Parser) SkipAllAdditionals() error {
598 if err := p.SkipAdditional(); err == ErrSectionDone {
600 } else if err != nil {
606 // CNAMEResource parses a single CNAMEResource.
608 // One of the XXXHeader methods must have been called before calling this
610 func (p *Parser) CNAMEResource() (CNAMEResource, error) {
611 if !p.resHeaderValid || p.resHeader.Type != TypeCNAME {
612 return CNAMEResource{}, ErrNotStarted
614 r, err := unpackCNAMEResource(p.msg, p.off)
616 return CNAMEResource{}, err
618 p.off += int(p.resHeader.Length)
619 p.resHeaderValid = false
624 // MXResource parses a single MXResource.
626 // One of the XXXHeader methods must have been called before calling this
628 func (p *Parser) MXResource() (MXResource, error) {
629 if !p.resHeaderValid || p.resHeader.Type != TypeMX {
630 return MXResource{}, ErrNotStarted
632 r, err := unpackMXResource(p.msg, p.off)
634 return MXResource{}, err
636 p.off += int(p.resHeader.Length)
637 p.resHeaderValid = false
642 // NSResource parses a single NSResource.
644 // One of the XXXHeader methods must have been called before calling this
646 func (p *Parser) NSResource() (NSResource, error) {
647 if !p.resHeaderValid || p.resHeader.Type != TypeNS {
648 return NSResource{}, ErrNotStarted
650 r, err := unpackNSResource(p.msg, p.off)
652 return NSResource{}, err
654 p.off += int(p.resHeader.Length)
655 p.resHeaderValid = false
660 // PTRResource parses a single PTRResource.
662 // One of the XXXHeader methods must have been called before calling this
664 func (p *Parser) PTRResource() (PTRResource, error) {
665 if !p.resHeaderValid || p.resHeader.Type != TypePTR {
666 return PTRResource{}, ErrNotStarted
668 r, err := unpackPTRResource(p.msg, p.off)
670 return PTRResource{}, err
672 p.off += int(p.resHeader.Length)
673 p.resHeaderValid = false
678 // SOAResource parses a single SOAResource.
680 // One of the XXXHeader methods must have been called before calling this
682 func (p *Parser) SOAResource() (SOAResource, error) {
683 if !p.resHeaderValid || p.resHeader.Type != TypeSOA {
684 return SOAResource{}, ErrNotStarted
686 r, err := unpackSOAResource(p.msg, p.off)
688 return SOAResource{}, err
690 p.off += int(p.resHeader.Length)
691 p.resHeaderValid = false
696 // TXTResource parses a single TXTResource.
698 // One of the XXXHeader methods must have been called before calling this
700 func (p *Parser) TXTResource() (TXTResource, error) {
701 if !p.resHeaderValid || p.resHeader.Type != TypeTXT {
702 return TXTResource{}, ErrNotStarted
704 r, err := unpackTXTResource(p.msg, p.off, p.resHeader.Length)
706 return TXTResource{}, err
708 p.off += int(p.resHeader.Length)
709 p.resHeaderValid = false
714 // SRVResource parses a single SRVResource.
716 // One of the XXXHeader methods must have been called before calling this
718 func (p *Parser) SRVResource() (SRVResource, error) {
719 if !p.resHeaderValid || p.resHeader.Type != TypeSRV {
720 return SRVResource{}, ErrNotStarted
722 r, err := unpackSRVResource(p.msg, p.off)
724 return SRVResource{}, err
726 p.off += int(p.resHeader.Length)
727 p.resHeaderValid = false
732 // AResource parses a single AResource.
734 // One of the XXXHeader methods must have been called before calling this
736 func (p *Parser) AResource() (AResource, error) {
737 if !p.resHeaderValid || p.resHeader.Type != TypeA {
738 return AResource{}, ErrNotStarted
740 r, err := unpackAResource(p.msg, p.off)
742 return AResource{}, err
744 p.off += int(p.resHeader.Length)
745 p.resHeaderValid = false
750 // AAAAResource parses a single AAAAResource.
752 // One of the XXXHeader methods must have been called before calling this
754 func (p *Parser) AAAAResource() (AAAAResource, error) {
755 if !p.resHeaderValid || p.resHeader.Type != TypeAAAA {
756 return AAAAResource{}, ErrNotStarted
758 r, err := unpackAAAAResource(p.msg, p.off)
760 return AAAAResource{}, err
762 p.off += int(p.resHeader.Length)
763 p.resHeaderValid = false
768 // Unpack parses a full Message.
769 func (m *Message) Unpack(msg []byte) error {
772 if m.Header, err = p.Start(msg); err != nil {
775 if m.Questions, err = p.AllQuestions(); err != nil {
778 if m.Answers, err = p.AllAnswers(); err != nil {
781 if m.Authorities, err = p.AllAuthorities(); err != nil {
784 if m.Additionals, err = p.AllAdditionals(); err != nil {
790 // Pack packs a full Message.
791 func (m *Message) Pack() ([]byte, error) {
792 // Validate the lengths. It is very unlikely that anyone will try to
793 // pack more than 65535 of any particular type, but it is possible and
794 // we should fail gracefully.
795 if len(m.Questions) > int(^uint16(0)) {
796 return nil, errTooManyQuestions
798 if len(m.Answers) > int(^uint16(0)) {
799 return nil, errTooManyAnswers
801 if len(m.Authorities) > int(^uint16(0)) {
802 return nil, errTooManyAuthorities
804 if len(m.Additionals) > int(^uint16(0)) {
805 return nil, errTooManyAdditionals
809 h.id, h.bits = m.Header.pack()
811 h.questions = uint16(len(m.Questions))
812 h.answers = uint16(len(m.Answers))
813 h.authorities = uint16(len(m.Authorities))
814 h.additionals = uint16(len(m.Additionals))
816 msg := make([]byte, 0, packStartingCap)
820 // RFC 1035 allows (but does not require) compression for packing. RFC
821 // 1035 requires unpacking implementations to support compression, so
822 // unconditionally enabling it is fine.
824 // DNS lookups are typically done over UDP, and RFC 1035 states that UDP
825 // DNS packets can be a maximum of 512 bytes long. Without compression,
826 // many DNS response packets are over this limit, so enabling
827 // compression will help ensure compliance.
828 compression := map[string]int{}
830 for i := range m.Questions {
832 if msg, err = m.Questions[i].pack(msg, compression); err != nil {
833 return nil, &nestedError{"packing Question", err}
836 for i := range m.Answers {
838 if msg, err = m.Answers[i].pack(msg, compression); err != nil {
839 return nil, &nestedError{"packing Answer", err}
842 for i := range m.Authorities {
844 if msg, err = m.Authorities[i].pack(msg, compression); err != nil {
845 return nil, &nestedError{"packing Authority", err}
848 for i := range m.Additionals {
850 if msg, err = m.Additionals[i].pack(msg, compression); err != nil {
851 return nil, &nestedError{"packing Additional", err}
858 // A Builder allows incrementally packing a DNS message.
859 type Builder struct {
863 compression map[string]int
866 // Start initializes the builder.
868 // buf is optional (nil is fine), but if provided, Start takes ownership of buf.
869 func (b *Builder) Start(buf []byte, h Header) {
870 b.StartWithoutCompression(buf, h)
871 b.compression = map[string]int{}
874 // StartWithoutCompression initializes the builder with compression disabled.
876 // This avoids compression related allocations, but can result in larger message
877 // sizes. Be careful with this mode as it can cause messages to exceed the UDP
880 // buf is optional (nil is fine), but if provided, Start takes ownership of buf.
881 func (b *Builder) StartWithoutCompression(buf []byte, h Header) {
882 *b = Builder{msg: buf}
883 b.header.id, b.header.bits = h.pack()
884 if cap(b.msg) < headerLen {
885 b.msg = make([]byte, 0, packStartingCap)
887 b.msg = b.msg[:headerLen]
888 b.section = sectionHeader
891 func (b *Builder) startCheck(s section) error {
892 if b.section <= sectionNotStarted {
896 return ErrSectionDone
901 // StartQuestions prepares the builder for packing Questions.
902 func (b *Builder) StartQuestions() error {
903 if err := b.startCheck(sectionQuestions); err != nil {
906 b.section = sectionQuestions
910 // StartAnswers prepares the builder for packing Answers.
911 func (b *Builder) StartAnswers() error {
912 if err := b.startCheck(sectionAnswers); err != nil {
915 b.section = sectionAnswers
919 // StartAuthorities prepares the builder for packing Authorities.
920 func (b *Builder) StartAuthorities() error {
921 if err := b.startCheck(sectionAuthorities); err != nil {
924 b.section = sectionAuthorities
928 // StartAdditionals prepares the builder for packing Additionals.
929 func (b *Builder) StartAdditionals() error {
930 if err := b.startCheck(sectionAdditionals); err != nil {
933 b.section = sectionAdditionals
937 func (b *Builder) incrementSectionCount() error {
941 case sectionQuestions:
942 count = &b.header.questions
943 err = errTooManyQuestions
945 count = &b.header.answers
946 err = errTooManyAnswers
947 case sectionAuthorities:
948 count = &b.header.authorities
949 err = errTooManyAuthorities
950 case sectionAdditionals:
951 count = &b.header.additionals
952 err = errTooManyAdditionals
954 if *count == ^uint16(0) {
961 // Question adds a single Question.
962 func (b *Builder) Question(q Question) error {
963 if b.section < sectionQuestions {
966 if b.section > sectionQuestions {
967 return ErrSectionDone
969 msg, err := q.pack(b.msg, b.compression)
973 if err := b.incrementSectionCount(); err != nil {
980 func (b *Builder) checkResourceSection() error {
981 if b.section < sectionAnswers {
984 if b.section > sectionAdditionals {
985 return ErrSectionDone
990 // CNAMEResource adds a single CNAMEResource.
991 func (b *Builder) CNAMEResource(h ResourceHeader, r CNAMEResource) error {
992 if err := b.checkResourceSection(); err != nil {
995 h.Type = r.realType()
996 msg, length, err := h.pack(b.msg, b.compression)
998 return &nestedError{"ResourceHeader", err}
1001 if msg, err = r.pack(msg, b.compression); err != nil {
1002 return &nestedError{"CNAMEResource body", err}
1004 if err := h.fixLen(msg, length, preLen); err != nil {
1007 if err := b.incrementSectionCount(); err != nil {
1014 // MXResource adds a single MXResource.
1015 func (b *Builder) MXResource(h ResourceHeader, r MXResource) error {
1016 if err := b.checkResourceSection(); err != nil {
1019 h.Type = r.realType()
1020 msg, length, err := h.pack(b.msg, b.compression)
1022 return &nestedError{"ResourceHeader", err}
1025 if msg, err = r.pack(msg, b.compression); err != nil {
1026 return &nestedError{"MXResource body", err}
1028 if err := h.fixLen(msg, length, preLen); err != nil {
1031 if err := b.incrementSectionCount(); err != nil {
1038 // NSResource adds a single NSResource.
1039 func (b *Builder) NSResource(h ResourceHeader, r NSResource) error {
1040 if err := b.checkResourceSection(); err != nil {
1043 h.Type = r.realType()
1044 msg, length, err := h.pack(b.msg, b.compression)
1046 return &nestedError{"ResourceHeader", err}
1049 if msg, err = r.pack(msg, b.compression); err != nil {
1050 return &nestedError{"NSResource body", err}
1052 if err := h.fixLen(msg, length, preLen); err != nil {
1055 if err := b.incrementSectionCount(); err != nil {
1062 // PTRResource adds a single PTRResource.
1063 func (b *Builder) PTRResource(h ResourceHeader, r PTRResource) error {
1064 if err := b.checkResourceSection(); err != nil {
1067 h.Type = r.realType()
1068 msg, length, err := h.pack(b.msg, b.compression)
1070 return &nestedError{"ResourceHeader", err}
1073 if msg, err = r.pack(msg, b.compression); err != nil {
1074 return &nestedError{"PTRResource body", err}
1076 if err := h.fixLen(msg, length, preLen); err != nil {
1079 if err := b.incrementSectionCount(); err != nil {
1086 // SOAResource adds a single SOAResource.
1087 func (b *Builder) SOAResource(h ResourceHeader, r SOAResource) error {
1088 if err := b.checkResourceSection(); err != nil {
1091 h.Type = r.realType()
1092 msg, length, err := h.pack(b.msg, b.compression)
1094 return &nestedError{"ResourceHeader", err}
1097 if msg, err = r.pack(msg, b.compression); err != nil {
1098 return &nestedError{"SOAResource body", err}
1100 if err := h.fixLen(msg, length, preLen); err != nil {
1103 if err := b.incrementSectionCount(); err != nil {
1110 // TXTResource adds a single TXTResource.
1111 func (b *Builder) TXTResource(h ResourceHeader, r TXTResource) error {
1112 if err := b.checkResourceSection(); err != nil {
1115 h.Type = r.realType()
1116 msg, length, err := h.pack(b.msg, b.compression)
1118 return &nestedError{"ResourceHeader", err}
1121 if msg, err = r.pack(msg, b.compression); err != nil {
1122 return &nestedError{"TXTResource body", err}
1124 if err := h.fixLen(msg, length, preLen); err != nil {
1127 if err := b.incrementSectionCount(); err != nil {
1134 // SRVResource adds a single SRVResource.
1135 func (b *Builder) SRVResource(h ResourceHeader, r SRVResource) error {
1136 if err := b.checkResourceSection(); err != nil {
1139 h.Type = r.realType()
1140 msg, length, err := h.pack(b.msg, b.compression)
1142 return &nestedError{"ResourceHeader", err}
1145 if msg, err = r.pack(msg, b.compression); err != nil {
1146 return &nestedError{"SRVResource body", err}
1148 if err := h.fixLen(msg, length, preLen); err != nil {
1151 if err := b.incrementSectionCount(); err != nil {
1158 // AResource adds a single AResource.
1159 func (b *Builder) AResource(h ResourceHeader, r AResource) error {
1160 if err := b.checkResourceSection(); err != nil {
1163 h.Type = r.realType()
1164 msg, length, err := h.pack(b.msg, b.compression)
1166 return &nestedError{"ResourceHeader", err}
1169 if msg, err = r.pack(msg, b.compression); err != nil {
1170 return &nestedError{"AResource body", err}
1172 if err := h.fixLen(msg, length, preLen); err != nil {
1175 if err := b.incrementSectionCount(); err != nil {
1182 // AAAAResource adds a single AAAAResource.
1183 func (b *Builder) AAAAResource(h ResourceHeader, r AAAAResource) error {
1184 if err := b.checkResourceSection(); err != nil {
1187 h.Type = r.realType()
1188 msg, length, err := h.pack(b.msg, b.compression)
1190 return &nestedError{"ResourceHeader", err}
1193 if msg, err = r.pack(msg, b.compression); err != nil {
1194 return &nestedError{"AAAAResource body", err}
1196 if err := h.fixLen(msg, length, preLen); err != nil {
1199 if err := b.incrementSectionCount(); err != nil {
1206 // Finish ends message building and generates a binary packet.
1207 func (b *Builder) Finish() ([]byte, error) {
1208 if b.section < sectionHeader {
1209 return nil, ErrNotStarted
1211 b.section = sectionDone
1212 b.header.pack(b.msg[:0])
1216 // A ResourceHeader is the header of a DNS resource record. There are
1217 // many types of DNS resource records, but they all share the same header.
1218 type ResourceHeader struct {
1219 // Name is the domain name for which this resource record pertains.
1222 // Type is the type of DNS resource record.
1224 // This field will be set automatically during packing.
1227 // Class is the class of network to which this DNS resource record
1231 // TTL is the length of time (measured in seconds) which this resource
1232 // record is valid for (time to live). All Resources in a set should
1233 // have the same TTL (RFC 2181 Section 5.2).
1236 // Length is the length of data in the resource record after the header.
1238 // This field will be set automatically during packing.
1242 // pack packs all of the fields in a ResourceHeader except for the length. The
1243 // length bytes are returned as a slice so they can be filled in after the rest
1244 // of the Resource has been packed.
1245 func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int) (msg []byte, length []byte, err error) {
1247 if msg, err = h.Name.pack(msg, compression); err != nil {
1248 return oldMsg, nil, &nestedError{"Name", err}
1250 msg = packType(msg, h.Type)
1251 msg = packClass(msg, h.Class)
1252 msg = packUint32(msg, h.TTL)
1253 lenBegin := len(msg)
1254 msg = packUint16(msg, h.Length)
1255 return msg, msg[lenBegin : lenBegin+uint16Len], nil
1258 func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) {
1261 if newOff, err = h.Name.unpack(msg, newOff); err != nil {
1262 return off, &nestedError{"Name", err}
1264 if h.Type, newOff, err = unpackType(msg, newOff); err != nil {
1265 return off, &nestedError{"Type", err}
1267 if h.Class, newOff, err = unpackClass(msg, newOff); err != nil {
1268 return off, &nestedError{"Class", err}
1270 if h.TTL, newOff, err = unpackUint32(msg, newOff); err != nil {
1271 return off, &nestedError{"TTL", err}
1273 if h.Length, newOff, err = unpackUint16(msg, newOff); err != nil {
1274 return off, &nestedError{"Length", err}
1279 func (h *ResourceHeader) fixLen(msg []byte, length []byte, preLen int) error {
1280 conLen := len(msg) - preLen
1281 if conLen > int(^uint16(0)) {
1282 return errResTooLong
1285 // Fill in the length now that we know how long the content is.
1286 packUint16(length[:0], uint16(conLen))
1287 h.Length = uint16(conLen)
1292 func skipResource(msg []byte, off int) (int, error) {
1293 newOff, err := skipName(msg, off)
1295 return off, &nestedError{"Name", err}
1297 if newOff, err = skipType(msg, newOff); err != nil {
1298 return off, &nestedError{"Type", err}
1300 if newOff, err = skipClass(msg, newOff); err != nil {
1301 return off, &nestedError{"Class", err}
1303 if newOff, err = skipUint32(msg, newOff); err != nil {
1304 return off, &nestedError{"TTL", err}
1306 length, newOff, err := unpackUint16(msg, newOff)
1308 return off, &nestedError{"Length", err}
1310 if newOff += int(length); newOff > len(msg) {
1311 return off, errResourceLen
1316 func packUint16(msg []byte, field uint16) []byte {
1317 return append(msg, byte(field>>8), byte(field))
1320 func unpackUint16(msg []byte, off int) (uint16, int, error) {
1321 if off+uint16Len > len(msg) {
1322 return 0, off, errBaseLen
1324 return uint16(msg[off])<<8 | uint16(msg[off+1]), off + uint16Len, nil
1327 func skipUint16(msg []byte, off int) (int, error) {
1328 if off+uint16Len > len(msg) {
1329 return off, errBaseLen
1331 return off + uint16Len, nil
1334 func packType(msg []byte, field Type) []byte {
1335 return packUint16(msg, uint16(field))
1338 func unpackType(msg []byte, off int) (Type, int, error) {
1339 t, o, err := unpackUint16(msg, off)
1340 return Type(t), o, err
1343 func skipType(msg []byte, off int) (int, error) {
1344 return skipUint16(msg, off)
1347 func packClass(msg []byte, field Class) []byte {
1348 return packUint16(msg, uint16(field))
1351 func unpackClass(msg []byte, off int) (Class, int, error) {
1352 c, o, err := unpackUint16(msg, off)
1353 return Class(c), o, err
1356 func skipClass(msg []byte, off int) (int, error) {
1357 return skipUint16(msg, off)
1360 func packUint32(msg []byte, field uint32) []byte {
1370 func unpackUint32(msg []byte, off int) (uint32, int, error) {
1371 if off+uint32Len > len(msg) {
1372 return 0, off, errBaseLen
1374 v := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])
1375 return v, off + uint32Len, nil
1378 func skipUint32(msg []byte, off int) (int, error) {
1379 if off+uint32Len > len(msg) {
1380 return off, errBaseLen
1382 return off + uint32Len, nil
1385 func packText(msg []byte, field string) []byte {
1386 for len(field) > 0 {
1391 msg = append(msg, byte(l))
1392 msg = append(msg, field[:l]...)
1398 func unpackText(msg []byte, off int) (string, int, error) {
1399 if off >= len(msg) {
1400 return "", off, errBaseLen
1403 endOff := beginOff + int(msg[off])
1404 if endOff > len(msg) {
1405 return "", off, errCalcLen
1407 return string(msg[beginOff:endOff]), endOff, nil
1410 func skipText(msg []byte, off int) (int, error) {
1411 if off >= len(msg) {
1412 return off, errBaseLen
1414 endOff := off + 1 + int(msg[off])
1415 if endOff > len(msg) {
1416 return off, errCalcLen
1421 func packBytes(msg []byte, field []byte) []byte {
1422 return append(msg, field...)
1425 func unpackBytes(msg []byte, off int, field []byte) (int, error) {
1426 newOff := off + len(field)
1427 if newOff > len(msg) {
1428 return off, errBaseLen
1430 copy(field, msg[off:newOff])
1434 func skipBytes(msg []byte, off int, field []byte) (int, error) {
1435 newOff := off + len(field)
1436 if newOff > len(msg) {
1437 return off, errBaseLen
1444 // A Name is a non-encoded domain name. It is used instead of strings to avoid
1451 // NewName creates a new Name from a string.
1452 func NewName(name string) (Name, error) {
1453 if len([]byte(name)) > nameLen {
1454 return Name{}, errCalcLen
1456 n := Name{Length: uint8(len(name))}
1457 copy(n.Data[:], []byte(name))
1461 func (n Name) String() string {
1462 return string(n.Data[:n.Length])
1465 // pack packs a domain name.
1467 // Domain names are a sequence of counted strings split at the dots. They end
1468 // with a zero-length string. Compression can be used to reuse domain suffixes.
1470 // The compression map will be updated with new domain suffixes. If compression
1471 // is nil, compression will not be used.
1472 func (n *Name) pack(msg []byte, compression map[string]int) ([]byte, error) {
1475 // Add a trailing dot to canonicalize name.
1476 if n.Length == 0 || n.Data[n.Length-1] != '.' {
1477 return oldMsg, errNonCanonicalName
1480 // Allow root domain.
1481 if n.Data[0] == '.' && n.Length == 1 {
1482 return append(msg, 0), nil
1485 // Emit sequence of counted strings, chopping at dots.
1486 for i, begin := 0, 0; i < int(n.Length); i++ {
1487 // Check for the end of the segment.
1488 if n.Data[i] == '.' {
1489 // The two most significant bits have special meaning.
1490 // It isn't allowed for segments to be long enough to
1492 if i-begin >= 1<<6 {
1493 return oldMsg, errSegTooLong
1496 // Segments must have a non-zero length.
1498 return oldMsg, errZeroSegLen
1501 msg = append(msg, byte(i-begin))
1503 for j := begin; j < i; j++ {
1504 msg = append(msg, n.Data[j])
1511 // We can only compress domain suffixes starting with a new
1512 // segment. A pointer is two bytes with the two most significant
1513 // bits set to 1 to indicate that it is a pointer.
1514 if (i == 0 || n.Data[i-1] == '.') && compression != nil {
1515 if ptr, ok := compression[string(n.Data[i:])]; ok {
1516 // Hit. Emit a pointer instead of the rest of
1518 return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil
1521 // Miss. Add the suffix to the compression table if the
1522 // offset can be stored in the available 14 bytes.
1523 if len(msg) <= int(^uint16(0)>>2) {
1524 compression[string(n.Data[i:])] = len(msg)
1528 return append(msg, 0), nil
1531 // unpack unpacks a domain name.
1532 func (n *Name) unpack(msg []byte, off int) (int, error) {
1533 // currOff is the current working offset.
1536 // newOff is the offset where the next record will start. Pointers lead
1537 // to data that belongs to other names and thus doesn't count towards to
1538 // the usage of this name.
1541 // ptr is the number of pointers followed.
1544 // Name is a slice representation of the name data.
1549 if currOff >= len(msg) {
1550 return off, errBaseLen
1552 c := int(msg[currOff])
1555 case 0x00: // String segment
1557 // A zero length signals the end of the name.
1560 endOff := currOff + c
1561 if endOff > len(msg) {
1562 return off, errCalcLen
1564 name = append(name, msg[currOff:endOff]...)
1565 name = append(name, '.')
1567 case 0xC0: // Pointer
1568 if currOff >= len(msg) {
1569 return off, errInvalidPtr
1576 // Don't follow too many pointers, maybe there's a loop.
1577 if ptr++; ptr > 10 {
1578 return off, errTooManyPtr
1580 currOff = (c^0xC0)<<8 | int(c1)
1582 // Prefixes 0x80 and 0x40 are reserved.
1583 return off, errReserved
1587 name = append(name, '.')
1589 if len(name) > len(n.Data) {
1590 return off, errCalcLen
1592 n.Length = uint8(len(name))
1599 func skipName(msg []byte, off int) (int, error) {
1600 // newOff is the offset where the next record will start. Pointers lead
1601 // to data that belongs to other names and thus doesn't count towards to
1602 // the usage of this name.
1607 if newOff >= len(msg) {
1608 return off, errBaseLen
1610 c := int(msg[newOff])
1615 // A zero length signals the end of the name.
1620 if newOff > len(msg) {
1621 return off, errCalcLen
1624 // Pointer to somewhere else in msg.
1626 // Pointers are two bytes.
1629 // Don't follow the pointer as the data here has ended.
1632 // Prefixes 0x80 and 0x40 are reserved.
1633 return off, errReserved
1640 // A Question is a DNS query.
1641 type Question struct {
1647 func (q *Question) pack(msg []byte, compression map[string]int) ([]byte, error) {
1648 msg, err := q.Name.pack(msg, compression)
1650 return msg, &nestedError{"Name", err}
1652 msg = packType(msg, q.Type)
1653 return packClass(msg, q.Class), nil
1656 func unpackResourceBody(msg []byte, off int, hdr ResourceHeader) (ResourceBody, int, error) {
1665 rb, err = unpackAResource(msg, off)
1670 rb, err = unpackNSResource(msg, off)
1674 var rb CNAMEResource
1675 rb, err = unpackCNAMEResource(msg, off)
1680 rb, err = unpackSOAResource(msg, off)
1685 rb, err = unpackPTRResource(msg, off)
1690 rb, err = unpackMXResource(msg, off)
1695 rb, err = unpackTXTResource(msg, off, hdr.Length)
1700 rb, err = unpackAAAAResource(msg, off)
1705 rb, err = unpackSRVResource(msg, off)
1710 return nil, off, &nestedError{name + " record", err}
1713 return nil, off, errors.New("invalid resource type: " + string(hdr.Type+'0'))
1715 return r, off + int(hdr.Length), nil
1718 // A CNAMEResource is a CNAME Resource record.
1719 type CNAMEResource struct {
1723 func (r *CNAMEResource) realType() Type {
1727 func (r *CNAMEResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
1728 return r.CNAME.pack(msg, compression)
1731 func unpackCNAMEResource(msg []byte, off int) (CNAMEResource, error) {
1733 if _, err := cname.unpack(msg, off); err != nil {
1734 return CNAMEResource{}, err
1736 return CNAMEResource{cname}, nil
1739 // An MXResource is an MX Resource record.
1740 type MXResource struct {
1745 func (r *MXResource) realType() Type {
1749 func (r *MXResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
1751 msg = packUint16(msg, r.Pref)
1752 msg, err := r.MX.pack(msg, compression)
1754 return oldMsg, &nestedError{"MXResource.MX", err}
1759 func unpackMXResource(msg []byte, off int) (MXResource, error) {
1760 pref, off, err := unpackUint16(msg, off)
1762 return MXResource{}, &nestedError{"Pref", err}
1765 if _, err := mx.unpack(msg, off); err != nil {
1766 return MXResource{}, &nestedError{"MX", err}
1768 return MXResource{pref, mx}, nil
1771 // An NSResource is an NS Resource record.
1772 type NSResource struct {
1776 func (r *NSResource) realType() Type {
1780 func (r *NSResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
1781 return r.NS.pack(msg, compression)
1784 func unpackNSResource(msg []byte, off int) (NSResource, error) {
1786 if _, err := ns.unpack(msg, off); err != nil {
1787 return NSResource{}, err
1789 return NSResource{ns}, nil
1792 // A PTRResource is a PTR Resource record.
1793 type PTRResource struct {
1797 func (r *PTRResource) realType() Type {
1801 func (r *PTRResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
1802 return r.PTR.pack(msg, compression)
1805 func unpackPTRResource(msg []byte, off int) (PTRResource, error) {
1807 if _, err := ptr.unpack(msg, off); err != nil {
1808 return PTRResource{}, err
1810 return PTRResource{ptr}, nil
1813 // An SOAResource is an SOA Resource record.
1814 type SOAResource struct {
1822 // MinTTL the is the default TTL of Resources records which did not
1823 // contain a TTL value and the TTL of negative responses. (RFC 2308
1828 func (r *SOAResource) realType() Type {
1832 func (r *SOAResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
1834 msg, err := r.NS.pack(msg, compression)
1836 return oldMsg, &nestedError{"SOAResource.NS", err}
1838 msg, err = r.MBox.pack(msg, compression)
1840 return oldMsg, &nestedError{"SOAResource.MBox", err}
1842 msg = packUint32(msg, r.Serial)
1843 msg = packUint32(msg, r.Refresh)
1844 msg = packUint32(msg, r.Retry)
1845 msg = packUint32(msg, r.Expire)
1846 return packUint32(msg, r.MinTTL), nil
1849 func unpackSOAResource(msg []byte, off int) (SOAResource, error) {
1851 off, err := ns.unpack(msg, off)
1853 return SOAResource{}, &nestedError{"NS", err}
1856 if off, err = mbox.unpack(msg, off); err != nil {
1857 return SOAResource{}, &nestedError{"MBox", err}
1859 serial, off, err := unpackUint32(msg, off)
1861 return SOAResource{}, &nestedError{"Serial", err}
1863 refresh, off, err := unpackUint32(msg, off)
1865 return SOAResource{}, &nestedError{"Refresh", err}
1867 retry, off, err := unpackUint32(msg, off)
1869 return SOAResource{}, &nestedError{"Retry", err}
1871 expire, off, err := unpackUint32(msg, off)
1873 return SOAResource{}, &nestedError{"Expire", err}
1875 minTTL, _, err := unpackUint32(msg, off)
1877 return SOAResource{}, &nestedError{"MinTTL", err}
1879 return SOAResource{ns, mbox, serial, refresh, retry, expire, minTTL}, nil
1882 // A TXTResource is a TXT Resource record.
1883 type TXTResource struct {
1884 Txt string // Not a domain name.
1887 func (r *TXTResource) realType() Type {
1891 func (r *TXTResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
1892 return packText(msg, r.Txt), nil
1895 func unpackTXTResource(msg []byte, off int, length uint16) (TXTResource, error) {
1897 for n := uint16(0); n < length; {
1900 if t, off, err = unpackText(msg, off); err != nil {
1901 return TXTResource{}, &nestedError{"text", err}
1903 // Check if we got too many bytes.
1904 if length-n < uint16(len(t))+1 {
1905 return TXTResource{}, errCalcLen
1907 n += uint16(len(t)) + 1
1910 return TXTResource{txt}, nil
1913 // An SRVResource is an SRV Resource record.
1914 type SRVResource struct {
1918 Target Name // Not compressed as per RFC 2782.
1921 func (r *SRVResource) realType() Type {
1925 func (r *SRVResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
1927 msg = packUint16(msg, r.Priority)
1928 msg = packUint16(msg, r.Weight)
1929 msg = packUint16(msg, r.Port)
1930 msg, err := r.Target.pack(msg, nil)
1932 return oldMsg, &nestedError{"SRVResource.Target", err}
1937 func unpackSRVResource(msg []byte, off int) (SRVResource, error) {
1938 priority, off, err := unpackUint16(msg, off)
1940 return SRVResource{}, &nestedError{"Priority", err}
1942 weight, off, err := unpackUint16(msg, off)
1944 return SRVResource{}, &nestedError{"Weight", err}
1946 port, off, err := unpackUint16(msg, off)
1948 return SRVResource{}, &nestedError{"Port", err}
1951 if _, err := target.unpack(msg, off); err != nil {
1952 return SRVResource{}, &nestedError{"Target", err}
1954 return SRVResource{priority, weight, port, target}, nil
1957 // An AResource is an A Resource record.
1958 type AResource struct {
1962 func (r *AResource) realType() Type {
1966 func (r *AResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
1967 return packBytes(msg, r.A[:]), nil
1970 func unpackAResource(msg []byte, off int) (AResource, error) {
1972 if _, err := unpackBytes(msg, off, a[:]); err != nil {
1973 return AResource{}, err
1975 return AResource{a}, nil
1978 // An AAAAResource is an AAAA Resource record.
1979 type AAAAResource struct {
1983 func (r *AAAAResource) realType() Type {
1987 func (r *AAAAResource) pack(msg []byte, compression map[string]int) ([]byte, error) {
1988 return packBytes(msg, r.AAAA[:]), nil
1991 func unpackAAAAResource(msg []byte, off int) (AAAAResource, error) {
1993 if _, err := unpackBytes(msg, off, aaaa[:]); err != nil {
1994 return AAAAResource{}, err
1996 return AAAAResource{aaaa}, nil