blob: 8ee6d87ecb932df22e3c15b677310dcb7f9f5fa6 [file] [log] [blame]
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "base/basictypes.h"
#include "base/containers/hash_tables.h"
#include "base/files/file_path.h"
#include "net/base/address_family.h"
#include "net/base/net_export.h"
#include "net/base/net_util.h" // can't forward-declare IPAddressNumber
namespace net {
typedef std::pair<std::string, AddressFamily> DnsHostsKey;
struct hash<net::DnsHostsKey> {
std::size_t operator()(const net::DnsHostsKey& key) const {
hash<base::StringPiece> string_piece_hash;
return string_piece_hash(key.first) + key.second;
} // namespace BASE_HASH_NAMESPACE
namespace net {
// There are OS-specific variations in how commas in the hosts file behave.
enum ParseHostsCommaMode {
// Comma is treated as part of a hostname:
// " foo,bar" parses as "foo,bar" mapping to "".
// Comma is treated as a hostname separator:
// " foo,bar" parses as "foo" and "bar" both mapping to "".
// Parsed results of a Hosts file.
// Although Hosts files map IP address to a list of domain names, for name
// resolution the desired mapping direction is: domain name to IP address.
// When parsing Hosts, we apply the "first hit" rule as Windows and glibc do.
// With a Hosts file of:
// 300.300.300.300 localhost # bad ip
// localhost
// localhost
// The expected resolution of localhost is
#if !defined(OS_ANDROID)
typedef base::hash_map<DnsHostsKey, IPAddressNumber> DnsHosts;
// Android's hash_map doesn't support ==, so fall back to map. (Chromium on
// Android doesn't use the built-in DNS resolver anyway, so it's irrelevant.)
typedef std::map<DnsHostsKey, IPAddressNumber> DnsHosts;
// Parses |contents| (as read from /etc/hosts or equivalent) and stores results
// in |dns_hosts|. Invalid lines are ignored (as in most implementations).
// Overrides the OS-specific default handling of commas, so unittests can test
// both modes.
void NET_EXPORT_PRIVATE ParseHostsWithCommaModeForTesting(
const std::string& contents,
DnsHosts* dns_hosts,
ParseHostsCommaMode comma_mode);
// Parses |contents| (as read from /etc/hosts or equivalent) and stores results
// in |dns_hosts|. Invalid lines are ignored (as in most implementations).
void NET_EXPORT_PRIVATE ParseHosts(const std::string& contents,
DnsHosts* dns_hosts);
// As above but reads the file pointed to by |path|.
bool NET_EXPORT_PRIVATE ParseHostsFile(const base::FilePath& path,
DnsHosts* dns_hosts);
} // namespace net
#endif // NET_DNS_DNS_HOSTS_H_