base.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 { fastStringArrayJoin } from 'foxts/fast-string-array-join';
  8. import { readFileByLine } from '../fetch-text-by-line';
  9. import { asyncWriteToStream } from 'foxts/async-write-to-stream';
  10. import type { BaseWriteStrategy } from '../writing-strategy/base';
  11. import { merge } from 'fast-cidr-tools';
  12. import { createRetrieKeywordFilter as createKeywordFilter } from 'foxts/retrie';
  13. import path from 'node:path';
  14. import { SurgeMitmSgmodule } from '../writing-strategy/surge';
  15. export class FileOutput {
  16. protected strategies: Array<BaseWriteStrategy | false> = [];
  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 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, 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: AsyncIterable<string> | Iterable<string> | string[]) {
  108. for await (const line of 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: AsyncIterable<string> | Iterable<string> | string[]) {
  117. this.pendingPromise = (this.pendingPromise ||= Promise.resolve()).then(() => this.addFromDomainsetPromise(source));
  118. return this;
  119. }
  120. private async addFromRulesetPromise(source: AsyncIterable<string> | Iterable<string>) {
  121. for await (const line of source) {
  122. const splitted = line.split(',');
  123. const type = splitted[0];
  124. const value = splitted[1];
  125. const arg = splitted[2];
  126. switch (type) {
  127. case 'DOMAIN':
  128. this.domainTrie.add(value, false, null, 0);
  129. break;
  130. case 'DOMAIN-SUFFIX':
  131. this.addDomainSuffix(value, false);
  132. break;
  133. case 'DOMAIN-KEYWORD':
  134. this.addDomainKeyword(value);
  135. break;
  136. case 'DOMAIN-WILDCARD':
  137. this.domainWildcard.add(value);
  138. break;
  139. case 'USER-AGENT':
  140. this.userAgent.add(value);
  141. break;
  142. case 'PROCESS-NAME':
  143. if (value.includes('/') || value.includes('\\')) {
  144. this.processPath.add(value);
  145. } else {
  146. this.processName.add(value);
  147. }
  148. break;
  149. case 'URL-REGEX': {
  150. const [, ...rest] = splitted;
  151. this.urlRegex.add(rest.join(','));
  152. break;
  153. }
  154. case 'IP-CIDR':
  155. (arg === 'no-resolve' ? this.ipcidrNoResolve : this.ipcidr).add(value);
  156. break;
  157. case 'IP-CIDR6':
  158. (arg === 'no-resolve' ? this.ipcidr6NoResolve : this.ipcidr6).add(value);
  159. break;
  160. case 'IP-ASN':
  161. (arg === 'no-resolve' ? this.ipasnNoResolve : this.ipasn).add(value);
  162. break;
  163. case 'GEOIP':
  164. (arg === 'no-resolve' ? this.groipNoResolve : this.geoip).add(value);
  165. break;
  166. case 'SRC-IP':
  167. this.sourceIpOrCidr.add(value);
  168. break;
  169. case 'SRC-PORT':
  170. this.sourcePort.add(value);
  171. break;
  172. case 'DEST-PORT':
  173. this.destPort.add(value);
  174. break;
  175. default:
  176. this.otherRules.push(line);
  177. break;
  178. }
  179. }
  180. }
  181. addFromRuleset(source: AsyncIterable<string> | Iterable<string> | Promise<Iterable<string>>) {
  182. if (this.pendingPromise) {
  183. this.pendingPromise = this.pendingPromise.then(() => source);
  184. } else {
  185. this.pendingPromise = Promise.resolve(source);
  186. }
  187. this.pendingPromise = this.pendingPromise.then((source) => this.addFromRulesetPromise(source));
  188. return this;
  189. }
  190. static readonly ipToCidr = (ip: string, version: 4 | 6) => {
  191. if (ip.includes('/')) return ip;
  192. if (version === 4) {
  193. return ip + '/32';
  194. }
  195. return ip + '/128';
  196. };
  197. bulkAddCIDR4(cidrs: string[]) {
  198. for (let i = 0, len = cidrs.length; i < len; i++) {
  199. this.ipcidr.add(FileOutput.ipToCidr(cidrs[i], 4));
  200. }
  201. return this;
  202. }
  203. bulkAddCIDR4NoResolve(cidrs: string[]) {
  204. for (let i = 0, len = cidrs.length; i < len; i++) {
  205. this.ipcidrNoResolve.add(FileOutput.ipToCidr(cidrs[i], 4));
  206. }
  207. return this;
  208. }
  209. bulkAddCIDR6(cidrs: string[]) {
  210. for (let i = 0, len = cidrs.length; i < len; i++) {
  211. this.ipcidr6.add(FileOutput.ipToCidr(cidrs[i], 6));
  212. }
  213. return this;
  214. }
  215. bulkAddCIDR6NoResolve(cidrs: string[]) {
  216. for (let i = 0, len = cidrs.length; i < len; i++) {
  217. this.ipcidr6NoResolve.add(FileOutput.ipToCidr(cidrs[i], 6));
  218. }
  219. return this;
  220. }
  221. async done() {
  222. await this.pendingPromise;
  223. this.pendingPromise = null;
  224. return this;
  225. }
  226. // private guardPendingPromise() {
  227. // // reverse invariant
  228. // if (this.pendingPromise !== null) {
  229. // console.trace('Pending promise:', this.pendingPromise);
  230. // throw new Error('You should call done() before calling this method');
  231. // }
  232. // }
  233. // async writeClash(outputDir?: null | string) {
  234. // await this.done();
  235. // invariant(this.title, 'Missing title');
  236. // invariant(this.description, 'Missing description');
  237. // return compareAndWriteFile(
  238. // this.span,
  239. // withBannerArray(
  240. // this.title,
  241. // this.description,
  242. // this.date,
  243. // this.clash()
  244. // ),
  245. // path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  246. // );
  247. // }
  248. private strategiesWritten = false;
  249. private async writeToStrategies() {
  250. if (this.strategiesWritten) {
  251. throw new Error('Strategies already written');
  252. }
  253. this.strategiesWritten = true;
  254. await this.done();
  255. const kwfilter = createKeywordFilter(Array.from(this.domainKeywords));
  256. if (this.strategies.filter(not(false)).length === 0) {
  257. throw new Error('No strategies to write ' + this.id);
  258. }
  259. this.domainTrie.dumpWithoutDot((domain, includeAllSubdomain) => {
  260. if (kwfilter(domain)) {
  261. return;
  262. }
  263. for (let i = 0, len = this.strategies.length; i < len; i++) {
  264. const strategy = this.strategies[i];
  265. if (strategy) {
  266. if (includeAllSubdomain) {
  267. strategy.writeDomainSuffix(domain);
  268. } else {
  269. strategy.writeDomain(domain);
  270. }
  271. }
  272. }
  273. }, true);
  274. for (let i = 0, len = this.strategies.length; i < len; i++) {
  275. const strategy = this.strategies[i];
  276. if (!strategy) continue;
  277. if (this.domainKeywords.size) {
  278. strategy.writeDomainKeywords(this.domainKeywords);
  279. }
  280. if (this.domainWildcard.size) {
  281. strategy.writeDomainWildcards(this.domainWildcard);
  282. }
  283. if (this.userAgent.size) {
  284. strategy.writeUserAgents(this.userAgent);
  285. }
  286. if (this.processName.size) {
  287. strategy.writeProcessNames(this.processName);
  288. }
  289. if (this.processPath.size) {
  290. strategy.writeProcessPaths(this.processPath);
  291. }
  292. }
  293. if (this.sourceIpOrCidr.size) {
  294. const sourceIpOrCidr = Array.from(this.sourceIpOrCidr);
  295. for (let i = 0, len = this.strategies.length; i < len; i++) {
  296. const strategy = this.strategies[i];
  297. if (strategy) {
  298. strategy.writeSourceIpCidrs(sourceIpOrCidr);
  299. }
  300. }
  301. }
  302. for (let i = 0, len = this.strategies.length; i < len; i++) {
  303. const strategy = this.strategies[i];
  304. if (strategy) {
  305. if (this.sourcePort.size) {
  306. strategy.writeSourcePorts(this.sourcePort);
  307. }
  308. if (this.destPort.size) {
  309. strategy.writeDestinationPorts(this.destPort);
  310. }
  311. if (this.otherRules.length) {
  312. strategy.writeOtherRules(this.otherRules);
  313. }
  314. if (this.urlRegex.size) {
  315. strategy.writeUrlRegexes(this.urlRegex);
  316. }
  317. }
  318. }
  319. let ipcidr: string[] | null = null;
  320. let ipcidrNoResolve: string[] | null = null;
  321. let ipcidr6: string[] | null = null;
  322. let ipcidr6NoResolve: string[] | null = null;
  323. if (this.ipcidr.size) {
  324. ipcidr = merge(Array.from(this.ipcidr), true);
  325. }
  326. if (this.ipcidrNoResolve.size) {
  327. ipcidrNoResolve = merge(Array.from(this.ipcidrNoResolve), true);
  328. }
  329. if (this.ipcidr6.size) {
  330. ipcidr6 = Array.from(this.ipcidr6);
  331. }
  332. if (this.ipcidr6NoResolve.size) {
  333. ipcidr6NoResolve = Array.from(this.ipcidr6NoResolve);
  334. }
  335. for (let i = 0, len = this.strategies.length; i < len; i++) {
  336. const strategy = this.strategies[i];
  337. if (strategy) {
  338. // no-resolve
  339. if (ipcidrNoResolve?.length) {
  340. strategy.writeIpCidrs(ipcidrNoResolve, true);
  341. }
  342. if (ipcidr6NoResolve?.length) {
  343. strategy.writeIpCidr6s(ipcidr6NoResolve, true);
  344. }
  345. if (this.ipasnNoResolve.size) {
  346. strategy.writeIpAsns(this.ipasnNoResolve, true);
  347. }
  348. if (this.groipNoResolve.size) {
  349. strategy.writeGeoip(this.groipNoResolve, true);
  350. }
  351. // triggers DNS resolution
  352. if (ipcidr?.length) {
  353. strategy.writeIpCidrs(ipcidr, false);
  354. }
  355. if (ipcidr6?.length) {
  356. strategy.writeIpCidr6s(ipcidr6, false);
  357. }
  358. if (this.ipasn.size) {
  359. strategy.writeIpAsns(this.ipasn, false);
  360. }
  361. if (this.geoip.size) {
  362. strategy.writeGeoip(this.geoip, false);
  363. }
  364. }
  365. }
  366. }
  367. write(): Promise<void> {
  368. return this.span.traceChildAsync('write all', async () => {
  369. const promises: Array<Promise<void> | void> = [];
  370. await this.writeToStrategies();
  371. invariant(this.title, 'Missing title');
  372. invariant(this.description, 'Missing description');
  373. for (let i = 0, len = this.strategies.length; i < len; i++) {
  374. const strategy = this.strategies[i];
  375. if (strategy) {
  376. const basename = (strategy.overwriteFilename || this.id) + '.' + strategy.fileExtension;
  377. promises.push(strategy.output(
  378. this.span,
  379. this.title,
  380. this.description,
  381. this.date,
  382. strategy.type
  383. ? path.join(strategy.type, basename)
  384. : basename
  385. ));
  386. }
  387. }
  388. await Promise.all(promises);
  389. });
  390. }
  391. async compile(): Promise<Array<string[] | null>> {
  392. await this.writeToStrategies();
  393. return this.strategies.reduce<Array<string[] | null>>((acc, strategy) => {
  394. if (strategy) {
  395. acc.push(strategy.content);
  396. } else {
  397. acc.push(null);
  398. }
  399. return acc;
  400. }, []);
  401. }
  402. withMitmSgmodulePath(moduleName: string | null) {
  403. if (moduleName) {
  404. this.withExtraStrategies(new SurgeMitmSgmodule(moduleName));
  405. }
  406. return this;
  407. }
  408. }
  409. export async function fileEqual(linesA: string[], source: AsyncIterable<string> | Iterable<string>): Promise<boolean> {
  410. if (linesA.length === 0) {
  411. return false;
  412. }
  413. const linesABound = linesA.length - 1;
  414. let index = -1;
  415. for await (const lineB of source) {
  416. index++;
  417. if (index > linesABound) {
  418. return (index === linesA.length && lineB.length === 0);
  419. }
  420. const lineA = linesA[index];
  421. if (lineA.length === 0 && lineB.length === 0) {
  422. continue;
  423. }
  424. // not both line are empty
  425. if (lineA.length === 0 || lineB.length === 0) {
  426. return false;
  427. }
  428. const firstCharA = lineA.charCodeAt(0);
  429. const firstCharB = lineB.charCodeAt(0);
  430. if (firstCharA !== firstCharB) {
  431. return false;
  432. }
  433. if (firstCharA === 35 /* # */ && firstCharB === 35 /* # */) {
  434. continue;
  435. }
  436. // adguard conf
  437. if (firstCharA === 33 /* ! */ && firstCharB === 33 /* ! */) {
  438. continue;
  439. }
  440. if (
  441. firstCharA === 47 /* / */ && firstCharB === 47 /* / */
  442. && lineA[1] === '/' && lineB[1] === '/'
  443. && lineA[3] === '#' && lineB[3] === '#'
  444. ) {
  445. continue;
  446. }
  447. if (lineA !== lineB) {
  448. return false;
  449. }
  450. }
  451. // The file becomes larger
  452. return !(index < linesABound);
  453. }
  454. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  455. const linesALen = linesA.length;
  456. const isEqual = await span.traceChildAsync(`compare ${filePath}`, async () => {
  457. if (fs.existsSync(filePath)) {
  458. return fileEqual(linesA, readFileByLine(filePath));
  459. }
  460. console.log(`${filePath} does not exists, writing...`);
  461. return false;
  462. });
  463. if (isEqual) {
  464. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  465. return;
  466. }
  467. await span.traceChildAsync(`writing ${filePath}`, async () => {
  468. // The default highwater mark is normally 16384,
  469. // So we make sure direct write to file if the content is
  470. // most likely less than 500 lines
  471. if (linesALen < 500) {
  472. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  473. }
  474. const writeStream = fs.createWriteStream(filePath);
  475. for (let i = 0; i < linesALen; i++) {
  476. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  477. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  478. if (p) await p;
  479. }
  480. writeStream.end();
  481. });
  482. }