base.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. private pendingPromise: Promise<void> | null = null;
  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 ||= Promise.resolve()).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 ||= Promise.resolve()).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. async done() {
  211. await this.pendingPromise;
  212. this.pendingPromise = null;
  213. }
  214. private guardPendingPromise() {
  215. // reverse invariant
  216. if (this.pendingPromise !== null) {
  217. console.trace('Pending promise:', this.pendingPromise);
  218. throw new Error('You should call done() before calling this method');
  219. }
  220. }
  221. private $$preprocessed: TPreprocessed | null = null;
  222. get $preprocessed() {
  223. if (this.$$preprocessed === null) {
  224. this.guardPendingPromise();
  225. this.$$preprocessed = this.span.traceChildSync('RuleOutput#preprocess: ' + this.id, () => this.preprocess());
  226. }
  227. return this.$$preprocessed;
  228. }
  229. async writeClash(outputDir?: null | string) {
  230. await this.done();
  231. invariant(this.title, 'Missing title');
  232. invariant(this.description, 'Missing description');
  233. return compareAndWriteFile(
  234. this.span,
  235. withBannerArray(
  236. this.title,
  237. this.description,
  238. this.date,
  239. this.clash()
  240. ),
  241. path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  242. );
  243. }
  244. async write(): Promise<void> {
  245. await this.done();
  246. invariant(this.title, 'Missing title');
  247. invariant(this.description, 'Missing description');
  248. const promises = [
  249. compareAndWriteFile(
  250. this.span,
  251. withBannerArray(
  252. this.title,
  253. this.description,
  254. this.date,
  255. this.surge()
  256. ),
  257. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  258. ),
  259. compareAndWriteFile(
  260. this.span,
  261. withBannerArray(
  262. this.title,
  263. this.description,
  264. this.date,
  265. this.clash()
  266. ),
  267. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  268. ),
  269. compareAndWriteFile(
  270. this.span,
  271. this.singbox(),
  272. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  273. )
  274. ];
  275. if (this.mitmSgmodule) {
  276. const sgmodule = this.mitmSgmodule();
  277. const sgModulePath = this.mitmSgmodulePath ?? path.join(this.type, this.id + '.sgmodule');
  278. if (sgmodule) {
  279. promises.push(
  280. compareAndWriteFile(
  281. this.span,
  282. sgmodule,
  283. path.join(OUTPUT_MODULES_DIR, sgModulePath)
  284. )
  285. );
  286. }
  287. }
  288. await Promise.all(promises);
  289. }
  290. abstract surge(): string[];
  291. abstract clash(): string[];
  292. abstract singbox(): string[];
  293. protected mitmSgmodulePath: string | null = null;
  294. withMitmSgmodulePath(path: string | null) {
  295. if (path) {
  296. this.mitmSgmodulePath = path;
  297. }
  298. return this;
  299. }
  300. abstract mitmSgmodule?(): string[] | null;
  301. }
  302. export async function fileEqual(linesA: string[], source: AsyncIterable<string>): Promise<boolean> {
  303. if (linesA.length === 0) {
  304. return false;
  305. }
  306. let index = -1;
  307. for await (const lineB of source) {
  308. index++;
  309. if (index > linesA.length - 1) {
  310. return (index === linesA.length && lineB === '');
  311. }
  312. const lineA = linesA[index];
  313. if (lineA[0] === '#' && lineB[0] === '#') {
  314. continue;
  315. }
  316. if (
  317. lineA[0] === '/'
  318. && lineA[1] === '/'
  319. && lineB[0] === '/'
  320. && lineB[1] === '/'
  321. && lineA[3] === '#'
  322. && lineB[3] === '#'
  323. ) {
  324. continue;
  325. }
  326. if (lineA !== lineB) {
  327. return false;
  328. }
  329. }
  330. // The file becomes larger
  331. return !(index < linesA.length - 1);
  332. }
  333. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  334. let isEqual = true;
  335. const linesALen = linesA.length;
  336. if (fs.existsSync(filePath)) {
  337. isEqual = await fileEqual(linesA, readFileByLine(filePath));
  338. } else {
  339. console.log(`${filePath} does not exists, writing...`);
  340. isEqual = false;
  341. }
  342. if (isEqual) {
  343. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  344. return;
  345. }
  346. await span.traceChildAsync(`writing ${filePath}`, async () => {
  347. // The default highwater mark is normally 16384,
  348. // So we make sure direct write to file if the content is
  349. // most likely less than 500 lines
  350. if (linesALen < 500) {
  351. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  352. }
  353. const writeStream = fs.createWriteStream(filePath);
  354. for (let i = 0; i < linesALen; i++) {
  355. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  356. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  357. if (p) await p;
  358. }
  359. writeStream.end();
  360. });
  361. }