Refactor log (#3446)

* Refactor log

* Add new log methods

* Fix logger test

* Change all logging code

* Clean up pathObj

* Rebase to latest main

* Remove invoking method name after the dot
This commit is contained in:
yuhan6665 2024-06-29 14:32:57 -04:00 committed by GitHub
parent 8320732743
commit 079d0bd8a9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
291 changed files with 1837 additions and 2368 deletions

View file

@ -9,6 +9,7 @@ import (
handlerservice "github.com/xtls/xray-core/app/proxyman/command"
routerservice "github.com/xtls/xray-core/app/router/command"
statsservice "github.com/xtls/xray-core/app/stats/command"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/serial"
)
@ -20,7 +21,7 @@ type APIConfig struct {
func (c *APIConfig) Build() (*commander.Config, error) {
if c.Tag == "" {
return nil, newError("API tag can't be empty.")
return nil, errors.New("API tag can't be empty.")
}
services := make([]*serial.TypedMessage, 0, 16)

View file

@ -3,6 +3,7 @@ package conf
import (
"encoding/json"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/blackhole"
"google.golang.org/protobuf/proto"
@ -29,7 +30,7 @@ func (v *BlackholeConfig) Build() (proto.Message, error) {
if v.Response != nil {
response, _, err := configLoader.Load(v.Response)
if err != nil {
return nil, newError("Config: Failed to parse Blackhole response config.").Base(err)
return nil, errors.New("Config: Failed to parse Blackhole response config.").Base(err)
}
responseSettings, err := response.(Buildable).Build()
if err != nil {

View file

@ -4,6 +4,7 @@ import (
"encoding/json"
"strings"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/platform"
"github.com/xtls/xray-core/common/protocol"
@ -33,7 +34,7 @@ func (v *StringList) UnmarshalJSON(data []byte) error {
*v = *NewStringList(strlist)
return nil
}
return newError("unknown format of a string list: " + string(data))
return errors.New("unknown format of a string list: " + string(data))
}
type Address struct {
@ -43,7 +44,7 @@ type Address struct {
func (v *Address) UnmarshalJSON(data []byte) error {
var rawStr string
if err := json.Unmarshal(data, &rawStr); err != nil {
return newError("invalid address: ", string(data)).Base(err)
return errors.New("invalid address: ", string(data)).Base(err)
}
if strings.HasPrefix(rawStr, "env:") {
rawStr = platform.NewEnvFlag(rawStr[4:]).GetValue(func() string { return "" })
@ -92,7 +93,7 @@ func (v *NetworkList) UnmarshalJSON(data []byte) error {
*v = nl
return nil
}
return newError("unknown format of a string list: " + string(data))
return errors.New("unknown format of a string list: " + string(data))
}
func (v *NetworkList) Build() []net.Network {
@ -123,7 +124,7 @@ func parseStringPort(s string) (net.Port, net.Port, error) {
pair := strings.SplitN(s, "-", 2)
if len(pair) == 0 {
return net.Port(0), net.Port(0), newError("invalid port range: ", s)
return net.Port(0), net.Port(0), errors.New("invalid port range: ", s)
}
if len(pair) == 1 {
port, err := net.PortFromString(pair[0])
@ -176,12 +177,12 @@ func (v *PortRange) UnmarshalJSON(data []byte) error {
v.From = uint32(from)
v.To = uint32(to)
if v.From > v.To {
return newError("invalid port range ", v.From, " -> ", v.To)
return errors.New("invalid port range ", v.From, " -> ", v.To)
}
return nil
}
return newError("invalid port range: ", string(data))
return errors.New("invalid port range: ", string(data))
}
type PortList struct {
@ -202,7 +203,7 @@ func (list *PortList) UnmarshalJSON(data []byte) error {
var number uint32
if err := json.Unmarshal(data, &listStr); err != nil {
if err2 := json.Unmarshal(data, &number); err2 != nil {
return newError("invalid port: ", string(data)).Base(err2)
return errors.New("invalid port: ", string(data)).Base(err2)
}
}
rangelist := strings.Split(listStr, ",")
@ -212,13 +213,13 @@ func (list *PortList) UnmarshalJSON(data []byte) error {
if strings.Contains(trimmed, "-") || strings.Contains(trimmed, "env:") {
from, to, err := parseStringPort(trimmed)
if err != nil {
return newError("invalid port range: ", trimmed).Base(err)
return errors.New("invalid port range: ", trimmed).Base(err)
}
list.Range = append(list.Range, PortRange{From: uint32(from), To: uint32(to)})
} else {
port, err := parseIntPort([]byte(trimmed))
if err != nil {
return newError("invalid port: ", trimmed).Base(err)
return errors.New("invalid port: ", trimmed).Base(err)
}
list.Range = append(list.Range, PortRange{From: uint32(port), To: uint32(port)})
}

View file

@ -7,6 +7,7 @@ import (
"github.com/xtls/xray-core/app/dns"
"github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
)
@ -47,7 +48,7 @@ func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
return nil
}
return newError("failed to parse name server: ", string(data))
return errors.New("failed to parse name server: ", string(data))
}
func toDomainMatchingType(t router.Domain_Type) dns.DomainMatchingType {
@ -67,7 +68,7 @@ func toDomainMatchingType(t router.Domain_Type) dns.DomainMatchingType {
func (c *NameServerConfig) Build() (*dns.NameServer, error) {
if c.Address == nil {
return nil, newError("NameServer address is not specified.")
return nil, errors.New("NameServer address is not specified.")
}
var domains []*dns.NameServer_PriorityDomain
@ -76,7 +77,7 @@ func (c *NameServerConfig) Build() (*dns.NameServer, error) {
for _, rule := range c.Domains {
parsedDomain, err := parseDomainRule(rule)
if err != nil {
return nil, newError("invalid domain rule: ", rule).Base(err)
return nil, errors.New("invalid domain rule: ", rule).Base(err)
}
for _, pd := range parsedDomain {
@ -93,13 +94,13 @@ func (c *NameServerConfig) Build() (*dns.NameServer, error) {
geoipList, err := ToCidrList(c.ExpectIPs)
if err != nil {
return nil, newError("invalid IP rule: ", c.ExpectIPs).Base(err)
return nil, errors.New("invalid IP rule: ", c.ExpectIPs).Base(err)
}
var myClientIP []byte
if c.ClientIP != nil {
if !c.ClientIP.Family().IsIP() {
return nil, newError("not an IP address:", c.ClientIP.String())
return nil, errors.New("not an IP address:", c.ClientIP.String())
}
myClientIP = []byte(c.ClientIP.IP())
}
@ -153,7 +154,7 @@ func (h *HostAddress) UnmarshalJSON(data []byte) error {
case json.Unmarshal(data, &addrs) == nil:
h.addrs = addrs
default:
return newError("invalid address")
return errors.New("invalid address")
}
return nil
}
@ -196,7 +197,7 @@ func (m *HostsWrapper) UnmarshalJSON(data []byte) error {
m.Hosts = hosts
return nil
}
return newError("invalid DNS hosts").Base(err)
return errors.New("invalid DNS hosts").Base(err)
}
// Build implements Buildable
@ -214,7 +215,7 @@ func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
case strings.HasPrefix(domain, "domain:"):
domainName := domain[7:]
if len(domainName) == 0 {
return nil, newError("empty domain type of rule: ", domain)
return nil, errors.New("empty domain type of rule: ", domain)
}
mapping := getHostMapping(m.Hosts[domain])
mapping.Type = dns.DomainMatchingType_Subdomain
@ -224,11 +225,11 @@ func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
case strings.HasPrefix(domain, "geosite:"):
listName := domain[8:]
if len(listName) == 0 {
return nil, newError("empty geosite rule: ", domain)
return nil, errors.New("empty geosite rule: ", domain)
}
geositeList, err := loadGeositeWithAttr("geosite.dat", listName)
if err != nil {
return nil, newError("failed to load geosite: ", listName).Base(err)
return nil, errors.New("failed to load geosite: ", listName).Base(err)
}
for _, d := range geositeList {
mapping := getHostMapping(m.Hosts[domain])
@ -240,7 +241,7 @@ func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
case strings.HasPrefix(domain, "regexp:"):
regexpVal := domain[7:]
if len(regexpVal) == 0 {
return nil, newError("empty regexp type of rule: ", domain)
return nil, errors.New("empty regexp type of rule: ", domain)
}
mapping := getHostMapping(m.Hosts[domain])
mapping.Type = dns.DomainMatchingType_Regex
@ -250,7 +251,7 @@ func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
case strings.HasPrefix(domain, "keyword:"):
keywordVal := domain[8:]
if len(keywordVal) == 0 {
return nil, newError("empty keyword type of rule: ", domain)
return nil, errors.New("empty keyword type of rule: ", domain)
}
mapping := getHostMapping(m.Hosts[domain])
mapping.Type = dns.DomainMatchingType_Keyword
@ -260,7 +261,7 @@ func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
case strings.HasPrefix(domain, "full:"):
fullVal := domain[5:]
if len(fullVal) == 0 {
return nil, newError("empty full domain type of rule: ", domain)
return nil, errors.New("empty full domain type of rule: ", domain)
}
mapping := getHostMapping(m.Hosts[domain])
mapping.Type = dns.DomainMatchingType_Full
@ -276,20 +277,20 @@ func (m *HostsWrapper) Build() ([]*dns.Config_HostMapping, error) {
case !strings.Contains(substr, "."):
mapping.Domain = "^[^.]*" + substr + "[^.]*$"
default:
return nil, newError("substr in dotless rule should not contain a dot: ", substr)
return nil, errors.New("substr in dotless rule should not contain a dot: ", substr)
}
mappings = append(mappings, mapping)
case strings.HasPrefix(domain, "ext:"):
kv := strings.Split(domain[4:], ":")
if len(kv) != 2 {
return nil, newError("invalid external resource: ", domain)
return nil, errors.New("invalid external resource: ", domain)
}
filename := kv[0]
list := kv[1]
geositeList, err := loadGeositeWithAttr(filename, list)
if err != nil {
return nil, newError("failed to load domain list: ", list, " from ", filename).Base(err)
return nil, errors.New("failed to load domain list: ", list, " from ", filename).Base(err)
}
for _, d := range geositeList {
mapping := getHostMapping(m.Hosts[domain])
@ -320,7 +321,7 @@ func (c *DNSConfig) Build() (*dns.Config, error) {
if c.ClientIP != nil {
if !c.ClientIP.Family().IsIP() {
return nil, newError("not an IP address:", c.ClientIP.String())
return nil, errors.New("not an IP address:", c.ClientIP.String())
}
config.ClientIp = []byte(c.ClientIP.IP())
}
@ -328,7 +329,7 @@ func (c *DNSConfig) Build() (*dns.Config, error) {
for _, server := range c.Servers {
ns, err := server.Build()
if err != nil {
return nil, newError("failed to build nameserver").Base(err)
return nil, errors.New("failed to build nameserver").Base(err)
}
config.NameServer = append(config.NameServer, ns)
}
@ -336,7 +337,7 @@ func (c *DNSConfig) Build() (*dns.Config, error) {
if c.Hosts != nil {
staticHosts, err := c.Hosts.Build()
if err != nil {
return nil, newError("failed to build hosts").Base(err)
return nil, errors.New("failed to build hosts").Base(err)
}
config.StaticHosts = append(config.StaticHosts, staticHosts...)
}

View file

@ -1,6 +1,7 @@
package conf
import (
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/proxy/dns"
"google.golang.org/protobuf/proto"
@ -30,7 +31,7 @@ func (c *DNSOutboundConfig) Build() (proto.Message, error) {
c.NonIPQuery = "drop"
case "drop", "skip":
default:
return nil, newError(`unknown "nonIPQuery": `, c.NonIPQuery)
return nil, errors.New(`unknown "nonIPQuery": `, c.NonIPQuery)
}
config.Non_IPQuery = c.NonIPQuery
return config, nil

View file

@ -1,9 +0,0 @@
package conf
import "github.com/xtls/xray-core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}

View file

@ -1,10 +1,12 @@
package conf
import (
"context"
"encoding/json"
"strings"
"github.com/xtls/xray-core/app/dns/fakedns"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/features/dns"
)
@ -28,7 +30,7 @@ func (f *FakeDNSConfig) UnmarshalJSON(data []byte) error {
case json.Unmarshal(data, &pools) == nil:
f.pools = pools
default:
return newError("invalid fakedns config")
return errors.New("invalid fakedns config")
}
return nil
}
@ -51,7 +53,7 @@ func (f *FakeDNSConfig) Build() (*fakedns.FakeDnsPoolMulti, error) {
return &fakeDNSPool, nil
}
return nil, newError("no valid FakeDNS config")
return nil, errors.New("no valid FakeDNS config")
}
type FakeDNSPostProcessingStage struct{}
@ -122,7 +124,7 @@ func (FakeDNSPostProcessingStage) Process(config *Config) error {
}
}
if !found {
newError("Defined FakeDNS but haven't enabled FakeDNS destOverride at any inbound.").AtWarning().WriteToLog()
errors.LogWarning(context.Background(), "Defined FakeDNS but haven't enabled FakeDNS destOverride at any inbound.")
}
}

View file

@ -5,6 +5,7 @@ import (
"strconv"
"strings"
"github.com/xtls/xray-core/common/errors"
v2net "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/proxy/freedom"
@ -53,7 +54,7 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
case "forceipv6v4":
config.DomainStrategy = freedom.Config_FORCE_IP64
default:
return nil, newError("unsupported domain strategy: ", c.DomainStrategy)
return nil, errors.New("unsupported domain strategy: ", c.DomainStrategy)
}
if c.Fragment != nil {
@ -80,22 +81,22 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
config.Fragment.PacketsTo = config.Fragment.PacketsFrom
}
if err != nil {
return nil, newError("Invalid PacketsFrom").Base(err)
return nil, errors.New("Invalid PacketsFrom").Base(err)
}
if err2 != nil {
return nil, newError("Invalid PacketsTo").Base(err2)
return nil, errors.New("Invalid PacketsTo").Base(err2)
}
if config.Fragment.PacketsFrom > config.Fragment.PacketsTo {
config.Fragment.PacketsFrom, config.Fragment.PacketsTo = config.Fragment.PacketsTo, config.Fragment.PacketsFrom
}
if config.Fragment.PacketsFrom == 0 {
return nil, newError("PacketsFrom can't be 0")
return nil, errors.New("PacketsFrom can't be 0")
}
}
{
if c.Fragment.Length == "" {
return nil, newError("Length can't be empty")
return nil, errors.New("Length can't be empty")
}
lengthMinMax := strings.Split(c.Fragment.Length, "-")
if len(lengthMinMax) == 2 {
@ -106,22 +107,22 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
config.Fragment.LengthMax = config.Fragment.LengthMin
}
if err != nil {
return nil, newError("Invalid LengthMin").Base(err)
return nil, errors.New("Invalid LengthMin").Base(err)
}
if err2 != nil {
return nil, newError("Invalid LengthMax").Base(err2)
return nil, errors.New("Invalid LengthMax").Base(err2)
}
if config.Fragment.LengthMin > config.Fragment.LengthMax {
config.Fragment.LengthMin, config.Fragment.LengthMax = config.Fragment.LengthMax, config.Fragment.LengthMin
}
if config.Fragment.LengthMin == 0 {
return nil, newError("LengthMin can't be 0")
return nil, errors.New("LengthMin can't be 0")
}
}
{
if c.Fragment.Interval == "" {
return nil, newError("Interval can't be empty")
return nil, errors.New("Interval can't be empty")
}
intervalMinMax := strings.Split(c.Fragment.Interval, "-")
if len(intervalMinMax) == 2 {
@ -132,10 +133,10 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
config.Fragment.IntervalMax = config.Fragment.IntervalMin
}
if err != nil {
return nil, newError("Invalid IntervalMin").Base(err)
return nil, errors.New("Invalid IntervalMin").Base(err)
}
if err2 != nil {
return nil, newError("Invalid IntervalMax").Base(err2)
return nil, errors.New("Invalid IntervalMax").Base(err2)
}
if config.Fragment.IntervalMin > config.Fragment.IntervalMax {
config.Fragment.IntervalMin, config.Fragment.IntervalMax = config.Fragment.IntervalMax, config.Fragment.IntervalMin
@ -150,11 +151,11 @@ func (c *FreedomConfig) Build() (proto.Message, error) {
if len(c.Redirect) > 0 {
host, portStr, err := net.SplitHostPort(c.Redirect)
if err != nil {
return nil, newError("invalid redirect address: ", c.Redirect, ": ", err).Base(err)
return nil, errors.New("invalid redirect address: ", c.Redirect, ": ", err).Base(err)
}
port, err := v2net.PortFromString(portStr)
if err != nil {
return nil, newError("invalid redirect port: ", c.Redirect, ": ", err).Base(err)
return nil, errors.New("invalid redirect port: ", c.Redirect, ": ", err).Base(err)
}
config.DestinationOverride = &freedom.DestinationOverride{
Server: &protocol.ServerEndpoint{

View file

@ -3,6 +3,7 @@ package conf
import (
"encoding/json"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/http"
@ -67,11 +68,11 @@ func (v *HTTPClientConfig) Build() (proto.Message, error) {
for _, rawUser := range serverConfig.Users {
user := new(protocol.User)
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, newError("failed to parse HTTP user").Base(err).AtError()
return nil, errors.New("failed to parse HTTP user").Base(err).AtError()
}
account := new(HTTPAccount)
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, newError("failed to parse HTTP account").Base(err).AtError()
return nil, errors.New("failed to parse HTTP account").Base(err).AtError()
}
user.Account = serial.ToTypedMessage(account.Build())
server.User = append(server.User, user)

View file

@ -1,5 +1,7 @@
package conf
import "github.com/xtls/xray-core/common/errors"
type ConfigureFilePostProcessingStage interface {
Process(conf *Config) error
}
@ -16,7 +18,7 @@ func RegisterConfigureFilePostProcessingStage(name string, stage ConfigureFilePo
func PostProcessConfigureFile(conf *Config) error {
for k, v := range configureFilePostProcessingStages {
if err := v.Process(conf); err != nil {
return newError("Rejected by Postprocessing Stage ", k).AtError().Base(err)
return errors.New("Rejected by Postprocessing Stage ", k).AtError().Base(err)
}
}
return nil

View file

@ -3,6 +3,8 @@ package conf
import (
"encoding/json"
"strings"
"github.com/xtls/xray-core/common/errors"
)
type ConfigCreator func() interface{}
@ -11,7 +13,7 @@ type ConfigCreatorCache map[string]ConfigCreator
func (v ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) error {
if _, found := v[id]; found {
return newError(id, " already registered.").AtError()
return errors.New(id, " already registered.").AtError()
}
v[id] = creator
@ -21,7 +23,7 @@ func (v ConfigCreatorCache) RegisterCreator(id string, creator ConfigCreator) er
func (v ConfigCreatorCache) CreateConfig(id string) (interface{}, error) {
creator, found := v[id]
if !found {
return nil, newError("unknown config id: ", id)
return nil, errors.New("unknown config id: ", id)
}
return creator(), nil
}
@ -59,7 +61,7 @@ func (v *JSONConfigLoader) Load(raw []byte) (interface{}, string, error) {
}
rawID, found := obj[v.idKey]
if !found {
return nil, "", newError(v.idKey, " not found in JSON context").AtError()
return nil, "", errors.New(v.idKey, " not found in JSON context").AtError()
}
var id string
if err := json.Unmarshal(rawID, &id); err != nil {

View file

@ -2,6 +2,7 @@ package conf
import (
"github.com/xtls/xray-core/app/metrics"
"github.com/xtls/xray-core/common/errors"
)
type MetricsConfig struct {
@ -10,7 +11,7 @@ type MetricsConfig struct {
func (c *MetricsConfig) Build() (*metrics.Config, error) {
if c.Tag == "" {
return nil, newError("metrics tag can't be empty.")
return nil, errors.New("metrics tag can't be empty.")
}
return &metrics.Config{

View file

@ -7,6 +7,7 @@ import (
"strings"
"github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/platform/filesystem"
"github.com/xtls/xray-core/common/serial"
@ -34,10 +35,10 @@ type BalancingRule struct {
// Build builds the balancing rule
func (r *BalancingRule) Build() (*router.BalancingRule, error) {
if r.Tag == "" {
return nil, newError("empty balancer tag")
return nil, errors.New("empty balancer tag")
}
if len(r.Selectors) == 0 {
return nil, newError("empty selector list")
return nil, errors.New("empty selector list")
}
r.Strategy.Type = strings.ToLower(r.Strategy.Type)
@ -46,7 +47,7 @@ func (r *BalancingRule) Build() (*router.BalancingRule, error) {
r.Strategy.Type = strategyRandom
case strategyRandom, strategyLeastLoad, strategyLeastPing, strategyRoundRobin:
default:
return nil, newError("unknown balancing strategy: " + r.Strategy.Type)
return nil, errors.New("unknown balancing strategy: " + r.Strategy.Type)
}
settings := []byte("{}")
@ -55,7 +56,7 @@ func (r *BalancingRule) Build() (*router.BalancingRule, error) {
}
rawConfig, err := strategyConfigLoader.LoadWithID(settings, r.Strategy.Type)
if err != nil {
return nil, newError("failed to parse to strategy config.").Base(err)
return nil, errors.New("failed to parse to strategy config.").Base(err)
}
var ts proto.Message
if builder, ok := rawConfig.(Buildable); ok {
@ -163,12 +164,12 @@ func ParseIP(s string) (*router.CIDR, error) {
if len(mask) > 0 {
bits64, err := strconv.ParseUint(mask, 10, 32)
if err != nil {
return nil, newError("invalid network mask for router: ", mask).Base(err)
return nil, errors.New("invalid network mask for router: ", mask).Base(err)
}
bits = uint32(bits64)
}
if bits > 32 {
return nil, newError("invalid network mask for router: ", bits)
return nil, errors.New("invalid network mask for router: ", bits)
}
return &router.CIDR{
Ip: []byte(ip.IP()),
@ -179,19 +180,19 @@ func ParseIP(s string) (*router.CIDR, error) {
if len(mask) > 0 {
bits64, err := strconv.ParseUint(mask, 10, 32)
if err != nil {
return nil, newError("invalid network mask for router: ", mask).Base(err)
return nil, errors.New("invalid network mask for router: ", mask).Base(err)
}
bits = uint32(bits64)
}
if bits > 128 {
return nil, newError("invalid network mask for router: ", bits)
return nil, errors.New("invalid network mask for router: ", bits)
}
return &router.CIDR{
Ip: []byte(ip.IP()),
Prefix: bits,
}, nil
default:
return nil, newError("unsupported address for router: ", s)
return nil, errors.New("unsupported address for router: ", s)
}
}
@ -209,10 +210,10 @@ func loadFile(file string) ([]byte, error) {
if FileCache[file] == nil {
bs, err := filesystem.ReadAsset(file)
if err != nil {
return nil, newError("failed to open file: ", file).Base(err)
return nil, errors.New("failed to open file: ", file).Base(err)
}
if len(bs) == 0 {
return nil, newError("empty file: ", file)
return nil, errors.New("empty file: ", file)
}
// Do not cache file, may save RAM when there
// are many files, but consume CPU each time.
@ -227,15 +228,15 @@ func loadIP(file, code string) ([]*router.CIDR, error) {
if IPCache[index] == nil {
bs, err := loadFile(file)
if err != nil {
return nil, newError("failed to load file: ", file).Base(err)
return nil, errors.New("failed to load file: ", file).Base(err)
}
bs = find(bs, []byte(code))
if bs == nil {
return nil, newError("code not found in ", file, ": ", code)
return nil, errors.New("code not found in ", file, ": ", code)
}
var geoip router.GeoIP
if err := proto.Unmarshal(bs, &geoip); err != nil {
return nil, newError("error unmarshal IP in ", file, ": ", code).Base(err)
return nil, errors.New("error unmarshal IP in ", file, ": ", code).Base(err)
}
defer runtime.GC() // or debug.FreeOSMemory()
return geoip.Cidr, nil // do not cache geoip
@ -249,15 +250,15 @@ func loadSite(file, code string) ([]*router.Domain, error) {
if SiteCache[index] == nil {
bs, err := loadFile(file)
if err != nil {
return nil, newError("failed to load file: ", file).Base(err)
return nil, errors.New("failed to load file: ", file).Base(err)
}
bs = find(bs, []byte(code))
if bs == nil {
return nil, newError("list not found in ", file, ": ", code)
return nil, errors.New("list not found in ", file, ": ", code)
}
var geosite router.GeoSite
if err := proto.Unmarshal(bs, &geosite); err != nil {
return nil, newError("error unmarshal Site in ", file, ": ", code).Base(err)
return nil, errors.New("error unmarshal Site in ", file, ": ", code).Base(err)
}
defer runtime.GC() // or debug.FreeOSMemory()
return geosite.Domain, nil // do not cache geosite
@ -361,7 +362,7 @@ func parseAttrs(attrs []string) *AttributeList {
func loadGeositeWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
parts := strings.Split(siteWithAttr, "@")
if len(parts) == 0 {
return nil, newError("empty site")
return nil, errors.New("empty site")
}
country := strings.ToUpper(parts[0])
attrs := parseAttrs(parts[1:])
@ -389,7 +390,7 @@ func parseDomainRule(domain string) ([]*router.Domain, error) {
country := strings.ToUpper(domain[8:])
domains, err := loadGeositeWithAttr("geosite.dat", country)
if err != nil {
return nil, newError("failed to load geosite: ", country).Base(err)
return nil, errors.New("failed to load geosite: ", country).Base(err)
}
return domains, nil
}
@ -407,13 +408,13 @@ func parseDomainRule(domain string) ([]*router.Domain, error) {
if isExtDatFile != 0 {
kv := strings.Split(domain[isExtDatFile:], ":")
if len(kv) != 2 {
return nil, newError("invalid external resource: ", domain)
return nil, errors.New("invalid external resource: ", domain)
}
filename := kv[0]
country := kv[1]
domains, err := loadGeositeWithAttr(filename, country)
if err != nil {
return nil, newError("failed to load external sites: ", country, " from ", filename).Base(err)
return nil, errors.New("failed to load external sites: ", country, " from ", filename).Base(err)
}
return domains, nil
}
@ -444,7 +445,7 @@ func parseDomainRule(domain string) ([]*router.Domain, error) {
case !strings.Contains(substr, "."):
domainRule.Value = "^[^.]*" + substr + "[^.]*$"
default:
return nil, newError("substr in dotless rule should not contain a dot: ", substr)
return nil, errors.New("substr in dotless rule should not contain a dot: ", substr)
}
default:
@ -467,11 +468,11 @@ func ToCidrList(ips StringList) ([]*router.GeoIP, error) {
isReverseMatch = true
}
if len(country) == 0 {
return nil, newError("empty country name in rule")
return nil, errors.New("empty country name in rule")
}
geoip, err := loadGeoIP(strings.ToUpper(country))
if err != nil {
return nil, newError("failed to load GeoIP: ", country).Base(err)
return nil, errors.New("failed to load GeoIP: ", country).Base(err)
}
geoipList = append(geoipList, &router.GeoIP{
@ -495,13 +496,13 @@ func ToCidrList(ips StringList) ([]*router.GeoIP, error) {
if isExtDatFile != 0 {
kv := strings.Split(ip[isExtDatFile:], ":")
if len(kv) != 2 {
return nil, newError("invalid external resource: ", ip)
return nil, errors.New("invalid external resource: ", ip)
}
filename := kv[0]
country := kv[1]
if len(filename) == 0 || len(country) == 0 {
return nil, newError("empty filename or empty country in rule")
return nil, errors.New("empty filename or empty country in rule")
}
isReverseMatch := false
@ -511,7 +512,7 @@ func ToCidrList(ips StringList) ([]*router.GeoIP, error) {
}
geoip, err := loadIP(filename, strings.ToUpper(country))
if err != nil {
return nil, newError("failed to load IPs: ", country, " from ", filename).Base(err)
return nil, errors.New("failed to load IPs: ", country, " from ", filename).Base(err)
}
geoipList = append(geoipList, &router.GeoIP{
@ -525,7 +526,7 @@ func ToCidrList(ips StringList) ([]*router.GeoIP, error) {
ipRule, err := ParseIP(ip)
if err != nil {
return nil, newError("invalid IP: ", ip).Base(err)
return nil, errors.New("invalid IP: ", ip).Base(err)
}
customCidrs = append(customCidrs, ipRule)
}
@ -572,7 +573,7 @@ func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
BalancingTag: rawFieldRule.BalancerTag,
}
default:
return nil, newError("neither outboundTag nor balancerTag is specified in routing rule")
return nil, errors.New("neither outboundTag nor balancerTag is specified in routing rule")
}
if rawFieldRule.DomainMatcher != "" {
@ -583,7 +584,7 @@ func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
for _, domain := range *rawFieldRule.Domain {
rules, err := parseDomainRule(domain)
if err != nil {
return nil, newError("failed to parse domain rule: ", domain).Base(err)
return nil, errors.New("failed to parse domain rule: ", domain).Base(err)
}
rule.Domain = append(rule.Domain, rules...)
}
@ -593,7 +594,7 @@ func parseFieldRule(msg json.RawMessage) (*router.RoutingRule, error) {
for _, domain := range *rawFieldRule.Domains {
rules, err := parseDomainRule(domain)
if err != nil {
return nil, newError("failed to parse domain rule: ", domain).Base(err)
return nil, errors.New("failed to parse domain rule: ", domain).Base(err)
}
rule.Domain = append(rule.Domain, rules...)
}
@ -656,14 +657,14 @@ func ParseRule(msg json.RawMessage) (*router.RoutingRule, error) {
rawRule := new(RouterRule)
err := json.Unmarshal(msg, rawRule)
if err != nil {
return nil, newError("invalid router rule").Base(err)
return nil, errors.New("invalid router rule").Base(err)
}
if rawRule.Type == "" || strings.EqualFold(rawRule.Type, "field") {
fieldrule, err := parseFieldRule(msg)
if err != nil {
return nil, newError("invalid field rule").Base(err)
return nil, errors.New("invalid field rule").Base(err)
}
return fieldrule, nil
}
return nil, newError("unknown router rule type: ", rawRule.Type)
return nil, errors.New("unknown router rule type: ", rawRule.Type)
}

View file

@ -1,8 +1,10 @@
package serial
import (
"context"
"io"
"github.com/xtls/xray-core/common/errors"
creflect "github.com/xtls/xray-core/common/reflect"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/infra/conf"
@ -18,20 +20,20 @@ func MergeConfigFromFiles(files []string, formats []string) (string, error) {
if j, ok := creflect.MarshalToJson(c); ok {
return j, nil
}
return "", newError("marshal to json failed.").AtError()
return "", errors.New("marshal to json failed.").AtError()
}
func mergeConfigs(files []string, formats []string) (*conf.Config, error) {
cf := &conf.Config{}
for i, file := range files {
newError("Reading config: ", file).AtInfo().WriteToLog()
errors.LogInfo(context.Background(), "Reading config: ", file)
r, err := confloader.LoadConfig(file)
if err != nil {
return nil, newError("failed to read config: ", file).Base(err)
return nil, errors.New("failed to read config: ", file).Base(err)
}
c, err := ReaderDecoderByFormat[formats[i]](r)
if err != nil {
return nil, newError("failed to decode config: ", file).Base(err)
return nil, errors.New("failed to decode config: ", file).Base(err)
}
if i == 0 {
*cf = *c

View file

@ -1,9 +0,0 @@
package serial
import "github.com/xtls/xray-core/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}

View file

@ -61,9 +61,9 @@ func DecodeJSONConfig(reader io.Reader) (*conf.Config, error) {
pos = findOffset(jsonContent.Bytes(), int(tErr.Offset))
}
if pos != nil {
return nil, newError("failed to read config file at line ", pos.line, " char ", pos.char).Base(err)
return nil, errors.New("failed to read config file at line ", pos.line, " char ", pos.char).Base(err)
}
return nil, newError("failed to read config file").Base(err)
return nil, errors.New("failed to read config file").Base(err)
}
return jsonConfig, nil
@ -77,7 +77,7 @@ func LoadJSONConfig(reader io.Reader) (*core.Config, error) {
pbConfig, err := jsonConfig.Build()
if err != nil {
return nil, newError("failed to parse json config").Base(err)
return nil, errors.New("failed to parse json config").Base(err)
}
return pbConfig, nil
@ -88,17 +88,17 @@ func LoadJSONConfig(reader io.Reader) (*core.Config, error) {
func DecodeTOMLConfig(reader io.Reader) (*conf.Config, error) {
tomlFile, err := io.ReadAll(reader)
if err != nil {
return nil, newError("failed to read config file").Base(err)
return nil, errors.New("failed to read config file").Base(err)
}
configMap := make(map[string]interface{})
if err := toml.Unmarshal(tomlFile, &configMap); err != nil {
return nil, newError("failed to convert toml to map").Base(err)
return nil, errors.New("failed to convert toml to map").Base(err)
}
jsonFile, err := json.Marshal(&configMap)
if err != nil {
return nil, newError("failed to convert map to json").Base(err)
return nil, errors.New("failed to convert map to json").Base(err)
}
return DecodeJSONConfig(bytes.NewReader(jsonFile))
@ -112,7 +112,7 @@ func LoadTOMLConfig(reader io.Reader) (*core.Config, error) {
pbConfig, err := tomlConfig.Build()
if err != nil {
return nil, newError("failed to parse toml config").Base(err)
return nil, errors.New("failed to parse toml config").Base(err)
}
return pbConfig, nil
@ -123,12 +123,12 @@ func LoadTOMLConfig(reader io.Reader) (*core.Config, error) {
func DecodeYAMLConfig(reader io.Reader) (*conf.Config, error) {
yamlFile, err := io.ReadAll(reader)
if err != nil {
return nil, newError("failed to read config file").Base(err)
return nil, errors.New("failed to read config file").Base(err)
}
jsonFile, err := yaml.YAMLToJSON(yamlFile)
if err != nil {
return nil, newError("failed to convert yaml to json").Base(err)
return nil, errors.New("failed to convert yaml to json").Base(err)
}
return DecodeJSONConfig(bytes.NewReader(jsonFile))
@ -142,7 +142,7 @@ func LoadYAMLConfig(reader io.Reader) (*core.Config, error) {
pbConfig, err := yamlConfig.Build()
if err != nil {
return nil, newError("failed to parse yaml config").Base(err)
return nil, errors.New("failed to parse yaml config").Base(err)
}
return pbConfig, nil

View file

@ -5,6 +5,7 @@ import (
"github.com/sagernet/sing-shadowsocks/shadowaead_2022"
C "github.com/sagernet/sing/common"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/shadowsocks"
@ -64,11 +65,11 @@ func (v *ShadowsocksServerConfig) Build() (proto.Message, error) {
IvCheck: v.IVCheck,
}
if account.Password == "" {
return nil, newError("Shadowsocks password is not specified.")
return nil, errors.New("Shadowsocks password is not specified.")
}
if account.CipherType < shadowsocks.CipherType_AES_128_GCM ||
account.CipherType > shadowsocks.CipherType_XCHACHA20_POLY1305 {
return nil, newError("unsupported cipher method: ", user.Cipher)
return nil, errors.New("unsupported cipher method: ", user.Cipher)
}
config.Users = append(config.Users, &protocol.User{
Email: user.Email,
@ -83,10 +84,10 @@ func (v *ShadowsocksServerConfig) Build() (proto.Message, error) {
IvCheck: v.IVCheck,
}
if account.Password == "" {
return nil, newError("Shadowsocks password is not specified.")
return nil, errors.New("Shadowsocks password is not specified.")
}
if account.CipherType == shadowsocks.CipherType_UNKNOWN {
return nil, newError("unknown cipher method: ", v.Cipher)
return nil, errors.New("unknown cipher method: ", v.Cipher)
}
config.Users = append(config.Users, &protocol.User{
Email: v.Email,
@ -109,10 +110,10 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
}
if v.Cipher == "" {
return nil, newError("shadowsocks 2022 (multi-user): missing server method")
return nil, errors.New("shadowsocks 2022 (multi-user): missing server method")
}
if !strings.Contains(v.Cipher, "aes") {
return nil, newError("shadowsocks 2022 (multi-user): only blake3-aes-*-gcm methods are supported")
return nil, errors.New("shadowsocks 2022 (multi-user): only blake3-aes-*-gcm methods are supported")
}
if v.Users[0].Address == nil {
@ -123,7 +124,7 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
for _, user := range v.Users {
if user.Cipher != "" {
return nil, newError("shadowsocks 2022 (multi-user): users must have empty method")
return nil, errors.New("shadowsocks 2022 (multi-user): users must have empty method")
}
config.Users = append(config.Users, &shadowsocks_2022.User{
Key: user.Password,
@ -139,10 +140,10 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
config.Network = v.NetworkList.Build()
for _, user := range v.Users {
if user.Cipher != "" {
return nil, newError("shadowsocks 2022 (relay): users must have empty method")
return nil, errors.New("shadowsocks 2022 (relay): users must have empty method")
}
if user.Address == nil {
return nil, newError("shadowsocks 2022 (relay): all users must have relay address")
return nil, errors.New("shadowsocks 2022 (relay): all users must have relay address")
}
config.Destinations = append(config.Destinations, &shadowsocks_2022.RelayDestination{
Key: user.Password,
@ -172,20 +173,20 @@ type ShadowsocksClientConfig struct {
func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
if len(v.Servers) == 0 {
return nil, newError("0 Shadowsocks server configured.")
return nil, errors.New("0 Shadowsocks server configured.")
}
if len(v.Servers) == 1 {
server := v.Servers[0]
if C.Contains(shadowaead_2022.List, server.Cipher) {
if server.Address == nil {
return nil, newError("Shadowsocks server address is not set.")
return nil, errors.New("Shadowsocks server address is not set.")
}
if server.Port == 0 {
return nil, newError("Invalid Shadowsocks port.")
return nil, errors.New("Invalid Shadowsocks port.")
}
if server.Password == "" {
return nil, newError("Shadowsocks password is not specified.")
return nil, errors.New("Shadowsocks password is not specified.")
}
config := new(shadowsocks_2022.ClientConfig)
@ -203,23 +204,23 @@ func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
serverSpecs := make([]*protocol.ServerEndpoint, len(v.Servers))
for idx, server := range v.Servers {
if C.Contains(shadowaead_2022.List, server.Cipher) {
return nil, newError("Shadowsocks 2022 accept no multi servers")
return nil, errors.New("Shadowsocks 2022 accept no multi servers")
}
if server.Address == nil {
return nil, newError("Shadowsocks server address is not set.")
return nil, errors.New("Shadowsocks server address is not set.")
}
if server.Port == 0 {
return nil, newError("Invalid Shadowsocks port.")
return nil, errors.New("Invalid Shadowsocks port.")
}
if server.Password == "" {
return nil, newError("Shadowsocks password is not specified.")
return nil, errors.New("Shadowsocks password is not specified.")
}
account := &shadowsocks.Account{
Password: server.Password,
}
account.CipherType = cipherFromString(server.Cipher)
if account.CipherType == shadowsocks.CipherType_UNKNOWN {
return nil, newError("unknown cipher method: ", server.Cipher)
return nil, errors.New("unknown cipher method: ", server.Cipher)
}
account.IvCheck = server.IVCheck

View file

@ -4,6 +4,7 @@ import (
"encoding/json"
"strings"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/proxy/socks"
@ -44,7 +45,7 @@ func (v *SocksServerConfig) Build() (proto.Message, error) {
case AuthMethodUserPass:
config.AuthType = socks.AuthType_PASSWORD
default:
// newError("unknown socks auth method: ", v.AuthMethod, ". Default to noauth.").AtWarning().WriteToLog()
// errors.New("unknown socks auth method: ", v.AuthMethod, ". Default to noauth.").AtWarning().WriteToLog()
config.AuthType = socks.AuthType_NO_AUTH
}
@ -87,7 +88,7 @@ func (v *SocksClientConfig) Build() (proto.Message, error) {
case "", "5":
config.Version = socks.Version_SOCKS5
default:
return nil, newError("failed to parse socks server version: ", v.Version).AtError()
return nil, errors.New("failed to parse socks server version: ", v.Version).AtError()
}
for idx, serverConfig := range v.Servers {
server := &protocol.ServerEndpoint{
@ -97,14 +98,14 @@ func (v *SocksClientConfig) Build() (proto.Message, error) {
for _, rawUser := range serverConfig.Users {
user := new(protocol.User)
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, newError("failed to parse Socks user").Base(err).AtError()
return nil, errors.New("failed to parse Socks user").Base(err).AtError()
}
account := new(SocksAccount)
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, newError("failed to parse socks account").Base(err).AtError()
return nil, errors.New("failed to parse socks account").Base(err).AtError()
}
if config.Version != socks.Version_SOCKS5 && account.Password != "" {
return nil, newError("password is only supported in socks5").AtError()
return nil, errors.New("password is only supported in socks5").AtError()
}
user.Account = serial.ToTypedMessage(account.Build())
server.User = append(server.User, user)

View file

@ -1,6 +1,7 @@
package conf
import (
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/transport/global"
"github.com/xtls/xray-core/transport/internet"
@ -26,7 +27,7 @@ func (c *TransportConfig) Build() (*global.Config, error) {
if c.TCPConfig != nil {
ts, err := c.TCPConfig.Build()
if err != nil {
return nil, newError("failed to build TCP config").Base(err).AtError()
return nil, errors.New("failed to build TCP config").Base(err).AtError()
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "tcp",
@ -37,7 +38,7 @@ func (c *TransportConfig) Build() (*global.Config, error) {
if c.KCPConfig != nil {
ts, err := c.KCPConfig.Build()
if err != nil {
return nil, newError("failed to build mKCP config").Base(err).AtError()
return nil, errors.New("failed to build mKCP config").Base(err).AtError()
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "mkcp",
@ -48,7 +49,7 @@ func (c *TransportConfig) Build() (*global.Config, error) {
if c.WSConfig != nil {
ts, err := c.WSConfig.Build()
if err != nil {
return nil, newError("failed to build WebSocket config").Base(err)
return nil, errors.New("failed to build WebSocket config").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "websocket",
@ -59,7 +60,7 @@ func (c *TransportConfig) Build() (*global.Config, error) {
if c.HTTPConfig != nil {
ts, err := c.HTTPConfig.Build()
if err != nil {
return nil, newError("Failed to build HTTP config.").Base(err)
return nil, errors.New("Failed to build HTTP config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "http",
@ -70,7 +71,7 @@ func (c *TransportConfig) Build() (*global.Config, error) {
if c.DSConfig != nil {
ds, err := c.DSConfig.Build()
if err != nil {
return nil, newError("Failed to build DomainSocket config.").Base(err)
return nil, errors.New("Failed to build DomainSocket config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "domainsocket",
@ -81,7 +82,7 @@ func (c *TransportConfig) Build() (*global.Config, error) {
if c.QUICConfig != nil {
qs, err := c.QUICConfig.Build()
if err != nil {
return nil, newError("Failed to build QUIC config.").Base(err)
return nil, errors.New("Failed to build QUIC config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "quic",
@ -95,7 +96,7 @@ func (c *TransportConfig) Build() (*global.Config, error) {
if c.GRPCConfig != nil {
gs, err := c.GRPCConfig.Build()
if err != nil {
return nil, newError("Failed to build gRPC config.").Base(err)
return nil, errors.New("Failed to build gRPC config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "grpc",
@ -106,7 +107,7 @@ func (c *TransportConfig) Build() (*global.Config, error) {
if c.HTTPUPGRADEConfig != nil {
hs, err := c.HTTPUPGRADEConfig.Build()
if err != nil {
return nil, newError("failed to build HttpUpgrade config").Base(err)
return nil, errors.New("failed to build HttpUpgrade config").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "httpupgrade",
@ -117,7 +118,7 @@ func (c *TransportConfig) Build() (*global.Config, error) {
if c.SplitHTTPConfig != nil {
shs, err := c.SplitHTTPConfig.Build()
if err != nil {
return nil, newError("failed to build SplitHTTP config").Base(err)
return nil, errors.New("failed to build SplitHTTP config").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "splithttp",

View file

@ -3,6 +3,7 @@ package conf
import (
"sort"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/transport/internet/headers/dns"
"github.com/xtls/xray-core/transport/internet/headers/http"
"github.com/xtls/xray-core/transport/internet/headers/noop"
@ -133,7 +134,7 @@ func (v *AuthenticatorRequest) Build() (*http.RequestConfig, error) {
for _, key := range headerNames {
value := v.Headers[key]
if value == nil {
return nil, newError("empty HTTP header value: " + key).AtError()
return nil, errors.New("empty HTTP header value: " + key).AtError()
}
config.Header = append(config.Header, &http.Header{
Name: key,
@ -201,7 +202,7 @@ func (v *AuthenticatorResponse) Build() (*http.ResponseConfig, error) {
for _, key := range headerNames {
value := v.Headers[key]
if value == nil {
return nil, newError("empty HTTP header value: " + key).AtError()
return nil, errors.New("empty HTTP header value: " + key).AtError()
}
config.Header = append(config.Header, &http.Header{
Name: key,

View file

@ -11,6 +11,7 @@ import (
"strings"
"syscall"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/platform/filesystem"
"github.com/xtls/xray-core/common/protocol"
@ -66,14 +67,14 @@ func (c *KCPConfig) Build() (proto.Message, error) {
if c.Mtu != nil {
mtu := *c.Mtu
if mtu < 576 || mtu > 1460 {
return nil, newError("invalid mKCP MTU size: ", mtu).AtError()
return nil, errors.New("invalid mKCP MTU size: ", mtu).AtError()
}
config.Mtu = &kcp.MTU{Value: mtu}
}
if c.Tti != nil {
tti := *c.Tti
if tti < 10 || tti > 100 {
return nil, newError("invalid mKCP TTI: ", tti).AtError()
return nil, errors.New("invalid mKCP TTI: ", tti).AtError()
}
config.Tti = &kcp.TTI{Value: tti}
}
@ -105,11 +106,11 @@ func (c *KCPConfig) Build() (proto.Message, error) {
if len(c.HeaderConfig) > 0 {
headerConfig, _, err := kcpHeaderLoader.Load(c.HeaderConfig)
if err != nil {
return nil, newError("invalid mKCP header config.").Base(err).AtError()
return nil, errors.New("invalid mKCP header config.").Base(err).AtError()
}
ts, err := headerConfig.(Buildable).Build()
if err != nil {
return nil, newError("invalid mKCP header config").Base(err).AtError()
return nil, errors.New("invalid mKCP header config").Base(err).AtError()
}
config.HeaderConfig = serial.ToTypedMessage(ts)
}
@ -132,11 +133,11 @@ func (c *TCPConfig) Build() (proto.Message, error) {
if len(c.HeaderConfig) > 0 {
headerConfig, _, err := tcpHeaderLoader.Load(c.HeaderConfig)
if err != nil {
return nil, newError("invalid TCP header config").Base(err).AtError()
return nil, errors.New("invalid TCP header config").Base(err).AtError()
}
ts, err := headerConfig.(Buildable).Build()
if err != nil {
return nil, newError("invalid TCP header config").Base(err).AtError()
return nil, errors.New("invalid TCP header config").Base(err).AtError()
}
config.HeaderSettings = serial.ToTypedMessage(ts)
}
@ -209,10 +210,10 @@ func (c *HttpUpgradeConfig) Build() (proto.Message, error) {
// Host priority: Host field > headers field > address.
if c.Host == "" && c.Headers["host"] != "" {
c.Host = c.Headers["host"]
delete(c.Headers,"host")
delete(c.Headers, "host")
} else if c.Host == "" && c.Headers["Host"] != "" {
c.Host = c.Headers["Host"]
delete(c.Headers,"Host")
delete(c.Headers, "Host")
}
config := &httpupgrade.Config{
Path: path,
@ -286,7 +287,7 @@ func (c *HTTPConfig) Build() (proto.Message, error) {
for _, key := range headerNames {
value := c.Headers[key]
if value == nil {
return nil, newError("empty HTTP header value: " + key).AtError()
return nil, errors.New("empty HTTP header value: " + key).AtError()
}
config.Header = append(config.Header, &httpheader.Header{
Name: key,
@ -312,11 +313,11 @@ func (c *QUICConfig) Build() (proto.Message, error) {
if len(c.Header) > 0 {
headerConfig, _, err := kcpHeaderLoader.Load(c.Header)
if err != nil {
return nil, newError("invalid QUIC header config.").Base(err).AtError()
return nil, errors.New("invalid QUIC header config.").Base(err).AtError()
}
ts, err := headerConfig.(Buildable).Build()
if err != nil {
return nil, newError("invalid QUIC header config").Base(err).AtError()
return nil, errors.New("invalid QUIC header config").Base(err).AtError()
}
config.Header = serial.ToTypedMessage(ts)
}
@ -360,7 +361,7 @@ func readFileOrString(f string, s []string) ([]byte, error) {
if len(s) > 0 {
return []byte(strings.Join(s, "\n")), nil
}
return nil, newError("both file and bytes are empty.")
return nil, errors.New("both file and bytes are empty.")
}
type TLSCertConfig struct {
@ -379,7 +380,7 @@ func (c *TLSCertConfig) Build() (*tls.Certificate, error) {
cert, err := readFileOrString(c.CertFile, c.CertStr)
if err != nil {
return nil, newError("failed to parse certificate").Base(err)
return nil, errors.New("failed to parse certificate").Base(err)
}
certificate.Certificate = cert
certificate.CertificatePath = c.CertFile
@ -387,7 +388,7 @@ func (c *TLSCertConfig) Build() (*tls.Certificate, error) {
if len(c.KeyFile) > 0 || len(c.KeyStr) > 0 {
key, err := readFileOrString(c.KeyFile, c.KeyStr)
if err != nil {
return nil, newError("failed to parse key").Base(err)
return nil, errors.New("failed to parse key").Base(err)
}
certificate.Key = key
certificate.KeyPath = c.KeyFile
@ -456,7 +457,7 @@ func (c *TLSConfig) Build() (proto.Message, error) {
config.CipherSuites = c.CipherSuites
config.Fingerprint = strings.ToLower(c.Fingerprint)
if config.Fingerprint != "" && tls.GetFingerprint(config.Fingerprint) == nil {
return nil, newError(`unknown fingerprint: `, config.Fingerprint)
return nil, errors.New(`unknown fingerprint: `, config.Fingerprint)
}
config.RejectUnknownSni = c.RejectUnknownSNI
@ -539,29 +540,29 @@ func (c *REALITYConfig) Build() (proto.Message, error) {
}
}
if c.Type == "" {
return nil, newError(`please fill in a valid value for "dest"`)
return nil, errors.New(`please fill in a valid value for "dest"`)
}
if c.Xver > 2 {
return nil, newError(`invalid PROXY protocol version, "xver" only accepts 0, 1, 2`)
return nil, errors.New(`invalid PROXY protocol version, "xver" only accepts 0, 1, 2`)
}
if len(c.ServerNames) == 0 {
return nil, newError(`empty "serverNames"`)
return nil, errors.New(`empty "serverNames"`)
}
if c.PrivateKey == "" {
return nil, newError(`empty "privateKey"`)
return nil, errors.New(`empty "privateKey"`)
}
if config.PrivateKey, err = base64.RawURLEncoding.DecodeString(c.PrivateKey); err != nil || len(config.PrivateKey) != 32 {
return nil, newError(`invalid "privateKey": `, c.PrivateKey)
return nil, errors.New(`invalid "privateKey": `, c.PrivateKey)
}
if c.MinClientVer != "" {
config.MinClientVer = make([]byte, 3)
var u uint64
for i, s := range strings.Split(c.MinClientVer, ".") {
if i == 3 {
return nil, newError(`invalid "minClientVer": `, c.MinClientVer)
return nil, errors.New(`invalid "minClientVer": `, c.MinClientVer)
}
if u, err = strconv.ParseUint(s, 10, 8); err != nil {
return nil, newError(`"minClientVer[`, i, `]" should be lesser than 256`)
return nil, errors.New(`"minClientVer[`, i, `]" should be lesser than 256`)
} else {
config.MinClientVer[i] = byte(u)
}
@ -572,23 +573,23 @@ func (c *REALITYConfig) Build() (proto.Message, error) {
var u uint64
for i, s := range strings.Split(c.MaxClientVer, ".") {
if i == 3 {
return nil, newError(`invalid "maxClientVer": `, c.MaxClientVer)
return nil, errors.New(`invalid "maxClientVer": `, c.MaxClientVer)
}
if u, err = strconv.ParseUint(s, 10, 8); err != nil {
return nil, newError(`"maxClientVer[`, i, `]" should be lesser than 256`)
return nil, errors.New(`"maxClientVer[`, i, `]" should be lesser than 256`)
} else {
config.MaxClientVer[i] = byte(u)
}
}
}
if len(c.ShortIds) == 0 {
return nil, newError(`empty "shortIds"`)
return nil, errors.New(`empty "shortIds"`)
}
config.ShortIds = make([][]byte, len(c.ShortIds))
for i, s := range c.ShortIds {
config.ShortIds[i] = make([]byte, 8)
if _, err = hex.Decode(config.ShortIds[i], []byte(s)); err != nil {
return nil, newError(`invalid "shortIds[`, i, `]": `, s)
return nil, errors.New(`invalid "shortIds[`, i, `]": `, s)
}
}
config.Dest = s
@ -598,35 +599,35 @@ func (c *REALITYConfig) Build() (proto.Message, error) {
config.MaxTimeDiff = c.MaxTimeDiff
} else {
if c.Fingerprint == "" {
return nil, newError(`empty "fingerprint"`)
return nil, errors.New(`empty "fingerprint"`)
}
if config.Fingerprint = strings.ToLower(c.Fingerprint); tls.GetFingerprint(config.Fingerprint) == nil {
return nil, newError(`unknown "fingerprint": `, config.Fingerprint)
return nil, errors.New(`unknown "fingerprint": `, config.Fingerprint)
}
if config.Fingerprint == "hellogolang" {
return nil, newError(`invalid "fingerprint": `, config.Fingerprint)
return nil, errors.New(`invalid "fingerprint": `, config.Fingerprint)
}
if len(c.ServerNames) != 0 {
return nil, newError(`non-empty "serverNames", please use "serverName" instead`)
return nil, errors.New(`non-empty "serverNames", please use "serverName" instead`)
}
if c.PublicKey == "" {
return nil, newError(`empty "publicKey"`)
return nil, errors.New(`empty "publicKey"`)
}
if config.PublicKey, err = base64.RawURLEncoding.DecodeString(c.PublicKey); err != nil || len(config.PublicKey) != 32 {
return nil, newError(`invalid "publicKey": `, c.PublicKey)
return nil, errors.New(`invalid "publicKey": `, c.PublicKey)
}
if len(c.ShortIds) != 0 {
return nil, newError(`non-empty "shortIds", please use "shortId" instead`)
return nil, errors.New(`non-empty "shortIds", please use "shortId" instead`)
}
config.ShortId = make([]byte, 8)
if _, err = hex.Decode(config.ShortId, []byte(c.ShortId)); err != nil {
return nil, newError(`invalid "shortId": `, c.ShortId)
return nil, errors.New(`invalid "shortId": `, c.ShortId)
}
if c.SpiderX == "" {
c.SpiderX = "/"
}
if c.SpiderX[0] != '/' {
return nil, newError(`invalid "spiderX": `, c.SpiderX)
return nil, errors.New(`invalid "spiderX": `, c.SpiderX)
}
config.SpiderY = make([]int64, 10)
u, _ := url.Parse(c.SpiderX)
@ -680,7 +681,7 @@ func (p TransportProtocol) Build() (string, error) {
case "splithttp":
return "splithttp", nil
default:
return "", newError("Config: unknown transport protocol: ", p)
return "", errors.New("Config: unknown transport protocol: ", p)
}
}
@ -717,7 +718,7 @@ func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
case float64:
tfo = int32(math.Min(v, math.MaxInt32))
default:
return nil, newError("tcpFastOpen: only boolean and integer value is acceptable")
return nil, errors.New("tcpFastOpen: only boolean and integer value is acceptable")
}
}
var tproxy internet.SocketConfig_TProxyMode
@ -755,7 +756,7 @@ func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
case "forceipv6v4":
dStrategy = internet.DomainStrategy_FORCE_IP64
default:
return nil, newError("unsupported domain strategy: ", c.DomainStrategy)
return nil, errors.New("unsupported domain strategy: ", c.DomainStrategy)
}
return &internet.SocketConfig{
@ -817,34 +818,34 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
}
ts, err := tlsSettings.Build()
if err != nil {
return nil, newError("Failed to build TLS config.").Base(err)
return nil, errors.New("Failed to build TLS config.").Base(err)
}
tm := serial.ToTypedMessage(ts)
config.SecuritySettings = append(config.SecuritySettings, tm)
config.SecurityType = tm.Type
case "reality":
if config.ProtocolName != "tcp" && config.ProtocolName != "http" && config.ProtocolName != "grpc" && config.ProtocolName != "domainsocket" {
return nil, newError("REALITY only supports TCP, H2, gRPC and DomainSocket for now.")
return nil, errors.New("REALITY only supports TCP, H2, gRPC and DomainSocket for now.")
}
if c.REALITYSettings == nil {
return nil, newError(`REALITY: Empty "realitySettings".`)
return nil, errors.New(`REALITY: Empty "realitySettings".`)
}
ts, err := c.REALITYSettings.Build()
if err != nil {
return nil, newError("Failed to build REALITY config.").Base(err)
return nil, errors.New("Failed to build REALITY config.").Base(err)
}
tm := serial.ToTypedMessage(ts)
config.SecuritySettings = append(config.SecuritySettings, tm)
config.SecurityType = tm.Type
case "xtls":
return nil, newError(`Please use VLESS flow "xtls-rprx-vision" with TLS or REALITY.`)
return nil, errors.New(`Please use VLESS flow "xtls-rprx-vision" with TLS or REALITY.`)
default:
return nil, newError(`Unknown security "` + c.Security + `".`)
return nil, errors.New(`Unknown security "` + c.Security + `".`)
}
if c.TCPSettings != nil {
ts, err := c.TCPSettings.Build()
if err != nil {
return nil, newError("Failed to build TCP config.").Base(err)
return nil, errors.New("Failed to build TCP config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "tcp",
@ -854,7 +855,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
if c.KCPSettings != nil {
ts, err := c.KCPSettings.Build()
if err != nil {
return nil, newError("Failed to build mKCP config.").Base(err)
return nil, errors.New("Failed to build mKCP config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "mkcp",
@ -864,7 +865,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
if c.WSSettings != nil {
ts, err := c.WSSettings.Build()
if err != nil {
return nil, newError("Failed to build WebSocket config.").Base(err)
return nil, errors.New("Failed to build WebSocket config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "websocket",
@ -874,7 +875,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
if c.HTTPSettings != nil {
ts, err := c.HTTPSettings.Build()
if err != nil {
return nil, newError("Failed to build HTTP config.").Base(err)
return nil, errors.New("Failed to build HTTP config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "http",
@ -884,7 +885,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
if c.DSSettings != nil {
ds, err := c.DSSettings.Build()
if err != nil {
return nil, newError("Failed to build DomainSocket config.").Base(err)
return nil, errors.New("Failed to build DomainSocket config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "domainsocket",
@ -894,7 +895,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
if c.QUICSettings != nil {
qs, err := c.QUICSettings.Build()
if err != nil {
return nil, newError("Failed to build QUIC config").Base(err)
return nil, errors.New("Failed to build QUIC config").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "quic",
@ -907,7 +908,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
if c.GRPCConfig != nil {
gs, err := c.GRPCConfig.Build()
if err != nil {
return nil, newError("Failed to build gRPC config.").Base(err)
return nil, errors.New("Failed to build gRPC config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "grpc",
@ -917,7 +918,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
if c.HTTPUPGRADESettings != nil {
hs, err := c.HTTPUPGRADESettings.Build()
if err != nil {
return nil, newError("Failed to build HttpUpgrade config.").Base(err)
return nil, errors.New("Failed to build HttpUpgrade config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "httpupgrade",
@ -927,7 +928,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
if c.SplitHTTPSettings != nil {
hs, err := c.SplitHTTPSettings.Build()
if err != nil {
return nil, newError("Failed to build SplitHTTP config.").Base(err)
return nil, errors.New("Failed to build SplitHTTP config.").Base(err)
}
config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
ProtocolName: "splithttp",
@ -937,7 +938,7 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
if c.SocketSettings != nil {
ss, err := c.SocketSettings.Build()
if err != nil {
return nil, newError("Failed to build sockopt").Base(err)
return nil, errors.New("Failed to build sockopt").Base(err)
}
config.SocketSettings = ss
}
@ -954,7 +955,7 @@ type ProxyConfig struct {
// Build implements Buildable.
func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) {
if v.Tag == "" {
return nil, newError("Proxy tag is not set.")
return nil, errors.New("Proxy tag is not set.")
}
return &internet.ProxyConfig{
Tag: v.Tag,

View file

@ -8,6 +8,7 @@ import (
"strings"
"syscall"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
@ -33,7 +34,7 @@ type TrojanClientConfig struct {
// Build implements Buildable
func (c *TrojanClientConfig) Build() (proto.Message, error) {
if len(c.Servers) == 0 {
return nil, newError("0 Trojan server configured.")
return nil, errors.New("0 Trojan server configured.")
}
config := &trojan.ClientConfig{
@ -42,16 +43,16 @@ func (c *TrojanClientConfig) Build() (proto.Message, error) {
for idx, rec := range c.Servers {
if rec.Address == nil {
return nil, newError("Trojan server address is not set.")
return nil, errors.New("Trojan server address is not set.")
}
if rec.Port == 0 {
return nil, newError("Invalid Trojan port.")
return nil, errors.New("Invalid Trojan port.")
}
if rec.Password == "" {
return nil, newError("Trojan password is not specified.")
return nil, errors.New("Trojan password is not specified.")
}
if rec.Flow != "" {
return nil, newError(`Trojan doesn't support "flow" anymore.`)
return nil, errors.New(`Trojan doesn't support "flow" anymore.`)
}
config.Server[idx] = &protocol.ServerEndpoint{
@ -105,7 +106,7 @@ func (c *TrojanServerConfig) Build() (proto.Message, error) {
for idx, rawUser := range c.Clients {
if rawUser.Flow != "" {
return nil, newError(`Trojan doesn't support "flow" anymore.`)
return nil, errors.New(`Trojan doesn't support "flow" anymore.`)
}
config.Users[idx] = &protocol.User{
@ -118,7 +119,7 @@ func (c *TrojanServerConfig) Build() (proto.Message, error) {
}
if c.Fallback != nil {
return nil, newError(`Trojan settings: please use "fallbacks":[{}] instead of "fallback":{}`)
return nil, errors.New(`Trojan settings: please use "fallbacks":[{}] instead of "fallback":{}`)
}
for _, fb := range c.Fallbacks {
var i uint16
@ -140,11 +141,11 @@ func (c *TrojanServerConfig) Build() (proto.Message, error) {
for _, fb := range config.Fallbacks {
/*
if fb.Alpn == "h2" && fb.Path != "" {
return nil, newError(`Trojan fallbacks: "alpn":"h2" doesn't support "path"`)
return nil, errors.New(`Trojan fallbacks: "alpn":"h2" doesn't support "path"`)
}
*/
if fb.Path != "" && fb.Path[0] != '/' {
return nil, newError(`Trojan fallbacks: "path" must be empty or start with "/"`)
return nil, errors.New(`Trojan fallbacks: "path" must be empty or start with "/"`)
}
if fb.Type == "" && fb.Dest != "" {
if fb.Dest == "serve-ws-none" {
@ -166,10 +167,10 @@ func (c *TrojanServerConfig) Build() (proto.Message, error) {
}
}
if fb.Type == "" {
return nil, newError(`Trojan fallbacks: please fill in a valid value for every "dest"`)
return nil, errors.New(`Trojan fallbacks: please fill in a valid value for every "dest"`)
}
if fb.Xver > 2 {
return nil, newError(`Trojan fallbacks: invalid PROXY protocol version, "xver" only accepts 0, 1, 2`)
return nil, errors.New(`Trojan fallbacks: invalid PROXY protocol version, "xver" only accepts 0, 1, 2`)
}
}

View file

@ -8,6 +8,7 @@ import (
"strings"
"syscall"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
@ -41,11 +42,11 @@ func (c *VLessInboundConfig) Build() (proto.Message, error) {
for idx, rawUser := range c.Clients {
user := new(protocol.User)
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, newError(`VLESS clients: invalid user`).Base(err)
return nil, errors.New(`VLESS clients: invalid user`).Base(err)
}
account := new(vless.Account)
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, newError(`VLESS clients: invalid user`).Base(err)
return nil, errors.New(`VLESS clients: invalid user`).Base(err)
}
u, err := uuid.ParseString(account.Id)
@ -57,11 +58,11 @@ func (c *VLessInboundConfig) Build() (proto.Message, error) {
switch account.Flow {
case "", vless.XRV:
default:
return nil, newError(`VLESS clients: "flow" doesn't support "` + account.Flow + `" in this version`)
return nil, errors.New(`VLESS clients: "flow" doesn't support "` + account.Flow + `" in this version`)
}
if account.Encryption != "" {
return nil, newError(`VLESS clients: "encryption" should not in inbound settings`)
return nil, errors.New(`VLESS clients: "encryption" should not in inbound settings`)
}
user.Account = serial.ToTypedMessage(account)
@ -69,12 +70,12 @@ func (c *VLessInboundConfig) Build() (proto.Message, error) {
}
if c.Decryption != "none" {
return nil, newError(`VLESS settings: please add/set "decryption":"none" to every settings`)
return nil, errors.New(`VLESS settings: please add/set "decryption":"none" to every settings`)
}
config.Decryption = c.Decryption
if c.Fallback != nil {
return nil, newError(`VLESS settings: please use "fallbacks":[{}] instead of "fallback":{}`)
return nil, errors.New(`VLESS settings: please use "fallbacks":[{}] instead of "fallback":{}`)
}
for _, fb := range c.Fallbacks {
var i uint16
@ -96,11 +97,11 @@ func (c *VLessInboundConfig) Build() (proto.Message, error) {
for _, fb := range config.Fallbacks {
/*
if fb.Alpn == "h2" && fb.Path != "" {
return nil, newError(`VLESS fallbacks: "alpn":"h2" doesn't support "path"`)
return nil, errors.New(`VLESS fallbacks: "alpn":"h2" doesn't support "path"`)
}
*/
if fb.Path != "" && fb.Path[0] != '/' {
return nil, newError(`VLESS fallbacks: "path" must be empty or start with "/"`)
return nil, errors.New(`VLESS fallbacks: "path" must be empty or start with "/"`)
}
if fb.Type == "" && fb.Dest != "" {
if fb.Dest == "serve-ws-none" {
@ -122,10 +123,10 @@ func (c *VLessInboundConfig) Build() (proto.Message, error) {
}
}
if fb.Type == "" {
return nil, newError(`VLESS fallbacks: please fill in a valid value for every "dest"`)
return nil, errors.New(`VLESS fallbacks: please fill in a valid value for every "dest"`)
}
if fb.Xver > 2 {
return nil, newError(`VLESS fallbacks: invalid PROXY protocol version, "xver" only accepts 0, 1, 2`)
return nil, errors.New(`VLESS fallbacks: invalid PROXY protocol version, "xver" only accepts 0, 1, 2`)
}
}
@ -147,15 +148,15 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
config := new(outbound.Config)
if len(c.Vnext) == 0 {
return nil, newError(`VLESS settings: "vnext" is empty`)
return nil, errors.New(`VLESS settings: "vnext" is empty`)
}
config.Vnext = make([]*protocol.ServerEndpoint, len(c.Vnext))
for idx, rec := range c.Vnext {
if rec.Address == nil {
return nil, newError(`VLESS vnext: "address" is not set`)
return nil, errors.New(`VLESS vnext: "address" is not set`)
}
if len(rec.Users) == 0 {
return nil, newError(`VLESS vnext: "users" is empty`)
return nil, errors.New(`VLESS vnext: "users" is empty`)
}
spec := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
@ -165,11 +166,11 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
for idx, rawUser := range rec.Users {
user := new(protocol.User)
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, newError(`VLESS users: invalid user`).Base(err)
return nil, errors.New(`VLESS users: invalid user`).Base(err)
}
account := new(vless.Account)
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, newError(`VLESS users: invalid user`).Base(err)
return nil, errors.New(`VLESS users: invalid user`).Base(err)
}
u, err := uuid.ParseString(account.Id)
@ -181,11 +182,11 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
switch account.Flow {
case "", vless.XRV, vless.XRV + "-udp443":
default:
return nil, newError(`VLESS users: "flow" doesn't support "` + account.Flow + `" in this version`)
return nil, errors.New(`VLESS users: "flow" doesn't support "` + account.Flow + `" in this version`)
}
if account.Encryption != "none" {
return nil, newError(`VLESS users: please add/set "encryption":"none" for every user`)
return nil, errors.New(`VLESS users: please add/set "encryption":"none" for every user`)
}
user.Account = serial.ToTypedMessage(account)

View file

@ -4,6 +4,7 @@ import (
"encoding/json"
"strings"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/protocol"
"github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/uuid"
@ -96,11 +97,11 @@ func (c *VMessInboundConfig) Build() (proto.Message, error) {
for idx, rawData := range c.Users {
user := new(protocol.User)
if err := json.Unmarshal(rawData, user); err != nil {
return nil, newError("invalid VMess user").Base(err)
return nil, errors.New("invalid VMess user").Base(err)
}
account := new(VMessAccount)
if err := json.Unmarshal(rawData, account); err != nil {
return nil, newError("invalid VMess user").Base(err)
return nil, errors.New("invalid VMess user").Base(err)
}
u, err := uuid.ParseString(account.ID)
@ -131,15 +132,15 @@ func (c *VMessOutboundConfig) Build() (proto.Message, error) {
config := new(outbound.Config)
if len(c.Receivers) == 0 {
return nil, newError("0 VMess receiver configured")
return nil, errors.New("0 VMess receiver configured")
}
serverSpecs := make([]*protocol.ServerEndpoint, len(c.Receivers))
for idx, rec := range c.Receivers {
if len(rec.Users) == 0 {
return nil, newError("0 user configured for VMess outbound")
return nil, errors.New("0 user configured for VMess outbound")
}
if rec.Address == nil {
return nil, newError("address is not set in VMess outbound config")
return nil, errors.New("address is not set in VMess outbound config")
}
spec := &protocol.ServerEndpoint{
Address: rec.Address.Build(),
@ -148,11 +149,11 @@ func (c *VMessOutboundConfig) Build() (proto.Message, error) {
for _, rawUser := range rec.Users {
user := new(protocol.User)
if err := json.Unmarshal(rawUser, user); err != nil {
return nil, newError("invalid VMess user").Base(err)
return nil, errors.New("invalid VMess user").Base(err)
}
account := new(VMessAccount)
if err := json.Unmarshal(rawUser, account); err != nil {
return nil, newError("invalid VMess user").Base(err)
return nil, errors.New("invalid VMess user").Base(err)
}
u, err := uuid.ParseString(account.ID)

View file

@ -1,10 +1,12 @@
package conf
import (
"context"
"encoding/base64"
"encoding/hex"
"strings"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/proxy/wireguard"
"google.golang.org/protobuf/proto"
)
@ -97,7 +99,7 @@ func (c *WireGuardConfig) Build() (proto.Message, error) {
config.NumWorkers = c.NumWorkers
if len(c.Reserved) != 0 && len(c.Reserved) != 3 {
return nil, newError(`"reserved" should be empty or 3 bytes`)
return nil, errors.New(`"reserved" should be empty or 3 bytes`)
}
config.Reserved = c.Reserved
@ -113,19 +115,19 @@ func (c *WireGuardConfig) Build() (proto.Message, error) {
case "forceipv6v4":
config.DomainStrategy = wireguard.DeviceConfig_FORCE_IP64
default:
return nil, newError("unsupported domain strategy: ", c.DomainStrategy)
return nil, errors.New("unsupported domain strategy: ", c.DomainStrategy)
}
config.IsClient = c.IsClient
if c.KernelMode != nil {
config.KernelMode = *c.KernelMode
if config.KernelMode && !wireguard.KernelTunSupported() {
newError("kernel mode is not supported on your OS or permission is insufficient").AtWarning().WriteToLog()
errors.LogWarning(context.Background(), "kernel mode is not supported on your OS or permission is insufficient")
}
} else {
config.KernelMode = wireguard.KernelTunSupported()
if config.KernelMode {
newError("kernel mode is enabled as it's supported and permission is sufficient").AtDebug().WriteToLog()
errors.LogDebug(context.Background(), "kernel mode is enabled as it's supported and permission is sufficient")
}
}
@ -153,5 +155,5 @@ func ParseWireGuardKey(str string) (string, error) {
return hex.EncodeToString(dat), nil
}
return "", newError("failed to deserialize key").Base(err)
return "", errors.New("failed to deserialize key").Base(err)
}

View file

@ -1,6 +1,7 @@
package conf
import (
"context"
"encoding/json"
"fmt"
"log"
@ -11,6 +12,7 @@ import (
"github.com/xtls/xray-core/app/dispatcher"
"github.com/xtls/xray-core/app/proxyman"
"github.com/xtls/xray-core/app/stats"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/serial"
core "github.com/xtls/xray-core/core"
@ -55,7 +57,7 @@ func toProtocolList(s []string) ([]proxyman.KnownProtocols, error) {
case "https", "tls", "ssl":
kp = append(kp, proxyman.KnownProtocols_TLS)
default:
return nil, newError("Unknown protocol: ", p)
return nil, errors.New("Unknown protocol: ", p)
}
}
return kp, nil
@ -86,7 +88,7 @@ func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) {
case "fakedns+others":
p = append(p, "fakedns+others")
default:
return nil, newError("unknown protocol: ", protocol)
return nil, errors.New("unknown protocol: ", protocol)
}
}
}
@ -121,7 +123,7 @@ func (m *MuxConfig) Build() (*proxyman.MultiplexingConfig, error) {
m.XudpProxyUDP443 = "reject"
case "reject", "allow", "skip":
default:
return nil, newError(`unknown "xudpProxyUDP443": `, m.XudpProxyUDP443)
return nil, errors.New(`unknown "xudpProxyUDP443": `, m.XudpProxyUDP443)
}
return &proxyman.MultiplexingConfig{
Enabled: m.Enabled,
@ -148,7 +150,7 @@ func (c *InboundDetourAllocationConfig) Build() (*proxyman.AllocationStrategy, e
case "external":
config.Type = proxyman.AllocationStrategy_External
default:
return nil, newError("unknown allocation strategy: ", c.Strategy)
return nil, errors.New("unknown allocation strategy: ", c.Strategy)
}
if c.Concurrency != nil {
config.Concurrency = &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
@ -184,7 +186,7 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
if c.ListenOn == nil {
// Listen on anyip, must set PortList
if c.PortList == nil {
return nil, newError("Listen on AnyIP but no Port(s) set in InboundDetour.")
return nil, errors.New("Listen on AnyIP but no Port(s) set in InboundDetour.")
}
receiverSettings.PortList = c.PortList.Build()
} else {
@ -195,7 +197,7 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
if listenIP {
// Listen on specific IP, must set PortList
if c.PortList == nil {
return nil, newError("Listen on specific ip without port in InboundDetour.")
return nil, errors.New("Listen on specific ip without port in InboundDetour.")
}
// Listen on IP:Port
receiverSettings.PortList = c.PortList.Build()
@ -205,7 +207,7 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
receiverSettings.PortList = nil
}
} else {
return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain())
return nil, errors.New("unable to listen on domain address: ", c.ListenOn.Domain())
}
}
@ -224,7 +226,7 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
for _, pr := range c.PortList.Range {
fmt.Fprintf(&ports, "%d-%d ", pr.From, pr.To)
}
return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", ports.String())
return nil, errors.New("not enough ports. concurrency = ", concurrency, " ports: ", ports.String())
}
as, err := c.Allocation.Build()
@ -243,14 +245,14 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
if c.SniffingConfig != nil {
s, err := c.SniffingConfig.Build()
if err != nil {
return nil, newError("failed to build sniffing config").Base(err)
return nil, errors.New("failed to build sniffing config").Base(err)
}
receiverSettings.SniffingSettings = s
}
if c.DomainOverride != nil {
kp, err := toProtocolList(*c.DomainOverride)
if err != nil {
return nil, newError("failed to parse inbound detour config").Base(err)
return nil, errors.New("failed to parse inbound detour config").Base(err)
}
receiverSettings.DomainOverride = kp
}
@ -261,7 +263,7 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
}
rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
if err != nil {
return nil, newError("failed to load inbound detour config.").Base(err)
return nil, errors.New("failed to load inbound detour config.").Base(err)
}
if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
@ -293,7 +295,7 @@ func (c *OutboundDetourConfig) checkChainProxyConfig() error {
return nil
}
if len(c.ProxySettings.Tag) > 0 && len(c.StreamSetting.SocketSettings.DialerProxy) > 0 {
return newError("proxySettings.tag is conflicted with sockopt.dialerProxy").AtWarning()
return errors.New("proxySettings.tag is conflicted with sockopt.dialerProxy").AtWarning()
}
return nil
}
@ -312,7 +314,7 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
senderSettings.ViaCidr = strings.Split(*c.SendThrough, "/")[1]
} else {
if address.Family().IsDomain() {
return nil, newError("unable to send through: " + address.String())
return nil, errors.New("unable to send through: " + address.String())
}
}
senderSettings.Via = address.Build()
@ -329,7 +331,7 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
if c.ProxySettings != nil {
ps, err := c.ProxySettings.Build()
if err != nil {
return nil, newError("invalid outbound detour proxy settings.").Base(err)
return nil, errors.New("invalid outbound detour proxy settings.").Base(err)
}
if ps.TransportLayerProxy {
if senderSettings.StreamSettings != nil {
@ -349,7 +351,7 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
if c.MuxSettings != nil {
ms, err := c.MuxSettings.Build()
if err != nil {
return nil, newError("failed to build Mux config.").Base(err)
return nil, errors.New("failed to build Mux config.").Base(err)
}
senderSettings.MultiplexSettings = ms
}
@ -360,7 +362,7 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
}
rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
if err != nil {
return nil, newError("failed to parse to outbound detour config.").Base(err)
return nil, errors.New("failed to parse to outbound detour config.").Base(err)
}
ts, err := rawConfig.(Buildable).Build()
if err != nil {
@ -505,11 +507,11 @@ func (c *Config) Override(o *Config, fn string) {
for i := range o.InboundConfigs {
if idx := c.findInboundTag(o.InboundConfigs[i].Tag); idx > -1 {
c.InboundConfigs[idx] = o.InboundConfigs[i]
newError("[", fn, "] updated inbound with tag: ", o.InboundConfigs[i].Tag).AtInfo().WriteToLog()
errors.LogInfo(context.Background(), "[", fn, "] updated inbound with tag: ", o.InboundConfigs[i].Tag)
} else {
c.InboundConfigs = append(c.InboundConfigs, o.InboundConfigs[i])
newError("[", fn, "] appended inbound with tag: ", o.InboundConfigs[i].Tag).AtInfo().WriteToLog()
errors.LogInfo(context.Background(), "[", fn, "] appended inbound with tag: ", o.InboundConfigs[i].Tag)
}
}
@ -521,14 +523,14 @@ func (c *Config) Override(o *Config, fn string) {
for i := range o.OutboundConfigs {
if idx := c.findOutboundTag(o.OutboundConfigs[i].Tag); idx > -1 {
c.OutboundConfigs[idx] = o.OutboundConfigs[i]
newError("[", fn, "] updated outbound with tag: ", o.OutboundConfigs[i].Tag).AtInfo().WriteToLog()
errors.LogInfo(context.Background(), "[", fn, "] updated outbound with tag: ", o.OutboundConfigs[i].Tag)
} else {
if strings.Contains(strings.ToLower(fn), "tail") {
c.OutboundConfigs = append(c.OutboundConfigs, o.OutboundConfigs[i])
newError("[", fn, "] appended outbound with tag: ", o.OutboundConfigs[i].Tag).AtInfo().WriteToLog()
errors.LogInfo(context.Background(), "[", fn, "] appended outbound with tag: ", o.OutboundConfigs[i].Tag)
} else {
outboundPrepends = append(outboundPrepends, o.OutboundConfigs[i])
newError("[", fn, "] prepend outbound with tag: ", o.OutboundConfigs[i].Tag).AtInfo().WriteToLog()
errors.LogInfo(context.Background(), "[", fn, "] prepend outbound with tag: ", o.OutboundConfigs[i].Tag)
}
}
}
@ -619,7 +621,7 @@ func (c *Config) Build() (*core.Config, error) {
if c.DNSConfig != nil {
dnsApp, err := c.DNSConfig.Build()
if err != nil {
return nil, newError("failed to parse DNS config").Base(err)
return nil, errors.New("failed to parse DNS config").Base(err)
}
config.App = append(config.App, serial.ToTypedMessage(dnsApp))
}