Skip to content

Commit

Permalink
net/url: return an error if port is out of range
Browse files Browse the repository at this point in the history
The existing implementation does not validate
that the port number is in the allowed range.

WHATWG URL Living Standard mandates that
parsing URLs with invalid ports fails:
https://url.spec.whatwg.org/#port-out-of-range

Fixes golang#69443.
  • Loading branch information
dunglas committed Sep 13, 2024
1 parent 547baaf commit f8180b9
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
14 changes: 6 additions & 8 deletions src/net/url/url.go
Original file line number Diff line number Diff line change
Expand Up @@ -789,20 +789,18 @@ func (u *URL) EscapedFragment() string {
}

// validOptionalPort reports whether port is either an empty string
// or matches /^:\d*$/
// or matches /^:\d*$/ and fits in an unsigned 16-bit integer
func validOptionalPort(port string) bool {
if port == "" {
if port == "" || port == ":" {
return true
}
if port[0] != ':' {
return false
}
for _, b := range port[1:] {
if b < '0' || b > '9' {
return false
}
}
return true

p, err := strconv.Atoi(port[1:])

return err == nil && p < 65536
}

// String reassembles the [URL] into a valid URL string.
Expand Down
3 changes: 3 additions & 0 deletions src/net/url/url_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,9 @@ var parseRequestURLTests = []struct {
// RFC 6874.
{"http://[fe80::1%en0]/", false},
{"http://[fe80::1%en0]:8080/", false},

// Tests exercising WHATWG URL Living Standard compliance:
{"https://example.org:70000", false}, // port out of range
}

func TestParseRequestURI(t *testing.T) {
Expand Down

0 comments on commit f8180b9

Please sign in to comment.