github.com/icodeface/tls@v0.0.0-20230910023335-34df9250cd12/internal/x/net/dns/dnsmessage/message.go (about) 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 // This implementation is designed to minimize heap allocations and avoid 9 // unnecessary packing and unpacking as much as possible. 10 package dnsmessage 11 12 import ( 13 "errors" 14 ) 15 16 // Message formats 17 18 // A Type is a type of DNS request and response. 19 type Type uint16 20 21 // A Class is a type of network. 22 type Class uint16 23 24 // An OpCode is a DNS operation code. 25 type OpCode uint16 26 27 // An RCode is a DNS response status code. 28 type RCode uint16 29 30 // Wire constants. 31 const ( 32 // ResourceHeader.Type and Question.Type 33 TypeA Type = 1 34 TypeNS Type = 2 35 TypeCNAME Type = 5 36 TypeSOA Type = 6 37 TypePTR Type = 12 38 TypeMX Type = 15 39 TypeTXT Type = 16 40 TypeAAAA Type = 28 41 TypeSRV Type = 33 42 43 // Question.Type 44 TypeWKS Type = 11 45 TypeHINFO Type = 13 46 TypeMINFO Type = 14 47 TypeAXFR Type = 252 48 TypeALL Type = 255 49 50 // ResourceHeader.Class and Question.Class 51 ClassINET Class = 1 52 ClassCSNET Class = 2 53 ClassCHAOS Class = 3 54 ClassHESIOD Class = 4 55 56 // Question.Class 57 ClassANY Class = 255 58 59 // Message.Rcode 60 RCodeSuccess RCode = 0 61 RCodeFormatError RCode = 1 62 RCodeServerFailure RCode = 2 63 RCodeNameError RCode = 3 64 RCodeNotImplemented RCode = 4 65 RCodeRefused RCode = 5 66 ) 67 68 var ( 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") 73 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") 77 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 .)") 93 errStringTooLong = errors.New("character string exceeds maximum length (255)") 94 errCompressedSRV = errors.New("compressed name in SRV resource data") 95 ) 96 97 // Internal constants. 98 const ( 99 // packStartingCap is the default initial buffer size allocated during 100 // packing. 101 // 102 // The starting capacity doesn't matter too much, but most DNS responses 103 // Will be <= 512 bytes as it is the limit for DNS over UDP. 104 packStartingCap = 512 105 106 // uint16Len is the length (in bytes) of a uint16. 107 uint16Len = 2 108 109 // uint32Len is the length (in bytes) of a uint32. 110 uint32Len = 4 111 112 // headerLen is the length (in bytes) of a DNS header. 113 // 114 // A header is comprised of 6 uint16s and no padding. 115 headerLen = 6 * uint16Len 116 ) 117 118 type nestedError struct { 119 // s is the current level's error message. 120 s string 121 122 // err is the nested error. 123 err error 124 } 125 126 // nestedError implements error.Error. 127 func (e *nestedError) Error() string { 128 return e.s + ": " + e.err.Error() 129 } 130 131 // Header is a representation of a DNS message header. 132 type Header struct { 133 ID uint16 134 Response bool 135 OpCode OpCode 136 Authoritative bool 137 Truncated bool 138 RecursionDesired bool 139 RecursionAvailable bool 140 RCode RCode 141 } 142 143 func (m *Header) pack() (id uint16, bits uint16) { 144 id = m.ID 145 bits = uint16(m.OpCode)<<11 | uint16(m.RCode) 146 if m.RecursionAvailable { 147 bits |= headerBitRA 148 } 149 if m.RecursionDesired { 150 bits |= headerBitRD 151 } 152 if m.Truncated { 153 bits |= headerBitTC 154 } 155 if m.Authoritative { 156 bits |= headerBitAA 157 } 158 if m.Response { 159 bits |= headerBitQR 160 } 161 return 162 } 163 164 // Message is a representation of a DNS message. 165 type Message struct { 166 Header 167 Questions []Question 168 Answers []Resource 169 Authorities []Resource 170 Additionals []Resource 171 } 172 173 type section uint8 174 175 const ( 176 sectionNotStarted section = iota 177 sectionHeader 178 sectionQuestions 179 sectionAnswers 180 sectionAuthorities 181 sectionAdditionals 182 sectionDone 183 184 headerBitQR = 1 << 15 // query/response (response=1) 185 headerBitAA = 1 << 10 // authoritative 186 headerBitTC = 1 << 9 // truncated 187 headerBitRD = 1 << 8 // recursion desired 188 headerBitRA = 1 << 7 // recursion available 189 ) 190 191 var sectionNames = map[section]string{ 192 sectionHeader: "header", 193 sectionQuestions: "Question", 194 sectionAnswers: "Answer", 195 sectionAuthorities: "Authority", 196 sectionAdditionals: "Additional", 197 } 198 199 // header is the wire format for a DNS message header. 200 type header struct { 201 id uint16 202 bits uint16 203 questions uint16 204 answers uint16 205 authorities uint16 206 additionals uint16 207 } 208 209 func (h *header) count(sec section) uint16 { 210 switch sec { 211 case sectionQuestions: 212 return h.questions 213 case sectionAnswers: 214 return h.answers 215 case sectionAuthorities: 216 return h.authorities 217 case sectionAdditionals: 218 return h.additionals 219 } 220 return 0 221 } 222 223 // pack appends the wire format of the header to msg. 224 func (h *header) pack(msg []byte) []byte { 225 msg = packUint16(msg, h.id) 226 msg = packUint16(msg, h.bits) 227 msg = packUint16(msg, h.questions) 228 msg = packUint16(msg, h.answers) 229 msg = packUint16(msg, h.authorities) 230 return packUint16(msg, h.additionals) 231 } 232 233 func (h *header) unpack(msg []byte, off int) (int, error) { 234 newOff := off 235 var err error 236 if h.id, newOff, err = unpackUint16(msg, newOff); err != nil { 237 return off, &nestedError{"id", err} 238 } 239 if h.bits, newOff, err = unpackUint16(msg, newOff); err != nil { 240 return off, &nestedError{"bits", err} 241 } 242 if h.questions, newOff, err = unpackUint16(msg, newOff); err != nil { 243 return off, &nestedError{"questions", err} 244 } 245 if h.answers, newOff, err = unpackUint16(msg, newOff); err != nil { 246 return off, &nestedError{"answers", err} 247 } 248 if h.authorities, newOff, err = unpackUint16(msg, newOff); err != nil { 249 return off, &nestedError{"authorities", err} 250 } 251 if h.additionals, newOff, err = unpackUint16(msg, newOff); err != nil { 252 return off, &nestedError{"additionals", err} 253 } 254 return newOff, nil 255 } 256 257 func (h *header) header() Header { 258 return Header{ 259 ID: h.id, 260 Response: (h.bits & headerBitQR) != 0, 261 OpCode: OpCode(h.bits>>11) & 0xF, 262 Authoritative: (h.bits & headerBitAA) != 0, 263 Truncated: (h.bits & headerBitTC) != 0, 264 RecursionDesired: (h.bits & headerBitRD) != 0, 265 RecursionAvailable: (h.bits & headerBitRA) != 0, 266 RCode: RCode(h.bits & 0xF), 267 } 268 } 269 270 // A Resource is a DNS resource record. 271 type Resource struct { 272 Header ResourceHeader 273 Body ResourceBody 274 } 275 276 // A ResourceBody is a DNS resource record minus the header. 277 type ResourceBody interface { 278 // pack packs a Resource except for its header. 279 pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) 280 281 // realType returns the actual type of the Resource. This is used to 282 // fill in the header Type field. 283 realType() Type 284 } 285 286 // pack appends the wire format of the Resource to msg. 287 func (r *Resource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 288 if r.Body == nil { 289 return msg, errNilResouceBody 290 } 291 oldMsg := msg 292 r.Header.Type = r.Body.realType() 293 msg, length, err := r.Header.pack(msg, compression, compressionOff) 294 if err != nil { 295 return msg, &nestedError{"ResourceHeader", err} 296 } 297 preLen := len(msg) 298 msg, err = r.Body.pack(msg, compression, compressionOff) 299 if err != nil { 300 return msg, &nestedError{"content", err} 301 } 302 if err := r.Header.fixLen(msg, length, preLen); err != nil { 303 return oldMsg, err 304 } 305 return msg, nil 306 } 307 308 // A Parser allows incrementally parsing a DNS message. 309 // 310 // When parsing is started, the Header is parsed. Next, each Question can be 311 // either parsed or skipped. Alternatively, all Questions can be skipped at 312 // once. When all Questions have been parsed, attempting to parse Questions 313 // will return (nil, nil) and attempting to skip Questions will return 314 // (true, nil). After all Questions have been either parsed or skipped, all 315 // Answers, Authorities and Additionals can be either parsed or skipped in the 316 // same way, and each type of Resource must be fully parsed or skipped before 317 // proceeding to the next type of Resource. 318 // 319 // Note that there is no requirement to fully skip or parse the message. 320 type Parser struct { 321 msg []byte 322 header header 323 324 section section 325 off int 326 index int 327 resHeaderValid bool 328 resHeader ResourceHeader 329 } 330 331 // Start parses the header and enables the parsing of Questions. 332 func (p *Parser) Start(msg []byte) (Header, error) { 333 if p.msg != nil { 334 *p = Parser{} 335 } 336 p.msg = msg 337 var err error 338 if p.off, err = p.header.unpack(msg, 0); err != nil { 339 return Header{}, &nestedError{"unpacking header", err} 340 } 341 p.section = sectionQuestions 342 return p.header.header(), nil 343 } 344 345 func (p *Parser) checkAdvance(sec section) error { 346 if p.section < sec { 347 return ErrNotStarted 348 } 349 if p.section > sec { 350 return ErrSectionDone 351 } 352 p.resHeaderValid = false 353 if p.index == int(p.header.count(sec)) { 354 p.index = 0 355 p.section++ 356 return ErrSectionDone 357 } 358 return nil 359 } 360 361 func (p *Parser) resource(sec section) (Resource, error) { 362 var r Resource 363 var err error 364 r.Header, err = p.resourceHeader(sec) 365 if err != nil { 366 return r, err 367 } 368 p.resHeaderValid = false 369 r.Body, p.off, err = unpackResourceBody(p.msg, p.off, r.Header) 370 if err != nil { 371 return Resource{}, &nestedError{"unpacking " + sectionNames[sec], err} 372 } 373 p.index++ 374 return r, nil 375 } 376 377 func (p *Parser) resourceHeader(sec section) (ResourceHeader, error) { 378 if p.resHeaderValid { 379 return p.resHeader, nil 380 } 381 if err := p.checkAdvance(sec); err != nil { 382 return ResourceHeader{}, err 383 } 384 var hdr ResourceHeader 385 off, err := hdr.unpack(p.msg, p.off) 386 if err != nil { 387 return ResourceHeader{}, err 388 } 389 p.resHeaderValid = true 390 p.resHeader = hdr 391 p.off = off 392 return hdr, nil 393 } 394 395 func (p *Parser) skipResource(sec section) error { 396 if p.resHeaderValid { 397 newOff := p.off + int(p.resHeader.Length) 398 if newOff > len(p.msg) { 399 return errResourceLen 400 } 401 p.off = newOff 402 p.resHeaderValid = false 403 p.index++ 404 return nil 405 } 406 if err := p.checkAdvance(sec); err != nil { 407 return err 408 } 409 var err error 410 p.off, err = skipResource(p.msg, p.off) 411 if err != nil { 412 return &nestedError{"skipping: " + sectionNames[sec], err} 413 } 414 p.index++ 415 return nil 416 } 417 418 // Question parses a single Question. 419 func (p *Parser) Question() (Question, error) { 420 if err := p.checkAdvance(sectionQuestions); err != nil { 421 return Question{}, err 422 } 423 var name Name 424 off, err := name.unpack(p.msg, p.off) 425 if err != nil { 426 return Question{}, &nestedError{"unpacking Question.Name", err} 427 } 428 typ, off, err := unpackType(p.msg, off) 429 if err != nil { 430 return Question{}, &nestedError{"unpacking Question.Type", err} 431 } 432 class, off, err := unpackClass(p.msg, off) 433 if err != nil { 434 return Question{}, &nestedError{"unpacking Question.Class", err} 435 } 436 p.off = off 437 p.index++ 438 return Question{name, typ, class}, nil 439 } 440 441 // AllQuestions parses all Questions. 442 func (p *Parser) AllQuestions() ([]Question, error) { 443 // Multiple questions are valid according to the spec, 444 // but servers don't actually support them. There will 445 // be at most one question here. 446 // 447 // Do not pre-allocate based on info in p.header, since 448 // the data is untrusted. 449 qs := []Question{} 450 for { 451 q, err := p.Question() 452 if err == ErrSectionDone { 453 return qs, nil 454 } 455 if err != nil { 456 return nil, err 457 } 458 qs = append(qs, q) 459 } 460 } 461 462 // SkipQuestion skips a single Question. 463 func (p *Parser) SkipQuestion() error { 464 if err := p.checkAdvance(sectionQuestions); err != nil { 465 return err 466 } 467 off, err := skipName(p.msg, p.off) 468 if err != nil { 469 return &nestedError{"skipping Question Name", err} 470 } 471 if off, err = skipType(p.msg, off); err != nil { 472 return &nestedError{"skipping Question Type", err} 473 } 474 if off, err = skipClass(p.msg, off); err != nil { 475 return &nestedError{"skipping Question Class", err} 476 } 477 p.off = off 478 p.index++ 479 return nil 480 } 481 482 // SkipAllQuestions skips all Questions. 483 func (p *Parser) SkipAllQuestions() error { 484 for { 485 if err := p.SkipQuestion(); err == ErrSectionDone { 486 return nil 487 } else if err != nil { 488 return err 489 } 490 } 491 } 492 493 // AnswerHeader parses a single Answer ResourceHeader. 494 func (p *Parser) AnswerHeader() (ResourceHeader, error) { 495 return p.resourceHeader(sectionAnswers) 496 } 497 498 // Answer parses a single Answer Resource. 499 func (p *Parser) Answer() (Resource, error) { 500 return p.resource(sectionAnswers) 501 } 502 503 // AllAnswers parses all Answer Resources. 504 func (p *Parser) AllAnswers() ([]Resource, error) { 505 // The most common query is for A/AAAA, which usually returns 506 // a handful of IPs. 507 // 508 // Pre-allocate up to a certain limit, since p.header is 509 // untrusted data. 510 n := int(p.header.answers) 511 if n > 20 { 512 n = 20 513 } 514 as := make([]Resource, 0, n) 515 for { 516 a, err := p.Answer() 517 if err == ErrSectionDone { 518 return as, nil 519 } 520 if err != nil { 521 return nil, err 522 } 523 as = append(as, a) 524 } 525 } 526 527 // SkipAnswer skips a single Answer Resource. 528 func (p *Parser) SkipAnswer() error { 529 return p.skipResource(sectionAnswers) 530 } 531 532 // SkipAllAnswers skips all Answer Resources. 533 func (p *Parser) SkipAllAnswers() error { 534 for { 535 if err := p.SkipAnswer(); err == ErrSectionDone { 536 return nil 537 } else if err != nil { 538 return err 539 } 540 } 541 } 542 543 // AuthorityHeader parses a single Authority ResourceHeader. 544 func (p *Parser) AuthorityHeader() (ResourceHeader, error) { 545 return p.resourceHeader(sectionAuthorities) 546 } 547 548 // Authority parses a single Authority Resource. 549 func (p *Parser) Authority() (Resource, error) { 550 return p.resource(sectionAuthorities) 551 } 552 553 // AllAuthorities parses all Authority Resources. 554 func (p *Parser) AllAuthorities() ([]Resource, error) { 555 // Authorities contains SOA in case of NXDOMAIN and friends, 556 // otherwise it is empty. 557 // 558 // Pre-allocate up to a certain limit, since p.header is 559 // untrusted data. 560 n := int(p.header.authorities) 561 if n > 10 { 562 n = 10 563 } 564 as := make([]Resource, 0, n) 565 for { 566 a, err := p.Authority() 567 if err == ErrSectionDone { 568 return as, nil 569 } 570 if err != nil { 571 return nil, err 572 } 573 as = append(as, a) 574 } 575 } 576 577 // SkipAuthority skips a single Authority Resource. 578 func (p *Parser) SkipAuthority() error { 579 return p.skipResource(sectionAuthorities) 580 } 581 582 // SkipAllAuthorities skips all Authority Resources. 583 func (p *Parser) SkipAllAuthorities() error { 584 for { 585 if err := p.SkipAuthority(); err == ErrSectionDone { 586 return nil 587 } else if err != nil { 588 return err 589 } 590 } 591 } 592 593 // AdditionalHeader parses a single Additional ResourceHeader. 594 func (p *Parser) AdditionalHeader() (ResourceHeader, error) { 595 return p.resourceHeader(sectionAdditionals) 596 } 597 598 // Additional parses a single Additional Resource. 599 func (p *Parser) Additional() (Resource, error) { 600 return p.resource(sectionAdditionals) 601 } 602 603 // AllAdditionals parses all Additional Resources. 604 func (p *Parser) AllAdditionals() ([]Resource, error) { 605 // Additionals usually contain OPT, and sometimes A/AAAA 606 // glue records. 607 // 608 // Pre-allocate up to a certain limit, since p.header is 609 // untrusted data. 610 n := int(p.header.additionals) 611 if n > 10 { 612 n = 10 613 } 614 as := make([]Resource, 0, n) 615 for { 616 a, err := p.Additional() 617 if err == ErrSectionDone { 618 return as, nil 619 } 620 if err != nil { 621 return nil, err 622 } 623 as = append(as, a) 624 } 625 } 626 627 // SkipAdditional skips a single Additional Resource. 628 func (p *Parser) SkipAdditional() error { 629 return p.skipResource(sectionAdditionals) 630 } 631 632 // SkipAllAdditionals skips all Additional Resources. 633 func (p *Parser) SkipAllAdditionals() error { 634 for { 635 if err := p.SkipAdditional(); err == ErrSectionDone { 636 return nil 637 } else if err != nil { 638 return err 639 } 640 } 641 } 642 643 // CNAMEResource parses a single CNAMEResource. 644 // 645 // One of the XXXHeader methods must have been called before calling this 646 // method. 647 func (p *Parser) CNAMEResource() (CNAMEResource, error) { 648 if !p.resHeaderValid || p.resHeader.Type != TypeCNAME { 649 return CNAMEResource{}, ErrNotStarted 650 } 651 r, err := unpackCNAMEResource(p.msg, p.off) 652 if err != nil { 653 return CNAMEResource{}, err 654 } 655 p.off += int(p.resHeader.Length) 656 p.resHeaderValid = false 657 p.index++ 658 return r, nil 659 } 660 661 // MXResource parses a single MXResource. 662 // 663 // One of the XXXHeader methods must have been called before calling this 664 // method. 665 func (p *Parser) MXResource() (MXResource, error) { 666 if !p.resHeaderValid || p.resHeader.Type != TypeMX { 667 return MXResource{}, ErrNotStarted 668 } 669 r, err := unpackMXResource(p.msg, p.off) 670 if err != nil { 671 return MXResource{}, err 672 } 673 p.off += int(p.resHeader.Length) 674 p.resHeaderValid = false 675 p.index++ 676 return r, nil 677 } 678 679 // NSResource parses a single NSResource. 680 // 681 // One of the XXXHeader methods must have been called before calling this 682 // method. 683 func (p *Parser) NSResource() (NSResource, error) { 684 if !p.resHeaderValid || p.resHeader.Type != TypeNS { 685 return NSResource{}, ErrNotStarted 686 } 687 r, err := unpackNSResource(p.msg, p.off) 688 if err != nil { 689 return NSResource{}, err 690 } 691 p.off += int(p.resHeader.Length) 692 p.resHeaderValid = false 693 p.index++ 694 return r, nil 695 } 696 697 // PTRResource parses a single PTRResource. 698 // 699 // One of the XXXHeader methods must have been called before calling this 700 // method. 701 func (p *Parser) PTRResource() (PTRResource, error) { 702 if !p.resHeaderValid || p.resHeader.Type != TypePTR { 703 return PTRResource{}, ErrNotStarted 704 } 705 r, err := unpackPTRResource(p.msg, p.off) 706 if err != nil { 707 return PTRResource{}, err 708 } 709 p.off += int(p.resHeader.Length) 710 p.resHeaderValid = false 711 p.index++ 712 return r, nil 713 } 714 715 // SOAResource parses a single SOAResource. 716 // 717 // One of the XXXHeader methods must have been called before calling this 718 // method. 719 func (p *Parser) SOAResource() (SOAResource, error) { 720 if !p.resHeaderValid || p.resHeader.Type != TypeSOA { 721 return SOAResource{}, ErrNotStarted 722 } 723 r, err := unpackSOAResource(p.msg, p.off) 724 if err != nil { 725 return SOAResource{}, err 726 } 727 p.off += int(p.resHeader.Length) 728 p.resHeaderValid = false 729 p.index++ 730 return r, nil 731 } 732 733 // TXTResource parses a single TXTResource. 734 // 735 // One of the XXXHeader methods must have been called before calling this 736 // method. 737 func (p *Parser) TXTResource() (TXTResource, error) { 738 if !p.resHeaderValid || p.resHeader.Type != TypeTXT { 739 return TXTResource{}, ErrNotStarted 740 } 741 r, err := unpackTXTResource(p.msg, p.off, p.resHeader.Length) 742 if err != nil { 743 return TXTResource{}, err 744 } 745 p.off += int(p.resHeader.Length) 746 p.resHeaderValid = false 747 p.index++ 748 return r, nil 749 } 750 751 // SRVResource parses a single SRVResource. 752 // 753 // One of the XXXHeader methods must have been called before calling this 754 // method. 755 func (p *Parser) SRVResource() (SRVResource, error) { 756 if !p.resHeaderValid || p.resHeader.Type != TypeSRV { 757 return SRVResource{}, ErrNotStarted 758 } 759 r, err := unpackSRVResource(p.msg, p.off) 760 if err != nil { 761 return SRVResource{}, err 762 } 763 p.off += int(p.resHeader.Length) 764 p.resHeaderValid = false 765 p.index++ 766 return r, nil 767 } 768 769 // AResource parses a single AResource. 770 // 771 // One of the XXXHeader methods must have been called before calling this 772 // method. 773 func (p *Parser) AResource() (AResource, error) { 774 if !p.resHeaderValid || p.resHeader.Type != TypeA { 775 return AResource{}, ErrNotStarted 776 } 777 r, err := unpackAResource(p.msg, p.off) 778 if err != nil { 779 return AResource{}, err 780 } 781 p.off += int(p.resHeader.Length) 782 p.resHeaderValid = false 783 p.index++ 784 return r, nil 785 } 786 787 // AAAAResource parses a single AAAAResource. 788 // 789 // One of the XXXHeader methods must have been called before calling this 790 // method. 791 func (p *Parser) AAAAResource() (AAAAResource, error) { 792 if !p.resHeaderValid || p.resHeader.Type != TypeAAAA { 793 return AAAAResource{}, ErrNotStarted 794 } 795 r, err := unpackAAAAResource(p.msg, p.off) 796 if err != nil { 797 return AAAAResource{}, err 798 } 799 p.off += int(p.resHeader.Length) 800 p.resHeaderValid = false 801 p.index++ 802 return r, nil 803 } 804 805 // Unpack parses a full Message. 806 func (m *Message) Unpack(msg []byte) error { 807 var p Parser 808 var err error 809 if m.Header, err = p.Start(msg); err != nil { 810 return err 811 } 812 if m.Questions, err = p.AllQuestions(); err != nil { 813 return err 814 } 815 if m.Answers, err = p.AllAnswers(); err != nil { 816 return err 817 } 818 if m.Authorities, err = p.AllAuthorities(); err != nil { 819 return err 820 } 821 if m.Additionals, err = p.AllAdditionals(); err != nil { 822 return err 823 } 824 return nil 825 } 826 827 // Pack packs a full Message. 828 func (m *Message) Pack() ([]byte, error) { 829 return m.AppendPack(make([]byte, 0, packStartingCap)) 830 } 831 832 // AppendPack is like Pack but appends the full Message to b and returns the 833 // extended buffer. 834 func (m *Message) AppendPack(b []byte) ([]byte, error) { 835 // Validate the lengths. It is very unlikely that anyone will try to 836 // pack more than 65535 of any particular type, but it is possible and 837 // we should fail gracefully. 838 if len(m.Questions) > int(^uint16(0)) { 839 return nil, errTooManyQuestions 840 } 841 if len(m.Answers) > int(^uint16(0)) { 842 return nil, errTooManyAnswers 843 } 844 if len(m.Authorities) > int(^uint16(0)) { 845 return nil, errTooManyAuthorities 846 } 847 if len(m.Additionals) > int(^uint16(0)) { 848 return nil, errTooManyAdditionals 849 } 850 851 var h header 852 h.id, h.bits = m.Header.pack() 853 854 h.questions = uint16(len(m.Questions)) 855 h.answers = uint16(len(m.Answers)) 856 h.authorities = uint16(len(m.Authorities)) 857 h.additionals = uint16(len(m.Additionals)) 858 859 compressionOff := len(b) 860 msg := h.pack(b) 861 862 // RFC 1035 allows (but does not require) compression for packing. RFC 863 // 1035 requires unpacking implementations to support compression, so 864 // unconditionally enabling it is fine. 865 // 866 // DNS lookups are typically done over UDP, and RFC 1035 states that UDP 867 // DNS messages can be a maximum of 512 bytes long. Without compression, 868 // many DNS response messages are over this limit, so enabling 869 // compression will help ensure compliance. 870 compression := map[string]int{} 871 872 for i := range m.Questions { 873 var err error 874 if msg, err = m.Questions[i].pack(msg, compression, compressionOff); err != nil { 875 return nil, &nestedError{"packing Question", err} 876 } 877 } 878 for i := range m.Answers { 879 var err error 880 if msg, err = m.Answers[i].pack(msg, compression, compressionOff); err != nil { 881 return nil, &nestedError{"packing Answer", err} 882 } 883 } 884 for i := range m.Authorities { 885 var err error 886 if msg, err = m.Authorities[i].pack(msg, compression, compressionOff); err != nil { 887 return nil, &nestedError{"packing Authority", err} 888 } 889 } 890 for i := range m.Additionals { 891 var err error 892 if msg, err = m.Additionals[i].pack(msg, compression, compressionOff); err != nil { 893 return nil, &nestedError{"packing Additional", err} 894 } 895 } 896 897 return msg, nil 898 } 899 900 // A Builder allows incrementally packing a DNS message. 901 // 902 // Example usage: 903 // buf := make([]byte, 2, 514) 904 // b := NewBuilder(buf, Header{...}) 905 // b.EnableCompression() 906 // // Optionally start a section and add things to that section. 907 // // Repeat adding sections as necessary. 908 // buf, err := b.Finish() 909 // // If err is nil, buf[2:] will contain the built bytes. 910 type Builder struct { 911 // msg is the storage for the message being built. 912 msg []byte 913 914 // section keeps track of the current section being built. 915 section section 916 917 // header keeps track of what should go in the header when Finish is 918 // called. 919 header header 920 921 // start is the starting index of the bytes allocated in msg for header. 922 start int 923 924 // compression is a mapping from name suffixes to their starting index 925 // in msg. 926 compression map[string]int 927 } 928 929 // NewBuilder creates a new builder with compression disabled. 930 // 931 // Note: Most users will want to immediately enable compression with the 932 // EnableCompression method. See that method's comment for why you may or may 933 // not want to enable compression. 934 // 935 // The DNS message is appended to the provided initial buffer buf (which may be 936 // nil) as it is built. The final message is returned by the (*Builder).Finish 937 // method, which may return the same underlying array if there was sufficient 938 // capacity in the slice. 939 func NewBuilder(buf []byte, h Header) Builder { 940 if buf == nil { 941 buf = make([]byte, 0, packStartingCap) 942 } 943 b := Builder{msg: buf, start: len(buf)} 944 b.header.id, b.header.bits = h.pack() 945 var hb [headerLen]byte 946 b.msg = append(b.msg, hb[:]...) 947 b.section = sectionHeader 948 return b 949 } 950 951 // EnableCompression enables compression in the Builder. 952 // 953 // Leaving compression disabled avoids compression related allocations, but can 954 // result in larger message sizes. Be careful with this mode as it can cause 955 // messages to exceed the UDP size limit. 956 // 957 // According to RFC 1035, section 4.1.4, the use of compression is optional, but 958 // all implementations must accept both compressed and uncompressed DNS 959 // messages. 960 // 961 // Compression should be enabled before any sections are added for best results. 962 func (b *Builder) EnableCompression() { 963 b.compression = map[string]int{} 964 } 965 966 func (b *Builder) startCheck(s section) error { 967 if b.section <= sectionNotStarted { 968 return ErrNotStarted 969 } 970 if b.section > s { 971 return ErrSectionDone 972 } 973 return nil 974 } 975 976 // StartQuestions prepares the builder for packing Questions. 977 func (b *Builder) StartQuestions() error { 978 if err := b.startCheck(sectionQuestions); err != nil { 979 return err 980 } 981 b.section = sectionQuestions 982 return nil 983 } 984 985 // StartAnswers prepares the builder for packing Answers. 986 func (b *Builder) StartAnswers() error { 987 if err := b.startCheck(sectionAnswers); err != nil { 988 return err 989 } 990 b.section = sectionAnswers 991 return nil 992 } 993 994 // StartAuthorities prepares the builder for packing Authorities. 995 func (b *Builder) StartAuthorities() error { 996 if err := b.startCheck(sectionAuthorities); err != nil { 997 return err 998 } 999 b.section = sectionAuthorities 1000 return nil 1001 } 1002 1003 // StartAdditionals prepares the builder for packing Additionals. 1004 func (b *Builder) StartAdditionals() error { 1005 if err := b.startCheck(sectionAdditionals); err != nil { 1006 return err 1007 } 1008 b.section = sectionAdditionals 1009 return nil 1010 } 1011 1012 func (b *Builder) incrementSectionCount() error { 1013 var count *uint16 1014 var err error 1015 switch b.section { 1016 case sectionQuestions: 1017 count = &b.header.questions 1018 err = errTooManyQuestions 1019 case sectionAnswers: 1020 count = &b.header.answers 1021 err = errTooManyAnswers 1022 case sectionAuthorities: 1023 count = &b.header.authorities 1024 err = errTooManyAuthorities 1025 case sectionAdditionals: 1026 count = &b.header.additionals 1027 err = errTooManyAdditionals 1028 } 1029 if *count == ^uint16(0) { 1030 return err 1031 } 1032 *count++ 1033 return nil 1034 } 1035 1036 // Question adds a single Question. 1037 func (b *Builder) Question(q Question) error { 1038 if b.section < sectionQuestions { 1039 return ErrNotStarted 1040 } 1041 if b.section > sectionQuestions { 1042 return ErrSectionDone 1043 } 1044 msg, err := q.pack(b.msg, b.compression, b.start) 1045 if err != nil { 1046 return err 1047 } 1048 if err := b.incrementSectionCount(); err != nil { 1049 return err 1050 } 1051 b.msg = msg 1052 return nil 1053 } 1054 1055 func (b *Builder) checkResourceSection() error { 1056 if b.section < sectionAnswers { 1057 return ErrNotStarted 1058 } 1059 if b.section > sectionAdditionals { 1060 return ErrSectionDone 1061 } 1062 return nil 1063 } 1064 1065 // CNAMEResource adds a single CNAMEResource. 1066 func (b *Builder) CNAMEResource(h ResourceHeader, r CNAMEResource) error { 1067 if err := b.checkResourceSection(); err != nil { 1068 return err 1069 } 1070 h.Type = r.realType() 1071 msg, length, err := h.pack(b.msg, b.compression, b.start) 1072 if err != nil { 1073 return &nestedError{"ResourceHeader", err} 1074 } 1075 preLen := len(msg) 1076 if msg, err = r.pack(msg, b.compression, b.start); err != nil { 1077 return &nestedError{"CNAMEResource body", err} 1078 } 1079 if err := h.fixLen(msg, length, preLen); err != nil { 1080 return err 1081 } 1082 if err := b.incrementSectionCount(); err != nil { 1083 return err 1084 } 1085 b.msg = msg 1086 return nil 1087 } 1088 1089 // MXResource adds a single MXResource. 1090 func (b *Builder) MXResource(h ResourceHeader, r MXResource) error { 1091 if err := b.checkResourceSection(); err != nil { 1092 return err 1093 } 1094 h.Type = r.realType() 1095 msg, length, err := h.pack(b.msg, b.compression, b.start) 1096 if err != nil { 1097 return &nestedError{"ResourceHeader", err} 1098 } 1099 preLen := len(msg) 1100 if msg, err = r.pack(msg, b.compression, b.start); err != nil { 1101 return &nestedError{"MXResource body", err} 1102 } 1103 if err := h.fixLen(msg, length, preLen); err != nil { 1104 return err 1105 } 1106 if err := b.incrementSectionCount(); err != nil { 1107 return err 1108 } 1109 b.msg = msg 1110 return nil 1111 } 1112 1113 // NSResource adds a single NSResource. 1114 func (b *Builder) NSResource(h ResourceHeader, r NSResource) error { 1115 if err := b.checkResourceSection(); err != nil { 1116 return err 1117 } 1118 h.Type = r.realType() 1119 msg, length, err := h.pack(b.msg, b.compression, b.start) 1120 if err != nil { 1121 return &nestedError{"ResourceHeader", err} 1122 } 1123 preLen := len(msg) 1124 if msg, err = r.pack(msg, b.compression, b.start); err != nil { 1125 return &nestedError{"NSResource body", err} 1126 } 1127 if err := h.fixLen(msg, length, preLen); err != nil { 1128 return err 1129 } 1130 if err := b.incrementSectionCount(); err != nil { 1131 return err 1132 } 1133 b.msg = msg 1134 return nil 1135 } 1136 1137 // PTRResource adds a single PTRResource. 1138 func (b *Builder) PTRResource(h ResourceHeader, r PTRResource) error { 1139 if err := b.checkResourceSection(); err != nil { 1140 return err 1141 } 1142 h.Type = r.realType() 1143 msg, length, err := h.pack(b.msg, b.compression, b.start) 1144 if err != nil { 1145 return &nestedError{"ResourceHeader", err} 1146 } 1147 preLen := len(msg) 1148 if msg, err = r.pack(msg, b.compression, b.start); err != nil { 1149 return &nestedError{"PTRResource body", err} 1150 } 1151 if err := h.fixLen(msg, length, preLen); err != nil { 1152 return err 1153 } 1154 if err := b.incrementSectionCount(); err != nil { 1155 return err 1156 } 1157 b.msg = msg 1158 return nil 1159 } 1160 1161 // SOAResource adds a single SOAResource. 1162 func (b *Builder) SOAResource(h ResourceHeader, r SOAResource) error { 1163 if err := b.checkResourceSection(); err != nil { 1164 return err 1165 } 1166 h.Type = r.realType() 1167 msg, length, err := h.pack(b.msg, b.compression, b.start) 1168 if err != nil { 1169 return &nestedError{"ResourceHeader", err} 1170 } 1171 preLen := len(msg) 1172 if msg, err = r.pack(msg, b.compression, b.start); err != nil { 1173 return &nestedError{"SOAResource body", err} 1174 } 1175 if err := h.fixLen(msg, length, preLen); err != nil { 1176 return err 1177 } 1178 if err := b.incrementSectionCount(); err != nil { 1179 return err 1180 } 1181 b.msg = msg 1182 return nil 1183 } 1184 1185 // TXTResource adds a single TXTResource. 1186 func (b *Builder) TXTResource(h ResourceHeader, r TXTResource) error { 1187 if err := b.checkResourceSection(); err != nil { 1188 return err 1189 } 1190 h.Type = r.realType() 1191 msg, length, err := h.pack(b.msg, b.compression, b.start) 1192 if err != nil { 1193 return &nestedError{"ResourceHeader", err} 1194 } 1195 preLen := len(msg) 1196 if msg, err = r.pack(msg, b.compression, b.start); err != nil { 1197 return &nestedError{"TXTResource body", err} 1198 } 1199 if err := h.fixLen(msg, length, preLen); err != nil { 1200 return err 1201 } 1202 if err := b.incrementSectionCount(); err != nil { 1203 return err 1204 } 1205 b.msg = msg 1206 return nil 1207 } 1208 1209 // SRVResource adds a single SRVResource. 1210 func (b *Builder) SRVResource(h ResourceHeader, r SRVResource) error { 1211 if err := b.checkResourceSection(); err != nil { 1212 return err 1213 } 1214 h.Type = r.realType() 1215 msg, length, err := h.pack(b.msg, b.compression, b.start) 1216 if err != nil { 1217 return &nestedError{"ResourceHeader", err} 1218 } 1219 preLen := len(msg) 1220 if msg, err = r.pack(msg, b.compression, b.start); err != nil { 1221 return &nestedError{"SRVResource body", err} 1222 } 1223 if err := h.fixLen(msg, length, preLen); err != nil { 1224 return err 1225 } 1226 if err := b.incrementSectionCount(); err != nil { 1227 return err 1228 } 1229 b.msg = msg 1230 return nil 1231 } 1232 1233 // AResource adds a single AResource. 1234 func (b *Builder) AResource(h ResourceHeader, r AResource) error { 1235 if err := b.checkResourceSection(); err != nil { 1236 return err 1237 } 1238 h.Type = r.realType() 1239 msg, length, err := h.pack(b.msg, b.compression, b.start) 1240 if err != nil { 1241 return &nestedError{"ResourceHeader", err} 1242 } 1243 preLen := len(msg) 1244 if msg, err = r.pack(msg, b.compression, b.start); err != nil { 1245 return &nestedError{"AResource body", err} 1246 } 1247 if err := h.fixLen(msg, length, preLen); err != nil { 1248 return err 1249 } 1250 if err := b.incrementSectionCount(); err != nil { 1251 return err 1252 } 1253 b.msg = msg 1254 return nil 1255 } 1256 1257 // AAAAResource adds a single AAAAResource. 1258 func (b *Builder) AAAAResource(h ResourceHeader, r AAAAResource) error { 1259 if err := b.checkResourceSection(); err != nil { 1260 return err 1261 } 1262 h.Type = r.realType() 1263 msg, length, err := h.pack(b.msg, b.compression, b.start) 1264 if err != nil { 1265 return &nestedError{"ResourceHeader", err} 1266 } 1267 preLen := len(msg) 1268 if msg, err = r.pack(msg, b.compression, b.start); err != nil { 1269 return &nestedError{"AAAAResource body", err} 1270 } 1271 if err := h.fixLen(msg, length, preLen); err != nil { 1272 return err 1273 } 1274 if err := b.incrementSectionCount(); err != nil { 1275 return err 1276 } 1277 b.msg = msg 1278 return nil 1279 } 1280 1281 // Finish ends message building and generates a binary message. 1282 func (b *Builder) Finish() ([]byte, error) { 1283 if b.section < sectionHeader { 1284 return nil, ErrNotStarted 1285 } 1286 b.section = sectionDone 1287 // Space for the header was allocated in NewBuilder. 1288 b.header.pack(b.msg[b.start:b.start]) 1289 return b.msg, nil 1290 } 1291 1292 // A ResourceHeader is the header of a DNS resource record. There are 1293 // many types of DNS resource records, but they all share the same header. 1294 type ResourceHeader struct { 1295 // Name is the domain name for which this resource record pertains. 1296 Name Name 1297 1298 // Type is the type of DNS resource record. 1299 // 1300 // This field will be set automatically during packing. 1301 Type Type 1302 1303 // Class is the class of network to which this DNS resource record 1304 // pertains. 1305 Class Class 1306 1307 // TTL is the length of time (measured in seconds) which this resource 1308 // record is valid for (time to live). All Resources in a set should 1309 // have the same TTL (RFC 2181 Section 5.2). 1310 TTL uint32 1311 1312 // Length is the length of data in the resource record after the header. 1313 // 1314 // This field will be set automatically during packing. 1315 Length uint16 1316 } 1317 1318 // pack appends the wire format of the ResourceHeader to oldMsg. 1319 // 1320 // The bytes where length was packed are returned as a slice so they can be 1321 // updated after the rest of the Resource has been packed. 1322 func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int, compressionOff int) (msg []byte, length []byte, err error) { 1323 msg = oldMsg 1324 if msg, err = h.Name.pack(msg, compression, compressionOff); err != nil { 1325 return oldMsg, nil, &nestedError{"Name", err} 1326 } 1327 msg = packType(msg, h.Type) 1328 msg = packClass(msg, h.Class) 1329 msg = packUint32(msg, h.TTL) 1330 lenBegin := len(msg) 1331 msg = packUint16(msg, h.Length) 1332 return msg, msg[lenBegin : lenBegin+uint16Len], nil 1333 } 1334 1335 func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) { 1336 newOff := off 1337 var err error 1338 if newOff, err = h.Name.unpack(msg, newOff); err != nil { 1339 return off, &nestedError{"Name", err} 1340 } 1341 if h.Type, newOff, err = unpackType(msg, newOff); err != nil { 1342 return off, &nestedError{"Type", err} 1343 } 1344 if h.Class, newOff, err = unpackClass(msg, newOff); err != nil { 1345 return off, &nestedError{"Class", err} 1346 } 1347 if h.TTL, newOff, err = unpackUint32(msg, newOff); err != nil { 1348 return off, &nestedError{"TTL", err} 1349 } 1350 if h.Length, newOff, err = unpackUint16(msg, newOff); err != nil { 1351 return off, &nestedError{"Length", err} 1352 } 1353 return newOff, nil 1354 } 1355 1356 func (h *ResourceHeader) fixLen(msg []byte, length []byte, preLen int) error { 1357 conLen := len(msg) - preLen 1358 if conLen > int(^uint16(0)) { 1359 return errResTooLong 1360 } 1361 1362 // Fill in the length now that we know how long the content is. 1363 packUint16(length[:0], uint16(conLen)) 1364 h.Length = uint16(conLen) 1365 1366 return nil 1367 } 1368 1369 func skipResource(msg []byte, off int) (int, error) { 1370 newOff, err := skipName(msg, off) 1371 if err != nil { 1372 return off, &nestedError{"Name", err} 1373 } 1374 if newOff, err = skipType(msg, newOff); err != nil { 1375 return off, &nestedError{"Type", err} 1376 } 1377 if newOff, err = skipClass(msg, newOff); err != nil { 1378 return off, &nestedError{"Class", err} 1379 } 1380 if newOff, err = skipUint32(msg, newOff); err != nil { 1381 return off, &nestedError{"TTL", err} 1382 } 1383 length, newOff, err := unpackUint16(msg, newOff) 1384 if err != nil { 1385 return off, &nestedError{"Length", err} 1386 } 1387 if newOff += int(length); newOff > len(msg) { 1388 return off, errResourceLen 1389 } 1390 return newOff, nil 1391 } 1392 1393 // packUint16 appends the wire format of field to msg. 1394 func packUint16(msg []byte, field uint16) []byte { 1395 return append(msg, byte(field>>8), byte(field)) 1396 } 1397 1398 func unpackUint16(msg []byte, off int) (uint16, int, error) { 1399 if off+uint16Len > len(msg) { 1400 return 0, off, errBaseLen 1401 } 1402 return uint16(msg[off])<<8 | uint16(msg[off+1]), off + uint16Len, nil 1403 } 1404 1405 func skipUint16(msg []byte, off int) (int, error) { 1406 if off+uint16Len > len(msg) { 1407 return off, errBaseLen 1408 } 1409 return off + uint16Len, nil 1410 } 1411 1412 // packType appends the wire format of field to msg. 1413 func packType(msg []byte, field Type) []byte { 1414 return packUint16(msg, uint16(field)) 1415 } 1416 1417 func unpackType(msg []byte, off int) (Type, int, error) { 1418 t, o, err := unpackUint16(msg, off) 1419 return Type(t), o, err 1420 } 1421 1422 func skipType(msg []byte, off int) (int, error) { 1423 return skipUint16(msg, off) 1424 } 1425 1426 // packClass appends the wire format of field to msg. 1427 func packClass(msg []byte, field Class) []byte { 1428 return packUint16(msg, uint16(field)) 1429 } 1430 1431 func unpackClass(msg []byte, off int) (Class, int, error) { 1432 c, o, err := unpackUint16(msg, off) 1433 return Class(c), o, err 1434 } 1435 1436 func skipClass(msg []byte, off int) (int, error) { 1437 return skipUint16(msg, off) 1438 } 1439 1440 // packUint32 appends the wire format of field to msg. 1441 func packUint32(msg []byte, field uint32) []byte { 1442 return append( 1443 msg, 1444 byte(field>>24), 1445 byte(field>>16), 1446 byte(field>>8), 1447 byte(field), 1448 ) 1449 } 1450 1451 func unpackUint32(msg []byte, off int) (uint32, int, error) { 1452 if off+uint32Len > len(msg) { 1453 return 0, off, errBaseLen 1454 } 1455 v := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3]) 1456 return v, off + uint32Len, nil 1457 } 1458 1459 func skipUint32(msg []byte, off int) (int, error) { 1460 if off+uint32Len > len(msg) { 1461 return off, errBaseLen 1462 } 1463 return off + uint32Len, nil 1464 } 1465 1466 // packText appends the wire format of field to msg. 1467 func packText(msg []byte, field string) ([]byte, error) { 1468 l := len(field) 1469 if l > 255 { 1470 return nil, errStringTooLong 1471 } 1472 msg = append(msg, byte(l)) 1473 msg = append(msg, field...) 1474 1475 return msg, nil 1476 } 1477 1478 func unpackText(msg []byte, off int) (string, int, error) { 1479 if off >= len(msg) { 1480 return "", off, errBaseLen 1481 } 1482 beginOff := off + 1 1483 endOff := beginOff + int(msg[off]) 1484 if endOff > len(msg) { 1485 return "", off, errCalcLen 1486 } 1487 return string(msg[beginOff:endOff]), endOff, nil 1488 } 1489 1490 func skipText(msg []byte, off int) (int, error) { 1491 if off >= len(msg) { 1492 return off, errBaseLen 1493 } 1494 endOff := off + 1 + int(msg[off]) 1495 if endOff > len(msg) { 1496 return off, errCalcLen 1497 } 1498 return endOff, nil 1499 } 1500 1501 // packBytes appends the wire format of field to msg. 1502 func packBytes(msg []byte, field []byte) []byte { 1503 return append(msg, field...) 1504 } 1505 1506 func unpackBytes(msg []byte, off int, field []byte) (int, error) { 1507 newOff := off + len(field) 1508 if newOff > len(msg) { 1509 return off, errBaseLen 1510 } 1511 copy(field, msg[off:newOff]) 1512 return newOff, nil 1513 } 1514 1515 func skipBytes(msg []byte, off int, field []byte) (int, error) { 1516 newOff := off + len(field) 1517 if newOff > len(msg) { 1518 return off, errBaseLen 1519 } 1520 return newOff, nil 1521 } 1522 1523 const nameLen = 255 1524 1525 // A Name is a non-encoded domain name. It is used instead of strings to avoid 1526 // allocations. 1527 type Name struct { 1528 Data [nameLen]byte 1529 Length uint8 1530 } 1531 1532 // NewName creates a new Name from a string. 1533 func NewName(name string) (Name, error) { 1534 if len([]byte(name)) > nameLen { 1535 return Name{}, errCalcLen 1536 } 1537 n := Name{Length: uint8(len(name))} 1538 copy(n.Data[:], []byte(name)) 1539 return n, nil 1540 } 1541 1542 func (n Name) String() string { 1543 return string(n.Data[:n.Length]) 1544 } 1545 1546 // pack appends the wire format of the Name to msg. 1547 // 1548 // Domain names are a sequence of counted strings split at the dots. They end 1549 // with a zero-length string. Compression can be used to reuse domain suffixes. 1550 // 1551 // The compression map will be updated with new domain suffixes. If compression 1552 // is nil, compression will not be used. 1553 func (n *Name) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 1554 oldMsg := msg 1555 1556 // Add a trailing dot to canonicalize name. 1557 if n.Length == 0 || n.Data[n.Length-1] != '.' { 1558 return oldMsg, errNonCanonicalName 1559 } 1560 1561 // Allow root domain. 1562 if n.Data[0] == '.' && n.Length == 1 { 1563 return append(msg, 0), nil 1564 } 1565 1566 // Emit sequence of counted strings, chopping at dots. 1567 for i, begin := 0, 0; i < int(n.Length); i++ { 1568 // Check for the end of the segment. 1569 if n.Data[i] == '.' { 1570 // The two most significant bits have special meaning. 1571 // It isn't allowed for segments to be long enough to 1572 // need them. 1573 if i-begin >= 1<<6 { 1574 return oldMsg, errSegTooLong 1575 } 1576 1577 // Segments must have a non-zero length. 1578 if i-begin == 0 { 1579 return oldMsg, errZeroSegLen 1580 } 1581 1582 msg = append(msg, byte(i-begin)) 1583 1584 for j := begin; j < i; j++ { 1585 msg = append(msg, n.Data[j]) 1586 } 1587 1588 begin = i + 1 1589 continue 1590 } 1591 1592 // We can only compress domain suffixes starting with a new 1593 // segment. A pointer is two bytes with the two most significant 1594 // bits set to 1 to indicate that it is a pointer. 1595 if (i == 0 || n.Data[i-1] == '.') && compression != nil { 1596 if ptr, ok := compression[string(n.Data[i:])]; ok { 1597 // Hit. Emit a pointer instead of the rest of 1598 // the domain. 1599 return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil 1600 } 1601 1602 // Miss. Add the suffix to the compression table if the 1603 // offset can be stored in the available 14 bytes. 1604 if len(msg) <= int(^uint16(0)>>2) { 1605 compression[string(n.Data[i:])] = len(msg) - compressionOff 1606 } 1607 } 1608 } 1609 return append(msg, 0), nil 1610 } 1611 1612 // unpack unpacks a domain name. 1613 func (n *Name) unpack(msg []byte, off int) (int, error) { 1614 return n.unpackCompressed(msg, off, true /* allowCompression */) 1615 } 1616 1617 func (n *Name) unpackCompressed(msg []byte, off int, allowCompression bool) (int, error) { 1618 // currOff is the current working offset. 1619 currOff := off 1620 1621 // newOff is the offset where the next record will start. Pointers lead 1622 // to data that belongs to other names and thus doesn't count towards to 1623 // the usage of this name. 1624 newOff := off 1625 1626 // ptr is the number of pointers followed. 1627 var ptr int 1628 1629 // Name is a slice representation of the name data. 1630 name := n.Data[:0] 1631 1632 Loop: 1633 for { 1634 if currOff >= len(msg) { 1635 return off, errBaseLen 1636 } 1637 c := int(msg[currOff]) 1638 currOff++ 1639 switch c & 0xC0 { 1640 case 0x00: // String segment 1641 if c == 0x00 { 1642 // A zero length signals the end of the name. 1643 break Loop 1644 } 1645 endOff := currOff + c 1646 if endOff > len(msg) { 1647 return off, errCalcLen 1648 } 1649 name = append(name, msg[currOff:endOff]...) 1650 name = append(name, '.') 1651 currOff = endOff 1652 case 0xC0: // Pointer 1653 if !allowCompression { 1654 return off, errCompressedSRV 1655 } 1656 if currOff >= len(msg) { 1657 return off, errInvalidPtr 1658 } 1659 c1 := msg[currOff] 1660 currOff++ 1661 if ptr == 0 { 1662 newOff = currOff 1663 } 1664 // Don't follow too many pointers, maybe there's a loop. 1665 if ptr++; ptr > 10 { 1666 return off, errTooManyPtr 1667 } 1668 currOff = (c^0xC0)<<8 | int(c1) 1669 default: 1670 // Prefixes 0x80 and 0x40 are reserved. 1671 return off, errReserved 1672 } 1673 } 1674 if len(name) == 0 { 1675 name = append(name, '.') 1676 } 1677 if len(name) > len(n.Data) { 1678 return off, errCalcLen 1679 } 1680 n.Length = uint8(len(name)) 1681 if ptr == 0 { 1682 newOff = currOff 1683 } 1684 return newOff, nil 1685 } 1686 1687 func skipName(msg []byte, off int) (int, error) { 1688 // newOff is the offset where the next record will start. Pointers lead 1689 // to data that belongs to other names and thus doesn't count towards to 1690 // the usage of this name. 1691 newOff := off 1692 1693 Loop: 1694 for { 1695 if newOff >= len(msg) { 1696 return off, errBaseLen 1697 } 1698 c := int(msg[newOff]) 1699 newOff++ 1700 switch c & 0xC0 { 1701 case 0x00: 1702 if c == 0x00 { 1703 // A zero length signals the end of the name. 1704 break Loop 1705 } 1706 // literal string 1707 newOff += c 1708 if newOff > len(msg) { 1709 return off, errCalcLen 1710 } 1711 case 0xC0: 1712 // Pointer to somewhere else in msg. 1713 1714 // Pointers are two bytes. 1715 newOff++ 1716 1717 // Don't follow the pointer as the data here has ended. 1718 break Loop 1719 default: 1720 // Prefixes 0x80 and 0x40 are reserved. 1721 return off, errReserved 1722 } 1723 } 1724 1725 return newOff, nil 1726 } 1727 1728 // A Question is a DNS query. 1729 type Question struct { 1730 Name Name 1731 Type Type 1732 Class Class 1733 } 1734 1735 // pack appends the wire format of the Question to msg. 1736 func (q *Question) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 1737 msg, err := q.Name.pack(msg, compression, compressionOff) 1738 if err != nil { 1739 return msg, &nestedError{"Name", err} 1740 } 1741 msg = packType(msg, q.Type) 1742 return packClass(msg, q.Class), nil 1743 } 1744 1745 func unpackResourceBody(msg []byte, off int, hdr ResourceHeader) (ResourceBody, int, error) { 1746 var ( 1747 r ResourceBody 1748 err error 1749 name string 1750 ) 1751 switch hdr.Type { 1752 case TypeA: 1753 var rb AResource 1754 rb, err = unpackAResource(msg, off) 1755 r = &rb 1756 name = "A" 1757 case TypeNS: 1758 var rb NSResource 1759 rb, err = unpackNSResource(msg, off) 1760 r = &rb 1761 name = "NS" 1762 case TypeCNAME: 1763 var rb CNAMEResource 1764 rb, err = unpackCNAMEResource(msg, off) 1765 r = &rb 1766 name = "CNAME" 1767 case TypeSOA: 1768 var rb SOAResource 1769 rb, err = unpackSOAResource(msg, off) 1770 r = &rb 1771 name = "SOA" 1772 case TypePTR: 1773 var rb PTRResource 1774 rb, err = unpackPTRResource(msg, off) 1775 r = &rb 1776 name = "PTR" 1777 case TypeMX: 1778 var rb MXResource 1779 rb, err = unpackMXResource(msg, off) 1780 r = &rb 1781 name = "MX" 1782 case TypeTXT: 1783 var rb TXTResource 1784 rb, err = unpackTXTResource(msg, off, hdr.Length) 1785 r = &rb 1786 name = "TXT" 1787 case TypeAAAA: 1788 var rb AAAAResource 1789 rb, err = unpackAAAAResource(msg, off) 1790 r = &rb 1791 name = "AAAA" 1792 case TypeSRV: 1793 var rb SRVResource 1794 rb, err = unpackSRVResource(msg, off) 1795 r = &rb 1796 name = "SRV" 1797 } 1798 if err != nil { 1799 return nil, off, &nestedError{name + " record", err} 1800 } 1801 if r == nil { 1802 return nil, off, errors.New("invalid resource type: " + string(hdr.Type+'0')) 1803 } 1804 return r, off + int(hdr.Length), nil 1805 } 1806 1807 // A CNAMEResource is a CNAME Resource record. 1808 type CNAMEResource struct { 1809 CNAME Name 1810 } 1811 1812 func (r *CNAMEResource) realType() Type { 1813 return TypeCNAME 1814 } 1815 1816 // pack appends the wire format of the CNAMEResource to msg. 1817 func (r *CNAMEResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 1818 return r.CNAME.pack(msg, compression, compressionOff) 1819 } 1820 1821 func unpackCNAMEResource(msg []byte, off int) (CNAMEResource, error) { 1822 var cname Name 1823 if _, err := cname.unpack(msg, off); err != nil { 1824 return CNAMEResource{}, err 1825 } 1826 return CNAMEResource{cname}, nil 1827 } 1828 1829 // An MXResource is an MX Resource record. 1830 type MXResource struct { 1831 Pref uint16 1832 MX Name 1833 } 1834 1835 func (r *MXResource) realType() Type { 1836 return TypeMX 1837 } 1838 1839 // pack appends the wire format of the MXResource to msg. 1840 func (r *MXResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 1841 oldMsg := msg 1842 msg = packUint16(msg, r.Pref) 1843 msg, err := r.MX.pack(msg, compression, compressionOff) 1844 if err != nil { 1845 return oldMsg, &nestedError{"MXResource.MX", err} 1846 } 1847 return msg, nil 1848 } 1849 1850 func unpackMXResource(msg []byte, off int) (MXResource, error) { 1851 pref, off, err := unpackUint16(msg, off) 1852 if err != nil { 1853 return MXResource{}, &nestedError{"Pref", err} 1854 } 1855 var mx Name 1856 if _, err := mx.unpack(msg, off); err != nil { 1857 return MXResource{}, &nestedError{"MX", err} 1858 } 1859 return MXResource{pref, mx}, nil 1860 } 1861 1862 // An NSResource is an NS Resource record. 1863 type NSResource struct { 1864 NS Name 1865 } 1866 1867 func (r *NSResource) realType() Type { 1868 return TypeNS 1869 } 1870 1871 // pack appends the wire format of the NSResource to msg. 1872 func (r *NSResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 1873 return r.NS.pack(msg, compression, compressionOff) 1874 } 1875 1876 func unpackNSResource(msg []byte, off int) (NSResource, error) { 1877 var ns Name 1878 if _, err := ns.unpack(msg, off); err != nil { 1879 return NSResource{}, err 1880 } 1881 return NSResource{ns}, nil 1882 } 1883 1884 // A PTRResource is a PTR Resource record. 1885 type PTRResource struct { 1886 PTR Name 1887 } 1888 1889 func (r *PTRResource) realType() Type { 1890 return TypePTR 1891 } 1892 1893 // pack appends the wire format of the PTRResource to msg. 1894 func (r *PTRResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 1895 return r.PTR.pack(msg, compression, compressionOff) 1896 } 1897 1898 func unpackPTRResource(msg []byte, off int) (PTRResource, error) { 1899 var ptr Name 1900 if _, err := ptr.unpack(msg, off); err != nil { 1901 return PTRResource{}, err 1902 } 1903 return PTRResource{ptr}, nil 1904 } 1905 1906 // An SOAResource is an SOA Resource record. 1907 type SOAResource struct { 1908 NS Name 1909 MBox Name 1910 Serial uint32 1911 Refresh uint32 1912 Retry uint32 1913 Expire uint32 1914 1915 // MinTTL the is the default TTL of Resources records which did not 1916 // contain a TTL value and the TTL of negative responses. (RFC 2308 1917 // Section 4) 1918 MinTTL uint32 1919 } 1920 1921 func (r *SOAResource) realType() Type { 1922 return TypeSOA 1923 } 1924 1925 // pack appends the wire format of the SOAResource to msg. 1926 func (r *SOAResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 1927 oldMsg := msg 1928 msg, err := r.NS.pack(msg, compression, compressionOff) 1929 if err != nil { 1930 return oldMsg, &nestedError{"SOAResource.NS", err} 1931 } 1932 msg, err = r.MBox.pack(msg, compression, compressionOff) 1933 if err != nil { 1934 return oldMsg, &nestedError{"SOAResource.MBox", err} 1935 } 1936 msg = packUint32(msg, r.Serial) 1937 msg = packUint32(msg, r.Refresh) 1938 msg = packUint32(msg, r.Retry) 1939 msg = packUint32(msg, r.Expire) 1940 return packUint32(msg, r.MinTTL), nil 1941 } 1942 1943 func unpackSOAResource(msg []byte, off int) (SOAResource, error) { 1944 var ns Name 1945 off, err := ns.unpack(msg, off) 1946 if err != nil { 1947 return SOAResource{}, &nestedError{"NS", err} 1948 } 1949 var mbox Name 1950 if off, err = mbox.unpack(msg, off); err != nil { 1951 return SOAResource{}, &nestedError{"MBox", err} 1952 } 1953 serial, off, err := unpackUint32(msg, off) 1954 if err != nil { 1955 return SOAResource{}, &nestedError{"Serial", err} 1956 } 1957 refresh, off, err := unpackUint32(msg, off) 1958 if err != nil { 1959 return SOAResource{}, &nestedError{"Refresh", err} 1960 } 1961 retry, off, err := unpackUint32(msg, off) 1962 if err != nil { 1963 return SOAResource{}, &nestedError{"Retry", err} 1964 } 1965 expire, off, err := unpackUint32(msg, off) 1966 if err != nil { 1967 return SOAResource{}, &nestedError{"Expire", err} 1968 } 1969 minTTL, _, err := unpackUint32(msg, off) 1970 if err != nil { 1971 return SOAResource{}, &nestedError{"MinTTL", err} 1972 } 1973 return SOAResource{ns, mbox, serial, refresh, retry, expire, minTTL}, nil 1974 } 1975 1976 // A TXTResource is a TXT Resource record. 1977 type TXTResource struct { 1978 TXT []string 1979 } 1980 1981 func (r *TXTResource) realType() Type { 1982 return TypeTXT 1983 } 1984 1985 // pack appends the wire format of the TXTResource to msg. 1986 func (r *TXTResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 1987 oldMsg := msg 1988 for _, s := range r.TXT { 1989 var err error 1990 msg, err = packText(msg, s) 1991 if err != nil { 1992 return oldMsg, err 1993 } 1994 } 1995 return msg, nil 1996 } 1997 1998 func unpackTXTResource(msg []byte, off int, length uint16) (TXTResource, error) { 1999 txts := make([]string, 0, 1) 2000 for n := uint16(0); n < length; { 2001 var t string 2002 var err error 2003 if t, off, err = unpackText(msg, off); err != nil { 2004 return TXTResource{}, &nestedError{"text", err} 2005 } 2006 // Check if we got too many bytes. 2007 if length-n < uint16(len(t))+1 { 2008 return TXTResource{}, errCalcLen 2009 } 2010 n += uint16(len(t)) + 1 2011 txts = append(txts, t) 2012 } 2013 return TXTResource{txts}, nil 2014 } 2015 2016 // An SRVResource is an SRV Resource record. 2017 type SRVResource struct { 2018 Priority uint16 2019 Weight uint16 2020 Port uint16 2021 Target Name // Not compressed as per RFC 2782. 2022 } 2023 2024 func (r *SRVResource) realType() Type { 2025 return TypeSRV 2026 } 2027 2028 // pack appends the wire format of the SRVResource to msg. 2029 func (r *SRVResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 2030 oldMsg := msg 2031 msg = packUint16(msg, r.Priority) 2032 msg = packUint16(msg, r.Weight) 2033 msg = packUint16(msg, r.Port) 2034 msg, err := r.Target.pack(msg, nil, compressionOff) 2035 if err != nil { 2036 return oldMsg, &nestedError{"SRVResource.Target", err} 2037 } 2038 return msg, nil 2039 } 2040 2041 func unpackSRVResource(msg []byte, off int) (SRVResource, error) { 2042 priority, off, err := unpackUint16(msg, off) 2043 if err != nil { 2044 return SRVResource{}, &nestedError{"Priority", err} 2045 } 2046 weight, off, err := unpackUint16(msg, off) 2047 if err != nil { 2048 return SRVResource{}, &nestedError{"Weight", err} 2049 } 2050 port, off, err := unpackUint16(msg, off) 2051 if err != nil { 2052 return SRVResource{}, &nestedError{"Port", err} 2053 } 2054 var target Name 2055 if _, err := target.unpackCompressed(msg, off, false /* allowCompression */); err != nil { 2056 return SRVResource{}, &nestedError{"Target", err} 2057 } 2058 return SRVResource{priority, weight, port, target}, nil 2059 } 2060 2061 // An AResource is an A Resource record. 2062 type AResource struct { 2063 A [4]byte 2064 } 2065 2066 func (r *AResource) realType() Type { 2067 return TypeA 2068 } 2069 2070 // pack appends the wire format of the AResource to msg. 2071 func (r *AResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 2072 return packBytes(msg, r.A[:]), nil 2073 } 2074 2075 func unpackAResource(msg []byte, off int) (AResource, error) { 2076 var a [4]byte 2077 if _, err := unpackBytes(msg, off, a[:]); err != nil { 2078 return AResource{}, err 2079 } 2080 return AResource{a}, nil 2081 } 2082 2083 // An AAAAResource is an AAAA Resource record. 2084 type AAAAResource struct { 2085 AAAA [16]byte 2086 } 2087 2088 func (r *AAAAResource) realType() Type { 2089 return TypeAAAA 2090 } 2091 2092 // pack appends the wire format of the AAAAResource to msg. 2093 func (r *AAAAResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { 2094 return packBytes(msg, r.AAAA[:]), nil 2095 } 2096 2097 func unpackAAAAResource(msg []byte, off int) (AAAAResource, error) { 2098 var aaaa [16]byte 2099 if _, err := unpackBytes(msg, off, aaaa[:]); err != nil { 2100 return AAAAResource{}, err 2101 } 2102 return AAAAResource{aaaa}, nil 2103 }