manager.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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(m); err != nil {
  29. return nil, newError("unable to register PolicyManager in core").Base(err).AtError()
  30. }
  31. }
  32. return m, nil
  33. }
  34. // Type implements common.HasType.
  35. func (*Instance) Type() interface{} {
  36. return policy.ManagerType()
  37. }
  38. // ForLevel implements policy.Manager.
  39. func (m *Instance) ForLevel(level uint32) policy.Session {
  40. if p, ok := m.levels[level]; ok {
  41. return p.ToCorePolicy()
  42. }
  43. return policy.SessionDefault()
  44. }
  45. // ForSystem implements policy.Manager.
  46. func (m *Instance) ForSystem() policy.System {
  47. if m.system == nil {
  48. return policy.System{}
  49. }
  50. return m.system.ToCorePolicy()
  51. }
  52. // Start implements common.Runnable.Start().
  53. func (m *Instance) Start() error {
  54. return nil
  55. }
  56. // Close implements common.Closable.Close().
  57. func (m *Instance) Close() error {
  58. return nil
  59. }
  60. func init() {
  61. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  62. return New(ctx, config.(*Config))
  63. }))
  64. }