parse-filter.ts 21 KB

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