xref: /aosp_15_r20/external/cronet/net/base/host_mapping_rules.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef NET_BASE_HOST_MAPPING_RULES_H_
6 #define NET_BASE_HOST_MAPPING_RULES_H_
7 
8 #include <string_view>
9 #include <vector>
10 
11 #include "net/base/net_export.h"
12 
13 class GURL;
14 
15 namespace net {
16 
17 class HostPortPair;
18 
19 class NET_EXPORT_PRIVATE HostMappingRules {
20  public:
21   enum class RewriteResult {
22     kRewritten,
23     kNoMatchingRule,
24     kInvalidRewrite,
25   };
26 
27   HostMappingRules();
28   HostMappingRules(const HostMappingRules& host_mapping_rules);
29   ~HostMappingRules();
30 
31   HostMappingRules& operator=(const HostMappingRules& host_mapping_rules);
32 
33   // Modifies `*host_port` based on the current rules. Returns true if
34   // `*host_port` was modified, false otherwise.
35   bool RewriteHost(HostPortPair* host_port) const;
36 
37   // Modifies the host and port of `url` based on current rules. May only be
38   // called for URLs with a host and a scheme that is standard, and if the
39   // scheme does not allow ports, only the host will be rewritten.
40   //
41   // If `url` is rewritten, returns `kRewritten`. If no matching rule is found,
42   // returns `kNoMatchingRule` and `url` is not modified. If a matching rule is
43   // found but it results in an invalid URL, e.g. if the rule maps to
44   // "^NOTFOUND", returns `kInvalidRewrite` and `url` is not modified.
45   RewriteResult RewriteUrl(GURL& url) const;
46 
47   // Adds a rule to this mapper. The format of the rule can be one of:
48   //
49   //   "MAP" <hostname_pattern> <replacement_host> [":" <replacement_port>]
50   //   "EXCLUDE" <hostname_pattern>
51   //
52   // The <replacement_host> can be either a hostname, or an IP address literal.
53   //
54   // Returns true if the rule was successfully parsed and added.
55   bool AddRuleFromString(std::string_view rule_string);
56 
57   // Sets the rules from a comma separated list of rules.
58   void SetRulesFromString(std::string_view rules_string);
59 
60  private:
61   struct MapRule;
62   struct ExclusionRule;
63 
64   typedef std::vector<MapRule> MapRuleList;
65   typedef std::vector<ExclusionRule> ExclusionRuleList;
66 
67   MapRuleList map_rules_;
68   ExclusionRuleList exclusion_rules_;
69 };
70 
71 }  // namespace net
72 
73 #endif  // NET_BASE_HOST_MAPPING_RULES_H_
74