policy.go 2.3 KB

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