Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

url: fix url.format with ipv6 hostname #36665

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions lib/url.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const {
ObjectCreate,
ObjectKeys,
SafeSet,
StringPrototypeCharCodeAt,
} = primordials;

const { toASCII } = require('internal/idna');
Expand Down Expand Up @@ -156,6 +157,14 @@ function urlParse(url, parseQueryString, slashesDenoteHost) {
return urlObject;
}

function isIpv6Hostname(hostname) {
return (
StringPrototypeCharCodeAt(hostname, 0) === CHAR_LEFT_SQUARE_BRACKET &&
StringPrototypeCharCodeAt(hostname, hostname.length - 1) ===
CHAR_RIGHT_SQUARE_BRACKET
);
}

Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {
validateString(url, 'url');

Expand Down Expand Up @@ -364,8 +373,7 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) {

// If hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
const ipv6Hostname = hostname.charCodeAt(0) === CHAR_LEFT_SQUARE_BRACKET &&
hostname.charCodeAt(hostname.length - 1) === CHAR_RIGHT_SQUARE_BRACKET;
const ipv6Hostname = isIpv6Hostname(hostname);

// validate a little.
if (!ipv6Hostname) {
Expand Down Expand Up @@ -590,7 +598,7 @@ Url.prototype.format = function format() {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (
this.hostname.includes(':') ?
this.hostname.includes(':') && !isIpv6Hostname(this.hostname) ?
'[' + this.hostname + ']' :
this.hostname
);
Expand Down
6 changes: 6 additions & 0 deletions test/parallel/test-url-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,12 @@ const formatTests = {
host: '[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:61616',
pathname: '/s/stopButton'
},
'http://[::]/': {
href: 'http://[::]/',
protocol: 'http:',
hostname: '[::]',
pathname: '/'
},

// Encode context-specific delimiters in path and query, but do not touch
// other non-delimiter chars like `%`.
Expand Down