From 675ff32e6c29b4547e854c73b6aa6fdabe2cd0f5 Mon Sep 17 00:00:00 2001 From: Josh Bleecher Snyder Date: Thu, 21 Jan 2021 09:23:45 -0800 Subject: device: improve MTU change handling The old code silently accepted negative MTUs. It also set MTUs above the maximum. It also had hard to follow deeply nested conditionals. Add more paranoid handling, and make the code more straight-line. Signed-off-by: Josh Bleecher Snyder --- device/tun.go | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) (limited to 'device') diff --git a/device/tun.go b/device/tun.go index 9ff6c23..17c2493 100644 --- a/device/tun.go +++ b/device/tun.go @@ -6,6 +6,7 @@ package device import ( + "fmt" "sync/atomic" "golang.zx2c4.com/wireguard/tun" @@ -20,16 +21,22 @@ func (device *Device) RoutineTUNEventReader() { for event := range device.tun.device.Events() { if event&tun.EventMTUUpdate != 0 { mtu, err := device.tun.device.MTU() - old := atomic.LoadInt32(&device.tun.mtu) if err != nil { device.log.Errorf("Failed to load updated MTU of device: %v", err) - } else if int(old) != mtu { - if mtu+MessageTransportSize > MaxMessageSize { - device.log.Verbosef("MTU updated: %v (too large)", mtu) - } else { - device.log.Verbosef("MTU updated: %v", mtu) - } - atomic.StoreInt32(&device.tun.mtu, int32(mtu)) + continue + } + if mtu < 0 { + device.log.Errorf("MTU not updated to negative value: %v", mtu) + continue + } + var tooLarge string + if mtu > MaxContentSize { + tooLarge = fmt.Sprintf(" (too large, capped at %v)", MaxContentSize) + mtu = MaxContentSize + } + old := atomic.SwapInt32(&device.tun.mtu, int32(mtu)) + if int(old) != mtu { + device.log.Verbosef("MTU updated: %v%s", mtu, tooLarge) } } -- cgit v1.2.3