tun: NetlinkListener: don't send EventDown before sending EventUp

This works around a startup race condition when competing with
HackListener, which is trying to do the same job. If HackListener
detects that the tundev is running while there is still an event in the
netlink queue that says it isn't running, then the device receives a
string of events like
	EventUp (HackListener)
	EventDown (NetlinkListener)
	EventUp (NetlinkListener)
Unfortunately, after the first EventDown, the device stops itself,
thinking incorrectly that the administrator has downed its tundev.

The device is ignoring the initial EventDown anyway, so just don't emit
it.

Signed-off-by: Avery Pennarun <apenwarr@tailscale.com>
This commit is contained in:
Avery Pennarun 2019-11-06 00:28:02 -08:00 committed by Jason A. Donenfeld
parent de374bfb44
commit c76b818466

View file

@ -66,14 +66,19 @@ func (tun *NativeTun) routineHackListener() {
} }
switch err { switch err {
case unix.EINVAL: case unix.EINVAL:
// If the tunnel is up, it reports that write() is
// allowed but we provided invalid data.
tun.events <- EventUp tun.events <- EventUp
case unix.EIO: case unix.EIO:
// If the tunnel is down, it reports that no I/O
// is possible, without checking our provided data.
tun.events <- EventDown tun.events <- EventDown
default: default:
return return
} }
select { select {
case <-time.After(time.Second): case <-time.After(time.Second):
// nothing
case <-tun.statusListenersShutdown: case <-tun.statusListenersShutdown:
return return
} }
@ -128,6 +133,7 @@ func (tun *NativeTun) routineNetlinkListener() {
default: default:
} }
wasEverUp := false
for remain := msg[:msgn]; len(remain) >= unix.SizeofNlMsghdr; { for remain := msg[:msgn]; len(remain) >= unix.SizeofNlMsghdr; {
hdr := *(*unix.NlMsghdr)(unsafe.Pointer(&remain[0])) hdr := *(*unix.NlMsghdr)(unsafe.Pointer(&remain[0]))
@ -151,11 +157,17 @@ func (tun *NativeTun) routineNetlinkListener() {
if info.Flags&unix.IFF_RUNNING != 0 { if info.Flags&unix.IFF_RUNNING != 0 {
tun.events <- EventUp tun.events <- EventUp
wasEverUp = true
} }
if info.Flags&unix.IFF_RUNNING == 0 { if info.Flags&unix.IFF_RUNNING == 0 {
// Don't emit EventDown before we've ever emitted EventUp.
// This avoids a startup race with HackListener, which
// might detect Up before we have finished reporting Down.
if wasEverUp {
tun.events <- EventDown tun.events <- EventDown
} }
}
tun.events <- EventMTUUpdate tun.events <- EventMTUUpdate