base.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. import type { Span } from '../../trace';
  2. import { HostnameSmolTrie } from '../trie';
  3. import { invariant, not } from 'foxts/guard';
  4. import picocolors from 'picocolors';
  5. import fs from 'node:fs';
  6. import { writeFile } from '../misc';
  7. import type { MaybePromise } from '../misc';
  8. import { fastStringArrayJoin } from 'foxts/fast-string-array-join';
  9. import { readFileByLine } from '../fetch-text-by-line';
  10. import { asyncWriteToStream } from 'foxts/async-write-to-stream';
  11. import type { BaseWriteStrategy } from '../writing-strategy/base';
  12. import { merge as mergeCidr } from 'fast-cidr-tools';
  13. import { createRetrieKeywordFilter as createKeywordFilter } from 'foxts/retrie';
  14. import path from 'node:path';
  15. import { SurgeMitmSgmodule } from '../writing-strategy/surge';
  16. /**
  17. * Holds the universal rule data (domain, ip, url-regex, etc. etc.)
  18. * This class is not about format, instead it will call the class that does
  19. */
  20. export class FileOutput {
  21. protected strategies: Array<BaseWriteStrategy | false> = [];
  22. public domainTrie = new HostnameSmolTrie(null);
  23. protected domainKeywords = new Set<string>();
  24. protected domainWildcard = new Set<string>();
  25. protected userAgent = new Set<string>();
  26. protected processName = new Set<string>();
  27. protected processPath = new Set<string>();
  28. protected urlRegex = new Set<string>();
  29. protected ipcidr = new Set<string>();
  30. protected ipcidrNoResolve = new Set<string>();
  31. protected ipasn = new Set<string>();
  32. protected ipasnNoResolve = new Set<string>();
  33. protected ipcidr6 = new Set<string>();
  34. protected ipcidr6NoResolve = new Set<string>();
  35. protected geoip = new Set<string>();
  36. protected groipNoResolve = new Set<string>();
  37. protected sourceIpOrCidr = new Set<string>();
  38. protected sourcePort = new Set<string>();
  39. protected destPort = new Set<string>();
  40. protected otherRules: string[] = [];
  41. private pendingPromise: Promise<any> | null = null;
  42. whitelistDomain = (domain: string) => {
  43. this.domainTrie.whitelist(domain);
  44. return this;
  45. };
  46. protected readonly span: Span;
  47. constructor($span: Span, protected readonly id: string) {
  48. this.span = $span.traceChild('RuleOutput#' + id);
  49. }
  50. protected title: string | null = null;
  51. withTitle(title: string) {
  52. this.title = title;
  53. return this;
  54. }
  55. public withStrategies(strategies: Array<BaseWriteStrategy | false>) {
  56. this.strategies = strategies;
  57. return this;
  58. }
  59. withExtraStrategies(strategy: BaseWriteStrategy | false) {
  60. if (strategy) {
  61. this.strategies.push(strategy);
  62. }
  63. }
  64. protected description: string[] | readonly string[] | null = null;
  65. withDescription(description: string[] | readonly string[]) {
  66. this.description = description;
  67. return this;
  68. }
  69. protected date = new Date();
  70. withDate(date: Date) {
  71. this.date = date;
  72. return this;
  73. }
  74. addDomain(domain: string) {
  75. this.domainTrie.add(domain);
  76. return this;
  77. }
  78. bulkAddDomain(domains: Array<string | null>) {
  79. let d: string | null;
  80. for (let i = 0, len = domains.length; i < len; i++) {
  81. d = domains[i];
  82. if (d !== null) {
  83. this.domainTrie.add(d, false, null, 0);
  84. }
  85. }
  86. return this;
  87. }
  88. addDomainSuffix(domain: string, lineFromDot = domain[0] === '.') {
  89. this.domainTrie.add(domain, true, lineFromDot ? 1 : 0);
  90. return this;
  91. }
  92. bulkAddDomainSuffix(domains: string[]) {
  93. for (let i = 0, len = domains.length; i < len; i++) {
  94. this.addDomainSuffix(domains[i]);
  95. }
  96. return this;
  97. }
  98. addDomainKeyword(keyword: string) {
  99. this.domainKeywords.add(keyword);
  100. return this;
  101. }
  102. addIPASN(asn: string) {
  103. this.ipasn.add(asn);
  104. return this;
  105. }
  106. bulkAddIPASN(asns: string[]) {
  107. for (let i = 0, len = asns.length; i < len; i++) {
  108. this.ipasn.add(asns[i]);
  109. }
  110. return this;
  111. }
  112. private async addFromDomainsetPromise(source: AsyncIterable<string> | Iterable<string> | string[]) {
  113. for await (const line of source) {
  114. if (line[0] === '.') {
  115. this.addDomainSuffix(line, true);
  116. } else {
  117. this.domainTrie.add(line, false, null, 0);
  118. }
  119. }
  120. }
  121. addFromDomainset(source: MaybePromise<AsyncIterable<string> | Iterable<string> | string[]>) {
  122. if (this.pendingPromise) {
  123. if ('then' in source) {
  124. this.pendingPromise = this.pendingPromise.then(() => source).then(src => this.addFromDomainsetPromise(src));
  125. return this;
  126. }
  127. this.pendingPromise = this.pendingPromise.then(() => this.addFromDomainsetPromise(source));
  128. return this;
  129. }
  130. if ('then' in source) {
  131. this.pendingPromise = source.then(src => this.addFromDomainsetPromise(src));
  132. return this;
  133. }
  134. this.pendingPromise = this.addFromDomainsetPromise(source);
  135. return this;
  136. }
  137. private async addFromRulesetPromise(source: AsyncIterable<string> | Iterable<string> | string[]) {
  138. for await (const line of source) {
  139. const splitted = line.split(',');
  140. const type = splitted[0];
  141. const value = splitted[1];
  142. const arg = splitted[2];
  143. switch (type) {
  144. case 'DOMAIN':
  145. this.domainTrie.add(value, false, null, 0);
  146. break;
  147. case 'DOMAIN-SUFFIX':
  148. this.addDomainSuffix(value, false);
  149. break;
  150. case 'DOMAIN-KEYWORD':
  151. this.addDomainKeyword(value);
  152. break;
  153. case 'DOMAIN-WILDCARD':
  154. this.domainWildcard.add(value);
  155. break;
  156. case 'USER-AGENT':
  157. this.userAgent.add(value);
  158. break;
  159. case 'PROCESS-NAME':
  160. if (value.includes('/') || value.includes('\\')) {
  161. this.processPath.add(value);
  162. } else {
  163. this.processName.add(value);
  164. }
  165. break;
  166. case 'URL-REGEX': {
  167. const [, ...rest] = splitted;
  168. this.urlRegex.add(rest.join(','));
  169. break;
  170. }
  171. case 'IP-CIDR':
  172. (arg === 'no-resolve' ? this.ipcidrNoResolve : this.ipcidr).add(value);
  173. break;
  174. case 'IP-CIDR6':
  175. (arg === 'no-resolve' ? this.ipcidr6NoResolve : this.ipcidr6).add(value);
  176. break;
  177. case 'IP-ASN':
  178. (arg === 'no-resolve' ? this.ipasnNoResolve : this.ipasn).add(value);
  179. break;
  180. case 'GEOIP':
  181. (arg === 'no-resolve' ? this.groipNoResolve : this.geoip).add(value);
  182. break;
  183. case 'SRC-IP':
  184. this.sourceIpOrCidr.add(value);
  185. break;
  186. case 'SRC-PORT':
  187. this.sourcePort.add(value);
  188. break;
  189. case 'DEST-PORT':
  190. this.destPort.add(value);
  191. break;
  192. default:
  193. this.otherRules.push(line);
  194. break;
  195. }
  196. }
  197. }
  198. addFromRuleset(source: MaybePromise<AsyncIterable<string> | Iterable<string>>) {
  199. if (this.pendingPromise) {
  200. if ('then' in source) {
  201. this.pendingPromise = this.pendingPromise.then(() => source).then(src => this.addFromRulesetPromise(src));
  202. return this;
  203. }
  204. this.pendingPromise = this.pendingPromise.then(() => this.addFromRulesetPromise(source));
  205. return this;
  206. }
  207. if ('then' in source) {
  208. this.pendingPromise = source.then(src => this.addFromRulesetPromise(src));
  209. return this;
  210. }
  211. this.pendingPromise = this.addFromRulesetPromise(source);
  212. return this;
  213. }
  214. static readonly ipToCidr = (ip: string, version: 4 | 6) => {
  215. if (ip.includes('/')) return ip;
  216. if (version === 4) {
  217. return ip + '/32';
  218. }
  219. return ip + '/128';
  220. };
  221. bulkAddCIDR4(cidrs: string[]) {
  222. for (let i = 0, len = cidrs.length; i < len; i++) {
  223. this.ipcidr.add(FileOutput.ipToCidr(cidrs[i], 4));
  224. }
  225. return this;
  226. }
  227. bulkAddCIDR4NoResolve(cidrs: string[]) {
  228. for (let i = 0, len = cidrs.length; i < len; i++) {
  229. this.ipcidrNoResolve.add(FileOutput.ipToCidr(cidrs[i], 4));
  230. }
  231. return this;
  232. }
  233. bulkAddCIDR6(cidrs: string[]) {
  234. for (let i = 0, len = cidrs.length; i < len; i++) {
  235. this.ipcidr6.add(FileOutput.ipToCidr(cidrs[i], 6));
  236. }
  237. return this;
  238. }
  239. bulkAddCIDR6NoResolve(cidrs: string[]) {
  240. for (let i = 0, len = cidrs.length; i < len; i++) {
  241. this.ipcidr6NoResolve.add(FileOutput.ipToCidr(cidrs[i], 6));
  242. }
  243. return this;
  244. }
  245. async done() {
  246. await this.pendingPromise;
  247. this.pendingPromise = null;
  248. return this;
  249. }
  250. // private guardPendingPromise() {
  251. // // reverse invariant
  252. // if (this.pendingPromise !== null) {
  253. // console.trace('Pending promise:', this.pendingPromise);
  254. // throw new Error('You should call done() before calling this method');
  255. // }
  256. // }
  257. // async writeClash(outputDir?: null | string) {
  258. // await this.done();
  259. // invariant(this.title, 'Missing title');
  260. // invariant(this.description, 'Missing description');
  261. // return compareAndWriteFile(
  262. // this.span,
  263. // withBannerArray(
  264. // this.title,
  265. // this.description,
  266. // this.date,
  267. // this.clash()
  268. // ),
  269. // path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  270. // );
  271. // }
  272. private strategiesWritten = false;
  273. private writeToStrategies() {
  274. if (this.pendingPromise) {
  275. throw new Error('You should call done() before calling writeToStrategies()');
  276. }
  277. if (this.strategiesWritten) {
  278. throw new Error('Strategies already written');
  279. }
  280. this.strategiesWritten = true;
  281. const kwfilter = createKeywordFilter(Array.from(this.domainKeywords));
  282. if (this.strategies.filter(not(false)).length === 0) {
  283. throw new Error('No strategies to write ' + this.id);
  284. }
  285. this.domainTrie.dumpWithoutDot((domain, includeAllSubdomain) => {
  286. if (kwfilter(domain)) {
  287. return;
  288. }
  289. for (let i = 0, len = this.strategies.length; i < len; i++) {
  290. const strategy = this.strategies[i];
  291. if (strategy) {
  292. if (includeAllSubdomain) {
  293. strategy.writeDomainSuffix(domain);
  294. } else {
  295. strategy.writeDomain(domain);
  296. }
  297. }
  298. }
  299. }, true);
  300. for (let i = 0, len = this.strategies.length; i < len; i++) {
  301. const strategy = this.strategies[i];
  302. if (!strategy) continue;
  303. if (this.domainKeywords.size) {
  304. strategy.writeDomainKeywords(this.domainKeywords);
  305. }
  306. if (this.domainWildcard.size) {
  307. strategy.writeDomainWildcards(this.domainWildcard);
  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. const strategy = this.strategies[i];
  323. if (strategy) {
  324. strategy.writeSourceIpCidrs(sourceIpOrCidr);
  325. }
  326. }
  327. }
  328. for (let i = 0, len = this.strategies.length; i < len; i++) {
  329. const strategy = this.strategies[i];
  330. if (strategy) {
  331. if (this.sourcePort.size) {
  332. strategy.writeSourcePorts(this.sourcePort);
  333. }
  334. if (this.destPort.size) {
  335. strategy.writeDestinationPorts(this.destPort);
  336. }
  337. if (this.otherRules.length) {
  338. strategy.writeOtherRules(this.otherRules);
  339. }
  340. if (this.urlRegex.size) {
  341. strategy.writeUrlRegexes(this.urlRegex);
  342. }
  343. }
  344. }
  345. let ipcidr: string[] | null = null;
  346. let ipcidrNoResolve: string[] | null = null;
  347. let ipcidr6: string[] | null = null;
  348. let ipcidr6NoResolve: string[] | null = null;
  349. if (this.ipcidr.size) {
  350. ipcidr = mergeCidr(Array.from(this.ipcidr), true);
  351. }
  352. if (this.ipcidrNoResolve.size) {
  353. ipcidrNoResolve = mergeCidr(Array.from(this.ipcidrNoResolve), true);
  354. }
  355. if (this.ipcidr6.size) {
  356. ipcidr6 = Array.from(this.ipcidr6);
  357. }
  358. if (this.ipcidr6NoResolve.size) {
  359. ipcidr6NoResolve = Array.from(this.ipcidr6NoResolve);
  360. }
  361. for (let i = 0, len = this.strategies.length; i < len; i++) {
  362. const strategy = this.strategies[i];
  363. if (strategy) {
  364. // no-resolve
  365. if (ipcidrNoResolve?.length) {
  366. strategy.writeIpCidrs(ipcidrNoResolve, true);
  367. }
  368. if (ipcidr6NoResolve?.length) {
  369. strategy.writeIpCidr6s(ipcidr6NoResolve, true);
  370. }
  371. if (this.ipasnNoResolve.size) {
  372. strategy.writeIpAsns(this.ipasnNoResolve, true);
  373. }
  374. if (this.groipNoResolve.size) {
  375. strategy.writeGeoip(this.groipNoResolve, true);
  376. }
  377. // triggers DNS resolution
  378. if (ipcidr?.length) {
  379. strategy.writeIpCidrs(ipcidr, false);
  380. }
  381. if (ipcidr6?.length) {
  382. strategy.writeIpCidr6s(ipcidr6, false);
  383. }
  384. if (this.ipasn.size) {
  385. strategy.writeIpAsns(this.ipasn, false);
  386. }
  387. if (this.geoip.size) {
  388. strategy.writeGeoip(this.geoip, false);
  389. }
  390. }
  391. }
  392. }
  393. write(): Promise<unknown> {
  394. return this.span.traceChildAsync('write all', async (childSpan) => {
  395. await this.done();
  396. childSpan.traceChildSync('write to strategies', this.writeToStrategies.bind(this));
  397. return childSpan.traceChildAsync('output to disk', (childSpan) => {
  398. const promises: Array<Promise<void> | void> = [];
  399. invariant(this.title, 'Missing title');
  400. invariant(this.description, 'Missing description');
  401. for (let i = 0, len = this.strategies.length; i < len; i++) {
  402. const strategy = this.strategies[i];
  403. if (strategy) {
  404. const basename = (strategy.overwriteFilename || this.id) + '.' + strategy.fileExtension;
  405. promises.push(strategy.output(
  406. childSpan,
  407. this.title,
  408. this.description,
  409. this.date,
  410. path.join(
  411. strategy.outputDir,
  412. strategy.type
  413. ? path.join(strategy.type, basename)
  414. : basename
  415. )
  416. ));
  417. }
  418. }
  419. return Promise.all(promises);
  420. });
  421. });
  422. }
  423. async compile(): Promise<Array<string[] | null>> {
  424. await this.done();
  425. this.writeToStrategies();
  426. return this.strategies.reduce<Array<string[] | null>>((acc, strategy) => {
  427. if (strategy) {
  428. acc.push(strategy.content);
  429. } else {
  430. acc.push(null);
  431. }
  432. return acc;
  433. }, []);
  434. }
  435. withMitmSgmodulePath(moduleName: string | null) {
  436. if (moduleName) {
  437. this.withExtraStrategies(new SurgeMitmSgmodule(moduleName));
  438. }
  439. return this;
  440. }
  441. }
  442. export async function fileEqual(linesA: string[], source: AsyncIterable<string> | Iterable<string>): Promise<boolean> {
  443. if (linesA.length === 0) {
  444. return false;
  445. }
  446. const linesABound = linesA.length - 1;
  447. let index = -1;
  448. for await (const lineB of source) {
  449. index++;
  450. if (index > linesABound) {
  451. return (index === linesA.length && lineB.length === 0);
  452. }
  453. const lineA = linesA[index];
  454. if (lineA.length === 0) {
  455. if (lineB.length === 0) {
  456. // both lines are empty, check next line
  457. continue;
  458. }
  459. // lineA is empty but lineB is not
  460. return false;
  461. }
  462. // now lineA can not be empty
  463. if (lineB.length === 0) {
  464. // lineB is empty but lineA is not
  465. return false;
  466. }
  467. // now both lines can not be empty
  468. const firstCharA = lineA.charCodeAt(0);
  469. const firstCharB = lineB.charCodeAt(0);
  470. if (firstCharA !== firstCharB) {
  471. return false;
  472. }
  473. // now firstCharA is equal to firstCharB, we only need to check the first char
  474. if (firstCharA === 35 /* # */) {
  475. continue;
  476. }
  477. // adguard conf
  478. if (firstCharA === 33 /* ! */) {
  479. continue;
  480. }
  481. if (
  482. firstCharA === 47 /* / */
  483. && lineA[1] === '/' && lineB[1] === '/'
  484. && lineA[3] === '#' && lineB[3] === '#'
  485. ) {
  486. continue;
  487. }
  488. if (lineA !== lineB) {
  489. return false;
  490. }
  491. }
  492. // The file becomes larger
  493. return !(index < linesABound);
  494. }
  495. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  496. const linesALen = linesA.length;
  497. const isEqual = await span.traceChildAsync(`compare ${filePath}`, async () => {
  498. if (fs.existsSync(filePath)) {
  499. return fileEqual(linesA, readFileByLine(filePath));
  500. }
  501. console.log(`${filePath} does not exists, writing...`);
  502. return false;
  503. });
  504. if (isEqual) {
  505. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  506. return;
  507. }
  508. await span.traceChildAsync(`writing ${filePath}`, async () => {
  509. // The default highwater mark is normally 16384,
  510. // So we make sure direct write to file if the content is
  511. // most likely less than 500 lines
  512. if (linesALen < 500) {
  513. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  514. }
  515. const writeStream = fs.createWriteStream(filePath);
  516. for (let i = 0; i < linesALen; i++) {
  517. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  518. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  519. if (p) await p;
  520. }
  521. writeStream.end();
  522. });
  523. }