0
mirror of https://github.com/XTLS/Xray-core.git synced 2025-06-12 19:39:35 +03:00

Refactor log (#3446)

* Refactor log

* Add new log methods

* Fix logger test

* Change all logging code

* Clean up pathObj

* Rebase to latest main

* Remove invoking method name after the dot
This commit is contained in:
yuhan6665
2024-06-29 14:32:57 -04:00
committed by GitHub
parent 8320732743
commit 079d0bd8a9
291 changed files with 1837 additions and 2368 deletions

View File

@ -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
}

View File

@ -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")
}
}

View File

@ -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

View File

@ -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 {

View File

@ -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{})
}

View File

@ -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)
}
}

View File

@ -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{})
}

View File

@ -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)
}
}

View File

@ -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)

View File

@ -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{})
}

View File

@ -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
}

View File

@ -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

View File

@ -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{})
}

View File

@ -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")
}
}()

View File

@ -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")
}

View File

@ -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{})
}

View File

@ -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 {

View File

@ -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
}

View File

@ -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{})
}

View File

@ -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")
}
}
}()

View File

@ -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
}

View File

@ -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{})
}

View File

@ -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.")
}))
}

View File

@ -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 {

View File

@ -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 {

View File

@ -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

View File

@ -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,

View File

@ -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{})
}

View File

@ -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
}

View File

@ -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) {

View File

@ -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 {

View File

@ -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{})
}

View File

@ -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)

View File

@ -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

View File

@ -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{})
}

View File

@ -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 {

View File

@ -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
}

View File

@ -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

View File

@ -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
}

View File

@ -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)
}
}
}

View File

@ -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
},

View File

@ -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{})
}

View File

@ -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")
}
}()

View File

@ -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

View File

@ -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.")
}))
}

View File

@ -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

View File

@ -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)

View File

@ -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)

View File

@ -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{})
}

View File

@ -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)

View File

@ -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)
}

View File

@ -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{})
}

View File

@ -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
}
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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

View File

@ -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{})
}

View File

@ -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
}

View File

@ -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{})
}

View File

@ -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")
}
}

View File

@ -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
}

View File

@ -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 {

View File

@ -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{})
}

View File

@ -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")
}
}()