frp/pkg/vnet/tun.go
2025-04-08 22:33:02 +08:00

74 lines
1.6 KiB
Go

// Copyright 2025 The frp Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package vnet
import (
"io"
"golang.zx2c4.com/wireguard/tun"
)
const (
offset = 16
)
type tunDevice struct {
dev tun.Device
}
func (d *tunDevice) Read(p []byte) (int, error) {
buf := make([]byte, len(p)+offset)
sz := make([]int, 1)
n, err := d.dev.Read([][]byte{buf}, sz, offset)
if err != nil {
return 0, err
}
if n == 0 {
return 0, io.EOF
}
dataSize := sz[0]
if dataSize > len(p) {
dataSize = len(p)
}
copy(p, buf[offset:offset+dataSize])
return dataSize, nil
}
func (d *tunDevice) Write(p []byte) (int, error) {
buf := make([]byte, len(p)+offset)
copy(buf[offset:], p)
return d.dev.Write([][]byte{buf}, offset)
}
func (d *tunDevice) Close() error {
return d.dev.Close()
}
func createTunDevice(adviceName string, mtu int) (io.ReadWriteCloser, string, error) {
ifce, err := tun.CreateTUN(adviceName, mtu)
if err != nil {
return nil, "", err
}
name, err := ifce.Name()
if err != nil {
return nil, "", err
}
return &tunDevice{dev: ifce}, name, nil
}