base.ts 9.4 KB

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