build-reject-domainset.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. const { promises: fsPromises } = require('fs');
  2. const fse = require('fs-extra');
  3. const { resolve: pathResolve } = require('path');
  4. const Piscina = require('piscina');
  5. const { processHosts, processFilterRules, preprocessFullDomainSetBeforeUsedAsWorkerData } = require('./lib/parse-filter');
  6. const cpuCount = require('os').cpus().length;
  7. const { isCI } = require('ci-info');
  8. const threads = isCI ? cpuCount : cpuCount / 2;
  9. const { HOSTS, ADGUARD_FILTERS, PREDEFINED_WHITELIST } = require('./lib/reject-data-source');
  10. const filterRuleWhitelistDomainSets = new Set(PREDEFINED_WHITELIST);
  11. (async () => {
  12. console.time('Total Time - build-reject-domain-set');
  13. /** @type Set<string> */
  14. const domainSets = new Set();
  15. console.log('Downloading hosts file...');
  16. console.time('* Download and process Hosts');
  17. // Parse from remote hosts & domain lists
  18. (await Promise.all(
  19. HOSTS.map(entry => processHosts(entry[0], entry[1]))
  20. )).forEach(hosts => {
  21. hosts.forEach(host => {
  22. if (host) {
  23. domainSets.add(host);
  24. }
  25. });
  26. });
  27. console.timeEnd('* Download and process Hosts');
  28. let previousSize = domainSets.size;
  29. console.log(`Import ${previousSize} rules from hosts files!`);
  30. // Parse from AdGuard Filters
  31. console.time('* Download and process AdBlock Filter Rules');
  32. (await Promise.all(ADGUARD_FILTERS.map(input => {
  33. if (typeof input === 'string') {
  34. return processFilterRules(input);
  35. }
  36. if (Array.isArray(input) && input.length === 2) {
  37. return processFilterRules(input[0], input[1]);
  38. }
  39. }))).forEach(({ white, black }) => {
  40. white.forEach(i => filterRuleWhitelistDomainSets.add(i));
  41. black.forEach(i => domainSets.add(i));
  42. });
  43. console.timeEnd('* Download and process AdBlock Filter Rules');
  44. previousSize = domainSets.size - previousSize;
  45. console.log(`Import ${previousSize} rules from adguard filters!`);
  46. await fsPromises.readFile(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), { encoding: 'utf-8' }).then(data => {
  47. data.split('\n').forEach(line => {
  48. const trimmed = line.trim();
  49. if (
  50. line.startsWith('#')
  51. || line.startsWith(' ')
  52. || line.startsWith('\r')
  53. || line.startsWith('\n')
  54. || trimmed === ''
  55. ) {
  56. return;
  57. }
  58. domainSets.add(trimmed);
  59. });
  60. });
  61. // Copy reject_sukka.conf for backward compatibility
  62. await fse.copy(pathResolve(__dirname, '../Source/domainset/reject_sukka.conf'), pathResolve(__dirname, '../List/domainset/reject_sukka.conf'))
  63. previousSize = domainSets.size - previousSize;
  64. console.log(`Import ${previousSize} rules from reject_sukka.conf!`);
  65. // Read DOMAIN Keyword
  66. const domainKeywordsSet = new Set();
  67. const domainSuffixSet = new Set();
  68. await fsPromises.readFile(pathResolve(__dirname, '../List/non_ip/reject.conf'), { encoding: 'utf-8' }).then(data => {
  69. data.split('\n').forEach(line => {
  70. if (line.startsWith('DOMAIN-KEYWORD')) {
  71. const [, ...keywords] = line.split(',');
  72. domainKeywordsSet.add(keywords.join(',').trim());
  73. } else if (line.startsWith('DOMAIN-SUFFIX')) {
  74. const [, ...keywords] = line.split(',');
  75. domainSuffixSet.add(keywords.join(',').trim());
  76. }
  77. });
  78. });
  79. // Read Special Phishing Suffix list
  80. await fsPromises.readFile(pathResolve(__dirname, '../List/domainset/reject_phishing.conf'), { encoding: 'utf-8' }).then(data => {
  81. data.split('\n').forEach(line => {
  82. const trimmed = line.trim();
  83. if (
  84. line.startsWith('#')
  85. || line.startsWith(' ')
  86. || line.startsWith('\r')
  87. || line.startsWith('\n')
  88. || trimmed === ''
  89. ) {
  90. return;
  91. }
  92. domainSuffixSet.add(trimmed);
  93. });
  94. });
  95. console.log(`Import ${domainKeywordsSet.size} black keywords and ${domainSuffixSet.size} black suffixes!`);
  96. previousSize = domainSets.size;
  97. // Dedupe domainSets
  98. console.log(`Start deduping from black keywords/suffixes! (${previousSize})`);
  99. console.time(`* Dedupe from black keywords/suffixes`);
  100. for (const domain of domainSets) {
  101. let isTobeRemoved = false;
  102. for (const suffix of domainSuffixSet) {
  103. if (domain.endsWith(suffix)) {
  104. isTobeRemoved = true;
  105. break;
  106. }
  107. }
  108. if (!isTobeRemoved) {
  109. for (const keyword of domainKeywordsSet) {
  110. if (domain.includes(keyword)) {
  111. isTobeRemoved = true;
  112. break;
  113. }
  114. }
  115. }
  116. if (!isTobeRemoved) {
  117. if (isInWhiteList(domain)) {
  118. isTobeRemoved = true;
  119. }
  120. }
  121. if (isTobeRemoved) {
  122. domainSets.delete(domain);
  123. }
  124. }
  125. console.timeEnd(`* Dedupe from black keywords/suffixes`);
  126. console.log(`Deduped ${previousSize} - ${domainSets.size} = ${previousSize - domainSets.size} from black keywords and suffixes!`);
  127. previousSize = domainSets.size;
  128. // Dedupe domainSets
  129. console.log(`Start deduping! (${previousSize})`);
  130. const START_TIME = Date.now();
  131. const piscina = new Piscina({
  132. filename: pathResolve(__dirname, 'worker/build-reject-domainset-worker.js'),
  133. workerData: preprocessFullDomainSetBeforeUsedAsWorkerData([...domainSets]),
  134. idleTimeout: 50,
  135. minThreads: threads,
  136. maxThreads: threads
  137. });
  138. console.log(`Launching ${threads} threads...`)
  139. const tasksArray = Array.from(domainSets)
  140. .reduce((result, element, index) => {
  141. const chunk = index % threads;
  142. result[chunk] ??= [];
  143. result[chunk].push(element);
  144. return result;
  145. }, []);
  146. (
  147. await Promise.all(
  148. Array.from(domainSets)
  149. .reduce((result, element, index) => {
  150. const chunk = index % threads;
  151. result[chunk] ??= [];
  152. result[chunk].push(element);
  153. return result;
  154. }, [])
  155. .map(chunk => piscina.run({ chunk }, { name: 'dedupe' }))
  156. )
  157. ).forEach((result, taskIndex) => {
  158. const chunk = tasksArray[taskIndex];
  159. for (let i = 0, len = result.length; i < len; i++) {
  160. if (result[i]) {
  161. domainSets.delete(chunk[i]);
  162. }
  163. }
  164. });
  165. console.log(`* Dedupe from covered subdomain - ${(Date.now() - START_TIME) / 1000}s`);
  166. console.log(`Deduped ${previousSize - domainSets.size} rules!`);
  167. await Promise.all([
  168. fsPromises.writeFile(
  169. pathResolve(__dirname, '../List/domainset/reject.conf'),
  170. `${[...domainSets].join('\n')}\n`,
  171. { encoding: 'utf-8' }
  172. ),
  173. piscina.destroy()
  174. ]);
  175. console.timeEnd('Total Time - build-reject-domain-set');
  176. if (piscina.queueSize === 0) {
  177. process.exit(0);
  178. }
  179. })();
  180. function isInWhiteList (domain) {
  181. for (const white of filterRuleWhitelistDomainSets) {
  182. if (domain === white || domain.endsWith(white)) {
  183. return true;
  184. }
  185. }
  186. return false;
  187. }