tun.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 NewTUN(ctx context.Context, config *Config, dispatcher routing.Dispatcher) *TUN {
  49. v := core.MustFromContext(ctx)
  50. return &TUN{
  51. ctx: ctx,
  52. dispatcher: dispatcher,
  53. config: config,
  54. policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
  55. }
  56. }
  57. func init() {
  58. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  59. tun := core.RequireFeatures(ctx, func(d routing.Dispatcher) *TUN {
  60. return NewTUN(ctx, config.(*Config), d)
  61. })
  62. return tun, nil
  63. }))
  64. }