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

Correctly format the Host header for IPv6 addresses #2571

Merged
merged 1 commit into from Mar 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 4 additions & 7 deletions request.js
Expand Up @@ -289,13 +289,10 @@ Request.prototype.init = function (options) {
self.setHost = false
if (!self.hasHeader('host')) {
var hostHeaderName = self.originalHostHeaderName || 'host'
self.setHeader(hostHeaderName, self.uri.hostname)
if (self.uri.port) {
if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
!(self.uri.port === 443 && self.uri.protocol === 'https:') ) {
self.setHeader(hostHeaderName, self.getHeader('host') + (':' + self.uri.port) )
}
}
// When used with an IPv6 address, `host` will provide
// the correct bracketed format, unlike using `hostname` and
// optionally adding the `port` when necessary.
self.setHeader(hostHeaderName, self.uri.host)
self.setHost = true
}

Expand Down
40 changes: 40 additions & 0 deletions tests/test-headers.js
Expand Up @@ -4,6 +4,7 @@ var server = require('./server')
, request = require('../index')
, util = require('util')
, tape = require('tape')
, url = require('url')

var s = server.createServer()

Expand Down Expand Up @@ -201,3 +202,42 @@ tape('catch invalid characters error - POST', function(t) {
t.end()
})
})

tape('IPv6 Host header', function(t) {
// Horrible hack to observe the raw data coming to the server
var rawData = ''

s.on('connection', function(socket) {
if (socket.ondata) {
var ondata = socket.ondata
}
function handledata (d, start, end) {
if (ondata) {
rawData += d.slice(start, end).toString()
return ondata.apply(this, arguments)
} else {
rawData += d
}
}
socket.on('data', handledata)
socket.ondata = handledata
})

function checkHostHeader(host) {
t.ok(
new RegExp('^Host: ' + host + '$', 'im').test(rawData),
util.format(
'Expected "Host: %s" in data "%s"',
host, rawData.trim().replace(/\r?\n/g, '\\n')))
rawData = ''
}

request({
url : s.url.replace(url.parse(s.url).hostname, '[::1]') + '/headers.json'
}, function(err, res, body) {
t.equal(err, null)
t.equal(res.statusCode, 200)
checkHostHeader('\\[::1\\]:' + s.port)
t.end()
})
})