portrange.go 1.6 KB

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