Skip to content

Commit 85a4e25

Browse files
committed
http: add type checking for hostname
Add type checking for options.hostname / options.host Maintains the use of `undefined` and `null` for default `localhost`, but other falsy values (like `false`, `0` and `NaN`) are rejected. PR-URL: #12494 Ref: #12488 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Ali Ijaz Sheikh <[email protected]>
1 parent b968d58 commit 85a4e25

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

lib/_http_client.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,14 @@ function isInvalidPath(s) {
6565
return false;
6666
}
6767

68+
function validateHost(host, name) {
69+
if (host != null && typeof host !== 'string') {
70+
throw new TypeError(
71+
`"options.${name}" must either be a string, undefined or null`);
72+
}
73+
return host;
74+
}
75+
6876
function ClientRequest(options, cb) {
6977
OutgoingMessage.call(this);
7078

@@ -123,7 +131,8 @@ function ClientRequest(options, cb) {
123131
this.agent && this.agent.defaultPort;
124132

125133
var port = options.port = options.port || defaultPort || 80;
126-
var host = options.host = options.hostname || options.host || 'localhost';
134+
var host = options.host = validateHost(options.hostname, 'hostname') ||
135+
validateHost(options.host, 'host') || 'localhost';
127136

128137
var setHost = (options.setHost === undefined);
129138

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
const assert = require('assert');
5+
const http = require('http');
6+
7+
// All of these values should cause http.request() to throw synchronously
8+
// when passed as the value of either options.hostname or options.host
9+
const vals = [{}, [], NaN, Infinity, -Infinity, true, false, 1, 0, new Date()];
10+
11+
function errCheck(name) {
12+
return new RegExp(`^TypeError: "options\\.${name}" must either be a ` +
13+
'string, undefined or null$');
14+
}
15+
16+
vals.forEach((v) => {
17+
assert.throws(() => http.request({hostname: v}), errCheck('hostname'));
18+
assert.throws(() => http.request({host: v}), errCheck('host'));
19+
});
20+
21+
// These values are OK and should not throw synchronously
22+
['', undefined, null].forEach((v) => {
23+
assert.doesNotThrow(() => {
24+
http.request({hostname: v}).on('error', common.noop);
25+
http.request({host: v}).on('error', common.noop);
26+
});
27+
});

0 commit comments

Comments
 (0)