port_json.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. )
  10. var (
  11. InvalidPortRange = errors.New("Invalid port range.")
  12. )
  13. func (this *PortRange) UnmarshalJSON(data []byte) error {
  14. var maybeint int
  15. err := json.Unmarshal(data, &maybeint)
  16. if err == nil {
  17. if maybeint <= 0 || maybeint >= 65535 {
  18. log.Error("Invalid port [", string(data), "]")
  19. return InvalidPortRange
  20. }
  21. this.From = Port(maybeint)
  22. this.To = Port(maybeint)
  23. return nil
  24. }
  25. var maybestring string
  26. err = json.Unmarshal(data, &maybestring)
  27. if err == nil {
  28. pair := strings.SplitN(maybestring, "-", 2)
  29. if len(pair) == 1 {
  30. value, err := strconv.Atoi(pair[0])
  31. if err != nil || value <= 0 || value >= 65535 {
  32. log.Error("Invalid from port ", pair[0])
  33. return InvalidPortRange
  34. }
  35. this.From = Port(value)
  36. this.To = Port(value)
  37. return nil
  38. } else if len(pair) == 2 {
  39. from, err := strconv.Atoi(pair[0])
  40. if err != nil || from <= 0 || from >= 65535 {
  41. log.Error("Invalid from port ", pair[0])
  42. return InvalidPortRange
  43. }
  44. this.From = Port(from)
  45. to, err := strconv.Atoi(pair[1])
  46. if err != nil || to <= 0 || to >= 65535 {
  47. log.Error("Invalid to port ", pair[1])
  48. return InvalidPortRange
  49. }
  50. this.To = Port(to)
  51. if this.From > this.To {
  52. log.Error("Invalid port range ", this.From, " -> ", this.To)
  53. return InvalidPortRange
  54. }
  55. return nil
  56. }
  57. }
  58. return InvalidPortRange
  59. }