base.ts 16 KB

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