sing-box/experimental/trackerconn/packet_conn.go

78 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-09-26 07:31:02 +00:00
package trackerconn
import (
"github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"go.uber.org/atomic"
)
2022-10-26 11:20:34 +00:00
func NewPacket(conn N.PacketConn, readCounter []*atomic.Int64, writeCounter []*atomic.Int64) *PacketConn {
2022-10-01 01:56:09 +00:00
return &PacketConn{conn, readCounter, writeCounter}
}
func NewHookPacket(conn N.PacketConn, readCounter func(n int64), writeCounter func(n int64)) *HookPacketConn {
return &HookPacketConn{conn, readCounter, writeCounter}
}
2022-09-26 07:31:02 +00:00
type PacketConn struct {
N.PacketConn
2022-10-26 11:20:34 +00:00
readCounter []*atomic.Int64
writeCounter []*atomic.Int64
2022-09-26 07:31:02 +00:00
}
func (c *PacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
destination, err = c.PacketConn.ReadPacket(buffer)
if err == nil {
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
}
func (c *PacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
dataLen := int64(buffer.Len())
err := c.PacketConn.WritePacket(buffer, destination)
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 *PacketConn) Upstream() any {
return c.PacketConn
}
2022-10-01 01:56:09 +00:00
type HookPacketConn struct {
N.PacketConn
readCounter func(n int64)
writeCounter func(n int64)
}
func (c *HookPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
destination, err = c.PacketConn.ReadPacket(buffer)
if err == nil {
c.readCounter(int64(buffer.Len()))
}
return
}
func (c *HookPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
dataLen := int64(buffer.Len())
err := c.PacketConn.WritePacket(buffer, destination)
if err != nil {
return err
}
c.writeCounter(dataLen)
return nil
}
func (c *HookPacketConn) Upstream() any {
return c.PacketConn
}