default.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package impl
  2. import (
  3. "github.com/v2ray/v2ray-core/app"
  4. "github.com/v2ray/v2ray-core/app/proxyman"
  5. "github.com/v2ray/v2ray-core/app/router"
  6. "github.com/v2ray/v2ray-core/common/alloc"
  7. "github.com/v2ray/v2ray-core/common/log"
  8. v2net "github.com/v2ray/v2ray-core/common/net"
  9. "github.com/v2ray/v2ray-core/proxy"
  10. "github.com/v2ray/v2ray-core/transport/ray"
  11. )
  12. type DefaultDispatcher struct {
  13. ohm proxyman.OutboundHandlerManager
  14. router router.Router
  15. }
  16. func NewDefaultDispatcher(space app.Space) *DefaultDispatcher {
  17. d := &DefaultDispatcher{}
  18. space.InitializeApplication(func() error {
  19. return d.Initialize(space)
  20. })
  21. return d
  22. }
  23. // @Private
  24. func (this *DefaultDispatcher) Initialize(space app.Space) error {
  25. if !space.HasApp(proxyman.APP_ID_OUTBOUND_MANAGER) {
  26. log.Error("DefaultDispatcher: OutboundHandlerManager is not found in the space.")
  27. return app.ErrMissingApplication
  28. }
  29. this.ohm = space.GetApp(proxyman.APP_ID_OUTBOUND_MANAGER).(proxyman.OutboundHandlerManager)
  30. if space.HasApp(router.APP_ID) {
  31. this.router = space.GetApp(router.APP_ID).(router.Router)
  32. }
  33. return nil
  34. }
  35. func (this *DefaultDispatcher) Release() {
  36. }
  37. func (this *DefaultDispatcher) DispatchToOutbound(meta *proxy.InboundHandlerMeta, session *proxy.SessionInfo) ray.InboundRay {
  38. direct := ray.NewRay()
  39. dispatcher := this.ohm.GetDefaultHandler()
  40. destination := session.Destination
  41. if this.router != nil {
  42. if tag, err := this.router.TakeDetour(destination); err == nil {
  43. if handler := this.ohm.GetHandler(tag); handler != nil {
  44. log.Info("DefaultDispatcher: Taking detour [", tag, "] for [", destination, "].")
  45. dispatcher = handler
  46. } else {
  47. log.Warning("DefaultDispatcher: Nonexisting tag: ", tag)
  48. }
  49. } else {
  50. log.Info("DefaultDispatcher: Default route for ", destination)
  51. }
  52. }
  53. if meta.AllowPassiveConnection {
  54. go dispatcher.Dispatch(destination, alloc.NewLocalBuffer(32).Clear(), direct)
  55. } else {
  56. go this.FilterPacketAndDispatch(destination, direct, dispatcher)
  57. }
  58. return direct
  59. }
  60. // @Private
  61. func (this *DefaultDispatcher) FilterPacketAndDispatch(destination v2net.Destination, link ray.OutboundRay, dispatcher proxy.OutboundHandler) {
  62. payload, err := link.OutboundInput().Read()
  63. if err != nil {
  64. log.Info("DefaultDispatcher: No payload towards ", destination, ", stopping now.")
  65. link.OutboundInput().Release()
  66. link.OutboundOutput().Release()
  67. return
  68. }
  69. dispatcher.Dispatch(destination, payload, link)
  70. }