base.ts 11 KB

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