Skip to content

Commit

Permalink
net: stricter checking for internal/net isLegalPort
Browse files Browse the repository at this point in the history
Add stricter testing for the isLegalPort method in internal/net.
This ensures that odd inputs such as isLegalPort(true) and
isLegalPort([1]) aren't acceptable as valid port inputs.
  • Loading branch information
jasnell committed Mar 21, 2016
1 parent 287bdab commit 551e3d2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
5 changes: 3 additions & 2 deletions lib/internal/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ module.exports = { isLegalPort };
// Check that the port number is not NaN when coerced to a number,
// is an integer and that it falls within the legal range of port numbers.
function isLegalPort(port) {
if (typeof port === 'string' && port.trim() === '')
if ((typeof port !== 'number' && typeof port !== 'string') ||
(typeof port === 'string' && port.trim().length === 0))
return false;
return +port === (port >>> 0) && port >= 0 && port <= 0xFFFF;
return +port === (+port >>> 0) && port <= 0xFFFF;
}
23 changes: 14 additions & 9 deletions test/parallel/test-net-internal.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@

require('../common');
const assert = require('assert');
const net = require('internal/net');

assert.strictEqual(net.isLegalPort(''), false);
assert.strictEqual(net.isLegalPort('0'), true);
assert.strictEqual(net.isLegalPort(0), true);
assert.strictEqual(net.isLegalPort(65536), false);
assert.strictEqual(net.isLegalPort('65535'), true);
assert.strictEqual(net.isLegalPort(undefined), false);
assert.strictEqual(net.isLegalPort(null), true);
const isLegalPort = require('internal/net').isLegalPort;

for (var n = 0; n <= 0xFFFF; n++) {
assert(isLegalPort(n));
assert(isLegalPort('' + n));
assert(`0x${n.toString(16)}`);
assert(`0o${n.toString(8)}`);
assert(`0b${n.toString(2)}`);
}

const bad = [-1, 'a', {}, [], false, true, 0xFFFF + 1, Infinity,
-Infinity, NaN, undefined, null, '', ' ', 1.1, '0x',
'-0x1', '-0o1', '-0b1', '0o', '0b'];
bad.forEach((i) => assert(!isLegalPort(i)));

0 comments on commit 551e3d2

Please sign in to comment.