Compare commits

..
1 Commits
Author SHA1 Message Date
Fangliding 59b0255d83 Treat int as int32 2026-10-15 00:53:10 +08:00
10 changed files with 48 additions and 61 deletions
+1 -1
View File
@@ -109,7 +109,7 @@ func (h *HealthPingRTTS) getStatistics() *HealthPingStats {
stats.Min = 0 stats.Min = 0
return stats return stats
} }
stats.Average = time.Duration(int(sum) / cnt) stats.Average = sum / time.Duration(cnt)
var std float64 var std float64
if cnt < 2 { if cnt < 2 {
// no enough data for standard deviation, we assume it's half of the average rtt // no enough data for standard deviation, we assume it's half of the average rtt
+5 -11
View File
@@ -169,17 +169,11 @@ func (i *Inbound) processUDP(ctx context.Context, conn stat.Connection, dispatch
} }
sessionItem.Unlock() sessionItem.Unlock()
} }
link := sessionItem.link.Load() link, err := sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(dest net.Destination, payload []byte) ([]byte, error) {
if link != nil { return i.udpCodec.EncodeServerPacket(decoded.SessionID, dest, payload)
sessionItem.UpdateConn(conn) })
} else { if err != nil {
var err error continue
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(dest net.Destination, payload []byte) ([]byte, error) {
return i.udpCodec.EncodeServerPacket(decoded.SessionID, dest, payload)
})
if err != nil {
continue
}
} }
payloadBuf := buf.New() payloadBuf := buf.New()
+5 -11
View File
@@ -336,17 +336,11 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
} }
sessionItem.Unlock() sessionItem.Unlock()
link := sessionItem.link.Load() link, err := sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
if link != nil { return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
sessionItem.UpdateConn(conn) })
} else { if err != nil {
var err error continue
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
})
if err != nil {
continue
}
} }
pBuf := buf.New() pBuf := buf.New()
+4 -10
View File
@@ -253,16 +253,10 @@ func (i *RelayInbound) processUDP(ctx context.Context, conn stat.Connection, dis
} }
sessionItem.Unlock() sessionItem.Unlock()
} }
link := sessionItem.link.Load() link, err := sessionItem.EnsureLink(ctx, conn, dest, dispatcher, i.policyManager, nil)
if link != nil { if err != nil {
sessionItem.UpdateConn(conn) b.Release()
} else { continue
var err error
link, err = sessionItem.EnsureLink(ctx, conn, dest, dispatcher, i.policyManager, nil)
if err != nil {
b.Release()
continue
}
} }
_ = link.Writer.WriteMultiBuffer(buf.MultiBuffer{b}) _ = link.Writer.WriteMultiBuffer(buf.MultiBuffer{b})
+4 -4
View File
@@ -169,8 +169,8 @@ func (o *Outbound) Process(ctx context.Context, link *transport.Link, dialer int
return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer)) return buf.Copy(responseReader, link.Writer, buf.UpdateActivity(timer))
} }
responseDonePost := task.OnSuccess(responseDone, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDonePost); err != nil { if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return errors.New("connection ends").Base(err) return errors.New("connection ends").Base(err)
} }
@@ -212,8 +212,8 @@ func (o *Outbound) Process(ctx context.Context, link *transport.Link, dialer int
return nil return nil
} }
responseDonePost := task.OnSuccess(responseDone, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDone, responseDonePost); err != nil { if err := task.Run(ctx, requestDone, responseDoneAndCloseWriter); err != nil {
return errors.New("connection ends").Base(err) return errors.New("connection ends").Base(err)
} }
+1 -1
View File
@@ -153,7 +153,7 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
return DecodedUDPPacket{}, ErrBadHeaderType return DecodedUDPPacket{}, ErrBadHeaderType
} }
epoch := binary.BigEndian.Uint64(bodyPlain[1:9]) epoch := binary.BigEndian.Uint64(bodyPlain[1:9])
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch)))) diff := math.Abs(float64(time.Now().Unix() - int64(epoch)))
if diff > 30 { if diff > 30 {
return DecodedUDPPacket{}, ErrBadTimestamp return DecodedUDPPacket{}, ErrBadTimestamp
} }
+2 -2
View File
@@ -49,12 +49,12 @@ func (f *SlidingWindow) Add(counter uint64) {
if counter > f.last { if counter > f.last {
lastBlockIndex := f.last >> swBlockBitLog lastBlockIndex := f.last >> swBlockBitLog
diff := int(blockIndex - lastBlockIndex) diff := blockIndex - lastBlockIndex
if diff > swRingBlocks { if diff > swRingBlocks {
diff = swRingBlocks diff = swRingBlocks
} }
for i := 0; i < diff; i++ { for i := 0; i < int(diff); i++ {
lastBlockIndex = (lastBlockIndex + 1) & swBlockMask lastBlockIndex = (lastBlockIndex + 1) & swBlockMask
f.ring[lastBlockIndex] = 0 f.ring[lastBlockIndex] = 0
} }
+21 -8
View File
@@ -18,8 +18,12 @@ import (
) )
func (s *ServerUDPSession) UpdateConn(conn stat.Connection) { func (s *ServerUDPSession) UpdateConn(conn stat.Connection) {
s.currentConn.Store(conn) if s.currentConn.Load() == nil {
s.timer.Update() s.currentConn.Store(conn)
}
if s.timer != nil {
s.timer.Update()
}
} }
func (s *ServerUDPSession) WriteToClient(b []byte) error { func (s *ServerUDPSession) WriteToClient(b []byte) error {
@@ -53,16 +57,19 @@ func (s *ServerUDPSession) EnsureLink(
policyManager policy.Manager, policyManager policy.Manager,
responseEncoder func(dest net.Destination, payload []byte) ([]byte, error), responseEncoder func(dest net.Destination, payload []byte) ([]byte, error),
) (*transport.Link, error) { ) (*transport.Link, error) {
s.UpdateConn(conn)
if link := s.link.Load(); link != nil {
return link, nil
}
s.Lock() s.Lock()
defer s.Unlock() defer s.Unlock()
if link := s.link.Load(); link != nil { if link := s.link.Load(); link != nil {
s.UpdateConn(conn)
return link, nil return link, nil
} }
s.currentConn.Store(conn)
sessCtx, cancel := context.WithCancel(ctx) sessCtx, cancel := context.WithCancel(ctx)
inbound := session.InboundFromContext(sessCtx) inbound := session.InboundFromContext(sessCtx)
if inbound != nil && s.User != nil { if inbound != nil && s.User != nil {
@@ -87,6 +94,7 @@ func (s *ServerUDPSession) EnsureLink(
return nil, err return nil, err
} }
s.link.Store(link)
sessionPolicy := policyManager.ForLevel(level) sessionPolicy := policyManager.ForLevel(level)
s.timer = signal.CancelAfterInactivity(sessCtx, func() { s.timer = signal.CancelAfterInactivity(sessCtx, func() {
if s.manager != nil { if s.manager != nil {
@@ -95,7 +103,6 @@ func (s *ServerUDPSession) EnsureLink(
s.Close() s.Close()
cancel() cancel()
}, sessionPolicy.Timeouts.ConnectionIdle) }, sessionPolicy.Timeouts.ConnectionIdle)
s.link.Store(link)
go handleUDPResponse(s, link, dest, responseEncoder) go handleUDPResponse(s, link, dest, responseEncoder)
return link, nil return link, nil
@@ -111,13 +118,19 @@ func ResetTCPConn(conn net.Conn) {
} }
func handleUDPResponse(s *ServerUDPSession, link *transport.Link, fallbackDest net.Destination, encode func(dest net.Destination, payload []byte) ([]byte, error)) { func handleUDPResponse(s *ServerUDPSession, link *transport.Link, fallbackDest net.Destination, encode func(dest net.Destination, payload []byte) ([]byte, error)) {
defer s.timer.SetTimeout(0) defer func() {
if s.timer != nil {
s.timer.SetTimeout(0)
}
}()
for { for {
resMb, err := link.Reader.ReadMultiBuffer() resMb, err := link.Reader.ReadMultiBuffer()
if err != nil { if err != nil {
return return
} }
s.timer.Update() if s.timer != nil {
s.timer.Update()
}
for i, rb := range resMb { for i, rb := range resMb {
b := rb.Bytes() b := rb.Bytes()
if encode != nil { if encode != nil {
+4 -12
View File
@@ -11,7 +11,6 @@ import (
"sync" "sync"
"time" "time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/antireplay" "github.com/xtls/xray-core/common/antireplay"
"github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
@@ -254,7 +253,7 @@ func ReadClientRequestHeaderWithFixed(reader *StreamReader, fixedChunk []byte) (
} }
epoch := binary.BigEndian.Uint64(plainFixed[1:9]) epoch := binary.BigEndian.Uint64(plainFixed[1:9])
diff := int(math.Abs(float64(time.Now().Unix() - int64(epoch)))) diff := math.Abs(float64(time.Now().Unix() - int64(epoch)))
if diff > 30 { if diff > 30 {
return nil, ErrBadTimestamp return nil, ErrBadTimestamp
} }
@@ -431,7 +430,7 @@ func ReadTCPResponse(r io.Reader, method *CipherMethod, psk []byte, clientSalt [
} }
serverEpoch := binary.BigEndian.Uint64(decryptedFixed[1:9]) serverEpoch := binary.BigEndian.Uint64(decryptedFixed[1:9])
diff := int(math.Abs(float64(time.Now().Unix() - int64(serverEpoch)))) diff := math.Abs(float64(time.Now().Unix() - int64(serverEpoch)))
if diff > 30 { if diff > 30 {
return nil, ErrBadTimestamp return nil, ErrBadTimestamp
} }
@@ -630,7 +629,6 @@ func InitServerStream(conn net.Conn, method *CipherMethod, psk, saltSlice []byte
func TransportTCP(ctx context.Context, sessionPolicy policy.Session, reader buf.Reader, writer buf.Writer, link *transport.Link) error { func TransportTCP(ctx context.Context, sessionPolicy policy.Session, reader buf.Reader, writer buf.Writer, link *transport.Link) error {
ctx, cancel := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle) timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
defer timer.SetTimeout(0)
ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer) ctx = policy.ContextWithBufferPolicy(ctx, sessionPolicy.Buffer)
requestDone := func() error { requestDone := func() error {
@@ -646,12 +644,6 @@ func TransportTCP(ctx context.Context, sessionPolicy policy.Session, reader buf.
return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer)) return buf.Copy(link.Reader, writer, buf.UpdateActivity(timer))
} }
requestDoneAndCloseWriter := task.OnSuccess(requestDone, task.Close(link.Writer)) responseDoneAndCloseWriter := task.OnSuccess(responseDone, task.Close(link.Writer))
if err := task.Run(ctx, requestDoneAndCloseWriter, responseDone); err != nil { return task.Run(ctx, requestDone, responseDoneAndCloseWriter)
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
return errors.New("connection ends").Base(err)
}
return nil
} }
+1 -1
View File
@@ -153,7 +153,7 @@ func jitter(backoff time.Duration) time.Duration {
if half <= 0 { if half <= 0 {
return backoff return backoff
} }
return half + time.Duration(dice.Roll(int(half))) return half + time.Duration(dice.RollInt63n(int64(half)))
} }
func rateLimited(payload []byte) bool { func rateLimited(payload []byte) bool {