-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
386 lines (336 loc) · 11.9 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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#!/usr/bin/env node
/* eslint-disable no-case-declarations */
/**
* @license MIT
* Copyright 2020 İlteriş Yağıztegin Eroğlu (linuxgemini)
* SPDX-License-Identifier: MIT
*/
"use strict";
const chalk = require("chalk");
const cliProgress = require("cli-progress");
const csvStringify = require("csv-stringify/lib/sync");
const dns = require("dns").promises;
const fetch = require("node-fetch");
const fs = require("fs");
const inquirer = require("inquirer");
const program = require("commander");
const { promisify } = require("util");
/*
* API Endpoint Constants
*/
const RIPESTAT_AS_OVERVIEW_URL = "https://stat.ripe.net/data/as-overview/data.json";
const RIPESTAT_COUNTRY_ASNS_URL = "https://stat.ripe.net/data/country-asns/data.json";
const RIPESTAT_RIS_PREFIXES_URL = "https://stat.ripe.net/data/ris-prefixes/data.json";
/**
* Constants that doesn't have to change
*/
const SCRIPT_NAME = "ripe-country-stat_js";
/**
* Critical constants
* DON'T CHANGE
*/
const COUNTRY_ASNS_REGEX = /{?(AsnSingle\()(\d+)(\),? ?)}?/g; // ASN is on $2
const COUNTRY_CODES = require("./cc.json");
const dnsresolver = new dns.Resolver();
dnsresolver.setServers([
"1.1.1.1",
"1.0.0.1",
"2606:4700:4700::1111",
"2606:4700:4700::1001",
"9.9.9.9"
]);
let printedMessages = [];
let processStamp = 0;
class ripeStatError extends Error {
constructor(errmessage = "no message provided.", ...params) {
super(...params);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ripeStatError);
}
this.message = errmessage;
this.date = new Date();
this.type = "ripeStatError";
}
}
const exit = () => {
return setTimeout(() => {
process.exit(0);
}, 1000);
};
/**
* @param {Error} err
*/
const exitWithError = (err) => {
console.error("\n\nAn error occured!\n");
if (err.stack) console.error(`\nStacktrace:\n${err.stack}\n`);
return setTimeout(() => {
process.exit(1);
}, 1000);
};
/**
* @param {Error} err
*/
const exitWithRIPEerror = (err) => {
console.error(`\n\nRIPEstat ${chalk.red("error")}: ${chalk.yellow(err.message)}`);
return setTimeout(() => {
process.exit(0);
}, 1000);
};
/**
* @param {number} ms
*/
const sleep = promisify(setTimeout);
/**
* @param {string} apiURL
* @param {string} resource
* @param {{}|any} extraParams
*/
const generateURLWithQueryParams = (apiURL, resource, extraParams = {}) => {
let qs = new URLSearchParams({
resource,
"sourceapp": SCRIPT_NAME,
"soft_limit": "ignore",
...extraParams
});
return `${apiURL}?${qs}`;
};
const createCSV = (asnObjectArray) => {
return csvStringify(asnObjectArray, {
header: true,
columns: {
asn: "AS Number",
asnOrg: "Organization Name",
prefixCount4: "Announced IPv4 Prefix Count",
prefixCount6: "Announced IPv6 Prefix Count"
}
});
};
/**
* @param {string} str
* @param {RegExp} regexp
* @param {number} index
* @returns {string}
*/
const getRegexGroupFromIndex = (str, regexp, index) => {
return Array.from(str.matchAll(regexp), match => match[index]);
};
/**
* @param {Object} object
* @param {any} value
* @returns {any}
*/
const getKeyByValue = (object, value) => {
return Object.keys(object).find(key => object[key] === value);
};
/**
* @param {string[][]} bigArr
* @param {boolean} ignoreMsg
*/
const processRIPEmessages = async (bigArr, ignoreMsg = false) => {
const caller = (new Error()).stack.split("\n")[2].trim().split(" ")[1];
if (bigArr && bigArr.length !== 0) {
for (const messageArray of bigArr) {
let msg;
switch (messageArray[0].toLowerCase()) {
case "info":
msg = `RIPEstat ${chalk.blue("info")} (${caller}): ${messageArray[1]}`;
if (!printedMessages.includes(msg) && !ignoreMsg) {
console.log(msg);
printedMessages.push(msg);
}
break;
case "error":
throw new ripeStatError(messageArray[1]);
default:
msg = `RIPEstat ${chalk.yellow(messageArray[0])} (${caller}): ${messageArray[1]}`;
if (!printedMessages.includes(msg) && !ignoreMsg) {
console.log(msg);
printedMessages.push(msg);
}
break;
}
}
}
return;
};
/**
* @param {string} str
* @returns {string}
*/
const strStrip = (str) => {
const regexStart = /^\s+/;
const regexEnd = /\s+$/;
return str.replace(regexStart, "").replace(regexEnd, "");
};
/**
* @deprecated
* @param {string} asn
* @returns {string}
*/
const getASNname = async (asn) => { // eslint-disable-line no-unused-vars
const raw = await fetch(generateURLWithQueryParams(RIPESTAT_AS_OVERVIEW_URL, asn));
if (!raw.ok) {
const errData = await raw.text();
throw new ripeStatError(`${raw.status}\n\n${errData}`);
}
const data = await raw.json();
await processRIPEmessages(data.messages);
return data.data.holder;
};
/**
* @param {string} asn
*/
const getASNnameOverDNS = async (asn) => {
const callDomain = `AS${asn}.asn.cymru.com`;
const reply = await dnsresolver.resolveTxt(callDomain);
let infoArray = strStrip(reply[0][0]).replace(/( \| )/g, "--||--").split("--||--");
return infoArray[4].slice(0,-4);
};
/**
* @param {string} asn
*/
const getOriginatedPrefixCount = async (asn) => {
const raw = await fetch(generateURLWithQueryParams(RIPESTAT_RIS_PREFIXES_URL, asn));
if (!raw.ok) {
const errData = await raw.text();
throw new ripeStatError(`${raw.status}\n\n${errData}`);
}
const data = await raw.json();
await processRIPEmessages(data.messages, true);
return {
/** @type {number} */
prefixCount4: data.data.counts.v4.originating,
/** @type {number} */
prefixCount6: data.data.counts.v6.originating
};
};
/**
* @param {string} cc
*/
const getCountryASNs = async (cc) => {
cc = cc.toUpperCase();
console.log(`Getting ASN list of ${COUNTRY_CODES[cc]}...`);
const raw = await fetch(generateURLWithQueryParams(RIPESTAT_COUNTRY_ASNS_URL, cc, { lod: 1 }));
if (!raw.ok) {
const errData = await raw.text();
throw new ripeStatError(`${raw.status}\n\n${errData}`);
}
const data = await raw.json();
await processRIPEmessages(data.messages);
const activeASNs = (data.data.countries[0].routed && (data.data.countries[0].routed !== "" || data.data.countries[0].routed !== "set()") ? getRegexGroupFromIndex(data.data.countries[0].routed, COUNTRY_ASNS_REGEX, 2).sort((a, b) => (parseInt(a) - parseInt(b))) : []);
const inactiveASNs = (data.data.countries[0].non_routed && (data.data.countries[0].non_routed !== "" || data.data.countries[0].non_routed !== "set()") ? getRegexGroupFromIndex(data.data.countries[0].non_routed, COUNTRY_ASNS_REGEX, 2).sort((a, b) => (parseInt(a) - parseInt(b))) : []);
const allASNs = activeASNs.concat(inactiveASNs).sort((a, b) => (parseInt(a) - parseInt(b)));
console.log(`${COUNTRY_CODES[cc]}:
${activeASNs.length} Active ASNs
${inactiveASNs.length} Inactive ASNs
${allASNs.length} Total ASNs`);
return {
/** @type {string[]} */
activeASNs,
/** @type {string[]} */
inactiveASNs,
/** @type {string[]} */
allASNs
};
};
const main = () => {
program
.version("0.1.0", "-v, --version")
.description("Get the IP prefix count stats for any country.");
program
.action(async () => {
const progress = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);
let isProgressStarted = false;
try {
let typePrompt = await inquirer.prompt([
{
"type": "list",
"name": "method",
"message": "How do you want to select the country?",
"choices": [
"Enter ISO-3166-1 alpha-2 code",
"Select from list"
],
"default": 0
}
]);
let countryCode;
switch (typePrompt.method) {
case "Select from list":
let countryPrompt = await inquirer.prompt([
{
"type": "list",
"name": "country",
"message": "Please select the country:",
"choices": Object.values(COUNTRY_CODES)
}
]);
countryCode = getKeyByValue(COUNTRY_CODES, countryPrompt.country);
break;
case "Enter ISO-3166-1 alpha-2 code":
let alphaCodePrompt = await inquirer.prompt([
{
"type": "input",
"name": "alphaCode",
"message": "Please enter the ISO-3166-1 alpha-2 code:",
"validate": (cc) => {
if (!COUNTRY_CODES[cc.toUpperCase()]) return false;
return true;
}
}
]);
countryCode = alphaCodePrompt.alphaCode;
break;
default:
break;
}
let countryASNs = await getCountryASNs(countryCode);
let finalArr = [];
if (countryASNs.allASNs.length === 0) {
console.log(chalk.yellow("No ASNs found, quitting..."));
return exit();
}
console.log(chalk.yellow("This process may take quite a while (and may even error) depending on country, get a coffee and do something else while this is running."));
progress.start(countryASNs.allASNs.length, 0);
isProgressStarted = true;
for (const asn of countryASNs.activeASNs) {
processStamp = Date.now();
const asnOrg = await getASNnameOverDNS(asn);
const prefixes = await getOriginatedPrefixCount(asn);
finalArr.push({
asn,
asnOrg,
...prefixes
});
progress.increment(1);
await sleep(Date.now() - processStamp);
}
for (const asn of countryASNs.inactiveASNs) {
const asnOrg = await getASNnameOverDNS(asn);
finalArr.push({
asn,
asnOrg,
prefixCount4: 0,
prefixCount6: 0
});
progress.increment(1);
}
progress.stop();
finalArr = finalArr.sort((a, b) => (parseInt(a.asn) - parseInt(b.asn)));
fs.writeFileSync(`./${countryCode.toUpperCase()}.csv`, createCSV(finalArr));
console.log(`
${chalk.green(`Processed ${finalArr.length} ASNs.`)}
Saved to "${countryCode.toUpperCase()}.csv".`);
exit();
} catch (e) {
if (isProgressStarted) progress.stop();
if (e.type && e.type === "ripeStatError") {
exitWithRIPEerror(e);
} else {
exitWithError(e);
}
}
});
program.parse(process.argv);
};
main();