port_json.go 1.5 KB

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