base.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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<void> | 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.addDomain(d);
  90. }
  91. }
  92. return this;
  93. }
  94. addDomainSuffix(domain: string) {
  95. this.domainTrie.add(domain, true);
  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);
  112. } else {
  113. this.addDomain(line);
  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.addDomain(value);
  130. break;
  131. case 'DOMAIN-SUFFIX':
  132. this.addDomainSuffix(value);
  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>) {
  183. this.pendingPromise = (this.pendingPromise ||= Promise.resolve()).then(() => this.addFromRulesetPromise(source));
  184. return this;
  185. }
  186. static readonly ipToCidr = (ip: string, version: 4 | 6) => {
  187. if (ip.includes('/')) return ip;
  188. if (version === 4) {
  189. return ip + '/32';
  190. }
  191. return ip + '/128';
  192. };
  193. bulkAddCIDR4(cidrs: string[]) {
  194. for (let i = 0, len = cidrs.length; i < len; i++) {
  195. this.ipcidr.add(RuleOutput.ipToCidr(cidrs[i], 4));
  196. }
  197. return this;
  198. }
  199. bulkAddCIDR4NoResolve(cidrs: string[]) {
  200. for (let i = 0, len = cidrs.length; i < len; i++) {
  201. this.ipcidrNoResolve.add(RuleOutput.ipToCidr(cidrs[i], 4));
  202. }
  203. return this;
  204. }
  205. bulkAddCIDR6(cidrs: string[]) {
  206. for (let i = 0, len = cidrs.length; i < len; i++) {
  207. this.ipcidr6.add(RuleOutput.ipToCidr(cidrs[i], 6));
  208. }
  209. return this;
  210. }
  211. bulkAddCIDR6NoResolve(cidrs: string[]) {
  212. for (let i = 0, len = cidrs.length; i < len; i++) {
  213. this.ipcidr6NoResolve.add(RuleOutput.ipToCidr(cidrs[i], 6));
  214. }
  215. return this;
  216. }
  217. protected abstract preprocess(): NonNullable<TPreprocessed>;
  218. async done() {
  219. await this.pendingPromise;
  220. this.pendingPromise = null;
  221. }
  222. private guardPendingPromise() {
  223. // reverse invariant
  224. if (this.pendingPromise !== null) {
  225. console.trace('Pending promise:', this.pendingPromise);
  226. throw new Error('You should call done() before calling this method');
  227. }
  228. }
  229. private $$preprocessed: TPreprocessed | null = null;
  230. get $preprocessed() {
  231. if (this.$$preprocessed === null) {
  232. this.guardPendingPromise();
  233. this.$$preprocessed = this.span.traceChildSync('preprocess', () => this.preprocess());
  234. }
  235. return this.$$preprocessed;
  236. }
  237. async writeClash(outputDir?: null | string) {
  238. await this.done();
  239. invariant(this.title, 'Missing title');
  240. invariant(this.description, 'Missing description');
  241. return compareAndWriteFile(
  242. this.span,
  243. withBannerArray(
  244. this.title,
  245. this.description,
  246. this.date,
  247. this.clash()
  248. ),
  249. path.join(outputDir ?? OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  250. );
  251. }
  252. write(): Promise<void> {
  253. return this.done().then(() => this.span.traceChildAsync('write all', async () => {
  254. invariant(this.title, 'Missing title');
  255. invariant(this.description, 'Missing description');
  256. const promises = [
  257. compareAndWriteFile(
  258. this.span,
  259. withBannerArray(
  260. this.title,
  261. this.description,
  262. this.date,
  263. this.surge()
  264. ),
  265. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  266. ),
  267. compareAndWriteFile(
  268. this.span,
  269. withBannerArray(
  270. this.title,
  271. this.description,
  272. this.date,
  273. this.clash()
  274. ),
  275. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  276. ),
  277. compareAndWriteFile(
  278. this.span,
  279. this.singbox(),
  280. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  281. )
  282. ];
  283. if (this.mitmSgmodule) {
  284. const sgmodule = this.mitmSgmodule();
  285. const sgModulePath = this.mitmSgmodulePath ?? path.join(this.type, this.id + '.sgmodule');
  286. if (sgmodule) {
  287. promises.push(
  288. compareAndWriteFile(
  289. this.span,
  290. sgmodule,
  291. path.join(OUTPUT_MODULES_DIR, sgModulePath)
  292. )
  293. );
  294. }
  295. }
  296. await Promise.all(promises);
  297. }));
  298. }
  299. abstract surge(): string[];
  300. abstract clash(): string[];
  301. abstract singbox(): string[];
  302. protected mitmSgmodulePath: string | null = null;
  303. withMitmSgmodulePath(path: string | null) {
  304. if (path) {
  305. this.mitmSgmodulePath = path;
  306. }
  307. return this;
  308. }
  309. abstract mitmSgmodule?(): string[] | null;
  310. }
  311. export async function fileEqual(linesA: string[], source: AsyncIterable<string>): Promise<boolean> {
  312. if (linesA.length === 0) {
  313. return false;
  314. }
  315. let index = -1;
  316. for await (const lineB of source) {
  317. index++;
  318. if (index > linesA.length - 1) {
  319. return (index === linesA.length && lineB === '');
  320. }
  321. const lineA = linesA[index];
  322. if (lineA[0] === '#' && lineB[0] === '#') {
  323. continue;
  324. }
  325. if (
  326. lineA[0] === '/'
  327. && lineA[1] === '/'
  328. && lineB[0] === '/'
  329. && lineB[1] === '/'
  330. && lineA[3] === '#'
  331. && lineB[3] === '#'
  332. ) {
  333. continue;
  334. }
  335. if (lineA !== lineB) {
  336. return false;
  337. }
  338. }
  339. // The file becomes larger
  340. return !(index < linesA.length - 1);
  341. }
  342. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  343. let isEqual = true;
  344. const linesALen = linesA.length;
  345. if (fs.existsSync(filePath)) {
  346. isEqual = await fileEqual(linesA, readFileByLine(filePath));
  347. } else {
  348. console.log(`${filePath} does not exists, writing...`);
  349. isEqual = false;
  350. }
  351. if (isEqual) {
  352. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  353. return;
  354. }
  355. await span.traceChildAsync(`writing ${filePath}`, async () => {
  356. // The default highwater mark is normally 16384,
  357. // So we make sure direct write to file if the content is
  358. // most likely less than 500 lines
  359. if (linesALen < 500) {
  360. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  361. }
  362. const writeStream = fs.createWriteStream(filePath);
  363. for (let i = 0; i < linesALen; i++) {
  364. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  365. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  366. if (p) await p;
  367. }
  368. writeStream.end();
  369. });
  370. }