default.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package impl
  2. import (
  3. "github.com/v2ray/v2ray-core/app"
  4. "github.com/v2ray/v2ray-core/app/dns"
  5. "github.com/v2ray/v2ray-core/app/proxyman"
  6. "github.com/v2ray/v2ray-core/app/router"
  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. dns dns.Server
  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
  25. func (this *DefaultDispatcher) Initialize(space app.Space) error {
  26. if !space.HasApp(proxyman.APP_ID_OUTBOUND_MANAGER) {
  27. log.Error("DefaultDispatcher: OutboundHandlerManager is not found in the space.")
  28. return app.ErrorMissingApplication
  29. }
  30. this.ohm = space.GetApp(proxyman.APP_ID_OUTBOUND_MANAGER).(proxyman.OutboundHandlerManager)
  31. if !space.HasApp(dns.APP_ID) {
  32. log.Error("DefaultDispatcher: DNS is not found in the space.")
  33. return app.ErrorMissingApplication
  34. }
  35. this.dns = space.GetApp(dns.APP_ID).(dns.Server)
  36. if space.HasApp(router.APP_ID) {
  37. this.router = space.GetApp(router.APP_ID).(router.Router)
  38. }
  39. return nil
  40. }
  41. func (this *DefaultDispatcher) Release() {
  42. }
  43. func (this *DefaultDispatcher) DispatchToOutbound(destination v2net.Destination) ray.InboundRay {
  44. direct := ray.NewRay()
  45. dispatcher := this.ohm.GetDefaultHandler()
  46. if this.router != nil {
  47. if tag, err := this.router.TakeDetour(destination); err == nil {
  48. if handler := this.ohm.GetHandler(tag); handler != nil {
  49. log.Info("DefaultDispatcher: Taking detour [", tag, "] for [", destination, "].")
  50. dispatcher = handler
  51. } else {
  52. log.Warning("DefaultDispatcher: Nonexisting tag: ", tag)
  53. }
  54. } else {
  55. log.Info("DefaultDispatcher: Default route for ", destination)
  56. }
  57. }
  58. go this.FilterPacketAndDispatch(destination, direct, dispatcher)
  59. return direct
  60. }
  61. // @Private
  62. func (this *DefaultDispatcher) FilterPacketAndDispatch(destination v2net.Destination, link ray.OutboundRay, dispatcher proxy.OutboundHandler) {
  63. payload, err := link.OutboundInput().Read()
  64. if err != nil {
  65. log.Info("DefaultDispatcher: No payload to dispatch, stopping now.")
  66. link.OutboundInput().Release()
  67. link.OutboundOutput().Release()
  68. return
  69. }
  70. dispatcher.Dispatch(destination, payload, link)
  71. }