blob: af8e4657f652f4d014646a48f08433fc0d4ae14f [file] [log] [blame]
[email protected]fb5bcc02012-02-17 14:05:421// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/extensions/api/declarative/url_matcher.h"
6
7#include <algorithm>
[email protected]9947d0e2012-02-23 22:36:538#include <iterator>
[email protected]fb5bcc02012-02-17 14:05:429
10#include "base/logging.h"
11#include "googleurl/src/gurl.h"
12
13namespace extensions {
14
15// This set of classes implement a mapping of URL Component Patterns, such as
16// host_prefix, host_suffix, host_equals, ..., etc., to SubstringPatterns.
17//
18// The idea of this mapping is to reduce the problem of comparing many
19// URL Component Patterns against one URL to the problem of searching many
20// substrings in one string:
21//
22// ---------------------- --------------------
23// | URL Query operator | ----translate----> | SubstringPattern |
24// ---------------------- --------------------
25// ^
26// |
27// compare
28// |
29// v
30// ---------------------- --------------------
31// | URL to compare | | |
32// | to all URL Query | ----translate----> | String |
33// | operators | | |
34// ---------------------- --------------------
35//
36// The reason for this problem reduction is that there are efficient algorithms
37// for searching many substrings in one string (see Aho-Corasick algorithm).
38//
39// Case 1: {host,path,query}_{prefix,suffix,equals} searches.
40// ==========================================================
41//
42// For searches in this class, we normalize URLs as follows:
43//
44// Step 1:
45// Remove scheme, port and segment from URL:
46// -> http://www.example.com:8080/index.html?search=foo#first_match becomes
47// www.example.com/index.html?search=foo
48//
49// We remove the scheme and port number because they can be checked later
50// in a secondary filter step. We remove the segment (the #... part) because
51// this is not guaranteed to be ASCII-7 encoded.
52//
53// Step 2:
54// Translate URL to String and add the following position markers:
55// - BU = Beginning of URL
56// - ED = End of Domain
57// - EP = End of Path
58// - EU = End of URL
59// Furthermore, the hostname is canonicalized to start with a ".".
60//
61// Position markers are represented as characters >127, which are therefore
62// guaranteed not to be part of the ASCII-7 encoded URL character set.
63//
64// -> www.example.com/index.html?search=foo becomes
65// BU .www.example.com ED /index.html EP ?search=foo EU
66//
67// -> www.example.com/index.html becomes
68// BU .www.example.com ED /index.html EP EU
69//
70// Step 3:
71// Translate URL Component Patterns as follows:
72//
73// host_prefix(prefix) = BU add_missing_dot_prefix(prefix)
74// -> host_prefix("www.example") = BU .www.example
75//
76// host_suffix(suffix) = suffix ED
77// -> host_suffix("example.com") = example.com ED
78// -> host_suffix(".example.com") = .example.com ED
79//
80// host_equals(domain) = BU add_missing_dot_prefix(domain) ED
81// -> host_equals("www.example.com") = BU .www.example.com ED
82//
83// Similarly for path query parameters ({path, query}_{prefix, suffix, equals}).
84//
85// With this, we can search the SubstringPatterns in the normalized URL.
86//
87//
88// Case 2: url_{prefix,suffix,equals,contains} searches.
89// =====================================================
90//
91// Step 1: as above
92//
93// Step 2:
94// Translate URL to String and add the following position markers:
95// - BU = Beginning of URL
96// - EU = End of URL
97// Furthermore, the hostname is canonicalized to start with a ".".
98//
99// -> www.example.com/index.html?search=foo becomes
100// BU .www.example.com/index.html?search=foo EU
101//
102// url_prefix(prefix) = BU add_missing_dot_prefix(prefix)
103// -> url_prefix("www.example") = BU .www.example
104//
105// url_contains(substring) = substring
106// -> url_contains("index") = index
107//
108//
109// Case 3: {host,path,query}_contains searches.
110// ============================================
111//
112// These kinds of searches are not supported directly but can be derived
113// by a combination of a url_contains() query followed by an explicit test:
114//
115// host_contains(str) = url_contains(str) followed by test whether str occurs
116// in host comonent of original URL.
117// -> host_contains("example.co") = example.co
118// followed by gurl.host().find("example.co");
119//
120// [similarly for path_contains and query_contains].
121
122
123//
124// URLMatcherCondition
125//
126
127URLMatcherCondition::URLMatcherCondition()
128 : criterion_(HOST_PREFIX),
129 substring_pattern_(NULL) {}
130
131URLMatcherCondition::~URLMatcherCondition() {}
132
133URLMatcherCondition::URLMatcherCondition(
134 Criterion criterion,
135 const SubstringPattern* substring_pattern)
136 : criterion_(criterion),
137 substring_pattern_(substring_pattern) {}
138
139URLMatcherCondition::URLMatcherCondition(const URLMatcherCondition& rhs)
140 : criterion_(rhs.criterion_),
141 substring_pattern_(rhs.substring_pattern_) {}
142
143URLMatcherCondition& URLMatcherCondition::operator=(
144 const URLMatcherCondition& rhs) {
145 criterion_ = rhs.criterion_;
146 substring_pattern_ = rhs.substring_pattern_;
147 return *this;
148}
149
150bool URLMatcherCondition::operator<(const URLMatcherCondition& rhs) const {
151 if (criterion_ < rhs.criterion_) return true;
152 if (criterion_ > rhs.criterion_) return false;
153 if (substring_pattern_ != NULL && rhs.substring_pattern_ != NULL)
154 return *substring_pattern_ < *rhs.substring_pattern_;
155 if (substring_pattern_ == NULL && rhs.substring_pattern_ != NULL) return true;
156 // Either substring_pattern_ != NULL && rhs.substring_pattern_ == NULL,
157 // or both are NULL.
158 return false;
159}
160
161bool URLMatcherCondition::IsFullURLCondition() const {
162 // For these criteria the SubstringMatcher needs to be executed on the
163 // GURL that is canonlizaliced with
164 // URLMatcherConditionFactory::CanonicalizeURLForFullSearches.
165 switch (criterion_) {
166 case HOST_CONTAINS:
167 case PATH_CONTAINS:
168 case QUERY_CONTAINS:
169 case URL_PREFIX:
170 case URL_SUFFIX:
171 case URL_CONTAINS:
172 case URL_EQUALS:
173 return true;
174 default:
175 break;
176 }
177 return false;
178}
179
180bool URLMatcherCondition::IsMatch(
181 const std::set<SubstringPattern::ID>& matching_substring_patterns,
182 const GURL& url) const {
183 DCHECK(substring_pattern_);
184 if (matching_substring_patterns.find(substring_pattern_->id()) ==
185 matching_substring_patterns.end())
186 return false;
187 // The criteria HOST_CONTAINS, PATH_CONTAINS, QUERY_CONTAINS are based on
188 // a substring match on the raw URL. In case of a match, we need to verify
189 // that the match was found in the correct component of the URL.
190 switch (criterion_) {
191 case HOST_CONTAINS:
192 return url.host().find(substring_pattern_->pattern()) !=
193 std::string::npos;
194 case PATH_CONTAINS:
195 return url.path().find(substring_pattern_->pattern()) !=
196 std::string::npos;
197 case QUERY_CONTAINS:
198 return url.query().find(substring_pattern_->pattern()) !=
199 std::string::npos;
200 default:
201 break;
202 }
203 return true;
204}
205
206//
207// URLMatcherConditionFactory
208//
209
210namespace {
211// These are symbols that are not contained in 7-bit ASCII used in GURLs.
212const char kBeginningOfURL[] = {-1, 0};
213const char kEndOfDomain[] = {-2, 0};
214const char kEndOfPath[] = {-3, 0};
215const char kEndOfURL[] = {-4, 0};
216} // namespace
217
218URLMatcherConditionFactory::URLMatcherConditionFactory() : id_counter_(0) {}
219
220URLMatcherConditionFactory::~URLMatcherConditionFactory() {
221 STLDeleteElements(&pattern_singletons_);
222}
223
224std::string URLMatcherConditionFactory::CanonicalizeURLForComponentSearches(
225 const GURL& url) {
226 return kBeginningOfURL + CanonicalizeHostname(url.host()) + kEndOfDomain +
227 url.path() + kEndOfPath + (url.has_query() ? "?" + url.query() : "") +
228 kEndOfURL;
229}
230
231URLMatcherCondition URLMatcherConditionFactory::CreateHostPrefixCondition(
232 const std::string& prefix) {
233 return CreateCondition(URLMatcherCondition::HOST_PREFIX,
234 kBeginningOfURL + CanonicalizeHostname(prefix));
235}
236
237URLMatcherCondition URLMatcherConditionFactory::CreateHostSuffixCondition(
238 const std::string& suffix) {
239 return CreateCondition(URLMatcherCondition::HOST_SUFFIX,
240 suffix + kEndOfDomain);
241}
242
243URLMatcherCondition URLMatcherConditionFactory::CreateHostContainsCondition(
244 const std::string& str) {
245 return CreateCondition(URLMatcherCondition::HOST_CONTAINS, str);
246}
247
248URLMatcherCondition URLMatcherConditionFactory::CreateHostEqualsCondition(
249 const std::string& str) {
250 return CreateCondition(URLMatcherCondition::HOST_EQUALS,
251 kBeginningOfURL + CanonicalizeHostname(str) + kEndOfDomain);
252}
253
254URLMatcherCondition URLMatcherConditionFactory::CreatePathPrefixCondition(
255 const std::string& prefix) {
256 return CreateCondition(URLMatcherCondition::PATH_PREFIX,
257 kEndOfDomain + prefix);
258}
259
260URLMatcherCondition URLMatcherConditionFactory::CreatePathSuffixCondition(
261 const std::string& suffix) {
262 return CreateCondition(URLMatcherCondition::HOST_SUFFIX, suffix + kEndOfPath);
263}
264
265URLMatcherCondition URLMatcherConditionFactory::CreatePathContainsCondition(
266 const std::string& str) {
267 return CreateCondition(URLMatcherCondition::PATH_CONTAINS, str);
268}
269
270URLMatcherCondition URLMatcherConditionFactory::CreatePathEqualsCondition(
271 const std::string& str) {
272 return CreateCondition(URLMatcherCondition::PATH_EQUALS,
273 kEndOfDomain + str + kEndOfPath);
274}
275
276URLMatcherCondition URLMatcherConditionFactory::CreateQueryPrefixCondition(
277 const std::string& prefix) {
278 return CreateCondition(URLMatcherCondition::QUERY_PREFIX,
279 kEndOfPath + prefix);
280}
281
282URLMatcherCondition URLMatcherConditionFactory::CreateQuerySuffixCondition(
283 const std::string& suffix) {
284 return CreateCondition(URLMatcherCondition::QUERY_SUFFIX, suffix + kEndOfURL);
285}
286
287URLMatcherCondition URLMatcherConditionFactory::CreateQueryContainsCondition(
288 const std::string& str) {
289 return CreateCondition(URLMatcherCondition::QUERY_CONTAINS, str);
290}
291
292URLMatcherCondition URLMatcherConditionFactory::CreateQueryEqualsCondition(
293 const std::string& str) {
294 return CreateCondition(URLMatcherCondition::QUERY_EQUALS,
295 kEndOfPath + str + kEndOfURL);
296}
297
298URLMatcherCondition
299 URLMatcherConditionFactory::CreateHostSuffixPathPrefixCondition(
300 const std::string& host_suffix,
301 const std::string& path_prefix) {
302 return CreateCondition(URLMatcherCondition::HOST_SUFFIX_PATH_PREFIX,
303 host_suffix + kEndOfDomain + path_prefix);
304}
305
306std::string URLMatcherConditionFactory::CanonicalizeURLForFullSearches(
307 const GURL& url) {
308 return kBeginningOfURL + CanonicalizeHostname(url.host()) + url.path() +
309 (url.has_query() ? "?" + url.query() : "") + kEndOfURL;
310}
311
312URLMatcherCondition URLMatcherConditionFactory::CreateURLPrefixCondition(
313 const std::string& prefix) {
314 return CreateCondition(URLMatcherCondition::URL_PREFIX,
315 kBeginningOfURL + CanonicalizeHostname(prefix));
316}
317
318URLMatcherCondition URLMatcherConditionFactory::CreateURLSuffixCondition(
319 const std::string& suffix) {
320 return CreateCondition(URLMatcherCondition::URL_SUFFIX, suffix + kEndOfURL);
321}
322
323URLMatcherCondition URLMatcherConditionFactory::CreateURLContainsCondition(
324 const std::string& str) {
325 return CreateCondition(URLMatcherCondition::URL_CONTAINS, str);
326}
327
328URLMatcherCondition URLMatcherConditionFactory::CreateURLEqualsCondition(
329 const std::string& str) {
330 return CreateCondition(URLMatcherCondition::QUERY_EQUALS,
331 kBeginningOfURL + CanonicalizeHostname(str) + kEndOfURL);
332}
333
334void URLMatcherConditionFactory::ForgetUnusedPatterns(
335 const std::set<SubstringPattern::ID>& used_patterns) {
336 PatternSingletons::iterator i = pattern_singletons_.begin();
337 while (i != pattern_singletons_.end()) {
[email protected]2fb51d92012-02-17 15:05:47338 if (used_patterns.find((*i)->id()) != used_patterns.end()) {
[email protected]fb5bcc02012-02-17 14:05:42339 ++i;
[email protected]2fb51d92012-02-17 15:05:47340 } else {
341 delete *i;
[email protected]fb5bcc02012-02-17 14:05:42342 pattern_singletons_.erase(i++);
[email protected]2fb51d92012-02-17 15:05:47343 }
[email protected]fb5bcc02012-02-17 14:05:42344 }
345}
346
347URLMatcherCondition URLMatcherConditionFactory::CreateCondition(
348 URLMatcherCondition::Criterion criterion,
349 const std::string& pattern) {
350 SubstringPattern search_pattern(pattern, 0);
351 PatternSingletons::const_iterator iter =
352 pattern_singletons_.find(&search_pattern);
353 if (iter != pattern_singletons_.end()) {
354 return URLMatcherCondition(criterion, *iter);
355 } else {
356 SubstringPattern* new_pattern =
357 new SubstringPattern(pattern, id_counter_++);
358 pattern_singletons_.insert(new_pattern);
359 return URLMatcherCondition(criterion, new_pattern);
360 }
361}
362
363std::string URLMatcherConditionFactory::CanonicalizeHostname(
364 const std::string& hostname) const {
365 if (!hostname.empty() && hostname[0] == '.')
366 return hostname;
367 else
368 return "." + hostname;
369}
370
371bool URLMatcherConditionFactory::SubstringPatternPointerCompare::operator()(
372 SubstringPattern* lhs,
373 SubstringPattern* rhs) const {
374 if (lhs == NULL && rhs != NULL) return true;
375 if (lhs != NULL && rhs != NULL)
376 return lhs->pattern() < rhs->pattern();
377 // Either both are NULL or only rhs is NULL.
378 return false;
379}
380
381//
382// URLMatcherConditionSet
383//
384
385URLMatcherConditionSet::URLMatcherConditionSet() : id_(-1) {}
386
387URLMatcherConditionSet::~URLMatcherConditionSet() {}
388
389URLMatcherConditionSet::URLMatcherConditionSet(
390 ID id,
391 const Conditions& conditions)
392 : id_(id),
393 conditions_(conditions) {}
394
395URLMatcherConditionSet::URLMatcherConditionSet(
396 const URLMatcherConditionSet& rhs)
397 : id_(rhs.id_), conditions_(rhs.conditions_) {}
398
399URLMatcherConditionSet& URLMatcherConditionSet::operator=(
400 const URLMatcherConditionSet& rhs) {
401 id_ = rhs.id_;
402 conditions_ = rhs.conditions_;
403 return *this;
404}
405
406bool URLMatcherConditionSet::IsMatch(
407 const std::set<SubstringPattern::ID>& matching_substring_patterns,
408 const GURL& url) const {
409 for (Conditions::const_iterator i = conditions_.begin();
410 i != conditions_.end(); ++i) {
411 if (!i->IsMatch(matching_substring_patterns, url))
412 return false;
413 }
414 return true;
415}
416
417
418//
419// URLMatcher
420//
421
422URLMatcher::URLMatcher() {}
423
424URLMatcher::~URLMatcher() {}
425
426void URLMatcher::AddConditionSets(
427 const std::vector<URLMatcherConditionSet>& condition_sets) {
428 for (std::vector<URLMatcherConditionSet>::const_iterator i =
429 condition_sets.begin(); i != condition_sets.end(); ++i) {
430 DCHECK(url_matcher_condition_sets_.find(i->id()) ==
431 url_matcher_condition_sets_.end());
432 url_matcher_condition_sets_[i->id()] = *i;
433 }
434 UpdateInternalDatastructures();
435}
436
437void URLMatcher::RemoveConditionSets(
438 const std::vector<URLMatcherConditionSet::ID>& condition_set_ids) {
439 for (std::vector<URLMatcherConditionSet::ID>::const_iterator i =
440 condition_set_ids.begin(); i != condition_set_ids.end(); ++i) {
441 DCHECK(url_matcher_condition_sets_.find(*i) !=
442 url_matcher_condition_sets_.end());
443 url_matcher_condition_sets_.erase(*i);
444 }
445 UpdateInternalDatastructures();
446}
447
448std::set<URLMatcherConditionSet::ID> URLMatcher::MatchURL(const GURL& url) {
449 // Find all IDs of SubstringPatterns that match |url|.
450 // See URLMatcherConditionFactory for the canonicalization of URLs and the
451 // distinction between full url searches and url component searches.
452 std::set<SubstringPattern::ID> matches;
453 full_url_matcher_.Match(
454 condition_factory_.CanonicalizeURLForFullSearches(url), &matches);
455 url_component_matcher_.Match(
456 condition_factory_.CanonicalizeURLForComponentSearches(url), &matches);
457
458 // Calculate all URLMatcherConditionSets for which all URLMatcherConditions
459 // were fulfilled.
460 std::set<URLMatcherConditionSet::ID> result;
461 for (std::set<SubstringPattern::ID>::const_iterator i = matches.begin();
462 i != matches.end(); ++i) {
463 // For each URLMatcherConditionSet there is exactly one condition
464 // registered in substring_match_triggers_. This means that the following
465 // logic tests each URLMatcherConditionSet exactly once if it can be
466 // completely fulfilled.
467 std::set<URLMatcherConditionSet::ID>& condition_sets =
468 substring_match_triggers_[*i];
469 for (std::set<URLMatcherConditionSet::ID>::const_iterator j =
470 condition_sets.begin(); j != condition_sets.end(); ++j) {
471 if (url_matcher_condition_sets_[*j].IsMatch(matches, url))
472 result.insert(*j);
473 }
474 }
475
476 return result;
477}
478
479void URLMatcher::UpdateSubstringSetMatcher(bool full_url_conditions) {
480 // The purpose of |full_url_conditions| is just that we need to execute
481 // the same logic once for Full URL searches and once for URL Component
482 // searches (see URLMatcherConditionFactory).
483
484 // Determine which patterns need to be registered when this function
485 // terminates.
486 std::set<const SubstringPattern*> new_patterns;
487 for (URLMatcherConditionSets::const_iterator condition_set_iter =
488 url_matcher_condition_sets_.begin();
489 condition_set_iter != url_matcher_condition_sets_.end();
490 ++condition_set_iter) {
491 const URLMatcherConditionSet::Conditions& conditions =
492 condition_set_iter->second.conditions();
493 for (URLMatcherConditionSet::Conditions::const_iterator condition_iter =
494 conditions.begin(); condition_iter != conditions.end();
495 ++condition_iter) {
496 // If we are called to process Full URL searches, ignore all others,
497 // and vice versa.
498 if (full_url_conditions == condition_iter->IsFullURLCondition())
499 new_patterns.insert(condition_iter->substring_pattern());
500 }
501 }
502
503 // This is the set of patterns that were registered before this function
504 // is called.
505 std::set<const SubstringPattern*>& registered_patterns =
506 full_url_conditions ? registered_full_url_patterns_
507 : registered_url_component_patterns_;
508
509 // Add all patterns that are in new_patterns but not in registered_patterns.
510 std::vector<const SubstringPattern*> patterns_to_register;
511 std::set_difference(
512 new_patterns.begin(), new_patterns.end(),
513 registered_patterns.begin(), registered_patterns.end(),
514 std::back_inserter(patterns_to_register));
515
516 // Remove all patterns that are in registered_patterns but not in
517 // new_patterns.
518 std::vector<const SubstringPattern*> patterns_to_unregister;
519 std::set_difference(
520 registered_patterns.begin(), registered_patterns.end(),
521 new_patterns.begin(), new_patterns.end(),
522 std::back_inserter(patterns_to_unregister));
523
524 // Update the SubstringSetMatcher.
525 SubstringSetMatcher& url_matcher =
526 full_url_conditions ? full_url_matcher_ : url_component_matcher_;
527 url_matcher.RegisterAndUnregisterPatterns(patterns_to_register,
528 patterns_to_unregister);
529
530 // Update the set of registered_patterns for the next time this function
531 // is being called.
532 registered_patterns.swap(new_patterns);
533}
534
535void URLMatcher::UpdateTriggers() {
536 // Count substring pattern frequencies.
537 std::map<SubstringPattern::ID, size_t> substring_pattern_frequencies;
538 for (URLMatcherConditionSets::const_iterator condition_set_iter =
539 url_matcher_condition_sets_.begin();
540 condition_set_iter != url_matcher_condition_sets_.end();
541 ++condition_set_iter) {
542 const URLMatcherConditionSet::Conditions& conditions =
543 condition_set_iter->second.conditions();
544 for (URLMatcherConditionSet::Conditions::const_iterator condition_iter =
545 conditions.begin(); condition_iter != conditions.end();
546 ++condition_iter) {
547 const SubstringPattern* pattern = condition_iter->substring_pattern();
548 substring_pattern_frequencies[pattern->id()]++;
549 }
550 }
551
552 // Update trigger conditions: Determine for each URLMatcherConditionSet which
553 // URLMatcherCondition contains a SubstringPattern that occurs least
554 // frequently in this URLMatcher. We assume that this condition is very
555 // specific and occurs rarely in URLs. If a match occurs for this
556 // URLMatcherCondition, we want to test all other URLMatcherCondition in the
557 // respective URLMatcherConditionSet as well to see whether the entire
558 // URLMatcherConditionSet is considered matching.
559 substring_match_triggers_.clear();
560 for (URLMatcherConditionSets::const_iterator condition_set_iter =
561 url_matcher_condition_sets_.begin();
562 condition_set_iter != url_matcher_condition_sets_.end();
563 ++condition_set_iter) {
564 const URLMatcherConditionSet::Conditions& conditions =
565 condition_set_iter->second.conditions();
566 if (conditions.empty())
567 continue;
568 URLMatcherConditionSet::Conditions::const_iterator condition_iter =
569 conditions.begin();
570 SubstringPattern::ID trigger = condition_iter->substring_pattern()->id();
571 // We skip the first element in the following loop.
572 ++condition_iter;
573 for (; condition_iter != conditions.end(); ++condition_iter) {
574 SubstringPattern::ID current_id =
575 condition_iter->substring_pattern()->id();
576 if (substring_pattern_frequencies[trigger] >
577 substring_pattern_frequencies[current_id]) {
578 trigger = current_id;
579 }
580 }
581 substring_match_triggers_[trigger].insert(condition_set_iter->second.id());
582 }
583}
584
585void URLMatcher::UpdateConditionFactory() {
586 std::set<SubstringPattern::ID> used_patterns;
587 for (URLMatcherConditionSets::const_iterator condition_set_iter =
588 url_matcher_condition_sets_.begin();
589 condition_set_iter != url_matcher_condition_sets_.end();
590 ++condition_set_iter) {
591 const URLMatcherConditionSet::Conditions& conditions =
592 condition_set_iter->second.conditions();
593 for (URLMatcherConditionSet::Conditions::const_iterator condition_iter =
594 conditions.begin(); condition_iter != conditions.end();
595 ++condition_iter) {
596 used_patterns.insert(condition_iter->substring_pattern()->id());
597 }
598 }
599 condition_factory_.ForgetUnusedPatterns(used_patterns);
600}
601
602void URLMatcher::UpdateInternalDatastructures() {
603 UpdateSubstringSetMatcher(false);
604 UpdateSubstringSetMatcher(true);
605 UpdateTriggers();
606 UpdateConditionFactory();
607}
608
609} // namespace extensions