url: fix url.format with ipv6 hostname

Fixes: https://github.com/nodejs/node/issues/36654

PR-URL: https://github.com/nodejs/node/pull/36665
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Daijiro Wachi <daijiro.wachi@gmail.com>
Reviewed-By: Yash Ladha <yash@yashladha.in>
This commit is contained in:
ZiJian Liu 2020-12-28 23:42:33 +08:00 committed by Node.js GitHub Bot
parent 37acaf668d
commit 1b7ac0c9ed
2 changed files with 17 additions and 3 deletions

View file

@ -26,6 +26,7 @@ const {
ObjectCreate,
ObjectKeys,
SafeSet,
StringPrototypeCharCodeAt,
} = primordials;
const { toASCII } = require('internal/idna');
@ -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');
@ -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) {
@ -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
);