tun.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. DeviceConstructor := tun.New
  27. device, err := DeviceConstructor(device.Options{
  28. Name: t.config.Name,
  29. MTU: t.config.Mtu,
  30. })
  31. if err != nil {
  32. return newError("failed to create device").Base(err).AtError()
  33. }
  34. stack, err := t.CreateStack(device)
  35. if err != nil {
  36. return newError("failed to create stack").Base(err).AtError()
  37. }
  38. t.stack = stack
  39. return nil
  40. }
  41. func (t *TUN) Close() error {
  42. if t.stack != nil {
  43. t.stack.Close()
  44. t.stack.Wait()
  45. }
  46. return nil
  47. }
  48. func (t *TUN) Init(ctx context.Context, config *Config, dispatcher routing.Dispatcher, policyManager policy.Manager) error {
  49. t.ctx = ctx
  50. t.config = config
  51. t.dispatcher = dispatcher
  52. t.policyManager = policyManager
  53. return nil
  54. }
  55. func init() {
  56. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  57. tun := new(TUN)
  58. err := core.RequireFeatures(ctx, func(d routing.Dispatcher, p policy.Manager) error {
  59. return tun.Init(ctx, config.(*Config), d, p)
  60. })
  61. return tun, err
  62. }))
  63. }