tun.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. DeviceCreator := tun.New
  27. device, err := DeviceCreator(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 := CreateStack(device)
  35. if err != nil {
  36. return newError("failed to create stack").Base(err).AtError()
  37. }
  38. t.stack = stack
  39. tcpHandler := &TCPHandler{
  40. ctx: t.ctx,
  41. dispatcher: t.dispatcher,
  42. policyManager: t.policyManager,
  43. config: t.config,
  44. stack: stack,
  45. }
  46. tcpHandler.SetHandler()
  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 NewTUN(ctx context.Context, config *Config, dispatcher routing.Dispatcher) *TUN {
  57. v := core.MustFromContext(ctx)
  58. return &TUN{
  59. ctx: ctx,
  60. dispatcher: dispatcher,
  61. config: config,
  62. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  63. }
  64. }
  65. func init() {
  66. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  67. tun := core.RequireFeatures(ctx, func(d routing.Dispatcher) *TUN {
  68. return NewTUN(ctx, config.(*Config), d)
  69. })
  70. return tun, nil
  71. }))
  72. }