From 8ed57bf6b895ad9f9f22d1e56b6b1940c9ec11ce Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Mon, 24 Jun 2019 18:15:58 +0200 Subject: [PATCH] http2: remove square brackets from parsed hostname Make `http2.connect()` work when using URLs with literal IPv6 addresses. Fixes: https://github.com/nodejs/node/issues/28216 PR-URL: https://github.com/nodejs/node/pull/28406 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott Reviewed-By: Trivikram Kamat Reviewed-By: James M Snell Reviewed-By: Jiawen Geng --- lib/internal/http2/core.js | 11 ++++++++++- test/parallel/test-http2-connect.js | 30 ++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index e3c4d2bc7b6e24..75ade8f7fa7acd 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -2782,7 +2782,16 @@ function connect(authority, options, listener) { const protocol = authority.protocol || options.protocol || 'https:'; const port = '' + (authority.port !== '' ? authority.port : (authority.protocol === 'http:' ? 80 : 443)); - const host = authority.hostname || authority.host || 'localhost'; + let host = 'localhost'; + + if (authority.hostname) { + host = authority.hostname; + + if (host[0] === '[') + host = host.slice(1, -1); + } else if (authority.host) { + host = authority.host; + } let socket; if (typeof options.createConnection === 'function') { diff --git a/test/parallel/test-http2-connect.js b/test/parallel/test-http2-connect.js index a2f30f974e9329..2137ef28926726 100644 --- a/test/parallel/test-http2-connect.js +++ b/test/parallel/test-http2-connect.js @@ -1,6 +1,12 @@ 'use strict'; -const { mustCall, hasCrypto, skip, expectsError } = require('../common'); +const { + mustCall, + hasCrypto, + hasIPv6, + skip, + expectsError +} = require('../common'); if (!hasCrypto) skip('missing crypto'); const { createServer, connect } = require('http2'); @@ -73,3 +79,25 @@ const { connect: netConnect } = require('net'); type: Error }); } + +// Check for literal IPv6 addresses in URL's +if (hasIPv6) { + const server = createServer(); + server.listen(0, '::1', mustCall(() => { + const { port } = server.address(); + const clients = new Set(); + + clients.add(connect(`http://[::1]:${port}`)); + clients.add(connect(new URL(`http://[::1]:${port}`))); + + for (const client of clients) { + client.once('connect', mustCall(() => { + client.close(); + clients.delete(client); + if (clients.size === 0) { + server.close(); + } + })); + } + })); +}