base.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. import type { Span } from '../../trace';
  2. import { HostnameSmolTrie } from '../trie';
  3. import { not, nullthrow } from 'foxts/guard';
  4. import { fastIpVersion } from '../misc';
  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. bulkAddAnyCIDR(cidrs: string[], noResolve = false) {
  221. const list4 = noResolve ? this.ipcidrNoResolve : this.ipcidr;
  222. const list6 = noResolve ? this.ipcidr6NoResolve : this.ipcidr6;
  223. for (let i = 0, len = cidrs.length; i < len; i++) {
  224. let cidr = cidrs[i];
  225. const version = fastIpVersion(cidr);
  226. if (version === 0) {
  227. continue; // skip invalid IPs
  228. }
  229. cidr = FileOutput.ipToCidr(cidr, version);
  230. if (version === 4) {
  231. list4.add(cidr);
  232. } else /* if (version === 6) */ {
  233. list6.add(cidr);
  234. }
  235. }
  236. return this;
  237. }
  238. bulkAddCIDR4(cidrs: string[]) {
  239. for (let i = 0, len = cidrs.length; i < len; i++) {
  240. this.ipcidr.add(FileOutput.ipToCidr(cidrs[i], 4));
  241. }
  242. return this;
  243. }
  244. bulkAddCIDR4NoResolve(cidrs: string[]) {
  245. for (let i = 0, len = cidrs.length; i < len; i++) {
  246. this.ipcidrNoResolve.add(FileOutput.ipToCidr(cidrs[i], 4));
  247. }
  248. return this;
  249. }
  250. bulkAddCIDR6(cidrs: string[]) {
  251. for (let i = 0, len = cidrs.length; i < len; i++) {
  252. this.ipcidr6.add(FileOutput.ipToCidr(cidrs[i], 6));
  253. }
  254. return this;
  255. }
  256. bulkAddCIDR6NoResolve(cidrs: string[]) {
  257. for (let i = 0, len = cidrs.length; i < len; i++) {
  258. this.ipcidr6NoResolve.add(FileOutput.ipToCidr(cidrs[i], 6));
  259. }
  260. return this;
  261. }
  262. async done() {
  263. await this.pendingPromise;
  264. this.pendingPromise = null;
  265. return this;
  266. }
  267. // private guardPendingPromise() {
  268. // // reverse invariant
  269. // if (this.pendingPromise !== null) {
  270. // console.trace('Pending promise:', this.pendingPromise);
  271. // throw new Error('You should call done() before calling this method');
  272. // }
  273. // }
  274. // async writeClash(outputDir?: null | string) {
  275. // await this.done();
  276. // invariant(this.title, 'Missing title');
  277. // invariant(this.description, 'Missing description');
  278. // return compareAndWriteFile(
  279. // this.span,
  280. // withBannerArray(
  281. // this.title,
  282. // this.description,
  283. // this.date,
  284. // this.clash()
  285. // ),
  286. // path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  287. // );
  288. // }
  289. private strategiesWritten = false;
  290. private writeToStrategies() {
  291. if (this.pendingPromise) {
  292. throw new Error('You should call done() before calling writeToStrategies()');
  293. }
  294. if (this.strategiesWritten) {
  295. throw new Error('Strategies already written');
  296. }
  297. this.strategiesWritten = true;
  298. // We use both DOMAIN-KEYWORD and whitelisted keyword to whitelist DOMAIN and DOMAIN-SUFFIX
  299. const kwfilter = createKeywordFilter(
  300. Array.from(this.domainKeywords)
  301. .concat(Array.from(this.whitelistKeywords))
  302. );
  303. if (this.strategies.filter(not(false)).length === 0) {
  304. throw new Error('No strategies to write ' + this.id);
  305. }
  306. const strategiesLen = this.strategies.length;
  307. this.domainTrie.dumpWithoutDot((domain, includeAllSubdomain) => {
  308. if (kwfilter(domain)) {
  309. return;
  310. }
  311. this.wildcardTrie.whitelist(domain, includeAllSubdomain);
  312. for (let i = 0; i < strategiesLen; i++) {
  313. const strategy = this.strategies[i];
  314. if (includeAllSubdomain) {
  315. strategy.writeDomainSuffix(domain);
  316. } else {
  317. strategy.writeDomain(domain);
  318. }
  319. }
  320. }, true);
  321. // Now, we whitelisted out DOMAIN-KEYWORD
  322. const whiteKwfilter = createKeywordFilter(Array.from(this.whitelistKeywords));
  323. const whitelistedKeywords = Array.from(this.domainKeywords).filter(kw => !whiteKwfilter(kw));
  324. for (let i = 0; i < strategiesLen; i++) {
  325. const strategy = this.strategies[i];
  326. if (whitelistedKeywords.length) {
  327. strategy.writeDomainKeywords(this.domainKeywords);
  328. }
  329. if (this.protocol.size) {
  330. strategy.writeProtocols(this.protocol);
  331. }
  332. }
  333. this.wildcardTrie.dumpWithoutDot((wildcard) => {
  334. if (kwfilter(wildcard)) {
  335. return;
  336. }
  337. for (let i = 0; i < strategiesLen; i++) {
  338. const strategy = this.strategies[i];
  339. strategy.writeDomainWildcard(wildcard);
  340. }
  341. });
  342. const sourceIpOrCidr = Array.from(this.sourceIpOrCidr);
  343. for (let i = 0; i < strategiesLen; i++) {
  344. const strategy = this.strategies[i];
  345. if (this.userAgent.size) {
  346. strategy.writeUserAgents(this.userAgent);
  347. }
  348. if (this.processName.size) {
  349. strategy.writeProcessNames(this.processName);
  350. }
  351. if (this.processPath.size) {
  352. strategy.writeProcessPaths(this.processPath);
  353. }
  354. if (this.sourceIpOrCidr.size) {
  355. strategy.writeSourceIpCidrs(sourceIpOrCidr);
  356. }
  357. if (this.sourcePort.size) {
  358. strategy.writeSourcePorts(this.sourcePort);
  359. }
  360. if (this.destPort.size) {
  361. strategy.writeDestinationPorts(this.destPort);
  362. }
  363. if (this.otherRules.length) {
  364. strategy.writeOtherRules(this.otherRules);
  365. }
  366. if (this.urlRegex.size) {
  367. strategy.writeUrlRegexes(this.urlRegex);
  368. }
  369. }
  370. let ipcidr: string[] | null = null;
  371. let ipcidrNoResolve: string[] | null = null;
  372. let ipcidr6: string[] | null = null;
  373. let ipcidr6NoResolve: string[] | null = null;
  374. if (this.ipcidr.size) {
  375. ipcidr = mergeCidr(Array.from(this.ipcidr), true);
  376. }
  377. if (this.ipcidrNoResolve.size) {
  378. ipcidrNoResolve = mergeCidr(Array.from(this.ipcidrNoResolve), true);
  379. }
  380. if (this.ipcidr6.size) {
  381. ipcidr6 = Array.from(this.ipcidr6);
  382. }
  383. if (this.ipcidr6NoResolve.size) {
  384. ipcidr6NoResolve = Array.from(this.ipcidr6NoResolve);
  385. }
  386. for (let i = 0; i < strategiesLen; i++) {
  387. const strategy = this.strategies[i];
  388. // no-resolve
  389. if (ipcidrNoResolve) {
  390. strategy.writeIpCidrs(ipcidrNoResolve, true);
  391. }
  392. if (ipcidr6NoResolve) {
  393. strategy.writeIpCidr6s(ipcidr6NoResolve, true);
  394. }
  395. if (this.ipasnNoResolve.size) {
  396. strategy.writeIpAsns(this.ipasnNoResolve, true);
  397. }
  398. if (this.groipNoResolve.size) {
  399. strategy.writeGeoip(this.groipNoResolve, true);
  400. }
  401. // triggers DNS resolution
  402. if (ipcidr?.length) {
  403. strategy.writeIpCidrs(ipcidr, false);
  404. }
  405. if (ipcidr6?.length) {
  406. strategy.writeIpCidr6s(ipcidr6, false);
  407. }
  408. if (this.ipasn.size) {
  409. strategy.writeIpAsns(this.ipasn, false);
  410. }
  411. if (this.geoip.size) {
  412. strategy.writeGeoip(this.geoip, false);
  413. }
  414. }
  415. }
  416. write(): Promise<unknown> {
  417. return this.span.traceChildAsync('write all', async (childSpan) => {
  418. await this.done();
  419. childSpan.traceChildSync('write to strategies', () => this.writeToStrategies());
  420. return childSpan.traceChildAsync('output to disk', (childSpan) => {
  421. const promises: Array<Promise<void> | void> = [];
  422. for (let i = 0, len = this.strategies.length; i < len; i++) {
  423. const strategy = this.strategies[i];
  424. const basename = (strategy.overwriteFilename || this.id) + '.' + strategy.fileExtension;
  425. promises.push(
  426. childSpan.traceChildAsync('write ' + strategy.name, (childSpan) => Promise.resolve(strategy.output(
  427. childSpan,
  428. nullthrow(this.title, 'Missing title'),
  429. nullthrow(this.description, 'Missing description'),
  430. this.date,
  431. path.join(
  432. strategy.outputDir,
  433. strategy.type
  434. ? path.join(strategy.type, basename)
  435. : basename
  436. )
  437. )))
  438. );
  439. }
  440. return Promise.all(promises);
  441. });
  442. });
  443. }
  444. async compile(): Promise<Array<string[] | null>> {
  445. await this.done();
  446. this.writeToStrategies();
  447. return this.strategies.reduce<Array<string[] | null>>((acc, strategy) => {
  448. acc.push(strategy.content);
  449. return acc;
  450. }, []);
  451. }
  452. withMitmSgmodulePath(moduleName: string | null) {
  453. if (moduleName) {
  454. this.withExtraStrategies(new SurgeMitmSgmodule(moduleName));
  455. }
  456. return this;
  457. }
  458. }