File: dns_hosts.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (251 lines) | stat: -rw-r--r-- 7,725 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/dns/dns_hosts.h"

#include <string>
#include <string_view>
#include <utility>

#include "base/check.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_util.h"
#include "base/trace_event/memory_usage_estimator.h"
#include "build/build_config.h"
#include "net/base/cronet_buildflags.h"
#include "net/base/url_util.h"
#include "net/dns/dns_util.h"
#include "url/url_canon.h"

namespace net {

namespace {

// Parses the contents of a hosts file.  Returns one token (IP or hostname) at
// a time.  Doesn't copy anything; accepts the file as a std::string_view and
// returns tokens as StringPieces.
class HostsParser {
 public:
  explicit HostsParser(std::string_view text, ParseHostsCommaMode comma_mode)
      : text_(text),
        end_(text.size()),
        comma_mode_(comma_mode) {}

  HostsParser(const HostsParser&) = delete;
  HostsParser& operator=(const HostsParser&) = delete;

  // Advances to the next token (IP or hostname).  Returns whether another
  // token was available.  |token_is_ip| and |token| can be used to find out
  // the type and text of the token.
  bool Advance() {
    bool next_is_ip = (pos_ == 0);
    while (pos_ < end_ && pos_ != std::string::npos) {
      switch (text_[pos_]) {
        case ' ':
        case '\t':
          SkipWhitespace();
          break;

        case '\r':
        case '\n':
          next_is_ip = true;
          pos_++;
          break;

        case '#':
          SkipRestOfLine();
          break;

        case ',':
          if (comma_mode_ == PARSE_HOSTS_COMMA_IS_WHITESPACE) {
            SkipWhitespace();
            break;
          }

          // If comma_mode_ is COMMA_IS_TOKEN, fall through:
          [[fallthrough]];

        default: {
          size_t token_start = pos_;
          SkipToken();
          size_t token_end = (pos_ == std::string::npos) ? end_ : pos_;

          token_ = text_.substr(token_start, token_end - token_start);
          token_is_ip_ = next_is_ip;

          return true;
        }
      }
    }

    return false;
  }

  // Fast-forwards the parser to the next line.  Should be called if an IP
  // address doesn't parse, to avoid wasting time tokenizing hostnames that
  // will be ignored.
  void SkipRestOfLine() { pos_ = text_.find("\n", pos_); }

  // Returns whether the last-parsed token is an IP address (true) or a
  // hostname (false).
  bool token_is_ip() { return token_is_ip_; }

  // Returns the text of the last-parsed token as a std::string_view referencing
  // the same underlying memory as the std::string_view passed to the
  // constructor. Returns an empty std::string_view if no token has been parsed
  // or the end of the input string has been reached.
  std::string_view token() { return token_; }

 private:
  void SkipToken() {
    switch (comma_mode_) {
      case PARSE_HOSTS_COMMA_IS_TOKEN:
        pos_ = text_.find_first_of(" \t\n\r#", pos_);
        break;
      case PARSE_HOSTS_COMMA_IS_WHITESPACE:
        pos_ = text_.find_first_of(" ,\t\n\r#", pos_);
        break;
    }
  }

  void SkipWhitespace() {
    switch (comma_mode_) {
      case PARSE_HOSTS_COMMA_IS_TOKEN:
        pos_ = text_.find_first_not_of(" \t", pos_);
        break;
      case PARSE_HOSTS_COMMA_IS_WHITESPACE:
        pos_ = text_.find_first_not_of(" ,\t", pos_);
        break;
    }
  }

  const std::string_view text_;
  const size_t end_;

  size_t pos_ = 0;
  std::string_view token_;
  bool token_is_ip_ = false;

  const ParseHostsCommaMode comma_mode_;
};

void ParseHostsWithCommaMode(const std::string& contents,
                             DnsHosts* dns_hosts,
                             ParseHostsCommaMode comma_mode) {
  CHECK(dns_hosts);

  std::string_view ip_text;
  IPAddress ip;
  AddressFamily family = ADDRESS_FAMILY_IPV4;
  HostsParser parser(contents, comma_mode);
  while (parser.Advance()) {
    if (parser.token_is_ip()) {
      std::string_view new_ip_text = parser.token();
      // Some ad-blocking hosts files contain thousands of entries pointing to
      // the same IP address (usually 127.0.0.1).  Don't bother parsing the IP
      // again if it's the same as the one above it.
      if (new_ip_text != ip_text) {
        IPAddress new_ip;
        if (new_ip.AssignFromIPLiteral(parser.token())) {
          ip_text = new_ip_text;
          ip = new_ip;
          family = (ip.IsIPv4()) ? ADDRESS_FAMILY_IPV4 : ADDRESS_FAMILY_IPV6;
        } else {
          parser.SkipRestOfLine();
        }
      }
    } else {
      url::CanonHostInfo canonicalization_info;
      std::string canonicalized_host =
          CanonicalizeHost(parser.token(), &canonicalization_info);

      // Skip if token is invalid for host canonicalization, or if it
      // canonicalizes as an IP address.
      if (canonicalization_info.family != url::CanonHostInfo::NEUTRAL)
        continue;

      DnsHostsKey key(std::move(canonicalized_host), family);
      if (!IsCanonicalizedHostCompliant(key.first))
        continue;
      IPAddress* mapped_ip = &(*dns_hosts)[key];
      if (mapped_ip->empty())
        *mapped_ip = ip;
      // else ignore this entry (first hit counts)
    }
  }
}

}  // namespace

void ParseHostsWithCommaModeForTesting(const std::string& contents,
                                       DnsHosts* dns_hosts,
                                       ParseHostsCommaMode comma_mode) {
  ParseHostsWithCommaMode(contents, dns_hosts, comma_mode);
}

void ParseHosts(const std::string& contents, DnsHosts* dns_hosts) {
  ParseHostsCommaMode comma_mode;
#if BUILDFLAG(IS_APPLE)
  // Mac OS X allows commas to separate hostnames.
  comma_mode = PARSE_HOSTS_COMMA_IS_WHITESPACE;
#else
  // Linux allows commas in hostnames.
  comma_mode = PARSE_HOSTS_COMMA_IS_TOKEN;
#endif

  ParseHostsWithCommaMode(contents, dns_hosts, comma_mode);

  // TODO(crbug.com/40874231): Remove this when we have enough data.
  base::UmaHistogramCounts100000("Net.DNS.DnsHosts.Count", dns_hosts->size());

#if !BUILDFLAG(CRONET_BUILD)
  // Cronet disables tracing and doesn't provide an implementation of
  // base::trace_event::EstimateMemoryUsage for DnsHosts. Having this
  // conditional is preferred over a fake implementation to avoid reporting fake
  // metrics.
  base::UmaHistogramMemoryKB(
      "Net.DNS.DnsHosts.EstimateMemoryUsage",
      base::trace_event::EstimateMemoryUsage(*dns_hosts));
#endif  // !BUILDFLAG(CRONET_BUILD)
}

DnsHostsParser::~DnsHostsParser() = default;

DnsHostsFileParser::DnsHostsFileParser(base::FilePath hosts_file_path)
    : hosts_file_path_(std::move(hosts_file_path)) {}

DnsHostsFileParser::~DnsHostsFileParser() = default;

bool DnsHostsFileParser::ParseHosts(DnsHosts* dns_hosts) const {
  dns_hosts->clear();
  // Missing file indicates empty HOSTS.
  if (!base::PathExists(hosts_file_path_))
    return true;

  std::optional<int64_t> size = base::GetFileSize(hosts_file_path_);
  if (!size.has_value()) {
    return false;
  }

  // Reject HOSTS files larger than |kMaxHostsSize| bytes.
  const int64_t kMaxHostsSize = 1 << 25;  // 32MB

  // TODO(crbug.com/40874231): Remove this when we have enough data.
  base::UmaHistogramCustomCounts("Net.DNS.DnsHosts.FileSize", size.value(), 1,
                                 kMaxHostsSize * 2, 50);
  if (size.value() > kMaxHostsSize) {
    return false;
  }

  std::string contents;
  if (!base::ReadFileToString(hosts_file_path_, &contents))
    return false;

  net::ParseHosts(contents, dns_hosts);
  return true;
}

}  // namespace net