base.ts 17 KB

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