Compare commits

...

3 Commits

Author SHA1 Message Date
Fangliding
73baf47358 prevent close of closed 2025-08-25 13:55:17 +08:00
Fangliding
ecc2f73108 refactor dns outbound conn 2025-08-25 13:28:25 +08:00
Fangliding
f45ca197a2 Fix dead lock 2025-08-25 13:16:51 +08:00

View File

@@ -5,6 +5,7 @@ import (
go_errors "errors"
"io"
"sync"
"sync/atomic"
"time"
"github.com/xtls/xray-core/common"
@@ -369,6 +370,10 @@ type outboundConn struct {
access sync.Mutex
dialer func() (stat.Connection, error)
closeOnce sync.Once
dialOnce sync.Once
closed atomic.Bool
conn net.Conn
connReady chan struct{}
}
@@ -378,24 +383,28 @@ func (c *outboundConn) dial() error {
if err != nil {
return err
}
if c.closed.Load() {
return errors.New("connection closed during dial")
}
c.conn = conn
c.connReady <- struct{}{}
return nil
}
func (c *outboundConn) Write(b []byte) (int, error) {
c.dialOnce.Do(func() {
c.dial()
})
c.access.Lock()
if c.conn == nil {
if err := c.dial(); err != nil {
c.access.Unlock()
errors.LogWarningInner(context.Background(), err, "failed to dial outbound connection")
return len(b), nil
}
}
conn := c.conn
c.access.Unlock()
if conn == nil {
_, open := <-c.connReady
if !open {
return 0, io.EOF
}
conn = c.conn
}
return c.conn.Write(b)
}
@@ -417,11 +426,14 @@ func (c *outboundConn) Read(b []byte) (int, error) {
}
func (c *outboundConn) Close() error {
c.access.Lock()
close(c.connReady)
if c.conn != nil {
c.conn.Close()
}
c.access.Unlock()
c.closeOnce.Do(func() {
c.access.Lock()
c.closed.Store(true)
close(c.connReady)
if c.conn != nil {
c.conn.Close()
}
c.access.Unlock()
})
return nil
}