We build up maps of both the existing MagicDNS configuration in hosts
and the desired MagicDNS configuration, compare the two, and only
write out a new one if there are changes. The comparison doesn't need
to be perfect, as the occasional false-positive is fine, but this
should greatly reduce rewrites of the hosts file.
I also changed the hosts updating code to remove the CRLF/LF conversion
stuff, and use Fprintf instead of Frintln to let us write those inline.
Updates #14428
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
want:=[]byte("#foo\r\n#bar\r\n#baz\r\n# TailscaleHostsSectionStart\r\n# This section contains MagicDNS entries for Tailscale.\r\n# Do not edit this section manually.\r\n\r\n192.168.1.1 aaron\r\n\r\n# TailscaleHostsSectionEnd\r\n")
got,err:=setTailscaleHosts(in,nil)
he:=[]*HostEntry{
&HostEntry{
Addr:netip.MustParseAddr("192.168.1.1"),
Hosts:[]string{"aaron"},
},
}
got,err:=setTailscaleHosts(logger.Discard,in,he)
iferr!=nil{
t.Fatal(err)
}
if!bytes.Equal(got,want){
t.Errorf("got %q, want %q\n",got,want)
}
}
funcTestHostFileUnchanged(t*testing.T){
in:=[]byte("#foo\r\n#bar\r\n#baz\r\n# TailscaleHostsSectionStart\r\n# This section contains MagicDNS entries for Tailscale.\r\n# Do not edit this section manually.\r\n\r\n192.168.1.1 aaron\r\n\r\n# TailscaleHostsSectionEnd\r\n")
he:=[]*HostEntry{
&HostEntry{
Addr:netip.MustParseAddr("192.168.1.1"),
Hosts:[]string{"aaron"},
},
}
got,err:=setTailscaleHosts(logger.Discard,in,he)
iferr!=nil{
t.Fatal(err)
}
ifgot!=nil{
t.Errorf("got %q, want nil\n",got)
}
}
funcTestHostFileChanged(t*testing.T){
in:=[]byte("#foo\r\n#bar\r\n#baz\r\n# TailscaleHostsSectionStart\r\n# This section contains MagicDNS entries for Tailscale.\r\n# Do not edit this section manually.\r\n\r\n192.168.1.1 aaron1\r\n\r\n# TailscaleHostsSectionEnd\r\n")
want:=[]byte("#foo\r\n#bar\r\n#baz\r\n# TailscaleHostsSectionStart\r\n# This section contains MagicDNS entries for Tailscale.\r\n# Do not edit this section manually.\r\n\r\n192.168.1.1 aaron1\r\n192.168.1.2 aaron2\r\n\r\n# TailscaleHostsSectionEnd\r\n")