tun.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "io"
  18. "github.com/fatedier/golib/pool"
  19. "golang.zx2c4.com/wireguard/tun"
  20. )
  21. const (
  22. offset = 16
  23. )
  24. type TunDevice interface {
  25. io.ReadWriteCloser
  26. }
  27. func OpenTun(ctx context.Context, addr string) (TunDevice, error) {
  28. td, err := openTun(ctx, addr)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return &tunDeviceWrapper{dev: td}, nil
  33. }
  34. type tunDeviceWrapper struct {
  35. dev tun.Device
  36. }
  37. func (d *tunDeviceWrapper) Read(p []byte) (int, error) {
  38. buf := pool.GetBuf(len(p) + offset)
  39. defer pool.PutBuf(buf)
  40. sz := make([]int, 1)
  41. n, err := d.dev.Read([][]byte{buf}, sz, offset)
  42. if err != nil {
  43. return 0, err
  44. }
  45. if n == 0 {
  46. return 0, io.EOF
  47. }
  48. dataSize := sz[0]
  49. if dataSize > len(p) {
  50. dataSize = len(p)
  51. }
  52. copy(p, buf[offset:offset+dataSize])
  53. return dataSize, nil
  54. }
  55. func (d *tunDeviceWrapper) Write(p []byte) (int, error) {
  56. buf := pool.GetBuf(len(p) + offset)
  57. defer pool.PutBuf(buf)
  58. copy(buf[offset:], p)
  59. return d.dev.Write([][]byte{buf}, offset)
  60. }
  61. func (d *tunDeviceWrapper) Close() error {
  62. return d.dev.Close()
  63. }