tun_linux.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. // Copyright 2025 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package vnet
  15. import (
  16. "context"
  17. "crypto/sha256"
  18. "encoding/hex"
  19. "fmt"
  20. "net"
  21. "strconv"
  22. "strings"
  23. "github.com/vishvananda/netlink"
  24. "golang.zx2c4.com/wireguard/tun"
  25. )
  26. const (
  27. baseTunName = "utun"
  28. defaultMTU = 1420
  29. )
  30. func openTun(_ context.Context, addr string) (tun.Device, error) {
  31. name, err := findNextTunName(baseTunName)
  32. if err != nil {
  33. name = getFallbackTunName(baseTunName, addr)
  34. }
  35. tunDevice, err := tun.CreateTUN(name, defaultMTU)
  36. if err != nil {
  37. return nil, fmt.Errorf("failed to create TUN device '%s': %w", name, err)
  38. }
  39. actualName, err := tunDevice.Name()
  40. if err != nil {
  41. return nil, err
  42. }
  43. ifn, err := net.InterfaceByName(actualName)
  44. if err != nil {
  45. return nil, err
  46. }
  47. link, err := netlink.LinkByName(actualName)
  48. if err != nil {
  49. return nil, err
  50. }
  51. ip, cidr, err := net.ParseCIDR(addr)
  52. if err != nil {
  53. return nil, err
  54. }
  55. if err := netlink.AddrAdd(link, &netlink.Addr{
  56. IPNet: &net.IPNet{
  57. IP: ip,
  58. Mask: cidr.Mask,
  59. },
  60. }); err != nil {
  61. return nil, err
  62. }
  63. if err := netlink.LinkSetUp(link); err != nil {
  64. return nil, err
  65. }
  66. if err = addRoutes(ifn, cidr); err != nil {
  67. return nil, err
  68. }
  69. return tunDevice, nil
  70. }
  71. func findNextTunName(basename string) (string, error) {
  72. interfaces, err := net.Interfaces()
  73. if err != nil {
  74. return "", fmt.Errorf("failed to get network interfaces: %w", err)
  75. }
  76. maxSuffix := -1
  77. for _, iface := range interfaces {
  78. name := iface.Name
  79. if strings.HasPrefix(name, basename) {
  80. suffix := name[len(basename):]
  81. if suffix == "" {
  82. continue
  83. }
  84. numSuffix, err := strconv.Atoi(suffix)
  85. if err == nil && numSuffix > maxSuffix {
  86. maxSuffix = numSuffix
  87. }
  88. }
  89. }
  90. nextSuffix := maxSuffix + 1
  91. name := fmt.Sprintf("%s%d", basename, nextSuffix)
  92. return name, nil
  93. }
  94. func addRoutes(ifn *net.Interface, cidr *net.IPNet) error {
  95. r := netlink.Route{
  96. Dst: cidr,
  97. LinkIndex: ifn.Index,
  98. }
  99. if err := netlink.RouteReplace(&r); err != nil {
  100. return fmt.Errorf("add route to %v error: %v", r.Dst, err)
  101. }
  102. return nil
  103. }
  104. // getFallbackTunName generates a deterministic fallback TUN device name
  105. // based on the base name and the provided address string using a hash.
  106. func getFallbackTunName(baseName, addr string) string {
  107. hasher := sha256.New()
  108. hasher.Write([]byte(addr))
  109. hashBytes := hasher.Sum(nil)
  110. // Use first 4 bytes -> 8 hex chars for brevity, respecting IFNAMSIZ limit.
  111. shortHash := hex.EncodeToString(hashBytes[:4])
  112. return fmt.Sprintf("%s%s", baseName, shortHash)
  113. }