base.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. protected domainKeywords = new Set<string>();
  19. protected domainWildcard = new Set<string>();
  20. protected userAgent = new Set<string>();
  21. protected processName = new Set<string>();
  22. protected processPath = new Set<string>();
  23. protected urlRegex = new Set<string>();
  24. protected ipcidr = new Set<string>();
  25. protected ipcidrNoResolve = new Set<string>();
  26. protected ipasn = new Set<string>();
  27. protected ipasnNoResolve = new Set<string>();
  28. protected ipcidr6 = new Set<string>();
  29. protected ipcidr6NoResolve = new Set<string>();
  30. protected geoip = new Set<string>();
  31. protected groipNoResolve = new Set<string>();
  32. protected sourceIpOrCidr = new Set<string>();
  33. protected sourcePort = new Set<string>();
  34. protected destPort = new Set<string>();
  35. protected protocol = new Set<string>();
  36. protected otherRules: string[] = [];
  37. private pendingPromise: Promise<any> | null = null;
  38. whitelistDomain = (domain: string) => {
  39. this.domainTrie.whitelist(domain);
  40. return this;
  41. };
  42. protected readonly span: Span;
  43. constructor($span: Span, protected readonly id: string) {
  44. this.span = $span.traceChild('RuleOutput#' + id);
  45. }
  46. protected title: string | null = null;
  47. withTitle(title: string) {
  48. this.title = title;
  49. return this;
  50. }
  51. public withStrategies(strategies: BaseWriteStrategy[]) {
  52. this.strategies = strategies;
  53. return this;
  54. }
  55. withExtraStrategies(strategy: BaseWriteStrategy) {
  56. this.strategies.push(strategy);
  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. case 'PROTOCOL':
  179. this.protocol.add(value.toUpperCase());
  180. break;
  181. default:
  182. this.otherRules.push(line);
  183. break;
  184. }
  185. }
  186. }
  187. addFromRuleset(source: MaybePromise<AsyncIterable<string> | Iterable<string>>) {
  188. if (this.pendingPromise) {
  189. this.pendingPromise = this.pendingPromise.then(() => this.addFromRulesetPromise(source));
  190. return this;
  191. }
  192. this.pendingPromise = this.addFromRulesetPromise(source);
  193. return this;
  194. }
  195. static readonly ipToCidr = (ip: string, version: 4 | 6) => {
  196. if (ip.includes('/')) return ip;
  197. if (version === 4) {
  198. return ip + '/32';
  199. }
  200. return ip + '/128';
  201. };
  202. bulkAddAnyCIDR(cidrs: string[], noResolve = false) {
  203. const list4 = noResolve ? this.ipcidrNoResolve : this.ipcidr;
  204. const list6 = noResolve ? this.ipcidr6NoResolve : this.ipcidr6;
  205. for (let i = 0, len = cidrs.length; i < len; i++) {
  206. let cidr = cidrs[i];
  207. const version = fastIpVersion(cidr);
  208. if (version === 0) {
  209. continue; // skip invalid IPs
  210. }
  211. cidr = FileOutput.ipToCidr(cidr, version);
  212. if (version === 4) {
  213. list4.add(cidr);
  214. } else /* if (version === 6) */ {
  215. list6.add(cidr);
  216. }
  217. }
  218. return this;
  219. }
  220. bulkAddCIDR4(cidrs: string[]) {
  221. for (let i = 0, len = cidrs.length; i < len; i++) {
  222. this.ipcidr.add(FileOutput.ipToCidr(cidrs[i], 4));
  223. }
  224. return this;
  225. }
  226. bulkAddCIDR4NoResolve(cidrs: string[]) {
  227. for (let i = 0, len = cidrs.length; i < len; i++) {
  228. this.ipcidrNoResolve.add(FileOutput.ipToCidr(cidrs[i], 4));
  229. }
  230. return this;
  231. }
  232. bulkAddCIDR6(cidrs: string[]) {
  233. for (let i = 0, len = cidrs.length; i < len; i++) {
  234. this.ipcidr6.add(FileOutput.ipToCidr(cidrs[i], 6));
  235. }
  236. return this;
  237. }
  238. bulkAddCIDR6NoResolve(cidrs: string[]) {
  239. for (let i = 0, len = cidrs.length; i < len; i++) {
  240. this.ipcidr6NoResolve.add(FileOutput.ipToCidr(cidrs[i], 6));
  241. }
  242. return this;
  243. }
  244. async done() {
  245. await this.pendingPromise;
  246. this.pendingPromise = null;
  247. return this;
  248. }
  249. // private guardPendingPromise() {
  250. // // reverse invariant
  251. // if (this.pendingPromise !== null) {
  252. // console.trace('Pending promise:', this.pendingPromise);
  253. // throw new Error('You should call done() before calling this method');
  254. // }
  255. // }
  256. // async writeClash(outputDir?: null | string) {
  257. // await this.done();
  258. // invariant(this.title, 'Missing title');
  259. // invariant(this.description, 'Missing description');
  260. // return compareAndWriteFile(
  261. // this.span,
  262. // withBannerArray(
  263. // this.title,
  264. // this.description,
  265. // this.date,
  266. // this.clash()
  267. // ),
  268. // path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  269. // );
  270. // }
  271. private strategiesWritten = false;
  272. private writeToStrategies() {
  273. if (this.pendingPromise) {
  274. throw new Error('You should call done() before calling writeToStrategies()');
  275. }
  276. if (this.strategiesWritten) {
  277. throw new Error('Strategies already written');
  278. }
  279. this.strategiesWritten = true;
  280. const kwfilter = createKeywordFilter(Array.from(this.domainKeywords));
  281. if (this.strategies.filter(not(false)).length === 0) {
  282. throw new Error('No strategies to write ' + this.id);
  283. }
  284. const strategiesLen = this.strategies.length;
  285. this.domainTrie.dumpWithoutDot((domain, includeAllSubdomain) => {
  286. if (kwfilter(domain)) {
  287. return;
  288. }
  289. for (let i = 0; i < strategiesLen; i++) {
  290. const strategy = this.strategies[i];
  291. if (includeAllSubdomain) {
  292. strategy.writeDomainSuffix(domain);
  293. } else {
  294. strategy.writeDomain(domain);
  295. }
  296. }
  297. }, true);
  298. for (let i = 0, len = this.strategies.length; i < len; i++) {
  299. const strategy = this.strategies[i];
  300. if (this.domainKeywords.size) {
  301. strategy.writeDomainKeywords(this.domainKeywords);
  302. }
  303. if (this.domainWildcard.size) {
  304. strategy.writeDomainWildcards(this.domainWildcard);
  305. }
  306. if (this.protocol.size) {
  307. strategy.writeProtocols(this.protocol);
  308. }
  309. if (this.userAgent.size) {
  310. strategy.writeUserAgents(this.userAgent);
  311. }
  312. if (this.processName.size) {
  313. strategy.writeProcessNames(this.processName);
  314. }
  315. if (this.processPath.size) {
  316. strategy.writeProcessPaths(this.processPath);
  317. }
  318. }
  319. if (this.sourceIpOrCidr.size) {
  320. const sourceIpOrCidr = Array.from(this.sourceIpOrCidr);
  321. for (let i = 0, len = this.strategies.length; i < len; i++) {
  322. this.strategies[i].writeSourceIpCidrs(sourceIpOrCidr);
  323. }
  324. }
  325. for (let i = 0, len = this.strategies.length; i < len; i++) {
  326. const strategy = this.strategies[i];
  327. if (this.sourcePort.size) {
  328. strategy.writeSourcePorts(this.sourcePort);
  329. }
  330. if (this.destPort.size) {
  331. strategy.writeDestinationPorts(this.destPort);
  332. }
  333. if (this.otherRules.length) {
  334. strategy.writeOtherRules(this.otherRules);
  335. }
  336. if (this.urlRegex.size) {
  337. strategy.writeUrlRegexes(this.urlRegex);
  338. }
  339. }
  340. let ipcidr: string[] | null = null;
  341. let ipcidrNoResolve: string[] | null = null;
  342. let ipcidr6: string[] | null = null;
  343. let ipcidr6NoResolve: string[] | null = null;
  344. if (this.ipcidr.size) {
  345. ipcidr = mergeCidr(Array.from(this.ipcidr), true);
  346. }
  347. if (this.ipcidrNoResolve.size) {
  348. ipcidrNoResolve = mergeCidr(Array.from(this.ipcidrNoResolve), true);
  349. }
  350. if (this.ipcidr6.size) {
  351. ipcidr6 = Array.from(this.ipcidr6);
  352. }
  353. if (this.ipcidr6NoResolve.size) {
  354. ipcidr6NoResolve = Array.from(this.ipcidr6NoResolve);
  355. }
  356. for (let i = 0, len = this.strategies.length; i < len; i++) {
  357. const strategy = this.strategies[i];
  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. write(): Promise<unknown> {
  387. return this.span.traceChildAsync('write all', async (childSpan) => {
  388. await this.done();
  389. childSpan.traceChildSync('write to strategies', () => this.writeToStrategies());
  390. return childSpan.traceChildAsync('output to disk', (childSpan) => {
  391. const promises: Array<Promise<void> | void> = [];
  392. for (let i = 0, len = this.strategies.length; i < len; i++) {
  393. const strategy = this.strategies[i];
  394. const basename = (strategy.overwriteFilename || this.id) + '.' + strategy.fileExtension;
  395. promises.push(
  396. childSpan.traceChildAsync('write ' + strategy.name, (childSpan) => Promise.resolve(strategy.output(
  397. childSpan,
  398. nullthrow(this.title, 'Missing title'),
  399. nullthrow(this.description, 'Missing description'),
  400. this.date,
  401. path.join(
  402. strategy.outputDir,
  403. strategy.type
  404. ? path.join(strategy.type, basename)
  405. : basename
  406. )
  407. )))
  408. );
  409. }
  410. return Promise.all(promises);
  411. });
  412. });
  413. }
  414. async compile(): Promise<Array<string[] | null>> {
  415. await this.done();
  416. this.writeToStrategies();
  417. return this.strategies.reduce<Array<string[] | null>>((acc, strategy) => {
  418. acc.push(strategy.content);
  419. return acc;
  420. }, []);
  421. }
  422. withMitmSgmodulePath(moduleName: string | null) {
  423. if (moduleName) {
  424. this.withExtraStrategies(new SurgeMitmSgmodule(moduleName));
  425. }
  426. return this;
  427. }
  428. }