portrange.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package json
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "strconv"
  6. "strings"
  7. "github.com/v2ray/v2ray-core/common/log"
  8. v2net "github.com/v2ray/v2ray-core/common/net"
  9. )
  10. var (
  11. InvalidPortRange = errors.New("Invalid port range.")
  12. )
  13. type PortRange struct {
  14. from v2net.Port
  15. to v2net.Port
  16. }
  17. func (this *PortRange) From() v2net.Port {
  18. return this.from
  19. }
  20. func (this *PortRange) To() v2net.Port {
  21. return this.to
  22. }
  23. func (this *PortRange) UnmarshalJSON(data []byte) error {
  24. var maybeint int
  25. err := json.Unmarshal(data, &maybeint)
  26. if err == nil {
  27. if maybeint <= 0 || maybeint >= 65535 {
  28. log.Error("Invalid port [%s]", string(data))
  29. return InvalidPortRange
  30. }
  31. this.from = v2net.Port(maybeint)
  32. this.to = v2net.Port(maybeint)
  33. return nil
  34. }
  35. var maybestring string
  36. err = json.Unmarshal(data, &maybestring)
  37. if err == nil {
  38. pair := strings.SplitN(maybestring, "-", 2)
  39. if len(pair) == 1 {
  40. value, err := strconv.Atoi(pair[0])
  41. if err != nil || value <= 0 || value >= 65535 {
  42. log.Error("Invalid from port %s", pair[0])
  43. return InvalidPortRange
  44. }
  45. this.from = v2net.Port(value)
  46. this.to = v2net.Port(value)
  47. return nil
  48. } else if len(pair) == 2 {
  49. from, err := strconv.Atoi(pair[0])
  50. if err != nil || from <= 0 || from >= 65535 {
  51. log.Error("Invalid from port %s", pair[0])
  52. return InvalidPortRange
  53. }
  54. this.from = v2net.Port(from)
  55. to, err := strconv.Atoi(pair[1])
  56. if err != nil || to <= 0 || to >= 65535 {
  57. log.Error("Invalid to port %s", pair[1])
  58. return InvalidPortRange
  59. }
  60. this.to = v2net.Port(to)
  61. if this.from > this.to {
  62. log.Error("Invalid port range %d -> %d", this.from, this.to)
  63. return InvalidPortRange
  64. }
  65. return nil
  66. }
  67. }
  68. return InvalidPortRange
  69. }