sing-box/experimental/trackerconn/conn.go

110 lines
2.3 KiB
Go
Raw Normal View History

2022-09-26 07:31:02 +00:00
package trackerconn
import (
"net"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
N "github.com/sagernet/sing/common/network"
"go.uber.org/atomic"
)
2022-10-26 11:20:34 +00:00
func New(conn net.Conn, readCounter []*atomic.Int64, writeCounter []*atomic.Int64, direct bool) *Conn {
return &Conn{bufio.NewExtendedConn(conn), readCounter, writeCounter}
2022-09-26 07:31:02 +00:00
}
2022-10-26 11:20:34 +00:00
func NewHook(conn net.Conn, readCounter func(n int64), writeCounter func(n int64), direct bool) *HookConn {
return &HookConn{bufio.NewExtendedConn(conn), readCounter, writeCounter}
2022-10-01 01:56:09 +00:00
}
2022-09-26 07:31:02 +00:00
type Conn struct {
N.ExtendedConn
2022-10-26 11:20:34 +00:00
readCounter []*atomic.Int64
writeCounter []*atomic.Int64
2022-09-26 07:31:02 +00:00
}
func (c *Conn) Read(p []byte) (n int, err error) {
n, err = c.ExtendedConn.Read(p)
2022-10-26 11:20:34 +00:00
for _, counter := range c.readCounter {
counter.Add(int64(n))
}
2022-09-26 07:31:02 +00:00
return n, err
}
func (c *Conn) ReadBuffer(buffer *buf.Buffer) error {
err := c.ExtendedConn.ReadBuffer(buffer)
if err != nil {
return err
}
2022-10-26 11:20:34 +00:00
for _, counter := range c.readCounter {
counter.Add(int64(buffer.Len()))
}
2022-09-26 07:31:02 +00:00
return nil
}
func (c *Conn) Write(p []byte) (n int, err error) {
n, err = c.ExtendedConn.Write(p)
2022-10-26 11:20:34 +00:00
for _, counter := range c.writeCounter {
counter.Add(int64(n))
}
2022-09-26 07:31:02 +00:00
return n, err
}
func (c *Conn) WriteBuffer(buffer *buf.Buffer) error {
dataLen := int64(buffer.Len())
err := c.ExtendedConn.WriteBuffer(buffer)
if err != nil {
return err
}
2022-10-26 11:20:34 +00:00
for _, counter := range c.writeCounter {
counter.Add(dataLen)
}
2022-09-26 07:31:02 +00:00
return nil
}
2022-09-26 11:37:06 +00:00
func (c *Conn) Upstream() any {
return c.ExtendedConn
}
2022-10-01 01:56:09 +00:00
type HookConn struct {
N.ExtendedConn
readCounter func(n int64)
writeCounter func(n int64)
}
func (c *HookConn) Read(p []byte) (n int, err error) {
n, err = c.ExtendedConn.Read(p)
c.readCounter(int64(n))
return n, err
}
func (c *HookConn) ReadBuffer(buffer *buf.Buffer) error {
err := c.ExtendedConn.ReadBuffer(buffer)
if err != nil {
return err
}
c.readCounter(int64(buffer.Len()))
return nil
}
func (c *HookConn) Write(p []byte) (n int, err error) {
n, err = c.ExtendedConn.Write(p)
c.writeCounter(int64(n))
return n, err
}
func (c *HookConn) WriteBuffer(buffer *buf.Buffer) error {
dataLen := int64(buffer.Len())
err := c.ExtendedConn.WriteBuffer(buffer)
if err != nil {
return err
}
c.writeCounter(dataLen)
return nil
}
func (c *HookConn) Upstream() any {
return c.ExtendedConn
}