Skip to content

Commit b176d30

Browse files
committed
dns: handle array holes in setServers()
This commit adds better handling of exceptional array formats passed to dns.setServers(). Prior to this commit, the input array was validated using map(), which preserves holes, allowing them to be passed to c-ares, crashing Node. This commit replaces map() with forEach(), which skips holes. Fixes: #8538 PR-URL: #8567 Reviewed-By: Ilkka Myller <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent d4bf5ca commit b176d30

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

lib/dns.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -286,25 +286,26 @@ exports.setServers = function(servers) {
286286
// cache the original servers because in the event of an error setting the
287287
// servers cares won't have any servers available for resolution
288288
const orig = cares.getServers();
289+
const newSet = [];
289290

290-
const newSet = servers.map((serv) => {
291+
servers.forEach((serv) => {
291292
var ipVersion = isIP(serv);
292293
if (ipVersion !== 0)
293-
return [ipVersion, serv];
294+
return newSet.push([ipVersion, serv]);
294295

295296
const match = serv.match(/\[(.*)\](:\d+)?/);
296297
// we have an IPv6 in brackets
297298
if (match) {
298299
ipVersion = isIP(match[1]);
299300
if (ipVersion !== 0)
300-
return [ipVersion, match[1]];
301+
return newSet.push([ipVersion, match[1]]);
301302
}
302303

303304
const s = serv.split(/:\d+$/)[0];
304305
ipVersion = isIP(s);
305306

306307
if (ipVersion !== 0)
307-
return [ipVersion, s];
308+
return newSet.push([ipVersion, s]);
308309

309310
throw new Error(`IP address is not properly formatted: ${serv}`);
310311
});

test/parallel/test-dns.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,33 @@ const dns = require('dns');
77
var existing = dns.getServers();
88
assert(existing.length);
99

10+
// Verify that setServers() handles arrays with holes and other oddities
11+
assert.doesNotThrow(() => {
12+
const servers = [];
13+
14+
servers[0] = '127.0.0.1';
15+
servers[2] = '0.0.0.0';
16+
dns.setServers(servers);
17+
});
18+
19+
assert.doesNotThrow(() => {
20+
const servers = ['127.0.0.1', '192.168.1.1'];
21+
22+
servers[3] = '127.1.0.1';
23+
servers[4] = '127.1.0.1';
24+
servers[5] = '127.1.1.1';
25+
26+
Object.defineProperty(servers, 2, {
27+
enumerable: true,
28+
get: () => {
29+
servers.length = 3;
30+
return '0.0.0.0';
31+
}
32+
});
33+
34+
dns.setServers(servers);
35+
});
36+
1037
function noop() {}
1138

1239
var goog = [

0 commit comments

Comments
 (0)