base.ts 11 KB

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