aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoradnano <[email protected]>2020-09-28 02:27:29 -0400
committeradnano <[email protected]>2020-09-28 02:27:29 -0400
commit99940c7c8ac6c9b1a3d8f2fe49446678024c28af (patch)
tree43038b0236db268262d136acce76a0545a266537
parentRemove unused code (diff)
downloadgo-gemini-99940c7c8ac6c9b1a3d8f2fe49446678024c28af.tar.xz
go-gemini-99940c7c8ac6c9b1a3d8f2fe49446678024c28af.zip
Use splitHostPort function from net/url
-rw-r--r--client.go12
-rw-r--r--verify.go37
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
+}