default.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. if !space.HasApp(proxyman.APP_ID_OUTBOUND_MANAGER) {
  19. log.Error("DefaultDispatcher: OutboundHandlerManager is not found in the space.")
  20. return nil
  21. }
  22. if !space.HasApp(dns.APP_ID) {
  23. log.Error("DefaultDispatcher: DNS is not found in the space.")
  24. return nil
  25. }
  26. d := &DefaultDispatcher{
  27. ohm: space.GetApp(proxyman.APP_ID_OUTBOUND_MANAGER).(proxyman.OutboundHandlerManager),
  28. dns: space.GetApp(dns.APP_ID).(dns.Server),
  29. }
  30. if space.HasApp(router.APP_ID) {
  31. d.router = space.GetApp(router.APP_ID).(router.Router)
  32. }
  33. return d
  34. }
  35. func (this *DefaultDispatcher) DispatchToOutbound(destination v2net.Destination) ray.InboundRay {
  36. direct := ray.NewRay()
  37. dispatcher := this.ohm.GetDefaultHandler()
  38. if this.router != nil {
  39. if tag, err := this.router.TakeDetour(destination); err == nil {
  40. if handler := this.ohm.GetHandler(tag); handler != nil {
  41. log.Info("DefaultDispatcher: Taking detour [", tag, "] for [", destination, "].")
  42. dispatcher = handler
  43. } else {
  44. log.Warning("DefaultDispatcher: Nonexisting tag: ", tag)
  45. }
  46. } else {
  47. log.Info("DefaultDispatcher: Default route for ", destination)
  48. }
  49. }
  50. go this.FilterPacketAndDispatch(destination, direct, dispatcher)
  51. return direct
  52. }
  53. // @Private
  54. func (this *DefaultDispatcher) FilterPacketAndDispatch(destination v2net.Destination, link ray.OutboundRay, dispatcher proxy.OutboundHandler) {
  55. payload, err := link.OutboundInput().Read()
  56. if err != nil {
  57. log.Info("DefaultDispatcher: No payload to dispatch, stopping now.")
  58. link.OutboundInput().Release()
  59. link.OutboundOutput().Release()
  60. return
  61. }
  62. dispatcher.Dispatch(destination, payload, link)
  63. }