manager.go 1.4 KB

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