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

os: add CIDR support #14307

Merged
merged 1 commit into from
Aug 14, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions doc/api/os.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,9 @@ The properties available on the assigned network address object include:
similar interface that is not remotely accessible; otherwise `false`
* `scopeid` {number} The numeric IPv6 scope ID (only specified when `family`
is `IPv6`)
* `cidr` {string} The assigned IPv4 or IPv6 address with the routing prefix
in CIDR notation. If the `netmask` is invalid, this property is set
to `null`

<!-- eslint-skip -->
```js
Expand All @@ -263,14 +266,16 @@ The properties available on the assigned network address object include:
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true
internal: true,
cidr: '127.0.0.1/8'
},
{
address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
internal: true
internal: true,
cidr: '::1/128'
}
],
eth0: [
Expand All @@ -279,14 +284,16 @@ The properties available on the assigned network address object include:
netmask: '255.255.255.0',
family: 'IPv4',
mac: '01:02:03:0a:0b:0c',
internal: false
internal: false,
cidr: '192.168.1.108/24'
},
{
address: 'fe80::a00:27ff:fe4e:66a1',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: '01:02:03:0a:0b:0c',
internal: false
internal: false,
cidr: 'fe80::a00:27ff:fe4e:66a1/64'
}
]
}
Expand Down
41 changes: 41 additions & 0 deletions lib/internal/os.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

function getCIDRSuffix(mask, protocol = 'ipv4') {
const isV6 = protocol === 'ipv6';
const bitsString = mask
.split(isV6 ? ':' : '.')
.filter((v) => !!v)
.map((v) => pad(parseInt(v, isV6 ? 16 : 10).toString(2), isV6))
.join('');

if (isValidMask(bitsString)) {
return countOnes(bitsString);
} else {
return null;
}
}

function pad(binaryString, isV6) {
const groupLength = isV6 ? 16 : 8;
const binLen = binaryString.length;

return binLen < groupLength ?
`${'0'.repeat(groupLength - binLen)}${binaryString}` : binaryString;
}

function isValidMask(bitsString) {
const firstIndexOfZero = bitsString.indexOf(0);
const lastIndexOfOne = bitsString.lastIndexOf(1);

return firstIndexOfZero < 0 || firstIndexOfZero > lastIndexOfOne;
}

function countOnes(bitsString) {
return bitsString
.split('')
.reduce((acc, bit) => acc += parseInt(bit, 10), 0);
}

module.exports = {
getCIDRSuffix
};
18 changes: 17 additions & 1 deletion lib/os.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
const pushValToArrayMax = process.binding('util').pushValToArrayMax;
const constants = process.binding('constants').os;
const deprecate = require('internal/util').deprecate;
const getCIDRSuffix = require('internal/os').getCIDRSuffix;
const isWindows = process.platform === 'win32';

const {
Expand Down Expand Up @@ -121,6 +122,21 @@ function endianness() {
}
endianness[Symbol.toPrimitive] = () => kEndianness;

function networkInterfaces() {
const interfaceAddresses = getInterfaceAddresses();

return Object.entries(interfaceAddresses).reduce((acc, [key, val]) => {
acc[key] = val.map((v) => {
const protocol = v.family.toLowerCase();
const suffix = getCIDRSuffix(v.netmask, protocol);
const cidr = suffix ? `${v.address}/${suffix}` : null;

return Object.assign({}, v, { cidr });
});
return acc;
}, {});
}

module.exports = exports = {
arch,
cpus,
Expand All @@ -130,7 +146,7 @@ module.exports = exports = {
homedir: getHomeDirectory,
hostname: getHostname,
loadavg,
networkInterfaces: getInterfaceAddresses,
networkInterfaces,
platform,
release: getOSRelease,
tmpdir,
Expand Down
1 change: 1 addition & 0 deletions node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
'lib/internal/linkedlist.js',
'lib/internal/net.js',
'lib/internal/module.js',
'lib/internal/os.js',
'lib/internal/process/next_tick.js',
'lib/internal/process/promises.js',
'lib/internal/process/stdio.js',
Expand Down
32 changes: 32 additions & 0 deletions test/parallel/test-internal-os.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Flags: --expose-internals
'use strict';

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

const specs = [
// valid
['128.0.0.0', 'ipv4', 1],
['255.0.0.0', 'ipv4', 8],
['255.255.255.128', 'ipv4', 25],
['255.255.255.255', 'ipv4', 32],
['ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', 'ipv6', 128],
['ffff:ffff:ffff:ffff::', 'ipv6', 64],
['ffff:ffff:ffff:ff80::', 'ipv6', 57],
// invalid
['255.0.0.1', 'ipv4', null],
['255.255.9.0', 'ipv4', null],
['255.255.1.0', 'ipv4', null],
['ffff:ffff:43::', 'ipv6', null],
['ffff:ffff:ffff:1::', 'ipv6', null]
];

specs.forEach(([mask, protocol, expectedSuffix]) => {
const actualSuffix = getCIDRSuffix(mask, protocol);

assert.strictEqual(
actualSuffix, expectedSuffix,
`Mask: ${mask}, expected: ${expectedSuffix}, actual: ${actualSuffix}`
);
});
25 changes: 23 additions & 2 deletions test/parallel/test-os.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const common = require('../common');
const assert = require('assert');
const os = require('os');
const path = require('path');
const { inspect } = require('util');

const is = {
string: (value) => { assert.strictEqual(typeof value, 'string'); },
Expand Down Expand Up @@ -121,7 +122,7 @@ switch (platform) {
const actual = interfaces.lo.filter(filter);
const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0',
mac: '00:00:00:00:00:00', family: 'IPv4',
internal: true }];
internal: true, cidr: '127.0.0.1/8' }];
assert.deepStrictEqual(actual, expected);
break;
}
Expand All @@ -131,11 +132,31 @@ switch (platform) {
const actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter);
const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0',
mac: '00:00:00:00:00:00', family: 'IPv4',
internal: true }];
internal: true, cidr: '127.0.0.1/8' }];
assert.deepStrictEqual(actual, expected);
break;
}
}
function flatten(arr) {
return arr.reduce(
(acc, c) => acc.concat(Array.isArray(c) ? flatten(c) : c),
[]
);
}
const netmaskToCIDRSuffixMap = new Map(Object.entries({
'255.0.0.0': 8,
'255.255.255.0': 24,
'ffff:ffff:ffff:ffff::': 64,
'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff': 128
Copy link
Contributor

@silverwind silverwind Jul 16, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also add some tests for non-byte-aligned subnet masks, e.g. 255.255.224.0 -> 19 and ffff:ffff:ffff:ff80:: -> 57.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is hard as I rely on the output of networkInterfaces method and that gets data from the os binding. So, I don't really know where I can inject some mock data with a custom non-aligned netmask and have the js land networkInterfaces method consume that. Any ideas?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, you could potential define the parsing method in a internal os module and test that separately.

Copy link
Contributor Author

@zeusdeux zeusdeux Jul 16, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@silverwind So I moved the code out but requiring internal/os fails with a module not found. Do I need to register it somewhere? Found this registry node.gyp.

Secondly, where do tests for internal modules go? I see thetest folder in lib/internal only has tests for unicode.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zeusdeux In test, just like everything else. You would need to specify a // Flags: --expose-internals to make the testing harness expose internal modules for testing though.

Copy link
Contributor Author

@zeusdeux zeusdeux Aug 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved the CIDR logic to internal/os and added tests for it @silverwind @TimothyGu.

}));
flatten(Object.values(interfaces))
.map((v) => ({ v, mask: netmaskToCIDRSuffixMap.get(v.netmask) }))
.forEach(({ v, mask }) => {
assert.ok('cidr' in v, `"cidr" prop not found in ${inspect(v)}`);
if (mask) {
assert.strictEqual(v.cidr, `${v.address}/${mask}`);
}
});

const EOL = os.EOL;
assert.ok(EOL.length > 0);
Expand Down