1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00
v2fly/common/net/port_json.go

70 lines
1.4 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"
"strings"
"github.com/v2ray/v2ray-core/common/log"
)
2016-02-05 18:13:13 -05:00
func parseIntPort(data []byte) (Port, error) {
var intPort int
err := json.Unmarshal(data, &intPort)
if err != nil {
return Port(0), err
}
return PortFromInt(intPort)
}
2015-10-31 16:43:26 -04:00
2016-02-05 18:13:13 -05:00
func parseStringPort(data []byte) (Port, Port, error) {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return Port(0), Port(0), err
}
pair := strings.SplitN(s, "-", 2)
if len(pair) == 0 {
return Port(0), Port(0), ErrorInvalidPortRange
}
if len(pair) == 1 {
port, err := PortFromString(pair[0])
return port, port, err
}
fromPort, err := PortFromString(pair[0])
if err != nil {
return Port(0), Port(0), err
}
toPort, err := PortFromString(pair[1])
if err != nil {
return Port(0), Port(0), err
}
return fromPort, toPort, nil
}
// UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
2015-10-31 16:43:26 -04:00
func (this *PortRange) UnmarshalJSON(data []byte) error {
2016-02-05 18:13:13 -05:00
port, err := parseIntPort(data)
2015-10-31 16:43:26 -04:00
if err == nil {
2016-02-05 18:13:13 -05:00
this.From = port
this.To = port
2015-10-31 16:43:26 -04:00
return nil
}
2016-02-05 18:13:13 -05:00
from, to, err := parseStringPort(data)
2015-10-31 16:43:26 -04:00
if err == nil {
2016-02-05 18:13:13 -05:00
this.From = from
this.To = to
if this.From > this.To {
log.Error("Invalid port range ", this.From, " -> ", this.To)
return ErrorInvalidPortRange
2015-10-31 16:43:26 -04:00
}
2016-02-05 18:13:13 -05:00
return nil
2015-10-31 16:43:26 -04:00
}
2016-02-05 18:13:13 -05:00
log.Error("Invalid port range: ", string(data))
2016-01-30 06:23:56 -05:00
return ErrorInvalidPortRange
2015-10-31 16:43:26 -04:00
}