parse-filter.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. import { NetworkFilter } from '@ghostery/adblocker';
  2. import { processLine } from './process-line';
  3. import tldts from 'tldts-experimental';
  4. import picocolors from 'picocolors';
  5. import { normalizeDomain } from './normalize-domain';
  6. import { deserializeArray, fsFetchCache, serializeArray, getFileContentHash } from './cache-filesystem';
  7. import type { Span } from '../trace';
  8. import { createRetrieKeywordFilter as createKeywordFilter } from 'foxts/retrie';
  9. import { looseTldtsOpt } from '../constants/loose-tldts-opt';
  10. import { identity } from 'foxts/identity';
  11. import { DEBUG_DOMAIN_TO_FIND } from '../constants/reject-data-source';
  12. import { noop } from 'foxts/noop';
  13. let foundDebugDomain = false;
  14. const temporaryBypass = typeof DEBUG_DOMAIN_TO_FIND === 'string';
  15. const onBlackFound = DEBUG_DOMAIN_TO_FIND
  16. ? (line: string, meta: string) => {
  17. if (line.includes(DEBUG_DOMAIN_TO_FIND!)) {
  18. console.warn(picocolors.red(meta), '(black)', line.replaceAll(DEBUG_DOMAIN_TO_FIND!, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  19. foundDebugDomain = true;
  20. }
  21. }
  22. : noop;
  23. const onWhiteFound = DEBUG_DOMAIN_TO_FIND
  24. ? (line: string, meta: string) => {
  25. if (line.includes(DEBUG_DOMAIN_TO_FIND!)) {
  26. console.warn(picocolors.red(meta), '(white)', line.replaceAll(DEBUG_DOMAIN_TO_FIND!, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  27. foundDebugDomain = true;
  28. }
  29. }
  30. : noop;
  31. function domainListLineCb(l: string, set: string[], includeAllSubDomain: boolean, meta: string) {
  32. let line = processLine(l);
  33. if (!line) return;
  34. line = line.toLowerCase();
  35. const domain = normalizeDomain(line);
  36. if (!domain) return;
  37. if (domain !== line) {
  38. console.log(
  39. picocolors.red('[process domain list]'),
  40. picocolors.gray(`line: ${line}`),
  41. picocolors.gray(`domain: ${domain}`),
  42. picocolors.gray(meta)
  43. );
  44. return;
  45. }
  46. onBlackFound(domain, meta);
  47. set.push(includeAllSubDomain ? `.${line}` : line);
  48. }
  49. export function processDomainLists(
  50. span: Span,
  51. domainListsUrl: string, mirrors: string[] | null, includeAllSubDomain = false,
  52. ttl: number | null = null, extraCacheKey: (input: string) => string = identity
  53. ) {
  54. return span.traceChild(`process domainlist: ${domainListsUrl}`).traceAsyncFn((childSpan) => fsFetchCache.applyWithHttp304AndMirrors<string[]>(
  55. domainListsUrl,
  56. mirrors ?? [],
  57. extraCacheKey(getFileContentHash(__filename)),
  58. (text) => {
  59. const domainSets: string[] = [];
  60. const filterRules = text.split('\n');
  61. childSpan.traceChild('parse domain list').traceSyncFn(() => {
  62. for (let i = 0, len = filterRules.length; i < len; i++) {
  63. domainListLineCb(filterRules[i], domainSets, includeAllSubDomain, domainListsUrl);
  64. }
  65. });
  66. return domainSets;
  67. },
  68. {
  69. ttl,
  70. temporaryBypass,
  71. serializer: serializeArray,
  72. deserializer: deserializeArray
  73. }
  74. ));
  75. }
  76. function hostsLineCb(l: string, set: string[], includeAllSubDomain: boolean, meta: string) {
  77. const line = processLine(l);
  78. if (!line) {
  79. return;
  80. }
  81. const _domain = line.split(/\s/)[1]?.trim();
  82. if (!_domain) {
  83. return;
  84. }
  85. const domain = normalizeDomain(_domain);
  86. if (!domain) {
  87. return;
  88. }
  89. onBlackFound(domain, meta);
  90. set.push(includeAllSubDomain ? `.${domain}` : domain);
  91. }
  92. export function processHosts(
  93. span: Span,
  94. hostsUrl: string, mirrors: string[] | null, includeAllSubDomain = false,
  95. ttl: number | null = null, extraCacheKey: (input: string) => string = identity
  96. ) {
  97. return span.traceChild(`processhosts: ${hostsUrl}`).traceAsyncFn((childSpan) => fsFetchCache.applyWithHttp304AndMirrors<string[]>(
  98. hostsUrl,
  99. mirrors ?? [],
  100. extraCacheKey(getFileContentHash(__filename)),
  101. (text) => {
  102. const domainSets: string[] = [];
  103. const filterRules = text.split('\n');
  104. childSpan.traceChild('parse hosts').traceSyncFn(() => {
  105. for (let i = 0, len = filterRules.length; i < len; i++) {
  106. hostsLineCb(filterRules[i], domainSets, includeAllSubDomain, hostsUrl);
  107. }
  108. });
  109. return domainSets;
  110. },
  111. {
  112. ttl,
  113. temporaryBypass,
  114. serializer: serializeArray,
  115. deserializer: deserializeArray
  116. }
  117. ));
  118. }
  119. const enum ParseType {
  120. WhiteIncludeSubdomain = 0,
  121. WhiteAbsolute = -1,
  122. BlackAbsolute = 1,
  123. BlackIncludeSubdomain = 2,
  124. ErrorMessage = 10,
  125. Null = 1000,
  126. NotParsed = 2000
  127. }
  128. export { type ParseType };
  129. export async function processFilterRules(
  130. parentSpan: Span,
  131. filterRulesUrl: string,
  132. fallbackUrls?: string[] | null,
  133. ttl: number | null = null,
  134. allowThirdParty = false
  135. ): Promise<{ white: string[], black: string[], foundDebugDomain: boolean }> {
  136. const [white, black, warningMessages] = await parentSpan.traceChild(`process filter rules: ${filterRulesUrl}`).traceAsyncFn((span) => fsFetchCache.applyWithHttp304AndMirrors<Readonly<[white: string[], black: string[], warningMessages: string[]]>>(
  137. filterRulesUrl,
  138. fallbackUrls ?? [],
  139. getFileContentHash(__filename),
  140. (text) => {
  141. const whitelistDomainSets = new Set<string>();
  142. const blacklistDomainSets = new Set<string>();
  143. const warningMessages: string[] = [];
  144. const MUTABLE_PARSE_LINE_RESULT: [string, ParseType] = ['', ParseType.NotParsed];
  145. /**
  146. * @param {string} line
  147. */
  148. const lineCb = (line: string) => {
  149. const result = parse(line, MUTABLE_PARSE_LINE_RESULT, allowThirdParty);
  150. const flag = result[1];
  151. if (flag === ParseType.NotParsed) {
  152. throw new Error(`Didn't parse line: ${line}`);
  153. }
  154. if (flag === ParseType.Null) {
  155. return;
  156. }
  157. const hostname = result[0];
  158. if (flag === ParseType.WhiteIncludeSubdomain || flag === ParseType.WhiteAbsolute) {
  159. onWhiteFound(hostname, filterRulesUrl);
  160. } else {
  161. onBlackFound(hostname, filterRulesUrl);
  162. }
  163. switch (flag) {
  164. case ParseType.WhiteIncludeSubdomain:
  165. if (hostname[0] === '.') {
  166. whitelistDomainSets.add(hostname);
  167. } else {
  168. whitelistDomainSets.add(`.${hostname}`);
  169. }
  170. break;
  171. case ParseType.WhiteAbsolute:
  172. whitelistDomainSets.add(hostname);
  173. break;
  174. case ParseType.BlackIncludeSubdomain:
  175. if (hostname[0] === '.') {
  176. blacklistDomainSets.add(hostname);
  177. } else {
  178. blacklistDomainSets.add(`.${hostname}`);
  179. }
  180. break;
  181. case ParseType.BlackAbsolute:
  182. blacklistDomainSets.add(hostname);
  183. break;
  184. case ParseType.ErrorMessage:
  185. warningMessages.push(hostname);
  186. break;
  187. default:
  188. break;
  189. }
  190. };
  191. const filterRules = text.split('\n');
  192. span.traceChild('parse adguard filter').traceSyncFn(() => {
  193. for (let i = 0, len = filterRules.length; i < len; i++) {
  194. lineCb(filterRules[i]);
  195. }
  196. });
  197. return [
  198. Array.from(whitelistDomainSets),
  199. Array.from(blacklistDomainSets),
  200. warningMessages
  201. ] as const;
  202. },
  203. {
  204. ttl,
  205. temporaryBypass,
  206. serializer: JSON.stringify,
  207. deserializer: JSON.parse
  208. }
  209. ));
  210. for (let i = 0, len = warningMessages.length; i < len; i++) {
  211. console.warn(
  212. picocolors.yellow(warningMessages[i]),
  213. picocolors.gray(picocolors.underline(filterRulesUrl))
  214. );
  215. }
  216. console.log(
  217. picocolors.gray('[process filter]'),
  218. picocolors.gray(filterRulesUrl),
  219. picocolors.gray(`white: ${white.length}`),
  220. picocolors.gray(`black: ${black.length}`)
  221. );
  222. return {
  223. white,
  224. black,
  225. foundDebugDomain
  226. };
  227. }
  228. // const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder|\$cname)/;
  229. // cname exceptional filter can not be parsed by NetworkFilter
  230. // Surge / Clash can't handle CNAME either, so we just ignore them
  231. const kwfilter = createKeywordFilter([
  232. '!',
  233. '?',
  234. '*',
  235. '[',
  236. '(',
  237. ']',
  238. ')',
  239. ',',
  240. '#',
  241. '%',
  242. '&',
  243. '=',
  244. '~',
  245. // special modifier
  246. '$popup',
  247. '$removeparam',
  248. '$popunder',
  249. '$cname',
  250. '$frame',
  251. // some bad syntax
  252. '^popup'
  253. ]);
  254. export function parse($line: string, result: [string, ParseType], allowThirdParty: boolean): [hostname: string, flag: ParseType] {
  255. if (
  256. // doesn't include
  257. !$line.includes('.') // rule with out dot can not be a domain
  258. // includes
  259. || kwfilter($line)
  260. ) {
  261. result[1] = ParseType.Null;
  262. return result;
  263. }
  264. const line = $line.trim();
  265. if (line.length === 0) {
  266. result[1] = ParseType.Null;
  267. return result;
  268. }
  269. const firstCharCode = line.charCodeAt(0);
  270. const lastCharCode = line.charCodeAt(line.length - 1);
  271. if (
  272. firstCharCode === 47 // 47 `/`
  273. // ends with
  274. // _160-600.
  275. // -detect-adblock.
  276. // _web-advert.
  277. || lastCharCode === 46 // 46 `.`, line.endsWith('.')
  278. || lastCharCode === 45 // 45 `-`, line.endsWith('-')
  279. || lastCharCode === 95 // 95 `_`, line.endsWith('_')
  280. // || line.includes('$popup')
  281. // || line.includes('$removeparam')
  282. // || line.includes('$popunder')
  283. ) {
  284. result[1] = ParseType.Null;
  285. return result;
  286. }
  287. if ((line.includes('/') || line.includes(':')) && !line.includes('://')) {
  288. result[1] = ParseType.Null;
  289. return result;
  290. }
  291. const filter = NetworkFilter.parse(line);
  292. if (filter) {
  293. if (
  294. // filter.isCosmeticFilter() // always false
  295. // filter.isNetworkFilter() // always true
  296. filter.isElemHide()
  297. || filter.isGenericHide()
  298. || filter.isSpecificHide()
  299. || filter.isRedirect()
  300. || filter.isRedirectRule()
  301. || filter.hasDomains()
  302. || filter.isCSP() // must not be csp rule
  303. || (!filter.fromHttp() && !filter.fromHttps())
  304. ) {
  305. // not supported type
  306. result[1] = ParseType.Null;
  307. return result;
  308. }
  309. if (
  310. !filter.fromAny()
  311. // $image, $websocket, $xhr this are all non-any
  312. && !filter.fromDocument() // $document, $doc
  313. // && !filter.fromSubdocument() // $subdocument, $subdoc
  314. ) {
  315. result[1] = ParseType.Null;
  316. return result;
  317. }
  318. if (
  319. filter.hostname // filter.hasHostname() // must have
  320. && filter.isPlain() // isPlain() === !isRegex()
  321. && (!filter.isFullRegex())
  322. ) {
  323. const hostname = normalizeDomain(filter.hostname);
  324. if (!hostname) {
  325. result[1] = ParseType.Null;
  326. return result;
  327. }
  328. // |: filter.isHostnameAnchor(),
  329. // |: filter.isLeftAnchor(),
  330. // |https://: !filter.isHostnameAnchor() && (filter.fromHttps() || filter.fromHttp())
  331. const isIncludeAllSubDomain = filter.isHostnameAnchor();
  332. if (filter.isException() || filter.isBadFilter()) {
  333. result[0] = hostname;
  334. result[1] = isIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  335. return result;
  336. }
  337. const _1p = filter.firstParty();
  338. const _3p = filter.thirdParty();
  339. if (_1p) { // first party is true
  340. if (_3p) { // third party is also true
  341. result[0] = hostname;
  342. result[1] = isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  343. return result;
  344. }
  345. result[1] = ParseType.Null;
  346. return result;
  347. }
  348. if (_3p) {
  349. if (allowThirdParty) {
  350. result[0] = hostname;
  351. result[1] = isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  352. return result;
  353. }
  354. result[1] = ParseType.Null;
  355. return result;
  356. }
  357. }
  358. }
  359. /**
  360. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  361. *
  362. * We can still salvage some of them by removing modifiers
  363. */
  364. let sliceStart = 0;
  365. let sliceEnd = 0;
  366. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  367. // We now need to "salvage" the line as much as possible
  368. let white = false;
  369. let includeAllSubDomain = false;
  370. if (
  371. firstCharCode === 64 // 64 `@`
  372. && line.charCodeAt(1) === 64 // 64 `@`
  373. ) {
  374. sliceStart += 2;
  375. white = true;
  376. includeAllSubDomain = true;
  377. }
  378. /**
  379. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  380. * "$genericblock`" is also not supported by NetworkFilter, see:
  381. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  382. *
  383. * `@@||cmechina.net^$genericblock`
  384. * `@@|ftp.bmp.ovh^|`
  385. * `@@|adsterra.com^|`
  386. * `@@.atlassian.net$document`
  387. * `@@||ad.alimama.com^$genericblock`
  388. */
  389. switch (line.charCodeAt(sliceStart)) {
  390. case 124: /** | */
  391. // line.startsWith('@@|') || line.startsWith('|')
  392. sliceStart += 1;
  393. includeAllSubDomain = false;
  394. if (line[sliceStart] === '|') { // line.startsWith('@@||') || line.startsWith('||')
  395. sliceStart += 1;
  396. includeAllSubDomain = true;
  397. }
  398. break;
  399. case 46: { /** | */ // line.startsWith('@@.') || line.startsWith('.')
  400. /**
  401. * `.ay.delivery^`
  402. * `.m.bookben.com^`
  403. * `.wap.x4399.com^`
  404. */
  405. sliceStart += 1;
  406. includeAllSubDomain = true;
  407. break;
  408. }
  409. default:
  410. break;
  411. }
  412. switch (line.charCodeAt(sliceStart)) {
  413. case 58: { /** : */
  414. /**
  415. * `@@://googleadservices.com^|`
  416. * `@@://www.googleadservices.com^|`
  417. * `://mine.torrent.pw^`
  418. * `://say.ac^`
  419. */
  420. if (line[sliceStart + 1] === '/' && line[sliceStart + 2] === '/') {
  421. includeAllSubDomain = false;
  422. sliceStart += 3;
  423. }
  424. break;
  425. }
  426. case 104: { /** h */
  427. /** |http://x.o2.pl^ */
  428. if (line.startsWith('http://', sliceStart)) {
  429. sliceStart += 7;
  430. } else if (line.startsWith('https://', sliceStart)) {
  431. sliceStart += 8;
  432. }
  433. break;
  434. }
  435. default:
  436. break;
  437. }
  438. const indexOfDollar = line.indexOf('$', sliceStart);
  439. if (indexOfDollar > -1) {
  440. sliceEnd = indexOfDollar - line.length;
  441. }
  442. /*
  443. * We skip third-party and frame rules, as Surge / Clash can't handle them
  444. *
  445. * `.sharecounter.$third-party`
  446. * `.bbelements.com^$third-party`
  447. * `://o0e.ru^$third-party`
  448. * `.1.1.1.l80.js^$third-party`
  449. */
  450. if (
  451. !allowThirdParty
  452. && (
  453. line.includes('third-party', indexOfDollar + 1)
  454. || line.includes('3p', indexOfDollar + 1)
  455. )
  456. ) {
  457. result[1] = ParseType.Null;
  458. return result;
  459. }
  460. if (line.includes('badfilter', indexOfDollar + 1)) {
  461. white = true;
  462. }
  463. if (line.includes('all', indexOfDollar + 1)) {
  464. includeAllSubDomain = true;
  465. }
  466. /**
  467. * `_vmind.qqvideo.tc.qq.com^`
  468. * `arketing.indianadunes.com^`
  469. * `charlestownwyllie.oaklawnnonantum.com^`
  470. * `-telemetry.officeapps.live.com^`
  471. * `-tracker.biliapi.net`
  472. * `-logging.nextmedia.com`
  473. * `_social_tracking.js^`
  474. */
  475. if (line.charCodeAt(line.length + sliceEnd - 1) === 94) { // 94 `^`
  476. /** line.endsWith('^') */
  477. sliceEnd -= 1;
  478. } else if (line.charCodeAt(line.length + sliceEnd - 1) === 124) { // 124 `|`
  479. /** line.endsWith('|') */
  480. sliceEnd -= 1;
  481. if (line.charCodeAt(line.length + sliceEnd - 1) === 94) { // 94 `^`
  482. /** line.endsWith('^|') */
  483. sliceEnd -= 1;
  484. }
  485. } else if (line.charCodeAt(line.length + sliceEnd - 1) === 46) { // 46 `.`
  486. /** line.endsWith('.') */
  487. sliceEnd -= 1;
  488. }
  489. const sliced = (sliceStart > 0 || sliceEnd < 0) ? line.slice(sliceStart, sliceEnd === 0 ? undefined : sliceEnd) : line;
  490. if (sliced.charCodeAt(0) === 45 /* - */) {
  491. // line.startsWith('-') is not a valid domain
  492. result[1] = ParseType.ErrorMessage;
  493. result[0] = `[parse-filter E0001] (${white ? 'white' : 'black'}) invalid domain: ${JSON.stringify({
  494. line, sliced, sliceStart, sliceEnd
  495. })}`;
  496. return result;
  497. }
  498. const suffix = tldts.getPublicSuffix(sliced, looseTldtsOpt);
  499. if (!suffix) {
  500. // This exclude domain-like resource like `_social_tracking.js^`
  501. result[1] = ParseType.Null;
  502. return result;
  503. }
  504. const domain = normalizeDomain(sliced);
  505. if (domain && domain === sliced) {
  506. result[0] = domain;
  507. if (white) {
  508. result[1] = includeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  509. } else {
  510. result[1] = includeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  511. }
  512. return result;
  513. }
  514. result[0] = `[parse-filter E0010] (${white ? 'white' : 'black'}) invalid domain: ${JSON.stringify({
  515. line, domain, suffix, sliced, sliceStart, sliceEnd
  516. })}`;
  517. result[1] = ParseType.ErrorMessage;
  518. return result;
  519. }