Move MatchPattern to its own header and the base namespace.
[chromium-blink-merge.git] / net / proxy / proxy_bypass_rules.cc
blobf2f32611e9b61b8d2489118e5ae7768a5e06ea4a
1 // Copyright (c) 2011 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.
5 #include "net/proxy/proxy_bypass_rules.h"
7 #include "base/stl_util.h"
8 #include "base/strings/pattern.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "base/strings/string_piece.h"
11 #include "base/strings/string_tokenizer.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/stringprintf.h"
14 #include "net/base/host_port_pair.h"
15 #include "net/base/ip_address_number.h"
16 #include "net/base/net_util.h"
18 namespace net {
20 namespace {
22 class HostnamePatternRule : public ProxyBypassRules::Rule {
23 public:
24 HostnamePatternRule(const std::string& optional_scheme,
25 const std::string& hostname_pattern,
26 int optional_port)
27 : optional_scheme_(base::StringToLowerASCII(optional_scheme)),
28 hostname_pattern_(base::StringToLowerASCII(hostname_pattern)),
29 optional_port_(optional_port) {
32 bool Matches(const GURL& url) const override {
33 if (optional_port_ != -1 && url.EffectiveIntPort() != optional_port_)
34 return false; // Didn't match port expectation.
36 if (!optional_scheme_.empty() && url.scheme() != optional_scheme_)
37 return false; // Didn't match scheme expectation.
39 // Note it is necessary to lower-case the host, since GURL uses capital
40 // letters for percent-escaped characters.
41 return base::MatchPattern(base::StringToLowerASCII(url.host()),
42 hostname_pattern_);
45 std::string ToString() const override {
46 std::string str;
47 if (!optional_scheme_.empty())
48 base::StringAppendF(&str, "%s://", optional_scheme_.c_str());
49 str += hostname_pattern_;
50 if (optional_port_ != -1)
51 base::StringAppendF(&str, ":%d", optional_port_);
52 return str;
55 Rule* Clone() const override {
56 return new HostnamePatternRule(optional_scheme_,
57 hostname_pattern_,
58 optional_port_);
61 private:
62 const std::string optional_scheme_;
63 const std::string hostname_pattern_;
64 const int optional_port_;
67 class BypassLocalRule : public ProxyBypassRules::Rule {
68 public:
69 bool Matches(const GURL& url) const override {
70 const std::string& host = url.host();
71 if (host == "127.0.0.1" || host == "[::1]")
72 return true;
73 return host.find('.') == std::string::npos;
76 std::string ToString() const override { return "<local>"; }
78 Rule* Clone() const override { return new BypassLocalRule(); }
81 // Rule for matching a URL that is an IP address, if that IP address falls
82 // within a certain numeric range. For example, you could use this rule to
83 // match all the IPs in the CIDR block 10.10.3.4/24.
84 class BypassIPBlockRule : public ProxyBypassRules::Rule {
85 public:
86 // |ip_prefix| + |prefix_length| define the IP block to match.
87 BypassIPBlockRule(const std::string& description,
88 const std::string& optional_scheme,
89 const IPAddressNumber& ip_prefix,
90 size_t prefix_length_in_bits)
91 : description_(description),
92 optional_scheme_(optional_scheme),
93 ip_prefix_(ip_prefix),
94 prefix_length_in_bits_(prefix_length_in_bits) {
97 bool Matches(const GURL& url) const override {
98 if (!url.HostIsIPAddress())
99 return false;
101 if (!optional_scheme_.empty() && url.scheme() != optional_scheme_)
102 return false; // Didn't match scheme expectation.
104 // Parse the input IP literal to a number.
105 IPAddressNumber ip_number;
106 if (!ParseIPLiteralToNumber(url.HostNoBrackets(), &ip_number))
107 return false;
109 // Test if it has the expected prefix.
110 return IPNumberMatchesPrefix(ip_number, ip_prefix_,
111 prefix_length_in_bits_);
114 std::string ToString() const override { return description_; }
116 Rule* Clone() const override {
117 return new BypassIPBlockRule(description_,
118 optional_scheme_,
119 ip_prefix_,
120 prefix_length_in_bits_);
123 private:
124 const std::string description_;
125 const std::string optional_scheme_;
126 const IPAddressNumber ip_prefix_;
127 const size_t prefix_length_in_bits_;
130 // Returns true if the given string represents an IP address.
131 // IPv6 addresses are expected to be bracketed.
132 bool IsIPAddress(const std::string& domain) {
133 // From GURL::HostIsIPAddress()
134 url::RawCanonOutputT<char, 128> ignored_output;
135 url::CanonHostInfo host_info;
136 url::Component domain_comp(0, domain.size());
137 url::CanonicalizeIPAddress(domain.c_str(), domain_comp, &ignored_output,
138 &host_info);
139 return host_info.IsIPAddress();
142 } // namespace
144 ProxyBypassRules::Rule::Rule() {
147 ProxyBypassRules::Rule::~Rule() {
150 bool ProxyBypassRules::Rule::Equals(const Rule& rule) const {
151 return ToString() == rule.ToString();
154 ProxyBypassRules::ProxyBypassRules() {
157 ProxyBypassRules::ProxyBypassRules(const ProxyBypassRules& rhs) {
158 AssignFrom(rhs);
161 ProxyBypassRules::~ProxyBypassRules() {
162 Clear();
165 ProxyBypassRules& ProxyBypassRules::operator=(const ProxyBypassRules& rhs) {
166 AssignFrom(rhs);
167 return *this;
170 bool ProxyBypassRules::Matches(const GURL& url) const {
171 for (RuleList::const_iterator it = rules_.begin(); it != rules_.end(); ++it) {
172 if ((*it)->Matches(url))
173 return true;
175 return false;
178 bool ProxyBypassRules::Equals(const ProxyBypassRules& other) const {
179 if (rules_.size() != other.rules_.size())
180 return false;
182 for (size_t i = 0; i < rules_.size(); ++i) {
183 if (!rules_[i]->Equals(*other.rules_[i]))
184 return false;
186 return true;
189 void ProxyBypassRules::ParseFromString(const std::string& raw) {
190 ParseFromStringInternal(raw, false);
193 void ProxyBypassRules::ParseFromStringUsingSuffixMatching(
194 const std::string& raw) {
195 ParseFromStringInternal(raw, true);
198 bool ProxyBypassRules::AddRuleForHostname(const std::string& optional_scheme,
199 const std::string& hostname_pattern,
200 int optional_port) {
201 if (hostname_pattern.empty())
202 return false;
204 rules_.push_back(new HostnamePatternRule(optional_scheme,
205 hostname_pattern,
206 optional_port));
207 return true;
210 void ProxyBypassRules::AddRuleToBypassLocal() {
211 rules_.push_back(new BypassLocalRule);
214 bool ProxyBypassRules::AddRuleFromString(const std::string& raw) {
215 return AddRuleFromStringInternalWithLogging(raw, false);
218 bool ProxyBypassRules::AddRuleFromStringUsingSuffixMatching(
219 const std::string& raw) {
220 return AddRuleFromStringInternalWithLogging(raw, true);
223 std::string ProxyBypassRules::ToString() const {
224 std::string result;
225 for (RuleList::const_iterator rule(rules_.begin());
226 rule != rules_.end();
227 ++rule) {
228 result += (*rule)->ToString();
229 result += ";";
231 return result;
234 void ProxyBypassRules::Clear() {
235 STLDeleteElements(&rules_);
238 void ProxyBypassRules::AssignFrom(const ProxyBypassRules& other) {
239 Clear();
241 // Make a copy of the rules list.
242 for (RuleList::const_iterator it = other.rules_.begin();
243 it != other.rules_.end(); ++it) {
244 rules_.push_back((*it)->Clone());
248 void ProxyBypassRules::ParseFromStringInternal(
249 const std::string& raw,
250 bool use_hostname_suffix_matching) {
251 Clear();
253 base::StringTokenizer entries(raw, ",;");
254 while (entries.GetNext()) {
255 AddRuleFromStringInternalWithLogging(entries.token(),
256 use_hostname_suffix_matching);
260 bool ProxyBypassRules::AddRuleFromStringInternal(
261 const std::string& raw_untrimmed,
262 bool use_hostname_suffix_matching) {
263 std::string raw;
264 base::TrimWhitespaceASCII(raw_untrimmed, base::TRIM_ALL, &raw);
266 // This is the special syntax used by WinInet's bypass list -- we allow it
267 // on all platforms and interpret it the same way.
268 if (base::LowerCaseEqualsASCII(raw, "<local>")) {
269 AddRuleToBypassLocal();
270 return true;
273 // Extract any scheme-restriction.
274 std::string::size_type scheme_pos = raw.find("://");
275 std::string scheme;
276 if (scheme_pos != std::string::npos) {
277 scheme = raw.substr(0, scheme_pos);
278 raw = raw.substr(scheme_pos + 3);
279 if (scheme.empty())
280 return false;
283 if (raw.empty())
284 return false;
286 // If there is a forward slash in the input, it is probably a CIDR style
287 // mask.
288 if (raw.find('/') != std::string::npos) {
289 IPAddressNumber ip_prefix;
290 size_t prefix_length_in_bits;
292 if (!ParseCIDRBlock(raw, &ip_prefix, &prefix_length_in_bits))
293 return false;
295 rules_.push_back(
296 new BypassIPBlockRule(raw, scheme, ip_prefix, prefix_length_in_bits));
298 return true;
301 // Check if we have an <ip-address>[:port] input. We need to treat this
302 // separately since the IP literal may not be in a canonical form.
303 std::string host;
304 int port;
305 if (ParseHostAndPort(raw, &host, &port)) {
306 // Note that HostPortPair is used to merely to convert any IPv6 literals to
307 // a URL-safe format that can be used by canonicalization below.
308 std::string bracketed_host = HostPortPair(host, 80).HostForURL();
309 if (IsIPAddress(bracketed_host)) {
310 // Canonicalize the IP literal before adding it as a string pattern.
311 GURL tmp_url("http://" + bracketed_host);
312 return AddRuleForHostname(scheme, tmp_url.host(), port);
316 // Otherwise assume we have <hostname-pattern>[:port].
317 std::string::size_type pos_colon = raw.rfind(':');
318 host = raw;
319 port = -1;
320 if (pos_colon != std::string::npos) {
321 if (!base::StringToInt(base::StringPiece(raw.begin() + pos_colon + 1,
322 raw.end()),
323 &port) ||
324 (port < 0 || port > 0xFFFF)) {
325 return false; // Port was invalid.
327 raw = raw.substr(0, pos_colon);
330 // Special-case hostnames that begin with a period.
331 // For example, we remap ".google.com" --> "*.google.com".
332 if (base::StartsWith(raw, ".", base::CompareCase::SENSITIVE))
333 raw = "*" + raw;
335 // If suffix matching was asked for, make sure the pattern starts with a
336 // wildcard.
337 if (use_hostname_suffix_matching &&
338 !base::StartsWith(raw, "*", base::CompareCase::SENSITIVE))
339 raw = "*" + raw;
341 return AddRuleForHostname(scheme, raw, port);
344 bool ProxyBypassRules::AddRuleFromStringInternalWithLogging(
345 const std::string& raw,
346 bool use_hostname_suffix_matching) {
347 return AddRuleFromStringInternal(raw, use_hostname_suffix_matching);
350 } // namespace net