From a7d467992df6165050c909abeff7bcdfb37e8022 Mon Sep 17 00:00:00 2001 From: Darien Raymond Date: Thu, 1 Mar 2018 11:32:55 +0100 Subject: [PATCH] try parse domain address as IP. fixes #894. --- common/protocol/address.go | 25 ++++++++++++++++++++++++- common/protocol/address_test.go | 11 +++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/common/protocol/address.go b/common/protocol/address.go index 44c1abb9..a0ae6352 100644 --- a/common/protocol/address.go +++ b/common/protocol/address.go @@ -55,6 +55,19 @@ func (p *AddressParser) readPort(b *buf.Buffer, reader io.Reader) (net.Port, err return net.PortFromBytes(b.BytesFrom(-2)), nil } +func maybeIPPrefix(b byte) bool { + return b == '[' || (b >= '0' && b <= '9') +} + +func isValidDomain(d string) bool { + for _, c := range d { + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-' || c == '.') { + return false + } + } + return true +} + func (p *AddressParser) readAddress(b *buf.Buffer, reader io.Reader) (net.Address, error) { if err := b.AppendSupplier(buf.ReadFullFrom(reader, 1)); err != nil { return nil, err @@ -89,7 +102,17 @@ func (p *AddressParser) readAddress(b *buf.Buffer, reader io.Reader) (net.Addres if err := b.AppendSupplier(buf.ReadFullFrom(reader, domainLength)); err != nil { return nil, err } - return net.DomainAddress(string(b.BytesFrom(-domainLength))), nil + domain := string(b.BytesFrom(-domainLength)) + if maybeIPPrefix(domain[0]) { + addr := net.ParseAddress(domain) + if addr.Family().IsIPv4() || addrFamily.IsIPv6() { + return addr, nil + } + } + if !isValidDomain(domain) { + return nil, newError("invalid domain name: ", domain) + } + return net.DomainAddress(domain), nil default: panic("impossible case") } diff --git a/common/protocol/address_test.go b/common/protocol/address_test.go index 584ae747..d66d119e 100644 --- a/common/protocol/address_test.go +++ b/common/protocol/address_test.go @@ -58,6 +58,17 @@ func TestAddressReading(t *testing.T) { Input: []byte{3, 9, 118, 50, 114, 97, 121, 46, 99, 111, 109, 0}, Error: true, }, + { + Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)}, + Input: []byte{3, 7, 56, 46, 56, 46, 56, 46, 56, 0, 80}, + Address: net.ParseAddress("8.8.8.8"), + Port: net.Port(80), + }, + { + Options: []AddressOption{AddressFamilyByte(0x03, net.AddressFamilyDomain)}, + Input: []byte{3, 7, 10, 46, 56, 46, 56, 46, 56, 0, 80}, + Error: true, + }, } for _, tc := range data {