default.go 2.2 KB

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