policy.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package conf
  2. import (
  3. "github.com/xtls/xray-core/app/policy"
  4. )
  5. type Policy struct {
  6. Handshake *uint32 `json:"handshake"`
  7. ConnectionIdle *uint32 `json:"connIdle"`
  8. UplinkOnly *uint32 `json:"uplinkOnly"`
  9. DownlinkOnly *uint32 `json:"downlinkOnly"`
  10. StatsUserUplink bool `json:"statsUserUplink"`
  11. StatsUserDownlink bool `json:"statsUserDownlink"`
  12. StatsUserOnline bool `json:"statsUserOnline"`
  13. BufferSize *int32 `json:"bufferSize"`
  14. }
  15. func (t *Policy) Build() (*policy.Policy, error) {
  16. config := new(policy.Policy_Timeout)
  17. if t.Handshake != nil {
  18. config.Handshake = &policy.Second{Value: *t.Handshake}
  19. }
  20. if t.ConnectionIdle != nil {
  21. config.ConnectionIdle = &policy.Second{Value: *t.ConnectionIdle}
  22. }
  23. if t.UplinkOnly != nil {
  24. config.UplinkOnly = &policy.Second{Value: *t.UplinkOnly}
  25. }
  26. if t.DownlinkOnly != nil {
  27. config.DownlinkOnly = &policy.Second{Value: *t.DownlinkOnly}
  28. }
  29. p := &policy.Policy{
  30. Timeout: config,
  31. Stats: &policy.Policy_Stats{
  32. UserUplink: t.StatsUserUplink,
  33. UserDownlink: t.StatsUserDownlink,
  34. UserOnline: t.StatsUserOnline,
  35. },
  36. }
  37. if t.BufferSize != nil {
  38. bs := int32(-1)
  39. if *t.BufferSize >= 0 {
  40. bs = (*t.BufferSize) * 1024
  41. }
  42. p.Buffer = &policy.Policy_Buffer{
  43. Connection: bs,
  44. }
  45. }
  46. return p, nil
  47. }
  48. type SystemPolicy struct {
  49. StatsInboundUplink bool `json:"statsInboundUplink"`
  50. StatsInboundDownlink bool `json:"statsInboundDownlink"`
  51. StatsOutboundUplink bool `json:"statsOutboundUplink"`
  52. StatsOutboundDownlink bool `json:"statsOutboundDownlink"`
  53. }
  54. func (p *SystemPolicy) Build() (*policy.SystemPolicy, error) {
  55. return &policy.SystemPolicy{
  56. Stats: &policy.SystemPolicy_Stats{
  57. InboundUplink: p.StatsInboundUplink,
  58. InboundDownlink: p.StatsInboundDownlink,
  59. OutboundUplink: p.StatsOutboundUplink,
  60. OutboundDownlink: p.StatsOutboundDownlink,
  61. },
  62. }, nil
  63. }
  64. type PolicyConfig struct {
  65. Levels map[uint32]*Policy `json:"levels"`
  66. System *SystemPolicy `json:"system"`
  67. }
  68. func (c *PolicyConfig) Build() (*policy.Config, error) {
  69. levels := make(map[uint32]*policy.Policy)
  70. for l, p := range c.Levels {
  71. if p != nil {
  72. pp, err := p.Build()
  73. if err != nil {
  74. return nil, err
  75. }
  76. levels[l] = pp
  77. }
  78. }
  79. config := &policy.Config{
  80. Level: levels,
  81. }
  82. if c.System != nil {
  83. sc, err := c.System.Build()
  84. if err != nil {
  85. return nil, err
  86. }
  87. config.System = sc
  88. }
  89. return config, nil
  90. }