1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-19 02:16:11 -04:00
v2fly/common/net/port_json.go

70 lines
1.5 KiB
Go
Raw Normal View History

2016-01-15 07:39:36 -05:00
// +build json
package net
2015-10-31 16:43:26 -04:00
import (
"encoding/json"
"errors"
"strconv"
"strings"
"github.com/v2ray/v2ray-core/common/log"
2016-01-18 06:58:04 -05:00
"github.com/v2ray/v2ray-core/common/serial"
2015-10-31 16:43:26 -04:00
)
var (
2016-01-30 06:23:56 -05:00
ErrorInvalidPortRange = errors.New("Invalid port range.")
2015-10-31 16:43:26 -04:00
)
func (this *PortRange) UnmarshalJSON(data []byte) error {
var maybeint int
err := json.Unmarshal(data, &maybeint)
if err == nil {
if maybeint <= 0 || maybeint >= 65535 {
2016-01-18 06:58:04 -05:00
log.Error("Invalid port [", serial.BytesLiteral(data), "]")
2016-01-30 06:23:56 -05:00
return ErrorInvalidPortRange
2015-10-31 16:43:26 -04:00
}
2016-01-15 07:39:36 -05:00
this.From = Port(maybeint)
this.To = Port(maybeint)
2015-10-31 16:43:26 -04:00
return nil
}
var maybestring string
err = json.Unmarshal(data, &maybestring)
if err == nil {
pair := strings.SplitN(maybestring, "-", 2)
if len(pair) == 1 {
value, err := strconv.Atoi(pair[0])
if err != nil || value <= 0 || value >= 65535 {
2016-01-18 06:24:33 -05:00
log.Error("Invalid from port ", pair[0])
2016-01-30 06:23:56 -05:00
return ErrorInvalidPortRange
2015-10-31 16:43:26 -04:00
}
2016-01-15 07:39:36 -05:00
this.From = Port(value)
this.To = Port(value)
2015-10-31 16:43:26 -04:00
return nil
} else if len(pair) == 2 {
from, err := strconv.Atoi(pair[0])
if err != nil || from <= 0 || from >= 65535 {
2016-01-18 06:24:33 -05:00
log.Error("Invalid from port ", pair[0])
2016-01-30 06:23:56 -05:00
return ErrorInvalidPortRange
2015-10-31 16:43:26 -04:00
}
2016-01-15 07:39:36 -05:00
this.From = Port(from)
2015-10-31 16:43:26 -04:00
to, err := strconv.Atoi(pair[1])
if err != nil || to <= 0 || to >= 65535 {
2016-01-18 06:24:33 -05:00
log.Error("Invalid to port ", pair[1])
2016-01-30 06:23:56 -05:00
return ErrorInvalidPortRange
2015-10-31 16:43:26 -04:00
}
2016-01-15 07:39:36 -05:00
this.To = Port(to)
2015-10-31 16:43:26 -04:00
2016-01-15 07:39:36 -05:00
if this.From > this.To {
2016-01-18 06:24:33 -05:00
log.Error("Invalid port range ", this.From, " -> ", this.To)
2016-01-30 06:23:56 -05:00
return ErrorInvalidPortRange
2015-10-31 16:43:26 -04:00
}
return nil
}
}
2016-01-30 06:23:56 -05:00
return ErrorInvalidPortRange
2015-10-31 16:43:26 -04:00
}