tun_linux.go 897 B

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build linux
  4. package prober
  5. import (
  6. "fmt"
  7. "net/netip"
  8. "github.com/tailscale/netlink"
  9. "go4.org/netipx"
  10. )
  11. const tunName = "derpprobe"
  12. func configureTUN(addr netip.Prefix, tunname string) error {
  13. link, err := netlink.LinkByName(tunname)
  14. if err != nil {
  15. return fmt.Errorf("failed to look up link %q: %w", tunname, err)
  16. }
  17. // We need to bring the TUN device up before assigning an address. This
  18. // allows the OS to automatically create a route for it. Otherwise, we'd
  19. // have to manually create the route.
  20. if err := netlink.LinkSetUp(link); err != nil {
  21. return fmt.Errorf("failed to bring tun %q up: %w", tunname, err)
  22. }
  23. if err := netlink.AddrReplace(link, &netlink.Addr{IPNet: netipx.PrefixIPNet(addr)}); err != nil {
  24. return fmt.Errorf("failed to add address: %w", err)
  25. }
  26. return nil
  27. }