From 99940c7c8ac6c9b1a3d8f2fe49446678024c28af Mon Sep 17 00:00:00 2001 From: adnano Date: Mon, 28 Sep 2020 02:27:29 -0400 Subject: [PATCH] Use splitHostPort function from net/url --- client.go | 12 ++---------- verify.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/client.go b/client.go index 7b85b33..a8f97ec 100644 --- a/client.go +++ b/client.go @@ -50,7 +50,8 @@ type Request struct { // Hostname returns the request host without the port. func (r *Request) Hostname() string { - return hostname(r.Host) + host, _ := splitHostPort(r.Host) + return host } // NewRequest returns a new request. The host is inferred from the provided URL. @@ -300,12 +301,3 @@ func validCertificate(cert *x509.Certificate) bool { // No need to check hash algorithms, hopefully tls has checked for us already return true } - -// hostname extracts the host name from a valid host or host:port -func hostname(host string) string { - i := strings.LastIndexByte(host, ':') - if i != -1 { - return host[:i] - } - return host -} diff --git a/verify.go b/verify.go index 8a0fd5a..13c6b0f 100644 --- a/verify.go +++ b/verify.go @@ -1,6 +1,8 @@ // Hostname verification code from the crypto/x509 package. // Modified to allow Common Names in the short term, until new certificates // can be issued with SANs. +// +// Also includes the splitHostPort function from net/url package. // Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style @@ -225,3 +227,38 @@ func verifyHostname(c *x509.Certificate, h string) error { return x509.HostnameError{c, h} } + +// validOptionalPort reports whether port is either an empty string +// or matches /^:\d*$/ +func validOptionalPort(port string) bool { + if port == "" { + return true + } + if port[0] != ':' { + return false + } + for _, b := range port[1:] { + if b < '0' || b > '9' { + return false + } + } + return true +} + +// splitHostPort separates host and port. If the port is not valid, it returns +// the entire input as host, and it doesn't check the validity of the host. +// Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric. +func splitHostPort(hostport string) (host, port string) { + host = hostport + + colon := strings.LastIndexByte(host, ':') + if colon != -1 && validOptionalPort(host[colon:]) { + host, port = host[:colon], host[colon+1:] + } + + if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { + host = host[1 : len(host)-1] + } + + return +}