default.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package impl
  2. import (
  3. "context"
  4. "v2ray.com/core/app"
  5. "v2ray.com/core/app/dispatcher"
  6. "v2ray.com/core/app/log"
  7. "v2ray.com/core/app/proxyman"
  8. "v2ray.com/core/app/router"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/errors"
  11. "v2ray.com/core/common/net"
  12. "v2ray.com/core/proxy"
  13. "v2ray.com/core/transport/ray"
  14. )
  15. type DefaultDispatcher struct {
  16. ohm proxyman.OutboundHandlerManager
  17. router *router.Router
  18. }
  19. func NewDefaultDispatcher(ctx context.Context, config *dispatcher.Config) (*DefaultDispatcher, error) {
  20. space := app.SpaceFromContext(ctx)
  21. if space == nil {
  22. return nil, errors.New("DefaultDispatcher: No space in context.")
  23. }
  24. d := &DefaultDispatcher{}
  25. space.OnInitialize(func() error {
  26. d.ohm = proxyman.OutboundHandlerManagerFromSpace(space)
  27. if d.ohm == nil {
  28. return errors.New("DefaultDispatcher: OutboundHandlerManager is not found in the space.")
  29. }
  30. d.router = router.FromSpace(space)
  31. return nil
  32. })
  33. return d, nil
  34. }
  35. func (DefaultDispatcher) Start() error {
  36. return nil
  37. }
  38. func (DefaultDispatcher) Close() {}
  39. func (DefaultDispatcher) Interface() interface{} {
  40. return (*dispatcher.Interface)(nil)
  41. }
  42. func (v *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (ray.InboundRay, error) {
  43. dispatcher := v.ohm.GetDefaultHandler()
  44. if !destination.IsValid() {
  45. panic("Dispatcher: Invalid destination.")
  46. }
  47. ctx = proxy.ContextWithTarget(ctx, destination)
  48. if v.router != nil {
  49. if tag, err := v.router.TakeDetour(ctx); err == nil {
  50. if handler := v.ohm.GetHandler(tag); handler != nil {
  51. log.Trace(errors.New("taking detour [", tag, "] for [", destination, "]").Path("App", "Dispatcher", "Default"))
  52. dispatcher = handler
  53. } else {
  54. log.Trace(errors.New("nonexisting tag: ", tag).AtWarning().Path("App", "Dispatcher", "Default"))
  55. }
  56. } else {
  57. log.Trace(errors.New("default route for ", destination).Path("App", "Dispatcher", "Default"))
  58. }
  59. }
  60. direct := ray.NewRay(ctx)
  61. go dispatcher.Dispatch(ctx, direct)
  62. return direct, nil
  63. }
  64. func init() {
  65. common.Must(common.RegisterConfig((*dispatcher.Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  66. return NewDefaultDispatcher(ctx, config.(*dispatcher.Config))
  67. }))
  68. }