2020-07-22 23:02:15 +08:00
|
|
|
package protocol
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"net"
|
|
|
|
|
2023-11-03 21:01:45 +08:00
|
|
|
"github.com/metacubex/mihomo/common/pool"
|
2020-07-22 23:02:15 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type Conn struct {
|
|
|
|
net.Conn
|
|
|
|
Protocol
|
2021-02-15 14:32:03 +08:00
|
|
|
decoded bytes.Buffer
|
2020-07-22 23:02:15 +08:00
|
|
|
underDecoded bytes.Buffer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) Read(b []byte) (int, error) {
|
2021-02-15 14:32:03 +08:00
|
|
|
if c.decoded.Len() > 0 {
|
|
|
|
return c.decoded.Read(b)
|
2020-07-22 23:02:15 +08:00
|
|
|
}
|
2021-02-15 14:32:03 +08:00
|
|
|
|
2020-07-22 23:02:15 +08:00
|
|
|
buf := pool.Get(pool.RelayBufferSize)
|
|
|
|
defer pool.Put(buf)
|
|
|
|
n, err := c.Conn.Read(buf)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
c.underDecoded.Write(buf[:n])
|
2021-02-15 14:32:03 +08:00
|
|
|
err = c.Decode(&c.decoded, &c.underDecoded)
|
2020-07-22 23:02:15 +08:00
|
|
|
if err != nil {
|
2021-02-15 14:32:03 +08:00
|
|
|
return 0, err
|
2020-07-22 23:02:15 +08:00
|
|
|
}
|
2021-02-15 14:32:03 +08:00
|
|
|
n, _ = c.decoded.Read(b)
|
2020-07-22 23:02:15 +08:00
|
|
|
return n, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) Write(b []byte) (int, error) {
|
2021-02-15 14:32:03 +08:00
|
|
|
bLength := len(b)
|
2021-09-20 21:02:18 +08:00
|
|
|
buf := pool.GetBuffer()
|
|
|
|
defer pool.PutBuffer(buf)
|
2021-02-15 14:32:03 +08:00
|
|
|
err := c.Encode(buf, b)
|
2020-07-22 23:02:15 +08:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2021-02-15 14:32:03 +08:00
|
|
|
_, err = c.Conn.Write(buf.Bytes())
|
2020-07-22 23:02:15 +08:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2021-02-15 14:32:03 +08:00
|
|
|
return bLength, nil
|
2020-07-22 23:02:15 +08:00
|
|
|
}
|