base.ts 17 KB

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