base.ts 13 KB

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