Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Delta Between Two Patch Sets: lib/abp2blocklist.js

Issue 29452289: Issue 5283 - Add support for $websocket and $webrtc (Closed) Base URL: https://hg.adblockplus.org/abp2blocklist
Left Patch Set: Add top-level exception after copying rule Created July 9, 2017, 9:27 a.m.
Right Patch Set: Rebase Created July 13, 2017, 11:41 a.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « no previous file | node_modules/filterClasses.js » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 /* 1 /*
2 * This file is part of Adblock Plus <https://adblockplus.org/>, 2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 * Copyright (C) 2006-2017 eyeo GmbH 3 * Copyright (C) 2006-2017 eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
(...skipping 85 matching lines...) Expand 10 before | Expand all | Expand 10 after
96 let subdomains = []; 96 let subdomains = [];
97 let suffixLength = domain.length + 1; 97 let suffixLength = domain.length + 1;
98 98
99 for (let name of list) 99 for (let name of list)
100 { 100 {
101 if (name.length > suffixLength && name.slice(-suffixLength) == "." + domain) 101 if (name.length > suffixLength && name.slice(-suffixLength) == "." + domain)
102 subdomains.push(name.slice(0, -suffixLength)); 102 subdomains.push(name.slice(0, -suffixLength));
103 } 103 }
104 104
105 return subdomains; 105 return subdomains;
106 }
107
108 function extractFilterDomains(filters)
109 {
110 let domains = new Set();
111 for (let filter of filters)
112 {
113 let parsed = parseFilterRegexpSource(filter.regexpSource);
114 if (parsed.justHostname)
115 domains.add(parsed.hostname);
116 }
117 return domains;
106 } 118 }
107 119
108 function convertElemHideFilter(filter, elemhideSelectorExceptions) 120 function convertElemHideFilter(filter, elemhideSelectorExceptions)
109 { 121 {
110 let included = []; 122 let included = [];
111 let excluded = []; 123 let excluded = [];
112 let rules = []; 124 let rules = [];
113 125
114 parseDomains(filter.domains, included, excluded); 126 parseDomains(filter.domains, included, excluded);
115 127
(...skipping 14 matching lines...) Expand all
130 * case, a hostname string (or undefined) and a bool 142 * case, a hostname string (or undefined) and a bool
131 * indicating if the source only contains a hostname or not: 143 * indicating if the source only contains a hostname or not:
132 * {regexp: "...", 144 * {regexp: "...",
133 * canSafelyMatchAsLowercase: true/false, 145 * canSafelyMatchAsLowercase: true/false,
134 * hostname: "...", 146 * hostname: "...",
135 * justHostname: true/false} 147 * justHostname: true/false}
136 */ 148 */
137 function parseFilterRegexpSource(text, urlScheme) 149 function parseFilterRegexpSource(text, urlScheme)
138 { 150 {
139 let regexp = []; 151 let regexp = [];
140 let lastIndex = text.length - 1; 152
153 // Convert the text into an array of Unicode characters.
154 //
155 // In the case of surrogate pairs (the smiley emoji, for example), one
156 // Unicode code point is represented by two JavaScript characters together.
157 // We want to iterate over Unicode code points rather than JavaScript
158 // characters.
159 let characters = Array.from(text);
160
161 let lastIndex = characters.length - 1;
141 let hostname; 162 let hostname;
142 let hostnameStart = null; 163 let hostnameStart = null;
143 let hostnameFinished = false; 164 let hostnameFinished = false;
144 let justHostname = false; 165 let justHostname = false;
145 let canSafelyMatchAsLowercase = false; 166 let canSafelyMatchAsLowercase = false;
146 167
147 if (!urlScheme) 168 if (!urlScheme)
148 urlScheme = getURLSchemes()[0]; 169 urlScheme = getURLSchemes()[0];
149 170
150 for (let i = 0; i < text.length; i++) 171 for (let i = 0; i < characters.length; i++)
151 { 172 {
152 let c = text[i]; 173 let c = characters[i];
153 174
154 if (hostnameFinished) 175 if (hostnameFinished)
155 justHostname = false; 176 justHostname = false;
156 177
157 // If we're currently inside the hostname we have to be careful not to 178 // If we're currently inside the hostname we have to be careful not to
158 // escape any characters until after we have converted it to punycode. 179 // escape any characters until after we have converted it to punycode.
159 if (hostnameStart != null && !hostnameFinished) 180 if (hostnameStart != null && !hostnameFinished)
160 { 181 {
161 let endingChar = (c == "*" || c == "^" || 182 let endingChar = (c == "*" || c == "^" ||
162 c == "?" || c == "/" || c == "|"); 183 c == "?" || c == "/" || c == "|");
163 if (!endingChar && i != lastIndex) 184 if (!endingChar && i != lastIndex)
164 continue; 185 continue;
165 186
166 hostname = punycode.toASCII( 187 hostname = punycode.toASCII(
167 text.substring(hostnameStart, endingChar ? i : i + 1) 188 characters.slice(hostnameStart, endingChar ? i : i + 1).join("")
189 .toLowerCase()
168 ); 190 );
169 hostnameFinished = justHostname = true; 191 hostnameFinished = justHostname = true;
170 regexp.push(escapeRegExp(hostname)); 192 regexp.push(escapeRegExp(hostname));
171 if (!endingChar) 193 if (!endingChar)
172 break; 194 break;
173 } 195 }
174 196
175 switch (c) 197 switch (c)
176 { 198 {
177 case "*": 199 case "*":
178 if (regexp.length > 0 && i < lastIndex && text[i + 1] != "*") 200 if (regexp.length > 0 && i < lastIndex && characters[i + 1] != "*")
179 regexp.push(".*"); 201 regexp.push(".*");
180 break; 202 break;
181 case "^": 203 case "^":
182 if (i < lastIndex) 204 let alphabet = "a-z";
183 regexp.push("."); 205 // If justHostname is true and we've encountered a "^", it means we're
206 // still in the hostname part of the URL. Since hostnames are always
207 // lower case (Punycode), there's no need to include "A-Z" in the
208 // pattern. Further, subsequent code may lower-case the entire regular
209 // expression (if the URL contains only the hostname part), leaving us
210 // with "a-za-z", which would be redundant.
211 if (!justHostname)
212 alphabet = "A-Z" + alphabet;
213 let digits = "0-9";
214 // Note that the "-" must appear first here in order to retain its
215 // literal meaning within the brackets.
216 let specialCharacters = "-_.%";
217 let separator = "[^" + specialCharacters + alphabet + digits + "]";
218 if (i == 0)
219 regexp.push("^" + urlScheme + "(.*" + separator + ")?");
220 else if (i == lastIndex)
221 regexp.push("(" + separator + ".*)?$");
222 else
223 regexp.push(separator);
184 break; 224 break;
185 case "|": 225 case "|":
186 if (i == 0) 226 if (i == 0)
187 { 227 {
188 regexp.push("^"); 228 regexp.push("^");
189 break; 229 break;
190 } 230 }
191 if (i == lastIndex) 231 if (i == lastIndex)
192 { 232 {
193 regexp.push("$"); 233 regexp.push("$");
194 break; 234 break;
195 } 235 }
196 if (i == 1 && text[0] == "|") 236 if (i == 1 && characters[0] == "|")
197 { 237 {
198 hostnameStart = i + 1; 238 hostnameStart = i + 1;
199 canSafelyMatchAsLowercase = true; 239 canSafelyMatchAsLowercase = true;
200 regexp.push(urlScheme + "([^/]+\\.)?"); 240 regexp.push(urlScheme + "([^/]+\\.)?");
201 break; 241 break;
202 } 242 }
203 regexp.push("\\|"); 243 regexp.push("\\|");
204 break; 244 break;
205 case "/": 245 case "/":
206 if (!hostnameFinished && 246 if (!hostnameFinished &&
207 text.charAt(i-2) == ":" && text.charAt(i-1) == "/") 247 characters[i - 2] == ":" && characters[i - 1] == "/")
208 { 248 {
209 hostnameStart = i + 1; 249 hostnameStart = i + 1;
210 canSafelyMatchAsLowercase = true; 250 canSafelyMatchAsLowercase = true;
211 } 251 }
212 regexp.push("/"); 252 regexp.push("/");
213 break; 253 break;
214 case ".": case "+": case "$": case "?": 254 case ".": case "+": case "$": case "?":
215 case "{": case "}": case "(": case ")": 255 case "{": case "}": case "(": case ")":
216 case "[": case "]": case "\\": 256 case "[": case "]": case "\\":
217 regexp.push("\\", c); 257 regexp.push("\\", c);
218 break; 258 break;
219 default: 259 default:
220 if (hostnameFinished && (c >= "a" && c <= "z" || 260 if (hostnameFinished && (c >= "a" && c <= "z" ||
221 c >= "A" && c <= "Z")) 261 c >= "A" && c <= "Z"))
222 canSafelyMatchAsLowercase = false; 262 canSafelyMatchAsLowercase = false;
223 regexp.push(c); 263 regexp.push(c == "%" ? c : encodeURI(c));
224 } 264 }
225 } 265 }
226 266
227 return { 267 return {
228 regexp: regexp.join(""), 268 regexp: regexp.join(""),
229 canSafelyMatchAsLowercase: canSafelyMatchAsLowercase, 269 canSafelyMatchAsLowercase: canSafelyMatchAsLowercase,
230 hostname: hostname, 270 hostname: hostname,
231 justHostname: justHostname 271 justHostname: justHostname
232 }; 272 };
233 } 273 }
234 274
235 function getResourceTypes(contentType) 275 function getResourceTypes(contentType)
236 { 276 {
237 let types = []; 277 let types = [];
238 278
239 if (contentType & typeMap.IMAGE) 279 if (contentType & typeMap.IMAGE)
240 types.push("image"); 280 types.push("image");
241 if (contentType & typeMap.STYLESHEET) 281 if (contentType & typeMap.STYLESHEET)
242 types.push("style-sheet"); 282 types.push("style-sheet");
243 if (contentType & typeMap.SCRIPT) 283 if (contentType & typeMap.SCRIPT)
244 types.push("script"); 284 types.push("script");
245 if (contentType & typeMap.FONT) 285 if (contentType & typeMap.FONT)
246 types.push("font"); 286 types.push("font");
247 if (contentType & (typeMap.MEDIA | typeMap.OBJECT)) 287 if (contentType & (typeMap.MEDIA | typeMap.OBJECT))
248 types.push("media"); 288 types.push("media");
249 if (contentType & typeMap.POPUP) 289 if (contentType & typeMap.POPUP)
250 types.push("popup"); 290 types.push("popup");
251 if (contentType & (typeMap.XMLHTTPREQUEST | 291 if (contentType & (typeMap.XMLHTTPREQUEST |
252 typeMap.WEBSOCKET | 292 typeMap.WEBSOCKET |
253 typeMap.WEBRTC | 293 typeMap.WEBRTC |
254 typeMap.OBJECT_SUBREQUEST | 294 typeMap.OBJECT_SUBREQUEST |
255 typeMap.PING | 295 typeMap.PING |
256 typeMap.OTHER)) 296 typeMap.OTHER))
257 { 297 {
258 types.push("raw"); 298 types.push("raw");
259 } 299 }
260 if (contentType & typeMap.SUBDOCUMENT) 300 if (contentType & typeMap.SUBDOCUMENT)
261 types.push("document"); 301 types.push("document");
262 302
263 return types; 303 return types;
264 } 304 }
265 305
266 function makeRuleCopies(trigger, action, urlSchemes) 306 function makeRuleCopies(trigger, action, urlSchemes)
(...skipping 138 matching lines...) Expand 10 before | Expand all | Expand 10 after
405 let included = []; 445 let included = [];
406 let excluded = []; 446 let excluded = [];
407 447
408 parseDomains(filter.domains, included, excluded); 448 parseDomains(filter.domains, included, excluded);
409 449
410 if (exceptionDomains) 450 if (exceptionDomains)
411 excluded = excluded.concat(exceptionDomains); 451 excluded = excluded.concat(exceptionDomains);
412 452
413 if (withResourceTypes) 453 if (withResourceTypes)
414 { 454 {
415 trigger["resource-type"] = getResourceTypes(contentType); 455 let resourceTypes = getResourceTypes(contentType);
416 456
417 if (trigger["resource-type"].length == 0) 457 // Content blocker rules can't differentiate between sub-document requests
458 // (iframes) and top-level document requests. To avoid too many false
459 // positives, we prevent rules with no hostname part from blocking document
460 // requests.
461 //
462 // Once Safari 11 becomes our minimum supported version, we could change
463 // our approach here to use the new "unless-top-url" property instead.
464 if (filter instanceof filterClasses.BlockingFilter && !parsed.hostname)
465 resourceTypes = resourceTypes.filter(type => type != "document");
466
467 if (resourceTypes.length == 0)
418 return; 468 return;
469
470 trigger["resource-type"] = resourceTypes;
419 } 471 }
420 472
421 if (filter.thirdParty != null) 473 if (filter.thirdParty != null)
422 trigger["load-type"] = [filter.thirdParty ? "third-party" : "first-party"]; 474 trigger["load-type"] = [filter.thirdParty ? "third-party" : "first-party"];
423 475
424 let addTopLevelException = false; 476 let addTopLevelException = false;
425 477
426 if (included.length > 0) 478 if (included.length > 0)
427 { 479 {
428 trigger["if-domain"] = []; 480 trigger["if-domain"] = [];
(...skipping 17 matching lines...) Expand all
446 { 498 {
447 trigger["if-domain"].push("*" + name); 499 trigger["if-domain"].push("*" + name);
448 } 500 }
449 } 501 }
450 } 502 }
451 else if (excluded.length > 0) 503 else if (excluded.length > 0)
452 { 504 {
453 trigger["unless-domain"] = excluded.map(name => "*" + name); 505 trigger["unless-domain"] = excluded.map(name => "*" + name);
454 } 506 }
455 else if (filter instanceof filterClasses.BlockingFilter && 507 else if (filter instanceof filterClasses.BlockingFilter &&
456 filter.contentType & typeMap.SUBDOCUMENT) 508 filter.contentType & typeMap.SUBDOCUMENT && parsed.hostname)
457 { 509 {
510 // Rules with a hostname part are still allowed to block document requests,
511 // but we add an exception for top-level documents.
512 //
513 // Note that we can only do this if there's no "unless-domain" property for
514 // now. This also only works in Safari 11 onwards, while older versions
515 // simply ignore this property. Once Safari 11 becomes our minimum
516 // supported version, we can merge "unless-domain" into "unless-top-url".
458 addTopLevelException = true; 517 addTopLevelException = true;
459 excludeTopURLFromTrigger(trigger); 518 excludeTopURLFromTrigger(trigger);
460 } 519 }
461 520
462 rules.push({trigger: trigger, action: {type: action}}); 521 rules.push({trigger: trigger, action: {type: action}});
463 522
464 if (needAltRules) 523 if (needAltRules)
465 { 524 {
466 // Generate additional rules for any alternative URL schemes. 525 // Generate additional rules for any alternative URL schemes.
467 for (let altRule of makeRuleCopies(trigger, {type: action}, urlSchemes)) 526 for (let altRule of makeRuleCopies(trigger, {type: action}, urlSchemes))
468 { 527 {
469 if (addTopLevelException) 528 if (addTopLevelException)
470 excludeTopURLFromTrigger(altRule.trigger); 529 excludeTopURLFromTrigger(altRule.trigger);
471 530
472 rules.push(altRule); 531 rules.push(altRule);
473 } 532 }
474 } 533 }
475 }
476
477 function hasNonASCI(obj)
478 {
479 if (typeof obj == "string")
480 {
481 if (/[^\x00-\x7F]/.test(obj))
482 return true;
483 }
484
485 if (typeof obj == "object")
486 {
487 if (obj instanceof Array)
488 for (let item of obj)
489 if (hasNonASCI(item))
490 return true;
491
492 let names = Object.getOwnPropertyNames(obj);
493 for (let name of names)
494 if (hasNonASCI(obj[name]))
495 return true;
496 }
497
498 return false;
499 } 534 }
500 535
501 function convertIDSelectorsToAttributeSelectors(selector) 536 function convertIDSelectorsToAttributeSelectors(selector)
502 { 537 {
503 // First we figure out where all the IDs are 538 // First we figure out where all the IDs are
504 let sep = ""; 539 let sep = "";
505 let start = null; 540 let start = null;
506 let positions = []; 541 let positions = [];
507 for (let i = 0; i < selector.length; i++) 542 for (let i = 0; i < selector.length; i++)
508 { 543 {
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
542 { 577 {
543 newSelector.push(selector.substring(i, pos.start)); 578 newSelector.push(selector.substring(i, pos.start));
544 newSelector.push('[id=', selector.substring(pos.start + 1, pos.end), ']'); 579 newSelector.push('[id=', selector.substring(pos.start + 1, pos.end), ']');
545 i = pos.end; 580 i = pos.end;
546 } 581 }
547 newSelector.push(selector.substring(i)); 582 newSelector.push(selector.substring(i));
548 583
549 return newSelector.join(""); 584 return newSelector.join("");
550 } 585 }
551 586
552 function addCSSRules(rules, selectors, matchDomain) 587 function addCSSRules(rules, selectors, matchDomain, exceptionDomains)
553 { 588 {
589 let unlessDomain = exceptionDomains.size > 0 ? [] : null;
590
591 exceptionDomains.forEach(name => unlessDomain.push("*" + name));
592
554 while (selectors.length) 593 while (selectors.length)
555 { 594 {
556 let selector = selectors.splice(0, selectorLimit).join(", "); 595 let selector = selectors.splice(0, selectorLimit).join(", ");
557 596
558 // As of Safari 9.0 element IDs are matched as lowercase. We work around 597 // As of Safari 9.0 element IDs are matched as lowercase. We work around
559 // this by converting to the attribute format [id="elementID"] 598 // this by converting to the attribute format [id="elementID"]
560 selector = convertIDSelectorsToAttributeSelectors(selector); 599 selector = convertIDSelectorsToAttributeSelectors(selector);
561 600
562 rules.push({ 601 let rule = {
563 trigger: {"url-filter": matchDomain, 602 trigger: {"url-filter": matchDomain,
564 "url-filter-is-case-sensitive": true}, 603 "url-filter-is-case-sensitive": true},
565 action: {type: "css-display-none", 604 action: {type: "css-display-none",
566 selector: selector} 605 selector: selector}
567 }); 606 };
607
608 if (unlessDomain)
609 rule.trigger["unless-domain"] = unlessDomain;
610
611 rules.push(rule);
568 } 612 }
569 } 613 }
570 614
571 let ContentBlockerList = 615 let ContentBlockerList =
572 /** 616 /**
573 * Create a new Adblock Plus filter to content blocker list converter 617 * Create a new Adblock Plus filter to content blocker list converter
574 * 618 *
575 * @constructor 619 * @constructor
576 */ 620 */
577 exports.ContentBlockerList = function () 621 exports.ContentBlockerList = function ()
(...skipping 76 matching lines...) Expand 10 before | Expand all | Expand 10 after
654 { 698 {
655 for (let matchDomain of result.matchDomains) 699 for (let matchDomain of result.matchDomains)
656 { 700 {
657 let group = groupedElemhideFilters.get(matchDomain) || []; 701 let group = groupedElemhideFilters.get(matchDomain) || [];
658 group.push(result.selector); 702 group.push(result.selector);
659 groupedElemhideFilters.set(matchDomain, group); 703 groupedElemhideFilters.set(matchDomain, group);
660 } 704 }
661 } 705 }
662 } 706 }
663 707
664 addCSSRules(rules, genericSelectors, "^https?://"); 708 // Separate out the element hiding exceptions that have only a hostname part
665 709 // from the rest. This allows us to implement a workaround for issue #5345
666 // Right after the generic element hiding filters, add the exceptions that 710 // (WebKit bug #167423), but as a bonus it also reduces the number of
667 // should apply only to those filters. 711 // generated rules. The downside is that the exception will only apply to the
668 for (let filter of this.generichideExceptions) 712 // top-level document, not to iframes. We have to live with this until the
669 convertFilterAddRules(rules, filter, "ignore-previous-rules", false); 713 // WebKit bug is fixed in all supported versions of Safari.
714 // https://bugs.webkit.org/show_bug.cgi?id=167423
715 //
716 // Note that as a result of this workaround we end up with a huge rule set in
717 // terms of the amount of memory used. This can cause Node.js to throw
718 // "JavaScript heap out of memory". To avoid this, call Node.js with
719 // --max_old_space_size=4096
720 let elemhideExceptionDomains = extractFilterDomains(this.elemhideExceptions);
721
722 let genericSelectorExceptionDomains =
723 extractFilterDomains(this.generichideExceptions);
724 elemhideExceptionDomains.forEach(name =>
725 {
726 genericSelectorExceptionDomains.add(name);
727 });
728
729 addCSSRules(rules, genericSelectors, "^https?://",
730 genericSelectorExceptionDomains);
670 731
671 groupedElemhideFilters.forEach((selectors, matchDomain) => 732 groupedElemhideFilters.forEach((selectors, matchDomain) =>
672 { 733 {
673 addCSSRules(rules, selectors, matchDomain); 734 addCSSRules(rules, selectors, matchDomain, elemhideExceptionDomains);
674 }); 735 });
675
676 for (let filter of this.elemhideExceptions)
677 convertFilterAddRules(rules, filter, "ignore-previous-rules", false);
678 736
679 let requestFilterExceptionDomains = []; 737 let requestFilterExceptionDomains = [];
680 for (let filter of this.genericblockExceptions) 738 for (let filter of this.genericblockExceptions)
681 { 739 {
682 let parsed = parseFilterRegexpSource(filter.regexpSource); 740 let parsed = parseFilterRegexpSource(filter.regexpSource);
683 if (parsed.hostname) 741 if (parsed.hostname)
684 requestFilterExceptionDomains.push(parsed.hostname); 742 requestFilterExceptionDomains.push(parsed.hostname);
685 } 743 }
686 744
687 for (let filter of this.requestFilters) 745 for (let filter of this.requestFilters)
688 { 746 {
689 convertFilterAddRules(rules, filter, "block", true, 747 convertFilterAddRules(rules, filter, "block", true,
690 requestFilterExceptionDomains); 748 requestFilterExceptionDomains);
691 } 749 }
692 750
693 for (let filter of this.requestExceptions) 751 for (let filter of this.requestExceptions)
694 convertFilterAddRules(rules, filter, "ignore-previous-rules", true); 752 convertFilterAddRules(rules, filter, "ignore-previous-rules", true);
695 753
696 return rules.filter(rule => !hasNonASCI(rule)); 754 return rules;
697 }; 755 };
LEFTRIGHT

Powered by Google App Engine
This is Rietveld