Remove serial.String

pull/168/head
v2ray 2016-05-24 22:41:51 +02:00
parent 444808a51a
commit c75d840706
17 changed files with 89 additions and 164 deletions

View File

@ -8,9 +8,9 @@ import (
"strings" "strings"
router "github.com/v2ray/v2ray-core/app/router" router "github.com/v2ray/v2ray-core/app/router"
"github.com/v2ray/v2ray-core/common/collect"
"github.com/v2ray/v2ray-core/common/log" "github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net" v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/serial"
) )
type JsonRule struct { type JsonRule struct {
@ -21,8 +21,8 @@ type JsonRule struct {
func parseFieldRule(msg json.RawMessage) (*Rule, error) { func parseFieldRule(msg json.RawMessage) (*Rule, error) {
type RawFieldRule struct { type RawFieldRule struct {
JsonRule JsonRule
Domain *serial.StringTList `json:"domain"` Domain *collect.StringList `json:"domain"`
IP *serial.StringTList `json:"ip"` IP *collect.StringList `json:"ip"`
Port *v2net.PortRange `json:"port"` Port *v2net.PortRange `json:"port"`
Network *v2net.NetworkList `json:"network"` Network *v2net.NetworkList `json:"network"`
} }
@ -37,14 +37,14 @@ func parseFieldRule(msg json.RawMessage) (*Rule, error) {
anyCond := NewAnyCondition() anyCond := NewAnyCondition()
for _, rawDomain := range *(rawFieldRule.Domain) { for _, rawDomain := range *(rawFieldRule.Domain) {
var matcher Condition var matcher Condition
if strings.HasPrefix(rawDomain.String(), "regexp:") { if strings.HasPrefix(rawDomain, "regexp:") {
rawMatcher, err := NewRegexpDomainMatcher(rawDomain.String()[7:]) rawMatcher, err := NewRegexpDomainMatcher(rawDomain[7:])
if err != nil { if err != nil {
return nil, err return nil, err
} }
matcher = rawMatcher matcher = rawMatcher
} else { } else {
matcher = NewPlainDomainMatcher(rawDomain.String()) matcher = NewPlainDomainMatcher(rawDomain)
} }
anyCond.Add(matcher) anyCond.Add(matcher)
} }
@ -54,7 +54,7 @@ func parseFieldRule(msg json.RawMessage) (*Rule, error) {
if rawFieldRule.IP != nil && rawFieldRule.IP.Len() > 0 { if rawFieldRule.IP != nil && rawFieldRule.IP.Len() > 0 {
anyCond := NewAnyCondition() anyCond := NewAnyCondition()
for _, ipStr := range *(rawFieldRule.IP) { for _, ipStr := range *(rawFieldRule.IP) {
cidrMatcher, err := NewCIDRMatcher(ipStr.String()) cidrMatcher, err := NewCIDRMatcher(ipStr)
if err != nil { if err != nil {
log.Error("Router: Invalid IP range in router rule: ", err) log.Error("Router: Invalid IP range in router rule: ", err)
return nil, err return nil, err
@ -128,10 +128,10 @@ func init() {
Rules: make([]*Rule, len(jsonConfig.RuleList)), Rules: make([]*Rule, len(jsonConfig.RuleList)),
DomainStrategy: DomainAsIs, DomainStrategy: DomainAsIs,
} }
domainStrategy := serial.StringT(jsonConfig.DomainStrategy).ToLower() domainStrategy := strings.ToLower(jsonConfig.DomainStrategy)
if domainStrategy.String() == "alwaysip" { if domainStrategy == "alwaysip" {
config.DomainStrategy = AlwaysUseIP config.DomainStrategy = AlwaysUseIP
} else if domainStrategy.String() == "ipifnonmatch" { } else if domainStrategy == "ipifnonmatch" {
config.DomainStrategy = UseIPIfNonMatch config.DomainStrategy = UseIPIfNonMatch
} }
for idx, rawRule := range jsonConfig.RuleList { for idx, rawRule := range jsonConfig.RuleList {

View File

@ -0,0 +1,12 @@
package collect
type StringList []string
func NewStringList(raw []string) *StringList {
list := StringList(raw)
return &list
}
func (this *StringList) Len() int {
return len(*this)
}

View File

@ -1,6 +1,6 @@
// +build json // +build json
package serial package collect
import ( import (
"encoding/json" "encoding/json"
@ -8,17 +8,17 @@ import (
"strings" "strings"
) )
func (this *StringTList) UnmarshalJSON(data []byte) error { func (this *StringList) UnmarshalJSON(data []byte) error {
var strarray []string var strarray []string
if err := json.Unmarshal(data, &strarray); err == nil { if err := json.Unmarshal(data, &strarray); err == nil {
*this = *NewStringTList(strarray) *this = *NewStringList(strarray)
return nil return nil
} }
var rawstr string var rawstr string
if err := json.Unmarshal(data, &rawstr); err == nil { if err := json.Unmarshal(data, &rawstr); err == nil {
strlist := strings.Split(rawstr, ",") strlist := strings.Split(rawstr, ",")
*this = *NewStringTList(strlist) *this = *NewStringList(strlist)
return nil return nil
} }
return errors.New("Unknown format of a string list: " + string(data)) return errors.New("Unknown format of a string list: " + string(data))

View File

@ -1,12 +1,12 @@
// +build json // +build json
package serial_test package collect_test
import ( import (
"encoding/json" "encoding/json"
"testing" "testing"
. "github.com/v2ray/v2ray-core/common/serial" . "github.com/v2ray/v2ray-core/common/collect"
"github.com/v2ray/v2ray-core/testing/assert" "github.com/v2ray/v2ray-core/testing/assert"
) )
@ -14,7 +14,7 @@ func TestStringListUnmarshalError(t *testing.T) {
assert := assert.On(t) assert := assert.On(t)
rawJson := `1234` rawJson := `1234`
list := new(StringTList) list := new(StringList)
err := json.Unmarshal([]byte(rawJson), list) err := json.Unmarshal([]byte(rawJson), list)
assert.Error(err).IsNotNil() assert.Error(err).IsNotNil()
} }

View File

@ -1,8 +1,6 @@
package log package log
import ( import (
"fmt"
"github.com/v2ray/v2ray-core/common/log/internal" "github.com/v2ray/v2ray-core/common/log/internal"
) )
@ -30,7 +28,7 @@ func InitAccessLogger(file string) error {
} }
// Access writes an access log. // Access writes an access log.
func Access(from, to fmt.Stringer, status AccessStatus, reason fmt.Stringer) { func Access(from, to interface{}, status AccessStatus, reason interface{}) {
accessLoggerInstance.Log(&internal.AccessLog{ accessLoggerInstance.Log(&internal.AccessLog{
From: from, From: from,
To: to, To: to,

View File

@ -8,6 +8,26 @@ import (
"github.com/v2ray/v2ray-core/common/serial" "github.com/v2ray/v2ray-core/common/serial"
) )
func InterfaceToString(value interface{}) string {
if value == nil {
return " "
}
switch value := value.(type) {
case string:
return value
case *string:
return *value
case fmt.Stringer:
return value.String()
case error:
return value.Error()
case []byte:
return serial.BytesToHexString(value)
default:
return fmt.Sprint(value)
}
}
type LogEntry interface { type LogEntry interface {
common.Releasable common.Releasable
fmt.Stringer fmt.Stringer
@ -32,29 +52,16 @@ func (this *ErrorLog) String() string {
b.AppendString(this.Prefix) b.AppendString(this.Prefix)
for _, value := range this.Values { for _, value := range this.Values {
switch typedVal := value.(type) { b.AppendString(InterfaceToString(value))
case string:
b.AppendString(typedVal)
case *string:
b.AppendString(*typedVal)
case fmt.Stringer:
b.AppendString(typedVal.String())
case error:
b.AppendString(typedVal.Error())
case []byte:
b.AppendString(serial.BytesToHexString(typedVal))
default:
b.AppendString(fmt.Sprint(value))
}
} }
return b.String() return b.String()
} }
type AccessLog struct { type AccessLog struct {
From fmt.Stringer From interface{}
To fmt.Stringer To interface{}
Status string Status string
Reason fmt.Stringer Reason interface{}
} }
func (this *AccessLog) Release() { func (this *AccessLog) Release() {
@ -67,5 +74,9 @@ func (this *AccessLog) String() string {
b := alloc.NewSmallBuffer().Clear() b := alloc.NewSmallBuffer().Clear()
defer b.Release() defer b.Release()
return b.AppendString(this.From.String()).AppendString(" ").AppendString(this.Status).AppendString(" ").AppendString(this.To.String()).AppendString(" ").AppendString(this.Reason.String()).String() b.AppendString(InterfaceToString(this.From)).AppendString(" ")
b.AppendString(this.Status).AppendString(" ")
b.AppendString(InterfaceToString(this.To)).AppendString(" ")
b.AppendString(InterfaceToString(this.Reason))
return b.String()
} }

View File

@ -4,7 +4,6 @@ import (
"testing" "testing"
. "github.com/v2ray/v2ray-core/common/log/internal" . "github.com/v2ray/v2ray-core/common/log/internal"
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/testing/assert" "github.com/v2ray/v2ray-core/testing/assert"
) )
@ -12,10 +11,10 @@ func TestAccessLog(t *testing.T) {
assert := assert.On(t) assert := assert.On(t)
entry := &AccessLog{ entry := &AccessLog{
From: serial.StringT("test_from"), From: "test_from",
To: serial.StringT("test_to"), To: "test_to",
Status: "Accepted", Status: "Accepted",
Reason: serial.StringT("test_reason"), Reason: "test_reason",
} }
entryStr := entry.String() entryStr := entry.String()

View File

@ -1,7 +1,9 @@
package net package net
import ( import (
"github.com/v2ray/v2ray-core/common/serial" "strings"
"github.com/v2ray/v2ray-core/common/collect"
) )
const ( const (
@ -13,7 +15,7 @@ const (
) )
// Network represents a communication network on internet. // Network represents a communication network on internet.
type Network serial.StringT type Network string
func (this Network) AsList() *NetworkList { func (this Network) AsList() *NetworkList {
list := NetworkList([]Network{this}) list := NetworkList([]Network{this})
@ -24,10 +26,10 @@ func (this Network) AsList() *NetworkList {
type NetworkList []Network type NetworkList []Network
// NewNetworkList construsts a NetWorklist from the given StringListeralList. // NewNetworkList construsts a NetWorklist from the given StringListeralList.
func NewNetworkList(networks serial.StringTList) NetworkList { func NewNetworkList(networks collect.StringList) NetworkList {
list := NetworkList(make([]Network, networks.Len())) list := NetworkList(make([]Network, networks.Len()))
for idx, network := range networks { for idx, network := range networks {
list[idx] = Network(network.TrimSpace().ToLower()) list[idx] = Network(strings.ToLower(strings.TrimSpace(network)))
} }
return list return list
} }

View File

@ -5,11 +5,11 @@ package net
import ( import (
"encoding/json" "encoding/json"
"github.com/v2ray/v2ray-core/common/serial" "github.com/v2ray/v2ray-core/common/collect"
) )
func (this *NetworkList) UnmarshalJSON(data []byte) error { func (this *NetworkList) UnmarshalJSON(data []byte) error {
var strlist serial.StringTList var strlist collect.StringList
if err := json.Unmarshal(data, &strlist); err != nil { if err := json.Unmarshal(data, &strlist); err != nil {
return err return err
} }

View File

@ -1,36 +0,0 @@
package serial
import (
"strings"
)
// An interface for any objects that has string presentation.
type String interface {
String() string
}
type StringT string
func NewStringT(str String) StringT {
return StringT(str.String())
}
func (this StringT) Contains(str String) bool {
return strings.Contains(this.String(), str.String())
}
func (this StringT) String() string {
return string(this)
}
func (this StringT) ToLower() StringT {
return StringT(strings.ToLower(string(this)))
}
func (this StringT) ToUpper() StringT {
return StringT(strings.ToUpper(string(this)))
}
func (this StringT) TrimSpace() StringT {
return StringT(strings.TrimSpace(string(this)))
}

View File

@ -1,16 +0,0 @@
// +build json
package serial
import (
"encoding/json"
)
func (this *StringT) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
*this = StringT(str)
return nil
}

View File

@ -1,28 +0,0 @@
// +build json
package serial_test
import (
"encoding/json"
"testing"
. "github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/testing/assert"
)
func TestInvalidStringTJson(t *testing.T) {
assert := assert.On(t)
var s StringT
err := json.Unmarshal([]byte("1"), &s)
assert.Error(err).IsNotNil()
}
func TestStringTParsing(t *testing.T) {
assert := assert.On(t)
var s StringT
err := json.Unmarshal([]byte("\"1\""), &s)
assert.Error(err).IsNil()
assert.String(s.String()).Equals("1")
}

View File

@ -1,15 +0,0 @@
package serial
type StringTList []StringT
func NewStringTList(raw []string) *StringTList {
list := StringTList(make([]StringT, len(raw)))
for idx, str := range raw {
list[idx] = StringT(str)
}
return &list
}
func (this *StringTList) Len() int {
return len(*this)
}

View File

@ -4,8 +4,8 @@ package freedom
import ( import (
"encoding/json" "encoding/json"
"strings"
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/proxy/internal/config" "github.com/v2ray/v2ray-core/proxy/internal/config"
) )
@ -18,8 +18,8 @@ func (this *Config) UnmarshalJSON(data []byte) error {
return err return err
} }
this.DomainStrategy = DomainStrategyAsIs this.DomainStrategy = DomainStrategyAsIs
domainStrategy := serial.StringT(jsonConfig.DomainStrategy).ToLower() domainStrategy := strings.ToLower(jsonConfig.DomainStrategy)
if domainStrategy.String() == "useip" { if domainStrategy == "useip" {
this.DomainStrategy = DomainStrategyUseIP this.DomainStrategy = DomainStrategyUseIP
} }
return nil return nil

View File

@ -4,21 +4,21 @@ package shadowsocks
import ( import (
"encoding/json" "encoding/json"
"strings"
"github.com/v2ray/v2ray-core/common/log" "github.com/v2ray/v2ray-core/common/log"
"github.com/v2ray/v2ray-core/common/protocol" "github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/proxy/internal" "github.com/v2ray/v2ray-core/proxy/internal"
"github.com/v2ray/v2ray-core/proxy/internal/config" "github.com/v2ray/v2ray-core/proxy/internal/config"
) )
func (this *Config) UnmarshalJSON(data []byte) error { func (this *Config) UnmarshalJSON(data []byte) error {
type JsonConfig struct { type JsonConfig struct {
Cipher serial.StringT `json:"method"` Cipher string `json:"method"`
Password serial.StringT `json:"password"` Password string `json:"password"`
UDP bool `json:"udp"` UDP bool `json:"udp"`
Level byte `json:"level"` Level byte `json:"level"`
Email string `json:"email"` Email string `json:"email"`
} }
jsonConfig := new(JsonConfig) jsonConfig := new(JsonConfig)
if err := json.Unmarshal(data, jsonConfig); err != nil { if err := json.Unmarshal(data, jsonConfig); err != nil {
@ -26,8 +26,8 @@ func (this *Config) UnmarshalJSON(data []byte) error {
} }
this.UDP = jsonConfig.UDP this.UDP = jsonConfig.UDP
jsonConfig.Cipher = jsonConfig.Cipher.ToLower() jsonConfig.Cipher = strings.ToLower(jsonConfig.Cipher)
switch jsonConfig.Cipher.String() { switch jsonConfig.Cipher {
case "aes-256-cfb": case "aes-256-cfb":
this.Cipher = &AesCfb{ this.Cipher = &AesCfb{
KeyBytes: 32, KeyBytes: 32,
@ -53,7 +53,7 @@ func (this *Config) UnmarshalJSON(data []byte) error {
log.Error("Shadowsocks: Password is not specified.") log.Error("Shadowsocks: Password is not specified.")
return internal.ErrorBadConfiguration return internal.ErrorBadConfiguration
} }
this.Key = PasswordToCipherKey(jsonConfig.Password.String(), this.Cipher.KeySize()) this.Key = PasswordToCipherKey(jsonConfig.Password, this.Cipher.KeySize())
this.Level = protocol.UserLevel(jsonConfig.Level) this.Level = protocol.UserLevel(jsonConfig.Level)
this.Email = jsonConfig.Email this.Email = jsonConfig.Email

View File

@ -14,7 +14,6 @@ import (
"github.com/v2ray/v2ray-core/common/log" "github.com/v2ray/v2ray-core/common/log"
v2net "github.com/v2ray/v2ray-core/common/net" v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/protocol" "github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/proxy" "github.com/v2ray/v2ray-core/proxy"
"github.com/v2ray/v2ray-core/proxy/internal" "github.com/v2ray/v2ray-core/proxy/internal"
"github.com/v2ray/v2ray-core/transport/hub" "github.com/v2ray/v2ray-core/transport/hub"
@ -106,14 +105,14 @@ func (this *Server) handlerUDPPayload(payload *alloc.Buffer, source v2net.Destin
request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(key, iv)), true) request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(key, iv)), true)
if err != nil { if err != nil {
log.Access(source, serial.StringT(""), log.AccessRejected, serial.StringT(err.Error())) log.Access(source, "", log.AccessRejected, err)
log.Warning("Shadowsocks: Invalid request from ", source, ": ", err) log.Warning("Shadowsocks: Invalid request from ", source, ": ", err)
return return
} }
//defer request.Release() //defer request.Release()
dest := v2net.UDPDestination(request.Address, request.Port) dest := v2net.UDPDestination(request.Address, request.Port)
log.Access(source, dest, log.AccessAccepted, serial.StringT("")) log.Access(source, dest, log.AccessAccepted, "")
log.Info("Shadowsocks: Tunnelling request to ", dest) log.Info("Shadowsocks: Tunnelling request to ", dest)
this.udpServer.Dispatch(source, dest, request.DetachUDPPayload(), func(destination v2net.Destination, payload *alloc.Buffer) { this.udpServer.Dispatch(source, dest, request.DetachUDPPayload(), func(destination v2net.Destination, payload *alloc.Buffer) {
@ -172,7 +171,7 @@ func (this *Server) handleConnection(conn *hub.Connection) {
ivLen := this.config.Cipher.IVSize() ivLen := this.config.Cipher.IVSize()
_, err := io.ReadFull(bufferedReader, buffer.Value[:ivLen]) _, err := io.ReadFull(bufferedReader, buffer.Value[:ivLen])
if err != nil { if err != nil {
log.Access(conn.RemoteAddr(), serial.StringT(""), log.AccessRejected, serial.StringT(err.Error())) log.Access(conn.RemoteAddr(), "", log.AccessRejected, err)
log.Error("Shadowsocks: Failed to read IV: ", err) log.Error("Shadowsocks: Failed to read IV: ", err)
return return
} }
@ -190,7 +189,7 @@ func (this *Server) handleConnection(conn *hub.Connection) {
request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(key, iv)), false) request, err := ReadRequest(reader, NewAuthenticator(HeaderKeyGenerator(key, iv)), false)
if err != nil { if err != nil {
log.Access(conn.RemoteAddr(), serial.StringT(""), log.AccessRejected, serial.StringT(err.Error())) log.Access(conn.RemoteAddr(), "", log.AccessRejected, err)
log.Warning("Shadowsocks: Invalid request from ", conn.RemoteAddr(), ": ", err) log.Warning("Shadowsocks: Invalid request from ", conn.RemoteAddr(), ": ", err)
return return
} }
@ -201,7 +200,7 @@ func (this *Server) handleConnection(conn *hub.Connection) {
timedReader.SetTimeOut(userSettings.PayloadReadTimeout) timedReader.SetTimeOut(userSettings.PayloadReadTimeout)
dest := v2net.TCPDestination(request.Address, request.Port) dest := v2net.TCPDestination(request.Address, request.Port)
log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, serial.StringT("")) log.Access(conn.RemoteAddr(), dest, log.AccessAccepted, "")
log.Info("Shadowsocks: Tunnelling request to ", dest) log.Info("Shadowsocks: Tunnelling request to ", dest)
ray := this.packetDispatcher.DispatchToOutbound(dest) ray := this.packetDispatcher.DispatchToOutbound(dest)

View File

@ -12,7 +12,6 @@ import (
v2net "github.com/v2ray/v2ray-core/common/net" v2net "github.com/v2ray/v2ray-core/common/net"
"github.com/v2ray/v2ray-core/common/protocol" "github.com/v2ray/v2ray-core/common/protocol"
"github.com/v2ray/v2ray-core/common/protocol/raw" "github.com/v2ray/v2ray-core/common/protocol/raw"
"github.com/v2ray/v2ray-core/common/serial"
"github.com/v2ray/v2ray-core/common/uuid" "github.com/v2ray/v2ray-core/common/uuid"
"github.com/v2ray/v2ray-core/proxy" "github.com/v2ray/v2ray-core/proxy"
"github.com/v2ray/v2ray-core/proxy/internal" "github.com/v2ray/v2ray-core/proxy/internal"
@ -130,11 +129,11 @@ func (this *VMessInboundHandler) HandleConnection(connection *hub.Connection) {
request, err := session.DecodeRequestHeader(reader) request, err := session.DecodeRequestHeader(reader)
if err != nil { if err != nil {
log.Access(connection.RemoteAddr(), serial.StringT(""), log.AccessRejected, serial.StringT(err.Error())) log.Access(connection.RemoteAddr(), "", log.AccessRejected, err)
log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err) log.Warning("VMessIn: Invalid request from ", connection.RemoteAddr(), ": ", err)
return return
} }
log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, serial.StringT("")) log.Access(connection.RemoteAddr(), request.Destination(), log.AccessAccepted, "")
log.Debug("VMessIn: Received request for ", request.Destination()) log.Debug("VMessIn: Received request for ", request.Destination())
ray := this.packetDispatcher.DispatchToOutbound(request.Destination()) ray := this.packetDispatcher.DispatchToOutbound(request.Destination())