base.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 { HostnameSmolTrie } 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 'foxts/guard';
  8. import picocolors from 'picocolors';
  9. import fs from 'node:fs';
  10. import { writeFile } from '../misc';
  11. import { fastStringArrayJoin } from 'foxts/fast-string-array-join';
  12. import { readFileByLine } from '../fetch-text-by-line';
  13. import { asyncWriteToStream } from 'foxts/async-write-to-stream';
  14. export abstract class RuleOutput<TPreprocessed = unknown> {
  15. protected domainTrie = new HostnameSmolTrie(null);
  16. protected domainKeywords = new Set<string>();
  17. protected domainWildcard = new Set<string>();
  18. protected userAgent = new Set<string>();
  19. protected processName = new Set<string>();
  20. protected processPath = new Set<string>();
  21. protected urlRegex = new Set<string>();
  22. protected ipcidr = new Set<string>();
  23. protected ipcidrNoResolve = new Set<string>();
  24. protected ipasn = new Set<string>();
  25. protected ipasnNoResolve = new Set<string>();
  26. protected ipcidr6 = new Set<string>();
  27. protected ipcidr6NoResolve = new Set<string>();
  28. protected geoip = new Set<string>();
  29. protected groipNoResolve = new Set<string>();
  30. protected sourceIpOrCidr = new Set<string>();
  31. protected sourcePort = new Set<string>();
  32. protected destPort = new Set<string>();
  33. protected otherRules: string[] = [];
  34. protected abstract type: 'domainset' | 'non_ip' | 'ip';
  35. private pendingPromise: Promise<any> | null = null;
  36. static readonly jsonToLines = (json: unknown): string[] => stringify(json).split('\n');
  37. whitelistDomain = (domain: string) => {
  38. this.domainTrie.whitelist(domain);
  39. return this;
  40. };
  41. static readonly domainWildCardToRegex = (domain: string) => {
  42. let result = '^';
  43. for (let i = 0, len = domain.length; i < len; i++) {
  44. switch (domain[i]) {
  45. case '.':
  46. result += String.raw`\.`;
  47. break;
  48. case '*':
  49. result += String.raw`[\w.-]*?`;
  50. break;
  51. case '?':
  52. result += String.raw`[\w.-]`;
  53. break;
  54. default:
  55. result += domain[i];
  56. }
  57. }
  58. result += '$';
  59. return result;
  60. };
  61. protected readonly span: Span;
  62. constructor($span: Span, protected readonly id: string) {
  63. this.span = $span.traceChild('RuleOutput#' + id);
  64. }
  65. protected title: string | null = null;
  66. withTitle(title: string) {
  67. this.title = title;
  68. return this;
  69. }
  70. protected description: string[] | readonly string[] | null = null;
  71. withDescription(description: string[] | readonly string[]) {
  72. this.description = description;
  73. return this;
  74. }
  75. protected date = new Date();
  76. withDate(date: Date) {
  77. this.date = date;
  78. return this;
  79. }
  80. addDomain(domain: string) {
  81. this.domainTrie.add(domain);
  82. return this;
  83. }
  84. bulkAddDomain(domains: Array<string | null>) {
  85. let d: string | null;
  86. for (let i = 0, len = domains.length; i < len; i++) {
  87. d = domains[i];
  88. if (d !== null) {
  89. this.domainTrie.add(d, false, null, 0);
  90. }
  91. }
  92. return this;
  93. }
  94. addDomainSuffix(domain: string, lineFromDot = domain[0] === '.') {
  95. this.domainTrie.add(domain, true, lineFromDot ? 1 : 0);
  96. return this;
  97. }
  98. bulkAddDomainSuffix(domains: string[]) {
  99. for (let i = 0, len = domains.length; i < len; i++) {
  100. this.addDomainSuffix(domains[i]);
  101. }
  102. return this;
  103. }
  104. addDomainKeyword(keyword: string) {
  105. this.domainKeywords.add(keyword);
  106. return this;
  107. }
  108. private async addFromDomainsetPromise(source: AsyncIterable<string> | Iterable<string> | string[]) {
  109. for await (const line of source) {
  110. if (line[0] === '.') {
  111. this.addDomainSuffix(line, true);
  112. } else {
  113. this.domainTrie.add(line, false, null, 0);
  114. }
  115. }
  116. }
  117. addFromDomainset(source: AsyncIterable<string> | Iterable<string> | string[]) {
  118. this.pendingPromise = (this.pendingPromise ||= Promise.resolve()).then(() => this.addFromDomainsetPromise(source));
  119. return this;
  120. }
  121. private async addFromRulesetPromise(source: AsyncIterable<string> | Iterable<string>) {
  122. for await (const line of source) {
  123. const splitted = line.split(',');
  124. const type = splitted[0];
  125. const value = splitted[1];
  126. const arg = splitted[2];
  127. switch (type) {
  128. case 'DOMAIN':
  129. this.domainTrie.add(value, false, null, 0);
  130. break;
  131. case 'DOMAIN-SUFFIX':
  132. this.addDomainSuffix(value, false);
  133. break;
  134. case 'DOMAIN-KEYWORD':
  135. this.addDomainKeyword(value);
  136. break;
  137. case 'DOMAIN-WILDCARD':
  138. this.domainWildcard.add(value);
  139. break;
  140. case 'USER-AGENT':
  141. this.userAgent.add(value);
  142. break;
  143. case 'PROCESS-NAME':
  144. if (value.includes('/') || value.includes('\\')) {
  145. this.processPath.add(value);
  146. } else {
  147. this.processName.add(value);
  148. }
  149. break;
  150. case 'URL-REGEX': {
  151. const [, ...rest] = splitted;
  152. this.urlRegex.add(rest.join(','));
  153. break;
  154. }
  155. case 'IP-CIDR':
  156. (arg === 'no-resolve' ? this.ipcidrNoResolve : this.ipcidr).add(value);
  157. break;
  158. case 'IP-CIDR6':
  159. (arg === 'no-resolve' ? this.ipcidr6NoResolve : this.ipcidr6).add(value);
  160. break;
  161. case 'IP-ASN':
  162. (arg === 'no-resolve' ? this.ipasnNoResolve : this.ipasn).add(value);
  163. break;
  164. case 'GEOIP':
  165. (arg === 'no-resolve' ? this.groipNoResolve : this.geoip).add(value);
  166. break;
  167. case 'SRC-IP':
  168. this.sourceIpOrCidr.add(value);
  169. break;
  170. case 'SRC-PORT':
  171. this.sourcePort.add(value);
  172. break;
  173. case 'DEST-PORT':
  174. this.destPort.add(value);
  175. break;
  176. default:
  177. this.otherRules.push(line);
  178. break;
  179. }
  180. }
  181. }
  182. addFromRuleset(source: AsyncIterable<string> | Iterable<string> | Promise<Iterable<string>>) {
  183. if (this.pendingPromise) {
  184. this.pendingPromise = this.pendingPromise.then(() => source);
  185. } else {
  186. this.pendingPromise = Promise.resolve(source);
  187. }
  188. this.pendingPromise = this.pendingPromise.then((source) => this.addFromRulesetPromise(source));
  189. return this;
  190. }
  191. static readonly ipToCidr = (ip: string, version: 4 | 6) => {
  192. if (ip.includes('/')) return ip;
  193. if (version === 4) {
  194. return ip + '/32';
  195. }
  196. return ip + '/128';
  197. };
  198. bulkAddCIDR4(cidrs: string[]) {
  199. for (let i = 0, len = cidrs.length; i < len; i++) {
  200. this.ipcidr.add(RuleOutput.ipToCidr(cidrs[i], 4));
  201. }
  202. return this;
  203. }
  204. bulkAddCIDR4NoResolve(cidrs: string[]) {
  205. for (let i = 0, len = cidrs.length; i < len; i++) {
  206. this.ipcidrNoResolve.add(RuleOutput.ipToCidr(cidrs[i], 4));
  207. }
  208. return this;
  209. }
  210. bulkAddCIDR6(cidrs: string[]) {
  211. for (let i = 0, len = cidrs.length; i < len; i++) {
  212. this.ipcidr6.add(RuleOutput.ipToCidr(cidrs[i], 6));
  213. }
  214. return this;
  215. }
  216. bulkAddCIDR6NoResolve(cidrs: string[]) {
  217. for (let i = 0, len = cidrs.length; i < len; i++) {
  218. this.ipcidr6NoResolve.add(RuleOutput.ipToCidr(cidrs[i], 6));
  219. }
  220. return this;
  221. }
  222. protected abstract preprocess(): TPreprocessed extends null ? null : NonNullable<TPreprocessed>;
  223. async done() {
  224. await this.pendingPromise;
  225. this.pendingPromise = null;
  226. return this;
  227. }
  228. private guardPendingPromise() {
  229. // reverse invariant
  230. if (this.pendingPromise !== null) {
  231. console.trace('Pending promise:', this.pendingPromise);
  232. throw new Error('You should call done() before calling this method');
  233. }
  234. }
  235. private $$preprocessed: TPreprocessed | null = null;
  236. protected runPreprocess() {
  237. if (this.$$preprocessed === null) {
  238. this.guardPendingPromise();
  239. this.$$preprocessed = this.span.traceChildSync('preprocess', () => this.preprocess());
  240. }
  241. }
  242. get $preprocessed(): TPreprocessed extends null ? null : NonNullable<TPreprocessed> {
  243. this.runPreprocess();
  244. return this.$$preprocessed as any;
  245. }
  246. async writeClash(outputDir?: null | string) {
  247. await this.done();
  248. invariant(this.title, 'Missing title');
  249. invariant(this.description, 'Missing description');
  250. return compareAndWriteFile(
  251. this.span,
  252. withBannerArray(
  253. this.title,
  254. this.description,
  255. this.date,
  256. this.clash()
  257. ),
  258. path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  259. );
  260. }
  261. write(): Promise<void> {
  262. return this.done().then(() => this.span.traceChildAsync('write all', async () => {
  263. invariant(this.title, 'Missing title');
  264. invariant(this.description, 'Missing description');
  265. const promises = [
  266. compareAndWriteFile(
  267. this.span,
  268. withBannerArray(
  269. this.title,
  270. this.description,
  271. this.date,
  272. this.surge()
  273. ),
  274. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  275. ),
  276. compareAndWriteFile(
  277. this.span,
  278. withBannerArray(
  279. this.title,
  280. this.description,
  281. this.date,
  282. this.clash()
  283. ),
  284. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  285. ),
  286. compareAndWriteFile(
  287. this.span,
  288. this.singbox(),
  289. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  290. )
  291. ];
  292. if (this.mitmSgmodule) {
  293. const sgmodule = this.mitmSgmodule();
  294. const sgModulePath = this.mitmSgmodulePath ?? path.join(this.type, this.id + '.sgmodule');
  295. if (sgmodule) {
  296. promises.push(
  297. compareAndWriteFile(
  298. this.span,
  299. sgmodule,
  300. path.join(OUTPUT_MODULES_DIR, sgModulePath)
  301. )
  302. );
  303. }
  304. }
  305. await Promise.all(promises);
  306. }));
  307. }
  308. abstract surge(): string[];
  309. abstract clash(): string[];
  310. abstract singbox(): string[];
  311. protected mitmSgmodulePath: string | null = null;
  312. withMitmSgmodulePath(path: string | null) {
  313. if (path) {
  314. this.mitmSgmodulePath = path;
  315. }
  316. return this;
  317. }
  318. abstract mitmSgmodule?(): string[] | null;
  319. }
  320. export async function fileEqual(linesA: string[], source: AsyncIterable<string>): Promise<boolean> {
  321. if (linesA.length === 0) {
  322. return false;
  323. }
  324. let index = -1;
  325. for await (const lineB of source) {
  326. index++;
  327. if (index > linesA.length - 1) {
  328. return (index === linesA.length && lineB === '');
  329. }
  330. const lineA = linesA[index];
  331. if (lineA[0] === '#' && lineB[0] === '#') {
  332. continue;
  333. }
  334. if (
  335. lineA[0] === '/'
  336. && lineA[1] === '/'
  337. && lineB[0] === '/'
  338. && lineB[1] === '/'
  339. && lineA[3] === '#'
  340. && lineB[3] === '#'
  341. ) {
  342. continue;
  343. }
  344. if (lineA !== lineB) {
  345. return false;
  346. }
  347. }
  348. // The file becomes larger
  349. return !(index < linesA.length - 1);
  350. }
  351. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  352. let isEqual = true;
  353. const linesALen = linesA.length;
  354. if (fs.existsSync(filePath)) {
  355. isEqual = await fileEqual(linesA, readFileByLine(filePath));
  356. } else {
  357. console.log(`${filePath} does not exists, writing...`);
  358. isEqual = false;
  359. }
  360. if (isEqual) {
  361. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  362. return;
  363. }
  364. await span.traceChildAsync(`writing ${filePath}`, async () => {
  365. // The default highwater mark is normally 16384,
  366. // So we make sure direct write to file if the content is
  367. // most likely less than 500 lines
  368. if (linesALen < 500) {
  369. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  370. }
  371. const writeStream = fs.createWriteStream(filePath);
  372. for (let i = 0; i < linesALen; i++) {
  373. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  374. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  375. if (p) await p;
  376. }
  377. writeStream.end();
  378. });
  379. }