base.ts 11 KB

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