base.ts 15 KB

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