base.ts 17 KB

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