default.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package impl
  2. import (
  3. "v2ray.com/core/app"
  4. "v2ray.com/core/app/proxyman"
  5. "v2ray.com/core/app/router"
  6. "v2ray.com/core/common/buf"
  7. "v2ray.com/core/common/errors"
  8. "v2ray.com/core/common/log"
  9. v2net "v2ray.com/core/common/net"
  10. "v2ray.com/core/proxy"
  11. "v2ray.com/core/transport/ray"
  12. )
  13. type DefaultDispatcher struct {
  14. ohm proxyman.OutboundHandlerManager
  15. router *router.Router
  16. }
  17. func NewDefaultDispatcher(space app.Space) *DefaultDispatcher {
  18. d := &DefaultDispatcher{}
  19. space.InitializeApplication(func() error {
  20. return d.Initialize(space)
  21. })
  22. return d
  23. }
  24. // Private: Used by app.Space only.
  25. func (v *DefaultDispatcher) Initialize(space app.Space) error {
  26. if !space.HasApp(proxyman.APP_ID_OUTBOUND_MANAGER) {
  27. return errors.New("DefaultDispatcher: OutboundHandlerManager is not found in the space.")
  28. }
  29. v.ohm = space.GetApp(proxyman.APP_ID_OUTBOUND_MANAGER).(proxyman.OutboundHandlerManager)
  30. if space.HasApp(router.APP_ID) {
  31. v.router = space.GetApp(router.APP_ID).(*router.Router)
  32. }
  33. return nil
  34. }
  35. func (v *DefaultDispatcher) Release() {
  36. }
  37. func (v *DefaultDispatcher) DispatchToOutbound(session *proxy.SessionInfo) ray.InboundRay {
  38. direct := ray.NewRay()
  39. dispatcher := v.ohm.GetDefaultHandler()
  40. destination := session.Destination
  41. if v.router != nil {
  42. if tag, err := v.router.TakeDetour(session); err == nil {
  43. if handler := v.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 session.Inbound != nil && session.Inbound.AllowPassiveConnection {
  54. go dispatcher.Dispatch(destination, buf.NewLocalBuffer(32), direct)
  55. } else {
  56. go v.FilterPacketAndDispatch(destination, direct, dispatcher)
  57. }
  58. return direct
  59. }
  60. // Private: Visible for testing.
  61. func (v *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. }