policy.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package core
  2. import (
  3. "sync"
  4. "time"
  5. "v2ray.com/core/common"
  6. )
  7. // TimeoutPolicy contains limits for connection timeout.
  8. type TimeoutPolicy struct {
  9. // Timeout for handshake phase in a connection.
  10. Handshake time.Duration
  11. // Timeout for connection being idle, i.e., there is no egress or ingress traffic in this connection.
  12. ConnectionIdle time.Duration
  13. // Timeout for an uplink only connection, i.e., the downlink of the connection has been closed.
  14. UplinkOnly time.Duration
  15. // Timeout for an downlink only connection, i.e., the uplink of the connection has been closed.
  16. DownlinkOnly time.Duration
  17. }
  18. type StatsPolicy struct {
  19. UserUplink bool
  20. UserDownlink bool
  21. }
  22. // Policy is session based settings for controlling V2Ray requests. It contains various settings (or limits) that may differ for different users in the context.
  23. type Policy struct {
  24. Timeouts TimeoutPolicy // Timeout settings
  25. Stats StatsPolicy
  26. }
  27. // PolicyManager is a feature that provides Policy for the given user by its id or level.
  28. type PolicyManager interface {
  29. Feature
  30. // ForLevel returns the Policy for the given user level.
  31. ForLevel(level uint32) Policy
  32. }
  33. // DefaultPolicy returns the Policy when user is not specified.
  34. func DefaultPolicy() Policy {
  35. return Policy{
  36. Timeouts: TimeoutPolicy{
  37. Handshake: time.Second * 4,
  38. ConnectionIdle: time.Second * 300,
  39. UplinkOnly: time.Second * 5,
  40. DownlinkOnly: time.Second * 30,
  41. },
  42. Stats: StatsPolicy{
  43. UserUplink: false,
  44. UserDownlink: false,
  45. },
  46. }
  47. }
  48. type syncPolicyManager struct {
  49. sync.RWMutex
  50. PolicyManager
  51. }
  52. func (m *syncPolicyManager) ForLevel(level uint32) Policy {
  53. m.RLock()
  54. defer m.RUnlock()
  55. if m.PolicyManager == nil {
  56. p := DefaultPolicy()
  57. if level == 1 {
  58. p.Timeouts.ConnectionIdle = time.Second * 600
  59. }
  60. return p
  61. }
  62. return m.PolicyManager.ForLevel(level)
  63. }
  64. func (m *syncPolicyManager) Start() error {
  65. m.RLock()
  66. defer m.RUnlock()
  67. if m.PolicyManager == nil {
  68. return nil
  69. }
  70. return m.PolicyManager.Start()
  71. }
  72. func (m *syncPolicyManager) Close() error {
  73. m.RLock()
  74. defer m.RUnlock()
  75. return common.Close(m.PolicyManager)
  76. }
  77. func (m *syncPolicyManager) Set(manager PolicyManager) {
  78. if manager == nil {
  79. return
  80. }
  81. m.Lock()
  82. defer m.Unlock()
  83. common.Close(m.PolicyManager)
  84. m.PolicyManager = manager
  85. }