base.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. import type { Span } from '../../trace';
  2. import { HostnameSmolTrie } from 'hntrie/smol';
  3. import { domainToASCII } from 'node:url';
  4. import { not, nullthrow } from 'foxts/guard';
  5. import { fastIpVersion } from 'foxts/fast-ip-version';
  6. import { addArrayElementsToSet } from 'foxts/add-array-elements-to-set';
  7. import type { MaybePromise } from '../misc';
  8. import type { BaseWriteStrategy } from '../writing-strategy/base';
  9. import { merge as mergeCidr } from 'fast-cidr-tools';
  10. import { createRetrieKeywordFilter as createKeywordFilter } from 'foxts/retrie';
  11. import path from 'node:path';
  12. import { SurgeMitmSgmodule } from '../writing-strategy/surge';
  13. import { appendArrayInPlace } from 'foxts/append-array-in-place';
  14. /**
  15. * Holds the universal rule data (domain, ip, url-regex, etc. etc.)
  16. * This class is not about format, instead it will call the class that does
  17. */
  18. export class FileOutput {
  19. protected strategies: BaseWriteStrategy[] = [];
  20. protected dataSource = new Set<string>();
  21. public domainTrie = new HostnameSmolTrie();
  22. public wildcardSet = new Set<string>();
  23. protected domainKeywords = new Set<string>();
  24. private readonly whitelistKeywords = new Set<string>();
  25. protected userAgent = new Set<string>();
  26. protected processName = new Set<string>();
  27. protected processPath = new Set<string>();
  28. protected urlRegex = new Set<string>();
  29. protected ipcidr = new Set<string>();
  30. protected ipcidrNoResolve = new Set<string>();
  31. protected ipasn = new Set<string>();
  32. protected ipasnNoResolve = new Set<string>();
  33. protected ipcidr6 = new Set<string>();
  34. protected ipcidr6NoResolve = new Set<string>();
  35. protected geoip = new Set<string>();
  36. protected groipNoResolve = new Set<string>();
  37. protected sourceIpOrCidr = new Set<string>();
  38. protected sourcePort = new Set<string>();
  39. protected destPort = new Set<string>();
  40. protected protocol = new Set<string>();
  41. protected otherRules: string[] = [];
  42. private pendingPromise: Promise<any> | null = null;
  43. whitelistDomain = (domain: string) => {
  44. this.domainTrie.whitelist(domain);
  45. return this;
  46. };
  47. whitelistKeyword = (keyword: string) => {
  48. this.whitelistKeywords.add(keyword);
  49. return this;
  50. };
  51. protected readonly span: Span;
  52. constructor($span: Span, protected readonly id: string) {
  53. this.span = $span.traceChild('RuleOutput#' + id);
  54. }
  55. protected title: string | null = null;
  56. withTitle(title: string) {
  57. this.title = title;
  58. return this;
  59. }
  60. public withStrategies(strategies: BaseWriteStrategy[]) {
  61. this.strategies = strategies;
  62. return this;
  63. }
  64. withExtraStrategies(strategy: BaseWriteStrategy) {
  65. this.strategies.push(strategy);
  66. }
  67. protected description: string[] | null = null;
  68. withDescription(description: string[] | readonly string[]) {
  69. this.description = description as string[];
  70. return this;
  71. }
  72. appendDescription(description: string | string[], ...rest: string[]) {
  73. this.description ??= [];
  74. if (typeof description === 'string') {
  75. this.description.push(description);
  76. } else {
  77. appendArrayInPlace(this.description, description);
  78. }
  79. if (rest.length) {
  80. appendArrayInPlace(this.description, rest);
  81. }
  82. return this;
  83. }
  84. protected date = new Date();
  85. withDate(date: Date) {
  86. this.date = date;
  87. return this;
  88. }
  89. addDomain(domain: string) {
  90. this.domainTrie.add(domain);
  91. return this;
  92. }
  93. bulkAddDomain(domains: Array<string | null>) {
  94. for (let i = 0, len = domains.length; i < len; i++) {
  95. const d = domains[i];
  96. if (d !== null) {
  97. this.domainTrie.add(d);
  98. }
  99. }
  100. return this;
  101. }
  102. addDomainSuffix(domain: string) {
  103. if (domain[0] === '.') {
  104. this.domainTrie.add(domain);
  105. } else {
  106. this.domainTrie.addSubdomain(domain);
  107. }
  108. return this;
  109. }
  110. bulkAddDomainSuffix(domains: string[]) {
  111. for (let i = 0, len = domains.length; i < len; i++) {
  112. this.addDomainSuffix(domains[i]);
  113. }
  114. return this;
  115. }
  116. addDomainKeyword(keyword: string) {
  117. this.domainKeywords.add(keyword);
  118. return this;
  119. }
  120. bulkAddDomainKeyword(keywords: string[]) {
  121. for (let i = 0, len = keywords.length; i < len; i++) {
  122. this.domainKeywords.add(keywords[i]);
  123. }
  124. return this;
  125. }
  126. addDomainWildcard(wildcard: string) {
  127. this.wildcardSet.add(wildcard);
  128. return this;
  129. }
  130. bulkAddDomainWildcard(wildcards: string[]) {
  131. for (let i = 0, len = wildcards.length; i < len; i++) {
  132. this.wildcardSet.add(wildcards[i]);
  133. }
  134. return this;
  135. }
  136. addIPASN(asn: string) {
  137. this.ipasn.add(asn);
  138. return this;
  139. }
  140. bulkAddIPASN(asns: string[]) {
  141. for (let i = 0, len = asns.length; i < len; i++) {
  142. this.ipasn.add(asns[i]);
  143. }
  144. return this;
  145. }
  146. private async addFromDomainsetPromise(source: MaybePromise<AsyncIterable<string> | Iterable<string> | string[]>) {
  147. for await (let line of await source) {
  148. const otherPoundSign = line.lastIndexOf('#');
  149. if (otherPoundSign > 0) {
  150. line = line.slice(0, otherPoundSign).trimEnd();
  151. }
  152. if (line[0] === '.') {
  153. this.addDomainSuffix(line);
  154. } else {
  155. this.domainTrie.add(line);
  156. }
  157. }
  158. }
  159. addFromDomainset(source: MaybePromise<AsyncIterable<string> | Iterable<string> | string[]>) {
  160. if (this.pendingPromise) {
  161. this.pendingPromise = this.pendingPromise.then(() => this.addFromDomainsetPromise(source));
  162. return this;
  163. }
  164. this.pendingPromise = this.addFromDomainsetPromise(source);
  165. return this;
  166. }
  167. private async addFromRulesetPromise(source: MaybePromise<AsyncIterable<string> | Iterable<string> | string[]>) {
  168. for await (let line of await source) {
  169. const otherPoundSign = line.lastIndexOf('#');
  170. if (otherPoundSign > 0) {
  171. line = line.slice(0, otherPoundSign).trimEnd();
  172. }
  173. const splitted = line.split(',');
  174. const type = splitted[0].toUpperCase();
  175. const value = splitted[1];
  176. const arg = splitted[2];
  177. switch (type) {
  178. case 'DOMAIN':
  179. this.domainTrie.add(value);
  180. break;
  181. case 'DOMAIN-SUFFIX':
  182. this.domainTrie.addSubdomain(value);
  183. break;
  184. case 'DOMAIN-KEYWORD':
  185. this.addDomainKeyword(value);
  186. break;
  187. case 'DOMAIN-WILDCARD':
  188. this.wildcardSet.add(value);
  189. break;
  190. case 'USER-AGENT':
  191. this.userAgent.add(value);
  192. break;
  193. case 'PROCESS-NAME':
  194. if (value.includes('/') || value.includes('\\')) {
  195. this.processPath.add(value);
  196. } else {
  197. this.processName.add(value);
  198. }
  199. break;
  200. case 'URL-REGEX': {
  201. const [, ...rest] = splitted;
  202. this.urlRegex.add(rest.join(','));
  203. break;
  204. }
  205. case 'IP-CIDR':
  206. (arg === 'no-resolve' ? this.ipcidrNoResolve : this.ipcidr).add(value);
  207. break;
  208. case 'IP-CIDR6':
  209. (arg === 'no-resolve' ? this.ipcidr6NoResolve : this.ipcidr6).add(value);
  210. break;
  211. case 'IP-ASN':
  212. (arg === 'no-resolve' ? this.ipasnNoResolve : this.ipasn).add(value);
  213. break;
  214. case 'GEOIP':
  215. (arg === 'no-resolve' ? this.groipNoResolve : this.geoip).add(value);
  216. break;
  217. case 'SRC-IP':
  218. this.sourceIpOrCidr.add(value);
  219. break;
  220. case 'SRC-PORT':
  221. this.sourcePort.add(value);
  222. break;
  223. case 'DEST-PORT':
  224. this.destPort.add(value);
  225. break;
  226. case 'PROTOCOL':
  227. this.protocol.add(value.toUpperCase());
  228. break;
  229. default:
  230. this.otherRules.push(line);
  231. break;
  232. }
  233. }
  234. }
  235. addFromRuleset(source: MaybePromise<AsyncIterable<string> | Iterable<string>>) {
  236. if (this.pendingPromise) {
  237. this.pendingPromise = this.pendingPromise.then(() => this.addFromRulesetPromise(source));
  238. return this;
  239. }
  240. this.pendingPromise = this.addFromRulesetPromise(source);
  241. return this;
  242. }
  243. static readonly ipToCidr = (ip: string, version: 4 | 6) => {
  244. if (ip.includes('/')) return ip;
  245. if (version === 4) {
  246. return ip + '/32';
  247. }
  248. return ip + '/128';
  249. };
  250. addAnyCIDR(cidr: string, noResolve = false) {
  251. const version = fastIpVersion(cidr);
  252. if (version === 0) return this;
  253. let list: Set<string>;
  254. if (version === 4) {
  255. list = noResolve ? this.ipcidrNoResolve : this.ipcidr;
  256. } else /* if (version === 6) */ {
  257. list = noResolve ? this.ipcidr6NoResolve : this.ipcidr6;
  258. }
  259. list.add(FileOutput.ipToCidr(cidr, version));
  260. return this;
  261. }
  262. bulkAddAnyCIDR(cidrs: string[], noResolve = false) {
  263. const list4 = noResolve ? this.ipcidrNoResolve : this.ipcidr;
  264. const list6 = noResolve ? this.ipcidr6NoResolve : this.ipcidr6;
  265. for (let i = 0, len = cidrs.length; i < len; i++) {
  266. let cidr = cidrs[i];
  267. const version = fastIpVersion(cidr);
  268. if (version === 0) {
  269. continue; // skip invalid IPs
  270. }
  271. cidr = FileOutput.ipToCidr(cidr, version);
  272. if (version === 4) {
  273. list4.add(cidr);
  274. } else /* if (version === 6) */ {
  275. list6.add(cidr);
  276. }
  277. }
  278. return this;
  279. }
  280. bulkAddCIDR4(cidrs: string[]) {
  281. for (let i = 0, len = cidrs.length; i < len; i++) {
  282. this.ipcidr.add(FileOutput.ipToCidr(cidrs[i], 4));
  283. }
  284. return this;
  285. }
  286. bulkAddCIDR4NoResolve(cidrs: string[]) {
  287. for (let i = 0, len = cidrs.length; i < len; i++) {
  288. this.ipcidrNoResolve.add(FileOutput.ipToCidr(cidrs[i], 4));
  289. }
  290. return this;
  291. }
  292. bulkAddCIDR6(cidrs: string[]) {
  293. for (let i = 0, len = cidrs.length; i < len; i++) {
  294. this.ipcidr6.add(FileOutput.ipToCidr(cidrs[i], 6));
  295. }
  296. return this;
  297. }
  298. bulkAddCIDR6NoResolve(cidrs: string[]) {
  299. for (let i = 0, len = cidrs.length; i < len; i++) {
  300. this.ipcidr6NoResolve.add(FileOutput.ipToCidr(cidrs[i], 6));
  301. }
  302. return this;
  303. }
  304. /**
  305. * Add data source information. This will be rendered inside description
  306. */
  307. appendDataSource(source: string | string[]) {
  308. if (typeof source === 'string') {
  309. this.dataSource.add(source);
  310. } else {
  311. addArrayElementsToSet(this.dataSource, source);
  312. }
  313. return this;
  314. }
  315. async done() {
  316. await this.pendingPromise;
  317. this.pendingPromise = null;
  318. return this;
  319. }
  320. // private guardPendingPromise() {
  321. // // reverse invariant
  322. // if (this.pendingPromise !== null) {
  323. // console.trace('Pending promise:', this.pendingPromise);
  324. // throw new Error('You should call done() before calling this method');
  325. // }
  326. // }
  327. // async writeClash(outputDir?: null | string) {
  328. // await this.done();
  329. // invariant(this.title, 'Missing title');
  330. // invariant(this.description, 'Missing description');
  331. // return compareAndWriteFile(
  332. // this.span,
  333. // withBannerArray(
  334. // this.title,
  335. // this.description,
  336. // this.date,
  337. // this.clash()
  338. // ),
  339. // path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  340. // );
  341. // }
  342. private strategiesWritten = false;
  343. private writeToStrategies() {
  344. if (this.pendingPromise) {
  345. throw new Error('You should call done() before calling writeToStrategies()');
  346. }
  347. if (this.strategiesWritten) {
  348. throw new Error('Strategies already written');
  349. }
  350. this.strategiesWritten = true;
  351. // We use both DOMAIN-KEYWORD and whitelisted keyword to whitelist DOMAIN and DOMAIN-SUFFIX
  352. const kwfilter = createKeywordFilter(
  353. Array.from(this.domainKeywords)
  354. .concat(Array.from(this.whitelistKeywords))
  355. );
  356. if (this.strategies.filter(not(false)).length === 0) {
  357. throw new Error('No strategies to write ' + this.id);
  358. }
  359. const strategiesLen = this.strategies.length;
  360. const domainEntries: Array<[domain: string, subdomain: boolean]> = [];
  361. this.domainTrie.dump((domain, includeSubdomain) => {
  362. const d = domainToASCII(domain);
  363. if (d) domainEntries.push([d, includeSubdomain]);
  364. });
  365. domainEntries.sort((a, b) => (a[0].length - b[0].length) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
  366. for (let j = 0, entriesLen = domainEntries.length; j < entriesLen; j++) {
  367. const [domain, includeAllSubdomain] = domainEntries[j];
  368. if (kwfilter(domain)) {
  369. continue;
  370. }
  371. for (let i = 0; i < strategiesLen; i++) {
  372. const strategy = this.strategies[i];
  373. if (includeAllSubdomain) {
  374. strategy.writeDomainSuffix(domain);
  375. } else {
  376. strategy.writeDomain(domain);
  377. }
  378. }
  379. }
  380. // Now, we whitelisted out DOMAIN-KEYWORD
  381. const whiteKwfilter = createKeywordFilter(Array.from(this.whitelistKeywords));
  382. const whitelistedKeywords = Array.from(this.domainKeywords).filter(kw => !whiteKwfilter(kw));
  383. for (let i = 0; i < strategiesLen; i++) {
  384. const strategy = this.strategies[i];
  385. if (whitelistedKeywords.length) {
  386. strategy.writeDomainKeywords(this.domainKeywords);
  387. }
  388. if (this.protocol.size) {
  389. strategy.writeProtocols(this.protocol);
  390. }
  391. }
  392. if (this.wildcardSet.size) {
  393. this.wildcardSet.forEach((wildcard) => {
  394. // Overlapped w/ DOMAIN-kEYWORD
  395. if (kwfilter(wildcard)) {
  396. return;
  397. }
  398. for (let i = 0; i < strategiesLen; i++) {
  399. const strategy = this.strategies[i];
  400. strategy.writeDomainWildcard(wildcard);
  401. }
  402. });
  403. }
  404. const sourceIpOrCidr = Array.from(this.sourceIpOrCidr);
  405. for (let i = 0; i < strategiesLen; i++) {
  406. const strategy = this.strategies[i];
  407. if (this.userAgent.size) {
  408. strategy.writeUserAgents(this.userAgent);
  409. }
  410. if (this.processName.size) {
  411. strategy.writeProcessNames(this.processName);
  412. }
  413. if (this.processPath.size) {
  414. strategy.writeProcessPaths(this.processPath);
  415. }
  416. if (this.sourceIpOrCidr.size) {
  417. strategy.writeSourceIpCidrs(sourceIpOrCidr);
  418. }
  419. if (this.sourcePort.size) {
  420. strategy.writeSourcePorts(this.sourcePort);
  421. }
  422. if (this.destPort.size) {
  423. strategy.writeDestinationPorts(this.destPort);
  424. }
  425. if (this.otherRules.length) {
  426. strategy.writeOtherRules(this.otherRules);
  427. }
  428. if (this.urlRegex.size) {
  429. strategy.writeUrlRegexes(this.urlRegex);
  430. }
  431. }
  432. let ipcidr: string[] | null = null;
  433. let ipcidrNoResolve: string[] | null = null;
  434. let ipcidr6: string[] | null = null;
  435. let ipcidr6NoResolve: string[] | null = null;
  436. if (this.ipcidr.size) {
  437. ipcidr = mergeCidr(Array.from(this.ipcidr), true);
  438. }
  439. if (this.ipcidrNoResolve.size) {
  440. ipcidrNoResolve = mergeCidr(Array.from(this.ipcidrNoResolve), true);
  441. }
  442. if (this.ipcidr6.size) {
  443. ipcidr6 = Array.from(this.ipcidr6);
  444. }
  445. if (this.ipcidr6NoResolve.size) {
  446. ipcidr6NoResolve = Array.from(this.ipcidr6NoResolve);
  447. }
  448. for (let i = 0; i < strategiesLen; i++) {
  449. const strategy = this.strategies[i];
  450. // no-resolve
  451. if (ipcidrNoResolve) {
  452. strategy.writeIpCidrs(ipcidrNoResolve, true);
  453. }
  454. if (ipcidr6NoResolve) {
  455. strategy.writeIpCidr6s(ipcidr6NoResolve, true);
  456. }
  457. if (this.ipasnNoResolve.size) {
  458. strategy.writeIpAsns(this.ipasnNoResolve, true);
  459. }
  460. if (this.groipNoResolve.size) {
  461. strategy.writeGeoip(this.groipNoResolve, true);
  462. }
  463. // triggers DNS resolution
  464. if (ipcidr?.length) {
  465. strategy.writeIpCidrs(ipcidr, false);
  466. }
  467. if (ipcidr6?.length) {
  468. strategy.writeIpCidr6s(ipcidr6, false);
  469. }
  470. if (this.ipasn.size) {
  471. strategy.writeIpAsns(this.ipasn, false);
  472. }
  473. if (this.geoip.size) {
  474. strategy.writeGeoip(this.geoip, false);
  475. }
  476. }
  477. }
  478. write(): Promise<unknown> {
  479. return this.span.traceChildAsync('write all', async (childSpan) => {
  480. await childSpan.traceChildAsync('done', () => this.done());
  481. childSpan.traceChildSync('write to strategies', () => this.writeToStrategies());
  482. return childSpan.traceChildAsync('output to disk', (childSpan) => {
  483. const promises: Array<Promise<void>> = [];
  484. const descriptions = nullthrow(this.description, 'Missing description');
  485. if (this.dataSource.size) {
  486. descriptions.push(
  487. '',
  488. 'This file contains data from:'
  489. );
  490. appendArrayInPlace(descriptions, Array.from(this.dataSource).sort().map((source) => ` - ${source}`));
  491. }
  492. for (let i = 0, len = this.strategies.length; i < len; i++) {
  493. const strategy = this.strategies[i];
  494. const basename = (strategy.overwriteFilename || this.id) + '.' + strategy.fileExtension;
  495. promises.push(
  496. childSpan.traceChildAsync('write ' + strategy.name, (childSpan) => Promise.resolve(strategy.output(
  497. childSpan,
  498. nullthrow(this.title, 'Missing title'),
  499. descriptions,
  500. this.date,
  501. path.join(
  502. strategy.outputDir,
  503. strategy.type
  504. ? path.join(strategy.type, basename)
  505. : basename
  506. )
  507. )))
  508. );
  509. }
  510. return Promise.all(promises);
  511. });
  512. });
  513. }
  514. async compile(): Promise<Array<string[] | null>> {
  515. await this.done();
  516. this.writeToStrategies();
  517. return this.strategies.reduce<Array<string[] | null>>((acc, strategy) => {
  518. acc.push(strategy.content);
  519. return acc;
  520. }, []);
  521. }
  522. withMitmSgmodulePath(moduleName: string | null) {
  523. if (moduleName) {
  524. this.withExtraStrategies(new SurgeMitmSgmodule(moduleName));
  525. }
  526. return this;
  527. }
  528. }