base.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 {
  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. 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 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. abstract surge(): string[];
  211. abstract clash(): string[];
  212. abstract singbox(): string[];
  213. done() {
  214. return this.pendingPromise;
  215. }
  216. async write(): Promise<void> {
  217. await this.done();
  218. invariant(this.title, 'Missing title');
  219. invariant(this.description, 'Missing description');
  220. await Promise.all([
  221. compareAndWriteFile(
  222. this.span,
  223. withBannerArray(
  224. this.title,
  225. this.description,
  226. this.date,
  227. this.surge()
  228. ),
  229. path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
  230. ),
  231. compareAndWriteFile(
  232. this.span,
  233. withBannerArray(
  234. this.title,
  235. this.description,
  236. this.date,
  237. this.clash()
  238. ),
  239. path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
  240. ),
  241. compareAndWriteFile(
  242. this.span,
  243. this.singbox(),
  244. path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
  245. )
  246. ]);
  247. }
  248. }
  249. export const fileEqual = async (linesA: string[], source: AsyncIterable<string>): Promise<boolean> => {
  250. if (linesA.length === 0) {
  251. return false;
  252. }
  253. let index = -1;
  254. for await (const lineB of source) {
  255. index++;
  256. if (index > linesA.length - 1) {
  257. if (index === linesA.length && lineB === '') {
  258. return true;
  259. }
  260. // The file becomes smaller
  261. return false;
  262. }
  263. const lineA = linesA[index];
  264. if (lineA[0] === '#' && lineB[0] === '#') {
  265. continue;
  266. }
  267. if (
  268. lineA[0] === '/'
  269. && lineA[1] === '/'
  270. && lineB[0] === '/'
  271. && lineB[1] === '/'
  272. && lineA[3] === '#'
  273. && lineB[3] === '#'
  274. ) {
  275. continue;
  276. }
  277. if (lineA !== lineB) {
  278. return false;
  279. }
  280. }
  281. if (index < linesA.length - 1) {
  282. // The file becomes larger
  283. return false;
  284. }
  285. return true;
  286. };
  287. export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
  288. let isEqual = true;
  289. const linesALen = linesA.length;
  290. if (fs.existsSync(filePath)) {
  291. isEqual = await fileEqual(linesA, readFileByLine(filePath));
  292. } else {
  293. console.log(`${filePath} does not exists, writing...`);
  294. isEqual = false;
  295. }
  296. if (isEqual) {
  297. console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
  298. return;
  299. }
  300. await span.traceChildAsync(`writing ${filePath}`, async () => {
  301. // The default highwater mark is normally 16384,
  302. // So we make sure direct write to file if the content is
  303. // most likely less than 500 lines
  304. if (linesALen < 500) {
  305. return writeFile(filePath, fastStringArrayJoin(linesA, '\n') + '\n');
  306. }
  307. const writeStream = fs.createWriteStream(filePath);
  308. for (let i = 0; i < linesALen; i++) {
  309. const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
  310. // eslint-disable-next-line no-await-in-loop -- stream high water mark
  311. if (p) await p;
  312. }
  313. await asyncWriteToStream(writeStream, '\n');
  314. writeStream.end();
  315. });
  316. }