base.ts 17 KB

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