base.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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' | (string & {});
  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({
  262. surge = true,
  263. clash = true,
  264. singbox = true,
  265. surgeDir = OUTPUT_SURGE_DIR,
  266. clashDir = OUTPUT_CLASH_DIR,
  267. singboxDir = OUTPUT_SINGBOX_DIR
  268. }: {
  269. surge?: boolean,
  270. clash?: boolean,
  271. singbox?: boolean,
  272. surgeDir?: string,
  273. clashDir?: string,
  274. singboxDir?: string
  275. } = {}): Promise<void> {
  276. return this.done().then(() => this.span.traceChildAsync('write all', async () => {
  277. invariant(this.title, 'Missing title');
  278. invariant(this.description, 'Missing description');
  279. const promises: Array<Promise<void>> = [];
  280. if (surge) {
  281. promises.push(compareAndWriteFile(
  282. this.span,
  283. withBannerArray(
  284. this.title,
  285. this.description,
  286. this.date,
  287. this.surge()
  288. ),
  289. path.join(surgeDir, this.type, this.id + '.conf')
  290. ));
  291. }
  292. if (clash) {
  293. promises.push(compareAndWriteFile(
  294. this.span,
  295. withBannerArray(
  296. this.title,
  297. this.description,
  298. this.date,
  299. this.clash()
  300. ),
  301. path.join(clashDir, this.type, this.id + '.txt')
  302. ));
  303. }
  304. if (singbox) {
  305. promises.push(compareAndWriteFile(
  306. this.span,
  307. this.singbox(),
  308. path.join(singboxDir, this.type, this.id + '.json')
  309. ));
  310. }
  311. if (this.mitmSgmodule) {
  312. const sgmodule = this.mitmSgmodule();
  313. const sgModulePath = this.mitmSgmodulePath ?? path.join(this.type, this.id + '.sgmodule');
  314. if (sgmodule) {
  315. promises.push(
  316. compareAndWriteFile(
  317. this.span,
  318. sgmodule,
  319. path.join(OUTPUT_MODULES_DIR, sgModulePath)
  320. )
  321. );
  322. }
  323. }
  324. await Promise.all(promises);
  325. }));
  326. }
  327. abstract surge(): string[];
  328. abstract clash(): string[];
  329. abstract singbox(): string[];
  330. protected mitmSgmodulePath: string | null = null;
  331. withMitmSgmodulePath(path: string | null) {
  332. if (path) {
  333. this.mitmSgmodulePath = path;
  334. }
  335. return this;
  336. }
  337. abstract mitmSgmodule?(): string[] | null;
  338. }
  339. export async function fileEqual(linesA: string[], source: AsyncIterable<string> | Iterable<string>): Promise<boolean> {
  340. if (linesA.length === 0) {
  341. return false;
  342. }
  343. const linesABound = linesA.length - 1;
  344. let index = -1;
  345. for await (const lineB of source) {
  346. index++;
  347. if (index > linesABound) {
  348. return (index === linesA.length && lineB.length === 0);
  349. }
  350. const lineA = linesA[index];
  351. const firstCharA = lineA.charCodeAt(0);
  352. const firstCharB = lineB.charCodeAt(0);
  353. if (firstCharA !== firstCharB) {
  354. return false;
  355. }
  356. if (firstCharA === 35 /* # */ && firstCharB === 35 /* # */) {
  357. continue;
  358. }
  359. // adguard conf
  360. if (firstCharA === 33 /* ! */ && firstCharB === 33 /* ! */) {
  361. continue;
  362. }
  363. if (
  364. firstCharA === 47 /* / */ && firstCharB === 47 /* / */
  365. && lineA[1] === '/' && lineB[1] === '/'
  366. && lineA[3] === '#' && lineB[3] === '#'
  367. ) {
  368. continue;
  369. }
  370. if (lineA !== lineB) {
  371. return false;
  372. }
  373. }
  374. // The file becomes larger
  375. return !(index < linesABound);
  376. }
  377. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  378. const linesALen = linesA.length;
  379. const isEqual = await span.traceChildAsync(`compare ${filePath}`, async () => {
  380. if (fs.existsSync(filePath)) {
  381. return fileEqual(linesA, readFileByLine(filePath));
  382. }
  383. console.log(`${filePath} does not exists, writing...`);
  384. return false;
  385. });
  386. if (isEqual) {
  387. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  388. return;
  389. }
  390. await span.traceChildAsync(`writing ${filePath}`, async () => {
  391. // The default highwater mark is normally 16384,
  392. // So we make sure direct write to file if the content is
  393. // most likely less than 500 lines
  394. if (linesALen < 500) {
  395. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  396. }
  397. const writeStream = fs.createWriteStream(filePath);
  398. for (let i = 0; i < linesALen; i++) {
  399. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  400. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  401. if (p) await p;
  402. }
  403. writeStream.end();
  404. });
  405. }