base.ts 9.1 KB

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