diff options
Diffstat (limited to 'vendor/golang.org/x/net')
36 files changed, 2042 insertions, 670 deletions
diff --git a/vendor/golang.org/x/net/context/context.go b/vendor/golang.org/x/net/context/context.go index f143ed6a1..d3681ab42 100644 --- a/vendor/golang.org/x/net/context/context.go +++ b/vendor/golang.org/x/net/context/context.go @@ -36,103 +36,6 @@ // Contexts. package context // import "golang.org/x/net/context" -import "time" - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - // - // WithCancel arranges for Done to be closed when cancel is called; - // WithDeadline arranges for Done to be closed when the deadline - // expires; WithTimeout arranges for Done to be closed when the timeout - // elapses. - // - // Done is provided for use in select statements: - // - // // Stream generates values with DoSomething and sends them to out - // // until DoSomething returns an error or ctx.Done is closed. - // func Stream(ctx context.Context, out chan<- Value) error { - // for { - // v, err := DoSomething(ctx) - // if err != nil { - // return err - // } - // select { - // case <-ctx.Done(): - // return ctx.Err() - // case out <- v: - // } - // } - // } - // - // See http://blog.golang.org/pipelines for more examples of how to use - // a Done channel for cancelation. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - // - // A key identifies a specific value in a Context. Functions that wish - // to store values in Context typically allocate a key in a global - // variable then use that key as the argument to context.WithValue and - // Context.Value. A key can be any type that supports equality; - // packages should define keys as an unexported type to avoid - // collisions. - // - // Packages that define a Context key should provide type-safe accessors - // for the values stores using that key: - // - // // Package user defines a User type that's stored in Contexts. - // package user - // - // import "golang.org/x/net/context" - // - // // User is the type of value stored in the Contexts. - // type User struct {...} - // - // // key is an unexported type for keys defined in this package. - // // This prevents collisions with keys defined in other packages. - // type key int - // - // // userKey is the key for user.User values in Contexts. It is - // // unexported; clients use user.NewContext and user.FromContext - // // instead of using this key directly. - // var userKey key = 0 - // - // // NewContext returns a new Context that carries value u. - // func NewContext(ctx context.Context, u *User) context.Context { - // return context.WithValue(ctx, userKey, u) - // } - // - // // FromContext returns the User value stored in ctx, if any. - // func FromContext(ctx context.Context) (*User, bool) { - // u, ok := ctx.Value(userKey).(*User) - // return u, ok - // } - Value(key interface{}) interface{} -} - // Background returns a non-nil, empty Context. It is never canceled, has no // values, and has no deadline. It is typically used by the main function, // initialization, and tests, and as the top-level Context for incoming @@ -149,8 +52,3 @@ func Background() Context { func TODO() Context { return todo } - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc func() diff --git a/vendor/golang.org/x/net/context/go19.go b/vendor/golang.org/x/net/context/go19.go new file mode 100644 index 000000000..d88bd1db1 --- /dev/null +++ b/vendor/golang.org/x/net/context/go19.go @@ -0,0 +1,20 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build go1.9 + +package context + +import "context" // standard library's context, as of Go 1.7 + +// A Context carries a deadline, a cancelation signal, and other values across +// API boundaries. +// +// Context's methods may be called by multiple goroutines simultaneously. +type Context = context.Context + +// A CancelFunc tells an operation to abandon its work. +// A CancelFunc does not wait for the work to stop. +// After the first call, subsequent calls to a CancelFunc do nothing. +type CancelFunc = context.CancelFunc diff --git a/vendor/golang.org/x/net/context/pre_go19.go b/vendor/golang.org/x/net/context/pre_go19.go new file mode 100644 index 000000000..b105f80be --- /dev/null +++ b/vendor/golang.org/x/net/context/pre_go19.go @@ -0,0 +1,109 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !go1.9 + +package context + +import "time" + +// A Context carries a deadline, a cancelation signal, and other values across +// API boundaries. +// +// Context's methods may be called by multiple goroutines simultaneously. +type Context interface { + // Deadline returns the time when work done on behalf of this context + // should be canceled. Deadline returns ok==false when no deadline is + // set. Successive calls to Deadline return the same results. + Deadline() (deadline time.Time, ok bool) + + // Done returns a channel that's closed when work done on behalf of this + // context should be canceled. Done may return nil if this context can + // never be canceled. Successive calls to Done return the same value. + // + // WithCancel arranges for Done to be closed when cancel is called; + // WithDeadline arranges for Done to be closed when the deadline + // expires; WithTimeout arranges for Done to be closed when the timeout + // elapses. + // + // Done is provided for use in select statements: + // + // // Stream generates values with DoSomething and sends them to out + // // until DoSomething returns an error or ctx.Done is closed. + // func Stream(ctx context.Context, out chan<- Value) error { + // for { + // v, err := DoSomething(ctx) + // if err != nil { + // return err + // } + // select { + // case <-ctx.Done(): + // return ctx.Err() + // case out <- v: + // } + // } + // } + // + // See http://blog.golang.org/pipelines for more examples of how to use + // a Done channel for cancelation. + Done() <-chan struct{} + + // Err returns a non-nil error value after Done is closed. Err returns + // Canceled if the context was canceled or DeadlineExceeded if the + // context's deadline passed. No other values for Err are defined. + // After Done is closed, successive calls to Err return the same value. + Err() error + + // Value returns the value associated with this context for key, or nil + // if no value is associated with key. Successive calls to Value with + // the same key returns the same result. + // + // Use context values only for request-scoped data that transits + // processes and API boundaries, not for passing optional parameters to + // functions. + // + // A key identifies a specific value in a Context. Functions that wish + // to store values in Context typically allocate a key in a global + // variable then use that key as the argument to context.WithValue and + // Context.Value. A key can be any type that supports equality; + // packages should define keys as an unexported type to avoid + // collisions. + // + // Packages that define a Context key should provide type-safe accessors + // for the values stores using that key: + // + // // Package user defines a User type that's stored in Contexts. + // package user + // + // import "golang.org/x/net/context" + // + // // User is the type of value stored in the Contexts. + // type User struct {...} + // + // // key is an unexported type for keys defined in this package. + // // This prevents collisions with keys defined in other packages. + // type key int + // + // // userKey is the key for user.User values in Contexts. It is + // // unexported; clients use user.NewContext and user.FromContext + // // instead of using this key directly. + // var userKey key = 0 + // + // // NewContext returns a new Context that carries value u. + // func NewContext(ctx context.Context, u *User) context.Context { + // return context.WithValue(ctx, userKey, u) + // } + // + // // FromContext returns the User value stored in ctx, if any. + // func FromContext(ctx context.Context) (*User, bool) { + // u, ok := ctx.Value(userKey).(*User) + // return u, ok + // } + Value(key interface{}) interface{} +} + +// A CancelFunc tells an operation to abandon its work. +// A CancelFunc does not wait for the work to stop. +// After the first call, subsequent calls to a CancelFunc do nothing. +type CancelFunc func() diff --git a/vendor/golang.org/x/net/context/withtimeout_test.go b/vendor/golang.org/x/net/context/withtimeout_test.go index a6754dc36..e6f56691d 100644 --- a/vendor/golang.org/x/net/context/withtimeout_test.go +++ b/vendor/golang.org/x/net/context/withtimeout_test.go @@ -11,16 +11,21 @@ import ( "golang.org/x/net/context" ) +// This example passes a context with a timeout to tell a blocking function that +// it should abandon its work after the timeout elapses. func ExampleWithTimeout() { // Pass a context with a timeout to tell a blocking function that it // should abandon its work after the timeout elapses. - ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + select { - case <-time.After(200 * time.Millisecond): + case <-time.After(1 * time.Second): fmt.Println("overslept") case <-ctx.Done(): fmt.Println(ctx.Err()) // prints "context deadline exceeded" } + // Output: // context deadline exceeded } diff --git a/vendor/golang.org/x/net/dns/dnsmessage/example_test.go b/vendor/golang.org/x/net/dns/dnsmessage/example_test.go new file mode 100644 index 000000000..5415c2d3a --- /dev/null +++ b/vendor/golang.org/x/net/dns/dnsmessage/example_test.go @@ -0,0 +1,132 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package dnsmessage_test + +import ( + "fmt" + "net" + "strings" + + "golang.org/x/net/dns/dnsmessage" +) + +func mustNewName(name string) dnsmessage.Name { + n, err := dnsmessage.NewName(name) + if err != nil { + panic(err) + } + return n +} + +func ExampleParser() { + msg := dnsmessage.Message{ + Header: dnsmessage.Header{Response: true, Authoritative: true}, + Questions: []dnsmessage.Question{ + { + Name: mustNewName("foo.bar.example.com."), + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + }, + { + Name: mustNewName("bar.example.com."), + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + }, + }, + Answers: []dnsmessage.Resource{ + { + dnsmessage.ResourceHeader{ + Name: mustNewName("foo.bar.example.com."), + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + }, + &dnsmessage.AResource{[4]byte{127, 0, 0, 1}}, + }, + { + dnsmessage.ResourceHeader{ + Name: mustNewName("bar.example.com."), + Type: dnsmessage.TypeA, + Class: dnsmessage.ClassINET, + }, + &dnsmessage.AResource{[4]byte{127, 0, 0, 2}}, + }, + }, + } + + buf, err := msg.Pack() + if err != nil { + panic(err) + } + + wantName := "bar.example.com." + + var p dnsmessage.Parser + if _, err := p.Start(buf); err != nil { + panic(err) + } + + for { + q, err := p.Question() + if err == dnsmessage.ErrSectionDone { + break + } + if err != nil { + panic(err) + } + + if q.Name.String() != wantName { + continue + } + + fmt.Println("Found question for name", wantName) + if err := p.SkipAllQuestions(); err != nil { + panic(err) + } + break + } + + var gotIPs []net.IP + for { + h, err := p.AnswerHeader() + if err == dnsmessage.ErrSectionDone { + break + } + if err != nil { + panic(err) + } + + if (h.Type != dnsmessage.TypeA && h.Type != dnsmessage.TypeAAAA) || h.Class != dnsmessage.ClassINET { + continue + } + + if !strings.EqualFold(h.Name.String(), wantName) { + if err := p.SkipAnswer(); err != nil { + panic(err) + } + continue + } + + switch h.Type { + case dnsmessage.TypeA: + r, err := p.AResource() + if err != nil { + panic(err) + } + gotIPs = append(gotIPs, r.A[:]) + case dnsmessage.TypeAAAA: + r, err := p.AAAAResource() + if err != nil { + panic(err) + } + gotIPs = append(gotIPs, r.AAAA[:]) + } + } + + fmt.Printf("Found A/AAAA records for name %s: %v\n", wantName, gotIPs) + + // Output: + // Found question for name bar.example.com. + // Found A/AAAA records for name bar.example.com.: [127.0.0.2] +} diff --git a/vendor/golang.org/x/net/dns/dnsmessage/message.go b/vendor/golang.org/x/net/dns/dnsmessage/message.go index da43b0ba4..19b260dea 100644 --- a/vendor/golang.org/x/net/dns/dnsmessage/message.go +++ b/vendor/golang.org/x/net/dns/dnsmessage/message.go @@ -68,18 +68,19 @@ const ( var ( // ErrNotStarted indicates that the prerequisite information isn't // available yet because the previous records haven't been appropriately - // parsed or skipped. - ErrNotStarted = errors.New("parsing of this type isn't available yet") + // parsed, skipped or finished. + ErrNotStarted = errors.New("parsing/packing of this type isn't available yet") // ErrSectionDone indicated that all records in the section have been - // parsed. - ErrSectionDone = errors.New("parsing of this section has completed") + // parsed or finished. + ErrSectionDone = errors.New("parsing/packing of this section has completed") errBaseLen = errors.New("insufficient data for base length type") errCalcLen = errors.New("insufficient data for calculated length type") errReserved = errors.New("segment prefix is reserved") errTooManyPtr = errors.New("too many pointers (>10)") errInvalidPtr = errors.New("invalid pointer") + errNilResouceBody = errors.New("nil resource body") errResourceLen = errors.New("insufficient data for resource body length") errSegTooLong = errors.New("segment length too long") errZeroSegLen = errors.New("zero length segment") @@ -88,6 +89,28 @@ var ( errTooManyAnswers = errors.New("too many Answers to pack (>65535)") errTooManyAuthorities = errors.New("too many Authorities to pack (>65535)") errTooManyAdditionals = errors.New("too many Additionals to pack (>65535)") + errNonCanonicalName = errors.New("name is not in canonical format (it must end with a .)") +) + +// Internal constants. +const ( + // packStartingCap is the default initial buffer size allocated during + // packing. + // + // The starting capacity doesn't matter too much, but most DNS responses + // Will be <= 512 bytes as it is the limit for DNS over UDP. + packStartingCap = 512 + + // uint16Len is the length (in bytes) of a uint16. + uint16Len = 2 + + // uint32Len is the length (in bytes) of a uint32. + uint32Len = 4 + + // headerLen is the length (in bytes) of a DNS header. + // + // A header is comprised of 6 uint16s and no padding. + headerLen = 6 * uint16Len ) type nestedError struct { @@ -148,7 +171,8 @@ type Message struct { type section uint8 const ( - sectionHeader section = iota + sectionNotStarted section = iota + sectionHeader sectionQuestions sectionAnswers sectionAuthorities @@ -241,10 +265,13 @@ func (h *header) header() Header { } // A Resource is a DNS resource record. -type Resource interface { - // Header return's the Resource's ResourceHeader. - Header() *ResourceHeader +type Resource struct { + Header ResourceHeader + Body ResourceBody +} +// A ResourceBody is a DNS resource record minus the header. +type ResourceBody interface { // pack packs a Resource except for its header. pack(msg []byte, compression map[string]int) ([]byte, error) @@ -253,25 +280,24 @@ type Resource interface { realType() Type } -func packResource(msg []byte, resource Resource, compression map[string]int) ([]byte, error) { +func (r *Resource) pack(msg []byte, compression map[string]int) ([]byte, error) { + if r.Body == nil { + return msg, errNilResouceBody + } oldMsg := msg - resource.Header().Type = resource.realType() - msg, length, err := resource.Header().pack(msg, compression) + r.Header.Type = r.Body.realType() + msg, length, err := r.Header.pack(msg, compression) if err != nil { return msg, &nestedError{"ResourceHeader", err} } preLen := len(msg) - msg, err = resource.pack(msg, compression) + msg, err = r.Body.pack(msg, compression) if err != nil { return msg, &nestedError{"content", err} } - conLen := len(msg) - preLen - if conLen > int(^uint16(0)) { - return oldMsg, errResTooLong + if err := r.Header.fixLen(msg, length, preLen); err != nil { + return oldMsg, err } - // Fill in the length now that we know how long the content is. - packUint16(length[:0], uint16(conLen)) - resource.Header().Length = uint16(conLen) return msg, nil } @@ -330,14 +356,15 @@ func (p *Parser) checkAdvance(sec section) error { func (p *Parser) resource(sec section) (Resource, error) { var r Resource - hdr, err := p.resourceHeader(sec) + var err error + r.Header, err = p.resourceHeader(sec) if err != nil { return r, err } p.resHeaderValid = false - r, p.off, err = unpackResource(p.msg, p.off, hdr) + r.Body, p.off, err = unpackResourceBody(p.msg, p.off, r.Header) if err != nil { - return nil, &nestedError{"unpacking " + sectionNames[sec], err} + return Resource{}, &nestedError{"unpacking " + sectionNames[sec], err} } p.index++ return r, nil @@ -389,7 +416,8 @@ func (p *Parser) Question() (Question, error) { if err := p.checkAdvance(sectionQuestions); err != nil { return Question{}, err } - name, off, err := unpackName(p.msg, p.off) + var name Name + off, err := name.unpack(p.msg, p.off) if err != nil { return Question{}, &nestedError{"unpacking Question.Name", err} } @@ -575,6 +603,168 @@ func (p *Parser) SkipAllAdditionals() error { } } +// CNAMEResource parses a single CNAMEResource. +// +// One of the XXXHeader methods must have been called before calling this +// method. +func (p *Parser) CNAMEResource() (CNAMEResource, error) { + if !p.resHeaderValid || p.resHeader.Type != TypeCNAME { + return CNAMEResource{}, ErrNotStarted + } + r, err := unpackCNAMEResource(p.msg, p.off) + if err != nil { + return CNAMEResource{}, err + } + p.off += int(p.resHeader.Length) + p.resHeaderValid = false + p.index++ + return r, nil +} + +// MXResource parses a single MXResource. +// +// One of the XXXHeader methods must have been called before calling this +// method. +func (p *Parser) MXResource() (MXResource, error) { + if !p.resHeaderValid || p.resHeader.Type != TypeMX { + return MXResource{}, ErrNotStarted + } + r, err := unpackMXResource(p.msg, p.off) + if err != nil { + return MXResource{}, err + } + p.off += int(p.resHeader.Length) + p.resHeaderValid = false + p.index++ + return r, nil +} + +// NSResource parses a single NSResource. +// +// One of the XXXHeader methods must have been called before calling this +// method. +func (p *Parser) NSResource() (NSResource, error) { + if !p.resHeaderValid || p.resHeader.Type != TypeNS { + return NSResource{}, ErrNotStarted + } + r, err := unpackNSResource(p.msg, p.off) + if err != nil { + return NSResource{}, err + } + p.off += int(p.resHeader.Length) + p.resHeaderValid = false + p.index++ + return r, nil +} + +// PTRResource parses a single PTRResource. +// +// One of the XXXHeader methods must have been called before calling this +// method. +func (p *Parser) PTRResource() (PTRResource, error) { + if !p.resHeaderValid || p.resHeader.Type != TypePTR { + return PTRResource{}, ErrNotStarted + } + r, err := unpackPTRResource(p.msg, p.off) + if err != nil { + return PTRResource{}, err + } + p.off += int(p.resHeader.Length) + p.resHeaderValid = false + p.index++ + return r, nil +} + +// SOAResource parses a single SOAResource. +// +// One of the XXXHeader methods must have been called before calling this +// method. +func (p *Parser) SOAResource() (SOAResource, error) { + if !p.resHeaderValid || p.resHeader.Type != TypeSOA { + return SOAResource{}, ErrNotStarted + } + r, err := unpackSOAResource(p.msg, p.off) + if err != nil { + return SOAResource{}, err + } + p.off += int(p.resHeader.Length) + p.resHeaderValid = false + p.index++ + return r, nil +} + +// TXTResource parses a single TXTResource. +// +// One of the XXXHeader methods must have been called before calling this +// method. +func (p *Parser) TXTResource() (TXTResource, error) { + if !p.resHeaderValid || p.resHeader.Type != TypeTXT { + return TXTResource{}, ErrNotStarted + } + r, err := unpackTXTResource(p.msg, p.off, p.resHeader.Length) + if err != nil { + return TXTResource{}, err + } + p.off += int(p.resHeader.Length) + p.resHeaderValid = false + p.index++ + return r, nil +} + +// SRVResource parses a single SRVResource. +// +// One of the XXXHeader methods must have been called before calling this +// method. +func (p *Parser) SRVResource() (SRVResource, error) { + if !p.resHeaderValid || p.resHeader.Type != TypeSRV { + return SRVResource{}, ErrNotStarted + } + r, err := unpackSRVResource(p.msg, p.off) + if err != nil { + return SRVResource{}, err + } + p.off += int(p.resHeader.Length) + p.resHeaderValid = false + p.index++ + return r, nil +} + +// AResource parses a single AResource. +// +// One of the XXXHeader methods must have been called before calling this +// method. +func (p *Parser) AResource() (AResource, error) { + if !p.resHeaderValid || p.resHeader.Type != TypeA { + return AResource{}, ErrNotStarted + } + r, err := unpackAResource(p.msg, p.off) + if err != nil { + return AResource{}, err + } + p.off += int(p.resHeader.Length) + p.resHeaderValid = false + p.index++ + return r, nil +} + +// AAAAResource parses a single AAAAResource. +// +// One of the XXXHeader methods must have been called before calling this +// method. +func (p *Parser) AAAAResource() (AAAAResource, error) { + if !p.resHeaderValid || p.resHeader.Type != TypeAAAA { + return AAAAResource{}, ErrNotStarted + } + r, err := unpackAAAAResource(p.msg, p.off) + if err != nil { + return AAAAResource{}, err + } + p.off += int(p.resHeader.Length) + p.resHeaderValid = false + p.index++ + return r, nil +} + // Unpack parses a full Message. func (m *Message) Unpack(msg []byte) error { var p Parser @@ -623,9 +813,7 @@ func (m *Message) Pack() ([]byte, error) { h.authorities = uint16(len(m.Authorities)) h.additionals = uint16(len(m.Additionals)) - // The starting capacity doesn't matter too much, but most DNS responses - // Will be <= 512 bytes as it is the limit for DNS over UDP. - msg := make([]byte, 0, 512) + msg := make([]byte, 0, packStartingCap) msg = h.pack(msg) @@ -639,31 +827,27 @@ func (m *Message) Pack() ([]byte, error) { // compression will help ensure compliance. compression := map[string]int{} - for _, q := range m.Questions { + for i := range m.Questions { var err error - msg, err = q.pack(msg, compression) - if err != nil { + if msg, err = m.Questions[i].pack(msg, compression); err != nil { return nil, &nestedError{"packing Question", err} } } - for _, a := range m.Answers { + for i := range m.Answers { var err error - msg, err = packResource(msg, a, compression) - if err != nil { + if msg, err = m.Answers[i].pack(msg, compression); err != nil { return nil, &nestedError{"packing Answer", err} } } - for _, a := range m.Authorities { + for i := range m.Authorities { var err error - msg, err = packResource(msg, a, compression) - if err != nil { + if msg, err = m.Authorities[i].pack(msg, compression); err != nil { return nil, &nestedError{"packing Authority", err} } } - for _, a := range m.Additionals { + for i := range m.Additionals { var err error - msg, err = packResource(msg, a, compression) - if err != nil { + if msg, err = m.Additionals[i].pack(msg, compression); err != nil { return nil, &nestedError{"packing Additional", err} } } @@ -671,11 +855,369 @@ func (m *Message) Pack() ([]byte, error) { return msg, nil } -// An ResourceHeader is the header of a DNS resource record. There are +// A Builder allows incrementally packing a DNS message. +type Builder struct { + msg []byte + header header + section section + compression map[string]int +} + +// Start initializes the builder. +// +// buf is optional (nil is fine), but if provided, Start takes ownership of buf. +func (b *Builder) Start(buf []byte, h Header) { + b.StartWithoutCompression(buf, h) + b.compression = map[string]int{} +} + +// StartWithoutCompression initializes the builder with compression disabled. +// +// This avoids compression related allocations, but can result in larger message +// sizes. Be careful with this mode as it can cause messages to exceed the UDP +// size limit. +// +// buf is optional (nil is fine), but if provided, Start takes ownership of buf. +func (b *Builder) StartWithoutCompression(buf []byte, h Header) { + *b = Builder{msg: buf} + b.header.id, b.header.bits = h.pack() + if cap(b.msg) < headerLen { + b.msg = make([]byte, 0, packStartingCap) + } + b.msg = b.msg[:headerLen] + b.section = sectionHeader +} + +func (b *Builder) startCheck(s section) error { + if b.section <= sectionNotStarted { + return ErrNotStarted + } + if b.section > s { + return ErrSectionDone + } + return nil +} + +// StartQuestions prepares the builder for packing Questions. +func (b *Builder) StartQuestions() error { + if err := b.startCheck(sectionQuestions); err != nil { + return err + } + b.section = sectionQuestions + return nil +} + +// StartAnswers prepares the builder for packing Answers. +func (b *Builder) StartAnswers() error { + if err := b.startCheck(sectionAnswers); err != nil { + return err + } + b.section = sectionAnswers + return nil +} + +// StartAuthorities prepares the builder for packing Authorities. +func (b *Builder) StartAuthorities() error { + if err := b.startCheck(sectionAuthorities); err != nil { + return err + } + b.section = sectionAuthorities + return nil +} + +// StartAdditionals prepares the builder for packing Additionals. +func (b *Builder) StartAdditionals() error { + if err := b.startCheck(sectionAdditionals); err != nil { + return err + } + b.section = sectionAdditionals + return nil +} + +func (b *Builder) incrementSectionCount() error { + var count *uint16 + var err error + switch b.section { + case sectionQuestions: + count = &b.header.questions + err = errTooManyQuestions + case sectionAnswers: + count = &b.header.answers + err = errTooManyAnswers + case sectionAuthorities: + count = &b.header.authorities + err = errTooManyAuthorities + case sectionAdditionals: + count = &b.header.additionals + err = errTooManyAdditionals + } + if *count == ^uint16(0) { + return err + } + *count++ + return nil +} + +// Question adds a single Question. +func (b *Builder) Question(q Question) error { + if b.section < sectionQuestions { + return ErrNotStarted + } + if b.section > sectionQuestions { + return ErrSectionDone + } + msg, err := q.pack(b.msg, b.compression) + if err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +func (b *Builder) checkResourceSection() error { + if b.section < sectionAnswers { + return ErrNotStarted + } + if b.section > sectionAdditionals { + return ErrSectionDone + } + return nil +} + +// CNAMEResource adds a single CNAMEResource. +func (b *Builder) CNAMEResource(h ResourceHeader, r CNAMEResource) error { + if err := b.checkResourceSection(); err != nil { + return err + } + h.Type = r.realType() + msg, length, err := h.pack(b.msg, b.compression) + if err != nil { + return &nestedError{"ResourceHeader", err} + } + preLen := len(msg) + if msg, err = r.pack(msg, b.compression); err != nil { + return &nestedError{"CNAMEResource body", err} + } + if err := h.fixLen(msg, length, preLen); err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +// MXResource adds a single MXResource. +func (b *Builder) MXResource(h ResourceHeader, r MXResource) error { + if err := b.checkResourceSection(); err != nil { + return err + } + h.Type = r.realType() + msg, length, err := h.pack(b.msg, b.compression) + if err != nil { + return &nestedError{"ResourceHeader", err} + } + preLen := len(msg) + if msg, err = r.pack(msg, b.compression); err != nil { + return &nestedError{"MXResource body", err} + } + if err := h.fixLen(msg, length, preLen); err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +// NSResource adds a single NSResource. +func (b *Builder) NSResource(h ResourceHeader, r NSResource) error { + if err := b.checkResourceSection(); err != nil { + return err + } + h.Type = r.realType() + msg, length, err := h.pack(b.msg, b.compression) + if err != nil { + return &nestedError{"ResourceHeader", err} + } + preLen := len(msg) + if msg, err = r.pack(msg, b.compression); err != nil { + return &nestedError{"NSResource body", err} + } + if err := h.fixLen(msg, length, preLen); err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +// PTRResource adds a single PTRResource. +func (b *Builder) PTRResource(h ResourceHeader, r PTRResource) error { + if err := b.checkResourceSection(); err != nil { + return err + } + h.Type = r.realType() + msg, length, err := h.pack(b.msg, b.compression) + if err != nil { + return &nestedError{"ResourceHeader", err} + } + preLen := len(msg) + if msg, err = r.pack(msg, b.compression); err != nil { + return &nestedError{"PTRResource body", err} + } + if err := h.fixLen(msg, length, preLen); err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +// SOAResource adds a single SOAResource. +func (b *Builder) SOAResource(h ResourceHeader, r SOAResource) error { + if err := b.checkResourceSection(); err != nil { + return err + } + h.Type = r.realType() + msg, length, err := h.pack(b.msg, b.compression) + if err != nil { + return &nestedError{"ResourceHeader", err} + } + preLen := len(msg) + if msg, err = r.pack(msg, b.compression); err != nil { + return &nestedError{"SOAResource body", err} + } + if err := h.fixLen(msg, length, preLen); err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +// TXTResource adds a single TXTResource. +func (b *Builder) TXTResource(h ResourceHeader, r TXTResource) error { + if err := b.checkResourceSection(); err != nil { + return err + } + h.Type = r.realType() + msg, length, err := h.pack(b.msg, b.compression) + if err != nil { + return &nestedError{"ResourceHeader", err} + } + preLen := len(msg) + if msg, err = r.pack(msg, b.compression); err != nil { + return &nestedError{"TXTResource body", err} + } + if err := h.fixLen(msg, length, preLen); err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +// SRVResource adds a single SRVResource. +func (b *Builder) SRVResource(h ResourceHeader, r SRVResource) error { + if err := b.checkResourceSection(); err != nil { + return err + } + h.Type = r.realType() + msg, length, err := h.pack(b.msg, b.compression) + if err != nil { + return &nestedError{"ResourceHeader", err} + } + preLen := len(msg) + if msg, err = r.pack(msg, b.compression); err != nil { + return &nestedError{"SRVResource body", err} + } + if err := h.fixLen(msg, length, preLen); err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +// AResource adds a single AResource. +func (b *Builder) AResource(h ResourceHeader, r AResource) error { + if err := b.checkResourceSection(); err != nil { + return err + } + h.Type = r.realType() + msg, length, err := h.pack(b.msg, b.compression) + if err != nil { + return &nestedError{"ResourceHeader", err} + } + preLen := len(msg) + if msg, err = r.pack(msg, b.compression); err != nil { + return &nestedError{"AResource body", err} + } + if err := h.fixLen(msg, length, preLen); err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +// AAAAResource adds a single AAAAResource. +func (b *Builder) AAAAResource(h ResourceHeader, r AAAAResource) error { + if err := b.checkResourceSection(); err != nil { + return err + } + h.Type = r.realType() + msg, length, err := h.pack(b.msg, b.compression) + if err != nil { + return &nestedError{"ResourceHeader", err} + } + preLen := len(msg) + if msg, err = r.pack(msg, b.compression); err != nil { + return &nestedError{"AAAAResource body", err} + } + if err := h.fixLen(msg, length, preLen); err != nil { + return err + } + if err := b.incrementSectionCount(); err != nil { + return err + } + b.msg = msg + return nil +} + +// Finish ends message building and generates a binary packet. +func (b *Builder) Finish() ([]byte, error) { + if b.section < sectionHeader { + return nil, ErrNotStarted + } + b.section = sectionDone + b.header.pack(b.msg[:0]) + return b.msg, nil +} + +// A ResourceHeader is the header of a DNS resource record. There are // many types of DNS resource records, but they all share the same header. type ResourceHeader struct { // Name is the domain name for which this resource record pertains. - Name string + Name Name // Type is the type of DNS resource record. // @@ -697,17 +1239,12 @@ type ResourceHeader struct { Length uint16 } -// Header implements Resource.Header. -func (h *ResourceHeader) Header() *ResourceHeader { - return h -} - // pack packs all of the fields in a ResourceHeader except for the length. The // length bytes are returned as a slice so they can be filled in after the rest // of the Resource has been packed. func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int) (msg []byte, length []byte, err error) { msg = oldMsg - if msg, err = packName(msg, h.Name, compression); err != nil { + if msg, err = h.Name.pack(msg, compression); err != nil { return oldMsg, nil, &nestedError{"Name", err} } msg = packType(msg, h.Type) @@ -715,13 +1252,13 @@ func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int) (msg [] msg = packUint32(msg, h.TTL) lenBegin := len(msg) msg = packUint16(msg, h.Length) - return msg, msg[lenBegin:], nil + return msg, msg[lenBegin : lenBegin+uint16Len], nil } func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) { newOff := off var err error - if h.Name, newOff, err = unpackName(msg, newOff); err != nil { + if newOff, err = h.Name.unpack(msg, newOff); err != nil { return off, &nestedError{"Name", err} } if h.Type, newOff, err = unpackType(msg, newOff); err != nil { @@ -739,6 +1276,19 @@ func (h *ResourceHeader) unpack(msg []byte, off int) (int, error) { return newOff, nil } +func (h *ResourceHeader) fixLen(msg []byte, length []byte, preLen int) error { + conLen := len(msg) - preLen + if conLen > int(^uint16(0)) { + return errResTooLong + } + + // Fill in the length now that we know how long the content is. + packUint16(length[:0], uint16(conLen)) + h.Length = uint16(conLen) + + return nil +} + func skipResource(msg []byte, off int) (int, error) { newOff, err := skipName(msg, off) if err != nil { @@ -768,17 +1318,17 @@ func packUint16(msg []byte, field uint16) []byte { } func unpackUint16(msg []byte, off int) (uint16, int, error) { - if off+2 > len(msg) { + if off+uint16Len > len(msg) { return 0, off, errBaseLen } - return uint16(msg[off])<<8 | uint16(msg[off+1]), off + 2, nil + return uint16(msg[off])<<8 | uint16(msg[off+1]), off + uint16Len, nil } func skipUint16(msg []byte, off int) (int, error) { - if off+2 > len(msg) { + if off+uint16Len > len(msg) { return off, errBaseLen } - return off + 2, nil + return off + uint16Len, nil } func packType(msg []byte, field Type) []byte { @@ -818,18 +1368,18 @@ func packUint32(msg []byte, field uint32) []byte { } func unpackUint32(msg []byte, off int) (uint32, int, error) { - if off+4 > len(msg) { + if off+uint32Len > len(msg) { return 0, off, errBaseLen } v := uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3]) - return v, off + 4, nil + return v, off + uint32Len, nil } func skipUint32(msg []byte, off int) (int, error) { - if off+4 > len(msg) { + if off+uint32Len > len(msg) { return off, errBaseLen } - return off + 4, nil + return off + uint32Len, nil } func packText(msg []byte, field string) []byte { @@ -889,30 +1439,53 @@ func skipBytes(msg []byte, off int, field []byte) (int, error) { return newOff, nil } -// packName packs a domain name. +const nameLen = 255 + +// A Name is a non-encoded domain name. It is used instead of strings to avoid +// allocations. +type Name struct { + Data [nameLen]byte + Length uint8 +} + +// NewName creates a new Name from a string. +func NewName(name string) (Name, error) { + if len([]byte(name)) > nameLen { + return Name{}, errCalcLen + } + n := Name{Length: uint8(len(name))} + copy(n.Data[:], []byte(name)) + return n, nil +} + +func (n Name) String() string { + return string(n.Data[:n.Length]) +} + +// pack packs a domain name. // // Domain names are a sequence of counted strings split at the dots. They end // with a zero-length string. Compression can be used to reuse domain suffixes. // // The compression map will be updated with new domain suffixes. If compression // is nil, compression will not be used. -func packName(msg []byte, name string, compression map[string]int) ([]byte, error) { +func (n *Name) pack(msg []byte, compression map[string]int) ([]byte, error) { oldMsg := msg // Add a trailing dot to canonicalize name. - if n := len(name); n == 0 || name[n-1] != '.' { - name += "." + if n.Length == 0 || n.Data[n.Length-1] != '.' { + return oldMsg, errNonCanonicalName } // Allow root domain. - if name == "." { + if n.Data[0] == '.' && n.Length == 1 { return append(msg, 0), nil } // Emit sequence of counted strings, chopping at dots. - for i, begin := 0, 0; i < len(name); i++ { + for i, begin := 0, 0; i < int(n.Length); i++ { // Check for the end of the segment. - if name[i] == '.' { + if n.Data[i] == '.' { // The two most significant bits have special meaning. // It isn't allowed for segments to be long enough to // need them. @@ -928,7 +1501,7 @@ func packName(msg []byte, name string, compression map[string]int) ([]byte, erro msg = append(msg, byte(i-begin)) for j := begin; j < i; j++ { - msg = append(msg, name[j]) + msg = append(msg, n.Data[j]) } begin = i + 1 @@ -938,8 +1511,8 @@ func packName(msg []byte, name string, compression map[string]int) ([]byte, erro // We can only compress domain suffixes starting with a new // segment. A pointer is two bytes with the two most significant // bits set to 1 to indicate that it is a pointer. - if (i == 0 || name[i-1] == '.') && compression != nil { - if ptr, ok := compression[name[i:]]; ok { + if (i == 0 || n.Data[i-1] == '.') && compression != nil { + if ptr, ok := compression[string(n.Data[i:])]; ok { // Hit. Emit a pointer instead of the rest of // the domain. return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil @@ -948,15 +1521,15 @@ func packName(msg []byte, name string, compression map[string]int) ([]byte, erro // Miss. Add the suffix to the compression table if the // offset can be stored in the available 14 bytes. if len(msg) <= int(^uint16(0)>>2) { - compression[name[i:]] = len(msg) + compression[string(n.Data[i:])] = len(msg) } } } return append(msg, 0), nil } -// unpackName unpacks a domain name. -func unpackName(msg []byte, off int) (string, int, error) { +// unpack unpacks a domain name. +func (n *Name) unpack(msg []byte, off int) (int, error) { // currOff is the current working offset. currOff := off @@ -965,15 +1538,16 @@ func unpackName(msg []byte, off int) (string, int, error) { // the usage of this name. newOff := off - // name is the domain name being unpacked. - name := make([]byte, 0, 255) - // ptr is the number of pointers followed. var ptr int + + // Name is a slice representation of the name data. + name := n.Data[:0] + Loop: for { if currOff >= len(msg) { - return "", off, errBaseLen + return off, errBaseLen } c := int(msg[currOff]) currOff++ @@ -985,14 +1559,14 @@ Loop: } endOff := currOff + c if endOff > len(msg) { - return "", off, errCalcLen + return off, errCalcLen } name = append(name, msg[currOff:endOff]...) name = append(name, '.') currOff = endOff case 0xC0: // Pointer if currOff >= len(msg) { - return "", off, errInvalidPtr + return off, errInvalidPtr } c1 := msg[currOff] currOff++ @@ -1001,21 +1575,25 @@ Loop: } // Don't follow too many pointers, maybe there's a loop. if ptr++; ptr > 10 { - return "", off, errTooManyPtr + return off, errTooManyPtr } currOff = (c^0xC0)<<8 | int(c1) default: // Prefixes 0x80 and 0x40 are reserved. - return "", off, errReserved + return off, errReserved } } if len(name) == 0 { name = append(name, '.') } + if len(name) > len(n.Data) { + return off, errCalcLen + } + n.Length = uint8(len(name)) if ptr == 0 { newOff = currOff } - return string(name), newOff, nil + return newOff, nil } func skipName(msg []byte, off int) (int, error) { @@ -1061,13 +1639,13 @@ Loop: // A Question is a DNS query. type Question struct { - Name string + Name Name Type Type Class Class } func (q *Question) pack(msg []byte, compression map[string]int) ([]byte, error) { - msg, err := packName(msg, q.Name, compression) + msg, err := q.Name.pack(msg, compression) if err != nil { return msg, &nestedError{"Name", err} } @@ -1075,55 +1653,71 @@ func (q *Question) pack(msg []byte, compression map[string]int) ([]byte, error) return packClass(msg, q.Class), nil } -func unpackResource(msg []byte, off int, hdr ResourceHeader) (Resource, int, error) { +func unpackResourceBody(msg []byte, off int, hdr ResourceHeader) (ResourceBody, int, error) { var ( - r Resource + r ResourceBody err error name string ) switch hdr.Type { case TypeA: - r, err = unpackAResource(hdr, msg, off) + var rb AResource + rb, err = unpackAResource(msg, off) + r = &rb name = "A" case TypeNS: - r, err = unpackNSResource(hdr, msg, off) + var rb NSResource + rb, err = unpackNSResource(msg, off) + r = &rb name = "NS" case TypeCNAME: - r, err = unpackCNAMEResource(hdr, msg, off) + var rb CNAMEResource + rb, err = unpackCNAMEResource(msg, off) + r = &rb name = "CNAME" case TypeSOA: - r, err = unpackSOAResource(hdr, msg, off) + var rb SOAResource + rb, err = unpackSOAResource(msg, off) + r = &rb name = "SOA" case TypePTR: - r, err = unpackPTRResource(hdr, msg, off) + var rb PTRResource + rb, err = unpackPTRResource(msg, off) + r = &rb name = "PTR" case TypeMX: - r, err = unpackMXResource(hdr, msg, off) + var rb MXResource + rb, err = unpackMXResource(msg, off) + r = &rb name = "MX" case TypeTXT: - r, err = unpackTXTResource(hdr, msg, off) + var rb TXTResource + rb, err = unpackTXTResource(msg, off, hdr.Length) + r = &rb name = "TXT" case TypeAAAA: - r, err = unpackAAAAResource(hdr, msg, off) + var rb AAAAResource + rb, err = unpackAAAAResource(msg, off) + r = &rb name = "AAAA" case TypeSRV: - r, err = unpackSRVResource(hdr, msg, off) + var rb SRVResource + rb, err = unpackSRVResource(msg, off) + r = &rb name = "SRV" } if err != nil { return nil, off, &nestedError{name + " record", err} } - if r != nil { - return r, off + int(hdr.Length), nil + if r == nil { + return nil, off, errors.New("invalid resource type: " + string(hdr.Type+'0')) } - return nil, off, errors.New("invalid resource type: " + string(hdr.Type+'0')) + return r, off + int(hdr.Length), nil } // A CNAMEResource is a CNAME Resource record. type CNAMEResource struct { - ResourceHeader - - CNAME string + CNAME Name } func (r *CNAMEResource) realType() Type { @@ -1131,23 +1725,21 @@ func (r *CNAMEResource) realType() Type { } func (r *CNAMEResource) pack(msg []byte, compression map[string]int) ([]byte, error) { - return packName(msg, r.CNAME, compression) + return r.CNAME.pack(msg, compression) } -func unpackCNAMEResource(hdr ResourceHeader, msg []byte, off int) (*CNAMEResource, error) { - cname, _, err := unpackName(msg, off) - if err != nil { - return nil, err +func unpackCNAMEResource(msg []byte, off int) (CNAMEResource, error) { + var cname Name + if _, err := cname.unpack(msg, off); err != nil { + return CNAMEResource{}, err } - return &CNAMEResource{hdr, cname}, nil + return CNAMEResource{cname}, nil } // An MXResource is an MX Resource record. type MXResource struct { - ResourceHeader - Pref uint16 - MX string + MX Name } func (r *MXResource) realType() Type { @@ -1157,30 +1749,28 @@ func (r *MXResource) realType() Type { func (r *MXResource) pack(msg []byte, compression map[string]int) ([]byte, error) { oldMsg := msg msg = packUint16(msg, r.Pref) - msg, err := packName(msg, r.MX, compression) + msg, err := r.MX.pack(msg, compression) if err != nil { return oldMsg, &nestedError{"MXResource.MX", err} } return msg, nil } -func unpackMXResource(hdr ResourceHeader, msg []byte, off int) (*MXResource, error) { +func unpackMXResource(msg []byte, off int) (MXResource, error) { pref, off, err := unpackUint16(msg, off) if err != nil { - return nil, &nestedError{"Pref", err} + return MXResource{}, &nestedError{"Pref", err} } - mx, _, err := unpackName(msg, off) - if err != nil { - return nil, &nestedError{"MX", err} + var mx Name + if _, err := mx.unpack(msg, off); err != nil { + return MXResource{}, &nestedError{"MX", err} } - return &MXResource{hdr, pref, mx}, nil + return MXResource{pref, mx}, nil } // An NSResource is an NS Resource record. type NSResource struct { - ResourceHeader - - NS string + NS Name } func (r *NSResource) realType() Type { @@ -1188,22 +1778,20 @@ func (r *NSResource) realType() Type { } func (r *NSResource) pack(msg []byte, compression map[string]int) ([]byte, error) { - return packName(msg, r.NS, compression) + return r.NS.pack(msg, compression) } -func unpackNSResource(hdr ResourceHeader, msg []byte, off int) (*NSResource, error) { - ns, _, err := unpackName(msg, off) - if err != nil { - return nil, err +func unpackNSResource(msg []byte, off int) (NSResource, error) { + var ns Name + if _, err := ns.unpack(msg, off); err != nil { + return NSResource{}, err } - return &NSResource{hdr, ns}, nil + return NSResource{ns}, nil } // A PTRResource is a PTR Resource record. type PTRResource struct { - ResourceHeader - - PTR string + PTR Name } func (r *PTRResource) realType() Type { @@ -1211,23 +1799,21 @@ func (r *PTRResource) realType() Type { } func (r *PTRResource) pack(msg []byte, compression map[string]int) ([]byte, error) { - return packName(msg, r.PTR, compression) + return r.PTR.pack(msg, compression) } -func unpackPTRResource(hdr ResourceHeader, msg []byte, off int) (*PTRResource, error) { - ptr, _, err := unpackName(msg, off) - if err != nil { - return nil, err +func unpackPTRResource(msg []byte, off int) (PTRResource, error) { + var ptr Name + if _, err := ptr.unpack(msg, off); err != nil { + return PTRResource{}, err } - return &PTRResource{hdr, ptr}, nil + return PTRResource{ptr}, nil } // An SOAResource is an SOA Resource record. type SOAResource struct { - ResourceHeader - - NS string - MBox string + NS Name + MBox Name Serial uint32 Refresh uint32 Retry uint32 @@ -1245,11 +1831,11 @@ func (r *SOAResource) realType() Type { func (r *SOAResource) pack(msg []byte, compression map[string]int) ([]byte, error) { oldMsg := msg - msg, err := packName(msg, r.NS, compression) + msg, err := r.NS.pack(msg, compression) if err != nil { return oldMsg, &nestedError{"SOAResource.NS", err} } - msg, err = packName(msg, r.MBox, compression) + msg, err = r.MBox.pack(msg, compression) if err != nil { return oldMsg, &nestedError{"SOAResource.MBox", err} } @@ -1260,42 +1846,41 @@ func (r *SOAResource) pack(msg []byte, compression map[string]int) ([]byte, erro return packUint32(msg, r.MinTTL), nil } -func unpackSOAResource(hdr ResourceHeader, msg []byte, off int) (*SOAResource, error) { - ns, off, err := unpackName(msg, off) +func unpackSOAResource(msg []byte, off int) (SOAResource, error) { + var ns Name + off, err := ns.unpack(msg, off) if err != nil { - return nil, &nestedError{"NS", err} + return SOAResource{}, &nestedError{"NS", err} } - mbox, off, err := unpackName(msg, off) - if err != nil { - return nil, &nestedError{"MBox", err} + var mbox Name + if off, err = mbox.unpack(msg, off); err != nil { + return SOAResource{}, &nestedError{"MBox", err} } serial, off, err := unpackUint32(msg, off) if err != nil { - return nil, &nestedError{"Serial", err} + return SOAResource{}, &nestedError{"Serial", err} } refresh, off, err := unpackUint32(msg, off) if err != nil { - return nil, &nestedError{"Refresh", err} + return SOAResource{}, &nestedError{"Refresh", err} } retry, off, err := unpackUint32(msg, off) if err != nil { - return nil, &nestedError{"Retry", err} + return SOAResource{}, &nestedError{"Retry", err} } expire, off, err := unpackUint32(msg, off) if err != nil { - return nil, &nestedError{"Expire", err} + return SOAResource{}, &nestedError{"Expire", err} } minTTL, _, err := unpackUint32(msg, off) if err != nil { - return nil, &nestedError{"MinTTL", err} + return SOAResource{}, &nestedError{"MinTTL", err} } - return &SOAResource{hdr, ns, mbox, serial, refresh, retry, expire, minTTL}, nil + return SOAResource{ns, mbox, serial, refresh, retry, expire, minTTL}, nil } // A TXTResource is a TXT Resource record. type TXTResource struct { - ResourceHeader - Txt string // Not a domain name. } @@ -1307,32 +1892,30 @@ func (r *TXTResource) pack(msg []byte, compression map[string]int) ([]byte, erro return packText(msg, r.Txt), nil } -func unpackTXTResource(hdr ResourceHeader, msg []byte, off int) (*TXTResource, error) { +func unpackTXTResource(msg []byte, off int, length uint16) (TXTResource, error) { var txt string - for n := uint16(0); n < hdr.Length; { + for n := uint16(0); n < length; { var t string var err error if t, off, err = unpackText(msg, off); err != nil { - return nil, &nestedError{"text", err} + return TXTResource{}, &nestedError{"text", err} } // Check if we got too many bytes. - if hdr.Length-n < uint16(len(t))+1 { - return nil, errCalcLen + if length-n < uint16(len(t))+1 { + return TXTResource{}, errCalcLen } n += uint16(len(t)) + 1 txt += t } - return &TXTResource{hdr, txt}, nil + return TXTResource{txt}, nil } // An SRVResource is an SRV Resource record. type SRVResource struct { - ResourceHeader - Priority uint16 Weight uint16 Port uint16 - Target string // Not compressed as per RFC 2782. + Target Name // Not compressed as per RFC 2782. } func (r *SRVResource) realType() Type { @@ -1344,37 +1927,35 @@ func (r *SRVResource) pack(msg []byte, compression map[string]int) ([]byte, erro msg = packUint16(msg, r.Priority) msg = packUint16(msg, r.Weight) msg = packUint16(msg, r.Port) - msg, err := packName(msg, r.Target, nil) + msg, err := r.Target.pack(msg, nil) if err != nil { return oldMsg, &nestedError{"SRVResource.Target", err} } return msg, nil } -func unpackSRVResource(hdr ResourceHeader, msg []byte, off int) (*SRVResource, error) { +func unpackSRVResource(msg []byte, off int) (SRVResource, error) { priority, off, err := unpackUint16(msg, off) if err != nil { - return nil, &nestedError{"Priority", err} + return SRVResource{}, &nestedError{"Priority", err} } weight, off, err := unpackUint16(msg, off) if err != nil { - return nil, &nestedError{"Weight", err} + return SRVResource{}, &nestedError{"Weight", err} } port, off, err := unpackUint16(msg, off) if err != nil { - return nil, &nestedError{"Port", err} + return SRVResource{}, &nestedError{"Port", err} } - target, _, err := unpackName(msg, off) - if err != nil { - return nil, &nestedError{"Target", err} + var target Name + if _, err := target.unpack(msg, off); err != nil { + return SRVResource{}, &nestedError{"Target", err} } - return &SRVResource{hdr, priority, weight, port, target}, nil + return SRVResource{priority, weight, port, target}, nil } // An AResource is an A Resource record. type AResource struct { - ResourceHeader - A [4]byte } @@ -1386,18 +1967,16 @@ func (r *AResource) pack(msg []byte, compression map[string]int) ([]byte, error) return packBytes(msg, r.A[:]), nil } -func unpackAResource(hdr ResourceHeader, msg []byte, off int) (*AResource, error) { +func unpackAResource(msg []byte, off int) (AResource, error) { var a [4]byte if _, err := unpackBytes(msg, off, a[:]); err != nil { - return nil, err + return AResource{}, err } - return &AResource{hdr, a}, nil + return AResource{a}, nil } // An AAAAResource is an AAAA Resource record. type AAAAResource struct { - ResourceHeader - AAAA [16]byte } @@ -1409,10 +1988,10 @@ func (r *AAAAResource) pack(msg []byte, compression map[string]int) ([]byte, err return packBytes(msg, r.AAAA[:]), nil } -func unpackAAAAResource(hdr ResourceHeader, msg []byte, off int) (*AAAAResource, error) { +func unpackAAAAResource(msg []byte, off int) (AAAAResource, error) { var aaaa [16]byte if _, err := unpackBytes(msg, off, aaaa[:]); err != nil { - return nil, err + return AAAAResource{}, err } - return &AAAAResource{hdr, aaaa}, nil + return AAAAResource{aaaa}, nil } diff --git a/vendor/golang.org/x/net/dns/dnsmessage/message_test.go b/vendor/golang.org/x/net/dns/dnsmessage/message_test.go index 46edd7243..9295d36ce 100644 --- a/vendor/golang.org/x/net/dns/dnsmessage/message_test.go +++ b/vendor/golang.org/x/net/dns/dnsmessage/message_test.go @@ -5,13 +5,20 @@ package dnsmessage import ( + "bytes" "fmt" - "net" "reflect" - "strings" "testing" ) +func mustNewName(name string) Name { + n, err := NewName(name) + if err != nil { + panic(err) + } + return n +} + func (m *Message) String() string { s := fmt.Sprintf("Message: %#v\n", &m.Header) if len(m.Questions) > 0 { @@ -41,9 +48,17 @@ func (m *Message) String() string { return s } +func TestNameString(t *testing.T) { + want := "foo" + name := mustNewName(want) + if got := fmt.Sprint(name); got != want { + t.Errorf("got fmt.Sprint(%#v) = %s, want = %s", name, got, want) + } +} + func TestQuestionPackUnpack(t *testing.T) { want := Question{ - Name: ".", + Name: mustNewName("."), Type: TypeA, Class: ClassINET, } @@ -68,16 +83,42 @@ func TestQuestionPackUnpack(t *testing.T) { } } +func TestName(t *testing.T) { + tests := []string{ + "", + ".", + "google..com", + "google.com", + "google..com.", + "google.com.", + ".google.com.", + "www..google.com.", + "www.google.com.", + } + + for _, test := range tests { + n, err := NewName(test) + if err != nil { + t.Errorf("Creating name for %q: %v", test, err) + continue + } + if ns := n.String(); ns != test { + t.Errorf("Got %#v.String() = %q, want = %q", n, ns, test) + continue + } + } +} + func TestNamePackUnpack(t *testing.T) { tests := []struct { in string want string err error }{ - {"", ".", nil}, + {"", "", errNonCanonicalName}, {".", ".", nil}, - {"google..com", "", errZeroSegLen}, - {"google.com", "google.com.", nil}, + {"google..com", "", errNonCanonicalName}, + {"google.com", "", errNonCanonicalName}, {"google..com.", "", errZeroSegLen}, {"google.com.", "google.com.", nil}, {".google.com.", "", errZeroSegLen}, @@ -86,29 +127,91 @@ func TestNamePackUnpack(t *testing.T) { } for _, test := range tests { - buf, err := packName(make([]byte, 0, 30), test.in, map[string]int{}) + in := mustNewName(test.in) + want := mustNewName(test.want) + buf, err := in.pack(make([]byte, 0, 30), map[string]int{}) if err != test.err { - t.Errorf("Packing of %s: got err = %v, want err = %v", test.in, err, test.err) + t.Errorf("Packing of %q: got err = %v, want err = %v", test.in, err, test.err) continue } if test.err != nil { continue } - got, n, err := unpackName(buf, 0) + var got Name + n, err := got.unpack(buf, 0) if err != nil { - t.Errorf("Unpacking for %s failed: %v", test.in, err) + t.Errorf("Unpacking for %q failed: %v", test.in, err) continue } if n != len(buf) { t.Errorf( - "Unpacked different amount than packed for %s: got n = %d, want = %d", + "Unpacked different amount than packed for %q: got n = %d, want = %d", test.in, n, len(buf), ) } - if got != test.want { - t.Errorf("Unpacking packing of %s: got = %s, want = %s", test.in, got, test.want) + if got != want { + t.Errorf("Unpacking packing of %q: got = %#v, want = %#v", test.in, got, want) + } + } +} + +func checkErrorPrefix(err error, prefix string) bool { + e, ok := err.(*nestedError) + return ok && e.s == prefix +} + +func TestHeaderUnpackError(t *testing.T) { + wants := []string{ + "id", + "bits", + "questions", + "answers", + "authorities", + "additionals", + } + var buf []byte + var h header + for _, want := range wants { + n, err := h.unpack(buf, 0) + if n != 0 || !checkErrorPrefix(err, want) { + t.Errorf("got h.unpack([%d]byte, 0) = %d, %v, want = 0, %s", len(buf), n, err, want) + } + buf = append(buf, 0, 0) + } +} + +func TestParserStart(t *testing.T) { + const want = "unpacking header" + var p Parser + for i := 0; i <= 1; i++ { + _, err := p.Start([]byte{}) + if !checkErrorPrefix(err, want) { + t.Errorf("got p.Start(nil) = _, %v, want = _, %s", err, want) + } + } +} + +func TestResourceNotStarted(t *testing.T) { + tests := []struct { + name string + fn func(*Parser) error + }{ + {"CNAMEResource", func(p *Parser) error { _, err := p.CNAMEResource(); return err }}, + {"MXResource", func(p *Parser) error { _, err := p.MXResource(); return err }}, + {"NSResource", func(p *Parser) error { _, err := p.NSResource(); return err }}, + {"PTRResource", func(p *Parser) error { _, err := p.PTRResource(); return err }}, + {"SOAResource", func(p *Parser) error { _, err := p.SOAResource(); return err }}, + {"TXTResource", func(p *Parser) error { _, err := p.TXTResource(); return err }}, + {"SRVResource", func(p *Parser) error { _, err := p.SRVResource(); return err }}, + {"AResource", func(p *Parser) error { _, err := p.AResource(); return err }}, + {"AAAAResource", func(p *Parser) error { _, err := p.AAAAResource(); return err }}, + } + + for _, test := range tests { + if err := test.fn(&Parser{}); err != ErrNotStarted { + t.Errorf("got _, %v = p.%s(), want = _, %v", err, test.name, ErrNotStarted) } } } @@ -118,7 +221,7 @@ func TestDNSPackUnpack(t *testing.T) { { Questions: []Question{ { - Name: ".", + Name: mustNewName("."), Type: TypeAAAA, Class: ClassINET, }, @@ -174,6 +277,69 @@ func TestSkipAll(t *testing.T) { } } +func TestSkipEach(t *testing.T) { + msg := smallTestMsg() + + buf, err := msg.Pack() + if err != nil { + t.Fatal("Packing test message:", err) + } + var p Parser + if _, err := p.Start(buf); err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + f func() error + }{ + {"SkipQuestion", p.SkipQuestion}, + {"SkipAnswer", p.SkipAnswer}, + {"SkipAuthority", p.SkipAuthority}, + {"SkipAdditional", p.SkipAdditional}, + } + for _, test := range tests { + if err := test.f(); err != nil { + t.Errorf("First call: got %s() = %v, want = %v", test.name, err, nil) + } + if err := test.f(); err != ErrSectionDone { + t.Errorf("Second call: got %s() = %v, want = %v", test.name, err, ErrSectionDone) + } + } +} + +func TestSkipAfterRead(t *testing.T) { + msg := smallTestMsg() + + buf, err := msg.Pack() + if err != nil { + t.Fatal("Packing test message:", err) + } + var p Parser + if _, err := p.Start(buf); err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + skip func() error + read func() error + }{ + {"Question", p.SkipQuestion, func() error { _, err := p.Question(); return err }}, + {"Answer", p.SkipAnswer, func() error { _, err := p.Answer(); return err }}, + {"Authority", p.SkipAuthority, func() error { _, err := p.Authority(); return err }}, + {"Additional", p.SkipAdditional, func() error { _, err := p.Additional(); return err }}, + } + for _, test := range tests { + if err := test.read(); err != nil { + t.Errorf("Got %s() = _, %v, want = _, %v", test.name, err, nil) + } + if err := test.skip(); err != ErrSectionDone { + t.Errorf("Got Skip%s() = %v, want = %v", test.name, err, ErrSectionDone) + } + } +} + func TestSkipNotStarted(t *testing.T) { var p Parser @@ -238,206 +404,581 @@ func TestTooManyRecords(t *testing.T) { } func TestVeryLongTxt(t *testing.T) { - want := &TXTResource{ - ResourceHeader: ResourceHeader{ - Name: "foo.bar.example.com.", + want := Resource{ + ResourceHeader{ + Name: mustNewName("foo.bar.example.com."), Type: TypeTXT, Class: ClassINET, }, - Txt: loremIpsum, + &TXTResource{loremIpsum}, } - buf, err := packResource(make([]byte, 0, 8000), want, map[string]int{}) + buf, err := want.pack(make([]byte, 0, 8000), map[string]int{}) if err != nil { t.Fatal("Packing failed:", err) } - var hdr ResourceHeader - off, err := hdr.unpack(buf, 0) + var got Resource + off, err := got.Header.unpack(buf, 0) if err != nil { t.Fatal("Unpacking ResourceHeader failed:", err) } - got, n, err := unpackResource(buf, off, hdr) + body, n, err := unpackResourceBody(buf, off, got.Header) if err != nil { t.Fatal("Unpacking failed:", err) } + got.Body = body if n != len(buf) { t.Errorf("Unpacked different amount than packed: got n = %d, want = %d", n, len(buf)) } if !reflect.DeepEqual(got, want) { - t.Errorf("Got = %+v, want = %+v", got, want) + t.Errorf("Got = %#v, want = %#v", got, want) + } +} + +func TestStartError(t *testing.T) { + tests := []struct { + name string + fn func(*Builder) error + }{ + {"Questions", func(b *Builder) error { return b.StartQuestions() }}, + {"Answers", func(b *Builder) error { return b.StartAnswers() }}, + {"Authorities", func(b *Builder) error { return b.StartAuthorities() }}, + {"Additionals", func(b *Builder) error { return b.StartAdditionals() }}, + } + + envs := []struct { + name string + fn func() *Builder + want error + }{ + {"sectionNotStarted", func() *Builder { return &Builder{section: sectionNotStarted} }, ErrNotStarted}, + {"sectionDone", func() *Builder { return &Builder{section: sectionDone} }, ErrSectionDone}, + } + + for _, env := range envs { + for _, test := range tests { + if got := test.fn(env.fn()); got != env.want { + t.Errorf("got Builder{%s}.Start%s = %v, want = %v", env.name, test.name, got, env.want) + } + } + } +} + +func TestBuilderResourceError(t *testing.T) { + tests := []struct { + name string + fn func(*Builder) error + }{ + {"CNAMEResource", func(b *Builder) error { return b.CNAMEResource(ResourceHeader{}, CNAMEResource{}) }}, + {"MXResource", func(b *Builder) error { return b.MXResource(ResourceHeader{}, MXResource{}) }}, + {"NSResource", func(b *Builder) error { return b.NSResource(ResourceHeader{}, NSResource{}) }}, + {"PTRResource", func(b *Builder) error { return b.PTRResource(ResourceHeader{}, PTRResource{}) }}, + {"SOAResource", func(b *Builder) error { return b.SOAResource(ResourceHeader{}, SOAResource{}) }}, + {"TXTResource", func(b *Builder) error { return b.TXTResource(ResourceHeader{}, TXTResource{}) }}, + {"SRVResource", func(b *Builder) error { return b.SRVResource(ResourceHeader{}, SRVResource{}) }}, + {"AResource", func(b *Builder) error { return b.AResource(ResourceHeader{}, AResource{}) }}, + {"AAAAResource", func(b *Builder) error { return b.AAAAResource(ResourceHeader{}, AAAAResource{}) }}, + } + + envs := []struct { + name string + fn func() *Builder + want error + }{ + {"sectionNotStarted", func() *Builder { return &Builder{section: sectionNotStarted} }, ErrNotStarted}, + {"sectionHeader", func() *Builder { return &Builder{section: sectionHeader} }, ErrNotStarted}, + {"sectionQuestions", func() *Builder { return &Builder{section: sectionQuestions} }, ErrNotStarted}, + {"sectionDone", func() *Builder { return &Builder{section: sectionDone} }, ErrSectionDone}, + } + + for _, env := range envs { + for _, test := range tests { + if got := test.fn(env.fn()); got != env.want { + t.Errorf("got Builder{%s}.%s = %v, want = %v", env.name, test.name, got, env.want) + } + } + } +} + +func TestFinishError(t *testing.T) { + var b Builder + want := ErrNotStarted + if _, got := b.Finish(); got != want { + t.Errorf("got Builder{}.Finish() = %v, want = %v", got, want) + } +} + +func TestBuilder(t *testing.T) { + msg := largeTestMsg() + want, err := msg.Pack() + if err != nil { + t.Fatal("Packing without builder:", err) + } + + var b Builder + b.Start(nil, msg.Header) + + if err := b.StartQuestions(); err != nil { + t.Fatal("b.StartQuestions():", err) + } + for _, q := range msg.Questions { + if err := b.Question(q); err != nil { + t.Fatalf("b.Question(%#v): %v", q, err) + } + } + + if err := b.StartAnswers(); err != nil { + t.Fatal("b.StartAnswers():", err) + } + for _, a := range msg.Answers { + switch a.Header.Type { + case TypeA: + if err := b.AResource(a.Header, *a.Body.(*AResource)); err != nil { + t.Fatalf("b.AResource(%#v): %v", a, err) + } + case TypeNS: + if err := b.NSResource(a.Header, *a.Body.(*NSResource)); err != nil { + t.Fatalf("b.NSResource(%#v): %v", a, err) + } + case TypeCNAME: + if err := b.CNAMEResource(a.Header, *a.Body.(*CNAMEResource)); err != nil { + t.Fatalf("b.CNAMEResource(%#v): %v", a, err) + } + case TypeSOA: + if err := b.SOAResource(a.Header, *a.Body.(*SOAResource)); err != nil { + t.Fatalf("b.SOAResource(%#v): %v", a, err) + } + case TypePTR: + if err := b.PTRResource(a.Header, *a.Body.(*PTRResource)); err != nil { + t.Fatalf("b.PTRResource(%#v): %v", a, err) + } + case TypeMX: + if err := b.MXResource(a.Header, *a.Body.(*MXResource)); err != nil { + t.Fatalf("b.MXResource(%#v): %v", a, err) + } + case TypeTXT: + if err := b.TXTResource(a.Header, *a.Body.(*TXTResource)); err != nil { + t.Fatalf("b.TXTResource(%#v): %v", a, err) + } + case TypeAAAA: + if err := b.AAAAResource(a.Header, *a.Body.(*AAAAResource)); err != nil { + t.Fatalf("b.AAAAResource(%#v): %v", a, err) + } + case TypeSRV: + if err := b.SRVResource(a.Header, *a.Body.(*SRVResource)); err != nil { + t.Fatalf("b.SRVResource(%#v): %v", a, err) + } + } + } + + if err := b.StartAuthorities(); err != nil { + t.Fatal("b.StartAuthorities():", err) + } + for _, a := range msg.Authorities { + if err := b.NSResource(a.Header, *a.Body.(*NSResource)); err != nil { + t.Fatalf("b.NSResource(%#v): %v", a, err) + } + } + + if err := b.StartAdditionals(); err != nil { + t.Fatal("b.StartAdditionals():", err) + } + for _, a := range msg.Additionals { + if err := b.TXTResource(a.Header, *a.Body.(*TXTResource)); err != nil { + t.Fatalf("b.TXTResource(%#v): %v", a, err) + } + } + + got, err := b.Finish() + if err != nil { + t.Fatal("b.Finish():", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("Got from Builder: %#v\nwant = %#v", got, want) + } +} + +func TestResourcePack(t *testing.T) { + for _, tt := range []struct { + m Message + err error + }{ + { + Message{ + Questions: []Question{ + { + Name: mustNewName("."), + Type: TypeAAAA, + Class: ClassINET, + }, + }, + Answers: []Resource{{ResourceHeader{}, nil}}, + }, + &nestedError{"packing Answer", errNilResouceBody}, + }, + { + Message{ + Questions: []Question{ + { + Name: mustNewName("."), + Type: TypeAAAA, + Class: ClassINET, + }, + }, + Authorities: []Resource{{ResourceHeader{}, (*NSResource)(nil)}}, + }, + &nestedError{"packing Authority", + &nestedError{"ResourceHeader", + &nestedError{"Name", errNonCanonicalName}, + }, + }, + }, + { + Message{ + Questions: []Question{ + { + Name: mustNewName("."), + Type: TypeA, + Class: ClassINET, + }, + }, + Additionals: []Resource{{ResourceHeader{}, nil}}, + }, + &nestedError{"packing Additional", errNilResouceBody}, + }, + } { + _, err := tt.m.Pack() + if !reflect.DeepEqual(err, tt.err) { + t.Errorf("got %v for %v; want %v", err, tt.m, tt.err) + } } } -func ExampleHeaderSearch() { +func BenchmarkParsing(b *testing.B) { + b.ReportAllocs() + + name := mustNewName("foo.bar.example.com.") msg := Message{ Header: Header{Response: true, Authoritative: true}, Questions: []Question{ { - Name: "foo.bar.example.com.", - Type: TypeA, - Class: ClassINET, - }, - { - Name: "bar.example.com.", + Name: name, Type: TypeA, Class: ClassINET, }, }, Answers: []Resource{ - &AResource{ - ResourceHeader: ResourceHeader{ - Name: "foo.bar.example.com.", - Type: TypeA, + { + ResourceHeader{ + Name: name, Class: ClassINET, }, - A: [4]byte{127, 0, 0, 1}, + &AResource{[4]byte{}}, }, - &AResource{ - ResourceHeader: ResourceHeader{ - Name: "bar.example.com.", - Type: TypeA, + { + ResourceHeader{ + Name: name, Class: ClassINET, }, - A: [4]byte{127, 0, 0, 2}, + &AAAAResource{[16]byte{}}, + }, + { + ResourceHeader{ + Name: name, + Class: ClassINET, + }, + &CNAMEResource{name}, + }, + { + ResourceHeader{ + Name: name, + Class: ClassINET, + }, + &NSResource{name}, }, }, } buf, err := msg.Pack() if err != nil { - panic(err) + b.Fatal("msg.Pack():", err) } - wantName := "bar.example.com." + for i := 0; i < b.N; i++ { + var p Parser + if _, err := p.Start(buf); err != nil { + b.Fatal("p.Start(buf):", err) + } - var p Parser - if _, err := p.Start(buf); err != nil { - panic(err) + for { + _, err := p.Question() + if err == ErrSectionDone { + break + } + if err != nil { + b.Fatal("p.Question():", err) + } + } + + for { + h, err := p.AnswerHeader() + if err == ErrSectionDone { + break + } + if err != nil { + panic(err) + } + + switch h.Type { + case TypeA: + if _, err := p.AResource(); err != nil { + b.Fatal("p.AResource():", err) + } + case TypeAAAA: + if _, err := p.AAAAResource(); err != nil { + b.Fatal("p.AAAAResource():", err) + } + case TypeCNAME: + if _, err := p.CNAMEResource(); err != nil { + b.Fatal("p.CNAMEResource():", err) + } + case TypeNS: + if _, err := p.NSResource(); err != nil { + b.Fatal("p.NSResource():", err) + } + default: + b.Fatalf("unknown type: %T", h) + } + } } +} + +func BenchmarkBuilding(b *testing.B) { + b.ReportAllocs() + + name := mustNewName("foo.bar.example.com.") + buf := make([]byte, 0, packStartingCap) + + for i := 0; i < b.N; i++ { + var bld Builder + bld.StartWithoutCompression(buf, Header{Response: true, Authoritative: true}) - for { - q, err := p.Question() - if err == ErrSectionDone { - break + if err := bld.StartQuestions(); err != nil { + b.Fatal("bld.StartQuestions():", err) } - if err != nil { - panic(err) + q := Question{ + Name: name, + Type: TypeA, + Class: ClassINET, } - - if q.Name != wantName { - continue + if err := bld.Question(q); err != nil { + b.Fatalf("bld.Question(%+v): %v", q, err) } - fmt.Println("Found question for name", wantName) - if err := p.SkipAllQuestions(); err != nil { - panic(err) + hdr := ResourceHeader{ + Name: name, + Class: ClassINET, } - break - } - - var gotIPs []net.IP - for { - h, err := p.AnswerHeader() - if err == ErrSectionDone { - break + if err := bld.StartAnswers(); err != nil { + b.Fatal("bld.StartQuestions():", err) } - if err != nil { - panic(err) + + ar := AResource{[4]byte{}} + if err := bld.AResource(hdr, ar); err != nil { + b.Fatalf("bld.AResource(%+v, %+v): %v", hdr, ar, err) } - if (h.Type != TypeA && h.Type != TypeAAAA) || h.Class != ClassINET { - continue + aaar := AAAAResource{[16]byte{}} + if err := bld.AAAAResource(hdr, aaar); err != nil { + b.Fatalf("bld.AAAAResource(%+v, %+v): %v", hdr, aaar, err) } - if !strings.EqualFold(h.Name, wantName) { - if err := p.SkipAnswer(); err != nil { - panic(err) - } - continue + cnr := CNAMEResource{name} + if err := bld.CNAMEResource(hdr, cnr); err != nil { + b.Fatalf("bld.CNAMEResource(%+v, %+v): %v", hdr, cnr, err) } - a, err := p.Answer() - if err != nil { - panic(err) + + nsr := NSResource{name} + if err := bld.NSResource(hdr, nsr); err != nil { + b.Fatalf("bld.NSResource(%+v, %+v): %v", hdr, nsr, err) } - switch r := a.(type) { - default: - panic(fmt.Sprintf("unknown type: %T", r)) - case *AResource: - gotIPs = append(gotIPs, r.A[:]) - case *AAAAResource: - gotIPs = append(gotIPs, r.AAAA[:]) + if _, err := bld.Finish(); err != nil { + b.Fatal("bld.Finish():", err) } } +} - fmt.Printf("Found A/AAAA records for name %s: %v\n", wantName, gotIPs) - - // Output: - // Found question for name bar.example.com. - // Found A/AAAA records for name bar.example.com.: [127.0.0.2] +func smallTestMsg() Message { + name := mustNewName("example.com.") + return Message{ + Header: Header{Response: true, Authoritative: true}, + Questions: []Question{ + { + Name: name, + Type: TypeA, + Class: ClassINET, + }, + }, + Answers: []Resource{ + { + ResourceHeader{ + Name: name, + Type: TypeA, + Class: ClassINET, + }, + &AResource{[4]byte{127, 0, 0, 1}}, + }, + }, + Authorities: []Resource{ + { + ResourceHeader{ + Name: name, + Type: TypeA, + Class: ClassINET, + }, + &AResource{[4]byte{127, 0, 0, 1}}, + }, + }, + Additionals: []Resource{ + { + ResourceHeader{ + Name: name, + Type: TypeA, + Class: ClassINET, + }, + &AResource{[4]byte{127, 0, 0, 1}}, + }, + }, + } } func largeTestMsg() Message { + name := mustNewName("foo.bar.example.com.") return Message{ Header: Header{Response: true, Authoritative: true}, Questions: []Question{ { - Name: "foo.bar.example.com.", + Name: name, Type: TypeA, Class: ClassINET, }, }, Answers: []Resource{ - &AResource{ - ResourceHeader: ResourceHeader{ - Name: "foo.bar.example.com.", + { + ResourceHeader{ + Name: name, Type: TypeA, Class: ClassINET, }, - A: [4]byte{127, 0, 0, 1}, + &AResource{[4]byte{127, 0, 0, 1}}, }, - &AResource{ - ResourceHeader: ResourceHeader{ - Name: "foo.bar.example.com.", + { + ResourceHeader{ + Name: name, Type: TypeA, Class: ClassINET, }, - A: [4]byte{127, 0, 0, 2}, + &AResource{[4]byte{127, 0, 0, 2}}, + }, + { + ResourceHeader{ + Name: name, + Type: TypeAAAA, + Class: ClassINET, + }, + &AAAAResource{[16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}}, + }, + { + ResourceHeader{ + Name: name, + Type: TypeCNAME, + Class: ClassINET, + }, + &CNAMEResource{mustNewName("alias.example.com.")}, + }, + { + ResourceHeader{ + Name: name, + Type: TypeSOA, + Class: ClassINET, + }, + &SOAResource{ + NS: mustNewName("ns1.example.com."), + MBox: mustNewName("mb.example.com."), + Serial: 1, + Refresh: 2, + Retry: 3, + Expire: 4, + MinTTL: 5, + }, + }, + { + ResourceHeader{ + Name: name, + Type: TypePTR, + Class: ClassINET, + }, + &PTRResource{mustNewName("ptr.example.com.")}, + }, + { + ResourceHeader{ + Name: name, + Type: TypeMX, + Class: ClassINET, + }, + &MXResource{ + 7, + mustNewName("mx.example.com."), + }, + }, + { + ResourceHeader{ + Name: name, + Type: TypeSRV, + Class: ClassINET, + }, + &SRVResource{ + 8, + 9, + 11, + mustNewName("srv.example.com."), + }, }, }, Authorities: []Resource{ - &NSResource{ - ResourceHeader: ResourceHeader{ - Name: "foo.bar.example.com.", + { + ResourceHeader{ + Name: name, Type: TypeNS, Class: ClassINET, }, - NS: "ns1.example.com.", + &NSResource{mustNewName("ns1.example.com.")}, }, - &NSResource{ - ResourceHeader: ResourceHeader{ - Name: "foo.bar.example.com.", + { + ResourceHeader{ + Name: name, Type: TypeNS, Class: ClassINET, }, - NS: "ns2.example.com.", + &NSResource{mustNewName("ns2.example.com.")}, }, }, Additionals: []Resource{ - &TXTResource{ - ResourceHeader: ResourceHeader{ - Name: "foo.bar.example.com.", + { + ResourceHeader{ + Name: name, Type: TypeTXT, Class: ClassINET, }, - Txt: "So Long, and Thanks for All the Fish", + &TXTResource{"So Long, and Thanks for All the Fish"}, }, - &TXTResource{ - ResourceHeader: ResourceHeader{ - Name: "foo.bar.example.com.", + { + ResourceHeader{ + Name: name, Type: TypeTXT, Class: ClassINET, }, - Txt: "Hamster Huey and the Gooey Kablooie", + &TXTResource{"Hamster Huey and the Gooey Kablooie"}, }, }, } diff --git a/vendor/golang.org/x/net/http2/ciphers_test.go b/vendor/golang.org/x/net/http2/ciphers_test.go index 25aead013..764bbc8c8 100644 --- a/vendor/golang.org/x/net/http2/ciphers_test.go +++ b/vendor/golang.org/x/net/http2/ciphers_test.go @@ -9,7 +9,7 @@ import "testing" func TestIsBadCipherBad(t *testing.T) { for _, c := range badCiphers { if !isBadCipher(c) { - t.Errorf("Wrong result for isBadCipher(%d), want true") + t.Errorf("Wrong result for isBadCipher(%d), want true", c) } } } diff --git a/vendor/golang.org/x/net/http2/server_test.go b/vendor/golang.org/x/net/http2/server_test.go index 437d1c378..b4e832894 100644 --- a/vendor/golang.org/x/net/http2/server_test.go +++ b/vendor/golang.org/x/net/http2/server_test.go @@ -286,7 +286,7 @@ func (st *serverTester) greetAndCheckSettings(checkSetting func(s Setting) error case *WindowUpdateFrame: if f.FrameHeader.StreamID != 0 { - st.t.Fatalf("WindowUpdate StreamID = %d; want 0", f.FrameHeader.StreamID, 0) + st.t.Fatalf("WindowUpdate StreamID = %d; want 0", f.FrameHeader.StreamID) } incr := uint32((&Server{}).initialConnRecvWindowSize() - initialWindowSize) if f.Increment != incr { diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index 24d0af84c..850d7ae09 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -1713,16 +1713,27 @@ func (rl *clientConnReadLoop) processData(f *DataFrame) error { } // Return any padded flow control now, since we won't // refund it later on body reads. - if pad := int32(f.Length) - int32(len(data)); pad > 0 { - cs.inflow.add(pad) - cc.inflow.add(pad) + var refund int + if pad := int(f.Length) - len(data); pad > 0 { + refund += pad + } + // Return len(data) now if the stream is already closed, + // since data will never be read. + didReset := cs.didReset + if didReset { + refund += len(data) + } + if refund > 0 { + cc.inflow.add(int32(refund)) cc.wmu.Lock() - cc.fr.WriteWindowUpdate(0, uint32(pad)) - cc.fr.WriteWindowUpdate(cs.ID, uint32(pad)) + cc.fr.WriteWindowUpdate(0, uint32(refund)) + if !didReset { + cs.inflow.add(int32(refund)) + cc.fr.WriteWindowUpdate(cs.ID, uint32(refund)) + } cc.bw.Flush() cc.wmu.Unlock() } - didReset := cs.didReset cc.mu.Unlock() if len(data) > 0 && !didReset { diff --git a/vendor/golang.org/x/net/http2/transport_test.go b/vendor/golang.org/x/net/http2/transport_test.go index bf34fc9dd..15dfa0739 100644 --- a/vendor/golang.org/x/net/http2/transport_test.go +++ b/vendor/golang.org/x/net/http2/transport_test.go @@ -2210,12 +2210,11 @@ func testTransportUsesGoAwayDebugError(t *testing.T, failMidBody bool) { ct.run() } -// See golang.org/issue/16481 -func TestTransportReturnsUnusedFlowControl(t *testing.T) { +func testTransportReturnsUnusedFlowControl(t *testing.T, oneDataFrame bool) { ct := newClientTester(t) - clientClosed := make(chan bool, 1) - serverWroteBody := make(chan bool, 1) + clientClosed := make(chan struct{}) + serverWroteFirstByte := make(chan struct{}) ct.client = func() error { req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) @@ -2223,13 +2222,13 @@ func TestTransportReturnsUnusedFlowControl(t *testing.T) { if err != nil { return err } - <-serverWroteBody + <-serverWroteFirstByte if n, err := res.Body.Read(make([]byte, 1)); err != nil || n != 1 { return fmt.Errorf("body read = %v, %v; want 1, nil", n, err) } res.Body.Close() // leaving 4999 bytes unread - clientClosed <- true + close(clientClosed) return nil } @@ -2264,10 +2263,27 @@ func TestTransportReturnsUnusedFlowControl(t *testing.T) { EndStream: false, BlockFragment: buf.Bytes(), }) - ct.fr.WriteData(hf.StreamID, false, make([]byte, 5000)) // without ending stream - serverWroteBody <- true - <-clientClosed + // Two cases: + // - Send one DATA frame with 5000 bytes. + // - Send two DATA frames with 1 and 4999 bytes each. + // + // In both cases, the client should consume one byte of data, + // refund that byte, then refund the following 4999 bytes. + // + // In the second case, the server waits for the client connection to + // close before seconding the second DATA frame. This tests the case + // where the client receives a DATA frame after it has reset the stream. + if oneDataFrame { + ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 5000)) + close(serverWroteFirstByte) + <-clientClosed + } else { + ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 1)) + close(serverWroteFirstByte) + <-clientClosed + ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 4999)) + } waitingFor := "RSTStreamFrame" for { @@ -2281,7 +2297,7 @@ func TestTransportReturnsUnusedFlowControl(t *testing.T) { switch waitingFor { case "RSTStreamFrame": if rf, ok := f.(*RSTStreamFrame); !ok || rf.ErrCode != ErrCodeCancel { - return fmt.Errorf("Expected a WindowUpdateFrame with code cancel; got %v", summarizeFrame(f)) + return fmt.Errorf("Expected a RSTStreamFrame with code cancel; got %v", summarizeFrame(f)) } waitingFor = "WindowUpdateFrame" case "WindowUpdateFrame": @@ -2295,6 +2311,16 @@ func TestTransportReturnsUnusedFlowControl(t *testing.T) { ct.run() } +// See golang.org/issue/16481 +func TestTransportReturnsUnusedFlowControlSingleWrite(t *testing.T) { + testTransportReturnsUnusedFlowControl(t, true) +} + +// See golang.org/issue/20469 +func TestTransportReturnsUnusedFlowControlMultipleWrites(t *testing.T) { + testTransportReturnsUnusedFlowControl(t, false) +} + // Issue 16612: adjust flow control on open streams when transport // receives SETTINGS with INITIAL_WINDOW_SIZE from server. func TestTransportAdjustsFlowControl(t *testing.T) { diff --git a/vendor/golang.org/x/net/icmp/helper.go b/vendor/golang.org/x/net/icmp/helper.go deleted file mode 100644 index 6c4e633bc..000000000 --- a/vendor/golang.org/x/net/icmp/helper.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package icmp - -import ( - "encoding/binary" - "unsafe" -) - -var ( - // See http://www.freebsd.org/doc/en/books/porters-handbook/freebsd-versions.html. - freebsdVersion uint32 - - nativeEndian binary.ByteOrder -) - -func init() { - i := uint32(1) - b := (*[4]byte)(unsafe.Pointer(&i)) - if b[0] == 1 { - nativeEndian = binary.LittleEndian - } else { - nativeEndian = binary.BigEndian - } -} diff --git a/vendor/golang.org/x/net/icmp/ipv4.go b/vendor/golang.org/x/net/icmp/ipv4.go index 729ddc97c..ffc66ed4d 100644 --- a/vendor/golang.org/x/net/icmp/ipv4.go +++ b/vendor/golang.org/x/net/icmp/ipv4.go @@ -9,9 +9,14 @@ import ( "net" "runtime" + "golang.org/x/net/internal/socket" "golang.org/x/net/ipv4" ) +// freebsdVersion is set in sys_freebsd.go. +// See http://www.freebsd.org/doc/en/books/porters-handbook/freebsd-versions.html. +var freebsdVersion uint32 + // ParseIPv4Header parses b as an IPv4 header of ICMP error message // invoking packet, which is contained in ICMP error message. func ParseIPv4Header(b []byte) (*ipv4.Header, error) { @@ -36,12 +41,12 @@ func ParseIPv4Header(b []byte) (*ipv4.Header, error) { } switch runtime.GOOS { case "darwin": - h.TotalLen = int(nativeEndian.Uint16(b[2:4])) + h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4])) case "freebsd": if freebsdVersion >= 1000000 { h.TotalLen = int(binary.BigEndian.Uint16(b[2:4])) } else { - h.TotalLen = int(nativeEndian.Uint16(b[2:4])) + h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4])) } default: h.TotalLen = int(binary.BigEndian.Uint16(b[2:4])) diff --git a/vendor/golang.org/x/net/icmp/ipv4_test.go b/vendor/golang.org/x/net/icmp/ipv4_test.go index 47cc00d07..058953f43 100644 --- a/vendor/golang.org/x/net/icmp/ipv4_test.go +++ b/vendor/golang.org/x/net/icmp/ipv4_test.go @@ -11,6 +11,7 @@ import ( "runtime" "testing" + "golang.org/x/net/internal/socket" "golang.org/x/net/ipv4" ) @@ -55,7 +56,7 @@ var ipv4HeaderLittleEndianTest = ipv4HeaderTest{ func TestParseIPv4Header(t *testing.T) { tt := &ipv4HeaderLittleEndianTest - if nativeEndian != binary.LittleEndian { + if socket.NativeEndian != binary.LittleEndian { t.Skip("no test for non-little endian machine yet") } diff --git a/vendor/golang.org/x/net/idna/example_test.go b/vendor/golang.org/x/net/idna/example_test.go index 941e707d8..948f6eb20 100644 --- a/vendor/golang.org/x/net/idna/example_test.go +++ b/vendor/golang.org/x/net/idna/example_test.go @@ -51,6 +51,10 @@ func ExampleNew() { idna.Transitional(true)) // Map ß -> ss fmt.Println(p.ToASCII("*.faß.com")) + // Lookup for registration. Also does not allow '*'. + p = idna.New(idna.ValidateForRegistration()) + fmt.Println(p.ToUnicode("*.faß.com")) + // Set up a profile maps for lookup, but allows wild cards. p = idna.New( idna.MapForLookup(), @@ -60,6 +64,7 @@ func ExampleNew() { // Output: // *.xn--fa-hia.com <nil> - // *.fass.com idna: disallowed rune U+002E + // *.fass.com idna: disallowed rune U+002A + // *.faß.com idna: disallowed rune U+002A // *.fass.com <nil> } diff --git a/vendor/golang.org/x/net/idna/idna.go b/vendor/golang.org/x/net/idna/idna.go index ee2dbda6d..eb2473507 100644 --- a/vendor/golang.org/x/net/idna/idna.go +++ b/vendor/golang.org/x/net/idna/idna.go @@ -67,6 +67,15 @@ func VerifyDNSLength(verify bool) Option { return func(o *options) { o.verifyDNSLength = verify } } +// RemoveLeadingDots removes leading label separators. Leading runes that map to +// dots, such as U+3002, are removed as well. +// +// This is the behavior suggested by the UTS #46 and is adopted by some +// browsers. +func RemoveLeadingDots(remove bool) Option { + return func(o *options) { o.removeLeadingDots = remove } +} + // ValidateLabels sets whether to check the mandatory label validation criteria // as defined in Section 5.4 of RFC 5891. This includes testing for correct use // of hyphens ('-'), normalization, validity of runes, and the context rules. @@ -133,14 +142,16 @@ func MapForLookup() Option { o.mapping = validateAndMap StrictDomainName(true)(o) ValidateLabels(true)(o) + RemoveLeadingDots(true)(o) } } type options struct { - transitional bool - useSTD3Rules bool - validateLabels bool - verifyDNSLength bool + transitional bool + useSTD3Rules bool + validateLabels bool + verifyDNSLength bool + removeLeadingDots bool trie *idnaTrie @@ -240,21 +251,23 @@ var ( punycode = &Profile{} lookup = &Profile{options{ - transitional: true, - useSTD3Rules: true, - validateLabels: true, - trie: trie, - fromPuny: validateFromPunycode, - mapping: validateAndMap, - bidirule: bidirule.ValidString, + transitional: true, + useSTD3Rules: true, + validateLabels: true, + removeLeadingDots: true, + trie: trie, + fromPuny: validateFromPunycode, + mapping: validateAndMap, + bidirule: bidirule.ValidString, }} display = &Profile{options{ - useSTD3Rules: true, - validateLabels: true, - trie: trie, - fromPuny: validateFromPunycode, - mapping: validateAndMap, - bidirule: bidirule.ValidString, + useSTD3Rules: true, + validateLabels: true, + removeLeadingDots: true, + trie: trie, + fromPuny: validateFromPunycode, + mapping: validateAndMap, + bidirule: bidirule.ValidString, }} registration = &Profile{options{ useSTD3Rules: true, @@ -293,7 +306,9 @@ func (p *Profile) process(s string, toASCII bool) (string, error) { s, err = p.mapping(p, s) } // Remove leading empty labels. - for ; len(s) > 0 && s[0] == '.'; s = s[1:] { + if p.removeLeadingDots { + for ; len(s) > 0 && s[0] == '.'; s = s[1:] { + } } // It seems like we should only create this error on ToASCII, but the // UTS 46 conformance tests suggests we should always check this. @@ -373,23 +388,20 @@ func validateRegistration(p *Profile, s string) (string, error) { if !norm.NFC.IsNormalString(s) { return s, &labelError{s, "V1"} } - var err error for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) - i += sz // Copy bytes not copied so far. switch p.simplify(info(v).category()) { // TODO: handle the NV8 defined in the Unicode idna data set to allow // for strict conformance to IDNA2008. case valid, deviation: case disallowed, mapped, unknown, ignored: - if err == nil { - r, _ := utf8.DecodeRuneInString(s[i:]) - err = runeError(r) - } + r, _ := utf8.DecodeRuneInString(s[i:]) + return s, runeError(r) } + i += sz } - return s, err + return s, nil } func validateAndMap(p *Profile, s string) (string, error) { @@ -408,7 +420,7 @@ func validateAndMap(p *Profile, s string) (string, error) { continue case disallowed: if err == nil { - r, _ := utf8.DecodeRuneInString(s[i:]) + r, _ := utf8.DecodeRuneInString(s[start:]) err = runeError(r) } continue diff --git a/vendor/golang.org/x/net/ipv4/helper.go b/vendor/golang.org/x/net/ipv4/helper.go index 5f747a443..a5052e324 100644 --- a/vendor/golang.org/x/net/ipv4/helper.go +++ b/vendor/golang.org/x/net/ipv4/helper.go @@ -43,3 +43,21 @@ func netAddrToIP4(a net.Addr) net.IP { } return nil } + +func opAddr(a net.Addr) net.Addr { + switch a.(type) { + case *net.TCPAddr: + if a == nil { + return nil + } + case *net.UDPAddr: + if a == nil { + return nil + } + case *net.IPAddr: + if a == nil { + return nil + } + } + return a +} diff --git a/vendor/golang.org/x/net/ipv4/icmp.go b/vendor/golang.org/x/net/ipv4/icmp.go index 097bea846..9902bb3d2 100644 --- a/vendor/golang.org/x/net/ipv4/icmp.go +++ b/vendor/golang.org/x/net/ipv4/icmp.go @@ -26,7 +26,7 @@ func (typ ICMPType) Protocol() int { // packets. The filter belongs to a packet delivery path on a host and // it cannot interact with forwarding packets or tunnel-outer packets. // -// Note: RFC 2460 defines a reasonable role model and it works not +// Note: RFC 8200 defines a reasonable role model and it works not // only for IPv6 but IPv4. A node means a device that implements IP. // A router means a node that forwards IP packets not explicitly // addressed to itself, and a host means a node that is not a router. diff --git a/vendor/golang.org/x/net/ipv4/packet_go1_9.go b/vendor/golang.org/x/net/ipv4/packet_go1_9.go index 285fdb0ed..082c36d73 100644 --- a/vendor/golang.org/x/net/ipv4/packet_go1_9.go +++ b/vendor/golang.org/x/net/ipv4/packet_go1_9.go @@ -61,7 +61,7 @@ func (c *packetHandler) writeTo(h *Header, p []byte, cm *ControlMessage) error { } m.Addr = dst if err := c.SendMsg(&m, 0); err != nil { - return &net.OpError{Op: "write", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Err: err} + return &net.OpError{Op: "write", Net: c.IPConn.LocalAddr().Network(), Source: c.IPConn.LocalAddr(), Addr: opAddr(dst), Err: err} } return nil } diff --git a/vendor/golang.org/x/net/ipv4/payload_cmsg_go1_8.go b/vendor/golang.org/x/net/ipv4/payload_cmsg_go1_8.go index 0a9c33a18..d26ccd90c 100644 --- a/vendor/golang.org/x/net/ipv4/payload_cmsg_go1_8.go +++ b/vendor/golang.org/x/net/ipv4/payload_cmsg_go1_8.go @@ -53,7 +53,7 @@ func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (n case *net.IPConn: n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr)) default: - return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Err: errInvalidConnType} + return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Addr: opAddr(dst), Err: errInvalidConnType} } return } diff --git a/vendor/golang.org/x/net/ipv4/payload_cmsg_go1_9.go b/vendor/golang.org/x/net/ipv4/payload_cmsg_go1_9.go index e697f35f4..2f1931183 100644 --- a/vendor/golang.org/x/net/ipv4/payload_cmsg_go1_9.go +++ b/vendor/golang.org/x/net/ipv4/payload_cmsg_go1_9.go @@ -61,7 +61,7 @@ func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (in } err := c.SendMsg(&m, 0) if err != nil { - err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} + err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Addr: opAddr(dst), Err: err} } return m.N, err } diff --git a/vendor/golang.org/x/net/ipv4/readwrite_test.go b/vendor/golang.org/x/net/ipv4/readwrite_test.go index a2384b8f9..3896a8ae4 100644 --- a/vendor/golang.org/x/net/ipv4/readwrite_test.go +++ b/vendor/golang.org/x/net/ipv4/readwrite_test.go @@ -16,77 +16,47 @@ import ( "golang.org/x/net/ipv4" ) -func benchmarkUDPListener() (net.PacketConn, net.Addr, error) { - c, err := net.ListenPacket("udp4", "127.0.0.1:0") +func BenchmarkReadWriteUnicast(b *testing.B) { + c, err := nettest.NewLocalPacketListener("udp4") if err != nil { - return nil, nil, err - } - dst, err := net.ResolveUDPAddr("udp4", c.LocalAddr().String()) - if err != nil { - c.Close() - return nil, nil, err - } - return c, dst, nil -} - -func BenchmarkReadWriteNetUDP(b *testing.B) { - c, dst, err := benchmarkUDPListener() - if err != nil { - b.Fatal(err) + b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() + dst := c.LocalAddr() wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) - b.ResetTimer() - for i := 0; i < b.N; i++ { - benchmarkReadWriteNetUDP(b, c, wb, rb, dst) - } -} - -func benchmarkReadWriteNetUDP(b *testing.B, c net.PacketConn, wb, rb []byte, dst net.Addr) { - if _, err := c.WriteTo(wb, dst); err != nil { - b.Fatal(err) - } - if _, _, err := c.ReadFrom(rb); err != nil { - b.Fatal(err) - } -} - -func BenchmarkReadWriteIPv4UDP(b *testing.B) { - c, dst, err := benchmarkUDPListener() - if err != nil { - b.Fatal(err) - } - defer c.Close() - - p := ipv4.NewPacketConn(c) - defer p.Close() - cf := ipv4.FlagTTL | ipv4.FlagInterface - if err := p.SetControlMessage(cf, true); err != nil { - b.Fatal(err) - } - ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) - wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) - b.ResetTimer() - for i := 0; i < b.N; i++ { - benchmarkReadWriteIPv4UDP(b, p, wb, rb, dst, ifi) - } -} + b.Run("NetUDP", func(b *testing.B) { + for i := 0; i < b.N; i++ { + if _, err := c.WriteTo(wb, dst); err != nil { + b.Fatal(err) + } + if _, _, err := c.ReadFrom(rb); err != nil { + b.Fatal(err) + } + } + }) + b.Run("IPv4UDP", func(b *testing.B) { + p := ipv4.NewPacketConn(c) + cf := ipv4.FlagTTL | ipv4.FlagInterface + if err := p.SetControlMessage(cf, true); err != nil { + b.Fatal(err) + } + cm := ipv4.ControlMessage{TTL: 1} + ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) + if ifi != nil { + cm.IfIndex = ifi.Index + } -func benchmarkReadWriteIPv4UDP(b *testing.B, p *ipv4.PacketConn, wb, rb []byte, dst net.Addr, ifi *net.Interface) { - cm := ipv4.ControlMessage{TTL: 1} - if ifi != nil { - cm.IfIndex = ifi.Index - } - if n, err := p.WriteTo(wb, &cm, dst); err != nil { - b.Fatal(err) - } else if n != len(wb) { - b.Fatalf("got %v; want %v", n, len(wb)) - } - if _, _, _, err := p.ReadFrom(rb); err != nil { - b.Fatal(err) - } + for i := 0; i < b.N; i++ { + if _, err := p.WriteTo(wb, &cm, dst); err != nil { + b.Fatal(err) + } + if _, _, _, err := p.ReadFrom(rb); err != nil { + b.Fatal(err) + } + } + }) } func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { @@ -95,7 +65,7 @@ func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { t.Skipf("not supported on %s", runtime.GOOS) } - c, err := net.ListenPacket("udp4", "127.0.0.1:0") + c, err := nettest.NewLocalPacketListener("udp4") if err != nil { t.Fatal(err) } @@ -103,11 +73,7 @@ func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { p := ipv4.NewPacketConn(c) defer p.Close() - dst, err := net.ResolveUDPAddr("udp4", c.LocalAddr().String()) - if err != nil { - t.Fatal(err) - } - + dst := c.LocalAddr() ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) cf := ipv4.FlagTTL | ipv4.FlagSrc | ipv4.FlagDst | ipv4.FlagInterface wb := []byte("HELLO-R-U-THERE") @@ -152,7 +118,7 @@ func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { t.Error(err) return } else if n != len(wb) { - t.Errorf("short write: %v", n) + t.Errorf("got %d; want %d", n, len(wb)) return } } diff --git a/vendor/golang.org/x/net/ipv4/unicast_test.go b/vendor/golang.org/x/net/ipv4/unicast_test.go index bce8763f7..02c089f00 100644 --- a/vendor/golang.org/x/net/ipv4/unicast_test.go +++ b/vendor/golang.org/x/net/ipv4/unicast_test.go @@ -28,18 +28,15 @@ func TestPacketConnReadWriteUnicastUDP(t *testing.T) { t.Skipf("not available on %s", runtime.GOOS) } - c, err := net.ListenPacket("udp4", "127.0.0.1:0") + c, err := nettest.NewLocalPacketListener("udp4") if err != nil { t.Fatal(err) } defer c.Close() - - dst, err := net.ResolveUDPAddr("udp4", c.LocalAddr().String()) - if err != nil { - t.Fatal(err) - } p := ipv4.NewPacketConn(c) defer p.Close() + + dst := c.LocalAddr() cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface wb := []byte("HELLO-R-U-THERE") diff --git a/vendor/golang.org/x/net/ipv6/control_rfc2292_unix.go b/vendor/golang.org/x/net/ipv6/control_rfc2292_unix.go index 1cf3901c8..9fd9eb15e 100644 --- a/vendor/golang.org/x/net/ipv6/control_rfc2292_unix.go +++ b/vendor/golang.org/x/net/ipv6/control_rfc2292_unix.go @@ -17,7 +17,7 @@ func marshal2292HopLimit(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_2292HOPLIMIT, 4) if cm != nil { - nativeEndian.PutUint32(m.Data(4), uint32(cm.HopLimit)) + socket.NativeEndian.PutUint32(m.Data(4), uint32(cm.HopLimit)) } return m.Next(4) } diff --git a/vendor/golang.org/x/net/ipv6/control_rfc3542_unix.go b/vendor/golang.org/x/net/ipv6/control_rfc3542_unix.go index 62cded610..eec529c20 100644 --- a/vendor/golang.org/x/net/ipv6/control_rfc3542_unix.go +++ b/vendor/golang.org/x/net/ipv6/control_rfc3542_unix.go @@ -18,26 +18,26 @@ func marshalTrafficClass(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_TCLASS, 4) if cm != nil { - nativeEndian.PutUint32(m.Data(4), uint32(cm.TrafficClass)) + socket.NativeEndian.PutUint32(m.Data(4), uint32(cm.TrafficClass)) } return m.Next(4) } func parseTrafficClass(cm *ControlMessage, b []byte) { - cm.TrafficClass = int(nativeEndian.Uint32(b[:4])) + cm.TrafficClass = int(socket.NativeEndian.Uint32(b[:4])) } func marshalHopLimit(b []byte, cm *ControlMessage) []byte { m := socket.ControlMessage(b) m.MarshalHeader(iana.ProtocolIPv6, sysIPV6_HOPLIMIT, 4) if cm != nil { - nativeEndian.PutUint32(m.Data(4), uint32(cm.HopLimit)) + socket.NativeEndian.PutUint32(m.Data(4), uint32(cm.HopLimit)) } return m.Next(4) } func parseHopLimit(cm *ControlMessage, b []byte) { - cm.HopLimit = int(nativeEndian.Uint32(b[:4])) + cm.HopLimit = int(socket.NativeEndian.Uint32(b[:4])) } func marshalPacketInfo(b []byte, cm *ControlMessage) []byte { diff --git a/vendor/golang.org/x/net/ipv6/doc.go b/vendor/golang.org/x/net/ipv6/doc.go index eaa24c580..664a97dea 100644 --- a/vendor/golang.org/x/net/ipv6/doc.go +++ b/vendor/golang.org/x/net/ipv6/doc.go @@ -8,7 +8,7 @@ // The package provides IP-level socket options that allow // manipulation of IPv6 facilities. // -// The IPv6 protocol is defined in RFC 2460. +// The IPv6 protocol is defined in RFC 8200. // Socket interface extensions are defined in RFC 3493, RFC 3542 and // RFC 3678. // MLDv1 and MLDv2 are defined in RFC 2710 and RFC 3810. diff --git a/vendor/golang.org/x/net/ipv6/helper.go b/vendor/golang.org/x/net/ipv6/helper.go index 7a42e5860..259740132 100644 --- a/vendor/golang.org/x/net/ipv6/helper.go +++ b/vendor/golang.org/x/net/ipv6/helper.go @@ -5,10 +5,8 @@ package ipv6 import ( - "encoding/binary" "errors" "net" - "unsafe" ) var ( @@ -17,20 +15,8 @@ var ( errInvalidConnType = errors.New("invalid conn type") errOpNoSupport = errors.New("operation not supported") errNoSuchInterface = errors.New("no such interface") - - nativeEndian binary.ByteOrder ) -func init() { - i := uint32(1) - b := (*[4]byte)(unsafe.Pointer(&i)) - if b[0] == 1 { - nativeEndian = binary.LittleEndian - } else { - nativeEndian = binary.BigEndian - } -} - func boolint(b bool) int { if b { return 1 @@ -51,3 +37,21 @@ func netAddrToIP16(a net.Addr) net.IP { } return nil } + +func opAddr(a net.Addr) net.Addr { + switch a.(type) { + case *net.TCPAddr: + if a == nil { + return nil + } + case *net.UDPAddr: + if a == nil { + return nil + } + case *net.IPAddr: + if a == nil { + return nil + } + } + return a +} diff --git a/vendor/golang.org/x/net/ipv6/icmp.go b/vendor/golang.org/x/net/ipv6/icmp.go index ff21d1071..b7f48e27b 100644 --- a/vendor/golang.org/x/net/ipv6/icmp.go +++ b/vendor/golang.org/x/net/ipv6/icmp.go @@ -29,7 +29,7 @@ func (typ ICMPType) Protocol() int { // packets. The filter belongs to a packet delivery path on a host and // it cannot interact with forwarding packets or tunnel-outer packets. // -// Note: RFC 2460 defines a reasonable role model. A node means a +// Note: RFC 8200 defines a reasonable role model. A node means a // device that implements IP. A router means a node that forwards IP // packets not explicitly addressed to itself, and a host means a node // that is not a router. diff --git a/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_8.go b/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_8.go index 431cff46f..fdc6c3994 100644 --- a/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_8.go +++ b/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_8.go @@ -49,7 +49,7 @@ func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (n case *net.IPConn: n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr)) default: - return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Err: errInvalidConnType} + return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Addr: opAddr(dst), Err: errInvalidConnType} } return } diff --git a/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_9.go b/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_9.go index 4072c585a..8f6d02e2f 100644 --- a/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_9.go +++ b/vendor/golang.org/x/net/ipv6/payload_cmsg_go1_9.go @@ -51,7 +51,7 @@ func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (in } err := c.SendMsg(&m, 0) if err != nil { - err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err} + err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Addr: opAddr(dst), Err: err} } return m.N, err } diff --git a/vendor/golang.org/x/net/ipv6/readwrite_test.go b/vendor/golang.org/x/net/ipv6/readwrite_test.go index 41f59be5a..206b915ce 100644 --- a/vendor/golang.org/x/net/ipv6/readwrite_test.go +++ b/vendor/golang.org/x/net/ipv6/readwrite_test.go @@ -17,87 +17,50 @@ import ( "golang.org/x/net/ipv6" ) -func benchmarkUDPListener() (net.PacketConn, net.Addr, error) { - c, err := net.ListenPacket("udp6", "[::1]:0") +func BenchmarkReadWriteUnicast(b *testing.B) { + c, err := nettest.NewLocalPacketListener("udp6") if err != nil { - return nil, nil, err - } - dst, err := net.ResolveUDPAddr("udp6", c.LocalAddr().String()) - if err != nil { - c.Close() - return nil, nil, err - } - return c, dst, nil -} - -func BenchmarkReadWriteNetUDP(b *testing.B) { - if !supportsIPv6 { - b.Skip("ipv6 is not supported") - } - - c, dst, err := benchmarkUDPListener() - if err != nil { - b.Fatal(err) + b.Skipf("not supported on %s/%s: %v", runtime.GOOS, runtime.GOARCH, err) } defer c.Close() + dst := c.LocalAddr() wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) - b.ResetTimer() - for i := 0; i < b.N; i++ { - benchmarkReadWriteNetUDP(b, c, wb, rb, dst) - } -} - -func benchmarkReadWriteNetUDP(b *testing.B, c net.PacketConn, wb, rb []byte, dst net.Addr) { - if _, err := c.WriteTo(wb, dst); err != nil { - b.Fatal(err) - } - if _, _, err := c.ReadFrom(rb); err != nil { - b.Fatal(err) - } -} -func BenchmarkReadWriteIPv6UDP(b *testing.B) { - if !supportsIPv6 { - b.Skip("ipv6 is not supported") - } - - c, dst, err := benchmarkUDPListener() - if err != nil { - b.Fatal(err) - } - defer c.Close() - - p := ipv6.NewPacketConn(c) - cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU - if err := p.SetControlMessage(cf, true); err != nil { - b.Fatal(err) - } - ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) - - wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) - b.ResetTimer() - for i := 0; i < b.N; i++ { - benchmarkReadWriteIPv6UDP(b, p, wb, rb, dst, ifi) - } -} + b.Run("NetUDP", func(b *testing.B) { + for i := 0; i < b.N; i++ { + if _, err := c.WriteTo(wb, dst); err != nil { + b.Fatal(err) + } + if _, _, err := c.ReadFrom(rb); err != nil { + b.Fatal(err) + } + } + }) + b.Run("IPv6UDP", func(b *testing.B) { + p := ipv6.NewPacketConn(c) + cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU + if err := p.SetControlMessage(cf, true); err != nil { + b.Fatal(err) + } + cm := ipv6.ControlMessage{ + TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, + HopLimit: 1, + } + ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) + if ifi != nil { + cm.IfIndex = ifi.Index + } -func benchmarkReadWriteIPv6UDP(b *testing.B, p *ipv6.PacketConn, wb, rb []byte, dst net.Addr, ifi *net.Interface) { - cm := ipv6.ControlMessage{ - TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, - HopLimit: 1, - } - if ifi != nil { - cm.IfIndex = ifi.Index - } - if n, err := p.WriteTo(wb, &cm, dst); err != nil { - b.Fatal(err) - } else if n != len(wb) { - b.Fatalf("got %v; want %v", n, len(wb)) - } - if _, _, _, err := p.ReadFrom(rb); err != nil { - b.Fatal(err) - } + for i := 0; i < b.N; i++ { + if _, err := p.WriteTo(wb, &cm, dst); err != nil { + b.Fatal(err) + } + if _, _, _, err := p.ReadFrom(rb); err != nil { + b.Fatal(err) + } + } + }) } func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { @@ -109,7 +72,7 @@ func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { t.Skip("ipv6 is not supported") } - c, err := net.ListenPacket("udp6", "[::1]:0") + c, err := nettest.NewLocalPacketListener("udp6") if err != nil { t.Fatal(err) } @@ -117,11 +80,7 @@ func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { p := ipv6.NewPacketConn(c) defer p.Close() - dst, err := net.ResolveUDPAddr("udp6", c.LocalAddr().String()) - if err != nil { - t.Fatal(err) - } - + dst := c.LocalAddr() ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU wb := []byte("HELLO-R-U-THERE") @@ -167,7 +126,7 @@ func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { t.Error(err) return } else if n != len(wb) { - t.Errorf("got %v; want %v", n, len(wb)) + t.Errorf("got %d; want %d", n, len(wb)) return } } diff --git a/vendor/golang.org/x/net/ipv6/unicast_test.go b/vendor/golang.org/x/net/ipv6/unicast_test.go index 406d07128..a0b7d9550 100644 --- a/vendor/golang.org/x/net/ipv6/unicast_test.go +++ b/vendor/golang.org/x/net/ipv6/unicast_test.go @@ -27,7 +27,7 @@ func TestPacketConnReadWriteUnicastUDP(t *testing.T) { t.Skip("ipv6 is not supported") } - c, err := net.ListenPacket("udp6", "[::1]:0") + c, err := nettest.NewLocalPacketListener("udp6") if err != nil { t.Fatal(err) } @@ -35,11 +35,7 @@ func TestPacketConnReadWriteUnicastUDP(t *testing.T) { p := ipv6.NewPacketConn(c) defer p.Close() - dst, err := net.ResolveUDPAddr("udp6", c.LocalAddr().String()) - if err != nil { - t.Fatal(err) - } - + dst := c.LocalAddr() cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, @@ -54,7 +50,8 @@ func TestPacketConnReadWriteUnicastUDP(t *testing.T) { for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { - t.Skipf("not supported on %s", runtime.GOOS) + t.Logf("not supported on %s", runtime.GOOS) + continue } t.Fatal(err) } @@ -151,7 +148,8 @@ func TestPacketConnReadWriteUnicastICMP(t *testing.T) { } if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { - t.Skipf("not supported on %s", runtime.GOOS) + t.Logf("not supported on %s", runtime.GOOS) + continue } t.Fatal(err) } diff --git a/vendor/golang.org/x/net/proxy/per_host.go b/vendor/golang.org/x/net/proxy/per_host.go index f540b196f..242d5623f 100644 --- a/vendor/golang.org/x/net/proxy/per_host.go +++ b/vendor/golang.org/x/net/proxy/per_host.go @@ -9,7 +9,7 @@ import ( "strings" ) -// A PerHost directs connections to a default Dialer unless the hostname +// A PerHost directs connections to a default Dialer unless the host name // requested matches one of a number of exceptions. type PerHost struct { def, bypass Dialer @@ -76,7 +76,7 @@ func (p *PerHost) dialerForRequest(host string) Dialer { // AddFromString parses a string that contains comma-separated values // specifying hosts that should use the bypass proxy. Each value is either an -// IP address, a CIDR range, a zone (*.example.com) or a hostname +// IP address, a CIDR range, a zone (*.example.com) or a host name // (localhost). A best effort is made to parse the string and errors are // ignored. func (p *PerHost) AddFromString(s string) { @@ -131,7 +131,7 @@ func (p *PerHost) AddZone(zone string) { p.bypassZones = append(p.bypassZones, zone) } -// AddHost specifies a hostname that will use the bypass proxy. +// AddHost specifies a host name that will use the bypass proxy. func (p *PerHost) AddHost(host string) { if strings.HasSuffix(host, ".") { host = host[:len(host)-1] diff --git a/vendor/golang.org/x/net/proxy/proxy.go b/vendor/golang.org/x/net/proxy/proxy.go index 78a8b7bee..553ead7cf 100644 --- a/vendor/golang.org/x/net/proxy/proxy.go +++ b/vendor/golang.org/x/net/proxy/proxy.go @@ -11,6 +11,7 @@ import ( "net" "net/url" "os" + "sync" ) // A Dialer is a means to establish a connection. @@ -27,7 +28,7 @@ type Auth struct { // FromEnvironment returns the dialer specified by the proxy related variables in // the environment. func FromEnvironment() Dialer { - allProxy := os.Getenv("all_proxy") + allProxy := allProxyEnv.Get() if len(allProxy) == 0 { return Direct } @@ -41,7 +42,7 @@ func FromEnvironment() Dialer { return Direct } - noProxy := os.Getenv("no_proxy") + noProxy := noProxyEnv.Get() if len(noProxy) == 0 { return proxy } @@ -92,3 +93,42 @@ func FromURL(u *url.URL, forward Dialer) (Dialer, error) { return nil, errors.New("proxy: unknown scheme: " + u.Scheme) } + +var ( + allProxyEnv = &envOnce{ + names: []string{"ALL_PROXY", "all_proxy"}, + } + noProxyEnv = &envOnce{ + names: []string{"NO_PROXY", "no_proxy"}, + } +) + +// envOnce looks up an environment variable (optionally by multiple +// names) once. It mitigates expensive lookups on some platforms +// (e.g. Windows). +// (Borrowed from net/http/transport.go) +type envOnce struct { + names []string + once sync.Once + val string +} + +func (e *envOnce) Get() string { + e.once.Do(e.init) + return e.val +} + +func (e *envOnce) init() { + for _, n := range e.names { + e.val = os.Getenv(n) + if e.val != "" { + return + } + } +} + +// reset is used by tests +func (e *envOnce) reset() { + e.once = sync.Once{} + e.val = "" +} diff --git a/vendor/golang.org/x/net/proxy/proxy_test.go b/vendor/golang.org/x/net/proxy/proxy_test.go index c19a5c063..0f31e211c 100644 --- a/vendor/golang.org/x/net/proxy/proxy_test.go +++ b/vendor/golang.org/x/net/proxy/proxy_test.go @@ -5,14 +5,73 @@ package proxy import ( + "bytes" + "fmt" "io" "net" "net/url" + "os" "strconv" + "strings" "sync" "testing" ) +type proxyFromEnvTest struct { + allProxyEnv string + noProxyEnv string + wantTypeOf Dialer +} + +func (t proxyFromEnvTest) String() string { + var buf bytes.Buffer + space := func() { + if buf.Len() > 0 { + buf.WriteByte(' ') + } + } + if t.allProxyEnv != "" { + fmt.Fprintf(&buf, "all_proxy=%q", t.allProxyEnv) + } + if t.noProxyEnv != "" { + space() + fmt.Fprintf(&buf, "no_proxy=%q", t.noProxyEnv) + } + return strings.TrimSpace(buf.String()) +} + +func TestFromEnvironment(t *testing.T) { + ResetProxyEnv() + + type dummyDialer struct { + direct + } + + RegisterDialerType("irc", func(_ *url.URL, _ Dialer) (Dialer, error) { + return dummyDialer{}, nil + }) + + proxyFromEnvTests := []proxyFromEnvTest{ + {allProxyEnv: "127.0.0.1:8080", noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: direct{}}, + {allProxyEnv: "ftp://example.com:8000", noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: direct{}}, + {allProxyEnv: "socks5://example.com:8080", noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: &PerHost{}}, + {allProxyEnv: "irc://example.com:8000", wantTypeOf: dummyDialer{}}, + {noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: direct{}}, + {wantTypeOf: direct{}}, + } + + for _, tt := range proxyFromEnvTests { + os.Setenv("ALL_PROXY", tt.allProxyEnv) + os.Setenv("NO_PROXY", tt.noProxyEnv) + ResetCachedEnvironment() + + d := FromEnvironment() + if got, want := fmt.Sprintf("%T", d), fmt.Sprintf("%T", tt.wantTypeOf); got != want { + t.Errorf("%v: got type = %T, want %T", tt, d, tt.wantTypeOf) + } + } +} + func TestFromURL(t *testing.T) { endSystem, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { @@ -140,3 +199,17 @@ func socks5Gateway(t *testing.T, gateway, endSystem net.Listener, typ byte, wg * return } } + +func ResetProxyEnv() { + for _, env := range []*envOnce{allProxyEnv, noProxyEnv} { + for _, v := range env.names { + os.Setenv(v, "") + } + } + ResetCachedEnvironment() +} + +func ResetCachedEnvironment() { + allProxyEnv.reset() + noProxyEnv.reset() +} diff --git a/vendor/golang.org/x/net/proxy/socks5.go b/vendor/golang.org/x/net/proxy/socks5.go index 973f57f19..2efec6e8d 100644 --- a/vendor/golang.org/x/net/proxy/socks5.go +++ b/vendor/golang.org/x/net/proxy/socks5.go @@ -154,7 +154,7 @@ func (s *socks5) connect(conn net.Conn, target string) error { buf = append(buf, ip...) } else { if len(host) > 255 { - return errors.New("proxy: destination hostname too long: " + host) + return errors.New("proxy: destination host name too long: " + host) } buf = append(buf, socks5Domain) buf = append(buf, byte(len(host))) |