base.ts 14 KB

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