1
0
mirror of https://github.com/fatedier/frp.git synced 2025-05-30 03:58:26 +00:00
2025-04-07 22:08:49 +08:00

76 lines
1.8 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"
)
type tunDevice struct {
dev tun.Device
}
func (d *tunDevice) Read(p []byte) (int, error) {
// Wireguard's TUN implementation expects a 4-byte offset before the data
// Make a larger buffer with room for the offset
buf := make([]byte, len(p)+4)
// Create sizes array for wireguard to populate
sz := make([]int, 1)
// Call wireguard's Read with offset=4
n, err := d.dev.Read([][]byte{buf}, sz, 4)
if err != nil {
return 0, err
}
if n == 0 {
return 0, io.EOF
}
// Copy the actual data (excluding the 4-byte offset) to the output buffer
dataSize := sz[0]
if dataSize > len(p) {
dataSize = len(p)
}
copy(p, buf[4:4+dataSize])
return dataSize, nil
}
func (d *tunDevice) Write(p []byte) (int, error) {
buf := make([]byte, len(p)+4)
copy(buf[4:], p)
return d.dev.Write([][]byte{buf}, 4)
}
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
}