base.ts 14 KB

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