From 079d0bd8a932e329c136ec4b962a068fa5def947 Mon Sep 17 00:00:00 2001 From: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Date: Sat, 29 Jun 2024 14:32:57 -0400 Subject: [PATCH] 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 --- app/commander/commander.go | 11 +- app/commander/errors.generated.go | 9 -- app/commander/outbound.go | 3 +- app/dispatcher/default.go | 25 ++-- app/dispatcher/errors.generated.go | 9 -- app/dispatcher/fakednssniffer.go | 9 +- app/dispatcher/sniffer.go | 3 +- app/dns/config.go | 7 +- app/dns/dns.go | 28 ++--- app/dns/dnscommon.go | 12 +- app/dns/errors.generated.go | 9 -- app/dns/fakedns/errors.generated.go | 9 -- app/dns/fakedns/fake.go | 17 +-- app/dns/hosts.go | 13 +- app/dns/nameserver.go | 22 ++-- app/dns/nameserver_doh.go | 25 ++-- app/dns/nameserver_fakedns.go | 7 +- app/dns/nameserver_local.go | 7 +- app/dns/nameserver_quic.go | 29 ++--- app/dns/nameserver_tcp.go | 27 ++-- app/dns/nameserver_udp.go | 22 ++-- app/log/command/command.go | 7 +- app/log/command/errors.generated.go | 9 -- app/log/errors.generated.go | 9 -- app/log/log.go | 9 +- app/log/log_creator.go | 5 +- app/metrics/errors.generated.go | 9 -- app/metrics/metrics.go | 5 +- app/metrics/outbound.go | 3 +- app/observatory/burst/burstobserver.go | 12 +- app/observatory/burst/errors.generated.go | 9 -- app/observatory/burst/healthping.go | 17 +-- app/observatory/errors.generated.go | 9 -- app/observatory/explainErrors.go | 6 +- app/observatory/observer.go | 25 ++-- app/policy/errors.generated.go | 9 -- app/proxyman/command/command.go | 19 +-- app/proxyman/command/errors.generated.go | 9 -- app/proxyman/inbound/always.go | 10 +- app/proxyman/inbound/dynamic.go | 11 +- app/proxyman/inbound/errors.generated.go | 9 -- app/proxyman/inbound/inbound.go | 21 ++-- app/proxyman/inbound/worker.go | 56 +++++---- app/proxyman/outbound/errors.generated.go | 9 -- app/proxyman/outbound/handler.go | 43 +++---- app/proxyman/outbound/outbound.go | 2 +- app/proxyman/outbound/uot.go | 5 +- app/reverse/bridge.go | 9 +- app/reverse/errors.generated.go | 9 -- app/reverse/portal.go | 25 ++-- app/router/balancing.go | 23 ++-- app/router/balancing_override.go | 4 +- app/router/command/command.go | 17 +-- app/router/command/errors.generated.go | 9 -- app/router/condition.go | 7 +- app/router/config.go | 14 ++- app/router/errors.generated.go | 9 -- app/router/router.go | 13 +- app/router/strategy_leastload.go | 7 +- app/router/strategy_leastping.go | 3 +- app/router/weight.go | 7 +- app/stats/channel.go | 3 +- app/stats/command/command.go | 5 +- app/stats/command/errors.generated.go | 9 -- app/stats/errors.generated.go | 9 -- app/stats/stats.go | 14 +-- common/buf/buffer.go | 5 +- common/buf/copy.go | 2 +- common/buf/copy_test.go | 4 +- common/buf/errors.generated.go | 9 -- common/buf/io.go | 6 +- common/buf/reader.go | 2 +- common/crypto/auth.go | 9 +- common/crypto/errors.generated.go | 9 -- common/ctx/context.go | 25 ++++ common/drain/drainer.go | 7 +- common/drain/errors.generated.go | 9 -- common/errors.generated.go | 9 -- common/errors/errorgen/main.go | 37 ------ common/errors/errors.go | 115 ++++++++++++------ common/errors/errors_test.go | 10 +- common/mux/client.go | 22 ++-- common/mux/errors.generated.go | 9 -- common/mux/frame.go | 11 +- common/mux/reader.go | 3 +- common/mux/server.go | 26 ++-- common/mux/session.go | 6 +- common/net/address.go | 5 +- common/net/errors.generated.go | 9 -- common/net/port.go | 6 +- common/ocsp/errors.generated.go | 9 -- common/ocsp/ocsp.go | 17 +-- common/platform/ctlcmd/ctlcmd.go | 10 +- common/platform/ctlcmd/errors.generated.go | 9 -- common/protocol/address.go | 11 +- common/protocol/dns/errors.generated.go | 9 -- common/protocol/dns/io.go | 3 +- common/protocol/errors.generated.go | 9 -- common/protocol/tls/cert/cert.go | 17 +-- common/protocol/tls/cert/cert_test.go | 3 +- common/protocol/tls/cert/errors.generated.go | 9 -- common/protocol/user.go | 6 +- common/retry/errors.generated.go | 9 -- common/retry/retry.go | 6 +- common/session/context.go | 37 ++---- common/session/session.go | 10 +- common/singbridge/handler.go | 3 +- common/singbridge/logger.go | 17 ++- common/type.go | 6 +- common/xudp/errors.generated.go | 9 -- common/xudp/xudp.go | 5 +- core/config.go | 15 +-- core/errors.generated.go | 9 -- core/functions.go | 5 +- core/xray.go | 21 ++-- features/dns/localdns/errors.generated.go | 9 -- features/errors.generated.go | 9 -- features/feature.go | 9 +- features/routing/dns/context.go | 5 +- features/routing/dns/errors.generated.go | 9 -- features/stats/errors.generated.go | 9 -- features/stats/stats.go | 5 +- infra/conf/api.go | 3 +- infra/conf/blackhole.go | 3 +- infra/conf/common.go | 19 +-- infra/conf/dns.go | 39 +++--- infra/conf/dns_proxy.go | 3 +- infra/conf/errors.generated.go | 9 -- infra/conf/fakedns.go | 8 +- infra/conf/freedom.go | 27 ++-- infra/conf/http.go | 5 +- infra/conf/lint.go | 4 +- infra/conf/loader.go | 8 +- infra/conf/metrics.go | 3 +- infra/conf/router.go | 69 +++++------ infra/conf/serial/builder.go | 10 +- infra/conf/serial/errors.generated.go | 9 -- infra/conf/serial/loader.go | 20 +-- infra/conf/shadowsocks.go | 37 +++--- infra/conf/socks.go | 11 +- infra/conf/transport.go | 19 +-- infra/conf/transport_authenticators.go | 5 +- infra/conf/transport_internet.go | 111 ++++++++--------- infra/conf/trojan.go | 23 ++-- infra/conf/vless.go | 35 +++--- infra/conf/vmess.go | 15 +-- infra/conf/wireguard.go | 12 +- infra/conf/xray.go | 46 +++---- main/commands/all/convert.go | 11 +- main/commands/all/errors.generated.go | 9 -- main/confloader/confloader.go | 7 +- main/confloader/errors.generated.go | 9 -- main/confloader/external/errors.generated.go | 9 -- main/confloader/external/external.go | 11 +- main/errors.generated.go | 9 -- main/json/errors.generated.go | 9 -- main/json/json.go | 10 +- main/run.go | 5 +- main/toml/errors.generated.go | 9 -- main/toml/toml.go | 10 +- main/yaml/errors.generated.go | 9 -- main/yaml/yaml.go | 10 +- proxy/blackhole/errors.generated.go | 9 -- proxy/dns/dns.go | 20 +-- proxy/dns/errors.generated.go | 9 -- proxy/dokodemo/dokodemo.go | 25 ++-- proxy/dokodemo/errors.generated.go | 9 -- proxy/errors.generated.go | 9 -- proxy/freedom/errors.generated.go | 9 -- proxy/freedom/freedom.go | 23 ++-- proxy/http/client.go | 29 ++--- proxy/http/errors.generated.go | 9 -- proxy/http/server.go | 24 ++-- proxy/loopback/errors.generated.go | 9 -- proxy/loopback/loopback.go | 15 +-- proxy/proxy.go | 42 +++---- proxy/shadowsocks/client.go | 27 ++-- proxy/shadowsocks/config.go | 9 +- proxy/shadowsocks/errors.generated.go | 9 -- proxy/shadowsocks/protocol.go | 57 ++++----- proxy/shadowsocks/server.go | 29 ++--- proxy/shadowsocks/validator.go | 9 +- proxy/shadowsocks_2022/errors.generated.go | 9 -- proxy/shadowsocks_2022/inbound.go | 11 +- proxy/shadowsocks_2022/inbound_multi.go | 23 ++-- proxy/shadowsocks_2022/inbound_relay.go | 13 +- proxy/shadowsocks_2022/outbound.go | 21 ++-- proxy/socks/client.go | 27 ++-- proxy/socks/errors.generated.go | 9 -- proxy/socks/protocol.go | 51 ++++---- proxy/socks/server.go | 31 ++--- proxy/trojan/client.go | 22 ++-- proxy/trojan/errors.generated.go | 9 -- proxy/trojan/protocol.go | 23 ++-- proxy/trojan/server.go | 72 ++++++----- proxy/trojan/validator.go | 7 +- proxy/vless/account.go | 3 +- proxy/vless/encoding/addons.go | 21 ++-- proxy/vless/encoding/encoding.go | 38 +++--- proxy/vless/encoding/errors.generated.go | 9 -- proxy/vless/errors.generated.go | 9 -- proxy/vless/inbound/errors.generated.go | 9 -- proxy/vless/inbound/inbound.go | 76 ++++++------ proxy/vless/outbound/errors.generated.go | 9 -- proxy/vless/outbound/outbound.go | 35 +++--- proxy/vless/validator.go | 7 +- proxy/vmess/account.go | 3 +- proxy/vmess/encoding/client.go | 27 ++-- proxy/vmess/encoding/commands.go | 11 +- proxy/vmess/encoding/errors.generated.go | 9 -- proxy/vmess/encoding/server.go | 35 +++--- proxy/vmess/errors.generated.go | 9 -- proxy/vmess/inbound/errors.generated.go | 9 -- proxy/vmess/inbound/inbound.go | 32 ++--- proxy/vmess/outbound/errors.generated.go | 9 -- proxy/vmess/outbound/outbound.go | 23 ++-- proxy/vmess/validator.go | 5 +- proxy/wireguard/bind.go | 2 +- proxy/wireguard/client.go | 23 ++-- proxy/wireguard/errors.generated.go | 9 -- proxy/wireguard/server.go | 17 +-- proxy/wireguard/tun.go | 6 +- proxy/wireguard/tun_linux.go | 2 +- proxy/wireguard/wireguard.go | 3 +- transport/internet/config.go | 5 +- transport/internet/dialer.go | 25 ++-- transport/internet/domainsocket/config.go | 3 +- transport/internet/domainsocket/dial.go | 3 +- .../internet/domainsocket/errors.generated.go | 9 -- transport/internet/domainsocket/listener.go | 15 +-- transport/internet/errors.generated.go | 9 -- transport/internet/filelocker_other.go | 10 +- transport/internet/grpc/dial.go | 18 +-- .../grpc/encoding/errors.generated.go | 9 -- transport/internet/grpc/encoding/hunkconn.go | 5 +- transport/internet/grpc/encoding/multiconn.go | 3 +- transport/internet/grpc/errors.generated.go | 9 -- transport/internet/grpc/hub.go | 12 +- transport/internet/header.go | 5 +- .../internet/headers/http/errors.generated.go | 9 -- transport/internet/headers/http/http.go | 5 +- transport/internet/http/dialer.go | 18 +-- transport/internet/http/errors.generated.go | 9 -- transport/internet/http/hub.go | 14 +-- transport/internet/httpupgrade/dialer.go | 16 +-- .../internet/httpupgrade/errors.generated.go | 9 -- transport/internet/httpupgrade/httpupgrade.go | 3 +- transport/internet/httpupgrade/hub.go | 20 +-- transport/internet/kcp/connection.go | 18 +-- transport/internet/kcp/crypt.go | 5 +- transport/internet/kcp/dialer.go | 9 +- transport/internet/kcp/errors.generated.go | 9 -- transport/internet/kcp/listener.go | 9 +- transport/internet/quic/config.go | 3 +- transport/internet/quic/dialer.go | 25 ++-- transport/internet/quic/errors.generated.go | 9 -- transport/internet/quic/hub.go | 9 +- transport/internet/reality/config.go | 4 +- .../internet/reality/errors.generated.go | 9 -- transport/internet/reality/reality.go | 19 ++- transport/internet/sockopt_darwin.go | 31 ++--- transport/internet/sockopt_freebsd.go | 39 +++--- transport/internet/sockopt_linux.go | 57 ++++----- transport/internet/sockopt_windows.go | 18 +-- transport/internet/splithttp/dialer.go | 24 ++-- .../internet/splithttp/errors.generated.go | 9 -- transport/internet/splithttp/hub.go | 26 ++-- transport/internet/splithttp/lazy_reader.go | 4 +- transport/internet/splithttp/splithttp.go | 3 +- transport/internet/splithttp/upload_queue.go | 6 +- transport/internet/system_dialer.go | 16 +-- transport/internet/system_listener.go | 12 +- .../tagged/taggedimpl/errors.generated.go | 9 -- transport/internet/tagged/taggedimpl/impl.go | 5 +- transport/internet/tcp/dialer.go | 8 +- transport/internet/tcp/errors.generated.go | 9 -- transport/internet/tcp/hub.go | 20 +-- transport/internet/tcp/sockopt_darwin.go | 5 +- transport/internet/tcp/sockopt_freebsd.go | 5 +- transport/internet/tcp/sockopt_linux.go | 12 +- transport/internet/tcp_hub.go | 17 +-- transport/internet/tls/config.go | 40 +++--- transport/internet/tls/config_other.go | 6 +- transport/internet/tls/errors.generated.go | 9 -- transport/internet/udp/dispatcher.go | 18 +-- transport/internet/udp/errors.generated.go | 9 -- transport/internet/udp/hub.go | 9 +- transport/internet/websocket/connection.go | 10 +- transport/internet/websocket/dialer.go | 20 +-- .../internet/websocket/errors.generated.go | 9 -- transport/internet/websocket/hub.go | 20 +-- 291 files changed, 1837 insertions(+), 2368 deletions(-) delete mode 100644 app/commander/errors.generated.go delete mode 100644 app/dispatcher/errors.generated.go delete mode 100644 app/dns/errors.generated.go delete mode 100644 app/dns/fakedns/errors.generated.go delete mode 100644 app/log/command/errors.generated.go delete mode 100644 app/log/errors.generated.go delete mode 100644 app/metrics/errors.generated.go delete mode 100644 app/observatory/burst/errors.generated.go delete mode 100644 app/observatory/errors.generated.go delete mode 100644 app/policy/errors.generated.go delete mode 100644 app/proxyman/command/errors.generated.go delete mode 100644 app/proxyman/inbound/errors.generated.go delete mode 100644 app/proxyman/outbound/errors.generated.go delete mode 100644 app/reverse/errors.generated.go delete mode 100644 app/router/command/errors.generated.go delete mode 100644 app/router/errors.generated.go delete mode 100644 app/stats/command/errors.generated.go delete mode 100644 app/stats/errors.generated.go delete mode 100644 common/buf/errors.generated.go delete mode 100644 common/crypto/errors.generated.go create mode 100644 common/ctx/context.go delete mode 100644 common/drain/errors.generated.go delete mode 100644 common/errors.generated.go delete mode 100644 common/errors/errorgen/main.go delete mode 100644 common/mux/errors.generated.go delete mode 100644 common/net/errors.generated.go delete mode 100644 common/ocsp/errors.generated.go delete mode 100644 common/platform/ctlcmd/errors.generated.go delete mode 100644 common/protocol/dns/errors.generated.go delete mode 100644 common/protocol/errors.generated.go delete mode 100644 common/protocol/tls/cert/errors.generated.go delete mode 100644 common/retry/errors.generated.go delete mode 100644 common/xudp/errors.generated.go delete mode 100644 core/errors.generated.go delete mode 100644 features/dns/localdns/errors.generated.go delete mode 100644 features/errors.generated.go delete mode 100644 features/routing/dns/errors.generated.go delete mode 100644 features/stats/errors.generated.go delete mode 100644 infra/conf/errors.generated.go delete mode 100644 infra/conf/serial/errors.generated.go delete mode 100644 main/commands/all/errors.generated.go delete mode 100644 main/confloader/errors.generated.go delete mode 100644 main/confloader/external/errors.generated.go delete mode 100644 main/errors.generated.go delete mode 100644 main/json/errors.generated.go delete mode 100644 main/toml/errors.generated.go delete mode 100644 main/yaml/errors.generated.go delete mode 100644 proxy/blackhole/errors.generated.go delete mode 100644 proxy/dns/errors.generated.go delete mode 100644 proxy/dokodemo/errors.generated.go delete mode 100644 proxy/errors.generated.go delete mode 100644 proxy/freedom/errors.generated.go delete mode 100644 proxy/http/errors.generated.go delete mode 100644 proxy/loopback/errors.generated.go delete mode 100644 proxy/shadowsocks/errors.generated.go delete mode 100644 proxy/shadowsocks_2022/errors.generated.go delete mode 100644 proxy/socks/errors.generated.go delete mode 100644 proxy/trojan/errors.generated.go delete mode 100644 proxy/vless/encoding/errors.generated.go delete mode 100644 proxy/vless/errors.generated.go delete mode 100644 proxy/vless/inbound/errors.generated.go delete mode 100644 proxy/vless/outbound/errors.generated.go delete mode 100644 proxy/vmess/encoding/errors.generated.go delete mode 100644 proxy/vmess/errors.generated.go delete mode 100644 proxy/vmess/inbound/errors.generated.go delete mode 100644 proxy/vmess/outbound/errors.generated.go delete mode 100644 proxy/wireguard/errors.generated.go delete mode 100644 transport/internet/domainsocket/errors.generated.go delete mode 100644 transport/internet/errors.generated.go delete mode 100644 transport/internet/grpc/encoding/errors.generated.go delete mode 100644 transport/internet/grpc/errors.generated.go delete mode 100644 transport/internet/headers/http/errors.generated.go delete mode 100644 transport/internet/http/errors.generated.go delete mode 100644 transport/internet/httpupgrade/errors.generated.go delete mode 100644 transport/internet/kcp/errors.generated.go delete mode 100644 transport/internet/quic/errors.generated.go delete mode 100644 transport/internet/reality/errors.generated.go delete mode 100644 transport/internet/splithttp/errors.generated.go delete mode 100644 transport/internet/tagged/taggedimpl/errors.generated.go delete mode 100644 transport/internet/tcp/errors.generated.go delete mode 100644 transport/internet/tls/errors.generated.go delete mode 100644 transport/internet/udp/errors.generated.go delete mode 100644 transport/internet/websocket/errors.generated.go diff --git a/app/commander/commander.go b/app/commander/commander.go index a893a4d5..c433454a 100644 --- a/app/commander/commander.go +++ b/app/commander/commander.go @@ -8,6 +8,7 @@ import ( "sync" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/signal/done" core "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/features/outbound" @@ -46,7 +47,7 @@ func NewCommander(ctx context.Context, config *Config) (*Commander, error) { } service, ok := rawService.(Service) if !ok { - return nil, newError("not a Service.") + return nil, errors.New("not a Service.") } c.services = append(c.services, service) } @@ -70,16 +71,16 @@ func (c *Commander) Start() error { var listen = func(listener net.Listener) { if err := c.server.Serve(listener); err != nil { - newError("failed to start grpc server").Base(err).AtError().WriteToLog() + errors.LogErrorInner(context.Background(), err, "failed to start grpc server") } } if len(c.listen) > 0 { if l, err := net.Listen("tcp", c.listen); err != nil { - newError("API server failed to listen on ", c.listen).Base(err).AtError().WriteToLog() + errors.LogErrorInner(context.Background(), err, "API server failed to listen on ", c.listen) return err } else { - newError("API server listening on ", l.Addr()).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "API server listening on ", l.Addr()) go listen(l) } return nil @@ -93,7 +94,7 @@ func (c *Commander) Start() error { go listen(listener) if err := c.ohm.RemoveHandler(context.Background(), c.tag); err != nil { - newError("failed to remove existing handler").WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to remove existing handler") } return c.ohm.AddHandler(context.Background(), &Outbound{ diff --git a/app/commander/errors.generated.go b/app/commander/errors.generated.go deleted file mode 100644 index c3cac329..00000000 --- a/app/commander/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package commander - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/commander/outbound.go b/app/commander/outbound.go index aa60bd1c..001423ff 100644 --- a/app/commander/outbound.go +++ b/app/commander/outbound.go @@ -5,6 +5,7 @@ import ( "sync" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/signal/done" @@ -31,7 +32,7 @@ func (l *OutboundListener) add(conn net.Conn) { func (l *OutboundListener) Accept() (net.Conn, error) { select { case <-l.done.Wait(): - return nil, newError("listen closed") + return nil, errors.New("listen closed") case c := <-l.buffer: return c, nil } diff --git a/app/dispatcher/default.go b/app/dispatcher/default.go index 4d65630d..34119ac2 100644 --- a/app/dispatcher/default.go +++ b/app/dispatcher/default.go @@ -10,6 +10,7 @@ import ( "time" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" @@ -26,7 +27,7 @@ import ( "github.com/xtls/xray-core/transport/pipe" ) -var errSniffingTimeout = newError("timeout on sniffing") +var errSniffingTimeout = errors.New("timeout on sniffing") type cachedReader struct { sync.Mutex @@ -191,7 +192,7 @@ func (d *DefaultDispatcher) shouldOverride(ctx context.Context, result SniffResu pattern := d[7:] re, err := regexp.Compile(pattern) if err != nil { - newError("Unable to compile regex").WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "Unable to compile regex") continue } if re.MatchString(domain) { @@ -213,7 +214,7 @@ func (d *DefaultDispatcher) shouldOverride(ctx context.Context, result SniffResu } if fkr0, ok := d.fdns.(dns.FakeDNSEngineRev0); ok && protocolString != "bittorrent" && p == "fakedns" && fkr0.IsIPInIPPool(destination.Address) { - newError("Using sniffer ", protocolString, " since the fake DNS missed").WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "Using sniffer ", protocolString, " since the fake DNS missed") return true } if resultSubset, ok := result.(SnifferIsProtoSubsetOf); ok { @@ -261,7 +262,7 @@ func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destin } if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) { domain := result.Domain() - newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "sniffed domain: ", domain) destination.Address = net.ParseAddress(domain) protocol := result.Protocol() if resComp, ok := result.(SnifferResultComposite); ok { @@ -286,7 +287,7 @@ func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destin // DispatchLink implements routing.Dispatcher. func (d *DefaultDispatcher) DispatchLink(ctx context.Context, destination net.Destination, outbound *transport.Link) error { if !destination.IsValid() { - return newError("Dispatcher: Invalid destination.") + return errors.New("Dispatcher: Invalid destination.") } outbounds := session.OutboundsFromContext(ctx) if len(outbounds) == 0 { @@ -315,7 +316,7 @@ func (d *DefaultDispatcher) DispatchLink(ctx context.Context, destination net.De } if err == nil && d.shouldOverride(ctx, result, sniffingRequest, destination) { domain := result.Domain() - newError("sniffed domain: ", domain).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "sniffed domain: ", domain) destination.Address = net.ParseAddress(domain) protocol := result.Protocol() if resComp, ok := result.(SnifferResultComposite); ok { @@ -407,10 +408,10 @@ func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport. ctx = session.SetForcedOutboundTagToContext(ctx, "") if h := d.ohm.GetHandler(forcedOutboundTag); h != nil { isPickRoute = 1 - newError("taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]") handler = h } else { - newError("non existing tag for platform initialized detour: ", forcedOutboundTag).AtError().WriteToLog(session.ExportIDToError(ctx)) + errors.LogError(ctx, "non existing tag for platform initialized detour: ", forcedOutboundTag) common.Close(link.Writer) common.Interrupt(link.Reader) return @@ -420,13 +421,13 @@ func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport. outTag := route.GetOutboundTag() if h := d.ohm.GetHandler(outTag); h != nil { isPickRoute = 2 - newError("taking detour [", outTag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "taking detour [", outTag, "] for [", destination, "]") handler = h } else { - newError("non existing outTag: ", outTag).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarning(ctx, "non existing outTag: ", outTag) } } else { - newError("default route for ", destination).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "default route for ", destination) } } @@ -435,7 +436,7 @@ func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport. } if handler == nil { - newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "default outbound handler not exist") common.Close(link.Writer) common.Interrupt(link.Reader) return diff --git a/app/dispatcher/errors.generated.go b/app/dispatcher/errors.generated.go deleted file mode 100644 index e13ee608..00000000 --- a/app/dispatcher/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package dispatcher - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/dispatcher/fakednssniffer.go b/app/dispatcher/fakednssniffer.go index 8d0804de..f7486d1d 100644 --- a/app/dispatcher/fakednssniffer.go +++ b/app/dispatcher/fakednssniffer.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/core" @@ -22,7 +23,7 @@ func newFakeDNSSniffer(ctx context.Context) (protocolSnifferWithMetadata, error) } if fakeDNSEngine == nil { - errNotInit := newError("FakeDNSEngine is not initialized, but such a sniffer is used").AtError() + errNotInit := errors.New("FakeDNSEngine is not initialized, but such a sniffer is used").AtError() return protocolSnifferWithMetadata{}, errNotInit } return protocolSnifferWithMetadata{protocolSniffer: func(ctx context.Context, bytes []byte) (SniffResult, error) { @@ -31,7 +32,7 @@ func newFakeDNSSniffer(ctx context.Context) (protocolSnifferWithMetadata, error) if ob.Target.Network == net.Network_TCP || ob.Target.Network == net.Network_UDP { domainFromFakeDNS := fakeDNSEngine.GetDomainFromFakeDNS(ob.Target.Address) if domainFromFakeDNS != "" { - newError("fake dns got domain: ", domainFromFakeDNS, " for ip: ", ob.Target.Address.String()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "fake dns got domain: ", domainFromFakeDNS, " for ip: ", ob.Target.Address.String()) return &fakeDNSSniffResult{domainName: domainFromFakeDNS}, nil } } @@ -109,10 +110,10 @@ func newFakeDNSThenOthers(ctx context.Context, fakeDNSSniffer protocolSnifferWit } return nil, common.ErrNoClue } - newError("ip address not in fake dns range, return as is").AtDebug().WriteToLog() + errors.LogDebug(ctx, "ip address not in fake dns range, return as is") return nil, common.ErrNoClue } - newError("fake dns sniffer did not set address in range option, assume false.").AtWarning().WriteToLog() + errors.LogWarning(ctx, "fake dns sniffer did not set address in range option, assume false.") return nil, common.ErrNoClue }, metadataSniffer: false, diff --git a/app/dispatcher/sniffer.go b/app/dispatcher/sniffer.go index e23277a7..4d62f1b3 100644 --- a/app/dispatcher/sniffer.go +++ b/app/dispatcher/sniffer.go @@ -4,6 +4,7 @@ import ( "context" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol/bittorrent" "github.com/xtls/xray-core/common/protocol/http" @@ -52,7 +53,7 @@ func NewSniffer(ctx context.Context) *Sniffer { return ret } -var errUnknownContent = newError("unknown content") +var errUnknownContent = errors.New("unknown content") func (s *Sniffer) Sniff(c context.Context, payload []byte, network net.Network) (SniffResult, error) { var pendingSniffer []protocolSnifferWithMetadata diff --git a/app/dns/config.go b/app/dns/config.go index 6236f7b5..ab547e14 100644 --- a/app/dns/config.go +++ b/app/dns/config.go @@ -1,6 +1,7 @@ package dns import ( + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/strmatcher" "github.com/xtls/xray-core/common/uuid" @@ -36,11 +37,11 @@ var localTLDsAndDotlessDomainsRule = &NameServer_OriginalRule{ func toStrMatcher(t DomainMatchingType, domain string) (strmatcher.Matcher, error) { strMType, f := typeMap[t] if !f { - return nil, newError("unknown mapping type", t).AtWarning() + return nil, errors.New("unknown mapping type", t).AtWarning() } matcher, err := strMType.New(domain) if err != nil { - return nil, newError("failed to create str matcher").Base(err) + return nil, errors.New("failed to create str matcher").Base(err) } return matcher, nil } @@ -51,7 +52,7 @@ func toNetIP(addrs []net.Address) ([]net.IP, error) { if addr.Family().IsIP() { ips = append(ips, addr.IP()) } else { - return nil, newError("Failed to convert address", addr, "to Net IP.").AtWarning() + return nil, errors.New("Failed to convert address", addr, "to Net IP.").AtWarning() } } return ips, nil diff --git a/app/dns/dns.go b/app/dns/dns.go index fbdf74ee..4abc8b33 100644 --- a/app/dns/dns.go +++ b/app/dns/dns.go @@ -54,7 +54,7 @@ func New(ctx context.Context, config *Config) (*DNS, error) { case 0, net.IPv4len, net.IPv6len: clientIP = net.IP(config.ClientIp) default: - return nil, newError("unexpected client IP length ", len(config.ClientIp)) + return nil, errors.New("unexpected client IP length ", len(config.ClientIp)) } var ipOption *dns.IPOption @@ -81,7 +81,7 @@ func New(ctx context.Context, config *Config) (*DNS, error) { hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts) if err != nil { - return nil, newError("failed to create hosts").Base(err) + return nil, errors.New("failed to create hosts").Base(err) } clients := []*Client{} @@ -99,7 +99,7 @@ func New(ctx context.Context, config *Config) (*DNS, error) { features.PrintDeprecatedFeatureWarning("simple DNS server") client, err := NewSimpleClient(ctx, endpoint, clientIP) if err != nil { - return nil, newError("failed to create client").Base(err) + return nil, errors.New("failed to create client").Base(err) } clients = append(clients, client) } @@ -122,7 +122,7 @@ func New(ctx context.Context, config *Config) (*DNS, error) { } client, err := NewClient(ctx, ns, myClientIP, geoipContainer, &matcherInfos, updateDomain) if err != nil { - return nil, newError("failed to create client").Base(err) + return nil, errors.New("failed to create client").Base(err) } clients = append(clients, client) } @@ -170,7 +170,7 @@ func (s *DNS) IsOwnLink(ctx context.Context) bool { // LookupIP implements dns.Client. func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) { if domain == "" { - return nil, newError("empty domain name") + return nil, errors.New("empty domain name") } option.IPv4Enable = option.IPv4Enable && s.ipOption.IPv4Enable @@ -190,10 +190,10 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) { case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled) return nil, dns.ErrEmptyResponse case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement - newError("domain replaced: ", domain, " -> ", addrs[0].Domain()).WriteToLog() + errors.LogInfo(s.ctx, "domain replaced: ", domain, " -> ", addrs[0].Domain()) domain = addrs[0].Domain() default: // Successfully found ip records in static host - newError("returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs).WriteToLog() + errors.LogInfo(s.ctx, "returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs) return toNetIP(addrs) } @@ -202,7 +202,7 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) { ctx := session.ContextWithInbound(s.ctx, &session.Inbound{Tag: s.tag}) for _, client := range s.sortClients(domain) { if !option.FakeEnable && strings.EqualFold(client.Name(), "FakeDNS") { - newError("skip DNS resolution for domain ", domain, " at server ", client.Name()).AtDebug().WriteToLog() + errors.LogDebug(s.ctx, "skip DNS resolution for domain ", domain, " at server ", client.Name()) continue } ips, err := client.QueryIP(ctx, domain, option, s.disableCache) @@ -210,7 +210,7 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) { return ips, nil } if err != nil { - newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog() + errors.LogInfoInner(s.ctx, err, "failed to lookup ip for domain ", domain, " at server ", client.Name()) errs = append(errs, err) } // 5 for RcodeRefused in miekg/dns, hardcode to reduce binary size @@ -219,7 +219,7 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) { } } - return nil, newError("returning nil for domain ", domain).Base(errors.Combine(errs...)) + return nil, errors.New("returning nil for domain ", domain).Base(errors.Combine(errs...)) } // LookupHosts implements dns.HostsLookup. @@ -231,7 +231,7 @@ func (s *DNS) LookupHosts(domain string) *net.Address { // Normalize the FQDN form query addrs := s.hosts.Lookup(domain, *s.ipOption) if len(addrs) > 0 { - newError("domain replaced: ", domain, " -> ", addrs[0].String()).AtInfo().WriteToLog() + errors.LogInfo(s.ctx, "domain replaced: ", domain, " -> ", addrs[0].String()) return &addrs[0] } @@ -289,16 +289,16 @@ func (s *DNS) sortClients(domain string) []*Client { } if len(domainRules) > 0 { - newError("domain ", domain, " matches following rules: ", domainRules).AtDebug().WriteToLog() + errors.LogDebug(s.ctx, "domain ", domain, " matches following rules: ", domainRules) } if len(clientNames) > 0 { - newError("domain ", domain, " will use DNS in order: ", clientNames).AtDebug().WriteToLog() + errors.LogDebug(s.ctx, "domain ", domain, " will use DNS in order: ", clientNames) } if len(clients) == 0 { clients = append(clients, s.clients[0]) clientNames = append(clientNames, s.clients[0].Name()) - newError("domain ", domain, " will use the first DNS: ", clientNames).AtDebug().WriteToLog() + errors.LogDebug(s.ctx, "domain ", domain, " will use the first DNS: ", clientNames) } return clients diff --git a/app/dns/dnscommon.go b/app/dns/dnscommon.go index df1b17af..42f9da2c 100644 --- a/app/dns/dnscommon.go +++ b/app/dns/dnscommon.go @@ -171,10 +171,10 @@ func parseResponse(payload []byte) (*IPRecord, error) { var parser dnsmessage.Parser h, err := parser.Start(payload) if err != nil { - return nil, newError("failed to parse DNS response").Base(err).AtWarning() + return nil, errors.New("failed to parse DNS response").Base(err).AtWarning() } if err := parser.SkipAllQuestions(); err != nil { - return nil, newError("failed to skip questions in DNS response").Base(err).AtWarning() + return nil, errors.New("failed to skip questions in DNS response").Base(err).AtWarning() } now := time.Now() @@ -189,7 +189,7 @@ L: ah, err := parser.AnswerHeader() if err != nil { if err != dnsmessage.ErrSectionDone { - newError("failed to parse answer section for domain: ", ah.Name.String()).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to parse answer section for domain: ", ah.Name.String()) } break } @@ -207,20 +207,20 @@ L: case dnsmessage.TypeA: ans, err := parser.AResource() if err != nil { - newError("failed to parse A record for domain: ", ah.Name).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to parse A record for domain: ", ah.Name) break L } ipRecord.IP = append(ipRecord.IP, net.IPAddress(ans.A[:])) case dnsmessage.TypeAAAA: ans, err := parser.AAAAResource() if err != nil { - newError("failed to parse AAAA record for domain: ", ah.Name).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to parse AAAA record for domain: ", ah.Name) break L } ipRecord.IP = append(ipRecord.IP, net.IPAddress(ans.AAAA[:])) default: if err := parser.SkipAnswer(); err != nil { - newError("failed to skip answer").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to skip answer") break L } continue diff --git a/app/dns/errors.generated.go b/app/dns/errors.generated.go deleted file mode 100644 index d7375a9b..00000000 --- a/app/dns/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package dns - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/dns/fakedns/errors.generated.go b/app/dns/fakedns/errors.generated.go deleted file mode 100644 index 84e0448c..00000000 --- a/app/dns/fakedns/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package fakedns - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/dns/fakedns/fake.go b/app/dns/fakedns/fake.go index e5550074..20e4bffa 100644 --- a/app/dns/fakedns/fake.go +++ b/app/dns/fakedns/fake.go @@ -10,6 +10,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/cache" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/features/dns" ) @@ -45,7 +46,7 @@ func (fkdns *Holder) Start() error { if fkdns.config != nil && fkdns.config.IpPool != "" && fkdns.config.LruSize != 0 { return fkdns.initializeFromConfig() } - return newError("invalid fakeDNS setting") + return errors.New("invalid fakeDNS setting") } func (fkdns *Holder) Close() error { @@ -60,7 +61,7 @@ func NewFakeDNSHolder() (*Holder, error) { var err error if fkdns, err = NewFakeDNSHolderConfigOnly(nil); err != nil { - return nil, newError("Unable to create Fake Dns Engine").Base(err).AtError() + return nil, errors.New("Unable to create Fake Dns Engine").Base(err).AtError() } err = fkdns.initialize(dns.FakeIPv4Pool, 65535) if err != nil { @@ -82,13 +83,13 @@ func (fkdns *Holder) initialize(ipPoolCidr string, lruSize int) error { var err error if _, ipRange, err = gonet.ParseCIDR(ipPoolCidr); err != nil { - return newError("Unable to parse CIDR for Fake DNS IP assignment").Base(err).AtError() + return errors.New("Unable to parse CIDR for Fake DNS IP assignment").Base(err).AtError() } ones, bits := ipRange.Mask.Size() rooms := bits - ones if math.Log2(float64(lruSize)) >= float64(rooms) { - return newError("LRU size is bigger than subnet size").AtError() + return errors.New("LRU size is bigger than subnet size").AtError() } fkdns.domainToIP = cache.NewLru(lruSize) fkdns.ipRange = ipRange @@ -137,7 +138,7 @@ func (fkdns *Holder) GetDomainFromFakeDNS(ip net.Address) string { if k, ok := fkdns.domainToIP.GetKeyFromValue(ip); ok { return k.(string) } - newError("A fake ip request to ", ip, ", however there is no matching domain name in fake DNS").AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "A fake ip request to ", ip, ", however there is no matching domain name in fake DNS") return "" } @@ -192,10 +193,10 @@ func (h *HolderMulti) Start() error { for _, v := range h.holders { if v.config != nil && v.config.IpPool != "" && v.config.LruSize != 0 { if err := v.Start(); err != nil { - return newError("Cannot start all fake dns pools").Base(err) + return errors.New("Cannot start all fake dns pools").Base(err) } } else { - return newError("invalid fakeDNS setting") + return errors.New("invalid fakeDNS setting") } } return nil @@ -204,7 +205,7 @@ func (h *HolderMulti) Start() error { func (h *HolderMulti) Close() error { for _, v := range h.holders { if err := v.Close(); err != nil { - return newError("Cannot close all fake dns pools").Base(err) + return errors.New("Cannot close all fake dns pools").Base(err) } } return nil diff --git a/app/dns/hosts.go b/app/dns/hosts.go index 64413481..a60d2514 100644 --- a/app/dns/hosts.go +++ b/app/dns/hosts.go @@ -1,7 +1,10 @@ package dns import ( + "context" + "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/strmatcher" "github.com/xtls/xray-core/features" @@ -32,7 +35,7 @@ func NewStaticHosts(hosts []*Config_HostMapping, legacy map[string]*net.IPOrDoma address := ip.AsAddress() if address.Family().IsDomain() { - return nil, newError("invalid domain address in static hosts: ", address.Domain()).AtWarning() + return nil, errors.New("invalid domain address in static hosts: ", address.Domain()).AtWarning() } sh.ips[id] = []net.Address{address} @@ -42,7 +45,7 @@ func NewStaticHosts(hosts []*Config_HostMapping, legacy map[string]*net.IPOrDoma for _, mapping := range hosts { matcher, err := toStrMatcher(mapping.Type, mapping.Domain) if err != nil { - return nil, newError("failed to create domain matcher").Base(err) + return nil, errors.New("failed to create domain matcher").Base(err) } id := g.Add(matcher) ips := make([]net.Address, 0, len(mapping.Ip)+1) @@ -53,12 +56,12 @@ func NewStaticHosts(hosts []*Config_HostMapping, legacy map[string]*net.IPOrDoma for _, ip := range mapping.Ip { addr := net.IPAddress(ip) if addr == nil { - return nil, newError("invalid IP address in static hosts: ", ip).AtWarning() + return nil, errors.New("invalid IP address in static hosts: ", ip).AtWarning() } ips = append(ips, addr) } default: - return nil, newError("neither IP address nor proxied domain specified for domain: ", mapping.Domain).AtWarning() + return nil, errors.New("neither IP address nor proxied domain specified for domain: ", mapping.Domain).AtWarning() } sh.ips[id] = ips @@ -90,7 +93,7 @@ func (h *StaticHosts) lookup(domain string, option dns.IPOption, maxDepth int) [ case len(addrs) == 0: // Not recorded in static hosts, return nil return nil case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Try to unwrap domain - newError("found replaced domain: ", domain, " -> ", addrs[0].Domain(), ". Try to unwrap it").AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "found replaced domain: ", domain, " -> ", addrs[0].Domain(), ". Try to unwrap it") if maxDepth > 0 { unwrapped := h.lookup(addrs[0].Domain(), option, maxDepth-1) if unwrapped != nil { diff --git a/app/dns/nameserver.go b/app/dns/nameserver.go index d5423b84..52ab7a91 100644 --- a/app/dns/nameserver.go +++ b/app/dns/nameserver.go @@ -64,7 +64,7 @@ func NewServer(dest net.Destination, dispatcher routing.Dispatcher, queryStrateg if dest.Network == net.Network_UDP { // UDP classic DNS mode return NewClassicNameServer(dest, dispatcher), nil } - return nil, newError("No available name server could be created from ", dest).AtWarning() + return nil, errors.New("No available name server could be created from ", dest).AtWarning() } // NewClient creates a DNS client managing a name server with client IP, domain rules and expected IPs. @@ -82,7 +82,7 @@ func NewClient( // Create a new server for each client for now server, err := NewServer(ns.Address.AsDestination(), dispatcher, ns.GetQueryStrategy()) if err != nil { - return newError("failed to create nameserver").Base(err).AtWarning() + return errors.New("failed to create nameserver").Base(err).AtWarning() } // Priotize local domains with specific TLDs or without any dot to local DNS @@ -111,7 +111,7 @@ func NewClient( for _, domain := range ns.PrioritizedDomain { domainRule, err := toStrMatcher(domain.Type, domain.Domain) if err != nil { - return newError("failed to create prioritized domain").Base(err).AtWarning() + return errors.New("failed to create prioritized domain").Base(err).AtWarning() } originalRuleIdx := ruleCurr if ruleCurr < len(ns.OriginalRules) { @@ -130,7 +130,7 @@ func NewClient( } err = updateDomainRule(domainRule, originalRuleIdx, *matcherInfos) if err != nil { - return newError("failed to create prioritized domain").Base(err).AtWarning() + return errors.New("failed to create prioritized domain").Base(err).AtWarning() } } @@ -139,7 +139,7 @@ func NewClient( for _, geoip := range ns.Geoip { matcher, err := container.Add(geoip) if err != nil { - return newError("failed to create ip matcher").Base(err).AtWarning() + return errors.New("failed to create ip matcher").Base(err).AtWarning() } matchers = append(matchers, matcher) } @@ -147,9 +147,9 @@ func NewClient( if len(clientIP) > 0 { switch ns.Address.Address.GetAddress().(type) { case *net.IPOrDomain_Domain: - newError("DNS: client ", ns.Address.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog() + errors.LogInfo(ctx, "DNS: client ", ns.Address.Address.GetDomain(), " uses clientIP ", clientIP.String()) case *net.IPOrDomain_Ip: - newError("DNS: client ", ns.Address.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog() + errors.LogInfo(ctx, "DNS: client ", ns.Address.Address.GetIp(), " uses clientIP ", clientIP.String()) } } @@ -169,7 +169,7 @@ func NewSimpleClient(ctx context.Context, endpoint *net.Endpoint, clientIP net.I err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error { server, err := NewServer(endpoint.AsDestination(), dispatcher, QueryStrategy_USE_IP) if err != nil { - return newError("failed to create nameserver").Base(err).AtWarning() + return errors.New("failed to create nameserver").Base(err).AtWarning() } client.server = server client.clientIP = clientIP @@ -179,9 +179,9 @@ func NewSimpleClient(ctx context.Context, endpoint *net.Endpoint, clientIP net.I if len(clientIP) > 0 { switch endpoint.Address.GetAddress().(type) { case *net.IPOrDomain_Domain: - newError("DNS: client ", endpoint.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog() + errors.LogInfo(ctx, "DNS: client ", endpoint.Address.GetDomain(), " uses clientIP ", clientIP.String()) case *net.IPOrDomain_Ip: - newError("DNS: client ", endpoint.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog() + errors.LogInfo(ctx, "DNS: client ", endpoint.Address.GetIp(), " uses clientIP ", clientIP.String()) } } @@ -222,7 +222,7 @@ func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error) if len(newIps) == 0 { return nil, errExpectedIPNonMatch } - newError("domain ", domain, " expectIPs ", newIps, " matched at server ", c.Name()).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "domain ", domain, " expectIPs ", newIps, " matched at server ", c.Name()) return newIps, nil } diff --git a/app/dns/nameserver_doh.go b/app/dns/nameserver_doh.go index 8657e3fb..01e7ede1 100644 --- a/app/dns/nameserver_doh.go +++ b/app/dns/nameserver_doh.go @@ -12,6 +12,7 @@ import ( "time" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" @@ -43,7 +44,7 @@ type DoHNameServer struct { // NewDoHNameServer creates DOH server object for remote resolving. func NewDoHNameServer(url *url.URL, dispatcher routing.Dispatcher, queryStrategy QueryStrategy) (*DoHNameServer, error) { - newError("DNS: created Remote DOH client for ", url.String()).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "DNS: created Remote DOH client for ", url.String()) s := baseDOHNameServer(url, "DOH", queryStrategy) s.dispatcher = dispatcher @@ -119,7 +120,7 @@ func NewDoHLocalNameServer(url *url.URL, queryStrategy QueryStrategy) *DoHNameSe Timeout: time.Second * 180, Transport: tr, } - newError("DNS: created Local DOH client for ", url.String()).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "DNS: created Local DOH client for ", url.String()) return s } @@ -150,7 +151,7 @@ func (s *DoHNameServer) Cleanup() error { defer s.Unlock() if len(s.ips) == 0 { - return newError("nothing to do. stopping...") + return errors.New("nothing to do. stopping...") } for domain, record := range s.ips { @@ -162,7 +163,7 @@ func (s *DoHNameServer) Cleanup() error { } if record.A == nil && record.AAAA == nil { - newError(s.name, " cleanup ", domain).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), s.name, " cleanup ", domain) delete(s.ips, domain) } else { s.ips[domain] = record @@ -205,7 +206,7 @@ func (s *DoHNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) { updated = true } } - newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed) if updated { s.ips[req.domain] = rec @@ -225,10 +226,10 @@ func (s *DoHNameServer) newReqID() uint16 { } func (s *DoHNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { - newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, s.name, " querying: ", domain) if s.name+"." == "DOH//"+domain { - newError(s.name, " tries to resolve itself! Use IP or set \"hosts\" instead.").AtError().WriteToLog(session.ExportIDToError(ctx)) + errors.LogError(ctx, s.name, " tries to resolve itself! Use IP or set \"hosts\" instead.") return } @@ -266,17 +267,17 @@ func (s *DoHNameServer) sendQuery(ctx context.Context, domain string, clientIP n b, err := dns.PackMessage(r.msg) if err != nil { - newError("failed to pack dns query for ", domain).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to pack dns query for ", domain) return } resp, err := s.dohHTTPSContext(dnsCtx, b.Bytes()) if err != nil { - newError("failed to retrieve response for ", domain).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to retrieve response for ", domain) return } rec, err := parseResponse(resp) if err != nil { - newError("failed to handle DOH response for ", domain).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to handle DOH response for ", domain) return } s.updateIP(r, rec) @@ -361,11 +362,11 @@ func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, clientIP net } if disableCache { - newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog() + errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name) } else { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { - newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog() + errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err}) return ips, err } diff --git a/app/dns/nameserver_fakedns.go b/app/dns/nameserver_fakedns.go index 44dcb01c..531417da 100644 --- a/app/dns/nameserver_fakedns.go +++ b/app/dns/nameserver_fakedns.go @@ -3,6 +3,7 @@ package dns import ( "context" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/features/dns" @@ -25,7 +26,7 @@ func (f *FakeDNSServer) QueryIP(ctx context.Context, domain string, _ net.IP, op if err := core.RequireFeatures(ctx, func(fd dns.FakeDNSEngine) { f.fakeDNSEngine = fd }); err != nil { - return nil, newError("Unable to locate a fake DNS Engine").Base(err).AtError() + return nil, errors.New("Unable to locate a fake DNS Engine").Base(err).AtError() } } var ips []net.Address @@ -37,10 +38,10 @@ func (f *FakeDNSServer) QueryIP(ctx context.Context, domain string, _ net.IP, op netIP, err := toNetIP(ips) if err != nil { - return nil, newError("Unable to convert IP to net ip").Base(err).AtError() + return nil, errors.New("Unable to convert IP to net ip").Base(err).AtError() } - newError(f.Name(), " got answer: ", domain, " -> ", ips).AtInfo().WriteToLog() + errors.LogInfo(ctx, f.Name(), " got answer: ", domain, " -> ", ips) if len(netIP) > 0 { return netIP, nil diff --git a/app/dns/nameserver_local.go b/app/dns/nameserver_local.go index bf741c23..f204981f 100644 --- a/app/dns/nameserver_local.go +++ b/app/dns/nameserver_local.go @@ -5,6 +5,7 @@ import ( "strings" "time" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/features/dns" @@ -19,7 +20,7 @@ type LocalNameServer struct { const errEmptyResponse = "No address associated with hostname" // QueryIP implements Server. -func (s *LocalNameServer) QueryIP(_ context.Context, domain string, _ net.IP, option dns.IPOption, _ bool) (ips []net.IP, err error) { +func (s *LocalNameServer) QueryIP(ctx context.Context, domain string, _ net.IP, option dns.IPOption, _ bool) (ips []net.IP, err error) { start := time.Now() ips, err = s.client.LookupIP(domain, option) @@ -28,7 +29,7 @@ func (s *LocalNameServer) QueryIP(_ context.Context, domain string, _ net.IP, op } if len(ips) > 0 { - newError("Localhost got answer: ", domain, " -> ", ips).AtInfo().WriteToLog() + errors.LogInfo(ctx, "Localhost got answer: ", domain, " -> ", ips) log.Record(&log.DNSLog{Server: s.Name(), Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err}) } @@ -42,7 +43,7 @@ func (s *LocalNameServer) Name() string { // NewLocalNameServer creates localdns server object for directly lookup in system DNS. func NewLocalNameServer() *LocalNameServer { - newError("DNS: created localhost client").AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "DNS: created localhost client") return &LocalNameServer{ client: localdns.New(), } diff --git a/app/dns/nameserver_quic.go b/app/dns/nameserver_quic.go index 817402f9..2d56f43e 100644 --- a/app/dns/nameserver_quic.go +++ b/app/dns/nameserver_quic.go @@ -12,6 +12,7 @@ import ( "github.com/quic-go/quic-go" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol/dns" @@ -45,7 +46,7 @@ type QUICNameServer struct { // NewQUICNameServer creates DNS-over-QUIC client object for local resolving func NewQUICNameServer(url *url.URL, queryStrategy QueryStrategy) (*QUICNameServer, error) { - newError("DNS: created Local DNS-over-QUIC client for ", url.String()).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "DNS: created Local DNS-over-QUIC client for ", url.String()) var err error port := net.Port(853) @@ -84,7 +85,7 @@ func (s *QUICNameServer) Cleanup() error { defer s.Unlock() if len(s.ips) == 0 { - return newError("nothing to do. stopping...") + return errors.New("nothing to do. stopping...") } for domain, record := range s.ips { @@ -96,7 +97,7 @@ func (s *QUICNameServer) Cleanup() error { } if record.A == nil && record.AAAA == nil { - newError(s.name, " cleanup ", domain).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), s.name, " cleanup ", domain) delete(s.ips, domain) } else { s.ips[domain] = record @@ -139,7 +140,7 @@ func (s *QUICNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) { updated = true } } - newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed) if updated { s.ips[req.domain] = rec @@ -159,7 +160,7 @@ func (s *QUICNameServer) newReqID() uint16 { } func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { - newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, s.name, " querying: ", domain) reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) @@ -192,7 +193,7 @@ func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP b, err := dns.PackMessage(r.msg) if err != nil { - newError("failed to pack dns query").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to pack dns query") return } @@ -203,13 +204,13 @@ func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP conn, err := s.openStream(dnsCtx) if err != nil { - newError("failed to open quic connection").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to open quic connection") return } _, err = conn.Write(dnsReqBuf.Bytes()) if err != nil { - newError("failed to send query").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to send query") return } @@ -219,25 +220,25 @@ func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP defer respBuf.Release() n, err := respBuf.ReadFullFrom(conn, 2) if err != nil && n == 0 { - newError("failed to read response length").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to read response length") return } var length int16 err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length) if err != nil { - newError("failed to parse response length").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to parse response length") return } respBuf.Clear() n, err = respBuf.ReadFullFrom(conn, int32(length)) if err != nil && n == 0 { - newError("failed to read response length").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to read response length") return } rec, err := parseResponse(respBuf.Bytes()) if err != nil { - newError("failed to handle response").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to handle response") return } s.updateIP(r, rec) @@ -296,11 +297,11 @@ func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP ne } if disableCache { - newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog() + errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name) } else { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { - newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog() + errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err}) return ips, err } diff --git a/app/dns/nameserver_tcp.go b/app/dns/nameserver_tcp.go index 4ed723e1..bc5bab44 100644 --- a/app/dns/nameserver_tcp.go +++ b/app/dns/nameserver_tcp.go @@ -11,6 +11,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" @@ -114,7 +115,7 @@ func (s *TCPNameServer) Cleanup() error { defer s.Unlock() if len(s.ips) == 0 { - return newError("nothing to do. stopping...") + return errors.New("nothing to do. stopping...") } for domain, record := range s.ips { @@ -126,7 +127,7 @@ func (s *TCPNameServer) Cleanup() error { } if record.A == nil && record.AAAA == nil { - newError(s.name, " cleanup ", domain).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), s.name, " cleanup ", domain) delete(s.ips, domain) } else { s.ips[domain] = record @@ -169,7 +170,7 @@ func (s *TCPNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) { updated = true } } - newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed) if updated { s.ips[req.domain] = rec @@ -189,7 +190,7 @@ func (s *TCPNameServer) newReqID() uint16 { } func (s *TCPNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { - newError(s.name, " querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, s.name, " querying DNS for: ", domain) reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) @@ -219,13 +220,13 @@ func (s *TCPNameServer) sendQuery(ctx context.Context, domain string, clientIP n b, err := dns.PackMessage(r.msg) if err != nil { - newError("failed to pack dns query").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to pack dns query") return } conn, err := s.dial(dnsCtx) if err != nil { - newError("failed to dial namesever").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to dial namesever") return } defer conn.Close() @@ -236,7 +237,7 @@ func (s *TCPNameServer) sendQuery(ctx context.Context, domain string, clientIP n _, err = conn.Write(dnsReqBuf.Bytes()) if err != nil { - newError("failed to send query").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to send query") return } dnsReqBuf.Release() @@ -245,25 +246,25 @@ func (s *TCPNameServer) sendQuery(ctx context.Context, domain string, clientIP n defer respBuf.Release() n, err := respBuf.ReadFullFrom(conn, 2) if err != nil && n == 0 { - newError("failed to read response length").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to read response length") return } var length int16 err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length) if err != nil { - newError("failed to parse response length").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to parse response length") return } respBuf.Clear() n, err = respBuf.ReadFullFrom(conn, int32(length)) if err != nil && n == 0 { - newError("failed to read response length").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to read response length") return } rec, err := parseResponse(respBuf.Bytes()) if err != nil { - newError("failed to parse DNS over TCP response").Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to parse DNS over TCP response") return } @@ -319,11 +320,11 @@ func (s *TCPNameServer) QueryIP(ctx context.Context, domain string, clientIP net } if disableCache { - newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog() + errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name) } else { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { - newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog() + errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err}) return ips, err } diff --git a/app/dns/nameserver_udp.go b/app/dns/nameserver_udp.go index d511df5b..67e1d73a 100644 --- a/app/dns/nameserver_udp.go +++ b/app/dns/nameserver_udp.go @@ -8,11 +8,11 @@ import ( "time" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol/dns" udp_proto "github.com/xtls/xray-core/common/protocol/udp" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/signal/pubsub" "github.com/xtls/xray-core/common/task" dns_feature "github.com/xtls/xray-core/features/dns" @@ -53,7 +53,7 @@ func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher Execute: s.Cleanup, } s.udpServer = udp.NewDispatcher(dispatcher, s.HandleResponse) - newError("DNS: created UDP client initialized for ", address.NetAddr()).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "DNS: created UDP client initialized for ", address.NetAddr()) return s } @@ -69,7 +69,7 @@ func (s *ClassicNameServer) Cleanup() error { defer s.Unlock() if len(s.ips) == 0 && len(s.requests) == 0 { - return newError(s.name, " nothing to do. stopping...") + return errors.New(s.name, " nothing to do. stopping...") } for domain, record := range s.ips { @@ -81,7 +81,7 @@ func (s *ClassicNameServer) Cleanup() error { } if record.A == nil && record.AAAA == nil { - newError(s.name, " cleanup ", domain).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), s.name, " cleanup ", domain) delete(s.ips, domain) } else { s.ips[domain] = record @@ -109,7 +109,7 @@ func (s *ClassicNameServer) Cleanup() error { func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_proto.Packet) { ipRec, err := parseResponse(packet.Payload.Bytes()) if err != nil { - newError(s.name, " fail to parse responded DNS udp").AtError().WriteToLog() + errors.LogError(ctx, s.name, " fail to parse responded DNS udp") return } @@ -122,7 +122,7 @@ func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_prot } s.Unlock() if !ok { - newError(s.name, " cannot find the pending request").AtError().WriteToLog() + errors.LogError(ctx, s.name, " cannot find the pending request") return } @@ -135,7 +135,7 @@ func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_prot } elapsed := time.Since(req.start) - newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog() + errors.LogInfo(ctx, s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed) if len(req.domain) > 0 && (rec.A != nil || rec.AAAA != nil) { s.updateIP(req.domain, &rec) } @@ -160,7 +160,7 @@ func (s *ClassicNameServer) updateIP(domain string, newRec *record) { } if updated { - newError(s.name, " updating IP records for domain:", domain).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), s.name, " updating IP records for domain:", domain) s.ips[domain] = rec } if newRec.A != nil { @@ -187,7 +187,7 @@ func (s *ClassicNameServer) addPendingRequest(req *dnsRequest) { } func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { - newError(s.name, " querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, s.name, " querying DNS for: ", domain) reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) @@ -241,11 +241,11 @@ func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, clientIP fqdn := Fqdn(domain) if disableCache { - newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog() + errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name) } else { ips, err := s.findIPsForDomain(fqdn, option) if err != errRecordNotFound { - newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog() + errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err}) return ips, err } diff --git a/app/log/command/command.go b/app/log/command/command.go index 74a02d77..74ce2d5b 100644 --- a/app/log/command/command.go +++ b/app/log/command/command.go @@ -7,6 +7,7 @@ import ( "github.com/xtls/xray-core/app/log" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/core" grpc "google.golang.org/grpc" ) @@ -19,13 +20,13 @@ type LoggerServer struct { func (s *LoggerServer) RestartLogger(ctx context.Context, request *RestartLoggerRequest) (*RestartLoggerResponse, error) { logger := s.V.GetFeature((*log.Instance)(nil)) if logger == nil { - return nil, newError("unable to get logger instance") + return nil, errors.New("unable to get logger instance") } if err := logger.Close(); err != nil { - return nil, newError("failed to close logger").Base(err) + return nil, errors.New("failed to close logger").Base(err) } if err := logger.Start(); err != nil { - return nil, newError("failed to start logger").Base(err) + return nil, errors.New("failed to start logger").Base(err) } return &RestartLoggerResponse{}, nil } diff --git a/app/log/command/errors.generated.go b/app/log/command/errors.generated.go deleted file mode 100644 index a1305932..00000000 --- a/app/log/command/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package command - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/log/errors.generated.go b/app/log/errors.generated.go deleted file mode 100644 index e09634a9..00000000 --- a/app/log/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package log - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/log/log.go b/app/log/log.go index 7cdd5390..88bac44f 100644 --- a/app/log/log.go +++ b/app/log/log.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" ) @@ -35,7 +36,7 @@ func New(ctx context.Context, config *Config) (*Instance, error) { return nil, err } - newError("Logger started").AtDebug().WriteToLog() + errors.LogDebug(ctx, "Logger started") return g, nil } @@ -77,10 +78,10 @@ func (g *Instance) startInternal() error { g.active = true if err := g.initAccessLogger(); err != nil { - return newError("failed to initialize access logger").Base(err).AtWarning() + return errors.New("failed to initialize access logger").Base(err).AtWarning() } if err := g.initErrorLogger(); err != nil { - return newError("failed to initialize error logger").Base(err).AtWarning() + return errors.New("failed to initialize error logger").Base(err).AtWarning() } return nil @@ -120,7 +121,7 @@ func (g *Instance) Handle(msg log.Message) { // Close implements common.Closable.Close(). func (g *Instance) Close() error { - newError("Logger closing").AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "Logger closing") g.Lock() defer g.Unlock() diff --git a/app/log/log_creator.go b/app/log/log_creator.go index 9db8e1c7..48287271 100644 --- a/app/log/log_creator.go +++ b/app/log/log_creator.go @@ -4,6 +4,7 @@ import ( "sync" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" ) @@ -19,7 +20,7 @@ var handlerCreatorMapLock = &sync.RWMutex{} func RegisterHandlerCreator(logType LogType, f HandlerCreator) error { if f == nil { - return newError("nil HandlerCreator") + return errors.New("nil HandlerCreator") } handlerCreatorMapLock.Lock() @@ -35,7 +36,7 @@ func createHandler(logType LogType, options HandlerCreatorOptions) (log.Handler, creator, found := handlerCreatorMap[logType] if !found { - return nil, newError("unable to create log handler for ", logType) + return nil, errors.New("unable to create log handler for ", logType) } return creator(logType, options) } diff --git a/app/metrics/errors.generated.go b/app/metrics/errors.generated.go deleted file mode 100644 index dee6b316..00000000 --- a/app/metrics/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package metrics - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/metrics/metrics.go b/app/metrics/metrics.go index 9b0ba071..757d673d 100644 --- a/app/metrics/metrics.go +++ b/app/metrics/metrics.go @@ -10,6 +10,7 @@ import ( "github.com/xtls/xray-core/app/observatory" "github.com/xtls/xray-core/app/stats" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/signal/done" "github.com/xtls/xray-core/core" @@ -93,12 +94,12 @@ func (p *MetricsHandler) Start() error { go func() { if err := http.Serve(listener, http.DefaultServeMux); err != nil { - newError("failed to start metrics server").Base(err).AtError().WriteToLog() + errors.LogErrorInner(context.Background(), err, "failed to start metrics server") } }() if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil { - newError("failed to remove existing handler").WriteToLog() + errors.LogInfo(context.Background(), "failed to remove existing handler") } return p.ohm.AddHandler(context.Background(), &Outbound{ diff --git a/app/metrics/outbound.go b/app/metrics/outbound.go index 32c0192b..40f19383 100644 --- a/app/metrics/outbound.go +++ b/app/metrics/outbound.go @@ -5,6 +5,7 @@ import ( "sync" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/signal/done" @@ -31,7 +32,7 @@ func (l *OutboundListener) add(conn net.Conn) { func (l *OutboundListener) Accept() (net.Conn, error) { select { case <-l.done.Wait(): - return nil, newError("listen closed") + return nil, errors.New("listen closed") case c := <-l.buffer: return c, nil } diff --git a/app/observatory/burst/burstobserver.go b/app/observatory/burst/burstobserver.go index 6b7dbc7c..f2204c00 100644 --- a/app/observatory/burst/burstobserver.go +++ b/app/observatory/burst/burstobserver.go @@ -2,15 +2,17 @@ package burst import ( "context" - - "github.com/xtls/xray-core/core" + + "sync" + "github.com/xtls/xray-core/app/observatory" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/signal/done" + "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/features/extension" "github.com/xtls/xray-core/features/outbound" "google.golang.org/protobuf/proto" - "sync" ) type Observer struct { @@ -66,7 +68,7 @@ func (o *Observer) Start() error { hs, ok := o.ohm.(outbound.HandlerSelector) if !ok { - return nil, newError("outbound.Manager is not a HandlerSelector") + return nil, errors.New("outbound.Manager is not a HandlerSelector") } outbounds := hs.Select(o.config.SubjectSelector) @@ -90,7 +92,7 @@ func New(ctx context.Context, config *Config) (*Observer, error) { outboundManager = om }) if err != nil { - return nil, newError("Cannot get depended features").Base(err) + return nil, errors.New("Cannot get depended features").Base(err) } hp := NewHealthPing(ctx, config.PingConfig) return &Observer{ diff --git a/app/observatory/burst/errors.generated.go b/app/observatory/burst/errors.generated.go deleted file mode 100644 index 35638eec..00000000 --- a/app/observatory/burst/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package burst - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/observatory/burst/healthping.go b/app/observatory/burst/healthping.go index 2f0bbcc6..34690f58 100644 --- a/app/observatory/burst/healthping.go +++ b/app/observatory/burst/healthping.go @@ -8,6 +8,7 @@ import ( "time" "github.com/xtls/xray-core/common/dice" + "github.com/xtls/xray-core/common/errors" ) // HealthPingSettings holds settings for health Checker @@ -51,7 +52,7 @@ func NewHealthPing(ctx context.Context, config *HealthPingConfig) *HealthPing { if settings.Interval == 0 { settings.Interval = time.Duration(1) * time.Minute } else if settings.Interval < 10 { - newError("health check interval is too small, 10s is applied").AtWarning().WriteToLog() + errors.LogWarning(ctx, "health check interval is too small, 10s is applied") settings.Interval = time.Duration(10) * time.Second } if settings.SamplingCount <= 0 { @@ -82,7 +83,7 @@ func (h *HealthPing) StartScheduler(selector func() ([]string, error)) { go func() { tags, err := selector() if err != nil { - newError("error select outbounds for initial health check: ", err).AtWarning().WriteToLog() + errors.LogWarning(h.ctx, "error select outbounds for initial health check: ", err) return } h.Check(tags) @@ -93,7 +94,7 @@ func (h *HealthPing) StartScheduler(selector func() ([]string, error)) { go func() { tags, err := selector() if err != nil { - newError("error select outbounds for scheduled health check: ", err).AtWarning().WriteToLog() + errors.LogWarning(h.ctx, "error select outbounds for scheduled health check: ", err) return } h.doCheck(tags, interval, h.Settings.SamplingCount) @@ -125,7 +126,7 @@ func (h *HealthPing) Check(tags []string) error { if len(tags) == 0 { return nil } - newError("perform one-time health check for tags ", tags).AtInfo().WriteToLog() + errors.LogInfo(h.ctx, "perform one-time health check for tags ", tags) h.doCheck(tags, 0, 1) return nil } @@ -158,7 +159,7 @@ func (h *HealthPing) doCheck(tags []string, duration time.Duration, rounds int) delay = time.Duration(dice.Roll(int(duration))) } time.AfterFunc(delay, func() { - newError("checking ", handler).AtDebug().WriteToLog() + errors.LogDebug(h.ctx, "checking ", handler) delay, err := client.MeasureDelay() if err == nil { ch <- &rtt{ @@ -168,19 +169,19 @@ func (h *HealthPing) doCheck(tags []string, duration time.Duration, rounds int) return } if !h.checkConnectivity() { - newError("network is down").AtWarning().WriteToLog() + errors.LogWarning(h.ctx, "network is down") ch <- &rtt{ handler: handler, value: 0, } return } - newError(fmt.Sprintf( + errors.LogWarning(h.ctx, fmt.Sprintf( "error ping %s with %s: %s", h.Settings.Destination, handler, err, - )).AtWarning().WriteToLog() + )) ch <- &rtt{ handler: handler, value: rttFailed, diff --git a/app/observatory/errors.generated.go b/app/observatory/errors.generated.go deleted file mode 100644 index 5cd4408a..00000000 --- a/app/observatory/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package observatory - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/observatory/explainErrors.go b/app/observatory/explainErrors.go index 9aba7923..287a78ef 100644 --- a/app/observatory/explainErrors.go +++ b/app/observatory/explainErrors.go @@ -8,10 +8,10 @@ type errorCollector struct { func (e *errorCollector) SubmitError(err error) { if e.errors == nil { - e.errors = newError("underlying connection error").Base(err) + e.errors = errors.New("underlying connection error").Base(err) return } - e.errors = e.errors.Base(newError("underlying connection error").Base(err)) + e.errors = e.errors.Base(errors.New("underlying connection error").Base(err)) } func newErrorCollector() *errorCollector { @@ -20,7 +20,7 @@ func newErrorCollector() *errorCollector { func (e *errorCollector) UnderlyingError() error { if e.errors == nil { - return newError("failed to produce report") + return errors.New("failed to produce report") } return e.errors } diff --git a/app/observatory/observer.go b/app/observatory/observer.go index 9d961f66..f29856db 100644 --- a/app/observatory/observer.go +++ b/app/observatory/observer.go @@ -10,6 +10,7 @@ import ( "time" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" v2net "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/signal/done" @@ -60,7 +61,7 @@ func (o *Observer) background() { for !o.finished.Done() { hs, ok := o.ohm.(outbound.HandlerSelector) if !ok { - newError("outbound.Manager is not a HandlerSelector").WriteToLog() + errors.LogInfo(o.ctx, "outbound.Manager is not a HandlerSelector") return } @@ -127,18 +128,18 @@ func (o *Observer) probe(outbound string) ProbeResult { // MUST use Xray's built in context system dest, err := v2net.ParseDestination(network + ":" + addr) if err != nil { - return newError("cannot understand address").Base(err) + return errors.New("cannot understand address").Base(err) } trackedCtx := session.TrackedConnectionError(o.ctx, errorCollectorForRequest) conn, err := tagged.Dialer(trackedCtx, dest, outbound) if err != nil { - return newError("cannot dial remote address ", dest).Base(err) + return errors.New("cannot dial remote address ", dest).Base(err) } connection = conn return nil }) if taskErr != nil { - return nil, newError("cannot finish connection").Base(taskErr) + return nil, errors.New("cannot finish connection").Base(taskErr) } return connection, nil }, @@ -161,7 +162,7 @@ func (o *Observer) probe(outbound string) ProbeResult { } response, err := httpClient.Get(probeURL) if err != nil { - return newError("outbound failed to relay connection").Base(err) + return errors.New("outbound failed to relay connection").Base(err) } if response.Body != nil { response.Body.Close() @@ -171,15 +172,11 @@ func (o *Observer) probe(outbound string) ProbeResult { return nil }) if err != nil { - fullerr := newError("underlying connection failed").Base(errorCollectorForRequest.UnderlyingError()) - fullerr = newError("with outbound handler report").Base(fullerr) - fullerr = newError("GET request failed:", err).Base(fullerr) - fullerr = newError("the outbound ", outbound, " is dead:").Base(fullerr) - fullerr = fullerr.AtInfo() - fullerr.WriteToLog() - return ProbeResult{Alive: false, LastErrorReason: fullerr.Error()} + var errorMessage = "the outbound " + outbound + " is dead: GET request failed:" + err.Error() + "with outbound handler report underlying connection failed" + errors.LogInfoInner(o.ctx, errorCollectorForRequest.UnderlyingError(), errorMessage) + return ProbeResult{Alive: false, LastErrorReason: errorMessage} } - newError("the outbound ", outbound, " is alive:", GETTime.Seconds()).AtInfo().WriteToLog() + errors.LogInfo(o.ctx, "the outbound ", outbound, " is alive:", GETTime.Seconds()) return ProbeResult{Alive: true, Delay: GETTime.Milliseconds()} } @@ -222,7 +219,7 @@ func New(ctx context.Context, config *Config) (*Observer, error) { outboundManager = om }) if err != nil { - return nil, newError("Cannot get depended features").Base(err) + return nil, errors.New("Cannot get depended features").Base(err) } return &Observer{ config: config, diff --git a/app/policy/errors.generated.go b/app/policy/errors.generated.go deleted file mode 100644 index 1fe4d613..00000000 --- a/app/policy/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package policy - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/proxyman/command/command.go b/app/proxyman/command/command.go index 9782d6c1..4554f32b 100644 --- a/app/proxyman/command/command.go +++ b/app/proxyman/command/command.go @@ -4,6 +4,7 @@ import ( "context" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/features/inbound" "github.com/xtls/xray-core/features/outbound" @@ -26,7 +27,7 @@ type OutboundOperation interface { func getInbound(handler inbound.Handler) (proxy.Inbound, error) { gi, ok := handler.(proxy.GetInbound) if !ok { - return nil, newError("can't get inbound proxy from handler.") + return nil, errors.New("can't get inbound proxy from handler.") } return gi.GetInbound(), nil } @@ -39,11 +40,11 @@ func (op *AddUserOperation) ApplyInbound(ctx context.Context, handler inbound.Ha } um, ok := p.(proxy.UserManager) if !ok { - return newError("proxy is not a UserManager") + return errors.New("proxy is not a UserManager") } mUser, err := op.User.ToMemoryUser() if err != nil { - return newError("failed to parse user").Base(err) + return errors.New("failed to parse user").Base(err) } return um.AddUser(ctx, mUser) } @@ -56,7 +57,7 @@ func (op *RemoveUserOperation) ApplyInbound(ctx context.Context, handler inbound } um, ok := p.(proxy.UserManager) if !ok { - return newError("proxy is not a UserManager") + return errors.New("proxy is not a UserManager") } return um.RemoveUser(ctx, op.Email) } @@ -82,16 +83,16 @@ func (s *handlerServer) RemoveInbound(ctx context.Context, request *RemoveInboun func (s *handlerServer) AlterInbound(ctx context.Context, request *AlterInboundRequest) (*AlterInboundResponse, error) { rawOperation, err := request.Operation.GetInstance() if err != nil { - return nil, newError("unknown operation").Base(err) + return nil, errors.New("unknown operation").Base(err) } operation, ok := rawOperation.(InboundOperation) if !ok { - return nil, newError("not an inbound operation") + return nil, errors.New("not an inbound operation") } handler, err := s.ihm.GetHandler(ctx, request.Tag) if err != nil { - return nil, newError("failed to get handler: ", request.Tag).Base(err) + return nil, errors.New("failed to get handler: ", request.Tag).Base(err) } return &AlterInboundResponse{}, operation.ApplyInbound(ctx, handler) @@ -111,11 +112,11 @@ func (s *handlerServer) RemoveOutbound(ctx context.Context, request *RemoveOutbo func (s *handlerServer) AlterOutbound(ctx context.Context, request *AlterOutboundRequest) (*AlterOutboundResponse, error) { rawOperation, err := request.Operation.GetInstance() if err != nil { - return nil, newError("unknown operation").Base(err) + return nil, errors.New("unknown operation").Base(err) } operation, ok := rawOperation.(OutboundOperation) if !ok { - return nil, newError("not an outbound operation") + return nil, errors.New("not an outbound operation") } handler := s.ohm.GetHandler(request.Tag) diff --git a/app/proxyman/command/errors.generated.go b/app/proxyman/command/errors.generated.go deleted file mode 100644 index a1305932..00000000 --- a/app/proxyman/command/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package command - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/proxyman/inbound/always.go b/app/proxyman/inbound/always.go index f422e626..ff585c87 100644 --- a/app/proxyman/inbound/always.go +++ b/app/proxyman/inbound/always.go @@ -55,7 +55,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig * } p, ok := rawProxy.(proxy.Inbound) if !ok { - return nil, newError("not an inbound proxy.") + return nil, errors.New("not an inbound proxy.") } h := &AlwaysOnInboundHandler{ @@ -75,7 +75,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig * mss, err := internet.ToMemoryStreamConfig(receiverConfig.StreamSettings) if err != nil { - return nil, newError("failed to parse stream config").Base(err).AtWarning() + return nil, errors.New("failed to parse stream config").Base(err).AtWarning() } if receiverConfig.ReceiveOriginalDestination { @@ -89,7 +89,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig * } if pl == nil { if net.HasNetwork(nl, net.Network_UNIX) { - newError("creating unix domain socket worker on ", address).AtDebug().WriteToLog() + errors.LogDebug(ctx, "creating unix domain socket worker on ", address) worker := &dsWorker{ address: address, @@ -109,7 +109,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig * for _, pr := range pl.Range { for port := pr.From; port <= pr.To; port++ { if net.HasNetwork(nl, net.Network_TCP) { - newError("creating stream worker on ", address, ":", port).AtDebug().WriteToLog() + errors.LogDebug(ctx, "creating stream worker on ", address, ":", port) worker := &tcpWorker{ address: address, @@ -167,7 +167,7 @@ func (h *AlwaysOnInboundHandler) Close() error { } errs = append(errs, h.mux.Close()) if err := errors.Combine(errs...); err != nil { - return newError("failed to close all resources").Base(err) + return errors.New("failed to close all resources").Base(err) } return nil } diff --git a/app/proxyman/inbound/dynamic.go b/app/proxyman/inbound/dynamic.go index 0f81c26e..0a98b888 100644 --- a/app/proxyman/inbound/dynamic.go +++ b/app/proxyman/inbound/dynamic.go @@ -7,6 +7,7 @@ import ( "github.com/xtls/xray-core/app/proxyman" "github.com/xtls/xray-core/common/dice" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/mux" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/task" @@ -46,7 +47,7 @@ func NewDynamicInboundHandler(ctx context.Context, tag string, receiverConfig *p mss, err := internet.ToMemoryStreamConfig(receiverConfig.StreamSettings) if err != nil { - return nil, newError("failed to parse stream settings").Base(err).AtWarning() + return nil, errors.New("failed to parse stream settings").Base(err).AtWarning() } if receiverConfig.ReceiveOriginalDestination { if mss.SocketSettings == nil { @@ -94,7 +95,7 @@ func (h *DynamicInboundHandler) closeWorkers(workers []worker) { for idx, worker := range workers { ports2Del[idx] = worker.Port() if err := worker.Close(); err != nil { - newError("failed to close worker").Base(err).WriteToLog() + errors.LogInfoInner(h.ctx, err, "failed to close worker") } } @@ -123,7 +124,7 @@ func (h *DynamicInboundHandler) refresh() error { port := h.allocatePort() rawProxy, err := core.CreateObject(h.v, h.proxyConfig) if err != nil { - newError("failed to create proxy instance").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(h.ctx, err, "failed to create proxy instance") continue } p := rawProxy.(proxy.Inbound) @@ -143,7 +144,7 @@ func (h *DynamicInboundHandler) refresh() error { ctx: h.ctx, } if err := worker.Start(); err != nil { - newError("failed to create TCP worker").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(h.ctx, err, "failed to create TCP worker") continue } workers = append(workers, worker) @@ -163,7 +164,7 @@ func (h *DynamicInboundHandler) refresh() error { ctx: h.ctx, } if err := worker.Start(); err != nil { - newError("failed to create UDP worker").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(h.ctx, err, "failed to create UDP worker") continue } workers = append(workers, worker) diff --git a/app/proxyman/inbound/errors.generated.go b/app/proxyman/inbound/errors.generated.go deleted file mode 100644 index c2d7295e..00000000 --- a/app/proxyman/inbound/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package inbound - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/proxyman/inbound/inbound.go b/app/proxyman/inbound/inbound.go index 3c9fb467..1881283a 100644 --- a/app/proxyman/inbound/inbound.go +++ b/app/proxyman/inbound/inbound.go @@ -8,6 +8,7 @@ import ( "github.com/xtls/xray-core/app/proxyman" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/core" @@ -43,7 +44,7 @@ func (m *Manager) AddHandler(ctx context.Context, handler inbound.Handler) error tag := handler.Tag() if len(tag) > 0 { if _, found := m.taggedHandlers[tag]; found { - return newError("existing tag found: " + tag) + return errors.New("existing tag found: " + tag) } m.taggedHandlers[tag] = handler } else { @@ -64,7 +65,7 @@ func (m *Manager) GetHandler(ctx context.Context, tag string) (inbound.Handler, handler, found := m.taggedHandlers[tag] if !found { - return nil, newError("handler not found: ", tag) + return nil, errors.New("handler not found: ", tag) } return handler, nil } @@ -80,7 +81,7 @@ func (m *Manager) RemoveHandler(ctx context.Context, tag string) error { if handler, found := m.taggedHandlers[tag]; found { if err := handler.Close(); err != nil { - newError("failed to close handler ", tag).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, err, "failed to close handler ", tag) } delete(m.taggedHandlers, tag) return nil @@ -117,20 +118,20 @@ func (m *Manager) Close() error { m.running = false - var errors []interface{} + var errs []interface{} for _, handler := range m.taggedHandlers { if err := handler.Close(); err != nil { - errors = append(errors, err) + errs = append(errs, err) } } for _, handler := range m.untaggedHandler { if err := handler.Close(); err != nil { - errors = append(errors, err) + errs = append(errs, err) } } - if len(errors) > 0 { - return newError("failed to close all handlers").Base(newError(serial.Concat(errors...))) + if len(errs) > 0 { + return errors.New("failed to close all handlers").Base(errors.New(serial.Concat(errs...))) } return nil @@ -150,7 +151,7 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound receiverSettings, ok := rawReceiverSettings.(*proxyman.ReceiverConfig) if !ok { - return nil, newError("not a ReceiverConfig").AtError() + return nil, errors.New("not a ReceiverConfig").AtError() } streamSettings := receiverSettings.StreamSettings @@ -168,7 +169,7 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound if allocStrategy.Type == proxyman.AllocationStrategy_Random { return NewDynamicInboundHandler(ctx, tag, receiverSettings, proxySettings) } - return nil, newError("unknown allocation strategy: ", receiverSettings.AllocationStrategy.Type).AtError() + return nil, errors.New("unknown allocation strategy: ", receiverSettings.AllocationStrategy.Type).AtError() } func init() { diff --git a/app/proxyman/inbound/worker.go b/app/proxyman/inbound/worker.go index 539508e1..a14a338f 100644 --- a/app/proxyman/inbound/worker.go +++ b/app/proxyman/inbound/worker.go @@ -9,6 +9,8 @@ import ( "github.com/xtls/xray-core/app/proxyman" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + c "github.com/xtls/xray-core/common/ctx" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/session" @@ -58,7 +60,7 @@ func getTProxyType(s *internet.MemoryStreamConfig) internet.SocketConfig_TProxyM func (w *tcpWorker) callback(conn stat.Connection) { ctx, cancel := context.WithCancel(w.ctx) sid := session.NewID() - ctx = session.ContextWithID(ctx, sid) + ctx = c.ContextWithID(ctx, sid) outbounds := []*session.Outbound{{}} if w.recvOrigDest { @@ -67,7 +69,7 @@ func (w *tcpWorker) callback(conn stat.Connection) { case internet.SocketConfig_Redirect: d, err := tcp.GetOriginalDestination(conn) if err != nil { - newError("failed to get original destination").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to get original destination") } else { dest = d } @@ -105,7 +107,7 @@ func (w *tcpWorker) callback(conn stat.Connection) { ctx = session.ContextWithContent(ctx, content) if err := w.proxy.Process(ctx, net.Network_TCP, conn, w.dispatcher); err != nil { - newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "connection ends") } cancel() conn.Close() @@ -121,24 +123,24 @@ func (w *tcpWorker) Start() error { go w.callback(conn) }) if err != nil { - return newError("failed to listen TCP on ", w.port).AtWarning().Base(err) + return errors.New("failed to listen TCP on ", w.port).AtWarning().Base(err) } w.hub = hub return nil } func (w *tcpWorker) Close() error { - var errors []interface{} + var errs []interface{} if w.hub != nil { if err := common.Close(w.hub); err != nil { - errors = append(errors, err) + errs = append(errs, err) } if err := common.Close(w.proxy); err != nil { - errors = append(errors, err) + errs = append(errs, err) } } - if len(errors) > 0 { - return newError("failed to close all resources").Base(newError(serial.Concat(errors...))) + if len(errs) > 0 { + return errors.New("failed to close all resources").Base(errors.New(serial.Concat(errs...))) } return nil @@ -306,7 +308,7 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest go func() { ctx := w.ctx sid := session.NewID() - ctx = session.ContextWithID(ctx, sid) + ctx = c.ContextWithID(ctx, sid) outbounds := []*session.Outbound{{}} if originalDest.IsValid() { @@ -327,7 +329,7 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest } ctx = session.ContextWithContent(ctx, content) if err := w.proxy.Process(ctx, net.Network_UDP, conn, w.dispatcher); err != nil { - newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "connection ends") } conn.Close() // conn not removed by checker TODO may be lock worker here is better @@ -358,7 +360,7 @@ func (w *udpWorker) clean() error { defer w.Unlock() if len(w.activeConn) == 0 { - return newError("no more connections. stopping...") + return errors.New("no more connections. stopping...") } for addr, conn := range w.activeConn { @@ -402,26 +404,26 @@ func (w *udpWorker) Close() error { w.Lock() defer w.Unlock() - var errors []interface{} + var errs []interface{} if w.hub != nil { if err := w.hub.Close(); err != nil { - errors = append(errors, err) + errs = append(errs, err) } } if w.checker != nil { if err := w.checker.Close(); err != nil { - errors = append(errors, err) + errs = append(errs, err) } } if err := common.Close(w.proxy); err != nil { - errors = append(errors, err) + errs = append(errs, err) } - if len(errors) > 0 { - return newError("failed to close all resources").Base(newError(serial.Concat(errors...))) + if len(errs) > 0 { + return errors.New("failed to close all resources").Base(errors.New(serial.Concat(errs...))) } return nil } @@ -452,7 +454,7 @@ type dsWorker struct { func (w *dsWorker) callback(conn stat.Connection) { ctx, cancel := context.WithCancel(w.ctx) sid := session.NewID() - ctx = session.ContextWithID(ctx, sid) + ctx = c.ContextWithID(ctx, sid) if w.uplinkCounter != nil || w.downlinkCounter != nil { conn = &stat.CounterConnection{ @@ -479,11 +481,11 @@ func (w *dsWorker) callback(conn stat.Connection) { ctx = session.ContextWithContent(ctx, content) if err := w.proxy.Process(ctx, net.Network_UNIX, conn, w.dispatcher); err != nil { - newError("connection ends").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "connection ends") } cancel() if err := conn.Close(); err != nil { - newError("failed to close connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to close connection") } } @@ -501,24 +503,24 @@ func (w *dsWorker) Start() error { go w.callback(conn) }) if err != nil { - return newError("failed to listen Unix Domain Socket on ", w.address).AtWarning().Base(err) + return errors.New("failed to listen Unix Domain Socket on ", w.address).AtWarning().Base(err) } w.hub = hub return nil } func (w *dsWorker) Close() error { - var errors []interface{} + var errs []interface{} if w.hub != nil { if err := common.Close(w.hub); err != nil { - errors = append(errors, err) + errs = append(errs, err) } if err := common.Close(w.proxy); err != nil { - errors = append(errors, err) + errs = append(errs, err) } } - if len(errors) > 0 { - return newError("failed to close all resources").Base(newError(serial.Concat(errors...))) + if len(errs) > 0 { + return errors.New("failed to close all resources").Base(errors.New(serial.Concat(errs...))) } return nil diff --git a/app/proxyman/outbound/errors.generated.go b/app/proxyman/outbound/errors.generated.go deleted file mode 100644 index 07966823..00000000 --- a/app/proxyman/outbound/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package outbound - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/proxyman/outbound/handler.go b/app/proxyman/outbound/handler.go index 4262c76a..47d7d6bf 100644 --- a/app/proxyman/outbound/handler.go +++ b/app/proxyman/outbound/handler.go @@ -3,9 +3,15 @@ package outbound import ( "context" "crypto/rand" - "errors" + goerrors "errors" + "io" + "math/big" + gonet "net" + "os" + "github.com/xtls/xray-core/app/proxyman" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/mux" "github.com/xtls/xray-core/common/net" @@ -21,10 +27,6 @@ import ( "github.com/xtls/xray-core/transport/internet/stat" "github.com/xtls/xray-core/transport/internet/tls" "github.com/xtls/xray-core/transport/pipe" - "io" - "math/big" - gonet "net" - "os" ) func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter) { @@ -87,11 +89,11 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou h.senderSettings = s mss, err := internet.ToMemoryStreamConfig(s.StreamSettings) if err != nil { - return nil, newError("failed to parse stream settings").Base(err).AtWarning() + return nil, errors.New("failed to parse stream settings").Base(err).AtWarning() } h.streamSettings = mss default: - return nil, newError("settings is not SenderConfig") + return nil, errors.New("settings is not SenderConfig") } } @@ -107,7 +109,7 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou proxyHandler, ok := rawProxyHandler.(proxy.Outbound) if !ok { - return nil, newError("not an outbound handler") + return nil, errors.New("not an outbound handler") } if h.senderSettings != nil && h.senderSettings.MultiplexSettings != nil { @@ -170,7 +172,7 @@ func (h *Handler) Tag() string { // Dispatch implements proxy.Outbound.Dispatch. func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address { link.Reader = &buf.EndpointOverrideReader{Reader: link.Reader, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address} link.Writer = &buf.EndpointOverrideWriter{Writer: link.Writer, Dest: ob.Target.Address, OriginalDest: ob.OriginalTarget.Address} @@ -178,16 +180,16 @@ func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) { if h.mux != nil { test := func(err error) { if err != nil { - err := newError("failed to process mux outbound traffic").Base(err) + err := errors.New("failed to process mux outbound traffic").Base(err) session.SubmitOutboundErrorToOriginator(ctx, err) - err.WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, err.Error()) common.Interrupt(link.Writer) } } if ob.Target.Network == net.Network_UDP && ob.Target.Port == 443 { switch h.udp443 { case "reject": - test(newError("XUDP rejected UDP/443 traffic").AtInfo()) + test(errors.New("XUDP rejected UDP/443 traffic").AtInfo()) return case "skip": goto out @@ -208,15 +210,15 @@ func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) { out: err := h.proxy.Process(ctx, link, h) if err != nil { - if errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) || errors.Is(err, context.Canceled) { + if goerrors.Is(err, io.EOF) || goerrors.Is(err, io.ErrClosedPipe) || goerrors.Is(err, context.Canceled) { err = nil } } if err != nil { // Ensure outbound ray is properly closed. - err := newError("failed to process outbound traffic").Base(err) + err := errors.New("failed to process outbound traffic").Base(err) session.SubmitOutboundErrorToOriginator(ctx, err) - err.WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, err.Error()) common.Interrupt(link.Writer) } else { common.Close(link.Writer) @@ -243,11 +245,11 @@ func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connecti tag := h.senderSettings.ProxySettings.Tag handler := h.outboundManager.GetHandler(tag) if handler != nil { - newError("proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, "proxying to ", tag, " for dest ", dest) outbounds := session.OutboundsFromContext(ctx) ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{ Target: dest, - Tag: tag, + Tag: tag, })) // add another outbound in session ctx opts := pipe.OptionsFromContext(ctx) uplinkReader, uplinkWriter := pipe.New(opts...) @@ -264,12 +266,12 @@ func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connecti return h.getStatCouterConnection(conn), nil } - newError("failed to get outbound handler with tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarning(ctx, "failed to get outbound handler with tag: ", tag) } if h.senderSettings.Via != nil { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if h.senderSettings.ViaCidr == "" { ob.Gateway = h.senderSettings.Via.AsAddress() } else { //Get a random address. @@ -285,7 +287,7 @@ func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connecti conn, err := internet.Dial(ctx, dest, h.streamSettings) conn = h.getStatCouterConnection(conn) outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] ob.Conn = conn return conn, err } @@ -317,7 +319,6 @@ func (h *Handler) Close() error { return nil } - func ParseRandomIPv6(address net.Address, prefix string) net.Address { _, network, _ := gonet.ParseCIDR(address.IP().String() + "/" + prefix) diff --git a/app/proxyman/outbound/outbound.go b/app/proxyman/outbound/outbound.go index 40f32965..f697801a 100644 --- a/app/proxyman/outbound/outbound.go +++ b/app/proxyman/outbound/outbound.go @@ -115,7 +115,7 @@ func (m *Manager) AddHandler(ctx context.Context, handler outbound.Handler) erro tag := handler.Tag() if len(tag) > 0 { if _, found := m.taggedHandler[tag]; found { - return newError("existing tag found: " + tag) + return errors.New("existing tag found: " + tag) } m.taggedHandler[tag] = handler } else { diff --git a/app/proxyman/outbound/uot.go b/app/proxyman/outbound/uot.go index f3c7426e..659f65a1 100644 --- a/app/proxyman/outbound/uot.go +++ b/app/proxyman/outbound/uot.go @@ -5,6 +5,7 @@ import ( "os" "github.com/sagernet/sing/common/uot" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/stat" @@ -12,7 +13,7 @@ import ( func (h *Handler) getUoTConnection(ctx context.Context, dest net.Destination) (stat.Connection, error) { if dest.Address == nil { - return nil, newError("nil destination address") + return nil, errors.New("nil destination address") } if !dest.Address.Family().IsDomain() { return nil, os.ErrInvalid @@ -27,7 +28,7 @@ func (h *Handler) getUoTConnection(ctx context.Context, dest net.Destination) (s } packetConn, err := internet.ListenSystemPacket(ctx, &net.UDPAddr{IP: net.AnyIP.IP(), Port: 0}, h.streamSettings.SocketSettings) if err != nil { - return nil, newError("unable to listen socket").Base(err) + return nil, errors.New("unable to listen socket").Base(err) } conn := uot.NewServerConn(packetConn, uotVersion) return h.getStatCouterConnection(conn), nil diff --git a/app/reverse/bridge.go b/app/reverse/bridge.go index be0fdcd9..3e46cc6c 100644 --- a/app/reverse/bridge.go +++ b/app/reverse/bridge.go @@ -4,6 +4,7 @@ import ( "context" "time" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/mux" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/session" @@ -26,10 +27,10 @@ type Bridge struct { // NewBridge creates a new Bridge instance. func NewBridge(config *BridgeConfig, dispatcher routing.Dispatcher) (*Bridge, error) { if config.Tag == "" { - return nil, newError("bridge tag is empty") + return nil, errors.New("bridge tag is empty") } if config.Domain == "" { - return nil, newError("bridge domain is empty") + return nil, errors.New("bridge domain is empty") } b := &Bridge{ @@ -74,7 +75,7 @@ func (b *Bridge) monitor() error { if numWorker == 0 || numConnections/numWorker > 16 { worker, err := NewBridgeWorker(b.domain, b.tag, b.dispatcher) if err != nil { - newError("failed to create bridge worker").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(context.Background(), err, "failed to create bridge worker") return nil } b.workers = append(b.workers, worker) @@ -157,7 +158,7 @@ func (w *BridgeWorker) handleInternalConn(link *transport.Link) { for _, b := range mb { var ctl Control if err := proto.Unmarshal(b.Bytes(), &ctl); err != nil { - newError("failed to parse proto message").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to parse proto message") break } if ctl.State != w.state { diff --git a/app/reverse/errors.generated.go b/app/reverse/errors.generated.go deleted file mode 100644 index 5dc907a2..00000000 --- a/app/reverse/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package reverse - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/reverse/portal.go b/app/reverse/portal.go index 456de550..d57ac29a 100644 --- a/app/reverse/portal.go +++ b/app/reverse/portal.go @@ -7,6 +7,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/mux" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/session" @@ -27,11 +28,11 @@ type Portal struct { func NewPortal(config *PortalConfig, ohm outbound.Manager) (*Portal, error) { if config.Tag == "" { - return nil, newError("portal tag is empty") + return nil, errors.New("portal tag is empty") } if config.Domain == "" { - return nil, newError("portal domain is empty") + return nil, errors.New("portal domain is empty") } picker, err := NewStaticMuxPicker() @@ -63,20 +64,20 @@ func (p *Portal) Close() error { func (p *Portal) HandleConnection(ctx context.Context, link *transport.Link) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if ob == nil { - return newError("outbound metadata not found").AtError() + return errors.New("outbound metadata not found").AtError() } if isDomain(ob.Target, p.domain) { muxClient, err := mux.NewClientWorker(*link, mux.ClientStrategy{}) if err != nil { - return newError("failed to create mux client worker").Base(err).AtWarning() + return errors.New("failed to create mux client worker").Base(err).AtWarning() } worker, err := NewPortalWorker(muxClient) if err != nil { - return newError("failed to create portal worker").Base(err) + return errors.New("failed to create portal worker").Base(err) } p.picker.AddWorker(worker) @@ -97,7 +98,7 @@ func (o *Outbound) Tag() string { func (o *Outbound) Dispatch(ctx context.Context, link *transport.Link) { if err := o.portal.HandleConnection(ctx, link); err != nil { - newError("failed to process reverse connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to process reverse connection") common.Interrupt(link.Writer) } } @@ -149,7 +150,7 @@ func (p *StaticMuxPicker) PickAvailable() (*mux.ClientWorker, error) { defer p.access.Unlock() if len(p.workers) == 0 { - return nil, newError("empty worker list") + return nil, errors.New("empty worker list") } var minIdx int = -1 @@ -183,7 +184,7 @@ func (p *StaticMuxPicker) PickAvailable() (*mux.ClientWorker, error) { return p.workers[minIdx].client, nil } - return nil, newError("no mux client worker available") + return nil, errors.New("no mux client worker available") } func (p *StaticMuxPicker) AddWorker(worker *PortalWorker) { @@ -216,7 +217,7 @@ func NewPortalWorker(client *mux.ClientWorker) (*PortalWorker, error) { Writer: downlinkWriter, }) if !f { - return nil, newError("unable to dispatch control connection") + return nil, errors.New("unable to dispatch control connection") } w := &PortalWorker{ client: client, @@ -233,11 +234,11 @@ func NewPortalWorker(client *mux.ClientWorker) (*PortalWorker, error) { func (w *PortalWorker) heartbeat() error { if w.client.Closed() { - return newError("client worker stopped") + return errors.New("client worker stopped") } if w.draining || w.writer == nil { - return newError("already disposed") + return errors.New("already disposed") } msg := &Control{} diff --git a/app/router/balancing.go b/app/router/balancing.go index c2eefe84..14f8e21f 100644 --- a/app/router/balancing.go +++ b/app/router/balancing.go @@ -6,6 +6,7 @@ import ( "github.com/xtls/xray-core/app/observatory" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/features/extension" "github.com/xtls/xray-core/features/outbound" @@ -24,8 +25,8 @@ type RoundRobinStrategy struct { ctx context.Context observatory extension.Observatory - mu sync.Mutex - index int + mu sync.Mutex + index int } func (s *RoundRobinStrategy) InjectContext(ctx context.Context) { @@ -95,7 +96,7 @@ func (b *Balancer) PickOutbound() (string, error) { candidates, err := b.SelectOutbounds() if err != nil { if b.fallbackTag != "" { - newError("fallback to [", b.fallbackTag, "], due to error: ", err).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "fallback to [", b.fallbackTag, "], due to error: ", err) return b.fallbackTag, nil } return "", err @@ -108,11 +109,11 @@ func (b *Balancer) PickOutbound() (string, error) { } if tag == "" { if b.fallbackTag != "" { - newError("fallback to [", b.fallbackTag, "], due to empty tag returned").AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "fallback to [", b.fallbackTag, "], due to empty tag returned") return b.fallbackTag, nil } // will use default handler - return "", newError("balancing strategy returns empty tag") + return "", errors.New("balancing strategy returns empty tag") } return tag, nil } @@ -127,7 +128,7 @@ func (b *Balancer) InjectContext(ctx context.Context) { func (b *Balancer) SelectOutbounds() ([]string, error) { hs, ok := b.ohm.(outbound.HandlerSelector) if !ok { - return nil, newError("outbound.Manager is not a HandlerSelector") + return nil, errors.New("outbound.Manager is not a HandlerSelector") } tags := hs.Select(b.selectors) return tags, nil @@ -139,13 +140,13 @@ func (r *Router) GetPrincipleTarget(tag string) ([]string, error) { if s, ok := b.strategy.(BalancingPrincipleTarget); ok { candidates, err := b.SelectOutbounds() if err != nil { - return nil, newError("unable to select outbounds").Base(err) + return nil, errors.New("unable to select outbounds").Base(err) } return s.GetPrincipleTarget(candidates), nil } - return nil, newError("unsupported GetPrincipleTarget") + return nil, errors.New("unsupported GetPrincipleTarget") } - return nil, newError("cannot find tag") + return nil, errors.New("cannot find tag") } // SetOverrideTarget implements routing.BalancerOverrider @@ -154,7 +155,7 @@ func (r *Router) SetOverrideTarget(tag, target string) error { b.override.Put(target) return nil } - return newError("cannot find tag") + return errors.New("cannot find tag") } // GetOverrideTarget implements routing.BalancerOverrider @@ -162,5 +163,5 @@ func (r *Router) GetOverrideTarget(tag string) (string, error) { if b, ok := r.balancers[tag]; ok { return b.override.Get(), nil } - return "", newError("cannot find tag") + return "", errors.New("cannot find tag") } diff --git a/app/router/balancing_override.go b/app/router/balancing_override.go index 30769f6b..96c0aea1 100644 --- a/app/router/balancing_override.go +++ b/app/router/balancing_override.go @@ -2,6 +2,8 @@ package router import ( sync "sync" + + "github.com/xtls/xray-core/common/errors" ) func (r *Router) OverrideBalancer(balancer string, target string) error { @@ -13,7 +15,7 @@ func (r *Router) OverrideBalancer(balancer string, target string) error { } } if b == nil { - return newError("balancer '", balancer, "' not found") + return errors.New("balancer '", balancer, "' not found") } b.override.Put(target) return nil diff --git a/app/router/command/command.go b/app/router/command/command.go index 520b9a30..515e2614 100644 --- a/app/router/command/command.go +++ b/app/router/command/command.go @@ -7,6 +7,7 @@ import ( "time" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/features/routing" "github.com/xtls/xray-core/features/stats" @@ -38,7 +39,7 @@ func (s *routingServer) GetBalancerInfo(ctx context.Context, request *GetBalance { res, err := pt.GetPrincipleTarget(request.GetTag()) if err != nil { - newError("unable to obtain principle target").Base(err).AtInfo().WriteToLog() + errors.LogInfoInner(ctx, err, "unable to obtain principle target") } else { ret.Balancer.PrincipleTarget = &PrincipleTargetInfo{Tag: res} } @@ -51,21 +52,21 @@ func (s *routingServer) OverrideBalancerTarget(ctx context.Context, request *Ove if bo, ok := s.router.(routing.BalancerOverrider); ok { return &OverrideBalancerTargetResponse{}, bo.SetOverrideTarget(request.BalancerTag, request.Target) } - return nil, newError("unsupported router implementation") + return nil, errors.New("unsupported router implementation") } func (s *routingServer) AddRule(ctx context.Context, request *AddRuleRequest) (*AddRuleResponse, error) { if bo, ok := s.router.(routing.Router); ok { return &AddRuleResponse{}, bo.AddRule(request.Config, request.ShouldAppend) } - return nil, newError("unsupported router implementation") + return nil, errors.New("unsupported router implementation") } func (s *routingServer) RemoveRule(ctx context.Context, request *RemoveRuleRequest) (*RemoveRuleResponse, error) { if bo, ok := s.router.(routing.Router); ok { return &RemoveRuleResponse{}, bo.RemoveRule(request.RuleTag) } - return nil, newError("unsupported router implementation") + return nil, errors.New("unsupported router implementation") } // NewRoutingServer creates a statistics service with statistics manager. @@ -78,7 +79,7 @@ func NewRoutingServer(router routing.Router, routingStats stats.Channel) Routing func (s *routingServer) TestRoute(ctx context.Context, request *TestRouteRequest) (*RoutingContext, error) { if request.RoutingContext == nil { - return nil, newError("Invalid routing request.") + return nil, errors.New("Invalid routing request.") } route, err := s.router.PickRoute(AsRoutingContext(request.RoutingContext)) if err != nil { @@ -93,7 +94,7 @@ func (s *routingServer) TestRoute(ctx context.Context, request *TestRouteRequest func (s *routingServer) SubscribeRoutingStats(request *SubscribeRoutingStatsRequest, stream RoutingService_SubscribeRoutingStatsServer) error { if s.routingStats == nil { - return newError("Routing statistics not enabled.") + return errors.New("Routing statistics not enabled.") } genMessage := AsProtobufMessage(request.FieldSelectors) subscriber, err := stats.SubscribeRunnableChannel(s.routingStats) @@ -105,11 +106,11 @@ func (s *routingServer) SubscribeRoutingStats(request *SubscribeRoutingStatsRequ select { case value, ok := <-subscriber: if !ok { - return newError("Upstream closed the subscriber channel.") + return errors.New("Upstream closed the subscriber channel.") } route, ok := value.(routing.Route) if !ok { - return newError("Upstream sent malformed statistics.") + return errors.New("Upstream sent malformed statistics.") } err := stream.Send(genMessage(route)) if err != nil { diff --git a/app/router/command/errors.generated.go b/app/router/command/errors.generated.go deleted file mode 100644 index a1305932..00000000 --- a/app/router/command/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package command - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/router/condition.go b/app/router/condition.go index 29056555..d53530e0 100644 --- a/app/router/condition.go +++ b/app/router/condition.go @@ -4,6 +4,7 @@ import ( "regexp" "strings" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/strmatcher" "github.com/xtls/xray-core/features/routing" @@ -49,12 +50,12 @@ var matcherTypeMap = map[Domain_Type]strmatcher.Type{ func domainToMatcher(domain *Domain) (strmatcher.Matcher, error) { matcherType, f := matcherTypeMap[domain.Type] if !f { - return nil, newError("unsupported domain type", domain.Type) + return nil, errors.New("unsupported domain type", domain.Type) } matcher, err := matcherType.New(domain.Value) if err != nil { - return nil, newError("failed to create domain matcher").Base(err) + return nil, errors.New("failed to create domain matcher").Base(err) } return matcher, nil @@ -69,7 +70,7 @@ func NewMphMatcherGroup(domains []*Domain) (*DomainMatcher, error) { for _, d := range domains { matcherType, f := matcherTypeMap[d.Type] if !f { - return nil, newError("unsupported domain type", d.Type) + return nil, errors.New("unsupported domain type", d.Type) } _, err := g.AddPattern(d.Value, matcherType) if err != nil { diff --git a/app/router/config.go b/app/router/config.go index e7c2af67..f2bad88f 100644 --- a/app/router/config.go +++ b/app/router/config.go @@ -1,9 +1,11 @@ package router import ( + "context" "regexp" "strings" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/features/outbound" "github.com/xtls/xray-core/features/routing" @@ -36,7 +38,7 @@ func (rr *RoutingRule) BuildCondition() (Condition, error) { case "linear": matcher, err := NewDomainMatcher(rr.Domain) if err != nil { - return nil, newError("failed to build domain condition").Base(err) + return nil, errors.New("failed to build domain condition").Base(err) } conds.Add(matcher) case "mph", "hybrid": @@ -44,9 +46,9 @@ func (rr *RoutingRule) BuildCondition() (Condition, error) { default: matcher, err := NewMphMatcherGroup(rr.Domain) if err != nil { - return nil, newError("failed to build domain condition with MphDomainMatcher").Base(err) + return nil, errors.New("failed to build domain condition with MphDomainMatcher").Base(err) } - newError("MphDomainMatcher is enabled for ", len(rr.Domain), " domain rule(s)").AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "MphDomainMatcher is enabled for ", len(rr.Domain), " domain rule(s)") conds.Add(matcher) } } @@ -116,7 +118,7 @@ func (rr *RoutingRule) BuildCondition() (Condition, error) { } if conds.Len() == 0 { - return nil, newError("this rule has no effective fields").AtWarning() + return nil, errors.New("this rule has no effective fields").AtWarning() } return conds, nil @@ -146,7 +148,7 @@ func (br *BalancingRule) Build(ohm outbound.Manager, dispatcher routing.Dispatch } s, ok := i.(*StrategyLeastLoadConfig) if !ok { - return nil, newError("not a StrategyLeastLoadConfig").AtError() + return nil, errors.New("not a StrategyLeastLoadConfig").AtError() } leastLoadStrategy := NewLeastLoadStrategy(s) return &Balancer{ @@ -165,6 +167,6 @@ func (br *BalancingRule) Build(ohm outbound.Manager, dispatcher routing.Dispatch strategy: &RandomStrategy{FallbackTag: br.FallbackTag}, }, nil default: - return nil, newError("unrecognized balancer type") + return nil, errors.New("unrecognized balancer type") } } diff --git a/app/router/errors.generated.go b/app/router/errors.generated.go deleted file mode 100644 index 1e5d74ba..00000000 --- a/app/router/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package router - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/router/router.go b/app/router/router.go index a45a6016..753ddfa8 100644 --- a/app/router/router.go +++ b/app/router/router.go @@ -7,6 +7,7 @@ import ( sync "sync" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/features/dns" @@ -68,7 +69,7 @@ func (r *Router) Init(ctx context.Context, config *Config, d dns.Client, ohm out if len(btag) > 0 { brule, found := r.balancers[btag] if !found { - return newError("balancer ", btag, " not found") + return errors.New("balancer ", btag, " not found") } rr.Balancer = brule } @@ -101,7 +102,7 @@ func (r *Router) AddRule(config *serial.TypedMessage, shouldAppend bool) error { if c, ok := inst.(*Config); ok { return r.ReloadRules(c, shouldAppend) } - return newError("AddRule: config type error") + return errors.New("AddRule: config type error") } func (r *Router) ReloadRules(config *Config, shouldAppend bool) error { @@ -115,7 +116,7 @@ func (r *Router) ReloadRules(config *Config, shouldAppend bool) error { for _, rule := range config.BalancingRule { _, found := r.balancers[rule.Tag] if found { - return newError("duplicate balancer tag") + return errors.New("duplicate balancer tag") } balancer, err := rule.Build(r.ohm, r.dispatcher) if err != nil { @@ -127,7 +128,7 @@ func (r *Router) ReloadRules(config *Config, shouldAppend bool) error { for _, rule := range config.Rule { if r.RuleExists(rule.GetRuleTag()) { - return newError("duplicate ruleTag ", rule.GetRuleTag()) + return errors.New("duplicate ruleTag ", rule.GetRuleTag()) } cond, err := rule.BuildCondition() if err != nil { @@ -142,7 +143,7 @@ func (r *Router) ReloadRules(config *Config, shouldAppend bool) error { if len(btag) > 0 { brule, found := r.balancers[btag] if !found { - return newError("balancer ", btag, " not found") + return errors.New("balancer ", btag, " not found") } rr.Balancer = brule } @@ -178,7 +179,7 @@ func (r *Router) RemoveRule(tag string) error { r.rules = newRules return nil } - return newError("empty tag name!") + return errors.New("empty tag name!") } func (r *Router) pickRouteInternal(ctx routing.Context) (*Rule, routing.Context, error) { diff --git a/app/router/strategy_leastload.go b/app/router/strategy_leastload.go index e8eb5567..bfdfd878 100644 --- a/app/router/strategy_leastload.go +++ b/app/router/strategy_leastload.go @@ -9,6 +9,7 @@ import ( "github.com/xtls/xray-core/app/observatory" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/dice" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/features/extension" ) @@ -95,7 +96,7 @@ func (s *LeastLoadStrategy) pickOutbounds(candidates []string) []*node { // with 'balancer.fallbackTag', it means: selects qualified nodes or use the fallback. func (s *LeastLoadStrategy) selectLeastLoad(nodes []*node) []*node { if len(nodes) == 0 { - newError("least load: no qualified outbound").AtInfo().WriteToLog() + errors.LogInfo(s.ctx, "least load: no qualified outbound") return nil } expected := int(s.settings.Expected) @@ -123,7 +124,7 @@ func (s *LeastLoadStrategy) selectLeastLoad(nodes []*node) []*node { } // don't continue if find expected selects if count >= expected { - newError("applied baseline: ", baseline).AtDebug().WriteToLog() + errors.LogDebug(s.ctx, "applied baseline: ", baseline) break } } @@ -142,7 +143,7 @@ func (s *LeastLoadStrategy) getNodes(candidates []string, maxRTT time.Duration) } observeResult, err := s.observer.GetObservation(s.ctx) if err != nil { - newError("cannot get observation").Base(err).WriteToLog() + errors.LogInfoInner(s.ctx, err, "cannot get observation") return make([]*node, 0) } diff --git a/app/router/strategy_leastping.go b/app/router/strategy_leastping.go index 09ff845f..28efe386 100644 --- a/app/router/strategy_leastping.go +++ b/app/router/strategy_leastping.go @@ -5,6 +5,7 @@ import ( "github.com/xtls/xray-core/app/observatory" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/features/extension" ) @@ -32,7 +33,7 @@ func (l *LeastPingStrategy) PickOutbound(strings []string) string { observeReport, err := l.observatory.GetObservation(l.ctx) if err != nil { - newError("cannot get observe report").Base(err).WriteToLog() + errors.LogInfoInner(l.ctx, err, "cannot get observe report") return "" } outboundsList := outboundList(strings) diff --git a/app/router/weight.go b/app/router/weight.go index c235740d..1bba645e 100644 --- a/app/router/weight.go +++ b/app/router/weight.go @@ -1,10 +1,13 @@ package router import ( + "context" "regexp" "strconv" "strings" "sync" + + "github.com/xtls/xray-core/common/errors" ) type weightScaler func(value, weight float64) float64 @@ -64,7 +67,7 @@ func (s *WeightManager) findValue(tag string) float64 { } weight, err := strconv.ParseFloat(numStr, 64) if err != nil { - newError("unexpected error from ParseFloat: ", err).AtError().WriteToLog() + errors.LogError(context.Background(), "unexpected error from ParseFloat: ", err) return s.defaultWeight } return weight @@ -82,7 +85,7 @@ func (s *WeightManager) getMatch(tag, find string, isRegexp bool) string { } r, err := regexp.Compile(find) if err != nil { - newError("invalid regexp: ", find, "err: ", err).AtError().WriteToLog() + errors.LogError(context.Background(), "invalid regexp: ", find, "err: ", err) return "" } return r.FindString(tag) diff --git a/app/stats/channel.go b/app/stats/channel.go index 99f3890c..b32850d3 100644 --- a/app/stats/channel.go +++ b/app/stats/channel.go @@ -5,6 +5,7 @@ import ( "sync" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" ) // Channel is an implementation of stats.Channel. @@ -44,7 +45,7 @@ func (c *Channel) Subscribe() (chan interface{}, error) { c.access.Lock() defer c.access.Unlock() if c.subsLimit > 0 && len(c.subscribers) >= c.subsLimit { - return nil, newError("Number of subscribers has reached limit") + return nil, errors.New("Number of subscribers has reached limit") } subscriber := make(chan interface{}, c.bufferSize) c.subscribers = append(c.subscribers, subscriber) diff --git a/app/stats/command/command.go b/app/stats/command/command.go index 24dc3db6..2c603ca2 100644 --- a/app/stats/command/command.go +++ b/app/stats/command/command.go @@ -9,6 +9,7 @@ import ( "github.com/xtls/xray-core/app/stats" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/strmatcher" "github.com/xtls/xray-core/core" feature_stats "github.com/xtls/xray-core/features/stats" @@ -31,7 +32,7 @@ func NewStatsServer(manager feature_stats.Manager) StatsServiceServer { func (s *statsServer) GetStats(ctx context.Context, request *GetStatsRequest) (*GetStatsResponse, error) { c := s.stats.GetCounter(request.Name) if c == nil { - return nil, newError(request.Name, " not found.") + return nil, errors.New(request.Name, " not found.") } var value int64 if request.Reset_ { @@ -57,7 +58,7 @@ func (s *statsServer) QueryStats(ctx context.Context, request *QueryStatsRequest manager, ok := s.stats.(*stats.Manager) if !ok { - return nil, newError("QueryStats only works its own stats.Manager.") + return nil, errors.New("QueryStats only works its own stats.Manager.") } manager.VisitCounters(func(name string, c feature_stats.Counter) bool { diff --git a/app/stats/command/errors.generated.go b/app/stats/command/errors.generated.go deleted file mode 100644 index a1305932..00000000 --- a/app/stats/command/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package command - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/stats/errors.generated.go b/app/stats/errors.generated.go deleted file mode 100644 index c64386f3..00000000 --- a/app/stats/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package stats - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/app/stats/stats.go b/app/stats/stats.go index c82277c3..95d5ae9c 100644 --- a/app/stats/stats.go +++ b/app/stats/stats.go @@ -40,9 +40,9 @@ func (m *Manager) RegisterCounter(name string) (stats.Counter, error) { defer m.access.Unlock() if _, found := m.counters[name]; found { - return nil, newError("Counter ", name, " already registered.") + return nil, errors.New("Counter ", name, " already registered.") } - newError("create new counter ", name).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "create new counter ", name) c := new(Counter) m.counters[name] = c return c, nil @@ -54,7 +54,7 @@ func (m *Manager) UnregisterCounter(name string) error { defer m.access.Unlock() if _, found := m.counters[name]; found { - newError("remove counter ", name).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "remove counter ", name) delete(m.counters, name) } return nil @@ -89,9 +89,9 @@ func (m *Manager) RegisterChannel(name string) (stats.Channel, error) { defer m.access.Unlock() if _, found := m.channels[name]; found { - return nil, newError("Channel ", name, " already registered.") + return nil, errors.New("Channel ", name, " already registered.") } - newError("create new channel ", name).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "create new channel ", name) c := NewChannel(&ChannelConfig{BufferSize: 64, Blocking: false}) m.channels[name] = c if m.running { @@ -106,7 +106,7 @@ func (m *Manager) UnregisterChannel(name string) error { defer m.access.Unlock() if c, found := m.channels[name]; found { - newError("remove channel ", name).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "remove channel ", name) delete(m.channels, name) return c.Close() } @@ -148,7 +148,7 @@ func (m *Manager) Close() error { m.running = false errs := []error{} for name, channel := range m.channels { - newError("remove channel ", name).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "remove channel ", name) delete(m.channels, name) if err := channel.Close(); err != nil { errs = append(errs, err) diff --git a/common/buf/buffer.go b/common/buf/buffer.go index 82795b98..57105d67 100644 --- a/common/buf/buffer.go +++ b/common/buf/buffer.go @@ -4,6 +4,7 @@ import ( "io" "github.com/xtls/xray-core/common/bytespool" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" ) @@ -226,7 +227,7 @@ func (b *Buffer) Write(data []byte) (int, error) { // WriteByte writes a single byte into the buffer. func (b *Buffer) WriteByte(v byte) error { if b.IsFull() { - return newError("buffer full") + return errors.New("buffer full") } b.v[b.end] = v b.end++ @@ -286,7 +287,7 @@ func (b *Buffer) ReadFullFrom(reader io.Reader, size int32) (int64, error) { end := b.end + size if end > int32(len(b.v)) { v := end - return 0, newError("out of bound: ", v) + return 0, errors.New("out of bound: ", v) } n, err := io.ReadFull(reader, b.v[b.end:end]) b.end += int32(n) diff --git a/common/buf/copy.go b/common/buf/copy.go index 3096dc57..4cc3be88 100644 --- a/common/buf/copy.go +++ b/common/buf/copy.go @@ -120,7 +120,7 @@ func Copy(reader Reader, writer Writer, options ...CopyOption) error { return nil } -var ErrNotTimeoutReader = newError("not a TimeoutReader") +var ErrNotTimeoutReader = errors.New("not a TimeoutReader") func CopyOnceTimeout(reader Reader, writer Writer, timeout time.Duration) error { timeoutReader, ok := reader.(TimeoutReader) diff --git a/common/buf/copy_test.go b/common/buf/copy_test.go index cb2f831b..3c896801 100644 --- a/common/buf/copy_test.go +++ b/common/buf/copy_test.go @@ -27,7 +27,7 @@ func TestReadError(t *testing.T) { t.Error("expected to be ReadError, but not") } - if err.Error() != "error" { + if err.Error() != "common/buf_test: error" { t.Fatal("unexpected error message: ", err.Error()) } } @@ -48,7 +48,7 @@ func TestWriteError(t *testing.T) { t.Error("expected to be WriteError, but not") } - if err.Error() != "error" { + if err.Error() != "common/buf_test: error" { t.Fatal("unexpected error message: ", err.Error()) } } diff --git a/common/buf/errors.generated.go b/common/buf/errors.generated.go deleted file mode 100644 index 032c0701..00000000 --- a/common/buf/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package buf - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/buf/io.go b/common/buf/io.go index f0b7689c..0974b4f3 100644 --- a/common/buf/io.go +++ b/common/buf/io.go @@ -1,12 +1,14 @@ package buf import ( + "context" "io" "net" "os" "syscall" "time" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/features/stats" "github.com/xtls/xray-core/transport/internet/stat" ) @@ -18,7 +20,7 @@ type Reader interface { } // ErrReadTimeout is an error that happens with IO timeout. -var ErrReadTimeout = newError("IO timeout") +var ErrReadTimeout = errors.New("IO timeout") // TimeoutReader is a reader that returns error if Read() operation takes longer than the given timeout. type TimeoutReader interface { @@ -74,7 +76,7 @@ func NewReader(reader io.Reader) Reader { if sc, ok := reader.(syscall.Conn); ok { rawConn, err := sc.SyscallConn() if err != nil { - newError("failed to get sysconn").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to get sysconn") } else { var counter stats.Counter diff --git a/common/buf/reader.go b/common/buf/reader.go index 3e35ad62..c6c50274 100644 --- a/common/buf/reader.go +++ b/common/buf/reader.go @@ -21,7 +21,7 @@ func readOneUDP(r io.Reader) (*Buffer, error) { } b.Release() - return nil, newError("Reader returns too many empty payloads.") + return nil, errors.New("Reader returns too many empty payloads.") } // ReadBuffer reads a Buffer from the given reader. diff --git a/common/crypto/auth.go b/common/crypto/auth.go index 0bc8e71d..6259e2a7 100644 --- a/common/crypto/auth.go +++ b/common/crypto/auth.go @@ -8,6 +8,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/bytespool" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" ) @@ -63,7 +64,7 @@ type AEADAuthenticator struct { func (v *AEADAuthenticator) Open(dst, cipherText []byte) ([]byte, error) { iv := v.NonceGenerator() if len(iv) != v.AEAD.NonceSize() { - return nil, newError("invalid AEAD nonce size: ", len(iv)) + return nil, errors.New("invalid AEAD nonce size: ", len(iv)) } var additionalData []byte @@ -76,7 +77,7 @@ func (v *AEADAuthenticator) Open(dst, cipherText []byte) ([]byte, error) { func (v *AEADAuthenticator) Seal(dst, plainText []byte) ([]byte, error) { iv := v.NonceGenerator() if len(iv) != v.AEAD.NonceSize() { - return nil, newError("invalid AEAD nonce size: ", len(iv)) + return nil, errors.New("invalid AEAD nonce size: ", len(iv)) } var additionalData []byte @@ -131,7 +132,7 @@ func (r *AuthenticationReader) readSize() (uint16, uint16, error) { return size, padding, err } -var errSoft = newError("waiting for more data") +var errSoft = errors.New("waiting for more data") func (r *AuthenticationReader) readBuffer(size int32, padding int32) (*buf.Buffer, error) { b := buf.New() @@ -255,7 +256,7 @@ func (w *AuthenticationWriter) seal(b []byte) (*buf.Buffer, error) { sizeBytes := w.sizeParser.SizeBytes() totalSize := sizeBytes + encryptedSize + paddingSize if totalSize > buf.Size { - return nil, newError("size too large: ", totalSize) + return nil, errors.New("size too large: ", totalSize) } eb := buf.New() diff --git a/common/crypto/errors.generated.go b/common/crypto/errors.generated.go deleted file mode 100644 index 2d983f89..00000000 --- a/common/crypto/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package crypto - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/ctx/context.go b/common/ctx/context.go new file mode 100644 index 00000000..94a57902 --- /dev/null +++ b/common/ctx/context.go @@ -0,0 +1,25 @@ +package ctx + +import "context" + +type SessionKey int + +// ID of a session. +type ID uint32 + +const( + idSessionKey SessionKey = 0 +) + +// ContextWithID returns a new context with the given ID. +func ContextWithID(ctx context.Context, id ID) context.Context { + return context.WithValue(ctx, idSessionKey, id) +} + +// IDFromContext returns ID in this context, or 0 if not contained. +func IDFromContext(ctx context.Context) ID { + if id, ok := ctx.Value(idSessionKey).(ID); ok { + return id + } + return 0 +} diff --git a/common/drain/drainer.go b/common/drain/drainer.go index bb1ae68a..16ed1f23 100644 --- a/common/drain/drainer.go +++ b/common/drain/drainer.go @@ -4,6 +4,7 @@ import ( "io" "github.com/xtls/xray-core/common/dice" + "github.com/xtls/xray-core/common/errors" ) type BehaviorSeedLimitedDrainer struct { @@ -27,9 +28,9 @@ func (d *BehaviorSeedLimitedDrainer) Drain(reader io.Reader) error { if d.DrainSize > 0 { err := drainReadN(reader, d.DrainSize) if err == nil { - return newError("drained connection") + return errors.New("drained connection") } - return newError("unable to drain connection").Base(err) + return errors.New("unable to drain connection").Base(err) } return nil } @@ -44,7 +45,7 @@ func WithError(drainer Drainer, reader io.Reader, err error) error { if drainErr == nil { return err } - return newError(drainErr).Base(err) + return errors.New(drainErr).Base(err) } type NopDrainer struct{} diff --git a/common/drain/errors.generated.go b/common/drain/errors.generated.go deleted file mode 100644 index 1535361e..00000000 --- a/common/drain/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package drain - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/errors.generated.go b/common/errors.generated.go deleted file mode 100644 index 28b9a625..00000000 --- a/common/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package common - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/errors/errorgen/main.go b/common/errors/errorgen/main.go deleted file mode 100644 index 4532fd8d..00000000 --- a/common/errors/errorgen/main.go +++ /dev/null @@ -1,37 +0,0 @@ -package main - -import ( - "fmt" - "os" - "path/filepath" -) - -func main() { - pwd, err := os.Getwd() - if err != nil { - fmt.Println("can not get current working directory") - os.Exit(1) - } - pkg := filepath.Base(pwd) - if pkg == "xray-core" { - pkg = "core" - } - - file, err := os.OpenFile("errors.generated.go", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644) - if err != nil { - fmt.Printf("Failed to generate errors.generated.go: %v", err) - os.Exit(1) - } - defer file.Close() - - fmt.Fprintf(file, `package %s - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} -`, pkg) -} diff --git a/common/errors/errors.go b/common/errors/errors.go index ef1dd6f9..1915144a 100644 --- a/common/errors/errors.go +++ b/common/errors/errors.go @@ -2,9 +2,11 @@ package errors // import "github.com/xtls/xray-core/common/errors" import ( - "reflect" + "context" + "runtime" "strings" + c "github.com/xtls/xray-core/common/ctx" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/serial" ) @@ -22,29 +24,13 @@ type hasSeverity interface { // Error is an error object with underlying error. type Error struct { - pathObj interface{} prefix []interface{} message []interface{} + caller string inner error severity log.Severity } -func (err *Error) WithPathObj(obj interface{}) *Error { - err.pathObj = obj - return err -} - -func (err *Error) pkgPath() string { - if err.pathObj == nil { - return "" - } - path := reflect.TypeOf(err.pathObj).PkgPath() - if len(path) >= trim { - return path[trim:] - } - return path -} - // Error implements error.Error(). func (err *Error) Error() string { builder := strings.Builder{} @@ -54,9 +40,8 @@ func (err *Error) Error() string { builder.WriteString("] ") } - path := err.pkgPath() - if len(path) > 0 { - builder.WriteString(path) + if len(err.caller) > 0 { + builder.WriteString(err.caller) builder.WriteString(": ") } @@ -129,24 +114,6 @@ func (err *Error) String() string { return err.Error() } -// WriteToLog writes current error into log. -func (err *Error) WriteToLog(opts ...ExportOption) { - var holder ExportOptionHolder - - for _, opt := range opts { - opt(&holder) - } - - if holder.SessionID > 0 { - err.prefix = append(err.prefix, holder.SessionID) - } - - log.Record(&log.GeneralMessage{ - Severity: GetSeverity(err), - Content: err, - }) -} - type ExportOptionHolder struct { SessionID uint32 } @@ -155,12 +122,82 @@ type ExportOption func(*ExportOptionHolder) // New returns a new error object with message formed from given arguments. func New(msg ...interface{}) *Error { + pc, _, _, _ := runtime.Caller(1) + details := runtime.FuncForPC(pc).Name() + if len(details) >= trim { + details = details[trim:] + } + i := strings.Index(details, ".") + if i > 0 { + details = details[:i] + } return &Error{ message: msg, severity: log.Severity_Info, + caller: details, } } +func LogDebug(ctx context.Context, msg ...interface{}) { + doLog(ctx, nil, log.Severity_Debug, msg...) +} + +func LogDebugInner(ctx context.Context, inner error, msg ...interface{}) { + doLog(ctx, inner, log.Severity_Debug, msg...) +} + +func LogInfo(ctx context.Context, msg ...interface{}) { + doLog(ctx, nil, log.Severity_Info, msg...) +} + +func LogInfoInner(ctx context.Context, inner error, msg ...interface{}) { + doLog(ctx, inner, log.Severity_Debug, msg...) +} + +func LogWarning(ctx context.Context, msg ...interface{}) { + doLog(ctx, nil, log.Severity_Warning, msg...) +} + +func LogWarningInner(ctx context.Context, inner error, msg ...interface{}) { + doLog(ctx, inner, log.Severity_Debug, msg...) +} + +func LogError(ctx context.Context, msg ...interface{}) { + doLog(ctx, nil, log.Severity_Error, msg...) +} + +func LogErrorInner(ctx context.Context, inner error, msg ...interface{}) { + doLog(ctx, inner, log.Severity_Debug, msg...) +} + +func doLog(ctx context.Context, inner error, severity log.Severity, msg ...interface{}) { + pc, _, _, _ := runtime.Caller(2) + details := runtime.FuncForPC(pc).Name() + if len(details) >= trim { + details = details[trim:] + } + i := strings.Index(details, ".") + if i > 0 { + details = details[:i] + } + err := &Error{ + message: msg, + severity: severity, + caller: details, + inner: inner, + } + if ctx != nil && ctx != context.Background() { + id := uint32(c.IDFromContext(ctx)) + if id > 0 { + err.prefix = append(err.prefix, id) + } + } + log.Record(&log.GeneralMessage{ + Severity: GetSeverity(err), + Content: err, + }) +} + // Cause returns the root cause of this error. func Cause(err error) error { if err == nil { diff --git a/common/errors/errors_test.go b/common/errors/errors_test.go index a38e8733..3a1cb134 100644 --- a/common/errors/errors_test.go +++ b/common/errors/errors_test.go @@ -36,20 +36,14 @@ func TestError(t *testing.T) { } } -type e struct{} - func TestErrorMessage(t *testing.T) { data := []struct { err error msg string }{ { - err: New("a").Base(New("b")).WithPathObj(e{}), - msg: "common/errors_test: a > b", - }, - { - err: New("a").Base(New("b").WithPathObj(e{})), - msg: "a > common/errors_test: b", + err: New("a").Base(New("b")), + msg: "common/errors_test: a > common/errors_test: b", }, } diff --git a/common/mux/client.go b/common/mux/client.go index 2537f02b..1cbc530a 100644 --- a/common/mux/client.go +++ b/common/mux/client.go @@ -37,7 +37,7 @@ func (m *ClientManager) Dispatch(ctx context.Context, link *transport.Link) erro } } - return newError("unable to find an available mux client").AtWarning() + return errors.New("unable to find an available mux client").AtWarning() } type WorkerPicker interface { @@ -57,7 +57,7 @@ func (p *IncrementalWorkerPicker) cleanupFunc() error { defer p.access.Unlock() if len(p.workers) == 0 { - return newError("no worker") + return errors.New("no worker") } p.cleanup() @@ -155,7 +155,7 @@ func (f *DialingWorkerFactory) Create() (*ClientWorker, error) { ctx, cancel := context.WithCancel(ctx) if err := p.Process(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter}, d); err != nil { - errors.New("failed to handler mux client connection").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "failed to handler mux client connection") } common.Must(c.Close()) cancel() @@ -244,7 +244,7 @@ func writeFirstPayload(reader buf.Reader, writer *Writer) error { func fetchInput(ctx context.Context, s *Session, output buf.Writer) { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] transferType := protocol.TransferTypeStream if ob.Target.Network == net.Network_UDP { transferType = protocol.TransferTypePacket @@ -254,15 +254,15 @@ func fetchInput(ctx context.Context, s *Session, output buf.Writer) { defer s.Close(false) defer writer.Close() - newError("dispatching request to ", ob.Target).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "dispatching request to ", ob.Target) if err := writeFirstPayload(s.input, writer); err != nil { - newError("failed to write first payload").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to write first payload") writer.hasError = true return } if err := buf.Copy(s.input, writer); err != nil { - newError("failed to fetch all input").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to fetch all input") writer.hasError = true return } @@ -335,7 +335,7 @@ func (m *ClientWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.Buffere rr := s.NewReader(reader, &meta.Target) err := buf.Copy(rr, s.output) if err != nil && buf.IsWriteError(err) { - newError("failed to write to downstream. closing session ", s.ID).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to write to downstream. closing session ", s.ID) s.Close(false) return buf.Copy(rr, buf.Discard) } @@ -365,7 +365,7 @@ func (m *ClientWorker) fetchOutput() { err := meta.Unmarshal(reader) if err != nil { if errors.Cause(err) != io.EOF { - newError("failed to read metadata").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to read metadata") } break } @@ -381,12 +381,12 @@ func (m *ClientWorker) fetchOutput() { err = m.handleStatusKeep(&meta, reader) default: status := meta.SessionStatus - newError("unknown status: ", status).AtError().WriteToLog() + errors.LogError(context.Background(), "unknown status: ", status) return } if err != nil { - newError("failed to process data").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to process data") return } } diff --git a/common/mux/errors.generated.go b/common/mux/errors.generated.go deleted file mode 100644 index 9318ceac..00000000 --- a/common/mux/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package mux - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/mux/frame.go b/common/mux/frame.go index d53ac202..bdf5cc8c 100644 --- a/common/mux/frame.go +++ b/common/mux/frame.go @@ -7,6 +7,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/bitmask" "github.com/xtls/xray-core/common/buf" + "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" @@ -102,7 +103,7 @@ func (f *FrameMetadata) Unmarshal(reader io.Reader) error { return err } if metaLen > 512 { - return newError("invalid metalen ", metaLen).AtError() + return errors.New("invalid metalen ", metaLen).AtError() } b := buf.New() @@ -118,7 +119,7 @@ func (f *FrameMetadata) Unmarshal(reader io.Reader) error { // Visible for testing only. func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer) error { if b.Len() < 4 { - return newError("insufficient buffer: ", b.Len()) + return errors.New("insufficient buffer: ", b.Len()) } f.SessionID = binary.BigEndian.Uint16(b.BytesTo(2)) @@ -129,14 +130,14 @@ func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer) error { if f.SessionStatus == SessionStatusNew || (f.SessionStatus == SessionStatusKeep && b.Len() > 4 && TargetNetwork(b.Byte(4)) == TargetNetworkUDP) { // MUST check the flag first if b.Len() < 8 { - return newError("insufficient buffer: ", b.Len()) + return errors.New("insufficient buffer: ", b.Len()) } network := TargetNetwork(b.Byte(4)) b.Advance(5) addr, port, err := addrParser.ReadAddressPort(nil, b) if err != nil { - return newError("failed to parse address and port").Base(err) + return errors.New("failed to parse address and port").Base(err) } switch network { @@ -145,7 +146,7 @@ func (f *FrameMetadata) UnmarshalFromBuffer(b *buf.Buffer) error { case TargetNetworkUDP: f.Target = net.UDPDestination(addr, port) default: - return newError("unknown network type: ", network) + return errors.New("unknown network type: ", network) } } diff --git a/common/mux/reader.go b/common/mux/reader.go index 31c008c3..b9714cdf 100644 --- a/common/mux/reader.go +++ b/common/mux/reader.go @@ -5,6 +5,7 @@ import ( "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/crypto" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/serial" ) @@ -37,7 +38,7 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { } if size > buf.Size { - return nil, newError("packet size too large: ", size) + return nil, errors.New("packet size too large: ", size) } b := buf.New() diff --git a/common/mux/server.go b/common/mux/server.go index 2d33189f..5a4e9974 100644 --- a/common/mux/server.go +++ b/common/mux/server.go @@ -94,7 +94,7 @@ func NewServerWorker(ctx context.Context, d routing.Dispatcher, link *transport. func handle(ctx context.Context, s *Session, output buf.Writer) { writer := NewResponseWriter(s.ID, output, s.transferType) if err := buf.Copy(s.input, writer); err != nil { - newError("session ", s.ID, " ends.").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "session ", s.ID, " ends.") writer.hasError = true } @@ -118,7 +118,7 @@ func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *buf.Bu } func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error { - newError("received request for ", meta.Target).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "received request for ", meta.Target) { msg := &log.AccessMessage{ To: meta.Target, @@ -134,7 +134,7 @@ func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, if network := session.AllowedNetworkFromContext(ctx); network != net.Network_Unknown { if meta.Target.Network != network { - return newError("unexpected network ", meta.Target.Network) // it will break the whole Mux connection + return errors.New("unexpected network ", meta.Target.Network) // it will break the whole Mux connection } } @@ -152,7 +152,7 @@ func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, } else { if x.Status == Initializing { // nearly impossible XUDPManager.Unlock() - newError("XUDP hit ", meta.GlobalID).Base(errors.New("conflict")).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, errors.New("conflict"), "XUDP hit ", meta.GlobalID) // It's not a good idea to return an err here, so just let client wait. // Client will receive an End frame after sending a Keep frame. return nil @@ -170,7 +170,7 @@ func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, b.Release() mb = nil } - newError("XUDP hit ", meta.GlobalID).Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err,"XUDP hit ", meta.GlobalID) } if mb != nil { ctx = session.ContextWithTimeoutOnly(ctx, true) @@ -180,7 +180,7 @@ func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, XUDPManager.Lock() delete(XUDPManager.Map, x.GlobalID) XUDPManager.Unlock() - err = newError("XUDP new ", meta.GlobalID).Base(errors.New("failed to dispatch request to ", meta.Target).Base(err)) + err = errors.New("XUDP new ", meta.GlobalID).Base(errors.New("failed to dispatch request to ", meta.Target).Base(err)) return err // it will break the whole Mux connection } link.Writer.WriteMultiBuffer(mb) // it's meaningless to test a new pipe @@ -188,7 +188,7 @@ func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, input: link.Reader, output: link.Writer, } - newError("XUDP new ", meta.GlobalID).Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "XUDP new ", meta.GlobalID) } x.Mux = &Session{ input: x.Mux.input, @@ -211,7 +211,7 @@ func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, if meta.Option.Has(OptionData) { buf.Copy(NewStreamReader(reader), buf.Discard) } - return newError("failed to dispatch request.").Base(err) + return errors.New("failed to dispatch request.").Base(err) } s := &Session{ input: link.Reader, @@ -255,7 +255,7 @@ func (w *ServerWorker) handleStatusKeep(meta *FrameMetadata, reader *buf.Buffere err := buf.Copy(rr, s.output) if err != nil && buf.IsWriteError(err) { - newError("failed to write to downstream writer. closing session ", s.ID).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to write to downstream writer. closing session ", s.ID) s.Close(false) return buf.Copy(rr, buf.Discard) } @@ -277,7 +277,7 @@ func (w *ServerWorker) handleFrame(ctx context.Context, reader *buf.BufferedRead var meta FrameMetadata err := meta.Unmarshal(reader) if err != nil { - return newError("failed to read metadata").Base(err) + return errors.New("failed to read metadata").Base(err) } switch meta.SessionStatus { @@ -291,11 +291,11 @@ func (w *ServerWorker) handleFrame(ctx context.Context, reader *buf.BufferedRead err = w.handleStatusKeep(&meta, reader) default: status := meta.SessionStatus - return newError("unknown status: ", status).AtError() + return errors.New("unknown status: ", status).AtError() } if err != nil { - return newError("failed to process data").Base(err) + return errors.New("failed to process data").Base(err) } return nil } @@ -314,7 +314,7 @@ func (w *ServerWorker) run(ctx context.Context) { err := w.handleFrame(ctx, reader) if err != nil { if errors.Cause(err) != io.EOF { - newError("unexpected EOF").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "unexpected EOF") common.Interrupt(input) } return diff --git a/common/mux/session.go b/common/mux/session.go index 69597440..5e4b69ca 100644 --- a/common/mux/session.go +++ b/common/mux/session.go @@ -1,6 +1,7 @@ package mux import ( + "context" "io" "runtime" "sync" @@ -8,6 +9,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "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/transport/pipe" @@ -180,7 +182,7 @@ func (s *Session) Close(locked bool) error { if s.XUDP.Status == Active { s.XUDP.Expire = time.Now().Add(time.Minute) s.XUDP.Status = Expiring - newError("XUDP put ", s.XUDP.GlobalID).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "XUDP put ", s.XUDP.GlobalID) } XUDPManager.Unlock() } @@ -230,7 +232,7 @@ func init() { if x.Status == Expiring && now.After(x.Expire) { x.Interrupt() delete(XUDPManager.Map, id) - newError("XUDP del ", id).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "XUDP del ", id) } } XUDPManager.Unlock() diff --git a/common/net/address.go b/common/net/address.go index 9ba8c473..a5f7c160 100644 --- a/common/net/address.go +++ b/common/net/address.go @@ -2,8 +2,11 @@ package net import ( "bytes" + "context" "net" "strings" + + "github.com/xtls/xray-core/common/errors" ) var ( @@ -112,7 +115,7 @@ func IPAddress(ip []byte) Address { } return addr default: - newError("invalid IP format: ", ip).AtError().WriteToLog() + errors.LogError(context.Background(), "invalid IP format: ", ip) return nil } } diff --git a/common/net/errors.generated.go b/common/net/errors.generated.go deleted file mode 100644 index fb64eac5..00000000 --- a/common/net/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package net - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/net/port.go b/common/net/port.go index 2a0bf637..d4a6514c 100644 --- a/common/net/port.go +++ b/common/net/port.go @@ -3,6 +3,8 @@ package net import ( "encoding/binary" "strconv" + + "github.com/xtls/xray-core/common/errors" ) // Port represents a network port in TCP and UDP protocol. @@ -18,7 +20,7 @@ func PortFromBytes(port []byte) Port { // @error when the integer is not positive or larger then 65535 func PortFromInt(val uint32) (Port, error) { if val > 65535 { - return Port(0), newError("invalid port range: ", val) + return Port(0), errors.New("invalid port range: ", val) } return Port(val), nil } @@ -28,7 +30,7 @@ func PortFromInt(val uint32) (Port, error) { func PortFromString(s string) (Port, error) { val, err := strconv.ParseUint(s, 10, 32) if err != nil { - return Port(0), newError("invalid port range: ", s) + return Port(0), errors.New("invalid port range: ", s) } return PortFromInt(uint32(val)) } diff --git a/common/ocsp/errors.generated.go b/common/ocsp/errors.generated.go deleted file mode 100644 index 4bdbc25c..00000000 --- a/common/ocsp/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package ocsp - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/ocsp/ocsp.go b/common/ocsp/ocsp.go index b2c0bc58..d67670af 100644 --- a/common/ocsp/ocsp.go +++ b/common/ocsp/ocsp.go @@ -8,6 +8,7 @@ import ( "net/http" "os" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/platform/filesystem" "golang.org/x/crypto/ocsp" ) @@ -63,26 +64,26 @@ func GetOCSPForCert(cert [][]byte) ([]byte, error) { } issuedCert := certificates[0] if len(issuedCert.OCSPServer) == 0 { - return nil, newError("no OCSP server specified in cert") + return nil, errors.New("no OCSP server specified in cert") } if len(certificates) == 1 { if len(issuedCert.IssuingCertificateURL) == 0 { - return nil, newError("no issuing certificate URL") + return nil, errors.New("no issuing certificate URL") } resp, errC := http.Get(issuedCert.IssuingCertificateURL[0]) if errC != nil { - return nil, newError("no issuing certificate URL") + return nil, errors.New("no issuing certificate URL") } defer resp.Body.Close() issuerBytes, errC := io.ReadAll(resp.Body) if errC != nil { - return nil, newError(errC) + return nil, errors.New(errC) } issuerCert, errC := x509.ParseCertificate(issuerBytes) if errC != nil { - return nil, newError(errC) + return nil, errors.New(errC) } certificates = append(certificates, issuerCert) @@ -96,12 +97,12 @@ func GetOCSPForCert(cert [][]byte) ([]byte, error) { reader := bytes.NewReader(ocspReq) req, err := http.Post(issuedCert.OCSPServer[0], "application/ocsp-request", reader) if err != nil { - return nil, newError(err) + return nil, errors.New(err) } defer req.Body.Close() ocspResBytes, err := io.ReadAll(req.Body) if err != nil { - return nil, newError(err) + return nil, errors.New(err) } return ocspResBytes, nil } @@ -128,7 +129,7 @@ func parsePEMBundle(bundle []byte) ([]*x509.Certificate, error) { } if len(certificates) == 0 { - return nil, newError("no certificates were found while parsing the bundle") + return nil, errors.New("no certificates were found while parsing the bundle") } return certificates, nil diff --git a/common/platform/ctlcmd/ctlcmd.go b/common/platform/ctlcmd/ctlcmd.go index ad9550fa..a5c21872 100644 --- a/common/platform/ctlcmd/ctlcmd.go +++ b/common/platform/ctlcmd/ctlcmd.go @@ -1,12 +1,14 @@ package ctlcmd import ( + "context" "io" "os" "os/exec" "strings" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/platform" ) @@ -15,7 +17,7 @@ import ( func Run(args []string, input io.Reader) (buf.MultiBuffer, error) { xctl := platform.GetToolLocation("xctl") if _, err := os.Stat(xctl); err != nil { - return nil, newError("xctl doesn't exist").Base(err) + return nil, errors.New("xctl doesn't exist").Base(err) } var errBuffer buf.MultiBufferContainer @@ -30,7 +32,7 @@ func Run(args []string, input io.Reader) (buf.MultiBuffer, error) { } if err := cmd.Start(); err != nil { - return nil, newError("failed to start xctl").Base(err) + return nil, errors.New("failed to start xctl").Base(err) } if err := cmd.Wait(); err != nil { @@ -38,12 +40,12 @@ func Run(args []string, input io.Reader) (buf.MultiBuffer, error) { if errBuffer.Len() > 0 { msg += ": \n" + strings.TrimSpace(errBuffer.MultiBuffer.String()) } - return nil, newError(msg).Base(err) + return nil, errors.New(msg).Base(err) } // log stderr, info message if !errBuffer.IsEmpty() { - newError(" \n", strings.TrimSpace(errBuffer.MultiBuffer.String())).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), " \n", strings.TrimSpace(errBuffer.MultiBuffer.String())) } return outBuffer.MultiBuffer, nil diff --git a/common/platform/ctlcmd/errors.generated.go b/common/platform/ctlcmd/errors.generated.go deleted file mode 100644 index c861825c..00000000 --- a/common/platform/ctlcmd/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package ctlcmd - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/protocol/address.go b/common/protocol/address.go index cf52a380..0dcb8165 100644 --- a/common/protocol/address.go +++ b/common/protocol/address.go @@ -5,6 +5,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/serial" ) @@ -181,12 +182,12 @@ func (p *addressParser) readAddress(b *buf.Buffer, reader io.Reader) (net.Addres } if addrType >= 16 { - return nil, newError("unknown address type: ", addrType) + return nil, errors.New("unknown address type: ", addrType) } addrFamily := p.addrTypeMap[addrType] if addrFamily == net.AddressFamily(afInvalid) { - return nil, newError("unknown address type: ", addrType) + return nil, errors.New("unknown address type: ", addrType) } switch addrFamily { @@ -216,7 +217,7 @@ func (p *addressParser) readAddress(b *buf.Buffer, reader io.Reader) (net.Addres } } if !isValidDomain(domain) { - return nil, newError("invalid domain name: ", domain) + return nil, errors.New("invalid domain name: ", domain) } return net.DomainAddress(domain), nil default: @@ -227,7 +228,7 @@ func (p *addressParser) readAddress(b *buf.Buffer, reader io.Reader) (net.Addres func (p *addressParser) writeAddress(writer io.Writer, address net.Address) error { tb := p.addrByteMap[address.Family()] if tb == afInvalid { - return newError("unknown address family", address.Family()) + return errors.New("unknown address family", address.Family()) } switch address.Family() { @@ -241,7 +242,7 @@ func (p *addressParser) writeAddress(writer io.Writer, address net.Address) erro case net.AddressFamilyDomain: domain := address.Domain() if isDomainTooLong(domain) { - return newError("Super long domain is not supported: ", domain) + return errors.New("Super long domain is not supported: ", domain) } if _, err := writer.Write([]byte{tb, byte(len(domain))}); err != nil { diff --git a/common/protocol/dns/errors.generated.go b/common/protocol/dns/errors.generated.go deleted file mode 100644 index d7375a9b..00000000 --- a/common/protocol/dns/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package dns - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/protocol/dns/io.go b/common/protocol/dns/io.go index 0c215a70..dd88b61d 100644 --- a/common/protocol/dns/io.go +++ b/common/protocol/dns/io.go @@ -6,6 +6,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/serial" "golang.org/x/net/dns/dnsmessage" ) @@ -96,7 +97,7 @@ func (r *TCPReader) ReadMessage() (*buf.Buffer, error) { return nil, err } if size > buf.Size { - return nil, newError("message size too large: ", size) + return nil, errors.New("message size too large: ", size) } b := buf.New() if _, err := b.ReadFullFrom(r.reader, int32(size)); err != nil { diff --git a/common/protocol/errors.generated.go b/common/protocol/errors.generated.go deleted file mode 100644 index 694dd667..00000000 --- a/common/protocol/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package protocol - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/protocol/tls/cert/cert.go b/common/protocol/tls/cert/cert.go index cd8e56f5..5bd92a5c 100644 --- a/common/protocol/tls/cert/cert.go +++ b/common/protocol/tls/cert/cert.go @@ -13,6 +13,7 @@ import ( "time" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" ) //go:generate go run github.com/xtls/xray-core/common/errors/errorgen @@ -27,11 +28,11 @@ type Certificate struct { func ParseCertificate(certPEM []byte, keyPEM []byte) (*Certificate, error) { certBlock, _ := pem.Decode(certPEM) if certBlock == nil { - return nil, newError("failed to decode certificate") + return nil, errors.New("failed to decode certificate") } keyBlock, _ := pem.Decode(keyPEM) if keyBlock == nil { - return nil, newError("failed to decode key") + return nil, errors.New("failed to decode key") } return &Certificate{ Certificate: certBlock.Bytes, @@ -116,7 +117,7 @@ func Generate(parent *Certificate, opts ...Option) (*Certificate, error) { // higher signing performance than RSA2048 selfKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { - return nil, newError("failed to generate self private key").Base(err) + return nil, errors.New("failed to generate self private key").Base(err) } parentKey = selfKey if parent != nil { @@ -128,7 +129,7 @@ func Generate(parent *Certificate, opts ...Option) (*Certificate, error) { pKey, err = x509.ParsePKCS1PrivateKey(parent.PrivateKey) } if err != nil { - return nil, newError("failed to parse parent private key").Base(err) + return nil, errors.New("failed to parse parent private key").Base(err) } parentKey = pKey } @@ -136,7 +137,7 @@ func Generate(parent *Certificate, opts ...Option) (*Certificate, error) { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { - return nil, newError("failed to generate serial number").Base(err) + return nil, errors.New("failed to generate serial number").Base(err) } template := &x509.Certificate{ @@ -156,19 +157,19 @@ func Generate(parent *Certificate, opts ...Option) (*Certificate, error) { if parent != nil { pCert, err := x509.ParseCertificate(parent.Certificate) if err != nil { - return nil, newError("failed to parse parent certificate").Base(err) + return nil, errors.New("failed to parse parent certificate").Base(err) } parentCert = pCert } derBytes, err := x509.CreateCertificate(rand.Reader, template, parentCert, publicKey(selfKey), parentKey) if err != nil { - return nil, newError("failed to create certificate").Base(err) + return nil, errors.New("failed to create certificate").Base(err) } privateKey, err := x509.MarshalPKCS8PrivateKey(selfKey) if err != nil { - return nil, newError("Unable to marshal private key").Base(err) + return nil, errors.New("Unable to marshal private key").Base(err) } return &Certificate{ diff --git a/common/protocol/tls/cert/cert_test.go b/common/protocol/tls/cert/cert_test.go index f4bfe090..e06e61d7 100644 --- a/common/protocol/tls/cert/cert_test.go +++ b/common/protocol/tls/cert/cert_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/task" ) @@ -41,7 +42,7 @@ func generate(domainNames []string, isCA bool, jsonOutput bool, fileOutput strin cert, err := Generate(nil, opts...) if err != nil { - return newError("failed to generate TLS certificate").Base(err) + return errors.New("failed to generate TLS certificate").Base(err) } if jsonOutput { diff --git a/common/protocol/tls/cert/errors.generated.go b/common/protocol/tls/cert/errors.generated.go deleted file mode 100644 index 6a4677f4..00000000 --- a/common/protocol/tls/cert/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package cert - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/protocol/user.go b/common/protocol/user.go index 8325f555..d6e3a131 100644 --- a/common/protocol/user.go +++ b/common/protocol/user.go @@ -1,8 +1,10 @@ package protocol +import "github.com/xtls/xray-core/common/errors" + func (u *User) GetTypedAccount() (Account, error) { if u.GetAccount() == nil { - return nil, newError("Account missing").AtWarning() + return nil, errors.New("Account missing").AtWarning() } rawAccount, err := u.Account.GetInstance() @@ -15,7 +17,7 @@ func (u *User) GetTypedAccount() (Account, error) { if account, ok := rawAccount.(Account); ok { return account, nil } - return nil, newError("Unknown account type: ", u.Account.Type) + return nil, errors.New("Unknown account type: ", u.Account.Type) } func (u *User) ToMemoryUser() (*MemoryUser, error) { diff --git a/common/retry/errors.generated.go b/common/retry/errors.generated.go deleted file mode 100644 index d9343213..00000000 --- a/common/retry/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package retry - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/retry/retry.go b/common/retry/retry.go index ec1ad696..346caf0c 100644 --- a/common/retry/retry.go +++ b/common/retry/retry.go @@ -4,9 +4,11 @@ package retry // import "github.com/xtls/xray-core/common/retry" import ( "time" + + "github.com/xtls/xray-core/common/errors" ) -var ErrRetryFailed = newError("all retry attempts failed") +var ErrRetryFailed = errors.New("all retry attempts failed") // Strategy is a way to retry on a specific function. type Strategy interface { @@ -36,7 +38,7 @@ func (r *retryer) On(method func() error) error { time.Sleep(time.Duration(delay) * time.Millisecond) attempt++ } - return newError(accumulatedError).Base(ErrRetryFailed) + return errors.New(accumulatedError).Base(ErrRetryFailed) } // Timed returns a retry strategy with fixed interval. diff --git a/common/session/context.go b/common/session/context.go index fc37bd72..da3ad4a8 100644 --- a/common/session/context.go +++ b/common/session/context.go @@ -4,6 +4,7 @@ import ( "context" _ "unsafe" + "github.com/xtls/xray-core/common/ctx" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/features/routing" ) @@ -11,35 +12,19 @@ import ( //go:linkname IndependentCancelCtx context.newCancelCtx func IndependentCancelCtx(parent context.Context) context.Context -type sessionKey int - const ( - idSessionKey sessionKey = iota - inboundSessionKey - outboundSessionKey - contentSessionKey - muxPreferedSessionKey - sockoptSessionKey - trackedConnectionErrorKey - dispatcherKey - timeoutOnlyKey - allowedNetworkKey - handlerSessionKey + inboundSessionKey ctx.SessionKey = 1 + outboundSessionKey ctx.SessionKey = 2 + contentSessionKey ctx.SessionKey = 3 + muxPreferedSessionKey ctx.SessionKey = 4 + sockoptSessionKey ctx.SessionKey = 5 + trackedConnectionErrorKey ctx.SessionKey = 6 + dispatcherKey ctx.SessionKey = 7 + timeoutOnlyKey ctx.SessionKey = 8 + allowedNetworkKey ctx.SessionKey = 9 + handlerSessionKey ctx.SessionKey = 10 ) -// ContextWithID returns a new context with the given ID. -func ContextWithID(ctx context.Context, id ID) context.Context { - return context.WithValue(ctx, idSessionKey, id) -} - -// IDFromContext returns ID in this context, or 0 if not contained. -func IDFromContext(ctx context.Context) ID { - if id, ok := ctx.Value(idSessionKey).(ID); ok { - return id - } - return 0 -} - func ContextWithInbound(ctx context.Context, inbound *Inbound) context.Context { return context.WithValue(ctx, inboundSessionKey, inbound) } diff --git a/common/session/session.go b/common/session/session.go index d8ab1ec4..c926a883 100644 --- a/common/session/session.go +++ b/common/session/session.go @@ -5,20 +5,18 @@ import ( "context" "math/rand" + c "github.com/xtls/xray-core/common/ctx" "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/signal" ) -// ID of a session. -type ID uint32 - // NewID generates a new ID. The generated ID is high likely to be unique, but not cryptographically secure. // The generated ID will never be 0. -func NewID() ID { +func NewID() c.ID { for { - id := ID(rand.Uint32()) + id := c.ID(rand.Uint32()) if id != 0 { return id } @@ -28,7 +26,7 @@ func NewID() ID { // ExportIDToError transfers session.ID into an error object, for logging purpose. // This can be used with error.WriteToLog(). func ExportIDToError(ctx context.Context) errors.ExportOption { - id := IDFromContext(ctx) + id := c.IDFromContext(ctx) return func(h *errors.ExportOptionHolder) { h.SessionID = uint32(id) } diff --git a/common/singbridge/handler.go b/common/singbridge/handler.go index 18d4ad71..f200075c 100644 --- a/common/singbridge/handler.go +++ b/common/singbridge/handler.go @@ -9,7 +9,6 @@ import ( "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/features/routing" "github.com/xtls/xray-core/transport" ) @@ -47,5 +46,5 @@ func (d *Dispatcher) NewPacketConnection(ctx context.Context, conn N.PacketConn, } func (d *Dispatcher) NewError(ctx context.Context, err error) { - d.newErrorFunc(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, err.Error()) } diff --git a/common/singbridge/logger.go b/common/singbridge/logger.go index c1702363..16ff29cc 100644 --- a/common/singbridge/logger.go +++ b/common/singbridge/logger.go @@ -5,7 +5,6 @@ import ( "github.com/sagernet/sing/common/logger" "github.com/xtls/xray-core/common/errors" - "github.com/xtls/xray-core/common/session" ) var _ logger.ContextLogger = (*XrayLogger)(nil) @@ -24,19 +23,19 @@ func (l *XrayLogger) Trace(args ...any) { } func (l *XrayLogger) Debug(args ...any) { - l.newError(args...).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), args...) } func (l *XrayLogger) Info(args ...any) { - l.newError(args...).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), args...) } func (l *XrayLogger) Warn(args ...any) { - l.newError(args...).AtWarning().WriteToLog() + errors.LogWarning(context.Background(), args...) } func (l *XrayLogger) Error(args ...any) { - l.newError(args...).AtError().WriteToLog() + errors.LogError(context.Background(), args...) } func (l *XrayLogger) Fatal(args ...any) { @@ -49,19 +48,19 @@ func (l *XrayLogger) TraceContext(ctx context.Context, args ...any) { } func (l *XrayLogger) DebugContext(ctx context.Context, args ...any) { - l.newError(args...).AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, args...) } func (l *XrayLogger) InfoContext(ctx context.Context, args ...any) { - l.newError(args...).AtInfo().WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, args...) } func (l *XrayLogger) WarnContext(ctx context.Context, args ...any) { - l.newError(args...).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarning(ctx, args...) } func (l *XrayLogger) ErrorContext(ctx context.Context, args ...any) { - l.newError(args...).AtError().WriteToLog(session.ExportIDToError(ctx)) + errors.LogError(ctx, args...) } func (l *XrayLogger) FatalContext(ctx context.Context, args ...any) { diff --git a/common/type.go b/common/type.go index 1f85b4ef..8ee8745c 100644 --- a/common/type.go +++ b/common/type.go @@ -3,6 +3,8 @@ package common import ( "context" "reflect" + + "github.com/xtls/xray-core/common/errors" ) // ConfigCreator is a function to create an object by a config. @@ -14,7 +16,7 @@ var typeCreatorRegistry = make(map[reflect.Type]ConfigCreator) func RegisterConfig(config interface{}, configCreator ConfigCreator) error { configType := reflect.TypeOf(config) if _, found := typeCreatorRegistry[configType]; found { - return newError(configType.Name() + " is already registered").AtError() + return errors.New(configType.Name() + " is already registered").AtError() } typeCreatorRegistry[configType] = configCreator return nil @@ -25,7 +27,7 @@ func CreateObject(ctx context.Context, config interface{}) (interface{}, error) configType := reflect.TypeOf(config) creator, found := typeCreatorRegistry[configType] if !found { - return nil, newError(configType.String() + " is not registered").AtError() + return nil, errors.New(configType.String() + " is not registered").AtError() } return creator(ctx, config) } diff --git a/common/xudp/errors.generated.go b/common/xudp/errors.generated.go deleted file mode 100644 index e14625a8..00000000 --- a/common/xudp/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package xudp - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/common/xudp/xudp.go b/common/xudp/xudp.go index 566ba749..1dfff16a 100644 --- a/common/xudp/xudp.go +++ b/common/xudp/xudp.go @@ -11,6 +11,7 @@ import ( "time" "github.com/xtls/xray-core/common/buf" + "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" @@ -36,7 +37,7 @@ func init() { } rand.Read(BaseKey) go func() { - time.Sleep(100 * time.Millisecond) // this is not nice, but need to give some time for Android to setup ENV + time.Sleep(100 * time.Millisecond) // this is not nice, but need to give some time for Android to setup ENV if raw := platform.NewEnvFlag(platform.XUDPBaseKey).GetValue(func() string { return "" }); raw != "" { if BaseKey, _ = base64.RawURLEncoding.DecodeString(raw); len(BaseKey) == 32 { return @@ -56,7 +57,7 @@ func GetGlobalID(ctx context.Context) (globalID [8]byte) { h.Write([]byte(inbound.Source.String())) copy(globalID[:], h.Sum(nil)) if Show { - newError(fmt.Sprintf("XUDP inbound.Source.String(): %v\tglobalID: %v\n", inbound.Source.String(), globalID)).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, fmt.Sprintf("XUDP inbound.Source.String(): %v\tglobalID: %v\n", inbound.Source.String(), globalID)) } } return diff --git a/core/config.go b/core/config.go index 1a5fa33f..32fea49e 100644 --- a/core/config.go +++ b/core/config.go @@ -7,6 +7,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/cmdarg" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/main/confloader" "google.golang.org/protobuf/proto" ) @@ -38,14 +39,14 @@ var ( func RegisterConfigLoader(format *ConfigFormat) error { name := strings.ToLower(format.Name) if _, found := configLoaderByName[name]; found { - return newError(format.Name, " already registered.") + return errors.New(format.Name, " already registered.") } configLoaderByName[name] = format for _, ext := range format.Extension { lext := strings.ToLower(ext) if f, found := configLoaderByExt[lext]; found { - return newError(ext, " already registered to ", f.Name) + return errors.New(ext, " already registered to ", f.Name) } configLoaderByExt[lext] = format } @@ -116,7 +117,7 @@ func LoadConfig(formatName string, input interface{}) (*Config, error) { } if f == "" { - return nil, newError("Failed to get format of ", file).AtWarning() + return nil, errors.New("Failed to get format of ", file).AtWarning() } if f == "protobuf" { @@ -130,7 +131,7 @@ func LoadConfig(formatName string, input interface{}) (*Config, error) { if len(v) == 1 { return configLoaderByName["protobuf"].Loader(v) } else { - return nil, newError("Only one protobuf config file is allowed").AtWarning() + return nil, errors.New("Only one protobuf config file is allowed").AtWarning() } } @@ -141,11 +142,11 @@ func LoadConfig(formatName string, input interface{}) (*Config, error) { if f, found := configLoaderByName[formatName]; found { return f.Loader(v) } else { - return nil, newError("Unable to load config in", formatName).AtWarning() + return nil, errors.New("Unable to load config in", formatName).AtWarning() } } - return nil, newError("Unable to load config").AtWarning() + return nil, errors.New("Unable to load config").AtWarning() } func loadProtobufConfig(data []byte) (*Config, error) { @@ -173,7 +174,7 @@ func init() { common.Must(err) return loadProtobufConfig(data) default: - return nil, newError("unknow type") + return nil, errors.New("unknow type") } }, })) diff --git a/core/errors.generated.go b/core/errors.generated.go deleted file mode 100644 index 47636b9c..00000000 --- a/core/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package core - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/core/functions.go b/core/functions.go index 7885fd14..09c4b5dd 100644 --- a/core/functions.go +++ b/core/functions.go @@ -5,6 +5,7 @@ import ( "context" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/features/routing" @@ -50,7 +51,7 @@ func Dial(ctx context.Context, v *Instance, dest net.Destination) (net.Conn, err dispatcher := v.GetFeature(routing.DispatcherType()) if dispatcher == nil { - return nil, newError("routing.Dispatcher is not registered in Xray core") + return nil, errors.New("routing.Dispatcher is not registered in Xray core") } r, err := dispatcher.(routing.Dispatcher).Dispatch(ctx, dest) @@ -77,7 +78,7 @@ func DialUDP(ctx context.Context, v *Instance) (net.PacketConn, error) { dispatcher := v.GetFeature(routing.DispatcherType()) if dispatcher == nil { - return nil, newError("routing.Dispatcher is not registered in Xray core") + return nil, errors.New("routing.Dispatcher is not registered in Xray core") } return udp.DialDispatcher(ctx, dispatcher.(routing.Dispatcher)) } diff --git a/core/xray.go b/core/xray.go index 20484c60..a81cf19b 100644 --- a/core/xray.go +++ b/core/xray.go @@ -6,6 +6,7 @@ import ( "sync" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/platform" "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/features" @@ -104,7 +105,7 @@ func AddInboundHandler(server *Instance, config *InboundHandlerConfig) error { } handler, ok := rawHandler.(inbound.Handler) if !ok { - return newError("not an InboundHandler") + return errors.New("not an InboundHandler") } if err := inboundManager.AddHandler(server.ctx, handler); err != nil { return err @@ -130,7 +131,7 @@ func AddOutboundHandler(server *Instance, config *OutboundHandlerConfig) error { } handler, ok := rawHandler.(outbound.Handler) if !ok { - return newError("not an OutboundHandler") + return errors.New("not an OutboundHandler") } if err := outboundManager.AddHandler(server.ctx, handler); err != nil { return err @@ -181,7 +182,7 @@ func NewWithContext(ctx context.Context, config *Config) (*Instance, error) { } func initInstanceWithConfig(config *Config, server *Instance) (bool, error) { - server.ctx = context.WithValue(server.ctx, "cone", + server.ctx = context.WithValue(server.ctx, "cone", platform.NewEnvFlag(platform.UseCone).GetValue(func() string { return "" }) != "true") if config.Transport != nil { @@ -234,7 +235,7 @@ func initInstanceWithConfig(config *Config, server *Instance) (bool, error) { ) if server.featureResolutions != nil { - return true, newError("not all dependency are resolved.") + return true, errors.New("not all dependency are resolved.") } if err := addInboundHandlers(server, config.Inbound); err != nil { @@ -259,14 +260,14 @@ func (s *Instance) Close() error { s.running = false - var errors []interface{} + var errs []interface{} for _, f := range s.features { if err := f.Close(); err != nil { - errors = append(errors, err) + errs = append(errs, err) } } - if len(errors) > 0 { - return newError("failed to close all features").Base(newError(serial.Concat(errors...))) + if len(errs) > 0 { + return errors.New("failed to close all features").Base(errors.New(serial.Concat(errs...))) } return nil @@ -302,7 +303,7 @@ func (s *Instance) AddFeature(feature features.Feature) error { if s.running { if err := feature.Start(); err != nil { - newError("failed to start feature").Base(err).WriteToLog() + errors.LogInfoInner(s.ctx, err, "failed to start feature") } return nil } @@ -350,7 +351,7 @@ func (s *Instance) Start() error { } } - newError("Xray ", Version(), " started").AtWarning().WriteToLog() + errors.LogWarning(s.ctx, "Xray ", Version(), " started") return nil } diff --git a/features/dns/localdns/errors.generated.go b/features/dns/localdns/errors.generated.go deleted file mode 100644 index a501d5e6..00000000 --- a/features/dns/localdns/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package localdns - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/features/errors.generated.go b/features/errors.generated.go deleted file mode 100644 index ee8a5182..00000000 --- a/features/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package features - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/features/feature.go b/features/feature.go index 1288a86b..7c749622 100644 --- a/features/feature.go +++ b/features/feature.go @@ -1,6 +1,11 @@ package features -import "github.com/xtls/xray-core/common" +import ( + "context" + + "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" +) //go:generate go run github.com/xtls/xray-core/common/errors/errorgen @@ -13,5 +18,5 @@ type Feature interface { // PrintDeprecatedFeatureWarning prints a warning for deprecated feature. func PrintDeprecatedFeatureWarning(feature string) { - newError("You are using a deprecated feature: " + feature + ". Please update your config file with latest configuration format, or update your client software.").WriteToLog() + errors.LogInfo(context.Background(), "You are using a deprecated feature: " + feature + ". Please update your config file with latest configuration format, or update your client software.") } diff --git a/features/routing/dns/context.go b/features/routing/dns/context.go index 7b7fe928..4ad7d267 100644 --- a/features/routing/dns/context.go +++ b/features/routing/dns/context.go @@ -3,6 +3,9 @@ package dns //go:generate go run github.com/xtls/xray-core/common/errors/errorgen import ( + "context" + + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/features/dns" "github.com/xtls/xray-core/features/routing" @@ -31,7 +34,7 @@ func (ctx *ResolvableContext) GetTargetIPs() []net.IP { ctx.resolvedIPs = ips return ips } - newError("resolve ip for ", domain).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "resolve ip for ", domain) } if ips := ctx.Context.GetTargetIPs(); len(ips) != 0 { diff --git a/features/routing/dns/errors.generated.go b/features/routing/dns/errors.generated.go deleted file mode 100644 index d7375a9b..00000000 --- a/features/routing/dns/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package dns - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/features/stats/errors.generated.go b/features/stats/errors.generated.go deleted file mode 100644 index c64386f3..00000000 --- a/features/stats/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package stats - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/features/stats/stats.go b/features/stats/stats.go index bf83df78..a6c1f6be 100644 --- a/features/stats/stats.go +++ b/features/stats/stats.go @@ -6,6 +6,7 @@ import ( "context" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/features" ) @@ -116,7 +117,7 @@ func (NoopManager) Type() interface{} { // RegisterCounter implements Manager. func (NoopManager) RegisterCounter(string) (Counter, error) { - return nil, newError("not implemented") + return nil, errors.New("not implemented") } // UnregisterCounter implements Manager. @@ -131,7 +132,7 @@ func (NoopManager) GetCounter(string) Counter { // RegisterChannel implements Manager. func (NoopManager) RegisterChannel(string) (Channel, error) { - return nil, newError("not implemented") + return nil, errors.New("not implemented") } // UnregisterChannel implements Manager. diff --git a/infra/conf/api.go b/infra/conf/api.go index e7f32980..dca34910 100644 --- a/infra/conf/api.go +++ b/infra/conf/api.go @@ -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) diff --git a/infra/conf/blackhole.go b/infra/conf/blackhole.go index 5044a8c0..7b78742f 100644 --- a/infra/conf/blackhole.go +++ b/infra/conf/blackhole.go @@ -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 { diff --git a/infra/conf/common.go b/infra/conf/common.go index 20868b83..9f9c0068 100644 --- a/infra/conf/common.go +++ b/infra/conf/common.go @@ -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)}) } diff --git a/infra/conf/dns.go b/infra/conf/dns.go index a0f3155c..d9ed9ab5 100644 --- a/infra/conf/dns.go +++ b/infra/conf/dns.go @@ -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...) } diff --git a/infra/conf/dns_proxy.go b/infra/conf/dns_proxy.go index 13a44597..712f4b1f 100644 --- a/infra/conf/dns_proxy.go +++ b/infra/conf/dns_proxy.go @@ -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 diff --git a/infra/conf/errors.generated.go b/infra/conf/errors.generated.go deleted file mode 100644 index a80cc140..00000000 --- a/infra/conf/errors.generated.go +++ /dev/null @@ -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{}) -} diff --git a/infra/conf/fakedns.go b/infra/conf/fakedns.go index ca425457..86240366 100644 --- a/infra/conf/fakedns.go +++ b/infra/conf/fakedns.go @@ -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.") } } diff --git a/infra/conf/freedom.go b/infra/conf/freedom.go index 90c99b37..d90b7c2d 100644 --- a/infra/conf/freedom.go +++ b/infra/conf/freedom.go @@ -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{ diff --git a/infra/conf/http.go b/infra/conf/http.go index b391dbf2..ef16cac7 100644 --- a/infra/conf/http.go +++ b/infra/conf/http.go @@ -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) diff --git a/infra/conf/lint.go b/infra/conf/lint.go index 93da35d4..f8a6b38c 100644 --- a/infra/conf/lint.go +++ b/infra/conf/lint.go @@ -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 diff --git a/infra/conf/loader.go b/infra/conf/loader.go index 51f268a3..1dc2de23 100644 --- a/infra/conf/loader.go +++ b/infra/conf/loader.go @@ -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 { diff --git a/infra/conf/metrics.go b/infra/conf/metrics.go index 2a0c8ef9..3f550e88 100644 --- a/infra/conf/metrics.go +++ b/infra/conf/metrics.go @@ -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{ diff --git a/infra/conf/router.go b/infra/conf/router.go index 6ae39d45..44f9e8fa 100644 --- a/infra/conf/router.go +++ b/infra/conf/router.go @@ -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) } diff --git a/infra/conf/serial/builder.go b/infra/conf/serial/builder.go index 88ea9e65..1ff4ed8a 100644 --- a/infra/conf/serial/builder.go +++ b/infra/conf/serial/builder.go @@ -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 diff --git a/infra/conf/serial/errors.generated.go b/infra/conf/serial/errors.generated.go deleted file mode 100644 index e78fc61e..00000000 --- a/infra/conf/serial/errors.generated.go +++ /dev/null @@ -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{}) -} diff --git a/infra/conf/serial/loader.go b/infra/conf/serial/loader.go index e3235675..ef9963df 100644 --- a/infra/conf/serial/loader.go +++ b/infra/conf/serial/loader.go @@ -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 diff --git a/infra/conf/shadowsocks.go b/infra/conf/shadowsocks.go index 3dcbb2f3..1bd6462c 100644 --- a/infra/conf/shadowsocks.go +++ b/infra/conf/shadowsocks.go @@ -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 diff --git a/infra/conf/socks.go b/infra/conf/socks.go index 61f6fae2..52fbe4c6 100644 --- a/infra/conf/socks.go +++ b/infra/conf/socks.go @@ -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) diff --git a/infra/conf/transport.go b/infra/conf/transport.go index 1e0e70de..b401dcab 100644 --- a/infra/conf/transport.go +++ b/infra/conf/transport.go @@ -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", diff --git a/infra/conf/transport_authenticators.go b/infra/conf/transport_authenticators.go index db9f4a72..4004b26b 100644 --- a/infra/conf/transport_authenticators.go +++ b/infra/conf/transport_authenticators.go @@ -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, diff --git a/infra/conf/transport_internet.go b/infra/conf/transport_internet.go index 12ed4197..fe80c647 100644 --- a/infra/conf/transport_internet.go +++ b/infra/conf/transport_internet.go @@ -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, diff --git a/infra/conf/trojan.go b/infra/conf/trojan.go index 6bc2385f..13a1df73 100644 --- a/infra/conf/trojan.go +++ b/infra/conf/trojan.go @@ -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`) } } diff --git a/infra/conf/vless.go b/infra/conf/vless.go index 9d293555..e9517614 100644 --- a/infra/conf/vless.go +++ b/infra/conf/vless.go @@ -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) diff --git a/infra/conf/vmess.go b/infra/conf/vmess.go index ba319356..23eb6948 100644 --- a/infra/conf/vmess.go +++ b/infra/conf/vmess.go @@ -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) diff --git a/infra/conf/wireguard.go b/infra/conf/wireguard.go index adf51841..d06bf689 100644 --- a/infra/conf/wireguard.go +++ b/infra/conf/wireguard.go @@ -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) } diff --git a/infra/conf/xray.go b/infra/conf/xray.go index 5e1adcbc..29616ef3 100644 --- a/infra/conf/xray.go +++ b/infra/conf/xray.go @@ -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)) } diff --git a/main/commands/all/convert.go b/main/commands/all/convert.go index 2ed25a13..eab66d14 100644 --- a/main/commands/all/convert.go +++ b/main/commands/all/convert.go @@ -12,6 +12,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/infra/conf" "github.com/xtls/xray-core/infra/conf/serial" "github.com/xtls/xray-core/main/commands/base" @@ -92,11 +93,11 @@ func loadArg(arg string) (out io.Reader, err error) { func FetchHTTPContent(target string) ([]byte, error) { parsedTarget, err := url.Parse(target) if err != nil { - return nil, newError("invalid URL: ", target).Base(err) + return nil, errors.New("invalid URL: ", target).Base(err) } if s := strings.ToLower(parsedTarget.Scheme); s != "http" && s != "https" { - return nil, newError("invalid scheme: ", parsedTarget.Scheme) + return nil, errors.New("invalid scheme: ", parsedTarget.Scheme) } client := &http.Client{ @@ -108,17 +109,17 @@ func FetchHTTPContent(target string) ([]byte, error) { Close: true, }) if err != nil { - return nil, newError("failed to dial to ", target).Base(err) + return nil, errors.New("failed to dial to ", target).Base(err) } defer resp.Body.Close() if resp.StatusCode != 200 { - return nil, newError("unexpected HTTP status code: ", resp.StatusCode) + return nil, errors.New("unexpected HTTP status code: ", resp.StatusCode) } content, err := buf.ReadAllToBytes(resp.Body) if err != nil { - return nil, newError("failed to read HTTP response").Base(err) + return nil, errors.New("failed to read HTTP response").Base(err) } return content, nil diff --git a/main/commands/all/errors.generated.go b/main/commands/all/errors.generated.go deleted file mode 100644 index ff138a8a..00000000 --- a/main/commands/all/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package all - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/main/confloader/confloader.go b/main/confloader/confloader.go index 80b3b306..315c500e 100644 --- a/main/confloader/confloader.go +++ b/main/confloader/confloader.go @@ -1,8 +1,11 @@ package confloader import ( + "context" "io" "os" + + "github.com/xtls/xray-core/common/errors" ) type ( @@ -19,7 +22,7 @@ var ( // actual work is in external module func LoadConfig(file string) (io.Reader, error) { if EffectiveConfigFileLoader == nil { - newError("external config module not loaded, reading from stdin").AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "external config module not loaded, reading from stdin") return os.Stdin, nil } return EffectiveConfigFileLoader(file) @@ -29,7 +32,7 @@ func LoadConfig(file string) (io.Reader, error) { // the actual work also in external module func LoadExtConfig(files []string, reader io.Reader) (io.Reader, error) { if EffectiveExtConfigLoader == nil { - return nil, newError("external config module not loaded").AtError() + return nil, errors.New("external config module not loaded").AtError() } return EffectiveExtConfigLoader(files, reader) diff --git a/main/confloader/errors.generated.go b/main/confloader/errors.generated.go deleted file mode 100644 index 1c234856..00000000 --- a/main/confloader/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package confloader - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/main/confloader/external/errors.generated.go b/main/confloader/external/errors.generated.go deleted file mode 100644 index 992674b7..00000000 --- a/main/confloader/external/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package external - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/main/confloader/external/external.go b/main/confloader/external/external.go index 20afa141..1e349ebf 100644 --- a/main/confloader/external/external.go +++ b/main/confloader/external/external.go @@ -12,6 +12,7 @@ import ( "time" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/platform/ctlcmd" "github.com/xtls/xray-core/main/confloader" ) @@ -39,11 +40,11 @@ func ConfigLoader(arg string) (out io.Reader, err error) { func FetchHTTPContent(target string) ([]byte, error) { parsedTarget, err := url.Parse(target) if err != nil { - return nil, newError("invalid URL: ", target).Base(err) + return nil, errors.New("invalid URL: ", target).Base(err) } if s := strings.ToLower(parsedTarget.Scheme); s != "http" && s != "https" { - return nil, newError("invalid scheme: ", parsedTarget.Scheme) + return nil, errors.New("invalid scheme: ", parsedTarget.Scheme) } client := &http.Client{ @@ -55,17 +56,17 @@ func FetchHTTPContent(target string) ([]byte, error) { Close: true, }) if err != nil { - return nil, newError("failed to dial to ", target).Base(err) + return nil, errors.New("failed to dial to ", target).Base(err) } defer resp.Body.Close() if resp.StatusCode != 200 { - return nil, newError("unexpected HTTP status code: ", resp.StatusCode) + return nil, errors.New("unexpected HTTP status code: ", resp.StatusCode) } content, err := buf.ReadAllToBytes(resp.Body) if err != nil { - return nil, newError("failed to read HTTP response").Base(err) + return nil, errors.New("failed to read HTTP response").Base(err) } return content, nil diff --git a/main/errors.generated.go b/main/errors.generated.go deleted file mode 100644 index e898cb5f..00000000 --- a/main/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package main - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/main/json/errors.generated.go b/main/json/errors.generated.go deleted file mode 100644 index 2c1b1452..00000000 --- a/main/json/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package json - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/main/json/json.go b/main/json/json.go index 2e4168c3..f14b0eec 100644 --- a/main/json/json.go +++ b/main/json/json.go @@ -1,10 +1,12 @@ package json import ( + "context" "io" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/cmdarg" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/infra/conf" "github.com/xtls/xray-core/infra/conf/serial" @@ -20,14 +22,14 @@ func init() { case cmdarg.Arg: cf := &conf.Config{} for i, arg := range v { - newError("Reading config: ", arg).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "Reading config: ", arg) r, err := confloader.LoadConfig(arg) if err != nil { - return nil, newError("failed to read config: ", arg).Base(err) + return nil, errors.New("failed to read config: ", arg).Base(err) } c, err := serial.DecodeJSONConfig(r) if err != nil { - return nil, newError("failed to decode config: ", arg).Base(err) + return nil, errors.New("failed to decode config: ", arg).Base(err) } if i == 0 { // This ensure even if the muti-json parser do not support a setting, @@ -41,7 +43,7 @@ func init() { case io.Reader: return serial.LoadJSONConfig(v) default: - return nil, newError("unknow type") + return nil, errors.New("unknow type") } }, })) diff --git a/main/run.go b/main/run.go index f54d7480..4134fb64 100644 --- a/main/run.go +++ b/main/run.go @@ -15,6 +15,7 @@ import ( "time" "github.com/xtls/xray-core/common/cmdarg" + "github.com/xtls/xray-core/common/errors" clog "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/platform" "github.com/xtls/xray-core/core" @@ -217,12 +218,12 @@ func startXray() (core.Server, error) { c, err := core.LoadConfig(getConfigFormat(), configFiles) if err != nil { - return nil, newError("failed to load config files: [", configFiles.String(), "]").Base(err) + return nil, errors.New("failed to load config files: [", configFiles.String(), "]").Base(err) } server, err := core.New(c) if err != nil { - return nil, newError("failed to create server").Base(err) + return nil, errors.New("failed to create server").Base(err) } return server, nil diff --git a/main/toml/errors.generated.go b/main/toml/errors.generated.go deleted file mode 100644 index 0bad202e..00000000 --- a/main/toml/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package toml - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/main/toml/toml.go b/main/toml/toml.go index e52077f3..22e1c3dc 100644 --- a/main/toml/toml.go +++ b/main/toml/toml.go @@ -1,10 +1,12 @@ package toml import ( + "context" "io" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/cmdarg" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/infra/conf" "github.com/xtls/xray-core/infra/conf/serial" @@ -20,14 +22,14 @@ func init() { case cmdarg.Arg: cf := &conf.Config{} for i, arg := range v { - newError("Reading config: ", arg).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "Reading config: ", arg) r, err := confloader.LoadConfig(arg) if err != nil { - return nil, newError("failed to read config: ", arg).Base(err) + return nil, errors.New("failed to read config: ", arg).Base(err) } c, err := serial.DecodeTOMLConfig(r) if err != nil { - return nil, newError("failed to decode config: ", arg).Base(err) + return nil, errors.New("failed to decode config: ", arg).Base(err) } if i == 0 { // This ensure even if the muti-json parser do not support a setting, @@ -41,7 +43,7 @@ func init() { case io.Reader: return serial.LoadTOMLConfig(v) default: - return nil, newError("unknow type") + return nil, errors.New("unknow type") } }, })) diff --git a/main/yaml/errors.generated.go b/main/yaml/errors.generated.go deleted file mode 100644 index c4da8fa9..00000000 --- a/main/yaml/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package yaml - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/main/yaml/yaml.go b/main/yaml/yaml.go index 760a5717..59bab8fa 100644 --- a/main/yaml/yaml.go +++ b/main/yaml/yaml.go @@ -1,10 +1,12 @@ package yaml import ( + "context" "io" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/cmdarg" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/infra/conf" "github.com/xtls/xray-core/infra/conf/serial" @@ -20,14 +22,14 @@ func init() { case cmdarg.Arg: cf := &conf.Config{} for i, arg := range v { - newError("Reading config: ", arg).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "Reading config: ", arg) r, err := confloader.LoadConfig(arg) if err != nil { - return nil, newError("failed to read config: ", arg).Base(err) + return nil, errors.New("failed to read config: ", arg).Base(err) } c, err := serial.DecodeYAMLConfig(r) if err != nil { - return nil, newError("failed to decode config: ", arg).Base(err) + return nil, errors.New("failed to decode config: ", arg).Base(err) } if i == 0 { // This ensure even if the muti-json parser do not support a setting, @@ -41,7 +43,7 @@ func init() { case io.Reader: return serial.LoadYAMLConfig(v) default: - return nil, newError("unknow type") + return nil, errors.New("unknow type") } }, })) diff --git a/proxy/blackhole/errors.generated.go b/proxy/blackhole/errors.generated.go deleted file mode 100644 index 344f86cb..00000000 --- a/proxy/blackhole/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package blackhole - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/dns/dns.go b/proxy/dns/dns.go index 86790f76..d797ca86 100644 --- a/proxy/dns/dns.go +++ b/proxy/dns/dns.go @@ -74,14 +74,14 @@ func parseIPQuery(b []byte) (r bool, domain string, id uint16, qType dnsmessage. var parser dnsmessage.Parser header, err := parser.Start(b) if err != nil { - newError("parser start").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "parser start") return } id = header.ID q, err := parser.Question() if err != nil { - newError("question").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "question") return } qType = q.Type @@ -97,9 +97,9 @@ func parseIPQuery(b []byte) (r bool, domain string, id uint16, qType dnsmessage. // Process implements proxy.Outbound. func (h *Handler) Process(ctx context.Context, link *transport.Link, d internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("invalid outbound") + return errors.New("invalid outbound") } ob.Name = "dns" @@ -116,7 +116,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, d internet. dest.Port = h.server.Port } - newError("handling DNS traffic to ", dest).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "handling DNS traffic to ", dest) conn := &outboundConn{ dialer: func() (stat.Connection, error) { @@ -216,7 +216,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, d internet. } if err := task.Run(ctx, request, response); err != nil { - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil @@ -245,7 +245,7 @@ func (h *Handler) handleIPQuery(id uint16, qType dnsmessage.Type, domain string, rcode := dns.RCodeFromError(err) if rcode == 0 && len(ips) == 0 && !errors.AllEqual(dns.ErrEmptyResponse, errors.Cause(err)) { - newError("ip query").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "ip query") return } @@ -297,14 +297,14 @@ func (h *Handler) handleIPQuery(id uint16, qType dnsmessage.Type, domain string, } msgBytes, err := builder.Finish() if err != nil { - newError("pack message").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "pack message") b.Release() return } b.Resize(0, int32(len(msgBytes))) if err := writer.WriteMessage(b); err != nil { - newError("write IP answer").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "write IP answer") } } @@ -332,7 +332,7 @@ func (c *outboundConn) Write(b []byte) (int, error) { if c.conn == nil { if err := c.dial(); err != nil { c.access.Unlock() - newError("failed to dial outbound connection").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(context.Background(), err, "failed to dial outbound connection") return len(b), nil } } diff --git a/proxy/dns/errors.generated.go b/proxy/dns/errors.generated.go deleted file mode 100644 index d7375a9b..00000000 --- a/proxy/dns/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package dns - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/dokodemo/dokodemo.go b/proxy/dokodemo/dokodemo.go index 5a07df5c..14ff7c72 100644 --- a/proxy/dokodemo/dokodemo.go +++ b/proxy/dokodemo/dokodemo.go @@ -9,6 +9,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol" @@ -42,7 +43,7 @@ type DokodemoDoor struct { // Init initializes the DokodemoDoor instance with necessary parameters. func (d *DokodemoDoor) Init(config *Config, pm policy.Manager, sockopt *session.Sockopt) error { if (config.NetworkList == nil || len(config.NetworkList.Network) == 0) && len(config.Networks) == 0 { - return newError("no network specified") + return errors.New("no network specified") } d.config = config d.address = config.GetPredefinedAddress() @@ -77,7 +78,7 @@ type hasHandshakeAddressContext interface { // Process implements proxy.Inbound. func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher) error { - newError("processing connection from: ", conn.RemoteAddr()).AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, "processing connection from: ", conn.RemoteAddr()) dest := net.Destination{ Network: network, Address: d.address, @@ -88,7 +89,7 @@ func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn st if d.config.FollowRedirect { outbounds := session.OutboundsFromContext(ctx) if len(outbounds) > 0 { - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if ob.Target.IsValid() { dest = ob.Target destinationOverridden = true @@ -103,7 +104,7 @@ func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn st } } if !dest.IsValid() || dest.Address == nil { - return newError("unable to get destination") + return errors.New("unable to get destination") } inbound := session.InboundFromContext(ctx) @@ -119,7 +120,7 @@ func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn st Status: log.AccessAccepted, Reason: "", }) - newError("received request for ", conn.RemoteAddr()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "received request for ", conn.RemoteAddr()) plcy := d.policy() ctx, cancel := context.WithCancel(ctx) @@ -132,7 +133,7 @@ func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn st ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer) link, err := dispatcher.Dispatch(ctx, dest) if err != nil { - return newError("failed to dispatch request").Base(err) + return errors.New("failed to dispatch request").Base(err) } requestCount := int32(1) @@ -150,7 +151,7 @@ func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn st reader = buf.NewReader(conn) } if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport request").Base(err) + return errors.New("failed to transport request").Base(err) } return nil @@ -217,7 +218,7 @@ func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn st } }() if err := buf.Copy(tReader, link.Writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport request (TPROXY conn)").Base(err) + return errors.New("failed to transport request (TPROXY conn)").Base(err) } return nil } @@ -229,7 +230,7 @@ func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn st defer timer.SetTimeout(plcy.Timeouts.UplinkOnly) if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport response").Base(err) + return errors.New("failed to transport response").Base(err) } return nil } @@ -239,7 +240,7 @@ func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn st }, task.Close(link.Writer)), responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil @@ -282,7 +283,7 @@ func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { w.mark, ) if err != nil { - newError(err).WriteToLog() + errors.LogInfo(context.Background(), err.Error()) b.Release() continue } @@ -290,7 +291,7 @@ func (w *PacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { } _, err = conn.WriteTo(b.Bytes(), w.back) if err != nil { - newError(err).WriteToLog() + errors.LogInfo(context.Background(), err.Error()) w.conns[*b.UDP] = nil conn.Close() } diff --git a/proxy/dokodemo/errors.generated.go b/proxy/dokodemo/errors.generated.go deleted file mode 100644 index cc4fd09c..00000000 --- a/proxy/dokodemo/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package dokodemo - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/errors.generated.go b/proxy/errors.generated.go deleted file mode 100644 index 1a643896..00000000 --- a/proxy/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package proxy - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/freedom/errors.generated.go b/proxy/freedom/errors.generated.go deleted file mode 100644 index 344fbb2f..00000000 --- a/proxy/freedom/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package freedom - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/freedom/freedom.go b/proxy/freedom/freedom.go index 29621c0e..dcb72b04 100644 --- a/proxy/freedom/freedom.go +++ b/proxy/freedom/freedom.go @@ -13,6 +13,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/dice" + "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/retry" @@ -87,7 +88,7 @@ func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Ad } } if err != nil { - newError("failed to get IP address for domain ", domain).Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to get IP address for domain ", domain) } if len(ips) == 0 { return nil @@ -107,9 +108,9 @@ func isValidAddress(addr *net.IPOrDomain) bool { // Process implements proxy.Outbound. func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified.") + return errors.New("target not specified.") } ob.Name = "freedom" ob.CanSpliceCopy = 1 @@ -143,7 +144,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte Address: ip, Port: dialDest.Port, } - newError("dialing to ", dialDest).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "dialing to ", dialDest) } else if h.config.forceIP() { return dns.ErrEmptyResponse } @@ -169,10 +170,10 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte return nil }) if err != nil { - return newError("failed to open connection to ", destination).Base(err) + return errors.New("failed to open connection to ", destination).Base(err) } defer conn.Close() - newError("connection opened to ", destination, ", local endpoint ", conn.LocalAddr(), ", remote endpoint ", conn.RemoteAddr()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "connection opened to ", destination, ", local endpoint ", conn.LocalAddr(), ", remote endpoint ", conn.RemoteAddr()) var newCtx context.Context var newCancel context.CancelFunc @@ -195,8 +196,8 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte var writer buf.Writer if destination.Network == net.Network_TCP { if h.config.Fragment != nil { - newError("FRAGMENT", h.config.Fragment.PacketsFrom, h.config.Fragment.PacketsTo, h.config.Fragment.LengthMin, h.config.Fragment.LengthMax, - h.config.Fragment.IntervalMin, h.config.Fragment.IntervalMax).AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, "FRAGMENT", h.config.Fragment.PacketsFrom, h.config.Fragment.PacketsTo, h.config.Fragment.LengthMin, h.config.Fragment.LengthMax, + h.config.Fragment.IntervalMin, h.config.Fragment.IntervalMax) writer = buf.NewWriter(&FragmentWriter{ fragment: h.config.Fragment, writer: conn, @@ -209,7 +210,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } if err := buf.Copy(input, writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to process request").Base(err) + return errors.New("failed to process request").Base(err) } return nil @@ -228,7 +229,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } reader := NewPacketReader(conn, UDPOverride) if err := buf.Copy(reader, output, buf.UpdateActivity(timer)); err != nil { - return newError("failed to process response").Base(err) + return errors.New("failed to process response").Base(err) } return nil } @@ -238,7 +239,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil { - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil diff --git a/proxy/http/client.go b/proxy/http/client.go index 80a0328a..862ca418 100644 --- a/proxy/http/client.go +++ b/proxy/http/client.go @@ -14,6 +14,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/bytespool" + "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/retry" @@ -51,12 +52,12 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { for _, rec := range config.Server { s, err := protocol.NewServerSpecFromPB(rec) if err != nil { - return nil, newError("failed to get server spec").Base(err) + return nil, errors.New("failed to get server spec").Base(err) } serverList.AddServer(s) } if serverList.Size() == 0 { - return nil, newError("0 target server") + return nil, errors.New("0 target server") } v := core.MustFromContext(ctx) @@ -70,9 +71,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { // Process implements proxy.Outbound.Process. We first create a socket tunnel via HTTP CONNECT method, then redirect all inbound traffic to that tunnel. func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified.") + return errors.New("target not specified.") } ob.Name = "http" ob.CanSpliceCopy = 2 @@ -80,7 +81,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter targetAddr := target.NetAddr() if target.Network == net.Network_UDP { - return newError("UDP is not supported by HTTP outbound") + return errors.New("UDP is not supported by HTTP outbound") } var user *protocol.MemoryUser @@ -97,7 +98,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter header, err := fillRequestHeader(ctx, c.header) if err != nil { - return newError("failed to fill out header").Base(err) + return errors.New("failed to fill out header").Base(err) } if err := retry.ExponentialBackoff(5, 100).On(func() error { @@ -117,12 +118,12 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter } return err }); err != nil { - return newError("failed to find an available destination").Base(err) + return errors.New("failed to find an available destination").Base(err) } defer func() { if err := conn.Close(); err != nil { - newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to closed connection") } }() @@ -160,7 +161,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer)) if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil @@ -174,10 +175,10 @@ func fillRequestHeader(ctx context.Context, header []*Header) ([]*Header, error) inbound := session.InboundFromContext(ctx) outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if inbound == nil || ob == nil { - return nil, newError("missing inbound or outbound metadata from context") + return nil, errors.New("missing inbound or outbound metadata from context") } data := struct { @@ -242,7 +243,7 @@ func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, u if resp.StatusCode != http.StatusOK { rawConn.Close() - return nil, newError("Proxy responded with non 200 code: " + resp.Status) + return nil, errors.New("Proxy responded with non 200 code: " + resp.Status) } return rawConn, nil } @@ -274,7 +275,7 @@ func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, u if resp.StatusCode != http.StatusOK { rawConn.Close() - return nil, newError("Proxy responded with non 200 code: " + resp.Status) + return nil, errors.New("Proxy responded with non 200 code: " + resp.Status) } return newHTTP2Conn(rawConn, pw, resp.Body), nil } @@ -344,7 +345,7 @@ func setUpHTTPTunnel(ctx context.Context, dest net.Destination, target string, u return proxyConn, err default: - return nil, newError("negotiated unsupported application layer protocol: " + nextProto) + return nil, errors.New("negotiated unsupported application layer protocol: " + nextProto) } } diff --git a/proxy/http/errors.generated.go b/proxy/http/errors.generated.go deleted file mode 100644 index f0048165..00000000 --- a/proxy/http/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package http - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/http/server.go b/proxy/http/server.go index a7df317d..60a01747 100644 --- a/proxy/http/server.go +++ b/proxy/http/server.go @@ -94,12 +94,12 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con Start: if err := conn.SetReadDeadline(time.Now().Add(s.policy().Timeouts.Handshake)); err != nil { - newError("failed to set read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to set read deadline") } request, err := http.ReadRequest(reader) if err != nil { - trace := newError("failed to read http request").Base(err) + trace := errors.New("failed to read http request").Base(err) if errors.Cause(err) != io.EOF && !isTimeout(errors.Cause(err)) { trace.AtWarning() } @@ -116,9 +116,9 @@ Start: } } - newError("request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]").WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]") if err := conn.SetReadDeadline(time.Time{}); err != nil { - newError("failed to clear read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebugInner(ctx, err, "failed to clear read deadline") } defaultPort := net.Port(80) @@ -131,7 +131,7 @@ Start: } dest, err := http_proto.ParseHost(host, defaultPort) if err != nil { - return newError("malformed proxy host: ", host).AtWarning().Base(err) + return errors.New("malformed proxy host: ", host).AtWarning().Base(err) } ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: conn.RemoteAddr(), @@ -160,7 +160,7 @@ Start: func (s *Server) handleConnect(ctx context.Context, _ *http.Request, reader *bufio.Reader, conn stat.Connection, dest net.Destination, dispatcher routing.Dispatcher, inbound *session.Inbound) error { _, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")) if err != nil { - return newError("failed to write back OK response").Base(err) + return errors.New("failed to write back OK response").Base(err) } plcy := s.policy() @@ -209,13 +209,13 @@ func (s *Server) handleConnect(ctx context.Context, _ *http.Request, reader *buf if err := task.Run(ctx, closeWriter, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil } -var errWaitAnother = newError("keep alive") +var errWaitAnother = errors.New("keep alive") func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, writer io.Writer, dest net.Destination, dispatcher routing.Dispatcher) error { if !s.config.AllowTransparent && request.URL.Host == "" { @@ -274,7 +274,7 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri requestWriter := buf.NewBufferedWriter(link.Writer) common.Must(requestWriter.SetBuffered(false)) if err := request.Write(requestWriter); err != nil { - return newError("failed to write whole request").Base(err).AtWarning() + return errors.New("failed to write whole request").Base(err).AtWarning() } return nil } @@ -295,7 +295,7 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri } defer response.Body.Close() } else { - newError("failed to read response from ", request.Host).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, err, "failed to read response from ", request.Host) response = &http.Response{ Status: "Service Unavailable", StatusCode: 503, @@ -311,7 +311,7 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri response.Header.Set("Proxy-Connection", "close") } if err := response.Write(writer); err != nil { - return newError("failed to write response").Base(err).AtWarning() + return errors.New("failed to write response").Base(err).AtWarning() } return nil } @@ -319,7 +319,7 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri if err := task.Run(ctx, requestDone, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return result diff --git a/proxy/loopback/errors.generated.go b/proxy/loopback/errors.generated.go deleted file mode 100644 index 0db02932..00000000 --- a/proxy/loopback/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package loopback - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/loopback/loopback.go b/proxy/loopback/loopback.go index f3be5a95..e1cac3c6 100644 --- a/proxy/loopback/loopback.go +++ b/proxy/loopback/loopback.go @@ -5,6 +5,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/retry" @@ -23,14 +24,14 @@ type Loopback struct { func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified.") + return errors.New("target not specified.") } ob.Name = "loopback" destination := ob.Target - newError("opening connection to ", destination).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "opening connection to ", destination) input := link.Reader output := link.Writer @@ -66,7 +67,7 @@ func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet return nil }) if err != nil { - return newError("failed to open connection to ", destination).Base(err) + return errors.New("failed to open connection to ", destination).Base(err) } defer conn.Close() @@ -79,7 +80,7 @@ func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet } if err := buf.Copy(input, writer); err != nil { - return newError("failed to process request").Base(err) + return errors.New("failed to process request").Base(err) } return nil @@ -93,14 +94,14 @@ func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet reader = buf.NewPacketReader(conn) } if err := buf.Copy(reader, output); err != nil { - return newError("failed to process response").Base(err) + return errors.New("failed to process response").Base(err) } return nil } if err := task.Run(ctx, requestDone, task.OnSuccess(responseDone, task.Close(output))); err != nil { - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil diff --git a/proxy/proxy.go b/proxy/proxy.go index db920510..87abd1a2 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -102,7 +102,7 @@ type TrafficState struct { // reader link state WithinPaddingBuffers bool ReaderSwitchToDirectCopy bool - RemainingCommand int32 + RemainingCommand int32 RemainingContent int32 RemainingPadding int32 CurrentCommand int @@ -168,7 +168,7 @@ func (w *VisionReader) ReadMultiBuffer() (buf.MultiBuffer, error) { w.trafficState.WithinPaddingBuffers = false w.trafficState.ReaderSwitchToDirectCopy = true } else { - newError("XtlsRead unknown command ", w.trafficState.CurrentCommand, buffer.Len()).WriteToLog(session.ExportIDToError(w.ctx)) + errors.LogInfo(w.ctx, "XtlsRead unknown command ", w.trafficState.CurrentCommand, buffer.Len()) } } if w.trafficState.NumberOfPacketToFilter > 0 { @@ -215,7 +215,7 @@ func (w *VisionWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { w.trafficState.WriterSwitchToDirectCopy = true } var command byte = CommandPaddingContinue - if i == len(mb) - 1 { + if i == len(mb)-1 { command = CommandPaddingEnd if w.trafficState.EnableXtls { command = CommandPaddingDirect @@ -231,7 +231,7 @@ func (w *VisionWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { break } var command byte = CommandPaddingContinue - if i == len(mb) - 1 && !w.trafficState.IsPadding { + if i == len(mb)-1 && !w.trafficState.IsPadding { command = CommandPaddingEnd if w.trafficState.EnableXtls { command = CommandPaddingDirect @@ -274,7 +274,7 @@ func ReshapeMultiBuffer(ctx context.Context, buffer buf.MultiBuffer) buf.MultiBu buffer[i] = nil } buffer = buffer[:0] - newError("ReshapeMultiBuffer ", toPrint).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "ReshapeMultiBuffer ", toPrint) return mb2 } @@ -288,13 +288,13 @@ func XtlsPadding(b *buf.Buffer, command byte, userUUID *[]byte, longPadding bool if contentLen < 900 && longPadding { l, err := rand.Int(rand.Reader, big.NewInt(500)) if err != nil { - newError("failed to generate padding").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebugInner(ctx, err, "failed to generate padding") } paddingLen = int32(l.Int64()) + 900 - contentLen } else { l, err := rand.Int(rand.Reader, big.NewInt(256)) if err != nil { - newError("failed to generate padding").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebugInner(ctx, err, "failed to generate padding") } paddingLen = int32(l.Int64()) } @@ -313,7 +313,7 @@ func XtlsPadding(b *buf.Buffer, command byte, userUUID *[]byte, longPadding bool b = nil } newbuffer.Extend(paddingLen) - newError("XtlsPadding ", contentLen, " ", paddingLen, " ", command).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "XtlsPadding ", contentLen, " ", paddingLen, " ", command) return newbuffer } @@ -338,14 +338,14 @@ func XtlsUnpadding(b *buf.Buffer, s *TrafficState, ctx context.Context) *buf.Buf case 5: s.CurrentCommand = int(data) case 4: - s.RemainingContent = int32(data)<<8 + s.RemainingContent = int32(data) << 8 case 3: s.RemainingContent = s.RemainingContent | int32(data) case 2: - s.RemainingPadding = int32(data)<<8 + s.RemainingPadding = int32(data) << 8 case 1: s.RemainingPadding = s.RemainingPadding | int32(data) - newError("Xtls Unpadding new block, content ", s.RemainingContent, " padding ", s.RemainingPadding, " command ", s.CurrentCommand).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "Xtls Unpadding new block, content ", s.RemainingContent, " padding ", s.RemainingPadding, " command ", s.CurrentCommand) } s.RemainingCommand-- } else if s.RemainingContent > 0 { @@ -404,11 +404,11 @@ func XtlsFilterTls(buffer buf.MultiBuffer, trafficState *TrafficState, ctx conte cipherSuite := b.BytesRange(43+sessionIdLen+1, 43+sessionIdLen+3) trafficState.Cipher = uint16(cipherSuite[0])<<8 | uint16(cipherSuite[1]) } else { - newError("XtlsFilterTls short server hello, tls 1.2 or older? ", b.Len(), " ", trafficState.RemainingServerHello).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "XtlsFilterTls short server hello, tls 1.2 or older? ", b.Len(), " ", trafficState.RemainingServerHello) } } else if bytes.Equal(TlsClientHandShakeStart, startsBytes[:2]) && startsBytes[5] == TlsHandshakeTypeClientHello { trafficState.IsTLS = true - newError("XtlsFilterTls found tls client hello! ", buffer.Len()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "XtlsFilterTls found tls client hello! ", buffer.Len()) } } if trafficState.RemainingServerHello > 0 { @@ -424,18 +424,18 @@ func XtlsFilterTls(buffer buf.MultiBuffer, trafficState *TrafficState, ctx conte } else if v != "TLS_AES_128_CCM_8_SHA256" { trafficState.EnableXtls = true } - newError("XtlsFilterTls found tls 1.3! ", b.Len(), " ", v).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "XtlsFilterTls found tls 1.3! ", b.Len(), " ", v) trafficState.NumberOfPacketToFilter = 0 return } else if trafficState.RemainingServerHello <= 0 { - newError("XtlsFilterTls found tls 1.2! ", b.Len()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "XtlsFilterTls found tls 1.2! ", b.Len()) trafficState.NumberOfPacketToFilter = 0 return } - newError("XtlsFilterTls inconclusive server hello ", b.Len(), " ", trafficState.RemainingServerHello).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "XtlsFilterTls inconclusive server hello ", b.Len(), " ", trafficState.RemainingServerHello) } if trafficState.NumberOfPacketToFilter <= 0 { - newError("XtlsFilterTls stop filtering", buffer.Len()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "XtlsFilterTls stop filtering", buffer.Len()) } } } @@ -505,10 +505,10 @@ func CopyRawConnIfExist(ctx context.Context, readerConn net.Conn, writerConn net } } if splice { - newError("CopyRawConn splice").WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "CopyRawConn splice") statWriter, _ := writer.(*dispatcher.SizeStatWriter) //runtime.Gosched() // necessary - time.Sleep(time.Millisecond) // without this, there will be a rare ssl error for freedom splice + time.Sleep(time.Millisecond) // without this, there will be a rare ssl error for freedom splice timer.SetTimeout(8 * time.Hour) // prevent leak, just in case if inTimer != nil { inTimer.SetTimeout(8 * time.Hour) @@ -545,9 +545,9 @@ func CopyRawConnIfExist(ctx context.Context, readerConn net.Conn, writerConn net } func readV(ctx context.Context, reader buf.Reader, writer buf.Writer, timer signal.ActivityUpdater, readCounter stats.Counter) error { - newError("CopyRawConn readv").WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "CopyRawConn readv") if err := buf.Copy(reader, writer, buf.UpdateActivity(timer), buf.AddToStatCounter(readCounter)); err != nil { - return newError("failed to process response").Base(err) + return errors.New("failed to process response").Base(err) } return nil } diff --git a/proxy/shadowsocks/client.go b/proxy/shadowsocks/client.go index 8ebe7631..c2ad1c1c 100644 --- a/proxy/shadowsocks/client.go +++ b/proxy/shadowsocks/client.go @@ -6,6 +6,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "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/retry" @@ -31,12 +32,12 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { for _, rec := range config.Server { s, err := protocol.NewServerSpecFromPB(rec) if err != nil { - return nil, newError("failed to parse server spec").Base(err) + return nil, errors.New("failed to parse server spec").Base(err) } serverList.AddServer(s) } if serverList.Size() == 0 { - return nil, newError("0 server") + return nil, errors.New("0 server") } v := core.MustFromContext(ctx) @@ -50,9 +51,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { // Process implements OutboundHandler.Process(). func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified") + return errors.New("target not specified") } ob.Name = "shadowsocks" ob.CanSpliceCopy = 3 @@ -75,9 +76,9 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter return nil }) if err != nil { - return newError("failed to find an available destination").AtWarning().Base(err) + return errors.New("failed to find an available destination").AtWarning().Base(err) } - newError("tunneling request to ", destination, " via ", network, ":", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunneling request to ", destination, " via ", network, ":", server.Destination().NetAddr()) defer conn.Close() @@ -95,7 +96,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter user := server.PickUser() _, ok := user.Account.(*MemoryAccount) if !ok { - return newError("user account is not valid") + return errors.New("user account is not valid") } request.User = user @@ -124,11 +125,11 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) bodyWriter, err := WriteTCPRequest(request, bufferedWriter) if err != nil { - return newError("failed to write request").Base(err) + return errors.New("failed to write request").Base(err) } if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { - return newError("failed to write A request payload").Base(err).AtWarning() + return errors.New("failed to write A request payload").Base(err).AtWarning() } if err := bufferedWriter.SetBuffered(false); err != nil { @@ -151,7 +152,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer)) if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil @@ -168,7 +169,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter } if err := buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport all UDP request").Base(err) + return errors.New("failed to transport all UDP request").Base(err) } return nil } @@ -182,14 +183,14 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter } if err := buf.Copy(reader, link.Writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport all UDP response").Base(err) + return errors.New("failed to transport all UDP response").Base(err) } return nil } responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer)) if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil { - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil diff --git a/proxy/shadowsocks/config.go b/proxy/shadowsocks/config.go index 1b977ded..396e59be 100644 --- a/proxy/shadowsocks/config.go +++ b/proxy/shadowsocks/config.go @@ -12,6 +12,7 @@ import ( "github.com/xtls/xray-core/common/antireplay" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/crypto" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" "golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/hkdf" @@ -25,7 +26,7 @@ type MemoryAccount struct { replayFilter antireplay.GeneralizedReplayFilter } -var ErrIVNotUnique = newError("IV is not unique") +var ErrIVNotUnique = errors.New("IV is not unique") // Equals implements protocol.Account.Equals(). func (a *MemoryAccount) Equals(another protocol.Account) bool { @@ -94,7 +95,7 @@ func (a *Account) getCipher() (Cipher, error) { case CipherType_NONE: return NoneCipher{}, nil default: - return nil, newError("Unsupported cipher.") + return nil, errors.New("Unsupported cipher.") } } @@ -102,7 +103,7 @@ func (a *Account) getCipher() (Cipher, error) { func (a *Account) AsAccount() (protocol.Account, error) { Cipher, err := a.getCipher() if err != nil { - return nil, newError("failed to get cipher").Base(err) + return nil, errors.New("failed to get cipher").Base(err) } return &MemoryAccount{ Cipher: Cipher, @@ -182,7 +183,7 @@ func (c *AEADCipher) EncodePacket(key []byte, b *buf.Buffer) error { func (c *AEADCipher) DecodePacket(key []byte, b *buf.Buffer) error { if b.Len() <= c.IVSize() { - return newError("insufficient data: ", b.Len()) + return errors.New("insufficient data: ", b.Len()) } ivLen := c.IVSize() payloadLen := b.Len() diff --git a/proxy/shadowsocks/errors.generated.go b/proxy/shadowsocks/errors.generated.go deleted file mode 100644 index dd33902b..00000000 --- a/proxy/shadowsocks/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package shadowsocks - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/shadowsocks/protocol.go b/proxy/shadowsocks/protocol.go index 3a0c7e22..00855c73 100644 --- a/proxy/shadowsocks/protocol.go +++ b/proxy/shadowsocks/protocol.go @@ -4,12 +4,13 @@ import ( "crypto/hmac" "crypto/rand" "crypto/sha256" - "errors" + goerrors "errors" "hash/crc32" "io" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/crypto" "github.com/xtls/xray-core/common/drain" "github.com/xtls/xray-core/common/net" @@ -58,7 +59,7 @@ func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHe drainer, errDrain := drain.NewBehaviorSeedLimitedDrainer(int64(behaviorSeed), 16+38, 3266, 64) if errDrain != nil { - return nil, nil, newError("failed to initialize drainer").Base(errDrain) + return nil, nil, errors.New("failed to initialize drainer").Base(errDrain) } var r buf.Reader @@ -67,7 +68,7 @@ func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHe if _, err := buffer.ReadFullFrom(reader, 50); err != nil { drainer.AcknowledgeReceive(int(buffer.Len())) - return nil, nil, drain.WithError(drainer, reader, newError("failed to read 50 bytes").Base(err)) + return nil, nil, drain.WithError(drainer, reader, errors.New("failed to read 50 bytes").Base(err)) } bs := buffer.Bytes() @@ -76,10 +77,10 @@ func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHe switch err { case ErrNotFound: drainer.AcknowledgeReceive(int(buffer.Len())) - return nil, nil, drain.WithError(drainer, reader, newError("failed to match an user").Base(err)) + return nil, nil, drain.WithError(drainer, reader, errors.New("failed to match an user").Base(err)) case ErrIVNotUnique: drainer.AcknowledgeReceive(int(buffer.Len())) - return nil, nil, drain.WithError(drainer, reader, newError("failed iv check").Base(err)) + return nil, nil, drain.WithError(drainer, reader, errors.New("failed iv check").Base(err)) default: reader = &FullReader{reader, bs[ivLen:]} drainer.AcknowledgeReceive(int(ivLen)) @@ -97,7 +98,7 @@ func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHe iv := append([]byte(nil), buffer.BytesTo(ivLen)...) r, err = account.Cipher.NewDecryptionReader(account.Key, iv, reader) if err != nil { - return nil, nil, drain.WithError(drainer, reader, newError("failed to initialize decoding stream").Base(err).AtError()) + return nil, nil, drain.WithError(drainer, reader, errors.New("failed to initialize decoding stream").Base(err).AtError()) } } } @@ -115,7 +116,7 @@ func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHe addr, port, err := addrParser.ReadAddressPort(buffer, br) if err != nil { drainer.AcknowledgeReceive(int(buffer.Len())) - return nil, nil, drain.WithError(drainer, reader, newError("failed to read address").Base(err)) + return nil, nil, drain.WithError(drainer, reader, errors.New("failed to read address").Base(err)) } request.Address = addr @@ -123,7 +124,7 @@ func ReadTCPSession(validator *Validator, reader io.Reader) (*protocol.RequestHe if request.Address == nil { drainer.AcknowledgeReceive(int(buffer.Len())) - return nil, nil, drain.WithError(drainer, reader, newError("invalid remote address.")) + return nil, nil, drain.WithError(drainer, reader, errors.New("invalid remote address.")) } return request, br, nil @@ -139,26 +140,26 @@ func WriteTCPRequest(request *protocol.RequestHeader, writer io.Writer) (buf.Wri iv = make([]byte, account.Cipher.IVSize()) common.Must2(rand.Read(iv)) if ivError := account.CheckIV(iv); ivError != nil { - return nil, newError("failed to mark outgoing iv").Base(ivError) + return nil, errors.New("failed to mark outgoing iv").Base(ivError) } if err := buf.WriteAllBytes(writer, iv, nil); err != nil { - return nil, newError("failed to write IV") + return nil, errors.New("failed to write IV") } } w, err := account.Cipher.NewEncryptionWriter(account.Key, iv, writer) if err != nil { - return nil, newError("failed to create encoding stream").Base(err).AtError() + return nil, errors.New("failed to create encoding stream").Base(err).AtError() } header := buf.New() if err := addrParser.WriteAddressPort(header, request.Address, request.Port); err != nil { - return nil, newError("failed to write address").Base(err) + return nil, errors.New("failed to write address").Base(err) } if err := w.WriteMultiBuffer(buf.MultiBuffer{header}); err != nil { - return nil, newError("failed to write header").Base(err) + return nil, errors.New("failed to write header").Base(err) } return w, nil @@ -174,21 +175,21 @@ func ReadTCPResponse(user *protocol.MemoryUser, reader io.Reader) (buf.Reader, e drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(behaviorSeed), 16+38, 3266, 64) if err != nil { - return nil, newError("failed to initialize drainer").Base(err) + return nil, errors.New("failed to initialize drainer").Base(err) } var iv []byte if account.Cipher.IVSize() > 0 { iv = make([]byte, account.Cipher.IVSize()) if n, err := io.ReadFull(reader, iv); err != nil { - return nil, newError("failed to read IV").Base(err) + return nil, errors.New("failed to read IV").Base(err) } else { // nolint: golint drainer.AcknowledgeReceive(n) } } if ivError := account.CheckIV(iv); ivError != nil { - return nil, drain.WithError(drainer, reader, newError("failed iv check").Base(ivError)) + return nil, drain.WithError(drainer, reader, errors.New("failed iv check").Base(ivError)) } return account.Cipher.NewDecryptionReader(account.Key, iv, reader) @@ -203,10 +204,10 @@ func WriteTCPResponse(request *protocol.RequestHeader, writer io.Writer) (buf.Wr iv = make([]byte, account.Cipher.IVSize()) common.Must2(rand.Read(iv)) if ivError := account.CheckIV(iv); ivError != nil { - return nil, newError("failed to mark outgoing iv").Base(ivError) + return nil, errors.New("failed to mark outgoing iv").Base(ivError) } if err := buf.WriteAllBytes(writer, iv, nil); err != nil { - return nil, newError("failed to write IV.").Base(err) + return nil, errors.New("failed to write IV.").Base(err) } } @@ -224,13 +225,13 @@ func EncodeUDPPacket(request *protocol.RequestHeader, payload []byte) (*buf.Buff } if err := addrParser.WriteAddressPort(buffer, request.Address, request.Port); err != nil { - return nil, newError("failed to write address").Base(err) + return nil, errors.New("failed to write address").Base(err) } buffer.Write(payload) if err := account.Cipher.EncodePacket(account.Key, buffer); err != nil { - return nil, newError("failed to encrypt UDP payload").Base(err) + return nil, errors.New("failed to encrypt UDP payload").Base(err) } return buffer, nil @@ -240,21 +241,21 @@ func DecodeUDPPacket(validator *Validator, payload *buf.Buffer) (*protocol.Reque rawPayload := payload.Bytes() user, _, d, _, err := validator.Get(rawPayload, protocol.RequestCommandUDP) - if errors.Is(err, ErrIVNotUnique) { - return nil, nil, newError("failed iv check").Base(err) + if goerrors.Is(err, ErrIVNotUnique) { + return nil, nil, errors.New("failed iv check").Base(err) } - if errors.Is(err, ErrNotFound) { - return nil, nil, newError("failed to match an user").Base(err) + if goerrors.Is(err, ErrNotFound) { + return nil, nil, errors.New("failed to match an user").Base(err) } if err != nil { - return nil, nil, newError("unexpected error").Base(err) + return nil, nil, errors.New("unexpected error").Base(err) } account, ok := user.Account.(*MemoryAccount) if !ok { - return nil, nil, newError("expected MemoryAccount returned from validator") + return nil, nil, errors.New("expected MemoryAccount returned from validator") } if account.Cipher.IsAEAD() { @@ -266,7 +267,7 @@ func DecodeUDPPacket(validator *Validator, payload *buf.Buffer) (*protocol.Reque copy(iv, payload.BytesTo(account.Cipher.IVSize())) } if err = account.Cipher.DecodePacket(account.Key, payload); err != nil { - return nil, nil, newError("failed to decrypt UDP payload").Base(err) + return nil, nil, errors.New("failed to decrypt UDP payload").Base(err) } } @@ -274,7 +275,7 @@ func DecodeUDPPacket(validator *Validator, payload *buf.Buffer) (*protocol.Reque addr, port, err := addrParser.ReadAddressPort(nil, payload) if err != nil { - return nil, nil, newError("failed to parse address").Base(err) + return nil, nil, errors.New("failed to parse address").Base(err) } request := &protocol.RequestHeader{ diff --git a/proxy/shadowsocks/server.go b/proxy/shadowsocks/server.go index 8253506a..e6135a45 100644 --- a/proxy/shadowsocks/server.go +++ b/proxy/shadowsocks/server.go @@ -6,6 +6,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol" @@ -33,11 +34,11 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) { for _, user := range config.Users { u, err := user.ToMemoryUser() if err != nil { - return nil, newError("failed to get shadowsocks user").Base(err).AtError() + return nil, errors.New("failed to get shadowsocks user").Base(err).AtError() } if err := validator.Add(u); err != nil { - return nil, newError("failed to add user").Base(err).AtError() + return nil, errors.New("failed to add user").Base(err).AtError() } } @@ -74,14 +75,14 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con inbound := session.InboundFromContext(ctx) inbound.Name = "shadowsocks" inbound.CanSpliceCopy = 3 - + switch network { case net.Network_TCP: return s.handleConnection(ctx, conn, dispatcher) case net.Network_UDP: return s.handleUDPPayload(ctx, conn, dispatcher) default: - return newError("unknown network: ", network) + return errors.New("unknown network: ", network) } } @@ -105,7 +106,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis data, err := EncodeUDPPacket(request, payload.Bytes()) payload.Release() if err != nil { - newError("failed to encode UDP packet").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, err, "failed to encode UDP packet") return } defer data.Release() @@ -140,7 +141,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis if err != nil { if inbound.Source.IsValid() { - newError("dropping invalid UDP packet from: ", inbound.Source).Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "dropping invalid UDP packet from: ", inbound.Source) log.Record(&log.AccessMessage{ From: inbound.Source, To: "", @@ -164,7 +165,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis Email: request.User.Email, }) } - newError("tunnelling request to ", destination).WriteToLog(session.ExportIDToError(currentPacketCtx)) + errors.LogInfo(ctx, "tunnelling request to ", destination) data.UDP = &destination @@ -183,7 +184,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dispatcher routing.Dispatcher) error { sessionPolicy := s.policyManager.ForLevel(0) if err := conn.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil { - return newError("unable to set read deadline").Base(err).AtWarning() + return errors.New("unable to set read deadline").Base(err).AtWarning() } bufferedReader := buf.BufferedReader{Reader: buf.NewReader(conn)} @@ -195,7 +196,7 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis Status: log.AccessRejected, Reason: err, }) - return newError("failed to create request from: ", conn.RemoteAddr()).Base(err) + return errors.New("failed to create request from: ", conn.RemoteAddr()).Base(err) } conn.SetReadDeadline(time.Time{}) @@ -213,7 +214,7 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis Reason: "", Email: request.User.Email, }) - newError("tunnelling request to ", dest).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunnelling request to ", dest) sessionPolicy = s.policyManager.ForLevel(request.User.Level) ctx, cancel := context.WithCancel(ctx) @@ -231,7 +232,7 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis bufferedWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) responseWriter, err := WriteTCPResponse(request, bufferedWriter) if err != nil { - return newError("failed to write response").Base(err) + return errors.New("failed to write response").Base(err) } { @@ -249,7 +250,7 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis } if err := buf.Copy(link.Reader, responseWriter, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport all TCP response").Base(err) + return errors.New("failed to transport all TCP response").Base(err) } return nil @@ -259,7 +260,7 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport all TCP request").Base(err) + return errors.New("failed to transport all TCP request").Base(err) } return nil @@ -269,7 +270,7 @@ func (s *Server) handleConnection(ctx context.Context, conn stat.Connection, dis if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil diff --git a/proxy/shadowsocks/validator.go b/proxy/shadowsocks/validator.go index 8888a1c0..ae92a8dc 100644 --- a/proxy/shadowsocks/validator.go +++ b/proxy/shadowsocks/validator.go @@ -9,6 +9,7 @@ import ( "sync" "github.com/xtls/xray-core/common/dice" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" ) @@ -21,7 +22,7 @@ type Validator struct { behaviorFused bool } -var ErrNotFound = newError("Not Found") +var ErrNotFound = errors.New("Not Found") // Add a Shadowsocks user. func (v *Validator) Add(u *protocol.MemoryUser) error { @@ -30,7 +31,7 @@ func (v *Validator) Add(u *protocol.MemoryUser) error { account := u.Account.(*MemoryAccount) if !account.Cipher.IsAEAD() && len(v.users) > 0 { - return newError("The cipher is not support Single-port Multi-user") + return errors.New("The cipher is not support Single-port Multi-user") } v.users = append(v.users, u) @@ -46,7 +47,7 @@ func (v *Validator) Add(u *protocol.MemoryUser) error { // Del a Shadowsocks user with a non-empty Email. func (v *Validator) Del(email string) error { if email == "" { - return newError("Email must not be empty.") + return errors.New("Email must not be empty.") } v.Lock() @@ -62,7 +63,7 @@ func (v *Validator) Del(email string) error { } if idx == -1 { - return newError("User ", email, " not found.") + return errors.New("User ", email, " not found.") } ulen := len(v.users) diff --git a/proxy/shadowsocks_2022/errors.generated.go b/proxy/shadowsocks_2022/errors.generated.go deleted file mode 100644 index 90db3d5e..00000000 --- a/proxy/shadowsocks_2022/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package shadowsocks_2022 - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/shadowsocks_2022/inbound.go b/proxy/shadowsocks_2022/inbound.go index f1eb76a5..a889fa0f 100644 --- a/proxy/shadowsocks_2022/inbound.go +++ b/proxy/shadowsocks_2022/inbound.go @@ -13,6 +13,7 @@ import ( N "github.com/sagernet/sing/common/network" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol" @@ -49,11 +50,11 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Inbound, error) { level: int(config.Level), } if !C.Contains(shadowaead_2022.List, config.Method) { - return nil, newError("unsupported method ", config.Method) + return nil, errors.New("unsupported method ", config.Method) } service, err := shadowaead_2022.NewServiceWithPassword(config.Method, config.Key, 500, inbound, nil) if err != nil { - return nil, newError("create service").Base(err) + return nil, errors.New("create service").Base(err) } inbound.service = service return inbound, nil @@ -112,7 +113,7 @@ func (i *Inbound) NewConnection(ctx context.Context, conn net.Conn, metadata M.M Status: log.AccessAccepted, Email: i.email, }) - newError("tunnelling request to tcp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunnelling request to tcp:", metadata.Destination) dispatcher := session.DispatcherFromContext(ctx) link, err := dispatcher.Dispatch(ctx, singbridge.ToDestination(metadata.Destination, net.Network_TCP)) if err != nil { @@ -133,7 +134,7 @@ func (i *Inbound) NewPacketConnection(ctx context.Context, conn N.PacketConn, me Status: log.AccessAccepted, Email: i.email, }) - newError("tunnelling request to udp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunnelling request to udp:", metadata.Destination) dispatcher := session.DispatcherFromContext(ctx) destination := singbridge.ToDestination(metadata.Destination, net.Network_UDP) link, err := dispatcher.Dispatch(ctx, destination) @@ -152,7 +153,7 @@ func (i *Inbound) NewError(ctx context.Context, err error) { if E.IsClosed(err) { return } - newError(err).AtWarning().WriteToLog() + errors.LogWarning(ctx, err.Error()) } type natPacketConn struct { diff --git a/proxy/shadowsocks_2022/inbound_multi.go b/proxy/shadowsocks_2022/inbound_multi.go index f80ec6d1..8cb2d65e 100644 --- a/proxy/shadowsocks_2022/inbound_multi.go +++ b/proxy/shadowsocks_2022/inbound_multi.go @@ -17,6 +17,7 @@ import ( N "github.com/sagernet/sing/common/network" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol" @@ -53,15 +54,15 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU users: config.Users, } if config.Key == "" { - return nil, newError("missing key") + return nil, errors.New("missing key") } psk, err := base64.StdEncoding.DecodeString(config.Key) if err != nil { - return nil, newError("parse config").Base(err) + return nil, errors.New("parse config").Base(err) } service, err := shadowaead_2022.NewMultiService[int](config.Method, psk, 500, inbound, nil) if err != nil { - return nil, newError("create service").Base(err) + return nil, errors.New("create service").Base(err) } for i, user := range config.Users { @@ -75,7 +76,7 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU C.Map(config.Users, func(it *User) string { return it.Key }), ) if err != nil { - return nil, newError("create service").Base(err) + return nil, errors.New("create service").Base(err) } inbound.service = service @@ -91,7 +92,7 @@ func (i *MultiUserInbound) AddUser(ctx context.Context, u *protocol.MemoryUser) if account.Email != "" { for idx := range i.users { if i.users[idx].Email == account.Email { - return newError("User ", account.Email, " already exists.") + return errors.New("User ", account.Email, " already exists.") } } } @@ -114,7 +115,7 @@ func (i *MultiUserInbound) AddUser(ctx context.Context, u *protocol.MemoryUser) // RemoveUser implements proxy.UserManager.RemoveUser(). func (i *MultiUserInbound) RemoveUser(ctx context.Context, email string) error { if email == "" { - return newError("Email must not be empty.") + return errors.New("Email must not be empty.") } i.Lock() @@ -129,7 +130,7 @@ func (i *MultiUserInbound) RemoveUser(ctx context.Context, email string) error { } if idx == -1 { - return newError("User ", email, " not found.") + return errors.New("User ", email, " not found.") } ulen := len(i.users) @@ -203,11 +204,11 @@ func (i *MultiUserInbound) NewConnection(ctx context.Context, conn net.Conn, met Status: log.AccessAccepted, Email: user.Email, }) - newError("tunnelling request to tcp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunnelling request to tcp:", metadata.Destination) dispatcher := session.DispatcherFromContext(ctx) destination := singbridge.ToDestination(metadata.Destination, net.Network_TCP) if !destination.IsValid() { - return newError("invalid destination") + return errors.New("invalid destination") } link, err := dispatcher.Dispatch(ctx, destination) @@ -231,7 +232,7 @@ func (i *MultiUserInbound) NewPacketConnection(ctx context.Context, conn N.Packe Status: log.AccessAccepted, Email: user.Email, }) - newError("tunnelling request to udp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunnelling request to udp:", metadata.Destination) dispatcher := session.DispatcherFromContext(ctx) destination := singbridge.ToDestination(metadata.Destination, net.Network_UDP) link, err := dispatcher.Dispatch(ctx, destination) @@ -250,5 +251,5 @@ func (i *MultiUserInbound) NewError(ctx context.Context, err error) { if E.IsClosed(err) { return } - newError(err).AtWarning().WriteToLog() + errors.LogWarning(ctx, err.Error()) } diff --git a/proxy/shadowsocks_2022/inbound_relay.go b/proxy/shadowsocks_2022/inbound_relay.go index 1c4b8248..19afd462 100644 --- a/proxy/shadowsocks_2022/inbound_relay.go +++ b/proxy/shadowsocks_2022/inbound_relay.go @@ -15,6 +15,7 @@ import ( N "github.com/sagernet/sing/common/network" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol" @@ -50,11 +51,11 @@ func NewRelayServer(ctx context.Context, config *RelayServerConfig) (*RelayInbou destinations: config.Destinations, } if !C.Contains(shadowaead_2022.List, config.Method) || !strings.Contains(config.Method, "aes") { - return nil, newError("unsupported method ", config.Method) + return nil, errors.New("unsupported method ", config.Method) } service, err := shadowaead_2022.NewRelayServiceWithPassword[int](config.Method, config.Key, 500, inbound) if err != nil { - return nil, newError("create service").Base(err) + return nil, errors.New("create service").Base(err) } for i, destination := range config.Destinations { @@ -74,7 +75,7 @@ func NewRelayServer(ctx context.Context, config *RelayServerConfig) (*RelayInbou }), ) if err != nil { - return nil, newError("create service").Base(err) + return nil, errors.New("create service").Base(err) } inbound.service = service return inbound, nil @@ -135,7 +136,7 @@ func (i *RelayInbound) NewConnection(ctx context.Context, conn net.Conn, metadat Status: log.AccessAccepted, Email: user.Email, }) - newError("tunnelling request to tcp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunnelling request to tcp:", metadata.Destination) dispatcher := session.DispatcherFromContext(ctx) link, err := dispatcher.Dispatch(ctx, singbridge.ToDestination(metadata.Destination, net.Network_TCP)) if err != nil { @@ -158,7 +159,7 @@ func (i *RelayInbound) NewPacketConnection(ctx context.Context, conn N.PacketCon Status: log.AccessAccepted, Email: user.Email, }) - newError("tunnelling request to udp:", metadata.Destination).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunnelling request to udp:", metadata.Destination) dispatcher := session.DispatcherFromContext(ctx) destination := singbridge.ToDestination(metadata.Destination, net.Network_UDP) link, err := dispatcher.Dispatch(ctx, destination) @@ -177,5 +178,5 @@ func (i *RelayInbound) NewError(ctx context.Context, err error) { if E.IsClosed(err) { return } - newError(err).AtWarning().WriteToLog() + errors.LogWarning(ctx, err.Error()) } diff --git a/proxy/shadowsocks_2022/outbound.go b/proxy/shadowsocks_2022/outbound.go index cac9a91b..dd2e4259 100644 --- a/proxy/shadowsocks_2022/outbound.go +++ b/proxy/shadowsocks_2022/outbound.go @@ -13,6 +13,7 @@ import ( "github.com/sagernet/sing/common/uot" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/singbridge" @@ -44,15 +45,15 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Outbound, error) { } if C.Contains(shadowaead_2022.List, config.Method) { if config.Key == "" { - return nil, newError("missing psk") + return nil, errors.New("missing psk") } method, err := shadowaead_2022.NewWithPassword(config.Method, config.Key, nil) if err != nil { - return nil, newError("create method").Base(err) + return nil, errors.New("create method").Base(err) } o.method = method } else { - return nil, newError("unknown method ", config.Method) + return nil, errors.New("unknown method ", config.Method) } if config.UdpOverTcp { o.uotClient = &uot.Client{Version: uint8(config.UdpOverTcpVersion)} @@ -68,16 +69,16 @@ func (o *Outbound) Process(ctx context.Context, link *transport.Link, dialer int } outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified") + return errors.New("target not specified") } ob.Name = "shadowsocks-2022" ob.CanSpliceCopy = 3 destination := ob.Target network := destination.Network - newError("tunneling request to ", destination, " via ", o.server.NetAddr()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunneling request to ", destination, " via ", o.server.NetAddr()) serverDestination := o.server if o.uotClient != nil { @@ -87,7 +88,7 @@ func (o *Outbound) Process(ctx context.Context, link *transport.Link, dialer int } connection, err := dialer.Dial(ctx, serverDestination) if err != nil { - return newError("failed to connect to server").Base(err) + return errors.New("failed to connect to server").Base(err) } if session.TimeoutOnlyFromContext(ctx) { @@ -100,7 +101,7 @@ func (o *Outbound) Process(ctx context.Context, link *transport.Link, dialer int if timeoutReader, isTimeoutReader := link.Reader.(buf.TimeoutReader); isTimeoutReader { mb, err := timeoutReader.ReadMultiBufferTimeout(time.Millisecond * 100) if err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { - return newError("read payload").Base(err) + return errors.New("read payload").Base(err) } payload := B.New() for { @@ -111,7 +112,7 @@ func (o *Outbound) Process(ctx context.Context, link *transport.Link, dialer int _, err = serverConn.Write(payload.Bytes()) if err != nil { payload.Release() - return newError("write payload").Base(err) + return errors.New("write payload").Base(err) } handshake = true } @@ -125,7 +126,7 @@ func (o *Outbound) Process(ctx context.Context, link *transport.Link, dialer int if !handshake { _, err = serverConn.Write(nil) if err != nil { - return newError("client handshake").Base(err) + return errors.New("client handshake").Base(err) } } return singbridge.CopyConn(ctx, inboundConn, link, serverConn) diff --git a/proxy/socks/client.go b/proxy/socks/client.go index b283eb65..ec1a3ce1 100644 --- a/proxy/socks/client.go +++ b/proxy/socks/client.go @@ -6,6 +6,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "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/retry" @@ -34,12 +35,12 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { for _, rec := range config.Server { s, err := protocol.NewServerSpecFromPB(rec) if err != nil { - return nil, newError("failed to get server spec").Base(err) + return nil, errors.New("failed to get server spec").Base(err) } serverList.AddServer(s) } if serverList.Size() == 0 { - return nil, newError("0 target server") + return nil, errors.New("0 target server") } v := core.MustFromContext(ctx) @@ -58,9 +59,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { // Process implements proxy.Outbound.Process. func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified.") + return errors.New("target not specified.") } ob.Name = "socks" ob.CanSpliceCopy = 2 @@ -85,12 +86,12 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter return nil }); err != nil { - return newError("failed to find an available destination").Base(err) + return errors.New("failed to find an available destination").Base(err) } defer func() { if err := conn.Close(); err != nil { - newError("failed to closed connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to closed connection") } }() @@ -121,9 +122,9 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter request.Version = socks4Version if destination.Network == net.Network_UDP { - return newError("udp is not supported in socks4") + return errors.New("udp is not supported in socks4") } else if destination.Address.Family().IsIPv6() { - return newError("ipv6 is not supported in socks4") + return errors.New("ipv6 is not supported in socks4") } } @@ -138,11 +139,11 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter } if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil { - newError("failed to set deadline for handshake").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to set deadline for handshake") } udpRequest, err := ClientHandshake(request, conn, conn) if err != nil { - return newError("failed to establish connection to server").AtWarning().Base(err) + return errors.New("failed to establish connection to server").AtWarning().Base(err) } if udpRequest != nil { if udpRequest.Address == net.AnyIP || udpRequest.Address == net.AnyIPv6 { @@ -151,7 +152,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter } if err := conn.SetDeadline(time.Time{}); err != nil { - newError("failed to clear deadline after handshake").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to clear deadline after handshake") } var newCtx context.Context @@ -182,7 +183,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter } else if request.Command == protocol.RequestCommandUDP { udpConn, err := dialer.Dial(ctx, udpRequest.Destination()) if err != nil { - return newError("failed to create UDP connection").Base(err) + return errors.New("failed to create UDP connection").Base(err) } defer udpConn.Close() requestFunc = func() error { @@ -203,7 +204,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter responseDonePost := task.OnSuccess(responseFunc, task.Close(link.Writer)) if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil diff --git a/proxy/socks/errors.generated.go b/proxy/socks/errors.generated.go deleted file mode 100644 index f466011d..00000000 --- a/proxy/socks/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package socks - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/socks/protocol.go b/proxy/socks/protocol.go index 3f371d57..fe13f24f 100644 --- a/proxy/socks/protocol.go +++ b/proxy/socks/protocol.go @@ -6,6 +6,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol" ) @@ -48,7 +49,7 @@ type ServerSession struct { func (s *ServerSession) handshake4(cmd byte, reader io.Reader, writer io.Writer) (*protocol.RequestHeader, error) { if s.config.AuthType == AuthType_PASSWORD { writeSocks4Response(writer, socks4RequestRejected, net.AnyIP, net.Port(0)) - return nil, newError("socks 4 is not allowed when auth is required.") + return nil, errors.New("socks 4 is not allowed when auth is required.") } var port net.Port @@ -58,7 +59,7 @@ func (s *ServerSession) handshake4(cmd byte, reader io.Reader, writer io.Writer) buffer := buf.StackNew() if _, err := buffer.ReadFullFrom(reader, 6); err != nil { buffer.Release() - return nil, newError("insufficient header").Base(err) + return nil, errors.New("insufficient header").Base(err) } port = net.PortFromBytes(buffer.BytesRange(0, 2)) address = net.IPAddress(buffer.BytesRange(2, 6)) @@ -71,7 +72,7 @@ func (s *ServerSession) handshake4(cmd byte, reader io.Reader, writer io.Writer) if address.IP()[0] == 0x00 { domain, err := ReadUntilNull(reader) if err != nil { - return nil, newError("failed to read domain for socks 4a").Base(err) + return nil, errors.New("failed to read domain for socks 4a").Base(err) } address = net.DomainAddress(domain) } @@ -90,7 +91,7 @@ func (s *ServerSession) handshake4(cmd byte, reader io.Reader, writer io.Writer) return request, nil default: writeSocks4Response(writer, socks4RequestRejected, net.AnyIP, net.Port(0)) - return nil, newError("unsupported command: ", cmd) + return nil, errors.New("unsupported command: ", cmd) } } @@ -99,7 +100,7 @@ func (s *ServerSession) auth5(nMethod byte, reader io.Reader, writer io.Writer) defer buffer.Release() if _, err = buffer.ReadFullFrom(reader, int32(nMethod)); err != nil { - return "", newError("failed to read auth methods").Base(err) + return "", errors.New("failed to read auth methods").Base(err) } var expectedAuth byte = authNotRequired @@ -109,26 +110,26 @@ func (s *ServerSession) auth5(nMethod byte, reader io.Reader, writer io.Writer) if !hasAuthMethod(expectedAuth, buffer.BytesRange(0, int32(nMethod))) { writeSocks5AuthenticationResponse(writer, socks5Version, authNoMatchingMethod) - return "", newError("no matching auth method") + return "", errors.New("no matching auth method") } if err := writeSocks5AuthenticationResponse(writer, socks5Version, expectedAuth); err != nil { - return "", newError("failed to write auth response").Base(err) + return "", errors.New("failed to write auth response").Base(err) } if expectedAuth == authPassword { username, password, err := ReadUsernamePassword(reader) if err != nil { - return "", newError("failed to read username and password for authentication").Base(err) + return "", errors.New("failed to read username and password for authentication").Base(err) } if !s.config.HasAccount(username, password) { writeSocks5AuthenticationResponse(writer, 0x01, 0xFF) - return "", newError("invalid username or password") + return "", errors.New("invalid username or password") } if err := writeSocks5AuthenticationResponse(writer, 0x01, 0x00); err != nil { - return "", newError("failed to write auth response").Base(err) + return "", errors.New("failed to write auth response").Base(err) } return username, nil } @@ -150,7 +151,7 @@ func (s *ServerSession) handshake5(nMethod byte, reader io.Reader, writer io.Wri buffer := buf.StackNew() if _, err := buffer.ReadFullFrom(reader, 3); err != nil { buffer.Release() - return nil, newError("failed to read request").Base(err) + return nil, errors.New("failed to read request").Base(err) } cmd = buffer.Byte(1) buffer.Release() @@ -167,22 +168,22 @@ func (s *ServerSession) handshake5(nMethod byte, reader io.Reader, writer io.Wri case cmdUDPAssociate: if !s.config.UdpEnabled { writeSocks5Response(writer, statusCmdNotSupport, net.AnyIP, net.Port(0)) - return nil, newError("UDP is not enabled.") + return nil, errors.New("UDP is not enabled.") } request.Command = protocol.RequestCommandUDP case cmdTCPBind: writeSocks5Response(writer, statusCmdNotSupport, net.AnyIP, net.Port(0)) - return nil, newError("TCP bind is not supported.") + return nil, errors.New("TCP bind is not supported.") default: writeSocks5Response(writer, statusCmdNotSupport, net.AnyIP, net.Port(0)) - return nil, newError("unknown command ", cmd) + return nil, errors.New("unknown command ", cmd) } request.Version = socks5Version addr, port, err := addrParser.ReadAddressPort(nil, reader) if err != nil { - return nil, newError("failed to read address").Base(err) + return nil, errors.New("failed to read address").Base(err) } request.Address = addr request.Port = port @@ -211,7 +212,7 @@ func (s *ServerSession) Handshake(reader io.Reader, writer io.Writer) (*protocol buffer := buf.StackNew() if _, err := buffer.ReadFullFrom(reader, 2); err != nil { buffer.Release() - return nil, newError("insufficient header").Base(err) + return nil, errors.New("insufficient header").Base(err) } version := buffer.Byte(0) @@ -224,7 +225,7 @@ func (s *ServerSession) Handshake(reader io.Reader, writer io.Writer) (*protocol case socks5Version: return s.handshake5(cmd, reader, writer) default: - return nil, newError("unknown Socks version: ", version) + return nil, errors.New("unknown Socks version: ", version) } } @@ -278,7 +279,7 @@ func ReadUntilNull(reader io.Reader) (string, error) { return b.String(), nil } if b.IsFull() { - return "", newError("buffer overrun") + return "", errors.New("buffer overrun") } } } @@ -322,7 +323,7 @@ func writeSocks4Response(writer io.Writer, errCode byte, address net.Address, po func DecodeUDPPacket(packet *buf.Buffer) (*protocol.RequestHeader, error) { if packet.Len() < 5 { - return nil, newError("insufficient length of packet.") + return nil, errors.New("insufficient length of packet.") } request := &protocol.RequestHeader{ Version: socks5Version, @@ -331,14 +332,14 @@ func DecodeUDPPacket(packet *buf.Buffer) (*protocol.RequestHeader, error) { // packet[0] and packet[1] are reserved if packet.Byte(2) != 0 /* fragments */ { - return nil, newError("discarding fragmented payload.") + return nil, errors.New("discarding fragmented payload.") } packet.Advance(3) addr, port, err := addrParser.ReadAddressPort(nil, packet) if err != nil { - return nil, newError("failed to read UDP header").Base(err) + return nil, errors.New("failed to read UDP header").Base(err) } request.Address = addr request.Port = port @@ -432,10 +433,10 @@ func ClientHandshake(request *protocol.RequestHeader, reader io.Reader, writer i } if b.Byte(0) != socks5Version { - return nil, newError("unexpected server version: ", b.Byte(0)).AtWarning() + return nil, errors.New("unexpected server version: ", b.Byte(0)).AtWarning() } if b.Byte(1) != authByte { - return nil, newError("auth method not supported.").AtWarning() + return nil, errors.New("auth method not supported.").AtWarning() } if authByte == authPassword { @@ -455,7 +456,7 @@ func ClientHandshake(request *protocol.RequestHeader, reader io.Reader, writer i return nil, err } if b.Byte(1) != 0x00 { - return nil, newError("server rejects account: ", b.Byte(1)) + return nil, errors.New("server rejects account: ", b.Byte(1)) } } @@ -485,7 +486,7 @@ func ClientHandshake(request *protocol.RequestHeader, reader io.Reader, writer i resp := b.Byte(1) if resp != 0x00 { - return nil, newError("server rejects request: ", resp) + return nil, errors.New("server rejects request: ", resp) } b.Clear() diff --git a/proxy/socks/server.go b/proxy/socks/server.go index 18084864..19c6c906 100644 --- a/proxy/socks/server.go +++ b/proxy/socks/server.go @@ -7,6 +7,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol" @@ -80,19 +81,19 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con case net.Network_UDP: return s.handleUDPPayload(ctx, conn, dispatcher) default: - return newError("unknown network: ", network) + return errors.New("unknown network: ", network) } } func (s *Server) processTCP(ctx context.Context, conn stat.Connection, dispatcher routing.Dispatcher) error { plcy := s.policy() if err := conn.SetReadDeadline(time.Now().Add(plcy.Timeouts.Handshake)); err != nil { - newError("failed to set deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to set deadline") } inbound := session.InboundFromContext(ctx) if inbound == nil || !inbound.Gateway.IsValid() { - return newError("inbound gateway not specified") + return errors.New("inbound gateway not specified") } svrSession := &ServerSession{ @@ -113,19 +114,19 @@ func (s *Server) processTCP(ctx context.Context, conn stat.Connection, dispatche Reason: err, }) } - return newError("failed to read request").Base(err) + return errors.New("failed to read request").Base(err) } if request.User != nil { inbound.User.Email = request.User.Email } if err := conn.SetReadDeadline(time.Time{}); err != nil { - newError("failed to clear deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to clear deadline") } if request.Command == protocol.RequestCommandTCP { dest := request.Destination() - newError("TCP Connect request to ", dest).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "TCP Connect request to ", dest) if inbound.Source.IsValid() { ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: inbound.Source, @@ -172,7 +173,7 @@ func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writ requestDone := func() error { defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly) if err := buf.Copy(buf.NewReader(reader), link.Writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport all TCP request").Base(err) + return errors.New("failed to transport all TCP request").Base(err) } return nil @@ -183,7 +184,7 @@ func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writ v2writer := buf.NewWriter(writer) if err := buf.Copy(link.Reader, v2writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport all TCP response").Base(err) + return errors.New("failed to transport all TCP response").Base(err) } return nil @@ -193,7 +194,7 @@ func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writ if err := task.Run(ctx, requestDonePost, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil @@ -201,12 +202,12 @@ func (s *Server) transport(ctx context.Context, reader io.Reader, writer io.Writ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dispatcher routing.Dispatcher) error { if s.udpFilter != nil && !s.udpFilter.Check(conn.RemoteAddr()) { - newError("Unauthorized UDP access from ", conn.RemoteAddr().String()).AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, "Unauthorized UDP access from ", conn.RemoteAddr().String()) return nil } udpServer := udp.NewDispatcher(dispatcher, func(ctx context.Context, packet *udp_proto.Packet) { payload := packet.Payload - newError("writing back UDP response with ", payload.Len(), " bytes").AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, "writing back UDP response with ", payload.Len(), " bytes") request := protocol.RequestHeaderFromContext(ctx) if request == nil { @@ -226,7 +227,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis defer udpMessage.Release() if err != nil { - newError("failed to write UDP response").AtWarning().Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, err, "failed to write UDP response") } conn.Write(udpMessage.Bytes()) @@ -234,7 +235,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis inbound := session.InboundFromContext(ctx) if inbound != nil && inbound.Source.IsValid() { - newError("client UDP connection from ", inbound.Source).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "client UDP connection from ", inbound.Source) } var dest *net.Destination @@ -249,7 +250,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis for _, payload := range mpayload { request, err := DecodeUDPPacket(payload) if err != nil { - newError("failed to parse UDP request").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to parse UDP request") payload.Release() continue } @@ -262,7 +263,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, conn stat.Connection, dis destination := request.Destination() currentPacketCtx := ctx - newError("send packet to ", destination, " with ", payload.Len(), " bytes").AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, "send packet to ", destination, " with ", payload.Len(), " bytes") if inbound != nil && inbound.Source.IsValid() { currentPacketCtx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ From: inbound.Source, diff --git a/proxy/trojan/client.go b/proxy/trojan/client.go index 3a4d838a..21b7d73e 100644 --- a/proxy/trojan/client.go +++ b/proxy/trojan/client.go @@ -32,12 +32,12 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { for _, rec := range config.Server { s, err := protocol.NewServerSpecFromPB(rec) if err != nil { - return nil, newError("failed to parse server spec").Base(err) + return nil, errors.New("failed to parse server spec").Base(err) } serverList.AddServer(s) } if serverList.Size() == 0 { - return nil, newError("0 server") + return nil, errors.New("0 server") } v := core.MustFromContext(ctx) @@ -51,9 +51,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) { // Process implements OutboundHandler.Process(). func (c *Client) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified") + return errors.New("target not specified") } ob.Name = "trojan" ob.CanSpliceCopy = 3 @@ -74,16 +74,16 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter return nil }) if err != nil { - return newError("failed to find an available destination").AtWarning().Base(err) + return errors.New("failed to find an available destination").AtWarning().Base(err) } - newError("tunneling request to ", destination, " via ", server.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunneling request to ", destination, " via ", server.Destination().NetAddr()) defer conn.Close() user := server.PickUser() account, ok := user.Account.(*MemoryAccount) if !ok { - return newError("user account is not valid") + return errors.New("user account is not valid") } var newCtx context.Context @@ -121,12 +121,12 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter // write some request payload to buffer if err = buf.CopyOnceTimeout(link.Reader, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { - return newError("failed to write A request payload").Base(err).AtWarning() + return errors.New("failed to write A request payload").Base(err).AtWarning() } // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer if err = bufferWriter.SetBuffered(false); err != nil { - return newError("failed to flush payload").Base(err).AtWarning() + return errors.New("failed to flush payload").Base(err).AtWarning() } // Send header if not sent yet @@ -135,7 +135,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter } if err = buf.Copy(link.Reader, bodyWriter, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transfer request payload").Base(err).AtInfo() + return errors.New("failed to transfer request payload").Base(err).AtInfo() } return nil @@ -161,7 +161,7 @@ func (c *Client) Process(ctx context.Context, link *transport.Link, dialer inter responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer)) if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil { - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil diff --git a/proxy/trojan/errors.generated.go b/proxy/trojan/errors.generated.go deleted file mode 100644 index 7fb81279..00000000 --- a/proxy/trojan/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package trojan - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/trojan/protocol.go b/proxy/trojan/protocol.go index 6fcfb4d4..96a16638 100644 --- a/proxy/trojan/protocol.go +++ b/proxy/trojan/protocol.go @@ -5,6 +5,7 @@ import ( "io" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol" ) @@ -38,7 +39,7 @@ type ConnWriter struct { func (c *ConnWriter) Write(p []byte) (n int, err error) { if !c.headerSent { if err := c.writeHeader(); err != nil { - return 0, newError("failed to write request header").Base(err) + return 0, errors.New("failed to write request header").Base(err) } } @@ -160,15 +161,15 @@ func (c *ConnReader) ParseHeader() error { var command [1]byte var hash [56]byte if _, err := io.ReadFull(c.Reader, hash[:]); err != nil { - return newError("failed to read user hash").Base(err) + return errors.New("failed to read user hash").Base(err) } if _, err := io.ReadFull(c.Reader, crlf[:]); err != nil { - return newError("failed to read crlf").Base(err) + return errors.New("failed to read crlf").Base(err) } if _, err := io.ReadFull(c.Reader, command[:]); err != nil { - return newError("failed to read command").Base(err) + return errors.New("failed to read command").Base(err) } network := net.Network_TCP @@ -178,12 +179,12 @@ func (c *ConnReader) ParseHeader() error { addr, port, err := addrParser.ReadAddressPort(nil, c.Reader) if err != nil { - return newError("failed to read address and port").Base(err) + return errors.New("failed to read address and port").Base(err) } c.Target = net.Destination{Network: network, Address: addr, Port: port} if _, err := io.ReadFull(c.Reader, crlf[:]); err != nil { - return newError("failed to read crlf").Base(err) + return errors.New("failed to read crlf").Base(err) } c.headerParsed = true @@ -217,22 +218,22 @@ type PacketReader struct { func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { addr, port, err := addrParser.ReadAddressPort(nil, r) if err != nil { - return nil, newError("failed to read address and port").Base(err) + return nil, errors.New("failed to read address and port").Base(err) } var lengthBuf [2]byte if _, err := io.ReadFull(r, lengthBuf[:]); err != nil { - return nil, newError("failed to read payload length").Base(err) + return nil, errors.New("failed to read payload length").Base(err) } remain := int(binary.BigEndian.Uint16(lengthBuf[:])) if remain > maxLength { - return nil, newError("oversize payload") + return nil, errors.New("oversize payload") } var crlf [2]byte if _, err := io.ReadFull(r, crlf[:]); err != nil { - return nil, newError("failed to read crlf").Base(err) + return nil, errors.New("failed to read crlf").Base(err) } dest := net.UDPDestination(addr, port) @@ -249,7 +250,7 @@ func (r *PacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { n, err := b.ReadFullFrom(r, int32(length)) if err != nil { buf.ReleaseMulti(mb) - return nil, newError("failed to read payload").Base(err) + return nil, errors.New("failed to read payload").Base(err) } remain -= int(n) diff --git a/proxy/trojan/server.go b/proxy/trojan/server.go index bc52c2b1..6110eec0 100644 --- a/proxy/trojan/server.go +++ b/proxy/trojan/server.go @@ -47,11 +47,11 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) { for _, user := range config.Users { u, err := user.ToMemoryUser() if err != nil { - return nil, newError("failed to get trojan user").Base(err).AtError() + return nil, errors.New("failed to get trojan user").Base(err).AtError() } if err := validator.Add(u); err != nil { - return nil, newError("failed to add user").Base(err).AtError() + return nil, errors.New("failed to add user").Base(err).AtError() } } @@ -132,8 +132,6 @@ func (s *Server) Network() []net.Network { // Process implements proxy.Inbound.Process(). func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher) error { - sid := session.ExportIDToError(ctx) - iConn := conn statConn, ok := iConn.(*stat.CounterConnection) if ok { @@ -142,16 +140,16 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con sessionPolicy := s.policyManager.ForLevel(0) if err := conn.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil { - return newError("unable to set read deadline").Base(err).AtWarning() + return errors.New("unable to set read deadline").Base(err).AtWarning() } first := buf.FromBytes(make([]byte, buf.Size)) first.Clear() firstLen, err := first.ReadFrom(conn) if err != nil { - return newError("failed to read first request").Base(err) + return errors.New("failed to read first request").Base(err) } - newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid) + errors.LogInfo(ctx, "firstLen = ", firstLen) bufferedReader := &buf.BufferedReader{ Reader: buf.NewReader(conn), @@ -166,7 +164,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con shouldFallback := false if firstLen < 58 || first.Byte(56) != '\r' { // invalid protocol - err = newError("not trojan protocol") + err = errors.New("not trojan protocol") log.Record(&log.AccessMessage{ From: conn.RemoteAddr(), To: "", @@ -179,7 +177,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con user = s.validator.Get(hexString(first.BytesTo(56))) if user == nil { // invalid user, let's fallback - err = newError("not a valid user") + err = errors.New("not a valid user") log.Record(&log.AccessMessage{ From: conn.RemoteAddr(), To: "", @@ -192,9 +190,9 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con } if isfb && shouldFallback { - return s.fallback(ctx, sid, err, sessionPolicy, conn, iConn, napfb, first, firstLen, bufferedReader) + return s.fallback(ctx, err, sessionPolicy, conn, iConn, napfb, first, firstLen, bufferedReader) } else if shouldFallback { - return newError("invalid protocol or invalid user") + return errors.New("invalid protocol or invalid user") } clientReader := &ConnReader{Reader: bufferedReader} @@ -205,12 +203,12 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con Status: log.AccessRejected, Reason: err, }) - return newError("failed to create request from: ", conn.RemoteAddr()).Base(err) + return errors.New("failed to create request from: ", conn.RemoteAddr()).Base(err) } destination := clientReader.Target if err := conn.SetReadDeadline(time.Time{}); err != nil { - return newError("unable to set read deadline").Base(err).AtWarning() + return errors.New("unable to set read deadline").Base(err).AtWarning() } inbound := session.InboundFromContext(ctx) @@ -231,7 +229,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con Email: user.Email, }) - newError("received request for ", destination).WriteToLog(sid) + errors.LogInfo(ctx, "received request for ", destination) return s.handleConnection(ctx, sessionPolicy, destination, clientReader, buf.NewWriter(conn), dispatcher) } @@ -243,7 +241,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, clientReader *PacketReade } if err := clientWriter.WriteMultiBuffer(buf.MultiBuffer{udpPayload}); err != nil { - newError("failed to write response").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, err, "failed to write response") } }) @@ -260,7 +258,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, clientReader *PacketReade mb, err := clientReader.ReadMultiBuffer() if err != nil { if errors.Cause(err) != io.EOF { - return newError("unexpected EOF").Base(err) + return errors.New("unexpected EOF").Base(err) } return nil } @@ -281,7 +279,7 @@ func (s *Server) handleUDPPayload(ctx context.Context, clientReader *PacketReade Email: user.Email, }) } - newError("tunnelling request to ", destination).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunnelling request to ", destination) if !s.cone || dest == nil { dest = &destination @@ -306,13 +304,13 @@ func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Sess link, err := dispatcher.Dispatch(ctx, destination) if err != nil { - return newError("failed to dispatch request to ", destination).Base(err) + return errors.New("failed to dispatch request to ", destination).Base(err) } requestDone := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly) if buf.Copy(clientReader, link.Writer, buf.UpdateActivity(timer)) != nil { - return newError("failed to transfer request").Base(err) + return errors.New("failed to transfer request").Base(err) } return nil } @@ -321,7 +319,7 @@ func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Sess defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) if err := buf.Copy(link.Reader, clientWriter, buf.UpdateActivity(timer)); err != nil { - return newError("failed to write response").Base(err) + return errors.New("failed to write response").Base(err) } return nil } @@ -330,17 +328,17 @@ func (s *Server) handleConnection(ctx context.Context, sessionPolicy policy.Sess if err := task.Run(ctx, requestDonePost, responseDone); err != nil { common.Must(common.Interrupt(link.Reader)) common.Must(common.Interrupt(link.Writer)) - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil } -func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err error, sessionPolicy policy.Session, connection stat.Connection, iConn stat.Connection, napfb map[string]map[string]map[string]*Fallback, first *buf.Buffer, firstLen int64, reader buf.Reader) error { +func (s *Server) fallback(ctx context.Context, err error, sessionPolicy policy.Session, connection stat.Connection, iConn stat.Connection, napfb map[string]map[string]map[string]*Fallback, first *buf.Buffer, firstLen int64, reader buf.Reader) error { if err := connection.SetReadDeadline(time.Time{}); err != nil { - newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid) + errors.LogWarningInner(ctx, err, "unable to set back read deadline") } - newError("fallback starts").Base(err).AtInfo().WriteToLog(sid) + errors.LogInfoInner(ctx, err, "fallback starts") name := "" alpn := "" @@ -348,14 +346,14 @@ func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err erro cs := tlsConn.ConnectionState() name = cs.ServerName alpn = cs.NegotiatedProtocol - newError("realName = " + name).AtInfo().WriteToLog(sid) - newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid) + errors.LogInfo(ctx, "realName = " + name) + errors.LogInfo(ctx, "realAlpn = " + alpn) } else if realityConn, ok := iConn.(*reality.Conn); ok { cs := realityConn.ConnectionState() name = cs.ServerName alpn = cs.NegotiatedProtocol - newError("realName = " + name).AtInfo().WriteToLog(sid) - newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid) + errors.LogInfo(ctx, "realName = " + name) + errors.LogInfo(ctx, "realAlpn = " + alpn) } name = strings.ToLower(name) alpn = strings.ToLower(alpn) @@ -377,7 +375,7 @@ func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err erro } apfb := napfb[name] if apfb == nil { - return newError(`failed to find the default "name" config`).AtWarning() + return errors.New(`failed to find the default "name" config`).AtWarning() } if apfb[alpn] == nil { @@ -385,7 +383,7 @@ func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err erro } pfb := apfb[alpn] if pfb == nil { - return newError(`failed to find the default "alpn" config`).AtWarning() + return errors.New(`failed to find the default "alpn" config`).AtWarning() } path := "" @@ -405,7 +403,7 @@ func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err erro } if k == '?' || k == ' ' { path = string(firstBytes[i:j]) - newError("realPath = " + path).AtInfo().WriteToLog(sid) + errors.LogInfo(ctx, "realPath = " + path) if pfb[path] == nil { path = "" } @@ -419,7 +417,7 @@ func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err erro } fb := pfb[path] if fb == nil { - return newError(`failed to find the default "path" config`).AtWarning() + return errors.New(`failed to find the default "path" config`).AtWarning() } ctx, cancel := context.WithCancel(ctx) @@ -435,7 +433,7 @@ func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err erro } return nil }); err != nil { - return newError("failed to dial to " + fb.Dest).Base(err).AtWarning() + return errors.New("failed to dial to " + fb.Dest).Base(err).AtWarning() } defer conn.Close() @@ -495,11 +493,11 @@ func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err erro common.Must2(pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)})) } if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil { - return newError("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning() + return errors.New("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning() } } if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil { - return newError("failed to fallback request payload").Base(err).AtInfo() + return errors.New("failed to fallback request payload").Base(err).AtInfo() } return nil } @@ -509,7 +507,7 @@ func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err erro getResponse := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to deliver response payload").Base(err).AtInfo() + return errors.New("failed to deliver response payload").Base(err).AtInfo() } return nil } @@ -517,7 +515,7 @@ func (s *Server) fallback(ctx context.Context, sid errors.ExportOption, err erro if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil { common.Must(common.Interrupt(serverReader)) common.Must(common.Interrupt(serverWriter)) - return newError("fallback ends").Base(err).AtInfo() + return errors.New("fallback ends").Base(err).AtInfo() } return nil diff --git a/proxy/trojan/validator.go b/proxy/trojan/validator.go index 26167e4b..4ffe41a1 100644 --- a/proxy/trojan/validator.go +++ b/proxy/trojan/validator.go @@ -4,6 +4,7 @@ import ( "strings" "sync" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" ) @@ -19,7 +20,7 @@ func (v *Validator) Add(u *protocol.MemoryUser) error { if u.Email != "" { _, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u) if loaded { - return newError("User ", u.Email, " already exists.") + return errors.New("User ", u.Email, " already exists.") } } v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u) @@ -29,12 +30,12 @@ func (v *Validator) Add(u *protocol.MemoryUser) error { // Del a trojan user with a non-empty Email. func (v *Validator) Del(e string) error { if e == "" { - return newError("Email must not be empty.") + return errors.New("Email must not be empty.") } le := strings.ToLower(e) u, _ := v.email.Load(le) if u == nil { - return newError("User ", e, " not found.") + return errors.New("User ", e, " not found.") } v.email.Delete(le) v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key)) diff --git a/proxy/vless/account.go b/proxy/vless/account.go index b20a9539..5349a3bd 100644 --- a/proxy/vless/account.go +++ b/proxy/vless/account.go @@ -1,6 +1,7 @@ package vless import ( + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/uuid" ) @@ -9,7 +10,7 @@ import ( func (a *Account) AsAccount() (protocol.Account, error) { id, err := uuid.ParseString(a.Id) if err != nil { - return nil, newError("failed to parse ID").Base(err).AtError() + return nil, errors.New("failed to parse ID").Base(err).AtError() } return &MemoryAccount{ ID: protocol.NewID(id), diff --git a/proxy/vless/encoding/addons.go b/proxy/vless/encoding/addons.go index 9426f6a0..1bf1817d 100644 --- a/proxy/vless/encoding/addons.go +++ b/proxy/vless/encoding/addons.go @@ -5,6 +5,7 @@ import ( "io" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/proxy" "github.com/xtls/xray-core/proxy/vless" @@ -16,17 +17,17 @@ func EncodeHeaderAddons(buffer *buf.Buffer, addons *Addons) error { case vless.XRV: bytes, err := proto.Marshal(addons) if err != nil { - return newError("failed to marshal addons protobuf value").Base(err) + return errors.New("failed to marshal addons protobuf value").Base(err) } if err := buffer.WriteByte(byte(len(bytes))); err != nil { - return newError("failed to write addons protobuf length").Base(err) + return errors.New("failed to write addons protobuf length").Base(err) } if _, err := buffer.Write(bytes); err != nil { - return newError("failed to write addons protobuf value").Base(err) + return errors.New("failed to write addons protobuf value").Base(err) } default: if err := buffer.WriteByte(0); err != nil { - return newError("failed to write addons protobuf length").Base(err) + return errors.New("failed to write addons protobuf length").Base(err) } } @@ -37,17 +38,17 @@ func DecodeHeaderAddons(buffer *buf.Buffer, reader io.Reader) (*Addons, error) { addons := new(Addons) buffer.Clear() if _, err := buffer.ReadFullFrom(reader, 1); err != nil { - return nil, newError("failed to read addons protobuf length").Base(err) + return nil, errors.New("failed to read addons protobuf length").Base(err) } if length := int32(buffer.Byte(0)); length != 0 { buffer.Clear() if _, err := buffer.ReadFullFrom(reader, length); err != nil { - return nil, newError("failed to read addons protobuf value").Base(err) + return nil, errors.New("failed to read addons protobuf value").Base(err) } if err := proto.Unmarshal(buffer.Bytes(), addons); err != nil { - return nil, newError("failed to unmarshal addons protobuf value").Base(err) + return nil, errors.New("failed to unmarshal addons protobuf value").Base(err) } // Verification. @@ -149,7 +150,7 @@ func (w *LengthPacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error { mb[i] = nil } if _, err := w.Write(w.cache); err != nil { - return newError("failed to write a packet").Base(err) + return errors.New("failed to write a packet").Base(err) } return nil } @@ -168,7 +169,7 @@ type LengthPacketReader struct { func (r *LengthPacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { if _, err := io.ReadFull(r.Reader, r.cache); err != nil { // maybe EOF - return nil, newError("failed to read packet length").Base(err) + return nil, errors.New("failed to read packet length").Base(err) } length := int32(r.cache[0])<<8 | int32(r.cache[1]) // fmt.Println("Read", length) @@ -181,7 +182,7 @@ func (r *LengthPacketReader) ReadMultiBuffer() (buf.MultiBuffer, error) { length -= size b := buf.New() if _, err := b.ReadFullFrom(r.Reader, size); err != nil { - return nil, newError("failed to read packet payload").Base(err) + return nil, errors.New("failed to read packet payload").Base(err) } mb = append(mb, b) } diff --git a/proxy/vless/encoding/encoding.go b/proxy/vless/encoding/encoding.go index 5954746e..038c0ed3 100644 --- a/proxy/vless/encoding/encoding.go +++ b/proxy/vless/encoding/encoding.go @@ -35,29 +35,29 @@ func EncodeRequestHeader(writer io.Writer, request *protocol.RequestHeader, requ defer buffer.Release() if err := buffer.WriteByte(request.Version); err != nil { - return newError("failed to write request version").Base(err) + return errors.New("failed to write request version").Base(err) } if _, err := buffer.Write(request.User.Account.(*vless.MemoryAccount).ID.Bytes()); err != nil { - return newError("failed to write request user id").Base(err) + return errors.New("failed to write request user id").Base(err) } if err := EncodeHeaderAddons(&buffer, requestAddons); err != nil { - return newError("failed to encode request header addons").Base(err) + return errors.New("failed to encode request header addons").Base(err) } if err := buffer.WriteByte(byte(request.Command)); err != nil { - return newError("failed to write request command").Base(err) + return errors.New("failed to write request command").Base(err) } if request.Command != protocol.RequestCommandMux { if err := addrParser.WriteAddressPort(&buffer, request.Address, request.Port); err != nil { - return newError("failed to write request address and port").Base(err) + return errors.New("failed to write request address and port").Base(err) } } if _, err := writer.Write(buffer.Bytes()); err != nil { - return newError("failed to write request header").Base(err) + return errors.New("failed to write request header").Base(err) } return nil @@ -74,7 +74,7 @@ func DecodeRequestHeader(isfb bool, first *buf.Buffer, reader io.Reader, validat request.Version = first.Byte(0) } else { if _, err := buffer.ReadFullFrom(reader, 1); err != nil { - return nil, nil, false, newError("failed to read request version").Base(err) + return nil, nil, false, errors.New("failed to read request version").Base(err) } request.Version = buffer.Byte(0) } @@ -89,13 +89,13 @@ func DecodeRequestHeader(isfb bool, first *buf.Buffer, reader io.Reader, validat } else { buffer.Clear() if _, err := buffer.ReadFullFrom(reader, 16); err != nil { - return nil, nil, false, newError("failed to read request user id").Base(err) + return nil, nil, false, errors.New("failed to read request user id").Base(err) } copy(id[:], buffer.Bytes()) } if request.User = validator.Get(id); request.User == nil { - return nil, nil, isfb, newError("invalid request user id") + return nil, nil, isfb, errors.New("invalid request user id") } if isfb { @@ -104,12 +104,12 @@ func DecodeRequestHeader(isfb bool, first *buf.Buffer, reader io.Reader, validat requestAddons, err := DecodeHeaderAddons(&buffer, reader) if err != nil { - return nil, nil, false, newError("failed to decode request header addons").Base(err) + return nil, nil, false, errors.New("failed to decode request header addons").Base(err) } buffer.Clear() if _, err := buffer.ReadFullFrom(reader, 1); err != nil { - return nil, nil, false, newError("failed to read request command").Base(err) + return nil, nil, false, errors.New("failed to read request command").Base(err) } request.Command = protocol.RequestCommand(buffer.Byte(0)) @@ -124,11 +124,11 @@ func DecodeRequestHeader(isfb bool, first *buf.Buffer, reader io.Reader, validat } } if request.Address == nil { - return nil, nil, false, newError("invalid request address") + return nil, nil, false, errors.New("invalid request address") } return request, requestAddons, false, nil default: - return nil, nil, isfb, newError("invalid request version") + return nil, nil, isfb, errors.New("invalid request version") } } @@ -138,15 +138,15 @@ func EncodeResponseHeader(writer io.Writer, request *protocol.RequestHeader, res defer buffer.Release() if err := buffer.WriteByte(request.Version); err != nil { - return newError("failed to write response version").Base(err) + return errors.New("failed to write response version").Base(err) } if err := EncodeHeaderAddons(&buffer, responseAddons); err != nil { - return newError("failed to encode response header addons").Base(err) + return errors.New("failed to encode response header addons").Base(err) } if _, err := writer.Write(buffer.Bytes()); err != nil { - return newError("failed to write response header").Base(err) + return errors.New("failed to write response header").Base(err) } return nil @@ -158,16 +158,16 @@ func DecodeResponseHeader(reader io.Reader, request *protocol.RequestHeader) (*A defer buffer.Release() if _, err := buffer.ReadFullFrom(reader, 1); err != nil { - return nil, newError("failed to read response version").Base(err) + return nil, errors.New("failed to read response version").Base(err) } if buffer.Byte(0) != request.Version { - return nil, newError("unexpected response version. Expecting ", int(request.Version), " but actually ", int(buffer.Byte(0))) + return nil, errors.New("unexpected response version. Expecting ", int(request.Version), " but actually ", int(buffer.Byte(0))) } responseAddons, err := DecodeHeaderAddons(&buffer, reader) if err != nil { - return nil, newError("failed to decode response header addons").Base(err) + return nil, errors.New("failed to decode response header addons").Base(err) } return responseAddons, nil diff --git a/proxy/vless/encoding/errors.generated.go b/proxy/vless/encoding/errors.generated.go deleted file mode 100644 index 267711d9..00000000 --- a/proxy/vless/encoding/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package encoding - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/vless/errors.generated.go b/proxy/vless/errors.generated.go deleted file mode 100644 index 9487ff0e..00000000 --- a/proxy/vless/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package vless - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/vless/inbound/errors.generated.go b/proxy/vless/inbound/errors.generated.go deleted file mode 100644 index c2d7295e..00000000 --- a/proxy/vless/inbound/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package inbound - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/vless/inbound/inbound.go b/proxy/vless/inbound/inbound.go index 1b31751c..891f725d 100644 --- a/proxy/vless/inbound/inbound.go +++ b/proxy/vless/inbound/inbound.go @@ -72,10 +72,10 @@ func New(ctx context.Context, config *Config, dc dns.Client) (*Handler, error) { for _, user := range config.Clients { u, err := user.ToMemoryUser() if err != nil { - return nil, newError("failed to get VLESS user").Base(err).AtError() + return nil, errors.New("failed to get VLESS user").Base(err).AtError() } if err := handler.AddUser(ctx, u); err != nil { - return nil, newError("failed to initiate user").Base(err).AtError() + return nil, errors.New("failed to initiate user").Base(err).AtError() } } @@ -93,7 +93,7 @@ func New(ctx context.Context, config *Config, dc dns.Client) (*Handler, error) { /* if fb.Path != "" { if r, err := regexp.Compile(fb.Path); err != nil { - return nil, newError("invalid path regexp").Base(err).AtError() + return nil, errors.New("invalid path regexp").Base(err).AtError() } else { handler.regexps[fb.Path] = r } @@ -177,8 +177,6 @@ func (*Handler) Network() []net.Network { // Process implements proxy.Inbound.Process(). func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error { - sid := session.ExportIDToError(ctx) - iConn := connection if statConn, ok := iConn.(*stat.CounterConnection); ok { iConn = statConn.Connection @@ -186,13 +184,13 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s sessionPolicy := h.policyManager.ForLevel(0) if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil { - return newError("unable to set read deadline").Base(err).AtWarning() + return errors.New("unable to set read deadline").Base(err).AtWarning() } first := buf.FromBytes(make([]byte, buf.Size)) first.Clear() firstLen, _ := first.ReadFrom(connection) - newError("firstLen = ", firstLen).AtInfo().WriteToLog(sid) + errors.LogInfo(ctx, "firstLen = ", firstLen) reader := &buf.BufferedReader{ Reader: buf.NewReader(connection), @@ -207,7 +205,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s isfb := napfb != nil if isfb && firstLen < 18 { - err = newError("fallback directly") + err = errors.New("fallback directly") } else { request, requestAddons, isfb, err = encoding.DecodeRequestHeader(isfb, first, reader, h.validator) } @@ -215,9 +213,9 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s if err != nil { if isfb { if err := connection.SetReadDeadline(time.Time{}); err != nil { - newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid) + errors.LogWarningInner(ctx, err, "unable to set back read deadline") } - newError("fallback starts").Base(err).AtInfo().WriteToLog(sid) + errors.LogInfoInner(ctx, err, "fallback starts") name := "" alpn := "" @@ -225,14 +223,14 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s cs := tlsConn.ConnectionState() name = cs.ServerName alpn = cs.NegotiatedProtocol - newError("realName = " + name).AtInfo().WriteToLog(sid) - newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid) + errors.LogInfo(ctx, "realName = " + name) + errors.LogInfo(ctx, "realAlpn = " + alpn) } else if realityConn, ok := iConn.(*reality.Conn); ok { cs := realityConn.ConnectionState() name = cs.ServerName alpn = cs.NegotiatedProtocol - newError("realName = " + name).AtInfo().WriteToLog(sid) - newError("realAlpn = " + alpn).AtInfo().WriteToLog(sid) + errors.LogInfo(ctx, "realName = " + name) + errors.LogInfo(ctx, "realAlpn = " + alpn) } name = strings.ToLower(name) alpn = strings.ToLower(alpn) @@ -254,7 +252,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s } apfb := napfb[name] if apfb == nil { - return newError(`failed to find the default "name" config`).AtWarning() + return errors.New(`failed to find the default "name" config`).AtWarning() } if apfb[alpn] == nil { @@ -262,7 +260,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s } pfb := apfb[alpn] if pfb == nil { - return newError(`failed to find the default "alpn" config`).AtWarning() + return errors.New(`failed to find the default "alpn" config`).AtWarning() } path := "" @@ -271,7 +269,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s if lines := bytes.Split(firstBytes, []byte{'\r', '\n'}); len(lines) > 1 { if s := bytes.Split(lines[0], []byte{' '}); len(s) == 3 { if len(s[0]) < 8 && len(s[1]) > 0 && len(s[2]) == 8 { - newError("realPath = " + string(s[1])).AtInfo().WriteToLog(sid) + errors.New("realPath = " + string(s[1])).AtInfo().WriteToLog(sid) for _, fb := range pfb { if fb.Path != "" && h.regexps[fb.Path].Match(s[1]) { path = fb.Path @@ -297,7 +295,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s } if k == '?' || k == ' ' { path = string(firstBytes[i:j]) - newError("realPath = " + path).AtInfo().WriteToLog(sid) + errors.LogInfo(ctx, "realPath = " + path) if pfb[path] == nil { path = "" } @@ -311,7 +309,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s } fb := pfb[path] if fb == nil { - return newError(`failed to find the default "path" config`).AtWarning() + return errors.New(`failed to find the default "path" config`).AtWarning() } ctx, cancel := context.WithCancel(ctx) @@ -327,7 +325,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s } return nil }); err != nil { - return newError("failed to dial to " + fb.Dest).Base(err).AtWarning() + return errors.New("failed to dial to " + fb.Dest).Base(err).AtWarning() } defer conn.Close() @@ -387,11 +385,11 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s pro.Write([]byte{byte(p1 >> 8), byte(p1), byte(p2 >> 8), byte(p2)}) } if err := serverWriter.WriteMultiBuffer(buf.MultiBuffer{pro}); err != nil { - return newError("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning() + return errors.New("failed to set PROXY protocol v", fb.Xver).Base(err).AtWarning() } } if err := buf.Copy(reader, serverWriter, buf.UpdateActivity(timer)); err != nil { - return newError("failed to fallback request payload").Base(err).AtInfo() + return errors.New("failed to fallback request payload").Base(err).AtInfo() } return nil } @@ -401,7 +399,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s getResponse := func() error { defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly) if err := buf.Copy(serverReader, writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to deliver response payload").Base(err).AtInfo() + return errors.New("failed to deliver response payload").Base(err).AtInfo() } return nil } @@ -409,7 +407,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), task.OnSuccess(getResponse, task.Close(writer))); err != nil { common.Interrupt(serverReader) common.Interrupt(serverWriter) - return newError("fallback ends").Base(err).AtInfo() + return errors.New("fallback ends").Base(err).AtInfo() } return nil } @@ -421,15 +419,15 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s Status: log.AccessRejected, Reason: err, }) - err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo() + err = errors.New("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo() } return err } if err := connection.SetReadDeadline(time.Time{}); err != nil { - newError("unable to set back read deadline").Base(err).AtWarning().WriteToLog(sid) + errors.LogWarningInner(ctx, err, "unable to set back read deadline") } - newError("received request for ", request.Destination()).AtInfo().WriteToLog(sid) + errors.LogInfo(ctx, "received request for ", request.Destination()) inbound := session.InboundFromContext(ctx) if inbound == nil { @@ -452,7 +450,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s inbound.CanSpliceCopy = 2 switch request.Command { case protocol.RequestCommandUDP: - return newError(requestAddons.Flow + " doesn't support UDP").AtWarning() + return errors.New(requestAddons.Flow + " doesn't support UDP").AtWarning() case protocol.RequestCommandMux: fallthrough // we will break Mux connections that contain TCP requests case protocol.RequestCommandTCP: @@ -460,7 +458,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s var p uintptr if tlsConn, ok := iConn.(*tls.Conn); ok { if tlsConn.ConnectionState().Version != gotls.VersionTLS13 { - return newError(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version).AtWarning() + return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version).AtWarning() } t = reflect.TypeOf(tlsConn.Conn).Elem() p = uintptr(unsafe.Pointer(tlsConn.Conn)) @@ -468,7 +466,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s t = reflect.TypeOf(realityConn.Conn).Elem() p = uintptr(unsafe.Pointer(realityConn.Conn)) } else { - return newError("XTLS only supports TLS and REALITY directly for now.").AtWarning() + return errors.New("XTLS only supports TLS and REALITY directly for now.").AtWarning() } i, _ := t.FieldByName("input") r, _ := t.FieldByName("rawInput") @@ -476,15 +474,15 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s rawInput = (*bytes.Buffer)(unsafe.Pointer(p + r.Offset)) } } else { - return newError(account.ID.String() + " is not able to use " + requestAddons.Flow).AtWarning() + return errors.New(account.ID.String() + " is not able to use " + requestAddons.Flow).AtWarning() } case "": inbound.CanSpliceCopy = 3 if account.Flow == vless.XRV && (request.Command == protocol.RequestCommandTCP || isMuxAndNotXUDP(request, first)) { - return newError(account.ID.String() + " is not able to use \"\". Note that the pure TLS proxy has certain TLS in TLS characters.").AtWarning() + return errors.New(account.ID.String() + " is not able to use \"\". Note that the pure TLS proxy has certain TLS in TLS characters.").AtWarning() } default: - return newError("unknown request flow " + requestAddons.Flow).AtWarning() + return errors.New("unknown request flow " + requestAddons.Flow).AtWarning() } if request.Command != protocol.RequestCommandMux { @@ -507,7 +505,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s link, err := dispatcher.Dispatch(ctx, request.Destination()) if err != nil { - return newError("failed to dispatch request to ", request.Destination()).Base(err).AtWarning() + return errors.New("failed to dispatch request to ", request.Destination()).Base(err).AtWarning() } serverReader := link.Reader // .(*pipe.Reader) @@ -531,7 +529,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s } if err != nil { - return newError("failed to transfer request payload").Base(err).AtInfo() + return errors.New("failed to transfer request payload").Base(err).AtInfo() } return nil @@ -542,7 +540,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s bufferWriter := buf.NewBufferedWriter(buf.NewWriter(connection)) if err := encoding.EncodeResponseHeader(bufferWriter, request, responseAddons); err != nil { - return newError("failed to encode response header").Base(err).AtWarning() + return errors.New("failed to encode response header").Base(err).AtWarning() } // default: clientWriter := bufferWriter @@ -556,7 +554,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s } // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer if err := bufferWriter.SetBuffered(false); err != nil { - return newError("failed to write A response payload").Base(err).AtWarning() + return errors.New("failed to write A response payload").Base(err).AtWarning() } var err error @@ -567,7 +565,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s err = buf.Copy(serverReader, clientWriter, buf.UpdateActivity(timer)) } if err != nil { - return newError("failed to transfer response payload").Base(err).AtInfo() + return errors.New("failed to transfer response payload").Base(err).AtInfo() } // Indicates the end of response payload. switch responseAddons.Flow { @@ -580,7 +578,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s if err := task.Run(ctx, task.OnSuccess(postRequest, task.Close(serverWriter)), getResponse); err != nil { common.Interrupt(serverReader) common.Interrupt(serverWriter) - return newError("connection ends").Base(err).AtInfo() + return errors.New("connection ends").Base(err).AtInfo() } return nil diff --git a/proxy/vless/outbound/errors.generated.go b/proxy/vless/outbound/errors.generated.go deleted file mode 100644 index 07966823..00000000 --- a/proxy/vless/outbound/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package outbound - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/vless/outbound/outbound.go b/proxy/vless/outbound/outbound.go index bf98253b..0c9e4721 100644 --- a/proxy/vless/outbound/outbound.go +++ b/proxy/vless/outbound/outbound.go @@ -13,6 +13,7 @@ import ( utls "github.com/refraction-networking/utls" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "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/retry" @@ -52,7 +53,7 @@ func New(ctx context.Context, config *Config) (*Handler, error) { for _, rec := range config.Vnext { s, err := protocol.NewServerSpecFromPB(rec) if err != nil { - return nil, newError("failed to parse server spec").Base(err).AtError() + return nil, errors.New("failed to parse server spec").Base(err).AtError() } serverList.AddServer(s) } @@ -71,9 +72,9 @@ func New(ctx context.Context, config *Config) (*Handler, error) { // Process implements proxy.Outbound.Process(). func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified").AtError() + return errors.New("target not specified").AtError() } ob.Name = "vless" @@ -88,7 +89,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } return nil }); err != nil { - return newError("failed to find an available destination").Base(err).AtWarning() + return errors.New("failed to find an available destination").Base(err).AtWarning() } defer conn.Close() @@ -97,7 +98,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte iConn = statConn.Connection } target := ob.Target - newError("tunneling request to ", target, " via ", rec.Destination().NetAddr()).AtInfo().WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunneling request to ", target, " via ", rec.Destination().NetAddr()) command := protocol.RequestCommandTCP if target.Network == net.Network_UDP { @@ -134,7 +135,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte switch request.Command { case protocol.RequestCommandUDP: if !allowUDP443 && request.Port == 443 { - return newError("XTLS rejected UDP/443 traffic").AtInfo() + return errors.New("XTLS rejected UDP/443 traffic").AtInfo() } case protocol.RequestCommandMux: fallthrough // let server break Mux connections that contain TCP requests @@ -151,7 +152,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte t = reflect.TypeOf(realityConn.Conn).Elem() p = uintptr(unsafe.Pointer(realityConn.Conn)) } else { - return newError("XTLS only supports TLS and REALITY directly for now.").AtWarning() + return errors.New("XTLS only supports TLS and REALITY directly for now.").AtWarning() } i, _ := t.FieldByName("input") r, _ := t.FieldByName("rawInput") @@ -191,7 +192,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte bufferWriter := buf.NewBufferedWriter(buf.NewWriter(conn)) if err := encoding.EncodeRequestHeader(bufferWriter, request, requestAddons); err != nil { - return newError("failed to encode request header").Base(err).AtWarning() + return errors.New("failed to encode request header").Base(err).AtWarning() } // default: serverWriter := bufferWriter @@ -210,28 +211,28 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte return err1 } else if requestAddons.Flow == vless.XRV { mb := make(buf.MultiBuffer, 1) - newError("Insert padding with empty content to camouflage VLESS header ", mb.Len()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "Insert padding with empty content to camouflage VLESS header ", mb.Len()) if err := serverWriter.WriteMultiBuffer(mb); err != nil { return err // ... } } } else { - newError("Reader is not timeout reader, will send out vless header separately from first payload").AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, "Reader is not timeout reader, will send out vless header separately from first payload") } // Flush; bufferWriter.WriteMultiBufer now is bufferWriter.writer.WriteMultiBuffer if err := bufferWriter.SetBuffered(false); err != nil { - return newError("failed to write A request payload").Base(err).AtWarning() + return errors.New("failed to write A request payload").Base(err).AtWarning() } var err error if requestAddons.Flow == vless.XRV { if tlsConn, ok := iConn.(*tls.Conn); ok { if tlsConn.ConnectionState().Version != gotls.VersionTLS13 { - return newError(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version).AtWarning() + return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, tlsConn.ConnectionState().Version).AtWarning() } } else if utlsConn, ok := iConn.(*tls.UConn); ok { if utlsConn.ConnectionState().Version != utls.VersionTLS13 { - return newError(`failed to use `+requestAddons.Flow+`, found outer tls version `, utlsConn.ConnectionState().Version).AtWarning() + return errors.New(`failed to use `+requestAddons.Flow+`, found outer tls version `, utlsConn.ConnectionState().Version).AtWarning() } } ctx1 := session.ContextWithInbound(ctx, nil) // TODO enable splice @@ -241,7 +242,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte err = buf.Copy(clientReader, serverWriter, buf.UpdateActivity(timer)) } if err != nil { - return newError("failed to transfer request payload").Base(err).AtInfo() + return errors.New("failed to transfer request payload").Base(err).AtInfo() } // Indicates the end of request payload. @@ -256,7 +257,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte responseAddons, err := encoding.DecodeResponseHeader(conn, request) if err != nil { - return newError("failed to decode response header").Base(err).AtInfo() + return errors.New("failed to decode response header").Base(err).AtInfo() } // default: serverReader := buf.NewReader(conn) @@ -280,7 +281,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } if err != nil { - return newError("failed to transfer response payload").Base(err).AtInfo() + return errors.New("failed to transfer response payload").Base(err).AtInfo() } return nil @@ -291,7 +292,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } if err := task.Run(ctx, postRequest, task.OnSuccess(getResponse, task.Close(clientWriter))); err != nil { - return newError("connection ends").Base(err).AtInfo() + return errors.New("connection ends").Base(err).AtInfo() } return nil diff --git a/proxy/vless/validator.go b/proxy/vless/validator.go index c294ecef..72038cab 100644 --- a/proxy/vless/validator.go +++ b/proxy/vless/validator.go @@ -4,6 +4,7 @@ import ( "strings" "sync" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/uuid" ) @@ -20,7 +21,7 @@ func (v *Validator) Add(u *protocol.MemoryUser) error { if u.Email != "" { _, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u) if loaded { - return newError("User ", u.Email, " already exists.") + return errors.New("User ", u.Email, " already exists.") } } v.users.Store(u.Account.(*MemoryAccount).ID.UUID(), u) @@ -30,12 +31,12 @@ func (v *Validator) Add(u *protocol.MemoryUser) error { // Del a VLESS user with a non-empty Email. func (v *Validator) Del(e string) error { if e == "" { - return newError("Email must not be empty.") + return errors.New("Email must not be empty.") } le := strings.ToLower(e) u, _ := v.email.Load(le) if u == nil { - return newError("User ", e, " not found.") + return errors.New("User ", e, " not found.") } v.email.Delete(le) v.users.Delete(u.(*protocol.MemoryUser).Account.(*MemoryAccount).ID.UUID()) diff --git a/proxy/vmess/account.go b/proxy/vmess/account.go index d0a776e6..5ece7a57 100644 --- a/proxy/vmess/account.go +++ b/proxy/vmess/account.go @@ -3,6 +3,7 @@ package vmess import ( "strings" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/common/uuid" ) @@ -31,7 +32,7 @@ func (a *MemoryAccount) Equals(account protocol.Account) bool { func (a *Account) AsAccount() (protocol.Account, error) { id, err := uuid.ParseString(a.Id) if err != nil { - return nil, newError("failed to parse ID").Base(err).AtError() + return nil, errors.New("failed to parse ID").Base(err).AtError() } protoID := protocol.NewID(id) var AuthenticatedLength, NoTerminationSignal bool diff --git a/proxy/vmess/encoding/client.go b/proxy/vmess/encoding/client.go index 0b7a0098..d678646b 100644 --- a/proxy/vmess/encoding/client.go +++ b/proxy/vmess/encoding/client.go @@ -17,6 +17,7 @@ import ( "github.com/xtls/xray-core/common/crypto" "github.com/xtls/xray-core/common/dice" "github.com/xtls/xray-core/common/drain" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/proxy/vmess" vmessaead "github.com/xtls/xray-core/proxy/vmess/aead" @@ -53,7 +54,7 @@ func NewClientSession(ctx context.Context, behaviorSeed int64) *ClientSession { var err error session.readDrainer, err = drain.NewBehaviorSeedLimitedDrainer(behaviorSeed, 18, 3266, 64) if err != nil { - newError("unable to initialize drainer").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "unable to initialize drainer") session.readDrainer = drain.NewNopDrainer() } } @@ -79,7 +80,7 @@ func (c *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writ if header.Command != protocol.RequestCommandMux { if err := addrParser.WriteAddressPort(buffer, header.Address, header.Port); err != nil { - return newError("failed to writer address and port").Base(err) + return errors.New("failed to writer address and port").Base(err) } } @@ -112,7 +113,7 @@ func (c *ClientSession) EncodeRequestBody(request *protocol.RequestHeader, write var ok bool padding, ok = sizeParser.(crypto.PaddingLengthGenerator) if !ok { - return nil, newError("invalid option: RequestOptionGlobalPadding") + return nil, errors.New("invalid option: RequestOptionGlobalPadding") } } @@ -173,7 +174,7 @@ func (c *ClientSession) EncodeRequestBody(request *protocol.RequestHeader, write } return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding), nil default: - return nil, newError("invalid option: Security") + return nil, errors.New("invalid option: Security") } } @@ -190,12 +191,12 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon if n, err := io.ReadFull(reader, aeadEncryptedResponseHeaderLength[:]); err != nil { c.readDrainer.AcknowledgeReceive(n) - return nil, drain.WithError(c.readDrainer, reader, newError("Unable to Read Header Len").Base(err)) + return nil, drain.WithError(c.readDrainer, reader, errors.New("Unable to Read Header Len").Base(err)) } else { // nolint: golint c.readDrainer.AcknowledgeReceive(n) } if decryptedResponseHeaderLengthBinaryBuffer, err := aeadResponseHeaderLengthEncryptionAEAD.Open(nil, aeadResponseHeaderLengthEncryptionIV, aeadEncryptedResponseHeaderLength[:], nil); err != nil { - return nil, drain.WithError(c.readDrainer, reader, newError("Failed To Decrypt Length").Base(err)) + return nil, drain.WithError(c.readDrainer, reader, errors.New("Failed To Decrypt Length").Base(err)) } else { // nolint: golint common.Must(binary.Read(bytes.NewReader(decryptedResponseHeaderLengthBinaryBuffer), binary.BigEndian, &decryptedResponseHeaderLengthBinaryDeserializeBuffer)) decryptedResponseHeaderLength = int(decryptedResponseHeaderLengthBinaryDeserializeBuffer) @@ -211,13 +212,13 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon if n, err := io.ReadFull(reader, encryptedResponseHeaderBuffer); err != nil { c.readDrainer.AcknowledgeReceive(n) - return nil, drain.WithError(c.readDrainer, reader, newError("Unable to Read Header Data").Base(err)) + return nil, drain.WithError(c.readDrainer, reader, errors.New("Unable to Read Header Data").Base(err)) } else { // nolint: golint c.readDrainer.AcknowledgeReceive(n) } if decryptedResponseHeaderBuffer, err := aeadResponseHeaderPayloadEncryptionAEAD.Open(nil, aeadResponseHeaderPayloadEncryptionIV, encryptedResponseHeaderBuffer, nil); err != nil { - return nil, drain.WithError(c.readDrainer, reader, newError("Failed To Decrypt Payload").Base(err)) + return nil, drain.WithError(c.readDrainer, reader, errors.New("Failed To Decrypt Payload").Base(err)) } else { // nolint: golint c.responseReader = bytes.NewReader(decryptedResponseHeaderBuffer) } @@ -226,11 +227,11 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon defer buffer.Release() if _, err := buffer.ReadFullFrom(c.responseReader, 4); err != nil { - return nil, newError("failed to read response header").Base(err).AtWarning() + return nil, errors.New("failed to read response header").Base(err).AtWarning() } if buffer.Byte(0) != c.responseHeader { - return nil, newError("unexpected response header. Expecting ", int(c.responseHeader), " but actually ", int(buffer.Byte(0))) + return nil, errors.New("unexpected response header. Expecting ", int(c.responseHeader), " but actually ", int(buffer.Byte(0))) } header := &protocol.ResponseHeader{ @@ -243,7 +244,7 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon buffer.Clear() if _, err := buffer.ReadFullFrom(c.responseReader, dataLen); err != nil { - return nil, newError("failed to read response command").Base(err) + return nil, errors.New("failed to read response command").Base(err) } command, err := UnmarshalCommand(cmdID, buffer.Bytes()) if err == nil { @@ -265,7 +266,7 @@ func (c *ClientSession) DecodeResponseBody(request *protocol.RequestHeader, read var ok bool padding, ok = sizeParser.(crypto.PaddingLengthGenerator) if !ok { - return nil, newError("invalid option: RequestOptionGlobalPadding") + return nil, errors.New("invalid option: RequestOptionGlobalPadding") } } @@ -328,7 +329,7 @@ func (c *ClientSession) DecodeResponseBody(request *protocol.RequestHeader, read } return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding), nil default: - return nil, newError("invalid option: Security") + return nil, errors.New("invalid option: Security") } } diff --git a/proxy/vmess/encoding/commands.go b/proxy/vmess/encoding/commands.go index 5a4d3708..cdab871b 100644 --- a/proxy/vmess/encoding/commands.go +++ b/proxy/vmess/encoding/commands.go @@ -6,6 +6,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "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" @@ -13,11 +14,11 @@ import ( ) var ( - ErrCommandTooLarge = newError("Command too large.") - ErrCommandTypeMismatch = newError("Command type mismatch.") - ErrInvalidAuth = newError("Invalid auth.") - ErrInsufficientLength = newError("Insufficient length.") - ErrUnknownCommand = newError("Unknown command.") + ErrCommandTooLarge = errors.New("Command too large.") + ErrCommandTypeMismatch = errors.New("Command type mismatch.") + ErrInvalidAuth = errors.New("Invalid auth.") + ErrInsufficientLength = errors.New("Insufficient length.") + ErrUnknownCommand = errors.New("Unknown command.") ) func MarshalCommand(command interface{}, writer io.Writer) error { diff --git a/proxy/vmess/encoding/errors.generated.go b/proxy/vmess/encoding/errors.generated.go deleted file mode 100644 index 267711d9..00000000 --- a/proxy/vmess/encoding/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package encoding - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/vmess/encoding/server.go b/proxy/vmess/encoding/server.go index 371bfdc0..99e7abc9 100644 --- a/proxy/vmess/encoding/server.go +++ b/proxy/vmess/encoding/server.go @@ -16,6 +16,7 @@ import ( "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/crypto" "github.com/xtls/xray-core/common/drain" + "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/task" @@ -75,7 +76,7 @@ func (h *SessionHistory) removeExpiredEntries() error { defer h.Unlock() if len(h.cache) == 0 { - return newError("nothing to do") + return errors.New("nothing to do") } for session, expire := range h.cache { @@ -130,7 +131,7 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader, isDrain bool) (*pr drainer, err := drain.NewBehaviorSeedLimitedDrainer(int64(s.userValidator.GetBehaviorSeed()), 16+38, 3266, 64) if err != nil { - return nil, newError("failed to initialize drainer").Base(err) + return nil, errors.New("failed to initialize drainer").Base(err) } drainConnection := func(e error) error { @@ -147,7 +148,7 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader, isDrain bool) (*pr }() if _, err := buffer.ReadFullFrom(reader, protocol.IDBytesLen); err != nil { - return nil, newError("failed to read request header").Base(err) + return nil, errors.New("failed to read request header").Base(err) } var decryptor io.Reader @@ -167,20 +168,20 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader, isDrain bool) (*pr if errorReason != nil { if shouldDrain { drainer.AcknowledgeReceive(bytesRead) - return nil, drainConnection(newError("AEAD read failed").Base(errorReason)) + return nil, drainConnection(errors.New("AEAD read failed").Base(errorReason)) } else { - return nil, drainConnection(newError("AEAD read failed, drain skipped").Base(errorReason)) + return nil, drainConnection(errors.New("AEAD read failed, drain skipped").Base(errorReason)) } } decryptor = bytes.NewReader(aeadData) default: - return nil, drainConnection(newError("invalid user").Base(errorAEAD)) + return nil, drainConnection(errors.New("invalid user").Base(errorAEAD)) } drainer.AcknowledgeReceive(int(buffer.Len())) buffer.Clear() if _, err := buffer.ReadFullFrom(decryptor, 38); err != nil { - return nil, newError("failed to read request header").Base(err) + return nil, errors.New("failed to read request header").Base(err) } request := &protocol.RequestHeader{ @@ -195,7 +196,7 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader, isDrain bool) (*pr sid.key = s.requestBodyKey sid.nonce = s.requestBodyIV if !s.sessionHistory.addIfNotExits(sid) { - return nil, newError("duplicated session id, possibly under replay attack, but this is a AEAD request") + return nil, errors.New("duplicated session id, possibly under replay attack, but this is a AEAD request") } s.responseHeader = buffer.Byte(33) // 1 byte @@ -219,12 +220,12 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader, isDrain bool) (*pr if paddingLen > 0 { if _, err := buffer.ReadFullFrom(decryptor, int32(paddingLen)); err != nil { - return nil, newError("failed to read padding").Base(err) + return nil, errors.New("failed to read padding").Base(err) } } if _, err := buffer.ReadFullFrom(decryptor, 4); err != nil { - return nil, newError("failed to read checksum").Base(err) + return nil, errors.New("failed to read checksum").Base(err) } fnv1a := fnv.New32a() @@ -233,15 +234,15 @@ func (s *ServerSession) DecodeRequestHeader(reader io.Reader, isDrain bool) (*pr expectedHash := binary.BigEndian.Uint32(buffer.BytesFrom(-4)) if actualHash != expectedHash { - return nil, newError("invalid auth, but this is a AEAD request") + return nil, errors.New("invalid auth, but this is a AEAD request") } if request.Address == nil { - return nil, newError("invalid remote address") + return nil, errors.New("invalid remote address") } if request.Security == protocol.SecurityType_UNKNOWN || request.Security == protocol.SecurityType_AUTO { - return nil, newError("unknown security type: ", request.Security) + return nil, errors.New("unknown security type: ", request.Security) } return request, nil @@ -258,7 +259,7 @@ func (s *ServerSession) DecodeRequestBody(request *protocol.RequestHeader, reade var ok bool padding, ok = sizeParser.(crypto.PaddingLengthGenerator) if !ok { - return nil, newError("invalid option: RequestOptionGlobalPadding") + return nil, errors.New("invalid option: RequestOptionGlobalPadding") } } @@ -321,7 +322,7 @@ func (s *ServerSession) DecodeRequestBody(request *protocol.RequestHeader, reade return crypto.NewAuthenticationReader(auth, sizeParser, reader, request.Command.TransferType(), padding), nil default: - return nil, newError("invalid option: Security") + return nil, errors.New("invalid option: Security") } } @@ -382,7 +383,7 @@ func (s *ServerSession) EncodeResponseBody(request *protocol.RequestHeader, writ var ok bool padding, ok = sizeParser.(crypto.PaddingLengthGenerator) if !ok { - return nil, newError("invalid option: RequestOptionGlobalPadding") + return nil, errors.New("invalid option: RequestOptionGlobalPadding") } } @@ -445,6 +446,6 @@ func (s *ServerSession) EncodeResponseBody(request *protocol.RequestHeader, writ return crypto.NewAuthenticationWriter(auth, sizeParser, writer, request.Command.TransferType(), padding), nil default: - return nil, newError("invalid option: Security") + return nil, errors.New("invalid option: Security") } } diff --git a/proxy/vmess/errors.generated.go b/proxy/vmess/errors.generated.go deleted file mode 100644 index 29d69d74..00000000 --- a/proxy/vmess/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package vmess - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/vmess/inbound/errors.generated.go b/proxy/vmess/inbound/errors.generated.go deleted file mode 100644 index c2d7295e..00000000 --- a/proxy/vmess/inbound/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package inbound - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/vmess/inbound/inbound.go b/proxy/vmess/inbound/inbound.go index f5340f20..77db249f 100644 --- a/proxy/vmess/inbound/inbound.go +++ b/proxy/vmess/inbound/inbound.go @@ -120,11 +120,11 @@ func New(ctx context.Context, config *Config) (*Handler, error) { for _, user := range config.User { mUser, err := user.ToMemoryUser() if err != nil { - return nil, newError("failed to get VMess user").Base(err) + return nil, errors.New("failed to get VMess user").Base(err) } if err := handler.AddUser(ctx, mUser); err != nil { - return nil, newError("failed to initiate user").Base(err) + return nil, errors.New("failed to initiate user").Base(err) } } @@ -153,17 +153,17 @@ func (h *Handler) GetUser(email string) *protocol.MemoryUser { func (h *Handler) AddUser(ctx context.Context, user *protocol.MemoryUser) error { if len(user.Email) > 0 && !h.usersByEmail.Add(user) { - return newError("User ", user.Email, " already exists.") + return errors.New("User ", user.Email, " already exists.") } return h.clients.Add(user) } func (h *Handler) RemoveUser(ctx context.Context, email string) error { if email == "" { - return newError("Email must not be empty.") + return errors.New("Email must not be empty.") } if !h.usersByEmail.Remove(email) { - return newError("User ", email, " not found.") + return errors.New("User ", email, " not found.") } h.clients.Remove(email) return nil @@ -174,7 +174,7 @@ func transferResponse(timer signal.ActivityUpdater, session *encoding.ServerSess bodyWriter, err := session.EncodeResponseBody(request, output) if err != nil { - return newError("failed to start decoding response").Base(err) + return errors.New("failed to start decoding response").Base(err) } { // Optimize for small response packet @@ -211,7 +211,7 @@ func transferResponse(timer signal.ActivityUpdater, session *encoding.ServerSess func (h *Handler) Process(ctx context.Context, network net.Network, connection stat.Connection, dispatcher routing.Dispatcher) error { sessionPolicy := h.policyManager.ForLevel(0) if err := connection.SetReadDeadline(time.Now().Add(sessionPolicy.Timeouts.Handshake)); err != nil { - return newError("unable to set read deadline").Base(err).AtWarning() + return errors.New("unable to set read deadline").Base(err).AtWarning() } iConn := connection @@ -234,7 +234,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s Status: log.AccessRejected, Reason: err, }) - err = newError("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo() + err = errors.New("invalid request from ", connection.RemoteAddr()).Base(err).AtInfo() } return err } @@ -249,10 +249,10 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s }) } - newError("received request for ", request.Destination()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "received request for ", request.Destination()) if err := connection.SetReadDeadline(time.Time{}); err != nil { - newError("unable to set back read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "unable to set back read deadline") } inbound := session.InboundFromContext(ctx) @@ -268,7 +268,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer) link, err := dispatcher.Dispatch(ctx, request.Destination()) if err != nil { - return newError("failed to dispatch request to ", request.Destination()).Base(err) + return errors.New("failed to dispatch request to ", request.Destination()).Base(err) } requestDone := func() error { @@ -276,10 +276,10 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s bodyReader, err := svrSession.DecodeRequestBody(request, reader) if err != nil { - return newError("failed to start decoding").Base(err) + return errors.New("failed to start decoding").Base(err) } if err := buf.Copy(bodyReader, link.Writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transfer request").Base(err) + return errors.New("failed to transfer request").Base(err) } return nil } @@ -300,7 +300,7 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s if err := task.Run(ctx, requestDonePost, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil @@ -312,7 +312,7 @@ func (h *Handler) generateCommand(ctx context.Context, request *protocol.Request if h.inboundHandlerManager != nil { handler, err := h.inboundHandlerManager.GetHandler(ctx, tag) if err != nil { - newError("failed to get detour handler: ", tag).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, err, "failed to get detour handler: ", tag) return nil } proxyHandler, port, availableMin := handler.GetRandomInboundProxy() @@ -322,7 +322,7 @@ func (h *Handler) generateCommand(ctx context.Context, request *protocol.Request availableMin = 255 } - newError("pick detour handler for port ", port, " for ", availableMin, " minutes.").AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, "pick detour handler for port ", port, " for ", availableMin, " minutes.") user := inboundHandler.GetUser(request.User.Email) if user == nil { return nil diff --git a/proxy/vmess/outbound/errors.generated.go b/proxy/vmess/outbound/errors.generated.go deleted file mode 100644 index 07966823..00000000 --- a/proxy/vmess/outbound/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package outbound - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/vmess/outbound/outbound.go b/proxy/vmess/outbound/outbound.go index 8f102dbb..2c339e42 100644 --- a/proxy/vmess/outbound/outbound.go +++ b/proxy/vmess/outbound/outbound.go @@ -11,6 +11,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "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" @@ -42,7 +43,7 @@ func New(ctx context.Context, config *Config) (*Handler, error) { for _, rec := range config.Receiver { s, err := protocol.NewServerSpecFromPB(rec) if err != nil { - return nil, newError("failed to parse server spec").Base(err) + return nil, errors.New("failed to parse server spec").Base(err) } serverList.AddServer(s) } @@ -61,9 +62,9 @@ func New(ctx context.Context, config *Config) (*Handler, error) { // Process implements proxy.Outbound.Process(). func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified").AtError() + return errors.New("target not specified").AtError() } ob.Name = "vmess" ob.CanSpliceCopy = 3 @@ -81,12 +82,12 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte return nil }) if err != nil { - return newError("failed to find an available destination").Base(err).AtWarning() + return errors.New("failed to find an available destination").Base(err).AtWarning() } defer conn.Close() target := ob.Target - newError("tunneling request to ", target, " via ", rec.Destination().NetAddr()).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "tunneling request to ", target, " via ", rec.Destination().NetAddr()) command := protocol.RequestCommandTCP if target.Network == net.Network_UDP { @@ -163,19 +164,19 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte writer := buf.NewBufferedWriter(buf.NewWriter(conn)) if err := session.EncodeRequestHeader(request, writer); err != nil { - return newError("failed to encode request").Base(err).AtWarning() + return errors.New("failed to encode request").Base(err).AtWarning() } bodyWriter, err := session.EncodeRequestBody(request, writer) if err != nil { - return newError("failed to start encoding").Base(err) + return errors.New("failed to start encoding").Base(err) } bodyWriter2 := bodyWriter if request.Command == protocol.RequestCommandMux && request.Port == 666 { bodyWriter = xudp.NewPacketWriter(bodyWriter, target, xudp.GetGlobalID(ctx)) } if err := buf.CopyOnceTimeout(input, bodyWriter, time.Millisecond*100); err != nil && err != buf.ErrNotTimeoutReader && err != buf.ErrReadTimeout { - return newError("failed to write first payload").Base(err) + return errors.New("failed to write first payload").Base(err) } if err := writer.SetBuffered(false); err != nil { @@ -201,13 +202,13 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte reader := &buf.BufferedReader{Reader: buf.NewReader(conn)} header, err := session.DecodeResponseHeader(reader) if err != nil { - return newError("failed to read header").Base(err) + return errors.New("failed to read header").Base(err) } h.handleCommand(rec.Destination(), header.Command) bodyReader, err := session.DecodeResponseBody(request, reader) if err != nil { - return newError("failed to start encoding response").Base(err) + return errors.New("failed to start encoding response").Base(err) } if request.Command == protocol.RequestCommandMux && request.Port == 666 { bodyReader = xudp.NewPacketReader(&buf.BufferedReader{Reader: bodyReader}) @@ -222,7 +223,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte responseDonePost := task.OnSuccess(responseDone, task.Close(output)) if err := task.Run(ctx, requestDone, responseDonePost); err != nil { - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil diff --git a/proxy/vmess/validator.go b/proxy/vmess/validator.go index bc844061..00e49ae2 100644 --- a/proxy/vmess/validator.go +++ b/proxy/vmess/validator.go @@ -8,6 +8,7 @@ import ( "sync" "github.com/xtls/xray-core/common/dice" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/protocol" "github.com/xtls/xray-core/proxy/vmess/aead" ) @@ -104,6 +105,6 @@ func (v *TimedUserValidator) GetBehaviorSeed() uint64 { return v.behaviorSeed } -var ErrNotFound = newError("Not Found") +var ErrNotFound = errors.New("Not Found") -var ErrTainted = newError("ErrTainted") +var ErrTainted = errors.New("ErrTainted") diff --git a/proxy/wireguard/bind.go b/proxy/wireguard/bind.go index aaca93ff..80ab6a8d 100644 --- a/proxy/wireguard/bind.go +++ b/proxy/wireguard/bind.go @@ -202,7 +202,7 @@ func (bind *netBindServer) Send(buff [][]byte, endpoint conn.Endpoint) error { } if nend.conn == nil { - return newError("connection not open yet") + return errors.New("connection not open yet") } for _, buff := range buff { diff --git a/proxy/wireguard/client.go b/proxy/wireguard/client.go index 04a72650..56c91cef 100644 --- a/proxy/wireguard/client.go +++ b/proxy/wireguard/client.go @@ -29,6 +29,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/dice" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" @@ -120,7 +121,7 @@ func (h *Handler) processWireGuard(ctx context.Context, dialer internet.Dialer) h.net, err = h.makeVirtualTun(bind) if err != nil { - return newError("failed to create virtual tun interface").Base(err) + return errors.New("failed to create virtual tun interface").Base(err) } h.bind = bind return nil @@ -129,9 +130,9 @@ func (h *Handler) processWireGuard(ctx context.Context, dialer internet.Dialer) // Process implements OutboundHandler.Dispatch(). func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer internet.Dialer) error { outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] if !ob.Target.IsValid() { - return newError("target not specified") + return errors.New("target not specified") } ob.Name = "wireguard" ob.CanSpliceCopy = 3 @@ -163,7 +164,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } } if err != nil { - return newError("failed to lookup DNS").Base(err) + return errors.New("failed to lookup DNS").Base(err) } else if len(ips) == 0 { return dns.ErrEmptyResponse } @@ -193,7 +194,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte if command == protocol.RequestCommandTCP { conn, err := h.net.DialContextTCPAddrPort(ctx, addrPort) if err != nil { - return newError("failed to create TCP connection").Base(err) + return errors.New("failed to create TCP connection").Base(err) } defer conn.Close() @@ -208,7 +209,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte } else if command == protocol.RequestCommandUDP { conn, err := h.net.DialUDPAddrPort(netip.AddrPort{}, addrPort) if err != nil { - return newError("failed to create UDP connection").Base(err) + return errors.New("failed to create UDP connection").Base(err) } defer conn.Close() @@ -230,7 +231,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte if err := task.Run(ctx, requestFunc, responseDonePost); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) - return newError("connection ends").Base(err) + return errors.New("connection ends").Base(err) } return nil @@ -275,14 +276,14 @@ func (h *Handler) createIPCRequest(bind *netBindClient, conf *DeviceConfig) stri address, port, err := net.SplitHostPort(peer.Endpoint) if err != nil { - newError("failed to split endpoint ", peer.Endpoint, " into address and port").AtError().WriteToLog() + errors.LogError(h.bind.ctx, "failed to split endpoint ", peer.Endpoint, " into address and port") } addr := net.ParseAddress(address) if addr.Family().IsDomain() { dialerIp := bind.dialer.DestIpAddress() if dialerIp != nil { addr = net.ParseAddress(dialerIp.String()) - newError("createIPCRequest use dialer dest ip: ", addr).WriteToLog() + errors.LogInfo(h.bind.ctx, "createIPCRequest use dialer dest ip: ", addr) } else { ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{ IPv4Enable: h.hasIPv4 && h.conf.preferIP4(), @@ -297,9 +298,9 @@ func (h *Handler) createIPCRequest(bind *netBindClient, conf *DeviceConfig) stri } } if err != nil { - newError("createIPCRequest failed to lookup DNS").Base(err).WriteToLog() + errors.LogInfoInner(h.bind.ctx, err, "createIPCRequest failed to lookup DNS") } else if len(ips) == 0 { - newError("createIPCRequest empty lookup DNS").WriteToLog() + errors.LogInfo(h.bind.ctx, "createIPCRequest empty lookup DNS") } else { addr = net.IPAddress(ips[dice.Roll(len(ips))]) } diff --git a/proxy/wireguard/errors.generated.go b/proxy/wireguard/errors.generated.go deleted file mode 100644 index 8319e07d..00000000 --- a/proxy/wireguard/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package wireguard - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/proxy/wireguard/server.go b/proxy/wireguard/server.go index 3d3b584c..77aa4985 100644 --- a/proxy/wireguard/server.go +++ b/proxy/wireguard/server.go @@ -2,11 +2,12 @@ package wireguard import ( "context" - "errors" + goerrors "errors" "io" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/session" @@ -81,7 +82,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con inbound.Name = "wireguard" inbound.CanSpliceCopy = 3 outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] s.info = routingInfo{ ctx: core.ToBackgroundDetachedContext(ctx), @@ -117,7 +118,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con v.endpoint = nep v.err = err v.waiter.Done() - if err != nil && errors.Is(err, io.EOF) { + if err != nil && goerrors.Is(err, io.EOF) { nep.conn = nil return nil } @@ -127,7 +128,7 @@ func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Con func (s *Server) forwardConnection(dest net.Destination, conn net.Conn) { if s.info.dispatcher == nil { - newError("unexpected: dispatcher == nil").AtError().WriteToLog() + errors.LogError(s.info.ctx, "unexpected: dispatcher == nil") return } defer conn.Close() @@ -155,14 +156,14 @@ func (s *Server) forwardConnection(dest net.Destination, conn net.Conn) { link, err := s.info.dispatcher.Dispatch(ctx, dest) if err != nil { - newError("dispatch connection").Base(err).AtError().WriteToLog() + errors.LogErrorInner(s.info.ctx, err, "dispatch connection") } defer cancel() requestDone := func() error { defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly) if err := buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport all TCP request").Base(err) + return errors.New("failed to transport all TCP request").Base(err) } return nil @@ -171,7 +172,7 @@ func (s *Server) forwardConnection(dest net.Destination, conn net.Conn) { responseDone := func() error { defer timer.SetTimeout(plcy.Timeouts.UplinkOnly) if err := buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer)); err != nil { - return newError("failed to transport all TCP response").Base(err) + return errors.New("failed to transport all TCP response").Base(err) } return nil @@ -181,7 +182,7 @@ func (s *Server) forwardConnection(dest net.Destination, conn net.Conn) { if err := task.Run(ctx, requestDonePost, responseDone); err != nil { common.Interrupt(link.Reader) common.Interrupt(link.Writer) - newError("connection ends").Base(err).AtDebug().WriteToLog() + errors.LogDebugInner(s.info.ctx, err, "connection ends") return } } diff --git a/proxy/wireguard/tun.go b/proxy/wireguard/tun.go index c2d30323..7fd8a817 100644 --- a/proxy/wireguard/tun.go +++ b/proxy/wireguard/tun.go @@ -2,7 +2,6 @@ package wireguard import ( "context" - "errors" "fmt" "net" "net/netip" @@ -12,6 +11,7 @@ import ( "sync" "time" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/log" xnet "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/proxy/wireguard/gvisortun" @@ -158,7 +158,7 @@ func createGVisorTun(localAddresses []netip.Addr, mtu int, handler promiscuousMo // Perform a TCP three-way handshake. ep, err := r.CreateEndpoint(&wq) if err != nil { - newError(err.String()).AtError().WriteToLog() + errors.LogError(context.Background(), err.String()) r.Complete(true) return } @@ -183,7 +183,7 @@ func createGVisorTun(localAddresses []netip.Addr, mtu int, handler promiscuousMo ep, err := r.CreateEndpoint(&wq) if err != nil { - newError(err.String()).AtError().WriteToLog() + errors.LogError(context.Background(), err.String()) return } defer ep.Close() diff --git a/proxy/wireguard/tun_linux.go b/proxy/wireguard/tun_linux.go index 5ec40ffe..88446339 100644 --- a/proxy/wireguard/tun_linux.go +++ b/proxy/wireguard/tun_linux.go @@ -73,7 +73,7 @@ func (d *deviceNet) Close() (err error) { func createKernelTun(localAddresses []netip.Addr, mtu int, handler promiscuousModeHandler) (t Tunnel, err error) { if handler != nil { - return nil, newError("TODO: support promiscuous mode") + return nil, errors.New("TODO: support promiscuous mode") } var v4, v6 *netip.Addr diff --git a/proxy/wireguard/wireguard.go b/proxy/wireguard/wireguard.go index 2b3c3007..16a73ca2 100644 --- a/proxy/wireguard/wireguard.go +++ b/proxy/wireguard/wireguard.go @@ -2,6 +2,7 @@ package wireguard import ( "context" + "errors" "fmt" "net/netip" "strings" @@ -53,7 +54,7 @@ func parseEndpoints(conf *DeviceConfig) ([]netip.Addr, bool, bool, error) { } addr = prefix.Addr() if prefix.Bits() != addr.BitLen() { - return nil, false, false, newError("interface address subnet should be /32 for IPv4 and /128 for IPv6") + return nil, false, false, errors.New("interface address subnet should be /32 for IPv4 and /128 for IPv6") } } else { var err error diff --git a/transport/internet/config.go b/transport/internet/config.go index dc0b95e5..80353f39 100644 --- a/transport/internet/config.go +++ b/transport/internet/config.go @@ -1,6 +1,7 @@ package internet import ( + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/features" ) @@ -52,7 +53,7 @@ func transportProtocolToString(protocol TransportProtocol) string { func RegisterProtocolConfigCreator(name string, creator ConfigCreator) error { if _, found := globalTransportConfigCreatorCache[name]; found { - return newError("protocol ", name, " is already registered").AtError() + return errors.New("protocol ", name, " is already registered").AtError() } globalTransportConfigCreatorCache[name] = creator return nil @@ -63,7 +64,7 @@ func RegisterProtocolConfigCreator(name string, creator ConfigCreator) error { func CreateTransportConfig(name string) (interface{}, error) { creator, ok := globalTransportConfigCreatorCache[name] if !ok { - return nil, newError("unknown transport protocol: ", name) + return nil, errors.New("unknown transport protocol: ", name) } return creator(), nil } diff --git a/transport/internet/dialer.go b/transport/internet/dialer.go index ffa868a3..989bfa03 100644 --- a/transport/internet/dialer.go +++ b/transport/internet/dialer.go @@ -5,6 +5,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/dice" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/session" @@ -35,7 +36,7 @@ var transportDialerCache = make(map[string]dialFunc) // RegisterTransportDialer registers a Dialer with given name. func RegisterTransportDialer(protocol string, dialer dialFunc) error { if _, found := transportDialerCache[protocol]; found { - return newError(protocol, " dialer already registered").AtError() + return errors.New(protocol, " dialer already registered").AtError() } transportDialerCache[protocol] = dialer return nil @@ -47,7 +48,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *MemoryStrea if streamSettings == nil { s, err := ToMemoryStreamConfig(nil) if err != nil { - return nil, newError("failed to create default stream settings").Base(err) + return nil, errors.New("failed to create default stream settings").Base(err) } streamSettings = s } @@ -55,7 +56,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *MemoryStrea protocol := streamSettings.ProtocolName dialer := transportDialerCache[protocol] if dialer == nil { - return nil, newError(protocol, " dialer not registered").AtError() + return nil, errors.New(protocol, " dialer not registered").AtError() } return dialer(ctx, dest, streamSettings) } @@ -63,12 +64,12 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *MemoryStrea if dest.Network == net.Network_UDP { udpDialer := transportDialerCache["udp"] if udpDialer == nil { - return nil, newError("UDP dialer not registered").AtError() + return nil, errors.New("UDP dialer not registered").AtError() } return udpDialer(ctx, dest, streamSettings) } - return nil, newError("unknown network ", dest.Network) + return nil, errors.New("unknown network ", dest.Network) } // DestIpAddress returns the ip of proxy server. It is useful in case of Android client, which prepare an IP before proxy connection is established @@ -110,13 +111,13 @@ func canLookupIP(ctx context.Context, dst net.Destination, sockopt *SocketConfig } func redirect(ctx context.Context, dst net.Destination, obt string) net.Conn { - newError("redirecting request " + dst.String() + " to " + obt).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "redirecting request " + dst.String() + " to " + obt) h := obm.GetHandler(obt) outbounds := session.OutboundsFromContext(ctx) - ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{ - Target: dst, + ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{ + Target: dst, Gateway: nil, - Tag: obt, + Tag: obt, })) // add another outbound in session ctx if h != nil { ur, uw := pipe.New(pipe.OptionsFromContext(ctx)...) @@ -138,7 +139,7 @@ func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig var src net.Address outbounds := session.OutboundsFromContext(ctx) if len(outbounds) > 0 { - ob := outbounds[len(outbounds) - 1] + ob := outbounds[len(outbounds)-1] src = ob.Gateway } if sockopt == nil { @@ -149,9 +150,9 @@ func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig ips, err := lookupIP(dest.Address.String(), sockopt.DomainStrategy, src) if err == nil && len(ips) > 0 { dest.Address = net.IPAddress(ips[dice.Roll(len(ips))]) - newError("replace destination with " + dest.String()).AtInfo().WriteToLog() + errors.LogInfo(ctx, "replace destination with " + dest.String()) } else if err != nil { - newError("failed to resolve ip").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(ctx, err, "failed to resolve ip") } } diff --git a/transport/internet/domainsocket/config.go b/transport/internet/domainsocket/config.go index 7dfb5ec4..7f80a595 100644 --- a/transport/internet/domainsocket/config.go +++ b/transport/internet/domainsocket/config.go @@ -2,6 +2,7 @@ package domainsocket import ( "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet" ) @@ -14,7 +15,7 @@ const ( func (c *Config) GetUnixAddr() (*net.UnixAddr, error) { path := c.Path if path == "" { - return nil, newError("empty domain socket path") + return nil, errors.New("empty domain socket path") } if c.Abstract && path[0] != '@' { path = "@" + path diff --git a/transport/internet/domainsocket/dial.go b/transport/internet/domainsocket/dial.go index a0032b36..a060da78 100644 --- a/transport/internet/domainsocket/dial.go +++ b/transport/internet/domainsocket/dial.go @@ -7,6 +7,7 @@ import ( "context" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/reality" @@ -23,7 +24,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me conn, err := net.DialUnix("unix", nil, addr) if err != nil { - return nil, newError("failed to dial unix: ", settings.Path).Base(err).AtWarning() + return nil, errors.New("failed to dial unix: ", settings.Path).Base(err).AtWarning() } if config := tls.ConfigFromStreamSettings(streamSettings); config != nil { diff --git a/transport/internet/domainsocket/errors.generated.go b/transport/internet/domainsocket/errors.generated.go deleted file mode 100644 index 451b1aa6..00000000 --- a/transport/internet/domainsocket/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package domainsocket - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/domainsocket/listener.go b/transport/internet/domainsocket/listener.go index 323321e4..0b19c681 100644 --- a/transport/internet/domainsocket/listener.go +++ b/transport/internet/domainsocket/listener.go @@ -11,6 +11,7 @@ import ( goreality "github.com/xtls/reality" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/reality" @@ -38,7 +39,7 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti unixListener, err := net.ListenUnix("unix", addr) if err != nil { - return nil, newError("failed to listen domain socket").Base(err).AtWarning() + return nil, errors.New("failed to listen domain socket").Base(err).AtWarning() } ln := &Listener{ @@ -88,7 +89,7 @@ func (ln *Listener) run() { if strings.Contains(err.Error(), "closed") { break } - newError("failed to accepted raw connections").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(context.Background(), err, "failed to accepted raw connections") continue } go func() { @@ -96,7 +97,7 @@ func (ln *Listener) run() { conn = tls.Server(conn, ln.tlsConfig) } else if ln.realityConfig != nil { if conn, err = reality.Server(conn, ln.realityConfig); err != nil { - newError(err).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), err.Error()) return } } @@ -117,7 +118,7 @@ func (fl *fileLocker) Acquire() error { } if err := unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil { f.Close() - return newError("failed to lock file: ", fl.path).Base(err) + return errors.New("failed to lock file: ", fl.path).Base(err) } fl.file = f return nil @@ -125,13 +126,13 @@ func (fl *fileLocker) Acquire() error { func (fl *fileLocker) Release() { if err := unix.Flock(int(fl.file.Fd()), unix.LOCK_UN); err != nil { - newError("failed to unlock file: ", fl.path).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to unlock file: ", fl.path) } if err := fl.file.Close(); err != nil { - newError("failed to close file: ", fl.path).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to close file: ", fl.path) } if err := os.Remove(fl.path); err != nil { - newError("failed to remove file: ", fl.path).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to remove file: ", fl.path) } } diff --git a/transport/internet/errors.generated.go b/transport/internet/errors.generated.go deleted file mode 100644 index caf158a1..00000000 --- a/transport/internet/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package internet - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/filelocker_other.go b/transport/internet/filelocker_other.go index 28fc0f58..36d937c1 100644 --- a/transport/internet/filelocker_other.go +++ b/transport/internet/filelocker_other.go @@ -4,8 +4,10 @@ package internet import ( + "context" "os" + "github.com/xtls/xray-core/common/errors" "golang.org/x/sys/unix" ) @@ -17,7 +19,7 @@ func (fl *FileLocker) Acquire() error { } if err := unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil { f.Close() - return newError("failed to lock file: ", fl.path).Base(err) + return errors.New("failed to lock file: ", fl.path).Base(err) } fl.file = f return nil @@ -26,12 +28,12 @@ func (fl *FileLocker) Acquire() error { // Release lock func (fl *FileLocker) Release() { if err := unix.Flock(int(fl.file.Fd()), unix.LOCK_UN); err != nil { - newError("failed to unlock file: ", fl.path).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to unlock file: ", fl.path) } if err := fl.file.Close(); err != nil { - newError("failed to close file: ", fl.path).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to close file: ", fl.path) } if err := os.Remove(fl.path); err != nil { - newError("failed to remove file: ", fl.path).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to remove file: ", fl.path) } } diff --git a/transport/internet/grpc/dial.go b/transport/internet/grpc/dial.go index a4b03ced..24ae8ad0 100644 --- a/transport/internet/grpc/dial.go +++ b/transport/internet/grpc/dial.go @@ -7,6 +7,8 @@ import ( "time" "github.com/xtls/xray-core/common" + c "github.com/xtls/xray-core/common/ctx" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/transport/internet" @@ -22,11 +24,11 @@ import ( ) func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) { - newError("creating connection to ", dest).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "creating connection to ", dest) conn, err := dialgRPC(ctx, dest, streamSettings) if err != nil { - return nil, newError("failed to dial gRPC").Base(err) + return nil, errors.New("failed to dial gRPC").Base(err) } return stat.Connection(conn), nil } @@ -50,22 +52,22 @@ func dialgRPC(ctx context.Context, dest net.Destination, streamSettings *interne conn, err := getGrpcClient(ctx, dest, streamSettings) if err != nil { - return nil, newError("Cannot dial gRPC").Base(err) + return nil, errors.New("Cannot dial gRPC").Base(err) } client := encoding.NewGRPCServiceClient(conn) if grpcSettings.MultiMode { - newError("using gRPC multi mode service name: `" + grpcSettings.getServiceName() + "` stream name: `" + grpcSettings.getTunMultiStreamName() + "`").AtDebug().WriteToLog() + errors.LogDebug(ctx, "using gRPC multi mode service name: `" + grpcSettings.getServiceName() + "` stream name: `" + grpcSettings.getTunMultiStreamName() + "`") grpcService, err := client.(encoding.GRPCServiceClientX).TunMultiCustomName(ctx, grpcSettings.getServiceName(), grpcSettings.getTunMultiStreamName()) if err != nil { - return nil, newError("Cannot dial gRPC").Base(err) + return nil, errors.New("Cannot dial gRPC").Base(err) } return encoding.NewMultiHunkConn(grpcService, nil), nil } - newError("using gRPC tun mode service name: `" + grpcSettings.getServiceName() + "` stream name: `" + grpcSettings.getTunStreamName() + "`").AtDebug().WriteToLog() + errors.LogDebug(ctx, "using gRPC tun mode service name: `" + grpcSettings.getServiceName() + "` stream name: `" + grpcSettings.getTunStreamName() + "`") grpcService, err := client.(encoding.GRPCServiceClientX).TunCustomName(ctx, grpcSettings.getServiceName(), grpcSettings.getTunStreamName()) if err != nil { - return nil, newError("Cannot dial gRPC").Base(err) + return nil, errors.New("Cannot dial gRPC").Base(err) } return encoding.NewHunkConn(grpcService, nil), nil @@ -117,7 +119,7 @@ func getGrpcClient(ctx context.Context, dest net.Destination, streamSettings *in } address := net.ParseAddress(rawHost) - gctx = session.ContextWithID(gctx, session.IDFromContext(ctx)) + gctx = c.ContextWithID(gctx, c.IDFromContext(ctx)) gctx = session.ContextWithOutbounds(gctx, session.OutboundsFromContext(ctx)) gctx = session.ContextWithTimeoutOnly(gctx, true) diff --git a/transport/internet/grpc/encoding/errors.generated.go b/transport/internet/grpc/encoding/errors.generated.go deleted file mode 100644 index 267711d9..00000000 --- a/transport/internet/grpc/encoding/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package encoding - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/grpc/encoding/hunkconn.go b/transport/internet/grpc/encoding/hunkconn.go index cfa0d527..f295f33a 100644 --- a/transport/internet/grpc/encoding/hunkconn.go +++ b/transport/internet/grpc/encoding/hunkconn.go @@ -6,6 +6,7 @@ import ( "net" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" xnet "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/signal/done" @@ -79,7 +80,7 @@ func (h *HunkReaderWriter) forceFetch() error { return err } - return newError("failed to fetch hunk from gRPC tunnel").Base(err) + return errors.New("failed to fetch hunk from gRPC tunnel").Base(err) } h.buf = hunk.Data @@ -135,7 +136,7 @@ func (h *HunkReaderWriter) Write(buf []byte) (int, error) { err := h.hc.Send(&Hunk{Data: buf[:]}) if err != nil { - return 0, newError("failed to send data over gRPC tunnel").Base(err) + return 0, errors.New("failed to send data over gRPC tunnel").Base(err) } return len(buf), nil } diff --git a/transport/internet/grpc/encoding/multiconn.go b/transport/internet/grpc/encoding/multiconn.go index ec503947..fa95cba8 100644 --- a/transport/internet/grpc/encoding/multiconn.go +++ b/transport/internet/grpc/encoding/multiconn.go @@ -6,6 +6,7 @@ import ( "net" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" xnet "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/signal/done" @@ -74,7 +75,7 @@ func (h *MultiHunkReaderWriter) forceFetch() error { return err } - return newError("failed to fetch hunk from gRPC tunnel").Base(err) + return errors.New("failed to fetch hunk from gRPC tunnel").Base(err) } h.buf = hunk.Data diff --git a/transport/internet/grpc/errors.generated.go b/transport/internet/grpc/errors.generated.go deleted file mode 100644 index 290cc82f..00000000 --- a/transport/internet/grpc/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package grpc - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/grpc/hub.go b/transport/internet/grpc/hub.go index e55f6f77..b07c3b75 100644 --- a/transport/internet/grpc/hub.go +++ b/transport/internet/grpc/hub.go @@ -6,8 +6,8 @@ import ( goreality "github.com/xtls/reality" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/grpc/encoding" "github.com/xtls/xray-core/transport/internet/reality" @@ -94,7 +94,7 @@ func Listen(ctx context.Context, address net.Address, port net.Port, settings *i listener.s = s if settings.SocketSettings != nil && settings.SocketSettings.AcceptProxyProtocol { - newError("accepting PROXY protocol").AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarning(ctx, "accepting PROXY protocol") } go func() { @@ -106,7 +106,7 @@ func Listen(ctx context.Context, address net.Address, port net.Port, settings *i Net: "unix", }, settings.SocketSettings) if err != nil { - newError("failed to listen on ", address).Base(err).AtError().WriteToLog(session.ExportIDToError(ctx)) + errors.LogErrorInner(ctx, err, "failed to listen on ", address) return } } else { // tcp @@ -115,19 +115,19 @@ func Listen(ctx context.Context, address net.Address, port net.Port, settings *i Port: int(port), }, settings.SocketSettings) if err != nil { - newError("failed to listen on ", address, ":", port).Base(err).AtError().WriteToLog(session.ExportIDToError(ctx)) + errors.LogErrorInner(ctx, err, "failed to listen on ", address, ":", port) return } } - newError("gRPC listen for service name `" + grpcSettings.getServiceName() + "` tun `" + grpcSettings.getTunStreamName() + "` multi tun `" + grpcSettings.getTunMultiStreamName() + "`").AtDebug().WriteToLog() + errors.LogDebug(ctx, "gRPC listen for service name `" + grpcSettings.getServiceName() + "` tun `" + grpcSettings.getTunStreamName() + "` multi tun `" + grpcSettings.getTunMultiStreamName() + "`") encoding.RegisterGRPCServiceServerX(s, listener, grpcSettings.getServiceName(), grpcSettings.getTunStreamName(), grpcSettings.getTunMultiStreamName()) if config := reality.ConfigFromStreamSettings(settings); config != nil { streamListener = goreality.NewListener(streamListener, config.GetREALITYConfig()) } if err = s.Serve(streamListener); err != nil { - newError("Listener for gRPC ended").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "Listener for gRPC ended") } }() diff --git a/transport/internet/header.go b/transport/internet/header.go index 1fc67133..95c76343 100644 --- a/transport/internet/header.go +++ b/transport/internet/header.go @@ -5,6 +5,7 @@ import ( "net" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" ) type PacketHeader interface { @@ -20,7 +21,7 @@ func CreatePacketHeader(config interface{}) (PacketHeader, error) { if h, ok := header.(PacketHeader); ok { return h, nil } - return nil, newError("not a packet header") + return nil, errors.New("not a packet header") } type ConnectionAuthenticator interface { @@ -36,5 +37,5 @@ func CreateConnectionAuthenticator(config interface{}) (ConnectionAuthenticator, if a, ok := auth.(ConnectionAuthenticator); ok { return a, nil } - return nil, newError("not a ConnectionAuthenticator") + return nil, errors.New("not a ConnectionAuthenticator") } diff --git a/transport/internet/headers/http/errors.generated.go b/transport/internet/headers/http/errors.generated.go deleted file mode 100644 index f0048165..00000000 --- a/transport/internet/headers/http/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package http - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/headers/http/http.go b/transport/internet/headers/http/http.go index b9afb230..01168808 100644 --- a/transport/internet/headers/http/http.go +++ b/transport/internet/headers/http/http.go @@ -14,6 +14,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" ) const ( @@ -28,9 +29,9 @@ const ( ) var ( - ErrHeaderToLong = newError("Header too long.") + ErrHeaderToLong = errors.New("Header too long.") - ErrHeaderMisMatch = newError("Header Mismatch.") + ErrHeaderMisMatch = errors.New("Header Mismatch.") ) type Reader interface { diff --git a/transport/internet/http/dialer.go b/transport/internet/http/dialer.go index 0148658c..a1421d3f 100644 --- a/transport/internet/http/dialer.go +++ b/transport/internet/http/dialer.go @@ -11,6 +11,8 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + c "github.com/xtls/xray-core/common/ctx" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/session" @@ -44,7 +46,7 @@ func getHTTPClient(ctx context.Context, dest net.Destination, streamSettings *in tlsConfigs := tls.ConfigFromStreamSettings(streamSettings) realityConfigs := reality.ConfigFromStreamSettings(streamSettings) if tlsConfigs == nil && realityConfigs == nil { - return nil, newError("TLS or REALITY must be enabled for http transport.").AtWarning() + return nil, errors.New("TLS or REALITY must be enabled for http transport.").AtWarning() } sockopt := streamSettings.SocketSettings @@ -67,13 +69,13 @@ func getHTTPClient(ctx context.Context, dest net.Destination, streamSettings *in } address := net.ParseAddress(rawHost) - hctx = session.ContextWithID(hctx, session.IDFromContext(ctx)) + hctx = c.ContextWithID(hctx, c.IDFromContext(ctx)) hctx = session.ContextWithOutbounds(hctx, session.OutboundsFromContext(ctx)) hctx = session.ContextWithTimeoutOnly(hctx, true) pconn, err := internet.DialSystem(hctx, net.TCPDestination(address, port), sockopt) if err != nil { - newError("failed to dial to " + addr).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to dial to " + addr) return nil, err } @@ -88,18 +90,18 @@ func getHTTPClient(ctx context.Context, dest net.Destination, streamSettings *in cn = tls.Client(pconn, tlsConfig).(*tls.Conn) } if err := cn.HandshakeContext(ctx); err != nil { - newError("failed to dial to " + addr).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to dial to " + addr) return nil, err } if !tlsConfig.InsecureSkipVerify { if err := cn.VerifyHostname(tlsConfig.ServerName); err != nil { - newError("failed to dial to " + addr).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to dial to " + addr) return nil, err } } negotiatedProtocol := cn.NegotiatedProtocol() if negotiatedProtocol != http2.NextProtoTLS { - return nil, newError("http2: unexpected ALPN protocol " + negotiatedProtocol + "; want q" + http2.NextProtoTLS).AtError() + return nil, errors.New("http2: unexpected ALPN protocol " + negotiatedProtocol + "; want q" + http2.NextProtoTLS).AtError() } return cn, nil }, @@ -168,7 +170,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me go func() { response, err := client.Do(request) if err != nil { - newError("failed to dial to ", dest).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, err, "failed to dial to ", dest) wrc.Close() { // Abandon `client` if `client.Do(request)` failed @@ -182,7 +184,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me return } if response.StatusCode != 200 { - newError("unexpected status", response.StatusCode).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarning(ctx, "unexpected status", response.StatusCode) wrc.Close() return } diff --git a/transport/internet/http/errors.generated.go b/transport/internet/http/errors.generated.go deleted file mode 100644 index f0048165..00000000 --- a/transport/internet/http/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package http - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/http/hub.go b/transport/internet/http/hub.go index f0260460..3421ae64 100644 --- a/transport/internet/http/hub.go +++ b/transport/internet/http/hub.go @@ -9,11 +9,11 @@ import ( goreality "github.com/xtls/reality" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" http_proto "github.com/xtls/xray-core/common/protocol/http" "github.com/xtls/xray-core/common/serial" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/signal/done" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/reality" @@ -89,7 +89,7 @@ func (l *Listener) ServeHTTP(writer http.ResponseWriter, request *http.Request) remoteAddr := l.Addr() dest, err := net.ParseDestination(request.RemoteAddr) if err != nil { - newError("failed to parse request remote addr: ", request.RemoteAddr).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to parse request remote addr: ", request.RemoteAddr) } else { remoteAddr = &net.TCPAddr{ IP: dest.Address.IP(), @@ -160,7 +160,7 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti } if streamSettings.SocketSettings != nil && streamSettings.SocketSettings.AcceptProxyProtocol { - newError("accepting PROXY protocol").AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarning(ctx, "accepting PROXY protocol") } listener.server = server @@ -173,7 +173,7 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti Net: "unix", }, streamSettings.SocketSettings) if err != nil { - newError("failed to listen on ", address).Base(err).AtError().WriteToLog(session.ExportIDToError(ctx)) + errors.LogErrorInner(ctx, err, "failed to listen on ", address) return } } else { // tcp @@ -182,7 +182,7 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti Port: int(port), }, streamSettings.SocketSettings) if err != nil { - newError("failed to listen on ", address, ":", port).Base(err).AtError().WriteToLog(session.ExportIDToError(ctx)) + errors.LogErrorInner(ctx, err, "failed to listen on ", address, ":", port) return } } @@ -193,12 +193,12 @@ func Listen(ctx context.Context, address net.Address, port net.Port, streamSetti } err = server.Serve(streamListener) if err != nil { - newError("stopping serving H2C or REALITY H2").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "stopping serving H2C or REALITY H2") } } else { err = server.ServeTLS(streamListener, "", "") if err != nil { - newError("stopping serving TLS H2").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "stopping serving TLS H2") } } }() diff --git a/transport/internet/httpupgrade/dialer.go b/transport/internet/httpupgrade/dialer.go index d1a8bb0d..013f4f28 100644 --- a/transport/internet/httpupgrade/dialer.go +++ b/transport/internet/httpupgrade/dialer.go @@ -8,8 +8,8 @@ import ( "strings" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/stat" "github.com/xtls/xray-core/transport/internet/tls" @@ -34,7 +34,7 @@ func (c *ConnRF) Read(b []byte) (int, error) { if resp.Status != "101 Switching Protocols" || strings.ToLower(resp.Header.Get("Upgrade")) != "websocket" || strings.ToLower(resp.Header.Get("Connection")) != "upgrade" { - return 0, newError("unrecognized reply") + return 0, errors.New("unrecognized reply") } // drain remaining bufreader return reader.Read(b[:reader.Buffered()]) @@ -47,7 +47,7 @@ func dialhttpUpgrade(ctx context.Context, dest net.Destination, streamSettings * pconn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings) if err != nil { - newError("failed to dial to ", dest).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to dial to ", dest) return nil, err } @@ -104,19 +104,19 @@ func dialhttpUpgrade(ctx context.Context, dest net.Destination, streamSettings * return connRF, nil } -//http.Header.Add() will convert headers to MIME header format. -//Some people don't like this because they want to send "Web*S*ocket". -//So we add a simple function to replace that method. +// http.Header.Add() will convert headers to MIME header format. +// Some people don't like this because they want to send "Web*S*ocket". +// So we add a simple function to replace that method. func AddHeader(header http.Header, key, value string) { header[key] = append(header[key], value) } func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) { - newError("creating connection to ", dest).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "creating connection to ", dest) conn, err := dialhttpUpgrade(ctx, dest, streamSettings) if err != nil { - return nil, newError("failed to dial request to ", dest).Base(err) + return nil, errors.New("failed to dial request to ", dest).Base(err) } return stat.Connection(conn), nil } diff --git a/transport/internet/httpupgrade/errors.generated.go b/transport/internet/httpupgrade/errors.generated.go deleted file mode 100644 index 9a3440c0..00000000 --- a/transport/internet/httpupgrade/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package httpupgrade - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/httpupgrade/httpupgrade.go b/transport/internet/httpupgrade/httpupgrade.go index c1410c61..e949f871 100644 --- a/transport/internet/httpupgrade/httpupgrade.go +++ b/transport/internet/httpupgrade/httpupgrade.go @@ -4,6 +4,7 @@ import ( "context" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" ) //go:generate go run github.com/xtls/xray-core/common/errors/errorgen @@ -12,6 +13,6 @@ const protocolName = "httpupgrade" func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { - return nil, newError("httpupgrade is a transport protocol.") + return nil, errors.New("httpupgrade is a transport protocol.") })) } diff --git a/transport/internet/httpupgrade/hub.go b/transport/internet/httpupgrade/hub.go index 7f873d7b..52e260a4 100644 --- a/transport/internet/httpupgrade/hub.go +++ b/transport/internet/httpupgrade/hub.go @@ -8,9 +8,9 @@ import ( "strings" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" http_proto "github.com/xtls/xray-core/common/protocol/http" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/stat" v2tls "github.com/xtls/xray-core/transport/internet/tls" @@ -40,11 +40,11 @@ func (s *server) Handle(conn net.Conn) (stat.Connection, error) { if s.config != nil { host := req.Host if len(s.config.Host) > 0 && host != s.config.Host { - return nil, newError("bad host: ", host) + return nil, errors.New("bad host: ", host) } path := s.config.GetNormalizedPath() if req.URL.Path != path { - return nil, newError("bad path: ", req.URL.Path) + return nil, errors.New("bad path: ", req.URL.Path) } } @@ -52,7 +52,7 @@ func (s *server) Handle(conn net.Conn) (stat.Connection, error) { upgrade := strings.ToLower(req.Header.Get("Upgrade")) if connection != "upgrade" || upgrade != "websocket" { _ = conn.Close() - return nil, newError("unrecognized request") + return nil, errors.New("unrecognized request") } resp := &http.Response{ Status: "101 Switching Protocols", @@ -90,7 +90,7 @@ func (s *server) keepAccepting() { } handledConn, err := s.Handle(conn) if err != nil { - newError("failed to handle request").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to handle request") continue } s.addConn(handledConn) @@ -113,22 +113,22 @@ func ListenHTTPUpgrade(ctx context.Context, address net.Address, port net.Port, Net: "unix", }, streamSettings.SocketSettings) if err != nil { - return nil, newError("failed to listen unix domain socket(for HttpUpgrade) on ", address).Base(err) + return nil, errors.New("failed to listen unix domain socket(for HttpUpgrade) on ", address).Base(err) } - newError("listening unix domain socket(for HttpUpgrade) on ", address).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "listening unix domain socket(for HttpUpgrade) on ", address) } else { // tcp listener, err = internet.ListenSystem(ctx, &net.TCPAddr{ IP: address.IP(), Port: int(port), }, streamSettings.SocketSettings) if err != nil { - return nil, newError("failed to listen TCP(for HttpUpgrade) on ", address, ":", port).Base(err) + return nil, errors.New("failed to listen TCP(for HttpUpgrade) on ", address, ":", port).Base(err) } - newError("listening TCP(for HttpUpgrade) on ", address, ":", port).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "listening TCP(for HttpUpgrade) on ", address, ":", port) } if streamSettings.SocketSettings != nil && streamSettings.SocketSettings.AcceptProxyProtocol { - newError("accepting PROXY protocol").AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarning(ctx, "accepting PROXY protocol") } if config := v2tls.ConfigFromStreamSettings(streamSettings); config != nil { diff --git a/transport/internet/kcp/connection.go b/transport/internet/kcp/connection.go index b0df75f0..ffedcfc7 100644 --- a/transport/internet/kcp/connection.go +++ b/transport/internet/kcp/connection.go @@ -2,6 +2,7 @@ package kcp import ( "bytes" + "context" "io" "net" "runtime" @@ -10,14 +11,15 @@ import ( "time" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/signal" "github.com/xtls/xray-core/common/signal/semaphore" ) var ( - ErrIOTimeout = newError("Read/Write timeout") - ErrClosedListener = newError("Listener closed.") - ErrClosedConnection = newError("Connection closed.") + ErrIOTimeout = errors.New("Read/Write timeout") + ErrClosedListener = errors.New("Listener closed.") + ErrClosedConnection = errors.New("Connection closed.") ) // State of the connection @@ -203,7 +205,7 @@ type Connection struct { // NewConnection create a new KCP connection between local and remote. func NewConnection(meta ConnMetadata, writer PacketWriter, closer io.Closer, config *Config) *Connection { - newError("#", meta.Conversation, " creating connection to ", meta.RemoteAddr).WriteToLog() + errors.LogInfo(context.Background(), "#", meta.Conversation, " creating connection to ", meta.RemoteAddr) conn := &Connection{ meta: meta, @@ -428,7 +430,7 @@ func (c *Connection) SetState(state State) { current := c.Elapsed() atomic.StoreInt32((*int32)(&c.state), int32(state)) atomic.StoreUint32(&c.stateBeginTime, current) - newError("#", c.meta.Conversation, " entering state ", state, " at ", current).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "#", c.meta.Conversation, " entering state ", state, " at ", current) switch state { case StateReadyToClose: @@ -472,7 +474,7 @@ func (c *Connection) Close() error { c.SetState(StateTerminated) } - newError("#", c.meta.Conversation, " closing connection to ", c.meta.RemoteAddr).WriteToLog() + errors.LogInfo(context.Background(), "#", c.meta.Conversation, " closing connection to ", c.meta.RemoteAddr) return nil } @@ -528,7 +530,7 @@ func (c *Connection) Terminate() { if c == nil { return } - newError("#", c.meta.Conversation, " terminating connection to ", c.RemoteAddr()).WriteToLog() + errors.LogInfo(context.Background(), "#", c.meta.Conversation, " terminating connection to ", c.RemoteAddr()) // v.SetState(StateTerminated) c.dataInput.Signal() @@ -616,7 +618,7 @@ func (c *Connection) flush() { } if c.State() == StateTerminating { - newError("#", c.meta.Conversation, " sending terminating cmd.").AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "#", c.meta.Conversation, " sending terminating cmd.") c.Ping(current, CommandTerminate) if current-atomic.LoadUint32(&c.stateBeginTime) > 8000 { diff --git a/transport/internet/kcp/crypt.go b/transport/internet/kcp/crypt.go index 0a5930f0..2843379a 100644 --- a/transport/internet/kcp/crypt.go +++ b/transport/internet/kcp/crypt.go @@ -6,6 +6,7 @@ import ( "hash/fnv" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" ) // SimpleAuthenticator is a legacy AEAD used for KCP encryption. @@ -64,12 +65,12 @@ func (a *SimpleAuthenticator) Open(dst, nonce, cipherText, extra []byte) ([]byte fnvHash := fnv.New32a() common.Must2(fnvHash.Write(dst[4:])) if binary.BigEndian.Uint32(dst[:4]) != fnvHash.Sum32() { - return nil, newError("invalid auth") + return nil, errors.New("invalid auth") } length := binary.BigEndian.Uint16(dst[4:6]) if len(dst)-6 != int(length) { - return nil, newError("invalid auth") + return nil, errors.New("invalid auth") } return dst[6:], nil diff --git a/transport/internet/kcp/dialer.go b/transport/internet/kcp/dialer.go index 3e8d1220..0a3968dc 100644 --- a/transport/internet/kcp/dialer.go +++ b/transport/internet/kcp/dialer.go @@ -8,6 +8,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/dice" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/stat" @@ -46,22 +47,22 @@ func fetchInput(_ context.Context, input io.Reader, reader PacketReader, conn *C // DialKCP dials a new KCP connections to the specific destination. func DialKCP(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) { dest.Network = net.Network_UDP - newError("dialing mKCP to ", dest).WriteToLog() + errors.LogInfo(ctx, "dialing mKCP to ", dest) rawConn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings) if err != nil { - return nil, newError("failed to dial to dest: ", err).AtWarning().Base(err) + return nil, errors.New("failed to dial to dest: ", err).AtWarning().Base(err) } kcpSettings := streamSettings.ProtocolSettings.(*Config) header, err := kcpSettings.GetPackerHeader() if err != nil { - return nil, newError("failed to create packet header").Base(err) + return nil, errors.New("failed to create packet header").Base(err) } security, err := kcpSettings.GetSecurity() if err != nil { - return nil, newError("failed to create security").Base(err) + return nil, errors.New("failed to create security").Base(err) } reader := &KCPPacketReader{ Header: header, diff --git a/transport/internet/kcp/errors.generated.go b/transport/internet/kcp/errors.generated.go deleted file mode 100644 index 63c51c6f..00000000 --- a/transport/internet/kcp/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package kcp - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/kcp/listener.go b/transport/internet/kcp/listener.go index 82b5a3bc..71ce6462 100644 --- a/transport/internet/kcp/listener.go +++ b/transport/internet/kcp/listener.go @@ -8,6 +8,7 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/stat" @@ -38,11 +39,11 @@ func NewListener(ctx context.Context, address net.Address, port net.Port, stream kcpSettings := streamSettings.ProtocolSettings.(*Config) header, err := kcpSettings.GetPackerHeader() if err != nil { - return nil, newError("failed to create packet header").Base(err).AtError() + return nil, errors.New("failed to create packet header").Base(err).AtError() } security, err := kcpSettings.GetSecurity() if err != nil { - return nil, newError("failed to create security").Base(err).AtError() + return nil, errors.New("failed to create security").Base(err).AtError() } l := &Listener{ header: header, @@ -67,7 +68,7 @@ func NewListener(ctx context.Context, address net.Address, port net.Port, stream l.Lock() l.hub = hub l.Unlock() - newError("listening on ", address, ":", port).WriteToLog() + errors.LogInfo(ctx, "listening on ", address, ":", port) go l.handlePackets() @@ -86,7 +87,7 @@ func (l *Listener) OnReceive(payload *buf.Buffer, src net.Destination) { payload.Release() if len(segments) == 0 { - newError("discarding invalid payload from ", src).WriteToLog() + errors.LogInfo(context.Background(), "discarding invalid payload from ", src) return } diff --git a/transport/internet/quic/config.go b/transport/internet/quic/config.go index fe13eec6..364ada7c 100644 --- a/transport/internet/quic/config.go +++ b/transport/internet/quic/config.go @@ -4,6 +4,7 @@ import ( "crypto/aes" "crypto/cipher" "crypto/sha256" + "errors" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/protocol" @@ -30,7 +31,7 @@ func getAuth(config *Config) (cipher.AEAD, error) { return chacha20poly1305.New(key[:]) } - return nil, newError("unsupported security type") + return nil, errors.New("unsupported security type") } func getHeader(config *Config) (internet.PacketHeader, error) { diff --git a/transport/internet/quic/dialer.go b/transport/internet/quic/dialer.go index 7c8122b6..df73e169 100644 --- a/transport/internet/quic/dialer.go +++ b/transport/internet/quic/dialer.go @@ -9,6 +9,7 @@ import ( "github.com/quic-go/quic-go/logging" "github.com/quic-go/quic-go/qlog" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/task" "github.com/xtls/xray-core/transport/internet" @@ -21,7 +22,7 @@ type connectionContext struct { conn quic.Connection } -var errConnectionClosed = newError("connection closed") +var errConnectionClosed = errors.New("connection closed") func (c *connectionContext) openStream(destAddr net.Addr) (*interConn, error) { if !isActive(c.conn) { @@ -65,17 +66,17 @@ func removeInactiveConnections(conns []*connectionContext) []*connectionContext continue } - newError("closing quic connection at index: ", i).WriteToLog() + errors.LogInfo(context.Background(), "closing quic connection at index: ", i) if err := s.conn.CloseWithError(0, ""); err != nil { - newError("failed to close connection").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to close connection") } if err := s.rawConn.Close(); err != nil { - newError("failed to close raw connection").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to close raw connection") } } if len(activeConnections) < len(conns) { - newError("active quic connection reduced from ", len(conns), " to ", len(activeConnections)).WriteToLog() + errors.LogInfo(context.Background(), "active quic connection reduced from ", len(conns), " to ", len(activeConnections)) return activeConnections } @@ -125,17 +126,17 @@ func (s *clientConnections) openConnection(ctx context.Context, destAddr net.Add if err == nil { return conn, nil } - newError("failed to openStream: ").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "failed to openStream: ") } else { - newError("current quic connection is not active!").WriteToLog() + errors.LogInfo(ctx, "current quic connection is not active!") } } conns = removeInactiveConnections(conns) - newError("dialing quic to ", dest).WriteToLog() + errors.LogInfo(ctx, "dialing quic to ", dest) rawConn, err := internet.DialSystem(ctx, dest, sockopt) if err != nil { - return nil, newError("failed to dial to dest: ", err).AtWarning().Base(err) + return nil, errors.New("failed to dial to dest: ", err).AtWarning().Base(err) } quicConfig := &quic.Config{ @@ -156,7 +157,7 @@ func (s *clientConnections) openConnection(ctx context.Context, destAddr net.Add default: // TODO: Support sockopt for QUIC rawConn.Close() - return nil, newError("QUIC with sockopt is unsupported").AtWarning() + return nil, errors.New("QUIC with sockopt is unsupported").AtWarning() } sysConn, err := wrapSysConn(udpConn, config) @@ -208,14 +209,14 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me IP: dest.Address.IP(), Port: int(dest.Port), } - } else { + } else { dialerIp := internet.DestIpAddress() if dialerIp != nil { destAddr = &net.UDPAddr{ IP: dialerIp, Port: int(dest.Port), } - newError("quic Dial use dialer dest addr: ", destAddr).WriteToLog() + errors.LogInfo(ctx, "quic Dial use dialer dest addr: ", destAddr) } else { addr, err := net.ResolveUDPAddr("udp", dest.NetAddr()) if err != nil { diff --git a/transport/internet/quic/errors.generated.go b/transport/internet/quic/errors.generated.go deleted file mode 100644 index 808fd980..00000000 --- a/transport/internet/quic/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package quic - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/quic/hub.go b/transport/internet/quic/hub.go index 7f7ea86f..de8919fd 100644 --- a/transport/internet/quic/hub.go +++ b/transport/internet/quic/hub.go @@ -8,6 +8,7 @@ import ( "github.com/quic-go/quic-go/logging" "github.com/quic-go/quic-go/qlog" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol/tls/cert" "github.com/xtls/xray-core/common/signal/done" @@ -27,13 +28,13 @@ func (l *Listener) acceptStreams(conn quic.Connection) { for { stream, err := conn.AcceptStream(context.Background()) if err != nil { - newError("failed to accept stream").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to accept stream") select { case <-conn.Context().Done(): return case <-l.done.Wait(): if err := conn.CloseWithError(0, ""); err != nil { - newError("failed to close connection").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to close connection") } return default: @@ -56,7 +57,7 @@ func (l *Listener) keepAccepting() { for { conn, err := l.listener.Accept(context.Background()) if err != nil { - newError("failed to accept QUIC connection").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to accept QUIC connection") if l.done.Done() { break } @@ -83,7 +84,7 @@ func (l *Listener) Close() error { // Listen creates a new Listener based on configurations. func Listen(ctx context.Context, address net.Address, port net.Port, streamSettings *internet.MemoryStreamConfig, handler internet.ConnHandler) (internet.Listener, error) { if address.Family().IsDomain() { - return nil, newError("domain address is not allows for listening quic") + return nil, errors.New("domain address is not allows for listening quic") } tlsConfig := tls.ConfigFromStreamSettings(streamSettings) diff --git a/transport/internet/reality/config.go b/transport/internet/reality/config.go index be3611e5..406494da 100644 --- a/transport/internet/reality/config.go +++ b/transport/internet/reality/config.go @@ -1,12 +1,14 @@ package reality import ( + "context" "io" "net" "os" "time" "github.com/xtls/reality" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/transport/internet" ) @@ -48,7 +50,7 @@ func KeyLogWriterFromConfig(c *Config) io.Writer { writer, err := os.OpenFile(c.MasterKeyLog, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644) if err != nil { - newError("failed to open ", c.MasterKeyLog, " as master key log").AtError().Base(err).WriteToLog() + errors.LogErrorInner(context.Background(), err, "failed to open ", c.MasterKeyLog, " as master key log") } return writer diff --git a/transport/internet/reality/errors.generated.go b/transport/internet/reality/errors.generated.go deleted file mode 100644 index e578015f..00000000 --- a/transport/internet/reality/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package reality - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/reality/reality.go b/transport/internet/reality/reality.go index 011bb907..8c77e79f 100644 --- a/transport/internet/reality/reality.go +++ b/transport/internet/reality/reality.go @@ -29,7 +29,6 @@ import ( "github.com/xtls/reality" "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/transport/internet/tls" "golang.org/x/crypto/chacha20poly1305" @@ -120,7 +119,7 @@ func UClient(c net.Conn, config *Config, ctx context.Context, dest net.Destinati uConn.ServerName = utlsConfig.ServerName fingerprint := tls.GetFingerprint(config.Fingerprint) if fingerprint == nil { - return nil, newError("REALITY: failed to get fingerprint").AtError() + return nil, errors.New("REALITY: failed to get fingerprint").AtError() } uConn.UConn = utls.UClient(c, utlsConfig, *fingerprint) { @@ -135,7 +134,7 @@ func UClient(c net.Conn, config *Config, ctx context.Context, dest net.Destinati binary.BigEndian.PutUint32(hello.SessionId[4:], uint32(time.Now().Unix())) copy(hello.SessionId[8:], config.ShortId) if config.Show { - newError(fmt.Sprintf("REALITY localAddr: %v\thello.SessionId[:16]: %v\n", localAddr, hello.SessionId[:16])).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, fmt.Sprintf("REALITY localAddr: %v\thello.SessionId[:16]: %v\n", localAddr, hello.SessionId[:16])) } publicKey, err := ecdh.X25519().NewPublicKey(config.PublicKey) if err != nil { @@ -156,7 +155,7 @@ func UClient(c net.Conn, config *Config, ctx context.Context, dest net.Destinati aead, _ = chacha20poly1305.New(uConn.AuthKey) } if config.Show { - newError(fmt.Sprintf("REALITY localAddr: %v\tuConn.AuthKey[:16]: %v\tAEAD: %T\n", localAddr, uConn.AuthKey[:16], aead)).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, fmt.Sprintf("REALITY localAddr: %v\tuConn.AuthKey[:16]: %v\tAEAD: %T\n", localAddr, uConn.AuthKey[:16], aead)) } aead.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw) copy(hello.Raw[39:], hello.SessionId) @@ -165,14 +164,14 @@ func UClient(c net.Conn, config *Config, ctx context.Context, dest net.Destinati return nil, err } if config.Show { - newError(fmt.Sprintf("REALITY localAddr: %v\tuConn.Verified: %v\n", localAddr, uConn.Verified)).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, fmt.Sprintf("REALITY localAddr: %v\tuConn.Verified: %v\n", localAddr, uConn.Verified)) } if !uConn.Verified { go func() { client := &http.Client{ Transport: &http2.Transport{ DialTLSContext: func(ctx context.Context, network, addr string, cfg *gotls.Config) (net.Conn, error) { - newError(fmt.Sprintf("REALITY localAddr: %v\tDialTLSContext\n", localAddr)).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, fmt.Sprintf("REALITY localAddr: %v\tDialTLSContext\n", localAddr)) return uConn, nil }, }, @@ -209,7 +208,7 @@ func UClient(c net.Conn, config *Config, ctx context.Context, dest net.Destinati } req.Header.Set("User-Agent", fingerprint.Client) // TODO: User-Agent map if first && config.Show { - newError(fmt.Sprintf("REALITY localAddr: %v\treq.UserAgent(): %v\n", localAddr, req.UserAgent())).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, fmt.Sprintf("REALITY localAddr: %v\treq.UserAgent(): %v\n", localAddr, req.UserAgent())) } times := 1 if !first { @@ -237,9 +236,9 @@ func UClient(c net.Conn, config *Config, ctx context.Context, dest net.Destinati } req.URL.Path = getPathLocked(paths) if config.Show { - newError(fmt.Sprintf("REALITY localAddr: %v\treq.Referer(): %v\n", localAddr, req.Referer())).WriteToLog(session.ExportIDToError(ctx)) - newError(fmt.Sprintf("REALITY localAddr: %v\tlen(body): %v\n", localAddr, len(body))).WriteToLog(session.ExportIDToError(ctx)) - newError(fmt.Sprintf("REALITY localAddr: %v\tlen(paths): %v\n", localAddr, len(paths))).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, fmt.Sprintf("REALITY localAddr: %v\treq.Referer(): %v\n", localAddr, req.Referer())) + errors.LogInfo(ctx, fmt.Sprintf("REALITY localAddr: %v\tlen(body): %v\n", localAddr, len(body))) + errors.LogInfo(ctx, fmt.Sprintf("REALITY localAddr: %v\tlen(paths): %v\n", localAddr, len(paths))) } maps.Unlock() if !first { diff --git a/transport/internet/sockopt_darwin.go b/transport/internet/sockopt_darwin.go index de405538..82e0efbb 100644 --- a/transport/internet/sockopt_darwin.go +++ b/transport/internet/sockopt_darwin.go @@ -6,6 +6,7 @@ import ( "syscall" "unsafe" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "golang.org/x/sys/unix" ) @@ -36,7 +37,7 @@ const ( func OriginalDst(la, ra net.Addr) (net.IP, int, error) { f, err := os.Open("/dev/pf") if err != nil { - return net.IP{}, -1, newError("failed to open device /dev/pf").Base(err) + return net.IP{}, -1, errors.New("failed to open device /dev/pf").Base(err) } defer f.Close() fd := f.Fd() @@ -111,7 +112,7 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf InterfaceIndex := getInterfaceIndexByName(config.Interface) if InterfaceIndex != 0 { if err := unix.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_BOUND_IF, InterfaceIndex); err != nil { - return newError("failed to set Interface").Base(err) + return errors.New("failed to set Interface").Base(err) } } } @@ -119,26 +120,26 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 { if config.TcpKeepAliveIdle > 0 { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_KEEPALIVE, int(config.TcpKeepAliveInterval)); err != nil { - return newError("failed to set TCP_KEEPINTVL", err) + return errors.New("failed to set TCP_KEEPINTVL", err) } } if config.TcpKeepAliveInterval > 0 { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, sysTCP_KEEPINTVL, int(config.TcpKeepAliveIdle)); err != nil { - return newError("failed to set TCP_KEEPIDLE", err) + return errors.New("failed to set TCP_KEEPIDLE", err) } } if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1); err != nil { - return newError("failed to set SO_KEEPALIVE", err) + return errors.New("failed to set SO_KEEPALIVE", err) } } else if config.TcpKeepAliveInterval < 0 || config.TcpKeepAliveIdle < 0 { if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 0); err != nil { - return newError("failed to unset SO_KEEPALIVE", err) + return errors.New("failed to unset SO_KEEPALIVE", err) } } if config.TcpNoDelay { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_NODELAY, 1); err != nil { - return newError("failed to set TCP_NODELAY", err) + return errors.New("failed to set TCP_NODELAY", err) } } } @@ -161,7 +162,7 @@ func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) InterfaceIndex := getInterfaceIndexByName(config.Interface) if InterfaceIndex != 0 { if err := unix.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_BOUND_IF, InterfaceIndex); err != nil { - return newError("failed to set Interface").Base(err) + return errors.New("failed to set Interface").Base(err) } } } @@ -169,20 +170,20 @@ func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 { if config.TcpKeepAliveIdle > 0 { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_KEEPALIVE, int(config.TcpKeepAliveInterval)); err != nil { - return newError("failed to set TCP_KEEPINTVL", err) + return errors.New("failed to set TCP_KEEPINTVL", err) } } if config.TcpKeepAliveInterval > 0 { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, sysTCP_KEEPINTVL, int(config.TcpKeepAliveIdle)); err != nil { - return newError("failed to set TCP_KEEPIDLE", err) + return errors.New("failed to set TCP_KEEPIDLE", err) } } if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1); err != nil { - return newError("failed to set SO_KEEPALIVE", err) + return errors.New("failed to set SO_KEEPALIVE", err) } } else if config.TcpKeepAliveInterval < 0 || config.TcpKeepAliveIdle < 0 { if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 0); err != nil { - return newError("failed to unset SO_KEEPALIVE", err) + return errors.New("failed to unset SO_KEEPALIVE", err) } } } @@ -210,7 +211,7 @@ func bindAddr(fd uintptr, address []byte, port uint32) error { copy(a6.Addr[:], address) sockaddr = a6 default: - return newError("unexpected length of ip") + return errors.New("unexpected length of ip") } return unix.Bind(int(fd), sockaddr) @@ -218,14 +219,14 @@ func bindAddr(fd uintptr, address []byte, port uint32) error { func setReuseAddr(fd uintptr) error { if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1); err != nil { - return newError("failed to set SO_REUSEADDR").Base(err).AtWarning() + return errors.New("failed to set SO_REUSEADDR").Base(err).AtWarning() } return nil } func setReusePort(fd uintptr) error { if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil { - return newError("failed to set SO_REUSEPORT").Base(err).AtWarning() + return errors.New("failed to set SO_REUSEPORT").Base(err).AtWarning() } return nil } diff --git a/transport/internet/sockopt_freebsd.go b/transport/internet/sockopt_freebsd.go index 66db4be3..4d490a40 100644 --- a/transport/internet/sockopt_freebsd.go +++ b/transport/internet/sockopt_freebsd.go @@ -7,6 +7,7 @@ import ( "syscall" "unsafe" + "github.com/xtls/xray-core/common/errors" "golang.org/x/sys/unix" ) @@ -59,7 +60,7 @@ func (nl *pfiocNatlook) setPort(remote, local int) { func OriginalDst(la, ra net.Addr) (net.IP, int, error) { f, err := os.Open("/dev/pf") if err != nil { - return net.IP{}, -1, newError("failed to open device /dev/pf").Base(err) + return net.IP{}, -1, errors.New("failed to open device /dev/pf").Base(err) } defer f.Close() fd := f.Fd() @@ -126,7 +127,7 @@ func OriginalDst(la, ra net.Addr) (net.IP, int, error) { func applyOutboundSocketOptions(network string, address string, fd uintptr, config *SocketConfig) error { if config.Mark != 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_USER_COOKIE, int(config.Mark)); err != nil { - return newError("failed to set SO_USER_COOKIE").Base(err) + return errors.New("failed to set SO_USER_COOKIE").Base(err) } } @@ -137,26 +138,26 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf } if tfo >= 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_FASTOPEN, tfo); err != nil { - return newError("failed to set TCP_FASTOPEN_CONNECT=", tfo).Base(err) + return errors.New("failed to set TCP_FASTOPEN_CONNECT=", tfo).Base(err) } } if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 { if config.TcpKeepAliveIdle > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE, int(config.TcpKeepAliveIdle)); err != nil { - return newError("failed to set TCP_KEEPIDLE", err) + return errors.New("failed to set TCP_KEEPIDLE", err) } } if config.TcpKeepAliveInterval > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL, int(config.TcpKeepAliveInterval)); err != nil { - return newError("failed to set TCP_KEEPINTVL", err) + return errors.New("failed to set TCP_KEEPINTVL", err) } } if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 1); err != nil { - return newError("failed to set SO_KEEPALIVE", err) + return errors.New("failed to set SO_KEEPALIVE", err) } } else if config.TcpKeepAliveInterval < 0 || config.TcpKeepAliveIdle < 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 0); err != nil { - return newError("failed to unset SO_KEEPALIVE", err) + return errors.New("failed to unset SO_KEEPALIVE", err) } } } @@ -165,11 +166,11 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf ip, _, _ := net.SplitHostPort(address) if net.ParseIP(ip).To4() != nil { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_BINDANY, 1); err != nil { - return newError("failed to set outbound IP_BINDANY").Base(err) + return errors.New("failed to set outbound IP_BINDANY").Base(err) } } else { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IPV6, syscall.IPV6_BINDANY, 1); err != nil { - return newError("failed to set outbound IPV6_BINDANY").Base(err) + return errors.New("failed to set outbound IPV6_BINDANY").Base(err) } } } @@ -179,33 +180,33 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) error { if config.Mark != 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_USER_COOKIE, int(config.Mark)); err != nil { - return newError("failed to set SO_USER_COOKIE").Base(err) + return errors.New("failed to set SO_USER_COOKIE").Base(err) } } if isTCPSocket(network) { tfo := config.ParseTFOValue() if tfo >= 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_FASTOPEN, tfo); err != nil { - return newError("failed to set TCP_FASTOPEN=", tfo).Base(err) + return errors.New("failed to set TCP_FASTOPEN=", tfo).Base(err) } } if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 { if config.TcpKeepAliveIdle > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE, int(config.TcpKeepAliveIdle)); err != nil { - return newError("failed to set TCP_KEEPIDLE", err) + return errors.New("failed to set TCP_KEEPIDLE", err) } } if config.TcpKeepAliveInterval > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL, int(config.TcpKeepAliveInterval)); err != nil { - return newError("failed to set TCP_KEEPINTVL", err) + return errors.New("failed to set TCP_KEEPINTVL", err) } } if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 1); err != nil { - return newError("failed to set SO_KEEPALIVE", err) + return errors.New("failed to set SO_KEEPALIVE", err) } } else if config.TcpKeepAliveInterval < 0 || config.TcpKeepAliveIdle < 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 0); err != nil { - return newError("failed to unset SO_KEEPALIVE", err) + return errors.New("failed to unset SO_KEEPALIVE", err) } } } @@ -213,7 +214,7 @@ func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) if config.Tproxy.IsEnabled() { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IPV6, syscall.IPV6_BINDANY, 1); err != nil { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_BINDANY, 1); err != nil { - return newError("failed to set inbound IP_BINDANY").Base(err) + return errors.New("failed to set inbound IP_BINDANY").Base(err) } } } @@ -241,7 +242,7 @@ func bindAddr(fd uintptr, ip []byte, port uint32) error { copy(a6.Addr[:], ip) sockaddr = a6 default: - return newError("unexpected length of ip") + return errors.New("unexpected length of ip") } return syscall.Bind(int(fd), sockaddr) @@ -249,7 +250,7 @@ func bindAddr(fd uintptr, ip []byte, port uint32) error { func setReuseAddr(fd uintptr) error { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil { - return newError("failed to set SO_REUSEADDR").Base(err).AtWarning() + return errors.New("failed to set SO_REUSEADDR").Base(err).AtWarning() } return nil } @@ -257,7 +258,7 @@ func setReuseAddr(fd uintptr) error { func setReusePort(fd uintptr) error { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, soReUsePortLB, 1); err != nil { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, soReUsePort, 1); err != nil { - return newError("failed to set SO_REUSEPORT").Base(err).AtWarning() + return errors.New("failed to set SO_REUSEPORT").Base(err).AtWarning() } } return nil diff --git a/transport/internet/sockopt_linux.go b/transport/internet/sockopt_linux.go index 56f24be8..5731aeb5 100644 --- a/transport/internet/sockopt_linux.go +++ b/transport/internet/sockopt_linux.go @@ -4,6 +4,7 @@ import ( "net" "syscall" + "github.com/xtls/xray-core/common/errors" "golang.org/x/sys/unix" ) @@ -27,7 +28,7 @@ func bindAddr(fd uintptr, ip []byte, port uint32) error { copy(a6.Addr[:], ip) sockaddr = a6 default: - return newError("unexpected length of ip") + return errors.New("unexpected length of ip") } return syscall.Bind(int(fd), sockaddr) @@ -36,13 +37,13 @@ func bindAddr(fd uintptr, ip []byte, port uint32) error { func applyOutboundSocketOptions(network string, address string, fd uintptr, config *SocketConfig) error { if config.Mark != 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, int(config.Mark)); err != nil { - return newError("failed to set SO_MARK").Base(err) + return errors.New("failed to set SO_MARK").Base(err) } } if config.Interface != "" { if err := syscall.BindToDevice(int(fd), config.Interface); err != nil { - return newError("failed to set Interface").Base(err) + return errors.New("failed to set Interface").Base(err) } } @@ -53,57 +54,57 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf } if tfo >= 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, unix.TCP_FASTOPEN_CONNECT, tfo); err != nil { - return newError("failed to set TCP_FASTOPEN_CONNECT", tfo).Base(err) + return errors.New("failed to set TCP_FASTOPEN_CONNECT", tfo).Base(err) } } if config.TcpKeepAliveInterval > 0 || config.TcpKeepAliveIdle > 0 { if config.TcpKeepAliveInterval > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL, int(config.TcpKeepAliveInterval)); err != nil { - return newError("failed to set TCP_KEEPINTVL", err) + return errors.New("failed to set TCP_KEEPINTVL", err) } } if config.TcpKeepAliveIdle > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE, int(config.TcpKeepAliveIdle)); err != nil { - return newError("failed to set TCP_KEEPIDLE", err) + return errors.New("failed to set TCP_KEEPIDLE", err) } } if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 1); err != nil { - return newError("failed to set SO_KEEPALIVE", err) + return errors.New("failed to set SO_KEEPALIVE", err) } } else if config.TcpKeepAliveInterval < 0 || config.TcpKeepAliveIdle < 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 0); err != nil { - return newError("failed to unset SO_KEEPALIVE", err) + return errors.New("failed to unset SO_KEEPALIVE", err) } } if config.TcpCongestion != "" { if err := syscall.SetsockoptString(int(fd), syscall.SOL_TCP, syscall.TCP_CONGESTION, config.TcpCongestion); err != nil { - return newError("failed to set TCP_CONGESTION", err) + return errors.New("failed to set TCP_CONGESTION", err) } } if config.TcpWindowClamp > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_WINDOW_CLAMP, int(config.TcpWindowClamp)); err != nil { - return newError("failed to set TCP_WINDOW_CLAMP", err) + return errors.New("failed to set TCP_WINDOW_CLAMP", err) } } if config.TcpUserTimeout > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, int(config.TcpUserTimeout)); err != nil { - return newError("failed to set TCP_USER_TIMEOUT", err) + return errors.New("failed to set TCP_USER_TIMEOUT", err) } } if config.TcpMaxSeg > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_MAXSEG, int(config.TcpMaxSeg)); err != nil { - return newError("failed to set TCP_MAXSEG", err) + return errors.New("failed to set TCP_MAXSEG", err) } } if config.TcpNoDelay { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_NODELAY, 1); err != nil { - return newError("failed to set TCP_NODELAY", err) + return errors.New("failed to set TCP_NODELAY", err) } } @@ -111,7 +112,7 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf if config.Tproxy.IsEnabled() { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil { - return newError("failed to set IP_TRANSPARENT").Base(err) + return errors.New("failed to set IP_TRANSPARENT").Base(err) } } @@ -121,65 +122,65 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) error { if config.Mark != 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, int(config.Mark)); err != nil { - return newError("failed to set SO_MARK").Base(err) + return errors.New("failed to set SO_MARK").Base(err) } } if isTCPSocket(network) { tfo := config.ParseTFOValue() if tfo >= 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_TCP, unix.TCP_FASTOPEN, tfo); err != nil { - return newError("failed to set TCP_FASTOPEN", tfo).Base(err) + return errors.New("failed to set TCP_FASTOPEN", tfo).Base(err) } } if config.TcpKeepAliveInterval > 0 || config.TcpKeepAliveIdle > 0 { if config.TcpKeepAliveInterval > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL, int(config.TcpKeepAliveInterval)); err != nil { - return newError("failed to set TCP_KEEPINTVL", err) + return errors.New("failed to set TCP_KEEPINTVL", err) } } if config.TcpKeepAliveIdle > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE, int(config.TcpKeepAliveIdle)); err != nil { - return newError("failed to set TCP_KEEPIDLE", err) + return errors.New("failed to set TCP_KEEPIDLE", err) } } if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 1); err != nil { - return newError("failed to set SO_KEEPALIVE", err) + return errors.New("failed to set SO_KEEPALIVE", err) } } else if config.TcpKeepAliveInterval < 0 || config.TcpKeepAliveIdle < 0 { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 0); err != nil { - return newError("failed to unset SO_KEEPALIVE", err) + return errors.New("failed to unset SO_KEEPALIVE", err) } } if config.TcpCongestion != "" { if err := syscall.SetsockoptString(int(fd), syscall.SOL_TCP, syscall.TCP_CONGESTION, config.TcpCongestion); err != nil { - return newError("failed to set TCP_CONGESTION", err) + return errors.New("failed to set TCP_CONGESTION", err) } } if config.TcpWindowClamp > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_WINDOW_CLAMP, int(config.TcpWindowClamp)); err != nil { - return newError("failed to set TCP_WINDOW_CLAMP", err) + return errors.New("failed to set TCP_WINDOW_CLAMP", err) } } if config.TcpUserTimeout > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, int(config.TcpUserTimeout)); err != nil { - return newError("failed to set TCP_USER_TIMEOUT", err) + return errors.New("failed to set TCP_USER_TIMEOUT", err) } } if config.TcpMaxSeg > 0 { if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_MAXSEG, int(config.TcpMaxSeg)); err != nil { - return newError("failed to set TCP_MAXSEG", err) + return errors.New("failed to set TCP_MAXSEG", err) } } } if config.Tproxy.IsEnabled() { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil { - return newError("failed to set IP_TRANSPARENT").Base(err) + return errors.New("failed to set IP_TRANSPARENT").Base(err) } } @@ -193,7 +194,7 @@ func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) if config.V6Only { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IPV6, syscall.IPV6_V6ONLY, 1); err != nil { - return newError("failed to set IPV6_V6ONLY", err) + return errors.New("failed to set IPV6_V6ONLY", err) } } @@ -202,14 +203,14 @@ func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) func setReuseAddr(fd uintptr) error { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil { - return newError("failed to set SO_REUSEADDR").Base(err).AtWarning() + return errors.New("failed to set SO_REUSEADDR").Base(err).AtWarning() } return nil } func setReusePort(fd uintptr) error { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil { - return newError("failed to set SO_REUSEPORT").Base(err).AtWarning() + return errors.New("failed to set SO_REUSEPORT").Base(err).AtWarning() } return nil } diff --git a/transport/internet/sockopt_windows.go b/transport/internet/sockopt_windows.go index e2f1f796..c7a79bb6 100644 --- a/transport/internet/sockopt_windows.go +++ b/transport/internet/sockopt_windows.go @@ -5,6 +5,8 @@ import ( "net" "syscall" "unsafe" + + "github.com/xtls/xray-core/common/errors" ) const ( @@ -29,7 +31,7 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf if config.Interface != "" { inf, err := net.InterfaceByName(config.Interface) if err != nil { - return newError("failed to find the interface").Base(err) + return errors.New("failed to find the interface").Base(err) } isV4 := (network == "tcp4") if isV4 { @@ -37,11 +39,11 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf binary.BigEndian.PutUint32(bytes[:], uint32(inf.Index)) idx := *(*uint32)(unsafe.Pointer(&bytes[0])) if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, IP_UNICAST_IF, int(idx)); err != nil { - return newError("failed to set IP_UNICAST_IF").Base(err) + return errors.New("failed to set IP_UNICAST_IF").Base(err) } } else { if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IPV6, IPV6_UNICAST_IF, inf.Index); err != nil { - return newError("failed to set IPV6_UNICAST_IF").Base(err) + return errors.New("failed to set IPV6_UNICAST_IF").Base(err) } } } @@ -52,16 +54,16 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf } if config.TcpKeepAliveIdle > 0 { if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 1); err != nil { - return newError("failed to set SO_KEEPALIVE", err) + return errors.New("failed to set SO_KEEPALIVE", err) } } else if config.TcpKeepAliveIdle < 0 { if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 0); err != nil { - return newError("failed to unset SO_KEEPALIVE", err) + return errors.New("failed to unset SO_KEEPALIVE", err) } } if config.TcpNoDelay { if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_TCP, syscall.TCP_NODELAY, 1); err != nil { - return newError("failed to set TCP_NODELAY", err) + return errors.New("failed to set TCP_NODELAY", err) } } } @@ -76,11 +78,11 @@ func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) } if config.TcpKeepAliveIdle > 0 { if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 1); err != nil { - return newError("failed to set SO_KEEPALIVE", err) + return errors.New("failed to set SO_KEEPALIVE", err) } } else if config.TcpKeepAliveIdle < 0 { if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 0); err != nil { - return newError("failed to unset SO_KEEPALIVE", err) + return errors.New("failed to unset SO_KEEPALIVE", err) } } } diff --git a/transport/internet/splithttp/dialer.go b/transport/internet/splithttp/dialer.go index 899f7810..cecab58f 100644 --- a/transport/internet/splithttp/dialer.go +++ b/transport/internet/splithttp/dialer.go @@ -14,8 +14,8 @@ import ( "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/signal/done" "github.com/xtls/xray-core/common/signal/semaphore" "github.com/xtls/xray-core/common/uuid" @@ -136,7 +136,7 @@ func init() { } func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) { - newError("dialing splithttp to ", dest).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "dialing splithttp to ", dest) var requestURL url.URL @@ -191,7 +191,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me nil, ) if err != nil { - newError("failed to construct download http request").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "failed to construct download http request") gotDownResponse.Close() return } @@ -201,14 +201,14 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me response, err := httpClient.download.Do(req) gotConn.Close() if err != nil { - newError("failed to send download http request").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "failed to send download http request") gotDownResponse.Close() return } if response.StatusCode != 200 { response.Body.Close() - newError("invalid status code on download:", response.Status).WriteToLog() + errors.LogInfo(ctx, "invalid status code on download:", response.Status) gotDownResponse.Close() return } @@ -219,7 +219,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me _, err = io.ReadFull(response.Body, trashHeader) if err != nil { response.Body.Close() - newError("failed to read initial response").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "failed to read initial response") gotDownResponse.Close() return } @@ -258,7 +258,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me defer requestsLimiter.Signal() req, err := http.NewRequest("POST", url, &buf.MultiBufferContainer{MultiBuffer: chunk}) if err != nil { - newError("failed to send upload").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "failed to send upload") uploadPipeReader.Interrupt() return } @@ -268,14 +268,14 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me if httpClient.isH2 { resp, err := httpClient.upload.Do(req) if err != nil { - newError("failed to send upload").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "failed to send upload") uploadPipeReader.Interrupt() return } defer resp.Body.Close() if resp.StatusCode != 200 { - newError("failed to send upload, bad status code:", resp.Status).WriteToLog() + errors.LogInfo(ctx, "failed to send upload, bad status code:", resp.Status) uploadPipeReader.Interrupt() return } @@ -287,7 +287,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me if uploadConn == nil { uploadConn, err = httpClient.dialUploadConn(context.WithoutCancel(ctx)) if err != nil { - newError("failed to connect upload").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "failed to connect upload") uploadPipeReader.Interrupt() return } @@ -300,7 +300,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me } if err != nil { - newError("failed to send upload").Base(err).WriteToLog() + errors.LogInfoInner(ctx, err, "failed to send upload") uploadPipeReader.Interrupt() return } @@ -324,7 +324,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me CreateReader: func() (io.ReadCloser, error) { <-gotDownResponse.Wait() if downResponse == nil { - return nil, newError("downResponse failed") + return nil, errors.New("downResponse failed") } return downResponse, nil }, diff --git a/transport/internet/splithttp/errors.generated.go b/transport/internet/splithttp/errors.generated.go deleted file mode 100644 index 30fca9f6..00000000 --- a/transport/internet/splithttp/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package splithttp - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/splithttp/hub.go b/transport/internet/splithttp/hub.go index 1e586eef..3dee0b9e 100644 --- a/transport/internet/splithttp/hub.go +++ b/transport/internet/splithttp/hub.go @@ -12,9 +12,9 @@ import ( "time" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" http_proto "github.com/xtls/xray-core/common/protocol/http" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/signal/done" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/stat" @@ -73,13 +73,13 @@ func (h *requestHandler) upsertSession(sessionId string) *httpSession { func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { if len(h.host) > 0 && request.Host != h.host { - newError("failed to validate host, request:", request.Host, ", config:", h.host).WriteToLog() + errors.LogInfo(context.Background(), "failed to validate host, request:", request.Host, ", config:", h.host) writer.WriteHeader(http.StatusNotFound) return } if !strings.HasPrefix(request.URL.Path, h.path) { - newError("failed to validate path, request:", request.URL.Path, ", config:", h.path).WriteToLog() + errors.LogInfo(context.Background(), "failed to validate path, request:", request.URL.Path, ", config:", h.path) writer.WriteHeader(http.StatusNotFound) return } @@ -91,7 +91,7 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req } if sessionId == "" { - newError("no sessionid on request:", request.URL.Path).WriteToLog() + errors.LogInfo(context.Background(), "no sessionid on request:", request.URL.Path) writer.WriteHeader(http.StatusBadRequest) return } @@ -117,21 +117,21 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req } if seq == "" { - newError("no seq on request:", request.URL.Path).WriteToLog() + errors.LogInfo(context.Background(), "no seq on request:", request.URL.Path) writer.WriteHeader(http.StatusBadRequest) return } payload, err := io.ReadAll(request.Body) if err != nil { - newError("failed to upload").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to upload") writer.WriteHeader(http.StatusInternalServerError) return } seqInt, err := strconv.ParseUint(seq, 10, 64) if err != nil { - newError("failed to upload").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to upload") writer.WriteHeader(http.StatusInternalServerError) return } @@ -142,7 +142,7 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req }) if err != nil { - newError("failed to upload").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to upload") writer.WriteHeader(http.StatusInternalServerError) return } @@ -249,9 +249,9 @@ func ListenSH(ctx context.Context, address net.Address, port net.Port, streamSet Net: "unix", }, streamSettings.SocketSettings) if err != nil { - return nil, newError("failed to listen unix domain socket(for SH) on ", address).Base(err) + return nil, errors.New("failed to listen unix domain socket(for SH) on ", address).Base(err) } - newError("listening unix domain socket(for SH) on ", address).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "listening unix domain socket(for SH) on ", address) } else { // tcp localAddr = gonet.TCPAddr{ IP: address.IP(), @@ -262,9 +262,9 @@ func ListenSH(ctx context.Context, address net.Address, port net.Port, streamSet Port: int(port), }, streamSettings.SocketSettings) if err != nil { - return nil, newError("failed to listen TCP(for SH) on ", address, ":", port).Base(err) + return nil, errors.New("failed to listen TCP(for SH) on ", address, ":", port).Base(err) } - newError("listening TCP(for SH) on ", address, ":", port).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "listening TCP(for SH) on ", address, ":", port) } if config := v2tls.ConfigFromStreamSettings(streamSettings); config != nil { @@ -294,7 +294,7 @@ func ListenSH(ctx context.Context, address net.Address, port net.Port, streamSet go func() { if err := l.server.Serve(l.listener); err != nil { - newError("failed to serve http for splithttp").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, err, "failed to serve http for splithttp") } }() diff --git a/transport/internet/splithttp/lazy_reader.go b/transport/internet/splithttp/lazy_reader.go index 5ae4ed55..8641cbac 100644 --- a/transport/internet/splithttp/lazy_reader.go +++ b/transport/internet/splithttp/lazy_reader.go @@ -3,6 +3,8 @@ package splithttp import ( "io" "sync" + + "github.com/xtls/xray-core/common/errors" ) type LazyReader struct { @@ -50,7 +52,7 @@ func (r *LazyReader) Close() error { if r.reader != nil { err = r.reader.Close() r.reader = nil - r.readerError = newError("closed reader") + r.readerError = errors.New("closed reader") } return err diff --git a/transport/internet/splithttp/splithttp.go b/transport/internet/splithttp/splithttp.go index 55d230df..6e458616 100644 --- a/transport/internet/splithttp/splithttp.go +++ b/transport/internet/splithttp/splithttp.go @@ -4,6 +4,7 @@ import ( "context" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" ) //go:generate go run github.com/xtls/xray-core/common/errors/errorgen @@ -12,6 +13,6 @@ const protocolName = "splithttp" func init() { common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { - return nil, newError("splithttp is a transport protocol.") + return nil, errors.New("splithttp is a transport protocol.") })) } diff --git a/transport/internet/splithttp/upload_queue.go b/transport/internet/splithttp/upload_queue.go index 62c69411..4737b811 100644 --- a/transport/internet/splithttp/upload_queue.go +++ b/transport/internet/splithttp/upload_queue.go @@ -6,6 +6,8 @@ package splithttp import ( "container/heap" "io" + + "github.com/xtls/xray-core/common/errors" ) type Packet struct { @@ -33,7 +35,7 @@ func NewUploadQueue(maxPackets int) *UploadQueue { func (h *UploadQueue) Push(p Packet) error { if h.closed { - return newError("splithttp packet queue closed") + return errors.New("splithttp packet queue closed") } h.pushedPackets <- p @@ -84,7 +86,7 @@ func (h *UploadQueue) Read(b []byte) (int, error) { // the "reassembly buffer" is too large, and we want to // constrain memory usage somehow. let's tear down the // connection, and hope the application retries. - return 0, newError("packet queue is too large") + return 0, errors.New("packet queue is too large") } heap.Push(&h.heap, packet) packet2, more := <-h.pushedPackets diff --git a/transport/internet/system_dialer.go b/transport/internet/system_dialer.go index 3c9239e8..73379e41 100644 --- a/transport/internet/system_dialer.go +++ b/transport/internet/system_dialer.go @@ -6,8 +6,8 @@ import ( "time" "github.com/sagernet/sing/common/control" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/features/dns" "github.com/xtls/xray-core/features/outbound" ) @@ -48,7 +48,7 @@ func hasBindAddr(sockopt *SocketConfig) bool { } func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest net.Destination, sockopt *SocketConfig) (net.Conn, error) { - newError("dialing to " + dest.String()).AtDebug().WriteToLog() + errors.LogDebug(ctx, "dialing to " + dest.String()) if dest.Network == net.Network_UDP && !hasBindAddr(sockopt) { srcAddr := resolveSrcAddr(net.Network_UDP, src) @@ -73,7 +73,7 @@ func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest ne } sys.Control(func(fd uintptr) { if err := applyOutboundSocketOptions("udp", dest.NetAddr(), fd, sockopt); err != nil { - newError("failed to apply socket options").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, err, "failed to apply socket options") } }) } @@ -99,17 +99,17 @@ func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest ne dialer.Control = func(network, address string, c syscall.RawConn) error { for _, ctl := range d.controllers { if err := ctl(network, address, c); err != nil { - newError("failed to apply external controller").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to apply external controller") } } return c.Control(func(fd uintptr) { if sockopt != nil { if err := applyOutboundSocketOptions(network, address, fd, sockopt); err != nil { - newError("failed to apply socket options").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to apply socket options") } if dest.Network == net.Network_UDP && hasBindAddr(sockopt) { if err := bindAddr(fd, sockopt.BindAddress, sockopt.BindPort); err != nil { - newError("failed to bind source address to ", sockopt.BindAddress).Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to bind source address to ", sockopt.BindAddress) } } } @@ -210,12 +210,12 @@ func UseAlternativeSystemDialer(dialer SystemDialer) { // xray:api:beta func RegisterDialerController(ctl control.Func) error { if ctl == nil { - return newError("nil listener controller") + return errors.New("nil listener controller") } dialer, ok := effectiveSystemDialer.(*DefaultSystemDialer) if !ok { - return newError("RegisterListenerController not supported in custom dialer") + return errors.New("RegisterListenerController not supported in custom dialer") } dialer.controllers = append(dialer.controllers, ctl) diff --git a/transport/internet/system_listener.go b/transport/internet/system_listener.go index 6593f4bc..ad7ae892 100644 --- a/transport/internet/system_listener.go +++ b/transport/internet/system_listener.go @@ -11,8 +11,8 @@ import ( "github.com/pires/go-proxyproto" "github.com/sagernet/sing/common/control" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" ) var effectiveListener = DefaultListener{} @@ -39,13 +39,13 @@ func getControlFunc(ctx context.Context, sockopt *SocketConfig, controllers []co return c.Control(func(fd uintptr) { for _, controller := range controllers { if err := controller(network, address, c); err != nil { - newError("failed to apply external controller").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to apply external controller") } } if sockopt != nil { if err := applyInboundSocketOptions(network, fd, sockopt); err != nil { - newError("failed to apply socket options to incoming connection").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to apply socket options to incoming connection") } } @@ -95,7 +95,7 @@ func (dl *DefaultListener) Listen(ctx context.Context, addr net.Addr, sockopt *S address = s[0] perm, perr := strconv.ParseUint(s[1], 8, 32) if perr != nil { - return nil, newError("failed to parse permission: " + s[1]).Base(perr) + return nil, errors.New("failed to parse permission: " + s[1]).Base(perr) } mode := os.FileMode(perm) @@ -122,7 +122,7 @@ func (dl *DefaultListener) Listen(ctx context.Context, addr net.Addr, sockopt *S err = os.Chmod(address, *filePerm) if err != nil { l.Close() - return nil, newError("failed to set permission for " + address).Base(err) + return nil, errors.New("failed to set permission for " + address).Base(err) } return l, nil } @@ -152,7 +152,7 @@ func (dl *DefaultListener) ListenPacket(ctx context.Context, addr net.Addr, sock // xray:api:beta func RegisterListenerController(controller control.Func) error { if controller == nil { - return newError("nil listener controller") + return errors.New("nil listener controller") } effectiveListener.controllers = append(effectiveListener.controllers, controller) diff --git a/transport/internet/tagged/taggedimpl/errors.generated.go b/transport/internet/tagged/taggedimpl/errors.generated.go deleted file mode 100644 index 178794cc..00000000 --- a/transport/internet/tagged/taggedimpl/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package taggedimpl - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/tagged/taggedimpl/impl.go b/transport/internet/tagged/taggedimpl/impl.go index 6b66e11f..29caec7c 100644 --- a/transport/internet/tagged/taggedimpl/impl.go +++ b/transport/internet/tagged/taggedimpl/impl.go @@ -3,6 +3,7 @@ package taggedimpl import ( "context" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net/cnc" "github.com/xtls/xray-core/common/session" @@ -14,12 +15,12 @@ import ( func DialTaggedOutbound(ctx context.Context, dest net.Destination, tag string) (net.Conn, error) { var dispatcher routing.Dispatcher if core.FromContext(ctx) == nil { - return nil, newError("Instance context variable is not in context, dial denied. ") + return nil, errors.New("Instance context variable is not in context, dial denied. ") } if err := core.RequireFeatures(ctx, func(dispatcherInstance routing.Dispatcher) { dispatcher = dispatcherInstance }); err != nil { - return nil, newError("Required Feature dispatcher not resolved").Base(err) + return nil, errors.New("Required Feature dispatcher not resolved").Base(err) } content := new(session.Content) diff --git a/transport/internet/tcp/dialer.go b/transport/internet/tcp/dialer.go index 06ee3ecf..bf50ed72 100644 --- a/transport/internet/tcp/dialer.go +++ b/transport/internet/tcp/dialer.go @@ -4,8 +4,8 @@ import ( "context" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/reality" "github.com/xtls/xray-core/transport/internet/stat" @@ -14,7 +14,7 @@ import ( // Dial dials a new TCP connection to the given destination. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) { - newError("dialing TCP to ", dest).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "dialing TCP to ", dest) conn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings) if err != nil { return nil, err @@ -40,11 +40,11 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me if tcpSettings.HeaderSettings != nil { headerConfig, err := tcpSettings.HeaderSettings.GetInstance() if err != nil { - return nil, newError("failed to get header settings").Base(err).AtError() + return nil, errors.New("failed to get header settings").Base(err).AtError() } auth, err := internet.CreateConnectionAuthenticator(headerConfig) if err != nil { - return nil, newError("failed to create header authenticator").Base(err).AtError() + return nil, errors.New("failed to create header authenticator").Base(err).AtError() } conn = auth.Client(conn) } diff --git a/transport/internet/tcp/errors.generated.go b/transport/internet/tcp/errors.generated.go deleted file mode 100644 index 0832d114..00000000 --- a/transport/internet/tcp/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package tcp - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/tcp/hub.go b/transport/internet/tcp/hub.go index d4b4f8b5..84e39163 100644 --- a/transport/internet/tcp/hub.go +++ b/transport/internet/tcp/hub.go @@ -8,8 +8,8 @@ import ( goreality "github.com/xtls/reality" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/reality" "github.com/xtls/xray-core/transport/internet/stat" @@ -47,22 +47,22 @@ func ListenTCP(ctx context.Context, address net.Address, port net.Port, streamSe Net: "unix", }, streamSettings.SocketSettings) if err != nil { - return nil, newError("failed to listen Unix Domain Socket on ", address).Base(err) + return nil, errors.New("failed to listen Unix Domain Socket on ", address).Base(err) } - newError("listening Unix Domain Socket on ", address).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "listening Unix Domain Socket on ", address) } else { listener, err = internet.ListenSystem(ctx, &net.TCPAddr{ IP: address.IP(), Port: int(port), }, streamSettings.SocketSettings) if err != nil { - return nil, newError("failed to listen TCP on ", address, ":", port).Base(err) + return nil, errors.New("failed to listen TCP on ", address, ":", port).Base(err) } - newError("listening TCP on ", address, ":", port).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "listening TCP on ", address, ":", port) } if streamSettings.SocketSettings != nil && streamSettings.SocketSettings.AcceptProxyProtocol { - newError("accepting PROXY protocol").AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarning(ctx, "accepting PROXY protocol") } l.listener = listener @@ -77,11 +77,11 @@ func ListenTCP(ctx context.Context, address net.Address, port net.Port, streamSe if tcpSettings.HeaderSettings != nil { headerConfig, err := tcpSettings.HeaderSettings.GetInstance() if err != nil { - return nil, newError("invalid header settings").Base(err).AtError() + return nil, errors.New("invalid header settings").Base(err).AtError() } auth, err := internet.CreateConnectionAuthenticator(headerConfig) if err != nil { - return nil, newError("invalid header settings.").Base(err).AtError() + return nil, errors.New("invalid header settings.").Base(err).AtError() } l.authConfig = auth } @@ -98,7 +98,7 @@ func (v *Listener) keepAccepting() { if strings.Contains(errStr, "closed") { break } - newError("failed to accepted raw connections").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(context.Background(), err, "failed to accepted raw connections") if strings.Contains(errStr, "too many") { time.Sleep(time.Millisecond * 500) } @@ -109,7 +109,7 @@ func (v *Listener) keepAccepting() { conn = tls.Server(conn, v.tlsConfig) } else if v.realityConfig != nil { if conn, err = reality.Server(conn, v.realityConfig); err != nil { - newError(err).AtInfo().WriteToLog() + errors.LogInfo(context.Background(), err.Error()) return } } diff --git a/transport/internet/tcp/sockopt_darwin.go b/transport/internet/tcp/sockopt_darwin.go index a1905cf4..ec0da29a 100644 --- a/transport/internet/tcp/sockopt_darwin.go +++ b/transport/internet/tcp/sockopt_darwin.go @@ -4,6 +4,7 @@ package tcp import ( + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/stat" @@ -15,11 +16,11 @@ func GetOriginalDestination(conn stat.Connection) (net.Destination, error) { ra := conn.RemoteAddr() ip, port, err := internet.OriginalDst(la, ra) if err != nil { - return net.Destination{}, newError("failed to get destination").Base(err) + return net.Destination{}, errors.New("failed to get destination").Base(err) } dest := net.TCPDestination(net.IPAddress(ip), net.Port(port)) if !dest.IsValid() { - return net.Destination{}, newError("failed to parse destination.") + return net.Destination{}, errors.New("failed to parse destination.") } return dest, nil } diff --git a/transport/internet/tcp/sockopt_freebsd.go b/transport/internet/tcp/sockopt_freebsd.go index 906e06ea..d7ab3ff0 100644 --- a/transport/internet/tcp/sockopt_freebsd.go +++ b/transport/internet/tcp/sockopt_freebsd.go @@ -4,6 +4,7 @@ package tcp import ( + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/stat" @@ -15,11 +16,11 @@ func GetOriginalDestination(conn stat.Connection) (net.Destination, error) { ra := conn.RemoteAddr() ip, port, err := internet.OriginalDst(la, ra) if err != nil { - return net.Destination{}, newError("failed to get destination").Base(err) + return net.Destination{}, errors.New("failed to get destination").Base(err) } dest := net.TCPDestination(net.IPAddress(ip), net.Port(port)) if !dest.IsValid() { - return net.Destination{}, newError("failed to parse destination.") + return net.Destination{}, errors.New("failed to parse destination.") } return dest, nil } diff --git a/transport/internet/tcp/sockopt_linux.go b/transport/internet/tcp/sockopt_linux.go index 86044a80..f5648e8f 100644 --- a/transport/internet/tcp/sockopt_linux.go +++ b/transport/internet/tcp/sockopt_linux.go @@ -4,9 +4,11 @@ package tcp import ( + "context" "syscall" "unsafe" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet/stat" ) @@ -16,11 +18,11 @@ const SO_ORIGINAL_DST = 80 func GetOriginalDestination(conn stat.Connection) (net.Destination, error) { sysrawconn, f := conn.(syscall.Conn) if !f { - return net.Destination{}, newError("unable to get syscall.Conn") + return net.Destination{}, errors.New("unable to get syscall.Conn") } rawConn, err := sysrawconn.SyscallConn() if err != nil { - return net.Destination{}, newError("failed to get sys fd").Base(err) + return net.Destination{}, errors.New("failed to get sys fd").Base(err) } var dest net.Destination err = rawConn.Control(func(fd uintptr) { @@ -30,7 +32,7 @@ func GetOriginalDestination(conn stat.Connection) (net.Destination, error) { } addr, err := syscall.GetsockoptIPv6MTUInfo(int(fd), level, SO_ORIGINAL_DST) if err != nil { - newError("failed to call getsockopt").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to call getsockopt") return } ip := (*[4]byte)(unsafe.Pointer(&addr.Addr.Flowinfo))[:4] @@ -41,10 +43,10 @@ func GetOriginalDestination(conn stat.Connection) (net.Destination, error) { dest = net.TCPDestination(net.IPAddress(ip), net.PortFromBytes(port)) }) if err != nil { - return net.Destination{}, newError("failed to control connection").Base(err) + return net.Destination{}, errors.New("failed to control connection").Base(err) } if !dest.IsValid() { - return net.Destination{}, newError("failed to call getsockopt") + return net.Destination{}, errors.New("failed to call getsockopt") } return dest, nil } diff --git a/transport/internet/tcp_hub.go b/transport/internet/tcp_hub.go index 2ebff9a7..0cdd50d1 100644 --- a/transport/internet/tcp_hub.go +++ b/transport/internet/tcp_hub.go @@ -3,6 +3,7 @@ package internet import ( "context" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet/stat" ) @@ -11,7 +12,7 @@ var transportListenerCache = make(map[string]ListenFunc) func RegisterTransportListener(protocol string, listener ListenFunc) error { if _, found := transportListenerCache[protocol]; found { - return newError(protocol, " listener already registered.").AtError() + return errors.New(protocol, " listener already registered.").AtError() } transportListenerCache[protocol] = listener return nil @@ -31,7 +32,7 @@ func ListenUnix(ctx context.Context, address net.Address, settings *MemoryStream if settings == nil { s, err := ToMemoryStreamConfig(nil) if err != nil { - return nil, newError("failed to create default unix stream settings").Base(err) + return nil, errors.New("failed to create default unix stream settings").Base(err) } settings = s } @@ -39,11 +40,11 @@ func ListenUnix(ctx context.Context, address net.Address, settings *MemoryStream protocol := settings.ProtocolName listenFunc := transportListenerCache[protocol] if listenFunc == nil { - return nil, newError(protocol, " unix istener not registered.").AtError() + return nil, errors.New(protocol, " unix istener not registered.").AtError() } listener, err := listenFunc(ctx, address, net.Port(0), settings, handler) if err != nil { - return nil, newError("failed to listen on unix address: ", address).Base(err) + return nil, errors.New("failed to listen on unix address: ", address).Base(err) } return listener, nil } @@ -52,7 +53,7 @@ func ListenTCP(ctx context.Context, address net.Address, port net.Port, settings if settings == nil { s, err := ToMemoryStreamConfig(nil) if err != nil { - return nil, newError("failed to create default stream settings").Base(err) + return nil, errors.New("failed to create default stream settings").Base(err) } settings = s } @@ -62,17 +63,17 @@ func ListenTCP(ctx context.Context, address net.Address, port net.Port, settings } if address.Family().IsDomain() { - return nil, newError("domain address is not allowed for listening: ", address.Domain()) + return nil, errors.New("domain address is not allowed for listening: ", address.Domain()) } protocol := settings.ProtocolName listenFunc := transportListenerCache[protocol] if listenFunc == nil { - return nil, newError(protocol, " listener not registered.").AtError() + return nil, errors.New(protocol, " listener not registered.").AtError() } listener, err := listenFunc(ctx, address, port, settings, handler) if err != nil { - return nil, newError("failed to listen on address: ", address, ":", port).Base(err) + return nil, errors.New("failed to listen on address: ", address, ":", port).Base(err) } return listener, nil } diff --git a/transport/internet/tls/config.go b/transport/internet/tls/config.go index 9d9289c3..7adb5a84 100644 --- a/transport/internet/tls/config.go +++ b/transport/internet/tls/config.go @@ -1,6 +1,7 @@ package tls import ( + "context" "crypto/hmac" "crypto/tls" "crypto/x509" @@ -10,6 +11,7 @@ import ( "sync" "time" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/ocsp" "github.com/xtls/xray-core/common/platform/filesystem" @@ -35,7 +37,7 @@ func (c *Config) loadSelfCertPool() (*x509.CertPool, error) { root := x509.NewCertPool() for _, cert := range c.Certificate { if !root.AppendCertsFromPEM(cert.Certificate) { - return nil, newError("failed to append cert").AtWarning() + return nil, errors.New("failed to append cert").AtWarning() } } return root, nil @@ -50,12 +52,12 @@ func (c *Config) BuildCertificates() []*tls.Certificate { } keyPair, err := tls.X509KeyPair(entry.Certificate, entry.Key) if err != nil { - newError("ignoring invalid X509 key pair").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(context.Background(), err, "ignoring invalid X509 key pair") continue } keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0]) if err != nil { - newError("ignoring invalid certificate").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(context.Background(), err, "ignoring invalid certificate") continue } certs = append(certs, &keyPair) @@ -73,25 +75,25 @@ func (c *Config) BuildCertificates() []*tls.Certificate { if entry.CertificatePath != "" && entry.KeyPath != "" { newCert, err := filesystem.ReadFile(entry.CertificatePath) if err != nil { - newError("failed to parse certificate").Base(err).AtError().WriteToLog() + errors.LogErrorInner(context.Background(), err, "failed to parse certificate") <-t.C continue } newKey, err := filesystem.ReadFile(entry.KeyPath) if err != nil { - newError("failed to parse key").Base(err).AtError().WriteToLog() + errors.LogErrorInner(context.Background(), err, "failed to parse key") <-t.C continue } if string(newCert) != string(entry.Certificate) && string(newKey) != string(entry.Key) { newKeyPair, err := tls.X509KeyPair(newCert, newKey) if err != nil { - newError("ignoring invalid X509 key pair").Base(err).AtError().WriteToLog() + errors.LogErrorInner(context.Background(), err, "ignoring invalid X509 key pair") <-t.C continue } if newKeyPair.Leaf, err = x509.ParseCertificate(newKeyPair.Certificate[0]); err != nil { - newError("ignoring invalid certificate").Base(err).AtError().WriteToLog() + errors.LogErrorInner(context.Background(), err, "ignoring invalid certificate") <-t.C continue } @@ -100,7 +102,7 @@ func (c *Config) BuildCertificates() []*tls.Certificate { } if isOcspstapling { if newOCSPData, err := ocsp.GetOCSPForCert(cert.Certificate); err != nil { - newError("ignoring invalid OCSP").Base(err).AtWarning().WriteToLog() + errors.LogWarningInner(context.Background(), err, "ignoring invalid OCSP") } else if string(newOCSPData) != string(cert.OCSPStaple) { cert.OCSPStaple = newOCSPData } @@ -128,11 +130,11 @@ func isCertificateExpired(c *tls.Certificate) bool { func issueCertificate(rawCA *Certificate, domain string) (*tls.Certificate, error) { parent, err := cert.ParseCertificate(rawCA.Certificate, rawCA.Key) if err != nil { - return nil, newError("failed to parse raw certificate").Base(err) + return nil, errors.New("failed to parse raw certificate").Base(err) } newCert, err := cert.Generate(parent, cert.CommonName(domain), cert.DNSNames(domain)) if err != nil { - return nil, newError("failed to generate new certificate for ", domain).Base(err) + return nil, errors.New("failed to generate new certificate for ", domain).Base(err) } newCertPEM, newKeyPEM := newCert.ToPEM() cert, err := tls.X509KeyPair(newCertPEM, newKeyPEM) @@ -176,7 +178,7 @@ func getGetCertificateFunc(c *tls.Config, ca []*Certificate) func(hello *tls.Cli newCerts = append(newCerts, certificate) } else if certificate.Leaf != nil { expTime := certificate.Leaf.NotAfter.Format(time.RFC3339) - newError("old certificate for ", domain, " (expire on ", expTime, ") discarded").AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "old certificate for ", domain, " (expire on ", expTime, ") discarded") } } @@ -191,16 +193,16 @@ func getGetCertificateFunc(c *tls.Config, ca []*Certificate) func(hello *tls.Cli if rawCert.Usage == Certificate_AUTHORITY_ISSUE { newCert, err := issueCertificate(rawCert, domain) if err != nil { - newError("failed to issue new certificate for ", domain).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to issue new certificate for ", domain) continue } parsed, err := x509.ParseCertificate(newCert.Certificate[0]) if err == nil { newCert.Leaf = parsed expTime := parsed.NotAfter.Format(time.RFC3339) - newError("new certificate for ", domain, " (expire on ", expTime, ") issued").AtInfo().WriteToLog() + errors.LogInfo(context.Background(), "new certificate for ", domain, " (expire on ", expTime, ") issued") } else { - newError("failed to parse new certificate for ", domain).Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to parse new certificate for ", domain) } access.Lock() @@ -212,7 +214,7 @@ func getGetCertificateFunc(c *tls.Config, ca []*Certificate) func(hello *tls.Cli } if issuedCertificate == nil { - return nil, newError("failed to create a new certificate for ", domain) + return nil, errors.New("failed to create a new certificate for ", domain) } access.Lock() @@ -265,7 +267,7 @@ func (c *Config) verifyPeerCert(rawCerts [][]byte, verifiedChains [][]*x509.Cert return nil } } - return newError("peer cert is unrecognized: ", base64.StdEncoding.EncodeToString(hashValue)) + return errors.New("peer cert is unrecognized: ", base64.StdEncoding.EncodeToString(hashValue)) } if c.PinnedPeerCertificatePublicKeySha256 != nil { @@ -279,7 +281,7 @@ func (c *Config) verifyPeerCert(rawCerts [][]byte, verifiedChains [][]*x509.Cert } } } - return newError("peer public key is unrecognized.") + return errors.New("peer public key is unrecognized.") } return nil } @@ -288,7 +290,7 @@ func (c *Config) verifyPeerCert(rawCerts [][]byte, verifiedChains [][]*x509.Cert func (c *Config) GetTLSConfig(opts ...Option) *tls.Config { root, err := c.getCertPool() if err != nil { - newError("failed to load system root certificate").AtError().Base(err).WriteToLog() + errors.LogErrorInner(context.Background(), err, "failed to load system root certificate") } if c == nil { @@ -366,7 +368,7 @@ func (c *Config) GetTLSConfig(opts ...Option) *tls.Config { if len(c.MasterKeyLog) > 0 && c.MasterKeyLog != "none" { writer, err := os.OpenFile(c.MasterKeyLog, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644) if err != nil { - newError("failed to open ", c.MasterKeyLog, " as master key log").AtError().Base(err).WriteToLog() + errors.LogErrorInner(context.Background(), err, "failed to open ", c.MasterKeyLog, " as master key log") } else { config.KeyLogWriter = writer } diff --git a/transport/internet/tls/config_other.go b/transport/internet/tls/config_other.go index 59e0c153..daaf39c7 100644 --- a/transport/internet/tls/config_other.go +++ b/transport/internet/tls/config_other.go @@ -6,6 +6,8 @@ package tls import ( "crypto/x509" "sync" + + "github.com/xtls/xray-core/common/errors" ) type rootCertsCache struct { @@ -42,11 +44,11 @@ func (c *Config) getCertPool() (*x509.CertPool, error) { pool, err := x509.SystemCertPool() if err != nil { - return nil, newError("system root").AtWarning().Base(err) + return nil, errors.New("system root").AtWarning().Base(err) } for _, cert := range c.Certificate { if !pool.AppendCertsFromPEM(cert.Certificate) { - return nil, newError("append cert to root").AtWarning().Base(err) + return nil, errors.New("append cert to root").AtWarning().Base(err) } } return pool, err diff --git a/transport/internet/tls/errors.generated.go b/transport/internet/tls/errors.generated.go deleted file mode 100644 index ba1851c8..00000000 --- a/transport/internet/tls/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package tls - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/udp/dispatcher.go b/transport/internet/udp/dispatcher.go index 9685213b..e6267d2f 100644 --- a/transport/internet/udp/dispatcher.go +++ b/transport/internet/udp/dispatcher.go @@ -2,16 +2,16 @@ package udp import ( "context" - "errors" + goerrors "errors" "io" "sync" "time" "github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol/udp" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/common/signal" "github.com/xtls/xray-core/common/signal/done" "github.com/xtls/xray-core/features/routing" @@ -59,7 +59,7 @@ func (v *Dispatcher) getInboundRay(ctx context.Context, dest net.Destination) (* return v.conn, nil } - newError("establishing new connection for ", dest).WriteToLog() + errors.LogInfo(ctx, "establishing new connection for ", dest) ctx, cancel := context.WithCancel(ctx) removeRay := func() { @@ -70,7 +70,7 @@ func (v *Dispatcher) getInboundRay(ctx context.Context, dest net.Destination) (* link, err := v.dispatcher.Dispatch(ctx, dest) if err != nil { - return nil, newError("failed to dispatch request to ", dest).Base(err) + return nil, errors.New("failed to dispatch request to ", dest).Base(err) } entry := &connEntry{ @@ -85,17 +85,17 @@ func (v *Dispatcher) getInboundRay(ctx context.Context, dest net.Destination) (* func (v *Dispatcher) Dispatch(ctx context.Context, destination net.Destination, payload *buf.Buffer) { // TODO: Add user to destString - newError("dispatch request to: ", destination).AtDebug().WriteToLog(session.ExportIDToError(ctx)) + errors.LogDebug(ctx, "dispatch request to: ", destination) conn, err := v.getInboundRay(ctx, destination) if err != nil { - newError("failed to get inbound").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to get inbound") return } outputStream := conn.link.Writer if outputStream != nil { if err := outputStream.WriteMultiBuffer(buf.MultiBuffer{payload}); err != nil { - newError("failed to write first UDP payload").Base(err).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfoInner(ctx, err, "failed to write first UDP payload") conn.cancel() return } @@ -122,8 +122,8 @@ func handleInput(ctx context.Context, conn *connEntry, dest net.Destination, cal mb, err := input.ReadMultiBuffer() if err != nil { - if !errors.Is(err, io.EOF) { - newError("failed to handle UDP input").Base(err).WriteToLog(session.ExportIDToError(ctx)) + if !goerrors.Is(err, io.EOF) { + errors.LogInfoInner(ctx, err, "failed to handle UDP input") } return } diff --git a/transport/internet/udp/errors.generated.go b/transport/internet/udp/errors.generated.go deleted file mode 100644 index b1b4aa70..00000000 --- a/transport/internet/udp/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package udp - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/udp/hub.go b/transport/internet/udp/hub.go index d91f5536..c16085d5 100644 --- a/transport/internet/udp/hub.go +++ b/transport/internet/udp/hub.go @@ -4,6 +4,7 @@ import ( "context" "github.com/xtls/xray-core/common/buf" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/protocol/udp" "github.com/xtls/xray-core/transport/internet" @@ -54,7 +55,7 @@ func ListenUDP(ctx context.Context, address net.Address, port net.Port, streamSe if err != nil { return nil, err } - newError("listening UDP on ", address, ":", port).WriteToLog() + errors.LogInfo(ctx, "listening UDP on ", address, ":", port) hub.conn = udpConn.(*net.UDPConn) hub.cache = make(chan *udp.Packet, hub.capacity) @@ -89,7 +90,7 @@ func (h *Hub) start() { n, noob, _, addr, err := ReadUDPMsg(h.conn, rawBytes, oobBytes) if err != nil { - newError("failed to read UDP msg").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to read UDP msg") buffer.Release() break } @@ -107,9 +108,9 @@ func (h *Hub) start() { if h.recvOrigDest && noob > 0 { payload.Target = RetrieveOriginalDest(oobBytes[:noob]) if payload.Target.IsValid() { - newError("UDP original destination: ", payload.Target).AtDebug().WriteToLog() + errors.LogDebug(context.Background(), "UDP original destination: ", payload.Target) } else { - newError("failed to read UDP original destination").WriteToLog() + errors.LogInfo(context.Background(), "failed to read UDP original destination") } } diff --git a/transport/internet/websocket/connection.go b/transport/internet/websocket/connection.go index ca53b619..395c2f01 100644 --- a/transport/internet/websocket/connection.go +++ b/transport/internet/websocket/connection.go @@ -74,15 +74,15 @@ func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error { } func (c *connection) Close() error { - var errors []interface{} + var errs []interface{} if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil { - errors = append(errors, err) + errs = append(errs, err) } if err := c.conn.Close(); err != nil { - errors = append(errors, err) + errs = append(errs, err) } - if len(errors) > 0 { - return newError("failed to close connection").Base(newError(serial.Concat(errors...))) + if len(errs) > 0 { + return errors.New("failed to close connection").Base(errors.New(serial.Concat(errs...))) } return nil } diff --git a/transport/internet/websocket/dialer.go b/transport/internet/websocket/dialer.go index 20161688..7003928b 100644 --- a/transport/internet/websocket/dialer.go +++ b/transport/internet/websocket/dialer.go @@ -12,9 +12,9 @@ import ( "github.com/gorilla/websocket" "github.com/xtls/xray-core/common" + "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/session" "github.com/xtls/xray-core/common/uuid" "github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet/stat" @@ -39,7 +39,7 @@ func init() { if conn, err := upgrader.Upgrade(w, r, nil); err == nil { conns <- conn } else { - newError("Browser dialer http upgrade unexpected error").AtError().WriteToLog() + errors.LogError(context.Background(), "Browser dialer http upgrade unexpected error") } } } else { @@ -51,7 +51,7 @@ func init() { // Dial dials a WebSocket connection to the given destination. func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.MemoryStreamConfig) (stat.Connection, error) { - newError("creating connection to ", dest).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "creating connection to ", dest) var conn net.Conn if streamSettings.ProtocolSettings.(*Config).Ed > 0 { ctx, cancel := context.WithCancel(ctx) @@ -65,7 +65,7 @@ func Dial(ctx context.Context, dest net.Destination, streamSettings *internet.Me } else { var err error if conn, err = dialWebSocket(ctx, dest, streamSettings, nil); err != nil { - return nil, newError("failed to dial WebSocket").Base(err) + return nil, errors.New("failed to dial WebSocket").Base(err) } } return stat.Connection(conn), nil @@ -98,18 +98,18 @@ func dialWebSocket(ctx context.Context, dest net.Destination, streamSettings *in // Like the NetDial in the dialer pconn, err := internet.DialSystem(ctx, dest, streamSettings.SocketSettings) if err != nil { - newError("failed to dial to " + addr).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to dial to " + addr) return nil, err } // TLS and apply the handshake cn := tls.UClient(pconn, tlsConfig, fingerprint).(*tls.UConn) if err := cn.WebsocketHandshakeContext(ctx); err != nil { - newError("failed to dial to " + addr).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to dial to " + addr) return nil, err } if !tlsConfig.InsecureSkipVerify { if err := cn.VerifyHostname(tlsConfig.ServerName); err != nil { - newError("failed to dial to " + addr).Base(err).AtError().WriteToLog() + errors.LogErrorInner(ctx, err, "failed to dial to " + addr) return nil, err } } @@ -143,7 +143,7 @@ func dialWebSocket(ctx context.Context, dest net.Destination, streamSettings *in return nil, err } else if s := string(p); s != "ok" { conn.Close() - return nil, newError(s) + return nil, errors.New(s) } return newConnection(conn, conn.RemoteAddr(), nil), nil } @@ -160,7 +160,7 @@ func dialWebSocket(ctx context.Context, dest net.Destination, streamSettings *in if resp != nil { reason = resp.Status } - return nil, newError("failed to dial to (", uri, "): ", reason).Base(err) + return nil, errors.New("failed to dial to (", uri, "): ", reason).Base(err) } return newConnection(conn, conn.RemoteAddr(), nil), nil @@ -188,7 +188,7 @@ func (d *delayDialConn) Write(b []byte) (int, error) { var err error if d.Conn, err = dialWebSocket(d.ctx, d.dest, d.streamSettings, ed); err != nil { d.Close() - return 0, newError("failed to dial WebSocket").Base(err) + return 0, errors.New("failed to dial WebSocket").Base(err) } d.dialed <- true if ed != nil { diff --git a/transport/internet/websocket/errors.generated.go b/transport/internet/websocket/errors.generated.go deleted file mode 100644 index 2361d0a6..00000000 --- a/transport/internet/websocket/errors.generated.go +++ /dev/null @@ -1,9 +0,0 @@ -package websocket - -import "github.com/xtls/xray-core/common/errors" - -type errPathObjHolder struct{} - -func newError(values ...interface{}) *errors.Error { - return errors.New(values...).WithPathObj(errPathObjHolder{}) -} diff --git a/transport/internet/websocket/hub.go b/transport/internet/websocket/hub.go index 60f07390..2fb893b2 100644 --- a/transport/internet/websocket/hub.go +++ b/transport/internet/websocket/hub.go @@ -13,9 +13,9 @@ import ( "github.com/gorilla/websocket" "github.com/xtls/xray-core/common" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" http_proto "github.com/xtls/xray-core/common/protocol/http" - "github.com/xtls/xray-core/common/session" "github.com/xtls/xray-core/transport/internet" v2tls "github.com/xtls/xray-core/transport/internet/tls" ) @@ -39,12 +39,12 @@ var upgrader = &websocket.Upgrader{ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) { if len(h.host) > 0 && request.Host != h.host { - newError("failed to validate host, request:", request.Host, ", config:", h.host).WriteToLog() + errors.LogInfo(context.Background(), "failed to validate host, request:", request.Host, ", config:", h.host) writer.WriteHeader(http.StatusNotFound) return } if request.URL.Path != h.path { - newError("failed to validate path, request:", request.URL.Path, ", config:", h.path).WriteToLog() + errors.LogInfo(context.Background(), "failed to validate path, request:", request.URL.Path, ", config:", h.path) writer.WriteHeader(http.StatusNotFound) return } @@ -60,7 +60,7 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req conn, err := upgrader.Upgrade(writer, request, responseHeader) if err != nil { - newError("failed to convert to WebSocket connection").Base(err).WriteToLog() + errors.LogInfoInner(context.Background(), err, "failed to convert to WebSocket connection") return } @@ -104,22 +104,22 @@ func ListenWS(ctx context.Context, address net.Address, port net.Port, streamSet Net: "unix", }, streamSettings.SocketSettings) if err != nil { - return nil, newError("failed to listen unix domain socket(for WS) on ", address).Base(err) + return nil, errors.New("failed to listen unix domain socket(for WS) on ", address).Base(err) } - newError("listening unix domain socket(for WS) on ", address).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "listening unix domain socket(for WS) on ", address) } else { // tcp listener, err = internet.ListenSystem(ctx, &net.TCPAddr{ IP: address.IP(), Port: int(port), }, streamSettings.SocketSettings) if err != nil { - return nil, newError("failed to listen TCP(for WS) on ", address, ":", port).Base(err) + return nil, errors.New("failed to listen TCP(for WS) on ", address, ":", port).Base(err) } - newError("listening TCP(for WS) on ", address, ":", port).WriteToLog(session.ExportIDToError(ctx)) + errors.LogInfo(ctx, "listening TCP(for WS) on ", address, ":", port) } if streamSettings.SocketSettings != nil && streamSettings.SocketSettings.AcceptProxyProtocol { - newError("accepting PROXY protocol").AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarning(ctx, "accepting PROXY protocol") } if config := v2tls.ConfigFromStreamSettings(streamSettings); config != nil { @@ -142,7 +142,7 @@ func ListenWS(ctx context.Context, address net.Address, port net.Port, streamSet go func() { if err := l.server.Serve(l.listener); err != nil { - newError("failed to serve http for WebSocket").Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) + errors.LogWarningInner(ctx, err, "failed to serve http for WebSocket") } }()