policy.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // Policy is session based settings for controlling V2Ray requests. It contains various settings (or limits) that may differ for different users in the context.
  19. type Policy struct {
  20. Timeouts TimeoutPolicy // Timeout settings
  21. }
  22. // PolicyManager is a feature that provides Policy for the given user by its id or level.
  23. type PolicyManager interface {
  24. Feature
  25. // ForLevel returns the Policy for the given user level.
  26. ForLevel(level uint32) Policy
  27. }
  28. // DefaultPolicy returns the Policy when user is not specified.
  29. func DefaultPolicy() Policy {
  30. return Policy{
  31. Timeouts: TimeoutPolicy{
  32. Handshake: time.Second * 4,
  33. ConnectionIdle: time.Second * 300,
  34. UplinkOnly: time.Second * 5,
  35. DownlinkOnly: time.Second * 30,
  36. },
  37. }
  38. }
  39. type syncPolicyManager struct {
  40. sync.RWMutex
  41. PolicyManager
  42. }
  43. func (m *syncPolicyManager) ForLevel(level uint32) Policy {
  44. m.RLock()
  45. defer m.RUnlock()
  46. if m.PolicyManager == nil {
  47. p := DefaultPolicy()
  48. if level == 1 {
  49. p.Timeouts.ConnectionIdle = time.Second * 600
  50. }
  51. return p
  52. }
  53. return m.PolicyManager.ForLevel(level)
  54. }
  55. func (m *syncPolicyManager) Start() error {
  56. m.RLock()
  57. defer m.RUnlock()
  58. if m.PolicyManager == nil {
  59. return nil
  60. }
  61. return m.PolicyManager.Start()
  62. }
  63. func (m *syncPolicyManager) Close() error {
  64. m.RLock()
  65. defer m.RUnlock()
  66. return common.Close(m.PolicyManager)
  67. }
  68. func (m *syncPolicyManager) Set(manager PolicyManager) {
  69. if manager == nil {
  70. return
  71. }
  72. m.Lock()
  73. defer m.Unlock()
  74. common.Close(m.PolicyManager)
  75. m.PolicyManager = manager
  76. }