base.ts 11 KB

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