1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 02:26:49 -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"
2016-08-20 14:55:45 -04:00
"v2ray.com/core/common/log"
2015-10-31 16:43:26 -04:00
)
2016-02-05 18:13:13 -05:00
func parseIntPort(data []byte) (Port, error) {
2016-08-26 18:04:35 -04:00
var intPort uint32
2016-02-05 18:13:13 -05:00
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 {
2016-06-27 02:53:35 -04:00
return Port(0), Port(0), ErrInvalidPortRange
2016-02-05 18:13:13 -05:00
}
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-08-26 18:04:35 -04:00
this.From = uint32(port)
this.To = uint32(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-08-26 18:04:35 -04:00
this.From = uint32(from)
this.To = uint32(to)
2016-02-05 18:13:13 -05:00
if this.From > this.To {
log.Error("Invalid port range ", this.From, " -> ", this.To)
2016-06-27 02:53:35 -04:00
return ErrInvalidPortRange
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-06-27 02:53:35 -04:00
return ErrInvalidPortRange
2015-10-31 16:43:26 -04:00
}