base.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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<unknown>(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. // TODO: add sourceIpcidr
  30. // TODO: add sourcePort
  31. // TODO: add port
  32. protected otherRules: string[] = [];
  33. protected abstract type: 'domainset' | 'non_ip' | 'ip';
  34. protected pendingPromise = Promise.resolve();
  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(
  61. protected readonly span: Span,
  62. protected readonly id: string
  63. ) { }
  64. protected title: string | null = null;
  65. withTitle(title: string) {
  66. this.title = title;
  67. return this;
  68. }
  69. protected description: string[] | readonly string[] | null = null;
  70. withDescription(description: string[] | readonly string[]) {
  71. this.description = description;
  72. return this;
  73. }
  74. protected date = new Date();
  75. withDate(date: Date) {
  76. this.date = date;
  77. return this;
  78. }
  79. protected apexDomainMap: Map<string, string> | null = null;
  80. protected subDomainMap: Map<string, string> | null = null;
  81. withDomainMap(apexDomainMap: Map<string, string>, subDomainMap: Map<string, string>) {
  82. this.apexDomainMap = apexDomainMap;
  83. this.subDomainMap = subDomainMap;
  84. return this;
  85. }
  86. addDomain(domain: string) {
  87. this.domainTrie.add(domain);
  88. return this;
  89. }
  90. bulkAddDomain(domains: string[]) {
  91. for (let i = 0, len = domains.length; i < len; i++) {
  92. this.addDomain(domains[i]);
  93. }
  94. return this;
  95. }
  96. addDomainSuffix(domain: string) {
  97. this.domainTrie.add(domain[0] === '.' ? domain : '.' + domain);
  98. return this;
  99. }
  100. bulkAddDomainSuffix(domains: string[]) {
  101. for (let i = 0, len = domains.length; i < len; i++) {
  102. this.addDomainSuffix(domains[i]);
  103. }
  104. return this;
  105. }
  106. addDomainKeyword(keyword: string) {
  107. this.domainKeywords.add(keyword);
  108. return this;
  109. }
  110. private async addFromDomainsetPromise(source: AsyncIterable<string> | Iterable<string> | string[]) {
  111. for await (const line of source) {
  112. if (line[0] === '.') {
  113. this.addDomainSuffix(line);
  114. } else {
  115. this.addDomain(line);
  116. }
  117. }
  118. }
  119. addFromDomainset(source: AsyncIterable<string> | Iterable<string> | string[]) {
  120. this.pendingPromise = this.pendingPromise.then(() => this.addFromDomainsetPromise(source));
  121. return this;
  122. }
  123. private async addFromRulesetPromise(source: AsyncIterable<string> | Iterable<string>) {
  124. for await (const line of source) {
  125. const splitted = line.split(',');
  126. const type = splitted[0];
  127. const value = splitted[1];
  128. const arg = splitted[2];
  129. switch (type) {
  130. case 'DOMAIN':
  131. this.addDomain(value);
  132. break;
  133. case 'DOMAIN-SUFFIX':
  134. this.addDomainSuffix(value);
  135. break;
  136. case 'DOMAIN-KEYWORD':
  137. this.addDomainKeyword(value);
  138. break;
  139. case 'DOMAIN-WILDCARD':
  140. this.domainWildcard.add(value);
  141. break;
  142. case 'USER-AGENT':
  143. this.userAgent.add(value);
  144. break;
  145. case 'PROCESS-NAME':
  146. if (value.includes('/') || value.includes('\\')) {
  147. this.processPath.add(value);
  148. } else {
  149. this.processName.add(value);
  150. }
  151. break;
  152. case 'URL-REGEX': {
  153. const [, ...rest] = splitted;
  154. this.urlRegex.add(rest.join(','));
  155. break;
  156. }
  157. case 'IP-CIDR':
  158. (arg === 'no-resolve' ? this.ipcidrNoResolve : this.ipcidr).add(value);
  159. break;
  160. case 'IP-CIDR6':
  161. (arg === 'no-resolve' ? this.ipcidr6NoResolve : this.ipcidr6).add(value);
  162. break;
  163. case 'IP-ASN':
  164. (arg === 'no-resolve' ? this.ipasnNoResolve : this.ipasn).add(value);
  165. break;
  166. case 'GEOIP':
  167. (arg === 'no-resolve' ? this.groipNoResolve : this.geoip).add(value);
  168. break;
  169. default:
  170. this.otherRules.push(line);
  171. break;
  172. }
  173. }
  174. }
  175. addFromRuleset(source: AsyncIterable<string> | Iterable<string>) {
  176. this.pendingPromise = this.pendingPromise.then(() => this.addFromRulesetPromise(source));
  177. return this;
  178. }
  179. static readonly ipToCidr = (ip: string, version: 4 | 6 = 4) => {
  180. if (ip.includes('/')) return ip;
  181. if (version === 4) {
  182. return ip + '/32';
  183. }
  184. return ip + '/128';
  185. };
  186. bulkAddCIDR4(cidrs: string[]) {
  187. for (let i = 0, len = cidrs.length; i < len; i++) {
  188. this.ipcidr.add(RuleOutput.ipToCidr(cidrs[i], 4));
  189. }
  190. return this;
  191. }
  192. bulkAddCIDR4NoResolve(cidrs: string[]) {
  193. for (let i = 0, len = cidrs.length; i < len; i++) {
  194. this.ipcidrNoResolve.add(RuleOutput.ipToCidr(cidrs[i], 4));
  195. }
  196. return this;
  197. }
  198. bulkAddCIDR6(cidrs: string[]) {
  199. for (let i = 0, len = cidrs.length; i < len; i++) {
  200. this.ipcidr6.add(RuleOutput.ipToCidr(cidrs[i], 6));
  201. }
  202. return this;
  203. }
  204. bulkAddCIDR6NoResolve(cidrs: string[]) {
  205. for (let i = 0, len = cidrs.length; i < len; i++) {
  206. this.ipcidr6NoResolve.add(RuleOutput.ipToCidr(cidrs[i], 6));
  207. }
  208. return this;
  209. }
  210. protected abstract preprocess(): NonNullable<TPreprocessed>;
  211. done() {
  212. return this.pendingPromise;
  213. }
  214. private $$preprocessed: TPreprocessed | null = null;
  215. get $preprocessed() {
  216. if (this.$$preprocessed === null) {
  217. this.$$preprocessed = this.span.traceChildSync('RuleOutput#preprocess: ' + this.id, () => this.preprocess());
  218. }
  219. return this.$$preprocessed;
  220. }
  221. async write(): Promise<void> {
  222. await this.done();
  223. invariant(this.title, 'Missing title');
  224. invariant(this.description, 'Missing description');
  225. const promises = [
  226. compareAndWriteFile(
  227. this.span,
  228. withBannerArray(
  229. this.title,
  230. this.description,
  231. this.date,
  232. this.surge()
  233. ),
  234. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  235. ),
  236. compareAndWriteFile(
  237. this.span,
  238. withBannerArray(
  239. this.title,
  240. this.description,
  241. this.date,
  242. this.clash()
  243. ),
  244. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  245. ),
  246. compareAndWriteFile(
  247. this.span,
  248. this.singbox(),
  249. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  250. )
  251. ];
  252. if (this.mitmSgmodule) {
  253. const sgmodule = this.mitmSgmodule();
  254. const sgMOdulePath = this.mitmSgmodulePath ?? path.join(this.type, this.id + '.sgmodule');
  255. if (sgmodule) {
  256. promises.push(
  257. compareAndWriteFile(
  258. this.span,
  259. sgmodule,
  260. path.join(OUTPUT_MODULES_DIR, sgMOdulePath)
  261. )
  262. );
  263. }
  264. }
  265. await Promise.all(promises);
  266. }
  267. abstract surge(): string[];
  268. abstract clash(): string[];
  269. abstract singbox(): string[];
  270. protected mitmSgmodulePath: string | null = null;
  271. withMitmSgmodulePath(path: string | null) {
  272. if (path) {
  273. this.mitmSgmodulePath = path;
  274. }
  275. return this;
  276. }
  277. abstract mitmSgmodule?(): string[] | null;
  278. }
  279. export const fileEqual = async (linesA: string[], source: AsyncIterable<string>): Promise<boolean> => {
  280. if (linesA.length === 0) {
  281. return false;
  282. }
  283. let index = -1;
  284. for await (const lineB of source) {
  285. index++;
  286. if (index > linesA.length - 1) {
  287. return (index === linesA.length && lineB === '');
  288. }
  289. const lineA = linesA[index];
  290. if (lineA[0] === '#' && lineB[0] === '#') {
  291. continue;
  292. }
  293. if (
  294. lineA[0] === '/'
  295. && lineA[1] === '/'
  296. && lineB[0] === '/'
  297. && lineB[1] === '/'
  298. && lineA[3] === '#'
  299. && lineB[3] === '#'
  300. ) {
  301. continue;
  302. }
  303. if (lineA !== lineB) {
  304. return false;
  305. }
  306. }
  307. // The file becomes larger
  308. return !(index < linesA.length - 1);
  309. };
  310. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  311. let isEqual = true;
  312. const linesALen = linesA.length;
  313. if (fs.existsSync(filePath)) {
  314. isEqual = await fileEqual(linesA, readFileByLine(filePath));
  315. } else {
  316. console.log(`${filePath} does not exists, writing...`);
  317. isEqual = false;
  318. }
  319. if (isEqual) {
  320. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  321. return;
  322. }
  323. await span.traceChildAsync(`writing ${filePath}`, async () => {
  324. // The default highwater mark is normally 16384,
  325. // So we make sure direct write to file if the content is
  326. // most likely less than 500 lines
  327. if (linesALen < 500) {
  328. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  329. }
  330. const writeStream = fs.createWriteStream(filePath);
  331. for (let i = 0; i < linesALen; i++) {
  332. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  333. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  334. if (p) await p;
  335. }
  336. writeStream.end();
  337. });
  338. }