base.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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, 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: AsyncIterable<string> | Iterable<string> | string[]) {
  107. for await (const line of 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. if ('then' in source) {
  118. this.pendingPromise = this.pendingPromise.then(() => source).then(src => this.addFromDomainsetPromise(src));
  119. return this;
  120. }
  121. this.pendingPromise = this.pendingPromise.then(() => this.addFromDomainsetPromise(source));
  122. return this;
  123. }
  124. if ('then' in source) {
  125. this.pendingPromise = source.then(src => this.addFromDomainsetPromise(src));
  126. return this;
  127. }
  128. this.pendingPromise = this.addFromDomainsetPromise(source);
  129. return this;
  130. }
  131. private async addFromRulesetPromise(source: AsyncIterable<string> | Iterable<string> | string[]) {
  132. for await (const line of source) {
  133. const splitted = line.split(',');
  134. const type = splitted[0];
  135. const value = splitted[1];
  136. const arg = splitted[2];
  137. switch (type) {
  138. case 'DOMAIN':
  139. this.domainTrie.add(value, false, null, 0);
  140. break;
  141. case 'DOMAIN-SUFFIX':
  142. this.addDomainSuffix(value, false);
  143. break;
  144. case 'DOMAIN-KEYWORD':
  145. this.addDomainKeyword(value);
  146. break;
  147. case 'DOMAIN-WILDCARD':
  148. this.domainWildcard.add(value);
  149. break;
  150. case 'USER-AGENT':
  151. this.userAgent.add(value);
  152. break;
  153. case 'PROCESS-NAME':
  154. if (value.includes('/') || value.includes('\\')) {
  155. this.processPath.add(value);
  156. } else {
  157. this.processName.add(value);
  158. }
  159. break;
  160. case 'URL-REGEX': {
  161. const [, ...rest] = splitted;
  162. this.urlRegex.add(rest.join(','));
  163. break;
  164. }
  165. case 'IP-CIDR':
  166. (arg === 'no-resolve' ? this.ipcidrNoResolve : this.ipcidr).add(value);
  167. break;
  168. case 'IP-CIDR6':
  169. (arg === 'no-resolve' ? this.ipcidr6NoResolve : this.ipcidr6).add(value);
  170. break;
  171. case 'IP-ASN':
  172. (arg === 'no-resolve' ? this.ipasnNoResolve : this.ipasn).add(value);
  173. break;
  174. case 'GEOIP':
  175. (arg === 'no-resolve' ? this.groipNoResolve : this.geoip).add(value);
  176. break;
  177. case 'SRC-IP':
  178. this.sourceIpOrCidr.add(value);
  179. break;
  180. case 'SRC-PORT':
  181. this.sourcePort.add(value);
  182. break;
  183. case 'DEST-PORT':
  184. this.destPort.add(value);
  185. break;
  186. default:
  187. this.otherRules.push(line);
  188. break;
  189. }
  190. }
  191. }
  192. addFromRuleset(source: MaybePromise<AsyncIterable<string> | Iterable<string>>) {
  193. if (this.pendingPromise) {
  194. if ('then' in source) {
  195. this.pendingPromise = this.pendingPromise.then(() => source).then(src => this.addFromRulesetPromise(src));
  196. return this;
  197. }
  198. this.pendingPromise = this.pendingPromise.then(() => this.addFromRulesetPromise(source));
  199. return this;
  200. }
  201. if ('then' in source) {
  202. this.pendingPromise = source.then(src => this.addFromRulesetPromise(src));
  203. return this;
  204. }
  205. this.pendingPromise = this.addFromRulesetPromise(source);
  206. return this;
  207. }
  208. static readonly ipToCidr = (ip: string, version: 4 | 6) => {
  209. if (ip.includes('/')) return ip;
  210. if (version === 4) {
  211. return ip + '/32';
  212. }
  213. return ip + '/128';
  214. };
  215. bulkAddCIDR4(cidrs: string[]) {
  216. for (let i = 0, len = cidrs.length; i < len; i++) {
  217. this.ipcidr.add(FileOutput.ipToCidr(cidrs[i], 4));
  218. }
  219. return this;
  220. }
  221. bulkAddCIDR4NoResolve(cidrs: string[]) {
  222. for (let i = 0, len = cidrs.length; i < len; i++) {
  223. this.ipcidrNoResolve.add(FileOutput.ipToCidr(cidrs[i], 4));
  224. }
  225. return this;
  226. }
  227. bulkAddCIDR6(cidrs: string[]) {
  228. for (let i = 0, len = cidrs.length; i < len; i++) {
  229. this.ipcidr6.add(FileOutput.ipToCidr(cidrs[i], 6));
  230. }
  231. return this;
  232. }
  233. bulkAddCIDR6NoResolve(cidrs: string[]) {
  234. for (let i = 0, len = cidrs.length; i < len; i++) {
  235. this.ipcidr6NoResolve.add(FileOutput.ipToCidr(cidrs[i], 6));
  236. }
  237. return this;
  238. }
  239. async done() {
  240. await this.pendingPromise;
  241. this.pendingPromise = null;
  242. return this;
  243. }
  244. // private guardPendingPromise() {
  245. // // reverse invariant
  246. // if (this.pendingPromise !== null) {
  247. // console.trace('Pending promise:', this.pendingPromise);
  248. // throw new Error('You should call done() before calling this method');
  249. // }
  250. // }
  251. // async writeClash(outputDir?: null | string) {
  252. // await this.done();
  253. // invariant(this.title, 'Missing title');
  254. // invariant(this.description, 'Missing description');
  255. // return compareAndWriteFile(
  256. // this.span,
  257. // withBannerArray(
  258. // this.title,
  259. // this.description,
  260. // this.date,
  261. // this.clash()
  262. // ),
  263. // path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  264. // );
  265. // }
  266. private strategiesWritten = false;
  267. private writeToStrategies() {
  268. if (this.pendingPromise) {
  269. throw new Error('You should call done() before calling writeToStrategies()');
  270. }
  271. if (this.strategiesWritten) {
  272. throw new Error('Strategies already written');
  273. }
  274. this.strategiesWritten = true;
  275. const kwfilter = createKeywordFilter(Array.from(this.domainKeywords));
  276. if (this.strategies.filter(not(false)).length === 0) {
  277. throw new Error('No strategies to write ' + this.id);
  278. }
  279. this.domainTrie.dumpWithoutDot((domain, includeAllSubdomain) => {
  280. if (kwfilter(domain)) {
  281. return;
  282. }
  283. for (let i = 0, len = this.strategies.length; i < len; i++) {
  284. const strategy = this.strategies[i];
  285. if (strategy) {
  286. if (includeAllSubdomain) {
  287. strategy.writeDomainSuffix(domain);
  288. } else {
  289. strategy.writeDomain(domain);
  290. }
  291. }
  292. }
  293. }, true);
  294. for (let i = 0, len = this.strategies.length; i < len; i++) {
  295. const strategy = this.strategies[i];
  296. if (!strategy) continue;
  297. if (this.domainKeywords.size) {
  298. strategy.writeDomainKeywords(this.domainKeywords);
  299. }
  300. if (this.domainWildcard.size) {
  301. strategy.writeDomainWildcards(this.domainWildcard);
  302. }
  303. if (this.userAgent.size) {
  304. strategy.writeUserAgents(this.userAgent);
  305. }
  306. if (this.processName.size) {
  307. strategy.writeProcessNames(this.processName);
  308. }
  309. if (this.processPath.size) {
  310. strategy.writeProcessPaths(this.processPath);
  311. }
  312. }
  313. if (this.sourceIpOrCidr.size) {
  314. const sourceIpOrCidr = Array.from(this.sourceIpOrCidr);
  315. for (let i = 0, len = this.strategies.length; i < len; i++) {
  316. const strategy = this.strategies[i];
  317. if (strategy) {
  318. strategy.writeSourceIpCidrs(sourceIpOrCidr);
  319. }
  320. }
  321. }
  322. for (let i = 0, len = this.strategies.length; i < len; i++) {
  323. const strategy = this.strategies[i];
  324. if (strategy) {
  325. if (this.sourcePort.size) {
  326. strategy.writeSourcePorts(this.sourcePort);
  327. }
  328. if (this.destPort.size) {
  329. strategy.writeDestinationPorts(this.destPort);
  330. }
  331. if (this.otherRules.length) {
  332. strategy.writeOtherRules(this.otherRules);
  333. }
  334. if (this.urlRegex.size) {
  335. strategy.writeUrlRegexes(this.urlRegex);
  336. }
  337. }
  338. }
  339. let ipcidr: string[] | null = null;
  340. let ipcidrNoResolve: string[] | null = null;
  341. let ipcidr6: string[] | null = null;
  342. let ipcidr6NoResolve: string[] | null = null;
  343. if (this.ipcidr.size) {
  344. ipcidr = mergeCidr(Array.from(this.ipcidr), true);
  345. }
  346. if (this.ipcidrNoResolve.size) {
  347. ipcidrNoResolve = mergeCidr(Array.from(this.ipcidrNoResolve), true);
  348. }
  349. if (this.ipcidr6.size) {
  350. ipcidr6 = Array.from(this.ipcidr6);
  351. }
  352. if (this.ipcidr6NoResolve.size) {
  353. ipcidr6NoResolve = Array.from(this.ipcidr6NoResolve);
  354. }
  355. for (let i = 0, len = this.strategies.length; i < len; i++) {
  356. const strategy = this.strategies[i];
  357. if (strategy) {
  358. // no-resolve
  359. if (ipcidrNoResolve?.length) {
  360. strategy.writeIpCidrs(ipcidrNoResolve, true);
  361. }
  362. if (ipcidr6NoResolve?.length) {
  363. strategy.writeIpCidr6s(ipcidr6NoResolve, true);
  364. }
  365. if (this.ipasnNoResolve.size) {
  366. strategy.writeIpAsns(this.ipasnNoResolve, true);
  367. }
  368. if (this.groipNoResolve.size) {
  369. strategy.writeGeoip(this.groipNoResolve, true);
  370. }
  371. // triggers DNS resolution
  372. if (ipcidr?.length) {
  373. strategy.writeIpCidrs(ipcidr, false);
  374. }
  375. if (ipcidr6?.length) {
  376. strategy.writeIpCidr6s(ipcidr6, false);
  377. }
  378. if (this.ipasn.size) {
  379. strategy.writeIpAsns(this.ipasn, false);
  380. }
  381. if (this.geoip.size) {
  382. strategy.writeGeoip(this.geoip, false);
  383. }
  384. }
  385. }
  386. }
  387. write(): Promise<unknown> {
  388. return this.span.traceChildAsync('write all', async (childSpan) => {
  389. await this.done();
  390. childSpan.traceChildSync('write to strategies', this.writeToStrategies.bind(this));
  391. return childSpan.traceChildAsync('output to disk', (childSpan) => {
  392. const promises: Array<Promise<void> | void> = [];
  393. for (let i = 0, len = this.strategies.length; i < len; i++) {
  394. const strategy = this.strategies[i];
  395. if (strategy) {
  396. const basename = (strategy.overwriteFilename || this.id) + '.' + strategy.fileExtension;
  397. promises.push(
  398. childSpan.traceChildAsync('write ' + strategy.name, (childSpan) => Promise.resolve(strategy.output(
  399. childSpan,
  400. nullthrow(this.title, 'Missing title'),
  401. nullthrow(this.description, 'Missing description'),
  402. this.date,
  403. path.join(
  404. strategy.outputDir,
  405. strategy.type
  406. ? path.join(strategy.type, basename)
  407. : basename
  408. )
  409. )))
  410. );
  411. }
  412. }
  413. return Promise.all(promises);
  414. });
  415. });
  416. }
  417. async compile(): Promise<Array<string[] | null>> {
  418. await this.done();
  419. this.writeToStrategies();
  420. return this.strategies.reduce<Array<string[] | null>>((acc, strategy) => {
  421. if (strategy) {
  422. acc.push(strategy.content);
  423. } else {
  424. acc.push(null);
  425. }
  426. return acc;
  427. }, []);
  428. }
  429. withMitmSgmodulePath(moduleName: string | null) {
  430. if (moduleName) {
  431. this.withExtraStrategies(new SurgeMitmSgmodule(moduleName));
  432. }
  433. return this;
  434. }
  435. }