1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-19 10:26:10 -04:00
v2fly/common/net/json/portrange.go

81 lines
1.7 KiB
Go
Raw Normal View History

2015-10-31 16:43:26 -04:00
package json
import (
"encoding/json"
"errors"
"strconv"
"strings"
"github.com/v2ray/v2ray-core/common/log"
2015-12-02 06:47:54 -05:00
v2net "github.com/v2ray/v2ray-core/common/net"
2015-10-31 16:43:26 -04:00
)
var (
InvalidPortRange = errors.New("Invalid port range.")
)
type PortRange struct {
2015-12-02 06:47:54 -05:00
from v2net.Port
to v2net.Port
2015-10-31 16:43:26 -04:00
}
2015-12-02 06:47:54 -05:00
func (this *PortRange) From() v2net.Port {
2015-10-31 16:43:26 -04:00
return this.from
}
2015-12-02 06:47:54 -05:00
func (this *PortRange) To() v2net.Port {
2015-10-31 16:43:26 -04:00
return this.to
}
func (this *PortRange) UnmarshalJSON(data []byte) error {
var maybeint int
err := json.Unmarshal(data, &maybeint)
if err == nil {
if maybeint <= 0 || maybeint >= 65535 {
log.Error("Invalid port [%s]", string(data))
return InvalidPortRange
}
2015-12-06 14:38:01 -05:00
this.from = v2net.Port(maybeint)
this.to = v2net.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 {
log.Error("Invalid from port %s", pair[0])
return InvalidPortRange
}
2015-12-06 14:38:01 -05:00
this.from = v2net.Port(value)
this.to = v2net.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 {
log.Error("Invalid from port %s", pair[0])
return InvalidPortRange
}
2015-12-06 14:38:01 -05:00
this.from = v2net.Port(from)
2015-10-31 16:43:26 -04:00
to, err := strconv.Atoi(pair[1])
if err != nil || to <= 0 || to >= 65535 {
log.Error("Invalid to port %s", pair[1])
return InvalidPortRange
}
2015-12-06 14:38:01 -05:00
this.to = v2net.Port(to)
2015-10-31 16:43:26 -04:00
if this.from > this.to {
log.Error("Invalid port range %d -> %d", this.from, this.to)
return InvalidPortRange
}
return nil
}
}
return InvalidPortRange
}