tun.go 1.9 KB

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