Skip to content

Commit

Permalink
Merge pull request #2571 from JamesMGreene/fix_ipv6_host_header
Browse files Browse the repository at this point in the history
Correctly format the Host header for IPv6 addresses
  • Loading branch information
mikeal committed Mar 4, 2017
2 parents 667e923 + ff6d6c6 commit bce66a5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
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()
})
})

0 comments on commit bce66a5

Please sign in to comment.