base.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { OUTPUT_CLASH_DIR, OUTPUT_MODULES_DIR, OUTPUT_SINGBOX_DIR, OUTPUT_SURGE_DIR } from '../../constants/dir';
  2. import type { Span } from '../../trace';
  3. import { createTrie } from '../trie';
  4. import stringify from 'json-stringify-pretty-compact';
  5. import path from 'node:path';
  6. import { withBannerArray } from '../misc';
  7. import { invariant } from 'foxact/invariant';
  8. import picocolors from 'picocolors';
  9. import fs from 'node:fs';
  10. import { fastStringArrayJoin, writeFile } from '../misc';
  11. import { readFileByLine } from '../fetch-text-by-line';
  12. import { asyncWriteToStream } from '../async-write-to-stream';
  13. export abstract class RuleOutput<TPreprocessed = unknown> {
  14. protected domainTrie = createTrie(null, true);
  15. protected domainKeywords = new Set<string>();
  16. protected domainWildcard = new Set<string>();
  17. protected userAgent = new Set<string>();
  18. protected processName = new Set<string>();
  19. protected processPath = new Set<string>();
  20. protected urlRegex = new Set<string>();
  21. protected ipcidr = new Set<string>();
  22. protected ipcidrNoResolve = new Set<string>();
  23. protected ipasn = new Set<string>();
  24. protected ipasnNoResolve = new Set<string>();
  25. protected ipcidr6 = new Set<string>();
  26. protected ipcidr6NoResolve = new Set<string>();
  27. protected geoip = new Set<string>();
  28. protected groipNoResolve = new Set<string>();
  29. protected sourceIpOrCidr = new Set<string>();
  30. protected sourcePort = new Set<string>();
  31. protected destPort = new Set<string>();
  32. protected otherRules: string[] = [];
  33. protected abstract type: 'domainset' | 'non_ip' | 'ip';
  34. protected pendingPromise = Promise.resolve();
  35. static readonly jsonToLines = (json: unknown): string[] => stringify(json).split('\n');
  36. whitelistDomain = (domain: string) => {
  37. this.domainTrie.whitelist(domain);
  38. return this;
  39. };
  40. static readonly domainWildCardToRegex = (domain: string) => {
  41. let result = '^';
  42. for (let i = 0, len = domain.length; i < len; i++) {
  43. switch (domain[i]) {
  44. case '.':
  45. result += String.raw`\.`;
  46. break;
  47. case '*':
  48. result += '[a-zA-Z0-9-_.]*?';
  49. break;
  50. case '?':
  51. result += '[a-zA-Z0-9-_.]';
  52. break;
  53. default:
  54. result += domain[i];
  55. }
  56. }
  57. result += '$';
  58. return result;
  59. };
  60. constructor(protected readonly span: Span, protected readonly id: string) { }
  61. protected title: string | null = null;
  62. withTitle(title: string) {
  63. this.title = title;
  64. return this;
  65. }
  66. protected description: string[] | readonly string[] | null = null;
  67. withDescription(description: string[] | readonly string[]) {
  68. this.description = description;
  69. return this;
  70. }
  71. protected date = new Date();
  72. withDate(date: Date) {
  73. this.date = date;
  74. return this;
  75. }
  76. addDomain(domain: string) {
  77. this.domainTrie.add(domain);
  78. return this;
  79. }
  80. bulkAddDomain(domains: string[]) {
  81. for (let i = 0, len = domains.length; i < len; i++) {
  82. this.addDomain(domains[i]);
  83. }
  84. return this;
  85. }
  86. addDomainSuffix(domain: string) {
  87. this.domainTrie.add(domain, true);
  88. return this;
  89. }
  90. bulkAddDomainSuffix(domains: string[]) {
  91. for (let i = 0, len = domains.length; i < len; i++) {
  92. this.addDomainSuffix(domains[i]);
  93. }
  94. return this;
  95. }
  96. addDomainKeyword(keyword: string) {
  97. this.domainKeywords.add(keyword);
  98. return this;
  99. }
  100. private async addFromDomainsetPromise(source: AsyncIterable<string> | Iterable<string> | string[]) {
  101. // eslint-disable-next-line @typescript-eslint/await-thenable -- https://github.com/typescript-eslint/typescript-eslint/issues/10080
  102. for await (const line of source) {
  103. if (line[0] === '.') {
  104. this.addDomainSuffix(line);
  105. } else {
  106. this.addDomain(line);
  107. }
  108. }
  109. }
  110. addFromDomainset(source: AsyncIterable<string> | Iterable<string> | string[]) {
  111. this.pendingPromise = this.pendingPromise.then(() => this.addFromDomainsetPromise(source));
  112. return this;
  113. }
  114. private async addFromRulesetPromise(source: AsyncIterable<string> | Iterable<string>) {
  115. // eslint-disable-next-line @typescript-eslint/await-thenable -- https://github.com/typescript-eslint/typescript-eslint/issues/10080
  116. for await (const line of source) {
  117. const splitted = line.split(',');
  118. const type = splitted[0];
  119. const value = splitted[1];
  120. const arg = splitted[2];
  121. switch (type) {
  122. case 'DOMAIN':
  123. this.addDomain(value);
  124. break;
  125. case 'DOMAIN-SUFFIX':
  126. this.addDomainSuffix(value);
  127. break;
  128. case 'DOMAIN-KEYWORD':
  129. this.addDomainKeyword(value);
  130. break;
  131. case 'DOMAIN-WILDCARD':
  132. this.domainWildcard.add(value);
  133. break;
  134. case 'USER-AGENT':
  135. this.userAgent.add(value);
  136. break;
  137. case 'PROCESS-NAME':
  138. if (value.includes('/') || value.includes('\\')) {
  139. this.processPath.add(value);
  140. } else {
  141. this.processName.add(value);
  142. }
  143. break;
  144. case 'URL-REGEX': {
  145. const [, ...rest] = splitted;
  146. this.urlRegex.add(rest.join(','));
  147. break;
  148. }
  149. case 'IP-CIDR':
  150. (arg === 'no-resolve' ? this.ipcidrNoResolve : this.ipcidr).add(value);
  151. break;
  152. case 'IP-CIDR6':
  153. (arg === 'no-resolve' ? this.ipcidr6NoResolve : this.ipcidr6).add(value);
  154. break;
  155. case 'IP-ASN':
  156. (arg === 'no-resolve' ? this.ipasnNoResolve : this.ipasn).add(value);
  157. break;
  158. case 'GEOIP':
  159. (arg === 'no-resolve' ? this.groipNoResolve : this.geoip).add(value);
  160. break;
  161. case 'SRC-IP':
  162. this.sourceIpOrCidr.add(value);
  163. break;
  164. case 'SRC-PORT':
  165. this.sourcePort.add(value);
  166. break;
  167. case 'DEST-PORT':
  168. this.destPort.add(value);
  169. break;
  170. default:
  171. this.otherRules.push(line);
  172. break;
  173. }
  174. }
  175. }
  176. addFromRuleset(source: AsyncIterable<string> | Iterable<string>) {
  177. this.pendingPromise = this.pendingPromise.then(() => this.addFromRulesetPromise(source));
  178. return this;
  179. }
  180. static readonly ipToCidr = (ip: string, version: 4 | 6 = 4) => {
  181. if (ip.includes('/')) return ip;
  182. if (version === 4) {
  183. return ip + '/32';
  184. }
  185. return ip + '/128';
  186. };
  187. bulkAddCIDR4(cidrs: string[]) {
  188. for (let i = 0, len = cidrs.length; i < len; i++) {
  189. this.ipcidr.add(RuleOutput.ipToCidr(cidrs[i], 4));
  190. }
  191. return this;
  192. }
  193. bulkAddCIDR4NoResolve(cidrs: string[]) {
  194. for (let i = 0, len = cidrs.length; i < len; i++) {
  195. this.ipcidrNoResolve.add(RuleOutput.ipToCidr(cidrs[i], 4));
  196. }
  197. return this;
  198. }
  199. bulkAddCIDR6(cidrs: string[]) {
  200. for (let i = 0, len = cidrs.length; i < len; i++) {
  201. this.ipcidr6.add(RuleOutput.ipToCidr(cidrs[i], 6));
  202. }
  203. return this;
  204. }
  205. bulkAddCIDR6NoResolve(cidrs: string[]) {
  206. for (let i = 0, len = cidrs.length; i < len; i++) {
  207. this.ipcidr6NoResolve.add(RuleOutput.ipToCidr(cidrs[i], 6));
  208. }
  209. return this;
  210. }
  211. protected abstract preprocess(): NonNullable<TPreprocessed>;
  212. done() {
  213. return this.pendingPromise;
  214. }
  215. private $$preprocessed: TPreprocessed | null = null;
  216. get $preprocessed() {
  217. if (this.$$preprocessed === null) {
  218. this.$$preprocessed = this.span.traceChildSync('RuleOutput#preprocess: ' + this.id, () => this.preprocess());
  219. }
  220. return this.$$preprocessed;
  221. }
  222. async writeClash(outputDir?: null | string) {
  223. await this.done();
  224. invariant(this.title, 'Missing title');
  225. invariant(this.description, 'Missing description');
  226. return compareAndWriteFile(
  227. this.span,
  228. withBannerArray(
  229. this.title,
  230. this.description,
  231. this.date,
  232. this.clash()
  233. ),
  234. path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  235. );
  236. }
  237. async write(): Promise<void> {
  238. await this.done();
  239. invariant(this.title, 'Missing title');
  240. invariant(this.description, 'Missing description');
  241. const promises = [
  242. compareAndWriteFile(
  243. this.span,
  244. withBannerArray(
  245. this.title,
  246. this.description,
  247. this.date,
  248. this.surge()
  249. ),
  250. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  251. ),
  252. compareAndWriteFile(
  253. this.span,
  254. withBannerArray(
  255. this.title,
  256. this.description,
  257. this.date,
  258. this.clash()
  259. ),
  260. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  261. ),
  262. compareAndWriteFile(
  263. this.span,
  264. this.singbox(),
  265. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  266. )
  267. ];
  268. if (this.mitmSgmodule) {
  269. const sgmodule = this.mitmSgmodule();
  270. const sgMOdulePath = this.mitmSgmodulePath ?? path.join(this.type, this.id + '.sgmodule');
  271. if (sgmodule) {
  272. promises.push(
  273. compareAndWriteFile(
  274. this.span,
  275. sgmodule,
  276. path.join(OUTPUT_MODULES_DIR, sgMOdulePath)
  277. )
  278. );
  279. }
  280. }
  281. await Promise.all(promises);
  282. }
  283. abstract surge(): string[];
  284. abstract clash(): string[];
  285. abstract singbox(): string[];
  286. protected mitmSgmodulePath: string | null = null;
  287. withMitmSgmodulePath(path: string | null) {
  288. if (path) {
  289. this.mitmSgmodulePath = path;
  290. }
  291. return this;
  292. }
  293. abstract mitmSgmodule?(): string[] | null;
  294. }
  295. export async function fileEqual(linesA: string[], source: AsyncIterable<string>): Promise<boolean> {
  296. if (linesA.length === 0) {
  297. return false;
  298. }
  299. let index = -1;
  300. for await (const lineB of source) {
  301. index++;
  302. if (index > linesA.length - 1) {
  303. return (index === linesA.length && lineB === '');
  304. }
  305. const lineA = linesA[index];
  306. if (lineA[0] === '#' && lineB[0] === '#') {
  307. continue;
  308. }
  309. if (
  310. lineA[0] === '/'
  311. && lineA[1] === '/'
  312. && lineB[0] === '/'
  313. && lineB[1] === '/'
  314. && lineA[3] === '#'
  315. && lineB[3] === '#'
  316. ) {
  317. continue;
  318. }
  319. if (lineA !== lineB) {
  320. return false;
  321. }
  322. }
  323. // The file becomes larger
  324. return !(index < linesA.length - 1);
  325. }
  326. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  327. let isEqual = true;
  328. const linesALen = linesA.length;
  329. if (fs.existsSync(filePath)) {
  330. isEqual = await fileEqual(linesA, readFileByLine(filePath));
  331. } else {
  332. console.log(`${filePath} does not exists, writing...`);
  333. isEqual = false;
  334. }
  335. if (isEqual) {
  336. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  337. return;
  338. }
  339. await span.traceChildAsync(`writing ${filePath}`, async () => {
  340. // The default highwater mark is normally 16384,
  341. // So we make sure direct write to file if the content is
  342. // most likely less than 500 lines
  343. if (linesALen < 500) {
  344. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  345. }
  346. const writeStream = fs.createWriteStream(filePath);
  347. for (let i = 0; i < linesALen; i++) {
  348. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  349. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  350. if (p) await p;
  351. }
  352. writeStream.end();
  353. });
  354. }