tun.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //go:build !confonly
  2. // +build !confonly
  3. package tun
  4. import (
  5. "context"
  6. "gvisor.dev/gvisor/pkg/tcpip/stack"
  7. core "github.com/v2fly/v2ray-core/v5"
  8. "github.com/v2fly/v2ray-core/v5/app/tun/device"
  9. "github.com/v2fly/v2ray-core/v5/app/tun/device/gvisor"
  10. "github.com/v2fly/v2ray-core/v5/app/tun/tunsorter"
  11. "github.com/v2fly/v2ray-core/v5/common"
  12. "github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
  13. "github.com/v2fly/v2ray-core/v5/features/policy"
  14. "github.com/v2fly/v2ray-core/v5/features/routing"
  15. )
  16. //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
  17. type TUN struct {
  18. ctx context.Context
  19. dispatcher routing.Dispatcher
  20. policyManager policy.Manager
  21. config *Config
  22. stack *stack.Stack
  23. }
  24. func (t *TUN) Type() interface{} {
  25. return (*TUN)(nil)
  26. }
  27. func (t *TUN) Start() error {
  28. DeviceConstructor := gvisor.New
  29. tunDevice, err := DeviceConstructor(device.Options{
  30. Name: t.config.Name,
  31. MTU: t.config.Mtu,
  32. })
  33. if err != nil {
  34. return newError("failed to create device").Base(err).AtError()
  35. }
  36. if t.config.PacketEncoding != packetaddr.PacketAddrType_None {
  37. writer := device.NewLinkWriterToWriter(tunDevice)
  38. sorter := tunsorter.NewTunSorter(writer, t.dispatcher, t.config.PacketEncoding, t.ctx)
  39. tunDeviceLayered := NewDeviceWithSorter(tunDevice, sorter)
  40. tunDevice = tunDeviceLayered
  41. }
  42. stack, err := t.CreateStack(tunDevice)
  43. if err != nil {
  44. return newError("failed to create stack").Base(err).AtError()
  45. }
  46. t.stack = stack
  47. return nil
  48. }
  49. func (t *TUN) Close() error {
  50. if t.stack != nil {
  51. t.stack.Close()
  52. t.stack.Wait()
  53. }
  54. return nil
  55. }
  56. func (t *TUN) Init(ctx context.Context, config *Config, dispatcher routing.Dispatcher, policyManager policy.Manager) error {
  57. t.ctx = ctx
  58. t.config = config
  59. t.dispatcher = dispatcher
  60. t.policyManager = policyManager
  61. return nil
  62. }
  63. func init() {
  64. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  65. tun := new(TUN)
  66. err := core.RequireFeatures(ctx, func(d routing.Dispatcher, p policy.Manager) error {
  67. return tun.Init(ctx, config.(*Config), d, p)
  68. })
  69. return tun, err
  70. }))
  71. }