* auto-hosts: support '#' comments after ip and hosts

Close #1807

Squashed commit of the following:

commit 9d3e2809df056354bb6195abf8106616c1e214b1
Author: Simon Zolin <s.zolin@adguard.com>
Date:   Wed Jun 17 19:23:15 2020 +0300

    improve

commit 9b8c7104560c9c80f848f15818d49a065a38e498
Author: Simon Zolin <s.zolin@adguard.com>
Date:   Wed Jun 17 11:07:56 2020 +0300

    * auto-hosts: support '#' comments after ip and hosts
This commit is contained in:
Simon Zolin 2020-06-17 19:36:35 +03:00
parent ec6ca93acd
commit 4870da7f94
2 changed files with 16 additions and 2 deletions

View File

@ -172,8 +172,18 @@ func (a *AutoHosts) load(table map[string][]net.IP, tableRev map[string]string,
if len(host) == 0 { if len(host) == 0 {
break break
} }
sharp := strings.IndexByte(host, '#')
if sharp == 0 {
break // skip the rest of the line after #
} else if sharp > 0 {
host = host[:sharp]
}
a.updateTable(table, host, ipAddr) a.updateTable(table, host, ipAddr)
a.updateTableRev(tableRev, host, ipAddr) a.updateTableRev(tableRev, host, ipAddr)
if sharp >= 0 {
break // skip the rest of the line after #
}
} }
} }
} }

View File

@ -29,8 +29,8 @@ func TestAutoHostsResolution(t *testing.T) {
defer func() { _ = os.Remove(f.Name()) }() defer func() { _ = os.Remove(f.Name()) }()
defer f.Close() defer f.Close()
_, _ = f.WriteString(" 127.0.0.1 host localhost \n") _, _ = f.WriteString(" 127.0.0.1 host localhost # comment \n")
_, _ = f.WriteString(" ::1 localhost \n") _, _ = f.WriteString(" ::1 localhost#comment \n")
ah.Init(f.Name()) ah.Init(f.Name())
@ -47,6 +47,10 @@ func TestAutoHostsResolution(t *testing.T) {
ips = ah.Process("newhost", dns.TypeA) ips = ah.Process("newhost", dns.TypeA)
assert.Nil(t, ips) assert.Nil(t, ips)
// Unknown host (comment)
ips = ah.Process("comment", dns.TypeA)
assert.Nil(t, ips)
// Test hosts file // Test hosts file
table := ah.List() table := ah.List()
name, ok := table["127.0.0.1"] name, ok := table["127.0.0.1"]