| // |
| 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 |
| 15 | package vnet |
| 16 |
| 17 | import ( |
| 18 | "context" |
| 19 | "fmt" |
| 20 | "net" |
| 21 | "os/exec" |
| 22 |
| 23 | "golang.zx2c4.com/wireguard/tun" |
| 24 | ) |
| 25 |
| 26 | const ( |
| 27 | defaultTunName = "utun" |
| 28 | defaultMTU = 1420 |
| 29 | ) |
| 30 |
| 31 | func openTun(_ context.Context, addr string) (tun.Device, error) { |
| 32 | dev, err := tun.CreateTUN(defaultTunName, defaultMTU) |
| 33 | if err != nil { |
| 34 | return nil, err |
| 35 | } |
| 36 |
| 37 | name, err := dev.Name() |
| 38 | if err != nil { |
| 39 | return nil, err |
| 40 | } |
| 41 |
| 42 | ip, ipNet, err := net.ParseCIDR(addr) |
| 43 | if err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 |
| 47 | // Calculate a peer IP for the point-to-point tunnel |
| 48 | peerIP := generatePeerIP(ip) |
| 49 |
| 50 | // Configure the interface with proper point-to-point addressing |
| 51 | if err = exec.Command("ifconfig", name, "inet", ip.String(), peerIP.String(), "mtu", fmt.Sprint(defaultMTU), "up").Run(); err != nil { |
| 52 | return nil, err |
| 53 | } |
| 54 |
| 55 | // Add default route for the tunnel subnet |
| 56 | routes := []net.IPNet{*ipNet} |
| 57 | if err = addRoutes(name, routes); err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | return dev, nil |
| 61 | } |
| 62 |
| 63 | // generatePeerIP creates a peer IP for the point-to-point tunnel |
| 64 | // by incrementing the last octet of the IP |
| 65 | func generatePeerIP(ip net.IP) net.IP { |
| 66 | // Make a copy to avoid modifying the original |
| 67 | peerIP := make(net.IP, len(ip)) |
| 68 | copy(peerIP, ip) |
| 69 |
| 70 | // Increment the last octet |
| 71 | peerIP[len(peerIP)-1]++ |
| 72 |
| 73 | return peerIP |
| 74 | } |
| 75 |
| 76 | // addRoutes configures system routes for the TUN interface |
| 77 | func addRoutes(ifName string, routes []net.IPNet) error { |
| 78 | for _, route := range routes { |
| 79 | routeStr := route.String() |
| 80 | if err := exec.Command("route", "add", "-net", routeStr, "-interface", ifName).Run(); err != nil { |
| 81 | return err |
| 82 | } |
| 83 | } |
| 84 | return nil |
| 85 | } |