forked from eviltik/cidr-clean
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (55 loc) · 1.65 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"use strict";
const Netmask = require('netmask').Netmask;
const ipInt = require('ip-to-int');
function isCidrV4(c) {
return c.match(/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$/);
}
function cleaner(cidr1, cidr2) {
let n1, n2, removeMe = [], tmp;
// merge both
if (cidr2) {
tmp = cidr1.concat(cidr2);
} else {
tmp = cidr1;
}
cidr1 = cidr2 = null;
// remove extra spaces
tmp = tmp.map(c => {
return c.trim();
});
// remove comments or badly formated cidr
tmp = tmp.filter(c => {
if (isCidrV4(c)) return true;
});
// remove duplicates
tmp = Array.from(new Set(tmp));
// detect overlaps
tmp = tmp.filter((c1,idx1) => {
n1 = new Netmask(c1);
n1.firstInt = ipInt(n1.first).toInt();
n1.lastInt = ipInt(n1.last).toInt();
tmp.filter((c2,idx2) => {
if (idx1 === idx2) return true;
n2 = new Netmask(c2);
n2.firstInt = ipInt(n2.first).toInt();
n2.lastInt = ipInt(n2.last).toInt();
if (
(n2.firstInt >= n1.firstInt && n2.firstInt <= n1.lastInt)
||
(n2.lastInt >= n1.firstInt && n2.lastInt <= n1.lastInt)
) {
if (n1.size>n2.size) {
removeMe.push(idx2);
}
}
return true;
});
return true;
});
while (removeMe.length) {
tmp.splice(removeMe[removeMe.length-1],1);
removeMe.pop();
}
return tmp;
}
module.exports = cleaner;