github.com/AntonOrnatskyi/goproxy@v0.0.0-20190205095733-4526a9fa18b4/core/lib/transport/encrypt/conn.go (about) 1 package encrypt 2 3 import ( 4 "crypto/cipher" 5 "fmt" 6 "io" 7 "net" 8 9 lbuf "github.com/AntonOrnatskyi/goproxy/core/lib/buf" 10 ) 11 12 var ( 13 lBuf = lbuf.NewLeakyBuf(2048, 2048) 14 ) 15 16 type Conn struct { 17 net.Conn 18 *Cipher 19 w io.Writer 20 r io.Reader 21 } 22 23 func NewConn(c net.Conn, method, password string) (conn net.Conn, err error) { 24 cipher0, err := NewCipher(method, password) 25 if err != nil { 26 return 27 } 28 conn = &Conn{ 29 Conn: c, 30 Cipher: cipher0, 31 r: &cipher.StreamReader{S: cipher0.ReadStream, R: c}, 32 w: &cipher.StreamWriter{S: cipher0.WriteStream, W: c}, 33 } 34 return 35 } 36 func (s *Conn) Read(b []byte) (n int, err error) { 37 if s.r == nil { 38 return 0, fmt.Errorf("use of closed network connection") 39 } 40 return s.r.Read(b) 41 } 42 func (s *Conn) Write(b []byte) (n int, err error) { 43 if s.w == nil { 44 return 0, fmt.Errorf("use of closed network connection") 45 } 46 return s.w.Write(b) 47 } 48 func (s *Conn) Close() (err error) { 49 if s.Cipher != nil { 50 err = s.Conn.Close() 51 s.Cipher = nil 52 s.r = nil 53 s.w = nil 54 } 55 return 56 }