chore: optimize code
Build / Build (push) Has been cancelled

This commit is contained in:
nadoo committed 2026-11-16 21:08:27 +08:00
1 parent 9eadb8d9f4
commit a7d0421c93
15 files changed
+422 -171

No files matched your search

+27 -12
View File
@@ -4,6 +4,7 @@ import (
"crypto/tls"
"fmt"
"net"
"time"
"github.com/nadoo/glider/pkg/log"
"github.com/nadoo/glider/pkg/socks"
@@ -60,7 +61,7 @@ func (s *AnyTLS) Dial(network, addr string) (net.Conn, error) {
_ = ss.Close()
return nil, err
}
return &clientConn{Conn: st, session: ss}, nil
return &clientConn{stream: st}, nil
}
func (s *AnyTLS) DialUDP(network, addr string) (net.PacketConn, error) {
@@ -99,7 +100,7 @@ func (s *AnyTLS) DialUDP(network, addr string) (net.PacketConn, error) {
_ = ss.Close()
return nil, err
}
return &clientPacketConn{PacketConn: newUOTPacketConn(st, target), session: ss}, nil
return &clientPacketConn{PacketConn: newUOTPacketConn(st, target), stream: st}, nil
}
func (s *AnyTLS) newClientSession() (*session, error) {
@@ -123,7 +124,7 @@ func (s *AnyTLS) newClientSession() (*session, error) {
}
ss := newSession(c)
if err := ss.writeFrame(frame{command: cmdSettings, data: clientSettings(s.padding)}); err != nil {
_ = c.Close()
_ = ss.Close()
return nil, err
}
ss.start()
@@ -131,23 +132,37 @@ func (s *AnyTLS) newClientSession() (*session, error) {
}
type clientConn struct {
net.Conn
session *session
*stream
}
func (c *clientConn) Close() error {
err := c.Conn.Close()
_ = c.session.Close()
return err
return closeClientSession(c.stream)
}
type clientPacketConn struct {
net.PacketConn
session *session
stream *stream
}
func (c *clientPacketConn) Close() error {
err := c.PacketConn.Close()
_ = c.session.Close()
return err
return closeClientSession(c.stream)
}
const clientFINTimeout = time.Second
// The client owns the whole session. Give FIN a chance to reach the transport
// before tearing it down, while keeping standalone stream.Close nonblocking.
func closeClientSession(st *stream) error {
_ = st.Close()
defer st.s.Close()
if st.fin != nil {
timer := time.NewTimer(clientFINTimeout)
defer timer.Stop()
select {
case <-st.fin.result:
case <-st.s.done:
case <-timer.C:
}
}
return nil
}
+7 -4
View File
@@ -83,15 +83,18 @@ func readFrame(r io.Reader) (frame, error) {
return frame{command: head[0], streamID: binary.BigEndian.Uint32(head[1:5]), data: data}, nil
}
func writeFrame(w io.Writer, f frame) error {
func writeFrame(w io.Writer, f frame) (int, error) {
if len(f.data) > maxFrameData {
return errors.New("frame data too large")
return 0, errors.New("frame data too large")
}
buf := make([]byte, 7+len(f.data))
buf[0] = f.command
binary.BigEndian.PutUint32(buf[1:5], f.streamID)
binary.BigEndian.PutUint16(buf[5:7], uint16(len(f.data)))
copy(buf[7:], f.data)
_, err := w.Write(buf)
return err
n, err := w.Write(buf)
if n < len(buf) && err == nil {
err = io.ErrShortWrite
}
return max(0, n-7), err
}
+162 -14
View File
@@ -1,10 +1,13 @@
package anytls
import (
"bytes"
"container/list"
"errors"
"fmt"
"io"
"net"
"os"
"sync"
"sync/atomic"
"time"
@@ -13,16 +16,19 @@ import (
type session struct {
conn net.Conn
writeMu sync.Mutex
mu sync.Mutex
streams map[uint32]*stream
synack map[uint32]chan synackResult
nextID atomic.Uint32
writeMu sync.Mutex
writes list.List
writeWake chan struct{}
mu sync.Mutex
streams map[uint32]*stream
synack map[uint32]chan synackResult
nextID atomic.Uint32
incoming chan *stream
done chan struct{}
closeOnce sync.Once
err atomic.Value
errOnce sync.Once
settingsSeen bool
}
@@ -31,15 +37,33 @@ type synackResult struct {
data []byte
}
type frameWrite struct {
frame frame
stream *stream
deadline <-chan struct{}
result chan frameWriteResult
// Guarded by session.writeMu.
elem *list.Element
started bool
}
type frameWriteResult struct {
n int // payload bytes, excluding the frame header
err error
}
func newSession(conn net.Conn) *session {
s := &session{
conn: conn,
streams: map[uint32]*stream{},
synack: map[uint32]chan synackResult{},
incoming: make(chan *stream, 32),
done: make(chan struct{}),
conn: conn,
streams: map[uint32]*stream{},
synack: map[uint32]chan synackResult{},
incoming: make(chan *stream, 32),
done: make(chan struct{}),
writeWake: make(chan struct{}, 1),
}
s.nextID.Store(1)
go s.writeLoop()
return s
}
@@ -103,9 +127,126 @@ func (s *session) waitSYNACK(id uint32, timeout time.Duration) error {
}
func (s *session) writeFrame(f frame) error {
req, err := s.queueFrame(f, nil, nil)
if err != nil {
return err
}
select {
case result := <-req.result:
return result.err
case <-s.done:
return s.Err()
}
}
func (s *session) writeStreamFrame(st *stream, f frame) (int, error) {
if channelClosed(st.done) {
return 0, errStreamClosed
}
deadline := st.writeDeadline.wait()
if channelClosed(deadline) {
return 0, os.ErrDeadlineExceeded
}
req, err := s.queueFrame(f, st, deadline)
if err != nil {
return 0, err
}
select {
case result := <-req.result:
return result.n, result.err
case <-st.done:
err = errStreamClosed
case <-s.done:
err = s.Err()
case <-deadline:
err = os.ErrDeadlineExceeded
}
started := s.cancelWrite(req)
// Prefer the transport result when both completion and cancellation are ready.
select {
case result := <-req.result:
return result.n, result.err
default:
}
if started {
// The writer owns the whole frame once it starts. Its payload can
// still reach the peer after this call returns, so count it in n.
return len(f.data), err
}
return 0, err
}
func (s *session) queueFrame(f frame, st *stream, deadline <-chan struct{}) (*frameWrite, error) {
// A stream may time out while the transport is writing. Own the payload so
// the caller can reuse its buffer without racing with the session writer.
f.data = bytes.Clone(f.data)
req := &frameWrite{frame: f, stream: st, deadline: deadline, result: make(chan frameWriteResult, 1)}
s.writeMu.Lock()
defer s.writeMu.Unlock()
return writeFrame(s.conn, f)
if channelClosed(s.done) {
return nil, s.Err()
}
req.elem = s.writes.PushBack(req)
select {
case s.writeWake <- struct{}{}:
default:
}
return req, nil
}
// cancelWrite removes a pending request and reports whether it had already started.
func (s *session) cancelWrite(req *frameWrite) bool {
s.writeMu.Lock()
defer s.writeMu.Unlock()
if req.elem != nil {
s.writes.Remove(req.elem)
req.elem = nil
}
return req.started
}
func (s *session) writeLoop() {
for {
select {
case <-s.done:
return
case <-s.writeWake:
}
for {
s.writeMu.Lock()
elem := s.writes.Front()
if elem == nil || channelClosed(s.done) {
s.writeMu.Unlock()
break
}
req := s.writes.Remove(elem).(*frameWrite)
req.elem = nil
if st := req.stream; st != nil {
if channelClosed(st.done) {
s.writeMu.Unlock()
req.result <- frameWriteResult{err: errStreamClosed}
continue
}
if channelClosed(req.deadline) {
s.writeMu.Unlock()
req.result <- frameWriteResult{err: os.ErrDeadlineExceeded}
continue
}
}
req.started = true
s.writeMu.Unlock()
// An in-flight frame must finish intact even if its stream times out.
// Only closing the session may interrupt the shared transport write.
n, err := writeFrame(s.conn, req.frame)
req.result <- frameWriteResult{n: n, err: err}
close(req.result)
if err != nil {
s.setErr(err)
s.Close()
return
}
}
}
}
func (s *session) readLoop() {
@@ -202,8 +343,8 @@ func (s *session) removeStream(id uint32) {
}
func (s *session) setErr(err error) {
if err != nil && s.err.Load() == nil {
s.err.Store(err)
if err != nil {
s.errOnce.Do(func() { s.err.Store(err) })
}
}
@@ -218,8 +359,16 @@ func (s *session) Close() error {
s.closeOnce.Do(func() {
close(s.done)
_ = s.conn.Close()
s.writeMu.Lock()
for elem := s.writes.Front(); elem != nil; elem = elem.Next() {
elem.Value.(*frameWrite).elem = nil
}
s.writes.Init()
s.writeMu.Unlock()
s.mu.Lock()
for _, st := range s.streams {
st.readDeadline.stop()
st.writeDeadline.stop()
st.closeRead()
}
s.streams = map[uint32]*stream{}
@@ -227,7 +376,6 @@ func (s *session) Close() error {
delete(s.synack, id)
close(ch)
}
close(s.incoming)
s.mu.Unlock()
})
return nil
+99 -36
View File
@@ -4,6 +4,7 @@ import (
"errors"
"io"
"net"
"os"
"sync"
"time"
)
@@ -14,80 +15,142 @@ type stream struct {
id uint32
s *session
in chan []byte
readBuf []byte
closeIn sync.Once
closeOut sync.Once
in chan []byte
readBuf []byte
readDone chan struct{}
done chan struct{}
closeIn sync.Once
closeOnce sync.Once
fin *frameWrite // published by closeOnce
readMu sync.Mutex
writeMu sync.Mutex
mu sync.Mutex
closed bool
readDeadline streamDeadline
writeDeadline streamDeadline
}
func newStream(id uint32, s *session) *stream {
return &stream{id: id, s: s, in: make(chan []byte, 32)}
return &stream{
id: id, s: s, in: make(chan []byte, 32),
readDone: make(chan struct{}), done: make(chan struct{}),
}
}
func (st *stream) Read(p []byte) (int, error) {
for len(st.readBuf) == 0 {
b, ok := <-st.in
if !ok {
return 0, io.EOF
st.readMu.Lock()
defer st.readMu.Unlock()
for {
if channelClosed(st.done) {
return 0, net.ErrClosed
}
deadline := st.readDeadline.wait()
if channelClosed(deadline) {
return 0, os.ErrDeadlineExceeded
}
if len(p) == 0 {
return 0, nil
}
if len(st.readBuf) > 0 {
n := copy(p, st.readBuf)
st.readBuf = st.readBuf[n:]
return n, nil
}
// A peer FIN ends input after previously received data has been read.
select {
case st.readBuf = <-st.in:
continue
default:
}
select {
case st.readBuf = <-st.in:
case <-st.readDone:
select {
case st.readBuf = <-st.in:
default:
return 0, io.EOF
}
case <-st.done:
return 0, net.ErrClosed
case <-st.s.done:
return 0, st.s.Err()
case <-deadline:
return 0, os.ErrDeadlineExceeded
}
st.readBuf = b
}
n := copy(p, st.readBuf)
st.readBuf = st.readBuf[n:]
return n, nil
}
func (st *stream) Write(p []byte) (int, error) {
st.mu.Lock()
closed := st.closed
st.mu.Unlock()
if closed {
st.writeMu.Lock()
defer st.writeMu.Unlock()
if channelClosed(st.done) {
return 0, errStreamClosed
}
if channelClosed(st.writeDeadline.wait()) {
return 0, os.ErrDeadlineExceeded
}
written := 0
for len(p) > 0 {
n := min(len(p), maxFrameData)
if err := st.s.writeFrame(frame{command: cmdPSH, streamID: st.id, data: p[:n]}); err != nil {
accepted, err := st.s.writeStreamFrame(st, frame{command: cmdPSH, streamID: st.id, data: p[:n]})
written += accepted
if err != nil {
return written, err
}
written += n
p = p[n:]
}
return written, nil
}
func (st *stream) Close() error {
st.mu.Lock()
already := st.closed
st.closed = true
st.mu.Unlock()
if !already {
st.closeOut.Do(func() {
_ = st.s.writeFrame(frame{command: cmdFIN, streamID: st.id})
})
st.closeOnce.Do(func() {
close(st.done)
st.readDeadline.stop()
st.writeDeadline.stop()
st.s.removeStream(st.id)
}
// FIN is queued behind any frame already being written. Closing a stream
// must not wait for a stalled transport or interrupt another stream.
st.fin, _ = st.s.queueFrame(frame{command: cmdFIN, streamID: st.id}, nil, nil)
})
return nil
}
func (st *stream) closeRead() {
st.closeIn.Do(func() { close(st.in) })
st.closeIn.Do(func() { close(st.readDone) })
}
func (st *stream) push(data []byte) {
if channelClosed(st.done) || channelClosed(st.readDone) || channelClosed(st.s.done) {
return
}
cp := make([]byte, len(data))
copy(cp, data)
select {
case st.in <- cp:
case <-st.done:
case <-st.readDone:
case <-st.s.done:
}
}
func (st *stream) LocalAddr() net.Addr { return st.s.conn.LocalAddr() }
func (st *stream) RemoteAddr() net.Addr { return st.s.conn.RemoteAddr() }
func (st *stream) SetDeadline(t time.Time) error { return st.s.conn.SetDeadline(t) }
func (st *stream) SetReadDeadline(t time.Time) error { return st.s.conn.SetReadDeadline(t) }
func (st *stream) SetWriteDeadline(t time.Time) error { return st.s.conn.SetWriteDeadline(t) }
func (st *stream) LocalAddr() net.Addr { return st.s.conn.LocalAddr() }
func (st *stream) RemoteAddr() net.Addr { return st.s.conn.RemoteAddr() }
func (st *stream) SetDeadline(t time.Time) error {
if err := st.SetReadDeadline(t); err != nil {
return err
}
return st.SetWriteDeadline(t)
}
func (st *stream) SetReadDeadline(t time.Time) error {
if channelClosed(st.done) || channelClosed(st.s.done) {
return net.ErrClosed
}
st.readDeadline.set(t)
return nil
}
func (st *stream) SetWriteDeadline(t time.Time) error {
if channelClosed(st.done) || channelClosed(st.s.done) {
return net.ErrClosed
}
st.writeDeadline.set(t)
return nil
}
+38 -24
View File
@@ -25,6 +25,20 @@ const (
chunkSize = 1 << 13 // 8192
)
// putBE16 writes v to buf as a big-endian uint16.
func putBE16(buf *bytes.Buffer, v uint16) {
var b [2]byte
binary.BigEndian.PutUint16(b[:], v)
buf.Write(b[:])
}
// putBE32 writes v to buf as a big-endian uint32.
func putBE32(buf *bytes.Buffer, v uint32) {
var b [4]byte
binary.BigEndian.PutUint32(b[:], v)
buf.Write(b[:])
}
// TLSObfs struct
type TLSObfs struct {
obfsHost string
@@ -67,7 +81,7 @@ func (c *TLSObfsConn) Write(b []byte) (int, error) {
end := min(i+chunkSize, n)
buf.Write([]byte{0x17, 0x03, 0x03})
binary.Write(buf, binary.BigEndian, uint16(len(b[i:end])))
putBE16(buf, uint16(len(b[i:end])))
buf.Write(b[i:end])
_, err := c.Conn.Write(buf.Bytes())
@@ -143,7 +157,7 @@ func (c *TLSObfsConn) handshake(b []byte) (int, error) {
buf.Write([]byte{0x03, 0x01})
// length
binary.Write(buf, binary.BigEndian, uint16(handshakeLen))
putBE16(buf, uint16(handshakeLen))
// Handshake Begin
// Handshake Type: Client Hello (1)
@@ -157,7 +171,7 @@ func (c *TLSObfsConn) handshake(b []byte) (int, error) {
// Extension Begin
// ext content length
binary.Write(buf, binary.BigEndian, uint16(extLen))
putBE16(buf, uint16(extLen))
// ext content
buf.Write(bufExt.Bytes())
@@ -182,7 +196,7 @@ func clientHello(buf *bytes.Buffer) {
// clients do not send current time, and server do not check it,
// golang tls client and chrome browser send random bytes instead.
//
binary.Write(buf, binary.BigEndian, uint32(time.Now().Unix()))
putBE32(buf, uint32(time.Now().Unix()))
random := make([]byte, 28)
// The above 2 lines of codes was added to make it compatible with some server implementation,
// if we don't need the compatibility, just use the following code instead.
@@ -200,7 +214,7 @@ func clientHello(buf *bytes.Buffer) {
// https://github.com/shadowsocks/simple-obfs/blob/7659eeccf473aa41eb294e92c32f8f60a8747325/src/obfs_tls.c#L57
// Cipher Suites Length: 56
binary.Write(buf, binary.BigEndian, uint16(56))
putBE16(buf, uint16(56))
// Cipher Suites (28 suites)
buf.Write([]byte{
0xc0, 0x2c, 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f,
@@ -219,44 +233,44 @@ func extension(b []byte, server string, buf *bytes.Buffer) {
// Extension: SessionTicket TLS
buf.Write([]byte{0x00, 0x23}) // type
// NOTE: send some data in sessionticket, the server will treat it as data too
binary.Write(buf, binary.BigEndian, uint16(len(b))) // length
putBE16(buf, uint16(len(b))) // length
buf.Write(b)
// Extension: server_name
buf.Write([]byte{0x00, 0x00}) // type
binary.Write(buf, binary.BigEndian, uint16(len(server)+5)) // length
binary.Write(buf, binary.BigEndian, uint16(len(server)+3)) // Server Name list length
buf.WriteByte(0x00) // Server Name Type: host_name (0)
binary.Write(buf, binary.BigEndian, uint16(len(server))) // Server Name length
buf.Write([]byte{0x00, 0x00}) // type
putBE16(buf, uint16(len(server)+5)) // length
putBE16(buf, uint16(len(server)+3)) // Server Name list length
buf.WriteByte(0x00) // Server Name Type: host_name (0)
putBE16(buf, uint16(len(server))) // Server Name length
buf.WriteString(server)
// https://github.com/shadowsocks/simple-obfs/blob/7659eeccf473aa41eb294e92c32f8f60a8747325/src/obfs_tls.c#L88
// Extension: ec_point_formats (len=4)
buf.Write([]byte{0x00, 0x0b}) // type
binary.Write(buf, binary.BigEndian, uint16(4)) // length
buf.WriteByte(0x03) // format length
buf.Write([]byte{0x00, 0x0b}) // type
putBE16(buf, uint16(4)) // length
buf.WriteByte(0x03) // format length
buf.Write([]byte{0x01, 0x00, 0x02})
// Extension: supported_groups (len=10)
buf.Write([]byte{0x00, 0x0a}) // type
binary.Write(buf, binary.BigEndian, uint16(10)) // length
binary.Write(buf, binary.BigEndian, uint16(8)) // Supported Groups List Length: 8
buf.Write([]byte{0x00, 0x0a}) // type
putBE16(buf, uint16(10)) // length
putBE16(buf, uint16(8)) // Supported Groups List Length: 8
buf.Write([]byte{0x00, 0x1d, 0x00, 0x17, 0x00, 0x19, 0x00, 0x18})
// Extension: signature_algorithms (len=32)
buf.Write([]byte{0x00, 0x0d}) // type
binary.Write(buf, binary.BigEndian, uint16(32)) // length
binary.Write(buf, binary.BigEndian, uint16(30)) // Signature Hash Algorithms Length: 30
buf.Write([]byte{0x00, 0x0d}) // type
putBE16(buf, uint16(32)) // length
putBE16(buf, uint16(30)) // Signature Hash Algorithms Length: 30
buf.Write([]byte{
0x06, 0x01, 0x06, 0x02, 0x06, 0x03, 0x05, 0x01, 0x05, 0x02, 0x05, 0x03, 0x04, 0x01, 0x04, 0x02,
0x04, 0x03, 0x03, 0x01, 0x03, 0x02, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x03,
})
// Extension: encrypt_then_mac (len=0)
buf.Write([]byte{0x00, 0x16}) // type
binary.Write(buf, binary.BigEndian, uint16(0)) // length
buf.Write([]byte{0x00, 0x16}) // type
putBE16(buf, uint16(0)) // length
// Extension: extended_master_secret (len=0)
buf.Write([]byte{0x00, 0x17}) // type
binary.Write(buf, binary.BigEndian, uint16(0)) // length
buf.Write([]byte{0x00, 0x17}) // type
putBE16(buf, uint16(0)) // length
}
+3 -1
View File
@@ -79,7 +79,9 @@ func (pc *PktConn) WriteTo(b []byte, addr net.Addr) (int, error) {
defer pool.PutBytesBuffer(buf)
tgtLen, _ := buf.Write(target)
binary.Write(buf, binary.BigEndian, uint16(len(b)))
var hdr [2]byte
binary.BigEndian.PutUint16(hdr[:], uint16(len(b)))
buf.Write(hdr[:])
buf.WriteString("\r\n")
buf.Write(b)
+3 -4
View File
@@ -81,10 +81,9 @@ func NewClientConn(c net.Conn, uuid [16]byte, network, target string) (*ClientCo
buf.WriteByte(byte(cmd)) // cmd
// target
err = binary.Write(buf, binary.BigEndian, uint16(port)) // port
if err != nil {
return nil, err
}
var portBuf [2]byte
binary.BigEndian.PutUint16(portBuf[:], uint16(port))
buf.Write(portBuf[:])
buf.WriteByte(byte(atyp)) // atyp
buf.Write(addr) //addr
+3 -1
View File
@@ -46,7 +46,9 @@ func (pc *PktConn) WriteTo(b []byte, addr net.Addr) (int, error) {
buf := pool.GetBytesBuffer()
defer pool.PutBytesBuffer(buf)
binary.Write(buf, binary.BigEndian, uint16(len(b)))
var hdr [2]byte
binary.BigEndian.PutUint16(hdr[:], uint16(len(b)))
buf.Write(hdr[:])
buf.Write(b)
n, err := pc.Write(buf.Bytes())
+5 -9
View File
@@ -119,17 +119,13 @@ func (h *hMacCreator) Create() hash.Hash {
}
func createAuthID(cmdKey []byte, time int64) [16]byte {
buf := &bytes.Buffer{}
binary.Write(buf, binary.BigEndian, time)
random := make([]byte, 4)
rand.Read(random)
buf.Write(random)
zero := crc32.ChecksumIEEE(buf.Bytes())
binary.Write(buf, binary.BigEndian, zero)
var buf [16]byte
binary.BigEndian.PutUint64(buf[0:8], uint64(time))
rand.Read(buf[8:12])
binary.BigEndian.PutUint32(buf[12:16], crc32.ChecksumIEEE(buf[:12]))
aesBlock, _ := aes.NewCipher(kdf(cmdKey[:], kdfSaltConstAuthIDEncryptionKey)[:16])
var result [16]byte
aesBlock.Encrypt(result[:], buf.Bytes())
aesBlock.Encrypt(result[:], buf[:])
return result
}
+5 -3
View File
@@ -201,9 +201,11 @@ func (c *Conn) Request(cmd CmdType) error {
buf.WriteByte(byte(cmd)) // cmd
// target
binary.Write(buf, binary.BigEndian, uint16(c.port)) // port
buf.WriteByte(byte(c.atyp)) // atyp
buf.Write(c.addr) // addr
var port [2]byte
binary.BigEndian.PutUint16(port[:], uint16(c.port))
buf.Write(port[:])
buf.WriteByte(byte(c.atyp)) // atyp
buf.Write(c.addr) // addr
// padding
if paddingLen > 0 {