base.ts 10 KB

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