base.ts 11 KB

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