base.ts 9.3 KB

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