parse-filter.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. // @ts-check
  2. import { fetchRemoteTextByLine } from './fetch-text-by-line';
  3. import { NetworkFilter } from '@cliqz/adblocker';
  4. import { processLine } from './process-line';
  5. import { getGorhillPublicSuffixPromise } from './get-gorhill-publicsuffix';
  6. import type { PublicSuffixList } from '@gorhill/publicsuffixlist';
  7. import picocolors from 'picocolors';
  8. import { normalizeDomain } from './normalize-domain';
  9. import { fetchAssets } from './fetch-assets';
  10. import { deserializeSet, fsFetchCache, serializeSet } from './cache-filesystem';
  11. import type { Span } from '../trace';
  12. import createKeywordFilter from './aho-corasick';
  13. const DEBUG_DOMAIN_TO_FIND: string | null = null; // example.com | null
  14. let foundDebugDomain = false;
  15. const temporaryBypass = DEBUG_DOMAIN_TO_FIND !== null;
  16. export function processDomainLists(span: Span, domainListsUrl: string, includeAllSubDomain = false, ttl: number | null = null) {
  17. return span.traceChild(`process domainlist: ${domainListsUrl}`).traceAsyncFn(() => fsFetchCache.apply(
  18. domainListsUrl,
  19. async () => {
  20. const domainSets = new Set<string>();
  21. for await (const line of await fetchRemoteTextByLine(domainListsUrl)) {
  22. let domainToAdd = processLine(line);
  23. if (!domainToAdd) continue;
  24. domainToAdd = normalizeDomain(domainToAdd);
  25. if (!domainToAdd) continue;
  26. if (DEBUG_DOMAIN_TO_FIND && domainToAdd.includes(DEBUG_DOMAIN_TO_FIND)) {
  27. console.warn(picocolors.red(domainListsUrl), '(black)', domainToAdd.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  28. foundDebugDomain = true;
  29. }
  30. domainSets.add(includeAllSubDomain ? `.${domainToAdd}` : domainToAdd);
  31. }
  32. return domainSets;
  33. },
  34. {
  35. ttl,
  36. temporaryBypass,
  37. serializer: serializeSet,
  38. deserializer: deserializeSet
  39. }
  40. ));
  41. }
  42. const hostsLineCb = (l: string, set: Set<string>, includeAllSubDomain: boolean, meta: string) => {
  43. const line = processLine(l);
  44. if (!line) {
  45. return;
  46. }
  47. const _domain = line.split(/\s/)[1]?.trim();
  48. if (!_domain) {
  49. return;
  50. }
  51. const domain = normalizeDomain(_domain);
  52. if (!domain) {
  53. return;
  54. }
  55. if (DEBUG_DOMAIN_TO_FIND && domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  56. console.warn(picocolors.red(meta), '(black)', domain.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  57. foundDebugDomain = true;
  58. }
  59. set.add(includeAllSubDomain ? `.${domain}` : domain);
  60. };
  61. export function processHosts(span: Span, hostsUrl: string, mirrors: string[] | null, includeAllSubDomain = false, ttl: number | null = null) {
  62. const domainSets = new Set<string>();
  63. return span.traceChild(`processhosts: ${hostsUrl}`).traceAsyncFn((childSpan) => fsFetchCache.apply(
  64. hostsUrl,
  65. async () => {
  66. if (mirrors == null || mirrors.length === 0) {
  67. for await (const l of await fetchRemoteTextByLine(hostsUrl)) {
  68. hostsLineCb(l, domainSets, includeAllSubDomain, hostsUrl);
  69. }
  70. } else {
  71. const filterRules = await childSpan
  72. .traceChild('download hosts')
  73. .traceAsyncFn(() => fetchAssets(hostsUrl, mirrors).then(text => text.split('\n')));
  74. childSpan.traceChild('parse hosts').traceSyncFn(() => {
  75. for (let i = 0, len = filterRules.length; i < len; i++) {
  76. hostsLineCb(filterRules[i], domainSets, includeAllSubDomain, hostsUrl);
  77. }
  78. });
  79. }
  80. console.log(picocolors.gray('[process hosts]'), picocolors.gray(hostsUrl), picocolors.gray(domainSets.size));
  81. return domainSets;
  82. },
  83. {
  84. ttl,
  85. temporaryBypass,
  86. serializer: serializeSet,
  87. deserializer: deserializeSet
  88. }
  89. ));
  90. }
  91. // eslint-disable-next-line sukka-ts/no-const-enum -- bun bundler is smart, maybe?
  92. const enum ParseType {
  93. WhiteIncludeSubdomain = 0,
  94. WhiteAbsolute = -1,
  95. BlackAbsolute = 1,
  96. BlackIncludeSubdomain = 2,
  97. ErrorMessage = 10
  98. }
  99. export async function processFilterRules(
  100. parentSpan: Span,
  101. filterRulesUrl: string,
  102. fallbackUrls?: readonly string[] | undefined | null,
  103. ttl: number | null = null
  104. ): Promise<{ white: string[], black: string[], foundDebugDomain: boolean }> {
  105. const [white, black, warningMessages] = await parentSpan.traceChild(`process filter rules: ${filterRulesUrl}`).traceAsyncFn((span) => fsFetchCache.apply<Readonly<[
  106. white: string[],
  107. black: string[],
  108. warningMessages: string[]
  109. ]>>(
  110. filterRulesUrl,
  111. async () => {
  112. const whitelistDomainSets = new Set<string>();
  113. const blacklistDomainSets = new Set<string>();
  114. const warningMessages: string[] = [];
  115. const gorhillPromise = getGorhillPublicSuffixPromise();
  116. const peekedGorhill = Bun.peek(gorhillPromise);
  117. const gorhill = peekedGorhill === gorhillPromise
  118. ? await span.traceChild('get gorhill').tracePromise(gorhillPromise)
  119. : (peekedGorhill as PublicSuffixList);
  120. /**
  121. * @param {string} line
  122. */
  123. const lineCb = (line: string) => {
  124. const result = parse(line, gorhill);
  125. if (!result) {
  126. return;
  127. }
  128. const flag = result[1];
  129. const hostname = result[0];
  130. if (DEBUG_DOMAIN_TO_FIND) {
  131. if (hostname.includes(DEBUG_DOMAIN_TO_FIND)) {
  132. console.warn(
  133. picocolors.red(filterRulesUrl),
  134. flag === ParseType.WhiteIncludeSubdomain || flag === ParseType.WhiteAbsolute
  135. ? '(white)'
  136. : '(black)',
  137. hostname.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND))
  138. );
  139. foundDebugDomain = true;
  140. }
  141. }
  142. switch (flag) {
  143. case ParseType.WhiteIncludeSubdomain:
  144. if (hostname[0] !== '.') {
  145. whitelistDomainSets.add(`.${hostname}`);
  146. } else {
  147. whitelistDomainSets.add(hostname);
  148. }
  149. break;
  150. case ParseType.WhiteAbsolute:
  151. whitelistDomainSets.add(hostname);
  152. break;
  153. case ParseType.BlackAbsolute:
  154. blacklistDomainSets.add(hostname);
  155. break;
  156. case ParseType.BlackIncludeSubdomain:
  157. if (hostname[0] !== '.') {
  158. blacklistDomainSets.add(`.${hostname}`);
  159. } else {
  160. blacklistDomainSets.add(hostname);
  161. }
  162. break;
  163. case ParseType.ErrorMessage:
  164. warningMessages.push(hostname);
  165. break;
  166. default:
  167. break;
  168. }
  169. };
  170. if (!fallbackUrls || fallbackUrls.length === 0) {
  171. for await (const line of await fetchRemoteTextByLine(filterRulesUrl)) {
  172. // don't trim here
  173. lineCb(line);
  174. }
  175. } else {
  176. const filterRules = await span.traceChild('download adguard filter').traceAsyncFn(() => {
  177. return fetchAssets(filterRulesUrl, fallbackUrls).then(text => text.split('\n'));
  178. });
  179. span.traceChild('parse adguard filter').traceSyncFn(() => {
  180. for (let i = 0, len = filterRules.length; i < len; i++) {
  181. lineCb(filterRules[i]);
  182. }
  183. });
  184. }
  185. return [
  186. Array.from(whitelistDomainSets),
  187. Array.from(blacklistDomainSets),
  188. warningMessages
  189. ] as const;
  190. },
  191. {
  192. ttl,
  193. temporaryBypass,
  194. serializer: JSON.stringify,
  195. deserializer: JSON.parse
  196. }
  197. ));
  198. for (let i = 0, len = warningMessages.length; i < len; i++) {
  199. console.warn(
  200. picocolors.yellow(warningMessages[i]),
  201. picocolors.gray(picocolors.underline(filterRulesUrl))
  202. );
  203. }
  204. console.log(
  205. picocolors.gray('[process filter]'),
  206. picocolors.gray(filterRulesUrl),
  207. picocolors.gray(`white: ${white.length}`),
  208. picocolors.gray(`black: ${black.length}`)
  209. );
  210. return {
  211. white,
  212. black,
  213. foundDebugDomain
  214. };
  215. }
  216. // const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder|\$cname)/;
  217. // cname exceptional filter can not be parsed by NetworkFilter
  218. // Surge / Clash can't handle CNAME either, so we just ignore them
  219. const kwfilter = createKeywordFilter([
  220. '!',
  221. '?',
  222. '*',
  223. '[',
  224. '(',
  225. ']',
  226. ')',
  227. ',',
  228. '#',
  229. '%',
  230. '&',
  231. '=',
  232. '~',
  233. // special modifier
  234. '$popup',
  235. '$removeparam',
  236. '$popunder',
  237. '$cname'
  238. ]);
  239. function parse($line: string, gorhill: PublicSuffixList): null | [hostname: string, flag: ParseType] {
  240. if (
  241. // doesn't include
  242. !$line.includes('.') // rule with out dot can not be a domain
  243. // includes
  244. || kwfilter($line)
  245. ) {
  246. return null;
  247. }
  248. const line = $line.trim();
  249. /** @example line.length */
  250. const len = line.length;
  251. if (len === 0) {
  252. return null;
  253. }
  254. const firstCharCode = line[0].charCodeAt(0);
  255. const lastCharCode = line[len - 1].charCodeAt(0);
  256. if (
  257. firstCharCode === 47 // 47 `/`
  258. // ends with
  259. || lastCharCode === 46 // 46 `.`, line.endsWith('.')
  260. || lastCharCode === 45 // 45 `-`, line.endsWith('-')
  261. || lastCharCode === 95 // 95 `_`, line.endsWith('_')
  262. // || line.includes('$popup')
  263. // || line.includes('$removeparam')
  264. // || line.includes('$popunder')
  265. ) {
  266. return null;
  267. }
  268. if ((line.includes('/') || line.includes(':')) && !line.includes('://')) {
  269. return null;
  270. }
  271. const filter = NetworkFilter.parse(line);
  272. if (filter) {
  273. if (
  274. // filter.isCosmeticFilter() // always false
  275. // filter.isNetworkFilter() // always true
  276. filter.isElemHide()
  277. || filter.isGenericHide()
  278. || filter.isSpecificHide()
  279. || filter.isRedirect()
  280. || filter.isRedirectRule()
  281. || filter.hasDomains()
  282. || filter.isCSP() // must not be csp rule
  283. || (!filter.fromAny() && !filter.fromDocument())
  284. ) {
  285. // not supported type
  286. return null;
  287. }
  288. if (
  289. filter.hostname // filter.hasHostname() // must have
  290. && filter.isPlain() // isPlain() === !isRegex()
  291. && (!filter.isFullRegex())
  292. ) {
  293. const hostname = normalizeDomain(filter.hostname);
  294. if (!hostname) {
  295. return null;
  296. }
  297. // |: filter.isHostnameAnchor(),
  298. // |: filter.isLeftAnchor(),
  299. // |https://: !filter.isHostnameAnchor() && (filter.fromHttps() || filter.fromHttp())
  300. const isIncludeAllSubDomain = filter.isHostnameAnchor();
  301. if (filter.isException() || filter.isBadFilter()) {
  302. return [hostname, isIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute];
  303. }
  304. const _1p = filter.firstParty();
  305. const _3p = filter.thirdParty();
  306. if (_1p) {
  307. if (_1p === _3p) {
  308. return [hostname, isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute];
  309. }
  310. return null;
  311. }
  312. if (_3p) {
  313. return null;
  314. }
  315. }
  316. }
  317. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  318. // We now need to "salvage" the line as much as possible
  319. /*
  320. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  321. * We first skip third-party and frame rules, as Surge / Clash can't handle them
  322. *
  323. * `.sharecounter.$third-party`
  324. * `.bbelements.com^$third-party`
  325. * `://o0e.ru^$third-party`
  326. * `.1.1.1.l80.js^$third-party`
  327. */
  328. if (line.includes('$third-party') || line.includes('$frame')) {
  329. return null;
  330. }
  331. /** @example line.endsWith('^') */
  332. const lineEndsWithCaret = lastCharCode === 94; // lastChar === '^';
  333. /** @example line.endsWith('^|') */
  334. const lineEndsWithCaretVerticalBar = (lastCharCode === 124 /** lastChar === '|' */) && line[len - 2] === '^';
  335. /** @example line.endsWith('^') || line.endsWith('^|') */
  336. const lineEndsWithCaretOrCaretVerticalBar = lineEndsWithCaret || lineEndsWithCaretVerticalBar;
  337. // whitelist (exception)
  338. if (
  339. firstCharCode === 64 // 64 `@`
  340. && line[1] === '@'
  341. ) {
  342. let whiteIncludeAllSubDomain = true;
  343. /**
  344. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  345. * "$genericblock`" is also not supported by NetworkFilter, see:
  346. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  347. *
  348. * `@@||cmechina.net^$genericblock`
  349. * `@@|ftp.bmp.ovh^|`
  350. * `@@|adsterra.com^|`
  351. * `@@.atlassian.net$document`
  352. * `@@||ad.alimama.com^$genericblock`
  353. */
  354. let sliceStart = 0;
  355. let sliceEnd: number | undefined;
  356. if (line[2] === '|') { // line.startsWith('@@|')
  357. sliceStart = 3;
  358. whiteIncludeAllSubDomain = false;
  359. if (line[3] === '|') { // line.startsWith('@@||')
  360. sliceStart = 4;
  361. whiteIncludeAllSubDomain = true;
  362. }
  363. } else if (line[2] === '.') { // line.startsWith('@@.')
  364. sliceStart = 3;
  365. whiteIncludeAllSubDomain = true;
  366. } else if (
  367. /**
  368. * line.startsWith('@@://')
  369. *
  370. * `@@://googleadservices.com^|`
  371. * `@@://www.googleadservices.com^|`
  372. */
  373. line[2] === ':' && line[3] === '/' && line[4] === '/'
  374. ) {
  375. whiteIncludeAllSubDomain = false;
  376. sliceStart = 5;
  377. }
  378. if (lineEndsWithCaretOrCaretVerticalBar) {
  379. sliceEnd = -2;
  380. } else if (line.endsWith('$genericblock')) {
  381. sliceEnd = -13;
  382. if (line[len - 14] === '^') { // line.endsWith('^$genericblock')
  383. sliceEnd = -14;
  384. }
  385. } else if (line.endsWith('$document')) {
  386. sliceEnd = -9;
  387. if (line[len - 10] === '^') { // line.endsWith('^$document')
  388. sliceEnd = -10;
  389. }
  390. }
  391. if (sliceStart !== 0 || sliceEnd !== undefined) {
  392. const sliced = line.slice(sliceStart, sliceEnd);
  393. const domain = normalizeDomain(sliced);
  394. if (domain) {
  395. return [domain, whiteIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute];
  396. }
  397. return [
  398. `[parse-filter E0001] (white) invalid domain: ${JSON.stringify({
  399. line, sliced, sliceStart, sliceEnd
  400. })}`,
  401. ParseType.ErrorMessage
  402. ];
  403. }
  404. return [
  405. `[parse-filter E0006] (white) failed to parse: ${JSON.stringify({
  406. line, sliceStart, sliceEnd
  407. })}`,
  408. ParseType.ErrorMessage
  409. ];
  410. }
  411. if (
  412. // 124 `|`
  413. // line.startsWith('|')
  414. firstCharCode === 124
  415. && lineEndsWithCaretOrCaretVerticalBar
  416. ) {
  417. /**
  418. * Some malformed filters can not be parsed by NetworkFilter:
  419. *
  420. * `||smetrics.teambeachbody.com^.com^`
  421. * `||solutions.|pages.indigovision.com^`
  422. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  423. * `app-uat.latrobehealth.com.au^predirect.snapdeal.com`
  424. */
  425. const includeAllSubDomain = line[1] === '|';
  426. const sliceStart = includeAllSubDomain ? 2 : 1;
  427. const sliceEnd = lineEndsWithCaret
  428. ? -1
  429. : (lineEndsWithCaretVerticalBar ? -2 : undefined);
  430. const sliced = line.slice(sliceStart, sliceEnd); // we already make sure line startsWith "|"
  431. const domain = normalizeDomain(sliced);
  432. if (domain) {
  433. return [domain, includeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute];
  434. }
  435. return [
  436. `[parse-filter E0002] (black) invalid domain: ${sliced}`,
  437. ParseType.ErrorMessage
  438. ];
  439. }
  440. const lineStartsWithSingleDot = firstCharCode === 46; // 46 `.`
  441. if (
  442. lineStartsWithSingleDot
  443. && lineEndsWithCaretOrCaretVerticalBar
  444. ) {
  445. /**
  446. * `.ay.delivery^`
  447. * `.m.bookben.com^`
  448. * `.wap.x4399.com^`
  449. */
  450. const sliced = line.slice(
  451. 1, // remove prefix dot
  452. lineEndsWithCaret // replaceAll('^', '')
  453. ? -1
  454. : (lineEndsWithCaretVerticalBar ? -2 : undefined) // replace('^|', '')
  455. );
  456. const suffix = gorhill.getPublicSuffix(sliced);
  457. if (!gorhill.suffixInPSL(suffix)) {
  458. // This exclude domain-like resource like `1.1.4.514.js`
  459. return null;
  460. }
  461. const domain = normalizeDomain(sliced);
  462. if (domain) {
  463. return [domain, ParseType.BlackIncludeSubdomain];
  464. }
  465. return [
  466. `[paparse-filter E0003] (black) invalid domain: ${sliced}`,
  467. ParseType.ErrorMessage
  468. ];
  469. }
  470. /**
  471. * `|http://x.o2.pl^`
  472. * `://mine.torrent.pw^`
  473. * `://say.ac^`
  474. */
  475. if (lineEndsWithCaretOrCaretVerticalBar) {
  476. let sliceStart = 0;
  477. let sliceEnd;
  478. if (lineEndsWithCaret) { // line.endsWith('^')
  479. sliceEnd = -1;
  480. } else if (lineEndsWithCaretVerticalBar) { // line.endsWith('^|')
  481. sliceEnd = -2;
  482. }
  483. if (line.startsWith('://')) {
  484. sliceStart = 3;
  485. } else if (line.startsWith('http://')) {
  486. sliceStart = 7;
  487. } else if (line.startsWith('https://')) {
  488. sliceStart = 8;
  489. } else if (line.startsWith('|http://')) {
  490. sliceStart = 8;
  491. } else if (line.startsWith('|https://')) {
  492. sliceStart = 9;
  493. }
  494. if (sliceStart !== 0 || sliceEnd !== undefined) {
  495. const sliced = line.slice(sliceStart, sliceEnd);
  496. const domain = normalizeDomain(sliced);
  497. if (domain) {
  498. return [domain, ParseType.BlackIncludeSubdomain];
  499. }
  500. return [
  501. `[parse-filter E0004] (black) invalid domain: ${JSON.stringify({
  502. line, sliced, sliceStart, sliceEnd
  503. })}`,
  504. ParseType.ErrorMessage
  505. ];
  506. }
  507. }
  508. /**
  509. * `_vmind.qqvideo.tc.qq.com^`
  510. * `arketing.indianadunes.com^`
  511. * `charlestownwyllie.oaklawnnonantum.com^`
  512. * `-telemetry.officeapps.live.com^`
  513. * `-tracker.biliapi.net`
  514. * `-logging.nextmedia.com`
  515. * `_social_tracking.js^`
  516. */
  517. if (
  518. firstCharCode !== 124 // 124 `|`
  519. && lastCharCode === 94 // 94 `^`
  520. ) {
  521. const _domain = line.slice(0, -1);
  522. const suffix = gorhill.getPublicSuffix(_domain);
  523. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  524. // This exclude domain-like resource like `_social_tracking.js^`
  525. return null;
  526. }
  527. const domain = normalizeDomain(_domain);
  528. if (domain) {
  529. return [domain, ParseType.BlackAbsolute];
  530. }
  531. return [
  532. `[parse-filter E0005] (black) invalid domain: ${_domain}`,
  533. ParseType.ErrorMessage
  534. ];
  535. }
  536. // Possibly that entire rule is domain
  537. /**
  538. * lineStartsWithSingleDot:
  539. *
  540. * `.cookielaw.js`
  541. * `.content_tracking.js`
  542. * `.ads.css`
  543. *
  544. * else:
  545. *
  546. * `_prebid.js`
  547. * `t.yesware.com`
  548. * `ubmcmm.baidustatic.com`
  549. * `://www.smfg-card.$document`
  550. * `portal.librus.pl$$advertisement-module`
  551. * `@@-ds.metric.gstatic.com^|`
  552. * `://gom.ge/cookie.js`
  553. * `://accout-update-smba.jp.$document`
  554. * `_200x250.png`
  555. * `@@://www.liquidweb.com/kb/wp-content/themes/lw-kb-theme/images/ads/vps-sidebar.jpg`
  556. */
  557. let sliceStart = 0;
  558. let sliceEnd: number | undefined;
  559. if (lineStartsWithSingleDot) {
  560. sliceStart = 1;
  561. }
  562. if (line.endsWith('^$all')) { // This salvage line `thepiratebay3.com^$all`
  563. sliceEnd = -5;
  564. } else if (
  565. // Try to salvage line like `://account.smba.$document`
  566. // For this specific line, it will fail anyway though.
  567. line.endsWith('$document')
  568. ) {
  569. sliceEnd = -9;
  570. }
  571. const sliced = (sliceStart !== 0 || sliceEnd !== undefined) ? line.slice(sliceStart, sliceEnd) : line;
  572. const suffix = gorhill.getPublicSuffix(sliced);
  573. /**
  574. * Fast exclude definitely not domain-like resource
  575. *
  576. * `.gatracking.js`, suffix is `js`,
  577. * `.ads.css`, suffix is `css`,
  578. * `-cpm-ads.$badfilter`, suffix is `$badfilter`,
  579. * `portal.librus.pl$$advertisement-module`, suffix is `pl$$advertisement-module`
  580. */
  581. if (!suffix || !gorhill.suffixInPSL(suffix)) {
  582. // This exclude domain-like resource like `.gatracking.js`, `.beacon.min.js` and `.cookielaw.js`
  583. return null;
  584. }
  585. const tryNormalizeDomain = normalizeDomain(sliced);
  586. if (tryNormalizeDomain === sliced) {
  587. // the entire rule is domain
  588. return [sliced, ParseType.BlackIncludeSubdomain];
  589. }
  590. return [
  591. `[parse-filter E0010] can not parse: ${line}`,
  592. ParseType.ErrorMessage
  593. ];
  594. }