github.com/kelleygo/clashcore@v1.0.2/transport/hysteria/conns/faketcp/obfs.go (about) 1 package faketcp 2 3 import ( 4 "github.com/kelleygo/clashcore/transport/hysteria/obfs" 5 "net" 6 "sync" 7 "syscall" 8 "time" 9 ) 10 11 const udpBufferSize = 65535 12 13 type ObfsFakeTCPConn struct { 14 orig *TCPConn 15 obfs obfs.Obfuscator 16 readBuf []byte 17 readMutex sync.Mutex 18 writeBuf []byte 19 writeMutex sync.Mutex 20 } 21 22 func NewObfsFakeTCPConn(orig *TCPConn, obfs obfs.Obfuscator) *ObfsFakeTCPConn { 23 return &ObfsFakeTCPConn{ 24 orig: orig, 25 obfs: obfs, 26 readBuf: make([]byte, udpBufferSize), 27 writeBuf: make([]byte, udpBufferSize), 28 } 29 } 30 31 func (c *ObfsFakeTCPConn) ReadFrom(p []byte) (int, net.Addr, error) { 32 for { 33 c.readMutex.Lock() 34 n, addr, err := c.orig.ReadFrom(c.readBuf) 35 if n <= 0 { 36 c.readMutex.Unlock() 37 return 0, addr, err 38 } 39 newN := c.obfs.Deobfuscate(c.readBuf[:n], p) 40 c.readMutex.Unlock() 41 if newN > 0 { 42 // Valid packet 43 return newN, addr, err 44 } else if err != nil { 45 // Not valid and orig.ReadFrom had some error 46 return 0, addr, err 47 } 48 } 49 } 50 51 func (c *ObfsFakeTCPConn) WriteTo(p []byte, addr net.Addr) (n int, err error) { 52 c.writeMutex.Lock() 53 bn := c.obfs.Obfuscate(p, c.writeBuf) 54 _, err = c.orig.WriteTo(c.writeBuf[:bn], addr) 55 c.writeMutex.Unlock() 56 if err != nil { 57 return 0, err 58 } else { 59 return len(p), nil 60 } 61 } 62 63 func (c *ObfsFakeTCPConn) Close() error { 64 return c.orig.Close() 65 } 66 67 func (c *ObfsFakeTCPConn) LocalAddr() net.Addr { 68 return c.orig.LocalAddr() 69 } 70 71 func (c *ObfsFakeTCPConn) SetDeadline(t time.Time) error { 72 return c.orig.SetDeadline(t) 73 } 74 75 func (c *ObfsFakeTCPConn) SetReadDeadline(t time.Time) error { 76 return c.orig.SetReadDeadline(t) 77 } 78 79 func (c *ObfsFakeTCPConn) SetWriteDeadline(t time.Time) error { 80 return c.orig.SetWriteDeadline(t) 81 } 82 83 func (c *ObfsFakeTCPConn) SetReadBuffer(bytes int) error { 84 return c.orig.SetReadBuffer(bytes) 85 } 86 87 func (c *ObfsFakeTCPConn) SetWriteBuffer(bytes int) error { 88 return c.orig.SetWriteBuffer(bytes) 89 } 90 91 func (c *ObfsFakeTCPConn) SyscallConn() (syscall.RawConn, error) { 92 return c.orig.SyscallConn() 93 }