base.ts 11 KB

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