/
DomainUtils.ts
101 lines (85 loc) · 2.63 KB
/
DomainUtils.ts
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import * as dns from 'dns';
import * as _ from 'lodash';
import {Log} from '../logging/Log';
import {PlatformUtils} from '@allgemein/base';
if (dns['getServers'] && dns['getServers']().length < 2) {
const serversToSet = [
'127.0.0.1',
'8.8.8.8', '8.8.4.4', // Google Public DNS
'77.88.8.8', '77.88.8.1', // Yandex Basic
// '77.88.8.88', '77.88.8.2', // Yandex Safe
// '77.88.8.7', '77.88.8.3', // Yandex Family
];
dns.setServers(serversToSet);
}
export class DomainUtils {
static IP_REGEX = /^(([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])$/;
static HOSTS: { host: string, ip: string }[] = [];
static domainLookup(domain: string): Promise<{ addr: string, family: number }> {
return new Promise(function (resolve, reject) {
if (DomainUtils.IP_REGEX.test(domain)) {
resolve({
addr: domain,
family: 4
});
} else {
dns.lookup(domain, function (err, address, family) {
if (err) {
resolve(null);
} else {
resolve({addr: address, family: family});
}
});
}
});
}
static reverse(ip: string, local: boolean = false): Promise<string[]> {
if (this.IP_REGEX.test(ip)) {
return new Promise(function (resolve, reject) {
const id = setTimeout(() => {
resolve(null);
}, 250);
dns.reverse(ip, function (err, hostnames) {
clearTimeout(id);
if (err) {
resolve(null);
} else {
resolve(hostnames);
}
});
})
.then((hostnames: string[]) => {
// TODO reload host if not loaded
const hosts = _.filter(DomainUtils.HOSTS, {ip: ip});
if (!_.isEmpty(hosts)) {
hosts.forEach(_x => {
hostnames.unshift(_x.host);
});
}
return _.uniq(hostnames);
}).catch(e => {
Log.error(e);
throw e;
});
} else {
return Promise.resolve([]);
}
}
static reloadHosts() {
this.HOSTS = this.getHostsSync();
}
static getHostsSync(): { host: string, ip: string }[] {
const content = PlatformUtils.getHostFileContent();
const hosts: { host: string, ip: string }[] = [];
content.split(/\r?\n/).map(function (x: string) {
const matches = /^\s*?([^#]+?)\s+([^#]+?)$/.exec(x);
if (matches && matches.length === 3) {
matches[2].trim().split(' ').forEach(_x => {
hosts.push({host: _x, ip: matches[1]}); // host:ip
});
}
return null;
});
return hosts;
}
}