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