github.com/liloew/wireguard-go@v0.0.0-20220224014633-9cd745e6f114/device/tun.go (about)

     1  /* SPDX-License-Identifier: MIT
     2   *
     3   * Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved.
     4   */
     5  
     6  package device
     7  
     8  import (
     9  	"fmt"
    10  	"sync/atomic"
    11  
    12  	"github.com/liloew/wireguard-go/tun"
    13  )
    14  
    15  const DefaultMTU = 1420
    16  
    17  func (device *Device) RoutineTUNEventReader() {
    18  	device.log.Verbosef("Routine: event worker - started")
    19  
    20  	for event := range device.tun.device.Events() {
    21  		if event&tun.EventMTUUpdate != 0 {
    22  			mtu, err := device.tun.device.MTU()
    23  			if err != nil {
    24  				device.log.Errorf("Failed to load updated MTU of device: %v", err)
    25  				continue
    26  			}
    27  			if mtu < 0 {
    28  				device.log.Errorf("MTU not updated to negative value: %v", mtu)
    29  				continue
    30  			}
    31  			var tooLarge string
    32  			if mtu > MaxContentSize {
    33  				tooLarge = fmt.Sprintf(" (too large, capped at %v)", MaxContentSize)
    34  				mtu = MaxContentSize
    35  			}
    36  			old := atomic.SwapInt32(&device.tun.mtu, int32(mtu))
    37  			if int(old) != mtu {
    38  				device.log.Verbosef("MTU updated: %v%s", mtu, tooLarge)
    39  			}
    40  		}
    41  
    42  		if event&tun.EventUp != 0 {
    43  			device.log.Verbosef("Interface up requested")
    44  			device.Up()
    45  		}
    46  
    47  		if event&tun.EventDown != 0 {
    48  			device.log.Verbosef("Interface down requested")
    49  			device.Down()
    50  		}
    51  	}
    52  
    53  	device.log.Verbosef("Routine: event worker - stopped")
    54  }