1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-02 22:21:19 +00:00

session id

This commit is contained in:
Darien Raymond 2018-02-22 15:26:00 +01:00
parent 80a1e73361
commit 6b872c266c
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
19 changed files with 143 additions and 55 deletions

View File

@ -62,7 +62,7 @@ func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destin
go func() { go func() {
domain, err := snifer(ctx, sniferList, outbound) domain, err := snifer(ctx, sniferList, outbound)
if err == nil { if err == nil {
newError("sniffed domain: ", domain).WriteToLog() newError("sniffed domain: ", domain).WithContext(ctx).WriteToLog()
destination.Address = net.ParseAddress(domain) destination.Address = net.ParseAddress(domain)
ctx = proxy.ContextWithTarget(ctx, destination) ctx = proxy.ContextWithTarget(ctx, destination)
} }
@ -107,13 +107,13 @@ func (d *DefaultDispatcher) routedDispatch(ctx context.Context, outbound ray.Out
if d.router != nil { if d.router != nil {
if tag, err := d.router.PickRoute(ctx); err == nil { if tag, err := d.router.PickRoute(ctx); err == nil {
if handler := d.ohm.GetHandler(tag); handler != nil { if handler := d.ohm.GetHandler(tag); handler != nil {
newError("taking detour [", tag, "] for [", destination, "]").WriteToLog() newError("taking detour [", tag, "] for [", destination, "]").WithContext(ctx).WriteToLog()
dispatcher = handler dispatcher = handler
} else { } else {
newError("nonexisting tag: ", tag).AtWarning().WriteToLog() newError("nonexisting tag: ", tag).AtWarning().WithContext(ctx).WriteToLog()
} }
} else { } else {
newError("default route for ", destination).WriteToLog() newError("default route for ", destination).WithContext(ctx).WriteToLog()
} }
} }
dispatcher.Dispatch(ctx, outbound) dispatcher.Dispatch(ctx, outbound)

View File

@ -7,6 +7,8 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"v2ray.com/core/common/session"
"v2ray.com/core" "v2ray.com/core"
"v2ray.com/core/app/proxyman" "v2ray.com/core/app/proxyman"
"v2ray.com/core/common" "v2ray.com/core/common"
@ -41,10 +43,13 @@ type tcpWorker struct {
func (w *tcpWorker) callback(conn internet.Connection) { func (w *tcpWorker) callback(conn internet.Connection) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
sid := session.NewID()
ctx = session.ContextWithID(ctx, sid)
if w.recvOrigDest { if w.recvOrigDest {
dest, err := tcp.GetOriginalDestination(conn) dest, err := tcp.GetOriginalDestination(conn)
if err != nil { if err != nil {
newError("failed to get original destination").Base(err).WriteToLog() newError("failed to get original destination").WithContext(ctx).Base(err).WriteToLog()
} }
if dest.IsValid() { if dest.IsValid() {
ctx = proxy.ContextWithOriginalTarget(ctx, dest) ctx = proxy.ContextWithOriginalTarget(ctx, dest)
@ -59,11 +64,11 @@ func (w *tcpWorker) callback(conn internet.Connection) {
ctx = proxyman.ContextWithProtocolSniffers(ctx, w.sniffers) ctx = proxyman.ContextWithProtocolSniffers(ctx, w.sniffers)
} }
if err := w.proxy.Process(ctx, net.Network_TCP, conn, w.dispatcher); err != nil { if err := w.proxy.Process(ctx, net.Network_TCP, conn, w.dispatcher); err != nil {
newError("connection ends").Base(err).WriteToLog() newError("connection ends").Base(err).WithContext(ctx).WriteToLog()
} }
cancel() cancel()
if err := conn.Close(); err != nil { if err := conn.Close(); err != nil {
newError("failed to close connection").Base(err).WriteToLog() newError("failed to close connection").Base(err).WithContext(ctx).WriteToLog()
} }
} }
@ -220,6 +225,9 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest
if !existing { if !existing {
go func() { go func() {
ctx := context.Background() ctx := context.Background()
sid := session.NewID()
ctx = session.ContextWithID(ctx, sid)
if originalDest.IsValid() { if originalDest.IsValid() {
ctx = proxy.ContextWithOriginalTarget(ctx, originalDest) ctx = proxy.ContextWithOriginalTarget(ctx, originalDest)
} }

View File

@ -149,14 +149,14 @@ func fetchInput(ctx context.Context, s *Session, output buf.Writer) {
defer writer.Close() defer writer.Close()
defer s.Close() defer s.Close()
newError("dispatching request to ", dest).WriteToLog() newError("dispatching request to ", dest).WithContext(ctx).WriteToLog()
data, _ := s.input.ReadTimeout(time.Millisecond * 500) data, _ := s.input.ReadTimeout(time.Millisecond * 500)
if err := writer.WriteMultiBuffer(data); err != nil { if err := writer.WriteMultiBuffer(data); err != nil {
newError("failed to write first payload").Base(err).WriteToLog() newError("failed to write first payload").Base(err).WithContext(ctx).WriteToLog()
return return
} }
if err := buf.Copy(s.input, writer); err != nil { if err := buf.Copy(s.input, writer); err != nil {
newError("failed to fetch all input").Base(err).WriteToLog() newError("failed to fetch all input").Base(err).WithContext(ctx).WriteToLog()
} }
} }
@ -298,7 +298,7 @@ type ServerWorker struct {
func handle(ctx context.Context, s *Session, output buf.Writer) { func handle(ctx context.Context, s *Session, output buf.Writer) {
writer := NewResponseWriter(s.ID, output, s.transferType) writer := NewResponseWriter(s.ID, output, s.transferType)
if err := buf.Copy(s.input, writer); err != nil { if err := buf.Copy(s.input, writer); err != nil {
newError("session ", s.ID, " ends.").Base(err).WriteToLog() newError("session ", s.ID, " ends.").Base(err).WithContext(ctx).WriteToLog()
} }
writer.Close() writer.Close()
s.Close() s.Close()
@ -312,7 +312,7 @@ func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *buf.Bu
} }
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error { func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
newError("received request for ", meta.Target).WriteToLog() newError("received request for ", meta.Target).WithContext(ctx).WriteToLog()
inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target) inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
if err != nil { if err != nil {
if meta.Option.Has(OptionData) { if meta.Option.Has(OptionData) {
@ -397,7 +397,7 @@ func (w *ServerWorker) run(ctx context.Context) {
err := w.handleFrame(ctx, reader) err := w.handleFrame(ctx, reader)
if err != nil { if err != nil {
if errors.Cause(err) != io.EOF { if errors.Cause(err) != io.EOF {
newError("unexpected EOF").Base(err).WriteToLog() newError("unexpected EOF").Base(err).WithContext(ctx).WriteToLog()
input.CloseError() input.CloseError()
} }
return return

View File

@ -78,14 +78,14 @@ func (h *Handler) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) {
if h.mux != nil { if h.mux != nil {
err := h.mux.Dispatch(ctx, outboundRay) err := h.mux.Dispatch(ctx, outboundRay)
if err != nil { if err != nil {
newError("failed to process outbound traffic").Base(err).WriteToLog() newError("failed to process outbound traffic").Base(err).WithContext(ctx).WriteToLog()
outboundRay.OutboundOutput().CloseError() outboundRay.OutboundOutput().CloseError()
} }
} else { } else {
err := h.proxy.Process(ctx, outboundRay, h) err := h.proxy.Process(ctx, outboundRay, h)
// Ensure outbound ray is properly closed. // Ensure outbound ray is properly closed.
if err != nil { if err != nil {
newError("failed to process outbound traffic").Base(err).WriteToLog() newError("failed to process outbound traffic").Base(err).WithContext(ctx).WriteToLog()
outboundRay.OutboundOutput().CloseError() outboundRay.OutboundOutput().CloseError()
} else { } else {
outboundRay.OutboundOutput().Close() outboundRay.OutboundOutput().Close()
@ -101,14 +101,14 @@ func (h *Handler) Dial(ctx context.Context, dest net.Destination) (internet.Conn
tag := h.senderSettings.ProxySettings.Tag tag := h.senderSettings.ProxySettings.Tag
handler := h.outboundManager.GetHandler(tag) handler := h.outboundManager.GetHandler(tag)
if handler != nil { if handler != nil {
newError("proxying to ", tag, " for dest ", dest).AtDebug().WriteToLog() newError("proxying to ", tag, " for dest ", dest).AtDebug().WithContext(ctx).WriteToLog()
ctx = proxy.ContextWithTarget(ctx, dest) ctx = proxy.ContextWithTarget(ctx, dest)
stream := ray.NewRay(ctx) stream := ray.NewRay(ctx)
go handler.Dispatch(ctx, stream) go handler.Dispatch(ctx, stream)
return ray.NewConnection(stream.InboundOutput(), stream.InboundInput()), nil return ray.NewConnection(stream.InboundOutput(), stream.InboundInput()), nil
} }
newError("failed to get outbound handler with tag: ", tag).AtWarning().WriteToLog() newError("failed to get outbound handler with tag: ", tag).AtWarning().WithContext(ctx).WriteToLog()
} }
if h.senderSettings.Via != nil { if h.senderSettings.Via != nil {

View File

@ -2,10 +2,12 @@
package errors package errors
import ( import (
"context"
"strings" "strings"
"v2ray.com/core/common/log" "v2ray.com/core/common/log"
"v2ray.com/core/common/serial" "v2ray.com/core/common/serial"
"v2ray.com/core/common/session"
) )
type hasInnerError interface { type hasInnerError interface {
@ -17,12 +19,17 @@ type hasSeverity interface {
Severity() log.Severity Severity() log.Severity
} }
type hasContext interface {
Context() context.Context
}
// Error is an error object with underlying error. // Error is an error object with underlying error.
type Error struct { type Error struct {
message []interface{} message []interface{}
inner error inner error
severity log.Severity severity log.Severity
path []string path []string
ctx context.Context
} }
// Error implements error.Error(). // Error implements error.Error().
@ -50,6 +57,27 @@ func (v *Error) Base(err error) *Error {
return v return v
} }
func (v *Error) WithContext(ctx context.Context) *Error {
v.ctx = ctx
return v
}
func (v *Error) Context() context.Context {
if v.ctx != nil {
return v.ctx
}
if v.inner == nil {
return nil
}
if c, ok := v.inner.(hasContext); ok {
return c.Context()
}
return nil
}
func (v *Error) atSeverity(s log.Severity) *Error { func (v *Error) atSeverity(s log.Severity) *Error {
v.severity = s v.severity = s
return v return v
@ -103,9 +131,21 @@ func (v *Error) String() string {
// WriteToLog writes current error into log. // WriteToLog writes current error into log.
func (v *Error) WriteToLog() { func (v *Error) WriteToLog() {
ctx := v.Context()
var sid session.ID
if ctx != nil {
sid = session.IDFromContext(ctx)
}
var c interface{} = v
if sid > 0 {
c = sessionLog{
id: sid,
content: v,
}
}
log.Record(&log.GeneralMessage{ log.Record(&log.GeneralMessage{
Severity: GetSeverity(v), Severity: GetSeverity(v),
Content: v, Content: c,
}) })
} }
@ -139,3 +179,12 @@ func GetSeverity(err error) log.Severity {
} }
return log.Severity_Info return log.Severity_Info
} }
type sessionLog struct {
id session.ID
content interface{}
}
func (s sessionLog) String() string {
return serial.Concat("[", s.id, "] ", s.content)
}

34
common/session/session.go Normal file
View File

@ -0,0 +1,34 @@
package session
import (
"context"
"math/rand"
)
type ID uint32
func NewID() ID {
for {
id := ID(rand.Uint32())
if id != 0 {
return id
}
}
}
type sessionKey int
const (
idSessionKey sessionKey = iota
)
func ContextWithID(ctx context.Context, id ID) context.Context {
return context.WithValue(ctx, idSessionKey, id)
}
func IDFromContext(ctx context.Context) ID {
if id, ok := ctx.Value(idSessionKey).(ID); ok {
return id
}
return 0
}

View File

@ -53,7 +53,7 @@ func (d *DokodemoDoor) policy() core.Policy {
} }
func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher core.Dispatcher) error { func (d *DokodemoDoor) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher core.Dispatcher) error {
newError("processing connection from: ", conn.RemoteAddr()).AtDebug().WriteToLog() newError("processing connection from: ", conn.RemoteAddr()).AtDebug().WithContext(ctx).WriteToLog()
dest := net.Destination{ dest := net.Destination{
Network: network, Network: network,
Address: d.address, Address: d.address,

View File

@ -56,7 +56,7 @@ func (h *Handler) resolveIP(ctx context.Context, domain string) net.Address {
ips, err := h.dns.LookupIP(domain) ips, err := h.dns.LookupIP(domain)
if err != nil { if err != nil {
newError("failed to get IP address for domain ", domain).Base(err).WriteToLog() newError("failed to get IP address for domain ", domain).Base(err).WithContext(ctx).WriteToLog()
} }
if len(ips) == 0 { if len(ips) == 0 {
return nil return nil
@ -75,7 +75,7 @@ func (h *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay, dial
Port: net.Port(server.Port), Port: net.Port(server.Port),
} }
} }
newError("opening connection to ", destination).WriteToLog() newError("opening connection to ", destination).WithContext(ctx).WriteToLog()
input := outboundRay.OutboundInput() input := outboundRay.OutboundInput()
output := outboundRay.OutboundOutput() output := outboundRay.OutboundOutput()
@ -88,7 +88,7 @@ func (h *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay, dial
Address: ip, Address: ip,
Port: destination.Port, Port: destination.Port,
} }
newError("changing destination to ", destination).WriteToLog() newError("changing destination to ", destination).WithContext(ctx).WriteToLog()
} }
} }

View File

@ -121,7 +121,7 @@ Start:
} }
} }
newError("request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]").WriteToLog() newError("request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]").WithContext(ctx).WriteToLog()
conn.SetReadDeadline(time.Time{}) conn.SetReadDeadline(time.Time{})
defaultPort := net.Port(80) defaultPort := net.Port(80)
@ -276,7 +276,7 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri
result = nil result = nil
} }
} else { } else {
newError("failed to read response from ", request.Host).Base(err).AtWarning().WriteToLog() newError("failed to read response from ", request.Host).Base(err).AtWarning().WithContext(ctx).WriteToLog()
response = &http.Response{ response = &http.Response{
Status: "Service Unavailable", Status: "Service Unavailable",
StatusCode: 503, StatusCode: 503,

View File

@ -80,7 +80,7 @@ func (s *Server) handlerUDPPayload(ctx context.Context, conn internet.Connection
request, data, err := DecodeUDPPacket(s.user, payload) request, data, err := DecodeUDPPacket(s.user, payload)
if err != nil { if err != nil {
if source, ok := proxy.SourceFromContext(ctx); ok { if source, ok := proxy.SourceFromContext(ctx); ok {
newError("dropping invalid UDP packet from: ", source).Base(err).WriteToLog() newError("dropping invalid UDP packet from: ", source).Base(err).WithContext(ctx).WriteToLog()
log.Record(&log.AccessMessage{ log.Record(&log.AccessMessage{
From: source, From: source,
To: "", To: "",
@ -93,13 +93,13 @@ func (s *Server) handlerUDPPayload(ctx context.Context, conn internet.Connection
} }
if request.Option.Has(RequestOptionOneTimeAuth) && s.account.OneTimeAuth == Account_Disabled { if request.Option.Has(RequestOptionOneTimeAuth) && s.account.OneTimeAuth == Account_Disabled {
newError("client payload enables OTA but server doesn't allow it").WriteToLog() newError("client payload enables OTA but server doesn't allow it").WithContext(ctx).WriteToLog()
payload.Release() payload.Release()
continue continue
} }
if !request.Option.Has(RequestOptionOneTimeAuth) && s.account.OneTimeAuth == Account_Enabled { if !request.Option.Has(RequestOptionOneTimeAuth) && s.account.OneTimeAuth == Account_Enabled {
newError("client payload disables OTA but server forces it").WriteToLog() newError("client payload disables OTA but server forces it").WithContext(ctx).WriteToLog()
payload.Release() payload.Release()
continue continue
} }
@ -113,7 +113,7 @@ func (s *Server) handlerUDPPayload(ctx context.Context, conn internet.Connection
Reason: "", Reason: "",
}) })
} }
newError("tunnelling request to ", dest).WriteToLog() newError("tunnelling request to ", dest).WithContext(ctx).WriteToLog()
ctx = protocol.ContextWithUser(ctx, request.User) ctx = protocol.ContextWithUser(ctx, request.User)
udpServer.Dispatch(ctx, dest, data, func(payload *buf.Buffer) { udpServer.Dispatch(ctx, dest, data, func(payload *buf.Buffer) {
@ -121,7 +121,7 @@ func (s *Server) handlerUDPPayload(ctx context.Context, conn internet.Connection
data, err := EncodeUDPPacket(request, payload.Bytes()) data, err := EncodeUDPPacket(request, payload.Bytes())
if err != nil { if err != nil {
newError("failed to encode UDP packet").Base(err).AtWarning().WriteToLog() newError("failed to encode UDP packet").Base(err).AtWarning().WithContext(ctx).WriteToLog()
return return
} }
defer data.Release() defer data.Release()
@ -159,7 +159,7 @@ func (s *Server) handleConnection(ctx context.Context, conn internet.Connection,
Status: log.AccessAccepted, Status: log.AccessAccepted,
Reason: "", Reason: "",
}) })
newError("tunnelling request to ", dest).WriteToLog() newError("tunnelling request to ", dest).WithContext(ctx).WriteToLog()
ctx = protocol.ContextWithUser(ctx, request.User) ctx = protocol.ContextWithUser(ctx, request.User)

View File

@ -86,7 +86,7 @@ func (c *Client) Process(ctx context.Context, ray ray.OutboundRay, dialer proxy.
} }
if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil { if err := conn.SetDeadline(time.Now().Add(p.Timeouts.Handshake)); err != nil {
newError("failed to set deadline for handshake").Base(err).WriteToLog() newError("failed to set deadline for handshake").Base(err).WithContext(ctx).WriteToLog()
} }
udpRequest, err := ClientHandshake(request, conn, conn) udpRequest, err := ClientHandshake(request, conn, conn)
if err != nil { if err != nil {
@ -94,7 +94,7 @@ func (c *Client) Process(ctx context.Context, ray ray.OutboundRay, dialer proxy.
} }
if err := conn.SetDeadline(time.Time{}); err != nil { if err := conn.SetDeadline(time.Time{}); err != nil {
newError("failed to clear deadline after handshake").Base(err).WriteToLog() newError("failed to clear deadline after handshake").Base(err).WithContext(ctx).WriteToLog()
} }
ctx, cancel := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctx)

View File

@ -91,7 +91,7 @@ func (s *Server) processTCP(ctx context.Context, conn internet.Connection, dispa
if request.Command == protocol.RequestCommandTCP { if request.Command == protocol.RequestCommandTCP {
dest := request.Destination() dest := request.Destination()
newError("TCP Connect request to ", dest).WriteToLog() newError("TCP Connect request to ", dest).WithContext(ctx).WriteToLog()
if source, ok := proxy.SourceFromContext(ctx); ok { if source, ok := proxy.SourceFromContext(ctx); ok {
log.Record(&log.AccessMessage{ log.Record(&log.AccessMessage{
From: source, From: source,
@ -163,7 +163,7 @@ func (v *Server) handleUDPPayload(ctx context.Context, conn internet.Connection,
udpServer := udp.NewDispatcher(dispatcher) udpServer := udp.NewDispatcher(dispatcher)
if source, ok := proxy.SourceFromContext(ctx); ok { if source, ok := proxy.SourceFromContext(ctx); ok {
newError("client UDP connection from ", source).WriteToLog() newError("client UDP connection from ", source).WithContext(ctx).WriteToLog()
} }
reader := buf.NewReader(conn) reader := buf.NewReader(conn)
@ -177,7 +177,7 @@ func (v *Server) handleUDPPayload(ctx context.Context, conn internet.Connection,
request, data, err := DecodeUDPPacket(payload.Bytes()) request, data, err := DecodeUDPPacket(payload.Bytes())
if err != nil { if err != nil {
newError("failed to parse UDP request").Base(err).WriteToLog() newError("failed to parse UDP request").Base(err).WithContext(ctx).WriteToLog()
continue continue
} }
@ -185,7 +185,7 @@ func (v *Server) handleUDPPayload(ctx context.Context, conn internet.Connection,
continue continue
} }
newError("send packet to ", request.Destination(), " with ", len(data), " bytes").AtDebug().WriteToLog() newError("send packet to ", request.Destination(), " with ", len(data), " bytes").AtDebug().WithContext(ctx).WriteToLog()
if source, ok := proxy.SourceFromContext(ctx); ok { if source, ok := proxy.SourceFromContext(ctx); ok {
log.Record(&log.AccessMessage{ log.Record(&log.AccessMessage{
From: source, From: source,
@ -200,12 +200,12 @@ func (v *Server) handleUDPPayload(ctx context.Context, conn internet.Connection,
udpServer.Dispatch(ctx, request.Destination(), dataBuf, func(payload *buf.Buffer) { udpServer.Dispatch(ctx, request.Destination(), dataBuf, func(payload *buf.Buffer) {
defer payload.Release() defer payload.Release()
newError("writing back UDP response with ", payload.Len(), " bytes").AtDebug().WriteToLog() newError("writing back UDP response with ", payload.Len(), " bytes").AtDebug().WithContext(ctx).WriteToLog()
udpMessage, err := EncodeUDPPacket(request, payload.Bytes()) udpMessage, err := EncodeUDPPacket(request, payload.Bytes())
defer udpMessage.Release() defer udpMessage.Release()
if err != nil { if err != nil {
newError("failed to write UDP response").AtWarning().Base(err).WriteToLog() newError("failed to write UDP response").AtWarning().Base(err).WithContext(ctx).WriteToLog()
} }
conn.Write(udpMessage.Bytes()) conn.Write(udpMessage.Bytes())

View File

@ -63,8 +63,7 @@ func (c *ClientSession) EncodeRequestHeader(header *protocol.RequestHeader, writ
timestamp := protocol.NewTimestampGenerator(protocol.NowTime(), 30)() timestamp := protocol.NewTimestampGenerator(protocol.NowTime(), 30)()
account, err := header.User.GetTypedAccount() account, err := header.User.GetTypedAccount()
if err != nil { if err != nil {
newError("failed to get user account: ", err).AtError().WriteToLog() return newError("failed to get user account: ", err).AtError()
return nil
} }
idHash := c.idHash(account.(*vmess.InternalAccount).AnyValidID().Bytes()) idHash := c.idHash(account.(*vmess.InternalAccount).AnyValidID().Bytes())
common.Must2(idHash.Write(timestamp.Bytes(nil))) common.Must2(idHash.Write(timestamp.Bytes(nil)))
@ -200,8 +199,7 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon
defer buffer.Release() defer buffer.Release()
if err := buffer.AppendSupplier(buf.ReadFullFrom(c.responseReader, 4)); err != nil { if err := buffer.AppendSupplier(buf.ReadFullFrom(c.responseReader, 4)); err != nil {
newError("failed to read response header").Base(err).WriteToLog() return nil, newError("failed to read response header").Base(err)
return nil, err
} }
if buffer.Byte(0) != c.responseHeader { if buffer.Byte(0) != c.responseHeader {
@ -217,8 +215,7 @@ func (c *ClientSession) DecodeResponseHeader(reader io.Reader) (*protocol.Respon
dataLen := int(buffer.Byte(3)) dataLen := int(buffer.Byte(3))
if err := buffer.Reset(buf.ReadFullFrom(c.responseReader, dataLen)); err != nil { if err := buffer.Reset(buf.ReadFullFrom(c.responseReader, dataLen)); err != nil {
newError("failed to read response command").Base(err).WriteToLog() return nil, newError("failed to read response command").Base(err)
return nil, err
} }
command, err := UnmarshalCommand(cmdID, buffer.Bytes()) command, err := UnmarshalCommand(cmdID, buffer.Bytes())
if err == nil { if err == nil {

View File

@ -242,10 +242,10 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection i
Reason: "", Reason: "",
}) })
newError("received request for ", request.Destination()).WriteToLog() newError("received request for ", request.Destination()).WithContext(ctx).WriteToLog()
if err := connection.SetReadDeadline(time.Time{}); err != nil { if err := connection.SetReadDeadline(time.Time{}); err != nil {
newError("unable to set back read deadline").Base(err).WriteToLog() newError("unable to set back read deadline").Base(err).WithContext(ctx).WriteToLog()
} }
sessionPolicy = h.policyManager.ForLevel(request.User.Level) sessionPolicy = h.policyManager.ForLevel(request.User.Level)
@ -292,7 +292,7 @@ func (h *Handler) generateCommand(ctx context.Context, request *protocol.Request
if h.inboundHandlerManager != nil { if h.inboundHandlerManager != nil {
handler, err := h.inboundHandlerManager.GetHandler(ctx, tag) handler, err := h.inboundHandlerManager.GetHandler(ctx, tag)
if err != nil { if err != nil {
newError("failed to get detour handler: ", tag).Base(err).AtWarning().WriteToLog() newError("failed to get detour handler: ", tag).Base(err).AtWarning().WithContext(ctx).WriteToLog()
return nil return nil
} }
proxyHandler, port, availableMin := handler.GetRandomInboundProxy() proxyHandler, port, availableMin := handler.GetRandomInboundProxy()
@ -302,7 +302,7 @@ func (h *Handler) generateCommand(ctx context.Context, request *protocol.Request
availableMin = 255 availableMin = 255
} }
newError("pick detour handler for port ", port, " for ", availableMin, " minutes.").AtDebug().WriteToLog() newError("pick detour handler for port ", port, " for ", availableMin, " minutes.").AtDebug().WithContext(ctx).WriteToLog()
user := inboundHandler.GetUser(request.User.Email) user := inboundHandler.GetUser(request.User.Email)
if user == nil { if user == nil {
return nil return nil

View File

@ -65,7 +65,7 @@ func (v *Handler) Process(ctx context.Context, outboundRay ray.OutboundRay, dial
if !ok { if !ok {
return newError("target not specified").AtError() return newError("target not specified").AtError()
} }
newError("tunneling request to ", target, " via ", rec.Destination()).WriteToLog() newError("tunneling request to ", target, " via ", rec.Destination()).WithContext(ctx).WriteToLog()
command := protocol.RequestCommandTCP command := protocol.RequestCommandTCP
if target.Network == net.Network_UDP { if target.Network == net.Network_UDP {

View File

@ -19,7 +19,7 @@ func getTCPSettingsFromContext(ctx context.Context) *Config {
// Dial dials a new TCP connection to the given destination. // Dial dials a new TCP connection to the given destination.
func Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) { func Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) {
newError("dialing TCP to ", dest).WriteToLog() newError("dialing TCP to ", dest).WithContext(ctx).WriteToLog()
src := internet.DialerSourceFromContext(ctx) src := internet.DialerSourceFromContext(ctx)
conn, err := internet.DialSystem(ctx, src, dest) conn, err := internet.DialSystem(ctx, src, dest)

View File

@ -29,7 +29,7 @@ func ListenTCP(ctx context.Context, address net.Address, port net.Port, handler
if err != nil { if err != nil {
return nil, err return nil, err
} }
newError("listening TCP on ", address, ":", port).WriteToLog() newError("listening TCP on ", address, ":", port).WithContext(ctx).WriteToLog()
networkSettings := internet.TransportSettingsFromContext(ctx) networkSettings := internet.TransportSettingsFromContext(ctx)
tcpSettings := networkSettings.(*Config) tcpSettings := networkSettings.(*Config)

View File

@ -72,13 +72,13 @@ func (v *Dispatcher) getInboundRay(dest net.Destination, callback ResponseCallba
func (v *Dispatcher) Dispatch(ctx context.Context, destination net.Destination, payload *buf.Buffer, callback ResponseCallback) { func (v *Dispatcher) Dispatch(ctx context.Context, destination net.Destination, payload *buf.Buffer, callback ResponseCallback) {
// TODO: Add user to destString // TODO: Add user to destString
newError("dispatch request to: ", destination).AtDebug().WriteToLog() newError("dispatch request to: ", destination).AtDebug().WithContext(ctx).WriteToLog()
conn := v.getInboundRay(destination, callback) conn := v.getInboundRay(destination, callback)
outputStream := conn.inbound.InboundInput() outputStream := conn.inbound.InboundInput()
if outputStream != nil { if outputStream != nil {
if err := outputStream.WriteMultiBuffer(buf.NewMultiBufferValue(payload)); err != nil { if err := outputStream.WriteMultiBuffer(buf.NewMultiBufferValue(payload)); err != nil {
newError("failed to write first UDP payload").Base(err).WriteToLog() newError("failed to write first UDP payload").Base(err).WithContext(ctx).WriteToLog()
conn.cancel() conn.cancel()
return return
} }
@ -98,7 +98,7 @@ func handleInput(ctx context.Context, conn *connEntry, callback ResponseCallback
mb, err := input.ReadMultiBuffer() mb, err := input.ReadMultiBuffer()
if err != nil { if err != nil {
newError("failed to handle UDP input").Base(err).WriteToLog() newError("failed to handle UDP input").Base(err).WithContext(ctx).WriteToLog()
conn.cancel() conn.cancel()
return return
} }

View File

@ -13,7 +13,7 @@ import (
// Dial dials a WebSocket connection to the given destination. // Dial dials a WebSocket connection to the given destination.
func Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) { func Dial(ctx context.Context, dest net.Destination) (internet.Connection, error) {
newError("creating connection to ", dest).WriteToLog() newError("creating connection to ", dest).WithContext(ctx).WriteToLog()
conn, err := dialWebsocket(ctx, dest) conn, err := dialWebsocket(ctx, dest)
if err != nil { if err != nil {