manager.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package policy
  2. import (
  3. "context"
  4. "v2ray.com/core"
  5. "v2ray.com/core/common"
  6. "v2ray.com/core/features/policy"
  7. )
  8. // Instance is an instance of Policy manager.
  9. type Instance struct {
  10. levels map[uint32]*Policy
  11. system *SystemPolicy
  12. }
  13. // New creates new Policy manager instance.
  14. func New(ctx context.Context, config *Config) (*Instance, error) {
  15. m := &Instance{
  16. levels: make(map[uint32]*Policy),
  17. system: config.System,
  18. }
  19. if len(config.Level) > 0 {
  20. for lv, p := range config.Level {
  21. pp := defaultPolicy()
  22. pp.overrideWith(p)
  23. m.levels[lv] = pp
  24. }
  25. }
  26. v := core.FromContext(ctx)
  27. if v != nil {
  28. if err := v.RegisterFeature((*policy.Manager)(nil), m); err != nil {
  29. return nil, newError("unable to register PolicyManager in core").Base(err).AtError()
  30. }
  31. }
  32. return m, nil
  33. }
  34. // ForLevel implements policy.Manager.
  35. func (m *Instance) ForLevel(level uint32) policy.Session {
  36. if p, ok := m.levels[level]; ok {
  37. return p.ToCorePolicy()
  38. }
  39. return policy.SessionDefault()
  40. }
  41. // ForSystem implements policy.Manager.
  42. func (m *Instance) ForSystem() policy.System {
  43. if m.system == nil {
  44. return policy.System{}
  45. }
  46. return m.system.ToCorePolicy()
  47. }
  48. // Start implements common.Runnable.Start().
  49. func (m *Instance) Start() error {
  50. return nil
  51. }
  52. // Close implements common.Closable.Close().
  53. func (m *Instance) Close() error {
  54. return nil
  55. }
  56. func init() {
  57. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  58. return New(ctx, config.(*Config))
  59. }))
  60. }